🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
QOL, Mobile, Import
sassanix95a0d87c38c4
diff --git a/backend/app.py b/backend/app.pyindex 2fc1622..ab3f733 100644--- a/backend/app.py+++ b/backend/app.py@@ -22,6 +22,12 @@ from pytz import timezone as pytz_timezoneimport pytzimport threadingimport json+import csv # Added for CSV import+import io # Added for CSV import+try: # Added for CSV import date calculation+ from dateutil.relativedelta import relativedelta+except ImportError:+ relativedelta = Noneapp = Flask(__name__)CORS(app, supports_credentials=True) # Enable CORS with credentials@@ -355,6 +361,17 @@ def is_valid_timezone(tz):except pytz.exceptions.UnknownTimeZoneError:return False+def convert_decimals(obj):+ """Recursively convert Decimal objects to float in dicts/lists for JSON serialization."""+ if isinstance(obj, dict):+ return {k: convert_decimals(v) for k, v in obj.items()}+ elif isinstance(obj, list):+ return [convert_decimals(i) for i in obj]+ elif isinstance(obj, Decimal):+ return float(obj)+ else:+ return obj+# Authentication routes@app.route('/api/auth/register', methods=['POST'])def register():@@ -835,9 +852,9 @@ def add_warranty():if not request.form.get('warranty_years'):return jsonify({"error": "Warranty period (years) is required unless it's a lifetime warranty"}), 400try:- warranty_years = int(request.form.get('warranty_years'))- if warranty_years <= 0 or warranty_years > 100:- return jsonify({"error": "Warranty years must be between 1 and 100"}), 400+ warranty_years = float(request.form.get('warranty_years'))+ if warranty_years < 0.1 or warranty_years > 100:+ return jsonify({"error": "Warranty years must be between 0.1 and 100"}), 400except ValueError:return jsonify({"error": "Warranty years must be a valid number"}), 400@@ -1077,17 +1094,15 @@ def update_warranty(warranty_id):if not warranty_years_str:return jsonify({"error": "Warranty years is required for non-lifetime warranties"}), 400try:- warranty_years = int(warranty_years_str)- if warranty_years <= 0 or warranty_years > 100:- # Allow 0 years if is_lifetime is true? Let's keep validation strict for now.- return jsonify({"error": "Warranty years must be between 1 and 100 for non-lifetime warranties"}), 400+ warranty_years = float(warranty_years_str)+ if warranty_years < 0.1 or warranty_years > 100:+ return jsonify({"error": "Warranty years must be between 0.1 and 100 for non-lifetime warranties"}), 400# Calculate expiration date precisely if possible, otherwise approximatetry:from dateutil.relativedelta import relativedeltaexpiration_date = purchase_date + relativedelta(years=warranty_years)except ImportError:- # Fallback to approximation if dateutil is not availableexpiration_date = purchase_date + timedelta(days=warranty_years * 365)except ValueError:@@ -1386,16 +1401,48 @@ def get_statistics():recent_warranties.append(warranty)+ # *** ADD CODE TO FETCH ALL WARRANTIES ***+ logger.info(f"Fetching all warranties for user {user_id}...")+ cur.execute(f"""+ SELECT+ id, product_name, purchase_date, warranty_years,+ expiration_date, invoice_path, manual_path, product_url, purchase_price, is_lifetime+ {from_clause}+ {where_clause}+ ORDER BY expiration_date DESC+ """, params)++ all_columns = [desc[0] for desc in cur.description]+ all_warranties_list = []++ for row in cur.fetchall():+ warranty = dict(zip(all_columns, row))++ # Convert dates to string format+ if warranty.get('purchase_date') and isinstance(warranty['purchase_date'], date):+ warranty['purchase_date'] = warranty['purchase_date'].isoformat()+ if warranty.get('expiration_date') and isinstance(warranty['expiration_date'], date):+ warranty['expiration_date'] = warranty['expiration_date'].isoformat()++ # Convert Decimal objects to float for JSON serialization+ if warranty.get('purchase_price') and isinstance(warranty['purchase_price'], Decimal):+ warranty['purchase_price'] = float(warranty['purchase_price'])++ all_warranties_list.append(warranty)+ logger.info(f"Fetched {len(all_warranties_list)} total warranties.")+ # *** END OF ADDED CODE ***+statistics = {'total': total_count,'active': active_count,'expired': expired_count,'expiring_soon': expiring_soon_count,'timeline': timeline,- 'recent_warranties': recent_warranties+ 'recent_warranties': recent_warranties,+ 'all_warranties': all_warranties_list # <-- Add the new list here}- return jsonify(statistics)+ return jsonify(convert_decimals(statistics))except Exception as e:logger.error(f"Error getting warranty statistics: {e}")@@ -2417,13 +2464,13 @@ def format_expiration_email(user, warranties):text_body += "\\nLog in to Warracker to view details:\\n"text_body += f"{email_base_url}\\n\\n" # Use configurable base URLtext_body += "Manage your notification settings:\\n"- text_body += f"{email_base_url}/settings.html\\n" # Use configurable base URL+ text_body += f"{email_base_url}/settings-new.html\\n" # Use configurable base URLhtml_body += f"""\</tbody></table>- <p>Log in to <a href="{email_base_url}">Warracker</a> to view details.</p> # Use configurable base URL- <p>Manage your notification settings <a href="{email_base_url}/settings.html">here</a>.</p> # Use configurable base URL+ <p>Log in to <a href="{email_base_url}">Warracker</a> to view details.</p>+ <p>Manage your notification settings <a href="{email_base_url}/settings-new.html">here</a>.</p></body></html>"""@@ -3125,3 +3172,262 @@ def add_tags_to_warranty(warranty_id):finally:if conn:release_db_connection(conn)++# --- CSV Import Endpoint ---+EXPECTED_CSV_HEADERS = [+ 'ProductName', 'PurchaseDate', 'WarrantyYears', 'IsLifetime',+ 'PurchasePrice', 'SerialNumber', 'ProductURL'+]+# Add Tags as an optional header+OPTIONAL_CSV_HEADERS = ['WarrantyYears', 'IsLifetime', 'PurchasePrice', 'SerialNumber', 'ProductURL', 'Tags']+REQUIRED_CSV_HEADERS = ['ProductName', 'PurchaseDate']+[email protected]('/api/warranties/import', methods=['POST'])+@token_required+def import_warranties():+ if 'csv_file' not in request.files:+ return jsonify({"error": "No CSV file provided"}), 400++ file = request.files['csv_file']++ if file.filename == '':+ return jsonify({"error": "No selected file"}), 400++ if not file.filename.lower().endswith('.csv'):+ return jsonify({"error": "Invalid file type. Please upload a .csv file"}), 400++ user_id = request.user['id']+ conn = None+ imported_count = 0+ failed_rows = []+ row_number = 1 # Start from 1 for header++ try:+ # Read the file content+ stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)+ csv_reader = csv.DictReader(stream)++ # Validate headers+ headers = csv_reader.fieldnames+ # Check required headers first+ missing_required = [h for h in REQUIRED_CSV_HEADERS if h not in headers]+ if missing_required:+ return jsonify({"error": f"Missing required CSV columns: {', '.join(missing_required)}"}), 400++ # Check for unknown headers+ known_headers = set(REQUIRED_CSV_HEADERS + OPTIONAL_CSV_HEADERS)+ unknown_headers = [h for h in headers if h not in known_headers]+ if unknown_headers:+ logger.warning(f"CSV file contains unknown headers which will be ignored: {', '.join(unknown_headers)}")++ conn = get_db_connection()+ conn.autocommit = False # Start transaction++ with conn.cursor() as cur:+ for row in csv_reader:+ row_number += 1 # Increment for each data row (header is row 1)+ errors = []+ processed_row = {}++ try:+ # --- Data Extraction and Basic Validation ---+ product_name = row.get('ProductName', '').strip()+ purchase_date_str = row.get('PurchaseDate', '').strip()+ is_lifetime_str = row.get('IsLifetime', 'false').strip().lower()+ warranty_years_str = row.get('WarrantyYears', '').strip()+ purchase_price_str = row.get('PurchasePrice', '').strip()+ serial_numbers_str = row.get('SerialNumber', '').strip()+ product_url = row.get('ProductURL', '').strip()+ tags_str = row.get('Tags', '').strip() # Get Tags string++ if not product_name:+ errors.append("ProductName is required.")+ if not purchase_date_str:+ errors.append("PurchaseDate is required.")++ # --- Type/Format Validation ---+ try:+ purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d').date()+ except ValueError:+ errors.append("Invalid PurchaseDate format. Use YYYY-MM-DD.")+ purchase_date = None # Set to None to prevent further errors++ is_lifetime = is_lifetime_str == 'true'+ warranty_years = None+ expiration_date = None++ if not is_lifetime:+ if not warranty_years_str:+ errors.append("WarrantyYears is required unless IsLifetime is TRUE.")+ else:+ try:+ warranty_years = float(warranty_years_str)+ if warranty_years < 0.1 or warranty_years > 100:+ errors.append("WarrantyYears must be between 0.1 and 100.")+ except ValueError:+ errors.append("WarrantyYears must be a valid number.")++ purchase_price = None+ if purchase_price_str:+ try:+ purchase_price = float(purchase_price_str)+ if purchase_price < 0:+ errors.append("PurchasePrice cannot be negative.")+ except ValueError:+ errors.append("PurchasePrice must be a valid number.")++ # Calculate expiration date if valid+ if not errors and not is_lifetime and warranty_years and purchase_date:+ if relativedelta:+ expiration_date = purchase_date + relativedelta(years=warranty_years)+ else:+ expiration_date = purchase_date + timedelta(days=warranty_years * 365) # Approximate++ # Split serial numbers+ serial_numbers = [sn.strip() for sn in serial_numbers_str.split(',') if sn.strip()] if serial_numbers_str else []++ # --- Process Tags ---+ tag_ids_to_link = []+ if tags_str:+ tag_names = [name.strip() for name in tags_str.split(',') if name.strip()]+ if tag_names:+ # Find existing tag IDs (case-insensitive)+ placeholders = ', '.join(['%s'] * len(tag_names))+ sql = f"SELECT id, LOWER(name) FROM tags WHERE LOWER(name) IN ({placeholders})"+ cur.execute(sql, [name.lower() for name in tag_names])+ existing_tags = {name_lower: tag_id for tag_id, name_lower in cur.fetchall()}++ processed_tag_ids = []+ tags_to_create = []++ for name in tag_names:+ name_lower = name.lower()+ if name_lower in existing_tags:+ processed_tag_ids.append(existing_tags[name_lower])+ else:+ # Avoid queuing the same new tag multiple times within the same row+ if name_lower not in [t['name_lower'] for t in tags_to_create]:+ tags_to_create.append({'name': name, 'name_lower': name_lower})++ # Create tags that don't exist+ if tags_to_create:+ default_color = '#808080' # Default color for new tags+ for tag_data in tags_to_create:+ try:+ # Insert new tag with default color, preserving original case for name+ cur.execute(+ "INSERT INTO tags (name, color) VALUES (%s, %s) RETURNING id",+ (tag_data['name'], default_color)+ )+ new_tag_id = cur.fetchone()[0]+ processed_tag_ids.append(new_tag_id)+ logger.info(f"Created new tag '{(tag_data['name'])}' with ID {new_tag_id} during CSV import.")+ except Exception as tag_insert_err:+ # If tag creation fails (e.g., unique constraint conflict due to race condition), log and potentially add error+ logger.error(f"Error creating tag '{(tag_data['name'])}' during import: {tag_insert_err}")+ # Attempt to fetch the ID again in case it was created by another process+ cur.execute("SELECT id FROM tags WHERE LOWER(name) = %s", (tag_data['name_lower'],))+ existing_id_result = cur.fetchone()+ if existing_id_result:+ processed_tag_ids.append(existing_id_result[0])+ else:+ # Add error to the row if tag creation failed and wasn't found+ errors.append(f"Failed to create or find tag: {(tag_data['name'])}")++ # Consolidate tag IDs to link+ if processed_tag_ids:+ tag_ids_to_link = list(set(processed_tag_ids)) # Ensure unique IDs++ # Removed the skipped tags warning as we now create them+ # if skipped_tags:+ # errors.append(f"Skipped non-existent tags: {', '.join(skipped_tags)}.")++ # --- Check for Duplicates ---+ if not errors and product_name and purchase_date:+ cur.execute("""+ SELECT id FROM warranties+ WHERE user_id = %s AND product_name = %s AND purchase_date = %s+ """, (user_id, product_name, purchase_date))+ if cur.fetchone():+ errors.append("Duplicate warranty found (same product name and purchase date).")++ # --- If errors, skip row ---+ if errors:+ failed_rows.append({"row": row_number, "errors": errors})+ continue++ # --- Insert into Database ---+ cur.execute("""+ INSERT INTO warranties (+ product_name, purchase_date, warranty_years, expiration_date,+ product_url, purchase_price, user_id, is_lifetime+ )+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s)+ RETURNING id+ """, (+ product_name, purchase_date, warranty_years, expiration_date,+ product_url, purchase_price, user_id, is_lifetime+ ))+ warranty_id = cur.fetchone()[0]++ # Insert serial numbers+ if serial_numbers:+ for serial_number in serial_numbers:+ cur.execute("""+ INSERT INTO serial_numbers (warranty_id, serial_number)+ VALUES (%s, %s)+ """, (warranty_id, serial_number))++ # Link tags+ if tag_ids_to_link:+ for tag_id in tag_ids_to_link:+ cur.execute("""+ INSERT INTO warranty_tags (warranty_id, tag_id)+ VALUES (%s, %s)+ ON CONFLICT (warranty_id, tag_id) DO NOTHING -- Avoid errors if somehow duplicated+ """, (warranty_id, tag_id))++ imported_count += 1++ except Exception as e:+ logger.error(f"Error processing CSV row {row_number}: {e}")+ failed_rows.append({"row": row_number, "errors": [f"Internal processing error: {str(e)}"]})+ # Don't rollback yet, just record failure++ # --- Transaction Commit/Rollback ---+ if failed_rows:+ conn.rollback() # Rollback if any row failed during processing or insertion+ # Reset imported count if we rollback+ final_success_count = 0+ # Modify errors for rows that might have been initially valid but failed due to rollback+ final_failure_count = row_number - 1 # Total data rows processed+ # Add a general error message+ return jsonify({+ "error": "Import failed due to errors in one or more rows. No warranties were imported.",+ "success_count": 0,+ "failure_count": final_failure_count,+ "errors": failed_rows+ }), 400+ else:+ conn.commit() # Commit transaction if all rows were processed successfully+ final_success_count = imported_count+ final_failure_count = len(failed_rows)++ return jsonify({+ "message": "CSV processed.",+ "success_count": final_success_count,+ "failure_count": final_failure_count,+ "errors": failed_rows+ }), 200++ except Exception as e:+ if conn:+ conn.rollback() # Rollback on general error+ logger.error(f"Error importing CSV: {e}")+ return jsonify({"error": f"Failed to import CSV: {str(e)}"}), 500+ finally:+ if conn:+ conn.autocommit = True # Reset autocommit+ release_db_connection(conn)++# --- End CSV Import Endpoint ---diff --git a/backend/migrations/012_allow_fractional_warranty_years.sql b/backend/migrations/012_allow_fractional_warranty_years.sqlnew file mode 100644index 0000000..3ae21c6--- /dev/null+++ b/backend/migrations/012_allow_fractional_warranty_years.sql@@ -0,0 +1,10 @@+-- Migration: Change warranty_years to NUMERIC(5,2) to allow fractional years+DO $$+BEGIN+ IF EXISTS (+ SELECT 1 FROM information_schema.columns+ WHERE table_name = 'warranties' AND column_name = 'warranty_years' AND data_type = 'integer'+ ) THEN+ ALTER TABLE warranties ALTER COLUMN warranty_years TYPE NUMERIC(5,2) USING warranty_years::NUMERIC(5,2);+ END IF;+END $$;diff --git a/backend/migrations/013_add_updated_at_to_tags.sql b/backend/migrations/013_add_updated_at_to_tags.sqlnew file mode 100644index 0000000..74a7a15--- /dev/null+++ b/backend/migrations/013_add_updated_at_to_tags.sql@@ -0,0 +1,5 @@+-- 013_add_updated_at_to_tags.sql+-- Adds an updated_at column to the tags table for tracking updates++ALTER TABLE tags+ADD COLUMN updated_at TIMESTAMP DEFAULT NOW();diff --git a/frontend/about.html b/frontend/about.htmlindex c0b619f..4a943a4 100644--- a/frontend/about.html+++ b/frontend/about.html@@ -16,6 +16,8 @@<link rel="stylesheet" href="styles.css"> <!-- Additional styles --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> <!-- Font Awesome --><link rel="stylesheet" href="header-fix.css"> <!-- Header specific styles -->+ <!-- Mobile Header specific styles -->+ <link rel="stylesheet" href="mobile-header.css"><!-- Scripts loaded in head --><script src="theme-loader.js"></script> <!-- Apply theme early -->@@ -40,58 +42,41 @@</a><!-- Consider adding an 'active' class to an 'About' link if created here --></div>- <div id="authContainer" class="auth-buttons">- <a href="login.html" class="auth-btn login-btn">- <i class="fas fa-sign-in-alt"></i> Login- </a>- <a href="register.html" class="auth-btn register-btn">- <i class="fas fa-user-plus"></i> Register- </a>- </div>- <div id="userMenu" class="user-menu" style="display: none;">- <button id="userBtn" class="user-btn">- <i class="fas fa-user-circle"></i>- <span id="userDisplayName">User</span>- </button>- <div id="userMenuDropdown" class="user-menu-dropdown">- <div class="user-info">- <div id="userName" class="user-name">User Name</div>- <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: block;">- <i class="fas fa-cog"></i> Settings- </a>- </div>- <div class="user-menu-item">- <i class="fas fa-info-circle"></i>- <a href="about.html" style="text-decoration: none; color: inherit;">About</a>- </div>- <div class="user-menu-item" id="logoutMenuItem">- <i class="fas fa-sign-out-alt"></i> Logout- </div>+ <!-- Group for right-aligned elements -->+ <div class="header-right-group">+ <div id="authContainer" class="auth-buttons">+ <a href="login.html" class="auth-btn login-btn">+ <i class="fas fa-sign-in-alt"></i> Login+ </a>+ <a href="register.html" class="auth-btn register-btn">+ <i class="fas fa-user-plus"></i> Register+ </a></div>- </div>- <!-- Settings Toggle (Optional - Include if needed on About page) -->- <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 id="userMenu" class="user-menu" style="display: none;">+ <button id="userBtn" class="user-btn">+ <i class="fas fa-user-circle"></i>+ <span id="userDisplayName">User</span>+ </button>+ <div id="userMenuDropdown" class="user-menu-dropdown">+ <div class="user-info">+ <div id="userName" class="user-name">User Name</div>+ <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: block;">+ <i class="fas fa-cog"></i> Settings+ </a>+ </div>+ <div class="user-menu-item">+ <i class="fas fa-info-circle"></i>+ <a href="about.html" style="text-decoration: none; color: inherit;">About</a>+ </div>+ <div class="user-menu-item" id="logoutMenuItem">+ <i class="fas fa-sign-out-alt"></i> Logout+ </div></div></div>- </div>+ </div> <!-- End header-right-group --></div></header>@@ -103,7 +88,7 @@<div class="about-container" style="background-color: var(--card-bg); color: var(--text-color); padding: 20px; border-radius: 8px; margin-top: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); width: 100%; box-sizing: border-box;"><h1 style="color: var(--primary-color); margin-bottom: 20px;">About Warracker</h1>- <p><strong>Version:</strong> v0.9.9.1</p>+ <p><strong>Version:</strong> v0.9.9.2</p><p><strong>GitHub Repository:</strong>@@ -165,4 +150,4 @@</script></body>-</html>\ No newline at end of file+</html>\ No newline at end of filediff --git a/frontend/auth.js b/frontend/auth.jsindex 6311c6a..9a77dc7 100644--- a/frontend/auth.js+++ b/frontend/auth.js@@ -29,36 +29,69 @@ document.addEventListener('DOMContentLoaded', () => {checkAuthState();// Set up periodic check of auth state (every 30 seconds)- setInterval(checkAuthState, 30000);+ // setInterval(checkAuthState, 30000); // Consider if needed, can cause flicker- // User menu toggle- if (userBtn) {- userBtn.addEventListener('click', (e) => {- e.stopPropagation();+ // --- USER MENU TOGGLE ---+ const userMenuBtn = document.getElementById('userMenuBtn');+ const userMenuDropdown = document.getElementById('userMenuDropdown');+ console.log('auth.js: Checking for user menu elements...', { userMenuBtn, userMenuDropdown }); // Debug log+ if (userMenuBtn && userMenuDropdown) {+ console.log('auth.js: User menu elements found, adding listener.'); // Debug log+ userMenuBtn.addEventListener('click', (e) => {+ console.log('auth.js: User menu button CLICKED!'); // *** ADDED LOG ***+ e.stopPropagation();userMenuDropdown.classList.toggle('active');+ console.log('auth.js: User menu dropdown toggled.', { active: userMenuDropdown.classList.contains('active') }); // *** ADDED LOG ***});+ } else {+ console.log('auth.js: User menu button or dropdown not found on this page.'); // Debug log}- // Close user menu when clicking outside+ // --- SETTINGS GEAR MENU TOGGLE (Moved from settings-new.js) ---+ const settingsBtn = document.getElementById('settingsBtn'); // Gear icon button+ const settingsMenu = document.getElementById('settingsMenu'); // The dropdown menu itself+ console.log('auth.js: Checking for settings menu elements...', { settingsBtn, settingsMenu }); // Debug log+ if (settingsBtn && settingsMenu) {+ console.log('auth.js: Settings menu elements found, adding listeners.'); // Debug log+ // Toggle settings menu when settings button is clicked+ settingsBtn.addEventListener('click', function(e) {+ e.stopPropagation(); // Prevent click from closing menu immediately+ settingsMenu.classList.toggle('active');+ console.log('auth.js: Settings button clicked, menu toggled.', { active: settingsMenu.classList.contains('active') }); // Debug log+ });+ } else {+ console.log('auth.js: Settings button or menu not found on this page.'); // Debug log+ }+ // --- END SETTINGS GEAR MENU TOGGLE ---++ // Close menus when clicking outsidedocument.addEventListener('click', (e) => {- if (userMenuDropdown && userBtn && !userMenuDropdown.contains(e.target) && !userBtn.contains(e.target)) {+ // Close user menu+ if (userMenuDropdown && userMenuBtn &&+ userMenuDropdown.classList.contains('active') &&+ !userMenuDropdown.contains(e.target) &&+ !userMenuBtn.contains(e.target)) {userMenuDropdown.classList.remove('active');}+ // Close settings menu+ if (settingsMenu && settingsBtn &&+ settingsMenu.classList.contains('active') &&+ !settingsMenu.contains(e.target) &&+ !settingsBtn.contains(e.target)) {+ settingsMenu.classList.remove('active');+ console.log('auth.js: Click outside closed settings menu.'); // Debug log+ }});// Logout functionality+ const logoutMenuItem = document.getElementById('logoutMenuItem');if (logoutMenuItem) {logoutMenuItem.addEventListener('click', logout);}- // Profile menu item- if (profileMenuItem) {- profileMenuItem.addEventListener('click', () => {- // Redirect to profile page when implemented- // For now, just show a message- showToast('Profile page coming soon!', 'info');- });- }+ // Profile menu item link (assuming it's an <a> tag now)+ // const profileLink = document.querySelector('.user-menu-item a[href="settings-new.html"]');+ // No special listener needed if it's just a link});/**@@ -90,6 +123,13 @@ function checkAuthState() {function updateUIForAuthenticatedUser() {console.log('auth.js: Updating UI for authenticated user');+ // Log the user data being used+ console.log('auth.js: Current user data from state:', currentUser);+ if (!currentUser) {+ console.error('auth.js: Cannot update UI, currentUser is null or undefined.');+ return;+ }+// Hide login/register buttonsif (authContainer) {console.log('auth.js: Hiding authContainer');@@ -104,13 +144,19 @@ function updateUIForAuthenticatedUser() {userMenu.style.visibility = 'visible';}- // Update user info- if (currentUser) {- const displayName = currentUser.first_name || currentUser.username;- if (userDisplayName) userDisplayName.textContent = displayName;- if (userName) userName.textContent = `${currentUser.first_name || ''} ${currentUser.last_name || ''}`.trim() || currentUser.username;- if (userEmail) userEmail.textContent = currentUser.email;- }+ // Update user info in the header menu+ const displayName = currentUser.first_name || currentUser.username || 'User'; // Fallback added+ const fullName = `${currentUser.first_name || ''} ${currentUser.last_name || ''}`.trim() || currentUser.username || 'User Name'; // Fallback added+ const email = currentUser.email || '[email protected]'; // Fallback added++ // Log the values being set+ console.log(`auth.js: Setting display name (short): [${displayName}]`);+ console.log(`auth.js: Setting full name (menu): [${fullName}]`);+ console.log(`auth.js: Setting email (menu): [${email}]`);++ if (userDisplayName) userDisplayName.textContent = displayName;+ if (userName) userName.textContent = fullName;+ if (userEmail) userEmail.textContent = email;// Hide all login and register buttonsconst loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');diff --git a/frontend/fix-auth-buttons.js b/frontend/fix-auth-buttons.jsindex 7a64091..e55896d 100644--- a/frontend/fix-auth-buttons.js+++ b/frontend/fix-auth-buttons.js@@ -146,17 +146,46 @@ function updateAuthButtons() {}}+// --- USER MENU DROPDOWN UNIVERSAL FIX (IMPROVED) ---+function setupUserMenuDropdown() {+ const userMenuBtn = document.getElementById('userMenuBtn') || document.getElementById('userBtn');+ const userMenuDropdown = document.getElementById('userMenuDropdown');+ if (userMenuBtn && userMenuDropdown) {+ // Remove all previous click listeners by replacing the node+ const newBtn = userMenuBtn.cloneNode(true);+ userMenuBtn.parentNode.replaceChild(newBtn, userMenuBtn);+ newBtn.addEventListener('click', function(e) {+ e.stopPropagation();+ userMenuDropdown.classList.toggle('active');+ });+ // Only add one document-level listener+ if (!window._userMenuDropdownListenerAdded) {+ document.addEventListener('click', function(e) {+ if (userMenuDropdown.classList.contains('active') &&+ !userMenuDropdown.contains(e.target) &&+ !newBtn.contains(e.target)) {+ userMenuDropdown.classList.remove('active');+ }+ });+ window._userMenuDropdownListenerAdded = true;+ }+ }+}+// Run immediatelyconsole.log('Running updateAuthButtons immediately');updateAuthButtons();+setupUserMenuDropdown();// Update auth buttons when page loadsdocument.addEventListener('DOMContentLoaded', () => {console.log('DOMContentLoaded event triggered, updating auth buttons');updateAuthButtons();+ setupUserMenuDropdown();// Set up periodic check (every 2 seconds)setInterval(updateAuthButtons, 2000);+ setInterval(setupUserMenuDropdown, 2000);});// Update auth buttons when localStorage changes@@ -165,4 +194,4 @@ window.addEventListener('storage', (event) => {console.log('Auth data changed, updating auth buttons');updateAuthButtons();}-});\ No newline at end of file+});\ No newline at end of filediff --git a/frontend/header-fix.css b/frontend/header-fix.cssindex f039636..59a63f0 100644--- a/frontend/header-fix.css+++ b/frontend/header-fix.css@@ -32,6 +32,13 @@ header .container {color: var(--primary-color) !important;}+/* Group for right-aligned header elements */+.header-right-group {+ display: flex !important; /* Ensure horizontal layout */+ align-items: center !important; /* Align items vertically */+ gap: 10px !important; /* Add space between items */+}+/* Navigation Links */.nav-links {display: flex !important;diff --git a/frontend/index.html b/frontend/index.htmlindex efde320..b18a07d 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -29,131 +29,8 @@<link rel="stylesheet" href="header-fix.css"><!-- Load fix for auth buttons --><script src="fix-auth-buttons-loader.js"></script>- <style>- .user-menu {- position: relative;- margin-left: 15px;- }-- .user-btn {- background: none;- border: none;- color: var(--text-color);- cursor: pointer;- display: flex;- align-items: center;- font-size: 0.9rem;- padding: 5px 10px;- border-radius: 20px;- transition: background-color 0.3s;- }-- .user-btn:hover {- background-color: rgba(0, 0, 0, 0.05);- }-- .dark-mode .user-btn:hover {- background-color: rgba(255, 255, 255, 0.1);- }-- .user-btn i {- margin-right: 5px;- }-- .user-menu-dropdown {- position: absolute;- top: 100%;- right: 0;- background-color: var(--card-bg);- border-radius: 8px;- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);- width: 200px;- z-index: 1000;- display: none;- padding: 10px 0;- margin-top: 5px;- }-- .user-menu-dropdown.active {- display: block;- }-- .user-info {- padding: 10px 15px;- border-bottom: 1px solid var(--border-color);- margin-bottom: 5px;- }-- .user-name {- font-weight: bold;- margin-bottom: 5px;- }-- .user-email {- font-size: 0.8rem;- color: var(--text-muted);- word-break: break-all;- }-- .user-menu-item {- padding: 8px 15px;- cursor: pointer;- transition: background-color 0.3s;- display: flex;- align-items: center;- }-- .user-menu-item:hover {- background-color: var(--hover-bg);- }-- .user-menu-item i {- margin-right: 10px;- width: 16px;- text-align: center;- }-- .auth-buttons {- display: flex;- gap: 10px;- margin-left: 15px;- }-- .auth-btn {- padding: 5px 15px;- border-radius: 20px;- font-size: 0.9rem;- display: flex;- align-items: center;- justify-content: center;- cursor: pointer;- transition: all 0.3s ease;- }-- .auth-btn i {- margin-right: 5px;- }-- .login-btn {- background-color: transparent;- border: 1px solid var(--primary-color);- color: var(--primary-color);- }-- .login-btn:hover {- background-color: rgba(var(--primary-rgb), 0.1);- }-- .register-btn {- background-color: var(--primary-color);- border: 1px solid var(--primary-color);- color: white;- }-- .register-btn:hover {- background-color: var(--primary-dark);- }- </style>+ <!-- Mobile Header specific styles -->+ <link rel="stylesheet" href="mobile-header.css"><!-- Immediate authentication check script --><script>@@ -226,57 +103,41 @@<i class="fas fa-chart-pie"></i> Status</a></div>- <div id="authContainer" class="auth-buttons">- <a href="login.html" class="auth-btn login-btn">- <i class="fas fa-sign-in-alt"></i> Login- </a>- <a href="register.html" class="auth-btn register-btn">- <i class="fas fa-user-plus"></i> Register- </a>- </div>- <div id="userMenu" class="user-menu" style="display: none;">- <button id="userBtn" class="user-btn">- <i class="fas fa-user-circle"></i>- <span id="userDisplayName">User</span>- </button>- <div id="userMenuDropdown" class="user-menu-dropdown">- <div class="user-info">- <div id="userName" class="user-name">User Name</div>- <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: block;">- <i class="fas fa-cog"></i> Settings- </a>- </div>- <div class="user-menu-item">- <i class="fas fa-info-circle"></i>- <a href="about.html" style="text-decoration: none; color: inherit;">About</a>- </div>- <div class="user-menu-item" id="logoutMenuItem">- <i class="fas fa-sign-out-alt"></i> Logout- </div>+ <!-- Group for right-aligned elements -->+ <div class="header-right-group">+ <div id="authContainer" class="auth-buttons">+ <a href="login.html" class="auth-btn login-btn">+ <i class="fas fa-sign-in-alt"></i> Login+ </a>+ <a href="register.html" class="auth-btn register-btn">+ <i class="fas fa-user-plus"></i> Register+ </a></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 id="userMenu" class="user-menu" style="display: none;">+ <button id="userBtn" class="user-btn">+ <i class="fas fa-user-circle"></i>+ <span id="userDisplayName">User</span>+ </button>+ <div id="userMenuDropdown" class="user-menu-dropdown">+ <div class="user-info">+ <div id="userName" class="user-name">User Name</div>+ <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: block;">+ <i class="fas fa-cog"></i> Settings+ </a>+ </div>+ <div class="user-menu-item">+ <i class="fas fa-info-circle"></i>+ <a href="about.html" style="text-decoration: none; color: inherit;">About</a>+ </div>+ <div class="user-menu-item" id="logoutMenuItem">+ <i class="fas fa-sign-out-alt"></i> Logout+ </div></div></div>- </div>+ </div> <!-- End header-right-group --></div></header>@@ -314,6 +175,10 @@<button id="exportBtn" class="export-btn" title="Export warranties"><i class="fas fa-file-export"></i> Export</button>+ <button id="importBtn" class="import-btn" title="Import warranties from CSV">+ <i class="fas fa-file-import"></i> Import+ </button>+ <input type="file" id="csvFileInput" accept=".csv" style="display: none;"></div><div class="filter-options">@@ -395,19 +260,19 @@<div class="form-panel" style="box-shadow: none; padding: 0; background: none;"><!-- Form Tabs --><div class="form-tabs" data-step="0">- <div class="form-tab active" data-tab="product-info">+ <div class="form-tab active" data-tab="product-info" id="productInfoTabBtn"><i class="fas fa-box"></i> Product</div>- <div class="form-tab" data-tab="warranty-details">+ <div class="form-tab" data-tab="warranty-details" id="warrantyDetailsTabBtn"><i class="fas fa-shield-alt"></i> Warranty</div>- <div class="form-tab" data-tab="documents">+ <div class="form-tab" data-tab="documents" id="documentsTabBtn"><i class="fas fa-file-alt"></i> Documents</div>- <div class="form-tab" data-tab="tags">+ <div class="form-tab" data-tab="tags" id="tagsTabBtn"><i class="fas fa-tags"></i> Tags</div>- <div class="form-tab" data-tab="summary">+ <div class="form-tab" data-tab="summary" id="summaryTabBtn"><i class="fas fa-check-circle"></i> Summary</div></div>@@ -429,6 +294,7 @@<label>Serial Numbers</label><div id="serialNumbersContainer"><!-- Serial number inputs will be added dynamically -->+ <input type="text" name="serial_numbers[]" class="form-control" style="margin-bottom: 8px;" placeholder="Enter serial number"></div></div></div>@@ -450,7 +316,7 @@<div class="form-group" id="warrantyYearsGroup"><label for="warrantyYears">Warranty Period (Years)</label>- <input type="number" id="warrantyYears" name="warranty_years" class="form-control" min="1" max="100" required>+ <input type="number" id="warrantyYears" name="warranty_years" class="form-control" min="0.1" max="100" step="any" required></div><div class="form-group">@@ -529,7 +395,6 @@<span id="summary-serial-numbers" class="summary-value">-</span></div></div>-<div class="summary-section"><h4><i class="fas fa-shield-alt"></i> Warranty Details</h4><div class="summary-item">@@ -545,7 +410,6 @@<span id="summary-purchase-price" class="summary-value">-</span></div></div>-<div class="summary-section"><h4><i class="fas fa-file-alt"></i> Documents</h4><div class="summary-item">@@ -557,7 +421,6 @@<span id="summary-manual" class="summary-value">-</span></div></div>-<div class="summary-section"><h4><i class="fas fa-tags"></i> Tags</h4><div class="summary-item">@@ -566,17 +429,16 @@</div></div></div>-<div class="form-group">- <button type="submit" class="btn btn-primary">Add Warranty</button>+ <button type="submit" class="btn btn-primary" id="submitWarrantyBtn">Add Warranty</button></div></div><!-- Tab Navigation --><div class="tab-navigation">- <button type="button" class="btn btn-secondary prev-tab">+ <button type="button" class="btn btn-secondary prev-tab" id="prevTabBtn"><i class="fas fa-arrow-left"></i> Previous</button>- <button type="button" class="btn btn-primary next-tab">+ <button type="button" class="btn btn-primary next-tab" id="nextTabBtn">Next <i class="fas fa-arrow-right"></i></button></div>@@ -657,7 +519,7 @@<div class="form-group" id="editWarrantyYearsGroup"><label for="editWarrantyYears">Warranty Period (Years)</label>- <input type="number" id="editWarrantyYears" name="warranty_years" class="form-control" min="1" max="100" required>+ <input type="number" id="editWarrantyYears" name="warranty_years" class="form-control" min="0.1" max="100" step="any" required></div><div class="form-group">diff --git a/frontend/mobile-header.css b/frontend/mobile-header.cssnew file mode 100644index 0000000..bc4e3f7--- /dev/null+++ b/frontend/mobile-header.css@@ -0,0 +1,54 @@+@media (max-width: 768px) {+ /* Header Responsive Styles */+ header .container {+ flex-wrap: wrap !important; /* Allow header items to wrap */+ justify-content: space-between !important; /* Push title left, right-group right */+ align-items: center !important; /* Vertically align items in the top row */+ gap: 10px 15px !important; /* Add space between wrapped items */+ padding: 10px 15px !important; /* Adjust padding */+ }++ header .app-title {+ /* flex-basis: 100%; Remove - allow sharing row */+ text-align: left !important; /* Align title text left */+ margin-bottom: 0 !important; /* Remove bottom margin */+ }++ header .app-title h1 {+ font-size: 1.8rem !important; /* Slightly reduce title size */+ margin: 0 auto !important; /* Center title text if needed */+ }++ header .app-title i {+ font-size: 1.6rem !important; /* Slightly reduce icon size */+ margin-right: 10px !important;+ /* display: none; /* Optionally hide icon on very small screens */+ }++ /* Group user/settings/auth buttons together */+ .header-right-group {+ display: flex !important;+ align-items: center !important;+ justify-content: flex-end !important; /* Keep content aligned right within the group */+ /* flex-basis: 100%; Remove - allow sharing row */+ flex-wrap: nowrap !important;+ gap: 10px !important;+ }++ header .nav-links {+ order: 3 !important; /* Ensure nav links are last */+ flex-basis: 100% !important; /* Make nav links take full width */+ justify-content: center !important; /* Center nav links */+ margin: 10px 0 0 0 !important;+ padding-bottom: 5px !important;+ gap: 15px !important;+ }++ /* Override specific margins from header-fix.css */+ header .auth-buttons,+ header .user-menu,+ header .settings-container {+ margin: 0 5px !important; /* Override margin-left from header-fix.css */+ flex-shrink: 0 !important; /* Prevent shrinking */+ }+}\ No newline at end of filediff --git a/frontend/script.js b/frontend/script.jsindex 57bcada..5ecf0d0 100644--- a/frontend/script.js+++ b/frontend/script.js@@ -1,7 +1,7 @@// Global variableslet warranties = [];let currentTabIndex = 0;-let tabContents;+let tabContents = []; // Initialize as empty arraylet editMode = false;let currentWarrantyId = null;let currentFilters = {@@ -46,6 +46,14 @@ const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');const loadingContainer = document.getElementById('loadingContainer');const toastContainer = document.getElementById('toastContainer');+// CSV Import Elements+const importBtn = document.getElementById('importBtn');+const csvFileInput = document.getElementById('csvFileInput');+if (importBtn) {+ importBtn.classList.remove('import-btn');+ importBtn.classList.add('export-btn');+}+// Tag DOM Elementsconst selectedTagsContainer = document.getElementById('selectedTags');const tagSearch = document.getElementById('tagSearch');@@ -89,43 +97,79 @@ function getPreferenceKeyPrefix() {return getUserType() === 'admin' ? 'admin_' : 'user_';}-// Theme Management+// Theme Management - Simplifiedfunction setTheme(isDark) {- // Get the appropriate key prefix based on user type- const prefix = getPreferenceKeyPrefix();- console.log(`Setting theme with prefix: ${prefix}`);+ const theme = isDark ? 'dark' : 'light';+ console.log('Setting theme to:', theme);- document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');+ // 1. Apply theme attribute to document root+ document.documentElement.setAttribute('data-theme', theme);++ // 2. Save the single source of truth to localStorage+ localStorage.setItem('darkMode', isDark);- // Update darkMode settings- localStorage.setItem(`${prefix}darkMode`, isDark);- localStorage.setItem('darkMode', isDark); // Keep for backward compatibility+ // Update toggle state if the toggle exists on this page (e.g., in the header)+ const headerToggle = document.getElementById('darkModeToggle');+ if (headerToggle) {+ headerToggle.checked = isDark;+ }+}++// Initialization logic on DOMContentLoaded+document.addEventListener('DOMContentLoaded', function() {+ // ... other initialization ...++ // REMOVE call to undefined checkLoginStatus - Handled by auth.js+ // checkLoginStatus();- // Update DOM- if (isDark) {- document.body.classList.add('dark-mode');- } else {- document.body.classList.remove('dark-mode');+ // Load warranties (assuming warrantiesList exists on this page)+ if (document.getElementById('warrantiesList')) {+ loadWarranties();+ }++ // Setup form submission (assuming addWarrantyForm exists)+ const form = document.getElementById('addWarrantyForm');+ if (form) {+ form.addEventListener('submit', handleFormSubmit);+ // Initialize form tabs if the form exists+ initFormTabs();+ }++ // REMOVED setupSettingsMenu - Handled by auth.js+ // setupSettingsMenu();++ // Initialize theme toggle state *after* DOM is loaded+ // ... (theme toggle init logic) ...++ // Setup view switcher (assuming view switcher elements exist)+ if (document.getElementById('gridViewBtn')) {+ // setupViewSwitcher(); // Removed undefined function+ loadViewPreference();}- // Set toggle state- if (darkModeToggle) {- darkModeToggle.checked = isDark;+ // Setup filter controls (assuming filter controls exist)+ if (document.getElementById('filterControls')) {+ // setupFilterControls(); // Removed: function not defined+ populateTagFilter();}++ // Initialize modal interactions+ // initializeModals(); // Removed: function not defined, handled by setupModalTriggers+ setupModalTriggers();- // Also update preferences in localStorage for consistency- try {- let userPrefs = {};- const storedPrefs = localStorage.getItem(`${prefix}preferences`);- if (storedPrefs) {- userPrefs = JSON.parse(storedPrefs);- }- userPrefs.theme = isDark ? 'dark' : 'light';- localStorage.setItem(`${prefix}preferences`, JSON.stringify(userPrefs));- } catch (e) {- console.error(`Error updating theme in ${prefix}preferences:`, e);+ // Initialize Tag functionality (assuming tag elements exist)+ if (document.getElementById('tagSearchInput')) {+ initTagFunctionality();+ loadTags();}-}++ // Initialize form-specific lifetime checkbox handler+ const lifetimeCheckbox = document.getElementById('isLifetime');+ if (lifetimeCheckbox) {+ lifetimeCheckbox.addEventListener('change', handleLifetimeChange);+ handleLifetimeChange({ target: lifetimeCheckbox }); // Initial check+ }+});// Initialize theme based on user preference or system preferencefunction initializeTheme() {@@ -155,9 +199,6 @@ function initializeTheme() {setTheme(prefersDarkMode);}-// Initialize theme when page loads-initializeTheme();-// Variableslet currentView = 'grid'; // Default viewlet expiringSoonDays = 30; // Default value, will be updated from user preferences@@ -165,64 +206,136 @@ let expiringSoonDays = 30; // Default value, will be updated from user preferenc// API URLconst API_URL = '/api/warranties';-// Form tab navigation variables-// Ensure these elements exist before trying to select them-const formTabsElements = document.querySelectorAll('.form-tab');-const formTabs = formTabsElements ? Array.from(formTabsElements) : [];-const tabContentsElements = document.querySelectorAll('.tab-content');-tabContents = tabContentsElements ? Array.from(tabContentsElements) : [];-const nextButton = document.querySelector('.next-tab');-const prevButton = document.querySelector('.prev-tab');+// Form tab navigation variables (simplified)+let formTabs = []; // Changed from const to let, initialized as empty+// Removed const formTabsElements = document.querySelectorAll('.form-tab');+// Removed const formTabs = formTabsElements ? Array.from(formTabsElements) : [];+// Removed const tabContentsElements = document.querySelectorAll('.tab-content');+// Removed tabContents assignment here++const nextButton = document.querySelector('.next-tab'); // Keep these if needed globally, otherwise might remove+const prevButton = document.querySelector('.prev-tab'); // Keep these if needed globally, otherwise might remove// --- Add near other DOM Element declarations ----const serialNumbersContainer = document.getElementById('serialNumbersContainer'); // Keep this line+// ... existing code ...// Initialize form tabsfunction initFormTabs() {console.log('Initializing form tabs...');-- // Hide the submit button initially- const submitButton = document.querySelector('button[type="submit"]');- if (submitButton) {- submitButton.style.display = 'none';+ // Use the modal context if available, otherwise query document+ const modalContext = document.getElementById('addWarrantyModal'); // Assuming this is the context+ const context = modalContext && modalContext.classList.contains('active') ? modalContext : document;++ const tabsContainer = context.querySelector('.form-tabs');+ // Re-query tabContents and formTabs within the correct context and update global variables+ const contentsElements = context.querySelectorAll('.tab-content');+ tabContents = contentsElements ? Array.from(contentsElements) : []; // Update global variable++ const tabsElements = tabsContainer ? tabsContainer.querySelectorAll('.form-tab') : [];+ formTabs = tabsElements ? Array.from(tabsElements) : []; // Update global variable++ const nextButton = context.querySelector('#nextTabBtn'); // Use context+ const prevButton = context.querySelector('#prevTabBtn'); // Use context+ const submitButton = context.querySelector('#submitWarrantyBtn'); // Use context++ // Use the updated global variables length for checks+ if (!tabsContainer || !tabContents.length || !formTabs.length || !nextButton || !prevButton || !submitButton) {+ console.warn('Form tab elements not found in the expected context. Skipping tab initialization.');+ return; // Don't proceed if elements aren't present}-- // Show/hide navigation buttons based on current tab- updateNavigationButtons();-- // Remove any existing event listeners before adding new ones++ // Remove the local 'tabs' and 'contents' variables, use global ones now+ // let currentTabIndex = 0; // Already global+ // const tabs = tabsContainer.querySelectorAll('.form-tab'); // Use global formTabs+ // const contents = document.querySelectorAll('.tab-content'); // Use global tabContents++ // Remove the inner switchToTab and updateNavigationButtons functions as they are defined globally+ /*+ function switchToTab(index) {+ // ... removed inner function ...+ }++ function updateNavigationButtons() {+ // ... removed inner function ...+ }+ */++ // --- CLONE AND REPLACE NAV BUTTONS TO REMOVE OLD LISTENERS ---+ // Ensure buttons exist before cloning+ let nextButtonCloned = nextButton;+ let prevButtonCloned = prevButton;if (nextButton && prevButton) {- const nextTabClone = nextButton.cloneNode(true);- const prevTabClone = prevButton.cloneNode(true);-- nextButton.parentNode.replaceChild(nextTabClone, nextButton);- prevButton.parentNode.replaceChild(prevTabClone, prevButton);-- // Add event listeners for tab navigation- document.querySelector('.next-tab').addEventListener('click', () => {- console.log('Next button clicked, current tab:', currentTabIndex);+ nextButtonCloned = nextButton.cloneNode(true);+ prevButtonCloned = prevButton.cloneNode(true);+ nextButton.parentNode.replaceChild(nextButtonCloned, nextButton);+ prevButton.parentNode.replaceChild(prevButtonCloned, prevButton);+ } else {+ console.warn("Next/Prev buttons not found for cloning listeners.");+ }+++ // ... (rest of initFormTabs, including event listeners, ensure element checks)+ // Make sure event listeners use the correct global functions and variables+ formTabs.forEach((tab, index) => { // Use global formTabs+ if (tab) { // Check if tab exists+ tab.addEventListener('click', () => {+ // Allow clicking only on previous tabs if valid, or current+ if (index < currentTabIndex) {+ let canSwitch = true;+ for (let i = 0; i < index; i++) {+ // Ensure validateTab uses the correct global tabContents+ if (!validateTab(i)) {+ canSwitch = false;+ break;+ }+ }+ if (canSwitch) switchToTab(index); // Call global function+ } else if (index === currentTabIndex) {+ // Clicking current tab does nothing+ } else {+ // Try to navigate forward by clicking tab+ // Ensure validateTab uses the correct global tabContents+ if (validateTab(currentTabIndex)) {+ // Mark current as completed+ if(formTabs[currentTabIndex]) formTabs[currentTabIndex].classList.add('completed'); // Use global formTabs+ switchToTab(index); // Call global function+ } else {+ // If current tab is invalid, show errors for it+ showValidationErrors(currentTabIndex);+ }+ }+ });+ }+ });++ if (nextButtonCloned) { // Check button exists+ nextButtonCloned.addEventListener('click', () => {+ // Ensure validateTab uses the correct global tabContentsif (validateTab(currentTabIndex)) {- switchToTab(currentTabIndex + 1);+ if (formTabs[currentTabIndex]) formTabs[currentTabIndex].classList.add('completed'); // Use global formTabs+ // Use global formTabs length+ if (currentTabIndex < formTabs.length - 1) { // <-- Ensure this uses formTabs.length+ switchToTab(currentTabIndex + 1); // Call global function+ }} else {+ // If current tab is invalid, show errorsshowValidationErrors(currentTabIndex);}});-- document.querySelector('.prev-tab').addEventListener('click', () => {- console.log('Previous button clicked, current tab:', currentTabIndex);- switchToTab(currentTabIndex - 1);- });+ } else {+ console.warn("Cloned Next button not found, listener not added.");}-- // 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);++ if (prevButtonCloned) { // Check button exists+ prevButtonCloned.addEventListener('click', () => {+ if (currentTabIndex > 0) {+ switchToTab(currentTabIndex - 1);}});- });+ }++ // Initialize the first tab+ switchToTab(0);}// Switch to a specific tab@@ -235,6 +348,11 @@ function switchToTab(index) {return;}+ // Update summary FIRST if switching TO the summary tab+ if (index === formTabs.length - 1) {+ updateSummary();+ }+// Update active tabformTabs.forEach(tab => tab.classList.remove('active'));tabContents.forEach(content => content.classList.remove('active'));@@ -253,11 +371,6 @@ function switchToTab(index) {// Update navigation buttonsupdateNavigationButtons();-- // Update summary if on summary tab- if (index === formTabs.length - 1) {- updateSummary();- }}// Update navigation buttons based on current tab@@ -389,7 +502,8 @@ function updateSummary() {if (isLifetime) {summaryWarrantyYears.textContent = 'Lifetime';} else if (warrantyYears) {- summaryWarrantyYears.textContent = `${warrantyYears} ${parseInt(warrantyYears) === 1 ? 'year' : 'years'}`;+ const yearsNum = parseFloat(warrantyYears);+ summaryWarrantyYears.textContent = `${yearsNum} ${yearsNum === 1 ? 'year' : 'years'}`;} else {summaryWarrantyYears.textContent = '-';}@@ -399,8 +513,14 @@ function updateSummary() {const summaryExpirationDate = document.getElementById('summary-expiration-date');if (summaryExpirationDate && purchaseDate && warrantyYears) {const expirationDate = new Date(purchaseDate);- expirationDate.setFullYear(expirationDate.getFullYear() + parseInt(warrantyYears));- summaryExpirationDate.textContent = expirationDate.toLocaleDateString();+ const yearsNum = parseFloat(warrantyYears);+ if (!isNaN(yearsNum)) {+ expirationDate.setFullYear(expirationDate.getFullYear() + Math.floor(yearsNum));+ expirationDate.setMonth(expirationDate.getMonth() + Math.round((yearsNum % 1) * 12));+ summaryExpirationDate.textContent = expirationDate.toLocaleDateString();+ } else {+ summaryExpirationDate.textContent = '-';+ }} else if (summaryExpirationDate) {summaryExpirationDate.textContent = '-';}@@ -576,8 +696,12 @@ function switchView(viewType) {// Get the appropriate key prefix based on user typeconst prefix = getPreferenceKeyPrefix();- localStorage.setItem(`${prefix}viewPreference`, viewType);- localStorage.setItem('viewPreference', viewType); // Keep for backward compatibility+ // --- BEGIN EDIT: Save to all relevant keys ---+ localStorage.setItem(`${prefix}viewPreference`, viewType); // Keep this one+ localStorage.setItem(`${prefix}defaultView`, viewType); // Add for consistency with settings load priority+ localStorage.setItem(`${prefix}warrantyView`, viewType); // Add for consistency with settings legacy save+ localStorage.setItem('viewPreference', viewType); // Keep general key+ // --- END EDIT ---// Make sure warrantiesList exists before modifying classesif (warrantiesList) {@@ -612,17 +736,29 @@ function switchView(viewType) {function loadViewPreference() {// Get the appropriate key prefix based on user typeconst prefix = getPreferenceKeyPrefix();- let savedView = localStorage.getItem(`${prefix}viewPreference`);-- // Fallback to global preference if user-specific one isn't found- if (!savedView) {- savedView = localStorage.getItem('viewPreference');+ let savedView = null;++ // --- BEGIN EDIT: Check keys in priority order ---+ const userSpecificView = localStorage.getItem(`${prefix}defaultView`);+ const generalView = localStorage.getItem('viewPreference');+ const legacyWarrantyView = localStorage.getItem(`${prefix}warrantyView`);++ if (userSpecificView) {+ savedView = userSpecificView;+ console.log(`Loaded view preference from ${prefix}defaultView:`, savedView);+ } else if (generalView) {+ savedView = generalView;+ console.log('Loaded view preference from viewPreference:', savedView);+ } else if (legacyWarrantyView) {+ savedView = legacyWarrantyView;+ console.log(`Loaded view preference from legacy ${prefix}warrantyView:`, savedView);}-+ // --- END EDIT ---+// Default to grid view if no preference is savedsavedView = savedView || 'grid';-- console.log(`Found global view preference: ${savedView}`);++ console.log(`Applying view preference: ${savedView}`);// Switch view only if view buttons exist (implying it's the main page)if (gridViewBtn || listViewBtn || tableViewBtn) {switchView(savedView);@@ -1114,7 +1250,7 @@ async function renderWarranties(warrantiesToRender) {<div class="document-links-row">${warranty.product_url ? `<a href="${warranty.product_url}" class="product-link" target="_blank">- <i class="fas fa-globe"></i> Product Website+ <i class="fas fa-globe"></i></a>` : ''}${warranty.invoice_path && warranty.invoice_path !== 'null' ? `@@ -1159,11 +1295,11 @@ async function renderWarranties(warrantiesToRender) {` : ''}${warranty.invoice_path && warranty.invoice_path !== 'null' ? `<a href="#" onclick="openSecureFile('${warranty.invoice_path}'); return false;" class="invoice-link">- <i class="fas fa-file-invoice"></i>+ <i class="fas fa-file-invoice"></i> Invoice</a>` : ''}${warranty.manual_path && warranty.manual_path !== 'null' ? `<a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;" class="manual-link">- <i class="fas fa-book"></i>+ <i class="fas fa-book"></i> Manual</a>` : ''}</div>${tagsHtml}@@ -1541,8 +1677,8 @@ function submitForm(event) {event.preventDefault();// --- Add Lifetime Check ---- if (!isLifetimeCheckbox.checked && !warrantyYearsInput.value) {- showToast('Warranty period (years) is required unless it\'s a lifetime warranty', 'error');+ if (!isLifetimeCheckbox.checked && (!warrantyYearsInput.value || parseFloat(warrantyYearsInput.value) <= 0)) {+ showToast('Warranty period (years) is required and must be greater than 0 unless it\'s a lifetime warranty', 'error');switchToTab(1); // Switch to warranty details tabwarrantyYearsInput.focus();warrantyYearsInput.classList.add('invalid');@@ -1640,6 +1776,50 @@ document.addEventListener('DOMContentLoaded', function() {// Set up event listeners for other UI controls (should contain checks)setupUIEventListeners();setupModalTriggers(); // Add the new modal listeners++ // Check if user is logged in and update UI+ // checkLoginStatus(); // Removed undefined function++ // Setup form submission+ const form = document.getElementById('addWarrantyForm');+ if (form) {+ form.addEventListener('submit', handleFormSubmit);+ }++ // Setup settings menu toggle+ // setupSettingsMenu(); // Removed: function not defined, handled by auth.js++ // Initialize theme toggle state *after* DOM is loaded+ // Find the header toggle (assuming ID 'darkModeToggle')+ const headerToggle = document.getElementById('darkModeToggle');+ if (headerToggle) {+ // Set initial state based on theme applied by theme-loader.js+ const currentTheme = document.documentElement.getAttribute('data-theme');+ headerToggle.checked = currentTheme === 'dark';++ // Add listener to update theme when toggled+ headerToggle.addEventListener('change', function() {+ setTheme(this.checked);+ });+ }++ // REMOVE any direct calls to initializeTheme() from here or globally+ // initializeTheme();++ // Setup view switcher+ // setupViewSwitcher(); // Removed undefined function++ // Setup filter controls+ // setupFilterControls(); // Removed: function not defined++ // Setup form tabs and navigation+ // initFormTabs(); // <-- Remove this line from DOMContentLoaded++ // Initialize modal interactions+ // initializeModals(); // Removed: function not defined, handled by setupModalTriggers++ // Load preferences (if needed for things other than theme)+ // loadPreferences(); // Consider if needed});// Add this function to handle edit tab functionality@@ -1899,7 +2079,12 @@ function renderTagsList(searchTerm = '') {createOption.className = 'tag-option create-tag';createOption.innerHTML = `<i class="fas fa-plus"></i> Create "${searchTerm}"`;createOption.addEventListener('click', () => {- createTag(searchTerm);+ createTag(searchTerm).then(newTag => {+ // Add the new tag to selectedTags+ selectedTags.push(newTag);+ renderSelectedTags();+ renderTagsList(''); // Clear search and refresh list+ });tagsList.classList.remove('show');});tagsList.appendChild(createOption);@@ -1943,6 +2128,71 @@ function renderTagsList(searchTerm = '') {tagsList.classList.add('show');}+// Update renderEditTagsList to add new tag to editSelectedTags after creation+function renderEditTagsList(searchTerm = '') {+ const editTagsList = document.getElementById('editTagsList');+ if (!editTagsList) return;+ editTagsList.innerHTML = '';+ // Filter tags based on search term+ const filteredTags = allTags.filter(tag =>+ !searchTerm || tag.name.toLowerCase().includes(searchTerm.toLowerCase())+ );+ // Add option to create new tag if search term is provided and not in list+ if (searchTerm && !filteredTags.some(tag => tag.name.toLowerCase() === searchTerm.toLowerCase())) {+ const createOption = document.createElement('div');+ createOption.className = 'tag-option create-tag';+ createOption.innerHTML = `<i class="fas fa-plus"></i> Create "${searchTerm}"`;+ createOption.addEventListener('click', () => {+ createTag(searchTerm).then(newTag => {+ // Add the new tag to editSelectedTags+ editSelectedTags.push(newTag);+ renderEditSelectedTags();+ renderEditTagsList(''); // Clear search and refresh list+ });+ editTagsList.classList.remove('show');+ });+ editTagsList.appendChild(createOption);+ }+ // Add existing tags to dropdown+ filteredTags.forEach(tag => {+ const option = document.createElement('div');+ option.className = 'tag-option';++ // Check if tag is already selected+ const isSelected = editSelectedTags.some(selected => selected.id === tag.id);++ option.innerHTML = `+ <span class="tag-color" style="background-color: ${tag.color}"></span>+ ${tag.name}+ <span class="tag-status">${isSelected ? '<i class="fas fa-check"></i>' : ''}</span>+ `;++ option.addEventListener('click', () => {+ if (isSelected) {+ // Remove tag if already selected+ editSelectedTags = editSelectedTags.filter(selected => selected.id !== tag.id);+ } else {+ // Add tag if not selected+ editSelectedTags.push({+ id: tag.id,+ name: tag.name,+ color: tag.color+ });+ }++ // Use our helper function to render selected tags+ renderEditSelectedTags();++ renderEditTagsList(searchTerm);+ });++ editTagsList.appendChild(option);+ });++ // Show the dropdown+ editTagsList.classList.add('show');+}+// Render the selected tagsfunction renderSelectedTags() {if (!selectedTagsContainer) return;@@ -1984,58 +2234,104 @@ function renderSelectedTags() {});}-// Create a new tag-function createTag(name) {- const token = localStorage.getItem('auth_token');- if (!token) {- console.error('No authentication token found');- return;- }+// Helper function to render the edit selected tags+function renderEditSelectedTags() {+ const editSelectedTagsContainer = document.getElementById('editSelectedTags');+ if (!editSelectedTagsContainer) return;- // Generate a random color for the tag- const color = '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');+ editSelectedTagsContainer.innerHTML = '';- fetch('/api/tags', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'Authorization': 'Bearer ' + token- },- body: JSON.stringify({- name: name,- color: color- })- })- .then(response => {- if (!response.ok) {- throw new Error('Failed to create tag');- }- return response.json();- })- .then(data => {- // Add new tag to allTags array- allTags.push({- id: data.id,- name: data.name,- color: data.color+ if (editSelectedTags.length > 0) {+ editSelectedTags.forEach(tag => {+ const tagElement = document.createElement('span');+ tagElement.className = 'tag';+ tagElement.style.backgroundColor = tag.color;+ tagElement.style.color = getContrastColor(tag.color);++ tagElement.innerHTML = `+ ${tag.name}+ <span class="remove-tag" data-id="${tag.id}">×</span>+ `;++ // Add event listener for removing tag+ const removeButton = tagElement.querySelector('.remove-tag');+ removeButton.addEventListener('click', (e) => {+ e.stopPropagation();+ e.preventDefault(); // Add this to prevent default action++ // Prevent the event from bubbling up to parent elements+ if (e.cancelBubble !== undefined) {+ e.cancelBubble = true;+ }++ editSelectedTags = editSelectedTags.filter(t => t.id !== tag.id);++ // Re-render just the tags+ renderEditSelectedTags();+ return false; // Add return false for older browsers+ });++ editSelectedTagsContainer.appendChild(tagElement);});-- // Select the new tag- selectedTags.push({- id: data.id,- name: data.name,- color: data.color+ } else {+ const placeholder = document.createElement('span');+ placeholder.className = 'no-tags-selected';+ placeholder.textContent = 'No tags selected';+ editSelectedTagsContainer.appendChild(placeholder);+ }+}++// Update createTag to return a Promise+function createTag(name) {+ return new Promise((resolve, reject) => {+ const token = localStorage.getItem('auth_token');+ if (!token) {+ console.error('No authentication token found');+ reject(new Error('No authentication token found'));+ return;+ }+ // Generate a random color for the tag+ const color = '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');+ fetch('/api/tags', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'Authorization': 'Bearer ' + token+ },+ body: JSON.stringify({+ name: name,+ color: color+ })+ })+ .then(response => {+ if (!response.ok) {+ if (response.status === 409) {+ reject(new Error('A tag with this name already exists'));+ return;+ }+ reject(new Error('Failed to create tag'));+ return;+ }+ return response.json();+ })+ .then(data => {+ if (!data) return;+ const newTag = {+ id: data.id,+ name: data.name,+ color: data.color+ };+ allTags.push(newTag);+ renderExistingTags();+ populateTagFilter();+ showToast('Tag created successfully', 'success');+ resolve(newTag);+ })+ .catch(error => {+ console.error('Error creating tag:', error);+ showToast(error.message || 'Failed to create tag', 'error');+ reject(error);});-- // Clear search and rerender- if (tagSearch) tagSearch.value = '';- renderSelectedTags();-- showToast('Tag created successfully', 'success');- })- .catch(error => {- console.error('Error creating tag:', error);- showToast(error.message || 'Failed to create tag', 'error');});}@@ -2279,38 +2575,44 @@ function deleteTag(id) {// Set up event listeners for UI controlsfunction setupUIEventListeners() {- // Initialize settings button- const settingsBtn = document.querySelector('.settings-btn');- const settingsMenu = document.querySelector('.settings-menu');-- 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');- }- });- }-// Initialize edit tabsinitEditTabs();// Close modals when clicking outside or on close buttondocument.querySelectorAll('.modal-backdrop, [data-dismiss="modal"]').forEach(element => {element.addEventListener('click', (e) => {- if (e.target === element) {- closeModals();+ // Check if the click is on the backdrop itself OR a dismiss button+ if (e.target === element || e.target.matches('[data-dismiss="modal"]')) {+ // Find the closest modal backdrop to the element clicked+ const modalToClose = e.target.closest('.modal-backdrop');++ if (modalToClose) {+ // *** MODIFIED CHECK ***+ // If the click target is the backdrop itself (not a dismiss button)+ // AND the modal is the 'addWarrantyModal', then DO NOTHING.+ if (modalToClose.id === 'addWarrantyModal' && e.target === modalToClose) {+ return; // Ignore backdrop click for addWarrantyModal+ }+ // *** END MODIFIED CHECK ***++ // Otherwise, close the modal (handles other modals' backdrop clicks and all dismiss buttons)+ modalToClose.classList.remove('active');++ // Reset forms only when closing the respective modal+ if (modalToClose.id === 'editModal') {+ // Optional: Add any edit form reset logic here if needed+ console.log('Edit modal closed, reset logic (if any) can go here.');+ } else if (modalToClose.id === 'addWarrantyModal') {+ // This reset will now only trigger if closed via dismiss button+ resetAddWarrantyWizard();+ }+ // Add similar reset logic for other modals like deleteModal if needed+ // else if (modalToClose.id === 'deleteModal') { ... }+ }}});});-+// Prevent modal content clicks from closing the modaldocument.querySelectorAll('.modal').forEach(modal => {modal.addEventListener('click', (e) => {@@ -2392,6 +2694,18 @@ function setupUIEventListeners() {const exportBtn = document.getElementById('exportBtn');if (exportBtn) exportBtn.addEventListener('click', exportWarranties);+ // Import button event listener+ if (importBtn && csvFileInput) {+ importBtn.addEventListener('click', () => {+ csvFileInput.click(); // Trigger hidden file input+ });+ csvFileInput.addEventListener('change', (event) => {+ if (event.target.files && event.target.files.length > 0) {+ handleImport(event.target.files[0]);+ }+ });+ }+// Refresh buttonconst refreshBtn = document.getElementById('refreshBtn');if (refreshBtn) refreshBtn.addEventListener('click', loadWarranties);@@ -2487,10 +2801,8 @@ function saveWarranty() {}// --- Modified Validation ---- // Only validate warrantyYears if it's NOT a lifetime warrantyif (!isLifetime) {- // Use parseInt to ensure it's treated as a number- if (!warrantyYears || parseInt(warrantyYears, 10) <= 0) {+ if (!warrantyYears || parseFloat(warrantyYears) <= 0) {showToast('Warranty period (years) must be greater than 0 for non-lifetime warranties', 'error');// Optional: focus the years input againconst yearsInput = document.getElementById('editWarrantyYears');@@ -2507,7 +2819,6 @@ function saveWarranty() {const formData = new FormData();formData.append('product_name', productName);formData.append('purchase_date', purchaseDate);- // formData.append('warranty_years', warrantyYears); // Append conditionally later// Optional fieldsconst productUrl = document.getElementById('editProductUrl').value.trim();@@ -2548,21 +2859,9 @@ function saveWarranty() {formData.append('manual', manualFile);}- // --- Remove redundant check (already covered by validation) ---- // if (!editIsLifetimeCheckbox.checked && !editWarrantyYearsInput.value) {- // showToast('Warranty period (years) is required unless it\'s a lifetime warranty', 'error');- // // Switch to the warranty details tab in the edit modal- // const warrantyTabBtn = document.querySelector('.edit-tab-btn[data-tab="edit-warranty-details"]');- // if (warrantyTabBtn) warrantyTabBtn.click();- // editWarrantyYearsInput.focus();- // editWarrantyYearsInput.classList.add('invalid');- // return;- // }-// --- Append is_lifetime and warranty_years ---formData.append('is_lifetime', isLifetime.toString());if (!isLifetime) {- // Use the value we already retrievedformData.append('warranty_years', warrantyYears);}@@ -2604,70 +2903,6 @@ function saveWarranty() {});}-// Render the tags dropdown list for edit mode-function renderEditTagsList(searchTerm = '') {- const editTagsList = document.getElementById('editTagsList');- if (!editTagsList) return;-- editTagsList.innerHTML = '';-- // Filter tags based on search term- const filteredTags = allTags.filter(tag =>- !searchTerm || tag.name.toLowerCase().includes(searchTerm.toLowerCase())- );-- // Add option to create new tag if search term is provided and not in list- if (searchTerm && !filteredTags.some(tag => tag.name.toLowerCase() === searchTerm.toLowerCase())) {- const createOption = document.createElement('div');- createOption.className = 'tag-option create-tag';- createOption.innerHTML = `<i class="fas fa-plus"></i> Create "${searchTerm}"`;- createOption.addEventListener('click', () => {- createTag(searchTerm);- editTagsList.classList.remove('show');- });- editTagsList.appendChild(createOption);- }-- // Add existing tags to dropdown- filteredTags.forEach(tag => {- const option = document.createElement('div');- option.className = 'tag-option';-- // Check if tag is already selected- const isSelected = editSelectedTags.some(selected => selected.id === tag.id);-- option.innerHTML = `- <span class="tag-color" style="background-color: ${tag.color}"></span>- ${tag.name}- <span class="tag-status">${isSelected ? '<i class="fas fa-check"></i>' : ''}</span>- `;-- option.addEventListener('click', () => {- if (isSelected) {- // Remove tag if already selected- editSelectedTags = editSelectedTags.filter(selected => selected.id !== tag.id);- } else {- // Add tag if not selected- editSelectedTags.push({- id: tag.id,- name: tag.name,- color: tag.color- });- }-- // Use our helper function to render selected tags- renderEditSelectedTags();-- renderEditTagsList(searchTerm);- });-- editTagsList.appendChild(option);- });-- // Show the dropdown- editTagsList.classList.add('show');-}-// Function to populate tag filter dropdownfunction populateTagFilter() {const tagFilter = document.getElementById('tagFilter');@@ -2705,127 +2940,6 @@ function populateTagFilter() {});}-// Helper function to render the edit selected tags-function renderEditSelectedTags() {- const editSelectedTagsContainer = document.getElementById('editSelectedTags');- if (!editSelectedTagsContainer) return;-- editSelectedTagsContainer.innerHTML = '';-- if (editSelectedTags.length > 0) {- editSelectedTags.forEach(tag => {- const tagElement = document.createElement('span');- tagElement.className = 'tag';- tagElement.style.backgroundColor = tag.color;- tagElement.style.color = getContrastColor(tag.color);-- tagElement.innerHTML = `- ${tag.name}- <span class="remove-tag" data-id="${tag.id}">×</span>- `;-- // Add event listener for removing tag- const removeButton = tagElement.querySelector('.remove-tag');- removeButton.addEventListener('click', (e) => {- e.stopPropagation();- e.preventDefault(); // Add this to prevent default action-- // Prevent the event from bubbling up to parent elements- if (e.cancelBubble !== undefined) {- e.cancelBubble = true;- }-- editSelectedTags = editSelectedTags.filter(t => t.id !== tag.id);-- // Re-render just the tags- renderEditSelectedTags();- return false; // Add return false for older browsers- });-- editSelectedTagsContainer.appendChild(tagElement);- });- } else {- const placeholder = document.createElement('span');- placeholder.className = 'no-tags-selected';- placeholder.textContent = 'No tags selected';- editSelectedTagsContainer.appendChild(placeholder);- }-}--// Create a new tag via the management modal form-function createNewTag() {- const tagNameInput = document.getElementById('newTagName');- const tagColorInput = document.getElementById('newTagColor');-- const name = tagNameInput ? tagNameInput.value.trim() : '';- const color = tagColorInput ? tagColorInput.value : '#808080'; // Default color if input not found-- if (!name) {- showToast('Tag name cannot be empty', 'error');- return;- }-- const token = localStorage.getItem('auth_token');- if (!token) {- console.error('No authentication token found');- showToast('Authentication required', 'error');- return;- }-- showLoadingSpinner(); // Show loading indicator-- fetch('/api/tags', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'Authorization': 'Bearer ' + token- },- body: JSON.stringify({- name: name,- color: color- })- })- .then(response => {- if (!response.ok) {- if (response.status === 409) {- throw new Error('A tag with this name already exists');- }- // Try to get error message from response body- return response.json().then(errData => {- throw new Error(errData.error || errData.message || 'Failed to create tag');- }).catch(() => {- // If response body is not JSON or empty- throw new Error(`Failed to create tag. Status: ${response.status}`);- });- }- return response.json();- })- .then(data => {- // Add new tag to allTags array- allTags.push({- id: data.id,- name: data.name,- color: data.color- });-- // --- FIX: Clear input fields and re-render existing tags ---- if (tagNameInput) tagNameInput.value = '';- if (tagColorInput) tagColorInput.value = '#808080'; // Reset color picker- renderExistingTags(); // Update the list in the modal- populateTagFilter(); // Update the filter dropdown on the main page- // --- END FIX ----- showToast('Tag created successfully', 'success');- })- .catch(error => {- console.error('Error creating tag:', error);- showToast(error.message || 'Failed to create tag', 'error');- })- .finally(() => {- hideLoadingSpinner(); // Hide loading indicator- });-}-// --- Add New Function ---function handleLifetimeChange(event) {const checkbox = event ? event.target : isLifetimeCheckbox;@@ -2878,7 +2992,25 @@ function resetAddWarrantyWizard() {// Reset file input displaysif (fileName) fileName.textContent = '';- if (manualFileName) manualFileName.textContent = '';+ if (manualFileName) fileName.textContent = '';++ // Reset selected tags+ selectedTags = [];+ console.log('Resetting Add Warranty Wizard...');+ // Reset the form fields+ if (warrantyForm) {+ warrantyForm.reset();+ }++ // Reset serial numbers container (remove all but the first input structure)+ if (serialNumbersContainer) {+ serialNumbersContainer.innerHTML = ''; // Clear it+ addSerialNumberInput(); // Add the initial input back+ }++ // Reset file input displays+ if (fileName) fileName.textContent = '';+ if (manualFileName) fileName.textContent = '';// Reset selected tagsselectedTags = [];@@ -2913,10 +3045,8 @@ function setupModalTriggers() {showAddWarrantyBtn.addEventListener('click', () => {resetAddWarrantyWizard(); // Reset before showingaddWarrantyModal.classList.add('active');- // Re-initialize tabs specifically for this modal if needed,- // but initFormTabs() in DOMContentLoaded should handle it.- // Ensure the first tab content is displayed correctly after reset- switchToTab(0);+ initFormTabs(); // Initialize tabs only when modal is shown+ switchToTab(0); // Ensure the first tab content is displayed correctly after reset});}@@ -2930,20 +3060,153 @@ function setupModalTriggers() {resetAddWarrantyWizard(); // Reset on close});}- // Backdrop click+ // REMOVED: Backdrop click listener+ /*addWarrantyModal.addEventListener('click', (e) => {if (e.target === addWarrantyModal) {addWarrantyModal.classList.remove('active');resetAddWarrantyWizard(); // Reset on close}});+ */// Optional: Cancel button in footer if you add one- // const cancelBtn = addWarrantyModal.querySelector('.cancel-btn');- // if (cancelBtn) {- // cancelBtn.addEventListener('click', () => {- // addWarrantyModal.classList.remove('active');- // resetAddWarrantyWizard(); // Reset on cancel- // });- // }- }-}\ No newline at end of file+ // ... (cancel button logic remains unchanged)+ }++ // --- Edit Modal Triggers (Keep existing logic) ---+ // Close edit/delete modals when clicking outside or on close button+ document.querySelectorAll('#editModal, #deleteModal, [data-dismiss="modal"]').forEach(element => {+ element.addEventListener('click', (e) => {+ // Check if the click is on the backdrop itself OR a dismiss button+ if (e.target === element || e.target.matches('[data-dismiss="modal"]')) {+ // Find the closest modal backdrop to the element clicked+ const modalToClose = e.target.closest('.modal-backdrop');+ if (modalToClose) {+ // *** ADD CHECK: Do NOT close addWarrantyModal via this general listener ***+ if (modalToClose.id === 'addWarrantyModal') {+ return; // Ignore backdrop clicks for the add modal here+ }+ // *** END ADD CHECK ***++ modalToClose.classList.remove('active');+ // Reset edit form state if closing edit modal+ if (modalToClose.id === 'editModal') {+ // Optional: Add any edit form reset logic here if needed+ }+ }+ }+ });+ });++ // Prevent modal content clicks from closing the modal (Keep for all modals)+ document.querySelectorAll('.modal').forEach(modal => {+ modal.addEventListener('click', (e) => {+ e.stopPropagation();+ });+ });+}++// --- CSV Import Functionality ---++async function handleImport(file) {+ if (!file) {+ showToast('No file selected.', 'warning');+ return;+ }++ if (!file.name.toLowerCase().endsWith('.csv')) {+ showToast('Invalid file type. Please select a .csv file.', 'error');+ return;+ }++ // Show loading indicator+ showLoadingSpinner();++ const formData = new FormData();+ formData.append('csv_file', file);++ try {+ // const token = localStorage.getItem('token'); // Incorrect key+ const token = localStorage.getItem('auth_token'); // Correct key used elsewhere+ if (!token) {+ showToast('Authentication error. Please log in again.', 'error');+ hideLoadingSpinner();+ // Maybe redirect to login: window.location.href = '/login.html';+ return;+ }++ const response = await fetch('/api/warranties/import', {+ method: 'POST',+ headers: {+ // Content-Type is automatically set by browser when using FormData+ 'Authorization': `Bearer ${token}`+ },+ body: formData+ });++ hideLoadingSpinner();+ const result = await response.json();++ if (response.ok) {+ const { success_count, failure_count, errors } = result;+ let message = `${success_count} warranties imported successfully.`;+ if (failure_count > 0) {+ message += ` ${failure_count} rows failed.`;+ // Log detailed errors to the console for now+ console.warn('Import errors:', errors);+ // Consider showing errors in a modal or separate report later+ }+ showToast(message, 'success');++ // ***** FIX: Reload the tags list *****+ console.log("Import successful, reloading tags...");+ await loadTags(); // Fetch the updated list of all tags+ // ***** END FIX *****++ loadWarranties(); // Refresh the list+ } else {+ showToast(`Import failed: ${result.error || 'Unknown error'}`, 'error');+ if (result.errors) {+ console.error('Detailed import errors:', result.errors);+ }+ }++ } catch (error) {+ hideLoadingSpinner();+ console.error('Error during file import:', error);+ showToast('An error occurred during import. Check console for details.', 'error');+ } finally {+ // Reset the file input so the user can select the same file again if needed+ if (csvFileInput) {+ csvFileInput.value = '';+ }+ }+}++// --- End CSV Import Functionality ---++// --- Add Storage Event Listener for Real-time Sync ---+window.addEventListener('storage', (event) => {+ const prefix = getPreferenceKeyPrefix();+ const viewKeys = [+ `${prefix}defaultView`,+ 'viewPreference',+ `${prefix}warrantyView`,+ // Add `${prefix}viewPreference` if still used/relevant+ `${prefix}viewPreference`+ ];++ if (viewKeys.includes(event.key) && event.newValue) {+ console.log(`Storage event detected for view preference (${event.key}). New value: ${event.newValue}`);+ // Check if the new value is different from the current view to avoid loops+ if (event.newValue !== currentView) {+ // Ensure view buttons exist before switching (we're on the main page)+ if (gridViewBtn || listViewBtn || tableViewBtn) {+ switchView(event.newValue);+ }+ } else {+ console.log('Storage event value matches current view, ignoring.');+ }+ }+});+// --- End Storage Event Listener ---\ No newline at end of filediff --git a/frontend/settings-new.html b/frontend/settings-new.htmlindex f3b2d78..4ea9ee5 100644--- a/frontend/settings-new.html+++ b/frontend/settings-new.html@@ -20,245 +20,15 @@<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"><!-- Then load settings-specific styles --><link rel="stylesheet" href="settings-styles.css">- <script src="theme-loader.js"></script> <!-- Apply theme early -->+ <!-- Apply theme immediately -->+ <script src="theme-loader.js"></script><!-- Load header fix styles last to override any conflicting styles --><link rel="stylesheet" href="header-fix.css">+ <!-- Mobile Header specific styles -->+ <link rel="stylesheet" href="mobile-header.css"><!-- Load fix for auth buttons --><script src="fix-auth-buttons-loader.js"></script>- <!-- Initialize theme immediately to prevent flash of wrong theme -->- <script>- document.addEventListener('DOMContentLoaded', function() {- // Initialize theme based on darkMode localStorage setting- const darkMode = localStorage.getItem('darkMode') === 'true';-- if (darkMode) {- document.body.classList.add('dark-mode');- document.documentElement.setAttribute('data-theme', 'dark');- } else {- document.body.classList.remove('dark-mode');- document.documentElement.setAttribute('data-theme', 'light');- }- });- </script>- <style>- /* User menu styles - copied from index.html to ensure consistency */- .user-menu {- position: relative;- margin-left: 15px;- }-- .user-btn {- background: none;- border: none;- color: var(--text-color);- cursor: pointer;- display: flex;- align-items: center;- font-size: 0.9rem;- padding: 5px 10px;- border-radius: 20px;- transition: background-color 0.3s;- }-- .user-btn:hover {- background-color: rgba(0, 0, 0, 0.05);- }-- .dark-mode .user-btn:hover {- background-color: rgba(255, 255, 255, 0.1);- }-- .user-btn i {- margin-right: 5px;- }-- .user-menu-dropdown {- position: absolute;- top: 100%;- right: 0;- background-color: var(--card-bg);- border-radius: 8px;- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);- width: 200px;- z-index: 1000;- display: none;- padding: 10px 0;- margin-top: 5px;- }-- .user-menu-dropdown.active {- display: block;- }-- .user-info {- padding: 10px 15px;- border-bottom: 1px solid var(--border-color);- margin-bottom: 5px;- }-- .user-name {- font-weight: bold;- margin-bottom: 5px;- }-- .user-email {- font-size: 0.8rem;- color: var(--text-muted);- word-break: break-all;- }-- .user-menu-item {- padding: 8px 15px;- cursor: pointer;- transition: background-color 0.3s;- display: flex;- align-items: center;- }-- .user-menu-item:hover {- background-color: var(--hover-bg);- }-- .user-menu-item i {- margin-right: 10px;- width: 16px;- text-align: center;- }-- .auth-buttons {- display: flex;- gap: 10px;- margin-left: 15px;- }-- .auth-btn {- padding: 5px 15px;- border-radius: 20px;- font-size: 0.9rem;- display: flex;- align-items: center;- justify-content: center;- cursor: pointer;- transition: all 0.3s ease;- }-- .auth-btn i {- margin-right: 5px;- }-- .login-btn {- background-color: transparent;- border: 1px solid var(--primary-color);- color: var(--primary-color);- }-- .login-btn:hover {- background-color: rgba(var(--primary-rgb), 0.1);- }-- .register-btn {- background-color: var(--primary-color);- border: 1px solid var(--primary-color);- color: white;- }-- .register-btn:hover {- background-color: var(--primary-dark);- }-- /* Admin section styles */- .admin-section {- margin-top: 30px;- border-top: 1px solid var(--border-color);- padding-top: 30px;- }-- .admin-section h2 {- color: var(--primary-color);- margin-bottom: 20px;- }-- .admin-controls {- margin-bottom: 15px;- display: flex;- justify-content: flex-end;- }-- .table {- width: 100%;- border-collapse: collapse;- margin-bottom: 20px;- color: var(--text-color);- }-- .table th {- background-color: var(--card-header-bg);- padding: 10px;- text-align: left;- font-weight: bold;- border-bottom: 2px solid var(--border-color);- }-- .table td {- padding: 10px;- border-bottom: 1px solid var(--border-color);- vertical-align: middle;- }-- .table tr:hover {- background-color: var(--hover-bg);- }-- .table-responsive {- overflow-x: auto;- margin-bottom: 20px;- }-- .badge {- display: inline-block;- padding: 4px 8px;- border-radius: 4px;- font-size: 0.75rem;- font-weight: bold;- text-align: center;- white-space: nowrap;- }-- .badge-success {- background-color: #28a745;- color: white;- }-- .badge-danger {- background-color: #dc3545;- color: white;- }-- .badge-primary {- background-color: var(--primary-color);- color: white;- }-- .badge-secondary {- background-color: #6c757d;- color: white;- }-- .btn-sm {- padding: 0.25rem 0.5rem;- font-size: 0.875rem;- line-height: 1.5;- border-radius: 0.2rem;- }-- .mr-2 {- margin-right: 0.5rem;- }-- .font-weight-bold {- font-weight: bold;- }- </style>+<!-- Immediate authentication check script --><script>// Check if user is logged in immediately to hide buttons@@ -312,23 +82,6 @@</script></head><body>- <!-- Immediate theme initialization before anything else loads -->- <script>- // Apply theme immediately to prevent flash of wrong theme- (function() {- // Check localStorage darkMode setting directly- const darkMode = localStorage.getItem('darkMode') === 'true';-- if (darkMode) {- document.body.classList.add('dark-mode');- document.documentElement.setAttribute('data-theme', 'dark');- } else {- document.body.classList.remove('dark-mode');- document.documentElement.setAttribute('data-theme', 'light');- }- })();- </script>-<!-- Header --><header><div class="container">@@ -347,34 +100,38 @@<i class="fas fa-cog"></i> Settings</a></div>- <div id="userMenu" class="user-menu" style="display: none;">- <button class="user-btn" id="userMenuBtn">- <i class="fas fa-user-circle"></i>- <span id="userDisplayName">User</span>- </button>- <div class="user-menu-dropdown" id="userMenuDropdown">- <div class="user-info">- <div id="userName" class="user-name">User Name</div>- <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: block;">- <i class="fas fa-cog"></i> Settings- </a>- </div>- <div class="user-menu-item">- <i class="fas fa-info-circle"></i>- <a href="about.html" style="text-decoration: none; color: inherit;">About</a>- </div>- <div class="user-menu-item" id="logoutMenuItem">- <i class="fas fa-sign-out-alt"></i> Logout+ <!-- Group for right-aligned elements -->+ <div class="header-right-group">+ <div id="userMenu" class="user-menu" style="display: none;">+ <button class="user-btn" id="userMenuBtn">+ <i class="fas fa-user-circle"></i>+ <span id="userDisplayName">User</span>+ </button>+ <div class="user-menu-dropdown" id="userMenuDropdown">+ <div class="user-info">+ <div id="userName" class="user-name">User Name</div>+ <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: block;">+ <i class="fas fa-cog"></i> Settings+ </a>+ </div>+ <div class="user-menu-item">+ <i class="fas fa-info-circle"></i>+ <a href="about.html" style="text-decoration: none; color: inherit;">About</a>+ </div>+ <div class="user-menu-item" id="logoutMenuItem">+ <i class="fas fa-sign-out-alt"></i> Logout+ </div></div></div>- </div>- <div id="authContainer" class="auth-buttons" style="display: none;">- <a href="login.html" class="auth-btn login-btn"><i class="fas fa-sign-in-alt"></i> Login</a>- <a href="register.html" class="auth-btn register-btn"><i class="fas fa-user-plus"></i> Register</a>- </div>+ <div id="authContainer" class="auth-buttons" style="display: none;">+ <a href="login.html" class="auth-btn login-btn"><i class="fas fa-sign-in-alt"></i> Login</a>+ <a href="register.html" class="auth-btn register-btn"><i class="fas fa-user-plus"></i> Register</a>+ </div>+ <!-- Note: The settings gear toggle from other pages is intentionally omitted here -->+ </div> <!-- End header-right-group --></div></header>diff --git a/frontend/settings-new.js b/frontend/settings-new.jsindex e208b17..88d55d6 100644--- a/frontend/settings-new.js+++ b/frontend/settings-new.js@@ -45,65 +45,61 @@ const saveSiteSettingsBtn = document.getElementById('saveSiteSettingsBtn');const emailBaseUrlInput = document.getElementById('emailBaseUrl'); // Added for email base URL/**- * Initialize dark mode toggle+ * Set theme (dark/light) - Unified and persistent+ * @param {boolean} isDark - Whether to use dark mode*/-function initDarkModeToggle() {- // Get current dark mode state from body class- const isDarkMode = document.body.classList.contains('dark-mode');- console.log('Current dark mode state (from body class):', isDarkMode);-- // Set the toggle states based on the current visual theme- if (darkModeToggle) {- darkModeToggle.checked = isDarkMode;+function setTheme(isDark) {+ const theme = isDark ? 'dark' : 'light';+ // Apply theme to document+ document.documentElement.setAttribute('data-theme', theme);+ if (isDark) {+ document.body.classList.add('dark-mode');+ } else {+ document.body.classList.remove('dark-mode');}-- if (darkModeToggleSetting) {- darkModeToggleSetting.checked = isDarkMode;+ // Save to localStorage (single source of truth)+ localStorage.setItem('darkMode', isDark);+ // Sync both toggles if present+ if (typeof darkModeToggle !== 'undefined' && darkModeToggle) {+ darkModeToggle.checked = isDark;}-- // Header toggle handler- if (darkModeToggle) {- darkModeToggle.addEventListener('change', function() {- const isDark = this.checked;- setTheme(isDark);-- if (darkModeToggleSetting) {- darkModeToggleSetting.checked = isDark;- }- });+ if (typeof darkModeToggleSetting !== 'undefined' && darkModeToggleSetting) {+ darkModeToggleSetting.checked = isDark;}-- // Settings toggle handler- if (darkModeToggleSetting) {- darkModeToggleSetting.addEventListener('change', function() {- const isDark = this.checked;- setTheme(isDark);-- if (darkModeToggle) {- darkModeToggle.checked = isDark;- }- });+ // Also update user_preferences.theme for backward compatibility+ try {+ let userPrefs = {};+ const storedPrefs = localStorage.getItem('user_preferences');+ if (storedPrefs) {+ userPrefs = JSON.parse(storedPrefs);+ }+ userPrefs.theme = theme;+ localStorage.setItem('user_preferences', JSON.stringify(userPrefs));+ } catch (e) {+ console.error('Error updating theme in user_preferences:', e);}-- // Also update the localStorage to match the visual state- localStorage.setItem('darkMode', isDarkMode);}/**- * Initialize settings gear menu in the header+ * Initialize dark mode toggle and synchronize state*/-function initSettingsMenu() {- if (settingsBtn && settingsMenu) {- // Toggle settings menu when settings button is clicked- settingsBtn.addEventListener('click', function() {- settingsMenu.classList.toggle('active');+function initDarkModeToggle() {+ // Always check the single source of truth in localStorage+ const isDarkMode = localStorage.getItem('darkMode') === 'true';+ // Apply theme to DOM if not already set+ document.documentElement.setAttribute('data-theme', isDarkMode ? 'dark' : 'light');+ document.body.classList.toggle('dark-mode', isDarkMode);+ // Sync both toggles+ if (typeof darkModeToggle !== 'undefined' && darkModeToggle) {+ darkModeToggle.checked = isDarkMode;+ darkModeToggle.addEventListener('change', function() {+ setTheme(this.checked);});-- // Close settings menu when clicking outside- document.addEventListener('click', function(event) {- if (!settingsBtn.contains(event.target) && !settingsMenu.contains(event.target)) {- settingsMenu.classList.remove('active');- }+ }+ if (typeof darkModeToggleSetting !== 'undefined' && darkModeToggleSetting) {+ darkModeToggleSetting.checked = isDarkMode;+ darkModeToggleSetting.addEventListener('change', function() {+ setTheme(this.checked);});}}@@ -112,98 +108,30 @@ function initSettingsMenu() {document.addEventListener('DOMContentLoaded', function() {console.log('DOM fully loaded, initializing settings page');- // Initialize the page- initPage();-// Set up event listeners- setupEventListeners();-- // Initialize modals- initModals();+ setupEventListeners(); // Ensure this doesn't also try to init settings menu// Set up direct event listeners for critical elementssetupCriticalEventListeners();- // Make deleteUser function globally accessible+ // Make functions globally accessible if neededwindow.deleteUser = deleteUser;window.directDeleteUserAPI = directDeleteUserAPI;- // Add a global click handler for delete buttons- document.addEventListener('click', function(event) {- // Check if the click was on a delete button or inside the delete modal- if (event.target && event.target.id === 'confirmDeleteUserBtn') {- console.log('Global click handler caught delete button click');- event.preventDefault();- event.stopPropagation();- deleteUser();- return false;- }-- // Check for clicks on the direct delete link- if (event.target && event.target.id === 'directDeleteLink') {- console.log('Global click handler caught direct delete link click');- event.preventDefault();- event.stopPropagation();- deleteUser();- return false;- }-- // Check for clicks on the direct API link- if (event.target && event.target.id === 'directAPILink') {- console.log('Global click handler caught direct API link click');- event.preventDefault();- event.stopPropagation();- const userId = window.currentDeleteUserId ||- (document.getElementById('deleteUserId') ? document.getElementById('deleteUserId').value : null);- directDeleteUserAPI(userId);- return false;- }-- // Check for clicks on the emergency delete button- if (event.target && event.target.id === 'emergencyDeleteBtn') {- console.log('Global click handler caught emergency delete button click');- // The button has its own inline handler, so we don't need to do anything here- }-- // Check for any element with delete-user-btn class or containing "delete" in the id- if (event.target &&- (event.target.classList.contains('delete-user-btn') ||- (event.target.id && event.target.id.toLowerCase().includes('delete')))) {- console.log('Global click handler caught click on element with delete in the id:', event.target.id);- console.log('Element:', event.target);-- // If this is a button inside the delete modal, try to delete the user- if (event.target.closest('#deleteUserModal')) {- console.log('Element is inside delete modal, attempting to delete user');- event.preventDefault();- event.stopPropagation();- deleteUser();- return false;- }- }- });-- // Add a direct event listener to the confirmDeleteUserBtn- const confirmDeleteUserBtn = document.getElementById('confirmDeleteUserBtn');- if (confirmDeleteUserBtn) {- console.log('Adding direct event listener to confirmDeleteUserBtn on page load');- confirmDeleteUserBtn.addEventListener('click', function(e) {- console.log('Direct event listener on confirmDeleteUserBtn triggered');- e.preventDefault();- e.stopPropagation();- deleteUser();- return false;- });- }-- // Initialize theme- applyInitialTheme();-+ // Add global click handlers if needed+ // ... (existing delete button handler logic) ...+// Initialize dark mode toggleinitDarkModeToggle();- // Initialize settings menu- initSettingsMenu();+ // REMOVED initSettingsMenu() call - Handled by auth.js++ // Load initial data for the settings page+ loadUserData();+ loadTimezones().then(() => loadPreferences()).catch(err => {+ console.error('Error loading timezones/prefs:', err);+ loadPreferences(); // Try loading prefs anyway+ });});/**@@ -275,58 +203,7 @@ function initPage() {}/**- * Apply the initial theme based on the user's preference- */-function applyInitialTheme() {- // Get the appropriate key prefix based on user type- const prefix = getPreferenceKeyPrefix();- console.log(`Checking initial theme with prefix: ${prefix}`);-- // First check user/admin specific setting- const userSpecificDarkMode = localStorage.getItem(`${prefix}darkMode`);- if (userSpecificDarkMode !== null) {- const isDarkMode = userSpecificDarkMode === 'true';- console.log(`Found user-specific dark mode setting: ${isDarkMode}`);-- if (isDarkMode) {- document.body.classList.add('dark-mode');- document.documentElement.setAttribute('data-theme', 'dark');- } else {- document.body.classList.remove('dark-mode');- document.documentElement.setAttribute('data-theme', 'light');- }- return;- }-- // If no user-specific setting, check global setting (for backward compatibility)- const globalDarkMode = localStorage.getItem('darkMode');- if (globalDarkMode !== null) {- const isDarkMode = globalDarkMode === 'true';- console.log(`Found global dark mode setting: ${isDarkMode}`);-- if (isDarkMode) {- document.body.classList.add('dark-mode');- document.documentElement.setAttribute('data-theme', 'dark');- } else {- document.body.classList.remove('dark-mode');- document.documentElement.setAttribute('data-theme', 'light');- }- return;- }-- // If no setting in localStorage, check system preference as final fallback- if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {- document.body.classList.add('dark-mode');- document.documentElement.setAttribute('data-theme', 'dark');- console.log('Applied dark theme from system preference');- return;- }-- console.log('No dark theme preference found, using light theme');-}--/**- * Set up critical event listeners that must work for core functionality+ * Setup critical event listeners that must work for core functionality*/function setupCriticalEventListeners() {console.log('Setting up critical event listeners');@@ -538,47 +415,74 @@ function loadPreferences() {darkModeToggleSetting.checked = isDarkMode;}- // Load other preferences from localStorage using the appropriate prefix- try {- const userPrefs = localStorage.getItem(`${prefix}preferences`);- if (userPrefs) {- const preferences = JSON.parse(userPrefs);-- // Default view preference- if (defaultViewSelect && preferences.default_view) {- defaultViewSelect.value = preferences.default_view;- }-- // Email notifications preference- if (emailNotificationsToggle && preferences.email_notifications) {- emailNotificationsToggle.checked = preferences.email_notifications;- }-- // Expiring soon days preference- if (expiringSoonDaysInput && preferences.expiring_soon_days) {- expiringSoonDaysInput.value = preferences.expiring_soon_days;- }-- // Notification frequency preference- if (notificationFrequencySelect && preferences.notification_frequency) {- notificationFrequencySelect.value = preferences.notification_frequency;- }-- // Notification time preference- if (notificationTimeInput && preferences.notification_time) {- notificationTimeInput.value = preferences.notification_time;- }-- // Timezone preference- if (timezoneSelect && preferences.timezone) {- timezoneSelect.value = preferences.timezone;+ // --- BEGIN EDIT: Load Default View with Priority ---+ let defaultViewLoaded = false;+ if (defaultViewSelect) {+ const userSpecificView = localStorage.getItem(`${prefix}defaultView`);+ const generalView = localStorage.getItem('viewPreference');+ const legacyWarrantyView = localStorage.getItem(`${prefix}warrantyView`); // Check legacy key++ if (userSpecificView) {+ defaultViewSelect.value = userSpecificView;+ defaultViewLoaded = true;+ console.log(`Loaded default view from ${prefix}defaultView:`, userSpecificView);+ } else if (generalView) {+ defaultViewSelect.value = generalView;+ defaultViewLoaded = true;+ console.log('Loaded default view from viewPreference:', generalView);+ } else if (legacyWarrantyView) {+ defaultViewSelect.value = legacyWarrantyView;+ defaultViewLoaded = true;+ console.log(`Loaded default view from legacy ${prefix}warrantyView:`, legacyWarrantyView);+ }+ }+ // --- END EDIT ---++ // Load other preferences from localStorage using the appropriate prefix (only if default view not loaded yet)+ if (!defaultViewLoaded) {+ try {+ const userPrefs = localStorage.getItem(`${prefix}preferences`);+ if (userPrefs) {+ const preferences = JSON.parse(userPrefs);++ // Default view preference (load only if not loaded above)+ if (defaultViewSelect && preferences.default_view && !defaultViewLoaded) {+ defaultViewSelect.value = preferences.default_view;+ defaultViewLoaded = true; // Mark as loaded+ console.log(`Loaded default view from ${prefix}preferences object:`, preferences.default_view);+ }++ // Email notifications preference+ if (emailNotificationsToggle && typeof preferences.email_notifications !== 'undefined') { // Check for undefined+ emailNotificationsToggle.checked = preferences.email_notifications;+ }++ // Expiring soon days preference+ if (expiringSoonDaysInput && preferences.expiring_soon_days) {+ expiringSoonDaysInput.value = preferences.expiring_soon_days;+ }++ // Notification frequency preference+ if (notificationFrequencySelect && preferences.notification_frequency) {+ notificationFrequencySelect.value = preferences.notification_frequency;+ }++ // Notification time preference+ if (notificationTimeInput && preferences.notification_time) {+ notificationTimeInput.value = preferences.notification_time;+ }++ // Timezone preference+ if (timezoneSelect && preferences.timezone) {+ timezoneSelect.value = preferences.timezone;+ }}+ } catch (e) {+ console.error('Error loading preferences from localStorage:', e);}- } catch (e) {- console.error('Error loading preferences from localStorage:', e);}-- // Load preferences from API++ // Load preferences from API (API data should override if available, except maybe for default view if already loaded)fetch('/api/auth/preferences', {method: 'GET',headers: {@@ -599,11 +503,14 @@ function loadPreferences() {const apiPrefs = data;// Update UI with API preferences- if (defaultViewSelect && apiPrefs.default_view) {+ // Default View: Only update if not already loaded from higher priority localStorage keys+ if (defaultViewSelect && apiPrefs.default_view && !defaultViewLoaded) {defaultViewSelect.value = apiPrefs.default_view;+ console.log('Loaded default view from API:', apiPrefs.default_view);}- if (emailNotificationsToggle && apiPrefs.email_notifications) {+ // Other preferences always updated from API if available+ if (emailNotificationsToggle && typeof apiPrefs.email_notifications !== 'undefined') { // Check for undefinedemailNotificationsToggle.checked = apiPrefs.email_notifications;}@@ -890,54 +797,6 @@ function resetPasswordForm() {confirmPasswordInput.value = '';}-/**- * Set theme (dark/light)- * @param {boolean} isDark - Whether to use dark mode- */-function setTheme(isDark) {- console.log('Setting theme to:', isDark ? 'dark' : 'light');-- // Get the appropriate key prefix based on user type- const prefix = getPreferenceKeyPrefix();- console.log(`Setting theme with prefix: ${prefix}`);-- // Apply theme to document- document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');-- // Also add/remove the dark-mode class on the body for additional styling- if (isDark) {- document.body.classList.add('dark-mode');- } else {- document.body.classList.remove('dark-mode');- }-- // Save to localStorage with the appropriate prefix- localStorage.setItem(`${prefix}darkMode`, isDark);- localStorage.setItem('darkMode', isDark); // Keep this for backward compatibility-- // Also update preferences in localStorage for consistency- try {- let userPrefs = {};- const storedPrefs = localStorage.getItem(`${prefix}preferences`);- if (storedPrefs) {- userPrefs = JSON.parse(storedPrefs);- }- userPrefs.theme = isDark ? 'dark' : 'light';- localStorage.setItem(`${prefix}preferences`, JSON.stringify(userPrefs));- } catch (e) {- console.error(`Error updating theme in ${prefix}preferences:`, e);- }-- // Update toggle states- if (darkModeToggle) {- darkModeToggle.checked = isDark;- }-- if (darkModeToggleSetting) {- darkModeToggleSetting.checked = isDark;- }-}-/*** Save user profile*/@@ -1071,10 +930,11 @@ function savePreferences() {// Save to localStorage with the appropriate prefixlocalStorage.setItem(`${prefix}preferences`, JSON.stringify(data));- // Also save individual preferences for backward compatibility+ // Also save individual preferences for backward compatibility and general preferencelocalStorage.setItem(`${prefix}defaultView`, defaultView);- localStorage.setItem(`${prefix}warrantyView`, defaultView);+ localStorage.setItem(`${prefix}warrantyView`, defaultView); // Keep saving legacy key for nowlocalStorage.setItem(`${prefix}emailNotifications`, emailNotifications);+ localStorage.setItem('viewPreference', defaultView); // --- EDIT: Save general key ---// Save the dark mode setting for the current user typelocalStorage.setItem(`${prefix}darkMode`, isDarkMode);@@ -1091,9 +951,10 @@ function savePreferences() {// Save to localStorage as fallback with the appropriate prefixlocalStorage.setItem(`${prefix}theme`, isDarkMode ? 'dark' : 'light');localStorage.setItem(`${prefix}defaultView`, defaultView);- localStorage.setItem(`${prefix}warrantyView`, defaultView);+ localStorage.setItem(`${prefix}warrantyView`, defaultView); // Keep saving legacy key for nowlocalStorage.setItem(`${prefix}emailNotifications`, emailNotifications);localStorage.setItem(`${prefix}darkMode`, isDarkMode);+ localStorage.setItem('viewPreference', defaultView); // --- EDIT: Save general key ---// Apply theme even if API save failsdocument.body.classList.toggle('dark-mode', isDarkMode);@@ -2963,4 +2824,34 @@ function saveEmailSettings() {showToast('Error saving email settings', 'error');hideLoading();}-}\ No newline at end of file+}++// --- Add Storage Event Listener for Real-time Sync ---+window.addEventListener('storage', (event) => {+ const prefix = getPreferenceKeyPrefix();+ const viewKeys = [+ `${prefix}defaultView`,+ 'viewPreference',+ `${prefix}warrantyView`,+ // Add `${prefix}viewPreference` if still used/relevant+ `${prefix}viewPreference`+ ];++ if (viewKeys.includes(event.key) && event.newValue) {+ console.log(`Storage event detected for view preference (${event.key}) in settings. New value: ${event.newValue}`);+ // Ensure the dropdown element exists and the value is different+ if (defaultViewSelect && defaultViewSelect.value !== event.newValue) {+ // Check if the new value is a valid option in the select+ const optionExists = [...defaultViewSelect.options].some(option => option.value === event.newValue);+ if (optionExists) {+ defaultViewSelect.value = event.newValue;+ console.log('Updated settings default view dropdown.');+ } else {+ console.warn(`Storage event value (${event.newValue}) not found in dropdown options.`);+ }+ } else if (defaultViewSelect) {+ console.log('Storage event value matches current dropdown selection, ignoring.');+ }+ }+});+// --- End Storage Event Listener ---\ No newline at end of filediff --git a/frontend/status.html b/frontend/status.htmlindex 76642ae..7762f52 100644--- a/frontend/status.html+++ b/frontend/status.html@@ -221,57 +221,41 @@<i class="fas fa-chart-pie"></i> Status</a></div>- <div id="authContainer" class="auth-buttons">- <a href="login.html" class="auth-btn login-btn">- <i class="fas fa-sign-in-alt"></i> Login- </a>- <a href="register.html" class="auth-btn register-btn">- <i class="fas fa-user-plus"></i> Register- </a>- </div>- <div id="userMenu" class="user-menu" style="display: none;">- <button id="userBtn" class="user-btn">- <i class="fas fa-user-circle"></i>- <span id="userDisplayName">User</span>- </button>- <div id="userMenuDropdown" class="user-menu-dropdown">- <div class="user-info">- <div id="userName" class="user-name">User Name</div>- <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: block;">- <i class="fas fa-cog"></i> Settings- </a>- </div>- <div class="user-menu-item">- <i class="fas fa-info-circle"></i>- <a href="about.html" style="text-decoration: none; color: inherit;">About</a>- </div>- <div class="user-menu-item" id="logoutMenuItem">- <i class="fas fa-sign-out-alt"></i> Logout- </div>+ <!-- Group for right-aligned elements -->+ <div class="header-right-group">+ <div id="authContainer" class="auth-buttons">+ <a href="login.html" class="auth-btn login-btn">+ <i class="fas fa-sign-in-alt"></i> Login+ </a>+ <a href="register.html" class="auth-btn register-btn">+ <i class="fas fa-user-plus"></i> Register+ </a></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 id="userMenu" class="user-menu" style="display: none;">+ <button id="userBtn" class="user-btn">+ <i class="fas fa-user-circle"></i>+ <span id="userDisplayName">User</span>+ </button>+ <div id="userMenuDropdown" class="user-menu-dropdown">+ <div class="user-info">+ <div id="userName" class="user-name">User Name</div>+ <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: block;">+ <i class="fas fa-cog"></i> Settings+ </a>+ </div>+ <div class="user-menu-item">+ <i class="fas fa-info-circle"></i>+ <a href="about.html" style="text-decoration: none; color: inherit;">About</a>+ </div>+ <div class="user-menu-item" id="logoutMenuItem">+ <i class="fas fa-sign-out-alt"></i> Logout+ </div></div></div>- </div>+ </div> <!-- End header-right-group --></div></header>diff --git a/frontend/status.js b/frontend/status.jsindex 611c06b..30b8c28 100644--- a/frontend/status.js+++ b/frontend/status.js@@ -22,123 +22,63 @@ let EXPIRING_SOON_DAYS = 30; // Default value, will be updated from user preferelet currentSort = { column: 'expiration', direction: 'asc' };let allWarranties = []; // Store all warranties for filtering/sorting-// Chart instances-window.statusChart = null;-window.timelineChart = null;+// Global variables for chart instances and data+let statusChart = null;+let timelineChart = null;+let currentStatusData = null; // To store data for redraws+let currentTimelineData = null; // To store data for redraws-// Theme Management+// Theme Management - Simplifiedfunction setTheme(isDark) {- document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');- localStorage.setItem('darkMode', isDark);- darkModeToggle.checked = isDark;-}+ const theme = isDark ? 'dark' : 'light';+ console.log('Setting theme to:', theme, 'from status.js');-// Initialize theme based on user preference or system preference-function initializeTheme() {- const savedTheme = localStorage.getItem('darkMode');+ // 1. Apply theme attribute to document root+ document.documentElement.setAttribute('data-theme', theme);- if (savedTheme !== null) {- // Use saved preference- setTheme(savedTheme === 'true');- } else {- // Check for system preference- const prefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;- setTheme(prefersDarkMode);+ // 2. Save the single source of truth to localStorage+ localStorage.setItem('darkMode', isDark);++ // Update toggle state if the toggle exists on this page+ if (darkModeToggle) {+ darkModeToggle.checked = isDark;}}-// Initialize theme when page loads-initializeTheme();--// Initialize settings button-document.addEventListener('DOMContentLoaded', () => {- // Ensure auth state is checked- if (window.auth && window.auth.checkAuthState) {- window.auth.checkAuthState();+// Function to redraw charts after theme change+function redrawChartsWithNewTheme() {+ console.log("Theme changed, redrawing charts...");+ // Destroy existing charts if they exist - USE CORRECT VARIABLE NAMES+ if (statusChart && typeof statusChart.destroy === 'function') {+ statusChart.destroy();+ statusChart = null; // Reset variable}-- // Ensure settings button works- if (settingsBtn && settingsMenu) {- console.log('Status page: Settings button found, adding event listener');- settingsBtn.addEventListener('click', function(e) {- e.stopPropagation();- settingsMenu.classList.toggle('active');- console.log('Status page: Settings button clicked, menu toggled');- });-- // Close settings menu when clicking outside- document.addEventListener('click', function(e) {- if (settingsMenu.classList.contains('active') &&- !settingsMenu.contains(e.target) &&- !settingsBtn.contains(e.target)) {- settingsMenu.classList.remove('active');- }- });- } else {- console.error('Status page: Settings button or menu not found');+ if (timelineChart && typeof timelineChart.destroy === 'function') {+ timelineChart.destroy();+ timelineChart = null; // Reset variable+ }+ // Re-create charts with current data which will use new theme colors+ if (currentStatusData) {+ createStatusChart(currentStatusData);+ }+ if (currentTimelineData) {+ createTimelineChart(currentTimelineData);}-- // ... existing code ...-});--// Refresh dashboard button-refreshDashboardBtn.addEventListener('click', () => {- refreshDashboard();-});--// Search input event listener-searchWarranties.addEventListener('input', () => {- filterAndSortWarranties();-});--// Status filter change event listener-statusFilter.addEventListener('change', () => {- filterAndSortWarranties();-});--// Add click event listeners to sortable headers-sortableHeaders.forEach(header => {- header.addEventListener('click', () => {- const column = header.getAttribute('data-sort');-- // Toggle sort direction if clicking the same column- if (currentSort.column === column) {- currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';- } else {- currentSort.column = column;- currentSort.direction = 'asc';- }-- // Update header classes- updateSortHeaderClasses();-- // Re-sort the table- filterAndSortWarranties();- });-});--// Update the sort header classes-function updateSortHeaderClasses() {- sortableHeaders.forEach(header => {- const column = header.getAttribute('data-sort');- header.classList.remove('sort-asc', 'sort-desc');-- if (column === currentSort.column) {- header.classList.add(currentSort.direction === 'asc' ? 'sort-asc' : 'sort-desc');- }- });}-// Show loading indicator+// Loading indicator functionsfunction showLoading() {- loadingIndicator.classList.add('active');- dashboardContent.style.opacity = '0.5';+ if (loadingIndicator) {+ loadingIndicator.classList.add('active');+ dashboardContent.style.opacity = '0.5';+ }}-// Hide loading indicatorfunction hideLoading() {- loadingIndicator.classList.remove('active');- dashboardContent.style.opacity = '1';+ if (loadingIndicator) {+ loadingIndicator.classList.remove('active');+ dashboardContent.style.opacity = '1';+ }}// Show error message@@ -231,11 +171,17 @@ function showToast(message, type = 'info') {}// Update the summary counts-function updateSummaryCounts(stats) {- document.getElementById('activeCount').textContent = stats.active;- document.getElementById('expiringCount').textContent = stats.expiring_soon;- document.getElementById('expiredCount').textContent = stats.expired;- document.getElementById('totalCount').textContent = stats.total;+function updateSummaryCounts(statusData) {+ // Check if the elements exist before trying to set textContent+ const totalEl = document.getElementById('totalCount');+ const activeEl = document.getElementById('activeCount');+ const expiringEl = document.getElementById('expiringCount');+ const expiredEl = document.getElementById('expiredCount');++ if (totalEl) totalEl.textContent = statusData.total || 0;+ if (activeEl) activeEl.textContent = statusData.active || 0;+ if (expiringEl) expiringEl.textContent = statusData.expiring_soon || 0;+ if (expiredEl) expiredEl.textContent = statusData.expired || 0;}// Create the status distribution chart@@ -256,12 +202,12 @@ function createStatusChart(stats) {// Calculate truly active (not expiring soon)const trulyActive = Math.max(0, active - expiringSoon);- // Destroy existing chart if it exists- if (window.statusChart) {- window.statusChart.destroy();+ // Destroy existing chart if it exists - USE CORRECT VARIABLE NAME+ if (statusChart && typeof statusChart.destroy === 'function') {+ statusChart.destroy();}- window.statusChart = new Chart(ctx, {+ statusChart = new Chart(ctx, {type: 'doughnut',data: {labels: ['Active', 'Expiring Soon', 'Expired'],@@ -348,12 +294,12 @@ function createTimelineChart(timeline) {}}- // Destroy existing chart if it exists- if (window.timelineChart) {- window.timelineChart.destroy();+ // Destroy existing chart if it exists - USE CORRECT VARIABLE NAME+ if (timelineChart && typeof timelineChart.destroy === 'function') {+ timelineChart.destroy();}- window.timelineChart = new Chart(ctx, {+ timelineChart = new Chart(ctx, {type: 'bar',data: {labels: formattedLabels,@@ -400,9 +346,6 @@ function updateRecentExpirations(recentWarranties) {};});- // Store all warranties for filtering/sorting- allWarranties = normalizedWarranties;-// Apply initial filtering and sortingfilterAndSortWarranties();}@@ -657,198 +600,251 @@ function refreshDashboard() {// Initialize the dashboardasync function initDashboard() {console.log('Initializing dashboard');-try {- // Show loading indicatorshowLoading();+ await loadUserPreferences(); // Load preferences first- // Load user preferences- await loadUserPreferences();+ // Fetch data using the statistics endpoint+ const data = await fetchStatistics();- // Check authentication- const token = localStorage.getItem('auth_token');- if (!token) {- window.location.href = 'login.html';- return;+ // Log the raw response+ console.log('Raw API Response for /api/statistics:', data);+ if (data && typeof data === 'object') {+ console.log('API Response type:', typeof data);+ console.log('API Response keys:', Object.keys(data));+ } else {+ console.log('API Response type:', typeof data);}-- const data = await fetchStatistics();- console.log('API Response:', data); // Log the actual response for debugging-- // Handle different possible API response structures- let summary, timeline, recentWarranties;-- // Check if data is directly the summary object- if (data && typeof data === 'object' && 'active' in data && 'expired' in data) {- summary = data;- timeline = data.timeline || [];- recentWarranties = data.recent_warranties || [];- }- // Check if data has summary as a property- else if (data && typeof data === 'object' && data.summary && typeof data.summary === 'object') {- summary = data.summary;- timeline = data.timeline || [];- recentWarranties = data.recent_warranties || [];- }- // If we can't find a valid structure, throw an error- else {- console.error('Unexpected API response structure:', data);- throw new Error('Invalid data structure received from API. Expected summary data with active and expired counts.');++ // *** UPDATED VALIDATION ***+ // Check for required top-level keys directly on the data object+ if (!data || typeof data !== 'object' || !('active' in data) || !('expired' in data)) {+ throw new Error(`Invalid data structure received from statistics API. Missing required keys (active, expired). Received: ${JSON.stringify(data)}`);}-- // Ensure summary has all required properties- if (!('active' in summary) || !('expired' in summary)) {- throw new Error('API response missing required summary fields (active, expired)');++ // *** USE DATA DIRECTLY (No 'summary' object) ***+ const recentWarranties = data.recent_warranties || [];+ const allWarrantiesData = data.all_warranties || recentWarranties; // Use all_warranties if available++ // *** ADD LOGGING HERE ***+ console.log('API Data received:', JSON.stringify(data, null, 2)); // Log the whole data object+ console.log('Does data have all_warranties?', data.hasOwnProperty('all_warranties'));+ if (data.hasOwnProperty('all_warranties')) {+ console.log('Length of data.all_warranties:', data.all_warranties ? data.all_warranties.length : 'null/undefined');}-- // Set default values for any missing properties- summary.expiring_soon = summary.expiring_soon || 0;- summary.total = summary.total || (summary.active + summary.expired);-- // Update summary counts- updateSummaryCounts(summary);-- // Create status chart- createStatusChart(summary);-- // Update recent expirations table with the initial data- updateRecentExpirations(recentWarranties);-- // Fetch all warranties for better filtering- try {- const allWarrantiesResponse = await fetch('/api/warranties', {- headers: {- 'Authorization': `Bearer ${token}`,- 'Content-Type': 'application/json'- }- });+ console.log('Length of data.recent_warranties:', recentWarranties.length);+ console.log('Content being assigned to global allWarranties:', JSON.stringify(allWarrantiesData, null, 2));+ // *** END LOGGING ***++ // Store data for potential redraws, directly from 'data'+ currentStatusData = {+ active: data.active || 0,+ expiring_soon: data.expiring_soon || 0,+ expired: data.expired || 0,+ total: data.total || 0 // Include total if needed+ };+ currentTimelineData = extractTimelineData(allWarrantiesData); // Use all warranties for timeline++ // Update UI using the structured data+ updateSummaryCounts(currentStatusData); // Pass the structured status data+ createStatusChart(currentStatusData); // Pass the structured status data+ createTimelineChart(currentTimelineData);+ allWarranties = allWarrantiesData; // Store for filtering+ console.log('Global allWarranties length AFTER assignment:', allWarranties.length); // Log length after assignment+ filterAndSortWarranties(); // Apply initial filters/sort to the table++ // Setup event listeners AFTER data is loaded and initial render is done+ setupEventListeners();++ hideLoading();+ } catch (error) {+ console.error('Error initializing dashboard:', error);+ // Display error appropriately using showError function+ showError(error.message || 'Failed to load dashboard', error.stack);+ } finally {+ hideLoading(); // Ensure loading is hidden even on error+ }+}++// Helper function to extract timeline data from warranties+function extractTimelineData(warranties) {+ // Create a map to store counts by month and year+ const timelineMap = new Map();++ // Get current date for reference+ const today = new Date();++ // Process each warranty+ warranties.forEach(warranty => {+ if (warranty.expiration_date) {+ const expDate = new Date(warranty.expiration_date);+ const month = expDate.getMonth() + 1; // 1-12+ const year = expDate.getFullYear();- if (allWarrantiesResponse.ok) {- const allWarrantiesData = await allWarrantiesResponse.json();- // Store all warranties for filtering- allWarranties = allWarrantiesData;- console.log('Fetched all warranties for filtering:', allWarranties.length);-- // Generate a more comprehensive timeline using all warranty data- if (allWarranties && allWarranties.length > 0) {- const timelineData = extractTimelineData(allWarranties);- console.log('Created comprehensive timeline data:', timelineData);- createTimelineChart(timelineData);- } else {- // Fallback to API timeline if no warranties found- createTimelineChart(timeline);- }+ // Create a key for this month/year+ const key = `${year}-${month}`;++ // Increment the count for this month/year+ if (timelineMap.has(key)) {+ timelineMap.set(key, timelineMap.get(key) + 1);} else {- // If we can't get all warranties, fall back to the recent ones- allWarranties = recentWarranties;- console.warn('Could not fetch all warranties, falling back to recent warranties');- // Use API timeline for the chart- createTimelineChart(timeline);+ timelineMap.set(key, 1);}- } catch (error) {- console.error('Error fetching all warranties:', error);- // Fall back to recent warranties on error- allWarranties = recentWarranties;- // Use API timeline for the chart- createTimelineChart(timeline);}+ });++ // Convert the map to an array of objects+ const timeline = Array.from(timelineMap.entries()).map(([key, count]) => {+ const [year, month] = key.split('-').map(Number);+ return { year, month, count };+ });++ // Sort by date+ timeline.sort((a, b) => {+ if (a.year !== b.year) return a.year - b.year;+ return a.month - b.month;+ });++ return timeline;+}++// Function to load user preferences+async function loadUserPreferences() {+ try {+ // Get the auth token+ const token = localStorage.getItem('auth_token');+ if (!token) return;- // Set up event listeners for filtering and sorting- setupEventListeners();+ // Get preferences from API+ const response = await fetch('/api/auth/preferences', {+ headers: {+ 'Authorization': `Bearer ${token}`+ }+ });- hideLoading();+ if (response.ok) {+ const data = await response.json();+ if (data && data.expiring_soon_days) {+ EXPIRING_SOON_DAYS = data.expiring_soon_days;+ console.log('Loaded expiring soon days from preferences:', EXPIRING_SOON_DAYS);+ }+ }} catch (error) {- console.error('Error initializing dashboard:', error);+ console.error('Error loading user preferences:', error);+ }+}++// Update the sort header classes+function updateSortHeaderClasses() {+ sortableHeaders.forEach(header => {+ const column = header.getAttribute('data-sort');+ header.classList.remove('sort-asc', 'sort-desc');- // Check if it's an authentication error- if (error.message.includes('Authentication required') ||- error.message.includes('Authentication token') ||- error.message.includes('401')) {-- showError('Authentication Required',- 'Please <a href="login.html">log in</a> to view your warranty statistics.');- } else {- showError('Error Loading Dashboard',- 'There was a problem loading the warranty statistics. Please try refreshing the page.');+ if (column === currentSort.column) {+ header.classList.add(currentSort.direction === 'asc' ? 'sort-asc' : 'sort-desc');}- } finally {- hideLoading();- }+ });+}++// Function to display overall status counts+function displayStatus(data) {+ document.getElementById('totalCount').textContent = data.total_count;+ document.getElementById('activeCount').textContent = data.active_count;+ document.getElementById('expiringCount').textContent = data.expiring_soon_count;+ document.getElementById('expiredCount').textContent = data.expired_count;+}++// Function to display errors+function displayError(error) {+ const statusContent = document.getElementById('statusContent'); // Assuming a main container+ if (!statusContent) return;+ statusContent.innerHTML = `+ <div class="error-message">+ <i class="fas fa-exclamation-triangle"></i>+ <h3>Failed to Load Status</h3>+ <p>Could not retrieve warranty status data. Please try again later.</p>+ <p>Error: ${error.message}</p>+ </div>+ `;}-// Initialize the dashboard when the page loads-document.addEventListener('DOMContentLoaded', initDashboard);+// Function to display recently expired/expiring warranties in the table+function displayRecentExpirations(expirations) {+ const tableBody = document.getElementById('recentExpirationsTableBody');+ if (!tableBody) return;-// Export button event listener-exportBtn.addEventListener('click', () => {- exportWarrantyData();-});+ tableBody.innerHTML = ''; // Clear existing rows++ if (!expirations || expirations.length === 0) {+ tableBody.innerHTML = '<tr class="empty-row"><td colspan="5" class="no-data">No warranties expiring soon or recently expired.</td></tr>';+ return;+ }++ expirations.forEach(warranty => {+ const row = tableBody.insertRow();+ const statusClass = warranty.status.toLowerCase().replace('_', '-'); // e.g., expiring-soon+ row.classList.add(`status-${statusClass}`);++ // Calculate days remaining/past+ let daysText = 'N/A';+ if (warranty.days_remaining !== null) {+ if (warranty.days_remaining < 0) {+ daysText = `${Math.abs(warranty.days_remaining)} days ago`;+ } else {+ daysText = `in ${warranty.days_remaining} days`;+ }+ }++ row.innerHTML = `+ <td>${warranty.product_name}</td>+ <td>${new Date(warranty.purchase_date).toLocaleDateString()}</td>+ <td>${new Date(warranty.expiration_date).toLocaleDateString()} (${daysText})</td>+ <td><span class="status-${statusClass}">${warranty.status.replace('_', ' ')}</span></td>+ <td>+ <a href="index.html#warranty-${warranty.id}" class="action-btn view-btn" title="View Warranty"><i class="fas fa-eye"></i></a>+ <!-- Add edit/delete if needed -->+ </td>+ `;+ });+}// Export warranty data as CSVfunction exportWarrantyData() {- // Get filtered and sorted warranties- const searchTerm = searchWarranties.value.toLowerCase();- const statusValue = statusFilter.value;+ // Get filtered and sorted warranties based on current view state+ const searchTerm = document.getElementById('searchWarranties').value.toLowerCase();+ const statusValue = document.getElementById('statusFilter').value;const today = new Date();- // Filter warranties+ // Filter warranties (similar logic to filterAndSortWarranties)let filteredWarranties = allWarranties.filter(warranty => {- // Apply search filter- const productName = warranty.product_name.toLowerCase();+ const productName = (warranty.product_name || '').toLowerCase();const matchesSearch = searchTerm === '' || productName.includes(searchTerm);-- // Apply status filter- if (statusValue === 'all') {- return matchesSearch;- }+ if (!matchesSearch) return false;++ if (statusValue === 'all') return true;+ if (!warranty.expiration_date) return false;const expirationDate = new Date(warranty.expiration_date);+ if (statusValue === 'expired') return expirationDate <= today;- if (statusValue === 'expired') {- return expirationDate <= today && matchesSearch;- } else if (statusValue === 'expiring') {- const timeDiff = expirationDate - today;- const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));- return expirationDate > today && daysDiff <= EXPIRING_SOON_DAYS && matchesSearch;- } else if (statusValue === 'active') {- const timeDiff = expirationDate - today;- const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));- return expirationDate > today && daysDiff > EXPIRING_SOON_DAYS && matchesSearch;- }+ const timeDiff = expirationDate - today;+ const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));- return matchesSearch;+ if (statusValue === 'expiring') return expirationDate > today && daysDiff <= EXPIRING_SOON_DAYS;+ if (statusValue === 'active') return expirationDate > today && daysDiff > EXPIRING_SOON_DAYS;++ return false; // Should not happen if statusValue is valid});// Sort warranties based on current sort settingsfilteredWarranties.sort((a, b) => {let valueA, valueB;-switch (currentSort.column) {- case 'product':- valueA = a.product_name;- valueB = b.product_name;- break;- case 'purchase':- valueA = new Date(a.purchase_date);- valueB = new Date(b.purchase_date);- break;- case 'expiration':- valueA = new Date(a.expiration_date);- valueB = new Date(b.expiration_date);- break;- case 'status':- // Sort by status priority: active, expiring, expired- const statusA = getStatusPriority(a.expiration_date, today);- const statusB = getStatusPriority(b.expiration_date, today);- valueA = statusA;- valueB = statusB;- break;- default:- valueA = new Date(a.expiration_date);- valueB = new Date(b.expiration_date);+ case 'product': valueA = a.product_name || ''; valueB = b.product_name || ''; break;+ case 'purchase': valueA = new Date(a.purchase_date || 0); valueB = new Date(b.purchase_date || 0); break;+ case 'status': valueA = getStatusPriority(a.expiration_date, today); valueB = getStatusPriority(b.expiration_date, today); break;+ default: valueA = new Date(a.expiration_date || 0); valueB = new Date(b.expiration_date || 0); // Default to expiration}-- // Compare values based on sort directionif (currentSort.direction === 'asc') {return valueA > valueB ? 1 : valueA < valueB ? -1 : 0;} else {@@ -856,40 +852,20 @@ function exportWarrantyData() {}});- // If no warranties to exportif (filteredWarranties.length === 0) {- showToast('No data to export', 'warning');+ showToast('No data to export based on current filters', 'warning');return;}// Create CSV contentlet csvContent = 'Product,Purchase Date,Expiration Date,Status\n';-filteredWarranties.forEach(warranty => {- const purchaseDate = new Date(warranty.purchase_date).toLocaleDateString();- const expirationDate = new Date(warranty.expiration_date).toLocaleDateString();-- // Determine status- const today = new Date();- const expDate = new Date(warranty.expiration_date);- let status = 'Active';-- if (expDate <= today) {- status = 'Expired';- } else {- const timeDiff = expDate - today;- const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));-- if (daysDiff <= EXPIRING_SOON_DAYS) {- status = 'Expiring Soon';- }- }-- // Escape commas in product name- const escapedProductName = warranty.product_name.includes(',')+ const purchaseDate = warranty.purchase_date ? new Date(warranty.purchase_date).toLocaleDateString() : 'N/A';+ const expirationDate = warranty.expiration_date ? new Date(warranty.expiration_date).toLocaleDateString() : 'N/A';+ const status = getStatusText(warranty.expiration_date, today);+ const escapedProductName = (warranty.product_name || '').includes(',')? `"${warranty.product_name}"`: warranty.product_name;-csvContent += `${escapedProductName},${purchaseDate},${expirationDate},${status}\n`;});@@ -897,150 +873,96 @@ function exportWarrantyData() {const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });const url = URL.createObjectURL(blob);const link = document.createElement('a');-- // Set link propertieslink.setAttribute('href', url);- link.setAttribute('download', 'warranty_data.csv');+ link.setAttribute('download', 'warranty_status_export.csv');link.style.visibility = 'hidden';-- // Add to document, click and removedocument.body.appendChild(link);link.click();document.body.removeChild(link);-+ URL.revokeObjectURL(url); // Clean up blob URLshowToast('Data exported successfully', 'success');}-// Set up event listeners for filtering and sorting+// Helper to get status text+function getStatusText(expirationDateStr, today) {+ if (!expirationDateStr) return 'Unknown';+ const expirationDate = new Date(expirationDateStr);+ if (expirationDate <= today) return 'Expired';+ const timeDiff = expirationDate - today;+ const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));+ if (daysDiff <= EXPIRING_SOON_DAYS) return 'Expiring Soon';+ return 'Active';+}++// Function to setup event listeners specific to the status pagefunction setupEventListeners() {- // Refresh button- if (refreshDashboardBtn) { // Check element exists before adding listener- refreshDashboardBtn.addEventListener('click', refreshDashboard);+ console.log("Setting up status page event listeners...");+ const refreshBtn = document.getElementById('refreshStatusBtn');+ const searchInput = document.getElementById('searchWarranties');+ const filterSelect = document.getElementById('statusFilter');+ const exportDataBtn = document.getElementById('exportBtn');+ const headers = document.querySelectorAll('.sortable');++ if (refreshBtn) {+ refreshBtn.addEventListener('click', initDashboard); // Reload everything on refresh}-- // Search input- if (searchWarranties) {- searchWarranties.addEventListener('input', filterAndSortWarranties);+ if (searchInput) {+ searchInput.addEventListener('input', filterAndSortWarranties);}-- // Status filter- if (statusFilter) { // Check element exists before adding listener- statusFilter.addEventListener('change', filterAndSortWarranties);+ if (filterSelect) {+ filterSelect.addEventListener('change', filterAndSortWarranties);}-- // Sortable headers (check if collection exists)- if (sortableHeaders) {- sortableHeaders.forEach(header => {+ if (exportDataBtn) {+ exportDataBtn.addEventListener('click', exportWarrantyData);+ }+ if (headers) {+ headers.forEach(header => {header.addEventListener('click', () => {const column = header.getAttribute('data-sort');-- // Toggle direction if same column, otherwise default to ascendingif (currentSort.column === column) {currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';} else {currentSort.column = column;currentSort.direction = 'asc';}-- // Update header classes to show sort directionupdateSortHeaderClasses();-- // Apply the new sortfilterAndSortWarranties();});});}++ // NOTE: The theme toggle listener is set up in DOMContentLoaded+ console.log("Status page event listeners setup complete.");+}- // Export button- if (exportBtn) { // Check element exists before adding listener- exportBtn.addEventListener('click', exportWarrantyData);- }+// Dummy checkLoginStatus and setupSettingsMenu for completeness+// function checkLoginStatus() { console.log("Checking login status..."); }+// function setupSettingsMenu() { console.log("Setting up settings menu..."); }- // Dark mode toggle (check element exists before adding listener)- if (darkModeToggle) {- darkModeToggle.addEventListener('change', (e) => {- setTheme(e.target.checked);+// --- Initialization ---+// IMPORTANT: Ensure ALL function definitions are ABOVE this listener+document.addEventListener('DOMContentLoaded', () => {+ console.log('Status page DOM loaded');+ // showLoading(); // Loading is shown inside initDashboard- // Redraw charts with new theme colors if they exist- if (window.statusChart) {- createStatusChart({- active: parseInt(document.getElementById('activeCount').textContent) || 0,- expiring_soon: parseInt(document.getElementById('expiringCount').textContent) || 0,- expired: parseInt(document.getElementById('expiredCount').textContent) || 0- });- }-- if (window.timelineChart && allWarranties.length > 0) {- createTimelineChart(extractTimelineData(allWarranties));- }+ // Initialize theme toggle state *after* DOM is loaded+ if (darkModeToggle) {+ const currentTheme = document.documentElement.getAttribute('data-theme');+ darkModeToggle.checked = currentTheme === 'dark';+ darkModeToggle.addEventListener('change', function() {+ setTheme(this.checked);+ redrawChartsWithNewTheme();});+ console.log(`Initialized theme toggle to: ${darkModeToggle.checked ? 'dark' : 'light'}`);}-}-// Helper function to extract timeline data from warranties-function extractTimelineData(warranties) {- // Create a map to store counts by month and year- const timelineMap = new Map();-- // Get current date for reference- const today = new Date();-- // Process each warranty- warranties.forEach(warranty => {- if (warranty.expiration_date) {- const expDate = new Date(warranty.expiration_date);- const month = expDate.getMonth() + 1; // 1-12- const year = expDate.getFullYear();-- // Create a key for this month/year- const key = `${year}-${month}`;-- // Increment the count for this month/year- if (timelineMap.has(key)) {- timelineMap.set(key, timelineMap.get(key) + 1);- } else {- timelineMap.set(key, 1);- }- }- });+ // Initialize the main dashboard logic+ initDashboard();- // Convert the map to an array of objects- const timeline = Array.from(timelineMap.entries()).map(([key, count]) => {- const [year, month] = key.split('-').map(Number);- return { year, month, count };- });-- // Sort by date- timeline.sort((a, b) => {- if (a.year !== b.year) return a.year - b.year;- return a.month - b.month;- });-- return timeline;-}--// Function to load user preferences-async function loadUserPreferences() {- try {- // Get the auth token- const token = localStorage.getItem('auth_token');- if (!token) return;-- // Get preferences from API- const response = await fetch('/api/auth/preferences', {- headers: {- 'Authorization': `Bearer ${token}`- }- });-- if (response.ok) {- const data = await response.json();- if (data && data.expiring_soon_days) {- EXPIRING_SOON_DAYS = data.expiring_soon_days;- console.log('Loaded expiring soon days from preferences:', EXPIRING_SOON_DAYS);- }- }- } catch (error) {- console.error('Error loading user preferences:', error);- }-}\ No newline at end of file+ // Setup settings menu (assuming it's part of the shared header)+ // if (typeof setupSettingsMenu === 'function') {+ // setupSettingsMenu();+ // } else if (window.auth && typeof window.auth.setupSettingsMenu === 'function') {+ // window.auth.setupSettingsMenu();+ // }+});\ No newline at end of filediff --git a/frontend/style.css b/frontend/style.cssindex 4b9cd54..755b3f1 100644--- a/frontend/style.css+++ b/frontend/style.css@@ -927,6 +927,39 @@ input.invalid {/* ===== RESPONSIVE ADJUSTMENTS ===== */@media (max-width: 768px) {+ /* Header Responsive Styles */+ header .container {+ flex-wrap: wrap; /* Allow header items to wrap */+ justify-content: center; /* Center items when wrapped */+ gap: 15px; /* Add space between wrapped items */+ padding: 10px 15px !important; /* Adjust padding for smaller screens */+ }++ header .app-title h1 {+ font-size: 1.8rem !important; /* Slightly reduce title size */+ }++ header .app-title i {+ font-size: 1.6rem !important; /* Slightly reduce icon size */+ margin-right: 10px !important;+ }++ header .nav-links {+ order: 3; /* Push nav links to the bottom row when wrapped */+ width: 100%; /* Make nav links take full width */+ justify-content: center; /* Center nav links */+ margin: 10px 0 0 0 !important; /* Add margin top, remove horizontal margin */+ padding-bottom: 5px; /* Add some padding below nav links */+ }++ header .auth-buttons,+ header .user-menu,+ header .settings-container {+ margin-left: 0 !important; /* Reset margins */+ margin-right: 0 !important;+ }+ /* End Header Responsive Styles */+.main-content {grid-template-columns: 1fr;}@@ -967,6 +1000,13 @@ input.invalid {z-index: 100;}+/* Group for right-aligned header elements (User Menu, Auth, Settings) */+.header-right-group {+ display: flex;+ align-items: center;+ gap: 10px; /* Adjust gap as needed */+}+.settings-btn {background-color: var(--card-bg);border: 1px solid var(--border-color);@@ -3022,4 +3062,43 @@ input.invalid {align-items: center;gap: 10px;flex-shrink: 0;+}++/* ===== RESPONSIVE ADJUSTMENTS ===== */+@media (max-width: 768px) {+ header .container {+ flex-wrap: wrap; /* Allow header items to wrap */+ justify-content: center; /* Center items when wrapped */+ gap: 15px; /* Add space between wrapped items */+ padding: 10px 15px !important; /* Adjust padding for smaller screens */+ }++ header .app-title h1 {+ font-size: 1.8rem !important; /* Slightly reduce title size */+ }++ header .app-title i {+ font-size: 1.6rem !important; /* Slightly reduce icon size */+ margin-right: 10px !important;+ }++ header .nav-links {+ order: 3; /* Push nav links to the bottom row when wrapped */+ width: 100%; /* Make nav links take full width */+ justify-content: center; /* Center nav links */+ margin: 10px 0 0 0 !important; /* Add margin top, remove horizontal margin */+ padding-bottom: 5px; /* Add some padding below nav links */+ }++ header .auth-buttons,+ header .user-menu,+ header .settings-container {+ margin-left: 0 !important; /* Reset margins */+ margin-right: 0 !important;+ }++ /* Adjust existing rules within the media query */+ .main-content {+ grid-template-columns: 1fr;+ }}\ No newline at end of filediff --git a/frontend/theme-loader.js b/frontend/theme-loader.jsindex 98399af..78ecf7b 100644--- a/frontend/theme-loader.js+++ b/frontend/theme-loader.js@@ -1,26 +1,35 @@// theme-loader.js(function() {try {- // Function to apply the theme+ // Function to apply the theme directly to the root elementfunction applyTheme(isDark) {- document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');- console.log(`Theme applied on load: ${isDark ? 'dark' : 'light'}`);+ const theme = isDark ? 'dark' : 'light';+ document.documentElement.setAttribute('data-theme', theme);+ // No need for console log in production loader script+ // console.log(`Theme applied on load: ${theme}`);}- // Check localStorage for saved theme+ // Default to light theme initially+ let isDarkMode = false;++ // Check localStorage for the standardized 'darkMode' keyconst savedTheme = localStorage.getItem('darkMode');if (savedTheme !== null) {- // Apply saved theme- applyTheme(savedTheme === 'true');+ // Use the saved theme preference+ isDarkMode = savedTheme === 'true';} else {- // Fallback to system preference if no theme saved+ // Fallback to system preference if no theme saved in localStorageconst prefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;- console.log(`No saved theme found, falling back to system preference: ${prefersDarkMode ? 'dark' : 'light'}`);- applyTheme(prefersDarkMode);- // Optionally, save the detected system preference as the initial setting- // localStorage.setItem('darkMode', prefersDarkMode);+ // console.log(`No saved theme found, falling back to system preference: ${prefersDarkMode ? 'dark' : 'light'}`);+ isDarkMode = prefersDarkMode;+ // Optionally, save the detected system preference as the initial setting for future loads+ // localStorage.setItem('darkMode', isDarkMode); // Consider if this is desired behavior}++ // Apply the determined theme+ applyTheme(isDarkMode);+} catch (e) {console.error("Error applying theme from theme-loader.js:", e);// Fallback to light theme in case of error