Skip to content

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

Notes,Doc Deletion, Currency, Password Reset

sassanixba2342f5792b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 551fde6..2045586 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,60 @@
# Changelog
+## [0.9.9.3] - 2025-04-27
+
+### Added
+
+ - **Document Deletion in Edit Warranty:**
+ - Users can now delete uploaded documents (Invoice/Receipt and Product Manual) when editing an existing warranty.
+ - The edit modal now displays "Delete Invoice" and "Delete Manual" buttons if a document is present. Clicking these marks the document for deletion, which is processed when saving changes.
+ - Backend and database are updated to remove the file from storage and clear the reference in the database.
+ _Files: `backend/app.py`, `frontend/index.html`, `frontend/script.js`_
+
+ - **Notes for Warranties:**
+ - Users can now add, view, and edit freeform notes for each warranty.
+ - Notes can be entered when adding or editing a warranty, and are accessible from the warranty card via a dedicated "Notes" link.
+ - A modal dialog allows users to view and edit notes in place, with support for multi-line text and instant updates.
+ - Notes are searchable and filterable alongside product names and tags.
+ - Backend and database support for notes has been added, including migration and API changes.
+ - UI includes clear styling for notes links and modal, with full support for both light and dark themes.
+ _Files: `backend/app.py`, `backend/migrations/014_add_notes_to_warranties.sql`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_
+
+ - **Currency Symbol Customization:**
+ - Users can now select their preferred currency symbol ($, €, £, ¥, ₹, or a custom one) in the settings page.
+ - The selected symbol is now displayed next to purchase prices on warranty cards on the main page (`index.html`).
+ _Files: `backend/app.py`, `backend/migrations/006_add_currency_symbol_column.py`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_
+
+ - **Password Reset Functionality:**
+ - Users can now reset their password via a secure, token-based email workflow.
+ - Added a "Forgot Password?" link on the login page that initiates the process.
+ - Users receive an email with a unique link to set a new password.
+ - Implemented frontend pages for requesting the reset and setting the new password.
+ - Backend handles token generation, validation, email sending, and password updates.
+ _Files: `backend/app.py`, `frontend/login.html`, `frontend/reset-password-request.html`, `frontend/reset-password.html`, `backend/migrations/003_add_users_table.sql` (or similar migration)_
+
+### Changed
+- **Status Page Table:** Removed the "Actions" column (and its buttons) from the "Recently Expired or Expiring Soon" table on `status.html` for a cleaner look.
+- **Table Layout:** Updated the table and CSS to use dynamic column widths, eliminating empty space after the Status column and ensuring the table fills the available space naturally.
+- **UI Polish:** Fixed awkward right-side spacing in the table and removed all flex styling and fixed-width rules for the last column, so the table now adapts responsively to its content.
+- **CSS Cleanup:** Cleaned up and removed obsolete or conflicting CSS rules for the recent expirations table, resolving layout and syntax errors.
+- **Status Page Table Sorting:**
+ - Fixed date comparison logic in the sort function to correctly handle `Date` objects.
+ - Refactored event listener attachment for sortable table headers to prevent duplicate listeners being added, resolving issues where sorting only worked once or behaved erratically.
+ - Ensured all event listeners (sort, filter, search, export, refresh) are attached reliably after initial data load and rendering.
+ _Files: `frontend/status.html`, `frontend/status.js`, `frontend/style.css`_
+
+- **Mobile Export Button:** On mobile devices, the export button at the bottom of the status page now only displays the icon (no text), for a cleaner and more compact UI. The text remains visible on desktop.
+- **Mobile Search Functionality:** The search box for recent expirations at the bottom of the status page now works correctly on mobile, with event listeners properly initialized to ensure filtering works as expected on all devices.
+ _Files: `frontend/status.html`, `frontend/status.js`, `frontend/style.css`_
+
+### Fixed
+- **Settings Toggle Size:** Fixed inconsistent toggle switch sizing on mobile views, ensuring all toggles render at the correct dimensions (`47x24px`).
+ _File: `frontend/settings-styles.css`_
+- **Username Display:** Resolved an issue where user interface elements sometimes incorrectly displayed the username instead of the first name (or vice versa).
+ _Files: `frontend/settings-new.js`, `frontend/auth.js`
+- **List/Table View:** Implemented updates and fixes for the warranty list and table views, improving layout and data presentation.
+ _Files: `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_
+
## [0.9.9.2] - 2025-04-20
### Added
diff --git a/backend/app.py b/backend/app.py
index ab3f733..093bfc5 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -699,22 +699,22 @@ def request_password_reset():
# Construct the full reset link
reset_link = f"{email_base_url}/reset-password.html?token={reset_token}" # Use base URL and correct page
- # TODO: Implement actual email sending logic here
- logger.info(f"Password reset requested for user {user_id}. Reset link: {reset_link}")
- # Send email using send_email function (implement this)
- # subject = "Password Reset Request"
- # body = f"Click the link to reset your password: {reset_link}"
- # try:
- # send_email(email, subject, body) # Placeholder for email sending
- # except Exception as e:
- # logger.error(f"Failed to send password reset email to {email}: {e}")
- # # Still return success to the user, don't leak email failure
+ # Send password reset email
+ logger.info(f"Password reset requested for user {user_id}. Preparing to send email.")
+ try:
+ send_password_reset_email(email, reset_link)
+ logger.info(f"Password reset email initiated for {email}")
+ except Exception as e:
+ logger.error(f"Failed to send password reset email to {email}: {e}")
+ # Even if email fails, don't tell the user.
+ # This prevents leaking information about registered emails or email server issues.
+ # The user journey remains the same: "If registered, you'll get an email."
+ # Always return success to the user, regardless of email success/failure
return jsonify({
'message': 'If your email is registered, you will receive a password reset link.'
}), 200
- # Remove reset_link from response in production
- # 'reset_link': reset_link
+
except Exception as e:
logger.error(f"Password reset request error: {e}")
if conn:
@@ -724,54 +724,42 @@ def request_password_reset():
if conn:
release_db_connection(conn)
[email protected]('/api/auth/password/reset', methods=['POST'])
-def reset_password():
[email protected]('/api/auth/password/verify-token', methods=['GET'])
+def verify_reset_token():
+ """Verify if a password reset token is valid and not expired."""
+ token = request.args.get('token')
+
+ if not token:
+ return jsonify({'valid': False, 'message': 'Token is missing!'}), 400
+
conn = None
try:
- data = request.get_json()
-
- if not data.get('token') or not data.get('password'):
- return jsonify({'message': 'Token and password are required!'}), 400
-
- token = data['token']
- password = data['password']
-
- # Validate password strength
- if not is_valid_password(password):
- return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
-
conn = get_db_connection()
with conn.cursor() as cur:
- # Check if token exists and is valid
- cur.execute('SELECT user_id, expires_at FROM password_reset_tokens WHERE token = %s', (token,))
+ cur.execute('SELECT expires_at FROM password_reset_tokens WHERE token = %s', (token,))
token_info = cur.fetchone()
- if not token_info or token_info[1] < datetime.utcnow():
- return jsonify({'message': 'Invalid or expired token!'}), 400
+ if not token_info:
+ return jsonify({'valid': False, 'message': 'Token not found!'}), 404
- user_id = token_info[0]
+ expires_at = token_info[0]
+ if expires_at < datetime.utcnow():
+ return jsonify({'valid': False, 'message': 'Token has expired!'}), 410 # 410 Gone might be appropriate
- # Hash the new password
- password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
+ # Token is valid and not expired
+ return jsonify({'valid': True, 'message': 'Token is valid.'}), 200
- # Update user's password
- cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (password_hash, user_id))
-
- # Delete the used token
- cur.execute('DELETE FROM password_reset_tokens WHERE token = %s', (token,))
-
- conn.commit()
-
- return jsonify({'message': 'Password reset successful!'}), 200
except Exception as e:
- logger.error(f"Password reset error: {e}")
- if conn:
- conn.rollback()
- return jsonify({'message': 'Password reset failed!'}), 500
+ logger.error(f"Token verification error for token {token}: {e}")
+ return jsonify({'valid': False, 'message': 'Error verifying token!'}), 500
finally:
if conn:
release_db_connection(conn)
+# Note: The actual reset_password function is defined earlier in the file.
+# The duplicated block that caused the error has been removed.
+
+
# Update existing endpoints to use authentication
@app.route('/api/warranties', methods=['GET'])
@@ -864,6 +852,7 @@ def add_warranty():
serial_numbers = request.form.getlist('serial_numbers[]')
product_url = request.form.get('product_url', '')
user_id = request.user['id']
+ notes = request.form.get('notes', '')
# Get tag IDs if provided
tag_ids = []
@@ -937,13 +926,13 @@ def add_warranty():
cur.execute('''
INSERT INTO warranties (
product_name, purchase_date, warranty_years, expiration_date,
- invoice_path, manual_path, product_url, purchase_price, user_id, is_lifetime
+ invoice_path, manual_path, product_url, purchase_price, user_id, is_lifetime, notes
)
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
''', (
product_name, purchase_date, warranty_years, expiration_date,
- db_invoice_path, db_manual_path, product_url, purchase_price, user_id, is_lifetime
+ db_invoice_path, db_manual_path, product_url, purchase_price, user_id, is_lifetime, notes
))
warranty_id = cur.fetchone()[0]
@@ -1114,6 +1103,7 @@ def update_warranty(warranty_id):
# purchase_date_str = request.form['purchase_date'] # Moved up
serial_numbers = request.form.getlist('serial_numbers')
product_url = request.form.get('product_url', '')
+ notes = request.form.get('notes', None)
# Get tag IDs if provided
tag_ids = []
@@ -1164,7 +1154,20 @@ 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}")
-
+ # Handle invoice deletion if requested
+ elif request.form.get('delete_invoice', 'false').lower() == 'true':
+ cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_invoice_path = cur.fetchone()[0]
+ if old_invoice_path:
+ full_path = os.path.join('/data', old_invoice_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted invoice (delete request): {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting invoice (delete request): {e}")
+ db_invoice_path = None # Set to None to clear in DB
+
# Handle manual file upload if new file is provided
db_manual_path = None
if 'manual' in request.files:
@@ -1194,7 +1197,20 @@ 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}")
-
+ # Handle manual deletion if requested
+ elif request.form.get('delete_manual', 'false').lower() == 'true':
+ cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_manual_path = cur.fetchone()[0]
+ if old_manual_path:
+ full_path = os.path.join('/data', old_manual_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted manual (delete request): {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting manual (delete request): {e}")
+ db_manual_path = None # Set to None to clear in DB
+
# Update the warranty in database - IMPORTANT: The database set operation needs to be updated
# Create a list of parameters for the UPDATE query
# --- Modified: Add is_lifetime, use potentially None values ---
@@ -1215,17 +1231,25 @@ def update_warranty(warranty_id):
for key, value in update_params.items():
sql_fields.append(f"{key} = %s")
sql_values.append(value)
+ # Add notes to the update fields before executing the SQL
+ if notes is not None:
+ sql_fields.append("notes = %s")
+ sql_values.append(notes)
# 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)
-
+ elif 'delete_invoice' in request.form and request.form.get('delete_invoice', 'false').lower() == 'true':
+ sql_fields.append("invoice_path = NULL")
+
# 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)
-
+ elif 'delete_manual' in request.form and request.form.get('delete_manual', 'false').lower() == 'true':
+ sql_fields.append("manual_path = NULL")
+
# --- Add updated_at to the SET clause ---
sql_fields.append("updated_at = NOW()") # Use SQL function, no parameter needed
@@ -1582,25 +1606,18 @@ def delete_account():
@token_required
def get_preferences():
user_id = request.user['id']
-
try:
- # Get database connection
conn = get_db_connection()
cursor = conn.cursor()
-
try:
- # Check if user_preferences table exists
cursor.execute("""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'user_preferences'
)
""")
-
table_exists = cursor.fetchone()[0]
-
if not table_exists:
- # Create the user_preferences table
cursor.execute("""
CREATE TABLE user_preferences (
id SERIAL PRIMARY KEY,
@@ -1612,47 +1629,58 @@ def get_preferences():
notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily',
notification_time VARCHAR(5) NOT NULL DEFAULT '09:00',
timezone VARCHAR(50) NOT NULL DEFAULT 'UTC',
+ currency_symbol VARCHAR(8) DEFAULT '$',
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(user_id)
)
""")
-
- # Add index for faster lookups
cursor.execute("""
CREATE INDEX idx_user_preferences_user_id ON user_preferences(user_id)
""")
-
conn.commit()
logger.info(f"Created user_preferences table")
-
- # Get user preferences
- cursor.execute(
- """
- SELECT email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone
- FROM user_preferences
- WHERE user_id = %s
- """,
- (user_id,)
- )
-
- preferences_data = cursor.fetchone()
-
- if not preferences_data:
- # Create default preferences if not exists
+ has_currency = has_currency_symbol_column(cursor)
+ if has_currency:
cursor.execute(
"""
- 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
+ SELECT email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone, currency_symbol
+ FROM user_preferences
+ WHERE user_id = %s
""",
(user_id,)
)
-
+ else:
+ cursor.execute(
+ """
+ SELECT email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone
+ FROM user_preferences
+ WHERE user_id = %s
+ """,
+ (user_id,)
+ )
+ preferences_data = cursor.fetchone()
+ if not preferences_data:
+ if has_currency:
+ cursor.execute(
+ """
+ INSERT INTO user_preferences (user_id, email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone, currency_symbol)
+ VALUES (%s, TRUE, 'grid', 'light', 30, 'daily', '09:00', 'UTC', '$')
+ RETURNING email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone, currency_symbol
+ """,
+ (user_id,)
+ )
+ else:
+ cursor.execute(
+ """
+ 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,)
+ )
preferences_data = cursor.fetchone()
conn.commit()
-
- # Format preferences data
preferences = {
'email_notifications': preferences_data[0],
'default_view': preferences_data[1],
@@ -1660,16 +1688,13 @@ def get_preferences():
'expiring_soon_days': preferences_data[3],
'notification_frequency': preferences_data[4],
'notification_time': preferences_data[5],
- 'timezone': preferences_data[6]
+ 'timezone': preferences_data[6] if len(preferences_data) > 6 else 'UTC',
+ 'currency_symbol': preferences_data[7] if has_currency and len(preferences_data) > 7 and preferences_data[7] else '$'
}
-
return jsonify(preferences), 200
-
except Exception as e:
conn.rollback()
logger.error(f"Database error in get_preferences: {str(e)}")
-
- # Return default preferences as fallback
default_preferences = {
'email_notifications': True,
'default_view': 'grid',
@@ -1677,18 +1702,15 @@ def get_preferences():
'expiring_soon_days': 30,
'notification_frequency': 'daily',
'notification_time': '09:00',
- 'timezone': 'UTC'
+ 'timezone': 'UTC',
+ 'currency_symbol': '$'
}
-
return jsonify(default_preferences), 200
finally:
cursor.close()
release_db_connection(conn)
-
except Exception as e:
logger.error(f"Error in get_preferences: {str(e)}")
-
- # Return default preferences as fallback
default_preferences = {
'email_notifications': True,
'default_view': 'grid',
@@ -1696,24 +1718,19 @@ def get_preferences():
'expiring_soon_days': 30,
'notification_frequency': 'daily',
'notification_time': '09:00',
- 'timezone': 'UTC'
+ 'timezone': 'UTC',
+ 'currency_symbol': '$'
}
-
return jsonify(default_preferences), 200
@app.route('/api/auth/preferences', methods=['PUT'])
@token_required
def update_preferences():
user_id = request.user['id']
-
try:
- # Get request data
data = request.get_json()
-
if not data:
return jsonify({'message': 'No input data provided'}), 400
-
- # Extract fields
email_notifications = data.get('email_notifications')
default_view = data.get('default_view')
theme = data.get('theme')
@@ -1721,14 +1738,11 @@ def update_preferences():
notification_frequency = data.get('notification_frequency')
notification_time = data.get('notification_time')
timezone = data.get('timezone')
-
- # Validate input
+ currency_symbol = data.get('currency_symbol')
if default_view and default_view not in ['grid', 'list', 'table']:
return jsonify({'message': 'Invalid default view'}), 400
-
if theme and theme not in ['light', 'dark']:
return jsonify({'message': 'Invalid theme'}), 400
-
if expiring_soon_days is not None:
try:
expiring_soon_days = int(expiring_soon_days)
@@ -1736,42 +1750,23 @@ def update_preferences():
return jsonify({'message': 'Expiring soon days must be between 1 and 365'}), 400
except ValueError:
return jsonify({'message': 'Expiring soon days must be a valid number'}), 400
-
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 (
SELECT FROM information_schema.tables
WHERE table_name = 'user_preferences'
)
""")
-
table_exists = cursor.fetchone()[0]
-
if not table_exists:
- # Create the user_preferences table
cursor.execute("""
CREATE TABLE user_preferences (
id SERIAL PRIMARY KEY,
@@ -1783,85 +1778,67 @@ def update_preferences():
notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily',
notification_time VARCHAR(5) NOT NULL DEFAULT '09:00',
timezone VARCHAR(50) NOT NULL DEFAULT 'UTC',
+ currency_symbol VARCHAR(8) DEFAULT '$',
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(user_id)
)
""")
-
- # Add index for faster lookups
cursor.execute("""
CREATE INDEX idx_user_preferences_user_id ON user_preferences(user_id)
""")
-
- # Set preferences_exist to false to create new preferences
preferences_exist = False
conn.commit()
logger.info(f"Created user_preferences table")
- else:
- # Check if preferences exist
- cursor.execute(
- "SELECT 1 FROM user_preferences WHERE user_id = %s",
- (user_id,)
- )
-
- preferences_exist = cursor.fetchone() is not None
-
+ has_currency = has_currency_symbol_column(cursor)
+ cursor.execute(
+ "SELECT 1 FROM user_preferences WHERE user_id = %s",
+ (user_id,)
+ )
+ preferences_exist = cursor.fetchone() is not None
if preferences_exist:
- # Update existing preferences
update_fields = []
update_values = []
-
if email_notifications is not None:
update_fields.append("email_notifications = %s")
update_values.append(email_notifications)
-
if default_view:
update_fields.append("default_view = %s")
update_values.append(default_view)
-
if theme:
update_fields.append("theme = %s")
update_values.append(theme)
-
if expiring_soon_days is not None:
update_fields.append("expiring_soon_days = %s")
update_values.append(expiring_soon_days)
-
if 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:
+ if timezone:
update_fields.append("timezone = %s")
update_values.append(timezone)
-
+ if has_currency and currency_symbol is not None:
+ update_fields.append("currency_symbol = %s")
+ update_values.append(currency_symbol)
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"
-
+ return_fields = "email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone"
+ if has_currency:
+ return_fields += ", currency_symbol"
update_query = f"""
UPDATE user_preferences
SET {', '.join(update_fields)}
WHERE user_id = %s
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"
-
+ select_fields = "email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone"
+ if has_currency:
+ select_fields += ", currency_symbol"
cursor.execute(
f"""
SELECT {select_fields}
@@ -1872,9 +1849,7 @@ def update_preferences():
)
preferences_data = cursor.fetchone()
else:
- # Create new preferences
- # Check for timezone column to adjust INSERT statement
- if has_timezone_column:
+ if has_currency:
cursor.execute(
"""
INSERT INTO user_preferences (
@@ -1885,10 +1860,11 @@ def update_preferences():
expiring_soon_days,
notification_frequency,
notification_time,
- timezone
+ timezone,
+ currency_symbol
)
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
- RETURNING email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
+ RETURNING email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone, currency_symbol
""",
(
user_id,
@@ -1898,7 +1874,8 @@ def update_preferences():
expiring_soon_days if expiring_soon_days is not None else 30,
notification_frequency or 'daily',
notification_time or '09:00',
- timezone or 'UTC'
+ timezone or 'UTC',
+ currency_symbol or '$'
)
)
else:
@@ -1911,10 +1888,11 @@ def update_preferences():
theme,
expiring_soon_days,
notification_frequency,
- notification_time
+ notification_time,
+ timezone
)
- VALUES (%s, %s, %s, %s, %s, %s, %s)
- RETURNING email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time
+ 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,
@@ -1923,36 +1901,30 @@ def update_preferences():
theme or 'light',
expiring_soon_days if expiring_soon_days is not None else 30,
notification_frequency or 'daily',
- notification_time or '09:00'
+ notification_time or '09:00',
+ timezone or 'UTC'
)
)
preferences_data = cursor.fetchone()
-
- # Format preferences data
preferences = {
'email_notifications': preferences_data[0],
'default_view': preferences_data[1],
'theme': preferences_data[2],
'expiring_soon_days': preferences_data[3],
'notification_frequency': preferences_data[4],
- 'notification_time': preferences_data[5]
+ 'notification_time': preferences_data[5],
+ 'timezone': preferences_data[6] if len(preferences_data) > 6 else 'UTC',
+ # Use parentheses for line continuation
+ 'currency_symbol': (
+ currency_symbol if has_currency and currency_symbol is not None
+ else (preferences_data[7] if has_currency and len(preferences_data) > 7 and preferences_data[7] else '$')
+ )
}
-
- # 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
-
except Exception as e:
conn.rollback()
logger.error(f"Database error in update_preferences: {str(e)}")
-
- # Return original data as fallback
fallback_preferences = {
'email_notifications': email_notifications if email_notifications is not None else True,
'default_view': default_view or 'grid',
@@ -1960,18 +1932,15 @@ def update_preferences():
'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'
+ 'timezone': timezone or 'UTC',
+ 'currency_symbol': currency_symbol or '$'
}
-
return jsonify(fallback_preferences), 200
finally:
cursor.close()
release_db_connection(conn)
-
except Exception as e:
logger.error(f"Error in update_preferences: {str(e)}")
-
- # Return default preferences as fallback
default_preferences = {
'email_notifications': True,
'default_view': 'grid',
@@ -1979,9 +1948,9 @@ def update_preferences():
'expiring_soon_days': 30,
'notification_frequency': 'daily',
'notification_time': '09:00',
- 'timezone': 'UTC'
+ 'timezone': 'UTC',
+ 'currency_symbol': '$'
}
-
return jsonify(default_preferences), 200
# Admin User Management Endpoints
@@ -2489,6 +2458,116 @@ def format_expiration_email(user, warranties):
return msg
+def send_password_reset_email(recipient_email, reset_link):
+ """Sends the password reset email."""
+ logger.info(f"Attempting to send password reset email to {recipient_email}")
+
+ subject = "Warracker: Password Reset Request"
+
+ # Basic text body
+ text_body = f"""Hello,
+
+You requested a password reset for your Warracker account.
+
+Click the link below to set a new password:
+{reset_link}
+
+If you did not request this reset, please ignore this email. This link will expire in 24 hours.
+
+Thanks,
+The Warracker Team
+"""
+
+ # Basic HTML body
+ html_body = f"""<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>Warracker Password Reset</title>
+</head>
+<body style="font-family: sans-serif; line-height: 1.6;">
+ <h2>Warracker Password Reset Request</h2>
+ <p>Hello,</p>
+ <p>You requested a password reset for your Warracker account.</p>
+ <p>Click the button below to set a new password:</p>
+ <p style="margin: 25px 0;">
+ <a href="{reset_link}" style="background-color: #007bff; color: white; padding: 12px 20px; text-decoration: none; border-radius: 5px; font-weight: bold;">
+ Reset Your Password
+ </a>
+ </p>
+ <p>If the button doesn't work, copy and paste this link into your browser:</p>
+ <p><a href="{reset_link}">{reset_link}</a></p>
+ <p>If you did not request this reset, please ignore this email. This link will expire in 24 hours.</p>
+ <p>Thanks,<br>The Warracker Team</p>
+</body>
+</html>
+"""
+
+ # Get SMTP settings from environment variables
+ smtp_host = os.environ.get('SMTP_HOST', 'localhost')
+ smtp_port = int(os.environ.get('SMTP_PORT', '1025'))
+ smtp_username = os.environ.get('SMTP_USERNAME') # No default sender here, should be configured
+ smtp_password = os.environ.get('SMTP_PASSWORD')
+ # Use SMTP_USERNAME as sender if available, otherwise a default
+ sender_email = smtp_username or '[email protected]'
+
+ if not smtp_username:
+ logger.warning("SMTP_USERNAME environment variable not set. Using default sender address.")
+
+ # Create a MIMEMultipart object for both text and HTML
+ msg = MIMEMultipart('alternative')
+ msg['Subject'] = subject
+ msg['From'] = sender_email
+ msg['To'] = recipient_email
+
+ part1 = MIMEText(text_body, 'plain', 'utf-8')
+ part2 = MIMEText(html_body, 'html', 'utf-8')
+
+ msg.attach(part1)
+ msg.attach(part2)
+
+ # Connect to SMTP server and send
+ try:
+ server = None # Initialize server to None
+ if smtp_port == 465:
+ logger.info(f"Using SMTP_SSL connection for port 465 to host {smtp_host}")
+ server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=10) # Add timeout
+ else:
+ logger.info(f"Using standard SMTP connection for port {smtp_port} to host {smtp_host}")
+ server = smtplib.SMTP(smtp_host, smtp_port, timeout=10) # Add timeout
+ # Start TLS for security if not local debug server and not using SSL
+ # Check if host suggests a non-local environment
+ if smtp_host != 'localhost' and not smtp_host.startswith('127.'):
+ logger.info("Attempting to start TLS")
+ 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 email
+ logger.info(f"Sending email via {smtp_host}:{smtp_port} from {sender_email}")
+ server.sendmail(sender_email, recipient_email, msg.as_string())
+ logger.info(f"Password reset email successfully sent to {recipient_email}")
+
+ except smtplib.SMTPAuthenticationError as e:
+ logger.error(f"SMTP Authentication Error sending email to {recipient_email}: {e}")
+ # Re-raise a more generic exception or handle appropriately
+ raise Exception(f"SMTP Authentication failed for {smtp_username}") from e
+ except Exception as e:
+ logger.error(f"Failed to send password reset email to {recipient_email}: {e}")
+ logger.error(f"SMTP details used - Host: {smtp_host}, Port: {smtp_port}, Username: {smtp_username}, Sender: {sender_email}")
+ # Raise an exception to be caught by the calling function
+ raise Exception("Failed to send password reset email") from e
+ finally:
+ if server:
+ try:
+ server.quit()
+ logger.info("SMTP connection closed.")
+ except Exception as e:
+ logger.error(f"Error quitting SMTP connection: {e}")
+
# Create a lock for the notification function
notification_lock = threading.Lock()
# Track when notifications were last sent to each user
@@ -2747,7 +2826,6 @@ if __name__ == '__main__':
except Exception as e:
logger.error(f"Application startup error: {e}")
-# Move this code before the if __name__ == '__main__' block
@app.route('/api/admin/send-notifications', methods=['POST'])
@admin_required
def trigger_notifications():
@@ -3431,3 +3509,72 @@ def import_warranties():
release_db_connection(conn)
# --- End CSV Import Endpoint ---
+
+# --- PATCH START: Currency Symbol Support ---
+# 1. Add a helper function to check if the currency_symbol column exists in user_preferences
+
+def has_currency_symbol_column(cursor):
+ cursor.execute("""
+ SELECT column_name FROM information_schema.columns
+ WHERE table_name = 'user_preferences' AND column_name = 'currency_symbol'
+ """)
+ return cursor.fetchone() is not None
+
+# 2. Update GET /api/auth/preferences
+# - Add currency_symbol to CREATE TABLE, SELECT, INSERT, and response
+# - Default to '$' if not set
+#
+# 3. Update PUT /api/auth/preferences
+# - Accept currency_symbol from request data and update if provided
+# - Add currency_symbol to CREATE TABLE, SELECT, INSERT, UPDATE, and response
+# - Default to '$' if not set
+# --- PATCH END ---
+
[email protected]('/api/auth/password/reset', methods=['POST'])
+def reset_password():
+ conn = None
+ try:
+ data = request.get_json()
+
+ if not data.get('token') or not data.get('password'):
+ return jsonify({'message': 'Token and password are required!'}), 400
+
+ token = data['token']
+ password = data['password']
+
+ # Validate password strength
+ if not is_valid_password(password):
+ return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if token exists and is valid
+ cur.execute('SELECT user_id, expires_at FROM password_reset_tokens WHERE token = %s', (token,))
+ token_info = cur.fetchone()
+
+ if not token_info or token_info[1] < datetime.utcnow():
+ return jsonify({'message': 'Invalid or expired token!'}), 400
+
+ user_id = token_info[0]
+
+ # Hash the new password
+ password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
+
+ # Update user's password
+ cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (password_hash, user_id))
+
+ # Delete the used token
+ cur.execute('DELETE FROM password_reset_tokens WHERE token = %s', (token,))
+
+ conn.commit()
+
+ return jsonify({'message': 'Password reset successful!'}), 200
+ except Exception as e:
+ logger.error(f"Password reset error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Password reset failed!'}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
diff --git a/backend/migrations/000_create_warranties_table.sql b/backend/migrations/000_create_warranties_table.sql
index 900f89f..f14738a 100644
--- a/backend/migrations/000_create_warranties_table.sql
+++ b/backend/migrations/000_create_warranties_table.sql
@@ -10,6 +10,7 @@ CREATE TABLE IF NOT EXISTS warranties (
invoice_path TEXT,
manual_path TEXT,
product_url TEXT,
+ notes TEXT,
-- purchase_price is added by migration 002
-- user_id is added by migration 003
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
diff --git a/backend/migrations/006_add_currency_symbol_column.py b/backend/migrations/006_add_currency_symbol_column.py
new file mode 100644
index 0000000..ae12d21
--- /dev/null
+++ b/backend/migrations/006_add_currency_symbol_column.py
@@ -0,0 +1,20 @@
+# Migration: Add currency_symbol column to user_preferences
+import psycopg2
+
+def upgrade(cur):
+ # Check if column already exists
+ cur.execute("""
+ SELECT column_name FROM information_schema.columns
+ WHERE table_name='user_preferences' AND column_name='currency_symbol'
+ """)
+ if not cur.fetchone():
+ cur.execute("""
+ ALTER TABLE user_preferences ADD COLUMN currency_symbol VARCHAR(8) DEFAULT '$';
+ """)
+ print("Added currency_symbol column to user_preferences table")
+
+def downgrade(cur):
+ cur.execute("""
+ ALTER TABLE user_preferences DROP COLUMN IF EXISTS currency_symbol;
+ """)
+ print("Removed currency_symbol column from user_preferences table")
\ No newline at end of file
diff --git a/backend/migrations/014_add_notes_to_warranties.sql b/backend/migrations/014_add_notes_to_warranties.sql
new file mode 100644
index 0000000..eb2924e
--- /dev/null
+++ b/backend/migrations/014_add_notes_to_warranties.sql
@@ -0,0 +1,2 @@
+-- Migration: Add notes column to warranties table if it does not exist
+ALTER TABLE warranties ADD COLUMN IF NOT EXISTS notes TEXT;
\ No newline at end of file
diff --git a/frontend/about.html b/frontend/about.html
index 4a943a4..b1517a1 100644
--- a/frontend/about.html
+++ b/frontend/about.html
@@ -88,7 +88,7 @@
<div class="about-container" style="background-color: var(--card-bg); color: var(--text-color); padding: 20px; border-radius: 8px; margin-top: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); width: 100%; box-sizing: border-box;">
<h1 style="color: var(--primary-color); margin-bottom: 20px;">About Warracker</h1>
- <p><strong>Version:</strong> v0.9.9.2</p>
+ <p><strong>Version:</strong> v0.9.9.3</p>
<p>
<strong>GitHub Repository:</strong>
diff --git a/frontend/auth-new.js b/frontend/auth-new.js
index 6fd3161..15e414b 100644
--- a/frontend/auth-new.js
+++ b/frontend/auth-new.js
@@ -88,7 +88,7 @@ function updateUIForAuthenticatedUser() {
// Show user info if it exists
const userDisplay = document.querySelector('.user-display');
if (userDisplay && currentUser) {
- const displayName = currentUser.first_name || currentUser.username || 'User';
+ let displayName = currentUser.username || 'User';
userDisplay.textContent = displayName;
userDisplay.style.display = 'inline-block';
}
diff --git a/frontend/auth.js b/frontend/auth.js
index 9a77dc7..562c4f8 100644
--- a/frontend/auth.js
+++ b/frontend/auth.js
@@ -145,7 +145,7 @@ function updateUIForAuthenticatedUser() {
}
// Update user info in the header menu
- const displayName = currentUser.first_name || currentUser.username || 'User'; // Fallback added
+ let displayName = currentUser.username || 'User';
const fullName = `${currentUser.first_name || ''} ${currentUser.last_name || ''}`.trim() || currentUser.username || 'User Name'; // Fallback added
const email = currentUser.email || '[email protected]'; // Fallback added
diff --git a/frontend/fix-auth-buttons.js b/frontend/fix-auth-buttons.js
index e55896d..49e301f 100644
--- a/frontend/fix-auth-buttons.js
+++ b/frontend/fix-auth-buttons.js
@@ -84,7 +84,7 @@ function updateAuthButtons() {
if (userInfo) {
try {
const user = JSON.parse(userInfo);
- const username = user.first_name || user.username || 'User';
+ const username = user.username || 'User';
console.log('Setting username to:', username);
// Find username display elements
diff --git a/frontend/include-auth-new.js b/frontend/include-auth-new.js
index 3e3009c..d5c21ab 100644
--- a/frontend/include-auth-new.js
+++ b/frontend/include-auth-new.js
@@ -56,7 +56,7 @@ if (localStorage.getItem('auth_token')) {
var userInfoStr = localStorage.getItem('user_info');
if (userInfoStr) {
var userInfo = JSON.parse(userInfoStr);
- var displayName = userInfo.first_name || userInfo.username || 'User';
+ var displayName = userInfo.username || 'User';
var userDisplayName = document.getElementById('userDisplayName');
if (userDisplayName) {
diff --git a/frontend/index.html b/frontend/index.html
index b18a07d..53f5094 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -167,7 +167,7 @@
<div class="search-container">
<div class="search-box">
<i class="fas fa-search"></i>
- <input type="text" id="searchWarranties" placeholder="Find products by name or tag...">
+ <input type="text" id="searchWarranties" placeholder="Find products by name, notes or tag...">
<button id="clearSearch" class="clear-search-btn" title="Clear search" style="display: none;">
<i class="fas fa-times"></i>
</button>
@@ -326,6 +326,10 @@
<input type="number" id="purchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">
</div>
</div>
+ <div class="form-group">
+ <label for="notes">Notes (Optional)</label>
+ <textarea id="notes" name="notes" class="form-control" rows="3" placeholder="Add any notes about this warranty..."></textarea>
+ </div>
</div>
<!-- Documents Tab -->
<div class="tab-content" id="documents">
@@ -529,6 +533,10 @@
<input type="number" id="editPurchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">
</div>
</div>
+ <div class="form-group">
+ <label for="editNotes">Notes (Optional)</label>
+ <textarea id="editNotes" name="notes" class="form-control" rows="3" placeholder="Add any notes about this warranty..."></textarea>
+ </div>
</div>
<!-- Documents Tab -->
@@ -543,8 +551,8 @@
</div>
<div id="editFileName" class="file-name"></div>
<div id="currentInvoice" class="mt-10"></div>
+ <button type="button" id="deleteInvoiceBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Invoice</button>
</div>
-
<div class="form-group">
<label>Product Manual (Optional)</label>
<div class="file-input-wrapper">
@@ -555,6 +563,7 @@
</div>
<div id="editManualFileName" class="file-name"></div>
<div id="currentManual" class="mt-10"></div>
+ <button type="button" id="deleteManualBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Manual</button>
</div>
</div>
diff --git a/frontend/login.html b/frontend/login.html
index b507fad..96fa0b4 100644
--- a/frontend/login.html
+++ b/frontend/login.html
@@ -216,9 +216,12 @@
console.error('Login error:', error);
showMessage(error.message || 'Login failed. Please check your credentials.', 'error');
- // Reset button
- submitBtn.innerHTML = originalBtnText;
- submitBtn.disabled = false;
+ // Reset button state explicitly
+ const submitBtn = loginForm.querySelector('button[type="submit"]'); // Ensure we have the button reference
+ if (submitBtn) {
+ submitBtn.innerHTML = '<i class="fas fa-sign-in-alt"></i> Login'; // Set back to original text
+ submitBtn.disabled = false; // Re-enable the button
+ }
}
});
diff --git a/frontend/register.html b/frontend/register.html
index 655bdfb..46ab107 100644
--- a/frontend/register.html
+++ b/frontend/register.html
@@ -275,7 +275,7 @@
<div class="container">
<div class="app-title">
<i class="fas fa-shield-alt"></i>
- <h1>Warranty Tracker</h1>
+ <h1>Warracker</h1>
</div>
</div>
</header>
diff --git a/frontend/reset-password-request.html b/frontend/reset-password-request.html
index 7db34f5..96c8ce9 100644
--- a/frontend/reset-password-request.html
+++ b/frontend/reset-password-request.html
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Reset Password - Warranty Tracker</title>
+ <title>Warracker - Reset Password</title>
<!-- Favicons -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
@@ -87,7 +87,7 @@
<div class="container">
<div class="app-title">
<i class="fas fa-shield-alt"></i>
- <h1>Warranty Tracker</h1>
+ <h1>Warracker</h1>
</div>
</div>
</header>
@@ -152,10 +152,19 @@
return;
}
+ // Get the submit button element
+ const submitBtn = resetRequestForm.querySelector('button[type="submit"]');
+ let originalBtnText = ''; // Initialize outside
+
+ if (!submitBtn) {
+ console.error('Submit button not found');
+ showMessage('An unexpected error occurred. Please try again.', 'error');
+ return;
+ }
+
try {
// Show loading state
- const submitBtn = resetRequestForm.querySelector('button[type="submit"]');
- const originalBtnText = submitBtn.innerHTML;
+ originalBtnText = submitBtn.innerHTML; // Assign original text here
submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending Request...';
submitBtn.disabled = true;
@@ -186,9 +195,11 @@
console.error('Password reset request error:', error);
showMessage(error.message || 'Password reset request failed. Please try again.', 'error');
} finally {
- // Reset button
- submitBtn.innerHTML = originalBtnText;
- submitBtn.disabled = false;
+ // Reset button only if it exists
+ if (submitBtn) {
+ submitBtn.innerHTML = originalBtnText;
+ submitBtn.disabled = false;
+ }
}
});
diff --git a/frontend/reset-password.html b/frontend/reset-password.html
index 0f77e39..1e62325 100644
--- a/frontend/reset-password.html
+++ b/frontend/reset-password.html
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Set New Password - Warranty Tracker</title>
+ <title>Warracker - Set New Password</title>
<!-- Favicons -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
@@ -144,7 +144,7 @@
<div class="container">
<div class="app-title">
<i class="fas fa-shield-alt"></i>
- <h1>Warranty Tracker</h1>
+ <h1>Warracker</h1>
</div>
</div>
</header>
diff --git a/frontend/script.js b/frontend/script.js
index 5ecf0d0..e965deb 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -169,6 +169,8 @@ document.addEventListener('DOMContentLoaded', function() {
lifetimeCheckbox.addEventListener('change', handleLifetimeChange);
handleLifetimeChange({ target: lifetimeCheckbox }); // Initial check
}
+
+ updateCurrencySymbols();
});
// Initialize theme based on user preference or system preference
@@ -1087,6 +1089,7 @@ async function renderWarranties(warrantiesToRender) {
}
const today = new Date();
+ const symbol = getCurrencySymbol(); // Get the correct symbol HERE
warrantiesList.innerHTML = '';
@@ -1139,17 +1142,10 @@ async function renderWarranties(warrantiesToRender) {
const statusText = warranty.statusText || 'Unknown Status';
const warrantyYearsText = isLifetime ? 'Lifetime' : (warranty.warranty_years !== undefined ? `${warranty.warranty_years} ${warranty.warranty_years === 1 ? 'year' : 'years'}` : 'N/A');
const expirationDateText = isLifetime ? 'Lifetime' : formatDate(expirationDate);
-
- // 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() !== '')
: [];
-
// Prepare tags HTML
const tagsHtml = warranty.tags && warranty.tags.length > 0
? `<div class="tags-row">
@@ -1160,6 +1156,14 @@ async function renderWarranties(warrantiesToRender) {
).join('')}
</div>`
: '';
+ // Add notes display button if present
+ let notesHtml = '';
+ const hasNotes = warranty.notes && warranty.notes.trim() !== '';
+ // Remove the button, and instead prepare a notes link for document-links-row
+ let notesLinkHtml = '';
+ if (hasNotes) {
+ notesLinkHtml = `<a href="#" class="notes-link" data-id="${warranty.id}" title="View Notes"><i class='fas fa-sticky-note'></i> Notes</a>`;
+ }
const cardElement = document.createElement('div');
cardElement.className = `warranty-card ${statusClass === 'expired' ? 'expired' : statusClass === 'expiring' ? 'expiring-soon' : 'active'}`;
@@ -1183,7 +1187,7 @@ async function renderWarranties(warrantiesToRender) {
<div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
<div>Warranty: <span>${warrantyYearsText}</span></div>
<div>Expires: <span>${expirationDateText}</span></div>
- ${warranty.purchase_price ? `<div>Price: <span>$${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
+ ${warranty.purchase_price ? `<div><span>Price: </span><span class="currency-symbol">${symbol}</span><span>${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
${validSerialNumbers.length > 0 ? `
<div class="serial-numbers">
<strong>Serial Numbers:</strong>
@@ -1198,19 +1202,22 @@ async function renderWarranties(warrantiesToRender) {
<span>${statusText}</span>
</div>
<div class="document-links-row">
- ${warranty.product_url ? `
- <a href="${warranty.product_url}" class="product-link" target="_blank">
- <i class="fas fa-globe"></i> Product Website
- </a>
- ` : ''}
- ${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 !== 'null' ? `
- <a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;" class="manual-link">
- <i class="fas fa-book"></i> Manual
- </a>` : ''}
+ <div class="document-links-inner-container">
+ ${warranty.product_url ? `
+ <a href="${warranty.product_url}" class="product-link" target="_blank">
+ <i class="fas fa-globe"></i> Product Website
+ </a>
+ ` : ''}
+ ${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 !== 'null' ? `
+ <a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;" class="manual-link">
+ <i class="fas fa-book"></i> Manual
+ </a>` : ''}
+ ${notesLinkHtml}
+ </div>
</div>
${tagsHtml}
`;
@@ -1233,7 +1240,7 @@ async function renderWarranties(warrantiesToRender) {
<div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
<div>Warranty: <span>${warrantyYearsText}</span></div>
<div>Expires: <span>${expirationDateText}</span></div>
- ${warranty.purchase_price ? `<div>Price: <span>$${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
+ ${warranty.purchase_price ? `<div><span>Price: </span><span class="currency-symbol">${symbol}</span><span>${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
${validSerialNumbers.length > 0 ? `
<div class="serial-numbers">
<strong>Serial Numbers:</strong>
@@ -1248,19 +1255,22 @@ async function renderWarranties(warrantiesToRender) {
<span>${statusText}</span>
</div>
<div class="document-links-row">
- ${warranty.product_url ? `
- <a href="${warranty.product_url}" class="product-link" target="_blank">
- <i class="fas fa-globe"></i>
- </a>
- ` : ''}
- ${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 !== 'null' ? `
- <a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;" class="manual-link">
- <i class="fas fa-book"></i> Manual
- </a>` : ''}
+ <div class="document-links-inner-container">
+ ${warranty.product_url ? `
+ <a href="${warranty.product_url}" class="product-link" target="_blank">
+ <i class="fas fa-globe"></i> Product Website
+ </a>
+ ` : ''}
+ ${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 !== 'null' ? `
+ <a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;" class="manual-link">
+ <i class="fas fa-book"></i> Manual
+ </a>` : ''}
+ ${notesLinkHtml}
+ </div>
</div>
${tagsHtml}
`;
@@ -1288,19 +1298,22 @@ async function renderWarranties(warrantiesToRender) {
<span>${statusText}</span>
</div>
<div class="document-links-row">
- ${warranty.product_url ? `
- <a href="${warranty.product_url}" class="product-link" target="_blank">
- <i class="fas fa-globe"></i>
- </a>
- ` : ''}
- ${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 !== 'null' ? `
- <a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;" class="manual-link">
- <i class="fas fa-book"></i> Manual
- </a>` : ''}
+ <div class="document-links-inner-container">
+ ${warranty.product_url ? `
+ <a href="${warranty.product_url}" class="product-link" target="_blank">
+ <i class="fas fa-globe"></i> Product Website
+ </a>
+ ` : ''}
+ ${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 !== 'null' ? `
+ <a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;" class="manual-link">
+ <i class="fas fa-book"></i> Manual
+ </a>` : ''}
+ ${notesLinkHtml}
+ </div>
</div>
${tagsHtml}
`;
@@ -1318,6 +1331,14 @@ async function renderWarranties(warrantiesToRender) {
cardElement.querySelector('.delete-btn').addEventListener('click', () => {
openDeleteModal(warranty.id, warranty.product_name);
});
+ // View notes button event listener
+ const notesLink = cardElement.querySelector('.notes-link');
+ if (notesLink) {
+ notesLink.addEventListener('click', (e) => {
+ e.preventDefault();
+ showNotesModal(warranty.notes, warranty);
+ });
+ }
});
}
@@ -1343,7 +1364,14 @@ function filterWarranties() {
// Check tags
if (warranty.tags && Array.isArray(warranty.tags)) {
- return warranty.tags.some(tag => tag.name && tag.name.toLowerCase().includes(searchTerm)); // Add null check
+ if (warranty.tags.some(tag => tag.name && tag.name.toLowerCase().includes(searchTerm))) {
+ return true;
+ }
+ }
+
+ // Check notes
+ if (warranty.notes && warranty.notes.toLowerCase().includes(searchTerm)) {
+ return true;
}
return false;
@@ -1382,16 +1410,15 @@ function applyFilters() {
// Search filter
if (currentFilters.search) {
const searchTerm = currentFilters.search.toLowerCase();
-
// Check if product name contains search term
const productNameMatch = warranty.product_name.toLowerCase().includes(searchTerm);
-
// Check if any tag name contains search term
const tagMatch = warranty.tags && Array.isArray(warranty.tags) &&
warranty.tags.some(tag => tag.name.toLowerCase().includes(searchTerm));
-
- // Return true if either product name or tag name matches
- if (!productNameMatch && !tagMatch) {
+ // Check if notes contains search term
+ const notesMatch = warranty.notes && warranty.notes.toLowerCase().includes(searchTerm);
+ // Return true if any match
+ if (!productNameMatch && !tagMatch && !notesMatch) {
return false;
}
}
@@ -1474,7 +1501,8 @@ function openEditModal(warranty) {
// Show current invoice if exists
const currentInvoiceElement = document.getElementById('currentInvoice');
- if (currentInvoiceElement) {
+ const deleteInvoiceBtn = document.getElementById('deleteInvoiceBtn');
+ if (currentInvoiceElement && deleteInvoiceBtn) {
if (warranty.invoice_path && warranty.invoice_path !== 'null') {
currentInvoiceElement.innerHTML = `
<span class="text-success">
@@ -1483,14 +1511,23 @@ function openEditModal(warranty) {
(Upload a new file to replace)
</span>
`;
+ deleteInvoiceBtn.style.display = '';
} else {
currentInvoiceElement.innerHTML = '<span>No invoice uploaded</span>';
+ deleteInvoiceBtn.style.display = 'none';
}
+ // Reset delete state
+ deleteInvoiceBtn.dataset.delete = 'false';
+ deleteInvoiceBtn.onclick = function() {
+ deleteInvoiceBtn.dataset.delete = 'true';
+ currentInvoiceElement.innerHTML = '<span class="text-danger">Invoice will be deleted on save</span>';
+ deleteInvoiceBtn.style.display = 'none';
+ };
}
-
// Show current manual if exists
const currentManualElement = document.getElementById('currentManual');
- if (currentManualElement) {
+ const deleteManualBtn = document.getElementById('deleteManualBtn');
+ if (currentManualElement && deleteManualBtn) {
if (warranty.manual_path && warranty.manual_path !== 'null') {
currentManualElement.innerHTML = `
<span class="text-success">
@@ -1499,9 +1536,18 @@ function openEditModal(warranty) {
(Upload a new file to replace)
</span>
`;
+ deleteManualBtn.style.display = '';
} else {
currentManualElement.innerHTML = '<span>No manual uploaded</span>';
+ deleteManualBtn.style.display = 'none';
}
+ // Reset delete state
+ deleteManualBtn.dataset.delete = 'false';
+ deleteManualBtn.onclick = function() {
+ deleteManualBtn.dataset.delete = 'true';
+ currentManualElement.innerHTML = '<span class="text-danger">Manual will be deleted on save</span>';
+ deleteManualBtn.style.display = 'none';
+ };
}
// Reset file inputs
@@ -1619,6 +1665,12 @@ function openEditModal(warranty) {
} else {
console.error("Lifetime warranty elements not found in edit form");
}
+
+ // Set notes
+ const notesInput = document.getElementById('editNotes');
+ if (notesInput) {
+ notesInput.value = warranty.notes || '';
+ }
}
function openDeleteModal(warrantyId, productName) {
@@ -1820,6 +1872,8 @@ document.addEventListener('DOMContentLoaded', function() {
// Load preferences (if needed for things other than theme)
// loadPreferences(); // Consider if needed
+
+ updateCurrencySymbols();
});
// Add this function to handle edit tab functionality
@@ -2859,11 +2913,29 @@ function saveWarranty() {
formData.append('manual', manualFile);
}
+ // Document deletion flags
+ const deleteInvoiceBtn = document.getElementById('deleteInvoiceBtn');
+ if (deleteInvoiceBtn && deleteInvoiceBtn.dataset.delete === 'true') {
+ formData.append('delete_invoice', 'true');
+ }
+ const deleteManualBtn = document.getElementById('deleteManualBtn');
+ if (deleteManualBtn && deleteManualBtn.dataset.delete === 'true') {
+ formData.append('delete_manual', 'true');
+ }
+
// --- Append is_lifetime and warranty_years ---
formData.append('is_lifetime', isLifetime.toString());
if (!isLifetime) {
formData.append('warranty_years', warrantyYears);
}
+ // Add notes
+ const notes = document.getElementById('editNotes').value;
+ if (notes && notes.trim() !== '') {
+ formData.append('notes', notes);
+ } else {
+ // Explicitly clear notes if empty
+ formData.append('notes', '');
+ }
// Get auth token
const token = localStorage.getItem('auth_token');
@@ -2894,7 +2966,44 @@ function saveWarranty() {
hideLoadingSpinner();
showToast('Warranty updated successfully', 'success');
closeModals();
- loadWarranties();
+ // Update the notes in the card immediately if present
+ if (typeof currentWarrantyId !== 'undefined' && currentWarrantyId !== null) {
+ const card = document.querySelector(`.warranty-card .edit-btn[data-id="${currentWarrantyId}"]`);
+ if (card) {
+ const cardElement = card.closest('.warranty-card');
+ if (cardElement) {
+ // Remove old notes button if present
+ const oldNotesBtn = cardElement.querySelector('.view-notes-btn');
+ if (oldNotesBtn) oldNotesBtn.remove();
+ // Get the new notes value
+ const newNotes = document.getElementById('editNotes').value;
+ if (newNotes && newNotes.trim() !== '') {
+ // Add the button if not present
+ let notesBtn = cardElement.querySelector('.view-notes-btn');
+ if (!notesBtn) {
+ const btn = document.createElement('button');
+ btn.className = 'btn btn-secondary btn-sm view-notes-btn';
+ btn.setAttribute('data-id', currentWarrantyId);
+ btn.style.margin = '10px 0 0 0';
+ btn.innerHTML = '<i class="fas fa-sticky-note"></i> View Notes';
+ btn.addEventListener('click', () => showNotesModal(newNotes));
+ // Insert after tags row if present, else at end
+ const tagsRow = cardElement.querySelector('.tags-row');
+ if (tagsRow && tagsRow.nextSibling) {
+ cardElement.insertBefore(btn, tagsRow.nextSibling);
+ } else {
+ cardElement.appendChild(btn);
+ }
+ }
+ } else {
+ // If notes are empty, ensure the button is removed
+ const notesBtn = cardElement.querySelector('.view-notes-btn');
+ if (notesBtn) notesBtn.remove();
+ }
+ }
+ }
+ }
+ loadWarranties(); // Still reload to ensure all data is fresh
})
.catch(error => {
hideLoadingSpinner();
@@ -3209,4 +3318,220 @@ window.addEventListener('storage', (event) => {
}
}
});
-// --- End Storage Event Listener ---
\ No newline at end of file
+// --- End Storage Event Listener ---
+
+// Add modal HTML to the end of the body if not present
+if (!document.getElementById('notesModal')) {
+ const notesModal = document.createElement('div');
+ notesModal.id = 'notesModal';
+ notesModal.className = 'modal-backdrop';
+ notesModal.innerHTML = `
+ <div class="modal" style="max-width: 500px;">
+ <div class="modal-header">
+ <h3 class="modal-title">Warranty Notes</h3>
+ <button class="close-btn" id="closeNotesModal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <div id="notesModalContent" style="white-space: pre-line;"></div>
+ <textarea id="notesModalTextarea" style="display:none;width:100%;min-height:100px;"></textarea>
+ </div>
+ <div class="modal-footer" id="notesModalFooter">
+ <button class="btn btn-secondary" id="editNotesBtn">Edit</button>
+ <button class="btn btn-primary" id="saveNotesBtn" style="display:none;">Save</button>
+ <button class="btn btn-danger" id="cancelEditNotesBtn" style="display:none;">Cancel</button>
+ </div>
+ </div>
+ `;
+ document.body.appendChild(notesModal);
+ document.getElementById('closeNotesModal').addEventListener('click', () => {
+ notesModal.classList.remove('active');
+ });
+}
+
+// Add global to track which warranty is being edited in the notes modal
+let notesModalWarrantyId = null;
+let notesModalWarrantyObj = null;
+
+function showNotesModal(notes, warrantyOrId = null) {
+ const notesModal = document.getElementById('notesModal');
+ const notesModalContent = document.getElementById('notesModalContent');
+ const notesModalTextarea = document.getElementById('notesModalTextarea');
+ const editBtn = document.getElementById('editNotesBtn');
+ const saveBtn = document.getElementById('saveNotesBtn');
+ const cancelBtn = document.getElementById('cancelEditNotesBtn');
+
+ // Support both (notes, warrantyObj) and (notes, id) for backward compatibility
+ if (typeof warrantyOrId === 'object' && warrantyOrId !== null) {
+ notesModalWarrantyId = warrantyOrId.id;
+ notesModalWarrantyObj = warrantyOrId;
+ } else {
+ notesModalWarrantyId = warrantyOrId;
+ // Try to find the warranty object from global warranties array
+ notesModalWarrantyObj = warranties.find(w => w.id === notesModalWarrantyId) || null;
+ }
+
+ // Show note content, hide textarea and edit controls
+ notesModalContent.style.display = '';
+ notesModalContent.textContent = notes;
+ notesModalTextarea.style.display = 'none';
+ editBtn.style.display = '';
+ saveBtn.style.display = 'none';
+ cancelBtn.style.display = 'none';
+
+ // Edit button handler
+ editBtn.onclick = function() {
+ notesModalContent.style.display = 'none';
+ notesModalTextarea.style.display = '';
+ notesModalTextarea.value = notes;
+ editBtn.style.display = 'none';
+ saveBtn.style.display = '';
+ cancelBtn.style.display = '';
+ notesModalTextarea.focus();
+ };
+ // Save button handler
+ saveBtn.onclick = async function() {
+ const newNote = notesModalTextarea.value.trim(); // Trim the note
+ if (!notesModalWarrantyId || !notesModalWarrantyObj) {
+ showToast('No warranty selected for note update', 'error');
+ return;
+ }
+ // Save note via API, sending all required fields
+ try {
+ showLoadingSpinner();
+ const token = localStorage.getItem('auth_token');
+ const formData = new FormData();
+ // --- Populate with existing data to avoid clearing fields ---
+ formData.append('product_name', notesModalWarrantyObj.product_name);
+ formData.append('purchase_date', (notesModalWarrantyObj.purchase_date || '').split('T')[0]);
+ formData.append('is_lifetime', notesModalWarrantyObj.is_lifetime ? 'true' : 'false');
+ if (!notesModalWarrantyObj.is_lifetime) {
+ formData.append('warranty_years', notesModalWarrantyObj.warranty_years || ''); // Use empty string if null/undefined
+ }
+ if (notesModalWarrantyObj.product_url) {
+ formData.append('product_url', notesModalWarrantyObj.product_url);
+ }
+ if (notesModalWarrantyObj.purchase_price !== null && notesModalWarrantyObj.purchase_price !== undefined) { // Check for null/undefined
+ formData.append('purchase_price', notesModalWarrantyObj.purchase_price);
+ }
+ if (notesModalWarrantyObj.serial_numbers && Array.isArray(notesModalWarrantyObj.serial_numbers)) {
+ notesModalWarrantyObj.serial_numbers.forEach(sn => {
+ if (sn && sn.trim() !== '') {
+ formData.append('serial_numbers', sn);
+ }
+ });
+ }
+ // Send empty array if no serial numbers exist or are provided
+ else if (!formData.has('serial_numbers')) {
+ formData.append('serial_numbers', JSON.stringify([]));
+ }
+
+ if (notesModalWarrantyObj.tags && Array.isArray(notesModalWarrantyObj.tags)) {
+ const tagIds = notesModalWarrantyObj.tags.map(tag => tag.id);
+ formData.append('tag_ids', JSON.stringify(tagIds));
+ }
+ // Send empty array if no tags exist or are provided
+ else {
+ formData.append('tag_ids', JSON.stringify([]));
+ }
+ // --- End Populate ---
+
+ formData.append('notes', newNote); // Append the potentially empty, trimmed note
+
+ const response = await fetch(`/api/warranties/${notesModalWarrantyId}`, { // Added await and response handling
+ method: 'PUT',
+ headers: {
+ 'Authorization': 'Bearer ' + token
+ },
+ body: formData
+ });
+
+ if (!response.ok) { // Check if the API call was successful
+ const errorData = await response.json().catch(() => ({})); // Try to parse error, default to empty object
+ throw new Error(errorData.error || `Failed to update note (Status: ${response.status})`);
+ }
+
+
+ hideLoadingSpinner();
+ showToast('Note updated', 'success');
+
+ // --- Updated UI logic ---
+ if (newNote === '') {
+ // If the note is now empty, close the modal
+ document.getElementById('notesModal').classList.remove('active');
+ } else {
+ // If note is not empty, update the view and stay in the modal
+ notesModalContent.textContent = newNote;
+ notesModalContent.style.display = '';
+ notesModalTextarea.style.display = 'none';
+ editBtn.style.display = '';
+ saveBtn.style.display = 'none';
+ cancelBtn.style.display = 'none';
+ // Update the local warranty object's notes
+ if (notesModalWarrantyObj) {
+ notesModalWarrantyObj.notes = newNote;
+ }
+ }
+ // --- End Updated UI logic ---
+
+ // Refresh warranties list to update the card UI state (e.g., show/hide notes link)
+ loadWarranties();
+ } catch (e) {
+ hideLoadingSpinner();
+ console.error("Error updating note:", e); // Log the error
+ showToast(e.message || 'Failed to update note', 'error'); // Show specific error if available
+ }
+ };
+ // Cancel button handler
+ cancelBtn.onclick = function() {
+ notesModalContent.style.display = '';
+ notesModalTextarea.style.display = 'none';
+ editBtn.style.display = '';
+ saveBtn.style.display = 'none';
+ cancelBtn.style.display = 'none';
+ };
+ notesModal.classList.add('active');
+}
+
+// Utility to get currency symbol from preferences/localStorage
+function getCurrencySymbol() {
+ const prefix = getPreferenceKeyPrefix();
+ console.log(`[getCurrencySymbol] Using prefix: ${prefix}`); // Log prefix
+ let symbol = '$'; // Default value
+ try {
+ const prefsString = localStorage.getItem(`${prefix}preferences`);
+ console.log(`[getCurrencySymbol] Read prefsString for ${prefix}preferences:`, prefsString); // Log raw string
+ if (prefsString) {
+ const prefs = JSON.parse(prefsString);
+ // Use the symbol from prefs if it exists, otherwise keep the default
+ if (prefs && prefs.currency_symbol) {
+ symbol = prefs.currency_symbol;
+ }
+ }
+ } catch (e) {
+ console.error(`Error reading ${prefix}preferences from localStorage:`, e);
+ // Keep the default '$' symbol in case of error
+ }
+ console.log(`[getCurrencySymbol] Returning symbol: ${symbol}`); // Log final symbol
+ return symbol;
+}
+
+function updateCurrencySymbols() {
+ const symbol = getCurrencySymbol();
+ console.log(`Updating currency symbols to: ${symbol}`); // Log the symbol being applied
+ const elements = document.querySelectorAll('.currency-symbol');
+ console.log(`Found ${elements.length} elements with class 'currency-symbol'.`); // Log how many elements are found
+ elements.forEach(el => {
+ // console.log('Updating element:', el); // Optional: Log each element being updated
+ el.textContent = symbol;
+ });
+}
+
+// If you want to update currency symbols live when storage changes (e.g. settings page open in another tab):
+window.addEventListener('storage', function(e) {
+ const prefix = getPreferenceKeyPrefix();
+ // Only update if the main preferences object for the current user type changed
+ if (e.key === `${prefix}preferences`) {
+ console.log(`Storage event detected for ${prefix}preferences. Updating currency symbols.`);
+ updateCurrencySymbols();
+ }
+});
\ No newline at end of file
diff --git a/frontend/settings-new.html b/frontend/settings-new.html
index 4ea9ee5..15805ad 100644
--- a/frontend/settings-new.html
+++ b/frontend/settings-new.html
@@ -205,6 +205,28 @@
</div>
</div>
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Currency Symbol</label>
+ <p class="text-muted">Choose the symbol to display for prices</p>
+ </div>
+ <select id="currencySymbolSelect" class="form-control" style="width: 120px; font-size: 1.1em;">
+ <option value="$">$ (USD)</option>
+ <option value="€">€ (EUR)</option>
+ <option value="£">£ (GBP)</option>
+ <option value="¥">¥ (JPY/CNY)</option>
+ <option value="₹">₹ (INR)</option>
+ <option value="₩">₩ (KRW)</option>
+ <option value="CHF">CHF (Swiss Franc)</option>
+ <option value="CAD">CAD (Canadian Dollar)</option>
+ <option value="AUD">AUD (Australian Dollar)</option>
+ <option value="other">Other...</option>
+ </select>
+ <input type="text" id="currencySymbolCustom" class="form-control" maxlength="6" style="width: 70px; text-align: center; font-size: 1.2em; display: none; margin-left: 10px;" placeholder="Custom">
+ </div>
+ </div>
+
<div class="form-group">
<div class="preference-item">
<div>
diff --git a/frontend/settings-new.js b/frontend/settings-new.js
index 88d55d6..a69d12e 100644
--- a/frontend/settings-new.js
+++ b/frontend/settings-new.js
@@ -43,6 +43,9 @@ const triggerNotificationsBtn = document.getElementById('triggerNotificationsBtn
const registrationEnabled = document.getElementById('registrationEnabled');
const saveSiteSettingsBtn = document.getElementById('saveSiteSettingsBtn');
const emailBaseUrlInput = document.getElementById('emailBaseUrl'); // Added for email base URL
+const currencySymbolInput = document.getElementById('currencySymbol');
+const currencySymbolSelect = document.getElementById('currencySymbolSelect');
+const currencySymbolCustom = document.getElementById('currencySymbolCustom');
/**
* Set theme (dark/light) - Unified and persistent
@@ -61,10 +64,10 @@ function setTheme(isDark) {
localStorage.setItem('darkMode', isDark);
// Sync both toggles if present
if (typeof darkModeToggle !== 'undefined' && darkModeToggle) {
- darkModeToggle.checked = isDark;
+ darkModeToggle.checked = isDarkMode;
}
if (typeof darkModeToggleSetting !== 'undefined' && darkModeToggleSetting) {
- darkModeToggleSetting.checked = isDark;
+ darkModeToggleSetting.checked = isDarkMode;
}
// Also update user_preferences.theme for backward compatibility
try {
@@ -132,6 +135,9 @@ document.addEventListener('DOMContentLoaded', function() {
console.error('Error loading timezones/prefs:', err);
loadPreferences(); // Try loading prefs anyway
});
+
+ // --- ADD THIS LINE TO INITIALIZE MODALS ---
+ initModals();
});
/**
@@ -298,7 +304,12 @@ async function loadUserData() {
if (emailInput) emailInput.value = currentUser.email || ''; // Add null checks
// --- UPDATE DISPLAY ELEMENT (Initial Load) ---
- const displayName = `${currentUser.first_name || ''} ${currentUser.last_name || ''}`.trim() || currentUser.username || 'User';
+ let displayName;
+ if (currentUser.first_name && currentUser.last_name) {
+ displayName = `${currentUser.first_name} ${currentUser.last_name}`;
+ } else {
+ displayName = currentUser.username || 'User';
+ }
if (userNameDisplay) userNameDisplay.textContent = displayName;
if (userEmailDisplay) userEmailDisplay.textContent = currentUser.email || 'N/A';
// --- END UPDATE ---
@@ -331,7 +342,12 @@ async function loadUserData() {
if (emailInput) emailInput.value = userData.email || ''; // Add null checks
// --- UPDATE DISPLAY ELEMENT (After API Load) ---
- const displayName = `${userData.first_name || ''} ${userData.last_name || ''}`.trim() || userData.username || 'User';
+ let displayName;
+ if (userData.first_name && userData.last_name) {
+ displayName = `${userData.first_name} ${userData.last_name}`;
+ } else {
+ displayName = userData.username || 'User';
+ }
if (userNameDisplay) userNameDisplay.textContent = displayName;
if (userEmailDisplay) userEmailDisplay.textContent = userData.email || 'N/A';
// --- END UPDATE ---
@@ -346,7 +362,21 @@ async function loadUserData() {
}
// Update localStorage
- localStorage.setItem('user_info', JSON.stringify(userData));
+ const currentUser = window.auth.getCurrentUser();
+ let first_name = userData.first_name;
+ let last_name = userData.last_name;
+ if (!last_name) first_name = '';
+ const updatedUser = {
+ ...(currentUser || {}), // Handle case where currentUser might be null
+ first_name,
+ last_name,
+ // Ensure email and username are preserved if they existed
+ email: currentUser ? currentUser.email : userData.email,
+ username: currentUser ? currentUser.username : userData.username,
+ is_admin: currentUser ? currentUser.is_admin : userData.is_admin,
+ id: currentUser ? currentUser.id : userData.id
+ };
+ localStorage.setItem('user_info', JSON.stringify(updatedUser));
} else {
const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
console.warn('API error fetching user data:', errorData.message);
@@ -476,10 +506,36 @@ function loadPreferences() {
if (timezoneSelect && preferences.timezone) {
timezoneSelect.value = preferences.timezone;
}
+
+ // Currency symbol preference
+ let symbol = '$';
+ if (preferences && preferences.currency_symbol) {
+ symbol = preferences.currency_symbol;
+ }
+ if (currencySymbolSelect && currencySymbolCustom) {
+ // If symbol is in the dropdown, select it; else, select 'other' and show custom
+ const found = Array.from(currencySymbolSelect.options).some(opt => opt.value === symbol);
+ if (found) {
+ currencySymbolSelect.value = symbol;
+ currencySymbolCustom.style.display = 'none';
+ currencySymbolCustom.value = '';
+ } else {
+ currencySymbolSelect.value = 'other';
+ currencySymbolCustom.style.display = '';
+ currencySymbolCustom.value = symbol;
+ }
+ }
}
} catch (e) {
console.error('Error loading preferences from localStorage:', e);
+ // Fallback to default '$' using the correct elements
+ if (currencySymbolSelect) currencySymbolSelect.value = '$';
+ if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
}
+ } else {
+ // Fallback to default '$' if no localStorage and defaultViewLoaded is true
+ if (currencySymbolSelect) currencySymbolSelect.value = '$';
+ if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
}
// Load preferences from API (API data should override if available, except maybe for default view if already loaded)
@@ -537,6 +593,21 @@ function loadPreferences() {
}, 500);
}
+ // Currency symbol from API
+ let apiSymbol = data.currency_symbol || '$';
+ if (currencySymbolSelect && currencySymbolCustom) {
+ const found = Array.from(currencySymbolSelect.options).some(opt => opt.value === apiSymbol);
+ if (found) {
+ currencySymbolSelect.value = apiSymbol;
+ currencySymbolCustom.style.display = 'none';
+ currencySymbolCustom.value = '';
+ } else {
+ currencySymbolSelect.value = 'other';
+ currencySymbolCustom.style.display = '';
+ currencySymbolCustom.value = apiSymbol;
+ }
+ }
+
// Store in localStorage with the appropriate prefix
localStorage.setItem(`${prefix}preferences`, JSON.stringify(apiPrefs));
})
@@ -712,41 +783,37 @@ function setupEventListeners() {
* Initialize modals
*/
function initModals() {
+ // Helper to close all modals and reset forms
+ function closeModalHandler(e) {
+ if (e) e.preventDefault();
+ document.querySelectorAll('.modal-backdrop').forEach(modal => {
+ modal.style.display = 'none';
+ });
+ // Reset delete confirm input
+ if (deleteConfirmInput) {
+ deleteConfirmInput.value = '';
+ confirmDeleteAccountBtn.disabled = true;
+ }
+ // Reset password form
+ resetPasswordForm();
+ }
+
// Close modal when clicking on X or outside
document.querySelectorAll('.close-btn, [data-dismiss="modal"]').forEach(closeBtn => {
- closeBtn.addEventListener('click', () => {
- document.querySelectorAll('.modal-backdrop').forEach(modal => {
- modal.style.display = 'none';
- });
-
- // Reset delete confirm input
- if (deleteConfirmInput) {
- deleteConfirmInput.value = '';
- confirmDeleteAccountBtn.disabled = true;
- }
-
- // Reset password form
- resetPasswordForm();
- });
+ closeBtn.addEventListener('click', closeModalHandler);
+ closeBtn.addEventListener('touchend', closeModalHandler);
});
- // Close modal when clicking outside
- window.addEventListener('click', (event) => {
+ // Close modal when clicking outside (backdrop)
+ function backdropHandler(event) {
document.querySelectorAll('.modal-backdrop').forEach(modal => {
if (event.target === modal) {
- modal.style.display = 'none';
-
- // Reset delete confirm input
- if (deleteConfirmInput) {
- deleteConfirmInput.value = '';
- confirmDeleteAccountBtn.disabled = true;
- }
-
- // Reset password form
- resetPasswordForm();
+ closeModalHandler(event);
}
});
- });
+ }
+ window.addEventListener('click', backdropHandler);
+ window.addEventListener('touchend', backdropHandler);
// Add direct click handler to delete user modal
if (deleteUserModal) {
@@ -829,10 +896,13 @@ async function saveProfile() {
// Update localStorage
const currentUser = window.auth.getCurrentUser();
+ let first_name = userData.first_name;
+ let last_name = userData.last_name;
+ if (!last_name) first_name = '';
const updatedUser = {
...(currentUser || {}), // Handle case where currentUser might be null
- first_name: userData.first_name,
- last_name: userData.last_name,
+ first_name,
+ last_name,
// Ensure email and username are preserved if they existed
email: currentUser ? currentUser.email : userData.email,
username: currentUser ? currentUser.username : userData.username,
@@ -842,7 +912,12 @@ async function saveProfile() {
localStorage.setItem('user_info', JSON.stringify(updatedUser));
// --- UPDATE DISPLAY ELEMENT IMMEDIATELY ---
- const displayName = `${userData.first_name || ''} ${userData.last_name || ''}`.trim() || updatedUser.username || 'User'; // Use updatedUser for username fallback
+ let displayName;
+ if (userData.first_name && userData.last_name) {
+ displayName = `${userData.first_name} ${userData.last_name}`;
+ } else {
+ displayName = updatedUser.username || 'User';
+ }
if (userNameDisplay) userNameDisplay.textContent = displayName;
// --- END UPDATE ---
@@ -886,6 +961,12 @@ function savePreferences() {
const notificationFrequency = notificationFrequencySelect.value;
const notificationTime = notificationTimeInput.value;
const timezone = timezoneSelect.value;
+ let currencySymbol = '$';
+ if (currencySymbolSelect && currencySymbolSelect.value === 'other') {
+ currencySymbol = currencySymbolCustom && currencySymbolCustom.value ? currencySymbolCustom.value : '$';
+ } else if (currencySymbolSelect) {
+ currencySymbol = currencySymbolSelect.value;
+ }
// Validate inputs
if (isNaN(expiringSoonDays) || expiringSoonDays < 1 || expiringSoonDays > 365) {
@@ -908,7 +989,8 @@ function savePreferences() {
expiring_soon_days: expiringSoonDays,
notification_frequency: notificationFrequency,
notification_time: notificationTime,
- timezone: timezone
+ timezone: timezone,
+ currency_symbol: currencySymbol
};
// Save to API
@@ -2854,4 +2936,17 @@ window.addEventListener('storage', (event) => {
}
}
});
-// --- End Storage Event Listener ---
\ No newline at end of file
+// --- End Storage Event Listener ---
+
+// Add event listener for dropdown to show/hide custom input
+if (currencySymbolSelect && currencySymbolCustom) {
+ currencySymbolSelect.addEventListener('change', function() {
+ if (this.value === 'other') {
+ currencySymbolCustom.style.display = '';
+ currencySymbolCustom.focus();
+ } else {
+ currencySymbolCustom.style.display = 'none';
+ currencySymbolCustom.value = '';
+ }
+ });
+}
\ No newline at end of file
diff --git a/frontend/settings-styles.css b/frontend/settings-styles.css
index b8f48d3..6adf2c9 100644
--- a/frontend/settings-styles.css
+++ b/frontend/settings-styles.css
@@ -260,8 +260,9 @@ header .container {
.toggle-switch {
position: relative;
display: inline-block;
- width: 50px;
+ width: 47px;
height: 24px;
+ flex-shrink: 0;
}
.toggle-switch input {
@@ -277,6 +278,8 @@ header .container {
left: 0;
right: 0;
bottom: 0;
+ width: 100%;
+ height: 100%;
background-color: var(--medium-gray);
transition: .4s;
border-radius: 34px;
@@ -301,7 +304,7 @@ input:checked + .toggle-slider {
}
input:checked + .toggle-slider:before {
- transform: translateX(26px);
+ transform: translateX(23px);
}
/* Responsive */
diff --git a/frontend/status.html b/frontend/status.html
index 7762f52..351a935 100644
--- a/frontend/status.html
+++ b/frontend/status.html
@@ -151,6 +151,12 @@
.register-btn:hover {
background-color: var(--primary-dark);
}
+
+ @media (max-width: 768px) {
+ .export-btn .export-text {
+ display: none;
+ }
+ }
</style>
<!-- Immediate authentication check script -->
@@ -362,7 +368,7 @@
</select>
</div>
<button id="exportBtn" class="export-btn" title="Export data">
- <i class="fas fa-download"></i> Export
+ <i class="fas fa-download"></i> <span class="export-text">Export</span>
</button>
</div>
</div>
@@ -374,7 +380,6 @@
<th class="sortable" data-sort="purchase">Purchase Date <i class="fas fa-sort"></i></th>
<th class="sortable" data-sort="expiration">Expiration Date <i class="fas fa-sort"></i></th>
<th class="sortable" data-sort="status">Status <i class="fas fa-sort"></i></th>
- <th>Actions</th>
</tr>
</thead>
<tbody id="recentExpirationsBody">
diff --git a/frontend/status.js b/frontend/status.js
index 30b8c28..39f4e48 100644
--- a/frontend/status.js
+++ b/frontend/status.js
@@ -466,9 +466,17 @@ function filterAndSortWarranties() {
// Compare values based on sort direction
if (currentSort.direction === 'asc') {
- return valueA > valueB ? 1 : valueA < valueB ? -1 : 0;
+ if (valueA instanceof Date && valueB instanceof Date) {
+ return valueA.getTime() - valueB.getTime();
+ } else {
+ return valueA > valueB ? 1 : valueA < valueB ? -1 : 0;
+ }
} else {
- return valueA < valueB ? 1 : valueA > valueB ? -1 : 0;
+ if (valueA instanceof Date && valueB instanceof Date) {
+ return valueB.getTime() - valueA.getTime();
+ } else {
+ return valueA < valueB ? 1 : valueA > valueB ? -1 : 0;
+ }
}
});
@@ -553,14 +561,6 @@ function filterAndSortWarranties() {
<td>${purchaseDate}</td>
<td>${formattedExpirationDate}</td>
<td><span class="${statusClass}">${statusText}</span></td>
- <td>
- <a href="index.html?edit=${warranty.id}" class="action-btn edit-btn" title="Edit">
- <i class="fas fa-edit"></i>
- </a>
- <a href="#" onclick="window.openSecureFile ? openSecureFile('${warranty.invoice_path || ''}') : alert('File viewer not available'); return false;" class="action-btn view-btn" title="View Invoice" ${!warranty.invoice_path ? 'style="display: none;"' : ''}>
- <i class="fas fa-file-alt"></i>
- </a>
- </td>
`;
tableBody.appendChild(row);
@@ -653,8 +653,41 @@ async function initDashboard() {
console.log('Global allWarranties length AFTER assignment:', allWarranties.length); // Log length after assignment
filterAndSortWarranties(); // Apply initial filters/sort to the table
- // Setup event listeners AFTER data is loaded and initial render is done
- setupEventListeners();
+ // Attach sort listeners *after* initial render
+ attachSortListeners();
+
+ // Re-add other listeners previously in setupEventListeners
+ const searchInput = document.getElementById('searchWarranties');
+ const filterSelect = document.getElementById('statusFilter');
+ const exportDataBtn = document.getElementById('exportBtn');
+ const refreshBtn = document.getElementById('refreshDashboardBtn'); // Use the correct ID
+
+ if (refreshBtn) {
+ // Avoid adding multiple listeners if initDashboard is called again
+ if (!refreshBtn.hasAttribute('data-listener-added')) {
+ refreshBtn.addEventListener('click', refreshDashboard); // Call the refresh wrapper
+ refreshBtn.setAttribute('data-listener-added', 'true');
+ }
+ }
+ if (searchInput) {
+ if (!searchInput.hasAttribute('data-listener-added')) {
+ searchInput.addEventListener('input', filterAndSortWarranties);
+ searchInput.setAttribute('data-listener-added', 'true');
+ }
+ }
+ if (filterSelect) {
+ if (!filterSelect.hasAttribute('data-listener-added')) {
+ filterSelect.addEventListener('change', filterAndSortWarranties);
+ filterSelect.setAttribute('data-listener-added', 'true');
+ }
+ }
+ if (exportDataBtn) {
+ if (!exportDataBtn.hasAttribute('data-listener-added')) {
+ exportDataBtn.addEventListener('click', exportWarrantyData);
+ exportDataBtn.setAttribute('data-listener-added', 'true');
+ }
+ }
+ console.log("Attached other listeners (search, filter, export, refresh).")
hideLoading();
} catch (error) {
@@ -800,10 +833,6 @@ function displayRecentExpirations(expirations) {
<td>${new Date(warranty.purchase_date).toLocaleDateString()}</td>
<td>${new Date(warranty.expiration_date).toLocaleDateString()} (${daysText})</td>
<td><span class="status-${statusClass}">${warranty.status.replace('_', ' ')}</span></td>
- <td>
- <a href="index.html#warranty-${warranty.id}" class="action-btn view-btn" title="View Warranty"><i class="fas fa-eye"></i></a>
- <!-- Add edit/delete if needed -->
- </td>
`;
});
}
@@ -894,51 +923,30 @@ function getStatusText(expirationDateStr, today) {
return 'Active';
}
-// Function to setup event listeners specific to the status page
-function setupEventListeners() {
- console.log("Setting up status page event listeners...");
- const refreshBtn = document.getElementById('refreshStatusBtn');
- const searchInput = document.getElementById('searchWarranties');
- const filterSelect = document.getElementById('statusFilter');
- const exportDataBtn = document.getElementById('exportBtn');
+// Define attachSortListeners globally within the script scope
+function attachSortListeners() {
const headers = document.querySelectorAll('.sortable');
-
- if (refreshBtn) {
- refreshBtn.addEventListener('click', initDashboard); // Reload everything on refresh
- }
- if (searchInput) {
- searchInput.addEventListener('input', filterAndSortWarranties);
- }
- if (filterSelect) {
- filterSelect.addEventListener('change', filterAndSortWarranties);
- }
- if (exportDataBtn) {
- exportDataBtn.addEventListener('click', exportWarrantyData);
- }
- if (headers) {
- headers.forEach(header => {
- header.addEventListener('click', () => {
- const column = header.getAttribute('data-sort');
- if (currentSort.column === column) {
- currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
- } else {
- currentSort.column = column;
- currentSort.direction = 'asc';
- }
- updateSortHeaderClasses();
- filterAndSortWarranties();
- });
+ headers.forEach(header => {
+ // Clear potentially existing listener to prevent duplicates if this is called multiple times
+ // A more robust way might involve checking if a listener already exists, but this is simpler
+ const newHeader = header.cloneNode(true);
+ header.parentNode.replaceChild(newHeader, header);
+
+ newHeader.addEventListener('click', () => {
+ const column = newHeader.getAttribute('data-sort');
+ if (currentSort.column === column) {
+ currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
+ } else {
+ currentSort.column = column;
+ currentSort.direction = 'asc';
+ }
+ updateSortHeaderClasses();
+ filterAndSortWarranties();
});
- }
-
- // NOTE: The theme toggle listener is set up in DOMContentLoaded
- console.log("Status page event listeners setup complete.");
+ });
+ console.log("Attached sort listeners.");
}
-// Dummy checkLoginStatus and setupSettingsMenu for completeness
-// function checkLoginStatus() { console.log("Checking login status..."); }
-// function setupSettingsMenu() { console.log("Setting up settings menu..."); }
-
// --- Initialization ---
// IMPORTANT: Ensure ALL function definitions are ABOVE this listener
document.addEventListener('DOMContentLoaded', () => {
@@ -958,11 +966,14 @@ document.addEventListener('DOMContentLoaded', () => {
// Initialize the main dashboard logic
initDashboard();
-
+
+ // Setup event listeners for search/filter/export/sort
+ // setupEventListeners(); // Removed: listeners now attached in initDashboard
+
// Setup settings menu (assuming it's part of the shared header)
// if (typeof setupSettingsMenu === 'function') {
// setupSettingsMenu();
// } else if (window.auth && typeof window.auth.setupSettingsMenu === 'function') {
// window.auth.setupSettingsMenu();
// }
-});
\ No newline at end of file
+});
\ No newline at end of file
diff --git a/frontend/style.css b/frontend/style.css
index 755b3f1..50f4938 100644
--- a/frontend/style.css
+++ b/frontend/style.css
@@ -14,7 +14,6 @@
--secondary-color: #2ecc71;
--danger-color: #e74c3c;
--warning-color: #f39c12;
- --text-color: #333333;
--light-gray: #f5f5f5;
--medium-gray: #e0e0e0;
--dark-gray: #777777;
@@ -22,6 +21,16 @@
--shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
--border-radius: 8px;
--transition: all 0.3s ease;
+
+ /* Ensure warranty card title is white in table view light mode */
+ .table-view .warranty-title {
+ color: #FFFFFF; /* White text for better contrast */
+ }
+
+ /* Make action button icons white in table view light mode */
+ .table-view .product-name-header .action-btn i {
+ color: #FFFFFF; /* White icon color */
+ }
}
* {
@@ -52,6 +61,16 @@
--text-muted: #909090;
--input-background: #1a1a1a;
--border-radius: 8px; /* Added missing border radius for dark theme */
+
+ /* Ensure warranty card title is white in table view dark mode */
+ .table-view .warranty-title {
+ color: #FFFFFF; /* White text for better contrast */
+ }
+
+ /* Make action button icons white in table view dark mode */
+ .table-view .product-name-header .action-btn i {
+ color: #FFFFFF; /* White icon color */
+ }
}
body {
@@ -981,7 +1000,7 @@ input.invalid {
gap: 5px;
}
- .invoice-link, .manual-link, .product-link {
+ .invoice-link, .manual-link, .product-link, .notes-link {
width: 100%;
justify-content: center;
}
@@ -1298,14 +1317,16 @@ input:checked + .toggle-slider:before {
.table-responsive {
overflow-x: auto;
width: 100%;
+ min-width: 0;
+ padding-right: 0;
}
#recentExpirationsTable {
+ table-layout: auto;
width: 100%;
border-collapse: separate;
border-spacing: 0;
- table-layout: fixed;
- border-right: 1px solid transparent;
+ border-right: none;
}
#recentExpirationsTable th,
@@ -1313,50 +1334,18 @@ input:checked + .toggle-slider:before {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid var(--border-color);
+ width: auto;
+ min-width: 120px;
+ max-width: none;
+ white-space: nowrap;
}
-/* Define column widths */
-#recentExpirationsTable th:nth-child(1),
-#recentExpirationsTable td:nth-child(1) {
- width: 25%;
- text-align: left;
-}
-
-#recentExpirationsTable th:nth-child(2),
-#recentExpirationsTable td:nth-child(2) {
- width: 20%;
- text-align: left;
-}
-
-#recentExpirationsTable th:nth-child(3),
-#recentExpirationsTable td:nth-child(3) {
- width: 20%;
- text-align: left;
-}
-
-#recentExpirationsTable th:nth-child(4),
-#recentExpirationsTable td:nth-child(4) {
- width: 20%;
- text-align: left;
-}
-
-#recentExpirationsTable th:nth-child(5),
-#recentExpirationsTable td:nth-child(5) {
- width: 15%;
- text-align: left;
-}
-
-#recentExpirationsTable thead th {
- background-color: rgba(0, 0, 0, 0.03);
- color: var(--text-color);
- font-weight: 600;
- position: sticky;
- top: 0;
- z-index: 10;
+#recentExpirationsTable td {
+ white-space: normal;
}
-#recentExpirationsTable tbody tr:hover {
- background-color: rgba(0, 0, 0, 0.03);
+#recentExpirationsTable tbody {
+ min-height: 250px; /* Ensure minimum height for the table body */
}
#recentExpirationsTable .no-data {
@@ -1391,15 +1380,6 @@ input:checked + .toggle-slider:before {
z-index: 0;
}
-#recentExpirationsTable td:last-child {
- display: flex;
- flex-direction: row;
- gap: 10px;
- justify-content: center;
- align-items: center;
- border-bottom: none;
-}
-
#recentExpirationsTable .action-btn {
display: inline-flex;
align-items: center;
@@ -1687,33 +1667,39 @@ tr.status-expiring {
.document-links-row {
display: flex;
- flex-wrap: wrap;
- gap: 8px;
+ /* flex-wrap: wrap; */ /* Remove wrapping */
+ /* gap: 8px; */ /* Remove gap, use margin on items */
margin-top: 15px;
justify-content: flex-start;
+ flex-direction: row; /* Explicitly set row direction */
+ align-items: center; /* Align items vertically */
+ /* Add border and background for consistency */
+ padding: 10px 15px;
+ background-color: rgba(0, 0, 0, 0.03);
+ border-top: 1px solid var(--border-color);
}
-.invoice-link, .manual-link, .product-link {
- display: inline-flex !important;
- align-items: center !important;
- color: var(--primary-color) !important;
- text-decoration: none !important;
- font-weight: 500 !important;
- padding: 5px 10px !important;
- background-color: var(--light-gray) !important;
- border-radius: var(--border-radius) !important;
- transition: var(--transition) !important;
- border: none !important;
- margin: 0 !important;
- white-space: nowrap !important;
+.invoice-link, .manual-link, .product-link, .notes-link { /* Added .notes-link here */
+ display: inline-flex; /* Remove !important */
+ align-items: center !important; /* Keep important if needed for vertical icon align */
+ color: var(--primary-color) !important; /* Keep appearance */
+ text-decoration: none !important; /* Keep appearance */
+ font-weight: 500 !important; /* Keep appearance */
+ padding: 5px 10px !important; /* Keep appearance */
+ background-color: var(--light-gray) !important; /* Keep appearance */
+ border-radius: var(--border-radius) !important; /* Keep appearance */
+ transition: var(--transition) !important; /* Keep appearance */
+ border: none !important; /* Keep appearance */
+ margin: 0 5px 0 0 !important; /* Add right margin for spacing, remove others */
+ white-space: nowrap !important; /* Keep appearance */
}
-.invoice-link i, .manual-link i, .product-link i {
+.invoice-link i, .manual-link i, .product-link i, .notes-link i { /* Added .notes-link here */
margin-right: 5px !important;
font-size: 1rem !important;
}
-.invoice-link:hover, .manual-link:hover, .product-link:hover {
+.invoice-link:hover, .manual-link:hover, .product-link:hover, .notes-link:hover {
text-decoration: none !important;
background-color: var(--medium-gray) !important;
color: var(--primary-dark) !important;
@@ -2108,6 +2094,7 @@ input.invalid {
display: table-row;
border: none;
border-bottom: 1px solid var(--border-color);
+ height: auto; /* Explicitly allow row height to adjust to content */
}
.table-view .warranty-card.expired {
@@ -2179,34 +2166,36 @@ input.invalid {
}
.table-view .document-links-row {
- display: table-cell;
- vertical-align: middle;
+ display: table-cell; /* Restore table-cell display */
+ vertical-align: middle; /* Restore vertical alignment */
padding: 12px 15px;
width: 20%; /* Set width for document links */
- overflow: hidden; /* Prevent overflow */
- text-align: center; /* Center align the content */
+}
+
+/* ADD: New rule for inner container */
+.document-links-inner-container {
+ display: flex;
+ flex-direction: column;
+ justify-content: center; /* Vertically center the group */
+ align-items: center; /* Horizontally center the group */
+ height: 100%; /* Fill cell height */
+ gap: 5px; /* Space between links */
}
/* Specific styling for links in table view */
.table-view .document-links-row a {
- display: inline-block !important; /* Allow links to be centered */
- margin: 0 auto 5px !important; /* Center links and add space between */
white-space: nowrap !important;
- overflow: hidden !important;
- text-overflow: ellipsis !important;
+ overflow: hidden !important; /* Restore overflow hidden */
+ text-overflow: ellipsis !important; /* Restore text overflow */
max-width: 90% !important; /* Slightly narrower to ensure centering works */
font-size: 0.9rem !important; /* Slightly smaller font size */
padding: 4px 8px !important; /* Smaller padding */
text-align: left !important; /* Keep text left-aligned within the link */
-}
-
-.table-view .document-links-row a i {
- font-size: 0.9rem !important; /* Smaller icon size */
- margin-right: 4px !important; /* Less spacing after icon */
+ width: auto; /* Allow natural width */
}
.table-view .document-links-row a:last-child {
- margin-bottom: 0 !important;
+ /* margin-bottom: 0 !important; */ /* Not needed */
}
.table-view .serial-numbers {
@@ -2315,8 +2304,7 @@ input.invalid {
}
.table-view .document-links-row {
- display: flex;
- flex-wrap: wrap;
+ display: block; /* Make it block for mobile card layout */
gap: 10px;
border-top: 1px solid var(--border-color);
background-color: rgba(0, 0, 0, 0.03);
@@ -2325,16 +2313,13 @@ input.invalid {
}
/* Reset the block display for links on mobile */
+ /* This might need adjustment if the parent is no longer flex */
.table-view .document-links-row a {
display: inline-flex !important;
- margin-bottom: 0 !important;
+ margin-bottom: 5px !important; /* Add back some margin */
max-width: none !important;
flex: 0 1 auto !important;
}
-
- .table-view .warranty-actions .action-btn {
- color: white;
- }
}
/* Price input styling */
@@ -2344,7 +2329,8 @@ input.invalid {
align-items: center;
}
-.currency-symbol {
+/* Apply absolute positioning ONLY inside input wrappers */
+.price-input-wrapper .currency-symbol {
position: absolute;
left: 12px;
color: var(--dark-gray);
@@ -2352,6 +2338,13 @@ input.invalid {
z-index: 1;
}
+/* Default style for currency symbols (e.g., on cards) */
+.currency-symbol {
+ display: inline; /* Ensure it stays inline */
+ margin-right: 0.2em; /* Add a small space after the symbol */
+ /* Remove absolute positioning properties if they were here */
+}
+
.price-input-wrapper .form-control {
padding-left: 25px;
}
@@ -2512,59 +2505,6 @@ input.invalid {
}
}
-#recentExpirationsTable td:last-child {
- display: flex;
- flex-direction: row;
- gap: 10px;
- justify-content: center;
- align-items: center;
-}
-
-/* Override the border-collapse for this specific table */
-#recentExpirationsTable {
- border-collapse: separate;
- border-spacing: 0;
- table-layout: fixed;
-}
-
-/* Ensure all cells have proper borders */
-#recentExpirationsTable th,
-#recentExpirationsTable td {
- border-bottom: 1px solid var(--border-color);
-}
-
-#recentExpirationsTable .action-btn {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 32px;
- height: 32px;
- border-radius: 4px;
- background-color: var(--light-gray);
- color: var(--text-color);
- text-decoration: none;
- transition: all 0.2s ease;
-}
-
-#recentExpirationsTable .action-btn:hover {
- background-color: var(--primary-color);
- color: white;
-}
-
-#recentExpirationsTable .edit-btn:hover {
- background-color: var(--secondary-color);
-}
-
-#recentExpirationsTable .view-btn:hover {
- background-color: var(--info-color);
-}
-
-@media (max-width: 768px) {
- #recentExpirationsTable td:last-child {
- padding: 8px;
- }
-}
-
/* GitHub link styling */
.settings-link.github-link {
background-color: #24292e; /* GitHub's dark color */
@@ -2671,26 +2611,6 @@ input.invalid {
margin-bottom: 2px;
}
-#recentExpirationsTable tbody {
- min-height: 250px; /* Ensure minimum height for the table body */
-}
-
-#recentExpirationsTable .no-data {
- text-align: center;
- color: var(--dark-gray);
- padding: 50px 30px;
- font-size: 1.2em;
-}
-
-#recentExpirationsTable .empty-row {
- height: 250px; /* Fixed height for the empty row */
-}
-
-#recentExpirationsTable .empty-row td {
- vertical-align: middle;
- text-align: center;
-}
-
/* Edit Warranty Tabs */
.edit-tabs-nav {
display: flex;
@@ -3033,11 +2953,6 @@ input.invalid {
} */
/* Forms */
-// ... existing code ...
-/* ===== WARRANTIES LIST ===== */
-.warranties-panel {
-// ... existing code ...
-}
/* ADD styles for Panel Header */
.panel-header {
@@ -3101,4 +3016,129 @@ input.invalid {
.main-content {
grid-template-columns: 1fr;
}
+}
+
+.warranty-notes {
+ background: #f8f9fa;
+ color: #333;
+ border-left: 4px solid var(--primary-color, #007bff);
+ padding: 8px 12px;
+ margin: 10px 0 0 0;
+ font-size: 0.97rem;
+ border-radius: 4px;
+ white-space: pre-line;
+}
+
+/* Custom style for View Notes button to match refined requirements */
+.view-notes-btn {
+ display: block;
+ width: auto;
+ min-width: 120px;
+ max-width: 220px;
+ margin: 18px auto 0 auto;
+ background-color: #8fc98a;
+ color: var(--text-color);
+ border: 1.5px solid #7bb87a;
+ border-radius: 6px;
+ font-size: 0.98rem;
+ font-family: inherit;
+ font-weight: 500;
+ padding: 7px 18px;
+ box-shadow: none;
+ text-align: center;
+ transition: background 0.2s, color 0.2s, border 0.2s;
+}
+.view-notes-btn i {
+ margin-right: 7px;
+}
+.view-notes-btn:hover, .view-notes-btn:focus {
+ background-color: #7bb87a;
+ color: var(--text-color);
+ border-color: #6fa96a;
+ outline: none;
+}
+
+.notes-link {
+ display: inline-flex;
+ align-items: center !important;
+ color: var(--primary-color) !important;
+ text-decoration: none !important;
+ font-weight: 500 !important;
+ padding: 5px 10px !important;
+ background-color: var(--light-gray) !important;
+ border-radius: var(--border-radius) !important;
+ transition: var(--transition) !important;
+ border: none !important;
+ white-space: nowrap !important;
+ font-size: 1rem !important;
+}
+.notes-link i {
+ margin-right: 5px !important;
+ font-size: 1rem !important;
+}
+.notes-link:hover, .notes-link:focus {
+ text-decoration: none !important;
+ background-color: var(--medium-gray) !important;
+ color: var(--primary-dark) !important;
+ outline: none;
+}
+
+/* ADD: Specific overrides for grid and list view */
+.grid-view .document-links-row,
+.list-view .document-links-row {
+ flex-direction: row; /* Ensure horizontal layout */
+ flex-wrap: wrap; /* Allow wrapping if needed in these views */
+ align-items: center; /* Vertically align items if they wrap */
+ justify-content: flex-start; /* Align items to the start */
+ margin-top: 10px; /* Adjust top margin if needed */
+ padding: 10px 15px; /* Ensure padding is consistent */
+ background-color: rgba(0, 0, 0, 0.03); /* Ensure background */
+ border-top: 1px solid var(--border-color); /* Ensure border */
+}
+
+/* Force horizontal layout for links in grid/list views */
+.grid-view .document-links-inner-container,
+.list-view .document-links-inner-container {
+ flex-direction: row !important;
+ align-items: center !important;
+ justify-content: flex-start !important;
+ gap: 10px !important;
+ height: auto !important;
+ flex-wrap: wrap !important;
+}
+
+@media (max-width: 768px) {
+ .table-view .document-links-row .notes-link {
+ margin-right: 5px !important;
+ }
+}
+
+@media (max-width: 768px) {
+ .document-links-row .notes-link,
+ .document-links-row .invoice-link,
+ .document-links-row .manual-link,
+ .document-links-row .product-link {
+ margin-right: 5px !important;
+ margin-left: 0 !important;
+ }
+}
+
+@media (max-width: 768px) {
+ .notes-link {
+ width: 100% !important;
+ justify-content: center !important;
+ }
+}
+
+@media (max-width: 768px) {
+ .document-links-row {
+ display: flex !important;
+ flex-direction: column !important;
+ align-items: center !important;
+ gap: 5px !important;
+ }
+ .invoice-link, .manual-link, .product-link, .notes-link {
+ width: auto !important;
+ justify-content: center !important;
+ }
}
\ No newline at end of file