From fce30342a7ae57829a9be2285d78205b636dfb3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Sun, 15 Dec 2024 13:14:30 +0100 Subject: [PATCH] modificado el listado de maquinas --- ci4/app/Config/Routes.php | 2 + .../Controllers/Configuracion/Maquinas.php | 113 +++++++---- ci4/app/Models/Configuracion/MaquinaModel.php | 83 ++------ .../maquinas/viewMaquinaList.php | 101 +--------- .../js/safekat/pages/maquinas/maquinasList.js | 185 ++++++++++++++++++ 5 files changed, 286 insertions(+), 198 deletions(-) create mode 100644 httpdocs/assets/js/safekat/pages/maquinas/maquinasList.js diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index b8c7b683..ef4675af 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -254,6 +254,8 @@ $routes->resource('papelesimpresionmargenes', ['namespace' => 'App\Controllers\C $routes->group('maquinas', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) { $routes->get('', 'Maquinas::index', ['as' => 'maquinaList']); $routes->get('add', 'Maquinas::add', ['as' => 'newMaquina']); + $routes->get('edit/(:num)', 'Maquinas::edit/$1'); + $routes->get('delete/(:num)', 'Maquinas::delete/$1'); $routes->post('add', 'Maquinas::add', ['as' => 'createMaquina']); $routes->post('create', 'Maquinas::create', ['as' => 'ajaxCreateMaquina']); $routes->put('update/(:num)', 'Maquinas::update/$1', ['as' => 'ajaxUpdateMaquina']); diff --git a/ci4/app/Controllers/Configuracion/Maquinas.php b/ci4/app/Controllers/Configuracion/Maquinas.php index 65166b70..8deac302 100755 --- a/ci4/app/Controllers/Configuracion/Maquinas.php +++ b/ci4/app/Controllers/Configuracion/Maquinas.php @@ -1,4 +1,5 @@ -respond(['status' => 'error', 'msg' => 'ID no válida']); + } + + // Buscar la máquina en la base de datos + $maquina = $this->model->find($id); + if (!$maquina) { + $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Maquinas.maquina')), $id]); + return $this->respond(['status' => 'error', 'msg' => 'ID no válida']); + } + + // Verificar que el usuario está autenticado + if (!auth()->user()) { + return $this->respond(['status' => 'error', 'msg' => 'Usuario no autenticado']); + } + + // Preparar los datos para actualizar + $data = [ + 'id' => $id, + 'is_deleted' => 1, + 'deleted_at' => date('Y-m-d H:i:s'), + 'user_updated_id' => auth()->user()->id, + ]; + + // Guardar los cambios + if (!$this->model->save($data)) { + return $this->respond(['status' => 'error', 'msg' => 'Error al eliminar']); + } + + // Retornar éxito + $message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]) . '.'; + return $this->respond(['status' => 'error', 'msg' => $message]); + } + public function add() { - - - - - if ($this->request->getPost()) : + if ($this->request->getPost()): $nullIfEmpty = true; // !(phpversion() >= '8.1'); @@ -84,10 +121,10 @@ class Maquinas extends \App\Controllers\BaseResourceController $sanitizedData['user_created_id'] = auth()->user()->id; $noException = true; - if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : + if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) : - if ($this->canValidate()) : + if ($this->canValidate()): try { $successfulResult = $this->model->skipValidation(true)->save($sanitizedData); } catch (\Exception $e) { @@ -101,14 +138,14 @@ class Maquinas extends \App\Controllers\BaseResourceController $thenRedirect = true; // Change this to false if you want your user to stay on the form after submission endif; - if ($noException && $successfulResult) : + if ($noException && $successfulResult): $id = $this->model->db->insertID(); $message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.'; - if ($thenRedirect) : - if (!empty($this->indexRoute)) : + if ($thenRedirect): + if (!empty($this->indexRoute)): //return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); return redirect()->to(site_url('configuracion/maquinas/edit/' . $id))->with('sweet-success', $message); else: @@ -138,20 +175,20 @@ class Maquinas extends \App\Controllers\BaseResourceController { - if ($requestedId == null) : + if ($requestedId == null): return $this->redirect2listView(); endif; $id = filter_var($requestedId, FILTER_SANITIZE_URL); $maquina = $this->model->find($id); - if ($maquina == false) : + if ($maquina == false): $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Maquinas.maquina')), $id]); return $this->redirect2listView('sweet-error', $message); endif; - - if ($this->request->getPost()) : + + if ($this->request->getPost()): $nullIfEmpty = true; // !(phpversion() >= '8.1'); @@ -171,17 +208,19 @@ class Maquinas extends \App\Controllers\BaseResourceController // JJO $sanitizedData['user_updated_id'] = auth()->user()->id; $noException = true; - if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : + if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) : - if ($this->canValidate()) : + if ($this->canValidate()): //JJO: comprobar alto y ancho impresion < alto y ancho if ($sanitizedData['alto'] < $sanitizedData['alto_impresion']) { $successfulResult = false; - $this->viewData['errorMessage'] = lang('Maquinas.validation.alto_menor_alto_impresion');; + $this->viewData['errorMessage'] = lang('Maquinas.validation.alto_menor_alto_impresion'); + ; $this->session->setFlashdata('formErrors', $this->model->errors()); } else if ($sanitizedData['ancho'] < $sanitizedData['ancho_impresion']) { $successfulResult = false; - $this->viewData['errorMessage'] = lang('Maquinas.validation.ancho_menor_ancho_impresion');; + $this->viewData['errorMessage'] = lang('Maquinas.validation.ancho_menor_ancho_impresion'); + ; $this->session->setFlashdata('formErrors', $this->model->errors()); } else { try { @@ -202,12 +241,12 @@ class Maquinas extends \App\Controllers\BaseResourceController $thenRedirect = false; endif; - if ($noException && $successfulResult) : + if ($noException && $successfulResult): $id = $maquina->id ?? $id; $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.'; - if ($thenRedirect) : - if (!empty($this->indexRoute)) : + if ($thenRedirect): + if (!empty($this->indexRoute)): return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); else: return $this->redirect2listView('sweet-success', $message); @@ -243,22 +282,24 @@ class Maquinas extends \App\Controllers\BaseResourceController } $start = $reqData['start'] ?? 0; $length = $reqData['length'] ?? 5; - $search = $reqData['search']['value']; - $requestedOrder = $reqData['order']['0']['column'] ?? 1; - $order = MaquinaModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 1]; - $dir = $reqData['order']['0']['dir'] ?? 'asc'; + $searchValues = get_filter_datatables_columns($reqData); + $requestedOrder = $reqData['order'] ?? []; - $resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(); - foreach ($resourceData as $item) : - if (isset($item->observaciones) && strlen($item->observaciones) > 100) : - $item->observaciones = character_limiter($item->observaciones, 100); - endif; - endforeach; + $resourceData = $this->model->getResource($searchValues); + foreach ($requestedOrder as $order) { + $column = $order['column'] ?? 0; + $dir = $order['dir'] ?? 'asc'; + $orderColumn = MaquinaModel::SORTABLE[$column] ?? null; + if ($orderColumn) { + $resourceData->orderBy($orderColumn, $dir); + } + } + $resourceData = $resourceData->limit($length, $start)->get()->getResultObject(); return $this->respond(Collection::datatable( $resourceData, - $this->model->getResource()->countAllResults(), - $this->model->getResource($search)->countAllResults() + $this->model->getResource([])->countAllResults(), + $this->model->getResource($searchValues)->countAllResults() )); } else { return $this->failUnauthorized('Invalid request', 403); @@ -319,11 +360,11 @@ class Maquinas extends \App\Controllers\BaseResourceController protected function getMaquinaListItems($selId = null) { $data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Maquinas.maquina'))])]; - if (!empty($selId)) : + if (!empty($selId)): $maquinaModel = model('App\Models\Configuracion\MaquinaModel'); $selOption = $maquinaModel->where('id', $selId)->findColumn('nombre'); - if (!empty($selOption)) : + if (!empty($selOption)): $data[$selId] = $selOption[0]; endif; endif; diff --git a/ci4/app/Models/Configuracion/MaquinaModel.php b/ci4/app/Models/Configuracion/MaquinaModel.php index 0cefa19a..650162e6 100755 --- a/ci4/app/Models/Configuracion/MaquinaModel.php +++ b/ci4/app/Models/Configuracion/MaquinaModel.php @@ -14,22 +14,13 @@ class MaquinaModel extends \App\Models\BaseModel protected $useAutoIncrement = true; const SORTABLE = [ - //1 => "t1.id", - 0 => "t1.nombre", + 0 => "t1.id", 1 => "t2.nombre", 2 => "t1.tipo", - 3 => "t1.velocidad", - 4 => "t1.duracion_jornada", - 5 => "t1.ancho", - 6 => "t1.alto", - 7 => "t1.ancho_impresion", - 8 => "t1.alto_impresion", - 9 => "t1.orden_planning", - 10 => "t1.min", - 11 => "t1.max", - - - ]; + 3 => "t1.ancho_impresion", + 4 => "t1.alto_impresion", + 5 => "t1.min", + 6 => "t1.max", ]; protected $allowedFields = [ "nombre", @@ -295,7 +286,7 @@ class MaquinaModel extends \App\Models\BaseModel * * @return \CodeIgniter\Database\BaseBuilder */ - public function getResource(string $search = "") + public function getResource($search = []) { $builder = $this->db ->table($this->table . " t1") @@ -313,56 +304,18 @@ class MaquinaModel extends \App\Models\BaseModel //JJO $builder->where("t1.is_deleted", 0); - return empty($search) - ? $builder - : $builder - ->groupStart() - ->like("t1.id", $search) - ->orLike("t1.nombre", $search) - ->orLike("t1.tipo", $search) - ->orLike("t1.velocidad", $search) - ->orLike("t1.ancho", $search) - ->orLike("t1.alto", $search) - ->orLike("t1.ancho_impresion", $search) - ->orLike("t1.alto_impresion", $search) - ->orLike("t1.alto_click", $search) - ->orLike("t1.min", $search) - ->orLike("t1.max", $search) - ->orLike("t1.duracion_jornada", $search) - ->orLike("t1.orden_planning", $search) - ->orLike("t1.precio_tinta_negro", $search) - ->orLike("t1.precio_tinta_color", $search) - ->orLike("t1.velocidad_corte", $search) - ->orLike("t1.precio_hora_corte", $search) - ->orLike("t1.metrosxminuto", $search) - ->orLike("t1.forzar_num_formas_horizontales_cubierta", $search) - ->orLike("t1.forzar_num_formas_verticales_cubierta", $search) - ->orLike("t1.observaciones", $search) - ->orLike("t2.id", $search) - ->orLike("t1.id", $search) - ->orLike("t1.nombre", $search) - ->orLike("t1.tipo", $search) - ->orLike("t1.velocidad", $search) - ->orLike("t1.ancho", $search) - ->orLike("t1.alto", $search) - ->orLike("t1.ancho_impresion", $search) - ->orLike("t1.alto_impresion", $search) - ->orLike("t1.alto_click", $search) - ->orLike("t1.padre_id", $search) - ->orLike("t1.min", $search) - ->orLike("t1.max", $search) - ->orLike("t1.duracion_jornada", $search) - ->orLike("t1.orden_planning", $search) - ->orLike("t1.precio_tinta_negro", $search) - ->orLike("t1.precio_tinta_color", $search) - ->orLike("t1.velocidad_corte", $search) - ->orLike("t1.precio_hora_corte", $search) - ->orLike("t1.metrosxminuto", $search) - ->orLike("t1.forzar_num_formas_horizontales_cubierta", $search) - ->orLike("t1.forzar_num_formas_verticales_cubierta", $search) - ->orLike("t1.observaciones", $search) - ->orLike("t2.nombre", $search) - ->groupEnd(); + if (empty($search)) + return $builder; + else { + $builder->groupStart(); + foreach ($search as $col_search) { + $column = self::SORTABLE[$col_search[0]]; + $value = $col_search[2]; + $builder->where("LOWER(CONVERT($column USING utf8)) COLLATE utf8_general_ci LIKE", "%" . strtolower($value) . "%"); + } + $builder->groupEnd(); + return $builder; + } } public function getMaquinaImpresionForPresupuesto($is_rotativa, $tarifa_tipo, $uso_tarifa , $tirada, $papel_impresion_id = -1) diff --git a/ci4/app/Views/themes/vuexy/form/configuracion/maquinas/viewMaquinaList.php b/ci4/app/Views/themes/vuexy/form/configuracion/maquinas/viewMaquinaList.php index c3e7a1b0..a6d48422 100644 --- a/ci4/app/Views/themes/vuexy/form/configuracion/maquinas/viewMaquinaList.php +++ b/ci4/app/Views/themes/vuexy/form/configuracion/maquinas/viewMaquinaList.php @@ -18,13 +18,14 @@ + - + @@ -42,102 +43,6 @@ endSection() ?> -section('additionalInlineJs') ?> - - const lastColNr = $('#tableOfMaquinas').find("tr:first th").length - 1; - const actionBtns = function(data) { - return ` - `; - }; - theTable = $('#tableOfMaquinas').DataTable({ - processing: true, - serverSide: true, - autoWidth: true, - responsive: true, - scrollX: true, - lengthMenu: [ 5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500 ], - pageLength: 10, - lengthChange: true, - "dom": 'lfBrtip', - "buttons": [ - 'copy', 'csv', 'excel', 'print', { - extend: 'pdfHtml5', - orientation: 'landscape', - pageSize: 'A4' - } - ], - stateSave: true, - order: [[0, 'asc']], - language: { - url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" - }, - ajax : $.fn.dataTable.pipeline( { - url: '', - method: 'POST', - headers: {'X-Requested-With': 'XMLHttpRequest'}, - async: true, - }), - columnDefs: [ - { - orderable: false, - searchable: false, - targets: [lastColNr] - } - ], - columns : [ - { 'data': 'nombre' }, - { 'data': 'tipo' }, - { 'data': 'ancho_impresion' }, - { 'data': 'alto_impresion' }, - { 'data': 'min' }, - { 'data': 'max' }, - { 'data': actionBtns } - ] - }); - - - theTable.on( 'draw.dt', function () { - const boolCols = []; - for (let coln of boolCols) { - theTable.column(coln, { page: 'current' }).nodes().each( function (cell, i) { - cell.innerHTML = cell.innerHTML == '1' ? '' : ''; - }); - } - }); - - $(document).on('click', '.btn-edit', function(e) { - window.location.href = `/configuracion/maquinas/edit/${$(this).attr('data-id')}`; - }); - - $(document).on('click', '.btn-delete', function(e) { - $(".btn-remove").attr('data-id', $(this).attr('data-id')); - }); - - $(document).on('click', '.btn-remove', function(e) { - const dataId = $(this).attr('data-id'); - const row = $(this).closest('tr'); - if ($.isNumeric(dataId)) { - $.ajax({ - url: `/configuracion/maquinas/delete/${dataId}`, - method: 'GET', - }).done((data, textStatus, jqXHR) => { - $('#confirm2delete').modal('toggle'); - theTable.clearPipeline(); - theTable.row($(row)).invalidate().draw(); - popSuccessAlert(data.msg ?? jqXHR.statusText); - }).fail((jqXHR, textStatus, errorThrown) => { - popErrorAlert(jqXHR.responseJSON.messages.error) - }) - } - }); -endSection() ?> - - section('css') ?> "> endSection() ?> @@ -151,5 +56,7 @@ + + endSection() ?> diff --git a/httpdocs/assets/js/safekat/pages/maquinas/maquinasList.js b/httpdocs/assets/js/safekat/pages/maquinas/maquinasList.js new file mode 100644 index 00000000..e85d8208 --- /dev/null +++ b/httpdocs/assets/js/safekat/pages/maquinas/maquinasList.js @@ -0,0 +1,185 @@ +import Table from '../../components/table.js'; +import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js'; +import Ajax from '../../components/ajax.js'; +import { getToken } from '../../common/common.js'; + + +class MaquinasList { + + constructor() { + + this.domItem = $('.card-body'); + + this.csrf_token = getToken(); + this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val(); + + this.tableMaquinas = null; + this.deleteModal = null; + } + + init() { + + const self = this; + + this.headerSearcher(); + + this.deleteModal = new ConfirmDeleteModal('maquinas'); + this.deleteModal.init(); + + this.#initTable(); + + // Editar en linea la fila + this.tableMaquinas.table.on('click', '.btn-edit-' + this.tableMaquinas.getAlias(), function (e) { + + const dataId = $(this).attr('data-id'); + + if (!Number.isNaN(Number(dataId))) { + window.location.href = '/maquinas/edit/' + dataId; + } + }); + + // Eliminar la fila + this.tableMaquinas.table.on('click', '.btn-delete-' + this.tableMaquinas.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( + '/maquinas/delete/' + dataId, + { + + }, + {}, + (data, textStatus, jqXHR) => { + + self.tableMaquinas.table.clearPipeline(); + self.tableMaquinas.table.row($(row)).invalidate().draw(); + + popSuccessAlert(data.msg ?? jqXHR.statusText); + }, + (error) => { + console.log(error); + } + + ).get(); + self.deleteModal.hide(); + } + }); + }); + } + + #initTable() { + + const self = this; + + const columns = [ + { 'data': 'id' }, + { 'data': 'nombre' }, + { 'data': 'tipo' }, + { 'data': 'ancho_impresion' }, + { 'data': 'alto_impresion' }, + { 'data': 'min' }, + { 'data': 'max' } + ]; + + const actions = ['edit', 'delete']; + + this.tableMaquinas = new Table( + $('#tableOfMaquinas'), + 'maquinasList', + '/maquinas/datatable', + columns, + [] + ); + + + this.tableMaquinas.init({ + actions: actions, + colVisibility: false, + buttonsExport: true, + }); + + + this.tableMaquinas.table.on('init.dt', function () { + self.tableMaquinas.table.page.len(50).draw(); + }); + + } + + headerSearcher() { + + const self = this; + + $('#tableOfMaquinas thead tr').clone(false).appendTo('#tableOfMaquinas thead'); + $('#tableOfMaquinas thead tr:eq(1) th').each(function (i) { + + if (!$(this).hasClass("noFilter")) { + + let min_width = 100; + if (i == 0) { + min_width = 50; + } + + if (i == 2) { + + // Agregar un selector en la segunda columna + $(this).html(''); + + // Agregar opciones al selector + var selector = $('select', this); + selector.append(''); // Opción vacía + selector.append(''); + selector.append(''); + selector.append(''); + + selector.on('change', function () { + var val = $.fn.dataTable.util.escapeRegex( + $(this).val() + ); + self.tableMaquinas.table.column(i).search(val).draw(); + }); + + } + else { + $(this).html(``); + + $('input', this).on('change clear', function () { + if (self.tableMaquinas.table.column(i).search() !== this.value) { + self.tableMaquinas.table + .column(i) + .search(this.value) + .draw(); + } + }); + } + + + } + else { + $(this).html(''); + } + }); + + + } + +} + +document.addEventListener('DOMContentLoaded', function () { + + const locale = document.querySelector('meta[name="locale"]').getAttribute('content'); + + new Ajax('/translate/getTranslation', { locale: locale, translationFile: ['Maquinas'] }, {}, + function (translations) { + window.language = JSON.parse(translations); + new MaquinasList().init(); + }, + function (error) { + console.log("Error getting translations:", error); + } + ).post(); +}); +
ID
-
- - -
-