You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.8 KiB
JavaScript

// export-service.js
/**
* Convierte un array de objetos JSON a formato CSV
*/
function convertToCSV(objArray) {
const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
if (!Array.isArray(array) || array.length === 0) {
throw new Error('No hay datos históricos disponibles para exportar.');
}
const headers = Object.keys(array[0]);
const rows = array.map((item) =>
headers.map((header) => escapeCsvValue(item[header])).join(',')
);
return [
headers.map(escapeCsvValue).join(','),
...rows
].join('\r\n');
}
function escapeCsvValue(value) {
const text = value == null ? '' : String(value);
return `"${text.replace(/"/g, '""')}"`;
}
async function getEnabledSensorsForExport() {
const response = await fetch('/api/config/runtime', { cache: 'no-store' });
const config = await response.json();
if (!response.ok || !Array.isArray(config.enabledSensors)) {
throw new Error('No se pudo leer la configuracion de sensores.');
}
return new Set(config.enabledSensors);
}
function normalizeExportSensor(sensorType) {
if (sensorType === 'rtd') return 'temperature';
return sensorType;
}
async function assertSensorExportEnabled(sensorType) {
if (sensorType === 'all') return;
const enabledSensors = await getEnabledSensorsForExport();
const sensorId = normalizeExportSensor(sensorType);
if (!enabledSensors.has(sensorId)) {
throw new Error(`El sensor ${sensorType.toUpperCase()} esta deshabilitado.`);
}
}
/**
* Manejador principal del evento click de los botones
*/
async function handleExport(sensorType) {
try {
await assertSensorExportEnabled(sensorType);
// 1. Obtener datos (Mock actual, fetch real en el futuro)
const data = await fetchHistoricalData(sensorType);
// 2. Convertir a CSV
const csvText = convertToCSV(data);
// 3. Crear un Blob (Objeto de datos binarios)
const blob = new Blob([csvText], { type: 'text/csv;charset=utf-8;' });
// 4. Crear un enlace temporal para forzar la descarga en la laptop
const link = document.createElement("a");
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", `export_${sensorType}_${new Date().getTime()}.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
console.log(`[EXITO] Archivo CSV descargado para ${sensorType}`);
} catch (error) {
console.error("[ERROR] Fallo al exportar el CSV:", error);
alert("Hubo un error al generar el archivo. Revisa la consola.");
}
}