Files
quality_recticel/py_app/app/static/script.js

148 lines
5.5 KiB
JavaScript

document.addEventListener('DOMContentLoaded', () => {
const reportButtons = document.querySelectorAll('.report-btn');
const reportTitle = document.getElementById('report-title');
const reportTable = document.getElementById('report-table');
const exportCsvButton = document.getElementById('export-csv');
const exportPdfButton = document.getElementById('export-pdf');
const themeToggleButton = document.getElementById('theme-toggle');
const body = document.body;
// Check and apply the saved theme from localStorage
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
body.classList.toggle('dark-mode', savedTheme === 'dark');
}
// Toggle the theme on button click
themeToggleButton.addEventListener('click', () => {
const isDarkMode = body.classList.toggle('dark-mode');
localStorage.setItem('theme', isDarkMode ? 'dark' : 'light');
});
// Helper function to format dates
function formatDate(dateString) {
const date = new Date(dateString);
if (!isNaN(date)) {
return date.toISOString().split('T')[0]; // Format as yyyy-mm-dd
}
return dateString; // Fallback if not a valid date
}
// Function to populate the table with data
function populateTable(data) {
const tableHead = reportTable.querySelector('thead tr');
const tableBody = reportTable.querySelector('tbody');
// Clear existing table content
tableHead.innerHTML = '';
tableBody.innerHTML = '';
if (data.headers && data.rows) {
// Populate table headers
data.headers.forEach((header) => {
const th = document.createElement('th');
th.textContent = header;
tableHead.appendChild(th);
});
// Populate table rows
data.rows.forEach((row) => {
const tr = document.createElement('tr');
row.forEach((cell, index) => {
const td = document.createElement('td');
// Format the "Date" column
if (data.headers[index].toLowerCase() === 'date' && cell) {
td.textContent = formatDate(cell);
} else {
td.textContent = cell;
}
tr.appendChild(td);
});
tableBody.appendChild(tr);
});
} else {
// No data available
const tr = document.createElement('tr');
const td = document.createElement('td');
td.textContent = 'No data available.';
td.colSpan = data.headers ? data.headers.length : 1;
tr.appendChild(td);
tableBody.appendChild(tr);
}
}
// Function to export table data as CSV
function exportTableToCSV(filename) {
let csv = [];
const rows = reportTable.querySelectorAll('tr');
// Loop through each row in the table
rows.forEach((row) => {
const cells = row.querySelectorAll('th, td');
const rowData = Array.from(cells).map((cell) => `"${cell.textContent.trim()}"`);
csv.push(rowData.join(','));
});
// Create a Blob from the CSV data
const csvBlob = new Blob([csv.join('\n')], { type: 'text/csv' });
// Create a link element to trigger the download
const downloadLink = document.createElement('a');
downloadLink.href = URL.createObjectURL(csvBlob);
downloadLink.download = filename;
// Append the link to the document, trigger the download, and remove the link
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
// Handle report button clicks
reportButtons.forEach((button) => {
button.addEventListener('click', () => {
const reportNumber = button.dataset.report;
const reportLabel = button.textContent.trim();
// Update the title dynamically
reportTitle.textContent = `Data for "${reportLabel}"`;
// Fetch data for the selected report
fetch(`/get_report_data?report=${reportNumber}`)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then((data) => {
console.log("Fetched data:", data); // Debugging
populateTable(data);
})
.catch((error) => {
console.error('Error fetching report data:', error);
reportTitle.textContent = 'Error loading data.';
});
});
});
// Bind the export functionality to the CSV button
exportCsvButton.addEventListener('click', () => {
const rows = reportTable.querySelectorAll('tr');
if (rows.length === 0) {
alert('No data available to export.');
return;
}
const reportTitleText = reportTitle.textContent.trim();
const filename = `${reportTitleText.replace(/\s+/g, '_')}.csv`; // Generate a filename based on the report title
exportTableToCSV(filename);
});
// Placeholder for PDF export functionality
exportPdfButton.addEventListener('click', () => {
alert('Exporting current report as PDF...');
// Add logic to export the current report as PDF
});
});