Merge branch 'main' into feat/revision-ot-2

This commit is contained in:
amazuecos
2025-05-05 00:48:01 +02:00
20 changed files with 2260 additions and 13 deletions

View File

@ -88,6 +88,9 @@ let ClassSelect = function (domItem, url, placeholder, allowClear = false, param
this.getText = () => {
return this.item.find(":selected").text();
};
this.getDesc = () => {
return this.item.find(":selected").data("desc");
};
this.onChange = function (callback) {
this.item.on('change', callback);
};

View File

@ -0,0 +1,467 @@
import ClassSelect from '../../components/select2.js';
import Ajax from '../../components/ajax.js';
import AlbaranComponent from '../../components/albaranComponent.js';
class EtiquetaEdit {
constructor() {
this.tableCols = [
{ data: "rowSelected" },
{ data: "ot" },
{ data: "titulo" },
{ data: "numero_caja" },
{ data: "unidades" },
{ data: "unidadesTotal" },
{ data: "id" },
{ data: "pesoUnidad" },
{ data: "unidadesRaw" },
{ data: "action" },
{ data: "numero_caja_raw" }
];
this.table = null;
this.direccion = $('#direccion');
this.addLineas = $('#btnAddLinea');
this.btnEliminarLineas = $('#btnEliminarLineas');
this.btbnGuardarComentarios = $('#guardarComentarios');
this.btnSelectAll = $('#btnSelectAll');
this.btnRenumber = $('#btnRenumber');
this.btnImprimirEtiquetas = $('#btnImprimirEtiquetas');
this.buscador = new ClassSelect($('#buscadorPedidos'), '/etiquetasTitulos/findOts', '', true, { 'id': $('#id').val() });
}
init() {
const self = this;
this._initDatatable();
this.buscador.init();
this.addLineas.on('click', this._addLineas.bind(this));
$(document).on('click', '.btn-delete', this._deleteLinea.bind(this));
$(document).on('change', '.input-lineas', this._updateLinea.bind(this));
this.btnEliminarLineas.on('click', this._deleteLinea.bind(this));
this.btbnGuardarComentarios.on('click', this._guardarComentarios.bind(this));
this.btnSelectAll.on('click', this._selectAll.bind(this));
this.btnRenumber.on('click', this._renumber.bind(this));
this.btnImprimirEtiquetas.on('click', this._imprimirEtiquetas.bind(this));
}
_imprimirEtiquetas() {
const self = this;
const ids = [];
this.table.rows().every(function (rowIdx, tableLoop, rowLoop) {
const node = this.node(); // DOM del tr
const checkbox = $(node).find('.checkbox-linea-envio');
if (checkbox.is(':checked')) {
const data = this.data();
ids.push(data.id);
}
});
$.post(
'/etiquetasTitulos/imprimirEtiquetas',
{
etiqueta_id: $('#id').val(),
ids: ids,
impresora_id: $('#impresoraEtiquetas').val()
},
function (response) {
if (response.status) {
popSuccessAlert(response.message);
if(response.data) {
// show xml in new tab
const blob = new Blob([response.data], { type: 'application/xml' });
const url = URL.createObjectURL(blob);
const newTab = window.open(url, '_blank');
if (newTab) {
newTab.onload = function () {
// Revoke the object URL after the new tab has loaded
URL.revokeObjectURL(url);
};
} else {
popErrorAlert('Error abriendo la pestaña');
}
}
} else {
popErrorAlert('Error imprimiendo las etiquetas');
}
}
).fail(function (xhr, status, error) {
popErrorAlert(error);
});
}
_renumber() {
const self = this;
$.post(
'/etiquetasTitulos/renumber',
{
id: $('#id').val()
},
function (response) {
if (response.status) {
self.table.ajax.reload();
popSuccessAlert(response.message);
} else {
popErrorAlert('Error renumerando las lineas');
}
}
).fail(function (xhr, status, error) {
popErrorAlert(error);
});
}
_selectAll() {
const checkboxes = this.table.$('input[type="checkbox"]');
const allChecked = checkboxes.length === checkboxes.filter(':checked').length;
checkboxes.prop('checked', !allChecked);
}
_initDatatable() {
const self = this;
this.table = $('#tableLineasEtiqueta').DataTable({
processing: true,
serverSide: true,
autoWidth: true,
responsive: true,
scrollX: true,
orderCellsTop: true,
rowId: 'id',
order: [[10, 'asc']],
rowGroup: {
dataSrc: 'numero_caja_raw',
startRender: function (rows, group) {
let totalUnidades = 0;
let totalPeso = 0;
rows.data().each(function (row) {
const unidades = parseFloat(row.unidadesRaw) || 0;
const pesoUnidad = parseFloat(row.pesoUnidad) || 0;
totalUnidades += unidades;
totalPeso += unidades * pesoUnidad;
});
const groupId = 'grupo-caja-' + group;
return $('<tr/>')
.attr('data-group', groupId)
.addClass('group-header bg-light fw-bold')
.css('cursor', 'pointer')
.append(
`<td colspan="11">
📦 CAJA ${group} UNIDADES: ${totalUnidades} PESO: ${totalPeso.toFixed(2)} kg
</td>`
);
}
},
rowReorder: {
dataSrc: 'numero_caja_raw',
update: false,
selector: 'td:not(.dt-no-reorder)' // evita inputs
},
lengthMenu: [5, 10, 25, 50, 100],
pageLength: 50,
ajax: {
url: "/etiquetasTitulos/datatableLineas/" + $('#id').val(),
data: function (d) {
d.direccion = $('#direccion').val();
d.id = $('#id').val();
},
},
columns: this.tableCols,
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
columnDefs: [
{
targets: [0, 9],
className: "text-center dt-no-reorder",
orderable: false,
searchable: false
},
{
targets: [3, 4],
className: "text-center dt-no-reorder"
},
{
targets: [1, 2, 4, 5, 6],
className: "text-center"
},
{
targets: [6, 7, 8, 10],
visible: false
}
]
});
$('#tableLineasEtiqueta tbody').on('click', 'tr.group-header', function () {
const group = $(this).data('group');
const table = $('#tableLineasEtiqueta').DataTable();
const icon = $(this).find('.group-toggle-icon');
let visible = true;
table.rows().every(function () {
const row = this.node();
const data = this.data();
if ('numero_caja' in data && ('grupo-caja-' + data.numero_caja) === group) {
if (!$(row).hasClass('group-header')) {
$(row).toggle();
visible = !$(row).is(':visible');
}
}
});
// Cambiar el icono
icon.text(visible ? '▼' : '►');
});
this.table.on('row-reorder', function (e, diff, edit) {
if (!diff.length || !edit.triggerRow) return;
const table = self.table;
const movedRowData = table.row(edit.triggerRow).data();
if (!movedRowData?.id) return;
const movedItem = diff.find(d => {
const rowData = table.row(d.node).data();
return rowData?.id === movedRowData.id;
});
if (!movedItem) return;
const payload = {
id: movedRowData.id,
numero_caja: movedItem.newData
};
$.ajax({
url: '/etiquetasTitulos/updateOrdenCajas',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ orden: [payload] }),
success: function (response) {
if (response.status) {
setTimeout(() => {
self.table.ajax.reload(null, false);
}, 100);
} else {
popErrorAlert('Error actualizando el orden');
}
},
error: function () {
popErrorAlert('Error en la solicitud AJAX');
}
});
});
}
_addLineas() {
if (this.buscador.item.select2('data').length > 0) {
let maxUnidades = 0;
if (this.buscador.item.select2('data')[0].desc) {
maxUnidades = parseInt(this.buscador.item.select2('data')[0].desc);
Swal.fire({
title: 'Unidades',
html: `
<div class="mb-2">
<label for="inputUnidades">Unidades:</label>
<input type="number" id="inputUnidades" class="swal2-input" value="${maxUnidades}">
</div>
<div>
<label for="inputCajas">Cajas:</label>
<input type="number" id="inputCajas" class="swal2-input" value="1">
</div>
`,
icon: 'info',
showCancelButton: true,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Aceptar',
cancelButtonText: 'Cancelar',
customClass: {
confirmButton: 'btn btn-primary me-1',
cancelButton: 'btn btn-secondary'
},
buttonsStyling: false,
preConfirm: () => {
const unidades = parseInt(document.getElementById('inputUnidades').value);
const cajas = parseInt(document.getElementById('inputCajas').value);
if (isNaN(unidades) || isNaN(cajas)) {
Swal.showValidationMessage('Debe completar ambos campos');
}
return { unidades, cajas };
}
}).then((result) => {
if (result.isConfirmed) {
const { unidades, cajas } = result.value;
const url = '/etiquetasTitulos/addLineas';
const data = {
etiqueta_id: $('#id').val(),
ot_id: this.buscador.getVal(),
unidades: unidades,
cajas: cajas
};
$.post(
url,
data,
function (response) {
if (response.status) {
self.table.ajax.reload();
popSuccessAlert(response.message);
} else {
popErrorAlert('Error en la respuesta');
}
}
).fail(function (xhr, status, error) {
popErrorAlert(error);
});
}
});
}
}
}
_deleteLinea(e) {
e.preventDefault();
const self = this;
let ids = [];
if (e.currentTarget.id == "btnEliminarLineas") {
this.table.rows().every(function (rowIdx, tableLoop, rowLoop) {
const node = this.node(); // DOM del tr
const checkbox = $(node).find('.checkbox-linea-envio');
if (checkbox.is(':checked')) {
const data = this.data();
ids.push(data.id);
}
});
}
else {
ids.push($(e.currentTarget).attr('data-id'));
}
Swal.fire({
title: '¿Está seguro de eliminar la linea?',
text: "No podrá revertir esta acción",
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Sí',
cancelButtonText: 'Cancelar',
customClass: {
confirmButton: 'btn btn-danger me-1',
cancelButton: 'btn btn-secondary'
},
buttonsStyling: false
}).then((result) => {
if (result.isConfirmed) {
$.post(
'/etiquetasTitulos/deleteLineas',
{
ids: ids
},
function (response) {
if (response.status) {
self.table.ajax.reload();
popSuccessAlert(response.message);
} else {
popErrorAlert('Error borrando la etiqueta');
}
}
).fail(function (xhr, status, error) {
popErrorAlert(error);
});
}
})
}
_updateLinea(e) {
e.preventDefault();
const self = this;
const id = $(e.currentTarget).attr('data-id');
const name = $(e.currentTarget).attr('data-name');
const value = $(e.currentTarget).val();
const url = '/etiquetasTitulos/updateLineas';
const data = {
id: id,
name: name,
value: value
};
$.post(
url,
data,
function (response) {
if (!response.status) {
popErrorAlert('Error actualizando la linea');
}
else {
self.table.ajax.reload();
}
}
).fail(function (xhr, status, error) {
popErrorAlert(error);
});
}
_guardarComentarios() {
const self = this;
const id = $('#id').val();
const comentarios = $('#comentarios').val();
const url = '/etiquetasTitulos/updateComentarios';
const data = {
id: id,
comentarios: comentarios
};
$.post(
url,
data,
function (response) {
if (!response.status) {
popErrorAlert('Error actualizando comentarios');
}
else {
popSuccessAlert(response.message);
}
}
).fail(function (xhr, status, error) {
popErrorAlert(error);
});
}
}
document.addEventListener('DOMContentLoaded', function () {
/*const dropdown = document.querySelector(".dropdown-language");
const activeItem = dropdown.querySelector(".dropdown-menu .dropdown-item");
let locale = 'es';
if (activeItem) {
locale = activeItem.getAttribute("data-language");
}
new Ajax('/translate/getTranslation', { locale: locale, translationFile: [] }, {},
function (translations) {
window.language = JSON.parse(translations);
new EtiquetaEdit().init();
},
function (error) {
console.log("Error getting translations:", error);
}
).post();
*/
new EtiquetaEdit().init();
});
export default EtiquetaEdit;

View File

@ -0,0 +1,177 @@
import ClassSelect from '../../components/select2.js';
$(() => {
let otsFilter = '';
const selectOts = new ClassSelect($('#buscadorPedidos'), '/etiquetasTitulos/otList', "", true);
selectOts.init();
const selectDirecciones = new ClassSelect($('#selectDirecciones'), '/etiquetasTitulos/addList', "", true, {
ot_id: () => selectOts.getVal()
});
selectDirecciones.init();
selectOts.item.on('select2:open', () => {
$('.select-direcciones').addClass('d-none');
$('.add-etiqueta').addClass('d-none');
})
selectOts.item.on('change', () => {
selectDirecciones.empty();
$('.add-etiqueta').addClass('d-none');
$('.select-direcciones').removeClass('d-none');
})
selectDirecciones.item.on('select2:open', () => {
$('.add-etiqueta').addClass('d-none');
})
selectDirecciones.item.on('change', () => {
$('.add-etiqueta').removeClass('d-none');
})
$('#btnAddEtiqueta').on('click', () => {
Swal.fire({
title: 'Unidades por caja',
text: 'Seleccione la cantidad de unidades por caja',
icon: 'info',
input: 'text',
inputLabel: 'Unidades/caja',
inputValue: 0,
showCancelButton: true,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Aceptar',
cancelButtonText: 'Cancelar',
customClass: {
confirmButton: 'btn btn-primary me-1',
cancelButton: 'btn btn-secondary'
},
buttonsStyling: false
}).then((result) => {
if (result.isConfirmed) {
const unidades_caja = result.value;
const url = '/etiquetasTitulos/newEtiquetaTitulos';
const data = {
ot_id: selectOts.getVal(),
direccion: selectDirecciones.getText(),
unidades_caja: unidades_caja
};
$.post(
url,
data,
function (response) {
if (response.status) {
tableEtiquetas.ajax.reload();
// open the new etiqueta in a new tab
window.open(`${window.location.origin}/etiquetasTitulos/edit/${response.etiqueta}`, '_blank');
} else {
popErrorAlert('Error en la respuesta');
}
}
).fail(function (xhr, status, error) {
popErrorAlert(error);
});
}
});
})
const tableEtiquetas = $('#tableOfEquiquetas').DataTable({
processing: true,
serverSide: true,
autoWidth: true,
responsive: true,
scrollX: true,
orderCellsTop: true,
lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500],
pageLength: 50,
"dom": 'lBrtip',
"ajax": {
"url": "/etiquetasTitulos/datatable",
"data": function (d) {
d.otsFilter = otsFilter;
}
},
"columns": [
{ "data": "id" },
{ "data": "lista_ots" },
{ "data": "cajas" },
{ "data": "att" },
{ "data": "direccion" },
{ "data": "action" }
],
"language": {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
"columnDefs": [
{
orderable: false,
searchable: false,
targets: [5]
},
],
"order": [[0, "desc"]],
});
$(document).on('click', '.btn-edit', function (e) {
window.location.href = '/etiquetasTitulos/edit/' + $(this).attr('data-id');
});
$(document).on('click', '.btn-delete', function (e) {
Swal.fire({
title: '¿Está seguro de eliminar la etiqueta?',
text: "No podrá revertir esta acción",
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Sí',
cancelButtonText: 'Cancelar',
customClass: {
confirmButton: 'btn btn-danger me-1',
cancelButton: 'btn btn-secondary'
},
buttonsStyling: false
}).then((result) => {
if (result.isConfirmed) {
$.post(
'/etiquetasTitulos/delete',
{
id: $(this).attr('data-id')
},
function (response) {
if (response.status) {
tableEtiquetas.ajax.reload();
popSuccessAlert(response.message);
} else {
popErrorAlert('Error borrando la etiqueta');
}
}
).fail(function (xhr, status, error) {
popErrorAlert(error);
});
}
})
});
$(document).on("keyup", ".envio-filter", (event) => {
let columnName = $(event.currentTarget).attr("name");
let columnIndex = $('#tableOfEquiquetas').DataTable().columns().eq(0).filter(function (index) {
return $('#tableOfEquiquetas').DataTable().column(index).dataSrc() === columnName;
})[0];
$('#tableOfEquiquetas').DataTable().column(columnIndex).search($(event.currentTarget).val()).draw()
})
$(document).on("keyup", ".envio-filter-ots", (event) => {
otsFilter = $(event.currentTarget).val();
$('#tableOfEquiquetas').DataTable().ajax.reload();
})
$(document).on("change", ".envio-filter-select", (event) => {
let columnName = $(event.currentTarget).attr("name");
let columnIndex = $('#tableOfEquiquetas').DataTable().columns().eq(0).filter(function (index) {
return $('#tableOfEquiquetas').DataTable().column(index).dataSrc() === columnName;
})[0];
$('#tableOfEquiquetas').DataTable().column(columnIndex).search($(event.currentTarget).val()).draw();
});
})

View File

@ -139,4 +139,8 @@
.dtrg-group.ui-droppable-hover {
background-color: #d1ecf1 !important;
cursor: move;
}
.dt-no-reorder {
cursor: auto !important;
}