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,243 +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');
// Handle report button clicks
reportButtons.forEach((button) => {
button.addEventListener('click', () => {
// Get the text label of the button
const reportLabel = button.textContent.trim();
// 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);
});
});
});
// 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) => {
const td = document.createElement('td');
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);
}
}
// Export buttons
const exportCsvButton = document.getElementById('export-csv');
const exportPdfButton = document.getElementById('export-pdf');
const themeToggleButton = document.getElementById('theme-toggle');
const body = document.body;
exportCsvButton.addEventListener('click', () => {
alert('Exporting current report as CSV...');
// Add logic to export the current report as CSV
});
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');
// 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}"`;
// 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}`);
// Check and apply the saved theme from localStorage
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
body.classList.toggle('dark-mode', savedTheme === 'dark');
}
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');
@@ -260,16 +51,9 @@ function populateTable(data) {
row.forEach((cell, index) => {
const td = document.createElement('td');
// Check if the header is "Date" and format the cell value
// Format the "Date" column
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
}
td.textContent = formatDate(cell);
} else {
td.textContent = cell;
}
@@ -287,6 +71,78 @@ function populateTable(data) {
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
});
});