$(document).ready(function() {
let globalIdPostFix = null;
let isSelect2DataLoaded = false;
$('.catalog-container a').on('click', function(event) {
event.preventDefault();
$('.catalog-container a').removeClass('selected');
$(this).addClass('selected');
let catalogId = $(this).data('catalog');
mostrarMiniTabla(catalogId); // Llama a la función para mostrar la mini tabla
});
let mainCatalogItem = document.querySelector('.catalog-item[data-catalog="1"]');
if (mainCatalogItem) {
mainCatalogItem.classList.add('selected');
}
cargarTablaCatalogo1();
function mostrarMiniTabla(catalogId) {
switch (catalogId) {
case 1:
cargarTablaCatalogo1();
break;
case 2:
cargarTablaCatalogo2();
break;
case 3:
cargarTablaCatalogo3();
break;
case 4:
cargarTablaCatalogo4();
break;
case 5:
cargarTablaCatalogo5();
break;
case 6:
cargarTablaCatalogo6();
break;
case 7:
cargarTablaCatalogo7();
break;
case 8:
cargarTablaCatalogo8();
break;
case 9:
cargarTablaCatalogo9();
break;
default:
$('#miniTableContainer').html('
`;
if (div) {
div.innerHTML = buttonHTML;
}
$('#miniTableContainer').html(tableHTML);
// Inicializar DataTables
$('#tablaCatalogo1').DataTable({
paging: true,
pageLength: 10,
searching: true,
info: true,
ordering: false,
lengthChange: true,
language: {
emptyTable: 'No hay datos disponibles en la tabla',
info: 'Mostrando _START_ a _END_ de _TOTAL_ entradas',
infoEmpty: 'Mostrando 0 a 0 de 0 entradas',
infoFiltered: '(filtrado de _MAX_ entradas totales)',
lengthMenu: 'Mostrar _MENU_ entradas',
search: 'Buscar:',
zeroRecords: 'No se encontraron coincidencias',
paginate: {
first: 'Primero',
last: 'Último',
next: 'Siguiente',
previous: 'Anterior'
}
}
});
// Inicializar Select2 en el botón después de mostrar la tabla
const addRowBtnCat = document.getElementById('addRowBtnCat');
addRowBtnCat.addEventListener('click', () => {
initializeSelect2('#select1', () => nivel1Options);
initializeSelect2('#select2', () => nivel2Options);
initializeSelect2('#select3', () => nivel3Options);
initializeSelect2('#select4', () => nivel4Options);
initializeSelect2('#select5', () => nivel5Options);
initializeSelect2('#select6', () => nivel6Options);
initializeSelect2('#select7', () => nivel7Options);
initializeSelect2('#selectTpCuenta', () => tcuentaOptions);
initializeSelect2('#selectNat', () => naturalezaOptions);
initializeSelect2('#selectCsat', () => csatOptions);
initializeSelect2('#selectReport', () => creportOptions);
// Mostrar el modal
$('#myModal').modal('show');
});
hideOverlay();
//Insertar Fila
$('#insertFi').off('click').on('click', function() {
const btnInsert = $(this);
btnInsert.prop('disabled', true).text('Procesando...');
// Obtener los valores seleccionados
const selectedValues = {
nivel1: $('#select1').val(),
nivel2: $('#select2').val(),
nivel3: $('#select3').val(),
nivel4: $('#select4').val(),
nivel5: $('#select5').val(),
nivel6: $('#select6').val(),
nivel7: $('#select7').val(),
tipoCuenta: $('#selectTpCuenta').val(),
naturaleza: $('#selectNat').val(),
cuentaSat: $('#selectCsat').val(),
reporte: $('#selectReport').val()
};
// Validar que al menos un valor esté seleccionado para niveles del 1 al 7
const nivelesSeleccionados = [
selectedValues.nivel1,
selectedValues.nivel2,
selectedValues.nivel3,
selectedValues.nivel4,
selectedValues.nivel5,
selectedValues.nivel6,
selectedValues.nivel7
];
// Verificar si al menos uno de los niveles del 1 al 7 tiene un valor seleccionado
const tieneNivelesValidos = nivelesSeleccionados.some(nivel => nivel !== null && nivel !== '');
const tieneCamposAdicionalesValidos =
selectedValues.tipoCuenta !== null && selectedValues.tipoCuenta !== '' &&
selectedValues.naturaleza !== null && selectedValues.naturaleza !== '' &&
selectedValues.cuentaSat !== null && selectedValues.cuentaSat !== '' &&
selectedValues.reporte !== null && selectedValues.reporte !== '';
if (!tieneNivelesValidos || !tieneCamposAdicionalesValidos) {
alert('Debe seleccionar al menos un valor para los niveles del 1 al 7 y todos los campos adicionales.');
btnInsert.prop('disabled', false).text('Insertar Fila');// Restaurar el texto del botón
return; // Salir de la función si la validación falla
}
// Enviar los datos con AJAX si la validación pasa
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/insertCatCompleto', // URL para insertar los datos
method: 'POST',
contentType: 'application/json',
data: JSON.stringify(selectedValues),
success: function(response) {
// Manejar la respuesta del servidor
console.log('Datos enviados correctamente:', response);
$('#myModal').modal('hide');
btnInsert.prop('disabled', false).text('Insertar Fila');
cargarTablaCatalogo1();
},
error: function(jqXHR, textStatus, errorThrown) {
// Manejar el error
console.error('Error al enviar los datos:', textStatus, errorThrown);
alert('Error al insertar la fila.');
btnInsert.prop('disabled', false).text('Insertar Fila');
}
});
});
$('#tablaCatalogo1 tbody').off('click', '[id^="edit_"]').on('click', '[id^="edit_"]', function () {
const buttonId = $(this).attr('id');
// Extraer el ID_CAT de la cadena del ID del botón
const idPostFix = buttonId.split('edit_')[1];
globalIdPostFix = idPostFix;
// Usar idPostFix para acceder a los valores en la fila correspondiente
const selectedValues = {
nivel1: $(`#idCatalogo_${idPostFix} [id^="nivel1_"]`).attr('id')?.split('_')[1] || null,
nivel2: $(`#idCatalogo_${idPostFix} [id^="nivel2_"]`).attr('id')?.split('_')[1] || null,
nivel3: $(`#idCatalogo_${idPostFix} [id^="nivel3_"], #idCatalogo_${idPostFix} [id^="idn3_"]`).attr('id')?.split('_')[1] || null,
nivel4: $(`#idCatalogo_${idPostFix} [id^="nivel4_"], #idCatalogo_${idPostFix} [id^="idn4_"]`).attr('id')?.split('_')[1] || null,
nivel5: $(`#idCatalogo_${idPostFix} [id^="nivel5_"], #idCatalogo_${idPostFix} [id^="idn5_"]`).attr('id')?.split('_')[1] || null,
nivel6: $(`#idCatalogo_${idPostFix} [id^="nivel6_"], #idCatalogo_${idPostFix} [id^="idn6_"]`).attr('id')?.split('_')[1] || null,
nivel7: $(`#idCatalogo_${idPostFix} [id^="nivel7_"], #idCatalogo_${idPostFix} [id^="idn7_"]`).attr('id')?.split('_')[1] || null,
tipoCuenta: $(`#idCatalogo_${idPostFix} [id^="tipoCuenta_"]`).attr('id')?.split('_')[1] || null,
naturaleza: $(`#idCatalogo_${idPostFix} [id^="idNat_"]`).attr('id')?.split('_')[1] || null,
cuentaSat: $(`#idCatalogo_${idPostFix} [id^="idSat_"]`).attr('id')?.split('_')[1] || null,
reporte: $(`#idCatalogo_${idPostFix} [id^="reporteId_"]`).attr('id')?.split('_')[1] || null
};
initializeSelect2Up('#select1Up', () => nivel1Options, selectedValues.nivel1);
initializeSelect2Up('#select2Up', () => nivel2Options, selectedValues.nivel2);
initializeSelect2Up('#select3Up', () => nivel3Options, selectedValues.nivel3);
initializeSelect2Up('#select4Up', () => nivel4Options, selectedValues.nivel4);
initializeSelect2Up('#select5Up', () => nivel5Options, selectedValues.nivel5);
initializeSelect2Up('#select6Up', () => nivel6Options, selectedValues.nivel6);
initializeSelect2Up('#select7Up', () => nivel7Options, selectedValues.nivel7);
initializeSelect2Up('#selectTpCuentaUp', () => tcuentaOptions, selectedValues.tipoCuenta);
initializeSelect2Up('#selectNatUp', () => naturalezaOptions, selectedValues.naturaleza);
initializeSelect2Up('#selectCsatUp', () => csatOptions, selectedValues.cuentaSat);
initializeSelect2Up('#selectReportUp', () => creportOptions, selectedValues.reporte);
// Mostrar el modal
$('#myModalUp').modal('show');
});
$('#actualizarFi').off('click').on('click', function() {
const btnUpdate = $(this);
btnUpdate.prop('disabled', true).text('Procesando...');
// Obtener los valores seleccionados
globalIdPostFix;
const selectedValues = {
nivel1: $('#select1Up').val(),
nivel2: $('#select2Up').val(),
nivel3: $('#select3Up').val(),
nivel4: $('#select4Up').val(),
nivel5: $('#select5Up').val(),
nivel6: $('#select6Up').val(),
nivel7: $('#select7Up').val(),
tipoCuenta: $('#selectTpCuentaUp').val(),
naturaleza: $('#selectNatUp').val(),
cuentaSat: $('#selectCsatUp').val(),
reporte: $('#selectReportUp').val()
};
// Validar que al menos un valor esté seleccionado para niveles del 1 al 7.
const nivelesSeleccionados = [
selectedValues.nivel1,
selectedValues.nivel2,
selectedValues.nivel3,
selectedValues.nivel4,
selectedValues.nivel5,
selectedValues.nivel6,
selectedValues.nivel7
];
// Verificar si al menos uno de los niveles del 1 al 7 tiene un valor seleccionado
const tieneNivelesValidos = nivelesSeleccionados.some(nivel => nivel !== null && nivel !== '');
const tieneCamposAdicionalesValidos =
selectedValues.tipoCuenta !== null && selectedValues.tipoCuenta !== '' &&
selectedValues.naturaleza !== null && selectedValues.naturaleza !== '' &&
selectedValues.cuentaSat !== null && selectedValues.cuentaSat !== '' &&
selectedValues.reporte !== null && selectedValues.reporte !== '';
if (!tieneNivelesValidos || !tieneCamposAdicionalesValidos) {
alert('Debe seleccionar al menos un valor para los niveles del 1 al 7 y todos los campos adicionales.');
btnUpdate.prop('disabled', false).text('Actualizar Fila');// Restaurar el texto del botón
return; // Salir de la función si la validación falla
}
const postData = {
ID_CAT: globalIdPostFix, // Incluye el globalIdPostFix si es necesario
...selectedValues // Añade todos los valores de nivel1, nivel2, ..., reporte
};
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/updateCat1', // Reemplaza con la URL de tu servidor
method: 'POST',
contentType: 'application/json', // Indicamos que los datos están en formato JSON
data: JSON.stringify({
catGeneral: postData
}),
success: function(response) {
// Restaurar el botón y mostrar un mensaje o realizar alguna acción adicional
btnUpdate.prop('disabled', false).text('Actualizar Fila');
cargarTablaCatalogo1();
globalIdPostFix = null;
$('#myModalUp').modal('hide');
},
error: function(xhr, status, error) {
// Maneja el error si la solicitud falla
alert('Datos iguales u ocurrio un problema');
console.log(error); // Para depuración
// Restaurar el botón y mostrar un mensaje de error
btnUpdate.prop('disabled', false).text('Actualizar Fila');
}
});
});
},
error: function() {
$('#miniTableContainer').html('
Error al cargar los datos del catálogo 1.
');
}
});
}
function cargarTablaCatalogo2() {
showOverlay();
const div = document.getElementById('divAddSave');
// Elimina cualquier botón dentro del divAddSave
if (div) {
const existingButton = div.querySelector('button');
if (existingButton) {
existingButton.remove();
}
}
const buttonProv = `
`;
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/proveedores',
method: 'GET',
success: function(response) {
let tableHTML = `
ID_PROVEEDOR
PROVEEDOR
${response.map(item => `
${item.ID_PROVEEDOR}
${item.PROVEEDOR }
`).join('')}
`;
if (div) {
div.innerHTML = buttonProv;
}
$('#miniTableContainer').html(tableHTML);
$('#tablaCatalogo2').DataTable({
paging: true,
pageLength: 10,
searching: true,
info: true,
ordering: false,
lengthChange: true,
columnDefs: [
{
targets: 0,
width: '10%' // Ajusta el ancho de la primera columna
},
{
targets: 1,
width: '90%' // Ajusta el ancho de la segunda columna
}
],
language: {
emptyTable: 'No hay datos disponibles en la tabla',
info: 'Mostrando _START_ a _END_ de _TOTAL_ entradas',
infoEmpty: 'Mostrando 0 a 0 de 0 entradas',
infoFiltered: '(filtrado de _MAX_ entradas totales)',
lengthMenu: 'Mostrar _MENU_ entradas',
search: 'Buscar:',
zeroRecords: 'No se encontraron coincidencias',
paginate: {
first: 'Primero',
last: 'Último',
next: 'Siguiente',
previous: 'Anterior'
}
}
});
hideOverlay();
//Insertar Fila
const btnInsertProv = document.getElementById('addRowBtnProv');
btnInsertProv.addEventListener('click', function() {
let rowBtn = document.getElementById('divAddSave');
if (!document.getElementById('saveBtn')) {
const saveBtn = document.createElement('button');
// Añadir texto
saveBtn.textContent = 'Guardar ';
// Añadir id
saveBtn.id = 'saveBtn';
// Añadir clase
saveBtn.classList.add('btn', 'btn-primary', 'ml-2');
// Añadir icono al botón
const iconSave = document.createElement('i');
iconSave.className = 'fas fa-save';
// Añadir icono al botón
saveBtn.appendChild(iconSave);
rowBtn.appendChild(saveBtn);
}
const uniqueId = new Date().getTime(); //Asignamos un unico ID para que no sea variable y sea unico
idprov = 'idProv_' + uniqueId;
deletIdT = 'del_' + uniqueId;
constprovedor = 'prov' + uniqueId;
let nuevaFila = `
` +
`
` +
`
` +
'
';
$('#tablaCatalogo2 tbody').prepend(nuevaFila);
});
//editar la tabla CODN1
$(document).off('click', '[id^="edProv_"]').on('click', '[id^="edProv_"]', function() {
let buttonId= $(this).attr('id');
let idProv = buttonId.split('_')[1];
let row = $('#idProv_' + idProv);
let mainRow = $(this).closest('tr');
let proveedor = row.find('td').eq(1).text().trim();
const uniqueId = idProv;
const newSelectCan = 'cancDate_' + uniqueId;
const newSelectDat = 'saveProv_' + uniqueId;
const newSelectDescripcionId = 'inptproov_'+uniqueId;
const filaOriginal = mainRow.html();
let newRow = `
`
row.replaceWith(newRow);
//dentro del scope para cancelar
$(document).on('click', '[id^="cancDate_"]', function() {
$(this).closest('tr').html(filaOriginal);
});
});
$(document).on('click', '[id^="saveProv_"]',function(){
showOverlay();
let updateProv= $(this).attr('id');
let idProv = updateProv.split('_')[1];
let newRow = $('#idProv_' + idProv);
let rowFinal = $(this).closest('tr');
let valueProveedor = newRow.find('td').eq(1).find('input').val().trim();
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/updateProveedoresTab',
type: 'POST',
data: {
ID_PROVEEDOR: idProv,
PROVEEDOR: valueProveedor
},
success: function(respuesta) {
let updateRow = `
${idProv}
${valueProveedor }
`
console.log('Éxito:', respuesta);
rowFinal.replaceWith(updateRow);
hideOverlay();
},
error: function(xhr, status, error) {
alert('No cambiaste los datos o no cumple con algún requisito');
hideOverlay();
console.error('Error:', error);
}
});
});
//INSERTAR LAS FILAS DE PROVEEDORES
$(document).off('click', '#saveBtn').on('click', '#saveBtn', function () {
showOverlay();
let isValid = true;
let allData = [];
// Iterar sobre cada fila en el tbody
$('#tablaCatalogo2 tbody tr').each(function() {
let $row = $(this);
// Verificar si la fila tiene elementos válidos (es decir, al menos un input o select con un valor)
if ($row.find('input, select').length > 0) {
// Obtener los valores de cada campo en la fila
const valorProveedor = $row.find('input[name="PROVEEDOR"]').val();
// Verificar si la fila tiene datos completos
if (valorProveedor) {
// Agregar los datos de la fila al array solo si todos los campos están completos
allData.push({
PROVEEDOR: valorProveedor,
});
} else {
isValid = false;
return false; // Rompe el each loop si una fila es inválida
}
}
});
// Si todos los campos son válidos, enviar la solicitud AJAX
if (isValid && allData.length > 0) {
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/insertProveedor',
type: 'POST',
dataType: 'json',
data: { rows: allData }, // Enviar todos los datos en un solo objeto
success: function (response) {
$('#overlay').css('visibility', 'hidden');
saveBtn.remove();
cargarTablaCatalogo2(); // Recargar los datos de la tabla
},
error: function (xhr, status, error) {
alert('Hubo un error en la inserción');
console.error('Error en la solicitud:', error);
$('#overlay').css('visibility', 'hidden');
}
});
} else {
alert('Por favor, completa todos los campos en cada fila antes de guardar.');
$('#overlay').css('visibility', 'hidden');
}
});
//Borrar Filas
$(document).on('click', '.delete-row', function () {
$(this).closest('tr').remove();
// Recalcular el número de botones de eliminación después de quitar la fila
let tamanoDeletes = $('.delete-row').length;
// Seleccionar el botón de guardar solo si existe
let saveBtn = $('#saveBtn');
// Verificar el número de filas con el botón de eliminar
if (tamanoDeletes > 1) {
// No hacer nada si hay más de una fila
return;
} else if (tamanoDeletes === 1) {
// Si hay exactamente una fila restante, no eliminar el botón de guardar
return;
} else {
// Si no hay más filas (tamanoDeletes === 0), eliminar el botón de guardar
if (saveBtn.length) {
saveBtn.remove(); // Eliminar el botón de guardar
}
}
});
},
error: function() {
$('#miniTableContainer').html('
Error al cargar los datos del catálogo 2.
');
}
});
}
//CAT 1
function cargarTablaCatalogo3() {
showOverlay();
const div = document.getElementById('divAddSave');
// Elimina cualquier botón dentro del divAddSave
if (div) {
const existingButton = div.querySelector('button');
if (existingButton) {
existingButton.remove();
}
}
const buttonProv = `
`;
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/cat1',
method: 'GET',
success: function(response) {
let tableHTML = `
ID_N1
COD_N1
NIVEL 1
${response.map(item => `
${item.ID_N1}
${item.COD_N1 }
${item.NIVEL_1 }
`).join('')}
`;
if (div) {
div.innerHTML = buttonProv;
}
$('#miniTableContainer').html(tableHTML);
$('#tablaCatalogo3').DataTable({
paging: true,
pageLength: 10,
searching: true,
info: true,
ordering: false,
lengthChange: true,
columnDefs: [
{
targets: 0,
width: '10%' // Ajusta el ancho de la primera columna
},
{
targets: 1,
width: '20%' // Ajusta el ancho de la primera columna
},
{
targets: 2,
width: '70%' // Ajusta el ancho de la segunda columna
}
],
language: {
emptyTable: 'No hay datos disponibles en la tabla',
info: 'Mostrando _START_ a _END_ de _TOTAL_ entradas',
infoEmpty: 'Mostrando 0 a 0 de 0 entradas',
infoFiltered: '(filtrado de _MAX_ entradas totales)',
lengthMenu: 'Mostrar _MENU_ entradas',
search: 'Buscar:',
zeroRecords: 'No se encontraron coincidencias',
paginate: {
first: 'Primero',
last: 'Último',
next: 'Siguiente',
previous: 'Anterior'
}
}
});
hideOverlay();
//Insertar Fila
const btnInsertProv = document.getElementById('addRowBtnCat1');
btnInsertProv.addEventListener('click', function() {
let rowBtn = document.getElementById('divAddSave');
if (!document.getElementById('saveBtn')) {
const saveBtn = document.createElement('button');
// Añadir texto
saveBtn.textContent = 'Guardar ';
// Añadir id
saveBtn.id = 'saveBtn';
// Añadir clase
saveBtn.classList.add('btn', 'btn-primary', 'ml-2');
// Añadir icono al botón
const iconSave = document.createElement('i');
iconSave.className = 'fas fa-save';
// Añadir icono al botón
saveBtn.appendChild(iconSave);
rowBtn.appendChild(saveBtn);
}
const uniqueId = new Date().getTime(); //Asignamos un unico ID para que no sea variable y sea unico
idniv1 = 'rowCodN1_' + uniqueId;
deletIdn = 'del_' + uniqueId;
constCodn1 = 'codN1_' + uniqueId;
inputNivel1 = 'levelN1_' + uniqueId;
let nuevaFila = `
` +
`
` +
`
` +
`
` +
'
';
$('#tablaCatalogo3 tbody').prepend(nuevaFila);
});
//editar la tabla CODN1
$(document).off('click', '[id^="idCodN1_"]').on('click', '[id^="idCodN1_"]', function(event) {
let buttonId = $(this).attr('id');
let idCodN1 = buttonId.split('_')[1];
let codN1Value = $('#codN1_' + idCodN1).text().trim();
let row = $('#rowCodN1_' + idCodN1); //tr principal
let mainRow = $(this).closest('tr');
let nivel = row.find('td').eq(2).text().trim();
const uniqueId = idCodN1;
const newSelectCan = 'canCD1_' + uniqueId;
const newSelectDat = 'saveCD1_' + uniqueId;
const newSelectNivel1 = 'levelN1_'+uniqueId;
const newCodNivel = 'codN1_'+uniqueId;
const filaOriginalCD1 = mainRow.html();
let newRow = `
`;
row.replaceWith(newRow);
// Dentro del scope para cancelar
$(document).on('click', '[id^="canCD1_"]', function() {
$(this).closest('tr').html(filaOriginalCD1);
});
});
$(document).on('click', '[id^="saveCD1_"]',function(){
showOverlay();
let updateCD1= $(this).attr('id');
let idCodN1 = updateCD1.split('_')[1];
let newRow = $('#rowCodN1_' + idCodN1);
let rowFinal = $(this).closest('tr');
let valueCodN1 = newRow.find('td').eq(1).find('input').val().trim();
let valueNivelCD1 = newRow.find('td').eq(2).find('input').val().trim();
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/updateCn1',
type: 'POST',
data: {
ID_N1: idCodN1,
COD_N1: valueCodN1,
NIVEL_1: valueNivelCD1
},
success: function(respuesta) {
let updateRow = `
${idCodN1}
${valueCodN1}
${valueNivelCD1}
`
console.log('Éxito:', respuesta);
rowFinal.replaceWith(updateRow);
hideOverlay();
},
error: function(xhr, status, error) {
alert('No cambiaste los datos o no cumple con algún requisito');
hideOverlay();
console.error('Error:', error);
}
});
});
//FIN EDITAR
//INSERTAR LAS FILAS DE CATN1
$(document).off('click', '#saveBtn').on('click', '#saveBtn', function () {
showOverlay();
let isValid = true;
let allData = [];
// Iterar sobre cada fila en el tbody
$('#tablaCatalogo3 tbody tr').each(function() {
let $row = $(this);
// Verificar si la fila tiene elementos válidos (es decir, al menos un input o select con un valor)
if ($row.find('input, select').length > 0) {
// Obtener los valores de cada campo en la fila
const cod_n1 = $row.find('input[name="CODN1"]').val();
const nivel1 = $row.find('input[name="NIVEL1"]').val();
// Verificar si la fila tiene datos completos
if (cod_n1 && nivel1) {
// Agregar los datos de la fila al array solo si todos los campos están completos
allData.push({
COD_N1: cod_n1,
NIVEL_1: nivel1,
});
} else {
isValid = false;
return false; // Rompe el each loop si una fila es inválida
}
}
});
// Si todos los campos son válidos, enviar la solicitud AJAX
if (isValid && allData.length > 0) {
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/insertNivel1',
type: 'POST',
dataType: 'json',
data: { rows: allData }, // Enviar todos los datos en un solo objeto
success: function (response) {
$('#overlay').css('visibility', 'hidden');
saveBtn.remove();
cargarTablaCatalogo3(); // Recargar los datos de la tabla
},
error: function (xhr, status, error) {
alert('Hubo un error en la inserción');
console.error('Error en la solicitud:', error);
$('#overlay').css('visibility', 'hidden');
}
});
} else {
alert('Por favor, completa todos los campos en cada fila antes de guardar.');
$('#overlay').css('visibility', 'hidden');
}
});
//Borrar Filas
$(document).off('click', '.delete-row').on('click', '.delete-row', function () {
$(this).closest('tr').remove();
// Recalcular el número de botones de eliminación después de quitar la fila
let tamanoDeletes = $('.delete-row').length;
// Seleccionar el botón de guardar solo si existe
let saveBtn = $('#saveBtn');
// Verificar el número de filas con el botón de eliminar
if (tamanoDeletes > 1) {
// No hacer nada si hay más de una fila
return;
} else if (tamanoDeletes === 1) {
// Si hay exactamente una fila restante, no eliminar el botón de guardar
return;
} else {
// Si no hay más filas (tamanoDeletes === 0), eliminar el botón de guardar
if (saveBtn.length) {
saveBtn.remove(); // Eliminar el botón de guardar
}
}
});
},
error: function() {
$('#miniTableContainer').html('
Error al cargar los datos del catálogo 1.
');
}
});
}
//CAT 2
function cargarTablaCatalogo4() {
showOverlay();
const div = document.getElementById('divAddSave');
// Elimina cualquier botón dentro del divAddSave
if (div) {
const existingButton = div.querySelector('button');
if (existingButton) {
existingButton.remove();
}
}
const buttonProv = `
`;
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/cat2',
method: 'GET',
success: function(response) {
let tableHTML = `
ID_N2
COD_N2
NIVEL 2
${response.map(item => `
${item.ID_N2}
${item.COD_N2 }
${item.NIVEL_2 }
`).join('')}
`;
if (div) {
div.innerHTML = buttonProv;
}
$('#miniTableContainer').html(tableHTML);
$('#tablaCatalogo4').DataTable({
paging: true,
pageLength: 10,
searching: true,
info: true,
ordering: false,
lengthChange: true,
columnDefs: [
{
targets: 0,
width: '10%' // Ajusta el ancho de la primera columna
},
{
targets: 1,
width: '20%' // Ajusta el ancho de la primera columna
},
{
targets: 2,
width: '70%' // Ajusta el ancho de la segunda columna
}
],
language: {
emptyTable: 'No hay datos disponibles en la tabla',
info: 'Mostrando _START_ a _END_ de _TOTAL_ entradas',
infoEmpty: 'Mostrando 0 a 0 de 0 entradas',
infoFiltered: '(filtrado de _MAX_ entradas totales)',
lengthMenu: 'Mostrar _MENU_ entradas',
search: 'Buscar:',
zeroRecords: 'No se encontraron coincidencias',
paginate: {
first: 'Primero',
last: 'Último',
next: 'Siguiente',
previous: 'Anterior'
}
}
});
hideOverlay();
//Insertar Fila
const btnInsertProv = document.getElementById('addRowBtnCat2');
btnInsertProv.addEventListener('click', function() {
let rowBtn = document.getElementById('divAddSave');
if (!document.getElementById('saveBtn')) {
const saveBtn = document.createElement('button');
// Añadir texto
saveBtn.textContent = 'Guardar ';
// Añadir id
saveBtn.id = 'saveBtn';
// Añadir clase
saveBtn.classList.add('btn', 'btn-primary', 'ml-2');
// Añadir icono al botón
const iconSave = document.createElement('i');
iconSave.className = 'fas fa-save';
// Añadir icono al botón
saveBtn.appendChild(iconSave);
rowBtn.appendChild(saveBtn);
}
const uniqueId = new Date().getTime(); //Asignamos un unico ID para que no sea variable y sea unico
idniv2 = 'rowCodN2_' + uniqueId;
deletIdn = 'del_' + uniqueId;
constCodn2 = 'codN1_' + uniqueId;
inputNivel2 = 'levelN2_' + uniqueId;
let nuevaFila = `
` +
`
` +
`
` +
`
` +
'
';
$('#tablaCatalogo4 tbody').prepend(nuevaFila);
});
//editar la tabla CODN2
$(document).off('click', '[id^="idCodN2_"]').on('click', '[id^="idCodN2_"]', function(event) {
let buttonId = $(this).attr('id');
let idCodN2 = buttonId.split('_')[1];
let codN2Value = $('#codN2_' + idCodN2).text().trim();
let row = $('#rowCodN2_' + idCodN2); //tr principal
let mainRow = $(this).closest('tr');
let nivel = row.find('td').eq(2).text().trim();
const uniqueId = idCodN2;
const newSelectCan = 'canCD2_' + uniqueId;
const newSelectDat = 'saveCD2_' + uniqueId;
const newSelectNivel2 = 'levelN2_'+uniqueId;
const newCodNivel = 'codN2_'+uniqueId;
const filaOriginalCD2 = mainRow.html();
let newRow = `
`;
row.replaceWith(newRow);
// Dentro del scope para cancelar
$(document).on('click', '[id^="canCD2_"]', function() {
$(this).closest('tr').html(filaOriginalCD2);
});
});
$(document).on('click', '[id^="saveCD2_"]',function(){
showOverlay();
let updateCD2= $(this).attr('id');
let idCodN2 = updateCD2.split('_')[1];
let newRow = $('#rowCodN2_' + idCodN2);
let rowFinal = $(this).closest('tr');
let valueCodN2 = newRow.find('td').eq(1).find('input').val().trim();
let valueNivelCD2 = newRow.find('td').eq(2).find('input').val().trim();
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/updateCn2',
type: 'POST',
data: {
ID_N2: idCodN2,
COD_N2: valueCodN2,
NIVEL_2: valueNivelCD2
},
success: function(respuesta) {
let updateRow = `
${idCodN2}
${valueCodN2}
${valueNivelCD2}
`
console.log('Éxito:', respuesta);
rowFinal.replaceWith(updateRow);
hideOverlay();
},
error: function(xhr, status, error) {
alert('No cambiaste los datos o no cumple con algún requisito');
hideOverlay();
console.error('Error:', error);
}
});
});
//FIN EDITAR
//INSERTAR LAS FILAS CAT2
$(document).off('click', '#saveBtn').on('click', '#saveBtn', function () {
showOverlay();
let isValid = true;
let allData = [];
// Iterar sobre cada fila en el tbody
$('#tablaCatalogo4 tbody tr').each(function() {
let $row = $(this);
// Verificar si la fila tiene elementos válidos (es decir, al menos un input o select con un valor)
if ($row.find('input, select').length > 0) {
// Obtener los valores de cada campo en la fila
const cod_n2 = $row.find('input[name="CODN2"]').val();
const nivel2 = $row.find('input[name="NIVEL2"]').val();
// Verificar si la fila tiene datos completos
if (cod_n2 && nivel2) {
// Agregar los datos de la fila al array solo si todos los campos están completos
allData.push({
COD_N2: cod_n2,
NIVEL_2: nivel2,
});
} else {
isValid = false;
return false; // Rompe el each loop si una fila es inválida
}
}
});
// Si todos los campos son válidos, enviar la solicitud AJAX
if (isValid && allData.length > 0) {
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/insertNivel2',
type: 'POST',
dataType: 'json',
data: { rows: allData }, // Enviar todos los datos en un solo objeto
success: function (response) {
$('#overlay').css('visibility', 'hidden');
saveBtn.remove();
cargarTablaCatalogo4(); // Recargar los datos de la tabla
},
error: function (xhr, status, error) {
alert('Hubo un error en la inserción');
console.error('Error en la solicitud:', error);
$('#overlay').css('visibility', 'hidden');
}
});
} else {
alert('Por favor, completa todos los campos en cada fila antes de guardar.');
$('#overlay').css('visibility', 'hidden');
}
});
//Borrar Filas
$(document).off('click', '.delete-row').on('click', '.delete-row', function () {
$(this).closest('tr').remove();
// Recalcular el número de botones de eliminación después de quitar la fila
let tamanoDeletes = $('.delete-row').length;
// Seleccionar el botón de guardar solo si existe
let saveBtn = $('#saveBtn');
// Verificar el número de filas con el botón de eliminar
if (tamanoDeletes > 1) {
// No hacer nada si hay más de una fila
return;
} else if (tamanoDeletes === 1) {
// Si hay exactamente una fila restante, no eliminar el botón de guardar
return;
} else {
// Si no hay más filas (tamanoDeletes === 0), eliminar el botón de guardar
if (saveBtn.length) {
saveBtn.remove(); // Eliminar el botón de guardar
}
}
});
},
error: function() {
$('#miniTableContainer').html('
Error al cargar los datos del catálogo 2.
');
}
});
}
//CAT 3
function cargarTablaCatalogo5() {
showOverlay();
const div = document.getElementById('divAddSave');
// Elimina cualquier botón dentro del divAddSave
if (div) {
const existingButton = div.querySelector('button');
if (existingButton) {
existingButton.remove();
}
}
const buttonProv = `
`;
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/cat3',
method: 'GET',
success: function(response) {
let tableHTML = `
ID_N3
COD_N3
NIVEL 3
${response.map(item => `
${item.ID_N3}
${item.COD_N3 }
${item.NIVEL_3 }
`).join('')}
`;
if (div) {
div.innerHTML = buttonProv;
}
$('#miniTableContainer').html(tableHTML);
$('#tablaCatalogo5').DataTable({
paging: true,
pageLength: 10,
searching: true,
info: true,
ordering: false,
lengthChange: true,
columnDefs: [
{
targets: 0,
width: '10%' // Ajusta el ancho de la primera columna
},
{
targets: 1,
width: '20%' // Ajusta el ancho de la primera columna
},
{
targets: 2,
width: '70%' // Ajusta el ancho de la segunda columna
}
],
language: {
emptyTable: 'No hay datos disponibles en la tabla',
info: 'Mostrando _START_ a _END_ de _TOTAL_ entradas',
infoEmpty: 'Mostrando 0 a 0 de 0 entradas',
infoFiltered: '(filtrado de _MAX_ entradas totales)',
lengthMenu: 'Mostrar _MENU_ entradas',
search: 'Buscar:',
zeroRecords: 'No se encontraron coincidencias',
paginate: {
first: 'Primero',
last: 'Último',
next: 'Siguiente',
previous: 'Anterior'
}
}
});
hideOverlay();
//Insertar Fila
const btnInsertProv = document.getElementById('addRowBtnCat3');
btnInsertProv.addEventListener('click', function() {
let rowBtn = document.getElementById('divAddSave');
if (!document.getElementById('saveBtn')) {
const saveBtn = document.createElement('button');
// Añadir texto
saveBtn.textContent = 'Guardar ';
// Añadir id
saveBtn.id = 'saveBtn';
// Añadir clase
saveBtn.classList.add('btn', 'btn-primary', 'ml-2');
// Añadir icono al botón
const iconSave = document.createElement('i');
iconSave.className = 'fas fa-save';
// Añadir icono al botón
saveBtn.appendChild(iconSave);
rowBtn.appendChild(saveBtn);
}
const uniqueId = new Date().getTime(); //Asignamos un unico ID para que no sea variable y sea unico
idniv3 = 'rowCodN3_' + uniqueId;
deletIdn = 'del_' + uniqueId;
constCodn3 = 'codN3_' + uniqueId;
inputNivel3 = 'levelN3_' + uniqueId;
let nuevaFila = `
` +
`
` +
`
` +
`
` +
'
';
$('#tablaCatalogo5 tbody').prepend(nuevaFila);
});
//editar la tabla CODN3
$(document).off('click', '[id^="idCodN3_"]').on('click', '[id^="idCodN3_"]', function(event) {
let buttonId = $(this).attr('id');
let idCodN3 = buttonId.split('_')[1];
let codN3Value = $('#codN3_' + idCodN3).text().trim();
let row = $('#rowCodN3_' + idCodN3); //tr principal
let mainRow = $(this).closest('tr');
let nivel = row.find('td').eq(2).text().trim();
const uniqueId = idCodN3;
const newSelectCan = 'canCD3_' + uniqueId;
const newSelectDat = 'saveCD3_' + uniqueId;
const newSelectNivel3 = 'levelN3_'+uniqueId;
const newCodNivel = 'codN3_'+uniqueId;
const filaOriginalCD3 = mainRow.html();
let newRow = `
`;
row.replaceWith(newRow);
// Dentro del scope para cancelar
$(document).on('click', '[id^="canCD3_"]', function() {
$(this).closest('tr').html(filaOriginalCD3);
});
});
$(document).on('click', '[id^="saveCD3_"]',function(){
showOverlay();
let updateCD3= $(this).attr('id');
let idCodN3 = updateCD3.split('_')[1];
let newRow = $('#rowCodN3_' + idCodN3);
let rowFinal = $(this).closest('tr');
let valueCodN3 = newRow.find('td').eq(1).find('input').val().trim();
let valueNivelCD3 = newRow.find('td').eq(2).find('input').val().trim();
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/updateCn3',
type: 'POST',
data: {
ID_N3: idCodN3,
COD_N3: valueCodN3,
NIVEL_3: valueNivelCD3
},
success: function(respuesta) {
let updateRow = `
${idCodN3}
${valueCodN3}
${valueNivelCD3}
`
console.log('Éxito:', respuesta);
rowFinal.replaceWith(updateRow);
hideOverlay();
},
error: function(xhr, status, error) {
alert('No cambiaste los datos o no cumple con algún requisito');
hideOverlay();
console.error('Error:', error);
}
});
});
//FIN EDITAR
//INSERTAR LAS FILAS DE PROVEEDORES
$(document).off('click', '#saveBtn').on('click', '#saveBtn', function () {
showOverlay();
let isValid = true;
let allData = [];
// Iterar sobre cada fila en el tbody
$('#tablaCatalogo5 tbody tr').each(function() {
let $row = $(this);
// Verificar si la fila tiene elementos válidos (es decir, al menos un input o select con un valor)
if ($row.find('input, select').length > 0) {
// Obtener los valores de cada campo en la fila
const cod_n3 = $row.find('input[name="CODN3"]').val();
const nivel3 = $row.find('input[name="NIVEL3"]').val();
// Verificar si la fila tiene datos completos
if (cod_n3 && nivel3) {
// Agregar los datos de la fila al array solo si todos los campos están completos
allData.push({
COD_N3: cod_n3,
NIVEL_3: nivel3,
});
} else {
isValid = false;
return false; // Rompe el each loop si una fila es inválida
}
}
});
// Si todos los campos son válidos, enviar la solicitud AJAX
if (isValid && allData.length > 0) {
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/insertNivel3',
type: 'POST',
dataType: 'json',
data: { rows: allData }, // Enviar todos los datos en un solo objeto
success: function (response) {
$('#overlay').css('visibility', 'hidden');
saveBtn.remove();
cargarTablaCatalogo5(); // Recargar los datos de la tabla
},
error: function (xhr, status, error) {
alert('Hubo un error en la inserción');
console.error('Error en la solicitud:', error);
$('#overlay').css('visibility', 'hidden');
}
});
} else {
alert('Por favor, completa todos los campos en cada fila antes de guardar.');
$('#overlay').css('visibility', 'hidden');
}
});
//Borrar Filas
$(document).off('click', '.delete-row').on('click', '.delete-row', function () {
$(this).closest('tr').remove();
// Recalcular el número de botones de eliminación después de quitar la fila
let tamanoDeletes = $('.delete-row').length;
// Seleccionar el botón de guardar solo si existe
let saveBtn = $('#saveBtn');
// Verificar el número de filas con el botón de eliminar
if (tamanoDeletes > 1) {
// No hacer nada si hay más de una fila
return;
} else if (tamanoDeletes === 1) {
// Si hay exactamente una fila restante, no eliminar el botón de guardar
return;
} else {
// Si no hay más filas (tamanoDeletes === 0), eliminar el botón de guardar
if (saveBtn.length) {
saveBtn.remove(); // Eliminar el botón de guardar
}
}
});
},
error: function() {
$('#miniTableContainer').html('
Error al cargar los datos del catálogo 3.
');
}
});
}
//CAT 4
function cargarTablaCatalogo6() {
showOverlay();
const div = document.getElementById('divAddSave');
// Elimina cualquier botón dentro del divAddSave
if (div) {
const existingButton = div.querySelector('button');
if (existingButton) {
existingButton.remove();
}
}
const buttonProv = `
`;
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/cat4',
method: 'GET',
success: function(response) {
let tableHTML = `
ID_N4
COD_N4
NIVEL 4
${response.map(item => `
${item.ID_N4}
${item.COD_N4 }
${item.NIVEL_4 }
`).join('')}
`;
if (div) {
div.innerHTML = buttonProv;
}
$('#miniTableContainer').html(tableHTML);
$('#tablaCatalogo6').DataTable({
paging: true,
pageLength: 10,
searching: true,
info: true,
ordering: false,
lengthChange: true,
columnDefs: [
{
targets: 0,
width: '10%' // Ajusta el ancho de la primera columna
},
{
targets: 1,
width: '20%' // Ajusta el ancho de la primera columna
},
{
targets: 2,
width: '70%' // Ajusta el ancho de la segunda columna
}
],
language: {
emptyTable: 'No hay datos disponibles en la tabla',
info: 'Mostrando _START_ a _END_ de _TOTAL_ entradas',
infoEmpty: 'Mostrando 0 a 0 de 0 entradas',
infoFiltered: '(filtrado de _MAX_ entradas totales)',
lengthMenu: 'Mostrar _MENU_ entradas',
search: 'Buscar:',
zeroRecords: 'No se encontraron coincidencias',
paginate: {
first: 'Primero',
last: 'Último',
next: 'Siguiente',
previous: 'Anterior'
}
}
});
hideOverlay();
//Insertar Fila
const btnInsertProv = document.getElementById('addRowBtnCat4');
btnInsertProv.addEventListener('click', function() {
let rowBtn = document.getElementById('divAddSave');
if (!document.getElementById('saveBtn')) {
const saveBtn = document.createElement('button');
// Añadir texto
saveBtn.textContent = 'Guardar ';
// Añadir id
saveBtn.id = 'saveBtn';
// Añadir clase
saveBtn.classList.add('btn', 'btn-primary', 'ml-2');
// Añadir icono al botón
const iconSave = document.createElement('i');
iconSave.className = 'fas fa-save';
// Añadir icono al botón
saveBtn.appendChild(iconSave);
rowBtn.appendChild(saveBtn);
}
const uniqueId = new Date().getTime(); //Asignamos un unico ID para que no sea variable y sea unico
idniv4 = 'rowCodN4_' + uniqueId;
deletIdn = 'del_' + uniqueId;
constCodn4 = 'codN4_' + uniqueId;
inputNivel4 = 'levelN4_' + uniqueId;
let nuevaFila = `
` +
`
` +
`
` +
`
` +
'
';
$('#tablaCatalogo6 tbody').prepend(nuevaFila);
});
//editar la tabla CODN4
$(document).off('click', '[id^="idCodN4_"]').on('click', '[id^="idCodN4_"]', function(event) {
let buttonId = $(this).attr('id');
let idCodN4 = buttonId.split('_')[1];
let codN4Value = $('#codN4_' + idCodN4).text().trim();
let row = $('#rowCodN4_' + idCodN4); //tr principal
let mainRow = $(this).closest('tr');
let nivel = row.find('td').eq(2).text().trim();
const uniqueId = idCodN4;
const newSelectCan = 'canCD4_' + uniqueId;
const newSelectDat = 'saveCD4_' + uniqueId;
const newSelectNivel4 = 'levelN4_'+uniqueId;
const newCodNivel = 'codN4_'+uniqueId;
const filaOriginalCD4 = mainRow.html();
let newRow = `
`;
row.replaceWith(newRow);
// Dentro del scope para cancelar
$(document).on('click', '[id^="canCD4_"]', function() {
$(this).closest('tr').html(filaOriginalCD4);
});
});
$(document).on('click', '[id^="saveCD4_"]',function(){
showOverlay();
let updateCD4= $(this).attr('id');
let idCodN4 = updateCD4.split('_')[1];
let newRow = $('#rowCodN4_' + idCodN4);
let rowFinal = $(this).closest('tr');
let valueCodN4 = newRow.find('td').eq(1).find('input').val().trim();
let valueNivelCD4 = newRow.find('td').eq(2).find('input').val().trim();
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/updateCn4',
type: 'POST',
data: {
ID_N4: idCodN4,
COD_N4: valueCodN4,
NIVEL_4: valueNivelCD4
},
success: function(respuesta) {
let updateRow = `
${idCodN4}
${valueCodN4}
${valueNivelCD4}
`
console.log('Éxito:', respuesta);
rowFinal.replaceWith(updateRow);
hideOverlay();
},
error: function(xhr, status, error) {
alert('No cambiaste los datos o no cumple con algún requisito');
hideOverlay();
console.error('Error:', error);
}
});
});
//FIN EDITAR
//INSERTAR LAS FILAS DE PROVEEDORES
$(document).off('click', '#saveBtn').on('click', '#saveBtn', function () {
showOverlay();
let isValid = true;
let allData = [];
// Iterar sobre cada fila en el tbody
$('#tablaCatalogo6 tbody tr').each(function() {
let $row = $(this);
// Verificar si la fila tiene elementos válidos (es decir, al menos un input o select con un valor)
if ($row.find('input, select').length > 0) {
// Obtener los valores de cada campo en la fila
const cod_n4 = $row.find('input[name="CODN4"]').val();
const nivel4 = $row.find('input[name="NIVEL4"]').val();
// Verificar si la fila tiene datos completos
if (cod_n4 && nivel4) {
// Agregar los datos de la fila al array solo si todos los campos están completos
allData.push({
COD_N4: cod_n4,
NIVEL_4: nivel4,
});
} else {
isValid = false;
return false; // Rompe el each loop si una fila es inválida
}
}
});
// Si todos los campos son válidos, enviar la solicitud AJAX
if (isValid && allData.length > 0) {
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/insertNivel4',
type: 'POST',
dataType: 'json',
data: { rows: allData }, // Enviar todos los datos en un solo objeto
success: function (response) {
$('#overlay').css('visibility', 'hidden');
saveBtn.remove();
cargarTablaCatalogo6(); // Recargar los datos de la tabla
},
error: function (xhr, status, error) {
alert('Hubo un error en la inserción');
console.error('Error en la solicitud:', error);
$('#overlay').css('visibility', 'hidden');
}
});
} else {
alert('Por favor, completa todos los campos en cada fila antes de guardar.');
$('#overlay').css('visibility', 'hidden');
}
});
//Borrar Filas
$(document).off('click', '.delete-row').on('click', '.delete-row', function () {
$(this).closest('tr').remove();
// Recalcular el número de botones de eliminación después de quitar la fila
let tamanoDeletes = $('.delete-row').length;
// Seleccionar el botón de guardar solo si existe
let saveBtn = $('#saveBtn');
// Verificar el número de filas con el botón de eliminar
if (tamanoDeletes > 1) {
// No hacer nada si hay más de una fila
return;
} else if (tamanoDeletes === 1) {
// Si hay exactamente una fila restante, no eliminar el botón de guardar
return;
} else {
// Si no hay más filas (tamanoDeletes === 0), eliminar el botón de guardar
if (saveBtn.length) {
saveBtn.remove(); // Eliminar el botón de guardar
}
}
});
},
error: function() {
$('#miniTableContainer').html('
Error al cargar los datos del catálogo 4.
');
}
});
}
//CAT 5
function cargarTablaCatalogo7() {
showOverlay();
const div = document.getElementById('divAddSave');
// Elimina cualquier botón dentro del divAddSave
if (div) {
const existingButton = div.querySelector('button');
if (existingButton) {
existingButton.remove();
}
}
const buttonProv = `
`;
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/cat5',
method: 'GET',
success: function(response) {
let tableHTML = `
ID_N5
COD_N5
NIVEL 5
${response.map(item => `
${item.ID_N5}
${item.COD_N5 }
${item.NIVEL_5 }
`).join('')}
`;
if (div) {
div.innerHTML = buttonProv;
}
$('#miniTableContainer').html(tableHTML);
$('#tablaCatalogo7').DataTable({
paging: true,
pageLength: 10,
searching: true,
info: true,
ordering: false,
lengthChange: true,
columnDefs: [
{
targets: 0,
width: '10%' // Ajusta el ancho de la primera columna
},
{
targets: 1,
width: '20%' // Ajusta el ancho de la primera columna
},
{
targets: 2,
width: '70%' // Ajusta el ancho de la segunda columna
}
],
language: {
emptyTable: 'No hay datos disponibles en la tabla',
info: 'Mostrando _START_ a _END_ de _TOTAL_ entradas',
infoEmpty: 'Mostrando 0 a 0 de 0 entradas',
infoFiltered: '(filtrado de _MAX_ entradas totales)',
lengthMenu: 'Mostrar _MENU_ entradas',
search: 'Buscar:',
zeroRecords: 'No se encontraron coincidencias',
paginate: {
first: 'Primero',
last: 'Último',
next: 'Siguiente',
previous: 'Anterior'
}
}
});
hideOverlay();
//Insertar Fila
const btnInsertProv = document.getElementById('addRowBtnCat5');
btnInsertProv.addEventListener('click', function() {
let rowBtn = document.getElementById('divAddSave');
if (!document.getElementById('saveBtn')) {
const saveBtn = document.createElement('button');
// Añadir texto
saveBtn.textContent = 'Guardar ';
// Añadir id
saveBtn.id = 'saveBtn';
// Añadir clase
saveBtn.classList.add('btn', 'btn-primary', 'ml-2');
// Añadir icono al botón
const iconSave = document.createElement('i');
iconSave.className = 'fas fa-save';
// Añadir icono al botón
saveBtn.appendChild(iconSave);
rowBtn.appendChild(saveBtn);
}
const uniqueId = new Date().getTime(); //Asignamos un unico ID para que no sea variable y sea unico
idniv5 = 'rowCodN5_' + uniqueId;
deletIdn = 'del_' + uniqueId;
constCodn5 = 'codN5_' + uniqueId;
inputNivel5 = 'levelN5_' + uniqueId;
let nuevaFila = `
` +
`
` +
`
` +
`
` +
'
';
$('#tablaCatalogo7 tbody').prepend(nuevaFila);
});
//editar la tabla CODN5
$(document).off('click', '[id^="idCodN5_"]').on('click', '[id^="idCodN5_"]', function(event) {
let buttonId = $(this).attr('id');
let idCodN5 = buttonId.split('_')[1];
let codN5Value = $('#codN5_' + idCodN5).text().trim();
let row = $('#rowCodN5_' + idCodN5); //tr principal
let mainRow = $(this).closest('tr');
let nivel = row.find('td').eq(2).text().trim();
const uniqueId = idCodN5;
const newSelectCan = 'canCD5_' + uniqueId;
const newSelectDat = 'saveCD5_' + uniqueId;
const newSelectNivel5 = 'levelN5_'+uniqueId;
const newCodNivel = 'codN5_'+uniqueId;
const filaOriginalCD5 = mainRow.html();
let newRow = `
`;
row.replaceWith(newRow);
// Dentro del scope para cancelar
$(document).on('click', '[id^="canCD5_"]', function() {
$(this).closest('tr').html(filaOriginalCD5);
});
});
$(document).on('click', '[id^="saveCD5_"]',function(){
showOverlay();
let updateCD5= $(this).attr('id');
let idCodN5 = updateCD5.split('_')[1];
let newRow = $('#rowCodN5_' + idCodN5);
let rowFinal = $(this).closest('tr');
let valueCodN5 = newRow.find('td').eq(1).find('input').val().trim();
let valueNivelCD5 = newRow.find('td').eq(2).find('input').val().trim();
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/updateCn5',
type: 'POST',
data: {
ID_N5: idCodN5,
COD_N5: valueCodN5,
NIVEL_5: valueNivelCD5
},
success: function(respuesta) {
let updateRow = `
${idCodN5}
${valueCodN5}
${valueNivelCD5}
`
console.log('Éxito:', respuesta);
rowFinal.replaceWith(updateRow);
hideOverlay();
},
error: function(xhr, status, error) {
alert('No cambiaste los datos o no cumple con algún requisito');
hideOverlay();
console.error('Error:', error);
}
});
});
//FIN EDITAR
//INSERTAR LAS FILAS DE PROVEEDORES
$(document).off('click', '#saveBtn').on('click', '#saveBtn', function () {
showOverlay();
let isValid = true;
let allData = [];
// Iterar sobre cada fila en el tbody
$('#tablaCatalogo7 tbody tr').each(function() {
let $row = $(this);
// Verificar si la fila tiene elementos válidos (es decir, al menos un input o select con un valor)
if ($row.find('input, select').length > 0) {
// Obtener los valores de cada campo en la fila
const cod_n5 = $row.find('input[name="CODN5"]').val();
const nivel5 = $row.find('input[name="NIVEL5"]').val();
// Verificar si la fila tiene datos completos
if (cod_n5 && nivel5) {
// Agregar los datos de la fila al array solo si todos los campos están completos
allData.push({
COD_N5: cod_n5,
NIVEL_5: nivel5,
});
} else {
isValid = false;
return false; // Rompe el each loop si una fila es inválida
}
}
});
// Si todos los campos son válidos, enviar la solicitud AJAX
if (isValid && allData.length > 0) {
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/insertNivel5',
type: 'POST',
dataType: 'json',
data: { rows: allData }, // Enviar todos los datos en un solo objeto
success: function (response) {
$('#overlay').css('visibility', 'hidden');
saveBtn.remove();
cargarTablaCatalogo7(); // Recargar los datos de la tabla
},
error: function (xhr, status, error) {
alert('Hubo un error en la inserción');
console.error('Error en la solicitud:', error);
$('#overlay').css('visibility', 'hidden');
}
});
} else {
alert('Por favor, completa todos los campos en cada fila antes de guardar.');
$('#overlay').css('visibility', 'hidden');
}
});
//Borrar Filas
$(document).off('click', '.delete-row').on('click', '.delete-row', function () {
$(this).closest('tr').remove();
// Recalcular el número de botones de eliminación después de quitar la fila
let tamanoDeletes = $('.delete-row').length;
// Seleccionar el botón de guardar solo si existe
let saveBtn = $('#saveBtn');
// Verificar el número de filas con el botón de eliminar
if (tamanoDeletes > 1) {
// No hacer nada si hay más de una fila
return;
} else if (tamanoDeletes === 1) {
// Si hay exactamente una fila restante, no eliminar el botón de guardar
return;
} else {
// Si no hay más filas (tamanoDeletes === 0), eliminar el botón de guardar
if (saveBtn.length) {
saveBtn.remove(); // Eliminar el botón de guardar
}
}
});
},
error: function() {
$('#miniTableContainer').html('
Error al cargar los datos del catálogo 5.
');
}
});
}
//CAT 6
function cargarTablaCatalogo8() {
showOverlay();
const div = document.getElementById('divAddSave');
// Elimina cualquier botón dentro del divAddSave
if (div) {
const existingButton = div.querySelector('button');
if (existingButton) {
existingButton.remove();
}
}
const buttonProv = `
`;
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/cat6',
method: 'GET',
success: function(response) {
let tableHTML = `
ID_N6
COD_N6
NIVEL 6
${response.map(item => `
${item.ID_N6}
${item.COD_N6 }
${item.NIVEL_6 }
`).join('')}
`;
if (div) {
div.innerHTML = buttonProv;
}
$('#miniTableContainer').html(tableHTML);
$('#tablaCatalogo8').DataTable({
paging: true,
pageLength: 10,
searching: true,
info: true,
ordering: false,
lengthChange: true,
columnDefs: [
{
targets: 0,
width: '10%' // Ajusta el ancho de la primera columna
},
{
targets: 1,
width: '20%' // Ajusta el ancho de la primera columna
},
{
targets: 2,
width: '70%' // Ajusta el ancho de la segunda columna
}
],
language: {
emptyTable: 'No hay datos disponibles en la tabla',
info: 'Mostrando _START_ a _END_ de _TOTAL_ entradas',
infoEmpty: 'Mostrando 0 a 0 de 0 entradas',
infoFiltered: '(filtrado de _MAX_ entradas totales)',
lengthMenu: 'Mostrar _MENU_ entradas',
search: 'Buscar:',
zeroRecords: 'No se encontraron coincidencias',
paginate: {
first: 'Primero',
last: 'Último',
next: 'Siguiente',
previous: 'Anterior'
}
}
});
hideOverlay();
//Insertar Fila
const btnInsertProv = document.getElementById('addRowBtnCat6');
btnInsertProv.addEventListener('click', function() {
let rowBtn = document.getElementById('divAddSave');
if (!document.getElementById('saveBtn')) {
const saveBtn = document.createElement('button');
// Añadir texto
saveBtn.textContent = 'Guardar ';
// Añadir id
saveBtn.id = 'saveBtn';
// Añadir clase
saveBtn.classList.add('btn', 'btn-primary', 'ml-2');
// Añadir icono al botón
const iconSave = document.createElement('i');
iconSave.className = 'fas fa-save';
// Añadir icono al botón
saveBtn.appendChild(iconSave);
rowBtn.appendChild(saveBtn);
}
const uniqueId = new Date().getTime(); //Asignamos un unico ID para que no sea variable y sea unico
idniv6 = 'rowCodN6_' + uniqueId;
deletIdn = 'del_' + uniqueId;
constCodn6 = 'codN6_' + uniqueId;
inputNivel6 = 'levelN6_' + uniqueId;
let nuevaFila = `
` +
`
` +
`
` +
`
` +
'
';
$('#tablaCatalogo8 tbody').prepend(nuevaFila);
});
//editar la tabla CODN6
$(document).off('click', '[id^="idCodN6_"]').on('click', '[id^="idCodN6_"]', function(event) {
let buttonId = $(this).attr('id');
let idCodN6 = buttonId.split('_')[1];
let codN6Value = $('#codN6_' + idCodN6).text().trim();
let row = $('#rowCodN6_' + idCodN6); //tr principal
let mainRow = $(this).closest('tr');
let nivel = row.find('td').eq(2).text().trim();
const uniqueId = idCodN6;
const newSelectCan = 'canCD6_' + uniqueId;
const newSelectDat = 'saveCD6_' + uniqueId;
const newSelectNivel6 = 'levelN6_'+uniqueId;
const newCodNivel = 'codN6_'+uniqueId;
const filaOriginalCD6 = mainRow.html();
let newRow = `
`;
row.replaceWith(newRow);
// Dentro del scope para cancelar
$(document).on('click', '[id^="canCD6_"]', function() {
$(this).closest('tr').html(filaOriginalCD6);
});
});
$(document).on('click', '[id^="saveCD6_"]',function(){
showOverlay();
let updateCD6= $(this).attr('id');
let idCodN6 = updateCD6.split('_')[1];
let newRow = $('#rowCodN6_' + idCodN6);
let rowFinal = $(this).closest('tr');
let valueCodN6 = newRow.find('td').eq(1).find('input').val().trim();
let valueNivelCD6 = newRow.find('td').eq(2).find('input').val().trim();
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/updateCn6',
type: 'POST',
data: {
ID_N6: idCodN6,
COD_N6: valueCodN6,
NIVEL_6: valueNivelCD6
},
success: function(respuesta) {
let updateRow = `
${idCodN6}
${valueCodN6}
${valueNivelCD6}
`
console.log('Éxito:', respuesta);
rowFinal.replaceWith(updateRow);
hideOverlay();
},
error: function(xhr, status, error) {
alert('No cambiaste los datos o no cumple con algún requisito');
hideOverlay();
console.error('Error:', error);
}
});
});
//FIN EDITAR
//INSERTAR LAS FILAS DE PROVEEDORES
$(document).off('click', '#saveBtn').on('click', '#saveBtn', function () {
showOverlay();
let isValid = true;
let allData = [];
// Iterar sobre cada fila en el tbody
$('#tablaCatalogo8 tbody tr').each(function() {
let $row = $(this);
// Verificar si la fila tiene elementos válidos (es decir, al menos un input o select con un valor)
if ($row.find('input, select').length > 0) {
// Obtener los valores de cada campo en la fila
const cod_n6 = $row.find('input[name="CODN6"]').val();
const nivel6 = $row.find('input[name="NIVEL6"]').val();
// Verificar si la fila tiene datos completos
if (cod_n6 && nivel6) {
// Agregar los datos de la fila al array solo si todos los campos están completos
allData.push({
COD_N6: cod_n6,
NIVEL_6: nivel6,
});
} else {
isValid = false;
return false; // Rompe el each loop si una fila es inválida
}
}
});
// Si todos los campos son válidos, enviar la solicitud AJAX
if (isValid && allData.length > 0) {
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/insertNivel6',
type: 'POST',
dataType: 'json',
data: { rows: allData }, // Enviar todos los datos en un solo objeto
success: function (response) {
$('#overlay').css('visibility', 'hidden');
saveBtn.remove();
cargarTablaCatalogo8(); // Recargar los datos de la tabla
},
error: function (xhr, status, error) {
alert('Hubo un error en la inserción');
console.error('Error en la solicitud:', error);
$('#overlay').css('visibility', 'hidden');
}
});
} else {
alert('Por favor, completa todos los campos en cada fila antes de guardar.');
$('#overlay').css('visibility', 'hidden');
}
});
//Borrar Filas
$(document).off('click', '.delete-row').on('click', '.delete-row', function () {
$(this).closest('tr').remove();
// Recalcular el número de botones de eliminación después de quitar la fila
let tamanoDeletes = $('.delete-row').length;
// Seleccionar el botón de guardar solo si existe
let saveBtn = $('#saveBtn');
// Verificar el número de filas con el botón de eliminar
if (tamanoDeletes > 1) {
// No hacer nada si hay más de una fila
return;
} else if (tamanoDeletes === 1) {
// Si hay exactamente una fila restante, no eliminar el botón de guardar
return;
} else {
// Si no hay más filas (tamanoDeletes === 0), eliminar el botón de guardar
if (saveBtn.length) {
saveBtn.remove(); // Eliminar el botón de guardar
}
}
});
},
error: function() {
$('#miniTableContainer').html('
Error al cargar los datos del catálogo 6.
');
}
});
}
//CAT 7
function cargarTablaCatalogo9() {
showOverlay();
const div = document.getElementById('divAddSave');
// Elimina cualquier botón dentro del divAddSave
if (div) {
const existingButton = div.querySelector('button');
if (existingButton) {
existingButton.remove();
}
}
const buttonProv = `
`;
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/cat7',
method: 'GET',
success: function(response) {
let tableHTML = `
ID_N7
COD_N7
NIVEL 7
${response.map(item => `
${item.ID_N7}
${item.COD_N7 }
${item.NIVEL_7 }
`).join('')}
`;
if (div) {
div.innerHTML = buttonProv;
}
$('#miniTableContainer').html(tableHTML);
$('#tablaCatalogo9').DataTable({
paging: true,
pageLength: 10,
searching: true,
info: true,
ordering: false,
lengthChange: true,
columnDefs: [
{
targets: 0,
width: '10%' // Ajusta el ancho de la primera columna
},
{
targets: 1,
width: '20%' // Ajusta el ancho de la primera columna
},
{
targets: 2,
width: '70%' // Ajusta el ancho de la segunda columna
}
],
language: {
emptyTable: 'No hay datos disponibles en la tabla',
info: 'Mostrando _START_ a _END_ de _TOTAL_ entradas',
infoEmpty: 'Mostrando 0 a 0 de 0 entradas',
infoFiltered: '(filtrado de _MAX_ entradas totales)',
lengthMenu: 'Mostrar _MENU_ entradas',
search: 'Buscar:',
zeroRecords: 'No se encontraron coincidencias',
paginate: {
first: 'Primero',
last: 'Último',
next: 'Siguiente',
previous: 'Anterior'
}
}
});
hideOverlay();
//Insertar Fila
const btnInsertProv = document.getElementById('addRowBtnCat7');
btnInsertProv.addEventListener('click', function() {
let rowBtn = document.getElementById('divAddSave');
if (!document.getElementById('saveBtn')) {
const saveBtn = document.createElement('button');
// Añadir texto
saveBtn.textContent = 'Guardar ';
// Añadir id
saveBtn.id = 'saveBtn';
// Añadir clase
saveBtn.classList.add('btn', 'btn-primary', 'ml-2');
// Añadir icono al botón
const iconSave = document.createElement('i');
iconSave.className = 'fas fa-save';
// Añadir icono al botón
saveBtn.appendChild(iconSave);
rowBtn.appendChild(saveBtn);
}
const uniqueId = new Date().getTime(); //Asignamos un unico ID para que no sea variable y sea unico
idniv7 = 'rowCodN7_' + uniqueId;
deletIdn = 'del_' + uniqueId;
constCodn7 = 'codN7_' + uniqueId;
inputNivel7 = 'levelN7_' + uniqueId;
let nuevaFila = `
` +
`
` +
`
` +
`
` +
'
';
$('#tablaCatalogo9 tbody').prepend(nuevaFila);
});
//editar la tabla CODN7
$(document).off('click', '[id^="idCodN7_"]').on('click', '[id^="idCodN7_"]', function(event) {
let buttonId = $(this).attr('id');
let idCodN7 = buttonId.split('_')[1];
let codN7Value = $('#codN7_' + idCodN7).text().trim();
let row = $('#rowCodN7_' + idCodN7); //tr principal
let mainRow = $(this).closest('tr');
let nivel = row.find('td').eq(2).text().trim();
const uniqueId = idCodN7;
const newSelectCan = 'canCD7_' + uniqueId;
const newSelectDat = 'saveCD7_' + uniqueId;
const newSelectNivel7 = 'levelN7_'+uniqueId;
const newCodNivel = 'codN7_'+uniqueId;
const filaOriginalCD7 = mainRow.html();
let newRow = `
`;
row.replaceWith(newRow);
// Dentro del scope para cancelar
$(document).on('click', '[id^="canCD7_"]', function() {
$(this).closest('tr').html(filaOriginalCD7);
});
});
$(document).on('click', '[id^="saveCD7_"]',function(){
showOverlay();
let updateCD7= $(this).attr('id');
let idCodN7 = updateCD7.split('_')[1];
let newRow = $('#rowCodN7_' + idCodN7);
let rowFinal = $(this).closest('tr');
let valueCodN7 = newRow.find('td').eq(1).find('input').val().trim();
let valueNivelCD7 = newRow.find('td').eq(2).find('input').val().trim();
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/updateCn7',
type: 'POST',
data: {
ID_N7: idCodN7,
COD_N7: valueCodN7,
NIVEL_7: valueNivelCD7
},
success: function(respuesta) {
let updateRow = `
${idCodN7}
${valueCodN7}
${valueNivelCD7}
`
console.log('Éxito:', respuesta);
rowFinal.replaceWith(updateRow);
hideOverlay();
},
error: function(xhr, status, error) {
alert('No cambiaste los datos o no cumple con algún requisito');
hideOverlay();
console.error('Error:', error);
}
});
});
//FIN EDITAR
//INSERTAR LAS FILAS DE PROVEEDORES
$(document).off('click', '#saveBtn').on('click', '#saveBtn', function () {
showOverlay();
let isValid = true;
let allData = [];
// Iterar sobre cada fila en el tbody
$('#tablaCatalogo9 tbody tr').each(function() {
let $row = $(this);
// Verificar si la fila tiene elementos válidos (es decir, al menos un input o select con un valor)
if ($row.find('input, select').length > 0) {
// Obtener los valores de cada campo en la fila
const cod_n7 = $row.find('input[name="CODN7"]').val();
const nivel7 = $row.find('input[name="NIVEL7"]').val();
// Verificar si la fila tiene datos completos
if (cod_n7 && nivel7) {
// Agregar los datos de la fila al array solo si todos los campos están completos
allData.push({
COD_N7: cod_n7,
NIVEL_7: nivel7,
});
} else {
isValid = false;
return false; // Rompe el each loop si una fila es inválida
}
}
});
// Si todos los campos son válidos, enviar la solicitud AJAX
if (isValid && allData.length > 0) {
$.ajax({
url: 'https://panel.fivetwofive.tech/yaaxlum/public/insertNivel7',
type: 'POST',
dataType: 'json',
data: { rows: allData }, // Enviar todos los datos en un solo objeto
success: function (response) {
$('#overlay').css('visibility', 'hidden');
saveBtn.remove();
cargarTablaCatalogo9(); // Recargar los datos de la tabla
},
error: function (xhr, status, error) {
alert('Hubo un error en la inserción');
console.error('Error en la solicitud:', error);
$('#overlay').css('visibility', 'hidden');
}
});
} else {
alert('Por favor, completa todos los campos en cada fila antes de guardar.');
$('#overlay').css('visibility', 'hidden');
}
});
//Borrar Filas
$(document).off('click', '.delete-row').on('click', '.delete-row', function () {
$(this).closest('tr').remove();
// Recalcular el número de botones de eliminación después de quitar la fila
let tamanoDeletes = $('.delete-row').length;
// Seleccionar el botón de guardar solo si existe
let saveBtn = $('#saveBtn');
// Verificar el número de filas con el botón de eliminar
if (tamanoDeletes > 1) {
// No hacer nada si hay más de una fila
return;
} else if (tamanoDeletes === 1) {
// Si hay exactamente una fila restante, no eliminar el botón de guardar
return;
} else {
// Si no hay más filas (tamanoDeletes === 0), eliminar el botón de guardar
if (saveBtn.length) {
saveBtn.remove(); // Eliminar el botón de guardar
}
}
});
},
error: function() {
$('#miniTableContainer').html('
Error al cargar los datos del catálogo 7.
');
}
});
}
//Finalizan cats
});
function showOverlay() {
$('#overlay').css('visibility', 'visible');
}
function hideOverlay() {
$('#overlay').css('visibility', 'hidden');
}
$('#sidebarToggle, .navbar-toggler').on('click', function () {
$('#sidebar, #content').toggleClass('active');
});