Actualización de Grafico con búsqueda Inteligente en DataTable

Actualización de Grafico con búsqueda Inteligente en DataTable

JuanAlbertoJuanAlberto Posts: 14Questions: 4Answers: 0
edited August 2023 in Free community support

Tengo un DataTable cargado de registros desde un archivo Excel y representado con dos gráficos, hasta el momento el DataTable trabaja bien en la carga de registros junto con los Graficos. El inconveniente que tengo es que cuando hago una búsqueda inteligente la actualización de registros en el DataTable no se refleja en los Gráficos,

Solo copiare 2 archivos .js, el DataTable y un grafico. También adjuntare los 4 archivos de trabajo

//script.js: DataTable se carga de registros desde un archivo Excel, e imprime los gráficos en
//la pagina con información del archivo de grafico
let dataTable;
let dataTableIsInitialized = false;
let data;
const initDataTable = () => {
console.log("Initializing DataTable...");
dataTable = $('#example').DataTable(dataTableOptions);
console.log("DataTable Initialized");

// Agregar un oyente para el evento draw.dt (Detallar movimientos de registros cuando se filtra el DataTable)
dataTable.on('draw.dt', function () {
console.log("DataTable redibujado. Cantidad de registros visibles:", dataTable.rows({search: 'applied'}).data().length);
let filteredData = dataTable.rows({ search: 'applied' }).data();
console.log("Llego esta Informacion",filteredData);
});

return dataTable;

};

document.getElementById("fileUpload").addEventListener("change", function (event) {
const selectedFile = event.target.files[0];
if (selectedFile) {
var fileReader = new FileReader();
fileReader.onload = function (event) {
var data = event.target.result;
var workbook = XLSX.read(data, { type: "binary" });
var jsonData = [];
workbook.SheetNames.forEach(sheet => {
var rowObject = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheet]);
jsonData.push(...rowObject);
});
loadJsonDataToDataTable(jsonData);
loadChart2Script();
loadChart1Script();
};
fileReader.readAsBinaryString(selectedFile);
}
});

function loadJsonDataToDataTable(jsonData) {
if (!jsonData || jsonData.length === 0) {
return;
}
dataTable.clear().draw();
jsonData.forEach(data => {
if (data[9] !== "") {
const rowData = [
data.Almc,
data.Articulo,
data.Descripcion,
data.Stock,
data.InvAsigTotal,
data.Reserva,
data.Transito,
data.CntOrd,
data.CntAsig,
data.CntPick,
data.FaltPick
];
const jsonString = JSON.stringify(rowData);
const jsonDataParsed = JSON.parse(jsonString);
dataTable.row.add(jsonDataParsed).draw();
}
});
}
Object.assign(window, {
initDataTable: initDataTable,
//getDataTable: getDataTable
});
window.getDataTable = function() {
return dataTable;
};

// Función para cargar el archivo chart2.js y ejecutar el código cuando esté listo
function loadChart2Script() {
const chart2Script = document.createElement('script');
chart2Script.src = 'chart2.js';
chart2Script.onload = function () {
};
document.body.appendChild(chart2Script);
}

// Función para cargar el archivo chart1.js y ejecutar el código cuando esté listo
function loadChart1Script() {
const chart1Script = document.createElement('script');
chart1Script.src = 'chart1.js';
chart1Script.onload = function () {
};
document.body.appendChild(chart1Script);
}

// Función para actualizar los gráficos después de cambios en el DataTable
function updateChartAfterDataTableChange() {
let filteredData = dataTable.rows({ search: 'applied' }).data();
drawChart2(filteredData);
drawChart1(filteredData);

}
// Ejecutar la función initDataTable al cargar la página para inicializar el DataTable.
window.addEventListener('load', () => {
initDataTable();
loadChart2Script();
loadChart1Script();
});

//Archivo Grafico chart1.js: enlaza su función con el archivo que enviara a imprimir el Grafico
google.charts.load('current', { 'packages': ['corechart'] });

function drawChart1(filteredData) {
var dataArray = [['Articulo', 'CntOrd', 'CntPick']];
filteredData.each(function (data) {
var articulo = data[1];
var cntOrd = parseFloat(data[7]);
var cntPick = parseFloat(data[9]);
var faltPick = parseFloat(data[10]); // Agregar la columna FaltPick
if (faltPick > 0) { // Aplicar la condición
dataArray.push([articulo, cntOrd, cntPick]);
}
});

var data = google.visualization.arrayToDataTable(dataArray);

var options = {
title: 'Quiebre de Articulo',
titleTextStyle: { fontSize: 18 },
vAxis: { title: 'Valores' },
hAxis: { title: 'Articulo' },
legend: { position: 'top' },
bar: { groupWidth: '95%' }
};

var chart = new google.visualization.ColumnChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}

google.charts.setOnLoadCallback(() => {
// Load the DataTable from the script.js file
var dataTable = window.getDataTable(); // Acceder a la función desde el ámbito global
var filteredData = dataTable.rows({ search: 'applied' }).data();
window.drawChart1(filteredData);
});

Answers

  • kthorngrenkthorngren Posts: 21,117Questions: 26Answers: 4,916

    Did you look at my simple Google charts example in your other thread?

    Please provide a running test case showing the issue so we can work with your example. Provide sample data similar to this example.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • JuanAlbertoJuanAlberto Posts: 14Questions: 4Answers: 0
    edited August 2023

    Si, revise el ejemplo con Grafico, en ese caso el Grafico esta vinculado a registros estáticos, en mi caso yo tengo registros cargados dinámicamente al DataTable, y la forma de acceder a los datos del DataTable es bastante distinto. Por eso pido ayuda.

    Además, en la pagina live.datatables.net no me permite registrarme solo con mi cuenta de correo, y cuando cargo mi proyecto en la pagina no dura mas de una hora porque se elimina.

    Es por ello que en mi planteamiento del problema subí los cuatro archivos que estoy trabajando para que puedan acceder a ellos y revisarlos.

  • kthorngrenkthorngren Posts: 21,117Questions: 26Answers: 4,916
    edited August 2023

    The problem is you have a lot of code to look at to try and understand your solution. Its very difficult and time consuming to try understanding someone else's code with specifics of how it runs and to learn how Google charts works. This is why we ask for test cases to we can use the browser's debugging tools to understand the code flow and diagnose issues.

    In addition, the live.datatables.net page does not allow me to register only with my email account, and when I load my project on the page it does not last more than an hour because it is deleted.

    live.datatables.net automatically saves your work. Not sure why its being deleted. I have not had that issue.

    Maybe start with building a simple test case with a sample of your data and a simplified version of your code. The test case doesn't need to be your full solution nor have all your code. Seems like the key might be the function drawChart1, setOnLoadCallback function and a simple Datatable with a sample of your data.

    Next add a second data set that can show how you are dynamically updating the data. Sounds like this is where you are having the issue.

    Kevin

  • JuanAlbertoJuanAlberto Posts: 14Questions: 4Answers: 0

    Ya logre que los Gráficos se actualicen. Pero surgieron dos problemas.
    Primer problema:
    La búsqueda inteligente por columnas no funciona cuando están vinculados los códigos de los Gráficos para cargar la pagina. Si elimino los Gráficos ahí si funcionan la búsqueda inteligente por columnas pero obviamente ya no hay Gráficos. Lo raro es que la búsqueda inteligente de origen del DataTable si funciona con los Gráficos.

    Segundo problema:
    Cuando coloco updateChartAfterDataTableChange(); ahí si se actualizan los Gráficos al hacer la búsqueda inteligente por el único input que viene de origen en el DataTable, pero no en la búsqueda inteligente implementada por columnas. Aquí el gran problema es que se pone demasiado lento la carga del DataTable (la carga de 500 registros puede durar como 7 segundos para cargar). Si retiro updateChartAfterDataTableChange(); de la instrucción ahí la carga baja a 0.5 segundos pero ya no se actualizan los Gráficos con la búsqueda inteligente. Este es el código de la instrucción
    dataTable.on('draw.dt', function () {
    console.log("DataTable redibujado. Cantidad de registros visibles:", dataTable.rows({search: 'applied'}).data().length);
    let filteredData = dataTable.rows({ search: 'applied' }).data();
    updateChartAfterDataTableChange();
    });

    Envío enlace donde se puede acceder al proyecto
    https://jsfiddle.net/JuanAlberto/hnzua845/11/

  • JuanAlbertoJuanAlberto Posts: 14Questions: 4Answers: 0
    edited August 2023

    Para probar la aplicación hay que tener un archivo Excel de 11 columnas con los siguientes encabezados (Solo el campo Descripcion es string). Los encabezados deben tener el nombre exacto como se menciona a continuación.

    Almc,
    Articulo,
    Descripcion,
    Stock,
    InvAsigTotal,
    Reserva,
    Transito,
    CntOrd,
    CntAsig,
    CntPick,
    FaltPick

Sign In or Register to comment.