modificado el listado de maquinas

This commit is contained in:
2024-12-15 13:14:30 +01:00
parent 8d25991ddc
commit fce30342a7
5 changed files with 286 additions and 198 deletions

View File

@ -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']);

View File

@ -1,4 +1,5 @@
<?php namespace App\Controllers\Configuracion;
<?php
namespace App\Controllers\Configuracion;
use App\Controllers\BaseResourceController;
@ -65,14 +66,50 @@ class Maquinas extends \App\Controllers\BaseResourceController
return view(static::$viewPath . 'viewMaquinaList', $viewData);
}
public function delete($id = null)
{
// Sanitizar el ID
$id = filter_var($id, FILTER_SANITIZE_URL);
// Validar que el ID es válido
if (empty($id) || !is_numeric($id)) {
return $this->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;

View File

@ -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)

View File

@ -18,13 +18,14 @@
<table id="tableOfMaquinas" class="table table-striped table-hover" style="width: 100%;">
<thead>
<tr>
<th style="max-width: 50px;">ID</th>
<th><?= lang('Maquinas.nombre') ?></th>
<th><?= lang('Maquinas.tipo') ?></th>
<th><?= lang('Maquinas.anchoImpresion') ?></th>
<th><?= lang('Maquinas.altoImpresion') ?></th>
<th><?= lang('Maquinas.min') ?></th>
<th><?= lang('Maquinas.max') ?></th>
<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
<th class="text-nowrap noFilter" style="min-width:80px;"><?= lang('Basic.global.Action') ?></th>
</tr>
</thead>
<tbody>
@ -42,102 +43,6 @@
<?=$this->endSection() ?>
<?=$this->section('additionalInlineJs') ?>
const lastColNr = $('#tableOfMaquinas').find("tr:first th").length - 1;
const actionBtns = function(data) {
return `
<td class="text-right py-0 align-middle">
<div class="btn-group btn-group-sm">
<a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="${data.id}"></i></a>
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="${data.id}" data-bs-toggle="modal" data-bs-target="#confirm2delete"></i></a>
</div>
</td>`;
};
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: '<?= route_to('dataTableOfMaquinas') ?>',
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' ? '<i class="text-success bi bi-check-lg"></i>' : '';
});
}
});
$(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)
})
}
});
<?=$this->endSection() ?>
<?=$this->section('css') ?>
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
<?=$this->endSection() ?>
@ -151,5 +56,7 @@
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/jszip/jszip.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/pdfmake.min.js") ?>" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/vfs_fonts.js") ?>"></script>
<script type="module" src="<?= site_url('assets/js/safekat/pages/maquinas/maquinasList.js') ?>"></script>
<?=$this->endSection() ?>

View File

@ -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('<select class="form-control" style="min-width:100px;max-width:120px;font-size:0.8rem !important;"></select>');
// Agregar opciones al selector
var selector = $('select', this);
selector.append('<option value="">Todos</option>'); // Opción vacía
selector.append('<option value="acabado">Acabado</option>');
selector.append('<option value="manipulado">Manupulado</option>');
selector.append('<option value="impresion">Impresión</option>');
selector.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tableMaquinas.table.column(i).search(val).draw();
});
}
else {
$(this).html(`<input type="text" class="form-control " style="min-width:${min_width}px;max-width:500px;font-size:0.8rem !important;" />`);
$('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('<span></span>');
}
});
}
}
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();
});