1039 lines
32 KiB
JavaScript
1039 lines
32 KiB
JavaScript
|
|
var clienteSeleccionado = "";
|
|
var complementoAerolinea = "";
|
|
var complementoINE = "";
|
|
var opcionFactura = 0;
|
|
var boton;
|
|
var contenidoConceptos = ""; //Conceptos dinamicos contenedor
|
|
var contenidoPagos = ""; //Contenedor pagos parciales
|
|
var opcionFacturaGlobal = "1";
|
|
var idFacturaPPD = "";
|
|
|
|
|
|
$(document).ready(function () {
|
|
|
|
$("#search-icon").click(function () {
|
|
|
|
var uuid = document.getElementById('uuid').value;
|
|
console.log(uuid)
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: 'php/consulta/datosPPD.php',
|
|
data: {
|
|
uuid: uuid
|
|
},
|
|
dataType: 'json',
|
|
success: function (response) {
|
|
console.log(response)
|
|
|
|
document.getElementById('RFC').textContent = response.rfc;
|
|
document.getElementById('razonSocial').textContent = response.razon;
|
|
document.getElementById('regimenFiscal').textContent = response.regimen;
|
|
document.getElementById('cpCliente').textContent = response.cp;
|
|
|
|
//inputs ocultos
|
|
document.getElementById('inputRazonSocial').value = response.razon;
|
|
document.getElementById('inputRFC').value = response.rfc;
|
|
document.getElementById('inputRegimenFiscal').value = response.regimen;
|
|
document.getElementById('inputCPCliente').value = response.cp;
|
|
|
|
//DATOS PAGO
|
|
document.getElementById('debe').value = response.total;
|
|
document.getElementById('numParcialidad').value = response.parcialidad;
|
|
document.getElementById('montoPagado').value = 0.00;
|
|
document.getElementById('impSaldoInsoluto').value = 0.00;
|
|
|
|
idFacturaPPD = response.id;
|
|
},
|
|
error: function (xhr, status, error) {
|
|
console.log(xhr.responseText, status, error)
|
|
|
|
}
|
|
});
|
|
|
|
|
|
|
|
});
|
|
|
|
$('#agregarFila').on('click', agregarFilaHandler);
|
|
let productosArray = [];
|
|
obtenerClientes();
|
|
obtenerMateriales();
|
|
obtenerFolio();
|
|
obtenerUsoCfdi();
|
|
obtenerMetodoPago();
|
|
obtenerViaPago();
|
|
var opciones = document.getElementById('opcionesFacturacion');
|
|
opciones.addEventListener("change", function (event) {
|
|
var opcionSeleccionada = event.target.value;
|
|
|
|
|
|
switch (opcionSeleccionada) {
|
|
case "1":
|
|
console.log(opcionSeleccionada)
|
|
opcionFactura = 1;
|
|
document.getElementById('tablaConceptos').innerHTML = contenidoConceptos;
|
|
//contenidoPagos = document.getElementById('contenedorPagos').innerHTML;
|
|
//document.getElementById('contenedorPagos').innerHTML = '';
|
|
document.getElementById('contenedorPagos').style.display = 'none';
|
|
$('#agregarFila').on('click', agregarFilaHandler);
|
|
|
|
obtenerFolio();
|
|
//$('#agregarFila').on('click', agregarFilaHandler);
|
|
document.getElementById('iconoCliente').style.display = '';
|
|
document.getElementById('cliente').style.display = ''
|
|
opcionFacturaGlobal = "1";
|
|
|
|
var razonSocial = document.getElementById('inputRazonSocial');
|
|
var cpReceptor = document.getElementById('inputCPCliente');
|
|
var rfcReceptor = document.getElementById('inputRFC');
|
|
var regimenReceptor = document.getElementById('inputRegimenFiscal');
|
|
cpReceptor.style.display = 'none';
|
|
cpReceptor.value = '';
|
|
regimenReceptor.style.display = 'none';
|
|
regimenReceptor.value = '';
|
|
rfcReceptor.style.display = 'none';
|
|
rfcReceptor.value = '';
|
|
razonSocial.style.display = 'none';
|
|
razonSocial.value = '';
|
|
|
|
document.getElementById('uuid').value = '';
|
|
document.getElementById('debe').value = '';
|
|
document.getElementById('numParcialidad').value = '';
|
|
document.getElementById('montoPagado').value = '';
|
|
document.getElementById('impSaldoInsoluto').value = '';
|
|
|
|
var usocontenedor = document.getElementById('uso_contenedor');
|
|
usocontenedor.style.display = '';
|
|
document.getElementById('uuid').value = '';
|
|
|
|
break;
|
|
case "2":
|
|
limpiarTablaHandler();
|
|
|
|
opcionFacturaGlobal = "2";
|
|
console.log(opcionSeleccionada)
|
|
|
|
var montoPago = document.getElementById('montoPagado')
|
|
montoPago.addEventListener('input', function () {
|
|
var montoDeuda = document.getElementById('debe');
|
|
var montoPago = document.getElementById('montoPagado')
|
|
var deuda = parseFloat(montoDeuda.value);
|
|
var pago = parseFloat(montoPago.value);
|
|
|
|
var saldoInsoluto = deuda - pago;
|
|
$('#impSaldoInsoluto').val(saldoInsoluto.toFixed(2));
|
|
var mensajeError = document.getElementById('mensajeError');
|
|
if (pago > deuda) {
|
|
mensajeError.textContent = 'El monto pagado no puede ser mayor que la deuda.';
|
|
} else {
|
|
mensajeError.textContent = '';
|
|
|
|
}
|
|
});
|
|
|
|
document.getElementById('contenedorPagos').style.display = '';
|
|
contenidoConceptos = document.getElementById('tablaConceptos').innerHTML;
|
|
document.getElementById('tablaConceptos').innerHTML = '';
|
|
var usocontenedor = document.getElementById('uso_contenedor');
|
|
usocontenedor.style.display = 'none';
|
|
|
|
document.getElementById('RFC').textContent = '';
|
|
document.getElementById('razonSocial').textContent = '';
|
|
document.getElementById('regimenFiscal').textContent = '';
|
|
document.getElementById('cpCliente').textContent = '';
|
|
document.getElementById('cliente').value = 'Selecciona un cliente';
|
|
document.getElementById('iconoCliente').style.display = 'none';
|
|
document.getElementById('cliente').style.display = 'none';
|
|
|
|
|
|
console.log(opcionSeleccionada)
|
|
break;
|
|
}
|
|
|
|
});
|
|
document.addEventListener("DOMContentLoaded", function () {
|
|
|
|
|
|
});
|
|
|
|
$('#tablaDatos').on('click', '.btnEliminarFila', function () {
|
|
$(this).closest('tr').remove();
|
|
nuevaFila.remove();
|
|
calcularTotales();
|
|
actualizarNombresConcepto();
|
|
});
|
|
|
|
|
|
});
|
|
|
|
function toggleLoader() {
|
|
console.log('ENTRA')
|
|
var loaderWrapper = document.getElementById("loaderWrapper");
|
|
if (loaderWrapper.classList.contains("hidden")) {
|
|
loaderWrapper.classList.remove("hidden");
|
|
$('#overlay').removeClass('hidden');
|
|
} else {
|
|
loaderWrapper.classList.add("hidden");
|
|
$('#overlay').addClass('hidden');
|
|
|
|
}
|
|
}
|
|
|
|
function toggleLoader2() {
|
|
console.log('ENTRA')
|
|
var loaderWrapper = document.getElementById("loaderWrapper2");
|
|
if (loaderWrapper.classList.contains("hidden")) {
|
|
loaderWrapper.classList.remove("hidden");
|
|
$('#overlay').removeClass('hidden');
|
|
} else {
|
|
loaderWrapper.classList.add("hidden");
|
|
$('#overlay').addClass('hidden');
|
|
|
|
}
|
|
}
|
|
|
|
|
|
function toggleLoader3() {
|
|
console.log('ENTRA')
|
|
var loaderWrapper = document.getElementById("loaderWrapper3");
|
|
if (loaderWrapper.classList.contains("hidden")) {
|
|
loaderWrapper.classList.remove("hidden");
|
|
$('#overlay').removeClass('hidden');
|
|
} else {
|
|
loaderWrapper.classList.add("hidden");
|
|
$('#overlay').addClass('hidden');
|
|
|
|
}
|
|
}
|
|
|
|
|
|
function complementoIne(val1) {
|
|
var ineContenedor = document.getElementById('ineContenedor');
|
|
var grupoEntidad = document.getElementById('grupoEntidad');
|
|
|
|
// Contenido para 'Ordinario'
|
|
var contenidoOrdinario = '<div class="col-lg-4" style="" id="tipoComiteDiv">' +
|
|
'<div class="input-group mb-3">' +
|
|
'<label class="input-group-text">Tipo Comite</label>' +
|
|
'<input type="otrosCargos" required="" name="ineTipoComite" class="form-control" style="background-color: #f3fcff;" name="tipoComite">' +
|
|
'</div>' +
|
|
'</div>' +
|
|
'<div class="col-lg-4" style="" id="idContabilidadDiv">' +
|
|
'<div class="input-group mb-3">' +
|
|
'<label class="input-group-text">Id Contabilidad</label>' +
|
|
'<input type="otrosCargos" required="" name="ineIdContabilidad" class="form-control" style="background-color: #f3fcff;" name="tipoComite">' +
|
|
'</div>' +
|
|
'</div>' +
|
|
'<hr>';
|
|
|
|
// Contenido para 'No Ordinario'
|
|
var contenidoNoOrdinario = '<div class="col-lg-4" id="divEntidad">' +
|
|
'<div class="input-group mb-3">' +
|
|
'<label class="input-group-text">Clave Entidad</label>' +
|
|
'<input type="otrosCargos" required="" name="ineClaveEntidad" class="form-control" style="background-color: #f3fcff;" name="claveEntidad">' +
|
|
'</div>' +
|
|
'</div>' +
|
|
'<div class="col-lg-4" id="divAmbito">' +
|
|
'<div class="input-group mb-3">' +
|
|
'<label class="input-group-text">Ambito</label>' +
|
|
'<input type="otrosCargos" required="" name="ineAmbito" class="form-control" style="background-color: #f3fcff;" name="claveEntidad">' +
|
|
'</div>' +
|
|
'</div>' +
|
|
'<hr>';
|
|
var tipoComiteDiv = document.getElementById('tipoComiteDiv');
|
|
var contabilidadDiv = document.getElementById('contabilidadDiv');
|
|
// Agregar el contenido correspondiente según la opción seleccionada
|
|
if (val1 === 'Ordinario') {
|
|
console.log("Ordinario", val1)
|
|
contabilidadDiv.style.display = 'none';
|
|
tipoComiteDiv.style.display = 'none';
|
|
//ineContenedor.innerHTML = contenidoOrdinario;
|
|
} else if (val1 == 'Campaña' || val1 == 'Precampaña') {
|
|
contabilidadDiv.style.display = 'none';
|
|
tipoComiteDiv.style.display = 'none';
|
|
console.log("Valor", val1)
|
|
//grupoEntidad.innerHTML = contenidoNoOrdinario;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function obtenerFolio() {
|
|
var timestamp = new Date().getTime();
|
|
var timestampString = timestamp.toString().slice(-6); // Utilizar solo los últimos 6 dígitos
|
|
|
|
// Generar un número aleatorio único de 4 dígitos
|
|
var uniqueSuffix = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
|
|
|
|
var folioInput = document.getElementById('folioP');
|
|
folioInput.addEventListener('input', function () {
|
|
if (folioInput.value.length > 10) {
|
|
folioInput.value = folioInput.value.slice(0, 10);
|
|
}
|
|
});
|
|
|
|
// Concatenar la marca de tiempo y el sufijo único
|
|
document.getElementById('folioP').value = timestampString + uniqueSuffix;
|
|
}
|
|
|
|
// Función para obtener el token CSRF de la cookie
|
|
function getCSRFToken() {
|
|
const cookies = document.cookie.split('; ');
|
|
for (let cookie of cookies) {
|
|
const [name, value] = cookie.split('=');
|
|
if (name === 'csrf_token') {
|
|
return value;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
|
|
|
|
function obtenerMateriales() {
|
|
|
|
const csrfToken = getCSRFToken();
|
|
if (!csrfToken) {
|
|
console.error('Token CSRF no encontrado');
|
|
return;
|
|
}
|
|
|
|
fetch('php/items/productos.php', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-Token': csrfToken // Envía el token CSRF en un encabezado personalizado
|
|
},
|
|
body: JSON.stringify({ csrf_token: csrfToken }) // Incluye el token CSRF en los datos de la solicitud
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
|
|
if (data.error) {
|
|
console.error('Error al obtener datos de clientes:', data.error);
|
|
} else {
|
|
productosArray = [];
|
|
|
|
data.forEach(producto => {
|
|
productosArray.push(producto);
|
|
});
|
|
}
|
|
})
|
|
.catch(error => console.error('Error al realizar la solicitud AJAX:', error));
|
|
}
|
|
|
|
|
|
function obtenerClientes() {
|
|
|
|
fetch('php/items/clientes.php', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
|
|
if (data.error) {
|
|
console.error('Error al obtener datos de clientes:', data.error);
|
|
} else {
|
|
|
|
|
|
data.sort((a, b) => a.Name1.localeCompare(b.Name1));
|
|
|
|
|
|
let clienteSelect = document.getElementById('cliente');
|
|
|
|
data.forEach(cliente => {
|
|
//se recorren todos los clientes
|
|
let option = document.createElement('option');
|
|
option.value = JSON.stringify(cliente);
|
|
|
|
if (cliente.Frgrp == '999') {
|
|
option.text = 'CLIENTE DE CONTADO';
|
|
} else {
|
|
option.text = cliente.Name1;
|
|
}
|
|
clienteSelect.add(option);
|
|
});
|
|
|
|
// Agregar un evento de cambio al select
|
|
clienteSelect.addEventListener('change', function () {
|
|
|
|
|
|
let selectedValue = JSON.parse(clienteSelect.value);
|
|
|
|
clienteSeleccionado = selectedValue.Kunnr;
|
|
|
|
|
|
if (selectedValue.Frgrp == '999') {
|
|
console.log('CONTADO');
|
|
|
|
document.getElementById('inputRazonSocial').value = '';
|
|
document.getElementById('inputRazonSocial').style = '';
|
|
document.getElementById('inputRFC').value = '';
|
|
document.getElementById('inputRFC').style = '';
|
|
document.getElementById('inputRegimenFiscal').value = '';
|
|
document.getElementById('inputRegimenFiscal').style = '';
|
|
document.getElementById('inputCPCliente').value = '';
|
|
document.getElementById('inputCPCliente').style = '';
|
|
|
|
document.getElementById('RFC').textContent = '';
|
|
document.getElementById('razonSocial').textContent = '';
|
|
document.getElementById('regimenFiscal').textContent = '';
|
|
document.getElementById('cpCliente').textContent = '';
|
|
|
|
return;
|
|
}
|
|
|
|
document.getElementById('inputRazonSocial').value = '';
|
|
document.getElementById('inputRazonSocial').style.display = 'none';
|
|
document.getElementById('inputRFC').value = '';
|
|
document.getElementById('inputRFC').style.display = 'none';
|
|
document.getElementById('inputRegimenFiscal').value = '';
|
|
document.getElementById('inputRegimenFiscal').style.display = 'none';
|
|
document.getElementById('inputCPCliente').value = '';
|
|
document.getElementById('inputCPCliente').style.display = 'none';
|
|
|
|
|
|
document.getElementById('RFC').textContent = selectedValue.Stcd1;
|
|
var razonSocial = selectedValue.Name1.toString();
|
|
document.getElementById('razonSocial').textContent = selectedValue.Name1;
|
|
document.getElementById('regimenFiscal').textContent = selectedValue.Frgrp;
|
|
document.getElementById('cpCliente').textContent = selectedValue.Pstlz;
|
|
|
|
//inputs ocultos
|
|
document.getElementById('inputRazonSocial').value = razonSocial;
|
|
var rfcR = selectedValue.Stcd1.toString();
|
|
document.getElementById('inputRFC').value = rfcR;
|
|
var regimenR = selectedValue.Frgrp.toString();
|
|
document.getElementById('inputRegimenFiscal').value = regimenR;
|
|
var cpCliente = selectedValue.Pstlz.toString();
|
|
document.getElementById('inputCPCliente').value = cpCliente;
|
|
});
|
|
}
|
|
})
|
|
.catch(error => console.error('Error al realizar la solicitud AJAX:', error));
|
|
}
|
|
|
|
|
|
|
|
|
|
// Cambiar valores de otras columnas al seleccionar código
|
|
$('#tablaDatos').on('change', '.codigo', function () {
|
|
var codigoSeleccionado = $(this).val();
|
|
var fila = $(this).closest('tr');
|
|
|
|
// Llamar a la función para calcular el importe
|
|
calcularImporte(fila);
|
|
calcularTotales();
|
|
|
|
actualizarNombresConcepto();
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
function obtenerUsoCfdi() { //03/03/2024 Michael Cabreras
|
|
$.ajax({
|
|
url: '../php/items/UsoCFDI.php',
|
|
type: 'GET',
|
|
dataType: 'json',
|
|
success: function (data) {
|
|
console.log(data)
|
|
// Una vez que se recibe el JSON, construir el select
|
|
$.each(data, function (index, objeto) {
|
|
$('#usoFactura').append($('<option>', {
|
|
'data-value': objeto.ID,
|
|
text: objeto.CODIGO + ' - ' + objeto.DESCRIPCION
|
|
}).val(objeto.CODIGO));
|
|
});
|
|
|
|
},
|
|
error: function (xhr, status, error) {
|
|
console.error(xhr, status, error);
|
|
}
|
|
});
|
|
}
|
|
|
|
function obtenerMetodoPago() { //03/03/2024 Michael Cabreras
|
|
$.ajax({
|
|
url: '../php/items/metodoPago.php',
|
|
type: 'GET',
|
|
dataType: 'json',
|
|
success: function (data) {
|
|
console.log(data)
|
|
$.each(data, function (index, objeto) {
|
|
$('#tipoPago').append($('<option>', {
|
|
'data-value': objeto.ID,
|
|
text: objeto.CODIGO + ' - ' + objeto.DESCRIPCION
|
|
}).val(objeto.CODIGO));
|
|
});
|
|
},
|
|
error: function (xhr, status, error) {
|
|
console.error(xhr, status, error);
|
|
}
|
|
});
|
|
}
|
|
|
|
function obtenerViaPago() { //03/03/2024 Michael Cabreras
|
|
$.ajax({
|
|
url: '../php/items/viaPago.php',
|
|
type: 'GET',
|
|
dataType: 'json',
|
|
success: function (data) {
|
|
console.log(data)
|
|
$.each(data, function (index, objeto) {
|
|
$('#formaPago').append($('<option>', {
|
|
'data-value': objeto.CODIGO,
|
|
text: objeto.CODIGO + ' - ' + objeto.DESCRIPCION
|
|
}).val(objeto.ID));
|
|
});
|
|
},
|
|
error: function (xhr, status, error) {
|
|
console.error(xhr, status, error);
|
|
}
|
|
});
|
|
}
|
|
// Función para calcular el importe
|
|
function calcularImporte(fila) {
|
|
var cantidad = fila.find('.cantidad').val();
|
|
var precioUnitario = fila.find('.precioUnitario').val();
|
|
var exentoiva=fila.find('.EXENTOIVA').val();
|
|
console.log(exentoiva);
|
|
var importe = cantidad * precioUnitario;
|
|
var ivaTemporal = precioUnitario * 0.16;
|
|
//var ivaTotal = ivaTemporal * cantidad;
|
|
if(exentoiva==1)
|
|
{
|
|
var ivaTotal = 0 * cantidad;
|
|
|
|
}
|
|
else{
|
|
var ivaTotal = ivaTemporal * cantidad;
|
|
}
|
|
|
|
// Asignar el valor del importe al campo visible
|
|
fila.find('.importe').val(importe.toFixed(2));
|
|
fila.find('.iva').val(ivaTotal.toFixed(2));
|
|
|
|
// Obtener el índice actual del tr en el que estás trabajando
|
|
var indice = fila.index();
|
|
|
|
// Eliminar campos ocultos existentes antes de agregar nuevos
|
|
fila.find('input[name^="impuestosConcepto["]').remove();
|
|
fila.find('input[name^="concepto["][type="hidden"]').remove();
|
|
|
|
|
|
// Agregar dos campos ocultos con información sobre el IVA y el precio unitario
|
|
fila.find('.importe').after(
|
|
'<input type="hidden" name="impuestosConcepto[' + indice + '][0]" value="' + ivaTotal.toFixed(2) + '">' +
|
|
'<input type="hidden" name="impuestosConcepto[' + indice + '][1]" value="' + importe.toFixed(2) + '">' +
|
|
'<input type="hidden" name="concepto[' + indice + '][7]" value="' + importe.toFixed(2) + '">'
|
|
);
|
|
}
|
|
|
|
// Función para calcular los totales
|
|
function calcularTotales() {
|
|
var totalImportes = 0;
|
|
var totalIvas = 0;
|
|
|
|
// Recorrer todas las filas
|
|
$('#tablaDatos tbody tr').each(function (index) {
|
|
var fila = $(this);
|
|
var importe = parseFloat(fila.find('.importe').val()) || 0;
|
|
var cantidad = parseFloat(fila.find('.cantidad').val()) || 0;
|
|
var precioUnitario = parseFloat(fila.find('.precioUnitario').val()) || 0; // Convertir a número
|
|
var exentoiva = parseFloat(fila.find('.EXENTOIVA').val()) || 0; // Convertir a número
|
|
//var ivaPorcentaje = 0.16; // Puedes ajustar este valor según tu necesidad
|
|
if(exentoiva==1)
|
|
{
|
|
var ivaPorcentaje = 0.00; // Puedes ajustar este valor según tu necesidad
|
|
}
|
|
else
|
|
{
|
|
var ivaPorcentaje = 0.16; // Puedes ajustar este valor según tu necesidad
|
|
}
|
|
// Calcular IVA por fila
|
|
// Calcular IVA por fila
|
|
var ivaTempo = (precioUnitario * cantidad) * ivaPorcentaje;
|
|
if (cantidad != 0) {
|
|
totalImportes += importe;
|
|
// totalIvas += ivaTempo;
|
|
|
|
totalIvas += Math.round(ivaTempo * 100) / 100;
|
|
|
|
}
|
|
|
|
|
|
});
|
|
|
|
|
|
//modificacion LASI 28 de enero mostrar conac e inah en el total
|
|
var conac = $("#conac").val()??0;
|
|
var inah = $("#inah").val()??0;
|
|
|
|
// Actualizar elementos HTML con los resultados
|
|
var subtotalElement = $('#subtotal');
|
|
var ivaElement = $('#iva');
|
|
var totalElement = $('#total');
|
|
|
|
subtotalElement.text(totalImportes.toFixed(2));
|
|
ivaElement.text(totalIvas.toFixed(2));
|
|
//totalElement.text((totalImportes + totalIvas).toFixed(2));
|
|
totalElement.text((totalImportes + totalIvas + parseFloat(conac) + parseFloat(inah)).toFixed(2));
|
|
|
|
// También actualiza los campos de input si es necesario
|
|
document.getElementById("subtotalInput").value = totalImportes.toFixed(2);
|
|
document.getElementById("ivaInput").value = totalIvas.toFixed(2);
|
|
//document.getElementById("totalInput").value = (totalImportes + totalIvas).toFixed(2);
|
|
document.getElementById("totalInput").value = (
|
|
totalImportes + totalIvas + parseFloat(conac) + parseFloat(inah)
|
|
).toFixed(2);
|
|
}
|
|
|
|
function actualizarNombresConcepto() {
|
|
$('#tablaDatos tbody tr').each(function (index) {
|
|
var fila = $(this);
|
|
fila.find('[name^="concepto["]').each(function () {
|
|
var originalName = $(this).attr('name');
|
|
var newName = 'concepto[' + index + ']' + originalName.substring(originalName.indexOf(']') + 1);
|
|
$(this).attr('name', newName);
|
|
});
|
|
});
|
|
}
|
|
|
|
function limitarDecimales() {
|
|
$(this).on('input', function () {
|
|
let value = $(this).val();
|
|
|
|
// Permite solo números y un punto decimal
|
|
value = value.replace(/[^0-9.]/g, '');
|
|
|
|
// Divide el valor en partes entera y decimal
|
|
let parts = value.split('.');
|
|
|
|
// Limita la parte decimal a dos dígitos
|
|
if (parts.length > 1) {
|
|
parts[1] = parts[1].substring(0, 2);
|
|
value = parts.join('.');
|
|
}
|
|
|
|
$(this).val(value);
|
|
});
|
|
}
|
|
|
|
function agregarFilaHandler() {
|
|
var nuevaFila = $('<tr > ' +
|
|
'<td><select class="form-control codigo" id="miSelect" name="codigo[]" style="width:auto;" size=1 >' +
|
|
' <option value="selecciona" disabled selected hidden>--</option>' +
|
|
'</select>' +
|
|
' <input type="text" class="form-control " name="concepto[' + $('#tablaDatos tbody tr').length + '][1]" style="display: none;">' +
|
|
'</td>' +
|
|
'<td><input type="text" class="form-control claveSat" name="concepto[' + $('#tablaDatos tbody tr').length + '][0]"></td>></td>' +
|
|
'<td><input type="text" class="form-control unidadMedida col-2" name="concepto[' + $('#tablaDatos tbody tr').length + '][4]">' +
|
|
'<input type="text" class="form-control " name="concepto[' + $('#tablaDatos tbody tr').length + '][3]" style="display: none;"></td>' +
|
|
'<td><input type="text" class="form-control cantidad col-2" name="concepto[' + $('#tablaDatos tbody tr').length + '][2]"></td>' +
|
|
'<td><input type="text" class="form-control precioUnitario" name="concepto[' + $('#tablaDatos tbody tr').length + '][6]"></td>' +
|
|
'<td><input type="text" disabled class="form-control importe"></td>' +
|
|
'<td><input type="number" disabled class="form-control iva" style="width: 100px;" name="concepto[' + $('#tablaDatos tbody tr').length + '][]"></td>' +
|
|
'<td><button class="btn btn-danger btnEliminarFila">Eliminar</button></td>' +
|
|
'<td><input type="text" id="descripcionConcepto" style="display: none;" class="form-control descripcion" name="concepto[' + $('#tablaDatos tbody tr').length + '][5]"></td>' +
|
|
'<td><input type="text" class="form-control EXENTOIVA" style="display: none;" name="EXENTOIVA"></td></td>' +
|
|
'</tr>');
|
|
|
|
|
|
var selectCodigo = nuevaFila.find('.codigo');
|
|
var inputCodigoHidden = nuevaFila.find('.codigo-hidden');
|
|
|
|
try {
|
|
productosArray.forEach(function (producto) {
|
|
var option = $('<option>');
|
|
// Obtener los últimos 10 caracteres y establecer la dirección del texto
|
|
var codigoProducto = producto.Matnr;
|
|
var displayText = producto.Matnr.slice(-10);
|
|
option.val(JSON.stringify(producto));
|
|
option.text(producto.Maktx);
|
|
|
|
// Aplicar la dirección del texto y la alineación
|
|
option.css({
|
|
"direction": "rtl",
|
|
"text-align": "left",
|
|
"border-bottom": "2px solid #ccc" // Agregar borde inferior
|
|
});
|
|
|
|
selectCodigo.append(option);
|
|
});
|
|
|
|
selectCodigo.on("focus", function () {
|
|
$(this).attr("size", 10);
|
|
});
|
|
|
|
selectCodigo.on("blur", function () {
|
|
$(this).attr("size", 1);
|
|
});
|
|
|
|
selectCodigo.on('change', function () {
|
|
var selectedValue = JSON.parse($(this).val());
|
|
var fila = $(this).closest('tr');
|
|
|
|
fila.find('.claveSat').val(selectedValue.Csatmat || '');
|
|
fila.find('.unidadMedida').val(selectedValue.Csatum || '');
|
|
fila.find("#descripcionConcepto").val(selectedValue.Maktx || '');
|
|
fila.find(".EXENTOIVA").val(selectedValue.EXENTOIVA || 0);//agregar exentoiva
|
|
|
|
var codigoProducto = selectedValue.Matnr;
|
|
fila.find('.form-control[name^="concepto"][name$="[1]"]').val(codigoProducto);
|
|
|
|
var codigoUnidadSat = selectedValue.Csatum;
|
|
fila.find('.form-control[name^="concepto"][name$="[12]"]').val(codigoUnidadSat);
|
|
|
|
fila.find('.form-control[name^="concepto"][name$="[3]"]').val(codigoUnidadSat);
|
|
|
|
|
|
// Después de seleccionar, volvemos a reducir el tamaño a 1
|
|
$(this).attr("size", 1);
|
|
});
|
|
|
|
} catch (error) {
|
|
alert("No se pudo obtener la lista de materiales");
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Agrega la nueva fila a la tabla
|
|
$('#tablaDatos tbody').append(nuevaFila);
|
|
|
|
nuevaFila.find('.precioUnitario').each(limitarDecimales);
|
|
|
|
|
|
// Evento para eliminar la fila al hacer clic en el botón "Eliminar"
|
|
nuevaFila.find('.btnEliminarFila').on('click', function () {
|
|
nuevaFila.remove();
|
|
calcularTotales();
|
|
actualizarNombresConcepto();
|
|
});
|
|
|
|
// Evento para calcular el importe al llenar cantidad o precio unitario en la nueva fila
|
|
nuevaFila.find('.cantidad, .precioUnitario').on('input', function () {
|
|
calcularImporte(nuevaFila);
|
|
calcularTotales();
|
|
});
|
|
|
|
|
|
|
|
// Evento para cambiar valores al seleccionar el código en la nueva fila
|
|
nuevaFila.find('.codigo').on('change', function () {
|
|
calcularImporte(nuevaFila);
|
|
calcularTotales();
|
|
actualizarNombresConcepto();
|
|
});
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
// Aplicar la función de limitar decimales a los inputs existentes (si hay)
|
|
$('.precioUnitario').each(limitarDecimales);
|
|
|
|
function consultarFolio() {
|
|
$.ajax({
|
|
url: 'php/consulta/facturas.php',
|
|
type: 'GET',
|
|
dataType: 'json',
|
|
success: function (data) {
|
|
|
|
if (data.length == 0) {
|
|
// alert('No se encontraron facturas.');
|
|
|
|
}
|
|
},
|
|
error: function (error) {
|
|
console.error('Error en la solicitud AJAX:', error);
|
|
}
|
|
});
|
|
}
|
|
|
|
//Funcion para regrear la tabla a su estado normal
|
|
function limpiarTablaHandler() {
|
|
// Elimina todas las filas de la tabla
|
|
$('#tablaDatos tbody').empty();
|
|
|
|
// Crea una nueva tabla limpia y la agrega al contenedor
|
|
var nuevaTabla = $(
|
|
'<table class="table" id="tablaDatos">' +
|
|
'<thead>' +
|
|
'<tr>' +
|
|
'<th>Código</th>' +
|
|
'<th>Clave SAT</th>' +
|
|
'<th>Descripción</th>' +
|
|
'<th>Unidad de Medida</th>' +
|
|
'<th>Cantidad</th>' +
|
|
'<th>Precio Unitario</th>' +
|
|
'<th>Importe</th>' +
|
|
'</tr>' +
|
|
'</thead>' +
|
|
'<tbody>' +
|
|
'<!-- Filas se agregarán aquí dinámicamente -->' +
|
|
'</tbody>' +
|
|
'</table>');
|
|
|
|
$('#tablaDinamica').empty().append(nuevaTabla);
|
|
}
|
|
|
|
|
|
|
|
if (boton) {
|
|
|
|
}
|
|
|
|
|
|
var pdfG = '';
|
|
|
|
|
|
function limpiarFormulario() {
|
|
|
|
|
|
|
|
var textarea = document.getElementById("texto");
|
|
textarea.value = ""; //LIMPIAR CAMPO PARA NOTAS
|
|
|
|
obtenerFolio();
|
|
limpiarTablaHandler();
|
|
|
|
|
|
var inputEmail = document.getElementById('email');
|
|
inputEmail.value = '';
|
|
var inputTelefono = document.getElementById('telefono');
|
|
inputTelefono.value = '';
|
|
document.getElementById("subtotalInput").value = '';
|
|
document.getElementById("ivaInput").value = '';
|
|
document.getElementById("totalInput").value = '';
|
|
var elementoIva = document.getElementById("iva");
|
|
var subtotal = document.getElementById("subtotal");
|
|
var total = document.getElementById("total");
|
|
elementoIva.textContent = "0.00";
|
|
subtotal.textContent = "0.00";
|
|
total.textContent = "0.00";
|
|
}
|
|
|
|
|
|
|
|
function facturaNormal(formData, user, cecoString, centroC, userName, folioP) {
|
|
|
|
toggleLoader();
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: 'php/Timbrado/timbrarApi.php',
|
|
data: formData,
|
|
processData: false,
|
|
contentType: false,
|
|
dataType: 'json',
|
|
success: function (response) {
|
|
console.log(response)
|
|
var code = response.code;
|
|
var mensaje = response.message;
|
|
var uuid = response.uuid;
|
|
pdfG = response.pdf;
|
|
console.log('Prueba json', response.uuid)
|
|
var datosTabla = obtenerDatosTabla();
|
|
//ID_VTA, ID_CLIENTE, ID_STATUS, CENTRO, centroENTAS, TOTAL_VNTA
|
|
var errores = response.errorF;
|
|
|
|
if (response.code == "200") {
|
|
toggleLoader();
|
|
$('#modalExito').modal('show');
|
|
var emailValue = $('#email').val();
|
|
$('#modalExito .modal-body p').html('La factura se ha enviado al correo: ' + emailValue + '<br>UUID:' + response.uuid);
|
|
limpiarFormulario();
|
|
}
|
|
else {
|
|
console.log('re', response);
|
|
toggleLoader();
|
|
$('#mensajeError').text(response.message);
|
|
$('#modalError').modal('show');
|
|
}
|
|
},
|
|
error: function (xhr, status, error) {
|
|
obtenerFolio();
|
|
console.log(xhr, status, error)
|
|
toggleLoader();
|
|
var mensaje = "Algo ocurrio, consulte a soporte\n\n";
|
|
let bandera = 0;
|
|
let uuid = '';
|
|
var logError = "";
|
|
|
|
// Seleccionar el elemento <p> dentro del modal
|
|
|
|
if (xhr.responseText) {
|
|
console.log('RESPONSE ERROR')
|
|
uuid = extractUuidFromText(xhr.responseText);
|
|
if (uuid) {
|
|
bandera = 1;
|
|
enviarDatosAlServidor(uuid, xhr.responseText);
|
|
} else {
|
|
enviarDatosAlServidor('ERROR DESCONOCIDO', xhr.responseText);
|
|
}
|
|
}
|
|
if (bandera == 1) {
|
|
limpiarFormulario();
|
|
const modalParagraph = document.querySelector('#staticBackdrop .modal-body p');
|
|
modalParagraph.textContent = "Algo ocurrio al guardar algunos datos, consulte a soporte\n\nLa factura se timbro con el UUID:\n" + uuid;
|
|
|
|
const myModal = new bootstrap.Modal(document.getElementById('staticBackdrop'));
|
|
myModal.show();
|
|
return;
|
|
}
|
|
$('#mensajeErrores').text(mensaje);
|
|
$('#modalErrores').modal('show');
|
|
}
|
|
});
|
|
}
|
|
|
|
|
|
function enviarDatosAlServidor(uuid, fragmentJson) {
|
|
$.ajax({
|
|
url: 'js/log_front.php',
|
|
type: 'POST',
|
|
data: {
|
|
uuid: uuid,
|
|
fragment: fragmentJson
|
|
},
|
|
success: function (response) {
|
|
console.log('Datos enviados al servidor correctamente.');
|
|
},
|
|
error: function (xhr, status, error) {
|
|
console.error('Error al enviar datos al servidor:', error);
|
|
}
|
|
});
|
|
}
|
|
|
|
function extractUuidFromText(text) {
|
|
|
|
const regex = /"uuid":"([a-f0-9-]+)"/i; // Expresión regular para buscar el UUID en el formato "uuid":"<UUID>"
|
|
const match = text.match(regex);
|
|
if (match && match[1]) {
|
|
return match[1]; // Devolver el UUID encontrado
|
|
} else {
|
|
return null; // Devolver null si no se encuentra ningún UUID
|
|
}
|
|
}
|
|
|
|
|
|
|
|
function complementoPago(formData) {
|
|
|
|
console.log(formData);
|
|
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: 'php/Timbrado/pagosApi.php',
|
|
data: formData,
|
|
contentType: false, // Eliminar esta línea
|
|
processData: false, // Eliminar esta línea
|
|
dataType: 'json',
|
|
success: function (response) {
|
|
|
|
console.log(response)
|
|
|
|
if (response.code == "200") {
|
|
obtenerFolio();
|
|
|
|
$('#modalExito').modal('show');
|
|
var emailValue = $('#email').val();
|
|
$('#modalExito .modal-body p').html('Complemento timbrado, enviado a: ' + emailValue);
|
|
document.getElementById('debe').value = '';
|
|
document.getElementById('numParcialidad').value = '';
|
|
document.getElementById('montoPagado').value = '';
|
|
document.getElementById('impSaldoInsoluto').value = '';
|
|
} else {
|
|
$('#modalExito').modal('show');
|
|
var emailValue = $('#email').val();
|
|
$('#modalExito .modal-body p').html(response.message);
|
|
}
|
|
|
|
}, error: function (error) {
|
|
console.log('Error ajax', error)
|
|
}
|
|
});
|
|
}
|
|
|
|
|
|
function guardarFactura(uuidF, folioF, id_factura) {
|
|
console.log(uuidF)
|
|
console.log(folioF)
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: 'php/RegistroFacturas/ManipulacionFacturas.php',
|
|
data: {
|
|
opcion: '4',
|
|
uuid: uuidF,
|
|
folio: folioF,
|
|
PDF: pdfG,
|
|
id_fac: id_factura
|
|
},
|
|
success: function (response) {
|
|
console.log(response);
|
|
},
|
|
error: function (error) {
|
|
console.error('Error en la segunda llamada AJAX', error);
|
|
}
|
|
});
|
|
|
|
}
|
|
|
|
function sincronizarClientes() {
|
|
toggleLoader2();
|
|
$.ajax({
|
|
url: 'Carga-Clientes/index.php',
|
|
type: 'POST',
|
|
success: function (data) {
|
|
console.log(data)
|
|
toggleLoader2();
|
|
Swal.fire("Clientes sincronizados!", "Continuar...", "success")
|
|
.then((result) => {
|
|
if (result.isConfirmed) {
|
|
|
|
}
|
|
});
|
|
|
|
},
|
|
error: function (error) {
|
|
console.error('Error en la llamada AJAX', error);
|
|
}
|
|
});
|
|
|
|
}
|
|
|
|
function sincronizarMateriales() {
|
|
toggleLoader3();
|
|
$.ajax({
|
|
url: 'Carga-Clientes/materiales.php',
|
|
type: 'POST',
|
|
success: function (data) {
|
|
console.log(data)
|
|
toggleLoader3();
|
|
Swal.fire("Materiales sincronizados!", "Continuar...", "success")
|
|
.then((result) => {
|
|
if (result.isConfirmed) {
|
|
|
|
}
|
|
});
|
|
|
|
},
|
|
error: function (error) {
|
|
console.error('Error en la llamada AJAX', error);
|
|
}
|
|
});
|
|
|
|
} |