1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2024-11-30 11:24:21 +01:00
fab-manager/app/assets/javascripts/controllers/application.coffee.erb

377 lines
12 KiB
Plaintext
Raw Normal View History

2015-05-05 03:10:25 +02:00
'use strict'
2016-11-23 14:27:11 +01:00
Application.Controllers.controller 'ApplicationController', ["$rootScope", "$scope", "$window", '$locale', "Session", "AuthService", "Auth", "$uibModal", "$state", 'growl', 'Notification', '$interval', "Setting", '_t', 'Version'
, ($rootScope, $scope, $window, $locale, Session, AuthService, Auth, $uibModal, $state, growl, Notification, $interval, Setting, _t, Version) ->
2015-05-05 03:10:25 +02:00
### PRIVATE STATIC CONSTANTS ###
# User's notifications will get refreshed every 30s
NOTIFICATIONS_CHECK_PERIOD = 30000
### PUBLIC SCOPE ###
## Fab-manager's version
$scope.version =
version: ''
2016-11-23 14:27:11 +01:00
## currency symbol for the current locale (cf. angular-i18n)
$rootScope.currencySymbol = $locale.NUMBER_FORMATS.CURRENCY_SYM;
2015-05-05 03:10:25 +02:00
##
# Set the current user to the provided value and initialize the session
# @param user {Object} Rails/Devise user
##
$scope.setCurrentUser = (user) ->
unless angular.isUndefinedOrNull(user)
$rootScope.currentUser = user
Session.create(user);
getNotifications()
# fab-manager's app-version
if user.role == 'admin'
$scope.version = Version.get()
else
$scope.version = {version: ''}
2015-05-05 03:10:25 +02:00
##
# Login callback
2016-03-23 18:39:41 +01:00
# @param e {Object} see https://docs.angularjs.org/guide/expression#-event-
2015-05-05 03:10:25 +02:00
# @param callback {function}
##
$scope.login = (e, callback) ->
e.preventDefault() if e
openLoginModal null, null, callback
##
# Logout callback
2016-03-23 18:39:41 +01:00
# @param e {Object} see https://docs.angularjs.org/guide/expression#-event-
2015-05-05 03:10:25 +02:00
##
$scope.logout = (e) ->
e.preventDefault()
Auth.logout().then (oldUser) ->
# console.log(oldUser.name + " you're signed out now.");
Session.destroy()
2016-03-23 18:39:41 +01:00
$rootScope.currentUser = null
2015-05-05 03:10:25 +02:00
$rootScope.toCheckNotifications = false
$scope.notifications =
total: 0
unread: 0
2015-05-05 03:10:25 +02:00
$state.go('app.public.home')
, (error) ->
# An error occurred logging out.
##
# Open the modal window allowing the user to create an account.
2016-03-23 18:39:41 +01:00
# @param e {Object} see https://docs.angularjs.org/guide/expression#-event-
2015-05-05 03:10:25 +02:00
##
$scope.signup = (e) ->
e.preventDefault() if e
2016-03-23 18:39:41 +01:00
$uibModal.open
2015-05-05 03:10:25 +02:00
templateUrl: '<%= asset_path "shared/signupModal.html" %>'
size: 'md'
2016-03-23 18:39:41 +01:00
controller: ['$scope', '$uibModalInstance', 'Group', 'CustomAsset', ($scope, $uibModalInstance, Group, CustomAsset) ->
2015-05-05 03:10:25 +02:00
# default parameters for the date picker in the account creation modal
$scope.datePicker =
format: Fablab.uibDateFormat
2015-05-05 03:10:25 +02:00
opened: false
options:
2016-03-23 18:39:41 +01:00
startingDay: Fablab.weekStartingDay
2015-05-05 03:10:25 +02:00
# callback to open the date picker (account creation modal)
$scope.openDatePicker = ($event) ->
$event.preventDefault()
$event.stopPropagation()
$scope.datePicker.opened = true
# retrieve the groups (standard, student ...)
Group.query (groups) ->
$scope.groups = groups
2016-03-23 18:39:41 +01:00
# retrieve the CGU
CustomAsset.get {name: 'cgu-file'}, (cgu) ->
$scope.cgu = cgu.custom_asset
2015-05-05 03:10:25 +02:00
# default user's parameters
$scope.user =
is_allow_contact: true
is_allow_newsletter: false
2015-05-05 03:10:25 +02:00
# Errors display
$scope.alerts = []
$scope.closeAlert = (index) ->
$scope.alerts.splice(index, 1)
# callback for form validation
$scope.ok = ->
# try to create the account
$scope.alerts = []
# remove 'organization' attribute
orga = $scope.user.organization
delete $scope.user.organization
# register on server
2015-05-05 03:10:25 +02:00
Auth.register($scope.user).then (user) ->
# creation successful
2016-03-23 18:39:41 +01:00
$uibModalInstance.close(user)
2015-05-05 03:10:25 +02:00
, (error) ->
# creation failed...
# restore organization param
$scope.user.organization = orga
# display errors
2015-05-05 03:10:25 +02:00
angular.forEach error.data.errors, (v, k) ->
angular.forEach 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)
##
# 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) ->
2016-03-23 18:39:41 +01:00
$uibModal.open
2015-05-05 03:10:25 +02:00
templateUrl: '<%= asset_path "shared/passwordEditModal.html" %>'
size: 'md'
2016-03-23 18:39:41 +01:00
controller: ['$scope', '$uibModalInstance', '$http', '_t', ($scope, $uibModalInstance, $http, _t) ->
2015-05-05 03:10:25 +02:00
$scope.user =
reset_password_token: token
$scope.alerts = []
$scope.closeAlert = (index) ->
$scope.alerts.splice(index, 1)
$scope.changePassword = ->
$scope.alerts = []
$http.put('/users/password.json', {user: $scope.user}).success (data) ->
2016-03-23 18:39:41 +01:00
$uibModalInstance.close()
2015-05-05 03:10:25 +02:00
.error (data) ->
angular.forEach data.errors, (v, k) ->
angular.forEach v, (err) ->
$scope.alerts.push
msg: k+': '+err
type: 'danger'
]
.result['finally'](null).then (user) ->
2016-03-23 18:39:41 +01:00
growl.success(_t('your_password_was_successfully_changed'))
2015-05-05 03:10:25 +02:00
Auth.login().then (user) ->
$scope.setCurrentUser(user)
, (error) ->
# Authentication failed...
2016-03-23 18:39:41 +01:00
2015-05-05 03:10:25 +02:00
##
# Compact/Expend the width of the left navigation bar
2016-03-23 18:39:41 +01:00
# @param e {Object} see https://docs.angularjs.org/guide/expression#-event-
2015-05-05 03:10:25 +02:00
##
$scope.toggleNavSize = (event) ->
if typeof event == 'undefined'
2016-03-23 18:39:41 +01:00
console.error '[ApplicationController::toggleNavSize] Missing event parameter'
2015-05-05 03:10:25 +02:00
return
toggler = $(event.target)
toggler = toggler.closest('[data-toggle^="class"]') unless toggler.data('toggle')
$class = toggler.data()['toggle']
$target = toggler.data('target') or toggler.attr('data-link')
if $class
$tmp = $class.split(':')[1]
$classes = $tmp.split(',') if $tmp
if $target
$targets = $target.split(',')
if $classes and $classes.length
$.each $targets, ( index, value ) ->
if $classes[index].indexOf( '*' ) != -1
patt = new RegExp( '\\s'
+ $classes[index].replace( /\*/g, '[A-Za-z0-9-_]+' ).split( ' ' ).join( '\\s|\\s' )
+ '\\s', 'g' )
$(toggler).each ( i, it ) ->
cn = ' ' + it.className + ' '
while patt.test( cn )
cn = cn.replace( patt, ' ' )
it.className = $.trim( cn )
($targets[index] !='#') and $($targets[index]).toggleClass($classes[index]) or toggler.toggleClass($classes[index])
toggler.toggleClass('active')
return
### PRIVATE SCOPE ###
##
# Kind of constructor: these actions will be realized first when the controller is loaded
##
initialize = ->
2016-03-23 18:39:41 +01:00
2015-05-05 03:10:25 +02:00
# try to retrieve any currently logged user
Auth.login().then (user) ->
$scope.setCurrentUser(user)
# force users to complete their profile if they are not
2016-03-23 18:39:41 +01:00
if user.need_completion
$state.transitionTo('app.logged.profileCompletion')
2015-05-05 03:10:25 +02:00
, (error) ->
# Authentication failed...
$rootScope.toCheckNotifications = false
# bind to the $stateChangeStart event (AngularJS/UI-Router)
$rootScope.$on '$stateChangeStart', (event, toState, toParams, fromState, fromParams) ->
return unless toState.data
authorizedRoles = toState.data.authorizedRoles
unless AuthService.isAuthorized(authorizedRoles)
event.preventDefault()
if AuthService.isAuthenticated()
# user is not allowed
2016-03-23 18:39:41 +01:00
console.error('[ApplicationController::initialize] user is not allowed')
2015-05-05 03:10:25 +02:00
else
# user is not logged in
openLoginModal(toState, toParams)
2016-03-23 18:39:41 +01:00
Setting.get { name: 'fablab_name' }, (data)->
$scope.fablabName = data.setting.value
Setting.get { name: 'name_genre' }, (data)->
$scope.nameGenre = data.setting.value
2015-05-05 03:10:25 +02:00
# shorthands
$scope.isAuthenticated = Auth.isAuthenticated
$scope.isAuthorized = AuthService.isAuthorized
$rootScope.login = $scope.login
2015-05-05 03:10:25 +02:00
##
# Retreive once the notifications from the server and display a message popup for each new one.
# Then, periodically check for new notifications.
##
getNotifications = ->
$rootScope.toCheckNotifications = true
2016-03-23 18:39:41 +01:00
unless $rootScope.checkNotificationsIsInit or !$rootScope.currentUser
setTimeout ->
# we request the most recent notifications
Notification.last_unread (notifications) ->
$rootScope.lastCheck = new Date()
$scope.notifications = notifications.totals
2015-05-05 03:10:25 +02:00
toDisplay = []
angular.forEach notifications.notifications, (n) ->
toDisplay.push(n)
2015-05-05 03:10:25 +02:00
if toDisplay.length < notifications.totals.unread
toDisplay.push({message: {description: _t('and_NUMBER_other_notifications', {NUMBER: notifications.totals.unread - toDisplay.length}, "messageformat")}})
2015-05-05 03:10:25 +02:00
angular.forEach toDisplay, (notification) ->
growl.info(notification.message.description)
, 2000
2015-05-05 03:10:25 +02:00
checkNotifications = ->
if $rootScope.toCheckNotifications
Notification.polling({last_poll: $rootScope.lastCheck}).$promise.then (data) ->
$rootScope.lastCheck = new Date()
$scope.notifications = data.totals
angular.forEach data.notifications, (notification) ->
growl.info(notification.message.description)
2015-05-05 03:10:25 +02:00
$interval(checkNotifications, NOTIFICATIONS_CHECK_PERIOD)
$rootScope.checkNotificationsIsInit = true
##
# Open the modal window allowing the user to log in.
##
openLoginModal = (toState, toParams, callback) ->
2016-03-23 18:39:41 +01:00
<% active_provider = AuthProvider.active %>
<% if active_provider.providable_type != DatabaseProvider.name %>
$window.location.href = '<%=user_omniauth_authorize_path(AuthProvider.active.strategy_name.to_sym)%>'
<% else %>
$uibModal.open
2015-05-05 03:10:25 +02:00
templateUrl: '<%= asset_path "shared/deviseModal.html" %>'
size: 'sm'
2016-03-23 18:39:41 +01:00
controller: ['$scope', '$uibModalInstance', '_t', ($scope, $uibModalInstance, _t) ->
2015-05-05 03:10:25 +02:00
user = $scope.user = {}
$scope.login = () ->
Auth.login(user).then (user) ->
# Authentification succeeded ...
2016-03-23 18:39:41 +01:00
$uibModalInstance.close(user)
2015-05-05 03:10:25 +02:00
if callback and typeof callback is "function"
callback(user)
, (error) ->
# Authentication failed...
$scope.alerts = []
$scope.alerts.push
2016-03-23 18:39:41 +01:00
msg: _t('wrong_email_or_password')
2015-05-05 03:10:25 +02:00
type: 'danger'
# handle modal behaviors. The provided reason will be used to define the following actions
$scope.dismiss = ->
2016-03-23 18:39:41 +01:00
$uibModalInstance.dismiss('cancel')
2015-05-05 03:10:25 +02:00
$scope.openSignup = (e) ->
e.preventDefault()
2016-03-23 18:39:41 +01:00
$uibModalInstance.dismiss('signup')
2015-05-05 03:10:25 +02:00
$scope.openResetPassword = (e) ->
e.preventDefault()
2016-03-23 18:39:41 +01:00
$uibModalInstance.dismiss('resetPassword')
2015-05-05 03:10:25 +02:00
]
# what to do when the modal is closed
.result['finally'](null).then (user) ->
# authentification succeeded, set the session, gather the notifications and redirect
$scope.setCurrentUser(user)
if toState isnt null and toParams isnt null
$state.go(toState, toParams)
, (reason) ->
# authentification did not ended successfully
if reason is 'signup'
# open signup modal
$scope.signup()
else if reason is 'resetPassword'
# open the 'reset password' modal
2016-03-23 18:39:41 +01:00
$uibModal.open
2015-05-05 03:10:25 +02:00
templateUrl: '<%= asset_path "shared/passwordNewModal.html" %>'
size: 'sm'
2016-03-23 18:39:41 +01:00
controller: ['$scope', '$uibModalInstance', '$http', ($scope, $uibModalInstance, $http) ->
2015-05-05 03:10:25 +02:00
$scope.user = {email: ''}
$scope.sendReset = () ->
$scope.alerts = []
$http.post('/users/password.json', {user: $scope.user}).success ->
2016-03-23 18:39:41 +01:00
$uibModalInstance.close()
2015-05-05 03:10:25 +02:00
.error ->
$scope.alerts.push
2016-03-23 18:39:41 +01:00
msg: _t('your_email_address_is_unknown')
2015-05-05 03:10:25 +02:00
type: 'danger'
]
.result['finally'](null).then ->
2016-03-23 18:39:41 +01:00
growl.info(_t('you_will_receive_in_a_moment_an_email_with_instructions_to_reset_your_password'))
2015-05-05 03:10:25 +02:00
# otherwise the user just closed the modal
2016-03-23 18:39:41 +01:00
<% end %>
2015-05-05 03:10:25 +02:00
## !!! MUST BE CALLED AT THE END of the controller
initialize()
]