Modificado Paises al metodo JS

This commit is contained in:
unknown
2025-04-09 00:37:30 +02:00
parent b7c5c328da
commit af57f7d5ae
8 changed files with 169 additions and 192 deletions

View File

@ -12,10 +12,11 @@ $routes->group('configuracion', ['namespace' => 'App\Controllers\Configuracion']
$routes->get('', 'Paises::index', ['as' => 'paisList']);
$routes->get('add', 'Paises::add', ['as' => 'newPais']);
$routes->post('add', 'Paises::add', ['as' => 'createPais']);
$routes->get('delete/(:num)', 'Paises::delete/$1');
$routes->post('create', 'Paises::create', ['as' => 'ajaxCreatePais']);
$routes->put('update/(:num)', 'Paises::update/$1', ['as' => 'ajaxUpdatePais']);
$routes->match(['get', 'post'], 'edit/(:num)', 'Paises::edit/$1', ['as' => 'updatePais']);
$routes->post('datatable', 'Paises::datatable', ['as' => 'dataTableOfPaises']);
$routes->get('datatable', 'Paises::datatable', ['as' => 'dataTableOfPaises']);
$routes->post('allmenuitems', 'Paises::allItemsSelect', ['as' => 'select2ItemsOfPaises']);
$routes->post('menuitems', 'Paises::menuItems', ['as' => 'menuItemsOfPaises']);
$routes->get('menuitems2', 'Paises::menuItems2', ['as' => 'menuItemsOfPaises2']);

View File

@ -88,7 +88,7 @@ class Routing extends BaseRouting
*
* If FALSE, will stop searching and do NO automatic routing.
*/
public bool $autoRoute = true;
public bool $autoRoute = false;
/**
* If TRUE, will enable the use of the 'prioritize' option

View File

@ -1,4 +1,5 @@
<?php namespace App\Controllers\Configuracion;
<?php
namespace App\Controllers\Configuracion;
use App\Controllers\BaseResourceController;
@ -9,6 +10,8 @@ use App\Entities\Configuracion\PaisEntity;
use App\Models\Configuracion\PaisModel;
use Hermawan\DataTables\DataTable;
class Paises extends \App\Controllers\BaseResourceController
{
@ -62,17 +65,17 @@ class Paises extends \App\Controllers\BaseResourceController
public function add()
{
if ($this->request->getPost()) :
if ($this->request->getPost()):
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, true);
$noException = true;
if ($successfulResult = $this->canValidate()) :
if ($successfulResult = $this->canValidate()):
if ($this->canValidate()) :
if ($this->canValidate()):
try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) {
@ -86,14 +89,14 @@ class Paises 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);
else:
return $this->redirect2listView('sweet-success', $message);
@ -117,20 +120,20 @@ class Paises extends \App\Controllers\BaseResourceController
public function edit($requestedId = null)
{
if ($requestedId == null) :
if ($requestedId == null):
return $this->redirect2listView();
endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
$paisEntity = $this->model->find($id);
if ($paisEntity == false) :
if ($paisEntity == false):
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Paises.pais')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->getPost()) :
if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -143,10 +146,10 @@ class Paises extends \App\Controllers\BaseResourceController
$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)->update($id, $sanitizedData);
} catch (\Exception $e) {
@ -163,12 +166,12 @@ class Paises extends \App\Controllers\BaseResourceController
$thenRedirect = false;
endif;
if ($noException && $successfulResult) :
if ($noException && $successfulResult):
$id = $paisEntity->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);
@ -193,30 +196,38 @@ class Paises extends \App\Controllers\BaseResourceController
public function datatable()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$order = PaisModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$q = $this->model->getDatatableQuery();
$resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
$result = DataTable::of($q)
->edit(
"show_erp",
function ($row, $meta) {
if($row->show_erp == 1) {
return '<i class="ti ti-check"></i>';
}else{
return '';
}
}
)
->add("actionBtns", callback: function ($q) {
$actions = '';
if (auth()->user()->can('paises.edit')) {
$actions .= '
<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="' . $q->id . '"></i></a>
</div>';
}
if (auth()->user()->can('paises.delete')) {
$actions .= '
<div class="btn-group btn-group-sm">
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="' . $q->id . '"></i></a>
</div>';
}
return $actions;
});
return $result->toJson(returnAsObject: true);
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),
$this->model->getResource($search)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function allItemsSelect()
@ -277,7 +288,7 @@ class Paises extends \App\Controllers\BaseResourceController
"id",
"nombre as name"
]
)->orderBy("nombre", "asc");
)->orderBy("nombre", "asc");
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("lg_paises.nombre", $this->request->getGet("q"))

View File

@ -14,7 +14,7 @@ class PaisEntity extends \CodeIgniter\Entity\Entity
"url_erp" => null,
"user_erp" => null,
"key_erp" => null,
"show_erp" => false,
"show_erp" => null,
];
protected $casts = [
"show_erp" => "boolean",

View File

@ -12,17 +12,6 @@ class PaisModel extends \App\Models\BaseModel
*/
protected $useAutoIncrement = true;
const SORTABLE = [
1 => "t1.id",
2 => "t1.nombre",
3 => "t1.code",
4 => "t1.code3",
5 => "t1.moneda",
6 => "t1.url_erp",
7 => "t1.user_erp",
8 => "t1.key_erp",
9 => "t1.show_erp",
];
protected $allowedFields = ["nombre", "code", "code3", "moneda", "url_erp", "user_erp", "key_erp", "show_erp"];
protected $returnType = "App\Entities\Configuracion\PaisEntity";
@ -91,38 +80,24 @@ class PaisModel extends \App\Models\BaseModel
/**
* Get resource data.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResource(string $search = "")
public function getDatatableQuery()
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id AS id, t1.nombre AS nombre, t1.code AS code, t1.code3 AS code3, t1.moneda AS moneda, t1.url_erp AS url_erp, t1.user_erp AS user_erp, t1.key_erp AS key_erp, t1.show_erp AS show_erp"
"t1.id AS id,
t1.nombre AS nombre,
t1.code AS code,
t1.code3 AS code3,
t1.moneda AS moneda,
t1.url_erp AS url_erp,
t1.user_erp AS user_erp,
t1.key_erp AS key_erp,
t1.show_erp AS show_erp"
);
return empty($search)
? $builder
: $builder
->groupStart()
->like("t1.id", $search)
->orLike("t1.nombre", $search)
->orLike("t1.code", $search)
->orLike("t1.code3", $search)
->orLike("t1.moneda", $search)
->orLike("t1.url_erp", $search)
->orLike("t1.user_erp", $search)
->orLike("t1.key_erp", $search)
->orLike("t1.id", $search)
->orLike("t1.nombre", $search)
->orLike("t1.code", $search)
->orLike("t1.code3", $search)
->orLike("t1.moneda", $search)
->orLike("t1.url_erp", $search)
->orLike("t1.user_erp", $search)
->orLike("t1.key_erp", $search)
->groupEnd();
return $builder;
}
}

View File

@ -1,5 +1,5 @@
<?= $this->include("themes_commonPartialsBs/select2bs5") ?>
<?= $this->include("themes_commonPartialsBs/sweetalert") ?>
<?= $this->include("themes/_commonPartialsBs/select2bs5") ?>
<?= $this->include("themes/_commonPartialsBs/sweetalert") ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section("content") ?>
<div class="row">
@ -11,7 +11,7 @@
<form id="paisForm" method="post" action="<?= $formAction ?>">
<?= csrf_field() ?>
<div class="card-body">
<?= view("themes_commonPartialsBs/_alertBoxes") ?>
<?= view("themes/_commonPartialsBs/_alertBoxes") ?>
<?= !empty($validation->getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?>
<?= view("themes/vuexy/form/configuracion/paises/_paisFormItems") ?>
</div><!-- /.card-body -->

View File

@ -25,7 +25,7 @@
<th><?= lang('Paises.userErp') ?></th>
<th><?= lang('Paises.keyErp') ?></th>
<th><?= lang('Paises.showErp') ?></th>
<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
<th class="text-nowrap" style="min-width: 85px;"><?= lang('Basic.global.Action') ?></th>
</tr>
</thead>
<tbody>
@ -43,119 +43,10 @@
<?=$this->endSection() ?>
<?=$this->section('additionalInlineJs') ?>
const lastColNr = $('#tableOfPaises').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">
<button class="btn btn-sm btn-warning btn-edit me-1" data-id="${data.id}"><?= lang('Basic.global.edit') ?></button>
<button class="btn btn-sm btn-danger btn-delete ms-1" data-id="${data.id}"><?= lang('Basic.global.Delete') ?></button>
</div>
</td>`;
};
theTable = $('#tableOfPaises').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: [[1, 'asc']],
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
ajax : $.fn.dataTable.pipeline( {
url: '<?= route_to('dataTableOfPaises') ?>',
method: 'POST',
headers: {'X-Requested-With': 'XMLHttpRequest'},
async: true,
}),
columnDefs: [
{
orderable: false,
searchable: false,
targets: [lastColNr]
}
],
columns : [
{ 'data': 'nombre' },
{ 'data': 'code' },
{ 'data': 'code3' },
{ 'data': 'moneda' },
{ 'data': 'url_erp' },
{ 'data': 'user_erp' },
{ 'data': 'key_erp' },
{ 'data': 'show_erp' },
{ 'data': actionBtns }
]
});
theTable.on( 'draw.dt', function () {
const boolCols = [7];
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 = `<?= route_to('paisList') ?>/edit/${$(this).attr('data-id')}`;
});
$(document).on('click', '.btn-delete', function(e) {
Swal.fire({
title: '<?= lang('Basic.global.sweet.sureToDeleteTitle', [mb_strtolower(lang('Paises.pais'))]) ?>',
text: '<?= lang('Basic.global.sweet.sureToDeleteText') ?>',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
confirmButtonText: '<?= lang('Basic.global.sweet.deleteConfirmationButton') ?>',
cancelButtonText: '<?= lang('Basic.global.Cancel') ?>',
cancelButtonColor: '#d33'
})
.then((result) => {
const dataId = $(this).data('id');
const row = $(this).closest('tr');
if (result.value) {
$.ajax({
url: `<?= route_to('paisList') ?>/${dataId}`,
method: 'DELETE',
}).done((data, textStatus, jqXHR) => {
Toast.fire({
icon: 'success',
title: data.msg ?? jqXHR.statusText,
});
theTable.clearPipeline();
theTable.row($(row)).invalidate().draw();
}).fail((jqXHR, textStatus, errorThrown) => {
Toast.fire({
icon: 'error',
title: 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") ?>">
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.css') ?>" />
<?=$this->endSection() ?>
@ -167,5 +58,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 src="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.js') ?>"></script>
<script type="module" src="<?= site_url("assets/js/safekat/pages/paises/list.js") ?>"></script>
<?=$this->endSection() ?>

View File

@ -0,0 +1,97 @@
import Ajax from '../../components/ajax.js';
document.addEventListener('DOMContentLoaded', function () {
const lastColNr = $('#tableOfPaises').find("tr:first th").length - 1;
const theTable = $('#tableOfPaises').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: [[1, 'asc']],
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
ajax: {
url: '/configuracion/paises/datatable',
method: 'GET'
},
columnDefs: [
{
orderable: false,
searchable: false,
targets: [lastColNr]
}
],
columns: [
{ data: 'nombre' },
{ data: 'code' },
{ data: 'code3' },
{ data: 'moneda' },
{ data: 'url_erp' },
{ data: 'user_erp' },
{ data: 'key_erp' },
{ data: 'show_erp' },
{ data: 'actionBtns' }
]
});
$(document).on('click', '.btn-edit', function (e) {
window.location.href = '/configuracion/paises/edit/' + $(this).attr('data-id');
});
$(document).on('click', '.btn-delete', function (e) {
e.preventDefault();
const row = $(this).closest('tr')[0]._DT_RowIndex;
const dataId = $(this).attr('data-id');
Swal.fire({
title: '¿Estás seguro?',
text: 'Esta acción no se puede deshacer.',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Sí',
cancelButtonText: 'No',
reverseButtons: false,
buttonsStyling: true,
customClass: {
confirmButton: 'btn btn-danger', // rojo para "Sí"
cancelButton: 'btn btn-secondary' // gris para "No"
}
}).then((result) => {
if (result.isConfirmed) {
new Ajax(
'/configuracion/paises/delete/' + dataId,
{},
{},
(data, textStatus, jqXHR) => {
theTable.clearPipeline();
theTable.row($(row)).invalidate().draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
},
(error) => {
console.error(error);
Swal.fire('Error', 'No se pudo eliminar el país.', 'error');
}
).get();
}
});
});
});