Created a new secretaries resource controller

This commit is contained in:
alextselegidis 2021-11-18 06:23:21 +01:00
parent e842089694
commit 7a3aa38622
4 changed files with 1060 additions and 0 deletions

View file

@ -0,0 +1,175 @@
<?php defined('BASEPATH') or exit('No direct script access allowed');
/* ----------------------------------------------------------------------------
* Easy!Appointments - Open Source Web Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) 2013 - 2020, Alex Tselegidis
* @license https://opensource.org/licenses/GPL-3.0 - GPLv3
* @link https://easyappointments.org
* @since v1.0.0
* ---------------------------------------------------------------------------- */
/**
* Secretaries controller.
*
* Handles the secretaries related operations.
*
* @package Controllers
*/
class Secretaries extends EA_Controller {
/**
* Secretaries constructor.
*/
public function __construct()
{
parent::__construct();
$this->load->model('secretaries_model');
$this->load->model('providers_model');
$this->load->model('roles_model');
$this->load->library('accounts');
$this->load->library('timezones');
}
/**
* Render the backend secretaries page.
*
* On this page secretary users will be able to manage secretaries, which are eventually selected by customers during the
* booking process.
*/
public function index()
{
session(['dest_url' => site_url('secretaries')]);
if (cannot('view', 'users'))
{
show_error('Forbidden', 403);
}
$user_id = session('user_id');
$role_slug = session('role_slug');
$this->load->view('pages/secretaries/secretaries_page', [
'page_title' => lang('secretaries'),
'active_menu' => PRIV_USERS,
'user_display_name' => $this->accounts->get_user_display_name($user_id),
'timezones' => $this->timezones->to_array(),
'privileges' => $this->roles_model->get_permissions_by_slug($role_slug),
'providers' => $this->providers_model->get(),
]);
}
/**
* Filter secretaries by the provided keyword.
*/
public function search()
{
try
{
if (cannot('view', 'users'))
{
show_error('Forbidden', 403);
}
$keyword = request('keyword', '');
$order_by = 'first_name ASC, last_name ASC, email ASC';
$limit = request('limit', 1000);
$offset = 0;
$secretaries = $this->secretaries_model->search($keyword, $limit, $offset, $order_by);
json_response($secretaries);
}
catch (Throwable $e)
{
json_exception($e);
}
}
/**
* Create a secretary.
*/
public function create()
{
try
{
$secretary = json_decode(request('secretary'), TRUE);
if (cannot('add', 'users'))
{
show_error('Forbidden', 403);
}
$secretary_id = $this->secretaries_model->save($secretary);
json_response([
'success' => TRUE,
'id' => $secretary_id
]);
}
catch (Throwable $e)
{
json_exception($e);
}
}
/**
* Update a secretary.
*/
public function update()
{
try
{
$secretary = json_decode(request('secretary'), TRUE);
if (cannot('edit', 'users'))
{
show_error('Forbidden', 403);
}
$secretary_id = $this->secretaries_model->save($secretary);
json_response([
'success' => TRUE,
'id' => $secretary_id
]);
}
catch (Throwable $e)
{
json_exception($e);
}
}
/**
* Remove a secretary.
*/
public function destroy()
{
try
{
if (cannot('delete', 'users'))
{
show_error('Forbidden', 403);
}
$secretary_id = request('secretary_id');
$this->secretaries_model->delete($secretary_id);
json_response([
'success' => TRUE,
]);
}
catch (Throwable $e)
{
json_exception($e);
}
}
}

View file

@ -0,0 +1,243 @@
<?php
/**
* @var array $providers
* @var string $timezones
* @var array $privileges
*/
?>
<?php extend('layouts/backend/backend_layout') ?>
<?php section('content') ?>
<script src="<?= asset_url('assets/js/backend_secretaries_helper.js') ?>"></script>
<script src="<?= asset_url('assets/js/backend_secretaries.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')) ?>,
providers: <?= json_encode($providers) ?>,
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 () {
BackendSecretaries.initialize(true);
});
</script>
<div class="container-fluid backend-page" id="secretaries-page">
<div class="row" id="secretaries">
<div id="filter-secretaries" class="filter-records column col-12 col-md-5">
<form class="mb-4">
<div class="input-group">
<input type="text" class="key form-control">
<div class="input-group-addon">
<div>
<button class="filter btn btn-outline-secondary" type="submit"
data-tippy-content="<?= lang('filter') ?>">
<i class="fas fa-search"></i>
</button>
<button class="clear btn btn-outline-secondary" type="button"
data-tippy-content="<?= lang('clear') ?>">
<i class="fas fa-redo-alt"></i>
</button>
</div>
</div>
</div>
</form>
<h3><?= lang('secretaries') ?></h3>
<div class="results"></div>
</div>
<div class="record-details column col-12 col-md-7">
<div class="btn-toolbar mb-4">
<div class="add-edit-delete-group btn-group">
<button id="add-secretary" class="btn btn-primary">
<i class="fas fa-plus-square mr-2"></i>
<?= lang('add') ?>
</button>
<button id="edit-secretary" class="btn btn-outline-secondary" disabled="disabled">
<i class="fas fa-edit mr-2"></i>
<?= lang('edit') ?>
</button>
<button id="delete-secretary" class="btn btn-outline-secondary" disabled="disabled">
<i class="fas fa-trash-alt mr-2"></i>
<?= lang('delete') ?>
</button>
</div>
<div class="save-cancel-group btn-group" style="display:none;">
<button id="save-secretary" class="btn btn-primary">
<i class="fas fa-check-square mr-2"></i>
<?= lang('save') ?>
</button>
<button id="cancel-secretary" class="btn btn-outline-secondary">
<i class="fas fa-ban mr-2"></i>
<?= lang('cancel') ?>
</button>
</div>
</div>
<h3><?= lang('details') ?></h3>
<div class="form-message alert" style="display:none;"></div>
<input type="hidden" id="secretary-id" class="record-id">
<div class="row">
<div class="secretary-details col-12 col-md-6">
<div class="form-group">
<label for="secretary-first-name">
<?= lang('first_name') ?>
<span class="text-danger">*</span>
</label>
<input id="secretary-first-name" class="form-control required" maxlength="256">
</div>
<div class="form-group">
<label for="secretary-last-name">
<?= lang('last_name') ?>
<span class="text-danger">*</span>
</label>
<input id="secretary-last-name" class="form-control required" maxlength="512">
</div>
<div class="form-group">
<label for="secretary-email">
<?= lang('email') ?>
<span class="text-danger">*</span>
</label>
<input id="secretary-email" class="form-control required" maxlength="512">
</div>
<div class="form-group">
<label for="secretary-phone-number">
<?= lang('phone_number') ?>
<span class="text-danger">*</span>
</label>
<input id="secretary-phone-number" class="form-control required" maxlength="128">
</div>
<div class="form-group">
<label for="secretary-mobile-number">
<?= lang('mobile_number') ?>
</label>
<input id="secretary-mobile-number" class="form-control" maxlength="128">
</div>
<div class="form-group">
<label for="secretary-address">
<?= lang('address') ?>
</label>
<input id="secretary-address" class="form-control" maxlength="256">
</div>
<div class="form-group">
<label for="secretary-city">
<?= lang('city') ?>
</label>
<input id="secretary-city" class="form-control" maxlength="256">
</div>
<div class="form-group">
<label for="secretary-state">
<?= lang('state') ?>
</label>
<input id="secretary-state" class="form-control" maxlength="128">
</div>
<div class="form-group">
<label for="secretary-zip-code">
<?= lang('zip_code') ?>
</label>
<input id="secretary-zip-code" class="form-control" maxlength="64">
</div>
<div class="form-group">
<label for="secretary-notes">
<?= lang('notes') ?>
</label>
<textarea id="secretary-notes" class="form-control" rows="3"></textarea>
</div>
</div>
<div class="secretary-settings col-12 col-md-6">
<div class="form-group">
<label for="secretary-username">
<?= lang('username') ?>
<span class="text-danger">*</span>
</label>
<input id="secretary-username" class="form-control required" maxlength="256">
</div>
<div class="form-group">
<label for="secretary-password">
<?= lang('password') ?>
<span class="text-danger">*</span>
</label>
<input type="password" id="secretary-password" class="form-control required"
maxlength="512" autocomplete="new-password">
</div>
<div class="form-group">
<label for="secretary-password-confirm">
<?= lang('retype_password') ?>
<span class="text-danger">*</span>
</label>
<input type="password" id="secretary-password-confirm" class="form-control required"
maxlength="512" autocomplete="new-password">
</div>
<div class="form-group">
<label for="secretary-calendar-view">
<?= lang('calendar') ?>
<span class="text-danger">*</span>
</label>
<select id="secretary-calendar-view" class="form-control required">
<option value="default">Default</option>
<option value="table">Table</option>
</select>
</div>
<div class="form-group">
<label for="secretary-timezone">
<?= lang('timezone') ?>
<span class="text-danger">*</span>
</label>
<?= render_timezone_dropdown('id="secretary-timezone" class="form-control required"') ?>
</div>
<br>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="secretary-notifications">
<label class="custom-control-label" for="secretary-notifications">
<?= lang('receive_notifications') ?>
</label>
</div>
<br>
<h4><?= lang('providers') ?></h4>
<div id="secretary-providers" class="card card-body bg-light border-light"></div>
</div>
</div>
</div>
</div>
</div>
<?php section('content') ?>

View file

@ -0,0 +1,130 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Open Source Web Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) 2013 - 2020, Alex Tselegidis
* @license http://opensource.org/licenses/GPL-3.0 - GPLv3
* @link http://easyappointments.org
* @since v1.0.0
* ---------------------------------------------------------------------------- */
window.BackendSecretaries = window.BackendSecretaries || {};
/**
* Backend Users
*
* This module handles the js functionality of the users backend page. It uses three other
* classes (defined below) in order to handle the admin, provider and secretary record types.
*
* @module BackendSecretaries
*/
(function (exports) {
'use strict';
/**
* Minimum Password Length
*
* @type {Number}
*/
exports.MIN_PASSWORD_LENGTH = 7;
/**
* Contains the current tab record methods for the page.
*
* @type {SecretariesHelper}
*/
var helper = {};
/**
* Initialize the backend users page.
*
* @param {Boolean} defaultEventHandlers (OPTIONAL) Whether to bind the default event handlers.
*/
exports.initialize = function (defaultEventHandlers) {
defaultEventHandlers = defaultEventHandlers || true;
// Instantiate default helper object.
helper = new SecretariesHelper();
helper.resetForm();
helper.filter('');
helper.bindEventHandlers();
GlobalVariables.providers.forEach(function (provider) {
$('<div/>', {
'class': 'checkbox',
'html': [
$('<div/>', {
'class': 'checkbox form-check',
'html': [
$('<input/>', {
'class': 'form-check-input',
'type': 'checkbox',
'data-id': provider.id
}),
$('<label/>', {
'class': 'form-check-label',
'text': provider.first_name + ' ' + provider.last_name,
'for': provider.id
})
]
})
]
}).appendTo('#secretary-providers');
});
// Bind event handlers.
if (defaultEventHandlers) {
bindEventHandlers();
}
};
/**
* Binds the default backend users event handlers. Do not use this method on a different
* page because it needs the backend users page DOM.
*/
function bindEventHandlers() {
/**
* Event: Secretary Username "Blue"
*
* When the user leaves the username input field we will need to check if the username
* is not taken by another record in the system.
*/
$('#secretary-username').focusout(function () {
var $input = $(this);
if ($input.prop('readonly') === true || $input.val() === '') {
return;
}
var userId = $input.parents().eq(2).find('.record-id').val();
if (!userId) {
return;
}
var url = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_validate_username';
var data = {
csrfToken: GlobalVariables.csrfToken,
username: $input.val(),
user_id: userId
};
$.post(url, data).done(function (response) {
if (response.is_valid === 'false') {
$input.closest('.form-group').addClass('has-error');
$input.attr('already-exists', 'true');
$input.parents().eq(3).find('.form-message').text(EALang.username_already_exists);
$input.parents().eq(3).find('.form-message').show();
} else {
$input.closest('.form-group').removeClass('has-error');
$input.attr('already-exists', 'false');
if ($input.parents().eq(3).find('.form-message').text() === EALang.username_already_exists) {
$input.parents().eq(3).find('.form-message').hide();
}
}
});
});
}
})(window.BackendSecretaries);

View file

@ -0,0 +1,512 @@
/* ----------------------------------------------------------------------------
* Easy!Appointments - Open Source Web Scheduler
*
* @package EasyAppointments
* @author A.Tselegidis <alextselegidis@gmail.com>
* @copyright Copyright (c) 2013 - 2020, Alex Tselegidis
* @license http://opensource.org/licenses/GPL-3.0 - GPLv3
* @link http://easyappointments.org
* @since v1.0.0
* ---------------------------------------------------------------------------- */
(function () {
'use strict';
/**
* Secretaries Helper
*
* This class contains the Secretaries helper class declaration, along with the "Secretaries"
* tab event handlers. By dividing the backend/users tab functionality into separate files
* it is easier to maintain the code.
*
* @class SecretariesHelper
*/
var SecretariesHelper = function () {
this.filterResults = {}; // Store the results for later use.
this.filterLimit = 20;
};
/**
* Bind the event handlers for the backend/users "Secretaries" tab.
*/
SecretariesHelper.prototype.bindEventHandlers = function () {
/**
* Event: Filter Secretaries Form "Submit"
*
* Filter the secretary records with the given key string.
*
* @param {jQuery.Event} event
*/
$('#secretaries').on(
'submit',
'#filter-secretaries form',
function (event) {
event.preventDefault();
var key = $('#filter-secretaries .key').val();
$('#filter-secretaries .selected').removeClass('selected');
this.resetForm();
this.filter(key);
}.bind(this)
);
/**
* Event: Clear Filter Results Button "Click"
*/
$('#secretaries').on(
'click',
'#filter-secretaries .clear',
function () {
this.filter('');
$('#filter-secretaries .key').val('');
this.resetForm();
}.bind(this)
);
/**
* Event: Filter Secretary Row "Click"
*
* Display the selected secretary data to the user.
*/
$('#secretaries').on(
'click',
'.secretary-row',
function (event) {
if ($('#filter-secretaries .filter').prop('disabled')) {
$('#filter-secretaries .results').css('color', '#AAA');
return; // exit because we are currently on edit mode
}
var secretaryId = $(event.currentTarget).attr('data-id');
var secretary = this.filterResults.find(function (filterResult) {
return Number(filterResult.id) === Number(secretaryId);
});
this.display(secretary);
$('#filter-secretaries .selected').removeClass('selected');
$(event.currentTarget).addClass('selected');
$('#edit-secretary, #delete-secretary').prop('disabled', false);
}.bind(this)
);
/**
* Event: Add New Secretary Button "Click"
*/
$('#secretaries').on(
'click',
'#add-secretary',
function () {
this.resetForm();
$('#filter-secretaries button').prop('disabled', true);
$('#filter-secretaries .results').css('color', '#AAA');
$('#secretaries .add-edit-delete-group').hide();
$('#secretaries .save-cancel-group').show();
$('#secretaries .record-details').find('input, textarea').prop('disabled', false);
$('#secretaries .record-details').find('select').prop('disabled', false);
$('#secretary-password, #secretary-password-confirm').addClass('required');
$('#secretary-providers input:checkbox').prop('disabled', false);
}.bind(this)
);
/**
* Event: Edit Secretary Button "Click"
*/
$('#secretaries').on('click', '#edit-secretary', function () {
$('#filter-secretaries button').prop('disabled', true);
$('#filter-secretaries .results').css('color', '#AAA');
$('#secretaries .add-edit-delete-group').hide();
$('#secretaries .save-cancel-group').show();
$('#secretaries .record-details').find('input, textarea').prop('disabled', false);
$('#secretaries .record-details').find('select').prop('disabled', false);
$('#secretary-password, #secretary-password-confirm').removeClass('required');
$('#secretary-providers input:checkbox').prop('disabled', false);
});
/**
* Event: Delete Secretary Button "Click"
*/
$('#secretaries').on(
'click',
'#delete-secretary',
function () {
var secretaryId = $('#secretary-id').val();
var buttons = [
{
text: EALang.cancel,
click: function () {
$('#message-box').dialog('close');
}
},
{
text: EALang.delete,
click: function () {
this.delete(secretaryId);
$('#message-box').dialog('close');
}.bind(this)
}
];
GeneralFunctions.displayMessageBox(EALang.delete_secretary, EALang.delete_record_prompt, buttons);
}.bind(this)
);
/**
* Event: Save Secretary Button "Click"
*/
$('#secretaries').on(
'click',
'#save-secretary',
function () {
var secretary = {
first_name: $('#secretary-first-name').val(),
last_name: $('#secretary-last-name').val(),
email: $('#secretary-email').val(),
mobile_number: $('#secretary-mobile-number').val(),
phone_number: $('#secretary-phone-number').val(),
address: $('#secretary-address').val(),
city: $('#secretary-city').val(),
state: $('#secretary-state').val(),
zip_code: $('#secretary-zip-code').val(),
notes: $('#secretary-notes').val(),
timezone: $('#secretary-timezone').val(),
settings: {
username: $('#secretary-username').val(),
notifications: $('#secretary-notifications').prop('checked'),
calendar_view: $('#secretary-calendar-view').val()
}
};
// Include secretary services.
secretary.providers = [];
$('#secretary-providers input:checkbox').each(function (index, checkbox) {
if ($(checkbox).prop('checked')) {
secretary.providers.push($(checkbox).attr('data-id'));
}
});
// Include password if changed.
if ($('#secretary-password').val() !== '') {
secretary.settings.password = $('#secretary-password').val();
}
// Include ID if changed.
if ($('#secretary-id').val() !== '') {
secretary.id = $('#secretary-id').val();
}
if (!this.validate()) {
return;
}
this.save(secretary);
}.bind(this)
);
/**
* Event: Cancel Secretary Button "Click"
*
* Cancel add or edit of an secretary record.
*/
$('#secretaries').on(
'click',
'#cancel-secretary',
function () {
var id = $('#secretary-id').val();
this.resetForm();
if (id) {
this.select(id, true);
}
}.bind(this)
);
};
/**
* Remove the previously registered event handlers.
*/
SecretariesHelper.prototype.unbindEventHandlers = function () {
$('#secretaries')
.off('submit', '#filter-secretaries form')
.off('click', '#filter-secretaries .clear')
.off('click', '.secretary-row')
.off('click', '#add-secretary')
.off('click', '#edit-secretary')
.off('click', '#delete-secretary')
.off('click', '#save-secretary')
.off('click', '#cancel-secretary');
};
/**
* Save secretary record to database.
*
* @param {Object} secretary Contains the secretary record data. If an 'id' value is provided
* then the update operation is going to be executed.
*/
SecretariesHelper.prototype.save = function (secretary) {
var url = GlobalVariables.baseUrl + '/index.php/secretaries/' + (secretary.id ? 'update' : 'create');
var data = {
csrfToken: GlobalVariables.csrfToken,
secretary: JSON.stringify(secretary)
};
$.post(url, data).done(
function (response) {
Backend.displayNotification(EALang.secretary_saved);
this.resetForm();
$('#filter-secretaries .key').val('');
this.filter('', response.id, true);
}.bind(this)
);
};
/**
* Delete a secretary record from database.
*
* @param {Number} id Record id to be deleted.
*/
SecretariesHelper.prototype.delete = function (id) {
var url = GlobalVariables.baseUrl + '/index.php/secretaries/destroy';
var data = {
csrfToken: GlobalVariables.csrfToken,
secretary_id: id
};
$.post(url, data).done(
function () {
Backend.displayNotification(EALang.secretary_deleted);
this.resetForm();
this.filter($('#filter-secretaries .key').val());
}.bind(this)
);
};
/**
* Validates a secretary record.
*
* @return {Boolean} Returns the validation result.
*/
SecretariesHelper.prototype.validate = function () {
$('#secretaries .has-error').removeClass('has-error');
$('#secretaries .form-message').removeClass('alert-danger');
try {
// Validate required fields.
var missingRequired = false;
$('#secretaries .required').each(function (index, requiredField) {
if (!$(requiredField).val()) {
$(requiredField).closest('.form-group').addClass('has-error');
missingRequired = true;
}
});
if (missingRequired) {
throw new Error('Fields with * are required.');
}
// Validate passwords.
if ($('#secretary-password').val() !== $('#secretary-password-confirm').val()) {
$('#secretary-password, #secretary-password-confirm').closest('.form-group').addClass('has-error');
throw new Error('Passwords mismatch!');
}
if (
$('#secretary-password').val().length < BackendSecretaries.MIN_PASSWORD_LENGTH &&
$('#secretary-password').val() !== ''
) {
$('#secretary-password, #secretary-password-confirm').closest('.form-group').addClass('has-error');
throw new Error('Password must be at least ' + BackendSecretaries.MIN_PASSWORD_LENGTH + ' characters long.');
}
// Validate user email.
if (!GeneralFunctions.validateEmail($('#secretary-email').val())) {
$('#secretary-email').closest('.form-group').addClass('has-error');
throw new Error('Invalid email address!');
}
// Check if username exists
if ($('#secretary-username').attr('already-exists') === 'true') {
$('#secretary-username').closest('.form-group').addClass('has-error');
throw new Error('Username already exists.');
}
return true;
} catch (error) {
$('#secretaries .form-message').addClass('alert-danger').text(error.message).show();
return false;
}
};
/**
* Resets the secretary tab form back to its initial state.
*/
SecretariesHelper.prototype.resetForm = function () {
$('#filter-secretaries .selected').removeClass('selected');
$('#filter-secretaries button').prop('disabled', false);
$('#filter-secretaries .results').css('color', '');
$('#secretaries .record-details').find('input, select, textarea').val('').prop('disabled', true);
$('#secretaries .record-details #secretary-calendar-view').val('default');
$('#secretaries .record-details #secretary-timezone').val('UTC');
$('#secretaries .add-edit-delete-group').show();
$('#secretaries .save-cancel-group').hide();
$('#edit-secretary, #delete-secretary').prop('disabled', true);
$('#secretaries .form-message').hide();
$('#secretary-providers input:checkbox').prop('checked', false);
$('#secretaries .has-error').removeClass('has-error');
};
/**
* Display a secretary record into the secretary form.
*
* @param {Object} secretary Contains the secretary record data.
*/
SecretariesHelper.prototype.display = function (secretary) {
$('#secretary-id').val(secretary.id);
$('#secretary-first-name').val(secretary.first_name);
$('#secretary-last-name').val(secretary.last_name);
$('#secretary-email').val(secretary.email);
$('#secretary-mobile-number').val(secretary.mobile_number);
$('#secretary-phone-number').val(secretary.phone_number);
$('#secretary-address').val(secretary.address);
$('#secretary-city').val(secretary.city);
$('#secretary-state').val(secretary.state);
$('#secretary-zip-code').val(secretary.zip_code);
$('#secretary-notes').val(secretary.notes);
$('#secretary-timezone').val(secretary.timezone);
$('#secretary-username').val(secretary.settings.username);
$('#secretary-calendar-view').val(secretary.settings.calendar_view);
$('#secretary-notifications').prop('checked', Boolean(Number(secretary.settings.notifications)));
$('#secretary-providers input:checkbox').prop('checked', false);
secretary.providers.forEach(function (secretaryProviderId) {
var $checkbox = $('#secretary-providers input[data-id="' + secretaryProviderId + '"]');
if (!$checkbox.length) {
return;
}
$checkbox.prop('checked', true);
});
};
/**
* Filters secretary records depending a string keyword.
*
* @param {String} keyword This is used to filter the secretary records of the database.
* @param {Numeric} selectId Optional, if provided the given ID will be selected in the filter results
* (only selected, not displayed).
* @param {Bool} display Optional (false).
*/
SecretariesHelper.prototype.filter = function (keyword, selectId, display) {
display = display || false;
var url = GlobalVariables.baseUrl + '/index.php/secretaries/search';
var data = {
csrfToken: GlobalVariables.csrfToken,
keyword: keyword,
limit: this.filterLimit
};
$.post(url, data).done(
function (response) {
this.filterResults = response;
$('#filter-secretaries .results').empty();
response.forEach(
function (secretary) {
$('#filter-secretaries .results').append(this.getFilterHtml(secretary)).append($('<hr/>'));
}.bind(this)
);
if (!response.length) {
$('#filter-secretaries .results').append(
$('<em/>', {
'text': EALang.no_records_found
})
);
} else if (response.length === this.filterLimit) {
$('<button/>', {
'type': 'button',
'class': 'btn btn-block btn-outline-secondary load-more text-center',
'text': EALang.load_more,
'click': function () {
this.filterLimit += 20;
this.filter(keyword, selectId, display);
}.bind(this)
}).appendTo('#filter-secretaries .results');
}
if (selectId) {
this.select(selectId, display);
}
}.bind(this)
);
};
/**
* Get an secretary row html code that is going to be displayed on the filter results list.
*
* @param {Object} secretary Contains the secretary record data.
*
* @return {String} The html code that represents the record on the filter results list.
*/
SecretariesHelper.prototype.getFilterHtml = function (secretary) {
var name = secretary.first_name + ' ' + secretary.last_name;
var info = secretary.email;
info = secretary.mobile_number ? info + ', ' + secretary.mobile_number : info;
info = secretary.phone_number ? info + ', ' + secretary.phone_number : info;
return $('<div/>', {
'class': 'secretary-row entry',
'data-id': secretary.id,
'html': [
$('<strong/>', {
'text': name
}),
$('<br/>'),
$('<span/>', {
'text': info
}),
$('<br/>')
]
});
};
/**
* Select a specific record from the current filter results. If the secretary 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 {Boolean} display Optional (false), if true the method will display the record in the form.
*/
SecretariesHelper.prototype.select = function (id, display) {
display = display || false;
$('#filter-secretaries .selected').removeClass('selected');
$('#filter-secretaries .secretary-row[data-id="' + id + '"]').addClass('selected');
if (display) {
var secretary = this.filterResults.find(
function (filterResult) {
return Number(filterResult.id) === Number(id);
}.bind(this)
);
this.display(secretary);
$('#edit-secretary, #delete-secretary').prop('disabled', false);
}
};
window.SecretariesHelper = SecretariesHelper;
})();