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

fix ERB JS controllers

This commit is contained in:
Sylvain 2018-11-20 12:26:06 +01:00
parent aac0e8125c
commit 74b6afd166
14 changed files with 832 additions and 696 deletions

View File

@ -27,11 +27,12 @@ const METHODS = {
* @param id {*} id of the element to retrieve in the list
* @returns {number} index of the requested element, in the provided array
*/
const findIdxById = (elements, id) =>
(elements.map(elem => elem.id)).indexOf(id)
const findIdxById = function (elements, id) {
return (elements.map(function (elem) { return elem.id })).indexOf(id)
}
/**
* For OAuth2 ententications, mapping the user's ID is mendatory. This function will check that this mapping
* For OAuth2 authentications, mapping the user's ID is mandatory. This function will check that this mapping
* is effective and will return false otherwise
* @param mappings {Array<Object>} expected: $scope.provider.providable_attributes.o_auth2_mappings_attributes
* @returns {Boolean} true if the mapping is declared
@ -70,12 +71,12 @@ class AuthenticationController {
/**
* Changes the admin's view to the members list page
*/
$scope.cancel = () => $state.go('app.admin.members')
$scope.cancel = function() { $state.go('app.admin.members') }
/**
* Open a modal allowing to specify the data mapping for the given field
*/
$scope.defineDataMapping = mapping =>
$scope.defineDataMapping = function (mapping) {
$uibModal.open({
templateUrl: '<%= asset_path "admin/authentications/_data_mapping.html" %>',
size: 'md',
@ -133,13 +134,14 @@ class AuthenticationController {
}
// close and save the modifications
$scope.ok = () => $uibModalInstance.close($scope.transformation.rules)
$scope.ok = function () { $uibModalInstance.close($scope.transformation.rules) }
// do not save the modifications
return $scope.cancel = () => $uibModalInstance.dismiss()
return $scope.cancel = function () { $uibModalInstance.dismiss() }
}
] })
.result['finally'](null).then(transfo_rules => mapping.transformation = transfo_rules)
.result['finally'](null).then(function (transfo_rules) { mapping.transformation = transfo_rules })
}
}
}
@ -186,26 +188,31 @@ Application.Controllers.controller('AuthentificationController', ['$scope', '$st
* @param providers {Array} full list of authentication providers
* @param provider {Object} provider to delete
*/
return $scope.destroyProvider = (providers, provider) =>
dialogs.confirm({
resolve: {
object () {
return {
title: _t('confirmation_required'),
msg: _t('do_you_really_want_to_delete_the_TYPE_authentication_provider_NAME', { TYPE: $scope.getType(provider.providable_type), NAME: provider.name })
$scope.destroyProvider = function (providers, provider) {
dialogs.confirm(
{
resolve: {
object () {
return {
title: _t('confirmation_required'),
msg: _t('do_you_really_want_to_delete_the_TYPE_authentication_provider_NAME', { TYPE: $scope.getType(provider.providable_type), NAME: provider.name })
}
}
}
},
function() {
// the admin has confirmed, delete
AuthProvider.delete(
{ id: provider.id },
function () {
providers.splice(findIdxById(providers, provider.id), 1)
growl.success(_t('authentication_provider_successfully_deleted'))
},
function () { growl.error(_t('an_error_occurred_unable_to_delete_the_specified_provider')) }
)
}
}
, () =>
// the admin has confirmed, delete
AuthProvider.delete({ id: provider.id }
, function () {
providers.splice(findIdxById(providers, provider.id), 1)
return growl.success(_t('authentication_provider_successfully_deleted'))
}
, () => growl.error(_t('an_error_occurred_unable_to_delete_the_specified_provider')))
)
}
}
])
@ -264,27 +271,29 @@ Application.Controllers.controller('NewAuthenticationController', ['$scope', '$s
}
// discourage the use of unsecure SSO
if (!($scope.provider.providable_attributes.base_url.indexOf('https://') > -1)) {
return dialogs.confirm({
size: 'l',
resolve: {
object () {
return {
title: _t('security_issue_detected'),
msg: _t('beware_the_oauth2_authenticatoin_provider_you_are_about_to_add_isnt_using_HTTPS') +
_t('this_is_a_serious_security_issue_on_internet_and_should_never_be_used_except_for_testing_purposes') +
_t('do_you_really_want_to_continue')
dialogs.confirm(
{
size: 'l',
resolve: {
object () {
return {
title: _t('security_issue_detected'),
msg: _t('beware_the_oauth2_authenticatoin_provider_you_are_about_to_add_isnt_using_HTTPS') +
_t('this_is_a_serious_security_issue_on_internet_and_should_never_be_used_except_for_testing_purposes') +
_t('do_you_really_want_to_continue')
}
}
}
},
function () { // unsecured http confirmed
AuthProvider.save({auth_provider: $scope.provider}, function (provider) {
growl.success(_t('unsecured_oauth2_provider_successfully_added'))
return $state.go('app.admin.members')
})
}
}
, () => // unsecured http confirmed
AuthProvider.save({ auth_provider: $scope.provider }, function (provider) {
growl.success(_t('unsecured_oauth2_provider_successfully_added'))
return $state.go('app.admin.members')
})
)
} else {
return AuthProvider.save({ auth_provider: $scope.provider }, function (provider) {
AuthProvider.save({ auth_provider: $scope.provider }, function (provider) {
growl.success(_t('oauth2_provider_successfully_added'))
return $state.go('app.admin.members')
})
@ -316,11 +325,15 @@ Application.Controllers.controller('EditAuthenticationController', ['$scope', '$
growl.error(_t('it_is_required_to_set_the_matching_between_User.uid_and_the_API_to_add_this_provider'))
return false
}
return AuthProvider.update({ id: $scope.provider.id }, { auth_provider: $scope.provider }, function (provider) {
growl.success(_t('provider_successfully_updated'))
return $state.go('app.admin.members')
}
, () => growl.error(_t('an_error_occurred_unable_to_update_the_provider')))
return AuthProvider.update(
{ id: $scope.provider.id },
{ auth_provider: $scope.provider },
function (provider) {
growl.success(_t('provider_successfully_updated'))
$state.go('app.admin.members')
},
function() { growl.error(_t('an_error_occurred_unable_to_update_the_provider')) }
)
}
// Using the AuthenticationController

View File

@ -73,38 +73,43 @@ Application.Controllers.controller('AdminCalendarController', ['$scope', '$state
* Open a confirmation modal to cancel the booking of a user for the currently selected event.
* @param slot {Object} reservation slot of a user, inherited from $resource
*/
$scope.cancelBooking = slot =>
$scope.cancelBooking = function(slot) {
// open a confirmation dialog
dialogs.confirm({
resolve: {
object () {
return {
title: _t('admin_calendar.confirmation_required'),
msg: _t('admin_calendar.do_you_really_want_to_cancel_the_USER_s_reservation_the_DATE_at_TIME_concerning_RESERVATION'
, { GENDER: getGender($scope.currentUser), USER: slot.user.name, DATE: moment(slot.start_at).format('L'), TIME: moment(slot.start_at).format('LT'), RESERVATION: slot.reservable.name }
, 'messageformat')
}
}
}
}
, () =>
// the admin has confirmed, cancel the subscription
Slot.cancel({ id: slot.slot_id }
, function (data, status) { // success
// update the canceled_at attribute
for (let resa of Array.from($scope.reservations)) {
if (resa.slot_id === data.id) {
resa.canceled_at = data.canceled_at
break
dialogs.confirm(
{
resolve: {
object () {
return {
title: _t('admin_calendar.confirmation_required'),
msg: _t('admin_calendar.do_you_really_want_to_cancel_the_USER_s_reservation_the_DATE_at_TIME_concerning_RESERVATION'
, { GENDER: getGender($scope.currentUser), USER: slot.user.name, DATE: moment(slot.start_at).format('L'), TIME: moment(slot.start_at).format('LT'), RESERVATION: slot.reservable.name }
, 'messageformat')
}
}
// notify the admin
return growl.success(_t('admin_calendar.reservation_was_successfully_cancelled'))
}
, (data, status) => // failed
growl.error(_t('admin_calendar.reservation_cancellation_failed'))
)
},
function() {
// the admin has confirmed, cancel the subscription
Slot.cancel(
{ id: slot.slot_id },
function (data, status) { // success
// update the canceled_at attribute
for (let resa of Array.from($scope.reservations)) {
if (resa.slot_id === data.id) {
resa.canceled_at = data.canceled_at
break
}
}
// notify the admin
return growl.success(_t('admin_calendar.reservation_was_successfully_cancelled'))
},
function (data, status) { // failed
growl.error(_t('admin_calendar.reservation_cancellation_failed'))
}
)
}
)
}
/**
* Open a confirmation modal to remove a machine for the currently selected availability,
@ -147,8 +152,9 @@ Application.Controllers.controller('AdminCalendarController', ['$scope', '$state
// notify the admin
return growl.success(_t('admin_calendar.the_machine_was_successfully_removed_from_the_slot'))
}
, (data, status) => // failed
, function(data, status) { // failed
growl.error(_t('admin_calendar.deletion_failed'))
}
)
})
}
@ -158,12 +164,13 @@ Application.Controllers.controller('AdminCalendarController', ['$scope', '$state
* Callback to alert the admin that the export request was acknowledged and is
* processing right now.
*/
$scope.alertExport = type =>
$scope.alertExport = function(type) {
Export.status({ category: 'availabilities', type }).then(function (res) {
if (!res.data.exists) {
return growl.success(_t('admin_calendar.export_is_running_you_ll_be_notified_when_its_ready'))
}
})
}
/**
* Mark the selected slot as unavailable for new reservations or allow reservations again on it
@ -183,27 +190,33 @@ Application.Controllers.controller('AdminCalendarController', ['$scope', '$state
}
if (!prevent) {
// open a confirmation dialog
return dialogs.confirm({
resolve: {
object () {
return {
title: _t('admin_calendar.confirmation_required'),
msg: locked ? _t('admin_calendar.do_you_really_want_to_allow_reservations') : _t('admin_calendar.do_you_really_want_to_block_this_slot')
dialogs.confirm(
{
resolve: {
object () {
return {
title: _t('admin_calendar.confirmation_required'),
msg: locked ? _t('admin_calendar.do_you_really_want_to_allow_reservations') : _t('admin_calendar.do_you_really_want_to_block_this_slot')
}
}
}
},
function() {
// the admin has confirmed, lock/unlock the slot
Availability.lock(
{ id: $scope.availability.id },
{ lock: !locked },
function (data) { // success
$scope.availability = data
growl.success(locked ? _t('admin_calendar.unlocking_success') : _t('admin_calendar.locking_success'))
uiCalendarConfig.calendars.calendar.fullCalendar('refetchEvents')
},
function (error) { // failed
growl.error(locked ? _t('admin_calendar.unlocking_failed') : _t('admin_calendar.locking_failed'))
console.error(error)
}
)
}
}
, () =>
// the admin has confirmed, lock/unlock the slot
Availability.lock({ id: $scope.availability.id }, { lock: !locked }
, function (data) { // success
$scope.availability = data
growl.success(locked ? _t('admin_calendar.unlocking_success') : _t('admin_calendar.locking_success'))
return uiCalendarConfig.calendars.calendar.fullCalendar('refetchEvents')
}
, error => // failed
growl.error(locked ? _t('admin_calendar.unlocking_failed') : _t('admin_calendar.locking_failed'))
)
)
} else {
return growl.error(_t('admin_calendar.unlockable_because_reservations'))
@ -213,28 +226,35 @@ Application.Controllers.controller('AdminCalendarController', ['$scope', '$state
/**
* Confirm and destroy the slot in $scope.availability
*/
$scope.removeSlot = () =>
// open a confirmation dialog
dialogs.confirm({
resolve: {
object () {
return {
title: _t('admin_calendar.confirmation_required'),
msg: _t('admin_calendar.do_you_really_want_to_delete_this_slot')
$scope.removeSlot = function() {
// open a confirmation dialog
dialogs.confirm(
{
resolve: {
object () {
return {
title: _t('admin_calendar.confirmation_required'),
msg: _t('admin_calendar.do_you_really_want_to_delete_this_slot')
}
}
}
}
}
, () =>
// the admin has confirmed, delete the slot
Availability.delete({ id: $scope.availability.id }, function () {
uiCalendarConfig.calendars.calendar.fullCalendar('removeEvents', $scope.availability.id)
},
function() {
// the admin has confirmed, delete the slot
Availability.delete(
{ id: $scope.availability.id },
function () {
uiCalendarConfig.calendars.calendar.fullCalendar('removeEvents', $scope.availability.id)
growl.success(_t('admin_calendar.the_slot_START-END_has_been_successfully_deleted', { START: moment(event.start).format('LL LT'), END: moment(event.end).format('LT') }))
return $scope.availability = null
growl.success(_t('admin_calendar.the_slot_START-END_has_been_successfully_deleted', { START: moment(event.start).format('LL LT'), END: moment(event.end).format('LT') }))
$scope.availability = null
},
function () {
growl.error(_t('admin_calendar.unable_to_delete_the_slot_START-END_because_it_s_already_reserved_by_a_member', { START: moment(event.start).format('LL LT'), END: moment(event.end).format('LT') }))
})
}
, () => growl.error(_t('admin_calendar.unable_to_delete_the_slot_START-END_because_it_s_already_reserved_by_a_member', { START: moment(event.start).format('LL LT'), END: moment(event.end).format('LT') })))
)
}
/* PRIVATE SCOPE */
@ -266,30 +286,32 @@ Application.Controllers.controller('AdminCalendarController', ['$scope', '$state
resolve: {
start () { return start },
end () { return end },
machinesPromise: ['Machine', Machine => Machine.query().$promise
],
trainingsPromise: ['Training', Training => Training.query().$promise
],
spacesPromise: ['Space', Space => Space.query().$promise
]
machinesPromise: ['Machine', function (Machine) { return Machine.query().$promise }],
trainingsPromise: ['Training', function (Training) { return Training.query().$promise }],
spacesPromise: ['Space', function (Space) { return Space.query().$promise }]
} })
// when the modal is closed, we send the slot to the server for saving
modalInstance.result.then(availability =>
uiCalendarConfig.calendars.calendar.fullCalendar('renderEvent', {
id: availability.id,
title: availability.title,
start: availability.start_at,
end: availability.end_at,
textColor: 'black',
backgroundColor: availability.backgroundColor,
borderColor: availability.borderColor,
tag_ids: availability.tag_ids,
tags: availability.tags,
machine_ids: availability.machine_ids
}
, true)
, () => uiCalendarConfig.calendars.calendar.fullCalendar('unselect'))
modalInstance.result.then(
function (availability) {
uiCalendarConfig.calendars.calendar.fullCalendar(
'renderEvent',
{
id: availability.id,
title: availability.title,
start: availability.start_at,
end: availability.end_at,
textColor: 'black',
backgroundColor: availability.backgroundColor,
borderColor: availability.borderColor,
tag_ids: availability.tag_ids,
tags: availability.tags,
machine_ids: availability.machine_ids
},
true
)
},
function() { uiCalendarConfig.calendars.calendar.fullCalendar('unselect') }
)
}
}
@ -308,7 +330,7 @@ Application.Controllers.controller('AdminCalendarController', ['$scope', '$state
return $scope.removeSlot()
// if the user has only clicked on the event, display its reservations
} else {
return Availability.reservations({ id: event.id }, reservations => $scope.reservations = reservations)
return Availability.reservations({ id: event.id }, function (reservations) { $scope.reservations = reservations })
}
}
@ -355,13 +377,13 @@ Application.Controllers.controller('CreateEventModalController', ['$scope', '$ui
$scope.end = end
// machines list
$scope.machines = machinesPromise.filter(m => !m.disabled)
$scope.machines = machinesPromise.filter(function(m) { return !m.disabled })
// trainings list
$scope.trainings = trainingsPromise.filter(t => !t.disabled)
$scope.trainings = trainingsPromise.filter(function (t) { return !t.disabled })
// spaces list
$scope.spaces = spacesPromise.filter(s => !s.disabled)
$scope.spaces = spacesPromise.filter(function (s) { return !s.disabled })
// machines associated with the created slot
$scope.selectedMachines = []
@ -416,7 +438,7 @@ Application.Controllers.controller('CreateEventModalController', ['$scope', '$ui
$scope.ok = function () {
if ($scope.availability.available_type === 'machines') {
if ($scope.selectedMachines.length > 0) {
$scope.availability.machine_ids = $scope.selectedMachines.map(m => m.id)
$scope.availability.machine_ids = $scope.selectedMachines.map(function (m) { return m.id })
} else {
growl.error(_t('admin_calendar.you_should_select_at_least_a_machine'))
return
@ -428,7 +450,7 @@ Application.Controllers.controller('CreateEventModalController', ['$scope', '$ui
}
return Availability.save(
{ availability: $scope.availability }
, availability => $uibModalInstance.close(availability))
, function (availability) { $uibModalInstance.close(availability) })
}
/**
@ -442,12 +464,12 @@ Application.Controllers.controller('CreateEventModalController', ['$scope', '$ui
/**
* Move the modal UI to the next step
*/
$scope.previous = () => $scope.step--
$scope.previous = function () { return $scope.step-- }
/**
* Callback to cancel the slot creation
*/
$scope.cancel = () => $uibModalInstance.dismiss('cancel')
$scope.cancel = function () { $uibModalInstance.dismiss('cancel') }
/**
* For training avaiabilities, set the maximum number of people allowed to register on this slot
@ -473,7 +495,7 @@ Application.Controllers.controller('CreateEventModalController', ['$scope', '$ui
$scope.selectedSpace = $scope.spaces[0]
}
Tag.query().$promise.then(data => $scope.tags = data)
Tag.query().$promise.then(function (data) { $scope.tags = data })
// When we configure a machine availability, do not let the user change the end time, as the total
// time must be dividable by 60 minutes (base slot duration). For training availabilities, the user

View File

@ -58,18 +58,18 @@ class EventsController {
$scope.submited = function (content) {
if ((content.id == null)) {
$scope.alerts = []
return angular.forEach(content, (v, k) =>
angular.forEach(v, err => $scope.alerts.push({ msg: k + ': ' + err, type: 'danger' }))
)
angular.forEach(content, function(v, k) {
angular.forEach(v, function(err) { $scope.alerts.push({ msg: k + ': ' + err, type: 'danger' }) })
})
} else {
return $state.go('app.public.events_list')
$state.go('app.public.events_list')
}
}
/**
* Changes the user's view to the events list page
*/
$scope.cancel = () => $state.go('app.public.events_list')
$scope.cancel = function() { $state.go('app.public.events_list') }
/**
* For use with 'ng-class', returns the CSS class name for the uploads previews.
@ -87,7 +87,7 @@ class EventsController {
/**
* This will create a single new empty entry into the event's attachements list.
*/
$scope.addFile = () => $scope.event.event_files_attributes.push({})
$scope.addFile = function() { $scope.event.event_files_attributes.push({}) }
/**
* This will remove the given file from the event's attachements list. If the file was previously uploaded
@ -134,11 +134,12 @@ class EventsController {
/**
* Initialize a new price item in the additional prices list
*/
$scope.addPrice = () =>
$scope.addPrice = function() {
$scope.event.prices.push({
category: null,
amount: null
})
}
/**
* Remove the price or mark it as 'to delete'
@ -147,10 +148,10 @@ class EventsController {
event.preventDefault()
event.stopPropagation()
if (price.id) {
return price._destroy = true
price._destroy = true
} else {
const index = $scope.event.prices.indexOf(price)
return $scope.event.prices.splice(index, 1)
$scope.event.prices.splice(index, 1)
}
}
}
@ -216,7 +217,7 @@ Application.Controllers.controller('AdminEventsController', ['$scope', '$state',
if (id != null) {
return getModel(model)[0].update({ id }, data)
} else {
return getModel(model)[0].save(data, resp => getModel(model)[1][getModel(model)[1].length - 1].id = resp.id)
return getModel(model)[0].save(data, function(resp) { getModel(model)[1][getModel(model)[1].length - 1].id = resp.id })
}
}
@ -244,10 +245,10 @@ Application.Controllers.controller('AdminEventsController', ['$scope', '$state',
}
}
}
, () => // delete confirmed
getModel(model)[0].delete(getModel(model)[1][index], null, () => getModel(model)[1].splice(index, 1)
, () => growl.error(_t('unable_to_delete_an_error_occured')))
)
, function () { // delete confirmed
getModel(model)[0].delete(getModel(model)[1][index], null, function() { getModel(model)[1].splice(index, 1) }
, function() { growl.error(_t('unable_to_delete_an_error_occured')) })
})
}
/**
@ -280,25 +281,25 @@ Application.Controllers.controller('AdminEventsController', ['$scope', '$state',
* Open a modal dialog allowing the definition of a new price category.
* Save it once filled and handle the result.
*/
$scope.newPriceCategory = () =>
$scope.newPriceCategory = function() {
$uibModal.open({
templateUrl: '<%= asset_path "admin/events/price_form.html" %>',
size: 'md',
resolve: {
category () { return {} }
},
controller: 'PriceCategoryController' }).result['finally'](null).then(p_cat =>
// save the price category to the API
PriceCategory.save(p_cat, function (cat) {
$scope.priceCategories.push(cat)
return growl.success(_t('price_category_successfully_created'))
}
, function (err) {
growl.error(_t('unable_to_add_the_price_category_check_name_already_used'))
return console.error(err)
})
)
controller: 'PriceCategoryController' }).result['finally'](null).then(function(p_cat) {
// save the price category to the API
PriceCategory.save(p_cat, function (cat) {
$scope.priceCategories.push(cat)
return growl.success(_t('price_category_successfully_created'))
}
, function (err) {
growl.error(_t('unable_to_add_the_price_category_check_name_already_used'))
return console.error(err)
})
})
}
/**
* Update the given price category with the new properties
* to specify in a modal dialog
@ -315,17 +316,17 @@ Application.Controllers.controller('AdminEventsController', ['$scope', '$state',
resolve: {
category () { return $scope.priceCategories[index] }
},
controller: 'PriceCategoryController' }).result['finally'](null).then(p_cat =>
// update the price category to the API
PriceCategory.update({ id }, { price_category: p_cat }, function (cat) {
$scope.priceCategories[index] = cat
return growl.success(_t('price_category_successfully_updated'))
}
, function (err) {
growl.error(_t('unable_to_update_the_price_category'))
return console.error(err)
})
)
controller: 'PriceCategoryController' }).result['finally'](null).then(function(p_cat) {
// update the price category to the API
PriceCategory.update({id}, {price_category: p_cat}, function (cat) {
$scope.priceCategories[index] = cat
return growl.success(_t('price_category_successfully_updated'))
}
, function (err) {
growl.error(_t('unable_to_update_the_price_category'))
return console.error(err)
})
})
}
}
@ -340,22 +341,27 @@ Application.Controllers.controller('AdminEventsController', ['$scope', '$state',
} else if ($scope.priceCategories[index].events > 0) {
return growl.error(_t('unable_to_delete_this_price_category_because_it_is_already_used'))
} else {
return dialogs.confirm({
resolve: {
object () {
return {
title: _t('confirmation_required'),
msg: _t('do_you_really_want_to_delete_this_price_category')
return dialogs.confirm(
{
resolve: {
object () {
return {
title: _t('confirmation_required'),
msg: _t('do_you_really_want_to_delete_this_price_category')
}
}
}
},
function() { // delete confirmed
PriceCategory.remove(
{id},
function () { // successfully deleted
growl.success(_t('price_category_successfully_deleted'))
$scope.priceCategories.splice(index, 1)
},
function() { growl.error(_t('price_category_deletion_failed')) }
)
}
}
, () => // delete confirmed
PriceCategory.remove({ id }, function () { // successfully deleted
growl.success(_t('price_category_successfully_deleted'))
return $scope.priceCategories.splice(index, 1)
}
, () => growl.error(_t('price_category_deletion_failed')))
)
}
}
@ -377,7 +383,7 @@ Application.Controllers.controller('AdminEventsController', ['$scope', '$state',
/**
* Kind of constructor: these actions will be realized first when the controller is loaded
*/
const initialize = () => paginationCheck(eventsPromise, $scope.events)
const initialize = function() { paginationCheck(eventsPromise, $scope.events) }
/**
* Check if all events are already displayed OR if the button 'load more events'
@ -426,8 +432,7 @@ Application.Controllers.controller('ShowEventReservationsController', ['$scope',
// list of reservations for the current event
return $scope.reservations = reservationsPromise
}
])
}])
/**
* Controller used in the event creation page

View File

@ -132,15 +132,15 @@ Application.Controllers.controller('InvoicesController', ['$scope', '$state', 'I
let sample = $scope.invoice.reference.model
if (sample) {
// invoice number per day (dd..dd)
sample = sample.replace(/d+(?![^\[]*])/g, (match, offset, string) => padWithZeros(2, match.length))
sample = sample.replace(/d+(?![^\[]*])/g, function (match, offset, string) { return padWithZeros(2, match.length) })
// invoice number per month (mm..mm)
sample = sample.replace(/m+(?![^\[]*])/g, (match, offset, string) => padWithZeros(12, match.length))
sample = sample.replace(/m+(?![^\[]*])/g, function (match, offset, string) { return padWithZeros(12, match.length) })
// invoice number per year (yy..yy)
sample = sample.replace(/y+(?![^\[]*])/g, (match, offset, string) => padWithZeros(8, match.length))
sample = sample.replace(/y+(?![^\[]*])/g, function (match, offset, string) { return padWithZeros(8, match.length) })
// date information
sample = sample.replace(/[YMD]+(?![^\[]*])/g, (match, offset, string) => $scope.today.format(match))
sample = sample.replace(/[YMD]+(?![^\[]*])/g, function (match, offset, string) { return $scope.today.format(match) })
// information about online selling (X[text])
sample = sample.replace(/X\[([^\]]+)\]/g, (match, p1, offset, string) => p1)
sample = sample.replace(/X\[([^\]]+)\]/g, function (match, p1, offset, string) { return p1 })
// information about wallet (W[text]) - does not apply here
sample = sample.replace(/W\[([^\]]+)\]/g, '')
// information about refunds (R[text]) - does not apply here
@ -157,15 +157,15 @@ Application.Controllers.controller('InvoicesController', ['$scope', '$state', 'I
let sample = $scope.invoice.number.model
if (sample) {
// global order number (nn..nn)
sample = sample.replace(/n+(?![^\[]*])/g, (match, offset, string) => padWithZeros(327, match.length))
sample = sample.replace(/n+(?![^\[]*])/g, function (match, offset, string) { return padWithZeros(327, match.length) })
// order number per year (yy..yy)
sample = sample.replace(/y+(?![^\[]*])/g, (match, offset, string) => padWithZeros(8, match.length))
sample = sample.replace(/y+(?![^\[]*])/g, function (match, offset, string) { return padWithZeros(8, match.length) })
// order number per month (mm..mm)
sample = sample.replace(/m+(?![^\[]*])/g, (match, offset, string) => padWithZeros(12, match.length))
sample = sample.replace(/m+(?![^\[]*])/g, function (match, offset, string) { return padWithZeros(12, match.length) })
// order number per day (dd..dd)
sample = sample.replace(/d+(?![^\[]*])/g, (match, offset, string) => padWithZeros(2, match.length))
sample = sample.replace(/d+(?![^\[]*])/g, function (match, offset, string) { return padWithZeros(2, match.length) })
// date information
sample = sample.replace(/[YMD]+(?![^\[]*])/g, (match, offset, string) => $scope.today.format(match))
sample = sample.replace(/[YMD]+(?![^\[]*])/g, function (match, offset, string) { return $scope.today.format(match) })
}
return sample
}
@ -185,21 +185,21 @@ Application.Controllers.controller('InvoicesController', ['$scope', '$state', 'I
},
controller ($scope, $uibModalInstance, model) {
$scope.model = model
$scope.ok = () => $uibModalInstance.close($scope.model)
return $scope.cancel = () => $uibModalInstance.dismiss('cancel')
$scope.ok = function() { $uibModalInstance.close($scope.model) }
$scope.cancel = function() { $uibModalInstance.dismiss('cancel') }
}
})
return modalInstance.result.then(model =>
modalInstance.result.then(function (model) {
Setting.update({ name: 'invoice_reference' }, { value: model }, function (data) {
$scope.invoice.reference.model = model
return growl.success(_t('invoice_reference_successfully_saved'))
growl.success(_t('invoice_reference_successfully_saved'))
}
, function (error) {
growl.error(_t('an_error_occurred_while_saving_invoice_reference'))
return console.error(error)
console.error(error)
})
)
})
}
/**
@ -222,8 +222,8 @@ Application.Controllers.controller('InvoicesController', ['$scope', '$state', 'I
$scope.codeModel = model
$scope.isSelected = active
$scope.ok = () => $uibModalInstance.close({ model: $scope.codeModel, active: $scope.isSelected })
return $scope.cancel = () => $uibModalInstance.dismiss('cancel')
$scope.ok = function() { $uibModalInstance.close({ model: $scope.codeModel, active: $scope.isSelected }) }
$scope.cancel = function() { $uibModalInstance.dismiss('cancel') }
}
})
@ -269,12 +269,12 @@ Application.Controllers.controller('InvoicesController', ['$scope', '$state', 'I
},
controller ($scope, $uibModalInstance, model) {
$scope.model = model
$scope.ok = () => $uibModalInstance.close($scope.model)
return $scope.cancel = () => $uibModalInstance.dismiss('cancel')
$scope.ok = function() { $uibModalInstance.close($scope.model) }
$scope.cancel = function() { $uibModalInstance.dismiss('cancel') }
}
})
return modalInstance.result.then(model =>
return modalInstance.result.then(function (model) {
Setting.update({ name: 'invoice_order-nb' }, { value: model }, function (data) {
$scope.invoice.number.model = model
return growl.success(_t('order_number_successfully_saved'))
@ -283,7 +283,7 @@ Application.Controllers.controller('InvoicesController', ['$scope', '$state', 'I
growl.error(_t('an_error_occurred_while_saving_the_order_number'))
return console.error(error)
})
)
})
}
/**
@ -307,8 +307,8 @@ Application.Controllers.controller('InvoicesController', ['$scope', '$state', 'I
$scope.rate = rate
$scope.isSelected = active
$scope.ok = () => $uibModalInstance.close({ rate: $scope.rate, active: $scope.isSelected })
return $scope.cancel = () => $uibModalInstance.dismiss('cancel')
$scope.ok = function () { $uibModalInstance.close({ rate: $scope.rate, active: $scope.isSelected }) }
return $scope.cancel = function () { $uibModalInstance.dismiss('cancel') }
}
})
@ -415,11 +415,15 @@ Application.Controllers.controller('InvoicesController', ['$scope', '$state', 'I
// Watch the logo, when a change occurs, save it
return $scope.$watch('invoice.logo', function () {
if ($scope.invoice.logo && $scope.invoice.logo.filesize) {
return Setting.update({ name: 'invoice_logo' }, { value: $scope.invoice.logo.base64 }, data => growl.success(_t('logo_successfully_saved'))
, function (error) {
return Setting.update(
{ name: 'invoice_logo' },
{ value: $scope.invoice.logo.base64 },
function (data) { growl.success(_t('logo_successfully_saved')) },
function (error) {
growl.error(_t('an_error_occurred_while_saving_the_logo'))
return console.error(error)
})
}
)
}
})
}
@ -430,7 +434,7 @@ Application.Controllers.controller('InvoicesController', ['$scope', '$state', 'I
* @param value {number} the integer to pad
* @param length {number} the length of the resulting string.
*/
var padWithZeros = (value, length) => (1e15 + value + '').slice(-length)
var padWithZeros = function (value, length) { return (1e15 + value + '').slice(-length) }
/**
* Remove every unsupported html tag from the given html text (like <p>, <span>, ...).
@ -438,14 +442,15 @@ Application.Controllers.controller('InvoicesController', ['$scope', '$state', 'I
* @param html {string} single line html text
* @return {string} multi line simplified html text
*/
var parseHtml = html =>
html = html.replace(/<\/?(\w+)((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/g, function (match, p1, offset, string) {
var parseHtml = function (html) {
return html.replace(/<\/?(\w+)((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/g, function (match, p1, offset, string) {
if (['b', 'u', 'i', 'br'].includes(p1)) {
return match
} else {
return ''
}
})
}
/**
* Reinitialize the context of invoices' search to display new results set
@ -460,7 +465,7 @@ Application.Controllers.controller('InvoicesController', ['$scope', '$state', 'I
* to $scope.invoices
* @param concat {boolean} if true, the result will be append to $scope.invoices instead of being affected
*/
var invoiceSearch = concat =>
var invoiceSearch = function(concat) {
Invoice.list({
query: {
number: $scope.searchInvoice.reference,
@ -481,6 +486,7 @@ Application.Controllers.controller('InvoicesController', ['$scope', '$state', 'I
return $scope.noMoreResults = true
}
})
}
// !!! MUST BE CALLED AT THE END of the controller
return initialize()
@ -553,13 +559,14 @@ Application.Controllers.controller('AvoirModalController', ['$scope', '$uibModal
if ($scope.avoir.invoice_items_ids.length === 0) {
return growl.error(_t('you_must_select_at_least_one_element_to_create_a_refund'))
} else {
return Invoice.save({ avoir: $scope.avoir }, avoir =>
// success
$uibModalInstance.close({ avoir, invoice: $scope.invoice })
, err =>
// failed
growl.error(_t('unable_to_create_the_refund'))
return Invoice.save(
{ avoir: $scope.avoir },
function(avoir) { // success
$uibModalInstance.close({avoir, invoice: $scope.invoice})
},
function (err) { // failed
growl.error(_t('unable_to_create_the_refund'))
}
)
}
}
@ -567,7 +574,7 @@ Application.Controllers.controller('AvoirModalController', ['$scope', '$uibModal
/**
* Cancel the refund, dismiss the modal window
*/
$scope.cancel = () => $uibModalInstance.dismiss('cancel')
$scope.cancel = function () { $uibModalInstance.dismiss('cancel') }
/* PRIVATE SCOPE */
@ -579,8 +586,9 @@ Application.Controllers.controller('AvoirModalController', ['$scope', '$uibModal
Invoice.get({ id: invoice.id }, function (data) {
$scope.invoice = data
// default : all elements of the invoice are refund
return Array.from(data.items).map((item) =>
($scope.partial[item.id] = (typeof item.avoir_item_id !== 'number')))
return Array.from(data.items).map(function (item) {
return ($scope.partial[item.id] = (typeof item.avoir_item_id !== 'number'))
})
})
if (invoice.stripe) {

View File

@ -38,18 +38,18 @@
class MembersController {
constructor ($scope, $state, Group, Training) {
// Retrieve the profiles groups (eg. students ...)
Group.query(groups => $scope.groups = groups.filter(g => (g.slug !== 'admins') && !g.disabled))
Group.query(function(groups) { $scope.groups = groups.filter(function(g) { return (g.slug !== 'admins') && !g.disabled }) })
// Retrieve the list of available trainings
Training.query().$promise.then(data =>
$scope.trainings = data.map(d =>
({
Training.query().$promise.then(function (data) {
$scope.trainings = data.map(function (d) {
return ({
id: d.id,
name: d.name,
disabled: d.disabled
})
)
)
})
})
// Default parameters for AngularUI-Bootstrap datepicker
$scope.datePicker = {
@ -90,14 +90,14 @@ class MembersController {
$scope.submited = function (content) {
if ((content.id == null)) {
$scope.alerts = []
return angular.forEach(content, (v, k) =>
angular.forEach(v, err =>
return angular.forEach(content, function (v, k) {
angular.forEach(v, function (err) {
$scope.alerts.push({
msg: k + ': ' + err,
type: 'danger'
})
)
)
})
})
} else {
return $state.go('app.admin.members')
}
@ -106,7 +106,7 @@ class MembersController {
/**
* Changes the admin's view to the members list page
*/
$scope.cancel = () => $state.go('app.admin.members')
$scope.cancel = function() { $state.go('app.admin.members') }
/**
* For use with 'ng-class', returns the CSS class name for the uploads previews.
@ -172,7 +172,7 @@ Application.Controllers.controller('AdminMembersController', ['$scope', '$sce',
/**
* Change the admins ordering criterion to the one provided
* @param orderBy {string} ordering criterion
* @param orderAdmin {string} ordering criterion
*/
$scope.setOrderAdmin = function (orderAdmin) {
if ($scope.orderAdmin === orderAdmin) {
@ -187,24 +187,30 @@ Application.Controllers.controller('AdminMembersController', ['$scope', '$sce',
* @param admins {Array} full list of administrators
* @param admin {Object} administrator to delete
*/
$scope.destroyAdmin = (admins, admin) =>
dialogs.confirm({
resolve: {
object () {
return {
title: _t('confirmation_required'),
msg: $sce.trustAsHtml(_t('do_you_really_want_to_delete_this_administrator_this_cannot_be_undone') + '<br/><br/>' + _t('this_may_take_a_while_please_wait'))
$scope.destroyAdmin = function (admins, admin) {
dialogs.confirm(
{
resolve: {
object () {
return {
title: _t('confirmation_required'),
msg: $sce.trustAsHtml(_t('do_you_really_want_to_delete_this_administrator_this_cannot_be_undone') + '<br/><br/>' + _t('this_may_take_a_while_please_wait'))
}
}
}
},
function () { // cancel confirmed
Admin.delete(
{ id: admin.id },
function () {
admins.splice(findAdminIdxById(admins, admin.id), 1)
return growl.success(_t('administrator_successfully_deleted'))
},
function (error) { growl.error(_t('unable_to_delete_the_administrator')) }
)
}
}
, () => // cancel confirmed
Admin.delete({ id: admin.id }, function () {
admins.splice(findAdminIdxById(admins, admin.id), 1)
return growl.success(_t('administrator_successfully_deleted'))
}
, error => growl.error(_t('unable_to_delete_the_administrator')))
)
}
/**
* Callback for the 'load more' button.
@ -227,12 +233,13 @@ Application.Controllers.controller('AdminMembersController', ['$scope', '$sce',
* Callback to alert the admin that the export request was acknowledged and is
* processing right now.
*/
$scope.alertExport = type =>
$scope.alertExport = function (type) {
Export.status({ category: 'users', type }).then(function (res) {
if (!res.data.exists) {
return growl.success(_t('export_is_running_you_ll_be_notified_when_its_ready'))
}
})
}
/* PRIVATE SCOPE */
@ -251,8 +258,9 @@ Application.Controllers.controller('AdminMembersController', ['$scope', '$sce',
* @param id {Number} user id of the admin to retrieve in the list
* @returns {Number} index of the requested admin, in the provided array
*/
var findAdminIdxById = (admins, id) =>
(admins.map(admin => admin.id)).indexOf(id)
var findAdminIdxById = function (admins, id) {
return (admins.map(function(admin) { return admin.id })).indexOf(id)
}
/**
* Reinitialize the context of members's search to display new results set
@ -267,8 +275,15 @@ Application.Controllers.controller('AdminMembersController', ['$scope', '$sce',
* and affect or append the result in $scope.members, depending on the concat parameter
* @param concat {boolean} if true, the result will be append to $scope.members instead of being affected
*/
var memberSearch = concat =>
Member.list({ query: { search: $scope.member.searchText, order_by: $scope.member.order, page: $scope.member.page, size: USERS_PER_PAGE } }, function (members) {
var memberSearch = function (concat) {
Member.list({
query: {
search: $scope.member.searchText,
order_by: $scope.member.order,
page: $scope.member.page,
size: USERS_PER_PAGE
}
}, function (members) {
if (concat) {
$scope.members = $scope.members.concat(members)
} else {
@ -279,6 +294,7 @@ Application.Controllers.controller('AdminMembersController', ['$scope', '$sce',
return $scope.member.noMore = true
}
})
}
// !!! MUST BE CALLED AT THE END of the controller
return initialize()
@ -315,8 +331,9 @@ Application.Controllers.controller('EditMemberController', ['$scope', '$state',
} else {
Plan.query({ group_id: $scope.user.group_id }, function (plans) {
$scope.plans = plans
return Array.from($scope.plans).map((plan) =>
(plan.nameToDisplay = $filter('humanReadablePlanName')(plan)))
return Array.from($scope.plans).map( function(plan) {
return (plan.nameToDisplay = $filter('humanReadablePlanName')(plan))
})
})
}
@ -366,18 +383,23 @@ Application.Controllers.controller('EditMemberController', ['$scope', '$state',
return $scope.datePicker.opened = true
}
$scope.ok = () =>
Subscription.update({ id: subscription.id }, { subscription: { expired_at: $scope.new_expired_at, free } }, function (_subscription) {
growl.success(_t('you_successfully_changed_the_expiration_date_of_the_user_s_subscription'))
return $uibModalInstance.close(_subscription)
}
, error => growl.error(_t('a_problem_occurred_while_saving_the_date')))
$scope.ok = function () {
Subscription.update(
{ id: subscription.id },
{ subscription: { expired_at: $scope.new_expired_at, free } },
function (_subscription) {
growl.success(_t('you_successfully_changed_the_expiration_date_of_the_user_s_subscription'))
return $uibModalInstance.close(_subscription)
},
function (error) { growl.error(_t('a_problem_occurred_while_saving_the_date')) }
)
}
return $scope.cancel = () => $uibModalInstance.dismiss('cancel')
}
] })
// once the form was validated succesfully ...
return modalInstance.result.then(subscription => $scope.subscription.expired_at = subscription.expired_at)
$scope.cancel = function () { $uibModalInstance.dismiss('cancel') }
}]
})
// once the form was validated successfully ...
return modalInstance.result.then(function(subscription) { $scope.subscription.expired_at = subscription.expired_at })
}
/**
@ -398,14 +420,14 @@ Application.Controllers.controller('EditMemberController', ['$scope', '$state',
$scope.plans = plans
/**
* Generate a string identifying the given plan by literal humain-readable name
* Generate a string identifying the given plan by literal human-readable name
* @param plan {Object} Plan object, as recovered from GET /api/plan/:id
* @param groups {Array} List of Groups objects, as recovered from GET /api/groups
* @param short {boolean} If true, the generated name will contains the group slug, otherwise the group full name
* will be included.
* @returns {String}
*/
$scope.humanReadablePlanName = (plan, groups, short) => `${$filter('humanReadablePlanName')(plan, groups, short)}`
$scope.humanReadablePlanName = function(plan, groups, short) { return `${$filter('humanReadablePlanName')(plan, groups, short)}` }
/**
* Modal dialog validation callback
@ -417,17 +439,20 @@ Application.Controllers.controller('EditMemberController', ['$scope', '$state',
$uibModalInstance.close(_subscription)
return $state.reload()
}
, error => growl.error(_t('a_problem_occurred_while_taking_the_subscription')))
, function (error) {
growl.error(_t('a_problem_occurred_while_taking_the_subscription'))
console.error(error);
})
}
/**
* Modal dialog cancellation callback
*/
return $scope.cancel = () => $uibModalInstance.dismiss('cancel')
}
] })
$scope.cancel = function() { $uibModalInstance.dismiss('cancel') }
}]
})
// once the form was validated succesfully ...
return modalInstance.result.then(subscription => $scope.subscription = subscription)
return modalInstance.result.then(function(subscription) { $scope.subscription = subscription })
}
$scope.createWalletCreditModal = function (user, wallet) {
@ -465,36 +490,43 @@ Application.Controllers.controller('EditMemberController', ['$scope', '$state',
/**
* Modal dialog validation callback
*/
$scope.ok = () =>
Wallet.credit({ id: wallet.id }, {
amount: $scope.amount,
avoir: $scope.generate_avoir,
avoir_date: $scope.avoir_date,
avoir_description: $scope.description
}
, function (_wallet) {
growl.success(_t('wallet_credit_successfully'))
return $uibModalInstance.close(_wallet)
}
, error => growl.error(_t('a_problem_occurred_for_wallet_credit')))
$scope.ok = function() {
Wallet.credit(
{ id: wallet.id },
{
amount: $scope.amount,
avoir: $scope.generate_avoir,
avoir_date: $scope.avoir_date,
avoir_description: $scope.description
},
function (_wallet) {
growl.success(_t('wallet_credit_successfully'))
return $uibModalInstance.close(_wallet)
},
function(error) {
growl.error(_t('a_problem_occurred_for_wallet_credit'));
console.error(error)
}
)
}
/**
* Modal dialog cancellation callback
*/
return $scope.cancel = () => $uibModalInstance.dismiss('cancel')
$scope.cancel = function() { $uibModalInstance.dismiss('cancel') }
}
] })
// once the form was validated succesfully ...
return modalInstance.result.then(function (wallet) {
$scope.wallet = wallet
return Wallet.transactions({ id: wallet.id }, transactions => $scope.transactions = transactions)
return Wallet.transactions({ id: wallet.id }, function (transactions) { $scope.transactions = transactions })
})
}
/**
* To use as callback in Array.prototype.filter to get only enabled plans
*/
$scope.filterDisabledPlans = plan => !plan.disabled
$scope.filterDisabledPlans = function (plan) { return !plan.disabled }
/* PRIVATE SCOPE */
@ -514,8 +546,9 @@ Application.Controllers.controller('EditMemberController', ['$scope', '$state',
} else {
Plan.query({ group_id: $scope.user.group_id }, function (plans) {
$scope.plans = plans
return Array.from($scope.plans).map((plan) =>
(plan.nameToDisplay = `${plan.base_name} - ${plan.interval}`))
return Array.from($scope.plans).map(function (plan) {
return (plan.nameToDisplay = `${plan.base_name} - ${plan.interval}`)
})
})
}
@ -592,22 +625,29 @@ Application.Controllers.controller('NewAdminController', ['$state', '$scope', 'A
* Shows the birth day datepicker
* @param $event {Object} jQuery event object
*/
$scope.openDatePicker = $event => $scope.datePicker.opened = true
$scope.openDatePicker = function($event) { $scope.datePicker.opened = true }
/**
* Send the new admin, currently stored in $scope.admin, to the server for database saving
*/
$scope.saveAdmin = () =>
Admin.save({}, { admin: $scope.admin }, function () {
growl.success(_t('administrator_successfully_created_he_will_receive_his_connection_directives_by_email', { GENDER: getGender($scope.admin) }, 'messageformat'))
return $state.go('app.admin.members')
}
, error => console.log(error))
$scope.saveAdmin = function() {
Admin.save(
{},
{ admin: $scope.admin },
function () {
growl.success(_t('administrator_successfully_created_he_will_receive_his_connection_directives_by_email', {GENDER: getGender($scope.admin)}, 'messageformat'))
return $state.go('app.admin.members')
}
, function (error) {
console.log(error)
}
)
}
/* PRIVATE SCOPE */
/**
* Return an enumerable meaninful string for the gender of the provider user
* Return an enumerable meaningful string for the gender of the provider user
* @param user {Object} Database user record
* @return {string} 'male' or 'female'
*/

View File

@ -26,7 +26,7 @@ class PlanController {
CSRF.setMetaTags()
// groups list
$scope.groups = groups.filter(g => (g.slug !== 'admins') && !g.disabled)
$scope.groups = groups.filter(function(g) { return (g.slug !== 'admins') && !g.disabled })
// users with role 'partner', notifiables for a partner plan
$scope.partners = partners.users
@ -64,14 +64,8 @@ class PlanController {
*/
Application.Controllers.controller('NewPlanController', ['$scope', '$uibModal', 'groups', 'prices', 'partners', 'CSRF', '$state', 'growl', '_t',
function ($scope, $uibModal, groups, prices, partners, CSRF, $state, growl, _t) {
({
/* PRIVATE STATIC CONSTANTS */
// when creating a new contact for a partner plan, this ID will be sent to the server
NEW_PARTNER_ID: null
/* PUBLIC SCOPE */
})
// current form is used to create a new plan
$scope.mode = 'creation'
@ -105,7 +99,7 @@ Application.Controllers.controller('NewPlanController', ['$scope', '$uibModal',
* Checks if the partner contact is a valid data. Used in the form validation process
* @returns {boolean}
*/
$scope.partnerIsValid = () => ($scope.plan.type === 'Plan') || ($scope.plan.partnerId || ($scope.plan.partnerContact && $scope.plan.partnerContact.email))
$scope.partnerIsValid = function() { return ($scope.plan.type === 'Plan') || ($scope.plan.partnerId || ($scope.plan.partnerContact && $scope.plan.partnerContact.email)) }
/**
* Open a modal dialog allowing the admin to create a new partner user
@ -118,18 +112,25 @@ Application.Controllers.controller('NewPlanController', ['$scope', '$uibModal',
controller: ['$scope', '$uibModalInstance', 'User', function ($scope, $uibModalInstance, User) {
$scope.partner = {}
$scope.ok = () =>
User.save({}, { user: $scope.partner }, function (user) {
$scope.partner.id = user.id
$scope.partner.name = `${user.first_name} ${user.last_name}`
return $uibModalInstance.close($scope.partner)
}
, error => growl.error(_t('new_plan.unable_to_save_this_user_check_that_there_isnt_an_already_a_user_with_the_same_name')))
return $scope.cancel = () => $uibModalInstance.dismiss('cancel')
}
] })
// once the form was validated succesfully ...
$scope.ok = function() {
User.save(
{},
{ user: $scope.partner },
function (user) {
$scope.partner.id = user.id
$scope.partner.name = `${user.first_name} ${user.last_name}`
$uibModalInstance.close($scope.partner)
},
function (error) {
growl.error(_t('new_plan.unable_to_save_this_user_check_that_there_isnt_an_already_a_user_with_the_same_name'))
console.error(error);
}
)
}
$scope.cancel = function() { $uibModalInstance.dismiss('cancel') }
}]
})
// once the form was validated successfully ...
return modalInstance.result.then(function (partner) {
$scope.partners.push(partner)
return $scope.plan.partnerId = partner.id
@ -199,9 +200,9 @@ Application.Controllers.controller('EditPlanController', ['$scope', 'groups', 'p
*/
$scope.copyPricesFromPlan = function () {
if ($scope.plan.parent) {
return Plan.get({ id: $scope.plan.parent }, parentPlan =>
Array.from(parentPlan.prices).map((parentPrice) =>
(() => {
return Plan.get({ id: $scope.plan.parent }, function (parentPlan) {
Array.from(parentPlan.prices).map(function (parentPrice) {
return (function () {
const result = []
for (let childKey in $scope.plan.prices) {
const childPrice = $scope.plan.prices[childKey]
@ -213,12 +214,13 @@ Application.Controllers.controller('EditPlanController', ['$scope', 'groups', 'p
}
}
return result
})())
})()})
}
)
// if no plan were selected, unset every prices
} else {
return (() => {
return (function () {
const result = []
for (let key in $scope.plan.prices) {
const price = $scope.plan.prices[key]
@ -250,7 +252,7 @@ Application.Controllers.controller('EditPlanController', ['$scope', 'groups', 'p
* will be included.
* @returns {String}
*/
$scope.humanReadablePlanName = (plan, groups, short) => `${$filter('humanReadablePlanName')(plan, groups, short)}`
$scope.humanReadablePlanName = function (plan, groups, short) { return `${$filter('humanReadablePlanName')(plan, groups, short)}` }
/**
* Retrieve the machine from its ID
@ -278,16 +280,8 @@ Application.Controllers.controller('EditPlanController', ['$scope', 'groups', 'p
}
}
/* PRIVATE SCOPE */
/**
* Kind of constructor: these actions will be realized first when the controller is loaded
*/
const initialize = () =>
// Using the PlansController
new PlanController($scope, groups, prices, partners, CSRF)
// !!! MUST BE CALLED AT THE END of the controller
return initialize()
return new PlanController($scope, groups, prices, partners, CSRF)
}
])

View File

@ -29,11 +29,11 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
// List of available subscriptions plans (eg. student/month, PME/year ...)
$scope.plans = plans
$scope.enabledPlans = plans.filter(p => !p.disabled)
$scope.enabledPlans = plans.filter(function (p) { return !p.disabled })
// List of groups (eg. normal, student ...)
$scope.groups = groups.filter(g => g.slug !== 'admins')
$scope.enabledGroups = groups.filter(g => (g.slug !== 'admins') && !g.disabled)
$scope.groups = groups.filter(function (g) { return g.slug !== 'admins' })
$scope.enabledGroups = groups.filter(function(g) { return (g.slug !== 'admins') && !g.disabled })
// Associate free machine hours with subscriptions
$scope.machineCredits = machineCreditsPromise
@ -45,18 +45,18 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
$scope.trainingCreditsGroups = {}
// List of trainings
$scope.trainings = trainingsPromise.filter(t => !t.disabled)
$scope.trainings = trainingsPromise.filter(function (t) { return !t.disabled })
// List of machines
$scope.machines = machinesPromise
$scope.enabledMachines = machinesPromise.filter(m => !m.disabled)
$scope.enabledMachines = machinesPromise.filter(function (m) { return !m.disabled })
// List of coupons
$scope.coupons = couponsPromise
// List of spaces
$scope.spaces = spacesPromise
$scope.enabledSpaces = spacesPromise.filter(s => !s.disabled)
$scope.enabledSpaces = spacesPromise.filter(function (s) { return !s.disabled })
// Associate free space hours with subscriptions
$scope.spaceCredits = spacesCreditsPromise
@ -150,10 +150,15 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
*/
$scope.saveTrainingCredits = function (newdata, planId) {
// save the number of credits
Plan.update({ id: planId },
Plan.update(
{ id: planId },
{ training_credit_nb: newdata.training_credits }
, angular.noop() // do nothing in case of success
, error => growl.error(_t('pricing.an_error_occurred_while_saving_the_number_of_credits')))
, function(error) {
growl.error(_t('pricing.an_error_occurred_while_saving_the_number_of_credits'));
console.error(error)
}
)
// save the associated trainings
return angular.forEach($scope.trainingCreditsGroups, function (original, key) {
@ -169,7 +174,10 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
$scope.trainingCredits.splice($scope.trainingCredits.indexOf(tc), 1)
return $scope.trainingCreditsGroups[planId].splice($scope.trainingCreditsGroups[planId].indexOf(tc.id), 1)
}
, error => growl.error(_t('pricing.an_error_occurred_while_deleting_credit_with_the_TRAINING', { TRAINING: tc.creditable.name })))
, function (error) {
growl.error(_t('pricing.an_error_occurred_while_deleting_credit_with_the_TRAINING', { TRAINING: tc.creditable.name }));
console.error(error)
})
} else {
return growl.error(_t('pricing.an_error_occurred_unable_to_find_the_credit_to_revoke'))
}
@ -206,7 +214,7 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
* Cancel the current training credit modification
* @param rowform {Object} see http://vitalets.github.io/angular-xeditable/
*/
$scope.cancelTrainingCredit = rowform => rowform.$cancel()
$scope.cancelTrainingCredit = function(rowform) { rowform.$cancel() }
/**
* Create a new empty entry in the $scope.machineCredits array
@ -281,7 +289,7 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
}
if (id != null) {
return Credit.update({ id }, { credit: data }, () => growl.success(_t('pricing.changes_have_been_successfully_saved')))
return Credit.update({ id }, { credit: data }, function() { growl.success(_t('pricing.changes_have_been_successfully_saved')) })
} else {
data.creditable_type = 'Machine'
return Credit.save(
@ -291,8 +299,9 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
return growl.success(_t('pricing.credit_was_successfully_saved'))
}
, function (err) {
$scope.machineCredits.pop()
return growl.error(_t('pricing.error_creating_credit'))
$scope.machineCredits.pop();
growl.error(_t('pricing.error_creating_credit'));
console.error(err);
})
}
}
@ -316,7 +325,7 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
*/
$scope.removeMachineCredit = function (index) {
Credit.delete($scope.machineCredits[index])
return $scope.machineCredits.splice(index, 1)
$scope.machineCredits.splice(index, 1)
}
/**
@ -329,7 +338,7 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
$scope.inserted =
{ creditable_type: 'Space' }
$scope.spaceCredits.push($scope.inserted)
return $scope.status.isopen = !$scope.status.isopen
$scope.status.isopen = !$scope.status.isopen
}
/**
@ -350,7 +359,7 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
}
if (id != null) {
return Credit.update({ id }, { credit: data }, () => growl.success(_t('pricing.changes_have_been_successfully_saved')))
return Credit.update({ id }, { credit: data }, function() { growl.success(_t('pricing.changes_have_been_successfully_saved')) })
} else {
data.creditable_type = 'Space'
return Credit.save(
@ -442,27 +451,31 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
return console.error('[EditPricingController::deletePlan] Error: invalid id parameter')
} else {
// open a confirmation dialog
return dialogs.confirm({
resolve: {
object () {
return {
title: _t('pricing.confirmation_required'),
msg: _t('pricing.do_you_really_want_to_delete_this_subscription_plan')
return dialogs.confirm(
{
resolve: {
object () {
return {
title: _t('pricing.confirmation_required'),
msg: _t('pricing.do_you_really_want_to_delete_this_subscription_plan')
}
}
}
},
function () {
// the admin has confirmed, delete the plan
Plan.delete(
{ id },
function (res) {
growl.success(_t('pricing.subscription_plan_was_successfully_deleted'))
return $scope.plans.splice(findItemIdxById(plans, id), 1)
},
function (error) {
if (error.statusText) { console.error(`[EditPricingController::deletePlan] Error: ${error.statusText}`) }
growl.error(_t('pricing.unable_to_delete_the_specified_subscription_an_error_occurred'))
}
)
}
}
, () =>
// the admin has confirmed, delete the plan
Plan.delete({ id }, function (res) {
growl.success(_t('pricing.subscription_plan_was_successfully_deleted'))
return $scope.plans.splice(findItemIdxById(plans, id), 1)
}
, function (error) {
if (error.statusText) { console.error(`[EditPricingController::deletePlan] Error: ${error.statusText}`) }
return growl.error(_t('pricing.unable_to_delete_the_specified_subscription_an_error_occurred'))
})
)
}
}
@ -475,7 +488,7 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
* will be included.
* @returns {String}
*/
$scope.humanReadablePlanName = (plan, groups, short) => `${$filter('humanReadablePlanName')(plan, groups, short)}`
$scope.humanReadablePlanName = function(plan, groups, short) { return `${$filter('humanReadablePlanName')(plan, groups, short)}` }
/**
* Delete a coupon from the server's database and, in case of success, from the list in memory
@ -497,7 +510,7 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
}
}
}
, () =>
, function() {
// the admin has confirmed, delete the coupon
Coupon.delete({ id }, function (res) {
growl.success(_t('coupon_was_successfully_deleted'))
@ -512,7 +525,7 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
return growl.error(_t('pricing.unable_to_delete_the_specified_coupon_an_unexpected_error_occurred'))
}
})
)
})
}
}
@ -520,7 +533,7 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
* Open a modal allowing to select an user and send him the details of the provided coupon
* @param coupon {Object} The coupon to send
*/
$scope.sendCouponToUser = coupon =>
$scope.sendCouponToUser = function(coupon) {
$uibModal.open({
templateUrl: '<%= asset_path "admin/pricing/sendCoupon.html" %>',
resolve: {
@ -536,17 +549,21 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
$scope.coupon = coupon
// Callback to validate sending of the coupon
$scope.ok = () =>
$scope.ok = function() {
Coupon.send({ coupon_code: coupon.code, user_id: $scope.ctrl.member.id }, function (res) {
growl.success(_t('pricing.coupon_successfully_sent_to_USER', { USER: $scope.ctrl.member.name }))
return $uibModalInstance.close({ user_id: $scope.ctrl.member.id })
}
, err => growl.error(_t('pricing.an_error_occurred_unable_to_send_the_coupon')))
, function(err) {
growl.error(_t('pricing.an_error_occurred_unable_to_send_the_coupon'))
console.error(err)
})
}
// Callback to close the modal and cancel the sending process
return $scope.cancel = () => $uibModalInstance.dismiss('cancel')
}
] })
$scope.cancel = function() { $uibModalInstance.dismiss('cancel') }
}]
})
}
/* PRIVATE SCOPE */
@ -557,7 +574,7 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
$scope.trainingCreditsGroups = groupCreditsByPlan($scope.trainingCredits)
// adds empty array for plan which hasn't any credits yet
return (() => {
return (function() {
const result = []
for (let plan of Array.from($scope.plans)) {
if ($scope.trainingCreditsGroups[plan.id] == null) {
@ -576,8 +593,9 @@ Application.Controllers.controller('EditPricingController', ['$scope', '$state',
* @param id {number}
* @returns {number} item index in the provided array
*/
var findItemIdxById = (items, id) =>
(items.map(item => item.id)).indexOf(id)
var findItemIdxById = function (items, id) {
return (items.map(function (item) { return item.id })).indexOf(id)
}
/**
* Group the given credits array into a map associating the plan ID with its associated trainings/machines

View File

@ -134,19 +134,19 @@ Application.Controllers.controller('StatisticsController', ['$scope', '$state',
* Callback to open the datepicker (interval start)
* @param $event {Object} jQuery event object
*/
$scope.toggleStartDatePicker = $event => toggleDatePicker($event, $scope.datePickerStart)
$scope.toggleStartDatePicker = function ($event) { toggleDatePicker($event, $scope.datePickerStart) }
/**
* Callback to open the datepicker (interval end)
* @param $event {Object} jQuery event object
*/
$scope.toggleEndDatePicker = $event => toggleDatePicker($event, $scope.datePickerEnd)
$scope.toggleEndDatePicker = function ($event) { toggleDatePicker($event, $scope.datePickerEnd) }
/**
* Callback to open the datepicker (custom filter)
* @param $event {Object} jQuery event object
*/
$scope.toggleCustomDatePicker = $event => toggleDatePicker($event, $scope.customFilter.datePicker)
$scope.toggleCustomDatePicker = function ($event) { toggleDatePicker($event, $scope.customFilter.datePicker) }
/**
* Callback called when the active tab is changed.
@ -207,7 +207,7 @@ Application.Controllers.controller('StatisticsController', ['$scope', '$state',
* Parse the given date and return a user-friendly string
* @param date {Date} JS date or ant moment.js compatible date string
*/
$scope.formatDate = date => moment(date).format('LL')
$scope.formatDate = function (date) { return moment(date).format('LL') }
/**
* Parse the sex and return a user-friendly string
@ -332,7 +332,7 @@ Application.Controllers.controller('StatisticsController', ['$scope', '$state',
}
return $uibModal.open(options)
.result['finally'](null).then(info => console.log(info))
.result['finally'](null).then(function (info) { console.log(info) })
}
/* PRIVATE SCOPE */
@ -340,14 +340,15 @@ Application.Controllers.controller('StatisticsController', ['$scope', '$state',
/**
* Kind of constructor: these actions will be realized first when the controller is loaded
*/
const initialize = () =>
// workaround for angular-bootstrap::tabs behavior: on tab deletion, another tab will be selected
// which will cause every tabs to reload, one by one, when the view is closed
const initialize = function () {
// workaround for angular-bootstrap::tabs behavior: on tab deletion, another tab will be selected
// which will cause every tabs to reload, one by one, when the view is closed
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
if ((fromState.name === 'app.admin.statistics') && (Object.keys(fromParams).length === 0)) {
return $scope.preventRefresh = true
}
})
}
/**
* Generic function to toggle a bootstrap datePicker
@ -383,7 +384,7 @@ Application.Controllers.controller('StatisticsController', ['$scope', '$state',
$scope.averageAge = Math.round(res.aggregations.average_age.value * 100) / 100
$scope.sumStat = res.aggregations.total_stat.value
$scope.scrollId = res._scroll_id
return (() => {
return (function () {
const result = []
for (custom of Array.from($scope.type.active.custom_aggregations)) {
result.push($scope.customAggs[custom.field] = res.aggregations[custom.field].value)
@ -515,7 +516,7 @@ Application.Controllers.controller('StatisticsController', ['$scope', '$state',
/**
* Build the elasticSearch query DSL to match the selected cutom filter
* @param custom {Object} if custom is empty or undefined, an empty string will be returned
* @returns {{match:{*}}|string}
* @returns {{match:*}|string}
*/
var buildElasticCustomCriterion = function (custom) {
if (custom) {
@ -555,9 +556,8 @@ Application.Controllers.controller('StatisticsController', ['$scope', '$state',
* properties and on index-specific properties (additional_fields)
*/
var buildCustomFiltersList = function () {
$scope.filters = []
const filters = [
$scope.filters = [
{ key: 'date', label: _t('date'), values: ['input_date'] },
{ key: 'userId', label: _t('user_id'), values: ['input_number'] },
{ key: 'gender', label: _t('gender'), values: [{ key: 'male', label: _t('man') }, { key: 'female', label: _t('woman') }] },
@ -566,8 +566,6 @@ Application.Controllers.controller('StatisticsController', ['$scope', '$state',
{ key: 'ca', label: _t('revenue'), values: ['input_number'] }
]
$scope.filters = filters
if (!$scope.type.active.simple) {
const f = { key: 'stat', label: $scope.type.active.label, values: ['input_number'] }
$scope.filters.push(f)
@ -663,13 +661,13 @@ Application.Controllers.controller('ExportStatisticsController', [ '$scope', '$u
* Callback to open the datepicker (interval start)
* @param $event {Object} jQuery event object
*/
$scope.toggleStartDatePicker = $event => $scope.exportStart.opened = !$scope.exportStart.opened
$scope.toggleStartDatePicker = function ($event) { $scope.exportStart.opened = !$scope.exportStart.opened }
/**
* Callback to open the datepicker (interval end)
* @param $event {Object} jQuery event object
*/
$scope.toggleEndDatePicker = $event => $scope.exportEnd.opened = !$scope.exportEnd.opened
$scope.toggleEndDatePicker = function ($event) { $scope.exportEnd.opened = !$scope.exportEnd.opened }
/**
* Callback when exchanging the export type between 'global' and 'current view'
@ -696,7 +694,7 @@ Application.Controllers.controller('ExportStatisticsController', [ '$scope', '$u
})
} else {
$scope.actionUrl = `/stats/${index.key}/export`
return $scope.query = JSON.stringify(query)
$scope.query = JSON.stringify(query)
}
}
@ -722,6 +720,6 @@ Application.Controllers.controller('ExportStatisticsController', [ '$scope', '$u
/**
* Callback to cancel the export and close the modal
*/
return $scope.cancel = () => $uibModalInstance.dismiss('cancel')
$scope.cancel = function() { $uibModalInstance.dismiss('cancel') }
}
])

View File

@ -28,7 +28,7 @@
* Requires :
* - $state (Ui-Router) [ 'app.admin.trainings' ]
* - $scope.training
/*
*/
class TrainingsController {
constructor ($scope, $state) {
/*
@ -40,14 +40,14 @@ class TrainingsController {
$scope.submited = function (content) {
if ((content.id == null)) {
$scope.alerts = []
return angular.forEach(content, (v, k) =>
angular.forEach(v, err =>
return angular.forEach(content, function(v, k) {
angular.forEach(v, function (err) {
$scope.alerts.push({
msg: k + ': ' + err,
type: 'danger'
})
)
)
})
})
} else {
return $state.go('app.admin.trainings')
}
@ -56,12 +56,12 @@ class TrainingsController {
/**
* Changes the current user's view, redirecting him to the machines list
*/
$scope.cancel = () => $state.go('app.admin.trainings')
$scope.cancel = function() { $state.go('app.admin.trainings') }
/**
* Force the 'public_page' attribute to false when the current training is disabled
*/
$scope.onDisableToggled = () => $scope.training.public_page = !$scope.training.disabled
$scope.onDisableToggled = function() { $scope.training.public_page = !$scope.training.disabled }
/**
* For use with 'ng-class', returns the CSS class name for the uploads previews.
@ -219,7 +219,7 @@ Application.Controllers.controller('TrainingsAdminController', ['$scope', '$stat
* @param training {Object} Training object, inherited from $resource
* @param availability {Object} time slot when the training occurs
*/
$scope.showReservations = (training, availability) =>
$scope.showReservations = function(training, availability) {
$uibModal.open({
templateUrl: '<%= asset_path "admin/trainings/validTrainingModal.html" %>',
controller: ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {
@ -244,14 +244,14 @@ Application.Controllers.controller('TrainingsAdminController', ['$scope', '$stat
* Validates the modifications (training validations) and save them to the server
*/
$scope.ok = function () {
const users = $scope.usersToValid.map(u => u.id)
const users = $scope.usersToValid.map(function (u) { return u.id })
return Training.update({ id: training.id }, {
training: {
users
}
}
, function () { // success
angular.forEach($scope.usersToValid, u => u.is_valid = true)
angular.forEach($scope.usersToValid, function(u) { u.is_valid = true })
$scope.usersToValid = []
return $uibModalInstance.close(training)
})
@ -260,37 +260,44 @@ Application.Controllers.controller('TrainingsAdminController', ['$scope', '$stat
/**
* Cancel the modifications and close the modal window
*/
return $scope.cancel = () => $uibModalInstance.dismiss('cancel')
return $scope.cancel = function() { $uibModalInstance.dismiss('cancel') }
}
] })
}
/**
* Delete the provided training and, in case of sucess, remove it from the trainings list afterwards
* Delete the provided training and, in case of success, remove it from the trainings list afterwards
* @param index {number} index of the provided training in $scope.trainings
* @param training {Object} training to delete
*/
$scope.removeTraining = (index, training) =>
dialogs.confirm({
resolve: {
object () {
return {
title: _t('confirmation_required'),
msg: _t('do_you_really_want_to_delete_this_training')
$scope.removeTraining = function (index, training) {
dialogs.confirm(
{
resolve: {
object () {
return {
title: _t('confirmation_required'),
msg: _t('do_you_really_want_to_delete_this_training')
}
}
}
},
function() { // deletion confirmed
training.$delete(function () {
$scope.trainings.splice(index, 1);
growl.info(_t('training_successfully_deleted'))
},
function (error) {
growl.warning(_t('unable_to_delete_the_training_because_some_users_alredy_booked_it'));
console.error(error)
})
}
}
, () => // deletion confirmed
training.$delete(function () {
$scope.trainings.splice(index, 1)
return growl.info(_t('training_successfully_deleted'))
}
, error => growl.warning(_t('unable_to_delete_the_training_because_some_users_alredy_booked_it')))
)
}
/**
* Takes a month number and return its localized literal name
* @param {Number} from 0 to 11
* @param number {Number} from 0 to 11
* @returns {String} eg. 'janvier'
*/
$scope.formatMonth = function (number) {
@ -317,22 +324,21 @@ Application.Controllers.controller('TrainingsAdminController', ['$scope', '$stat
* Callback when the drop-down selection is changed.
* The selected training details will be loaded from the API and rendered into the accordions.
*/
$scope.selectTrainingToMonitor = () =>
$scope.selectTrainingToMonitor = function () {
Training.availabilities({ id: $scope.monitoring.training.id }, function (training) {
$scope.groupedAvailabilities = groupAvailabilities([training])
// we open current year/month by default
const now = moment()
$scope.accordions[training.name] = {}
$scope.accordions[training.name][now.year()] =
{ isOpenFirst: true }
return $scope.accordions[training.name][now.year()][now.month()] =
{ isOpenFirst: true }
$scope.accordions[training.name][now.year()] = { isOpenFirst: true }
$scope.accordions[training.name][now.year()][now.month()] = { isOpenFirst: true }
})
}
/* PRIVATE SCOPE */
/**
* Group the trainings availabilites by trainings and by dates and return the resulting tree
* Group the trainings availabilities by trainings and by dates and return the resulting tree
* @param trainings {Array} $scope.trainings is expected here
* @returns {Object} Tree constructed as /training_name/year/month/day/[availabilities]
*/

View File

@ -17,8 +17,7 @@ Application.Controllers.controller('PlansIndexController', ['$scope', '$rootScop
/* PUBLIC SCOPE */
// list of groups
let plan
$scope.groups = groupsPromise.filter(g => (g.slug !== 'admins') & !g.disabled)
$scope.groups = groupsPromise.filter(function (g) { return (g.slug !== 'admins') & !g.disabled; } )
// default : do not show the group changing form
// group ID of the current/selected user
@ -31,7 +30,7 @@ Application.Controllers.controller('PlansIndexController', ['$scope', '$rootScop
$scope.plansClassifiedByGroup = []
for (var group of Array.from($scope.groups)) {
const groupObj = { id: group.id, name: group.name, plans: [] }
for (plan of Array.from(plansPromise)) {
for (let plan of Array.from(plansPromise)) {
if (plan.group_id === group.id) { groupObj.plans.push(plan) }
}
$scope.plansClassifiedByGroup.push(groupObj)
@ -95,7 +94,7 @@ Application.Controllers.controller('PlansIndexController', ['$scope', '$rootScop
/**
* Callback to trigger the payment process of the subscription
*/
$scope.openSubscribePlanModal = () =>
$scope.openSubscribePlanModal = function () {
Wallet.getWalletByUser({ user_id: $scope.ctrl.member.id }, function (wallet) {
const amountToPay = helpers.getAmountToPay($scope.cart.total, wallet.amount)
if (($scope.currentUser.role !== 'admin') && (amountToPay > 0)) {
@ -106,6 +105,7 @@ Application.Controllers.controller('PlansIndexController', ['$scope', '$rootScop
}
}
})
}
/**
* Return the group object, identified by the ID set in $scope.group.id
@ -121,26 +121,27 @@ Application.Controllers.controller('PlansIndexController', ['$scope', '$rootScop
/**
* Change the group of the current/selected user to the one set in $scope.group.id
*/
$scope.selectGroup = () =>
$scope.selectGroup = function () {
Member.update({ id: $scope.ctrl.member.id }, { user: { group_id: $scope.group.id } }, function (user) {
$scope.ctrl.member = user
$scope.group.change = false
if ($scope.currentUser.role !== 'admin') {
$rootScope.currentUser = user
Auth._currentUser.group_id = user.group_id
return growl.success(_t('your_group_was_successfully_changed'))
} else {
return growl.success(_t('the_user_s_group_was_successfully_changed'))
$scope.ctrl.member = user
$scope.group.change = false
if ($scope.currentUser.role !== 'admin') {
$rootScope.currentUser = user
Auth._currentUser.group_id = user.group_id
growl.success(_t('your_group_was_successfully_changed'))
} else {
growl.success(_t('the_user_s_group_was_successfully_changed'))
}
}
}
, function (err) {
if ($scope.currentUser.role !== 'admin') {
growl.error(_t('an_error_prevented_your_group_from_being_changed'))
} else {
growl.error(_t('an_error_prevented_to_change_the_user_s_group'))
}
return console.error(err)
})
, function (err) {
if ($scope.currentUser.role !== 'admin') {
growl.error(_t('an_error_prevented_your_group_from_being_changed'))
} else {
growl.error(_t('an_error_prevented_to_change_the_user_s_group'))
}
console.error(err)
})
}
/**
* Return an enumerable meaninful string for the gender of the provider user
@ -159,17 +160,13 @@ Application.Controllers.controller('PlansIndexController', ['$scope', '$rootScop
* @return {boolean}
*/
$scope.isInFuture = function (dateTime) {
if (moment().diff(moment(dateTime)) < 0) {
return true
} else {
return false
}
return (moment().diff(moment(dateTime)) < 0);
}
/**
* To use as callback in Array.prototype.filter to get only enabled plans
*/
$scope.filterDisabledPlans = plan => !plan.disabled
$scope.filterDisabledPlans = function (plan) { return !plan.disabled }
/* PRIVATE SCOPE */
@ -185,7 +182,7 @@ Application.Controllers.controller('PlansIndexController', ['$scope', '$rootScop
}
}
$scope.$on('devise:new-session', (event, user) => $scope.ctrl.member = user)
$scope.$on('devise:new-session', function (event, user) { $scope.ctrl.member = user; });
// watch when a coupon is applied to re-compute the total price
return $scope.$watch('coupon.applied', function (newValue, oldValue) {
@ -221,7 +218,7 @@ Application.Controllers.controller('PlansIndexController', ['$scope', '$rootScop
/**
* Open a modal window which trigger the stripe payment process
*/
var payByStripe = () =>
var payByStripe = function () {
$uibModal.open({
templateUrl: '<%= asset_path "stripe/payment_modal.html" %>',
size: 'md',
@ -236,7 +233,7 @@ Application.Controllers.controller('PlansIndexController', ['$scope', '$rootScop
},
controller: ['$scope', '$uibModalInstance', '$state', 'selectedPlan', 'member', 'price', 'Subscription', 'CustomAsset', 'wallet', 'helpers', '$filter', 'coupon',
function ($scope, $uibModalInstance, $state, selectedPlan, member, price, Subscription, CustomAsset, wallet, helpers, $filter, coupon) {
// User's wallet amount
// User's wallet amount
$scope.walletAmount = wallet.amount
// Final price to pay by the user
@ -249,50 +246,52 @@ Application.Controllers.controller('PlansIndexController', ['$scope', '$rootScop
$scope.numberFilter = $filter('number')
// retrieve the CGV
CustomAsset.get({ name: 'cgv-file' }, cgv => $scope.cgv = cgv.custom_asset)
CustomAsset.get({ name: 'cgv-file' }, function (cgv) { $scope.cgv = cgv.custom_asset; });
/**
* Callback for click on the 'proceed' button.
* Handle the stripe's card tokenization process response and save the subscription to the API with the
* card token just created.
*/
return $scope.payment = function (status, response) {
$scope.payment = function (status, response) {
if (response.error) {
return growl.error(response.error.message)
growl.error(response.error.message)
} else {
$scope.attempting = true
return Subscription.save({
coupon_code: ((coupon ? coupon.code : undefined)),
subscription: {
plan_id: selectedPlan.id,
user_id: member.id,
card_token: response.id
Subscription.save({
coupon_code: ((coupon ? coupon.code : undefined)),
subscription: {
plan_id: selectedPlan.id,
user_id: member.id,
card_token: response.id
}
}
}
, (data, status) => // success
$uibModalInstance.close(data)
, function (data, status) { // failed
$scope.alerts = []
$scope.alerts.push({ msg: _t('an_error_occured_during_the_payment_process_please_try_again_later'), type: 'danger' })
return $scope.attempting = false
})
, function (data) { // success
$uibModalInstance.close(data)
}
, function (data, status) { // failed
$scope.alerts = []
$scope.alerts.push({ msg: _t('an_error_occured_during_the_payment_process_please_try_again_later'), type: 'danger' })
$scope.attempting = false
}
)
}
}
}
] })
.result['finally'](null).then(function (subscription) {
$scope.ctrl.member.subscribed_plan = angular.copy($scope.selectedPlan)
Auth._currentUser.subscribed_plan = angular.copy($scope.selectedPlan)
$scope.paid.plan = angular.copy($scope.selectedPlan)
$scope.selectedPlan = null
return $scope.coupon.applied = null
})
]
}).result['finally'](null).then(function (subscription) {
$scope.ctrl.member.subscribed_plan = angular.copy($scope.selectedPlan)
Auth._currentUser.subscribed_plan = angular.copy($scope.selectedPlan)
$scope.paid.plan = angular.copy($scope.selectedPlan)
$scope.selectedPlan = null
$scope.coupon.applied = null
})
}
/**
* Open a modal window which trigger the local payment process
*/
var payOnSite = () =>
var payOnSite = function () {
$uibModal.open({
templateUrl: '<%= asset_path "plans/payment_modal.html" %>',
size: 'sm',
@ -307,7 +306,7 @@ Application.Controllers.controller('PlansIndexController', ['$scope', '$rootScop
},
controller: ['$scope', '$uibModalInstance', '$state', 'selectedPlan', 'member', 'price', 'Subscription', 'wallet', 'helpers', '$filter', 'coupon',
function ($scope, $uibModalInstance, $state, selectedPlan, member, price, Subscription, wallet, helpers, $filter, coupon) {
// user wallet amount
// user wallet amount
$scope.walletAmount = wallet.amount
// subcription price, coupon subtracted if any
@ -342,38 +341,40 @@ Application.Controllers.controller('PlansIndexController', ['$scope', '$rootScop
*/
$scope.ok = function () {
$scope.attempting = true
return Subscription.save({
coupon_code: ((coupon ? coupon.code : undefined)),
subscription: {
plan_id: selectedPlan.id,
user_id: member.id
Subscription.save({
coupon_code: ((coupon ? coupon.code : undefined)),
subscription: {
plan_id: selectedPlan.id,
user_id: member.id
}
}
}
, (data, status) => // success
$uibModalInstance.close(data)
, function (data, status) { // failed
, function (data) { // success
$uibModalInstance.close(data)
}
, function (data, status) { // failed
$scope.alerts = []
$scope.alerts.push({ msg: _t('an_error_occured_during_the_payment_process_please_try_again_later'), type: 'danger' })
return $scope.attempting = false
})
$scope.alerts.push({ msg: _t('an_error_occured_during_the_payment_process_please_try_again_later'), type: 'danger' })
$scope.attempting = false
}
)
}
/**
* Callback for the 'cancel' button.
* Close the modal box.
*/
return $scope.cancel = () => $uibModalInstance.dismiss('cancel')
$scope.cancel = function () { $uibModalInstance.dismiss('cancel') }
}
] })
.result['finally'](null).then(function (reservation) {
$scope.ctrl.member.subscribed_plan = angular.copy($scope.selectedPlan)
Auth._currentUser.subscribed_plan = angular.copy($scope.selectedPlan)
$scope.ctrl.member = null
$scope.paid.plan = angular.copy($scope.selectedPlan)
$scope.selectedPlan = null
return $scope.coupon.applied = null
})
]
}).result['finally'](null).then(function (reservation) {
$scope.ctrl.member.subscribed_plan = angular.copy($scope.selectedPlan)
Auth._currentUser.subscribed_plan = angular.copy($scope.selectedPlan)
$scope.ctrl.member = null
$scope.paid.plan = angular.copy($scope.selectedPlan)
$scope.selectedPlan = null
return $scope.coupon.applied = null
})
}
// !!! MUST BE CALLED AT THE END of the controller
return initialize()

View File

@ -76,14 +76,14 @@ Application.Controllers.controller('CompleteProfileController', ['$scope', '$roo
$scope.submited = function (content) {
if ((content.id == null)) {
$scope.alerts = []
return angular.forEach(content, (v, k) =>
angular.forEach(v, err =>
angular.forEach(content, function (v, k) {
angular.forEach(v, function (err) {
$scope.alerts.push({
msg: k + ': ' + err,
type: 'danger'
})
)
)
})
})
} else {
$scope.user.profile.user_avatar = content.profile.user_avatar
Auth._currentUser.profile.user_avatar = content.profile.user_avatar
@ -112,21 +112,22 @@ Application.Controllers.controller('CompleteProfileController', ['$scope', '$roo
/**
* Merge the current user into the account with the given auth_token
*/
$scope.registerAuthToken = () =>
$scope.registerAuthToken = function () {
Member.merge({ id: $rootScope.currentUser.id }, { user: { auth_token: $scope.user.auth_token } }, function (user) {
$scope.user = user
Auth._currentUser = user
$rootScope.currentUser = user
return $state.go('app.public.home')
}
, function (err) {
if (err.data.error) {
return growl.error(err.data.error)
} else {
growl.error(_t('an_unexpected_error_occurred_check_your_authentication_code'))
return console.error(err)
$scope.user = user
Auth._currentUser = user
$rootScope.currentUser = user
$state.go('app.public.home')
}
})
, function (err) {
if (err.data.error) {
growl.error(err.data.error)
} else {
growl.error(_t('an_unexpected_error_occurred_check_your_authentication_code'))
console.error(err)
}
})
}
/**
* Return the email given by the SSO provider, parsed if needed
@ -156,30 +157,34 @@ Application.Controllers.controller('CompleteProfileController', ['$scope', '$roo
/**
* Ask for email confirmation and send the SSO merging token again
* @param $event {Object} jQuery event object
* @param event {Object} jQuery event object
*/
$scope.resendCode = function (event) {
event.preventDefault()
event.stopPropagation()
return dialogs.confirm({
templateUrl: '<%= asset_path "profile/resend_code_modal.html" %>',
resolve: {
object () {
return { email: memberPromise.email }
dialogs.confirm(
{
templateUrl: '<%= asset_path "profile/resend_code_modal.html" %>',
resolve: {
object () {
return { email: memberPromise.email }
}
}
},
function (email) {
// Request the server to send an auth-migration email to the current user
AuthProvider.send_code({ email },
function (res) { growl.info(_t('code_successfully_sent_again')) },
function (err) { growl.error(err.data.error) }
)
}
}
, email =>
// Request the server to send an auth-migration email to the current user
AuthProvider.send_code({ email }, res => growl.info(_t('code_successfully_sent_again'))
, err => growl.error(err.data.error))
)
}
/**
* Disconnect and re-connect the user to the SSO to force the synchronisation of the profile's data
*/
$scope.syncProfile = () =>
$scope.syncProfile = function () {
Auth.logout().then(function (oldUser) {
Session.destroy()
$rootScope.currentUser = null
@ -188,8 +193,9 @@ Application.Controllers.controller('CompleteProfileController', ['$scope', '$roo
total: 0,
unread: 0
}
return $window.location.href = activeProviderPromise.link_to_sso_connect
$window.location.href = activeProviderPromise.link_to_sso_connect
})
}
/* PRIVATE SCOPE */
@ -203,7 +209,7 @@ Application.Controllers.controller('CompleteProfileController', ['$scope', '$roo
$scope.user.profile.birthday = moment($scope.user.profile.birthday).toDate()
// bind fields protection with sso fields
return angular.forEach(activeProviderPromise.mapping, map => $scope.preventField[map] = true)
angular.forEach(activeProviderPromise.mapping, function (map) { $scope.preventField[map] = true; })
}
// !!! MUST BE CALLED AT THE END of the controller

View File

@ -44,44 +44,44 @@
class ProjectsController {
constructor ($scope, $state, Project, Machine, Member, Component, Theme, Licence, $document, Diacritics, dialogs, allowedExtensions, _t) {
// Retrieve the list of machines from the server
Machine.query().$promise.then(data =>
$scope.machines = data.map(d =>
Machine.query().$promise.then(function (data) {
$scope.machines = data.map(function (d) {
({
id: d.id,
name: d.name
})
)
)
})
})
// Retrieve the list of components from the server
Component.query().$promise.then(data =>
$scope.components = data.map(d =>
Component.query().$promise.then(function (data) {
$scope.components = data.map(function (d) {
({
id: d.id,
name: d.name
})
)
)
})
})
// Retrieve the list of themes from the server
Theme.query().$promise.then(data =>
$scope.themes = data.map(d =>
Theme.query().$promise.then(function (data) {
$scope.themes = data.map(function (d) {
({
id: d.id,
name: d.name
})
)
)
})
})
// Retrieve the list of licences from the server
Licence.query().$promise.then(data =>
$scope.licences = data.map(d =>
Licence.query().$promise.then(function (data) {
$scope.licences = data.map(function (d) {
({
id: d.id,
name: d.name
})
)
)
})
})
// Total number of documentation steps for the current project
$scope.totalSteps = $scope.project.project_steps_attributes.length
@ -98,14 +98,14 @@ class ProjectsController {
$scope.submited = function (content) {
if ((content.id == null)) {
$scope.alerts = []
angular.forEach(content, (v, k) =>
angular.forEach(v, err =>
angular.forEach(content, function (v, k) {
angular.forEach(v, function (err) {
$scope.alerts.push({
msg: k + ': ' + err,
type: 'danger'
})
)
)
})
})
// using https://github.com/oblador/angular-scroll
$('section[ui-view=main]').scrollTop(0, 200)
} else {
@ -129,7 +129,7 @@ class ProjectsController {
/**
* This will create a single new empty entry into the project's CAO attachements list.
*/
$scope.addFile = () => $scope.project.project_caos_attributes.push({})
$scope.addFile = function() { $scope.project.project_caos_attributes.push({}) }
/**
* This will remove the given file from the project's CAO attachements list. If the file was previously uploaded
@ -158,42 +158,43 @@ class ProjectsController {
* This will remove the given step from the project's steps list. If the step was previously saved
* on the server, it will be marked for deletion for the next saving. Otherwise, it will be simply truncated from
* the steps array.
* @param file {Object} the file to delete
* @param step {Object} the step to delete
*/
$scope.deleteStep = step =>
$scope.deleteStep = function (step) {
dialogs.confirm({
resolve: {
object () {
return {
title: _t('confirmation_required'),
msg: _t('do_you_really_want_to_delete_this_step')
resolve: {
object() {
return {
title: _t('confirmation_required'),
msg: _t('do_you_really_want_to_delete_this_step')
}
}
}
}
}
, function () { // deletion confirmed
const index = $scope.project.project_steps_attributes.indexOf(step)
if (step.id != null) {
step._destroy = true
} else {
$scope.project.project_steps_attributes.splice(index, 1)
}
, function () { // deletion confirmed
const index = $scope.project.project_steps_attributes.indexOf(step)
if (step.id != null) {
step._destroy = true
} else {
$scope.project.project_steps_attributes.splice(index, 1)
}
// update the new total number of steps
$scope.totalSteps -= 1
// reindex the remaning steps
return (() => {
const result = []
for (let s of Array.from($scope.project.project_steps_attributes)) {
if (s.step_nb > step.step_nb) {
result.push(s.step_nb -= 1)
} else {
result.push(undefined)
// update the new total number of steps
$scope.totalSteps -= 1
// reindex the remaining steps
return (function () {
const result = []
for (let s of Array.from($scope.project.project_steps_attributes)) {
if (s.step_nb > step.step_nb) {
result.push(s.step_nb -= 1)
} else {
result.push(undefined)
}
}
}
return result
})()
})
return result
})()
})
}
/**
* Change the step_nb property of the given step to the new value provided. The step that was previously at this
@ -220,14 +221,17 @@ class ProjectsController {
}
const asciiName = Diacritics.remove(nameLookup)
return Member.search({ query: asciiName }, users => $scope.matchingMembers = users
, error => console.error(error))
Member.search(
{ query: asciiName },
function (users) { $scope.matchingMembers = users },
function (error) { console.error(error) }
)
}
/**
* This will create a single new empty entry into the project's step image list.
*/
$scope.addProjectStepImage = step => step.project_step_images_attributes.push({})
$scope.addProjectStepImage = function (step) { step.project_step_images_attributes.push({}) }
/**
* This will remove the given image from the project's step image list.
@ -287,9 +291,12 @@ Application.Controllers.controller('ProjectsController', ['$scope', '$state', 'P
// list of components / used for filtering
$scope.components = componentsPromise
$scope.searchOverWholeNetworkChanged = () =>
setTimeout(() => $scope.resetFiltersAndTriggerSearch()
, 150)
$scope.searchOverWholeNetworkChanged = function () {
setTimeout(
function() { $scope.resetFiltersAndTriggerSearch() },
150
)
}
$scope.loadMore = function () {
if ($scope.openlab.searchOverWholeNetwork === true) {
@ -380,7 +387,7 @@ Application.Controllers.controller('ProjectsController', ['$scope', '$state', 'P
var updateUrlParam = function (name, value) {
$state.current.reloadOnSearch = false
$location.search(name, value)
return $timeout(() => $state.current.reloadOnSearch = undefined)
return $timeout(function() { $state.current.reloadOnSearch = undefined})
}
var loadMoreCallback = function (projectsPromise) {
@ -393,11 +400,12 @@ Application.Controllers.controller('ProjectsController', ['$scope', '$state', 'P
return updateUrlParam('page', $scope.projectsPagination.currentPage)
}
var normalizeProjectsAttrs = projects =>
var normalizeProjectsAttrs = function (projects) {
projects.map(function (project) {
project.project_image = project.image_url
return project
})
}
// !!! MUST BE CALLED AT THE END of the controller
return initialize()
@ -446,12 +454,12 @@ Application.Controllers.controller('EditProjectController', ['$scope', '$state',
// Retrieve the project's details, if an error occured, redirect the user to the projects list page
$scope.project = projectPromise
$scope.matchingMembers = $scope.project.project_users.map(u =>
({
$scope.matchingMembers = $scope.project.project_users.map(function (u) {
return ({
id: u.id,
name: u.full_name
})
)
})
// Using the ProjectsController
return new ProjectsController($scope, $state, Project, Machine, Member, Component, Theme, Licence, $document, Diacritics, dialogs, allowedExtensions, _t)
@ -513,9 +521,9 @@ Application.Controllers.controller('ShowProjectController', ['$scope', '$state',
}
}
}
, () => // cancel confirmed
$scope.project.$delete(() => $state.go('app.public.projects_list', {}, { reload: true }))
)
, function () { // cancel confirmed
$scope.project.$delete(function() { $state.go('app.public.projects_list', {}, { reload: true }) })
})
} else {
return console.error(_t('unauthorized_operation'))
}
@ -528,7 +536,7 @@ Application.Controllers.controller('ShowProjectController', ['$scope', '$state',
$scope.signalAbuse = function (e) {
if (e) { e.preventDefault() }
return $uibModal.open({
$uibModal.open({
templateUrl: '<%= asset_path "shared/signalAbuseModal.html" %>',
size: 'md',
resolve: {
@ -542,31 +550,36 @@ Application.Controllers.controller('ShowProjectController', ['$scope', '$state',
}
// callback for signaling cancellation
$scope.cancel = () => $uibModalInstance.dismiss('cancel')
$scope.cancel = function() { $uibModalInstance.dismiss('cancel') }
// callback for form validation
return $scope.ok = () =>
Abuse.save({}, { abuse: $scope.signaler }, function (res) {
// creation successful
growl.success(_t('your_report_was_successful_thanks'))
return $uibModalInstance.close(res)
}
, error =>
// creation failed...
growl.error(_t('an_error_occured_while_sending_your_report'))
return $scope.ok = function() {
Abuse.save(
{},
{ abuse: $scope.signaler },
function (res) {
// creation successful
growl.success(_t('your_report_was_successful_thanks'))
return $uibModalInstance.close(res)
}
, function (error) {
// creation failed...
growl.error(_t('an_error_occured_while_sending_your_report'))
}
)
}
] })
}
}]
})
}
/**
* Return the URL allowing to share the current project on the Facebook social network
*/
$scope.shareOnFacebook = () => `https://www.facebook.com/share.php?u=${$state.href('app.public.projects_show', { id: $scope.project.slug }, { absolute: true }).replace('#', '%23')}`
$scope.shareOnFacebook = function () { return `https://www.facebook.com/share.php?u=${$state.href('app.public.projects_show', { id: $scope.project.slug }, { absolute: true }).replace('#', '%23')}` }
/**
* Return the URL allowing to share the current project on the Twitter social network
*/
return $scope.shareOnTwitter = () => `https://twitter.com/intent/tweet?url=${encodeURIComponent($state.href('app.public.projects_show', { id: $scope.project.slug }, { absolute: true }))}&text=${encodeURIComponent($scope.project.name)}`
$scope.shareOnTwitter = function () { return `https://twitter.com/intent/tweet?url=${encodeURIComponent($state.href('app.public.projects_show', { id: $scope.project.slug }, { absolute: true }))}&text=${encodeURIComponent($scope.project.name)}` }
}
])

View File

@ -42,23 +42,23 @@ class SpacesController {
$scope.submited = function (content) {
if ((content.id == null)) {
$scope.alerts = []
return angular.forEach(content, (v, k) =>
angular.forEach(v, err =>
angular.forEach(content, function (v, k) {
angular.forEach(v, function (err) {
$scope.alerts.push({
msg: k + ': ' + err,
type: 'danger'
})
)
)
})
})
} else {
return $state.go('app.public.spaces_list')
$state.go('app.public.spaces_list')
}
}
/**
* Changes the current user's view, redirecting him to the spaces list
*/
$scope.cancel = () => $state.go('app.public.spaces_list')
$scope.cancel = function() { $state.go('app.public.spaces_list') }
/**
* For use with 'ng-class', returns the CSS class name for the uploads previews.
@ -74,14 +74,14 @@ class SpacesController {
}
/**
* This will create a single new empty entry into the space attachements list.
* This will create a single new empty entry into the space attachments list.
*/
$scope.addFile = () => $scope.space.space_files_attributes.push({})
$scope.addFile = function() { $scope.space.space_files_attributes.push({}) }
/**
* This will remove the given file from the space attachements list. If the file was previously uploaded
* This will remove the given file from the space attachments list. If the file was previously uploaded
* to the server, it will be marked for deletion on the server. Otherwise, it will be simply truncated from
* the attachements array.
* the attachments array.
* @param file {Object} the file to delete
*/
$scope.deleteFile = function (file) {
@ -105,24 +105,23 @@ Application.Controllers.controller('SpacesController', ['$scope', '$state', 'spa
/**
* Redirect the user to the space details page
*/
$scope.showSpace = space => $state.go('app.public.space_show', { id: space.slug })
$scope.showSpace = function (space) { $state.go('app.public.space_show', { id: space.slug }) }
/**
* Callback to book a reservation for the current space
*/
$scope.reserveSpace = space => $state.go('app.logged.space_reserve', { id: space.slug })
$scope.reserveSpace = function (space) { $state.go('app.logged.space_reserve', { id: space.slug }) }
// Default: we show only enabled spaces
$scope.spaceFiltering = 'enabled'
// Available options for filtering spaces by status
return $scope.filterDisabled = [
$scope.filterDisabled = [
'enabled',
'disabled',
'all'
]
}
])
}])
/**
* Controller used in the space creation page (admin)
@ -142,8 +141,7 @@ Application.Controllers.controller('NewSpaceController', ['$scope', '$state', 'C
// Using the SpacesController
return new SpacesController($scope, $state)
}
])
}])
/**
* Controller used in the space edition page (admin)
@ -162,8 +160,7 @@ Application.Controllers.controller('EditSpaceController', ['$scope', '$state', '
// Using the SpacesController
return new SpacesController($scope, $state)
}
])
}])
Application.Controllers.controller('ShowSpaceController', ['$scope', '$state', 'spacePromise', '_t', 'dialogs', 'growl', function ($scope, $state, spacePromise, _t, dialogs, growl) {
// Details of the space witch id/slug is provided in the URL
@ -182,7 +179,7 @@ Application.Controllers.controller('ShowSpaceController', ['$scope', '$state', '
* Callback to book a reservation for the current space
* @param event {Object} see https://docs.angularjs.org/guide/expression#-event-
*/
return $scope.deleteSpace = function (event) {
$scope.deleteSpace = function (event) {
event.preventDefault()
// check the permissions
if ($scope.currentUser.role !== 'admin') {
@ -198,15 +195,21 @@ Application.Controllers.controller('ShowSpaceController', ['$scope', '$state', '
}
}
}
, () => // deletion confirmed
, function() { // deletion confirmed
// delete the machine then redirect to the machines listing
$scope.space.$delete(() => $state.go('app.public.spaces_list')
, error => growl.warning(_t('space_show.the_space_cant_be_deleted_because_it_is_already_reserved_by_some_users')))
)
$scope.space.$delete(
function () {
$state.go('app.public.spaces_list')
},
function (error) {
growl.warning(_t('space_show.the_space_cant_be_deleted_because_it_is_already_reserved_by_some_users'));
console.error(error)
}
)
})
}
}
}
])
}])
/**
* Controller used in the spaces reservation agenda page.
@ -321,7 +324,7 @@ Application.Controllers.controller('ReserveSpaceController', ['$scope', '$stateP
/**
* Callback when a slot was successfully cancelled. Reset the slot style as 'ready to book'
*/
$scope.slotCancelled = () => $scope.markSlotAsRemoved($scope.selectedEvent)
$scope.slotCancelled = function() { $scope.markSlotAsRemoved($scope.selectedEvent) }
/**
* Change the last selected slot's appearence to looks like 'currently looking for a new destination to exchange'
@ -435,7 +438,7 @@ Application.Controllers.controller('ReserveSpaceController', ['$scope', '$stateP
/**
* Switch the user's view from the reservation agenda to the plan subscription
*/
$scope.showPlans = () => $scope.plansAreShown = true
$scope.showPlans = function () { $scope.plansAreShown = true }
/**
* Once the reservation is booked (payment process successfully completed), change the event style
@ -469,7 +472,7 @@ Application.Controllers.controller('ReserveSpaceController', ['$scope', '$stateP
/**
* To use as callback in Array.prototype.filter to get only enabled plans
*/
$scope.filterDisabledPlans = plan => !plan.disabled
$scope.filterDisabledPlans = function (plan) { return !plan.disabled; }
/* PRIVATE SCOPE */
@ -478,7 +481,7 @@ Application.Controllers.controller('ReserveSpaceController', ['$scope', '$stateP
*/
const initialize = function () {
if ($scope.currentUser.role !== 'admin') {
return Member.get({ id: $scope.currentUser.id }, member => $scope.ctrl.member = member)
return Member.get({ id: $scope.currentUser.id }, function (member) { $scope.ctrl.member = member })
}
}
@ -518,26 +521,28 @@ Application.Controllers.controller('ReserveSpaceController', ['$scope', '$stateP
* @param slot {Object}
* @param reservation {Object}
*/
var updateSpaceSlotId = (slot, reservation) =>
var updateSpaceSlotId = function (slot, reservation) {
angular.forEach(reservation.slots, function (s) {
if (slot.start_at === slot.start_at) {
return slot.id = s.id
}
})
}
/**
* Update the calendar's display to render the new attributes of the events
*/
var updateCalendar = () => uiCalendarConfig.calendars.calendar.fullCalendar('rerenderEvents')
var updateCalendar = function() { uiCalendarConfig.calendars.calendar.fullCalendar('rerenderEvents') }
/**
* Asynchronously fetch the events from the API and refresh the calendar's view with these new events
*/
var refetchCalendar = () =>
var refetchCalendar = function () {
$timeout(function () {
uiCalendarConfig.calendars.calendar.fullCalendar('refetchEvents')
return uiCalendarConfig.calendars.calendar.fullCalendar('rerenderEvents')
})
}
// !!! MUST BE CALLED AT THE END of the controller
return initialize()

View File

@ -24,14 +24,13 @@ Application.Controllers.controller('TrainingsController', ['$scope', '$state', '
/**
* Callback for the 'reserve' button
*/
$scope.reserveTraining = (training, event) => $state.go('app.logged.trainings_reserve', { id: training.slug })
$scope.reserveTraining = function (training, event) { $state.go('app.logged.trainings_reserve', { id: training.slug }) }
/**
* Callback for the 'show' button
*/
return $scope.showTraining = training => $state.go('app.public.training_show', { id: training.slug })
}
])
return $scope.showTraining = function (training) { $state.go('app.public.training_show', { id: training.slug }) }
}])
/**
* Public view of a specific training
@ -46,22 +45,29 @@ Application.Controllers.controller('ShowTrainingController', ['$scope', '$state'
$scope.delete = function (training) {
// check the permissions
if ($scope.currentUser.role !== 'admin') {
return console.error(_t('unauthorized_operation'))
console.error(_t('unauthorized_operation'))
} else {
return dialogs.confirm({
resolve: {
object () {
return {
title: _t('confirmation_required'),
msg: _t('do_you_really_want_to_delete_this_training')
dialogs.confirm(
{
resolve: {
object () {
return {
title: _t('confirmation_required'),
msg: _t('do_you_really_want_to_delete_this_training')
}
}
}
},
function() { // deletion confirmed
// delete the training then redirect to the trainings listing
training.$delete(
function() { $state.go('app.public.trainings_list') },
function (error) {
growl.warning(_t('the_training_cant_be_deleted_because_it_is_already_reserved_by_some_users'));
console.error(error);
}
)
}
}
, () => // deletion confirmed
// delete the training then redirect to the trainings listing
training.$delete(() => $state.go('app.public.trainings_list')
, error => growl.warning(_t('the_training_cant_be_deleted_because_it_is_already_reserved_by_some_users')))
)
}
}
@ -69,14 +75,13 @@ Application.Controllers.controller('ShowTrainingController', ['$scope', '$state'
/**
* Callback for the 'reserve' button
*/
$scope.reserveTraining = (training, event) => $state.go('app.logged.trainings_reserve', { id: training.id })
$scope.reserveTraining = function (training, event) { $state.go('app.logged.trainings_reserve', { id: training.id }) }
/**
* Revert view to the full list of trainings ("<-" button)
*/
return $scope.cancel = event => $state.go('app.public.trainings_list')
}
])
$scope.cancel = function (event) { $state.go('app.public.trainings_list') }
}])
/**
* Controller used in the training reservation agenda page.
@ -194,7 +199,7 @@ Application.Controllers.controller('ReserveTrainingController', ['$scope', '$sta
/**
* Callback when a slot was successfully cancelled. Reset the slot style as 'ready to book'
*/
$scope.slotCancelled = () => $scope.markSlotAsRemoved($scope.selectedEvent)
$scope.slotCancelled = function () { $scope.markSlotAsRemoved($scope.selectedEvent) }
/**
* Change the last selected slot's appearence to looks like 'currently looking for a new destination to exchange'
@ -309,7 +314,7 @@ Application.Controllers.controller('ReserveTrainingController', ['$scope', '$sta
/**
* Switch the user's view from the reservation agenda to the plan subscription
*/
$scope.showPlans = () => $scope.plansAreShown = true
$scope.showPlans = function () { $scope.plansAreShown = true }
/**
* Once the reservation is booked (payment process successfully completed), change the event style
@ -341,7 +346,7 @@ Application.Controllers.controller('ReserveTrainingController', ['$scope', '$sta
/**
* To use as callback in Array.prototype.filter to get only enabled plans
*/
$scope.filterDisabledPlans = plan => !plan.disabled
$scope.filterDisabledPlans = function (plan) { return !plan.disabled }
/* PRIVATE SCOPE */
@ -350,7 +355,7 @@ Application.Controllers.controller('ReserveTrainingController', ['$scope', '$sta
*/
const initialize = function () {
if ($scope.currentUser.role !== 'admin') {
return Member.get({ id: $scope.currentUser.id }, member => $scope.ctrl.member = member)
return Member.get({ id: $scope.currentUser.id }, function (member) { $scope.ctrl.member = member })
}
}
@ -390,26 +395,28 @@ Application.Controllers.controller('ReserveTrainingController', ['$scope', '$sta
* @param slot {Object}
* @param reservation {Object}
*/
var updateTrainingSlotId = (slot, reservation) =>
var updateTrainingSlotId = function (slot, reservation) {
angular.forEach(reservation.slots, function (s) {
if (slot.start_at === slot.start_at) {
return slot.id = s.id
}
})
}
/**
* Update the calendar's display to render the new attributes of the events
*/
var updateCalendar = () => uiCalendarConfig.calendars.calendar.fullCalendar('rerenderEvents')
var updateCalendar = function () { uiCalendarConfig.calendars.calendar.fullCalendar('rerenderEvents') }
/**
* Asynchronously fetch the events from the API and refresh the calendar's view with these new events
*/
var refetchCalendar = () =>
var refetchCalendar = function () {
$timeout(function () {
uiCalendarConfig.calendars.calendar.fullCalendar('refetchEvents')
return uiCalendarConfig.calendars.calendar.fullCalendar('rerenderEvents')
})
}
// !!! MUST BE CALLED AT THE END of the controller
return initialize()