1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-01-18 07:52:23 +01:00

fixed javascript for application controller

This commit is contained in:
Sylvain 2018-11-07 16:36:10 +01:00
parent e7031c90d5
commit 39b18933b6

View File

@ -11,28 +11,28 @@
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
'use strict'
Application.Controllers.controller('ApplicationController', ['$rootScope', '$scope', '$window', '$locale', 'Session', 'AuthService', 'Auth', '$uibModal', '$state', 'growl', 'Notification', '$interval', 'Setting', '_t', 'Version',
function ($rootScope, $scope, $window, $locale, Session, AuthService, Auth, $uibModal, $state, growl, Notification, $interval, Setting, _t, Version) {
/* PRIVATE STATIC CONSTANTS */
// User's notifications will get refreshed every 30s
const NOTIFICATIONS_CHECK_PERIOD = 30000
/* PUBLIC SCOPE */
/* PUBLIC SCOPE */
// # Fab-manager's version
// Fab-manager's version
$scope.version =
{ version: '' }
// # currency symbol for the current locale (cf. angular-i18n)
// currency symbol for the current locale (cf. angular-i18n)
$rootScope.currencySymbol = $locale.NUMBER_FORMATS.CURRENCY_SYM
// #
// Set the current user to the provided value and initialize the session
// @param user {Object} Rails/Devise user
// #
/**
* Set the current user to the provided value and initialize the session
* @param user {Object} Rails/Devise user
*/
$scope.setCurrentUser = function (user) {
if (!angular.isUndefinedOrNull(user)) {
$rootScope.currentUser = user
@ -47,24 +47,23 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
}
}
// #
// Login callback
// @param e {Object} see https://docs.angularjs.org/guide/expression#-event-
// @param callback {function}
// #
/**
* Login callback
* @param e {Object} see https://docs.angularjs.org/guide/expression#-event-
* @param callback {function}
*/
$scope.login = function (e, callback) {
if (e) { e.preventDefault() }
return openLoginModal(null, null, callback)
}
// #
// Logout callback
// @param e {Object} see https://docs.angularjs.org/guide/expression#-event-
// #
/**
* Logout callback
* @param e {Object} see https://docs.angularjs.org/guide/expression#-event-
*/
$scope.logout = function (e) {
e.preventDefault()
return Auth.logout().then(function (oldUser) {
// console.log(oldUser.name + " you're signed out now.");
return Auth.logout().then(function () {
Session.destroy()
$rootScope.currentUser = null
$rootScope.toCheckNotifications = false
@ -73,15 +72,15 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
unread: 0
}
return $state.go('app.public.home')
}
, function (error) {})
}, function (error) {
console.error(`An error occurred logging out: ${error}`);
})
}
// An error occurred logging out.
// #
// Open the modal window allowing the user to create an account.
// @param e {Object} see https://docs.angularjs.org/guide/expression#-event-
// #
/**
* Open the modal window allowing the user to create an account.
* @param e {Object} see https://docs.angularjs.org/guide/expression#-event-
*/
$scope.signup = function (e) {
if (e) { e.preventDefault() }
@ -89,7 +88,7 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
templateUrl: '<%= asset_path "shared/signupModal.html" %>',
size: 'md',
controller: ['$scope', '$uibModalInstance', 'Group', 'CustomAsset', function ($scope, $uibModalInstance, Group, CustomAsset) {
// default parameters for the date picker in the account creation modal
// default parameters for the date picker in the account creation modal
$scope.datePicker = {
format: Fablab.uibDateFormat,
opened: false,
@ -106,10 +105,14 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
}
// retrieve the groups (standard, student ...)
Group.query(groups => $scope.groups = groups)
Group.query(function(groups) {
$scope.groups = groups;
})
// retrieve the CGU
CustomAsset.get({ name: 'cgu-file' }, cgu => $scope.cgu = cgu.custom_asset)
CustomAsset.get({ name: 'cgu-file' }, function(cgu) {
$scope.cgu = cgu.custom_asset;
})
// default user's parameters
$scope.user = {
@ -119,84 +122,87 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
// Errors display
$scope.alerts = []
$scope.closeAlert = index => $scope.alerts.splice(index, 1)
$scope.closeAlert = function (index) {
$scope.alerts.splice(index, 1);
};
// callback for form validation
return $scope.ok = function () {
$scope.ok = function () {
// try to create the account
$scope.alerts = []
$scope.alerts = [];
// remove 'organization' attribute
const orga = $scope.user.organization
delete $scope.user.organization
const orga = $scope.user.organization;
delete $scope.user.organization;
// register on server
return Auth.register($scope.user).then(user =>
// creation successful
return Auth.register($scope.user).then(function(user) {
// creation successful
$uibModalInstance.close(user)
, function (error) {
// creation failed...
// restore organization param
}, function (error) {
// creation failed...
// restore organization param
$scope.user.organization = orga
// display errors
return angular.forEach(error.data.errors, (v, k) =>
angular.forEach(v, err =>
angular.forEach(error.data.errors, function(v, k) {
angular.forEach(function (v, err) {
$scope.alerts.push({
msg: k + ': ' + err,
type: 'danger'
})
)
)
});
});
});
})
}
}
] })
.result['finally'](null).then(user =>
// when the account was created succesfully, set the session to the newly created account
$scope.setCurrentUser(user)
)
};
}]
}).result['finally'](null).then(function(user) {
// when the account was created successfully, set the session to the newly created account
$scope.setCurrentUser(user)
})
}
// #
// Open the modal window allowing the user to change his password.
// @param token {string} security token for password changing. The user should have recieved it by mail
// #
$scope.editPassword = token =>
/**
* Open the modal window allowing the user to change his password.
* @param token {string} security token for password changing. The user should have recieved it by mail
*/
$scope.editPassword = function(token) {
$uibModal.open({
templateUrl: '<%= asset_path "shared/passwordEditModal.html" %>',
size: 'md',
controller: ['$scope', '$uibModalInstance', '$http', '_t', function ($scope, $uibModalInstance, $http, _t) {
$scope.user =
{ reset_password_token: token }
$scope.alerts = []
$scope.closeAlert = index => $scope.alerts.splice(index, 1)
controller: ['$scope', '$uibModalInstance', '$http', function ($scope, $uibModalInstance, $http) {
$scope.user = { reset_password_token: token };
$scope.alerts = [];
$scope.closeAlert = function (index) {
$scope.alerts.splice(index, 1)
};
return $scope.changePassword = function () {
$scope.alerts = []
return $http.put('/users/password.json', { user: $scope.user }).success(data => $uibModalInstance.close()).error(data =>
angular.forEach(data.errors, (v, k) =>
angular.forEach(v, err =>
return $http.put('/users/password.json', { user: $scope.user }).success(function () { $uibModalInstance.close() }).error(function (data) {
angular.forEach(data.errors, function(v, k) {
angular.forEach(function(v, err) {
$scope.alerts.push({
msg: k + ': ' + err,
type: 'danger'
})
)
)
)
});
});
});
})
}
}]
}).result['finally'](null).then(function () {
growl.success(_t('your_password_was_successfully_changed'))
return Auth.login().then(function(user) {
$scope.setCurrentUser(user)
}, function (error) {
console.error(`Authentication failed: ${error}`);
}
] })
.result['finally'](null).then(function (user) {
growl.success(_t('your_password_was_successfully_changed'))
return Auth.login().then(user => $scope.setCurrentUser(user)
, function (error) {})
})
)
})
};
// Authentication failed...
// #
// Compact/Expend the width of the left navigation bar
// @param e {Object} see https://docs.angularjs.org/guide/expression#-event-
// #
/**
* Compact/Expend the width of the left navigation bar
* @param event {Object} see https://docs.angularjs.org/guide/expression#-event-
*/
$scope.toggleNavSize = function (event) {
let $classes, $targets
if (typeof event === 'undefined') {
@ -220,7 +226,7 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
}
if ($classes && $classes.length) {
$.each($targets, function (index, value) {
$.each($targets, function (index) {
if ($classes[index].indexOf('*') !== -1) {
const patt = new RegExp('\\s',
+$classes[index].replace(/\*/g, '[A-Za-z0-9-_]+').split(' ').join('\\s|\\s'),
@ -241,26 +247,25 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
toggler.toggleClass('active')
}
/* PRIVATE SCOPE */
// #
// Kind of constructor: these actions will be realized first when the controller is loaded
// #
/* PRIVATE SCOPE */
/**
* Kind of constructor: these actions will be realized first when the controller is loaded
*/
const initialize = function () {
// try to retrieve any currently logged user
// try to retrieve any currently logged user
Auth.login().then(function (user) {
$scope.setCurrentUser(user)
// force users to complete their profile if they are not
if (user.need_completion) {
return $state.transitionTo('app.logged.profileCompletion')
}
}
, error =>
// Authentication failed...
}, function(error) {
console.error(`Authentication failed: ${error}`);
$rootScope.toCheckNotifications = false
)
})
// bind to the $stateChangeStart event (AngularJS/UI-Router)
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
if (!toState.data) { return }
const { authorizedRoles } = toState.data
@ -268,19 +273,19 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
event.preventDefault()
if (AuthService.isAuthenticated()) {
// user is not allowed
return console.error('[ApplicationController::initialize] user is not allowed')
console.error('[ApplicationController::initialize] user is not allowed')
} else {
// user is not logged in
return openLoginModal(toState, toParams)
openLoginModal(toState, toParams)
}
}
})
// we stop polling notifications when the page is not in foreground
onPageVisible(state => $rootScope.toCheckNotifications = (state === 'visible'))
onPageVisible(function(state) { $rootScope.toCheckNotifications = (state === 'visible') })
Setting.get({ name: 'fablab_name' }, data => $scope.fablabName = data.setting.value)
Setting.get({ name: 'name_genre' }, data => $scope.nameGenre = data.setting.value)
Setting.get({ name: 'fablab_name' }, function(data) { $scope.fablabName = data.setting.value })
Setting.get({ name: 'name_genre' }, function(data) { $scope.nameGenre = data.setting.value })
// shorthands
$scope.isAuthenticated = Auth.isAuthenticated
@ -288,50 +293,50 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
return $rootScope.login = $scope.login
}
// #
// Retreive once the notifications from the server and display a message popup for each new one.
// Then, periodically check for new notifications.
// #
/**
* Retreive once the notifications from the server and display a message popup for each new one.
* Then, periodically check for new notifications.
*/
var getNotifications = function () {
$rootScope.toCheckNotifications = true
if (!$rootScope.checkNotificationsIsInit && !!$rootScope.currentUser) {
setTimeout(() =>
// we request the most recent notifications
setTimeout(function() {
// we request the most recent notifications
Notification.last_unread(function (notifications) {
$rootScope.lastCheck = new Date()
$scope.notifications = notifications.totals
const toDisplay = []
angular.forEach(notifications.notifications, n => toDisplay.push(n))
const toDisplay = [];
angular.forEach(notifications.notifications, function(n) { toDisplay.push(n) });
if (toDisplay.length < notifications.totals.unread) {
toDisplay.push({ message: { description: _t('and_NUMBER_other_notifications', { NUMBER: notifications.totals.unread - toDisplay.length }, 'messageformat') } })
toDisplay.push({ message: { description: _t('and_NUMBER_other_notifications', { NUMBER: notifications.totals.unread - toDisplay.length }, 'messageformat') } });
}
return angular.forEach(toDisplay, notification => growl.info(notification.message.description))
angular.forEach(toDisplay, function(notification) { growl.info(notification.message.description); })
})
, 2000)
}, 2000)
const checkNotifications = function () {
if ($rootScope.toCheckNotifications) {
return Notification.polling({ last_poll: $rootScope.lastCheck }).$promise.then(function (data) {
$rootScope.lastCheck = new Date()
$scope.notifications = data.totals
$rootScope.lastCheck = new Date();
$scope.notifications = data.totals;
return angular.forEach(data.notifications, notification => growl.info(notification.message.description))
angular.forEach(data.notifications, function(notification) { growl.info(notification.message.description) });
})
}
}
};
$interval(checkNotifications, NOTIFICATIONS_CHECK_PERIOD)
return $rootScope.checkNotificationsIsInit = true
$interval(checkNotifications, NOTIFICATIONS_CHECK_PERIOD);
$rootScope.checkNotificationsIsInit = true;
}
}
// #
// Open the modal window allowing the user to log in.
// #
/**
* Open the modal window allowing the user to log in.
*/
var openLoginModal = function (toState, toParams, callback) {
<% active_provider = AuthProvider.active %>
<% if active_provider.providable_type != DatabaseProvider.name %>
@ -342,25 +347,25 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
size: 'sm',
controller: ['$scope', '$uibModalInstance', '_t', function ($scope, $uibModalInstance, _t) {
const user = ($scope.user = {})
$scope.login = () =>
$scope.login = function() {
Auth.login(user).then(function (user) {
// Authentification succeeded ...
// Authentication succeeded ...
$uibModalInstance.close(user)
if (callback && (typeof callback === 'function')) {
return callback(user)
}
}
, function (error) {
// Authentication failed...
$scope.alerts = []
console.error(`Authentication failed: ${error}`);
$scope.alerts = [];
return $scope.alerts.push({
msg: _t('wrong_email_or_password'),
type: 'danger'
})
})
}
// handle modal behaviors. The provided reason will be used to define the following actions
$scope.dismiss = () => $uibModalInstance.dismiss('cancel')
$scope.dismiss = function() { $uibModalInstance.dismiss('cancel') }
$scope.openSignup = function (e) {
e.preventDefault()
@ -371,24 +376,21 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
e.preventDefault()
return $uibModalInstance.dismiss('resetPassword')
}
}
] })
}]
}).result['finally'](null).then(function (user) {
// what to do when the modal is closed
// what to do when the modal is closed
.result['finally'](null).then(function (user) {
// authentification succeeded, set the session, gather the notifications and redirect
$scope.setCurrentUser(user)
// authentication succeeded, set the session, gather the notifications and redirect
$scope.setCurrentUser(user);
if ((toState !== null) && (toParams !== null)) {
return $state.go(toState, toParams)
}
}
, function (reason) {
// authentification did not ended successfully
}, function (reason) {
// authentication did not ended successfully
if (reason === 'signup') {
// open signup modal
return $scope.signup()
$scope.signup();
} else if (reason === 'resetPassword') {
// open the 'reset password' modal
return $uibModal.open({
@ -398,17 +400,15 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
$scope.user = { email: '' }
return $scope.sendReset = function () {
$scope.alerts = []
return $http.post('/users/password.json', { user: $scope.user }).success(() => $uibModalInstance.close()).error(() =>
return $http.post('/users/password.json', { user: $scope.user }).success(function() { $uibModalInstance.close() }).error(function() {
$scope.alerts.push({
msg: _t('your_email_address_is_unknown'),
type: 'danger'
})
)
});
})
}
}
] })
.result['finally'](null).then(() => growl.info(_t('you_will_receive_in_a_moment_an_email_with_instructions_to_reset_your_password')))
}]
}).result['finally'](null).then(function() { growl.info(_t('you_will_receive_in_a_moment_an_email_with_instructions_to_reset_your_password')) })
}
})
}
@ -416,11 +416,11 @@ Application.Controllers.controller('ApplicationController', ['$rootScope', '$sco
// otherwise the user just closed the modal
<% end %>
// #
// Detect if the current page (tab/window) is active of put as background.
// When the status changes, the callback is triggered with the new status as parameter
// Inspired by http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active#answer-1060034
// #
/**
* Detect if the current page (tab/window) is active of put as background.
* When the status changes, the callback is triggered with the new status as parameter
* Inspired by http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active#answer-1060034
*/
var onPageVisible = function (callback) {
let hidden = 'hidden'