diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index c97c56e8..b8c7b683 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -425,6 +425,9 @@ $routes->resource('clienteplantillaprecioslineas', ['namespace' => 'App\Controll $routes->group('clienteusuarios', ['namespace' => 'App\Controllers\Clientes'], function ($routes) { $routes->post('datatable', 'Clienteusuarios::datatable', ['as' => 'dataTableOfClienteUsuarios']); + $routes->post('adduser', 'Clienteusuarios::addUserToClient'); + $routes->get('delete/(:num)', 'Clienteusuarios::removeClienteFromUser/$1'); + $routes->get('getusers', 'Clienteusuarios::getAvailableUsers'); }); diff --git a/ci4/app/Controllers/Clientes/Clienteusuarios.php b/ci4/app/Controllers/Clientes/Clienteusuarios.php index 8e2cdaac..ba0c9952 100644 --- a/ci4/app/Controllers/Clientes/Clienteusuarios.php +++ b/ci4/app/Controllers/Clientes/Clienteusuarios.php @@ -1,4 +1,5 @@ -request->isAJAX()) { + if (intval($user_id) > 0) { + $this->model->removeClienteFromUser($user_id); + return $this->respond(['status' => 'success', 'msg' => 'Usuario eliminado correctamente']); + } + } else { + return $this->failUnauthorized('Invalid request', 403); + } + } + + public function addUserToClient(){ + + if ($this->request->isAJAX()) { + $user_id = $this->request->getPost("user_id"); + $cliente_id = $this->request->getPost("cliente_id"); + if (intval($user_id) > 0 && intval($cliente_id) > 0) { + $this->model->addUserToClient($user_id, $cliente_id); + return $this->respond(['status' => 'success', 'msg' => 'Usuario añadido correctamente']); + } + } else { + return $this->failUnauthorized('Invalid request', 403); + } + } + + public function getAvailableUsers() + { + if ($this->request->isAJAX()) { + $query = $this->model->builder()->select( + [ + "id", + "CONCAT(first_name, ' ', last_name) as name" + ] + ) + ->where("deleted_at", null) + ->where("cliente_id", null); + + if ($this->request->getGet("q")) { + $column = "CONCAT(first_name, ' ', last_name)"; + $value = $this->request->getGet("q"); + $query->groupStart() + ->where("LOWER(CONVERT($column USING utf8)) COLLATE utf8_general_ci LIKE", "%" . strtolower($value) . "%") + ->groupEnd(); + } + + $items = $query->get()->getResultObject(); + return $this->response->setJSON($items); + + } else { + return $this->failUnauthorized('Invalid request', 403); + } + } public function datatable() @@ -53,14 +107,19 @@ class Clienteusuarios extends \App\Controllers\BaseResourceController } $start = $reqData['start'] ?? 0; $length = $reqData['length'] ?? 5; - $search = $reqData['search']['value']; - $requestedOrder = $reqData['order']['0']['column'] ?? 1; - $order = ClienteUsuariosModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 1]; - $dir = $reqData['order']['0']['dir'] ?? 'asc'; - + $requestedOrder = $reqData['order'] ?? []; $id_C = $reqData['id_cliente'] ?? -1; - $resourceData = $this->model->getResource("", $id_C)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(); + $resourceData = $this->model->getResource("", $id_C); + foreach ($requestedOrder as $order) { + $column = $order['column'] ?? 0; + $dir = $order['dir'] ?? 'asc'; + $orderColumn = ClienteUsuariosModel::SORTABLE[$column] ?? null; + if ($orderColumn) { + $resourceData->orderBy($orderColumn, $dir); + } + } + $resourceData = $resourceData->limit($length, $start)->get()->getResultObject(); return $this->respond(Collection::datatable( $resourceData, diff --git a/ci4/app/Language/es/Users.php b/ci4/app/Language/es/Users.php index 620aa2df..81059ba3 100755 --- a/ci4/app/Language/es/Users.php +++ b/ci4/app/Language/es/Users.php @@ -3,6 +3,7 @@ return [ + 'add' => 'Añadir', 'address' => 'Dirección', 'blocked' => 'Bloqueado', 'non_blocked' => 'No bloqueado', @@ -38,6 +39,7 @@ return [ 'user' => 'Usuario', 'userList' => 'Lista de usuarios', 'users' => 'Usuarios', + 'usersAvailables' => 'Usuarios disponibles', 'zipCode' => 'Código postal', 'admin' => 'Administrador', diff --git a/ci4/app/Models/Clientes/ClienteUsuariosModel.php b/ci4/app/Models/Clientes/ClienteUsuariosModel.php index 474b6ce3..4eedadf5 100644 --- a/ci4/app/Models/Clientes/ClienteUsuariosModel.php +++ b/ci4/app/Models/Clientes/ClienteUsuariosModel.php @@ -16,9 +16,10 @@ class ClienteUsuariosModel extends ShieldUserModel protected $useAutoIncrement = true; const SORTABLE = [ - 0 => "t1.first_name", - 1 => "t1.last_name", - 2 => "t2.secret", + 0 => "t1.id", + 1 => "t1.first_name", + 2 => "t1.last_name", + 3 => "t2.secret", ]; protected $allowedFields = ["id", "first_name", "last_name", "email"]; @@ -83,6 +84,19 @@ class ClienteUsuariosModel extends ShieldUserModel return $result; } + public function removeClienteFromUser($user_id = -1){ + + $this->db->table($this->table)->where('id', $user_id)->update(['cliente_id' => null]); + } + + + public function addUserToClient($user_id = -1, $cliente_id = -1){ + if($user_id < 1 || $cliente_id < 1){ + return; + } + $this->db->table($this->table)->where('id', $user_id)->update(['cliente_id' => $cliente_id]); + } + /** * Get resource data. * @@ -100,15 +114,8 @@ class ClienteUsuariosModel extends ShieldUserModel ); $builder->join("auth_identities t2", "t1.id = t2.user_id", "left"); - $builder->where('t1.id', $cliente_id); + $builder->where('t1.cliente_id', $cliente_id); - return empty($search) - ? $builder - : $builder - ->groupStart() - ->like("t1.first_name", $search) - ->orLike("t1.last_name", $search) - ->orLike("t2.secret", $search) - ->groupEnd(); + return $builder; } } diff --git a/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php b/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php index 5766a61f..6c67d6a6 100644 --- a/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php +++ b/ci4/app/Views/themes/vuexy/form/clientes/cliente/_clienteFormItems.php @@ -654,6 +654,24 @@
+ +
+ +
+
+ + + +
+
+
+ +
+
+ @@ -1104,67 +1122,6 @@ function delete_direccion_envio(dataId){ endSection() ?> -section("additionalInlineJs") ?> -/**************************************** - Contactos -*****************************************/ - - const lastColNrCU = $('#tableOfClienteUsuarios').find("tr:first th").length - 1; - - var theTableCU = $('#tableOfClienteUsuarios').DataTable( { - serverSide: true, - processing: true, - autoWidth: true, - responsive: true, - lengthMenu: [ 5, 10, 25], - order: [[ 0, "asc" ], [ 1, "asc" ]], - pageLength: 10, - lengthChange: true, - searching: false, - paging: true, - info: false, - dom: '<"mt-4"><"float-end"B><"float-start"l><"mt-4 mb-3"p>', - ajax : $.fn.dataTable.pipeline( { - url: '', - data: { - //id_cliente: id, - id_cliente: 1, - }, - method: 'POST', - headers: {'X-Requested-With': 'XMLHttpRequest'}, - async: true, - }), - columns: [ - { 'data': 'id' }, - { 'data': 'nombre' }, - { 'data': 'apellidos' }, - { 'data': 'email' }, - { - data: actionBtns, - className: 'row-edit dt-center' - } - ], - columnDefs: [ - { - orderable: false, - searchable: false, - targets: [lastColNrCU] - }, - { - "orderData": [ 0, 1 ], - "targets": 0 - }, - - ], - language: { - url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" - } - } ); - -endSection() ?> - - - section('css') ?> diff --git a/httpdocs/assets/js/safekat/pages/cliente/cliente.js b/httpdocs/assets/js/safekat/pages/cliente/cliente.js index 0ef85e60..a49e68ca 100644 --- a/httpdocs/assets/js/safekat/pages/cliente/cliente.js +++ b/httpdocs/assets/js/safekat/pages/cliente/cliente.js @@ -1,5 +1,7 @@ import ClassSelect from '../../components/select2.js'; import tarifasClienteView from './tarifasCliente.js'; +import ClienteUsuarios from './clienteUsuarios.js'; + import Ajax from '../../components/ajax.js'; class Cliente { @@ -15,6 +17,8 @@ class Cliente { this.provincia = new ClassSelect($("#provinciaId"), '/provincias/menuitems2', "Seleccione una provincia", {[this.csrf_token]: this.csrf_hash}); this.comunidadAutonoma = new ClassSelect($("#comunidadAutonomaId"), '/comunidades-autonomas/menuitems2', "Seleccione una comunidad autónoma", {[this.csrf_token]: this.csrf_hash}); + this.clienteUsuarios = new ClienteUsuarios($('#usuarios')); + } init() { @@ -32,6 +36,7 @@ class Cliente { this.comunidadAutonoma.init(); this.tarifas.init(); + this.clienteUsuarios.init(); $(document).keypress(function (e) { var key = e.which; diff --git a/httpdocs/assets/js/safekat/pages/cliente/clienteUsuarios.js b/httpdocs/assets/js/safekat/pages/cliente/clienteUsuarios.js new file mode 100644 index 00000000..4b87f394 --- /dev/null +++ b/httpdocs/assets/js/safekat/pages/cliente/clienteUsuarios.js @@ -0,0 +1,115 @@ +import Table from '../../components/table.js'; +import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js'; +import Ajax from '../../components/ajax.js'; +import ClassSelect from '../../components/select2.js'; + +class ClienteUsuarios { + + constructor(domItem) { + + this.domItem = domItem; + this.table = null; + this.deleteModal = null; + + this.usersSelect = new ClassSelect($('#usuariosDisponibles'), '/clienteusuarios/getusers', ""); + this.userAdd = this.domItem.find('#addUserToClient'); + + this.clienteId = window.location.href.split("/").pop(); + } + + init() { + + const self = this; + + this.#initTable(); + this.usersSelect.init(); + + this.deleteModal = new ConfirmDeleteModal('clienteUsuarios'); + this.deleteModal.init(); + + // Eliminar la fila + this.table.table.on('click', '.btn-delete-' + this.table.getAlias(), function (e) { + const row = $(this).closest('tr')[0]._DT_RowIndex; + const dataId = $(this).attr('data-id'); + self.deleteModal.setData($(this).attr('data-id')); + self.deleteModal.show(() => { + + if (!Number.isNaN(Number(self.deleteModal.getData()))) { + + new Ajax( + '/clienteusuarios/delete/' + dataId, + { + + }, + {}, + (data, textStatus, jqXHR) => { + + self.table.table.clearPipeline(); + self.table.table.row($(row)).invalidate().draw(); + + popSuccessAlert(data.msg ?? jqXHR.statusText); + }, + (error) => { + console.log(error); + } + + ).get(); + self.deleteModal.hide(); + } + }); + }); + + this.userAdd.on('click', function (e) { + e.preventDefault(); + const userId = self.usersSelect.getVal(); + if (userId != "") { + new Ajax( + '/clienteusuarios/adduser', + { + cliente_id: self.clienteId, + user_id: userId, + }, + {}, + (data, textStatus, jqXHR) => { + self.table.table.clearPipeline(); + self.table.table.draw(); + popSuccessAlert(data.msg ?? jqXHR.statusText); + }, + (error) => { + console.log(error); + } + + ).post(); + } + }); + } + + #initTable() { + + const columns = [ + { 'data': 'id' }, + { 'data': 'nombre' }, + { 'data': 'apellidos' }, + { 'data': 'email' }, + ]; + + const actions = ['delete']; + + this.table = new Table( + $('#tableOfClienteUsuarios'), + 'clienteUsuarios', + '/clienteusuarios/datatable', + columns, + [{ name: 'id_cliente', value: this.clienteId },] + ); + + + this.table.init({ + actions: actions, + colVisibility: false, + buttonsExport: false, + }); + } +} + +export default ClienteUsuarios; \ No newline at end of file