Skip to content

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

Notifications and QOL

sassanix8165b797d847
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1ebd01c..d6af161 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,29 @@
# Changelog
+
+## [0.9.8.3] - 2025-03-26
+
+### Added
+
+* **Authentication:** Users are now automatically logged in after successful registration, removing an extra step in the onboarding process.
+* **Notifications:** Introduced email notifications for warranty expiration alerts.
+* **Notifications:** Added user preferences to customize notification frequency (daily, weekly, monthly), preferred delivery time, and timezone.
+* **Admin:** Added controls for administrators to manually trigger notifications, useful for testing.
+
+### Changed
+
+* **Notifications:** Improved the reliability and processing efficiency of the backend notification system.
+* **UI:** Standardized the header's appearance and layout across all pages (home, status, settings) for a consistent look and feel.
+
+### Fixed
+
+* **Charts:** Resolved an issue where the status page timeline chart initially displayed incomplete data, requiring a theme toggle to show all months correctly. The chart now loads with complete data.
+* **Preferences:** Corrected an issue where preference changes made by an admin could unintentionally affect regular users' settings. Preferences are now stored separately based on user type.
+* **Preferences:** Fixed synchronization issues ensuring that view preferences set in the settings page are consistently applied throughout the application.
+* **File Access:** Resolved authentication errors ("Authentication token is missing!") that occurred when attempting to open attached invoice or manual files. Secure file access now correctly uses authentication tokens.
+* **File Uploads:** Corrected a critical bug where uploading only one document type (e.g., just an invoice) could inadvertently delete the existing document of the other type (e.g., the manual). Both documents are now preserved correctly during updates.
+
+
## [0.9.8.2] - 2025-03-22
- **Edit Warranty Modal Improvements**
diff --git a/Dockerfile b/Dockerfile
index 0665377..a3e103c 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -17,6 +17,7 @@ RUN pip install --no-cache-dir -r requirements.txt
# Copy backend code
COPY backend/app.py .
+COPY backend/gunicorn_config.py .
COPY backend/run_migrations.py .
COPY backend/fix_permissions.py .
COPY backend/fix_permissions.sql .
@@ -61,8 +62,8 @@ done\n\
echo "Running fix permissions script..."\n\
python /app/fix_permissions.py\n\
echo "Starting services..."\n\
-nginx\n\
-gunicorn --bind 0.0.0.0:5000 --workers 4 app:app\n\
+# Remove direct nginx call that conflicts with supervisor\n\
+gunicorn --bind 0.0.0.0:5000 --workers 4 --worker-class=sync --env GUNICORN_WORKER_CLASS=sync --env GUNICORN_WORKER_ID=0 app:app\n\
' > /app/start.sh && chmod +x /app/start.sh
# This is just a fallback, the copied nginx.conf will be used
@@ -118,25 +119,45 @@ COPY <<EOF /etc/supervisor/conf.d/supervisord.conf
[supervisord]
nodaemon=true
user=root
+logfile=/dev/stdout
+logfile_maxbytes=0
+pidfile=/var/run/supervisord.pid
[program:nginx]
command=nginx -g "daemon off;"
autostart=true
autorestart=true
+startretries=5
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
+priority=10
[program:gunicorn]
-command=/app/start.sh
+command=gunicorn --config /app/gunicorn_config.py app:app
directory=/app
autostart=true
autorestart=true
+startretries=5
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
+priority=20
+
+[program:migrations]
+command=bash -c "cd /app/migrations && python apply_migrations.py"
+directory=/app
+autostart=true
+autorestart=false
+startsecs=0
+startretries=3
+stdout_logfile=/dev/stdout
+stdout_logfile_maxbytes=0
+stderr_logfile=/dev/stderr
+stderr_logfile_maxbytes=0
+priority=5
EOF
# Make sure the uploads directory is writable
diff --git a/README.md b/README.md
index a3828e1..eea9664 100644
--- a/README.md
+++ b/README.md
@@ -153,7 +153,7 @@ warracker/
* Settings Page - **Completed ✅**
* Status Page - **Completed ✅**
* Customizing Reminders to any day needed - **Completed ✅**
-* Email Reminders for Expiring Warranties - **Planned**
+* Email Reminders for Expiring Warranties - **Completed ✅**
* Warranty Data Import (CSV) - **Planned**
* Improved Search and Filtering - **Planned**
* Warranty claim tracking - **Planned**
diff --git a/backend/app.py b/backend/app.py
index 1debb59..26d4f71 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -13,6 +13,14 @@ from flask_bcrypt import Bcrypt
import re
from functools import wraps
import uuid
+import smtplib
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+from apscheduler.schedulers.background import BackgroundScheduler
+import atexit
+from pytz import timezone as pytz_timezone
+import pytz
+import threading
app = Flask(__name__)
CORS(app, supports_credentials=True) # Enable CORS with credentials
@@ -110,124 +118,114 @@ def allowed_file(filename):
# Initialize database
def init_db():
- conn = None
+ """Initialize the database with required tables"""
try:
conn = get_db_connection()
- with conn.cursor() as cur:
- # Create warranties table if it doesn't exist
- cur.execute('''
- CREATE TABLE IF NOT EXISTS warranties (
- id SERIAL PRIMARY KEY,
- product_name TEXT NOT NULL,
- purchase_date DATE NOT NULL,
- warranty_years INTEGER NOT NULL,
- expiration_date DATE,
- invoice_path TEXT,
- manual_path TEXT,
- product_url TEXT,
- purchase_price DECIMAL(10, 2),
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- )
- ''')
-
- # Add user_id column if it doesn't exist - use DO block to avoid errors
- cur.execute('''
- DO $$
+ cur = conn.cursor()
+
+ # Create users table if it doesn't exist
+ cur.execute("""
+ CREATE TABLE IF NOT EXISTS users (
+ id SERIAL PRIMARY KEY,
+ username VARCHAR(50) UNIQUE NOT NULL,
+ email VARCHAR(100) UNIQUE NOT NULL,
+ password_hash VARCHAR(255) NOT NULL,
+ first_name VARCHAR(50),
+ last_name VARCHAR(50),
+ is_active BOOLEAN DEFAULT TRUE,
+ is_admin BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
+ )
+ """)
+
+ # Create user_preferences table if it doesn't exist
+ cur.execute("""
+ CREATE TABLE IF NOT EXISTS 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,
+ notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily',
+ notification_time VARCHAR(5) NOT NULL DEFAULT '09:00',
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ UNIQUE(user_id)
+ )
+ """)
+
+ # Check if timezone column exists and add if it doesn't
+ cur.execute("""
+ DO $$
+ BEGIN
+ IF NOT EXISTS (
+ SELECT column_name
+ FROM information_schema.columns
+ WHERE table_name = 'user_preferences' AND column_name = 'timezone'
+ ) THEN
+ ALTER TABLE user_preferences
+ ADD COLUMN timezone VARCHAR(50) NOT NULL DEFAULT 'UTC';
+ RAISE NOTICE 'Added timezone column to user_preferences table';
+ END IF;
+ END $$;
+ """)
+
+ # Create warranties table if it doesn't exist
+ cur.execute("""
+ CREATE TABLE IF NOT EXISTS warranties (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ item_name VARCHAR(100) NOT NULL,
+ purchase_date DATE NOT NULL,
+ expiration_date DATE NOT NULL,
+ purchase_price DECIMAL(10,2),
+ serial_number VARCHAR(100),
+ category VARCHAR(50),
+ notes TEXT,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
+ )
+ """)
+
+ # Create warranty_documents table if it doesn't exist
+ cur.execute("""
+ CREATE TABLE IF NOT EXISTS warranty_documents (
+ id INTEGER PRIMARY KEY,
+ warranty_id INTEGER NOT NULL REFERENCES warranties(id) ON DELETE CASCADE,
+ file_name VARCHAR(255) NOT NULL,
+ file_path VARCHAR(255) NOT NULL,
+ file_type VARCHAR(50),
+ file_size INTEGER,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
+ )
+ """)
+
+ # Create sequence if it doesn't exist
+ cur.execute("""
+ DO $$
BEGIN
- IF NOT EXISTS (
- SELECT column_name
- FROM information_schema.columns
- WHERE table_name='warranties' AND column_name='user_id'
- ) THEN
- ALTER TABLE warranties ADD COLUMN user_id INTEGER;
+ IF NOT EXISTS (SELECT 1 FROM pg_sequences WHERE sequencename = 'warranty_documents_id_seq') THEN
+ CREATE SEQUENCE warranty_documents_id_seq;
END IF;
END $$;
- ''')
-
- # Add indexes for faster queries
- cur.execute('CREATE INDEX IF NOT EXISTS idx_expiration_date ON warranties(expiration_date)')
- cur.execute('CREATE INDEX IF NOT EXISTS idx_product_name ON warranties(product_name)')
- cur.execute('CREATE INDEX IF NOT EXISTS idx_user_id ON warranties(user_id)')
-
- # Create serial numbers table
- cur.execute('''
- CREATE TABLE IF NOT EXISTS serial_numbers (
- id SERIAL PRIMARY KEY,
- warranty_id INTEGER NOT NULL,
- serial_number VARCHAR(255) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (warranty_id) REFERENCES warranties(id) ON DELETE CASCADE
- )
- ''')
-
- # Add indexes for serial numbers
- cur.execute('CREATE INDEX IF NOT EXISTS idx_warranty_id ON serial_numbers(warranty_id)')
- cur.execute('CREATE INDEX IF NOT EXISTS idx_serial_number ON serial_numbers(serial_number)')
-
- # Create users table
- cur.execute('''
- CREATE TABLE IF NOT EXISTS users (
- id SERIAL PRIMARY KEY,
- username VARCHAR(255) NOT NULL UNIQUE,
- email VARCHAR(255) NOT NULL UNIQUE,
- password_hash VARCHAR(255) NOT NULL,
- first_name VARCHAR(255),
- last_name VARCHAR(255),
- is_active BOOLEAN DEFAULT TRUE,
- is_admin BOOLEAN DEFAULT FALSE,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- last_login TIMESTAMP
- )
- ''')
-
- # Add indexes for users
- cur.execute('CREATE INDEX IF NOT EXISTS idx_username ON users(username)')
- cur.execute('CREATE INDEX IF NOT EXISTS idx_email ON users(email)')
-
- # Create password reset tokens table
- cur.execute('''
- CREATE TABLE IF NOT EXISTS password_reset_tokens (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL,
- token VARCHAR(255) NOT NULL,
- expires_at TIMESTAMP NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
- )
- ''')
-
- # Add indexes for password reset tokens
- cur.execute('CREATE INDEX IF NOT EXISTS idx_token ON password_reset_tokens(token)')
- cur.execute('CREATE INDEX IF NOT EXISTS idx_user_id_token ON password_reset_tokens(user_id)')
-
- # Create user sessions table
- cur.execute('''
- CREATE TABLE IF NOT EXISTS user_sessions (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL,
- session_token VARCHAR(255) NOT NULL,
- expires_at TIMESTAMP NOT NULL,
- ip_address VARCHAR(45),
- user_agent TEXT,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
- )
- ''')
-
- # Add indexes for user sessions
- cur.execute('CREATE INDEX IF NOT EXISTS idx_session_token ON user_sessions(session_token)')
- cur.execute('CREATE INDEX IF NOT EXISTS idx_user_id_session ON user_sessions(user_id)')
-
+ """)
+
+ # Alter table to use the sequence
+ cur.execute("""
+ ALTER TABLE warranty_documents
+ ALTER COLUMN id SET DEFAULT nextval('warranty_documents_id_seq');
+ """)
+
conn.commit()
+ cur.close()
+ conn.close()
logger.info("Database initialized successfully")
+
except Exception as e:
- logger.error(f"Database initialization error: {e}")
- if conn:
- conn.rollback()
+ logger.error(f"Database initialization error: {str(e)}")
raise
- finally:
- if conn:
- release_db_connection(conn)
# Authentication helper functions
def generate_token(user_id):
@@ -263,6 +261,10 @@ def token_required(f):
# If no token in header, check form data for POST requests
if not token and request.method == 'POST':
token = request.form.get('auth_token') # Check form data
+
+ # If still no token, check URL query parameters
+ if not token:
+ token = request.args.get('token') # Check query parameters
# If no token is provided
if not token:
@@ -343,6 +345,14 @@ def is_valid_password(password):
return False
return True
+def is_valid_timezone(tz):
+ """Validate if a timezone string is valid"""
+ try:
+ pytz.timezone(tz)
+ return True
+ except pytz.exceptions.UnknownTimeZoneError:
+ return False
+
# Authentication routes
@app.route('/api/auth/register', methods=['POST'])
def register():
@@ -428,6 +438,17 @@ def register():
# Update last login
cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
+ # Store session info
+ ip_address = request.remote_addr
+ user_agent = request.headers.get('User-Agent', '')
+ session_token = str(uuid.uuid4())
+ expires_at = datetime.utcnow() + app.config['JWT_EXPIRATION_DELTA']
+
+ cur.execute(
+ 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent) VALUES (%s, %s, %s, %s, %s)',
+ (user_id, session_token, expires_at, ip_address, user_agent)
+ )
+
conn.commit()
return jsonify({
@@ -831,15 +852,12 @@ def add_warranty():
return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
filename = secure_filename(invoice.filename)
- # Make filename unique by adding timestamp
filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
invoice_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
- # Ensure directory exists
- os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
-
invoice.save(invoice_path)
db_invoice_path = os.path.join('uploads', filename)
+ logger.info(f"New invoice uploaded: {db_invoice_path}")
# Handle manual file upload
db_manual_path = None
@@ -850,15 +868,12 @@ def add_warranty():
return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
filename = secure_filename(manual.filename)
- # Make filename unique by adding timestamp
filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_manual_{filename}"
manual_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
- # Ensure directory exists
- os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
-
manual.save(manual_path)
db_manual_path = os.path.join('uploads', filename)
+ logger.info(f"New manual uploaded: {db_manual_path}")
# Save to database
conn = get_db_connection()
@@ -1024,6 +1039,7 @@ def update_warranty(warranty_id):
invoice.save(invoice_path)
db_invoice_path = os.path.join('uploads', filename)
+ logger.info(f"New invoice uploaded: {db_invoice_path}")
# Remove old invoice file if exists and different from new one
cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
@@ -1032,6 +1048,12 @@ def update_warranty(warranty_id):
old_full_path = os.path.join('/data', old_invoice_path)
if os.path.exists(old_full_path):
os.remove(old_full_path)
+ logger.info(f"Removed old invoice: {old_invoice_path}")
+ else:
+ # If no new invoice file is uploaded, preserve the existing one
+ cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
+ db_invoice_path = cur.fetchone()[0]
+ logger.info(f"Preserving existing invoice: {db_invoice_path}")
# Handle manual file upload if new file is provided
db_manual_path = None
@@ -1047,6 +1069,7 @@ def update_warranty(warranty_id):
manual.save(manual_path)
db_manual_path = os.path.join('uploads', filename)
+ logger.info(f"New manual uploaded: {db_manual_path}")
# Remove old manual file if exists and different from new one
cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))
@@ -1055,15 +1078,50 @@ def update_warranty(warranty_id):
old_full_path = os.path.join('/data', old_manual_path)
if os.path.exists(old_full_path):
os.remove(old_full_path)
+ logger.info(f"Removed old manual: {old_manual_path}")
+ else:
+ # If no new manual file is uploaded, preserve the existing one
+ cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))
+ db_manual_path = cur.fetchone()[0]
+ logger.info(f"Preserving existing manual: {db_manual_path or 'None'}")
+
+ # Update the warranty in database - IMPORTANT: The database set operation needs to be updated
+ # Create a list of parameters for the UPDATE query
+ update_params = {
+ 'product_name': product_name,
+ 'purchase_date': purchase_date,
+ 'warranty_years': warranty_years,
+ 'expiration_date': expiration_date,
+ 'product_url': product_url,
+ 'purchase_price': purchase_price
+ }
- # Update the warranty in database
- cur.execute('''
- UPDATE warranties
- SET product_name = %s, purchase_date = %s, warranty_years = %s,
- expiration_date = %s, invoice_path = %s, manual_path = %s, product_url = %s, purchase_price = %s
- WHERE id = %s
- ''', (product_name, purchase_date, warranty_years, expiration_date,
- db_invoice_path, db_manual_path, product_url, purchase_price, warranty_id))
+ # Build dynamic SQL query based on which files have been uploaded or preserved
+ sql_fields = []
+ sql_values = []
+
+ for key, value in update_params.items():
+ sql_fields.append(f"{key} = %s")
+ sql_values.append(value)
+
+ # Only include invoice_path in the update if it's not None
+ if db_invoice_path is not None:
+ sql_fields.append("invoice_path = %s")
+ sql_values.append(db_invoice_path)
+
+ # Only include manual_path in the update if it's not None
+ if db_manual_path is not None:
+ sql_fields.append("manual_path = %s")
+ sql_values.append(db_manual_path)
+
+ # Add the warranty_id at the end
+ sql_values.append(warranty_id)
+
+ # Execute the dynamic SQL update
+ update_sql = f"UPDATE warranties SET {', '.join(sql_fields)} WHERE id = %s"
+ cur.execute(update_sql, sql_values)
+ logger.info(f"Updated warranty with SQL: {update_sql}")
+ logger.info(f"Parameters: {sql_values}")
# Update serial numbers
# First, delete existing serial numbers for this warranty
@@ -1079,6 +1137,7 @@ def update_warranty(warranty_id):
''', (warranty_id, serial_number.strip()))
conn.commit()
+
return jsonify({"message": "Warranty updated successfully"}), 200
except Exception as e:
@@ -1401,6 +1460,9 @@ def get_preferences():
default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
theme VARCHAR(10) NOT NULL DEFAULT 'light',
expiring_soon_days INTEGER NOT NULL DEFAULT 30,
+ notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily',
+ notification_time VARCHAR(5) NOT NULL DEFAULT '09:00',
+ timezone VARCHAR(50) NOT NULL DEFAULT 'UTC',
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(user_id)
@@ -1418,7 +1480,7 @@ def get_preferences():
# Get user preferences
cursor.execute(
"""
- SELECT email_notifications, default_view, theme, expiring_soon_days
+ SELECT email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone
FROM user_preferences
WHERE user_id = %s
""",
@@ -1431,9 +1493,9 @@ def get_preferences():
# Create default preferences if not exists
cursor.execute(
"""
- 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
+ INSERT INTO user_preferences (user_id, email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone)
+ VALUES (%s, TRUE, 'grid', 'light', 30, 'daily', '09:00', 'UTC')
+ RETURNING email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone
""",
(user_id,)
)
@@ -1446,7 +1508,10 @@ def get_preferences():
'email_notifications': preferences_data[0],
'default_view': preferences_data[1],
'theme': preferences_data[2],
- 'expiring_soon_days': preferences_data[3]
+ 'expiring_soon_days': preferences_data[3],
+ 'notification_frequency': preferences_data[4],
+ 'notification_time': preferences_data[5],
+ 'timezone': preferences_data[6]
}
return jsonify(preferences), 200
@@ -1460,7 +1525,10 @@ def get_preferences():
'email_notifications': True,
'default_view': 'grid',
'theme': 'light',
- 'expiring_soon_days': 30
+ 'expiring_soon_days': 30,
+ 'notification_frequency': 'daily',
+ 'notification_time': '09:00',
+ 'timezone': 'UTC'
}
return jsonify(default_preferences), 200
@@ -1476,7 +1544,10 @@ def get_preferences():
'email_notifications': True,
'default_view': 'grid',
'theme': 'light',
- 'expiring_soon_days': 30
+ 'expiring_soon_days': 30,
+ 'notification_frequency': 'daily',
+ 'notification_time': '09:00',
+ 'timezone': 'UTC'
}
return jsonify(default_preferences), 200
@@ -1498,6 +1569,9 @@ def update_preferences():
default_view = data.get('default_view')
theme = data.get('theme')
expiring_soon_days = data.get('expiring_soon_days')
+ notification_frequency = data.get('notification_frequency')
+ notification_time = data.get('notification_time')
+ timezone = data.get('timezone')
# Validate input
if default_view and default_view not in ['grid', 'list', 'table']:
@@ -1514,11 +1588,29 @@ def update_preferences():
except ValueError:
return jsonify({'message': 'Expiring soon days must be a valid number'}), 400
+ if notification_frequency and notification_frequency not in ['daily', 'weekly', 'monthly']:
+ return jsonify({'message': 'Invalid notification frequency'}), 400
+
+ if notification_time and not re.match(r'^([01]?[0-9]|2[0-3]):[0-5][0-9]$', notification_time):
+ return jsonify({'message': 'Invalid notification time format'}), 400
+
+ if timezone and not is_valid_timezone(timezone):
+ return jsonify({'message': 'Invalid timezone'}), 400
+
# Get database connection
conn = get_db_connection()
cursor = conn.cursor()
try:
+ # Check if timezone column exists in user_preferences
+ cursor.execute("""
+ SELECT column_name
+ FROM information_schema.columns
+ WHERE table_name = 'user_preferences' AND column_name = 'timezone'
+ """)
+
+ has_timezone_column = cursor.fetchone() is not None
+
# Check if user_preferences table exists
cursor.execute("""
SELECT EXISTS (
@@ -1539,6 +1631,9 @@ def update_preferences():
default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
theme VARCHAR(10) NOT NULL DEFAULT 'light',
expiring_soon_days INTEGER NOT NULL DEFAULT 30,
+ notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily',
+ notification_time VARCHAR(5) NOT NULL DEFAULT '09:00',
+ timezone VARCHAR(50) NOT NULL DEFAULT 'UTC',
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(user_id)
@@ -1584,21 +1679,43 @@ def update_preferences():
update_fields.append("expiring_soon_days = %s")
update_values.append(expiring_soon_days)
+ if notification_frequency:
+ update_fields.append("notification_frequency = %s")
+ update_values.append(notification_frequency)
+
+ if notification_time:
+ update_fields.append("notification_time = %s")
+ update_values.append(notification_time)
+
+ if timezone and has_timezone_column:
+ update_fields.append("timezone = %s")
+ update_values.append(timezone)
+
if update_fields:
+ # Construct return fields based on whether timezone column exists
+ return_fields = "email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time"
+ if has_timezone_column:
+ return_fields += ", timezone"
+
update_query = f"""
UPDATE user_preferences
SET {', '.join(update_fields)}, updated_at = NOW()
WHERE user_id = %s
- RETURNING email_notifications, default_view, theme, expiring_soon_days
+ RETURNING {return_fields}
"""
cursor.execute(update_query, update_values + [user_id])
preferences_data = cursor.fetchone()
else:
# No fields to update
+ # Construct select fields based on whether timezone column exists
+ select_fields = "email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time"
+ if has_timezone_column:
+ select_fields += ", timezone"
+
cursor.execute(
- """
- SELECT email_notifications, default_view, theme, expiring_soon_days
+ f"""
+ SELECT {select_fields}
FROM user_preferences
WHERE user_id = %s
""",
@@ -1607,26 +1724,59 @@ def update_preferences():
preferences_data = cursor.fetchone()
else:
# Create new preferences
- cursor.execute(
- """
- INSERT INTO user_preferences (
- user_id,
- email_notifications,
- default_view,
- theme,
- expiring_soon_days
+ # Check for timezone column to adjust INSERT statement
+ if has_timezone_column:
+ cursor.execute(
+ """
+ INSERT INTO user_preferences (
+ user_id,
+ email_notifications,
+ default_view,
+ theme,
+ expiring_soon_days,
+ notification_frequency,
+ notification_time,
+ timezone
+ )
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
+ RETURNING email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone
+ """,
+ (
+ 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,
+ notification_frequency or 'daily',
+ notification_time or '09:00',
+ timezone or 'UTC'
+ )
)
- 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',
- expiring_soon_days if expiring_soon_days is not None else 30
+ else:
+ cursor.execute(
+ """
+ INSERT INTO user_preferences (
+ user_id,
+ email_notifications,
+ default_view,
+ theme,
+ expiring_soon_days,
+ notification_frequency,
+ notification_time
+ )
+ VALUES (%s, %s, %s, %s, %s, %s, %s)
+ RETURNING email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time
+ """,
+ (
+ 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,
+ notification_frequency or 'daily',
+ notification_time or '09:00'
+ )
)
- )
preferences_data = cursor.fetchone()
# Format preferences data
@@ -1634,9 +1784,17 @@ def update_preferences():
'email_notifications': preferences_data[0],
'default_view': preferences_data[1],
'theme': preferences_data[2],
- 'expiring_soon_days': preferences_data[3]
+ 'expiring_soon_days': preferences_data[3],
+ 'notification_frequency': preferences_data[4],
+ 'notification_time': preferences_data[5]
}
+ # Add timezone if column exists
+ if has_timezone_column and len(preferences_data) > 6:
+ preferences['timezone'] = preferences_data[6]
+ else:
+ preferences['timezone'] = timezone or 'UTC'
+
conn.commit()
return jsonify(preferences), 200
@@ -1650,7 +1808,10 @@ def update_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
+ 'expiring_soon_days': expiring_soon_days if expiring_soon_days is not None else 30,
+ 'notification_frequency': notification_frequency or 'daily',
+ 'notification_time': notification_time or '09:00',
+ 'timezone': timezone or 'UTC'
}
return jsonify(fallback_preferences), 200
@@ -1666,7 +1827,10 @@ def update_preferences():
'email_notifications': True,
'default_view': 'grid',
'theme': 'light',
- 'expiring_soon_days': 30
+ 'expiring_soon_days': 30,
+ 'notification_frequency': 'daily',
+ 'notification_time': '09:00',
+ 'timezone': 'UTC'
}
return jsonify(default_preferences), 200
@@ -2032,15 +2196,530 @@ def secure_file_access(filename):
logger.error(f"Error in secure file access for {filename}: {e}")
return jsonify({"message": "Error accessing file"}), 500
+def get_expiring_warranties():
+ """
+ Query the database to find warranties that are expiring soon based on user preferences.
+ Returns a list of dictionaries containing the necessary information for email notifications.
+ """
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Get today's date
+ today = date.today()
+
+ cur.execute("""
+ SELECT
+ u.email,
+ u.first_name,
+ w.product_name,
+ w.expiration_date,
+ COALESCE(up.expiring_soon_days, 30) AS expiring_soon_days
+ FROM
+ warranties w
+ JOIN
+ users u ON w.user_id = u.id
+ LEFT JOIN
+ user_preferences up ON u.id = up.user_id
+ WHERE
+ w.expiration_date > %s
+ AND w.expiration_date <= %s + (COALESCE(up.expiring_soon_days, 30) || ' days')::interval
+ AND u.is_active = TRUE
+ AND COALESCE(up.email_notifications, TRUE) = TRUE;
+ """, (today, today))
+
+ expiring_warranties = []
+ for row in cur.fetchall():
+ email, first_name, product_name, expiration_date, expiring_soon_days = row
+ expiration_date_str = expiration_date.strftime('%Y-%m-%d')
+ expiring_warranties.append({
+ 'email': email,
+ 'first_name': first_name or 'User', # Default if first_name is NULL
+ 'product_name': product_name,
+ 'expiration_date': expiration_date_str,
+ })
+
+ return expiring_warranties
+
+ except Exception as e:
+ logger.error(f"Error retrieving expiring warranties: {e}")
+ return [] # Return an empty list on error
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+def format_expiration_email(user, warranties):
+ """
+ Format an email notification for expiring warranties.
+ Returns a MIMEMultipart email object with both text and HTML versions.
+ """
+ subject = "Warracker: Upcoming Warranty Expirations"
+
+ # Create both plain text and HTML versions of the email body
+ text_body = f"Hello {user['first_name']},\n\n"
+ text_body += "The following warranties are expiring soon:\n\n"
+
+ html_body = f"""\
+ <html>
+ <head></head>
+ <body>
+ <p>Hello {user['first_name']},</p>
+ <p>The following warranties are expiring soon:</p>
+ <table border="1" style="border-collapse: collapse;">
+ <thead>
+ <tr>
+ <th style="padding: 8px; text-align: left;">Product Name</th>
+ <th style="padding: 8px; text-align: left;">Expiration Date</th>
+ </tr>
+ </thead>
+ <tbody>
+ """
+
+ for warranty in warranties:
+ text_body += f"- {warranty['product_name']} (expires on {warranty['expiration_date']})\n"
+ html_body += f"""\
+ <tr>
+ <td style="padding: 8px;">{warranty['product_name']}</td>
+ <td style="padding: 8px;">{warranty['expiration_date']}</td>
+ </tr>
+ """
+
+ text_body += "\nLog in to Warracker to view details:\n"
+ text_body += "http://localhost:8080\n\n"
+ text_body += "Manage your notification settings:\n"
+ text_body += "http://localhost:8080/settings.html\n"
+
+ html_body += f"""\
+ </tbody>
+ </table>
+ <p>Log in to <a href="http://localhost:8080">Warracker</a> to view details.</p>
+ <p>Manage your notification settings <a href="http://localhost:8080/settings.html">here</a>.</p>
+ </body>
+ </html>
+ """
+
+ # Create a MIMEMultipart object for both text and HTML
+ msg = MIMEMultipart('alternative')
+ msg['Subject'] = subject
+ msg['From'] = os.environ.get('SMTP_USERNAME', '[email protected]')
+ msg['To'] = user['email']
+
+ part1 = MIMEText(text_body, 'plain')
+ part2 = MIMEText(html_body, 'html')
+
+ msg.attach(part1)
+ msg.attach(part2)
+
+ return msg
+
+# Create a lock for the notification function
+notification_lock = threading.Lock()
+# Track when notifications were last sent to each user
+last_notification_sent = {}
+
+def send_expiration_notifications(manual_trigger=False):
+ """
+ Main function to send warranty expiration notifications.
+ Retrieves expiring warranties, groups them by user, and sends emails.
+
+ Args:
+ manual_trigger (bool): Whether this function was triggered manually (vs scheduled)
+ If True, it ignores notification frequency/time preferences
+ """
+ # Use a lock to prevent concurrent executions
+ if not notification_lock.acquire(blocking=False):
+ logger.info("Notification job already running, skipping this execution")
+ return
+
+ try:
+ logger.info("Starting expiration notification process")
+
+ # If not manually triggered, check if notifications should be sent today based on preferences
+ if not manual_trigger:
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Get today's date and current time in UTC
+ utc_now = datetime.utcnow()
+
+ # Get user IDs that should receive notifications today
+ eligible_users_query = """
+ SELECT
+ u.id,
+ u.email,
+ u.first_name,
+ up.notification_time,
+ up.timezone,
+ up.notification_frequency
+ FROM users u
+ JOIN user_preferences up ON u.id = up.user_id
+ WHERE u.is_active = TRUE
+ AND up.email_notifications = TRUE
+ """
+ cur.execute(eligible_users_query)
+ eligible_users = cur.fetchall()
+
+ if not eligible_users:
+ logger.info("No users are eligible for notifications")
+ return
+
+ # Check if we should send notifications based on time and timezone
+ users_for_current_time = []
+ for user in eligible_users:
+ user_id, email, first_name, notification_time, timezone, frequency = user
+
+ try:
+ # Convert UTC time to user's timezone
+ user_tz = pytz_timezone(timezone or 'UTC')
+ user_local_time = utc_now.replace(tzinfo=pytz.UTC).astimezone(user_tz)
+
+ # Check if notification should be sent based on frequency
+ should_send = False
+
+ if frequency == 'daily':
+ should_send = True
+ elif frequency == 'weekly' and user_local_time.weekday() == 0: # Monday
+ should_send = True
+ elif frequency == 'monthly' and user_local_time.day == 1:
+ should_send = True
+
+ if should_send:
+ # Parse notification time
+ time_hour, time_minute = map(int, notification_time.split(':'))
+
+ # Get current hour and minute in user's timezone
+ current_hour = user_local_time.hour
+ current_minute = user_local_time.minute
+
+ # Calculate minutes difference
+ user_minutes = time_hour * 60 + time_minute
+ current_minutes = current_hour * 60 + current_minute
+
+ # Calculate exact time difference (can be negative if current time is before notification time)
+ time_diff = current_minutes - user_minutes
+
+ # For notifications, we want to send:
+ # 1. If current time is 0-2 minutes after scheduled time (11:27 → send between 11:27-11:29)
+ # 2. Or, if the next scheduler run would miss the time (scheduler runs every 5 min)
+ # For example, if it's 11:24 and notification is set for 11:27, next run is 11:29 so we should send now
+ send_window = time_diff >= 0 and time_diff <= 2 # 0-2 minutes after scheduled time
+ next_miss_window = time_diff < 0 and time_diff >= -3 # 1-3 minutes before scheduled time
+
+ logger.info(f"Time check for {email}: scheduled={time_hour}:{time_minute:02d}, " +
+ f"current={current_hour}:{current_minute:02d}, diff={time_diff} min, " +
+ f"send_window={send_window}, next_miss_window={next_miss_window}")
+
+ if send_window or next_miss_window:
+ # Check if we've already sent a notification to this user recently
+ now_timestamp = int(utc_now.timestamp())
+ if email in last_notification_sent:
+ last_sent = last_notification_sent[email]
+ # Only send if it's been more than 10 minutes since the last notification
+ # (longer than the 5-minute scheduler interval)
+ if now_timestamp - last_sent > 600:
+ users_for_current_time.append(user_id)
+ logger.info(f"User {email} eligible for notification at their local time {notification_time} ({timezone})")
+ else:
+ logger.info(f"Skipping notification for {email} - already sent within the last 10 minutes (last sent: {datetime.fromtimestamp(last_sent).strftime('%Y-%m-%d %H:%M:%S')})")
+ else:
+ users_for_current_time.append(user_id)
+ logger.info(f"User {email} eligible for notification at their local time {notification_time} ({timezone})")
+
+ except Exception as e:
+ logger.error(f"Error processing timezone for user {email}: {e}")
+ continue
+
+ if not users_for_current_time:
+ logger.info("No users are scheduled for notifications at their local time")
+ return
+
+ logger.info(f"Found {len(users_for_current_time)} users eligible for notifications now")
+ except Exception as e:
+ logger.error(f"Error determining notification eligibility: {e}")
+ return
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+ expiring_warranties = get_expiring_warranties()
+ if not expiring_warranties:
+ logger.info("No expiring warranties found.")
+ return
+
+ # Group warranties by user
+ users_warranties = {}
+ for warranty in expiring_warranties:
+ email = warranty['email']
+ if email not in users_warranties:
+ users_warranties[email] = {
+ 'first_name': warranty['first_name'],
+ 'warranties': []
+ }
+ users_warranties[email]['warranties'].append(warranty)
+
+ # Get SMTP settings from environment variables with fallbacks
+ smtp_host = os.environ.get('SMTP_HOST', 'localhost')
+ smtp_port = int(os.environ.get('SMTP_PORT', '1025'))
+ smtp_username = os.environ.get('SMTP_USERNAME', '[email protected]')
+ smtp_password = os.environ.get('SMTP_PASSWORD', '')
+
+ # Connect to SMTP server
+ try:
+ # Use SMTP_SSL for port 465, regular SMTP for other ports
+ if smtp_port == 465:
+ import smtplib
+ logger.info(f"Using SMTP_SSL connection for port 465")
+ server = smtplib.SMTP_SSL(smtp_host, smtp_port)
+ else:
+ server = smtplib.SMTP(smtp_host, smtp_port)
+ # Start TLS for security if not local debug server and not using SSL
+ if smtp_host != 'localhost':
+ server.starttls()
+
+ # Login if credentials are provided
+ if smtp_username and smtp_password:
+ logger.info(f"Logging in with username: {smtp_username}")
+ server.login(smtp_username, smtp_password)
+
+ # Send emails to each user
+ utc_now = datetime.utcnow()
+ timestamp = int(utc_now.timestamp())
+
+ emails_sent = 0
+ for email, user_data in users_warranties.items():
+ # For manual triggers, check if we've sent recently
+ if manual_trigger and email in last_notification_sent:
+ last_sent = last_notification_sent[email]
+ # Only allow manual trigger to bypass the time limit if it's been more than 2 minutes
+ # This prevents accidental double-clicks by admins
+ if timestamp - last_sent < 120:
+ logger.info(f"Manual trigger: Skipping notification for {email} - already sent within the last 2 minutes")
+ continue
+
+ msg = format_expiration_email(
+ {'first_name': user_data['first_name'], 'email': email},
+ user_data['warranties']
+ )
+ try:
+ server.sendmail(smtp_username, email, msg.as_string())
+ # Record timestamp when we sent the notification
+ last_notification_sent[email] = timestamp
+ emails_sent += 1
+ logger.info(f"Expiration notification email sent to {email} for {len(user_data['warranties'])} warranties at {datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')}")
+ except Exception as e:
+ logger.error(f"Error sending email to {email}: {e}")
+
+ logger.info(f"Email notification process completed. Sent {emails_sent} emails out of {len(users_warranties)} eligible users.")
+ # Close the server connection
+ server.quit()
+
+ except Exception as e:
+ logger.error(f"Error connecting to SMTP server: {e}")
+ logger.error(f"SMTP details - Host: {smtp_host}, Port: {smtp_port}, Username: {smtp_username}")
+
+ except Exception as e:
+ logger.error(f"Error in send_expiration_notifications: {e}")
+ finally:
+ notification_lock.release()
+
+# Initialize scheduler
+scheduler = BackgroundScheduler(
+ job_defaults={
+ 'coalesce': True, # Combine multiple executions into one
+ 'max_instances': 1, # Only allow one instance of the job to run at a time
+ 'misfire_grace_time': 300 # Allow 5 minutes for a misfired job (increased from 60 seconds)
+ }
+)
+
+# Helper to check if this is the main process that should run the scheduler
+def should_run_scheduler():
+ # For gunicorn
+ if os.environ.get('GUNICORN_WORKER_PROCESS_NAME') == 'worker-0' or \
+ (os.environ.get('GUNICORN_WORKER_CLASS') and int(os.environ.get('GUNICORN_WORKER_ID', '0')) == 0):
+ logger.info("Starting scheduler in Gunicorn worker 0")
+ return True
+ # For development server
+ elif __name__ == '__main__':
+ logger.info("Starting scheduler in development server")
+ return True
+ # Default case - don't start scheduler
+ return False
+
+# Only start the scheduler in the main process, not in workers
+if should_run_scheduler():
+ # Check for scheduled notifications every 2 minutes for more precise timing
+ scheduler.add_job(func=send_expiration_notifications, trigger="interval", minutes=2, id='notification_job')
+ scheduler.start()
+ logger.info("Email notification scheduler started - checking every 2 minutes")
+
+ # Add a shutdown hook
+ atexit.register(lambda: scheduler.shutdown())
+
# Initialize the database when the application starts
-try:
- init_db()
- logger.info("Database initialized during application startup")
-except Exception as e:
- logger.error(f"Database initialization error during startup: {e}")
+if __name__ != '__main__': # Only for production
+ try:
+ init_db()
+ logger.info("Database initialized during application startup")
+ except Exception as e:
+ logger.error(f"Database initialization error during startup: {e}")
if __name__ == '__main__':
try:
app.run(debug=os.environ.get('FLASK_DEBUG', '0') == '1', host='0.0.0.0')
except Exception as e:
- logger.error(f"Application startup error: {e}")
\ No newline at end of file
+ logger.error(f"Application startup error: {e}")
+
+# Move this code before the if __name__ == '__main__' block
[email protected]('/api/admin/send-notifications', methods=['POST'])
+@admin_required
+def trigger_notifications():
+ """
+ Admin-only endpoint to manually trigger warranty expiration notifications.
+ Useful for testing and for sending notifications outside the scheduled time.
+ """
+ try:
+ logger.info(f"Manual notification trigger requested by admin user {request.user['id']}")
+ send_expiration_notifications(manual_trigger=True)
+ return jsonify({'message': 'Notifications triggered successfully'}), 200
+ except Exception as e:
+ error_msg = f"Error triggering notifications: {str(e)}"
+ logger.error(error_msg)
+ return jsonify({'message': 'Failed to trigger notifications', 'error': error_msg}), 500
+
[email protected]('/api/timezones', methods=['GET'])
+def get_timezones():
+ """Get list of all available timezones"""
+ try:
+ # Get all timezones from pytz
+ all_timezones = pytz.all_timezones
+
+ # Group timezones by region
+ timezone_groups = {}
+ for tz in all_timezones:
+ # Split timezone into parts (e.g., 'America/New_York' -> ['America', 'New_York'])
+ parts = tz.split('/')
+
+ if len(parts) > 1:
+ region = parts[0]
+ city = '/'.join(parts[1:]).replace('_', ' ')
+
+ if region not in timezone_groups:
+ timezone_groups[region] = []
+
+ timezone_groups[region].append({
+ 'value': tz,
+ 'label': f"{city} ({tz})"
+ })
+ else:
+ # Handle special cases like 'UTC'
+ if 'Other' not in timezone_groups:
+ timezone_groups['Other'] = []
+ timezone_groups['Other'].append({
+ 'value': tz,
+ 'label': tz
+ })
+
+ # Convert to list of groups
+ timezone_list = [
+ {
+ 'region': region,
+ 'timezones': sorted(timezones, key=lambda x: x['label'])
+ }
+ for region, timezones in sorted(timezone_groups.items())
+ ]
+
+ return jsonify(timezone_list), 200
+ except Exception as e:
+ logger.error(f"Error getting timezones: {e}")
+ return jsonify({'message': 'Failed to get timezones'}), 500
+
[email protected]('/api/debug/warranty/<int:warranty_id>', methods=['GET'])
+@token_required
+def debug_warranty(warranty_id):
+ conn = None
+ try:
+ user_id = request.user['id']
+ is_admin = request.user['is_admin']
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # If admin, can see any warranty, otherwise only user's warranties
+ if is_admin:
+ cur.execute('SELECT * FROM warranties WHERE id = %s', (warranty_id,))
+ else:
+ cur.execute('SELECT * FROM warranties WHERE id = %s AND user_id = %s',
+ (warranty_id, user_id))
+
+ warranty = cur.fetchone()
+ if not warranty:
+ return jsonify({"error": "Warranty not found or you don't have permission to view it"}), 404
+
+ columns = [desc[0] for desc in cur.description]
+ warranty_dict = dict(zip(columns, warranty))
+
+ # Convert date objects to ISO format strings for JSON serialization
+ for key, value in warranty_dict.items():
+ if isinstance(value, (datetime, date)):
+ warranty_dict[key] = value.isoformat()
+ # Convert Decimal objects to float for JSON serialization
+ elif isinstance(value, Decimal):
+ warranty_dict[key] = float(value)
+
+ # Get serial numbers for this warranty
+ cur.execute('SELECT id, serial_number FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))
+ serial_numbers = [{
+ 'id': row[0],
+ 'serial_number': row[1]
+ } for row in cur.fetchall()]
+ warranty_dict['serial_numbers'] = serial_numbers
+
+ return jsonify({
+ 'warranty': warranty_dict,
+ 'columns': columns
+ })
+ except Exception as e:
+ logger.error(f"Error retrieving warranty debug info: {e}")
+ return jsonify({"error": f"Failed to retrieve warranty debug info: {str(e)}"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/debug/file-check', methods=['GET'])
+@token_required
+def debug_file_check():
+ if not request.user.get('is_admin', False):
+ return jsonify({"error": "Admin access required"}), 403
+
+ filepath = request.args.get('path')
+ if not filepath:
+ return jsonify({"error": "No file path provided"}), 400
+
+ # Check if this is just a filename or a path
+ if '/' not in filepath:
+ filepath = os.path.join('uploads', filepath)
+
+ # Prepend /data if it doesn't start with it
+ if not filepath.startswith('/data'):
+ full_path = os.path.join('/data', filepath)
+ else:
+ full_path = filepath
+
+ result = {
+ 'requested_path': filepath,
+ 'full_path': full_path,
+ 'exists': os.path.exists(full_path),
+ 'is_file': os.path.isfile(full_path) if os.path.exists(full_path) else False,
+ 'size_bytes': os.path.getsize(full_path) if os.path.exists(full_path) and os.path.isfile(full_path) else None,
+ 'last_modified': None
+ }
+
+ if result['exists'] and result['is_file']:
+ try:
+ stat_info = os.stat(full_path)
+ result['last_modified'] = datetime.fromtimestamp(stat_info.st_mtime).isoformat()
+ result['size_human'] = f"{result['size_bytes'] / 1024:.2f} KB" if result['size_bytes'] else None
+ except Exception as e:
+ result['error'] = str(e)
+
+ return jsonify(result)
\ No newline at end of file
diff --git a/backend/fix_permissions.sql b/backend/fix_permissions.sql
index 82fdfe6..b8b6522 100644
--- a/backend/fix_permissions.sql
+++ b/backend/fix_permissions.sql
@@ -40,7 +40,7 @@ DO $$
DECLARE
rec RECORD;
BEGIN
- FOR rec IN SELECT proname, oid FROM pg_proc p JOIN pg_namespace n ON p.pronamespace = n.oid WHERE n.nspname = 'public'
+ FOR rec IN SELECT proname, p.oid FROM pg_proc p JOIN pg_namespace n ON p.pronamespace = n.oid WHERE n.nspname = 'public'
LOOP
BEGIN
EXECUTE 'ALTER FUNCTION public.' || quote_ident(rec.proname) || '(' || pg_get_function_arguments(rec.oid) || ') OWNER TO warranty_user';
diff --git a/backend/gunicorn_config.py b/backend/gunicorn_config.py
new file mode 100644
index 0000000..29324dc
--- /dev/null
+++ b/backend/gunicorn_config.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Gunicorn configuration file for Warracker application.
+This ensures scheduler only runs in one worker process.
+"""
+
+import os
+import multiprocessing
+
+# Server configurations
+bind = "0.0.0.0:5000"
+workers = 4
+worker_class = "sync"
+timeout = 120
+keepalive = 5
+
+# Set worker environment variables
+def worker_int(worker):
+ """Called just after a worker exited on SIGINT or SIGQUIT."""
+ print(f"Worker {worker.pid} received SIGINT/SIGQUIT")
+
+def worker_abort(worker):
+ """Called when a worker receives the SIGABRT signal."""
+ print(f"Worker {worker.pid} received SIGABRT")
+
+def worker_exit(server, worker):
+ """Called just after a worker has been exited."""
+ print(f"Worker {worker.pid} exited")
+
+def on_starting(server):
+ """Called just before the master process is initialized."""
+ print("Server is starting")
+
+def post_fork(server, worker):
+ """Called just after a worker has been forked."""
+ os.environ["GUNICORN_WORKER_ID"] = str(worker.age - 1) # Worker ID starts at 0
+ os.environ["GUNICORN_WORKER_PROCESS_NAME"] = f"worker-{worker.age - 1}"
+ os.environ["GUNICORN_WORKER_CLASS"] = worker_class
+
+ print(f"Worker {worker.pid} (ID: {worker.age - 1}) forked")
+
+def pre_fork(server, worker):
+ """Called just before a worker is forked."""
+ print(f"Forking worker #{worker.age}")
+
+print(f"Gunicorn configuration loaded with {workers} workers")
\ No newline at end of file
diff --git a/backend/migrations/003_add_notification_preferences.sql b/backend/migrations/003_add_notification_preferences.sql
new file mode 100644
index 0000000..9b630fb
--- /dev/null
+++ b/backend/migrations/003_add_notification_preferences.sql
@@ -0,0 +1,25 @@
+-- Add notification preferences columns if they don't exist
+DO $$
+BEGIN
+ -- Check if notification_frequency column exists
+ IF NOT EXISTS (
+ SELECT 1
+ FROM information_schema.columns
+ WHERE table_name = 'user_preferences'
+ AND column_name = 'notification_frequency'
+ ) THEN
+ ALTER TABLE user_preferences
+ ADD COLUMN notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily';
+ END IF;
+
+ -- Check if notification_time column exists
+ IF NOT EXISTS (
+ SELECT 1
+ FROM information_schema.columns
+ WHERE table_name = 'user_preferences'
+ AND column_name = 'notification_time'
+ ) THEN
+ ALTER TABLE user_preferences
+ ADD COLUMN notification_time VARCHAR(5) NOT NULL DEFAULT '09:00';
+ END IF;
+END $$;
\ No newline at end of file
diff --git a/backend/requirements.txt b/backend/requirements.txt
index 9d5b241..f7e8d3c 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -6,4 +6,5 @@ flask-cors==3.0.10
Flask-Login==0.6.2
Flask-Bcrypt==1.0.1
PyJWT==2.6.0
-email-validator==1.3.1
\ No newline at end of file
+email-validator==1.3.1
+APScheduler==3.10.4
\ No newline at end of file
diff --git a/backend/tests/test_notifications.py b/backend/tests/test_notifications.py
new file mode 100644
index 0000000..0563d69
--- /dev/null
+++ b/backend/tests/test_notifications.py
@@ -0,0 +1,167 @@
+import unittest
+from datetime import date, timedelta
+import sys
+import os
+import json
+from unittest.mock import patch, MagicMock
+
+# Add the parent directory to sys.path to allow importing app.py
+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
+
+# Import the functions from app.py
+from app import get_expiring_warranties, format_expiration_email, send_expiration_notifications
+
+class TestWarrantyNotifications(unittest.TestCase):
+
+ @patch('app.get_db_connection')
+ def test_get_expiring_warranties(self, mock_get_db_connection):
+ """Test that get_expiring_warranties correctly queries expiring warranties."""
+ # Set up mock connection and cursor
+ mock_conn = MagicMock()
+ mock_cur = MagicMock()
+ mock_conn.cursor.return_value.__enter__.return_value = mock_cur
+ mock_get_db_connection.return_value = mock_conn
+
+ # Set up mock cursor fetchall response
+ today = date.today()
+ mock_cur.fetchall.return_value = [
+ # Format: email, first_name, product_name, expiration_date, expiring_soon_days
+ ('[email protected]', 'John', 'Laptop', today + timedelta(days=10), 30),
+ ('[email protected]', 'Jane', 'Phone', today + timedelta(days=20), 30),
+ ('[email protected]', None, 'Tablet', today + timedelta(days=5), 30)
+ ]
+
+ # Call the function
+ result = get_expiring_warranties()
+
+ # Verify the SQL query is correct (simplified check)
+ self.assertTrue(mock_cur.execute.called)
+ args = mock_cur.execute.call_args[0]
+ self.assertIn('warranties w', args[0]) # Check if the query includes the warranties table
+ self.assertIn('users u', args[0]) # Check if the query includes the users table
+ self.assertIn('user_preferences up', args[0]) # Check if the query includes user_preferences
+
+ # Verify the result
+ self.assertEqual(len(result), 3) # Should return 3 warranties
+
+ # Check the first warranty
+ self.assertEqual(result[0]['email'], '[email protected]')
+ self.assertEqual(result[0]['first_name'], 'John')
+ self.assertEqual(result[0]['product_name'], 'Laptop')
+ self.assertEqual(result[0]['expiration_date'], (today + timedelta(days=10)).strftime('%Y-%m-%d'))
+
+ # Check that null first_name is handled correctly
+ self.assertEqual(result[2]['first_name'], 'User') # Default value for NULL
+
+ # Verify the connection is released
+ self.assertTrue(mock_conn.close.called)
+
+ def test_format_expiration_email(self):
+ """Test that format_expiration_email correctly formats the email."""
+ # Test data
+ user = {
+ 'first_name': 'John',
+ 'email': '[email protected]'
+ }
+
+ warranties = [
+ {
+ 'product_name': 'Laptop',
+ 'expiration_date': '2023-12-31'
+ },
+ {
+ 'product_name': 'Phone',
+ 'expiration_date': '2023-11-30'
+ }
+ ]
+
+ # Call the function
+ email = format_expiration_email(user, warranties)
+
+ # Verify the email
+ self.assertEqual(email['Subject'], 'Warracker: Upcoming Warranty Expirations')
+ self.assertEqual(email['From'], '[email protected]')
+ self.assertEqual(email['To'], '[email protected]')
+
+ # Check both parts exist (plain text and HTML)
+ self.assertEqual(len(email.get_payload()), 2)
+
+ # Check content of plain text part
+ plain_text = email.get_payload(0).get_payload()
+ self.assertIn('Hello John', plain_text)
+ self.assertIn('Laptop (expires on 2023-12-31)', plain_text)
+ self.assertIn('Phone (expires on 2023-11-30)', plain_text)
+
+ # Check content of HTML part
+ html = email.get_payload(1).get_payload()
+ self.assertIn('Hello John', html)
+ self.assertIn('Laptop', html)
+ self.assertIn('2023-12-31', html)
+ self.assertIn('Phone', html)
+ self.assertIn('2023-11-30', html)
+
+ @patch('app.get_expiring_warranties')
+ @patch('smtplib.SMTP')
+ def test_send_expiration_notifications(self, mock_smtp, mock_get_expiring_warranties):
+ """Test that send_expiration_notifications correctly sends emails."""
+ # Mock environment variables
+ with patch.dict(os.environ, {
+ 'SMTP_HOST': 'test.example.com',
+ 'SMTP_PORT': '587',
+ 'SMTP_USERNAME': '[email protected]',
+ 'SMTP_PASSWORD': 'test_password'
+ }):
+ # Set up mock SMTP instance
+ mock_smtp_instance = MagicMock()
+ mock_smtp.return_value.__enter__.return_value = mock_smtp_instance
+
+ # Set up mock for expiring warranties
+ mock_get_expiring_warranties.return_value = [
+ {
+ 'email': '[email protected]',
+ 'first_name': 'John',
+ 'product_name': 'Laptop',
+ 'expiration_date': '2023-12-31'
+ },
+ {
+ 'email': '[email protected]',
+ 'first_name': 'John',
+ 'product_name': 'Phone',
+ 'expiration_date': '2023-11-30'
+ },
+ {
+ 'email': '[email protected]',
+ 'first_name': 'Jane',
+ 'product_name': 'Tablet',
+ 'expiration_date': '2023-10-15'
+ }
+ ]
+
+ # Call the function
+ send_expiration_notifications()
+
+ # Verify SMTP is initialized with correct parameters
+ mock_smtp.assert_called_once_with('test.example.com', 587)
+
+ # Verify starttls and login are called
+ self.assertTrue(mock_smtp_instance.starttls.called)
+ mock_smtp_instance.login.assert_called_once_with('[email protected]', 'test_password')
+
+ # Verify sendmail is called twice (for two different users)
+ self.assertEqual(mock_smtp_instance.sendmail.call_count, 2)
+
+ # Verify first call to sendmail (for user1 with 2 warranties)
+ from_email, to_email, msg = mock_smtp_instance.sendmail.call_args_list[0][0]
+ self.assertEqual(from_email, '[email protected]')
+ self.assertEqual(to_email, '[email protected]')
+ self.assertIn('Laptop', msg)
+ self.assertIn('Phone', msg)
+
+ # Verify second call to sendmail (for user2 with 1 warranty)
+ from_email, to_email, msg = mock_smtp_instance.sendmail.call_args_list[1][0]
+ self.assertEqual(from_email, '[email protected]')
+ self.assertEqual(to_email, '[email protected]')
+ self.assertIn('Tablet', msg)
+
+if __name__ == '__main__':
+ unittest.main()
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
index ee72560..aaa6093 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -6,7 +6,9 @@ services:
ports:
- "8005:80"
volumes:
+ - ./data:/data
- ./uploads:/data/uploads
+ - ./migrations:/app/migrations
environment:
- DB_HOST=warrackerdb
- DB_NAME=warranty_db
@@ -14,10 +16,21 @@ services:
- DB_PASSWORD=${DB_PASSWORD:-warranty_password}
- DB_ADMIN_USER=warracker_admin
- DB_ADMIN_PASSWORD=${DB_ADMIN_PASSWORD:-change_this_password_in_production}
+ - SMTP_HOST=${SMTP_HOST:-localhost}
+ - SMTP_PORT=${SMTP_PORT:-1025}
+ - SMTP_USERNAME=${SMTP_USERNAME:[email protected]}
+ - SMTP_PASSWORD=${SMTP_PASSWORD:-}
depends_on:
warrackerdb:
condition: service_healthy
restart: unless-stopped
+ command: >
+ bash -c "
+ chmod -R 777 /data/uploads &&
+ cd /app/migrations && python apply_migrations.py &&
+ python /app/fix_permissions.py &&
+ exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf
+ "
warrackerdb:
image: "postgres:15-alpine"
diff --git a/frontend/auth.js b/frontend/auth.js
index 5d0f1cd..6311c6a 100644
--- a/frontend/auth.js
+++ b/frontend/auth.js
@@ -41,7 +41,7 @@ document.addEventListener('DOMContentLoaded', () => {
// Close user menu when clicking outside
document.addEventListener('click', (e) => {
- if (userMenuDropdown && !userMenuDropdown.contains(e.target) && !userBtn.contains(e.target)) {
+ if (userMenuDropdown && userBtn && !userMenuDropdown.contains(e.target) && !userBtn.contains(e.target)) {
userMenuDropdown.classList.remove('active');
}
});
diff --git a/frontend/register.html b/frontend/register.html
index f29938c..882b438 100644
--- a/frontend/register.html
+++ b/frontend/register.html
@@ -542,12 +542,16 @@
const data = await response.json();
if (response.ok) {
- showMessage('Registration successful! Redirecting to login...', 'success');
+ // Store token and user info in localStorage
+ localStorage.setItem('auth_token', data.token);
+ localStorage.setItem('user_info', JSON.stringify(data.user));
+
+ showMessage('Registration successful! Redirecting to dashboard...', 'success');
setTimeout(() => {
- window.location.href = 'login.html';
+ window.location.href = 'index.html';
}, 2000);
} else {
- showMessage(data.error || 'Registration failed. Please try again.', 'error');
+ showMessage(data.error || data.message || 'Registration failed. Please try again.', 'error');
}
} catch (error) {
showMessage('Network error. Please check your connection and try again.', 'error');
diff --git a/frontend/script.js b/frontend/script.js
index 76f3cd9..d3b3fe7 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -25,25 +25,92 @@ const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
const loadingContainer = document.getElementById('loadingContainer');
const toastContainer = document.getElementById('toastContainer');
+/**
+ * Get current user type (admin or user)
+ * @returns {string} 'admin' or 'user'
+ */
+function getUserType() {
+ try {
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ return userInfo.is_admin === true ? 'admin' : 'user';
+ } catch (e) {
+ console.error('Error determining user type:', e);
+ return 'user'; // Default to user if we can't determine
+ }
+}
+
+/**
+ * Get the appropriate localStorage key prefix based on user type
+ * @returns {string} The prefix to use for localStorage keys
+ */
+function getPreferenceKeyPrefix() {
+ return getUserType() === 'admin' ? 'admin_' : 'user_';
+}
+
// Theme Management
function setTheme(isDark) {
+ // Get the appropriate key prefix based on user type
+ const prefix = getPreferenceKeyPrefix();
+ console.log(`Setting theme with prefix: ${prefix}`);
+
document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');
- localStorage.setItem('darkMode', isDark);
- darkModeToggle.checked = isDark;
+
+ // Update darkMode settings
+ localStorage.setItem(`${prefix}darkMode`, isDark);
+ localStorage.setItem('darkMode', isDark); // Keep for backward compatibility
+
+ // Update DOM
+ if (isDark) {
+ document.body.classList.add('dark-mode');
+ } else {
+ document.body.classList.remove('dark-mode');
+ }
+
+ // Set toggle state
+ if (darkModeToggle) {
+ darkModeToggle.checked = isDark;
+ }
+
+ // 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 theme based on user preference or system preference
function initializeTheme() {
- const savedTheme = localStorage.getItem('darkMode');
+ // Get the appropriate key prefix based on user type
+ const prefix = getPreferenceKeyPrefix();
+ console.log(`Initializing theme with prefix: ${prefix}`);
+
+ // First check user-specific setting
+ const userDarkMode = localStorage.getItem(`${prefix}darkMode`);
+ if (userDarkMode !== null) {
+ console.log(`Found user-specific dark mode setting: ${userDarkMode}`);
+ setTheme(userDarkMode === 'true');
+ return;
+ }
- 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);
+ // Then check global setting for backward compatibility
+ const globalDarkMode = localStorage.getItem('darkMode');
+ if (globalDarkMode !== null) {
+ console.log(`Found global dark mode setting: ${globalDarkMode}`);
+ setTheme(globalDarkMode === 'true');
+ return;
}
+
+ // Check for system preference if no stored preference
+ const prefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+ console.log(`No saved preference, using system preference: ${prefersDarkMode}`);
+ setTheme(prefersDarkMode);
}
// Initialize theme when page loads
@@ -398,50 +465,87 @@ async function exportWarranties() {
showToast('Warranties exported successfully', 'success');
}
-// Function to switch between views
+// Switch view of warranties list
function switchView(viewType) {
- console.log('Switching view to:', viewType);
-
- // Process all warranties to ensure consistency
- processAllWarranties();
+ console.log(`Switching to ${viewType} view...`);
- // Update current view
+ // Update currentView
currentView = viewType;
- // Update view buttons
- gridViewBtn.classList.toggle('active', viewType === 'grid');
- listViewBtn.classList.toggle('active', viewType === 'list');
- tableViewBtn.classList.toggle('active', viewType === 'table');
+ // Remove active class from all view buttons
+ gridViewBtn.classList.remove('active');
+ listViewBtn.classList.remove('active');
+ tableViewBtn.classList.remove('active');
- // Update warranties list class
+ // Update the view
warrantiesList.className = `warranties-list ${viewType}-view`;
- // Show/hide table header for table view
+ // Hide table header if not in table view
if (tableViewHeader) {
- tableViewHeader.classList.toggle('visible', viewType === 'table');
+ tableViewHeader.style.display = viewType === 'table' ? 'flex' : 'none';
+ }
+
+ // Add active class to the selected view button
+ if (viewType === 'grid') {
+ gridViewBtn.classList.add('active');
+ } else if (viewType === 'list') {
+ listViewBtn.classList.add('active');
+ } else if (viewType === 'table') {
+ tableViewBtn.classList.add('active');
}
// Re-render warranties with the new view
console.log('Applying filters after switching view...');
applyFilters();
- // Save view preference to localStorage
- localStorage.setItem('warrantyView', viewType);
+ // Get prefix for user-specific preferences
+ const prefix = getPreferenceKeyPrefix();
+
+ // Save view preference to localStorage with the appropriate prefix
+ localStorage.setItem(`${prefix}warrantyView`, viewType);
+ localStorage.setItem('warrantyView', viewType); // Keep global setting for backward compatibility
}
// Load saved view preference
function loadViewPreference() {
- // First check for warrantyView (direct view selection)
- const savedView = localStorage.getItem('warrantyView');
- // If not found, check for defaultView (from settings)
- const defaultView = localStorage.getItem('defaultView');
+ // Get prefix for user-specific preferences
+ const prefix = getPreferenceKeyPrefix();
- // Use warrantyView if available, otherwise use defaultView, or fall back to grid
- const viewToUse = savedView || defaultView || 'grid';
+ // First check for user-specific warrantyView
+ const userSavedView = localStorage.getItem(`${prefix}warrantyView`);
- if (viewToUse) {
- switchView(viewToUse);
+ if (userSavedView) {
+ console.log(`Found user-specific view preference: ${userSavedView}`);
+ switchView(userSavedView);
+ return;
+ }
+
+ // If not found, check for user-specific defaultView
+ const userDefaultView = localStorage.getItem(`${prefix}defaultView`);
+ if (userDefaultView) {
+ console.log(`Found user-specific default view: ${userDefaultView}`);
+ switchView(userDefaultView);
+ return;
+ }
+
+ // If no user-specific preferences found, check global preferences for backward compatibility
+ const globalSavedView = localStorage.getItem('warrantyView');
+ if (globalSavedView) {
+ console.log(`Found global view preference: ${globalSavedView}`);
+ switchView(globalSavedView);
+ return;
}
+
+ const globalDefaultView = localStorage.getItem('defaultView');
+ if (globalDefaultView) {
+ console.log(`Found global default view: ${globalDefaultView}`);
+ switchView(globalDefaultView);
+ return;
+ }
+
+ // Default to grid view if no preferences found
+ console.log('No view preference found, defaulting to grid view');
+ switchView('grid');
}
// Dark mode toggle
@@ -801,6 +905,11 @@ async function renderWarranties(warrantiesToRender) {
const statusClass = warranty.status || 'unknown';
const statusText = warranty.statusText || 'Unknown status';
+ // Debug file paths
+ console.log(`Warranty ID ${warranty.id} - Product: ${warranty.product_name}`);
+ console.log(`- Invoice path: ${warranty.invoice_path}`);
+ console.log(`- Manual path: ${warranty.manual_path}`);
+
// Make sure serial numbers array exists and is valid
const validSerialNumbers = Array.isArray(warranty.serial_numbers)
? warranty.serial_numbers.filter(sn => sn && typeof sn === 'string' && sn.trim() !== '')
@@ -849,11 +958,11 @@ async function renderWarranties(warrantiesToRender) {
<i class="fas fa-globe"></i> Product Website
</a>
` : ''}
- ${warranty.invoice_path ? `
+ ${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> Invoice
</a>` : ''}
- ${warranty.manual_path ? `
+ ${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> Manual
</a>` : ''}
@@ -898,11 +1007,11 @@ async function renderWarranties(warrantiesToRender) {
<i class="fas fa-globe"></i> Product Website
</a>
` : ''}
- ${warranty.invoice_path ? `
+ ${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> Invoice
</a>` : ''}
- ${warranty.manual_path ? `
+ ${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> Manual
</a>` : ''}
@@ -937,11 +1046,11 @@ async function renderWarranties(warrantiesToRender) {
<i class="fas fa-globe"></i>
</a>
` : ''}
- ${warranty.invoice_path ? `
+ ${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>
</a>` : ''}
- ${warranty.manual_path ? `
+ ${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>
</a>` : ''}
@@ -1073,7 +1182,7 @@ function openEditModal(warranty) {
// Show current invoice if exists
const currentInvoiceElement = document.getElementById('currentInvoice');
if (currentInvoiceElement) {
- if (warranty.invoice_path) {
+ if (warranty.invoice_path && warranty.invoice_path !== 'null') {
currentInvoiceElement.innerHTML = `
<span class="text-success">
<i class="fas fa-check-circle"></i> Current invoice:
@@ -1089,7 +1198,7 @@ function openEditModal(warranty) {
// Show current manual if exists
const currentManualElement = document.getElementById('currentManual');
if (currentManualElement) {
- if (warranty.manual_path) {
+ if (warranty.manual_path && warranty.manual_path !== 'null') {
currentManualElement.innerHTML = `
<span class="text-success">
<i class="fas fa-check-circle"></i> Current manual:
@@ -1652,4 +1761,52 @@ function validateEditTab(tabId) {
}
return isValid;
+}
+
+// Add this function for secure file access
+function openSecureFile(filePath) {
+ if (!filePath || filePath === 'null') {
+ console.error('Invalid file path:', filePath);
+ showToast('Invalid file path', 'error');
+ return false;
+ }
+
+ console.log('Opening secure file:', filePath);
+
+ // Get the file name from the path
+ const fileName = filePath.split('/').pop();
+
+ // Get auth token
+ const token = window.auth.getToken();
+ if (!token) {
+ showToast('Authentication error. Please log in again.', 'error');
+ return false;
+ }
+
+ // Use fetch with proper authorization header
+ fetch(`/api/secure-file/${fileName}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error(`Error: ${response.status} ${response.statusText}`);
+ }
+ return response.blob();
+ })
+ .then(blob => {
+ // Create a URL for the blob
+ const blobUrl = window.URL.createObjectURL(blob);
+
+ // Open in new tab
+ window.open(blobUrl, '_blank');
+ })
+ .catch(error => {
+ console.error('Error fetching file:', error);
+ showToast('Error opening file: ' + error.message, 'error');
+ });
+
+ return false;
}
\ No newline at end of file
diff --git a/frontend/settings-new.html b/frontend/settings-new.html
index 65ec384..84371e2 100644
--- a/frontend/settings-new.html
+++ b/frontend/settings-new.html
@@ -20,6 +20,21 @@
<link rel="stylesheet" href="header-fix.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 {
@@ -292,6 +307,23 @@
</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">
@@ -310,34 +342,28 @@
<i class="fas fa-cog"></i> Settings
</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">
+ <button class="user-btn" id="userMenuBtn">
<i class="fas fa-user-circle"></i>
<span id="userDisplayName">User</span>
</button>
- <div id="userMenuDropdown" class="user-menu-dropdown">
+ <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 class="user-name" id="userName">User</div>
+ <div class="user-email" id="userEmail">[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 class="user-menu-item" onclick="window.location.href='settings-new.html'">
+ <i class="fas fa-cog"></i> Settings
</div>
<div class="user-menu-item" id="logoutMenuItem">
<i class="fas fa-sign-out-alt"></i> Logout
</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>
</header>
@@ -430,6 +456,42 @@
</div>
</div>
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Notification Frequency</label>
+ <p class="text-muted">How often to receive email notifications</p>
+ </div>
+ <select id="notificationFrequency" class="form-control">
+ <option value="daily">Daily</option>
+ <option value="weekly">Weekly</option>
+ <option value="monthly">Monthly</option>
+ </select>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Notification Time</label>
+ <p class="text-muted">Time of day to receive notifications (in 24-hour format)</p>
+ </div>
+ <input type="time" id="notificationTime" class="form-control" value="09:00">
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Timezone</label>
+ <p class="text-muted">Your local timezone for notifications</p>
+ </div>
+ <select id="timezone" class="form-control">
+ <option value="">Loading timezones...</option>
+ </select>
+ </div>
+ </div>
+
<button type="button" id="savePreferencesBtn" class="btn btn-primary">Save Preferences</button>
</form>
</div>
@@ -516,6 +578,10 @@
<i class="fas fa-vial"></i>
<span>Test API</span>
</button>
+ <button id="triggerNotificationsBtn" class="admin-action-btn">
+ <i class="fas fa-envelope"></i>
+ <span>Send Warranty Notifications</span>
+ </button>
</div>
</div>
</div>
diff --git a/frontend/settings-new.js b/frontend/settings-new.js
index cce7323..6bc959a 100644
--- a/frontend/settings-new.js
+++ b/frontend/settings-new.js
@@ -4,6 +4,9 @@ const darkModeToggleSetting = document.getElementById('darkModeToggleSetting');
const defaultViewSelect = document.getElementById('defaultView');
const emailNotificationsToggle = document.getElementById('emailNotifications');
const expiringSoonDaysInput = document.getElementById('expiringSoonDays');
+const notificationFrequencySelect = document.getElementById('notificationFrequency');
+const notificationTimeInput = document.getElementById('notificationTime');
+const timezoneSelect = document.getElementById('timezone');
const saveProfileBtn = document.getElementById('saveProfileBtn');
const savePreferencesBtn = document.getElementById('savePreferencesBtn');
const changePasswordBtn = document.getElementById('changePasswordBtn');
@@ -35,9 +38,74 @@ const refreshUsersBtn = document.getElementById('refreshUsersBtn');
const checkAdminBtn = document.getElementById('checkAdminBtn');
const showUsersBtn = document.getElementById('showUsersBtn');
const testApiBtn = document.getElementById('testApiBtn');
+const triggerNotificationsBtn = document.getElementById('triggerNotificationsBtn');
const registrationEnabled = document.getElementById('registrationEnabled');
const saveSiteSettingsBtn = document.getElementById('saveSiteSettingsBtn');
+/**
+ * Initialize dark mode toggle
+ */
+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;
+ }
+
+ if (darkModeToggleSetting) {
+ darkModeToggleSetting.checked = isDarkMode;
+ }
+
+ // Header toggle handler
+ if (darkModeToggle) {
+ darkModeToggle.addEventListener('change', function() {
+ const isDark = this.checked;
+ setTheme(isDark);
+
+ if (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 the localStorage to match the visual state
+ localStorage.setItem('darkMode', isDarkMode);
+}
+
+/**
+ * Initialize settings gear menu in the header
+ */
+function initSettingsMenu() {
+ if (settingsBtn && settingsMenu) {
+ // Toggle settings menu when settings button is clicked
+ settingsBtn.addEventListener('click', function() {
+ settingsMenu.classList.toggle('active');
+ });
+
+ // Close settings menu when clicking outside
+ document.addEventListener('click', function(event) {
+ if (!settingsBtn.contains(event.target) && !settingsMenu.contains(event.target)) {
+ settingsMenu.classList.remove('active');
+ }
+ });
+ }
+}
+
// Initialize settings page
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM fully loaded, initializing settings page');
@@ -125,6 +193,15 @@ document.addEventListener('DOMContentLoaded', function() {
return false;
});
}
+
+ // Initialize theme
+ applyInitialTheme();
+
+ // Initialize dark mode toggle
+ initDarkModeToggle();
+
+ // Initialize settings menu
+ initSettingsMenu();
});
/**
@@ -152,12 +229,20 @@ function initPage() {
// Load user data and preferences with error handling
try {
+ // First load timezones, then load preferences to ensure correct order
+ loadTimezones().then(() => {
+ console.log('Timezones loaded, now loading preferences');
+ loadPreferences();
+ }).catch(err => {
+ console.error('Error loading timezones:', err);
+ // Still try to load preferences even if timezones fail
+ loadPreferences();
+ });
+
loadUserData().catch(err => {
console.error('Error loading user data:', err);
// Continue with page initialization even if user data fails
});
-
- loadPreferences();
} catch (err) {
console.error('Error during page initialization:', err);
// Continue despite errors to allow basic functionality
@@ -187,6 +272,57 @@ function initPage() {
console.log('Settings page initialization complete');
}
+/**
+ * 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
*/
@@ -342,52 +478,150 @@ async function loadUserData() {
}
/**
- * Load user preferences from localStorage and API
+ * Get current user type (admin or user)
+ * @returns {string} 'admin' or 'user'
+ */
+function getUserType() {
+ try {
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ return userInfo.is_admin === true ? 'admin' : 'user';
+ } catch (e) {
+ console.error('Error determining user type:', e);
+ return 'user'; // Default to user if we can't determine
+ }
+}
+
+/**
+ * Get the appropriate localStorage key prefix based on user type
+ * @returns {string} The prefix to use for localStorage keys
+ */
+function getPreferenceKeyPrefix() {
+ return getUserType() === 'admin' ? 'admin_' : 'user_';
+}
+
+/**
+ * Load user preferences
*/
function loadPreferences() {
- // Load dark mode preference
- const darkMode = localStorage.getItem('darkMode') === 'true';
+ console.log('Loading preferences...');
+ showLoading();
- // Check if elements exist before setting properties
- if (darkModeToggleSetting) {
- darkModeToggleSetting.checked = darkMode;
- }
+ // Get the appropriate key prefix based on user type
+ const prefix = getPreferenceKeyPrefix();
+ console.log(`Loading preferences with prefix: ${prefix}`);
- // The darkModeToggle element doesn't exist in the page anymore
- // so we need to check before accessing it
+ // First check if we're in dark mode by checking the body class
+ const isDarkMode = document.body.classList.contains('dark-mode');
+
+ // Set the toggle state based on the current theme
if (darkModeToggle) {
- darkModeToggle.checked = darkMode;
+ darkModeToggle.checked = isDarkMode;
}
- // Apply the theme immediately
- setTheme(darkMode);
-
- // Load default view preference
- const defaultView = localStorage.getItem('defaultView') || 'grid';
- if (defaultViewSelect) {
- defaultViewSelect.value = defaultView;
+ if (darkModeToggleSetting) {
+ darkModeToggleSetting.checked = isDarkMode;
}
- // Load email notifications preference (default to true if not set)
- const emailNotifications = localStorage.getItem('emailNotifications') !== 'false';
- if (emailNotificationsToggle) {
- emailNotificationsToggle.checked = emailNotifications;
+ // 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;
+ }
+ }
+ } catch (e) {
+ console.error('Error loading preferences from localStorage:', e);
}
- // Load expiring soon days from API
+ // Load preferences from API
fetch('/api/auth/preferences', {
+ method: 'GET',
headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
}
})
- .then(response => response.json())
+ .then(response => {
+ if (!response.ok) {
+ throw new Error('Failed to load preferences from API');
+ }
+ return response.json();
+ })
.then(data => {
- if (data && data.expiring_soon_days) {
- expiringSoonDaysInput.value = data.expiring_soon_days;
+ console.log('Preferences loaded from API:', data);
+
+ // API returns preferences directly, not nested under a 'preferences' key
+ const apiPrefs = data;
+
+ // Update UI with API preferences
+ if (defaultViewSelect && apiPrefs.default_view) {
+ defaultViewSelect.value = apiPrefs.default_view;
+ }
+
+ if (emailNotificationsToggle && apiPrefs.email_notifications) {
+ emailNotificationsToggle.checked = apiPrefs.email_notifications;
+ }
+
+ if (expiringSoonDaysInput && apiPrefs.expiring_soon_days) {
+ expiringSoonDaysInput.value = apiPrefs.expiring_soon_days;
+ }
+
+ if (notificationFrequencySelect && apiPrefs.notification_frequency) {
+ notificationFrequencySelect.value = apiPrefs.notification_frequency;
+ }
+
+ if (notificationTimeInput && apiPrefs.notification_time) {
+ notificationTimeInput.value = apiPrefs.notification_time;
+ }
+
+ if (timezoneSelect && apiPrefs.timezone) {
+ console.log('API provided timezone:', apiPrefs.timezone);
+ // Will be populated once timezones are loaded
+ setTimeout(() => {
+ if (timezoneSelect.options.length > 1) {
+ timezoneSelect.value = apiPrefs.timezone;
+ console.log('Applied timezone from API:', apiPrefs.timezone, 'Current select value:', timezoneSelect.value);
+ }
+ }, 500);
}
+
+ // Store in localStorage with the appropriate prefix
+ localStorage.setItem(`${prefix}preferences`, JSON.stringify(apiPrefs));
})
.catch(error => {
console.error('Error loading preferences from API:', error);
+ })
+ .finally(() => {
+ hideLoading();
});
}
@@ -397,6 +631,29 @@ function loadPreferences() {
function setupEventListeners() {
console.log('Setting up event listeners');
+ // Set up user menu button click handler
+ const userMenuBtn = document.getElementById('userMenuBtn');
+ const userMenuDropdown = document.getElementById('userMenuDropdown');
+
+ if (userMenuBtn && userMenuDropdown) {
+ console.log('Setting up user menu button click handler');
+
+ // Toggle dropdown when user button is clicked
+ userMenuBtn.addEventListener('click', function(e) {
+ e.stopPropagation();
+ userMenuDropdown.classList.toggle('active');
+ });
+
+ // Close dropdown when clicking outside
+ document.addEventListener('click', function(e) {
+ if (userMenuDropdown.classList.contains('active') &&
+ !userMenuDropdown.contains(e.target) &&
+ !userMenuBtn.contains(e.target)) {
+ userMenuDropdown.classList.remove('active');
+ }
+ });
+ }
+
// Dark mode toggle in header (no longer exists)
if (darkModeToggle) {
darkModeToggle.addEventListener('change', function() {
@@ -472,26 +729,52 @@ function setupEventListeners() {
confirmDeleteAccountBtn.addEventListener('click', deleteAccount);
}
+ // Add event listener for logout menu item
+ const logoutMenuItem = document.getElementById('logoutMenuItem');
+ if (logoutMenuItem) {
+ logoutMenuItem.addEventListener('click', function() {
+ if (window.auth && window.auth.logout) {
+ window.auth.logout();
+ }
+ });
+ }
+
// Admin section buttons
if (refreshUsersBtn) {
- refreshUsersBtn.addEventListener('click', loadUsers);
+ refreshUsersBtn.addEventListener('click', function() {
+ loadUsers();
+ });
}
if (checkAdminBtn) {
- checkAdminBtn.addEventListener('click', checkAdminPermissions);
+ checkAdminBtn.addEventListener('click', function() {
+ checkAdminPermissions();
+ });
}
if (showUsersBtn) {
- showUsersBtn.addEventListener('click', showUsersList);
+ showUsersBtn.addEventListener('click', function() {
+ showUsersList();
+ });
}
if (testApiBtn) {
- testApiBtn.addEventListener('click', checkApiEndpoint);
+ testApiBtn.addEventListener('click', function() {
+ checkApiEndpoint();
+ });
+ }
+
+ if (triggerNotificationsBtn) {
+ triggerNotificationsBtn.addEventListener('click', function() {
+ triggerWarrantyNotifications();
+ });
}
// Site settings save button
if (saveSiteSettingsBtn) {
- saveSiteSettingsBtn.addEventListener('click', saveSiteSettings);
+ saveSiteSettingsBtn.addEventListener('click', function() {
+ saveSiteSettings();
+ });
}
console.log('Event listeners setup complete');
@@ -591,10 +874,11 @@ function resetPasswordForm() {
* @param {boolean} isDark - Whether to use dark mode
*/
function setTheme(isDark) {
- // Default to current theme if isDark is undefined
- if (isDark === undefined) {
- isDark = localStorage.getItem('darkMode') === 'true';
- }
+ 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');
@@ -606,10 +890,31 @@ function setTheme(isDark) {
document.body.classList.remove('dark-mode');
}
- // Save to localStorage
- localStorage.setItem('darkMode', isDark);
+ // 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;
+ }
- console.log('Theme set to:', isDark ? 'dark' : 'light');
+ if (darkModeToggleSetting) {
+ darkModeToggleSetting.checked = isDark;
+ }
}
/**
@@ -699,61 +1004,100 @@ async function saveProfile() {
* Save user preferences
*/
function savePreferences() {
- // Get preferences with null checks
- const isDark = darkModeToggleSetting && darkModeToggleSetting.checked;
-
- // Apply theme
- setTheme(isDark);
-
- // Update darkModeToggle if it exists
- if (darkModeToggle) {
- darkModeToggle.checked = isDark;
- }
-
- // Save default view preference with null check
- const defaultView = defaultViewSelect ? defaultViewSelect.value : 'grid';
- localStorage.setItem('defaultView', defaultView);
- localStorage.setItem('warrantyView', defaultView);
-
- // Save email notifications preference with null check
- const emailNotifications = emailNotificationsToggle ? emailNotificationsToggle.checked : true;
- localStorage.setItem('emailNotifications', emailNotifications);
-
- // Get expiring soon days value with null check
- const expiringSoonDaysValue = expiringSoonDaysInput ? expiringSoonDaysInput.value : '30';
- let expiringSoonDays = parseInt(expiringSoonDaysValue);
-
- // Validate expiring soon days
- if (isNaN(expiringSoonDays) || expiringSoonDays < 1 || expiringSoonDays > 365) {
- showToast('Expiring soon days must be between 1 and 365', 'error');
- return;
- }
+ showLoading();
- // Save preferences to API
- fetch('/api/auth/preferences', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
+ try {
+ // Get the appropriate key prefix based on user type
+ const prefix = getPreferenceKeyPrefix();
+ console.log(`Saving preferences with prefix: ${prefix}`);
+
+ // Get values
+ const isDarkMode = darkModeToggleSetting.checked;
+ const defaultView = defaultViewSelect.value;
+ const emailNotifications = emailNotificationsToggle.checked;
+ const expiringSoonDays = parseInt(expiringSoonDaysInput.value);
+ const notificationFrequency = notificationFrequencySelect.value;
+ const notificationTime = notificationTimeInput.value;
+ const timezone = timezoneSelect.value;
+
+ // Validate inputs
+ if (isNaN(expiringSoonDays) || expiringSoonDays < 1 || expiringSoonDays > 365) {
+ showToast('Expiring soon days must be between 1 and 365', 'error');
+ hideLoading();
+ return;
+ }
+
+ if (!timezone) {
+ showToast('Please select a timezone', 'error');
+ hideLoading();
+ return;
+ }
+
+ // Create preferences object
+ const preferences = {
+ theme: isDarkMode ? 'dark' : 'light',
default_view: defaultView,
email_notifications: emailNotifications,
- theme: isDark ? 'dark' : 'light',
- expiring_soon_days: expiringSoonDays
+ expiring_soon_days: expiringSoonDays,
+ notification_frequency: notificationFrequency,
+ notification_time: notificationTime,
+ timezone: timezone
+ };
+
+ // Save to API
+ fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(preferences)
})
- })
- .then(response => {
- if (response.ok) {
+ .then(response => {
+ if (!response.ok) {
+ throw new Error('Failed to save preferences');
+ }
+ return response.json();
+ })
+ .then(data => {
+ // Save to localStorage with the appropriate prefix
+ localStorage.setItem(`${prefix}preferences`, JSON.stringify(data));
+
+ // Also save individual preferences for backward compatibility
+ localStorage.setItem(`${prefix}defaultView`, defaultView);
+ localStorage.setItem(`${prefix}warrantyView`, defaultView);
+ localStorage.setItem(`${prefix}emailNotifications`, emailNotifications);
+
+ // Save the dark mode setting for the current user type
+ localStorage.setItem(`${prefix}darkMode`, isDarkMode);
+
+ // Apply theme immediately
+ document.body.classList.toggle('dark-mode', isDarkMode);
+
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');
- });
+ })
+ .catch(error => {
+ console.error('Error saving preferences:', error);
+ showToast('Error saving preferences', 'error');
+
+ // Save to localStorage as fallback with the appropriate prefix
+ localStorage.setItem(`${prefix}theme`, isDarkMode ? 'dark' : 'light');
+ localStorage.setItem(`${prefix}defaultView`, defaultView);
+ localStorage.setItem(`${prefix}warrantyView`, defaultView);
+ localStorage.setItem(`${prefix}emailNotifications`, emailNotifications);
+ localStorage.setItem(`${prefix}darkMode`, isDarkMode);
+
+ // Apply theme even if API save fails
+ document.body.classList.toggle('dark-mode', isDarkMode);
+ })
+ .finally(() => {
+ hideLoading();
+ });
+ } catch (error) {
+ console.error('Error in savePreferences:', error);
+ showToast('Error saving preferences', 'error');
+ hideLoading();
+ }
}
/**
@@ -2346,4 +2690,151 @@ function checkApiEndpoint() {
console.error('Error checking API endpoint:', error);
showToast('Error checking API endpoint: ' + error.message, 'error');
});
+}
+
+/**
+ * Trigger warranty expiration notifications (admin only)
+ */
+async function triggerWarrantyNotifications() {
+ console.log('Trigger warranty notifications requested');
+
+ // Check if admin
+ try {
+ const response = await fetch('/api/auth/user', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to check user status');
+ }
+
+ const userData = await response.json();
+
+ if (!userData.is_admin) {
+ showToast('Only administrators can send warranty notifications', 'error');
+ return;
+ }
+
+ // Show confirmation dialog
+ if (!confirm('Are you sure you want to send warranty expiration notifications to all eligible users? This will immediately email users with warranties expiring soon.')) {
+ return;
+ }
+
+ showLoading();
+
+ // Call the API endpoint to trigger notifications
+ const notificationResponse = await fetch('/api/admin/send-notifications', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!notificationResponse.ok) {
+ const errorData = await notificationResponse.json();
+ throw new Error(errorData.message || 'Failed to send notifications');
+ }
+
+ const result = await notificationResponse.json();
+ showToast(result.message || 'Notifications triggered successfully', 'success');
+
+ } catch (error) {
+ console.error('Error triggering notifications:', error);
+ showToast('Error: ' + error.message, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Load available timezones from the API
+ * @returns {Promise} A promise that resolves when timezones are loaded
+ */
+function loadTimezones() {
+ console.log('Loading timezones...');
+ return new Promise((resolve, reject) => {
+ fetch('/api/timezones', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error('Failed to load timezones');
+ }
+ return response.json();
+ })
+ .then(timezoneGroups => {
+ // Clear loading option
+ timezoneSelect.innerHTML = '';
+
+ // Add timezone groups and their options
+ timezoneGroups.forEach(group => {
+ const optgroup = document.createElement('optgroup');
+ optgroup.label = group.region;
+
+ group.timezones.forEach(timezone => {
+ const option = document.createElement('option');
+ option.value = timezone.value;
+ option.textContent = timezone.label;
+ optgroup.appendChild(option);
+ });
+
+ timezoneSelect.appendChild(optgroup);
+ });
+
+ // Set the current timezone from preferences
+ // Get the appropriate key prefix based on user type
+ const prefix = getPreferenceKeyPrefix();
+ const savedPreferences = JSON.parse(localStorage.getItem(`${prefix}preferences`) || '{}');
+
+ console.log('Loading timezone preference from localStorage', {
+ prefix: prefix,
+ preferenceKey: `${prefix}preferences`,
+ savedTimezone: savedPreferences.timezone
+ });
+
+ if (savedPreferences.timezone) {
+ timezoneSelect.value = savedPreferences.timezone;
+ console.log('Set timezone select to:', savedPreferences.timezone, 'Current value:', timezoneSelect.value);
+ resolve();
+ } else {
+ // If no timezone preference found in localStorage, load from API as backup
+ console.log('No timezone found in localStorage, fetching from API');
+ fetch('/api/auth/preferences', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ })
+ .then(response => response.json())
+ .then(data => {
+ // API returns preferences directly, not nested
+ if (data && data.timezone) {
+ console.log('Received timezone from API:', data.timezone);
+ timezoneSelect.value = data.timezone;
+ console.log('Set timezone select to:', data.timezone, 'Current value:', timezoneSelect.value);
+ }
+ resolve();
+ })
+ .catch(error => {
+ console.error('Error loading preferences from API:', error);
+ resolve(); // Still resolve to continue the chain
+ });
+ }
+ })
+ .catch(error => {
+ console.error('Error loading timezones:', error);
+ timezoneSelect.innerHTML = '<option value="UTC">UTC (Coordinated Universal Time)</option>';
+ reject(error);
+ });
+ });
}
\ No newline at end of file
diff --git a/frontend/settings-styles.css b/frontend/settings-styles.css
index e05326e..17898ec 100644
--- a/frontend/settings-styles.css
+++ b/frontend/settings-styles.css
@@ -18,19 +18,27 @@ body {
header {
background-color: var(--card-bg);
box-shadow: var(--shadow);
- padding: 20px 0;
+ padding: 20px 0 !important;
margin-bottom: 30px;
+ height: auto !important;
+ min-height: 80px !important;
+ max-height: none !important;
}
header .container {
display: flex;
justify-content: space-between;
align-items: center;
+ max-width: 1200px !important;
+ margin: 0 auto !important;
+ padding: 0 20px !important;
+ height: auto !important;
}
.app-title {
display: flex;
align-items: center;
+ flex-shrink: 0 !important;
}
.app-title h1 {
@@ -49,7 +57,9 @@ header .container {
.nav-links {
display: flex;
gap: 20px;
- margin: 0 20px;
+ margin: 0 20px !important;
+ flex-grow: 1 !important;
+ justify-content: center !important;
}
.nav-link {
@@ -164,9 +174,9 @@ header .container {
/* Content Styles */
.content-wrapper {
- max-width: 800px;
- margin: 0 auto;
- padding: 20px 0;
+ max-width: 1200px !important;
+ margin: 0 auto !important;
+ padding: 20px !important;
}
.content-wrapper h2 {
@@ -247,32 +257,33 @@ header .container {
}
/* Toggle switch */
-.switch {
+.toggle-switch {
position: relative;
display: inline-block;
width: 50px;
height: 24px;
}
-.switch input {
+.toggle-switch input {
opacity: 0;
width: 0;
height: 0;
}
-.slider {
+.toggle-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
- background-color: #ccc;
+ background-color: var(--medium-gray);
transition: .4s;
- border-radius: 24px;
+ border-radius: 34px;
+ box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
}
-.slider:before {
+.toggle-slider:before {
position: absolute;
content: "";
height: 16px;
@@ -282,13 +293,14 @@ header .container {
background-color: white;
transition: .4s;
border-radius: 50%;
+ box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}
-input:checked + .slider {
+input:checked + .toggle-slider {
background-color: var(--primary-color);
}
-input:checked + .slider:before {
+input:checked + .toggle-slider:before {
transform: translateX(26px);
}
@@ -611,52 +623,6 @@ input:checked + .slider:before {
color: var(--danger-color);
}
-/* Toggle switch */
-.toggle-switch {
- position: relative;
- display: inline-block;
- width: 50px;
- height: 24px;
-}
-
-.toggle-switch input {
- opacity: 0;
- width: 0;
- height: 0;
-}
-
-.toggle-slider {
- position: absolute;
- cursor: pointer;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- background-color: #ccc;
- transition: .4s;
- border-radius: 24px;
-}
-
-.toggle-slider:before {
- position: absolute;
- content: "";
- height: 16px;
- width: 16px;
- left: 4px;
- bottom: 4px;
- background-color: white;
- transition: .4s;
- border-radius: 50%;
-}
-
-input:checked + .toggle-slider {
- background-color: var(--primary-color);
-}
-
-input:checked + .toggle-slider:before {
- transform: translateX(26px);
-}
-
/* Button styles */
.btn {
display: inline-block;
diff --git a/frontend/status.js b/frontend/status.js
index f82e0bd..b161ba5 100644
--- a/frontend/status.js
+++ b/frontend/status.js
@@ -713,9 +713,8 @@ async function initDashboard() {
// Update summary counts
updateSummaryCounts(summary);
- // Create charts
+ // Create status chart
createStatusChart(summary);
- createTimelineChart(timeline);
// Update recent expirations table with the initial data
updateRecentExpirations(recentWarranties);
@@ -734,15 +733,29 @@ async function initDashboard() {
// 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);
+ }
} 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);
}
} 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);
}
// Set up event listeners for filtering and sorting
diff --git a/migrations/003_add_notification_preferences.sql b/migrations/003_add_notification_preferences.sql
new file mode 100644
index 0000000..25270f6
--- /dev/null
+++ b/migrations/003_add_notification_preferences.sql
@@ -0,0 +1,34 @@
+-- Add notification preferences columns to user_preferences table
+
+-- Check if notification_frequency column exists
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT FROM information_schema.columns
+ WHERE table_name = 'user_preferences' AND column_name = 'notification_frequency'
+ ) THEN
+ ALTER TABLE user_preferences ADD COLUMN notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily';
+ END IF;
+END $$;
+
+-- Check if notification_time column exists
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT FROM information_schema.columns
+ WHERE table_name = 'user_preferences' AND column_name = 'notification_time'
+ ) THEN
+ ALTER TABLE user_preferences ADD COLUMN notification_time VARCHAR(5) NOT NULL DEFAULT '09:00';
+ END IF;
+END $$;
+
+-- Add indexes for the new columns
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE tablename = 'user_preferences' AND indexname = 'idx_user_preferences_notification'
+ ) THEN
+ CREATE INDEX idx_user_preferences_notification ON user_preferences(notification_frequency, notification_time);
+ END IF;
+END $$;
\ No newline at end of file
diff --git a/migrations/apply_migrations.py b/migrations/apply_migrations.py
new file mode 100644
index 0000000..8840b5a
--- /dev/null
+++ b/migrations/apply_migrations.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+import os
+import glob
+import psycopg2
+import logging
+import time
+import sys
+
+# Set up logging
+logging.basicConfig(
+ level=logging.INFO,
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
+ handlers=[logging.StreamHandler()]
+)
+logger = logging.getLogger(__name__)
+
+def get_db_connection(max_attempts=5, attempt_delay=5):
+ """Get a connection to the PostgreSQL database with retry logic"""
+ for attempt in range(1, max_attempts + 1):
+ try:
+ logger.info(f"Attempting to connect to database (attempt {attempt}/{max_attempts})")
+
+ # Get connection details from environment variables or use defaults
+ db_host = os.environ.get('DB_HOST', 'localhost')
+ db_port = os.environ.get('DB_PORT', '5432')
+ db_name = os.environ.get('DB_NAME', 'warranty_db')
+ db_user = os.environ.get('DB_USER', 'warranty_user')
+ db_password = os.environ.get('DB_PASSWORD', 'warranty_password')
+
+ conn = psycopg2.connect(
+ host=db_host,
+ port=db_port,
+ dbname=db_name,
+ user=db_user,
+ password=db_password
+ )
+
+ # Set autocommit to False for transaction control
+ conn.autocommit = False
+
+ logger.info("Database connection successful")
+ return conn
+
+ except Exception as e:
+ logger.error(f"Database connection error (attempt {attempt}/{max_attempts}): {e}")
+
+ if attempt < max_attempts:
+ logger.info(f"Retrying in {attempt_delay} seconds...")
+ time.sleep(attempt_delay)
+ else:
+ logger.error("Maximum connection attempts reached. Could not connect to database.")
+ raise
+
+def apply_migrations():
+ """Apply all SQL migration files in the migrations directory"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ cur = conn.cursor()
+
+ # Create migrations table if it doesn't exist
+ cur.execute("""
+ CREATE TABLE IF NOT EXISTS migrations (
+ id SERIAL PRIMARY KEY,
+ filename VARCHAR(255) NOT NULL UNIQUE,
+ applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )
+ """)
+ conn.commit()
+
+ # Get list of migration files
+ migration_dir = os.path.dirname(os.path.abspath(__file__))
+ migration_files = sorted(glob.glob(os.path.join(migration_dir, '*.sql')))
+
+ if not migration_files:
+ logger.info("No migration files found.")
+ return
+
+ # Get list of already applied migrations
+ cur.execute("SELECT filename FROM migrations")
+ applied_migrations = set([row[0] for row in cur.fetchall()])
+
+ # Apply each migration file if not already applied
+ for migration_file in migration_files:
+ filename = os.path.basename(migration_file)
+
+ if filename in applied_migrations:
+ logger.info(f"Migration {filename} already applied, skipping.")
+ continue
+
+ logger.info(f"Applying migration: {filename}")
+
+ try:
+ # Read and execute the SQL file
+ with open(migration_file, 'r') as f:
+ sql = f.read()
+
+ cur.execute(sql)
+
+ # Record the migration as applied
+ cur.execute(
+ "INSERT INTO migrations (filename) VALUES (%s)",
+ (filename,)
+ )
+
+ conn.commit()
+ logger.info(f"Migration {filename} applied successfully")
+
+ except Exception as e:
+ conn.rollback()
+ logger.error(f"Error applying migration {filename}: {e}")
+ logger.error(f"\nQUERY: {sql}\n")
+ raise
+
+ except Exception as e:
+ logger.error(f"Migration error: {e}")
+ if conn:
+ conn.rollback()
+ raise
+
+ finally:
+ if conn:
+ conn.close()
+
+if __name__ == "__main__":
+ try:
+ apply_migrations()
+ logger.info("Migrations completed successfully")
+ except Exception as e:
+ logger.error(f"Migration process failed: {e}")
+ sys.exit(1)
\ No newline at end of file
diff --git a/migrations/run_migrations.sh b/migrations/run_migrations.sh
new file mode 100644
index 0000000..ff122bc
--- /dev/null
+++ b/migrations/run_migrations.sh
@@ -0,0 +1,13 @@
+#!/bin/bash
+
+# Display script execution
+set -x
+
+# Change to the migrations directory
+cd /app/migrations
+
+# Run the migration script
+python3 apply_migrations.py
+
+# Return the exit code
+exit $?
\ No newline at end of file