Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Settings updated

sassanix7d59e08da886
diff --git a/backend/app.py b/backend/app.py
index d27e00a..4c8aad2 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -1093,36 +1093,69 @@ def update_warranty(warranty_id):
@app.route('/api/statistics', methods=['GET'])
@token_required
def get_statistics():
+ user_id = request.user['id']
conn = None
+
try:
- user_id = request.user['id']
- is_admin = request.user['is_admin']
-
conn = get_db_connection()
+
+ # Get the user's expiring_soon_days preference
+ expiring_soon_days = 30 # Default value
+
+ try:
+ # Check if user_preferences table exists before trying to query it
+ with conn.cursor() as check_cur:
+ check_cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'user_preferences'
+ )
+ """)
+
+ table_exists = check_cur.fetchone()[0]
+
+ if table_exists:
+ with conn.cursor() as pref_cur:
+ pref_cur.execute(
+ """
+ SELECT expiring_soon_days FROM user_preferences
+ WHERE user_id = %s
+ """,
+ (user_id,)
+ )
+
+ preference = pref_cur.fetchone()
+ if preference:
+ expiring_soon_days = preference[0]
+ except Exception as e:
+ logger.error(f"Error getting user preferences: {e}")
+ # Continue with default value
+
+ # Current date
+ today = date.today()
+ thirty_days_later = today + timedelta(days=expiring_soon_days)
+ ninety_days_later = today + timedelta(days=90)
+
+ # Build the SQL query based on user role
+ from_clause = "FROM warranties"
+ where_clause = ""
+ active_where = "AND"
+ params = []
+
+ # For non-admin users, filter by user_id
+ if not request.user.get('is_admin', False):
+ # For non-admin users, add join to warranty_users table
+ from_clause = "FROM warranties w JOIN warranty_users wu ON w.id = wu.warranty_id"
+ where_clause = "WHERE wu.user_id = %s"
+ params = [user_id]
+
with conn.cursor() as cur:
- # Base query parts
- from_clause = 'FROM warranties'
- where_clause = ''
- params = []
-
- # Add user filtering if not admin
- if not is_admin:
- where_clause = 'WHERE user_id = %s'
- params.append(user_id)
-
- # Calculate expiration ranges
- today = date.today()
- logger.info(f"Current date: {today}")
- thirty_days_later = today + timedelta(days=30)
- ninety_days_later = today + timedelta(days=90)
-
# Get total count
cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause}", params)
total_count = cur.fetchone()[0]
logger.info(f"Total warranties: {total_count}")
# Get active count
- active_where = "WHERE" if not where_clause else "AND"
cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} expiration_date > %s", params + [today])
active_count = cur.fetchone()[0]
logger.info(f"Active warranties: {active_count}")
@@ -1132,7 +1165,7 @@ def get_statistics():
expired_count = cur.fetchone()[0]
logger.info(f"Expired warranties: {expired_count}")
- # Get expiring soon count (30 days)
+ # Get expiring soon count (using user preference)
cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} expiration_date > %s AND expiration_date <= %s",
params + [today, thirty_days_later])
expiring_soon_count = cur.fetchone()[0]
@@ -1348,10 +1381,44 @@ def get_preferences():
cursor = conn.cursor()
try:
+ # Check if user_preferences table exists
+ cursor.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'user_preferences'
+ )
+ """)
+
+ table_exists = cursor.fetchone()[0]
+
+ if not table_exists:
+ # Create the user_preferences table
+ cursor.execute("""
+ CREATE TABLE user_preferences (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ email_notifications BOOLEAN NOT NULL DEFAULT TRUE,
+ default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
+ theme VARCHAR(10) NOT NULL DEFAULT 'light',
+ expiring_soon_days INTEGER NOT NULL DEFAULT 30,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ UNIQUE(user_id)
+ )
+ """)
+
+ # Add index for faster lookups
+ cursor.execute("""
+ CREATE INDEX idx_user_preferences_user_id ON user_preferences(user_id)
+ """)
+
+ conn.commit()
+ logger.info(f"Created user_preferences table")
+
# Get user preferences
cursor.execute(
"""
- SELECT email_notifications, default_view, theme
+ SELECT email_notifications, default_view, theme, expiring_soon_days
FROM user_preferences
WHERE user_id = %s
""",
@@ -1364,9 +1431,9 @@ def get_preferences():
# Create default preferences if not exists
cursor.execute(
"""
- INSERT INTO user_preferences (user_id, email_notifications, default_view, theme)
- VALUES (%s, TRUE, 'grid', 'light')
- RETURNING email_notifications, default_view, theme
+ INSERT INTO user_preferences (user_id, email_notifications, default_view, theme, expiring_soon_days)
+ VALUES (%s, TRUE, 'grid', 'light', 30)
+ RETURNING email_notifications, default_view, theme, expiring_soon_days
""",
(user_id,)
)
@@ -1378,7 +1445,8 @@ def get_preferences():
preferences = {
'email_notifications': preferences_data[0],
'default_view': preferences_data[1],
- 'theme': preferences_data[2]
+ 'theme': preferences_data[2],
+ 'expiring_soon_days': preferences_data[3]
}
return jsonify(preferences), 200
@@ -1386,14 +1454,32 @@ def get_preferences():
except Exception as e:
conn.rollback()
logger.error(f"Database error in get_preferences: {str(e)}")
- return jsonify({'message': 'Database error occurred'}), 500
+
+ # Return default preferences as fallback
+ default_preferences = {
+ 'email_notifications': True,
+ 'default_view': 'grid',
+ 'theme': 'light',
+ 'expiring_soon_days': 30
+ }
+
+ return jsonify(default_preferences), 200
finally:
cursor.close()
release_db_connection(conn)
except Exception as e:
logger.error(f"Error in get_preferences: {str(e)}")
- return jsonify({'message': 'An error occurred while getting preferences'}), 500
+
+ # Return default preferences as fallback
+ default_preferences = {
+ 'email_notifications': True,
+ 'default_view': 'grid',
+ 'theme': 'light',
+ 'expiring_soon_days': 30
+ }
+
+ return jsonify(default_preferences), 200
@app.route('/api/auth/preferences', methods=['PUT'])
@token_required
@@ -1411,6 +1497,7 @@ def update_preferences():
email_notifications = data.get('email_notifications')
default_view = data.get('default_view')
theme = data.get('theme')
+ expiring_soon_days = data.get('expiring_soon_days')
# Validate input
if default_view and default_view not in ['grid', 'list', 'table']:
@@ -1419,18 +1506,62 @@ def update_preferences():
if theme and theme not in ['light', 'dark']:
return jsonify({'message': 'Invalid theme'}), 400
+ if expiring_soon_days is not None:
+ try:
+ expiring_soon_days = int(expiring_soon_days)
+ if expiring_soon_days < 1 or expiring_soon_days > 365:
+ return jsonify({'message': 'Expiring soon days must be between 1 and 365'}), 400
+ except ValueError:
+ return jsonify({'message': 'Expiring soon days must be a valid number'}), 400
+
# Get database connection
conn = get_db_connection()
cursor = conn.cursor()
try:
- # Check if preferences exist
- cursor.execute(
- "SELECT 1 FROM user_preferences WHERE user_id = %s",
- (user_id,)
- )
+ # Check if user_preferences table exists
+ cursor.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'user_preferences'
+ )
+ """)
- preferences_exist = cursor.fetchone() is not None
+ table_exists = cursor.fetchone()[0]
+
+ if not table_exists:
+ # Create the user_preferences table
+ cursor.execute("""
+ CREATE TABLE user_preferences (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ email_notifications BOOLEAN NOT NULL DEFAULT TRUE,
+ default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
+ theme VARCHAR(10) NOT NULL DEFAULT 'light',
+ expiring_soon_days INTEGER NOT NULL DEFAULT 30,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ UNIQUE(user_id)
+ )
+ """)
+
+ # Add index for faster lookups
+ cursor.execute("""
+ CREATE INDEX idx_user_preferences_user_id ON user_preferences(user_id)
+ """)
+
+ # Set preferences_exist to false to create new preferences
+ preferences_exist = False
+ conn.commit()
+ logger.info(f"Created user_preferences table")
+ else:
+ # Check if preferences exist
+ cursor.execute(
+ "SELECT 1 FROM user_preferences WHERE user_id = %s",
+ (user_id,)
+ )
+
+ preferences_exist = cursor.fetchone() is not None
if preferences_exist:
# Update existing preferences
@@ -1449,12 +1580,16 @@ def update_preferences():
update_fields.append("theme = %s")
update_values.append(theme)
+ if expiring_soon_days is not None:
+ update_fields.append("expiring_soon_days = %s")
+ update_values.append(expiring_soon_days)
+
if update_fields:
update_query = f"""
UPDATE user_preferences
SET {', '.join(update_fields)}, updated_at = NOW()
WHERE user_id = %s
- RETURNING email_notifications, default_view, theme
+ RETURNING email_notifications, default_view, theme, expiring_soon_days
"""
cursor.execute(update_query, update_values + [user_id])
@@ -1463,7 +1598,7 @@ def update_preferences():
# No fields to update
cursor.execute(
"""
- SELECT email_notifications, default_view, theme
+ SELECT email_notifications, default_view, theme, expiring_soon_days
FROM user_preferences
WHERE user_id = %s
""",
@@ -1478,44 +1613,63 @@ def update_preferences():
user_id,
email_notifications,
default_view,
- theme
+ theme,
+ expiring_soon_days
)
- VALUES (%s, %s, %s, %s)
- RETURNING email_notifications, default_view, theme
+ VALUES (%s, %s, %s, %s, %s)
+ RETURNING email_notifications, default_view, theme, expiring_soon_days
""",
(
- user_id,
- email_notifications if email_notifications is not None else True,
- default_view or 'grid',
- theme or 'light'
+ user_id,
+ email_notifications if email_notifications is not None else True,
+ default_view or 'grid',
+ theme or 'light',
+ expiring_soon_days if expiring_soon_days is not None else 30
)
)
-
preferences_data = cursor.fetchone()
- # Commit changes
- conn.commit()
-
# Format preferences data
preferences = {
'email_notifications': preferences_data[0],
'default_view': preferences_data[1],
- 'theme': preferences_data[2]
+ 'theme': preferences_data[2],
+ 'expiring_soon_days': preferences_data[3]
}
+ conn.commit()
+
return jsonify(preferences), 200
except Exception as e:
conn.rollback()
logger.error(f"Database error in update_preferences: {str(e)}")
- return jsonify({'message': 'Database error occurred'}), 500
+
+ # Return original data as fallback
+ fallback_preferences = {
+ 'email_notifications': email_notifications if email_notifications is not None else True,
+ 'default_view': default_view or 'grid',
+ 'theme': theme or 'light',
+ 'expiring_soon_days': expiring_soon_days if expiring_soon_days is not None else 30
+ }
+
+ return jsonify(fallback_preferences), 200
finally:
cursor.close()
release_db_connection(conn)
except Exception as e:
logger.error(f"Error in update_preferences: {str(e)}")
- return jsonify({'message': 'An error occurred while updating preferences'}), 500
+
+ # Return default preferences as fallback
+ default_preferences = {
+ 'email_notifications': True,
+ 'default_view': 'grid',
+ 'theme': 'light',
+ 'expiring_soon_days': 30
+ }
+
+ return jsonify(default_preferences), 200
# Admin User Management Endpoints
diff --git a/backend/migrations/007_add_expiring_soon_days.py b/backend/migrations/007_add_expiring_soon_days.py
new file mode 100644
index 0000000..35bd760
--- /dev/null
+++ b/backend/migrations/007_add_expiring_soon_days.py
@@ -0,0 +1,85 @@
+"""
+Migration 007: Add expiring_soon_days to user_preferences
+"""
+
+def upgrade(cursor):
+ """
+ Create user_preferences table if it doesn't exist and
+ add expiring_soon_days column to user_preferences table to allow customization of
+ how many days before expiration a warranty should be considered "expiring soon"
+ """
+ # Check if user_preferences table exists
+ cursor.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'user_preferences'
+ )
+ """)
+
+ table_exists = cursor.fetchone()[0]
+
+ if not table_exists:
+ # Create the user_preferences table
+ cursor.execute("""
+ CREATE TABLE user_preferences (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ email_notifications BOOLEAN NOT NULL DEFAULT TRUE,
+ default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
+ theme VARCHAR(10) NOT NULL DEFAULT 'light',
+ expiring_soon_days INTEGER NOT NULL DEFAULT 30,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ UNIQUE(user_id)
+ )
+ """)
+
+ # Add index for faster lookups
+ cursor.execute("""
+ CREATE INDEX idx_user_preferences_user_id ON user_preferences(user_id)
+ """)
+
+ print("Created user_preferences table with expiring_soon_days column")
+ else:
+ # Add expiring_soon_days column if it doesn't exist
+ cursor.execute("""
+ ALTER TABLE user_preferences
+ ADD COLUMN IF NOT EXISTS expiring_soon_days INTEGER NOT NULL DEFAULT 30
+ """)
+
+ print("Added expiring_soon_days column to existing user_preferences table")
+
+def downgrade(cursor):
+ """
+ Remove expiring_soon_days column from user_preferences
+ """
+ # Check if user_preferences table exists
+ cursor.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'user_preferences'
+ )
+ """)
+
+ table_exists = cursor.fetchone()[0]
+
+ if table_exists:
+ # Check if column exists
+ cursor.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.columns
+ WHERE table_name = 'user_preferences' AND column_name = 'expiring_soon_days'
+ )
+ """)
+
+ column_exists = cursor.fetchone()[0]
+
+ if column_exists:
+ cursor.execute("""
+ ALTER TABLE user_preferences
+ DROP COLUMN IF EXISTS expiring_soon_days
+ """)
+
+ print("Removed expiring_soon_days column from user_preferences table")
+ else:
+ print("user_preferences table does not exist, nothing to downgrade")
\ No newline at end of file
diff --git a/frontend/auth.js b/frontend/auth.js
index b2f02e5..5d0f1cd 100644
--- a/frontend/auth.js
+++ b/frontend/auth.js
@@ -65,6 +65,7 @@ document.addEventListener('DOMContentLoaded', () => {
* Check if user is authenticated and update UI accordingly
*/
function checkAuthState() {
+ // Get latest token from localStorage
authToken = localStorage.getItem('auth_token');
const userInfo = localStorage.getItem('user_info');
@@ -232,6 +233,7 @@ async function logout() {
* Clear authentication data from localStorage
*/
function clearAuthData() {
+ // Clear both localStorage and global variables
localStorage.removeItem('auth_token');
localStorage.removeItem('user_info');
authToken = null;
@@ -315,8 +317,9 @@ function addAuthHeader(options = {}) {
* @returns {string} - The authentication token
*/
function getToken() {
- // Always get the latest token from localStorage
- return localStorage.getItem('auth_token');
+ // Always get the latest token from localStorage and update global variable
+ authToken = localStorage.getItem('auth_token');
+ return authToken;
}
// Export authentication functions for use in other scripts
diff --git a/frontend/index.html b/frontend/index.html
index cde3f6f..cab589a 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -265,21 +265,6 @@
<i class="fab fa-github"></i> GitHub
</a>
</div>
- <div class="settings-item">
- <a href="simple-status.html" class="settings-link">
- <i class="fas fa-vial"></i> Simple Test
- </a>
- </div>
- <div class="settings-item">
- <a href="api-test.html" class="settings-link">
- <i class="fas fa-terminal"></i> API Test
- </a>
- </div>
- <div class="settings-item">
- <a href="page-test.html" class="settings-link">
- <i class="fas fa-sitemap"></i> Page Test
- </a>
- </div>
</div>
</div>
</div>
diff --git a/frontend/page-test.html b/frontend/page-test.html
deleted file mode 100644
index 767d3e4..0000000
--- a/frontend/page-test.html
+++ /dev/null
@@ -1,160 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Page Navigation Test</title>
- <style>
- body {
- font-family: Arial, sans-serif;
- max-width: 800px;
- margin: 0 auto;
- padding: 20px;
- }
- h1 {
- color: #2c3e50;
- border-bottom: 2px solid #ecf0f1;
- padding-bottom: 10px;
- }
- .test-links {
- margin: 20px 0;
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: 15px;
- }
- .link-card {
- border: 1px solid #e0e0e0;
- border-radius: 5px;
- padding: 15px;
- display: flex;
- flex-direction: column;
- box-shadow: 0 2px 5px rgba(0,0,0,0.1);
- }
- .link-card h3 {
- margin-top: 0;
- color: #3498db;
- }
- .link-card p {
- margin-bottom: 15px;
- flex-grow: 1;
- }
- .direct-link, .iframe-test {
- display: inline-block;
- padding: 8px 15px;
- background-color: #3498db;
- color: white;
- text-decoration: none;
- border-radius: 4px;
- margin-right: 10px;
- border: none;
- cursor: pointer;
- font-size: 14px;
- }
- .direct-link:hover, .iframe-test:hover {
- background-color: #2980b9;
- }
- .test-frame {
- width: 100%;
- height: 300px;
- border: 1px solid #e0e0e0;
- border-radius: 5px;
- margin-top: 20px;
- display: none;
- }
- .message {
- padding: 10px;
- margin: 10px 0;
- border-radius: 4px;
- }
- .success {
- background-color: #d4edda;
- color: #155724;
- border: 1px solid #c3e6cb;
- }
- .error {
- background-color: #f8d7da;
- color: #721c24;
- border: 1px solid #f5c6cb;
- }
- </style>
-</head>
-<body>
- <h1>Page Navigation Test</h1>
- <p>This page helps test if direct navigation to different pages in your application works correctly.</p>
-
- <div id="message" style="display: none;" class="message"></div>
-
- <div class="test-links">
- <div class="link-card">
- <h3>Home Page</h3>
- <p>The main dashboard page of the application.</p>
- <a href="index.html" class="direct-link">Direct Link</a>
- <button class="iframe-test" data-page="index.html">Test in iframe</button>
- </div>
-
- <div class="link-card">
- <h3>Status Page</h3>
- <p>The warranty status dashboard.</p>
- <a href="status.html" class="direct-link">Direct Link</a>
- <button class="iframe-test" data-page="status.html">Test in iframe</button>
- </div>
-
- <div class="link-card">
- <h3>Simple Status Test</h3>
- <p>A simplified test page with no JavaScript.</p>
- <a href="simple-status.html" class="direct-link">Direct Link</a>
- <button class="iframe-test" data-page="simple-status.html">Test in iframe</button>
- </div>
-
- <div class="link-card">
- <h3>Chart Test Page</h3>
- <p>A page that tests Chart.js rendering.</p>
- <a href="status-simple.html" class="direct-link">Direct Link</a>
- <button class="iframe-test" data-page="status-simple.html">Test in iframe</button>
- </div>
-
- <div class="link-card">
- <h3>API Test Page</h3>
- <p>A page that tests API endpoints.</p>
- <a href="api-test.html" class="direct-link">Direct Link</a>
- <button class="iframe-test" data-page="api-test.html">Test in iframe</button>
- </div>
-
- <div class="link-card">
- <h3>This Test Page</h3>
- <p>The current page you're viewing.</p>
- <a href="page-test.html" class="direct-link">Direct Link</a>
- <button class="iframe-test" data-page="page-test.html">Test in iframe</button>
- </div>
- </div>
-
- <iframe id="testFrame" class="test-frame" title="Test frame"></iframe>
-
- <script>
- document.querySelectorAll('.iframe-test').forEach(button => {
- button.addEventListener('click', function() {
- const pagePath = this.getAttribute('data-page');
- const frame = document.getElementById('testFrame');
- const message = document.getElementById('message');
-
- // Show the frame
- frame.style.display = 'block';
- frame.src = pagePath;
-
- // Listen for load or error
- frame.onload = function() {
- message.className = 'message success';
- message.textContent = `Success! Page "${pagePath}" loaded correctly in the iframe.`;
- message.style.display = 'block';
- };
-
- frame.onerror = function() {
- message.className = 'message error';
- message.textContent = `Error! Page "${pagePath}" failed to load in the iframe.`;
- message.style.display = 'block';
- };
- });
- });
- </script>
-</body>
-</html>
\ No newline at end of file
diff --git a/frontend/script.js b/frontend/script.js
index dc0e1e0..5636cee 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -51,6 +51,8 @@ initializeTheme();
// Initialize page
document.addEventListener('DOMContentLoaded', () => {
+ console.log('DOM fully loaded, initializing app...');
+
// Ensure auth state is checked
if (window.auth && window.auth.checkAuthState) {
window.auth.checkAuthState();
@@ -73,8 +75,133 @@ document.addEventListener('DOMContentLoaded', () => {
});
}
- // Initialize other event listeners and functionality
- // ... existing initialization code ...
+ // Initialize the app
+ initializeTheme();
+
+ // Initialize form tabs
+ initFormTabs();
+
+ // Initialize the form
+ resetForm();
+
+ // Close modals when clicking outside or on close button
+ document.querySelectorAll('.modal-backdrop, [data-dismiss="modal"]').forEach(element => {
+ element.addEventListener('click', (e) => {
+ if (e.target === element) {
+ closeModals();
+ }
+ });
+ });
+
+ // Prevent modal content clicks from closing the modal
+ document.querySelectorAll('.modal').forEach(modal => {
+ modal.addEventListener('click', (e) => {
+ e.stopPropagation();
+ });
+ });
+
+ // Filter event listeners
+ if (searchInput) {
+ searchInput.addEventListener('input', () => {
+ currentFilters.search = searchInput.value.toLowerCase();
+ applyFilters();
+ });
+ }
+
+ if (statusFilter) {
+ statusFilter.addEventListener('change', () => {
+ currentFilters.status = statusFilter.value;
+ applyFilters();
+ });
+ }
+
+ if (sortBySelect) {
+ sortBySelect.addEventListener('change', () => {
+ currentFilters.sort = sortBySelect.value;
+ applyFilters();
+ });
+ }
+
+ // View switcher event listeners
+ if (gridViewBtn) gridViewBtn.addEventListener('click', () => switchView('grid'));
+ if (listViewBtn) listViewBtn.addEventListener('click', () => switchView('list'));
+ if (tableViewBtn) tableViewBtn.addEventListener('click', () => switchView('table'));
+
+ // Export button event listener
+ if (exportBtn) exportBtn.addEventListener('click', exportWarranties);
+
+ // File input change event
+ if (fileInput) fileInput.addEventListener('change', (e) => updateFileName(e, 'invoice', 'fileName'));
+ if (manualInput) manualInput.addEventListener('change', (e) => updateFileName(e, 'manual', 'manualFileName'));
+
+ const editInvoice = document.getElementById('editInvoice');
+ if (editInvoice) {
+ editInvoice.addEventListener('change', () => {
+ updateFileName(null, 'editInvoice', 'editFileName');
+ });
+ }
+
+ const editManual = document.getElementById('editManual');
+ if (editManual) {
+ editManual.addEventListener('change', () => {
+ updateFileName(null, 'editManual', 'editManualFileName');
+ });
+ }
+
+ // Form submission
+ if (warrantyForm) warrantyForm.addEventListener('submit', addWarranty);
+
+ // Refresh button
+ if (refreshBtn) refreshBtn.addEventListener('click', loadWarranties);
+
+ // Save warranty changes
+ if (saveWarrantyBtn) saveWarrantyBtn.addEventListener('click', updateWarranty);
+
+ // Confirm delete button
+ if (confirmDeleteBtn) confirmDeleteBtn.addEventListener('click', deleteWarranty);
+
+ // Load saved view preference
+ loadViewPreference();
+
+ // Load preferences first to ensure we have the correct expiringSoonDays value
+ // before loading warranties
+ if (window.auth && window.auth.isAuthenticated()) {
+ console.log('User is authenticated, loading preferences...');
+ const token = window.auth.getToken();
+
+ if (token) {
+ fetch('/api/auth/preferences', {
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ })
+ .then(response => {
+ if (response.ok) return response.json();
+ throw new Error('Failed to load preferences');
+ })
+ .then(data => {
+ if (data && data.expiring_soon_days) {
+ expiringSoonDays = data.expiring_soon_days;
+ console.log('Updated expiring soon days from preferences during initialization:', expiringSoonDays);
+ }
+ // Now load warranties with the updated preference
+ loadWarranties();
+ })
+ .catch(error => {
+ console.error('Error loading preferences during initialization:', error);
+ // Still load warranties even if preferences couldn't be loaded
+ loadWarranties();
+ });
+ } else {
+ // No token available, load warranties with default preference
+ loadWarranties();
+ }
+ } else {
+ // User not authenticated, load warranties (this will show login prompt)
+ loadWarranties();
+ }
+
+ console.log('App initialization complete');
});
// Dark mode toggle
@@ -139,6 +266,7 @@ let currentFilters = {
sort: 'expiration'
};
let currentView = 'grid'; // Default view
+let expiringSoonDays = 30; // Default value, will be updated from user preferences
// API URL
const API_URL = '/api/warranties';
@@ -150,8 +278,8 @@ document.addEventListener('DOMContentLoaded', () => {
// Initialize the app
initializeTheme();
- // Load warranties
- loadWarranties();
+ // Load warranties - now handled by the preferences loading logic
+ // loadWarranties();
// Initialize form tabs
initFormTabs();
@@ -335,7 +463,8 @@ function processWarrantyData(warranty) {
} else if (daysRemaining < 0) {
statusClass = 'expired';
statusText = 'Expired';
- } else if (daysRemaining < 30) {
+ } else if (daysRemaining < expiringSoonDays) {
+ console.log(`Using expiringSoonDays: ${expiringSoonDays} for warranty: ${processedWarranty.product_name}`);
statusClass = 'expiring';
statusText = `Expiring Soon (${daysRemaining} days)`;
} else {
@@ -365,6 +494,34 @@ async function loadWarranties() {
console.log('Loading warranties...');
showLoading();
+ // Get expiring soon days from user preferences if available
+ try {
+ const prefsResponse = await fetch('/api/auth/preferences', {
+ headers: {
+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
+ }
+ });
+
+ if (prefsResponse.ok) {
+ const data = await prefsResponse.json();
+ if (data && data.expiring_soon_days) {
+ const oldValue = expiringSoonDays;
+ expiringSoonDays = data.expiring_soon_days;
+ console.log('Updated expiring soon days from preferences:', expiringSoonDays);
+
+ // If we already have warranties loaded and the value changed, reprocess them
+ if (warranties && warranties.length > 0 && oldValue !== expiringSoonDays) {
+ console.log('Reprocessing warranties with new expiringSoonDays value');
+ warranties = warranties.map(warranty => processWarrantyData(warranty));
+ renderWarrantiesTable(warranties);
+ }
+ }
+ }
+ } catch (error) {
+ console.error('Error loading preferences:', error);
+ // Continue with default value
+ }
+
// Use the full URL to avoid path issues
const apiUrl = window.location.origin + '/api/warranties';
@@ -1338,7 +1495,7 @@ async function exportWarranties() {
if (daysRemaining < 0) {
warranty.status = 'Expired';
- } else if (daysRemaining < 30) {
+ } else if (daysRemaining < expiringSoonDays) {
warranty.status = 'Expiring Soon';
} else {
warranty.status = 'Active';
diff --git a/frontend/settings-new.html b/frontend/settings-new.html
index 07c3dfd..39d4bf7 100644
--- a/frontend/settings-new.html
+++ b/frontend/settings-new.html
@@ -355,11 +355,6 @@
<i class="fab fa-github"></i> GitHub
</a>
</div>
- <div class="settings-item">
- <a href="settings.html" class="settings-link">
- <i class="fas fa-cogs"></i> Old Settings
- </a>
- </div>
</div>
</div>
</div>
@@ -444,6 +439,16 @@
</div>
</div>
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Expiring Soon Days</label>
+ <p class="text-muted">Number of days before warranty expiration to mark as "Expiring Soon"</p>
+ </div>
+ <input type="number" id="expiringSoonDays" class="form-control" min="1" max="365" value="30">
+ </div>
+ </div>
+
<button type="button" id="savePreferencesBtn" class="btn btn-primary">Save Preferences</button>
</form>
</div>
diff --git a/frontend/settings-new.js b/frontend/settings-new.js
index 2bbc77e..b32daf6 100644
--- a/frontend/settings-new.js
+++ b/frontend/settings-new.js
@@ -3,6 +3,7 @@ const darkModeToggle = document.getElementById('darkModeToggle');
const darkModeToggleSetting = document.getElementById('darkModeToggleSetting');
const defaultViewSelect = document.getElementById('defaultView');
const emailNotificationsToggle = document.getElementById('emailNotifications');
+const expiringSoonDaysInput = document.getElementById('expiringSoonDays');
const saveProfileBtn = document.getElementById('saveProfileBtn');
const savePreferencesBtn = document.getElementById('savePreferencesBtn');
const changePasswordBtn = document.getElementById('changePasswordBtn');
@@ -319,7 +320,7 @@ async function loadUserData() {
}
/**
- * Load user preferences from localStorage
+ * Load user preferences from localStorage and API
*/
function loadPreferences() {
// Load dark mode preference
@@ -337,6 +338,22 @@ function loadPreferences() {
// Load email notifications preference (default to true if not set)
const emailNotifications = localStorage.getItem('emailNotifications') !== 'false';
emailNotificationsToggle.checked = emailNotifications;
+
+ // Load expiring soon days from API
+ fetch('/api/auth/preferences', {
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ })
+ .then(response => response.json())
+ .then(data => {
+ if (data && data.expiring_soon_days) {
+ expiringSoonDaysInput.value = data.expiring_soon_days;
+ }
+ })
+ .catch(error => {
+ console.error('Error loading preferences from API:', error);
+ });
}
/**
@@ -652,7 +669,40 @@ function savePreferences() {
const emailNotifications = emailNotificationsToggle.checked;
localStorage.setItem('emailNotifications', emailNotifications);
- showToast('Preferences saved successfully', 'success');
+ // Get expiring soon days value
+ let expiringSoonDays = parseInt(expiringSoonDaysInput.value);
+
+ // Validate expiring soon days
+ if (isNaN(expiringSoonDays) || expiringSoonDays < 1 || expiringSoonDays > 365) {
+ showToast('Expiring soon days must be between 1 and 365', 'error');
+ return;
+ }
+
+ // Save preferences to API
+ fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ default_view: defaultView,
+ email_notifications: emailNotifications,
+ theme: isDark ? 'dark' : 'light',
+ expiring_soon_days: expiringSoonDays
+ })
+ })
+ .then(response => {
+ if (response.ok) {
+ showToast('Preferences saved successfully', 'success');
+ } else {
+ throw new Error('Failed to save preferences to API');
+ }
+ })
+ .catch(error => {
+ console.error('Error saving preferences:', error);
+ showToast('Preferences saved locally, but failed to sync with server', 'warning');
+ });
}
/**
@@ -1722,20 +1772,17 @@ function showUsersList() {
console.log('=== SHOW USERS LIST COMPLETED ===');
}
-// Add the test API buttons when the page loads
-document.addEventListener('DOMContentLoaded', function() {
- // Add the test API buttons after a short delay to ensure the page is fully loaded
- setTimeout(addTestApiButtons, 1000);
-});
-
/**
* Promise-based version of findUserIdByUsername
* @param {string} username - The username to look up
* @returns {Promise<number|null>} - Promise that resolves to the user ID or null if not found
*/
function findUserIdByUsernameAsync(username) {
- return new Promise((resolve) => {
- findUserIdByUsername(username, resolve);
+ return new Promise((resolve, reject) => {
+ findUserIdByUsername(username, (err, userId) => {
+ if (err) reject(err);
+ else resolve(userId);
+ });
});
}
@@ -2014,104 +2061,6 @@ async function saveSiteSettings() {
}
}
-/**
- * Add test API buttons to the page
- */
-function addTestApiButtons() {
- console.log('Test API buttons function called but disabled');
- // Function disabled to prevent floating buttons from appearing
- // The functionality is now available through the admin action buttons in the Admin Settings section
- return;
-
- // Original code below is kept for reference but will not execute due to the return above
- console.log('Adding test API buttons to the page');
-
- // Create a container for the buttons
- const buttonContainer = document.createElement('div');
- buttonContainer.style.position = 'fixed';
- buttonContainer.style.bottom = '20px';
- buttonContainer.style.right = '20px';
- buttonContainer.style.zIndex = '9999';
- buttonContainer.style.display = 'flex';
- buttonContainer.style.flexDirection = 'column';
- buttonContainer.style.gap = '10px';
-
- // Create a button to check API endpoint
- const apiCheckBtn = document.createElement('button');
- apiCheckBtn.className = 'btn btn-info';
- apiCheckBtn.textContent = 'Check API Endpoint';
- apiCheckBtn.addEventListener('click', checkApiEndpoint);
-
- // Create a button to test user deletion
- const testDeleteBtn = document.createElement('button');
- testDeleteBtn.className = 'btn btn-danger';
- testDeleteBtn.textContent = 'Test User Deletion';
- testDeleteBtn.addEventListener('click', function() {
- const userId = prompt('Enter user ID to delete:');
- if (userId) {
- if (confirm(`Are you sure you want to delete user ID ${userId}?`)) {
- testUserDeletion(userId);
- }
- }
- });
-
- // Create a button to check permissions
- const checkPermissionsBtn = document.createElement('button');
- checkPermissionsBtn.className = 'btn btn-warning';
- checkPermissionsBtn.textContent = 'Check Admin Permissions';
- checkPermissionsBtn.addEventListener('click', checkAdminPermissions);
-
- // Create a button to show users
- const showUsersBtn = document.createElement('button');
- showUsersBtn.className = 'btn btn-primary';
- showUsersBtn.textContent = 'Show Users';
- showUsersBtn.addEventListener('click', showUsersList);
-
- // Add buttons to the container
- buttonContainer.appendChild(apiCheckBtn);
- buttonContainer.appendChild(testDeleteBtn);
- buttonContainer.appendChild(checkPermissionsBtn);
- buttonContainer.appendChild(showUsersBtn);
-
- // Add the container to the body
- document.body.appendChild(buttonContainer);
-
- console.log('Test API buttons added to the page');
-}
-
-/**
- * Check if the API endpoint is accessible
- */
-function checkApiEndpoint() {
- console.log('Checking API endpoint accessibility...');
-
- // Try to access a simple API endpoint
- fetch('/api/auth/validate-token', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`
- }
- })
- .then(response => {
- console.log('API endpoint check response status:', response.status);
- if (response.ok) {
- console.log('API endpoint is accessible');
- showToast('API endpoint is accessible', 'success');
- } else {
- console.error('API endpoint is not accessible');
- showToast('API endpoint is not accessible. Status: ' + response.status, 'error');
- }
- return response.json().catch(() => ({}));
- })
- .then(data => {
- console.log('API endpoint check response data:', data);
- })
- .catch(error => {
- console.error('Error checking API endpoint:', error);
- showToast('Error checking API endpoint: ' + error.message, 'error');
- });
-}
-
/**
* Set up the delete button for user deletion
*/
@@ -2309,4 +2258,37 @@ function directDeleteUserAPI(userId) {
reject(error);
});
});
+}
+
+/**
+ * Check if the API endpoint is accessible
+ */
+function checkApiEndpoint() {
+ console.log('Checking API endpoint accessibility...');
+
+ // Try to access a simple API endpoint
+ fetch('/api/auth/validate-token', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ })
+ .then(response => {
+ console.log('API endpoint check response status:', response.status);
+ if (response.ok) {
+ console.log('API endpoint is accessible');
+ showToast('API endpoint is accessible', 'success');
+ } else {
+ console.error('API endpoint is not accessible');
+ showToast('API endpoint is not accessible. Status: ' + response.status, 'error');
+ }
+ return response.json().catch(() => ({}));
+ })
+ .then(data => {
+ console.log('API endpoint check response data:', data);
+ })
+ .catch(error => {
+ console.error('Error checking API endpoint:', error);
+ showToast('Error checking API endpoint: ' + error.message, 'error');
+ });
}
\ No newline at end of file
diff --git a/frontend/simple-status.html b/frontend/simple-status.html
deleted file mode 100644
index fc4977e..0000000
--- a/frontend/simple-status.html
+++ /dev/null
@@ -1,35 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Simple Status Page</title>
- <style>
- body {
- font-family: Arial, sans-serif;
- text-align: center;
- padding: 50px;
- }
- .success {
- color: green;
- font-size: 24px;
- margin: 20px 0;
- }
- a {
- display: inline-block;
- padding: 10px 20px;
- background-color: #4CAF50;
- color: white;
- text-decoration: none;
- border-radius: 4px;
- margin-top: 20px;
- }
- </style>
-</head>
-<body>
- <h1>Simple Status Page</h1>
- <p class="success">If you can see this, basic navigation to the status page is working!</p>
- <p>This is a minimal test page with no JavaScript or external dependencies.</p>
- <a href="index.html">Back to Home</a>
-</body>
-</html>
\ No newline at end of file
diff --git a/frontend/status-simple.html b/frontend/status-simple.html
deleted file mode 100644
index 9cf4b83..0000000
--- a/frontend/status-simple.html
+++ /dev/null
@@ -1,109 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Simple Status Page with Chart.js</title>
- <link rel="stylesheet" href="style.css">
- <!-- Font Awesome for icons -->
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
- <!-- Chart.js for visualizations -->
- <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
- <style>
- .chart-container {
- width: 400px;
- height: 400px;
- margin: 50px auto;
- }
- </style>
-</head>
-<body>
- <!-- Header -->
- <header>
- <div class="container">
- <div class="app-title">
- <i class="fas fa-shield-alt"></i>
- <h1>Warranty Tracker</h1>
- </div>
- <div class="nav-links">
- <a href="index.html" class="nav-link">
- <i class="fas fa-home"></i> Home
- </a>
- <a href="status.html" class="nav-link">
- <i class="fas fa-chart-pie"></i> Status
- </a>
- <a href="simple-status.html" class="nav-link">
- <i class="fas fa-vial"></i> Simple Test
- </a>
- <a href="status-simple.html" class="nav-link active">
- <i class="fas fa-chart-line"></i> Simple Chart
- </a>
- <a href="page-test.html" class="nav-link">
- <i class="fas fa-sitemap"></i> Page Test
- </a>
- </div>
- </div>
- </header>
-
- <!-- Main Content -->
- <div class="container">
- <div class="status-content">
- <h2>Simple Chart.js Test</h2>
-
- <div class="chart-container">
- <canvas id="sampleChart"></canvas>
- </div>
-
- <div style="text-align: center; margin-top: 20px;">
- <a href="index.html" class="btn btn-primary">Back to Home</a>
- </div>
- </div>
- </div>
-
- <!-- Footer -->
- <footer>
- <div class="container">
- <p>&copy; 2023 Warracker. All rights reserved.</p>
- </div>
- </footer>
-
- <script>
- // Create a simple chart when the page loads
- document.addEventListener('DOMContentLoaded', function() {
- // Get the canvas element
- const ctx = document.getElementById('sampleChart').getContext('2d');
-
- // Sample data
- const data = {
- labels: ['Active', 'Expiring Soon', 'Expired'],
- datasets: [{
- data: [12, 5, 3],
- backgroundColor: [
- '#4CAF50', // Green for active
- '#FF9800', // Orange for expiring soon
- '#F44336' // Red for expired
- ],
- borderWidth: 1
- }]
- };
-
- // Create and render the chart
- const myChart = new Chart(ctx, {
- type: 'doughnut',
- data: data,
- options: {
- responsive: true,
- maintainAspectRatio: false,
- plugins: {
- legend: {
- position: 'bottom'
- }
- }
- }
- });
-
- console.log('Chart rendered successfully!');
- });
- </script>
-</body>
-</html>
\ No newline at end of file
diff --git a/frontend/status-test.html b/frontend/status-test.html
deleted file mode 100644
index 938fa6d..0000000
--- a/frontend/status-test.html
+++ /dev/null
@@ -1,79 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Status API Test</title>
- <style>
- body {
- font-family: Arial, sans-serif;
- line-height: 1.6;
- padding: 20px;
- max-width: 800px;
- margin: 0 auto;
- }
- pre {
- background-color: #f5f5f5;
- padding: 10px;
- border-radius: 5px;
- overflow-x: auto;
- }
- button {
- padding: 10px 15px;
- background-color: #4CAF50;
- color: white;
- border: none;
- border-radius: 4px;
- cursor: pointer;
- margin: 10px 0;
- }
- .error {
- color: #F44336;
- font-weight: bold;
- }
- </style>
-</head>
-<body>
- <h1>Status API Test</h1>
- <p>This page tests if the statistics API endpoint is working correctly.</p>
-
- <button id="testBtn">Test Statistics API</button>
-
- <h2>Results:</h2>
- <pre id="results">Click the button to test the API</pre>
-
- <script>
- document.getElementById('testBtn').addEventListener('click', async () => {
- const resultsElement = document.getElementById('results');
- resultsElement.textContent = 'Testing...';
-
- try {
- // Test with fetch API
- console.log('Testing /api/statistics endpoint...');
- const response = await fetch('/api/statistics');
-
- if (!response.ok) {
- const errorText = await response.text();
- throw new Error(`HTTP Error: ${response.status} - ${errorText}`);
- }
-
- const data = await response.json();
-
- // Display results
- resultsElement.textContent = 'SUCCESS! Statistics API returned:\n\n' +
- JSON.stringify(data, null, 2);
-
- // Create a direct link to main status page
- const linkElement = document.createElement('p');
- linkElement.innerHTML = '<a href="status.html">Go to Status Dashboard</a>';
- document.body.appendChild(linkElement);
-
- } catch (error) {
- console.error('API test failed:', error);
- resultsElement.innerHTML = `<span class="error">ERROR: ${error.message}</span>\n\n` +
- 'Check browser console for more details.';
- }
- });
- </script>
-</body>
-</html>
\ No newline at end of file
diff --git a/frontend/status.html b/frontend/status.html
index e1d2c6a..021cd30 100644
--- a/frontend/status.html
+++ b/frontend/status.html
@@ -264,21 +264,6 @@
<i class="fab fa-github"></i> GitHub
</a>
</div>
- <div class="settings-item">
- <a href="simple-status.html" class="settings-link">
- <i class="fas fa-vial"></i> Simple Test
- </a>
- </div>
- <div class="settings-item">
- <a href="api-test.html" class="settings-link">
- <i class="fas fa-terminal"></i> API Test
- </a>
- </div>
- <div class="settings-item">
- <a href="page-test.html" class="settings-link">
- <i class="fas fa-sitemap"></i> Page Test
- </a>
- </div>
</div>
</div>
</div>
diff --git a/frontend/status.js b/frontend/status.js
index 946e535..f82e0bd 100644
--- a/frontend/status.js
+++ b/frontend/status.js
@@ -16,7 +16,7 @@ const exportBtn = document.getElementById('exportBtn');
// Configuration
const API_BASE_URL = '/api/statistics'; // Base URL for statistics endpoint
const API_URL = window.location.origin + API_BASE_URL; // Full URL for statistics endpoint
-const EXPIRING_SOON_DAYS = 30; // Number of days to consider "expiring soon"
+let EXPIRING_SOON_DAYS = 30; // Default value, will be updated from user preferences
// Global variables for sorting and filtering
let currentSort = { column: 'expiration', direction: 'asc' };
@@ -468,8 +468,11 @@ function filterAndSortWarranties() {
// Filter warranties
let filteredWarranties = allWarranties.filter(warranty => {
+ // Skip warranties without proper dates
+ if (!warranty.expiration_date) return false;
+
// Apply search filter
- const productName = warranty.product_name.toLowerCase();
+ const productName = (warranty.product_name || '').toLowerCase();
const matchesSearch = searchTerm === '' || productName.includes(searchTerm);
// Apply status filter
@@ -500,16 +503,16 @@ function filterAndSortWarranties() {
switch (currentSort.column) {
case 'product':
- valueA = a.product_name;
- valueB = b.product_name;
+ valueA = a.product_name || '';
+ valueB = b.product_name || '';
break;
case 'purchase':
- valueA = new Date(a.purchase_date);
- valueB = new Date(b.purchase_date);
+ valueA = new Date(a.purchase_date || 0);
+ valueB = new Date(b.purchase_date || 0);
break;
case 'expiration':
- valueA = new Date(a.expiration_date);
- valueB = new Date(b.expiration_date);
+ valueA = new Date(a.expiration_date || 0);
+ valueB = new Date(b.expiration_date || 0);
break;
case 'status':
// Sort by status priority: active, expiring, expired
@@ -519,8 +522,8 @@ function filterAndSortWarranties() {
valueB = statusB;
break;
default:
- valueA = new Date(a.expiration_date);
- valueB = new Date(b.expiration_date);
+ valueA = new Date(a.expiration_date || 0);
+ valueB = new Date(b.expiration_date || 0);
}
// Compare values based on sort direction
@@ -578,6 +581,9 @@ function filterAndSortWarranties() {
filteredWarranties.forEach(warranty => {
const row = document.createElement('tr');
+ // Make sure we have valid data to work with
+ if (!warranty.expiration_date) return;
+
// Determine status
const expirationDate = new Date(warranty.expiration_date);
let status = 'active';
@@ -596,7 +602,7 @@ function filterAndSortWarranties() {
row.className = `status-${status}`;
// Format dates
- const purchaseDate = new Date(warranty.purchase_date).toLocaleDateString();
+ const purchaseDate = warranty.purchase_date ? new Date(warranty.purchase_date).toLocaleDateString() : 'N/A';
const formattedExpirationDate = expirationDate.toLocaleDateString();
// Status display
@@ -605,7 +611,7 @@ function filterAndSortWarranties() {
// Create table cells with proper structure
row.innerHTML = `
- <td>${warranty.product_name}</td>
+ <td>${warranty.product_name || 'Unknown Product'}</td>
<td>${purchaseDate}</td>
<td>${formattedExpirationDate}</td>
<td><span class="${statusClass}">${statusText}</span></td>
@@ -613,7 +619,7 @@ function filterAndSortWarranties() {
<a href="index.html?edit=${warranty.id}" class="action-btn edit-btn" title="Edit">
<i class="fas fa-edit"></i>
</a>
- <a href="#" onclick="openSecureFile('${warranty.invoice_path}'); return false;" class="action-btn view-btn" title="View Invoice" ${!warranty.invoice_path ? 'style="display: none;"' : ''}>
+ <a href="#" onclick="window.openSecureFile ? openSecureFile('${warranty.invoice_path || ''}') : alert('File viewer not available'); return false;" class="action-btn view-btn" title="View Invoice" ${!warranty.invoice_path ? 'style="display: none;"' : ''}>
<i class="fas fa-file-alt"></i>
</a>
</td>
@@ -655,10 +661,22 @@ function refreshDashboard() {
// Initialize the dashboard
async function initDashboard() {
- showLoading();
- hideError();
+ console.log('Initializing dashboard');
try {
+ // Show loading indicator
+ showLoading();
+
+ // Load user preferences
+ await loadUserPreferences();
+
+ // Check authentication
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ window.location.href = 'login.html';
+ return;
+ }
+
const data = await fetchStatistics();
console.log('API Response:', data); // Log the actual response for debugging
@@ -699,11 +717,33 @@ async function initDashboard() {
createStatusChart(summary);
createTimelineChart(timeline);
- // Update recent expirations table
+ // Update recent expirations table with the initial data
updateRecentExpirations(recentWarranties);
- // Store all warranties for filtering
- allWarranties = recentWarranties;
+ // Fetch all warranties for better filtering
+ try {
+ const allWarrantiesResponse = await fetch('/api/warranties', {
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (allWarrantiesResponse.ok) {
+ const allWarrantiesData = await allWarrantiesResponse.json();
+ // Store all warranties for filtering
+ allWarranties = allWarrantiesData;
+ console.log('Fetched all warranties for filtering:', allWarranties.length);
+ } 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');
+ }
+ } catch (error) {
+ console.error('Error fetching all warranties:', error);
+ // Fall back to recent warranties on error
+ allWarranties = recentWarranties;
+ }
// Set up event listeners for filtering and sorting
setupEventListeners();
@@ -884,7 +924,7 @@ function setupEventListeners() {
if (sortableHeaders) {
sortableHeaders.forEach(header => {
header.addEventListener('click', () => {
- const column = header.getAttribute('data-column');
+ const column = header.getAttribute('data-sort');
// Toggle direction if same column, otherwise default to ascending
if (currentSort.column === column) {
@@ -969,4 +1009,30 @@ function extractTimelineData(warranties) {
});
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