updated JS file to work correctly

This commit is contained in:
2025-04-25 14:08:03 +03:00
parent 0c06ac6051
commit a8f07497a0

View File

@@ -1,159 +1,34 @@
document.addEventListener('DOMContentLoaded', () => { 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 reportButtons = document.querySelectorAll('.report-btn');
const reportTitle = document.getElementById('report-title'); const reportTitle = document.getElementById('report-title');
const reportTable = document.getElementById('report-table'); 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 // Check and apply the saved theme from localStorage
reportButtons.forEach((button) => { const savedTheme = localStorage.getItem('theme');
button.addEventListener('click', () => { if (savedTheme) {
// Get the text label of the button body.classList.toggle('dark-mode', savedTheme === 'dark');
const reportLabel = button.textContent.trim(); }
// Update the title dynamically with the button's text label // Toggle the theme on button click
reportTitle.textContent = `Data for "${reportLabel}"`; themeToggleButton.addEventListener('click', () => {
const isDarkMode = body.classList.toggle('dark-mode');
// Fetch data for the selected report localStorage.setItem('theme', isDarkMode ? 'dark' : 'light');
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);
});
});
}); });
// 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) { function populateTable(data) {
const tableHead = reportTable.querySelector('thead tr'); const tableHead = reportTable.querySelector('thead tr');
const tableBody = reportTable.querySelector('tbody'); const tableBody = reportTable.querySelector('tbody');
@@ -173,9 +48,16 @@ console.log("Fetched data:", data); // Debugging
// Populate table rows // Populate table rows
data.rows.forEach((row) => { data.rows.forEach((row) => {
const tr = document.createElement('tr'); const tr = document.createElement('tr');
row.forEach((cell) => { row.forEach((cell, index) => {
const td = document.createElement('td'); 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); tr.appendChild(td);
}); });
tableBody.appendChild(tr); tableBody.appendChild(tr);
@@ -191,33 +73,40 @@ console.log("Fetched data:", data); // Debugging
} }
} }
// Export buttons // Function to export table data as CSV
const exportCsvButton = document.getElementById('export-csv'); function exportTableToCSV(filename) {
const exportPdfButton = document.getElementById('export-pdf'); let csv = [];
const rows = reportTable.querySelectorAll('tr');
exportCsvButton.addEventListener('click', () => { // Loop through each row in the table
alert('Exporting current report as CSV...'); rows.forEach((row) => {
// Add logic to export the current report as CSV const cells = row.querySelectorAll('th, td');
}); const rowData = Array.from(cells).map((cell) => `"${cell.textContent.trim()}"`);
csv.push(rowData.join(','));
});
exportPdfButton.addEventListener('click', () => { // Create a Blob from the CSV data
alert('Exporting current report as PDF...'); const csvBlob = new Blob([csv.join('\n')], { type: 'text/csv' });
// Add logic to export the current report as PDF
}); // Create a link element to trigger the download
}); const downloadLink = document.createElement('a');
document.addEventListener('DOMContentLoaded', () => { downloadLink.href = URL.createObjectURL(csvBlob);
const reportButtons = document.querySelectorAll('.report-btn'); downloadLink.download = filename;
const reportTitle = document.getElementById('report-title');
const reportTable = document.getElementById('report-table'); // 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 // Handle report button clicks
reportButtons.forEach((button) => { reportButtons.forEach((button) => {
button.addEventListener('click', () => { button.addEventListener('click', () => {
const reportNumber = button.dataset.report; const reportNumber = button.dataset.report;
// Get the text label of the button
const reportLabel = button.textContent.trim(); const reportLabel = button.textContent.trim();
// Update the title dynamically // Update the title dynamically
reportTitle.textContent = `Date pentru "${reportLabel}"`; reportTitle.textContent = `Data for "${reportLabel}"`;
// Fetch data for the selected report // Fetch data for the selected report
fetch(`/get_report_data?report=${reportNumber}`) fetch(`/get_report_data?report=${reportNumber}`)
@@ -233,60 +122,27 @@ document.addEventListener('DOMContentLoaded', () => {
}) })
.catch((error) => { .catch((error) => {
console.error('Error fetching report data:', error); console.error('Error fetching report data:', error);
reportTitle.textContent = 'Error loading data.';
}); });
}); });
}); });
// Populate the table with data // Bind the export functionality to the CSV button
function populateTable(data) { exportCsvButton.addEventListener('click', () => {
const tableHead = reportTable.querySelector('thead tr'); const rows = reportTable.querySelectorAll('tr');
const tableBody = reportTable.querySelector('tbody'); if (rows.length === 0) {
alert('No data available to export.');
return;
}
// Clear existing table content const reportTitleText = reportTitle.textContent.trim();
tableHead.innerHTML = ''; const filename = `${reportTitleText.replace(/\s+/g, '_')}.csv`; // Generate a filename based on the report title
tableBody.innerHTML = ''; exportTableToCSV(filename);
});
if (data.headers && data.rows) { // Placeholder for PDF export functionality
// Populate table headers exportPdfButton.addEventListener('click', () => {
data.headers.forEach((header) => { alert('Exporting current report as PDF...');
const th = document.createElement('th'); // Add logic to export the current report as PDF
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);
}
}
}); });