first commit
Some checks failed
CI / build-test (push) Has been cancelled

This commit is contained in:
2025-05-31 18:56:37 +02:00
commit 8c4798a5fd
1240 changed files with 190468 additions and 0 deletions

198
assets/js/pages/account.js Normal file
View File

@ -0,0 +1,198 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Account page.
*
* This module implements the functionality of the account page.
*/
App.Pages.Account = (function () {
const $userId = $('#user-id');
const $firstName = $('#first-name');
const $lastName = $('#last-name');
const $email = $('#email');
const $mobileNumber = $('#mobile-number');
const $phoneNumber = $('#phone-number');
const $address = $('#address');
const $city = $('#city');
const $state = $('#state');
const $zipCode = $('#zip-code');
const $notes = $('#notes');
const $language = $('#language');
const $timezone = $('#timezone');
const $username = $('#username');
const $password = $('#password');
const $retypePassword = $('#retype-password');
const $calendarView = $('#calendar-view');
const notifications = $('#notifications');
const $saveSettings = $('#save-settings');
const $footerUserDisplayName = $('#footer-user-display-name');
/**
* Check if the form has invalid values.
*
* @return {Boolean}
*/
function isInvalid() {
try {
$('#account .is-invalid').removeClass('is-invalid');
// Validate required fields.
let missingRequiredFields = false;
$('#account .required').each((index, requiredField) => {
const $requiredField = $(requiredField);
if (!$requiredField.val()) {
$requiredField.addClass('is-invalid');
missingRequiredFields = true;
}
});
if (missingRequiredFields) {
throw new Error(lang('fields_are_required'));
}
// Validate passwords (if values provided).
if ($password.val() && $password.val() !== $retypePassword.val()) {
$password.addClass('is-invalid');
$retypePassword.addClass('is-invalid');
throw new Error(lang('passwords_mismatch'));
}
// Validate user email.
const emailValue = $email.val();
if (!App.Utils.Validation.email(emailValue)) {
$email.addClass('is-invalid');
throw new Error(lang('invalid_email'));
}
if ($username.hasClass('is-invalid')) {
throw new Error(lang('username_already_exists'));
}
return false;
} catch (error) {
App.Layouts.Backend.displayNotification(error.message);
return true;
}
}
/**
* Apply the account values to the form.
*
* @param {Object} account
*/
function deserialize(account) {
$userId.val(account.id);
$firstName.val(account.first_name);
$lastName.val(account.last_name);
$email.val(account.email);
$mobileNumber.val(account.mobile_number);
$phoneNumber.val(account.phone_number);
$address.val(account.address);
$city.val(account.city);
$state.val(account.state);
$zipCode.val(account.zip_code);
$notes.val(account.notes);
$language.val(account.language);
$timezone.val(account.timezone);
$username.val(account.settings.username);
$password.val('');
$retypePassword.val('');
$calendarView.val(account.settings.calendar_view);
notifications.prop('checked', Boolean(Number(account.settings.notifications)));
}
/**
* Get the account information from the form.
*
* @return {Object}
*/
function serialize() {
return {
id: $userId.val(),
first_name: $firstName.val(),
last_name: $lastName.val(),
email: $email.val(),
mobile_number: $mobileNumber.val(),
phone_number: $phoneNumber.val(),
address: $address.val(),
city: $city.val(),
state: $state.val(),
zip_code: $zipCode.val(),
notes: $notes.val(),
language: $language.val(),
timezone: $timezone.val(),
settings: {
username: $username.val(),
password: $password.val() || undefined,
calendar_view: $calendarView.val(),
notifications: Number(notifications.prop('checked')),
},
};
}
/**
* Save the account information.
*/
function onSaveSettingsClick() {
if (isInvalid()) {
App.Layouts.Backend.displayNotification(lang('user_settings_are_invalid'));
return;
}
const account = serialize();
App.Http.Account.save(account).done(() => {
App.Layouts.Backend.displayNotification(lang('settings_saved'));
$footerUserDisplayName.text('Hello, ' + $firstName.val() + ' ' + $lastName.val() + '!');
});
}
/**
* Make sure the username is unique.
*/
function onUsernameChange() {
const username = $username.val();
App.Http.Account.validateUsername(vars('user_id'), username).done((response) => {
const isValid = response.is_valid;
$username.toggleClass('is-invalid', !isValid);
if (!isValid) {
App.Layouts.Backend.displayNotification(lang('username_already_exists'));
}
});
}
/**
* Initialize the page.
*/
function initialize() {
const account = vars('account');
deserialize(account);
$saveSettings.on('click', onSaveSettingsClick);
$username.on('change', onUsernameChange);
}
document.addEventListener('DOMContentLoaded', initialize);
return {};
})();

496
assets/js/pages/admins.js Normal file
View File

@ -0,0 +1,496 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Admins page.
*
* This module implements the functionality of admins page.
*/
App.Pages.Admins = (function () {
const $admins = $('#admins');
const $id = $('#id');
const $firstName = $('#first-name');
const $lastName = $('#last-name');
const $email = $('#email');
const $mobileNumber = $('#mobile-number');
const $phoneNumber = $('#phone-number');
const $address = $('#address');
const $city = $('#city');
const $state = $('#state');
const $zipCode = $('#zip-code');
const $notes = $('#notes');
const $language = $('#language');
const $timezone = $('#timezone');
const $ldapDn = $('#ldap-dn');
const $username = $('#username');
const $password = $('#password');
const $passwordConfirmation = $('#password-confirm');
const $notifications = $('#notifications');
const $calendarView = $('#calendar-view');
const $filterAdmins = $('#filter-admins');
let filterResults = {};
let filterLimit = 20;
/**
* Add the page event listeners.
*/
function addEventListeners() {
/**
* Event: Admin Username "Blur"
*
* When the admin leaves the username input field we will need to check if the username
* is not taken by another record in the system.
*
* @param {jQuery.Event} event
*/
$admins.on('blur', '#username', (event) => {
const $input = $(event.currentTarget);
if ($input.prop('readonly') === true || $input.val() === '') {
return;
}
const adminId = $input.parents().eq(2).find('.record-id').val();
if (!adminId) {
return;
}
const username = $input.val();
App.Http.Account.validateUsername(adminId, username).done((response) => {
if (response.is_valid === 'false') {
$input.addClass('is-invalid');
$input.attr('already-exists', 'true');
$input.parents().eq(3).find('.form-message').text(lang('username_already_exists'));
$input.parents().eq(3).find('.form-message').show();
} else {
$input.removeClass('is-invalid');
$input.attr('already-exists', 'false');
if ($input.parents().eq(3).find('.form-message').text() === lang('username_already_exists')) {
$input.parents().eq(3).find('.form-message').hide();
}
}
});
});
/**
* Event: Filter Admins Form "Submit"
*
* Filter the admin records with the given key string.
*
* @param {jQuery.Event} event
*/
$admins.on('submit', '#filter-admins form', (event) => {
event.preventDefault();
const key = $('#filter-admins .key').val();
$('#filter-admins .selected').removeClass('selected');
App.Pages.Admins.resetForm();
App.Pages.Admins.filter(key);
});
/**
* Event: Filter Admin Row "Click"
*
* Display the selected admin data to the user.
*/
$admins.on('click', '.admin-row', (event) => {
if ($('#filter-admins .filter').prop('disabled')) {
$('#filter-admins .results').css('color', '#AAA');
return; // exit because we are currently on edit mode
}
const adminId = $(event.currentTarget).attr('data-id');
const admin = filterResults.find((filterResult) => Number(filterResult.id) === Number(adminId));
App.Pages.Admins.display(admin);
$('#filter-admins .selected').removeClass('selected');
$(event.currentTarget).addClass('selected');
$('#edit-admin, #delete-admin').prop('disabled', false);
});
/**
* Event: Add New Admin Button "Click"
*/
$admins.on('click', '#add-admin', () => {
App.Pages.Admins.resetForm();
$admins.find('.add-edit-delete-group').hide();
$admins.find('.save-cancel-group').show();
$admins.find('.record-details').find('input, select, textarea').prop('disabled', false);
$admins.find('.record-details .form-label span').prop('hidden', false);
$('#password, #password-confirm').addClass('required');
$('#filter-admins button').prop('disabled', true);
$('#filter-admins .results').css('color', '#AAA');
});
/**
* Event: Edit Admin Button "Click"
*/
$admins.on('click', '#edit-admin', () => {
$admins.find('.add-edit-delete-group').hide();
$admins.find('.save-cancel-group').show();
$admins.find('.record-details').find('input, select, textarea').prop('disabled', false);
$admins.find('.record-details .form-label span').prop('hidden', false);
$('#password, #password-confirm').removeClass('required');
$('#filter-admins button').prop('disabled', true);
$('#filter-admins .results').css('color', '#AAA');
});
/**
* Event: Delete Admin Button "Click"
*/
$admins.on('click', '#delete-admin', () => {
const adminId = $id.val();
const buttons = [
{
text: lang('cancel'),
click: (event, messageModal) => {
messageModal.hide();
},
},
{
text: lang('delete'),
click: (event, messageModal) => {
App.Pages.Admins.remove(adminId);
messageModal.hide();
},
},
];
App.Utils.Message.show(lang('delete_admin'), lang('delete_record_prompt'), buttons);
});
/**
* Event: Save Admin Button "Click"
*/
$admins.on('click', '#save-admin', () => {
const admin = {
first_name: $firstName.val(),
last_name: $lastName.val(),
email: $email.val(),
mobile_number: $mobileNumber.val(),
phone_number: $phoneNumber.val(),
address: $address.val(),
city: $city.val(),
state: $state.val(),
zip_code: $zipCode.val(),
notes: $notes.val(),
language: $language.val(),
timezone: $timezone.val(),
ldap_dn: $ldapDn.val(),
settings: {
username: $username.val(),
notifications: Number($notifications.prop('checked')),
calendar_view: $calendarView.val(),
},
};
// Include password if changed.
if ($password.val() !== '') {
admin.settings.password = $password.val();
}
// Include id if changed.
if ($id.val() !== '') {
admin.id = $id.val();
}
if (!App.Pages.Admins.validate()) {
return;
}
App.Pages.Admins.save(admin);
});
/**
* Event: Cancel Admin Button "Click"
*
* Cancel add or edit of an admin record.
*/
$admins.on('click', '#cancel-admin', () => {
const id = $id.val();
App.Pages.Admins.resetForm();
if (id) {
App.Pages.Admins.select(id, true);
}
});
}
/**
* Save admin record to database.
*
* @param {Object} admin Contains the admin record data. If an 'id' value is provided
* then the update operation is going to be executed.
*/
function save(admin) {
App.Http.Admins.save(admin).then((response) => {
App.Layouts.Backend.displayNotification(lang('admin_saved'));
App.Pages.Admins.resetForm();
$('#filter-admins .key').val('');
App.Pages.Admins.filter('', response.id, true);
});
}
/**
* Delete an admin record from database.
*
* @param {Number} id Record id to be deleted.
*/
function remove(id) {
App.Http.Admins.destroy(id).then(() => {
App.Layouts.Backend.displayNotification(lang('admin_deleted'));
App.Pages.Admins.resetForm();
App.Pages.Admins.filter($('#filter-admins .key').val());
});
}
/**
* Validates an admin record.
*
* @return {Boolean} Returns the validation result.
*/
function validate() {
$admins.find('.is-invalid').removeClass('is-invalid');
try {
// Validate required fields.
let missingRequired = false;
$admins.find('.required').each((index, requiredField) => {
if (!$(requiredField).val()) {
$(requiredField).addClass('is-invalid');
missingRequired = true;
}
});
if (missingRequired) {
throw new Error('Fields with * are required.');
}
// Validate passwords.
if ($password.val() !== $passwordConfirmation.val()) {
$('#password, #password-confirm').addClass('is-invalid');
throw new Error(lang('passwords_mismatch'));
}
if ($password.val().length < vars('min_password_length') && $password.val() !== '') {
$('#password, #password-confirm').addClass('is-invalid');
throw new Error(lang('password_length_notice').replace('$number', vars('min_password_length')));
}
// Validate user email.
if (!App.Utils.Validation.email($email.val())) {
$email.addClass('is-invalid');
throw new Error(lang('invalid_email'));
}
// Validate phone number.
const phoneNumber = $phoneNumber.val();
if (phoneNumber && !App.Utils.Validation.phone(phoneNumber)) {
$phoneNumber.addClass('is-invalid');
throw new Error(lang('invalid_phone'));
}
// Validate mobile number.
const mobileNumber = $mobileNumber.val();
if (mobileNumber && !App.Utils.Validation.phone(mobileNumber)) {
$mobileNumber.addClass('is-invalid');
throw new Error(lang('invalid_phone'));
}
// Check if username exists
if ($username.attr('already-exists') === 'true') {
$username.addClass('is-invalid');
throw new Error(lang('username_already_exists'));
}
return true;
} catch (error) {
$admins.find('.form-message').addClass('alert-danger').text(error.message).show();
return false;
}
}
/**
* Resets the admin form back to its initial state.
*/
function resetForm() {
$('#filter-admins .selected').removeClass('selected');
$('#filter-admins button').prop('disabled', false);
$('#filter-admins .results').css('color', '');
$admins.find('.add-edit-delete-group').show();
$admins.find('.save-cancel-group').hide();
$admins.find('.record-details').find('input, select, textarea').val('').prop('disabled', true);
$admins.find('.record-details .form-label span').prop('hidden', true);
$admins.find('.record-details #calendar-view').val('default');
$admins.find('.record-details #language').val(vars('default_language'));
$admins.find('.record-details #timezone').val(vars('default_timezone'));
$admins.find('.record-details #notifications').prop('checked', true);
$('#edit-admin, #delete-admin').prop('disabled', true);
$('#admins .is-invalid').removeClass('is-invalid');
$('#admins .form-message').hide();
}
/**
* Display a admin record into the admin form.
*
* @param {Object} admin Contains the admin record data.
*/
function display(admin) {
$id.val(admin.id);
$firstName.val(admin.first_name);
$lastName.val(admin.last_name);
$email.val(admin.email);
$mobileNumber.val(admin.mobile_number);
$phoneNumber.val(admin.phone_number);
$address.val(admin.address);
$city.val(admin.city);
$state.val(admin.state);
$zipCode.val(admin.zip_code);
$notes.val(admin.notes);
$language.val(admin.language);
$timezone.val(admin.timezone);
$ldapDn.val(admin.ldap_dn);
$username.val(admin.settings.username);
$calendarView.val(admin.settings.calendar_view);
$notifications.prop('checked', Boolean(Number(admin.settings.notifications)));
}
/**
* Filters admin records by a keyword string.
*
* @param {String} keyword This string is used to filter the admin records of the database.
* @param {Number} [selectId] (OPTIONAL = undefined) This record id will be selected when
* the filter operation is finished.
* @param {Boolean} [show] (OPTIONAL = false) If true the selected record data are going
* to be displayed on the details column (requires a selected record though).
*/
function filter(keyword, selectId = null, show = false) {
App.Http.Admins.search(keyword, filterLimit).then((response) => {
filterResults = response;
$filterAdmins.find('.results').empty();
response.forEach((admin) => {
$filterAdmins.find('.results').append(App.Pages.Admins.getFilterHtml(admin)).append($('<hr/>'));
});
if (!response.length) {
$filterAdmins.find('.results').append(
$('<em/>', {
'text': lang('no_records_found'),
}),
);
} else if (response.length === filterLimit) {
$('<button/>', {
'type': 'button',
'class': 'btn btn-outline-secondary w-100 load-more text-center',
'text': lang('load_more'),
'click': () => {
filterLimit += 20;
App.Pages.Admins.filter(keyword, selectId, show);
},
}).appendTo('#filter-admins .results');
}
if (selectId) {
App.Pages.Admins.select(selectId, show);
}
});
}
/**
* Get an admin row html code that is going to be displayed on the filter results list.
*
* @param {Object} admin Contains the admin record data.
*
* @return {String} The html code that represents the record on the filter results list.
*/
function getFilterHtml(admin) {
const name = admin.first_name + ' ' + admin.last_name;
let info = admin.email;
info = admin.mobile_number ? info + ', ' + admin.mobile_number : info;
info = admin.phone_number ? info + ', ' + admin.phone_number : info;
return $('<div/>', {
'class': 'admin-row entry',
'data-id': admin.id,
'html': [
$('<strong/>', {
'text': name,
}),
$('<br/>'),
$('<small/>', {
'class': 'text-muted',
'text': info,
}),
$('<br/>'),
],
});
}
/**
* Select a specific record from the current filter results. If the admin id does not exist
* in the list then no record will be selected.
*
* @param {Number} id The record id to be selected from the filter results.
* @param {Boolean} show Optional (false), if true then the method will display the record
* on the form.
*/
function select(id, show = false) {
$filterAdmins.find('.selected').removeClass('selected');
$filterAdmins.find('.admin-row[data-id="' + id + '"]').addClass('selected');
if (show) {
const admin = filterResults.find((filterResult) => Number(filterResult.id) === Number(id));
App.Pages.Admins.display(admin);
$('#edit-admin, #delete-admin').prop('disabled', false);
}
}
/**
* Initialize the module.
*/
function initialize() {
App.Pages.Admins.resetForm();
App.Pages.Admins.filter('');
App.Pages.Admins.addEventListeners();
}
document.addEventListener('DOMContentLoaded', initialize);
return {
filter,
save,
remove,
validate,
getFilterHtml,
resetForm,
display,
select,
addEventListeners,
};
})();

View File

@ -0,0 +1,109 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* API settings page.
*
* This module implements the functionality of the API settings page.
*/
App.Pages.ApiSettings = (function () {
const $saveSettings = $('#save-settings');
/**
* Check if the form has invalid values.
*
* @return {Boolean}
*/
function isInvalid() {
try {
$('#api-settings .is-invalid').removeClass('is-invalid');
// Validate required fields.
let missingRequiredFields = false;
$('#api-settings .required').each((index, requiredField) => {
const $requiredField = $(requiredField);
if (!$requiredField.val()) {
$requiredField.addClass('is-invalid');
missingRequiredFields = true;
}
});
if (missingRequiredFields) {
throw new Error(lang('fields_are_required'));
}
return false;
} catch (error) {
App.Layouts.Backend.displayNotification(error.message);
return true;
}
}
function deserialize(apiSettings) {
apiSettings.forEach((apiSetting) => {
const $field = $('[data-field="' + apiSetting.name + '"]');
$field.is(':checkbox')
? $field.prop('checked', Boolean(Number(apiSetting.value)))
: $field.val(apiSetting.value);
});
}
function serialize() {
const apiSettings = [];
$('[data-field]').each((index, field) => {
const $field = $(field);
apiSettings.push({
name: $field.data('field'),
value: $field.is(':checkbox') ? Number($field.prop('checked')) : $field.val(),
});
});
return apiSettings;
}
/**
* Save the account information.
*/
function onSaveSettingsClick() {
if (isInvalid()) {
App.Layouts.Backend.displayNotification(lang('settings_are_invalid'));
return;
}
const apiSettings = serialize();
App.Http.ApiSettings.save(apiSettings).done(() => {
App.Layouts.Backend.displayNotification(lang('settings_saved'));
});
}
/**
* Initialize the module.
*/
function initialize() {
$saveSettings.on('click', onSaveSettingsClick);
const apiSettings = vars('api_settings');
deserialize(apiSettings);
}
document.addEventListener('DOMContentLoaded', initialize);
return {};
})();

View File

@ -0,0 +1,395 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Blocked-periods page.
*
* This module implements the functionality of the blocked-periods page.
*/
App.Pages.BlockedPeriods = (function () {
const $blockedPeriods = $('#blocked-periods');
const $filterBlockedPeriods = $('#filter-blocked-periods');
const $id = $('#id');
const $name = $('#name');
const $startDateTime = $('#start-date-time');
const $endDateTime = $('#end-date-time');
const $notes = $('#notes');
const moment = window.moment;
let filterResults = {};
let filterLimit = 20;
let backupStartDateTimeObject = undefined;
/**
* Add the page event listeners.
*/
function addEventListeners() {
/**
* Event: Filter Blocked Periods Form "Submit"
*
* @param {jQuery.Event} event
*/
$blockedPeriods.on('submit', '#filter-blocked-periods form', (event) => {
event.preventDefault();
const key = $('#filter-blocked-periods .key').val();
$('.selected').removeClass('selected');
App.Pages.BlockedPeriods.resetForm();
App.Pages.BlockedPeriods.filter(key);
});
/**
* Event: Filter Blocked-Periods Row "Click"
*
* Displays the selected row data on the right side of the page.
*
* @param {jQuery.Event} event
*/
$blockedPeriods.on('click', '.blocked-period-row', (event) => {
if ($('#filter-blocked-periods .filter').prop('disabled')) {
$('#filter-blocked-periods .results').css('color', '#AAA');
return; // exit because we are on edit mode
}
const blockedPeriodId = $(event.currentTarget).attr('data-id');
const blockedPeriod = filterResults.find(
(filterResult) => Number(filterResult.id) === Number(blockedPeriodId),
);
App.Pages.BlockedPeriods.display(blockedPeriod);
$('#filter-blocked-periods .selected').removeClass('selected');
$(event.currentTarget).addClass('selected');
$('#edit-blocked-period, #delete-blocked-period').prop('disabled', false);
});
/**
* Event: Add Blocked-Period Button "Click"
*/
$blockedPeriods.on('click', '#add-blocked-period', () => {
App.Pages.BlockedPeriods.resetForm();
$blockedPeriods.find('.add-edit-delete-group').hide();
$blockedPeriods.find('.save-cancel-group').show();
$blockedPeriods.find('.record-details').find('input, select, textarea').prop('disabled', false);
$blockedPeriods.find('.record-details .form-label span').prop('hidden', false);
$filterBlockedPeriods.find('button').prop('disabled', true);
$filterBlockedPeriods.find('.results').css('color', '#AAA');
App.Utils.UI.setDateTimePickerValue($startDateTime, moment('00:00', 'HH:mm').toDate());
App.Utils.UI.setDateTimePickerValue($endDateTime, moment('00:00', 'HH:mm').add(1, 'day').toDate());
});
/**
* Event: Edit Blocked-Period Button "Click"
*/
$blockedPeriods.on('click', '#edit-blocked-period', () => {
$blockedPeriods.find('.add-edit-delete-group').hide();
$blockedPeriods.find('.save-cancel-group').show();
$blockedPeriods.find('.record-details').find('input, select, textarea').prop('disabled', false);
$blockedPeriods.find('.record-details .form-label span').prop('hidden', false);
$filterBlockedPeriods.find('button').prop('disabled', true);
$filterBlockedPeriods.find('.results').css('color', '#AAA');
});
/**
* Event: Delete Blocked-Period Button "Click"
*/
$blockedPeriods.on('click', '#delete-blocked-period', () => {
const blockedPeriodId = $id.val();
const buttons = [
{
text: lang('cancel'),
click: (event, messageModal) => {
messageModal.hide();
},
},
{
text: lang('delete'),
click: (event, messageModal) => {
App.Pages.BlockedPeriods.remove(blockedPeriodId);
messageModal.hide();
},
},
];
App.Utils.Message.show(lang('delete_blocked_period'), lang('delete_record_prompt'), buttons);
});
/**
* Event: Blocked period Save Button "Click"
*/
$blockedPeriods.on('click', '#save-blocked-period', () => {
const startDateTimeObject = App.Utils.UI.getDateTimePickerValue($startDateTime);
const startDateTimeMoment = moment(startDateTimeObject);
const endDateTimeObject = App.Utils.UI.getDateTimePickerValue($endDateTime);
const endDateTimeMoment = moment(endDateTimeObject);
const blockedPeriod = {
name: $name.val(),
start_datetime: startDateTimeMoment.format('YYYY-MM-DD HH:mm:ss'),
end_datetime: endDateTimeMoment.format('YYYY-MM-DD HH:mm:ss'),
notes: $notes.val(),
};
if ($id.val() !== '') {
blockedPeriod.id = $id.val();
}
if (!App.Pages.BlockedPeriods.validate()) {
return;
}
App.Pages.BlockedPeriods.save(blockedPeriod);
});
/**
* Event: Cancel Blocked-Period Button "Click"
*/
$blockedPeriods.on('click', '#cancel-blocked-period', () => {
const id = $id.val();
App.Pages.BlockedPeriods.resetForm();
if (id !== '') {
App.Pages.BlockedPeriods.select(id, true);
}
});
$blockedPeriods.on('focus', '#start-date-time', () => {
backupStartDateTimeObject = App.Utils.UI.getDateTimePickerValue($startDateTime);
});
/**
* Event: Start Date Time Input "Change"
*/
$blockedPeriods.on('change', '#start-date-time', (event) => {
const endDateTimeObject = App.Utils.UI.getDateTimePickerValue($endDateTime);
if (!backupStartDateTimeObject || !endDateTimeObject) {
return;
}
const endDateTimeMoment = moment(endDateTimeObject);
const backupStartDateTimeMoment = moment(backupStartDateTimeObject);
const diff = endDateTimeMoment.diff(backupStartDateTimeMoment);
const newEndDateTimeMoment = endDateTimeMoment.clone().add(diff, 'milliseconds');
App.Utils.UI.setDateTimePickerValue($endDateTime, newEndDateTimeMoment.toDate());
});
}
/**
* Filter blocked periods records.
*
* @param {String} keyword This key string is used to filter the blocked-period records.
* @param {Number} selectId Optional, if set then after the filter operation the record with the given ID will be
* selected (but not displayed).
* @param {Boolean} show Optional (false), if true then the selected record will be displayed on the form.
*/
function filter(keyword, selectId = null, show = false) {
App.Http.BlockedPeriods.search(keyword, filterLimit).then((response) => {
filterResults = response;
$('#filter-blocked-periods .results').empty();
response.forEach((blockedPeriod) => {
$('#filter-blocked-periods .results')
.append(App.Pages.BlockedPeriods.getFilterHtml(blockedPeriod))
.append($('<hr/>'));
});
if (response.length === 0) {
$('#filter-blocked-periods .results').append(
$('<em/>', {
'text': lang('no_records_found'),
}),
);
} else if (response.length === filterLimit) {
$('<button/>', {
'type': 'button',
'class': 'btn btn-outline-secondary w-100 load-more text-center',
'text': lang('load_more'),
'click': () => {
filterLimit += 20;
App.Pages.BlockedPeriods.filter(keyword, selectId, show);
},
}).appendTo('#filter-blocked-periods .results');
}
if (selectId) {
App.Pages.BlockedPeriods.select(selectId, show);
}
});
}
/**
* Save a blocked-period record to the database (via AJAX post).
*
* @param {Object} blockedPeriod Contains the blocked-period data.
*/
function save(blockedPeriod) {
App.Http.BlockedPeriods.save(blockedPeriod).then((response) => {
App.Layouts.Backend.displayNotification(lang('blocked_period_saved'));
App.Pages.BlockedPeriods.resetForm();
$filterBlockedPeriods.find('.key').val('');
App.Pages.BlockedPeriods.filter('', response.id, true);
});
}
/**
* Delete blocked-period record.
*
* @param {Number} id Record ID to be deleted.
*/
function remove(id) {
App.Http.BlockedPeriods.destroy(id).then(() => {
App.Layouts.Backend.displayNotification(lang('blocked_period_deleted'));
App.Pages.BlockedPeriods.resetForm();
App.Pages.BlockedPeriods.filter($('#filter-blocked-periods .key').val());
});
}
/**
* Display a blocked-period record on the form.
*
* @param {Object} blockedPeriod Contains the blocked-period data.
*/
function display(blockedPeriod) {
$id.val(blockedPeriod.id);
$name.val(blockedPeriod.name);
App.Utils.UI.setDateTimePickerValue($startDateTime, new Date(blockedPeriod.start_datetime));
App.Utils.UI.setDateTimePickerValue($endDateTime, new Date(blockedPeriod.end_datetime));
$notes.val(blockedPeriod.notes);
}
/**
* Validate blocked-period data before save (insert or update).
*
* @return {Boolean} Returns the validation result.
*/
function validate() {
$blockedPeriods.find('.is-invalid').removeClass('is-invalid');
$blockedPeriods.find('.form-message').removeClass('alert-danger').hide();
try {
let missingRequired = false;
$blockedPeriods.find('.required').each((index, fieldEl) => {
if (!$(fieldEl).val()) {
$(fieldEl).addClass('is-invalid');
missingRequired = true;
}
});
if (missingRequired) {
throw new Error(lang('fields_are_required'));
}
const startDateTimeObject = App.Utils.UI.getDateTimePickerValue($startDateTime);
const endDateTimeObject = App.Utils.UI.getDateTimePickerValue($endDateTime);
if (startDateTimeObject >= endDateTimeObject) {
$startDateTime.addClass('is-invalid');
$endDateTime.addClass('is-invalid');
throw new Error(lang('start_date_before_end_error'));
}
return true;
} catch (error) {
$blockedPeriods.find('.form-message').addClass('alert-danger').text(error.message).show();
return false;
}
}
/**
* Bring the blocked-period form back to its initial state.
*/
function resetForm() {
$filterBlockedPeriods.find('.selected').removeClass('selected');
$filterBlockedPeriods.find('button').prop('disabled', false);
$filterBlockedPeriods.find('.results').css('color', '');
$blockedPeriods.find('.add-edit-delete-group').show();
$blockedPeriods.find('.save-cancel-group').hide();
$blockedPeriods.find('.record-details').find('input, select, textarea').val('').prop('disabled', true);
$blockedPeriods.find('.record-details .form-label span').prop('hidden', true);
$('#edit-blocked-period, #delete-blocked-period').prop('disabled', true);
$blockedPeriods.find('.record-details .is-invalid').removeClass('is-invalid');
$blockedPeriods.find('.record-details .form-message').hide();
backupStartDateTimeObject = undefined;
}
/**
* Get the filter results row HTML code.
*
* @param {Object} blockedPeriod Contains the blocked-period data.
*
* @return {String} Returns the record HTML code.
*/
function getFilterHtml(blockedPeriod) {
return $('<div/>', {
'class': 'blocked-period-row entry',
'data-id': blockedPeriod.id,
'html': [
$('<strong/>', {
'text': blockedPeriod.name,
}),
$('<br/>'),
],
});
}
/**
* Select a specific record from the current filter results.
*
* If the blocked-period ID does not exist in the list then no record will be selected.
*
* @param {Number} id The record ID to be selected from the filter results.
* @param {Boolean} show Optional (false), if true then the method will display the record on the form.
*/
function select(id, show = false) {
$filterBlockedPeriods.find('.selected').removeClass('selected');
$filterBlockedPeriods.find('.blocked-period-row[data-id="' + id + '"]').addClass('selected');
if (show) {
const blockedPeriod = filterResults.find((blockedPeriod) => Number(blockedPeriod.id) === Number(id));
App.Pages.BlockedPeriods.display(blockedPeriod);
$('#edit-blocked-period, #delete-blocked-period').prop('disabled', false);
}
}
/**
* Initialize the module.
*/
function initialize() {
App.Pages.BlockedPeriods.resetForm();
App.Pages.BlockedPeriods.filter('');
App.Pages.BlockedPeriods.addEventListeners();
App.Utils.UI.initializeDateTimePicker($startDateTime);
App.Utils.UI.initializeDateTimePicker($endDateTime);
}
document.addEventListener('DOMContentLoaded', initialize);
return {
filter,
save,
remove,
validate,
getFilterHtml,
resetForm,
display,
select,
addEventListeners,
};
})();

974
assets/js/pages/booking.js Normal file
View File

@ -0,0 +1,974 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Booking page.
*
* This module implements the functionality of the booking page
*
* Old Name: FrontendBook
*/
App.Pages.Booking = (function () {
const $selectDate = $('#select-date');
const $selectService = $('#select-service');
const $selectProvider = $('#select-provider');
const $selectTimezone = $('#select-timezone');
const $firstName = $('#first-name');
const $lastName = $('#last-name');
const $email = $('#email');
const $phoneNumber = $('#phone-number');
const $address = $('#address');
const $city = $('#city');
const $zipCode = $('#zip-code');
const $notes = $('#notes');
const $captchaTitle = $('.captcha-title');
const $availableHours = $('#available-hours');
const $bookAppointmentSubmit = $('#book-appointment-submit');
const $deletePersonalInformation = $('#delete-personal-information');
const $customField1 = $('#custom-field-1');
const $customField2 = $('#custom-field-2');
const $customField3 = $('#custom-field-3');
const $customField4 = $('#custom-field-4');
const $customField5 = $('#custom-field-5');
const $displayBookingSelection = $('.display-booking-selection');
const tippy = window.tippy;
const moment = window.moment;
/**
* Determines the functionality of the page.
*
* @type {Boolean}
*/
let manageMode = vars('manage_mode') || false;
/**
* Detect the month step.
*
* @param previousDateTimeMoment
* @param nextDateTimeMoment
*
* @returns {Number}
*/
function detectDatepickerMonthChangeStep(previousDateTimeMoment, nextDateTimeMoment) {
return previousDateTimeMoment.isAfter(nextDateTimeMoment) ? -1 : 1;
}
/**
* Initialize the module.
*/
function initialize() {
if (Boolean(Number(vars('display_cookie_notice'))) && window?.cookieconsent) {
cookieconsent.initialise({
palette: {
popup: {
background: '#ffffffbd',
text: '#666666',
},
button: {
background: '#429a82',
text: '#ffffff',
},
},
content: {
message: lang('website_using_cookies_to_ensure_best_experience'),
dismiss: 'OK',
},
});
const $cookieNoticeLink = $('.cc-link');
$cookieNoticeLink.replaceWith(
$('<a/>', {
'data-bs-toggle': 'modal',
'data-bs-target': '#cookie-notice-modal',
'href': '#',
'class': 'cc-link',
'text': $cookieNoticeLink.text(),
}),
);
}
manageMode = vars('manage_mode');
// Initialize page's components (tooltips, date pickers etc).
tippy('[data-tippy-content]');
let monthTimeout;
App.Utils.UI.initializeDatePicker($selectDate, {
inline: true,
minDate: moment().subtract(1, 'day').set({hours: 23, minutes: 59, seconds: 59}).toDate(),
maxDate: moment().add(vars('future_booking_limit'), 'days').toDate(),
onChange: (selectedDates) => {
App.Http.Booking.getAvailableHours(moment(selectedDates[0]).format('YYYY-MM-DD'));
App.Pages.Booking.updateConfirmFrame();
},
onMonthChange: (selectedDates, dateStr, instance) => {
$selectDate.parent().fadeTo(400, 0.3); // Change opacity during loading
if (monthTimeout) {
clearTimeout(monthTimeout);
}
monthTimeout = setTimeout(() => {
const previousMoment = moment(instance.selectedDates[0]);
const displayedMonthMoment = moment(
instance.currentYearElement.value +
'-' +
String(Number(instance.monthsDropdownContainer.value) + 1).padStart(2, '0') +
'-01',
);
const monthChangeStep = detectDatepickerMonthChangeStep(previousMoment, displayedMonthMoment);
App.Http.Booking.getUnavailableDates(
$selectProvider.val(),
$selectService.val(),
displayedMonthMoment.format('YYYY-MM-DD'),
monthChangeStep,
);
}, 500);
},
onYearChange: (selectedDates, dateStr, instance) => {
setTimeout(() => {
const previousMoment = moment(instance.selectedDates[0]);
const displayedMonthMoment = moment(
instance.currentYearElement.value +
'-' +
(Number(instance.monthsDropdownContainer.value) + 1) +
'-01',
);
const monthChangeStep = detectDatepickerMonthChangeStep(previousMoment, displayedMonthMoment);
App.Http.Booking.getUnavailableDates(
$selectProvider.val(),
$selectService.val(),
displayedMonthMoment.format('YYYY-MM-DD'),
monthChangeStep,
);
}, 500);
},
});
App.Utils.UI.setDateTimePickerValue($selectDate, new Date());
const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const isTimezoneSupported = $selectTimezone.find(`option[value="${browserTimezone}"]`).length > 0;
$selectTimezone.val(isTimezoneSupported ? browserTimezone : 'UTC');
// Bind the event handlers (might not be necessary every time we use this class).
addEventListeners();
optimizeContactInfoDisplay();
const serviceOptionCount = $selectService.find('option').length;
if (serviceOptionCount === 2) {
$selectService.find('option[value=""]').remove();
const firstServiceId = $selectService.find('option:first').attr('value');
$selectService.val(firstServiceId).trigger('change');
}
// If the manage mode is true, the appointment data should be loaded by default.
if (manageMode) {
applyAppointmentData(vars('appointment_data'), vars('provider_data'), vars('customer_data'));
$('#wizard-frame-1')
.css({
'visibility': 'visible',
'display': 'none',
})
.fadeIn();
} else {
// Check if a specific service was selected (via URL parameter).
const selectedServiceId = App.Utils.Url.queryParam('service');
if (selectedServiceId && $selectService.find('option[value="' + selectedServiceId + '"]').length > 0) {
$selectService.val(selectedServiceId);
}
$selectService.trigger('change'); // Load the available hours.
// Check if a specific provider was selected.
const selectedProviderId = App.Utils.Url.queryParam('provider');
if (selectedProviderId && $selectProvider.find('option[value="' + selectedProviderId + '"]').length === 0) {
// Select a service of this provider in order to make the provider available in the select box.
for (const index in vars('available_providers')) {
const provider = vars('available_providers')[index];
if (Number(provider.id) === Number(selectedProviderId) && provider.services.length > 0) {
$selectService.val(provider.services[0]).trigger('change');
}
}
}
if (selectedProviderId && $selectProvider.find('option[value="' + selectedProviderId + '"]').length > 0) {
$selectProvider.val(selectedProviderId).trigger('change');
}
if (
(selectedServiceId && selectedProviderId) ||
(vars('available_services').length === 1 && vars('available_providers').length === 1)
) {
if (!selectedServiceId) {
$selectService.val(vars('available_services')[0].id).trigger('change');
}
if (!selectedProviderId) {
$selectProvider.val(vars('available_providers')[0].id).trigger('change');
}
$('.active-step').removeClass('active-step');
$('#step-2').addClass('active-step');
$('#wizard-frame-1').hide();
$('#wizard-frame-2').fadeIn();
$selectService.closest('.wizard-frame').find('.button-next').trigger('click');
$(document).find('.book-step:first').hide();
$(document).find('.button-back:first').css('visibility', 'hidden');
$(document)
.find('.book-step:not(:first)')
.each((index, bookStepEl) =>
$(bookStepEl)
.find('strong')
.text(index + 1),
);
} else {
$('#wizard-frame-1')
.css({
'visibility': 'visible',
'display': 'none',
})
.fadeIn();
}
prefillFromQueryParam('#first-name', 'first_name');
prefillFromQueryParam('#last-name', 'last_name');
prefillFromQueryParam('#email', 'email');
prefillFromQueryParam('#phone-number', 'phone');
prefillFromQueryParam('#address', 'address');
prefillFromQueryParam('#city', 'city');
prefillFromQueryParam('#zip-code', 'zip');
}
}
function prefillFromQueryParam(field, param) {
const $target = $(field);
if (!$target.length) {
return;
}
$target.val(App.Utils.Url.queryParam(param));
}
/**
* Remove empty columns and center elements if needed.
*/
function optimizeContactInfoDisplay() {
// If a column has only one control shown then move the control to the other column.
const $firstCol = $('#wizard-frame-3 .field-col:first');
const $firstColControls = $firstCol.find('.form-control');
const $secondCol = $('#wizard-frame-3 .field-col:last');
const $secondColControls = $secondCol.find('.form-control');
if ($firstColControls.length === 1 && $secondColControls.length > 1) {
$firstColControls.each((index, controlEl) => {
$(controlEl).parent().insertBefore($secondColControls.first().parent());
});
}
if ($secondColControls.length === 1 && $firstColControls.length > 1) {
$secondColControls.each((index, controlEl) => {
$(controlEl).parent().insertAfter($firstColControls.last().parent());
});
}
// Hide columns that do not have any controls displayed.
const $fieldCols = $(document).find('#wizard-frame-3 .field-col');
$fieldCols.each((index, fieldColEl) => {
const $fieldCol = $(fieldColEl);
if (!$fieldCol.find('.form-control').length) {
$fieldCol.hide();
}
});
}
/**
* Add the page event listeners.
*/
function addEventListeners() {
/**
* Event: Timezone "Changed"
*/
$selectTimezone.on('change', () => {
const date = App.Utils.UI.getDateTimePickerValue($selectDate);
if (!date) {
return;
}
App.Http.Booking.getAvailableHours(moment(date).format('YYYY-MM-DD'));
App.Pages.Booking.updateConfirmFrame();
});
/**
* Event: Selected Provider "Changed"
*
* Whenever the provider changes the available appointment date - time periods must be updated.
*/
$selectProvider.on('change', (event) => {
const $target = $(event.target);
const todayDateTimeObject = new Date();
const todayDateTimeMoment = moment(todayDateTimeObject);
App.Utils.UI.setDateTimePickerValue($selectDate, todayDateTimeObject);
App.Http.Booking.getUnavailableDates(
$target.val(),
$selectService.val(),
todayDateTimeMoment.format('YYYY-MM-DD'),
);
App.Pages.Booking.updateConfirmFrame();
});
/**
* Event: Selected Service "Changed"
*
* When the user clicks on a service, its available providers should
* become visible.
*/
$selectService.on('change', (event) => {
const $target = $(event.target);
const serviceId = $selectService.val();
$selectProvider.parent().prop('hidden', !Boolean(serviceId));
$selectProvider.empty();
$selectProvider.append(new Option(lang('please_select'), ''));
vars('available_providers').forEach((provider) => {
// If the current provider is able to provide the selected service, add him to the list box.
const canServeService =
provider.services.filter((providerServiceId) => Number(providerServiceId) === Number(serviceId))
.length > 0;
if (canServeService) {
$selectProvider.append(new Option(provider.first_name + ' ' + provider.last_name, provider.id));
}
});
const providerOptionCount = $selectProvider.find('option').length;
// Remove the "Please Select" option, if there is only one provider available
if (providerOptionCount === 2) {
$selectProvider.find('option[value=""]').remove();
}
// Add the "Any Provider" entry
if (providerOptionCount > 2 && Boolean(Number(vars('display_any_provider')))) {
$(new Option(lang('any_provider'), 'any-provider')).insertAfter($selectProvider.find('option:first'));
}
App.Http.Booking.getUnavailableDates(
$selectProvider.val(),
$target.val(),
moment(App.Utils.UI.getDateTimePickerValue($selectDate)).format('YYYY-MM-DD'),
);
App.Pages.Booking.updateConfirmFrame();
App.Pages.Booking.updateServiceDescription(serviceId);
});
/**
* Event: Next Step Button "Clicked"
*
* This handler is triggered every time the user pressed the "next" button on the book wizard.
* Some special tasks might be performed, depending on the current wizard step.
*/
$('.button-next').on('click', (event) => {
const $target = $(event.currentTarget);
// If we are on the first step and there is no provider selected do not continue with the next step.
if ($target.attr('data-step_index') === '1' && !$selectProvider.val()) {
return;
}
// If we are on the 2nd tab then the user should have an appointment hour selected.
if ($target.attr('data-step_index') === '2') {
if (!$('.selected-hour').length) {
if (!$('#select-hour-prompt').length) {
$('<div/>', {
'id': 'select-hour-prompt',
'class': 'text-danger mb-4',
'text': lang('appointment_hour_missing'),
}).prependTo('#available-hours');
}
return;
}
}
// If we are on the 3rd tab then we will need to validate the user's input before proceeding to the next
// step.
if ($target.attr('data-step_index') === '3') {
if (!App.Pages.Booking.validateCustomerForm()) {
return; // Validation failed, do not continue.
} else {
App.Pages.Booking.updateConfirmFrame();
}
}
// Display the next step tab (uses jquery animation effect).
const nextTabIndex = parseInt($target.attr('data-step_index')) + 1;
$target
.parents()
.eq(1)
.fadeOut(() => {
$('.active-step').removeClass('active-step');
$('#step-' + nextTabIndex).addClass('active-step');
$('#wizard-frame-' + nextTabIndex).fadeIn();
});
// Scroll to the top of the page. On a small screen, especially on a mobile device, this is very useful.
const scrollingElement = document.scrollingElement || document.body;
if (window.innerHeight < scrollingElement.scrollHeight) {
scrollingElement.scrollTop = 0;
}
});
/**
* Event: Back Step Button "Clicked"
*
* This handler is triggered every time the user pressed the "back" button on the
* book wizard.
*/
$('.button-back').on('click', (event) => {
const prevTabIndex = parseInt($(event.currentTarget).attr('data-step_index')) - 1;
$(event.currentTarget)
.parents()
.eq(1)
.fadeOut(() => {
$('.active-step').removeClass('active-step');
$('#step-' + prevTabIndex).addClass('active-step');
$('#wizard-frame-' + prevTabIndex).fadeIn();
});
});
/**
* Event: Available Hour "Click"
*
* Triggered whenever the user clicks on an available hour for his appointment.
*/
$availableHours.on('click', '.available-hour', (event) => {
$availableHours.find('.selected-hour').removeClass('selected-hour');
$(event.target).addClass('selected-hour');
App.Pages.Booking.updateConfirmFrame();
});
if (manageMode) {
/**
* Event: Cancel Appointment Button "Click"
*
* When the user clicks the "Cancel" button this form is going to be submitted. We need
* the user to confirm this action because once the appointment is cancelled, it will be
* deleted from the database.
*
* @param {jQuery.Event} event
*/
$('#cancel-appointment').on('click', () => {
const $cancelAppointmentForm = $('#cancel-appointment-form');
let $cancellationReason;
const buttons = [
{
text: lang('close'),
click: (event, messageModal) => {
messageModal.hide();
},
},
{
text: lang('confirm'),
click: () => {
if ($cancellationReason.val() === '') {
$cancellationReason.css('border', '2px solid #DC3545');
return;
}
$cancelAppointmentForm.find('#hidden-cancellation-reason').val($cancellationReason.val());
$cancelAppointmentForm.submit();
},
},
];
App.Utils.Message.show(
lang('cancel_appointment_title'),
lang('write_appointment_removal_reason'),
buttons,
);
$cancellationReason = $('<textarea/>', {
'class': 'form-control mt-2',
'id': 'cancellation-reason',
'rows': '3',
'css': {
'width': '100%',
},
}).appendTo('#message-modal .modal-body');
return false;
});
$deletePersonalInformation.on('click', () => {
const buttons = [
{
text: lang('cancel'),
click: (event, messageModal) => {
messageModal.hide();
},
},
{
text: lang('delete'),
click: () => {
App.Http.Booking.deletePersonalInformation(vars('customer_token'));
},
},
];
App.Utils.Message.show(
lang('delete_personal_information'),
lang('delete_personal_information_prompt'),
buttons,
);
});
}
/**
* Event: Book Appointment Form "Submit"
*
* Before the form is submitted to the server we need to make sure that in the meantime the selected appointment
* date/time wasn't reserved by another customer or event.
*
* @param {jQuery.Event} event
*/
$bookAppointmentSubmit.on('click', () => {
const $acceptToTermsAndConditions = $('#accept-to-terms-and-conditions');
$acceptToTermsAndConditions.removeClass('is-invalid');
if ($acceptToTermsAndConditions.length && !$acceptToTermsAndConditions.prop('checked')) {
$acceptToTermsAndConditions.addClass('is-invalid');
return;
}
const $acceptToPrivacyPolicy = $('#accept-to-privacy-policy');
$acceptToPrivacyPolicy.removeClass('is-invalid');
if ($acceptToPrivacyPolicy.length && !$acceptToPrivacyPolicy.prop('checked')) {
$acceptToPrivacyPolicy.addClass('is-invalid');
return;
}
App.Http.Booking.registerAppointment();
});
/**
* Event: Refresh captcha image.
*/
$captchaTitle.on('click', 'button', () => {
$('.captcha-image').attr('src', App.Utils.Url.siteUrl('captcha?' + Date.now()));
});
$selectDate.on('mousedown', '.ui-datepicker-calendar td', () => {
setTimeout(() => {
App.Http.Booking.applyPreviousUnavailableDates();
}, 300);
});
}
/**
* This function validates the customer's data input. The user cannot continue without passing all the validation
* checks.
*
* @return {Boolean} Returns the validation result.
*/
function validateCustomerForm() {
$('#wizard-frame-3 .is-invalid').removeClass('is-invalid');
$('#wizard-frame-3 label.text-danger').removeClass('text-danger');
// Validate required fields.
let missingRequiredField = false;
$('.required').each((index, requiredField) => {
if (!$(requiredField).val()) {
$(requiredField).addClass('is-invalid');
missingRequiredField = true;
}
});
if (missingRequiredField) {
$('#form-message').text(lang('fields_are_required'));
return false;
}
// Validate email address.
if ($email.val() && !App.Utils.Validation.email($email.val())) {
$email.addClass('is-invalid');
$('#form-message').text(lang('invalid_email'));
return false;
}
// Validate phone number.
const phoneNumber = $phoneNumber.val();
if (phoneNumber && !App.Utils.Validation.phone(phoneNumber)) {
$phoneNumber.addClass('is-invalid');
$('#form-message').text(lang('invalid_phone'));
return false;
}
return true;
}
/**
* Every time this function is executed, it updates the confirmation page with the latest
* customer settings and input for the appointment booking.
*/
function updateConfirmFrame() {
const serviceId = $selectService.val();
const providerId = $selectProvider.val();
$displayBookingSelection.text(`${lang('service')}${lang('provider')}`); // Notice: "│" is a custom ASCII char
const serviceOptionText = serviceId ? $selectService.find('option:selected').text() : lang('service');
const providerOptionText = providerId ? $selectProvider.find('option:selected').text() : lang('provider');
if (serviceId || providerId) {
$displayBookingSelection.text(`${serviceOptionText}${providerOptionText}`);
}
if (!$availableHours.find('.selected-hour').text()) {
return; // No time is selected, skip the rest of this function...
}
// Render the appointment details
const service = vars('available_services').find(
(availableService) => Number(availableService.id) === Number(serviceId),
);
if (!service) {
return; // Service was not found
}
const selectedDateObject = App.Utils.UI.getDateTimePickerValue($selectDate);
const selectedDateMoment = moment(selectedDateObject);
const selectedDate = selectedDateMoment.format('YYYY-MM-DD');
const selectedTime = $availableHours.find('.selected-hour').text();
let formattedSelectedDate = '';
if (selectedDateObject) {
formattedSelectedDate =
App.Utils.Date.format(selectedDate, vars('date_format'), vars('time_format'), false) +
' ' +
selectedTime;
}
const timezoneOptionText = $selectTimezone.find('option:selected').text();
$('#appointment-details').html(`
<div>
<div class="mb-2 fw-bold fs-3">
${serviceOptionText}
</div>
<div class="mb-2 fw-bold text-muted">
${providerOptionText}
</div>
<div class="mb-2">
<i class="fas fa-calendar-day me-2"></i>
${formattedSelectedDate}
</div>
<div class="mb-2">
<i class="fas fa-clock me-2"></i>
${service.duration} ${lang('minutes')}
</div>
<div class="mb-2">
<i class="fas fa-globe me-2"></i>
${timezoneOptionText}
</div>
<div class="mb-2" ${!Number(service.price) ? 'hidden' : ''}>
<i class="fas fa-cash-register me-2"></i>
${Number(service.price).toFixed(2)} ${service.currency}
</div>
</div>
`);
// Render the customer information
const firstName = App.Utils.String.escapeHtml($firstName.val());
const lastName = App.Utils.String.escapeHtml($lastName.val());
const fullName = `${firstName} ${lastName}`.trim();
const email = App.Utils.String.escapeHtml($email.val());
const phoneNumber = App.Utils.String.escapeHtml($phoneNumber.val());
const address = App.Utils.String.escapeHtml($address.val());
const city = App.Utils.String.escapeHtml($city.val());
const zipCode = App.Utils.String.escapeHtml($zipCode.val());
const addressParts = [];
if (city) {
addressParts.push(city);
}
if (zipCode) {
addressParts.push(zipCode);
}
$('#customer-details').html(`
<div>
<div class="mb-2 fw-bold fs-3">
${lang('contact_info')}
</div>
<div class="mb-2 fw-bold text-muted" ${!fullName ? 'hidden' : ''}>
${fullName}
</div>
<div class="mb-2" ${!email ? 'hidden' : ''}>
${email}
</div>
<div class="mb-2" ${!email ? 'hidden' : ''}>
${phoneNumber}
</div>
<div class="mb-2" ${!address ? 'hidden' : ''}>
${address}
</div>
<div class="mb-2" ${!addressParts.length ? 'hidden' : ''}>
${addressParts.join(', ')}
</div>
</div>
`);
// Update appointment form data for submission to server when the user confirms the appointment.
const data = {};
data.customer = {
last_name: $lastName.val(),
first_name: $firstName.val(),
email: $email.val(),
phone_number: $phoneNumber.val(),
address: $address.val(),
city: $city.val(),
zip_code: $zipCode.val(),
timezone: $selectTimezone.val(),
custom_field_1: $customField1.val(),
custom_field_2: $customField2.val(),
custom_field_3: $customField3.val(),
custom_field_4: $customField4.val(),
custom_field_5: $customField5.val(),
};
data.appointment = {
start_datetime:
moment(App.Utils.UI.getDateTimePickerValue($selectDate)).format('YYYY-MM-DD') +
' ' +
moment($('.selected-hour').data('value'), 'HH:mm').format('HH:mm') +
':00',
end_datetime: calculateEndDatetime(),
notes: $notes.val(),
is_unavailability: false,
id_users_provider: $selectProvider.val(),
id_services: $selectService.val(),
};
data.manage_mode = Number(manageMode);
if (manageMode) {
data.appointment.id = vars('appointment_data').id;
data.customer.id = vars('customer_data').id;
}
$('input[name="post_data"]').val(JSON.stringify(data));
}
/**
* This method calculates the end datetime of the current appointment.
*
* End datetime is depending on the service and start datetime fields.
*
* @return {String} Returns the end datetime in string format.
*/
function calculateEndDatetime() {
// Find selected service duration.
const serviceId = $selectService.val();
const service = vars('available_services').find(
(availableService) => Number(availableService.id) === Number(serviceId),
);
// Add the duration to the start datetime.
const selectedDate = moment(App.Utils.UI.getDateTimePickerValue($selectDate)).format('YYYY-MM-DD');
const selectedHour = $('.selected-hour').data('value'); // HH:mm
const startMoment = moment(selectedDate + ' ' + selectedHour);
let endMoment;
if (service.duration && startMoment) {
endMoment = startMoment.clone().add({'minutes': parseInt(service.duration)});
} else {
endMoment = moment();
}
return endMoment.format('YYYY-MM-DD HH:mm:ss');
}
/**
* This method applies the appointment's data to the wizard so
* that the user can start making changes on an existing record.
*
* @param {Object} appointment Selected appointment's data.
* @param {Object} provider Selected provider's data.
* @param {Object} customer Selected customer's data.
*
* @return {Boolean} Returns the operation result.
*/
function applyAppointmentData(appointment, provider, customer) {
try {
// Select Service & Provider
$selectService.val(appointment.id_services).trigger('change');
$selectProvider.val(appointment.id_users_provider);
// Set Appointment Date
const startMoment = moment(appointment.start_datetime);
App.Utils.UI.setDateTimePickerValue($selectDate, startMoment.toDate());
App.Http.Booking.getAvailableHours(startMoment.format('YYYY-MM-DD'));
// Apply Customer's Data
$lastName.val(customer.last_name);
$firstName.val(customer.first_name);
$email.val(customer.email);
$phoneNumber.val(customer.phone_number);
$address.val(customer.address);
$city.val(customer.city);
$zipCode.val(customer.zip_code);
if (customer.timezone) {
$selectTimezone.val(customer.timezone);
}
const appointmentNotes = appointment.notes !== null ? appointment.notes : '';
$notes.val(appointmentNotes);
$customField1.val(customer.custom_field_1);
$customField2.val(customer.custom_field_2);
$customField3.val(customer.custom_field_3);
$customField4.val(customer.custom_field_4);
$customField5.val(customer.custom_field_5);
App.Pages.Booking.updateConfirmFrame();
return true;
} catch (exc) {
return false;
}
}
/**
* Update the service description and information.
*
* This method updates the HTML content with a brief description of the
* user selected service (only if available in db). This is useful for the
* customers upon selecting the correct service.
*
* @param {Number} serviceId The selected service record id.
*/
function updateServiceDescription(serviceId) {
const $serviceDescription = $('#service-description');
$serviceDescription.empty();
const service = vars('available_services').find(
(availableService) => Number(availableService.id) === Number(serviceId),
);
if (!service) {
return; // Service not found
}
// Render the additional service information
const additionalInfoParts = [];
if (service.duration) {
additionalInfoParts.push(`${lang('duration')}: ${service.duration} ${lang('minutes')}`);
}
if (Number(service.price) > 0) {
additionalInfoParts.push(`${lang('price')}: ${Number(service.price).toFixed(2)} ${service.currency}`);
}
if (service.location) {
additionalInfoParts.push(`${lang('location')}: ${service.location}`);
}
if (additionalInfoParts.length) {
$(`
<div class="mb-2 fst-italic">
${additionalInfoParts.join(', ')}
</div>
`).appendTo($serviceDescription);
}
// Render the service description
if (service.description?.length) {
const escapedDescription = App.Utils.String.escapeHtml(service.description);
const multiLineDescription = escapedDescription.replaceAll('\n', '<br/>');
$(`
<div class="text-muted">
${multiLineDescription}
</div>
`).appendTo($serviceDescription);
}
}
document.addEventListener('DOMContentLoaded', initialize);
return {
manageMode,
updateConfirmFrame,
updateServiceDescription,
validateCustomerForm,
};
})();

View File

@ -0,0 +1,235 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Booking settings page.
*
* This module implements the functionality of the booking settings page.
*/
App.Pages.BookingSettings = (function () {
const $bookingSettings = $('#booking-settings');
const $saveSettings = $('#save-settings');
const $disableBooking = $('#disable-booking');
const $disableBookingMessage = $('#disable-booking-message');
/**
* Check if the form has invalid values.
*
* @return {Boolean}
*/
function isInvalid() {
try {
$('#booking-settings .is-invalid').removeClass('is-invalid');
// Validate required fields.
let missingRequiredFields = false;
$('#booking-settings .required').each((index, requiredField) => {
const $requiredField = $(requiredField);
if (!$requiredField.val()) {
$requiredField.addClass('is-invalid');
missingRequiredFields = true;
}
});
if (missingRequiredFields) {
throw new Error(lang('fields_are_required'));
}
// Ensure there is at least one field displayed.
if (!$('.display-switch:checked').length) {
throw new Error(lang('at_least_one_field'));
}
// Ensure there is at least one field required.
if (!$('.require-switch:checked').length) {
throw new Error(lang('at_least_one_field_required'));
}
return false;
} catch (error) {
App.Layouts.Backend.displayNotification(error.message);
return true;
}
}
/**
* Apply the booking settings into the page.
*
* @param {Object} bookingSettings
*/
function deserialize(bookingSettings) {
bookingSettings.forEach((bookingSetting) => {
if (bookingSetting.name === 'disable_booking_message') {
$disableBookingMessage.trumbowyg('html', bookingSetting.value);
return;
}
const $field = $('[data-field="' + bookingSetting.name + '"]');
if ($field.is(':checkbox')) {
$field.prop('checked', Boolean(Number(bookingSetting.value)));
} else {
$field.val(bookingSetting.value);
}
});
}
/**
* Serialize the page values into an array.
*
* @returns {Array}
*/
function serialize() {
const bookingSettings = [];
$('[data-field]').each((index, field) => {
const $field = $(field);
bookingSettings.push({
name: $field.data('field'),
value: $field.is(':checkbox') ? Number($field.prop('checked')) : $field.val(),
});
});
bookingSettings.push({
name: 'disable_booking_message',
value: $disableBookingMessage.trumbowyg('html'),
});
return bookingSettings;
}
/**
* Update the UI based on the display switch state.
*
* @param {jQuery} $displaySwitch
*/
function updateDisplaySwitch($displaySwitch) {
const isChecked = $displaySwitch.prop('checked');
const $formGroup = $displaySwitch.closest('.form-group');
$formGroup.find('.require-switch').prop('disabled', !isChecked);
$formGroup.find('.form-label, .form-control').toggleClass('opacity-25', !isChecked);
if (!isChecked) {
$formGroup.find('.require-switch').prop('checked', false);
$formGroup.find('.text-danger').hide();
}
}
/**
* Update the UI based on the require switch state.
*
* @param {jQuery} $requireSwitch
*/
function updateRequireSwitch($requireSwitch) {
const isChecked = $requireSwitch.prop('checked');
const $formGroup = $requireSwitch.closest('.form-group');
$formGroup.find('.text-danger').toggle(isChecked);
}
/**
* Update the UI based on the initial values.
*/
function applyInitialState() {
$bookingSettings.find('.display-switch').each((index, displaySwitchEl) => {
const $displaySwitch = $(displaySwitchEl);
updateDisplaySwitch($displaySwitch);
});
$bookingSettings.find('.require-switch').each((index, requireSwitchEl) => {
const $requireSwitch = $(requireSwitchEl);
updateRequireSwitch($requireSwitch);
});
$disableBookingMessage.closest('.form-group').prop('hidden', !$disableBooking.prop('checked'));
}
/**
* Save the account information.
*/
function onSaveSettingsClick() {
if (isInvalid()) {
return;
}
const bookingSettings = serialize();
App.Http.BookingSettings.save(bookingSettings).done(() => {
App.Layouts.Backend.displayNotification(lang('settings_saved'));
});
}
/**
* Update the UI.
*
* @param {jQuery} event
*/
function onDisplaySwitchClick(event) {
const $displaySwitch = $(event.target);
updateDisplaySwitch($displaySwitch);
}
/**
* Update the UI.
*
* @param {Event} event
*/
function onRequireSwitchClick(event) {
const $requireSwitch = $(event.target);
updateRequireSwitch($requireSwitch);
}
/**
* Toggle the message container.
*/
function onDisableBookingClick() {
$disableBookingMessage.closest('.form-group').prop('hidden', !$disableBooking.prop('checked'));
}
/**
* Initialize the module.
*/
function initialize() {
const bookingSettings = vars('booking_settings');
$saveSettings.on('click', onSaveSettingsClick);
$disableBooking.on('click', onDisableBookingClick);
$bookingSettings
.on('click', '.display-switch', onDisplaySwitchClick)
.on('click', '.require-switch', onRequireSwitchClick);
$disableBookingMessage.trumbowyg();
deserialize(bookingSettings);
applyInitialState();
}
document.addEventListener('DOMContentLoaded', initialize);
return {};
})();

View File

@ -0,0 +1,178 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Business settings page.
*
* This module implements the functionality of the business settings page.
*/
App.Pages.BusinessSettings = (function () {
const $saveSettings = $('#save-settings');
const $applyGlobalWorkingPlan = $('#apply-global-working-plan');
const $appointmentStatusOptions = $('#appointment-status-options');
let workingPlanManager = null;
/**
* Check if the form has invalid values.
*
* @return {Boolean}
*/
function isInvalid() {
try {
$('#business-settings .is-invalid').removeClass('is-invalid');
// Validate required fields.
let missingRequiredFields = false;
$('#business-settings .required').each((index, requiredField) => {
const $requiredField = $(requiredField);
if (!$requiredField.val()) {
$requiredField.addClass('is-invalid');
missingRequiredFields = true;
}
});
if (missingRequiredFields) {
throw new Error(lang('fields_are_required'));
}
return false;
} catch (error) {
App.Layouts.Backend.displayNotification(error.message);
return true;
}
}
function deserialize(businessSettings) {
businessSettings.forEach((businessSetting) => {
const $field = $('[data-field="' + businessSetting.name + '"]');
$field.is(':checkbox')
? $field.prop('checked', Boolean(Number(businessSetting.value)))
: $field.val(businessSetting.value);
});
}
function serialize() {
const businessSettings = [];
$('[data-field]').each((index, field) => {
const $field = $(field);
businessSettings.push({
name: $field.data('field'),
value: $field.is(':checkbox') ? Number($field.prop('checked')) : $field.val(),
});
});
const workingPlan = workingPlanManager.get();
businessSettings.push({
name: 'company_working_plan',
value: JSON.stringify(workingPlan),
});
const appointmentStatusOptions = App.Components.AppointmentStatusOptions.getOptions($appointmentStatusOptions);
businessSettings.push({
name: 'appointment_status_options',
value: JSON.stringify(appointmentStatusOptions),
});
return businessSettings;
}
/**
* Save the account information.
*/
function onSaveSettingsClick() {
if (isInvalid()) {
App.Layouts.Backend.displayNotification(lang('settings_are_invalid'));
return;
}
const businessSettings = serialize();
App.Http.BusinessSettings.save(businessSettings).done(() => {
App.Layouts.Backend.displayNotification(lang('settings_saved'));
});
}
/**
* Save the global working plan information.
*/
function onApplyGlobalWorkingPlan() {
const buttons = [
{
text: lang('cancel'),
click: (event, messageModal) => {
messageModal.hide();
},
},
{
text: 'OK',
click: (event, messageModal) => {
const workingPlan = workingPlanManager.get();
App.Http.BusinessSettings.applyGlobalWorkingPlan(workingPlan)
.done(() => {
App.Layouts.Backend.displayNotification(lang('working_plans_got_updated'));
})
.always(() => {
messageModal.hide();
});
},
},
];
App.Utils.Message.show(lang('working_plan'), lang('overwrite_existing_working_plans'), buttons);
}
/**
* Initialize the module.
*/
function initialize() {
const businessSettings = vars('business_settings');
deserialize(businessSettings);
let companyWorkingPlan = {};
let appointmentStatusOptions = [];
vars('business_settings').forEach((businessSetting) => {
if (businessSetting.name === 'company_working_plan') {
companyWorkingPlan = JSON.parse(businessSetting.value);
}
if (businessSetting.name === 'appointment_status_options') {
appointmentStatusOptions = JSON.parse(businessSetting.value);
}
});
workingPlanManager = new App.Utils.WorkingPlan();
workingPlanManager.setup(companyWorkingPlan);
workingPlanManager.timepickers(false);
workingPlanManager.addEventListeners();
App.Components.AppointmentStatusOptions.setOptions($appointmentStatusOptions, appointmentStatusOptions);
$saveSettings.on('click', onSaveSettingsClick);
$applyGlobalWorkingPlan.on('click', onApplyGlobalWorkingPlan);
}
document.addEventListener('DOMContentLoaded', initialize);
return {};
})();

164
assets/js/pages/calendar.js Normal file
View File

@ -0,0 +1,164 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Calendar page.
*
* This module implements the functionality of the backend calendar page.
*/
App.Pages.Calendar = (function () {
const $insertWorkingPlanException = $('#insert-working-plan-exception');
const moment = window.moment;
/**
* Add the page event listeners.
*/
function addEventListeners() {
const $calendarPage = $('#calendar-page');
$calendarPage.on('click', '#toggle-fullscreen', (event) => {
const $toggleFullscreen = $(event.target);
const element = document.documentElement;
const isFullScreen =
document.fullScreenElement || document.mozFullScreen || document.webkitIsFullScreen || false;
if (isFullScreen) {
// Exit fullscreen mode.
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
$toggleFullscreen.removeClass('btn-success').addClass('btn-light');
} else {
// Switch to fullscreen mode.
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
}
$toggleFullscreen.removeClass('btn-light').addClass('btn-success');
}
});
$insertWorkingPlanException.on('click', () => {
const providerId = $('#select-filter-item').val();
if (providerId === App.Utils.CalendarDefaultView.FILTER_TYPE_ALL) {
return;
}
const provider = vars('available_providers').find((availableProvider) => {
return Number(availableProvider.id) === Number(providerId);
});
if (!provider) {
throw new Error('Provider could not be found: ' + providerId);
}
App.Components.WorkingPlanExceptionsModal.add().done((date, workingPlanException) => {
const successCallback = () => {
App.Layouts.Backend.displayNotification(lang('working_plan_exception_saved'));
const workingPlanExceptions = JSON.parse(provider.settings.working_plan_exceptions) || {};
workingPlanExceptions[date] = workingPlanException;
for (let index in vars('available_providers')) {
const availableProvider = vars('available_providers')[index];
if (Number(availableProvider.id) === Number(providerId)) {
vars('available_providers')[index].settings.working_plan_exceptions =
JSON.stringify(workingPlanExceptions);
break;
}
}
$('#select-filter-item').trigger('change'); // Update the calendar.
};
App.Http.Calendar.saveWorkingPlanException(
date,
workingPlanException,
providerId,
successCallback,
null,
);
});
});
}
/**
* Get calendar selection end date.
*
* On calendar slot selection, calculate the end date based on the provided start date.
*
* @param {Object} info Holding the "start" and "end" props, as provided by FullCalendar.
*
* @return {Date}
*/
function getSelectionEndDate(info) {
const startMoment = moment(info.start);
const endMoment = moment(info.end);
const startTillEndDiff = endMoment.diff(startMoment);
const startTillEndDuration = moment.duration(startTillEndDiff);
const durationInMinutes = startTillEndDuration.asMinutes();
const minDurationInMinutes = 15;
if (durationInMinutes <= minDurationInMinutes) {
const serviceId = $('#select-service').val();
const service = vars('available_services').find(
(availableService) => Number(availableService.id) === Number(serviceId),
);
if (service) {
endMoment.add(service.duration - durationInMinutes, 'minutes');
}
}
return endMoment.toDate();
}
/**
* Initialize the module.
*
* This function makes the necessary initialization for the default backend calendar page.
*
* If this module is used in another page then this function might not be needed.
*/
function initialize() {
// Load and initialize the calendar view.
if (vars('calendar_view') === 'table') {
App.Utils.CalendarTableView.initialize();
} else {
App.Utils.CalendarDefaultView.initialize();
}
App.Pages.Calendar.addEventListeners();
}
document.addEventListener('DOMContentLoaded', initialize);
return {
addEventListeners,
getSelectionEndDate,
};
})();

View File

@ -0,0 +1,502 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Customers page.
*
* This module implements the functionality of the customers page.
*/
App.Pages.Customers = (function () {
const $customers = $('#customers');
const $filterCustomers = $('#filter-customers');
const $id = $('#customer-id');
const $firstName = $('#first-name');
const $lastName = $('#last-name');
const $email = $('#email');
const $phoneNumber = $('#phone-number');
const $address = $('#address');
const $city = $('#city');
const $zipCode = $('#zip-code');
const $timezone = $('#timezone');
const $language = $('#language');
const $ldapDn = $('#ldap-dn');
const $customField1 = $('#custom-field-1');
const $customField2 = $('#custom-field-2');
const $customField3 = $('#custom-field-3');
const $customField4 = $('#custom-field-4');
const $customField5 = $('#custom-field-5');
const $notes = $('#notes');
const $formMessage = $('#form-message');
const $customerAppointments = $('#customer-appointments');
const moment = window.moment;
let filterResults = {};
let filterLimit = 20;
/**
* Add the page event listeners.
*/
function addEventListeners() {
/**
* Event: Filter Customers Form "Submit"
*
* @param {jQuery.Event} event
*/
$customers.on('submit', '#filter-customers form', (event) => {
event.preventDefault();
const key = $filterCustomers.find('.key').val();
$filterCustomers.find('.selected').removeClass('selected');
filterLimit = 20;
App.Pages.Customers.resetForm();
App.Pages.Customers.filter(key);
});
/**
* Event: Filter Entry "Click"
*
* Display the customer data of the selected row.
*
* @param {jQuery.Event} event
*/
$customers.on('click', '.customer-row', (event) => {
if ($filterCustomers.find('.filter').prop('disabled')) {
return; // Do nothing when user edits a customer record.
}
const customerId = $(event.currentTarget).attr('data-id');
const customer = filterResults.find((filterResult) => Number(filterResult.id) === Number(customerId));
App.Pages.Customers.display(customer);
$('#filter-customers .selected').removeClass('selected');
$(event.currentTarget).addClass('selected');
$('#edit-customer, #delete-customer').prop('disabled', false);
});
/**
* Event: Add Customer Button "Click"
*/
$customers.on('click', '#add-customer', () => {
App.Pages.Customers.resetForm();
$customers.find('#add-edit-delete-group').hide();
$customers.find('#save-cancel-group').show();
$customers.find('.record-details').find('input, select, textarea').prop('disabled', false);
$customers.find('.record-details .form-label span').prop('hidden', false);
$filterCustomers.find('button').prop('disabled', true);
$filterCustomers.find('.results').css('color', '#AAA');
});
/**
* Event: Edit Customer Button "Click"
*/
$customers.on('click', '#edit-customer', () => {
$customers.find('.record-details').find('input, select, textarea').prop('disabled', false);
$customers.find('.record-details .form-label span').prop('hidden', false);
$customers.find('#add-edit-delete-group').hide();
$customers.find('#save-cancel-group').show();
$filterCustomers.find('button').prop('disabled', true);
$filterCustomers.find('.results').css('color', '#AAA');
});
/**
* Event: Cancel Customer Add/Edit Operation Button "Click"
*/
$customers.on('click', '#cancel-customer', () => {
const id = $id.val();
App.Pages.Customers.resetForm();
if (id) {
select(id, true);
}
});
/**
* Event: Save Add/Edit Customer Operation "Click"
*/
$customers.on('click', '#save-customer', () => {
const customer = {
first_name: $firstName.val(),
last_name: $lastName.val(),
email: $email.val(),
phone_number: $phoneNumber.val(),
address: $address.val(),
city: $city.val(),
zip_code: $zipCode.val(),
notes: $notes.val(),
timezone: $timezone.val(),
language: $language.val() || 'english',
custom_field_1: $customField1.val(),
custom_field_2: $customField2.val(),
custom_field_3: $customField3.val(),
custom_field_4: $customField4.val(),
custom_field_5: $customField5.val(),
ldap_dn: $ldapDn.val(),
};
if ($id.val()) {
customer.id = $id.val();
}
if (!App.Pages.Customers.validate()) {
return;
}
App.Pages.Customers.save(customer);
});
/**
* Event: Delete Customer Button "Click"
*/
$customers.on('click', '#delete-customer', () => {
const customerId = $id.val();
const buttons = [
{
text: lang('cancel'),
click: (event, messageModal) => {
messageModal.hide();
},
},
{
text: lang('delete'),
click: (event, messageModal) => {
App.Pages.Customers.remove(customerId);
messageModal.hide();
},
},
];
App.Utils.Message.show(lang('delete_customer'), lang('delete_record_prompt'), buttons);
});
}
/**
* Save a customer record to the database (via ajax post).
*
* @param {Object} customer Contains the customer data.
*/
function save(customer) {
App.Http.Customers.save(customer).then((response) => {
App.Layouts.Backend.displayNotification(lang('customer_saved'));
App.Pages.Customers.resetForm();
$('#filter-customers .key').val('');
App.Pages.Customers.filter('', response.id, true);
});
}
/**
* Delete a customer record from database.
*
* @param {Number} id Record id to be deleted.
*/
function remove(id) {
App.Http.Customers.destroy(id).then(() => {
App.Layouts.Backend.displayNotification(lang('customer_deleted'));
App.Pages.Customers.resetForm();
App.Pages.Customers.filter($('#filter-customers .key').val());
});
}
/**
* Validate customer data before save (insert or update).
*/
function validate() {
$formMessage.removeClass('alert-danger').hide();
$('.is-invalid').removeClass('is-invalid');
try {
// Validate required fields.
let missingRequired = false;
$('.required').each((index, requiredField) => {
if ($(requiredField).val() === '') {
$(requiredField).addClass('is-invalid');
missingRequired = true;
}
});
if (missingRequired) {
throw new Error(lang('fields_are_required'));
}
// Validate email address.
const email = $email.val();
if (email && !App.Utils.Validation.email(email)) {
$email.addClass('is-invalid');
throw new Error(lang('invalid_email'));
}
// Validate phone number.
const phoneNumber = $phoneNumber.val();
if (phoneNumber && !App.Utils.Validation.phone(phoneNumber)) {
$phoneNumber.addClass('is-invalid');
throw new Error(lang('invalid_phone'));
}
return true;
} catch (error) {
$formMessage.addClass('alert-danger').text(error.message).show();
return false;
}
}
/**
* Bring the customer form back to its initial state.
*/
function resetForm() {
$customers.find('.record-details').find('input, select, textarea').val('').prop('disabled', true);
$customers.find('.record-details .form-label span').prop('hidden', true);
$customers.find('.record-details #timezone').val(vars('default_timezone'));
$customers.find('.record-details #language').val(vars('default_language'));
$customerAppointments.empty();
$customers.find('#edit-customer, #delete-customer').prop('disabled', true);
$customers.find('#add-edit-delete-group').show();
$customers.find('#save-cancel-group').hide();
$customers.find('.record-details .is-invalid').removeClass('is-invalid');
$customers.find('.record-details #form-message').hide();
$filterCustomers.find('button').prop('disabled', false);
$filterCustomers.find('.selected').removeClass('selected');
$filterCustomers.find('.results').css('color', '');
}
/**
* Display a customer record into the form.
*
* @param {Object} customer Contains the customer record data.
*/
function display(customer) {
$id.val(customer.id);
$firstName.val(customer.first_name);
$lastName.val(customer.last_name);
$email.val(customer.email);
$phoneNumber.val(customer.phone_number);
$address.val(customer.address);
$city.val(customer.city);
$zipCode.val(customer.zip_code);
$notes.val(customer.notes);
$timezone.val(customer.timezone);
$language.val(customer.language || 'english');
$ldapDn.val(customer.ldap_dn);
$customField1.val(customer.custom_field_1);
$customField2.val(customer.custom_field_2);
$customField3.val(customer.custom_field_3);
$customField4.val(customer.custom_field_4);
$customField5.val(customer.custom_field_5);
$customerAppointments.empty();
if (!customer.appointments.length) {
$('<p/>', {
'text': lang('no_records_found'),
}).appendTo($customerAppointments);
}
customer.appointments.forEach((appointment) => {
if (
vars('role_slug') === App.Layouts.Backend.DB_SLUG_PROVIDER &&
parseInt(appointment.id_users_provider) !== vars('user_id')
) {
return;
}
if (
vars('role_slug') === App.Layouts.Backend.DB_SLUG_SECRETARY &&
vars('secretary_providers').indexOf(appointment.id_users_provider) === -1
) {
return;
}
const start = App.Utils.Date.format(
moment(appointment.start_datetime).toDate(),
vars('date_format'),
vars('time_format'),
true,
);
const end = App.Utils.Date.format(
moment(appointment.end_datetime).toDate(),
vars('date_format'),
vars('time_format'),
true,
);
$('<div/>', {
'class': 'appointment-row',
'data-id': appointment.id,
'html': [
// Service - Provider
$('<a/>', {
'href': App.Utils.Url.siteUrl(`calendar/reschedule/${appointment.hash}`),
'html': [
$('<i/>', {
'class': 'fas fa-edit me-1',
}),
$('<strong/>', {
'text':
appointment.service.name +
' - ' +
appointment.provider.first_name +
' ' +
appointment.provider.last_name,
}),
$('<br/>'),
],
}),
// Start
$('<small/>', {
'text': start,
}),
$('<br/>'),
// End
$('<small/>', {
'text': end,
}),
$('<br/>'),
// Timezone
$('<small/>', {
'text': vars('timezones')[appointment.provider.timezone],
}),
],
}).appendTo('#customer-appointments');
});
}
/**
* Filter customer records.
*
* @param {String} keyword This keyword string is used to filter the customer records.
* @param {Number} selectId Optional, if set then after the filter operation the record with the given
* ID will be selected (but not displayed).
* @param {Boolean} show Optional (false), if true then the selected record will be displayed on the form.
*/
function filter(keyword, selectId = null, show = false) {
App.Http.Customers.search(keyword, filterLimit).then((response) => {
filterResults = response;
$filterCustomers.find('.results').empty();
response.forEach((customer) => {
$('#filter-customers .results').append(App.Pages.Customers.getFilterHtml(customer)).append($('<hr/>'));
});
if (!response.length) {
$filterCustomers.find('.results').append(
$('<em/>', {
'text': lang('no_records_found'),
}),
);
} else if (response.length === filterLimit) {
$('<button/>', {
'type': 'button',
'class': 'btn btn-outline-secondary w-100 load-more text-center',
'text': lang('load_more'),
'click': () => {
filterLimit += 20;
App.Pages.Customers.filter(keyword, selectId, show);
},
}).appendTo('#filter-customers .results');
}
if (selectId) {
App.Pages.Customers.select(selectId, show);
}
});
}
/**
* Get the filter results row HTML code.
*
* @param {Object} customer Contains the customer data.
*
* @return {String} Returns the record HTML code.
*/
function getFilterHtml(customer) {
const name = (customer.first_name || '[No First Name]') + ' ' + (customer.last_name || '[No Last Name]');
let info = customer.email || '[No Email]';
info = customer.phone_number ? info + ', ' + customer.phone_number : info;
return $('<div/>', {
'class': 'customer-row entry',
'data-id': customer.id,
'html': [
$('<strong/>', {
'text': name,
}),
$('<br/>'),
$('<small/>', {
'class': 'text-muted',
'text': info,
}),
$('<br/>'),
],
});
}
/**
* Select a specific record from the current filter results.
*
* If the customer id does not exist in the list then no record will be selected.
*
* @param {Number} id The record id to be selected from the filter results.
* @param {Boolean} show Optional (false), if true then the method will display the record on the form.
*/
function select(id, show = false) {
$('#filter-customers .selected').removeClass('selected');
$('#filter-customers .entry[data-id="' + id + '"]').addClass('selected');
if (show) {
const customer = filterResults.find((filterResult) => Number(filterResult.id) === Number(id));
App.Pages.Customers.display(customer);
$('#edit-customer, #delete-customer').prop('disabled', false);
}
}
/**
* Initialize the module.
*/
function initialize() {
App.Pages.Customers.resetForm();
App.Pages.Customers.addEventListeners();
App.Pages.Customers.filter('');
}
document.addEventListener('DOMContentLoaded', initialize);
return {
filter,
save,
remove,
validate,
getFilterHtml,
resetForm,
display,
select,
addEventListeners,
};
})();

View File

@ -0,0 +1,188 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* General settings page.
*
* This module implements the functionality of the general settings page.
*/
App.Pages.GeneralSettings = (function () {
const $saveSettings = $('#save-settings');
const $companyLogo = $('#company-logo');
const $companyLogoPreview = $('#company-logo-preview');
const $removeCompanyLogo = $('#remove-company-logo');
const $companyColor = $('#company-color');
const $resetCompanyColor = $('#reset-company-color');
let companyLogoBase64 = '';
/**
* Check if the form has invalid values.
*
* @return {Boolean}
*/
function isInvalid() {
try {
$('#general-settings .is-invalid').removeClass('is-invalid');
// Validate required fields.
let missingRequiredFields = false;
$('#general-settings .required').each((index, requiredField) => {
const $requiredField = $(requiredField);
if (!$requiredField.val()) {
$requiredField.addClass('is-invalid');
missingRequiredFields = true;
}
});
if (missingRequiredFields) {
throw new Error(lang('fields_are_required'));
}
return false;
} catch (error) {
App.Layouts.Backend.displayNotification(error.message);
return true;
}
}
function deserialize(generalSettings) {
generalSettings.forEach((generalSetting) => {
if (generalSetting.name === 'company_logo' && generalSetting.value) {
companyLogoBase64 = generalSetting.value;
$companyLogoPreview.attr('src', generalSetting.value);
$companyLogoPreview.prop('hidden', false);
$removeCompanyLogo.prop('hidden', false);
return;
}
if (generalSetting.name === 'company_color' && generalSetting.value !== '#ffffff') {
$resetCompanyColor.prop('hidden', false);
}
const $field = $('[data-field="' + generalSetting.name + '"]');
$field.is(':checkbox')
? $field.prop('checked', Boolean(Number(generalSetting.value)))
: $field.val(generalSetting.value);
});
}
function serialize() {
const generalSettings = [];
$('[data-field]').each((index, field) => {
const $field = $(field);
generalSettings.push({
name: $field.data('field'),
value: $field.is(':checkbox') ? Number($field.prop('checked')) : $field.val(),
});
});
generalSettings.push({
name: 'company_logo',
value: companyLogoBase64,
});
return generalSettings;
}
/**
* Save the account information.
*/
function onSaveSettingsClick() {
if (isInvalid()) {
App.Layouts.Backend.displayNotification(lang('settings_are_invalid'));
return;
}
const generalSettings = serialize();
App.Http.GeneralSettings.save(generalSettings).done(() => {
App.Layouts.Backend.displayNotification(lang('settings_saved'), [
{
label: lang('reload'), // Reload Page
function: () => window.location.reload(),
},
]);
});
}
/**
* Convert the selected image to a base64 encoded string.
*/
function onCompanyLogoChange() {
const file = $companyLogo[0].files[0];
if (!file) {
$removeCompanyLogo.trigger('click');
return;
}
App.Utils.File.toBase64(file).then((base64) => {
companyLogoBase64 = base64;
$companyLogoPreview.attr('src', base64);
$companyLogoPreview.prop('hidden', false);
$removeCompanyLogo.prop('hidden', false);
});
}
/**
* Remove the company logo data.
*/
function onRemoveCompanyLogoClick() {
companyLogoBase64 = '';
$companyLogo.val('');
$companyLogoPreview.attr('src', '#');
$companyLogoPreview.prop('hidden', true);
$removeCompanyLogo.prop('hidden', true);
}
/**
* Toggle the reset company color button.
*/
function onCompanyColorChange() {
$resetCompanyColor.prop('hidden', $companyColor.val() === '#ffffff');
}
/**
* Set the company color value to "#ffffff" which is the default one.
*/
function onResetCompanyColorClick() {
$companyColor.val('#ffffff');
}
/**
* Initialize the module.
*/
function initialize() {
$saveSettings.on('click', onSaveSettingsClick);
$companyLogo.on('change', onCompanyLogoChange);
$removeCompanyLogo.on('click', onRemoveCompanyLogoClick);
$companyColor.on('change', onCompanyColorChange);
$resetCompanyColor.on('click', onResetCompanyColorClick);
const generalSettings = vars('general_settings');
deserialize(generalSettings);
}
document.addEventListener('DOMContentLoaded', initialize);
return {};
})();

View File

@ -0,0 +1,109 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Google Analytics settings page.
*
* This module implements the functionality of the Google Analytics settings page.
*/
App.Pages.GoogleAnalyticsSettings = (function () {
const $saveSettings = $('#save-settings');
/**
* Check if the form has invalid values.
*
* @return {Boolean}
*/
function isInvalid() {
try {
$('#google-analytics-settings .is-invalid').removeClass('is-invalid');
// Validate required fields.
let missingRequiredFields = false;
$('#google-analytics-settings .required').each((index, requiredField) => {
const $requiredField = $(requiredField);
if (!$requiredField.val()) {
$requiredField.addClass('is-invalid');
missingRequiredFields = true;
}
});
if (missingRequiredFields) {
throw new Error(lang('fields_are_required'));
}
return false;
} catch (error) {
App.Layouts.Backend.displayNotification(error.message);
return true;
}
}
function deserialize(googleAnalyticsSettings) {
googleAnalyticsSettings.forEach((googleAnalyticsSetting) => {
const $field = $('[data-field="' + googleAnalyticsSetting.name + '"]');
$field.is(':checkbox')
? $field.prop('checked', Boolean(Number(googleAnalyticsSetting.value)))
: $field.val(googleAnalyticsSetting.value);
});
}
function serialize() {
const googleAnalyticsSettings = [];
$('[data-field]').each((index, field) => {
const $field = $(field);
googleAnalyticsSettings.push({
name: $field.data('field'),
value: $field.is(':checkbox') ? Number($field.prop('checked')) : $field.val(),
});
});
return googleAnalyticsSettings;
}
/**
* Save the account information.
*/
function onSaveSettingsClick() {
if (isInvalid()) {
App.Layouts.Backend.displayNotification(lang('settings_are_invalid'));
return;
}
const googleAnalyticsSettings = serialize();
App.Http.GoogleAnalyticsSettings.save(googleAnalyticsSettings).done(() => {
App.Layouts.Backend.displayNotification(lang('settings_saved'));
});
}
/**
* Initialize the module.
*/
function initialize() {
$saveSettings.on('click', onSaveSettingsClick);
const googleAnalyticsSettings = vars('google_analytics_settings');
deserialize(googleAnalyticsSettings);
}
document.addEventListener('DOMContentLoaded', initialize);
return {};
})();

View File

@ -0,0 +1,176 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Installation page.
*
* This module implements the functionality of the installation page.
*/
App.Pages.Installation = (function () {
const MIN_PASSWORD_LENGTH = 7;
const $install = $('#install');
const $alert = $('.alert');
const $loading = $('#loading');
const $firstName = $('#first-name');
const $lastName = $('#last-name');
const $email = $('#email');
const $phoneNumber = $('#phone-number');
const $username = $('#username');
const $password = $('#password');
const $passwordConfirm = $('#password-confirm');
const $language = $('#language');
const $companyName = $('#company-name');
const $companyEmail = $('#company-email');
const $companyLink = $('#company-link');
$(document).ajaxStart(() => {
$loading.removeClass('d-none');
});
$(document).ajaxStop(() => {
$loading.addClass('d-none');
});
/**
* Event: Install Easy!Appointments Button "Click"
*/
$install.on('click', () => {
if (!validate()) {
return;
}
const url = App.Utils.Url.siteUrl('installation/perform');
const data = {
csrf_token: vars('csrf_token'),
admin: getAdminData(),
company: getCompanyData(),
};
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'json',
}).done(() => {
$alert
.text('Easy!Appointments has been successfully installed!')
.addClass('alert-success')
.prop('hidden', false);
setTimeout(() => {
window.location.href = App.Utils.Url.siteUrl('calendar');
}, 1000);
});
});
/**
* Validates the user input.
*
* Use this before executing the installation procedure.
*
* @return {Boolean} Returns the validation result.
*/
function validate() {
try {
const $fields = $('input');
$alert.removeClass('alert-danger').prop('hidden', true);
$fields.removeClass('is-invalid');
// Check for empty fields.
let missingRequired = false;
$fields.each((index, field) => {
if (!$(field).val()) {
$(field).addClass('is-invalid');
missingRequired = true;
}
});
if (missingRequired) {
throw new Error(lang('fields_are_required'));
}
// Validate Passwords
if ($password.val() !== $passwordConfirm.val()) {
$password.addClass('is-invalid');
$passwordConfirm.addClass('is-invalid');
throw new Error(lang('passwords_mismatch'));
}
if ($password.val().length < MIN_PASSWORD_LENGTH) {
$password.addClass('is-invalid');
$passwordConfirm.addClass('is-invalid');
throw new Error(lang('password_length_notice').replace('$number', MIN_PASSWORD_LENGTH));
}
// Validate Email
if (!App.Utils.Validation.email($email.val())) {
$email.addClass('is-invalid');
throw new Error(lang('invalid_email'));
}
if (!App.Utils.Validation.email($companyEmail.val())) {
$companyEmail.addClass('is-invalid');
throw new Error(lang('invalid_email'));
}
return true;
} catch (error) {
$alert.addClass('alert-danger').text(error.message).prop('hidden', false);
return false;
}
}
/**
* Get the admin data as an object.
*
* @return {Object}
*/
function getAdminData() {
return {
first_name: $firstName.val(),
last_name: $lastName.val(),
email: $email.val(),
phone_number: $phoneNumber.val(),
username: $username.val(),
password: $password.val(),
language: $language.val(),
};
}
/**
* Get the company data as an object.
*
* @return {Object}
*/
function getCompanyData() {
return {
company_name: $companyName.val(),
company_email: $companyEmail.val(),
company_link: $companyLink.val(),
};
}
// Validate the base URL setting (must not contain any trailing slash).
if (vars('base_url').slice(-1) === '/') {
App.Utils.Message.show(
'Invalid Configuration Detected',
'Please remove any trailing slashes from your "BASE_URL" setting of the root "config.php" file and try again.',
);
$install.prop('disabled', true).fadeTo('0.4');
}
return {};
})();

View File

@ -0,0 +1,256 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* LDAP settings page.
*
* This module implements the functionality of the LDAP settings page.
*/
App.Pages.LdapSettings = (function () {
const $saveSettings = $('#save-settings');
const $searchForm = $('#ldap-search-form');
const $searchKeyword = $('#ldap-search-keyword');
const $searchResults = $('#ldap-search-results');
const $ldapFilter = $('#ldap-filter');
const $ldapFieldMapping = $('#ldap-field-mapping');
const $resetFilter = $('#ldap-reset-filter');
const $resetFieldMapping = $('#ldap-reset-field-mapping');
/**
* Check if the form has invalid values.
*
* @return {Boolean}
*/
function isInvalid() {
try {
$('#ldap-settings .is-invalid').removeClass('is-invalid');
// Validate required fields.
let missingRequiredFields = false;
$('#ldap-settings .required').each((index, requiredField) => {
const $requiredField = $(requiredField);
if (!$requiredField.val()) {
$requiredField.addClass('is-invalid');
missingRequiredFields = true;
}
});
if (missingRequiredFields) {
throw new Error(lang('fields_are_required'));
}
return false;
} catch (error) {
App.Layouts.Backend.displayNotification(error.message);
return true;
}
}
/**
* Apply the setting values to the UI form.
*
* @param {Array} ldapSettings
*/
function deserialize(ldapSettings) {
ldapSettings.forEach((ldapSetting) => {
const $field = $('[data-field="' + ldapSetting.name + '"]');
$field.is(':checkbox')
? $field.prop('checked', Boolean(Number(ldapSetting.value)))
: $field.val(ldapSetting.value);
});
}
/**
* Prepare an array of setting values based on the UI form.
*
* @return {Array}
*/
function serialize() {
const ldapSettings = [];
$('[data-field]').each((index, field) => {
const $field = $(field);
ldapSettings.push({
name: $field.data('field'),
value: $field.is(':checkbox') ? Number($field.prop('checked')) : $field.val(),
});
});
return ldapSettings;
}
function getLdapFieldMapping() {
const jsonLdapFieldMapping = $ldapFieldMapping.val();
return JSON.parse(jsonLdapFieldMapping);
}
/**
* Save the current server settings.
*/
function saveSettings() {
if (isInvalid()) {
App.Layouts.Backend.displayNotification(lang('settings_are_invalid'));
return;
}
const ldapSettings = serialize();
return App.Http.LdapSettings.save(ldapSettings);
}
/**
* Search the LDAP server based on a keyword.
*/
function searchServer() {
$searchResults.empty();
const keyword = $searchKeyword.val();
if (!keyword) {
return;
}
App.Http.LdapSettings.search(keyword).done((entries) => {
$searchResults.empty();
if (!entries?.length) {
renderNoRecordsFound().appendTo($searchResults);
return;
}
entries.forEach((entry) => {
renderEntry(entry).appendTo($searchResults);
});
});
}
/**
* Save the account information.
*/
function onSaveSettingsClick() {
saveSettings().done(() => {
App.Layouts.Backend.displayNotification(lang('settings_saved'));
});
}
/**
* Set the field value back to the original state.
*/
function onResetFilterClick() {
$ldapFilter.val(vars('ldap_default_filter'));
}
/**
* Set the field value back to the original state.
*/
function onResetFieldMappingClick() {
const defaultFieldMapping = vars('ldap_default_field_mapping');
const jsonDefaultFieldMapping = JSON.stringify(defaultFieldMapping, null, 2);
$ldapFieldMapping.val(jsonDefaultFieldMapping);
}
/**
* Handle the LDAP import button click
*/
function onLdapImportClick(event) {
const $target = $(event.target);
const $card = $target.closest('.card');
const entry = $card.data('entry');
const ldapFieldMapping = getLdapFieldMapping();
App.Components.LdapImportModal.open(entry, ldapFieldMapping).done(() => {
App.Layouts.Backend.displayNotification(lang('user_imported'));
});
}
/**
* Render the no-records-found message
*/
function renderNoRecordsFound() {
return $(`
<div class="text-muted fst-italic">
${lang('no_records_found')}
</div>
`);
}
/**
* Render the LDAP entry data on screen
*
* @param {Object} entry
*/
function renderEntry(entry) {
if (!entry?.dn) {
return;
}
const $entry = $(`
<div class="card small mb-2">
<div class="card-header p-2 fw-bold">
${entry.dn}
</div>
<div class="card-body p-2">
<p class="d-block mb-2">${lang('content')}</p>
<pre class="overflow-y-auto bg-light rounded p-2" style="max-height: 200px">${JSON.stringify(entry, null, 2)}</pre>
<div class="d-lg-flex">
<button class="btn btn-outline-primary btn-sm px-4 ldap-import ms-lg-auto">
${lang('import')}
</button>
</div>
</div>
</div>
`);
$entry.data('entry', entry);
return $entry;
}
/**
* Save the current connection settings and then search the directory based on the provided keyword.
*
* @param {Object} event
*/
function onSearchFormSubmit(event) {
event.preventDefault();
saveSettings().done(() => {
searchServer();
});
}
/**
* Initialize the module.
*/
function initialize() {
$saveSettings.on('click', onSaveSettingsClick);
$resetFilter.on('click', onResetFilterClick);
$resetFieldMapping.on('click', onResetFieldMappingClick);
$searchForm.on('submit', onSearchFormSubmit);
$searchResults.on('click', '.ldap-import', onLdapImportClick);
const ldapSettings = vars('ldap_settings');
deserialize(ldapSettings);
}
document.addEventListener('DOMContentLoaded', initialize);
return {};
})();

View File

@ -0,0 +1,158 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Legal settings page.
*
* This module implements the functionality of the legal settings page.
*/
App.Pages.LegalSettings = (function () {
const $saveSettings = $('#save-settings');
const $displayCookieNotice = $('#display-cookie-notice');
const $cookieNoticeContent = $('#cookie-notice-content');
const $displayTermsAndConditions = $('#display-terms-and-conditions');
const $termsAndConditionsContent = $('#terms-and-conditions-content');
const $displayPrivacyPolicy = $('#display-privacy-policy');
const $privacyPolicyContent = $('#privacy-policy-content');
/**
* Check if the form has invalid values.
*
* @return {Boolean}
*/
function isInvalid() {
try {
$('#legal-settings .is-invalid').removeClass('is-invalid');
// Validate required fields.
let missingRequiredFields = false;
$('#legal-settings .required').each((index, requiredField) => {
const $requiredField = $(requiredField);
if (!$requiredField.val()) {
$requiredField.addClass('is-invalid');
missingRequiredFields = true;
}
});
if (missingRequiredFields) {
throw new Error(lang('fields_are_required'));
}
return false;
} catch (error) {
App.Layouts.Backend.displayNotification(error.message);
return true;
}
}
function deserialize(legalSettings) {
legalSettings.forEach((legalSetting) => {
if (legalSetting.name === 'display_cookie_notice') {
$displayCookieNotice.prop('checked', Boolean(Number(legalSetting.value)));
}
if (legalSetting.name === 'cookie_notice_content') {
$cookieNoticeContent.trumbowyg('html', legalSetting.value);
}
if (legalSetting.name === 'display_terms_and_conditions') {
$displayTermsAndConditions.prop('checked', Boolean(Number(legalSetting.value)));
}
if (legalSetting.name === 'terms_and_conditions_content') {
$termsAndConditionsContent.trumbowyg('html', legalSetting.value);
}
if (legalSetting.name === 'display_privacy_policy') {
$displayPrivacyPolicy.prop('checked', Boolean(Number(legalSetting.value)));
}
if (legalSetting.name === 'privacy_policy_content') {
$privacyPolicyContent.trumbowyg('html', legalSetting.value);
}
});
}
function serialize() {
const legalSettings = [];
legalSettings.push({
name: 'display_cookie_notice',
value: $displayCookieNotice.prop('checked') ? '1' : '0',
});
legalSettings.push({
name: 'cookie_notice_content',
value: $cookieNoticeContent.trumbowyg('html'),
});
legalSettings.push({
name: 'display_terms_and_conditions',
value: $displayTermsAndConditions.prop('checked') ? '1' : '0',
});
legalSettings.push({
name: 'terms_and_conditions_content',
value: $termsAndConditionsContent.trumbowyg('html'),
});
legalSettings.push({
name: 'display_privacy_policy',
value: $displayPrivacyPolicy.prop('checked') ? '1' : '0',
});
legalSettings.push({
name: 'privacy_policy_content',
value: $privacyPolicyContent.trumbowyg('html'),
});
return legalSettings;
}
/**
* Save the account information.
*/
function onSaveSettingsClick() {
if (isInvalid()) {
App.Layouts.Backend.displayNotification(lang('settings_are_invalid'));
return;
}
const legalSettings = serialize();
App.Http.LegalSettings.save(legalSettings).done(() => {
App.Layouts.Backend.displayNotification(lang('settings_saved'));
});
}
/**
* Initialize the module.
*/
function initialize() {
App.Utils.UI.initializeTextEditor($cookieNoticeContent);
App.Utils.UI.initializeTextEditor($termsAndConditionsContent);
App.Utils.UI.initializeTextEditor($privacyPolicyContent);
const legalSettings = vars('legal_settings');
deserialize(legalSettings);
$saveSettings.on('click', onSaveSettingsClick);
}
document.addEventListener('DOMContentLoaded', initialize);
return {};
})();

56
assets/js/pages/login.js Normal file
View File

@ -0,0 +1,56 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Login page.
*
* This module implements the functionality of the login page.
*/
App.Pages.Login = (function () {
const $loginForm = $('#login-form');
const $username = $('#username');
const $password = $('#password');
/**
* Login Button "Click"
*
* Make an ajax call to the server and check whether the user's credentials are right.
*
* If yes then redirect him to his desired page, otherwise display a message.
*/
function onLoginFormSubmit(event) {
event.preventDefault();
const username = $username.val();
const password = $password.val();
if (!username || !password) {
return;
}
const $alert = $('.alert');
$alert.addClass('d-none');
App.Http.Login.validate(username, password).done((response) => {
if (response.success) {
window.location.href = vars('dest_url');
} else {
$alert.text(lang('login_failed'));
$alert.removeClass('d-none alert-danger alert-success').addClass('alert-danger');
}
});
}
$loginForm.on('submit', onLoginFormSubmit);
return {};
})();

View File

@ -0,0 +1,109 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Matomo Analytics settings page.
*
* This module implements the functionality of the Matomo Analytics settings page.
*/
App.Pages.MatomoAnalyticsSettings = (function () {
const $saveSettings = $('#save-settings');
/**
* Check if the form has invalid values.
*
* @return {Boolean}
*/
function isInvalid() {
try {
$('#matomo-analytics-settings .is-invalid').removeClass('is-invalid');
// Validate required fields.
let missingRequiredFields = false;
$('#matomo-analytics-settings .required').each((index, requiredField) => {
const $requiredField = $(requiredField);
if (!$requiredField.val()) {
$requiredField.addClass('is-invalid');
missingRequiredFields = true;
}
});
if (missingRequiredFields) {
throw new Error(lang('fields_are_required'));
}
return false;
} catch (error) {
App.Layouts.Backend.displayNotification(error.message);
return true;
}
}
function deserialize(matomoAnalyticsSettings) {
matomoAnalyticsSettings.forEach((matomoAnalyticsSetting) => {
const $field = $('[data-field="' + matomoAnalyticsSetting.name + '"]');
$field.is(':checkbox')
? $field.prop('checked', Boolean(Number(matomoAnalyticsSetting.value)))
: $field.val(matomoAnalyticsSetting.value);
});
}
function serialize() {
const matomoAnalyticsSettings = [];
$('[data-field]').each((index, field) => {
const $field = $(field);
matomoAnalyticsSettings.push({
name: $field.data('field'),
value: $field.is(':checkbox') ? Number($field.prop('checked')) : $field.val(),
});
});
return matomoAnalyticsSettings;
}
/**
* Save the account information.
*/
function onSaveSettingsClick() {
if (isInvalid()) {
App.Layouts.Backend.displayNotification(lang('settings_are_invalid'));
return;
}
const matomoAnalyticsSettings = serialize();
App.Http.MatomoAnalyticsSettings.save(matomoAnalyticsSettings).done(() => {
App.Layouts.Backend.displayNotification(lang('settings_saved'));
});
}
/**
* Initialize the module.
*/
function initialize() {
$saveSettings.on('click', onSaveSettingsClick);
const matomoAnalyticsSettings = vars('matomo_analytics_settings');
deserialize(matomoAnalyticsSettings);
}
document.addEventListener('DOMContentLoaded', initialize);
return {};
})();

View File

@ -0,0 +1,608 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Providers page.
*
* This module implements the functionality of the providers page.
*/
App.Pages.Providers = (function () {
const $providers = $('#providers');
const $id = $('#id');
const $firstName = $('#first-name');
const $lastName = $('#last-name');
const $email = $('#email');
const $mobileNumber = $('#mobile-number');
const $phoneNumber = $('#phone-number');
const $address = $('#address');
const $city = $('#city');
const $state = $('#state');
const $zipCode = $('#zip-code');
const $isPrivate = $('#is-private');
const $notes = $('#notes');
const $language = $('#language');
const $timezone = $('#timezone');
const $ldapDn = $('#ldap-dn');
const $username = $('#username');
const $password = $('#password');
const $passwordConfirmation = $('#password-confirm');
const $notifications = $('#notifications');
const $calendarView = $('#calendar-view');
const $filterProviders = $('#filter-providers');
let filterResults = {};
let filterLimit = 20;
let workingPlanManager;
/**
* Add the page event listeners.
*/
function addEventListeners() {
/**
* Event: Filter Providers Form "Submit"
*
* Filter the provider records with the given key string.
*
* @param {jQuery.Event} event
*/
$providers.on('submit', '#filter-providers form', (event) => {
event.preventDefault();
const key = $('#filter-providers .key').val();
$('.selected').removeClass('selected');
App.Pages.Providers.resetForm();
App.Pages.Providers.filter(key);
});
/**
* Event: Filter Provider Row "Click"
*
* Display the selected provider data to the user.
*/
$providers.on('click', '.provider-row', (event) => {
if ($filterProviders.find('.filter').prop('disabled')) {
$filterProviders.find('.results').css('color', '#AAA');
return; // Exit because we are currently on edit mode.
}
const providerId = $(event.currentTarget).attr('data-id');
const provider = filterResults.find((filterResult) => Number(filterResult.id) === Number(providerId));
App.Pages.Providers.display(provider);
$filterProviders.find('.selected').removeClass('selected');
$(event.currentTarget).addClass('selected');
$('#edit-provider, #delete-provider').prop('disabled', false);
});
/**
* Event: Add New Provider Button "Click"
*/
$providers.on('click', '#add-provider', () => {
App.Pages.Providers.resetForm();
$filterProviders.find('button').prop('disabled', true);
$filterProviders.find('.results').css('color', '#AAA');
$providers.find('.add-edit-delete-group').hide();
$providers.find('.save-cancel-group').show();
$providers.find('.record-details').find('input, select, textarea').prop('disabled', false);
$providers.find('.record-details .form-label span').prop('hidden', false);
$('#password, #password-confirm').addClass('required');
$providers
.find(
'.add-break, .edit-break, .delete-break, .add-working-plan-exception, .edit-working-plan-exception, .delete-working-plan-exception, #reset-working-plan',
)
.prop('disabled', false);
$('#provider-services input:checkbox').prop('disabled', false);
// Apply default working plan
const companyWorkingPlan = JSON.parse(vars('company_working_plan'));
workingPlanManager.setup(companyWorkingPlan);
workingPlanManager.timepickers(false);
});
/**
* Event: Edit Provider Button "Click"
*/
$providers.on('click', '#edit-provider', () => {
$providers.find('.add-edit-delete-group').hide();
$providers.find('.save-cancel-group').show();
$filterProviders.find('button').prop('disabled', true);
$filterProviders.find('.results').css('color', '#AAA');
$providers.find('.record-details').find('input, select, textarea').prop('disabled', false);
$providers.find('.record-details .form-label span').prop('hidden', false);
$('#password, #password-confirm').removeClass('required');
$('#provider-services input:checkbox').prop('disabled', false);
$providers
.find(
'.add-break, .edit-break, .delete-break, .add-working-plan-exception, .edit-working-plan-exception, .delete-working-plan-exception, #reset-working-plan',
)
.prop('disabled', false);
$('#providers input:checkbox').prop('disabled', false);
workingPlanManager.timepickers(false);
});
/**
* Event: Delete Provider Button "Click"
*/
$providers.on('click', '#delete-provider', () => {
const providerId = $id.val();
const buttons = [
{
text: lang('cancel'),
click: (event, messageModal) => {
messageModal.hide();
},
},
{
text: lang('delete'),
click: (event, messageModal) => {
App.Pages.Providers.remove(providerId);
messageModal.hide();
},
},
];
App.Utils.Message.show(lang('delete_provider'), lang('delete_record_prompt'), buttons);
});
/**
* Event: Save Provider Button "Click"
*/
$providers.on('click', '#save-provider', () => {
const provider = {
first_name: $firstName.val(),
last_name: $lastName.val(),
email: $email.val(),
mobile_number: $mobileNumber.val(),
phone_number: $phoneNumber.val(),
address: $address.val(),
city: $city.val(),
state: $state.val(),
zip_code: $zipCode.val(),
is_private: Number($isPrivate.prop('checked')),
notes: $notes.val(),
language: $language.val(),
timezone: $timezone.val(),
ldap_dn: $ldapDn.val(),
settings: {
username: $username.val(),
working_plan: JSON.stringify(workingPlanManager.get()),
working_plan_exceptions: JSON.stringify(workingPlanManager.getWorkingPlanExceptions()),
notifications: Number($notifications.prop('checked')),
calendar_view: $calendarView.val(),
},
};
// Include provider services.
provider.services = [];
$('#provider-services input:checkbox').each((index, checkboxEl) => {
if ($(checkboxEl).prop('checked')) {
provider.services.push($(checkboxEl).attr('data-id'));
}
});
// Include password if changed.
if ($password.val() !== '') {
provider.settings.password = $password.val();
}
// Include id if changed.
if ($id.val() !== '') {
provider.id = $id.val();
}
if (!App.Pages.Providers.validate()) {
return;
}
App.Pages.Providers.save(provider);
});
/**
* Event: Cancel Provider Button "Click"
*
* Cancel add or edit of an provider record.
*/
$providers.on('click', '#cancel-provider', () => {
const id = $('#filter-providers .selected').attr('data-id');
App.Pages.Providers.resetForm();
if (id) {
App.Pages.Providers.select(id, true);
}
});
/**
* Event: Reset Working Plan Button "Click".
*/
$providers.on('click', '#reset-working-plan', () => {
$('.breaks tbody').empty();
$('.working-plan-exceptions tbody').empty();
$('.work-start, .work-end').val('');
const companyWorkingPlan = JSON.parse(vars('company_working_plan'));
workingPlanManager.setup(companyWorkingPlan);
workingPlanManager.timepickers(false);
});
}
/**
* Save provider record to database.
*
* @param {Object} provider Contains the provider record data. If an 'id' value is provided
* then the update operation is going to be executed.
*/
function save(provider) {
App.Http.Providers.save(provider).then((response) => {
App.Layouts.Backend.displayNotification(lang('provider_saved'));
App.Pages.Providers.resetForm();
$('#filter-providers .key').val('');
App.Pages.Providers.filter('', response.id, true);
});
}
/**
* Delete a provider record from database.
*
* @param {Number} id Record id to be deleted.
*/
function remove(id) {
App.Http.Providers.destroy(id).then(() => {
App.Layouts.Backend.displayNotification(lang('provider_deleted'));
App.Pages.Providers.resetForm();
App.Pages.Providers.filter($('#filter-providers .key').val());
});
}
/**
* Validates a provider record.
*
* @return {Boolean} Returns the validation result.
*/
function validate() {
$providers.find('.is-invalid').removeClass('is-invalid');
$providers.find('.form-message').removeClass('alert-danger').hide();
try {
// Validate required fields.
let missingRequired = false;
$providers.find('.required').each((index, requiredFieldEl) => {
if (!$(requiredFieldEl).val()) {
$(requiredFieldEl).addClass('is-invalid');
missingRequired = true;
}
});
if (missingRequired) {
throw new Error(lang('fields_are_required'));
}
// Validate passwords.
if ($password.val() !== $passwordConfirmation.val()) {
$('#password, #password-confirm').addClass('is-invalid');
throw new Error(lang('passwords_mismatch'));
}
if ($password.val().length < vars('min_password_length') && $password.val() !== '') {
$('#password, #password-confirm').addClass('is-invalid');
throw new Error(lang('password_length_notice').replace('$number', vars('min_password_length')));
}
// Validate user email.
if (!App.Utils.Validation.email($email.val())) {
$email.addClass('is-invalid');
throw new Error(lang('invalid_email'));
}
// Validate phone number.
const phoneNumber = $phoneNumber.val();
if (phoneNumber && !App.Utils.Validation.phone(phoneNumber)) {
$phoneNumber.addClass('is-invalid');
throw new Error(lang('invalid_phone'));
}
// Validate mobile number.
const mobileNumber = $mobileNumber.val();
if (mobileNumber && !App.Utils.Validation.phone(mobileNumber)) {
$mobileNumber.addClass('is-invalid');
throw new Error(lang('invalid_phone'));
}
// Check if username exists
if ($username.attr('already-exists') === 'true') {
$username.addClass('is-invalid');
throw new Error(lang('username_already_exists'));
}
return true;
} catch (error) {
$('#providers .form-message').addClass('alert-danger').text(error.message).show();
return false;
}
}
/**
* Resets the provider tab form back to its initial state.
*/
function resetForm() {
$filterProviders.find('.selected').removeClass('selected');
$filterProviders.find('button').prop('disabled', false);
$filterProviders.find('.results').css('color', '');
$providers.find('.add-edit-delete-group').show();
$providers.find('.save-cancel-group').hide();
$providers.find('.record-details h4 a').remove();
$providers.find('.record-details').find('input, select, textarea').val('').prop('disabled', true);
$providers.find('.record-details .form-label span').prop('hidden', true);
$providers.find('.record-details #calendar-view').val('default');
$providers.find('.record-details #language').val(vars('default_language'));
$providers.find('.record-details #timezone').val(vars('default_timezone'));
$providers.find('.record-details #is-private').prop('checked', false);
$providers.find('.record-details #notifications').prop('checked', true);
$providers.find('.add-break, .add-working-plan-exception, #reset-working-plan').prop('disabled', true);
workingPlanManager.timepickers(true);
$providers.find('#providers .working-plan input:checkbox').prop('disabled', true);
$('.breaks').find('.edit-break, .delete-break').prop('disabled', true);
$('.working-plan-exceptions')
.find('.edit-working-plan-exception, .delete-working-plan-exception')
.prop('disabled', true);
$providers.find('.record-details .is-invalid').removeClass('is-invalid');
$providers.find('.record-details .form-message').hide();
$('#edit-provider, #delete-provider').prop('disabled', true);
$('#provider-services input:checkbox').prop('disabled', true).prop('checked', false);
$('#provider-services a').remove();
$('#providers .working-plan tbody').empty();
$('#providers .breaks tbody').empty();
$('#providers .working-plan-exceptions tbody').empty();
}
/**
* Display a provider record into the provider form.
*
* @param {Object} provider Contains the provider record data.
*/
function display(provider) {
$id.val(provider.id);
$firstName.val(provider.first_name);
$lastName.val(provider.last_name);
$email.val(provider.email);
$mobileNumber.val(provider.mobile_number);
$phoneNumber.val(provider.phone_number);
$address.val(provider.address);
$city.val(provider.city);
$state.val(provider.state);
$zipCode.val(provider.zip_code);
$isPrivate.prop('checked', provider.is_private);
$notes.val(provider.notes);
$language.val(provider.language);
$timezone.val(provider.timezone);
$ldapDn.val(provider.ldap_dn);
$username.val(provider.settings.username);
$calendarView.val(provider.settings.calendar_view);
$notifications.prop('checked', Boolean(Number(provider.settings.notifications)));
// Add dedicated provider link.
let dedicatedUrl = App.Utils.Url.siteUrl('?provider=' + encodeURIComponent(provider.id));
let $link = $('<a/>', {
'href': dedicatedUrl,
'target': '_blank',
'html': [
$('<i/>', {
'class': 'fas fa-link me-2',
}),
$('<span/>', {
'text': lang('booking_link'),
}),
],
});
$providers.find('.details-view h4').find('a').remove().end().append($link);
$('#provider-services a').remove();
$('#provider-services input:checkbox').prop('checked', false);
provider.services.forEach((providerServiceId) => {
const $checkbox = $('#provider-services input[data-id="' + providerServiceId + '"]');
if (!$checkbox.length) {
return;
}
$checkbox.prop('checked', true);
// Add dedicated service-provider link.
dedicatedUrl = App.Utils.Url.siteUrl(
'?provider=' + encodeURIComponent(provider.id) + '&service=' + encodeURIComponent(providerServiceId),
);
$link = $('<a/>', {
'href': dedicatedUrl,
'target': '_blank',
'html': [
$('<i/>', {
'class': 'fas fa-link me-2',
}),
$('<span/>', {
'text': lang('booking_link'),
}),
],
});
$checkbox.parent().append($link);
});
// Display working plan
const workingPlan = JSON.parse(provider.settings.working_plan);
workingPlanManager.setup(workingPlan);
$('.working-plan').find('input').prop('disabled', true);
$('.breaks').find('.edit-break, .delete-break').prop('disabled', true);
$providers.find('.working-plan-exceptions tbody').empty();
const workingPlanExceptions = JSON.parse(provider.settings.working_plan_exceptions);
workingPlanManager.setupWorkingPlanExceptions(workingPlanExceptions);
$('.working-plan-exceptions')
.find('.edit-working-plan-exception, .delete-working-plan-exception')
.prop('disabled', true);
$providers.find('.working-plan input:checkbox').prop('disabled', true);
}
/**
* Filters provider records depending a string keyword.
*
* @param {string} keyword This is used to filter the provider records of the database.
* @param {numeric} selectId Optional, if set, when the function is complete a result row can be set as selected.
* @param {bool} show Optional (false), if true the selected record will be also displayed.
*/
function filter(keyword, selectId = null, show = false) {
App.Http.Providers.search(keyword, filterLimit).then((response) => {
filterResults = response;
$filterProviders.find('.results').empty();
response.forEach((provider) => {
$('#filter-providers .results').append(App.Pages.Providers.getFilterHtml(provider)).append($('<hr/>'));
});
if (!response.length) {
$filterProviders.find('.results').append(
$('<em/>', {
'text': lang('no_records_found'),
}),
);
} else if (response.length === filterLimit) {
$('<button/>', {
'type': 'button',
'class': 'btn btn-outline-secondary w-100 load-more text-center',
'text': lang('load_more'),
'click': () => {
filterLimit += 20;
App.Pages.Providers.filter(keyword, selectId, show);
},
}).appendTo('#filter-providers .results');
}
if (selectId) {
App.Pages.Providers.select(selectId, show);
}
});
}
/**
* Get an provider row html code that is going to be displayed on the filter results list.
*
* @param {Object} provider Contains the provider record data.
*
* @return {String} The html code that represents the record on the filter results list.
*/
function getFilterHtml(provider) {
const name = provider.first_name + ' ' + provider.last_name;
let info = provider.email;
info = provider.mobile_number ? info + ', ' + provider.mobile_number : info;
info = provider.phone_number ? info + ', ' + provider.phone_number : info;
return $('<div/>', {
'class': 'provider-row entry',
'data-id': provider.id,
'html': [
$('<strong/>', {
'text': name,
}),
$('<br/>'),
$('<small/>', {
'class': 'text-muted',
'text': info,
}),
$('<br/>'),
],
});
}
/**
* Select and display a providers filter result on the form.
*
* @param {Number} id Record id to be selected.
* @param {Boolean} show Optional (false), if true the record will be displayed on the form.
*/
function select(id, show = false) {
// Select record in filter results.
$filterProviders.find('.provider-row[data-id="' + id + '"]').addClass('selected');
// Display record in form (if display = true).
if (show) {
const provider = filterResults.find((filterResult) => Number(filterResult.id) === Number(id));
App.Pages.Providers.display(provider);
$('#edit-provider, #delete-provider').prop('disabled', false);
}
}
/**
* Initialize the module.
*/
function initialize() {
workingPlanManager = new App.Utils.WorkingPlan();
workingPlanManager.addEventListeners();
App.Pages.Providers.resetForm();
App.Pages.Providers.filter('');
App.Pages.Providers.addEventListeners();
vars('services').forEach((service) => {
const checkboxId = `provider-service-${service.id}`;
$('<div/>', {
'class': 'checkbox',
'html': [
$('<div/>', {
'class': 'checkbox form-check',
'html': [
$('<input/>', {
'id': checkboxId,
'class': 'form-check-input',
'type': 'checkbox',
'data-id': service.id,
'prop': {
'disabled': true,
},
}),
$('<label/>', {
'class': 'form-check-label',
'text': service.name,
'for': checkboxId,
}),
],
}),
],
}).appendTo('#provider-services');
});
}
document.addEventListener('DOMContentLoaded', initialize);
return {
filter,
save,
remove,
validate,
getFilterHtml,
resetForm,
display,
select,
addEventListeners,
};
})();

View File

@ -0,0 +1,64 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Recovery page.
*
* This module implements the functionality of the recovery page.
*/
App.Pages.Recovery = (function () {
const $form = $('form');
const $username = $('#username');
const $email = $('#email');
const $getNewPassword = $('#get-new-password');
/**
* Event: Login Button "Click"
*
* Make an HTTP request to the server and check whether the user's credentials are right. If yes then redirect the
* user to the destination page, otherwise display an error message.
*/
function onFormSubmit(event) {
event.preventDefault();
const $alert = $('.alert');
$alert.addClass('d-none');
$getNewPassword.prop('disabled', true);
const username = $username.val();
const email = $email.val();
App.Http.Recovery.perform(username, email)
.done((response) => {
$alert.removeClass('d-none alert-danger alert-success');
if (response.success) {
$alert.addClass('alert-success');
$alert.text(lang('new_password_sent_with_email'));
} else {
$alert.addClass('alert-danger');
$alert.text(
'The operation failed! Please enter a valid username ' +
'and email address in order to get a new password.',
);
}
})
.always(() => {
$getNewPassword.prop('disabled', false);
});
}
$form.on('submit', onFormSubmit);
return {};
})();

View File

@ -0,0 +1,548 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Secretaries page.
*
* This module implements the functionality of the secretaries page.
*/
App.Pages.Secretaries = (function () {
const $secretaries = $('#secretaries');
const $id = $('#id');
const $firstName = $('#first-name');
const $lastName = $('#last-name');
const $email = $('#email');
const $mobileNumber = $('#mobile-number');
const $phoneNumber = $('#phone-number');
const $address = $('#address');
const $city = $('#city');
const $state = $('#state');
const $zipCode = $('#zip-code');
const $notes = $('#notes');
const $language = $('#language');
const $timezone = $('#timezone');
const $ldapDn = $('#ldap-dn');
const $username = $('#username');
const $password = $('#password');
const $passwordConfirmation = $('#password-confirm');
const $notifications = $('#notifications');
const $calendarView = $('#calendar-view');
const $filterSecretaries = $('#filter-secretaries');
let filterResults = {};
let filterLimit = 20;
/**
* Add the page event listeners.
*/
function addEventListeners() {
/**
* Event: Admin Username "Blur"
*
* When the admin leaves the username input field we will need to check if the username
* is not taken by another record in the system.
*
* @param {jQuery.Event} event
*/
$secretaries.on('blur', '#username', (event) => {
const $input = $(event.target);
if ($input.prop('readonly') === true || $input.val() === '') {
return;
}
const secretaryId = $input.parents().eq(2).find('.record-id').val();
if (!secretaryId) {
return;
}
const username = $input.val();
App.Http.Account.validateUsername(secretaryId, username).done((response) => {
if (response.is_valid === 'false') {
$input.addClass('is-invalid');
$input.attr('already-exists', 'true');
$input.parents().eq(3).find('.form-message').text(lang('username_already_exists'));
$input.parents().eq(3).find('.form-message').show();
} else {
$input.removeClass('is-invalid');
$input.attr('already-exists', 'false');
if ($input.parents().eq(3).find('.form-message').text() === lang('username_already_exists')) {
$input.parents().eq(3).find('.form-message').hide();
}
}
});
});
/**
* Event: Filter Secretaries Form "Submit"
*
* Filter the secretary records with the given key string.
*
* @param {jQuery.Event} event
*/
$secretaries.on('submit', '#filter-secretaries form', (event) => {
event.preventDefault();
const key = $('#filter-secretaries .key').val();
$filterSecretaries.find('.selected').removeClass('selected');
App.Pages.Secretaries.resetForm();
App.Pages.Secretaries.filter(key);
});
/**
* Event: Filter Secretary Row "Click"
*
* Display the selected secretary data to the user.
*/
$secretaries.on('click', '.secretary-row', (event) => {
if ($('#filter-secretaries .filter').prop('disabled')) {
$('#filter-secretaries .results').css('color', '#AAA');
return; // exit because we are currently on edit mode
}
const secretaryId = $(event.currentTarget).attr('data-id');
const secretary = filterResults.find((filterResult) => Number(filterResult.id) === Number(secretaryId));
App.Pages.Secretaries.display(secretary);
$('#filter-secretaries .selected').removeClass('selected');
$(event.currentTarget).addClass('selected');
$('#edit-secretary, #delete-secretary').prop('disabled', false);
});
/**
* Event: Add New Secretary Button "Click"
*/
$secretaries.on('click', '#add-secretary', () => {
App.Pages.Secretaries.resetForm();
$filterSecretaries.find('button').prop('disabled', true);
$filterSecretaries.find('.results').css('color', '#AAA');
$secretaries.find('.add-edit-delete-group').hide();
$secretaries.find('.save-cancel-group').show();
$secretaries.find('.record-details').find('input, select, textarea').prop('disabled', false);
$secretaries.find('.record-details .form-label span').prop('hidden', false);
$('#password, #password-confirm').addClass('required');
$('#secretary-providers input:checkbox').prop('disabled', false);
});
/**
* Event: Edit Secretary Button "Click"
*/
$secretaries.on('click', '#edit-secretary', () => {
$filterSecretaries.find('button').prop('disabled', true);
$filterSecretaries.find('.results').css('color', '#AAA');
$secretaries.find('.add-edit-delete-group').hide();
$secretaries.find('.save-cancel-group').show();
$secretaries.find('.record-details').find('input, select, textarea').prop('disabled', false);
$secretaries.find('.record-details .form-label span').prop('hidden', false);
$('#password, #password-confirm').removeClass('required');
$('#secretary-providers input:checkbox').prop('disabled', false);
});
/**
* Event: Delete Secretary Button "Click"
*/
$secretaries.on('click', '#delete-secretary', () => {
const secretaryId = $id.val();
const buttons = [
{
text: lang('cancel'),
click: (event, messageModal) => {
messageModal.hide();
},
},
{
text: lang('delete'),
click: (event, messageModal) => {
remove(secretaryId);
messageModal.hide();
},
},
];
App.Utils.Message.show(lang('delete_secretary'), lang('delete_record_prompt'), buttons);
});
/**
* Event: Save Secretary Button "Click"
*/
$secretaries.on('click', '#save-secretary', () => {
const secretary = {
first_name: $firstName.val(),
last_name: $lastName.val(),
email: $email.val(),
mobile_number: $mobileNumber.val(),
phone_number: $phoneNumber.val(),
address: $address.val(),
city: $city.val(),
state: $state.val(),
zip_code: $zipCode.val(),
notes: $notes.val(),
language: $language.val(),
timezone: $timezone.val(),
ldap_dn: $ldapDn.val(),
settings: {
username: $username.val(),
notifications: Number($notifications.prop('checked')),
calendar_view: $calendarView.val(),
},
};
// Include secretary services.
secretary.providers = [];
$('#secretary-providers input:checkbox').each((index, checkbox) => {
if ($(checkbox).prop('checked')) {
secretary.providers.push($(checkbox).attr('data-id'));
}
});
// Include password if changed.
if ($password.val() !== '') {
secretary.settings.password = $password.val();
}
// Include ID if changed.
if ($id.val() !== '') {
secretary.id = $id.val();
}
if (!App.Pages.Secretaries.validate()) {
return;
}
App.Pages.Secretaries.save(secretary);
});
/**
* Event: Cancel Secretary Button "Click"
*
* Cancel add or edit of an secretary record.
*/
$secretaries.on('click', '#cancel-secretary', () => {
const id = $id.val();
resetForm();
if (id) {
select(id, true);
}
});
}
/**
* Save secretary record to database.
*
* @param {Object} secretary Contains the secretary record data. If an 'id' value is provided
* then the update operation is going to be executed.
*/
function save(secretary) {
App.Http.Secretaries.save(secretary).done((response) => {
App.Layouts.Backend.displayNotification(lang('secretary_saved'));
App.Pages.Secretaries.resetForm();
$('#filter-secretaries .key').val('');
App.Pages.Secretaries.filter('', response.id, true);
});
}
/**
* Delete a secretary record from database.
*
* @param {Number} id Record id to be deleted.
*/
function remove(id) {
App.Http.Secretaries.destroy(id).done(() => {
App.Layouts.Backend.displayNotification(lang('secretary_deleted'));
App.Pages.Secretaries.resetForm();
App.Pages.Secretaries.filter($('#filter-secretaries .key').val());
});
}
/**
* Validates a secretary record.
*
* @return {Boolean} Returns the validation result.
*/
function validate() {
$('#secretaries .is-invalid').removeClass('is-invalid');
$secretaries.find('.form-message').removeClass('alert-danger');
try {
// Validate required fields.
let missingRequired = false;
$secretaries.find('.required').each((index, requiredField) => {
if (!$(requiredField).val()) {
$(requiredField).addClass('is-invalid');
missingRequired = true;
}
});
if (missingRequired) {
throw new Error(lang('fields_are_required'));
}
// Validate passwords.
if ($password.val() !== $passwordConfirmation.val()) {
$('#password, #password-confirm').addClass('is-invalid');
throw new Error(lang('passwords_mismatch'));
}
if ($password.val().length < vars('min_password_length') && $password.val() !== '') {
$('#password, #password-confirm').addClass('is-invalid');
throw new Error(lang('password_length_notice').replace('$number', vars('min_password_length')));
}
// Validate user email.
if (!App.Utils.Validation.email($email.val())) {
$email.addClass('is-invalid');
throw new Error(lang('invalid_email'));
}
// Validate phone number.
const phoneNumber = $phoneNumber.val();
if (phoneNumber && !App.Utils.Validation.phone(phoneNumber)) {
$phoneNumber.addClass('is-invalid');
throw new Error(lang('invalid_phone'));
}
// Validate mobile number.
const mobileNumber = $mobileNumber.val();
if (mobileNumber && !App.Utils.Validation.phone(mobileNumber)) {
$mobileNumber.addClass('is-invalid');
throw new Error(lang('invalid_phone'));
}
// Check if username exists
if ($username.attr('already-exists') === 'true') {
$username.addClass('is-invalid');
throw new Error(lang('username_already_exists'));
}
return true;
} catch (error) {
$('#secretaries .form-message').addClass('alert-danger').text(error.message).show();
return false;
}
}
/**
* Resets the secretary tab form back to its initial state.
*/
function resetForm() {
$filterSecretaries.find('.selected').removeClass('selected');
$filterSecretaries.find('button').prop('disabled', false);
$filterSecretaries.find('.results').css('color', '');
$secretaries.find('.record-details').find('input, select, textarea').val('').prop('disabled', true);
$secretaries.find('.record-details .form-label span').prop('hidden', true);
$secretaries.find('.record-details #calendar-view').val('default');
$secretaries.find('.record-details #timezone').val(vars('default_timezone'));
$secretaries.find('.record-details #language').val(vars('default_language'));
$secretaries.find('.record-details #notifications').prop('checked', true);
$secretaries.find('.add-edit-delete-group').show();
$secretaries.find('.save-cancel-group').hide();
$secretaries.find('.form-message').hide();
$secretaries.find('.is-invalid').removeClass('is-invalid');
$('#edit-secretary, #delete-secretary').prop('disabled', true);
$('#secretary-providers input:checkbox').prop('disabled', true).prop('checked', false);
}
/**
* Display a secretary record into the secretary form.
*
* @param {Object} secretary Contains the secretary record data.
*/
function display(secretary) {
$id.val(secretary.id);
$firstName.val(secretary.first_name);
$lastName.val(secretary.last_name);
$email.val(secretary.email);
$mobileNumber.val(secretary.mobile_number);
$phoneNumber.val(secretary.phone_number);
$address.val(secretary.address);
$city.val(secretary.city);
$state.val(secretary.state);
$zipCode.val(secretary.zip_code);
$notes.val(secretary.notes);
$language.val(secretary.language);
$timezone.val(secretary.timezone);
$ldapDn.val(secretary.ldap_dn);
$username.val(secretary.settings.username);
$calendarView.val(secretary.settings.calendar_view);
$notifications.prop('checked', Boolean(Number(secretary.settings.notifications)));
$('#secretary-providers input:checkbox').prop('checked', false);
secretary.providers.forEach((secretaryProviderId) => {
const $checkbox = $('#secretary-providers input[data-id="' + secretaryProviderId + '"]');
if (!$checkbox.length) {
return;
}
$checkbox.prop('checked', true);
});
}
/**
* Filters secretary records based on a string keyword.
*
* @param {String} keyword This is used to filter the secretary records of the database.
* @param {Number} selectId Optional, if provided the given ID will be selected in the filter results
* (only selected, not displayed).
* @param {Boolean} show Optional (false).
*/
function filter(keyword, selectId = null, show = false) {
App.Http.Secretaries.search(keyword, filterLimit).done((response) => {
filterResults = response;
$filterSecretaries.find('.results').empty();
response.forEach((secretary) => {
$filterSecretaries
.find('.results')
.append(App.Pages.Secretaries.getFilterHtml(secretary))
.append($('<hr/>'));
});
if (!response.length) {
$('#filter-secretaries .results').append(
$('<em/>', {
'text': lang('no_records_found'),
}),
);
} else if (response.length === filterLimit) {
$('<button/>', {
'type': 'button',
'class': 'btn btn-outline-secondary w-100 load-more text-center',
'text': lang('load_more'),
'click': () => {
filterLimit += 20;
App.Pages.Customers.filter(keyword, selectId, show);
},
}).appendTo('#filter-secretaries .results');
}
if (selectId) {
select(selectId, show);
}
});
}
/**
* Get an secretary row html code that is going to be displayed on the filter results list.
*
* @param {Object} secretary Contains the secretary record data.
*
* @return {String} The html code that represents the record on the filter results list.
*/
function getFilterHtml(secretary) {
const name = secretary.first_name + ' ' + secretary.last_name;
let info = secretary.email;
info = secretary.mobile_number ? info + ', ' + secretary.mobile_number : info;
info = secretary.phone_number ? info + ', ' + secretary.phone_number : info;
return $('<div/>', {
'class': 'secretary-row entry',
'data-id': secretary.id,
'html': [
$('<strong/>', {
'text': name,
}),
$('<br/>'),
$('<small/>', {
'class': 'text-muted',
'text': info,
}),
$('<br/>'),
],
});
}
/**
* Select a specific record from the current filter results. If the secretary id does not exist
* in the list then no record will be selected.
*
* @param {Number} id The record id to be selected from the filter results.
* @param {Boolean} show Optional (false), if true the method will display the record in the form.
*/
function select(id, show = false) {
$filterSecretaries.find('.selected').removeClass('selected');
$('#filter-secretaries .secretary-row[data-id="' + id + '"]').addClass('selected');
if (show) {
const secretary = filterResults.find((filterResult) => Number(filterResult.id) === Number(id));
App.Pages.Secretaries.display(secretary);
$('#edit-secretary, #delete-secretary').prop('disabled', false);
}
}
/**
* Initialize the module.
*/
function initialize() {
App.Pages.Secretaries.resetForm();
App.Pages.Secretaries.filter('');
App.Pages.Secretaries.addEventListeners();
vars('providers').forEach((provider) => {
const checkboxId = `provider-service-${provider.id}`;
$('<div/>', {
'class': 'checkbox',
'html': [
$('<div/>', {
'class': 'checkbox form-check',
'html': [
$('<input/>', {
'id': checkboxId,
'class': 'form-check-input',
'type': 'checkbox',
'data-id': provider.id,
'prop': {
'disabled': true,
},
}),
$('<label/>', {
'class': 'form-check-label',
'text': provider.first_name + ' ' + provider.last_name,
'for': checkboxId,
}),
],
}),
],
}).appendTo('#secretary-providers');
});
}
document.addEventListener('DOMContentLoaded', initialize);
return {
filter,
save,
remove,
validate,
getFilterHtml,
resetForm,
display,
select,
addEventListeners,
};
})();

View File

@ -0,0 +1,344 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Service-categories page.
*
* This module implements the functionality of the service-categories page.
*/
App.Pages.ServiceCategories = (function () {
const $serviceCategories = $('#service-categories');
const $filterServiceCategories = $('#filter-service-categories');
const $id = $('#id');
const $name = $('#name');
const $description = $('#description');
let filterResults = {};
let filterLimit = 20;
/**
* Add the page event listeners.
*/
function addEventListeners() {
/**
* Event: Filter Service-Categories Form "Submit"
*
* @param {jQuery.Event} event
*/
$serviceCategories.on('submit', '#filter-service-categories form', (event) => {
event.preventDefault();
const key = $('#filter-service-categories .key').val();
$('.selected').removeClass('selected');
App.Pages.ServiceCategories.resetForm();
App.Pages.ServiceCategories.filter(key);
});
/**
* Event: Filter Service-Categories Row "Click"
*
* Displays the selected row data on the right side of the page.
*
* @param {jQuery.Event} event
*/
$serviceCategories.on('click', '.service-category-row', (event) => {
if ($('#filter-service-categories .filter').prop('disabled')) {
$('#filter-service-categories .results').css('color', '#AAA');
return; // exit because we are on edit mode
}
const serviceCategoryId = $(event.currentTarget).attr('data-id');
const serviceCategory = filterResults.find(
(filterResult) => Number(filterResult.id) === Number(serviceCategoryId),
);
App.Pages.ServiceCategories.display(serviceCategory);
$('#filter-service-categories .selected').removeClass('selected');
$(event.currentTarget).addClass('selected');
$('#edit-service-category, #delete-service-category').prop('disabled', false);
});
/**
* Event: Add Service-Category Button "Click"
*/
$serviceCategories.on('click', '#add-service-category', () => {
App.Pages.ServiceCategories.resetForm();
$serviceCategories.find('.add-edit-delete-group').hide();
$serviceCategories.find('.save-cancel-group').show();
$serviceCategories.find('.record-details').find('input, select, textarea').prop('disabled', false);
$serviceCategories.find('.record-details .form-label span').prop('hidden', false);
$filterServiceCategories.find('button').prop('disabled', true);
$filterServiceCategories.find('.results').css('color', '#AAA');
});
/**
* Event: Edit Service-Category Button "Click"
*/
$serviceCategories.on('click', '#edit-service-category', () => {
$serviceCategories.find('.add-edit-delete-group').hide();
$serviceCategories.find('.save-cancel-group').show();
$serviceCategories.find('.record-details').find('input, select, textarea').prop('disabled', false);
$serviceCategories.find('.record-details .form-label span').prop('hidden', false);
$filterServiceCategories.find('button').prop('disabled', true);
$filterServiceCategories.find('.results').css('color', '#AAA');
});
/**
* Event: Delete Service-Category Button "Click"
*/
$serviceCategories.on('click', '#delete-service-category', () => {
const serviceCategoryId = $id.val();
const buttons = [
{
text: lang('cancel'),
click: (event, messageModal) => {
messageModal.hide();
},
},
{
text: lang('delete'),
click: (event, messageModal) => {
remove(serviceCategoryId);
messageModal.hide();
},
},
];
App.Utils.Message.show(lang('delete_service_category'), lang('delete_record_prompt'), buttons);
});
/**
* Event: Categories Save Button "Click"
*/
$serviceCategories.on('click', '#save-service-category', () => {
const serviceCategory = {
name: $name.val(),
description: $description.val(),
};
if ($id.val() !== '') {
serviceCategory.id = $id.val();
}
if (!validate()) {
return;
}
App.Pages.ServiceCategories.save(serviceCategory);
});
/**
* Event: Cancel Service-Category Button "Click"
*/
$serviceCategories.on('click', '#cancel-service-category', () => {
const id = $id.val();
App.Pages.ServiceCategories.resetForm();
if (id !== '') {
select(id, true);
}
});
}
/**
* Filter service categories records.
*
* @param {String} keyword This key string is used to filter the service-category records.
* @param {Number} selectId Optional, if set then after the filter operation the record with the given
* ID will be selected (but not displayed).
* @param {Boolean} show Optional (false), if true then the selected record will be displayed on the form.
*/
function filter(keyword, selectId = null, show = false) {
App.Http.ServiceCategories.search(keyword, filterLimit).then((response) => {
filterResults = response;
$('#filter-service-categories .results').empty();
response.forEach((serviceCategory) => {
$('#filter-service-categories .results')
.append(App.Pages.ServiceCategories.getFilterHtml(serviceCategory))
.append($('<hr/>'));
});
if (response.length === 0) {
$('#filter-service-categories .results').append(
$('<em/>', {
'text': lang('no_records_found'),
}),
);
} else if (response.length === filterLimit) {
$('<button/>', {
'type': 'button',
'class': 'btn btn-outline-secondary w-100 load-more text-center',
'text': lang('load_more'),
'click': () => {
filterLimit += 20;
App.Pages.ServiceCategories.filter(keyword, selectId, show);
},
}).appendTo('#filter-service-categories .results');
}
if (selectId) {
select(selectId, show);
}
});
}
/**
* Save a service-category record to the database (via AJAX post).
*
* @param {Object} serviceCategory Contains the service-category data.
*/
function save(serviceCategory) {
App.Http.ServiceCategories.save(serviceCategory).then((response) => {
App.Layouts.Backend.displayNotification(lang('service_category_saved'));
App.Pages.ServiceCategories.resetForm();
$filterServiceCategories.find('.key').val('');
App.Pages.ServiceCategories.filter('', response.id, true);
});
}
/**
* Delete service-category record.
*
* @param {Number} id Record ID to be deleted.
*/
function remove(id) {
App.Http.ServiceCategories.destroy(id).then(() => {
App.Layouts.Backend.displayNotification(lang('service_category_deleted'));
App.Pages.ServiceCategories.resetForm();
App.Pages.ServiceCategories.filter($('#filter-service-categories .key').val());
});
}
/**
* Display a service-category record on the form.
*
* @param {Object} serviceCategory Contains the service-category data.
*/
function display(serviceCategory) {
$id.val(serviceCategory.id);
$name.val(serviceCategory.name);
$description.val(serviceCategory.description);
}
/**
* Validate service-category data before save (insert or update).
*
* @return {Boolean} Returns the validation result.
*/
function validate() {
$serviceCategories.find('.is-invalid').removeClass('is-invalid');
$serviceCategories.find('.form-message').removeClass('alert-danger').hide();
try {
let missingRequired = false;
$serviceCategories.find('.required').each((index, fieldEl) => {
if (!$(fieldEl).val()) {
$(fieldEl).addClass('is-invalid');
missingRequired = true;
}
});
if (missingRequired) {
throw new Error(lang('fields_are_required'));
}
return true;
} catch (error) {
$serviceCategories.find('.form-message').addClass('alert-danger').text(error.message).show();
return false;
}
}
/**
* Bring the service-category form back to its initial state.
*/
function resetForm() {
$filterServiceCategories.find('.selected').removeClass('selected');
$filterServiceCategories.find('button').prop('disabled', false);
$filterServiceCategories.find('.results').css('color', '');
$serviceCategories.find('.add-edit-delete-group').show();
$serviceCategories.find('.save-cancel-group').hide();
$serviceCategories.find('.record-details').find('input, select, textarea').val('').prop('disabled', true);
$serviceCategories.find('.record-details .form-label span').prop('hidden', true);
$('#edit-service-category, #delete-service-category').prop('disabled', true);
$serviceCategories.find('.record-details .is-invalid').removeClass('is-invalid');
$serviceCategories.find('.record-details .form-message').hide();
}
/**
* Get the filter results row HTML code.
*
* @param {Object} serviceCategory Contains the service-category data.
*
* @return {String} Returns the record HTML code.
*/
function getFilterHtml(serviceCategory) {
return $('<div/>', {
'class': 'service-category-row entry',
'data-id': serviceCategory.id,
'html': [
$('<strong/>', {
'text': serviceCategory.name,
}),
$('<br/>'),
],
});
}
/**
* Select a specific record from the current filter results.
*
* If the service-category ID does not exist in the list then no record will be selected.
*
* @param {Number} id The record ID to be selected from the filter results.
* @param {Boolean} show Optional (false), if true then the method will display the record on the form.
*/
function select(id, show = false) {
$filterServiceCategories.find('.selected').removeClass('selected');
$filterServiceCategories.find('.service-category-row[data-id="' + id + '"]').addClass('selected');
if (show) {
const serviceCategory = filterResults.find((serviceCategory) => Number(serviceCategory.id) === Number(id));
App.Pages.ServiceCategories.display(serviceCategory);
$('#edit-service-category, #delete-service-category').prop('disabled', false);
}
}
/**
* Initialize the module.
*/
function initialize() {
App.Pages.ServiceCategories.resetForm();
App.Pages.ServiceCategories.filter('');
App.Pages.ServiceCategories.addEventListeners();
}
document.addEventListener('DOMContentLoaded', initialize);
return {
filter,
save,
remove,
validate,
getFilterHtml,
resetForm,
display,
select,
addEventListeners,
};
})();

441
assets/js/pages/services.js Normal file
View File

@ -0,0 +1,441 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Services page.
*
* This module implements the functionality of the services page.
*/
App.Pages.Services = (function () {
const $services = $('#services');
const $id = $('#id');
const $name = $('#name');
const $duration = $('#duration');
const $price = $('#price');
const $currency = $('#currency');
const $serviceCategoryId = $('#service-category-id');
const $availabilitiesType = $('#availabilities-type');
const $attendantsNumber = $('#attendants-number');
const $isPrivate = $('#is-private');
const $location = $('#location');
const $description = $('#description');
const $filterServices = $('#filter-services');
const $color = $('#color');
let filterResults = {};
let filterLimit = 20;
/**
* Add page event listeners.
*/
function addEventListeners() {
/**
* Event: Filter Services Form "Submit"
*
* @param {jQuery.Event} event
*/
$services.on('submit', '#filter-services form', (event) => {
event.preventDefault();
const key = $filterServices.find('.key').val();
$filterServices.find('.selected').removeClass('selected');
App.Pages.Services.resetForm();
App.Pages.Services.filter(key);
});
/**
* Event: Filter Service Row "Click"
*
* Display the selected service data to the user.
*/
$services.on('click', '.service-row', (event) => {
if ($filterServices.find('.filter').prop('disabled')) {
$filterServices.find('.results').css('color', '#AAA');
return; // exit because we are on edit mode
}
const serviceId = $(event.currentTarget).attr('data-id');
const service = filterResults.find((filterResult) => Number(filterResult.id) === Number(serviceId));
// Add dedicated provider link.
const dedicatedUrl = App.Utils.Url.siteUrl('?service=' + encodeURIComponent(service.id));
const $link = $('<a/>', {
'href': dedicatedUrl,
'target': '_blank',
'html': [
$('<i/>', {
'class': 'fas fa-link me-2',
}),
$('<span/>', {
'text': lang('booking_link'),
}),
],
});
$services.find('.record-details h4').find('a').remove().end().append($link);
App.Pages.Services.display(service);
$filterServices.find('.selected').removeClass('selected');
$(event.currentTarget).addClass('selected');
$('#edit-service, #delete-service').prop('disabled', false);
});
/**
* Event: Add New Service Button "Click"
*/
$services.on('click', '#add-service', () => {
App.Pages.Services.resetForm();
$services.find('.add-edit-delete-group').hide();
$services.find('.save-cancel-group').show();
$services.find('.record-details').find('input, select, textarea').prop('disabled', false);
$services.find('.record-details .form-label span').prop('hidden', false);
$filterServices.find('button').prop('disabled', true);
$filterServices.find('.results').css('color', '#AAA');
App.Components.ColorSelection.enable($color);
// Default values
$name.val('Service');
$duration.val('30');
$price.val('0');
$currency.val('');
$serviceCategoryId.val('');
$availabilitiesType.val('flexible');
$attendantsNumber.val('1');
});
/**
* Event: Cancel Service Button "Click"
*
* Cancel add or edit of a service record.
*/
$services.on('click', '#cancel-service', () => {
const id = $id.val();
App.Pages.Services.resetForm();
if (id !== '') {
App.Pages.Services.select(id, true);
}
});
/**
* Event: Save Service Button "Click"
*/
$services.on('click', '#save-service', () => {
const service = {
name: $name.val(),
duration: $duration.val(),
price: $price.val(),
currency: $currency.val(),
description: $description.val(),
location: $location.val(),
color: App.Components.ColorSelection.getColor($color),
availabilities_type: $availabilitiesType.val(),
attendants_number: $attendantsNumber.val(),
is_private: Number($isPrivate.prop('checked')),
id_service_categories: $serviceCategoryId.val() || undefined,
};
if ($id.val() !== '') {
service.id = $id.val();
}
if (!App.Pages.Services.validate()) {
return;
}
App.Pages.Services.save(service);
});
/**
* Event: Edit Service Button "Click"
*/
$services.on('click', '#edit-service', () => {
$services.find('.add-edit-delete-group').hide();
$services.find('.save-cancel-group').show();
$services.find('.record-details').find('input, select, textarea').prop('disabled', false);
$services.find('.record-details .form-label span').prop('hidden', false);
$filterServices.find('button').prop('disabled', true);
$filterServices.find('.results').css('color', '#AAA');
App.Components.ColorSelection.enable($color);
});
/**
* Event: Delete Service Button "Click"
*/
$services.on('click', '#delete-service', () => {
const serviceId = $id.val();
const buttons = [
{
text: lang('cancel'),
click: (event, messageModal) => {
messageModal.hide();
},
},
{
text: lang('delete'),
click: (event, messageModal) => {
App.Pages.Services.remove(serviceId);
messageModal.hide();
},
},
];
App.Utils.Message.show(lang('delete_service'), lang('delete_record_prompt'), buttons);
});
}
/**
* Save service record to database.
*
* @param {Object} service Contains the service record data. If an 'id' value is provided
* then the update operation is going to be executed.
*/
function save(service) {
App.Http.Services.save(service).then((response) => {
App.Layouts.Backend.displayNotification(lang('service_saved'));
App.Pages.Services.resetForm();
$filterServices.find('.key').val('');
App.Pages.Services.filter('', response.id, true);
});
}
/**
* Delete a service record from database.
*
* @param {Number} id Record ID to be deleted.
*/
function remove(id) {
App.Http.Services.destroy(id).then(() => {
App.Layouts.Backend.displayNotification(lang('service_deleted'));
App.Pages.Services.resetForm();
App.Pages.Services.filter($filterServices.find('.key').val());
});
}
/**
* Validates a service record.
*
* @return {Boolean} Returns the validation result.
*/
function validate() {
$services.find('.is-invalid').removeClass('is-invalid');
$services.find('.form-message').removeClass('alert-danger').hide();
try {
// Validate required fields.
let missingRequired = false;
$services.find('.required').each((index, requiredField) => {
if (!$(requiredField).val()) {
$(requiredField).addClass('is-invalid');
missingRequired = true;
}
});
if (missingRequired) {
throw new Error(lang('fields_are_required'));
}
// Validate the duration.
if (Number($duration.val()) < vars('event_minimum_duration')) {
$duration.addClass('is-invalid');
throw new Error(lang('invalid_duration'));
}
return true;
} catch (error) {
$services.find('.form-message').addClass('alert-danger').text(error.message).show();
return false;
}
}
/**
* Resets the service tab form back to its initial state.
*/
function resetForm() {
$filterServices.find('.selected').removeClass('selected');
$filterServices.find('button').prop('disabled', false);
$filterServices.find('.results').css('color', '');
$services.find('.record-details').find('input, select, textarea').val('').prop('disabled', true);
$services.find('.record-details .form-label span').prop('hidden', true);
$services.find('.record-details #is-private').prop('checked', false);
$services.find('.record-details h4 a').remove();
$services.find('.add-edit-delete-group').show();
$services.find('.save-cancel-group').hide();
$('#edit-service, #delete-service').prop('disabled', true);
$services.find('.record-details .is-invalid').removeClass('is-invalid');
$services.find('.record-details .form-message').hide();
App.Components.ColorSelection.disable($color);
}
/**
* Display a service record into the service form.
*
* @param {Object} service Contains the service record data.
*/
function display(service) {
$id.val(service.id);
$name.val(service.name);
$duration.val(service.duration);
$price.val(service.price);
$currency.val(service.currency);
$description.val(service.description);
$location.val(service.location);
$availabilitiesType.val(service.availabilities_type);
$attendantsNumber.val(service.attendants_number);
$isPrivate.prop('checked', service.is_private);
App.Components.ColorSelection.setColor($color, service.color);
const serviceCategoryId = service.id_service_categories !== null ? service.id_service_categories : '';
$serviceCategoryId.val(serviceCategoryId);
}
/**
* Filters service records depending on a string keyword.
*
* @param {String} keyword This is used to filter the service records of the database.
* @param {Number} selectId Optional, if set then after the filter operation the record with this
* ID will be selected (but not displayed).
* @param {Boolean} show Optional (false), if true then the selected record will be displayed on the form.
*/
function filter(keyword, selectId = null, show = false) {
App.Http.Services.search(keyword, filterLimit).then((response) => {
filterResults = response;
$filterServices.find('.results').empty();
response.forEach((service) => {
$filterServices.find('.results').append(App.Pages.Services.getFilterHtml(service)).append($('<hr/>'));
});
if (response.length === 0) {
$filterServices.find('.results').append(
$('<em/>', {
'text': lang('no_records_found'),
}),
);
} else if (response.length === filterLimit) {
$('<button/>', {
'type': 'button',
'class': 'btn btn-outline-secondary w-100 load-more text-center',
'text': lang('load_more'),
'click': () => {
filterLimit += 20;
App.Pages.Services.filter(keyword, selectId, show);
},
}).appendTo('#filter-services .results');
}
if (selectId) {
App.Pages.Services.select(selectId, show);
}
});
}
/**
* Get Filter HTML
*
* Get a service row HTML code that is going to be displayed on the filter results list.
*
* @param {Object} service Contains the service record data.
*
* @return {String} The HTML code that represents the record on the filter results list.
*/
function getFilterHtml(service) {
const name = service.name;
const info = service.duration + ' min - ' + service.price + ' ' + service.currency;
return $('<div/>', {
'class': 'service-row entry',
'data-id': service.id,
'html': [
$('<strong/>', {
'text': name,
}),
$('<br/>'),
$('<small/>', {
'class': 'text-muted',
'text': info,
}),
$('<br/>'),
],
});
}
/**
* Select a specific record from the current filter results. If the service id does not exist
* in the list then no record will be selected.
*
* @param {Number} id The record id to be selected from the filter results.
* @param {Boolean} show Optional (false), if true then the method will display the record on the form.
*/
function select(id, show = false) {
$filterServices.find('.selected').removeClass('selected');
$filterServices.find('.service-row[data-id="' + id + '"]').addClass('selected');
if (show) {
const service = filterResults.find((filterResult) => Number(filterResult.id) === Number(id));
App.Pages.Services.display(service);
$('#edit-service, #delete-service').prop('disabled', false);
}
}
/**
* Update the service-category list box.
*
* Use this method every time a change is made to the service categories db table.
*/
function updateAvailableServiceCategories() {
App.Http.ServiceCategories.search('', 999).then((response) => {
$serviceCategoryId.empty();
$serviceCategoryId.append(new Option('', '')).val('');
response.forEach((serviceCategory) => {
$serviceCategoryId.append(new Option(serviceCategory.name, serviceCategory.id));
});
});
}
/**
* Initialize the module.
*/
function initialize() {
App.Pages.Services.resetForm();
App.Pages.Services.filter('');
App.Pages.Services.addEventListeners();
updateAvailableServiceCategories();
}
document.addEventListener('DOMContentLoaded', initialize);
return {
filter,
save,
remove,
validate,
getFilterHtml,
resetForm,
display,
select,
addEventListeners,
};
})();

389
assets/js/pages/webhooks.js Normal file
View File

@ -0,0 +1,389 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* Webhooks page.
*
* This module implements the functionality of the webhooks page.
*/
App.Pages.Webhooks = (function () {
const $webhooks = $('#webhooks');
const $id = $('#id');
const $name = $('#name');
const $url = $('#url');
const $actions = $('#actions');
const $secretHeader = $('#secret-header');
const $secretToken = $('#secret-token');
const $isSslVerified = $('#is-ssl-verified');
const $notes = $('#notes');
const $filterWebhooks = $('#filter-webhooks');
let filterResults = {};
let filterLimit = 20;
/**
* Add page event listeners.
*/
function addEventListeners() {
/**
* Event: Filter Webhooks Form "Submit"
*
* @param {jQuery.Event} event
*/
$webhooks.on('submit', '#filter-webhooks form', (event) => {
event.preventDefault();
const key = $filterWebhooks.find('.key').val();
$filterWebhooks.find('.selected').removeClass('selected');
App.Pages.Webhooks.resetForm();
App.Pages.Webhooks.filter(key);
});
/**
* Event: Filter Webhook Row "Click"
*
* Display the selected webhook data to the user.
*/
$webhooks.on('click', '.webhook-row', (event) => {
if ($filterWebhooks.find('.filter').prop('disabled')) {
$filterWebhooks.find('.results').css('color', '#AAA');
return; // exit because we are on edit mode
}
const webhookId = $(event.currentTarget).attr('data-id');
const webhook = filterResults.find((filterResult) => Number(filterResult.id) === Number(webhookId));
App.Pages.Webhooks.display(webhook);
$filterWebhooks.find('.selected').removeClass('selected');
$(event.currentTarget).addClass('selected');
$('#edit-webhook, #delete-webhook').prop('disabled', false);
});
/**
* Event: Add New Webhook Button "Click"
*/
$webhooks.on('click', '#add-webhook', () => {
App.Pages.Webhooks.resetForm();
$webhooks.find('.add-edit-delete-group').hide();
$webhooks.find('.save-cancel-group').show();
$webhooks.find('.record-details').find('input, select, textarea').prop('disabled', false);
$webhooks.find('.record-details .form-label span').prop('hidden', false);
$filterWebhooks.find('button').prop('disabled', true);
$filterWebhooks.find('.results').css('color', '#AAA');
});
/**
* Event: Cancel Webhook Button "Click"
*
* Cancel add or edit of a webhook record.
*/
$webhooks.on('click', '#cancel-webhook', () => {
const id = $id.val();
App.Pages.Webhooks.resetForm();
if (id !== '') {
select(id, true);
}
});
/**
* Event: Save Webhook Button "Click"
*/
$webhooks.on('click', '#save-webhook', () => {
const webhook = {
name: $name.val(),
url: $url.val(),
actions: '',
secret_header: $secretHeader.val(),
secret_token: $secretToken.val(),
is_ssl_verified: Number($isSslVerified.prop('checked')),
notes: $notes.val(),
};
const actions = [];
$actions.find('input:checked').each((index, checkbox) => {
var action = $(checkbox).data('action');
actions.push(action);
});
webhook.actions = actions.join(',');
if ($id.val() !== '') {
webhook.id = $id.val();
}
if (!App.Pages.Webhooks.validate()) {
return;
}
App.Pages.Webhooks.save(webhook);
});
/**
* Event: Edit Webhook Button "Click"
*/
$webhooks.on('click', '#edit-webhook', () => {
$webhooks.find('.add-edit-delete-group').hide();
$webhooks.find('.save-cancel-group').show();
$webhooks.find('.record-details').find('input, select, textarea').prop('disabled', false);
$webhooks.find('.record-details .form-label span').prop('hidden', false);
$filterWebhooks.find('button').prop('disabled', true);
$filterWebhooks.find('.results').css('color', '#AAA');
});
/**
* Event: Delete Webhook Button "Click"
*/
$webhooks.on('click', '#delete-webhook', () => {
const webhookId = $id.val();
const buttons = [
{
text: lang('cancel'),
click: (event, messageModal) => {
messageModal.hide();
},
},
{
text: lang('delete'),
click: (event, messageModal) => {
App.Pages.Webhooks.remove(webhookId);
messageModal.hide();
},
},
];
App.Utils.Message.show(lang('delete_webhook'), lang('delete_record_prompt'), buttons);
});
}
/**
* Save webhook record to database.
*
* @param {Object} webhook Contains the webhook record data. If an 'id' value is provided
* then the update operation is going to be executed.
*/
function save(webhook) {
App.Http.Webhooks.save(webhook).then((response) => {
App.Layouts.Backend.displayNotification(lang('webhook_saved'));
App.Pages.Webhooks.resetForm();
$filterWebhooks.find('.key').val('');
App.Pages.Webhooks.filter('', response.id, true);
});
}
/**
* Delete a webhook record from database.
*
* @param {Number} id Record ID to be deleted.
*/
function remove(id) {
App.Http.Webhooks.destroy(id).then(() => {
App.Layouts.Backend.displayNotification(lang('webhook_deleted'));
App.Pages.Webhooks.resetForm();
App.Pages.Webhooks.filter($filterWebhooks.find('.key').val());
});
}
/**
* Validates a webhook record.
*
* @return {Boolean} Returns the validation result.
*/
function validate() {
$webhooks.find('.is-invalid').removeClass('is-invalid');
$webhooks.find('.form-message').removeClass('alert-danger').hide();
try {
// Validate required fields.
let missingRequired = false;
$webhooks.find('.required').each((index, requiredField) => {
if (!$(requiredField).val()) {
$(requiredField).addClass('is-invalid');
missingRequired = true;
}
});
if (missingRequired) {
throw new Error(lang('fields_are_required'));
}
return true;
} catch (error) {
$webhooks.find('.form-message').addClass('alert-danger').text(error.message).show();
return false;
}
}
/**
* Resets the webhook tab form back to its initial state.
*/
function resetForm() {
$filterWebhooks.find('.selected').removeClass('selected');
$filterWebhooks.find('button').prop('disabled', false);
$filterWebhooks.find('.results').css('color', '');
$webhooks.find('.record-details').find('input, select, textarea').val('').prop('disabled', true);
$webhooks.find('.record-details .form-label span').prop('hidden', true);
$webhooks.find('.record-details h3 a').remove();
$webhooks.find('.add-edit-delete-group').show();
$webhooks.find('.save-cancel-group').hide();
$('#edit-webhook, #delete-webhook').prop('disabled', true);
$webhooks.find('.record-details .is-invalid').removeClass('is-invalid');
$webhooks.find('.record-details .form-message').hide();
$actions.find('input:checkbox').prop('checked', false);
}
/**
* Display a webhook record into the webhook form.
*
* @param {Object} webhook Contains the webhook record data.
*/
function display(webhook) {
$id.val(webhook.id);
$name.val(webhook.name);
$url.val(webhook.url);
$secretHeader.val(webhook.secret_header);
$secretToken.val(webhook.secret_token);
$isSslVerified.prop('checked', Boolean(Number(webhook.is_ssl_verified)));
$actions.find('input:checkbox').prop('checked', false);
if (webhook.actions && webhook.actions.length) {
const actions = webhook.actions.split(',');
actions.forEach((action) => $(`[data-action="${action}"]`).prop('checked', true));
}
}
/**
* Filters webhook records depending a string keyword.
*
* @param {String} keyword This is used to filter the webhook records of the database.
* @param {Number} selectId Optional, if set then after the filter operation the record with this
* ID will be selected (but not displayed).
* @param {Boolean} show Optional (false), if true then the selected record will be displayed on the form.
*/
function filter(keyword, selectId = null, show = false) {
App.Http.Webhooks.search(keyword, filterLimit).then((response) => {
filterResults = response;
$filterWebhooks.find('.results').empty();
response.forEach((webhook) => {
$filterWebhooks.find('.results').append(App.Pages.Webhooks.getFilterHtml(webhook)).append($('<hr/>'));
});
if (response.length === 0) {
$filterWebhooks.find('.results').append(
$('<em/>', {
'text': lang('no_records_found'),
}),
);
} else if (response.length === filterLimit) {
$('<button/>', {
'type': 'button',
'class': 'btn btn-outline-secondary w-100 load-more text-center',
'text': lang('load_more'),
'click': () => {
filterLimit += 20;
App.Pages.Webhooks.filter(keyword, selectId, show);
},
}).appendTo('#filter-webhooks .results');
}
if (selectId) {
App.Pages.Webhooks.select(selectId, show);
}
});
}
/**
* Get Filter HTML
*
* Get a webhook row HTML code that is going to be displayed on the filter results list.
*
* @param {Object} webhook Contains the webhook record data.
*
* @return {String} The HTML code that represents the record on the filter results list.
*/
function getFilterHtml(webhook) {
const name = webhook.name;
const actionCount = webhook.actions && webhook.actions.length ? webhook.actions.split(',').length : 0;
const info = `${actionCount} ${lang('actions')}`;
return $('<div/>', {
'class': 'webhook-row entry',
'data-id': webhook.id,
'html': [
$('<strong/>', {
'text': name,
}),
$('<br/>'),
$('<small/>', {
'class': 'text-muted',
'text': info,
}),
$('<br/>'),
],
});
}
/**
* Select a specific record from the current filter results. If the webhook id does not exist
* in the list then no record will be selected.
*
* @param {Number} id The record id to be selected from the filter results.
* @param {Boolean} show Optional (false), if true then the method will display the record on the form.
*/
function select(id, show = false) {
$filterWebhooks.find('.selected').removeClass('selected');
$filterWebhooks.find('.webhook-row[data-id="' + id + '"]').addClass('selected');
if (show) {
const webhook = filterResults.find((filterResult) => Number(filterResult.id) === Number(id));
App.Pages.Webhooks.display(webhook);
$('#edit-webhook, #delete-webhook').prop('disabled', false);
}
}
/**
* Initialize the module.
*/
function initialize() {
App.Pages.Webhooks.resetForm();
App.Pages.Webhooks.filter('');
App.Pages.Webhooks.addEventListeners();
}
document.addEventListener('DOMContentLoaded', initialize);
return {
filter,
save,
remove,
validate,
getFilterHtml,
resetForm,
display,
select,
addEventListeners,
};
})();