diff --git a/client/app.js b/client/app.js index 65e09563c..e6a010db5 100644 --- a/client/app.js +++ b/client/app.js @@ -1,80 +1,79 @@ /* eslint-disable angular/window-service */ // The webpack entrypoint -function requireAll(context) { - context.keys().forEach(context); +function requireAll (context) { + context.keys().forEach(context) } // Globals that are expected in application code and some libraries -window.$ = window.jQuery = require('jquery'); -window._ = require('lodash'); -window.moment = require('moment'); -window.sprintf = require('sprintf-js').sprintf; -window.c3 = require('c3/c3.js'); -window.d3 = require('d3/d3.js'); +window.$ = window.jQuery = require('jquery') +window._ = require('lodash') +window.moment = require('moment') +window.sprintf = require('sprintf-js').sprintf +window.c3 = require('c3/c3.js') +window.d3 = require('d3/d3.js') // Vendor libraries, order matters -require('jquery-ui-bundle'); -require('moment-timezone'); -require('es6-shim'); -require('angular'); -require('angular-animate'); -require('angular-cookies'); -require('angular-resource'); -require('angular-messages'); -require('angular-sanitize'); -require('angular-base64'); -require('angular-bootstrap-switch'); -require('angular-file-saver'); -require('angular-ui-bootstrap'); -require('angular-ui-sortable'); -require('angular-gettext'); -require('bootstrap'); -require('angular-dragdrop'); -require('angular-drag-and-drop-lists/angular-drag-and-drop-lists'); -require('bootstrap-combobox'); -require('bootstrap-datepicker'); -require('bootstrap-select'); -require('bootstrap-switch'); -require('bootstrap-touchspin'); -require('angular-svg-base-fix'); -require('angular-ui-router'); -require('angular-ui-router/release/stateEvents'); -require('patternfly/dist/js/patternfly.js'); -require('@manageiq/ui-components/dist/js/ui-components.js'); -require('ngprogress/build/ngprogress.min.js'); -require('ngstorage'); -require('datatables.net/js/jquery.dataTables'); -require('datatables.net-select/js/dataTables.select'); -require('angular-datatables'); -require('angular-datatables/dist/plugins/select/angular-datatables.select'); -require('ui-select'); -require('patternfly-timeline/dist/timeline'); +require('jquery-ui-bundle') +require('moment-timezone') +require('es6-shim') +require('angular') +require('angular-animate') +require('angular-cookies') +require('angular-resource') +require('angular-messages') +require('angular-sanitize') +require('angular-base64') +require('angular-bootstrap-switch') +require('angular-file-saver') +require('angular-ui-bootstrap') +require('angular-ui-sortable') +require('angular-gettext') +require('bootstrap') +require('angular-dragdrop') +require('angular-drag-and-drop-lists/angular-drag-and-drop-lists') +require('bootstrap-combobox') +require('bootstrap-datepicker') +require('bootstrap-select') +require('bootstrap-switch') +require('bootstrap-touchspin') +require('angular-svg-base-fix') +require('angular-ui-router') +require('angular-ui-router/release/stateEvents') +require('patternfly/dist/js/patternfly.js') +require('@manageiq/ui-components/dist/js/ui-components.js') +require('ngprogress/build/ngprogress.min.js') +require('ngstorage') +require('datatables.net/js/jquery.dataTables') +require('datatables.net-select/js/dataTables.select') +require('angular-datatables') +require('angular-datatables/dist/plugins/select/angular-datatables.select') +require('ui-select') +require('patternfly-timeline/dist/timeline') -// Needs imports loader because it expects `this` to be `window` -require('imports-loader?this=>window!actioncable'); +// eslint-disable-next-line import/no-webpack-loader-syntax +require('imports-loader?this=>window!actioncable') // Must be required last because of its dependencies -require('angular-patternfly/dist/angular-patternfly'); +require('angular-patternfly/dist/angular-patternfly') // Application scripts, order matters -require('./app/app.module.js'); +require('./app/app.module.js') // Vendor styles, order matters -require('patternfly/dist/css/patternfly-additions.css'); -require('angular-patternfly/dist/styles/angular-patternfly.css'); -require('@manageiq/ui-components/dist/css/ui-components.css'); -require('ngprogress/ngProgress.css'); -require('datatables.net-dt/css/jquery.dataTables.css'); -require('ui-select/dist/select.css'); -require('patternfly-timeline/dist/timeline.css'); - +require('patternfly/dist/css/patternfly-additions.css') +require('angular-patternfly/dist/styles/angular-patternfly.css') +require('@manageiq/ui-components/dist/css/ui-components.css') +require('ngprogress/ngProgress.css') +require('datatables.net-dt/css/jquery.dataTables.css') +require('ui-select/dist/select.css') +require('patternfly-timeline/dist/timeline.css') // Application styles -require('./assets/sass/styles.sass'); +require('./assets/sass/styles.sass') // Angular templates -requireAll(require.context('./app', true, /\.html$/)); +requireAll(require.context('./app', true, /\.html$/)) // Skin overrides, require all js and css files within `client/skin` -requireAll(require.context('./', true, /skin\/.*\.(js|css)$/)); +requireAll(require.context('./', true, /skin\/.*\.(js|css)$/)) diff --git a/client/app/app.controller.js b/client/app/app.controller.js index f7e824488..135278e89 100644 --- a/client/app/app.controller.js +++ b/client/app/app.controller.js @@ -1,33 +1,33 @@ export class AppController { - constructor($scope, ngProgressFactory) { - 'ngInject'; + constructor ($scope, ngProgressFactory) { + 'ngInject' - this.progressbar = ngProgressFactory.createInstance(); - this.progressbar.setColor('#0088ce'); - this.progressbar.setHeight('3px'); + this.progressbar = ngProgressFactory.createInstance() + this.progressbar.setColor('#0088ce') + this.progressbar.setHeight('3px') - this.$scope = $scope; + this.$scope = $scope } - $onInit() { + $onInit () { this.$scope.$on('$stateChangeStart', (_event, toState) => { if (toState.resolve) { - this.progressbar.start(); + this.progressbar.start() } - }); + }) this.$scope.$on('$stateChangeSuccess', (_event, toState) => { if (toState.resolve) { - this.progressbar.complete(); + this.progressbar.complete() } - }); + }) } - keyDown(evt) { - this.$scope.$broadcast('bodyKeyDown', {origEvent: evt}); + keyDown (evt) { + this.$scope.$broadcast('bodyKeyDown', {origEvent: evt}) } - keyUp(evt) { - this.$scope.$broadcast('bodyKeyUp', {origEvent: evt}); + keyUp (evt) { + this.$scope.$broadcast('bodyKeyUp', {origEvent: evt}) } } diff --git a/client/app/app.module.js b/client/app/app.module.js index eeb46e3ff..99d07c32d 100644 --- a/client/app/app.module.js +++ b/client/app/app.module.js @@ -1,12 +1,12 @@ -import './globals.js'; -import './components/components.module.js'; +import './globals.js' +import './components/components.module.js' -import { AppController } from './app.controller.js'; -import { AppRoutingModule } from './states/states.module.js'; -import { CatalogsModule } from './catalogs/catalogs.module.js'; -import { CoreModule } from './core/core.module.js'; -import { RequestsModule } from './requests/requests.module.js'; -import { ServicesModule } from './services/services.module.js'; +import { AppController } from './app.controller.js' +import { AppRoutingModule } from './states/states.module.js' +import { CatalogsModule } from './catalogs/catalogs.module.js' +import { CoreModule } from './core/core.module.js' +import { RequestsModule } from './requests/requests.module.js' +import { ServicesModule } from './services/services.module.js' export default angular .module('app', [ @@ -18,7 +18,7 @@ export default angular // Feature Modules CatalogsModule, RequestsModule, - ServicesModule, + ServicesModule ]) .controller('AppController', AppController) - .name; + .name diff --git a/client/app/catalogs/catalog-explorer.component.js b/client/app/catalogs/catalog-explorer.component.js index 92e46e9a2..b32f44894 100644 --- a/client/app/catalogs/catalog-explorer.component.js +++ b/client/app/catalogs/catalog-explorer.component.js @@ -1,19 +1,19 @@ /* eslint camelcase: "off" */ -import '../../assets/sass/_explorer.sass'; -import templateUrl from './catalog-explorer.html'; +import '../../assets/sass/_explorer.sass' +import templateUrl from './catalog-explorer.html' export const CatalogExplorerComponent = { templateUrl, controller: ComponentController, - controllerAs: 'vm', -}; + controllerAs: 'vm' +} /** @ngInject */ -function ComponentController($state, CatalogsState, ListView, EventNotifications) { - const vm = this; - vm.permissions = CatalogsState.getPermissions(); +function ComponentController ($state, CatalogsState, ListView, EventNotifications) { + const vm = this + vm.permissions = CatalogsState.getPermissions() - vm.$onInit = function() { + vm.$onInit = function () { angular.extend(vm, { title: __('Catalogs'), loading: false, @@ -32,101 +32,101 @@ function ComponentController($state, CatalogsState, ListView, EventNotifications toolbarConfig: { sortConfig: getSortConfig(), filterConfig: {}, - isTableView: false, - }, - }); - resolveServiceTemplates(vm.limit, 0); - }; + isTableView: false + } + }) + resolveServiceTemplates(vm.limit, 0) + } // Config - function getCardConfig() { + function getCardConfig () { return { showSelectBox: false, selectionMatchProp: 'id', - onClick: viewDetails, - }; + onClick: viewDetails + } } - function getFilterConfig() { - const catalogNames = vm.catalogsList.map((catalog) => catalog.name); + function getFilterConfig () { + const catalogNames = vm.catalogsList.map((catalog) => catalog.name) return { fields: [ ListView.createFilterField('name', __('Name'), __('Filter by Name'), 'text'), ListView.createFilterField('description', __('Description'), __('Filter by Description'), 'text'), - ListView.createFilterField('service_template_catalog.name', __('Catalog Name'), __('Filter by Catalog Name'), 'select', catalogNames), + ListView.createFilterField('service_template_catalog.name', __('Catalog Name'), __('Filter by Catalog Name'), 'select', catalogNames) ], resultsCount: 0, totalCount: 0, appliedFilters: CatalogsState.getFilters(), - onFilterChange: filterChange, - }; + onFilterChange: filterChange + } } - function filterChange(filters) { - CatalogsState.setFilters(filters); - resolveServiceTemplates(vm.limit, 0); + function filterChange (filters) { + CatalogsState.setFilters(filters) + resolveServiceTemplates(vm.limit, 0) } - function getSortConfig() { + function getSortConfig () { return { fields: [ ListView.createSortField('name', __('Name'), 'alpha'), - ListView.createSortField('tenant_id', __('Tenant'), 'numeric'), + ListView.createSortField('tenant_id', __('Tenant'), 'numeric') // ListView.createSortField('service_templates.count', __('Catalog Items'), 'numeric'), ], onSortChange: sortChange, isAscending: CatalogsState.getSort().isAscending, - currentField: CatalogsState.getSort().currentField, - }; + currentField: CatalogsState.getSort().currentField + } } // Private - function resolveServiceTemplates(limit, offset) { - vm.loading = true; - vm.offset = offset; + function resolveServiceTemplates (limit, offset) { + vm.loading = true + vm.offset = offset - return CatalogsState.getServiceTemplates(limit, offset).then(success, failure); + return CatalogsState.getServiceTemplates(limit, offset).then(success, failure) - function success(response) { - vm.serviceTemplateList = response.resources; + function success (response) { + vm.serviceTemplateList = response.resources CatalogsState.getCatalogs(limit, offset).then((response) => { - vm.catalogsList = response.resources; - vm.loading = false; - vm.toolbarConfig.filterConfig = getFilterConfig(); - getFilterCount(); - }); - - function getFilterCount() { - CatalogsState.getMinimal('service_templates').then(success, failure); - - function success(result) { - vm.filterCount = result.subcount; - vm.toolbarConfig.filterConfig.resultsCount = result.subcount; + vm.catalogsList = response.resources + vm.loading = false + vm.toolbarConfig.filterConfig = getFilterConfig() + getFilterCount() + }) + + function getFilterCount () { + CatalogsState.getMinimal('service_templates').then(success, failure) + + function success (result) { + vm.filterCount = result.subcount + vm.toolbarConfig.filterConfig.resultsCount = result.subcount } } } - function failure(_error) { - vm.loading = false; - EventNotifications.error(__('There was an error loading catalogs.')); + function failure (_error) { + vm.loading = false + EventNotifications.error(__('There was an error loading catalogs.')) } } - function sortChange(sortId, isAscending) { - CatalogsState.setSort(sortId, isAscending); - resolveServiceTemplates(vm.limit, 0); + function sortChange (sortId, isAscending) { + CatalogsState.setSort(sortId, isAscending) + resolveServiceTemplates(vm.limit, 0) } - function viewDetails(template) { - $state.go('catalogs.details', {serviceTemplateId: template.id}); + function viewDetails (template) { + $state.go('catalogs.details', {serviceTemplateId: template.id}) } - function updatePagination(limit, offset) { - vm.limit = limit; - vm.offset = offset; - vm.resolveServiceTemplates(limit, offset); + function updatePagination (limit, offset) { + vm.limit = limit + vm.offset = offset + vm.resolveServiceTemplates(limit, offset) } } diff --git a/client/app/catalogs/catalogs-state.service.js b/client/app/catalogs/catalogs-state.service.js index d350462ab..b2d10a629 100644 --- a/client/app/catalogs/catalogs-state.service.js +++ b/client/app/catalogs/catalogs-state.service.js @@ -1,12 +1,12 @@ /* eslint camelcase: "off" */ /** @ngInject */ -export function CatalogsStateFactory(CollectionsApi, RBAC) { +export function CatalogsStateFactory (CollectionsApi, RBAC) { const sort = { isAscending: true, - currentField: {id: 'name', title: __('Name'), sortType: 'alpha'}, - }; - let filters = []; + currentField: {id: 'name', title: __('Name'), sortType: 'alpha'} + } + let filters = [] return { getMinimal: getMinimal, @@ -16,85 +16,85 @@ export function CatalogsStateFactory(CollectionsApi, RBAC) { setSort: setSort, getFilters: getFilters, setFilters: setFilters, - getPermissions: getPermissions, - }; + getPermissions: getPermissions + } - function setSort(currentField, isAscending) { - sort.isAscending = isAscending; - sort.currentField = currentField; + function setSort (currentField, isAscending) { + sort.isAscending = isAscending + sort.currentField = currentField } - function getSort() { - return sort; + function getSort () { + return sort } - function setFilters(filterArray) { - filters = filterArray; + function setFilters (filterArray) { + filters = filterArray } - function getFilters() { - return filters; + function getFilters () { + return filters } - function getQueryFilters(filters) { - const queryFilters = ["display=true"]; + function getQueryFilters (filters) { + const queryFilters = ['display=true'] - angular.forEach(filters, function(nextFilter) { + angular.forEach(filters, function (nextFilter) { switch (nextFilter.id) { case 'name': - queryFilters.push("name='%" + nextFilter.value + "%'"); - break; + queryFilters.push("name='%" + nextFilter.value + "%'") + break case 'description': - queryFilters.push("description='%" + nextFilter.value + "%'"); - break; + queryFilters.push("description='%" + nextFilter.value + "%'") + break default: - queryFilters.push(nextFilter.id + '=' + nextFilter.value); + queryFilters.push(nextFilter.id + '=' + nextFilter.value) } - }); + }) - return queryFilters; + return queryFilters } - function getPermissions() { + function getPermissions () { const permissions = { create: RBAC.hasAny(['st_catalog_new', 'st_catalog_admin']), edit: RBAC.hasAny(['st_catalog_edit', 'st_catalog_admin']), - delete: RBAC.hasAny(['st_catalog_delete', 'st_catalog_admin']), - }; + delete: RBAC.hasAny(['st_catalog_delete', 'st_catalog_admin']) + } - return permissions; + return permissions } - function getCatalogs() { + function getCatalogs () { const options = { - expand: ['resources'], - }; + expand: ['resources'] + } - return CollectionsApi.query('service_catalogs', options); + return CollectionsApi.query('service_catalogs', options) } - function getServiceTemplates(limit, offset) { + function getServiceTemplates (limit, offset) { const options = { expand: ['resources'], attributes: ['picture', 'picture.image_href', 'service_template_catalog'], limit: limit, offset: offset, - filter: getQueryFilters(getFilters()), - }; + filter: getQueryFilters(getFilters()) + } - options.sort_by = getSort().currentField.id; - options.sort_options = getSort().currentField.sortType === 'alpha' ? 'ignore_case' : ''; - options.sort_order = getSort().isAscending ? 'asc' : 'desc'; + options.sort_by = getSort().currentField.id + options.sort_options = getSort().currentField.sortType === 'alpha' ? 'ignore_case' : '' + options.sort_order = getSort().isAscending ? 'asc' : 'desc' - return CollectionsApi.query('service_templates', options); + return CollectionsApi.query('service_templates', options) } - function getMinimal(collection) { + function getMinimal (collection) { const options = { filter: getQueryFilters(getFilters()), - hide: 'resources', - }; + hide: 'resources' + } - return CollectionsApi.query(collection, options); + return CollectionsApi.query(collection, options) } } diff --git a/client/app/catalogs/catalogs.module.js b/client/app/catalogs/catalogs.module.js index 8acab679b..09fbf252c 100644 --- a/client/app/catalogs/catalogs.module.js +++ b/client/app/catalogs/catalogs.module.js @@ -1,11 +1,11 @@ -import { CatalogExplorerComponent } from './catalog-explorer.component.js'; -import { CatalogsStateFactory } from './catalogs-state.service.js'; -import { SharedModule } from '../shared/shared.module.js'; +import { CatalogExplorerComponent } from './catalog-explorer.component.js' +import { CatalogsStateFactory } from './catalogs-state.service.js' +import { SharedModule } from '../shared/shared.module.js' export const CatalogsModule = angular .module('app.catalogs', [ - SharedModule, + SharedModule ]) .component('catalogExplorer', CatalogExplorerComponent) .factory('CatalogsState', CatalogsStateFactory) - .name; + .name diff --git a/client/app/components/components.module.js b/client/app/components/components.module.js index ff9810ccd..e2532d4e7 100644 --- a/client/app/components/components.module.js +++ b/client/app/components/components.module.js @@ -1,7 +1,7 @@ -import { SharedModule } from '../shared/shared.module.js'; +import { SharedModule } from '../shared/shared.module.js' export default angular .module('app.components', [ - SharedModule, + SharedModule ]) - .name; + .name diff --git a/client/app/core/appliance-info.service.js b/client/app/core/appliance-info.service.js index 0e3552171..442e83e39 100644 --- a/client/app/core/appliance-info.service.js +++ b/client/app/core/appliance-info.service.js @@ -1,17 +1,17 @@ /** @ngInject */ -export function ApplianceInfo() { - let applianceInfo = {}; +export function ApplianceInfo () { + let applianceInfo = {} return { get: get, - set: set, - }; + set: set + } - function get() { - return applianceInfo; + function get () { + return applianceInfo } - function set(data) { + function set (data) { applianceInfo = { copyright: data.product_info.copyright, supportWebsiteText: data.product_info.support_website_text, @@ -20,7 +20,7 @@ export function ApplianceInfo() { role: data.identity.role, version: data.server_info.version + '.' + data.server_info.build, server: data.server_info.appliance, - asyncNotify: data.settings.asynchronous_notifications, - }; + asyncNotify: data.settings.asynchronous_notifications + } } } diff --git a/client/app/core/authentication-api.factory.js b/client/app/core/authentication-api.factory.js index f59fac0da..be9fa7ab3 100644 --- a/client/app/core/authentication-api.factory.js +++ b/client/app/core/authentication-api.factory.js @@ -1,29 +1,29 @@ /** @ngInject */ -export function AuthenticationApiFactory($http, $base64, API_BASE, Session, Notifications) { +export function AuthenticationApiFactory ($http, $base64, API_BASE, Session, Notifications) { var service = { - login: login, - }; + login: login + } - return service; + return service - function login(userLogin, password) { + function login (userLogin, password) { return $http.get(API_BASE + '/api/auth?requester_type=ui', { headers: { 'Authorization': 'Basic ' + $base64.encode([userLogin, password].join(':')), 'X-Auth-Token': undefined, - 'X-Miq-Group': undefined, - }, - }).then(loginSuccess, loginFailure); + 'X-Miq-Group': undefined + } + }).then(loginSuccess, loginFailure) - function loginSuccess(response) { - Session.setAuthToken(response.data.auth_token); + function loginSuccess (response) { + Session.setAuthToken(response.data.auth_token) } - function loginFailure(response) { - Session.destroy(); - Notifications.message('danger', '', __('Incorrect username or password.'), false); + function loginFailure (response) { + Session.destroy() + Notifications.message('danger', '', __('Incorrect username or password.'), false) - return response; + return response } } } diff --git a/client/app/core/authorization.config.js b/client/app/core/authorization.config.js index 71f94d026..57d44d814 100644 --- a/client/app/core/authorization.config.js +++ b/client/app/core/authorization.config.js @@ -1,132 +1,135 @@ /* eslint camelcase: "off" */ /** @ngInject */ -export function authConfig($httpProvider) { - $httpProvider.interceptors.push(interceptor); +export function authConfig ($httpProvider) { + $httpProvider.interceptors.push(interceptor) /** @ngInject */ - function interceptor($injector, $q, $window) { + function interceptor ($injector, $q, $window) { return { response: response, - responseError: responseError, - }; + responseError: responseError + } - function response(res) { - if (401 === res.status) { - endSession(); + function response (res) { + if (res.status === 401) { + endSession() - return $q.reject(res); + return $q.reject(res) } - return $q.resolve(res); + return $q.resolve(res) } - function responseError(rej) { - if (401 === rej.status) { - endSession(); + function responseError (rej) { + if (rej.status === 401) { + endSession() - return $q.reject(rej); + return $q.reject(rej) } - return $q.reject(rej); + return $q.reject(rej) } - function endSession() { - var $state = $injector.get('$state'); - var Session = $injector.get('Session'); + function endSession () { + var $state = $injector.get('$state') + var Session = $injector.get('Session') - if ('login' !== $state.current.name) { - Session.destroy(); - $window.location.href = $state.href('login') + "?timeout"; + if ($state.current.name !== 'login') { + Session.destroy() + $window.location.href = $state.href('login') + '?timeout' } } } } /** @ngInject */ -export function authInit($rootScope, $state, $log, Session, $sessionStorage, Language, ApplianceInfo, $window, RBAC) { - $rootScope.$on('$stateChangeStart', changeStart); - $rootScope.$on('$stateChangeError', changeError); - $rootScope.$on('$stateChangeSuccess', changeSuccess); +export function authInit ($rootScope, $state, $log, Session, $sessionStorage, Language, ApplianceInfo, $window, RBAC) { + $rootScope.$on('$stateChangeStart', changeStart) + $rootScope.$on('$stateChangeError', changeError) + $rootScope.$on('$stateChangeSuccess', changeSuccess) - $sessionStorage.$sync(); // needed when called right on reload + $sessionStorage.$sync() // needed when called right on reload if ($sessionStorage.token) { - syncSession(); + syncSession() } - function changeStart(event, toState, toParams, _fromState, _fromParams) { + + function changeStart (event, toState, toParams, _fromState, _fromParams) { if (angular.isDefined(toState.data)) { if (angular.isDefined(toState.data.authorization) && !toState.data.authorization) { - event.preventDefault(); - $state.transitionTo('dashboard'); + event.preventDefault() + $state.transitionTo('dashboard') - return; + return } if (!toState.data.requireUser) { - return; + return } } if (Session.active()) { - return; + return } // user is required and session not active - not going anywhere right away - event.preventDefault(); - $sessionStorage.$sync(); // needed when called right on reload + event.preventDefault() + $sessionStorage.$sync() // needed when called right on reload if (!$sessionStorage.token) { // no saved token, go directly to login - $state.transitionTo('login'); + $state.transitionTo('login') - return; + return } - syncSession().then(rbacReloadOrLogin(toState, toParams)).catch(badUser); + syncSession().then(rbacReloadOrLogin(toState, toParams)).catch(badUser) } - function syncSession() { - return new Promise(function (resolve, _reject) { + + function syncSession () { + return new Promise(function (resolve, reject) { // trying saved token.. - Session.setAuthToken($sessionStorage.token); - Session.setMiqGroup($sessionStorage.miqGroup); + Session.setAuthToken($sessionStorage.token) + Session.setMiqGroup($sessionStorage.miqGroup) Session.loadUser() .then(function (response) { if (angular.isDefined(response)) { - Language.onReload(response); - ApplianceInfo.set(response); - RBAC.setRole(response.identity.role); + Language.onReload(response) + ApplianceInfo.set(response) + RBAC.setRole(response.identity.role) } - resolve(); + resolve() }) - .catch(badUser); - }); + .catch(badUser) + }) } - function rbacReloadOrLogin(toState, toParams) { - return function() { + + function rbacReloadOrLogin (toState, toParams) { + return function () { if (RBAC.navigationEnabled()) { - $state.go(toState, toParams); + $state.go(toState, toParams) } else { - Session.privilegesError = true; - $window.location.href = $state.href('login'); + Session.privilegesError = true + $window.location.href = $state.href('login') } - }; + } } - function badUser(error) { - $log.error(__('Error retrieving user info'), [error]); - $window.location.href = $state.href('login'); + function badUser (error) { + $log.error(__('Error retrieving user info'), [error]) + $window.location.href = $state.href('login') } - function changeError(event, toState, _toParams, _fromState, _fromParams, error) { + function changeError (event, toState, _toParams, _fromState, _fromParams, error) { // If a 401 is encountered during a state change, then kick the user back to the login - if (401 || 403 === error.status) { - event.preventDefault(); + if (401 || error.status === 403) { + event.preventDefault() if (Session.active()) { - $state.transitionTo('logout'); - } else if ('login' !== toState.name) { - $state.transitionTo('login'); + $state.transitionTo('logout') + } else if (toState.name !== 'login') { + $state.transitionTo('login') } } } - function changeSuccess() { - angular.element('html, body').animate({scrollTop: 0}, 200); + function changeSuccess () { + angular.element('html, body').animate({scrollTop: 0}, 200) } } diff --git a/client/app/core/chargeback.service.js b/client/app/core/chargeback.service.js index e9d07d358..99136b36f 100644 --- a/client/app/core/chargeback.service.js +++ b/client/app/core/chargeback.service.js @@ -1,83 +1,83 @@ /* eslint-disable camelcase */ /** @ngInject */ -export function ChargebackFactory(lodash) { +export function ChargebackFactory (lodash) { const service = { adjustRelativeCost: adjustRelativeCost, currentReport: currentReport, processReports: processReports, - reportUsedCost: reportUsedCost, - }; + reportUsedCost: reportUsedCost + } // recomputes items[*].chargeback_relative_cost - function adjustRelativeCost(items) { + function adjustRelativeCost (items) { const sums = lodash(items) .map('chargeback') .map('used_cost_sum') .values().sort() .filter(angular.identity) // nonzero - .value(); + .value() - const len = sums.length; - const bounds = [len * 0.25, len * 0.5, len * 0.75]; + const len = sums.length + const bounds = [len * 0.25, len * 0.5, len * 0.75] - items.forEach(function(item) { + items.forEach(function (item) { if (!item.chargeback.used_cost_sum) { - item.chargeback_relative_cost = ''; + item.chargeback_relative_cost = '' - return; + return } - const idx = sums.findIndex(function(v) { - return v === item.chargeback.used_cost_sum; - }); + const idx = sums.findIndex(function (v) { + return v === item.chargeback.used_cost_sum + }) if (idx < bounds[0]) { - item.chargeback_relative_cost = '$'; + item.chargeback_relative_cost = '$' } else if (idx < bounds[1]) { - item.chargeback_relative_cost = '$$'; + item.chargeback_relative_cost = '$$' } else if (idx < bounds[2]) { - item.chargeback_relative_cost = '$$$'; + item.chargeback_relative_cost = '$$$' } else { - item.chargeback_relative_cost = '$$$$'; + item.chargeback_relative_cost = '$$$$' } - }); + }) } - function currentReport(item) { + function currentReport (item) { const latestDate = lodash(item.chargeback_report.results || []) .map('start_date') .values() .sort() .reverse() - .first(); + .first() const latestReports = lodash(item.chargeback_report.results || []) .filter({start_date: latestDate}) - .value(); + .value() - latestReports.forEach(function(report) { - report.used_cost_sum = reportUsedCost(report); - }); + latestReports.forEach(function (report) { + report.used_cost_sum = reportUsedCost(report) + }) return { start_date: latestDate, used_cost_sum: lodash.sumBy(latestReports, 'used_cost_sum'), - vms: latestReports, - }; + vms: latestReports + } } - function processReports(item) { - item.chargeback = service.currentReport(item); + function processReports (item) { + item.chargeback = service.currentReport(item) } // sum all *_used_cost fields in the report - function reportUsedCost(report) { - return lodash.reduce(report, function(total, v, k) { - total += k.match(/_used_cost$/) ? Number(v) : 0; + function reportUsedCost (report) { + return lodash.reduce(report, function (total, v, k) { + total += k.match(/_used_cost$/) ? Number(v) : 0 - return total; - }, 0); + return total + }, 0) } - return service; + return service } diff --git a/client/app/core/collections-api.factory.js b/client/app/core/collections-api.factory.js index e5fa5bc9d..69bb54596 100644 --- a/client/app/core/collections-api.factory.js +++ b/client/app/core/collections-api.factory.js @@ -1,151 +1,151 @@ /* eslint camelcase: "off" */ /** @ngInject */ -export function CollectionsApiFactory($http, API_BASE) { +export function CollectionsApiFactory ($http, API_BASE) { const service = { query: query, get: get, post: post, options: options, - delete: remove, - }; + delete: remove + } - return service; + return service - function query(collection, options) { - const url = API_BASE + '/api/' + collection; + function query (collection, options) { + const url = API_BASE + '/api/' + collection // $log.debug("query = " + url + buildQuery(options)); return $http.get(url + buildQuery(options), buildConfig(options)) - .then(handleSuccess); + .then(handleSuccess) - function handleSuccess(response) { - return response.data; + function handleSuccess (response) { + return response.data } } - function get(collection, id, options) { - const url = API_BASE + '/api/' + collection + '/' + id; + function get (collection, id, options) { + const url = API_BASE + '/api/' + collection + '/' + id // $log.debug("get = " + url + buildQuery(options)); return $http.get(url + buildQuery(options), buildConfig(options)) - .then(handleSuccess); + .then(handleSuccess) - function handleSuccess(response) { - return response.data; + function handleSuccess (response) { + return response.data } } - function post(collection, id, options, data) { - const url = API_BASE + '/api/' + collection + '/' + (id || "") + buildQuery(options); + function post (collection, id, options, data) { + const url = API_BASE + '/api/' + collection + '/' + (id || '') + buildQuery(options) // $log.debug("post = " + url + buildQuery(options)); return $http.post(url, data, buildConfig(options)) - .then(handleSuccess); + .then(handleSuccess) - function handleSuccess(response) { - return response.data; + function handleSuccess (response) { + return response.data } } - function options(collection) { - const url = API_BASE + '/api/' + collection; + function options (collection) { + const url = API_BASE + '/api/' + collection return $http.get(url + buildQuery(options)) - .then(handleSuccess); + .then(handleSuccess) - function handleSuccess(response) { - return response.data; + function handleSuccess (response) { + return response.data } } // delete is a reserved word in JS - function remove(collection, id, options) { - const url = API_BASE + '/api/' + collection + '/' + (id || "") + buildQuery(options); + function remove (collection, id, options) { + const url = API_BASE + '/api/' + collection + '/' + (id || '') + buildQuery(options) // $log.debug("post = " + url + buildQuery(options)); return $http.delete(url, buildConfig(options)) - .then(handleSuccess); + .then(handleSuccess) - function handleSuccess(response) { - return response.data; + function handleSuccess (response) { + return response.data } } // Private - function buildQuery(options) { - const params = []; - options = options || {}; + function buildQuery (options) { + const params = [] + options = options || {} if (options.expand) { if (angular.isArray(options.expand)) { - options.expand = options.expand.join(','); + options.expand = options.expand.join(',') } - params.push('expand=' + encodeURIComponent(options.expand)); + params.push('expand=' + encodeURIComponent(options.expand)) } if (options.attributes) { if (angular.isArray(options.attributes)) { - options.attributes = options.attributes.join(','); + options.attributes = options.attributes.join(',') } - params.push('attributes=' + encodeURIComponent(options.attributes)); + params.push('attributes=' + encodeURIComponent(options.attributes)) } if (options.format_attributes) { if (angular.isArray(options.format_attributes)) { - options.format_attributes = options.format_attributes.join(','); + options.format_attributes = options.format_attributes.join(',') } - params.push('format_attributes=' + encodeURIComponent(options.format_attributes)); + params.push('format_attributes=' + encodeURIComponent(options.format_attributes)) } if (options.filter) { - angular.forEach(options.filter, function(filter) { - params.push('filter[]=' + encodeURIComponent(filter)); - }); + angular.forEach(options.filter, function (filter) { + params.push('filter[]=' + encodeURIComponent(filter)) + }) } if (options.limit) { - params.push('limit=' + encodeURIComponent(options.limit)); + params.push('limit=' + encodeURIComponent(options.limit)) } if (options.offset) { - params.push('offset=' + encodeURIComponent(options.offset)); + params.push('offset=' + encodeURIComponent(options.offset)) } if (options.hide) { - params.push('hide=' + encodeURIComponent(options.hide)); + params.push('hide=' + encodeURIComponent(options.hide)) } if (options.sort_by) { - params.push('sort_by=' + encodeURIComponent(options.sort_by)); + params.push('sort_by=' + encodeURIComponent(options.sort_by)) } if (options.sort_order) { - params.push('sort_order=' + encodeURIComponent(options.sort_order)); + params.push('sort_order=' + encodeURIComponent(options.sort_order)) } if (options.sort_options) { - params.push('sort_options=' + encodeURIComponent(options.sort_options)); + params.push('sort_options=' + encodeURIComponent(options.sort_options)) } - return params.length ? '?' + params.join('&') : ''; + return params.length ? '?' + params.join('&') : '' } - function buildConfig(options) { - const config = {}; - options = options || {}; + function buildConfig (options) { + const config = {} + options = options || {} if (options.auto_refresh) { config.headers = { - 'X-Auth-Skip-Token-Renewal': 'true', - }; + 'X-Auth-Skip-Token-Renewal': 'true' + } } - return config; + return config } } diff --git a/client/app/core/config.js b/client/app/core/config.js index 64ae5fa25..8fbb80d95 100644 --- a/client/app/core/config.js +++ b/client/app/core/config.js @@ -3,19 +3,18 @@ var DEVEL_DOMAINS = [ 'localhost', '127.0.0.1', - '[::1]', -]; + '[::1]' +] -var isDevel = window._.includes(DEVEL_DOMAINS, window.location.hostname); +var isDevel = window._.includes(DEVEL_DOMAINS, window.location.hostname) /** @ngInject */ -export function configure($logProvider, $compileProvider, $qProvider) { - $logProvider.debugEnabled(isDevel); - $compileProvider.debugInfoEnabled(isDevel); +export function configure ($logProvider, $compileProvider, $qProvider) { + $logProvider.debugEnabled(isDevel) + $compileProvider.debugInfoEnabled(isDevel) // TODO: Remove following line as per: https://docs.angularjs.org/guide/migration#migrate1.5to1.6-ng-services-$compile - $compileProvider.preAssignBindingsEnabled(true); + $compileProvider.preAssignBindingsEnabled(true) - $qProvider.errorOnUnhandledRejections(false); + $qProvider.errorOnUnhandledRejections(false) } - diff --git a/client/app/core/core.module.js b/client/app/core/core.module.js index a454d731e..7196b374e 100644 --- a/client/app/core/core.module.js +++ b/client/app/core/core.module.js @@ -3,49 +3,49 @@ import { authConfig, - authInit, -} from './authorization.config.js'; + authInit +} from './authorization.config.js' import { configure, - init, -} from './config.js'; + init +} from './config.js' import { navConfig, - navInit, -} from './navigation.config.js'; + navInit +} from './navigation.config.js' // Core -import { ApplianceInfo } from './appliance-info.service.js'; -import { AuthenticationApiFactory } from './authentication-api.factory.js'; -import { BaseModalController } from './modal/base-modal-controller.js'; -import { BaseModalFactory } from './modal/base-modal.factory.js'; -import { ChargebackFactory } from './chargeback.service.js'; -import { CollectionsApiFactory } from './collections-api.factory.js'; -import { DialogFieldRefreshFactory } from './dialog-field-refresh.service.js'; -import { EventNotificationsFactory } from './event-notifications.service.js'; -import { ExceptionModule } from './exception/exception.module.js'; -import { LanguageFactory } from './language.service.js'; -import { LanguageSwitcherDirective } from './language-switcher/language-switcher.directive.js'; -import { ListConfigurationFactory } from './list-configuration.service.js'; -import { ListViewFactory } from './list-view.service.js'; -import { NavCountsFactory } from './navcounts.service.js'; -import { NavigationController } from './navigation/navigation-controller.js'; -import { NavigationProvider } from './navigation.provider.js'; -import { PollingFactory } from './polling.service.js'; -import { RBACFactory } from './rbac.service.js'; -import { RouterModule } from './router/router.module.js'; -import { SaveModalDialogFactory } from './save-modal-dialog/save-modal-dialog.factory.js'; -import { SessionFactory } from './session.service.js'; -import { SharedModule } from '../shared/shared.module.js'; -import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component.js'; -import { ShoppingCartFactory } from './shopping-cart.service.js'; -import { SkinModule } from '../skin/skin.module.js'; -import { TagEditorFactory } from './tag-editor-modal/tag-editor-modal.service.js'; -import { gettextInit } from './gettext.config.js'; -import { layoutInit } from './layouts.config.js'; -import { TaggingService } from './tagging.service.js'; +import { ApplianceInfo } from './appliance-info.service.js' +import { AuthenticationApiFactory } from './authentication-api.factory.js' +import { BaseModalController } from './modal/base-modal-controller.js' +import { BaseModalFactory } from './modal/base-modal.factory.js' +import { ChargebackFactory } from './chargeback.service.js' +import { CollectionsApiFactory } from './collections-api.factory.js' +import { DialogFieldRefreshFactory } from './dialog-field-refresh.service.js' +import { EventNotificationsFactory } from './event-notifications.service.js' +import { ExceptionModule } from './exception/exception.module.js' +import { LanguageFactory } from './language.service.js' +import { LanguageSwitcherDirective } from './language-switcher/language-switcher.directive.js' +import { ListConfigurationFactory } from './list-configuration.service.js' +import { ListViewFactory } from './list-view.service.js' +import { NavCountsFactory } from './navcounts.service.js' +import { NavigationController } from './navigation/navigation-controller.js' +import { NavigationProvider } from './navigation.provider.js' +import { PollingFactory } from './polling.service.js' +import { RBACFactory } from './rbac.service.js' +import { RouterModule } from './router/router.module.js' +import { SaveModalDialogFactory } from './save-modal-dialog/save-modal-dialog.factory.js' +import { SessionFactory } from './session.service.js' +import { SharedModule } from '../shared/shared.module.js' +import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component.js' +import { ShoppingCartFactory } from './shopping-cart.service.js' +import { SkinModule } from '../skin/skin.module.js' +import { TagEditorFactory } from './tag-editor-modal/tag-editor-modal.service.js' +import { gettextInit } from './gettext.config.js' +import { layoutInit } from './layouts.config.js' +import { TaggingService } from './tagging.service.js' export const CoreModule = angular .module('app.core', [ @@ -63,7 +63,7 @@ export const CoreModule = angular ExceptionModule, RouterModule, SharedModule, - SkinModule, + SkinModule ]) .constant('lodash', _) .constant('ActionCable', ActionCable) @@ -105,4 +105,4 @@ export const CoreModule = angular .run(layoutInit) .run(navInit) .run(init) - .name; + .name diff --git a/client/app/core/dialog-field-refresh.service.js b/client/app/core/dialog-field-refresh.service.js index 78e614a27..aea9f7524 100644 --- a/client/app/core/dialog-field-refresh.service.js +++ b/client/app/core/dialog-field-refresh.service.js @@ -2,14 +2,14 @@ /* eslint angular/angularelement: "off" */ /** @ngInject */ -export function DialogFieldRefreshFactory(CollectionsApi) { +export function DialogFieldRefreshFactory (CollectionsApi) { var service = { - refreshDialogField: refreshDialogField, - }; + refreshDialogField: refreshDialogField + } - return service; + return service - function refreshDialogField(dialogData, dialogField, url, resourceId) { + function refreshDialogField (dialogData, dialogField, url, resourceId) { return new Promise((resolve, reject) => { CollectionsApi.post( url, @@ -19,14 +19,14 @@ export function DialogFieldRefreshFactory(CollectionsApi) { action: 'refresh_dialog_fields', resource: { dialog_fields: dialogData, - fields: dialogField, - }, + fields: dialogField + } }) ).then((response) => { - resolve(response.result[dialogField]); + resolve(response.result[dialogField]) }).catch((response) => { - reject(response); - }); - }); + reject(response) + }) + }) } } diff --git a/client/app/core/event-notifications.service.js b/client/app/core/event-notifications.service.js index 3bb9e1e8e..7403e45a2 100644 --- a/client/app/core/event-notifications.service.js +++ b/client/app/core/event-notifications.service.js @@ -1,7 +1,7 @@ /** @ngInject */ -export function EventNotificationsFactory($timeout, lodash, CollectionsApi, Session, $log, ActionCable, ApplianceInfo) { - const state = {}; - const toastDelay = 8 * 1000; +export function EventNotificationsFactory ($timeout, lodash, CollectionsApi, Session, $log, ActionCable, ApplianceInfo) { + const state = {} + const toastDelay = 8 * 1000 const service = { state: getState, batch: batchAdd, @@ -16,147 +16,147 @@ export function EventNotificationsFactory($timeout, lodash, CollectionsApi, Sess clear: clear, clearAll: clearAll, setViewingToast: setViewingToast, - dismissToast: dismissToast, - }; + dismissToast: dismissToast + } - notificationsInit(); - asyncInit(); + notificationsInit() + asyncInit() - return service; + return service - function getState() { - return state; + function getState () { + return state } - function batchAdd(events, successMsg = "", failMsg = "") { - const displayToast = events.length <= 6; - events.forEach(function(event) { + function batchAdd (events, successMsg = '', failMsg = '') { + const displayToast = events.length <= 6 + events.forEach(function (event) { if (event.success) { - service.success(successMsg + ' ' + event.message); + service.success(successMsg + ' ' + event.message) } else { - service.error(failMsg + ' ' + event.message); + service.error(failMsg + ' ' + event.message) } - }); + }) if (!displayToast) { - state.toastNotifications = []; - service.info(__('Review the notification tray for results of this batch operation')); + state.toastNotifications = [] + service.info(__('Review the notification tray for results of this batch operation')) } } - function addInfo(message, notificationData, id) { - add('info', 'info', message, notificationData, id); + function addInfo (message, notificationData, id) { + add('info', 'info', message, notificationData, id) } - function addSuccess(message, notificationData, id) { - add('success', 'success', message, notificationData, id); + function addSuccess (message, notificationData, id) { + add('success', 'success', message, notificationData, id) } - function addError(message, notificationData, id, displayToast) { - add('error', 'danger', message, notificationData, id, displayToast); + function addError (message, notificationData, id, displayToast) { + add('error', 'danger', message, notificationData, id, displayToast) } - function addWarn(message, notificationData, id) { - add('warning', 'warning', message, notificationData, id); + function addWarn (message, notificationData, id) { + add('warning', 'warning', message, notificationData, id) } - function updateNotificationRead(unread, notification, group) { + function updateNotificationRead (unread, notification, group) { if (notification) { - notification.unread = unread; + notification.unread = unread if (!unread) { - removeToast(notification); + removeToast(notification) } } - updateUnreadCount(group); + updateUnreadCount(group) } - function markRead(notification, group) { + function markRead (notification, group) { if (notification && notification.href) { - CollectionsApi.post('notifications', notification.id, {}, {action: 'mark_as_seen'}); + CollectionsApi.post('notifications', notification.id, {}, {action: 'mark_as_seen'}) } - updateNotificationRead(false, notification, group); + updateNotificationRead(false, notification, group) } - function markUnread(notification, group) { - updateNotificationRead(true, notification, group); + function markUnread (notification, group) { + updateNotificationRead(true, notification, group) } - function markAllRead(group) { + function markAllRead (group) { if (group) { - const resources = group.notifications.map(function(notification) { - notification.unread = false; - removeToast(notification); + const resources = group.notifications.map(function (notification) { + notification.unread = false + removeToast(notification) - return {href: notification.href}; - }); + return {href: notification.href} + }) if (resources.length > 0) { - CollectionsApi.post('notifications', undefined, {}, {action: 'mark_as_seen', resources: resources}); + CollectionsApi.post('notifications', undefined, {}, {action: 'mark_as_seen', resources: resources}) } - updateUnreadCount(group); + updateUnreadCount(group) } } - function markAllUnread(group) { + function markAllUnread (group) { if (group) { - group.notifications.forEach(function(notification) { - notification.unread = true; - }); - updateUnreadCount(group); + group.notifications.forEach(function (notification) { + notification.unread = true + }) + updateUnreadCount(group) } } - function clear(notification, group) { - let index; + function clear (notification, group) { + let index if (!group) { - group = lodash.find(state.groups, {notificationType: notification.notificationType}); + group = lodash.find(state.groups, {notificationType: notification.notificationType}) } if (group) { - index = group.notifications.indexOf(notification); + index = group.notifications.indexOf(notification) if (index > -1) { - group.notifications.splice(index, 1); - removeToast(notification); + group.notifications.splice(index, 1) + removeToast(notification) if (notification.href) { - CollectionsApi.delete('notifications', notification.id); + CollectionsApi.delete('notifications', notification.id) } - updateUnreadCount(group); + updateUnreadCount(group) } } } - function clearAll(group) { + function clearAll (group) { if (group) { - const resources = group.notifications.map(function(notification) { - removeToast(notification); + const resources = group.notifications.map(function (notification) { + removeToast(notification) - return {href: notification.href}; - }); + return {href: notification.href} + }) if (resources.length > 0) { - CollectionsApi.post('notifications', undefined, {}, {action: 'delete', resources: resources}); + CollectionsApi.post('notifications', undefined, {}, {action: 'delete', resources: resources}) } - group.notifications = []; - updateUnreadCount(group); + group.notifications = [] + updateUnreadCount(group) } } - function setViewingToast(notification, viewing) { - notification.viewing = viewing; + function setViewingToast (notification, viewing) { + notification.viewing = viewing if (!viewing && !notification.show) { - removeToast(notification); + removeToast(notification) } } - function dismissToast(notification) { - notification.show = false; - removeToast(notification); - service.markRead(notification); + function dismissToast (notification) { + notification.show = false + removeToast(notification) + service.markRead(notification) } // Private - function add(notificationType, type, message, notificationData, id) { - const group = lodash.find(state.groups, {notificationType: notificationType}); + function add (notificationType, type, message, notificationData, id) { + const group = lodash.find(state.groups, {notificationType: notificationType}) const newNotification = { id: id, notificationType: notificationType, @@ -165,75 +165,74 @@ export function EventNotificationsFactory($timeout, lodash, CollectionsApi, Sess message: message, data: notificationData || {}, href: id ? '/api/notifications/' + id : undefined, - timeStamp: (new Date()).getTime(), - }; + timeStamp: (new Date()).getTime() + } - group.notifications.unshift(newNotification); - updateUnreadCount(group); - showToast(newNotification); + group.notifications.unshift(newNotification) + updateUnreadCount(group) + showToast(newNotification) } - - function asyncInit() { + function asyncInit () { if (ApplianceInfo.get().asyncNotify) { - const cable = ActionCable.createConsumer('/ws/notifications'); + const cable = ActionCable.createConsumer('/ws/notifications') cable.subscriptions.create('NotificationChannel', { - disconnected: function() { - const vm = this; - Session.requestWsToken().then(null, function() { - $log.warn('Unable to retrieve a valid ws_token!'); + disconnected: function () { + const vm = this + Session.requestWsToken().then(null, function () { + $log.warn('Unable to retrieve a valid ws_token!') // Disconnect permanently if the ws_token cannot be fetched - vm.consumer.connection.close({allowReconnect: false}); - }); + vm.consumer.connection.close({allowReconnect: false}) + }) }, - received: function(data) { - $timeout(function() { - const msg = miqFormatNotification(data.text, data.bindings); - add('event', data.level, msg, {message: msg}, data.id); - }); - }, - }); + received: function (data) { + $timeout(function () { + const msg = miqFormatNotification(data.text, data.bindings) + add('event', data.level, msg, {message: msg}, data.id) + }) + } + }) } } - function miqFormatNotification(text, bindings) { - let str = __(text); - lodash.each(bindings, function(value, key) { - str = str.replace(new RegExp('%{' + key + '}', 'g'), value.text); - }); + function miqFormatNotification (text, bindings) { + let str = __(text) + lodash.each(bindings, function (value, key) { + str = str.replace(new RegExp('%{' + key + '}', 'g'), value.text) + }) - return str; + return str } - function notificationsInit() { - const eventTypes = ['info', 'success', 'error', 'warning']; + function notificationsInit () { + const eventTypes = ['info', 'success', 'error', 'warning'] - function Group(type) { - this.notificationType = type; - this.heading = lodash.capitalize(type); - this.unreadCount = 0; - this.notifications = []; + function Group (type) { + this.notificationType = type + this.heading = lodash.capitalize(type) + this.unreadCount = 0 + this.notifications = [] } - state.groups = eventTypes.map((type) => new Group(type)); - state.unreadNotifications = false; - state.toastNotifications = []; + state.groups = eventTypes.map((type) => new Group(type)) + state.unreadNotifications = false + state.toastNotifications = [] const options = { expand: 'resources', - attributes: 'details', - }; + attributes: 'details' + } CollectionsApi.query('notifications', options).then((result) => { result.resources.forEach((resource) => { - const group = lodash.find(state.groups, {notificationType: resource.details.level}) || new Group(resource.details.level); - importServerNotifications(group, resource); - }); - updateUnreadCount(); - }); - - function importServerNotifications(group, resource) { - const msg = miqFormatNotification(resource.details.text, resource.details.bindings); + const group = lodash.find(state.groups, {notificationType: resource.details.level}) || new Group(resource.details.level) + importServerNotifications(group, resource) + }) + updateUnreadCount() + }) + + function importServerNotifications (group, resource) { + const msg = miqFormatNotification(resource.details.text, resource.details.bindings) group.notifications.unshift({ id: resource.id, notificationType: resource.details.level, @@ -241,52 +240,52 @@ export function EventNotificationsFactory($timeout, lodash, CollectionsApi, Sess type: resource.details.level, message: msg, data: { - message: msg, + message: msg }, href: resource.href, - timeStamp: resource.details.created_at, - }); + timeStamp: resource.details.created_at + }) } } - function removeToast(notification) { - const index = state.toastNotifications.indexOf(notification); + function removeToast (notification) { + const index = state.toastNotifications.indexOf(notification) if (index > -1) { - state.toastNotifications.splice(index, 1); + state.toastNotifications.splice(index, 1) } } - function showToast(notification) { - notification.show = true; - notification.persistent = notification.data.persistent || notification.type === 'danger' || notification.type === 'error'; - state.toastNotifications.push(notification); + function showToast (notification) { + notification.show = true + notification.persistent = notification.data.persistent || notification.type === 'danger' || notification.type === 'error' + state.toastNotifications.push(notification) // any toast notifications with out 'danger' or 'error' status are automatically removed after a delay if (!notification.persistent) { - notification.viewing = false; - $timeout(function() { - notification.show = false; + notification.viewing = false + $timeout(function () { + notification.show = false if (!notification.viewing) { - removeToast(notification); + removeToast(notification) } - }, notification.data.toastDelay || toastDelay); + }, notification.data.toastDelay || toastDelay) } } - function updateUnreadCount(group) { + function updateUnreadCount (group) { if (group) { - update(group); + update(group) } else { state.groups.forEach((group) => { - update(group); - }); + update(group) + }) } - function update(group) { - group.unreadCount = group.notifications.filter((notification) => notification.unread).length; - state.unreadNotifications = angular.isDefined(lodash.find(state.groups, function(group) { - return group.unreadCount > 0; - })); + function update (group) { + group.unreadCount = group.notifications.filter((notification) => notification.unread).length + state.unreadNotifications = angular.isDefined(lodash.find(state.groups, function (group) { + return group.unreadCount > 0 + })) } } } diff --git a/client/app/core/exception/exception-handler.provider.js b/client/app/core/exception/exception-handler.provider.js index 8cec29df6..77d27dfa3 100644 --- a/client/app/core/exception/exception-handler.provider.js +++ b/client/app/core/exception/exception-handler.provider.js @@ -2,18 +2,18 @@ * Must configure the exception handling * @return {[type]} */ -export function exceptionHandlerProvider() { +export function exceptionHandlerProvider () { this.config = { - appErrorPrefix: undefined, - }; + appErrorPrefix: undefined + } - this.configure = function(appErrorPrefix) { - this.config.appErrorPrefix = appErrorPrefix; - }; + this.configure = function (appErrorPrefix) { + this.config.appErrorPrefix = appErrorPrefix + } - this.$get = function() { - return {config: this.config}; - }; + this.$get = function () { + return {config: this.config} + } } /** @@ -23,8 +23,8 @@ export function exceptionHandlerProvider() { * @return {[type]} * @ngInject */ -export function config($provide) { - $provide.decorator('$exceptionHandler', extendExceptionHandler); +export function config ($provide) { + $provide.decorator('$exceptionHandler', extendExceptionHandler) } /** @@ -35,16 +35,16 @@ export function config($provide) { * @return {Function} the decorated $exceptionHandler service * @ngInject */ -function extendExceptionHandler($delegate, exceptionHandler, $log) { - return function(exception, cause) { +function extendExceptionHandler ($delegate, exceptionHandler, $log) { + return function (exception, cause) { if (angular.isString(exception)) { - exception = Error(exception); + exception = Error(exception) } - var appErrorPrefix = exceptionHandler.config.appErrorPrefix || ''; - var errorData = {exception: exception, cause: cause}; - exception.message = appErrorPrefix + exception.message; - $delegate(exception, cause); + var appErrorPrefix = exceptionHandler.config.appErrorPrefix || '' + var errorData = {exception: exception, cause: cause} + exception.message = appErrorPrefix + exception.message + $delegate(exception, cause) /** * Could add the error to a service's collection, * add errors to $rootScope, log errors to remote web server, @@ -54,6 +54,6 @@ function extendExceptionHandler($delegate, exceptionHandler, $log) { * @example * throw { message: 'error message we added' }; */ - $log.error(exception.message, errorData); - }; + $log.error(exception.message, errorData) + } } diff --git a/client/app/core/exception/exception.module.js b/client/app/core/exception/exception.module.js index b6dda54ef..3389471ae 100644 --- a/client/app/core/exception/exception.module.js +++ b/client/app/core/exception/exception.module.js @@ -1,9 +1,9 @@ -import { config, exceptionHandlerProvider } from './exception-handler.provider.js'; -import { exception } from './exception.service.js'; +import { config, exceptionHandlerProvider } from './exception-handler.provider.js' +import { exception } from './exception.service.js' export const ExceptionModule = angular .module('app.core.exception', []) .factory('exception', exception) .provider('exceptionHandler', exceptionHandlerProvider) .config(config) - .name; + .name diff --git a/client/app/core/exception/exception.service.js b/client/app/core/exception/exception.service.js index 633e434c4..61937af1f 100644 --- a/client/app/core/exception/exception.service.js +++ b/client/app/core/exception/exception.service.js @@ -12,35 +12,35 @@ // .catch(exception.catch('Nothing to do here')); /** @ngInject */ -export function exception($log) { +export function exception ($log) { var service = { catch: exceptionCatcher, - log: exceptionLogger, - }; + log: exceptionLogger + } - return service; + return service - function exceptionCatcher(message) { - return function(error) { - logErrorMessage(message, error); - }; + function exceptionCatcher (message) { + return function (error) { + logErrorMessage(message, error) + } } - function exceptionLogger(message) { - return function(error) { - logErrorMessage(message, error); + function exceptionLogger (message) { + return function (error) { + logErrorMessage(message, error) - return Promise.reject(error); - }; + return Promise.reject(error) + } } // Private - function logErrorMessage(message, error) { + function logErrorMessage (message, error) { if (error.data && error.data.description) { - message += '\n' + error.data.description; - error.data.description = message; + message += '\n' + error.data.description + error.data.description = message } - $log.error(message, error); + $log.error(message, error) } } diff --git a/client/app/core/gettext.config.js b/client/app/core/gettext.config.js index d9ca6b64a..c4bdf1af9 100644 --- a/client/app/core/gettext.config.js +++ b/client/app/core/gettext.config.js @@ -2,25 +2,25 @@ /* eslint no-constant-condition: "off" */ /** @ngInject */ -export function gettextInit($window, gettextCatalog, gettext) { +export function gettextInit ($window, gettextCatalog, gettext) { // prepend [MISSING] to untranslated strings - gettextCatalog.debug = false; + gettextCatalog.debug = false - gettextCatalog.loadAndSet = function(lang) { + gettextCatalog.loadAndSet = function (lang) { if (lang) { - lang = lang.replace('_', '-'); - gettextCatalog.setCurrentLanguage(lang); + lang = lang.replace('_', '-') + gettextCatalog.setCurrentLanguage(lang) if (lang !== 'en') { - gettextCatalog.loadRemote("gettext/json/manageiq-ui-service.json"); + gettextCatalog.loadRemote('gettext/json/manageiq-ui-service.json') } } - }; + } - $window.N_ = gettext; - $window.__ = gettextCatalog.getString.bind(gettextCatalog); + $window.N_ = gettext + $window.__ = gettextCatalog.getString.bind(gettextCatalog) // 'locale_name' will be translated into locale name in every translation // For example, in german translation it will be 'Deutsch', in slovak 'Slovensky', etc. // The localized locale name will then be presented to the user to select from in the UI. - const localeName = __('locale_name'); + const localeName = __('locale_name') } diff --git a/client/app/core/language-switcher/language-switcher.directive.js b/client/app/core/language-switcher/language-switcher.directive.js index ddaf553fd..7226dd73b 100644 --- a/client/app/core/language-switcher/language-switcher.directive.js +++ b/client/app/core/language-switcher/language-switcher.directive.js @@ -1,51 +1,51 @@ -import "./_language-switcher.sass"; -import templateUrl from "./language-switcher.html"; +import './_language-switcher.sass' +import templateUrl from './language-switcher.html' /** @ngInject */ -export function LanguageSwitcherDirective() { +export function LanguageSwitcherDirective () { return { restrict: 'AE', scope: { - mode: '@?', + mode: '@?' }, templateUrl, controller: LanguageSwitcherController, controllerAs: 'vm', - bindToController: true, - }; + bindToController: true + } /** @ngInject */ - function LanguageSwitcherController(Language, lodash, $state) { - const vm = this; + function LanguageSwitcherController (Language, lodash, $state) { + const vm = this angular.extend(vm, { switchLanguage: switchLanguage, - available: [], - }); + available: [] + }) - vm.mode = vm.mode || 'menu'; + vm.mode = vm.mode || 'menu' const hardcoded = { - _browser_: __("Browser Default"), - }; + _browser_: __('Browser Default') + } Language.ready - .then(function(available) { + .then(function (available) { if (vm.mode !== 'menu') { - hardcoded._user_ = __("User Default"); - Language.chosen = {code: '_user_'}; + hardcoded._user_ = __('User Default') + Language.chosen = {code: '_user_'} } lodash.forEach(lodash.extend({}, hardcoded, available), (value, key) => { - vm.available.push({value: key, label: value}); - }); - vm.chosen = lodash.find(vm.available, {'value': '_user_'}); - }); + vm.available.push({value: key, label: value}) + }) + vm.chosen = lodash.find(vm.available, {'value': '_user_'}) + }) - function switchLanguage(input) { - Language.setLocale(input.value || input); + function switchLanguage (input) { + Language.setLocale(input.value || input) if (!input.value) { - Language.save(input); - $state.reload(); + Language.save(input) + $state.reload() } } } diff --git a/client/app/core/language.service.js b/client/app/core/language.service.js index 083c2bf9f..39ce17f8f 100644 --- a/client/app/core/language.service.js +++ b/client/app/core/language.service.js @@ -1,114 +1,114 @@ /* eslint camelcase: "off" */ /** @ngInject */ -export function LanguageFactory($http, $q, $log, $window, gettextCatalog, lodash) { - var availableAvailable = $q.defer(); +export function LanguageFactory ($http, $q, $log, $window, gettextCatalog, lodash) { + var availableAvailable = $q.defer() var service = { available: { - 'en': 'English', // not translated on purpose + 'en': 'English' // not translated on purpose }, ready: availableAvailable.promise, browser: browser, onLogin: onLogin, onReload: onReload, chosen: { - code: null, + code: null }, save: save, match: match, userHref: null, setLocale: setLocale, - fixState: fixState, - }; + fixState: fixState + } - init(); + init() - return service; + return service - function init() { + function init () { $http.get('gettext/json/available_languages.json') - .then(function(response) { - lodash.extend(service.available, response.data); - availableAvailable.resolve(service.available); - }); + .then(function (response) { + lodash.extend(service.available, response.data) + availableAvailable.resolve(service.available) + }) } // returns a list of user's preferred languages, in order - function browser() { - var ary = []; + function browser () { + var ary = [] // the standard if (lodash.isArray($window.navigator.languages)) { - ary = lodash.slice($window.navigator.languages); + ary = lodash.slice($window.navigator.languages) } // IE 11 and older browers if ($window.navigator.language) { - ary.push($window.navigator.language); + ary.push($window.navigator.language) } // IE<11 if ($window.navigator.userLanguage) { - ary.push($window.navigator.userLanguage); + ary.push($window.navigator.userLanguage) } - return lodash.uniq(ary); + return lodash.uniq(ary) } - function setLocale(code) { + function setLocale (code) { if (!code || (code === '_browser_')) { - code = service.match(service.available, service.browser()); + code = service.match(service.available, service.browser()) } - gettextCatalog.loadAndSet(code); + gettextCatalog.loadAndSet(code) - return code; + return code } - function getLocale(data) { - return data - && data.settings - && data.settings.ui_service - && data.settings.ui_service.display - && data.settings.ui_service.display.locale; + function getLocale (data) { + return data && + data.settings && + data.settings.ui_service && + data.settings.ui_service.display && + data.settings.ui_service.display.locale } - function setUser(data) { - service.userHref = data.identity.user_href.replace(/^.*?\/api\//, '/api/'); + function setUser (data) { + service.userHref = data.identity.user_href.replace(/^.*?\/api\//, '/api/') } - function onLogin(data) { - setUser(data); - var code = 'en'; + function onLogin (data) { + setUser(data) + var code = 'en' if (!service.chosen.code || (service.chosen.code === '_user_')) { - code = getLocale(data); + code = getLocale(data) } else { - code = service.chosen.code; - save(code); + code = service.chosen.code + save(code) } - setLocale(code); + setLocale(code) - return code; + return code } - function onReload(data) { - setUser(data); + function onReload (data) { + setUser(data) - var code = getLocale(data); - setLocale(code); + var code = getLocale(data) + setLocale(code) - return code; + return code } - function save(code) { + function save (code) { if (!service.userHref) { - $log.error('Trying to save language selection without a valid userHref'); + $log.error('Trying to save language selection without a valid userHref') - return; + return } if (code === '_browser_') { - code = null; + code = null } return $http.post(service.userHref, { @@ -117,58 +117,58 @@ export function LanguageFactory($http, $q, $log, $window, gettextCatalog, lodash settings: { ui_service: { display: { - locale: code, - }, - }, - }, - }, - }); + locale: code + } + } + } + } + }) } // returns the best match from available - function match(available, requested) { - var shorten = function(str) { + function match (available, requested) { + var shorten = function (str) { return { orig: str, - short: str.replace(/[-_].*$/, ''), - }; - }; + short: str.replace(/[-_].*$/, '') + } + } var short = { available: lodash.keys(available).map(shorten), - requested: requested.map(shorten), - }; + requested: requested.map(shorten) + } for (var k in short.requested) { - var r = short.requested[k]; + var r = short.requested[k] - var match = lodash.find(short.available, function(a) { + var match = lodash.find(short.available, function (a) { // try exact match first - return a.orig.toLowerCase() === r.orig.toLowerCase(); - }) || lodash.find(short.available, function(a) { + return a.orig.toLowerCase() === r.orig.toLowerCase() + }) || lodash.find(short.available, function (a) { // lowercase, only language code match second - return a.short.toLowerCase() === r.short.toLowerCase(); - }); + return a.short.toLowerCase() === r.short.toLowerCase() + }) if (match) { - return match.orig; + return match.orig } } - return 'en'; + return 'en' } - function fixState(state, toolbarConfig) { - var fields = toolbarConfig.sortConfig.fields; - var current = state.sort.currentField; + function fixState (state, toolbarConfig) { + var fields = toolbarConfig.sortConfig.fields + var current = state.sort.currentField if (!current || !current.id) { - return; + return } - var found = lodash.find(fields, { id: current.id }) || current; + var found = lodash.find(fields, { id: current.id }) || current // can't just replace currentField, the original instance stays inside pf-sort - state.sort.currentField.title = found.title; + state.sort.currentField.title = found.title } } diff --git a/client/app/core/layouts.config.js b/client/app/core/layouts.config.js index e72c4aa08..395ac5924 100644 --- a/client/app/core/layouts.config.js +++ b/client/app/core/layouts.config.js @@ -1,48 +1,48 @@ -import applicationTemplate from '../layouts/application.html'; -import blankTemplate from '../layouts/blank.html'; +import applicationTemplate from '../layouts/application.html' +import blankTemplate from '../layouts/blank.html' /** @ngInject */ -export function layoutInit(routerHelper) { - routerHelper.configureStates(getLayouts()); +export function layoutInit (routerHelper) { + routerHelper.configureStates(getLayouts()) } -function getLayouts() { +function getLayouts () { return { 'blank': { abstract: true, - templateUrl: blankTemplate, + templateUrl: blankTemplate }, 'application': { abstract: true, templateUrl: applicationTemplate, onEnter: enterApplication, - onExit: exitApplication, - }, - }; + onExit: exitApplication + } + } } /** @ngInject */ -function enterApplication(Polling, lodash, NavCounts, Navigation, RBAC) { +function enterApplication (Polling, lodash, NavCounts, Navigation, RBAC) { // Application layout displays the navigation which might have items that require polling to update the counts - const navFeatures = RBAC.getNavFeatures(); - angular.forEach(NavCounts.counts, updateCount); + const navFeatures = RBAC.getNavFeatures() + angular.forEach(NavCounts.counts, updateCount) angular.forEach(Navigation.items, (value, key) => { - navFeatures[key] = lodash.merge(value, navFeatures[key]); - }); - RBAC.setNavFeatures(navFeatures); + navFeatures[key] = lodash.merge(value, navFeatures[key]) + }) + RBAC.setNavFeatures(navFeatures) - function updateCount(count, key) { + function updateCount (count, key) { if (angular.isDefined(navFeatures[key]) && navFeatures[key].show) { - count.func(); + count.func() if (count.interval) { - Polling.start(key, count.func, count.interval); + Polling.start(key, count.func, count.interval) } } } } /** @ngInject */ -function exitApplication(lodash, Polling, NavCounts) { +function exitApplication (lodash, Polling, NavCounts) { // Remove all of the navigation polls - angular.forEach(lodash.keys(NavCounts.counts), Polling.stop); + angular.forEach(lodash.keys(NavCounts.counts), Polling.stop) } diff --git a/client/app/core/list-configuration.service.js b/client/app/core/list-configuration.service.js index 66304bee6..44f886ce3 100644 --- a/client/app/core/list-configuration.service.js +++ b/client/app/core/list-configuration.service.js @@ -1,34 +1,34 @@ /* eslint camelcase: "off" */ /** @ngInject */ -export function ListConfigurationFactory() { - var configuration = {}; +export function ListConfigurationFactory () { + var configuration = {} - configuration.setupListFunctions = function(list, currentField) { + configuration.setupListFunctions = function (list, currentField) { list.sort = { isAscending: true, - currentField: currentField, - }; + currentField: currentField + } - list.filters = []; + list.filters = [] list.setSort = function (currentField, isAscending) { - list.sort.isAscending = isAscending; - list.sort.currentField = currentField; - }; + list.sort.isAscending = isAscending + list.sort.currentField = currentField + } list.getSort = function () { - return list.sort; - }; + return list.sort + } list.setFilters = function (filterArray) { - list.filters = filterArray; - }; + list.filters = filterArray + } list.getFilters = function () { - return list.filters; - }; - }; + return list.filters + } + } - return configuration; + return configuration } diff --git a/client/app/core/list-view.service.js b/client/app/core/list-view.service.js index a33e0def9..7c3767c38 100644 --- a/client/app/core/list-view.service.js +++ b/client/app/core/list-view.service.js @@ -2,62 +2,61 @@ /* eslint no-cond-assign: "off" */ /** @ngInject */ -export function ListViewFactory() { - var listView = {}; +export function ListViewFactory () { + var listView = {} - listView.applyFilters = function(filters, retList, origList, stateFactory, matchesFilter) { - retList = []; + listView.applyFilters = function (filters, retList, origList, stateFactory, matchesFilter) { + retList = [] if (filters && filters.length > 0) { - angular.forEach(origList, filterChecker); + angular.forEach(origList, filterChecker) } else { - retList = origList; + retList = origList } /* Keep track of the current filtering state */ - stateFactory.setFilters(filters); + stateFactory.setFilters(filters) - return retList; + return retList - function filterChecker(item) { + function filterChecker (item) { if (matchesFilters(item, filters)) { - retList.push(item); + retList.push(item) } } - function matchesFilters(item, filters) { - var matches = true; - angular.forEach(filters, filterMatcher); + function matchesFilters (item, filters) { + var matches = true + angular.forEach(filters, filterMatcher) - function filterMatcher(filter) { + function filterMatcher (filter) { if (!matchesFilter(item, filter)) { - matches = false; + matches = false - return false; + return false } } - return matches; + return matches } - }; + } - listView.createFilterField = function(id, title, placeholder, type, values) { + listView.createFilterField = function (id, title, placeholder, type, values) { return { id: id, title: title, placeholder: placeholder, filterType: type, - filterValues: values, - }; - }; + filterValues: values + } + } listView.createSortField = function (id, title, sortType) { return { id: id, title: title, - sortType: sortType, - }; - }; - + sortType: sortType + } + } - return listView; + return listView } diff --git a/client/app/core/modal/base-modal-controller.js b/client/app/core/modal/base-modal-controller.js index db42d0560..4518413ab 100644 --- a/client/app/core/modal/base-modal-controller.js +++ b/client/app/core/modal/base-modal-controller.js @@ -1,35 +1,35 @@ /** @ngInject */ -export function BaseModalController($uibModalInstance, $state, CollectionsApi, EventNotifications) { - var vm = this; - vm.cancel = cancel; - vm.reset = reset; - vm.save = save; +export function BaseModalController ($uibModalInstance, $state, CollectionsApi, EventNotifications) { + var vm = this + vm.cancel = cancel + vm.reset = reset + vm.save = save - function cancel() { - $uibModalInstance.dismiss(); + function cancel () { + $uibModalInstance.dismiss() } - function reset(event) { - angular.copy(event.original, this.modalData); // eslint-disable-line angular/controller-as-vm + function reset (event) { + angular.copy(event.original, this.modalData) // eslint-disable-line angular/controller-as-vm } - function save() { - var vm = this; + function save () { + var vm = this var data = { action: vm.action, - resource: vm.modalData, - }; + resource: vm.modalData + } - CollectionsApi.post(vm.collection, vm.modalData.id, {}, data).then(saveSuccess, saveFailure); + CollectionsApi.post(vm.collection, vm.modalData.id, {}, data).then(saveSuccess, saveFailure) - function saveSuccess() { - $uibModalInstance.close(); - EventNotifications.success(vm.onSuccessMessage); - $state.go($state.current, {}, {reload: true}); + function saveSuccess () { + $uibModalInstance.close() + EventNotifications.success(vm.onSuccessMessage) + $state.go($state.current, {}, {reload: true}) } - function saveFailure() { - EventNotifications.error(vm.onFailureMessage); + function saveFailure () { + EventNotifications.error(vm.onFailureMessage) } } } diff --git a/client/app/core/modal/base-modal.factory.js b/client/app/core/modal/base-modal.factory.js index 63ad3701c..8028f136f 100644 --- a/client/app/core/modal/base-modal.factory.js +++ b/client/app/core/modal/base-modal.factory.js @@ -1,16 +1,16 @@ /** @ngInject */ -export function BaseModalFactory($uibModal) { +export function BaseModalFactory ($uibModal) { return { - open: openModal, - }; + open: openModal + } - function openModal(overrideOptions) { + function openModal (overrideOptions) { var defaultOptions = { - size: 'md', - }; - var modalOptions = angular.merge({}, defaultOptions, overrideOptions); - var modal = $uibModal.open(modalOptions); + size: 'md' + } + var modalOptions = angular.merge({}, defaultOptions, overrideOptions) + var modal = $uibModal.open(modalOptions) - return modal.result; + return modal.result } } diff --git a/client/app/core/navcounts.service.js b/client/app/core/navcounts.service.js index 731e9c81a..879611470 100644 --- a/client/app/core/navcounts.service.js +++ b/client/app/core/navcounts.service.js @@ -1,20 +1,20 @@ /** @ngInject */ -export function NavCountsFactory() { - var counts = {}; +export function NavCountsFactory () { + var counts = {} var service = { add: add, - counts: counts, - }; + counts: counts + } - return service; + return service - function add(key, func, interval) { + function add (key, func, interval) { if (!counts[key]) { counts[key] = { func: func, - interval: interval, - }; + interval: interval + } } } } diff --git a/client/app/core/navigation.config.js b/client/app/core/navigation.config.js index d2611ad5a..c8975e4b7 100644 --- a/client/app/core/navigation.config.js +++ b/client/app/core/navigation.config.js @@ -1,13 +1,13 @@ /* eslint camelcase: "off" */ /** @ngInject */ -export function navConfig(NavigationProvider) { +export function navConfig (NavigationProvider) { const dashboard = createItem({ title: N_('Dashboard'), originalTitle: 'Dashboard', state: 'dashboard', - iconClass: 'fa fa-dashboard', - }); + iconClass: 'fa fa-dashboard' + }) const services = createItem({ title: N_('My Services'), @@ -15,8 +15,8 @@ export function navConfig(NavigationProvider) { state: 'services', iconClass: 'pficon pficon-service', badgeTooltip: N_('Total services ordered, both active and retired'), - originalTooltip: 'Total services ordered, both active and retired', - }); + originalTooltip: 'Total services ordered, both active and retired' + }) const orders = createItem({ title: N_('My Orders'), @@ -24,8 +24,8 @@ export function navConfig(NavigationProvider) { state: 'orders', iconClass: 'fa fa-file-o', badgeTooltip: N_('Total orders submitted'), - originalTooltip: 'Total orders submitted', - }); + originalTooltip: 'Total orders submitted' + }) const catalogs = createItem({ title: N_('Service Catalog'), @@ -33,73 +33,73 @@ export function navConfig(NavigationProvider) { state: 'catalogs', iconClass: 'fa fa-folder-open-o', badgeTooltip: N_('The total number of available catalogs'), - originalTooltip: 'The total number of available catalogs', - }); + originalTooltip: 'The total number of available catalogs' + }) NavigationProvider.configure({ items: { dashboard: dashboard, services: services, orders: orders, - catalogs: catalogs, - }, - }); + catalogs: catalogs + } + }) - function createItem(item) { + function createItem (item) { if (angular.isDefined(item.badgeTooltip)) { item.badges = [ { count: 0, tooltip: item.badgeTooltip, - originalTooltip: item.originalTooltip, - }, - ]; + originalTooltip: item.originalTooltip + } + ] } - return item; + return item } } /** @ngInject */ -export function navInit(lodash, CollectionsApi, Navigation, NavCounts, POLLING_INTERVAL) { - const refreshTimeMs = POLLING_INTERVAL; +export function navInit (lodash, CollectionsApi, Navigation, NavCounts, POLLING_INTERVAL) { + const refreshTimeMs = POLLING_INTERVAL const options = { hide: 'resources', - auto_refresh: true, - }; + auto_refresh: true + } - NavCounts.add('services', fetchServices, refreshTimeMs); - NavCounts.add('orders', fetchOrders, refreshTimeMs); - NavCounts.add('catalogs', fetchServiceCatalogs, refreshTimeMs); + NavCounts.add('services', fetchServices, refreshTimeMs) + NavCounts.add('orders', fetchOrders, refreshTimeMs) + NavCounts.add('catalogs', fetchServiceCatalogs, refreshTimeMs) - function fetchOrders() { + function fetchOrders () { angular.extend(options, { - filter: ['state=ordered'], - }); + filter: ['state=ordered'] + }) CollectionsApi.query('service_orders', options) - .then(lodash.partial(updateCount, 'orders')); + .then(lodash.partial(updateCount, 'orders')) } - function fetchServices() { + function fetchServices () { angular.extend(options, { - filter: ['ancestry=null'], - }); + filter: ['ancestry=null'] + }) CollectionsApi.query('services', options) - .then(lodash.partial(updateCount, 'services')); + .then(lodash.partial(updateCount, 'services')) } - function fetchServiceCatalogs() { + function fetchServiceCatalogs () { angular.extend(options, { - filter: ['display=true'], - }); + filter: ['display=true'] + }) CollectionsApi.query('service_templates', options) - .then(lodash.partial(updateCount, 'catalogs')); + .then(lodash.partial(updateCount, 'catalogs')) } - function updateCount(item, data) { - Navigation.items[item].badges[0].count = data.subcount; + function updateCount (item, data) { + Navigation.items[item].badges[0].count = data.subcount } } diff --git a/client/app/core/navigation.provider.js b/client/app/core/navigation.provider.js index 7039dcd05..28982df5e 100644 --- a/client/app/core/navigation.provider.js +++ b/client/app/core/navigation.provider.js @@ -1,28 +1,28 @@ /** @ngInject */ -export function NavigationProvider() { +export function NavigationProvider () { var provider = { $get: Navigation, - configure: configure, - }; + configure: configure + } var model = { items: { - primary: {}, - }, - }; + primary: {} + } + } - return provider; + return provider - function configure(value) { - angular.extend(model, value); + function configure (value) { + angular.extend(model, value) } /** @ngInject */ - function Navigation() { + function Navigation () { var service = { - items: model.items, - }; + items: model.items + } - return service; + return service } } diff --git a/client/app/core/navigation/navigation-controller.js b/client/app/core/navigation/navigation-controller.js index c2a36b386..4006b4c4d 100644 --- a/client/app/core/navigation/navigation-controller.js +++ b/client/app/core/navigation/navigation-controller.js @@ -1,5 +1,5 @@ /** @ngInject */ -export function NavigationController(Text, +export function NavigationController (Text, Navigation, Session, API_BASE, @@ -9,36 +9,36 @@ export function NavigationController(Text, $state, EventNotifications, ApplianceInfo) { - const vm = this; + const vm = this - const destroy = $scope.$on('shoppingCartUpdated', refresh); - const destroyCart = $scope.$on('shoppingCartUpdated', refreshCart); + const destroy = $scope.$on('shoppingCartUpdated', refresh) + const destroyCart = $scope.$on('shoppingCartUpdated', refreshCart) const destroyNotifications = $scope.$watch( - function() { - return EventNotifications.state().groups; + function () { + return EventNotifications.state().groups }, - refreshNotifications, true); + refreshNotifications, true) const destroyToast = $scope.$watch( - function() { - return EventNotifications.state().toastNotifications; + function () { + return EventNotifications.state().toastNotifications }, - refreshToast, true); - const applianceInfo = ApplianceInfo.get(); + refreshToast, true) + const applianceInfo = ApplianceInfo.get() - $scope.$on('destroy', function() { - destroyCart(); - destroyNotifications(); - destroyToast(); - destroy(); - }); - $scope.$on("$stateChangeSuccess", function() { - clearActiveItems(); - setActiveItems(); - }); + $scope.$on('destroy', function () { + destroyCart() + destroyNotifications() + destroyToast() + destroy() + }) + $scope.$on('$stateChangeSuccess', function () { + clearActiveItems() + setActiveItems() + }) - activate(); + activate() - function activate() { + function activate () { angular.extend(vm, { state: Navigation.state, text: Text.app, @@ -63,213 +63,213 @@ export function NavigationController(Text, markAllRead: markAllRead, shoppingCart: shoppingCart(), about: about(), - sites: sites(), - }); - getNavigationItems(Navigation.items); - refresh(); + sites: sites() + }) + getNavigationItems(Navigation.items) + refresh() if (ShoppingCart.allowed()) { - ShoppingCart.reload(); + ShoppingCart.reload() } - setActiveItems(); + setActiveItems() } - function shoppingCart() { + function shoppingCart () { return { count: 0, - open: function() { + open: function () { return $uibModal.open({ template: '', size: 'lg', - controller: function($uibModalInstance) { - const vm = this; - vm.modalInstance = $uibModalInstance; + controller: function ($uibModalInstance) { + const vm = this + vm.modalInstance = $uibModalInstance }, controllerAs: 'vm', - bindToController: true, + bindToController: true - }).result; + }).result }, - allowed: ShoppingCart.allowed, - }; + allowed: ShoppingCart.allowed + } } - function about() { + function about () { return { isOpen: false, - additionalInfo: "", - imgAlt: __("Product logo"), - imgSrc: "images/login-screen-logo.png", + additionalInfo: '', + imgAlt: __('Product logo'), + imgSrc: 'images/login-screen-logo.png', title: Text.app.name, productInfo: [ {name: __('Version: '), value: applianceInfo.version}, {name: __('Server Name: '), value: applianceInfo.server}, {name: __('User Name: '), value: applianceInfo.user}, - {name: __('User Role: '), value: applianceInfo.role}, + {name: __('User Role: '), value: applianceInfo.role} ], copyright: applianceInfo.copyright, supportWebsiteText: applianceInfo.supportWebsiteText, - supportWebsite: applianceInfo.supportWebsite, - }; + supportWebsite: applianceInfo.supportWebsite + } } - function sites() { + function sites () { return [{ title: __('Administration UI'), tooltip: __('Log into the full administrative UI'), iconClass: 'fa-cogs', - url: API_BASE, - }]; + url: API_BASE + }] } - function clearActiveItems() { - angular.forEach(vm.items, function(item) { - item.isActive = false; + function clearActiveItems () { + angular.forEach(vm.items, function (item) { + item.isActive = false if (item.children) { - angular.forEach(item.children, function(secondary) { - secondary.isActive = false; + angular.forEach(item.children, function (secondary) { + secondary.isActive = false if (secondary.children) { - secondary.children.forEach(function(tertiary) { - tertiary.isActive = false; - }); + secondary.children.forEach(function (tertiary) { + tertiary.isActive = false + }) } - }); + }) } - }); + }) } - function setActiveItems() { - angular.forEach(vm.items, function(topLevel) { + function setActiveItems () { + angular.forEach(vm.items, function (topLevel) { if ($state.includes(topLevel.state)) { - topLevel.isActive = true; + topLevel.isActive = true } if (topLevel.children) { - angular.forEach(topLevel.children, function(secondLevel) { + angular.forEach(topLevel.children, function (secondLevel) { if ($state.includes(secondLevel.state)) { - secondLevel.isActive = true; - topLevel.isActive = true; + secondLevel.isActive = true + topLevel.isActive = true } if (secondLevel.children) { - angular.forEach(secondLevel.children, function(thirdLevel) { + angular.forEach(secondLevel.children, function (thirdLevel) { if ($state.includes(thirdLevel.state)) { - thirdLevel.isActive = true; - secondLevel.isActive = true; - topLevel.isActive = true; + thirdLevel.isActive = true + secondLevel.isActive = true + topLevel.isActive = true } - }); + }) } - }); + }) } - }); + }) } - function getNavigationItems(items) { - vm.items.splice(0, vm.items.length); - angular.forEach(items, function(nextPrimary) { + function getNavigationItems (items) { + vm.items.splice(0, vm.items.length) + angular.forEach(items, function (nextPrimary) { if (nextPrimary.show !== false) { - getTextForNavigationItems(nextPrimary); - vm.items.push(nextPrimary); + getTextForNavigationItems(nextPrimary) + vm.items.push(nextPrimary) if (nextPrimary.children) { - nextPrimary.children.splice(0, nextPrimary.children.length); + nextPrimary.children.splice(0, nextPrimary.children.length) } if (nextPrimary.secondary) { if (angular.isUndefined(nextPrimary.children)) { - nextPrimary.children = []; + nextPrimary.children = [] } - angular.forEach(nextPrimary.secondary, function(nextSecondary) { + angular.forEach(nextPrimary.secondary, function (nextSecondary) { if (nextSecondary.show !== false) { - getTextForNavigationItems(nextSecondary); - nextPrimary.children.push(nextSecondary); + getTextForNavigationItems(nextSecondary) + nextPrimary.children.push(nextSecondary) } - }); + }) } } - }); + }) } - function getTextForNavigationItems(navItem) { + function getTextForNavigationItems (navItem) { if (angular.isDefined(navItem.originalTitle)) { - navItem.title = __(navItem.originalTitle); + navItem.title = __(navItem.originalTitle) } if (angular.isDefined(navItem.badges)) { - angular.forEach(navItem.badges, function(badge) { - badge.tooltip = __(badge.originalTooltip); - }); + angular.forEach(navItem.badges, function (badge) { + badge.tooltip = __(badge.originalTooltip) + }) } } - function refreshCart() { - vm.shoppingCart.count = ShoppingCart.count(); + function refreshCart () { + vm.shoppingCart.count = ShoppingCart.count() } - function refreshNotifications() { - vm.notificationGroups = EventNotifications.state().groups; - vm.newNotifications = EventNotifications.state().unreadNotifications; - vm.unreadNotificationCount = 0; - angular.forEach(vm.notificationGroups, function(group) { - vm.unreadNotificationCount += group.unreadCount; - }); - vm.notificationsIndicatorTooltip = __(vm.unreadNotificationCount + " unread notifications"); + function refreshNotifications () { + vm.notificationGroups = EventNotifications.state().groups + vm.newNotifications = EventNotifications.state().unreadNotifications + vm.unreadNotificationCount = 0 + angular.forEach(vm.notificationGroups, function (group) { + vm.unreadNotificationCount += group.unreadCount + }) + vm.notificationsIndicatorTooltip = __(vm.unreadNotificationCount + ' unread notifications') } - function refreshToast() { - vm.toastNotifications = EventNotifications.state().toastNotifications; + function refreshToast () { + vm.toastNotifications = EventNotifications.state().toastNotifications } - function refresh() { - refreshCart(); - refreshNotifications(); - refreshToast(); + function refresh () { + refreshCart() + refreshNotifications() + refreshToast() } - function handleItemClick(item) { - $state.transitionTo(item.state); + function handleItemClick (item) { + $state.transitionTo(item.state) } - function toggleNotificationsList() { - vm.notificationsDrawerShown = !vm.notificationsDrawerShown; + function toggleNotificationsList () { + vm.notificationsDrawerShown = !vm.notificationsDrawerShown } - function getNotficationStatusIconClass(notification) { - var retClass = ''; + function getNotficationStatusIconClass (notification) { + var retClass = '' if (notification && notification.type) { if (notification.type === 'info') { - retClass = "pficon pficon-info"; + retClass = 'pficon pficon-info' } else if (notification.type === 'error') { - retClass = "pficon pficon-error-circle-o"; + retClass = 'pficon pficon-error-circle-o' } else if (notification.type === 'warning') { - retClass = "pficon pficon-warning-triangle-o"; + retClass = 'pficon pficon-warning-triangle-o' } else if (notification.type === 'success') { - retClass = "pficon pficon-ok"; + retClass = 'pficon pficon-ok' } else { - retClass = "pficon pficon-info"; // default to info + retClass = 'pficon pficon-info' // default to info } } - return retClass; + return retClass } - function markNotificationRead(notification, group) { - EventNotifications.markRead(notification, group); + function markNotificationRead (notification, group) { + EventNotifications.markRead(notification, group) } - function clearNotification(notification, group) { - EventNotifications.clear(notification, group); + function clearNotification (notification, group) { + EventNotifications.clear(notification, group) } - function clearAllNotifications(group) { - EventNotifications.clearAll(group); + function clearAllNotifications (group) { + EventNotifications.clearAll(group) } - function markAllRead(group) { - EventNotifications.markAllRead(group); + function markAllRead (group) { + EventNotifications.markAllRead(group) } - function updateViewingToast(viewing, notification) { - EventNotifications.setViewingToast(notification, viewing); + function updateViewingToast (viewing, notification) { + EventNotifications.setViewingToast(notification, viewing) } - function handleDismissToast(notification) { - EventNotifications.dismissToast(notification); + function handleDismissToast (notification) { + EventNotifications.dismissToast(notification) } } diff --git a/client/app/core/polling.service.js b/client/app/core/polling.service.js index f84b32ae6..988c10a34 100644 --- a/client/app/core/polling.service.js +++ b/client/app/core/polling.service.js @@ -1,39 +1,39 @@ /** @ngInject */ -export function PollingFactory($interval, $sessionStorage, lodash) { +export function PollingFactory ($interval, $sessionStorage, lodash) { var service = { start: start, stop: stop, stopAll: stopAll, - getPolls: getPolls, - }; + getPolls: getPolls + } + + var polls = {} - var polls = {}; + return service - return service; - - function getPolls() { - return polls; + function getPolls () { + return polls } - - function start(key, func, interval, limit) { - var poll; + + function start (key, func, interval, limit) { + var poll if (angular.isDefined($sessionStorage.pause)) { - interval = $sessionStorage.pause; + interval = $sessionStorage.pause } if (!polls[key]) { - poll = $interval(func, interval, limit); - polls[key] = poll; + poll = $interval(func, interval, limit) + polls[key] = poll } } - function stop(key) { + function stop (key) { if (polls[key]) { - $interval.cancel(polls[key]); - delete polls[key]; + $interval.cancel(polls[key]) + delete polls[key] } } - function stopAll() { - angular.forEach(lodash.keys(polls), stop); + function stopAll () { + angular.forEach(lodash.keys(polls), stop) } } diff --git a/client/app/core/product-info.service.js b/client/app/core/product-info.service.js index e9fb636ad..9029d20bf 100644 --- a/client/app/core/product-info.service.js +++ b/client/app/core/product-info.service.js @@ -1,19 +1,19 @@ /** @ngInject */ -export function ProductInfo($q) { - var factory = {}; - factory.data = {}; - factory.promise = $q(function(resolve) { - factory.set = function(data) { +export function ProductInfo ($q) { + var factory = {} + factory.data = {} + factory.promise = $q(function (resolve) { + factory.set = function (data) { factory.data = { copyright: data.product_info.copyright, supportWebsiteText: data.product_info.support_website_text, - supportWebsite: data.product_info.support_website, - }; - resolve(factory.data); + supportWebsite: data.product_info.support_website + } + resolve(factory.data) - return data; - }; - }); + return data + } + }) - return factory; + return factory } diff --git a/client/app/core/rbac.service.js b/client/app/core/rbac.service.js index 9deb4dded..411993d6c 100644 --- a/client/app/core/rbac.service.js +++ b/client/app/core/rbac.service.js @@ -1,8 +1,8 @@ /** @ngInject */ -export function RBACFactory(lodash) { - var navFeatures = {}; - let features = {}; - let currentRole; +export function RBACFactory (lodash) { + var navFeatures = {} + let features = {} + let currentRole return { all: all, @@ -13,49 +13,49 @@ export function RBACFactory(lodash) { setRole: setRole, getNavFeatures: getNavFeatures, setNavFeatures: setNavFeatures, - navigationEnabled: navigationEnabled, - }; + navigationEnabled: navigationEnabled + } - function set(productFeatures) { - features = productFeatures || {}; + function set (productFeatures) { + features = productFeatures || {} const navPermissions = { services: {show: angular.isDefined(productFeatures.service_view)}, orders: {show: angular.isDefined(productFeatures.svc_catalog_provision)}, - catalogs: {show: angular.isDefined(productFeatures.catalog_items_view)}, - }; - setNavFeatures(navPermissions); + catalogs: {show: angular.isDefined(productFeatures.catalog_items_view)} + } + setNavFeatures(navPermissions) } - function has(feature) { - return feature in features; + function has (feature) { + return feature in features } - function hasAny(permissions) { - return permissions.some((feature) => angular.isDefined(features[feature])); + function hasAny (permissions) { + return permissions.some((feature) => angular.isDefined(features[feature])) } - function hasRole(...roles) { - return roles.some((role) => role === currentRole || role === '_ALL_'); + function hasRole (...roles) { + return roles.some((role) => role === currentRole || role === '_ALL_') } - function all() { - return features; + function all () { + return features } - function setNavFeatures(features) { - navFeatures = features; + function setNavFeatures (features) { + navFeatures = features } - function setRole(newRole) { - currentRole = newRole; + function setRole (newRole) { + currentRole = newRole } - function getNavFeatures() { - return navFeatures; + function getNavFeatures () { + return navFeatures } - function navigationEnabled() { - return lodash.some(navFeatures, (item) => item.show); + function navigationEnabled () { + return lodash.some(navFeatures, (item) => item.show) } } diff --git a/client/app/core/router/router-helper.provider.js b/client/app/core/router/router-helper.provider.js index 54f219a67..46632204d 100644 --- a/client/app/core/router/router-helper.provider.js +++ b/client/app/core/router/router-helper.provider.js @@ -1,115 +1,115 @@ /* Help configure the state-base ui.router */ /** @ngInject */ -export function routerHelperProvider($locationProvider, $stateProvider, $urlRouterProvider, $injector) { +export function routerHelperProvider ($locationProvider, $stateProvider, $urlRouterProvider, $injector) { var config = { docTitle: undefined, - resolveAlways: {}, - }; + resolveAlways: {} + } var provider = { configure: configure, - $get: RouterHelper, - }; + $get: RouterHelper + } - $locationProvider.html5Mode(true); + $locationProvider.html5Mode(true) - return provider; + return provider - function configure(cfg) { - angular.extend(config, cfg); + function configure (cfg) { + angular.extend(config, cfg) } /** @ngInject */ - function RouterHelper($location, $rootScope, $state, $log) { - var handlingStateChangeError = false; - var hasOtherwise = false; + function RouterHelper ($location, $rootScope, $state, $log) { + var handlingStateChangeError = false + var hasOtherwise = false var stateCounts = { errors: 0, - changes: 0, - }; + changes: 0 + } var service = { configureStates: configureStates, getStates: getStates, - stateCounts: stateCounts, - }; + stateCounts: stateCounts + } - init(); + init() - return service; + return service - function configureStates(states, otherwisePath) { - angular.forEach(states, buildState); + function configureStates (states, otherwisePath) { + angular.forEach(states, buildState) if (otherwisePath && !hasOtherwise) { - hasOtherwise = true; - $urlRouterProvider.otherwise(otherwisePath); + hasOtherwise = true + $urlRouterProvider.otherwise(otherwisePath) } - function buildState(stateConfig, state) { - stateConfig.resolve = angular.extend(stateConfig.resolve || {}, config.resolveAlways); - $stateProvider.state(state, stateConfig); + function buildState (stateConfig, state) { + stateConfig.resolve = angular.extend(stateConfig.resolve || {}, config.resolveAlways) + $stateProvider.state(state, stateConfig) } } - function init() { + function init () { // Route cancellation: // On routing error, go to the dashboard. // Provide an exit clause if it tries to do it twice. - $rootScope.$on('$stateChangeError', handleRoutingErrors); - $rootScope.$on('$stateChangeSuccess', updateTitle); + $rootScope.$on('$stateChangeError', handleRoutingErrors) + $rootScope.$on('$stateChangeSuccess', updateTitle) // Hack in redirect to default children // Discussions: https://github.com/angular-ui/ui-router/issues/1235 // https://github.com/angular-ui/ui-router/issues/27 - $rootScope.$on('$stateChangeStart', redirectTo); + $rootScope.$on('$stateChangeStart', redirectTo) } - function getStates() { - return $state.get(); + function getStates () { + return $state.get() } // Private - function handleRoutingErrors(_event, toState, _toParams, _fromState, _fromParams, error) { - var destination, msg; + function handleRoutingErrors (_event, toState, _toParams, _fromState, _fromParams, error) { + var destination, msg if (handlingStateChangeError) { - return; + return } - stateCounts.errors++; - handlingStateChangeError = true; - destination = (toState && (toState.title ? __(toState.title) : (toState.name || toState.loadedTemplateUrl))) || 'unknown target'; - msg = 'Error routing to ' + destination + '. ' - + (error.data || '') + '.
' + (error.statusText || '') - + ': ' + (error.status || ''); - $log.warn(msg, [toState, error]); - $location.path('/'); + stateCounts.errors++ + handlingStateChangeError = true + destination = (toState && (toState.title ? __(toState.title) : (toState.name || toState.loadedTemplateUrl))) || 'unknown target' + msg = 'Error routing to ' + destination + '. ' + + (error.data || '') + '.
' + (error.statusText || '') + + ': ' + (error.status || '') + $log.warn(msg, [toState, error]) + $location.path('/') } - function updateTitle(_event, toState) { - stateCounts.changes++; - handlingStateChangeError = false; - $rootScope.title = config.docTitle + ' ' + (toState.title ? __(toState.title) : ''); // data bind to + function updateTitle (_event, toState) { + stateCounts.changes++ + handlingStateChangeError = false + $rootScope.title = config.docTitle + ' ' + (toState.title ? __(toState.title) : '') // data bind to <title> } - function redirectTo(event, toState, toParams) { - var redirect = toState.redirectTo; - var newState; + function redirectTo (event, toState, toParams) { + var redirect = toState.redirectTo + var newState if (redirect) { if (angular.isString(redirect)) { - event.preventDefault(); - $state.go(redirect, toParams); + event.preventDefault() + $state.go(redirect, toParams) } else { - newState = $injector.invoke(redirect, null, {toState: toState, toParams: toParams}); + newState = $injector.invoke(redirect, null, {toState: toState, toParams: toParams}) if (newState) { if (angular.isString(newState)) { - event.preventDefault(); - $state.go(newState); + event.preventDefault() + $state.go(newState) } else if (newState.state) { - event.preventDefault(); - $state.go(newState.state, newState.params); + event.preventDefault() + $state.go(newState.state, newState.params) } } } diff --git a/client/app/core/router/router.module.js b/client/app/core/router/router.module.js index 14f97960a..b37fa0101 100644 --- a/client/app/core/router/router.module.js +++ b/client/app/core/router/router.module.js @@ -1,6 +1,6 @@ -import { routerHelperProvider } from './router-helper.provider.js'; +import { routerHelperProvider } from './router-helper.provider.js' export const RouterModule = angular .module('app.core.router', []) .provider('routerHelper', routerHelperProvider) - .name; + .name diff --git a/client/app/core/save-modal-dialog/save-modal-dialog.factory.js b/client/app/core/save-modal-dialog/save-modal-dialog.factory.js index f26225185..be3cb7c94 100644 --- a/client/app/core/save-modal-dialog/save-modal-dialog.factory.js +++ b/client/app/core/save-modal-dialog/save-modal-dialog.factory.js @@ -1,14 +1,14 @@ -import templateUrl from "./save-modal-dialog.html"; +import templateUrl from './save-modal-dialog.html' /** @ngInject */ -export function SaveModalDialogFactory($uibModal) { +export function SaveModalDialogFactory ($uibModal) { var modalSaveDialog = { - showModal: showModal, - }; + showModal: showModal + } - return modalSaveDialog; + return modalSaveDialog - function showModal(saveCallback, cancelCallback, okToSave) { + function showModal (saveCallback, cancelCallback, okToSave) { var modalOptions = { templateUrl, controller: SaveModalDialogController, @@ -16,42 +16,42 @@ export function SaveModalDialogFactory($uibModal) { resolve: { saveCallback: resolveSave, cancelCallback: resolveCancel, - okToSave: resolveOkToSave, - }, - }; + okToSave: resolveOkToSave + } + } - function resolveSave() { - return saveCallback; + function resolveSave () { + return saveCallback } - function resolveCancel() { - return cancelCallback; + function resolveCancel () { + return cancelCallback } - function resolveOkToSave() { - return okToSave; + function resolveOkToSave () { + return okToSave } - var modal = $uibModal.open(modalOptions); + var modal = $uibModal.open(modalOptions) - return modal.result; + return modal.result } } /** @ngInject */ -function SaveModalDialogController(saveCallback, cancelCallback, okToSave, $uibModalInstance) { - var vm = this; - vm.save = save; - vm.cancel = cancel; - vm.okToSave = okToSave; - - function save() { - saveCallback(); - $uibModalInstance.close(); +function SaveModalDialogController (saveCallback, cancelCallback, okToSave, $uibModalInstance) { + var vm = this + vm.save = save + vm.cancel = cancel + vm.okToSave = okToSave + + function save () { + saveCallback() + $uibModalInstance.close() } - function cancel() { - cancelCallback(); - $uibModalInstance.close(); + function cancel () { + cancelCallback() + $uibModalInstance.close() } } diff --git a/client/app/core/server-info.service.js b/client/app/core/server-info.service.js index 22904b78f..c35fb70ff 100644 --- a/client/app/core/server-info.service.js +++ b/client/app/core/server-info.service.js @@ -1,21 +1,21 @@ /** @ngInject */ -export function ServerInfo($q) { - var factory = {}; - factory.data = {}; - factory.promise = $q(function(resolve) { - factory.set = function(data) { +export function ServerInfo ($q) { + var factory = {} + factory.data = {} + factory.promise = $q(function (resolve) { + factory.set = function (data) { factory.data = { user: data.identity.name, role: data.identity.role, version: data.server_info.version + '.' + data.server_info.build, server: data.server_info.appliance, - asyncNotify: data.settings.asynchronous_notifications, - }; - resolve(factory.data); + asyncNotify: data.settings.asynchronous_notifications + } + resolve(factory.data) - return data; - }; - }); + return data + } + }) - return factory; + return factory } diff --git a/client/app/core/session.service.js b/client/app/core/session.service.js index b61e7801c..2650fd3bf 100644 --- a/client/app/core/session.service.js +++ b/client/app/core/session.service.js @@ -1,10 +1,10 @@ /* eslint-disable dot-notation */ /** @ngInject */ -export function SessionFactory($http, $q, $sessionStorage, $window, $state, $cookies, RBAC, Polling) { +export function SessionFactory ($http, $q, $sessionStorage, $window, $state, $cookies, RBAC, Polling) { var model = { token: null, - user: {}, - }; + user: {} + } var service = { current: model, @@ -17,112 +17,112 @@ export function SessionFactory($http, $q, $sessionStorage, $window, $state, $coo requestWsToken: requestWsToken, destroyWsToken: destroyWsToken, switchGroup: switchGroup, - setPause: setPause, - }; + setPause: setPause + } - destroy(); + destroy() - return service; + return service - function setAuthToken(token) { - model.token = token; - $http.defaults.headers.common['X-Auth-Token'] = model.token; - $sessionStorage.token = model.token; + function setAuthToken (token) { + model.token = token + $http.defaults.headers.common['X-Auth-Token'] = model.token + $sessionStorage.token = model.token } - function setMiqGroup(group) { - $http.defaults.headers.common['Accept'] = 'application/json;charset=UTF-8'; - $http.defaults.headers.common['X-Miq-Group'] = unescape(encodeURIComponent(group)); - $sessionStorage.miqGroup = group || null; - $sessionStorage.selectedMiqGroup = group; + function setMiqGroup (group) { + $http.defaults.headers.common['Accept'] = 'application/json;charset=UTF-8' + $http.defaults.headers.common['X-Miq-Group'] = unescape(encodeURIComponent(group)) + $sessionStorage.miqGroup = group || null + $sessionStorage.selectedMiqGroup = group } - - function setPause(pauseLength) { - $sessionStorage.pause = pauseLength * 1000; - return $sessionStorage.pause; + function setPause (pauseLength) { + $sessionStorage.pause = pauseLength * 1000 + + return $sessionStorage.pause } - function destroy() { - model.token = null; - model.user = {}; - destroyWsToken(); - delete $http.defaults.headers.common['X-Auth-Token']; - delete $http.defaults.headers.common['X-Miq-Group']; - delete $sessionStorage.miqGroup; - delete $sessionStorage.selectedMiqGroup; - delete $sessionStorage.token; - delete $sessionStorage.user; + function destroy () { + model.token = null + model.user = {} + destroyWsToken() + delete $http.defaults.headers.common['X-Auth-Token'] + delete $http.defaults.headers.common['X-Miq-Group'] + delete $sessionStorage.miqGroup + delete $sessionStorage.selectedMiqGroup + delete $sessionStorage.token + delete $sessionStorage.user } - function loadUser() { - Polling.start('UserPolling', getUserAuthorizations, 300000); - var deferred = $q.defer(); + function loadUser () { + Polling.start('UserPolling', getUserAuthorizations, 300000) + var deferred = $q.defer() if (angular.isUndefined($sessionStorage.user)) { getUserAuthorizations().then(function (response) { - deferred.resolve(response); - }); + deferred.resolve(response) + }) } else { - var response = angular.fromJson($sessionStorage.user); - currentUser(response.identity); - const miqGroup = (angular.isUndefined($sessionStorage.selectedMiqGroup) ? response.identity.group : $sessionStorage.selectedMiqGroup ); - setMiqGroup(miqGroup); - RBAC.set(response.authorization.product_features); - deferred.resolve(response); + var response = angular.fromJson($sessionStorage.user) + currentUser(response.identity) + const miqGroup = (angular.isUndefined($sessionStorage.selectedMiqGroup) ? response.identity.group : $sessionStorage.selectedMiqGroup) + setMiqGroup(miqGroup) + RBAC.set(response.authorization.product_features) + deferred.resolve(response) } - return deferred.promise; + return deferred.promise } - function getUserAuthorizations() { + function getUserAuthorizations () { const config = { headers: { - 'X-Auth-Skip-Token-Renewal': 'true', - }, - }; + 'X-Auth-Skip-Token-Renewal': 'true' + } + } return $http.get('/api?attributes=authorization', config) .then(function (response) { - $sessionStorage.user = angular.toJson(response.data); - currentUser(response.data.identity); - setMiqGroup(response.data.identity.group); - RBAC.set(response.data.authorization.product_features); + $sessionStorage.user = angular.toJson(response.data) + currentUser(response.data.identity) + setMiqGroup(response.data.identity.group) + RBAC.set(response.data.authorization.product_features) - return response.data; - }); + return response.data + }) } - function requestWsToken(arg) { + function requestWsToken (arg) { return $http.get('/api/auth?requester_type=ws') - .then(function(response) { - destroyWsToken(); - $cookies.put('ws_token', response.data.auth_token, { path: '/ws/notifications' }); + .then(function (response) { + destroyWsToken() + $cookies.put('ws_token', response.data.auth_token, { path: '/ws/notifications' }) - return arg; - }); + return arg + }) } - function destroyWsToken() { - $cookies.remove('ws_token', { path: '/ws/notifications' }); + function destroyWsToken () { + $cookies.remove('ws_token', { path: '/ws/notifications' }) } - function currentUser(user) { + function currentUser (user) { if (angular.isDefined(user)) { - model.user = user; + model.user = user } - return model.user; + return model.user } - function switchGroup(group) { - $sessionStorage.miqGroup = group; - setMiqGroup(group); + function switchGroup (group) { + $sessionStorage.miqGroup = group + setMiqGroup(group) // reload .. but on dashboard - $window.location.href = $state.href('dashboard'); + $window.location.href = $state.href('dashboard') } // Helpers - function active() { + function active () { // may not be current, but if we have one, we'll rely on API 401ing if it's not - return angular.isString(model.token) ? model.token : false; + return angular.isString(model.token) ? model.token : false } } diff --git a/client/app/core/shopping-cart.service.js b/client/app/core/shopping-cart.service.js index 3598d7b64..5bb611c0c 100644 --- a/client/app/core/shopping-cart.service.js +++ b/client/app/core/shopping-cart.service.js @@ -1,6 +1,6 @@ /** @ngInject */ -export function ShoppingCartFactory($rootScope, CollectionsApi, $q, lodash, RBAC) { - var state = null; +export function ShoppingCartFactory ($rootScope, CollectionsApi, $q, lodash, RBAC) { + var state = null var service = { add: add, @@ -10,240 +10,240 @@ export function ShoppingCartFactory($rootScope, CollectionsApi, $q, lodash, RBAC count: count, removeItem: removeItem, submit: submit, - state: function() { - return state; + state: function () { + return state }, allowed: allowed, - isDuplicate: isDuplicate, - }; + isDuplicate: isDuplicate + } var persistence = { // an array of items already in the basket - getItems: function() { + getItems: function () { return CollectionsApi.query('service_orders/cart/service_requests', { - expand: 'resources', + expand: 'resources' }) - .catch(function(err) { + .catch(function (err) { // 404 means cart doesn't exist yet, we can simply create it if (err.status !== 404) { - return $q.reject(err); + return $q.reject(err) } - return CollectionsApi.post('service_orders', null, {}, { state: "cart" }) - .then(function() { + return CollectionsApi.post('service_orders', null, {}, { state: 'cart' }) + .then(function () { // we just care it's been successfully created - return {}; - }); + return {} + }) + }) + .then(function (response) { + return response.resources || [] }) - .then(function(response) { - return response.resources || []; - }); }, // order the cart - orderCart: function() { + orderCart: function () { return CollectionsApi.post('service_orders', 'cart', null, { - action: 'order', - }); + action: 'order' + }) }, // clear the cart - clearCart: function() { + clearCart: function () { return CollectionsApi.post('service_orders', 'cart', null, { - action: 'clear', - }); + action: 'clear' + }) }, // add a thingy to the cart - addItem: function(request) { + addItem: function (request) { return CollectionsApi.post('service_orders/cart/service_requests', null, null, { - action: "add", - resources: [ request ], + action: 'add', + resources: [ request ] }) - .then(function(response) { + .then(function (response) { // handle failure if (response.results[0].success === false) { - return $q.reject(response.results[0].message); + return $q.reject(response.results[0].message) } - return response.results[0]; - }); + return response.results[0] + }) }, // remove a thingy from the cart - removeItem: function(requestId) { + removeItem: function (requestId) { return new Promise((resolve, reject) => { CollectionsApi.post('service_orders/cart/service_requests', null, null, { - action: "remove", - resources: [ { id: requestId } ], + action: 'remove', + resources: [ { id: requestId } ] }) - .then(function(response) { + .then(function (response) { // handle failure if (response.results[0].success === false) { - reject(response.results[0].message); + reject(response.results[0].message) } - resolve(response.results[0]); - }); - }); - }, - }; + resolve(response.results[0]) + }) + }) + } + } - doReset(); + doReset() - return service; + return service - function add(item) { + function add (item) { return persistence.addItem(item.data) - .then(function(response) { + .then(function (response) { var newItem = { id: response.service_request_id, description: item.description, // for duplicate detection - data: clientToCommon(item.data), - }; + data: clientToCommon(item.data) + } - state.items.push(newItem); + state.items.push(newItem) - dedup(); - notify(); + dedup() + notify() - return newItem; - }); + return newItem + }) } - function deleteCart() { - persistence.getItems(); - - return CollectionsApi.delete('service_orders', 'cart', null); + function deleteCart () { + persistence.getItems() + + return CollectionsApi.delete('service_orders', 'cart', null) } - function reload() { + function reload () { return persistence.getItems() - .then(function(items) { + .then(function (items) { state = { - items: items.map(function(o) { + items: items.map(function (o) { return { id: o.id, description: o.description, - data: apiToCommon(o.options), - }; - }), - }; + data: apiToCommon(o.options) + } + }) + } - dedup(); - notify(); - }); + dedup() + notify() + }) } - function doReset() { + function doReset () { state = { - items: [], - }; + items: [] + } } - function reset() { + function reset () { return persistence.clearCart() - .then(reload); + .then(reload) } - function removeItem(item) { + function removeItem (item) { return persistence.removeItem(item.id) - .then(function() { - state.items = lodash.filter(state.items, function(i) { - return i.id !== item.id; - }); + .then(function () { + state.items = lodash.filter(state.items, function (i) { + return i.id !== item.id + }) - dedup(); - notify(); - }); + dedup() + notify() + }) } - function submit() { + function submit () { return persistence.orderCart() - .then(reload); + .then(reload) } - function count() { - return state.items.length; + function count () { + return state.items.length } - function notify() { - $rootScope.$broadcast('shoppingCartUpdated'); + function notify () { + $rootScope.$broadcast('shoppingCartUpdated') } - function allowed() { - return RBAC.has('svc_catalog_provision'); + function allowed () { + return RBAC.has('svc_catalog_provision') } - function dedup() { - var potential = []; + function dedup () { + var potential = [] - state.items.forEach(function(item) { + state.items.forEach(function (item) { if (!item.data) { - return; + return } - item.duplicate = []; - potential.push(item); - }); + item.duplicate = [] + potential.push(item) + }) for (var i = 0; i < potential.length - 1; i++) { for (var j = i + 1; j < potential.length; j++) { - var a = potential[i]; - var b = potential[j]; + var a = potential[i] + var b = potential[j] if (angular.equals(a.data, b.data)) { - a.duplicate.push(b.id); - b.duplicate.push(a.id); + a.duplicate.push(b.id) + b.duplicate.push(a.id) } } } - potential.forEach(function(item) { + potential.forEach(function (item) { if (item.duplicate && !item.duplicate.length) { - delete item.duplicate; + delete item.duplicate } - }); + }) } - function isDuplicate(item) { - var data = clientToCommon(item); + function isDuplicate (item) { + var data = clientToCommon(item) for (var i in state.items) { if (!state.items[i].data) { - continue; + continue } if (angular.equals(data, state.items[i].data)) { - return true; + return true } } - return false; + return false } // convert options value from the API to the format used when sending - for deduplication across reloads - function apiToCommon(options) { - var data = { "service_template_href": "/api/service_templates/" + options.src_id }; + function apiToCommon (options) { + var data = { 'service_template_href': '/api/service_templates/' + options.src_id } - lodash.each(options.dialog, function(value, key) { - data[ key.replace(/^dialog_/, '') ] = value; - }); + lodash.each(options.dialog, function (value, key) { + data[ key.replace(/^dialog_/, '') ] = value + }) - return data; + return data } // remove falsy fields from data, to achieve compatibility with data received back from the API - function clientToCommon(data) { - data = angular.copy(data); + function clientToCommon (data) { + data = angular.copy(data) - lodash.each(data, function(value, key) { + lodash.each(data, function (value, key) { if (!value) { - delete data[key]; + delete data[key] } - }); + }) - return data; + return data } } diff --git a/client/app/core/shopping-cart/shopping-cart.component.js b/client/app/core/shopping-cart/shopping-cart.component.js index 23f7ce9df..30dbf9a58 100644 --- a/client/app/core/shopping-cart/shopping-cart.component.js +++ b/client/app/core/shopping-cart/shopping-cart.component.js @@ -1,57 +1,57 @@ -import './_shopping-cart.sass'; -import templateUrl from './shopping-cart.html'; +import './_shopping-cart.sass' +import templateUrl from './shopping-cart.html' export const ShoppingCartComponent = { controller: ComponentController, controllerAs: 'vm', bindings: { - modalInstance: '<?', + modalInstance: '<?' }, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController($state, ShoppingCart, EventNotifications) { - var vm = this; +function ComponentController ($state, ShoppingCart, EventNotifications) { + var vm = this - vm.$doCheck = refresh; + vm.$doCheck = refresh - vm.submit = submit; - vm.close = close; - vm.clear = ShoppingCart.reset; - vm.remove = ShoppingCart.removeItem; - vm.state = null; + vm.submit = submit + vm.close = close + vm.clear = ShoppingCart.reset + vm.remove = ShoppingCart.removeItem + vm.state = null /** * Refreshes shopping cart state * @function refresh */ - function refresh() { - vm.state = ShoppingCart.state(); + function refresh () { + vm.state = ShoppingCart.state() } /** * Submits a shopping cart * @function submit - * @returns Promise + * @returns Promise */ - function submit() { + function submit () { return ShoppingCart.submit() - .then(function() { - EventNotifications.success(__('Shopping cart successfully ordered')); - vm.modalInstance.dismiss(); - $state.go('orders'); + .then(function () { + EventNotifications.success(__('Shopping cart successfully ordered')) + vm.modalInstance.dismiss() + $state.go('orders') + }) + .then(null, function (err) { + EventNotifications.error(__('There was an error submitting this request: ') + err) }) - .then(null, function(err) { - EventNotifications.error(__('There was an error submitting this request: ') + err); - }); } /** * closes a shopping cart modal * @function close */ - function close() { - vm.modalInstance.dismiss(); + function close () { + vm.modalInstance.dismiss() } } diff --git a/client/app/core/tag-editor-modal/tag-editor-modal.service.js b/client/app/core/tag-editor-modal/tag-editor-modal.service.js index 198a1d034..64c9a39f8 100644 --- a/client/app/core/tag-editor-modal/tag-editor-modal.service.js +++ b/client/app/core/tag-editor-modal/tag-editor-modal.service.js @@ -1,14 +1,14 @@ -import templateUrl from './tag-editor-modal.html'; +import templateUrl from './tag-editor-modal.html' /** @ngInject */ -export function TagEditorFactory($uibModal) { +export function TagEditorFactory ($uibModal) { var modalService = { - showModal: showModal, - }; + showModal: showModal + } - return modalService; + return modalService - function showModal(services, tags) { + function showModal (services, tags) { var modalOptions = { templateUrl, controller: TagEditorModalController, @@ -16,50 +16,50 @@ export function TagEditorFactory($uibModal) { size: 'md', resolve: { services: resolveServices, - tags: resolveTags, - }, - }; - var modal = $uibModal.open(modalOptions); + tags: resolveTags + } + } + var modal = $uibModal.open(modalOptions) - return modal.result; + return modal.result - function resolveServices() { - return services; + function resolveServices () { + return services } - function resolveTags() { - return tags; + function resolveTags () { + return tags } } } /** @ngInject */ -function TagEditorModalController(services, tags, $controller, $uibModalInstance, +function TagEditorModalController (services, tags, $controller, $uibModalInstance, $state, TaggingService, EventNotifications) { - var vm = this; + var vm = this var base = $controller('BaseModalController', { - $uibModalInstance: $uibModalInstance, - }); - angular.extend(vm, base); + $uibModalInstance: $uibModalInstance + }) + angular.extend(vm, base) - vm.save = save; - vm.services = angular.isArray(services) ? services : [services]; - vm.modalData = { tags: angular.copy(tags) }; + vm.save = save + vm.services = angular.isArray(services) ? services : [services] + vm.modalData = { tags: angular.copy(tags) } // Override - function save() { + function save () { return TaggingService.assignTags('services', vm.services, tags, vm.modalData.tags) .then(saveSuccess) - .catch(saveFailure); + .catch(saveFailure) - function saveSuccess() { - $uibModalInstance.close(); - EventNotifications.success(__('Tagging successful.')); - $state.go($state.current, {}, {reload: true}); + function saveSuccess () { + $uibModalInstance.close() + EventNotifications.success(__('Tagging successful.')) + $state.go($state.current, {}, {reload: true}) } - function saveFailure() { - EventNotifications.error(__('There was an error tagging this service.')); + function saveFailure () { + EventNotifications.error(__('There was an error tagging this service.')) } } } diff --git a/client/app/core/tagging.service.js b/client/app/core/tagging.service.js index 23b995588..4e9898603 100644 --- a/client/app/core/tagging.service.js +++ b/client/app/core/tagging.service.js @@ -1,97 +1,97 @@ /** @ngInject */ -export function TaggingService(CollectionsApi, lodash, exception) { +export function TaggingService (CollectionsApi, lodash, exception) { var service = { assignTags: assignTags, findSharedTags: findSharedTags, parseTag: parseTag, - queryAvailableTags: queryAvailableTags, - }; + queryAvailableTags: queryAvailableTags + } - return service; + return service // High-level method to declaratively assign tags to resource(s). Current // tagging APIs require separate requests for assignment of new tags and // unassignment of existing tags. - function assignTags(collection, selectedResources, originalTags, tagsToAssign) { - const tagObjectsToAssign = tagsToAssign.map(toTagObject); - const tagsToUnassign = lodash.difference(originalTags.map(tagName), tagsToAssign.map(tagName)); - const tagObjectsToUnassign = tagsToUnassign.map(toTagObject); + function assignTags (collection, selectedResources, originalTags, tagsToAssign) { + const tagObjectsToAssign = tagsToAssign.map(toTagObject) + const tagsToUnassign = lodash.difference(originalTags.map(tagName), tagsToAssign.map(tagName)) + const tagObjectsToUnassign = tagsToUnassign.map(toTagObject) return Promise.all([ postTagPayload('assign_tags', tagObjectsToAssign), - postTagPayload('unassign_tags', tagObjectsToUnassign), - ]); + postTagPayload('unassign_tags', tagObjectsToUnassign) + ]) - function tagName(tag) { - return tag.name; + function tagName (tag) { + return tag.name } - function toTagObject(tag) { - return { name: tag.name || tag }; + function toTagObject (tag) { + return { name: tag.name || tag } } - function postTagPayload(action, tags) { + function postTagPayload (action, tags) { if (tags.length > 0) { const payload = { action, - resources: selectedResources.map(({ href }) => ({ href, tags })), - }; + resources: selectedResources.map(({ href }) => ({ href, tags })) + } - return CollectionsApi.post(collection, null, {}, payload); + return CollectionsApi.post(collection, null, {}, payload) } } } // Returns the common list of tags between all selected resources. - function findSharedTags(selectedResources, availableTags) { - return availableTags.filter(function(tag) { - return selectedResources.every(function(resource) { - return resource.tags.some(function(resourceTag) { - return tag.name === resourceTag.name; - }); - }); - }); + function findSharedTags (selectedResources, availableTags) { + return availableTags.filter(function (tag) { + return selectedResources.every(function (resource) { + return resource.tags.some(function (resourceTag) { + return tag.name === resourceTag.name + }) + }) + }) } // Ensures that tags have the correct shape to be processed. - function parseTag(tagResponse) { + function parseTag (tagResponse) { return { id: tagResponse.id, name: tagResponse.name, category: { - id: tagResponse.category.id, + id: tagResponse.category.id }, categorization: { - displayName: tagResponse.categorization.display_name, - }, - }; + displayName: tagResponse.categorization.display_name + } + } } // With no arguments query all available tags, with a single resource url // queries all available tags for that resource. The result is filtered of // invalid tags (missing required properties). - function queryAvailableTags(resourceUrl) { + function queryAvailableTags (resourceUrl) { var queryOptions = { expand: 'resources', - attributes: ['categorization', 'category'], - }; + attributes: ['categorization', 'category'] + } return CollectionsApi.query(resourceUrl || 'tags', queryOptions) .then(filterValidTags) - .catch(exception.log('Request failed for #queryAvailableTags')); + .catch(exception.log('Request failed for #queryAvailableTags')) - function filterValidTags(response) { + function filterValidTags (response) { return response.resources .filter(isValidTag) - .map(service.parseTag); + .map(service.parseTag) } - function isValidTag(tagResponse) { - return tagResponse.categorization - && tagResponse.categorization.display_name - && tagResponse.category - && tagResponse.category.id - && tagResponse.category.description; + function isValidTag (tagResponse) { + return tagResponse.categorization && + tagResponse.categorization.display_name && + tagResponse.category && + tagResponse.category.id && + tagResponse.category.description } } } diff --git a/client/app/globals.js b/client/app/globals.js index ed6a0a9c5..8a518f5b7 100644 --- a/client/app/globals.js +++ b/client/app/globals.js @@ -1,17 +1,17 @@ /* eslint angular/window-service: "off" */ // overriden from gettext.config once the initialization is done if (!window.__) { - window.__ = function(str) { + window.__ = function (str) { throw new Error([ 'Attempting to call gettext before the service was initialized.', - 'Maybe you\'re calling it in the .config phase? ("' + str + '")', - ].join(' ')); - }; + 'Maybe you\'re calling it in the .config phase? ("' + str + '")' + ].join(' ')) + } } // N_ is OK anywhere if (!window.N_) { - window.N_ = function(str) { - return str; - }; + window.N_ = function (str) { + return str + } } diff --git a/client/app/requests/order-explorer/order-explorer.component.js b/client/app/requests/order-explorer/order-explorer.component.js index 77f669c18..9c606138f 100644 --- a/client/app/requests/order-explorer/order-explorer.component.js +++ b/client/app/requests/order-explorer/order-explorer.component.js @@ -1,23 +1,23 @@ -import "../../../assets/sass/_explorer.sass"; -import templateUrl from "./order-explorer.html"; +import '../../../assets/sass/_explorer.sass' +import templateUrl from './order-explorer.html' export const OrderExplorerComponent = { controller: ComponentController, controllerAs: 'vm', - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController($filter, lodash, ListView, Language, OrdersState, ShoppingCart, EventNotifications, Session, RBAC, ModalService, +function ComponentController ($filter, lodash, ListView, Language, OrdersState, ShoppingCart, EventNotifications, Session, RBAC, ModalService, CollectionsApi, sprintf, Polling, POLLING_INTERVAL) { - const vm = this; - vm.permissions = OrdersState.getPermissions(); - vm.$onInit = activate(); - vm.$onDestroy = function() { - Polling.stop('orderListPolling'); - }; - - function activate() { + const vm = this + vm.permissions = OrdersState.getPermissions() + vm.$onInit = activate() + vm.$onDestroy = function () { + Polling.stop('orderListPolling') + } + + function activate () { angular.extend(vm, { currentUser: Session.currentUser(), loading: false, @@ -38,44 +38,44 @@ function ComponentController($filter, lodash, ListView, Language, OrdersState, S listConfig: getListConfig(), expandedListConfig: getExpandedListConfig(), offset: 0, - pollingInterval: POLLING_INTERVAL, - }); - OrdersState.setSort({id: "placed_at", title: "Order Date", sortType: "numeric"}, false); - resolveOrders(vm.limit, 0); - Polling.start('orderListPolling', pollUpdateOrderList, vm.pollingInterval); - Language.fixState(OrdersState, vm.toolbarConfig); + pollingInterval: POLLING_INTERVAL + }) + OrdersState.setSort({id: 'placed_at', title: 'Order Date', sortType: 'numeric'}, false) + resolveOrders(vm.limit, 0) + Polling.start('orderListPolling', pollUpdateOrderList, vm.pollingInterval) + Language.fixState(OrdersState, vm.toolbarConfig) } - function getListConfig() { + function getListConfig () { return { showSelectBox: checkApproval(), useExpandingRows: true, selectionMatchProp: 'id', onClick: expandRow, - onCheckBoxChange: selectionChange, - }; + onCheckBoxChange: selectionChange + } } - function pollUpdateOrderList() { - resolveOrders(vm.limit, vm.offset, true); + function pollUpdateOrderList () { + resolveOrders(vm.limit, vm.offset, true) } - function getExpandedListConfig() { + function getExpandedListConfig () { return { showSelectBox: checkApproval(), selectionMatchProp: 'id', onClick: selectItem, - onCheckBoxChange: extendedSelectionChange, - }; + onCheckBoxChange: extendedSelectionChange + } } - function getToolbarConfig() { + function getToolbarConfig () { const sortConfig = { fields: getOrderSortFields(), onSortChange: sortChange, isAscending: OrdersState.getSort().isAscending, - currentField: OrdersState.getSort().currentField, - }; + currentField: OrdersState.getSort().currentField + } const filterConfig = { fields: getOrderFilterFields(), @@ -83,44 +83,44 @@ function ComponentController($filter, lodash, ListView, Language, OrdersState, S totalCount: 0, selectedCount: 0, appliedFilters: OrdersState.filterApplied ? OrdersState.getFilters() : [], - onFilterChange: orderFilterChange, - }; + onFilterChange: orderFilterChange + } return { sortConfig: sortConfig, filterConfig: filterConfig, actionsConfig: { - actionsInclude: checkApproval(), - }, - }; + actionsInclude: checkApproval() + } + } } - function getOrderFilterFields() { + function getOrderFilterFields () { return [ ListView.createFilterField('name', __('Name'), __('Filter by Name'), 'text'), ListView.createFilterField('id', __('Order ID'), __('Filter by ID'), 'text'), - ListView.createFilterField('placed_at', __('Order Date'), __('Filter by Order Date'), 'text'), - ]; + ListView.createFilterField('placed_at', __('Order Date'), __('Filter by Order Date'), 'text') + ] } - function getOrderSortFields() { + function getOrderSortFields () { return [ ListView.createSortField('name', __('Name'), 'alpha'), ListView.createSortField('id', __('Order ID'), 'numeric'), - ListView.createSortField('placed_at', __('Order Date'), 'numeric'), - ]; + ListView.createSortField('placed_at', __('Order Date'), 'numeric') + ] } - function getMenuActions() { - const menuActions = []; + function getMenuActions () { + const menuActions = [] if (vm.permissions.copy) { menuActions.push({ name: __('Duplicate'), actionName: 'duplicate', title: __('Duplicate Order'), actionFn: duplicateOrder, - isDisabled: true, - }); + isDisabled: true + }) } if (vm.permissions.delete) { @@ -130,88 +130,88 @@ function ComponentController($filter, lodash, ListView, Language, OrdersState, S actionName: 'remove', title: __('Remove Order'), actionFn: removeOrder, - isDisabled: false, + isDisabled: false } - ); + ) } - return checkApproval() ? menuActions : null; + return checkApproval() ? menuActions : null } - function expandRow(item) { + function expandRow (item) { if (!item.disableRowExpansion) { - item.isExpanded = !item.isExpanded; + item.isExpanded = !item.isExpanded } } - function sortChange(sortId, direction) { - OrdersState.setSort(sortId, direction); - resolveOrders(vm.limit, 0); + function sortChange (sortId, direction) { + OrdersState.setSort(sortId, direction) + resolveOrders(vm.limit, 0) } - function orderFilterChange(filters) { - vm.ordersList = ListView.applyFilters(filters, vm.ordersList, vm.orders, OrdersState, orderMatchesFilter); - resolveOrders(vm.limit, 0); + function orderFilterChange (filters) { + vm.ordersList = ListView.applyFilters(filters, vm.ordersList, vm.orders, OrdersState, orderMatchesFilter) + resolveOrders(vm.limit, 0) } - function orderMatchesFilter(item, filter) { + function orderMatchesFilter (item, filter) { if (filter.id === 'name') { - return item.name.toLowerCase().indexOf(filter.value.toLowerCase()) !== -1; + return item.name.toLowerCase().indexOf(filter.value.toLowerCase()) !== -1 } else if (filter.id === 'id') { - return String(item.id).toLowerCase().indexOf(filter.value.toLowerCase()) !== -1; + return String(item.id).toLowerCase().indexOf(filter.value.toLowerCase()) !== -1 } else if (filter.id === 'placed_at') { - return $filter('date')(item.placed_at || item.updated_at).toLowerCase().indexOf(filter.value.toLowerCase()) !== -1; + return $filter('date')(item.placed_at || item.updated_at).toLowerCase().indexOf(filter.value.toLowerCase()) !== -1 } - return false; + return false } - function selectionChange(item) { + function selectionChange (item) { if (angular.isDefined(item.service_requests)) { // if any child requests are unchecked, check them otherwise uncheck all if (item.service_requests.length === lodash.filter(item.service_requests, returnSelected).length) { item.service_requests.forEach((request) => { - request.selected = false; - }); + request.selected = false + }) } else { item.service_requests.forEach((request) => { - request.selected = true; - }); + request.selected = true + }) } } - vm.selectedItemsList = vm.ordersList.filter((item) => item.selected); - vm.toolbarConfig.filterConfig.selectedCount = vm.selectedItemsList.length; + vm.selectedItemsList = vm.ordersList.filter((item) => item.selected) + vm.toolbarConfig.filterConfig.selectedCount = vm.selectedItemsList.length } - function extendedSelectionChange(item) { - const parent = lodash.find(vm.ordersList, findItem); + function extendedSelectionChange (item) { + const parent = lodash.find(vm.ordersList, findItem) if (parent.service_requests.length === lodash.filter(parent.service_requests, returnSelected).length) { - parent.selected = !parent.selected; + parent.selected = !parent.selected } else { - parent.selected = false; + parent.selected = false } - lodash.indexOf(vm.selectedItemsList, item) === -1 ? vm.selectedItemsList.push(item) : lodash.pull(vm.selectedItemsList, item); + lodash.indexOf(vm.selectedItemsList, item) === -1 ? vm.selectedItemsList.push(item) : lodash.pull(vm.selectedItemsList, item) - vm.toolbarConfig.filterConfig.selectedCount = vm.selectedItemsList.length; + vm.toolbarConfig.filterConfig.selectedCount = vm.selectedItemsList.length - function findItem(order) { - return lodash.find(order.service_requests, item); + function findItem (order) { + return lodash.find(order.service_requests, item) } } - function returnSelected(item) { - return item.selected; + function returnSelected (item) { + return item.selected } - function resolveOrders(limit, offset, refresh) { + function resolveOrders (limit, offset, refresh) { if (!refresh) { - vm.loading = true; + vm.loading = true } - var existingOrders = (angular.isDefined(vm.ordersList) && refresh ? angular.copy(vm.ordersList) : []); + var existingOrders = (angular.isDefined(vm.ordersList) && refresh ? angular.copy(vm.ordersList) : []) - vm.offset = offset; + vm.offset = offset getFilterCount().then(() => { OrdersState.getOrders( limit, @@ -219,122 +219,121 @@ function ComponentController($filter, lodash, ListView, Language, OrdersState, S OrdersState.getFilters(), OrdersState.getSort().currentField, OrdersState.getSort().isAscending, - refresh).then(querySuccess, queryFailure); - }); - + refresh).then(querySuccess, queryFailure) + }) - function querySuccess(response) { - vm.loading = false; - vm.orders = []; - vm.selectedItemsList = []; - vm.toolbarConfig.filterConfig.selectedCount = 0; - vm.toolbarConfig.filterConfig.resultsCount = vm.filterCount; - vm.toolbarConfig.filterConfig.totalCount = response.subcount; + function querySuccess (response) { + vm.loading = false + vm.orders = [] + vm.selectedItemsList = [] + vm.toolbarConfig.filterConfig.selectedCount = 0 + vm.toolbarConfig.filterConfig.resultsCount = vm.filterCount + vm.toolbarConfig.filterConfig.totalCount = response.subcount - angular.forEach(response.resources, checkExpansion); + angular.forEach(response.resources, checkExpansion) - function checkExpansion(item) { + function checkExpansion (item) { if (angular.isDefined(item.id)) { - item.disableRowExpansion = angular.isUndefined(item.service_requests) - || (angular.isDefined(item.service_requests) && item.service_requests.length < 1); - let dataRow = item; + item.disableRowExpansion = angular.isUndefined(item.service_requests) || + (angular.isDefined(item.service_requests) && item.service_requests.length < 1) + let dataRow = item if (refresh) { - dataRow = refreshRow(item); + dataRow = refreshRow(item) } - vm.orders.push(dataRow); + vm.orders.push(dataRow) } } - function refreshRow(item) { + function refreshRow (item) { existingOrders.forEach((order) => { if (order.id === item.id) { - item.isExpanded = angular.isDefined(order.isExpanded) ? order.isExpanded : false; - item.selected = angular.isDefined(order.selected) ? order.selected : false; + item.isExpanded = angular.isDefined(order.isExpanded) ? order.isExpanded : false + item.selected = angular.isDefined(order.selected) ? order.selected : false if (item.selected) { - vm.selectedItemsList.push(item); + vm.selectedItemsList.push(item) } - lodash.pull(existingOrders, order); + lodash.pull(existingOrders, order) } - }); + }) - return item; + return item } - vm.ordersList = angular.copy(vm.orders); + vm.ordersList = angular.copy(vm.orders) } - function queryFailure(_error) { - vm.loading = false; - EventNotifications.error(__('There was an error loading orders.')); + function queryFailure (_error) { + vm.loading = false + EventNotifications.error(__('There was an error loading orders.')) } } - function getFilterCount() { + function getFilterCount () { return new Promise((resolve, reject) => { - OrdersState.getMinimal(OrdersState.getFilters()).then(querySuccess, queryFailure); + OrdersState.getMinimal(OrdersState.getFilters()).then(querySuccess, queryFailure) - function querySuccess(result) { - vm.filterCount = result.subcount; - resolve(); + function querySuccess (result) { + vm.filterCount = result.subcount + resolve() } - function queryFailure(_error) { - EventNotifications.error(__('There was an error loading orders.')); - reject(); + function queryFailure (_error) { + EventNotifications.error(__('There was an error loading orders.')) + reject(__('There was an error loading orders.')) } - }); + }) } - function duplicateOrder(_action, item) { - ShoppingCart.reset(); - ShoppingCart.delete(); + function duplicateOrder (_action, item) { + ShoppingCart.reset() + ShoppingCart.delete() - CollectionsApi.post('service_orders', null, null, {action: "copy", resources: [{id: item.id}]}).then(success, failure); + CollectionsApi.post('service_orders', null, null, {action: 'copy', resources: [{id: item.id}]}).then(success, failure) - function success(response) { - ShoppingCart.reload(); - EventNotifications.success(sprintf(__('%s was duplicated, id # %d.'), item.name, response.results[0].id)); + function success (response) { + ShoppingCart.reload() + EventNotifications.success(sprintf(__('%s was duplicated, id # %d.'), item.name, response.results[0].id)) } - function failure(_error) { - EventNotifications.error(sprintf(__('There was an error duplicating %s.'), item.name)); + function failure (_error) { + EventNotifications.error(sprintf(__('There was an error duplicating %s.'), item.name)) } } - function removeOrder(_action, item) { + function removeOrder (_action, item) { const modalOptions = { component: 'processOrderModal', resolve: { - order: function() { - return item; - }, - }, - }; - ModalService.open(modalOptions); + order: function () { + return item + } + } + } + ModalService.open(modalOptions) } - function checkApproval() { - return lodash.reduce(lodash.map(['miq_request_approval', 'miq_request_admin'], RBAC.has)); + function checkApproval () { + return lodash.reduce(lodash.map(['miq_request_approval', 'miq_request_admin'], RBAC.has)) } - function selectItem(item) { - item.selected = !item.selected; - extendedSelectionChange(item); + function selectItem (item) { + item.selected = !item.selected + extendedSelectionChange(item) } - function listActionDisable(config, items) { - items.length <= 0 ? config.isDisabled = true : config.isDisabled = false; + function listActionDisable (config, items) { + items.length <= 0 ? config.isDisabled = true : config.isDisabled = false } - function updatePagination(limit, offset) { - vm.limit = limit; - vm.offset = offset; - vm.resolveOrders(limit, offset); + function updatePagination (limit, offset) { + vm.limit = limit + vm.offset = offset + vm.resolveOrders(limit, offset) } - function updateMenuActionForItemFn(action, item) { + function updateMenuActionForItemFn (action, item) { if (action.actionName === 'duplicate') { - action.isDisabled = item.state !== 'cart' && angular.isUndefined(item.service_requests); + action.isDisabled = item.state !== 'cart' && angular.isUndefined(item.service_requests) } } } diff --git a/client/app/requests/orders-state.service.js b/client/app/requests/orders-state.service.js index cb8dda250..6648d5a14 100644 --- a/client/app/requests/orders-state.service.js +++ b/client/app/requests/orders-state.service.js @@ -1,69 +1,69 @@ /* eslint camelcase: "off" */ /** @ngInject */ -export function OrdersStateFactory(ListConfiguration, CollectionsApi, RBAC) { - const collection = 'service_orders'; +export function OrdersStateFactory (ListConfiguration, CollectionsApi, RBAC) { + const collection = 'service_orders' const service = { getMinimal: getMinimal, getOrders: getOrders, - getPermissions: getPermissions, - }; + getPermissions: getPermissions + } - ListConfiguration.setupListFunctions(service, {id: 'placed_at', title: __('Order Date'), sortType: 'numeric'}); + ListConfiguration.setupListFunctions(service, {id: 'placed_at', title: __('Order Date'), sortType: 'numeric'}) - return service; + return service - function getMinimal(filters) { + function getMinimal (filters) { const options = { filter: getQueryFilters(filters), hide: 'resources', - auto_refresh: true, - }; + auto_refresh: true + } - return CollectionsApi.query(collection, options); + return CollectionsApi.query(collection, options) } - function getOrders(limit, offset, filters, sortField, sortAscending, refresh) { + function getOrders (limit, offset, filters, sortField, sortAscending, refresh) { const options = { expand: ['resources', 'service_requests'], limit: limit, offset: String(offset), attributes: [], filter: getQueryFilters(filters), - auto_refresh: refresh, - }; + auto_refresh: refresh + } if (angular.isDefined(sortField)) { - options.sort_by = service.getSort().currentField.id; - options.sort_options = service.getSort().currentField.sortType === 'alpha' ? 'ignore_case' : ''; - options.sort_order = sortAscending ? 'asc' : 'desc'; + options.sort_by = service.getSort().currentField.id + options.sort_options = service.getSort().currentField.sortType === 'alpha' ? 'ignore_case' : '' + options.sort_order = sortAscending ? 'asc' : 'desc' } - return CollectionsApi.query(collection, options); + return CollectionsApi.query(collection, options) } // Private - function getQueryFilters(filters) { - const queryFilters = ['state=ordered']; + function getQueryFilters (filters) { + const queryFilters = ['state=ordered'] - angular.forEach(filters, function(nextFilter) { + angular.forEach(filters, function (nextFilter) { if (nextFilter.id === 'name') { - queryFilters.push("name='%" + nextFilter.value + "%'"); + queryFilters.push("name='%" + nextFilter.value + "%'") } else { - queryFilters.push(nextFilter.id + '=' + nextFilter.value); + queryFilters.push(nextFilter.id + '=' + nextFilter.value) } - }); + }) - return queryFilters; + return queryFilters } - function getPermissions() { + function getPermissions () { const permissions = { approve: RBAC.has('miq_request_approval'), delete: RBAC.has('miq_request_delete'), - copy: RBAC.has('miq_request_copy'), - }; + copy: RBAC.has('miq_request_copy') + } - return permissions; + return permissions } } diff --git a/client/app/requests/process-order-modal/process-order-modal.component.js b/client/app/requests/process-order-modal/process-order-modal.component.js index d26d1c7fd..bbd14428e 100644 --- a/client/app/requests/process-order-modal/process-order-modal.component.js +++ b/client/app/requests/process-order-modal/process-order-modal.component.js @@ -1,4 +1,4 @@ -import templateUrl from './process-order-modal.html'; +import templateUrl from './process-order-modal.html' export const ProcessOrderModalComponent = { controller: ComponentController, @@ -6,40 +6,40 @@ export const ProcessOrderModalComponent = { bindings: { resolve: '<', close: '&', - dismiss: '&', + dismiss: '&' }, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController($state, CollectionsApi, EventNotifications) { - var vm = this; +function ComponentController ($state, CollectionsApi, EventNotifications) { + var vm = this angular.extend(vm, { order: vm.resolve.order, confirm: confirm, - cancel: cancel, - }); + cancel: cancel + }) - function cancel() { - vm.dismiss({$value: 'cancel'}); + function cancel () { + vm.dismiss({$value: 'cancel'}) } - function confirm() { + function confirm () { var data = { action: 'delete', - resources: [vm.order], - }; - CollectionsApi.post('service_orders', '', {}, data).then(saveSuccess, saveFailure); + resources: [vm.order] + } + CollectionsApi.post('service_orders', '', {}, data).then(saveSuccess, saveFailure) - function saveSuccess(response) { - vm.close(); - EventNotifications.batch(response.results, __('Deleting order.'), __('Error deleting order.')); - $state.go($state.current, {}, {reload: true}); + function saveSuccess (response) { + vm.close() + EventNotifications.batch(response.results, __('Deleting order.'), __('Error deleting order.')) + $state.go($state.current, {}, {reload: true}) } - function saveFailure() { - EventNotifications.error(__('There was an error removing order')); + function saveFailure () { + EventNotifications.error(__('There was an error removing order')) } } } diff --git a/client/app/requests/requests-state.service.js b/client/app/requests/requests-state.service.js index 0c73f4465..53722c207 100644 --- a/client/app/requests/requests-state.service.js +++ b/client/app/requests/requests-state.service.js @@ -1,20 +1,20 @@ /* eslint camelcase: "off" */ /* @ngInject */ -export function RequestsStateFactory(ListConfiguration, RBAC, CollectionsApi) { - const collection = 'requests'; +export function RequestsStateFactory (ListConfiguration, RBAC, CollectionsApi) { + const collection = 'requests' const service = { listActions: {}, get: get, getMinimal: getMinimal, - getPermissions: getPermissions, - }; + getPermissions: getPermissions + } - ListConfiguration.setupListFunctions(service.listActions, {id: 'created_on', title: __('Request Date'), sortType: 'numeric'}); + ListConfiguration.setupListFunctions(service.listActions, {id: 'created_on', title: __('Request Date'), sortType: 'numeric'}) - return service; + return service - function get(limit, offset) { + function get (limit, offset) { const attributes = [ 'approval_state', 'created_on', @@ -22,8 +22,8 @@ export function RequestsStateFactory(ListConfiguration, RBAC, CollectionsApi) { 'message', 'picture', 'picture.image_href', - 'requester_name', - ]; + 'requester_name' + ] const options = { expand: 'resources', limit: limit, @@ -32,35 +32,35 @@ export function RequestsStateFactory(ListConfiguration, RBAC, CollectionsApi) { filter: getQueryFilters(service.listActions.getFilters()), sort_by: service.listActions.getSort().currentField.id, sort_options: service.listActions.getSort().currentField.sortType === 'alpha' ? 'ignore_case' : '', - sort_order: service.listActions.getSort().isAscending ? 'asc' : 'desc', - }; + sort_order: service.listActions.getSort().isAscending ? 'asc' : 'desc' + } - return CollectionsApi.query(collection, options); + return CollectionsApi.query(collection, options) } - function getMinimal() { + function getMinimal () { const options = { filter: getQueryFilters(service.listActions.getFilters()), - hide: 'resources', - }; + hide: 'resources' + } - return CollectionsApi.query(collection, options); + return CollectionsApi.query(collection, options) } - function getPermissions() { + function getPermissions () { return { approval: RBAC.hasAny(['miq_request_approval']), - edit: RBAC.hasAny(['miq_request_edit']), - }; + edit: RBAC.hasAny(['miq_request_edit']) + } } - function getQueryFilters(filters) { - const queryFilters = []; + function getQueryFilters (filters) { + const queryFilters = [] filters.forEach((nextFilter) => { - queryFilters.push(nextFilter.id + '=' + nextFilter.value); - }); + queryFilters.push(nextFilter.id + '=' + nextFilter.value) + }) - return queryFilters; + return queryFilters } } diff --git a/client/app/requests/requests.module.js b/client/app/requests/requests.module.js index bf737ab55..55e0f50c4 100644 --- a/client/app/requests/requests.module.js +++ b/client/app/requests/requests.module.js @@ -1,15 +1,15 @@ -import { OrderExplorerComponent } from './order-explorer/order-explorer.component.js'; -import { OrdersStateFactory } from './orders-state.service.js'; -import { ProcessOrderModalComponent } from './process-order-modal/process-order-modal.component.js'; -import { RequestsStateFactory } from './requests-state.service.js'; -import { SharedModule } from '../shared/shared.module.js'; +import { OrderExplorerComponent } from './order-explorer/order-explorer.component.js' +import { OrdersStateFactory } from './orders-state.service.js' +import { ProcessOrderModalComponent } from './process-order-modal/process-order-modal.component.js' +import { RequestsStateFactory } from './requests-state.service.js' +import { SharedModule } from '../shared/shared.module.js' export const RequestsModule = angular .module('app.requests', [ - SharedModule, + SharedModule ]) .component('processOrderModal', ProcessOrderModalComponent) .component('orderExplorer', OrderExplorerComponent) .factory('OrdersState', OrdersStateFactory) .factory('RequestsState', RequestsStateFactory) - .name; + .name diff --git a/client/app/services/consoles.service.js b/client/app/services/consoles.service.js index b0578fa30..2e0552b6d 100644 --- a/client/app/services/consoles.service.js +++ b/client/app/services/consoles.service.js @@ -1,101 +1,101 @@ /** @ngInject */ -export function ConsolesFactory($window, CollectionsApi, $timeout, $location, EventNotifications) { +export function ConsolesFactory ($window, CollectionsApi, $timeout, $location, EventNotifications) { var service = { - open: openConsole, - }; + open: openConsole + } - return service; + return service - function openConsole(vmId) { + function openConsole (vmId) { return CollectionsApi.post('vms', vmId, {}, { action: 'request_console', - resource: {protocol: "html5"}, + resource: {protocol: 'html5'} }) .then(consoleResponse) - .catch(consoleError); + .catch(consoleError) } - function consoleResponse(response) { + function consoleResponse (response) { if (!response.success) { // for some reason failure is 200 + success=false here, so throwing the message to use the same error handler - throw response; + throw response } - EventNotifications.info(__("Waiting for the console to become ready. "), response.message); - consoleWatch(response.task_id); + EventNotifications.info(__('Waiting for the console to become ready. '), response.message) + consoleWatch(response.task_id) } // try to get the task results every second, until Finished (or error) - function consoleWatch(id) { - $timeout(function() { + function consoleWatch (id) { + $timeout(function () { CollectionsApi.get('tasks', id, {attributes: 'task_results'}) .then(consoleSuccess) - .catch(consoleError); - }, 1000); + .catch(consoleError) + }, 1000) } - function consoleSuccess(task) { + function consoleSuccess (task) { if ((task.state === 'Finished') && (task.status === 'Ok')) { // success - consoleOpen(task.task_results); + consoleOpen(task.task_results) } else if ((task.state === 'Queued') && (task.status === 'Ok')) { // waiting - consoleWatch(task.id); + consoleWatch(task.id) } else { // failure - throw task.message; + throw task.message } } - function consoleError(error) { - EventNotifications.error(__("There was an error opening the console. " + error.message)); + function consoleError (error) { + EventNotifications.error(__('There was an error opening the console. ' + error.message)) } - function consoleOpen(results) { + function consoleOpen (results) { switch (results.proto) { case 'spice': - openSpice(results); - break; + openSpice(results) + break case 'vnc': - openVnc(results); - break; + openVnc(results) + break case 'remote': - openRemote(results); - break; + openRemote(results) + break default: - EventNotifications.error(__("Unsupported console protocol returned. ") + results.proto); + EventNotifications.error(__('Unsupported console protocol returned. ') + results.proto) } } - function openSpice(results) { - var url = '/ui/service/vendor/spice-html5-bower/spiceHTML5/spice_auto.html' - + '?host=' + $location.host() - + '&port=' + $location.port() - + '&path=' + results.url - + '&password=' + results.secret; + function openSpice (results) { + var url = '/ui/service/vendor/spice-html5-bower/spiceHTML5/spice_auto.html' + + '?host=' + $location.host() + + '&port=' + $location.port() + + '&path=' + results.url + + '&password=' + results.secret // encrypt is divined automagically in spice_auto - $window.open(url); + $window.open(url) } - function openVnc(results) { - var url = '/ui/service/vendor/no-vnc/vnc_auto.html' - + '?host=' + $location.host() - + '&port=' + $location.port() - + '&path=' + results.url - + '&password=' + results.secret - + '&true_color=1'; + function openVnc (results) { + var url = '/ui/service/vendor/no-vnc/vnc_auto.html' + + '?host=' + $location.host() + + '&port=' + $location.port() + + '&path=' + results.url + + '&password=' + results.secret + + '&true_color=1' if ($location.protocol() === 'https') { - url += '&encrypt=1'; + url += '&encrypt=1' } - $window.open(url); + $window.open(url) } - function openRemote(results) { + function openRemote (results) { // openstack - $window.open(results.remote_url); + $window.open(results.remote_url) } } diff --git a/client/app/services/custom-button/custom-button.component.js b/client/app/services/custom-button/custom-button.component.js index 0a4fcf062..bb51eea64 100644 --- a/client/app/services/custom-button/custom-button.component.js +++ b/client/app/services/custom-button/custom-button.component.js @@ -1,58 +1,58 @@ -import './_custom-button.sass'; -import templateUrl from './custom-button.html'; +import './_custom-button.sass' +import templateUrl from './custom-button.html' export const CustomButtonComponent = { bindings: { customActions: '<', serviceId: '<', - vmId: '<', + vmId: '<' }, controller: CustomButtonController, controllerAs: 'vm', - templateUrl, -}; + templateUrl +} /** @ngInject */ -function CustomButtonController($state, EventNotifications, CollectionsApi, RBAC) { - const vm = this; +function CustomButtonController ($state, EventNotifications, CollectionsApi, RBAC) { + const vm = this - vm.hasRequiredRole = hasRequiredRole; - vm.invokeCustomAction = invokeCustomAction; + vm.hasRequiredRole = hasRequiredRole + vm.invokeCustomAction = invokeCustomAction - function hasRequiredRole(button) { - const acceptableRoles = button.visibility.roles; + function hasRequiredRole (button) { + const acceptableRoles = button.visibility.roles - return RBAC.hasRole(...acceptableRoles); + return RBAC.hasRole(...acceptableRoles) } - function invokeCustomAction(button) { + function invokeCustomAction (button) { if (button.resource_action && button.resource_action.dialog_id) { $state.go('services.custom_button_details', { button: button, - serviceId: vm.serviceId, - }); - } else if (vm.vmId) { - const data = {action: button.name}; + serviceId: vm.serviceId + }) + } else if (vm.vmId) { + const data = {action: button.name} CollectionsApi.post('vms', vm.vmId, {}, data) .then(postSuccess) - .catch(postFailure); + .catch(postFailure) } else { - const data = {action: button.name}; + const data = {action: button.name} CollectionsApi.post('services', vm.serviceId, {}, data) .then(postSuccess) - .catch(postFailure); + .catch(postFailure) } - function postSuccess(response) { + function postSuccess (response) { if (response.success === false) { - EventNotifications.error(response.message); + EventNotifications.error(response.message) } else { - EventNotifications.success(response.message); + EventNotifications.success(response.message) } } - function postFailure() { - EventNotifications.error(__('Action not able to submit.')); + function postFailure () { + EventNotifications.error(__('Action not able to submit.')) } } } diff --git a/client/app/services/detail-reveal/detail-reveal.component.js b/client/app/services/detail-reveal/detail-reveal.component.js index 11abbbf64..7f3ce2ecc 100644 --- a/client/app/services/detail-reveal/detail-reveal.component.js +++ b/client/app/services/detail-reveal/detail-reveal.component.js @@ -1,5 +1,5 @@ -import './_detail-reveal.sass'; -import templateUrl from './detail-reveal.html'; +import './_detail-reveal.sass' +import templateUrl from './detail-reveal.html' export const DetailRevealComponent = { controller: ComponentController, @@ -10,26 +10,26 @@ export const DetailRevealComponent = { icon: '@', translateTitle: '<', rowClass: '@', - displayField: '<?', + displayField: '<?' }, transclude: true, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController($transclude) { - var vm = this; - vm.$onInit = activate(); +function ComponentController ($transclude) { + var vm = this + vm.$onInit = activate() - function activate() { + function activate () { if (angular.isUndefined(vm.displayField)) { - vm.displayField = false; + vm.displayField = false } - vm.translateTitle = (angular.isUndefined(vm.translateTitle) ? true : vm.translateTitle); - vm.detailTitle = (vm.translateTitle === true ? __(vm.detailTitle) : vm.detailTitle); - vm.rowClass = (angular.isDefined(vm.rowClass) ? vm.rowClass : 'row detail-row'); - vm.toggleDetails = false; - vm.hasMoreDetails = $transclude().length > 0; + vm.translateTitle = (angular.isUndefined(vm.translateTitle) ? true : vm.translateTitle) + vm.detailTitle = (vm.translateTitle === true ? __(vm.detailTitle) : vm.detailTitle) + vm.rowClass = (angular.isDefined(vm.rowClass) ? vm.rowClass : 'row detail-row') + vm.toggleDetails = false + vm.hasMoreDetails = $transclude().length > 0 } } diff --git a/client/app/services/edit-service-modal/edit-service-modal.component.js b/client/app/services/edit-service-modal/edit-service-modal.component.js index cef220847..0f8127268 100644 --- a/client/app/services/edit-service-modal/edit-service-modal.component.js +++ b/client/app/services/edit-service-modal/edit-service-modal.component.js @@ -1,4 +1,4 @@ -import templateUrl from './edit-service-modal.html'; +import templateUrl from './edit-service-modal.html' export const EditServiceModalComponent = { controller: ComponentController, @@ -7,27 +7,27 @@ export const EditServiceModalComponent = { resolve: '<', modalInstance: '<', close: '&', - dismiss: '&', + dismiss: '&' }, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController($controller, sprintf) { - var vm = this; +function ComponentController ($controller, sprintf) { + var vm = this var base = $controller('BaseModalController', { - $uibModalInstance: vm.modalInstance, - }); - angular.extend(vm, base); + $uibModalInstance: vm.modalInstance + }) + angular.extend(vm, base) vm.modalData = { id: vm.resolve.service.id, name: vm.resolve.service.name, - description: vm.resolve.service.description, - }; + description: vm.resolve.service.description + } - vm.action = 'edit'; - vm.collection = 'services'; - vm.onSuccessMessage = sprintf(__("%s was edited."), vm.resolve.service.name); - vm.onFailureMessage = __('There was an error editing this service.'); + vm.action = 'edit' + vm.collection = 'services' + vm.onSuccessMessage = sprintf(__('%s was edited.'), vm.resolve.service.name) + vm.onFailureMessage = __('There was an error editing this service.') } diff --git a/client/app/services/ownership-service-modal/ownership-service-modal.component.js b/client/app/services/ownership-service-modal/ownership-service-modal.component.js index f17eb492a..54992ba58 100644 --- a/client/app/services/ownership-service-modal/ownership-service-modal.component.js +++ b/client/app/services/ownership-service-modal/ownership-service-modal.component.js @@ -1,5 +1,5 @@ /* eslint camelcase: "off" */ -import templateUrl from './ownership-service-modal.html'; +import templateUrl from './ownership-service-modal.html' export const OwnershipServiceModalComponent = { controller: ComponentController, @@ -7,23 +7,23 @@ export const OwnershipServiceModalComponent = { bindings: { resolve: '<', close: '&', - dismiss: '&', + dismiss: '&' }, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController($state, lodash, CollectionsApi, EventNotifications) { - var vm = this; +function ComponentController ($state, lodash, CollectionsApi, EventNotifications) { + var vm = this angular.extend(vm, { modalData: { 'owner': { - 'userid': '', + 'userid': '' }, 'group': { - 'description': '', - }, + 'description': '' + } }, isService: vm.resolve.services.length === 1, resetModal: false, @@ -32,59 +32,58 @@ function ComponentController($state, lodash, CollectionsApi, EventNotifications) groups: vm.resolve.groups, save: save, cancel: cancel, - reset: reset, - }); - activate(); + reset: reset + }) + activate() - - function cancel() { - vm.dismiss({$value: 'cancel'}); + function cancel () { + vm.dismiss({$value: 'cancel'}) } - function reset(event) { - angular.copy(event.original, this.modalData); // eslint-disable-line angular/controller-as-vm + function reset (event) { + angular.copy(event.original, this.modalData) // eslint-disable-line angular/controller-as-vm } - function save() { + function save () { var data = { action: 'set_ownership', - resources: null, - }; + resources: null + } if (vm.isService) { - data.resources = [vm.modalData]; + data.resources = [vm.modalData] } else { - var resources = []; - angular.copy(vm.services, resources); - lodash.forEach(resources, setOwnership); - data.resources = resources; + var resources = [] + angular.copy(vm.services, resources) + lodash.forEach(resources, setOwnership) + data.resources = resources } - CollectionsApi.post('services', '', {}, data).then(saveSuccess, saveFailure); + CollectionsApi.post('services', '', {}, data).then(saveSuccess, saveFailure) - function saveSuccess(response) { - vm.close(); - EventNotifications.batch(response.results, __('Setting ownership.'), __('Error setting ownership.')); - $state.go($state.current, {}, {reload: true}); + function saveSuccess (response) { + vm.close() + EventNotifications.batch(response.results, __('Setting ownership.'), __('Error setting ownership.')) + $state.go($state.current, {}, {reload: true}) } - function saveFailure() { - EventNotifications.error(__('There was an error saving ownership.')); + function saveFailure () { + EventNotifications.error(__('There was an error saving ownership.')) } - function setOwnership(service) { - service.owner = {userid: vm.modalData.owner.userid}; - service.group = {description: vm.modalData.group.description}; + function setOwnership (service) { + service.owner = {userid: vm.modalData.owner.userid} + service.group = {description: vm.modalData.group.description} } } // Private - function activate() { + function activate () { if (vm.isService) { - vm.resetModal = true; - vm.modalData.id = vm.services[0].id; - vm.modalData.owner.userid = vm.services[0].evm_owner && vm.services[0].evm_owner.userid || ''; - vm.modalData.group.description = vm.services[0].miq_group && vm.services[0].miq_group.description || ''; + vm.resetModal = true + vm.modalData.id = vm.services[0].id + vm.modalData.owner.userid = (vm.services[0].evm_owner && vm.services[0].evm_owner.userid) || '' + vm.modalData.group.description = (vm.services[0].miq_group && vm.services[0].miq_group.description) || '' } } } diff --git a/client/app/services/poweroperations.service.js b/client/app/services/poweroperations.service.js index f0368160b..840e9fa83 100644 --- a/client/app/services/poweroperations.service.js +++ b/client/app/services/poweroperations.service.js @@ -1,7 +1,7 @@ /* eslint-disable camelcase */ /** @ngInject */ -export function PowerOperationsFactory(CollectionsApi, EventNotifications, sprintf) { +export function PowerOperationsFactory (CollectionsApi, EventNotifications, sprintf) { var service = { startService: startService, stopService: stopService, @@ -25,223 +25,223 @@ export function PowerOperationsFactory(CollectionsApi, EventNotifications, sprin powerOperationTimeoutState: powerOperationTimeoutState, powerOperationStartTimeoutState: powerOperationStartTimeoutState, powerOperationStopTimeoutState: powerOperationStopTimeoutState, - powerOperationSuspendTimeoutState: powerOperationSuspendTimeoutState, - }; + powerOperationSuspendTimeoutState: powerOperationSuspendTimeoutState + } - function powerStatesMatch(powerStates, match) { - var matches = angular.isArray(powerStates) && powerStates.length > 0; + function powerStatesMatch (powerStates, match) { + var matches = angular.isArray(powerStates) && powerStates.length > 0 - angular.forEach(powerStates, function(powerState) { - matches = matches && (powerState === match); - }); + angular.forEach(powerStates, function (powerState) { + matches = matches && (powerState === match) + }) - return matches; + return matches } - function allowStart(item) { - return powerOperationUnknownState(item) - || powerOperationOffState(item) - || powerOperationSuspendState(item) - || powerOperationTimeoutState(item); + function allowStart (item) { + return powerOperationUnknownState(item) || + powerOperationOffState(item) || + powerOperationSuspendState(item) || + powerOperationTimeoutState(item) } - function allowStop(item) { - return !powerOperationUnknownState(item) - && !powerOperationOffState(item); + function allowStop (item) { + return !powerOperationUnknownState(item) && + !powerOperationOffState(item) } - function allowSuspend(item) { - return !powerOperationUnknownState(item) - && !powerOperationSuspendState(item); + function allowSuspend (item) { + return !powerOperationUnknownState(item) && + !powerOperationSuspendState(item) } - function getPowerState(item) { - var powerState = ""; + function getPowerState (item) { + var powerState = '' if (angular.isDefined(item.power_state)) { - powerState = item.power_state; + powerState = item.power_state } else if (angular.isArray(item.power_states)) { if (powerStatesMatch(item.power_states, 'on')) { - powerState = 'on'; + powerState = 'on' } else if (powerStatesMatch(item.power_states, 'off')) { - powerState = 'off'; + powerState = 'off' } else if (powerStatesMatch(item.power_states, 'timeout')) { - powerState = 'timeout'; + powerState = 'timeout' } } - return powerState; + return powerState } - function powerOperationUnknownState(item) { - return getPowerState(item) === ""; + function powerOperationUnknownState (item) { + return getPowerState(item) === '' } - function powerOperationInProgressState(item) { - return !powerOperationTimeoutState(item) - && ((item.power_status === "starting") - || (item.power_status === "stopping") - || (item.power_status === "suspending")); + function powerOperationInProgressState (item) { + return !powerOperationTimeoutState(item) && + ((item.power_status === 'starting') || + (item.power_status === 'stopping') || + (item.power_status === 'suspending')) } - function powerOperationOnState(item) { - return getPowerState(item) === 'on'; + function powerOperationOnState (item) { + return getPowerState(item) === 'on' } - function powerOperationOffState(item) { - return getPowerState(item) === 'off'; + function powerOperationOffState (item) { + return getPowerState(item) === 'off' } - function powerOperationSuspendState(item) { - return getPowerState(item) === 'off'; + function powerOperationSuspendState (item) { + return getPowerState(item) === 'off' } - function powerOperationTimeoutState(item) { - return getPowerState(item) === 'timeout'; + function powerOperationTimeoutState (item) { + return getPowerState(item) === 'timeout' } - function powerOperationStartTimeoutState(item) { - return powerOperationTimeoutState(item) && item.power_status === "starting"; + function powerOperationStartTimeoutState (item) { + return powerOperationTimeoutState(item) && item.power_status === 'starting' } - function powerOperationStopTimeoutState(item) { - return powerOperationTimeoutState(item) && item.power_status === "stopping"; + function powerOperationStopTimeoutState (item) { + return powerOperationTimeoutState(item) && item.power_status === 'stopping' } - function powerOperationSuspendTimeoutState(item) { - return powerOperationTimeoutState(item) && item.power_status === "suspending"; + function powerOperationSuspendTimeoutState (item) { + return powerOperationTimeoutState(item) && item.power_status === 'suspending' } - function startService(item) { - item.power_state = ''; - item.power_status = 'starting'; - - return new Promise((resolve, _reject) => { + function startService (item) { + item.power_state = '' + item.power_status = 'starting' + + return new Promise((resolve, reject) => { servicePowerOperation('start', item).then((results) => { - resolve(results); - }); - }); + resolve(results) + }) + }) } - function stopService(item) { - item.power_state = ''; - item.power_status = 'stopping'; + function stopService (item) { + item.power_state = '' + item.power_status = 'stopping' - return new Promise((resolve, _reject) => { + return new Promise((resolve, reject) => { servicePowerOperation('stop', item).then((results) => { - resolve(results); - }); - }); + resolve(results) + }) + }) } - function suspendService(item) { - item.power_state = ''; - item.power_status = 'suspending'; - - return new Promise((resolve, _reject) => { + function suspendService (item) { + item.power_state = '' + item.power_status = 'suspending' + + return new Promise((resolve, reject) => { servicePowerOperation('suspend', item).then((results) => { - resolve(results); - }); - }); + resolve(results) + }) + }) } - function startVm(item) { - item.power_state = ''; - item.power_status = 'starting'; - - return new Promise((resolve, _reject) => { + function startVm (item) { + item.power_state = '' + item.power_status = 'starting' + + return new Promise((resolve, reject) => { vmPowerOperation('start', item).then((results) => { - resolve(results); - }); - }); + resolve(results) + }) + }) } - function stopVm(item) { - item.power_state = ''; - item.power_status = 'stopping'; - - return new Promise((resolve, _reject) => { + function stopVm (item) { + item.power_state = '' + item.power_status = 'stopping' + + return new Promise((resolve, reject) => { vmPowerOperation('stop', item).then((results) => { - resolve(results); - }); - }); + resolve(results) + }) + }) } - function suspendVm(item) { - item.power_state = ''; - item.power_status = 'suspending'; + function suspendVm (item) { + item.power_state = '' + item.power_status = 'suspending' - return new Promise((resolve, _reject) => { + return new Promise((resolve, reject) => { vmPowerOperation('suspend', item).then((results) => { - resolve(results); - }); - }); + resolve(results) + }) + }) } - function retireVm(item) { - item.power_state = ''; - item.power_status = 'retiring'; + function retireVm (item) { + item.power_state = '' + item.power_status = 'retiring' - return new Promise((resolve, _reject) => { + return new Promise((resolve, reject) => { vmPowerOperation('retire', item).then((results) => { - resolve(results); - }); - }); + resolve(results) + }) + }) } - function powerOperation(apiType, powerAction, item, itemType) { - return new Promise((resolve, _reject) => { - resolve(CollectionsApi.post(apiType, item.id, {}, {action: powerAction}).then(actionSuccess, actionFailure)); - }); - function actionSuccess(response) { + function powerOperation (apiType, powerAction, item, itemType) { + return new Promise((resolve, reject) => { + resolve(CollectionsApi.post(apiType, item.id, {}, {action: powerAction}).then(actionSuccess, actionFailure)) + }) + function actionSuccess (response) { switch (powerAction) { case 'start': - EventNotifications.success(sprintf(__("%s was started. " + response.message), item.name)); - break; + EventNotifications.success(sprintf(__('%s was started. ' + response.message), item.name)) + break case 'stop': - EventNotifications.success(sprintf(__("%s was stopped. " + response.message), item.name)); - break; + EventNotifications.success(sprintf(__('%s was stopped. ' + response.message), item.name)) + break case 'suspend': - EventNotifications.success(sprintf(__("%s was suspended. " + response.message), item.name)); - break; + EventNotifications.success(sprintf(__('%s was suspended. ' + response.message), item.name)) + break case 'retire': - EventNotifications.success(sprintf(__("%s was retired. " + response.message), item.name)); - break; + EventNotifications.success(sprintf(__('%s was retired. ' + response.message), item.name)) + break } } - function actionFailure() { + function actionFailure () { switch (powerAction) { case 'start': - EventNotifications.error(sprintf(__('There was an error starting this %s.'), itemType)); - break; + EventNotifications.error(sprintf(__('There was an error starting this %s.'), itemType)) + break case 'stop': - EventNotifications.error(sprintf(__('There was an error stopping this %s.'), itemType)); - break; + EventNotifications.error(sprintf(__('There was an error stopping this %s.'), itemType)) + break case 'suspend': - EventNotifications.error(sprintf(__('There was an error suspending this %s.'), itemType)); - break; + EventNotifications.error(sprintf(__('There was an error suspending this %s.'), itemType)) + break case 'retire': - EventNotifications.error(sprintf(__('There was an error retiring this %s.'), itemType)); - break; + EventNotifications.error(sprintf(__('There was an error retiring this %s.'), itemType)) + break } } } - function servicePowerOperation(powerAction, item) { - return new Promise((resolve, _reject) => { + function servicePowerOperation (powerAction, item) { + return new Promise((resolve, reject) => { powerOperation('services', powerAction, item, 'service').then((result) => { - resolve(result); - }); - }); + resolve(result) + }) + }) } - function vmPowerOperation(powerAction, item) { - return new Promise((resolve, _reject) => { + function vmPowerOperation (powerAction, item) { + return new Promise((resolve, reject) => { powerOperation('vms', powerAction, item, 'virtual machine').then((result) => { - resolve(result); - }); - }); + resolve(result) + }) + }) } - return service; + return service } diff --git a/client/app/services/process-snapshots-modal/process-snapshots-modal.component.js b/client/app/services/process-snapshots-modal/process-snapshots-modal.component.js index fdf2d14e3..ad3534ba7 100644 --- a/client/app/services/process-snapshots-modal/process-snapshots-modal.component.js +++ b/client/app/services/process-snapshots-modal/process-snapshots-modal.component.js @@ -1,4 +1,4 @@ -import templateUrl from './process-snapshots-modal.html'; +import templateUrl from './process-snapshots-modal.html' export const ProcessSnapshotsModalComponent = { controller: ComponentController, @@ -7,39 +7,39 @@ export const ProcessSnapshotsModalComponent = { resolve: '<', modalInstance: '<', close: '&', - dismiss: '&', + dismiss: '&' }, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController($controller, $state, EventNotifications, VmsService) { - const vm = this; +function ComponentController ($controller, $state, EventNotifications, VmsService) { + const vm = this - vm.$onInit = function() { + vm.$onInit = function () { angular.extend(vm, $controller('BaseModalController', { - $uibModalInstance: vm.modalInstance, - })); + $uibModalInstance: vm.modalInstance + })) angular.extend(vm, { modalData: {}, vm: vm.resolve.vm, modalType: vm.resolve.modalType, - save: save, - }); - }; + save: save + }) + } - function save() { - VmsService.createSnapshots(vm.vm.id, vm.modalData).then(success, failure); + function save () { + VmsService.createSnapshots(vm.vm.id, vm.modalData).then(success, failure) } - function success(response) { - vm.close(); - $state.go($state.current, {}, {reload: true}); - EventNotifications.batch(response.results, __('Creating snapshot.'), __('Error creating snapshot.')); + function success (response) { + vm.close() + $state.go($state.current, {}, {reload: true}) + EventNotifications.batch(response.results, __('Creating snapshot.'), __('Error creating snapshot.')) } - function failure(response) { - EventNotifications.error(__('There was an error creating the snapshot.') + response.message); + function failure (response) { + EventNotifications.error(__('There was an error creating the snapshot.') + response.message) } } diff --git a/client/app/services/retire-remove-service-modal/retire-remove-service-modal.component.js b/client/app/services/retire-remove-service-modal/retire-remove-service-modal.component.js index 33e4cda7f..069b06ac4 100644 --- a/client/app/services/retire-remove-service-modal/retire-remove-service-modal.component.js +++ b/client/app/services/retire-remove-service-modal/retire-remove-service-modal.component.js @@ -1,4 +1,4 @@ -import templateUrl from './retire-remove-service-modal.html'; +import templateUrl from './retire-remove-service-modal.html' export const RetireRemoveServiceModalComponent = { controller: ComponentController, @@ -6,49 +6,49 @@ export const RetireRemoveServiceModalComponent = { bindings: { resolve: '<', close: '&', - dismiss: '&', + dismiss: '&' }, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController($state, CollectionsApi, EventNotifications) { - var vm = this; +function ComponentController ($state, CollectionsApi, EventNotifications) { + var vm = this angular.extend(vm, { services: vm.resolve.services, - isRemove: vm.resolve.modalType === "remove", - isRetireNow: vm.resolve.modalType === "retire", + isRemove: vm.resolve.modalType === 'remove', + isRetireNow: vm.resolve.modalType === 'retire', confirm: confirm, - cancel: cancel, - }); + cancel: cancel + }) - function cancel() { - vm.dismiss({$value: 'cancel'}); + function cancel () { + vm.dismiss({$value: 'cancel'}) } - function confirm() { + function confirm () { var data = { action: vm.isRemove ? 'delete' : 'retire', - resources: vm.services, - }; - CollectionsApi.post('services', '', {}, data).then(saveSuccess, saveFailure); + resources: vm.services + } + CollectionsApi.post('services', '', {}, data).then(saveSuccess, saveFailure) - function saveSuccess(response) { - vm.close(); + function saveSuccess (response) { + vm.close() switch (vm.resolve.modalType) { - case "retire": - EventNotifications.success(__("Services Retired")); - break; - case "remove": - EventNotifications.batch(response.results, __('Service deleting.'), __('Error deleting service.')); - break; + case 'retire': + EventNotifications.success(__('Services Retired')) + break + case 'remove': + EventNotifications.batch(response.results, __('Service deleting.'), __('Error deleting service.')) + break } - $state.go($state.current, {}, {reload: true}); + $state.go($state.current, {}, {reload: true}) } - function saveFailure() { - EventNotifications.error(__('There was an error removing one or more services.')); + function saveFailure () { + EventNotifications.error(__('There was an error removing one or more services.')) } } } diff --git a/client/app/services/retire-service-modal/retire-service-modal.component.js b/client/app/services/retire-service-modal/retire-service-modal.component.js index f1e318dce..3ffa85a82 100644 --- a/client/app/services/retire-service-modal/retire-service-modal.component.js +++ b/client/app/services/retire-service-modal/retire-service-modal.component.js @@ -1,4 +1,4 @@ -import templateUrl from './retire-service-modal.html'; +import templateUrl from './retire-service-modal.html' export const RetireServiceModalComponent = { controller: ComponentController, @@ -6,14 +6,14 @@ export const RetireServiceModalComponent = { bindings: { resolve: '<', close: '&', - dismiss: '&', + dismiss: '&' }, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController($scope, $state, CollectionsApi, EventNotifications, moment) { - var vm = this; +function ComponentController ($scope, $state, CollectionsApi, EventNotifications, moment) { + var vm = this angular.extend(vm, { visibleOptions: [], @@ -23,77 +23,76 @@ function ComponentController($scope, $state, CollectionsApi, EventNotifications, services: vm.resolve.services, save: save, reset: reset, - cancel: cancel, - }); - + cancel: cancel + }) vm.dateOptions = { initDate: new Date(), minDate: new Date(), - showWeeks: false, - }; + showWeeks: false + } vm.warningOptions = [ {value: 0, label: __('No Warning')}, {value: 7, label: __('1 Week')}, {value: 14, label: __('2 Weeks')}, {value: 21, label: __('3 Weeks')}, - {value: 28, label: __('4 Weeks')}, - ]; + {value: 28, label: __('4 Weeks')} + ] - activate(); + activate() - function activate() { + function activate () { if (vm.isService) { - vm.modalData.id = vm.services[0].id; - vm.resetModal = true; - var existingDate = new Date(vm.services[0].retires_on); - var existingUTCDate = new Date(existingDate.getTime() + existingDate.getTimezoneOffset() * 60000); - vm.modalData.date = vm.services[0].retires_on ? existingUTCDate : null; - vm.modalData.warn = vm.services[0].retirement_warn || 0; + vm.modalData.id = vm.services[0].id + vm.resetModal = true + var existingDate = new Date(vm.services[0].retires_on) + var existingUTCDate = new Date(existingDate.getTime() + existingDate.getTimezoneOffset() * 60000) + vm.modalData.date = vm.services[0].retires_on ? existingUTCDate : null + vm.modalData.warn = vm.services[0].retirement_warn || 0 } - $scope.$watch('vm.modalData.date', function(date) { - var daysBetween = moment(date).diff(moment(), 'days'); + $scope.$watch('vm.modalData.date', function (date) { + var daysBetween = moment(date).diff(moment(), 'days') - vm.visibleOptions = vm.warningOptions.filter(function(option) { - return option.value <= daysBetween; - }); - }); + vm.visibleOptions = vm.warningOptions.filter(function (option) { + return option.value <= daysBetween + }) + }) } - function save() { + function save () { var data = { action: 'retire', - resources: vm.services.map(setRetire), - }; + resources: vm.services.map(setRetire) + } - CollectionsApi.post('services', '', {}, data).then(saveSuccess, saveFailure); + CollectionsApi.post('services', '', {}, data).then(saveSuccess, saveFailure) - function saveSuccess() { - vm.close(); - EventNotifications.success(__('Scheduling retirement.')); - $state.go($state.current, {}, {reload: true}); + function saveSuccess () { + vm.close() + EventNotifications.success(__('Scheduling retirement.')) + $state.go($state.current, {}, {reload: true}) } - function saveFailure() { - EventNotifications.error(__('There was an error retiring this service.')); + function saveFailure () { + EventNotifications.error(__('There was an error retiring this service.')) } - function setRetire(service) { - const copy = angular.copy(service); - copy.date = vm.modalData.date || ''; - copy.warn = vm.modalData.warn; + function setRetire (service) { + const copy = angular.copy(service) + copy.date = vm.modalData.date || '' + copy.warn = vm.modalData.warn - return copy; + return copy } } - function cancel() { - vm.dismiss({$value: 'cancel'}); + function cancel () { + vm.dismiss({$value: 'cancel'}) } - function reset(event) { - angular.copy(event.original, this.modalData); // eslint-disable-line angular/controller-as-vm + function reset (event) { + angular.copy(event.original, this.modalData) // eslint-disable-line angular/controller-as-vm } } diff --git a/client/app/services/service-details/service-details-ansible-modal.component.js b/client/app/services/service-details/service-details-ansible-modal.component.js index ce7265105..7b737f81d 100644 --- a/client/app/services/service-details/service-details-ansible-modal.component.js +++ b/client/app/services/service-details/service-details-ansible-modal.component.js @@ -1,4 +1,4 @@ -import templateUrl from './service-details-ansible-modal.html'; +import templateUrl from './service-details-ansible-modal.html' export const ServiceDetailsAnsibleModalComponent = { controller: ComponentController, @@ -6,20 +6,20 @@ export const ServiceDetailsAnsibleModalComponent = { bindings: { resolve: '<', close: '&', - dismiss: '&', + dismiss: '&' }, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController() { - const vm = this; +function ComponentController () { + const vm = this angular.extend(vm, { - cancel: cancel, - }); + cancel: cancel + }) - function cancel() { - vm.dismiss({$value: 'cancel'}); + function cancel () { + vm.dismiss({$value: 'cancel'}) } } diff --git a/client/app/services/service-details/service-details-ansible.component.js b/client/app/services/service-details/service-details-ansible.component.js index 440a7929d..da5554628 100644 --- a/client/app/services/service-details/service-details-ansible.component.js +++ b/client/app/services/service-details/service-details-ansible.component.js @@ -1,22 +1,22 @@ /* eslint camelcase: "off" */ -import templateUrl from "./service-details-ansible.html"; +import templateUrl from './service-details-ansible.html' export const ServiceDetailsAnsibleComponent = { controller: ComponentController, controllerAs: 'vm', bindings: { - service: '<', + service: '<' }, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController(ModalService, ServicesState, lodash) { - const vm = this; - vm.$onInit = activate; - vm.$onChanges = changes; +function ComponentController (ModalService, ServicesState, lodash) { + const vm = this + vm.$onInit = activate + vm.$onChanges = changes - function activate() { + function activate () { angular.extend(vm, { // Functions fetchResources: fetchResources, @@ -27,85 +27,83 @@ function ComponentController(ModalService, ServicesState, lodash) { // Config credListConfig: credListConfig(), - playsListConfig: playsListConfig(), - }); + playsListConfig: playsListConfig() + }) } - function changes() { - fetchResources(); + function changes () { + fetchResources() } - function fetchResources() { - vm.loading = true; - const credentialTypes = ['credential_id', 'network_credential_id', 'machine_credential_id']; + function fetchResources () { + vm.loading = true + const credentialTypes = ['credential_id', 'network_credential_id', 'machine_credential_id'] if (angular.isDefined(vm.service.options.config_info)) { - vm.orcStacks = {}; + vm.orcStacks = {} vm.service.service_resources.forEach((resource) => { if (resource.name) { - const resourceName = resource.name.toLowerCase(); - vm.orcStacks[resourceName] = {}; - vm.orcStacks[resourceName].stack = lodash.find(vm.service.orchestration_stacks, {'id': resource.resource_id}); - vm.orcStacks[resourceName].resource = resource; + const resourceName = resource.name.toLowerCase() + vm.orcStacks[resourceName] = {} + vm.orcStacks[resourceName].stack = lodash.find(vm.service.orchestration_stacks, {'id': resource.resource_id}) + vm.orcStacks[resourceName].resource = resource - vm.orcStacks[resourceName].credentials = []; + vm.orcStacks[resourceName].credentials = [] credentialTypes.forEach((credential) => { if (angular.isDefined(vm.service.options.config_info[resourceName][credential])) { ServicesState.getServiceCredential(vm.service.options.config_info[resourceName][credential]).then((response) => { - response.type = response.type.substring(response.type.lastIndexOf('::') + 2, response.type.lastIndexOf('Credential')); - vm.orcStacks[resourceName].credentials.push(response); - }); + response.type = response.type.substring(response.type.lastIndexOf('::') + 2, response.type.lastIndexOf('Credential')) + vm.orcStacks[resourceName].credentials.push(response) + }) } - }); + }) ServicesState.getServiceRepository(vm.service.options.config_info[resourceName].repository_id).then((response) => { - vm.orcStacks[resourceName].repository = response; - }); + vm.orcStacks[resourceName].repository = response + }) - vm.orcStacks[resourceName].jobs = []; - vm.orcStacks[resourceName].output = {}; + vm.orcStacks[resourceName].jobs = [] + vm.orcStacks[resourceName].output = {} ServicesState.getServiceJobsStdout(vm.service.id, vm.orcStacks[resourceName].stack.id).then((response) => { - vm.orcStacks[resourceName].stdout = response.stdout || 'No standard out avaliable.'; - vm.orcStacks[resourceName].jobs = response.job_plays; + vm.orcStacks[resourceName].stdout = response.stdout || 'No standard out avaliable.' + vm.orcStacks[resourceName].jobs = response.job_plays vm.orcStacks[resourceName].jobs.forEach((item) => { - item.elapsed = vm.elapsed(item.finish_time, item.start_time); - }); - }); + item.elapsed = vm.elapsed(item.finish_time, item.start_time) + }) + }) } - }); + }) } - vm.loading = false; + vm.loading = false } - function credListConfig() { + function credListConfig () { return { showSelectBox: false, - selectionMatchProp: 'id', - }; + selectionMatchProp: 'id' + } } - function playsListConfig() { + function playsListConfig () { return { showSelectBox: false, - selectionMatchProp: 'id', - }; + selectionMatchProp: 'id' + } } - function watchLive(item) { + function watchLive (item) { const modalOptions = { component: 'serviceDetailsAnsibleModal', resolve: { item: function () { - return item; - }, - }, - }; - ModalService.open(modalOptions); + return item + } + } + } + ModalService.open(modalOptions) } - function elapsed(finish, start) { - return Math.abs(new Date(finish) - new Date(start)) / 100; + function elapsed (finish, start) { + return Math.abs(new Date(finish) - new Date(start)) / 100 } } - - diff --git a/client/app/services/service-details/service-details.component.js b/client/app/services/service-details/service-details.component.js index bb2705415..941735735 100644 --- a/client/app/services/service-details/service-details.component.js +++ b/client/app/services/service-details/service-details.component.js @@ -1,31 +1,31 @@ /* eslint camelcase: "off" */ -import './_service-details.sass'; -import templateUrl from './service-details.html'; +import './_service-details.sass' +import templateUrl from './service-details.html' export const ServiceDetailsComponent = { controller: ComponentController, controllerAs: 'vm', templateUrl, - bindings: {}, -}; + bindings: {} +} /** @ngInject */ -function ComponentController($stateParams, $state, $window, CollectionsApi, EventNotifications, Chargeback, Consoles, +function ComponentController ($stateParams, $state, $window, CollectionsApi, EventNotifications, Chargeback, Consoles, TagEditorModal, ModalService, PowerOperations, ServicesState, TaggingService, lodash, Polling, LONG_POLLING_INTERVAL, UsageGraphsService) { - const vm = this; - vm.$onInit = activate; - vm.$onDestroy = onDestroy; + const vm = this + vm.$onInit = activate + vm.$onDestroy = onDestroy - function onDestroy() { - Polling.stop('servicesPolling'); + function onDestroy () { + Polling.stop('servicesPolling') } - function activate() { - vm.permissions = ServicesState.getPermissions(); - vm.storageChartConfigOptions = {'units': __('GB'), 'chartId': 'storageChart', 'label': __('used')}; - vm.memoryChartConfigOptions = {'units': __('GB'), 'chartId': 'memoryChart', 'label': __('used')}; - vm.cpuChartConfigOptions = {'units': __('MHz'), 'chartId': 'cpuChart', 'label': __('used')}; + function activate () { + vm.permissions = ServicesState.getPermissions() + vm.storageChartConfigOptions = {'units': __('GB'), 'chartId': 'storageChart', 'label': __('used')} + vm.memoryChartConfigOptions = {'units': __('GB'), 'chartId': 'memoryChart', 'label': __('used')} + vm.cpuChartConfigOptions = {'units': __('MHz'), 'chartId': 'cpuChart', 'label': __('used')} angular.extend(vm, { serviceId: $stateParams.serviceId, @@ -62,78 +62,78 @@ function ComponentController($stateParams, $state, $window, CollectionsApi, Even headerConfig: getHeaderConfig(), resourceListConfig: { showSelectBox: false, - checkDisabled: isResourceDisabled, - }, - }); - fetchResources(vm.serviceId); - Polling.start('servicesPolling', startPollingService, LONG_POLLING_INTERVAL); + checkDisabled: isResourceDisabled + } + }) + fetchResources(vm.serviceId) + Polling.start('servicesPolling', startPollingService, LONG_POLLING_INTERVAL) } - function startPollingService() { - fetchResources(vm.serviceId, true); + function startPollingService () { + fetchResources(vm.serviceId, true) } - function viewSelected(view) { - vm.viewType = view; + function viewSelected (view) { + vm.viewType = view } - function getChartConfigs() { - const allocatedStorage = UsageGraphsService.convertBytestoGb(vm.service.aggregate_all_vm_disk_space_allocated); - const usedStorage = UsageGraphsService.convertBytestoGb(vm.service.aggregate_all_vm_disk_space_used); - let usedMemory = 0; - let usedCPU = 0; - let totalCPU = 0; - const allocatedMemory = vm.service.aggregate_all_vm_memory / 1024; // this metric is in mb + function getChartConfigs () { + const allocatedStorage = UsageGraphsService.convertBytestoGb(vm.service.aggregate_all_vm_disk_space_allocated) + const usedStorage = UsageGraphsService.convertBytestoGb(vm.service.aggregate_all_vm_disk_space_used) + let usedMemory = 0 + let usedCPU = 0 + let totalCPU = 0 + const allocatedMemory = vm.service.aggregate_all_vm_memory / 1024 // this metric is in mb if (vm.service.vms) { vm.service.vms.forEach((instance) => { - usedCPU += instance.cpu_usagemhz_rate_average_avg_over_time_period; - totalCPU += (angular.isDefined(instance.hardware.aggregate_cpu_speed) ? instance.hardware.aggregate_cpu_speed : 0); - usedMemory += instance.max_mem_usage_absolute_average_avg_over_time_period; - }); + usedCPU += instance.cpu_usagemhz_rate_average_avg_over_time_period + totalCPU += (angular.isDefined(instance.hardware.aggregate_cpu_speed) ? instance.hardware.aggregate_cpu_speed : 0) + usedMemory += instance.max_mem_usage_absolute_average_avg_over_time_period + }) } - usedMemory = UsageGraphsService.convertBytestoGb(usedMemory); - vm.cpuChart = UsageGraphsService.getChartConfig(vm.cpuChartConfigOptions, usedCPU, totalCPU); - vm.memoryChart = UsageGraphsService.getChartConfig(vm.memoryChartConfigOptions, usedMemory, allocatedMemory); - vm.storageChart = UsageGraphsService.getChartConfig(vm.storageChartConfigOptions, usedStorage, allocatedStorage); + usedMemory = UsageGraphsService.convertBytestoGb(usedMemory) + vm.cpuChart = UsageGraphsService.getChartConfig(vm.cpuChartConfigOptions, usedCPU, totalCPU) + vm.memoryChart = UsageGraphsService.getChartConfig(vm.memoryChartConfigOptions, usedMemory, allocatedMemory) + vm.storageChart = UsageGraphsService.getChartConfig(vm.storageChartConfigOptions, usedStorage, allocatedStorage) } - function fetchResources(id, refresh) { - ServicesState.getService(id, refresh).then(handleSuccess, handleFailure); + function fetchResources (id, refresh) { + ServicesState.getService(id, refresh).then(handleSuccess, handleFailure) - function handleSuccess(response) { - vm.service = response; - vm.service.credential = []; - vm.title = vm.service.name; - getListActions(); - getChartConfigs(); - Chargeback.processReports(vm.service); - vm.computeGroup = vm.createResourceGroups(vm.service); + function handleSuccess (response) { + vm.service = response + vm.service.credential = [] + vm.title = vm.service.name + getListActions() + getChartConfigs() + Chargeback.processReports(vm.service) + vm.computeGroup = vm.createResourceGroups(vm.service) TaggingService.queryAvailableTags('services/' + id + '/tags/').then((response) => { - vm.availableTags = response; - }); - vm.loading = false; + vm.availableTags = response + }) + vm.loading = false } - function handleFailure(response) { - EventNotifications.error(__('There was an error fetching this service. ') + response); + function handleFailure (response) { + EventNotifications.error(__('There was an error fetching this service. ') + response) } } - function hasCustomButtons(service) { - const actions = service.custom_actions || {}; - const groups = actions.button_groups || []; - const buttons = [].concat(actions.buttons, ...groups.map((g) => g.buttons)); + function hasCustomButtons (service) { + const actions = service.custom_actions || {} + const groups = actions.button_groups || [] + const buttons = [].concat(actions.buttons, ...groups.map((g) => g.buttons)) - return lodash.compact(buttons).length > 0; + return lodash.compact(buttons).length > 0 } - function getListActions() { - const lifeCycleActions = ServicesState.getLifeCycleCustomDropdown(setServiceRetirement, retireService); - const configActions = ServicesState.getConfigurationCustomDropdown(editService, removeService, setOwnership); - const policyActions = ServicesState.getPolicyCustomDropdown(editTags); - const listActions = []; + function getListActions () { + const lifeCycleActions = ServicesState.getLifeCycleCustomDropdown(setServiceRetirement, retireService) + const configActions = ServicesState.getConfigurationCustomDropdown(editService, removeService, setOwnership) + const policyActions = ServicesState.getPolicyCustomDropdown(editTags) + const listActions = [] if (angular.isUndefined(vm.service.type)) { const powerOptionsMenu = { @@ -142,8 +142,8 @@ function ComponentController($stateParams, $state, $window, CollectionsApi, Even icon: 'fa fa-power-off', actions: [], isDisabled: false, - tooltipText: __('Power Operations'), - }; + tooltipText: __('Power Operations') + } // TODO: once service_control rbac operations are available, gate the following actions const powerOptionsActions = [ { @@ -152,39 +152,39 @@ function ComponentController($stateParams, $state, $window, CollectionsApi, Even title: __('Start the Service'), actionFn: startService, permission: true, - isDisabled: disableStartButton(vm.service), + isDisabled: disableStartButton(vm.service) }, { name: __('Stop'), actionName: 'stop', title: __('Stop the Service'), actionFn: stopService, permission: true, - isDisabled: disableStopButton(vm.service), + isDisabled: disableStopButton(vm.service) }, { name: __('Suspend'), actionName: 'suspend', title: __('Suspend the Service'), actionFn: suspendService, permission: true, - isDisabled: disableSuspendButton(vm.service), - }, - ]; + isDisabled: disableSuspendButton(vm.service) + } + ] angular.forEach(powerOptionsActions, (menuOption) => { if (menuOption.permission) { - powerOptionsMenu.actions.push(menuOption); + powerOptionsMenu.actions.push(menuOption) } - }); + }) if (powerOptionsMenu.actions.length > 0) { - listActions.push(powerOptionsMenu); + listActions.push(powerOptionsMenu) } } if (lifeCycleActions) { - listActions.push(lifeCycleActions); + listActions.push(lifeCycleActions) } if (policyActions) { - listActions.push(policyActions); + listActions.push(policyActions) } if (configActions) { @@ -196,214 +196,214 @@ function ComponentController($stateParams, $state, $window, CollectionsApi, Even actionName: 'reconfigure', title: __('Reconfigure the Service'), actionFn: reconfigureService, - isDisabled: false, + isDisabled: false } - ); + ) } - listActions.push(configActions); + listActions.push(configActions) } - vm.listActions = listActions; + vm.listActions = listActions } - function disableStartButton(item) { - return !PowerOperations.allowStartService(item); + function disableStartButton (item) { + return !PowerOperations.allowStartService(item) } - function disableStopButton(item) { - return !PowerOperations.allowStopService(item); + function disableStopButton (item) { + return !PowerOperations.allowStopService(item) } - function disableSuspendButton(item) { - return !PowerOperations.allowSuspendService(item); + function disableSuspendButton (item) { + return !PowerOperations.allowSuspendService(item) } - function startService() { - PowerOperations.startService(vm.service); - getListActions(); + function startService () { + PowerOperations.startService(vm.service) + getListActions() } - function stopService() { - PowerOperations.stopService(vm.service); - getListActions(); + function stopService () { + PowerOperations.stopService(vm.service) + getListActions() } - function suspendService() { - PowerOperations.suspendService(vm.service); - getListActions(); + function suspendService () { + PowerOperations.suspendService(vm.service) + getListActions() } - function getHeaderConfig() { + function getHeaderConfig () { return { actionsConfig: { - actionsInclude: true, - }, - }; + actionsInclude: true + } + } } - function editService() { + function editService () { const modalOptions = { component: 'editServiceModal', resolve: { - service: function() { - return vm.service; - }, - }, - }; - ModalService.open(modalOptions); + service: function () { + return vm.service + } + } + } + ModalService.open(modalOptions) } - function editTags() { - TagEditorModal.showModal(vm.service, vm.availableTags); + function editTags () { + TagEditorModal.showModal(vm.service, vm.availableTags) } - function removeService() { - CollectionsApi.delete('services', vm.service.id).then(removeSuccess, removeFailure); + function removeService () { + CollectionsApi.delete('services', vm.service.id).then(removeSuccess, removeFailure) - function removeSuccess() { - EventNotifications.success(vm.service.name + __(' was removed.')); - $state.go('services'); + function removeSuccess () { + EventNotifications.success(vm.service.name + __(' was removed.')) + $state.go('services') } - function removeFailure(_data) { - EventNotifications.error(__('There was an error removing this service.')); + function removeFailure (_data) { + EventNotifications.error(__('There was an error removing this service.')) } } - function setOwnership() { + function setOwnership () { const modalOptions = { component: 'ownershipServiceModal', resolve: { - services: function() { - return [vm.service]; + services: function () { + return [vm.service] }, users: resolveUsers, - groups: resolveGroups, - }, - }; + groups: resolveGroups + } + } - ModalService.open(modalOptions); + ModalService.open(modalOptions) /** @ngInject */ - function resolveUsers(CollectionsApi) { - const options = {expand: 'resources', attributes: ['userid', 'name'], sort_by: 'name', sort_options: 'ignore_case'}; + function resolveUsers (CollectionsApi) { + const options = {expand: 'resources', attributes: ['userid', 'name'], sort_by: 'name', sort_options: 'ignore_case'} - return CollectionsApi.query('users', options); + return CollectionsApi.query('users', options) } /** @ngInject */ - function resolveGroups(CollectionsApi) { - const options = {expand: 'resources', attributes: ['description'], sort_by: 'description', sort_options: 'ignore_case'}; + function resolveGroups (CollectionsApi) { + const options = {expand: 'resources', attributes: ['description'], sort_by: 'description', sort_options: 'ignore_case'} - return CollectionsApi.query('groups', options); + return CollectionsApi.query('groups', options) } } - function reconfigureService() { - $state.go('services.reconfigure', {serviceId: vm.service.id}); + function reconfigureService () { + $state.go('services.reconfigure', {serviceId: vm.service.id}) } - function setServiceRetirement() { + function setServiceRetirement () { const modalOptions = { component: 'retireServiceModal', resolve: { - services: function() { - return [vm.service]; - }, - }, - }; - ModalService.open(modalOptions); + services: function () { + return [vm.service] + } + } + } + ModalService.open(modalOptions) } - function retireService() { - const data = {action: 'retire'}; - CollectionsApi.post('services', vm.service.id, {}, data).then(retireSuccess, retireFailure); + function retireService () { + const data = {action: 'retire'} + CollectionsApi.post('services', vm.service.id, {}, data).then(retireSuccess, retireFailure) - function retireSuccess() { - EventNotifications.success(vm.service.name + __(' was retired.')); - $state.go('services'); + function retireSuccess () { + EventNotifications.success(vm.service.name + __(' was retired.')) + $state.go('services') } - function retireFailure() { - EventNotifications.error(__('There was an error retiring this service.')); + function retireFailure () { + EventNotifications.error(__('There was an error retiring this service.')) } } - function createResourceGroups(service) { + function createResourceGroups (service) { return { title: __('Compute'), open: true, resourceTypeClass: 'pficon pficon-screen', emptyMessage: __('There are no Compute Resources for this service.'), - resources: service.vms || [], - }; + resources: service.vms || [] + } } - function toggleOpenResourceGroup(group) { - group.open = !group.open; + function toggleOpenResourceGroup (group) { + group.open = !group.open } - function openConsole(item) { + function openConsole (item) { if (item['supports_console?'] && item.power_state === 'on') { - Consoles.open(item.id); + Consoles.open(item.id) } } - function openCockpit(item) { + function openCockpit (item) { if (item['supports_launch_cockpit?'] && item.power_state === 'on') { - $window.open('http://' + item.ipaddresses[0] + ':9090'); + $window.open('http://' + item.ipaddresses[0] + ':9090') } } - function gotoComputeResource(resource) { - $state.go('vms.details', {vmId: resource.id}); + function gotoComputeResource (resource) { + $state.go('vms.details', {vmId: resource.id}) } - function startVM(item, isDisabled) { + function startVM (item, isDisabled) { if (!isDisabled) { - PowerOperations.startVm(item); + PowerOperations.startVm(item) } } - function stopVM(item, isDisabled) { + function stopVM (item, isDisabled) { if (!isDisabled) { - PowerOperations.stopVm(item); + PowerOperations.stopVm(item) } } - function suspendVM(item, isDisabled) { + function suspendVM (item, isDisabled) { if (!isDisabled) { - PowerOperations.suspendVm(item); + PowerOperations.suspendVm(item) } } - function retireVM(item, isDisabled) { + function retireVM (item, isDisabled) { if (!isDisabled) { - PowerOperations.retireVM(item); + PowerOperations.retireVM(item) } } - function gotoCatalogItem() { - $state.go('catalogs.details', {serviceTemplateId: vm.service.service_template.id}); + function gotoCatalogItem () { + $state.go('catalogs.details', {serviceTemplateId: vm.service.service_template.id}) } - function gotoService(service) { - $state.go('services.details', {serviceId: service.id}); + function gotoService (service) { + $state.go('services.details', {serviceId: service.id}) } - function isResourceDisabled(item) { - return item.retired; + function isResourceDisabled (item) { + return item.retired } - function processSnapshot(item) { + function processSnapshot (item) { const modalOptions = { component: 'processSnapshotsModal', resolve: { vm: () => item, - modalType: () => "create", + modalType: () => 'create' }, - size: 'lg', - }; - ModalService.open(modalOptions); + size: 'lg' + } + ModalService.open(modalOptions) } } diff --git a/client/app/services/service-explorer/service-explorer.component.js b/client/app/services/service-explorer/service-explorer.component.js index 730dd3af9..b54d60707 100644 --- a/client/app/services/service-explorer/service-explorer.component.js +++ b/client/app/services/service-explorer/service-explorer.component.js @@ -1,32 +1,32 @@ /* eslint camelcase: "off" */ -import '../../../assets/sass/_explorer.sass'; -import templateUrl from './service-explorer.html'; +import '../../../assets/sass/_explorer.sass' +import templateUrl from './service-explorer.html' export const ServiceExplorerComponent = { controller: ComponentController, controllerAs: 'vm', - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController($state, ServicesState, Language, ListView, Chargeback, TaggingService, TagEditorModal, +function ComponentController ($state, ServicesState, Language, ListView, Chargeback, TaggingService, TagEditorModal, EventNotifications, ModalService, PowerOperations, lodash, Polling, POLLING_INTERVAL) { - var vm = this; + var vm = this - vm.$onDestroy = function() { - Polling.stop('serviceListPolling'); - }; + vm.$onDestroy = function () { + Polling.stop('serviceListPolling') + } vm.$onInit = () => { - vm.permissions = ServicesState.getPermissions(); + vm.permissions = ServicesState.getPermissions() if ($state.params.filter) { - ServicesState.services.setFilters($state.params.filter); - ServicesState.services.filterApplied = true; + ServicesState.services.setFilters($state.params.filter) + ServicesState.services.filterApplied = true } else { - ServicesState.services.setFilters([]); - ServicesState.services.filterApplied = false; + ServicesState.services.setFilters([]) + ServicesState.services.filterApplied = false } - ServicesState.services.setSort({id: "created_at", title: "Created", sortType: "numeric"}, false); + ServicesState.services.setSort({id: 'created_at', title: 'Created', sortType: 'numeric'}, false) angular.extend(vm, { loading: false, title: __('Services'), @@ -56,160 +56,159 @@ function ComponentController($state, ServicesState, Language, ListView, Chargeba headerConfig: getHeaderConfig(), menuActions: getMenuActions(), serviceChildrenListConfig: createServiceChildrenListConfig(), - pollingInterval: POLLING_INTERVAL, - }); - vm.offset = 0; + pollingInterval: POLLING_INTERVAL + }) + vm.offset = 0 - Language.fixState(ServicesState.services, vm.headerConfig); + Language.fixState(ServicesState.services, vm.headerConfig) - resolveServices(vm.limit, 0); - Polling.start('serviceListPolling', pollUpdateServicesList, vm.pollingInterval); - }; + resolveServices(vm.limit, 0) + Polling.start('serviceListPolling', pollUpdateServicesList, vm.pollingInterval) + } - function getCardConfig() { + function getCardConfig () { return { multiSelect: true, selectionMatchProp: 'id', onCheckBoxChange: handleSelectionChange, - onClick: viewService, - }; + onClick: viewService + } } - function getListConfig() { + function getListConfig () { return { useExpandingRows: true, selectionMatchProp: 'id', onCheckBoxChange: handleSelectionChange, - onClick: viewService, - }; + onClick: viewService + } } - function handleSelectionChange() { - vm.selectedItemsList = vm.servicesList.filter((service) => service.selected); - vm.headerConfig.filterConfig.selectedCount = vm.selectedItemsList.length; + function handleSelectionChange () { + vm.selectedItemsList = vm.servicesList.filter((service) => service.selected) + vm.headerConfig.filterConfig.selectedCount = vm.selectedItemsList.length } - function isAnsibleService(service) { - var compareValue = angular.isDefined(service.type) ? service.type : service.name; + function isAnsibleService (service) { + var compareValue = angular.isDefined(service.type) ? service.type : service.name - return compareValue.toLowerCase().indexOf('ansible') !== -1; + return compareValue.toLowerCase().indexOf('ansible') !== -1 } - function getListActions() { - var configActions, lifeCycleActions, policyActions; - var listActions = []; + function getListActions () { + var configActions, lifeCycleActions, policyActions + var listActions = [] - lifeCycleActions = ServicesState.getLifeCycleCustomDropdown(setServiceRetirement, retireService); + lifeCycleActions = ServicesState.getLifeCycleCustomDropdown(setServiceRetirement, retireService) if (lifeCycleActions) { - listActions.push(lifeCycleActions); + listActions.push(lifeCycleActions) } - policyActions = ServicesState.getPolicyCustomDropdown(editTags); + policyActions = ServicesState.getPolicyCustomDropdown(editTags) if (policyActions) { - listActions.push(policyActions); + listActions.push(policyActions) } - configActions = ServicesState.getConfigurationCustomDropdown(editService, removeServices, setOwnership); + configActions = ServicesState.getConfigurationCustomDropdown(editService, removeServices, setOwnership) if (configActions) { - listActions.push(configActions); + listActions.push(configActions) } - return listActions; + return listActions } - function actionEnabled(actionName, item) { - var enabled = true; + function actionEnabled (actionName, item) { + var enabled = true switch (actionName) { - case "start": - enabled = PowerOperations.allowStartService(item); - break; - case "stop": - enabled = PowerOperations.allowStopService(item); - break; - case "suspend": - enabled = PowerOperations.allowSuspendService(item); - break; + case 'start': + enabled = PowerOperations.allowStartService(item) + break + case 'stop': + enabled = PowerOperations.allowStopService(item) + break + case 'suspend': + enabled = PowerOperations.allowSuspendService(item) + break } - return enabled; + return enabled } - function updateMenuActionForItemFn(action, item) { + function updateMenuActionForItemFn (action, item) { switch (action.actionName) { - case "start": - action.isVisible = !isAnsibleService(item); - break; - case "stop": - action.isVisible = !isAnsibleService(item); - break; - case "suspend": - action.isVisible = !isAnsibleService(item); - break; - case "powerOperationsDivider": - action.isVisible = !isAnsibleService(item); - break; + case 'start': + action.isVisible = !isAnsibleService(item) + break + case 'stop': + action.isVisible = !isAnsibleService(item) + break + case 'suspend': + action.isVisible = !isAnsibleService(item) + break + case 'powerOperationsDivider': + action.isVisible = !isAnsibleService(item) + break } - action.isDisabled = !actionEnabled(action.actionName, item); + action.isDisabled = !actionEnabled(action.actionName, item) } - function startService(_action, item) { - PowerOperations.startService(item); + function startService (_action, item) { + PowerOperations.startService(item) } - function stopService(_action, item) { - PowerOperations.stopService(item); + function stopService (_action, item) { + PowerOperations.stopService(item) } - function suspendService(_action, item) { - PowerOperations.suspendService(item); + function suspendService (_action, item) { + PowerOperations.suspendService(item) } - function pollUpdateServicesList() { - resolveServices(vm.limit, vm.offset, true); + function pollUpdateServicesList () { + resolveServices(vm.limit, vm.offset, true) } - function viewSelected(viewId) { - vm.viewType = viewId; + function viewSelected (viewId) { + vm.viewType = viewId } - - function getHeaderConfig() { + function getHeaderConfig () { var serviceFilterConfig = { fields: getServiceFilterFields(), resultsCount: 0, totalCount: 0, selectedCount: 0, appliedFilters: ServicesState.services.filterApplied ? ServicesState.services.getFilters() : [], - onFilterChange: filterChange, - }; + onFilterChange: filterChange + } var serviceSortConfig = { fields: getServiceSortFields(), onSortChange: sortChange, isAscending: ServicesState.services.getSort().isAscending, - currentField: ServicesState.services.getSort().currentField, - }; + currentField: ServicesState.services.getSort().currentField + } return { sortConfig: serviceSortConfig, filterConfig: serviceFilterConfig, actionsConfig: { - actionsInclude: true, - }, - }; + actionsInclude: true + } + } } - function createServiceChildrenListConfig() { + function createServiceChildrenListConfig () { return { - showSelectBox: false, - }; + showSelectBox: false + } } - function getMenuActions() { - const menu = []; - let showPowerMenu = false; + function getMenuActions () { + const menu = [] + let showPowerMenu = false if (vm.permissions.powerOn || vm.permissions.powerOff || vm.permissions.suspend) { - showPowerMenu = true; + showPowerMenu = true } const menuOptions = [ { @@ -218,7 +217,7 @@ function ComponentController($state, ServicesState, Language, ListView, Chargeba title: __('Edit Service'), actionFn: editServiceItem, isDisabled: false, - permission: vm.permissions.edit, + permission: vm.permissions.edit }, { name: __('Edit Tags'), @@ -226,7 +225,7 @@ function ComponentController($state, ServicesState, Language, ListView, Chargeba title: __('Edit Tags'), actionFn: editTagsItem, isDisabled: false, - permission: vm.permissions.editTags, + permission: vm.permissions.editTags }, { name: __('Set Ownership'), @@ -234,7 +233,7 @@ function ComponentController($state, ServicesState, Language, ListView, Chargeba title: __('Set Ownership'), actionFn: setOwnershipItem, isDisabled: false, - permission: vm.permissions.setOwnership, + permission: vm.permissions.setOwnership }, { name: __('Retire'), @@ -242,7 +241,7 @@ function ComponentController($state, ServicesState, Language, ListView, Chargeba title: __('Retire Service'), actionFn: retireServiceItem, isDisabled: false, - permission: vm.permissions.retire, + permission: vm.permissions.retire }, { name: __('Set Retirement'), @@ -250,7 +249,7 @@ function ComponentController($state, ServicesState, Language, ListView, Chargeba title: __('Set Retirement Dates'), actionFn: setServiceRetirementItem, isDisabled: false, - permission: vm.permissions.setRetireDate, + permission: vm.permissions.setRetireDate }, { name: __('Remove'), @@ -258,12 +257,12 @@ function ComponentController($state, ServicesState, Language, ListView, Chargeba title: __('Remove Service'), actionFn: removeServicesItem, isDisabled: false, - permission: vm.permissions.delete, + permission: vm.permissions.delete }, { actionName: 'powerOperationsDivider', isSeparator: true, - permission: showPowerMenu, + permission: showPowerMenu }, { name: __('Start'), @@ -271,7 +270,7 @@ function ComponentController($state, ServicesState, Language, ListView, Chargeba title: __('Start this service'), actionFn: startService, isDisabled: false, - permission: vm.permissions.powerOn, + permission: vm.permissions.powerOn }, { name: __('Stop'), @@ -279,7 +278,7 @@ function ComponentController($state, ServicesState, Language, ListView, Chargeba title: __('Stop this service'), actionFn: stopService, isDisabled: false, - permission: vm.permissions.powerOff, + permission: vm.permissions.powerOff }, { name: __('Suspend'), @@ -287,85 +286,85 @@ function ComponentController($state, ServicesState, Language, ListView, Chargeba title: __('Suspend this service'), actionFn: suspendService, isDisabled: false, - permission: vm.permissions.suspend, - }, - ]; + permission: vm.permissions.suspend + } + ] - angular.forEach(menuOptions, hasPermission); - function hasPermission(item) { + angular.forEach(menuOptions, hasPermission) + function hasPermission (item) { if (item.permission) { - menu.push(item); + menu.push(item) } } - return menu; + return menu } - function sortChange(sortId, isAscending) { - ServicesState.services.setSort(sortId, isAscending); - resolveServices(vm.limit, 0); + function sortChange (sortId, isAscending) { + ServicesState.services.setSort(sortId, isAscending) + resolveServices(vm.limit, 0) } - function viewService(item, ev) { - $state.go('services.details', {serviceId: item.id}); - ev.stopImmediatePropagation(); + function viewService (item, ev) { + $state.go('services.details', {serviceId: item.id}) + ev.stopImmediatePropagation() } // Private - function filterChange(filters) { - ServicesState.services.setFilters(filters); - resolveServices(vm.limit, 0); + function filterChange (filters) { + ServicesState.services.setFilters(filters) + resolveServices(vm.limit, 0) } - function getServiceFilterFields() { + function getServiceFilterFields () { return [ ListView.createFilterField('name', __('Name'), __('Filter by Name'), 'text'), - ListView.createFilterField('description', __('Description'), __('Filter by Description'), 'text'), + ListView.createFilterField('description', __('Description'), __('Filter by Description'), 'text') // TODO: find a way to filter on virtual attributes // ListView.createFilterField('chargeback_relative_cost', __('Relative Cost'), __('Filter by Relative Cost'), 'select', dollars), // TODO: find a good way to filter on date other than string // ListView.createFilterField('owner', __('Created'), __('Filter by Created On'), 'text'), - ]; + ] } - function getServiceSortFields() { + function getServiceSortFields () { return [ ListView.createSortField('created_at', __('Created'), 'numeric'), ListView.createSortField('name', __('Name'), 'alpha'), - ListView.createSortField('retires_on', __('Retirement Date'), 'numeric'), + ListView.createSortField('retires_on', __('Retirement Date'), 'numeric') // TODO: Find a way to sort by charback cost // ListView.createSortField('chargeback_report.used_cost_sum', __('Relative Cost'), 'alpha'), - ]; + ] } - function getFilterCount() { + function getFilterCount () { return new Promise((resolve, reject) => { ServicesState.getServicesMinimal(ServicesState.services.getFilters()) - .then(querySuccess, queryFailure); + .then(querySuccess, queryFailure) - function querySuccess(result) { - vm.filterCount = result.subcount; - vm.headerConfig.filterConfig.resultsCount = vm.filterCount; - resolve(); + function querySuccess (result) { + vm.filterCount = result.subcount + vm.headerConfig.filterConfig.resultsCount = vm.filterCount + resolve() } - function queryFailure(_error) { - vm.loading = false; - EventNotifications.error(__('There was an error loading the services.')); - reject(); + function queryFailure (_error) { + vm.loading = false + EventNotifications.error(__('There was an error loading the services.')) + reject(__('There was an error loading the services.')) } - }); + }) } - function resolveServices(limit, offset, refresh) { + function resolveServices (limit, offset, refresh) { if (!refresh) { - vm.loading = true; + vm.loading = true } else { - vm.loading = false; + vm.loading = false } - vm.offset = offset; + vm.offset = offset getFilterCount().then(() => { ServicesState.getServices( limit, @@ -373,234 +372,234 @@ function ComponentController($state, ServicesState, Language, ListView, Chargeba ServicesState.services.getFilters(), ServicesState.services.getSort().currentField, ServicesState.services.getSort().isAscending, - refresh).then(querySuccess, queryFailure); - }); - - function querySuccess(result) { - vm.loading = false; - vm.services = []; - var existingServices = (angular.isDefined(vm.servicesList) && refresh ? angular.copy(vm.servicesList) : []); - vm.selectedItemsList = []; - vm.headerConfig.filterConfig.totalCount = result.subcount; - vm.headerConfig.filterConfig.selectedCount = 0; - - angular.forEach(result.resources, function(item) { + refresh).then(querySuccess, queryFailure) + }) + + function querySuccess (result) { + vm.loading = false + vm.services = [] + var existingServices = (angular.isDefined(vm.servicesList) && refresh ? angular.copy(vm.servicesList) : []) + vm.selectedItemsList = [] + vm.headerConfig.filterConfig.totalCount = result.subcount + vm.headerConfig.filterConfig.selectedCount = 0 + + angular.forEach(result.resources, function (item) { if (angular.isUndefined(item.service_id)) { - item.disableRowExpansion = item.all_service_children.length < 1; - item.power_state = PowerOperations.getPowerState(item); - item.power = getPowerInfo(item.power_state); - angular.forEach(item.all_service_children, function(childService) { - childService.power_state = PowerOperations.getPowerState(item); - childService.power = getPowerInfo(childService.power_state); - }); + item.disableRowExpansion = item.all_service_children.length < 1 + item.power_state = PowerOperations.getPowerState(item) + item.power = getPowerInfo(item.power_state) + angular.forEach(item.all_service_children, function (childService) { + childService.power_state = PowerOperations.getPowerState(item) + childService.power = getPowerInfo(childService.power_state) + }) if (refresh) { for (var i = 0; i < existingServices.length; i++) { - var currentService = existingServices[i]; + var currentService = existingServices[i] if (currentService.id === item.id) { - item.selected = (angular.isDefined(currentService.selected) ? currentService.selected : false); - item.isExpanded = (angular.isDefined(currentService.isExpanded) ? currentService.isExpanded : false); + item.selected = (angular.isDefined(currentService.selected) ? currentService.selected : false) + item.isExpanded = (angular.isDefined(currentService.isExpanded) ? currentService.isExpanded : false) if (item.selected) { - vm.selectedItemsList.push(item); + vm.selectedItemsList.push(item) } - existingServices.splice(i, 1); - break; + existingServices.splice(i, 1) + break } } } - vm.services.push(item); + vm.services.push(item) } - }); - vm.services.forEach(Chargeback.processReports); - Chargeback.adjustRelativeCost(vm.services); - vm.servicesList = angular.copy(vm.services); + }) + vm.services.forEach(Chargeback.processReports) + Chargeback.adjustRelativeCost(vm.services) + vm.servicesList = angular.copy(vm.services) } - function getPowerInfo(powerState) { + function getPowerInfo (powerState) { const powerStates = { 'on': {icon: 'pficon-ok', tooltip: __('Power State: On')}, 'off': {icon: 'fa-power-off', tooltip: __('Power State: Off')}, - 'unknown': {icon: 'fa-question-circle', tooltip: __('Power State: Unknown')}, - }; + 'unknown': {icon: 'fa-question-circle', tooltip: __('Power State: Unknown')} + } - return (powerState !== 'on' && powerState !== 'off' ? powerStates.unknown : powerStates[powerState]); + return (powerState !== 'on' && powerState !== 'off' ? powerStates.unknown : powerStates[powerState]) } - function queryFailure(_error) { - vm.loading = false; - EventNotifications.error(__('There was an error loading the services.')); + function queryFailure (_error) { + vm.loading = false + EventNotifications.error(__('There was an error loading the services.')) } } - function listActionDisable(config, items) { - config.isDisabled = items.length <= 0; - if (config.actionName === "configuration") { + function listActionDisable (config, items) { + config.isDisabled = items.length <= 0 + if (config.actionName === 'configuration') { if (items.length > 1) { - lodash.forEach(config.actions, disableItems); + lodash.forEach(config.actions, disableItems) } else { - lodash.forEach(config.actions, enableItems); + lodash.forEach(config.actions, enableItems) } } - function disableItems(item) { - if (item.actionName === "edit") { - item.isDisabled = true; + function disableItems (item) { + if (item.actionName === 'edit') { + item.isDisabled = true } } - function enableItems(item) { - if (item.actionName === "edit") { - item.isDisabled = false; + function enableItems (item) { + if (item.actionName === 'edit') { + item.isDisabled = false } } } - function doEditService(service) { + function doEditService (service) { var modalOptions = { component: 'editServiceModal', resolve: { - service: function() { - return service; - }, - }, - }; - ModalService.open(modalOptions); + service: function () { + return service + } + } + } + ModalService.open(modalOptions) } - function doEditTags(services) { - var extractSharedTagsFromSelectedServices - = lodash.partial(TaggingService.findSharedTags, services); + function doEditTags (services) { + var extractSharedTagsFromSelectedServices = + lodash.partial(TaggingService.findSharedTags, services) - var launchTagEditorForSelectedServices - = lodash.partial(TagEditorModal.showModal, services); + var launchTagEditorForSelectedServices = + lodash.partial(TagEditorModal.showModal, services) return TaggingService.queryAvailableTags() .then(extractSharedTagsFromSelectedServices) - .then(launchTagEditorForSelectedServices); + .then(launchTagEditorForSelectedServices) } - function doRemoveServices(services) { + function doRemoveServices (services) { var modalOptions = { component: 'retireRemoveServiceModal', resolve: { - services: function() { - return services; - }, - modalType: function() { - return "remove"; + services: function () { + return services }, - }, - }; - ModalService.open(modalOptions); + modalType: function () { + return 'remove' + } + } + } + ModalService.open(modalOptions) } - function doSetOwnership(services) { + function doSetOwnership (services) { var modalOptions = { component: 'ownershipServiceModal', resolve: { - services: function() { - return services; + services: function () { + return services }, users: resolveUsers, - groups: resolveGroups, - }, - }; + groups: resolveGroups + } + } - ModalService.open(modalOptions); + ModalService.open(modalOptions) /** @ngInject */ - function resolveUsers(CollectionsApi) { - var options = {expand: 'resources', attributes: ['userid', 'name'], sort_by: 'name', sort_options: 'ignore_case'}; + function resolveUsers (CollectionsApi) { + var options = {expand: 'resources', attributes: ['userid', 'name'], sort_by: 'name', sort_options: 'ignore_case'} - return CollectionsApi.query('users', options); + return CollectionsApi.query('users', options) } /** @ngInject */ - function resolveGroups(CollectionsApi) { - var options = {expand: 'resources', attributes: ['description'], sort_by: 'description', sort_options: 'ignore_case'}; + function resolveGroups (CollectionsApi) { + var options = {expand: 'resources', attributes: ['description'], sort_by: 'description', sort_options: 'ignore_case'} - return CollectionsApi.query('groups', options); + return CollectionsApi.query('groups', options) } } - function doSetServiceRetirement(services) { + function doSetServiceRetirement (services) { var modalOptions = { component: 'retireServiceModal', resolve: { - services: function() { - return services; - }, - }, - }; - ModalService.open(modalOptions); + services: function () { + return services + } + } + } + ModalService.open(modalOptions) } - function doRetireService(services) { + function doRetireService (services) { var modalOptions = { component: 'retireRemoveServiceModal', resolve: { - services: function() { - return services; - }, - modalType: function() { - return "retire"; + services: function () { + return services }, - }, - }; - ModalService.open(modalOptions); + modalType: function () { + return 'retire' + } + } + } + ModalService.open(modalOptions) } - function paginationUpdate(limit, offset) { - vm.limit = limit; - vm.offset = offset; - vm.resolveServices(limit, offset); + function paginationUpdate (limit, offset) { + vm.limit = limit + vm.offset = offset + vm.resolveServices(limit, offset) } - function editService() { - doEditService(vm.selectedItemsList[0]); + function editService () { + doEditService(vm.selectedItemsList[0]) } - function editTags() { - doEditTags(vm.selectedItemsList); + function editTags () { + doEditTags(vm.selectedItemsList) } - function removeServices() { - doRemoveServices(vm.selectedItemsList); + function removeServices () { + doRemoveServices(vm.selectedItemsList) } - function setOwnership() { - doSetOwnership(vm.selectedItemsList); + function setOwnership () { + doSetOwnership(vm.selectedItemsList) } - function setServiceRetirement() { - doSetServiceRetirement(vm.selectedItemsList); + function setServiceRetirement () { + doSetServiceRetirement(vm.selectedItemsList) } - function retireService() { - doRetireService(vm.selectedItemsList); + function retireService () { + doRetireService(vm.selectedItemsList) } - function editServiceItem(_action, item) { - doEditService(item); + function editServiceItem (_action, item) { + doEditService(item) } - function editTagsItem(_action, item) { - doEditTags([item]); + function editTagsItem (_action, item) { + doEditTags([item]) } - function removeServicesItem(_action, item) { - doRemoveServices([item]); + function removeServicesItem (_action, item) { + doRemoveServices([item]) } - function setOwnershipItem(_action, item) { - doSetOwnership([item]); + function setOwnershipItem (_action, item) { + doSetOwnership([item]) } - function setServiceRetirementItem(_action, item) { - doSetServiceRetirement([item]); + function setServiceRetirementItem (_action, item) { + doSetServiceRetirement([item]) } - function retireServiceItem(_action, item) { - doRetireService([item]); + function retireServiceItem (_action, item) { + doRetireService([item]) } } diff --git a/client/app/services/services-state.service.js b/client/app/services/services-state.service.js index f29c29cb9..c18a73f02 100644 --- a/client/app/services/services-state.service.js +++ b/client/app/services/services-state.service.js @@ -1,11 +1,11 @@ /* eslint camelcase: "off" */ /** @ngInject */ -export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { - const permissions = getPermissions(); - const services = {}; +export function ServicesStateFactory (ListConfiguration, CollectionsApi, RBAC) { + const permissions = getPermissions() + const services = {} - ListConfiguration.setupListFunctions(services, {id: 'name', title: __('Name'), sortType: 'alpha'}); + ListConfiguration.setupListFunctions(services, {id: 'name', title: __('Name'), sortType: 'alpha'}) return { services: services, @@ -18,10 +18,10 @@ export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { getPermissions: getPermissions, getLifeCycleCustomDropdown: getLifeCycleCustomDropdown, getPolicyCustomDropdown: getPolicyCustomDropdown, - getConfigurationCustomDropdown: getConfigurationCustomDropdown, - }; + getConfigurationCustomDropdown: getConfigurationCustomDropdown + } - function getService(id, refresh) { + function getService (id, refresh) { const options = { attributes: [ 'name', 'guid', 'created_at', 'type', 'description', 'picture', 'picture.image_href', 'evm_owner.name', 'evm_owner.userid', @@ -31,42 +31,42 @@ export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { 'chargeback_report', 'service_template', 'parent_service', 'power_state', 'power_status', 'options', 'vms.ipaddresses', 'vms.snapshots', 'vms.v_total_snapshots', 'vms.v_snapshot_newest_name', 'vms.v_snapshot_newest_timestamp', 'vms.v_snapshot_newest_total_size', 'vms.supports_console?', 'vms.supports_launch_cockpit?', 'vms.max_mem_usage_absolute_average_avg_over_time_period', 'vms.hardware', - 'vms.hardware.aggregate_cpu_speed', 'vms.cpu_usagemhz_rate_average_avg_over_time_period', + 'vms.hardware.aggregate_cpu_speed', 'vms.cpu_usagemhz_rate_average_avg_over_time_period' ], expand: ['vms', 'orchestration_stacks'], - auto_refresh: refresh, - }; + auto_refresh: refresh + } - return CollectionsApi.get('services', id, options); + return CollectionsApi.get('services', id, options) } - function getServiceCredential(credentialId) { - return CollectionsApi.get('authentications', credentialId, {}); + function getServiceCredential (credentialId) { + return CollectionsApi.get('authentications', credentialId, {}) } - function getServiceRepository(repositoryId) { - return CollectionsApi.get('configuration_script_sources', repositoryId, {}); + function getServiceRepository (repositoryId) { + return CollectionsApi.get('configuration_script_sources', repositoryId, {}) } - function getServiceJobsStdout(serviceId, stackId) { + function getServiceJobsStdout (serviceId, stackId) { const options = { attributes: ['job_plays', 'stdout'], - format_attributes: 'stdout=html', - }; + format_attributes: 'stdout=html' + } - return CollectionsApi.get(`services/${serviceId}/orchestration_stacks`, stackId, options); + return CollectionsApi.get(`services/${serviceId}/orchestration_stacks`, stackId, options) } // Returns minimal data for the services matching the current filters, useful for getting a filter count - function getServicesMinimal(filters) { + function getServicesMinimal (filters) { const options = { - filter: getQueryFilters(filters), - }; + filter: getQueryFilters(filters) + } - return CollectionsApi.query('services', options); + return CollectionsApi.query('services', options) } - function getServices(limit, offset, filters, sortField, sortAscending, refresh) { + function getServices (limit, offset, filters, sortField, sortAscending, refresh) { const options = { expand: 'resources', limit: limit, @@ -85,22 +85,22 @@ export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { 'all_vms', 'custom_actions', 'service_resources', - 'tags', + 'tags' ], filter: getQueryFilters(filters), - auto_refresh: refresh, - }; + auto_refresh: refresh + } if (angular.isDefined(sortField)) { - options.sort_by = services.getSort().currentField.id; - options.sort_options = services.getSort().currentField.sortType === 'alpha' ? 'ignore_case' : ''; - options.sort_order = sortAscending ? 'asc' : 'desc'; + options.sort_by = services.getSort().currentField.id + options.sort_options = services.getSort().currentField.sortType === 'alpha' ? 'ignore_case' : '' + options.sort_order = sortAscending ? 'asc' : 'desc' } - return CollectionsApi.query('services', options); + return CollectionsApi.query('services', options) } - function getPermissions() { + function getPermissions () { return { edit: RBAC.hasAny(['service_admin', 'service_edit']), delete: RBAC.hasAny(['service_admin', 'service_delete']), @@ -128,13 +128,13 @@ export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { storage_show_list: RBAC.has('storage_show_list'), // Display Lists of Datastores instance_show: RBAC.has('instance_show'), // Display Individual Instances related to a CI vm_drift: RBAC.has('vm_drift'), // Displays VMs Drift - vm_check_compliance: RBAC.has('vm_check_compliance'), // Check Compliance of Last Known Configuration - }; + vm_check_compliance: RBAC.has('vm_check_compliance') // Check Compliance of Last Known Configuration + } } - function getLifeCycleCustomDropdown(setServiceRetirementFn, retireServiceFn) { - let lifeCycleActions; - const clockIcon = 'fa fa-clock-o'; + function getLifeCycleCustomDropdown (setServiceRetirementFn, retireServiceFn) { + let lifeCycleActions + const clockIcon = 'fa fa-clock-o' if (permissions.retire || permissions.setRetireDate) { lifeCycleActions = { @@ -143,8 +143,8 @@ export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { icon: 'fa fa-recycle', actions: [], isDisabled: false, - tooltipText: __('Lifecycle'), - }; + tooltipText: __('Lifecycle') + } const lifecycleOptions = [ { icon: clockIcon, @@ -153,7 +153,7 @@ export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { title: __('Set Retirement'), actionFn: setServiceRetirementFn, permission: permissions.setRetireDate, - isDisabled: false, + isDisabled: false }, { title: __('Retire'), @@ -169,28 +169,28 @@ export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { confirmationOkStyle: 'primary', confirmationId: 'retireServiceConfirmId', permission: permissions.retire, - isDisabled: false, - }, - ]; - lifeCycleActions.actions = checkMenuPermissions(lifecycleOptions); + isDisabled: false + } + ] + lifeCycleActions.actions = checkMenuPermissions(lifecycleOptions) } - return lifeCycleActions; + return lifeCycleActions } - function checkMenuPermissions(menuOptions) { - const menu = []; + function checkMenuPermissions (menuOptions) { + const menu = [] angular.forEach(menuOptions, (menuOption) => { if (menuOption.permission) { - menu.push(menuOption); + menu.push(menuOption) } - }); + }) - return menu; + return menu } - function getPolicyCustomDropdown(editTagsFn) { - let policyActions; + function getPolicyCustomDropdown (editTagsFn) { + let policyActions if (permissions.editTags) { policyActions = { @@ -205,18 +205,18 @@ export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { actionName: 'editTags', title: __('Edit Tags'), actionFn: editTagsFn, - isDisabled: false, - }, + isDisabled: false + } ], - isDisabled: false, - }; + isDisabled: false + } } - return policyActions; + return policyActions } - function getConfigurationCustomDropdown(editServiceFn, removeServicesFn, setOwnershipFn) { - let configActions; + function getConfigurationCustomDropdown (editServiceFn, removeServicesFn, setOwnershipFn) { + let configActions if (permissions.edit || permissions.delete || permissions.setOwnership) { configActions = { @@ -225,8 +225,8 @@ export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { icon: 'fa fa-cog', actions: [], isDisabled: false, - tooltipText: __('Configuration'), - }; + tooltipText: __('Configuration') + } const configMenuOptions = [ { @@ -236,7 +236,7 @@ export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { title: __('Edit'), actionFn: editServiceFn, isDisabled: false, - permission: permissions.edit, + permission: permissions.edit }, { icon: 'pficon pficon-delete', @@ -252,7 +252,7 @@ export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { confirmationOkText: __('Yes, Remove Service'), confirmationOkStyle: 'primary', confirmationShowCancel: true, - permission: permissions.delete, + permission: permissions.delete }, { icon: 'pficon pficon-user', @@ -261,31 +261,31 @@ export function ServicesStateFactory(ListConfiguration, CollectionsApi, RBAC) { title: __('Set Ownership'), actionFn: setOwnershipFn, isDisabled: false, - permission: permissions.setOwnership, - }, - ]; - configActions.actions = checkMenuPermissions(configMenuOptions); + permission: permissions.setOwnership + } + ] + configActions.actions = checkMenuPermissions(configMenuOptions) } - return configActions; + return configActions } // Private - function getQueryFilters(filters) { - const queryFilters = ['ancestry=null']; + function getQueryFilters (filters) { + const queryFilters = ['ancestry=null'] - angular.forEach(filters, function(nextFilter) { + angular.forEach(filters, function (nextFilter) { if (nextFilter.id === 'name') { - queryFilters.push("name='%" + nextFilter.value + "%'"); + queryFilters.push("name='%" + nextFilter.value + "%'") } else { if (angular.isDefined(nextFilter.operator)) { - queryFilters.push(nextFilter.id + nextFilter.operator + nextFilter.value); + queryFilters.push(nextFilter.id + nextFilter.operator + nextFilter.value) } else { - queryFilters.push(nextFilter.id + '=' + nextFilter.value); + queryFilters.push(nextFilter.id + '=' + nextFilter.value) } } - }); + }) - return queryFilters; + return queryFilters } } diff --git a/client/app/services/services.module.js b/client/app/services/services.module.js index 61091b78c..cd2bc241a 100644 --- a/client/app/services/services.module.js +++ b/client/app/services/services.module.js @@ -1,27 +1,27 @@ -import { ConsolesFactory } from './consoles.service.js'; -import { CustomButtonComponent } from './custom-button/custom-button.component.js'; -import { DetailRevealComponent } from './detail-reveal/detail-reveal.component.js'; -import { EditServiceModalComponent } from './edit-service-modal/edit-service-modal.component.js'; -import { OwnershipServiceModalComponent } from './ownership-service-modal/ownership-service-modal.component.js'; -import { PowerOperationsFactory } from './poweroperations.service.js'; -import { ProcessSnapshotsModalComponent } from './process-snapshots-modal/process-snapshots-modal.component'; -import { RetireRemoveServiceModalComponent } from './retire-remove-service-modal/retire-remove-service-modal.component.js'; -import { RetireServiceModalComponent } from './retire-service-modal/retire-service-modal.component.js'; -import { ServiceDetailsAnsibleComponent } from './service-details/service-details-ansible.component'; -import { ServiceDetailsAnsibleModalComponent } from './service-details/service-details-ansible-modal.component'; -import { ServiceDetailsComponent } from './service-details/service-details.component'; -import { ServiceExplorerComponent } from './service-explorer/service-explorer.component.js'; -import { ServicesStateFactory } from './services-state.service.js'; -import { SharedModule } from '../shared/shared.module.js'; -import { UsageGraphsComponent } from './usage-graphs/usage-graphs.component.js'; -import { UsageGraphsFactory } from './usage-graphs/usage-graphs.service.js'; -import { VmDetailsComponent } from './vm-details/vm-details.component'; -import { VmSnapshotsComponent } from './vms/snapshots.component'; -import { VmsService } from './vms.service.js'; +import { ConsolesFactory } from './consoles.service.js' +import { CustomButtonComponent } from './custom-button/custom-button.component.js' +import { DetailRevealComponent } from './detail-reveal/detail-reveal.component.js' +import { EditServiceModalComponent } from './edit-service-modal/edit-service-modal.component.js' +import { OwnershipServiceModalComponent } from './ownership-service-modal/ownership-service-modal.component.js' +import { PowerOperationsFactory } from './poweroperations.service.js' +import { ProcessSnapshotsModalComponent } from './process-snapshots-modal/process-snapshots-modal.component' +import { RetireRemoveServiceModalComponent } from './retire-remove-service-modal/retire-remove-service-modal.component.js' +import { RetireServiceModalComponent } from './retire-service-modal/retire-service-modal.component.js' +import { ServiceDetailsAnsibleComponent } from './service-details/service-details-ansible.component' +import { ServiceDetailsAnsibleModalComponent } from './service-details/service-details-ansible-modal.component' +import { ServiceDetailsComponent } from './service-details/service-details.component' +import { ServiceExplorerComponent } from './service-explorer/service-explorer.component.js' +import { ServicesStateFactory } from './services-state.service.js' +import { SharedModule } from '../shared/shared.module.js' +import { UsageGraphsComponent } from './usage-graphs/usage-graphs.component.js' +import { UsageGraphsFactory } from './usage-graphs/usage-graphs.service.js' +import { VmDetailsComponent } from './vm-details/vm-details.component' +import { VmSnapshotsComponent } from './vms/snapshots.component' +import { VmsService } from './vms.service.js' export const ServicesModule = angular .module('app.services', [ - SharedModule, + SharedModule ]) .component('customButton', CustomButtonComponent) .component('detailReveal', DetailRevealComponent) @@ -42,4 +42,4 @@ export const ServicesModule = angular .factory('ServicesState', ServicesStateFactory) .factory('UsageGraphsService', UsageGraphsFactory) .factory('VmsService', VmsService) - .name; + .name diff --git a/client/app/services/usage-graphs/usage-graphs.component.js b/client/app/services/usage-graphs/usage-graphs.component.js index a3a3f4783..3c9d92d9e 100644 --- a/client/app/services/usage-graphs/usage-graphs.component.js +++ b/client/app/services/usage-graphs/usage-graphs.component.js @@ -1,40 +1,40 @@ -import './_usage-graphs.sass'; -import templateUrl from './usage-graphs.html'; +import './_usage-graphs.sass' +import templateUrl from './usage-graphs.html' export const UsageGraphsComponent = { bindings: { cpuChart: '<', memoryChart: '<', - storageChart: '<', + storageChart: '<' }, controller: ComponentController, controllerAs: 'vm', - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController() { - const vm = this; - vm.$onChanges = activate; +function ComponentController () { + const vm = this + vm.$onChanges = activate - function activate() { + function activate () { angular.extend(vm, { cpuDataExists: true, memoryDataExists: true, - storageDataExists: true, - }); + storageDataExists: true + }) if (vm.cpuChart.data.total === 0) { - vm.cpuDataExists = false; + vm.cpuDataExists = false } if (vm.memoryChart.data.total === 0) { - vm.memoryDataExists = false; + vm.memoryDataExists = false } if (vm.storageChart.data.total === 0) { - vm.storageDataExists = false; + vm.storageDataExists = false } - vm.availableCPU = vm.cpuChart.data.total - vm.cpuChart.data.used; - vm.availableMemory = vm.memoryChart.data.total - vm.memoryChart.data.used; - vm.availableStorage = vm.storageChart.data.total - vm.storageChart.data.used; + vm.availableCPU = vm.cpuChart.data.total - vm.cpuChart.data.used + vm.availableMemory = vm.memoryChart.data.total - vm.memoryChart.data.used + vm.availableStorage = vm.storageChart.data.total - vm.storageChart.data.used } } diff --git a/client/app/services/usage-graphs/usage-graphs.service.js b/client/app/services/usage-graphs/usage-graphs.service.js index 705be7c49..e1f1c2fe1 100644 --- a/client/app/services/usage-graphs/usage-graphs.service.js +++ b/client/app/services/usage-graphs/usage-graphs.service.js @@ -1,35 +1,35 @@ /** @ngInject */ -export function UsageGraphsFactory() { +export function UsageGraphsFactory () { var service = { convertBytestoGb: convertBytestoGb, - getChartConfig: getChartConfig, - }; + getChartConfig: getChartConfig + } - function getChartConfig(config, used, total) { - let usedValue = 0; - let totalValue = 0; + function getChartConfig (config, used, total) { + let usedValue = 0 + let totalValue = 0 if (angular.isDefined(used)) { - usedValue = used; - totalValue = total; + usedValue = used + totalValue = total } return { config: { units: config.units, - chartId: config.chartId, + chartId: config.chartId }, data: { 'used': usedValue, - 'total': totalValue, + 'total': totalValue }, - label: config.label, - }; + label: config.label + } } - function convertBytestoGb(bytes) { - return (bytes / 1073741824).toFixed(2); + function convertBytestoGb (bytes) { + return (bytes / 1073741824).toFixed(2) } - return service; + return service } diff --git a/client/app/services/vm-details/vm-details.component.js b/client/app/services/vm-details/vm-details.component.js index d321a0810..ecf09d9ac 100644 --- a/client/app/services/vm-details/vm-details.component.js +++ b/client/app/services/vm-details/vm-details.component.js @@ -1,45 +1,45 @@ /* eslint camelcase: "off" */ -import './_vm-details.sass'; -import templateUrl from './vm-details.html'; +import './_vm-details.sass' +import templateUrl from './vm-details.html' export const VmDetailsComponent = { controller: ComponentController, controllerAs: 'vm', - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController($stateParams, VmsService, ServicesState, sprintf, lodash, - EventNotifications, Polling, PowerOperations, LONG_POLLING_INTERVAL, UsageGraphsService) { - const vm = this; - vm.$onInit = activate; - vm.$onDestroy = onDestroy; - vm.hasUsageGraphs = true; - vm.startVm = startVM; - vm.stopVm = stopVM; - vm.suspendVM = suspendVM; - vm.getListActions = getListActions; - vm.pollVM = pollVM; - vm.retireVM = retireVM; - vm.getData = resolveData; - vm.storageChartConfigOptions = {'units': __('GB'), 'chartId': 'storageChart', 'label': __('used')}; - vm.memoryChartConfigOptions = {'units': __('GB'), 'chartId': 'memoryChart', 'label': __('used')}; - vm.cpuChartConfigOptions = {'units': __('MHz'), 'chartId': 'cpuChart', 'label': __('used')}; - vm.processInstanceVariables = processInstanceVariables; - - function onDestroy() { - Polling.stop('vmPolling'); +function ComponentController ($stateParams, VmsService, ServicesState, sprintf, lodash, + EventNotifications, Polling, PowerOperations, LONG_POLLING_INTERVAL, UsageGraphsService) { + const vm = this + vm.$onInit = activate + vm.$onDestroy = onDestroy + vm.hasUsageGraphs = true + vm.startVm = startVM + vm.stopVm = stopVM + vm.suspendVM = suspendVM + vm.getListActions = getListActions + vm.pollVM = pollVM + vm.retireVM = retireVM + vm.getData = resolveData + vm.storageChartConfigOptions = {'units': __('GB'), 'chartId': 'storageChart', 'label': __('used')} + vm.memoryChartConfigOptions = {'units': __('GB'), 'chartId': 'memoryChart', 'label': __('used')} + vm.cpuChartConfigOptions = {'units': __('MHz'), 'chartId': 'cpuChart', 'label': __('used')} + vm.processInstanceVariables = processInstanceVariables + + function onDestroy () { + Polling.stop('vmPolling') } - function activate() { - vm.permissions = ServicesState.getPermissions(); + function activate () { + vm.permissions = ServicesState.getPermissions() angular.extend(vm, { hasCustomButtons: hasCustomButtons, loading: true, neverText: __('Never'), noneText: __('None'), availableText: __('Available'), - notAvailable: __("Not Available"), + notAvailable: __('Not Available'), vmDetails: {}, viewType: $stateParams.viewType || 'detailsView', viewSelected: viewSelected, @@ -50,122 +50,125 @@ function ComponentController($stateParams, VmsService, ServicesState, sprintf, l // Config headerConfig: { actionsConfig: { - actionsInclude: true, - }, + actionsInclude: true + } }, - listActions: [], - }); + listActions: [] + }) - EventNotifications.info(__("The contents of this page is a function of the current users's group.")); - resolveData(); - Polling.start('vmPolling', pollVM, LONG_POLLING_INTERVAL); + EventNotifications.info(__('The contents of this page is a function of the current users\'s group.')) + resolveData() + Polling.start('vmPolling', pollVM, LONG_POLLING_INTERVAL) } // Private - function startVM() { - PowerOperations.startVm(vm.vmDetails); + function startVM () { + PowerOperations.startVm(vm.vmDetails) } - function stopVM() { - PowerOperations.stopVm(vm.vmDetails); + function stopVM () { + PowerOperations.stopVm(vm.vmDetails) } - function suspendVM() { - PowerOperations.suspendVm(vm.vmDetails); + function suspendVM () { + PowerOperations.suspendVm(vm.vmDetails) } - function retireVM() { - PowerOperations.retireVM(vm.vmDetails); + function retireVM () { + PowerOperations.retireVM(vm.vmDetails) } - function viewSelected(view) { - vm.viewType = view; + function viewSelected (view) { + vm.viewType = view } - function pollVM() { - resolveData(true); + function pollVM () { + resolveData(true) } - function resolveData(refresh) { - return VmsService.getVm($stateParams.vmId, refresh).then(handleSuccess, handleFailure); - - function handleSuccess(response) { - vm.vmDetails = response; - const allocatedStorage = UsageGraphsService.convertBytestoGb(vm.vmDetails.allocated_disk_storage); // convert bytes to gb - const usedStorage = UsageGraphsService.convertBytestoGb(vm.vmDetails.used_storage); - const totalMemory = vm.vmDetails.ram_size / 1024; - const usedMemory = UsageGraphsService.convertBytestoGb(vm.vmDetails.max_mem_usage_absolute_average_avg_over_time_period); - const usedCPU = vm.vmDetails.cpu_usagemhz_rate_average_avg_over_time_period; - const totalCPU = (angular.isDefined(vm.vmDetails.hardware.aggregate_cpu_speed) ? vm.vmDetails.hardware.aggregate_cpu_speed : 0); + function resolveData (refresh) { + return VmsService.getVm($stateParams.vmId, refresh).then(handleSuccess, handleFailure) + + function handleSuccess (response) { + vm.vmDetails = response + const allocatedStorage = UsageGraphsService.convertBytestoGb(vm.vmDetails.allocated_disk_storage) // convert bytes to gb + const usedStorage = UsageGraphsService.convertBytestoGb(vm.vmDetails.used_storage) + const totalMemory = vm.vmDetails.ram_size / 1024 + const usedMemory = UsageGraphsService.convertBytestoGb(vm.vmDetails.max_mem_usage_absolute_average_avg_over_time_period) + const usedCPU = vm.vmDetails.cpu_usagemhz_rate_average_avg_over_time_period + const totalCPU = (angular.isDefined(vm.vmDetails.hardware.aggregate_cpu_speed) ? vm.vmDetails.hardware.aggregate_cpu_speed : 0) if (response.cloud) { VmsService.getInstance(response.id).then((response) => { - vm.instance = response; - processInstanceVariables(vm.instance); - }); + vm.instance = response + processInstanceVariables(vm.instance) + }) } - hasUsageGraphs(); - vm.vmDetails.lastSyncOn = (angular.isUndefined(vm.vmDetails.last_sync_on) ? vm.neverText : vm.vmDetails.last_sync_on); - vm.vmDetails.retiresOn = (angular.isUndefined(vm.vmDetails.retires_on) ? vm.neverText : vm.vmDetails.retires_on); - vm.vmDetails.snapshotCount = defaultText(vm.vmDetails.snapshots); - vm.vmDetails.resourceAvailability = (vm.vmDetails.template === false ? vm.availableText : vm.noneText); - vm.vmDetails.driftHistory = defaultText(vm.vmDetails.drift_states); - vm.vmDetails.scanHistoryCount = defaultText(vm.vmDetails.scan_histories); - vm.vmDetails.lastComplianceStatus = (angular.isUndefined(vm.vmDetails.last_compliance_status) ? __('Never Verified') : vm.vmDetails.last_compliance_status); - vm.vmDetails.complianceHistory = (vm.vmDetails.compliances.length > 0 ? vm.availableText : vm.notAvailable); - vm.vmDetails.provisionDate = angular.isDefined(vm.vmDetails.service.miq_request) ? vm.vmDetails.service.miq_request.fulfilled_on : __('Unknown'); - vm.vmDetails.containerSpecsText = vm.vmDetails.vendor + ': ' + vm.vmDetails.hardware.cpu_total_cores + ' CPUs (' + vm.vmDetails.hardware.cpu_sockets - + ' sockets x ' + vm.vmDetails.hardware.cpu_cores_per_socket + ' core), ' + vm.vmDetails.hardware.memory_mb + ' MB'; - vm.cpuChart = UsageGraphsService.getChartConfig(vm.cpuChartConfigOptions, usedCPU, totalCPU); - vm.memoryChart = UsageGraphsService.getChartConfig(vm.memoryChartConfigOptions, usedMemory, totalMemory); - vm.storageChart = UsageGraphsService.getChartConfig(vm.storageChartConfigOptions, usedStorage, allocatedStorage); + hasUsageGraphs() + vm.vmDetails.lastSyncOn = (angular.isUndefined(vm.vmDetails.last_sync_on) ? vm.neverText : vm.vmDetails.last_sync_on) + vm.vmDetails.retiresOn = (angular.isUndefined(vm.vmDetails.retires_on) ? vm.neverText : vm.vmDetails.retires_on) + vm.vmDetails.snapshotCount = defaultText(vm.vmDetails.snapshots) + vm.vmDetails.resourceAvailability = (vm.vmDetails.template === false ? vm.availableText : vm.noneText) + vm.vmDetails.driftHistory = defaultText(vm.vmDetails.drift_states) + vm.vmDetails.scanHistoryCount = defaultText(vm.vmDetails.scan_histories) + vm.vmDetails.lastComplianceStatus = (angular.isUndefined(vm.vmDetails.last_compliance_status) ? __('Never Verified') : vm.vmDetails.last_compliance_status) + vm.vmDetails.complianceHistory = (vm.vmDetails.compliances.length > 0 ? vm.availableText : vm.notAvailable) + vm.vmDetails.provisionDate = angular.isDefined(vm.vmDetails.service.miq_request) ? vm.vmDetails.service.miq_request.fulfilled_on : __('Unknown') + vm.vmDetails.containerSpecsText = vm.vmDetails.vendor + ': ' + vm.vmDetails.hardware.cpu_total_cores + ' CPUs (' + vm.vmDetails.hardware.cpu_sockets + + ' sockets x ' + vm.vmDetails.hardware.cpu_cores_per_socket + ' core), ' + vm.vmDetails.hardware.memory_mb + ' MB' + vm.cpuChart = UsageGraphsService.getChartConfig(vm.cpuChartConfigOptions, usedCPU, totalCPU) + vm.memoryChart = UsageGraphsService.getChartConfig(vm.memoryChartConfigOptions, usedMemory, totalMemory) + vm.storageChart = UsageGraphsService.getChartConfig(vm.storageChartConfigOptions, usedStorage, allocatedStorage) if (vm.vmDetails.retired) { - EventNotifications.clearAll(lodash.find(EventNotifications.state().groups, {notificationType: 'warning'})); - EventNotifications.warn(sprintf(__("%s is a retired resource"), vm.vmDetails.name), {persistent: true, unread: false}); + EventNotifications.clearAll(lodash.find(EventNotifications.state().groups, {notificationType: 'warning'})) + EventNotifications.warn(sprintf(__('%s is a retired resource'), vm.vmDetails.name), { + persistent: true, + unread: false + }) } - getListActions(); - hasCustomButtons(); - vm.loading = false; + getListActions() + hasCustomButtons() + vm.loading = false } - function handleFailure(_error) { - EventNotifications.error(__('There was an error loading the vm details.')); + function handleFailure (_error) { + EventNotifications.error(__('There was an error loading the vm details.')) } } - function hasCustomButtons() { - const actions = vm.vmDetails.custom_actions || {}; - const groups = actions.button_groups || []; - const buttons = [].concat(actions.buttons, ...groups.map((g) => g.buttons)); + function hasCustomButtons () { + const actions = vm.vmDetails.custom_actions || {} + const groups = actions.button_groups || [] + const buttons = [].concat(actions.buttons, ...groups.map((g) => g.buttons)) - return lodash.compact(buttons).length > 0; + return lodash.compact(buttons).length > 0 } - function hasUsageGraphs() { + function hasUsageGraphs () { if (angular.isUndefined(vm.vmDetails.allocated_disk_storage) || vm.vmDetails.allocated_disk_storage === 0) { - vm.usageGraphs = false; + vm.usageGraphs = false } - if (angular.isUndefined(vm.vmDetails.max_mem_usage_absolute_average_avg_over_time_period) - || vm.vmDetails.max_mem_usage_absolute_average_avg_over_time_period === 0) { - vm.usageGraphs = false; + if (angular.isUndefined(vm.vmDetails.max_mem_usage_absolute_average_avg_over_time_period) || + vm.vmDetails.max_mem_usage_absolute_average_avg_over_time_period === 0) { + vm.usageGraphs = false } - if (angular.isUndefined(vm.vmDetails.hardware.aggregate_cpu_speed) - || vm.vmDetails.hardware.aggregate_cpu_speed === 0) { - vm.usageGraphs = false; + if (angular.isUndefined(vm.vmDetails.hardware.aggregate_cpu_speed) || + vm.vmDetails.hardware.aggregate_cpu_speed === 0) { + vm.usageGraphs = false } - return vm.usageGraphs; + return vm.usageGraphs } - function getListActions() { - vm.listActions = []; + function getListActions () { + vm.listActions = [] const powerOptionsMenu = { title: __('Power Operations'), name: __('Power'), actionName: 'powerOperations', icon: 'fa fa-power-off', actions: [], - isDisabled: false, - }; + isDisabled: false + } const powerOptionsActions = [ { icon: 'fa fa-play', @@ -174,7 +177,7 @@ function ComponentController($stateParams, VmsService, ServicesState, sprintf, l title: __('Start the Service'), actionFn: startVM, permission: vm.permissions.instanceStart, - isDisabled: vm.vmDetails.power_state === 'on', + isDisabled: vm.vmDetails.power_state === 'on' }, { icon: 'fa fa-stop', name: __('Stop'), @@ -182,7 +185,7 @@ function ComponentController($stateParams, VmsService, ServicesState, sprintf, l title: __('Stop the Service'), actionFn: stopVM, permission: vm.permissions.instanceStop, - isDisabled: vm.vmDetails.power_state !== 'on', + isDisabled: vm.vmDetails.power_state !== 'on' }, { icon: 'fa fa-pause', name: __('Suspend'), @@ -190,7 +193,7 @@ function ComponentController($stateParams, VmsService, ServicesState, sprintf, l title: __('Suspend the Service'), actionFn: suspendVM, permission: vm.permissions.instanceSuspend, - isDisabled: vm.vmDetails.power_state !== 'on', + isDisabled: vm.vmDetails.power_state !== 'on' }, { icon: 'fa fa-clock-o', name: __('Retire'), @@ -198,39 +201,38 @@ function ComponentController($stateParams, VmsService, ServicesState, sprintf, l title: __('Retire the Service'), actionFn: retireVM, permission: vm.permissions.instanceRetire, - isDisabled: vm.vmDetails.power_state !== 'on', - }, - ]; - powerOptionsActions.forEach((menuOption) => { - menuOption.permission ? powerOptionsMenu.actions.push(menuOption) : false; - }); - powerOptionsMenu.actions.length ? vm.listActions.push(powerOptionsMenu) : false; + isDisabled: vm.vmDetails.power_state !== 'on' + } + ] + powerOptionsActions.forEach((menuOption) => menuOption.permission ? powerOptionsMenu.actions.push(menuOption) : false) + if (powerOptionsMenu.actions.length) { + vm.listActions.push(powerOptionsMenu) + } - return vm.listActions; + return vm.listActions } - function defaultText(inputCount, defaultText) { - const inputArrSize = inputCount.length; - defaultText = (defaultText === null ? 'None' : defaultText); + function defaultText (inputCount, defaultText) { + const inputArrSize = inputCount.length + defaultText = (defaultText === null ? 'None' : defaultText) if (inputArrSize === 0) { - return __(defaultText); + return __(defaultText) } else { - return inputArrSize; + return inputArrSize } } + function processInstanceVariables (data) { + data.availabilityZone = (angular.isUndefined(data.availability_zone) ? vm.noneText : data.availability_zone.name) + data.cloudTenant = (angular.isUndefined(data.cloud_tenant) ? vm.noneText : data.cloud_tenant) + data.orchestrationStack = (angular.isUndefined(data.orchestration_stack) ? vm.noneText : data.orchestration_stack) + data.keyPairLabels = [] + data.key_pairs.forEach(function (keyPair) { + data.keyPairLabels.push(keyPair.name) + }) - function processInstanceVariables(data) { - data.availabilityZone = (angular.isUndefined(data.availability_zone) ? vm.noneText : data.availability_zone.name); - data.cloudTenant = (angular.isUndefined(data.cloud_tenant) ? vm.noneText : data.cloud_tenant); - data.orchestrationStack = ( angular.isUndefined(data.orchestration_stack) ? vm.noneText : data.orchestration_stack); - data.keyPairLabels = []; - data.key_pairs.forEach(function(keyPair) { - data.keyPairLabels.push(keyPair.name); - }); - - vm.vmDetails.instance = data; + vm.vmDetails.instance = data - return vm.vmDetails.instance; + return vm.vmDetails.instance } } diff --git a/client/app/services/vms.service.js b/client/app/services/vms.service.js index 101223134..6a055e405 100644 --- a/client/app/services/vms.service.js +++ b/client/app/services/vms.service.js @@ -1,13 +1,13 @@ /* eslint camelcase: "off" */ /** @ngInject */ -export function VmsService(CollectionsApi, RBAC) { - const collection = 'vms'; +export function VmsService (CollectionsApi, RBAC) { + const collection = 'vms' const sort = { isAscending: true, - currentField: {id: 'name', title: __('Name'), sortType: 'alpha'}, - }; - let filters = []; + currentField: {id: 'name', title: __('Name'), sortType: 'alpha'} + } + let filters = [] return { getVm: getVm, @@ -20,24 +20,24 @@ export function VmsService(CollectionsApi, RBAC) { getPermissions: getPermissions, revertSnapshot: revertSnapshot, createSnapshots: createSnapshots, - deleteSnapshots: deleteSnapshots, - }; + deleteSnapshots: deleteSnapshots + } - function getSnapshots(vmId) { + function getSnapshots (vmId) { const options = { attributes: [], expand: ['resources'], - filter: getQueryFilters(getFilters()), - }; + filter: getQueryFilters(getFilters()) + } - options.sort_by = getSort().currentField.id; - options.sort_options = getSort().currentField.sortType === 'alpha' ? 'ignore_case' : ''; - options.sort_order = getSort().isAscending ? 'asc' : 'desc'; + options.sort_by = getSort().currentField.id + options.sort_options = getSort().currentField.sortType === 'alpha' ? 'ignore_case' : '' + options.sort_order = getSort().isAscending ? 'asc' : 'desc' - return CollectionsApi.query(collection + '/' + vmId + '/snapshots', options); + return CollectionsApi.query(collection + '/' + vmId + '/snapshots', options) } - function getVm(vmId, refresh) { + function getVm (vmId, refresh) { const options = { attributes: [ 'advanced_settings', @@ -99,68 +99,68 @@ export function VmsService(CollectionsApi, RBAC) { 'max_mem_usage_absolute_average_avg_over_time_period', 'hardware.aggregate_cpu_speed', 'allocated_disk_storage', - 'ram_size', + 'ram_size' ], expand: [], - auto_refresh: refresh, - }; + auto_refresh: refresh + } - return CollectionsApi.query(collection + '/' + vmId, options); + return CollectionsApi.query(collection + '/' + vmId, options) } - function setSort(currentField, isAscending) { - sort.isAscending = isAscending; - sort.currentField = currentField; + function setSort (currentField, isAscending) { + sort.isAscending = isAscending + sort.currentField = currentField } - function getSort() { - return sort; + function getSort () { + return sort } - function setFilters(filterArray) { - filters = filterArray; + function setFilters (filterArray) { + filters = filterArray } - function getFilters() { - return filters; + function getFilters () { + return filters } - function getPermissions() { + function getPermissions () { return { create: RBAC.hasAny(['vm_snapshot_add']), delete: RBAC.hasAny(['vm_snapshot_delete']), deleteAll: RBAC.hasAny(['vm_snapshot_delete_all']), - revert: RBAC.hasAny(['vm_snapshot_revert']), - }; + revert: RBAC.hasAny(['vm_snapshot_revert']) + } } - function deleteSnapshots(vmId, data) { + function deleteSnapshots (vmId, data) { const options = { - "action": "delete", - "resources": data, - }; + 'action': 'delete', + 'resources': data + } - return CollectionsApi.post(collection + '/' + vmId + '/snapshots/', null, {}, options); + return CollectionsApi.post(collection + '/' + vmId + '/snapshots/', null, {}, options) } - function createSnapshots(vmId, data) { + function createSnapshots (vmId, data) { const options = { - "action": "create", - "resources": [data], - }; + 'action': 'create', + 'resources': [data] + } - return CollectionsApi.post(collection + '/' + vmId + '/snapshots/', null, {}, options); + return CollectionsApi.post(collection + '/' + vmId + '/snapshots/', null, {}, options) } - function revertSnapshot(vmId, snapshotId) { + function revertSnapshot (vmId, snapshotId) { const options = { - "action": "revert", - }; + 'action': 'revert' + } - return CollectionsApi.post(collection + '/' + vmId + '/snapshots/' + snapshotId, null, {}, options); + return CollectionsApi.post(collection + '/' + vmId + '/snapshots/' + snapshotId, null, {}, options) } - function getInstance(vmId) { + function getInstance (vmId) { const options = { attributes: [ 'availability_zone', @@ -177,25 +177,25 @@ export function VmsService(CollectionsApi, RBAC) { 'network_routers', 'miq_provision_template', 'orchestration_stack', - 'security_groups', - ], - }; + 'security_groups' + ] + } - return CollectionsApi.get('instances', vmId, options); + return CollectionsApi.get('instances', vmId, options) } // Private - function getQueryFilters(filters) { - const queryFilters = []; + function getQueryFilters (filters) { + const queryFilters = [] filters.forEach((nextFilter) => { if (nextFilter.id === 'name' || nextFilter.id === 'description') { - queryFilters.push(nextFilter.id + "='%" + nextFilter.value + "%'"); + queryFilters.push(nextFilter.id + "='%" + nextFilter.value + "%'") } else { - queryFilters.push(nextFilter.id + '=' + nextFilter.value); + queryFilters.push(nextFilter.id + '=' + nextFilter.value) } - }); + }) - return queryFilters; + return queryFilters } } diff --git a/client/app/services/vms/snapshots.component.js b/client/app/services/vms/snapshots.component.js index 2d9f94eb3..7a9bec657 100644 --- a/client/app/services/vms/snapshots.component.js +++ b/client/app/services/vms/snapshots.component.js @@ -1,6 +1,6 @@ /* eslint camelcase: "off", no-undef: "off" */ -import './_snapshots.sass'; -import templateUrl from './snapshots.html'; +import './_snapshots.sass' +import templateUrl from './snapshots.html' export const VmSnapshotsComponent = { templateUrl, @@ -8,16 +8,16 @@ export const VmSnapshotsComponent = { controllerAs: 'vm', bindToController: true, bindings: { - vmId: '<', - }, -}; + vmId: '<' + } +} /** @ngInject */ -function ComponentController(VmsService, sprintf, EventNotifications, ListView, ModalService, lodash) { - const vm = this; +function ComponentController (VmsService, sprintf, EventNotifications, ListView, ModalService, lodash) { + const vm = this - vm.$onInit = function() { - vm.permissions = VmsService.getPermissions(); + vm.$onInit = function () { + vm.permissions = VmsService.getPermissions() angular.extend(vm, { title: __('Snapshots'), @@ -37,96 +37,96 @@ function ComponentController(VmsService, sprintf, EventNotifications, ListView, listConfig: getListConfig(), menuActions: getMenuActions(), listActions: getListActions(), - toolbarConfig: getToolbarConfig(), - }); - resolveSnapshots(); - resolveVm(); - }; + toolbarConfig: getToolbarConfig() + }) + resolveSnapshots() + resolveVm() + } - function getToolbarConfig() { + function getToolbarConfig () { return { filterConfig: getFilterConfig(), sortConfig: getSortConfig(), actionsConfig: { - actionsInclude: true, - }, - }; + actionsInclude: true + } + } } - function getListConfig() { + function getListConfig () { return { showSelectBox: false, selectionMatchProp: 'id', - onClick: angular.noop(), - }; + onClick: angular.noop() + } } - function getMenuActions() { + function getMenuActions () { const menuActions = [{ name: __('Revert'), actionName: 'revert', title: __('Revert Snapshot'), actionFn: revertSnapshot, isDisabled: true, - permissions: vm.permissions.revert, + permissions: vm.permissions.revert }, { name: __('Delete'), actionName: 'delete', title: __('Delete Snapshot'), actionFn: deleteSnapshot, - permissions: vm.permissions.delete, - }]; + permissions: vm.permissions.delete + }] - return menuActions.filter((item) => item.permissions); + return menuActions.filter((item) => item.permissions) } - function updateMenuActionForItemFn(action, item) { + function updateMenuActionForItemFn (action, item) { if (action.actionName === 'revert') { - action.isDisabled = !item.current && angular.isUndefined(item.parent_uid); + action.isDisabled = !item.current && angular.isUndefined(item.parent_uid) } } - function getFilterConfig() { + function getFilterConfig () { return { fields: [ ListView.createFilterField('name', __('Name'), __('Filter by Name'), 'text'), - ListView.createFilterField('description', __('Description'), __('Filter by Description'), 'text'), + ListView.createFilterField('description', __('Description'), __('Filter by Description'), 'text') ], resultsCount: 0, appliedFilters: VmsService.getFilters(), - onFilterChange: filterChange, - }; + onFilterChange: filterChange + } } - function getSortConfig() { + function getSortConfig () { return { fields: [ ListView.createSortField('name', __('Name'), 'alpha'), ListView.createSortField('create_time', __('Created'), 'numeric'), - ListView.createSortField('updated_on', __('Updated'), 'numeric'), + ListView.createSortField('updated_on', __('Updated'), 'numeric') ], onSortChange: sortChange, isAscending: VmsService.getSort().isAscending, - currentField: VmsService.getSort().currentField, - }; + currentField: VmsService.getSort().currentField + } } - function getListActions() { + function getListActions () { const listActions = [{ name: __('Create Snapshot'), actionName: 'create', title: __('Create snapshot'), actionFn: processSnapshot, isDisabled: false, - permissions: vm.permissions.create, + permissions: vm.permissions.create }, { name: __('Delete All Snapshots'), actionName: 'delete', title: __('Delete all snapshots'), actionFn: deleteSnapshot, isDisabled: false, - permissions: vm.permissions.deleteAll, - }]; + permissions: vm.permissions.deleteAll + }] return { title: __('Configuration'), @@ -134,161 +134,161 @@ function ComponentController(VmsService, sprintf, EventNotifications, ListView, actionName: 'configuration', icon: 'fa fa-cog', isDisabled: false, - actions: listActions.filter((item) => item.permissions), - }; + actions: listActions.filter((item) => item.permissions) + } } - function deleteSnapshots() { - cancelDelete(); - VmsService.deleteSnapshots(vm.vm.id, vm.snapshotsToRemove).then(success, failure); + function deleteSnapshots () { + cancelDelete() + VmsService.deleteSnapshots(vm.vm.id, vm.snapshotsToRemove).then(success, failure) - function success(response) { - EventNotifications.batch(response.results, __('Deleting snapshot.'), __('Error deleting snapshot.')); - vm.snapshotsToRemove = undefined; - resolveSnapshots(); + function success (response) { + EventNotifications.batch(response.results, __('Deleting snapshot.'), __('Error deleting snapshot.')) + vm.snapshotsToRemove = undefined + resolveSnapshots() } - function failure(response) { - EventNotifications.error(response.data.error.message); + function failure (response) { + EventNotifications.error(response.data.error.message) } } - function cancelDelete() { - vm.deleteModal = false; + function cancelDelete () { + vm.deleteModal = false } // Private - function resolveSnapshots() { - vm.loading = true; + function resolveSnapshots () { + vm.loading = true - VmsService.getSnapshots(vm.vmId).then(success, failure); + VmsService.getSnapshots(vm.vmId).then(success, failure) - function success(response) { - vm.loading = false; - vm.toolbarConfig.filterConfig.resultsCount = response.subcount; - vm.snapshots = response.resources; + function success (response) { + vm.loading = false + vm.toolbarConfig.filterConfig.resultsCount = response.subcount + vm.snapshots = response.resources - const start = lodash.minBy(vm.snapshots, 'create_time'); - const end = lodash.maxBy(vm.snapshots, 'create_time'); + const start = lodash.minBy(vm.snapshots, 'create_time') + const end = lodash.maxBy(vm.snapshots, 'create_time') const tlSnapshots = vm.snapshots.map((item) => ({ - "date": new Date(item.create_time), - "details": {"event": item.name, "object": item.name, item}, - })); + 'date': new Date(item.create_time), + 'details': {'event': item.name, 'object': item.name, item} + })) vm.tlData = [{ - "data": tlSnapshots, - "display": true, - }]; + 'data': tlSnapshots, + 'display': true + }] vm.tlOptions = { start: new Date(start.create_time), end: new Date(end.create_time), eventShape: '\uf030', - eventHover: showTooltip, - }; + eventHover: showTooltip + } } - function failure(_error) { - vm.loading = false; - EventNotifications.error(__('There was an error loading snapshots.')); + function failure (_error) { + vm.loading = false + EventNotifications.error(__('There was an error loading snapshots.')) } } - function resolveVm() { - VmsService.getVm(vm.vmId).then(success, failure); + function resolveVm () { + VmsService.getVm(vm.vmId).then(success, failure) - function success(response) { - vm.vm = response; + function success (response) { + vm.vm = response } - function failure(_error) { - EventNotifications.error(__('There was an error loading the vm.')); + function failure (_error) { + EventNotifications.error(__('There was an error loading the vm.')) } } - function sortChange(sortId, isAscending) { - VmsService.setSort(sortId, isAscending); - resolveSnapshots(); + function sortChange (sortId, isAscending) { + VmsService.setSort(sortId, isAscending) + resolveSnapshots() } - function filterChange(filters) { - VmsService.setFilters(filters); - resolveSnapshots(); + function filterChange (filters) { + VmsService.setFilters(filters) + resolveSnapshots() } - function deleteSnapshot(_action, item) { + function deleteSnapshot (_action, item) { if (angular.isDefined(item)) { - vm.snapshotsToRemove = [{"href": item.href}]; - vm.deleteTitle = __('Delete Snapshot'); - vm.deleteMessage = sprintf(__('Please confirm, this action will delete snapshot %s'), item.name); + vm.snapshotsToRemove = [{'href': item.href}] + vm.deleteTitle = __('Delete Snapshot') + vm.deleteMessage = sprintf(__('Please confirm, this action will delete snapshot %s'), item.name) } else { - vm.snapshotsToRemove = vm.snapshots; - vm.deleteTitle = sprintf(__('Delete All Snapshots on VM %s'), vm.vm.name); - vm.deleteMessage = sprintf(__('Please confirm, this action will delete all snapshots of vm %s'), vm.vm.name); + vm.snapshotsToRemove = vm.snapshots + vm.deleteTitle = sprintf(__('Delete All Snapshots on VM %s'), vm.vm.name) + vm.deleteMessage = sprintf(__('Please confirm, this action will delete all snapshots of vm %s'), vm.vm.name) } - vm.deleteModal = true; + vm.deleteModal = true } - function revertSnapshot(_action, item) { - VmsService.revertSnapshot(vm.vm.id, item.id).then(success, failure); + function revertSnapshot (_action, item) { + VmsService.revertSnapshot(vm.vm.id, item.id).then(success, failure) - function success(response) { - EventNotifications.batch({results: [response]}, __('Reverting snapshot.'), __('Error reverting snapshot.')); - resolveSnapshots(); + function success (response) { + EventNotifications.batch({results: [response]}, __('Reverting snapshot.'), __('Error reverting snapshot.')) + resolveSnapshots() } - function failure(response) { - EventNotifications.error(response.data.error.message); + function failure (response) { + EventNotifications.error(response.data.error.message) } } - function processSnapshot(_action, _item) { + function processSnapshot (_action, _item) { const modalOptions = { component: 'processSnapshotsModal', resolve: { - vm: function() { - return vm.vm; - }, - modalType: function() { - return "create"; + vm: function () { + return vm.vm }, + modalType: function () { + return 'create' + } }, - size: 'lg', - }; - ModalService.open(modalOptions); + size: 'lg' + } + ModalService.open(modalOptions) } const showTooltip = (item) => { - d3.select('body').selectAll('.popover').remove(); + d3.select('body').selectAll('.popover').remove() - const fontSize = 12; // in pixels - const tooltipWidth = 9; // in rem + const fontSize = 12 // in pixels + const tooltipWidth = 9 // in rem const tooltip = d3 .select('body') .append('div') .attr('class', 'popover fade bottom in') .attr('role', 'tooltip') .on('mouseout', () => { - d3.select('body').selectAll('.popover').remove(); - }); - const rightOrLeftLimit = fontSize * tooltipWidth; - const direction = d3.event.pageX > rightOrLeftLimit ? 'right' : 'left'; - const left = direction === 'right' ? d3.event.pageX - rightOrLeftLimit : d3.event.pageX; - const options = {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric'}; + d3.select('body').selectAll('.popover').remove() + }) + const rightOrLeftLimit = fontSize * tooltipWidth + const direction = d3.event.pageX > rightOrLeftLimit ? 'right' : 'left' + const left = direction === 'right' ? d3.event.pageX - rightOrLeftLimit : d3.event.pageX + const options = {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric'} tooltip.html( ` <div class="arrow"></div> <div class="popover-content"> <div>Name: ${item.details.event}</div> - <div>Date: ${item.date.toLocaleDateString("en-US", options)}</div> + <div>Date: ${item.date.toLocaleDateString('en-US', options)}</div> </div> ` - ); + ) tooltip .style('left', `${left}px`) .style('top', `${d3.event.pageY + 8}px`) - .style('display', 'block'); - }; + .style('display', 'block') + } } diff --git a/client/app/shared/action-button-group/action-button-group.component.js b/client/app/shared/action-button-group/action-button-group.component.js index b1a9372a5..69668e8af 100644 --- a/client/app/shared/action-button-group/action-button-group.component.js +++ b/client/app/shared/action-button-group/action-button-group.component.js @@ -1,4 +1,4 @@ -import templateUrl from './action-button-group.html'; +import templateUrl from './action-button-group.html' export const ActionButtonGroupComponent = { controller: ComponentController, @@ -14,64 +14,62 @@ export const ActionButtonGroupComponent = { onReset: '&', onSave: '&', onOk: '&', - onCustomButton: '&', + onCustomButton: '&' }, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController(sprintf) { - const vm = this; - +function ComponentController (sprintf) { + const vm = this - vm.$onInit = function() { + vm.$onInit = function () { angular.extend(vm, { isDisabled: angular.isUndefined(vm.isDisabled) ? false : vm.isDisabled, isInverted: angular.isUndefined(vm.isInverted) ? false : vm.isInverted, - customButtonTranslated: sprintf(__("%s"), vm.customButton), + customButtonTranslated: sprintf(__('%s'), vm.customButton), isPristine: isPristine, cancelAction: cancelAction, emitOriginal: emitOriginal, saveResource: saveResource, affirmConfirmation: affirmConfirmation, - customButtonAction: customButtonAction, + customButtonAction: customButtonAction }) - ; - vm.original = angular.copy(vm.data); - }; + vm.original = angular.copy(vm.data) + } - vm.$onChanges = function(changes) { + vm.$onChanges = function (changes) { if (angular.isDefined(changes.isDisabled)) { - vm.isDisabled = changes.isDisabled.currentValue; + vm.isDisabled = changes.isDisabled.currentValue } - }; + } - function cancelAction() { - vm.onCancel(); + function cancelAction () { + vm.onCancel() } - function isPristine() { - return angular.equals(vm.data, vm.original); + function isPristine () { + return angular.equals(vm.data, vm.original) } - function emitOriginal() { + function emitOriginal () { vm.onReset({ $event: { - original: vm.original, - }, - }); + original: vm.original + } + }) } - function saveResource() { - vm.onSave(); + function saveResource () { + vm.onSave() } - function affirmConfirmation() { - vm.onOk(); + function affirmConfirmation () { + vm.onOk() } - function customButtonAction() { - vm.onCustomButton(); + function customButtonAction () { + vm.onCustomButton() } } diff --git a/client/app/shared/autofocus.directive.js b/client/app/shared/autofocus.directive.js index e1e934223..d4ea9c4ed 100644 --- a/client/app/shared/autofocus.directive.js +++ b/client/app/shared/autofocus.directive.js @@ -5,19 +5,19 @@ This directive is redundant for browsers that do but has no negative effects. */ /** @ngInject */ -export function AutofocusDirective($timeout) { +export function AutofocusDirective ($timeout) { var directive = { restrict: 'A', - link: link, - }; + link: link + } - return directive; + return directive - function link(_scope, element) { - $timeout(setFocus, 1); + function link (_scope, element) { + $timeout(setFocus, 1) - function setFocus() { - element[0].focus(); + function setFocus () { + element[0].focus() } } } diff --git a/client/app/shared/confirmation/confirmation.directive.js b/client/app/shared/confirmation/confirmation.directive.js index 5b68e23b7..550440d14 100644 --- a/client/app/shared/confirmation/confirmation.directive.js +++ b/client/app/shared/confirmation/confirmation.directive.js @@ -1,8 +1,8 @@ -import './_confirmation.sass'; -import templateUrl from './confirmation.html'; +import './_confirmation.sass' +import templateUrl from './confirmation.html' /** @ngInject */ -export function ConfirmationDirective($uibPosition, $window) { +export function ConfirmationDirective ($uibPosition, $window) { var directive = { restrict: 'AE', scope: { @@ -21,203 +21,203 @@ export function ConfirmationDirective($uibPosition, $window) { showCancel: '=?confirmationShowCancel', itemsTitle: '@?confirmationItemsTitle', items: '=?confirmationItems', - itemNameField: '@?confirmationItemNameField', + itemNameField: '@?confirmationItemNameField' }, link: link, controller: ConfirmationController, controllerAs: 'vm', - bindToController: true, - }; + bindToController: true + } - return directive; + return directive - function link(scope, element, attrs, controller) { + function link (scope, element, attrs, controller) { controller.activate({ getOffset: getOffset, getPosition: getPosition, - size: getSizeOfConfirmation(), - }); + size: getSizeOfConfirmation() + }) if (angular.isDefined(controller.triggerOnValue)) { - scope.$watch(function() { - return controller.triggerOnValue; + scope.$watch(function () { + return controller.triggerOnValue }, - function(newValue) { + function (newValue) { if (newValue === true) { - controller.onTrigger(); + controller.onTrigger() } - }); + }) } else { - element.on(attrs.confirmationTrigger || 'click', controller.onTrigger); + element.on(attrs.confirmationTrigger || 'click', controller.onTrigger) } - function getOffset() { - return $window.pageYOffset; + function getOffset () { + return $window.pageYOffset } - function getPosition() { - return $uibPosition.offset(element); + function getPosition () { + return $uibPosition.offset(element) } // Private - function getSizeOfConfirmation() { - var height, width; - var sizerMessage = attrs.confirmationMessage || __('For Sizing'); - var sizer = angular.element('<div class="confirmation__dialog"><div class="confirmation__content">' - + '<div class="confirmation__body"><p class="confirmation_message">' + sizerMessage - + '</p><div class="confirmation_buttons">' - + '<button type="button" class="confirmation__button btn-rounded">' - + __('For Sizing') - + '</button>' - + '</div></div></div></div>'); - - sizer.css('visibility', 'hidden'); - element.parent().append(sizer); - height = sizer.prop('offsetHeight'); - width = sizer.prop('offsetWidth'); - sizer.detach(); + function getSizeOfConfirmation () { + var height, width + var sizerMessage = attrs.confirmationMessage || __('For Sizing') + var sizer = angular.element('<div class="confirmation__dialog"><div class="confirmation__content">' + + '<div class="confirmation__body"><p class="confirmation_message">' + sizerMessage + + '</p><div class="confirmation_buttons">' + + '<button type="button" class="confirmation__button btn-rounded">' + + __('For Sizing') + + '</button>' + + '</div></div></div></div>') + + sizer.css('visibility', 'hidden') + element.parent().append(sizer) + height = sizer.prop('offsetHeight') + width = sizer.prop('offsetWidth') + sizer.detach() return { height: height, - width: width, - }; + width: width + } } } /** @ngInject */ - function ConfirmationController($scope, $uibModal, lodash) { - var vm = this; + function ConfirmationController ($scope, $uibModal, lodash) { + var vm = this var modalOptions = { templateUrl, - scope: $scope, - }; - - vm.top = 0; - vm.left = 0; - - vm.activate = activate; - vm.onTrigger = onTrigger; - - vm.collapseItemsThreshold = 5; - vm.toggleShowItems = function() { - vm.showItems = !vm.showItems; - }; - - function activate(api) { - angular.extend(vm, api); - vm.position = angular.isDefined(vm.position) ? vm.position : 'top-center'; - vm.title = angular.isDefined(vm.title) ? vm.title : false; - vm.message = angular.isDefined(vm.message) ? vm.message : __('Are you sure you wish to proceed?'); - vm.ok = angular.isDefined(vm.ok) ? vm.ok : 'Ok'; - vm.cancel = angular.isDefined(vm.cancel) ? vm.cancel : __('Cancel'); - vm.onCancel = angular.isDefined(vm.onCancel) ? vm.onCancel : angular.noop; - vm.okClass = angular.isDefined(vm.okStyle) ? 'btn-' + vm.okStyle : ''; - vm.confirmIf = angular.isDefined(vm.confirmIf) ? vm.confirmIf : lodash.constant(true); - vm.showCancel = angular.isDefined(vm.showCancel) ? vm.showCancel : true; + scope: $scope + } + + vm.top = 0 + vm.left = 0 + + vm.activate = activate + vm.onTrigger = onTrigger + + vm.collapseItemsThreshold = 5 + vm.toggleShowItems = function () { + vm.showItems = !vm.showItems + } + + function activate (api) { + angular.extend(vm, api) + vm.position = angular.isDefined(vm.position) ? vm.position : 'top-center' + vm.title = angular.isDefined(vm.title) ? vm.title : false + vm.message = angular.isDefined(vm.message) ? vm.message : __('Are you sure you wish to proceed?') + vm.ok = angular.isDefined(vm.ok) ? vm.ok : 'Ok' + vm.cancel = angular.isDefined(vm.cancel) ? vm.cancel : __('Cancel') + vm.onCancel = angular.isDefined(vm.onCancel) ? vm.onCancel : angular.noop + vm.okClass = angular.isDefined(vm.okStyle) ? 'btn-' + vm.okStyle : '' + vm.confirmIf = angular.isDefined(vm.confirmIf) ? vm.confirmIf : lodash.constant(true) + vm.showCancel = angular.isDefined(vm.showCancel) ? vm.showCancel : true } - function onTrigger() { - var position = getModalPosition(); - var modal; + function onTrigger () { + var position = getModalPosition() + var modal - vm.showItems = false; - vm.useCollapse = angular.isArray(vm.items) && (vm.items.length > vm.collapseItemsThreshold); + vm.showItems = false + vm.useCollapse = angular.isArray(vm.items) && (vm.items.length > vm.collapseItemsThreshold) if (vm.confirmIf()) { - vm.left = position.left; - vm.top = position.top - vm.getOffset(); + vm.left = position.left + vm.top = position.top - vm.getOffset() - modal = $uibModal.open(modalOptions); - modal.result.then(onOk, onCancel); + modal = $uibModal.open(modalOptions) + modal.result.then(onOk, onCancel) } else { - vm.onOk(); + vm.onOk() } - function onOk() { - vm.onOk(); + function onOk () { + vm.onOk() } - function onCancel() { - vm.onCancel(); + function onCancel () { + vm.onCancel() } } // Grafted in from ui.bootstraps $uibPosition.positionElements() - function getModalPosition() { - var posParts = vm.position.split('-'); - var pos0 = posParts[0]; - var pos1 = posParts[1] || 'center'; - var hostElPos = vm.getPosition(); - var targetElPos = {}; + function getModalPosition () { + var posParts = vm.position.split('-') + var pos0 = posParts[0] + var pos1 = posParts[1] || 'center' + var hostElPos = vm.getPosition() + var targetElPos = {} - var targetElWidth = vm.size.width; - var targetElHeight = vm.size.height; + var targetElWidth = vm.size.width + var targetElHeight = vm.size.height var shiftWidth = { center: widthCenter, left: widthLeft, - right: widthRight, - }; + right: widthRight + } var shiftHeight = { center: heightCenter, top: heightTop, - bottom: heightBottom, - }; + bottom: heightBottom + } switch (pos0) { case 'right': targetElPos = { top: shiftHeight[pos1](), - left: shiftWidth[pos0](), - }; - break; + left: shiftWidth[pos0]() + } + break case 'left': targetElPos = { top: shiftHeight[pos1](), - left: hostElPos.left - targetElWidth, - }; - break; + left: hostElPos.left - targetElWidth + } + break case 'bottom': targetElPos = { top: shiftHeight[pos0](), - left: shiftWidth[pos1](), - }; - break; + left: shiftWidth[pos1]() + } + break default: targetElPos = { top: hostElPos.top - targetElHeight, - left: shiftWidth[pos1](), - }; - break; + left: shiftWidth[pos1]() + } + break } - return targetElPos; + return targetElPos - function widthRight() { - return hostElPos.left + hostElPos.width; + function widthRight () { + return hostElPos.left + hostElPos.width } - function widthLeft() { - return hostElPos.left; + function widthLeft () { + return hostElPos.left } - function widthCenter() { - return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2; + function widthCenter () { + return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2 } - function heightBottom() { - return hostElPos.top + hostElPos.height; + function heightBottom () { + return hostElPos.top + hostElPos.height } - function heightTop() { - return hostElPos.top; + function heightTop () { + return hostElPos.top } - function heightCenter() { - return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2; + function heightCenter () { + return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2 } } } diff --git a/client/app/shared/custom-dropdown/custom-dropdown.component.js b/client/app/shared/custom-dropdown/custom-dropdown.component.js index da53e196a..173756d01 100644 --- a/client/app/shared/custom-dropdown/custom-dropdown.component.js +++ b/client/app/shared/custom-dropdown/custom-dropdown.component.js @@ -1,5 +1,5 @@ -import './_custom-dropdown.sass'; -import templateUrl from './custom-dropdown.html'; +import './_custom-dropdown.sass' +import templateUrl from './custom-dropdown.html' export const CustomDropdownComponent = { controller: ComponentController, @@ -9,36 +9,36 @@ export const CustomDropdownComponent = { items: '<', itemsCount: '<', onUpdate: '&', - menuRight: '@', + menuRight: '@' }, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController() { - var vm = this; +function ComponentController () { + var vm = this - vm.$onInit = function() { - vm.menuRight = vm.menuRight && (vm.menuRight === 'true' || vm.menuRight === true); + vm.$onInit = function () { + vm.menuRight = vm.menuRight && (vm.menuRight === 'true' || vm.menuRight === true) angular.extend(vm, { - handleAction: handleAction, - }); - }; + handleAction: handleAction + }) + } - vm.$onChanges = function() { - updateDisabled(); - }; + vm.$onChanges = function () { + updateDisabled() + } // Public // Private - function updateDisabled() { - vm.onUpdate({$config: vm.config, $changes: vm.items}); + function updateDisabled () { + vm.onUpdate({$config: vm.config, $changes: vm.items}) } - function handleAction(option) { + function handleAction (option) { if (!option.isDisabled) { - option.actionFn(option); + option.actionFn(option) } } } diff --git a/client/app/shared/elapsedTime.filter.js b/client/app/shared/elapsedTime.filter.js index 6e6b98c92..5601f4507 100644 --- a/client/app/shared/elapsedTime.filter.js +++ b/client/app/shared/elapsedTime.filter.js @@ -1,24 +1,24 @@ // Accepts a value of seconds, returns sting of hours minutes seconds -export function ElapsedTime() { - return function(time) { +export function ElapsedTime () { + return function (time) { if (!angular.isNumber(time) || time < 0) { - return "00:00:00"; + return '00:00:00' } - const hours = Math.floor(time / 3600); - const minutes = Math.floor((time % 3600) / 60); - const seconds = Math.floor(time % 60); + const hours = Math.floor(time / 3600) + const minutes = Math.floor((time % 3600) / 60) + const seconds = Math.floor(time % 60) if (hours > 0) { - return padding(hours) + " hours " + padding(minutes) + " min " + padding(seconds) + " sec"; + return padding(hours) + ' hours ' + padding(minutes) + ' min ' + padding(seconds) + ' sec' } else if (minutes > 0) { - return padding(minutes) + " min " + padding(seconds) + " sec"; + return padding(minutes) + ' min ' + padding(seconds) + ' sec' } else { - return padding(seconds) + " sec"; + return padding(seconds) + ' sec' } - }; + } - function padding(t) { - return t < 10 ? "0" + t : t; + function padding (t) { + return t < 10 ? '0' + t : t } } diff --git a/client/app/shared/format-bytes.filter.js b/client/app/shared/format-bytes.filter.js index 87a3192e8..6cb759d16 100644 --- a/client/app/shared/format-bytes.filter.js +++ b/client/app/shared/format-bytes.filter.js @@ -1,21 +1,21 @@ -export function formatBytes() { - return function(bytes) { +export function formatBytes () { + return function (bytes) { if (bytes === 0) { - return '0 Bytes'; + return '0 Bytes' } if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) { - return '-'; + return '-' } - var availableUnits = ['Bytes', 'kB', 'MB', 'GB', 'TB', 'PB']; - var unit = Math.floor(Math.log(bytes) / Math.log(1024)); - var val = (bytes / Math.pow(1024, Math.floor(unit))).toFixed(1); + var availableUnits = ['Bytes', 'kB', 'MB', 'GB', 'TB', 'PB'] + var unit = Math.floor(Math.log(bytes) / Math.log(1024)) + var val = (bytes / Math.pow(1024, Math.floor(unit))).toFixed(1) - return (val.match(/\.0*$/) ? val.substr(0, val.indexOf('.')) : val) + ' ' + availableUnits[unit]; - }; + return (val.match(/\.0*$/) ? val.substr(0, val.indexOf('.')) : val) + ' ' + availableUnits[unit] + } } -export function megaBytes() { - return function(bytes) { - return bytes * 1024 * 1024; - }; +export function megaBytes () { + return function (bytes) { + return bytes * 1024 * 1024 + } } diff --git a/client/app/shared/icon-list/icon-list.component.js b/client/app/shared/icon-list/icon-list.component.js index 3e59a9458..5245fe0c6 100644 --- a/client/app/shared/icon-list/icon-list.component.js +++ b/client/app/shared/icon-list/icon-list.component.js @@ -1,10 +1,10 @@ -import './_icon-list.sass'; -import templateUrl from './icon-list.html'; +import './_icon-list.sass' +import templateUrl from './icon-list.html' export const IconListComponent = { controllerAs: 'vm', bindings: { - items: '<', + items: '<' }, - templateUrl, -}; + templateUrl +} diff --git a/client/app/shared/icon-status.component.js b/client/app/shared/icon-status.component.js index 8e0e6e1ee..daf65c067 100644 --- a/client/app/shared/icon-status.component.js +++ b/client/app/shared/icon-status.component.js @@ -6,7 +6,7 @@ export const IconStatusComponent = { success: '<?', error: '<?', queued: '<?', - inprogress: '<?', + inprogress: '<?' }, template: ` <i class="pficon pficon-ok" ng-if="vm.isSuccess" @@ -30,21 +30,21 @@ export const IconStatusComponent = { tooltip-append-to-body="true" tooltip-popup-delay="1000" tooltip-placement="bottom" /> - `, -}; + ` +} /** @ngInject */ -function ComponentController(lodash) { - const vm = this; - vm.$onChanges = function() { - vm.status = lodash.capitalize(vm.status); +function ComponentController (lodash) { + const vm = this + vm.$onChanges = function () { + vm.status = lodash.capitalize(vm.status) angular.extend(vm, { isSuccess: vm.success ? vm.success.some((status) => status.toLowerCase() === vm.status.toLowerCase()) : false, isError: vm.error ? vm.error.some((status) => status.toLowerCase() === vm.status.toLowerCase()) : false, isQueued: vm.queued ? vm.queued.some((status) => status.toLowerCase() === vm.status.toLowerCase()) : false, - isInprogress: vm.inprogress ? vm.inprogress.some((status) => status.toLowerCase() === vm.status.toLowerCase()) : false, - }); - vm.isUnknown = !vm.isSuccess && !vm.isError && !vm.isQueued && !vm.isInprogress; - }; + isInprogress: vm.inprogress ? vm.inprogress.some((status) => status.toLowerCase() === vm.status.toLowerCase()) : false + }) + vm.isUnknown = !vm.isSuccess && !vm.isError && !vm.isQueued && !vm.isInprogress + } } diff --git a/client/app/shared/loading.component.js b/client/app/shared/loading.component.js index 15f4f967a..0331c3767 100644 --- a/client/app/shared/loading.component.js +++ b/client/app/shared/loading.component.js @@ -1,7 +1,7 @@ export const LoadingComponent = { bindings: { - status: '<', + status: '<' }, - template: '<div ng-if="$ctrl.status" class="drawer-pf-loading text-center">' - + '<span class="spinner spinner-xs spinner-inline"></span> {{ "Loading More" | translate }} </div>', -}; + template: '<div ng-if="$ctrl.status" class="drawer-pf-loading text-center">' + + '<span class="spinner spinner-xs spinner-inline"></span> {{ "Loading More" | translate }} </div>' +} diff --git a/client/app/shared/pagination/pagination.component.js b/client/app/shared/pagination/pagination.component.js index 6045f64ca..014fd45dc 100644 --- a/client/app/shared/pagination/pagination.component.js +++ b/client/app/shared/pagination/pagination.component.js @@ -1,5 +1,5 @@ -import './_pagination.sass'; -import templateUrl from './pagination.html'; +import './_pagination.sass' +import templateUrl from './pagination.html' export const PaginationComponent = { controller: ComponentController, @@ -8,16 +8,16 @@ export const PaginationComponent = { limit: '<', limitOptions: '<?', count: '<', - onUpdate: '&', + onUpdate: '&' }, - templateUrl, -}; + templateUrl +} /** @ngInject */ -function ComponentController() { - var vm = this; +function ComponentController () { + var vm = this - vm.$onInit = function() { + vm.$onInit = function () { angular.extend(vm, { leftBoundary: 0, rightBoundary: 0, @@ -26,84 +26,84 @@ function ComponentController() { disabled: disabled, updateLimit: updateLimit, previous: previous, - next: next, - }); + next: next + }) - establishBoundaries(); - }; + establishBoundaries() + } - vm.$onChanges = function(changes) { + vm.$onChanges = function (changes) { if (angular.isDefined(changes.limit) || angular.isDefined(changes.count)) { - vm.offset = 0; + vm.offset = 0 } - vm.lastOffset = lastOffset(); - establishBoundaries(); - }; + vm.lastOffset = lastOffset() + establishBoundaries() + } // Public - function disabled(side) { + function disabled (side) { if (vm.limit > vm.count) { - return true; + return true } if (side === 'left') { - return vm.offset === 0; + return vm.offset === 0 } if (side === 'right') { - return vm.offset === vm.lastOffset; + return vm.offset === vm.lastOffset } } - function updateLimit(newLimit) { - vm.offset = 0; - vm.limit = newLimit; - vm.lastOffset = Math.floor(vm.count / vm.limit) * vm.limit; - establishBoundaries(); - vm.onUpdate({$limit: vm.limit, $offset: vm.offset}); + function updateLimit (newLimit) { + vm.offset = 0 + vm.limit = newLimit + vm.lastOffset = Math.floor(vm.count / vm.limit) * vm.limit + establishBoundaries() + vm.onUpdate({$limit: vm.limit, $offset: vm.offset}) } - function previous(first) { + function previous (first) { if (vm.offset > 0) { if (angular.isDefined(first)) { - vm.offset = 0; + vm.offset = 0 } else { - vm.offset = vm.offset - vm.limit; + vm.offset = vm.offset - vm.limit } - establishBoundaries(); - vm.onUpdate({$limit: vm.limit, $offset: vm.offset}); + establishBoundaries() + vm.onUpdate({$limit: vm.limit, $offset: vm.offset}) } } - function next(last) { + function next (last) { if (vm.offset < vm.lastOffset) { if (angular.isDefined(last)) { - vm.offset = vm.lastOffset; + vm.offset = vm.lastOffset } else { - vm.offset = vm.offset + vm.limit; + vm.offset = vm.offset + vm.limit } - establishBoundaries(); - vm.onUpdate({$limit: vm.limit, $offset: vm.offset}); + establishBoundaries() + vm.onUpdate({$limit: vm.limit, $offset: vm.offset}) } } // Private - function establishBoundaries() { - leftBoundary(); - rightBoundary(); + function establishBoundaries () { + leftBoundary() + rightBoundary() } - function leftBoundary() { - vm.leftBoundary = vm.count === 0 ? 0 : vm.offset + 1; + function leftBoundary () { + vm.leftBoundary = vm.count === 0 ? 0 : vm.offset + 1 } - function rightBoundary() { - vm.rightBoundary = vm.offset + vm.limit; + function rightBoundary () { + vm.rightBoundary = vm.offset + vm.limit if (vm.rightBoundary > vm.count) { - vm.rightBoundary = vm.count; + vm.rightBoundary = vm.count } } - function lastOffset() { - return (vm.count % vm.limit) === 0 ? vm.count - vm.limit : Math.floor(vm.count / vm.limit) * vm.limit; + function lastOffset () { + return (vm.count % vm.limit) === 0 ? vm.count - vm.limit : Math.floor(vm.count / vm.limit) * vm.limit } } diff --git a/client/app/shared/shared.module.js b/client/app/shared/shared.module.js index 16f4c77df..544c33efa 100644 --- a/client/app/shared/shared.module.js +++ b/client/app/shared/shared.module.js @@ -1,17 +1,17 @@ -import {formatBytes, megaBytes} from "./format-bytes.filter.js"; -import {ActionButtonGroupComponent} from "./action-button-group/action-button-group.component.js"; -import {AutofocusDirective} from "./autofocus.directive.js"; -import {ConfirmationDirective} from "./confirmation/confirmation.directive.js"; -import {CustomDropdownComponent} from "./custom-dropdown/custom-dropdown.component.js"; -import {ElapsedTime} from "./elapsedTime.filter.js"; -import {IconListComponent} from "./icon-list/icon-list.component.js"; -import {IconStatusComponent} from './icon-status.component.js'; -import {LoadingComponent} from "./loading.component.js"; -import {PaginationComponent} from "./pagination/pagination.component.js"; -import {SSCardComponent} from "./ss-card/ss-card.component.js"; -import {TaggingComponent} from "./tagging/tagging.component.js"; -import {TimelineComponent} from "./timeline/timeline.component.js"; -import {substitute} from "./substitute.filter.js"; +import {formatBytes, megaBytes} from './format-bytes.filter.js' +import {ActionButtonGroupComponent} from './action-button-group/action-button-group.component.js' +import {AutofocusDirective} from './autofocus.directive.js' +import {ConfirmationDirective} from './confirmation/confirmation.directive.js' +import {CustomDropdownComponent} from './custom-dropdown/custom-dropdown.component.js' +import {ElapsedTime} from './elapsedTime.filter.js' +import {IconListComponent} from './icon-list/icon-list.component.js' +import {IconStatusComponent} from './icon-status.component.js' +import {LoadingComponent} from './loading.component.js' +import {PaginationComponent} from './pagination/pagination.component.js' +import {SSCardComponent} from './ss-card/ss-card.component.js' +import {TaggingComponent} from './tagging/tagging.component.js' +import {TimelineComponent} from './timeline/timeline.component.js' +import {substitute} from './substitute.filter.js' export const SharedModule = angular .module('app.shared', [ @@ -23,7 +23,7 @@ export const SharedModule = angular 'patternfly', 'patternfly.charts', 'patternfly.table', - 'ui.select', + 'ui.select' ]) .component('actionButtonGroup', ActionButtonGroupComponent) .component('customDropdown', CustomDropdownComponent) @@ -40,4 +40,4 @@ export const SharedModule = angular .filter('megaBytes', megaBytes) .filter('substitute', substitute) .filter('elapsedTime', ElapsedTime) - .name; + .name diff --git a/client/app/shared/ss-card/ss-card.component.js b/client/app/shared/ss-card/ss-card.component.js index 2dc263219..82603a7f8 100644 --- a/client/app/shared/ss-card/ss-card.component.js +++ b/client/app/shared/ss-card/ss-card.component.js @@ -1,13 +1,13 @@ -import './_ss-card.sass'; -import templateUrl from './ss-card.html'; +import './_ss-card.sass' +import templateUrl from './ss-card.html' export const SSCardComponent = { bindings: { header: '<', subHeader: '<', description: '<', - image: '<', + image: '<' }, controllerAs: 'vm', - templateUrl, -}; + templateUrl +} diff --git a/client/app/shared/substitute.filter.js b/client/app/shared/substitute.filter.js index 8277c41ab..a954274ff 100644 --- a/client/app/shared/substitute.filter.js +++ b/client/app/shared/substitute.filter.js @@ -1,9 +1,9 @@ /** @ngInject */ -export function substitute($interpolate) { - return function(text, context) { - text = text.replace(/\[\[/g, '{{').replace(/\]\]/g, '}}'); - var interpolateFn = $interpolate(text); +export function substitute ($interpolate) { + return function (text, context) { + text = text.replace(/\[\[/g, '{{').replace(/\]\]/g, '}}') + var interpolateFn = $interpolate(text) - return interpolateFn(context); - }; + return interpolateFn(context) + } } diff --git a/client/app/shared/tagging/tagging.component.js b/client/app/shared/tagging/tagging.component.js index 7fa66ca77..7e01666d3 100644 --- a/client/app/shared/tagging/tagging.component.js +++ b/client/app/shared/tagging/tagging.component.js @@ -1,146 +1,146 @@ -import './_tagging.sass'; -import templateUrl from './tagging.html'; +import './_tagging.sass' +import templateUrl from './tagging.html' export const TaggingComponent = { bindings: { tagsOfItem: '=', - readOnly: '=', + readOnly: '=' }, controller: TaggingController, controllerAs: 'vm', - templateUrl, -}; + templateUrl +} /** @ngInject */ -function TaggingController($scope, $filter, $q, $log, CollectionsApi, TaggingService, lodash) { - var vm = this; +function TaggingController ($scope, $filter, $q, $log, CollectionsApi, TaggingService, lodash) { + var vm = this const placeholderCategorization = { placeholder: true, categorization: { - description: __('Select a value to assign'), - }, - }; + description: __('Select a value to assign') + } + } - vm.tags = {}; + vm.tags = {} - function loadAllTagInfo() { - var deferred = $q.defer(); + function loadAllTagInfo () { + var deferred = $q.defer() - vm.loadAllTags().then(function() { - vm.loadAllCategories().then(function() { - deferred.resolve(); - }, loadAllTagsfailure); - }, loadAllCategoriesfailure); + vm.loadAllTags().then(function () { + vm.loadAllCategories().then(function () { + deferred.resolve() + }, loadAllTagsfailure) + }, loadAllCategoriesfailure) - function loadAllTagsfailure() { - deferred.reject(); + function loadAllTagsfailure () { + deferred.reject() } - function loadAllCategoriesfailure() { - deferred.reject(); + function loadAllCategoriesfailure () { + deferred.reject() } - return deferred.promise; + return deferred.promise } - vm.loadAllTags = function() { - var deferred = $q.defer(); + vm.loadAllTags = function () { + var deferred = $q.defer() - var attributes = ['categorization', 'category.id', 'category.single_value']; + var attributes = ['categorization', 'category.id', 'category.single_value'] var options = { expand: 'resources', - attributes: attributes, - }; + attributes: attributes + } - CollectionsApi.query('tags', options).then(loadSuccess, loadFailure); + CollectionsApi.query('tags', options).then(loadSuccess, loadFailure) - function loadSuccess(response) { - vm.tags.all = response.resources; - deferred.resolve(); + function loadSuccess (response) { + vm.tags.all = response.resources + deferred.resolve() } - function loadFailure() { - $log.error('There was an error loading all tags.'); - deferred.reject(); + function loadFailure () { + $log.error('There was an error loading all tags.') + deferred.reject() } - return deferred.promise; - }; + return deferred.promise + } - vm.loadAllCategories = function() { - var deferred = $q.defer(); + vm.loadAllCategories = function () { + var deferred = $q.defer() var options = { - expand: 'resources', - }; + expand: 'resources' + } - CollectionsApi.query('categories', options).then(loadSuccess, loadFailure); + CollectionsApi.query('categories', options).then(loadSuccess, loadFailure) - function loadSuccess(response) { - vm.tags.categories = lodash.sortBy(response.resources, 'description'); - vm.tags.selectedCategory = vm.tags.categories[0]; - deferred.resolve(); + function loadSuccess (response) { + vm.tags.categories = lodash.sortBy(response.resources, 'description') + vm.tags.selectedCategory = vm.tags.categories[0] + deferred.resolve() } - function loadFailure() { - $log.error('There was an error loading categories.'); - deferred.reject(); + function loadFailure () { + $log.error('There was an error loading categories.') + deferred.reject() } - return deferred.promise; - }; + return deferred.promise + } if (!vm.readOnly) { - loadAllTagInfo(); + loadAllTagInfo() } - vm.showTagDropdowns = false; + vm.showTagDropdowns = false - $scope.$watch('vm.tags.selectedCategory', function() { - vm.tags.filtered = $filter('filter')(vm.tags.all, matchCategory); + $scope.$watch('vm.tags.selectedCategory', function () { + vm.tags.filtered = $filter('filter')(vm.tags.all, matchCategory) if (vm.tags.filtered) { - vm.tags.filtered[0] = placeholderCategorization; - vm.tags.selectedTag = vm.tags.filtered[0]; - vm.showTagDropdowns = true; + vm.tags.filtered[0] = placeholderCategorization + vm.tags.selectedTag = vm.tags.filtered[0] + vm.showTagDropdowns = true } - }, true); + }, true) - function matchCategory(tag) { + function matchCategory (tag) { if (tag.category) { - return tag.category.id === vm.tags.selectedCategory.id; + return tag.category.id === vm.tags.selectedCategory.id } else { - return false; + return false } } - vm.removeTag = function(tag) { - var index = vm.tagsOfItem.indexOf(tag); + vm.removeTag = function (tag) { + var index = vm.tagsOfItem.indexOf(tag) if (index !== -1) { - vm.tagsOfItem.splice(index, 1); + vm.tagsOfItem.splice(index, 1) } - }; + } - vm.addTag = function() { + vm.addTag = function () { // Handle single_value category/tags if (vm.tags.selectedTag.category && angular.isDefined(vm.tags.selectedTag.category.single_value)) { if (vm.tags.selectedTag.category.single_value) { // Find existing tag w/ category in tags.of_item for (var i = 0; i < vm.tagsOfItem.length; i++) { - var tag = vm.tagsOfItem[i]; + var tag = vm.tagsOfItem[i] if (tag.category.id === vm.tags.selectedTag.category.id) { - vm.removeTag(tag); - break; + vm.removeTag(tag) + break } } } } - var matchingTag = $filter('filter')(vm.tagsOfItem, {id: vm.tags.selectedTag.id}); + var matchingTag = $filter('filter')(vm.tagsOfItem, {id: vm.tags.selectedTag.id}) // Add Selected Tag if (!matchingTag.length) { - var parsedTag = TaggingService.parseTag(vm.tags.selectedTag); - vm.tagsOfItem.push(parsedTag); + var parsedTag = TaggingService.parseTag(vm.tags.selectedTag) + vm.tagsOfItem.push(parsedTag) } - }; + } } diff --git a/client/app/shared/timeline/timeline.component.js b/client/app/shared/timeline/timeline.component.js index f787d361b..21365aefb 100644 --- a/client/app/shared/timeline/timeline.component.js +++ b/client/app/shared/timeline/timeline.component.js @@ -1,47 +1,47 @@ -import './_timeline.sass'; +import './_timeline.sass' export const TimelineComponent = { bindings: { data: '<', - options: '<', + options: '<' }, controller: TimelineController, - controllerAs: 'vm', -}; + controllerAs: 'vm' +} /** @ngInject */ -function TimelineController($element, $window) { - const vm = this; - const d3 = $window.d3; +function TimelineController ($element, $window) { + const vm = this + const d3 = $window.d3 - angular.element($window).on('resize', function() { - renderTimeline(); - }); + angular.element($window).on('resize', function () { + renderTimeline() + }) vm.$onChanges = (changes) => { - vm.options = changes.options.currentValue || vm.options; + vm.options = changes.options.currentValue || vm.options vm.data = changes.data.currentValue || [{ - "name": "", - "data": [ - {"date": "", "details": {"event": "", "object": ""}}, + 'name': '', + 'data': [ + {'date': '', 'details': {'event': '', 'object': ''}} ], - "display": true, - }]; + 'display': true + }] - renderTimeline(); - }; + renderTimeline() + } - function renderTimeline() { - angular.element($element[0]).find('div.timeline').remove(); - const config = buildConfig(vm.options); - buildTimeline(config, vm.data); + function renderTimeline () { + angular.element($element[0]).find('div.timeline').remove() + const config = buildConfig(vm.options) + buildTimeline(config, vm.data) } - function buildConfig(options = {}) { - const hour = 60 * 60 * 1000; - const day = 24 * hour; - const week = 7 * day; - const month = 30 * day; + function buildConfig (options = {}) { + const hour = 60 * 60 * 1000 + const day = 24 * hour + const week = 7 * day + const month = 30 * day const { start = new Date(0), @@ -61,7 +61,7 @@ function TimelineController($element, $window) { ['%I %p', (d) => d.getHours()], ['%b %d', (d) => d.getMonth() && d.getDate()], ['%b', (d) => d.getMonth()], - ['%Y', () => true], + ['%Y', () => true] ], eventHover = null, eventZoom = null, @@ -69,30 +69,30 @@ function TimelineController($element, $window) { eventLineColor = (_d, i) => { switch (i % 5) { case 0: - return "#00659c"; + return '#00659c' case 1: - return "#0088ce"; + return '#0088ce' case 2: - return "#3f9c35"; + return '#3f9c35' case 3: - return "#ec7a08"; + return '#ec7a08' case 4: - return "#cc0000"; + return '#cc0000' } }, eventColor = null, eventShape = (d) => { - if (d.hasOwnProperty("events")) { - return '\uf140'; + if (d.hasOwnProperty('events')) { + return '\uf140' } else { - return '\uf111'; + return '\uf111' } }, eventPopover = null, context = true, slider = true, - eventGrouping = 60000, - } = options; + eventGrouping = 60000 + } = options return d3.chart.timeline() .start(start) @@ -115,13 +115,13 @@ function TimelineController($element, $window) { .eventPopover(eventPopover) .context(context) .slider(slider) - .eventGrouping(eventGrouping); + .eventGrouping(eventGrouping) } - function buildTimeline(config, data) { + function buildTimeline (config, data) { d3.select($element[0]) .append('div').attr('class', 'timeline') .datum(data) - .call(config); + .call(config) } } diff --git a/client/app/skin/skin.module.js b/client/app/skin/skin.module.js index 4bb820f31..f143ffae3 100644 --- a/client/app/skin/skin.module.js +++ b/client/app/skin/skin.module.js @@ -1,20 +1,20 @@ const text = { app: { - name: 'ManageIQ Self Service', + name: 'ManageIQ Self Service' }, login: { - brand: '<strong>ManageIQ</strong> Self Service', - }, -}; + brand: '<strong>ManageIQ</strong> Self Service' + } +} export const SkinModule = angular .module('app.skin', []) .constant('Text', text) .config(configure) - .name; + .name /** @ngInject */ -function configure(routerHelperProvider, exceptionHandlerProvider) { - exceptionHandlerProvider.configure('[ManageIQ] '); - routerHelperProvider.configure({docTitle: 'ManageIQ: '}); +function configure (routerHelperProvider, exceptionHandlerProvider) { + exceptionHandlerProvider.configure('[ManageIQ] ') + routerHelperProvider.configure({docTitle: 'ManageIQ: '}) } diff --git a/client/app/states/404/404.state.js b/client/app/states/404/404.state.js index c56b959f8..8413a7850 100644 --- a/client/app/states/404/404.state.js +++ b/client/app/states/404/404.state.js @@ -1,12 +1,12 @@ -import templateUrl from './404.html'; +import templateUrl from './404.html' /** @ngInject */ -export function NotFoundState(routerHelper) { - var otherwise = '/404'; - routerHelper.configureStates(getStates(), otherwise); +export function NotFoundState (routerHelper) { + var otherwise = '/404' + routerHelper.configureStates(getStates(), otherwise) } -function getStates() { +function getStates () { return { '404': { parent: 'blank', @@ -14,8 +14,8 @@ function getStates() { templateUrl, title: '404', data: { - layout: 'blank', - }, - }, - }; + layout: 'blank' + } + } + } } diff --git a/client/app/states/about-me/about-me.state.js b/client/app/states/about-me/about-me.state.js index 9c94f1ae6..3ab19a00f 100644 --- a/client/app/states/about-me/about-me.state.js +++ b/client/app/states/about-me/about-me.state.js @@ -1,11 +1,11 @@ -import templateUrl from './about-me.html'; +import templateUrl from './about-me.html' /** @ngInject */ -export function AboutMeState(routerHelper) { - routerHelper.configureStates(getStates()); +export function AboutMeState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'about-me': { parent: 'application', @@ -13,11 +13,11 @@ function getStates() { templateUrl, controller: StateController, controllerAs: 'vm', - title: N_('About Me'), - }, - }; + title: N_('About Me') + } + } } /** @ngInject */ -function StateController() { +function StateController () { } diff --git a/client/app/states/catalogs/catalogs.state.js b/client/app/states/catalogs/catalogs.state.js index 5b619910b..9e622e3a1 100644 --- a/client/app/states/catalogs/catalogs.state.js +++ b/client/app/states/catalogs/catalogs.state.js @@ -1,15 +1,15 @@ /** @ngInject */ -export function CatalogsState(routerHelper) { - routerHelper.configureStates(getStates()); +export function CatalogsState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'catalogs': { parent: 'application', url: '/catalogs', redirectTo: 'catalogs.explorer', - template: '<ui-view></ui-view>', - }, - }; + template: '<ui-view></ui-view>' + } + } } diff --git a/client/app/states/catalogs/details/details.state.js b/client/app/states/catalogs/details/details.state.js index 3f2879e3e..ee9a774fd 100644 --- a/client/app/states/catalogs/details/details.state.js +++ b/client/app/states/catalogs/details/details.state.js @@ -1,11 +1,11 @@ -import templateUrl from './details.html'; +import templateUrl from './details.html' /** @ngInject */ -export function CatalogsDetailsState(routerHelper) { - routerHelper.configureStates(getStates()); +export function CatalogsDetailsState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'catalogs.details': { url: '/:serviceTemplateId', @@ -15,10 +15,10 @@ function getStates() { title: __('Service Template Details'), resolve: { dialogs: resolveDialogs, - serviceTemplate: resolveServiceTemplate, - }, - }, - }; + serviceTemplate: resolveServiceTemplate + } + } + } } /** @ngInject */ @@ -28,10 +28,10 @@ function getStates() { * @param {object} $stateParams * @param {object} CollectionsApi */ -function resolveServiceTemplate($stateParams, CollectionsApi) { - var options = {attributes: ['picture', 'picture.image_href']}; +function resolveServiceTemplate ($stateParams, CollectionsApi) { + var options = {attributes: ['picture', 'picture.image_href']} - return CollectionsApi.get('service_templates', $stateParams.serviceTemplateId, options); + return CollectionsApi.get('service_templates', $stateParams.serviceTemplateId, options) } /** @@ -41,58 +41,58 @@ function resolveServiceTemplate($stateParams, CollectionsApi) { * @param {object} CollectionsApi */ /** @ngInject */ -function resolveDialogs($stateParams, CollectionsApi) { - var options = {expand: 'resources', attributes: 'content'}; +function resolveDialogs ($stateParams, CollectionsApi) { + var options = {expand: 'resources', attributes: 'content'} - return CollectionsApi.query('service_templates/' + $stateParams.serviceTemplateId + '/service_dialogs', options); + return CollectionsApi.query('service_templates/' + $stateParams.serviceTemplateId + '/service_dialogs', options) } /** @ngInject */ -function Controller(dialogs, serviceTemplate, EventNotifications, ShoppingCart, DialogFieldRefresh, lodash) { - var vm = this; +function Controller (dialogs, serviceTemplate, EventNotifications, ShoppingCart, DialogFieldRefresh, lodash) { + var vm = this - vm.serviceTemplate = serviceTemplate; + vm.serviceTemplate = serviceTemplate if (dialogs.subcount > 0) { - vm.dialogs = dialogs.resources[0].content; + vm.dialogs = dialogs.resources[0].content } - vm.addToCart = addToCart; - vm.cartAllowed = ShoppingCart.allowed; - vm.addToCartEnabled = false; - vm.alreadyInCart = alreadyInCart; - vm.addToCartDisabled = addToCartDisabled; - vm.refreshField = refreshField; - vm.setDialogData = setDialogData; - vm.dialogData = {}; - - vm.dialogUrl = 'service_catalogs/' + serviceTemplate.service_template_catalog_id + '/service_templates'; - + vm.addToCart = addToCart + vm.cartAllowed = ShoppingCart.allowed + vm.addToCartEnabled = false + vm.alreadyInCart = alreadyInCart + vm.addToCartDisabled = addToCartDisabled + vm.refreshField = refreshField + vm.setDialogData = setDialogData + vm.dialogData = {} + + vm.dialogUrl = 'service_catalogs/' + serviceTemplate.service_template_catalog_id + '/service_templates' + /** * This function triggers a refresh of a single dialog field * @function refreshField * @param {object} field * @returns {Promise} */ - function refreshField(field) { - return DialogFieldRefresh.refreshDialogField(vm.dialogData, [field.name], vm.dialogUrl, vm.serviceTemplate.id); + function refreshField (field) { + return DialogFieldRefresh.refreshDialogField(vm.dialogData, [field.name], vm.dialogUrl, vm.serviceTemplate.id) } /** * Stores resulting data output from a dialog * @function setDialogData * @param {object} data */ - function setDialogData(data) { - vm.addToCartEnabled = data.validations.isValid; - vm.dialogData = data.data; + function setDialogData (data) { + vm.addToCartEnabled = data.validations.isValid + vm.dialogData = data.data } /** * Determines whether a user can add to cart * @function addToCartDisabled * @returns {boolean} */ - function addToCartDisabled() { - return (!vm.cartAllowed() || !vm.addToCartEnabled); + function addToCartDisabled () { + return (!vm.cartAllowed() || !vm.addToCartEnabled) } /** @@ -101,55 +101,55 @@ function Controller(dialogs, serviceTemplate, EventNotifications, ShoppingCart, * @param {string} href * @returns {object} */ - function dataForSubmit(href) { - var dialogFieldData = {}; - dialogFieldData[href] = '/api/service_templates/' + serviceTemplate.id; + function dataForSubmit (href) { + var dialogFieldData = {} + dialogFieldData[href] = '/api/service_templates/' + serviceTemplate.id - return lodash.merge(vm.dialogData, dialogFieldData); + return lodash.merge(vm.dialogData, dialogFieldData) } /** * Checks to see if a user is submitting a duplicate request * @function alreadyInCart * @returns {boolean} */ - function alreadyInCart() { - return ShoppingCart.isDuplicate(dataForSubmit('service_template_href')); + function alreadyInCart () { + return ShoppingCart.isDuplicate(dataForSubmit('service_template_href')) } /** * Adds service to cart * @function addToCart */ - function addToCart() { + function addToCart () { if (!ShoppingCart.allowed()) { - return; + return } - var dialogFieldData = dataForSubmit('service_template_href'); + var dialogFieldData = dataForSubmit('service_template_href') + + vm.addingToCart = true - vm.addingToCart = true; - return ShoppingCart.add({ description: vm.serviceTemplate.name, - data: dialogFieldData, + data: dialogFieldData }) .then(addSuccess, addFailure) - .then(function() { - vm.addingToCart = false; - }); + .then(function () { + vm.addingToCart = false + }) - function addSuccess(result) { + function addSuccess (result) { if (result.duplicate) { - EventNotifications.success(__("Item added to shopping cart, but it's a duplicate of an existing item")); + EventNotifications.success(__("Item added to shopping cart, but it's a duplicate of an existing item")) } else { - EventNotifications.success(__("Item added to shopping cart")); + EventNotifications.success(__('Item added to shopping cart')) } } - function addFailure(result) { - var errors = result.split(","); + function addFailure (result) { + var errors = result.split(',') for (var i = 0; i < errors.length; ++i) { - EventNotifications.error(__("There was an error adding to shopping cart: ") + errors[i]); + EventNotifications.error(__('There was an error adding to shopping cart: ') + errors[i]) } } } diff --git a/client/app/states/catalogs/explorer/explorer.state.js b/client/app/states/catalogs/explorer/explorer.state.js index 5d606c291..722ebca57 100644 --- a/client/app/states/catalogs/explorer/explorer.state.js +++ b/client/app/states/catalogs/explorer/explorer.state.js @@ -1,11 +1,11 @@ -import templateUrl from './catalogs.html'; +import templateUrl from './catalogs.html' /** @ngInject */ -export function CatalogsExplorerState(routerHelper, RBAC) { - routerHelper.configureStates(getStates(RBAC)); +export function CatalogsExplorerState (routerHelper, RBAC) { + routerHelper.configureStates(getStates(RBAC)) } -function getStates(RBAC) { +function getStates (RBAC) { return { 'catalogs.explorer': { url: '', @@ -14,14 +14,14 @@ function getStates(RBAC) { controllerAs: 'vm', title: __('Catalogs'), data: { - authorization: RBAC.hasAny(['svc_catalog_provision']), - }, - }, - }; + authorization: RBAC.hasAny(['svc_catalog_provision']) + } + } + } } /** @ngInject */ -function CatalogsController() { - var vm = this; - vm.title = __('Catalogs'); +function CatalogsController () { + var vm = this + vm.title = __('Catalogs') } diff --git a/client/app/states/dashboard/dashboard.state.js b/client/app/states/dashboard/dashboard.state.js index 2c3f59d76..8ea44b8e9 100644 --- a/client/app/states/dashboard/dashboard.state.js +++ b/client/app/states/dashboard/dashboard.state.js @@ -1,11 +1,11 @@ -import templateUrl from './dashboard.html'; +import templateUrl from './dashboard.html' /** @ngInject */ -export function DashboardState(routerHelper) { - routerHelper.configureStates(getStates()); +export function DashboardState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'dashboard': { parent: 'application', @@ -15,196 +15,196 @@ function getStates() { controllerAs: 'vm', title: N_('Dashboard'), data: { - requireUser: true, + requireUser: true }, resolve: { definedServiceIdsServices: resolveServicesWithDefinedServiceIds, retiredServices: resolveRetiredServices, expiringServices: resolveExpiringServices, - allRequests: resolveAllRequests, - }, - }, - }; + allRequests: resolveAllRequests + } + } + } } /** @ngInject */ -function resolveAllRequests(CollectionsApi, RBAC) { +function resolveAllRequests (CollectionsApi, RBAC) { if (!RBAC.has('miq_request_view')) { - return undefined; + return undefined } return [ [ pendingRequestsForServiceTemplateProvisionRequest(CollectionsApi), - pendingRequestsForServiceReconfigureRequest(CollectionsApi), + pendingRequestsForServiceReconfigureRequest(CollectionsApi) ], [ approvedRequestsForServiceTemplateProvisionRequest(CollectionsApi), - approvedRequestsForServiceReconfigureRequest(CollectionsApi), + approvedRequestsForServiceReconfigureRequest(CollectionsApi) ], [ deniedRequestsForServiceTemplateProvisionRequest(CollectionsApi), - deniedRequestsForServiceReconfigureRequest(CollectionsApi), - ], - ]; + deniedRequestsForServiceReconfigureRequest(CollectionsApi) + ] + ] } -function pendingRequestsForServiceTemplateProvisionRequest(CollectionsApi) { - var filterValues = ['approval_state=pending_approval']; - var options = {hide: 'resources', filter: filterValues}; +function pendingRequestsForServiceTemplateProvisionRequest (CollectionsApi) { + var filterValues = ['approval_state=pending_approval'] + var options = {hide: 'resources', filter: filterValues} - return CollectionsApi.query('requests', options); + return CollectionsApi.query('requests', options) } -function pendingRequestsForServiceReconfigureRequest(CollectionsApi) { - var filterValues = ['type=ServiceReconfigureRequest', 'approval_state=pending_approval']; - var options = {hide: 'resources', filter: filterValues}; +function pendingRequestsForServiceReconfigureRequest (CollectionsApi) { + var filterValues = ['type=ServiceReconfigureRequest', 'approval_state=pending_approval'] + var options = {hide: 'resources', filter: filterValues} - return CollectionsApi.query('requests', options); + return CollectionsApi.query('requests', options) } -function approvedRequestsForServiceTemplateProvisionRequest(CollectionsApi) { - var filterValues = ['type=ServiceTemplateProvisionRequest', 'approval_state=approved']; - var options = {hide: 'resources', filter: filterValues}; +function approvedRequestsForServiceTemplateProvisionRequest (CollectionsApi) { + var filterValues = ['type=ServiceTemplateProvisionRequest', 'approval_state=approved'] + var options = {hide: 'resources', filter: filterValues} - return CollectionsApi.query('requests', options); + return CollectionsApi.query('requests', options) } -function approvedRequestsForServiceReconfigureRequest(CollectionsApi) { - var filterValues = ['type=ServiceReconfigureRequest', 'approval_state=approved']; - var options = {hide: 'resources', filter: filterValues}; +function approvedRequestsForServiceReconfigureRequest (CollectionsApi) { + var filterValues = ['type=ServiceReconfigureRequest', 'approval_state=approved'] + var options = {hide: 'resources', filter: filterValues} - return CollectionsApi.query('requests', options); + return CollectionsApi.query('requests', options) } -function deniedRequestsForServiceTemplateProvisionRequest(CollectionsApi) { - var filterValues = ['type=ServiceTemplateProvisionRequest', 'approval_state=denied']; - var options = {hide: 'resources', filter: filterValues}; +function deniedRequestsForServiceTemplateProvisionRequest (CollectionsApi) { + var filterValues = ['type=ServiceTemplateProvisionRequest', 'approval_state=denied'] + var options = {hide: 'resources', filter: filterValues} - return CollectionsApi.query('requests', options); + return CollectionsApi.query('requests', options) } -function deniedRequestsForServiceReconfigureRequest(CollectionsApi) { - var filterValues = ['type=ServiceReconfigureRequest', 'approval_state=denied']; - var options = {hide: 'resources', filter: filterValues}; +function deniedRequestsForServiceReconfigureRequest (CollectionsApi) { + var filterValues = ['type=ServiceReconfigureRequest', 'approval_state=denied'] + var options = {hide: 'resources', filter: filterValues} - return CollectionsApi.query('requests', options); + return CollectionsApi.query('requests', options) } /** @ngInject */ -function resolveExpiringServices(CollectionsApi, RBAC) { - var navFeatures = RBAC.getNavFeatures(); +function resolveExpiringServices (CollectionsApi, RBAC) { + var navFeatures = RBAC.getNavFeatures() if (!navFeatures.services.show) { - return undefined; + return undefined } - var currentDate = new Date(); - var date1 = 'retires_on>' + currentDate.toISOString(); - var days30 = currentDate.setDate(currentDate.getDate() + 30); - var date2 = 'retires_on<' + new Date(days30).toISOString(); - var options = {hide: 'resources', filter: ['retired=false', date1, date2]}; + var currentDate = new Date() + var date1 = 'retires_on>' + currentDate.toISOString() + var days30 = currentDate.setDate(currentDate.getDate() + 30) + var date2 = 'retires_on<' + new Date(days30).toISOString() + var options = {hide: 'resources', filter: ['retired=false', date1, date2]} - return CollectionsApi.query('services', options); + return CollectionsApi.query('services', options) } /** @ngInject */ -function resolveRetiredServices(CollectionsApi, RBAC) { - var navFeatures = RBAC.getNavFeatures(); +function resolveRetiredServices (CollectionsApi, RBAC) { + var navFeatures = RBAC.getNavFeatures() if (!navFeatures.services.show) { - return undefined; + return undefined } - var options = {hide: 'resources', filter: ['service_id=nil', 'retired=true']}; + var options = {hide: 'resources', filter: ['service_id=nil', 'retired=true']} - return CollectionsApi.query('services', options); + return CollectionsApi.query('services', options) } /** @ngInject */ -function resolveServicesWithDefinedServiceIds(CollectionsApi, RBAC) { - var navFeatures = RBAC.getNavFeatures(); +function resolveServicesWithDefinedServiceIds (CollectionsApi, RBAC) { + var navFeatures = RBAC.getNavFeatures() if (!navFeatures.services.show) { - return undefined; + return undefined } var options = { expand: 'resources', filter: ['service_id=nil'], - attributes: ['chargeback_report'], - }; + attributes: ['chargeback_report'] + } - return CollectionsApi.query('services', options); + return CollectionsApi.query('services', options) } /** @ngInject */ -function StateController($state, definedServiceIdsServices, retiredServices, expiringServices, allRequests, lodash, $q, Chargeback) { - var vm = this; +function StateController ($state, definedServiceIdsServices, retiredServices, expiringServices, allRequests, lodash, $q, Chargeback) { + var vm = this if (angular.isDefined(definedServiceIdsServices)) { - vm.servicesCount = {}; - vm.servicesFeature = false; - vm.servicesCount.total = 0; - vm.servicesCount.current = 0; - vm.servicesCount.retired = 0; - vm.servicesCount.soon = 0; + vm.servicesCount = {} + vm.servicesFeature = false + vm.servicesCount.total = 0 + vm.servicesCount.current = 0 + vm.servicesCount.retired = 0 + vm.servicesCount.soon = 0 if (definedServiceIdsServices.subcount > 0) { - vm.servicesCount.total = definedServiceIdsServices.subcount; - vm.servicesCount.retired = retiredServices.subcount; - vm.servicesCount.soon = expiringServices.subcount; - vm.servicesCount.current = vm.servicesCount.total - vm.servicesCount.retired - vm.servicesCount.soon; + vm.servicesCount.total = definedServiceIdsServices.subcount + vm.servicesCount.retired = retiredServices.subcount + vm.servicesCount.soon = expiringServices.subcount + vm.servicesCount.current = vm.servicesCount.total - vm.servicesCount.retired - vm.servicesCount.soon - var services = definedServiceIdsServices.resources; - services.forEach(Chargeback.processReports); + var services = definedServiceIdsServices.resources + services.forEach(Chargeback.processReports) vm.chargeback = { - 'used_cost_sum': lodash(services).map('chargeback').map('used_cost_sum').values().sum(), - }; + 'used_cost_sum': lodash(services).map('chargeback').map('used_cost_sum').values().sum() + } } - vm.servicesFeature = true; + vm.servicesFeature = true } - vm.requestsFeature = false; + vm.requestsFeature = false if (angular.isDefined(allRequests)) { - vm.requestsCount = {}; - vm.requestsCount.total = 0; + vm.requestsCount = {} + vm.requestsCount.total = 0 - var allRequestTypes = ['pending', 'approved', 'denied']; - allRequests.forEach(function(promise, n) { - resolveRequestPromises(promise, allRequestTypes[n], lodash, $q); - }); + var allRequestTypes = ['pending', 'approved', 'denied'] + allRequests.forEach(function (promise, n) { + resolveRequestPromises(promise, allRequestTypes[n], lodash, $q) + }) - vm.requestsFeature = true; + vm.requestsFeature = true } - vm.navigateToServicesList = function(filterValue) { - $state.go('services', {'filter': [{'id': 'retirement', 'title': __('Retirement Date'), 'value': filterValue}]}); - }; + vm.navigateToServicesList = function (filterValue) { + $state.go('services', {'filter': [{'id': 'retirement', 'title': __('Retirement Date'), 'value': filterValue}]}) + } - vm.navigateToRetiredServicesList = function() { - $state.go('services', {'filter': [{'id': 'retired', 'title': __('Retired'), 'value': true}]}); - }; + vm.navigateToRetiredServicesList = function () { + $state.go('services', {'filter': [{'id': 'retired', 'title': __('Retired'), 'value': true}]}) + } - vm.navigateToRetiringSoonServicesList = function() { - var currentDate = new Date(); - var filters = []; + vm.navigateToRetiringSoonServicesList = function () { + var currentDate = new Date() + var filters = [] - filters.push({'id': 'retires_on', 'operator': '>', 'value': currentDate.toISOString()}); - filters.push({'id': 'retired', 'title': __('Retired'), 'value': false}); - var days30 = currentDate.setDate(currentDate.getDate() + 30); - filters.push({'id': 'retires_on', 'operator': '<', 'value': new Date(days30).toISOString()}); + filters.push({'id': 'retires_on', 'operator': '>', 'value': currentDate.toISOString()}) + filters.push({'id': 'retired', 'title': __('Retired'), 'value': false}) + var days30 = currentDate.setDate(currentDate.getDate() + 30) + filters.push({'id': 'retires_on', 'operator': '<', 'value': new Date(days30).toISOString()}) - $state.go('services', {'filter': filters}); - }; + $state.go('services', {'filter': filters}) + } - vm.navigateToCurrentServicesList = function() { - $state.go('services', {'filter': [{'id': 'retired', 'title': 'Retired', 'value': false}]}); - }; + vm.navigateToCurrentServicesList = function () { + $state.go('services', {'filter': [{'id': 'retired', 'title': 'Retired', 'value': false}]}) + } - function resolveRequestPromises(promiseArray, type, lodash, $q) { - $q.all(promiseArray).then(function(data) { - var count = lodash.sumBy(data, 'subcount'); - vm.requestsCount[type] = count; - vm.requestsCount.total += count; - }); + function resolveRequestPromises (promiseArray, type, lodash, $q) { + $q.all(promiseArray).then(function (data) { + var count = lodash.sumBy(data, 'subcount') + vm.requestsCount[type] = count + vm.requestsCount.total += count + }) } } diff --git a/client/app/states/error/error.state.js b/client/app/states/error/error.state.js index 58254df6f..e533f6eb8 100644 --- a/client/app/states/error/error.state.js +++ b/client/app/states/error/error.state.js @@ -1,12 +1,12 @@ -import templateUrl from './error.html'; +import templateUrl from './error.html' /** @ngInject */ -export function ErrorState(routerHelper) { - var otherwise = '/error'; - routerHelper.configureStates(getStates(), otherwise); +export function ErrorState (routerHelper) { + var otherwise = '/error' + routerHelper.configureStates(getStates(), otherwise) } -function getStates() { +function getStates () { return { 'error': { parent: 'blank', @@ -16,18 +16,18 @@ function getStates() { controllerAs: 'vm', title: N_('Error'), data: { - layout: 'blank', + layout: 'blank' }, params: { - error: null, - }, - }, - }; + error: null + } + } + } } /** @ngInject */ -function StateController($stateParams) { - var vm = this; +function StateController ($stateParams) { + var vm = this - vm.error = $stateParams.error; + vm.error = $stateParams.error } diff --git a/client/app/states/help/help.state.js b/client/app/states/help/help.state.js index c8e132e40..08ef17b60 100644 --- a/client/app/states/help/help.state.js +++ b/client/app/states/help/help.state.js @@ -1,11 +1,11 @@ -import templateUrl from './help.html'; +import templateUrl from './help.html' /** @ngInject */ -export function HelpState(routerHelper) { - routerHelper.configureStates(getStates()); +export function HelpState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'help': { parent: 'application', @@ -13,11 +13,11 @@ function getStates() { templateUrl, controller: StateController, controllerAs: 'vm', - title: N_('Help'), - }, - }; + title: N_('Help') + } + } } /** @ngInject */ -function StateController() { +function StateController () { } diff --git a/client/app/states/login/login.state.js b/client/app/states/login/login.state.js index b853e97d8..7c8fc848b 100644 --- a/client/app/states/login/login.state.js +++ b/client/app/states/login/login.state.js @@ -1,11 +1,11 @@ -import templateUrl from './login.html'; +import templateUrl from './login.html' /** @ngInject */ -export function LoginState(routerHelper) { - routerHelper.configureStates(getStates()); +export function LoginState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'login': { parent: 'blank', @@ -15,65 +15,64 @@ function getStates() { controllerAs: 'vm', title: N_('Login'), data: { - layout: 'blank', - }, - }, - }; + layout: 'blank' + } + } + } } /** @ngInject */ -function StateController(exception, $state, Text, RBAC, API_LOGIN, API_PASSWORD, AuthenticationApi, +function StateController (exception, $state, Text, RBAC, API_LOGIN, API_PASSWORD, AuthenticationApi, Session, $rootScope, Notifications, Language, ApplianceInfo, $window) { - var vm = this; + var vm = this - vm.text = Text.login; + vm.text = Text.login vm.credentials = { login: API_LOGIN, - password: API_PASSWORD, - }; + password: API_PASSWORD + } - if ($window.location.href.includes("?timeout")) { - Notifications.message('danger', '', __('Your session has timed out.'), true); + if ($window.location.href.includes('?timeout')) { + Notifications.message('danger', '', __('Your session has timed out.'), true) } - + if ($window.location.href.includes('?pause')) { - const params = (new URL($window.document.location)).searchParams; - const pauseLength = params.get('pause'); - Session.setPause(pauseLength); + const params = (new URL($window.document.location)).searchParams + const pauseLength = params.get('pause') + Session.setPause(pauseLength) } if (Session.privilegesError) { - Notifications.error(__('User does not have privileges to login.')); + Notifications.error(__('User does not have privileges to login.')) } - vm.onSubmit = onSubmit; + vm.onSubmit = onSubmit - function onSubmit() { - Session.timeoutNotified = false; - Session.privilegesError = false; + function onSubmit () { + Session.timeoutNotified = false + Session.privilegesError = false return AuthenticationApi.login(vm.credentials.login, vm.credentials.password) .then(Session.loadUser) .then(Session.requestWsToken) - .then(function(response) { + .then(function (response) { if (angular.isDefined(response)) { - Language.onLogin(response); - ApplianceInfo.set(response); - RBAC.setRole(response.identity.role); + Language.onLogin(response) + ApplianceInfo.set(response) + RBAC.setRole(response.identity.role) } - if (RBAC.navigationEnabled()) { if (angular.isDefined($rootScope.notifications) && $rootScope.notifications.data.length > 0) { - $rootScope.notifications.data.splice(0, $rootScope.notifications.data.length); + $rootScope.notifications.data.splice(0, $rootScope.notifications.data.length) } - $window.location.href = $state.href('dashboard'); + $window.location.href = $state.href('dashboard') } else { - Session.privilegesError = true; - Notifications.error(__('You do not have permission to view the Service UI. Contact your administrator to update your group permissions.')); + Session.privilegesError = true + Notifications.error(__('You do not have permission to view the Service UI. Contact your administrator to update your group permissions.')) } }) - .catch(exception.catch('Login failed, possibly invalid credentials.')); + .catch(exception.catch('Login failed, possibly invalid credentials.')) } } diff --git a/client/app/states/logout/logout.state.js b/client/app/states/logout/logout.state.js index 6268639e2..b40e75a1e 100644 --- a/client/app/states/logout/logout.state.js +++ b/client/app/states/logout/logout.state.js @@ -1,25 +1,25 @@ /** @ngInject */ -export function LogoutState(routerHelper) { - routerHelper.configureStates(getStates()); +export function LogoutState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'logout': { url: '/logout', controller: StateController, controllerAs: 'vm', - title: N_('Logout'), - }, - }; + title: N_('Logout') + } + } } /** @ngInject */ -function StateController(Session, $window) { - activate(); +function StateController (Session, $window) { + activate() - function activate() { - Session.destroy(); - $window.location.href = $window.location.href; + function activate () { + Session.destroy() + $window.location.href = $window.location.href } } diff --git a/client/app/states/orders/details/details.state.js b/client/app/states/orders/details/details.state.js index 02b87f019..ed83dab46 100644 --- a/client/app/states/orders/details/details.state.js +++ b/client/app/states/orders/details/details.state.js @@ -1,11 +1,11 @@ -import templateUrl from './details.html'; +import templateUrl from './details.html' /** @ngInject */ -export function OrdersDetailsState(routerHelper, RBAC) { - routerHelper.configureStates(getStates(RBAC)); +export function OrdersDetailsState (routerHelper, RBAC) { + routerHelper.configureStates(getStates(RBAC)) } -function getStates(RBAC) { +function getStates (RBAC) { return { 'orders.details': { url: '/:serviceOrderId', @@ -14,36 +14,36 @@ function getStates(RBAC) { controllerAs: 'vm', title: __('Order Details'), resolve: { - order: resolveOrder, + order: resolveOrder }, data: { - authorization: RBAC.has('miq_request_show'), - }, - }, - }; + authorization: RBAC.has('miq_request_show') + } + } + } } /** @ngInject */ -function resolveOrder($stateParams, CollectionsApi) { +function resolveOrder ($stateParams, CollectionsApi) { return CollectionsApi.get('service_orders', $stateParams.serviceOrderId, { - expand: ['resources', 'service_requests'], - }); + expand: ['resources', 'service_requests'] + }) } /** @ngInject */ -function StateController(order, $state) { - var vm = this; +function StateController (order, $state) { + var vm = this - vm.title = order.name; - vm.order = order; + vm.title = order.name + vm.order = order vm.requestListConfig = { showSelectBox: false, selectionMatchProp: 'id', - onClick: handleRequestClick, - }; + onClick: handleRequestClick + } - function handleRequestClick(item, _e) { - $state.go('requests.details', { requestId: item.id }); + function handleRequestClick (item, _e) { + $state.go('requests.details', { requestId: item.id }) } } diff --git a/client/app/states/orders/explorer/explorer.state.js b/client/app/states/orders/explorer/explorer.state.js index bb5aa7506..fb9efb47f 100644 --- a/client/app/states/orders/explorer/explorer.state.js +++ b/client/app/states/orders/explorer/explorer.state.js @@ -1,17 +1,17 @@ /** @ngInject */ -export function OrdersExplorerState(routerHelper, RBAC) { - routerHelper.configureStates(getStates(RBAC)); +export function OrdersExplorerState (routerHelper, RBAC) { + routerHelper.configureStates(getStates(RBAC)) } -function getStates(RBAC) { +function getStates (RBAC) { return { 'orders.explorer': { url: '', template: '<order-explorer></order-explorer>', title: __('Orders'), data: { - authorization: RBAC.hasAny(['miq_request_show', 'miq_request_show_list']), - }, - }, - }; + authorization: RBAC.hasAny(['miq_request_show', 'miq_request_show_list']) + } + } + } } diff --git a/client/app/states/orders/orders.state.js b/client/app/states/orders/orders.state.js index cdd95e684..ab0f75b4c 100644 --- a/client/app/states/orders/orders.state.js +++ b/client/app/states/orders/orders.state.js @@ -1,15 +1,15 @@ /** @ngInject */ -export function OrdersState(routerHelper) { - routerHelper.configureStates(getStates()); +export function OrdersState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'orders': { parent: 'application', url: '/orders', redirectTo: 'orders.explorer', - template: '<ui-view></ui-view>', - }, - }; + template: '<ui-view></ui-view>' + } + } } diff --git a/client/app/states/services/custom_button_details/custom_button_details.state.js b/client/app/states/services/custom_button_details/custom_button_details.state.js index b7a4126f3..bec60a794 100644 --- a/client/app/states/services/custom_button_details/custom_button_details.state.js +++ b/client/app/states/services/custom_button_details/custom_button_details.state.js @@ -1,12 +1,11 @@ -import templateUrl from './custom_button_details.html'; - +import templateUrl from './custom_button_details.html' /** @ngInject */ -export function CustomButtonDetailsState(routerHelper) { - routerHelper.configureStates(getStates()); +export function CustomButtonDetailsState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'services.custom_button_details': { url: '/:serviceId/custom_button_details', @@ -16,77 +15,77 @@ function getStates() { title: __('Service Custom Button Details'), params: { button: { - value: null, + value: null }, serviceId: { - value: null, - }, + value: null + } }, resolve: { dialog: resolveDialog, - service: resolveService, - }, - }, - }; + service: resolveService + } + } + } } /** @ngInject */ -function resolveService($stateParams, CollectionsApi) { - var options = {attributes: ['picture', 'picture.image_href']}; +function resolveService ($stateParams, CollectionsApi) { + var options = {attributes: ['picture', 'picture.image_href']} - return CollectionsApi.get('services', $stateParams.serviceId, options); + return CollectionsApi.get('services', $stateParams.serviceId, options) } /** @ngInject */ -function resolveDialog($stateParams, CollectionsApi) { - const options = {expand: 'resources', attributes: 'content'}; - const dialogId = $stateParams.button.resource_action.dialog_id; - - return CollectionsApi.query('service_dialogs/' + dialogId, options); +function resolveDialog ($stateParams, CollectionsApi) { + const options = {expand: 'resources', attributes: 'content'} + const dialogId = $stateParams.button.resource_action.dialog_id + + return CollectionsApi.query('service_dialogs/' + dialogId, options) } /** @ngInject */ -function StateController($state, $stateParams, dialog, service, CollectionsApi, EventNotifications, DialogFieldRefresh) { - var vm = this; - vm.title = __('Custom button action'); - vm.dialogs = dialog.content; - vm.service = service; - vm.serviceId = $stateParams.serviceId; - vm.button = $stateParams.button; - vm.submitCustomButton = submitCustomButton; - vm.submitButtonEnabled = false; - vm.dialogUrl = 'service_dialogs/'; - vm.refreshField = refreshField; - vm.setDialogData = setDialogData; - vm.dialogData = {}; +function StateController ($state, $stateParams, dialog, service, CollectionsApi, EventNotifications, DialogFieldRefresh) { + var vm = this + vm.title = __('Custom button action') + vm.dialogs = dialog.content + vm.service = service + vm.serviceId = $stateParams.serviceId + vm.button = $stateParams.button + vm.submitCustomButton = submitCustomButton + vm.submitButtonEnabled = false + vm.dialogUrl = 'service_dialogs/' + vm.refreshField = refreshField + vm.setDialogData = setDialogData + vm.dialogData = {} - function refreshField(field) { - return DialogFieldRefresh.refreshDialogField(vm.dialogData, [field.name], vm.dialogUrl, dialog.id); + function refreshField (field) { + return DialogFieldRefresh.refreshDialogField(vm.dialogData, [field.name], vm.dialogUrl, dialog.id) } - function setDialogData(data) { - vm.submitButtonEnabled = data.validations.isValid; - vm.dialogData = data.data; + function setDialogData (data) { + vm.submitButtonEnabled = data.validations.isValid + vm.dialogData = data.data } - - function submitCustomButton() { - const buttonClass = vm.button.applies_to_class.toLowerCase(); - const collection = buttonClass === 'servicetemplate' ? 'services' : buttonClass === 'vm' ? 'vms' : null; + + function submitCustomButton () { + const buttonClass = vm.button.applies_to_class.toLowerCase() + const collection = buttonClass === 'servicetemplate' ? 'services' : buttonClass === 'vm' ? 'vms' : null CollectionsApi.post( collection, $stateParams.serviceId, {}, angular.toJson({action: $stateParams.button.name, resource: vm.dialogData}) - ).then(submitSuccess, submitFailure); + ).then(submitSuccess, submitFailure) - function submitSuccess(result) { - EventNotifications.success(result.message); - $state.go('services.details', {serviceId: $stateParams.serviceId}); + function submitSuccess (result) { + EventNotifications.success(result.message) + $state.go('services.details', {serviceId: $stateParams.serviceId}) } - function submitFailure(result) { - EventNotifications.error(__('There was an error submitting this request: ') + result.data.error.message); + function submitFailure (result) { + EventNotifications.error(__('There was an error submitting this request: ') + result.data.error.message) } } } diff --git a/client/app/states/services/details/details.state.js b/client/app/states/services/details/details.state.js index 9cbbf600a..556b02313 100644 --- a/client/app/states/services/details/details.state.js +++ b/client/app/states/services/details/details.state.js @@ -1,9 +1,9 @@ /** @ngInject */ -export function ServicesDetailsState(routerHelper, RBAC) { - routerHelper.configureStates(getStates(RBAC)); +export function ServicesDetailsState (routerHelper, RBAC) { + routerHelper.configureStates(getStates(RBAC)) } -function getStates(RBAC) { +function getStates (RBAC) { return { 'services.details': { url: '/:serviceId', @@ -11,8 +11,8 @@ function getStates(RBAC) { controllerAs: 'vm', title: __('Service Details'), data: { - authorization: RBAC.hasAny(['service_view']), - }, - }, - }; + authorization: RBAC.hasAny(['service_view']) + } + } + } } diff --git a/client/app/states/services/explorer/explorer.state.js b/client/app/states/services/explorer/explorer.state.js index d1eb2dfb5..7695bd65e 100644 --- a/client/app/states/services/explorer/explorer.state.js +++ b/client/app/states/services/explorer/explorer.state.js @@ -1,9 +1,9 @@ /** @ngInject */ -export function ServicesExplorerState(routerHelper, RBAC) { - routerHelper.configureStates(getStates(RBAC)); +export function ServicesExplorerState (routerHelper, RBAC) { + routerHelper.configureStates(getStates(RBAC)) } -function getStates(RBAC) { +function getStates (RBAC) { return { 'services.explorer': { url: '', @@ -12,8 +12,8 @@ function getStates(RBAC) { title: __('Services Explorer'), params: { filter: null }, data: { - authorization: RBAC.hasAny(['service_view']), - }, - }, - }; + authorization: RBAC.hasAny(['service_view']) + } + } + } } diff --git a/client/app/states/services/reconfigure/reconfigure.state.js b/client/app/states/services/reconfigure/reconfigure.state.js index 260f98a1f..fca87c82e 100644 --- a/client/app/states/services/reconfigure/reconfigure.state.js +++ b/client/app/states/services/reconfigure/reconfigure.state.js @@ -1,13 +1,12 @@ /* eslint camelcase: "off" */ -import templateUrl from './reconfigure.html'; - +import templateUrl from './reconfigure.html' /** @ngInject */ -export function ServicesReconfigureState(routerHelper) { - routerHelper.configureStates(getStates()); +export function ServicesReconfigureState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'services.reconfigure': { url: '/:serviceId', @@ -16,89 +15,89 @@ function getStates() { controllerAs: 'vm', title: __('Service Details'), resolve: { - service: resolveService, - }, - }, - }; + service: resolveService + } + } + } } /** @ngInject */ -function resolveService($stateParams, CollectionsApi) { +function resolveService ($stateParams, CollectionsApi) { var requestAttributes = [ - 'provision_dialog', - ]; - var options = {attributes: requestAttributes}; + 'provision_dialog' + ] + var options = {attributes: requestAttributes} - return CollectionsApi.get('services', $stateParams.serviceId, options); + return CollectionsApi.get('services', $stateParams.serviceId, options) } /** @ngInject */ -function StateController($state, $stateParams, CollectionsApi, service, EventNotifications, DialogFieldRefresh) { - var vm = this; +function StateController ($state, $stateParams, CollectionsApi, service, EventNotifications, DialogFieldRefresh) { + var vm = this - vm.title = __('Service Details'); - vm.service = service; - vm.dialogs = [setFieldValueDefaults(vm.service.provision_dialog)]; - vm.submitDialog = submitDialog; - vm.cancelDialog = cancelDialog; - vm.backToService = backToService; - vm.dialogUrl = 'services/' + vm.service.service_template_catalog_id + '/service_templates'; - vm.refreshField = refreshField; - vm.setDialogData = setDialogData; - vm.dialogData = {}; + vm.title = __('Service Details') + vm.service = service + vm.dialogs = [setFieldValueDefaults(vm.service.provision_dialog)] + vm.submitDialog = submitDialog + vm.cancelDialog = cancelDialog + vm.backToService = backToService + vm.dialogUrl = 'services/' + vm.service.service_template_catalog_id + '/service_templates' + vm.refreshField = refreshField + vm.setDialogData = setDialogData + vm.dialogData = {} - function refreshField(field) { - return DialogFieldRefresh.refreshDialogField(vm.dialogData, [field.name], vm.dialogUrl, vm.service.id); + function refreshField (field) { + return DialogFieldRefresh.refreshDialogField(vm.dialogData, [field.name], vm.dialogUrl, vm.service.id) } - function setFieldValueDefaults(dialog) { - const fieldValues = {}; + function setFieldValueDefaults (dialog) { + const fieldValues = {} if (angular.isDefined(vm.service.options)) { for (var option in vm.service.options.dialog) { - fieldValues[option.replace('dialog_', '')] = vm.service.options.dialog[option]; + fieldValues[option.replace('dialog_', '')] = vm.service.options.dialog[option] } // Just for user reference for dialog heirarchy dialog => tabs => groups => fields => field dialog.dialog_tabs.forEach((tab, tab_index) => { - tab.dialog_groups.forEach((group, group_index) => { - group.dialog_fields.forEach((field, field_index) => { - const fieldValue = (angular.isDefined(fieldValues[field.name]) ? fieldValues[field.name] : field.default_value); - dialog.dialog_tabs[tab_index].dialog_groups[group_index].dialog_fields[field_index].default_value = fieldValue; - }); - }); - }); + tab.dialog_groups.forEach((group, group_index) => { + group.dialog_fields.forEach((field, field_index) => { + const fieldValue = (angular.isDefined(fieldValues[field.name]) ? fieldValues[field.name] : field.default_value) + dialog.dialog_tabs[tab_index].dialog_groups[group_index].dialog_fields[field_index].default_value = fieldValue + }) + }) + }) } - return dialog; + return dialog } - function setDialogData(data) { - vm.dialogData = data.data; + function setDialogData (data) { + vm.dialogData = data.data } - function submitDialog() { - vm.dialogData.href = '/api/services/' + service.id; + function submitDialog () { + vm.dialogData.href = '/api/services/' + service.id CollectionsApi.post( 'services', $stateParams.serviceId, {}, angular.toJson({action: 'reconfigure', resource: vm.dialogData}) - ).then(submitSuccess, submitFailure); + ).then(submitSuccess, submitFailure) - function submitSuccess(result) { - EventNotifications.success(result.message); - $state.go('services.details', {serviceId: $stateParams.serviceId}); + function submitSuccess (result) { + EventNotifications.success(result.message) + $state.go('services.details', {serviceId: $stateParams.serviceId}) } - function submitFailure(result) { - EventNotifications.error(__('There was an error submitting this request: ') + result); + function submitFailure (result) { + EventNotifications.error(__('There was an error submitting this request: ') + result) } } - function cancelDialog() { - EventNotifications.success(__('Reconfigure this service has been cancelled')); - $state.go('services.details', {serviceId: $stateParams.serviceId}); + function cancelDialog () { + EventNotifications.success(__('Reconfigure this service has been cancelled')) + $state.go('services.details', {serviceId: $stateParams.serviceId}) } - function backToService() { - $state.go('services.details', {serviceId: service.id}); + function backToService () { + $state.go('services.details', {serviceId: service.id}) } } diff --git a/client/app/states/services/services.state.js b/client/app/states/services/services.state.js index c925d1506..962ef4144 100644 --- a/client/app/states/services/services.state.js +++ b/client/app/states/services/services.state.js @@ -1,16 +1,16 @@ /** @ngInject */ -export function ServicesState(routerHelper) { - routerHelper.configureStates(getStates()); +export function ServicesState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'services': { parent: 'application', url: '/services', redirectTo: 'services.explorer', template: '<ui-view></ui-view>', - params: { filter: null }, - }, - }; + params: { filter: null } + } + } } diff --git a/client/app/states/states.module.js b/client/app/states/states.module.js index b98300ce2..8ca7fb44a 100644 --- a/client/app/states/states.module.js +++ b/client/app/states/states.module.js @@ -1,29 +1,29 @@ -import {AboutMeState} from "./about-me/about-me.state.js"; -import {CatalogsDetailsState} from "./catalogs/details/details.state.js"; -import {CatalogsExplorerState} from "./catalogs/explorer/explorer.state.js"; -import {CatalogsState} from "./catalogs/catalogs.state.js"; -import {CustomButtonDetailsState} from "./services/custom_button_details/custom_button_details.state.js"; -import {DashboardState} from "./dashboard/dashboard.state.js"; -import {ErrorState} from "./error/error.state.js"; -import {HelpState} from "./help/help.state.js"; -import {LoginState} from "./login/login.state.js"; -import {LogoutState} from "./logout/logout.state.js"; -import {NotFoundState} from "./404/404.state.js"; -import {OrdersDetailsState} from "./orders/details/details.state.js"; -import {OrdersExplorerState} from "./orders/explorer/explorer.state.js"; -import {OrdersState} from "./orders/orders.state.js"; -import {ServicesDetailsState} from "./services/details/details.state.js"; -import {ServicesExplorerState} from "./services/explorer/explorer.state.js"; -import {ServicesReconfigureState} from "./services/reconfigure/reconfigure.state.js"; -import {ServicesState} from "./services/services.state.js"; -import {VmsDetailsState} from "./vms/details/details.state.js"; -import {VmsSnapshotsState} from "./vms/snapshots/snapshots.state.js"; -import {VmsState} from "./vms/vms.state.js"; +import {AboutMeState} from './about-me/about-me.state.js' +import {CatalogsDetailsState} from './catalogs/details/details.state.js' +import {CatalogsExplorerState} from './catalogs/explorer/explorer.state.js' +import {CatalogsState} from './catalogs/catalogs.state.js' +import {CustomButtonDetailsState} from './services/custom_button_details/custom_button_details.state.js' +import {DashboardState} from './dashboard/dashboard.state.js' +import {ErrorState} from './error/error.state.js' +import {HelpState} from './help/help.state.js' +import {LoginState} from './login/login.state.js' +import {LogoutState} from './logout/logout.state.js' +import {NotFoundState} from './404/404.state.js' +import {OrdersDetailsState} from './orders/details/details.state.js' +import {OrdersExplorerState} from './orders/explorer/explorer.state.js' +import {OrdersState} from './orders/orders.state.js' +import {ServicesDetailsState} from './services/details/details.state.js' +import {ServicesExplorerState} from './services/explorer/explorer.state.js' +import {ServicesReconfigureState} from './services/reconfigure/reconfigure.state.js' +import {ServicesState} from './services/services.state.js' +import {VmsDetailsState} from './vms/details/details.state.js' +import {VmsSnapshotsState} from './vms/snapshots/snapshots.state.js' +import {VmsState} from './vms/vms.state.js' export const AppRoutingModule = angular .module('app.states', [ 'app.core', - 'app.components', + 'app.components' ]) .run(NotFoundState) .run(AboutMeState) @@ -46,4 +46,4 @@ export const AppRoutingModule = angular .run(VmsDetailsState) .run(VmsSnapshotsState) .run(VmsState) - .name; + .name diff --git a/client/app/states/vms/details/details.state.js b/client/app/states/vms/details/details.state.js index 786800f64..552067d0d 100644 --- a/client/app/states/vms/details/details.state.js +++ b/client/app/states/vms/details/details.state.js @@ -1,15 +1,15 @@ /** @ngInject */ -export function VmsDetailsState(routerHelper) { - routerHelper.configureStates(getStates()); +export function VmsDetailsState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'vms.details': { url: '/:vmId', params: { viewType: null }, - template: '<vm-details \>', - title: N_('VM Details'), - }, - }; + template: '<vm-details>', + title: N_('VM Details') + } + } } diff --git a/client/app/states/vms/snapshots/snapshots.state.js b/client/app/states/vms/snapshots/snapshots.state.js index 8f06f00f5..f7d0ea219 100644 --- a/client/app/states/vms/snapshots/snapshots.state.js +++ b/client/app/states/vms/snapshots/snapshots.state.js @@ -1,26 +1,25 @@ /** @ngInject */ -export function VmsSnapshotsState(routerHelper) { - routerHelper.configureStates(getStates()); +export function VmsSnapshotsState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'vms.snapshots': { url: '/:vmId/snapshots', template: '<vm-snapshots vm-id="vm.vmId" />', controller: StateController, controllerAs: 'vm', - title: N_('VM Snapshots'), + title: N_('VM Snapshots') - }, - }; + } + } } - /** @ngInject */ -function StateController($stateParams) { - const vm = this; +function StateController ($stateParams) { + const vm = this angular.extend(vm, { - vmId: $stateParams.vmId, - }); + vmId: $stateParams.vmId + }) } diff --git a/client/app/states/vms/vms.state.js b/client/app/states/vms/vms.state.js index 783a2b121..40ff5a0a7 100644 --- a/client/app/states/vms/vms.state.js +++ b/client/app/states/vms/vms.state.js @@ -1,15 +1,15 @@ /** @ngInject */ -export function VmsState(routerHelper) { - routerHelper.configureStates(getStates()); +export function VmsState (routerHelper) { + routerHelper.configureStates(getStates()) } -function getStates() { +function getStates () { return { 'vms': { parent: 'application', url: '/vms', redirectTo: 'services.explorer', - template: '<ui-view></ui-view>', - }, - }; + template: '<ui-view></ui-view>' + } + } } diff --git a/config/available-languages.js b/config/available-languages.js index b5da95213..6f133e578 100644 --- a/config/available-languages.js +++ b/config/available-languages.js @@ -1,45 +1,44 @@ /* eslint-disable angular/definedundefined, angular/json-functions, global-require */ -'use strict'; +'use strict' -const glob = require('glob'); -const fs = require('fs'); +const glob = require('glob') +const fs = require('fs') -task(); +task() -function task() { +function task () { const config = { catalogs: '../client/gettext/json/manageiq-ui-service.json', availLangsFile: '../client/gettext/json/available_languages.json', - supportedLangsFile: '../client/gettext/json/supported_languages.json', - }; + supportedLangsFile: '../client/gettext/json/supported_languages.json' + } - const langFile = glob.sync(config.catalogs); - let availableLanguages = {}; - let supportedLanguages = []; + const langFile = glob.sync(config.catalogs) + let availableLanguages = {} + let supportedLanguages = [] if (fs.existsSync(config.supportedLangsFile)) { - supportedLanguages = JSON.parse(fs.readFileSync(config.supportedLangsFile, 'utf8')); + supportedLanguages = JSON.parse(fs.readFileSync(config.supportedLangsFile, 'utf8')) } - const catalog = JSON.parse(fs.readFileSync(langFile[0], 'utf8')); + const catalog = JSON.parse(fs.readFileSync(langFile[0], 'utf8')) for (const propName in catalog) { - if (typeof(catalog[propName]) !== 'undefined') { + if (typeof (catalog[propName]) !== 'undefined') { // If we have a list of supported languages and the language is not on the list, we skip it if (supportedLanguages.length > 0 && !supportedLanguages.includes(propName)) { - continue; + continue } - if (typeof(catalog[propName].locale_name) !== 'undefined') { - availableLanguages[propName] = catalog[propName].locale_name; + if (typeof (catalog[propName].locale_name) !== 'undefined') { + availableLanguages[propName] = catalog[propName].locale_name } else { - availableLanguages[propName] = ''; + availableLanguages[propName] = '' } } } - availableLanguages = JSON.stringify(availableLanguages); - fs.writeFileSync(config.availLangsFile, availableLanguages, {encoding: 'utf-8', flag: 'w+'}); + availableLanguages = JSON.stringify(availableLanguages) + fs.writeFileSync(config.availLangsFile, availableLanguages, {encoding: 'utf-8', flag: 'w+'}) } - diff --git a/config/webpack.dev.js b/config/webpack.dev.js index 7a3d1f189..84eb571c1 100644 --- a/config/webpack.dev.js +++ b/config/webpack.dev.js @@ -1,33 +1,33 @@ /* eslint-disable angular/log, no-console */ -const fs = require('fs'); -const path = require('path'); -const webpack = require('webpack'); -const CopyWebpackPlugin = require('copy-webpack-plugin'); -const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin'); -const HtmlWebpackPlugin = require('html-webpack-plugin'); - -const root = path.resolve(__dirname, '../client'); -const outputPath = process.env.BUILD_OUTPUT || '../../manageiq/public/ui/service'; -const dist = path.resolve(__dirname, outputPath); -const nodeModules = path.resolve(__dirname, '../node_modules'); -const protocol = process.env.PROXY_PROTOCOL || 'http://'; -const host = process.env.PROXY_HOST || process.env.MOCK_API_HOST || '[::1]:3000'; -const hasSkinImages = fs.existsSync(`${root}/skin/images`); -const appBasePath = process.env.NODE_ENV === 'production' ? "'/ui/service/'" : "'/'"; - -console.log("Backend proxied on " + protocol + host); +const fs = require('fs') +const path = require('path') +const webpack = require('webpack') +const CopyWebpackPlugin = require('copy-webpack-plugin') +const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin') +const HtmlWebpackPlugin = require('html-webpack-plugin') + +const root = path.resolve(__dirname, '../client') +const outputPath = process.env.BUILD_OUTPUT || '../../manageiq/public/ui/service' +const dist = path.resolve(__dirname, outputPath) +const nodeModules = path.resolve(__dirname, '../node_modules') +const protocol = process.env.PROXY_PROTOCOL || 'http://' +const host = process.env.PROXY_HOST || process.env.MOCK_API_HOST || '[::1]:3000' +const hasSkinImages = fs.existsSync(`${root}/skin/images`) +const appBasePath = process.env.NODE_ENV === 'production' ? "'/ui/service/'" : "'/'" + +console.log('Backend proxied on ' + protocol + host) module.exports = { context: root, entry: { - app: './app/main.ts', + app: './app/main.ts' }, output: { chunkFilename: 'js/[name]-[hash].chunk.js', filename: 'js/[name]-[hash].js', - path: dist, + path: dist }, devServer: { @@ -37,17 +37,17 @@ module.exports = { proxy: { '/api': { target: `${protocol}${host}`, - secure: false, + secure: false }, '/pictures': { target: `${protocol}${host}`, - secure: false, + secure: false }, '/ws': { target: `ws://${host}`, - ws: true, - }, - }, + ws: true + } + } }, // Output source maps suitable for development @@ -66,8 +66,8 @@ module.exports = { test: /\.html$/, use: [ `ngtemplate-loader?relativeTo=${root}/`, - `html-loader?attrs=false&minimize=true`, - ], + `html-loader?attrs=false&minimize=true` + ] }, // ts loaders: standard typescript loader @@ -75,8 +75,8 @@ module.exports = { test: /\.ts$/, use: [ 'babel-loader?presets[]=env', - 'ts-loader', - ], + 'ts-loader' + ] }, // js loaders: transpile based on browserslist from package.json @@ -86,8 +86,8 @@ module.exports = { use: [ 'ng-annotate-loader', 'babel-loader?presets[]=env', - ], 'standard-loader' + ] }, // font/images loaders: if smaller than limit embed as data uri @@ -103,13 +103,13 @@ module.exports = { // Determine publicPath dynamically because in production, assets // must be relative to `/ui/service/` publicPath: (url) => { - const path = process.env.NODE_ENV === 'production' ? '/ui/service/' : '/'; + const path = process.env.NODE_ENV === 'production' ? '/ui/service/' : '/' - return path + url; - }, - }, - }, - ], + return path + url + } + } + } + ] }, // css loaders: extract styles to a separate bundle @@ -120,9 +120,9 @@ module.exports = { allChunks: true, use: [ 'css-loader?importLoaders=1&sourceMap=true', - 'postcss-loader', - ], - }), + 'postcss-loader' + ] + }) }, { test: /\.(sass|scss)$/, @@ -141,14 +141,14 @@ module.exports = { `${nodeModules}/bootstrap-sass/assets/stylesheets`, `${nodeModules}/patternfly-sass/assets/stylesheets`, `${nodeModules}/font-awesome/scss`, - `${nodeModules}/font-fabulous/assets/stylesheets`, - ], - }, - }, - ], - }), - }, - ], + `${nodeModules}/font-fabulous/assets/stylesheets` + ] + } + } + ] + }) + } + ] }, plugins: [ @@ -164,13 +164,13 @@ module.exports = { {from: `${nodeModules}/spice-html5-bower`, to: 'vendor/spice-html5-bower'}, // Override images with skin replacements if they exist - {from: hasSkinImages ? `${root}/skin/images` : '', to: 'images', force: true}, + {from: hasSkinImages ? `${root}/skin/images` : '', to: 'images', force: true} ]), // Generate index.html from template with script/link tags for bundles new HtmlWebpackPlugin({ base: '/', - template: '../client/index.ejs', + template: '../client/index.ejs' }), // Fix circular dependency error: @@ -178,17 +178,17 @@ module.exports = { new webpack.ContextReplacementPlugin( /angular(\\|\/)core(\\|\/)@angular/, root - ), + ) ], resolve: { extensions: ['.ts', '.js'], - symlinks: false, + symlinks: false }, // Disables noisy performance warnings. While the warnings are important, it // is not feasible to satisfy the recommendations until we start code splitting performance: { - hints: false, - }, -}; + hints: false + } +} diff --git a/config/webpack.prod.js b/config/webpack.prod.js index 649d6d9f9..b73124e77 100644 --- a/config/webpack.prod.js +++ b/config/webpack.prod.js @@ -1,12 +1,12 @@ -const webpack = require('webpack'); -const CleanWebpackPlugin = require('clean-webpack-plugin'); -const HtmlWebpackPlugin = require('html-webpack-plugin'); -const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin'); +const webpack = require('webpack') +const CleanWebpackPlugin = require('clean-webpack-plugin') +const HtmlWebpackPlugin = require('html-webpack-plugin') +const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin') -const config = require('./webpack.dev.js'); +const config = require('./webpack.dev.js') // Source maps suitable for production use -config.devtool = 'cheap-module-source-map'; +config.devtool = 'cheap-module-source-map' config.plugins.push( new webpack.NoEmitOnErrorsPlugin(), @@ -15,16 +15,16 @@ config.plugins.push( // Cleans previous build new CleanWebpackPlugin([config.output.path], { - allowExternal: true, + allowExternal: true }), // Replace index.html with correct base href for production use new HtmlWebpackPlugin({ base: '/ui/service/', - template: '../client/index.ejs', + template: '../client/index.ejs' }), new OptimizeCssAssetsWebpackPlugin() -); +) -module.exports = config; +module.exports = config diff --git a/config/webpack.static.js b/config/webpack.static.js index 184e71ee5..df59038ad 100644 --- a/config/webpack.static.js +++ b/config/webpack.static.js @@ -1,17 +1,17 @@ -const webpack = require('webpack'); -const path = require('path'); -const CleanWebpackPlugin = require('clean-webpack-plugin'); -const HtmlWebpackPlugin = require('html-webpack-plugin'); -const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin'); -const config = require('./webpack.dev.js'); -var urlBase = '/ui/service'; +const webpack = require('webpack') +const path = require('path') +const CleanWebpackPlugin = require('clean-webpack-plugin') +const HtmlWebpackPlugin = require('html-webpack-plugin') +const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin') +const config = require('./webpack.dev.js') +var urlBase = '/ui/service' if (process.env.BUILD_OUTPUT) { - config.output.path = path.resolve(__dirname, process.env.BUILD_OUTPUT); - urlBase = '/'; + config.output.path = path.resolve(__dirname, process.env.BUILD_OUTPUT) + urlBase = '/' } // Source maps suitable for production use -config.devtool = 'cheap-module-source-map'; +config.devtool = 'cheap-module-source-map' config.plugins.push( new webpack.NoEmitOnErrorsPlugin(), @@ -20,16 +20,16 @@ config.plugins.push( // Cleans previous build new CleanWebpackPlugin([config.output.path], { - allowExternal: true, + allowExternal: true }), // Replace index.html with correct base href for production use new HtmlWebpackPlugin({ base: urlBase, - template: '../client/index.ejs', + template: '../client/index.ejs' }), new OptimizeCssAssetsWebpackPlugin() -); +) -module.exports = config; +module.exports = config diff --git a/config/webpack.test.js b/config/webpack.test.js index 617576afa..88f4eeb1b 100644 --- a/config/webpack.test.js +++ b/config/webpack.test.js @@ -1,11 +1,11 @@ -const config = require('./webpack.dev.js'); +const config = require('./webpack.dev.js') config.module.rules.push({ test: /\.js$/, enforce: 'post', include: `${config.context}/app`, loader: 'istanbul-instrumenter-loader', - exclude: [/\.config.js$/, /\.spec\.js$/, /node_modules/], -}); + exclude: [/\.config.js$/, /\.spec\.js$/, /node_modules/] +}) -module.exports = config; +module.exports = config diff --git a/karma.conf.js b/karma.conf.js index 3ca938381..98c20f24f 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -1,8 +1,8 @@ -'use strict'; +'use strict' -const webpackConfig = require('./config/webpack.test.js'); +const webpackConfig = require('./config/webpack.test.js') -module.exports = function(config) { +module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: './', @@ -14,7 +14,7 @@ module.exports = function(config) { concurrency: Infinity, webpack: webpackConfig, webpackMiddleware: { - stats: 'errors-only', + stats: 'errors-only' }, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || @@ -32,10 +32,10 @@ module.exports = function(config) { {pattern: './client/app/**/*.spec.js'}, {pattern: './tests/**/*.js'}, {pattern: './tests/**/*.json', included: false, served: true, nocache: false}, - {pattern: './client/assets/images/**/*', included: false, served: true, nocache: false}, + {pattern: './client/assets/images/**/*', included: false, served: true, nocache: false} ], proxies: { - '/images/': '/base/client/assets/images/', + '/images/': '/base/client/assets/images/' }, // preprocess matching files before serving them to the browser @@ -43,7 +43,7 @@ module.exports = function(config) { preprocessors: { './tests/**/*.js': ['babel'], './client/app/**/*.spec.js': ['babel'], - './client/app.js': ['webpack'], + './client/app.js': ['webpack'] }, // test results reporter to use @@ -56,9 +56,9 @@ module.exports = function(config) { fixWebpackSourcePaths: true, 'report-config': { html: { - subdir: 'html', - }, - }, - }, - }); -}; + subdir: 'html' + } + } + } + }) +} diff --git a/language/index.js b/language/index.js index 71627dbc1..8b106b299 100644 --- a/language/index.js +++ b/language/index.js @@ -1,13 +1,13 @@ /* eslint-disable no-console, angular/log, no-process-exit, global-require */ -const fs = require('fs'); -const path = require('path'); -const args = process.argv; -let action = ''; -let config = {}; -const zanata = require('./zanata'); -const configFile = path.join(__dirname, '../zanata.local.json'); -const availableLanguages = require('../client/gettext/json/available_languages.json'); -const languages = setLanguages(availableLanguages); +const fs = require('fs') +const path = require('path') +const args = process.argv +let action = '' +let config = {} +const zanata = require('./zanata') +const configFile = path.join(__dirname, '../zanata.local.json') +const availableLanguages = require('../client/gettext/json/available_languages.json') +const languages = setLanguages(availableLanguages) /** * Sample Zanata config file * { @@ -18,42 +18,42 @@ const languages = setLanguages(availableLanguages); } */ if (fs.existsSync(configFile)) { - config = require(configFile); + config = require(configFile) } else { if (!process.env.apiKey) { - console.log("Please set env variables or create config file"); - process.exit(1); + console.log('Please set env variables or create config file') + process.exit(1) } else { - config.apiKey = process.env.apiKey; - config.project = process.env.project; - config.version = process.env.version; - config.user = process.env.user; + config.apiKey = process.env.apiKey + config.project = process.env.project + config.version = process.env.version + config.user = process.env.user } } -zanata.setConfig(config); +zanata.setConfig(config) if (args.length < 3) { - console.log('Did not specify the correct number of args'); - process.exit(1); + console.log('Did not specify the correct number of args') + process.exit(1) } else { - action = args[2]; + action = args[2] } if (action === 'upload') { - const potFile = path.join(__dirname, '../client/gettext/po/manageiq-ui-service.pot'); - zanata.upload(potFile); + const potFile = path.join(__dirname, '../client/gettext/po/manageiq-ui-service.pot') + zanata.upload(potFile) } else if (action === 'download') { - console.log("Downloading Files"); - const outputDir = path.join(__dirname, '../client/gettext/po/'); + console.log('Downloading Files') + const outputDir = path.join(__dirname, '../client/gettext/po/') - zanata.download(languages, outputDir); + zanata.download(languages, outputDir) } -function setLanguages(languageList) { - const tmpLanguages = []; +function setLanguages (languageList) { + const tmpLanguages = [] for (var key in languageList) { - tmpLanguages.push(key); + tmpLanguages.push(key) } - return tmpLanguages; + return tmpLanguages } diff --git a/language/zanata.js b/language/zanata.js index a2e25afc5..c192f0bd5 100644 --- a/language/zanata.js +++ b/language/zanata.js @@ -1,73 +1,73 @@ /* eslint-disable no-undef, no-console, angular/log, angular/json-functions, no-return-assign */ -const axios = require('axios'); -const fs = require('fs'); -const Gettext = require('./gettext.js').Gettext; -const _ = require('lodash'); -let config = {}; +const axios = require('axios') +const fs = require('fs') +const Gettext = require('./gettext.js').Gettext +const _ = require('lodash') +let config = {} const zanata = { - setConfig(configSettings) { - config = configSettings; - axios.defaults.baseURL = `https://translate.zanata.org/zanata/`; - axios.defaults.headers.common['X-Auth-User'] = config.user; - axios.defaults.headers.common['X-Auth-Token'] = config.apiKey; + setConfig (configSettings) { + config = configSettings + axios.defaults.baseURL = `https://translate.zanata.org/zanata/` + axios.defaults.headers.common['X-Auth-User'] = config.user + axios.defaults.headers.common['X-Auth-Token'] = config.apiKey }, - upload(potFile) { - const contents = fs.readFileSync(potFile, 'UTF-8'); + upload (potFile) { + const contents = fs.readFileSync(potFile, 'UTF-8') Gettext.po2json('manageiq-ui-service.pot', 'pot', contents) .then((data) => { var requestConfig = { - headers: {'Content-Type': 'application/json'}, - }; + headers: {'Content-Type': 'application/json'} + } axios.put(`rest/projects/p/${config.project}/iterations/i/${config.version}/r/manageiq-ui-service`, JSON.stringify(data), requestConfig).then((response) => { // console.log(response); - if (response.status === 200) { - console.log('POT file uploaded successfully'); - } - }); - }); + if (response.status === 200) { + console.log('POT file uploaded successfully') + } + }) + }) }, - download(locales, outputDir) { + download (locales, outputDir) { zanata.getSourceFile().then((outputFile) => { locales.forEach((locale) => { - console.log("downloading locale " + locale); + console.log('downloading locale ' + locale) zanata.getFile(locale).then((data) => { - const sourceFile = _.clone(outputFile); - Object.keys(data).forEach((k) => sourceFile[k] = data[k]); + const sourceFile = _.clone(outputFile) + Object.keys(data).forEach((k) => sourceFile[k] = data[k]) Gettext.json2po(sourceFile).then((poData) => { - const poFilename = locale.replace(/-/g, '_'); - fs.writeFile(`${outputDir}/${locale}/${poFilename}.po`, poData.toString(), function(err) { + const poFilename = locale.replace(/-/g, '_') + fs.writeFile(`${outputDir}/${locale}/${poFilename}.po`, poData.toString(), function (err) { if (err) { - return console.log(err); + return console.log(err) } - }); - }); - }); - }); - }); + }) + }) + }) + }) + }) }, - getFile(locale) { - return new Promise((resolve, _reject) => { + getFile (locale) { + return new Promise((resolve, reject) => { const reqConfig = { - headers: {'Accept': 'application/json'}, - }; - const url = `rest/projects/p/${config.project}/iterations/i/${config.version}/r/manageiq-ui-service/translations/${locale}?ext=gettext&ext=comment&skeletons=true`; + headers: {'Accept': 'application/json'} + } + const url = `rest/projects/p/${config.project}/iterations/i/${config.version}/r/manageiq-ui-service/translations/${locale}?ext=gettext&ext=comment&skeletons=true` axios.get(url, reqConfig).then((data) => { - resolve(data.data); - }); - }); + resolve(data.data) + }) + }) }, - getSourceFile() { - return new Promise((resolve, _reject) => { + getSourceFile () { + return new Promise((resolve, reject) => { const reqConfig = { - headers: {'Accept': 'application/json'}, - }; - const url = `rest/projects/p/${config.project}/iterations/i/${config.version}/r/manageiq-ui-service?ext=gettext&ext=comment`; + headers: {'Accept': 'application/json'} + } + const url = `rest/projects/p/${config.project}/iterations/i/${config.version}/r/manageiq-ui-service?ext=gettext&ext=comment` axios.get(url, reqConfig).then((data) => { - resolve(data.data); - }); - }); - }, -}; -module.exports = zanata; + resolve(data.data) + }) + }) + } +} +module.exports = zanata diff --git a/postcss.config.js b/postcss.config.js index 4732bdac6..8a19a4f04 100644 --- a/postcss.config.js +++ b/postcss.config.js @@ -2,6 +2,6 @@ module.exports = { plugins: [ - require('autoprefixer')(), - ], -}; + require('autoprefixer')() + ] +} diff --git a/protractor.conf.js b/protractor.conf.js index ea2212ffb..1e2eac5b3 100644 --- a/protractor.conf.js +++ b/protractor.conf.js @@ -1,6 +1,6 @@ /* eslint-disable angular/definedundefined, angular/log, no-console, no-process-exit */ -var webServerDefaultPort = 3001; +var webServerDefaultPort = 3001 var env = { // The address of a running selenium server. @@ -12,7 +12,7 @@ var env = { 'browserName': (process.env.TEST_BROWSER_NAME || 'chrome'), 'version': - (process.env.TEST_BROWSER_VERSION || 'ANY'), + (process.env.TEST_BROWSER_VERSION || 'ANY') }, // Default http port to host the web server @@ -23,54 +23,54 @@ var env = { // A base URL for your application under test. baseUrl: - 'http://' + (process.env.HTTP_HOST || 'localhost') - + ':' + (process.env.HTTP_PORT || webServerDefaultPort), + 'http://' + (process.env.HTTP_HOST || 'localhost') + + ':' + (process.env.HTTP_PORT || webServerDefaultPort) -}; +} // This is the configuration file showing how a suite of tests might // handle log-in using the onPrepare field. var config = { specs: [ - '**/*.e2e.js', + '**/*.e2e.js' ], capabilities: env.capabilities, baseUrl: env.baseUrl + '/', - onPrepare: function() { + onPrepare: function () { // Required for protractor to work with a hybrid AngularJs/Angular app - browser.ignoreSynchronization = true; - browser.waitForAngularEnabled(false); + browser.ignoreSynchronization = true + browser.waitForAngularEnabled(false) - browser.driver.manage().window().setSize(1400, 900); - browser.driver.get(env.baseUrl ); - browser.driver.findElement(by.id('inputUsername')).sendKeys('admin'); - browser.driver.findElement(by.id('inputPassword')).sendKeys('smartvm'); - browser.driver.findElement(by.css('button[type=submit]')).click(); + browser.driver.manage().window().setSize(1400, 900) + browser.driver.get(env.baseUrl) + browser.driver.findElement(by.id('inputUsername')).sendKeys('admin') + browser.driver.findElement(by.id('inputPassword')).sendKeys('smartvm') + browser.driver.findElement(by.css('button[type=submit]')).click() return browser.driver.wait( protractor.until.urlIs(browser.baseUrl), 10 * 1000, 'Browser did not redirect to dashboard after logging in...' - ); - }, -}; + ) + } +} if (process.env.TRAVIS) { if (typeof process.env.SAUCE_USERNAME === 'undefined') { - console.log("E2E Testing was not run because Sauce credentials are not set. Please set in order to test"); - process.exit(); + console.log('E2E Testing was not run because Sauce credentials are not set. Please set in order to test') + process.exit() } - config.sauceUser = process.env.SAUCE_USERNAME; - config.sauceKey = process.env.SAUCE_ACCESS_KEY; + config.sauceUser = process.env.SAUCE_USERNAME + config.sauceKey = process.env.SAUCE_ACCESS_KEY config.capabilities = { 'browserName': 'chrome', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, - 'build': process.env.TRAVIS_BUILD_NUMBER, - }; + 'build': process.env.TRAVIS_BUILD_NUMBER + } } else { - config.seleniumAddress = env.seleniumAddress; + config.seleniumAddress = env.seleniumAddress } -module.exports.config = exports.config = config; +module.exports.config = exports.config = config diff --git a/server/app.js b/server/app.js index c0667539b..0eed92d21 100644 --- a/server/app.js +++ b/server/app.js @@ -1,77 +1,77 @@ /* eslint-disable no-undef, no-console, angular/log, no-path-concat */ -const path = require('path'); -const http = require('http'); -const express = require('express'); -const helmet = require('helmet'); -const bodyParser = require('body-parser'); -const favicon = require('serve-favicon'); -const logger = require('morgan'); -const httpProxy = require('http-proxy'); -const four0four = require('./utils/404')(); -const proxyService = require('./utils/proxy')(); -const serviceApi = require('./utils/serviceApi'); +const path = require('path') +const http = require('http') +const express = require('express') +const helmet = require('helmet') +const bodyParser = require('body-parser') +const favicon = require('serve-favicon') +const logger = require('morgan') +const httpProxy = require('http-proxy') +const four0four = require('./utils/404')() +const proxyService = require('./utils/proxy')() +const serviceApi = require('./utils/serviceApi') -const buildOutputPath = process.env.BUILD_OUTPUT || './'; -const app = express(); -const port = process.env.PORT || 3001; -const environment = process.env.NODE_ENV; +const buildOutputPath = process.env.BUILD_OUTPUT || './' +const app = express() +const port = process.env.PORT || 3001 +const environment = process.env.NODE_ENV // Secure http headers -app.use(helmet()); +app.use(helmet()) // Api -app.use('/api', serviceApi); +app.use('/api', serviceApi) // Endowing these assets with higher precedence than api will cause issues -app.use(favicon(__dirname + '/favicon.ico')); -app.use(bodyParser.urlencoded({ extended: true })); -app.use(bodyParser.json()); -app.use(logger('dev')); +app.use(favicon(__dirname + '/favicon.ico')) +app.use(bodyParser.urlencoded({ extended: true })) +app.use(bodyParser.json()) +app.use(logger('dev')) -console.log('About to crank up node'); -console.log('PORT=' + port); -console.log('NODE_ENV=' + environment); +console.log('About to crank up node') +console.log('PORT=' + port) +console.log('NODE_ENV=' + environment) switch (environment) { case 'build': - console.log('** BUILD **'); - app.use(express.static('./build')); + console.log('** BUILD **') + app.use(express.static('./build')) // Any invalid calls for templateUrls are under app/* and should return 404 - app.use('/app/*', function(req, res) { - four0four.send404(req, res); - }); + app.use('/app/*', function (req, res) { + four0four.send404(req, res) + }) // Any deep link calls should return index.html - app.use('/*', express.static('./public/index.html')); - break; + app.use('/*', express.static('./public/index.html')) + break default: { - const proxyHost = proxyService.proxyHost(); - const proxyErrorHandler = proxyService.proxyErrorHandler; + const proxyHost = proxyService.proxyHost() + const proxyErrorHandler = proxyService.proxyErrorHandler - console.log('** DEV **'); - app.use(express.static(path.resolve(__dirname, buildOutputPath))); + console.log('** DEV **') + app.use(express.static(path.resolve(__dirname, buildOutputPath))) // dev routes - app.use('/pictures', function(req, res) { - pictureProxy.web(req, res, proxyErrorHandler(req, res)); - }); + app.use('/pictures', function (req, res) { + pictureProxy.web(req, res, proxyErrorHandler(req, res)) + }) const pictureProxy = httpProxy.createProxyServer({ - target: 'http://' + proxyHost + '/pictures', - }); + target: 'http://' + proxyHost + '/pictures' + }) app.all('*', function (_req, res, _next) { // Just send the index.html for other files to support HTML5Mode - res.sendFile(path.resolve(__dirname, buildOutputPath + '/index.html')); - }); - break; + res.sendFile(path.resolve(__dirname, buildOutputPath + '/index.html')) + }) + break } } -const server = http.createServer(app); +const server = http.createServer(app) -server.listen(port, function() { - console.log('Express server listening on port ' + port); - console.log('env = ' + app.get('env') + '\n__dirname = ' - + __dirname + '\nprocess.cwd = ' + process.cwd()); -}); +server.listen(port, function () { + console.log('Express server listening on port ' + port) + console.log('env = ' + app.get('env') + '\n__dirname = ' + + __dirname + '\nprocess.cwd = ' + process.cwd()) +}) diff --git a/server/utils/404.js b/server/utils/404.js index 72d1b674d..396398148 100644 --- a/server/utils/404.js +++ b/server/utils/404.js @@ -1,28 +1,28 @@ /* eslint-disable no-undef */ -'use strict'; +'use strict' -module.exports = function() { +module.exports = function () { var service = { notFoundMiddleware: notFoundMiddleware, - send404: send404, - }; + send404: send404 + } - return service; + return service - function notFoundMiddleware(req, res) { - send404(req, res, 'API endpoint not found'); + function notFoundMiddleware (req, res) { + send404(req, res, 'API endpoint not found') } - function send404(req, res, description) { + function send404 (req, res, description) { var data = { status: 404, message: 'Not Found', description: description, - url: req.url, - }; + url: req.url + } res.status(404) .send(data) - .end(); + .end() } -}; +} diff --git a/server/utils/proxy.js b/server/utils/proxy.js index 791004144..90e34e035 100644 --- a/server/utils/proxy.js +++ b/server/utils/proxy.js @@ -1,33 +1,33 @@ /* eslint-disable no-undef, no-console, no-process-env, angular/log */ -'use strict'; +'use strict' -module.exports = function() { +module.exports = function () { var service = { proxyHost: proxyHost, - proxyErrorHandler: proxyErrorHandler, - }; + proxyErrorHandler: proxyErrorHandler + } - return service; + return service // Private - function proxyHost() { - return process.env.PROXY_HOST || '[::1]:3000'; + function proxyHost () { + return process.env.PROXY_HOST || '[::1]:3000' } - function proxyErrorHandler(_req, res) { - return function(err, _data) { + function proxyErrorHandler (_req, res) { + return function (err, _data) { if (!err) { - return; + return } res.writeHead(500, { - 'Content-Type': 'text/plain', - }); + 'Content-Type': 'text/plain' + }) - res.end('Something went wrong: ' + err); - console.error(err); - }; + res.end('Something went wrong: ' + err) + console.error(err) + } } -}; +} diff --git a/server/utils/serviceApi.js b/server/utils/serviceApi.js index d718aa7ed..4df13cfd1 100644 --- a/server/utils/serviceApi.js +++ b/server/utils/serviceApi.js @@ -1,27 +1,27 @@ /* eslint-disable no-undef, no-console, angular/log */ -const express = require('express'); -const httpProxy = require('http-proxy'); -const url = require('url'); -const proxyService = require('./proxy')(); +const express = require('express') +const httpProxy = require('http-proxy') +const url = require('url') +const proxyService = require('./proxy')() -const router = express.Router(); +const router = express.Router() -const proxyHost = proxyService.proxyHost(); -const proxyTarget = 'http://' + proxyHost + '/api'; -const proxyErrorHandler = proxyService.proxyErrorHandler; +const proxyHost = proxyService.proxyHost() +const proxyTarget = 'http://' + proxyHost + '/api' +const proxyErrorHandler = proxyService.proxyErrorHandler const proxy = httpProxy.createProxyServer({ - target: proxyTarget, -}); + target: proxyTarget +}) router.use(function (req, res) { - const path = url.parse(req.url).path; - console.log('PROXY: ' + proxyTarget + path); + const path = url.parse(req.url).path + console.log('PROXY: ' + proxyTarget + path) if (req.url === '/?attributes=authorization') { - req.url = '?attributes=authorization'; + req.url = '?attributes=authorization' } - proxy.web(req, res, proxyErrorHandler(req, res)); -}); + proxy.web(req, res, proxyErrorHandler(req, res)) +}) -module.exports = router; +module.exports = router diff --git a/server/utils/serviceApp.js b/server/utils/serviceApp.js index 7d17c07a7..fd876da7b 100644 --- a/server/utils/serviceApp.js +++ b/server/utils/serviceApp.js @@ -1,15 +1,14 @@ /* eslint-disable no-undef, angular/log */ +'use strict' -'use strict'; +var express = require('express') -var express = require('express'); +var router = express.Router() -var router = express.Router(); +router.use(express.static('./client')) +router.use(express.static('./images')) +router.use(express.static('./.tmp')) +router.use(express.static('./node_modules')) -router.use(express.static('./client')); -router.use(express.static('./images')); -router.use(express.static('./.tmp')); -router.use(express.static('./node_modules')); - -module.exports = router; +module.exports = router diff --git a/server/utils/wsProxy.js b/server/utils/wsProxy.js index 0dd10dd85..f52d8bdd2 100644 --- a/server/utils/wsProxy.js +++ b/server/utils/wsProxy.js @@ -1,16 +1,16 @@ /* eslint-disable no-undef */ -'use strict'; +'use strict' -var httpProxy = require('http-proxy'); -var proxyService = require('./proxy')(); +var httpProxy = require('http-proxy') +var proxyService = require('./proxy')() -var proxyHost = proxyService.proxyHost(); -var proxyTarget = 'http://' + proxyHost; +var proxyHost = proxyService.proxyHost() +var proxyTarget = 'http://' + proxyHost var wsProxy = httpProxy.createProxyServer({ target: proxyTarget, - ws: true, -}); + ws: true +}) -module.exports = wsProxy; +module.exports = wsProxy diff --git a/skin-sample/skin.js b/skin-sample/skin.js index 362b1456f..7752e0f6c 100644 --- a/skin-sample/skin.js +++ b/skin-sample/skin.js @@ -1,22 +1,22 @@ -(function() { - 'use strict'; +(function () { + 'use strict' var text = { app: { - name: 'Magic UI', // app name + name: 'Magic UI' // app name }, login: { - brand: 'The <strong>Amazing</strong> Magic UI', // login screen - }, - }; + brand: 'The <strong>Amazing</strong> Magic UI' // login screen + } + } angular.module('app.skin', []) .constant('Text', text) - .config(configure); + .config(configure) /** @ngInject */ - function configure(routerHelperProvider, exceptionHandlerProvider) { - exceptionHandlerProvider.configure('[MAGIC] '); // error prefix - routerHelperProvider.configure({docTitle: 'Magic UI: '}); // page title + function configure (routerHelperProvider, exceptionHandlerProvider) { + exceptionHandlerProvider.configure('[MAGIC] ') // error prefix + routerHelperProvider.configure({docTitle: 'Magic UI: '}) // page title } -})(); +})() diff --git a/yarn.lock b/yarn.lock index c40c71b9b..ab98ba0d4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -151,7 +151,7 @@ ajv@^4.7.0, ajv@^4.9.1: co "^4.6.0" json-stable-stringify "^1.0.1" -ajv@^5.0.0, ajv@^5.1.5, ajv@^5.2.0: +ajv@^5.0.0, ajv@^5.1.5: version "5.2.1" resolved "https://registry.yarnpkg.com/ajv/-/ajv-5.2.1.tgz#dcd03045175883ba1b636e5ae9ec3df9ab85323a" dependencies: @@ -362,10 +362,6 @@ ansi-escapes@^1.1.0: version "1.4.0" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-1.4.0.tgz#d3a8a83b319aa67793662b13e761c7911422306e" -ansi-escapes@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-2.0.0.tgz#5bae52be424878dd9783e8910e3fc2922e83c81b" - ansi-html@0.0.7: version "0.0.7" resolved "https://registry.yarnpkg.com/ansi-html/-/ansi-html-0.0.7.tgz#813584021962a9e9e6fd039f940d12f56ca7859e" @@ -461,6 +457,13 @@ array-unique@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.2.1.tgz#a1d97ccafcbc2625cc70fadceb36a50c58b01a53" +array.prototype.find@^2.0.1: + version "2.0.4" + resolved "https://registry.yarnpkg.com/array.prototype.find/-/array.prototype.find-2.0.4.tgz#556a5c5362c08648323ddaeb9de9d14bc1864c90" + dependencies: + define-properties "^1.1.2" + es-abstract "^1.7.0" + arraybuffer.slice@0.0.6: version "0.0.6" resolved "https://registry.yarnpkg.com/arraybuffer.slice/-/arraybuffer.slice-0.0.6.tgz#f33b2159f0532a3f3107a272c0ccfbd1ad2979ca" @@ -575,6 +578,14 @@ babel-code-frame@^6.11.0, babel-code-frame@^6.22.0: esutils "^2.0.2" js-tokens "^3.0.0" +babel-code-frame@^6.16.0, babel-code-frame@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.26.0.tgz#63fd43f7dc1e3bb7ce35947db8fe369a3f58c74b" + dependencies: + chalk "^1.1.3" + esutils "^2.0.2" + js-tokens "^3.0.2" + babel-core@6.25.0, babel-core@^6.0.0, babel-core@^6.24.1: version "6.25.0" resolved "https://registry.yarnpkg.com/babel-core/-/babel-core-6.25.0.tgz#7dd42b0463c742e9d5296deb3ec67a9322dad729" @@ -650,6 +661,15 @@ babel-core@^5.4.3: trim-right "^1.0.0" try-resolve "^1.0.0" +babel-eslint@7.2.3: + version "7.2.3" + resolved "https://registry.yarnpkg.com/babel-eslint/-/babel-eslint-7.2.3.tgz#b2fe2d80126470f5c19442dc757253a897710827" + dependencies: + babel-code-frame "^6.22.0" + babel-traverse "^6.23.1" + babel-types "^6.23.0" + babylon "^6.17.0" + babel-generator@^6.18.0, babel-generator@^6.25.0: version "6.25.0" resolved "https://registry.yarnpkg.com/babel-generator/-/babel-generator-6.25.0.tgz#33a1af70d5f2890aeb465a4a7793c1df6a9ea9fc" @@ -1111,6 +1131,13 @@ babel-runtime@^6.18.0, babel-runtime@^6.22.0: core-js "^2.4.0" regenerator-runtime "^0.10.0" +babel-runtime@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.26.0.tgz#965c7058668e82b55d7bfe04ff2337bc8b5647fe" + dependencies: + core-js "^2.4.0" + regenerator-runtime "^0.11.0" + babel-template@^6.16.0, babel-template@^6.24.1, babel-template@^6.25.0: version "6.25.0" resolved "https://registry.yarnpkg.com/babel-template/-/babel-template-6.25.0.tgz#665241166b7c2aa4c619d71e192969552b10c071" @@ -1135,6 +1162,20 @@ babel-traverse@^6.18.0, babel-traverse@^6.24.1, babel-traverse@^6.25.0: invariant "^2.2.0" lodash "^4.2.0" +babel-traverse@^6.23.1: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-traverse/-/babel-traverse-6.26.0.tgz#46a9cbd7edcc62c8e5c064e2d2d8d0f4035766ee" + dependencies: + babel-code-frame "^6.26.0" + babel-messages "^6.23.0" + babel-runtime "^6.26.0" + babel-types "^6.26.0" + babylon "^6.18.0" + debug "^2.6.8" + globals "^9.18.0" + invariant "^2.2.2" + lodash "^4.17.4" + babel-types@^6.18.0, babel-types@^6.19.0, babel-types@^6.24.1, babel-types@^6.25.0: version "6.25.0" resolved "https://registry.yarnpkg.com/babel-types/-/babel-types-6.25.0.tgz#70afb248d5660e5d18f811d91c8303b54134a18e" @@ -1144,6 +1185,15 @@ babel-types@^6.18.0, babel-types@^6.19.0, babel-types@^6.24.1, babel-types@^6.25 lodash "^4.2.0" to-fast-properties "^1.0.1" +babel-types@^6.23.0, babel-types@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-types/-/babel-types-6.26.0.tgz#a3b073f94ab49eb6fa55cd65227a334380632497" + dependencies: + babel-runtime "^6.26.0" + esutils "^2.0.2" + lodash "^4.17.4" + to-fast-properties "^1.0.3" + babylon@^5.8.38: version "5.8.38" resolved "https://registry.yarnpkg.com/babylon/-/babylon-5.8.38.tgz#ec9b120b11bf6ccd4173a18bf217e60b79859ffd" @@ -1152,6 +1202,10 @@ babylon@^6.11.4, babylon@^6.17.2, babylon@^6.17.4: version "6.17.4" resolved "https://registry.yarnpkg.com/babylon/-/babylon-6.17.4.tgz#3e8b7402b88d22c3423e137a1577883b15ff869a" +babylon@^6.17.0, babylon@^6.18.0: + version "6.18.0" + resolved "https://registry.yarnpkg.com/babylon/-/babylon-6.18.0.tgz#af2f3b88fa6f5c1e4c634d1a0f8eac4f55b395e3" + backo2@1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/backo2/-/backo2-1.0.2.tgz#31ab1ac8b129363463e35b3ebb69f4dfcfba7947" @@ -1463,7 +1517,7 @@ buffer@^4.3.0: ieee754 "^1.1.4" isarray "^1.0.0" -builtin-modules@^1.0.0: +builtin-modules@^1.0.0, builtin-modules@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f" @@ -1677,12 +1731,6 @@ cli-cursor@^1.0.1: dependencies: restore-cursor "^1.0.1" -cli-cursor@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-2.1.0.tgz#b35dac376479facc3e94747d41d0d0f5238ffcb5" - dependencies: - restore-cursor "^2.0.0" - cli-width@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-2.1.0.tgz#b234ca209b29ef66fc518d9b98d5847b00edf00a" @@ -1864,7 +1912,7 @@ concat-map@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" -concat-stream@1.6.0, concat-stream@^1.4.6, concat-stream@^1.6.0: +concat-stream@1.6.0, concat-stream@^1.4.6, concat-stream@^1.5.0, concat-stream@^1.5.2: version "1.6.0" resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.0.tgz#0aac662fd52be78964d5532f694784e70110acf7" dependencies: @@ -1917,6 +1965,10 @@ constants-browserify@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/constants-browserify/-/constants-browserify-1.0.0.tgz#c20b96d8c617748aaf1c16021760cd27fcb8cb75" +contains-path@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/contains-path/-/contains-path-0.1.0.tgz#fe8cf184ff6670b6baef01a9d4861a5cbec4120a" + content-disposition@0.5.2: version "0.5.2" resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.2.tgz#0cf68bb9ddf5f2be7961c3a85178cb85dba78cb4" @@ -2044,14 +2096,6 @@ cross-spawn@^4.0.0: lru-cache "^4.0.1" which "^1.2.9" -cross-spawn@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-5.1.0.tgz#e8bd0efee58fcff6f8f94510a0a554bbfa235449" - dependencies: - lru-cache "^4.0.1" - shebang-command "^1.2.0" - which "^1.2.9" - cryptiles@2.x.x: version "2.0.5" resolved "https://registry.yarnpkg.com/cryptiles/-/cryptiles-2.0.5.tgz#3bdfecdc608147c1c67202fa291e7dca59eaa3b8" @@ -2291,6 +2335,10 @@ dateformat@^1.0.6: get-stdin "^4.0.1" meow "^3.3.0" +debug-log@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/debug-log/-/debug-log-1.0.1.tgz#2307632d4c04382b8df8a32f70b895046d52745f" + debug@2, debug@2.6.8, debug@^2.1.1, debug@^2.2.0, debug@^2.4.5, debug@^2.6.3, debug@^2.6.6, debug@^2.6.8: version "2.6.8" resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.8.tgz#e731531ca2ede27d188222427da17821d68ff4fc" @@ -2361,6 +2409,13 @@ default-require-extensions@^1.0.0: dependencies: strip-bom "^2.0.0" +define-properties@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.2.tgz#83a73f2fea569898fb737193c8f873caf6d45c94" + dependencies: + foreach "^2.0.5" + object-keys "^1.0.8" + defined@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/defined/-/defined-1.0.0.tgz#c98d9bcef75674188e110969151199e39b1fa693" @@ -2380,6 +2435,17 @@ defs@~1.1.0: tryor "~0.1.2" yargs "~3.27.0" +deglob@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/deglob/-/deglob-2.1.0.tgz#4d44abe16ef32c779b4972bd141a80325029a14a" + dependencies: + find-root "^1.0.0" + glob "^7.0.5" + ignore "^3.0.9" + pkg-config "^1.1.0" + run-parallel "^1.1.2" + uniq "^1.0.1" + del@^2.0.2, del@^2.2.0: version "2.2.2" resolved "https://registry.yarnpkg.com/del/-/del-2.2.2.tgz#c12c981d067846c84bcaf862cff930d907ffd1a8" @@ -2484,7 +2550,7 @@ dns-txt@^2.0.2: dependencies: buffer-indexof "^1.0.0" -doctrine@^1.2.2: +doctrine@1.5.0, doctrine@^1.2.2: version "1.5.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-1.5.0.tgz#379dce730f6166f76cefa4e6707a159b02c5a6fa" dependencies: @@ -2730,6 +2796,24 @@ errorhandler@^1.2.0: accepts "~1.3.3" escape-html "~1.0.3" +es-abstract@^1.7.0: + version "1.8.0" + resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.8.0.tgz#3b00385e85729932beffa9163bbea1234e932914" + dependencies: + es-to-primitive "^1.1.1" + function-bind "^1.1.0" + has "^1.0.1" + is-callable "^1.1.3" + is-regex "^1.0.4" + +es-to-primitive@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.1.1.tgz#45355248a88979034b6792e19bb81f2b7975dd0d" + dependencies: + is-callable "^1.1.1" + is-date-object "^1.0.1" + is-symbol "^1.0.1" + es5-ext@^0.10.14, es5-ext@^0.10.9, es5-ext@~0.10.14: version "0.10.15" resolved "https://registry.yarnpkg.com/es5-ext/-/es5-ext-0.10.15.tgz#c330a5934c1ee21284a7c081a86e5fd937c91ea6" @@ -2829,67 +2913,75 @@ eslint-config-angular@0.5.0: version "0.5.0" resolved "https://registry.yarnpkg.com/eslint-config-angular/-/eslint-config-angular-0.5.0.tgz#e0aae0132e39e7467df3f7547fec81a44d3685c4" -eslint-loader@1.9.0: - version "1.9.0" - resolved "https://registry.yarnpkg.com/eslint-loader/-/eslint-loader-1.9.0.tgz#7e1be9feddca328d3dcfaef1ad49d5beffe83a13" +eslint-config-standard-jsx@4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/eslint-config-standard-jsx/-/eslint-config-standard-jsx-4.0.2.tgz#009e53c4ddb1e9ee70b4650ffe63a7f39f8836e1" + +eslint-config-standard@10.2.1: + version "10.2.1" + resolved "https://registry.yarnpkg.com/eslint-config-standard/-/eslint-config-standard-10.2.1.tgz#c061e4d066f379dc17cd562c64e819b4dd454591" + +eslint-import-resolver-node@^0.2.0: + version "0.2.3" + resolved "https://registry.yarnpkg.com/eslint-import-resolver-node/-/eslint-import-resolver-node-0.2.3.tgz#5add8106e8c928db2cba232bcd9efa846e3da16c" dependencies: - loader-fs-cache "^1.0.0" - loader-utils "^1.0.2" + debug "^2.2.0" object-assign "^4.0.1" - object-hash "^1.1.4" - rimraf "^2.6.1" + resolve "^1.1.6" + +eslint-module-utils@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.1.1.tgz#abaec824177613b8a95b299639e1b6facf473449" + dependencies: + debug "^2.6.8" + pkg-dir "^1.0.0" eslint-plugin-angular@3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-angular/-/eslint-plugin-angular-3.0.0.tgz#495dba339c9af7fe2a595547746bddd6dc3ed7d3" -eslint-scope@^3.7.1: - version "3.7.1" - resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-3.7.1.tgz#3d63c3edfda02e06e01a452ad88caacc7cdcb6e8" +eslint-plugin-import@~2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.2.0.tgz#72ba306fad305d67c4816348a4699a4229ac8b4e" dependencies: - esrecurse "^4.1.0" - estraverse "^4.1.1" + builtin-modules "^1.1.1" + contains-path "^0.1.0" + debug "^2.2.0" + doctrine "1.5.0" + eslint-import-resolver-node "^0.2.0" + eslint-module-utils "^2.0.0" + has "^1.0.1" + lodash.cond "^4.3.0" + minimatch "^3.0.3" + pkg-up "^1.0.0" -eslint@4.4.1: - version "4.4.1" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-4.4.1.tgz#99cd7eafcffca2ff99a5c8f5f2a474d6364b4bd3" +eslint-plugin-node@~4.2.2: + version "4.2.3" + resolved "https://registry.yarnpkg.com/eslint-plugin-node/-/eslint-plugin-node-4.2.3.tgz#c04390ab8dbcbb6887174023d6f3a72769e63b97" dependencies: - ajv "^5.2.0" - babel-code-frame "^6.22.0" - chalk "^1.1.3" - concat-stream "^1.6.0" - cross-spawn "^5.1.0" - debug "^2.6.8" - doctrine "^2.0.0" - eslint-scope "^3.7.1" - espree "^3.5.0" - esquery "^1.0.0" - estraverse "^4.2.0" - esutils "^2.0.2" - file-entry-cache "^2.0.0" - functional-red-black-tree "^1.0.1" - glob "^7.1.2" - globals "^9.17.0" - ignore "^3.3.3" - imurmurhash "^0.1.4" - inquirer "^3.0.6" - is-resolvable "^1.0.0" - js-yaml "^3.9.1" - json-stable-stringify "^1.0.1" - levn "^0.3.0" - lodash "^4.17.4" + ignore "^3.0.11" minimatch "^3.0.2" - mkdirp "^0.5.1" - natural-compare "^1.4.0" - optionator "^0.8.2" - path-is-inside "^1.0.2" - pluralize "^4.0.0" - progress "^2.0.0" - require-uncached "^1.0.3" - semver "^5.3.0" - strip-json-comments "~2.0.1" - table "^4.0.1" - text-table "~0.2.0" + object-assign "^4.0.1" + resolve "^1.1.7" + semver "5.3.0" + +eslint-plugin-promise@~3.5.0: + version "3.5.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-promise/-/eslint-plugin-promise-3.5.0.tgz#78fbb6ffe047201627569e85a6c5373af2a68fca" + +eslint-plugin-react@~6.10.0: + version "6.10.3" + resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-6.10.3.tgz#c5435beb06774e12c7db2f6abaddcbf900cd3f78" + dependencies: + array.prototype.find "^2.0.1" + doctrine "^1.2.2" + has "^1.0.1" + jsx-ast-utils "^1.3.4" + object.assign "^4.0.4" + +eslint-plugin-standard@~3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/eslint-plugin-standard/-/eslint-plugin-standard-3.0.1.tgz#34d0c915b45edc6f010393c7eef3823b08565cf2" eslint@^2.7.0: version "2.13.1" @@ -2929,7 +3021,47 @@ eslint@^2.7.0: text-table "~0.2.0" user-home "^2.0.0" -espree@^3.1.6, espree@^3.5.0: +eslint@~3.19.0: + version "3.19.0" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-3.19.0.tgz#c8fc6201c7f40dd08941b87c085767386a679acc" + dependencies: + babel-code-frame "^6.16.0" + chalk "^1.1.3" + concat-stream "^1.5.2" + debug "^2.1.1" + doctrine "^2.0.0" + escope "^3.6.0" + espree "^3.4.0" + esquery "^1.0.0" + estraverse "^4.2.0" + esutils "^2.0.2" + file-entry-cache "^2.0.0" + glob "^7.0.3" + globals "^9.14.0" + ignore "^3.2.0" + imurmurhash "^0.1.4" + inquirer "^0.12.0" + is-my-json-valid "^2.10.0" + is-resolvable "^1.0.0" + js-yaml "^3.5.1" + json-stable-stringify "^1.0.0" + levn "^0.3.0" + lodash "^4.0.0" + mkdirp "^0.5.0" + natural-compare "^1.4.0" + optionator "^0.8.2" + path-is-inside "^1.0.1" + pluralize "^1.2.1" + progress "^1.1.8" + require-uncached "^1.0.2" + shelljs "^0.7.5" + strip-bom "^3.0.0" + strip-json-comments "~2.0.1" + table "^3.7.8" + text-table "~0.2.0" + user-home "^2.0.0" + +espree@^3.1.6, espree@^3.4.0: version "3.5.0" resolved "https://registry.yarnpkg.com/espree/-/espree-3.5.0.tgz#98358625bdd055861ea27e2867ea729faf463d8d" dependencies: @@ -3108,14 +3240,6 @@ extend@3, extend@^3.0.0, extend@~3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.1.tgz#a755ea7bc1adfcc5a31ce7e762dbaadc5e636444" -external-editor@^2.0.4: - version "2.0.4" - resolved "https://registry.yarnpkg.com/external-editor/-/external-editor-2.0.4.tgz#1ed9199da9cbfe2ef2f7a31b2fde8b0d12368972" - dependencies: - iconv-lite "^0.4.17" - jschardet "^1.4.2" - tmp "^0.0.31" - extglob@^0.3.1: version "0.3.2" resolved "https://registry.yarnpkg.com/extglob/-/extglob-0.3.2.tgz#2e18ff3d2f49ab2765cec9023f011daa8d8349a1" @@ -3181,12 +3305,6 @@ figures@^1.3.5: escape-string-regexp "^1.0.5" object-assign "^4.1.0" -figures@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/figures/-/figures-2.0.0.tgz#3ab1a2d2a62c8bfb431a0c94cb797a2fce27c962" - dependencies: - escape-string-regexp "^1.0.5" - file-entry-cache@^1.1.1: version "1.3.1" resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-1.3.1.tgz#44c61ea607ae4be9c1402f41f44270cbfe334ff8" @@ -3260,14 +3378,6 @@ finalhandler@~1.0.4: statuses "~1.3.1" unpipe "~1.0.0" -find-cache-dir@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/find-cache-dir/-/find-cache-dir-0.1.1.tgz#c8defae57c8a52a8a784f9e31c57c742e993a0b9" - dependencies: - commondir "^1.0.1" - mkdirp "^0.5.1" - pkg-dir "^1.0.0" - find-cache-dir@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/find-cache-dir/-/find-cache-dir-1.0.0.tgz#9288e3e9e3cc3748717d39eade17cf71fc30ee6f" @@ -3276,6 +3386,10 @@ find-cache-dir@^1.0.0: make-dir "^1.0.0" pkg-dir "^2.0.0" +find-root@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/find-root/-/find-root-1.1.0.tgz#abcfc8ba76f708c42a97b3d685b7e9450bfb9ce4" + find-up@^1.0.0: version "1.1.2" resolved "https://registry.yarnpkg.com/find-up/-/find-up-1.1.2.tgz#6b2e9822b1a2ce0a60ab64d610eccad53cb24d0f" @@ -3347,6 +3461,10 @@ for-own@^1.0.0: dependencies: for-in "^1.0.1" +foreach@^2.0.5: + version "2.0.5" + resolved "https://registry.yarnpkg.com/foreach/-/foreach-2.0.5.tgz#0bee005018aeb260d0a3af3ae658dd0136ec1b99" + forever-agent@~0.6.1: version "0.6.1" resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91" @@ -3439,14 +3557,10 @@ fstream@^1.0.0, fstream@^1.0.10, fstream@^1.0.2: mkdirp ">=0.5 0" rimraf "2" -function-bind@^1.0.2: +function-bind@^1.0.2, function-bind@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.0.tgz#16176714c801798e4e8f2cf7f7529467bb4a5771" -functional-red-black-tree@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327" - gauge@~2.7.1: version "2.7.4" resolved "https://registry.yarnpkg.com/gauge/-/gauge-2.7.4.tgz#2c03405c7538c39d7eb37b317022e325fb018bf7" @@ -3484,6 +3598,10 @@ get-stdin@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-4.0.1.tgz#b968c6b0a04384324902e8bf1a5df32579a450fe" +get-stdin@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-5.0.1.tgz#122e161591e21ff4c52530305693f20e6393a398" + get-stream@^2.2.0: version "2.3.1" resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-2.3.1.tgz#5f38f93f346009666ee0150a054167f91bdd95de" @@ -3532,7 +3650,7 @@ glob@7.1.1: once "^1.3.0" path-is-absolute "^1.0.0" -glob@7.1.2, glob@^7.0.0, glob@^7.0.3, glob@^7.0.5, glob@^7.0.6, glob@^7.1, glob@^7.1.1, glob@^7.1.2, glob@~7.1.1: +glob@7.1.2, glob@^7.0.0, glob@^7.0.3, glob@^7.0.5, glob@^7.0.6, glob@^7.1, glob@^7.1.1, glob@~7.1.1: version "7.1.2" resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15" dependencies: @@ -3582,10 +3700,14 @@ globals@^6.4.0: version "6.4.1" resolved "https://registry.yarnpkg.com/globals/-/globals-6.4.1.tgz#8498032b3b6d1cc81eebc5f79690d8fe29fabf4f" -globals@^9.0.0, globals@^9.17.0, globals@^9.2.0: +globals@^9.0.0, globals@^9.2.0: version "9.17.0" resolved "https://registry.yarnpkg.com/globals/-/globals-9.17.0.tgz#0c0ca696d9b9bb694d2e5470bd37777caad50286" +globals@^9.14.0, globals@^9.18.0: + version "9.18.0" + resolved "https://registry.yarnpkg.com/globals/-/globals-9.18.0.tgz#aa3896b3e69b487f17e31ed2143d69a8e30c2d8a" + globby@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/globby/-/globby-5.0.0.tgz#ebd84667ca0dbb330b99bcfc68eac2bc54370e0d" @@ -4027,7 +4149,7 @@ iconv-lite@0.4.15: version "0.4.15" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.15.tgz#fe265a218ac6a57cfe854927e9d04c19825eddeb" -iconv-lite@^0.4.17, iconv-lite@^0.4.5: +iconv-lite@^0.4.5: version "0.4.18" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.18.tgz#23d8656b16aae6742ac29732ea8f0336a4789cf2" @@ -4057,7 +4179,7 @@ ienoopen@1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/ienoopen/-/ienoopen-1.0.0.tgz#346a428f474aac8f50cf3784ea2d0f16f62bda6b" -ignore@^3.1.2, ignore@^3.3.3: +ignore@^3.0.11, ignore@^3.0.9, ignore@^3.1.2, ignore@^3.2.0: version "3.3.3" resolved "https://registry.yarnpkg.com/ignore/-/ignore-3.3.3.tgz#432352e57accd87ab3110e82d3fea0e47812156d" @@ -4131,25 +4253,6 @@ inquirer@^0.12.0: strip-ansi "^3.0.0" through "^2.3.6" -inquirer@^3.0.6: - version "3.1.1" - resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-3.1.1.tgz#87621c4fba4072f48a8dd71c9f9df6f100b2d534" - dependencies: - ansi-escapes "^2.0.0" - chalk "^1.0.0" - cli-cursor "^2.1.0" - cli-width "^2.0.0" - external-editor "^2.0.4" - figures "^2.0.0" - lodash "^4.3.0" - mute-stream "0.0.7" - run-async "^2.2.0" - rx-lite "^4.0.8" - rx-lite-aggregates "^4.0.8" - string-width "^2.0.0" - strip-ansi "^3.0.0" - through "^2.3.6" - internal-ip@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/internal-ip/-/internal-ip-1.2.0.tgz#ae9fbf93b984878785d50a8de1b356956058cf5c" @@ -4202,6 +4305,14 @@ is-builtin-module@^1.0.0: dependencies: builtin-modules "^1.0.0" +is-callable@^1.1.1, is-callable@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.1.3.tgz#86eb75392805ddc33af71c92a0eedf74ee7604b2" + +is-date-object@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.1.tgz#9aa20eb6aeebbff77fbd33e74ca01b33581d3a16" + is-directory@^0.3.1: version "0.3.1" resolved "https://registry.yarnpkg.com/is-directory/-/is-directory-0.3.1.tgz#61339b6f2475fc772fd9c9d83f5c8575dc154ae1" @@ -4335,6 +4446,12 @@ is-redirect@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-redirect/-/is-redirect-1.0.0.tgz#1d03dded53bd8db0f30c26e4f95d36fc7c87dc24" +is-regex@^1.0.4: + version "1.0.4" + resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.0.4.tgz#5517489b547091b0930e095654ced25ee97e9491" + dependencies: + has "^1.0.1" + is-resolvable@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-resolvable/-/is-resolvable-1.0.0.tgz#8df57c61ea2e3c501408d100fb013cf8d6e0cc62" @@ -4355,6 +4472,10 @@ is-svg@^2.0.0: dependencies: html-comment-regex "^1.1.0" +is-symbol@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.1.tgz#3cc59f00025194b6ab2e38dbae6689256b660572" + is-typedarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" @@ -4538,6 +4659,10 @@ js-tokens@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.1.tgz#08e9f132484a2c45a30907e9dc4d5567b7f114d7" +js-tokens@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.2.tgz#9866df395102130e38f7f996bceb65443209c25b" + js-yaml@3.6.1: version "3.6.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.6.1.tgz#6e5fe67d8b205ce4d22fad05b7781e8dadcc4b30" @@ -4545,7 +4670,7 @@ js-yaml@3.6.1: argparse "^1.0.7" esprima "^2.6.0" -js-yaml@3.x, js-yaml@^3.4.3, js-yaml@^3.4.6, js-yaml@^3.5.1, js-yaml@^3.5.4, js-yaml@^3.7.0, js-yaml@^3.9.1: +js-yaml@3.x, js-yaml@^3.4.3, js-yaml@^3.4.6, js-yaml@^3.5.1, js-yaml@^3.5.4, js-yaml@^3.7.0: version "3.9.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.9.1.tgz#08775cebdfdd359209f0d2acd383c8f86a6904a0" dependencies: @@ -4570,10 +4695,6 @@ jsbn@~0.1.0: version "0.1.1" resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" -jschardet@^1.4.2: - version "1.4.2" - resolved "https://registry.yarnpkg.com/jschardet/-/jschardet-1.4.2.tgz#2aa107f142af4121d145659d44f50830961e699a" - jsesc@^0.5.0, jsesc@~0.5.0: version "0.5.0" resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-0.5.0.tgz#e7dee66e35d6fc16f710fe91d5cf69f70f08911d" @@ -4670,6 +4791,10 @@ jsprim@^1.2.2: json-schema "0.2.3" verror "1.3.6" +jsx-ast-utils@^1.3.4: + version "1.4.1" + resolved "https://registry.yarnpkg.com/jsx-ast-utils/-/jsx-ast-utils-1.4.1.tgz#3867213e8dd79bf1e8f2300c0cfc1efb182c0df1" + just-extend@^1.1.22: version "1.1.22" resolved "https://registry.yarnpkg.com/just-extend/-/just-extend-1.1.22.tgz#3330af756cab6a542700c64b2e4e4aa062d52fff" @@ -4876,13 +5001,6 @@ load-json-file@^2.0.0: pify "^2.0.0" strip-bom "^3.0.0" -loader-fs-cache@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/loader-fs-cache/-/loader-fs-cache-1.0.1.tgz#56e0bf08bd9708b26a765b68509840c8dec9fdbc" - dependencies: - find-cache-dir "^0.1.1" - mkdirp "0.5.1" - loader-runner@^2.3.0: version "2.3.0" resolved "https://registry.yarnpkg.com/loader-runner/-/loader-runner-2.3.0.tgz#f482aea82d543e07921700d5a46ef26fdac6b8a2" @@ -4954,6 +5072,10 @@ lodash.clonedeep@^4.3.2: version "4.5.0" resolved "https://registry.yarnpkg.com/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz#e23f3f9c4f8fbdde872529c1071857a086e5ccef" +lodash.cond@^4.3.0: + version "4.5.2" + resolved "https://registry.yarnpkg.com/lodash.cond/-/lodash.cond-4.5.2.tgz#f471a1da486be60f6ab955d17115523dd1d255d5" + lodash.create@3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/lodash.create/-/lodash.create-3.1.1.tgz#d7f2849f0dbda7e04682bb8cd72ab022461debe7" @@ -5261,7 +5383,7 @@ minimist@1.1.x: version "1.1.3" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.1.3.tgz#3bedfd91a92d39016fcfaa1c681e8faa1a1efda8" -minimist@1.2.0, minimist@^1.1.0, minimist@^1.1.3, minimist@^1.2, minimist@^1.2.0: +minimist@1.2.0, minimist@^1.1.0, minimist@^1.1.1, minimist@^1.1.3, minimist@^1.2, minimist@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" @@ -5361,10 +5483,6 @@ mute-stream@0.0.5: version "0.0.5" resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.5.tgz#8fbfabb0a98a253d3184331f9e8deb7372fac6c0" -mute-stream@0.0.7: - version "0.0.7" - resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.7.tgz#3075ce93bc21b8fab43e1bc4da7e8115ed1e7bab" - nan@^2.3.0, nan@^2.3.2: version "2.6.2" resolved "https://registry.yarnpkg.com/nan/-/nan-2.6.2.tgz#e4ff34e6c95fdfb5aecc08de6596f43605a7db45" @@ -5635,7 +5753,7 @@ object-assign@4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.0.tgz#7a3b3d0e98063d43f4c03f2e8ae6cd51a86883a0" -object-assign@^4, object-assign@^4.0.1, object-assign@^4.1.0: +object-assign@^4, object-assign@^4.0.1, object-assign@^4.1.0, object-assign@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" @@ -5643,9 +5761,17 @@ object-component@0.0.3: version "0.0.3" resolved "https://registry.yarnpkg.com/object-component/-/object-component-0.0.3.tgz#f0c69aa50efc95b866c186f400a33769cb2f1291" -object-hash@^1.1.4: - version "1.1.8" - resolved "https://registry.yarnpkg.com/object-hash/-/object-hash-1.1.8.tgz#28a659cf987d96a4dabe7860289f3b5326c4a03c" +object-keys@^1.0.10, object-keys@^1.0.8: + version "1.0.11" + resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.0.11.tgz#c54601778ad560f1142ce0e01bcca8b56d13426d" + +object.assign@^4.0.4: + version "4.0.4" + resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.0.4.tgz#b1c9cc044ef1b9fe63606fc141abbb32e14730cc" + dependencies: + define-properties "^1.1.2" + function-bind "^1.1.0" + object-keys "^1.0.10" object.omit@^2.0.0: version "2.0.1" @@ -5678,12 +5804,6 @@ onetime@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/onetime/-/onetime-1.1.0.tgz#a1f7838f8314c516f05ecefcbc4ccfe04b4ed789" -onetime@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/onetime/-/onetime-2.0.1.tgz#067428230fd67443b2794b22bba528b6867962d4" - dependencies: - mimic-fn "^1.0.0" - opn@4.0.2: version "4.0.2" resolved "https://registry.yarnpkg.com/opn/-/opn-4.0.2.tgz#7abc22e644dff63b0a96d5ab7f2790c0f01abc95" @@ -5883,7 +6003,7 @@ path-is-absolute@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" -path-is-inside@^1.0.1, path-is-inside@^1.0.2: +path-is-inside@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/path-is-inside/-/path-is-inside-1.0.2.tgz#365417dede44430d1c11af61027facf074bdfc53" @@ -6063,6 +6183,21 @@ pinkie@^2.0.0: version "2.0.4" resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" +pkg-conf@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/pkg-conf/-/pkg-conf-2.0.0.tgz#071c87650403bccfb9c627f58751bfe47c067279" + dependencies: + find-up "^2.0.0" + load-json-file "^2.0.0" + +pkg-config@^1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/pkg-config/-/pkg-config-1.1.1.tgz#557ef22d73da3c8837107766c52eadabde298fe4" + dependencies: + debug-log "^1.0.0" + find-root "^1.0.0" + xtend "^4.0.1" + pkg-dir@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-1.0.0.tgz#7a4b508a8d5bb2d629d447056ff4e9c9314cf3d4" @@ -6075,6 +6210,12 @@ pkg-dir@^2.0.0: dependencies: find-up "^2.1.0" +pkg-up@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/pkg-up/-/pkg-up-1.0.0.tgz#3e08fb461525c4421624a33b9f7e6d0af5b05a26" + dependencies: + find-up "^1.0.0" + platform@1.3.4: version "1.3.4" resolved "https://registry.yarnpkg.com/platform/-/platform-1.3.4.tgz#6f0fb17edaaa48f21442b3a975c063130f1c3ebd" @@ -6087,10 +6228,6 @@ pluralize@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-3.1.0.tgz#84213d0a12356069daa84060c559242633161368" -pluralize@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-4.0.0.tgz#59b708c1c0190a2f692f1c7618c446b052fd1762" - pofile@~1.0.0: version "1.0.8" resolved "https://registry.yarnpkg.com/pofile/-/pofile-1.0.8.tgz#09246a1788035404fc4d1ee087fa5e9ea686567d" @@ -6416,10 +6553,6 @@ progress@^1.1.8, progress@~1.1.8: version "1.1.8" resolved "https://registry.yarnpkg.com/progress/-/progress-1.1.8.tgz#e260c78f6161cdd9b0e56cc3e0a85de17c7a57be" -progress@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.0.tgz#8a1be366bf8fc23db2bd23f10c6fe920b4389d1f" - protractor@5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/protractor/-/protractor-5.1.2.tgz#9b221741709a4c62d5cd53c6aadd54a71137e95f" @@ -6658,6 +6791,12 @@ recast@^0.11.17, recast@~0.11.12: private "~0.1.5" source-map "~0.5.0" +rechoir@^0.6.2: + version "0.6.2" + resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384" + dependencies: + resolve "^1.1.6" + redent@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/redent/-/redent-1.0.0.tgz#cf916ab1fd5f1f16dfb20822dd6ec7f730c2afde" @@ -6691,6 +6830,10 @@ regenerator-runtime@^0.10.0: version "0.10.5" resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.10.5.tgz#336c3efc1220adcedda2c9fab67b5a7955a33658" +regenerator-runtime@^0.11.0: + version "0.11.0" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.11.0.tgz#7e54fe5b5ccd5d6624ea6255c3473be090b802e1" + regenerator-transform@0.9.11: version "0.9.11" resolved "https://registry.yarnpkg.com/regenerator-transform/-/regenerator-transform-0.9.11.tgz#3a7d067520cb7b7176769eb5ff868691befe1283" @@ -6874,7 +7017,7 @@ require-main-filename@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz#97f717b69d48784f5f526a6c5aa8ffdda055a4d1" -require-uncached@^1.0.2, require-uncached@^1.0.3: +require-uncached@^1.0.2: version "1.0.3" resolved "https://registry.yarnpkg.com/require-uncached/-/require-uncached-1.0.3.tgz#4e0d56d6c9662fd31e43011c4b95aa49955421d3" dependencies: @@ -6893,6 +7036,12 @@ resolve@1.1.x, resolve@^1.1.6: version "1.1.7" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" +resolve@^1.1.7: + version "1.4.0" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.4.0.tgz#a75be01c53da25d934a98ebd0e4c4a7312f92a86" + dependencies: + path-parse "^1.0.5" + restore-cursor@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-1.0.1.tgz#34661f46886327fed2991479152252df92daa541" @@ -6900,13 +7049,6 @@ restore-cursor@^1.0.1: exit-hook "^1.0.0" onetime "^1.0.0" -restore-cursor@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-2.0.0.tgz#9f7ee287f82fd326d4fd162923d62129eee0dfaf" - dependencies: - onetime "^2.0.0" - signal-exit "^3.0.2" - right-align@^0.1.1: version "0.1.3" resolved "https://registry.yarnpkg.com/right-align/-/right-align-0.1.3.tgz#61339b722fe6a3515689210d24e14c96148613ef" @@ -6939,21 +7081,9 @@ run-async@^0.1.0: dependencies: once "^1.3.0" -run-async@^2.2.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/run-async/-/run-async-2.3.0.tgz#0371ab4ae0bdd720d4166d7dfda64ff7a445a6c0" - dependencies: - is-promise "^2.1.0" - -rx-lite-aggregates@^4.0.8: - version "4.0.8" - resolved "https://registry.yarnpkg.com/rx-lite-aggregates/-/rx-lite-aggregates-4.0.8.tgz#753b87a89a11c95467c4ac1626c4efc4e05c67be" - dependencies: - rx-lite "*" - -rx-lite@*, rx-lite@^4.0.8: - version "4.0.8" - resolved "https://registry.yarnpkg.com/rx-lite/-/rx-lite-4.0.8.tgz#0b1e11af8bc44836f04a6407e92da42467b79444" +run-parallel@^1.1.2: + version "1.1.6" + resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.1.6.tgz#29003c9a2163e01e2d2dfc90575f2c6c1d61a039" rx-lite@^3.1.2: version "3.1.2" @@ -7077,7 +7207,7 @@ semver-diff@^2.0.0: dependencies: semver "^5.0.3" -"semver@2 || 3 || 4 || 5", semver@^5.0.1, semver@^5.0.3, semver@^5.1.0, semver@^5.3.0, semver@~5.3.0: +"semver@2 || 3 || 4 || 5", semver@5.3.0, semver@^5.0.1, semver@^5.0.3, semver@^5.1.0, semver@^5.3.0, semver@~5.3.0: version "5.3.0" resolved "https://registry.yarnpkg.com/semver/-/semver-5.3.0.tgz#9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f" @@ -7177,12 +7307,6 @@ shallow-clone@^0.1.2: lazy-cache "^0.2.3" mixin-object "^2.0.1" -shebang-command@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea" - dependencies: - shebang-regex "^1.0.0" - shebang-regex@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3" @@ -7191,6 +7315,14 @@ shelljs@^0.6.0: version "0.6.1" resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.6.1.tgz#ec6211bed1920442088fe0f70b2837232ed2c8a8" +shelljs@^0.7.5: + version "0.7.8" + resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.7.8.tgz#decbcf874b0d1e5fb72e14b164a9683048e9acb3" + dependencies: + glob "^7.0.0" + interpret "^1.0.0" + rechoir "^0.6.2" + shortid@^2.2.6: version "2.2.8" resolved "https://registry.yarnpkg.com/shortid/-/shortid-2.2.8.tgz#033b117d6a2e975804f6f0969dbe7d3d0b355131" @@ -7199,7 +7331,7 @@ sigmund@~1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/sigmund/-/sigmund-1.0.1.tgz#3ff21f198cad2175f9f3b781853fd94d0d19b590" -signal-exit@^3.0.0, signal-exit@^3.0.2: +signal-exit@^3.0.0: version "3.0.2" resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d" @@ -7241,6 +7373,18 @@ slide@^1.1.5: version "1.1.6" resolved "https://registry.yarnpkg.com/slide/-/slide-1.1.6.tgz#56eb027d65b4d2dce6cb2e2d32c4d4afc9e1d707" +snazzy@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/snazzy/-/snazzy-6.0.0.tgz#6a17d4798cbbc8bc6e113153694907a8bac9494d" + dependencies: + chalk "^1.1.0" + inherits "^2.0.1" + minimist "^1.1.1" + readable-stream "^2.0.6" + standard "*" + standard-json "^1.0.0" + text-table "^0.2.0" + sntp@1.x.x: version "1.0.9" resolved "https://registry.yarnpkg.com/sntp/-/sntp-1.0.9.tgz#6541184cc90aeea6c6e7b35e2659082443c66198" @@ -7428,6 +7572,43 @@ stable@~0.1.3, stable@~0.1.5: version "0.1.6" resolved "https://registry.yarnpkg.com/stable/-/stable-0.1.6.tgz#910f5d2aed7b520c6e777499c1f32e139fdecb10" +standard-engine@~7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/standard-engine/-/standard-engine-7.0.0.tgz#ebb77b9c8fc2c8165ffa353bd91ba0dff41af690" + dependencies: + deglob "^2.1.0" + get-stdin "^5.0.1" + minimist "^1.1.0" + pkg-conf "^2.0.0" + +standard-json@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/standard-json/-/standard-json-1.0.2.tgz#82dea4a14c78cd9e35d38cde4b88ac6b62596a23" + dependencies: + concat-stream "^1.5.0" + +standard-loader@6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/standard-loader/-/standard-loader-6.0.1.tgz#9bb4c7c229b5230f67899aa1bd798967f98ed1b6" + dependencies: + loader-utils "^1.0.2" + object-assign "^4.1.1" + snazzy "^6.0.0" + +standard@*, standard@10.0.3: + version "10.0.3" + resolved "https://registry.yarnpkg.com/standard/-/standard-10.0.3.tgz#7869bcbf422bdeeaab689a1ffb1fea9677dd50ea" + dependencies: + eslint "~3.19.0" + eslint-config-standard "10.2.1" + eslint-config-standard-jsx "4.0.2" + eslint-plugin-import "~2.2.0" + eslint-plugin-node "~4.2.2" + eslint-plugin-promise "~3.5.0" + eslint-plugin-react "~6.10.0" + eslint-plugin-standard "~3.0.1" + standard-engine "~7.0.0" + "statuses@>= 1.3.1 < 2", statuses@~1.3.1: version "1.3.1" resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.3.1.tgz#faf51b9eb74aaef3b3acf4ad5f61abf24cb7b93e" @@ -7598,17 +7779,6 @@ table@^3.7.8: slice-ansi "0.0.4" string-width "^2.0.0" -table@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/table/-/table-4.0.1.tgz#a8116c133fac2c61f4a420ab6cdf5c4d61f0e435" - dependencies: - ajv "^4.7.0" - ajv-keywords "^1.0.0" - chalk "^1.1.1" - lodash "^4.0.0" - slice-ansi "0.0.4" - string-width "^2.0.0" - tapable@^0.2.5, tapable@^0.2.7: version "0.2.8" resolved "https://registry.yarnpkg.com/tapable/-/tapable-0.2.8.tgz#99372a5c999bf2df160afc0d74bed4f47948cd22" @@ -7638,7 +7808,7 @@ text-encoding@0.6.4: version "0.6.4" resolved "https://registry.yarnpkg.com/text-encoding/-/text-encoding-0.6.4.tgz#e399a982257a276dae428bb92845cb71bdc26d19" -text-table@~0.2.0: +text-table@^0.2.0, text-table@~0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" @@ -7674,7 +7844,7 @@ tmp@0.0.30: dependencies: os-tmpdir "~1.0.1" -tmp@0.0.31, tmp@0.0.x, tmp@^0.0.31: +tmp@0.0.31, tmp@0.0.x: version "0.0.31" resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.31.tgz#8f38ab9438e17315e5dbd8b3657e8bfb277ae4a7" dependencies: @@ -7692,6 +7862,10 @@ to-fast-properties@^1.0.0, to-fast-properties@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-1.0.2.tgz#f3f5c0c3ba7299a7ef99427e44633257ade43320" +to-fast-properties@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-1.0.3.tgz#b83571fa4d8c25b82e231b06e3a3055de4ca1a47" + toposort@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/toposort/-/toposort-1.0.3.tgz#f02cd8a74bd8be2fc0e98611c3bacb95a171869c" @@ -8261,7 +8435,7 @@ xmlhttprequest-ssl@1.5.3: version "1.5.3" resolved "https://registry.yarnpkg.com/xmlhttprequest-ssl/-/xmlhttprequest-ssl-1.5.3.tgz#185a888c04eca46c3e4070d99f7b49de3528992d" -xtend@^4.0.0: +xtend@^4.0.0, xtend@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af"