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; // Helper function to update the theme toggle button text function updateThemeToggleButtonText() { if (body.classList.contains('dark-mode')) { themeToggleButton.textContent = 'Change to Light Mode'; } else { themeToggleButton.textContent = 'Change to Dark Mode'; } } // Check and apply the saved theme from localStorage const savedTheme = localStorage.getItem('theme'); if (savedTheme) { body.classList.toggle('dark-mode', savedTheme === 'dark'); } // Update the button text based on the current theme updateThemeToggleButtonText(); // Toggle the theme on button click themeToggleButton.addEventListener('click', () => { const isDarkMode = body.classList.toggle('dark-mode'); localStorage.setItem('theme', isDarkMode ? 'dark' : 'light'); updateThemeToggleButtonText(); // Update the button text after toggling }); // 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 }); }); document.addEventListener('DOMContentLoaded', () => { const templateList = document.getElementById('template-list'); const createTemplateBtn = document.getElementById('create-template-btn'); // Example: Handle the "Create New Template" button click createTemplateBtn.addEventListener('click', () => { window.location.href = '/create_template'; }); // Example: Handle the "Edit" and "Delete" buttons templateList.addEventListener('click', (event) => { if (event.target.classList.contains('edit-btn')) { const templateId = event.target.closest('li').dataset.id; window.location.href = `/edit_template/${templateId}`; } else if (event.target.classList.contains('delete-btn')) { const templateId = event.target.closest('li').dataset.id; if (confirm('Are you sure you want to delete this template?')) { fetch(`/delete_template/${templateId}`, { method: 'POST' }) .then(response => response.text()) .then(data => { alert(data); // Optionally, remove the template from the list event.target.closest('li').remove(); }); } } }); }); document.addEventListener('DOMContentLoaded', () => { const setDimensionsBtn = document.getElementById('set-dimensions-btn'); const labelPreview = document.getElementById('label-preview'); // Handle setting label dimensions setDimensionsBtn.addEventListener('click', () => { const widthInput = document.getElementById('label-width').value; const heightInput = document.getElementById('label-height').value; if (!widthInput || !heightInput) { alert('Please enter valid dimensions for width and height.'); return; } // Convert mm to pixels (1 mm = 3.779528 pixels) const widthPixels = parseFloat(widthInput) * 3.779528; const heightPixels = parseFloat(heightInput) * 3.779528; // Set the size of the label container labelPreview.style.width = `${widthPixels}px`; labelPreview.style.height = `${heightPixels}px`; alert(`Label dimensions set to ${widthPixels.toFixed(2)}px x ${heightPixels.toFixed(2)}px.`); }); }); document.addEventListener('DOMContentLoaded', () => { const labelPreview = document.getElementById('label-preview'); const addFieldButtons = document.querySelectorAll('.add-field-btn'); // Add fields dynamically addFieldButtons.forEach(button => { button.addEventListener('click', () => { const fieldType = button.getAttribute('data-type'); addFieldToPreview(fieldType); }); }); // Function to add a field to the preview function addFieldToPreview(type) { const field = document.createElement('div'); field.classList.add('draggable-field'); field.setAttribute('draggable', 'true'); field.style.position = 'absolute'; field.style.top = '10px'; field.style.left = '10px'; switch (type) { case 'text-label': field.textContent = 'Text Label'; field.style.fontSize = '14px'; break; case 'text-input': field.innerHTML = ''; break; case 'barcode': field.textContent = 'Barcode Box'; field.style.border = '1px dashed #000'; field.style.width = '100px'; field.style.height = '50px'; break; case 'qrcode': field.textContent = 'QR Code Box'; field.style.border = '1px dashed #000'; field.style.width = '50px'; field.style.height = '50px'; break; } labelPreview.appendChild(field); // Make the field draggable makeFieldDraggable(field); } // Function to make a field draggable function makeFieldDraggable(field) { field.addEventListener('dragstart', (e) => { e.dataTransfer.setData('text/plain', null); field.classList.add('dragging'); }); field.addEventListener('dragend', () => { field.classList.remove('dragging'); }); labelPreview.addEventListener('dragover', (e) => { e.preventDefault(); const draggingField = document.querySelector('.dragging'); const rect = labelPreview.getBoundingClientRect(); draggingField.style.left = `${e.clientX - rect.left}px`; draggingField.style.top = `${e.clientY - rect.top}px`; }); } // Calendar functionality for date selection const selectDayReportBtn = document.getElementById('select-day-report'); const calendarModal = document.getElementById('calendar-modal'); const closeModal = document.querySelector('.close-modal'); const cancelDate = document.getElementById('cancel-date'); const confirmDate = document.getElementById('confirm-date'); const calendarDays = document.getElementById('calendar-days'); const calendarMonthYear = document.getElementById('calendar-month-year'); const prevMonth = document.getElementById('prev-month'); const nextMonth = document.getElementById('next-month'); let currentDate = new Date(); let selectedDate = null; // Show calendar modal if (selectDayReportBtn) { selectDayReportBtn.addEventListener('click', () => { calendarModal.style.display = 'block'; generateCalendar(currentDate); }); } // Close modal events if (closeModal) { closeModal.addEventListener('click', closeCalendarModal); } if (cancelDate) { cancelDate.addEventListener('click', closeCalendarModal); } // Click outside modal to close window.addEventListener('click', (e) => { if (e.target === calendarModal) { closeCalendarModal(); } }); // Navigation buttons if (prevMonth) { prevMonth.addEventListener('click', () => { currentDate.setMonth(currentDate.getMonth() - 1); generateCalendar(currentDate); }); } if (nextMonth) { nextMonth.addEventListener('click', () => { currentDate.setMonth(currentDate.getMonth() + 1); generateCalendar(currentDate); }); } // Confirm date selection if (confirmDate) { confirmDate.addEventListener('click', () => { if (selectedDate) { // Format date as YYYY-MM-DD const formattedDate = selectedDate.toISOString().split('T')[0]; closeCalendarModal(); // Fetch report data for the selected date fetchCustomDateReport(formattedDate); } }); } function closeCalendarModal() { calendarModal.style.display = 'none'; selectedDate = null; confirmDate.disabled = true; // Remove selected class from all days const selectedDays = document.querySelectorAll('.calendar-day.selected'); selectedDays.forEach(day => day.classList.remove('selected')); } function generateCalendar(date) { const year = date.getFullYear(); const month = date.getMonth(); // Update header const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; calendarMonthYear.textContent = `${monthNames[month]} ${year}`; // Clear previous days calendarDays.innerHTML = ''; // Get first day of month and number of days const firstDay = new Date(year, month, 1).getDay(); const daysInMonth = new Date(year, month + 1, 0).getDate(); const today = new Date(); // Add empty cells for days before month starts for (let i = 0; i < firstDay; i++) { const emptyDay = document.createElement('div'); emptyDay.classList.add('calendar-day', 'other-month'); calendarDays.appendChild(emptyDay); } // Add days of the month for (let day = 1; day <= daysInMonth; day++) { const dayElement = document.createElement('div'); dayElement.classList.add('calendar-day'); dayElement.textContent = day; const dayDate = new Date(year, month, day); // Highlight today if (dayDate.toDateString() === today.toDateString()) { dayElement.classList.add('today'); } // Add click event dayElement.addEventListener('click', () => { // Remove previous selection const previousSelected = document.querySelector('.calendar-day.selected'); if (previousSelected) { previousSelected.classList.remove('selected'); } // Select this day dayElement.classList.add('selected'); selectedDate = new Date(year, month, day); confirmDate.disabled = false; }); calendarDays.appendChild(dayElement); } } function fetchCustomDateReport(dateString) { reportTitle.textContent = `Loading report for ${dateString}...`; fetch(`/generate_report?report=6&date=${dateString}`) .then(response => response.json()) .then(data => { if (data.error) { reportTitle.textContent = `Error: ${data.error}`; populateTable({ headers: [], rows: [] }); } else { reportTitle.textContent = `Daily Report for ${dateString}`; populateTable(data); } }) .catch(error => { console.error('Error fetching custom date report:', error); reportTitle.textContent = 'Error loading report'; populateTable({ headers: [], rows: [] }); }); } });