Refactor the providers helper JS file so that it becomes a standalone module.

This commit is contained in:
Alex Tselegidis 2022-01-11 10:54:46 +01:00
parent 5e59c3b5a3
commit 21be3e7b50
6 changed files with 603 additions and 844 deletions

View file

@ -37,7 +37,7 @@ class Providers extends EA_Controller {
/**
* Render the backend providers page.
*
* On this page admin users will be able to manage providers, which are eventually selected by customers during the
* On this page admin users will be able to manage providers, which are eventually selected by customers during the
* booking process.
*/
public function index()
@ -53,6 +53,25 @@ class Providers extends EA_Controller {
$role_slug = session('role_slug');
$services = $this->services_model->get();
foreach($services as &$service)
{
$this->services_model->only($service, ['id', 'name']);
}
script_vars([
'user_id' => $user_id,
'role_slug' => $role_slug,
'company_working_plan' => setting('company_working_plan'),
'date_format' => setting('date_format'),
'time_format' => setting('time_format'),
'first_weekday' => setting('first_weekday'),
'min_password_length' => MIN_PASSWORD_LENGTH,
'timezones' => $this->timezones->to_array(),
'services' => $services,
]);
html_vars([
'page_title' => lang('providers'),
'active_menu' => PRIV_USERS,
@ -82,7 +101,7 @@ class Providers extends EA_Controller {
$order_by = 'first_name ASC, last_name ASC, email ASC';
$limit = request('limit', 1000);
$offset = 0;
$providers = $this->providers_model->search($keyword, $limit, $offset, $order_by);
@ -102,7 +121,7 @@ class Providers extends EA_Controller {
{
try
{
$provider = json_decode(request('provider'), TRUE);
$provider = request('provider');
if (cannot('add', PRIV_USERS))
{
@ -129,7 +148,7 @@ class Providers extends EA_Controller {
{
try
{
$provider = json_decode(request('provider'), TRUE);
$provider = request('provider');
if (cannot('edit', PRIV_USERS))
{

View file

@ -211,9 +211,9 @@
<br>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="provider-notifications">
<label class="custom-form-label" for="provider-notifications">
<div class="form-check form-switch me-4">
<input class="form-check-input" type="checkbox" id="provider-notifications">
<label class="form-check-label" for="provider-notifications">
<?= lang('receive_notifications') ?>
</label>
</div>
@ -311,35 +311,19 @@
<?php section('content') ?>
<?php section('scripts') ?>
<script src="<?= asset_url('assets/js/pages/backend_providers_helper.js') ?>"></script>
<script src="<?= asset_url('assets/js/pages/backend_providers.js') ?>"></script>
<script src="<?= asset_url('assets/js/utils/working_plan.js') ?>"></script>
<script src="<?= asset_url('assets/js/components/working_plan_exceptions_modal.js') ?>"></script>
<script src="<?= asset_url('assets/vendor/jquery-ui-timepicker-addon/jquery-ui-timepicker-addon.min.js') ?>"></script>
<script src="<?= asset_url('assets/vendor/jquery-jeditable/jquery.jeditable.min.js') ?>"></script>
<script>
var GlobalVariables = {
csrfToken: <?= json_encode($this->security->get_csrf_hash()) ?>,
baseUrl: <?= json_encode(config('base_url')) ?>,
dateFormat: <?= json_encode(setting('date_format')) ?>,
timeFormat: <?= json_encode(setting('time_format')) ?>,
firstWeekday: <?= json_encode(setting('first_weekday')) ?>,
services: <?= json_encode($services) ?>,
timezones: <?= json_encode($timezones) ?>,
workingPlan: <?= json_encode(json_decode(setting('company_working_plan'))) ?>,
user: {
id: <?= session('user_id') ?>,
email: <?= json_encode(session('user_email')) ?>,
timezone: <?= json_encode(session('timezone')) ?>,
role_slug: <?= json_encode(session('role_slug')) ?>,
privileges: <?= json_encode($privileges) ?>
}
};
<script src="<?= asset_url('assets/js/utils/date.js') ?>"></script>
<script src="<?= asset_url('assets/js/utils/message.js') ?>"></script>
<script src="<?= asset_url('assets/js/utils/string.js') ?>"></script>
<script src="<?= asset_url('assets/js/utils/url.js') ?>"></script>
<script src="<?= asset_url('assets/js/utils/validation.js') ?>"></script>
<script src="<?= asset_url('assets/js/utils/working_plan.js') ?>"></script>
<script src="<?= asset_url('assets/js/http/account_http_client.js') ?>"></script>
<script src="<?= asset_url('assets/js/http/providers_http_client.js') ?>"></script>
<script src="<?= asset_url('assets/js/pages/providers.js') ?>"></script>
$(function () {
BackendProviders.initialize(true);
});
</script>
<?php section('scripts') ?>

View file

@ -11,7 +11,18 @@
App.Http.Providers = (function () {
/**
* Create an provider.
* Save (create or update) a provider.
*
* @param {Object} provider
*
* @return {Object}
*/
function save(provider) {
return provider.id ? update(provider) : create(provider);
}
/**
* Create a provider.
*
* @param {Object} provider
*
@ -29,7 +40,7 @@ App.Http.Providers = (function () {
}
/**
* Update an provider.
* Update a provider.
*
* @param {Object} provider
*
@ -47,7 +58,7 @@ App.Http.Providers = (function () {
}
/**
* Delete an provider.
* Delete a provider.
*
* @param {Number} providerId
*
@ -89,7 +100,7 @@ App.Http.Providers = (function () {
}
/**
* Find an provider.
* Find a provider.
*
* @param {Number} providerId
*
@ -107,6 +118,7 @@ App.Http.Providers = (function () {
}
return {
save,
create,
update,
destroy,

View file

@ -1,143 +0,0 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Open Source Web 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.0.0
* ---------------------------------------------------------------------------- */
window.BackendProviders = window.BackendProviders || {};
/**
* Backend Providers
*
* This module handles the js functionality of the providers backend page.
*
* @module BackendProviders
*/
(function (exports) {
'use strict';
/**
* Minimum Password Length
*
* @type {Number}
*/
exports.MIN_PASSWORD_LENGTH = 7;
/**
* Contains the current tab record methods for the page.
*
* @type {ProvidersHelper}
*/
var helper = {};
/**
* Use this class instance for performing actions on the working plan.
*
* @type {WorkingPlan}
*/
exports.wp = {};
/**
* Initialize the backend providers page.
*
* @param {Boolean} defaultEventHandlers (OPTIONAL) Whether to bind the default event handlers.
*/
exports.initialize = function (defaultEventHandlers) {
defaultEventHandlers = defaultEventHandlers || true;
exports.wp = new WorkingPlan();
exports.wp.bindEventHandlers();
// Instantiate default helper object (admin).
helper = new ProvidersHelper();
helper.resetForm();
helper.filter('');
helper.bindEventHandlers();
// Fill the services and providers list boxes.
GlobalVariables.services.forEach(function (service) {
$('<div/>', {
'class': 'checkbox',
'html': [
$('<div/>', {
'class': 'checkbox form-check',
'html': [
$('<input/>', {
'class': 'form-check-input',
'type': 'checkbox',
'data-id': service.id,
'prop': {
'disabled': true
}
}),
$('<label/>', {
'class': 'form-check-label',
'text': service.name,
'for': service.id
})
]
})
]
}).appendTo('#provider-services');
});
// Bind event handlers.
if (defaultEventHandlers) {
bindEventHandlers();
}
};
/**
* Binds the default backend providers event handlers. Do not use this method on a different
* page because it needs the backend providers page DOM.
*/
function bindEventHandlers() {
/**
* Event: Provider Username "Blur"
*
* When the provider leaves the provider username input field we will need to check if the username
* is not taken by another record in the system.
*/
$('#provider-username').focusout(function () {
var $input = $(this);
if ($input.prop('readonly') === true || $input.val() === '') {
return;
}
var providerId = $input.parents().eq(2).find('.record-id').val();
if (!providerId) {
return;
}
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_validate_username';
var data = {
csrf_token: GlobalVariables.csrfToken,
username: $input.val(),
user_id: providerId
};
$.post(url, data).done(function (response) {
if (response.is_valid === 'false') {
$input.addClass('is-invalid');
$input.attr('already-exists', 'true');
$input.parents().eq(3).find('.form-message').text(App.Lang.username_already_exists);
$input.parents().eq(3).find('.form-message').show();
} else {
$input.removeClass('is-invalid');
$input.attr('already-exists', 'false');
if ($input.parents().eq(3).find('.form-message').text() === App.Lang.username_already_exists) {
$input.parents().eq(3).find('.form-message').hide();
}
}
});
});
}
})(window.BackendProviders);

View file

@ -1,664 +0,0 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Open Source Web 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.0.0
* ---------------------------------------------------------------------------- */
(function () {
'use strict';
/**
* Providers Helper
*
* This class contains the Providers helper class declaration, along with the "Providers" tab
* event handlers. By dividing the backend/users tab functionality into separate files
* it is easier to maintain the code.
*
* @class ProvidersHelper
*/
var ProvidersHelper = function () {
this.filterResults = {}; // Store the results for later use.
this.filterLimit = 20;
};
/**
* Bind the event handlers for the backend/users "Providers" tab.
*/
ProvidersHelper.prototype.bindEventHandlers = function () {
/**
* Event: Filter Providers Form "Submit"
*
* Filter the provider records with the given key string.
*
* @param {jQuery.Event} event
*/
$('#providers').on(
'submit',
'#filter-providers form',
function (event) {
event.preventDefault();
var key = $('#filter-providers .key').val();
$('.selected').removeClass('selected');
this.resetForm();
this.filter(key);
}.bind(this)
);
/**
* Event: Filter Provider Row "Click"
*
* Display the selected provider data to the user.
*/
$('#providers').on(
'click',
'.provider-row',
function (event) {
if ($('#filter-providers .filter').prop('disabled')) {
$('#filter-providers .results').css('color', '#AAA');
return; // Exit because we are currently on edit mode.
}
var providerId = $(event.currentTarget).attr('data-id');
var provider = this.filterResults.find(function (filterResult) {
return Number(filterResult.id) === Number(providerId);
});
this.display(provider);
$('#filter-providers .selected').removeClass('selected');
$(event.currentTarget).addClass('selected');
$('#edit-provider, #delete-provider').prop('disabled', false);
}.bind(this)
);
/**
* Event: Add New Provider Button "Click"
*/
$('#providers').on(
'click',
'#add-provider',
function () {
this.resetForm();
$('#filter-providers button').prop('disabled', true);
$('#filter-providers .results').css('color', '#AAA');
$('#providers .add-edit-delete-group').hide();
$('#providers .save-cancel-group').show();
$('#providers .record-details').find('input, select, textarea').prop('disabled', false);
$('#provider-password, #provider-password-confirm').addClass('required');
$('#providers')
.find(
'.add-break, .edit-break, .delete-break, .add-working-plan-exception, .edit-working-plan-exception, .delete-working-plan-exception, #reset-working-plan'
)
.prop('disabled', false);
$('#provider-services input:checkbox').prop('disabled', false);
// Apply default working plan
BackendProviders.wp.setup(GlobalVariables.workingPlan);
BackendProviders.wp.timepickers(false);
}.bind(this)
);
/**
* Event: Edit Provider Button "Click"
*/
$('#providers').on('click', '#edit-provider', function () {
$('#providers .add-edit-delete-group').hide();
$('#providers .save-cancel-group').show();
$('#filter-providers button').prop('disabled', true);
$('#filter-providers .results').css('color', '#AAA');
$('#providers .record-details').find('input, select, textarea').prop('disabled', false);
$('#provider-password, #provider-password-confirm').removeClass('required');
$('#provider-services input:checkbox').prop('disabled', false);
$('#providers')
.find(
'.add-break, .edit-break, .delete-break, .add-working-plan-exception, .edit-working-plan-exception, .delete-working-plan-exception, #reset-working-plan'
)
.prop('disabled', false);
$('#providers input:checkbox').prop('disabled', false);
BackendProviders.wp.timepickers(false);
});
/**
* Event: Delete Provider Button "Click"
*/
$('#providers').on(
'click',
'#delete-provider',
function () {
var providerId = $('#provider-id').val();
var buttons = [
{
text: App.Lang.cancel,
click: function () {
$('#message-box').dialog('close');
}
},
{
text: App.Lang.delete,
click: function () {
this.delete(providerId);
$('#message-box').dialog('close');
}.bind(this)
}
];
GeneralFunctions.displayMessageBox(App.Lang.delete_provider, App.Lang.delete_record_prompt, buttons);
}.bind(this)
);
/**
* Event: Save Provider Button "Click"
*/
$('#providers').on(
'click',
'#save-provider',
function () {
var provider = {
first_name: $('#provider-first-name').val(),
last_name: $('#provider-last-name').val(),
email: $('#provider-email').val(),
mobile_number: $('#provider-mobile-number').val(),
phone_number: $('#provider-phone-number').val(),
address: $('#provider-address').val(),
city: $('#provider-city').val(),
state: $('#provider-state').val(),
zip_code: $('#provider-zip-code').val(),
notes: $('#provider-notes').val(),
timezone: $('#provider-timezone').val(),
settings: {
username: $('#provider-username').val(),
working_plan: JSON.stringify(BackendProviders.wp.get()),
working_plan_exceptions: JSON.stringify(BackendProviders.wp.getWorkingPlanExceptions()),
notifications: $('#provider-notifications').prop('checked'),
calendar_view: $('#provider-calendar-view').val()
}
};
// Include provider services.
provider.services = [];
$('#provider-services input:checkbox').each(function (index, checkbox) {
if ($(checkbox).prop('checked')) {
provider.services.push($(checkbox).attr('data-id'));
}
});
// Include password if changed.
if ($('#provider-password').val() !== '') {
provider.settings.password = $('#provider-password').val();
}
// Include id if changed.
if ($('#provider-id').val() !== '') {
provider.id = $('#provider-id').val();
}
if (!this.validate()) {
return;
}
this.save(provider);
}.bind(this)
);
/**
* Event: Cancel Provider Button "Click"
*
* Cancel add or edit of an provider record.
*/
$('#providers').on(
'click',
'#cancel-provider',
function () {
var id = $('#filter-providers .selected').attr('data-id');
this.resetForm();
if (id) {
this.select(id, true);
}
}.bind(this)
);
/**
* Event: Display Provider Details "Click"
*/
$('#providers').on('shown.bs.tab', 'a[data-toggle="tab"]', function () {
Backend.placeFooterToBottom();
});
/**
* Event: Reset Working Plan Button "Click".
*/
$('#providers').on('click', '#reset-working-plan', function () {
$('.breaks tbody').empty();
$('.working-plan-exceptions tbody').empty();
$('.work-start, .work-end').val('');
BackendProviders.wp.setup(GlobalVariables.workingPlan);
BackendProviders.wp.timepickers(false);
});
};
/**
* Remove the previously registered event handlers.
*/
ProvidersHelper.prototype.unbindEventHandlers = function () {
$('#providers')
.off('submit', '#filter-providers form')
.off('click', '#filter-providers .clear')
.off('click', '.provider-row')
.off('click', '#add-provider')
.off('click', '#edit-provider')
.off('click', '#delete-provider')
.off('click', '#save-provider')
.off('click', '#cancel-provider')
.off('shown.bs.tab', 'a[data-toggle="tab"]')
.off('click', '#reset-working-plan');
};
/**
* Save provider record to database.
*
* @param {Object} provider Contains the provider record data. If an 'id' value is provided
* then the update operation is going to be executed.
*/
ProvidersHelper.prototype.save = function (provider) {
var url = GlobalVariables.baseUrl + '/index.php/providers/' + (provider.id ? 'update' : 'create');
var data = {
csrf_token: GlobalVariables.csrfToken,
provider: JSON.stringify(provider)
};
$.post(url, data).done(
function (response) {
Backend.displayNotification(App.Lang.provider_saved);
this.resetForm();
$('#filter-providers .key').val('');
this.filter('', response.id, true);
}.bind(this)
);
};
/**
* Delete a provider record from database.
*
* @param {Number} id Record id to be deleted.
*/
ProvidersHelper.prototype.delete = function (id) {
var url = GlobalVariables.baseUrl + '/index.php/providers/destroy';
var data = {
csrf_token: GlobalVariables.csrfToken,
provider_id: id
};
$.post(url, data).done(
function () {
Backend.displayNotification(App.Lang.provider_deleted);
this.resetForm();
this.filter($('#filter-providers .key').val());
}.bind(this)
);
};
/**
* Validates a provider record.
*
* @return {Boolean} Returns the validation result.
*/
ProvidersHelper.prototype.validate = function () {
$('#providers .is-invalid').removeClass('is-invalid');
$('#providers .form-message').removeClass('alert-danger').hide();
try {
// Validate required fields.
var missingRequired = false;
$('#providers .required').each(function (index, requiredField) {
if (!$(requiredField).val()) {
$(requiredField).addClass('is-invalid');
missingRequired = true;
}
});
if (missingRequired) {
throw new Error(App.Lang.fields_are_required);
}
// Validate passwords.
if ($('#provider-password').val() !== $('#provider-password-confirm').val()) {
$('#provider-password, #provider-password-confirm').addClass('is-invalid');
throw new Error(App.Lang.passwords_mismatch);
}
if (
$('#provider-password').val().length < BackendProviders.MIN_PASSWORD_LENGTH &&
$('#provider-password').val() !== ''
) {
$('#provider-password, #provider-password-confirm').addClass('is-invalid');
throw new Error(
App.Lang.password_length_notice.replace('$number', BackendProviders.MIN_PASSWORD_LENGTH)
);
}
// Validate user email.
if (!GeneralFunctions.validateEmail($('#provider-email').val())) {
$('#provider-email').addClass('is-invalid');
throw new Error(App.Lang.invalid_email);
}
// Check if username exists
if ($('#provider-username').attr('already-exists') === 'true') {
$('#provider-username').addClass('is-invalid');
throw new Error(App.Lang.username_already_exists);
}
return true;
} catch (error) {
$('#providers .form-message').addClass('alert-danger').text(error.message).show();
return false;
}
};
/**
* Resets the provider tab form back to its initial state.
*/
ProvidersHelper.prototype.resetForm = function () {
$('#filter-providers .selected').removeClass('selected');
$('#filter-providers button').prop('disabled', false);
$('#filter-providers .results').css('color', '');
$('#providers .add-edit-delete-group').show();
$('#providers .save-cancel-group').hide();
$('#providers .record-details h3 a').remove();
$('#providers .record-details').find('input, select, textarea').val('').prop('disabled', true);
$('#providers .record-details #provider-calendar-view').val('default');
$('#providers .record-details #provider-timezone').val('UTC');
$('#providers .add-break, .add-working-plan-exception, #reset-working-plan').prop('disabled', true);
BackendProviders.wp.timepickers(true);
$('#providers .working-plan input:text').timepicker('destroy');
$('#providers .working-plan input:checkbox').prop('disabled', true);
$('.breaks').find('.edit-break, .delete-break').prop('disabled', true);
$('.working-plan-exceptions')
.find('.edit-working-plan-exception, .delete-working-plan-exception')
.prop('disabled', true);
$('#providers .record-details .is-invalid').removeClass('is-invalid');
$('#providers .record-details .form-message').hide();
$('#edit-provider, #delete-provider').prop('disabled', true);
$('#provider-services input:checkbox').prop('disabled', true).prop('checked', false);
$('#provider-services a').remove();
$('#providers .working-plan tbody').empty();
$('#providers .breaks tbody').empty();
$('#providers .working-plan-exceptions tbody').empty();
};
/**
* Display a provider record into the provider form.
*
* @param {Object} provider Contains the provider record data.
*/
ProvidersHelper.prototype.display = function (provider) {
$('#provider-id').val(provider.id);
$('#provider-first-name').val(provider.first_name);
$('#provider-last-name').val(provider.last_name);
$('#provider-email').val(provider.email);
$('#provider-mobile-number').val(provider.mobile_number);
$('#provider-phone-number').val(provider.phone_number);
$('#provider-address').val(provider.address);
$('#provider-city').val(provider.city);
$('#provider-state').val(provider.state);
$('#provider-zip-code').val(provider.zip_code);
$('#provider-notes').val(provider.notes);
$('#provider-timezone').val(provider.timezone);
$('#provider-username').val(provider.settings.username);
$('#provider-calendar-view').val(provider.settings.calendar_view);
$('#provider-notifications').prop('checked', Boolean(Number(provider.settings.notifications)));
// Add dedicated provider link.
var dedicatedUrl = GlobalVariables.baseUrl + '/index.php?provider=' + encodeURIComponent(provider.id);
var $link = $('<a/>', {
'href': dedicatedUrl,
'html': [
$('<span/>', {
'class': 'fas fa-link'
})
]
});
$('#providers .details-view h3').find('a').remove().end().append($link);
$('#provider-services a').remove();
$('#provider-services input:checkbox').prop('checked', false);
provider.services.forEach(function (providerServiceId) {
var $checkbox = $('#provider-services input[data-id="' + providerServiceId + '"]');
if (!$checkbox.length) {
return;
}
$checkbox.prop('checked', true);
// Add dedicated service-provider link.
dedicatedUrl =
GlobalVariables.baseUrl +
'/index.php?provider=' +
encodeURIComponent(provider.id) +
'&service=' +
encodeURIComponent(providerServiceId);
$link = $('<a/>', {
'href': dedicatedUrl,
'html': [
$('<span/>', {
'class': 'fas fa-link'
})
]
});
$checkbox.parent().append($link);
});
// Display working plan
var workingPlan = $.parseJSON(provider.settings.working_plan);
BackendProviders.wp.setup(workingPlan);
$('.working-plan').find('input').prop('disabled', true);
$('.breaks').find('.edit-break, .delete-break').prop('disabled', true);
$('#providers .working-plan-exceptions tbody').empty();
var workingPlanExceptions = $.parseJSON(provider.settings.working_plan_exceptions);
BackendProviders.wp.setupWorkingPlanExceptions(workingPlanExceptions);
$('.working-plan-exceptions')
.find('.edit-working-plan-exception, .delete-working-plan-exception')
.prop('disabled', true);
$('#providers .working-plan input:checkbox').prop('disabled', true);
Backend.placeFooterToBottom();
};
/**
* Filters provider records depending a string keyword.
*
* @param {string} keyword This is used to filter the provider records of the database.
* @param {numeric} selectId Optional, if set, when the function is complete a result row can be set as selected.
* @param {bool} display Optional (false), if true the selected record will be also displayed.
*/
ProvidersHelper.prototype.filter = function (keyword, selectId, display) {
display = display || false;
var url = GlobalVariables.baseUrl + '/index.php/providers/search';
var data = {
csrf_token: GlobalVariables.csrfToken,
keyword: keyword,
limit: this.filterLimit
};
$.post(url, data).done(
function (response) {
this.filterResults = response;
$('#filter-providers .results').empty();
response.forEach(
function (provider) {
$('#filter-providers .results').append(this.getFilterHtml(provider)).append($('<hr/>'));
}.bind(this)
);
if (!response.length) {
$('#filter-providers .results').append(
$('<em/>', {
'text': App.Lang.no_records_found
})
);
} else if (response.length === this.filterLimit) {
$('<button/>', {
'type': 'button',
'class': 'btn btn-outline-secondary w-100 load-more text-center',
'text': App.Lang.load_more,
'click': function () {
this.filterLimit += 20;
this.filter(keyword, selectId, display);
}.bind(this)
}).appendTo('#filter-providers .results');
}
if (selectId) {
this.select(selectId, display);
}
}.bind(this)
);
};
/**
* Get an provider row html code that is going to be displayed on the filter results list.
*
* @param {Object} provider Contains the provider record data.
*
* @return {String} The html code that represents the record on the filter results list.
*/
ProvidersHelper.prototype.getFilterHtml = function (provider) {
var name = provider.first_name + ' ' + provider.last_name;
var info = provider.email;
info = provider.mobile_number ? info + ', ' + provider.mobile_number : info;
info = provider.phone_number ? info + ', ' + provider.phone_number : info;
return $('<div/>', {
'class': 'provider-row entry',
'data-id': provider.id,
'html': [
$('<strong/>', {
'text': name
}),
$('<br/>'),
$('<span/>', {
'text': info
}),
$('<br/>')
]
});
};
/**
* Initialize the editable functionality to the break day table cells.
*
* @param {Object} $selector The cells to be initialized.
*/
ProvidersHelper.prototype.editableDayCell = function ($selector) {
var weekDays = {};
weekDays[App.Lang.monday] = 'Monday';
weekDays[App.Lang.tuesday] = 'Tuesday';
weekDays[App.Lang.wednesday] = 'Wednesday';
weekDays[App.Lang.thursday] = 'Thursday';
weekDays[App.Lang.friday] = 'Friday';
weekDays[App.Lang.saturday] = 'Saturday';
weekDays[App.Lang.sunday] = 'Sunday';
$selector.editable(
function (value, settings) {
return value;
},
{
type: 'select',
data: weekDays,
event: 'edit',
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 (settings, td) {
if (!BackendProviders.enableCancel) {
return false; // disable ESC button
}
},
onsubmit: function (settings, td) {
if (!BackendProviders.enableSubmit) {
return false; // disable Enter button
}
}
}
);
};
/**
* Initialize the editable functionality to the break time table cells.
*
* @param {jQuery} $selector The cells to be initialized.
*/
ProvidersHelper.prototype.editableTimeCell = function ($selector) {
$selector.editable(
function (value, settings) {
// Do not return the value because the user needs to press the "Save" button.
return value;
},
{
event: 'edit',
height: '25px',
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 (settings, td) {
if (!BackendProviders.enableCancel) {
return false; // disable ESC button
}
},
onsubmit: function (settings, td) {
if (!BackendProviders.enableSubmit) {
return false; // disable Enter button
}
}
}
);
};
/**
* Select and display a providers filter result on the form.
*
* @param {Number} id Record id to be selected.
* @param {Boolean} display Optional (false), if true the record will be displayed on the form.
*/
ProvidersHelper.prototype.select = function (id, display) {
display = display || false;
// Select record in filter results.
$('#filter-providers .provider-row[data-id="' + id + '"]').addClass('selected');
// Display record in form (if display = true).
if (display) {
var provider = this.filterResults.find(
function (filterResult) {
return Number(filterResult.id) === Number(id);
}.bind(this)
);
this.display(provider);
$('#edit-provider, #delete-provider').prop('disabled', false);
}
};
window.ProvidersHelper = ProvidersHelper;
})();

551
assets/js/pages/providers.js Executable file
View file

@ -0,0 +1,551 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Open Source Web 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.0.0
* ---------------------------------------------------------------------------- */
App.Pages.Providers = (function () {
const $providers = $('#providers');
let filterResults = {};
let filterLimit = 20;
let enableSubmit;
let enableCancel;
let workingPlanManager;
/**
* Bind the event handlers for the backend/users "Providers" tab.
*/
function bindEventHandlers() {
/**
* Event: Filter Providers Form "Submit"
*
* Filter the provider records with the given key string.
*
* @param {jQuery.Event} event
*/
$providers.on('submit', '#filter-providers form', function (event) {
event.preventDefault();
const key = $('#filter-providers .key').val();
$('.selected').removeClass('selected');
resetForm();
filter(key);
});
/**
* Event: Filter Provider Row "Click"
*
* Display the selected provider data to the user.
*/
$providers.on('click', '.provider-row', function (event) {
if ($('#filter-providers .filter').prop('disabled')) {
$('#filter-providers .results').css('color', '#AAA');
return; // Exit because we are currently on edit mode.
}
const providerId = $(event.currentTarget).attr('data-id');
const provider = filterResults.find(function (filterResult) {
return Number(filterResult.id) === Number(providerId);
});
display(provider);
$('#filter-providers .selected').removeClass('selected');
$(event.currentTarget).addClass('selected');
$('#edit-provider, #delete-provider').prop('disabled', false);
});
/**
* Event: Add New Provider Button "Click"
*/
$providers.on('click', '#add-provider', function () {
resetForm();
$('#filter-providers button').prop('disabled', true);
$('#filter-providers .results').css('color', '#AAA');
$('#providers .add-edit-delete-group').hide();
$('#providers .save-cancel-group').show();
$('#providers .record-details').find('input, select, textarea').prop('disabled', false);
$('#provider-password, #provider-password-confirm').addClass('required');
$providers
.find(
'.add-break, .edit-break, .delete-break, .add-working-plan-exception, .edit-working-plan-exception, .delete-working-plan-exception, #reset-working-plan'
)
.prop('disabled', false);
$('#provider-services input:checkbox').prop('disabled', false);
// Apply default working plan
const companyWorkingPlan = JSON.parse(App.Vars.company_working_plan);
workingPlanManager.setup(companyWorkingPlan);
workingPlanManager.timepickers(false);
});
/**
* Event: Edit Provider Button "Click"
*/
$providers.on('click', '#edit-provider', function () {
$('#providers .add-edit-delete-group').hide();
$('#providers .save-cancel-group').show();
$('#filter-providers button').prop('disabled', true);
$('#filter-providers .results').css('color', '#AAA');
$('#providers .record-details').find('input, select, textarea').prop('disabled', false);
$('#provider-password, #provider-password-confirm').removeClass('required');
$('#provider-services input:checkbox').prop('disabled', false);
$providers
.find(
'.add-break, .edit-break, .delete-break, .add-working-plan-exception, .edit-working-plan-exception, .delete-working-plan-exception, #reset-working-plan'
)
.prop('disabled', false);
$('#providers input:checkbox').prop('disabled', false);
workingPlanManager.timepickers(false);
});
/**
* Event: Delete Provider Button "Click"
*/
$providers.on('click', '#delete-provider', function () {
const providerId = $('#provider-id').val();
const buttons = [
{
text: App.Lang.cancel,
click: function () {
$('#message-box').dialog('close');
}
},
{
text: App.Lang.delete,
click: function () {
remove(providerId);
$('#message-box').dialog('close');
}
}
];
App.Utils.Message.show(App.Lang.delete_provider, App.Lang.delete_record_prompt, buttons);
});
/**
* Event: Save Provider Button "Click"
*/
$providers.on('click', '#save-provider', function () {
const provider = {
first_name: $('#provider-first-name').val(),
last_name: $('#provider-last-name').val(),
email: $('#provider-email').val(),
mobile_number: $('#provider-mobile-number').val(),
phone_number: $('#provider-phone-number').val(),
address: $('#provider-address').val(),
city: $('#provider-city').val(),
state: $('#provider-state').val(),
zip_code: $('#provider-zip-code').val(),
notes: $('#provider-notes').val(),
timezone: $('#provider-timezone').val(),
settings: {
username: $('#provider-username').val(),
working_plan: JSON.stringify(workingPlanManager.get()),
working_plan_exceptions: JSON.stringify(workingPlanManager.getWorkingPlanExceptions()),
notifications: Number($('#provider-notifications').prop('checked')),
calendar_view: $('#provider-calendar-view').val()
}
};
// Include provider services.
provider.services = [];
$('#provider-services input:checkbox').each(function (index, checkbox) {
if ($(checkbox).prop('checked')) {
provider.services.push($(checkbox).attr('data-id'));
}
});
// Include password if changed.
if ($('#provider-password').val() !== '') {
provider.settings.password = $('#provider-password').val();
}
// Include id if changed.
if ($('#provider-id').val() !== '') {
provider.id = $('#provider-id').val();
}
if (!validate()) {
return;
}
save(provider);
});
/**
* Event: Cancel Provider Button "Click"
*
* Cancel add or edit of an provider record.
*/
$providers.on('click', '#cancel-provider', function () {
const id = $('#filter-providers .selected').attr('data-id');
resetForm();
if (id) {
select(id, true);
}
});
/**
* Event: Display Provider Details "Click"
*/
$providers.on('shown.bs.tab', 'a[data-toggle="tab"]', function () {
Backend.placeFooterToBottom();
});
/**
* Event: Reset Working Plan Button "Click".
*/
$providers.on('click', '#reset-working-plan', function () {
$('.breaks tbody').empty();
$('.working-plan-exceptions tbody').empty();
$('.work-start, .work-end').val('');
const companyWorkingPlan = JSON.parse(App.Vars.company_working_plan);
workingPlanManager.setup(companyWorkingPlan);
workingPlanManager.timepickers(false);
});
}
/**
* Save provider record to database.
*
* @param {Object} provider Contains the provider record data. If an 'id' value is provided
* then the update operation is going to be executed.
*/
function save(provider) {
App.Http.Providers.save(provider).then((response) => {
Backend.displayNotification(App.Lang.provider_saved);
resetForm();
$('#filter-providers .key').val('');
filter('', response.id, true);
});
}
/**
* Delete a provider record from database.
*
* @param {Number} id Record id to be deleted.
*/
function remove(id) {
App.Http.Providers.destroy(id).then(() => {
Backend.displayNotification(App.Lang.provider_deleted);
resetForm();
filter($('#filter-providers .key').val());
});
}
/**
* Validates a provider record.
*
* @return {Boolean} Returns the validation result.
*/
function validate() {
$('#providers .is-invalid').removeClass('is-invalid');
$('#providers .form-message').removeClass('alert-danger').hide();
try {
// Validate required fields.
let missingRequired = false;
$('#providers .required').each(function (index, requiredField) {
if (!$(requiredField).val()) {
$(requiredField).addClass('is-invalid');
missingRequired = true;
}
});
if (missingRequired) {
throw new Error(App.Lang.fields_are_required);
}
// Validate passwords.
if ($('#provider-password').val() !== $('#provider-password-confirm').val()) {
$('#provider-password, #provider-password-confirm').addClass('is-invalid');
throw new Error(App.Lang.passwords_mismatch);
}
if (
$('#provider-password').val().length < App.Vars.min_password_length &&
$('#provider-password').val() !== ''
) {
$('#provider-password, #provider-password-confirm').addClass('is-invalid');
throw new Error(App.Lang.password_length_notice.replace('$number', MIN_PASSWORD_LENGTH));
}
// Validate user email.
if (!App.Utils.Validation.email($('#provider-email').val())) {
$('#provider-email').addClass('is-invalid');
throw new Error(App.Lang.invalid_email);
}
// Check if username exists
if ($('#provider-username').attr('already-exists') === 'true') {
$('#provider-username').addClass('is-invalid');
throw new Error(App.Lang.username_already_exists);
}
return true;
} catch (error) {
$('#providers .form-message').addClass('alert-danger').text(error.message).show();
return false;
}
}
/**
* Resets the provider tab form back to its initial state.
*/
function resetForm() {
$('#filter-providers .selected').removeClass('selected');
$('#filter-providers button').prop('disabled', false);
$('#filter-providers .results').css('color', '');
$('#providers .add-edit-delete-group').show();
$('#providers .save-cancel-group').hide();
$('#providers .record-details h3 a').remove();
$('#providers .record-details').find('input, select, textarea').val('').prop('disabled', true);
$('#providers .record-details #provider-calendar-view').val('default');
$('#providers .record-details #provider-timezone').val('UTC');
$('#providers .add-break, .add-working-plan-exception, #reset-working-plan').prop('disabled', true);
workingPlanManager.timepickers(true);
$('#providers .working-plan input:text').timepicker('destroy');
$('#providers .working-plan input:checkbox').prop('disabled', true);
$('.breaks').find('.edit-break, .delete-break').prop('disabled', true);
$('.working-plan-exceptions')
.find('.edit-working-plan-exception, .delete-working-plan-exception')
.prop('disabled', true);
$('#providers .record-details .is-invalid').removeClass('is-invalid');
$('#providers .record-details .form-message').hide();
$('#edit-provider, #delete-provider').prop('disabled', true);
$('#provider-services input:checkbox').prop('disabled', true).prop('checked', false);
$('#provider-services a').remove();
$('#providers .working-plan tbody').empty();
$('#providers .breaks tbody').empty();
$('#providers .working-plan-exceptions tbody').empty();
}
/**
* Display a provider record into the provider form.
*
* @param {Object} provider Contains the provider record data.
*/
function display(provider) {
$('#provider-id').val(provider.id);
$('#provider-first-name').val(provider.first_name);
$('#provider-last-name').val(provider.last_name);
$('#provider-email').val(provider.email);
$('#provider-mobile-number').val(provider.mobile_number);
$('#provider-phone-number').val(provider.phone_number);
$('#provider-address').val(provider.address);
$('#provider-city').val(provider.city);
$('#provider-state').val(provider.state);
$('#provider-zip-code').val(provider.zip_code);
$('#provider-notes').val(provider.notes);
$('#provider-timezone').val(provider.timezone);
$('#provider-username').val(provider.settings.username);
$('#provider-calendar-view').val(provider.settings.calendar_view);
$('#provider-notifications').prop('checked', Boolean(Number(provider.settings.notifications)));
// Add dedicated provider link.
let dedicatedUrl = App.Utils.Url.siteUrl('?provider=' + encodeURIComponent(provider.id));
let $link = $('<a/>', {
'href': dedicatedUrl,
'html': [
$('<span/>', {
'class': 'fas fa-link'
})
]
});
$('#providers .details-view h3').find('a').remove().end().append($link);
$('#provider-services a').remove();
$('#provider-services input:checkbox').prop('checked', false);
provider.services.forEach(function (providerServiceId) {
const $checkbox = $('#provider-services input[data-id="' + providerServiceId + '"]');
if (!$checkbox.length) {
return;
}
$checkbox.prop('checked', true);
// Add dedicated service-provider link.
dedicatedUrl = App.Utils.Url.siteUrl(
'?provider=' + encodeURIComponent(provider.id) + '&service=' + encodeURIComponent(providerServiceId)
);
$link = $('<a/>', {
'href': dedicatedUrl,
'html': [
$('<span/>', {
'class': 'fas fa-link'
})
]
});
$checkbox.parent().append($link);
});
// Display working plan
const workingPlan = JSON.parse(provider.settings.working_plan);
workingPlanManager.setup(workingPlan);
$('.working-plan').find('input').prop('disabled', true);
$('.breaks').find('.edit-break, .delete-break').prop('disabled', true);
$('#providers .working-plan-exceptions tbody').empty();
const workingPlanExceptions = JSON.parse(provider.settings.working_plan_exceptions);
workingPlanManager.setupWorkingPlanExceptions(workingPlanExceptions);
$('.working-plan-exceptions')
.find('.edit-working-plan-exception, .delete-working-plan-exception')
.prop('disabled', true);
$('#providers .working-plan input:checkbox').prop('disabled', true);
Backend.placeFooterToBottom();
}
/**
* Filters provider records depending a string keyword.
*
* @param {string} keyword This is used to filter the provider records of the database.
* @param {numeric} selectId Optional, if set, when the function is complete a result row can be set as selected.
* @param {bool} show Optional (false), if true the selected record will be also displayed.
*/
function filter(keyword, selectId = null, show = false) {
App.Http.Providers.search(keyword, filterLimit).then((response) => {
filterResults = response;
$('#filter-providers .results').empty();
response.forEach(function (provider) {
$('#filter-providers .results').append(getFilterHtml(provider)).append($('<hr/>'));
});
if (!response.length) {
$('#filter-providers .results').append(
$('<em/>', {
'text': App.Lang.no_records_found
})
);
} else if (response.length === filterLimit) {
$('<button/>', {
'type': 'button',
'class': 'btn btn-outline-secondary w-100 load-more text-center',
'text': App.Lang.load_more,
'click': function () {
filterLimit += 20;
filter(keyword, selectId, show);
}
}).appendTo('#filter-providers .results');
}
if (selectId) {
select(selectId, show);
}
});
}
/**
* Get an provider row html code that is going to be displayed on the filter results list.
*
* @param {Object} provider Contains the provider record data.
*
* @return {String} The html code that represents the record on the filter results list.
*/
function getFilterHtml(provider) {
const name = provider.first_name + ' ' + provider.last_name;
let info = provider.email;
info = provider.mobile_number ? info + ', ' + provider.mobile_number : info;
info = provider.phone_number ? info + ', ' + provider.phone_number : info;
return $('<div/>', {
'class': 'provider-row entry',
'data-id': provider.id,
'html': [
$('<strong/>', {
'text': name
}),
$('<br/>'),
$('<span/>', {
'text': info
}),
$('<br/>')
]
});
}
/**
* Select and display a providers filter result on the form.
*
* @param {Number} id Record id to be selected.
* @param {Boolean} show Optional (false), if true the record will be displayed on the form.
*/
function select(id, show = false) {
// Select record in filter results.
$('#filter-providers .provider-row[data-id="' + id + '"]').addClass('selected');
// Display record in form (if display = true).
if (show) {
const provider = filterResults.find(function (filterResult) {
return Number(filterResult.id) === Number(id);
});
display(provider);
$('#edit-provider, #delete-provider').prop('disabled', false);
}
}
function init() {
workingPlanManager = new App.Utils.WorkingPlan();
workingPlanManager.bindEventHandlers();
resetForm();
filter('');
bindEventHandlers();
App.Vars.services.forEach(function (service) {
$('<div/>', {
'class': 'checkbox',
'html': [
$('<div/>', {
'class': 'checkbox form-check',
'html': [
$('<input/>', {
'class': 'form-check-input',
'type': 'checkbox',
'data-id': service.id,
'prop': {
'disabled': true
}
}),
$('<label/>', {
'class': 'form-check-label',
'text': service.name,
'for': service.id
})
]
})
]
}).appendTo('#provider-services');
});
}
document.addEventListener('DOMContentLoaded', init);
return {
filter,
save,
remove,
getFilterHtml,
resetForm,
select
};
})();