Skip to content

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

Vendor, Date Format, Added security

sassanixe045aae20869
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2045586..fe9c488 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,115 @@
# Changelog
+## [0.9.9.4] - 2025-05-04
+
+### Fixed
+- **Theme Persistence & Consistency:**
+ - Refactored dark mode logic to use only a single `localStorage` key (`darkMode`) as the source of truth for theme preference across all pages.
+ - Removed all legacy and user-prefixed theme keys (e.g., `user_darkMode`, `admin_darkMode`, `${prefix}darkMode`).
+ - Ensured all theme toggles and settings update only the `darkMode` key, and all pages read only this key for theme initialization.
+ - Verified that `theme-loader.js` is included early in every HTML file to prevent flashes of incorrect theme.
+ - Cleaned up redundant or conflicting theme logic in all frontend scripts and HTML files.
+ - Theme preference now persists reliably across logins, logouts, and browser sessions (except in incognito/private mode, where localStorage is temporary by design).
+ _Files: `frontend/script.js`, `frontend/settings-new.js`, `frontend/status.js`, `frontend/register.html`, `frontend/reset-password.html`, `frontend/reset-password-request.html`, `frontend/theme-loader.js`, all main HTML files._
+
+### Added
+- **Admin/User Tag Separation:**
+ - Implemented distinct tags for Admins and regular Users.
+ - Tags created by an Admin are only visible to other Admins.
+ - Tags created by a User are only visible to other Users.
+ - Added `is_admin_tag` boolean column to the `tags` table via migration (`backend/migrations/009_add_admin_flag_to_tags.sql`).
+ - Backend API endpoints (`/api/tags`, `/api/warranties`, `/api/warranties/<id>/tags`) updated to filter tags based on the logged-in user's role (`is_admin`).
+ - Tag creation (`POST /api/tags`) now automatically sets the `is_admin_tag` flag based on the creator's role.
+ - Tag update (`PUT /api/tags/<id>`) and deletion (`DELETE /api/tags/<id>`) endpoints now prevent users/admins from modifying tags belonging to the other role.
+ _Files: `backend/app.py`, `backend/migrations/009_add_admin_flag_to_tags.sql`_
+
+ - **Version Check:**
+
+ - Added a version checker to the About page (`frontend/about.html`) that compares the current version with the latest GitHub release and displays the update status.
+ _Files: `frontend/about.html`, `frontend/version-checker.js`_
+
+- **Mobile Home Screen Icon Support:**
+ - Added support for mobile devices to display the app icon when added to the home screen.
+ - Included `<link rel="apple-touch-icon" sizes="180x180">` for iOS devices, referencing a new 512x512 PNG icon.
+ - Added a web app manifest (`manifest.json`) referencing the 512x512 icon for Android/Chrome home screen support.
+ - Updated all main HTML files to include these tags for consistent experience across devices.
+ _Files: `frontend/index.html`, `frontend/login.html`, `frontend/register.html`, `frontend/about.html`, `frontend/reset-password.html`, `frontend/reset-password-request.html`, `frontend/status.html`, `frontend/settings-new.html`, `frontend/manifest.json`, `frontend/img/favicon-512x512.png`_
+
+- **Optional Vendor Field for Warranties:**
+ - Users can now specify the vendor (e.g., Amazon, Best Buy) where a product was purchased, as an optional informational field for each warranty.
+ - The field is available when adding a new warranty and when editing an existing warranty.
+ - The vendor is displayed on warranty cards and in the summary tab of the add warranty wizard.
+ - The vendor field is now searchable alongside product name, notes, and tags.
+ - Backend API and database updated to support this field, including a migration to add the column to the warranties table.
+ - Editing a warranty now correctly updates the vendor field.
+ _Files: `backend/app.py`, `backend/migrations/017_add_vendor_to_warranties.sql`, `frontend/index.html`, `frontend/script.js`_
+
+- **Serial Number Search:**
+ - Enhanced search functionality to include serial numbers.
+ - Updated search input placeholder text to reflect serial number search capability.
+ _Files: `frontend/script.js`, `frontend/index.html`_
+
+- **CSV Import Vendor Field:**
+ - Added support for importing the `Vendor` field via CSV file upload.
+ - The CSV header should be `Vendor`.
+ _Files: `backend/app.py`, `frontend/script.js`_
+
+- **Date Format Customization:**
+ - Users can now choose their preferred date display format in Settings > Preferences.
+ - Available formats include:
+ - Month/Day/Year (e.g., 12/31/2024)
+ - Day/Month/Year (e.g., 31/12/2024)
+ - Year-Month-Day (e.g., 2024-12-31)
+ - Mon Day, Year (e.g., Dec 31, 2024)
+ - Day Mon Year (e.g., 31 Dec 2024)
+ - Year Mon Day (e.g., 2024 Dec 31)
+ - The selected format is applied to purchase and expiration dates on warranty cards.
+ - The setting persists across sessions and is synchronized between open tabs.
+ _Files: `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/script.js`_
+
+- **IPv6 Support:** Added `listen [::]:80;` directive to the Nginx configuration (`nginx.conf`) to enable listening on IPv6 interfaces alongside IPv4.
+ _Files: `nginx.conf`_
+
+- **Cloudflare Compatibility:** Added `<script data-cfasync="false" src="/javascript.js">` to the `<head>` of the status page (`frontend/status.html`) to ensure proper loading when behind Cloudflare.
+ _Files: `frontend/status.html`_
+
+ ### Changed
+ - **Migration System Overhaul:** Refactored the database migration system for improved reliability and consistency.
+ - **House cleaning**: Removed redundant files such as migrations, .env, and uploads folder.
+ - **Warranty Listing:** Admins now only see their own warranties on the main warranty list (`/api/warranties`).
+ - **Warranty Visibility:** Fixed issue where admins could see all users' warranties. Now both admins and regular users only see their own warranties on all pages.
+ _Files: `backend/app.py`_
+
+**Bug Fixes:**
+
+* **Date Handling:** Fixed issues causing warranty purchase and expiration dates to display incorrectly (off by one day) due to timezone differences:
+ * **Backend:** Corrected expiration date calculation in `backend/app.py` by removing the inaccurate `timedelta` fallback logic and ensuring the `python-dateutil` library (using `relativedelta`) is consistently used for accurate year addition.
+ * **Backend:** Added `python-dateutil` to `backend/requirements.txt` dependencies.
+ * **Frontend:** Updated date parsing in `frontend/script.js` (`processWarrantyData`) to use `Date.UTC()` when creating `Date` objects from `YYYY-MM-DD` strings, preventing local timezone interpretation.
+ * **Frontend:** Simplified and corrected date formatting in `frontend/script.js` (`formatDate`) to always use UTC date components (`getUTCFullYear`, etc.) for display, bypassing potential `toLocaleDateString` timezone issues.
+ * **Frontend:** Fixed purchase date display in the "Add Warranty" summary tab (`updateSummary` in `frontend/script.js`) by applying the same UTC-based parsing and formatting used elsewhere, resolving the off-by-one-day error during summary view.
+* **Fractional Warranty Years & Date Accuracy:** Corrected the backend expiration date calculation (`backend/app.py`) to accurately handle fractional warranty years (e.g., 1.5 years) and prevent off-by-one-day errors.
+ * The initial fix for fractional years used an approximation (`timedelta`) which sometimes resulted in dates being a day early.
+ * The calculation now uses `dateutil.relativedelta` after decomposing the fractional years into integer years, months, and days, ensuring correct handling of leap years and month lengths.
+* **UI:** Fixed toasts overlapping header menu due to z-index conflict (`style.css`).
+* **API:** Fixed bug preventing updates to user preferences if only the timezone was changed (`app.py`).
+* **Settings:** Resolved issue where opening the settings page in multiple tabs could cause both tabs to refresh continuously and potentially log the user out. This involved:
+ * Preventing `settings-new.js` from unnecessarily updating `user_info` in `localStorage` on load.
+ * Changing the `storage` event listener in `include-auth-new.js` to update the UI directly instead of reloading the page when auth data changes.
+ * Removing redundant checks (`setInterval`) and `storage` listener from `fix-auth-buttons.js` to prevent conflicts.
+
+**New Features & Enhancements:**
+
+* **API:** Added `/api/timezones` endpoint to provide a structured list of timezones grouped by region (`app.py`).
+
+### Fixed
+- **Tag Visibility:** Fixed an issue where tag visibility was incorrectly reversed between Admins and Users (Users saw Admin tags and vice-versa). Adjusted backend logic to correctly display tags based on role.
+ _Files: `backend/app.py`_
+- Fixed currency symbol not persisting after browser restart/re-login:
+ - Prevented main warranty list from rendering before user authentication and preferences are fully loaded.
+ - Ensured preferences (currency, date format, etc.) are fetched from API and saved to localStorage immediately after login.
+ - Corrected inconsistent user type prefix (`user_` vs `admin_`) determination during initial page load.
+
## [0.9.9.3] - 2025-04-27
### Added
diff --git a/Docker/.env.example b/Docker/.env.example
deleted file mode 100644
index 9148b77..0000000
--- a/Docker/.env.example
+++ /dev/null
@@ -1,9 +0,0 @@
-# Database configuration
-DB_PASSWORD=warranty_password
-DB_ADMIN_PASSWORD=change_this_password_in_production
-
-# Email configuration
-SMTP_HOST=localhost
-SMTP_PORT=1025
-SMTP_PASSWORD=your_smtp_password
\ No newline at end of file
diff --git a/README.md b/README.md
index 3b61466..d4885d2 100644
--- a/README.md
+++ b/README.md
@@ -40,6 +40,7 @@ Warracker is an open-source warranty tracker application designed to help you ef
- **Data Export and Import:** Export warranty data to CSV, or import warranties from CSV files.
- **Email Notifications:** Receive timely email reminders about upcoming expirations — configurable as daily, weekly, or monthly.
- **Customizable Currency Symbols:** Display prices using your preferred currency symbol ($, €, £, ¥, ₹, or a custom symbol).
+- **Customizable Dates:** Display dates based on your own region.
- **Tagging:** Organize warranties with flexible, multi-tag support.
- **Password Reset:** Easily recover accounts through a secure, token-based password reset flow.
@@ -189,6 +190,7 @@ To get the docker compose file please go [here](https://github.com/sassanix/Warr
| **PurchasePrice** | Number (`199.99`, `50`) | ❌ No (Optional) | Cannot be negative if provided. |
| **SerialNumber** | Text (`SN123`, `SN123,SN456`) | ❌ No (Optional) | For multiple values, separate with commas. |
| **ProductURL** | Text (URL format) | ❌ No (Optional) | Full URL to product page (optional field). https://producturl.com |
+| **Vendor** | Text | ❌ No (Optional) | Name of the vendor or seller where the product was purchased. |
| **Tags** | Text (`tag1,tag2`) | ❌ No (Optional) | Use comma-separated values for multiple tags. |
diff --git a/backend/app.py b/backend/app.py
index 093bfc5..3133962 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -24,10 +24,7 @@ import threading
import json
import csv # Added for CSV import
import io # Added for CSV import
-try: # Added for CSV import date calculation
- from dateutil.relativedelta import relativedelta
-except ImportError:
- relativedelta = None
+from dateutil.relativedelta import relativedelta
app = Flask(__name__)
CORS(app, supports_credentials=True) # Enable CORS with credentials
@@ -768,15 +765,13 @@ def get_warranties():
conn = None
try:
user_id = request.user['id']
- is_admin = request.user['is_admin']
-
+ # is_admin = request.user.get('is_admin', False) # Removed admin check
+
conn = get_db_connection()
with conn.cursor() as cur:
- # If admin, can see all warranties, otherwise only user's warranties
- if is_admin:
- cur.execute('SELECT * FROM warranties ORDER BY CASE WHEN is_lifetime THEN 1 ELSE 0 END, expiration_date NULLS LAST, product_name')
- else:
- cur.execute('SELECT * FROM warranties WHERE user_id = %s ORDER BY CASE WHEN is_lifetime THEN 1 ELSE 0 END, expiration_date NULLS LAST, product_name', (user_id,))
+ # Always fetch warranties belonging to the logged-in user
+ # Removed the if is_admin: block
+ cur.execute('SELECT * FROM warranties WHERE user_id = %s ORDER BY CASE WHEN is_lifetime THEN 1 ELSE 0 END, expiration_date NULLS LAST, product_name', (user_id,))
warranties = cur.fetchall()
columns = [desc[0] for desc in cur.description]
@@ -798,12 +793,12 @@ def get_warranties():
serial_numbers = [row[0] for row in cur.fetchall()]
warranty_dict['serial_numbers'] = serial_numbers
- # Get tags for this warranty
+ # Get tags for this warranty (show all associated tags the user can see via warranty access)
cur.execute('''
SELECT t.id, t.name, t.color
FROM tags t
JOIN warranty_tags wt ON t.id = wt.tag_id
- WHERE wt.warranty_id = %s
+ WHERE wt.warranty_id = %s -- Removed user_id/is_admin filter here
ORDER BY t.name
''', (warranty_id,))
tags = [{'id': t[0], 'name': t[1], 'color': t[2]} for t in cur.fetchall()]
@@ -853,6 +848,7 @@ def add_warranty():
product_url = request.form.get('product_url', '')
user_id = request.user['id']
notes = request.form.get('notes', '')
+ vendor = request.form.get('vendor', None)
# Get tag IDs if provided
tag_ids = []
@@ -881,11 +877,23 @@ def add_warranty():
# Calculate expiration date only if not lifetime
if not is_lifetime and warranty_years is not None:
+ # Decompose fractional years into years, months, days
try:
- from dateutil.relativedelta import relativedelta
- expiration_date = purchase_date + relativedelta(years=warranty_years)
- except ImportError:
- expiration_date = purchase_date + timedelta(days=warranty_years * 365) # Approximate
+ years_float = float(warranty_years)
+ total_months_float = years_float * 12
+ years_int = int(years_float)
+ remaining_months_float = total_months_float - (years_int * 12)
+ months_int = int(remaining_months_float)
+ # Approximate remaining days based on fraction of a month
+ remaining_days_float = (remaining_months_float - months_int) * (365.2425 / 12)
+ days_int = int(round(remaining_days_float)) # Round to nearest day
+
+ expiration_date = purchase_date + relativedelta(years=years_int, months=months_int, days=days_int)
+ logger.info(f"Calculated relativedelta for {warranty_years} years: years={years_int}, months={months_int}, days={days_int}")
+ except Exception as calc_err:
+ logger.error(f"Error calculating expiration date from warranty_years={warranty_years}: {calc_err}")
+ # Fallback or re-raise depending on desired behavior. Let's return error for now.
+ return jsonify({"error": "Failed to calculate expiration date from warranty years"}), 500
# Handle invoice file upload
db_invoice_path = None
@@ -926,13 +934,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, notes
+ invoice_path, manual_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor
)
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
+ VALUES (%s, %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, notes
+ db_invoice_path, db_manual_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor
))
warranty_id = cur.fetchone()[0]
@@ -1039,7 +1047,6 @@ def update_warranty(warranty_id):
try:
user_id = request.user['id']
is_admin = request.user['is_admin']
-
conn = get_db_connection()
with conn.cursor() as cur:
# Check if warranty exists and belongs to the user
@@ -1047,37 +1054,34 @@ def update_warranty(warranty_id):
cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
else:
cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s', (warranty_id, user_id))
-
warranty = cur.fetchone()
-
if not warranty:
return jsonify({"error": "Warranty not found or you don't have permission to update it"}), 404
-
+
+ # --- PATCH: Support JSON-only notes update ---
+ if request.is_json and 'notes' in request.json and len(request.json) == 1:
+ notes = request.json.get('notes', None)
+ cur.execute("UPDATE warranties SET notes = %s, updated_at = NOW() WHERE id = %s", (notes, warranty_id))
+ conn.commit()
+ return jsonify({"message": "Notes updated successfully"}), 200
+
+ # --- Otherwise, continue with the original (form-based) update logic ---
# Validate input data similar to the add_warranty route
if not request.form.get('product_name'):
return jsonify({"error": "Product name is required"}), 400
-
if not request.form.get('purchase_date'):
return jsonify({"error": "Purchase date is required"}), 400
-
- # --- Log received data ---
logger.info(f"Received update request for warranty {warranty_id}")
logger.info(f"Form data received: is_lifetime={request.form.get('is_lifetime')}, warranty_years={request.form.get('warranty_years')}")
-
- # --- Added: Get is_lifetime ---
is_lifetime = request.form.get('is_lifetime', 'false').lower() == 'true'
logger.info(f"Parsed is_lifetime as: {is_lifetime}")
-
purchase_date_str = request.form['purchase_date']
try:
purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d').date() # Use .date()
except ValueError:
return jsonify({"error": "Invalid date format for purchase date. Use YYYY-MM-DD"}), 400
-
warranty_years = None
expiration_date = None
-
- # --- Modified: Conditional validation and calculation ---
if not is_lifetime:
warranty_years_str = request.form.get('warranty_years')
if not warranty_years_str:
@@ -1086,26 +1090,27 @@ def update_warranty(warranty_id):
warranty_years = float(warranty_years_str)
if warranty_years < 0.1 or warranty_years > 100:
return jsonify({"error": "Warranty years must be between 0.1 and 100 for non-lifetime warranties"}), 400
-
- # Calculate expiration date precisely if possible, otherwise approximate
try:
- from dateutil.relativedelta import relativedelta
- expiration_date = purchase_date + relativedelta(years=warranty_years)
- except ImportError:
- expiration_date = purchase_date + timedelta(days=warranty_years * 365)
-
+ years_float = float(warranty_years)
+ total_months_float = years_float * 12
+ years_int = int(years_float)
+ remaining_months_float = total_months_float - (years_int * 12)
+ months_int = int(remaining_months_float)
+ remaining_days_float = (remaining_months_float - months_int) * (365.2425 / 12)
+ days_int = int(round(remaining_days_float)) # Round to nearest day
+ expiration_date = purchase_date + relativedelta(years=years_int, months=months_int, days=days_int)
+ logger.info(f"Calculated relativedelta for {warranty_years} years: years={years_int}, months={months_int}, days={days_int}")
+ except Exception as calc_err:
+ logger.error(f"Error calculating expiration date from warranty_years={warranty_years}: {calc_err}")
+ return jsonify({"error": "Failed to calculate expiration date from warranty years"}), 500
except ValueError:
return jsonify({"error": "Warranty years must be a valid number"}), 400
- # else: warranty_years and expiration_date remain None for lifetime
-
- # Process the data
+ logger.info(f"Calculated values: warranty_years={warranty_years}, expiration_date={expiration_date}")
product_name = request.form['product_name']
- # 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
+ vendor = request.form.get('vendor', None)
tag_ids = []
if request.form.get('tag_ids'):
try:
@@ -1114,8 +1119,6 @@ def update_warranty(warranty_id):
return jsonify({"error": "tag_ids must be a JSON array"}), 400
except json.JSONDecodeError:
return jsonify({"error": "tag_ids must be a valid JSON array"}), 400
-
- # Handle purchase price (optional)
purchase_price = None
if request.form.get('purchase_price'):
try:
@@ -1124,19 +1127,14 @@ def update_warranty(warranty_id):
return jsonify({"error": "Purchase price cannot be negative"}), 400
except ValueError:
return jsonify({"error": "Purchase price must be a valid number"}), 400
-
- # Handle invoice file upload if new file is provided
db_invoice_path = None
if 'invoice' in request.files:
invoice = request.files['invoice']
if invoice.filename != '':
if not allowed_file(invoice.filename):
return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
-
- # First check if there's an existing invoice to delete
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):
@@ -1145,16 +1143,12 @@ def update_warranty(warranty_id):
logger.info(f"Deleted old invoice: {full_path}")
except Exception as e:
logger.error(f"Error deleting old invoice: {e}")
-
- # Save new invoice
filename = secure_filename(invoice.filename)
filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
invoice_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
-
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]
@@ -1167,19 +1161,14 @@ def update_warranty(warranty_id):
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:
manual = request.files['manual']
if manual.filename != '':
if not allowed_file(manual.filename):
return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
-
- # First check if there's an existing manual to delete
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):
@@ -1188,16 +1177,12 @@ def update_warranty(warranty_id):
logger.info(f"Deleted old manual: {full_path}")
except Exception as e:
logger.error(f"Error deleting old manual: {e}")
-
- # Save new manual
filename = secure_filename(manual.filename)
filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_manual_{filename}"
manual_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
-
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]
@@ -1210,10 +1195,6 @@ def update_warranty(warranty_id):
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 ---
update_params = {
'product_name': product_name,
'purchase_date': purchase_date,
@@ -1221,52 +1202,34 @@ def update_warranty(warranty_id):
'warranty_years': warranty_years, # Will be None if lifetime
'expiration_date': expiration_date, # Will be None if lifetime
'product_url': product_url,
- 'purchase_price': purchase_price
+ 'purchase_price': purchase_price,
+ 'vendor': vendor
}
-
- # Build dynamic SQL query based on which files have been uploaded or preserved
sql_fields = []
sql_values = []
-
for key, value in update_params.items():
sql_fields.append(f"{key} = %s")
sql_values.append(value)
- # 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
-
- # Add the warranty_id at the end
sql_values.append(warranty_id)
-
- # Execute the dynamic SQL update
update_sql = f"UPDATE warranties SET {', '.join(sql_fields)} WHERE id = %s"
cur.execute(update_sql, sql_values)
logger.info(f"Updated warranty with SQL: {update_sql}")
logger.info(f"Parameters: {sql_values}")
-
- # Update serial numbers
- # First, delete existing serial numbers for this warranty
cur.execute('DELETE FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))
-
- # Then insert the new serial numbers
if serial_numbers:
for serial_number in serial_numbers:
if serial_number.strip(): # Only insert non-empty serial numbers
@@ -1343,6 +1306,11 @@ def get_statistics():
where_clause = "WHERE w.user_id = %s"
params = [user_id]
active_where = "AND"
+ else:
+ # Admin should only see their own warranties
+ where_clause = "WHERE w.user_id = %s"
+ params = [user_id]
+ active_where = "AND"
with conn.cursor() as cur:
# Get total count
@@ -1582,8 +1550,20 @@ def delete_account():
# Delete user's reset tokens if any
cursor.execute("DELETE FROM password_reset_tokens WHERE user_id = %s", (user_id,))
+ # Delete user's sessions if any
+ cur.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
+ sessions_deleted = cur.rowcount
+ logger.info(f"Deleted {sessions_deleted} sessions belonging to user {user_id}")
+
+ # Delete user's tags
+ cur.execute('DELETE FROM tags WHERE user_id = %s', (user_id,))
+ tags_deleted = cur.rowcount
+ logger.info(f"Deleted {tags_deleted} tags belonging to user {user_id}")
+
# Delete user
cursor.execute("DELETE FROM users WHERE id = %s", (user_id,))
+ user_deleted = cur.rowcount
+ logger.info(f"Deleted user {user_id}, affected rows: {user_deleted}")
# Commit transaction
cursor.execute("COMMIT")
@@ -1641,56 +1621,74 @@ def get_preferences():
conn.commit()
logger.info(f"Created user_preferences table")
has_currency = has_currency_symbol_column(cursor)
+
+ cursor.execute("SELECT column_name FROM information_schema.columns WHERE table_name='user_preferences' AND column_name='date_format'")
+ has_date_format_col = cursor.fetchone() is not None
+
+ # Build select list dynamically
+ select_fields_list = ["email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
if has_currency:
- cursor.execute(
- """
- 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,)
- )
+ select_fields_list.append("currency_symbol")
+ if has_date_format_col:
+ select_fields_list.append("date_format") # Add date_format if column exists
+ select_fields = ", ".join(select_fields_list)
+
+ cursor.execute(
+ f"""
+ SELECT {select_fields}
+ FROM user_preferences
+ WHERE user_id = %s
+ """,
+ (user_id,)
+ )
preferences_data = cursor.fetchone()
+
if not preferences_data:
+ # Build insert list dynamically
+ insert_cols_list = ["user_id", "email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
+ insert_vals = [user_id, True, 'grid', 'light', 30, 'daily', '09:00', 'UTC']
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,)
- )
+ insert_cols_list.append("currency_symbol")
+ insert_vals.append('$')
+ if has_date_format_col:
+ insert_cols_list.append("date_format")
+ insert_vals.append('MDY') # Default date format
+
+ insert_cols = ", ".join(insert_cols_list)
+ insert_vals_placeholders = ", ".join(["%s"] * len(insert_cols_list))
+ return_fields = insert_cols # Return the same columns we inserted
+
+ cursor.execute(
+ f"""
+ INSERT INTO user_preferences ({insert_cols})
+ VALUES ({insert_vals_placeholders})
+ RETURNING {return_fields}
+ """,
+ tuple(insert_vals)
+ )
preferences_data = cursor.fetchone()
conn.commit()
- 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],
- '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 '$'
- }
+
+ # Map returned data to dictionary using the dynamically determined fields
+ returned_columns = [col.strip() for col in select_fields.split(',')]
+ if preferences_data:
+ pref_map = {col: i for i, col in enumerate(returned_columns)}
+ preferences = {
+ 'email_notifications': preferences_data[pref_map.get('email_notifications', 0)],
+ 'default_view': preferences_data[pref_map.get('default_view', 1)],
+ 'theme': preferences_data[pref_map.get('theme', 2)],
+ 'expiring_soon_days': preferences_data[pref_map.get('expiring_soon_days', 3)],
+ 'notification_frequency': preferences_data[pref_map.get('notification_frequency', 4)],
+ 'notification_time': preferences_data[pref_map.get('notification_time', 5)],
+ 'timezone': preferences_data[pref_map.get('timezone', 6)],
+ 'currency_symbol': preferences_data[pref_map['currency_symbol']] if 'currency_symbol' in pref_map else '$', # Handle currency optionality
+ 'date_format': preferences_data[pref_map['date_format']] if 'date_format' in pref_map else 'MDY' # Handle date_format optionality
+ }
+ else:
+ # Fallback if even insert failed or returned nothing
+ preferences = default_preferences.copy()
+ preferences['date_format'] = 'MDY' # Ensure date_format is in fallback
+
return jsonify(preferences), 200
except Exception as e:
conn.rollback()
@@ -1739,6 +1737,8 @@ def update_preferences():
notification_time = data.get('notification_time')
timezone = data.get('timezone')
currency_symbol = data.get('currency_symbol')
+ date_format = data.get('date_format')
+
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']:
@@ -1756,46 +1756,26 @@ def update_preferences():
return jsonify({'message': 'Invalid notification time format'}), 400
if timezone and not is_valid_timezone(timezone):
return jsonify({'message': 'Invalid timezone'}), 400
+
+ # Add validation for date_format
+ valid_date_formats = ['MDY', 'DMY', 'YMD', 'MDY_WORDS', 'DMY_WORDS', 'YMD_WORDS']
+ if date_format and date_format not in valid_date_formats:
+ return jsonify({'message': 'Invalid date format'}), 400
+
conn = get_db_connection()
cursor = conn.cursor()
try:
- cursor.execute("""
- SELECT EXISTS (
- SELECT FROM information_schema.tables
- WHERE table_name = 'user_preferences'
- )
- """)
- table_exists = cursor.fetchone()[0]
- if not table_exists:
- cursor.execute("""
- CREATE TABLE user_preferences (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- email_notifications BOOLEAN NOT NULL DEFAULT TRUE,
- default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
- theme VARCHAR(10) NOT NULL DEFAULT 'light',
- expiring_soon_days INTEGER NOT NULL DEFAULT 30,
- 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)
- )
- """)
- cursor.execute("""
- CREATE INDEX idx_user_preferences_user_id ON user_preferences(user_id)
- """)
- preferences_exist = False
- conn.commit()
- logger.info(f"Created user_preferences table")
+ # Check if date_format column exists first to handle dynamic schema changes
+ cursor.execute("SELECT column_name FROM information_schema.columns WHERE table_name='user_preferences' AND column_name='date_format'")
+ has_date_format_col = 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_fields = []
update_values = []
@@ -1823,10 +1803,20 @@ def update_preferences():
if has_currency and currency_symbol is not None:
update_fields.append("currency_symbol = %s")
update_values.append(currency_symbol)
+ # Add date_format to update only if the column exists
+ if has_date_format_col and date_format:
+ update_fields.append("date_format = %s")
+ update_values.append(date_format)
+
if update_fields:
- return_fields = "email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone"
+ # Build the returning fields string dynamically based on existing columns
+ return_fields_list = ["email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
if has_currency:
- return_fields += ", currency_symbol"
+ return_fields_list.append("currency_symbol")
+ if has_date_format_col:
+ return_fields_list.append("date_format")
+ return_fields = ", ".join(return_fields_list)
+
update_query = f"""
UPDATE user_preferences
SET {', '.join(update_fields)}
@@ -1836,9 +1826,14 @@ def update_preferences():
cursor.execute(update_query, update_values + [user_id])
preferences_data = cursor.fetchone()
else:
- select_fields = "email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone"
+ # If no fields to update, select existing data
+ select_fields_list = ["email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
if has_currency:
- select_fields += ", currency_symbol"
+ select_fields_list.append("currency_symbol")
+ if has_date_format_col:
+ select_fields_list.append("date_format")
+ select_fields = ", ".join(select_fields_list)
+
cursor.execute(
f"""
SELECT {select_fields}
@@ -1848,78 +1843,56 @@ def update_preferences():
(user_id,)
)
preferences_data = cursor.fetchone()
- else:
+ else: # Insert new record
+ # Build insert dynamically
+ insert_cols_list = ["user_id", "email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
+ insert_vals = [
+ user_id,
+ email_notifications if email_notifications is not None else True,
+ default_view or 'grid',
+ theme or 'light',
+ expiring_soon_days if expiring_soon_days is not None else 30,
+ notification_frequency or 'daily',
+ notification_time or '09:00',
+ timezone or 'UTC'
+ ]
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, %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,
- email_notifications if email_notifications is not None else True,
- default_view or 'grid',
- theme or 'light',
- expiring_soon_days if expiring_soon_days is not None else 30,
- notification_frequency or 'daily',
- notification_time or '09:00',
- timezone or 'UTC',
- currency_symbol or '$'
- )
- )
- else:
- cursor.execute(
- """
- INSERT INTO user_preferences (
- user_id,
- email_notifications,
- default_view,
- theme,
- expiring_soon_days,
- notification_frequency,
- notification_time,
- timezone
- )
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
- RETURNING email_notifications, default_view, theme, expiring_soon_days, notification_frequency, notification_time, timezone
- """,
- (
- user_id,
- email_notifications if email_notifications is not None else True,
- default_view or 'grid',
- theme or 'light',
- expiring_soon_days if expiring_soon_days is not None else 30,
- notification_frequency or 'daily',
- notification_time or '09:00',
- timezone or 'UTC'
- )
- )
+ insert_cols_list.append("currency_symbol")
+ insert_vals.append(currency_symbol or '$')
+ if has_date_format_col:
+ insert_cols_list.append("date_format")
+ insert_vals.append(date_format or 'MDY')
+
+ insert_cols = ", ".join(insert_cols_list)
+ insert_vals_placeholders = ", ".join(["%s"] * len(insert_cols_list))
+ return_fields = insert_cols # Return the same columns we inserted
+
+ cursor.execute(
+ f"""
+ INSERT INTO user_preferences ({insert_cols})
+ VALUES ({insert_vals_placeholders})
+ RETURNING {return_fields}
+ """,
+ tuple(insert_vals)
+ )
preferences_data = cursor.fetchone()
+
+ # Map returned data to dictionary using the dynamically determined fields
+ returned_columns = [col.strip() for col in return_fields.split(',')]
+ pref_map = {col: i for i, col in enumerate(returned_columns)}
+
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],
- '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 '$')
- )
+ 'email_notifications': preferences_data[pref_map.get('email_notifications', 0)], # Default index 0 might be risky, but needed if column is missing
+ 'default_view': preferences_data[pref_map.get('default_view', 1)],
+ 'theme': preferences_data[pref_map.get('theme', 2)],
+ 'expiring_soon_days': preferences_data[pref_map.get('expiring_soon_days', 3)],
+ 'notification_frequency': preferences_data[pref_map.get('notification_frequency', 4)],
+ 'notification_time': preferences_data[pref_map.get('notification_time', 5)],
+ 'timezone': preferences_data[pref_map.get('timezone', 6)],
+ 'currency_symbol': preferences_data[pref_map['currency_symbol']] if 'currency_symbol' in pref_map else '$', # Handle currency optionality
+ 'date_format': preferences_data[pref_map['date_format']] if 'date_format' in pref_map else 'MDY' # Handle date_format optionality
}
+
conn.commit()
return jsonify(preferences), 200
except Exception as e:
@@ -1933,7 +1906,8 @@ def update_preferences():
'notification_frequency': notification_frequency or 'daily',
'notification_time': notification_time or '09:00',
'timezone': timezone or 'UTC',
- 'currency_symbol': currency_symbol or '$'
+ 'currency_symbol': currency_symbol or '$',
+ 'date_format': date_format or 'MDY' # Add to fallback
}
return jsonify(fallback_preferences), 200
finally:
@@ -2083,7 +2057,12 @@ def delete_user(user_id):
cur.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
sessions_deleted = cur.rowcount
logger.info(f"Deleted {sessions_deleted} sessions belonging to user {user_id}")
-
+
+ # Delete user's tags
+ cur.execute('DELETE FROM tags WHERE user_id = %s', (user_id,))
+ tags_deleted = cur.rowcount
+ logger.info(f"Deleted {tags_deleted} tags belonging to user {user_id}")
+
# Delete user
cur.execute('DELETE FROM users WHERE id = %s', (user_id,))
user_deleted = cur.rowcount
@@ -2334,6 +2313,7 @@ def get_expiring_warranties():
with conn.cursor() as cur:
cur.execute("""
SELECT
+ u.id, -- Select user_id
u.email,
u.first_name,
w.product_name,
@@ -2355,9 +2335,10 @@ def get_expiring_warranties():
expiring_warranties = []
for row in cur.fetchall():
- email, first_name, product_name, expiration_date, expiring_soon_days = row
+ user_id, email, first_name, product_name, expiration_date, expiring_soon_days = row # Include user_id
expiration_date_str = expiration_date.strftime('%Y-%m-%d')
expiring_warranties.append({
+ 'user_id': user_id, # Add user_id to the dict
'email': email,
'first_name': first_name or 'User', # Default if first_name is NULL
'product_name': product_name,
@@ -2621,7 +2602,7 @@ def send_expiration_notifications(manual_trigger=False):
return
# Check if we should send notifications based on time and timezone
- users_for_current_time = []
+ users_to_notify_now = set() # Changed variable name and type to set
for user in eligible_users:
user_id, email, first_name, notification_time, timezone, frequency = user
@@ -2674,23 +2655,23 @@ def send_expiration_notifications(manual_trigger=False):
# Only send if it's been more than 10 minutes since the last notification
# (longer than the 5-minute scheduler interval)
if now_timestamp - last_sent > 600:
- users_for_current_time.append(user_id)
+ users_to_notify_now.add(user_id) # Add user_id to the set
logger.info(f"User {email} eligible for notification at their local time {notification_time} ({timezone})")
else:
logger.info(f"Skipping notification for {email} - already sent within the last 10 minutes (last sent: {datetime.fromtimestamp(last_sent).strftime('%Y-%m-%d %H:%M:%S')})")
else:
- users_for_current_time.append(user_id)
+ users_to_notify_now.add(user_id) # Add user_id to the set
logger.info(f"User {email} eligible for notification at their local time {notification_time} ({timezone})")
except Exception as e:
logger.error(f"Error processing timezone for user {email}: {e}")
continue
- if not users_for_current_time:
+ if not users_to_notify_now: # Check the set now
logger.info("No users are scheduled for notifications at their local time")
return
- logger.info(f"Found {len(users_for_current_time)} users eligible for notifications now")
+ logger.info(f"Found {len(users_to_notify_now)} users eligible for notifications now")
except Exception as e:
logger.error(f"Error determining notification eligibility: {e}")
return
@@ -2706,9 +2687,11 @@ def send_expiration_notifications(manual_trigger=False):
# Group warranties by user
users_warranties = {}
for warranty in expiring_warranties:
+ user_id = warranty['user_id'] # Get user_id
email = warranty['email']
if email not in users_warranties:
users_warranties[email] = {
+ 'user_id': user_id, # Store user_id
'first_name': warranty['first_name'],
'warranties': []
}
@@ -2744,6 +2727,12 @@ def send_expiration_notifications(manual_trigger=False):
emails_sent = 0
for email, user_data in users_warranties.items():
+ # ---> ADD CHECK HERE <-----
+ user_id_to_check = user_data.get('user_id')
+ if not manual_trigger and user_id_to_check not in users_to_notify_now:
+ logger.debug(f"Skipping email for {email} (user_id: {user_id_to_check}) - not in current notification window.")
+ continue # Skip sending if not in the set for scheduled notifications
+
# For manual triggers, check if we've sent recently
if manual_trigger and email in last_notification_sent:
last_sent = last_notification_sent[email]
@@ -2982,12 +2971,16 @@ def debug_file_check():
@app.route('/api/tags', methods=['GET'])
@token_required
def get_tags():
- """Get all tags"""
+ """Get tags based on user role."""
conn = None
try:
+ user_id = request.user['id']
+
conn = get_db_connection()
with conn.cursor() as cur:
- cur.execute('SELECT id, name, color, created_at FROM tags ORDER BY name')
+ # Fetch tags created by the currently logged-in user
+ cur.execute('SELECT id, name, color, created_at FROM tags WHERE user_id = %s ORDER BY name', (user_id,))
+
tags = cur.fetchall()
result = []
@@ -2997,6 +2990,7 @@ def get_tags():
'name': tag[1],
'color': tag[2],
'created_at': tag[3].isoformat() if tag[3] else None
+ # Removed is_admin_tag comment
})
return jsonify(result), 200
@@ -3010,9 +3004,10 @@ def get_tags():
@app.route('/api/tags', methods=['POST'])
@token_required
def create_tag():
- """Create a new tag"""
+ """Create a new tag owned by the requesting user."""
conn = None
try:
+ user_id = request.user['id'] # Get user ID
data = request.json
if not data or 'name' not in data:
@@ -3030,17 +3025,18 @@ def create_tag():
conn = get_db_connection()
with conn.cursor() as cur:
- # Check if tag with this name already exists
- cur.execute('SELECT id FROM tags WHERE name = %s', (name,))
+ # Check if tag with this name already exists FOR THIS USER
+ cur.execute('SELECT id FROM tags WHERE name = %s AND user_id = %s', (name, user_id)) # Added user_id check
existing_tag = cur.fetchone()
if existing_tag:
- return jsonify({"error": "A tag with this name already exists"}), 409
+ # Differentiate error message slightly
+ return jsonify({"error": f"A tag with this name already exists for your account"}), 409 # Updated error message
- # Create new tag
+ # Create new tag, setting user_id
cur.execute(
- 'INSERT INTO tags (name, color) VALUES (%s, %s) RETURNING id',
- (name, color)
+ 'INSERT INTO tags (name, color, user_id) VALUES (%s, %s, %s) RETURNING id', # Added user_id
+ (name, color, user_id) # Pass user_id here
)
tag_id = cur.fetchone()[0]
conn.commit()
@@ -3063,7 +3059,8 @@ def create_tag():
@app.route('/api/tags/<int:tag_id>', methods=['PUT'])
@token_required
def update_tag(tag_id):
- """Update an existing tag"""
+ """Update an existing tag, ensuring user can only update their own type of tag."""
+ user_id = request.user['id']
data = request.get_json()
new_name = data.get('name')
new_color = data.get('color')
@@ -3079,17 +3076,24 @@ def update_tag(tag_id):
try:
conn = get_db_connection()
with conn.cursor() as cur:
- # Check if tag exists
- cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
+ # Check if tag exists AND belongs to the user
+ cur.execute('SELECT id, user_id FROM tags WHERE id = %s', (tag_id,)) # Check user_id
tag = cur.fetchone()
if not tag:
return jsonify({"error": "Tag not found"}), 404
- # Check if new name conflicts with another tag
- cur.execute('SELECT id FROM tags WHERE name = %s AND id != %s', (new_name, tag_id))
+ tag_user_id = tag[1]
+ if tag_user_id != user_id:
+ # Prevent user from updating tag they don't own
+ return jsonify({"error": "Permission denied to update this tag"}), 403
+
+ # Check if new name conflicts with another tag FOR THIS USER
+ cur.execute('SELECT id FROM tags WHERE name = %s AND id != %s AND user_id = %s',
+ (new_name, tag_id, user_id)) # Added user_id check
existing = cur.fetchone()
if existing:
- return jsonify({"error": "A tag with this name already exists"}), 409
+ # tag_type = "admin" if is_admin_updater else "user" # Removed
+ return jsonify({"error": f"Another tag with this name already exists for your account"}), 409 # Updated error message
# Update the tag
cur.execute('UPDATE tags SET name = %s, color = %s, updated_at = NOW() WHERE id = %s RETURNING id, name, color',
@@ -3110,21 +3114,25 @@ def update_tag(tag_id):
release_db_connection(conn)
@app.route('/api/tags/<int:tag_id>', methods=['DELETE'])
-@token_required # Or @admin_required if only admins should delete tags
+@token_required
def delete_tag_endpoint(tag_id):
- """Delete a tag and its associations"""
+ """Delete a tag owned by the requesting user and its associations."""
+ user_id = request.user['id'] # Get user ID
conn = None
try:
- # Check if the user has permission (you might want admin_required here)
- # For now, just check if logged in using token_required
-
conn = get_db_connection()
with conn.cursor() as cur:
- # Check if tag exists
- cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
+ # Check if tag exists AND belongs to the user
+ cur.execute('SELECT id, user_id FROM tags WHERE id = %s', (tag_id,)) # Check user_id
tag = cur.fetchone()
if not tag:
return jsonify({"error": "Tag not found"}), 404
+
+ tag_user_id = tag[1]
+ # Only allow deletion if the user owns the tag
+ if tag_user_id != user_id:
+ # Prevent users from deleting tags they don't own
+ return jsonify({"error": "Permission denied to delete this tag"}), 403
# Delete associations from warranty_tags first
cur.execute('DELETE FROM warranty_tags WHERE tag_id = %s', (tag_id,))
@@ -3148,30 +3156,36 @@ def delete_tag_endpoint(tag_id):
@app.route('/api/warranties/<int:warranty_id>/tags', methods=['GET'])
@token_required
def get_warranty_tags(warranty_id):
- """Get all tags associated with a specific warranty"""
+ # """Get tags associated with a specific warranty, filtered by user role.""" # Docstring update needed
+ """Get tags associated with a specific warranty."""
conn = None
try:
user_id = request.user['id']
- is_admin = request.user['is_admin']
+ # is_admin = request.user.get('is_admin', False) # Removed
conn = get_db_connection()
with conn.cursor() as cur:
# First check if the warranty exists and user has access to it
- if is_admin:
- cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
- else:
- cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s',
- (warranty_id, user_id))
+ # Simplified check: just check if warranty exists and belongs to the user
+ cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s',
+ (warranty_id, user_id))
if cur.fetchone() is None:
- return jsonify({"error": "Warranty not found or you don't have permission to access it"}), 404
+ # Add admin check here if admins should be able to see tags for any warranty
+ is_admin = request.user.get('is_admin', False)
+ if is_admin:
+ cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
+ if cur.fetchone() is None:
+ return jsonify({"error": "Warranty not found"}), 404
+ else:
+ return jsonify({"error": "Warranty not found or you don't have permission to access it"}), 404
- # Get tags for this warranty
+ # Get tags for this warranty (show all associated tags)
cur.execute('''
SELECT t.id, t.name, t.color, t.created_at
FROM tags t
JOIN warranty_tags wt ON t.id = wt.tag_id
- WHERE wt.warranty_id = %s
+ WHERE wt.warranty_id = %s -- Removed user_id/is_admin filter
ORDER BY t.name
''', (warranty_id,))
@@ -3197,11 +3211,12 @@ def get_warranty_tags(warranty_id):
@app.route('/api/warranties/<int:warranty_id>/tags', methods=['POST'])
@token_required
def add_tags_to_warranty(warranty_id):
- """Add tags to a warranty"""
+ # """Add tags to a warranty, ensuring tags match user role.""" # Docstring update needed
+ """Add tags owned by the user to a warranty they own."""
conn = None
try:
user_id = request.user['id']
- is_admin = request.user['is_admin']
+ # is_admin = request.user.get('is_admin', False) # Removed
data = request.json
if not data or 'tag_ids' not in data:
@@ -3213,32 +3228,56 @@ def add_tags_to_warranty(warranty_id):
conn = get_db_connection()
with conn.cursor() as cur:
- # First check if the warranty exists and user has access to it
- if is_admin:
- cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
- else:
- cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s',
- (warranty_id, user_id))
+ # First check if the warranty exists and user has access to it (owns it)
+ cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s',
+ (warranty_id, user_id))
if cur.fetchone() is None:
- return jsonify({"error": "Warranty not found or you don't have permission to modify it"}), 404
-
- # Remove existing tags
+ # Add admin check here if admins should modify any warranty tags
+ is_admin = request.user.get('is_admin', False)
+ if is_admin:
+ cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
+ if cur.fetchone() is None:
+ return jsonify({"error": "Warranty not found"}), 404
+ # Allow admin to proceed even if they don't own it
+ else:
+ return jsonify({"error": "Warranty not found or you don't have permission to modify it"}), 404
+
+ # Validate tags before removing/adding
+ valid_tag_ids = []
+ if tag_ids: # Only validate if there are tags to add
+ # Check if all provided tag IDs exist AND belong to the user
+ placeholders = ', '.join(['%s'] * len(tag_ids))
+ # Ensure the tags being added are owned by the user adding them
+ sql = f'SELECT id, user_id FROM tags WHERE id IN ({placeholders}) AND user_id = %s'
+ cur.execute(sql, tag_ids + [user_id]) # Check against current user_id
+ found_tags = cur.fetchall()
+
+ found_tag_map = {tag[0]: tag[1] for tag in found_tags}
+
+ for tag_id in tag_ids:
+ if tag_id not in found_tag_map: # This check also implicitly confirms ownership due to the query change
+ conn.rollback() # Ensure transaction consistency
+ return jsonify({"error": f"Tag with ID {tag_id} not found or not owned by you"}), 404
+ # Removed the old is_admin check
+ # if found_tag_map[tag_id] != is_admin:
+ # conn.rollback()
+ # tag_type_required = "admin" if is_admin else "user"
+ # return jsonify({"error": f"Tag with ID {tag_id} is not a valid {tag_type_required} tag"}), 403
+ valid_tag_ids.append(tag_id) # Keep track of validated tags
+
+ # Remove ALL existing tags before adding new ones for simplicity
+ # The old logic only removed tags of the same "type", which is no longer relevant
cur.execute('DELETE FROM warranty_tags WHERE warranty_id = %s', (warranty_id,))
- # Add new tags
- for tag_id in tag_ids:
- # Verify tag exists
- cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
- if cur.fetchone() is None:
- conn.rollback()
- return jsonify({"error": f"Tag with ID {tag_id} not found"}), 404
-
- # Add tag to warranty
- cur.execute(
- 'INSERT INTO warranty_tags (warranty_id, tag_id) VALUES (%s, %s)',
- (warranty_id, tag_id)
- )
+ # Add new (validated) tags
+ if valid_tag_ids:
+ values_placeholder = ', '.join(['(%s, %s)'] * len(valid_tag_ids))
+ sql = f'INSERT INTO warranty_tags (warranty_id, tag_id) VALUES {values_placeholder}'
+ params = []
+ for tag_id in valid_tag_ids:
+ params.extend([warranty_id, tag_id])
+ cur.execute(sql, params)
conn.commit()
return jsonify({"message": "Tags updated successfully"}), 200
@@ -3257,7 +3296,7 @@ EXPECTED_CSV_HEADERS = [
'PurchasePrice', 'SerialNumber', 'ProductURL'
]
# Add Tags as an optional header
-OPTIONAL_CSV_HEADERS = ['WarrantyYears', 'IsLifetime', 'PurchasePrice', 'SerialNumber', 'ProductURL', 'Tags']
+OPTIONAL_CSV_HEADERS = ['WarrantyYears', 'IsLifetime', 'PurchasePrice', 'SerialNumber', 'ProductURL', 'Tags', 'Vendor'] # Added Vendor
REQUIRED_CSV_HEADERS = ['ProductName', 'PurchaseDate']
@app.route('/api/warranties/import', methods=['POST'])
@@ -3317,6 +3356,7 @@ def import_warranties():
serial_numbers_str = row.get('SerialNumber', '').strip()
product_url = row.get('ProductURL', '').strip()
tags_str = row.get('Tags', '').strip() # Get Tags string
+ vendor = row.get('Vendor', '').strip() # Extract Vendor
if not product_name:
errors.append("ProductName is required.")
@@ -3356,10 +3396,23 @@ def import_warranties():
# Calculate expiration date if valid
if not errors and not is_lifetime and warranty_years and purchase_date:
- if relativedelta:
- expiration_date = purchase_date + relativedelta(years=warranty_years)
- else:
- expiration_date = purchase_date + timedelta(days=warranty_years * 365) # Approximate
+ # Decompose fractional years into years, months, days
+ try:
+ years_float = float(warranty_years)
+ total_months_float = years_float * 12
+ years_int = int(years_float)
+ remaining_months_float = total_months_float - (years_int * 12)
+ months_int = int(remaining_months_float)
+ # Approximate remaining days based on fraction of a month
+ remaining_days_float = (remaining_months_float - months_int) * (365.2425 / 12)
+ days_int = int(round(remaining_days_float)) # Round to nearest day
+
+ expiration_date = purchase_date + relativedelta(years=years_int, months=months_int, days=days_int)
+ logger.info(f"[Import] Calculated relativedelta for {warranty_years} years: years={years_int}, months={months_int}, days={days_int}")
+ except Exception as calc_err:
+ logger.error(f"[Import] Error calculating expiration date for row {row_number} from warranty_years={warranty_years}: {calc_err}")
+ errors.append("Failed to calculate expiration date from WarrantyYears.")
+ expiration_date = None # Ensure expiration_date is None if calculation fails
# Split serial numbers
serial_numbers = [sn.strip() for sn in serial_numbers_str.split(',') if sn.strip()] if serial_numbers_str else []
@@ -3369,10 +3422,11 @@ def import_warranties():
if tags_str:
tag_names = [name.strip() for name in tags_str.split(',') if name.strip()]
if tag_names:
- # Find existing tag IDs (case-insensitive)
+ # Find existing tag IDs (case-insensitive) for THIS USER
placeholders = ', '.join(['%s'] * len(tag_names))
- sql = f"SELECT id, LOWER(name) FROM tags WHERE LOWER(name) IN ({placeholders})"
- cur.execute(sql, [name.lower() for name in tag_names])
+ # Include user_id in the lookup
+ sql = f"SELECT id, LOWER(name) FROM tags WHERE LOWER(name) IN ({placeholders}) AND user_id = %s"
+ cur.execute(sql, [name.lower() for name in tag_names] + [user_id]) # Add user_id to params
existing_tags = {name_lower: tag_id for tag_id, name_lower in cur.fetchall()}
processed_tag_ids = []
@@ -3387,24 +3441,25 @@ def import_warranties():
if name_lower not in [t['name_lower'] for t in tags_to_create]:
tags_to_create.append({'name': name, 'name_lower': name_lower})
- # Create tags that don't exist
+ # Create tags that don't exist for this user
if tags_to_create:
default_color = '#808080' # Default color for new tags
for tag_data in tags_to_create:
try:
- # Insert new tag with default color, preserving original case for name
+ # Insert new tag with default color, preserving original case for name, AND user_id
cur.execute(
- "INSERT INTO tags (name, color) VALUES (%s, %s) RETURNING id",
- (tag_data['name'], default_color)
+ "INSERT INTO tags (name, color, user_id) VALUES (%s, %s, %s) RETURNING id",
+ (tag_data['name'], default_color, user_id) # Add user_id
)
new_tag_id = cur.fetchone()[0]
processed_tag_ids.append(new_tag_id)
- logger.info(f"Created new tag '{(tag_data['name'])}' with ID {new_tag_id} during CSV import.")
+ logger.info(f"Created new tag '{(tag_data['name'])}' with ID {new_tag_id} for user {user_id} during CSV import.")
except Exception as tag_insert_err:
- # If tag creation fails (e.g., unique constraint conflict due to race condition), log and potentially add error
- logger.error(f"Error creating tag '{(tag_data['name'])}' during import: {tag_insert_err}")
+ # If tag creation fails (e.g., unique constraint conflict due to race condition),
+ # ensure the constraint includes user_id
+ logger.error(f"Error creating tag '{(tag_data['name'])}' for user {user_id} during import: {tag_insert_err}")
# Attempt to fetch the ID again in case it was created by another process
- cur.execute("SELECT id FROM tags WHERE LOWER(name) = %s", (tag_data['name_lower'],))
+ cur.execute("SELECT id FROM tags WHERE LOWER(name) = %s AND user_id = %s", (tag_data['name_lower'], user_id))
existing_id_result = cur.fetchone()
if existing_id_result:
processed_tag_ids.append(existing_id_result[0])
@@ -3438,13 +3493,13 @@ def import_warranties():
cur.execute("""
INSERT INTO warranties (
product_name, purchase_date, warranty_years, expiration_date,
- product_url, purchase_price, user_id, is_lifetime
+ product_url, purchase_price, user_id, is_lifetime, vendor
)
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""", (
product_name, purchase_date, warranty_years, expiration_date,
- product_url, purchase_price, user_id, is_lifetime
+ product_url, purchase_price, user_id, is_lifetime, vendor
))
warranty_id = cur.fetchone()[0]
diff --git a/backend/init.sql b/backend/init.sql
deleted file mode 100644
index 1afc0cc..0000000
--- a/backend/init.sql
+++ /dev/null
@@ -1,7 +0,0 @@
--- backend/init.sql
-
--- Grant superuser privileges to warranty_user
-ALTER ROLE warranty_user WITH SUPERUSER;
-
--- The rest of the file content (CREATE TABLE, INSERT INTO) should be removed.
--- The migration system (apply_migrations.py) will handle table creation.
\ No newline at end of file
diff --git a/backend/migrations/006_add_notification_preferences.sql b/backend/migrations/007_add_notification_preferences.sql
similarity index 100%
rename from backend/migrations/006_add_notification_preferences.sql
rename to backend/migrations/007_add_notification_preferences.sql
diff --git a/backend/migrations/007_add_tags.sql b/backend/migrations/008_add_tags.sql
similarity index 100%
rename from backend/migrations/007_add_tags.sql
rename to backend/migrations/008_add_tags.sql
diff --git a/backend/migrations/009_add_admin_flag_to_tags.sql b/backend/migrations/009_add_admin_flag_to_tags.sql
new file mode 100644
index 0000000..e95a179
--- /dev/null
+++ b/backend/migrations/009_add_admin_flag_to_tags.sql
@@ -0,0 +1,6 @@
+-- Add is_admin_tag column to tags table
+ALTER TABLE tags
+ADD COLUMN IF NOT EXISTS is_admin_tag BOOLEAN NOT NULL DEFAULT FALSE;
+
+-- Optional: Add an index for faster lookups based on admin status
+CREATE INDEX IF NOT EXISTS idx_tags_is_admin_tag ON tags (is_admin_tag);
\ No newline at end of file
diff --git a/backend/migrations/008_configure_admin_roles.sql b/backend/migrations/010_configure_admin_roles.sql
similarity index 100%
rename from backend/migrations/008_configure_admin_roles.sql
rename to backend/migrations/010_configure_admin_roles.sql
diff --git a/backend/migrations/009_ensure_admin_permissions.sql b/backend/migrations/011_ensure_admin_permissions.sql
similarity index 100%
rename from backend/migrations/009_ensure_admin_permissions.sql
rename to backend/migrations/011_ensure_admin_permissions.sql
diff --git a/backend/migrations/010_add_timezone_column.sql b/backend/migrations/012_add_timezone_column.sql
similarity index 100%
rename from backend/migrations/010_add_timezone_column.sql
rename to backend/migrations/012_add_timezone_column.sql
diff --git a/backend/migrations/011_add_lifetime_warranty.sql b/backend/migrations/013_add_lifetime_warranty.sql
similarity index 100%
rename from backend/migrations/011_add_lifetime_warranty.sql
rename to backend/migrations/013_add_lifetime_warranty.sql
diff --git a/backend/migrations/013_add_updated_at_to_tags.sql b/backend/migrations/013_add_updated_at_to_tags.sql
deleted file mode 100644
index 74a7a15..0000000
--- a/backend/migrations/013_add_updated_at_to_tags.sql
+++ /dev/null
@@ -1,5 +0,0 @@
--- 013_add_updated_at_to_tags.sql
--- Adds an updated_at column to the tags table for tracking updates
-
-ALTER TABLE tags
-ADD COLUMN updated_at TIMESTAMP DEFAULT NOW();
diff --git a/backend/migrations/012_add_updated_at_to_warranties.sql b/backend/migrations/014_add_updated_at_to_warranties.sql
similarity index 100%
rename from backend/migrations/012_add_updated_at_to_warranties.sql
rename to backend/migrations/014_add_updated_at_to_warranties.sql
diff --git a/backend/migrations/012_allow_fractional_warranty_years.sql b/backend/migrations/015_allow_fractional_warranty_years.sql
similarity index 100%
rename from backend/migrations/012_allow_fractional_warranty_years.sql
rename to backend/migrations/015_allow_fractional_warranty_years.sql
diff --git a/backend/migrations/016_add_updated_at_to_tags.sql b/backend/migrations/016_add_updated_at_to_tags.sql
new file mode 100644
index 0000000..e7be0a0
--- /dev/null
+++ b/backend/migrations/016_add_updated_at_to_tags.sql
@@ -0,0 +1,5 @@
+-- 016_add_updated_at_to_tags.sql
+-- Adds an updated_at column to the tags table for tracking updates
+
+ALTER TABLE tags
+ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP DEFAULT NOW();
diff --git a/backend/migrations/014_add_notes_to_warranties.sql b/backend/migrations/017_add_notes_to_warranties.sql
similarity index 100%
rename from backend/migrations/014_add_notes_to_warranties.sql
rename to backend/migrations/017_add_notes_to_warranties.sql
diff --git a/backend/migrations/018_add_vendor_to_warranties.sql b/backend/migrations/018_add_vendor_to_warranties.sql
new file mode 100644
index 0000000..bcfd4a3
--- /dev/null
+++ b/backend/migrations/018_add_vendor_to_warranties.sql
@@ -0,0 +1,3 @@
+-- Migration to add vendor field to warranties table
+ALTER TABLE warranties ADD COLUMN IF NOT EXISTS
+vendor VARCHAR(255) NULL;
\ No newline at end of file
diff --git a/backend/migrations/019_add_date_format_column.sql b/backend/migrations/019_add_date_format_column.sql
new file mode 100644
index 0000000..cc3cfcf
--- /dev/null
+++ b/backend/migrations/019_add_date_format_column.sql
@@ -0,0 +1,18 @@
+-- Add date_format column to user_preferences table if it doesn't exist
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1
+ FROM information_schema.columns
+ WHERE table_name = 'user_preferences'
+ AND column_name = 'date_format'
+ ) THEN
+ -- Add the column with a default value of 'MDY'
+ ALTER TABLE user_preferences
+ ADD COLUMN date_format VARCHAR(10) NOT NULL DEFAULT 'MDY';
+
+ RAISE NOTICE 'Added date_format column to user_preferences table with default MDY';
+ ELSE
+ RAISE NOTICE 'date_format column already exists in user_preferences table';
+ END IF;
+END $$;
\ No newline at end of file
diff --git a/backend/migrations/020_add_user_id_to_tags.sql b/backend/migrations/020_add_user_id_to_tags.sql
new file mode 100644
index 0000000..4ed0244
--- /dev/null
+++ b/backend/migrations/020_add_user_id_to_tags.sql
@@ -0,0 +1,32 @@
+-- Add user_id column to tags table and update constraints
+DO $$
+BEGIN
+ -- Add user_id column if it doesn't exist
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_name = 'tags' AND column_name = 'user_id'
+ ) THEN
+ -- First, add the column as nullable
+ ALTER TABLE tags ADD COLUMN user_id INTEGER;
+
+ -- Update existing tags to have user_id = 1 (assuming this is the admin user)
+ UPDATE tags SET user_id = 1 WHERE user_id IS NULL;
+
+ -- Make the column NOT NULL
+ ALTER TABLE tags ALTER COLUMN user_id SET NOT NULL;
+
+ -- Add foreign key constraint
+ ALTER TABLE tags ADD CONSTRAINT fk_tags_user_id
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;
+
+ -- Drop the old unique constraint on name
+ ALTER TABLE tags DROP CONSTRAINT IF EXISTS tags_name_key;
+
+ -- Add new unique constraint on name and user_id
+ ALTER TABLE tags ADD CONSTRAINT tags_name_user_id_key
+ UNIQUE (name, user_id);
+
+ -- Create index for faster lookups
+ CREATE INDEX IF NOT EXISTS idx_tags_user_id ON tags (user_id);
+ END IF;
+END $$;
\ No newline at end of file
diff --git a/backend/migrations/__pycache__/004_add_user_preferences.cpython-39.pyc b/backend/migrations/__pycache__/004_add_user_preferences.cpython-39.pyc
deleted file mode 100644
index 46e206f..0000000
Binary files a/backend/migrations/__pycache__/004_add_user_preferences.cpython-39.pyc and /dev/null differ
diff --git a/backend/migrations/__pycache__/004_create_user_preferences_table.cpython-39.pyc b/backend/migrations/__pycache__/004_create_user_preferences_table.cpython-39.pyc
deleted file mode 100644
index fcac455..0000000
Binary files a/backend/migrations/__pycache__/004_create_user_preferences_table.cpython-39.pyc and /dev/null differ
diff --git a/backend/migrations/__pycache__/005_add_expiring_soon_days_column.cpython-39.pyc b/backend/migrations/__pycache__/005_add_expiring_soon_days_column.cpython-39.pyc
deleted file mode 100644
index efbb225..0000000
Binary files a/backend/migrations/__pycache__/005_add_expiring_soon_days_column.cpython-39.pyc and /dev/null differ
diff --git a/backend/migrations/__pycache__/007_add_expiring_soon_days.cpython-39.pyc b/backend/migrations/__pycache__/007_add_expiring_soon_days.cpython-39.pyc
deleted file mode 100644
index fe52eac..0000000
Binary files a/backend/migrations/__pycache__/007_add_expiring_soon_days.cpython-39.pyc and /dev/null differ
diff --git a/backend/requirements.txt b/backend/requirements.txt
index f7e8d3c..6b795a0 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -7,4 +7,5 @@ Flask-Login==0.6.2
Flask-Bcrypt==1.0.1
PyJWT==2.6.0
email-validator==1.3.1
-APScheduler==3.10.4
\ No newline at end of file
+APScheduler==3.10.4
+python-dateutil
\ No newline at end of file
diff --git a/backend/tests/test_notifications.py b/backend/tests/test_notifications.py
deleted file mode 100644
index 0563d69..0000000
--- a/backend/tests/test_notifications.py
+++ /dev/null
@@ -1,167 +0,0 @@
-import unittest
-from datetime import date, timedelta
-import sys
-import os
-import json
-from unittest.mock import patch, MagicMock
-
-# Add the parent directory to sys.path to allow importing app.py
-sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
-
-# Import the functions from app.py
-from app import get_expiring_warranties, format_expiration_email, send_expiration_notifications
-
-class TestWarrantyNotifications(unittest.TestCase):
-
- @patch('app.get_db_connection')
- def test_get_expiring_warranties(self, mock_get_db_connection):
- """Test that get_expiring_warranties correctly queries expiring warranties."""
- # Set up mock connection and cursor
- mock_conn = MagicMock()
- mock_cur = MagicMock()
- mock_conn.cursor.return_value.__enter__.return_value = mock_cur
- mock_get_db_connection.return_value = mock_conn
-
- # Set up mock cursor fetchall response
- today = date.today()
- mock_cur.fetchall.return_value = [
- # Format: email, first_name, product_name, expiration_date, expiring_soon_days
- ('[email protected]', 'John', 'Laptop', today + timedelta(days=10), 30),
- ('[email protected]', 'Jane', 'Phone', today + timedelta(days=20), 30),
- ('[email protected]', None, 'Tablet', today + timedelta(days=5), 30)
- ]
-
- # Call the function
- result = get_expiring_warranties()
-
- # Verify the SQL query is correct (simplified check)
- self.assertTrue(mock_cur.execute.called)
- args = mock_cur.execute.call_args[0]
- self.assertIn('warranties w', args[0]) # Check if the query includes the warranties table
- self.assertIn('users u', args[0]) # Check if the query includes the users table
- self.assertIn('user_preferences up', args[0]) # Check if the query includes user_preferences
-
- # Verify the result
- self.assertEqual(len(result), 3) # Should return 3 warranties
-
- # Check the first warranty
- self.assertEqual(result[0]['email'], '[email protected]')
- self.assertEqual(result[0]['first_name'], 'John')
- self.assertEqual(result[0]['product_name'], 'Laptop')
- self.assertEqual(result[0]['expiration_date'], (today + timedelta(days=10)).strftime('%Y-%m-%d'))
-
- # Check that null first_name is handled correctly
- self.assertEqual(result[2]['first_name'], 'User') # Default value for NULL
-
- # Verify the connection is released
- self.assertTrue(mock_conn.close.called)
-
- def test_format_expiration_email(self):
- """Test that format_expiration_email correctly formats the email."""
- # Test data
- user = {
- 'first_name': 'John',
- 'email': '[email protected]'
- }
-
- warranties = [
- {
- 'product_name': 'Laptop',
- 'expiration_date': '2023-12-31'
- },
- {
- 'product_name': 'Phone',
- 'expiration_date': '2023-11-30'
- }
- ]
-
- # Call the function
- email = format_expiration_email(user, warranties)
-
- # Verify the email
- self.assertEqual(email['Subject'], 'Warracker: Upcoming Warranty Expirations')
- self.assertEqual(email['From'], '[email protected]')
- self.assertEqual(email['To'], '[email protected]')
-
- # Check both parts exist (plain text and HTML)
- self.assertEqual(len(email.get_payload()), 2)
-
- # Check content of plain text part
- plain_text = email.get_payload(0).get_payload()
- self.assertIn('Hello John', plain_text)
- self.assertIn('Laptop (expires on 2023-12-31)', plain_text)
- self.assertIn('Phone (expires on 2023-11-30)', plain_text)
-
- # Check content of HTML part
- html = email.get_payload(1).get_payload()
- self.assertIn('Hello John', html)
- self.assertIn('Laptop', html)
- self.assertIn('2023-12-31', html)
- self.assertIn('Phone', html)
- self.assertIn('2023-11-30', html)
-
- @patch('app.get_expiring_warranties')
- @patch('smtplib.SMTP')
- def test_send_expiration_notifications(self, mock_smtp, mock_get_expiring_warranties):
- """Test that send_expiration_notifications correctly sends emails."""
- # Mock environment variables
- with patch.dict(os.environ, {
- 'SMTP_HOST': 'test.example.com',
- 'SMTP_PORT': '587',
- 'SMTP_USERNAME': '[email protected]',
- 'SMTP_PASSWORD': 'test_password'
- }):
- # Set up mock SMTP instance
- mock_smtp_instance = MagicMock()
- mock_smtp.return_value.__enter__.return_value = mock_smtp_instance
-
- # Set up mock for expiring warranties
- mock_get_expiring_warranties.return_value = [
- {
- 'email': '[email protected]',
- 'first_name': 'John',
- 'product_name': 'Laptop',
- 'expiration_date': '2023-12-31'
- },
- {
- 'email': '[email protected]',
- 'first_name': 'John',
- 'product_name': 'Phone',
- 'expiration_date': '2023-11-30'
- },
- {
- 'email': '[email protected]',
- 'first_name': 'Jane',
- 'product_name': 'Tablet',
- 'expiration_date': '2023-10-15'
- }
- ]
-
- # Call the function
- send_expiration_notifications()
-
- # Verify SMTP is initialized with correct parameters
- mock_smtp.assert_called_once_with('test.example.com', 587)
-
- # Verify starttls and login are called
- self.assertTrue(mock_smtp_instance.starttls.called)
- mock_smtp_instance.login.assert_called_once_with('[email protected]', 'test_password')
-
- # Verify sendmail is called twice (for two different users)
- self.assertEqual(mock_smtp_instance.sendmail.call_count, 2)
-
- # Verify first call to sendmail (for user1 with 2 warranties)
- from_email, to_email, msg = mock_smtp_instance.sendmail.call_args_list[0][0]
- self.assertEqual(from_email, '[email protected]')
- self.assertEqual(to_email, '[email protected]')
- self.assertIn('Laptop', msg)
- self.assertIn('Phone', msg)
-
- # Verify second call to sendmail (for user2 with 1 warranty)
- from_email, to_email, msg = mock_smtp_instance.sendmail.call_args_list[1][0]
- self.assertEqual(from_email, '[email protected]')
- self.assertEqual(to_email, '[email protected]')
- self.assertIn('Tablet', msg)
-
-if __name__ == '__main__':
- unittest.main()
\ No newline at end of file
diff --git a/frontend/about.html b/frontend/about.html
index b1517a1..3fd4da8 100644
--- a/frontend/about.html
+++ b/frontend/about.html
@@ -10,6 +10,8 @@
<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">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
+ <link rel="manifest" href="manifest.json">
<!-- Stylesheets -->
<link rel="stylesheet" href="style.css"> <!-- Main stylesheet -->
@@ -23,6 +25,22 @@
<script src="theme-loader.js"></script> <!-- Apply theme early -->
<script src="include-auth-new.js"></script> <!-- Handles auth state display -->
<script src="fix-auth-buttons-loader.js"></script> <!-- Fixes auth button display timing -->
+ <script src="auth.js"></script> <!-- Load auth.js early for authentication check -->
+
+ <!-- Authentication Check -->
+ <script>
+ document.addEventListener('DOMContentLoaded', () => {
+ // Check if user is authenticated
+ const authToken = localStorage.getItem('auth_token');
+ const userInfo = localStorage.getItem('user_info');
+
+ if (!authToken || !userInfo) {
+ // User is not authenticated, redirect to login page
+ window.location.href = 'login.html';
+ return;
+ }
+ });
+ </script>
</head>
<body>
@@ -88,7 +106,14 @@
<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.3</p>
+ <p><strong>Version:</strong> v0.9.9.4</p>
+
+ <div id="versionTracker" style="margin-bottom: 20px;">
+ <p><strong>Update Status:</strong> <span id="updateStatus">Checking for updates...</span></p>
+ <a id="updateLink" href="#" target="_blank" rel="noopener noreferrer" style="display: none; color: var(--link-color);">
+ <i class="fa-solid fa-arrow-up-right-from-square"></i> Release Notes
+ </a>
+ </div>
<p>
<strong>GitHub Repository:</strong>
@@ -137,6 +162,7 @@
<!-- Scripts loaded at the end of body -->
<script src="auth.js"></script> <!-- Added for user menu and other auth interactions -->
<script src="script.js"></script> <!-- Include main site script, might contain helpers -->
+ <script src="version-checker.js"></script> <!-- Version checker script -->
<!-- Explicitly call setupUIEventListeners for this page -->
<script>
diff --git a/frontend/api-test.html b/frontend/api-test.html
deleted file mode 100644
index 38387ed..0000000
--- a/frontend/api-test.html
+++ /dev/null
@@ -1,95 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>API Connection Test</title>
- <script src="theme-loader.js"></script> <!-- Apply theme early -->
- <!-- 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">
- <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
- <link rel="stylesheet" href="style.css">
- <!-- Font Awesome for icons -->
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
- <style>
- .alert {
- padding: 15px;
- margin-bottom: 20px;
- border-radius: 4px;
- }
- .alert-success {
- background-color: #d4edda;
- color: #155724;
- border: 1px solid #c3e6cb;
- }
- .alert-danger {
- background-color: #f8d7da;
- color: #721c24;
- border: 1px solid #f5c6cb;
- }
- pre {
- background-color: #f8f9fa;
- padding: 10px;
- border-radius: 4px;
- overflow: auto;
- max-height: 300px;
- }
- </style>
-</head>
-<body>
- <!-- Header -->
- <header>
- <div class="container">
- <div class="app-title">
- <i class="fas fa-shield-alt"></i>
- <h1>Warranty Tracker</h1>
- </div>
- <div class="nav-links">
- <a href="index.html" class="nav-link">
- <i class="fas fa-home"></i> Home
- </a>
- <a href="status.html" class="nav-link">
- <i class="fas fa-chart-pie"></i> Status
- </a>
- </div>
- </div>
- </header>
-
- <!-- Main Content -->
- <div class="container">
- <div class="content">
- <h2><i class="fas fa-terminal"></i> API Connection Test</h2>
-
- <div class="card">
- <div class="card-header">
- <h3>Testing API Connection</h3>
- </div>
- <div class="card-body">
- <div id="apiTestResult">
- <p>Checking API connection...</p>
- </div>
-
- <div class="debug-info">
- <h4>Manual API Test</h4>
- <p>You can also test the API manually with tools like curl:</p>
- <pre>curl -X GET -H "Authorization: Bearer YOUR_AUTH_TOKEN" http://localhost:8005/api/warranties</pre>
- </div>
-
- <div class="actions">
- <button onclick="location.reload()" class="btn">
- <i class="fas fa-sync-alt"></i> Run Test Again
- </button>
- <a href="index.html" class="btn">
- <i class="fas fa-home"></i> Back to Home
- </a>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Load test script -->
- <script src="test-api.js"></script>
-</body>
-</html>
\ No newline at end of file
diff --git a/frontend/auth.js b/frontend/auth.js
index 562c4f8..cc03297 100644
--- a/frontend/auth.js
+++ b/frontend/auth.js
@@ -121,6 +121,11 @@ function checkAuthState() {
* Update UI elements for authenticated user
*/
function updateUIForAuthenticatedUser() {
+ // Fire a global event so other scripts (like script.js) can react to authentication being ready
+ setTimeout(() => {
+ console.log('[auth.js] Dispatching authStateReady event');
+ window.dispatchEvent(new Event('authStateReady'));
+ }, 0);
console.log('auth.js: Updating UI for authenticated user');
// Log the user data being used
diff --git a/frontend/fix-auth-buttons.js b/frontend/fix-auth-buttons.js
index 49e301f..c4575bf 100644
--- a/frontend/fix-auth-buttons.js
+++ b/frontend/fix-auth-buttons.js
@@ -182,16 +182,4 @@ document.addEventListener('DOMContentLoaded', () => {
console.log('DOMContentLoaded event triggered, updating auth buttons');
updateAuthButtons();
setupUserMenuDropdown();
-
- // Set up periodic check (every 2 seconds)
- setInterval(updateAuthButtons, 2000);
- setInterval(setupUserMenuDropdown, 2000);
-});
-
-// Update auth buttons when localStorage changes
-window.addEventListener('storage', (event) => {
- if (event.key === 'auth_token' || event.key === 'user_info') {
- console.log('Auth data changed, updating auth buttons');
- updateAuthButtons();
- }
});
\ No newline at end of file
diff --git a/frontend/img/favicon-512x512.png b/frontend/img/favicon-512x512.png
new file mode 100644
index 0000000..d670094
Binary files /dev/null and b/frontend/img/favicon-512x512.png differ
diff --git a/frontend/include-auth-new.js b/frontend/include-auth-new.js
index d5c21ab..56e55f2 100644
--- a/frontend/include-auth-new.js
+++ b/frontend/include-auth-new.js
@@ -7,107 +7,87 @@
console.log('include-auth-new.js: Running immediate auth check');
-// Immediately check if user is logged in
-if (localStorage.getItem('auth_token')) {
- console.log('include-auth-new.js: Auth token found, hiding login/register buttons immediately');
-
- // Create and inject CSS to hide auth buttons
- var style = document.createElement('style');
- style.textContent = `
- #authContainer, .auth-buttons, a[href="login.html"], a[href="register.html"],
- .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn {
- display: none !important;
- visibility: hidden !important;
- }
-
- #userMenu, .user-menu {
- display: block !important;
- visibility: visible !important;
- }
- `;
- document.head.appendChild(style);
-
- // Set the display style as soon as DOM is ready
- window.addEventListener('DOMContentLoaded', function() {
- console.log('include-auth-new.js: DOM loaded, ensuring buttons are hidden');
-
- // Hide auth container
- var authContainer = document.getElementById('authContainer');
- if (authContainer) {
- authContainer.style.display = 'none';
- authContainer.style.visibility = 'hidden';
- }
-
- // Hide all login/register buttons
- document.querySelectorAll('a[href="login.html"], a[href="register.html"], .login-btn, .register-btn, .auth-btn').forEach(function(button) {
- button.style.display = 'none';
- button.style.visibility = 'hidden';
- });
-
- // Show user menu
- var userMenu = document.getElementById('userMenu');
- if (userMenu) {
- userMenu.style.display = 'block';
- userMenu.style.visibility = 'visible';
+// Function to update UI based on auth state (extracted for reuse)
+function updateAuthUI() {
+ if (localStorage.getItem('auth_token')) {
+ console.log('include-auth-new.js: Updating UI for authenticated user');
+ // Inject CSS to hide auth buttons and show user menu
+ const styleId = 'auth-ui-style';
+ let style = document.getElementById(styleId);
+ if (!style) {
+ style = document.createElement('style');
+ style.id = styleId;
+ document.head.appendChild(style);
}
-
- // Update user information
+ style.textContent = `
+ #authContainer, .auth-buttons, a[href="login.html"], a[href="register.html"],
+ .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn {
+ display: none !important;
+ visibility: hidden !important;
+ }
+ #userMenu, .user-menu {
+ display: block !important;
+ visibility: visible !important;
+ }
+ `;
+
+ // Update user info display elements immediately
try {
var userInfoStr = localStorage.getItem('user_info');
if (userInfoStr) {
var userInfo = JSON.parse(userInfoStr);
var displayName = userInfo.username || 'User';
-
var userDisplayName = document.getElementById('userDisplayName');
- if (userDisplayName) {
- userDisplayName.textContent = displayName;
- }
-
+ if (userDisplayName) userDisplayName.textContent = displayName;
var userName = document.getElementById('userName');
if (userName) {
userName.textContent = (userInfo.first_name || '') + ' ' + (userInfo.last_name || '');
if (!userName.textContent.trim()) userName.textContent = userInfo.username || 'User';
}
-
var userEmail = document.getElementById('userEmail');
- if (userEmail && userInfo.email) {
- userEmail.textContent = userInfo.email;
- }
+ if (userEmail && userInfo.email) userEmail.textContent = userInfo.email;
}
} catch (e) {
- console.error('include-auth-new.js: Error updating user info:', e);
+ console.error('include-auth-new.js: Error updating user info display:', e);
}
- });
-} else {
- console.log('include-auth-new.js: No auth token found, showing login/register buttons');
-
- // Create and inject CSS to show auth buttons
- var style = document.createElement('style');
- style.textContent = `
- #authContainer, .auth-buttons {
- display: flex !important;
- visibility: visible !important;
- }
-
- a[href="login.html"], a[href="register.html"],
- .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn {
- display: inline-block !important;
- visibility: visible !important;
- }
-
- #userMenu, .user-menu {
- display: none !important;
- visibility: hidden !important;
+
+ } else {
+ console.log('include-auth-new.js: Updating UI for logged-out user');
+ // Inject CSS to show auth buttons and hide user menu
+ const styleId = 'auth-ui-style';
+ let style = document.getElementById(styleId);
+ if (!style) {
+ style = document.createElement('style');
+ style.id = styleId;
+ document.head.appendChild(style);
}
- `;
- document.head.appendChild(style);
+ style.textContent = `
+ #authContainer, .auth-buttons {
+ display: flex !important; /* Use flex for container */
+ visibility: visible !important;
+ }
+ a[href="login.html"], a[href="register.html"],
+ .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn {
+ display: inline-block !important; /* Use inline-block for buttons */
+ visibility: visible !important;
+ }
+ #userMenu, .user-menu {
+ display: none !important;
+ visibility: hidden !important;
+ }
+ `;
+ }
}
-// Listen for changes to localStorage
+// Immediately check auth state and update UI
+updateAuthUI();
+
+// Listen for changes to localStorage and update UI without reloading
window.addEventListener('storage', function(event) {
if (event.key === 'auth_token' || event.key === 'user_info') {
- console.log('include-auth-new.js: Auth data changed, reloading page to update UI');
- window.location.reload();
+ console.log(`include-auth-new.js: Storage event detected for ${event.key}. Updating UI.`);
+ updateAuthUI(); // Update UI instead of reloading
+ // window.location.reload(); // <-- Keep commented out / Remove permanently
}
});
diff --git a/frontend/index.html b/frontend/index.html
index 53f5094..1fc2799 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -20,6 +20,8 @@
<!-- Add new favicon links -->
<link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
+ <link rel="manifest" href="manifest.json">
<link rel="stylesheet" href="style.css">
<script src="theme-loader.js"></script> <!-- Apply theme early -->
@@ -167,7 +169,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, notes or tag...">
+ <input type="text" id="searchWarranties" placeholder="Find by name, notes, tag, or serial number...">
<button id="clearSearch" class="clear-search-btn" title="Clear search" style="display: none;">
<i class="fas fa-times"></i>
</button>
@@ -297,6 +299,10 @@
<input type="text" name="serial_numbers[]" class="form-control" style="margin-bottom: 8px;" placeholder="Enter serial number">
</div>
</div>
+ <div class="form-group">
+ <label for="vendor">Vendor (Optional)</label>
+ <input type="text" id="vendor" name="vendor" class="form-control" placeholder="e.g. Amazon, Best Buy, etc.">
+ </div>
</div>
<!-- Warranty Details Tab -->
<div class="tab-content" id="warranty-details">
@@ -398,6 +404,10 @@
<span class="summary-label">Serial Numbers:</span>
<span id="summary-serial-numbers" class="summary-value">-</span>
</div>
+ <div class="summary-item">
+ <span class="summary-label">Vendor:</span>
+ <span id="summary-vendor" class="summary-value">-</span>
+ </div>
</div>
<div class="summary-section">
<h4><i class="fas fa-shield-alt"></i> Warranty Details</h4>
@@ -503,6 +513,10 @@
<!-- Serial number inputs will be added dynamically -->
</div>
</div>
+ <div class="form-group">
+ <label for="editVendor">Vendor (Optional)</label>
+ <input type="text" id="editVendor" name="vendor" class="form-control" placeholder="e.g. Amazon, Best Buy, etc.">
+ </div>
</div>
<!-- Warranty Details Tab -->
diff --git a/frontend/login.html b/frontend/login.html
index 96fa0b4..285d8b4 100644
--- a/frontend/login.html
+++ b/frontend/login.html
@@ -11,6 +11,8 @@
<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">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
+ <link rel="manifest" href="manifest.json">
<link rel="stylesheet" href="style.css">
<script src="theme-loader.js"></script> <!-- Apply theme early -->
<!-- Font Awesome for icons -->
diff --git a/frontend/manifest.json b/frontend/manifest.json
new file mode 100644
index 0000000..82723fa
--- /dev/null
+++ b/frontend/manifest.json
@@ -0,0 +1,15 @@
+{
+ "name": "Warracker",
+ "short_name": "Warracker",
+ "icons": [
+ {
+ "src": "img/favicon-512x512.png",
+ "sizes": "512x512",
+ "type": "image/png"
+ }
+ ],
+ "start_url": "./index.html",
+ "display": "standalone",
+ "background_color": "#ffffff",
+ "theme_color": "#ffffff"
+}
\ No newline at end of file
diff --git a/frontend/register.html b/frontend/register.html
index 46ab107..6f82ec6 100644
--- a/frontend/register.html
+++ b/frontend/register.html
@@ -11,6 +11,8 @@
<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">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
+ <link rel="manifest" href="manifest.json">
<link rel="stylesheet" href="style.css">
<script src="theme-loader.js"></script> <!-- Apply theme early -->
<!-- Font Awesome for icons -->
@@ -574,16 +576,9 @@
authMessage.className = 'auth-message';
authMessage.classList.add(type);
authMessage.style.display = 'block';
-
// Scroll to message
authMessage.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
-
- // Check for dark mode preference
- const darkModeEnabled = localStorage.getItem('darkMode') === 'enabled';
- if (darkModeEnabled) {
- document.body.classList.add('dark-mode');
- }
});
// Theme initialization
diff --git a/frontend/reset-password-request.html b/frontend/reset-password-request.html
index 96c8ce9..9fdb5da 100644
--- a/frontend/reset-password-request.html
+++ b/frontend/reset-password-request.html
@@ -8,6 +8,8 @@
<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">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
+ <link rel="manifest" href="manifest.json">
<link rel="stylesheet" href="style.css">
<script src="theme-loader.js"></script> <!-- Apply theme early -->
<!-- Font Awesome for icons -->
@@ -210,11 +212,7 @@
authMessage.style.display = 'block';
}
- // Check for dark mode preference
- const darkModeEnabled = localStorage.getItem('darkMode') === 'enabled';
- if (darkModeEnabled) {
- document.body.classList.add('dark-mode');
- }
+ // No longer check for 'enabled' value. Theme is handled by theme-loader.js and below.
});
// Theme initialization
diff --git a/frontend/reset-password.html b/frontend/reset-password.html
index 1e62325..862fda7 100644
--- a/frontend/reset-password.html
+++ b/frontend/reset-password.html
@@ -8,6 +8,8 @@
<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">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
+ <link rel="manifest" href="manifest.json">
<link rel="stylesheet" href="style.css">
<script src="theme-loader.js"></script> <!-- Apply theme early -->
<!-- Font Awesome for icons -->
@@ -398,11 +400,7 @@
}
}
- // Check for dark mode preference
- const darkModeEnabled = localStorage.getItem('darkMode') === 'enabled';
- if (darkModeEnabled) {
- document.body.classList.add('dark-mode');
- }
+ // No longer check for 'enabled' value. Theme is handled by theme-loader.js and below.
});
// Theme initialization
diff --git a/frontend/script.js b/frontend/script.js
index e965deb..d7a3a24 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -1,9 +1,13 @@
+// alert('script.js loaded!'); // Remove alert after confirming script loads
+console.log('[DEBUG] script.js loaded and running');
+
// Global variables
let warranties = [];
let currentTabIndex = 0;
let tabContents = []; // Initialize as empty array
let editMode = false;
let currentWarrantyId = null;
+let userPreferencePrefix = null; // <<< ADDED GLOBAL PREFIX VARIABLE
let currentFilters = {
status: 'all',
tag: 'all',
@@ -117,15 +121,18 @@ function setTheme(isDark) {
// Initialization logic on DOMContentLoaded
document.addEventListener('DOMContentLoaded', function() {
+ console.log('[DEBUG] Registering authStateReady event handler');
// ... other initialization ...
// REMOVE call to undefined checkLoginStatus - Handled by auth.js
// checkLoginStatus();
-
- // Load warranties (assuming warrantiesList exists on this page)
- if (document.getElementById('warrantiesList')) {
- loadWarranties();
- }
+
+ // --- DEFERRED WARRANTY LOADING ---
+ // Don't load warranties immediately. Wait for authentication.
+ // if (document.getElementById('warrantiesList')) {
+ // loadWarranties(); // <<< OLD CALL - REMOVED
+ // }
+ // --- END DEFERRED WARRANTY LOADING ---
// Setup form submission (assuming addWarrantyForm exists)
const form = document.getElementById('addWarrantyForm');
@@ -137,32 +144,32 @@ document.addEventListener('DOMContentLoaded', function() {
// REMOVED setupSettingsMenu - Handled by auth.js
// setupSettingsMenu();
-
+
// Initialize theme toggle state *after* DOM is loaded
// ... (theme toggle init logic) ...
-
+
// Setup view switcher (assuming view switcher elements exist)
if (document.getElementById('gridViewBtn')) {
// setupViewSwitcher(); // Removed undefined function
loadViewPreference();
}
-
+
// Setup filter controls (assuming filter controls exist)
if (document.getElementById('filterControls')) {
// setupFilterControls(); // Removed: function not defined
populateTagFilter();
}
-
+
// Initialize modal interactions
// initializeModals(); // Removed: function not defined, handled by setupModalTriggers
setupModalTriggers();
-
+
// Initialize Tag functionality (assuming tag elements exist)
if (document.getElementById('tagSearchInput')) {
initTagFunctionality();
loadTags();
}
-
+
// Initialize form-specific lifetime checkbox handler
const lifetimeCheckbox = document.getElementById('isLifetime');
if (lifetimeCheckbox) {
@@ -170,35 +177,56 @@ document.addEventListener('DOMContentLoaded', function() {
handleLifetimeChange({ target: lifetimeCheckbox }); // Initial check
}
- updateCurrencySymbols();
+ // --- LOAD WARRANTIES AFTER AUTH ---
+ // Listen for an event from auth.js indicating authentication is complete and user context is ready.
+ // ** IMPORTANT: Replace 'authStateReady' with the actual event name fired by auth.js **
+ window.addEventListener('authStateReady', async function handleAuthReady() { // <-- Make handler async
+ console.log('[DEBUG] authStateReady handler called');
+ console.log("Auth state ready event received. Preparing preferences and warranties...");
+ // Ensure this listener runs only once
+ window.removeEventListener('authStateReady', handleAuthReady);
+
+ // Set prefix
+ userPreferencePrefix = getPreferenceKeyPrefix();
+ console.log(`[authStateReady] Determined and stored global prefix: ${userPreferencePrefix}`);
+
+ // Load preferences
+ await loadAndApplyUserPreferences();
+
+ // Load warranty data (fetches, processes, populates global array)
+ if (document.getElementById('warrantiesList')) {
+ console.log("[authStateReady] Loading warranty data...");
+ await loadWarranties(); // Waits for fetch/process
+ console.log('[DEBUG] After loadWarranties, warranties array:', warranties);
+ } else {
+ console.log("[authStateReady] Warranties list element not found.");
+ }
+
+ // Now that data and preferences are ready, apply view/currency and render via applyFilters
+ console.log("[authStateReady] Applying preferences and rendering...");
+ loadViewPreference(); // Sets currentView and UI classes/buttons
+ updateCurrencySymbols(); // Update symbols
+
+ // Apply filters using the loaded data and render the list
+ if (document.getElementById('warrantiesList')) {
+ applyFilters();
+ }
+
+ }, { once: true }); // Use { once: true } as a fallback if removeEventListener isn't reliable across scripts
+ // --- END LOAD WARRANTIES AFTER AUTH ---
+
+ // updateCurrencySymbols(); // Call removed, rely on loadWarranties triggering render with correct symbol
});
// Initialize theme based on user preference or system preference
function initializeTheme() {
- // Get the appropriate key prefix based on user type
- const prefix = getPreferenceKeyPrefix();
- console.log(`Initializing theme with prefix: ${prefix}`);
-
- // First check user-specific setting
- const userDarkMode = localStorage.getItem(`${prefix}darkMode`);
- if (userDarkMode !== null) {
- console.log(`Found user-specific dark mode setting: ${userDarkMode}`);
- setTheme(userDarkMode === 'true');
- return;
- }
-
- // Then check global setting for backward compatibility
- const globalDarkMode = localStorage.getItem('darkMode');
- if (globalDarkMode !== null) {
- console.log(`Found global dark mode setting: ${globalDarkMode}`);
- setTheme(globalDarkMode === 'true');
- return;
+ // Only use the global darkMode key for theme persistence
+ const savedTheme = localStorage.getItem('darkMode');
+ if (savedTheme !== null) {
+ setTheme(savedTheme === 'true');
+ } else {
+ setTheme(window.matchMedia('(prefers-color-scheme: dark)').matches);
}
-
- // Check for system preference if no stored preference
- const prefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
- console.log(`No saved preference, using system preference: ${prefersDarkMode}`);
- setTheme(prefersDarkMode);
}
// Variables
@@ -219,7 +247,79 @@ const nextButton = document.querySelector('.next-tab'); // Keep these if needed
const prevButton = document.querySelector('.prev-tab'); // Keep these if needed globally, otherwise might remove
// --- Add near other DOM Element declarations ---
-// ... existing code ...
+ // ... existing code ...
+ // Add save button handler for notes modal (if not already present)
+ const saveNotesBtn = document.getElementById('saveNotesBtn');
+ if (saveNotesBtn) {
+ saveNotesBtn.onclick = async function() {
+ // Get the warranty ID being edited
+ const warrantyId = notesModalWarrantyId;
+ const notesValue = document.getElementById('notesModalTextarea').value;
+ if (!warrantyId || !notesModalWarrantyObj) return;
+ // Get auth token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ showToast('Authentication required', 'error');
+ return;
+ }
+ showLoadingSpinner();
+ try {
+ // Use FormData and send all required fields, just like the edit modal
+ const formData = new FormData();
+ 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 || '');
+ }
+ if (notesModalWarrantyObj.product_url) {
+ formData.append('product_url', notesModalWarrantyObj.product_url);
+ }
+ if (notesModalWarrantyObj.purchase_price !== null && notesModalWarrantyObj.purchase_price !== 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);
+ }
+ });
+ } 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));
+ } else {
+ formData.append('tag_ids', JSON.stringify([]));
+ }
+ formData.append('notes', notesValue);
+ const response = await fetch(`/api/warranties/${warrantyId}`, {
+ method: 'PUT',
+ headers: {
+ 'Authorization': 'Bearer ' + token
+ },
+ body: formData
+ });
+ if (!response.ok) {
+ const data = await response.json();
+ throw new Error(data.error || 'Failed to update notes');
+ }
+ hideLoadingSpinner();
+ showToast('Notes updated successfully', 'success');
+ // Close the modal
+ const notesModal = document.getElementById('notesModal');
+ if (notesModal) notesModal.style.display = 'none';
+ // Now reload warranties and re-render UI
+ await loadWarranties();
+ applyFilters();
+ } catch (error) {
+ hideLoadingSpinner();
+ console.error('Error updating notes:', error);
+ showToast(error.message || 'Failed to update notes', 'error');
+ }
+ };
+ }
// Initialize form tabs
function initFormTabs() {
@@ -488,11 +588,29 @@ function updateSummary() {
}
// Warranty details
- const purchaseDate = document.getElementById('purchaseDate')?.value;
+ const purchaseDateStr = document.getElementById('purchaseDate')?.value;
const summaryPurchaseDate = document.getElementById('summary-purchase-date');
if (summaryPurchaseDate) {
- summaryPurchaseDate.textContent = purchaseDate ?
- new Date(purchaseDate).toLocaleDateString() : '-';
+ if (purchaseDateStr) {
+ // Use the same logic as formatDate to handle YYYY-MM-DD
+ const parts = String(purchaseDateStr).split('-');
+ let formattedDate = '-'; // Default
+ if (parts.length === 3) {
+ const year = parseInt(parts[0], 10);
+ const month = parseInt(parts[1], 10) - 1; // JS months are 0-indexed
+ const day = parseInt(parts[2], 10);
+ const dateObj = new Date(Date.UTC(year, month, day));
+ if (!isNaN(dateObj.getTime())) {
+ // Format manually (example: Jan 1, 2023)
+ const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+ formattedDate = `${monthNames[month]} ${day}, ${year}`;
+ }
+ }
+ summaryPurchaseDate.textContent = formattedDate;
+ } else {
+ summaryPurchaseDate.textContent = '-';
+ }
}
// --- Handle Lifetime in Summary ---
@@ -513,8 +631,8 @@ function updateSummary() {
// Calculate and display expiration date
const summaryExpirationDate = document.getElementById('summary-expiration-date');
- if (summaryExpirationDate && purchaseDate && warrantyYears) {
- const expirationDate = new Date(purchaseDate);
+ if (summaryExpirationDate && purchaseDateStr && warrantyYears) {
+ const expirationDate = new Date(Date.UTC(parseInt(purchaseDateStr.split('-')[0]), parseInt(purchaseDateStr.split('-')[1]) - 1, parseInt(purchaseDateStr.split('-')[2])));
const yearsNum = parseFloat(warrantyYears);
if (!isNaN(yearsNum)) {
expirationDate.setFullYear(expirationDate.getFullYear() + Math.floor(yearsNum));
@@ -569,6 +687,10 @@ function updateSummary() {
summaryTags.textContent = 'No tags selected';
}
}
+
+ // Vendor/Retailer
+ const vendor = document.getElementById('vendor');
+ document.getElementById('summary-vendor').textContent = vendor && vendor.value ? vendor.value : '-';
}
// Add input event listeners to remove validation errors when user types
@@ -621,8 +743,11 @@ async function exportWarranties() {
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
- return productNameMatch || tagMatch;
+ // Check if vendor name contains search term
+ const vendorMatch = warranty.vendor && warranty.vendor.toLowerCase().includes(searchTerm);
+
+ // Return true if either product name, tag name, or vendor name matches
+ return productNameMatch || tagMatch || vendorMatch;
});
}
@@ -645,7 +770,7 @@ async function exportWarranties() {
let csvContent = "data:text/csv;charset=utf-8,";
// Add headers
- csvContent += "Product Name,Purchase Date,Warranty Period,Expiration Date,Status,Serial Numbers,Tags\n";
+ csvContent += "Product Name,Purchase Date,Warranty Period,Expiration Date,Status,Serial Numbers,Tags,Vendor\n";
// Add data rows
warrantiesToExport.forEach(warranty => {
@@ -667,7 +792,8 @@ async function exportWarranties() {
formatDate(new Date(warranty.expiration_date)),
warranty.status || '',
serialNumbers,
- tags
+ tags,
+ warranty.vendor || ''
];
// Add row to CSV content
@@ -692,18 +818,60 @@ async function exportWarranties() {
}
// Switch view of warranties list
-function switchView(viewType) {
+async function switchView(viewType) { // Added async
console.log(`Switching to view: ${viewType}`);
currentView = viewType;
- // Get the appropriate key prefix based on user type
const prefix = getPreferenceKeyPrefix();
- // --- BEGIN EDIT: Save to all relevant keys ---
- localStorage.setItem(`${prefix}viewPreference`, viewType); // Keep this one
- localStorage.setItem(`${prefix}defaultView`, viewType); // Add for consistency with settings load priority
- localStorage.setItem(`${prefix}warrantyView`, viewType); // Add for consistency with settings legacy save
- localStorage.setItem('viewPreference', viewType); // Keep general key
- // --- END EDIT ---
+ const viewKey = `${prefix}defaultView`;
+ const currentStoredValue = localStorage.getItem(viewKey);
+
+ // Save to localStorage immediately for responsiveness
+ if (currentStoredValue !== viewType) {
+ localStorage.setItem(viewKey, viewType);
+ // Keep legacy keys for now if needed, but primary is viewKey
+ localStorage.setItem(`${prefix}warrantyView`, viewType);
+ localStorage.setItem('viewPreference', viewType);
+ console.log(`Saved view preference (${viewKey}) to localStorage: ${viewType}`);
+ } else {
+ console.log(`View preference (${viewKey}) already set to ${viewType} in localStorage.`);
+ }
+
+ // --- BEGIN ADDED: Save preference to API ---
+ if (window.auth && window.auth.isAuthenticated()) {
+ const token = window.auth.getToken();
+ if (token) {
+ try {
+ console.log(`Attempting to save view preference (${viewType}) to API...`);
+ const response = await fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ default_view: viewType }) // Send only the changed preference
+ });
+
+ if (response.ok) {
+ console.log('Successfully saved view preference to API.');
+ } else {
+ const errorData = await response.json().catch(() => ({}));
+ console.warn(`Failed to save view preference to API: ${response.status}`, errorData.message || '');
+ // Optional: Show a non-intrusive warning toast?
+ // showToast('Failed to sync view preference with server.', 'warning');
+ }
+ } catch (error) {
+ console.error('Error saving view preference to API:', error);
+ // Optional: Show a non-intrusive warning toast?
+ // showToast('Error syncing view preference with server.', 'error');
+ }
+ } else {
+ console.warn('Cannot save view preference to API: No auth token found.');
+ }
+ } else {
+ console.warn('Cannot save view preference to API: User not authenticated or auth module not loaded.');
+ }
+ // --- END ADDED: Save preference to API ---
// Make sure warrantiesList exists before modifying classes
if (warrantiesList) {
@@ -716,13 +884,12 @@ function switchView(viewType) {
gridViewBtn.classList.remove('active');
listViewBtn.classList.remove('active');
tableViewBtn.classList.remove('active');
+ // Add active class to the correct button
+ if (viewType === 'grid') gridViewBtn.classList.add('active');
+ if (viewType === 'list') listViewBtn.classList.add('active');
+ if (viewType === 'table') tableViewBtn.classList.add('active');
}
- // Make sure the specific button exists
- if (viewType === 'grid' && gridViewBtn) gridViewBtn.classList.add('active');
- if (viewType === 'list' && listViewBtn) listViewBtn.classList.add('active');
- if (viewType === 'table' && tableViewBtn) tableViewBtn.classList.add('active');
-
// Show/hide table header only if it exists
if (tableViewHeader) {
tableViewHeader.classList.toggle('visible', viewType === 'table');
@@ -730,7 +897,7 @@ function switchView(viewType) {
// Re-render warranties only if warrantiesList exists
if (warrantiesList) {
- renderWarranties(filterWarranties());
+ renderWarranties(filterWarranties()); // Assuming filterWarranties() returns the correct array
}
}
@@ -907,8 +1074,48 @@ function processWarrantyData(warranty) {
const today = new Date();
today.setHours(0, 0, 0, 0); // Normalize today to midnight for accurate date comparisons
- processedWarranty.purchaseDate = processedWarranty.purchase_date ? new Date(processedWarranty.purchase_date) : null;
- processedWarranty.expirationDate = processedWarranty.expiration_date ? new Date(processedWarranty.expiration_date) : null;
+ // Parse purchase_date string (YYYY-MM-DD) into a UTC Date object
+ let purchaseDateObj = null;
+ if (processedWarranty.purchase_date) {
+ const parts = String(processedWarranty.purchase_date).split('-');
+ if (parts.length === 3) {
+ const year = parseInt(parts[0], 10);
+ const month = parseInt(parts[1], 10) - 1; // JS months are 0-indexed
+ const day = parseInt(parts[2], 10);
+ purchaseDateObj = new Date(Date.UTC(year, month, day));
+ if (isNaN(purchaseDateObj.getTime())) {
+ purchaseDateObj = null; // Invalid date parsed
+ }
+ } else {
+ // Fallback for unexpected formats, though backend should send YYYY-MM-DD
+ purchaseDateObj = new Date(processedWarranty.purchase_date);
+ if (isNaN(purchaseDateObj.getTime())) {
+ purchaseDateObj = null;
+ }
+ }
+ }
+ processedWarranty.purchaseDate = purchaseDateObj;
+
+ // Parse expiration_date similarly (assuming it's also YYYY-MM-DD)
+ let expirationDateObj = null;
+ if (processedWarranty.expiration_date) {
+ const parts = String(processedWarranty.expiration_date).split('-');
+ if (parts.length === 3) {
+ const year = parseInt(parts[0], 10);
+ const month = parseInt(parts[1], 10) - 1;
+ const day = parseInt(parts[2], 10);
+ expirationDateObj = new Date(Date.UTC(year, month, day));
+ if (isNaN(expirationDateObj.getTime())) {
+ expirationDateObj = null;
+ }
+ } else {
+ expirationDateObj = new Date(processedWarranty.expiration_date);
+ if (isNaN(expirationDateObj.getTime())) {
+ expirationDateObj = null;
+ }
+ }
+ }
+ processedWarranty.expirationDate = expirationDateObj;
// --- Lifetime Handling ---
if (processedWarranty.is_lifetime) {
@@ -954,53 +1161,93 @@ function processAllWarranties() {
}
async function loadWarranties() {
+ // +++ REMOVED: Ensure Preferences are loaded FIRST (Now handled by authStateReady) +++
+ // await loadAndApplyUserPreferences();
+ // +++ Preferences Loaded +++
+
try {
- console.log('Loading warranties...');
+ console.log('[DEBUG] Entered loadWarranties');
showLoading();
- // Get expiring soon days from user preferences if available
+ // Fetch user preferences (including date format) before loading warranties
+ // --- THIS INNER PREFERENCE FETCH IS NOW REDUNDANT, REMOVE/COMMENT OUT ---
+ /*
try {
+ const token = window.auth.getToken(); // Ensure token is retrieved here
+ if (!token) throw new Error("No auth token found"); // Added error handling
+
const prefsResponse = await fetch('/api/auth/preferences', {
headers: {
- 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
+ 'Authorization': `Bearer ${token}`
}
});
if (prefsResponse.ok) {
- const data = await prefsResponse.json();
- if (data && data.expiring_soon_days) {
+ const prefsData = await prefsResponse.json();
+ console.log("Preferences fetched in loadWarranties:", prefsData);
+
+ // Update expiringSoonDays
+ if (prefsData && typeof prefsData.expiring_soon_days !== 'undefined') {
const oldValue = expiringSoonDays;
- expiringSoonDays = data.expiring_soon_days;
+ expiringSoonDays = prefsData.expiring_soon_days;
console.log('Updated expiring soon days from preferences:', expiringSoonDays);
-
- // If we already have warranties loaded and the value changed, reprocess them
- if (warranties && warranties.length > 0 && oldValue !== expiringSoonDays) {
- console.log('Reprocessing warranties with new expiringSoonDays value');
- warranties = warranties.map(warranty => processWarrantyData(warranty));
- renderWarrantiesTable(warranties);
+ // Reprocess logic moved below warranty fetch
+ }
+
+ // --- ADDED: Update dateFormat in localStorage ---
+ if (prefsData && typeof prefsData.date_format !== 'undefined') {
+ const oldDateFormat = localStorage.getItem('dateFormat');
+ localStorage.setItem('dateFormat', prefsData.date_format);
+ console.log(`Updated dateFormat in localStorage from API: ${prefsData.date_format}`);
+ // Trigger re-render if format changed and warranties already exist (though unlikely at this stage)
+ if (warranties && warranties.length > 0 && oldDateFormat !== prefsData.date_format) {
+ console.log('Date format changed, triggering re-render via applyFilters');
+ applyFilters(); // Re-render warranties with new format
}
+ } else {
+ // If API doesn't return date_format, ensure localStorage has a default
+ if (!localStorage.getItem('dateFormat')) {
+ localStorage.setItem('dateFormat', 'MDY');
+ console.log('API did not return date_format, setting localStorage default to MDY');
+ }
}
+ // --- END ADDED SECTION ---
+
+ } else {
+ // Handle failed preference fetch
+ console.warn('Failed to fetch preferences:', prefsResponse.status);
+ // Ensure a default date format exists if fetch fails
+ if (!localStorage.getItem('dateFormat')) {
+ localStorage.setItem('dateFormat', 'MDY');
+ console.log('Preferences fetch failed, setting localStorage default date format to MDY');
+ }
}
} catch (error) {
console.error('Error loading preferences:', error);
- // Continue with default value
+ // Ensure a default date format exists on error
+ if (!localStorage.getItem('dateFormat')) {
+ localStorage.setItem('dateFormat', 'MDY');
+ console.log('Error fetching preferences, setting localStorage default date format to MDY');
+ }
+ // Continue loading warranties even if preferences fail
}
+ */
+ // --- END REDUNDANT PREFERENCE FETCH ---
// Use the full URL to avoid path issues
const apiUrl = window.location.origin + '/api/warranties';
// Check if auth is available and user is authenticated
if (!window.auth || !window.auth.isAuthenticated()) {
- console.log('User not authenticated, showing empty state');
+ console.log('[DEBUG] Early return: User not authenticated');
renderEmptyState('Please log in to view your warranties.');
hideLoading();
return;
}
-
// Get the auth token
const token = window.auth.getToken();
if (!token) {
- console.log('No auth token available');
+ console.log('[DEBUG] Early return: No auth token available');
renderEmptyState('Authentication error. Please log in again.');
hideLoading();
return;
@@ -1017,22 +1264,23 @@ async function loadWarranties() {
console.log('Fetching warranties with auth token');
const response = await fetch(apiUrl, options);
-
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));
console.error('Error loading warranties:', response.status, errorData);
throw new Error(`Error loading warranties: ${errorData.message || response.status}`);
}
-
const data = await response.json();
- console.log('Received warranties from server:', data);
-
+ console.log('[DEBUG] Received warranties from server:', data);
+ if (!Array.isArray(data)) {
+ console.error('[DEBUG] API did not return an array! Data:', data);
+ }
// Process each warranty to calculate status and days remaining
- warranties = data.map(warranty => {
- return processWarrantyData(warranty);
- });
-
- console.log('Processed warranties:', warranties);
+ warranties = Array.isArray(data) ? data.map(warranty => {
+ const processed = processWarrantyData(warranty);
+ console.log('[DEBUG] Processed warranty:', processed);
+ return processed;
+ }) : [];
+ console.log('[DEBUG] Final warranties array:', warranties);
if (warranties.length === 0) {
console.log('No warranties found, showing empty state');
@@ -1043,10 +1291,10 @@ async function loadWarranties() {
// Populate tag filter dropdown with tags from warranties
populateTagFilter();
- applyFilters();
+ // REMOVED: applyFilters(); // Now called from authStateReady after data and prefs are loaded
}
} catch (error) {
- console.error('Error loading warranties:', error);
+ console.error('[DEBUG] Error loading warranties:', error);
renderEmptyState('Error loading warranties. Please try again later.');
} finally {
hideLoading();
@@ -1064,21 +1312,43 @@ function renderEmptyState(message = 'No warranties yet. Add your first warranty
}
function formatDate(date) {
- if (!date) return 'N/A';
-
- // If date is already a Date object, use it directly
- const dateObj = date instanceof Date ? date : new Date(date);
-
- // Check if date is valid
- if (isNaN(dateObj.getTime())) {
+ // Input 'date' should now be a Date object created by processWarrantyData (or null)
+ if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
return 'N/A';
}
-
- return dateObj.toLocaleDateString('en-US', {
- year: 'numeric',
- month: 'short',
- day: 'numeric'
- });
+
+ // Get the user's preferred format from localStorage, default to MDY
+ const formatPreference = localStorage.getItem('dateFormat') || 'MDY';
+
+ // Manually extract UTC components to avoid timezone discrepancies
+ const year = date.getUTCFullYear();
+ const monthIndex = date.getUTCMonth(); // 0-indexed for month names array
+ const day = date.getUTCDate();
+
+ // Padded numeric values
+ const monthPadded = (monthIndex + 1).toString().padStart(2, '0');
+ const dayPadded = day.toString().padStart(2, '0');
+
+ // Abbreviated month names
+ const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+ const monthAbbr = monthNames[monthIndex];
+
+ switch (formatPreference) {
+ case 'DMY':
+ return `${dayPadded}/${monthPadded}/${year}`;
+ case 'YMD':
+ return `${year}-${monthPadded}-${dayPadded}`;
+ case 'MDY_WORDS': // Added
+ return `${monthAbbr} ${day}, ${year}`;
+ case 'DMY_WORDS': // Added
+ return `${day} ${monthAbbr} ${year}`;
+ case 'YMD_WORDS': // Added
+ return `${year} ${monthAbbr} ${day}`;
+ case 'MDY':
+ default:
+ return `${monthPadded}/${dayPadded}/${year}`;
+ }
}
async function renderWarranties(warrantiesToRender) {
@@ -1188,6 +1458,7 @@ async function renderWarranties(warrantiesToRender) {
<div>Warranty: <span>${warrantyYearsText}</span></div>
<div>Expires: <span>${expirationDateText}</span></div>
${warranty.purchase_price ? `<div><span>Price: </span><span class="currency-symbol">${symbol}</span><span>${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
+ ${warranty.vendor ? `<div>Vendor: <span>${warranty.vendor}</span></div>` : ''}
${validSerialNumbers.length > 0 ? `
<div class="serial-numbers">
<strong>Serial Numbers:</strong>
@@ -1241,6 +1512,7 @@ async function renderWarranties(warrantiesToRender) {
<div>Warranty: <span>${warrantyYearsText}</span></div>
<div>Expires: <span>${expirationDateText}</span></div>
${warranty.purchase_price ? `<div><span>Price: </span><span class="currency-symbol">${symbol}</span><span>${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
+ ${warranty.vendor ? `<div>Vendor: <span>${warranty.vendor}</span></div>` : ''}
${validSerialNumbers.length > 0 ? `
<div class="serial-numbers">
<strong>Serial Numbers:</strong>
@@ -1374,6 +1646,18 @@ function filterWarranties() {
return true;
}
+ // Check vendor
+ if (warranty.vendor && warranty.vendor.toLowerCase().includes(searchTerm)) {
+ return true;
+ }
+
+ // Check if any serial number contains search term
+ if (warranty.serial_numbers && Array.isArray(warranty.serial_numbers)) {
+ if (warranty.serial_numbers.some(sn => sn && sn.toLowerCase().includes(searchTerm))) {
+ return true;
+ }
+ }
+
return false;
});
@@ -1417,8 +1701,13 @@ function applyFilters() {
warranty.tags.some(tag => tag.name.toLowerCase().includes(searchTerm));
// Check if notes contains search term
const notesMatch = warranty.notes && warranty.notes.toLowerCase().includes(searchTerm);
+ // Check if vendor contains search term
+ const vendorMatch = warranty.vendor && warranty.vendor.toLowerCase().includes(searchTerm);
+ // Check if any serial number contains search term
+ const serialNumberMatch = warranty.serial_numbers && Array.isArray(warranty.serial_numbers) &&
+ warranty.serial_numbers.some(sn => sn && sn.toLowerCase().includes(searchTerm));
// Return true if any match
- if (!productNameMatch && !tagMatch && !notesMatch) {
+ if (!productNameMatch && !tagMatch && !notesMatch && !vendorMatch && !serialNumberMatch) {
return false;
}
}
@@ -1441,6 +1730,7 @@ function openEditModal(warranty) {
document.getElementById('editPurchaseDate').value = warranty.purchase_date.split('T')[0];
document.getElementById('editWarrantyYears').value = warranty.warranty_years;
document.getElementById('editPurchasePrice').value = warranty.purchase_price || '';
+ document.getElementById('editVendor').value = warranty.vendor || '';
// Clear existing serial number inputs
const editSerialNumbersContainer = document.getElementById('editSerialNumbersContainer');
@@ -1798,7 +2088,9 @@ function submitForm(event) {
resetAddWarrantyWizard(); // Reset the wizard form
// --- End modification ---
- loadWarranties(); // Reload the list
+ loadWarranties().then(() => {
+ applyFilters();
+ }); // Reload the list and update UI
})
.catch(error => {
hideLoadingSpinner();
@@ -1816,8 +2108,8 @@ document.addEventListener('DOMContentLoaded', function() {
// Load warranties (might need checks if warrantiesList doesn't always exist)
if (warrantiesList) {
- loadWarranties();
- loadViewPreference(); // Load user's preferred view
+ // REMOVED: loadWarranties(); // Now called after authStateReady
+ // REMOVED: loadViewPreference(); // Now called after authStateReady
loadTags(); // Load tags for the form
initTagFunctionality(); // Initialize tag search/selection
}
@@ -1873,7 +2165,7 @@ document.addEventListener('DOMContentLoaded', function() {
// Load preferences (if needed for things other than theme)
// loadPreferences(); // Consider if needed
- updateCurrencySymbols();
+ // REMOVED: updateCurrencySymbols(); // Now called after authStateReady
});
// Add this function to handle edit tab functionality
@@ -2773,7 +3065,7 @@ function setupUIEventListeners() {
if (confirmDeleteBtn) confirmDeleteBtn.addEventListener('click', deleteWarranty);
// Load saved view preference
- loadViewPreference();
+ // loadViewPreference(); // Disabled: now called after authStateReady
}
// Function to show loading spinner
@@ -2821,7 +3113,16 @@ function deleteWarranty() {
hideLoadingSpinner();
showToast('Warranty deleted successfully', 'success');
closeModals();
- loadWarranties();
+
+ // --- BEGIN FIX: Update UI immediately ---
+ // Remove the deleted warranty from the global array
+ const deletedId = currentWarrantyId; // Store ID before resetting
+ warranties = warranties.filter(warranty => warranty.id !== deletedId);
+ currentWarrantyId = null; // Reset current ID
+
+ // Re-render the list using the updated local array
+ applyFilters();
+ // --- END FIX ---
})
.catch(error => {
hideLoadingSpinner();
@@ -2937,6 +3238,10 @@ function saveWarranty() {
formData.append('notes', '');
}
+ // Add vendor/retailer to form data
+ const editVendorInput = document.getElementById('editVendor'); // Use the correct ID
+ formData.append('vendor', editVendorInput ? editVendorInput.value.trim() : ''); // Use the correct variable
+
// Get auth token
const token = localStorage.getItem('auth_token');
if (!token) {
@@ -2966,44 +3271,15 @@ function saveWarranty() {
hideLoadingSpinner();
showToast('Warranty updated successfully', 'success');
closeModals();
- // 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();
- }
- }
+ // Instantly reload and re-render the warranties list
+ loadWarranties().then(() => {
+ applyFilters();
+ // Always close the notes modal if open, to ensure UI is in sync
+ const notesModal = document.getElementById('notesModal');
+ if (notesModal && notesModal.style.display === 'block') {
+ notesModal.style.display = 'none';
}
- }
- loadWarranties(); // Still reload to ensure all data is fresh
+ });
})
.catch(error => {
hideLoadingSpinner();
@@ -3272,7 +3548,14 @@ async function handleImport(file) {
await loadTags(); // Fetch the updated list of all tags
// ***** END FIX *****
- loadWarranties(); // Refresh the list
+ // Add a small delay to ensure backend has processed the data
+ await new Promise(resolve => setTimeout(resolve, 500));
+
+ // Await the warranties load to ensure UI is updated
+ await loadWarranties();
+
+ // Force a UI refresh by reapplying filters
+ applyFilters();
} else {
showToast(`Import failed: ${result.error || 'Unknown error'}`, 'error');
if (result.errors) {
@@ -3305,6 +3588,7 @@ window.addEventListener('storage', (event) => {
`${prefix}viewPreference`
];
+ // Check for view preference changes
if (viewKeys.includes(event.key) && event.newValue) {
console.log(`Storage event detected for view preference (${event.key}). New value: ${event.newValue}`);
// Check if the new value is different from the current view to avoid loops
@@ -3317,6 +3601,28 @@ window.addEventListener('storage', (event) => {
console.log('Storage event value matches current view, ignoring.');
}
}
+
+ // --- Added: Check for date format changes ---
+ if (event.key === 'dateFormat' && event.newValue) {
+ console.log(`Storage event detected for dateFormat. New value: ${event.newValue}`);
+ // Re-apply filters to re-render warranties with the new date format
+ if (warrantiesList) { // Only apply if the warranty list exists on the page
+ applyFilters();
+ showToast('Date format updated.', 'info'); // Optional: Notify user
+ }
+ }
+ // --- End Added Check ---
+
+ // --- Added: Check for currency symbol changes ---
+ if (event.key === `${prefix}currencySymbol` && event.newValue) {
+ console.log(`Storage event detected for ${prefix}currencySymbol. New value: ${event.newValue}`);
+ if (warrantiesList) { // Only apply if on the main page
+ updateCurrencySymbols(); // Update symbols outside cards (e.g., in forms if they exist)
+ applyFilters(); // Re-render cards to update symbols inside them
+ showToast('Currency symbol updated.', 'info'); // Optional: Notify user
+ }
+ }
+ // --- End Added Check ---
});
// --- End Storage Event Listener ---
@@ -3437,6 +3743,10 @@ function showNotesModal(notes, warrantyOrId = null) {
formData.append('notes', newNote); // Append the potentially empty, trimmed note
+ // Add vendor/retailer to form data
+ const editVendorOrRetailer = document.getElementById('editVendorOrRetailer');
+ formData.append('vendor', editVendorOrRetailer ? editVendorOrRetailer.value.trim() : '');
+
const response = await fetch(`/api/warranties/${notesModalWarrantyId}`, { // Added await and response handling
method: 'PUT',
headers: {
@@ -3473,8 +3783,10 @@ function showNotesModal(notes, warrantyOrId = null) {
}
// --- End Updated UI logic ---
- // Refresh warranties list to update the card UI state (e.g., show/hide notes link)
- loadWarranties();
+ // Refresh warranties list and THEN update UI
+ await loadWarranties(); // Wait for data refresh
+ applyFilters(); // Re-render the list with updated data
+
} catch (e) {
hideLoadingSpinner();
console.error("Error updating note:", e); // Log the error
@@ -3494,24 +3806,44 @@ function showNotesModal(notes, warrantyOrId = null) {
// Utility to get currency symbol from preferences/localStorage
function getCurrencySymbol() {
- const prefix = getPreferenceKeyPrefix();
- console.log(`[getCurrencySymbol] Using prefix: ${prefix}`); // Log prefix
+ // Use the global prefix determined after auth ready
+ let prefix = userPreferencePrefix; // Use let to allow default override
+ if (!prefix) {
+ console.warn('[getCurrencySymbol] User preference prefix not set yet, defaulting prefix to user_');
+ prefix = 'user_'; // Default prefix if called too early
+ }
+ console.log(`[getCurrencySymbol] Using determined prefix: ${prefix}`);
let symbol = '$'; // Default value
+
+ const rawValue = localStorage.getItem(`${prefix}currencySymbol`);
+ console.log(`[getCurrencySymbol Debug] Raw value read from localStorage key '${prefix}currencySymbol':`, rawValue);
+ // +++ END ADDED LOG +++
+
+ // --- Priority 1: Load from individual key --- (Saved by settings-new.js)
+ const individualSymbol = rawValue; // Use the already read value
+ if (individualSymbol) { // Check uses the already read value
+ symbol = individualSymbol;
+ console.log(`[getCurrencySymbol] Loaded symbol from individual key (${prefix}currencySymbol): ${symbol}`);
+ return symbol;
+ }
+
+ // --- Priority 2: Load from preferences object (Legacy/Fallback) ---
try {
const prefsString = localStorage.getItem(`${prefix}preferences`);
- console.log(`[getCurrencySymbol] Read prefsString for ${prefix}preferences:`, prefsString); // Log raw string
+ console.log(`[getCurrencySymbol] Read prefsString for ${prefix}preferences:`, prefsString);
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;
+ console.log(`[getCurrencySymbol] Loaded symbol from object key (${prefix}preferences): ${symbol}`);
}
}
} catch (e) {
console.error(`Error reading ${prefix}preferences from localStorage:`, e);
- // Keep the default '$' symbol in case of error
+ // Keep the default '$' symbol in case of error parsing the object
}
- console.log(`[getCurrencySymbol] Returning symbol: ${symbol}`); // Log final symbol
+
+ console.log(`[getCurrencySymbol] Returning symbol (default or from object): ${symbol}`);
return symbol;
}
@@ -3534,4 +3866,84 @@ window.addEventListener('storage', function(e) {
console.log(`Storage event detected for ${prefix}preferences. Updating currency symbols.`);
updateCurrencySymbols();
}
-});
\ No newline at end of file
+});
+
+// +++ NEW FUNCTION TO LOAD PREFS AND SAVE TO LOCALSTORAGE +++
+async function loadAndApplyUserPreferences() {
+ // Use the global prefix determined after auth ready
+ let prefix = userPreferencePrefix; // <<< CHANGED const to let
+ if (!prefix) {
+ console.error('[Prefs Loader] Cannot load preferences: User preference prefix not set yet. Defaulting to user_');
+ // Setting a default might be risky if the user *is* admin but prefix wasn't set in time.
+ // Consider how authStateReady ensures prefix is set before this runs.
+ // For now, let's try defaulting, but this might need review.
+ prefix = 'user_';
+ }
+ console.log(`[Prefs Loader] Attempting to load preferences using prefix: ${prefix}`);
+
+ if (window.auth && window.auth.isAuthenticated()) {
+ const token = window.auth.getToken();
+ if (!token) {
+ console.error('[Prefs Loader] Cannot load preferences: No auth token found.');
+ return; // Exit if no token
+ }
+
+ try {
+ const response = await fetch('/api/auth/preferences', {
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ });
+
+ if (response.ok) {
+ const apiPrefs = await response.json();
+ console.log('[Prefs Loader] Preferences loaded from API:', apiPrefs);
+
+ // Save relevant prefs to localStorage
+ if (apiPrefs.currency_symbol) {
+ localStorage.setItem(`${prefix}currencySymbol`, apiPrefs.currency_symbol);
+ console.log(`[Prefs Loader] Saved ${prefix}currencySymbol: ${apiPrefs.currency_symbol}`);
+ }
+ if (apiPrefs.default_view) {
+ localStorage.setItem(`${prefix}defaultView`, apiPrefs.default_view);
+ console.log(`[Prefs Loader] Saved ${prefix}defaultView: ${apiPrefs.default_view}`);
+ }
+ if (apiPrefs.expiring_soon_days !== undefined) {
+ localStorage.setItem(`${prefix}expiringSoonDays`, apiPrefs.expiring_soon_days);
+ // Also update the global variable used by processWarrantyData
+ expiringSoonDays = apiPrefs.expiring_soon_days;
+ console.log(`[Prefs Loader] Saved ${prefix}expiringSoonDays: ${apiPrefs.expiring_soon_days}`);
+ console.log(`[Prefs Loader] Updated global expiringSoonDays variable to: ${expiringSoonDays}`);
+ }
+ if (apiPrefs.date_format) {
+ localStorage.setItem('dateFormat', apiPrefs.date_format);
+ console.log(`[Prefs Loader] Saved dateFormat: ${apiPrefs.date_format}`);
+ }
+
+ // Optionally trigger immediate UI updates if needed, although renderWarranties will use these new values
+ // updateCurrencySymbols();
+
+ } else {
+ const errorData = await response.json().catch(() => ({}));
+ console.warn(`[Prefs Loader] Failed to load preferences from API: ${response.status}`, errorData.message || '');
+ // Set defaults in localStorage maybe?
+ if (!localStorage.getItem('dateFormat')) localStorage.setItem('dateFormat', 'MDY');
+ if (!localStorage.getItem(`${prefix}currencySymbol`)) localStorage.setItem(`${prefix}currencySymbol`, '$');
+ // etc.
+ }
+ } catch (error) {
+ console.error('[Prefs Loader] Error fetching/applying preferences from API:', error);
+ // Set defaults in localStorage on error?
+ if (!localStorage.getItem('dateFormat')) localStorage.setItem('dateFormat', 'MDY');
+ if (!localStorage.getItem(`${prefix}currencySymbol`)) localStorage.setItem(`${prefix}currencySymbol`, '$');
+ // etc.
+ }
+ } else {
+ console.warn('[Prefs Loader] Cannot load preferences: User not authenticated or auth module not available.');
+ // Apply defaults if not authenticated?
+ if (!localStorage.getItem('dateFormat')) localStorage.setItem('dateFormat', 'MDY');
+ if (!localStorage.getItem(`${prefix}currencySymbol`)) localStorage.setItem(`${prefix}currencySymbol`, '$');
+ // etc.
+ }
+}
+// +++ END NEW FUNCTION +++
diff --git a/frontend/settings-new.html b/frontend/settings-new.html
index 15805ad..2747295 100644
--- a/frontend/settings-new.html
+++ b/frontend/settings-new.html
@@ -14,6 +14,8 @@
<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">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
+ <link rel="manifest" href="manifest.json">
<!-- Load the main site styles first -->
<link rel="stylesheet" href="style.css">
<!-- Font Awesome for icons -->
@@ -236,6 +238,23 @@
<input type="number" id="expiringSoonDays" class="form-control" min="1" max="365" value="30">
</div>
</div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label for="dateFormat">Date Format</label>
+ <p class="text-muted">Choose how dates are displayed</p>
+ </div>
+ <select id="dateFormat" class="form-control">
+ <option value="MDY">Month/Day/Year (e.g., 12/31/2024)</option>
+ <option value="DMY">Day/Month/Year (e.g., 31/12/2024)</option>
+ <option value="YMD">Year-Month-Day (e.g., 2024-12-31)</option>
+ <option value="MDY_WORDS">Mon Day, Year (e.g., Dec 31, 2024)</option>
+ <option value="DMY_WORDS">Day Mon Year (e.g., 31 Dec 2024)</option>
+ <option value="YMD_WORDS">Year Mon Day (e.g., 2024 Dec 31)</option>
+ </select>
+ </div>
+ </div>
<button type="button" id="savePreferencesBtn" class="btn btn-primary">Save Preferences</button>
</form>
diff --git a/frontend/settings-new.js b/frontend/settings-new.js
index a69d12e..440684d 100644
--- a/frontend/settings-new.js
+++ b/frontend/settings-new.js
@@ -47,6 +47,9 @@ const currencySymbolInput = document.getElementById('currencySymbol');
const currencySymbolSelect = document.getElementById('currencySymbolSelect');
const currencySymbolCustom = document.getElementById('currencySymbolCustom');
+// Add dateFormatSelect near other DOM element declarations if not already there
+const dateFormatSelect = document.getElementById('dateFormat');
+
/**
* Set theme (dark/light) - Unified and persistent
* @param {boolean} isDark - Whether to use dark mode
@@ -64,10 +67,10 @@ function setTheme(isDark) {
localStorage.setItem('darkMode', isDark);
// Sync both toggles if present
if (typeof darkModeToggle !== 'undefined' && darkModeToggle) {
- darkModeToggle.checked = isDarkMode;
+ darkModeToggle.checked = isDark;
}
if (typeof darkModeToggleSetting !== 'undefined' && darkModeToggleSetting) {
- darkModeToggleSetting.checked = isDarkMode;
+ darkModeToggleSetting.checked = isDark;
}
// Also update user_preferences.theme for backward compatibility
try {
@@ -87,23 +90,46 @@ function setTheme(isDark) {
* Initialize dark mode toggle and synchronize state
*/
function initDarkModeToggle() {
- // Always check the single source of truth in localStorage
+ // Always check the single source of truth in localStorage (fallback)
const isDarkMode = localStorage.getItem('darkMode') === 'true';
// Apply theme to DOM if not already set
document.documentElement.setAttribute('data-theme', isDarkMode ? 'dark' : 'light');
document.body.classList.toggle('dark-mode', isDarkMode);
- // Sync both toggles
+ // Sync both toggles and add unified handler
+ const syncToggles = (val) => {
+ if (typeof darkModeToggle !== 'undefined' && darkModeToggle) darkModeToggle.checked = val;
+ if (typeof darkModeToggleSetting !== 'undefined' && darkModeToggleSetting) darkModeToggleSetting.checked = val;
+ };
+ syncToggles(isDarkMode);
+ // Handler to update theme, localStorage, backend
+ const handleToggle = async function(checked) {
+ setTheme(checked);
+ syncToggles(checked);
+ // Save to backend if authenticated
+ if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
+ try {
+ let prefs = {};
+ const storedPrefs = localStorage.getItem('user_preferences');
+ if (storedPrefs) prefs = JSON.parse(storedPrefs);
+ prefs.theme = checked ? 'dark' : 'light';
+ await fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(prefs)
+ });
+ } catch (e) {
+ console.warn('Failed to save dark mode to backend:', e);
+ }
+ }
+ };
if (typeof darkModeToggle !== 'undefined' && darkModeToggle) {
- darkModeToggle.checked = isDarkMode;
- darkModeToggle.addEventListener('change', function() {
- setTheme(this.checked);
- });
+ darkModeToggle.onchange = function() { handleToggle(this.checked); };
}
if (typeof darkModeToggleSetting !== 'undefined' && darkModeToggleSetting) {
- darkModeToggleSetting.checked = isDarkMode;
- darkModeToggleSetting.addEventListener('change', function() {
- setTheme(this.checked);
- });
+ darkModeToggleSetting.onchange = function() { handleToggle(this.checked); };
}
}
@@ -126,6 +152,12 @@ document.addEventListener('DOMContentLoaded', function() {
// Initialize dark mode toggle
initDarkModeToggle();
+ // Clear dark mode preference on logout for privacy
+ if (window.auth && window.auth.onLogout) {
+ window.auth.onLogout(() => {
+ localStorage.removeItem('darkMode');
+ });
+ }
// REMOVED initSettingsMenu() call - Handled by auth.js
@@ -361,22 +393,34 @@ async function loadUserData() {
}
}
- // Update localStorage
+ // Update localStorage ONLY if data has changed
const currentUser = window.auth.getCurrentUser();
let first_name = userData.first_name;
let last_name = userData.last_name;
- if (!last_name) first_name = '';
+ if (!last_name) first_name = ''; // Reset first name if last name is empty
+
const updatedUser = {
- ...(currentUser || {}), // Handle case where currentUser might be null
- first_name,
- last_name,
- // Ensure email and username are preserved if they existed
+ ...(currentUser || {}), // Preserve existing fields
+ first_name, // Update first name
+ last_name, // Update last name
+ // Preserve other essential fields from fetched data if currentUser was null
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));
+
+ // Convert both to JSON strings for reliable comparison
+ const currentUserString = JSON.stringify(currentUser);
+ const updatedUserString = JSON.stringify(updatedUser);
+
+ if (currentUserString !== updatedUserString) {
+ console.log('User data changed, updating localStorage.');
+ localStorage.setItem('user_info', updatedUserString);
+ } else {
+ console.log('User data from API matches localStorage, skipping update.');
+ }
+ // localStorage.setItem('user_info', JSON.stringify(updatedUser)); // OLD LINE
} else {
const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
console.warn('API error fetching user data:', errorData.message);
@@ -425,198 +469,194 @@ function getPreferenceKeyPrefix() {
/**
* Load user preferences
*/
-function loadPreferences() {
+async function loadPreferences() {
console.log('Loading preferences...');
- showLoading();
-
- // Get the appropriate key prefix based on user type
const prefix = getPreferenceKeyPrefix();
- console.log(`Loading preferences with prefix: ${prefix}`);
-
- // First check if we're in dark mode by checking the body class
- const isDarkMode = document.body.classList.contains('dark-mode');
-
- // Set the toggle state based on the current theme
- if (darkModeToggle) {
- darkModeToggle.checked = isDarkMode;
+ console.log('Loading preferences with prefix:', prefix);
+
+ let darkModeFromAPI = null;
+ let apiPrefs = null;
+ // Try to load preferences from backend if authenticated
+ if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
+ try {
+ const response = await fetch('/api/auth/preferences', {
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ });
+ if (response.ok) {
+ apiPrefs = await response.json();
+ if (apiPrefs && apiPrefs.theme) {
+ darkModeFromAPI = apiPrefs.theme === 'dark';
+ setTheme(darkModeFromAPI);
+ // Sync localStorage
+ localStorage.setItem('darkMode', darkModeFromAPI);
+ }
+ }
+ } catch (e) {
+ console.warn('Failed to load preferences from backend:', e);
+ }
}
-
- if (darkModeToggleSetting) {
- darkModeToggleSetting.checked = isDarkMode;
- }
-
- // --- BEGIN EDIT: Load Default View with Priority ---
- let defaultViewLoaded = false;
- if (defaultViewSelect) {
- const userSpecificView = localStorage.getItem(`${prefix}defaultView`);
- const generalView = localStorage.getItem('viewPreference');
- const legacyWarrantyView = localStorage.getItem(`${prefix}warrantyView`); // Check legacy key
-
- if (userSpecificView) {
- defaultViewSelect.value = userSpecificView;
- defaultViewLoaded = true;
- console.log(`Loaded default view from ${prefix}defaultView:`, userSpecificView);
- } else if (generalView) {
- defaultViewSelect.value = generalView;
- defaultViewLoaded = true;
- console.log('Loaded default view from viewPreference:', generalView);
- } else if (legacyWarrantyView) {
- defaultViewSelect.value = legacyWarrantyView;
- defaultViewLoaded = true;
- console.log(`Loaded default view from legacy ${prefix}warrantyView:`, legacyWarrantyView);
+ // Fallback: use localStorage if not authenticated or API fails
+ if (darkModeFromAPI === null) {
+ const storedDarkMode = localStorage.getItem('darkMode') === 'true';
+ setTheme(storedDarkMode);
+ }
+ // --- Load Date Format --- Add this section
+ const storedDateFormat = localStorage.getItem('dateFormat');
+ if (storedDateFormat && dateFormatSelect) {
+ dateFormatSelect.value = storedDateFormat;
+ console.log(`Loaded dateFormat from localStorage: ${storedDateFormat}`);
+ } else if (dateFormatSelect) {
+ dateFormatSelect.value = 'MDY'; // Default if not found
+ console.log('dateFormat not found in localStorage, defaulting to MDY');
+ }
+ // --- End Date Format Section ---
+
+ // Default View
+ const storedView = localStorage.getItem(`${prefix}defaultView`);
+ if (storedView && defaultViewSelect) {
+ defaultViewSelect.value = storedView;
+ console.log(`Loaded default view from ${prefix}defaultView: ${storedView}`);
+ } else if (defaultViewSelect) {
+ defaultViewSelect.value = 'grid'; // Default
+ console.log(`${prefix}defaultView not found, defaulting view to grid`);
+ }
+
+ // Currency Symbol
+ const storedCurrency = localStorage.getItem(`${prefix}currencySymbol`);
+ if (storedCurrency) {
+ if (currencySymbolSelect) {
+ // Check if the stored symbol is a standard option
+ const standardOption = Array.from(currencySymbolSelect.options).find(opt => opt.value === storedCurrency);
+ if (standardOption) {
+ currencySymbolSelect.value = storedCurrency;
+ if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
+ } else {
+ // It's a custom symbol
+ currencySymbolSelect.value = 'other';
+ if (currencySymbolCustom) {
+ currencySymbolCustom.value = storedCurrency;
+ currencySymbolCustom.style.display = 'inline-block';
+ }
+ }
+ console.log(`Loaded currency symbol from ${prefix}currencySymbol: ${storedCurrency}`);
}
+ } else {
+ // Default to '$' if nothing stored
+ if (currencySymbolSelect) currencySymbolSelect.value = '$';
+ if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
+ console.log(`${prefix}currencySymbol not found, defaulting to $`);
+ }
+
+ // Expiring Soon Days
+ const storedExpiringDays = localStorage.getItem(`${prefix}expiringSoonDays`);
+ if (storedExpiringDays && expiringSoonDaysInput) {
+ expiringSoonDaysInput.value = storedExpiringDays;
+ console.log(`Loaded expiring soon days from ${prefix}expiringSoonDays: ${storedExpiringDays}`);
+ } else if (expiringSoonDaysInput) {
+ expiringSoonDaysInput.value = 30; // Default
+ console.log(`${prefix}expiringSoonDays not found, defaulting to 30`);
}
- // --- END EDIT ---
- // Load other preferences from localStorage using the appropriate prefix (only if default view not loaded yet)
- if (!defaultViewLoaded) {
+ // Now, try fetching preferences from API to override/confirm
+ if (window.auth && window.auth.isAuthenticated()) {
try {
- const userPrefs = localStorage.getItem(`${prefix}preferences`);
- if (userPrefs) {
- const preferences = JSON.parse(userPrefs);
-
- // Default view preference (load only if not loaded above)
- if (defaultViewSelect && preferences.default_view && !defaultViewLoaded) {
- defaultViewSelect.value = preferences.default_view;
- defaultViewLoaded = true; // Mark as loaded
- console.log(`Loaded default view from ${prefix}preferences object:`, preferences.default_view);
+ const token = window.auth.getToken();
+ const response = await fetch('/api/auth/preferences', {
+ headers: {
+ 'Authorization': `Bearer ${token}`
}
+ });
- // Email notifications preference
- if (emailNotificationsToggle && typeof preferences.email_notifications !== 'undefined') { // Check for undefined
- emailNotificationsToggle.checked = preferences.email_notifications;
+ if (response.ok) {
+ const apiPrefs = await response.json();
+ console.log('Preferences loaded from API:', apiPrefs);
+
+ // Update UI elements with API data where available
+ if (apiPrefs.default_view && defaultViewSelect) {
+ // Only update if different from localStorage value (or if localStorage was empty)
+ const storedView = localStorage.getItem(`${prefix}defaultView`) || 'grid'; // Default if null
+ if (apiPrefs.default_view !== storedView) {
+ console.log(`API default_view (${apiPrefs.default_view}) differs from localStorage (${storedView}). Updating UI.`);
+ defaultViewSelect.value = apiPrefs.default_view;
+ }
}
-
- // Expiring soon days preference
- if (expiringSoonDaysInput && preferences.expiring_soon_days) {
- expiringSoonDaysInput.value = preferences.expiring_soon_days;
+ // --- MODIFIED CURRENCY SYMBOL HANDLING ---
+ const storedCurrency = localStorage.getItem(`${prefix}currencySymbol`); // Get localStorage value again for comparison
+ if (apiPrefs.currency_symbol && currencySymbolSelect) {
+ // Only update UI from API if the API value is different from what was in localStorage
+ // Or if localStorage didn't have a value initially
+ if (!storedCurrency || apiPrefs.currency_symbol !== storedCurrency) {
+ console.log(`API currency_symbol (${apiPrefs.currency_symbol}) differs from localStorage (${storedCurrency}). Updating UI.`);
+ // Logic to handle standard vs custom symbol from API
+ const standardOption = Array.from(currencySymbolSelect.options).find(opt => opt.value === apiPrefs.currency_symbol);
+ if (standardOption) {
+ currencySymbolSelect.value = apiPrefs.currency_symbol;
+ if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
+ } else {
+ currencySymbolSelect.value = 'other';
+ if (currencySymbolCustom) {
+ currencySymbolCustom.value = apiPrefs.currency_symbol;
+ currencySymbolCustom.style.display = 'inline-block';
+ }
+ }
+ } else {
+ console.log(`API currency_symbol (${apiPrefs.currency_symbol}) matches localStorage (${storedCurrency}). Skipping UI update.`);
+ }
}
-
- // Notification frequency preference
- if (notificationFrequencySelect && preferences.notification_frequency) {
- notificationFrequencySelect.value = preferences.notification_frequency;
+ // --- END MODIFIED CURRENCY SYMBOL HANDLING ---
+ if (apiPrefs.expiring_soon_days && expiringSoonDaysInput) {
+ // Only update if different from localStorage value (or if localStorage was empty)
+ const storedExpiringDays = localStorage.getItem(`${prefix}expiringSoonDays`) || '30'; // Default if null
+ if (String(apiPrefs.expiring_soon_days) !== storedExpiringDays) {
+ console.log(`API expiring_soon_days (${apiPrefs.expiring_soon_days}) differs from localStorage (${storedExpiringDays}). Updating UI.`);
+ expiringSoonDaysInput.value = apiPrefs.expiring_soon_days;
+ }
}
- // Notification time preference
- if (notificationTimeInput && preferences.notification_time) {
- notificationTimeInput.value = preferences.notification_time;
- }
+ // --- Update Date Format from API Prefs --- Add this check
+ const storedDateFormat = localStorage.getItem('dateFormat') || 'MDY'; // Default if null
+ if (apiPrefs.date_format && dateFormatSelect) {
+ if (apiPrefs.date_format !== storedDateFormat) {
+ console.log(`API date_format (${apiPrefs.date_format}) differs from localStorage (${storedDateFormat}). Updating UI.`);
+ dateFormatSelect.value = apiPrefs.date_format;
+ }
+ }
+ // --- End Date Format Check ---
- // Timezone preference
- if (timezoneSelect && preferences.timezone) {
- timezoneSelect.value = preferences.timezone;
+ // Update Email Settings from API
+ if (emailNotificationsToggle) {
+ emailNotificationsToggle.checked = apiPrefs.email_notifications !== false; // Default true if null/undefined
}
-
- // Currency symbol preference
- let symbol = '$';
- if (preferences && preferences.currency_symbol) {
- symbol = preferences.currency_symbol;
+ if (notificationFrequencySelect && apiPrefs.notification_frequency) {
+ notificationFrequencySelect.value = apiPrefs.notification_frequency;
}
- 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 = '';
+ if (notificationTimeInput && apiPrefs.notification_time) {
+ notificationTimeInput.value = apiPrefs.notification_time.substring(0, 5); // HH:MM format
+ }
+ // Load and set timezone from API
+ if (timezoneSelect && apiPrefs.timezone) {
+ console.log('API provided timezone:', apiPrefs.timezone);
+ // Ensure the option exists before setting
+ if (Array.from(timezoneSelect.options).some(option => option.value === apiPrefs.timezone)) {
+ timezoneSelect.value = apiPrefs.timezone;
+ console.log('Applied timezone from API:', timezoneSelect.value, 'Current select value:', timezoneSelect.value);
} else {
- currencySymbolSelect.value = 'other';
- currencySymbolCustom.style.display = '';
- currencySymbolCustom.value = symbol;
+ console.warn(`Timezone '${apiPrefs.timezone}' from API not found in dropdown.`);
}
+ } else {
+ console.log('No timezone preference found in API or timezone select element missing.');
}
- }
- } 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)
- fetch('/api/auth/preferences', {
- method: 'GET',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- }
- })
- .then(response => {
- if (!response.ok) {
- throw new Error('Failed to load preferences from API');
- }
- return response.json();
- })
- .then(data => {
- console.log('Preferences loaded from API:', data);
-
- // API returns preferences directly, not nested under a 'preferences' key
- const apiPrefs = data;
-
- // Update UI with API preferences
- // Default View: Only update if not already loaded from higher priority localStorage keys
- if (defaultViewSelect && apiPrefs.default_view && !defaultViewLoaded) {
- defaultViewSelect.value = apiPrefs.default_view;
- console.log('Loaded default view from API:', apiPrefs.default_view);
- }
-
- // Other preferences always updated from API if available
- if (emailNotificationsToggle && typeof apiPrefs.email_notifications !== 'undefined') { // Check for undefined
- emailNotificationsToggle.checked = apiPrefs.email_notifications;
- }
-
- if (expiringSoonDaysInput && apiPrefs.expiring_soon_days) {
- expiringSoonDaysInput.value = apiPrefs.expiring_soon_days;
- }
-
- if (notificationFrequencySelect && apiPrefs.notification_frequency) {
- notificationFrequencySelect.value = apiPrefs.notification_frequency;
- }
-
- if (notificationTimeInput && apiPrefs.notification_time) {
- notificationTimeInput.value = apiPrefs.notification_time;
- }
-
- if (timezoneSelect && apiPrefs.timezone) {
- console.log('API provided timezone:', apiPrefs.timezone);
- // Will be populated once timezones are loaded
- setTimeout(() => {
- if (timezoneSelect.options.length > 1) {
- timezoneSelect.value = apiPrefs.timezone;
- console.log('Applied timezone from API:', apiPrefs.timezone, 'Current select value:', timezoneSelect.value);
- }
- }, 500);
- }
-
- // 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;
+ const errorData = await response.json().catch(() => ({}));
+ console.warn(`Failed to load preferences from API: ${response.status}`, errorData.message || '');
}
+ } catch (error) {
+ console.error('Error fetching preferences from API:', error);
}
-
- // Store in localStorage with the appropriate prefix
- localStorage.setItem(`${prefix}preferences`, JSON.stringify(apiPrefs));
- })
- .catch(error => {
- console.error('Error loading preferences from API:', error);
- })
- .finally(() => {
- hideLoading();
- });
+ }
}
/**
@@ -945,109 +985,80 @@ async function saveProfile() {
/**
* Save user preferences
*/
-function savePreferences() {
- showLoading();
-
- try {
- // Get the appropriate key prefix based on user type
- const prefix = getPreferenceKeyPrefix();
- console.log(`Saving preferences with prefix: ${prefix}`);
-
- // Get values
- const isDarkMode = darkModeToggleSetting.checked;
- const defaultView = defaultViewSelect.value;
- const emailNotifications = emailNotificationsToggle.checked;
- const expiringSoonDays = parseInt(expiringSoonDaysInput.value);
- const notificationFrequency = notificationFrequencySelect.value;
- const notificationTime = notificationTimeInput.value;
- const timezone = timezoneSelect.value;
- let currencySymbol = '$';
- if (currencySymbolSelect && currencySymbolSelect.value === 'other') {
- currencySymbol = currencySymbolCustom && currencySymbolCustom.value ? currencySymbolCustom.value : '$';
- } else if (currencySymbolSelect) {
+async function savePreferences() {
+ console.log('Saving preferences...');
+ const prefix = getPreferenceKeyPrefix();
+
+ // --- Prepare data to save --- Add dateFormat and dark mode
+ const preferencesToSave = {
+ default_view: defaultViewSelect ? defaultViewSelect.value : 'grid',
+ expiring_soon_days: expiringSoonDaysInput ? parseInt(expiringSoonDaysInput.value) : 30,
+ date_format: dateFormatSelect ? dateFormatSelect.value : 'MDY',
+ theme: (localStorage.getItem('darkMode') === 'true') ? 'dark' : 'light',
+ };
+
+ // Handle currency symbol (standard or custom)
+ let currencySymbol = '$'; // Default
+ if (currencySymbolSelect) {
+ if (currencySymbolSelect.value === 'other' && currencySymbolCustom) {
+ currencySymbol = currencySymbolCustom.value.trim() || '$'; // Use custom or default to $ if empty
+ } else {
currencySymbol = currencySymbolSelect.value;
}
-
- // Validate inputs
- if (isNaN(expiringSoonDays) || expiringSoonDays < 1 || expiringSoonDays > 365) {
- showToast('Expiring soon days must be between 1 and 365', 'error');
- hideLoading();
- return;
- }
-
- if (!timezone) {
- showToast('Please select a timezone', 'error');
+ }
+ preferencesToSave.currency_symbol = currencySymbol;
+ // --- End data preparation ---
+
+ // +++ ADDED DEBUG LOGGING +++
+ console.log(`[SavePrefs Debug] Currency Select Value: ${currencySymbolSelect ? currencySymbolSelect.value : 'N/A'}`);
+ console.log(`[SavePrefs Debug] Custom Input Value: ${currencySymbolCustom ? currencySymbolCustom.value : 'N/A'}`);
+ console.log(`[SavePrefs Debug] Final currencySymbol value determined: ${currencySymbol}`);
+ // +++ END DEBUG LOGGING +++
+
+ // Save Dark Mode separately (using the single source of truth)
+ const isDark = darkModeToggleSetting ? darkModeToggleSetting.checked : false;
+ setTheme(isDark);
+ console.log(`Saved dark mode: ${isDark}`);
+
+ // Save simple preferences to localStorage immediately
+ localStorage.setItem('dateFormat', preferencesToSave.date_format); // Added
+ localStorage.setItem(`${prefix}defaultView`, preferencesToSave.default_view);
+ localStorage.setItem(`${prefix}currencySymbol`, preferencesToSave.currency_symbol);
+ localStorage.setItem(`${prefix}expiringSoonDays`, preferencesToSave.expiring_soon_days);
+
+ console.log('Preferences saved to localStorage (prefix:', prefix, '):', preferencesToSave);
+ console.log(`Value of dateFormat in localStorage: ${localStorage.getItem('dateFormat')}`);
+
+ // Try saving to API
+ if (window.auth && window.auth.isAuthenticated()) {
+ try {
+ showLoading();
+ const token = window.auth.getToken();
+ const response = await fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(preferencesToSave)
+ });
+
hideLoading();
- return;
- }
-
- // Create preferences object
- const preferences = {
- theme: isDarkMode ? 'dark' : 'light',
- default_view: defaultView,
- email_notifications: emailNotifications,
- expiring_soon_days: expiringSoonDays,
- notification_frequency: notificationFrequency,
- notification_time: notificationTime,
- timezone: timezone,
- currency_symbol: currencySymbol
- };
-
- // Save to API
- fetch('/api/auth/preferences', {
- method: 'PUT',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(preferences)
- })
- .then(response => {
- if (!response.ok) {
- throw new Error('Failed to save preferences');
+ if (response.ok) {
+ showToast('Preferences saved successfully.', 'success');
+ console.log('Preferences successfully saved to API.');
+ } else {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.message || `Failed to save preferences to API: ${response.status}`);
}
- return response.json();
- })
- .then(data => {
- // Save to localStorage with the appropriate prefix
- localStorage.setItem(`${prefix}preferences`, JSON.stringify(data));
-
- // Also save individual preferences for backward compatibility and general preference
- localStorage.setItem(`${prefix}defaultView`, defaultView);
- localStorage.setItem(`${prefix}warrantyView`, defaultView); // Keep saving legacy key for now
- localStorage.setItem(`${prefix}emailNotifications`, emailNotifications);
- localStorage.setItem('viewPreference', defaultView); // --- EDIT: Save general key ---
-
- // Save the dark mode setting for the current user type
- localStorage.setItem(`${prefix}darkMode`, isDarkMode);
-
- // Apply theme immediately
- document.body.classList.toggle('dark-mode', isDarkMode);
-
- showToast('Preferences saved successfully', 'success');
- })
- .catch(error => {
- console.error('Error saving preferences:', error);
- showToast('Error saving preferences', 'error');
-
- // Save to localStorage as fallback with the appropriate prefix
- localStorage.setItem(`${prefix}theme`, isDarkMode ? 'dark' : 'light');
- localStorage.setItem(`${prefix}defaultView`, defaultView);
- localStorage.setItem(`${prefix}warrantyView`, defaultView); // Keep saving legacy key for now
- localStorage.setItem(`${prefix}emailNotifications`, emailNotifications);
- localStorage.setItem(`${prefix}darkMode`, isDarkMode);
- localStorage.setItem('viewPreference', defaultView); // --- EDIT: Save general key ---
-
- // Apply theme even if API save fails
- document.body.classList.toggle('dark-mode', isDarkMode);
- })
- .finally(() => {
+ } catch (error) {
hideLoading();
- });
- } catch (error) {
- console.error('Error in savePreferences:', error);
- showToast('Error saving preferences', 'error');
- hideLoading();
+ console.error('Error saving preferences to API:', error);
+ showToast(`Preferences saved locally, but failed to sync with server: ${error.message}`, 'warning');
+ }
+ } else {
+ // No auth, just show local save success
+ showToast('Preferences saved locally.', 'success');
}
}
@@ -2910,31 +2921,80 @@ function saveEmailSettings() {
// --- Add Storage Event Listener for Real-time Sync ---
window.addEventListener('storage', (event) => {
+ console.log(`[Settings Storage Listener] Event received: key=${event.key}, newValue=${event.newValue}`); // Log all events
+
const prefix = getPreferenceKeyPrefix();
- const viewKeys = [
- `${prefix}defaultView`,
- 'viewPreference',
- `${prefix}warrantyView`,
- // Add `${prefix}viewPreference` if still used/relevant
- `${prefix}viewPreference`
- ];
-
- if (viewKeys.includes(event.key) && event.newValue) {
- console.log(`Storage event detected for view preference (${event.key}) in settings. New value: ${event.newValue}`);
- // Ensure the dropdown element exists and the value is different
- if (defaultViewSelect && defaultViewSelect.value !== event.newValue) {
- // Check if the new value is a valid option in the select
+ const targetKey = `${prefix}defaultView`;
+
+ // Only react to changes in the specific default view key for the current user type
+ if (event.key === targetKey) { // Check key match first
+ console.log(`[Settings Storage Listener] Matched key: ${targetKey}`);
+ console.log(`[Settings Storage Listener] defaultViewSelect exists: ${!!defaultViewSelect}`);
+ if (defaultViewSelect) {
+ console.log(`[Settings Storage Listener] Current dropdown value: ${defaultViewSelect.value}`);
+ }
+ console.log(`[Settings Storage Listener] Event newValue: ${event.newValue}`);
+
+ if (event.newValue && defaultViewSelect && defaultViewSelect.value !== event.newValue) {
+ console.log(`[Settings Storage Listener] Value changed and dropdown exists. Checking options...`);
const optionExists = [...defaultViewSelect.options].some(option => option.value === event.newValue);
+ console.log(`[Settings Storage Listener] Option ${event.newValue} exists: ${optionExists}`);
if (optionExists) {
defaultViewSelect.value = event.newValue;
- console.log('Updated settings default view dropdown.');
+ console.log(`[Settings Storage Listener] SUCCESS: Updated settings default view dropdown via storage event to ${event.newValue}.`);
} else {
- console.warn(`Storage event value (${event.newValue}) not found in dropdown options.`);
+ console.warn(`[Settings Storage Listener] Storage event value (${event.newValue}) not found in dropdown options.`);
}
- } else if (defaultViewSelect) {
- console.log('Storage event value matches current dropdown selection, ignoring.');
+ } else if (!event.newValue) {
+ console.log(`[Settings Storage Listener] Ignoring event for ${targetKey} because newValue is null/empty.`);
+ } else if (!defaultViewSelect) {
+ console.log(`[Settings Storage Listener] Ignoring event for ${targetKey} because defaultViewSelect element not found.`);
+ } else {
+ console.log(`[Settings Storage Listener] Ignoring event for ${targetKey} because value hasn't changed (${defaultViewSelect.value} === ${event.newValue}).`);
}
}
+
+ // Add similar checks for other preferences if needed, e.g., dateFormat, currencySymbol
+ if (event.key === 'dateFormat') { // Simplified log for other keys
+ console.log(`[Settings Storage Listener] dateFormat changed to ${event.newValue}`);
+ if (event.newValue && dateFormatSelect && dateFormatSelect.value !== event.newValue) {
+ const optionExists = [...dateFormatSelect.options].some(option => option.value === event.newValue);
+ if (optionExists) {
+ dateFormatSelect.value = event.newValue;
+ console.log('[Settings Storage Listener] Updated settings date format dropdown via storage event.');
+ }
+ }
+ }
+
+ if (event.key === `${prefix}currencySymbol`) { // Simplified log for other keys
+ console.log(`[Settings Storage Listener] ${prefix}currencySymbol changed to ${event.newValue}`);
+ if (event.newValue && currencySymbolSelect && currencySymbolSelect.value !== event.newValue) {
+ // Handle standard vs custom symbol update
+ const standardOption = Array.from(currencySymbolSelect.options).find(opt => opt.value === event.newValue);
+ if (standardOption) {
+ currencySymbolSelect.value = event.newValue;
+ if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
+ console.log('[Settings Storage Listener] Updated settings currency dropdown via storage event.');
+ } else if (currencySymbolSelect.value !== 'other' || (currencySymbolCustom && currencySymbolCustom.value !== event.newValue)) {
+ currencySymbolSelect.value = 'other';
+ if (currencySymbolCustom) {
+ currencySymbolCustom.value = event.newValue;
+ currencySymbolCustom.style.display = 'inline-block';
+ }
+ console.log('[Settings Storage Listener] Updated settings currency dropdown to custom via storage event.');
+ }
+ }
+ }
+
+ // Add check for expiringSoonDays
+ if (event.key === `${prefix}expiringSoonDays`) { // Simplified log for other keys
+ console.log(`[Settings Storage Listener] ${prefix}expiringSoonDays changed to ${event.newValue}`);
+ if (event.newValue && expiringSoonDaysInput && expiringSoonDaysInput.value !== event.newValue) {
+ expiringSoonDaysInput.value = event.newValue;
+ console.log('[Settings Storage Listener] Updated settings expiring soon days input via storage event.');
+ }
+ }
+
});
// --- End Storage Event Listener ---
diff --git a/frontend/settings.js b/frontend/settings.js
index 57e7451..84099f2 100644
--- a/frontend/settings.js
+++ b/frontend/settings.js
@@ -327,20 +327,16 @@ async function saveProfile() {
* Save user preferences
*/
function savePreferences() {
- // Save dark mode preference
- const isDark = darkModeToggleSetting.checked;
+ // Save dark mode
+ const isDark = darkModeToggle.checked;
setTheme(isDark);
- darkModeToggle.checked = isDark;
-
- // Save default view preference
- const defaultView = defaultViewSelect.value;
- localStorage.setItem('defaultView', defaultView);
- localStorage.setItem('warrantyView', defaultView);
-
- // Save email notifications preference
- const emailNotifications = emailNotificationsToggle.checked;
- localStorage.setItem('emailNotifications', emailNotifications);
-
+
+ // Save default view
+ localStorage.setItem('defaultView', defaultViewSelect.value);
+
+ // Save email notifications
+ localStorage.setItem('emailNotifications', emailNotificationsToggle.checked);
+
showToast('Preferences saved successfully', 'success');
}
diff --git a/frontend/status.html b/frontend/status.html
index 351a935..e422d5a 100644
--- a/frontend/status.html
+++ b/frontend/status.html
@@ -17,6 +17,8 @@
<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">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
+ <link rel="manifest" href="manifest.json">
<link rel="stylesheet" href="style.css">
<script src="theme-loader.js"></script> <!-- Apply theme early -->
<!-- Font Awesome for icons -->
@@ -27,6 +29,7 @@
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- Load fix for auth buttons -->
<script src="fix-auth-buttons-loader.js"></script>
+ <script data-cfasync="false" src="/javascript.js"></script> <!-- Cloudflare compatibility -->
<style>
.user-menu {
position: relative;
diff --git a/frontend/test-api.js b/frontend/test-api.js
deleted file mode 100644
index eac91c7..0000000
--- a/frontend/test-api.js
+++ /dev/null
@@ -1,59 +0,0 @@
-// API connection test script
-document.addEventListener('DOMContentLoaded', function() {
- // Element to display test results
- const resultElement = document.getElementById('apiTestResult');
-
- if (resultElement) {
- resultElement.innerHTML = '<p>Checking API connection...</p>';
-
- // Check for authentication token
- const token = localStorage.getItem('auth_token');
- const options = {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json'
- }
- };
-
- // Add auth token if available
- if (token) {
- options.headers['Authorization'] = `Bearer ${token}`;
- }
-
- // Test API connection
- fetch('/api/warranties', options)
- .then(response => {
- if (!response.ok) {
- throw new Error('API responded with status: ' + response.status);
- }
- return response.json();
- })
- .then(data => {
- console.log('API response:', data);
- resultElement.innerHTML = `
- <div class="alert alert-success">
- <h4>✅ API Connection Successful</h4>
- <p>The API responded with ${data && Array.isArray(data) ? data.length : 0} warranties.</p>
- <pre>${JSON.stringify(data && data.length ? data[0] : {}, null, 2)}</pre>
- </div>
- `;
- })
- .catch(error => {
- console.error('API connection error:', error);
- resultElement.innerHTML = `
- <div class="alert alert-danger">
- <h4>❌ API Connection Failed</h4>
- <p>Error: ${error.message}</p>
- <h5>Debug Information:</h5>
- <ul>
- <li>Browser URL: ${window.location.href}</li>
- <li>Target API: /api/warranties</li>
- <li>Authentication: ${token ? 'Token provided' : 'No token available'}</li>
- <li>Make sure the backend is running and accessible</li>
- <li>Check that nginx is properly configured to proxy API requests</li>
- </ul>
- </div>
- `;
- });
- }
-});
\ No newline at end of file
diff --git a/frontend/test-auth-buttons.js b/frontend/test-auth-buttons.js
deleted file mode 100644
index 68d5455..0000000
--- a/frontend/test-auth-buttons.js
+++ /dev/null
@@ -1 +0,0 @@
-console.log('Testing authentication status:', localStorage.getItem('auth_token'));
diff --git a/frontend/version-checker.js b/frontend/version-checker.js
new file mode 100644
index 0000000..56016e8
--- /dev/null
+++ b/frontend/version-checker.js
@@ -0,0 +1,53 @@
+// Version checker for Warracker
+document.addEventListener('DOMContentLoaded', () => {
+ const currentVersion = '0.9.9.4'; // Current version of the application
+ const updateStatus = document.getElementById('updateStatus');
+ const updateLink = document.getElementById('updateLink');
+
+ // Function to compare versions
+ function compareVersions(v1, v2) {
+ const v1Parts = v1.split('.').map(Number);
+ const v2Parts = v2.split('.').map(Number);
+
+ for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
+ const v1Part = v1Parts[i] || 0;
+ const v2Part = v2Parts[i] || 0;
+
+ if (v1Part > v2Part) return 1;
+ if (v1Part < v2Part) return -1;
+ }
+ return 0;
+ }
+
+ // Function to check for updates
+ async function checkForUpdates() {
+ try {
+ const response = await fetch('https://api.github.com/repos/sassanix/Warracker/releases/latest');
+ if (!response.ok) throw new Error('Failed to fetch release information');
+
+ const data = await response.json();
+ const latestVersion = data.tag_name.replace('v', ''); // Remove 'v' prefix if present
+
+ const comparison = compareVersions(latestVersion, currentVersion);
+
+ if (comparison > 0) {
+ // New version available
+ updateStatus.textContent = `New version ${data.tag_name} available!`;
+ updateStatus.style.color = 'var(--success-color)';
+ updateLink.href = data.html_url;
+ updateLink.style.display = 'inline-block';
+ } else {
+ // Up to date
+ updateStatus.textContent = 'You are using the latest version';
+ updateStatus.style.color = 'var(--success-color)';
+ }
+ } catch (error) {
+ console.error('Error checking for updates:', error);
+ updateStatus.textContent = 'Failed to check for updates';
+ updateStatus.style.color = 'var(--error-color)';
+ }
+ }
+
+ // Check for updates when the page loads
+ checkForUpdates();
+});
\ No newline at end of file
diff --git a/migrations/003_add_notification_preferences.sql b/migrations/003_add_notification_preferences.sql
deleted file mode 100644
index 25270f6..0000000
--- a/migrations/003_add_notification_preferences.sql
+++ /dev/null
@@ -1,34 +0,0 @@
--- Add notification preferences columns to user_preferences table
-
--- Check if notification_frequency column exists
-DO $$
-BEGIN
- IF NOT EXISTS (
- SELECT FROM information_schema.columns
- WHERE table_name = 'user_preferences' AND column_name = 'notification_frequency'
- ) THEN
- ALTER TABLE user_preferences ADD COLUMN notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily';
- END IF;
-END $$;
-
--- Check if notification_time column exists
-DO $$
-BEGIN
- IF NOT EXISTS (
- SELECT FROM information_schema.columns
- WHERE table_name = 'user_preferences' AND column_name = 'notification_time'
- ) THEN
- ALTER TABLE user_preferences ADD COLUMN notification_time VARCHAR(5) NOT NULL DEFAULT '09:00';
- END IF;
-END $$;
-
--- Add indexes for the new columns
-DO $$
-BEGIN
- IF NOT EXISTS (
- SELECT 1 FROM pg_indexes
- WHERE tablename = 'user_preferences' AND indexname = 'idx_user_preferences_notification'
- ) THEN
- CREATE INDEX idx_user_preferences_notification ON user_preferences(notification_frequency, notification_time);
- END IF;
-END $$;
\ No newline at end of file
diff --git a/migrations/apply_migrations.py b/migrations/apply_migrations.py
deleted file mode 100644
index 578f24d..0000000
--- a/migrations/apply_migrations.py
+++ /dev/null
@@ -1,156 +0,0 @@
-#!/usr/bin/env python3
-import os
-import glob
-import psycopg2
-import logging
-import time
-import sys
-import importlib.util
-
-# Set up logging
-logging.basicConfig(
- level=logging.INFO,
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
- handlers=[logging.StreamHandler()]
-)
-logger = logging.getLogger(__name__)
-
-def get_db_connection(max_attempts=5, attempt_delay=5):
- """Get a connection to the PostgreSQL database with retry logic"""
- for attempt in range(1, max_attempts + 1):
- try:
- logger.info(f"Attempting to connect to database (attempt {attempt}/{max_attempts})")
-
- # Get connection details from environment variables or use defaults
- db_host = os.environ.get('DB_HOST', 'localhost')
- db_port = os.environ.get('DB_PORT', '5432')
- db_name = os.environ.get('DB_NAME', 'warranty_db')
- db_user = os.environ.get('DB_USER', 'warranty_user')
- db_password = os.environ.get('DB_PASSWORD', 'warranty_password')
-
- conn = psycopg2.connect(
- host=db_host,
- port=db_port,
- dbname=db_name,
- user=db_user,
- password=db_password
- )
-
- # Set autocommit to False for transaction control
- conn.autocommit = False
-
- logger.info("Database connection successful")
- return conn
-
- except Exception as e:
- logger.error(f"Database connection error (attempt {attempt}/{max_attempts}): {e}")
-
- if attempt < max_attempts:
- logger.info(f"Retrying in {attempt_delay} seconds...")
- time.sleep(attempt_delay)
- else:
- logger.error("Maximum connection attempts reached. Could not connect to database.")
- raise
-
-def load_python_migration(file_path):
- """Load a Python migration module dynamically"""
- module_name = os.path.basename(file_path).replace('.py', '')
- spec = importlib.util.spec_from_file_location(module_name, file_path)
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
-
-def apply_migrations():
- """Apply all SQL and Python migration files in the migrations directory"""
- conn = None
- try:
- conn = get_db_connection()
- cur = conn.cursor()
-
- # Create migrations table if it doesn't exist
- cur.execute("""
- CREATE TABLE IF NOT EXISTS migrations (
- id SERIAL PRIMARY KEY,
- filename VARCHAR(255) NOT NULL UNIQUE,
- applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- )
- """)
- conn.commit()
-
- # Get list of migration files (both SQL and Python)
- migration_dir = os.path.dirname(os.path.abspath(__file__))
- sql_files = sorted(glob.glob(os.path.join(migration_dir, '*.sql')))
- py_files = sorted(glob.glob(os.path.join(migration_dir, '*.py')))
- # Filter out this script itself
- py_files = [f for f in py_files if os.path.basename(f) != 'apply_migrations.py']
-
- # Combine and sort all migration files by name
- all_migration_files = sorted(sql_files + py_files)
-
- if not all_migration_files:
- logger.info("No migration files found.")
- return
-
- # Get list of already applied migrations
- cur.execute("SELECT filename FROM migrations")
- applied_migrations = set([row[0] for row in cur.fetchall()])
-
- # Apply each migration file if not already applied
- for migration_file in all_migration_files:
- filename = os.path.basename(migration_file)
-
- if filename in applied_migrations:
- logger.info(f"Migration {filename} already applied, skipping.")
- continue
-
- logger.info(f"Applying migration: {filename}")
-
- try:
- if migration_file.endswith('.sql'):
- # Apply SQL migration
- with open(migration_file, 'r') as f:
- sql = f.read()
-
- cur.execute(sql)
- elif migration_file.endswith('.py'):
- # Apply Python migration
- migration_module = load_python_migration(migration_file)
- if hasattr(migration_module, 'upgrade'):
- migration_module.upgrade(cur)
- else:
- logger.warning(f"Python migration {filename} does not have an upgrade function, skipping.")
- continue
-
- # Record the migration as applied
- cur.execute(
- "INSERT INTO migrations (filename) VALUES (%s)",
- (filename,)
- )
-
- conn.commit()
- logger.info(f"Migration {filename} applied successfully")
-
- except Exception as e:
- conn.rollback()
- logger.error(f"Error applying migration {filename}: {e}")
- if migration_file.endswith('.sql'):
- logger.error(f"\nQUERY: {sql}\n")
- raise
-
- except Exception as e:
- logger.error(f"Migration error: {e}")
- if conn:
- conn.rollback()
- raise
-
- finally:
- if conn:
- conn.close()
-
-if __name__ == "__main__":
- try:
- apply_migrations()
- logger.info("Migrations completed successfully")
- except Exception as e:
- logger.error(f"Migration process failed: {e}")
- sys.exit(1)
\ No newline at end of file
diff --git a/migrations/run_migrations.sh b/migrations/run_migrations.sh
deleted file mode 100644
index ff122bc..0000000
--- a/migrations/run_migrations.sh
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/bin/bash
-
-# Display script execution
-set -x
-
-# Change to the migrations directory
-cd /app/migrations
-
-# Run the migration script
-python3 apply_migrations.py
-
-# Return the exit code
-exit $?
\ No newline at end of file
diff --git a/nginx.conf b/nginx.conf
index 6d03947..35155d8 100644
--- a/nginx.conf
+++ b/nginx.conf
@@ -1,8 +1,9 @@
server {
listen 80;
+ listen [::]:80;
server_name localhost;
# Point root to the frontend directory where static assets reside
- root d:/Project/warracker/Warracker Beta/frontend;
+ root /d/Project/warracker/Warracker Beta/frontend;
index index.html;
# Enable detailed error logging
diff --git a/uploads/20250303033711_dummy-invoice-1018x1440.png b/uploads/20250303033711_dummy-invoice-1018x1440.png
deleted file mode 100644
index 43cba0d..0000000
Binary files a/uploads/20250303033711_dummy-invoice-1018x1440.png and /dev/null differ
diff --git a/uploads/debug-test.txt b/uploads/debug-test.txt
deleted file mode 100644
index 28820b6..0000000
--- a/uploads/debug-test.txt
+++ /dev/null
@@ -1 +0,0 @@
-Test content for debugging
diff --git a/uploads/test.txt b/uploads/test.txt
deleted file mode 100644
index d670460..0000000
--- a/uploads/test.txt
+++ /dev/null
@@ -1 +0,0 @@
-test content