🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Upload Size Increase
sassanix47923fe54495
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0407368..03ac7da 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,52 @@# Changelog+## [0.9.8.1] - 2025-03-21+++- **UI Improvements**+ - **User Menu Refinement**+ - Removed the Profile button from the username dropdown menu+ - Simplified the user menu interface by removing unimplemented functionality+ - Improved user interface clarity by removing the "Profile page coming soon" placeholder+ - Updated all HTML templates (index.html, status.html, settings-new.html) for consistency++- **Bug Fixes**+ - **Add Warranty Form Wizard**+ - Fixed issue where clicking the "Next" button sometimes skipped the "Documents" tab+ - Removed duplicate DOMContentLoaded event listeners in script.js to prevent multiple form initializations+ - Implemented clone-and-replace technique to ensure clean event listener attachment+ - Added comprehensive logging for tab navigation to assist future debugging+ - Enhanced form validation to ensure a smoother user experience+ - Improved error handling when navigating between form tabs++ - **Warranty Filtering**+ - Fixed "ReferenceError: applyFilters is not defined" error in script.js+ - Added missing applyFilters function that was referenced but not implemented+ - Restored filter functionality for the warranty list on the main page+ - Enhanced console logging to provide better debugging information++- **Upload Size Increase**+ - Increased maximum file upload size from 16MB to 32MB for invoices and manuals+ - Updated `MAX_CONTENT_LENGTH` in Flask configuration from 16MB to 32MB+ - Added `client_max_body_size 32M` directive to Nginx configuration+ - Updated documentation in memory bank to reflect new file size limits+ - Enhanced fallback Nginx configuration in Dockerfile with upload size limits+ - Added frontend validation to prevent oversized file uploads+ - Improved error handling for 413 Request Entity Too Large errors+ - Added detailed error messages with file size information++- **UI Consistency Improvements**+ - **Settings Page Header**+ - Fixed settings page header to match the structure and appearance of the home page+ - Standardized navigation menu appearance across all application pages+ - Removed duplicate settings container from the header for cleaner UI+ - Added proper "active" class to the current page in the navigation menu+ - **JavaScript Enhancements**+ - Improved error handling in settings-new.js with proper null checking+ - Enhanced preferences saving functionality with graceful fallbacks+ - Fixed dark mode toggle to work without the header settings container+ - Prevented console errors when UI elements were changed or removed+## [0.9.8.0] - 2025-03-21- **Feature Added**diff --git a/Dockerfile b/Dockerfileindex fb0312c..0665377 100644--- a/Dockerfile+++ b/Dockerfile@@ -79,6 +79,7 @@ RUN echo 'server {\n\# Enable gzip compression\n\gzip on;\n\gzip_types text/plain text/css application/javascript application/json;\n\+ client_max_body_size 32M;\n\\n\location / {\n\try_files $uri $uri/ /index.html;\n\@@ -89,6 +90,7 @@ RUN echo 'server {\n\proxy_pass http://127.0.0.1:5000;\n\proxy_set_header Host $host;\n\proxy_set_header X-Real-IP $remote_addr;\n\+ client_max_body_size 32M;\n\}\n\\n\# Direct access to uploads directory\n\diff --git a/backend/app.py b/backend/app.pyindex 4c8aad2..1debb59 100644--- a/backend/app.py+++ b/backend/app.py@@ -28,7 +28,7 @@ app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=7) # Token expiration timeUPLOAD_FOLDER = '/data/uploads'ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg'}-MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16MB max upload+MAX_CONTENT_LENGTH = 32 * 1024 * 1024 # 32MB max uploadapp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDERapp.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTHdiff --git a/frontend/index.html b/frontend/index.htmlindex cab589a..8b0abbe 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -235,9 +235,6 @@<div id="userName" class="user-name">User Name</div><div id="userEmail" class="user-email">[email protected]</div></div>- <div class="user-menu-item" id="profileMenuItem">- <i class="fas fa-id-card"></i> Profile- </div><div class="user-menu-item"><a href="settings-new.html" style="color: inherit; text-decoration: none; display: block;"><i class="fas fa-cog"></i> Settingsdiff --git a/frontend/script.js b/frontend/script.jsindex 5636cee..ca0605d 100644--- a/frontend/script.js+++ b/frontend/script.js@@ -49,183 +49,423 @@ function initializeTheme() {// Initialize theme when page loadsinitializeTheme();-// Initialize page-document.addEventListener('DOMContentLoaded', () => {- console.log('DOM fully loaded, initializing app...');+// Variables+let warranties = [];+let currentWarrantyId = null;+let currentFilters = {+ search: '',+ status: 'all',+ sort: 'expiration'+};+let currentView = 'grid'; // Default view+let expiringSoonDays = 30; // Default value, will be updated from user preferences++// API URL+const API_URL = '/api/warranties';++// Form tab navigation variables+const formTabs = Array.from(document.querySelectorAll('.form-tab'));+const tabContents = Array.from(document.querySelectorAll('.tab-content'));+let currentTabIndex = 0;++// Initialize form tabs+function initFormTabs() {+ console.log('Initializing form tabs...');- // Ensure auth state is checked- if (window.auth && window.auth.checkAuthState) {- window.auth.checkAuthState();+ // Hide the submit button initially+ const submitButton = document.querySelector('button[type="submit"]');+ if (submitButton) {+ submitButton.style.display = 'none';}- // Initialize settings button- if (settingsBtn && settingsMenu) {- settingsBtn.addEventListener('click', (e) => {- e.stopPropagation();- settingsMenu.classList.toggle('active');- });+ // Show/hide navigation buttons based on current tab+ updateNavigationButtons();++ // Remove any existing event listeners before adding new ones+ const nextTabButton = document.querySelector('.next-tab');+ const prevTabButton = document.querySelector('.prev-tab');++ // Clone and replace the buttons to remove any existing event listeners+ if (nextTabButton && prevTabButton) {+ const nextTabClone = nextTabButton.cloneNode(true);+ const prevTabClone = prevTabButton.cloneNode(true);- // Close settings menu when clicking outside- document.addEventListener('click', (e) => {- if (settingsMenu.classList.contains('active') &&- !settingsMenu.contains(e.target) &&- !settingsBtn.contains(e.target)) {- settingsMenu.classList.remove('active');+ nextTabButton.parentNode.replaceChild(nextTabClone, nextTabButton);+ prevTabButton.parentNode.replaceChild(prevTabClone, prevTabButton);++ // Add event listeners for tab navigation+ document.querySelector('.next-tab').addEventListener('click', () => {+ console.log('Next button clicked, current tab:', currentTabIndex);+ if (validateTab(currentTabIndex)) {+ switchToTab(currentTabIndex + 1);+ } else {+ showValidationErrors(currentTabIndex);}});++ document.querySelector('.prev-tab').addEventListener('click', () => {+ console.log('Previous button clicked, current tab:', currentTabIndex);+ switchToTab(currentTabIndex - 1);+ });}- // Initialize the app- initializeTheme();-- // Initialize form tabs- initFormTabs();-- // Initialize the form- resetForm();-- // Close modals when clicking outside or on close button- document.querySelectorAll('.modal-backdrop, [data-dismiss="modal"]').forEach(element => {- element.addEventListener('click', (e) => {- if (e.target === element) {- closeModals();+ // Add click event for tab headers+ formTabs.forEach((tab, index) => {+ tab.addEventListener('click', () => {+ // Only allow clicking on previous tabs or current tab+ if (index <= currentTabIndex) {+ switchToTab(index);}});});+}++// Switch to a specific tab+function switchToTab(index) {+ console.log(`Switching to tab ${index} from tab ${currentTabIndex}`);- // Prevent modal content clicks from closing the modal- document.querySelectorAll('.modal').forEach(modal => {- modal.addEventListener('click', (e) => {- e.stopPropagation();- });- });-- // Filter event listeners- if (searchInput) {- searchInput.addEventListener('input', () => {- currentFilters.search = searchInput.value.toLowerCase();- applyFilters();- });+ // Ensure index is within bounds+ if (index < 0 || index >= formTabs.length) {+ console.log(`Invalid tab index: ${index}, not switching`);+ return;}- if (statusFilter) {- statusFilter.addEventListener('change', () => {- currentFilters.status = statusFilter.value;- applyFilters();- });- }+ // Update active tab+ formTabs.forEach(tab => tab.classList.remove('active'));+ tabContents.forEach(content => content.classList.remove('active'));- if (sortBySelect) {- sortBySelect.addEventListener('change', () => {- currentFilters.sort = sortBySelect.value;- applyFilters();- });- }+ formTabs[index].classList.add('active');+ tabContents[index].classList.add('active');- // View switcher event listeners- if (gridViewBtn) gridViewBtn.addEventListener('click', () => switchView('grid'));- if (listViewBtn) listViewBtn.addEventListener('click', () => switchView('list'));- if (tableViewBtn) tableViewBtn.addEventListener('click', () => switchView('table'));+ // Update current tab index+ currentTabIndex = index;- // Export button event listener- if (exportBtn) exportBtn.addEventListener('click', exportWarranties);+ // Update progress indicator+ document.querySelector('.form-tabs').setAttribute('data-step', currentTabIndex);- // File input change event- if (fileInput) fileInput.addEventListener('change', (e) => updateFileName(e, 'invoice', 'fileName'));- if (manualInput) manualInput.addEventListener('change', (e) => updateFileName(e, 'manual', 'manualFileName'));+ // Update completed tabs+ updateCompletedTabs();- const editInvoice = document.getElementById('editInvoice');- if (editInvoice) {- editInvoice.addEventListener('change', () => {- updateFileName(null, 'editInvoice', 'editFileName');- });- }+ // Update navigation buttons+ updateNavigationButtons();- const editManual = document.getElementById('editManual');- if (editManual) {- editManual.addEventListener('change', () => {- updateFileName(null, 'editManual', 'editManualFileName');- });+ // Update summary if on summary tab+ if (index === formTabs.length - 1) {+ updateSummary();}+}++// Update navigation buttons based on current tab+function updateNavigationButtons() {+ const prevButton = document.querySelector('.prev-tab');+ const nextButton = document.querySelector('.next-tab');+ const submitButton = document.querySelector('button[type="submit"]');- // Form submission- if (warrantyForm) warrantyForm.addEventListener('submit', addWarranty);-- // Refresh button- if (refreshBtn) refreshBtn.addEventListener('click', loadWarranties);+ // Hide/show previous button+ prevButton.style.display = currentTabIndex === 0 ? 'none' : 'block';- // Save warranty changes- if (saveWarrantyBtn) saveWarrantyBtn.addEventListener('click', updateWarranty);+ // Hide/show next button and submit button+ if (currentTabIndex === formTabs.length - 1) {+ nextButton.style.display = 'none';+ submitButton.style.display = 'block';+ } else {+ nextButton.style.display = 'block';+ submitButton.style.display = 'none';+ }+}++// Update completed tabs+function updateCompletedTabs() {+ formTabs.forEach((tab, index) => {+ if (index < currentTabIndex) {+ tab.classList.add('completed');+ } else {+ tab.classList.remove('completed');+ }+ });+}++// Validate a specific tab+function validateTab(tabIndex) {+ const tabContent = tabContents[tabIndex];+ const requiredInputs = tabContent.querySelectorAll('input[required]');- // Confirm delete button- if (confirmDeleteBtn) confirmDeleteBtn.addEventListener('click', deleteWarranty);+ // If there are no required inputs in this tab, it's automatically valid+ if (requiredInputs.length === 0) {+ return true;+ }- // Load saved view preference- loadViewPreference();+ let isValid = true;- // Load preferences first to ensure we have the correct expiringSoonDays value- // before loading warranties- if (window.auth && window.auth.isAuthenticated()) {- console.log('User is authenticated, loading preferences...');- const token = window.auth.getToken();-- if (token) {- fetch('/api/auth/preferences', {- headers: {- 'Authorization': `Bearer ${token}`- }- })- .then(response => {- if (response.ok) return response.json();- throw new Error('Failed to load preferences');- })- .then(data => {- if (data && data.expiring_soon_days) {- expiringSoonDays = data.expiring_soon_days;- console.log('Updated expiring soon days from preferences during initialization:', expiringSoonDays);- }- // Now load warranties with the updated preference- loadWarranties();- })- .catch(error => {- console.error('Error loading preferences during initialization:', error);- // Still load warranties even if preferences couldn't be loaded- loadWarranties();- });+ requiredInputs.forEach(input => {+ if (!input.value.trim()) {+ isValid = false;+ input.classList.add('invalid');} else {- // No token available, load warranties with default preference- loadWarranties();+ input.classList.remove('invalid');}- } else {- // User not authenticated, load warranties (this will show login prompt)- loadWarranties();- }+ });- console.log('App initialization complete');-});--// Dark mode toggle-darkModeToggle.addEventListener('change', (e) => {- setTheme(e.target.checked);-});--const serialNumbersContainer = document.getElementById('serialNumbersContainer');--// Add event listener for adding new serial number inputs-serialNumbersContainer.addEventListener('click', (e) => {- if (e.target.closest('.add-serial-number')) {- addSerialNumberInput();- }-});+ return isValid;+}-function addSerialNumberInput(container = serialNumbersContainer) {- // Check if this is the first input or an additional one- const isFirstInput = container.querySelectorAll('.serial-number-input').length === 0;-- const newInput = document.createElement('div');- newInput.className = 'serial-number-input';+// Show validation errors for a specific tab+function showValidationErrors(tabIndex) {+ const tabContent = tabContents[tabIndex];+ const requiredInputs = tabContent.querySelectorAll('input[required]');- if (isFirstInput) {+ requiredInputs.forEach(input => {+ if (!input.value.trim()) {+ input.classList.add('invalid');++ // Add validation message if not already present+ let validationMessage = input.nextElementSibling;+ if (!validationMessage || !validationMessage.classList.contains('validation-message')) {+ validationMessage = document.createElement('div');+ validationMessage.className = 'validation-message';+ validationMessage.textContent = 'This field is required';+ input.parentNode.insertBefore(validationMessage, input.nextSibling);+ }+ }+ });++ // Show toast message+ showToast('Please fill in all required fields', 'error');+}++// Update summary tab with current form values+function updateSummary() {+ // Product information+ document.getElementById('summary-product-name').textContent =+ document.getElementById('productName').value || '-';++ document.getElementById('summary-product-url').textContent =+ document.getElementById('productUrl').value || '-';++ // Serial numbers+ const serialNumbers = [];+ document.querySelectorAll('input[name="serial_numbers[]"]').forEach(input => {+ if (input.value.trim()) {+ serialNumbers.push(input.value.trim());+ }+ });++ const serialNumbersContainer = document.getElementById('summary-serial-numbers');+ if (serialNumbers.length > 0) {+ serialNumbersContainer.innerHTML = '<ul>' ++ serialNumbers.map(sn => `<li>${sn}</li>`).join('') ++ '</ul>';+ } else {+ serialNumbersContainer.textContent = 'None';+ }++ // Warranty details+ const purchaseDate = document.getElementById('purchaseDate').value;+ document.getElementById('summary-purchase-date').textContent = purchaseDate ?+ new Date(purchaseDate).toLocaleDateString() : '-';++ const warrantyYears = document.getElementById('warrantyYears').value;+ document.getElementById('summary-warranty-years').textContent = warrantyYears ?+ `${warrantyYears} ${warrantyYears > 1 ? 'years' : 'year'}` : '-';++ // Calculate and display expiration date+ if (purchaseDate && warrantyYears) {+ const expirationDate = new Date(purchaseDate);+ expirationDate.setFullYear(expirationDate.getFullYear() + parseInt(warrantyYears));+ document.getElementById('summary-expiration-date').textContent =+ expirationDate.toLocaleDateString();+ } else {+ document.getElementById('summary-expiration-date').textContent = '-';+ }++ // Purchase price+ const purchasePrice = document.getElementById('purchasePrice').value;+ document.getElementById('summary-purchase-price').textContent = purchasePrice ?+ `$${parseFloat(purchasePrice).toFixed(2)}` : 'Not specified';++ // Documents+ const invoiceFile = document.getElementById('invoice').files[0];+ document.getElementById('summary-invoice').textContent = invoiceFile ?+ invoiceFile.name : 'No file selected';++ const manualFile = document.getElementById('manual').files[0];+ document.getElementById('summary-manual').textContent = manualFile ?+ manualFile.name : 'No file selected';+}++// Add input event listeners to remove validation errors when user types+document.addEventListener('input', (e) => {+ if (e.target.hasAttribute('required') && e.target.classList.contains('invalid')) {+ if (e.target.value.trim()) {+ e.target.classList.remove('invalid');++ // Remove validation message if exists+ const validationMessage = e.target.nextElementSibling;+ if (validationMessage && validationMessage.classList.contains('validation-message')) {+ validationMessage.remove();+ }+ }+ }+});++// Function to reset the form and initialize serial number inputs+function resetForm() {+ // Reset the form+ warrantyForm.reset();++ // Reset serial numbers container+ serialNumbersContainer.innerHTML = '';++ // Add the first serial number input+ addSerialNumberInput();++ // Reset form tabs+ currentTabIndex = 0;+ switchToTab(0);++ // Clear any file input displays+ fileName.textContent = '';+ manualFileName.textContent = '';+}++async function exportWarranties() {+ // Get filtered warranties+ let warrantiesToExport = [...warranties];++ // Apply current filters+ if (currentFilters.search) {+ warrantiesToExport = warrantiesToExport.filter(warranty =>+ warranty.product_name.toLowerCase().includes(currentFilters.search)+ );+ }++ if (currentFilters.status !== 'all') {+ warrantiesToExport = warrantiesToExport.filter(warranty =>+ warranty.status === currentFilters.status+ );+ }++ // Create CSV content+ let csvContent = "data:text/csv;charset=utf-8,";++ // Add headers+ csvContent += "Product Name,Purchase Date,Warranty Period,Expiration Date,Status,Serial Numbers\n";++ // Add data rows+ warrantiesToExport.forEach(warranty => {+ const purchaseDate = new Date(warranty.purchase_date).toLocaleDateString();+ const expirationDate = new Date(warranty.expiration_date).toLocaleDateString();+ const serialNumbers = Array.isArray(warranty.serial_numbers)+ ? warranty.serial_numbers.join('; ')+ : '';++ // Calculate status if not already set+ if (!warranty.status) {+ const today = new Date();+ const expDate = new Date(warranty.expiration_date);+ const daysRemaining = Math.floor((expDate - today) / (1000 * 60 * 60 * 24));++ if (daysRemaining < 0) {+ warranty.status = 'Expired';+ } else if (daysRemaining < expiringSoonDays) {+ warranty.status = 'Expiring Soon';+ } else {+ warranty.status = 'Active';+ }+ }++ // Format status for CSV+ let statusText = warranty.status.charAt(0).toUpperCase() + warranty.status.slice(1);+ if (statusText === 'Expiring') statusText = 'Expiring Soon';++ // Create CSV row+ csvContent += `"${warranty.product_name}",${purchaseDate},${warranty.warranty_years} years,${expirationDate},${statusText},"${serialNumbers}"\n`;+ });++ // Create download link+ const encodedUri = encodeURI(csvContent);+ const link = document.createElement("a");+ link.setAttribute("href", encodedUri);+ link.setAttribute("download", "warranties.csv");+ document.body.appendChild(link);++ // Trigger download+ link.click();++ // Clean up+ document.body.removeChild(link);++ showToast('Warranties exported successfully', 'success');+}++// Function to switch between views+function switchView(viewType) {+ console.log('Switching view to:', viewType);++ // Process all warranties to ensure consistency+ processAllWarranties();++ // Update current view+ currentView = viewType;++ // Update view buttons+ gridViewBtn.classList.toggle('active', viewType === 'grid');+ listViewBtn.classList.toggle('active', viewType === 'list');+ tableViewBtn.classList.toggle('active', viewType === 'table');++ // Update warranties list class+ warrantiesList.className = `warranties-list ${viewType}-view`;++ // Show/hide table header for table view+ if (tableViewHeader) {+ tableViewHeader.classList.toggle('visible', viewType === 'table');+ }++ // Re-render warranties with the new view+ console.log('Applying filters after switching view...');+ applyFilters();++ // Save view preference to localStorage+ localStorage.setItem('warrantyView', viewType);+}++// Load saved view preference+function loadViewPreference() {+ // First check for warrantyView (direct view selection)+ const savedView = localStorage.getItem('warrantyView');+ // If not found, check for defaultView (from settings)+ const defaultView = localStorage.getItem('defaultView');++ // Use warrantyView if available, otherwise use defaultView, or fall back to grid+ const viewToUse = savedView || defaultView || 'grid';++ if (viewToUse) {+ switchView(viewToUse);+ }+}++// Dark mode toggle+darkModeToggle.addEventListener('change', (e) => {+ setTheme(e.target.checked);+});++const serialNumbersContainer = document.getElementById('serialNumbersContainer');++// Add event listener for adding new serial number inputs+serialNumbersContainer.addEventListener('click', (e) => {+ if (e.target.closest('.add-serial-number')) {+ addSerialNumberInput();+ }+});++function addSerialNumberInput(container = serialNumbersContainer) {+ // Check if this is the first input or an additional one+ const isFirstInput = container.querySelectorAll('.serial-number-input').length === 0;++ const newInput = document.createElement('div');+ newInput.className = 'serial-number-input';++ if (isFirstInput) {// First input should have both Add and Remove buttonsnewInput.innerHTML = `<input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number">@@ -257,118 +497,6 @@ function addSerialNumberInput(container = serialNumbersContainer) {container.appendChild(newInput);}-// Variables-let warranties = [];-let currentWarrantyId = null;-let currentFilters = {- search: '',- status: 'all',- sort: 'expiration'-};-let currentView = 'grid'; // Default view-let expiringSoonDays = 30; // Default value, will be updated from user preferences--// API URL-const API_URL = '/api/warranties';--// Event Listeners-document.addEventListener('DOMContentLoaded', () => {- console.log('DOM fully loaded, initializing app...');-- // Initialize the app- initializeTheme();-- // Load warranties - now handled by the preferences loading logic- // loadWarranties();-- // Initialize form tabs- initFormTabs();-- // Initialize the form- resetForm();-- // Close modals when clicking outside or on close button- document.querySelectorAll('.modal-backdrop, [data-dismiss="modal"]').forEach(element => {- element.addEventListener('click', (e) => {- if (e.target === element) {- closeModals();- }- });- });-- // Prevent modal content clicks from closing the modal- document.querySelectorAll('.modal').forEach(modal => {- modal.addEventListener('click', (e) => {- e.stopPropagation();- });- });-- // Filter event listeners- if (searchInput) {- searchInput.addEventListener('input', () => {- currentFilters.search = searchInput.value.toLowerCase();- applyFilters();- });- }-- if (statusFilter) {- statusFilter.addEventListener('change', () => {- currentFilters.status = statusFilter.value;- applyFilters();- });- }-- if (sortBySelect) {- sortBySelect.addEventListener('change', () => {- currentFilters.sort = sortBySelect.value;- applyFilters();- });- }-- // View switcher event listeners- if (gridViewBtn) gridViewBtn.addEventListener('click', () => switchView('grid'));- if (listViewBtn) listViewBtn.addEventListener('click', () => switchView('list'));- if (tableViewBtn) tableViewBtn.addEventListener('click', () => switchView('table'));-- // Export button event listener- if (exportBtn) exportBtn.addEventListener('click', exportWarranties);-- // File input change event- if (fileInput) fileInput.addEventListener('change', (e) => updateFileName(e, 'invoice', 'fileName'));- if (manualInput) manualInput.addEventListener('change', (e) => updateFileName(e, 'manual', 'manualFileName'));-- const editInvoice = document.getElementById('editInvoice');- if (editInvoice) {- editInvoice.addEventListener('change', () => {- updateFileName(null, 'editInvoice', 'editFileName');- });- }-- const editManual = document.getElementById('editManual');- if (editManual) {- editManual.addEventListener('change', () => {- updateFileName(null, 'editManual', 'editManualFileName');- });- }-- // Form submission- if (warrantyForm) warrantyForm.addEventListener('submit', addWarranty);-- // Refresh button- if (refreshBtn) refreshBtn.addEventListener('click', loadWarranties);-- // Save warranty changes- if (saveWarrantyBtn) saveWarrantyBtn.addEventListener('click', updateWarranty);-- // Confirm delete button- if (confirmDeleteBtn) confirmDeleteBtn.addEventListener('click', deleteWarranty);-- // Load saved view preference- loadViewPreference();-- console.log('App initialization complete');-});-// Functionsfunction showLoading() {loadingContainer.classList.add('active');@@ -851,6 +979,30 @@ function filterWarranties() {renderWarranties(filtered);}+function applyFilters() {+ console.log('Applying filters with:', currentFilters);++ // Filter warranties based on currentFilters+ const filtered = warranties.filter(warranty => {+ // Status filter+ if (currentFilters.status !== 'all' && warranty.status !== currentFilters.status) {+ return false;+ }++ // Search filter+ if (currentFilters.search && !warranty.product_name.toLowerCase().includes(currentFilters.search.toLowerCase())) {+ return false;+ }++ return true;+ });++ console.log('Filtered warranties:', filtered);++ // Render the filtered warranties+ renderWarranties(filtered);+}+function openEditModal(warranty) {currentWarrantyId = warranty.id;@@ -912,447 +1064,93 @@ function openEditModal(warranty) {// Add remove button functionalitynewInput.querySelector('.remove-serial-number').addEventListener('click', function() {this.parentElement.remove();- });-- editSerialNumbersContainer.appendChild(newInput);- }- }-- // Show current invoice if exists- const currentInvoiceElement = document.getElementById('currentInvoice');- if (currentInvoiceElement) {- if (warranty.invoice_path) {- currentInvoiceElement.innerHTML = `- <span class="text-success">- <i class="fas fa-check-circle"></i> Current invoice:- <a href="#" onclick="openSecureFile('${warranty.invoice_path}'); return false;">View</a>- (Upload a new file to replace)- </span>- `;- } else {- currentInvoiceElement.innerHTML = '<span>No invoice uploaded</span>';- }- }-- // Show current manual if exists- const currentManualElement = document.getElementById('currentManual');- if (currentManualElement) {- if (warranty.manual_path) {- currentManualElement.innerHTML = `- <span class="text-success">- <i class="fas fa-check-circle"></i> Current manual:- <a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;">View</a>- (Upload a new file to replace)- </span>- `;- } else {- currentManualElement.innerHTML = '<span>No manual uploaded</span>';- }- }-- // Reset file input display- document.getElementById('editFileName').textContent = '';-- // Show modal- editModal.classList.add('active');-}--function openDeleteModal(warrantyId) {- currentWarrantyId = warrantyId;- deleteModal.classList.add('active');-}--function closeModals() {- editModal.classList.remove('active');- deleteModal.classList.remove('active');- currentWarrantyId = null;-}--async function updateWarranty() {- // Check if user is authenticated- if (window.auth && !window.auth.isAuthenticated()) {- showToast('Please login to update warranties', 'warning');- closeModals();- setTimeout(() => {- window.location.href = 'login.html';- }, 1500);- return;- }-- if (!currentWarrantyId) {- showToast('No warranty selected for update', 'error');- return;- }-- // Create FormData object- const formData = new FormData(editWarrantyForm);-- // Get all serial numbers- const serialNumbers = [];- document.querySelectorAll('#editSerialNumbersContainer input[name="serial_numbers[]"]').forEach(input => {- if (input.value.trim()) {- serialNumbers.push(input.value.trim());- }- });-- // Remove default serial numbers entry and add the collected ones- formData.delete('serial_numbers[]');- serialNumbers.forEach(sn => {- formData.append('serial_numbers', sn);- });-- try {- showLoading();-- // Get the auth token- const token = window.auth.getToken();- if (!token) {- showToast('Authentication error. Please log in again.', 'error');- hideLoading();- closeModals();- return;- }-- // Create request with auth header- const options = {- method: 'PUT',- body: formData,- headers: {- 'Authorization': `Bearer ${token}`- }- };-- // Use the full URL to avoid path issues- const apiUrl = `${window.location.origin}/api/warranties/${currentWarrantyId}`;-- console.log('Updating warranty with ID:', currentWarrantyId);- const response = await fetch(apiUrl, options);-- if (!response.ok) {- const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));- throw new Error(errorData.message || `Error updating warranty: ${response.status}`);- }-- const result = await response.json();- console.log('Received update warranty result:', result);-- // Reload all warranties to get the complete data- await loadWarranties();-- // Close modal- closeModals();-- // Show success message- showToast('Warranty updated successfully!', 'success');- } catch (error) {- console.error('Error updating warranty:', error);- showToast(error.message || 'Error updating warranty. Please try again.', 'error');- } finally {- hideLoading();- }-}--async function deleteWarranty() {- // Check if user is authenticated- if (window.auth && !window.auth.isAuthenticated()) {- showToast('Please login to delete warranties', 'warning');- closeModals();- setTimeout(() => {- window.location.href = 'login.html';- }, 1500);- return;- }-- if (!currentWarrantyId) {- showToast('No warranty selected for deletion', 'error');- return;- }-- try {- showLoading();-- // Get the auth token- const token = window.auth.getToken();- if (!token) {- showToast('Authentication error. Please log in again.', 'error');- hideLoading();- closeModals();- return;- }-- // Create request with auth header- const options = {- method: 'DELETE',- headers: {- 'Authorization': `Bearer ${token}`,- 'Content-Type': 'application/json'- }- };-- // Use the full URL to avoid path issues- const apiUrl = `${window.location.origin}/api/warranties/${currentWarrantyId}`;-- console.log('Deleting warranty with ID:', currentWarrantyId);- const response = await fetch(apiUrl, options);-- if (!response.ok) {- const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));- throw new Error(errorData.message || `Error deleting warranty: ${response.status}`);- }-- // Reload all warranties to get the updated list- await loadWarranties();-- // Close the modal- closeModals();-- // Show success message- showToast('Warranty deleted successfully!', 'success');- } catch (error) {- console.error('Error deleting warranty:', error);- showToast(error.message || 'Error deleting warranty. Please try again.', 'error');- } finally {- hideLoading();- }-}--// Form tab navigation variables-const formTabs = Array.from(document.querySelectorAll('.form-tab'));-const tabContents = Array.from(document.querySelectorAll('.tab-content'));-let currentTabIndex = 0;--// Initialize form tabs-function initFormTabs() {- // Hide the submit button initially- const submitButton = document.querySelector('button[type="submit"]');- if (submitButton) {- submitButton.style.display = 'none';- }-- // Show/hide navigation buttons based on current tab- updateNavigationButtons();-- // Add event listeners for tab navigation- document.querySelector('.next-tab').addEventListener('click', () => {- if (validateTab(currentTabIndex)) {- switchToTab(currentTabIndex + 1);- } else {- showValidationErrors(currentTabIndex);- }- });-- document.querySelector('.prev-tab').addEventListener('click', () => {- switchToTab(currentTabIndex - 1);- });-- // Add click event for tab headers- formTabs.forEach((tab, index) => {- tab.addEventListener('click', () => {- // Only allow clicking on previous tabs or current tab- if (index <= currentTabIndex) {- switchToTab(index);- }- });- });-}--// Switch to a specific tab-function switchToTab(index) {- // Ensure index is within bounds- if (index < 0 || index >= formTabs.length) return;-- // Update active tab- formTabs.forEach(tab => tab.classList.remove('active'));- tabContents.forEach(content => content.classList.remove('active'));-- formTabs[index].classList.add('active');- tabContents[index].classList.add('active');-- // Update current tab index- currentTabIndex = index;-- // Update progress indicator- document.querySelector('.form-tabs').setAttribute('data-step', currentTabIndex);-- // Update completed tabs- updateCompletedTabs();-- // Update navigation buttons- updateNavigationButtons();-- // Update summary if on summary tab- if (index === formTabs.length - 1) {- updateSummary();- }-}--// Update navigation buttons based on current tab-function updateNavigationButtons() {- const prevButton = document.querySelector('.prev-tab');- const nextButton = document.querySelector('.next-tab');- const submitButton = document.querySelector('button[type="submit"]');-- // Hide/show previous button- prevButton.style.display = currentTabIndex === 0 ? 'none' : 'block';-- // Hide/show next button and submit button- if (currentTabIndex === formTabs.length - 1) {- nextButton.style.display = 'none';- submitButton.style.display = 'block';- } else {- nextButton.style.display = 'block';- submitButton.style.display = 'none';- }-}--// Update completed tabs-function updateCompletedTabs() {- formTabs.forEach((tab, index) => {- if (index < currentTabIndex) {- tab.classList.add('completed');- } else {- tab.classList.remove('completed');- }- });-}--// Validate a specific tab-function validateTab(tabIndex) {- const tabContent = tabContents[tabIndex];- const requiredInputs = tabContent.querySelectorAll('input[required]');- let isValid = true;-- requiredInputs.forEach(input => {- if (!input.value.trim()) {- isValid = false;- input.classList.add('invalid');- } else {- input.classList.remove('invalid');- }- });-- return isValid;-}--// Show validation errors for a specific tab-function showValidationErrors(tabIndex) {- const tabContent = tabContents[tabIndex];- const requiredInputs = tabContent.querySelectorAll('input[required]');-- requiredInputs.forEach(input => {- if (!input.value.trim()) {- input.classList.add('invalid');-- // Add validation message if not already present- let validationMessage = input.nextElementSibling;- if (!validationMessage || !validationMessage.classList.contains('validation-message')) {- validationMessage = document.createElement('div');- validationMessage.className = 'validation-message';- validationMessage.textContent = 'This field is required';- input.parentNode.insertBefore(validationMessage, input.nextSibling);- }- }- });-- // Show toast message- showToast('Please fill in all required fields', 'error');-}--// Update summary tab with current form values-function updateSummary() {- // Product information- document.getElementById('summary-product-name').textContent =- document.getElementById('productName').value || '-';-- document.getElementById('summary-product-url').textContent =- document.getElementById('productUrl').value || '-';-- // Serial numbers- const serialNumbers = [];- document.querySelectorAll('input[name="serial_numbers[]"]').forEach(input => {- if (input.value.trim()) {- serialNumbers.push(input.value.trim());- }- });-- const serialNumbersContainer = document.getElementById('summary-serial-numbers');- if (serialNumbers.length > 0) {- serialNumbersContainer.innerHTML = '<ul>' +- serialNumbers.map(sn => `<li>${sn}</li>`).join('') +- '</ul>';- } else {- serialNumbersContainer.textContent = 'None';+ });++ editSerialNumbersContainer.appendChild(newInput);+ }}- // Warranty details- const purchaseDate = document.getElementById('purchaseDate').value;- document.getElementById('summary-purchase-date').textContent = purchaseDate ?- new Date(purchaseDate).toLocaleDateString() : '-';-- const warrantyYears = document.getElementById('warrantyYears').value;- document.getElementById('summary-warranty-years').textContent = warrantyYears ?- `${warrantyYears} ${warrantyYears > 1 ? 'years' : 'year'}` : '-';-- // Calculate and display expiration date- if (purchaseDate && warrantyYears) {- const expirationDate = new Date(purchaseDate);- expirationDate.setFullYear(expirationDate.getFullYear() + parseInt(warrantyYears));- document.getElementById('summary-expiration-date').textContent =- expirationDate.toLocaleDateString();- } else {- document.getElementById('summary-expiration-date').textContent = '-';+ // Show current invoice if exists+ const currentInvoiceElement = document.getElementById('currentInvoice');+ if (currentInvoiceElement) {+ if (warranty.invoice_path) {+ currentInvoiceElement.innerHTML = `+ <span class="text-success">+ <i class="fas fa-check-circle"></i> Current invoice:+ <a href="#" onclick="openSecureFile('${warranty.invoice_path}'); return false;">View</a>+ (Upload a new file to replace)+ </span>+ `;+ } else {+ currentInvoiceElement.innerHTML = '<span>No invoice uploaded</span>';+ }}- // Purchase price- const purchasePrice = document.getElementById('purchasePrice').value;- document.getElementById('summary-purchase-price').textContent = purchasePrice ?- `$${parseFloat(purchasePrice).toFixed(2)}` : 'Not specified';+ // Show current manual if exists+ const currentManualElement = document.getElementById('currentManual');+ if (currentManualElement) {+ if (warranty.manual_path) {+ currentManualElement.innerHTML = `+ <span class="text-success">+ <i class="fas fa-check-circle"></i> Current manual:+ <a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;">View</a>+ (Upload a new file to replace)+ </span>+ `;+ } else {+ currentManualElement.innerHTML = '<span>No manual uploaded</span>';+ }+ }- // Documents- const invoiceFile = document.getElementById('invoice').files[0];- document.getElementById('summary-invoice').textContent = invoiceFile ?- invoiceFile.name : 'No file selected';+ // Reset file input display+ document.getElementById('editFileName').textContent = '';- const manualFile = document.getElementById('manual').files[0];- document.getElementById('summary-manual').textContent = manualFile ?- manualFile.name : 'No file selected';+ // Show modal+ editModal.classList.add('active');}-// Add input event listeners to remove validation errors when user types-document.addEventListener('input', (e) => {- if (e.target.hasAttribute('required') && e.target.classList.contains('invalid')) {- if (e.target.value.trim()) {- e.target.classList.remove('invalid');-- // Remove validation message if exists- const validationMessage = e.target.nextElementSibling;- if (validationMessage && validationMessage.classList.contains('validation-message')) {- validationMessage.remove();- }- }- }-});+function openDeleteModal(warrantyId) {+ currentWarrantyId = warrantyId;+ deleteModal.classList.add('active');+}-// Function to reset the form and initialize serial number inputs-function resetForm() {- // Reset the form- warrantyForm.reset();+function closeModals() {+ editModal.classList.remove('active');+ deleteModal.classList.remove('active');+ currentWarrantyId = null;+}++// Validate file size before upload+function validateFileSize(formData, maxSizeMB = 32) {+ let totalSize = 0;- // Reset serial numbers container- serialNumbersContainer.innerHTML = '';+ // Check file sizes+ if (formData.has('invoice') && formData.get('invoice').size > 0) {+ totalSize += formData.get('invoice').size;+ }- // Add the first serial number input- addSerialNumberInput();+ if (formData.has('manual') && formData.get('manual').size > 0) {+ totalSize += formData.get('manual').size;+ }- // Reset form tabs- currentTabIndex = 0;- switchToTab(0);+ // Convert bytes to MB for comparison and display+ const totalSizeMB = totalSize / (1024 * 1024);+ console.log(`Total upload size: ${totalSizeMB.toFixed(2)} MB`);- // Clear any file input displays- fileName.textContent = '';- manualFileName.textContent = '';+ // Check if total size exceeds limit+ if (totalSizeMB > maxSizeMB) {+ return {+ valid: false,+ message: `Total file size (${totalSizeMB.toFixed(2)} MB) exceeds the maximum allowed size of ${maxSizeMB} MB. Please reduce file sizes.`+ };+ }++ return {+ valid: true+ };}+// Modify the beginning of the addWarranty function to check file sizes before uploadingasync function addWarranty(event) {event.preventDefault();@@ -1373,20 +1171,34 @@ async function addWarranty(event) {// Create FormData objectconst formData = new FormData(warrantyForm);- // Add serial numbers- const serialNumberInputs = document.querySelectorAll('input[name="serial_numbers[]"]');- formData.delete('serial_numbers[]'); // Remove the default entries- serialNumberInputs.forEach(input => {+ // Validate file sizes before trying to upload+ const fileSizeValidation = validateFileSize(formData);+ if (!fileSizeValidation.valid) {+ showToast(fileSizeValidation.message, 'error');+ hideLoading();+ return;+ }++ // Get all serial numbers+ const serialNumbers = [];+ document.querySelectorAll('input[name="serial_numbers[]"]').forEach(input => {if (input.value.trim()) {- formData.append('serial_numbers', input.value.trim());+ serialNumbers.push(input.value.trim());}});+ // Remove default serial numbers entry and add the collected ones+ formData.delete('serial_numbers[]');+ serialNumbers.forEach(sn => {+ formData.append('serial_numbers', sn);+ });+// Get the auth tokenconst token = window.auth.getToken();if (!token) {showToast('Authentication error. Please log in again.', 'error');hideLoading();+ closeModals();return;}@@ -1406,6 +1218,11 @@ async function addWarranty(event) {const response = await fetch(apiUrl, options);if (!response.ok) {+ // Specifically handle 413 Request Entity Too Large error+ if (response.status === 413) {+ throw new Error('File size too large. Please reduce the file size of your uploads (maximum 32MB total) or split into multiple warranties.');+ }+const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));throw new Error(errorData.message || `Error adding warranty: ${response.status}`);}@@ -1429,145 +1246,325 @@ async function addWarranty(event) {throw new Error('Failed to get warranty ID from server response');}} catch (error) {- console.error('Error adding warranty:', error);- showToast(error.message || 'Error adding warranty. Please try again.', 'error');+ console.error('Error adding warranty:', error);+ showToast(error.message || 'Error adding warranty. Please try again.', 'error');+ } finally {+ hideLoading();+ }+}++// Modify the beginning of the updateWarranty function to check file sizes before uploading+async function updateWarranty() {+ // Check if user is authenticated+ if (window.auth && !window.auth.isAuthenticated()) {+ showToast('Please login to update warranties', 'warning');+ closeModals();+ setTimeout(() => {+ window.location.href = 'login.html';+ }, 1500);+ return;+ }++ if (!currentWarrantyId) {+ showToast('No warranty selected for update', 'error');+ return;+ }++ // Create FormData object+ const formData = new FormData(editWarrantyForm);++ // Validate file sizes before trying to upload+ const fileSizeValidation = validateFileSize(formData);+ if (!fileSizeValidation.valid) {+ showToast(fileSizeValidation.message, 'error');+ return;+ }++ // Get all serial numbers+ const serialNumbers = [];+ document.querySelectorAll('#editSerialNumbersContainer input[name="serial_numbers[]"]').forEach(input => {+ if (input.value.trim()) {+ serialNumbers.push(input.value.trim());+ }+ });++ // Remove default serial numbers entry and add the collected ones+ formData.delete('serial_numbers[]');+ serialNumbers.forEach(sn => {+ formData.append('serial_numbers', sn);+ });++ try {+ showLoading();++ // Get the auth token+ const token = window.auth.getToken();+ if (!token) {+ showToast('Authentication error. Please log in again.', 'error');+ hideLoading();+ closeModals();+ return;+ }++ // Create request with auth header+ const options = {+ method: 'PUT',+ body: formData,+ headers: {+ 'Authorization': `Bearer ${token}`+ }+ };++ // Use the full URL to avoid path issues+ const apiUrl = `${window.location.origin}/api/warranties/${currentWarrantyId}`;++ console.log('Updating warranty with ID:', currentWarrantyId);+ const response = await fetch(apiUrl, options);++ if (!response.ok) {+ // Specifically handle 413 Request Entity Too Large error+ if (response.status === 413) {+ throw new Error('File size too large. Please reduce the file size of your uploads (maximum 32MB total) or split into multiple warranties.');+ }++ const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));+ throw new Error(errorData.message || `Error updating warranty: ${response.status}`);+ }++ const result = await response.json();+ console.log('Received update warranty result:', result);++ // Reload all warranties to get the complete data+ await loadWarranties();++ // Close modal+ closeModals();++ // Show success message+ showToast('Warranty updated successfully!', 'success');+ } catch (error) {+ console.error('Error updating warranty:', error);+ showToast(error.message || 'Error updating warranty. Please try again.', 'error');+ } finally {+ hideLoading();+ }+}++async function deleteWarranty() {+ // Check if user is authenticated+ if (window.auth && !window.auth.isAuthenticated()) {+ showToast('Please login to delete warranties', 'warning');+ closeModals();+ setTimeout(() => {+ window.location.href = 'login.html';+ }, 1500);+ return;+ }++ if (!currentWarrantyId) {+ showToast('No warranty selected for deletion', 'error');+ return;+ }++ try {+ showLoading();++ // Get the auth token+ const token = window.auth.getToken();+ if (!token) {+ showToast('Authentication error. Please log in again.', 'error');+ hideLoading();+ closeModals();+ return;+ }++ // Create request with auth header+ const options = {+ method: 'DELETE',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Content-Type': 'application/json'+ }+ };++ // Use the full URL to avoid path issues+ const apiUrl = `${window.location.origin}/api/warranties/${currentWarrantyId}`;++ console.log('Deleting warranty with ID:', currentWarrantyId);+ const response = await fetch(apiUrl, options);++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));+ throw new Error(errorData.message || `Error deleting warranty: ${response.status}`);+ }++ // Reload all warranties to get the updated list+ await loadWarranties();++ // Close the modal+ closeModals();++ // Show success message+ showToast('Warranty deleted successfully!', 'success');+ } catch (error) {+ console.error('Error deleting warranty:', error);+ showToast(error.message || 'Error deleting warranty. Please try again.', 'error');} finally {hideLoading();}}-function applyFilters() {- console.log('applyFilters called with warranties:', warranties);- const filtered = warranties.filter(warranty => {- // Status filter- if (currentFilters.status !== 'all' && warranty.status !== currentFilters.status) {- return false;- }-- // Search filter- if (currentFilters.search && !warranty.product_name.toLowerCase().includes(currentFilters.search.toLowerCase())) {- return false;- }-- return true;- });-- console.log('Filtered warranties:', filtered);- renderWarranties(filtered);-}--async function exportWarranties() {- // Get filtered warranties- let warrantiesToExport = [...warranties];+// Initialize page+document.addEventListener('DOMContentLoaded', () => {+ console.log('DOM fully loaded, initializing app...');- // Apply current filters- if (currentFilters.search) {- warrantiesToExport = warrantiesToExport.filter(warranty =>- warranty.product_name.toLowerCase().includes(currentFilters.search)- );+ // Ensure auth state is checked+ if (window.auth && window.auth.checkAuthState) {+ window.auth.checkAuthState();}- if (currentFilters.status !== 'all') {- warrantiesToExport = warrantiesToExport.filter(warranty =>- warranty.status === currentFilters.status- );+ // Initialize settings button+ if (settingsBtn && settingsMenu) {+ settingsBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ settingsMenu.classList.toggle('active');+ });++ // Close settings menu when clicking outside+ document.addEventListener('click', (e) => {+ if (settingsMenu.classList.contains('active') &&+ !settingsMenu.contains(e.target) &&+ !settingsBtn.contains(e.target)) {+ settingsMenu.classList.remove('active');+ }+ });}- // Create CSV content- let csvContent = "data:text/csv;charset=utf-8,";+ // Initialize the app+ initializeTheme();- // Add headers- csvContent += "Product Name,Purchase Date,Warranty Period,Expiration Date,Status,Serial Numbers\n";+ // Initialize form tabs+ initFormTabs();- // Add data rows- warrantiesToExport.forEach(warranty => {- const purchaseDate = new Date(warranty.purchase_date).toLocaleDateString();- const expirationDate = new Date(warranty.expiration_date).toLocaleDateString();- const serialNumbers = Array.isArray(warranty.serial_numbers)- ? warranty.serial_numbers.join('; ')- : '';-- // Calculate status if not already set- if (!warranty.status) {- const today = new Date();- const expDate = new Date(warranty.expiration_date);- const daysRemaining = Math.floor((expDate - today) / (1000 * 60 * 60 * 24));-- if (daysRemaining < 0) {- warranty.status = 'Expired';- } else if (daysRemaining < expiringSoonDays) {- warranty.status = 'Expiring Soon';- } else {- warranty.status = 'Active';+ // Initialize the form+ resetForm();++ // Close modals when clicking outside or on close button+ document.querySelectorAll('.modal-backdrop, [data-dismiss="modal"]').forEach(element => {+ element.addEventListener('click', (e) => {+ if (e.target === element) {+ closeModals();}- }-- // Format status for CSV- let statusText = warranty.status.charAt(0).toUpperCase() + warranty.status.slice(1);- if (statusText === 'Expiring') statusText = 'Expiring Soon';-- // Create CSV row- csvContent += `"${warranty.product_name}",${purchaseDate},${warranty.warranty_years} years,${expirationDate},${statusText},"${serialNumbers}"\n`;+ });});- // Create download link- const encodedUri = encodeURI(csvContent);- const link = document.createElement("a");- link.setAttribute("href", encodedUri);- link.setAttribute("download", "warranties.csv");- document.body.appendChild(link);+ // Prevent modal content clicks from closing the modal+ document.querySelectorAll('.modal').forEach(modal => {+ modal.addEventListener('click', (e) => {+ e.stopPropagation();+ });+ });- // Trigger download- link.click();+ // Filter event listeners+ if (searchInput) {+ searchInput.addEventListener('input', () => {+ currentFilters.search = searchInput.value.toLowerCase();+ applyFilters();+ });+ }- // Clean up- document.body.removeChild(link);+ if (statusFilter) {+ statusFilter.addEventListener('change', () => {+ currentFilters.status = statusFilter.value;+ applyFilters();+ });+ }- showToast('Warranties exported successfully', 'success');-}--// Function to switch between views-function switchView(viewType) {- console.log('Switching view to:', viewType);+ if (sortBySelect) {+ sortBySelect.addEventListener('change', () => {+ currentFilters.sort = sortBySelect.value;+ applyFilters();+ });+ }- // Process all warranties to ensure consistency- processAllWarranties();+ // View switcher event listeners+ if (gridViewBtn) gridViewBtn.addEventListener('click', () => switchView('grid'));+ if (listViewBtn) listViewBtn.addEventListener('click', () => switchView('list'));+ if (tableViewBtn) tableViewBtn.addEventListener('click', () => switchView('table'));- // Update current view- currentView = viewType;+ // Export button event listener+ if (exportBtn) exportBtn.addEventListener('click', exportWarranties);- // Update view buttons- gridViewBtn.classList.toggle('active', viewType === 'grid');- listViewBtn.classList.toggle('active', viewType === 'list');- tableViewBtn.classList.toggle('active', viewType === 'table');+ // File input change event+ if (fileInput) fileInput.addEventListener('change', (e) => updateFileName(e, 'invoice', 'fileName'));+ if (manualInput) manualInput.addEventListener('change', (e) => updateFileName(e, 'manual', 'manualFileName'));- // Update warranties list class- warrantiesList.className = `warranties-list ${viewType}-view`;+ const editInvoice = document.getElementById('editInvoice');+ if (editInvoice) {+ editInvoice.addEventListener('change', () => {+ updateFileName(null, 'editInvoice', 'editFileName');+ });+ }- // Show/hide table header for table view- if (tableViewHeader) {- tableViewHeader.classList.toggle('visible', viewType === 'table');+ const editManual = document.getElementById('editManual');+ if (editManual) {+ editManual.addEventListener('change', () => {+ updateFileName(null, 'editManual', 'editManualFileName');+ });}- // Re-render warranties with the new view- console.log('Applying filters after switching view...');- applyFilters();+ // Form submission+ if (warrantyForm) warrantyForm.addEventListener('submit', addWarranty);- // Save view preference to localStorage- localStorage.setItem('warrantyView', viewType);-}--// Load saved view preference-function loadViewPreference() {- // First check for warrantyView (direct view selection)- const savedView = localStorage.getItem('warrantyView');- // If not found, check for defaultView (from settings)- const defaultView = localStorage.getItem('defaultView');+ // Refresh button+ if (refreshBtn) refreshBtn.addEventListener('click', loadWarranties);- // Use warrantyView if available, otherwise use defaultView, or fall back to grid- const viewToUse = savedView || defaultView || 'grid';+ // Save warranty changes+ if (saveWarrantyBtn) saveWarrantyBtn.addEventListener('click', updateWarranty);- if (viewToUse) {- switchView(viewToUse);+ // Confirm delete button+ if (confirmDeleteBtn) confirmDeleteBtn.addEventListener('click', deleteWarranty);++ // Load saved view preference+ loadViewPreference();++ // Load preferences first to ensure we have the correct expiringSoonDays value+ // before loading warranties+ if (window.auth && window.auth.isAuthenticated()) {+ console.log('User is authenticated, loading preferences...');+ const token = window.auth.getToken();++ if (token) {+ fetch('/api/auth/preferences', {+ headers: {+ 'Authorization': `Bearer ${token}`+ }+ })+ .then(response => {+ if (response.ok) return response.json();+ throw new Error('Failed to load preferences');+ })+ .then(data => {+ if (data && data.expiring_soon_days) {+ expiringSoonDays = data.expiring_soon_days;+ console.log('Updated expiring soon days from preferences during initialization:', expiringSoonDays);+ }+ // Now load warranties with the updated preference+ loadWarranties();+ })+ .catch(error => {+ console.error('Error loading preferences during initialization:', error);+ // Still load warranties even if preferences couldn't be loaded+ loadWarranties();+ });+ } else {+ // No token available, load warranties with default preference+ loadWarranties();+ }+ } else {+ // User not authenticated, load warranties (this will show login prompt)+ loadWarranties();}-}\ No newline at end of file++ console.log('App initialization complete');+});\ No newline at end of filediff --git a/frontend/settings-new.html b/frontend/settings-new.htmlindex 39d4bf7..65ec384 100644--- a/frontend/settings-new.html+++ b/frontend/settings-new.html@@ -306,6 +306,9 @@<a href="status.html" class="nav-link"><i class="fas fa-chart-pie"></i> Status</a>+ <a href="settings-new.html" class="nav-link active">+ <i class="fas fa-cog"></i> Settings+ </a></div><div id="authContainer" class="auth-buttons"><a href="login.html" class="auth-btn login-btn">@@ -326,37 +329,15 @@<div id="userEmail" class="user-email">[email protected]</div></div><div class="user-menu-item">- <a href="settings-new.html" style="color: inherit; text-decoration: none; display: flex; align-items: center; width: 100%;">+ <a href="settings-new.html" style="color: inherit; text-decoration: none; display: block;"><i class="fas fa-cog"></i> Settings</a></div>- <div class="user-menu-item" id="profileMenuItem">- <i class="fas fa-id-card"></i> Profile- </div><div class="user-menu-item" id="logoutMenuItem"><i class="fas fa-sign-out-alt"></i> Logout</div></div></div>- <div class="settings-container">- <button id="settingsBtn" class="settings-btn" aria-label="Settings" type="button">- <i class="fas fa-cog"></i>- </button>- <div id="settingsMenu" class="settings-menu">- <div class="settings-item">- <span>Dark Mode</span>- <label class="toggle-switch" title="Toggle dark mode">- <input type="checkbox" id="darkModeToggle">- <span class="toggle-slider"></span>- </label>- </div>- <div class="settings-item">- <a href="https://github.com/sassanix/Warracker" class="settings-link github-link" target="_blank" rel="noopener noreferrer">- <i class="fab fa-github"></i> GitHub- </a>- </div>- </div>- </div></div></header>diff --git a/frontend/settings-new.js b/frontend/settings-new.jsindex b32daf6..cce7323 100644--- a/frontend/settings-new.js+++ b/frontend/settings-new.js@@ -19,6 +19,7 @@ const loadingContainer = document.getElementById('loadingContainer');const toastContainer = document.getElementById('toastContainer');const settingsBtn = document.getElementById('settingsBtn');const settingsMenu = document.getElementById('settingsMenu');+const usersTableBody = document.getElementById('usersTableBody');// Form fieldsconst firstNameInput = document.getElementById('firstName');@@ -149,11 +150,20 @@ function initPage() {return;}- // Load user data and preferences- loadUserData();- loadPreferences();+ // Load user data and preferences with error handling+ try {+ loadUserData().catch(err => {+ console.error('Error loading user data:', err);+ // Continue with page initialization even if user data fails+ });++ loadPreferences();+ } catch (err) {+ console.error('Error during page initialization:', err);+ // Continue despite errors to allow basic functionality+ }- // Fix for settings button+ // Fix for settings button - not needed anymore as we've removed itif (settingsBtn) {console.log('Settings button found, adding event listener');settingsBtn.addEventListener('click', function(e) {@@ -171,7 +181,7 @@ function initPage() {}});} else {- console.error('Settings button not found');+ console.log('Settings button not found - this is expected after UI update');}console.log('Settings page initialization complete');@@ -294,11 +304,23 @@ async function loadUserData() {lastNameInput.value = userData.last_name || '';emailInput.value = userData.email || '';- // Check if user is admin and show admin section+ // Show admin section if user is adminif (userData.is_admin) {- adminSection.style.display = 'block';- loadUsers();- loadSiteSettings();+ if (adminSection) {+ adminSection.style.display = 'block';+ }++ // Only try to load admin data if the elements exist+ // This prevents errors when the admin elements don't exist in the DOM+ if (usersTableBody) {+ loadUsers();+ } else {+ console.log('Admin UI elements not found, skipping admin data loading');+ }++ if (registrationEnabled) {+ loadSiteSettings();+ }}// Update localStorage@@ -325,19 +347,32 @@ async function loadUserData() {function loadPreferences() {// Load dark mode preferenceconst darkMode = localStorage.getItem('darkMode') === 'true';- darkModeToggle.checked = darkMode;- darkModeToggleSetting.checked = darkMode;++ // Check if elements exist before setting properties+ if (darkModeToggleSetting) {+ darkModeToggleSetting.checked = darkMode;+ }++ // The darkModeToggle element doesn't exist in the page anymore+ // so we need to check before accessing it+ if (darkModeToggle) {+ darkModeToggle.checked = darkMode;+ }// Apply the theme immediatelysetTheme(darkMode);// Load default view preferenceconst defaultView = localStorage.getItem('defaultView') || 'grid';- defaultViewSelect.value = defaultView;+ if (defaultViewSelect) {+ defaultViewSelect.value = defaultView;+ }// Load email notifications preference (default to true if not set)const emailNotifications = localStorage.getItem('emailNotifications') !== 'false';- emailNotificationsToggle.checked = emailNotifications;+ if (emailNotificationsToggle) {+ emailNotificationsToggle.checked = emailNotifications;+ }// Load expiring soon days from APIfetch('/api/auth/preferences', {@@ -362,7 +397,7 @@ function loadPreferences() {function setupEventListeners() {console.log('Setting up event listeners');- // Dark mode toggle+ // Dark mode toggle in header (no longer exists)if (darkModeToggle) {darkModeToggle.addEventListener('change', function() {setTheme(this.checked);@@ -379,7 +414,7 @@ function setupEventListeners() {darkModeToggleSetting.addEventListener('change', function() {setTheme(this.checked);- // Also update the header toggle+ // Also update the header toggle if it existsif (darkModeToggle) {darkModeToggle.checked = this.checked;}@@ -556,6 +591,12 @@ function resetPasswordForm() {* @param {boolean} isDark - Whether to use dark mode*/function setTheme(isDark) {+ // Default to current theme if isDark is undefined+ if (isDark === undefined) {+ isDark = localStorage.getItem('darkMode') === 'true';+ }++ // Apply theme to documentdocument.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');// Also add/remove the dark-mode class on the body for additional styling@@ -565,7 +606,10 @@ function setTheme(isDark) {document.body.classList.remove('dark-mode');}+ // Save to localStoragelocalStorage.setItem('darkMode', isDark);++ console.log('Theme set to:', isDark ? 'dark' : 'light');}/**@@ -655,22 +699,29 @@ async function saveProfile() {* Save user preferences*/function savePreferences() {- // Save dark mode preference- const isDark = darkModeToggleSetting.checked;+ // Get preferences with null checks+ const isDark = darkModeToggleSetting && darkModeToggleSetting.checked;++ // Apply themesetTheme(isDark);- darkModeToggle.checked = isDark;- // Save default view preference- const defaultView = defaultViewSelect.value;+ // Update darkModeToggle if it exists+ if (darkModeToggle) {+ darkModeToggle.checked = isDark;+ }++ // Save default view preference with null check+ const defaultView = defaultViewSelect ? defaultViewSelect.value : 'grid';localStorage.setItem('defaultView', defaultView);localStorage.setItem('warrantyView', defaultView);- // Save email notifications preference- const emailNotifications = emailNotificationsToggle.checked;+ // Save email notifications preference with null check+ const emailNotifications = emailNotificationsToggle ? emailNotificationsToggle.checked : true;localStorage.setItem('emailNotifications', emailNotifications);- // Get expiring soon days value- let expiringSoonDays = parseInt(expiringSoonDaysInput.value);+ // Get expiring soon days value with null check+ const expiringSoonDaysValue = expiringSoonDaysInput ? expiringSoonDaysInput.value : '30';+ let expiringSoonDays = parseInt(expiringSoonDaysValue);// Validate expiring soon daysif (isNaN(expiringSoonDays) || expiringSoonDays < 1 || expiringSoonDays > 365) {@@ -899,7 +950,11 @@ function showToast(message, type = 'info', duration = 5000) {* Load users for admin*/async function loadUsers() {- if (!usersTableBody) return;+ // Exit if usersTableBody doesn't exist+ if (!usersTableBody) {+ console.log('usersTableBody element not found, skipping loadUsers');+ return;+ }showLoading();diff --git a/frontend/status.html b/frontend/status.htmlindex 021cd30..38f8bc8 100644--- a/frontend/status.html+++ b/frontend/status.html@@ -234,9 +234,6 @@<div id="userName" class="user-name">User Name</div><div id="userEmail" class="user-email">[email protected]</div></div>- <div class="user-menu-item" id="profileMenuItem">- <i class="fas fa-id-card"></i> Profile- </div><div class="user-menu-item"><a href="settings-new.html" style="color: inherit; text-decoration: none; display: block;"><i class="fas fa-cog"></i> Settingsdiff --git a/nginx.conf b/nginx.confindex 651a8cb..c1fa612 100644--- a/nginx.conf+++ b/nginx.conf@@ -11,6 +11,7 @@ server {# Global settingsgzip on;gzip_types text/plain text/css application/javascript application/json;+ client_max_body_size 32M;# Add CORS headers globallyadd_header 'Access-Control-Allow-Origin' '*';@@ -36,6 +37,7 @@ server {proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;+ client_max_body_size 32M;# Pass Authorization header to backendproxy_set_header Authorization $http_authorization;