From a8f07497a08df99c696f7762a3ea3c6ab28b76d6 Mon Sep 17 00:00:00 2001 From: ske087 Date: Fri, 25 Apr 2025 14:08:03 +0300 Subject: [PATCH] updated JS file to work correctly --- py_app/app/static/script.js | 292 +++++++++--------------------------- 1 file changed, 74 insertions(+), 218 deletions(-) diff --git a/py_app/app/static/script.js b/py_app/app/static/script.js index 9fd30ac..d996744 100644 --- a/py_app/app/static/script.js +++ b/py_app/app/static/script.js @@ -1,159 +1,34 @@ document.addEventListener('DOMContentLoaded', () => { - const themeToggle = document.getElementById('theme-toggle'); - const body = document.body; - - // Check for saved theme in localStorage - const savedTheme = localStorage.getItem('theme'); - if (savedTheme) { - body.className = savedTheme; - updateButtonText(); - } - - // Toggle theme on button click - if (themeToggle) { - themeToggle.addEventListener('click', () => { - if (body.classList.contains('light-mode')) { - body.className = 'dark-mode'; - localStorage.setItem('theme', 'dark-mode'); - } else { - body.className = 'light-mode'; - localStorage.setItem('theme', 'light-mode'); - } - updateButtonText(); - }); - } - - // Function to update the button text - function updateButtonText() { - if (body.classList.contains('light-mode')) { - themeToggle.textContent = 'Change to dark theme'; - } else { - themeToggle.textContent = 'Change to light theme'; - } - } - - const createUserBtn = document.getElementById('create-user-btn'); - const createUserPopup = document.getElementById('create-user-popup'); - const closePopupBtn = document.getElementById('close-popup-btn'); - - // Open the popup - createUserBtn.addEventListener('click', () => { - createUserPopup.style.display = 'flex'; - }); - - // Close the popup - closePopupBtn.addEventListener('click', () => { - createUserPopup.style.display = 'none'; - }); - - // Close the popup when clicking outside the popup content - createUserPopup.addEventListener('click', (e) => { - if (e.target === createUserPopup) { - createUserPopup.style.display = 'none'; - } - }); - - const editButtons = document.querySelectorAll('.edit-btn'); - const editUserPopup = document.getElementById('edit-user-popup'); - const closeEditPopupBtn = document.getElementById('close-edit-popup-btn'); - - // Open the edit user popup - editButtons.forEach((button) => { - button.addEventListener('click', (e) => { - const userElement = e.target.closest('li'); - const username = userElement.querySelector('.user-name').textContent; - const role = userElement.querySelector('.user-role').textContent.split(': ')[1]; - const userId = userElement.dataset.userId; - - // Populate the form fields - document.getElementById('edit-user-id').value = userId; - document.getElementById('edit-username').value = username; - document.getElementById('edit-role').value = role; - - // Show the popup - editUserPopup.style.display = 'flex'; - }); - }); - - // Close the edit user popup - closeEditPopupBtn.addEventListener('click', () => { - editUserPopup.style.display = 'none'; - }); - - // Close the popup when clicking outside the popup content - editUserPopup.addEventListener('click', (e) => { - if (e.target === editUserPopup) { - editUserPopup.style.display = 'none'; - } - }); - - const deleteButtons = document.querySelectorAll('.delete-btn'); - const deleteUserPopup = document.getElementById('delete-user-popup'); - const closeDeletePopupBtn = document.getElementById('close-delete-popup-btn'); - const deleteUsernameSpan = document.getElementById('delete-username'); - const deleteUserIdInput = document.getElementById('delete-user-id'); - - // Open the delete user popup - deleteButtons.forEach((button) => { - button.addEventListener('click', (e) => { - const userElement = e.target.closest('li'); - const username = userElement.querySelector('.user-name').textContent; - const userId = userElement.dataset.userId; - - // Populate the popup with user details - deleteUsernameSpan.textContent = username; - deleteUserIdInput.value = userId; - - // Show the popup - deleteUserPopup.style.display = 'flex'; - }); - }); - - // Close the delete user popup - closeDeletePopupBtn.addEventListener('click', () => { - deleteUserPopup.style.display = 'none'; - }); - - // Close the popup when clicking outside the popup content - deleteUserPopup.addEventListener('click', (e) => { - if (e.target === deleteUserPopup) { - deleteUserPopup.style.display = 'none'; - } - }); - 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; - // Handle report button clicks - reportButtons.forEach((button) => { - button.addEventListener('click', () => { -// Get the text label of the button - const reportLabel = button.textContent.trim(); + // Check and apply the saved theme from localStorage + const savedTheme = localStorage.getItem('theme'); + if (savedTheme) { + body.classList.toggle('dark-mode', savedTheme === 'dark'); + } - // Update the title dynamically with the button's text label - reportTitle.textContent = `Data for "${reportLabel}"`; - - // Fetch data for the selected report - const reportNumber = button.dataset.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); - }); - }); + // Toggle the theme on button click + themeToggleButton.addEventListener('click', () => { + const isDarkMode = body.classList.toggle('dark-mode'); + localStorage.setItem('theme', isDarkMode ? 'dark' : 'light'); }); - // Populate the table with data + // 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'); @@ -173,9 +48,16 @@ console.log("Fetched data:", data); // Debugging // Populate table rows data.rows.forEach((row) => { const tr = document.createElement('tr'); - row.forEach((cell) => { + row.forEach((cell, index) => { const td = document.createElement('td'); - td.textContent = cell; + + // 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); @@ -191,33 +73,40 @@ console.log("Fetched data:", data); // Debugging } } - // Export buttons - const exportCsvButton = document.getElementById('export-csv'); - const exportPdfButton = document.getElementById('export-pdf'); + // Function to export table data as CSV + function exportTableToCSV(filename) { + let csv = []; + const rows = reportTable.querySelectorAll('tr'); - exportCsvButton.addEventListener('click', () => { - alert('Exporting current report as CSV...'); - // Add logic to export the current report as CSV - }); + // 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(',')); + }); - exportPdfButton.addEventListener('click', () => { - alert('Exporting current report as PDF...'); - // Add logic to export the current report as PDF - }); -}); -document.addEventListener('DOMContentLoaded', () => { - const reportButtons = document.querySelectorAll('.report-btn'); - const reportTitle = document.getElementById('report-title'); - const reportTable = document.getElementById('report-table'); + // 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; - // Get the text label of the button const reportLabel = button.textContent.trim(); + // Update the title dynamically - reportTitle.textContent = `Date pentru "${reportLabel}"`; + reportTitle.textContent = `Data for "${reportLabel}"`; // Fetch data for the selected report fetch(`/get_report_data?report=${reportNumber}`) @@ -233,60 +122,27 @@ document.addEventListener('DOMContentLoaded', () => { }) .catch((error) => { console.error('Error fetching report data:', error); + reportTitle.textContent = 'Error loading data.'; }); }); }); - // Populate the table with data -function populateTable(data) { - const tableHead = reportTable.querySelector('thead tr'); - const tableBody = reportTable.querySelector('tbody'); + // 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; + } - // Clear existing table content - tableHead.innerHTML = ''; - tableBody.innerHTML = ''; + const reportTitleText = reportTitle.textContent.trim(); + const filename = `${reportTitleText.replace(/\s+/g, '_')}.csv`; // Generate a filename based on the report title + exportTableToCSV(filename); + }); - 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'); - - // Check if the header is "Date" and format the cell value - if (data.headers[index].toLowerCase() === 'date' && cell) { - const date = new Date(cell); - if (!isNaN(date)) { - // Format as yyyy-mm-dd - const formattedDate = date.toISOString().split('T')[0]; - td.textContent = formattedDate; - } else { - td.textContent = cell; // Fallback if not a valid date - } - } 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); - } - - } + // Placeholder for PDF export functionality + exportPdfButton.addEventListener('click', () => { + alert('Exporting current report as PDF...'); + // Add logic to export the current report as PDF + }); }); \ No newline at end of file