Files
safekat/httpdocs/assets/js/safekat/pages/logistica/envioEdit.js

914 lines
34 KiB
JavaScript

import ClassSelect from '../../components/select2.js';
import Ajax from '../../components/ajax.js';
import AlbaranComponent from '../../components/albaranComponent.js';
class EnvioEdit {
constructor() {
this.tableCols = [
{ data: "rowSelected" },
{ data: "ordenTrabajo" },
{ data: "pedido" },
{ data: "presupuesto" },
{ data: "titulo" },
{ data: "unidadesEnvio" },
{ data: "unidadesEnviadas" },
{ data: "unidadesTotal" },
{ data: "id" },
{ data: "pesoUnidad" },
{ data: "unidadesEnvioRaw" }
];
this.table = null;
this.buscarPedidos = new ClassSelect($("#buscadorPedidos"), '/logistica/selectAddLinea', "", true, { 'envio': $("#id").val() });
this.btnAddLinea = $("#btnAddLinea");
this.btnDeleteLinea = $("#btnEliminarLineas");
this.btnGuardarComentarios = $("#guardarComentarios");
this.btnGenerarAlbaran = $("#btnGenerarAlbaran");
this.btnbtnSelectAll = $("#btnSelectAll");
this.cajas = $("#cajas");
this.codigoSeguimiento = $("#codigoSeguimiento");
if (!$("#empresaMensajeriaInput").length) {
this.proveedor = new ClassSelect($("#empresaMensajeria"), '/compras/proveedores/getProveedores', "", true, { 'tipo_id': 2 });
}
this.impresoraEtiquetas = $("#impresoraEtiquetas");
}
init() {
if (!$("#empresaMensajeriaInput").length) {
this.proveedor.init();
}
if ($("#proximosEnvios").length) {
new PerfectScrollbar(document.getElementById('proximosEnvios'), {
wheelPropagation: false
});
}
this.table = $('#tableLineasEnvio').DataTable({
processing: true,
serverSide: true,
autoWidth: true,
responsive: true,
scrollX: true,
orderCellsTop: true,
orderable: false,
order: [[7, 'asc']],
lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500],
pageLength: 50,
"dom": 'lrtip',
"ajax": {
"url": "/logistica/datatableLineasEnvios/" + $('#id').val(),
},
"columns": this.tableCols,
"language": {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
footerCallback: function (row, data, start, end, display) {
let totalUnidades = 0;
let totalPeso = 0;
data.forEach(row => {
const unidades = parseFloat(row.unidadesEnvioRaw) || 0;
const pesoUnidad = parseFloat(row.pesoUnidad) || 0;
totalUnidades += unidades;
totalPeso += unidades * pesoUnidad;
});
// Mostrar en spans personalizados del <tfoot>
$('#footer-unidades-envio').text(totalUnidades);
$('#footer-peso').text(totalPeso.toFixed(2));
},
"columnDefs": [
{
"targets": [0],
"className": "text-center",
"orderable": false,
"searchable": false,
},
{
"targets": [1, 2, 4, 5, 6, 7],
"className": "text-center",
},
{
targets: [8, 9, 10],
visible: false
}
]
});
$('#btnImprimirEtiquetas').on('click', () => {
const table = this.table;
const selectedRows = table.rows({ page: 'current' }).nodes().filter((node) => {
const checkbox = $(node).find('.checkbox-linea-envio');
return checkbox.is(':checked');
}
);
const ids = selectedRows.map((node) => {
const rowData = table.row(node).data();
return rowData.id;
}).toArray();
if (ids.length <= 0) {
Swal.fire({
title: 'Atención!',
text: 'Debe seleccionar al menos una línea de envío para imprimir etiquetas.',
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
return;
}
const idEnvio = $('#id').val();
let num_cajas = this.cajas.val();
if (ids.length != table.rows().count()) {
// se preguntará el numero de cajas en un swal con un input para obtener el valor
Swal.fire({
title: 'Atención!',
text: 'No se ha seleccionado todas las líneas de envío. Ingrese el número de cajas a imprimir.',
icon: 'info',
input: 'text',
inputLabel: 'Número de cajas',
inputValue: num_cajas,
showCancelButton: true,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Imprimir etiquetas',
cancelButtonText: 'Cancelar',
customClass: {
confirmButton: 'btn btn-primary me-1',
cancelButton: 'btn btn-secondary'
},
buttonsStyling: false
}).then((result) => {
if (result.isConfirmed) {
num_cajas = result.value;
this._imprimirEtiquetas(idEnvio, ids, num_cajas);
}
});
}
else {
this._imprimirEtiquetas(idEnvio, ids, num_cajas);
}
});
this.cajas.on('change', (e) => {
const value = $(e.currentTarget).val();
if (value < 0) {
Swal.fire({
title: 'Atención!',
text: 'El número de cajas no puede ser negativo.',
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
$(e.currentTarget).val(0);
return;
}
$.post('/logistica/updateCajasEnvio', {
id: $('#id').val(),
cajas: value
}, function (response) {
if (!response.status) {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
$(e.currentTarget).val(0);
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo actualizar el número de cajas.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
$(e.currentTarget).val(0);
});
});
$(document).on('change', '.input-lineas', (e) => {
const table = this.table;
const row = table.row($(e.currentTarget).closest('tr'));
const rowData = row.data();
const fieldName = $(e.currentTarget).data('name');
const fieldValue = $(e.currentTarget).val();
$.post('/logistica/updateLineaEnvio', {
id: rowData.id,
"name": fieldName,
'value': fieldValue
}, function (response) {
if (response.status) {
table.draw(false);
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.draw(false);
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo actualizar el dato.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.draw(false);
});
});
this.buscarPedidos.init();
if (this.btnAddLinea.length) this.btnAddLinea.on('click', this._addEnvioLinea.bind(this));
if (this.btnDeleteLinea.length) this.btnDeleteLinea.on('click', this._deleteLineas.bind(this));
if (this.btnGenerarAlbaran.length) this.btnGenerarAlbaran.on('click', this._generarAlbaran.bind(this));
if (this.btnGuardarComentarios.length) {
this.btnGuardarComentarios.on('click', () => {
$.post('/logistica/updateComentariosEnvio', {
id: $('#id').val(),
comentarios: $('#comentarios').val()
}, function (response) {
if (response.status) {
popSuccessAlert('Comentarios guardados correctamente');
} else {
popErrorAlert(response.message);
}
}).fail((error) => {
popErrorAlert(error.responseJSON.message);
});
});
}
this.btnbtnSelectAll.on('click', () => {
const checkboxes = this.table.$('input[type="checkbox"]');
const allChecked = checkboxes.length === checkboxes.filter(':checked').length;
checkboxes.prop('checked', !allChecked);
});
this.codigoSeguimiento.on('change', (e) => {
const value = $(e.currentTarget).val();
$.post('/logistica/updateCodigoSeguimiento', {
id: $('#id').val(),
codigo_seguimiento: value
}, function (response) {
if (!response.status) {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
$(e.currentTarget).val(value.substring(0, 100));
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo actualizar el código de seguimiento.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
$(e.currentTarget).val(value.substring(0, 100));
}
);
});
if (!$("#empresaMensajeriaInput").length) {
this.proveedor.onChange((e) => {
const value = this.proveedor.getVal();
$.post('/logistica/updateProveedorEnvio', {
id: $('#id').val(),
proveedor_id: value
}, function (response) {
if (!response.status) {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
this.proveedor.setVal(0);
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo actualizar el proveedor.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
this.proveedor.setVal(0);
}
);
});
}
$('#finalizarEnvio').on('click', (e) => {
if (!this._checkDatosFinalizar())
return;
Swal.fire({
title: 'Finalizar envío',
text: '¿Está seguro de que desea finalizar el envío?',
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('/logistica/finalizarEnvio', {
id: $('#id').val()
}, function (response) {
if (response.status) {
Swal.fire({
text: response.message,
icon: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
}).then(() => {
window.location.reload();
});
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo finalizar el envío.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
});
}
});
});
$('#finalizarEnvioYOTs').on('click', (e) => {
if (!this._checkDatosFinalizar())
return;
Swal.fire({
title: 'Finalizar envío y las OTs',
text: '¿Está seguro de que desea finalizar el envío y las OTs de las líneas de envío?',
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('/logistica/finalizarEnvio', {
id: $('#id').val(),
finalizar_ots: true
}, function (response) {
if (response.status) {
Swal.fire({
text: response.message,
icon: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
}).then(() => {
window.location.reload();
});
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo finalizar el envío.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
});
}
});
});
$('#ficharEmbalaje').on('click', (e) => {
this._ficharEmbalajeLineas();
});
this._getAlbaranes();
}
_imprimirEtiquetas(envio_id, ids, num_cajas) {
$.post('/logistica/imprimirEtiquetas', {
envio_id: envio_id,
envio_lineas: ids,
cajas: num_cajas,
printer_id: this.impresoraEtiquetas.val(),
}, function (response) {
if (response.status) {
Swal.fire({
title: 'Etiquetas generadas',
text: 'Las etiquetas se han generado correctamente.',
icon: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
}).then(() => {
if (response.data) {
// show xml in a new tab
const blob = new Blob([response.data], { type: 'application/xml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'etiquetas.xml';
a.click();
URL.revokeObjectURL(url);
a.remove();
}
});
}
else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}
).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo generar las etiquetas.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
});
}
_checkDatosFinalizar() {
if (this.codigoSeguimiento.val().length <= 0 || this.proveedor.getVal() <= 0) {
Swal.fire({
title: 'Atención!',
text: 'Debe seleccionar un proveedor y un código de seguimiento antes de finalizar el envío.',
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
return false;
}
return true;
}
_getAlbaranes() {
$.get('/albaranes/albaranesEnvio', {
envio_id: $('#id').val(),
}, function (response) {
if (response.status && response.data) {
for (let i = 0; i < response.data.length; i++) {
const albaran = response.data[i];
new AlbaranComponent(albaran).mount('#contenedorAlbaranes');
}
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se han podido obtener los albaranes.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
});
}
_generarAlbaran() {
const table = this.table;
const selectedRows = table.rows({ page: 'current' }).nodes().filter((node) => {
const checkbox = $(node).find('.checkbox-linea-envio');
return checkbox.is(':checked');
});
const ids = selectedRows.map((node) => {
const rowData = table.row(node).data();
return rowData.id;
}).toArray();
if (ids.length <= 0) {
Swal.fire({
title: 'Atención!',
text: 'Debe seleccionar al menos una línea de envío para generar el albarán.',
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
return;
}
const idEnvio = $('#id').val();
$.post('/albaranes/generarAlbaran', {
envio_id: idEnvio,
envio_lineas: ids,
cajas: this.cajas.val()
}, function (response) {
if (response.status && response.albaran) {
new AlbaranComponent(response.albaran).mount('#contenedorAlbaranes');
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo generar el albarán.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
});
}
_ficharEmbalajeLineas() {
const table = this.table;
const selectedRows = table.rows({ page: 'current' }).nodes().filter((node) => {
const checkbox = $(node).find('.checkbox-linea-envio');
return checkbox.is(':checked');
});
const ids = selectedRows.map((node) => {
const rowData = table.row(node).data();
const parser = new DOMParser();
const doc = parser.parseFromString(rowData.ordenTrabajo, 'text/html');
return doc.body.textContent.trim(); // extrae solo el texto dentro del <a>
}).toArray();
if (ids.length > 0) {
Swal.fire({
title: 'Fichar embalaje',
text: '¿Está seguro de fichar el embalaje de las líneas seleccionadas?',
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('/logistica/ficharEmbalaje', {
ids: ids
}, function (response) {
if (response.status) {
Swal.fire({
text: response.message,
icon: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.ajax.reload();
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo realizar el fichaje.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.ajax.reload();
});
}
});
} else {
Swal.fire({
title: 'Sin filas seleccionadas',
text: 'Marca al menos una línea para eliminarla.',
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}
_deleteLineas() {
const table = this.table;
const selectedRows = table.rows({ page: 'current' }).nodes().filter((node) => {
const checkbox = $(node).find('.checkbox-linea-envio');
return checkbox.is(':checked');
});
const ids = selectedRows.map((node) => {
const rowData = table.row(node).data();
return rowData.id;
}).toArray();
if (ids.length > 0) {
Swal.fire({
title: 'Eliminar líneas de envío',
text: '¿Está seguro de que desea eliminar las líneas seleccionadas?',
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('/logistica/deleteLineasEnvio', {
ids: ids
}, function (response) {
if (response.status) {
table.draw(false);
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.ajax.reload();
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo eliminar la línea de envío.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.ajax.reload();
});
}
});
} else {
Swal.fire({
title: 'Sin filas seleccionadas',
text: 'Marca al menos una línea para eliminarla.',
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}
_addEnvioLinea() {
if (!this.buscarPedidos.getVal()) {
Swal.fire({
title: 'Atención!',
text: 'Debe seleccionar un pedido antes de añadir una línea de envío.',
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
return;
}
new Ajax('/logistica/addLineaEnvio', {
'envio_id': $('#id').val(),
'pedido_id': this.buscarPedidos.getVal(),
'direccion': $("#direccion").val()
}, {},
(response) => {
if (response.status) {
this.table.draw();
this.buscarPedidos.empty();
} else {
Swal.fire({
title: 'Atención!',
text: response.message,
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}, (error) => {
console.error(error);
}).get();
}
}
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: ['Albaran'] }, {},
function (translations) {
window.language = JSON.parse(translations);
new EnvioEdit().init();
},
function (error) {
console.log("Error getting translations:", error);
}
).post();
});
export default EnvioEdit;