Merge branch 'main' into 'feat/facturas_tiradas_flex'

Main

See merge request jjimenez/safekat!301
This commit is contained in:
2024-08-06 07:17:43 +00:00
7 changed files with 317 additions and 35 deletions

View File

@ -245,13 +245,31 @@ class Pedido extends \App\Controllers\BaseResourceController
$estado = $reqData['estado'] ?? 'todos';
if($estado == 'todos') $estado = '';
$model_linea = model('\App\Models\Pedidos\PedidoLineaModel');
$resourceData = $model_linea->getResource($search, $estado)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
$showTotal = $reqData['showTotal'] ?? false;
$searchValues = get_filter_datatables_columns($reqData);
$model_linea = model('\App\Models\Pedidos\PedidoLineaModel');
$resourceData = $model_linea->getResource($searchValues, $estado)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
$totalTirada = $model_linea->getSumOfTirada($searchValues, $estado, $start, $length);
$total = $model_linea->getSumOfTotalAceptado($searchValues, $estado, $start, $length);
$total2 = 0;
if($showTotal){
$total2 = $model_linea->getTotalOfTotalAceptado();
}
if($total2 != 0){
$total = "" . $total . " \n(" . $total2 . ")";
}
return $this->respond(Collection::datatable(
$resourceData,
$model_linea->getResource("", $estado)->countAllResults(),
$model_linea->getResource($search, $estado)->countAllResults()
$model_linea->getResource($searchValues, $estado)->countAllResults(),
"",
[
'total_tirada' => $totalTirada,
'total' => $total
]
));
} else {
return $this->failUnauthorized('Invalid request', 403);

View File

@ -111,7 +111,7 @@ class Buscador extends \App\Controllers\BaseResourceController
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource("")->countAllResults(),
$this->model->getResource($search)->countAllResults()
$this->model->getResource($searchValues)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);

View File

@ -78,6 +78,8 @@ return [
'facturas' => 'Invoices',
'showTotal' => 'Show totals',
'validation' => [
],

View File

@ -78,6 +78,8 @@ return [
'facturas' => 'Facturas',
'showTotal' => 'Mostrar totales',
'validation' => [
],

View File

@ -15,7 +15,7 @@ class Collection
*
* @return array
*/
public static function datatable(array $data, int $recordsTotal, int $recordsFiltered, string $error = null)
public static function datatable(array $data, int $recordsTotal, int $recordsFiltered, string $error = null, $extra_data = [])
{
$draw = 1;
$req = service('request');
@ -38,6 +38,10 @@ class Collection
$response['error'] = $error;
}
if (count($extra_data)>0) {
$response['extra'] = $extra_data;
}
return $response;
}
}

View File

@ -14,12 +14,20 @@ class PedidoLineaModel extends \App\Models\BaseModel
protected $useAutoIncrement = true;
const SORTABLE = [
0 => "t1.id",
1 => "t1.estado",
2 => "t1.total_precio",
3 => "t1.total_tirada",
0 => "t2.id",
1 => "t2.updated_at",
2 => "t2.fecha_entrega_real",
3 => "t4.nombre",
4 => "CONCAT(t5.first_name, ' ', t5.last_name)",
5 => "t3.titulo",
6 => "t6.nombre",
7 => "t3.inc_rei",
8 => "t3.paginas",
9 => "t3.tirada",
10 => "t3.total_aceptado",
11 => "t2.estado"
];
protected $allowedFields = [
"pedido_id",
"presupuesto_id",
@ -40,7 +48,7 @@ class PedidoLineaModel extends \App\Models\BaseModel
public static $labelField = "id";
public function getResource(string $search = "", $estado="")
public function getResource($search = [], $estado="")
{
$builder = $this->db
->table($this->table . " t1")
@ -67,16 +75,112 @@ class PedidoLineaModel extends \App\Models\BaseModel
}
}
// Falta implementar la busqueda por grupos
return empty($search)
? $builder
: $builder
->groupStart()
->like("t1.id", $search)
->orLike("t1.id", $search)
->groupEnd();
if (empty($search))
return $builder;
else {
$builder->groupStart();
foreach ($search as $col_search) {
if ($col_search[0] != 1 && $col_search[0] != 2)
$builder->like(self::SORTABLE[$col_search[0]], $col_search[2]);
else {
$dates = explode(" ", $col_search[2]);
$builder->where(self::SORTABLE[$col_search[0]] . ">=", $dates[0]);
$builder->where(self::SORTABLE[$col_search[0]] . "<=", $dates[1]);
}
}
$builder->groupEnd();
return $builder;
}
}
public function getSumOfTirada(array $search, $estado = '', $start = 0, $length = 5)
{
$builder = $this->db
->table($this->table . " t1")
->selectSum('t3.tirada', 'total_tirada');
$builder->join("pedidos t2", "t2.id = t1.pedido_id", "left");
$builder->join("presupuestos t3", "t1.presupuesto_id = t3.id", "left");
// Aplica los filtros de búsqueda y estado
if (!empty($search)) {
$builder->groupStart();
foreach ($search as $col_search) {
if ($col_search[0] != 1 && $col_search[0] != 2)
$builder->like(self::SORTABLE[$col_search[0]], $col_search[2]);
else {
$dates = explode(" ", $col_search[2]);
$builder->where(self::SORTABLE[$col_search[0]] . ">=", $dates[0]);
$builder->where(self::SORTABLE[$col_search[0]] . "<=", $dates[1]);
}
}
$builder->groupEnd();
}
if ($estado !== '') {
$builder->where('estado', $estado);
}
// Aplicar el orden y el límite
$builder->limit($length, $start);
return $builder->get()->getRow()->total_tirada;
}
public function getSumOfTotalAceptado(array $search, $estado = '', $start = 0, $length = 5)
{
$builder = $this->db
->table($this->table . " t1")
->selectSum('t3.total_aceptado', 'total');
$builder->join("pedidos t2", "t2.id = t1.pedido_id", "left");
$builder->join("presupuestos t3", "t1.presupuesto_id = t3.id", "left");
// Aplica los filtros de búsqueda y estado
if (!empty($search)) {
$builder->groupStart();
foreach ($search as $col_search) {
if ($col_search[0] != 1 && $col_search[0] != 2)
$builder->like(self::SORTABLE[$col_search[0]], $col_search[2]);
else {
$dates = explode(" ", $col_search[2]);
$builder->where(self::SORTABLE[$col_search[0]] . ">=", $dates[0]);
$builder->where(self::SORTABLE[$col_search[0]] . "<=", $dates[1]);
}
}
$builder->groupEnd();
}
if ($estado !== '') {
$builder->where('estado', $estado);
}
// Aplicar el orden y el límite
$builder
->limit($length, $start);
return $builder->get()->getRow()->total;
}
public function getTotalOfTotalAceptado()
{
$builder = $this->db
->table($this->table . " t1")
->selectSum('t3.total_aceptado', 'total');
$builder->join("pedidos t2", "t2.id = t1.pedido_id", "left");
$builder->join("presupuestos t3", "t1.presupuesto_id = t3.id", "left");
return $builder->get()->getRow()->total;
}
public function obtenerLineasPedidoSinFacturar($cliente_id) {
$resultaArray = [];

View File

@ -11,6 +11,14 @@
</div><!--//.card-header -->
<div class="card-body">
<?= view('themes/_commonPartialsBs/_alertBoxes'); ?>
<div class="row">
<div class="form-check form-check-inline">
<input type="checkbox" class="form-check-input" id="showTotal" name="showTotal">
<label for="showTotal" class="form-check-label">
<?= lang('Pedidos.showTotal') ?>
</label>
</div>
</div>
<table id="tableOfPedidos" class="table table-striped table-hover" style="width: 100%;">
<thead>
@ -23,11 +31,11 @@
<th><?= lang('Pedidos.titulo') ?></th>
<th><?= lang('Pedidos.ubicacion') ?></th>
<th><?= lang('Pedidos.inc_rei') ?></th>
<th><?= lang('Pedidos.num_paginas') ?></th>
<th><?= lang('Pedidos.tiradas') ?></th>
<th><?= lang('Pedidos.total_presupuesto') ?></th>
<th class='noFilter'><?= lang('Pedidos.num_paginas') ?></th>
<th class='totalizador'><?= lang('Pedidos.tiradas') ?></th>
<th class='totalizador'><?= lang('Pedidos.total_presupuesto') ?></th>
<th><?= lang('Pedidos.estado') ?></th>
<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
<th class="noFilter text-nowrap"><?= lang('Basic.global.Action') ?></th>
</tr>
</thead>
<tbody>
@ -57,24 +65,130 @@
</td>`;
};
theTable = $('#tableOfPedidos').DataTable({
// Setup - add a text input to each footer cell
$('#tableOfPedidos thead tr').clone(true).appendTo('#tableOfPedidos thead');
$('#tableOfPedidos thead tr:eq(1) th').each(function (i) {
if (!$(this).hasClass("noFilter")) {
var title = $(this).text();
if($(this).hasClass("totalizador")){
if(i==9){
$(this).html('<label id="total_tirada" />');
}
else if(i==10){
$(this).html('<label id="total_aceptado" />');
}
}
else{
if(i==1 || i==2){
name = 'bs-rangepicker-range_' + i;
$(this).html('<input id="'+name+'" type="text" class="form-control " style="min-width:100px;max-width:120px;font-size:0.8rem !important;" />');
var bsRangePickerRange = $('#' + name);
bsRangePickerRange.daterangepicker({
ranges: {
'<?= lang('datePicker.hoy') ?>': [moment(), moment()],
'<?= lang('datePicker.ayer') ?>': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'<?= lang('datePicker.ultimos7') ?>': [moment().subtract(6, 'days'), moment()],
'<?= lang('datePicker.ultimos30') ?>': [moment().subtract(29, 'days'), moment()],
'<?= lang('datePicker.esteMes') ?>': [moment().startOf('month'), moment().endOf('month')],
'<?= lang('datePicker.ultimoMes') ?>': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
opens: 'right',
language: '<?= config('Basics')->i18n ?>',
"locale": {
"customRangeLabel": "<?= lang('datePicker.personalizar') ?>",
"format": "YYYY-MM-DD",
"separator": " ",
"applyLabel": "<?= lang('datePicker.aplicar') ?>",
"cancelLabel": "<?= lang('datePicker.limpiar') ?>",
},
"alwaysShowCalendars": true,
autoUpdateInput: false,
});
bsRangePickerRange.on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('YYYY-MM-DD') + ' ' + picker.endDate.format('YYYY-MM-DD'));
theTable
.column(i)
.search(this.value)
.draw();
});
bsRangePickerRange.on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
theTable
.column(i)
.search(this.value)
.draw();
});
}
else if (i == 11) {
// Agregar un selector en la tercera 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="validacion"><?= lang('Pedidos.validacion') ?></option>');
selector.append('<option value="produccion"><?= lang('Pedidos.produccion') ?></option>');
selector.append('<option value="finalizado"><?= lang('Pedidos.finalizado') ?></option>');
selector.append('<option value="enviado"><?= lang('Pedidos.enviado') ?></option>');
selector.append('<option value="cancelado"><?= lang('Pedidos.cancelado') ?></option>');
selector.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
theTable.column(i).search(val).draw();
});
}
else{
$(this).html('<input type="text" class="form-control " style="min-width:100px;max-width:120px;font-size:0.8rem !important;" />');
$('input', this).on('change clear', function () {
if (theTable.column(i).search() !== this.value) {
theTable
.column(i)
.search(this.value)
.draw();
}
});
}
}
}
else {
$(this).html('<span></span>');
}
});
var theTable = $('#tableOfPedidos').DataTable({
select: {
style: 'multi',
info: false
},
orderCellsTop: true,
fixedHeader: true,
processing: true,
serverSide: true,
autoWidth: true,
responsive: true,
searching: true,
scrollX: true,
lengthMenu: [ 5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500 ],
pageLength: 50,
pageLength: 100,
lengthChange: true,
"dom": 'lfBrtip',
"dom": '<"mb-3"l>Brtip',
"buttons": [
'copy', 'csv', 'excel', 'print', {
'colvis', 'copy', 'csv', 'excel', 'print', {
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'A4'
}
],
stateSave: true,
stateSave: false,
order: [[0, 'asc']],
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
@ -82,8 +196,9 @@
ajax : $.fn.dataTable.pipeline( {
url: '<?= route_to('dataTableOfPedidos') ?>',
method: 'POST',
data: {
estado: "<?= $estadoPedidos ?>",
data: function(d, settings){
d.estado= "<?= $estadoPedidos ?>";
d.showTotal= $('#showTotal').is(':checked')? "1":"0";
},
headers: {'X-Requested-With': 'XMLHttpRequest'},
async: true,
@ -91,7 +206,7 @@
columnDefs: [
{
orderable: false,
searchable: false,
searchable: true,
targets: [lastColNr]
}
],
@ -138,39 +253,76 @@
}
},
{ 'data': actionBtns }
]
],
drawCallback: function (settings) {
$('#total_tirada').text(settings.json.extra.total_tirada);
$('#total_aceptado').text(settings.json.extra.total);
}
});
theTable.on( 'draw.dt', function () {
const boolCols = [];
for (let coln of boolCols) {
const dateCols = [1,2];
const priceCols = [10];
for (let coln of dateCols) {
theTable.column(coln, { page: 'current' }).nodes().each( function (cell, i) {
cell.innerHTML = cell.innerHTML == '1' ? '<i class="ti ti-check"></i>' : '';
const datestr = cell.innerHTML;
const dateStrLen = datestr.toString().trim().length;
if (dateStrLen > 0) {
let dateTimeParts= datestr.split(/[- :]/); // regular expression split that creates array with: year, month, day, hour, minutes, seconds values
dateTimeParts[1]--; // monthIndex begins with 0 for January and ends with 11 for December so we need to decrement by one
const d = new Date(...dateTimeParts); // new Date(datestr);
cell.innerHTML = d.toLocaleDateString();
}
});
}
for (let coln of priceCols) {
theTable.column(coln, { page: 'current' }).nodes().each( function (cell, i) {
cell.innerHTML = parseFloat(cell.innerHTML).toFixed(2);
});
}
});
$(document).on('click', '.btn-edit', function(e) {
var url = '<?= route_to('editarPedido', ':id') ?>';
url = url.replace(':id', `${$(this).attr('data-id')}` );
window.location.href = url;
});
theTable.on('click', 'tbody tr', function (e) {
e.currentTarget.classList.toggle('selected');
});
$('#showTotal').on('change', function() {
theTable.clearPipeline();
theTable.ajax.reload(null, false);
//theTable.draw();
});
<?=$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/datatables-sk/plugins/fixedheader/fixedHeader.dataTables.min.css") ?>">
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/bootstrap-daterangepicker/bootstrap-daterangepicker.css') ?>" />
<?=$this->endSection() ?>
<?= $this->section('additionalExternalJs') ?>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/dataTables.buttons.min.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/datatables-sk/plugins/select/dataTables.select.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.html5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.print.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.colVis.min.js") ?>"></script>
<script src="<?= site_url('themes/vuexy/vendor/libs/moment/moment.js') ?>"></script>
<script src="<?= site_url('themes/vuexy/vendor/libs/bootstrap-daterangepicker/bootstrap-daterangepicker.js') ?>"></script>
<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>