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

This commit is contained in:
Alex Tselegidis 2022-01-10 09:26:28 +01:00
parent 195680e8b3
commit e2bffc5e95
5 changed files with 138 additions and 229 deletions

View file

@ -52,6 +52,11 @@ class Categories extends EA_Controller {
$role_slug = session('role_slug'); $role_slug = session('role_slug');
script_vars([
'user_id' => $user_id,
'role_slug' => $role_slug,
]);
html_vars([ html_vars([
'page_title' => lang('categories'), 'page_title' => lang('categories'),
'active_menu' => PRIV_SERVICES, 'active_menu' => PRIV_SERVICES,
@ -100,7 +105,7 @@ class Categories extends EA_Controller {
{ {
try try
{ {
$category = json_decode(request('category'), TRUE); $category = request('category');
if (cannot('add', PRIV_SERVICES)) if (cannot('add', PRIV_SERVICES))
{ {
@ -127,7 +132,7 @@ class Categories extends EA_Controller {
{ {
try try
{ {
$category = json_decode(request('category'), TRUE); $category = request('category');
if (cannot('edit', PRIV_SERVICES)) if (cannot('edit', PRIV_SERVICES))
{ {

View file

@ -87,27 +87,10 @@
<?php section('scripts') ?> <?php section('scripts') ?>
<script src="<?= asset_url('assets/js/pages/backend_categories_helper.js') ?>"></script> <script src="<?= asset_url('assets/js/utils/message.js') ?>"></script>
<script src="<?= asset_url('assets/js/pages/backend_categories.js') ?>"></script> <script src="<?= asset_url('assets/js/utils/validation.js') ?>"></script>
<script> <script src="<?= asset_url('assets/js/utils/url.js') ?>"></script>
var GlobalVariables = { <script src="<?= asset_url('assets/js/http/categories_http_client.js') ?>"></script>
csrfToken: <?= json_encode($this->security->get_csrf_hash()) ?>, <script src="<?= asset_url('assets/js/pages/categories.js') ?>"></script>
baseUrl: <?= json_encode(config('base_url')) ?>,
dateFormat: <?= json_encode(setting('date_format')) ?>,
timeFormat: <?= json_encode(setting('time_format')) ?>,
timezones: <?= json_encode($timezones) ?>,
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) ?>
}
};
$(function () {
BackendCategories.initialize(true);
});
</script>
<?php section('scripts') ?> <?php section('scripts') ?>

View file

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

View file

@ -1,62 +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.BackendCategories = window.BackendCategories || {};
/**
* Backend Categories
*
* This namespace handles the js functionality of the backend categories page.
*
* @module BackendCategories
*/
(function (exports) {
'use strict';
/**
* Contains the basic record methods for the page.
*
* @type {CategoriesHelper}
*/
var helper;
var categoriesHelper = new CategoriesHelper();
/**
* Default initialize method of the page.
*
* @param {Boolean} [defaultEventHandlers] Optional (true), determines whether to bind the default event handlers.
*/
exports.initialize = function (defaultEventHandlers) {
defaultEventHandlers = defaultEventHandlers || true;
// Instantiate helper object (category helper by default).
helper = categoriesHelper;
helper.resetForm();
helper.filter('');
helper.bindEventHandlers();
if (defaultEventHandlers) {
bindEventHandlers();
}
Backend.placeFooterToBottom();
};
/**
* Binds the default event handlers of the backend categories page.
*
* Do not use this method if you include the "BackendCategories" namespace on another page.
*/
function bindEventHandlers() {
//
}
})(window.BackendCategories);

View file

@ -9,39 +9,26 @@
* @since v1.0.0 * @since v1.0.0
* ---------------------------------------------------------------------------- */ * ---------------------------------------------------------------------------- */
(function () { App.Pages.Categories = (function () {
'use strict'; const $categories = $('#categories');
let filterResults = {};
/** let filterLimit = 20;
* CategoriesHelper Class
*
* This class contains the core method implementations that belong to the categories tab
* of the backend services page.
*
* @class CategoriesHelper
*/
function CategoriesHelper() {
this.filterResults = {};
this.filterLimit = 20;
}
/** /**
* Binds the default event handlers of the categories tab. * Binds the default event handlers of the categories tab.
*/ */
CategoriesHelper.prototype.bindEventHandlers = function () { function bindEventHandlers() {
var instance = this;
/** /**
* Event: Filter Categories Form "Submit" * Event: Filter Categories Form "Submit"
* *
* @param {jQuery.Event} event * @param {jQuery.Event} event
*/ */
$('#categories').on('submit', '#filter-categories form', function (event) { $categories.on('submit', '#filter-categories form', function (event) {
event.preventDefault(); event.preventDefault();
var key = $('#filter-categories .key').val(); const key = $('#filter-categories .key').val();
$('.selected').removeClass('selected'); $('.selected').removeClass('selected');
instance.resetForm(); resetForm();
instance.filter(key); filter(key);
}); });
/** /**
@ -49,19 +36,19 @@
* *
* Displays the selected row data on the right side of the page. * Displays the selected row data on the right side of the page.
*/ */
$('#categories').on('click', '.category-row', function () { $categories.on('click', '.category-row', function () {
if ($('#filter-categories .filter').prop('disabled')) { if ($('#filter-categories .filter').prop('disabled')) {
$('#filter-categories .results').css('color', '#AAA'); $('#filter-categories .results').css('color', '#AAA');
return; // exit because we are on edit mode return; // exit because we are on edit mode
} }
var categoryId = $(this).attr('data-id'); const categoryId = $(this).attr('data-id');
var category = instance.filterResults.find(function (filterResult) { const category = filterResults.find(function (filterResult) {
return Number(filterResult.id) === Number(categoryId); return Number(filterResult.id) === Number(categoryId);
}); });
instance.display(category); display(category);
$('#filter-categories .selected').removeClass('selected'); $('#filter-categories .selected').removeClass('selected');
$(this).addClass('selected'); $(this).addClass('selected');
$('#edit-category, #delete-category').prop('disabled', false); $('#edit-category, #delete-category').prop('disabled', false);
@ -70,8 +57,8 @@
/** /**
* Event: Add Category Button "Click" * Event: Add Category Button "Click"
*/ */
$('#categories').on('click', '#add-category', function () { $categories.on('click', '#add-category', function () {
instance.resetForm(); resetForm();
$('#categories .add-edit-delete-group').hide(); $('#categories .add-edit-delete-group').hide();
$('#categories .save-cancel-group').show(); $('#categories .save-cancel-group').show();
$('#categories .record-details').find('input, select, textarea').prop('disabled', false); $('#categories .record-details').find('input, select, textarea').prop('disabled', false);
@ -82,7 +69,7 @@
/** /**
* Event: Edit Category Button "Click" * Event: Edit Category Button "Click"
*/ */
$('#categories').on('click', '#edit-category', function () { $categories.on('click', '#edit-category', function () {
$('#categories .add-edit-delete-group').hide(); $('#categories .add-edit-delete-group').hide();
$('#categories .save-cancel-group').show(); $('#categories .save-cancel-group').show();
$('#categories .record-details').find('input, select, textarea').prop('disabled', false); $('#categories .record-details').find('input, select, textarea').prop('disabled', false);
@ -93,10 +80,10 @@
/** /**
* Event: Delete Category Button "Click" * Event: Delete Category Button "Click"
*/ */
$('#categories').on('click', '#delete-category', function () { $categories.on('click', '#delete-category', function () {
var categoryId = $('#category-id').val(); const categoryId = $('#category-id').val();
var buttons = [ const buttons = [
{ {
text: App.Lang.cancel, text: App.Lang.cancel,
click: function () { click: function () {
@ -106,20 +93,20 @@
{ {
text: App.Lang.delete, text: App.Lang.delete,
click: function () { click: function () {
instance.delete(categoryId); remove(categoryId);
$('#message-box').dialog('close'); $('#message-box').dialog('close');
} }
} }
]; ];
GeneralFunctions.displayMessageBox(App.Lang.delete_category, App.Lang.delete_record_prompt, buttons); App.Utils.Message.show(App.Lang.delete_category, App.Lang.delete_record_prompt, buttons);
}); });
/** /**
* Event: Categories Save Button "Click" * Event: Categories Save Button "Click"
*/ */
$('#categories').on('click', '#save-category', function () { $categories.on('click', '#save-category', function () {
var category = { const category = {
name: $('#category-name').val(), name: $('#category-name').val(),
description: $('#category-description').val() description: $('#category-description').val()
}; };
@ -128,30 +115,30 @@
category.id = $('#category-id').val(); category.id = $('#category-id').val();
} }
if (!instance.validate()) { if (!validate()) {
return; return;
} }
instance.save(category); save(category);
}); });
/** /**
* Event: Cancel Category Button "Click" * Event: Cancel Category Button "Click"
*/ */
$('#categories').on('click', '#cancel-category', function () { $categories.on('click', '#cancel-category', function () {
var id = $('#category-id').val(); const id = $('#category-id').val();
instance.resetForm(); resetForm();
if (id !== '') { if (id !== '') {
instance.select(id, true); select(id, true);
} }
}); });
}; }
/** /**
* Remove the previously registered event handlers. * Remove the previously registered event handlers.
*/ */
CategoriesHelper.prototype.unbindEventHandlers = function () { function unbindEventHandlers() {
$('#categories') $categories
.off('click', '#filter-categories .clear') .off('click', '#filter-categories .clear')
.off('submit', '#filter-categories form') .off('submit', '#filter-categories form')
.off('click', '.category-row') .off('click', '.category-row')
@ -160,7 +147,7 @@
.off('click', '#delete-category') .off('click', '#delete-category')
.off('click', '#save-category') .off('click', '#save-category')
.off('click', '#cancel-category'); .off('click', '#cancel-category');
}; }
/** /**
* Filter service categories records. * Filter service categories records.
@ -168,122 +155,93 @@
* @param {String} keyword This key string is used to filter the category records. * @param {String} keyword This key string is used to filter the category records.
* @param {Number} selectId Optional, if set then after the filter operation the record with the given * @param {Number} selectId Optional, if set then after the filter operation the record with the given
* 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} show Optional (false), if true then the selected record will be displayed on the form.
*/ */
CategoriesHelper.prototype.filter = function (keyword, selectId, display) { function filter(keyword, selectId = null, show = false) {
var url = GlobalVariables.baseUrl + '/index.php/categories/search'; App.Http.Categories.search(keyword, filterLimit).then((response) => {
filterResults = response;
var data = { $('#filter-categories .results').empty();
csrf_token: GlobalVariables.csrfToken,
keyword: keyword,
limit: this.filterLimit
};
$.post(url, data).done( response.forEach(
function (response) { function (category) {
this.filterResults = response; $('#filter-categories .results').append(getFilterHtml(category)).append($('<hr/>'));
}.bind(this)
);
$('#filter-categories .results').empty(); if (response.length === 0) {
$('#filter-categories .results').append(
response.forEach( $('<em/>', {
function (category) { 'text': App.Lang.no_records_found
$('#filter-categories .results').append(this.getFilterHtml(category)).append($('<hr/>')); })
}.bind(this)
); );
} 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);
}.bind(this)
}).appendTo('#filter-categories .results');
}
if (response.length === 0) { if (selectId) {
$('#filter-categories .results').append( select(selectId, show);
$('<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-categories .results');
}
if (selectId) {
this.select(selectId, display);
}
}.bind(this)
);
};
/** /**
* Save a category record to the database (via AJAX post). * Save a category record to the database (via AJAX post).
* *
* @param {Object} category Contains the category data. * @param {Object} category Contains the category data.
*/ */
CategoriesHelper.prototype.save = function (category) { function save(category) {
var url = GlobalVariables.baseUrl + '/index.php/categories/' + (category.id ? 'update' : 'create'); App.Http.Categories.save(category).then((response) => {
Backend.displayNotification(App.Lang.category_saved);
var data = { resetForm();
csrf_token: GlobalVariables.csrfToken, $('#filter-categories .key').val('');
category: JSON.stringify(category) filter('', response.id, true);
}; });
}
$.post(url, data).done(
function (response) {
Backend.displayNotification(App.Lang.category_saved);
this.resetForm();
$('#filter-categories .key').val('');
this.filter('', response.id, true);
}.bind(this)
);
};
/** /**
* Delete category record. * Delete category record.
* *
* @param {Number} id Record ID to be deleted. * @param {Number} id Record ID to be deleted.
*/ */
CategoriesHelper.prototype.delete = function (id) { function remove(id) {
var url = GlobalVariables.baseUrl + '/index.php/categories/destroy'; App.Http.Categories.destroy(id).then(() => {
Backend.displayNotification(App.Lang.category_deleted);
var data = { resetForm();
csrf_token: GlobalVariables.csrfToken, filter($('#filter-categories .key').val());
category_id: id });
}; }
$.post(url, data).done(
function () {
Backend.displayNotification(App.Lang.category_deleted);
this.resetForm();
this.filter($('#filter-categories .key').val());
}.bind(this)
);
};
/** /**
* Display a category record on the form. * Display a category record on the form.
* *
* @param {Object} category Contains the category data. * @param {Object} category Contains the category data.
*/ */
CategoriesHelper.prototype.display = function (category) { function display(category) {
$('#category-id').val(category.id); $('#category-id').val(category.id);
$('#category-name').val(category.name); $('#category-name').val(category.name);
$('#category-description').val(category.description); $('#category-description').val(category.description);
}; }
/** /**
* Validate category data before save (insert or update). * Validate category data before save (insert or update).
* *
* @return {Boolean} Returns the validation result. * @return {Boolean} Returns the validation result.
*/ */
CategoriesHelper.prototype.validate = function () { function validate() {
$('#categories .is-invalid').removeClass('is-invalid'); $('#categories .is-invalid').removeClass('is-invalid');
$('#categories .form-message').removeClass('alert-danger').hide(); $('#categories .form-message').removeClass('alert-danger').hide();
try { try {
var missingRequired = false; let missingRequired = false;
$('#categories .required').each(function (index, requiredField) { $('#categories .required').each(function (index, requiredField) {
if (!$(requiredField).val()) { if (!$(requiredField).val()) {
@ -301,12 +259,12 @@
$('#categories .form-message').addClass('alert-danger').text(error.message).show(); $('#categories .form-message').addClass('alert-danger').text(error.message).show();
return false; return false;
} }
}; }
/** /**
* Bring the category form back to its initial state. * Bring the category form back to its initial state.
*/ */
CategoriesHelper.prototype.resetForm = function () { function resetForm() {
$('#filter-categories .selected').removeClass('selected'); $('#filter-categories .selected').removeClass('selected');
$('#filter-categories button').prop('disabled', false); $('#filter-categories button').prop('disabled', false);
$('#filter-categories .results').css('color', ''); $('#filter-categories .results').css('color', '');
@ -318,7 +276,7 @@
$('#categories .record-details .is-invalid').removeClass('is-invalid'); $('#categories .record-details .is-invalid').removeClass('is-invalid');
$('#categories .record-details .form-message').hide(); $('#categories .record-details .form-message').hide();
}; }
/** /**
* Get the filter results row HTML code. * Get the filter results row HTML code.
@ -327,7 +285,7 @@
* *
* @return {String} Returns the record HTML code. * @return {String} Returns the record HTML code.
*/ */
CategoriesHelper.prototype.getFilterHtml = function (category) { function getFilterHtml(category) {
return $('<div/>', { return $('<div/>', {
'class': 'category-row entry', 'class': 'category-row entry',
'data-id': category.id, 'data-id': category.id,
@ -338,7 +296,7 @@
$('<br/>') $('<br/>')
] ]
}); });
}; }
/** /**
* Select a specific record from the current filter results. * Select a specific record from the current filter results.
@ -346,28 +304,41 @@
* If the category ID does not exist in the list then no record will be selected. * If the category ID does not exist in the list then no record will be selected.
* *
* @param {Number} id The record ID to be selected from the filter results. * @param {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.
*/ */
CategoriesHelper.prototype.select = function (id, display) { function select(id, show = false) {
display = display || false;
$('#filter-categories .selected').removeClass('selected'); $('#filter-categories .selected').removeClass('selected');
$('#filter-categories .category-row[data-id="' + id + '"]').addClass('selected'); $('#filter-categories .category-row[data-id="' + id + '"]').addClass('selected');
if (display) { if (show) {
var category = this.filterResults.find( const category = filterResults.find(
function (category) { function (category) {
return Number(category.id) === Number(id); return Number(category.id) === Number(id);
}.bind(this) }.bind(this)
); );
this.display(category); display(category);
$('#edit-category, #delete-category').prop('disabled', false); $('#edit-category, #delete-category').prop('disabled', false);
} }
}; }
window.CategoriesHelper = CategoriesHelper; function init() {
resetForm();
filter('');
bindEventHandlers();
}
document.addEventListener('DOMContentLoaded', init);
return {
filter,
save,
remove,
getFilterHtml,
resetForm,
select
};
})(); })();