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

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

File diff suppressed because it is too large Load Diff

View 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,
};
})();

View 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,
};
})();

File diff suppressed because it is too large Load Diff

198
assets/js/utils/date.js Normal file
View File

@ -0,0 +1,198 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* 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
View 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
View File

@ -0,0 +1,176 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Online Appointment Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.5.0
* ---------------------------------------------------------------------------- */
/**
* 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
View 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
View 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
View 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
View 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
View 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,
};
})();

View 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,
};
})();

View 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;
})();