Skip to content

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

Added warranty claims tracking, document URL support, and custom database port configuration.

sassanixd9d52743e24f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 95dae03..e921565 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,38 @@
# Changelog
+## 0.10.1.10 - 2025-08-30
+
+### Enhanced
+- **URL/Link Support for Documents and Invoices:** Introduced comprehensive URL/Link support allowing users to add external URLs for their documents (invoices, manuals, and other files) in addition to the existing file upload functionality. This enhancement provides flexible document management options while maintaining full backward compatibility with existing features.
+ - **Database Schema:** Added three nullable columns (`invoice_url`, `manual_url`, `other_document_url`) to the warranties table via migration 043, ensuring zero impact on existing records.
+ - **Complete Modal Integration:** Enhanced both Add and Edit warranty modals across all pages with intuitive URL input fields featuring link icons and clean visual integration alongside existing file upload sections. Added URL input fields to both the homepage edit modal (`index.html`) and status page edit modal (`status.html`) for complete feature parity.
+ - **Dual Display Support:** Updated warranty cards to display both file links and URL links side by side, with URL links opening in new tabs for seamless external document access.
+ - **Smart Summary:** Enhanced the Add Warranty summary to intelligently display either uploaded file names or "URL: [link]" when URLs are provided instead of files.
+ - **API Enhancement:** Extended backend API endpoints to handle URL fields in warranty creation, updates, and retrieval with proper form validation and data processing.
+ - **Responsive Design:** Added CSS styling for URL input fields with proper icon positioning, hover effects, and mobile-friendly responsive behavior.
+ - **Cross-Page Compatibility:** Implemented robust null safety checks in JavaScript functions to prevent errors when URL input elements don't exist on certain pages, ensuring seamless operation across different page contexts.
+ - **Error Resolution:** Fixed TypeError issues in edit modal functionality by adding comprehensive null checks for URL field access, ensuring stable operation when switching between different modal implementations.
+ - **User Experience:** Users can now choose between file uploads, external URLs, or a combination of both, providing maximum flexibility for different document management workflows and storage preferences across all warranty management interfaces.
+ - _Files: `backend/migrations/043_add_document_urls_to_warranties.sql`, `backend/warranties_routes.py`, `frontend/index.html`, `frontend/status.html`, `frontend/script.js`, `frontend/style.css`_
+
+- **Database Port Configuration Support:** Added support for custom database port configuration via the `DB_PORT` environment variable to enhance deployment flexibility. The implementation is fully backward-compatible, defaulting to port 5432 if the variable is not set.
+ - **Backend Integration:** Updated `backend/db_handler.py` and `backend/fix_permissions.py` to recognize and use the `DB_PORT` environment variable in all database connection calls.
+ - **Docker Support:** Added `DB_PORT` environment variable support to both `docker-compose.yml` files with fallback defaults (`${DB_PORT:-5432}`).
+ - **Configuration Examples:** Updated `env.example` with commented DB_PORT configuration option for local development guidance.
+ - **Deployment Flexibility:** Users can now customize database ports for non-standard PostgreSQL deployments, multi-instance setups, or specific infrastructure requirements.
+ - _Files: `backend/db_handler.py`, `backend/fix_permissions.py`, `docker-compose.yml`, `Docker/docker-compose.yml`, `env.example`_
+
+- **Warranty Claims Tracking System:** Introduced comprehensive warranty claims management functionality allowing users to track and manage warranty claims for their products throughout the entire claim lifecycle.
+ - **Database Schema:** Added `warranty_claims` table via migration 044 with support for claim dates, status tracking, claim numbers, descriptions, resolutions, and resolution dates with proper foreign key relationships and indexing.
+ - **Backend API:** Implemented full REST API for claims management including endpoints for creating, reading, updating, and deleting warranty claims with proper authentication and authorization checks.
+ - **Frontend Integration:** Added intuitive claims modal interface accessible from warranty cards with comprehensive claim management features including status tracking, date management, and detailed claim information.
+ - **Status Management:** Implemented claim status workflow with predefined statuses (Submitted, In Progress, Approved, Denied, Resolved, Cancelled) and proper status badge styling for visual clarity.
+ - **Date Handling:** Enhanced date formatting and display logic to properly handle claim dates, resolution dates, and warranty expiration dates with robust null value handling and user-friendly formatting.
+ - **User Interface:** Positioned Claims button as the first action button in warranty card headers (Claims, Edit, Delete order) with hover tooltip for easy identification and access.
+ - **Modal Behavior:** Enhanced claims modal stability by preventing accidental closure when clicking outside the modal area, requiring explicit close button interaction for better user experience.
+ - **Data Integrity:** Implemented proper validation, error handling, and database constraints to ensure data consistency and prevent orphaned records.
+ - _Files: `backend/migrations/044_create_warranty_claims_table.sql`, `backend/warranties_routes.py`, `frontend/script.js`, `frontend/index.html`_
+
## 0.10.1.9 - 2025-08-24
### Fixed
diff --git a/Docker/docker-compose.yml b/Docker/docker-compose.yml
index 7113612..c9aab49 100644
--- a/Docker/docker-compose.yml
+++ b/Docker/docker-compose.yml
@@ -7,6 +7,7 @@ services:
- warracker_uploads:/data/uploads
environment:
- DB_HOST=warrackerdb
+ - DB_PORT=${DB_PORT:-5432}
- DB_NAME=warranty_db
- DB_USER=warranty_user
- DB_PASSWORD=${DB_PASSWORD:-warranty_password}
diff --git a/backend/db_handler.py b/backend/db_handler.py
index 3b59cba..da47a26 100644
--- a/backend/db_handler.py
+++ b/backend/db_handler.py
@@ -11,6 +11,7 @@ logger = logging.getLogger(__name__)
# PostgreSQL connection details
DB_HOST = os.environ.get('DB_HOST', 'warrackerdb')
+DB_PORT = os.environ.get('DB_PORT', '5432')
DB_NAME = os.environ.get('DB_NAME', 'warranty_db')
DB_USER = os.environ.get('DB_USER', 'warranty_user')
DB_PASSWORD = os.environ.get('DB_PASSWORD', 'warranty_password')
@@ -33,6 +34,7 @@ def init_db_pool(max_retries=5, retry_delay=5):
connection_pool = pool.SimpleConnectionPool(
1, 4, # Reduced from 1,10 to 1,4 for memory efficiency
host=DB_HOST,
+ port=DB_PORT,
database=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
diff --git a/backend/fix_permissions.py b/backend/fix_permissions.py
index a8380b7..1abe8bb 100644
--- a/backend/fix_permissions.py
+++ b/backend/fix_permissions.py
@@ -13,6 +13,7 @@ logger = logging.getLogger(__name__)
# PostgreSQL connection details
DB_HOST = os.environ.get('DB_HOST', 'warrackerdb')
+DB_PORT = os.environ.get('DB_PORT', '5432')
DB_NAME = os.environ.get('DB_NAME', 'warranty_db')
DB_USER = os.environ.get('DB_USER', 'warranty_user')
DB_PASSWORD = os.environ.get('DB_PASSWORD', 'warranty_password')
@@ -27,6 +28,7 @@ def create_db_connection(max_retries=5, retry_delay=5):
logger.info(f"Attempting to connect to database (attempt {attempt+1}/{max_retries})")
conn = psycopg2.connect(
host=DB_HOST,
+ port=DB_PORT,
database=DB_NAME,
user=DB_USER,
password=DB_PASSWORD
diff --git a/backend/migrations/043_add_document_urls_to_warranties.sql b/backend/migrations/043_add_document_urls_to_warranties.sql
new file mode 100644
index 0000000..904f0c5
--- /dev/null
+++ b/backend/migrations/043_add_document_urls_to_warranties.sql
@@ -0,0 +1,9 @@
+-- Migration: Add document URL columns to warranties table
+-- Description: Add support for external URLs for invoices, manuals, and other documents
+-- Date: 2025-01-20
+
+-- Add nullable TEXT columns for storing document URLs
+ALTER TABLE warranties
+ADD COLUMN IF NOT EXISTS invoice_url TEXT,
+ADD COLUMN IF NOT EXISTS manual_url TEXT,
+ADD COLUMN IF NOT EXISTS other_document_url TEXT;
diff --git a/backend/migrations/044_create_warranty_claims_table.sql b/backend/migrations/044_create_warranty_claims_table.sql
new file mode 100644
index 0000000..8804f26
--- /dev/null
+++ b/backend/migrations/044_create_warranty_claims_table.sql
@@ -0,0 +1,36 @@
+-- Migration: Create warranty claims table
+-- Description: Add support for warranty claim tracking with many-to-one relationship to warranties
+-- Date: 2025-01-20
+
+-- Create warranty_claims table
+CREATE TABLE IF NOT EXISTS warranty_claims (
+ id SERIAL PRIMARY KEY,
+ warranty_id INTEGER NOT NULL REFERENCES warranties(id) ON DELETE CASCADE,
+ claim_date DATE NOT NULL DEFAULT CURRENT_DATE,
+ status VARCHAR(50) NOT NULL DEFAULT 'Submitted',
+ claim_number VARCHAR(255),
+ description TEXT,
+ resolution TEXT,
+ resolution_date DATE,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
+);
+
+-- Create indexes for better query performance
+CREATE INDEX IF NOT EXISTS idx_warranty_claims_warranty_id ON warranty_claims(warranty_id);
+CREATE INDEX IF NOT EXISTS idx_warranty_claims_status ON warranty_claims(status);
+
+-- Add trigger to update updated_at timestamp
+CREATE OR REPLACE FUNCTION update_warranty_claims_updated_at()
+RETURNS TRIGGER AS $$
+BEGIN
+ NEW.updated_at = CURRENT_TIMESTAMP;
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TRIGGER warranty_claims_updated_at
+ BEFORE UPDATE ON warranty_claims
+ FOR EACH ROW
+ EXECUTE FUNCTION update_warranty_claims_updated_at();
+
diff --git a/backend/warranties_routes.py b/backend/warranties_routes.py
index 79e4de4..5b4f115 100644
--- a/backend/warranties_routes.py
+++ b/backend/warranties_routes.py
@@ -63,7 +63,8 @@ def get_warranties():
SELECT id, product_name, purchase_date, expiration_date, invoice_path, manual_path, other_document_path, product_url, notes,
purchase_price, user_id, created_at, updated_at, is_lifetime, vendor, warranty_type,
warranty_duration_years, warranty_duration_months, warranty_duration_days, product_photo_path, currency,
- paperless_invoice_id, paperless_manual_id, paperless_photo_id, paperless_other_id
+ paperless_invoice_id, paperless_manual_id, paperless_photo_id, paperless_other_id,
+ invoice_url, manual_url, other_document_url
FROM warranties
WHERE user_id = %s
ORDER BY CASE WHEN is_lifetime THEN 1 ELSE 0 END, expiration_date NULLS LAST, product_name
@@ -176,6 +177,11 @@ def add_warranty():
vendor = request.form.get('vendor', None)
warranty_type = request.form.get('warranty_type', None)
+ # Get URL fields for documents
+ invoice_url = request.form.get('invoice_url', None)
+ manual_url = request.form.get('manual_url', None)
+ other_document_url = request.form.get('other_document_url', None)
+
# Get tag IDs if provided
tag_ids = []
if request.form.get('tag_ids'):
@@ -360,15 +366,17 @@ def add_warranty():
product_name, purchase_date, expiration_date,
invoice_path, manual_path, other_document_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor, warranty_type,
warranty_duration_years, warranty_duration_months, warranty_duration_days, product_photo_path, currency,
- paperless_invoice_id, paperless_manual_id, paperless_photo_id, paperless_other_id
+ paperless_invoice_id, paperless_manual_id, paperless_photo_id, paperless_other_id,
+ invoice_url, manual_url, other_document_url
)
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
''', (
product_name, purchase_date, expiration_date,
db_invoice_path, db_manual_path, db_other_document_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor, warranty_type,
warranty_duration_years, warranty_duration_months, warranty_duration_days, db_product_photo_path, currency,
- paperless_invoice_id, paperless_manual_id, paperless_photo_id, paperless_other_id
+ paperless_invoice_id, paperless_manual_id, paperless_photo_id, paperless_other_id,
+ invoice_url, manual_url, other_document_url
))
warranty_id = cur.fetchone()[0]
@@ -588,6 +596,11 @@ def update_warranty(warranty_id):
notes = request.form.get('notes', None)
vendor = request.form.get('vendor', None)
warranty_type = request.form.get('warranty_type', None)
+
+ # Get URL fields for documents
+ invoice_url = request.form.get('invoice_url', None)
+ manual_url = request.form.get('manual_url', None)
+ other_document_url = request.form.get('other_document_url', None)
tag_ids = []
if request.form.get('tag_ids'):
try:
@@ -924,6 +937,17 @@ def update_warranty(warranty_id):
sql_fields.append("paperless_other_id = %s")
sql_values.append(paperless_other_id)
+ # Handle URL fields for documents
+ if 'invoice_url' in request.form:
+ sql_fields.append("invoice_url = %s")
+ sql_values.append(request.form.get('invoice_url'))
+ if 'manual_url' in request.form:
+ sql_fields.append("manual_url = %s")
+ sql_values.append(request.form.get('manual_url'))
+ if 'other_document_url' in request.form:
+ sql_fields.append("other_document_url = %s")
+ sql_values.append(request.form.get('other_document_url'))
+
sql_fields.append("updated_at = NOW()") # Use SQL function, no parameter needed
sql_values.append(warranty_id)
update_sql = f"UPDATE warranties SET {', '.join(sql_fields)} WHERE id = %s"
@@ -1768,4 +1792,330 @@ def get_locales():
logger.error(f"Error getting locales: {e}")
return jsonify([{'code': 'en', 'name': 'English', 'native_name': 'English'}]), 500
+# ====== WARRANTY CLAIMS ENDPOINTS ======
+
+@warranties_bp.route('/warranties/<int:warranty_id>/claims', methods=['POST'])
+@token_required
+def create_claim(warranty_id):
+ """Create a new warranty claim"""
+ conn = None
+ cur = None
+
+ try:
+ user_id = request.user['id']
+ data = request.get_json()
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ # Verify warranty exists and user owns it
+ conn = get_db_connection()
+ cur = conn.cursor()
+
+ cur.execute("""
+ SELECT id, product_name FROM warranties
+ WHERE id = %s AND user_id = %s
+ """, (warranty_id, user_id))
+
+ warranty = cur.fetchone()
+ if not warranty:
+ return jsonify({'error': 'Warranty not found or access denied'}), 404
+
+ # Validate required fields
+ claim_date = data.get('claim_date')
+ status = data.get('status', 'Submitted')
+ claim_number = data.get('claim_number', '').strip()
+ description = data.get('description', '').strip()
+ resolution = data.get('resolution', '').strip()
+ resolution_date = data.get('resolution_date')
+
+ if not claim_date:
+ return jsonify({'error': 'Claim date is required'}), 400
+
+ # Parse dates
+ try:
+ parsed_claim_date = date_parse(claim_date).date() if isinstance(claim_date, str) else claim_date
+ except (ValueError, TypeError):
+ return jsonify({'error': 'Invalid claim date format'}), 400
+
+ parsed_resolution_date = None
+ if resolution_date:
+ try:
+ parsed_resolution_date = date_parse(resolution_date).date() if isinstance(resolution_date, str) else resolution_date
+ except (ValueError, TypeError):
+ return jsonify({'error': 'Invalid resolution date format'}), 400
+
+ # Validate status
+ valid_statuses = ['Submitted', 'In Progress', 'Approved', 'Denied', 'Resolved', 'Cancelled']
+ if status not in valid_statuses:
+ status = 'Submitted'
+
+ # Insert new claim
+ cur.execute("""
+ INSERT INTO warranty_claims
+ (warranty_id, claim_date, status, claim_number, description, resolution, resolution_date)
+ VALUES (%s, %s, %s, %s, %s, %s, %s)
+ RETURNING id, created_at, updated_at
+ """, (warranty_id, parsed_claim_date, status, claim_number or None, description or None,
+ resolution or None, parsed_resolution_date))
+
+ result = cur.fetchone()
+ claim_id = result[0]
+ created_at = result[1]
+ updated_at = result[2]
+
+ conn.commit()
+
+ # Return the created claim
+ claim = {
+ 'id': claim_id,
+ 'warranty_id': warranty_id,
+ 'claim_date': parsed_claim_date.isoformat(),
+ 'status': status,
+ 'claim_number': claim_number or None,
+ 'description': description or None,
+ 'resolution': resolution or None,
+ 'resolution_date': parsed_resolution_date.isoformat() if parsed_resolution_date else None,
+ 'created_at': created_at.isoformat() if created_at else None,
+ 'updated_at': updated_at.isoformat() if updated_at else None
+ }
+
+ logger.info(f"Created claim {claim_id} for warranty {warranty_id} by user {user_id}")
+ return jsonify(claim), 201
+
+ except Exception as e:
+ if conn:
+ conn.rollback()
+ logger.error(f"Error creating claim: {e}")
+ return jsonify({'error': 'Internal server error'}), 500
+
+ finally:
+ if cur:
+ cur.close()
+ if conn:
+ release_db_connection(conn)
+
+@warranties_bp.route('/warranties/<int:warranty_id>/claims', methods=['GET'])
+@token_required
+def get_claims(warranty_id):
+ """Get all claims for a warranty"""
+ conn = None
+ cur = None
+
+ try:
+ user_id = request.user['id']
+ # Verify warranty exists and user owns it
+ conn = get_db_connection()
+ cur = conn.cursor()
+
+ cur.execute("""
+ SELECT id, product_name FROM warranties
+ WHERE id = %s AND user_id = %s
+ """, (warranty_id, user_id))
+
+ warranty = cur.fetchone()
+ if not warranty:
+ return jsonify({'error': 'Warranty not found or access denied'}), 404
+
+ # Get all claims for this warranty
+ cur.execute("""
+ SELECT id, warranty_id, claim_date, status, claim_number, description,
+ resolution, resolution_date, created_at, updated_at
+ FROM warranty_claims
+ WHERE warranty_id = %s
+ ORDER BY claim_date DESC, created_at DESC
+ """, (warranty_id,))
+
+ claims = []
+ for row in cur.fetchall():
+ claim = {
+ 'id': row[0],
+ 'warranty_id': row[1],
+ 'claim_date': row[2].isoformat() if row[2] else None,
+ 'status': row[3],
+ 'claim_number': row[4],
+ 'description': row[5],
+ 'resolution': row[6],
+ 'resolution_date': row[7].isoformat() if row[7] else None,
+ 'created_at': row[8].isoformat() if row[8] else None,
+ 'updated_at': row[9].isoformat() if row[9] else None
+ }
+ claims.append(claim)
+
+ return jsonify(claims), 200
+
+ except Exception as e:
+ logger.error(f"Error getting claims: {e}")
+ return jsonify({'error': 'Internal server error'}), 500
+
+ finally:
+ if cur:
+ cur.close()
+ if conn:
+ release_db_connection(conn)
+
+@warranties_bp.route('/warranties/<int:warranty_id>/claims/<int:claim_id>', methods=['PUT'])
+@token_required
+def update_claim(warranty_id, claim_id):
+ """Update a warranty claim"""
+ conn = None
+ cur = None
+
+ try:
+ user_id = request.user['id']
+ data = request.get_json()
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ # Verify warranty exists and user owns it
+ conn = get_db_connection()
+ cur = conn.cursor()
+
+ cur.execute("""
+ SELECT w.id, w.product_name
+ FROM warranties w
+ JOIN warranty_claims c ON w.id = c.warranty_id
+ WHERE w.id = %s AND c.id = %s AND w.user_id = %s
+ """, (warranty_id, claim_id, user_id))
+
+ result = cur.fetchone()
+ if not result:
+ return jsonify({'error': 'Warranty or claim not found or access denied'}), 404
+
+ # Get current claim data
+ cur.execute("""
+ SELECT claim_date, status, claim_number, description, resolution, resolution_date
+ FROM warranty_claims
+ WHERE id = %s AND warranty_id = %s
+ """, (claim_id, warranty_id))
+
+ current_claim = cur.fetchone()
+ if not current_claim:
+ return jsonify({'error': 'Claim not found'}), 404
+
+ # Update fields (keep existing values if not provided)
+ claim_date = data.get('claim_date')
+ status = data.get('status', current_claim[1])
+ claim_number = data.get('claim_number', current_claim[2])
+ description = data.get('description', current_claim[3])
+ resolution = data.get('resolution', current_claim[4])
+ resolution_date = data.get('resolution_date', current_claim[5])
+
+ # Parse dates
+ if claim_date:
+ try:
+ parsed_claim_date = date_parse(claim_date).date() if isinstance(claim_date, str) else claim_date
+ except (ValueError, TypeError):
+ return jsonify({'error': 'Invalid claim date format'}), 400
+ else:
+ parsed_claim_date = current_claim[0]
+
+ if resolution_date:
+ try:
+ parsed_resolution_date = date_parse(resolution_date).date() if isinstance(resolution_date, str) else resolution_date
+ except (ValueError, TypeError):
+ return jsonify({'error': 'Invalid resolution date format'}), 400
+ else:
+ parsed_resolution_date = current_claim[5]
+
+ # Validate status
+ valid_statuses = ['Submitted', 'In Progress', 'Approved', 'Denied', 'Resolved', 'Cancelled']
+ if status not in valid_statuses:
+ status = current_claim[1]
+
+ # Handle empty strings as None
+ claim_number = claim_number.strip() if claim_number else None
+ description = description.strip() if description else None
+ resolution = resolution.strip() if resolution else None
+
+ # Update the claim
+ cur.execute("""
+ UPDATE warranty_claims
+ SET claim_date = %s, status = %s, claim_number = %s, description = %s,
+ resolution = %s, resolution_date = %s, updated_at = CURRENT_TIMESTAMP
+ WHERE id = %s AND warranty_id = %s
+ RETURNING updated_at
+ """, (parsed_claim_date, status, claim_number, description, resolution,
+ parsed_resolution_date, claim_id, warranty_id))
+
+ updated_at = cur.fetchone()[0]
+ conn.commit()
+
+ # Return updated claim
+ claim = {
+ 'id': claim_id,
+ 'warranty_id': warranty_id,
+ 'claim_date': parsed_claim_date.isoformat() if parsed_claim_date else None,
+ 'status': status,
+ 'claim_number': claim_number,
+ 'description': description,
+ 'resolution': resolution,
+ 'resolution_date': parsed_resolution_date.isoformat() if parsed_resolution_date else None,
+ 'updated_at': updated_at.isoformat() if updated_at else None
+ }
+
+ logger.info(f"Updated claim {claim_id} for warranty {warranty_id} by user {user_id}")
+ return jsonify(claim), 200
+
+ except Exception as e:
+ if conn:
+ conn.rollback()
+ logger.error(f"Error updating claim: {e}")
+ return jsonify({'error': 'Internal server error'}), 500
+
+ finally:
+ if cur:
+ cur.close()
+ if conn:
+ release_db_connection(conn)
+
+@warranties_bp.route('/warranties/<int:warranty_id>/claims/<int:claim_id>', methods=['DELETE'])
+@token_required
+def delete_claim(warranty_id, claim_id):
+ """Delete a warranty claim"""
+ conn = None
+ cur = None
+
+ try:
+ user_id = request.user['id']
+ # Verify warranty exists and user owns it
+ conn = get_db_connection()
+ cur = conn.cursor()
+
+ cur.execute("""
+ SELECT w.id, w.product_name
+ FROM warranties w
+ JOIN warranty_claims c ON w.id = c.warranty_id
+ WHERE w.id = %s AND c.id = %s AND w.user_id = %s
+ """, (warranty_id, claim_id, user_id))
+
+ result = cur.fetchone()
+ if not result:
+ return jsonify({'error': 'Warranty or claim not found or access denied'}), 404
+
+ # Delete the claim
+ cur.execute("""
+ DELETE FROM warranty_claims
+ WHERE id = %s AND warranty_id = %s
+ """, (claim_id, warranty_id))
+
+ if cur.rowcount == 0:
+ return jsonify({'error': 'Claim not found'}), 404
+
+ conn.commit()
+
+ logger.info(f"Deleted claim {claim_id} for warranty {warranty_id} by user {user_id}")
+ return jsonify({'message': 'Claim deleted successfully'}), 200
+
+ except Exception as e:
+ if conn:
+ conn.rollback()
+ logger.error(f"Error deleting claim: {e}")
+ return jsonify({'error': 'Internal server error'}), 500
+
+ finally:
+ if cur:
+ cur.close()
+ if conn:
+ release_db_connection(conn)
+
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
index 9a2908f..214eed1 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -10,6 +10,7 @@ services:
- ./backend/migrations:/app/migrations
environment:
- DB_HOST=warrackerdb
+ - DB_PORT=${DB_PORT:-5432}
- DB_NAME=warranty_test
- DB_USER=warranty_user
- DB_PASSWORD=${DB_PASSWORD:-warranty_password}
diff --git a/env.example b/env.example
index 8a0cb8b..be72d24 100644
--- a/env.example
+++ b/env.example
@@ -4,6 +4,7 @@
# Database Configuration
DB_PASSWORD=your_secure_database_password
DB_ADMIN_PASSWORD=your_secure_admin_password
+# DB_PORT=5432
# Application Security
SECRET_KEY=your_very_secure_flask_secret_key_change_this_in_production
diff --git a/frontend/about.html b/frontend/about.html
index 8515a10..ee09b1e 100644
--- a/frontend/about.html
+++ b/frontend/about.html
@@ -318,7 +318,7 @@
<!-- Hero Section -->
<div class="about-hero">
<h1><i class="fas fa-shield-alt"></i> Warracker</h1>
- <div class="version" id="versionDisplay" data-i18n="about.version">Version v0.10.1.9</div>
+ <div class="version" id="versionDisplay" data-i18n="about.version">Version v0.10.1.10</div>
<p class="description" data-i18n="about.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.html
index 3c08958..db14c25 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -509,6 +509,14 @@
</button>
</div>
</div>
+ <!-- URL Input for Invoice -->
+ <div class="form-group url-input-group">
+ <label for="invoiceUrl" data-i18n="warranties.or_link_to_invoice_url">Or Link to Invoice URL</label>
+ <div class="input-with-icon">
+ <i class="fas fa-link"></i>
+ <input type="url" id="invoiceUrl" name="invoice_url" class="form-control" placeholder="https://example.com/invoice.pdf">
+ </div>
+ </div>
</div>
<div class="form-group">
@@ -549,6 +557,14 @@
</button>
</div>
</div>
+ <!-- URL Input for Manual -->
+ <div class="form-group url-input-group">
+ <label for="manualUrl" data-i18n="warranties.or_link_to_manual_url">Or Link to Manual URL</label>
+ <div class="input-with-icon">
+ <i class="fas fa-link"></i>
+ <input type="url" id="manualUrl" name="manual_url" class="form-control" placeholder="https://example.com/manual.pdf">
+ </div>
+ </div>
</div>
<div class="form-group">
<label data-i18n="warranties.files_zip_rar_optional">Files (ZIP/RAR, Optional)</label>
@@ -559,6 +575,14 @@
<input type="file" id="otherDocument" name="other_document" class="file-input" accept=".zip,.rar">
</div>
<div id="otherDocumentFileName" class="file-name"></div>
+ <!-- URL Input for Other Document -->
+ <div class="form-group url-input-group">
+ <label for="otherDocumentUrl" data-i18n="warranties.or_link_to_files_url">Or Link to Files URL</label>
+ <div class="input-with-icon">
+ <i class="fas fa-link"></i>
+ <input type="url" id="otherDocumentUrl" name="other_document_url" class="form-control" placeholder="https://example.com/files.zip">
+ </div>
+ </div>
</div>
</div>
@@ -889,6 +913,14 @@
</button>
</div>
</div>
+ <!-- URL Input for Invoice -->
+ <div class="form-group url-input-group">
+ <label for="editInvoiceUrl" data-i18n="warranties.or_link_to_invoice_url">Or Link to Invoice URL</label>
+ <div class="input-with-icon">
+ <i class="fas fa-link"></i>
+ <input type="url" id="editInvoiceUrl" name="invoice_url" class="form-control" placeholder="https://example.com/invoice.pdf">
+ </div>
+ </div>
</div>
<div class="form-group">
@@ -931,6 +963,14 @@
</button>
</div>
</div>
+ <!-- URL Input for Manual -->
+ <div class="form-group url-input-group">
+ <label for="editManualUrl" data-i18n="warranties.or_link_to_manual_url">Or Link to Manual URL</label>
+ <div class="input-with-icon">
+ <i class="fas fa-link"></i>
+ <input type="url" id="editManualUrl" name="manual_url" class="form-control" placeholder="https://example.com/manual.pdf">
+ </div>
+ </div>
</div>
<div class="form-group">
<label data-i18n="warranties.files_zip_rar_optional">Files (ZIP/RAR, Optional)</label>
@@ -943,6 +983,14 @@
<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> <span data-i18n="warranties.delete_files">Delete Files</span></button>
+ <!-- URL Input for Other Document -->
+ <div class="form-group url-input-group">
+ <label for="editOtherDocumentUrl" data-i18n="warranties.or_link_to_files_url">Or Link to Files URL</label>
+ <div class="input-with-icon">
+ <i class="fas fa-link"></i>
+ <input type="url" id="editOtherDocumentUrl" name="other_document_url" class="form-control" placeholder="https://example.com/files.zip">
+ </div>
+ </div>
</div>
</div>
@@ -1082,6 +1130,97 @@
</div>
</div>
+ <!-- Claims Modal -->
+ <div id="claimsModal" class="modal-backdrop">
+ <div class="modal modal-large">
+ <div class="modal-header">
+ <h3 class="modal-title" data-i18n="claims.warranty_claims">Warranty Claims</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <div class="claims-header">
+ <div id="warrantyClaimInfo" class="warranty-claim-info">
+ <!-- Warranty info will be populated here -->
+ </div>
+ </div>
+ <div id="claimsListBody" class="claims-list">
+ <div class="loading-message" style="text-align: center; padding: 20px;">
+ <i class="fas fa-spinner fa-spin"></i> Loading claims...
+ </div>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button id="addClaimBtn" class="btn btn-primary">
+ <i class="fas fa-plus"></i> <span data-i18n="claims.add_new_claim">Add New Claim</span>
+ </button>
+ <button class="btn btn-secondary" data-dismiss="modal" data-i18n="actions.close">Close</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Claim Form Modal -->
+ <div id="claimFormModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3 class="modal-title" id="claimFormTitle" data-i18n="claims.add_claim">Add Claim</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <form id="claimForm">
+ <input type="hidden" id="editClaimId" value="">
+
+ <div class="form-group">
+ <label for="claimDate" data-i18n="claims.claim_date">Claim Date:</label>
+ <input type="date" id="claimDate" name="claim_date" class="form-control" required>
+ </div>
+
+ <div class="form-group">
+ <label for="claimStatus" data-i18n="claims.status">Status:</label>
+ <select id="claimStatus" name="status" class="form-control" required>
+ <option value="Submitted" data-i18n="claims.status_submitted">Submitted</option>
+ <option value="In Progress" data-i18n="claims.status_in_progress">In Progress</option>
+ <option value="Approved" data-i18n="claims.status_approved">Approved</option>
+ <option value="Denied" data-i18n="claims.status_denied">Denied</option>
+ <option value="Resolved" data-i18n="claims.status_resolved">Resolved</option>
+ <option value="Cancelled" data-i18n="claims.status_cancelled">Cancelled</option>
+ </select>
+ </div>
+
+ <div class="form-group">
+ <label for="claimNumber" data-i18n="claims.claim_number">Claim Number:</label>
+ <input type="text" id="claimNumber" name="claim_number" class="form-control"
+ placeholder="e.g., CLM-2025-001">
+ </div>
+
+ <div class="form-group">
+ <label for="claimDescription" data-i18n="claims.description">Description:</label>
+ <textarea id="claimDescription" name="description" class="form-control" rows="4"
+ data-i18n-placeholder="claims.description_placeholder"
+ placeholder="Describe the issue and reason for the claim..."></textarea>
+ </div>
+
+ <div class="form-group">
+ <label for="claimResolution" data-i18n="claims.resolution">Resolution:</label>
+ <textarea id="claimResolution" name="resolution" class="form-control" rows="3"
+ data-i18n-placeholder="claims.resolution_placeholder"
+ placeholder="Resolution details (if any)..."></textarea>
+ </div>
+
+ <div class="form-group">
+ <label for="resolutionDate" data-i18n="claims.resolution_date">Resolution Date:</label>
+ <input type="date" id="resolutionDate" name="resolution_date" class="form-control">
+ </div>
+ </form>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-dismiss="modal" data-i18n="actions.cancel">Cancel</button>
+ <button type="submit" form="claimForm" class="btn btn-primary" id="saveClaimBtn">
+ <i class="fas fa-save"></i> <span data-i18n="actions.save">Save</span>
+ </button>
+ </div>
+ </div>
+ </div>
+
<!-- Toast Container -->
<div id="toastContainer" class="toast-container"></div>
diff --git a/frontend/script.js b/frontend/script.js
index dfd39da..1a75570 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -83,6 +83,17 @@ const tagManagementModal = document.getElementById('tagManagementModal');
const newTagForm = document.getElementById('newTagForm');
const existingTagsContainer = document.getElementById('existingTags');
+// Claims modal elements
+const claimsModal = document.getElementById('claimsModal');
+const claimFormModal = document.getElementById('claimFormModal');
+const claimsListBody = document.getElementById('claimsListBody');
+const addClaimBtn = document.getElementById('addClaimBtn');
+const claimForm = document.getElementById('claimForm');
+const saveClaimBtn = document.getElementById('saveClaimBtn');
+const editClaimId = document.getElementById('editClaimId');
+const claimFormTitle = document.getElementById('claimFormTitle');
+const warrantyClaimInfo = document.getElementById('warrantyClaimInfo');
+
// --- Add near other DOM Element declarations ---
const isLifetimeCheckbox = document.getElementById('isLifetime');
const warrantyDurationFields = document.getElementById('warrantyDurationFields'); // New container
@@ -1139,25 +1150,46 @@ function updateSummary() {
productPhotoFile.name : 'No photo selected';
}
- const invoiceFile = document.getElementById('invoice')?.files[0];
+ const invoiceFile = document.getElementById('invoice')?.files[0];
+ const invoiceUrlField = document.getElementById('invoiceUrl');
+ const invoiceUrl = invoiceUrlField ? invoiceUrlField.value : '';
const summaryInvoice = document.getElementById('summary-invoice');
if (summaryInvoice) {
- summaryInvoice.textContent = invoiceFile ?
- invoiceFile.name : 'No file selected';
+ if (invoiceFile) {
+ summaryInvoice.textContent = invoiceFile.name;
+ } else if (invoiceUrl) {
+ summaryInvoice.textContent = 'URL: ' + invoiceUrl;
+ } else {
+ summaryInvoice.textContent = 'Not specified';
+ }
}
-
+
const manualFile = document.getElementById('manual')?.files[0];
+ const manualUrlField = document.getElementById('manualUrl');
+ const manualUrl = manualUrlField ? manualUrlField.value : '';
const summaryManual = document.getElementById('summary-manual');
if (summaryManual) {
- summaryManual.textContent = manualFile ?
- manualFile.name : 'No file selected';
+ if (manualFile) {
+ summaryManual.textContent = manualFile.name;
+ } else if (manualUrl) {
+ summaryManual.textContent = 'URL: ' + manualUrl;
+ } else {
+ summaryManual.textContent = 'Not specified';
+ }
}
const otherDocumentFile = document.getElementById('otherDocument')?.files[0];
+ const otherDocumentUrlField = document.getElementById('otherDocumentUrl');
+ const otherDocumentUrl = otherDocumentUrlField ? otherDocumentUrlField.value : '';
const summaryOtherDocument = document.getElementById('summary-other-document');
if (summaryOtherDocument) {
- summaryOtherDocument.textContent = otherDocumentFile ?
- otherDocumentFile.name : 'No file selected';
+ if (otherDocumentFile) {
+ summaryOtherDocument.textContent = otherDocumentFile.name;
+ } else if (otherDocumentUrl) {
+ summaryOtherDocument.textContent = 'URL: ' + otherDocumentUrl;
+ } else {
+ summaryOtherDocument.textContent = 'Not specified';
+ }
}
// Tags
@@ -2305,6 +2337,9 @@ async function renderWarranties(warrantiesToRender) {
// Generate action buttons HTML based on permissions
const actionButtonsHtml = canEdit ? `
+ <button class="action-btn claims-link" title="Claims" data-id="${warranty.id}">
+ <i class="fas fa-clipboard-list"></i>
+ </button>
<button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
<i class="fas fa-edit"></i>
</button>
@@ -2312,6 +2347,9 @@ async function renderWarranties(warrantiesToRender) {
<i class="fas fa-trash"></i>
</button>
` : `
+ <button class="action-btn claims-link" title="Claims" data-id="${warranty.id}">
+ <i class="fas fa-clipboard-list"></i>
+ </button>
<span class="action-btn-placeholder" title="View only - not your warranty">
<i class="fas fa-eye" style="color: #666;"></i>
</span>
@@ -2373,6 +2411,7 @@ async function renderWarranties(warrantiesToRender) {
${generateDocumentLink(warranty, 'manual')}
${generateDocumentLink(warranty, 'other')}
${notesLinkHtml}
+
</div>
</div>
` : ''}
@@ -2434,6 +2473,7 @@ async function renderWarranties(warrantiesToRender) {
${generateDocumentLink(warranty, 'manual')}
${generateDocumentLink(warranty, 'other')}
${notesLinkHtml}
+
</div>
</div>
` : ''}
@@ -2498,6 +2538,7 @@ async function renderWarranties(warrantiesToRender) {
${generateDocumentLink(warranty, 'manual')}
${generateDocumentLink(warranty, 'other')}
${notesLinkHtml}
+
</div>
</div>
` : ''}
@@ -2751,6 +2792,16 @@ async function openEditModal(warranty) {
}
document.getElementById('editVendor').value = warranty.vendor || '';
+ // Populate URL fields for documents (with null checks)
+ const editInvoiceUrl = document.getElementById('editInvoiceUrl');
+ if (editInvoiceUrl) editInvoiceUrl.value = warranty.invoice_url || '';
+
+ const editManualUrl = document.getElementById('editManualUrl');
+ if (editManualUrl) editManualUrl.value = warranty.manual_url || '';
+
+ const editOtherDocumentUrl = document.getElementById('editOtherDocumentUrl');
+ if (editOtherDocumentUrl) editOtherDocumentUrl.value = warranty.other_document_url || '';
+
// Handle warranty type - check if it's a predefined option or custom
const editWarrantyTypeSelect = document.getElementById('editWarrantyType');
const editWarrantyTypeCustom = document.getElementById('editWarrantyTypeCustom');
@@ -3432,6 +3483,16 @@ async function handleFormSubmit(event) { // Made async to properly await paperle
formData.append('tag_ids', JSON.stringify([])); // Send empty array if no tags
}
+ // Add URL fields for documents (with null checks)
+ const invoiceUrlField = document.getElementById('invoiceUrl');
+ formData.append('invoice_url', invoiceUrlField ? invoiceUrlField.value || '' : '');
+
+ const manualUrlField = document.getElementById('manualUrl');
+ formData.append('manual_url', manualUrlField ? manualUrlField.value || '' : '');
+
+ const otherDocumentUrlField = document.getElementById('otherDocumentUrl');
+ formData.append('other_document_url', otherDocumentUrlField ? otherDocumentUrlField.value || '' : '');
+
// --- Ensure is_lifetime is correctly added ---
// FormData already includes it if the checkbox is checked. If not checked, it's omitted.
// We need to explicitly add 'false' if it's not checked.
@@ -3662,8 +3723,373 @@ document.addEventListener('DOMContentLoaded', function() {
// loadPreferences(); // Consider if needed
// REMOVED: updateCurrencySymbols(); // Now called after authStateReady
+
+ // Initialize claims functionality
+ initClaimsEventListeners();
});
+// ====== WARRANTY CLAIMS FUNCTIONALITY ======
+
+// Global variables for claims
+let currentClaimsWarrantyId = null;
+let currentClaims = [];
+
+/**
+ * Initialize claims event listeners
+ */
+function initClaimsEventListeners() {
+ // Event delegation for claims links
+ if (warrantiesList) {
+ warrantiesList.addEventListener('click', (e) => {
+ if (e.target.closest('.claims-link')) {
+ e.preventDefault();
+ const warrantyId = parseInt(e.target.closest('.claims-link').dataset.id);
+ openClaimsModal(warrantyId);
+ }
+ });
+ }
+
+ // Add claim button
+ if (addClaimBtn) {
+ addClaimBtn.addEventListener('click', () => {
+ openClaimFormModal();
+ });
+ }
+
+ // Claim form submission
+ if (claimForm) {
+ claimForm.addEventListener('submit', handleClaimFormSubmit);
+ }
+
+ // Modal close handling - Removed backdrop click listeners to match warranty modal behavior
+ // Claims modals now only close via explicit close buttons with [data-dismiss="modal"]
+ // The general modal click prevention (e.stopPropagation) handles preventing backdrop clicks
+
+ // Add event listeners for claims modal close buttons
+ if (claimsModal) {
+ claimsModal.querySelectorAll('[data-dismiss="modal"]').forEach(closeBtn => {
+ closeBtn.addEventListener('click', () => {
+ closeClaimsModal();
+ });
+ });
+ }
+
+ if (claimFormModal) {
+ claimFormModal.querySelectorAll('[data-dismiss="modal"]').forEach(closeBtn => {
+ closeBtn.addEventListener('click', () => {
+ closeClaimFormModal();
+ });
+ });
+ }
+}
+
+/**
+ * Open the claims modal for a specific warranty
+ */
+async function openClaimsModal(warrantyId) {
+ try {
+ currentClaimsWarrantyId = warrantyId;
+
+ // Find warranty info
+ const warranty = warranties.find(w => w.id === warrantyId);
+ if (!warranty) {
+ showToast(window.i18next ? window.i18next.t('claims.warranty_not_found') : 'Warranty not found', 'error');
+ return;
+ }
+
+ // Update warranty info in modal
+ if (warrantyClaimInfo) {
+ warrantyClaimInfo.innerHTML = `
+ <div class="warranty-info-card">
+ <h4>${warranty.product_name || 'Unnamed Product'}</h4>
+ <div class="warranty-details">
+ <span><i class="fas fa-building"></i> ${warranty.vendor || 'Unknown Vendor'}</span>
+ <span><i class="fas fa-calendar"></i> Expires: ${formatDate(warranty.expiration_date ? new Date(warranty.expiration_date) : null)}</span>
+ <span class="warranty-status status-${warranty.status || 'unknown'}">
+ ${warranty.statusText || 'Unknown Status'}
+ </span>
+ </div>
+ </div>
+ `;
+ }
+
+ // Show modal
+ claimsModal.classList.add('active');
+
+ // Load claims
+ await loadClaims(warrantyId);
+
+ } catch (error) {
+ console.error('Error opening claims modal:', error);
+ showToast('Failed to open claims modal', 'error');
+ }
+}
+
+/**
+ * Load claims for a warranty
+ */
+async function loadClaims(warrantyId) {
+ try {
+ // Show loading
+ if (claimsListBody) {
+ claimsListBody.innerHTML = `
+ <div class="loading-message" style="text-align: center; padding: 20px;">
+ <i class="fas fa-spinner fa-spin"></i> Loading claims...
+ </div>
+ `;
+ }
+
+ // Fetch claims
+ const response = await fetch(`/api/warranties/${warrantyId}/claims`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to load claims');
+ }
+
+ currentClaims = await response.json();
+ renderClaims();
+
+ } catch (error) {
+ console.error('Error loading claims:', error);
+ if (claimsListBody) {
+ claimsListBody.innerHTML = `
+ <div class="error-message" style="text-align: center; padding: 20px; color: var(--danger-color);">
+ <i class="fas fa-exclamation-triangle"></i> Failed to load claims
+ </div>
+ `;
+ }
+ }
+}
+
+/**
+ * Render claims list
+ */
+function renderClaims() {
+ if (!claimsListBody) return;
+
+ if (currentClaims.length === 0) {
+ claimsListBody.innerHTML = `
+ <div class="no-claims-message" style="text-align: center; padding: 40px;">
+ <i class="fas fa-clipboard-list" style="font-size: 3rem; color: var(--medium-gray); margin-bottom: 1rem;"></i>
+ <h4 style="color: var(--text-color); margin-bottom: 0.5rem;">${window.i18next ? window.i18next.t('claims.no_claims_yet') : 'No Claims Yet'}</h4>
+ <p style="color: var(--dark-gray); margin-bottom: 0;">${window.i18next ? window.i18next.t('claims.no_claims_message') : 'Click "Add New Claim" to get started'}</p>
+ </div>
+ `;
+ return;
+ }
+
+ let claimsHtml = '';
+ currentClaims.forEach(claim => {
+ claimsHtml += `
+ <div class="claim-item" data-claim-id="${claim.id}">
+ <div class="claim-header">
+ <div class="claim-info">
+ <div class="claim-title">
+ ${claim.claim_number ? `<strong>${claim.claim_number}</strong>` : `<strong>Claim #${claim.id}</strong>`}
+ <span class="claim-status-badge claim-status-${claim.status.toLowerCase().replace(' ', '-')}">
+ ${claim.status}
+ </span>
+ </div>
+ <div class="claim-date">
+ <i class="fas fa-calendar"></i> ${formatDate(claim.claim_date ? new Date(claim.claim_date) : null)}
+ ${claim.resolution_date && claim.resolution_date.trim() ? `<span style="margin-left: 10px;"><i class="fas fa-check-circle"></i> Resolved: ${formatDate(new Date(claim.resolution_date))}</span>` : ''}
+ </div>
+ </div>
+ <div class="claim-actions">
+ <button class="btn btn-sm btn-secondary edit-claim-btn" data-claim-id="${claim.id}">
+ <i class="fas fa-edit"></i> Edit
+ </button>
+ <button class="btn btn-sm btn-danger delete-claim-btn" data-claim-id="${claim.id}">
+ <i class="fas fa-trash"></i> Delete
+ </button>
+ </div>
+ </div>
+ ${claim.description ? `<div class="claim-description">${escapeHtml(claim.description)}</div>` : ''}
+ ${claim.resolution ? `<div class="claim-resolution"><strong>Resolution:</strong> ${escapeHtml(claim.resolution)}</div>` : ''}
+ </div>
+ `;
+ });
+
+ claimsListBody.innerHTML = claimsHtml;
+
+ // Add event listeners for edit and delete buttons
+ claimsListBody.addEventListener('click', (e) => {
+ if (e.target.closest('.edit-claim-btn')) {
+ const claimId = parseInt(e.target.closest('.edit-claim-btn').dataset.claimId);
+ const claim = currentClaims.find(c => c.id === claimId);
+ if (claim) {
+ openClaimFormModal(claim);
+ }
+ }
+
+ if (e.target.closest('.delete-claim-btn')) {
+ const claimId = parseInt(e.target.closest('.delete-claim-btn').dataset.claimId);
+ if (confirm(window.i18next ? window.i18next.t('claims.confirm_delete_claim') : 'Are you sure you want to delete this claim?')) {
+ deleteClaim(claimId);
+ }
+ }
+ });
+}
+
+/**
+ * Open claim form modal for adding or editing
+ */
+function openClaimFormModal(claim = null) {
+ if (!claimFormModal) return;
+
+ // Update title
+ if (claimFormTitle) {
+ claimFormTitle.textContent = claim ? (window.i18next ? window.i18next.t('claims.edit_claim') : 'Edit Claim') : (window.i18next ? window.i18next.t('claims.add_new_claim') : 'Add New Claim');
+ }
+
+ // Reset form
+ if (claimForm) {
+ claimForm.reset();
+ }
+
+ if (claim) {
+ // Populate form with claim data
+ if (editClaimId) editClaimId.value = claim.id;
+ if (document.getElementById('claimDate')) document.getElementById('claimDate').value = claim.claim_date || '';
+ if (document.getElementById('claimStatus')) document.getElementById('claimStatus').value = claim.status;
+ if (document.getElementById('claimNumber')) document.getElementById('claimNumber').value = claim.claim_number || '';
+ if (document.getElementById('claimDescription')) document.getElementById('claimDescription').value = claim.description || '';
+ if (document.getElementById('claimResolution')) document.getElementById('claimResolution').value = claim.resolution || '';
+ if (document.getElementById('resolutionDate')) document.getElementById('resolutionDate').value = claim.resolution_date || '';
+ } else {
+ // Set default values for new claim
+ if (editClaimId) editClaimId.value = '';
+ if (document.getElementById('claimDate')) document.getElementById('claimDate').value = new Date().toISOString().split('T')[0];
+ if (document.getElementById('claimStatus')) document.getElementById('claimStatus').value = 'Submitted';
+ }
+
+ // Show modal
+ claimFormModal.classList.add('active');
+}
+
+/**
+ * Handle claim form submission
+ */
+async function handleClaimFormSubmit(event) {
+ event.preventDefault();
+
+ try {
+ const formData = new FormData(claimForm);
+ const claimId = editClaimId.value;
+
+ const claimData = {
+ claim_date: formData.get('claim_date'),
+ status: formData.get('status'),
+ claim_number: formData.get('claim_number'),
+ description: formData.get('description'),
+ resolution: formData.get('resolution'),
+ resolution_date: formData.get('resolution_date')
+ };
+
+ // Remove empty strings
+ Object.keys(claimData).forEach(key => {
+ if (claimData[key] === '') {
+ claimData[key] = null;
+ }
+ });
+
+ const isEdit = claimId && claimId !== '';
+ const url = isEdit
+ ? `/api/warranties/${currentClaimsWarrantyId}/claims/${claimId}`
+ : `/api/warranties/${currentClaimsWarrantyId}/claims`;
+ const method = isEdit ? 'PUT' : 'POST';
+
+ const response = await fetch(url, {
+ method: method,
+ headers: {
+ 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(claimData)
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to save claim');
+ }
+
+ showToast(isEdit ? (window.i18next ? window.i18next.t('claims.claim_updated_successfully') : 'Claim updated successfully') : (window.i18next ? window.i18next.t('claims.claim_created_successfully') : 'Claim created successfully'), 'success');
+ closeClaimFormModal();
+
+ // Reload claims
+ await loadClaims(currentClaimsWarrantyId);
+
+ } catch (error) {
+ console.error('Error saving claim:', error);
+ showToast(error.message || 'Failed to save claim', 'error');
+ }
+}
+
+/**
+ * Delete a claim
+ */
+async function deleteClaim(claimId) {
+ try {
+ const response = await fetch(`/api/warranties/${currentClaimsWarrantyId}/claims/${claimId}`, {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to delete claim');
+ }
+
+ showToast(window.i18next ? window.i18next.t('claims.claim_deleted_successfully') : 'Claim deleted successfully', 'success');
+
+ // Reload claims
+ await loadClaims(currentClaimsWarrantyId);
+
+ } catch (error) {
+ console.error('Error deleting claim:', error);
+ showToast(error.message || 'Failed to delete claim', 'error');
+ }
+}
+
+/**
+ * Close claims modal
+ */
+function closeClaimsModal() {
+ if (claimsModal) {
+ claimsModal.classList.remove('active');
+ }
+ currentClaimsWarrantyId = null;
+ currentClaims = [];
+}
+
+/**
+ * Close claim form modal
+ */
+function closeClaimFormModal() {
+ if (claimFormModal) {
+ claimFormModal.classList.remove('active');
+ }
+}
+
+/**
+ * Escape HTML to prevent XSS
+ */
+function escapeHtml(text) {
+ if (!text) return '';
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML;
+}
+
// Add this function to handle edit tab functionality
function initEditTabs() {
const editTabBtns = document.querySelectorAll('.edit-tab-btn');
@@ -3868,6 +4294,7 @@ function generateDocumentLink(warranty, docType) {
invoice: {
localPath: warranty.invoice_path,
paperlessId: warranty.paperless_invoice_id,
+ url: warranty.invoice_url,
icon: 'fas fa-file-invoice',
label: 'Invoice',
className: 'invoice-link'
@@ -3875,6 +4302,7 @@ function generateDocumentLink(warranty, docType) {
manual: {
localPath: warranty.manual_path,
paperlessId: warranty.paperless_manual_id,
+ url: warranty.manual_url,
icon: 'fas fa-book',
label: 'Manual',
className: 'manual-link'
@@ -3882,6 +4310,7 @@ function generateDocumentLink(warranty, docType) {
other: {
localPath: warranty.other_document_path,
paperlessId: warranty.paperless_other_id,
+ url: warranty.other_document_url,
icon: 'fas fa-file-alt',
label: 'Files',
className: 'other-document-link'
@@ -3889,6 +4318,7 @@ function generateDocumentLink(warranty, docType) {
photo: {
localPath: warranty.product_photo_path,
paperlessId: warranty.paperless_photo_id,
+ url: null, // Photos don't have URLs
icon: 'fas fa-image',
label: 'Photo',
className: 'photo-link'
@@ -3900,19 +4330,29 @@ function generateDocumentLink(warranty, docType) {
const hasLocal = config.localPath && config.localPath !== 'null';
const hasPaperless = config.paperlessId && config.paperlessId !== null;
-
+ const hasUrl = config.url && config.url.trim() !== '';
+
+ let linksHtml = '';
if (hasLocal) {
- return `<a href="#" onclick="openSecureFile('${config.localPath}'); return false;" class="${config.className}">
+ linksHtml += `<a href="#" onclick="openSecureFile('${config.localPath}'); return false;" class="${config.className}">
<i class="${config.icon}"></i> ${config.label}
</a>`;
} else if (hasPaperless) {
- return `<a href="#" onclick="openPaperlessDocument(${config.paperlessId}); return false;" class="${config.className}">
+ linksHtml += `<a href="#" onclick="openPaperlessDocument(${config.paperlessId}); return false;" class="${config.className}">
<i class="${config.icon}"></i> ${config.label} <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i>
</a>`;
}
- return '';
+ // Add URL link if available
+ if (hasUrl) {
+ if (linksHtml) linksHtml += ' ';
+ linksHtml += `<a href="${config.url}" target="_blank" class="document-url-link ${config.className}" title="Open ${config.label} URL">
+ <i class="fas fa-link"></i> ${config.label} Link
+ </a>`;
+ }
+
+ return linksHtml;
}
// Initialize the warranty form and all its components
@@ -4681,9 +5121,10 @@ function setupUIEventListeners() {
if (modalToClose) {
// *** MODIFIED CHECK ***
// If the click target is the backdrop itself (not a dismiss button)
- // AND the modal is the 'addWarrantyModal' or 'editModal', then DO NOTHING.
- if ((modalToClose.id === 'addWarrantyModal' || modalToClose.id === 'editModal') && e.target === modalToClose) {
- return; // Ignore backdrop click for addWarrantyModal and editModal
+ // AND the modal is one of the protected modals, then DO NOTHING.
+ if ((modalToClose.id === 'addWarrantyModal' || modalToClose.id === 'editModal' ||
+ modalToClose.id === 'claimsModal' || modalToClose.id === 'claimFormModal') && e.target === modalToClose) {
+ return; // Ignore backdrop click for protected modals
}
// *** END MODIFIED CHECK ***
@@ -5223,6 +5664,16 @@ function saveWarranty() {
formData.append('tag_ids', JSON.stringify([]));
}
+ // Add URL fields for documents (with null checks)
+ const editInvoiceUrlField = document.getElementById('editInvoiceUrl');
+ formData.append('invoice_url', editInvoiceUrlField ? editInvoiceUrlField.value || '' : '');
+
+ const editManualUrlField = document.getElementById('editManualUrl');
+ formData.append('manual_url', editManualUrlField ? editManualUrlField.value || '' : '');
+
+ const editOtherDocumentUrlField = document.getElementById('editOtherDocumentUrl');
+ formData.append('other_document_url', editOtherDocumentUrlField ? editOtherDocumentUrlField.value || '' : '');
+
// Files
const invoiceFile = document.getElementById('editInvoice').files[0];
if (invoiceFile) {
diff --git a/frontend/status.html b/frontend/status.html
index ea73dad..dc3374e 100644
--- a/frontend/status.html
+++ b/frontend/status.html
@@ -677,6 +677,14 @@
<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> <span data-i18n="warranties.delete_invoice">Delete Invoice</span></button>
+ <!-- URL Input for Invoice -->
+ <div class="form-group url-input-group">
+ <label for="editInvoiceUrl" data-i18n="warranties.or_link_to_invoice_url">Or Link to Invoice URL</label>
+ <div class="input-with-icon">
+ <i class="fas fa-link"></i>
+ <input type="url" id="editInvoiceUrl" name="invoice_url" class="form-control" placeholder="https://example.com/invoice.pdf">
+ </div>
+ </div>
</div>
<div class="form-group">
<label data-i18n="warranties.product_manual_optional">Product Manual (Optional)</label>
@@ -689,6 +697,14 @@
<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> <span data-i18n="warranties.delete_manual">Delete Manual</span></button>
+ <!-- URL Input for Manual -->
+ <div class="form-group url-input-group">
+ <label for="editManualUrl" data-i18n="warranties.or_link_to_manual_url">Or Link to Manual URL</label>
+ <div class="input-with-icon">
+ <i class="fas fa-link"></i>
+ <input type="url" id="editManualUrl" name="manual_url" class="form-control" placeholder="https://example.com/manual.pdf">
+ </div>
+ </div>
</div>
<div class="form-group">
<label data-i18n="warranties.files_optional">Files (ZIP/RAR, Optional)</label>
@@ -701,6 +717,14 @@
<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> <span data-i18n="warranties.delete_files">Delete Files</span></button>
+ <!-- URL Input for Other Document -->
+ <div class="form-group url-input-group">
+ <label for="editOtherDocumentUrl" data-i18n="warranties.or_link_to_files_url">Or Link to Files URL</label>
+ <div class="input-with-icon">
+ <i class="fas fa-link"></i>
+ <input type="url" id="editOtherDocumentUrl" name="other_document_url" class="form-control" placeholder="https://example.com/files.zip">
+ </div>
+ </div>
</div>
</div>
diff --git a/frontend/style.css b/frontend/style.css
index 005c18e..15ef9bb 100644
--- a/frontend/style.css
+++ b/frontend/style.css
@@ -484,6 +484,56 @@ input.invalid {
word-break: break-all;
}
+/* URL Input Groups */
+.url-input-group {
+ margin-top: 15px;
+}
+
+.input-with-icon {
+ position: relative;
+ display: flex;
+ align-items: center;
+}
+
+.input-with-icon i {
+ position: absolute;
+ left: 12px;
+ top: 50%;
+ transform: translateY(-50%);
+ color: var(--text-muted, #6c757d);
+ font-size: 1rem;
+ z-index: 2;
+}
+
+.input-with-icon input {
+ padding-left: 40px;
+ width: 100%;
+}
+
+/* Document URL Links */
+.document-url-link {
+ display: inline-flex;
+ align-items: center;
+ color: var(--primary-color);
+ text-decoration: none;
+ font-size: 0.9rem;
+ margin-right: 10px;
+ padding: 4px 8px;
+ border-radius: 4px;
+ transition: background-color 0.2s, color 0.2s;
+}
+
+.document-url-link:hover {
+ background-color: rgba(52, 152, 219, 0.1);
+ color: var(--primary-dark);
+ text-decoration: none;
+}
+
+.document-url-link i {
+ margin-right: 4px;
+ font-size: 0.8em;
+}
+
.btn {
display: inline-block;
font-weight: 500;
@@ -4485,3 +4535,267 @@ html.dark-mode .warracker-footer a:hover {
[dir="rtl"] .collapse-icon.rotated {
transform: rotate(0deg);
}
+
+/* === WARRANTY CLAIMS STYLES === */
+
+/* Claims link styling */
+.claims-link {
+ display: inline-flex;
+ align-items: center;
+ padding: 6px 12px;
+ margin: 2px;
+ color: var(--primary-color);
+ text-decoration: none;
+ border: 1px solid var(--primary-color);
+ border-radius: 4px;
+ font-size: 0.85rem;
+ transition: all 0.2s ease;
+ background: transparent;
+}
+
+.claims-link:hover {
+ background: var(--primary-color);
+ color: white;
+ text-decoration: none;
+}
+
+.claims-link i {
+ margin-right: 5px;
+}
+
+/* Claims modal styles */
+.warranty-info-card {
+ background: var(--card-bg);
+ border: 1px solid var(--border-color);
+ border-radius: var(--border-radius);
+ padding: 15px;
+ margin-bottom: 20px;
+}
+
+.warranty-info-card h4 {
+ margin: 0 0 10px 0;
+ color: var(--text-color);
+ font-size: 1.2rem;
+}
+
+.warranty-details {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 15px;
+}
+
+.warranty-details span {
+ display: flex;
+ align-items: center;
+ font-size: 0.9rem;
+ color: var(--dark-gray);
+}
+
+.warranty-details i {
+ margin-right: 5px;
+}
+
+/* Claims list styles */
+.claims-list {
+ max-height: 500px;
+ overflow-y: auto;
+}
+
+.claim-item {
+ border: 1px solid var(--border-color);
+ border-radius: var(--border-radius);
+ margin-bottom: 15px;
+ padding: 15px;
+ background: var(--card-bg);
+ transition: box-shadow 0.2s ease;
+}
+
+.claim-item:hover {
+ box-shadow: 0 2px 8px var(--shadow-color);
+}
+
+.claim-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-start;
+ margin-bottom: 10px;
+}
+
+.claim-info {
+ flex: 1;
+}
+
+.claim-title {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin-bottom: 5px;
+}
+
+.claim-title strong {
+ color: var(--text-color);
+ font-size: 1.1rem;
+}
+
+.claim-date {
+ display: flex;
+ align-items: center;
+ font-size: 0.9rem;
+ color: var(--dark-gray);
+}
+
+.claim-date i {
+ margin-right: 5px;
+}
+
+.claim-actions {
+ display: flex;
+ gap: 8px;
+}
+
+.claim-description, .claim-resolution {
+ background: var(--light-gray);
+ padding: 10px;
+ border-radius: 4px;
+ font-size: 0.9rem;
+ line-height: 1.4;
+ margin-top: 10px;
+}
+
+.claim-resolution {
+ background: rgba(46, 204, 113, 0.1);
+ border-left: 4px solid var(--secondary-color);
+}
+
+/* Status badges */
+.claim-status-badge {
+ padding: 3px 8px;
+ border-radius: 12px;
+ font-size: 0.75rem;
+ font-weight: 500;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+}
+
+.claim-status-submitted {
+ background-color: #3498db;
+ color: white;
+}
+
+.claim-status-in-progress {
+ background-color: #f39c12;
+ color: white;
+}
+
+.claim-status-approved {
+ background-color: #2ecc71;
+ color: white;
+}
+
+.claim-status-denied {
+ background-color: #e74c3c;
+ color: white;
+}
+
+.claim-status-resolved {
+ background-color: #27ae60;
+ color: white;
+}
+
+.claim-status-cancelled {
+ background-color: #95a5a6;
+ color: white;
+}
+
+/* No claims message */
+.no-claims-message {
+ text-align: center;
+ padding: 40px 20px;
+}
+
+.no-claims-message i {
+ font-size: 3rem;
+ color: var(--medium-gray);
+ margin-bottom: 1rem;
+}
+
+.no-claims-message h4 {
+ color: var(--text-color);
+ margin-bottom: 0.5rem;
+ font-weight: 500;
+}
+
+.no-claims-message p {
+ color: var(--dark-gray);
+ margin: 0;
+}
+
+/* Claim form styles */
+.claim-form .form-group {
+ margin-bottom: 20px;
+}
+
+.claim-form label {
+ display: block;
+ margin-bottom: 5px;
+ font-weight: 500;
+ color: var(--text-color);
+}
+
+.claim-form .form-control {
+ width: 100%;
+ padding: 10px;
+ border: 1px solid var(--border-color);
+ border-radius: var(--border-radius);
+ font-size: 0.9rem;
+ background: var(--card-bg);
+ color: var(--text-color);
+ transition: border-color 0.2s ease;
+}
+
+.claim-form .form-control:focus {
+ outline: none;
+ border-color: var(--primary-color);
+ box-shadow: 0 0 0 2px rgba(var(--primary-rgb), 0.2);
+}
+
+.claim-form textarea.form-control {
+ resize: vertical;
+ min-height: 80px;
+}
+
+/* Responsive design */
+@media (max-width: 768px) {
+ .claim-header {
+ flex-direction: column;
+ gap: 10px;
+ }
+
+ .claim-actions {
+ align-self: flex-start;
+ }
+
+ .warranty-details {
+ flex-direction: column;
+ gap: 8px;
+ }
+
+ .claims-link {
+ font-size: 0.8rem;
+ padding: 4px 8px;
+ }
+}
+
+/* Dark mode specific adjustments */
+:root[data-theme="dark"] .claim-item,
+:root[data-theme="dark"] .warranty-info-card {
+ border-color: #444;
+}
+
+:root[data-theme="dark"] .claim-description {
+ background: #2d2d2d;
+}
+
+:root[data-theme="dark"] .claim-resolution {
+ background: rgba(46, 204, 113, 0.15);
+}
diff --git a/frontend/version-checker.js b/frontend/version-checker.js
index 369c624..8e2556c 100644
--- a/frontend/version-checker.js
+++ b/frontend/version-checker.js
@@ -1,6 +1,6 @@
// Version checker for Warracker
document.addEventListener('DOMContentLoaded', () => {
- const currentVersion = '0.10.1.9'; // Current version of the application
+ const currentVersion = '0.10.1.10'; // Current version of the application
const updateStatus = document.getElementById('updateStatus');
const updateLink = document.getElementById('updateLink');
const versionDisplay = document.getElementById('versionDisplay');
diff --git a/locales/en/translation.json b/locales/en/translation.json
index 623f7cb..e05c52f 100644
--- a/locales/en/translation.json
+++ b/locales/en/translation.json
@@ -559,5 +559,36 @@
"license": "License",
"copyright": "Copyright",
"developed_by": "Developed by"
+ },
+ "claims": {
+ "claims": "Claims",
+ "warranty_claims": "Warranty Claims",
+ "add_new_claim": "Add New Claim",
+ "add_claim": "Add Claim",
+ "edit_claim": "Edit Claim",
+ "claim_date": "Claim Date",
+ "status": "Status",
+ "claim_number": "Claim Number",
+ "description": "Description",
+ "resolution": "Resolution",
+ "resolution_date": "Resolution Date",
+ "status_submitted": "Submitted",
+ "status_in_progress": "In Progress",
+ "status_approved": "Approved",
+ "status_denied": "Denied",
+ "status_resolved": "Resolved",
+ "status_cancelled": "Cancelled",
+ "description_placeholder": "Describe the issue and reason for the claim...",
+ "resolution_placeholder": "Resolution details (if any)...",
+ "no_claims_yet": "No Claims Yet",
+ "no_claims_message": "Click \"Add New Claim\" to get started",
+ "claim_deleted_successfully": "Claim deleted successfully",
+ "claim_created_successfully": "Claim created successfully",
+ "claim_updated_successfully": "Claim updated successfully",
+ "confirm_delete_claim": "Are you sure you want to delete this claim?",
+ "failed_to_load_claims": "Failed to load claims",
+ "failed_to_save_claim": "Failed to save claim",
+ "failed_to_delete_claim": "Failed to delete claim",
+ "warranty_not_found": "Warranty not found"
}
}