π‘οΈ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
warranty UI improvements & Paperless-ngx integration
sassanixf3ba71bdbcae
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 53fd9c4..1873ba5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,4 +1,80 @@# Changelog++## 0.10.1.4 - 2025-06-24++### Enhanced+- **Warranty Card Information Display Improvements:** Redesigned warranty card layout with clean icon-based display and improved visual organization.+ - **Icon-Based Information Display:** Added intuitive icons to warranty information for better visual scanning:+ - π Calendar icon for Product Age+ - π Document icon for Warranty Duration+ - π§ Wrench icon for Warranty End Date+ - πͺ Coins icon for Purchase Price+ - π Barcode icon for Serial Number+ - πͺ Store icon for Vendor+ - π‘οΈ Shield icon for Warranty Type+ - **Reorganized Information Order:** Reordered warranty details for logical information hierarchy:+ - Age β Warranty Duration β Warranty End Date β Price β Serial Number β Vendor β Type+ - **Layout Improvements:**+ - Fixed text overlapping with product photo thumbnails by removing right-alignment+ - Values now positioned close to labels with consistent spacing+ - Applied improvements across all view modes (grid, list, table)+ - **Visual Enhancements:**+ - Added light grey background (#f5f5f5) to product photo thumbnails+ - Dark mode photo backgrounds use #2a2a2a for proper contrast+ - Improved serial number display - first serial shown inline, additional ones in list below+ - _Files: `frontend/script.js`, `frontend/style.css`_++### Added+- **Paperless-ngx Document Browser:** Complete GUI interface for browsing and selecting documents from Paperless-ngx in warranty forms.+ - **Interactive Document Browser:** Added comprehensive document browser modal accessible from warranty add/edit forms:+ - **Browse Buttons:** Added "Browse Paperless" buttons for invoice and manual document selection in warranty forms+ - **Search and Filter:** Full-text search across document titles and content with tag-based filtering capabilities+ - **Pagination Support:** Efficient pagination for large document collections with configurable page sizes+ - **Document Selection:** Single-click document selection with visual confirmation and selection state management+ - **Backend API Enhancements (`backend/app.py`):** Added `/api/paperless/tags` endpoint for document filtering:+ - **Tag Retrieval:** Fetches available tags from Paperless-ngx for filter dropdown population+ - **Authentication:** Properly authenticated endpoint with user permission validation+ - **Error Handling:** Comprehensive error handling for Paperless-ngx connection issues+ - **Frontend Integration (`frontend/index.html`, `frontend/script.js`, `frontend/style.css`):**+ - **Modal Interface:** Large, responsive document browser modal with search bar, filters, and document grid+ - **Document Display:** Clean document cards showing title, creation date, tags, and selection status+ - **Form Integration:** Selected documents automatically populate warranty form fields with document IDs+ - **Mobile Responsive:** Optimized layout for mobile devices with appropriate touch targets+ - **Visual Feedback:** Loading states, error messages, and success confirmations for all operations+ - **User Experience Features:**+ - **Conditional Visibility:** Browse buttons only appear when Paperless-ngx is enabled and configured+ - **Real-time Search:** Instant search results as users type in the search field+ - **Tag Filtering:** Multi-select tag filter for refined document discovery+ - **Keyboard Navigation:** Full keyboard support for accessibility+ - **Cache Management:** Intelligent caching of document lists and tags for improved performance+ - _Files: `backend/app.py`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_++- **Paperless-ngx Document Viewing Preference:** Added user preference to view Paperless documents within Warracker instead of opening in Paperless domain.+ - **User Preference Setting:** Added "View Documents in Warracker" toggle in Paperless-ngx settings section:+ - **Individual Choice:** Each user can choose their preferred document viewing method between Warracker interface or Paperless-ngx instance+ - **Dual Viewing Options:** Users can view documents either within Warracker's interface or directly in the Paperless-ngx web interface+ - **Persistent Setting:** Preference saved to user preferences database and localStorage+ - **Immediate Effect:** Setting changes apply immediately without requiring page refresh+ - **Database Schema (`backend/migrations/037_add_paperless_view_in_app_preference.sql`):** Added `paperless_view_in_app` boolean column to `user_preferences` table:+ - **Default Value:** Set to FALSE (open in Paperless-ngx domain) for backward compatibility+ - **User-Specific:** Each user maintains their own viewing preference independently+ - **Backend API Integration (`backend/auth_routes.py`):** Enhanced user preferences endpoints:+ - **GET /api/auth/preferences:** Returns paperless viewing preference with proper fallback handling+ - **PUT /api/auth/preferences:** Validates and saves paperless viewing preference with boolean validation+ - **Default Handling:** All preference responses include paperless_view_in_app with appropriate defaults+ - **Frontend Implementation (`frontend/script.js`, `frontend/settings-new.html`, `frontend/settings-new.js`):**+ - **Document Opening Logic:** Modified `openPaperlessDocument()` function to check user preference+ - **Warracker Viewing:** When enabled, documents open via `/api/paperless-file/{id}` endpoint within Warracker interface+ - **Paperless-ngx Viewing:** When disabled, documents open directly in the Paperless-ngx web interface at the configured instance URL+ - **Authentication Handling:** Proper token authentication for in-app document viewing with query parameter support+ - **Fallback Support:** Graceful fallback to Paperless-ngx domain if in-app viewing fails+ - **Settings UI:** Toggle switch in Paperless-ngx settings section with clear description of both viewing options+ - **Security Features:**+ - **Token Authentication:** Documents accessed through Warracker maintain proper user authentication+ - **Permission Validation:** Backend validates user access rights before serving documents+ - **Secure Token Passing:** Authentication tokens properly encoded in query parameters for secure access+ - _Files: `backend/migrations/037_add_paperless_view_in_app_preference.sql`, `backend/auth_routes.py`, `frontend/script.js`, `frontend/settings-new.html`, `frontend/settings-new.js`_+## 0.10.1.3 - 2025-06-17### Added@@ -23,6 +99,24 @@- **Document Access Integration:** Direct access to Paperless-ngx documents through warranty interface with secure authentication- _Files: `backend/app.py`, `frontend/script.js`, `frontend/settings-new.html`, `frontend/settings-new.js`_+### Fixed+- **Application Loading Performance:** Eliminated empty warranty list flash during login by preventing premature rendering before data is loaded.+ - **Loading State Management:** Added `warrantiesLoaded` flag to track when warranty data has been successfully fetched from the API+ - **Render Prevention:** Modified `switchView()` function to skip rendering warranties until data is actually loaded from the server+ - **Smooth User Experience:** Users now see warranties appear directly without the brief flash of empty content during authentication+ - **State Synchronization:** Warranty loading flag properly reset on load start and error conditions to maintain accurate state+ - **Initialization Flow:** View preference loading no longer triggers empty warranty rendering during page initialization+ - _Files: `frontend/script.js`_++- **Settings Page Horizontal Scrollbar:** Eliminated horizontal scrollbar issue on the settings page that was causing unwanted left-right scrolling.+ - **Footer Overflow Fix:** Replaced problematic viewport width calculations (`100vw`) with standard width (`100%`) in `.warracker-footer` class to prevent horizontal overflow+ - **Margin Calculation Fix:** Removed `calc(-50vw + 50%)` margin calculations that were causing overflow beyond viewport boundaries+ - **Global Overflow Prevention:** Added `overflow-x: hidden` to `html`, `body`, and `.content-wrapper` elements to prevent any horizontal scrolling+ - **Grid Responsiveness:** Reduced minimum column width from `200px` to `150px` in admin actions, apprise actions, and status grid layouts for better mobile compatibility+ - **Text Handling:** Added `word-wrap: break-word` and `box-sizing: border-box` to form controls and cards to prevent text overflow+ - **Cross-Device Compatibility:** Settings page now displays properly without horizontal scrollbars on all screen sizes and devices+ - _Files: `frontend/settings-styles.css`_+## 0.10.1.2 - 2025-06-16diff --git a/backend/app.py b/backend/app.pyindex 6e02425..9306abb 100644--- a/backend/app.py+++ b/backend/app.py@@ -42,6 +42,7 @@ import csv # Added for CSV importimport io # Added for CSV importfrom dateutil.relativedelta import relativedeltaimport mimetypes+import requestsapp = Flask(__name__)@@ -1213,21 +1214,25 @@ def update_warranty(warranty_id):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")+ sql_fields.append("paperless_invoice_id = NULL") # Also clear Paperless IDif 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")+ sql_fields.append("paperless_manual_id = NULL") # Also clear Paperless IDif db_other_document_path is not None:sql_fields.append("other_document_path = %s")sql_values.append(db_other_document_path)elif 'delete_other_document' in request.form and request.form.get('delete_other_document', 'false').lower() == 'true':sql_fields.append("other_document_path = NULL")+ sql_fields.append("paperless_other_id = NULL") # Also clear Paperless IDif db_product_photo_path is not None:sql_fields.append("product_photo_path = %s")sql_values.append(db_product_photo_path)elif 'delete_product_photo' in request.form and request.form.get('delete_product_photo', 'false').lower() == 'true':sql_fields.append("product_photo_path = NULL")+ sql_fields.append("paperless_photo_id = NULL") # Also clear Paperless ID# Handle Paperless-ngx document IDsif paperless_invoice_id is not None:@@ -4294,28 +4299,117 @@ def paperless_search():paperless_handler = get_paperless_handler(conn)if not paperless_handler:- return jsonify({"error": "Paperless-ngx integration not available"}), 400+ return jsonify({'success': False, 'message': 'Paperless-ngx not configured'}), 400- query = request.args.get('q', '')- limit = min(int(request.args.get('limit', 25)), 100)+ # Get query parameters+ ordering = request.args.get('ordering', '-created')+ created_gte = request.args.get('created__gte')+ search_query = request.args.get('query', '')- success, documents, message = paperless_handler.search_documents(query, limit)+ # Get pagination parameters (support both old and new formats)+ limit = request.args.get('limit', request.args.get('page_size', '25'))+ offset = request.args.get('offset', '0')+ page = request.args.get('page', '1')- if success:- return jsonify({- "success": True,- "documents": documents,- "message": message- }), 200- else:- return jsonify({- "success": False,- "error": message- }), 500+ # Calculate page from offset if needed+ try:+ limit_int = int(limit)+ offset_int = int(offset)+ if offset_int > 0:+ page = str((offset_int // limit_int) + 1)+ except (ValueError, ZeroDivisionError):+ page = '1'+ limit = '25'++ # Build search URL using paperless handler's configuration+ search_url = f"{paperless_handler.base_url.rstrip('/')}/api/documents/"+ params = {+ 'ordering': ordering,+ 'page_size': limit,+ 'page': page+ }++ if created_gte:+ # Convert ISO format to Paperless-ngx expected format+ # Remove 'Z' and use format that Paperless-ngx accepts+ try:+ from datetime import datetime, timezone+ # Parse the ISO format and convert to YYYY-MM-DD format+ dt = datetime.fromisoformat(created_gte.replace('Z', '+00:00'))+ # Use date only format for better compatibility+ params['created__gte'] = dt.strftime('%Y-%m-%d')+ logger.info(f"Converted date filter from {created_gte} to {params['created__gte']}")+ except Exception as date_error:+ logger.warning(f"Could not parse date {created_gte}: {date_error}")+ # Fallback: use today's date+ from datetime import datetime+ params['created__gte'] = datetime.now().strftime('%Y-%m-%d')+ if search_query:+ params['query'] = search_query++ # Add document type filter+ document_type = request.args.get('document_type', '')+ if document_type:+ params['document_type'] = document_type++ # Add tag filter+ tags_filter = request.args.get('tags__id__in', '')+ if tags_filter:+ params['tags__id__in'] = tags_filter++ logger.info(f"Searching Paperless documents with params: {params}")++ # Make request to Paperless-ngx using the session from paperless handler+ response = paperless_handler.session.get(+ search_url,+ params=params,+ timeout=30+ )++ response.raise_for_status()+ search_result = response.json()++ logger.info(f"Paperless search returned {len(search_result.get('results', []))} documents")++ return jsonify(search_result)++ except Exception as e:+ logger.error(f"Error searching Paperless documents: {e}")+ return jsonify({'success': False, 'message': str(e)}), 500+ finally:+ if conn:+ release_db_connection(conn)+[email protected]('/api/paperless/tags', methods=['GET'])+@token_required+def paperless_tags():+ """+ Get tags from Paperless-ngx+ """+ conn = None+ try:+ conn = get_db_connection()+ paperless_handler = get_paperless_handler(conn)++ if not paperless_handler:+ return jsonify({'success': False, 'message': 'Paperless-ngx integration not available'}), 400++ # Make request to Paperless-ngx tags endpoint+ response = paperless_handler.session.get(+ f"{paperless_handler.paperless_url}/api/tags/",+ timeout=30+ )++ response.raise_for_status()+ tags_result = response.json()++ logger.info(f"Paperless tags returned {len(tags_result.get('results', []))} tags")++ return jsonify(tags_result)except Exception as e:- logger.error(f"Error in Paperless search: {e}")- return jsonify({"error": "Search failed"}), 500+ logger.error(f"Error fetching Paperless tags: {e}")+ return jsonify({'success': False, 'message': str(e)}), 500finally:if conn:release_db_connection(conn)@@ -4564,3 +4658,126 @@ def cleanup_invalid_paperless_documents():finally:if conn:release_db_connection(conn)+[email protected]('/api/paperless-search-and-link', methods=['POST'])+@token_required+def paperless_search_and_link():+ """Search for a Paperless document by title and link it to a warranty."""++ conn = None # Single connection for the full request lifecycle+ try:+ logger.info("paperless_search_and_link called by user: %s", request.user)++ data = request.get_json() or {}+ warranty_id = data.get("warranty_id")+ document_type = data.get("document_type") # 'invoice', 'manual', 'photo', 'other'+ search_title = data.get("search_title")++ logger.info("Search request: warranty_id=%s, document_type=%s, search_title=%s", warranty_id, document_type, search_title)++ if not all([warranty_id, document_type, search_title]):+ return jsonify({"success": False, "message": "Missing required parameters"}), 400++ # Validate document_type+ valid_types = {+ "invoice": "paperless_invoice_id",+ "manual": "paperless_manual_id",+ "photo": "paperless_photo_id",+ "other": "paperless_other_id",+ }++ if document_type not in valid_types:+ return jsonify({"success": False, "message": "Invalid document type"}), 400++ # Get DB connection once and reuse it throughout+ conn = get_db_connection()++ # Obtain Paperless handler (uses same connection to fetch settings)+ paperless_handler = get_paperless_handler(conn)+ if not paperless_handler:+ return jsonify({"success": False, "message": "Paperless-ngx not configured"}), 400++ # Search for the document in Paperless-ngx+ success, document_id, message = paperless_handler.find_document_by_title(search_title)+ logger.info("Paperless search result: success=%s, document_id=%s, message=%s", success, document_id, message)++ if not success or not document_id:+ return jsonify({"success": False, "message": f"Document not found: {message}"}), 404++ # Update warranty with the found document ID+ db_field = valid_types[document_type]++ with conn.cursor() as cursor:+ logger.info(+ "Updating warranty %s field %s with document ID %s for user %s",+ warranty_id,+ db_field,+ document_id,+ request.user["id"],+ )++ cursor.execute(+ f"""+ UPDATE warranties+ SET {db_field} = %s+ WHERE id = %s AND user_id = %s+ """,+ (document_id, warranty_id, request.user["id"]),+ )++ if cursor.rowcount == 0:+ logger.warning("No warranty found with ID %s for user %s", warranty_id, request.user["id"])+ conn.rollback()+ return jsonify({"success": False, "message": "Warranty not found or access denied"}), 404++ conn.commit()++ logger.info("Successfully linked document %s to warranty %s", document_id, warranty_id)++ return jsonify({"success": True, "message": "Document linked successfully", "document_id": document_id})++ except Exception as e:+ logger.error("Error in paperless_search_and_link: %s", e, exc_info=True)+ return jsonify({"success": False, "message": "Internal server error"}), 500+ finally:+ if conn:+ release_db_connection(conn)+[email protected]('/api/test-auth', methods=['POST'])+@token_required+def test_auth():+ """Simple test endpoint to verify authentication is working"""+ try:+ logger.info(f"test_auth called by user: {request.user}")+ return jsonify({+ 'success': True,+ 'user': request.user,+ 'message': 'Authentication working'+ })+ except Exception as e:+ logger.error(f"Error in test_auth: {e}")+ return jsonify({'success': False, 'message': str(e)}), 500+[email protected]('/api/paperless/url', methods=['GET'])+@token_required+def get_paperless_url():+ """Get the Paperless-ngx base URL for opening documents directly"""+ conn = None+ try:+ conn = get_db_connection()+ paperless_handler = get_paperless_handler(conn)++ if not paperless_handler:+ return jsonify({'success': False, 'message': 'Paperless-ngx not configured'}), 400++ return jsonify({+ 'success': True,+ 'url': paperless_handler.base_url+ })++ except Exception as e:+ logger.error(f"Error getting Paperless URL: {e}")+ return jsonify({'success': False, 'message': str(e)}), 500+ finally:+ if conn:+ release_db_connection(conn)diff --git a/backend/auth_routes.py b/backend/auth_routes.pyindex 085ded9..a9c27b7 100644--- a/backend/auth_routes.py+++ b/backend/auth_routes.py@@ -821,14 +821,15 @@ def get_preferences():'timezone': 'UTC','notification_channel': 'email','currency_symbol': '$',- 'date_format': 'MDY'+ 'date_format': 'MDY',+ 'paperless_view_in_app': False}return jsonify(default_preferences), 200# Get user preferencescursor.execute("""SELECT email_notifications, default_view, theme, expiring_soon_days,- notification_frequency, notification_time, timezone, currency_symbol, date_format, notification_channel, apprise_notification_time, apprise_notification_frequency, apprise_timezone, currency_position+ notification_frequency, notification_time, timezone, currency_symbol, date_format, notification_channel, apprise_notification_time, apprise_notification_frequency, apprise_timezone, currency_position, paperless_view_in_appFROM user_preferencesWHERE user_id = %s""", (user_id,))@@ -850,7 +851,8 @@ def get_preferences():'apprise_notification_time': preferences_data[10] if preferences_data[10] else '09:00','apprise_notification_frequency': preferences_data[11] if preferences_data[11] else 'daily','apprise_timezone': preferences_data[12] if preferences_data[12] else 'UTC',- 'currency_position': preferences_data[13] if preferences_data[13] else 'left'+ 'currency_position': preferences_data[13] if preferences_data[13] else 'left',+ 'paperless_view_in_app': preferences_data[14] if len(preferences_data) > 14 and preferences_data[14] is not None else False}else:# Create default preferences for user@@ -865,7 +867,8 @@ def get_preferences():'notification_channel': 'email','currency_symbol': '$','date_format': 'MDY',- 'currency_position': 'left'+ 'currency_position': 'left',+ 'paperless_view_in_app': False}preferences = default_preferences@@ -884,7 +887,8 @@ def get_preferences():'notification_channel': 'email','currency_symbol': '$','date_format': 'MDY',- 'currency_position': 'left'+ 'currency_position': 'left',+ 'paperless_view_in_app': False}return jsonify(default_preferences), 200finally:@@ -904,7 +908,8 @@ def get_preferences():'notification_channel': 'email','currency_symbol': '$','date_format': 'MDY',- 'currency_position': 'left'+ 'currency_position': 'left',+ 'paperless_view_in_app': False}return jsonify(default_preferences), 200@@ -932,6 +937,7 @@ def update_preferences():apprise_notification_frequency = data.get('apprise_notification_frequency')timezone = data.get('timezone')apprise_timezone = data.get('apprise_timezone')+ paperless_view_in_app = data.get('paperless_view_in_app')if default_view and default_view not in ['grid', 'list', 'table']:return jsonify({'message': 'Invalid default view'}), 400@@ -952,6 +958,8 @@ def update_preferences():return jsonify({'message': 'Invalid date format'}), 400if notification_channel and notification_channel not in ['none', 'email', 'apprise', 'both']:return jsonify({'message': 'Invalid notification channel'}), 400+ if paperless_view_in_app is not None and not isinstance(paperless_view_in_app, bool):+ return jsonify({'message': 'paperless_view_in_app must be a boolean'}), 400conn = db_handler.get_db_connection()cursor = conn.cursor()@@ -1005,6 +1013,9 @@ def update_preferences():if apprise_timezone is not None:update_fields.append("apprise_timezone = %s")update_values.append(apprise_timezone)+ if paperless_view_in_app is not None:+ update_fields.append("paperless_view_in_app = %s")+ update_values.append(paperless_view_in_app)if update_fields:update_query = f"UPDATE user_preferences SET {', '.join(update_fields)} WHERE user_id = %s"@@ -1012,16 +1023,16 @@ def update_preferences():else:# Insert new preferencescursor.execute("""- INSERT INTO user_preferences (user_id, default_view, theme, expiring_soon_days, currency_symbol, currency_position, date_format, notification_channel, notification_frequency, notification_time, apprise_notification_time, apprise_notification_frequency, timezone, apprise_timezone)- VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)- """, (user_id, default_view or 'grid', theme or 'light', expiring_soon_days or 30, currency_symbol or '$', currency_position or 'left', date_format or 'MDY', notification_channel or 'email', notification_frequency or 'daily', notification_time or '09:00', apprise_notification_time or '09:00', apprise_notification_frequency or 'daily', timezone or 'UTC', apprise_timezone or 'UTC'))+ INSERT INTO user_preferences (user_id, default_view, theme, expiring_soon_days, currency_symbol, currency_position, date_format, notification_channel, notification_frequency, notification_time, apprise_notification_time, apprise_notification_frequency, timezone, apprise_timezone, paperless_view_in_app)+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)+ """, (user_id, default_view or 'grid', theme or 'light', expiring_soon_days or 30, currency_symbol or '$', currency_position or 'left', date_format or 'MDY', notification_channel or 'email', notification_frequency or 'daily', notification_time or '09:00', apprise_notification_time or '09:00', apprise_notification_frequency or 'daily', timezone or 'UTC', apprise_timezone or 'UTC', paperless_view_in_app if paperless_view_in_app is not None else False))conn.commit()# Return updated preferencescursor.execute("""SELECT email_notifications, default_view, theme, expiring_soon_days,- notification_frequency, notification_time, timezone, currency_symbol, date_format, notification_channel, apprise_notification_time, apprise_notification_frequency, apprise_timezone, currency_position+ notification_frequency, notification_time, timezone, currency_symbol, date_format, notification_channel, apprise_notification_time, apprise_notification_frequency, apprise_timezone, currency_position, paperless_view_in_appFROM user_preferencesWHERE user_id = %s""", (user_id,))@@ -1043,7 +1054,8 @@ def update_preferences():'apprise_notification_time': preferences_data[10] if preferences_data[10] else '09:00','apprise_notification_frequency': preferences_data[11] if preferences_data[11] else 'daily','apprise_timezone': preferences_data[12] if preferences_data[12] else 'UTC',- 'currency_position': preferences_data[13] if preferences_data[13] else 'left'+ 'currency_position': preferences_data[13] if preferences_data[13] else 'left',+ 'paperless_view_in_app': preferences_data[14] if len(preferences_data) > 14 and preferences_data[14] is not None else False}else:preferences = {@@ -1060,7 +1072,8 @@ def update_preferences():'currency_position': currency_position or 'left','apprise_notification_time': apprise_notification_time or '09:00','apprise_notification_frequency': apprise_notification_frequency or 'daily',- 'apprise_timezone': apprise_timezone or 'UTC'+ 'apprise_timezone': apprise_timezone or 'UTC',+ 'paperless_view_in_app': paperless_view_in_app if paperless_view_in_app is not None else False}return jsonify(preferences), 200diff --git a/backend/migrations/037_add_paperless_view_in_app_preference.sql b/backend/migrations/037_add_paperless_view_in_app_preference.sqlnew file mode 100644index 0000000..5e09e11--- /dev/null+++ b/backend/migrations/037_add_paperless_view_in_app_preference.sql@@ -0,0 +1,8 @@+-- Migration: Add paperless_view_in_app preference to user_preferences table+-- This allows users to choose whether to view Paperless-ngx documents within Warracker or in the Paperless domain++-- Add column for storing Paperless-ngx document viewing preference+ALTER TABLE user_preferences ADD COLUMN IF NOT EXISTS paperless_view_in_app BOOLEAN DEFAULT FALSE;++-- Add comment for documentation+COMMENT ON COLUMN user_preferences.paperless_view_in_app IS 'Whether to view Paperless-ngx documents within Warracker interface instead of opening them in Paperless domain';\ No newline at end of filediff --git a/backend/paperless_handler.py b/backend/paperless_handler.pyindex c84fe6c..42d0cf2 100644--- a/backend/paperless_handler.py+++ b/backend/paperless_handler.py@@ -26,6 +26,7 @@ class PaperlessHandler:api_token: API token for authentication"""self.paperless_url = paperless_url.rstrip('/')+ self.base_url = self.paperless_url # Add base_url alias for compatibilityself.api_token = api_tokenself.session = requests.Session()self.session.headers.update({@@ -127,7 +128,24 @@ class PaperlessHandler:logger.info(f"Paperless-ngx upload response: {result}")except Exception as e:logger.warning(f"Could not parse response as JSON: {e}")- # If we can't parse JSON but got 200, treat as success++ # If Paperless returns plain text, it is often just the task UUID.+ text_body = response.text.strip().strip('"') # paperless may wrap uuid in quotes++ import re+ uuid_pattern = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")++ if uuid_pattern.match(text_body):+ # Treat as task ID and try to resolve the document ID+ resolved_id = self._get_document_id_from_task(text_body)++ if resolved_id:+ return True, resolved_id, "Document uploaded and processed successfully"+ else:+ logger.info("Upload accepted; processing asynchronously (task %s)", text_body)+ return True, None, f"Document uploaded successfully: {text_body}"++ # If we can't recognise the content, still mark success but without IDreturn True, None, "Document uploaded successfully"# Handle different possible response formats from Paperless-ngx@@ -136,9 +154,21 @@ class PaperlessHandler:# JSON object responseif 'task_id' in result:# Task-based response (asynchronous processing)- document_id = result.get('task_id')- logger.info(f"Document upload task created: {document_id}")- return True, document_id, "Document uploaded successfully (processing)"+ task_id = result.get('task_id')+ logger.info(f"Document upload task created: {task_id}")++ # NEW: Poll Paperless-ngx task endpoint to resolve the final document ID.+ resolved_id = self._get_document_id_from_task(task_id)++ if resolved_id:+ logger.info(f"Resolved task {task_id} to document ID {resolved_id}")+ return True, resolved_id, "Document uploaded and processed successfully"+ else:+ logger.warning(+ "Timed out waiting for Paperless-ngx to finish processing task %s", task_id+ )+ # Processing will still finish in background; caller can attempt later auto-link.+ return True, None, "Document uploaded (processing asynchronously β link pending)"elif 'id' in result:# Direct document ID response (synchronous processing)document_id = result.get('id')@@ -157,9 +187,10 @@ class PaperlessHandler:logger.info(f"Document uploaded successfully (string response): {result}")# Try to extract an ID from the string if it looks like oneimport re- id_match = re.search(r'\d+', result)+ # Only match standalone numbers, not task IDs+ id_match = re.search(r'"id"\s*:\s*(\d+)', result)if id_match:- document_id = int(id_match.group())+ document_id = int(id_match.group(1))logger.info(f"Extracted document ID from string: {document_id}")return True, document_id, f"Document uploaded successfully: {result}"else:@@ -430,6 +461,151 @@ class PaperlessHandler:logger.warning(f"Error checking document existence {document_id}: {e}")return False+ def find_document_by_title(self, title: str) -> Tuple[bool, Optional[int], str]:+ """+ Find a document by its title in Paperless-ngx++ Args:+ title: Document title to search for++ Returns:+ (success: bool, document_id: Optional[int], message: str)+ """+ try:+ logger.info(f"Searching for document by title: {title}")++ # Search for documents with the given title+ response = self.session.get(+ f'{self.paperless_url}/api/documents/',+ params={+ 'title__icontains': title, # Case-insensitive partial match+ 'ordering': '-created', # Most recent first+ 'page_size': 10 # Limit results+ },+ timeout=15+ )++ response.raise_for_status()+ result = response.json()++ if 'results' in result and result['results']:+ # Return the first (most recent) match+ document = result['results'][0]+ document_id = document.get('id')+ document_title = document.get('title', 'Unknown')++ logger.info(f"Found document: ID {document_id}, Title: {document_title}")+ return True, document_id, f"Found document: {document_title}"+ else:+ logger.info(f"No document found with title containing: {title}")+ return False, None, "Document not found"++ except requests.exceptions.HTTPError as e:+ logger.error(f"HTTP error searching for document: {e}")+ return False, None, f"Search failed: HTTP {e.response.status_code}"+ except Exception as e:+ logger.error(f"Error searching for document: {e}")+ return False, None, f"Search failed: {str(e)}"++ # ---------------------------------------------------------------------+ # Internal helpers+ # ---------------------------------------------------------------------++ def _get_document_id_from_task(+ self,+ task_id: str,+ timeout_secs: int = 600, # increased to 10 minutes per user request+ poll_interval: float = 5.0, # less frequent polling to reduce load+ ) -> Optional[int]:+ """Poll /api/tasks endpoint until the task completes and returns a document ID.++ Args:+ task_id: The UUID returned by the document upload request.+ timeout_secs: Maximum time to wait before giving up.+ poll_interval: Seconds between polls.++ Returns:+ The related document ID if the task completed successfully within the+ timeout window; otherwise, ``None``.+ """++ import time++ if not task_id:+ return None++ # Prefer the dedicated task endpoint (Paperless β₯2.3). Some older+ # releases only support the list + filter variant. We therefore try the+ # singular endpoint first and fall back to the legacy query if it 404s.++ task_url_primary = f"{self.paperless_url}/api/tasks/{task_id}/"+ task_url_legacy_list = f"{self.paperless_url}/api/tasks/"++ deadline = time.time() + timeout_secs++ while time.time() < deadline:+ try:+ try:+ resp = self.session.get(task_url_primary, timeout=10)+ if resp.status_code == 404:+ # Fall back to legacy ?task_id=<uuid> filter+ resp = self.session.get(task_url_legacy_list, params={"task_id": task_id}, timeout=10)+ except requests.exceptions.HTTPError as http_err:+ if http_err.response.status_code == 404 and http_err.response.url.rstrip('/') == task_url_primary.rstrip('/'):+ # Primary endpoint not available, try legacy+ resp = self.session.get(task_url_legacy_list, params={"task_id": task_id}, timeout=10)+ else:+ raise++ resp.raise_for_status()++ # Legacy endpoint returns a list+ if isinstance(resp.json(), list):+ task_info = resp.json()[0] if resp.json() else {}+ else:+ task_info = resp.json()++ # In newer Paperless versions the field is called "state"; fall back to+ # "status" for backwards-compatibility.+ state = task_info.get("state") or task_info.get("status")+ related_doc = task_info.get("related_document")++ # Some Paperless versions don't fill related_document but embed the+ # newly-created ID in the free-text "result" string, e.g.+ # "Success. New document id 416 created" β see GH#3064.+ if not related_doc and isinstance(task_info.get("result"), str):+ import re+ m = re.search(r"document id (\d+)", task_info["result"])+ if m:+ related_doc = m.group(1)++ if state == "SUCCESS" and related_doc:+ try:+ return int(related_doc)+ except (ValueError, TypeError):+ logger.warning("Unexpected related_document value: %s", related_doc)+ return None++ if state in {"FAILURE", "REVOKED"}:+ logger.error("Paperless task %s finished with state %s", task_id, state)+ return None++ # Task still running β wait and try again+ time.sleep(poll_interval)++ except Exception as poll_err:+ # Transient network or parsing error β log and retry until deadline+ logger.warning("Error polling task %s: %s", task_id, poll_err)+ time.sleep(poll_interval)++ # Timed out waiting for the task to finish+ logger.warning(+ "Timed out after %s seconds waiting for task %s (state pending) β will return None so frontend can attempt auto-link",+ timeout_secs,+ task_id,+ )+ return None+def get_paperless_handler(conn) -> Optional[PaperlessHandler]:"""diff --git a/frontend/about.html b/frontend/about.htmlindex 517560d..2c58822 100644--- a/frontend/about.html+++ b/frontend/about.html@@ -312,7 +312,7 @@<!-- Hero Section --><div class="about-hero"><h1><i class="fas fa-shield-alt"></i> Warracker</h1>- <div class="version">Version v0.10.1.3</div>+ <div class="version">Version v0.10.1.4</div><p class="description">A comprehensive warranty management system designed to help you track, organize, and manage all your product warranties in one secure, user-friendly platform.</p>diff --git a/frontend/index.html b/frontend/index.htmlindex 3c8c4b2..e5cfcf3 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -450,23 +450,6 @@<div class="form-group"><label>Product Photo (Optional)</label>- <!-- Storage Selection -->- <div id="productPhotoStorageSelection" class="storage-selection" style="display: none;">- <div class="storage-options">- <label class="storage-option">- <input type="radio" name="productPhotoStorage" value="local" checked>- <span class="storage-label">- <i class="fas fa-hdd"></i> Store Locally- </span>- </label>- <label class="storage-option">- <input type="radio" name="productPhotoStorage" value="paperless">- <span class="storage-label">- <i class="fas fa-cloud"></i> Store in Paperless-ngx- </span>- </label>- </div>- </div><div class="file-input-wrapper"><label for="productPhoto" class="file-input-label"><i class="fas fa-camera"></i> Choose Photo@@ -477,6 +460,7 @@<div id="productPhotoPreview" class="photo-preview" style="display: none;"><img id="productPhotoImg" src="" alt="Product Photo Preview" style="max-width: 200px; max-height: 200px; border-radius: 8px; margin-top: 10px;"></div>+</div><div class="form-group">@@ -505,6 +489,18 @@<input type="file" id="invoice" name="invoice" class="file-input" accept=".pdf,.png,.jpg,.jpeg"></div><div id="fileName" class="file-name"></div>+ <!-- Paperless Browse Button -->+ <div id="invoicePaperlessBrowse" class="paperless-browse-section" style="display: none;">+ <button type="button" class="btn btn-secondary btn-sm" onclick="openPaperlessBrowser('invoice')">+ <i class="fas fa-search"></i> Browse Paperless-ngx Documents+ </button>+ <div id="selectedInvoiceFromPaperless" class="selected-paperless-doc" style="display: none;">+ <span class="selected-doc-name"></span>+ <button type="button" class="btn btn-danger btn-xs" onclick="clearPaperlessSelection('invoice')">+ <i class="fas fa-times"></i>+ </button>+ </div>+ </div></div><div class="form-group">@@ -533,26 +529,21 @@<input type="file" id="manual" name="manual" class="file-input" accept=".pdf,.png,.jpg,.jpeg"></div><div id="manualFileName" class="file-name"></div>+ <!-- Paperless Browse Button -->+ <div id="manualPaperlessBrowse" class="paperless-browse-section" style="display: none;">+ <button type="button" class="btn btn-secondary btn-sm" onclick="openPaperlessBrowser('manual')">+ <i class="fas fa-search"></i> Browse Paperless-ngx Documents+ </button>+ <div id="selectedManualFromPaperless" class="selected-paperless-doc" style="display: none;">+ <span class="selected-doc-name"></span>+ <button type="button" class="btn btn-danger btn-xs" onclick="clearPaperlessSelection('manual')">+ <i class="fas fa-times"></i>+ </button>+ </div>+ </div></div><div class="form-group"><label>Files (ZIP/RAR, Optional)</label>- <!-- Storage Selection -->- <div id="otherDocumentStorageSelection" class="storage-selection" style="display: none;">- <div class="storage-options">- <label class="storage-option">- <input type="radio" name="otherDocumentStorage" value="local" checked>- <span class="storage-label">- <i class="fas fa-hdd"></i> Store Locally- </span>- </label>- <label class="storage-option">- <input type="radio" name="otherDocumentStorage" value="paperless">- <span class="storage-label">- <i class="fas fa-cloud"></i> Store in Paperless-ngx- </span>- </label>- </div>- </div><div class="file-input-wrapper"><label for="otherDocument" class="file-input-label"><i class="fas fa-upload"></i> Choose File@@ -560,6 +551,7 @@<input type="file" id="otherDocument" name="other_document" class="file-input" accept=".zip,.rar"></div><div id="otherDocumentFileName" class="file-name"></div>+</div></div><!-- Tags Tab -->@@ -834,23 +826,6 @@<div class="edit-tab-content" id="edit-documents"><div class="form-group"><label>Product Photo (Optional)</label>- <!-- Storage Selection -->- <div id="editProductPhotoStorageSelection" class="storage-selection" style="display: none;">- <div class="storage-options">- <label class="storage-option">- <input type="radio" name="editProductPhotoStorage" value="local" checked>- <span class="storage-label">- <i class="fas fa-hdd"></i> Store Locally- </span>- </label>- <label class="storage-option">- <input type="radio" name="editProductPhotoStorage" value="paperless">- <span class="storage-label">- <i class="fas fa-cloud"></i> Store in Paperless-ngx- </span>- </label>- </div>- </div><div class="file-input-wrapper"><label for="editProductPhoto" class="file-input-label"><i class="fas fa-camera"></i> Choose Photo@@ -863,6 +838,7 @@</div><div id="currentProductPhoto" class="mt-10"></div><button type="button" id="deleteProductPhotoBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Photo</button>+</div><div class="form-group">@@ -893,6 +869,18 @@<div id="editFileName" class="file-name"></div><div id="currentInvoice" class="mt-10"></div><button type="button" id="deleteInvoiceBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Invoice</button>+ <!-- Paperless Browse Button -->+ <div id="editInvoicePaperlessBrowse" class="paperless-browse-section" style="display: none;">+ <button type="button" class="btn btn-secondary btn-sm" onclick="openPaperlessBrowser('edit_invoice')">+ <i class="fas fa-search"></i> Browse Paperless-ngx Documents+ </button>+ <div id="selectedEditInvoiceFromPaperless" class="selected-paperless-doc" style="display: none;">+ <span class="selected-doc-name"></span>+ <button type="button" class="btn btn-danger btn-xs" onclick="clearPaperlessSelection('edit_invoice')">+ <i class="fas fa-times"></i>+ </button>+ </div>+ </div></div><div class="form-group">@@ -923,26 +911,21 @@<div id="editManualFileName" class="file-name"></div><div id="currentManual" class="mt-10"></div><button type="button" id="deleteManualBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Manual</button>+ <!-- Paperless Browse Button -->+ <div id="editManualPaperlessBrowse" class="paperless-browse-section" style="display: none;">+ <button type="button" class="btn btn-secondary btn-sm" onclick="openPaperlessBrowser('edit_manual')">+ <i class="fas fa-search"></i> Browse Paperless-ngx Documents+ </button>+ <div id="selectedEditManualFromPaperless" class="selected-paperless-doc" style="display: none;">+ <span class="selected-doc-name"></span>+ <button type="button" class="btn btn-danger btn-xs" onclick="clearPaperlessSelection('edit_manual')">+ <i class="fas fa-times"></i>+ </button>+ </div>+ </div></div><div class="form-group"><label>Files (ZIP/RAR, Optional)</label>- <!-- Storage Selection -->- <div id="editOtherDocumentStorageSelection" class="storage-selection" style="display: none;">- <div class="storage-options">- <label class="storage-option">- <input type="radio" name="editOtherDocumentStorage" value="local" checked>- <span class="storage-label">- <i class="fas fa-hdd"></i> Store Locally- </span>- </label>- <label class="storage-option">- <input type="radio" name="editOtherDocumentStorage" value="paperless">- <span class="storage-label">- <i class="fas fa-cloud"></i> Store in Paperless-ngx- </span>- </label>- </div>- </div><div class="file-input-wrapper"><label for="editOtherDocument" class="file-input-label"><i class="fas fa-upload"></i> Choose File@@ -952,6 +935,7 @@<div id="editOtherDocumentFileName" class="file-name"></div><div id="currentOtherDocument" class="mt-10"></div><button type="button" id="deleteOtherDocumentBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Files</button>+</div></div>@@ -1033,6 +1017,63 @@</div></div>+ <!-- Paperless Document Browser Modal -->+ <div id="paperlessBrowserModal" class="modal-backdrop">+ <div class="modal modal-large">+ <div class="modal-header">+ <h3 class="modal-title">Browse Paperless-ngx Documents</h3>+ <button class="close-btn" data-dismiss="modal">×</button>+ </div>+ <div class="modal-body">+ <div class="paperless-browser-controls">+ <div class="search-section">+ <input type="text" id="paperlessSearchInput" class="form-control" placeholder="Search documents by title, content, or tags...">+ <button type="button" class="btn btn-primary" id="paperlessSearchBtn">+ <i class="fas fa-search"></i> Search+ </button>+ <button type="button" class="btn btn-secondary" id="paperlessShowAllBtn">+ <i class="fas fa-list"></i> Show All+ </button>+ </div>+ <div class="filter-section">+ <select id="paperlessTypeFilter" class="form-control">+ <option value="">All Document Types</option>+ <option value="application/pdf">PDF Documents</option>+ <option value="image/jpeg,image/jpg,image/png">Images</option>+ <option value="application/zip">Archives</option>+ </select>+ <select id="paperlessTagFilter" class="form-control">+ <option value="">All Tags</option>+ <!-- Tags will be populated dynamically -->+ </select>+ </div>+ </div>++ <div id="paperlessDocumentsList" class="paperless-documents-list">+ <div class="loading-message" style="text-align: center; padding: 20px;">+ <i class="fas fa-spinner fa-spin"></i> Loading documents...+ </div>+ </div>++ <div class="pagination-controls" id="paperlessPagination" style="display: none;">+ <button type="button" class="btn btn-secondary" id="prevPageBtn" onclick="changePage(-1)">+ <i class="fas fa-chevron-left"></i> Previous+ </button>+ <span id="pageInfo">Page 1 of 1</span>+ <button type="button" class="btn btn-secondary" id="nextPageBtn" onclick="changePage(1)">+ Next <i class="fas fa-chevron-right"></i>+ </button>+ </div>+ </div>+ <div class="modal-footer">+ <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>+ <button id="selectPaperlessDocBtn" class="btn btn-primary" style="display: none;">+ <i class="fas fa-check"></i> Select Document+ </button>+ </div>+ </div>+ </div>+<!-- Toast Container --><div id="toastContainer" class="toast-container"></div>@@ -1042,7 +1083,7 @@</div><script src="auth.js"></script>- <script src="script.js?v=20250617007"></script>+ <script src="script.js?v=20250617018"></script><!-- Footer Width Fix --><script src="footer-fix.js"></script>diff --git a/frontend/script.js b/frontend/script.jsindex 3678ec0..30601c5 100644--- a/frontend/script.js+++ b/frontend/script.js@@ -5,6 +5,7 @@ console.log('[DEBUG] script.js loaded and running');// Global variableslet warranties = [];+let warrantiesLoaded = false; // Track if warranties have been loaded from APIlet currentTabIndex = 0;let tabContents = []; // Initialize as empty arraylet editMode = false;@@ -553,6 +554,9 @@ document.addEventListener('DOMContentLoaded', function() {await loadTags(); // Ensure all available tags are loadedawait loadCurrencies(); // Load currencies for dropdowns+ // Initialize Paperless-ngx integration+ await initPaperlessNgxIntegration();+// Initialize view controls for all usersinitViewControls();@@ -622,6 +626,19 @@ let expiringSoonDays = 30; // Default value, will be updated from user preferenc// API URLconst API_URL = '/api/warranties';+// Utility function to escape HTML+function escapeHtml(text) {+ if (typeof text !== 'string') return text;+ const map = {+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ "'": '''+ };+ return text.replace(/[&<>"']/g, function(m) { return map[m]; });+}+// Form tab navigation variables (simplified)let formTabs = []; // Changed from const to let, initialized as empty// Removed const formTabsElements = document.querySelectorAll('.form-tab');@@ -1388,8 +1405,8 @@ async function switchView(viewType, saveToApi = true) { // Added saveToApi paramtableViewHeader.classList.toggle('visible', viewType === 'table');}- // Re-render warranties only if warrantiesList exists- if (warrantiesList) {+ // Re-render warranties only if warrantiesList exists AND warranties have been loaded from API+ if (warrantiesList && warrantiesLoaded) {renderWarranties(filterWarranties()); // Assuming filterWarranties() returns the correct array}}@@ -1730,6 +1747,10 @@ async function loadWarranties(isAuthenticated) { // Added isAuthenticated parametry {console.log('[DEBUG] Entered loadWarranties, isAuthenticated:', isAuthenticated);++ // Reset the flag when starting to load warranties+ warrantiesLoaded = false;+showLoading();// Fetch user preferences (including date format) before loading warranties@@ -1858,6 +1879,9 @@ async function loadWarranties(isAuthenticated) { // Added isAuthenticated parameconsole.log('[DEBUG] Total warranties loaded:', warranties.length);console.log('[DEBUG] Warranty IDs loaded:', warranties.map(w => w.id));+ // Set flag to indicate warranties have been loaded from API+ warrantiesLoaded = true;+if (warranties.length === 0) {console.log('No warranties found, showing empty state');renderEmptyState('No warranties found. Add your first warranty using the form.');@@ -1873,6 +1897,7 @@ async function loadWarranties(isAuthenticated) { // Added isAuthenticated parame}} catch (error) {console.error('[DEBUG] Error loading warranties:', error);+ warrantiesLoaded = false; // Reset flag on errorrenderEmptyState('Error loading warranties. Please try again later.');} finally {hideLoading();@@ -2211,21 +2236,22 @@ async function renderWarranties(warrantiesToRender) {${photoThumbnailHtml}<div class="warranty-info">${userInfoHtml}- <div>Purchased: <span>${formatDate(purchaseDate)}</span></div>- <div>Age: <span>${productAge}</span></div>- <div>Warranty: <span>${warrantyDurationText}</span></div>- <div>Expires: <span>${expirationDateText}</span></div>- ${warranty.purchase_price ? `<div><span>Price: </span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</div>` : ''}- ${warranty.vendor ? `<div>Vendor: <span>${warranty.vendor}</span></div>` : ''}- ${warranty.warranty_type ? `<div>Type: <span>${warranty.warranty_type}</span></div>` : ''}+ <div><i class="fas fa-calendar"></i> Age: <span>${productAge}</span></div>+ <div><i class="fas fa-file-alt"></i> Warranty: <span>${warrantyDurationText}</span></div>+ <div><i class="fas fa-wrench"></i> Warranty Ends: <span>${expirationDateText}</span></div>+ ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> Price: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}${validSerialNumbers.length > 0 ? `- <div class="serial-numbers">- <strong>Serial Numbers:</strong>- <ul>- ${validSerialNumbers.map(sn => `<li>${sn}</li>`).join('')}- </ul>- </div>+ <div><i class="fas fa-barcode"></i> Serial Number: <span>${validSerialNumbers[0]}</span></div>+ ${validSerialNumbers.length > 1 ? `+ <div style="margin-left: 28px;">+ <ul style="margin-top: 5px;">+ ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}+ </ul>+ </div>+ ` : ''}` : ''}+ ${warranty.vendor ? `<div><i class="fas fa-store"></i> Vendor: <span>${warranty.vendor}</span></div>` : ''}+ ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> Type: <span>${warranty.warranty_type}</span></div>` : ''}</div></div><div class="warranty-status-row status-${statusClass}">@@ -2252,7 +2278,7 @@ async function renderWarranties(warrantiesToRender) {<div class="product-photo-thumbnail"><a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image"><img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"- style="width: 70px; height: 70px; object-fit: cover; border-radius: 6px; border: 2px solid var(--border-color); cursor: pointer;"+ style="width: 180px; height: 180px; object-fit: cover; border-radius: 6px; border: 2px solid var(--border-color); cursor: pointer;"onerror="this.style.display='none'" class="secure-image"></a></div>@@ -2269,21 +2295,22 @@ async function renderWarranties(warrantiesToRender) {${photoThumbnailHtml}<div class="warranty-info">${userInfoHtml}- <div>Purchased: <span>${formatDate(purchaseDate)}</span></div>- <div>Age: <span>${productAge}</span></div>- <div>Warranty: <span>${warrantyDurationText}</span></div>- <div>Expires: <span>${expirationDateText}</span></div>- ${warranty.purchase_price ? `<div><span>Price: </span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</div>` : ''}- ${warranty.vendor ? `<div>Vendor: <span>${warranty.vendor}</span></div>` : ''}- ${warranty.warranty_type ? `<div>Type: <span>${warranty.warranty_type}</span></div>` : ''}+ <div><i class="fas fa-calendar"></i> Age: <span>${productAge}</span></div>+ <div><i class="fas fa-file-alt"></i> Warranty: <span>${warrantyDurationText}</span></div>+ <div><i class="fas fa-wrench"></i> Warranty Ends: <span>${expirationDateText}</span></div>+ ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> Price: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}${validSerialNumbers.length > 0 ? `- <div class="serial-numbers">- <strong>Serial Numbers:</strong>- <ul>- ${validSerialNumbers.map(sn => `<li>${sn}</li>`).join('')}- </ul>- </div>+ <div><i class="fas fa-barcode"></i> Serial Number: <span>${validSerialNumbers[0]}</span></div>+ ${validSerialNumbers.length > 1 ? `+ <div style="margin-left: 28px;">+ <ul style="margin-top: 5px;">+ ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}+ </ul>+ </div>+ ` : ''}` : ''}+ ${warranty.vendor ? `<div><i class="fas fa-store"></i> Vendor: <span>${warranty.vendor}</span></div>` : ''}+ ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> Type: <span>${warranty.warranty_type}</span></div>` : ''}</div></div><div class="warranty-status-row status-${statusClass}">@@ -2327,10 +2354,22 @@ async function renderWarranties(warrantiesToRender) {${photoThumbnailHtml}<div class="warranty-info">${userInfoHtml}- <div>Purchased: <span>${formatDate(purchaseDate)}</span></div>- <div>Age: <span>${productAge}</span></div>- <div>Expires: <span>${expirationDateText}</span></div>- ${warranty.purchase_price ? `<div><span>Price: </span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</div>` : ''}+ <div><i class="fas fa-calendar"></i> Age: <span>${productAge}</span></div>+ <div><i class="fas fa-file-alt"></i> Warranty: <span>${warrantyDurationText}</span></div>+ <div><i class="fas fa-wrench"></i> Warranty Ends: <span>${expirationDateText}</span></div>+ ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> Price: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}+ ${validSerialNumbers.length > 0 ? `+ <div><i class="fas fa-barcode"></i> Serial Number: <span>${validSerialNumbers[0]}</span></div>+ ${validSerialNumbers.length > 1 ? `+ <div style="margin-left: 28px;">+ <ul style="margin-top: 5px;">+ ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}+ </ul>+ </div>+ ` : ''}+ ` : ''}+ ${warranty.vendor ? `<div><i class="fas fa-store"></i> Vendor: <span>${warranty.vendor}</span></div>` : ''}+ ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> Type: <span>${warranty.warranty_type}</span></div>` : ''}</div></div><div class="warranty-status-row status-${statusClass}">@@ -2809,6 +2848,52 @@ async function openEditModal(warranty) {editPhotoPreview.style.display = 'none';}+ // Set storage options based on current document storage+ if (paperlessNgxEnabled) {+ // Set product photo storage option+ const editProductPhotoStorageRadios = document.getElementsByName('editProductPhotoStorage');+ if (editProductPhotoStorageRadios.length > 0) {+ const isPaperlessPhoto = warranty.paperless_photo_id && warranty.paperless_photo_id !== null;+ editProductPhotoStorageRadios.forEach(radio => {+ radio.checked = isPaperlessPhoto ? (radio.value === 'paperless') : (radio.value === 'local');+ });+ }++ // Set invoice storage option+ const editInvoiceStorageRadios = document.getElementsByName('editInvoiceStorage');+ if (editInvoiceStorageRadios.length > 0) {+ const isPaperlessInvoice = warranty.paperless_invoice_id && warranty.paperless_invoice_id !== null;+ editInvoiceStorageRadios.forEach(radio => {+ radio.checked = isPaperlessInvoice ? (radio.value === 'paperless') : (radio.value === 'local');+ });+ }++ // Set manual storage option+ const editManualStorageRadios = document.getElementsByName('editManualStorage');+ if (editManualStorageRadios.length > 0) {+ const isPaperlessManual = warranty.paperless_manual_id && warranty.paperless_manual_id !== null;+ editManualStorageRadios.forEach(radio => {+ radio.checked = isPaperlessManual ? (radio.value === 'paperless') : (radio.value === 'local');+ });+ }++ // Set other document storage option+ const editOtherDocumentStorageRadios = document.getElementsByName('editOtherDocumentStorage');+ if (editOtherDocumentStorageRadios.length > 0) {+ const isPaperlessOther = warranty.paperless_other_id && warranty.paperless_other_id !== null;+ editOtherDocumentStorageRadios.forEach(radio => {+ radio.checked = isPaperlessOther ? (radio.value === 'paperless') : (radio.value === 'local');+ });+ }++ console.log('[Edit Modal] Storage options set based on current document storage:', {+ photo: warranty.paperless_photo_id ? 'paperless' : 'local',+ invoice: warranty.paperless_invoice_id ? 'paperless' : 'local',+ manual: warranty.paperless_manual_id ? 'paperless' : 'local',+ other: warranty.paperless_other_id ? 'paperless' : 'local'+ });+ }+// Initialize file input event listenersconst editProductPhotoInput = document.getElementById('editProductPhoto');if (editProductPhotoInput) {@@ -3211,6 +3296,25 @@ function handleFormSubmit(event) { // Renamed from submitFormformData.append('other_document', otherDocumentFile);}+ // Add selected Paperless documents+ const selectedPaperlessProductPhoto = document.getElementById('selectedPaperlessProductPhoto');+ const selectedPaperlessInvoice = document.getElementById('selectedPaperlessInvoice');+ const selectedPaperlessManual = document.getElementById('selectedPaperlessManual');+ const selectedPaperlessOtherDocument = document.getElementById('selectedPaperlessOtherDocument');++ if (selectedPaperlessProductPhoto && selectedPaperlessProductPhoto.value) {+ formData.append('paperless_photo_id', selectedPaperlessProductPhoto.value);+ }+ if (selectedPaperlessInvoice && selectedPaperlessInvoice.value) {+ formData.append('paperless_invoice_id', selectedPaperlessInvoice.value);+ }+ if (selectedPaperlessManual && selectedPaperlessManual.value) {+ formData.append('paperless_manual_id', selectedPaperlessManual.value);+ }+ if (selectedPaperlessOtherDocument && selectedPaperlessOtherDocument.value) {+ formData.append('paperless_other_id', selectedPaperlessOtherDocument.value);+ }+// Show loading spinnershowLoadingSpinner();@@ -3243,6 +3347,9 @@ function handleFormSubmit(event) { // Renamed from submitFormhideLoadingSpinner();showToast('Warranty added successfully', 'success');+ // Store the new warranty ID for auto-linking+ const newWarrantyId = data.id;+// --- Close and reset the modal on success ---if (addWarrantyModal) {addWarrantyModal.classList.remove('active');@@ -3258,6 +3365,25 @@ function handleFormSubmit(event) { // Renamed from submitFormconsole.log('Loading secure images for new warranty cards');loadSecureImages();}, 200); // Slightly longer delay to ensure everything is rendered++ // Auto-link any documents that were uploaded to Paperless-ngx+ const invoiceFile = document.getElementById('invoice').files[0];+ const manualFile = document.getElementById('manual').files[0];+ const otherDocumentFile = document.getElementById('otherDocument').files[0];++ if ((invoiceFile || manualFile || otherDocumentFile) && newWarrantyId) {+ console.log('[Auto-Link] Starting automatic document linking after warranty creation');++ // Collect filename information for intelligent searching+ const fileInfo = {};+ if (invoiceFile) fileInfo.invoice = invoiceFile.name;+ if (manualFile) fileInfo.manual = manualFile.name;+ if (otherDocumentFile) fileInfo.other = otherDocumentFile.name;++ setTimeout(() => {+ autoLinkRecentDocuments(newWarrantyId, ['invoice', 'manual', 'other'], 10, 10000, fileInfo);+ }, 3000); // Wait 3 seconds for Paperless-ngx to process the documents+ }}).catch(error => {console.error('Error reloading warranties after adding:', error);}); // Reload the list and update UI@@ -4547,6 +4673,162 @@ function hideLoadingSpinner() {}}+// Paperless upload loading functions+function showPaperlessUploadLoading(documentType) {+ // Create or show the Paperless upload overlay+ let overlay = document.getElementById('paperless-upload-overlay');+ if (!overlay) {+ overlay = document.createElement('div');+ overlay.id = 'paperless-upload-overlay';+ overlay.innerHTML = `+ <div class="paperless-upload-modal">+ <div class="paperless-upload-content">+ <div class="paperless-upload-spinner"></div>+ <h3>Uploading to Paperless-ngx</h3>+ <p id="paperless-upload-status">Uploading document...</p>+ <div class="paperless-upload-progress">+ <div class="paperless-upload-progress-bar" id="paperless-progress-bar"></div>+ </div>+ </div>+ </div>+ `;+ document.body.appendChild(overlay);++ // Add CSS styles+ const style = document.createElement('style');+ style.textContent = `+ #paperless-upload-overlay {+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ background: rgba(0, 0, 0, 0.7);+ display: flex;+ justify-content: center;+ align-items: center;+ z-index: 10000;+ backdrop-filter: blur(2px);+ }++ .paperless-upload-modal {+ background: var(--card-bg, #fff);+ border-radius: 12px;+ padding: 2rem;+ max-width: 400px;+ width: 90%;+ text-align: center;+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);+ border: 1px solid var(--border-color, #ddd);+ }++ .paperless-upload-content h3 {+ margin: 1rem 0 0.5rem 0;+ color: var(--text-color, #333);+ font-size: 1.2rem;+ }++ .paperless-upload-content p {+ margin: 0.5rem 0 1.5rem 0;+ color: var(--text-secondary, #666);+ font-size: 0.9rem;+ }++ .paperless-upload-spinner {+ width: 40px;+ height: 40px;+ border: 4px solid var(--border-color, #ddd);+ border-top: 4px solid var(--primary-color, #007bff);+ border-radius: 50%;+ animation: paperless-spin 1s linear infinite;+ margin: 0 auto 1rem auto;+ }++ @keyframes paperless-spin {+ 0% { transform: rotate(0deg); }+ 100% { transform: rotate(360deg); }+ }++ .paperless-upload-progress {+ width: 100%;+ height: 6px;+ background: var(--border-color, #ddd);+ border-radius: 3px;+ overflow: hidden;+ margin-top: 1rem;+ }++ .paperless-upload-progress-bar {+ height: 100%;+ background: linear-gradient(90deg, var(--primary-color, #007bff), var(--success-color, #28a745));+ border-radius: 3px;+ width: 0%;+ transition: width 0.3s ease;+ animation: paperless-progress-pulse 2s ease-in-out infinite;+ }++ @keyframes paperless-progress-pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.7; }+ }+ `;+ document.head.appendChild(style);+ }++ overlay.style.display = 'flex';++ // Update status text+ const statusEl = document.getElementById('paperless-upload-status');+ if (statusEl) {+ statusEl.textContent = `Uploading ${documentType} to Paperless-ngx...`;+ }++ // Animate progress bar+ const progressBar = document.getElementById('paperless-progress-bar');+ if (progressBar) {+ progressBar.style.width = '30%';+ setTimeout(() => {+ progressBar.style.width = '60%';+ }, 1000);+ setTimeout(() => {+ progressBar.style.width = '80%';+ }, 2000);+ }+}++function updatePaperlessUploadStatus(message, isProcessing = false) {+ const statusEl = document.getElementById('paperless-upload-status');+ const progressBar = document.getElementById('paperless-progress-bar');++ if (statusEl) {+ statusEl.textContent = message;+ }++ if (isProcessing && progressBar) {+ progressBar.style.width = '90%';+ }+}++function hidePaperlessUploadLoading() {+ const overlay = document.getElementById('paperless-upload-overlay');+ if (overlay) {+ // Complete the progress bar first+ const progressBar = document.getElementById('paperless-progress-bar');+ if (progressBar) {+ progressBar.style.width = '100%';+ }++ // Hide after a short delay to show completion+ setTimeout(() => {+ overlay.style.display = 'none';+ // Reset progress bar for next use+ if (progressBar) {+ progressBar.style.width = '0%';+ }+ }, 500);+ }+}+// Delete warranty functionfunction deleteWarranty() {if (!currentWarrantyId) {@@ -4791,6 +5073,25 @@ function saveWarranty() {}formData.append('warranty_type', warrantyTypeValue);+ // Add selected Paperless documents for edit form+ const selectedEditPaperlessProductPhoto = document.getElementById('selectedEditPaperlessProductPhoto');+ const selectedEditPaperlessInvoice = document.getElementById('selectedEditPaperlessInvoice');+ const selectedEditPaperlessManual = document.getElementById('selectedEditPaperlessManual');+ const selectedEditPaperlessOtherDocument = document.getElementById('selectedEditPaperlessOtherDocument');++ if (selectedEditPaperlessProductPhoto && selectedEditPaperlessProductPhoto.value) {+ formData.append('paperless_photo_id', selectedEditPaperlessProductPhoto.value);+ }+ if (selectedEditPaperlessInvoice && selectedEditPaperlessInvoice.value) {+ formData.append('paperless_invoice_id', selectedEditPaperlessInvoice.value);+ }+ if (selectedEditPaperlessManual && selectedEditPaperlessManual.value) {+ formData.append('paperless_manual_id', selectedEditPaperlessManual.value);+ }+ if (selectedEditPaperlessOtherDocument && selectedEditPaperlessOtherDocument.value) {+ formData.append('paperless_other_id', selectedEditPaperlessOtherDocument.value);+ }+// DEBUG: Log what we're sending to the backendconsole.log('[DEBUG saveWarranty] Form data being sent:');console.log('[DEBUG saveWarranty] isLifetime:', isLifetime);@@ -4860,6 +5161,21 @@ function saveWarranty() {}console.log('Warranty updated and reloaded from server');++ // Auto-link any documents that were uploaded to Paperless-ngx+ if ((invoiceFile || manualFile || otherDocumentFile) && currentWarrantyId) {+ console.log('[Auto-Link] Starting automatic document linking after warranty update');++ // Collect filename information for intelligent searching+ const fileInfo = {};+ if (invoiceFile) fileInfo.invoice = invoiceFile.name;+ if (manualFile) fileInfo.manual = manualFile.name;+ if (otherDocumentFile) fileInfo.other = otherDocumentFile.name;++ setTimeout(() => {+ autoLinkRecentDocuments(currentWarrantyId, ['invoice', 'manual', 'other'], 10, 10000, fileInfo);+ }, 3000); // Wait 3 seconds for Paperless-ngx to process the documents+ }}).catch(error => {console.error('Error reloading warranties after edit:', error);});@@ -5071,6 +5387,10 @@ function resetAddWarrantyWizard() {if (manualFileName) manualFileName.textContent = '';if (otherDocumentFileName) otherDocumentFileName.textContent = '';+ // Clear Paperless document selections (only for invoice and manual)+ clearPaperlessSelection('invoice');+ clearPaperlessSelection('manual');+// Reset selected tagsselectedTags = [];console.log('Resetting Add Warranty Wizard...');@@ -6214,6 +6534,7 @@ async function checkPaperlessNgxStatus() {if (response.ok) {const settings = await response.json();paperlessNgxEnabled = settings.paperless_enabled === 'true';+ window.paperlessNgxEnabled = paperlessNgxEnabled; // Set global variableconsole.log('[Paperless-ngx] Integration status:', paperlessNgxEnabled);return paperlessNgxEnabled;}@@ -6237,12 +6558,10 @@ async function initPaperlessNgxIntegration() {infoAlert.style.display = 'block';}- // Show storage selection options for add modal+ // Show storage selection options for add modal (only invoice and manual)const storageSelections = [- 'productPhotoStorageSelection','invoiceStorageSelection',- 'manualStorageSelection',- 'otherDocumentStorageSelection'+ 'manualStorageSelection'];storageSelections.forEach(id => {@@ -6252,12 +6571,10 @@ async function initPaperlessNgxIntegration() {}});- // Show storage selection options for edit modal+ // Show storage selection options for edit modal (only invoice and manual)const editStorageSelections = [- 'editProductPhotoStorageSelection','editInvoiceStorageSelection',- 'editManualStorageSelection',- 'editOtherDocumentStorageSelection'+ 'editManualStorageSelection'];editStorageSelections.forEach(id => {@@ -6267,9 +6584,17 @@ async function initPaperlessNgxIntegration() {}});+ // Show Paperless browse sections+ console.log('[Paperless-ngx] Calling togglePaperlessBrowseSections...');+ togglePaperlessBrowseSections();+console.log('[Paperless-ngx] UI elements initialized and shown');} else {console.log('[Paperless-ngx] Integration disabled, hiding UI elements');++ // Hide Paperless browse sections+ console.log('[Paperless-ngx] Calling togglePaperlessBrowseSections (disabled)...');+ togglePaperlessBrowseSections();}}@@ -6280,6 +6605,13 @@ async function initPaperlessNgxIntegration() {* @returns {string} - 'local' or 'paperless'*/function getStorageOption(documentType, isEdit = false) {+ // Only allow Paperless-ngx storage for invoices and manuals+ const paperlessAllowedTypes = ['invoice', 'manual'];++ if (!paperlessAllowedTypes.includes(documentType)) {+ return 'local'; // Force local storage for productPhoto and otherDocument+ }+const prefix = isEdit ? 'edit' : '';const capitalizedType = documentType.charAt(0).toUpperCase() + documentType.slice(1);const name = `${prefix}${capitalizedType}Storage`;@@ -6300,6 +6632,9 @@ async function uploadToPaperlessNgx(file, documentType) {throw new Error('Authentication token not available');}+ // Show upload loading screen+ showPaperlessUploadLoading(documentType);+const formData = new FormData();formData.append('file', file);formData.append('document_type', documentType);@@ -6315,6 +6650,8 @@ async function uploadToPaperlessNgx(file, documentType) {console.log(' - title:', `Warracker ${documentType} - ${file.name}`);console.log(' - tags:', tags.join(','));+ updatePaperlessUploadStatus('Uploading file to Paperless-ngx...');+const response = await fetch('/api/paperless/upload', {method: 'POST',headers: {@@ -6333,12 +6670,20 @@ async function uploadToPaperlessNgx(file, documentType) {console.error('[Paperless-ngx] Could not parse error response:', parseError);errorMessage = `HTTP ${response.status}: ${response.statusText}`;}+ hidePaperlessUploadLoading();throw new Error(errorMessage);}const result = await response.json();console.log('[Paperless-ngx] Upload successful:', result);+ // Update status based on result+ if (result.document_id) {+ updatePaperlessUploadStatus('Document uploaded and ready!');+ } else {+ updatePaperlessUploadStatus('Document uploaded, processing...', true);+ }+return {success: true,document_id: result.document_id,@@ -6347,6 +6692,7 @@ async function uploadToPaperlessNgx(file, documentType) {} catch (error) {console.error('[Paperless-ngx] Upload error:', error);+ hidePaperlessUploadLoading();return {success: false,error: error.message@@ -6364,7 +6710,8 @@ async function processPaperlessNgxUploads(formData) {}const uploads = {};- const documentTypes = ['productPhoto', 'invoice', 'manual', 'otherDocument'];+ // Only process invoice and manual for Paperless-ngx uploads+ const documentTypes = ['invoice', 'manual'];for (const docType of documentTypes) {const storageOption = getStorageOption(docType);@@ -6389,16 +6736,24 @@ async function processPaperlessNgxUploads(formData) {};const dbField = fieldMapping[docType];- if (dbField) {+ if (dbField && uploadResult.document_id) {+ // Only store the ID if we actually got a document ID (not a task ID)uploads[dbField] = uploadResult.document_id;+ console.log(`[Paperless-ngx] ${docType} uploaded successfully, ID: ${uploadResult.document_id}, stored as: ${dbField}`);+ // Hide loading screen immediately for direct uploads+ hidePaperlessUploadLoading();+ } else if (dbField && !uploadResult.document_id) {+ console.log(`[Paperless-ngx] ${docType} uploaded successfully but no document ID received (async processing). Not storing reference.`);+ // Don't hide loading screen yet - auto-link will handle it+ updatePaperlessUploadStatus('Document processing, searching for link...', true);}- // Remove the file from FormData since it's stored in Paperless-ngx+ // ALWAYS remove the file from FormData since it's been uploaded to Paperless-ngx+ // This prevents the backend from also saving it locallyif (formData.has(docType)) {formData.delete(docType);+ console.log(`[Paperless-ngx] Removed ${docType} from FormData to prevent local storage`);}-- console.log(`[Paperless-ngx] ${docType} uploaded successfully, ID: ${uploadResult.document_id}, stored as: ${dbField}`);} else {throw new Error(`Failed to upload ${docType} to Paperless-ngx: ${uploadResult.error}`);}@@ -6419,7 +6774,8 @@ async function processEditPaperlessNgxUploads(formData) {}const uploads = {};- const documentTypes = ['productPhoto', 'invoice', 'manual', 'otherDocument'];+ // Only process invoice and manual for Paperless-ngx uploads+ const documentTypes = ['invoice', 'manual'];for (const docType of documentTypes) {const storageOption = getStorageOption(docType, true); // true for edit modal@@ -6444,17 +6800,25 @@ async function processEditPaperlessNgxUploads(formData) {};const dbField = fieldMapping[docType];- if (dbField) {+ if (dbField && uploadResult.document_id) {+ // Only store the ID if we actually got a document ID (not a task ID)uploads[dbField] = uploadResult.document_id;+ console.log(`[Paperless-ngx] ${docType} uploaded successfully (edit), ID: ${uploadResult.document_id}, stored as: ${dbField}`);+ // Hide loading screen immediately for direct uploads+ hidePaperlessUploadLoading();+ } else if (dbField && !uploadResult.document_id) {+ console.log(`[Paperless-ngx] ${docType} uploaded successfully (edit) but no document ID received (async processing). Not storing reference.`);+ // Don't hide loading screen yet - auto-link will handle it+ updatePaperlessUploadStatus('Document processing, searching for link...', true);}- // Remove the file from FormData since it's stored in Paperless-ngx- const editFieldName = `edit${docType.charAt(0).toUpperCase() + docType.slice(1)}`;- if (formData.has(editFieldName)) {- formData.delete(editFieldName);+ // ALWAYS remove the file from FormData since it's been uploaded to Paperless-ngx+ // This prevents the backend from also saving it locally+ // Note: In edit mode, the form field names don't have 'edit' prefix in FormData+ if (formData.has(docType)) {+ formData.delete(docType);+ console.log(`[Paperless-ngx] Removed ${docType} from FormData to prevent local storage`);}-- console.log(`[Paperless-ngx] ${docType} uploaded successfully (edit), ID: ${uploadResult.document_id}, stored as: ${dbField}`);} else {throw new Error(`Failed to upload ${docType} to Paperless-ngx: ${uploadResult.error}`);}@@ -6474,75 +6838,191 @@ document.addEventListener('DOMContentLoaded', function() {});/**- * Open a Paperless-ngx document in a new tab+ * Debug Paperless-ngx configuration+ */+async function debugPaperlessConfiguration() {+ try {+ const token = localStorage.getItem('auth_token');+ if (!token) {+ console.error('[Paperless Debug] No auth token found');+ return null;+ }++ console.log('[Paperless Debug] Checking configuration...');++ const response = await fetch('/api/paperless/debug', {+ method: 'GET',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Content-Type': 'application/json'+ }+ });++ if (!response.ok) {+ console.error('[Paperless Debug] Debug endpoint failed:', response.status, response.statusText);+ const errorText = await response.text();+ console.error('[Paperless Debug] Error response:', errorText);+ return null;+ }++ const result = await response.json();+ console.log('[Paperless Debug] Configuration:', result);++ return result;+ } catch (error) {+ console.error('[Paperless Debug] Error:', error);+ return null;+ }+}++/**+ * Open a Paperless-ngx document either in Warracker interface or in Paperless-ngx directly*/async function openPaperlessDocument(paperlessId) {console.log(`[openPaperlessDocument] Opening Paperless document: ${paperlessId}`);- const token = auth.getToken();+ // First, debug the Paperless configuration+ const debugInfo = await debugPaperlessConfiguration();+ if (debugInfo) {+ console.log('[openPaperlessDocument] Debug info:', debugInfo);++ if (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false') {+ showToast('Paperless-ngx integration is not enabled', 'error');+ return;+ }++ if (!debugInfo.paperless_handler_available) {+ showToast('Paperless-ngx is not properly configured. Please check the settings.', 'error');+ console.error('[openPaperlessDocument] Paperless handler not available');+ if (debugInfo.paperless_handler_error) {+ console.error('[openPaperlessDocument] Handler error:', debugInfo.paperless_handler_error);+ }+ return;+ }++ if (debugInfo.test_connection_result && !debugInfo.test_connection_result.success) {+ showToast(`Paperless-ngx connection failed: ${debugInfo.test_connection_result.message || debugInfo.test_connection_result.error}`, 'error');+ return;+ }+ }++ const token = localStorage.getItem('auth_token');if (!token) {console.error('[openPaperlessDocument] No auth token available');showToast('Authentication required', 'error');return;}- // Retry mechanism for document retrieval- const maxRetries = 3;- const retryDelay = 2000; // 2 seconds+ // Check user preference for viewing documents+ const viewInApp = await getUserPaperlessViewPreference();+ console.log(`[openPaperlessDocument] User preference view in app: ${viewInApp}`);- const fetchWithRetry = async (attempt = 1) => {- try {- console.log(`[openPaperlessDocument] Attempt ${attempt} to fetch: /api/paperless-file/${paperlessId}`);-- const response = await fetch(`/api/paperless-file/${paperlessId}`, {- method: 'GET',- headers: {- 'Authorization': `Bearer ${token}`,- 'Content-Type': 'application/json'- }- });-- if (response.status === 404) {- throw new Error('Document not found in Paperless-ngx.');- }-- if (!response.ok) {- const errorText = await response.text();- throw new Error(`HTTP ${response.status}: ${errorText}`);+ if (viewInApp) {+ // Open document in Warracker interface+ console.log(`[openPaperlessDocument] Opening document ${paperlessId} in Warracker interface`);+ const documentUrl = `/api/paperless-file/${paperlessId}?token=${encodeURIComponent(token)}`;++ const newTab = window.open(documentUrl, '_blank');+ if (!newTab) {+ showToast('Please allow popups to view documents', 'warning');+ } else {+ showToast('Opening document in Warracker...', 'info');+ }+ return;+ }++ // Default behavior: open in Paperless-ngx interface+ try {+ // Get the Paperless-ngx base URL+ const response = await fetch('/api/paperless/url', {+ method: 'GET',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Content-Type': 'application/json'}+ });++ if (!response.ok) {+ const errorText = await response.text();+ console.error('[openPaperlessDocument] URL endpoint failed:', response.status, errorText);+ throw new Error(`Failed to get Paperless-ngx URL: ${response.status}`);+ }++ const result = await response.json();+ if (!result.success) {+ throw new Error(result.message || 'Failed to get Paperless-ngx URL');+ }++ // Construct the direct link to the document in Paperless-ngx+ const paperlessUrl = result.url.replace(/\/$/, ''); // Remove trailing slash+ const documentUrl = `${paperlessUrl}/documents/${paperlessId}/details`;++ console.log(`[openPaperlessDocument] Opening Paperless-ngx document at: ${documentUrl}`);++ // Open the document directly in Paperless-ngx interface+ const newTab = window.open(documentUrl, '_blank');+ if (!newTab) {+ showToast('Please allow popups to view documents in Paperless-ngx', 'warning');+ } else {+ showToast('Opening document in Paperless-ngx...', 'info');+ }++ } catch (error) {+ console.error('Error opening Paperless document:', error);+ showToast(`Error opening document: ${error.message}`, 'error');++ // Try to determine the base URL from debug info for fallback+ if (debugInfo && debugInfo.paperless_url) {+ const fallbackUrl = `${debugInfo.paperless_url.replace(/\/$/, '')}/documents/${paperlessId}/details`;+ console.log(`[openPaperlessDocument] Trying fallback URL: ${fallbackUrl}`);- // Get the blob and create object URL- const blob = await response.blob();- const url = URL.createObjectURL(blob);-- // Open in new tab- const newTab = window.open(url, '_blank');- if (!newTab) {- showToast('Please allow popups to view documents', 'warning');+ const fallbackTab = window.open(fallbackUrl, '_blank');+ if (fallbackTab) {+ showToast('Opened with fallback URL - please check if Paperless-ngx is accessible', 'warning');}+ } else {+ // Last resort fallback+ const genericFallbackUrl = `${window.location.protocol}//${window.location.hostname}:8000/documents/${paperlessId}/details`;+ console.log(`[openPaperlessDocument] Trying generic fallback URL: ${genericFallbackUrl}`);- // Clean up the object URL after a delay- setTimeout(() => URL.revokeObjectURL(url), 10000);-- } catch (error) {- console.error(`[openPaperlessDocument] Attempt ${attempt} failed:`, error);-- if (attempt < maxRetries) {- console.log(`[openPaperlessDocument] Retrying in ${retryDelay}ms...`);- setTimeout(() => fetchWithRetry(attempt + 1), retryDelay);- } else {- console.error(`[openPaperlessDocument] All ${maxRetries} attempts failed`);- showToast(`Failed to open document: ${error.message}`, 'error');+ const genericTab = window.open(genericFallbackUrl, '_blank');+ if (genericTab) {+ showToast('Opened with generic fallback URL', 'warning');}}- };+ }+}++/**+ * Get user preference for viewing Paperless documents in app+ */+async function getUserPaperlessViewPreference() {+ // First check localStorage+ const prefix = getPreferenceKeyPrefix();+ const localPreference = localStorage.getItem(`${prefix}paperlessViewInApp`);+ if (localPreference !== null) {+ return localPreference === 'true';+ }- try {- await fetchWithRetry();- } catch (error) {- console.error('Error fetching Paperless document:', error);- showToast(`Error opening document: ${error.message}`, 'error');+ // If not in localStorage, check API+ 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) {+ const prefs = await response.json();+ return prefs.paperless_view_in_app || false;+ }+ } catch (e) {+ console.warn('Failed to load preferences from API:', e);+ }}++ // Default to false (open in Paperless-ngx)+ return false;}/**@@ -6655,6 +7135,1093 @@ async function cleanupInvalidPaperlessDocuments() {}}-// Make debug and cleanup functions available globally for console testing-window.debugPaperlessDocument = debugPaperlessDocument;-window.cleanupInvalidPaperlessDocuments = cleanupInvalidPaperlessDocuments;+/**+ * Search for and link a Paperless document by title+ * Used when documents were uploaded with async processing and we lost the document ID+ */+async function searchAndLinkPaperlessDocument(warrantyId, documentType, searchTitle) {+ try {+ console.log(`[Paperless-ngx] Searching for document: ${searchTitle}`);++ const response = await fetch('/api/paperless-search-and-link', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`+ },+ body: JSON.stringify({+ warranty_id: warrantyId,+ document_type: documentType,+ search_title: searchTitle+ })+ });++ const result = await response.json();++ if (result.success) {+ console.log(`[Paperless-ngx] Document linked successfully: ID ${result.document_id}`);+ showToast('Document linked successfully! Refreshing...', 'success');++ // Reload warranties to show the updated document links+ setTimeout(async () => {+ console.log('π [Search&Link] Reloading warranties to show updated document links...');+ await loadWarranties(true); // Pass isAuthenticated parameter++ // Force re-render of the warranty cards+ applyFilters();++ // Also reload secure images to update cloud icons+ await loadSecureImages();++ console.log('β [Search&Link] Warranties reloaded and UI updated');+ }, 1000);++ return { success: true, document_id: result.document_id };+ } else {+ console.error(`[Paperless-ngx] Failed to link document: ${result.message}`);+ showToast(`Failed to link document: ${result.message}`, 'error');+ return { success: false, message: result.message };+ }+ } catch (error) {+ console.error(`[Paperless-ngx] Error searching for document:`, error);+ showToast('Error searching for document', 'error');+ return { success: false, message: error.message };+ }+}++/**+ * Automatically search for and link recently uploaded documents+ * This handles the case where Paperless-ngx async processing returns task_id instead of document_id+ */+async function autoLinkRecentDocuments(warrantyId, documentTypes = ['invoice', 'manual'], maxRetries = 10, retryDelay = 10000, fileInfo = {}) {+ console.log(`[Auto-Link] Starting automatic document linking for warranty ${warrantyId}`);++ const token = auth.getToken();+ if (!token) {+ console.error('[Auto-Link] No auth token available');+ return;+ }++ let attempt = 0;+ let linkedDocuments = [];++ const tryLinking = async () => {+ attempt++;+ console.log(`[Auto-Link] Attempt ${attempt}/${maxRetries} for warranty ${warrantyId}`);++ try {+ // First check if Paperless-ngx is properly configured+ const debugInfo = await debugPaperlessConfiguration();+ if (!debugInfo) {+ console.error('[Auto-Link] Could not get Paperless debug info');+ return;+ }++ if (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false') {+ console.log('[Auto-Link] Paperless-ngx integration is not enabled, skipping auto-link');+ return;+ }++ if (!debugInfo.paperless_handler_available) {+ console.error('[Auto-Link] Paperless handler not available:', debugInfo.paperless_handler_error || 'Unknown error');+ return;+ }++ if (debugInfo.test_connection_result && !debugInfo.test_connection_result.success) {+ console.error('[Auto-Link] Paperless connection test failed:', debugInfo.test_connection_result.message || debugInfo.test_connection_result.error);+ return;+ }++ console.log(`[Auto-Link] Using intelligent filename-based search. File info:`, fileInfo);++ // Strategy 1: Search by exact filename (most reliable)+ let candidateDocuments = [];++ for (const [docType, filename] of Object.entries(fileInfo)) {+ if (!documentTypes.includes(docType)) continue;++ console.log(`[Auto-Link] Searching for ${docType} with filename: "${filename}"`);++ // Remove file extension for searching+ const baseFilename = filename.replace(/\.[^/.]+$/, '');++ // Try multiple search strategies+ const searchQueries = [+ filename, // Exact filename with extension+ baseFilename, // Filename without extension+ `"${filename}"`, // Quoted exact match+ `"${baseFilename}"`, // Quoted base filename+ `Warracker ${docType} - ${baseFilename}` // Warracker format+ ];++ for (const query of searchQueries) {+ try {+ console.log(`[Auto-Link] Trying search query: "${query}"`);++ const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(query)}`, {+ method: 'GET',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Content-Type': 'application/json'+ }+ });++ if (response.ok) {+ const result = await response.json();+ const docs = result.results || [];++ console.log(`[Auto-Link] Query "${query}" found ${docs.length} documents`);++ if (docs.length > 0) {+ // Filter for recent documents (last 24 hours)+ const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);+ const recentDocs = docs.filter(doc => {+ try {+ const docDate = new Date(doc.created);+ return docDate > oneDayAgo;+ } catch {+ return true; // Include if we can't parse the date+ }+ });++ if (recentDocs.length > 0) {+ console.log(`[Auto-Link] Found ${recentDocs.length} recent documents for ${docType}`);+ candidateDocuments.push({+ docType,+ filename,+ documents: recentDocs,+ searchQuery: query+ });+ break; // Found documents, no need to try other queries for this file+ } else if (docs.length > 0) {+ // If no recent docs but we found some documents, include them anyway+ console.log(`[Auto-Link] Found ${docs.length} older documents for ${docType}, including them anyway`);+ candidateDocuments.push({+ docType,+ filename,+ documents: docs.slice(0, 3), // Take up to 3 most recent+ searchQuery: query+ });+ break;+ }+ }+ }+ } catch (error) {+ console.error(`[Auto-Link] Error searching with query "${query}":`, error);+ }+ }+ }++ // Strategy 2: Fallback to Warracker tag search if filename search fails+ if (candidateDocuments.length === 0) {+ console.log('[Auto-Link] No documents found by filename, trying Warracker tag search...');++ const response = await fetch('/api/paperless/search?ordering=-created&created__gte=' ++ new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), {+ method: 'GET',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Content-Type': 'application/json'+ }+ });++ if (response.ok) {+ const searchResult = await response.json();+ let recentDocs = searchResult.results || [];++ // Filter for Warracker documents+ const warrackerDocs = recentDocs.filter(doc =>+ doc.title && doc.title.includes('Warracker')+ );++ console.log(`[Auto-Link] Found ${warrackerDocs.length} Warracker documents from last 2 hours`);++ // Group by document type+ for (const docType of documentTypes) {+ const typeDocs = warrackerDocs.filter(doc =>+ doc.title && doc.title.includes(docType)+ );++ if (typeDocs.length > 0) {+ candidateDocuments.push({+ docType,+ filename: fileInfo[docType] || `${docType} document`,+ documents: typeDocs,+ searchQuery: `Warracker ${docType}`+ });+ }+ }+ }+ }++ // Debug: Show what candidate documents we found+ if (candidateDocuments.length > 0) {+ console.log('[Auto-Link] Candidate documents found:');+ candidateDocuments.forEach(candidate => {+ console.log(` ${candidate.docType}: ${candidate.documents.length} documents found with query "${candidate.searchQuery}"`);+ candidate.documents.forEach((doc, i) => {+ console.log(` ${i+1}. ID: ${doc.id}, Title: "${doc.title}", Created: ${doc.created}`);+ });+ });+ }++ // Try to link the best candidate for each document type+ for (const candidate of candidateDocuments) {+ // Use the most recent document (first in the ordered list)+ const doc = candidate.documents[0];++ console.log(`[Auto-Link] Attempting to link ${candidate.docType}: ${doc.title} (ID: ${doc.id})`);++ try {+ const linkResponse = await fetch('/api/paperless-search-and-link', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`+ },+ body: JSON.stringify({+ warranty_id: warrantyId,+ document_type: candidate.docType,+ search_title: doc.title.replace('Warracker ' + candidate.docType + ' - ', '')+ })+ });++ const linkResult = await linkResponse.json();++ if (linkResult.success) {+ console.log(`[Auto-Link] Successfully linked ${candidate.docType}: ${doc.title}`);+ linkedDocuments.push({+ type: candidate.docType,+ title: doc.title,+ id: doc.id,+ filename: candidate.filename+ });+ } else {+ console.log(`[Auto-Link] Failed to link ${candidate.docType}: ${linkResult.message}`);+ }+ } catch (error) {+ console.error(`[Auto-Link] Error linking ${candidate.docType}:`, error);+ }+ }++ // If we found and linked documents, we're done+ if (linkedDocuments.length > 0) {+ console.log(`[Auto-Link] Successfully linked ${linkedDocuments.length} documents:`, linkedDocuments);++ // Update loading screen to show success+ updatePaperlessUploadStatus('Documents linked successfully!');++ // Show success message with filenames+ const docInfo = linkedDocuments.map(d => `${d.type} (${d.filename || d.title})`).join(', ');+ showToast(`Automatically linked ${linkedDocuments.length} document(s): ${docInfo}`, 'success');++ // Reload warranties to show the updated document links+ setTimeout(async () => {+ console.log('π [Auto-Link] Reloading warranties to show updated document links...');+ await loadWarranties(true); // Pass isAuthenticated parameter++ // Force re-render of the warranty cards+ applyFilters();++ // Also reload secure images to update cloud icons+ await loadSecureImages();++ console.log('β [Auto-Link] Warranties reloaded and UI updated');++ // Hide loading screen after successful completion+ hidePaperlessUploadLoading();+ }, 1000);++ return true;+ }++ // If no documents found and we have retries left, try again+ if (attempt < maxRetries) {+ console.log(`[Auto-Link] No documents found, retrying in ${retryDelay}ms...`);+ updatePaperlessUploadStatus(`Searching for documents (attempt ${attempt + 1}/${maxRetries})...`, true);+ setTimeout(tryLinking, retryDelay);+ } else {+ console.log(`[Auto-Link] No documents found after ${maxRetries} attempts`);+ updatePaperlessUploadStatus('Document uploaded but could not auto-link');+ showToast('Document uploaded to Paperless-ngx but could not be automatically linked. You can manually link it later.', 'warning');+ // Hide loading screen after failed auto-link+ setTimeout(() => {+ hidePaperlessUploadLoading();+ }, 2000);+ }++ } catch (error) {+ console.error(`[Auto-Link] Error in attempt ${attempt}:`, error);++ if (attempt < maxRetries) {+ console.log(`[Auto-Link] Retrying in ${retryDelay}ms...`);+ updatePaperlessUploadStatus(`Error occurred, retrying (${attempt + 1}/${maxRetries})...`, true);+ setTimeout(tryLinking, retryDelay);+ } else {+ updatePaperlessUploadStatus('Upload completed with errors');+ showToast('Document uploaded but auto-linking failed due to errors. You can manually link it later.', 'warning');+ // Hide loading screen after final error+ setTimeout(() => {+ hidePaperlessUploadLoading();+ }, 2000);+ }+ }+ };++ // Start the linking process+ tryLinking();+}++// Make debug and cleanup functions available globally for console testing+window.debugPaperlessDocument = debugPaperlessDocument;+window.cleanupInvalidPaperlessDocuments = cleanupInvalidPaperlessDocuments;+window.searchAndLinkPaperlessDocument = searchAndLinkPaperlessDocument;+window.autoLinkRecentDocuments = autoLinkRecentDocuments;++// Helper function to manually link a specific document by title+window.manualLinkDocument = async function(warrantyId, documentType, titleSearchTerm) {+ console.log(`π Manually linking document for warranty ${warrantyId}`);+ console.log(` Document type: ${documentType}`);+ console.log(` Searching for title containing: "${titleSearchTerm}"`);++ const token = auth.getToken();+ if (!token) {+ console.error('β No auth token available');+ return;+ }++ try {+ // Search for documents containing the search term+ const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(titleSearchTerm)}`, {+ method: 'GET',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Content-Type': 'application/json'+ }+ });++ if (!response.ok) {+ console.error(`β Search failed: ${response.status}`);+ return;+ }++ const result = await response.json();+ const docs = result.results || [];++ console.log(`π Found ${docs.length} documents matching "${titleSearchTerm}"`);++ if (docs.length === 0) {+ console.log('β No documents found. The document might still be processing in Paperless-ngx.');+ return;+ }++ // Show all matching documents+ docs.forEach((doc, index) => {+ console.log(` ${index + 1}. ID: ${doc.id}, Title: "${doc.title}", Created: ${doc.created}`);+ });++ // Try to link the first matching document+ const docToLink = docs[0];+ console.log(`π Attempting to link document ID ${docToLink.id}: "${docToLink.title}"`);++ const linkResponse = await fetch('/api/paperless-search-and-link', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'Authorization': `Bearer ${token}`+ },+ body: JSON.stringify({+ warranty_id: warrantyId,+ document_type: documentType,+ search_title: docToLink.title.replace('Warracker ' + documentType + ' - ', '')+ })+ });++ const linkResult = await linkResponse.json();++ if (linkResult.success) {+ console.log(`β Successfully linked ${documentType}: ${docToLink.title}`);+ showToast(`Document linked successfully: ${documentType}`, 'success');++ // Reload warranties to show the updated document links+ setTimeout(async () => {+ console.log('π Reloading warranties to show updated document links...');+ await loadWarranties(true); // Pass isAuthenticated parameter++ // Force re-render of the warranty cards+ applyFilters();++ // Also reload secure images to update cloud icons+ await loadSecureImages();++ console.log('β Warranties reloaded and UI updated');+ }, 1000);+ } else {+ console.error(`β Failed to link ${documentType}: ${linkResult.message}`);+ }++ return docToLink;++ } catch (error) {+ console.error('β Error in manual linking:', error);+ }+};++// Helper function to search for documents in Paperless-ngx (debug function)+window.debugSearchPaperlessDocuments = async function(searchTerm = 'Warracker', limit = 10) {+ console.log(`π Searching for documents containing: "${searchTerm}"`);++ const token = auth.getToken();+ if (!token) {+ console.error('β No auth token available');+ return;+ }++ try {+ const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(searchTerm)}`, {+ method: 'GET',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Content-Type': 'application/json'+ }+ });++ if (!response.ok) {+ console.error(`β Search failed: ${response.status}`);+ return;+ }++ const result = await response.json();+ const docs = result.results || [];++ console.log(`π Found ${docs.length} documents:`);+ docs.slice(0, limit).forEach((doc, index) => {+ console.log(` ${index + 1}. ID: ${doc.id}, Title: "${doc.title}", Created: ${doc.created}`);+ });++ if (docs.length > limit) {+ console.log(` ... and ${docs.length - limit} more documents`);+ }++ return docs;+ } catch (error) {+ console.error('β Error searching documents:', error);+ }+};++// Helper function for users to debug Paperless-ngx configuration+window.debugPaperlessSetup = async function() {+ console.log('π Debugging Paperless-ngx setup...');++ const debugInfo = await debugPaperlessConfiguration();+ if (!debugInfo) {+ console.error('β Could not get debug information');+ return;+ }++ console.log('π Paperless-ngx Configuration:');+ console.log(` Enabled: ${debugInfo.paperless_enabled}`);+ console.log(` URL: ${debugInfo.paperless_url || 'Not set'}`);+ console.log(` API Token Set: ${debugInfo.paperless_api_token_set}`);+ console.log(` Handler Available: ${debugInfo.paperless_handler_available}`);++ if (debugInfo.paperless_handler_error) {+ console.error(` Handler Error: ${debugInfo.paperless_handler_error}`);+ }++ if (debugInfo.test_connection_result) {+ console.log(` Connection Test: ${debugInfo.test_connection_result.success ? 'β Success' : 'β Failed'}`);+ console.log(` Message: ${debugInfo.test_connection_result.message || debugInfo.test_connection_result.error}`);+ }++ // Provide recommendations+ console.log('\nπ‘ Recommendations:');++ if (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false') {+ console.log(' - Enable Paperless-ngx integration in Settings');+ }++ if (!debugInfo.paperless_url) {+ console.log(' - Set Paperless-ngx URL in Settings (e.g., http://paperless:8000)');+ }++ if (!debugInfo.paperless_api_token_set) {+ console.log(' - Set API token in Settings (generate from Paperless-ngx β Settings β API Tokens)');+ }++ if (debugInfo.test_connection_result && !debugInfo.test_connection_result.success) {+ console.log(' - Check if Paperless-ngx is running and accessible');+ console.log(' - Verify URL and API token are correct');+ console.log(' - Check network connectivity between Warracker and Paperless-ngx');+ }++ return debugInfo;+};++// ===== PAPERLESS DOCUMENT BROWSER FUNCTIONALITY =====++// Global variables for paperless browser+let currentPaperlessDocuments = [];+let selectedPaperlessDocument = null;+let currentPaperlessPage = 1;+let totalPaperlessPages = 1;+let currentDocumentType = '';+let paperlessSearchQuery = '';++/**+ * Open the Paperless document browser modal+ * @param {string} documentType - Type of document being selected (invoice, manual, product_photo, other_document)+ */+function openPaperlessBrowser(documentType) {+ currentDocumentType = documentType;+ selectedPaperlessDocument = null;++ // Reset pagination state+ currentPaperlessPage = 1;+ totalPaperlessPages = 1;+ paperlessSearchQuery = '';++ // Show the modal+ const modal = document.getElementById('paperlessBrowserModal');+ modal.classList.add('active');++ // Reset search and filters+ document.getElementById('paperlessSearchInput').value = '';+ document.getElementById('paperlessTypeFilter').value = '';+ document.getElementById('paperlessTagFilter').value = '';++ // Load documents+ loadAllPaperlessDocuments();++ // Load tags for filter+ loadPaperlessTags();++ // Hide select button initially+ const selectBtn = document.getElementById('selectPaperlessDocBtn');+ if (selectBtn) {+ selectBtn.style.display = 'none';+ }+}++/**+ * Load all Paperless documents+ */+async function loadAllPaperlessDocuments() {+ try {+ showPaperlessLoading();++ const params = new URLSearchParams();+ const offset = (currentPaperlessPage - 1) * 25;+ params.append('limit', '25');+ params.append('offset', offset.toString());++ const response = await fetch(`/api/paperless/search?${params.toString()}`, {+ method: 'GET',+ headers: {+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,+ 'Content-Type': 'application/json'+ }+ });++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ const data = await response.json();+ currentPaperlessDocuments = data.results || [];+ totalPaperlessPages = Math.ceil(data.count / 25) || 1;++ renderPaperlessDocuments();+ updatePaperlessPagination();++ } catch (error) {+ console.error('Error loading Paperless documents:', error);+ showPaperlessError('Failed to load documents from Paperless-ngx');+ }+}++/**+ * Search Paperless documents+ */+async function searchPaperlessDocuments() {+ const searchInput = document.getElementById('paperlessSearchInput');+ const typeFilter = document.getElementById('paperlessTypeFilter');+ const tagFilter = document.getElementById('paperlessTagFilter');++ paperlessSearchQuery = searchInput.value.trim();++ try {+ showPaperlessLoading();++ const params = new URLSearchParams();+ if (paperlessSearchQuery) {+ params.append('query', paperlessSearchQuery);+ }+ if (typeFilter.value) {+ params.append('document_type', typeFilter.value);+ }+ if (tagFilter.value) {+ params.append('tags__id__in', tagFilter.value);+ }++ // Add pagination+ const offset = (currentPaperlessPage - 1) * 25;+ params.append('limit', '25');+ params.append('offset', offset.toString());++ const response = await fetch(`/api/paperless/search?${params.toString()}`, {+ method: 'GET',+ headers: {+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,+ 'Content-Type': 'application/json'+ }+ });++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ const data = await response.json();+ currentPaperlessDocuments = data.results || [];+ totalPaperlessPages = Math.ceil(data.count / 25) || 1;++ renderPaperlessDocuments();+ updatePaperlessPagination();++ } catch (error) {+ console.error('Error searching Paperless documents:', error);+ showPaperlessError('Failed to search documents');+ }+}++/**+ * Load Paperless tags for filter dropdown+ */+async function loadPaperlessTags() {+ try {+ const response = await fetch('/api/paperless/tags', {+ method: 'GET',+ headers: {+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,+ 'Content-Type': 'application/json'+ }+ });++ if (response.ok) {+ const data = await response.json();+ const tagFilter = document.getElementById('paperlessTagFilter');++ // Clear existing options except the first one+ tagFilter.innerHTML = '<option value="">All Tags</option>';++ // Add tag options+ if (data.results) {+ data.results.forEach(tag => {+ const option = document.createElement('option');+ option.value = tag.id;+ option.textContent = tag.name;+ tagFilter.appendChild(option);+ });+ }+ }+ } catch (error) {+ console.error('Error loading Paperless tags:', error);+ }+}++/**+ * Render the list of Paperless documents+ */+function renderPaperlessDocuments() {+ const container = document.getElementById('paperlessDocumentsList');++ if (currentPaperlessDocuments.length === 0) {+ container.innerHTML = `+ <div class="no-documents-message">+ <i class="fas fa-file-alt"></i>+ <h4>No documents found</h4>+ <p>Try adjusting your search terms or filters.</p>+ </div>+ `;+ return;+ }++ const documentsHtml = currentPaperlessDocuments.map(doc => {+ const createdDate = new Date(doc.created).toLocaleDateString();+ const fileType = doc.mime_type || 'Unknown';+ const tags = doc.tags || [];++ return `+ <div class="paperless-document-item" data-id="${doc.id}" onclick="selectPaperlessDocument(${doc.id})">+ <div class="document-title">${escapeHtml(doc.title)}</div>+ <div class="document-meta">+ <span><i class="fas fa-calendar"></i> ${createdDate}</span>+ <span><i class="fas fa-file"></i> ${fileType}</span>+ ${doc.correspondent ? `<span><i class="fas fa-user"></i> ${escapeHtml(doc.correspondent)}</span>` : ''}+ </div>+ ${tags.length > 0 ? `+ <div class="document-tags">+ ${tags.map(tag => `<span class="document-tag">${escapeHtml(tag)}</span>`).join('')}+ </div>+ ` : ''}+ </div>+ `;+ }).join('');++ container.innerHTML = documentsHtml;+}++/**+ * Select a Paperless document+ * @param {number} documentId - ID of the document to select+ */+function selectPaperlessDocument(documentId) {+ // Remove previous selection+ document.querySelectorAll('.paperless-document-item').forEach(item => {+ item.classList.remove('selected');+ });++ // Add selection to clicked item+ const selectedItem = document.querySelector(`[data-id="${documentId}"]`);+ if (selectedItem) {+ selectedItem.classList.add('selected');+ selectedPaperlessDocument = currentPaperlessDocuments.find(doc => doc.id === documentId);++ // Show select button+ const selectBtn = document.getElementById('selectPaperlessDocBtn');+ selectBtn.style.display = 'inline-block';+ selectBtn.onclick = () => confirmPaperlessSelection();+ }+}++/**+ * Confirm the selection of a Paperless document+ */+function confirmPaperlessSelection() {+ if (!selectedPaperlessDocument) return;++ // Update the UI to show the selected document+ updatePaperlessSelectionUI();++ // Close the modal+ closePaperlessBrowser();+}++/**+ * Update the UI to show the selected Paperless document+ */+function updatePaperlessSelectionUI() {+ if (!selectedPaperlessDocument || !currentDocumentType) return;++ const docName = selectedPaperlessDocument.title;+ const docId = selectedPaperlessDocument.id;++ // Map document types to their UI elements (only for invoice and manual)+ const typeMapping = {+ 'invoice': {+ selectedDiv: 'selectedInvoiceFromPaperless',+ hiddenInput: 'selectedPaperlessInvoice'+ },+ 'manual': {+ selectedDiv: 'selectedManualFromPaperless',+ hiddenInput: 'selectedPaperlessManual'+ },+ // Edit modal versions+ 'edit_invoice': {+ selectedDiv: 'selectedEditInvoiceFromPaperless',+ hiddenInput: 'selectedEditPaperlessInvoice'+ },+ 'edit_manual': {+ selectedDiv: 'selectedEditManualFromPaperless',+ hiddenInput: 'selectedEditPaperlessManual'+ }+ };++ const mapping = typeMapping[currentDocumentType];+ if (!mapping) return;++ // Show the selected document+ const selectedDiv = document.getElementById(mapping.selectedDiv);+ if (selectedDiv) {+ selectedDiv.style.display = 'flex';+ selectedDiv.querySelector('.selected-doc-name').textContent = docName;+ }++ // Create or update hidden input to store the document ID+ let hiddenInput = document.getElementById(mapping.hiddenInput);+ if (!hiddenInput) {+ hiddenInput = document.createElement('input');+ hiddenInput.type = 'hidden';+ hiddenInput.id = mapping.hiddenInput;+ hiddenInput.name = mapping.hiddenInput;+ document.body.appendChild(hiddenInput);+ }+ hiddenInput.value = docId;+}++/**+ * Clear the Paperless document selection+ * @param {string} documentType - Type of document to clear+ */+function clearPaperlessSelection(documentType) {+ const typeMapping = {+ 'invoice': {+ selectedDiv: 'selectedInvoiceFromPaperless',+ hiddenInput: 'selectedPaperlessInvoice'+ },+ 'manual': {+ selectedDiv: 'selectedManualFromPaperless',+ hiddenInput: 'selectedPaperlessManual'+ },+ // Edit modal versions+ 'edit_invoice': {+ selectedDiv: 'selectedEditInvoiceFromPaperless',+ hiddenInput: 'selectedEditPaperlessInvoice'+ },+ 'edit_manual': {+ selectedDiv: 'selectedEditManualFromPaperless',+ hiddenInput: 'selectedEditPaperlessManual'+ }+ };++ const mapping = typeMapping[documentType];+ if (!mapping) return;++ // Hide the selected document display+ const selectedDiv = document.getElementById(mapping.selectedDiv);+ if (selectedDiv) {+ selectedDiv.style.display = 'none';+ }++ // Clear the hidden input+ const hiddenInput = document.getElementById(mapping.hiddenInput);+ if (hiddenInput) {+ hiddenInput.value = '';+ }+}++/**+ * Close the Paperless browser modal+ */+function closePaperlessBrowser() {+ const modal = document.getElementById('paperlessBrowserModal');+ modal.classList.remove('active');++ // Reset state+ selectedPaperlessDocument = null;+ currentDocumentType = '';++ // Hide select button+ const selectBtn = document.getElementById('selectPaperlessDocBtn');+ selectBtn.style.display = 'none';+}++/**+ * Change page in Paperless document browser+ * @param {number} direction - Direction to change page (-1 for previous, 1 for next)+ */+function changePage(direction) {+ const newPage = currentPaperlessPage + direction;+ if (newPage < 1 || newPage > totalPaperlessPages) return;++ currentPaperlessPage = newPage;++ // Check if we have any active filters+ const searchInput = document.getElementById('paperlessSearchInput');+ const typeFilter = document.getElementById('paperlessTypeFilter');+ const tagFilter = document.getElementById('paperlessTagFilter');++ const hasFilters = (searchInput && searchInput.value.trim()) ||+ (typeFilter && typeFilter.value) ||+ (tagFilter && tagFilter.value);++ if (hasFilters) {+ searchPaperlessDocuments();+ } else {+ loadAllPaperlessDocuments();+ }+}++/**+ * Update pagination controls+ */+function updatePaperlessPagination() {+ const paginationDiv = document.getElementById('paperlessPagination');+ const prevBtn = document.getElementById('prevPageBtn');+ const nextBtn = document.getElementById('nextPageBtn');+ const pageInfo = document.getElementById('pageInfo');++ if (totalPaperlessPages <= 1) {+ paginationDiv.style.display = 'none';+ return;+ }++ paginationDiv.style.display = 'flex';+ prevBtn.disabled = currentPaperlessPage <= 1;+ nextBtn.disabled = currentPaperlessPage >= totalPaperlessPages;+ pageInfo.textContent = `Page ${currentPaperlessPage} of ${totalPaperlessPages}`;+}++/**+ * Show loading state in Paperless browser+ */+function showPaperlessLoading() {+ const container = document.getElementById('paperlessDocumentsList');+ container.innerHTML = `+ <div class="loading-message" style="text-align: center; padding: 40px;">+ <i class="fas fa-spinner fa-spin"></i> Loading documents...+ </div>+ `;+}++/**+ * Show error message in Paperless browser+ * @param {string} message - Error message to display+ */+function showPaperlessError(message) {+ const container = document.getElementById('paperlessDocumentsList');+ container.innerHTML = `+ <div class="no-documents-message">+ <i class="fas fa-exclamation-triangle"></i>+ <h4>Error</h4>+ <p>${escapeHtml(message)}</p>+ </div>+ `;+}++/**+ * Show/hide Paperless browse sections based on Paperless-ngx availability+ */+function togglePaperlessBrowseSections() {+ const paperlessEnabled = window.paperlessNgxEnabled || false;+ console.log('[togglePaperlessBrowseSections] Paperless enabled:', paperlessEnabled);++ // List of paperless browse section IDs (only for invoice and manual)+ const browseSectionIds = [+ 'invoicePaperlessBrowse',+ 'manualPaperlessBrowse',+ 'editInvoicePaperlessBrowse',+ 'editManualPaperlessBrowse'+ ];++ let foundSections = 0;+ browseSectionIds.forEach(id => {+ const section = document.getElementById(id);+ if (section) {+ foundSections++;+ section.style.display = paperlessEnabled ? 'block' : 'none';+ console.log(`[togglePaperlessBrowseSections] ${id}: ${paperlessEnabled ? 'shown' : 'hidden'}`);+ } else {+ console.warn(`[togglePaperlessBrowseSections] Section not found: ${id}`);+ }+ });++ console.log(`[togglePaperlessBrowseSections] Found ${foundSections} of ${browseSectionIds.length} sections`);+}++// Initialize Paperless browser functionality when DOM is loaded+document.addEventListener('DOMContentLoaded', function() {+ // Add event listeners for modal close buttons+ const paperlessModal = document.getElementById('paperlessBrowserModal');+ if (paperlessModal) {+ // Close on backdrop click+ paperlessModal.addEventListener('click', function(e) {+ if (e.target === paperlessModal) {+ closePaperlessBrowser();+ }+ });++ // Close on close button click+ const closeBtn = paperlessModal.querySelector('.close-btn');+ if (closeBtn) {+ closeBtn.addEventListener('click', closePaperlessBrowser);+ }++ // Close on cancel button click - but only the Cancel button, not all secondary buttons+ const cancelBtn = paperlessModal.querySelector('.modal-footer .btn-secondary');+ if (cancelBtn) {+ cancelBtn.addEventListener('click', closePaperlessBrowser);+ }+ }++ // Add event listeners for search and filters+ const searchInput = document.getElementById('paperlessSearchInput');+ if (searchInput) {+ // Search on Enter key+ searchInput.addEventListener('keypress', function(e) {+ if (e.key === 'Enter') {+ currentPaperlessPage = 1; // Reset to first page+ searchPaperlessDocuments();+ }+ });++ // Search on input change (with debounce)+ let searchTimeout;+ searchInput.addEventListener('input', function() {+ clearTimeout(searchTimeout);+ searchTimeout = setTimeout(() => {+ currentPaperlessPage = 1; // Reset to first page+ searchPaperlessDocuments();+ }, 500);+ });+ }++ // Add event listeners for filter dropdowns+ const typeFilter = document.getElementById('paperlessTypeFilter');+ if (typeFilter) {+ typeFilter.addEventListener('change', function() {+ currentPaperlessPage = 1; // Reset to first page+ searchPaperlessDocuments();+ });+ }++ const tagFilter = document.getElementById('paperlessTagFilter');+ if (tagFilter) {+ tagFilter.addEventListener('change', function() {+ currentPaperlessPage = 1; // Reset to first page+ searchPaperlessDocuments();+ });+ }++ // Add event listener for search button+ const searchBtn = document.getElementById('paperlessSearchBtn');+ if (searchBtn) {+ searchBtn.addEventListener('click', function(e) {+ e.preventDefault();+ e.stopPropagation();+ currentPaperlessPage = 1; // Reset to first page+ searchPaperlessDocuments();+ });+ }++ // Add event listener for "Show All" button+ const showAllBtn = document.getElementById('paperlessShowAllBtn');+ if (showAllBtn) {+ showAllBtn.addEventListener('click', function(e) {+ e.preventDefault();+ e.stopPropagation();++ // Clear all filters+ if (searchInput) searchInput.value = '';+ if (typeFilter) typeFilter.value = '';+ if (tagFilter) tagFilter.value = '';++ // Reset page and load all documents+ currentPaperlessPage = 1;+ paperlessSearchQuery = '';+ loadAllPaperlessDocuments();+ });+ }++ // Toggle browse sections will be handled by initPaperlessNgxIntegration()+ // togglePaperlessBrowseSections();+});++// Make functions available globally+window.openPaperlessBrowser = openPaperlessBrowser;+window.loadAllPaperlessDocuments = loadAllPaperlessDocuments;+window.selectPaperlessDocument = selectPaperlessDocument;+window.clearPaperlessSelection = clearPaperlessSelection;+window.changePage = changePage;++// ===== END PAPERLESS BROWSER FUNCTIONALITY =====diff --git a/frontend/settings-new.html b/frontend/settings-new.htmlindex b846046..dfead5b 100644--- a/frontend/settings-new.html+++ b/frontend/settings-new.html@@ -640,6 +640,19 @@<small class="text-muted">Generate an API token from your Paperless-ngx instance (Settings β API Tokens).</small></div>+ <div class="form-group">+ <div class="preference-item">+ <div>+ <label>View Documents in Warracker</label>+ <p class="text-muted">View Paperless-ngx documents within Warracker instead of opening them in Paperless domain</p>+ </div>+ <label class="toggle-switch">+ <input type="checkbox" id="paperlessViewInApp">+ <span class="toggle-slider"></span>+ </label>+ </div>+ </div>+<div class="form-group" style="margin-top: 20px;"><label>Connection Testing</label><div class="paperless-button-group">@@ -1067,7 +1080,7 @@<!-- Scripts --><script src="auth.js?v=20250529006"></script>- <script src="settings-new.js?v=20250529006"></script>+ <script src="settings-new.js?v=20250617018"></script><!-- Footer Width Fix --><script src="footer-fix.js"></script>diff --git a/frontend/settings-new.js b/frontend/settings-new.jsindex 6e52603..dda1070 100644--- a/frontend/settings-new.js+++ b/frontend/settings-new.js@@ -106,6 +106,7 @@ const dateFormatSelect = document.getElementById('dateFormat');const paperlessEnabledToggle = document.getElementById('paperlessEnabled');const paperlessUrlInput = document.getElementById('paperlessUrl');const paperlessApiTokenInput = document.getElementById('paperlessApiToken');+const paperlessViewInAppToggle = document.getElementById('paperlessViewInApp');const paperlessSettingsContainer = document.getElementById('paperlessSettingsContainer');const testPaperlessConnectionBtn = document.getElementById('testPaperlessConnectionBtn');const savePaperlessSettingsBtn = document.getElementById('savePaperlessSettingsBtn');@@ -773,6 +774,16 @@ async function loadPreferences() {console.log(`${prefix}expiringSoonDays not found, defaulting to 30`);}+ // Paperless View in App+ const storedPaperlessViewInApp = localStorage.getItem(`${prefix}paperlessViewInApp`);+ if (storedPaperlessViewInApp !== null && paperlessViewInAppToggle) {+ paperlessViewInAppToggle.checked = storedPaperlessViewInApp === 'true';+ console.log(`Loaded Paperless view in app from ${prefix}paperlessViewInApp: ${storedPaperlessViewInApp}`);+ } else if (paperlessViewInAppToggle) {+ paperlessViewInAppToggle.checked = false; // Default+ console.log(`${prefix}paperlessViewInApp not found, defaulting to false`);+ }+// Apply API preferences to form elements (apiPrefs already loaded above)if (apiPrefs) {console.log('Applying API preferences to form elements:', apiPrefs);@@ -841,6 +852,13 @@ async function loadPreferences() {}// --- End Date Format Check ---+ // --- Update Paperless View in App from API Prefs ---+ if (apiPrefs.paperless_view_in_app !== undefined && paperlessViewInAppToggle) {+ paperlessViewInAppToggle.checked = apiPrefs.paperless_view_in_app;+ console.log(`Set Paperless view in app from API: ${apiPrefs.paperless_view_in_app}`);+ }+ // --- End Paperless View in App from API Prefs ---+// Update Email Settings from APIif (notificationChannel) {const channelValue = apiPrefs.notification_channel || 'email'; // Default to email if not present@@ -1416,6 +1434,7 @@ async function savePreferences() {expiring_soon_days: expiringSoonDaysInput ? parseInt(expiringSoonDaysInput.value) : 30,date_format: dateFormatSelect ? dateFormatSelect.value : 'MDY',theme: isDark ? 'dark' : 'light', // Use current UI state, not old localStorage+ paperless_view_in_app: paperlessViewInAppToggle ? paperlessViewInAppToggle.checked : false,};// Handle currency symbol (standard or custom)@@ -1465,6 +1484,7 @@ async function savePreferences() {localStorage.setItem(`${prefix}currencyCode`, currencyCode); // Save currency codelocalStorage.setItem(`${prefix}currencyPosition`, preferencesToSave.currency_position);localStorage.setItem(`${prefix}expiringSoonDays`, preferencesToSave.expiring_soon_days);+ localStorage.setItem(`${prefix}paperlessViewInApp`, preferencesToSave.paperless_view_in_app);console.log('Preferences saved to localStorage (prefix:', prefix, '):', preferencesToSave);console.log(`Value of dateFormat in localStorage: ${localStorage.getItem('dateFormat')}`);@@ -4582,6 +4602,7 @@ async function savePaperlessSettings() {settingsData.paperless_api_token = apiToken;}+ // Save admin settings firstconst response = await fetch('/api/admin/settings', {method: 'PUT',headers: {@@ -4596,7 +4617,28 @@ async function savePaperlessSettings() {throw new Error(errorData.message || 'Failed to save Paperless-ngx settings');}- const result = await response.json();+ // Also save the user preference for viewing documents in app+ const paperlessViewInApp = paperlessViewInAppToggle ? paperlessViewInAppToggle.checked : false;+ const preferencesData = {+ paperless_view_in_app: paperlessViewInApp+ };++ const preferencesResponse = await fetch('/api/auth/preferences', {+ method: 'PUT',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify(preferencesData)+ });++ if (!preferencesResponse.ok) {+ console.warn('Failed to save paperless view preference, but admin settings were saved');+ }++ // Update localStorage for the preference+ const prefix = getPreferenceKeyPrefix();+ localStorage.setItem(`${prefix}paperlessViewInApp`, paperlessViewInApp);showToast('Paperless-ngx settings saved successfully!', 'success');diff --git a/frontend/settings-styles.css b/frontend/settings-styles.cssindex ca73157..9b51542 100644--- a/frontend/settings-styles.css+++ b/frontend/settings-styles.css@@ -6,12 +6,17 @@--hover-bg: rgba(0, 0, 0, 0.05);}+html {+ overflow-x: hidden;+}+body {background-color: var(--bg-color);color: var(--text-color);font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;line-height: 1.6;transition: background-color 0.3s ease, color 0.3s ease;+ overflow-x: hidden;}/* Header Styles */@@ -177,6 +182,7 @@ header .container {max-width: 1200px !important;margin: 0 auto !important;padding: 20px !important;+ overflow-x: hidden;}.content-wrapper h2 {@@ -447,6 +453,8 @@ input:checked + .toggle-slider:before {border: 1px solid var(--border-color);border-radius: 0.25rem;transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;+ box-sizing: border-box;+ word-wrap: break-word;}.form-control:focus {@@ -535,6 +543,7 @@ input:checked + .toggle-slider:before {box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);margin-bottom: 20px;overflow: hidden;+ word-wrap: break-word;}.card-header {@@ -842,7 +851,7 @@ input:checked + .toggle-slider:before {/* Admin Actions Grid */.admin-actions-grid {display: grid;- grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));gap: 20px;margin-bottom: 20px;}@@ -1002,7 +1011,7 @@ input:checked + .toggle-slider:before {.apprise-actions {display: grid;- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));gap: 10px;margin-top: 20px;}@@ -1018,7 +1027,7 @@ input:checked + .toggle-slider:before {.status-grid {display: grid;- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));gap: 15px;margin-top: 10px;}@@ -1205,12 +1214,12 @@ textarea.form-control {}}-/* Footer Overrides - Ensure footer spans full width */+/* Footer Overrides - Ensure footer spans full width without causing horizontal scroll */.warracker-footer {- width: 100vw !important;- margin-left: calc(-50vw + 50%) !important;- margin-right: calc(-50vw + 50%) !important;+ width: 100% !important;max-width: none !important;+ margin-left: 0 !important;+ margin-right: 0 !important;position: relative !important;left: 0 !important;right: 0 !important;@@ -1219,9 +1228,9 @@ textarea.form-control {/* Additional mobile responsive styles if needed */@media (max-width: 768px) {.warracker-footer {- width: 100vw !important;- margin-left: calc(-50vw + 50%) !important;- margin-right: calc(-50vw + 50%) !important;+ width: 100% !important;+ margin-left: 0 !important;+ margin-right: 0 !important;}}diff --git a/frontend/status.html b/frontend/status.htmlindex 8909180..744d4ca 100644--- a/frontend/status.html+++ b/frontend/status.html@@ -29,7 +29,7 @@<script src="chart.js"></script><!-- Load fix for auth buttons --><script src="fix-auth-buttons-loader.js"></script>- <script src="script.js?v=20250617007" defer></script> <!-- Added script.js -->+ <script src="script.js?v=20250617018" defer></script> <!-- Added script.js --><script src="status.js" defer></script> <!-- Status page specific functionality --><style>.user-menu {diff --git a/frontend/style.css b/frontend/style.cssindex c154745..3a258f6 100644--- a/frontend/style.css+++ b/frontend/style.css@@ -2827,24 +2827,58 @@ input.invalid {flex: 0 1 auto; /* Allow natural sizing */display: flex;flex-direction: column;+ gap: 10px;}.warranty-info > div {- margin-bottom: 8px;+ display: flex;+ align-items: center;+ margin-bottom: 0;}.warranty-info > div:last-child {margin-bottom: 0;}+.warranty-info > div i {+ width: 20px;+ margin-right: 8px;+ color: #666;+ font-size: 14px;+ text-align: center;+}++.warranty-info > div span {+ margin-left: 5px;+ font-weight: 500;+ color: var(--text-color);+}++:root[data-theme="dark"] .warranty-info > div i {+ color: #999;+}+/* Serial numbers section */.serial-numbers {- margin-top: 10px;+ display: flex;+ align-items: flex-start;+ margin-top: 0;+}++.serial-numbers strong {+ margin-right: 8px;+ flex-shrink: 0;+}++.serial-numbers span {+ margin-left: 5px;+ font-weight: 500;}.serial-numbers ul {margin: 5px 0 0 0;padding-left: 20px;+ flex: 1;}.serial-numbers li {@@ -2873,6 +2907,18 @@ input.invalid {.list-view .warranty-info > div {margin-bottom: 0;margin-right: 15px;+ display: flex;+ align-items: center;+}++.list-view .warranty-info > div i {+ width: auto;+ margin-right: 5px;+}++.list-view .warranty-info > div span {+ margin-left: 5px;+ font-weight: 500;}/* Document links row */@@ -2989,15 +3035,30 @@ input.invalid {.table-view .warranty-info > div {margin-bottom: 4px;font-size: 0.9rem;+ display: flex;+ align-items: center;}.table-view .warranty-info > div:last-child {margin-bottom: 0;}+.table-view .warranty-info > div i {+ width: auto;+ margin-right: 5px;+ font-size: 0.85rem;+}++.table-view .warranty-info > div span {+ margin-left: 5px;+}+/* Improve serial numbers display in table view */.table-view .serial-numbers {- margin-top: 5px;+ margin-top: 0;+ display: flex;+ align-items: flex-start;+ font-size: 0.9rem;}.table-view .serial-numbers ul {@@ -3929,6 +3990,7 @@ html.dark-mode .warracker-footer a:hover {border-radius: 8px;object-fit: cover;transition: transform 0.2s ease, box-shadow 0.2s ease;+ background-color: #f5f5f5;}.product-photo-thumbnail img:hover {@@ -3964,8 +4026,8 @@ html.dark-mode .warracker-footer a:hover {/* List view photo positioning */.list-view .product-photo-thumbnail img {- width: 70px;- height: 70px;+ width: 180px;+ height: 180px;}/* Table view photo positioning */@@ -3977,6 +4039,7 @@ html.dark-mode .warracker-footer a:hover {/* Dark mode adjustments */:root[data-theme="dark"] .product-photo-thumbnail img {border-color: var(--border-color);+ background-color: #2a2a2a;}:root[data-theme="dark"] .photo-preview img {@@ -3986,12 +4049,16 @@ html.dark-mode .warracker-footer a:hover {/* Mobile responsiveness */@media (max-width: 768px) {- .grid-view .product-photo-thumbnail img,- .list-view .product-photo-thumbnail img {+ .grid-view .product-photo-thumbnail img {width: 60px;height: 60px;}+ .list-view .product-photo-thumbnail img {+ width: 120px;+ height: 120px;+ }+.table-view .product-photo-thumbnail img {width: 50px;height: 50px;@@ -4002,3 +4069,244 @@ html.dark-mode .warracker-footer a:hover {right: 6px;}}++@media (max-width: 768px) {+ .grid-view .product-photo-thumbnail img {+ width: 30px;+ height: 30px;+ }+ .list-view .product-photo-thumbnail img {+ width: 25px;+ height: 25px;+ }+ .table-view .product-photo-thumbnail img {+ width: 20px;+ height: 20px;+ }+ .product-photo-thumbnail {+ margin-right: 5px;+ }+}++/* ===== PAPERLESS BROWSER STYLES ===== */+.modal-large {+ max-width: 90vw;+ width: 900px;+}++.paperless-browse-section {+ margin-top: 10px;+ padding: 10px;+ background-color: var(--light-gray);+ border-radius: var(--border-radius);+ border: 1px solid var(--border-color);+}++:root[data-theme="dark"] .paperless-browse-section {+ background-color: var(--medium-gray);+ border-color: var(--border-color);+}++.selected-paperless-doc {+ margin-top: 8px;+ padding: 8px 12px;+ background-color: var(--primary-color);+ color: white;+ border-radius: 4px;+ display: flex;+ justify-content: space-between;+ align-items: center;+}++.selected-paperless-doc .selected-doc-name {+ font-weight: 500;+ flex-grow: 1;+}++.selected-paperless-doc .btn-xs {+ padding: 2px 6px;+ font-size: 0.8em;+ margin-left: 10px;+}++.paperless-browser-controls {+ margin-bottom: 20px;+}++.search-section {+ display: flex;+ gap: 10px;+ margin-bottom: 15px;+ align-items: center;+}++.search-section input {+ flex: 1;+ min-width: 250px;+ padding: 10px 12px;+ font-size: 1rem;+}++.filter-section {+ display: flex;+ gap: 10px;+}++.filter-section select {+ flex: 1;+}++.paperless-documents-list {+ max-height: 400px;+ overflow-y: auto;+ border: 1px solid var(--border-color);+ border-radius: var(--border-radius);+ background-color: var(--card-bg);+}++.paperless-document-item {+ padding: 12px 16px;+ border-bottom: 1px solid var(--border-color);+ cursor: pointer;+ transition: background-color 0.2s;+}++.paperless-document-item:last-child {+ border-bottom: none;+}++.paperless-document-item:hover {+ background-color: var(--light-gray);+}++:root[data-theme="dark"] .paperless-document-item:hover {+ background-color: var(--medium-gray);+}++.paperless-document-item.selected {+ background-color: var(--primary-color);+ color: white;+}++.paperless-document-item.selected:hover {+ background-color: var(--primary-dark);+}++.document-title {+ font-weight: 600;+ font-size: 1.1em;+ margin-bottom: 4px;+}++.document-meta {+ font-size: 0.9em;+ color: var(--dark-gray);+ display: flex;+ gap: 15px;+ flex-wrap: wrap;+}++.paperless-document-item.selected .document-meta {+ color: rgba(255, 255, 255, 0.8);+}++.document-tags {+ display: flex;+ gap: 4px;+ flex-wrap: wrap;+ margin-top: 6px;+}++.document-tag {+ background-color: var(--medium-gray);+ color: var(--text-color);+ padding: 2px 6px;+ border-radius: 12px;+ font-size: 0.75em;+}++.paperless-document-item.selected .document-tag {+ background-color: rgba(255, 255, 255, 0.2);+ color: white;+}++.pagination-controls {+ display: flex;+ justify-content: center;+ align-items: center;+ gap: 15px;+ margin-top: 15px;+ padding: 10px;+ flex-wrap: nowrap;+}++.pagination-controls button {+ white-space: nowrap;+ min-width: fit-content;+ padding: 8px 12px;+}++.pagination-controls button:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++#pageInfo {+ font-weight: 500;+ color: var(--text-color);+ white-space: nowrap;+ min-width: fit-content;+}++.loading-message {+ color: var(--dark-gray);+ font-style: italic;+}++.no-documents-message {+ text-align: center;+ padding: 40px 20px;+ color: var(--dark-gray);+}++.no-documents-message i {+ font-size: 3em;+ margin-bottom: 15px;+ opacity: 0.5;+}++.no-documents-message h4 {+ margin-bottom: 10px;+ color: var(--text-color);+}++/* Mobile responsiveness for paperless browser */+@media (max-width: 768px) {+ .modal-large {+ max-width: 95vw;+ width: 95vw;+ }++ .search-section {+ flex-direction: column;+ }++ .filter-section {+ flex-direction: column;+ }++ .paperless-documents-list {+ max-height: 300px;+ }++ .document-meta {+ flex-direction: column;+ gap: 5px;+ }++ .pagination-controls {+ flex-direction: row;+ gap: 10px;+ flex-wrap: nowrap;+ }+}diff --git a/frontend/version-checker.js b/frontend/version-checker.jsindex 40eed2e..2f51d8e 100644--- a/frontend/version-checker.js+++ b/frontend/version-checker.js@@ -1,6 +1,6 @@// Version checker for Warrackerdocument.addEventListener('DOMContentLoaded', () => {- const currentVersion = '0.10.1.3'; // Current version of the application+ const currentVersion = '0.10.1.4'; // Current version of the applicationconst updateStatus = document.getElementById('updateStatus');const updateLink = document.getElementById('updateLink');