Refactored the customers helper JS file so that it becomes a standalone module.

This commit is contained in:
Alex Tselegidis 2022-01-06 09:53:16 +01:00
parent def2668ede
commit 00c3aebef0

View file

@ -6,52 +6,45 @@
* @copyright Copyright (c) Alex Tselegidis * @copyright Copyright (c) Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3 * @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org * @link https://easyappointments.org
* @since v1.0.0 * @since v1.5.0
* ---------------------------------------------------------------------------- */ * ---------------------------------------------------------------------------- */
(function () { /**
'use strict'; * Customers page module.
/**
* CustomersHelper Class
* *
* This class contains the methods that are used in the backend customers page. * This class contains the methods that are used in the backend customers page.
*
* @class CustomersHelper
*/ */
function CustomersHelper() { App.Pages.Customers = (function () {
this.filterResults = {}; const $customers = $('#customers');
this.filterLimit = 20; let filterResults = {};
} let filterLimit = 20;
/** /**
* Binds the default event handlers of the backend customers page. * Binds the default event handlers of the backend customers page.
*/ */
CustomersHelper.prototype.bindEventHandlers = function () { function bindEventHandlers() {
var instance = this;
/** /**
* Event: Filter Customers Form "Submit" * Event: Filter Customers Form "Submit"
* *
* @param {jQuery.Event} event * @param {jQuery.Event} event
*/ */
$('#customers').on('submit', '#filter-customers form', function (event) { $customers.on('submit', '#filter-customers form', function (event) {
event.preventDefault(); event.preventDefault();
var key = $('#filter-customers .key').val(); const key = $('#filter-customers .key').val();
$('#filter-customers .selected').removeClass('selected'); $('#filter-customers .selected').removeClass('selected');
instance.filterLimit = 20; filterLimit = 20;
instance.resetForm(); resetForm();
instance.filter(key); filter(key);
}); });
/** /**
* Event: Filter Customers Clear Button "Click" * Event: Filter Customers Clear Button "Click"
*/ */
$('#customers').on('click', '#filter-customers .clear', function () { $customers.on('click', '#filter-customers .clear', function () {
$('#filter-customers .key').val(''); $('#filter-customers .key').val('');
instance.filterLimit = 20; filterLimit = 20;
instance.filter(''); filter('');
instance.resetForm(); resetForm();
}); });
/** /**
@ -59,17 +52,17 @@
* *
* Display the customer data of the selected row. * Display the customer data of the selected row.
*/ */
$('#customers').on('click', '.customer-row', function () { $customers.on('click', '.customer-row', function () {
if ($('#filter-customers .filter').prop('disabled')) { if ($('#filter-customers .filter').prop('disabled')) {
return; // Do nothing when user edits a customer record. return; // Do nothing when user edits a customer record.
} }
var customerId = $(this).attr('data-id'); var customerId = $(this).attr('data-id');
var customer = instance.filterResults.find(function (filterResult) { var customer = filterResults.find(function (filterResult) {
return Number(filterResult.id) === Number(customerId); return Number(filterResult.id) === Number(customerId);
}); });
instance.display(customer); display(customer);
$('#filter-customers .selected').removeClass('selected'); $('#filter-customers .selected').removeClass('selected');
$(this).addClass('selected'); $(this).addClass('selected');
$('#edit-customer, #delete-customer').prop('disabled', false); $('#edit-customer, #delete-customer').prop('disabled', false);
@ -78,8 +71,8 @@
/** /**
* Event: Add Customer Button "Click" * Event: Add Customer Button "Click"
*/ */
$('#customers').on('click', '#add-customer', function () { $customers.on('click', '#add-customer', function () {
instance.resetForm(); resetForm();
$('#add-edit-delete-group').hide(); $('#add-edit-delete-group').hide();
$('#save-cancel-group').show(); $('#save-cancel-group').show();
$('.record-details').find('input, select, textarea').prop('disabled', false); $('.record-details').find('input, select, textarea').prop('disabled', false);
@ -90,7 +83,7 @@
/** /**
* Event: Edit Customer Button "Click" * Event: Edit Customer Button "Click"
*/ */
$('#customers').on('click', '#edit-customer', function () { $customers.on('click', '#edit-customer', function () {
$('.record-details').find('input, select, textarea').prop('disabled', false); $('.record-details').find('input, select, textarea').prop('disabled', false);
$('#add-edit-delete-group').hide(); $('#add-edit-delete-group').hide();
$('#save-cancel-group').show(); $('#save-cancel-group').show();
@ -101,18 +94,18 @@
/** /**
* Event: Cancel Customer Add/Edit Operation Button "Click" * Event: Cancel Customer Add/Edit Operation Button "Click"
*/ */
$('#customers').on('click', '#cancel-customer', function () { $customers.on('click', '#cancel-customer', function () {
var id = $('#customer-id').val(); var id = $('#customer-id').val();
instance.resetForm(); resetForm();
if (id) { if (id) {
instance.select(id, true); select(id, true);
} }
}); });
/** /**
* Event: Save Add/Edit Customer Operation "Click" * Event: Save Add/Edit Customer Operation "Click"
*/ */
$('#customers').on('click', '#save-customer', function () { $customers.on('click', '#save-customer', function () {
var customer = { var customer = {
first_name: $('#first-name').val(), first_name: $('#first-name').val(),
last_name: $('#last-name').val(), last_name: $('#last-name').val(),
@ -130,17 +123,17 @@
customer.id = $('#customer-id').val(); customer.id = $('#customer-id').val();
} }
if (!instance.validate()) { if (!validate()) {
return; return;
} }
instance.save(customer); save(customer);
}); });
/** /**
* Event: Delete Customer Button "Click" * Event: Delete Customer Button "Click"
*/ */
$('#customers').on('click', '#delete-customer', function () { $customers.on('click', '#delete-customer', function () {
var customerId = $('#customer-id').val(); var customerId = $('#customer-id').val();
var buttons = [ var buttons = [
{ {
@ -152,65 +145,47 @@
{ {
text: App.Lang.delete, text: App.Lang.delete,
click: function () { click: function () {
instance.delete(customerId); remove(customerId);
$('#message-box').dialog('close'); $('#message-box').dialog('close');
} }
} }
]; ];
GeneralFunctions.displayMessageBox(App.Lang.delete_customer, App.Lang.delete_record_prompt, buttons); App.Utils.Message.show(App.Lang.delete_customer, App.Lang.delete_record_prompt, buttons);
}); });
}; }
/** /**
* Save a customer record to the database (via ajax post). * Save a customer record to the database (via ajax post).
* *
* @param {Object} customer Contains the customer data. * @param {Object} customer Contains the customer data.
*/ */
CustomersHelper.prototype.save = function (customer) { function save(customer) {
var url = GlobalVariables.baseUrl + '/index.php/customers/' + (customer.id ? 'update' : 'create'); App.Http.Customers.save(customer).then((response) => {
var data = {
csrf_token: GlobalVariables.csrfToken,
customer: JSON.stringify(customer)
};
$.post(url, data).done(
function (response) {
Backend.displayNotification(App.Lang.customer_saved); Backend.displayNotification(App.Lang.customer_saved);
this.resetForm(); resetForm();
$('#filter-customers .key').val(''); $('#filter-customers .key').val('');
this.filter('', response.id, true); filter('', response.id, true);
}.bind(this) });
); }
};
/** /**
* Delete a customer record from database. * Delete a customer record from database.
* *
* @param {Number} id Record id to be deleted. * @param {Number} id Record id to be deleted.
*/ */
CustomersHelper.prototype.delete = function (id) { function remove(id) {
var url = GlobalVariables.baseUrl + '/index.php/customers/destroy'; App.Http.Customers.destroy(id).then(() => {
var data = {
csrf_token: GlobalVariables.csrfToken,
customer_id: id
};
$.post(url, data).done(
function () {
Backend.displayNotification(App.Lang.customer_deleted); Backend.displayNotification(App.Lang.customer_deleted);
this.resetForm(); resetForm();
this.filter($('#filter-customers .key').val()); filter($('#filter-customers .key').val());
}.bind(this) });
); }
};
/** /**
* Validate customer data before save (insert or update). * Validate customer data before save (insert or update).
*/ */
CustomersHelper.prototype.validate = function () { function validate() {
$('#form-message').removeClass('alert-danger').hide(); $('#form-message').removeClass('alert-danger').hide();
$('.is-invalid').removeClass('is-invalid'); $('.is-invalid').removeClass('is-invalid');
@ -240,12 +215,12 @@
$('#form-message').addClass('alert-danger').text(error.message).show(); $('#form-message').addClass('alert-danger').text(error.message).show();
return false; return false;
} }
}; }
/** /**
* Bring the customer form back to its initial state. * Bring the customer form back to its initial state.
*/ */
CustomersHelper.prototype.resetForm = function () { function resetForm() {
$('.record-details').find('input, select, textarea').val('').prop('disabled', true); $('.record-details').find('input, select, textarea').val('').prop('disabled', true);
$('.record-details #timezone').val('UTC'); $('.record-details #timezone').val('UTC');
@ -262,14 +237,14 @@
$('#filter-customers button').prop('disabled', false); $('#filter-customers button').prop('disabled', false);
$('#filter-customers .selected').removeClass('selected'); $('#filter-customers .selected').removeClass('selected');
$('#filter-customers .results').css('color', ''); $('#filter-customers .results').css('color', '');
}; }
/** /**
* Display a customer record into the form. * Display a customer record into the form.
* *
* @param {Object} customer Contains the customer record data. * @param {Object} customer Contains the customer record data.
*/ */
CustomersHelper.prototype.display = function (customer) { function display(customer) {
$('#customer-id').val(customer.id); $('#customer-id').val(customer.id);
$('#first-name').val(customer.first_name); $('#first-name').val(customer.first_name);
$('#last-name').val(customer.last_name); $('#last-name').val(customer.last_name);
@ -292,27 +267,27 @@
customer.appointments.forEach(function (appointment) { customer.appointments.forEach(function (appointment) {
if ( if (
GlobalVariables.user.role_slug === Backend.DB_SLUG_PROVIDER && App.Vars.role_slug === Backend.DB_SLUG_PROVIDER &&
parseInt(appointment.id_users_provider) !== GlobalVariables.user.id parseInt(appointment.id_users_provider) !== App.Vars.user_id
) { ) {
return; return;
} }
if ( if (
GlobalVariables.user.role_slug === Backend.DB_SLUG_SECRETARY && App.Vars.role_slug === Backend.DB_SLUG_SECRETARY &&
GlobalVariables.secretaryProviders.indexOf(appointment.id_users_provider) === -1 App.Vars.secretary_providers.indexOf(appointment.id_users_provider) === -1
) { ) {
return; return;
} }
var start = GeneralFunctions.formatDate( var start = GeneralFunctions.formatDate(
moment(appointment.start_datetime).toDate(), moment(appointment.start_datetime).toDate(),
GlobalVariables.dateFormat, App.Vars.date_format,
true true
); );
var end = GeneralFunctions.formatDate( var end = GeneralFunctions.formatDate(
moment(appointment.end_datetime).toDate(), moment(appointment.end_datetime).toDate(),
GlobalVariables.dateFormat, App.Vars.date_format,
true true
); );
@ -323,7 +298,7 @@
// Service - Provider // Service - Provider
$('<a/>', { $('<a/>', {
'href': GlobalVariables.baseUrl + '/index.php/backend/index/' + appointment.hash, 'href': App.Utils.Url.siteUrl(`backend/index/${appointment.hash}`),
'html': [ 'html': [
$('<i/>', { $('<i/>', {
'class': 'fas fa-edit me-1' 'class': 'fas fa-edit me-1'
@ -357,12 +332,12 @@
// Timezone // Timezone
$('<small/>', { $('<small/>', {
'text': GlobalVariables.timezones[appointment.provider.timezone] 'text': App.Vars.timezones[appointment.provider.timezone]
}) })
] ]
}).appendTo('#customer-appointments'); }).appendTo('#customer-appointments');
}); });
}; }
/** /**
* Filter customer records. * Filter customer records.
@ -372,26 +347,15 @@
* ID will be selected (but not displayed). * ID will be selected (but not displayed).
* @param {Boolean} display Optional (false), if true then the selected record will be displayed on the form. * @param {Boolean} display Optional (false), if true then the selected record will be displayed on the form.
*/ */
CustomersHelper.prototype.filter = function (keyword, selectId, display) { function filter(keyword, selectId = null, display = false) {
display = display || false; App.Http.Customers.search(keyword, filterLimit).then((response) => {
filterResults = response;
var url = GlobalVariables.baseUrl + '/index.php/customers/search';
var data = {
csrf_token: GlobalVariables.csrfToken,
keyword: keyword,
limit: this.filterLimit
};
$.post(url, data).done(
function (response) {
this.filterResults = response;
$('#filter-customers .results').empty(); $('#filter-customers .results').empty();
response.forEach( response.forEach(
function (customer) { function (customer) {
$('#filter-customers .results').append(this.getFilterHtml(customer)).append($('<hr/>')); $('#filter-customers .results').append(getFilterHtml(customer)).append($('<hr/>'));
}.bind(this) }.bind(this)
); );
@ -401,24 +365,23 @@
'text': App.Lang.no_records_found 'text': App.Lang.no_records_found
}) })
); );
} else if (response.length === this.filterLimit) { } else if (response.length === filterLimit) {
$('<button/>', { $('<button/>', {
'type': 'button', 'type': 'button',
'class': 'btn btn-outline-secondary w-100 load-more text-center', 'class': 'btn btn-outline-secondary w-100 load-more text-center',
'text': App.Lang.load_more, 'text': App.Lang.load_more,
'click': function () { 'click': function () {
this.filterLimit += 20; filterLimit += 20;
this.filter(keyword, selectId, display); filter(keyword, selectId, display);
}.bind(this) }.bind(this)
}).appendTo('#filter-customers .results'); }).appendTo('#filter-customers .results');
} }
if (selectId) { if (selectId) {
this.select(selectId, display); select(selectId, display);
}
});
} }
}.bind(this)
);
};
/** /**
* Get the filter results row HTML code. * Get the filter results row HTML code.
@ -427,7 +390,7 @@
* *
* @return {String} Returns the record HTML code. * @return {String} Returns the record HTML code.
*/ */
CustomersHelper.prototype.getFilterHtml = function (customer) { function getFilterHtml(customer) {
var name = customer.first_name + ' ' + customer.last_name; var name = customer.first_name + ' ' + customer.last_name;
var info = customer.email; var info = customer.email;
@ -448,7 +411,7 @@
$('<br/>') $('<br/>')
] ]
}); });
}; }
/** /**
* Select a specific record from the current filter results. * Select a specific record from the current filter results.
@ -456,26 +419,39 @@
* If the customer id does not exist in the list then no record will be selected. * If the customer id does not exist in the list then no record will be selected.
* *
* @param {Number} id The record id to be selected from the filter results. * @param {Number} id The record id to be selected from the filter results.
* @param {Boolean} display Optional (false), if true then the method will display the record * @param {Boolean} show Optional (false), if true then the method will display the record
* on the form. * on the form.
*/ */
CustomersHelper.prototype.select = function (id, display) { function select(id, show = false) {
display = display || false;
$('#filter-customers .selected').removeClass('selected'); $('#filter-customers .selected').removeClass('selected');
$('#filter-customers .entry[data-id="' + id + '"]').addClass('selected'); $('#filter-customers .entry[data-id="' + id + '"]').addClass('selected');
if (display) { if (show) {
var customer = this.filterResults.find(function (filterResult) { const customer = filterResults.find(function (filterResult) {
return Number(filterResult.id) === Number(id); return Number(filterResult.id) === Number(id);
}); });
this.display(customer); display(customer);
$('#edit-customer, #delete-customer').prop('disabled', false); $('#edit-customer, #delete-customer').prop('disabled', false);
} }
}; }
window.CustomersHelper = CustomersHelper; function init() {
resetForm();
bindEventHandlers();
filter('');
}
document.addEventListener('DOMContentLoaded', init);
return {
filter,
save,
remove,
getFilterHtml,
resetForm,
select
};
})(); })();