This commit is contained in:
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,
|
||||
};
|
||||
})();
|
Reference in New Issue
Block a user