Refactored the backend_settings.js module.

This commit is contained in:
Alex Tselegidis 2016-04-13 19:54:56 +02:00
parent 6deba85a36
commit 967021acf7
4 changed files with 311 additions and 254 deletions

View file

@ -1,3 +1,7 @@
<script type="text/javascript"
src="<?php echo $base_url; ?>/assets/js/backend_settings_system.js"></script>
<script type="text/javascript"
src="<?php echo $base_url; ?>/assets/js/backend_settings_user.js"></script>
<script type="text/javascript" <script type="text/javascript"
src="<?php echo $base_url; ?>/assets/js/backend_settings.js"></script> src="<?php echo $base_url; ?>/assets/js/backend_settings.js"></script>
<script type="text/javascript" <script type="text/javascript"

View file

@ -9,29 +9,35 @@
* @since v1.0.0 * @since v1.0.0
* ---------------------------------------------------------------------------- */ * ---------------------------------------------------------------------------- */
window.BackendSettings = window.BackendSettings || {};
/** /**
* Contains the functionality of the backend settings page. Can either work for * Contains the functionality of the backend settings page. Can either work for
* system or user settings, but the actions allowed to the user are restricted to * system or user settings, but the actions allowed to the user are restricted to
* his role (only admin has full privileges). * his role (only admin has full privileges).
* *
* @namespace BackendSettings * @module BackendSettings
*/ */
var BackendSettings = { (function(exports) {
SETTINGS_SYSTEM: 'SETTINGS_SYSTEM',
SETTINGS_USER: 'SETTINGS_USER', 'use strict';
// Constants
exports.SETTINGS_SYSTEM = 'SETTINGS_SYSTEM';
exports.SETTINGS_USER = 'SETTINGS_USER';
/** /**
* Use this WorkingPlan class instance to perform actions on the page's working plan * Use this WorkingPlan class instance to perform actions on the page's working plan
* tables. * tables.
*/ */
wp: {}, exports.wp = {};
/** /**
* Tab settings object. * Tab settings object.
* *
* @type {object} * @type {object}
*/ */
settings: {}, var settings = {};
/** /**
* Initialize Page * Initialize Page
@ -40,8 +46,8 @@ var BackendSettings = {
* handlers (default = true). * handlers (default = true).
* @returns {undefined} * @returns {undefined}
*/ */
initialize: function(bindEventHandlers) { exports.initialize = function(bindEventHandlers) {
if (bindEventHandlers == undefined) bindEventHandlers = true; bindEventHandlers = bindEventHandlers || true;
// Apply setting values from database. // Apply setting values from database.
$.each(GlobalVariables.settings.system, function(index, setting) { $.each(GlobalVariables.settings.system, function(index, setting) {
@ -64,9 +70,9 @@ var BackendSettings = {
} }
}); });
BackendSettings.wp = new WorkingPlan(); exports.wp = new WorkingPlan();
BackendSettings.wp.setup(workingPlan); exports.wp.setup(workingPlan);
BackendSettings.wp.timepickers(false); exports.wp.timepickers(false);
// Book Advance Timeout Spinner // Book Advance Timeout Spinner
$('#book-advance-timeout').spinner({ $('#book-advance-timeout').spinner({
@ -96,10 +102,10 @@ var BackendSettings = {
} }
// Set default settings helper. // Set default settings helper.
BackendSettings.settings = new SystemSettings(); settings = new SystemSettings();
if (bindEventHandlers) { if (bindEventHandlers) {
BackendSettings.bindEventHandlers(); _bindEventHandlers();
$('#settings-page .nav li').first().addClass('active'); $('#settings-page .nav li').first().addClass('active');
$('#settings-page .nav li').first().find('a').trigger('click'); $('#settings-page .nav li').first().find('a').trigger('click');
} }
@ -116,14 +122,14 @@ var BackendSettings = {
} }
Backend.placeFooterToBottom(); Backend.placeFooterToBottom();
}, };
/** /**
* Bind the backend/settings default event handlers. This method depends on the * Bind the backend/settings default event handlers. This method depends on the
* backend/settings html, so do not use this method on a different page. * backend/settings html, so do not use this method on a different page.
*/ */
bindEventHandlers: function() { function _bindEventHandlers() {
BackendSettings.wp.bindEventHandlers(); exports.wp.bindEventHandlers();
/** /**
* Event: Tab "Click" * Event: Tab "Click"
@ -142,14 +148,14 @@ var BackendSettings = {
if ($(this).hasClass('general-tab')) { if ($(this).hasClass('general-tab')) {
$('#general').show(); $('#general').show();
BackendSettings.settings = new SystemSettings(); settings = new SystemSettings();
} else if ($(this).hasClass('business-logic-tab')) { } else if ($(this).hasClass('business-logic-tab')) {
$('#business-logic').show(); $('#business-logic').show();
BackendSettings.settings = new SystemSettings(); settings = new SystemSettings();
} else if ($(this).hasClass('user-tab')) { } else if ($(this).hasClass('user-tab')) {
$('#user').show(); $('#user').show();
BackendSettings.settings = new UserSettings(); settings = new UserSettings();
// Apply toggle state to user notifications button. // Apply toggle state to user notifications button.
if (areNotificationsActive) { if (areNotificationsActive) {
@ -170,8 +176,8 @@ var BackendSettings = {
* Store the setting changes into the database. * Store the setting changes into the database.
*/ */
$('.save-settings').click(function() { $('.save-settings').click(function() {
var settings = BackendSettings.settings.get(); var data = settings.get();
BackendSettings.settings.save(settings); settings.save(data);
}); });
/** /**
@ -183,17 +189,22 @@ var BackendSettings = {
$('#username').focusout(function() { $('#username').focusout(function() {
var $input = $(this); var $input = $(this);
if ($input.prop('readonly') == true || $input.val() == '') return; if ($input.prop('readonly') == true || $input.val() == '') {
return;
}
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_validate_username'; var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_validate_username',
var postData = { postData = {
'csrfToken': GlobalVariables.csrfToken, csrfToken: GlobalVariables.csrfToken,
'username': $input.val(), username: $input.val(),
'user_id': $input.parents().eq(2).find('#user-id').val() user_id: $input.parents().eq(2).find('#user-id').val()
}; };
$.post(postUrl, postData, function(response) { $.post(postUrl, postData, function(response) {
if (!GeneralFunctions.handleAjaxExceptions(response)) return; if (!GeneralFunctions.handleAjaxExceptions(response)) {
return;
}
if (response == false) { if (response == false) {
$input.css('border', '2px solid red'); $input.css('border', '2px solid red');
Backend.displayNotification(EALang['username_already_exists']); Backend.displayNotification(EALang['username_already_exists']);
@ -205,229 +216,5 @@ var BackendSettings = {
}, 'json').fail(GeneralFunctions.ajaxFailureHandler); }, 'json').fail(GeneralFunctions.ajaxFailureHandler);
}); });
} }
};
/** })(window.BackendSettings);
* "System Settings" Tab Helper
* @class SystemSettings
*/
var SystemSettings = function() {};
/**
* Save the system settings. This method is run after changes are detected on the
* tab input fields.
*
* @param {array} settings Contains the system settings data.
*/
SystemSettings.prototype.save = function(settings) {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_settings';
var postData = {
'csrfToken': GlobalVariables.csrfToken,
'settings': JSON.stringify(settings),
'type': BackendSettings.SETTINGS_SYSTEM
};
$.post(postUrl, postData, function(response) {
if (!GeneralFunctions.handleAjaxExceptions(response)) return;
Backend.displayNotification(EALang['settings_saved']);
// Update the logo title on the header.
$('#header-logo span').text($('#company-name').val());
// We need to refresh the working plan.
var workingPlan = BackendSettings.wp.get();
$('.breaks').empty();
BackendSettings.wp.setup(workingPlan);
BackendSettings.wp.timepickers(false);
}, 'json').fail(GeneralFunctions.ajaxFailureHandler);
};
/**
* Prepare the system settings array. This method uses the DOM elements of the
* backend/settings page, so it can't be used in another page.
*
* @returns {array} Returns the system settings array.
*/
SystemSettings.prototype.get = function() {
var settings = [];
// General Settings Tab
$('#general').find('input, select').each(function() {
settings.push({
'name': $(this).attr('data-field'),
'value': $(this).val()
});
});
settings.push({
'name': 'customer_notifications',
'value': $('#customer-notifications').hasClass('active') === true ? '1' : '0'
});
settings.push({
'name': 'require_captcha',
'value': $('#require-captcha').hasClass('active') === true ? '1' : '0'
});
// Business Logic Tab
settings.push({
'name': 'company_working_plan',
'value': JSON.stringify(BackendSettings.wp.get())
});
settings.push({
'name': 'book_advance_timeout',
'value': $('#book-advance-timeout').val()
});
return settings;
};
/**
* Validate the settings data. If the validation fails then display a
* message to the user.
*
* @returns {bool} Returns the validation result.
*/
SystemSettings.prototype.validate = function() {
$('#general .required').css('border', '');
try {
// Validate required fields.
var missingRequired = false;
$('#general .required').each(function() {
if ($(this).val() == '' || $(this).val() == undefined) {
$(this).css('border', '2px solid red');
missingRequired = true;
}
});
if (missingRequired) {
throw EALang['fields_are_required'];
}
// Validate company email address.
if (!GeneralFunctions.validateEmail($('#company-email').val())) {
$('#company-email').css('border', '2px solid red');
throw EALang['invalid_email'];
}
return true;
} catch(exc) {
Backend.displayNotification(exc);
return false;
}
};
/**
* "User Settings" Tab Helper
* @class UserSettings
*/
var UserSettings = function() {};
/**
* Get the settings data for the user settings.
*
* @returns {object} Returns the user settings array.
*/
UserSettings.prototype.get = function() {
var user = {
'id': $('#user-id').val(),
'first_name': $('#first-name').val(),
'last_name': $('#last-name').val(),
'email': $('#email').val(),
'mobile_number': $('#mobile-number').val(),
'phone_number': $('#phone-number').val(),
'address': $('#address').val(),
'city': $('#city').val(),
'state': $('#state').val(),
'zip_code': $('#zip-code').val(),
'notes': $('#notes').val(),
'settings': {
'username': $('#username').val(),
'notifications': $('#user-notifications').hasClass('active')
}
};
if ($('#password').val() != '') {
user.settings.password = $('#password').val();
}
return user;
};
/**
* Store the user settings into the database.
*
* @param {array} settings Contains the user settings.
*/
UserSettings.prototype.save = function(settings) {
if (!BackendSettings.settings.validate(settings)) {
Backend.displayNotification(EALang['user_settings_are_invalid']);
return; // Validation failed, do not procceed.
}
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_settings';
var postData = {
'csrfToken': GlobalVariables.csrfToken,
'type': BackendSettings.SETTINGS_USER,
'settings': JSON.stringify(settings)
};
$.post(postUrl, postData, function(response) {
if (!GeneralFunctions.handleAjaxExceptions(response)) return;
Backend.displayNotification(EALang['settings_saved']);
// Update footer greetings.
$('#footer-user-display-name').text('Hello, ' + $('#first-name').val() + ' ' + $('#last-name').val() + '!');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler);
};
/**
* Validate the settings data. If the validation fails then display a
* message to the user.
*
* @returns {bool} Returns the validation result.
*/
UserSettings.prototype.validate = function() {
$('#user .required').css('border', '');
$('#user').find('#password, #retype-password').css('border', '');
try {
// Validate required fields.
var missingRequired = false;
$('#user .required').each(function() {
if ($(this).val() == '' || $(this).val() == undefined) {
$(this).css('border', '2px solid red');
missingRequired = true;
}
});
if (missingRequired) {
throw EALang['fields_are_required'];
}
// Validate passwords (if provided).
if ($('#password').val() != $('#retype-password').val()) {
$('#password, #retype-password').css('border', '2px solid red');
throw EALang['passwords_mismatch'];
}
// Validate user email.
if (!GeneralFunctions.validateEmail($('#email').val())) {
$('#email').css('border', '2px solid red');
throw EALang['invalid_email'];
}
if ($('#username').attr('already-exists') === 'true') {
$('#username').css('border', '2px solid red');
throw EALang['username_already_exists'];
}
return true;
} catch(exc) {
Backend.displayNotification(exc);
return false;
}
};

View file

@ -0,0 +1,132 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Open Source Web Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) 2013 - 2016, Alex Tselegidis
* @license http://opensource.org/licenses/GPL-3.0 - GPLv3
* @link http://easyappointments.org
* @since v1.0.0
* ---------------------------------------------------------------------------- */
(function() {
'use strict';
/**
* "System Settings" Tab Helper
* @class SystemSettings
*/
var SystemSettings = function() {};
/**
* Save the system settings. This method is run after changes are detected on the
* tab input fields.
*
* @param {array} settings Contains the system settings data.
*/
SystemSettings.prototype.save = function(settings) {
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_settings',
postData = {
csrfToken: GlobalVariables.csrfToken,
settings: JSON.stringify(settings),
type: BackendSettings.SETTINGS_SYSTEM
};
$.post(postUrl, postData, function(response) {
if (!GeneralFunctions.handleAjaxExceptions(response)) {
return;
}
Backend.displayNotification(EALang['settings_saved']);
// Update the logo title on the header.
$('#header-logo span').text($('#company-name').val());
// We need to refresh the working plan.
var workingPlan = BackendSettings.wp.get();
$('.breaks').empty();
BackendSettings.wp.setup(workingPlan);
BackendSettings.wp.timepickers(false);
}, 'json').fail(GeneralFunctions.ajaxFailureHandler);
};
/**
* Prepare the system settings array. This method uses the DOM elements of the
* backend/settings page, so it can't be used in another page.
*
* @returns {array} Returns the system settings array.
*/
SystemSettings.prototype.get = function() {
var settings = [];
// General Settings Tab
$('#general').find('input, select').each(function() {
settings.push({
name: $(this).attr('data-field'),
value: $(this).val()
});
});
settings.push({
name: 'customer_notifications',
value: $('#customer-notifications').hasClass('active') === true ? '1' : '0'
});
settings.push({
name: 'require_captcha',
value: $('#require-captcha').hasClass('active') === true ? '1' : '0'
});
// Business Logic Tab
settings.push({
name: 'company_working_plan',
value: JSON.stringify(BackendSettings.wp.get())
});
settings.push({
name: 'book_advance_timeout',
value: $('#book-advance-timeout').val()
});
return settings;
};
/**
* Validate the settings data. If the validation fails then display a
* message to the user.
*
* @returns {bool} Returns the validation result.
*/
SystemSettings.prototype.validate = function() {
$('#general .required').css('border', '');
try {
// Validate required fields.
var missingRequired = false;
$('#general .required').each(function() {
if ($(this).val() == '' || $(this).val() == undefined) {
$(this).css('border', '2px solid red');
missingRequired = true;
}
});
if (missingRequired) {
throw EALang['fields_are_required'];
}
// Validate company email address.
if (!GeneralFunctions.validateEmail($('#company-email').val())) {
$('#company-email').css('border', '2px solid red');
throw EALang['invalid_email'];
}
return true;
} catch(exc) {
Backend.displayNotification(exc);
return false;
}
};
window.SystemSettings = SystemSettings;
})();

View file

@ -0,0 +1,134 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Open Source Web Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) 2013 - 2016, Alex Tselegidis
* @license http://opensource.org/licenses/GPL-3.0 - GPLv3
* @link http://easyappointments.org
* @since v1.0.0
* ---------------------------------------------------------------------------- */
(function() {
'use strict';
/**
* "User Settings" Tab Helper
* @class UserSettings
*/
var UserSettings = function() {};
/**
* Get the settings data for the user settings.
*
* @returns {object} Returns the user settings array.
*/
UserSettings.prototype.get = function() {
var user = {
id: $('#user-id').val(),
first_name: $('#first-name').val(),
last_name: $('#last-name').val(),
email: $('#email').val(),
mobile_number: $('#mobile-number').val(),
phone_number: $('#phone-number').val(),
address: $('#address').val(),
city: $('#city').val(),
state: $('#state').val(),
zip_code: $('#zip-code').val(),
notes: $('#notes').val(),
settings: {
username: $('#username').val(),
notifications: $('#user-notifications').hasClass('active')
}
};
if ($('#password').val() != '') {
user.settings.password = $('#password').val();
}
return user;
};
/**
* Store the user settings into the database.
*
* @param {array} settings Contains the user settings.
*/
UserSettings.prototype.save = function(settings) {
if (!this.validate(settings)) {
Backend.displayNotification(EALang['user_settings_are_invalid']);
return; // Validation failed, do not procceed.
}
var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_settings',
postData = {
csrfToken: GlobalVariables.csrfToken,
type: BackendSettings.SETTINGS_USER,
settings: JSON.stringify(settings)
};
$.post(postUrl, postData, function(response) {
if (!GeneralFunctions.handleAjaxExceptions(response)) {
return;
}
Backend.displayNotification(EALang['settings_saved']);
// Update footer greetings.
$('#footer-user-display-name').text('Hello, ' + $('#first-name').val() + ' ' + $('#last-name').val() + '!');
}, 'json').fail(GeneralFunctions.ajaxFailureHandler);
};
/**
* Validate the settings data. If the validation fails then display a
* message to the user.
*
* @returns {bool} Returns the validation result.
*/
UserSettings.prototype.validate = function() {
$('#user .required').css('border', '');
$('#user').find('#password, #retype-password').css('border', '');
try {
// Validate required fields.
var missingRequired = false;
$('#user .required').each(function() {
if ($(this).val() == '' || $(this).val() == undefined) {
$(this).css('border', '2px solid red');
missingRequired = true;
}
});
if (missingRequired) {
throw EALang['fields_are_required'];
}
// Validate passwords (if provided).
if ($('#password').val() != $('#retype-password').val()) {
$('#password, #retype-password').css('border', '2px solid red');
throw EALang['passwords_mismatch'];
}
// Validate user email.
if (!GeneralFunctions.validateEmail($('#email').val())) {
$('#email').css('border', '2px solid red');
throw EALang['invalid_email'];
}
if ($('#username').attr('already-exists') === 'true') {
$('#username').css('border', '2px solid red');
throw EALang['username_already_exists'];
}
return true;
} catch(exc) {
Backend.displayNotification(exc);
return false;
}
};
window.UserSettings = UserSettings;
})();