This commit is contained in:
62
assets/js/app.js
Normal file
62
assets/js/app.js
Normal file
@@ -0,0 +1,62 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* Easy!Appointments - Online Appointment Scheduler
|
||||
*
|
||||
* @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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* App global namespace object.
|
||||
*
|
||||
* This script should be loaded before the other modules in order to define the global application namespace.
|
||||
*/
|
||||
window.App = (function () {
|
||||
function onAjaxError(event, jqXHR, textStatus, errorThrown) {
|
||||
console.error('Unexpected HTTP Error: ', jqXHR, textStatus, errorThrown);
|
||||
|
||||
let response;
|
||||
|
||||
try {
|
||||
response = JSON.parse(jqXHR.responseText); // JSON response
|
||||
} catch (error) {
|
||||
response = {message: jqXHR.responseText}; // String response
|
||||
}
|
||||
|
||||
if (!response || !response.message) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (App.Utils.Message) {
|
||||
App.Utils.Message.show(lang('unexpected_issues'), lang('unexpected_issues_message'));
|
||||
|
||||
$('<div/>', {
|
||||
'class': 'card',
|
||||
'html': [
|
||||
$('<div/>', {
|
||||
'class': 'card-body overflow-auto',
|
||||
'html': response.message,
|
||||
}),
|
||||
],
|
||||
}).appendTo('#message-modal .modal-body');
|
||||
}
|
||||
}
|
||||
|
||||
$(document).ajaxError(onAjaxError);
|
||||
|
||||
$(function () {
|
||||
if (window.moment) {
|
||||
window.moment.locale(vars('language_code'));
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
Components: {},
|
||||
Http: {},
|
||||
Layouts: {},
|
||||
Pages: {},
|
||||
Utils: {},
|
||||
};
|
||||
})();
|
||||
124
assets/js/components/appointment_status_options.js
Normal file
124
assets/js/components/appointment_status_options.js
Normal file
@@ -0,0 +1,124 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Appointment status options component.
|
||||
*
|
||||
* This module implements the appointment status options.
|
||||
*/
|
||||
App.Components.AppointmentStatusOptions = (function () {
|
||||
/**
|
||||
* Render an appointment status option.
|
||||
*
|
||||
* @param {String} [appointmentStatusOption]
|
||||
*
|
||||
* @return {jQuery} Returns a jQuery selector with the list group item markup.
|
||||
*/
|
||||
function renderListGroupItem(appointmentStatusOption = '') {
|
||||
return $(`
|
||||
<li class="list-group-item d-flex justify-content-between align-items-center p-0 border-0 mb-3 appointment-status-option">
|
||||
<label class="w-100 me-2">
|
||||
<input class="form-control" value="${appointmentStatusOption}">
|
||||
</label>
|
||||
|
||||
<button type="button" class="btn btn-outline-danger delete-appointment-status-option">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
</li>
|
||||
`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Event: Delete Appointment Status Option "Click"
|
||||
*
|
||||
* @param {jQuery.Event} event
|
||||
*/
|
||||
function onDeleteAppointmentStatusOptionClick(event) {
|
||||
$(event.currentTarget).closest('li').remove();
|
||||
}
|
||||
|
||||
/**
|
||||
* Event: Add Appointment Status Option "Click"
|
||||
*
|
||||
* @param {jQuery.Event} event
|
||||
*/
|
||||
function onAddAppointmentStatusOptionClick(event) {
|
||||
const $target = $(event.currentTarget);
|
||||
|
||||
const $listGroup = $target.closest('.appointment-status-options').find('.list-group');
|
||||
|
||||
if (!$listGroup.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
renderListGroupItem().appendTo($listGroup);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get target options.
|
||||
*
|
||||
* @param {jQuery} $target Container element ".status-list" selector.
|
||||
*
|
||||
* @return {String[]}
|
||||
*/
|
||||
function getOptions($target) {
|
||||
const $listGroup = $target.find('.list-group');
|
||||
|
||||
const appointmentStatusOptions = [];
|
||||
|
||||
$listGroup.find('li').each((index, listGroupItemEl) => {
|
||||
const $listGroupItem = $(listGroupItemEl);
|
||||
const appointmentStatusOption = $listGroupItem.find('input:text').val();
|
||||
appointmentStatusOptions.push(appointmentStatusOption);
|
||||
});
|
||||
|
||||
return appointmentStatusOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set target options.
|
||||
*
|
||||
* @param {jQuery} $target Container element ".status-list" selector.
|
||||
* @param {String[]} appointmentStatusOptions Appointment status options.
|
||||
*/
|
||||
function setOptions($target, appointmentStatusOptions) {
|
||||
if (!$target.length || !appointmentStatusOptions || !appointmentStatusOptions.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const $listGroup = $target.find('.list-group');
|
||||
|
||||
if (!$listGroup.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
$listGroup.empty();
|
||||
|
||||
appointmentStatusOptions.forEach((appointmentStatusOption) => {
|
||||
renderListGroupItem(appointmentStatusOption).appendTo($listGroup);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the module.
|
||||
*/
|
||||
function initialize() {
|
||||
$(document).on('click', '.delete-appointment-status-option', onDeleteAppointmentStatusOptionClick);
|
||||
$(document).on('click', '.add-appointment-status-option', onAddAppointmentStatusOptionClick);
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialize);
|
||||
|
||||
return {
|
||||
getOptions,
|
||||
setOptions,
|
||||
};
|
||||
})();
|
||||
585
assets/js/components/appointments_modal.js
Normal file
585
assets/js/components/appointments_modal.js
Normal file
@@ -0,0 +1,585 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Appointments modal component.
|
||||
*
|
||||
* This module implements the appointments modal functionality.
|
||||
*
|
||||
* Old Name: BackendCalendarAppointmentsModal
|
||||
*/
|
||||
App.Components.AppointmentsModal = (function () {
|
||||
const $appointmentsModal = $('#appointments-modal');
|
||||
const $startDatetime = $('#start-datetime');
|
||||
const $endDatetime = $('#end-datetime');
|
||||
const $filterExistingCustomers = $('#filter-existing-customers');
|
||||
const $customerId = $('#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 $language = $('#language');
|
||||
const $timezone = $('#timezone');
|
||||
const $customerNotes = $('#customer-notes');
|
||||
const $selectCustomer = $('#select-customer');
|
||||
const $saveAppointment = $('#save-appointment');
|
||||
const $appointmentId = $('#appointment-id');
|
||||
const $appointmentLocation = $('#appointment-location');
|
||||
const $appointmentStatus = $('#appointment-status');
|
||||
const $appointmentColor = $('#appointment-color');
|
||||
const $appointmentNotes = $('#appointment-notes');
|
||||
const $reloadAppointments = $('#reload-appointments');
|
||||
const $selectFilterItem = $('#select-filter-item');
|
||||
const $selectService = $('#select-service');
|
||||
const $selectProvider = $('#select-provider');
|
||||
const $insertAppointment = $('#insert-appointment');
|
||||
const $existingCustomersList = $('#existing-customers-list');
|
||||
const $newCustomer = $('#new-customer');
|
||||
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 moment = window.moment;
|
||||
|
||||
/**
|
||||
* Update the displayed timezone.
|
||||
*/
|
||||
function updateTimezone() {
|
||||
const providerId = $selectProvider.val();
|
||||
|
||||
const provider = vars('available_providers').find(
|
||||
(availableProvider) => Number(availableProvider.id) === Number(providerId),
|
||||
);
|
||||
|
||||
if (provider && provider.timezone) {
|
||||
$('.provider-timezone').text(vars('timezones')[provider.timezone]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the component event listeners.
|
||||
*/
|
||||
function addEventListeners() {
|
||||
/**
|
||||
* Event: Manage Appointments Dialog Save Button "Click"
|
||||
*
|
||||
* Stores the appointment changes or inserts a new appointment depending on the dialog mode.
|
||||
*/
|
||||
$saveAppointment.on('click', () => {
|
||||
// Before doing anything the appointment data need to be validated.
|
||||
if (!App.Components.AppointmentsModal.validateAppointmentForm()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ID must exist on the object in order for the model to update the record and not to perform
|
||||
// an insert operation.
|
||||
|
||||
const startDateTimeObject = App.Utils.UI.getDateTimePickerValue($startDatetime);
|
||||
const startDatetime = moment(startDateTimeObject).format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
const endDateTimeObject = App.Utils.UI.getDateTimePickerValue($endDatetime);
|
||||
const endDatetime = moment(endDateTimeObject).format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
const appointment = {
|
||||
id_services: $selectService.val(),
|
||||
id_users_provider: $selectProvider.val(),
|
||||
start_datetime: startDatetime,
|
||||
end_datetime: endDatetime,
|
||||
location: $appointmentLocation.val(),
|
||||
color: App.Components.ColorSelection.getColor($appointmentColor),
|
||||
status: $appointmentStatus.val(),
|
||||
notes: $appointmentNotes.val(),
|
||||
is_unavailability: Number(false),
|
||||
};
|
||||
|
||||
if ($appointmentId.val() !== '') {
|
||||
// Set the id value, only if we are editing an appointment.
|
||||
appointment.id = $appointmentId.val();
|
||||
}
|
||||
|
||||
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(),
|
||||
language: $language.val(),
|
||||
timezone: $timezone.val(),
|
||||
notes: $customerNotes.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(),
|
||||
};
|
||||
|
||||
if ($customerId.val() !== '') {
|
||||
// Set the id value, only if we are editing an appointment.
|
||||
customer.id = $customerId.val();
|
||||
appointment.id_users_customer = customer.id;
|
||||
}
|
||||
|
||||
// Define success callback.
|
||||
const successCallback = () => {
|
||||
// Display success message to the user.
|
||||
App.Layouts.Backend.displayNotification(lang('appointment_saved'));
|
||||
|
||||
// Close the modal dialog and refresh the calendar appointments.
|
||||
$appointmentsModal.find('.alert').addClass('d-none');
|
||||
$appointmentsModal.modal('hide');
|
||||
$reloadAppointments.trigger('click');
|
||||
};
|
||||
|
||||
// Define error callback.
|
||||
const errorCallback = () => {
|
||||
$appointmentsModal.find('.modal-message').text(lang('service_communication_error'));
|
||||
$appointmentsModal.find('.modal-message').addClass('alert-danger').removeClass('d-none');
|
||||
$appointmentsModal.find('.modal-body').scrollTop(0);
|
||||
};
|
||||
|
||||
// Save appointment data.
|
||||
App.Http.Calendar.saveAppointment(appointment, customer, successCallback, errorCallback);
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Insert Appointment Button "Click"
|
||||
*
|
||||
* When the user presses this button, the manage appointment dialog opens and lets the user create a new
|
||||
* appointment.
|
||||
*/
|
||||
$insertAppointment.on('click', () => {
|
||||
$('.popover').remove();
|
||||
|
||||
App.Components.AppointmentsModal.resetModal();
|
||||
|
||||
// Set the selected filter item and find the next appointment time as the default modal values.
|
||||
if ($selectFilterItem.find('option:selected').attr('type') === 'provider') {
|
||||
const providerId = $('#select-filter-item').val();
|
||||
|
||||
const providers = vars('available_providers').filter(
|
||||
(provider) => Number(provider.id) === Number(providerId),
|
||||
);
|
||||
|
||||
if (providers.length) {
|
||||
$selectService.val(providers[0].services[0]).trigger('change');
|
||||
$selectProvider.val(providerId);
|
||||
}
|
||||
} else if ($selectFilterItem.find('option:selected').attr('type') === 'service') {
|
||||
$selectService.find('option[value="' + $selectFilterItem.val() + '"]').prop('selected', true);
|
||||
} else {
|
||||
$selectService.find('option:first').prop('selected', true).trigger('change');
|
||||
}
|
||||
|
||||
$selectProvider.trigger('change');
|
||||
|
||||
const serviceId = $selectService.val();
|
||||
|
||||
const service = vars('available_services').find(
|
||||
(availableService) => Number(availableService.id) === Number(serviceId),
|
||||
);
|
||||
|
||||
const duration = service ? service.duration : 60;
|
||||
|
||||
const startMoment = moment();
|
||||
|
||||
const currentMin = parseInt(startMoment.format('mm'));
|
||||
|
||||
if (currentMin > 0 && currentMin < 15) {
|
||||
startMoment.set({minutes: 15});
|
||||
} else if (currentMin > 15 && currentMin < 30) {
|
||||
startMoment.set({minutes: 30});
|
||||
} else if (currentMin > 30 && currentMin < 45) {
|
||||
startMoment.set({minutes: 45});
|
||||
} else {
|
||||
startMoment.add(1, 'hour').set({minutes: 0});
|
||||
}
|
||||
|
||||
App.Utils.UI.setDateTimePickerValue($startDatetime, startMoment.toDate());
|
||||
App.Utils.UI.setDateTimePickerValue($endDatetime, startMoment.add(duration, 'minutes').toDate());
|
||||
|
||||
// Display modal form.
|
||||
$appointmentsModal.find('.modal-header h3').text(lang('new_appointment_title'));
|
||||
|
||||
$appointmentsModal.modal('show');
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Pick Existing Customer Button "Click"
|
||||
*
|
||||
* @param {jQuery.Event} event
|
||||
*/
|
||||
$selectCustomer.on('click', (event) => {
|
||||
if (!$existingCustomersList.is(':visible')) {
|
||||
$(event.target).find('span').text(lang('hide'));
|
||||
$existingCustomersList.empty();
|
||||
$existingCustomersList.slideDown('slow');
|
||||
$filterExistingCustomers.fadeIn('slow').val('');
|
||||
vars('customers').forEach((customer) => {
|
||||
$('<div/>', {
|
||||
'data-id': customer.id,
|
||||
'text':
|
||||
(customer.first_name || '[No First Name]') + ' ' + (customer.last_name || '[No Last Name]'),
|
||||
}).appendTo($existingCustomersList);
|
||||
});
|
||||
} else {
|
||||
$existingCustomersList.slideUp('slow');
|
||||
$filterExistingCustomers.fadeOut('slow');
|
||||
$(event.target).find('span').text(lang('select'));
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Select Existing Customer From List "Click"
|
||||
*
|
||||
* @param {jQuery.Event}
|
||||
*/
|
||||
$appointmentsModal.on('click', '#existing-customers-list div', (event) => {
|
||||
const customerId = $(event.target).attr('data-id');
|
||||
|
||||
const customer = vars('customers').find((customer) => Number(customer.id) === Number(customerId));
|
||||
|
||||
if (customer) {
|
||||
$customerId.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);
|
||||
$language.val(customer.language);
|
||||
$timezone.val(customer.timezone);
|
||||
$customerNotes.val(customer.notes);
|
||||
$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);
|
||||
}
|
||||
|
||||
$selectCustomer.trigger('click'); // Hide the list.
|
||||
});
|
||||
|
||||
let filterExistingCustomersTimeout = null;
|
||||
|
||||
/**
|
||||
* Event: Filter Existing Customers "Change"
|
||||
*
|
||||
* @param {jQuery.Event}
|
||||
*/
|
||||
$filterExistingCustomers.on('keyup', (event) => {
|
||||
if (filterExistingCustomersTimeout) {
|
||||
clearTimeout(filterExistingCustomersTimeout);
|
||||
}
|
||||
|
||||
const keyword = $(event.target).val().toLowerCase();
|
||||
|
||||
filterExistingCustomersTimeout = setTimeout(() => {
|
||||
$('#loading').css('visibility', 'hidden');
|
||||
|
||||
App.Http.Customers.search(keyword, 50)
|
||||
.done((response) => {
|
||||
$existingCustomersList.empty();
|
||||
|
||||
response.forEach((customer) => {
|
||||
$('<div/>', {
|
||||
'data-id': customer.id,
|
||||
'text':
|
||||
(customer.first_name || '[No First Name]') +
|
||||
' ' +
|
||||
(customer.last_name || '[No Last Name]'),
|
||||
}).appendTo($existingCustomersList);
|
||||
|
||||
// Verify if this customer is on the old customer list.
|
||||
const result = vars('customers').filter((existingCustomer) => {
|
||||
return Number(existingCustomer.id) === Number(customer.id);
|
||||
});
|
||||
|
||||
// Add it to the customer list.
|
||||
if (!result.length) {
|
||||
vars('customers').push(customer);
|
||||
}
|
||||
});
|
||||
})
|
||||
.fail(() => {
|
||||
// If there is any error on the request, search by the local client database.
|
||||
$existingCustomersList.empty();
|
||||
|
||||
vars('customers').forEach((customer) => {
|
||||
if (
|
||||
customer.first_name.toLowerCase().indexOf(keyword) !== -1 ||
|
||||
customer.last_name.toLowerCase().indexOf(keyword) !== -1 ||
|
||||
customer.email.toLowerCase().indexOf(keyword) !== -1 ||
|
||||
customer.phone_number.toLowerCase().indexOf(keyword) !== -1 ||
|
||||
customer.address.toLowerCase().indexOf(keyword) !== -1 ||
|
||||
customer.city.toLowerCase().indexOf(keyword) !== -1 ||
|
||||
customer.zip_code.toLowerCase().indexOf(keyword) !== -1 ||
|
||||
customer.notes.toLowerCase().indexOf(keyword) !== -1
|
||||
) {
|
||||
$('<div/>', {
|
||||
'data-id': customer.id,
|
||||
'text':
|
||||
(customer.first_name || '[No First Name]') +
|
||||
' ' +
|
||||
(customer.last_name || '[No Last Name]'),
|
||||
}).appendTo($existingCustomersList);
|
||||
}
|
||||
});
|
||||
})
|
||||
.always(() => {
|
||||
$('#loading').css('visibility', '');
|
||||
});
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Selected Service "Change"
|
||||
*
|
||||
* When the user clicks on a service, its available providers should become visible. We also need to
|
||||
* update the start and end time of the appointment.
|
||||
*/
|
||||
$selectService.on('change', () => {
|
||||
const serviceId = $selectService.val();
|
||||
|
||||
const providerId = $selectProvider.val();
|
||||
|
||||
$selectProvider.empty();
|
||||
|
||||
// Automatically update the service duration.
|
||||
const service = vars('available_services').find((availableService) => {
|
||||
return Number(availableService.id) === Number(serviceId);
|
||||
});
|
||||
|
||||
if (service?.color) {
|
||||
App.Components.ColorSelection.setColor($appointmentColor, service.color);
|
||||
}
|
||||
|
||||
const duration = service ? service.duration : 60;
|
||||
|
||||
const startDateTimeObject = App.Utils.UI.getDateTimePickerValue($startDatetime);
|
||||
const endDateTimeObject = new Date(startDateTimeObject.getTime() + duration * 60000);
|
||||
App.Utils.UI.setDateTimePickerValue($endDatetime, endDateTimeObject);
|
||||
|
||||
// Update the providers select box.
|
||||
|
||||
vars('available_providers').forEach((provider) => {
|
||||
provider.services.forEach((providerServiceId) => {
|
||||
if (
|
||||
vars('role_slug') === App.Layouts.Backend.DB_SLUG_PROVIDER &&
|
||||
Number(provider.id) !== vars('user_id')
|
||||
) {
|
||||
return; // continue
|
||||
}
|
||||
|
||||
if (
|
||||
vars('role_slug') === App.Layouts.Backend.DB_SLUG_SECRETARY &&
|
||||
vars('secretary_providers').indexOf(Number(provider.id)) === -1
|
||||
) {
|
||||
return; // continue
|
||||
}
|
||||
|
||||
// If the current provider is able to provide the selected service, add him to the list box.
|
||||
if (Number(providerServiceId) === Number(serviceId)) {
|
||||
$selectProvider.append(new Option(provider.first_name + ' ' + provider.last_name, provider.id));
|
||||
}
|
||||
});
|
||||
|
||||
if ($selectProvider.find(`option[value="${providerId}"]`).length) {
|
||||
$selectProvider.val(providerId);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Provider "Change"
|
||||
*/
|
||||
$selectProvider.on('change', () => {
|
||||
updateTimezone();
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Enter New Customer Button "Click"
|
||||
*/
|
||||
$newCustomer.on('click', () => {
|
||||
$customerId.val('');
|
||||
$firstName.val('');
|
||||
$lastName.val('');
|
||||
$email.val('');
|
||||
$phoneNumber.val('');
|
||||
$address.val('');
|
||||
$city.val('');
|
||||
$zipCode.val('');
|
||||
$language.val(vars('default_language'));
|
||||
$timezone.val(vars('default_timezone'));
|
||||
$customerNotes.val('');
|
||||
$customField1.val('');
|
||||
$customField2.val('');
|
||||
$customField3.val('');
|
||||
$customField4.val('');
|
||||
$customField5.val('');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset Appointment Dialog
|
||||
*
|
||||
* This method resets the manage appointment dialog modal to its initial state. After that you can make
|
||||
* any modification might be necessary in order to bring the dialog to the desired state.
|
||||
*/
|
||||
function resetModal() {
|
||||
// Empty form fields.
|
||||
$appointmentsModal.find('input, textarea').val('');
|
||||
$appointmentsModal.find('.modal-message').addClass('.d-none');
|
||||
|
||||
const defaultStatusValue = $appointmentStatus.find('option:first').val();
|
||||
$appointmentStatus.val(defaultStatusValue);
|
||||
|
||||
$language.val(vars('default_language'));
|
||||
$timezone.val(vars('default_timezone'));
|
||||
|
||||
// Reset color.
|
||||
$appointmentColor.find('.color-selection-option:first').trigger('click');
|
||||
|
||||
// Prepare service and provider select boxes.
|
||||
$selectService.val($selectService.eq(0).attr('value'));
|
||||
|
||||
// Fill the providers list box with providers that can serve the appointment's service and then select the
|
||||
// user's provider.
|
||||
$selectProvider.empty();
|
||||
vars('available_providers').forEach((provider) => {
|
||||
const serviceId = $selectService.val();
|
||||
|
||||
const canProvideService =
|
||||
provider.services.filter((providerServiceId) => {
|
||||
return Number(providerServiceId) === Number(serviceId);
|
||||
}).length > 0;
|
||||
|
||||
if (canProvideService) {
|
||||
// Add the provider to the list box.
|
||||
$selectProvider.append(new Option(provider.first_name + ' ' + provider.last_name, provider.id));
|
||||
}
|
||||
});
|
||||
|
||||
// Close existing customers-filter frame.
|
||||
$existingCustomersList.slideUp('slow');
|
||||
$filterExistingCustomers.fadeOut('slow');
|
||||
$selectCustomer.find('span').text(lang('select'));
|
||||
|
||||
// Setup start and datetimepickers.
|
||||
// Get the selected service duration. It will be needed in order to calculate the appointment end datetime.
|
||||
const serviceId = $selectService.val();
|
||||
|
||||
const service = vars('available_services').forEach((service) => Number(service.id) === Number(serviceId));
|
||||
|
||||
const duration = service ? service.duration : 0;
|
||||
|
||||
const startDatetime = new Date();
|
||||
const endDatetime = moment().add(duration, 'minutes').toDate();
|
||||
|
||||
App.Utils.UI.initializeDateTimePicker($startDatetime, {
|
||||
onClose: () => {
|
||||
const serviceId = $selectService.val();
|
||||
|
||||
// Automatically update the #end-datetime DateTimePicker based on service duration.
|
||||
const service = vars('available_services').find(
|
||||
(availableService) => Number(availableService.id) === Number(serviceId),
|
||||
);
|
||||
|
||||
const startDateTimeObject = App.Utils.UI.getDateTimePickerValue($startDatetime);
|
||||
const endDateTimeObject = new Date(startDateTimeObject.getTime() + service.duration * 60000);
|
||||
App.Utils.UI.setDateTimePickerValue($endDatetime, endDateTimeObject);
|
||||
},
|
||||
});
|
||||
|
||||
App.Utils.UI.setDateTimePickerValue($startDatetime, startDatetime);
|
||||
|
||||
App.Utils.UI.initializeDateTimePicker($endDatetime);
|
||||
App.Utils.UI.setDateTimePickerValue($endDatetime, endDatetime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the manage appointment dialog data.
|
||||
*
|
||||
* Validation checks need to run every time the data are going to be saved.
|
||||
*
|
||||
* @return {Boolean} Returns the validation result.
|
||||
*/
|
||||
function validateAppointmentForm() {
|
||||
// Reset previous validation css formatting.
|
||||
$appointmentsModal.find('.is-invalid').removeClass('is-invalid');
|
||||
$appointmentsModal.find('.modal-message').addClass('d-none');
|
||||
|
||||
try {
|
||||
// Check required fields.
|
||||
let missingRequiredField = false;
|
||||
|
||||
$appointmentsModal.find('.required').each((index, requiredField) => {
|
||||
if ($(requiredField).val() === '' || $(requiredField).val() === null) {
|
||||
$(requiredField).addClass('is-invalid');
|
||||
missingRequiredField = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (missingRequiredField) {
|
||||
throw new Error(lang('fields_are_required'));
|
||||
}
|
||||
|
||||
// Check email address.
|
||||
if (
|
||||
$appointmentsModal.find('#email').val() &&
|
||||
!App.Utils.Validation.email($appointmentsModal.find('#email').val())
|
||||
) {
|
||||
$appointmentsModal.find('#email').addClass('is-invalid');
|
||||
throw new Error(lang('invalid_email'));
|
||||
}
|
||||
|
||||
// Check appointment start and end time.
|
||||
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) {
|
||||
$appointmentsModal
|
||||
.find('.modal-message')
|
||||
.addClass('alert-danger')
|
||||
.text(error.message)
|
||||
.removeClass('d-none');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the module.
|
||||
*/
|
||||
function initialize() {
|
||||
addEventListeners();
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialize);
|
||||
|
||||
return {
|
||||
resetModal,
|
||||
validateAppointmentForm,
|
||||
};
|
||||
})();
|
||||
110
assets/js/components/color_selection.js
Normal file
110
assets/js/components/color_selection.js
Normal file
@@ -0,0 +1,110 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Color selection component.
|
||||
*
|
||||
* This module implements the color selection functionality.
|
||||
*/
|
||||
App.Components.ColorSelection = (function () {
|
||||
/**
|
||||
* Event: Color Selection Option "Click"
|
||||
*
|
||||
* @param {jQuery.Event} event
|
||||
*/
|
||||
function onColorSelectionOptionClick(event) {
|
||||
const $target = $(event.currentTarget);
|
||||
|
||||
const $colorSelection = $target.closest('.color-selection');
|
||||
|
||||
$colorSelection.find('.color-selection-option.selected').removeClass('selected');
|
||||
|
||||
$target.addClass('selected');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get target color.
|
||||
*
|
||||
* @param {jQuery} $target Container element ".color-selection" selector.
|
||||
*/
|
||||
function getColor($target) {
|
||||
return $target.find('.color-selection-option.selected').data('value');
|
||||
}
|
||||
|
||||
/**
|
||||
* Set target color.
|
||||
*
|
||||
* @param {jQuery} $target Container element ".color-selection" selector.
|
||||
* @param {String} color Color value.
|
||||
*/
|
||||
function setColor($target, color) {
|
||||
$target
|
||||
.find('.color-selection-option')
|
||||
.removeClass('selected')
|
||||
.each((index, colorSelectionOptionEl) => {
|
||||
var $colorSelectionOption = $(colorSelectionOptionEl);
|
||||
|
||||
if ($colorSelectionOption.data('value') === color) {
|
||||
$colorSelectionOption.addClass('selected');
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable the color selection for the target element.
|
||||
*
|
||||
* @param {jQuery} $target
|
||||
*/
|
||||
function disable($target) {
|
||||
$target.find('.color-selection-option').prop('disabled', true).removeClass('selected');
|
||||
$target.find('.color-selection-option:first').addClass('selected');
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable the color selection for the target element.
|
||||
*
|
||||
* @param {jQuery} $target
|
||||
*/
|
||||
function enable($target) {
|
||||
$target.find('.color-selection-option').prop('disabled', false);
|
||||
}
|
||||
|
||||
function applyBackgroundColors() {
|
||||
$(document)
|
||||
.find('.color-selection-option')
|
||||
.each((index, colorSelectionOptionEl) => {
|
||||
const $colorSelectionOption = $(colorSelectionOptionEl);
|
||||
|
||||
const color = $colorSelectionOption.data('value');
|
||||
|
||||
$colorSelectionOption.css('background-color', color);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the module.
|
||||
*/
|
||||
function initialize() {
|
||||
$(document).on('click', '.color-selection-option', onColorSelectionOptionClick);
|
||||
|
||||
applyBackgroundColors();
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialize);
|
||||
|
||||
return {
|
||||
disable,
|
||||
enable,
|
||||
getColor,
|
||||
setColor,
|
||||
};
|
||||
})();
|
||||
198
assets/js/components/ldap_import_modal.js
Normal file
198
assets/js/components/ldap_import_modal.js
Normal 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* LDAP import modal component.
|
||||
*
|
||||
* This module implements the LDAP import modal functionality.
|
||||
*
|
||||
* This module requires the following scripts:
|
||||
*
|
||||
* - App.Http.Customers
|
||||
* - App.Http.Providers
|
||||
* - App.Http.Secretaries
|
||||
* - App.Http.Admins
|
||||
*/
|
||||
App.Components.LdapImportModal = (function () {
|
||||
const $modal = $('#ldap-import-modal');
|
||||
const $save = $('#ldap-import-save');
|
||||
const $firstName = $('#ldap-import-first-name');
|
||||
const $lastName = $('#ldap-import-last-name');
|
||||
const $email = $('#ldap-import-email');
|
||||
const $phoneNumber = $('#ldap-import-phone-number');
|
||||
const $username = $('#ldap-import-username');
|
||||
const $ldapDn = $('#ldap-import-ldap-dn');
|
||||
const $roleSlug = $('#ldap-import-role-slug');
|
||||
const $password = $('#ldap-import-password');
|
||||
|
||||
let deferred;
|
||||
|
||||
/**
|
||||
* Validate the import modal form.
|
||||
*
|
||||
* @return {Boolean}
|
||||
*/
|
||||
function validate() {
|
||||
$modal.find('.is-invalid').removeClass('is-invalid');
|
||||
|
||||
// Check required fields.
|
||||
let missingRequiredField = false;
|
||||
|
||||
$modal.find('.required').each((index, requiredField) => {
|
||||
if ($(requiredField).val() === '' || $(requiredField).val() === null) {
|
||||
$(requiredField).addClass('is-invalid');
|
||||
missingRequiredField = true;
|
||||
}
|
||||
});
|
||||
|
||||
return !missingRequiredField;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the right HTTP client for the create-user request.
|
||||
*
|
||||
* @param {String} roleSlug
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function getHttpClient(roleSlug) {
|
||||
switch (roleSlug) {
|
||||
case App.Layouts.Backend.DB_SLUG_CUSTOMER:
|
||||
return App.Http.Customers;
|
||||
case App.Layouts.Backend.DB_SLUG_PROVIDER:
|
||||
return App.Http.Providers;
|
||||
case App.Layouts.Backend.DB_SLUG_SECRETARY:
|
||||
return App.Http.Secretaries;
|
||||
case App.Layouts.Backend.DB_SLUG_ADMIN:
|
||||
return App.Http.Admins;
|
||||
default:
|
||||
throw new Error(`Unsupported role slug provided: ${roleSlug}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the user data object, based on the form values the user provided.
|
||||
*
|
||||
* @param {String} roleSlug
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function getUser(roleSlug) {
|
||||
const user = {
|
||||
first_name: $firstName.val(),
|
||||
last_name: $lastName.val(),
|
||||
email: $email.val(),
|
||||
phone_number: $phoneNumber.val(),
|
||||
ldap_dn: $ldapDn.val(),
|
||||
};
|
||||
|
||||
if (roleSlug !== App.Layouts.Backend.DB_SLUG_CUSTOMER) {
|
||||
user.settings = {
|
||||
username: $username.val(),
|
||||
password: $password.val(),
|
||||
notification: 1,
|
||||
};
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Go through the available values and try to load as many as possible based on the provided mapping.
|
||||
*
|
||||
* @param {Object} entry
|
||||
* @param {Object} ldapFieldMapping
|
||||
*/
|
||||
function loadEntry(entry, ldapFieldMapping) {
|
||||
$ldapDn.val(entry.dn);
|
||||
$firstName.val(entry?.[ldapFieldMapping?.first_name] ?? '');
|
||||
$lastName.val(entry?.[ldapFieldMapping?.last_name] ?? '');
|
||||
$email.val(entry?.[ldapFieldMapping?.email] ?? '');
|
||||
$phoneNumber.val(entry?.[ldapFieldMapping?.phone_number] ?? '');
|
||||
$username.val(entry?.[ldapFieldMapping?.username] ?? '');
|
||||
$password.val('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the current user data.
|
||||
*/
|
||||
function onSaveClick() {
|
||||
if (!validate()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const roleSlug = $roleSlug.val();
|
||||
|
||||
const user = getUser(roleSlug);
|
||||
|
||||
const httpClient = getHttpClient(roleSlug);
|
||||
|
||||
httpClient.store(user).done(() => {
|
||||
deferred.resolve();
|
||||
deferred = undefined;
|
||||
$modal.modal('hide');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the modal every time it's hidden.
|
||||
*/
|
||||
function onModalHidden() {
|
||||
resetModal();
|
||||
|
||||
if (deferred) {
|
||||
deferred.reject();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the modal fields and state.
|
||||
*/
|
||||
function resetModal() {
|
||||
$modal.find('input, select, textarea').val('');
|
||||
$modal.find(':checkbox').prop('checked', false);
|
||||
$roleSlug.val(App.Layouts.Backend.DB_SLUG_PROVIDER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the import modal for an LDAP entry.
|
||||
*
|
||||
* @param {Object} entry
|
||||
* @param {Object} ldapFieldMapping
|
||||
*
|
||||
* @return {Object} $.Deferred
|
||||
*/
|
||||
function open(entry, ldapFieldMapping) {
|
||||
resetModal();
|
||||
|
||||
deferred = $.Deferred();
|
||||
|
||||
loadEntry(entry, ldapFieldMapping);
|
||||
|
||||
$modal.modal('show');
|
||||
|
||||
return deferred.promise();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the module.
|
||||
*/
|
||||
function initialize() {
|
||||
$save.on('click', onSaveClick);
|
||||
$modal.on('hidden.bs.modal', onModalHidden);
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialize);
|
||||
|
||||
return {
|
||||
open,
|
||||
};
|
||||
})();
|
||||
218
assets/js/components/unavailabilities_modal.js
Normal file
218
assets/js/components/unavailabilities_modal.js
Normal file
@@ -0,0 +1,218 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Unavailabilities modal component.
|
||||
*
|
||||
* This module implements the unavailabilities modal functionality.
|
||||
*
|
||||
* Old Name: BackendCalendarUnavailabilityEventsModal
|
||||
*/
|
||||
App.Components.UnavailabilitiesModal = (function () {
|
||||
const $unavailabilitiesModal = $('#unavailabilities-modal');
|
||||
const $id = $('#unavailability-id');
|
||||
const $startDatetime = $('#unavailability-start');
|
||||
const $endDatetime = $('#unavailability-end');
|
||||
const $selectProvider = $('#unavailability-provider');
|
||||
const $notes = $('#unavailability-notes');
|
||||
const $saveUnavailability = $('#save-unavailability');
|
||||
const $insertUnavailability = $('#insert-unavailability');
|
||||
const $selectFilterItem = $('#select-filter-item');
|
||||
const $reloadAppointments = $('#reload-appointments');
|
||||
|
||||
const moment = window.moment;
|
||||
|
||||
/**
|
||||
* Update the displayed timezone.
|
||||
*/
|
||||
function updateTimezone() {
|
||||
const providerId = $selectProvider.val();
|
||||
|
||||
const provider = vars('available_providers').find(
|
||||
(availableProvider) => Number(availableProvider.id) === Number(providerId),
|
||||
);
|
||||
|
||||
if (provider && provider.timezone) {
|
||||
$unavailabilitiesModal.find('.provider-timezone').text(vars('timezones')[provider.timezone]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the component event listeners.
|
||||
*/
|
||||
function addEventListeners() {
|
||||
/**
|
||||
* Event: Provider "Change"
|
||||
*/
|
||||
$selectProvider.on('change', () => {
|
||||
updateTimezone();
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Manage Unavailability Dialog Save Button "Click"
|
||||
*
|
||||
* Stores the unavailability period changes or inserts a new record.
|
||||
*/
|
||||
$saveUnavailability.on('click', () => {
|
||||
$unavailabilitiesModal.find('.modal-message').addClass('d-none');
|
||||
$unavailabilitiesModal.find('.is-invalid').removeClass('is-invalid');
|
||||
|
||||
if (!$selectProvider.val()) {
|
||||
$selectProvider.addClass('is-invalid');
|
||||
return;
|
||||
}
|
||||
|
||||
const startDateTimeMoment = moment(App.Utils.UI.getDateTimePickerValue($startDatetime));
|
||||
|
||||
if (!startDateTimeMoment.isValid()) {
|
||||
$startDatetime.addClass('is-invalid');
|
||||
return;
|
||||
}
|
||||
|
||||
const endDateTimeMoment = moment(App.Utils.UI.getDateTimePickerValue($endDatetime));
|
||||
|
||||
if (!endDateTimeMoment.isValid()) {
|
||||
$endDatetime.addClass('is-invalid');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (startDateTimeMoment.isAfter(endDateTimeMoment)) {
|
||||
// Start time is after end time - display message to user.
|
||||
$unavailabilitiesModal
|
||||
.find('.modal-message')
|
||||
.text(lang('start_date_before_end_error'))
|
||||
.addClass('alert-danger')
|
||||
.removeClass('d-none');
|
||||
|
||||
$startDatetime.addClass('is-invalid');
|
||||
|
||||
$endDatetime.addClass('is-invalid');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Unavailability period records go to the appointments table.
|
||||
const unavailability = {
|
||||
start_datetime: startDateTimeMoment.format('YYYY-MM-DD HH:mm:ss'),
|
||||
end_datetime: endDateTimeMoment.format('YYYY-MM-DD HH:mm:ss'),
|
||||
notes: $unavailabilitiesModal.find('#unavailability-notes').val(),
|
||||
id_users_provider: $selectProvider.val(),
|
||||
};
|
||||
|
||||
if ($id.val() !== '') {
|
||||
// Set the id value, only if we are editing an appointment.
|
||||
unavailability.id = $id.val();
|
||||
}
|
||||
|
||||
const successCallback = () => {
|
||||
// Display success message to the user.
|
||||
App.Layouts.Backend.displayNotification(lang('unavailability_saved'));
|
||||
|
||||
// Close the modal dialog and refresh the calendar appointments.
|
||||
$unavailabilitiesModal.find('.alert').addClass('d-none');
|
||||
|
||||
$unavailabilitiesModal.modal('hide');
|
||||
|
||||
$reloadAppointments.trigger('click');
|
||||
};
|
||||
|
||||
App.Http.Calendar.saveUnavailability(unavailability, successCallback, null);
|
||||
});
|
||||
|
||||
/**
|
||||
* Event : Insert Unavailability Time Period Button "Click"
|
||||
*
|
||||
* When the user clicks this button a popup dialog appears and the use can set a time period where
|
||||
* he cannot accept any appointments.
|
||||
*/
|
||||
$insertUnavailability.on('click', () => {
|
||||
resetModal();
|
||||
|
||||
const $dialog = $('#unavailabilities-modal');
|
||||
|
||||
// Set the default datetime values.
|
||||
const startMoment = moment();
|
||||
|
||||
const currentMin = parseInt(startMoment.format('mm'));
|
||||
|
||||
if (currentMin > 0 && currentMin < 15) {
|
||||
startMoment.set({minutes: 15});
|
||||
} else if (currentMin > 15 && currentMin < 30) {
|
||||
startMoment.set({minutes: 30});
|
||||
} else if (currentMin > 30 && currentMin < 45) {
|
||||
startMoment.set({minutes: 45});
|
||||
} else {
|
||||
startMoment.add(1, 'hour').set({minutes: 0});
|
||||
}
|
||||
|
||||
if ($('.calendar-view').length === 0) {
|
||||
$selectProvider.val($selectFilterItem.val()).closest('.form-group').hide();
|
||||
}
|
||||
|
||||
App.Utils.UI.setDateTimePickerValue($startDatetime, startMoment.toDate());
|
||||
App.Utils.UI.setDateTimePickerValue($endDatetime, startMoment.add(1, 'hour').toDate());
|
||||
|
||||
$dialog.find('.modal-header h3').text(lang('new_unavailability_title'));
|
||||
$dialog.modal('show');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset unavailability dialog form.
|
||||
*
|
||||
* Reset the "#unavailabilities-modal" dialog. Use this method to bring the dialog to the initial state
|
||||
* before it becomes visible to the user.
|
||||
*/
|
||||
function resetModal() {
|
||||
$id.val('');
|
||||
|
||||
// Set default time values
|
||||
const start = App.Utils.Date.format(moment().toDate(), vars('date_format'), vars('time_format'), true);
|
||||
|
||||
const end = App.Utils.Date.format(
|
||||
moment().add(1, 'hour').toDate(),
|
||||
vars('date_format'),
|
||||
vars('time_format'),
|
||||
true,
|
||||
);
|
||||
|
||||
App.Utils.UI.initializeDateTimePicker($startDatetime);
|
||||
|
||||
$startDatetime.val(start);
|
||||
|
||||
App.Utils.UI.initializeDateTimePicker($endDatetime);
|
||||
|
||||
$endDatetime.val(end);
|
||||
|
||||
// Clear the unavailability notes field.
|
||||
$notes.val('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the module.
|
||||
*/
|
||||
function initialize() {
|
||||
for (const index in vars('available_providers')) {
|
||||
const provider = vars('available_providers')[index];
|
||||
|
||||
$selectProvider.append(new Option(provider.first_name + ' ' + provider.last_name, provider.id));
|
||||
}
|
||||
|
||||
addEventListeners();
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialize);
|
||||
|
||||
return {
|
||||
resetModal,
|
||||
};
|
||||
})();
|
||||
493
assets/js/components/working_plan_exceptions_modal.js
Normal file
493
assets/js/components/working_plan_exceptions_modal.js
Normal file
@@ -0,0 +1,493 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Working plan exceptions modal component.
|
||||
*
|
||||
* This module implements the working plan exceptions modal functionality.
|
||||
*/
|
||||
App.Components.WorkingPlanExceptionsModal = (function () {
|
||||
const $modal = $('#working-plan-exceptions-modal');
|
||||
const $date = $('#working-plan-exceptions-date');
|
||||
const $start = $('#working-plan-exceptions-start');
|
||||
const $end = $('#working-plan-exceptions-end');
|
||||
const $breaks = $('#working-plan-exceptions-breaks');
|
||||
const $save = $('#working-plan-exceptions-save');
|
||||
const $addBreak = $('.working-plan-exceptions-add-break');
|
||||
const $isNonWorkingDay = $('#working-plan-exceptions-is-non-working-day');
|
||||
|
||||
const moment = window.moment;
|
||||
|
||||
let deferred = null;
|
||||
let enableSubmit = false;
|
||||
let enableCancel = false;
|
||||
|
||||
/**
|
||||
* Reset the modal fields back to the original empty state.
|
||||
*/
|
||||
function resetModal() {
|
||||
$addBreak.prop('disabled', false);
|
||||
$date.val('');
|
||||
$start.val('');
|
||||
$end.val('');
|
||||
$breaks.find('tbody').html(renderNoBreaksRow());
|
||||
$isNonWorkingDay.prop('checked', false);
|
||||
toggleFieldsByNonWorkingDay(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a single table row as a placeholder to empty breaks table.
|
||||
*/
|
||||
function renderNoBreaksRow() {
|
||||
return $(`
|
||||
<tr class="no-breaks-row">
|
||||
<td colspan="3" class="text-center">
|
||||
${lang('no_breaks')}
|
||||
</td>
|
||||
</tr>
|
||||
`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle the state of the fields depending on the non-working day checkbox value.
|
||||
*
|
||||
* @param {Boolean} isNonWorkingDay
|
||||
*/
|
||||
function toggleFieldsByNonWorkingDay(isNonWorkingDay) {
|
||||
$start.prop('disabled', isNonWorkingDay).toggleClass('text-decoration-line-through', isNonWorkingDay);
|
||||
$end.prop('disabled', isNonWorkingDay).toggleClass('text-decoration-line-through', isNonWorkingDay);
|
||||
$addBreak.prop('disabled', isNonWorkingDay);
|
||||
$breaks.find('button').prop('disabled', isNonWorkingDay);
|
||||
$breaks.toggleClass('text-decoration-line-through', isNonWorkingDay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the modal form fields and return false if the validation fails.
|
||||
*
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
function validate() {
|
||||
$modal.find('.is-invalid').removeClass('is-invalid');
|
||||
|
||||
const date = App.Utils.UI.getDateTimePickerValue($date);
|
||||
|
||||
if (!date) {
|
||||
$date.addClass('is-invalid');
|
||||
}
|
||||
|
||||
const start = App.Utils.UI.getDateTimePickerValue($start);
|
||||
|
||||
if (!start) {
|
||||
$start.addClass('is-invalid');
|
||||
}
|
||||
|
||||
const end = App.Utils.UI.getDateTimePickerValue($end);
|
||||
|
||||
if (!end) {
|
||||
$end.addClass('is-invalid');
|
||||
}
|
||||
|
||||
return !$modal.find('.is-invalid').length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Event: On Modal "Hidden"
|
||||
*
|
||||
* This event is used to automatically reset the modal back to the original state.
|
||||
*/
|
||||
function onModalHidden() {
|
||||
resetModal();
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the entered break entries.
|
||||
*
|
||||
* @returns {Array}
|
||||
*/
|
||||
function getBreaks() {
|
||||
const breaks = [];
|
||||
|
||||
$breaks
|
||||
.find('tbody tr')
|
||||
.not('.no-breaks-row')
|
||||
.each((index, tr) => {
|
||||
const $tr = $(tr);
|
||||
|
||||
if ($tr.find('input:text').length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const start = $tr.find('.working-plan-exceptions-break-start').text();
|
||||
const end = $tr.find('.working-plan-exceptions-break-end').text();
|
||||
|
||||
breaks.push({
|
||||
start: moment(start, vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm').format('HH:mm'),
|
||||
end: moment(end, vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm').format('HH:mm'),
|
||||
});
|
||||
});
|
||||
|
||||
// Sort breaks increasingly by hour within day
|
||||
breaks.sort((break1, break2) => {
|
||||
// We can do a direct string comparison since we have time based on 24 hours clock.
|
||||
return break1.start.localeCompare(break2.start);
|
||||
});
|
||||
|
||||
return breaks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Event: On Save "Click"
|
||||
*
|
||||
* Serialize the entire working plan exception and resolved the promise so that external code can save it.
|
||||
*/
|
||||
function onSaveClick() {
|
||||
if (!deferred) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validate()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const date = moment(App.Utils.UI.getDateTimePickerValue($date)).format('YYYY-MM-DD');
|
||||
|
||||
const isNonWorkingDay = $isNonWorkingDay.prop('checked');
|
||||
|
||||
const workingPlanException = isNonWorkingDay
|
||||
? null
|
||||
: {
|
||||
start: moment(App.Utils.UI.getDateTimePickerValue($start)).format('HH:mm'),
|
||||
end: moment(App.Utils.UI.getDateTimePickerValue($end)).format('HH:mm'),
|
||||
breaks: getBreaks(),
|
||||
};
|
||||
|
||||
deferred.resolve(date, workingPlanException);
|
||||
|
||||
$modal.modal('hide');
|
||||
|
||||
resetModal();
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable the inline-editable table cell functionality for the provided target element..
|
||||
*
|
||||
* @param {jQuery} $target
|
||||
*/
|
||||
function editableTimeCell($target) {
|
||||
$target.editable(
|
||||
(value) => {
|
||||
// Do not return the value because the user needs to press the "Save" button.
|
||||
return value;
|
||||
},
|
||||
{
|
||||
event: 'edit',
|
||||
height: '30px',
|
||||
submit: $('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'd-none submit-editable',
|
||||
'text': lang('save'),
|
||||
}).get(0).outerHTML,
|
||||
cancel: $('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'd-none cancel-editable',
|
||||
'text': lang('cancel'),
|
||||
}).get(0).outerHTML,
|
||||
onblur: 'ignore',
|
||||
onreset: () => {
|
||||
if (!enableCancel) {
|
||||
return false; // disable ESC button
|
||||
}
|
||||
},
|
||||
onsubmit: () => {
|
||||
if (!enableSubmit) {
|
||||
return false; // disable Enter button
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function resetTimeSelection() {
|
||||
App.Utils.UI.setDateTimePickerValue($start, moment('08:00', 'HH:mm').toDate());
|
||||
App.Utils.UI.setDateTimePickerValue($end, moment('20:00', 'HH:mm').toDate());
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the modal and start adding a new working plan exception.
|
||||
*
|
||||
* @returns {*|jQuery.Deferred}
|
||||
*/
|
||||
function add() {
|
||||
deferred = $.Deferred();
|
||||
|
||||
App.Utils.UI.setDateTimePickerValue($date, new Date());
|
||||
|
||||
resetTimeSelection();
|
||||
|
||||
$isNonWorkingDay.prop('checked', false);
|
||||
|
||||
$breaks.find('tbody').html(renderNoBreaksRow());
|
||||
|
||||
$modal.modal('show');
|
||||
|
||||
return deferred.promise();
|
||||
}
|
||||
|
||||
/**
|
||||
* Modify the provided working plan exception for the selected date.
|
||||
*
|
||||
* @param {String} date
|
||||
* @param {Object} workingPlanException
|
||||
*
|
||||
* @return {*|jQuery.Deferred}
|
||||
*/
|
||||
function edit(date, workingPlanException) {
|
||||
deferred = $.Deferred();
|
||||
|
||||
const isNonWorkingDay = !Boolean(workingPlanException);
|
||||
|
||||
App.Utils.UI.setDateTimePickerValue($date, moment(date, 'YYYY-MM-DD').toDate());
|
||||
|
||||
if (isNonWorkingDay === false) {
|
||||
App.Utils.UI.setDateTimePickerValue($start, moment(workingPlanException.start, 'HH:mm').toDate());
|
||||
App.Utils.UI.setDateTimePickerValue($end, moment(workingPlanException.end, 'HH:mm').toDate());
|
||||
|
||||
if (!workingPlanException.breaks) {
|
||||
$breaks.find('tbody').html(renderNoBreaksRow());
|
||||
}
|
||||
|
||||
workingPlanException.breaks.forEach((workingPlanExceptionBreak) => {
|
||||
renderBreakRow(workingPlanExceptionBreak).appendTo($breaks.find('tbody'));
|
||||
});
|
||||
|
||||
editableTimeCell(
|
||||
$breaks.find('tbody .working-plan-exceptions-break-start, tbody .working-plan-exceptions-break-end'),
|
||||
);
|
||||
} else {
|
||||
App.Utils.UI.setDateTimePickerValue($start, moment('08:00', 'HH:mm').toDate());
|
||||
App.Utils.UI.setDateTimePickerValue($end, moment('20:00', 'HH:mm').toDate());
|
||||
$breaks.find('tbody').html(renderNoBreaksRow());
|
||||
}
|
||||
|
||||
$isNonWorkingDay.prop('checked', isNonWorkingDay);
|
||||
|
||||
toggleFieldsByNonWorkingDay(isNonWorkingDay);
|
||||
|
||||
$modal.modal('show');
|
||||
|
||||
return deferred.promise();
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a break table row based on the provided break period object.
|
||||
*
|
||||
* @param {Object} breakPeriod
|
||||
*
|
||||
* @return {jQuery}
|
||||
*/
|
||||
function renderBreakRow(breakPeriod) {
|
||||
const timeFormat = vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm';
|
||||
|
||||
return $('<tr/>', {
|
||||
'html': [
|
||||
$('<td/>', {
|
||||
'class': 'working-plan-exceptions-break-start editable',
|
||||
'text': moment(breakPeriod.start, 'HH:mm').format(timeFormat),
|
||||
}),
|
||||
$('<td/>', {
|
||||
'class': 'working-plan-exceptions-break-end editable',
|
||||
'text': moment(breakPeriod.end, 'HH:mm').format(timeFormat),
|
||||
}),
|
||||
$('<td/>', {
|
||||
'html': [
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm me-2 working-plan-exceptions-edit-break',
|
||||
'title': lang('edit'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-edit',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm working-plan-exceptions-delete-break',
|
||||
'title': lang('delete'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-trash-alt',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm me-2 working-plan-exceptions-save-break d-none',
|
||||
'title': lang('save'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-check-circle',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm working-plan-exceptions-cancel-break d-none',
|
||||
'title': lang('cancel'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-ban',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Event: Add Break "Click"
|
||||
*/
|
||||
function onAddBreakClick() {
|
||||
const $newBreak = renderBreakRow({
|
||||
start: '12:00',
|
||||
end: '14:00',
|
||||
}).appendTo('#working-plan-exceptions-breaks tbody');
|
||||
|
||||
// Bind editable and event handlers.
|
||||
editableTimeCell($newBreak.find('.working-plan-exceptions-break-start, .working-plan-exceptions-break-end'));
|
||||
$newBreak.find('.working-plan-exceptions-edit-break').trigger('click');
|
||||
$addBreak.prop('disabled', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Event: Edit Break "Click"
|
||||
*/
|
||||
function onEditBreakClick() {
|
||||
// Reset previous editable table cells.
|
||||
const $previousEdits = $(this).closest('table').find('.editable');
|
||||
|
||||
$previousEdits.each((index, editable) => {
|
||||
if (editable.reset) {
|
||||
editable.reset();
|
||||
}
|
||||
});
|
||||
|
||||
// Make all cells in current row editable.
|
||||
let $tr = $(this).closest('tr');
|
||||
$tr.children().trigger('edit');
|
||||
App.Utils.UI.initializeTimePicker(
|
||||
$tr.find('.working-plan-exceptions-break-start input, .working-plan-exceptions-break-end input'),
|
||||
);
|
||||
$(this).closest('tr').find('.working-plan-exceptions-break-start').focus();
|
||||
|
||||
// Show save - cancel buttons.
|
||||
$tr = $(this).closest('tr');
|
||||
$tr.find('.working-plan-exceptions-edit-break, .working-plan-exceptions-delete-break').addClass('d-none');
|
||||
$tr.find('.working-plan-exceptions-save-break, .working-plan-exceptions-cancel-break').removeClass('d-none');
|
||||
$tr.find('select,input:text').addClass('form-control input-sm');
|
||||
|
||||
$addBreak.prop('disabled', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Event: Delete Break "Click"
|
||||
*/
|
||||
function onDeleteBreakClick() {
|
||||
$(this).closest('tr').remove();
|
||||
}
|
||||
|
||||
/**
|
||||
* Event: Save Break "Click"
|
||||
*/
|
||||
function onSaveBreakClick() {
|
||||
// Break's start time must always be prior to break's end.
|
||||
const $tr = $(this).closest('tr');
|
||||
const start = moment(
|
||||
$tr.find('.working-plan-exceptions-break-start input').val(),
|
||||
vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm',
|
||||
);
|
||||
const end = moment(
|
||||
$tr.find('.working-plan-exceptions-break-end input').val(),
|
||||
vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm',
|
||||
);
|
||||
|
||||
if (start > end) {
|
||||
$tr.find('.working-plan-exceptions-break-end input').val(
|
||||
start.add(1, 'hour').format(vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm'),
|
||||
);
|
||||
}
|
||||
|
||||
enableSubmit = true;
|
||||
$tr.find('.editable .submit-editable').trigger('click');
|
||||
enableSubmit = false;
|
||||
|
||||
$tr.find('.working-plan-exceptions-save-break, .working-plan-exceptions-cancel-break').addClass('d-none');
|
||||
$tr.closest('table')
|
||||
.find('.working-plan-exceptions-edit-break, .working-plan-exceptions-delete-break')
|
||||
.removeClass('d-none');
|
||||
$addBreak.prop('disabled', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Event: Cancel Break "Click"
|
||||
*/
|
||||
function onCancelBreakClick() {
|
||||
const $tr = $(this).closest('tr');
|
||||
enableCancel = true;
|
||||
$tr.find('.cancel-editable').trigger('click');
|
||||
enableCancel = false;
|
||||
|
||||
$breaks
|
||||
.find('.working-plan-exceptions-edit-break, .working-plan-exceptions-delete-break')
|
||||
.removeClass('d-none');
|
||||
$tr.find('.working-plan-exceptions-save-break, .working-plan-exceptions-cancel-break').addClass('d-none');
|
||||
$addBreak.prop('disabled', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Event: Is Non-Working Day "Change"
|
||||
*/
|
||||
function onIsNonWorkingDayChange() {
|
||||
const isNonWorkingDay = $isNonWorkingDay.prop('checked');
|
||||
resetTimeSelection();
|
||||
toggleFieldsByNonWorkingDay(isNonWorkingDay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the module.
|
||||
*/
|
||||
function initialize() {
|
||||
App.Utils.UI.initializeDatePicker($date);
|
||||
App.Utils.UI.initializeTimePicker($start);
|
||||
App.Utils.UI.initializeTimePicker($end);
|
||||
|
||||
$modal
|
||||
.on('hidden.bs.modal', onModalHidden)
|
||||
.on('click', '.working-plan-exceptions-add-break', onAddBreakClick)
|
||||
.on('click', '.working-plan-exceptions-edit-break', onEditBreakClick)
|
||||
.on('click', '.working-plan-exceptions-delete-break', onDeleteBreakClick)
|
||||
.on('click', '.working-plan-exceptions-save-break', onSaveBreakClick)
|
||||
.on('click', '.working-plan-exceptions-cancel-break', onCancelBreakClick);
|
||||
|
||||
$save.on('click', onSaveClick);
|
||||
|
||||
$isNonWorkingDay.on('change', onIsNonWorkingDayChange);
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialize);
|
||||
|
||||
return {
|
||||
add,
|
||||
edit,
|
||||
};
|
||||
})();
|
||||
60
assets/js/http/account_http_client.js
Normal file
60
assets/js/http/account_http_client.js
Normal file
@@ -0,0 +1,60 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the account related HTTP requests.
|
||||
*/
|
||||
App.Http.Account = (function () {
|
||||
/**
|
||||
* Save account.
|
||||
*
|
||||
* @param {Object} account
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(account) {
|
||||
const url = App.Utils.Url.siteUrl('account/save');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
account,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate username.
|
||||
*
|
||||
* @param {Number} userId
|
||||
* @param {String} username
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function validateUsername(userId, username) {
|
||||
const url = App.Utils.Url.siteUrl('account/validate_username');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
user_id: userId,
|
||||
username,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
validateUsername,
|
||||
};
|
||||
})();
|
||||
133
assets/js/http/admins_http_client.js
Normal file
133
assets/js/http/admins_http_client.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the admins related HTTP requests.
|
||||
*/
|
||||
App.Http.Admins = (function () {
|
||||
/**
|
||||
* Save (create or update) a admin.
|
||||
*
|
||||
* @param {Object} admin
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(admin) {
|
||||
return admin.id ? update(admin) : store(admin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an admin.
|
||||
*
|
||||
* @param {Object} admin
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function store(admin) {
|
||||
const url = App.Utils.Url.siteUrl('admins/store');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
admin: admin,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an admin.
|
||||
*
|
||||
* @param {Object} admin
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function update(admin) {
|
||||
const url = App.Utils.Url.siteUrl('admins/update');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
admin: admin,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an admin.
|
||||
*
|
||||
* @param {Number} adminId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function destroy(adminId) {
|
||||
const url = App.Utils.Url.siteUrl('admins/destroy');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
admin_id: adminId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search admins by keyword.
|
||||
*
|
||||
* @param {String} keyword
|
||||
* @param {Number} [limit]
|
||||
* @param {Number} [offset]
|
||||
* @param {String} [orderBy]
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function search(keyword, limit = null, offset = null, orderBy = null) {
|
||||
const url = App.Utils.Url.siteUrl('admins/search');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
keyword,
|
||||
limit,
|
||||
offset,
|
||||
order_by: orderBy || undefined,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an admin.
|
||||
*
|
||||
* @param {Number} adminId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function find(adminId) {
|
||||
const url = App.Utils.Url.siteUrl('admins/find');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
admin_id: adminId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
store,
|
||||
update,
|
||||
destroy,
|
||||
search,
|
||||
find,
|
||||
};
|
||||
})();
|
||||
39
assets/js/http/api_settings_http_client.js
Normal file
39
assets/js/http/api_settings_http_client.js
Normal file
@@ -0,0 +1,39 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the API settings related HTTP requests.
|
||||
*/
|
||||
App.Http.ApiSettings = (function () {
|
||||
/**
|
||||
* Save API settings.
|
||||
*
|
||||
* @param {Object} apiSettings
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(apiSettings) {
|
||||
const url = App.Utils.Url.siteUrl('api_settings/save');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
api_settings: apiSettings,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
};
|
||||
})();
|
||||
133
assets/js/http/appointments_http_client.js
Normal file
133
assets/js/http/appointments_http_client.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Appointments HTTP client.
|
||||
*
|
||||
* This module implements the appointments related HTTP requests.
|
||||
*/
|
||||
App.Http.Appointments = (function () {
|
||||
/**
|
||||
* Save (create or update) an appointment.
|
||||
*
|
||||
* @param {Object} appointment
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(appointment) {
|
||||
return appointment.id ? update(appointment) : store(appointment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an appointment.
|
||||
*
|
||||
* @param {Object} appointment
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function store(appointment) {
|
||||
const url = App.Utils.Url.siteUrl('appointments/store');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
appointment: appointment,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an appointment.
|
||||
*
|
||||
* @param {Object} appointment
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function update(appointment) {
|
||||
const url = App.Utils.Url.siteUrl('appointments/update');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
appointment: appointment,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an appointment.
|
||||
*
|
||||
* @param {Number} appointmentId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function destroy(appointmentId) {
|
||||
const url = App.Utils.Url.siteUrl('appointments/destroy');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
appointment_id: appointmentId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search appointments by keyword.
|
||||
*
|
||||
* @param {String} keyword
|
||||
* @param {Number} [limit]
|
||||
* @param {Number} [offset]
|
||||
* @param {String} [orderBy]
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function search(keyword, limit = null, offset = null, orderBy = null) {
|
||||
const url = App.Utils.Url.siteUrl('appointments/search');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
keyword,
|
||||
limit,
|
||||
offset,
|
||||
order_by: orderBy || undefined,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an appointment.
|
||||
*
|
||||
* @param {Number} appointmentId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function find(appointmentId) {
|
||||
const url = App.Utils.Url.siteUrl('appointments/find');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
appointment_id: appointmentId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
store,
|
||||
update,
|
||||
destroy,
|
||||
search,
|
||||
find,
|
||||
};
|
||||
})();
|
||||
133
assets/js/http/blocked_periods_http_client.js
Normal file
133
assets/js/http/blocked_periods_http_client.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the blocked-periods related HTTP requests.
|
||||
*/
|
||||
App.Http.BlockedPeriods = (function () {
|
||||
/**
|
||||
* Save (create or update) a blocked-period.
|
||||
*
|
||||
* @param {Object} blockedPeriod
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(blockedPeriod) {
|
||||
return blockedPeriod.id ? update(blockedPeriod) : store(blockedPeriod);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a blocked-period.
|
||||
*
|
||||
* @param {Object} blockedPeriod
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function store(blockedPeriod) {
|
||||
const url = App.Utils.Url.siteUrl('blocked_periods/store');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
blocked_period: blockedPeriod,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a blocked-period.
|
||||
*
|
||||
* @param {Object} blockedPeriod
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function update(blockedPeriod) {
|
||||
const url = App.Utils.Url.siteUrl('blocked_periods/update');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
blocked_period: blockedPeriod,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a blocked-period.
|
||||
*
|
||||
* @param {Number} blockedPeriodId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function destroy(blockedPeriodId) {
|
||||
const url = App.Utils.Url.siteUrl('blocked_periods/destroy');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
blocked_period_id: blockedPeriodId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search blocked-periods by keyword.
|
||||
*
|
||||
* @param {String} keyword
|
||||
* @param {Number} [limit]
|
||||
* @param {Number} [offset]
|
||||
* @param {String} [orderBy]
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function search(keyword, limit = null, offset = null, orderBy = null) {
|
||||
const url = App.Utils.Url.siteUrl('blocked_periods/search');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
keyword,
|
||||
limit,
|
||||
offset,
|
||||
order_by: orderBy || undefined,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a blocked-period.
|
||||
*
|
||||
* @param {Number} blockedPeriodId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function find(blockedPeriodId) {
|
||||
const url = App.Utils.Url.siteUrl('blocked_periods/find');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
blocked_period_id: blockedPeriodId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
store,
|
||||
update,
|
||||
destroy,
|
||||
search,
|
||||
find,
|
||||
};
|
||||
})();
|
||||
400
assets/js/http/booking_http_client.js
Normal file
400
assets/js/http/booking_http_client.js
Normal file
@@ -0,0 +1,400 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the booking related HTTP requests.
|
||||
*
|
||||
* Old Name: FrontendBookApi
|
||||
*/
|
||||
App.Http.Booking = (function () {
|
||||
const $selectDate = $('#select-date');
|
||||
const $selectService = $('#select-service');
|
||||
const $selectProvider = $('#select-provider');
|
||||
const $availableHours = $('#available-hours');
|
||||
const $captchaHint = $('#captcha-hint');
|
||||
const $captchaTitle = $('.captcha-title');
|
||||
|
||||
const MONTH_SEARCH_LIMIT = 2; // Months in the future
|
||||
|
||||
const moment = window.moment;
|
||||
|
||||
let unavailableDatesBackup;
|
||||
let selectedDateStringBackup;
|
||||
let processingUnavailableDates = false;
|
||||
let searchedMonthStart;
|
||||
let searchedMonthCounter = 0;
|
||||
|
||||
/**
|
||||
* Get Available Hours
|
||||
*
|
||||
* This function makes an AJAX call and returns the available hours for the selected service,
|
||||
* provider and date.
|
||||
*
|
||||
* @param {String} selectedDate The selected date of the available hours we need.
|
||||
*/
|
||||
function getAvailableHours(selectedDate) {
|
||||
$availableHours.empty();
|
||||
|
||||
// Find the selected service duration (it is going to be send within the "data" object).
|
||||
const serviceId = $selectService.val();
|
||||
|
||||
// Default value of duration (in minutes).
|
||||
let serviceDuration = 15;
|
||||
|
||||
const service = vars('available_services').find(
|
||||
(availableService) => Number(availableService.id) === Number(serviceId),
|
||||
);
|
||||
|
||||
if (service) {
|
||||
serviceDuration = service.duration;
|
||||
}
|
||||
|
||||
// If the manage mode is true then the appointment's start date should return as available too.
|
||||
const appointmentId = vars('manage_mode') ? vars('appointment_data').id : null;
|
||||
|
||||
// Make ajax post request and get the available hours.
|
||||
const url = App.Utils.Url.siteUrl('booking/get_available_hours');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
service_id: $selectService.val(),
|
||||
provider_id: $selectProvider.val(),
|
||||
selected_date: selectedDate,
|
||||
service_duration: serviceDuration,
|
||||
manage_mode: Number(vars('manage_mode') || 0),
|
||||
appointment_id: appointmentId,
|
||||
};
|
||||
|
||||
$.post(url, data).done((response) => {
|
||||
$availableHours.empty();
|
||||
|
||||
// The response contains the available hours for the selected provider and service. Fill the available
|
||||
// hours div with response data.
|
||||
if (response.length > 0) {
|
||||
let providerId = $selectProvider.val();
|
||||
|
||||
if (providerId === 'any-provider') {
|
||||
for (const availableProvider of vars('available_providers')) {
|
||||
if (availableProvider.services.indexOf(Number(serviceId)) !== -1) {
|
||||
providerId = availableProvider.id; // Use first available provider.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const provider = vars('available_providers').find(
|
||||
(availableProvider) => Number(providerId) === Number(availableProvider.id),
|
||||
);
|
||||
|
||||
if (!provider) {
|
||||
throw new Error('Could not find provider.');
|
||||
}
|
||||
|
||||
const providerTimezone = provider.timezone;
|
||||
const selectedTimezone = $('#select-timezone').val();
|
||||
const timeFormat = vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm';
|
||||
|
||||
response.forEach((availableHour) => {
|
||||
const availableHourMoment = moment
|
||||
.tz(selectedDate + ' ' + availableHour + ':00', providerTimezone)
|
||||
.tz(selectedTimezone);
|
||||
|
||||
if (availableHourMoment.format('YYYY-MM-DD') !== selectedDate) {
|
||||
return; // Due to the selected timezone the available hour belongs to another date.
|
||||
}
|
||||
|
||||
$availableHours.append(
|
||||
$('<button/>', {
|
||||
'class': 'btn btn-outline-secondary w-100 shadow-none available-hour',
|
||||
'data': {
|
||||
'value': availableHour,
|
||||
},
|
||||
'text': availableHourMoment.format(timeFormat),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
if (App.Pages.Booking.manageMode) {
|
||||
// Set the appointment's start time as the default selection.
|
||||
$('.available-hour')
|
||||
.removeClass('selected-hour')
|
||||
.filter(
|
||||
(index, availableHourEl) =>
|
||||
$(availableHourEl).text() ===
|
||||
moment(vars('appointment_data').start_datetime).format(timeFormat),
|
||||
)
|
||||
.addClass('selected-hour');
|
||||
} else {
|
||||
// Set the first available hour as the default selection.
|
||||
$('.available-hour:eq(0)').addClass('selected-hour');
|
||||
}
|
||||
|
||||
App.Pages.Booking.updateConfirmFrame();
|
||||
}
|
||||
|
||||
if (!$availableHours.find('.available-hour').length) {
|
||||
$availableHours.text(lang('no_available_hours'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an appointment to the database.
|
||||
*
|
||||
* This method will make an ajax call to the appointments controller that will register
|
||||
* the appointment to the database.
|
||||
*/
|
||||
function registerAppointment() {
|
||||
const $captchaText = $('.captcha-text');
|
||||
|
||||
if ($captchaText.length > 0) {
|
||||
$captchaText.removeClass('is-invalid');
|
||||
if ($captchaText.val() === '') {
|
||||
$captchaText.addClass('is-invalid');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const formData = JSON.parse($('input[name="post_data"]').val());
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
post_data: formData,
|
||||
};
|
||||
|
||||
if ($captchaText.length > 0) {
|
||||
data.captcha = $captchaText.val();
|
||||
}
|
||||
|
||||
if (vars('manage_mode')) {
|
||||
data.exclude_appointment_id = vars('appointment_data').id;
|
||||
}
|
||||
|
||||
const url = App.Utils.Url.siteUrl('booking/register');
|
||||
|
||||
const $layer = $('<div/>');
|
||||
|
||||
$.ajax({
|
||||
url: url,
|
||||
method: 'post',
|
||||
data: data,
|
||||
dataType: 'json',
|
||||
beforeSend: () => {
|
||||
$layer.appendTo('body').css({
|
||||
background: 'white',
|
||||
position: 'fixed',
|
||||
top: '0',
|
||||
left: '0',
|
||||
height: '100vh',
|
||||
width: '100vw',
|
||||
opacity: '0.5',
|
||||
});
|
||||
},
|
||||
})
|
||||
.done((response) => {
|
||||
if (response.captcha_verification === false) {
|
||||
$captchaHint.text(lang('captcha_is_wrong')).fadeTo(400, 1);
|
||||
|
||||
setTimeout(() => {
|
||||
$captchaHint.fadeTo(400, 0);
|
||||
}, 3000);
|
||||
|
||||
$captchaTitle.find('button').trigger('click');
|
||||
|
||||
$captchaText.addClass('is-invalid');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
window.location.href = App.Utils.Url.siteUrl('booking_confirmation/of/' + response.appointment_hash);
|
||||
})
|
||||
.fail(() => {
|
||||
$captchaTitle.find('button').trigger('click');
|
||||
})
|
||||
.always(() => {
|
||||
$layer.remove();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the unavailable dates of a provider.
|
||||
*
|
||||
* This method will fetch the unavailable dates of the selected provider and service and then it will
|
||||
* select the first available date (if any). It uses the "FrontendBookApi.getAvailableHours" method to
|
||||
* fetch the appointment* hours of the selected date.
|
||||
*
|
||||
* @param {Number} providerId The selected provider ID.
|
||||
* @param {Number} serviceId The selected service ID.
|
||||
* @param {String} selectedDateString Y-m-d value of the selected date.
|
||||
* @param {Number} [monthChangeStep] Whether to add or subtract months.
|
||||
*/
|
||||
function getUnavailableDates(providerId, serviceId, selectedDateString, monthChangeStep = 1) {
|
||||
if (processingUnavailableDates) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!providerId || !serviceId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const appointmentId = App.Pages.Booking.manageMode ? vars('appointment_data').id : null;
|
||||
|
||||
const url = App.Utils.Url.siteUrl('booking/get_unavailable_dates');
|
||||
|
||||
const data = {
|
||||
provider_id: providerId,
|
||||
service_id: serviceId,
|
||||
selected_date: encodeURIComponent(selectedDateString),
|
||||
csrf_token: vars('csrf_token'),
|
||||
manage_mode: Number(App.Pages.Booking.manageMode),
|
||||
appointment_id: appointmentId,
|
||||
};
|
||||
|
||||
$.ajax({
|
||||
url: url,
|
||||
type: 'GET',
|
||||
data: data,
|
||||
dataType: 'json',
|
||||
})
|
||||
.done((response) => {
|
||||
// In case the current month has no availability, the app will try the next one or the one after in order to
|
||||
// find a date that has at least one slot
|
||||
|
||||
if (response.is_month_unavailable) {
|
||||
if (!searchedMonthStart) {
|
||||
searchedMonthStart = selectedDateString;
|
||||
}
|
||||
|
||||
if (searchedMonthCounter >= MONTH_SEARCH_LIMIT) {
|
||||
// Need to mark the current month dates as unavailable
|
||||
const selectedDateMoment = moment(searchedMonthStart);
|
||||
const startOfMonthMoment = selectedDateMoment.clone().startOf('month');
|
||||
const endOfMonthMoment = selectedDateMoment.clone().endOf('month');
|
||||
const unavailableDates = [];
|
||||
|
||||
while (startOfMonthMoment.isSameOrBefore(endOfMonthMoment)) {
|
||||
unavailableDates.push(startOfMonthMoment.format('YYYY-MM-DD'));
|
||||
startOfMonthMoment.add(Math.abs(monthChangeStep), 'days'); // Move to the next day
|
||||
}
|
||||
|
||||
applyUnavailableDates(unavailableDates, searchedMonthStart, true);
|
||||
searchedMonthStart = undefined;
|
||||
searchedMonthCounter = 0;
|
||||
|
||||
return; // Stop searching
|
||||
}
|
||||
|
||||
searchedMonthCounter++;
|
||||
|
||||
const selectedDateMoment = moment(selectedDateString);
|
||||
selectedDateMoment.add(1, 'month');
|
||||
|
||||
const nextSelectedDate = selectedDateMoment.format('YYYY-MM-DD');
|
||||
getUnavailableDates(providerId, serviceId, nextSelectedDate, monthChangeStep);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
unavailableDatesBackup = response;
|
||||
selectedDateStringBackup = selectedDateString;
|
||||
applyUnavailableDates(response, selectedDateString, true);
|
||||
})
|
||||
.fail(() => {
|
||||
$selectDate.parent().fadeTo(400, 1);
|
||||
});
|
||||
}
|
||||
|
||||
function applyPreviousUnavailableDates() {
|
||||
applyUnavailableDates(unavailableDatesBackup, selectedDateStringBackup);
|
||||
}
|
||||
|
||||
function applyUnavailableDates(unavailableDates, selectedDateString, setDate) {
|
||||
setDate = setDate || false;
|
||||
|
||||
$selectDate.parent().fadeTo(400, 1);
|
||||
|
||||
processingUnavailableDates = true;
|
||||
|
||||
// Select first enabled date.
|
||||
const selectedDateMoment = moment(selectedDateString);
|
||||
const selectedDate = selectedDateMoment.toDate();
|
||||
const numberOfDays = selectedDateMoment.daysInMonth();
|
||||
|
||||
// If all the days are unavailable then hide the appointments hours.
|
||||
if (unavailableDates.length === numberOfDays) {
|
||||
$availableHours.text(lang('no_available_hours'));
|
||||
}
|
||||
|
||||
// Grey out unavailable dates.
|
||||
$selectDate[0]._flatpickr.set(
|
||||
'disable',
|
||||
unavailableDates.map((unavailableDate) => new Date(unavailableDate + 'T00:00')),
|
||||
);
|
||||
|
||||
if (setDate && !vars('manage_mode')) {
|
||||
for (let i = 1; i <= numberOfDays; i++) {
|
||||
const currentDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), i);
|
||||
|
||||
if (unavailableDates.indexOf(moment(currentDate).format('YYYY-MM-DD')) === -1) {
|
||||
App.Utils.UI.setDateTimePickerValue($selectDate, currentDate);
|
||||
getAvailableHours(moment(currentDate).format('YYYY-MM-DD'));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const dateQueryParam = App.Utils.Url.queryParam('date');
|
||||
|
||||
if (dateQueryParam) {
|
||||
const dateQueryParamMoment = moment(dateQueryParam);
|
||||
|
||||
if (
|
||||
dateQueryParamMoment.isValid() &&
|
||||
!unavailableDates.includes(dateQueryParam) &&
|
||||
dateQueryParamMoment.format('YYYY-MM') === selectedDateMoment.format('YYYY-MM')
|
||||
) {
|
||||
App.Utils.UI.setDateTimePickerValue($selectDate, dateQueryParamMoment.toDate());
|
||||
}
|
||||
}
|
||||
|
||||
searchedMonthStart = undefined;
|
||||
searchedMonthCounter = 0;
|
||||
processingUnavailableDates = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete personal information.
|
||||
*
|
||||
* @param {Number} customerToken Customer unique token.
|
||||
*/
|
||||
function deletePersonalInformation(customerToken) {
|
||||
const url = App.Utils.Url.siteUrl('privacy/delete_personal_information');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
customer_token: customerToken,
|
||||
};
|
||||
|
||||
$.post(url, data).done(() => {
|
||||
window.location.href = vars('base_url');
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
registerAppointment,
|
||||
getAvailableHours,
|
||||
getUnavailableDates,
|
||||
applyPreviousUnavailableDates,
|
||||
deletePersonalInformation,
|
||||
};
|
||||
})();
|
||||
39
assets/js/http/booking_settings_http_client.js
Normal file
39
assets/js/http/booking_settings_http_client.js
Normal file
@@ -0,0 +1,39 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the booking settings related HTTP requests.
|
||||
*/
|
||||
App.Http.BookingSettings = (function () {
|
||||
/**
|
||||
* Save booking settings.
|
||||
*
|
||||
* @param {Object} bookingSettings
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(bookingSettings) {
|
||||
const url = App.Utils.Url.siteUrl('booking_settings/save');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
booking_settings: bookingSettings,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
};
|
||||
})();
|
||||
58
assets/js/http/business_settings_http_client.js
Normal file
58
assets/js/http/business_settings_http_client.js
Normal file
@@ -0,0 +1,58 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the business settings related HTTP requests.
|
||||
*/
|
||||
App.Http.BusinessSettings = (function () {
|
||||
/**
|
||||
* Save business settings.
|
||||
*
|
||||
* @param {Object} businessSettings
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(businessSettings) {
|
||||
const url = App.Utils.Url.siteUrl('business_settings/save');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
business_settings: businessSettings,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply global working plan.
|
||||
*
|
||||
* @param {Object} workingPlan
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function applyGlobalWorkingPlan(workingPlan) {
|
||||
const url = App.Utils.Url.siteUrl('business_settings/apply_global_working_plan');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
working_plan: JSON.stringify(workingPlan),
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
applyGlobalWorkingPlan,
|
||||
};
|
||||
})();
|
||||
108
assets/js/http/caldav_http_client.js
Normal file
108
assets/js/http/caldav_http_client.js
Normal file
@@ -0,0 +1,108 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Caldav HTTP client.
|
||||
*
|
||||
* This module implements the Caldav Calendar related HTTP requests.
|
||||
*/
|
||||
App.Http.Caldav = (function () {
|
||||
/**
|
||||
* Select the Caldav Calendar for the synchronization with a provider.
|
||||
*
|
||||
* @param {Number} providerId
|
||||
* @param {String} caldavCalendarId
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function selectCaldavCalendar(providerId, caldavCalendarId) {
|
||||
const url = App.Utils.Url.siteUrl('caldav/select_caldav_calendar');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
provider_id: providerId,
|
||||
calendar_id: caldavCalendarId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable the Caldav Calendar syncing of a provider.
|
||||
*
|
||||
* @param {Number} providerId
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function disableProviderSync(providerId) {
|
||||
const url = App.Utils.Url.siteUrl('caldav/disable_provider_sync');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
provider_id: providerId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the available Caldav Calendars of the connected provider's account.
|
||||
*
|
||||
* @param {Number} providerId
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function getCaldavCalendars(providerId) {
|
||||
const url = App.Utils.Url.siteUrl('caldav/get_caldav_calendars');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
provider_id: providerId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger the sync process between Easy!Appointments and Caldav Calendar.
|
||||
*
|
||||
* @param {Number} providerId
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function syncWithCaldav(providerId) {
|
||||
const url = App.Utils.Url.siteUrl('caldav/sync/' + providerId);
|
||||
|
||||
return $.get(url);
|
||||
}
|
||||
|
||||
function connectToServer(providerId, caldavUrl, caldavUsername, caldavPassword) {
|
||||
const url = App.Utils.Url.siteUrl('caldav/connect_to_server');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
provider_id: providerId,
|
||||
caldav_url: caldavUrl,
|
||||
caldav_username: caldavUsername,
|
||||
caldav_password: caldavPassword,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
getCaldavCalendars,
|
||||
selectCaldavCalendar,
|
||||
disableProviderSync,
|
||||
syncWithCaldav,
|
||||
connectToServer,
|
||||
};
|
||||
})();
|
||||
255
assets/js/http/calendar_http_client.js
Normal file
255
assets/js/http/calendar_http_client.js
Normal file
@@ -0,0 +1,255 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the calendar related HTTP requests.
|
||||
*
|
||||
* Old Name: BackendCalendarApi
|
||||
*/
|
||||
App.Http.Calendar = (function () {
|
||||
/**
|
||||
* Save Appointment
|
||||
*
|
||||
* This method stores the changes of an already registered appointment into the database, via an ajax call.
|
||||
*
|
||||
* @param {Object} appointment Contain the new appointment data. The ID of the appointment must be already included.
|
||||
* The rest values must follow the database structure.
|
||||
* @param {Object} [customer] Optional, contains the customer data.
|
||||
* @param {Function} [successCallback] Optional, if defined, this function is going to be executed on post success.
|
||||
* @param {Function} [errorCallback] Optional, if defined, this function is going to be executed on post failure.
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function saveAppointment(appointment, customer, successCallback, errorCallback) {
|
||||
const url = App.Utils.Url.siteUrl('calendar/save_appointment');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
appointment_data: appointment,
|
||||
};
|
||||
|
||||
if (customer) {
|
||||
data.customer_data = customer;
|
||||
}
|
||||
|
||||
return $.post(url, data)
|
||||
.done((response) => {
|
||||
if (successCallback) {
|
||||
successCallback(response);
|
||||
}
|
||||
})
|
||||
.fail(() => {
|
||||
if (errorCallback) {
|
||||
errorCallback();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an appointment.
|
||||
*
|
||||
* @param {Number} appointmentId
|
||||
* @param {String} cancellationReason
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function deleteAppointment(appointmentId, cancellationReason) {
|
||||
const url = App.Utils.Url.siteUrl('calendar/delete_appointment');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
appointment_id: appointmentId,
|
||||
cancellation_reason: cancellationReason,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save unavailability period to database.
|
||||
*
|
||||
* @param {Object} unavailability Contains the unavailability period data.
|
||||
* @param {Function} [successCallback] The ajax success callback function.
|
||||
* @param {Function} [errorCallback] The ajax failure callback function.
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function saveUnavailability(unavailability, successCallback, errorCallback) {
|
||||
const url = App.Utils.Url.siteUrl('calendar/save_unavailability');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
unavailability: unavailability,
|
||||
};
|
||||
|
||||
return $.post(url, data)
|
||||
.done((response) => {
|
||||
if (successCallback) {
|
||||
successCallback(response);
|
||||
}
|
||||
})
|
||||
.fail(() => {
|
||||
if (errorCallback) {
|
||||
errorCallback();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an unavailability.
|
||||
*
|
||||
* @param {Number} unavailabilityId
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function deleteUnavailability(unavailabilityId) {
|
||||
const url = App.Utils.Url.siteUrl('calendar/delete_unavailability');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
unavailability_id: unavailabilityId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save working plan exception of work to database.
|
||||
*
|
||||
* @param {Date} date Contains the working plan exceptions data.
|
||||
* @param {Object} workingPlanException Contains the working plan exceptions data.
|
||||
* @param {Number} providerId Contains the working plan exceptions data.
|
||||
* @param {Function} successCallback The ajax success callback function.
|
||||
* @param {Function} errorCallback The ajax failure callback function.
|
||||
* @param {Date} [originalDate] On edit, provide the original date.
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function saveWorkingPlanException(
|
||||
date,
|
||||
workingPlanException,
|
||||
providerId,
|
||||
successCallback,
|
||||
errorCallback,
|
||||
originalDate,
|
||||
) {
|
||||
const url = App.Utils.Url.siteUrl('calendar/save_working_plan_exception');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
date: date,
|
||||
working_plan_exception: workingPlanException,
|
||||
provider_id: providerId,
|
||||
original_date: originalDate,
|
||||
};
|
||||
|
||||
return $.post(url, data)
|
||||
.done((response) => {
|
||||
if (successCallback) {
|
||||
successCallback(response);
|
||||
}
|
||||
})
|
||||
.fail(() => {
|
||||
if (errorCallback) {
|
||||
errorCallback();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete working plan exception
|
||||
*
|
||||
* @param {String} date
|
||||
* @param {Number} providerId
|
||||
* @param {Function} [successCallback]
|
||||
* @param {Function} [errorCallback]
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function deleteWorkingPlanException(date, providerId, successCallback, errorCallback) {
|
||||
const url = App.Utils.Url.siteUrl('calendar/delete_working_plan_exception');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
date: date,
|
||||
provider_id: providerId,
|
||||
};
|
||||
|
||||
return $.post(url, data)
|
||||
.done((response) => {
|
||||
if (successCallback) {
|
||||
successCallback(response);
|
||||
}
|
||||
})
|
||||
.fail(() => {
|
||||
if (errorCallback) {
|
||||
errorCallback();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the appointments for the displayed calendar period.
|
||||
*
|
||||
* @param {Number} recordId Record ID (provider or service).
|
||||
* @param {String} filterType The filter type, could be either "provider" or "service".
|
||||
* @param {String} startDate Visible start date of the calendar.
|
||||
* @param {String} endDate Visible end date of the calendar.
|
||||
*
|
||||
* @returns {jQuery.jqXHR}
|
||||
*/
|
||||
function getCalendarAppointments(recordId, startDate, endDate, filterType) {
|
||||
const url = App.Utils.Url.siteUrl('calendar/get_calendar_appointments');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
record_id: recordId,
|
||||
start_date: moment(startDate).format('YYYY-MM-DD'),
|
||||
end_date: moment(endDate).format('YYYY-MM-DD'),
|
||||
filter_type: filterType,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the calendar appointments for the table view (different data structure).
|
||||
*
|
||||
* @param {Date} startDate
|
||||
* @param {Date} endDate
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function getCalendarAppointmentsForTableView(startDate, endDate) {
|
||||
const url = App.Utils.Url.siteUrl('calendar/get_calendar_appointments_for_table_view');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
start_date: moment(startDate).format('YYYY-MM-DD'),
|
||||
end_date: moment(endDate).format('YYYY-MM-DD'),
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
saveAppointment,
|
||||
deleteAppointment,
|
||||
saveUnavailability,
|
||||
deleteUnavailability,
|
||||
saveWorkingPlanException,
|
||||
deleteWorkingPlanException,
|
||||
getCalendarAppointments,
|
||||
getCalendarAppointmentsForTableView,
|
||||
};
|
||||
})();
|
||||
133
assets/js/http/customers_http_client.js
Normal file
133
assets/js/http/customers_http_client.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the customers related HTTP requests.
|
||||
*/
|
||||
App.Http.Customers = (function () {
|
||||
/**
|
||||
* Save (create or update) a customer.
|
||||
*
|
||||
* @param {Object} customer
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(customer) {
|
||||
return customer.id ? update(customer) : store(customer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a customer.
|
||||
*
|
||||
* @param {Object} customer
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function store(customer) {
|
||||
const url = App.Utils.Url.siteUrl('customers/store');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
customer: customer,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a customer.
|
||||
*
|
||||
* @param {Object} customer
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function update(customer) {
|
||||
const url = App.Utils.Url.siteUrl('customers/update');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
customer: customer,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a customer.
|
||||
*
|
||||
* @param {Number} customerId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function destroy(customerId) {
|
||||
const url = App.Utils.Url.siteUrl('customers/destroy');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
customer_id: customerId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search customers by keyword.
|
||||
*
|
||||
* @param {String} keyword
|
||||
* @param {Number} [limit]
|
||||
* @param {Number} [offset]
|
||||
* @param {String} [orderBy]
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function search(keyword, limit = null, offset = null, orderBy = null) {
|
||||
const url = App.Utils.Url.siteUrl('customers/search');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
keyword,
|
||||
limit,
|
||||
offset,
|
||||
order_by: orderBy || undefined,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a customer.
|
||||
*
|
||||
* @param {Number} customerId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function find(customerId) {
|
||||
const url = App.Utils.Url.siteUrl('customers/find');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
customer_id: customerId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
store,
|
||||
update,
|
||||
destroy,
|
||||
search,
|
||||
find,
|
||||
};
|
||||
})();
|
||||
39
assets/js/http/general_settings_http_client.js
Normal file
39
assets/js/http/general_settings_http_client.js
Normal file
@@ -0,0 +1,39 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the general settings related HTTP requests.
|
||||
*/
|
||||
App.Http.GeneralSettings = (function () {
|
||||
/**
|
||||
* Save general settings.
|
||||
*
|
||||
* @param {Object} generalSettings
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(generalSettings) {
|
||||
const url = App.Utils.Url.siteUrl('general_settings/save');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
general_settings: generalSettings,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
};
|
||||
})();
|
||||
39
assets/js/http/google_analytics_settings_http_client.js
Normal file
39
assets/js/http/google_analytics_settings_http_client.js
Normal file
@@ -0,0 +1,39 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the Google Analytics settings related HTTP requests.
|
||||
*/
|
||||
App.Http.GoogleAnalyticsSettings = (function () {
|
||||
/**
|
||||
* Save Google Analytics settings.
|
||||
*
|
||||
* @param {Object} googleAnalyticsSettings
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(googleAnalyticsSettings) {
|
||||
const url = App.Utils.Url.siteUrl('google_analytics_settings/save');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
google_analytics_settings: googleAnalyticsSettings,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
};
|
||||
})();
|
||||
93
assets/js/http/google_http_client.js
Normal file
93
assets/js/http/google_http_client.js
Normal file
@@ -0,0 +1,93 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the Google Calendar related HTTP requests.
|
||||
*/
|
||||
App.Http.Google = (function () {
|
||||
/**
|
||||
* Select the Google Calendar for the synchronization with a provider.
|
||||
*
|
||||
* @param {Number} providerId
|
||||
* @param {String} googleCalendarId
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function selectGoogleCalendar(providerId, googleCalendarId) {
|
||||
const url = App.Utils.Url.siteUrl('google/select_google_calendar');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
provider_id: providerId,
|
||||
calendar_id: googleCalendarId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable the Google Calendar syncing of a provider.
|
||||
*
|
||||
* @param {Number} providerId
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function disableProviderSync(providerId) {
|
||||
const url = App.Utils.Url.siteUrl('google/disable_provider_sync');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
provider_id: providerId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the available Google Calendars of the connected provider's account.
|
||||
*
|
||||
* @param {Number} providerId
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function getGoogleCalendars(providerId) {
|
||||
const url = App.Utils.Url.siteUrl('google/get_google_calendars');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
provider_id: providerId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger the sync process between Easy!Appointments and Google Calendar.
|
||||
*
|
||||
* @param {Number} providerId
|
||||
*
|
||||
* @return {*|jQuery}
|
||||
*/
|
||||
function syncWithGoogle(providerId) {
|
||||
const url = App.Utils.Url.siteUrl('google/sync/' + providerId);
|
||||
|
||||
return $.get(url);
|
||||
}
|
||||
|
||||
return {
|
||||
getGoogleCalendars,
|
||||
selectGoogleCalendar,
|
||||
disableProviderSync,
|
||||
syncWithGoogle,
|
||||
};
|
||||
})();
|
||||
58
assets/js/http/ldap_settings_http_client.js
Normal file
58
assets/js/http/ldap_settings_http_client.js
Normal file
@@ -0,0 +1,58 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the LDAP settings related HTTP requests.
|
||||
*/
|
||||
App.Http.LdapSettings = (function () {
|
||||
/**
|
||||
* Save LDAP settings.
|
||||
*
|
||||
* @param {Object} ldapSettings
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(ldapSettings) {
|
||||
const url = App.Utils.Url.siteUrl('ldap_settings/save');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
ldap_settings: ldapSettings,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search LDAP server.
|
||||
*
|
||||
* @param {String} keyword
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function search(keyword) {
|
||||
const url = App.Utils.Url.siteUrl('ldap_settings/search');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
keyword,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
search,
|
||||
};
|
||||
})();
|
||||
39
assets/js/http/legal_settings_http_client.js
Normal file
39
assets/js/http/legal_settings_http_client.js
Normal file
@@ -0,0 +1,39 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the legal settings related HTTP requests.
|
||||
*/
|
||||
App.Http.LegalSettings = (function () {
|
||||
/**
|
||||
* Save legal settings.
|
||||
*
|
||||
* @param {Object} legalSettings
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(legalSettings) {
|
||||
const url = App.Utils.Url.siteUrl('legal_settings/save');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
legal_settings: legalSettings,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
};
|
||||
})();
|
||||
37
assets/js/http/localization_http_client.js
Normal file
37
assets/js/http/localization_http_client.js
Normal file
@@ -0,0 +1,37 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Localization HTTP client.
|
||||
*
|
||||
* This module implements the account related HTTP requests.
|
||||
*/
|
||||
App.Http.Localization = (function () {
|
||||
/**
|
||||
* Change language.
|
||||
*
|
||||
* @param {String} language
|
||||
*/
|
||||
function changeLanguage(language) {
|
||||
const url = App.Utils.Url.siteUrl('localization/change_language');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
language,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
changeLanguage,
|
||||
};
|
||||
})();
|
||||
41
assets/js/http/login_http_client.js
Normal file
41
assets/js/http/login_http_client.js
Normal file
@@ -0,0 +1,41 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the account login related HTTP requests.
|
||||
*/
|
||||
App.Http.Login = (function () {
|
||||
/**
|
||||
* Perform an account recovery.
|
||||
*
|
||||
* @param {String} username
|
||||
* @param {String} password
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function validate(username, password) {
|
||||
const url = App.Utils.Url.siteUrl('login/validate');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
username,
|
||||
password,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
validate,
|
||||
};
|
||||
})();
|
||||
39
assets/js/http/matomo_analytics_settings_http_client.js
Normal file
39
assets/js/http/matomo_analytics_settings_http_client.js
Normal file
@@ -0,0 +1,39 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the Matomo Analytics settings related HTTP requests.
|
||||
*/
|
||||
App.Http.MatomoAnalyticsSettings = (function () {
|
||||
/**
|
||||
* Save Matomo Analytics settings.
|
||||
*
|
||||
* @param {Object} matomoAnalyticsSettings
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(matomoAnalyticsSettings) {
|
||||
const url = App.Utils.Url.siteUrl('matomo_analytics_settings/save');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
matomo_analytics_settings: matomoAnalyticsSettings,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
};
|
||||
})();
|
||||
133
assets/js/http/providers_http_client.js
Normal file
133
assets/js/http/providers_http_client.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the providers related HTTP requests.
|
||||
*/
|
||||
App.Http.Providers = (function () {
|
||||
/**
|
||||
* Save (create or update) a provider.
|
||||
*
|
||||
* @param {Object} provider
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(provider) {
|
||||
return provider.id ? update(provider) : store(provider);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a provider.
|
||||
*
|
||||
* @param {Object} provider
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function store(provider) {
|
||||
const url = App.Utils.Url.siteUrl('providers/store');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
provider: provider,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a provider.
|
||||
*
|
||||
* @param {Object} provider
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function update(provider) {
|
||||
const url = App.Utils.Url.siteUrl('providers/update');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
provider: provider,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a provider.
|
||||
*
|
||||
* @param {Number} providerId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function destroy(providerId) {
|
||||
const url = App.Utils.Url.siteUrl('providers/destroy');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
provider_id: providerId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search providers by keyword.
|
||||
*
|
||||
* @param {String} keyword
|
||||
* @param {Number} [limit]
|
||||
* @param {Number} [offset]
|
||||
* @param {String} [orderBy]
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function search(keyword, limit = null, offset = null, orderBy = null) {
|
||||
const url = App.Utils.Url.siteUrl('providers/search');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
keyword,
|
||||
limit,
|
||||
offset,
|
||||
order_by: orderBy || undefined,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a provider.
|
||||
*
|
||||
* @param {Number} providerId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function find(providerId) {
|
||||
const url = App.Utils.Url.siteUrl('providers/find');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
provider_id: providerId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
store,
|
||||
update,
|
||||
destroy,
|
||||
search,
|
||||
find,
|
||||
};
|
||||
})();
|
||||
41
assets/js/http/recovery_http_client.js
Normal file
41
assets/js/http/recovery_http_client.js
Normal file
@@ -0,0 +1,41 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the account recovery related HTTP requests.
|
||||
*/
|
||||
App.Http.Recovery = (function () {
|
||||
/**
|
||||
* Perform an account recovery.
|
||||
*
|
||||
* @param {String} username
|
||||
* @param {String} email
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function perform(username, email) {
|
||||
const url = App.Utils.Url.siteUrl('recovery/perform');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
username,
|
||||
email,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
perform,
|
||||
};
|
||||
})();
|
||||
133
assets/js/http/secretaries_http_client.js
Normal file
133
assets/js/http/secretaries_http_client.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the secretaries related HTTP requests.
|
||||
*/
|
||||
App.Http.Secretaries = (function () {
|
||||
/**
|
||||
* Save (create or update) a secretary.
|
||||
*
|
||||
* @param {Object} secretary
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(secretary) {
|
||||
return secretary.id ? update(secretary) : store(secretary);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a secretary.
|
||||
*
|
||||
* @param {Object} secretary
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function store(secretary) {
|
||||
const url = App.Utils.Url.siteUrl('secretaries/store');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
secretary: secretary,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a secretary.
|
||||
*
|
||||
* @param {Object} secretary
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function update(secretary) {
|
||||
const url = App.Utils.Url.siteUrl('secretaries/update');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
secretary: secretary,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a secretary.
|
||||
*
|
||||
* @param {Number} secretaryId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function destroy(secretaryId) {
|
||||
const url = App.Utils.Url.siteUrl('secretaries/destroy');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
secretary_id: secretaryId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search secretaries by keyword.
|
||||
*
|
||||
* @param {String} keyword
|
||||
* @param {Number} [limit]
|
||||
* @param {Number} [offset]
|
||||
* @param {String} [orderBy]
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function search(keyword, limit = null, offset = null, orderBy = null) {
|
||||
const url = App.Utils.Url.siteUrl('secretaries/search');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
keyword,
|
||||
limit,
|
||||
offset,
|
||||
order_by: orderBy || undefined,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a secretary.
|
||||
*
|
||||
* @param {Number} secretaryId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function find(secretaryId) {
|
||||
const url = App.Utils.Url.siteUrl('secretaries/find');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
secretary_id: secretaryId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
store,
|
||||
update,
|
||||
destroy,
|
||||
search,
|
||||
find,
|
||||
};
|
||||
})();
|
||||
133
assets/js/http/service_categories_http_client.js
Normal file
133
assets/js/http/service_categories_http_client.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the service-categories related HTTP requests.
|
||||
*/
|
||||
App.Http.ServiceCategories = (function () {
|
||||
/**
|
||||
* Save (create or update) a service-category.
|
||||
*
|
||||
* @param {Object} serviceCategory
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(serviceCategory) {
|
||||
return serviceCategory.id ? update(serviceCategory) : store(serviceCategory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a service-category.
|
||||
*
|
||||
* @param {Object} serviceCategory
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function store(serviceCategory) {
|
||||
const url = App.Utils.Url.siteUrl('service_categories/store');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
service_category: serviceCategory,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a service-category.
|
||||
*
|
||||
* @param {Object} serviceCategory
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function update(serviceCategory) {
|
||||
const url = App.Utils.Url.siteUrl('service_categories/update');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
service_category: serviceCategory,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a service-category.
|
||||
*
|
||||
* @param {Number} serviceCategoryId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function destroy(serviceCategoryId) {
|
||||
const url = App.Utils.Url.siteUrl('service_categories/destroy');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
service_category_id: serviceCategoryId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search service-categories by keyword.
|
||||
*
|
||||
* @param {String} keyword
|
||||
* @param {Number} [limit]
|
||||
* @param {Number} [offset]
|
||||
* @param {String} [orderBy]
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function search(keyword, limit = null, offset = null, orderBy = null) {
|
||||
const url = App.Utils.Url.siteUrl('service_categories/search');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
keyword,
|
||||
limit,
|
||||
offset,
|
||||
order_by: orderBy || undefined,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a service-category.
|
||||
*
|
||||
* @param {Number} serviceCategoryId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function find(serviceCategoryId) {
|
||||
const url = App.Utils.Url.siteUrl('service_categories/find');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
service_category_id: serviceCategoryId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
store,
|
||||
update,
|
||||
destroy,
|
||||
search,
|
||||
find,
|
||||
};
|
||||
})();
|
||||
133
assets/js/http/services_http_client.js
Normal file
133
assets/js/http/services_http_client.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the services related HTTP requests.
|
||||
*/
|
||||
App.Http.Services = (function () {
|
||||
/**
|
||||
* Save (create or update) a service.
|
||||
*
|
||||
* @param {Object} service
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(service) {
|
||||
return service.id ? update(service) : store(service);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an service.
|
||||
*
|
||||
* @param {Object} service
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function store(service) {
|
||||
const url = App.Utils.Url.siteUrl('services/store');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
service: service,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an service.
|
||||
*
|
||||
* @param {Object} service
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function update(service) {
|
||||
const url = App.Utils.Url.siteUrl('services/update');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
service: service,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an service.
|
||||
*
|
||||
* @param {Number} serviceId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function destroy(serviceId) {
|
||||
const url = App.Utils.Url.siteUrl('services/destroy');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
service_id: serviceId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search services by keyword.
|
||||
*
|
||||
* @param {String} keyword
|
||||
* @param {Number} [limit]
|
||||
* @param {Number} [offset]
|
||||
* @param {String} [orderBy]
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function search(keyword, limit = null, offset = null, orderBy = null) {
|
||||
const url = App.Utils.Url.siteUrl('services/search');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
keyword,
|
||||
limit,
|
||||
offset,
|
||||
order_by: orderBy || undefined,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an service.
|
||||
*
|
||||
* @param {Number} serviceId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function find(serviceId) {
|
||||
const url = App.Utils.Url.siteUrl('services/find');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
service_id: serviceId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
store,
|
||||
update,
|
||||
destroy,
|
||||
search,
|
||||
find,
|
||||
};
|
||||
})();
|
||||
133
assets/js/http/settings_http_client.js
Normal file
133
assets/js/http/settings_http_client.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Settings HTTP client.
|
||||
*
|
||||
* This module implements the settings related HTTP requests.
|
||||
*/
|
||||
App.Http.Settings = (function () {
|
||||
/**
|
||||
* Save (create or update) a setting.
|
||||
*
|
||||
* @param {Object} setting
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(setting) {
|
||||
return setting.id ? update(setting) : create(setting);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an setting.
|
||||
*
|
||||
* @param {Object} setting
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function create(setting) {
|
||||
const url = App.Utils.Url.siteUrl('settings/create');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
setting: setting,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an setting.
|
||||
*
|
||||
* @param {Object} setting
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function update(setting) {
|
||||
const url = App.Utils.Url.siteUrl('settings/update');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
setting: setting,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an setting.
|
||||
*
|
||||
* @param {Number} settingId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function destroy(settingId) {
|
||||
const url = App.Utils.Url.siteUrl('settings/destroy');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
setting_id: settingId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search settings by keyword.
|
||||
*
|
||||
* @param {String} keyword
|
||||
* @param {Number} [limit]
|
||||
* @param {Number} [offset]
|
||||
* @param {String} [orderBy]
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function search(keyword, limit = null, offset = null, orderBy = null) {
|
||||
const url = App.Utils.Url.siteUrl('settings/search');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
keyword,
|
||||
limit,
|
||||
offset,
|
||||
order_by: orderBy || undefined,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an setting.
|
||||
*
|
||||
* @param {Number} settingId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function find(settingId) {
|
||||
const url = App.Utils.Url.siteUrl('settings/find');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
setting_id: settingId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
create,
|
||||
update,
|
||||
destroy,
|
||||
search,
|
||||
find,
|
||||
};
|
||||
})();
|
||||
133
assets/js/http/unavailabilities_http_client.js
Normal file
133
assets/js/http/unavailabilities_http_client.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Unavailabilities HTTP client.
|
||||
*
|
||||
* This module implements the unavailabilities related HTTP requests.
|
||||
*/
|
||||
App.Http.Unavailabilities = (function () {
|
||||
/**
|
||||
* Save (create or update) an unavailability.
|
||||
*
|
||||
* @param {Object} unavailability
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(unavailability) {
|
||||
return unavailability.id ? update(unavailability) : store(unavailability);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an unavailability.
|
||||
*
|
||||
* @param {Object} unavailability
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function store(unavailability) {
|
||||
const url = App.Utils.Url.siteUrl('unavailabilities/store');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
unavailability: unavailability,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an unavailability.
|
||||
*
|
||||
* @param {Object} unavailability
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function update(unavailability) {
|
||||
const url = App.Utils.Url.siteUrl('unavailabilities/update');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
unavailability: unavailability,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an unavailability.
|
||||
*
|
||||
* @param {Number} unavailabilityId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function destroy(unavailabilityId) {
|
||||
const url = App.Utils.Url.siteUrl('unavailabilities/destroy');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
unavailability_id: unavailabilityId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search unavailabilities by keyword.
|
||||
*
|
||||
* @param {String} keyword
|
||||
* @param {Number} [limit]
|
||||
* @param {Number} [offset]
|
||||
* @param {String} [orderBy]
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function search(keyword, limit = null, offset = null, orderBy = null) {
|
||||
const url = App.Utils.Url.siteUrl('unavailabilities/search');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
keyword,
|
||||
limit,
|
||||
offset,
|
||||
order_by: orderBy || undefined,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an unavailability.
|
||||
*
|
||||
* @param {Number} unavailabilityId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function find(unavailabilityId) {
|
||||
const url = App.Utils.Url.siteUrl('unavailabilities/find');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
unavailability_id: unavailabilityId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
store,
|
||||
update,
|
||||
destroy,
|
||||
search,
|
||||
find,
|
||||
};
|
||||
})();
|
||||
133
assets/js/http/webhooks_http_client.js
Normal file
133
assets/js/http/webhooks_http_client.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 HTTP client.
|
||||
*
|
||||
* This module implements the webhooks related HTTP requests.
|
||||
*/
|
||||
App.Http.Webhooks = (function () {
|
||||
/**
|
||||
* Save (create or update) a webhook.
|
||||
*
|
||||
* @param {Object} webhook
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function save(webhook) {
|
||||
return webhook.id ? update(webhook) : store(webhook);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an webhook.
|
||||
*
|
||||
* @param {Object} webhook
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function store(webhook) {
|
||||
const url = App.Utils.Url.siteUrl('webhooks/store');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
webhook: webhook,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an webhook.
|
||||
*
|
||||
* @param {Object} webhook
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function update(webhook) {
|
||||
const url = App.Utils.Url.siteUrl('webhooks/update');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
webhook: webhook,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an webhook.
|
||||
*
|
||||
* @param {Number} webhookId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function destroy(webhookId) {
|
||||
const url = App.Utils.Url.siteUrl('webhooks/destroy');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
webhook_id: webhookId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search webhooks by keyword.
|
||||
*
|
||||
* @param {String} keyword
|
||||
* @param {Number} [limit]
|
||||
* @param {Number} [offset]
|
||||
* @param {String} [orderBy]
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function search(keyword, limit = null, offset = null, orderBy = null) {
|
||||
const url = App.Utils.Url.siteUrl('webhooks/search');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
keyword,
|
||||
limit,
|
||||
offset,
|
||||
order_by: orderBy || undefined,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an webhook.
|
||||
*
|
||||
* @param {Number} webhookId
|
||||
*
|
||||
* @return {Object}
|
||||
*/
|
||||
function find(webhookId) {
|
||||
const url = App.Utils.Url.siteUrl('webhooks/find');
|
||||
|
||||
const data = {
|
||||
csrf_token: vars('csrf_token'),
|
||||
webhook_id: webhookId,
|
||||
};
|
||||
|
||||
return $.post(url, data);
|
||||
}
|
||||
|
||||
return {
|
||||
save,
|
||||
store,
|
||||
update,
|
||||
destroy,
|
||||
search,
|
||||
find,
|
||||
};
|
||||
})();
|
||||
10
assets/js/index.html
Normal file
10
assets/js/index.html
Normal file
@@ -0,0 +1,10 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>403 Forbidden</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<p>Directory access is forbidden.</p>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
30
assets/js/layouts/account_layout.js
Normal file
30
assets/js/layouts/account_layout.js
Normal file
@@ -0,0 +1,30 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 layout.
|
||||
*
|
||||
* This module implements the account layout functionality.
|
||||
*/
|
||||
window.App.Layouts.Account = (function () {
|
||||
const $selectLanguage = $('#select-language');
|
||||
|
||||
/**
|
||||
* Initialize the module.
|
||||
*/
|
||||
function initialize() {
|
||||
App.Utils.Lang.enableLanguageSelection($selectLanguage);
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialize);
|
||||
|
||||
return {};
|
||||
})();
|
||||
120
assets/js/layouts/backend_layout.js
Normal file
120
assets/js/layouts/backend_layout.js
Normal file
@@ -0,0 +1,120 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Backend layout.
|
||||
*
|
||||
* This module implements the backend layout functionality.
|
||||
*/
|
||||
window.App.Layouts.Backend = (function () {
|
||||
const $selectLanguage = $('#select-language');
|
||||
const $notification = $('#notification');
|
||||
const $loading = $('#loading');
|
||||
const $footer = $('#footer');
|
||||
|
||||
const DB_SLUG_ADMIN = 'admin';
|
||||
const DB_SLUG_PROVIDER = 'provider';
|
||||
const DB_SLUG_SECRETARY = 'secretary';
|
||||
const DB_SLUG_CUSTOMER = 'customer';
|
||||
|
||||
const PRIV_VIEW = 1;
|
||||
const PRIV_ADD = 2;
|
||||
const PRIV_EDIT = 4;
|
||||
const PRIV_DELETE = 8;
|
||||
|
||||
const PRIV_APPOINTMENTS = 'appointments';
|
||||
const PRIV_CUSTOMERS = 'customers';
|
||||
const PRIV_SERVICES = 'services';
|
||||
const PRIV_USERS = 'users';
|
||||
const PRIV_SYSTEM_SETTINGS = 'system_settings';
|
||||
const PRIV_USER_SETTINGS = 'user_settings';
|
||||
|
||||
/**
|
||||
* Display backend notifications to user.
|
||||
*
|
||||
* Using this method you can display notifications to the use with custom messages. If the 'actions' array is
|
||||
* provided then an action link will be displayed too.
|
||||
*
|
||||
* @param {String} message Notification message
|
||||
* @param {Array} [actions] An array with custom actions that will be available to the user. Every array item is an
|
||||
* object that contains the 'label' and 'function' key values.
|
||||
*/
|
||||
function displayNotification(message, actions = []) {
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
const $toast = $(`
|
||||
<div class="toast bg-dark d-flex align-items-center mb-2 fade show position-fixed p-1 m-4 bottom-0 end-0 backend-notification" role="alert" aria-live="assertive" aria-atomic="true">
|
||||
<div class="toast-body w-100 text-white">
|
||||
${message}
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2" data-bs-dismiss="toast" aria-label="Close"></button>
|
||||
</div>
|
||||
`).appendTo('body');
|
||||
|
||||
actions.forEach(function (action) {
|
||||
$('<button/>', {
|
||||
class: 'btn btn-light btn-sm ms-2',
|
||||
text: action.label,
|
||||
on: {
|
||||
click: action.function,
|
||||
},
|
||||
}).prependTo($toast);
|
||||
});
|
||||
|
||||
const toast = new bootstrap.Toast($toast[0]);
|
||||
|
||||
toast.show();
|
||||
|
||||
setTimeout(() => {
|
||||
toast.dispose();
|
||||
$toast.remove();
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the module.
|
||||
*/
|
||||
function initialize() {
|
||||
$(document).ajaxStart(() => {
|
||||
$loading.show();
|
||||
});
|
||||
|
||||
$(document).ajaxStop(() => {
|
||||
$loading.hide();
|
||||
});
|
||||
|
||||
tippy('[data-tippy-content]');
|
||||
|
||||
App.Utils.Lang.enableLanguageSelection($selectLanguage);
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialize);
|
||||
|
||||
return {
|
||||
DB_SLUG_ADMIN,
|
||||
DB_SLUG_PROVIDER,
|
||||
DB_SLUG_SECRETARY,
|
||||
DB_SLUG_CUSTOMER,
|
||||
PRIV_VIEW,
|
||||
PRIV_ADD,
|
||||
PRIV_EDIT,
|
||||
PRIV_DELETE,
|
||||
PRIV_APPOINTMENTS,
|
||||
PRIV_CUSTOMERS,
|
||||
PRIV_SERVICES,
|
||||
PRIV_USERS,
|
||||
PRIV_SYSTEM_SETTINGS,
|
||||
PRIV_USER_SETTINGS,
|
||||
displayNotification,
|
||||
};
|
||||
})();
|
||||
30
assets/js/layouts/booking_layout.js
Normal file
30
assets/js/layouts/booking_layout.js
Normal file
@@ -0,0 +1,30 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 layout.
|
||||
*
|
||||
* This module implements the booking layout functionality.
|
||||
*/
|
||||
window.App.Layouts.Booking = (function () {
|
||||
const $selectLanguage = $('#select-language');
|
||||
|
||||
/**
|
||||
* Initialize the module.
|
||||
*/
|
||||
function initialize() {
|
||||
App.Utils.Lang.enableLanguageSelection($selectLanguage);
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialize);
|
||||
|
||||
return {};
|
||||
})();
|
||||
19
assets/js/layouts/message_layout.js
Normal file
19
assets/js/layouts/message_layout.js
Normal file
@@ -0,0 +1,19 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Message layout.
|
||||
*
|
||||
* This module implements the message layout functionality.
|
||||
*/
|
||||
window.App.Layouts.Message = (function () {
|
||||
return {};
|
||||
})();
|
||||
198
assets/js/pages/account.js
Normal file
198
assets/js/pages/account.js
Normal 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
496
assets/js/pages/admins.js
Normal 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,
|
||||
};
|
||||
})();
|
||||
109
assets/js/pages/api_settings.js
Normal file
109
assets/js/pages/api_settings.js
Normal 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 {};
|
||||
})();
|
||||
395
assets/js/pages/blocked_periods.js
Normal file
395
assets/js/pages/blocked_periods.js
Normal 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
974
assets/js/pages/booking.js
Normal 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,
|
||||
};
|
||||
})();
|
||||
235
assets/js/pages/booking_settings.js
Normal file
235
assets/js/pages/booking_settings.js
Normal 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 {};
|
||||
})();
|
||||
178
assets/js/pages/business_settings.js
Normal file
178
assets/js/pages/business_settings.js
Normal 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
164
assets/js/pages/calendar.js
Normal 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,
|
||||
};
|
||||
})();
|
||||
502
assets/js/pages/customers.js
Normal file
502
assets/js/pages/customers.js
Normal 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,
|
||||
};
|
||||
})();
|
||||
188
assets/js/pages/general_settings.js
Normal file
188
assets/js/pages/general_settings.js
Normal 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 {};
|
||||
})();
|
||||
109
assets/js/pages/google_analytics_settings.js
Normal file
109
assets/js/pages/google_analytics_settings.js
Normal 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 {};
|
||||
})();
|
||||
176
assets/js/pages/installation.js
Normal file
176
assets/js/pages/installation.js
Normal 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 {};
|
||||
})();
|
||||
256
assets/js/pages/ldap_settings.js
Normal file
256
assets/js/pages/ldap_settings.js
Normal 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 {};
|
||||
})();
|
||||
158
assets/js/pages/legal_settings.js
Normal file
158
assets/js/pages/legal_settings.js
Normal 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
56
assets/js/pages/login.js
Normal 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 {};
|
||||
})();
|
||||
109
assets/js/pages/matomo_analytics_settings.js
Normal file
109
assets/js/pages/matomo_analytics_settings.js
Normal 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 {};
|
||||
})();
|
||||
608
assets/js/pages/providers.js
Normal file
608
assets/js/pages/providers.js
Normal 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,
|
||||
};
|
||||
})();
|
||||
64
assets/js/pages/recovery.js
Normal file
64
assets/js/pages/recovery.js
Normal 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 {};
|
||||
})();
|
||||
548
assets/js/pages/secretaries.js
Normal file
548
assets/js/pages/secretaries.js
Normal 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,
|
||||
};
|
||||
})();
|
||||
344
assets/js/pages/service_categories.js
Normal file
344
assets/js/pages/service_categories.js
Normal 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
441
assets/js/pages/services.js
Normal 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
389
assets/js/pages/webhooks.js
Normal 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,
|
||||
};
|
||||
})();
|
||||
1668
assets/js/utils/calendar_default_view.js
Normal file
1668
assets/js/utils/calendar_default_view.js
Normal file
File diff suppressed because it is too large
Load Diff
140
assets/js/utils/calendar_event_popover.js
Normal file
140
assets/js/utils/calendar_event_popover.js
Normal file
@@ -0,0 +1,140 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 event popover utility.
|
||||
*
|
||||
* This module implements the functionality of calendar event popovers.
|
||||
*/
|
||||
App.Utils.CalendarEventPopover = (function () {
|
||||
/**
|
||||
* Render a map icon that links to Google maps.
|
||||
*
|
||||
* Old Name: GeneralFunctions.renderMapIcon
|
||||
*
|
||||
* @param {Object} user Should have the address, city, etc properties.
|
||||
*
|
||||
* @return {String} The rendered HTML.
|
||||
*/
|
||||
function renderMapIcon(user) {
|
||||
const data = [];
|
||||
|
||||
if (user.address) {
|
||||
data.push(user.address);
|
||||
}
|
||||
|
||||
if (user.city) {
|
||||
data.push(user.city);
|
||||
}
|
||||
|
||||
if (user.state) {
|
||||
data.push(user.state);
|
||||
}
|
||||
|
||||
if (user.zip_code) {
|
||||
data.push(user.zip_code);
|
||||
}
|
||||
|
||||
if (!data.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $('<div/>', {
|
||||
'html': [
|
||||
$('<a/>', {
|
||||
'href': 'https://google.com/maps/place/' + data.join(','),
|
||||
'target': '_blank',
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-map-marker-alt',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}).html();
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a mail icon.
|
||||
*
|
||||
* Old Name: GeneralFunctions.renderMailIcon
|
||||
*
|
||||
* @param {String} email
|
||||
*
|
||||
* @return {String} The rendered HTML.
|
||||
*/
|
||||
function renderMailIcon(email) {
|
||||
if (!email) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $('<div/>', {
|
||||
'html': [
|
||||
$('<a/>', {
|
||||
'href': 'mailto:' + email,
|
||||
'target': '_blank',
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-envelope',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}).html();
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a phone icon.
|
||||
*
|
||||
* Old Name: GeneralFunctions.renderPhoneIcon
|
||||
*
|
||||
* @param {String} phone
|
||||
*
|
||||
* @return {String} The rendered HTML.
|
||||
*/
|
||||
function renderPhoneIcon(phone) {
|
||||
if (!phone) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $('<div/>', {
|
||||
'html': [
|
||||
$('<a/>', {
|
||||
'href': 'tel:' + phone,
|
||||
'target': '_blank',
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-phone-alt',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}).html();
|
||||
}
|
||||
|
||||
/**
|
||||
* Render custom content into the popover of events.
|
||||
*
|
||||
* @param {Object} info The info object as passed from FullCalendar
|
||||
*
|
||||
* @return {Object|String|null} Return HTML string, a jQuery selector or null for nothing.
|
||||
*/
|
||||
function renderCustomContent(info) {
|
||||
return null; // Default behavior
|
||||
}
|
||||
|
||||
return {
|
||||
renderPhoneIcon,
|
||||
renderMapIcon,
|
||||
renderMailIcon,
|
||||
renderCustomContent,
|
||||
};
|
||||
})();
|
||||
416
assets/js/utils/calendar_sync.js
Normal file
416
assets/js/utils/calendar_sync.js
Normal file
@@ -0,0 +1,416 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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 sync utility.
|
||||
*
|
||||
* This module implements the functionality of calendar sync.
|
||||
*
|
||||
* Old Name: BackendCalendarSync
|
||||
*/
|
||||
App.Utils.CalendarSync = (function () {
|
||||
const $selectFilterItem = $('#select-filter-item');
|
||||
const $enableSync = $('#enable-sync');
|
||||
const $disableSync = $('#disable-sync');
|
||||
const $triggerSync = $('#trigger-sync');
|
||||
const $syncButtonGroup = $('#sync-button-group');
|
||||
const $reloadAppointments = $('#reload-appointments');
|
||||
|
||||
const FILTER_TYPE_PROVIDER = 'provider';
|
||||
let isSyncing = false;
|
||||
|
||||
function hasSync(type) {
|
||||
const $selectedOption = $selectFilterItem.find('option:selected');
|
||||
|
||||
return Boolean(Number($selectedOption.attr(`${type}-sync`)));
|
||||
}
|
||||
|
||||
function updateSyncButtons() {
|
||||
const $selectedOption = $selectFilterItem.find('option:selected');
|
||||
const type = $selectedOption.attr('type');
|
||||
const isProvider = type === FILTER_TYPE_PROVIDER;
|
||||
const hasGoogleSync = Boolean(Number($selectedOption.attr('google-sync')));
|
||||
const hasCaldavSync = Boolean(Number($selectedOption.attr('caldav-sync')));
|
||||
const hasSync = hasGoogleSync || hasCaldavSync;
|
||||
|
||||
$enableSync.prop('hidden', !isProvider || hasSync);
|
||||
$syncButtonGroup.prop('hidden', !isProvider || !hasSync);
|
||||
}
|
||||
|
||||
function enableGoogleSync() {
|
||||
// Enable synchronization for selected provider.
|
||||
|
||||
const authUrl = App.Utils.Url.siteUrl('google/oauth/' + $('#select-filter-item').val());
|
||||
|
||||
const redirectUrl = App.Utils.Url.siteUrl('google/oauth_callback');
|
||||
|
||||
const windowHandle = window.open(authUrl, 'Easy!Appointments', 'width=800, height=600');
|
||||
|
||||
const authInterval = window.setInterval(() => {
|
||||
// When the browser redirects to the Google user consent page the "window.document" variable
|
||||
// becomes "undefined" and when it comes back to the redirect URL it changes back. So check
|
||||
// whether the variable is undefined to avoid javascript errors.
|
||||
try {
|
||||
if (windowHandle.document) {
|
||||
if (windowHandle.document.URL.indexOf(redirectUrl) !== -1) {
|
||||
// The user has granted access to his data.
|
||||
windowHandle.close();
|
||||
|
||||
window.clearInterval(authInterval);
|
||||
|
||||
const $selectedOption = $selectFilterItem.find('option:selected');
|
||||
|
||||
$selectedOption.attr('google-sync', '1');
|
||||
|
||||
updateSyncButtons();
|
||||
|
||||
selectGoogleCalendar();
|
||||
}
|
||||
}
|
||||
} catch (Error) {
|
||||
// Accessing the document object before the window is loaded throws an error, but it will only
|
||||
// happen during the initialization of the window. Attaching "load" event handling is not
|
||||
// possible due to CORS restrictions.
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
|
||||
function disableGoogleSync() {
|
||||
App.Utils.Message.show(lang('disable_sync'), lang('disable_sync_prompt'), [
|
||||
{
|
||||
text: lang('cancel'),
|
||||
click: (event, messageModal) => {
|
||||
messageModal.hide();
|
||||
},
|
||||
},
|
||||
{
|
||||
text: lang('confirm'),
|
||||
click: (event, messageModal) => {
|
||||
// Disable synchronization for selected provider.
|
||||
const providerId = $selectFilterItem.val();
|
||||
|
||||
const provider = vars('available_providers').find(
|
||||
(availableProvider) => Number(availableProvider.id) === Number(providerId),
|
||||
);
|
||||
|
||||
if (!provider) {
|
||||
throw new Error('Provider not found: ' + providerId);
|
||||
}
|
||||
|
||||
provider.settings.google_sync = '0';
|
||||
provider.settings.google_token = null;
|
||||
|
||||
App.Http.Google.disableProviderSync(provider.id);
|
||||
|
||||
const $selectedOption = $selectFilterItem.find('option:selected');
|
||||
|
||||
$selectedOption.attr('google-sync', '0');
|
||||
|
||||
updateSyncButtons();
|
||||
|
||||
messageModal.hide();
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function selectGoogleCalendar() {
|
||||
const providerId = $selectFilterItem.val();
|
||||
|
||||
App.Http.Google.getGoogleCalendars(providerId).done((googleCalendars) => {
|
||||
const $selectGoogleCalendar = $(`
|
||||
<select class="form-control">
|
||||
<!-- JS -->
|
||||
</select>
|
||||
`);
|
||||
|
||||
googleCalendars.forEach((googleCalendar) => {
|
||||
$selectGoogleCalendar.append(new Option(googleCalendar.summary, googleCalendar.id));
|
||||
});
|
||||
|
||||
const $messageModal = App.Utils.Message.show(
|
||||
lang('select_sync_calendar'),
|
||||
lang('select_sync_calendar_prompt'),
|
||||
[
|
||||
{
|
||||
text: lang('select'),
|
||||
click: (event, messageModal) => {
|
||||
const googleCalendarId = $selectGoogleCalendar.val();
|
||||
|
||||
App.Http.Google.selectGoogleCalendar(providerId, googleCalendarId).done(() => {
|
||||
App.Layouts.Backend.displayNotification(lang('sync_calendar_selected'));
|
||||
});
|
||||
|
||||
messageModal.hide();
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
$selectGoogleCalendar.appendTo($messageModal.find('.modal-body'));
|
||||
});
|
||||
}
|
||||
|
||||
function triggerGoogleSync() {
|
||||
const providerId = $selectFilterItem.val();
|
||||
|
||||
App.Http.Google.syncWithGoogle(providerId)
|
||||
.done(() => {
|
||||
App.Layouts.Backend.displayNotification(lang('calendar_sync_completed'));
|
||||
$reloadAppointments.trigger('click');
|
||||
})
|
||||
.fail(() => {
|
||||
App.Layouts.Backend.displayNotification(lang('calendar_sync_failed'));
|
||||
})
|
||||
.always(() => {
|
||||
isSyncing = false;
|
||||
});
|
||||
}
|
||||
|
||||
function enableCaldavSync(defaultCaldavUrl = '', defaultCaldavUsername = '', defaultCaldavPassword = '') {
|
||||
const $container = $(`
|
||||
<div>
|
||||
<div class="mb-3">
|
||||
<label for="caldav-url" class="form-label">
|
||||
${lang('calendar_url')}
|
||||
</label>
|
||||
<input type="text" class="form-control" id="caldav-url" value="${defaultCaldavUrl}"/>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="caldav-username" class="form-label">
|
||||
${lang('username')}
|
||||
</label>
|
||||
<input type="text" class="form-control" id="caldav-username" value="${defaultCaldavUsername}"/>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="caldav-password" class="form-label">
|
||||
${lang('password')}
|
||||
</label>
|
||||
<input type="password" class="form-control" id="caldav-password" value="${defaultCaldavPassword}"/>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-danger" hidden>
|
||||
<!-- JS -->
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
const $messageModal = App.Utils.Message.show(lang('caldav_server'), lang('caldav_connection_info_prompt'), [
|
||||
{
|
||||
text: lang('cancel'),
|
||||
click: (event, messageModal) => {
|
||||
messageModal.hide();
|
||||
},
|
||||
},
|
||||
{
|
||||
text: lang('connect'),
|
||||
click: (event, messageModal) => {
|
||||
const providerId = $selectFilterItem.val();
|
||||
|
||||
$messageModal.find('.is-invalid').removeClass('is-invalid');
|
||||
|
||||
const $alert = $messageModal.find('.alert');
|
||||
$alert.text('').prop('hidden', true);
|
||||
|
||||
const $caldavUrl = $container.find('#caldav-url');
|
||||
const caldavUrl = $caldavUrl.val();
|
||||
|
||||
if (!caldavUrl) {
|
||||
$caldavUrl.addClass('is-invalid');
|
||||
return;
|
||||
}
|
||||
|
||||
const $caldavUsername = $container.find('#caldav-username');
|
||||
const caldavUsername = $caldavUsername.val();
|
||||
|
||||
if (!caldavUsername) {
|
||||
$caldavUsername.addClass('is-invalid');
|
||||
return;
|
||||
}
|
||||
|
||||
const $caldavPassword = $container.find('#caldav-password');
|
||||
const caldavPassword = $caldavPassword.val();
|
||||
|
||||
if (!caldavPassword) {
|
||||
$caldavPassword.addClass('is-invalid');
|
||||
return;
|
||||
}
|
||||
|
||||
App.Http.Caldav.connectToServer(providerId, caldavUrl, caldavUsername, caldavPassword).done(
|
||||
(response) => {
|
||||
if (!response.success) {
|
||||
$caldavUrl.addClass('is-invalid');
|
||||
$caldavUsername.addClass('is-invalid');
|
||||
$caldavPassword.addClass('is-invalid');
|
||||
|
||||
$alert.text(lang('login_failed') + ' ' + response.message).prop('hidden', false);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const $selectedOption = $selectFilterItem.find('option:selected');
|
||||
|
||||
$selectedOption.attr('caldav-sync', '1');
|
||||
|
||||
updateSyncButtons();
|
||||
|
||||
App.Layouts.Backend.displayNotification(lang('sync_calendar_selected'));
|
||||
|
||||
messageModal.hide();
|
||||
},
|
||||
);
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
$messageModal.find('.modal-body').append($container);
|
||||
}
|
||||
|
||||
function disableCaldavSync() {
|
||||
App.Utils.Message.show(lang('disable_sync'), lang('disable_sync_prompt'), [
|
||||
{
|
||||
text: lang('cancel'),
|
||||
click: (event, messageModal) => {
|
||||
messageModal.hide();
|
||||
},
|
||||
},
|
||||
{
|
||||
text: lang('confirm'),
|
||||
click: (event, messageModal) => {
|
||||
// Disable synchronization for selected provider.
|
||||
const providerId = $selectFilterItem.val();
|
||||
|
||||
const provider = vars('available_providers').find(
|
||||
(availableProvider) => Number(availableProvider.id) === Number(providerId),
|
||||
);
|
||||
|
||||
if (!provider) {
|
||||
throw new Error('Provider not found: ' + providerId);
|
||||
}
|
||||
|
||||
provider.settings.caldav_sync = '0';
|
||||
provider.settings.caldav_url = null;
|
||||
provider.settings.caldav_username = null;
|
||||
provider.settings.caldav_password = null;
|
||||
|
||||
App.Http.Caldav.disableProviderSync(provider.id);
|
||||
|
||||
const $selectedOption = $selectFilterItem.find('option:selected');
|
||||
|
||||
$selectedOption.attr('caldav-sync', '0');
|
||||
|
||||
updateSyncButtons();
|
||||
|
||||
messageModal.hide();
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function triggerCaldavSync() {
|
||||
const providerId = $selectFilterItem.val();
|
||||
|
||||
App.Http.Caldav.syncWithCaldav(providerId)
|
||||
.done(() => {
|
||||
App.Layouts.Backend.displayNotification(lang('calendar_sync_completed'));
|
||||
$reloadAppointments.trigger('click');
|
||||
})
|
||||
.fail(() => {
|
||||
App.Layouts.Backend.displayNotification(lang('calendar_sync_failed'));
|
||||
})
|
||||
.always(() => {
|
||||
isSyncing = false;
|
||||
});
|
||||
}
|
||||
|
||||
function onSelectFilterItemChange() {
|
||||
updateSyncButtons();
|
||||
}
|
||||
|
||||
function onEnableSyncClick() {
|
||||
const isGoogleSyncFeatureEnabled = vars('google_sync_feature');
|
||||
|
||||
if (!isGoogleSyncFeatureEnabled) {
|
||||
enableCaldavSync();
|
||||
return;
|
||||
}
|
||||
|
||||
App.Utils.Message.show(lang('enable_sync'), lang('sync_method_prompt'), [
|
||||
{
|
||||
text: 'CalDAV Calendar',
|
||||
className: 'btn btn-outline-primary me-auto',
|
||||
click: (event, messageModal) => {
|
||||
messageModal.hide();
|
||||
enableCaldavSync();
|
||||
},
|
||||
},
|
||||
{
|
||||
text: 'Google Calendar',
|
||||
click: (event, messageModal) => {
|
||||
messageModal.hide();
|
||||
enableGoogleSync();
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function onDisableSyncClick() {
|
||||
const hasGoogleSync = hasSync('google');
|
||||
|
||||
if (hasGoogleSync) {
|
||||
disableGoogleSync();
|
||||
return;
|
||||
}
|
||||
|
||||
const hasCalSync = hasSync('caldav');
|
||||
|
||||
if (hasCalSync) {
|
||||
disableCaldavSync();
|
||||
}
|
||||
}
|
||||
|
||||
function onTriggerSyncClick() {
|
||||
const hasGoogleSync = hasSync('google');
|
||||
isSyncing = true;
|
||||
|
||||
if (hasGoogleSync) {
|
||||
triggerGoogleSync();
|
||||
return;
|
||||
}
|
||||
|
||||
const hasCalSync = hasSync('caldav');
|
||||
|
||||
if (hasCalSync) {
|
||||
triggerCaldavSync();
|
||||
}
|
||||
}
|
||||
|
||||
function isCurrentlySyncing() {
|
||||
return isSyncing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the module.
|
||||
*/
|
||||
function initialize() {
|
||||
$selectFilterItem.on('change', onSelectFilterItemChange);
|
||||
$enableSync.on('click', onEnableSyncClick);
|
||||
$disableSync.on('click', onDisableSyncClick);
|
||||
$triggerSync.on('click', onTriggerSyncClick);
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialize);
|
||||
|
||||
return {
|
||||
initialize,
|
||||
isCurrentlySyncing,
|
||||
};
|
||||
})();
|
||||
1904
assets/js/utils/calendar_table_view.js
Normal file
1904
assets/js/utils/calendar_table_view.js
Normal file
File diff suppressed because it is too large
Load Diff
198
assets/js/utils/date.js
Normal file
198
assets/js/utils/date.js
Normal 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Date utility.
|
||||
*
|
||||
* This module implements the functionality of dates.
|
||||
*/
|
||||
window.App.Utils.Date = (function () {
|
||||
/**
|
||||
* Format a YYYY-MM-DD HH:mm:ss date string.
|
||||
*
|
||||
* @param {String|Date} dateValue The date string to be formatted.
|
||||
* @param {String} [dateFormatType] The date format type value ("DMY", "MDY" or "YMD").
|
||||
* @param {String} [timeFormatType] The time format type value ("regular", "military").
|
||||
* @param {Boolean} [withHours] Whether to add hours to the returned string.
|
||||
|
||||
* @return {String} Returns the formatted string.
|
||||
*/
|
||||
function format(dateValue, dateFormatType = 'YMD', timeFormatType = 'regular', withHours = false) {
|
||||
const dateMoment = moment(dateValue);
|
||||
|
||||
if (!dateMoment.isValid()) {
|
||||
throw new Error(`Invalid date value provided: ${dateValue}`);
|
||||
}
|
||||
|
||||
let dateFormat;
|
||||
|
||||
switch (dateFormatType) {
|
||||
case 'DMY':
|
||||
dateFormat = 'DD/MM/YYYY';
|
||||
break;
|
||||
|
||||
case 'MDY':
|
||||
dateFormat = 'MM/DD/YYYY';
|
||||
break;
|
||||
|
||||
case 'YMD':
|
||||
dateFormat = 'YYYY/MM/DD';
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`Invalid date format type provided: ${dateFormatType}`);
|
||||
}
|
||||
|
||||
let timeFormat;
|
||||
|
||||
switch (timeFormatType) {
|
||||
case 'regular':
|
||||
timeFormat = 'h:mm a';
|
||||
break;
|
||||
case 'military':
|
||||
timeFormat = 'HH:mm';
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Invalid time format type provided: ${timeFormatType}`);
|
||||
}
|
||||
|
||||
const format = withHours ? `${dateFormat} ${timeFormat}` : dateFormat;
|
||||
|
||||
return dateMoment.format(format);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Id of a Weekday using the US week format and day names (Sunday=0) as used in the JS code of the
|
||||
* application, case-insensitive, short and long names supported.
|
||||
*
|
||||
* @param {String} weekDayName The weekday name among Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
|
||||
* Saturday.
|
||||
|
||||
* @return {Number} Returns the ID of the weekday.
|
||||
*/
|
||||
function getWeekdayId(weekDayName) {
|
||||
let result;
|
||||
|
||||
switch (weekDayName.toLowerCase()) {
|
||||
case 'sunday':
|
||||
case 'sun':
|
||||
result = 0;
|
||||
break;
|
||||
|
||||
case 'monday':
|
||||
case 'mon':
|
||||
result = 1;
|
||||
break;
|
||||
|
||||
case 'tuesday':
|
||||
case 'tue':
|
||||
result = 2;
|
||||
break;
|
||||
|
||||
case 'wednesday':
|
||||
case 'wed':
|
||||
result = 3;
|
||||
break;
|
||||
|
||||
case 'thursday':
|
||||
case 'thu':
|
||||
result = 4;
|
||||
break;
|
||||
|
||||
case 'friday':
|
||||
case 'fri':
|
||||
result = 5;
|
||||
break;
|
||||
|
||||
case 'saturday':
|
||||
case 'sat':
|
||||
result = 6;
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`Invalid weekday name provided: ${weekDayName}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort a dictionary where keys are weekdays
|
||||
*
|
||||
* @param {Object} weekDictionary A dictionary with weekdays as keys.
|
||||
* @param {Number} startDayId Id of the first day to start sorting (From 0 for sunday to 6 for saturday).
|
||||
|
||||
* @return {Object} Returns a sorted dictionary
|
||||
*/
|
||||
function sortWeekDictionary(weekDictionary, startDayId) {
|
||||
const sortedWeekDictionary = {};
|
||||
|
||||
for (let i = startDayId; i < startDayId + 7; i++) {
|
||||
const weekdayName = getWeekdayName(i % 7);
|
||||
sortedWeekDictionary[weekdayName] = weekDictionary[weekdayName];
|
||||
}
|
||||
|
||||
return sortedWeekDictionary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name in lowercase of a Weekday using its Id.
|
||||
*
|
||||
* @param {Number} weekDayId The Id (From 0 for sunday to 6 for saturday).
|
||||
|
||||
* @return {String} Returns the name of the weekday.
|
||||
*/
|
||||
function getWeekdayName(weekDayId) {
|
||||
let result;
|
||||
|
||||
switch (weekDayId) {
|
||||
case 0:
|
||||
result = 'sunday';
|
||||
break;
|
||||
|
||||
case 1:
|
||||
result = 'monday';
|
||||
break;
|
||||
|
||||
case 2:
|
||||
result = 'tuesday';
|
||||
break;
|
||||
|
||||
case 3:
|
||||
result = 'wednesday';
|
||||
break;
|
||||
|
||||
case 4:
|
||||
result = 'thursday';
|
||||
break;
|
||||
|
||||
case 5:
|
||||
result = 'friday';
|
||||
break;
|
||||
|
||||
case 6:
|
||||
result = 'saturday';
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`Invalid weekday Id provided: ${weekDayId}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
return {
|
||||
format,
|
||||
getWeekdayId,
|
||||
sortWeekDictionary,
|
||||
getWeekdayName,
|
||||
};
|
||||
})();
|
||||
37
assets/js/utils/file.js
Normal file
37
assets/js/utils/file.js
Normal file
@@ -0,0 +1,37 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* File utility.
|
||||
*
|
||||
* This module implements the functionality of files.
|
||||
*/
|
||||
window.App.Utils.File = (function () {
|
||||
/**
|
||||
* Convert a file to a base 64 string.
|
||||
*
|
||||
* @param {File} file
|
||||
*
|
||||
* @return {Promise}
|
||||
*/
|
||||
function toBase64(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.readAsDataURL(file);
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = (error) => reject(error);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
toBase64,
|
||||
};
|
||||
})();
|
||||
176
assets/js/utils/http.js
Normal file
176
assets/js/utils/http.js
Normal 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* HTTP requests utility.
|
||||
*
|
||||
* This module implements the functionality of HTTP requests.
|
||||
*/
|
||||
window.App.Utils.Http = (function () {
|
||||
/**
|
||||
* Perform an HTTP request.
|
||||
*
|
||||
* @param {String} method
|
||||
* @param {String} url
|
||||
* @param {Object} data
|
||||
*
|
||||
* @return {Promise}
|
||||
*/
|
||||
function request(method, url, data) {
|
||||
return new Promise((resolve, reject) => {
|
||||
fetch(App.Utils.Url.siteUrl(url), {
|
||||
method,
|
||||
mode: 'cors',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
redirect: 'follow',
|
||||
referrer: 'no-referrer',
|
||||
body: data ? JSON.stringify(data) : undefined,
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
response
|
||||
.text()
|
||||
.then((message) => {
|
||||
const error = new Error(message);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
reject(error);
|
||||
});
|
||||
}
|
||||
|
||||
return response;
|
||||
})
|
||||
.then((response) => {
|
||||
return response.json();
|
||||
})
|
||||
.then((json) => {
|
||||
resolve(json);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload the provided file.
|
||||
*
|
||||
* @param {String} method
|
||||
* @param {String} url
|
||||
* @param {File} file
|
||||
*
|
||||
* @return {Promise}
|
||||
*/
|
||||
function upload(method, url, file) {
|
||||
const formData = new FormData();
|
||||
|
||||
formData.append('file', file, file.name);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
fetch(App.Utils.Url.siteUrl(url), {
|
||||
method,
|
||||
redirect: 'follow',
|
||||
referrer: 'no-referrer',
|
||||
body: formData,
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
response
|
||||
.text()
|
||||
.then((message) => {
|
||||
const error = new Error(message);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
reject(error);
|
||||
});
|
||||
}
|
||||
|
||||
return response;
|
||||
})
|
||||
.then((response) => {
|
||||
return response.json();
|
||||
})
|
||||
.then((json) => {
|
||||
resolve(json);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Download the requested URL.
|
||||
*
|
||||
* @param {String} method
|
||||
* @param {String} url
|
||||
*
|
||||
* @return {Promise}
|
||||
*/
|
||||
function download(method, url) {
|
||||
return new Promise((resolve, reject) => {
|
||||
fetch(App.Utils.Url.siteUrl(url), {
|
||||
method,
|
||||
mode: 'cors',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
redirect: 'follow',
|
||||
referrer: 'no-referrer',
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
response
|
||||
.text()
|
||||
.then((message) => {
|
||||
const error = new Error(message);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
reject(error);
|
||||
});
|
||||
}
|
||||
|
||||
return response;
|
||||
})
|
||||
.then((response) => {
|
||||
return response.arrayBuffer();
|
||||
})
|
||||
.then((json) => {
|
||||
resolve(json);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
request,
|
||||
upload,
|
||||
download,
|
||||
};
|
||||
})();
|
||||
78
assets/js/utils/lang.js
Normal file
78
assets/js/utils/lang.js
Normal file
@@ -0,0 +1,78 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Lang utility.
|
||||
*
|
||||
* This module implements the functionality of translations.
|
||||
*/
|
||||
window.App.Utils.Lang = (function () {
|
||||
/**
|
||||
* Enable Language Selection
|
||||
*
|
||||
* Enables the language selection functionality. Must be called on every page has a language selection button.
|
||||
* This method requires the global variable "vars('available_variables')" to be initialized before the execution.
|
||||
*
|
||||
* @param {Object} $target Selected element button for the language selection.
|
||||
*/
|
||||
function enableLanguageSelection($target) {
|
||||
// Select Language
|
||||
const $languageList = $('<ul/>', {
|
||||
'id': 'language-list',
|
||||
'html': vars('available_languages').map((availableLanguage) =>
|
||||
$('<li/>', {
|
||||
'class': 'language',
|
||||
'data-language': availableLanguage,
|
||||
'text': App.Utils.String.upperCaseFirstLetter(availableLanguage),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
$target.popover({
|
||||
placement: 'top',
|
||||
title: 'Select Language',
|
||||
content: $languageList[0],
|
||||
html: true,
|
||||
container: 'body',
|
||||
trigger: 'manual',
|
||||
});
|
||||
|
||||
$target.on('click', function (event) {
|
||||
event.stopPropagation();
|
||||
|
||||
const $target = $(event.target);
|
||||
|
||||
if ($('#language-list').length === 0) {
|
||||
$target.popover('show');
|
||||
} else {
|
||||
$target.popover('hide');
|
||||
}
|
||||
|
||||
$target.toggleClass('active');
|
||||
});
|
||||
|
||||
$(document).on('click', 'li.language', (event) => {
|
||||
// Change language with HTTP request and refresh page.
|
||||
|
||||
const language = $(event.target).data('language');
|
||||
|
||||
App.Http.Localization.changeLanguage(language).done(() => document.location.reload());
|
||||
});
|
||||
|
||||
$(document).on('click', () => {
|
||||
$target.popover('hide');
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
enableLanguageSelection,
|
||||
};
|
||||
})();
|
||||
126
assets/js/utils/message.js
Normal file
126
assets/js/utils/message.js
Normal file
@@ -0,0 +1,126 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Messages utility.
|
||||
*
|
||||
* This module implements the functionality of messages.
|
||||
*/
|
||||
window.App.Utils.Message = (function () {
|
||||
let messageModal = null;
|
||||
|
||||
/**
|
||||
* Show a message box to the user.
|
||||
*
|
||||
* This functions displays a message box in the admin array. It is useful when user
|
||||
* decisions or verifications are needed.
|
||||
*
|
||||
* @param {String} title The title of the message box.
|
||||
* @param {String} message The message of the dialog.
|
||||
* @param {Array} [buttons] Contains the dialog buttons along with their functions.
|
||||
* @param {Boolean} [isDismissible] If true, the button will show the close X in the header and close with the press of the Escape button.
|
||||
*
|
||||
* @return {jQuery|null} Return the #message-modal selector or null if the arguments are invalid.
|
||||
*/
|
||||
function show(title, message, buttons = null, isDismissible = true) {
|
||||
if (!title || !message) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!buttons) {
|
||||
buttons = [
|
||||
{
|
||||
text: lang('close'),
|
||||
className: 'btn btn-outline-primary',
|
||||
click: function (event, messageModal) {
|
||||
messageModal.hide();
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (messageModal?.dispose && messageModal?.hide && messageModal?._element) {
|
||||
messageModal.hide();
|
||||
messageModal.dispose();
|
||||
messageModal = undefined;
|
||||
}
|
||||
|
||||
$('#message-modal').remove();
|
||||
|
||||
const $messageModal = $(`
|
||||
<div class="modal" id="message-modal" tabindex="-1">
|
||||
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">
|
||||
${title}
|
||||
</h5>
|
||||
${
|
||||
isDismissible
|
||||
? '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>'
|
||||
: ''
|
||||
}
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
${message}
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<!-- * -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`).appendTo('body');
|
||||
|
||||
buttons.forEach((button) => {
|
||||
if (!button) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!button.className) {
|
||||
button.className = 'btn btn-outline-primary';
|
||||
}
|
||||
|
||||
const $button = $(`
|
||||
<button type="button" class="${button.className}">
|
||||
${button.text}
|
||||
</button>
|
||||
`).appendTo($messageModal.find('.modal-footer'));
|
||||
|
||||
if (button.click) {
|
||||
$button.on('click', (event) => button.click(event, messageModal));
|
||||
}
|
||||
});
|
||||
|
||||
messageModal = new bootstrap.Modal('#message-modal', {
|
||||
keyboard: isDismissible,
|
||||
backdrop: 'static',
|
||||
});
|
||||
|
||||
$messageModal.on('shown.bs.modal', () => {
|
||||
$messageModal
|
||||
.find('.modal-footer button:last')
|
||||
.removeClass('btn-outline-primary')
|
||||
.addClass('btn-primary')
|
||||
.focus();
|
||||
});
|
||||
|
||||
messageModal.show();
|
||||
|
||||
$messageModal.css('z-index', '99999').next().css('z-index', '9999');
|
||||
|
||||
return $messageModal;
|
||||
}
|
||||
|
||||
return {
|
||||
show,
|
||||
};
|
||||
})();
|
||||
48
assets/js/utils/string.js
Normal file
48
assets/js/utils/string.js
Normal file
@@ -0,0 +1,48 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Strings utility.
|
||||
*
|
||||
* This module implements the functionality of strings.
|
||||
*/
|
||||
window.App.Utils.String = (function () {
|
||||
/**
|
||||
* Upper case the first letter of the provided string.
|
||||
*
|
||||
* Old Name: GeneralFunctions.upperCaseFirstLetter
|
||||
*
|
||||
* @param {String} value
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function upperCaseFirstLetter(value) {
|
||||
return value.charAt(0).toUpperCase() + value.slice(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape HTML content with the use of jQuery.
|
||||
*
|
||||
* Old Name: GeneralFunctions.escapeHtml
|
||||
*
|
||||
* @param {String} content
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
function escapeHtml(content) {
|
||||
return $('<div/>').text(content).html();
|
||||
}
|
||||
|
||||
return {
|
||||
upperCaseFirstLetter,
|
||||
escapeHtml,
|
||||
};
|
||||
})();
|
||||
264
assets/js/utils/ui.js
Normal file
264
assets/js/utils/ui.js
Normal file
@@ -0,0 +1,264 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* UI utility.
|
||||
*
|
||||
* This module provides commonly used UI functionality.
|
||||
*/
|
||||
window.App.Utils.UI = (function () {
|
||||
/**
|
||||
* Get the Flatpickr compatible date format.
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
function getDateFormat() {
|
||||
switch (vars('date_format')) {
|
||||
case 'DMY':
|
||||
return 'd/m/Y';
|
||||
case 'MDY':
|
||||
return 'm/d/Y';
|
||||
case 'YMD':
|
||||
return 'Y/m/d';
|
||||
default:
|
||||
throw new Error('Invalid date format value.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Flatpickr compatible date format.
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
function getTimeFormat() {
|
||||
switch (vars('time_format')) {
|
||||
case 'regular':
|
||||
return 'h:i K';
|
||||
case 'military':
|
||||
return 'H:i';
|
||||
default:
|
||||
throw new Error('Invalid date format value.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the localization object.
|
||||
*
|
||||
* @return Object
|
||||
*/
|
||||
function getFlatpickrLocale() {
|
||||
const firstWeekDay = vars('first_weekday');
|
||||
|
||||
const firstWeekDayNumber = App.Utils.Date.getWeekdayId(firstWeekDay);
|
||||
|
||||
return {
|
||||
weekdays: {
|
||||
shorthand: [
|
||||
lang('sunday_short'),
|
||||
lang('monday_short'),
|
||||
lang('tuesday_short'),
|
||||
lang('wednesday_short'),
|
||||
lang('thursday_short'),
|
||||
lang('friday_short'),
|
||||
lang('saturday_short'),
|
||||
],
|
||||
longhand: [
|
||||
lang('sunday'),
|
||||
lang('monday'),
|
||||
lang('tuesday'),
|
||||
lang('wednesday'),
|
||||
lang('thursday'),
|
||||
lang('friday'),
|
||||
lang('saturday'),
|
||||
],
|
||||
},
|
||||
months: {
|
||||
shorthand: [
|
||||
lang('january_short'),
|
||||
lang('february_short'),
|
||||
lang('march_short'),
|
||||
lang('april_short'),
|
||||
lang('may_short'),
|
||||
lang('june_short'),
|
||||
lang('july_short'),
|
||||
lang('august_short'),
|
||||
lang('september_short'),
|
||||
lang('october_short'),
|
||||
lang('november_short'),
|
||||
lang('december_short'),
|
||||
],
|
||||
longhand: [
|
||||
lang('january'),
|
||||
lang('february'),
|
||||
lang('march'),
|
||||
lang('april'),
|
||||
lang('may'),
|
||||
lang('june'),
|
||||
lang('july'),
|
||||
lang('august'),
|
||||
lang('september'),
|
||||
lang('october'),
|
||||
lang('november'),
|
||||
lang('december'),
|
||||
],
|
||||
},
|
||||
daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
|
||||
firstDayOfWeek: firstWeekDayNumber,
|
||||
ordinal: function (nth) {
|
||||
const s = nth % 100;
|
||||
|
||||
if (s > 3 && s < 21) return 'th';
|
||||
switch (s % 10) {
|
||||
case 1:
|
||||
return 'st';
|
||||
case 2:
|
||||
return 'nd';
|
||||
case 3:
|
||||
return 'rd';
|
||||
default:
|
||||
return 'th';
|
||||
}
|
||||
},
|
||||
rangeSeparator: ` ${lang('to')} `,
|
||||
weekAbbreviation: lang('week_short'),
|
||||
scrollTitle: lang('scroll_to_increment'),
|
||||
toggleTitle: lang('click_to_toggle'),
|
||||
amPM: ['am', 'pm'],
|
||||
yearAriaLabel: lang('year'),
|
||||
monthAriaLabel: lang('month'),
|
||||
hourAriaLabel: lang('hour'),
|
||||
minuteAriaLabel: lang('minute'),
|
||||
time_24hr: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the date time picker component.
|
||||
*
|
||||
* This method is based on jQuery UI.
|
||||
*
|
||||
* @param {jQuery} $target
|
||||
* @param {Object} [params]
|
||||
*/
|
||||
function initializeDateTimePicker($target, params = {}) {
|
||||
$target.flatpickr({
|
||||
enableTime: true,
|
||||
allowInput: true,
|
||||
static: true,
|
||||
dateFormat: `${getDateFormat()} ${getTimeFormat()}`,
|
||||
time_24hr: vars('time_format') === 'military',
|
||||
locale: getFlatpickrLocale(),
|
||||
...params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the date picker component.
|
||||
*
|
||||
* This method is based on jQuery UI.
|
||||
*
|
||||
* @param {jQuery} $target
|
||||
* @param {Object} [params]
|
||||
*/
|
||||
function initializeDatePicker($target, params = {}) {
|
||||
$target.flatpickr({
|
||||
allowInput: true,
|
||||
dateFormat: getDateFormat(),
|
||||
locale: getFlatpickrLocale(),
|
||||
static: true,
|
||||
...params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the time picker component.
|
||||
*
|
||||
* This method is based on jQuery UI.
|
||||
*
|
||||
* @param {jQuery} $target
|
||||
* @param {Object} [params]
|
||||
*/
|
||||
function initializeTimePicker($target, params = {}) {
|
||||
$target.flatpickr({
|
||||
noCalendar: true,
|
||||
enableTime: true,
|
||||
allowInput: true,
|
||||
dateFormat: getTimeFormat(),
|
||||
time_24hr: vars('time_format') === 'military',
|
||||
locale: getFlatpickrLocale(),
|
||||
static: true,
|
||||
...params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the select dropdown component.
|
||||
*
|
||||
* This method is based on Select2.
|
||||
*
|
||||
* @param {jQuery} $target
|
||||
* @param {Object} [params]
|
||||
*/
|
||||
function initializeDropdown($target, params = {}) {
|
||||
$target.select2(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the text editor component.
|
||||
*
|
||||
* This method is based on Trumbowyg.
|
||||
*
|
||||
* @param {jQuery} $target
|
||||
* @param {Object} [params]
|
||||
*/
|
||||
function initializeTextEditor($target, params = {}) {
|
||||
$target.trumbowyg(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Date, Date-Time or Time picker value.
|
||||
*
|
||||
* @param {jQuery} $target
|
||||
*
|
||||
* @return {Date}
|
||||
*/
|
||||
function getDateTimePickerValue($target) {
|
||||
if (!$target?.length) {
|
||||
throw new Error('Empty $target argument provided.');
|
||||
}
|
||||
|
||||
return $target[0]._flatpickr.selectedDates[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Date, Date-Time or Time picker value.
|
||||
*
|
||||
* @param {jQuery} $target
|
||||
* @param {Date} value
|
||||
*/
|
||||
function setDateTimePickerValue($target, value) {
|
||||
if (!$target?.length) {
|
||||
throw new Error('Empty $target argument provided.');
|
||||
}
|
||||
|
||||
return $target[0]._flatpickr.setDate(value);
|
||||
}
|
||||
|
||||
return {
|
||||
initializeDateTimePicker,
|
||||
initializeDatePicker,
|
||||
initializeTimePicker,
|
||||
initializeDropdown,
|
||||
initializeTextEditor,
|
||||
getDateTimePickerValue,
|
||||
setDateTimePickerValue,
|
||||
};
|
||||
})();
|
||||
74
assets/js/utils/url.js
Normal file
74
assets/js/utils/url.js
Normal file
@@ -0,0 +1,74 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* URLs utility.
|
||||
*
|
||||
* This module implements the functionality of URLs.
|
||||
*/
|
||||
window.App.Utils.Url = (function () {
|
||||
/**
|
||||
* Get complete URL of the provided URI segment.
|
||||
*
|
||||
* @param {String} uri
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
function baseUrl(uri) {
|
||||
return `${vars('base_url')}/${uri}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the complete site URL (including the index.php) of the provided URI segment.
|
||||
*
|
||||
* @param {String} uri
|
||||
*
|
||||
* @returns {String}
|
||||
*/
|
||||
function siteUrl(uri) {
|
||||
return `${vars('base_url')}${vars('index_page') ? '/' + vars('index_page') : ''}/${uri}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a query parameter from the current request.
|
||||
*
|
||||
* @link http://www.netlobo.com/url_query_string_javascript.html
|
||||
*
|
||||
* @param {String} name Parameter name.
|
||||
|
||||
* @return {String} Returns the parameter value.
|
||||
*/
|
||||
function queryParam(name) {
|
||||
const url = location.href;
|
||||
|
||||
const parsedUrl = url.substr(url.indexOf('?')).slice(1).split('&');
|
||||
|
||||
for (let index in parsedUrl) {
|
||||
const parsedValue = parsedUrl[index].split('=');
|
||||
|
||||
if (parsedValue.length === 1 && parsedValue[0] === name) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (parsedValue.length === 2 && parsedValue[0] === name) {
|
||||
return decodeURIComponent(parsedValue[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
baseUrl,
|
||||
siteUrl,
|
||||
queryParam,
|
||||
};
|
||||
})();
|
||||
49
assets/js/utils/validation.js
Normal file
49
assets/js/utils/validation.js
Normal file
@@ -0,0 +1,49 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Validation utility.
|
||||
*
|
||||
* This module implements the functionality of validation.
|
||||
*/
|
||||
window.App.Utils.Validation = (function () {
|
||||
/**
|
||||
* Validate the provided email.
|
||||
*
|
||||
* @param {String} value
|
||||
*
|
||||
* @return {Boolean}
|
||||
*/
|
||||
function email(value) {
|
||||
const re =
|
||||
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
|
||||
|
||||
return re.test(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the provided phone.
|
||||
*
|
||||
* @param {String} value
|
||||
*
|
||||
* @return {Boolean}
|
||||
*/
|
||||
function phone(value) {
|
||||
const re = /^[+]?([0-9]*[\.\s\-\(\)]|[0-9]+){3,24}$/;
|
||||
|
||||
return re.test(value);
|
||||
}
|
||||
|
||||
return {
|
||||
email,
|
||||
phone,
|
||||
};
|
||||
})();
|
||||
763
assets/js/utils/working_plan.js
Normal file
763
assets/js/utils/working_plan.js
Normal file
@@ -0,0 +1,763 @@
|
||||
/* ----------------------------------------------------------------------------
|
||||
* 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
|
||||
* ---------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Working plan utility.
|
||||
*
|
||||
* This module implements the functionality of working plans.
|
||||
*/
|
||||
App.Utils.WorkingPlan = (function () {
|
||||
const moment = window.moment;
|
||||
|
||||
/**
|
||||
* Class WorkingPlan
|
||||
*
|
||||
* Contains the working plan functionality. The working plan DOM elements must be same
|
||||
* in every page this class is used.
|
||||
*
|
||||
* @class WorkingPlan
|
||||
*/
|
||||
class WorkingPlan {
|
||||
/**
|
||||
* This flag is used when trying to cancel row editing. It is
|
||||
* true only whenever the user presses the cancel button.
|
||||
*
|
||||
* @type {Boolean}
|
||||
*/
|
||||
enableCancel = false;
|
||||
|
||||
/**
|
||||
* This flag determines whether the jeditables are allowed to submit. It is
|
||||
* true only whenever the user presses the save button.
|
||||
*
|
||||
* @type {Boolean}
|
||||
*/
|
||||
enableSubmit = false;
|
||||
|
||||
/**
|
||||
* Set up the dom elements of a given working plan.
|
||||
*
|
||||
* @param {Object} workingPlan Contains the working hours and breaks for each day of the week.
|
||||
*/
|
||||
setup(workingPlan) {
|
||||
const weekDayId = App.Utils.Date.getWeekdayId(vars('first_weekday'));
|
||||
const workingPlanSorted = App.Utils.Date.sortWeekDictionary(workingPlan, weekDayId);
|
||||
|
||||
$('.working-plan tbody').empty();
|
||||
$('.breaks tbody').empty();
|
||||
|
||||
// Build working plan day list starting with the first weekday as set in the General settings
|
||||
const timeFormat = vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm';
|
||||
|
||||
$.each(
|
||||
workingPlanSorted,
|
||||
function (index, workingDay) {
|
||||
const day = this.convertValueToDay(index);
|
||||
|
||||
const dayDisplayName = App.Utils.String.upperCaseFirstLetter(day);
|
||||
|
||||
$('<tr/>', {
|
||||
'html': [
|
||||
$('<td/>', {
|
||||
'html': [
|
||||
$('<div/>', {
|
||||
'class': 'checkbox form-check',
|
||||
'html': [
|
||||
$('<input/>', {
|
||||
'class': 'form-check-input',
|
||||
'type': 'checkbox',
|
||||
'id': index,
|
||||
}),
|
||||
$('<label/>', {
|
||||
'class': 'form-check-label',
|
||||
'text': dayDisplayName,
|
||||
'for': index,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
$('<td/>', {
|
||||
'html': [
|
||||
$('<input/>', {
|
||||
'id': index + '-start',
|
||||
'class': 'work-start form-control form-control-sm',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
$('<td/>', {
|
||||
'html': [
|
||||
$('<input/>', {
|
||||
'id': index + '-end',
|
||||
'class': 'work-end form-control form-control-sm',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}).appendTo('.working-plan tbody');
|
||||
|
||||
if (workingDay) {
|
||||
$('#' + index).prop('checked', true);
|
||||
$('#' + index + '-start').val(
|
||||
moment(workingDay.start, 'HH:mm').format(timeFormat).toLowerCase(),
|
||||
);
|
||||
$('#' + index + '-end').val(moment(workingDay.end, 'HH:mm').format(timeFormat).toLowerCase());
|
||||
|
||||
// Sort day's breaks according to the starting hour
|
||||
workingDay.breaks.sort(function (break1, break2) {
|
||||
// We can do a direct string comparison since we have time based on 24 hours clock.
|
||||
return break1.start.localeCompare(break2.start);
|
||||
});
|
||||
|
||||
workingDay.breaks.forEach(function (workingDayBreak) {
|
||||
$('<tr/>', {
|
||||
'html': [
|
||||
$('<td/>', {
|
||||
'class': 'break-day editable',
|
||||
'text': dayDisplayName,
|
||||
}),
|
||||
$('<td/>', {
|
||||
'class': 'break-start editable',
|
||||
'text': moment(workingDayBreak.start, 'HH:mm').format(timeFormat).toLowerCase(),
|
||||
}),
|
||||
$('<td/>', {
|
||||
'class': 'break-end editable',
|
||||
'text': moment(workingDayBreak.end, 'HH:mm').format(timeFormat).toLowerCase(),
|
||||
}),
|
||||
$('<td/>', {
|
||||
'html': [
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm edit-break',
|
||||
'title': lang('edit'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-edit',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm delete-break',
|
||||
'title': lang('delete'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-trash-alt',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm save-break d-none',
|
||||
'title': lang('save'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-check-circle',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm cancel-break d-none',
|
||||
'title': lang('cancel'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-ban',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}).appendTo('.breaks tbody');
|
||||
});
|
||||
} else {
|
||||
$('#' + index).prop('checked', false);
|
||||
$('#' + index + '-start').prop('disabled', true);
|
||||
$('#' + index + '-end').prop('disabled', true);
|
||||
}
|
||||
}.bind(this),
|
||||
);
|
||||
|
||||
// Make break cells editable.
|
||||
this.editableDayCell($('.breaks .break-day'));
|
||||
this.editableTimeCell($('.breaks').find('.break-start, .break-end'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup the dom elements of a given working plan exception.
|
||||
*
|
||||
* @param {Object} workingPlanExceptions Contains the working plan exception.
|
||||
*/
|
||||
setupWorkingPlanExceptions(workingPlanExceptions) {
|
||||
for (const date in workingPlanExceptions) {
|
||||
const workingPlanException = workingPlanExceptions[date];
|
||||
|
||||
this.renderWorkingPlanExceptionRow(date, workingPlanException).appendTo(
|
||||
'.working-plan-exceptions tbody',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable editable break day.
|
||||
*
|
||||
* This method makes editable the break day cells.
|
||||
*
|
||||
* @param {Object} $selector The jquery selector ready for use.
|
||||
*/
|
||||
editableDayCell($selector) {
|
||||
const weekDays = {};
|
||||
weekDays[lang('sunday')] = lang('sunday'); //'Sunday';
|
||||
weekDays[lang('monday')] = lang('monday'); //'Monday';
|
||||
weekDays[lang('tuesday')] = lang('tuesday'); //'Tuesday';
|
||||
weekDays[lang('wednesday')] = lang('wednesday'); //'Wednesday';
|
||||
weekDays[lang('thursday')] = lang('thursday'); //'Thursday';
|
||||
weekDays[lang('friday')] = lang('friday'); //'Friday';
|
||||
weekDays[lang('saturday')] = lang('saturday'); //'Saturday';
|
||||
|
||||
$selector.editable(
|
||||
function (value) {
|
||||
return value;
|
||||
},
|
||||
{
|
||||
type: 'select',
|
||||
data: weekDays,
|
||||
event: 'edit',
|
||||
width: '100px',
|
||||
height: '30px',
|
||||
submit: '<button type="button" class="d-none submit-editable">Submit</button>',
|
||||
cancel: '<button type="button" class="d-none cancel-editable">Cancel</button>',
|
||||
onblur: 'ignore',
|
||||
onreset: function () {
|
||||
if (!this.enableCancel) {
|
||||
return false; // disable ESC button
|
||||
}
|
||||
}.bind(this),
|
||||
onsubmit: function () {
|
||||
if (!this.enableSubmit) {
|
||||
return false; // disable Enter button
|
||||
}
|
||||
}.bind(this),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable editable break time.
|
||||
*
|
||||
* This method makes editable the break time cells.
|
||||
*
|
||||
* @param {Object} $selector The jquery selector ready for use.
|
||||
*/
|
||||
editableTimeCell($selector) {
|
||||
$selector.editable(
|
||||
function (value) {
|
||||
// Do not return the value because the user needs to press the "Save" button.
|
||||
return value;
|
||||
},
|
||||
{
|
||||
event: 'edit',
|
||||
width: '100px',
|
||||
height: '30px',
|
||||
submit: $('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'd-none submit-editable',
|
||||
'text': lang('save'),
|
||||
}).get(0).outerHTML,
|
||||
cancel: $('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'd-none cancel-editable',
|
||||
'text': lang('cancel'),
|
||||
}).get(0).outerHTML,
|
||||
onblur: 'ignore',
|
||||
onreset: function () {
|
||||
if (!this.enableCancel) {
|
||||
return false; // disable ESC button
|
||||
}
|
||||
}.bind(this),
|
||||
onsubmit: function () {
|
||||
if (!this.enableSubmit) {
|
||||
return false; // disable Enter button
|
||||
}
|
||||
}.bind(this),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a working plan exception row.
|
||||
*
|
||||
* This method makes editable the break time cells.
|
||||
*
|
||||
* @param {String} date In "Y-m-d" format.
|
||||
* @param {Object} workingPlanException Contains exception information.
|
||||
*/
|
||||
renderWorkingPlanExceptionRow(date, workingPlanException) {
|
||||
const timeFormat = vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm';
|
||||
|
||||
const start = workingPlanException?.start;
|
||||
const end = workingPlanException?.end;
|
||||
|
||||
return $('<tr/>', {
|
||||
'data': {
|
||||
'date': date,
|
||||
'workingPlanException': workingPlanException,
|
||||
},
|
||||
'html': [
|
||||
$('<td/>', {
|
||||
'class': 'working-plan-exception-date',
|
||||
'text': App.Utils.Date.format(date, vars('date_format'), vars('time_format'), false),
|
||||
}),
|
||||
$('<td/>', {
|
||||
'class': 'working-plan-exception--start',
|
||||
'text': start ? moment(start, 'HH:mm').format(timeFormat).toLowerCase() : '-',
|
||||
}),
|
||||
$('<td/>', {
|
||||
'class': 'working-plan-exception--end',
|
||||
'text': end ? moment(end, 'HH:mm').format(timeFormat).toLowerCase() : '-',
|
||||
}),
|
||||
$('<td/>', {
|
||||
'html': [
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm edit-working-plan-exception',
|
||||
'title': lang('edit'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-edit',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm delete-working-plan-exception',
|
||||
'title': lang('delete'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-trash-alt',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the utility event listeners.
|
||||
*/
|
||||
addEventListeners() {
|
||||
/**
|
||||
* Event: Day Checkbox "Click"
|
||||
*
|
||||
* Enable or disable the time selection for each day.
|
||||
*
|
||||
* @param {jQuery.Event} event
|
||||
*/
|
||||
$('.working-plan tbody').on('click', 'input:checkbox', (event) => {
|
||||
const id = $(event.currentTarget).attr('id');
|
||||
|
||||
if ($(event.currentTarget).prop('checked') === true) {
|
||||
$('#' + id + '-start')
|
||||
.prop('disabled', false)
|
||||
.val('9:00 AM');
|
||||
$('#' + id + '-end')
|
||||
.prop('disabled', false)
|
||||
.val('6:00 PM');
|
||||
} else {
|
||||
$('#' + id + '-start')
|
||||
.prop('disabled', true)
|
||||
.val('');
|
||||
$('#' + id + '-end')
|
||||
.prop('disabled', true)
|
||||
.val('');
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Add Break Button "Click"
|
||||
*
|
||||
* A new row is added on the table and the user can enter the new break
|
||||
* data. After that he can either press the save or cancel button.
|
||||
*/
|
||||
$('.add-break').on('click', () => {
|
||||
const timeFormat = vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm';
|
||||
|
||||
const $newBreak = $('<tr/>', {
|
||||
'html': [
|
||||
$('<td/>', {
|
||||
'class': 'break-day editable',
|
||||
'text': lang('sunday'),
|
||||
}),
|
||||
$('<td/>', {
|
||||
'class': 'break-start editable',
|
||||
'text': moment('12:00', 'HH:mm').format(timeFormat).toLowerCase(),
|
||||
}),
|
||||
$('<td/>', {
|
||||
'class': 'break-end editable',
|
||||
'text': moment('14:00', 'HH:mm').format(timeFormat).toLowerCase(),
|
||||
}),
|
||||
$('<td/>', {
|
||||
'html': [
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm edit-break',
|
||||
'title': lang('edit'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-edit',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm delete-break',
|
||||
'title': lang('delete'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-trash-alt',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm save-break d-none',
|
||||
'title': lang('save'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-check-circle',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
$('<button/>', {
|
||||
'type': 'button',
|
||||
'class': 'btn btn-outline-secondary btn-sm cancel-break d-none',
|
||||
'title': lang('cancel'),
|
||||
'html': [
|
||||
$('<span/>', {
|
||||
'class': 'fas fa-ban',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}).appendTo('.breaks tbody');
|
||||
|
||||
// Bind editable and event handlers.
|
||||
this.editableDayCell($newBreak.find('.break-day'));
|
||||
this.editableTimeCell($newBreak.find('.break-start, .break-end'));
|
||||
$newBreak.find('.edit-break').trigger('click');
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Edit Break Button "Click"
|
||||
*
|
||||
* Enables the row editing for the "Breaks" table rows.
|
||||
*
|
||||
* @param {jQuery.Event} event
|
||||
*/
|
||||
$(document).on('click', '.edit-break', (event) => {
|
||||
// Reset previous editable table cells.
|
||||
const $previousEdits = $(event.currentTarget).closest('table').find('.editable');
|
||||
|
||||
$previousEdits.each(function (index, editable) {
|
||||
if (editable.reset) {
|
||||
editable.reset();
|
||||
}
|
||||
});
|
||||
|
||||
// Make all cells in current row editable.
|
||||
const $tr = $(event.currentTarget).closest('tr');
|
||||
|
||||
$tr.children().trigger('edit');
|
||||
|
||||
App.Utils.UI.initializeTimePicker($tr.find('.break-start input, .break-end input'));
|
||||
|
||||
$tr.find('.break-day select').focus();
|
||||
|
||||
// Show save - cancel buttons.
|
||||
$tr.find('.edit-break, .delete-break').addClass('d-none');
|
||||
$tr.find('.save-break, .cancel-break').removeClass('d-none');
|
||||
$tr.find('select,input:text').addClass('form-control form-control-sm');
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Delete Break Button "Click"
|
||||
*
|
||||
* Removes the current line from the "Breaks" table.
|
||||
*
|
||||
* @param {jQuery.Event} event
|
||||
*/
|
||||
$(document).on('click', '.delete-break', (event) => {
|
||||
$(event.currentTarget).closest('tr').remove();
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Cancel Break Button "Click"
|
||||
*
|
||||
* Bring the ".breaks" table back to its initial state.
|
||||
*
|
||||
* @param {jQuery.Event} event
|
||||
*/
|
||||
$(document).on('click', '.cancel-break', (event) => {
|
||||
const element = event.target;
|
||||
const $modifiedRow = $(element).closest('tr');
|
||||
this.enableCancel = true;
|
||||
$modifiedRow.find('.cancel-editable').trigger('click');
|
||||
this.enableCancel = false;
|
||||
|
||||
$modifiedRow.find('.edit-break, .delete-break').removeClass('d-none');
|
||||
$modifiedRow.find('.save-break, .cancel-break').addClass('d-none');
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Save Break Button "Click"
|
||||
*
|
||||
* Save the editable values and restore the table to its initial state.
|
||||
*
|
||||
* @param {jQuery.Event} event
|
||||
*/
|
||||
$(document).on('click', '.save-break', (event) => {
|
||||
const timeFormat = vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm';
|
||||
// Break's start time must always be prior to break's end.
|
||||
const element = event.target;
|
||||
|
||||
const $modifiedRow = $(element).closest('tr');
|
||||
|
||||
const startMoment = moment($modifiedRow.find('.break-start input').val(), timeFormat);
|
||||
|
||||
const endMoment = moment($modifiedRow.find('.break-end input').val(), timeFormat);
|
||||
|
||||
if (startMoment.isAfter(endMoment)) {
|
||||
$modifiedRow.find('.break-end input').val(
|
||||
startMoment
|
||||
.add(1, 'hour')
|
||||
.format(timeFormat)
|
||||
.toLowerCase(),
|
||||
);
|
||||
}
|
||||
|
||||
this.enableSubmit = true;
|
||||
$modifiedRow.find('.editable .submit-editable').trigger('click');
|
||||
this.enableSubmit = false;
|
||||
|
||||
$modifiedRow.find('.save-break, .cancel-break').addClass('d-none');
|
||||
$modifiedRow.find('.edit-break, .delete-break').removeClass('d-none');
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Add Working Plan Exception Button "Click"
|
||||
*
|
||||
* A new row is added on the table and the user can enter the new working plan exception.
|
||||
*/
|
||||
$(document).on('click', '.add-working-plan-exception', () => {
|
||||
App.Components.WorkingPlanExceptionsModal.add().done((date, workingPlanException) => {
|
||||
let $tr = null;
|
||||
|
||||
$('.working-plan-exceptions tbody tr').each((index, tr) => {
|
||||
if (date === $(tr).data('date')) {
|
||||
$tr = $(tr);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
let $newTr = this.renderWorkingPlanExceptionRow(date, workingPlanException);
|
||||
|
||||
if ($tr) {
|
||||
$tr.replaceWith($newTr);
|
||||
} else {
|
||||
$newTr.appendTo('.working-plan-exceptions tbody');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Edit working plan exception Button "Click"
|
||||
*
|
||||
* Enables the row editing for the "working plan exception" table rows.
|
||||
*
|
||||
* @param {jQuery.Event} event
|
||||
*/
|
||||
$(document).on('click', '.edit-working-plan-exception', (event) => {
|
||||
const $tr = $(event.target).closest('tr');
|
||||
const date = $tr.data('date');
|
||||
const workingPlanException = $tr.data('workingPlanException');
|
||||
|
||||
App.Components.WorkingPlanExceptionsModal.edit(date, workingPlanException).done(
|
||||
(date, workingPlanException) => {
|
||||
$tr.replaceWith(this.renderWorkingPlanExceptionRow(date, workingPlanException));
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Event: Delete working plan exception Button "Click"
|
||||
*
|
||||
* Removes the current line from the "working plan exceptions" table.
|
||||
*
|
||||
* @param {jQuery.Event} event
|
||||
*/
|
||||
$(document).on('click', '.delete-working-plan-exception', (event) => {
|
||||
$(event.currentTarget).closest('tr').remove();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the working plan settings.
|
||||
*
|
||||
* @return {Object} Returns the working plan settings object.
|
||||
*/
|
||||
get() {
|
||||
const workingPlan = {};
|
||||
|
||||
const timeFormat = vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm';
|
||||
|
||||
$('.working-plan input:checkbox').each((index, checkbox) => {
|
||||
const id = $(checkbox).attr('id');
|
||||
if ($(checkbox).prop('checked') === true) {
|
||||
workingPlan[id] = {
|
||||
start: moment($('#' + id + '-start').val(), timeFormat).format('HH:mm'),
|
||||
end: moment($('#' + id + '-end').val(), timeFormat).format('HH:mm'),
|
||||
breaks: [],
|
||||
};
|
||||
|
||||
$('.breaks tr').each((index, tr) => {
|
||||
const day = this.convertDayToValue($(tr).find('.break-day').text());
|
||||
|
||||
if (day === id) {
|
||||
const start = $(tr).find('.break-start').text();
|
||||
const end = $(tr).find('.break-end').text();
|
||||
|
||||
workingPlan[id].breaks.push({
|
||||
start: moment(start, vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm').format(
|
||||
'HH:mm',
|
||||
),
|
||||
end: moment(end, vars('time_format') === 'regular' ? 'h:mm a' : 'HH:mm').format(
|
||||
'HH:mm',
|
||||
),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Sort breaks increasingly by hour within day
|
||||
workingPlan[id].breaks.sort((break1, break2) => {
|
||||
// We can do a direct string comparison since we have time based on 24 hours clock.
|
||||
return break1.start.localeCompare(break2.start);
|
||||
});
|
||||
} else {
|
||||
workingPlan[id] = null;
|
||||
}
|
||||
});
|
||||
|
||||
return workingPlan;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the working plan exceptions settings.
|
||||
*
|
||||
* @return {Object} Returns the working plan exceptions settings object.
|
||||
*/
|
||||
getWorkingPlanExceptions() {
|
||||
const workingPlanExceptions = {};
|
||||
|
||||
$('.working-plan-exceptions tbody tr').each((index, tr) => {
|
||||
const $tr = $(tr);
|
||||
const date = $tr.data('date');
|
||||
workingPlanExceptions[date] = $tr.data('workingPlanException');
|
||||
});
|
||||
|
||||
return workingPlanExceptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables or disables the timepicker functionality from the working plan input text fields.
|
||||
*
|
||||
* @param {Boolean} [disabled] If true then the timepickers will be disabled.
|
||||
*/
|
||||
timepickers(disabled) {
|
||||
disabled = disabled || false;
|
||||
|
||||
if (disabled === false) {
|
||||
App.Utils.UI.initializeTimePicker($('.working-plan input:text'), {
|
||||
onChange: (selectedDates, dateStr, instance) => {
|
||||
const startMoment = moment(selectedDates[0]);
|
||||
|
||||
const $workEnd = $(instance.input).closest('tr').find('.work-end');
|
||||
|
||||
const endMoment = moment(App.Utils.UI.getDateTimePickerValue($workEnd));
|
||||
|
||||
if (startMoment > endMoment) {
|
||||
App.Utils.UI.setDateTimePickerValue($workEnd, startMoment.add(1, 'hour').toDate());
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the current plan back to the company's default working plan.
|
||||
*/
|
||||
reset() {}
|
||||
|
||||
/**
|
||||
* This is necessary for translated days.
|
||||
*
|
||||
* @param {String} value Day value could be like "monday", "tuesday" etc.
|
||||
*/
|
||||
convertValueToDay(value) {
|
||||
switch (value) {
|
||||
case 'sunday':
|
||||
return lang('sunday');
|
||||
case 'monday':
|
||||
return lang('monday');
|
||||
case 'tuesday':
|
||||
return lang('tuesday');
|
||||
case 'wednesday':
|
||||
return lang('wednesday');
|
||||
case 'thursday':
|
||||
return lang('thursday');
|
||||
case 'friday':
|
||||
return lang('friday');
|
||||
case 'saturday':
|
||||
return lang('saturday');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is necessary for translated days.
|
||||
*
|
||||
* @param {String} day Day value could be like "Monday", "Tuesday" etc.
|
||||
*/
|
||||
convertDayToValue(day) {
|
||||
switch (day) {
|
||||
case lang('sunday'):
|
||||
return 'sunday';
|
||||
case lang('monday'):
|
||||
return 'monday';
|
||||
case lang('tuesday'):
|
||||
return 'tuesday';
|
||||
case lang('wednesday'):
|
||||
return 'wednesday';
|
||||
case lang('thursday'):
|
||||
return 'thursday';
|
||||
case lang('friday'):
|
||||
return 'friday';
|
||||
case lang('saturday'):
|
||||
return 'saturday';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return WorkingPlan;
|
||||
})();
|
||||
Reference in New Issue
Block a user