Skip to content

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

Tags for warranties

sassanix60fa3402c986
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6e1effd..24bed13 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,23 @@
# Changelog
+## [0.9.8.6] - 2025-04-01
+
+### Added
+ - Added tags to warranties, you can create and manage them
+ - Choose different colours to tags
+ - Search by tags
+ - Added tags to the warranty cards
+ - You can also edit current warranties to add tags
+
+### Changed
+ - Removed docker and docker compose from making data/uploads
+
+### Current bugs with this release
+
+ - Status page recently expired or expiring soon section will only work when a warranty is expiring.
+ - Currently tags are for all users, if an admin creates a tag, it will show up for the users as well.
+
+
## [0.9.8.5] - 2025-03-29
### Changed
diff --git a/Dockerfile b/Dockerfile
index a3e103c..19d0729 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,13 +1,19 @@
# Start with Python base image
FROM python:3.9-slim-buster
-# Install nginx and dependencies
-RUN apt-get update && apt-get install -y \
- nginx \
- curl \
+# Install nginx, postgresql-client, supervisor and dependencies
+RUN apt-get update && \
+ apt-get install -y --no-install-recommends \
+ nginx \
+ curl \
+ postgresql-client \
+ supervisor \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
+# Ensure nginx runs in the foreground for Supervisor
+RUN sed -i '1i daemon off;' /etc/nginx/nginx.conf
+
# Set working directory
WORKDIR /app
@@ -23,25 +29,18 @@ COPY backend/fix_permissions.py .
COPY backend/fix_permissions.sql .
COPY backend/migrations/ ./migrations/
-# Create directory for uploads with proper permissions
-RUN mkdir -p /data/uploads && chmod 777 /data/uploads
-
# Copy frontend files
COPY frontend/*.html /var/www/html/
COPY frontend/*.js /var/www/html/
COPY frontend/*.css /var/www/html/
-# Configure nginx
+# Configure nginx site
RUN rm /etc/nginx/sites-enabled/default
COPY nginx.conf /etc/nginx/conf.d/default.conf
-# Create startup script with directory permission check and database initialization
+# Create startup script with database initialization
RUN echo '#!/bin/bash\n\
-echo "Checking /data/uploads directory:"\n\
-ls -la /data/uploads\n\
-echo "Setting permissions:"\n\
-chmod -R 777 /data/uploads\n\
-ls -la /data/uploads\n\
+set -e # Exit immediately if a command exits with a non-zero status.\n\
echo "Running database migrations..."\n\
python /app/run_migrations.py\n\
echo "Ensuring admin role has proper permissions..."\n\
@@ -50,23 +49,35 @@ max_attempts=5\n\
attempt=0\n\
while [ $attempt -lt $max_attempts ]; do\n\
echo "Attempt $((attempt+1)) to grant superuser privileges..."\n\
- if PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -U $DB_USER -d $DB_NAME -c "ALTER ROLE warranty_user WITH SUPERUSER;" 2>/dev/null; then\n\
+ # Ensure DB variables are set (you might pass these at runtime)\n\
+ if [ -z "$DB_PASSWORD" ] || [ -z "$DB_HOST" ] || [ -z "$DB_USER" ] || [ -z "$DB_NAME" ]; then\n\
+ echo "Error: Database connection variables (DB_PASSWORD, DB_HOST, DB_USER, DB_NAME) are not set."\n\
+ exit 1\n\
+ fi\n\
+ # Use timeout to prevent indefinite hanging if DB is not ready\n\
+ if PGPASSWORD=$DB_PASSWORD psql -w -h $DB_HOST -U $DB_USER -d $DB_NAME -c "ALTER ROLE warranty_user WITH SUPERUSER;" 2>/dev/null; then\n\
echo "Successfully granted superuser privileges to warranty_user"\n\
break\n\
else\n\
- echo "Failed to grant privileges, retrying in 5 seconds..."\n\
+ echo "Failed to grant privileges (attempt $((attempt+1))), retrying in 5 seconds..."\n\
sleep 5\n\
attempt=$((attempt+1))\n\
fi\n\
done\n\
+if [ $attempt -eq $max_attempts ]; then\n\
+ echo "Error: Failed to grant superuser privileges after $max_attempts attempts."\n\
+ exit 1 # Exit if granting fails after retries\n\
+fi\n\
echo "Running fix permissions script..."\n\
python /app/fix_permissions.py\n\
-echo "Starting services..."\n\
-# Remove direct nginx call that conflicts with supervisor\n\
-gunicorn --bind 0.0.0.0:5000 --workers 4 --worker-class=sync --env GUNICORN_WORKER_CLASS=sync --env GUNICORN_WORKER_ID=0 app:app\n\
+echo "Setup script finished successfully."\n\
+# The actual services (gunicorn, nginx) will be started by Supervisor below\n\
+exit 0 # Exit successfully, Supervisor takes over\n\
' > /app/start.sh && chmod +x /app/start.sh
-# This is just a fallback, the copied nginx.conf will be used
+# This is just a fallback Nginx config echo, the copied nginx.conf is primary
+# Note: Removed the /uploads/ location block from here.
+# Ensure your actual nginx.conf doesn't reference it if not needed.
RUN echo 'server {\n\
listen 80;\n\
server_name localhost;\n\
@@ -94,74 +105,76 @@ RUN echo 'server {\n\
client_max_body_size 32M;\n\
}\n\
\n\
- # Direct access to uploads directory\n\
- location /uploads/ {\n\
- return 403 "Access forbidden";\n\
- }\n\
}' > /etc/nginx/conf.d/default.conf
# Expose port
EXPOSE 80
# Define health check
-HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
+HEALTHCHECK --interval=30s --timeout=10s --start-period=15s --retries=3 \
CMD curl -f http://localhost/ || exit 1
# Set environment variables
ENV PYTHONUNBUFFERED=1
-# Install supervisor to manage multiple processes
-RUN apt-get update && apt-get install -y supervisor && apt-get clean
+# Create supervisor log directory
RUN mkdir -p /var/log/supervisor
# Create supervisor configuration
+# Using Heredoc for cleaner multiline config
COPY <<EOF /etc/supervisor/conf.d/supervisord.conf
[supervisord]
-nodaemon=true
-user=root
-logfile=/dev/stdout
-logfile_maxbytes=0
+nodaemon=true ; Run Supervisor in the foreground
+user=root ; Run Supervisor as root
+logfile=/dev/stdout ; Log Supervisor messages to stdout
+logfile_maxbytes=0 ; Disable log rotation for stdout
pidfile=/var/run/supervisord.pid
-[program:nginx]
-command=nginx -g "daemon off;"
+; Program for initial setup (migrations, permissions)
+; Runs once at the start
+[program:setup]
+command=/app/start.sh ; Execute the setup script
+directory=/app
autostart=true
-autorestart=true
-startretries=5
-stdout_logfile=/dev/stdout
+autorestart=false ; Do not restart if it finishes
+startsecs=0 ; Start immediately
+startretries=1 ; Only retry once if it fails immediately
+exitcodes=0 ; Expected exit code is 0
+stdout_logfile=/dev/stdout ; Log stdout to container stdout
stdout_logfile_maxbytes=0
-stderr_logfile=/dev/stderr
+stderr_logfile=/dev/stderr ; Log stderr to container stderr
stderr_logfile_maxbytes=0
-priority=10
+priority=5 ; Run before nginx and gunicorn
-[program:gunicorn]
-command=gunicorn --config /app/gunicorn_config.py app:app
-directory=/app
+[program:nginx]
+command=/usr/sbin/nginx ; Run nginx reading default config (with 'daemon off;' added)
autostart=true
-autorestart=true
+autorestart=true ; Restart nginx if it crashes
+startsecs=5 ; Give setup some time before starting nginx
startretries=5
-stdout_logfile=/dev/stdout
+stdout_logfile=/dev/stdout ; Log stdout to container stdout
stdout_logfile_maxbytes=0
-stderr_logfile=/dev/stderr
+stderr_logfile=/dev/stderr ; Log stderr to container stderr
stderr_logfile_maxbytes=0
-priority=20
+priority=10 ; Start after setup
-[program:migrations]
-command=bash -c "cd /app/migrations && python apply_migrations.py"
+[program:gunicorn]
+command=gunicorn --config /app/gunicorn_config.py app:app ; Start Gunicorn
directory=/app
autostart=true
-autorestart=false
-startsecs=0
-startretries=3
-stdout_logfile=/dev/stdout
+autorestart=true ; Restart Gunicorn if it crashes
+startsecs=5 ; Give setup some time before starting gunicorn
+startretries=5
+stdout_logfile=/dev/stdout ; Log stdout to container stdout
stdout_logfile_maxbytes=0
-stderr_logfile=/dev/stderr
+stderr_logfile=/dev/stderr ; Log stderr to container stderr
stderr_logfile_maxbytes=0
-priority=5
+priority=20 ; Start after setup
+stopsignal=QUIT ; Graceful shutdown signal for Gunicorn
+stopwaitsecs=10 ; Wait up to 10 seconds for graceful shutdown
+killasgroup=true ; Ensure all gunicorn processes are killed
+stopasgroup=true ; Ensure all gunicorn processes receive the stop signal
EOF
-# Make sure the uploads directory is writable
-RUN chmod -R 777 /data/uploads
-
-# Start supervisor
+# Start supervisor which will manage the setup, nginx, and gunicorn processes
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
\ No newline at end of file
diff --git a/backend/app.py b/backend/app.py
index 26d4f71..4a17097 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -21,6 +21,7 @@ import atexit
from pytz import timezone as pytz_timezone
import pytz
import threading
+import json
app = Flask(__name__)
CORS(app, supports_credentials=True) # Enable CORS with credentials
@@ -790,6 +791,17 @@ def get_warranties():
serial_numbers = [row[0] for row in cur.fetchall()]
warranty_dict['serial_numbers'] = serial_numbers
+ # Get tags for this warranty
+ cur.execute('''
+ SELECT t.id, t.name, t.color
+ FROM tags t
+ JOIN warranty_tags wt ON t.id = wt.tag_id
+ WHERE wt.warranty_id = %s
+ ORDER BY t.name
+ ''', (warranty_id,))
+ tags = [{'id': t[0], 'name': t[1], 'color': t[2]} for t in cur.fetchall()]
+ warranty_dict['tags'] = tags
+
warranties_list.append(warranty_dict)
return jsonify(warranties_list)
@@ -826,6 +838,16 @@ def add_warranty():
product_url = request.form.get('product_url', '')
user_id = request.user['id']
+ # Get tag IDs if provided
+ tag_ids = []
+ if request.form.get('tag_ids'):
+ try:
+ tag_ids = json.loads(request.form.get('tag_ids'))
+ if not isinstance(tag_ids, list):
+ return jsonify({"error": "tag_ids must be a JSON array"}), 400
+ except json.JSONDecodeError:
+ return jsonify({"error": "tag_ids must be a valid JSON array"}), 400
+
# Handle purchase price (optional)
purchase_price = None
if request.form.get('purchase_price'):
@@ -895,6 +917,19 @@ def add_warranty():
VALUES (%s, %s)
''', (warranty_id, serial_number.strip()))
+ # Insert tags if provided
+ if tag_ids:
+ for tag_id in tag_ids:
+ # Verify tag exists
+ cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
+ if cur.fetchone():
+ cur.execute('''
+ INSERT INTO warranty_tags (warranty_id, tag_id)
+ VALUES (%s, %s)
+ ''', (warranty_id, tag_id))
+ else:
+ logger.warning(f"Skipping non-existent tag ID: {tag_id}")
+
conn.commit()
return jsonify({
@@ -1008,6 +1043,16 @@ def update_warranty(warranty_id):
serial_numbers = request.form.getlist('serial_numbers')
product_url = request.form.get('product_url', '')
+ # Get tag IDs if provided
+ tag_ids = []
+ if request.form.get('tag_ids'):
+ try:
+ tag_ids = json.loads(request.form.get('tag_ids'))
+ if not isinstance(tag_ids, list):
+ return jsonify({"error": "tag_ids must be a JSON array"}), 400
+ except json.JSONDecodeError:
+ return jsonify({"error": "tag_ids must be a valid JSON array"}), 400
+
# Handle purchase price (optional)
purchase_price = None
if request.form.get('purchase_price'):
@@ -1033,6 +1078,20 @@ def update_warranty(warranty_id):
if not allowed_file(invoice.filename):
return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
+ # First check if there's an existing invoice to delete
+ cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_invoice_path = cur.fetchone()[0]
+
+ if old_invoice_path:
+ full_path = os.path.join('/data', old_invoice_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted old invoice: {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting old invoice: {e}")
+
+ # Save new invoice
filename = secure_filename(invoice.filename)
filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
invoice_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
@@ -1040,20 +1099,6 @@ def update_warranty(warranty_id):
invoice.save(invoice_path)
db_invoice_path = os.path.join('uploads', filename)
logger.info(f"New invoice uploaded: {db_invoice_path}")
-
- # Remove old invoice file if exists and different from new one
- cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
- old_invoice_path = cur.fetchone()[0]
- if old_invoice_path and old_invoice_path != db_invoice_path:
- old_full_path = os.path.join('/data', old_invoice_path)
- if os.path.exists(old_full_path):
- os.remove(old_full_path)
- logger.info(f"Removed old invoice: {old_invoice_path}")
- else:
- # If no new invoice file is uploaded, preserve the existing one
- cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
- db_invoice_path = cur.fetchone()[0]
- logger.info(f"Preserving existing invoice: {db_invoice_path}")
# Handle manual file upload if new file is provided
db_manual_path = None
@@ -1063,6 +1108,20 @@ def update_warranty(warranty_id):
if not allowed_file(manual.filename):
return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
+ # First check if there's an existing manual to delete
+ cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_manual_path = cur.fetchone()[0]
+
+ if old_manual_path:
+ full_path = os.path.join('/data', old_manual_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted old manual: {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting old manual: {e}")
+
+ # Save new manual
filename = secure_filename(manual.filename)
filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_manual_{filename}"
manual_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
@@ -1070,20 +1129,6 @@ def update_warranty(warranty_id):
manual.save(manual_path)
db_manual_path = os.path.join('uploads', filename)
logger.info(f"New manual uploaded: {db_manual_path}")
-
- # Remove old manual file if exists and different from new one
- cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))
- old_manual_path = cur.fetchone()[0]
- if old_manual_path and old_manual_path != db_manual_path:
- old_full_path = os.path.join('/data', old_manual_path)
- if os.path.exists(old_full_path):
- os.remove(old_full_path)
- logger.info(f"Removed old manual: {old_manual_path}")
- else:
- # If no new manual file is uploaded, preserve the existing one
- cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))
- db_manual_path = cur.fetchone()[0]
- logger.info(f"Preserving existing manual: {db_manual_path or 'None'}")
# Update the warranty in database - IMPORTANT: The database set operation needs to be updated
# Create a list of parameters for the UPDATE query
@@ -1136,6 +1181,23 @@ def update_warranty(warranty_id):
VALUES (%s, %s)
''', (warranty_id, serial_number.strip()))
+ # Update tags if provided
+ if tag_ids is not None:
+ # Remove existing tags
+ cur.execute('DELETE FROM warranty_tags WHERE warranty_id = %s', (warranty_id,))
+
+ # Add new tags
+ for tag_id in tag_ids:
+ # Verify tag exists
+ cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
+ if cur.fetchone():
+ cur.execute('''
+ INSERT INTO warranty_tags (warranty_id, tag_id)
+ VALUES (%s, %s)
+ ''', (warranty_id, tag_id))
+ else:
+ logger.warning(f"Skipping non-existent tag ID: {tag_id}")
+
conn.commit()
return jsonify({"message": "Warranty updated successfully"}), 200
@@ -2722,4 +2784,254 @@ def debug_file_check():
except Exception as e:
result['error'] = str(e)
- return jsonify(result)
\ No newline at end of file
+ return jsonify(result)
+
[email protected]('/api/tags', methods=['GET'])
+@token_required
+def get_tags():
+ """Get all tags"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ cur.execute('SELECT id, name, color, created_at FROM tags ORDER BY name')
+ tags = cur.fetchall()
+
+ result = []
+ for tag in tags:
+ result.append({
+ 'id': tag[0],
+ 'name': tag[1],
+ 'color': tag[2],
+ 'created_at': tag[3].isoformat() if tag[3] else None
+ })
+
+ return jsonify(result), 200
+ except Exception as e:
+ logger.error(f"Error fetching tags: {e}")
+ return jsonify({"error": "Failed to fetch tags"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/tags', methods=['POST'])
+@token_required
+def create_tag():
+ """Create a new tag"""
+ conn = None
+ try:
+ data = request.json
+
+ if not data or 'name' not in data:
+ return jsonify({"error": "Tag name is required"}), 400
+
+ name = data['name'].strip()
+ color = data.get('color', '#808080')
+
+ if not name:
+ return jsonify({"error": "Tag name cannot be empty"}), 400
+
+ # Validate color format (should be a hex color)
+ if not re.match(r'^#[0-9A-Fa-f]{6}$', color):
+ return jsonify({"error": "Invalid color format. Use hex format (e.g., #FF5733)"}), 400
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if tag with this name already exists
+ cur.execute('SELECT id FROM tags WHERE name = %s', (name,))
+ existing_tag = cur.fetchone()
+
+ if existing_tag:
+ return jsonify({"error": "A tag with this name already exists"}), 409
+
+ # Create new tag
+ cur.execute(
+ 'INSERT INTO tags (name, color) VALUES (%s, %s) RETURNING id',
+ (name, color)
+ )
+ tag_id = cur.fetchone()[0]
+ conn.commit()
+
+ return jsonify({
+ "id": tag_id,
+ "name": name,
+ "color": color,
+ "message": "Tag created successfully"
+ }), 201
+ except Exception as e:
+ logger.error(f"Error creating tag: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to create tag"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/tags/<int:tag_id>', methods=['PUT'])
+@token_required
+def update_tag(tag_id):
+ """Update an existing tag"""
+ conn = None
+ try:
+ data = request.json
+
+ if not data:
+ return jsonify({"error": "No data provided"}), 400
+
+ name = data.get('name')
+ color = data.get('color')
+
+ if not name and not color:
+ return jsonify({"error": "At least one field (name or color) is required"}), 400
+
+ # Validate color format if provided
+ if color and not re.match(r'^#[0-9A-Fa-f]{6}$', color):
+ return jsonify({"error": "Invalid color format. Use hex format (e.g., #FF5733)"}), 400
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if tag exists
+ cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
+ if cur.fetchone() is None:
+ return jsonify({"error": "Tag not found"}), 404
+
+ # Check if new name already exists (if name is being updated)
+ if name:
+ cur.execute('SELECT id FROM tags WHERE name = %s AND id != %s', (name, tag_id))
+ if cur.fetchone():
+ return jsonify({"error": "A tag with this name already exists"}), 409
+
+ # Build update query
+ update_fields = []
+ values = []
+
+ if name:
+ update_fields.append("name = %s")
+ values.append(name)
+
+ if color:
+ update_fields.append("color = %s")
+ values.append(color)
+
+ values.append(tag_id)
+
+ # Update tag
+ query = f"UPDATE tags SET {', '.join(update_fields)} WHERE id = %s"
+ cur.execute(query, values)
+ conn.commit()
+
+ return jsonify({"message": "Tag updated successfully"}), 200
+ except Exception as e:
+ logger.error(f"Error updating tag {tag_id}: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to update tag"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/warranties/<int:warranty_id>/tags', methods=['GET'])
+@token_required
+def get_warranty_tags(warranty_id):
+ """Get all tags for a specific warranty"""
+ conn = None
+ try:
+ user_id = request.user['id']
+ is_admin = request.user['is_admin']
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # First check if the warranty exists and user has access to it
+ if is_admin:
+ cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
+ else:
+ cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s',
+ (warranty_id, user_id))
+
+ if cur.fetchone() is None:
+ return jsonify({"error": "Warranty not found or you don't have permission to access it"}), 404
+
+ # Get tags for this warranty
+ cur.execute('''
+ SELECT t.id, t.name, t.color, t.created_at
+ FROM tags t
+ JOIN warranty_tags wt ON t.id = wt.tag_id
+ WHERE wt.warranty_id = %s
+ ORDER BY t.name
+ ''', (warranty_id,))
+
+ tags = cur.fetchall()
+
+ result = []
+ for tag in tags:
+ result.append({
+ 'id': tag[0],
+ 'name': tag[1],
+ 'color': tag[2],
+ 'created_at': tag[3].isoformat() if tag[3] else None
+ })
+
+ return jsonify(result), 200
+ except Exception as e:
+ logger.error(f"Error fetching tags for warranty {warranty_id}: {e}")
+ return jsonify({"error": "Failed to fetch tags for this warranty"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/warranties/<int:warranty_id>/tags', methods=['POST'])
+@token_required
+def add_tags_to_warranty(warranty_id):
+ """Add tags to a warranty"""
+ conn = None
+ try:
+ user_id = request.user['id']
+ is_admin = request.user['is_admin']
+
+ data = request.json
+ if not data or 'tag_ids' not in data:
+ return jsonify({"error": "tag_ids array is required"}), 400
+
+ tag_ids = data['tag_ids']
+ if not isinstance(tag_ids, list):
+ return jsonify({"error": "tag_ids must be an array of tag IDs"}), 400
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # First check if the warranty exists and user has access to it
+ if is_admin:
+ cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
+ else:
+ cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s',
+ (warranty_id, user_id))
+
+ if cur.fetchone() is None:
+ return jsonify({"error": "Warranty not found or you don't have permission to modify it"}), 404
+
+ # Remove existing tags
+ cur.execute('DELETE FROM warranty_tags WHERE warranty_id = %s', (warranty_id,))
+
+ # Add new tags
+ for tag_id in tag_ids:
+ # Verify tag exists
+ cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
+ if cur.fetchone() is None:
+ conn.rollback()
+ return jsonify({"error": f"Tag with ID {tag_id} not found"}), 404
+
+ # Add tag to warranty
+ cur.execute(
+ 'INSERT INTO warranty_tags (warranty_id, tag_id) VALUES (%s, %s)',
+ (warranty_id, tag_id)
+ )
+
+ conn.commit()
+ return jsonify({"message": "Tags updated successfully"}), 200
+ except Exception as e:
+ logger.error(f"Error updating tags for warranty {warranty_id}: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to update tags"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
\ No newline at end of file
diff --git a/backend/migrations/003_add_tags.sql b/backend/migrations/003_add_tags.sql
new file mode 100644
index 0000000..bad5c02
--- /dev/null
+++ b/backend/migrations/003_add_tags.sql
@@ -0,0 +1,39 @@
+-- Add tags table and warranty_tags junction table
+DO $$
+BEGIN
+ -- Create tags table if it doesn't exist
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_name = 'tags'
+ ) THEN
+ CREATE TABLE tags (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(50) NOT NULL,
+ color VARCHAR(7) NOT NULL DEFAULT '#808080',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(name)
+ );
+
+ -- Create index on tag name
+ CREATE INDEX idx_tag_name ON tags(name);
+ END IF;
+
+ -- Create warranty_tags junction table if it doesn't exist
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_name = 'warranty_tags'
+ ) THEN
+ CREATE TABLE warranty_tags (
+ warranty_id INTEGER NOT NULL,
+ tag_id INTEGER NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (warranty_id, tag_id),
+ FOREIGN KEY (warranty_id) REFERENCES warranties(id) ON DELETE CASCADE,
+ FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
+ );
+
+ -- Create indexes for better query performance
+ CREATE INDEX idx_warranty_tags_warranty_id ON warranty_tags(warranty_id);
+ CREATE INDEX idx_warranty_tags_tag_id ON warranty_tags(tag_id);
+ END IF;
+END $$;
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
index 8ae0f07..939cf2e 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -6,7 +6,6 @@ services:
ports:
- "8005:80"
volumes:
- - ./data:/data
- ./uploads:/data/uploads
- ./migrations:/app/migrations
- ./backend/migrations:/app/backend_migrations
@@ -28,7 +27,6 @@ services:
restart: unless-stopped
command: >
bash -c "
- chmod -R 777 /data/uploads &&
cd /app && ls -la /app/backend_migrations &&
python /app/backend_migrations/apply_migrations.py &&
python /app/fix_permissions.py &&
diff --git a/frontend/index.html b/frontend/index.html
index e3c2bff..6142781 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -283,6 +283,9 @@
<div class="form-tab" data-tab="documents">
<i class="fas fa-file-alt"></i> Documents
</div>
+ <div class="form-tab" data-tab="tags">
+ <i class="fas fa-tags"></i> Tags
+ </div>
<div class="form-tab" data-tab="summary">
<i class="fas fa-check-circle"></i> Summary
</div>
@@ -354,9 +357,35 @@
</div>
</div>
+ <!-- Tags Tab -->
+ <div class="tab-content" id="tags">
+ <div class="form-group">
+ <label>Add Tags</label>
+ <p class="text-muted">Tags help you organize and filter your warranties</p>
+
+ <div class="tags-container">
+ <div class="selected-tags" id="selectedTags">
+ <!-- Selected tags will be displayed here -->
+ </div>
+
+ <div class="tags-dropdown">
+ <input type="text" id="tagSearch" class="form-control" placeholder="Search or add new tag...">
+ <div class="tags-list" id="tagsList">
+ <!-- Tag options will be populated by JavaScript -->
+ </div>
+ </div>
+
+ <div class="mt-10">
+ <button type="button" id="manageTagsBtn" class="btn btn-secondary btn-sm">
+ <i class="fas fa-cog"></i> Manage Tags
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
<!-- Summary Tab -->
<div class="tab-content" id="summary">
- <h3>Review Your Warranty Information</h3>
<div class="summary-container">
<div class="summary-section">
<h4><i class="fas fa-box"></i> Product Information</h4>
@@ -370,7 +399,7 @@
</div>
<div class="summary-item">
<span class="summary-label">Serial Numbers:</span>
- <div id="summary-serial-numbers" class="summary-value">-</div>
+ <span id="summary-serial-numbers" class="summary-value">-</span>
</div>
</div>
@@ -384,10 +413,6 @@
<span class="summary-label">Warranty Period:</span>
<span id="summary-warranty-years" class="summary-value">-</span>
</div>
- <div class="summary-item">
- <span class="summary-label">Expiration Date:</span>
- <span id="summary-expiration-date" class="summary-value">-</span>
- </div>
<div class="summary-item">
<span class="summary-label">Purchase Price:</span>
<span id="summary-purchase-price" class="summary-value">-</span>
@@ -405,6 +430,14 @@
<span id="summary-manual" class="summary-value">-</span>
</div>
</div>
+
+ <div class="summary-section">
+ <h4><i class="fas fa-tags"></i> Tags</h4>
+ <div class="summary-item">
+ <span class="summary-label">Selected Tags:</span>
+ <div id="summary-tags" class="summary-value">-</div>
+ </div>
+ </div>
</div>
<div class="form-group">
@@ -434,9 +467,17 @@
</h2>
<div class="filter-controls">
- <div class="search-box">
- <i class="fas fa-search"></i>
- <input type="text" id="searchWarranties" placeholder="Search warranties...">
+ <div class="search-container">
+ <div class="search-box">
+ <i class="fas fa-search"></i>
+ <input type="text" id="searchWarranties" placeholder="Find products by name or tag...">
+ <button id="clearSearch" class="clear-search-btn" title="Clear search" style="display: none;">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ <button id="exportBtn" class="export-btn" title="Export warranties">
+ <i class="fas fa-file-export"></i> Export
+ </button>
</div>
<div class="filter-options">
@@ -450,6 +491,14 @@
</select>
</div>
+ <div class="filter-group">
+ <label class="filter-label">Tag</label>
+ <select id="tagFilter" class="filter-select">
+ <option value="all">All Tags</option>
+ <!-- Tag options will be populated by JavaScript -->
+ </select>
+ </div>
+
<div class="filter-group">
<label class="filter-label">Sort By</label>
<select id="sortBy" class="filter-select">
@@ -473,10 +522,6 @@
</button>
</div>
</div>
-
- <button id="exportBtn" class="export-btn" title="Export warranties">
- <i class="fas fa-file-export"></i> Export
- </button>
</div>
</div>
@@ -522,6 +567,9 @@
<button type="button" class="edit-tab-btn" data-tab="edit-documents">
<i class="fas fa-file-alt"></i> Documents
</button>
+ <button type="button" class="edit-tab-btn" data-tab="edit-tags">
+ <i class="fas fa-tags"></i> Tags
+ </button>
</div>
<form id="editWarrantyForm">
@@ -594,6 +642,33 @@
<div id="currentManual" class="mt-10"></div>
</div>
</div>
+
+ <!-- Tags Tab -->
+ <div class="edit-tab-content" id="edit-tags">
+ <div class="form-group">
+ <label>Add Tags</label>
+ <p class="text-muted">Tags help you organize and filter your warranties</p>
+
+ <div class="tags-container">
+ <div class="selected-tags" id="editSelectedTags">
+ <!-- Selected tags will be displayed here -->
+ </div>
+
+ <div class="tags-dropdown">
+ <input type="text" id="editTagSearch" class="form-control" placeholder="Search or add new tag...">
+ <div class="tags-list" id="editTagsList">
+ <!-- Tag options will be populated by JavaScript -->
+ </div>
+ </div>
+
+ <div class="mt-10">
+ <button type="button" id="editManageTagsBtn" class="btn btn-secondary btn-sm">
+ <i class="fas fa-cog"></i> Manage Tags
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
</form>
</div>
<div class="modal-footer">
@@ -611,8 +686,8 @@
<button class="close-btn" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body">
- <p>Are you sure you want to delete this warranty?</p>
- <p class="text-danger"><strong>This action cannot be undone.</strong></p>
+ <p>Are you sure you want to delete this warranty? This action cannot be undone.</p>
+ <p><strong>Product:</strong> <span id="deleteProductName"></span></p>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
@@ -621,8 +696,33 @@
</div>
</div>
- <!-- Toast Notifications -->
- <div class="toast-container" id="toastContainer"></div>
+ <!-- Tag Management Modal -->
+ <div id="tagManagementModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3 class="modal-title">Manage Tags</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <form id="newTagForm" class="tag-form">
+ <input type="text" id="newTagName" class="form-control" placeholder="New tag name" required>
+ <input type="color" id="newTagColor" value="#808080">
+ <button type="submit" class="btn btn-primary">Add Tag</button>
+ </form>
+
+ <h4 class="mt-20">Existing Tags</h4>
+ <div id="existingTags" class="existing-tags">
+ <!-- Tags will be populated here by JavaScript -->
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" data-dismiss="modal">Close</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Toast Container -->
+ <div id="toastContainer" class="toast-container"></div>
<!-- Loading Spinner -->
<div class="loading-container" id="loadingContainer">
diff --git a/frontend/script.js b/frontend/script.js
index d3b3fe7..83acb5a 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -1,3 +1,23 @@
+// Global variables
+let warranties = [];
+let currentTabIndex = 0;
+let tabContents;
+let editMode = false;
+let currentWarrantyId = null;
+let currentFilters = {
+ status: 'all',
+ tag: 'all',
+ search: '',
+ sortBy: 'expiration'
+};
+
+// Tag related variables
+let allTags = [];
+let selectedTags = []; // Will hold objects with id, name, color
+
+// Global variable for edit mode tags
+let editSelectedTags = [];
+
// DOM Elements
const warrantyForm = document.getElementById('warrantyForm');
const settingsBtn = document.getElementById('settingsBtn');
@@ -6,6 +26,7 @@ const darkModeToggle = document.getElementById('darkModeToggle');
const warrantiesList = document.getElementById('warrantiesList');
const refreshBtn = document.getElementById('refreshBtn');
const searchInput = document.getElementById('searchWarranties');
+const clearSearchBtn = document.getElementById('clearSearch');
const statusFilter = document.getElementById('statusFilter');
const sortBySelect = document.getElementById('sortBy');
const exportBtn = document.getElementById('exportBtn');
@@ -25,6 +46,15 @@ const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
const loadingContainer = document.getElementById('loadingContainer');
const toastContainer = document.getElementById('toastContainer');
+// Tag DOM Elements
+const selectedTagsContainer = document.getElementById('selectedTags');
+const tagSearch = document.getElementById('tagSearch');
+const tagsList = document.getElementById('tagsList');
+const manageTagsBtn = document.getElementById('manageTagsBtn');
+const tagManagementModal = document.getElementById('tagManagementModal');
+const newTagForm = document.getElementById('newTagForm');
+const existingTagsContainer = document.getElementById('existingTags');
+
/**
* Get current user type (admin or user)
* @returns {string} 'admin' or 'user'
@@ -117,13 +147,6 @@ function initializeTheme() {
initializeTheme();
// Variables
-let warranties = [];
-let currentWarrantyId = null;
-let currentFilters = {
- search: '',
- status: 'all',
- sort: 'expiration'
-};
let currentView = 'grid'; // Default view
let expiringSoonDays = 30; // Default value, will be updated from user preferences
@@ -132,8 +155,10 @@ const API_URL = '/api/warranties';
// Form tab navigation variables
const formTabs = Array.from(document.querySelectorAll('.form-tab'));
-const tabContents = Array.from(document.querySelectorAll('.tab-content'));
-let currentTabIndex = 0;
+const tabContentsArray = document.querySelectorAll('.tab-content');
+tabContents = Array.from(tabContentsArray); // Convert NodeList to Array
+const nextButton = document.querySelector('.next-tab');
+const prevButton = document.querySelector('.prev-tab');
// Initialize form tabs
function initFormTabs() {
@@ -149,16 +174,12 @@ function initFormTabs() {
updateNavigationButtons();
// Remove any existing event listeners before adding new ones
- const nextTabButton = document.querySelector('.next-tab');
- const prevTabButton = document.querySelector('.prev-tab');
-
- // Clone and replace the buttons to remove any existing event listeners
- if (nextTabButton && prevTabButton) {
- const nextTabClone = nextTabButton.cloneNode(true);
- const prevTabClone = prevTabButton.cloneNode(true);
+ if (nextButton && prevButton) {
+ const nextTabClone = nextButton.cloneNode(true);
+ const prevTabClone = prevButton.cloneNode(true);
- nextTabButton.parentNode.replaceChild(nextTabClone, nextTabButton);
- prevTabButton.parentNode.replaceChild(prevTabClone, prevTabButton);
+ nextButton.parentNode.replaceChild(nextTabClone, nextButton);
+ prevButton.parentNode.replaceChild(prevTabClone, prevButton);
// Add event listeners for tab navigation
document.querySelector('.next-tab').addEventListener('click', () => {
@@ -303,61 +324,104 @@ function showValidationErrors(tabIndex) {
// Update summary tab with current form values
function updateSummary() {
// Product information
- document.getElementById('summary-product-name').textContent =
- document.getElementById('productName').value || '-';
+ const summaryProductName = document.getElementById('summary-product-name');
+ if (summaryProductName) {
+ summaryProductName.textContent =
+ document.getElementById('productName')?.value || '-';
+ }
- document.getElementById('summary-product-url').textContent =
- document.getElementById('productUrl').value || '-';
+ const summaryProductUrl = document.getElementById('summary-product-url');
+ if (summaryProductUrl) {
+ summaryProductUrl.textContent =
+ document.getElementById('productUrl')?.value || '-';
+ }
// Serial numbers
const serialNumbers = [];
document.querySelectorAll('input[name="serial_numbers[]"]').forEach(input => {
- if (input.value.trim()) {
+ if (input && input.value && input.value.trim()) {
serialNumbers.push(input.value.trim());
}
});
const serialNumbersContainer = document.getElementById('summary-serial-numbers');
- if (serialNumbers.length > 0) {
- serialNumbersContainer.innerHTML = '<ul>' +
- serialNumbers.map(sn => `<li>${sn}</li>`).join('') +
- '</ul>';
- } else {
- serialNumbersContainer.textContent = 'None';
+ if (serialNumbersContainer) {
+ if (serialNumbers.length > 0) {
+ serialNumbersContainer.innerHTML = '<ul>' +
+ serialNumbers.map(sn => `<li>${sn}</li>`).join('') +
+ '</ul>';
+ } else {
+ serialNumbersContainer.textContent = 'None';
+ }
}
// Warranty details
- const purchaseDate = document.getElementById('purchaseDate').value;
- document.getElementById('summary-purchase-date').textContent = purchaseDate ?
- new Date(purchaseDate).toLocaleDateString() : '-';
+ const purchaseDate = document.getElementById('purchaseDate')?.value;
+ const summaryPurchaseDate = document.getElementById('summary-purchase-date');
+ if (summaryPurchaseDate) {
+ summaryPurchaseDate.textContent = purchaseDate ?
+ new Date(purchaseDate).toLocaleDateString() : '-';
+ }
- const warrantyYears = document.getElementById('warrantyYears').value;
- document.getElementById('summary-warranty-years').textContent = warrantyYears ?
- `${warrantyYears} ${warrantyYears > 1 ? 'years' : 'year'}` : '-';
+ const warrantyYears = document.getElementById('warrantyYears')?.value;
+ const summaryWarrantyYears = document.getElementById('summary-warranty-years');
+ if (summaryWarrantyYears) {
+ summaryWarrantyYears.textContent = warrantyYears ?
+ `${warrantyYears} ${warrantyYears > 1 ? 'years' : 'year'}` : '-';
+ }
// Calculate and display expiration date
- if (purchaseDate && warrantyYears) {
+ const summaryExpirationDate = document.getElementById('summary-expiration-date');
+ if (summaryExpirationDate && purchaseDate && warrantyYears) {
const expirationDate = new Date(purchaseDate);
expirationDate.setFullYear(expirationDate.getFullYear() + parseInt(warrantyYears));
- document.getElementById('summary-expiration-date').textContent =
- expirationDate.toLocaleDateString();
- } else {
- document.getElementById('summary-expiration-date').textContent = '-';
+ summaryExpirationDate.textContent = expirationDate.toLocaleDateString();
+ } else if (summaryExpirationDate) {
+ summaryExpirationDate.textContent = '-';
}
// Purchase price
- const purchasePrice = document.getElementById('purchasePrice').value;
- document.getElementById('summary-purchase-price').textContent = purchasePrice ?
- `$${parseFloat(purchasePrice).toFixed(2)}` : 'Not specified';
+ const purchasePrice = document.getElementById('purchasePrice')?.value;
+ const summaryPurchasePrice = document.getElementById('summary-purchase-price');
+ if (summaryPurchasePrice) {
+ summaryPurchasePrice.textContent = purchasePrice ?
+ `$${parseFloat(purchasePrice).toFixed(2)}` : 'Not specified';
+ }
// Documents
- const invoiceFile = document.getElementById('invoice').files[0];
- document.getElementById('summary-invoice').textContent = invoiceFile ?
- invoiceFile.name : 'No file selected';
+ const invoiceFile = document.getElementById('invoice')?.files[0];
+ const summaryInvoice = document.getElementById('summary-invoice');
+ if (summaryInvoice) {
+ summaryInvoice.textContent = invoiceFile ?
+ invoiceFile.name : 'No file selected';
+ }
+
+ const manualFile = document.getElementById('manual')?.files[0];
+ const summaryManual = document.getElementById('summary-manual');
+ if (summaryManual) {
+ summaryManual.textContent = manualFile ?
+ manualFile.name : 'No file selected';
+ }
- const manualFile = document.getElementById('manual').files[0];
- document.getElementById('summary-manual').textContent = manualFile ?
- manualFile.name : 'No file selected';
+ // Tags
+ const summaryTags = document.getElementById('summary-tags');
+ if (summaryTags) {
+ if (selectedTags && selectedTags.length > 0) {
+ summaryTags.innerHTML = '';
+
+ selectedTags.forEach(tag => {
+ const tagElement = document.createElement('span');
+ tagElement.className = 'tag';
+ tagElement.style.backgroundColor = tag.color;
+ tagElement.style.color = getContrastColor(tag.color);
+ tagElement.textContent = tag.name;
+
+ summaryTags.appendChild(tagElement);
+ });
+ } else {
+ summaryTags.textContent = 'No tags selected';
+ }
+ }
}
// Add input event listeners to remove validation errors when user types
@@ -401,9 +465,18 @@ async function exportWarranties() {
// Apply current filters
if (currentFilters.search) {
- warrantiesToExport = warrantiesToExport.filter(warranty =>
- warranty.product_name.toLowerCase().includes(currentFilters.search)
- );
+ const searchTerm = currentFilters.search.toLowerCase();
+ warrantiesToExport = warrantiesToExport.filter(warranty => {
+ // Check if product name contains search term
+ const productNameMatch = warranty.product_name.toLowerCase().includes(searchTerm);
+
+ // Check if any tag name contains search term
+ const tagMatch = warranty.tags && Array.isArray(warranty.tags) &&
+ warranty.tags.some(tag => tag.name.toLowerCase().includes(searchTerm));
+
+ // Return true if either product name or tag name matches
+ return productNameMatch || tagMatch;
+ });
}
if (currentFilters.status !== 'all') {
@@ -412,48 +485,53 @@ async function exportWarranties() {
);
}
+ // Apply tag filter
+ if (currentFilters.tag !== 'all') {
+ const tagId = parseInt(currentFilters.tag);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ warranty.tags && Array.isArray(warranty.tags) &&
+ warranty.tags.some(tag => tag.id === tagId)
+ );
+ }
+
// Create CSV content
let csvContent = "data:text/csv;charset=utf-8,";
// Add headers
- csvContent += "Product Name,Purchase Date,Warranty Period,Expiration Date,Status,Serial Numbers\n";
+ csvContent += "Product Name,Purchase Date,Warranty Period,Expiration Date,Status,Serial Numbers,Tags\n";
// Add data rows
warrantiesToExport.forEach(warranty => {
- const purchaseDate = new Date(warranty.purchase_date).toLocaleDateString();
- const expirationDate = new Date(warranty.expiration_date).toLocaleDateString();
+ // Format serial numbers as comma-separated string
const serialNumbers = Array.isArray(warranty.serial_numbers)
- ? warranty.serial_numbers.join('; ')
+ ? warranty.serial_numbers.filter(s => s).join(', ')
: '';
- // Calculate status if not already set
- if (!warranty.status) {
- const today = new Date();
- const expDate = new Date(warranty.expiration_date);
- const daysRemaining = Math.floor((expDate - today) / (1000 * 60 * 60 * 24));
-
- if (daysRemaining < 0) {
- warranty.status = 'Expired';
- } else if (daysRemaining < expiringSoonDays) {
- warranty.status = 'Expiring Soon';
- } else {
- warranty.status = 'Active';
- }
- }
+ // Format tags as comma-separated string
+ const tags = Array.isArray(warranty.tags)
+ ? warranty.tags.map(tag => tag.name).join(', ')
+ : '';
- // Format status for CSV
- let statusText = warranty.status.charAt(0).toUpperCase() + warranty.status.slice(1);
- if (statusText === 'Expiring') statusText = 'Expiring Soon';
+ // Format row data
+ const row = [
+ warranty.product_name || '',
+ formatDate(new Date(warranty.purchase_date)),
+ `${warranty.warranty_years || 0} ${warranty.warranty_years === 1 ? 'year' : 'years'}`,
+ formatDate(new Date(warranty.expiration_date)),
+ warranty.status || '',
+ serialNumbers,
+ tags
+ ];
- // Create CSV row
- csvContent += `"${warranty.product_name}",${purchaseDate},${warranty.warranty_years} years,${expirationDate},${statusText},"${serialNumbers}"\n`;
+ // Add row to CSV content
+ csvContent += row.map(field => `"${field.toString().replace(/"/g, '""')}"`).join(',') + '\n';
});
- // Create download link
+ // Create a download link
const encodedUri = encodeURI(csvContent);
- const link = document.createElement("a");
- link.setAttribute("href", encodedUri);
- link.setAttribute("download", "warranties.csv");
+ const link = document.createElement('a');
+ link.setAttribute('href', encodedUri);
+ link.setAttribute('download', `warranties_export_${formatDate(new Date())}.csv`);
document.body.appendChild(link);
// Trigger download
@@ -462,6 +540,7 @@ async function exportWarranties() {
// Clean up
document.body.removeChild(link);
+ // Show success notification
showToast('Warranties exported successfully', 'success');
}
@@ -562,43 +641,63 @@ serialNumbersContainer.addEventListener('click', (e) => {
}
});
+// Add a serial number input field
function addSerialNumberInput(container = serialNumbersContainer) {
- // Check if this is the first input or an additional one
+ if (!container) return;
+
+ // Create a new input group
+ const inputGroup = document.createElement('div');
+ inputGroup.className = 'serial-number-input';
+
+ // Create an input element
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'form-control';
+ input.name = 'serial_numbers[]';
+ input.placeholder = 'Enter serial number';
+
+ // Check if this is the first serial number input
const isFirstInput = container.querySelectorAll('.serial-number-input').length === 0;
- const newInput = document.createElement('div');
- newInput.className = 'serial-number-input';
+ // Append input to the input group
+ inputGroup.appendChild(input);
- if (isFirstInput) {
- // First input should have both Add and Remove buttons
- newInput.innerHTML = `
- <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number">
- <button type="button" class="btn btn-sm btn-primary add-serial-number">
- <i class="fas fa-plus"></i> Add Another
- </button>
- `;
+ // Only add remove button if this is not the first input
+ if (!isFirstInput) {
+ // Create a remove button
+ const removeButton = document.createElement('button');
+ removeButton.type = 'button';
+ removeButton.className = 'btn btn-sm btn-danger remove-serial';
+ removeButton.innerHTML = '<i class="fas fa-times"></i>';
- // Add event listener for the Add button
- newInput.querySelector('.add-serial-number').addEventListener('click', function(e) {
- e.stopPropagation(); // Stop event from bubbling up to the container
- addSerialNumberInput(container);
+ // Add event listener to remove button
+ removeButton.addEventListener('click', function() {
+ container.removeChild(inputGroup);
});
+
+ // Append remove button to the input group
+ inputGroup.appendChild(removeButton);
+ }
+
+ // Insert the new input group before the add button
+ const addButton = container.querySelector('.add-serial');
+ if (addButton) {
+ container.insertBefore(inputGroup, addButton);
} else {
- // Additional inputs should have only Remove button
- newInput.innerHTML = `
- <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number">
- <button type="button" class="btn btn-sm btn-danger remove-serial-number">
- <i class="fas fa-minus"></i> Remove
- </button>
- `;
+ container.appendChild(inputGroup);
- // Add remove button functionality
- newInput.querySelector('.remove-serial-number').addEventListener('click', function() {
- this.parentElement.remove();
+ // Create and append an add button if it doesn't exist
+ const addButton = document.createElement('button');
+ addButton.type = 'button';
+ addButton.className = 'btn btn-sm btn-secondary add-serial';
+ addButton.innerHTML = '<i class="fas fa-plus"></i> Add Serial Number';
+
+ addButton.addEventListener('click', function() {
+ addSerialNumberInput(container);
});
+
+ container.appendChild(addButton);
}
-
- container.appendChild(newInput);
}
// Functions
@@ -633,11 +732,14 @@ function showToast(message, type = 'info') {
}, 3000);
}
+// Update file name display when a file is selected
function updateFileName(event, inputId = 'invoice', outputId = 'fileName') {
- const input = document.getElementById(inputId);
+ const input = event ? event.target : document.getElementById(inputId);
const output = document.getElementById(outputId);
- if (input.files.length > 0) {
+ if (!input || !output) return;
+
+ if (input.files && input.files[0]) {
output.textContent = input.files[0].name;
} else {
output.textContent = '';
@@ -807,6 +909,10 @@ async function loadWarranties() {
renderEmptyState('No warranties found. Add your first warranty using the form.');
} else {
console.log('Applying filters to display warranties');
+
+ // Populate tag filter dropdown with tags from warranties
+ populateTagFilter();
+
applyFilters();
}
} catch (error) {
@@ -858,7 +964,7 @@ async function renderWarranties(warrantiesToRender) {
// Apply sorting based on current sort selection
const sortedWarranties = [...warrantiesToRender].sort((a, b) => {
- switch (currentFilters.sort) {
+ switch (currentFilters.sortBy) {
case 'name':
return a.product_name.localeCompare(b.product_name);
case 'purchase':
@@ -915,10 +1021,20 @@ async function renderWarranties(warrantiesToRender) {
? warranty.serial_numbers.filter(sn => sn && typeof sn === 'string' && sn.trim() !== '')
: [];
+ // Prepare tags HTML
+ const tagsHtml = warranty.tags && warranty.tags.length > 0
+ ? `<div class="tags-row">
+ ${warranty.tags.map(tag =>
+ `<span class="tag" style="background-color: ${tag.color}; color: ${getContrastColor(tag.color)}">
+ ${tag.name}
+ </span>`
+ ).join('')}
+ </div>`
+ : '';
+
const cardElement = document.createElement('div');
cardElement.className = `warranty-card ${statusClass === 'expired' ? 'expired' : statusClass === 'expiring' ? 'expiring-soon' : 'active'}`;
- // Create different HTML structure based on the current view
if (currentView === 'grid') {
// Grid view HTML structure
cardElement.innerHTML = `
@@ -967,6 +1083,7 @@ async function renderWarranties(warrantiesToRender) {
<i class="fas fa-book"></i> Manual
</a>` : ''}
</div>
+ ${tagsHtml}
`;
} else if (currentView === 'list') {
// List view HTML structure
@@ -1016,6 +1133,7 @@ async function renderWarranties(warrantiesToRender) {
<i class="fas fa-book"></i> Manual
</a>` : ''}
</div>
+ ${tagsHtml}
`;
} else if (currentView === 'table') {
// Table view HTML structure
@@ -1055,6 +1173,7 @@ async function renderWarranties(warrantiesToRender) {
<i class="fas fa-book"></i>
</a>` : ''}
</div>
+ ${tagsHtml}
`;
}
@@ -1068,7 +1187,7 @@ async function renderWarranties(warrantiesToRender) {
// Delete button event listener
cardElement.querySelector('.delete-btn').addEventListener('click', () => {
- openDeleteModal(warranty.id);
+ openDeleteModal(warranty.id, warranty.product_name);
});
});
}
@@ -1076,16 +1195,34 @@ async function renderWarranties(warrantiesToRender) {
function filterWarranties() {
const searchTerm = searchInput.value.toLowerCase();
+ // Show or hide the clear search button
+ clearSearchBtn.style.display = searchTerm ? 'flex' : 'none';
+
if (!searchTerm) {
renderWarranties();
return;
}
- const filtered = warranties.filter(warranty =>
- warranty.product_name.toLowerCase().includes(searchTerm)
- );
+ const filtered = warranties.filter(warranty => {
+ // Check product name
+ if (warranty.product_name.toLowerCase().includes(searchTerm)) {
+ return true;
+ }
+
+ // Check tags
+ if (warranty.tags && Array.isArray(warranty.tags)) {
+ return warranty.tags.some(tag => tag.name.toLowerCase().includes(searchTerm));
+ }
+
+ return false;
+ });
- renderWarranties(filtered);
+ // Add visual feedback if no results found
+ if (filtered.length === 0) {
+ renderEmptyState(`No matches found for "${searchTerm}". Try a different search term.`);
+ } else {
+ renderWarranties(filtered);
+ }
}
function applyFilters() {
@@ -1098,9 +1235,31 @@ function applyFilters() {
return false;
}
+ // Tag filter
+ if (currentFilters.tag !== 'all') {
+ const tagId = parseInt(currentFilters.tag);
+ const hasTag = warranty.tags && Array.isArray(warranty.tags) &&
+ warranty.tags.some(tag => tag.id === tagId);
+ if (!hasTag) {
+ return false;
+ }
+ }
+
// Search filter
- if (currentFilters.search && !warranty.product_name.toLowerCase().includes(currentFilters.search.toLowerCase())) {
- return false;
+ if (currentFilters.search) {
+ const searchTerm = currentFilters.search.toLowerCase();
+
+ // Check if product name contains search term
+ const productNameMatch = warranty.product_name.toLowerCase().includes(searchTerm);
+
+ // Check if any tag name contains search term
+ const tagMatch = warranty.tags && Array.isArray(warranty.tags) &&
+ warranty.tags.some(tag => tag.name.toLowerCase().includes(searchTerm));
+
+ // Return true if either product name or tag name matches
+ if (!productNameMatch && !tagMatch) {
+ return false;
+ }
}
return true;
@@ -1141,7 +1300,7 @@ function openEditModal(warranty) {
// Add a single empty input if there are no serial numbers
addSerialNumberInput(editSerialNumbersContainer);
} else {
- // Add the first serial number with an "Add Another" button
+ // Add the first serial number with an "Add Another" button only (no remove button)
const firstInput = document.createElement('div');
firstInput.className = 'serial-number-input';
firstInput.innerHTML = `
@@ -1217,9 +1376,26 @@ function openEditModal(warranty) {
document.getElementById('editFileName').textContent = '';
document.getElementById('editManualFileName').textContent = '';
+ // Initialize file input event listeners
+ const editInvoiceInput = document.getElementById('editInvoice');
+ if (editInvoiceInput) {
+ editInvoiceInput.addEventListener('change', function(event) {
+ updateFileName(event, 'editInvoice', 'editFileName');
+ });
+ }
+
+ const editManualInput = document.getElementById('editManual');
+ if (editManualInput) {
+ editManualInput.addEventListener('change', function(event) {
+ updateFileName(event, 'editManual', 'editManualFileName');
+ });
+ }
+
// Show edit modal
- const modal = document.getElementById('editModal');
- modal.classList.add('active'); // Add active class instead of setting display style
+ const modalBackdrop = document.getElementById('editModal');
+ if (modalBackdrop) {
+ modalBackdrop.classList.add('active'); // Add active class to display as flex
+ }
// Reset tabs to first tab
const editTabBtns = document.querySelectorAll('.edit-tab-btn');
@@ -1230,10 +1406,58 @@ function openEditModal(warranty) {
document.querySelectorAll('.edit-tab-content').forEach(content => content.classList.remove('active'));
document.getElementById('edit-product-info').classList.add('active');
+ // Initialize edit mode tags
+ editSelectedTags = [];
+
+ // If warranty has tags, populate editSelectedTags
+ if (warranty.tags && Array.isArray(warranty.tags)) {
+ editSelectedTags = warranty.tags.map(tag => ({
+ id: tag.id,
+ name: tag.name,
+ color: tag.color
+ }));
+ }
+
+ // Render selected tags using the helper function
+ renderEditSelectedTags();
+
+ // Set up tag search in edit mode
+ const editTagSearch = document.getElementById('editTagSearch');
+ const editTagsList = document.getElementById('editTagsList');
+
+ if (editTagSearch && editTagsList) {
+ // Add event listeners for tag search
+ editTagSearch.addEventListener('focus', () => {
+ renderEditTagsList();
+ editTagsList.classList.add('show');
+ });
+
+ editTagSearch.addEventListener('input', () => {
+ renderEditTagsList(editTagSearch.value);
+ });
+
+ // Add event listener to close dropdown when clicking outside
+ document.addEventListener('click', (e) => {
+ if (!editTagSearch.contains(e.target) && !editTagsList.contains(e.target)) {
+ editTagsList.classList.remove('show');
+ }
+ });
+ }
+
+ // Set up manage tags button in edit mode
+ const editManageTagsBtn = document.getElementById('editManageTagsBtn');
+ if (editManageTagsBtn) {
+ editManageTagsBtn.addEventListener('click', (e) => {
+ e.preventDefault();
+ openTagManagementModal();
+ });
+ }
+
// Validate all tabs to update completion indicators
validateEditTab('edit-product-info');
validateEditTab('edit-warranty-details');
validateEditTab('edit-documents');
+ validateEditTab('edit-tags');
// Add input event listeners to update validation status
document.querySelectorAll('#editWarrantyForm input').forEach(input => {
@@ -1247,15 +1471,25 @@ function openEditModal(warranty) {
});
}
-function openDeleteModal(warrantyId) {
+function openDeleteModal(warrantyId, productName) {
currentWarrantyId = warrantyId;
- deleteModal.classList.add('active');
+
+ const deleteProductNameElement = document.getElementById('deleteProductName');
+ if (deleteProductNameElement) {
+ deleteProductNameElement.textContent = productName || '';
+ }
+
+ const deleteModal = document.getElementById('deleteModal');
+ if (deleteModal) {
+ deleteModal.classList.add('active');
+ }
}
+// Function to close all modals
function closeModals() {
- editModal.classList.remove('active');
- deleteModal.classList.remove('active');
- currentWarrantyId = null;
+ document.querySelectorAll('.modal-backdrop').forEach(modal => {
+ modal.classList.remove('active');
+ });
}
// Validate file size before upload
@@ -1288,280 +1522,712 @@ function validateFileSize(formData, maxSizeMB = 32) {
};
}
-// Modify the beginning of the addWarranty function to check file sizes before uploading
-async function addWarranty(event) {
+// Submit form function - event handler for form submit
+function submitForm(event) {
event.preventDefault();
- // Check authentication first
- if (!window.auth || !window.auth.isAuthenticated()) {
- showToast('Please log in to add warranties', 'error');
- return;
+ // Validate all tabs
+ for (let i = 0; i < tabContents.length; i++) {
+ if (!validateTab(i)) {
+ // Switch to the first invalid tab
+ switchToTab(i);
+ return;
+ }
}
- // Validate the current tab
- if (!validateTab(currentTabIndex)) {
- return;
- }
+ // Create form data object
+ const formData = new FormData(warrantyForm);
- try {
- showLoading();
-
- // Create FormData object
- const formData = new FormData(warrantyForm);
-
- // Validate file sizes before trying to upload
- const fileSizeValidation = validateFileSize(formData);
- if (!fileSizeValidation.valid) {
- showToast(fileSizeValidation.message, 'error');
- hideLoading();
- return;
+ // Add serial numbers to form data
+ const serialInputs = document.querySelectorAll('#serialNumbersContainer input');
+ serialInputs.forEach(input => {
+ if (input.value.trim()) {
+ formData.append('serial_numbers', input.value.trim());
}
-
- // Get all serial numbers
- const serialNumbers = [];
- document.querySelectorAll('input[name="serial_numbers[]"]').forEach(input => {
- if (input.value.trim()) {
- serialNumbers.push(input.value.trim());
- }
- });
-
- // Remove default serial numbers entry and add the collected ones
- formData.delete('serial_numbers[]');
- serialNumbers.forEach(sn => {
- formData.append('serial_numbers', sn);
- });
-
- // Get the auth token
- const token = window.auth.getToken();
- if (!token) {
- showToast('Authentication error. Please log in again.', 'error');
- hideLoading();
- closeModals();
- return;
+ });
+
+ // Add tag IDs to form data as JSON string
+ if (selectedTags && selectedTags.length > 0) {
+ const tagIds = selectedTags.map(tag => tag.id);
+ formData.append('tag_ids', JSON.stringify(tagIds));
+ }
+
+ // Show loading spinner
+ showLoadingSpinner();
+
+ // Send the form data to the server
+ fetch('/api/warranties', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token')
+ },
+ body: formData
+ })
+ .then(response => {
+ if (!response.ok) {
+ return response.json().then(data => {
+ throw new Error(data.error || 'Failed to add warranty');
+ });
}
+ return response.json();
+ })
+ .then(data => {
+ hideLoadingSpinner();
+ showToast('Warranty added successfully', 'success');
- // Create request with auth header
- const options = {
- method: 'POST',
- body: formData,
- headers: {
- 'Authorization': `Bearer ${token}`
- }
- };
-
- // Use the full URL to avoid path issues
- const apiUrl = window.location.origin + '/api/warranties';
-
- console.log('Sending warranty data to server...');
- const response = await fetch(apiUrl, options);
+ // Reset form and reload warranties
+ resetForm();
- if (!response.ok) {
- // Specifically handle 413 Request Entity Too Large error
- if (response.status === 413) {
- throw new Error('File size too large. Please reduce the file size of your uploads (maximum 32MB total) or split into multiple warranties.');
- }
-
- const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));
- throw new Error(errorData.message || `Error adding warranty: ${response.status}`);
+ // Reset selected tags
+ selectedTags = [];
+ if (selectedTagsContainer) {
+ selectedTagsContainer.innerHTML = '';
}
- const result = await response.json();
- console.log('Received add warranty result:', result);
-
- // The server only returns the ID, so we need to fetch the complete warranty data
- if (result.id) {
- console.log('Fetching complete warranty data for ID:', result.id);
+ loadWarranties();
+ })
+ .catch(error => {
+ hideLoadingSpinner();
+ console.error('Error adding warranty:', error);
+ showToast(error.message || 'Failed to add warranty', 'error');
+ });
+}
+
+// Initialize page
+document.addEventListener('DOMContentLoaded', function() {
+ // Initialize the warranty form
+ initWarrantyForm();
+
+ // Load warranties
+ loadWarranties();
+
+ // Initialize theme
+ initializeTheme();
+
+ // Set up event listeners for other UI controls
+ setupUIEventListeners();
+});
+
+// Add this function to handle edit tab functionality
+function initEditTabs() {
+ const editTabBtns = document.querySelectorAll('.edit-tab-btn');
+
+ editTabBtns.forEach(btn => {
+ btn.addEventListener('click', () => {
+ // Remove active class from all tabs
+ editTabBtns.forEach(b => b.classList.remove('active'));
- // Reload all warranties to get the complete data
- await loadWarranties();
+ // Add active class to clicked tab
+ btn.classList.add('active');
- // Reset the form and initialize serial number inputs
- resetForm();
+ // Hide all tab content
+ document.querySelectorAll('.edit-tab-content').forEach(content => {
+ content.classList.remove('active');
+ });
- // Show success message
- showToast('Warranty added successfully!', 'success');
+ // Show the selected tab content
+ const tabId = btn.getAttribute('data-tab');
+ document.getElementById(tabId).classList.add('active');
+ });
+ });
+}
+
+// Update validateEditTabs function
+function validateEditTab(tabId) {
+ const tab = document.getElementById(tabId);
+ let isValid = true;
+
+ // Get all required inputs in this tab
+ const requiredInputs = tab.querySelectorAll('input[required]');
+
+ // Check if all required fields are filled
+ requiredInputs.forEach(input => {
+ if (!input.value) {
+ isValid = false;
+ input.classList.add('invalid');
} else {
- throw new Error('Failed to get warranty ID from server response');
+ input.classList.remove('invalid');
}
- } catch (error) {
- console.error('Error adding warranty:', error);
- showToast(error.message || 'Error adding warranty. Please try again.', 'error');
- } finally {
- hideLoading();
+ });
+
+ // Update the tab button to show completion status
+ const tabBtn = document.querySelector(`.edit-tab-btn[data-tab="${tabId}"]`);
+ if (isValid) {
+ tabBtn.classList.add('completed');
+ } else {
+ tabBtn.classList.remove('completed');
}
+
+ return isValid;
}
-// Modify the beginning of the updateWarranty function to check file sizes before uploading
-async function updateWarranty() {
- // Check if user is authenticated
- if (window.auth && !window.auth.isAuthenticated()) {
- showToast('Please login to update warranties', 'warning');
- closeModals();
- setTimeout(() => {
- window.location.href = 'login.html';
- }, 1500);
- return;
+// Add this function for secure file access
+function openSecureFile(filePath) {
+ if (!filePath || filePath === 'null') {
+ console.error('Invalid file path:', filePath);
+ showToast('Invalid file path', 'error');
+ return false;
}
- if (!currentWarrantyId) {
- showToast('No warranty selected for update', 'error');
- return;
- }
+ console.log('Opening secure file:', filePath);
- // Create FormData object
- const formData = new FormData(editWarrantyForm);
+ // Get the file name from the path
+ const fileName = filePath.split('/').pop();
- // Validate file sizes before trying to upload
- const fileSizeValidation = validateFileSize(formData);
- if (!fileSizeValidation.valid) {
- showToast(fileSizeValidation.message, 'error');
+ // Get auth token
+ const token = window.auth.getToken();
+ if (!token) {
+ showToast('Authentication error. Please log in again.', 'error');
+ return false;
+ }
+
+ // Use fetch with proper authorization header
+ fetch(`/api/secure-file/${fileName}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error(`Error: ${response.status} ${response.statusText}`);
+ }
+ return response.blob();
+ })
+ .then(blob => {
+ // Create a URL for the blob
+ const blobUrl = window.URL.createObjectURL(blob);
+
+ // Open in new tab
+ window.open(blobUrl, '_blank');
+ })
+ .catch(error => {
+ console.error('Error fetching file:', error);
+ showToast('Error opening file: ' + error.message, 'error');
+ });
+
+ return false;
+}
+
+// Initialize the warranty form and all its components
+function initWarrantyForm() {
+ // Initialize form tabs
+ if (formTabs && tabContents) {
+ initFormTabs();
+ }
+
+ // Initialize serial number inputs
+ addSerialNumberInput();
+
+ // Initialize file input display
+ if (document.getElementById('invoice')) {
+ document.getElementById('invoice').addEventListener('change', function(event) {
+ updateFileName(event, 'invoice', 'fileName');
+ });
+ }
+
+ if (document.getElementById('manual')) {
+ document.getElementById('manual').addEventListener('change', function(event) {
+ updateFileName(event, 'manual', 'manualFileName');
+ });
+ }
+
+ // Initialize tag functionality
+ initTagFunctionality();
+
+ // Form submission
+ if (warrantyForm) {
+ warrantyForm.addEventListener('submit', submitForm);
+ }
+}
+
+// Initialize tag functionality
+function initTagFunctionality() {
+ // Skip if tag elements don't exist
+ if (!tagSearch || !tagsList || !manageTagsBtn || !selectedTagsContainer) {
+ console.log('Tag elements not found, skipping tag initialization');
return;
}
+
+ // Load tags from API if not already loaded
+ if (allTags.length === 0) {
+ loadTags();
+ }
- // Get all serial numbers
- const serialNumbers = [];
- document.querySelectorAll('#editSerialNumbersContainer input[name="serial_numbers[]"]').forEach(input => {
- if (input.value.trim()) {
- serialNumbers.push(input.value.trim());
+ // Tag search input
+ tagSearch.addEventListener('focus', () => {
+ renderTagsList();
+ tagsList.classList.add('show');
+ });
+
+ tagSearch.addEventListener('input', () => {
+ renderTagsList(tagSearch.value);
+ });
+
+ document.addEventListener('click', (e) => {
+ if (!tagSearch.contains(e.target) && !tagsList.contains(e.target)) {
+ tagsList.classList.remove('show');
}
});
- // Remove default serial numbers entry and add the collected ones
- formData.delete('serial_numbers[]');
- serialNumbers.forEach(sn => {
- formData.append('serial_numbers', sn);
+ // Manage tags button
+ manageTagsBtn.addEventListener('click', (e) => {
+ e.preventDefault();
+ openTagManagementModal();
});
+ // Tag management form
+ if (newTagForm) {
+ newTagForm.addEventListener('submit', (e) => {
+ e.preventDefault();
+ createNewTag();
+ });
+ }
+
+ // Close modal buttons
+ if (tagManagementModal) {
+ const closeButtons = tagManagementModal.querySelectorAll('[data-dismiss="modal"]');
+ closeButtons.forEach(button => {
+ button.addEventListener('click', () => {
+ tagManagementModal.style.display = 'none';
+ });
+ });
+ }
+}
+
+// Function to load all tags
+async function loadTags() {
try {
- showLoading();
-
- // Get the auth token
- const token = window.auth.getToken();
+ const token = localStorage.getItem('auth_token');
if (!token) {
- showToast('Authentication error. Please log in again.', 'error');
- hideLoading();
- closeModals();
+ console.error('No auth token found');
return;
}
- // Create request with auth header
- const options = {
- method: 'PUT',
- body: formData,
+ showLoadingSpinner();
+
+ const response = await fetch('/api/tags', {
headers: {
'Authorization': `Bearer ${token}`
}
- };
-
- // Use the full URL to avoid path issues
- const apiUrl = `${window.location.origin}/api/warranties/${currentWarrantyId}`;
-
- console.log('Updating warranty with ID:', currentWarrantyId);
- const response = await fetch(apiUrl, options);
+ });
if (!response.ok) {
- // Specifically handle 413 Request Entity Too Large error
- if (response.status === 413) {
- throw new Error('File size too large. Please reduce the file size of your uploads (maximum 32MB total) or split into multiple warranties.');
- }
-
- const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));
- throw new Error(errorData.message || `Error updating warranty: ${response.status}`);
+ throw new Error(`Failed to load tags: ${response.status}`);
}
- const result = await response.json();
- console.log('Received update warranty result:', result);
+ const data = await response.json();
+ console.log('Loaded tags:', data);
- // Reload all warranties to get the complete data
- await loadWarranties();
+ // Store tags globally
+ allTags = data;
- // Close modal
- closeModals();
+ // Populate the tag filter
+ populateTagFilter();
- // Show success message
- showToast('Warranty updated successfully!', 'success');
+ // Render selected tags if any
+ if (selectedTagsContainer) {
+ renderSelectedTags();
+ }
+
+ hideLoadingSpinner();
+
+ return data;
} catch (error) {
- console.error('Error updating warranty:', error);
- showToast(error.message || 'Error updating warranty. Please try again.', 'error');
- } finally {
- hideLoading();
+ console.error('Error loading tags:', error);
+ hideLoadingSpinner();
+ return [];
}
}
-async function deleteWarranty() {
- // Check if user is authenticated
- if (window.auth && !window.auth.isAuthenticated()) {
- showToast('Please login to delete warranties', 'warning');
- closeModals();
- setTimeout(() => {
- window.location.href = 'login.html';
- }, 1500);
- return;
+// Render the tags dropdown list
+function renderTagsList(searchTerm = '') {
+ if (!tagsList) return;
+
+ tagsList.innerHTML = '';
+
+ // Filter tags based on search term
+ const filteredTags = allTags.filter(tag =>
+ !searchTerm || tag.name.toLowerCase().includes(searchTerm.toLowerCase())
+ );
+
+ // Add option to create new tag if search term is provided and not in list
+ if (searchTerm && !filteredTags.some(tag => tag.name.toLowerCase() === searchTerm.toLowerCase())) {
+ const createOption = document.createElement('div');
+ createOption.className = 'tag-option create-tag';
+ createOption.innerHTML = `<i class="fas fa-plus"></i> Create "${searchTerm}"`;
+ createOption.addEventListener('click', () => {
+ createTag(searchTerm);
+ tagsList.classList.remove('show');
+ });
+ tagsList.appendChild(createOption);
}
- if (!currentWarrantyId) {
- showToast('No warranty selected for deletion', 'error');
+ // Add existing tags to dropdown
+ filteredTags.forEach(tag => {
+ const option = document.createElement('div');
+ option.className = 'tag-option';
+
+ // Check if tag is already selected
+ const isSelected = selectedTags.some(selected => selected.id === tag.id);
+
+ option.innerHTML = `
+ <span class="tag-color" style="background-color: ${tag.color}"></span>
+ ${tag.name}
+ <span class="tag-status">${isSelected ? '<i class="fas fa-check"></i>' : ''}</span>
+ `;
+
+ option.addEventListener('click', () => {
+ if (isSelected) {
+ // Remove tag if already selected
+ selectedTags = selectedTags.filter(selected => selected.id !== tag.id);
+ } else {
+ // Add tag if not selected
+ selectedTags.push({
+ id: tag.id,
+ name: tag.name,
+ color: tag.color
+ });
+ }
+
+ renderSelectedTags();
+ renderTagsList(searchTerm);
+ });
+
+ tagsList.appendChild(option);
+ });
+
+ // Show the dropdown
+ tagsList.classList.add('show');
+}
+
+// Render the selected tags
+function renderSelectedTags() {
+ if (!selectedTagsContainer) return;
+
+ selectedTagsContainer.innerHTML = '';
+
+ if (selectedTags.length === 0) {
+ const placeholder = document.createElement('span');
+ placeholder.className = 'no-tags-selected';
+ placeholder.textContent = 'No tags selected';
+ selectedTagsContainer.appendChild(placeholder);
return;
}
- try {
- showLoading();
+ selectedTags.forEach(tag => {
+ const tagElement = document.createElement('span');
+ tagElement.className = 'tag';
+ tagElement.style.backgroundColor = tag.color;
+ tagElement.style.color = getContrastColor(tag.color);
- // Get the auth token
- const token = window.auth.getToken();
- if (!token) {
- showToast('Authentication error. Please log in again.', 'error');
- hideLoading();
- closeModals();
- return;
+ tagElement.innerHTML = `
+ ${tag.name}
+ <span class="remove-tag" data-id="${tag.id}">&times;</span>
+ `;
+
+ // Add event listener for removing tag
+ tagElement.querySelector('.remove-tag').addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedTags = selectedTags.filter(t => t.id !== tag.id);
+ renderSelectedTags();
+
+ // Update summary if needed
+ if (document.getElementById('summary-tags')) {
+ updateSummary();
+ }
+ });
+
+ selectedTagsContainer.appendChild(tagElement);
+ });
+}
+
+// Create a new tag
+function createTag(name) {
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('No authentication token found');
+ return;
+ }
+
+ // Generate a random color for the tag
+ const color = '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');
+
+ fetch('/api/tags', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': 'Bearer ' + token
+ },
+ body: JSON.stringify({
+ name: name,
+ color: color
+ })
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error('Failed to create tag');
}
+ return response.json();
+ })
+ .then(data => {
+ // Add new tag to allTags array
+ allTags.push({
+ id: data.id,
+ name: data.name,
+ color: data.color
+ });
- // Create request with auth header
- const options = {
- method: 'DELETE',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
+ // Select the new tag
+ selectedTags.push({
+ id: data.id,
+ name: data.name,
+ color: data.color
+ });
+
+ // Clear search and rerender
+ if (tagSearch) tagSearch.value = '';
+ renderSelectedTags();
+
+ showToast('Tag created successfully', 'success');
+ })
+ .catch(error => {
+ console.error('Error creating tag:', error);
+ showToast(error.message || 'Failed to create tag', 'error');
+ });
+}
+
+// Helper function to determine text color based on background color
+function getContrastColor(hexColor) {
+ // Convert hex to RGB
+ const r = parseInt(hexColor.substr(1, 2), 16);
+ const g = parseInt(hexColor.substr(3, 2), 16);
+ const b = parseInt(hexColor.substr(5, 2), 16);
+
+ // Calculate luminance
+ const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
+
+ // Return black or white depending on luminance
+ return (yiq >= 128) ? '#000000' : '#ffffff';
+}
+
+// Open tag management modal
+function openTagManagementModal() {
+ if (!tagManagementModal) return;
+
+ // Populate existing tags
+ renderExistingTags();
+
+ // Show modal
+ tagManagementModal.style.display = 'block';
+}
+
+// Render existing tags in the management modal
+function renderExistingTags() {
+ if (!existingTagsContainer) return;
+
+ existingTagsContainer.innerHTML = '';
+
+ if (allTags.length === 0) {
+ existingTagsContainer.innerHTML = '<div class="no-tags">No tags created yet</div>';
+ return;
+ }
+
+ allTags.forEach(tag => {
+ const tagElement = document.createElement('div');
+ tagElement.className = 'existing-tag';
+
+ tagElement.innerHTML = `
+ <div class="existing-tag-info">
+ <div class="existing-tag-color" style="background-color: ${tag.color}"></div>
+ <div class="existing-tag-name">${tag.name}</div>
+ </div>
+ <div class="existing-tag-actions">
+ <button class="btn btn-sm btn-secondary edit-tag" data-id="${tag.id}">
+ <i class="fas fa-edit"></i>
+ </button>
+ <button class="btn btn-sm btn-danger delete-tag" data-id="${tag.id}">
+ <i class="fas fa-trash"></i>
+ </button>
+ </div>
+ `;
+
+ // Add event listeners for edit and delete
+ tagElement.querySelector('.edit-tag').addEventListener('click', () => {
+ editTag(tag);
+ });
+
+ tagElement.querySelector('.delete-tag').addEventListener('click', () => {
+ deleteTag(tag.id);
+ });
+
+ existingTagsContainer.appendChild(tagElement);
+ });
+}
+
+// Edit a tag
+function editTag(tag) {
+ const tagInfoElement = document.querySelector(`.existing-tag .existing-tag-info:has(+ .existing-tag-actions button[data-id="${tag.id}"])`);
+
+ if (!tagInfoElement) {
+ // Alternative selector for browsers that don't support :has
+ const tagElement = document.querySelector(`.existing-tag`);
+ const buttons = tagElement?.querySelectorAll(`.existing-tag-actions button[data-id="${tag.id}"]`);
+ if (buttons?.length > 0) {
+ const parent = buttons[0].closest('.existing-tag');
+ if (parent) {
+ const infoElement = parent.querySelector('.existing-tag-info');
+ if (infoElement) {
+ tagInfoElement = infoElement;
+ }
}
- };
+ }
- // Use the full URL to avoid path issues
- const apiUrl = `${window.location.origin}/api/warranties/${currentWarrantyId}`;
+ if (!tagInfoElement) return;
+ }
+
+ const originalHTML = tagInfoElement.innerHTML;
+
+ tagInfoElement.innerHTML = `
+ <input type="text" class="form-control edit-tag-name" value="${tag.name}" style="width: 60%;">
+ <input type="color" class="edit-tag-color" value="${tag.color}" style="width: 40px; height: 38px;">
+ <button class="btn btn-sm btn-primary save-edit" data-id="${tag.id}">Save</button>
+ <button class="btn btn-sm btn-secondary cancel-edit">Cancel</button>
+ `;
+
+ // Add event listeners
+ tagInfoElement.querySelector('.save-edit').addEventListener('click', () => {
+ const newName = tagInfoElement.querySelector('.edit-tag-name').value.trim();
+ const newColor = tagInfoElement.querySelector('.edit-tag-color').value;
- console.log('Deleting warranty with ID:', currentWarrantyId);
- const response = await fetch(apiUrl, options);
+ if (!newName) {
+ showToast('Tag name is required', 'error');
+ return;
+ }
+ updateTag(tag.id, newName, newColor);
+ });
+
+ tagInfoElement.querySelector('.cancel-edit').addEventListener('click', () => {
+ // Restore original HTML
+ tagInfoElement.innerHTML = originalHTML;
+ });
+}
+
+// Update a tag
+function updateTag(id, name, color) {
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('No authentication token found');
+ return;
+ }
+
+ fetch(`/api/tags/${id}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': 'Bearer ' + token
+ },
+ body: JSON.stringify({
+ name: name,
+ color: color
+ })
+ })
+ .then(response => {
if (!response.ok) {
- const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));
- throw new Error(errorData.message || `Error deleting warranty: ${response.status}`);
+ if (response.status === 409) {
+ throw new Error('A tag with this name already exists');
+ }
+ throw new Error('Failed to update tag');
+ }
+ return response.json();
+ })
+ .then(data => {
+ // Update tag in allTags array
+ const index = allTags.findIndex(tag => tag.id === id);
+ if (index !== -1) {
+ allTags[index].name = name;
+ allTags[index].color = color;
}
- // Reload all warranties to get the updated list
- await loadWarranties();
+ // Update tag in selectedTags if present
+ const selectedIndex = selectedTags.findIndex(tag => tag.id === id);
+ if (selectedIndex !== -1) {
+ selectedTags[selectedIndex].name = name;
+ selectedTags[selectedIndex].color = color;
+ }
- // Close the modal
- closeModals();
+ // Rerender existing tags and selected tags
+ renderExistingTags();
+ renderSelectedTags();
- // Show success message
- showToast('Warranty deleted successfully!', 'success');
- } catch (error) {
- console.error('Error deleting warranty:', error);
- showToast(error.message || 'Error deleting warranty. Please try again.', 'error');
- } finally {
- hideLoading();
- }
+ // Update summary if needed
+ if (document.getElementById('summary-tags')) {
+ updateSummary();
+ }
+
+ showToast('Tag updated successfully', 'success');
+ })
+ .catch(error => {
+ console.error('Error updating tag:', error);
+ showToast(error.message || 'Failed to update tag', 'error');
+ });
}
-// Initialize page
-document.addEventListener('DOMContentLoaded', () => {
- console.log('DOM fully loaded, initializing app...');
+// Delete a tag
+function deleteTag(id) {
+ if (!confirm('Are you sure you want to delete this tag? It will be removed from all warranties.')) {
+ return;
+ }
- // Ensure auth state is checked
- if (window.auth && window.auth.checkAuthState) {
- window.auth.checkAuthState();
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('No authentication token found');
+ return;
}
+ fetch(`/api/tags/${id}`, {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': 'Bearer ' + token
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error('Failed to delete tag');
+ }
+ return response.json();
+ })
+ .then(data => {
+ // Remove tag from allTags array
+ allTags = allTags.filter(tag => tag.id !== id);
+
+ // Remove tag from selectedTags if present
+ selectedTags = selectedTags.filter(tag => tag.id !== id);
+
+ // Rerender existing tags and selected tags
+ renderExistingTags();
+ renderSelectedTags();
+
+ // Update summary if needed
+ if (document.getElementById('summary-tags')) {
+ updateSummary();
+ }
+
+ showToast('Tag deleted successfully', 'success');
+ })
+ .catch(error => {
+ console.error('Error deleting tag:', error);
+ showToast('Failed to delete tag', 'error');
+ });
+}
+
+// Set up event listeners for UI controls
+function setupUIEventListeners() {
// Initialize settings button
+ const settingsBtn = document.querySelector('.settings-btn');
+ const settingsMenu = document.querySelector('.settings-menu');
+
if (settingsBtn && settingsMenu) {
settingsBtn.addEventListener('click', (e) => {
e.stopPropagation();
@@ -1578,14 +2244,8 @@ document.addEventListener('DOMContentLoaded', () => {
});
}
- // Initialize the app
- initializeTheme();
-
- // Initialize form tabs
- initFormTabs();
-
- // Initialize the form
- resetForm();
+ // Initialize edit tabs
+ initEditTabs();
// Close modals when clicking outside or on close button
document.querySelectorAll('.modal-backdrop, [data-dismiss="modal"]').forEach(element => {
@@ -1604,13 +2264,45 @@ document.addEventListener('DOMContentLoaded', () => {
});
// Filter event listeners
+ const searchInput = document.getElementById('searchWarranties');
+ const clearSearchBtn = document.getElementById('clearSearch');
+ const statusFilter = document.getElementById('statusFilter');
+ const tagFilter = document.getElementById('tagFilter');
+ const sortBySelect = document.getElementById('sortBy');
+
if (searchInput) {
searchInput.addEventListener('input', () => {
currentFilters.search = searchInput.value.toLowerCase();
+
+ // Show/hide clear button based on search input
+ if (clearSearchBtn) {
+ clearSearchBtn.style.display = searchInput.value ? 'flex' : 'none';
+ }
+
+ // Add visual feedback class to search box when active
+ if (searchInput.value) {
+ searchInput.parentElement.classList.add('active-search');
+ } else {
+ searchInput.parentElement.classList.remove('active-search');
+ }
+
applyFilters();
});
}
+ if (clearSearchBtn) {
+ clearSearchBtn.addEventListener('click', () => {
+ if (searchInput) {
+ searchInput.value = '';
+ currentFilters.search = '';
+ clearSearchBtn.style.display = 'none';
+ searchInput.parentElement.classList.remove('active-search');
+ searchInput.focus();
+ applyFilters();
+ }
+ });
+ }
+
if (statusFilter) {
statusFilter.addEventListener('change', () => {
currentFilters.status = statusFilter.value;
@@ -1618,195 +2310,357 @@ document.addEventListener('DOMContentLoaded', () => {
});
}
+ if (tagFilter) {
+ tagFilter.addEventListener('change', () => {
+ currentFilters.tag = tagFilter.value;
+ applyFilters();
+ });
+ }
+
if (sortBySelect) {
sortBySelect.addEventListener('change', () => {
- currentFilters.sort = sortBySelect.value;
+ currentFilters.sortBy = sortBySelect.value;
applyFilters();
});
}
// View switcher event listeners
+ const gridViewBtn = document.getElementById('gridViewBtn');
+ const listViewBtn = document.getElementById('listViewBtn');
+ const tableViewBtn = document.getElementById('tableViewBtn');
+
if (gridViewBtn) gridViewBtn.addEventListener('click', () => switchView('grid'));
if (listViewBtn) listViewBtn.addEventListener('click', () => switchView('list'));
if (tableViewBtn) tableViewBtn.addEventListener('click', () => switchView('table'));
// Export button event listener
+ const exportBtn = document.getElementById('exportBtn');
if (exportBtn) exportBtn.addEventListener('click', exportWarranties);
- // File input change event
- if (fileInput) fileInput.addEventListener('change', (e) => updateFileName(e, 'invoice', 'fileName'));
- if (manualInput) manualInput.addEventListener('change', (e) => updateFileName(e, 'manual', 'manualFileName'));
-
- const editInvoiceInput = document.getElementById('editInvoice');
- if (editInvoiceInput) {
- editInvoiceInput.addEventListener('change', () => {
- updateFileName(null, 'editInvoice', 'editFileName');
- });
- }
-
- const editManualInput = document.getElementById('editManual');
- if (editManualInput) {
- editManualInput.addEventListener('change', () => {
- updateFileName(null, 'editManual', 'editManualFileName');
- });
- }
-
- // Form submission
- if (warrantyForm) warrantyForm.addEventListener('submit', addWarranty);
-
// Refresh button
+ const refreshBtn = document.getElementById('refreshBtn');
if (refreshBtn) refreshBtn.addEventListener('click', loadWarranties);
// Save warranty changes
- if (saveWarrantyBtn) saveWarrantyBtn.addEventListener('click', updateWarranty);
+ const saveWarrantyBtn = document.getElementById('saveWarrantyBtn');
+ if (saveWarrantyBtn) saveWarrantyBtn.addEventListener('click', saveWarranty);
// Confirm delete button
+ const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
if (confirmDeleteBtn) confirmDeleteBtn.addEventListener('click', deleteWarranty);
// Load saved view preference
loadViewPreference();
-
- // Load preferences first to ensure we have the correct expiringSoonDays value
- // before loading warranties
- if (window.auth && window.auth.isAuthenticated()) {
- console.log('User is authenticated, loading preferences...');
- const token = window.auth.getToken();
-
- if (token) {
- fetch('/api/auth/preferences', {
- headers: {
- 'Authorization': `Bearer ${token}`
- }
- })
- .then(response => {
- if (response.ok) return response.json();
- throw new Error('Failed to load preferences');
- })
- .then(data => {
- if (data && data.expiring_soon_days) {
- expiringSoonDays = data.expiring_soon_days;
- console.log('Updated expiring soon days from preferences during initialization:', expiringSoonDays);
- }
- // Now load warranties with the updated preference
- loadWarranties();
- })
- .catch(error => {
- console.error('Error loading preferences during initialization:', error);
- // Still load warranties even if preferences couldn't be loaded
- loadWarranties();
- });
- } else {
- // No token available, load warranties with default preference
- loadWarranties();
- }
- } else {
- // User not authenticated, load warranties (this will show login prompt)
- loadWarranties();
+}
+
+// Function to show loading spinner
+function showLoadingSpinner() {
+ if (loadingContainer) {
+ loadingContainer.style.display = 'flex';
+ }
+}
+
+// Function to hide loading spinner
+function hideLoadingSpinner() {
+ if (loadingContainer) {
+ loadingContainer.style.display = 'none';
+ }
+}
+
+// Delete warranty function
+function deleteWarranty() {
+ if (!currentWarrantyId) {
+ showToast('No warranty selected for deletion', 'error');
+ return;
}
- // Initialize edit tabs
- initEditTabs();
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ showToast('Authentication required', 'error');
+ return;
+ }
- console.log('App initialization complete');
-});
-
-// Add this function to handle edit tab functionality
-function initEditTabs() {
- const editTabBtns = document.querySelectorAll('.edit-tab-btn');
+ showLoadingSpinner();
- editTabBtns.forEach(btn => {
- btn.addEventListener('click', () => {
- // Remove active class from all tabs
- editTabBtns.forEach(b => b.classList.remove('active'));
-
- // Add active class to clicked tab
- btn.classList.add('active');
-
- // Hide all tab content
- document.querySelectorAll('.edit-tab-content').forEach(content => {
- content.classList.remove('active');
- });
-
- // Show the selected tab content
- const tabId = btn.getAttribute('data-tab');
- document.getElementById(tabId).classList.add('active');
- });
+ fetch(`/api/warranties/${currentWarrantyId}`, {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': 'Bearer ' + token
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error('Failed to delete warranty');
+ }
+ return response.json();
+ })
+ .then(data => {
+ hideLoadingSpinner();
+ showToast('Warranty deleted successfully', 'success');
+ closeModals();
+ loadWarranties();
+ })
+ .catch(error => {
+ hideLoadingSpinner();
+ console.error('Error deleting warranty:', error);
+ showToast('Failed to delete warranty', 'error');
});
}
-// Update validateEditTabs function
-function validateEditTab(tabId) {
- const tab = document.getElementById(tabId);
- let isValid = true;
+// Save warranty updates
+function saveWarranty() {
+ if (!currentWarrantyId) {
+ showToast('No warranty selected for update', 'error');
+ return;
+ }
- // Get all required inputs in this tab
- const requiredInputs = tab.querySelectorAll('input[required]');
+ const productName = document.getElementById('editProductName').value.trim();
+ const purchaseDate = document.getElementById('editPurchaseDate').value;
+ const warrantyYears = document.getElementById('editWarrantyYears').value;
- // Check if all required fields are filled
- requiredInputs.forEach(input => {
- if (!input.value) {
- isValid = false;
- input.classList.add('invalid');
- } else {
- input.classList.remove('invalid');
+ // Basic validation
+ if (!productName) {
+ showToast('Product name is required', 'error');
+ return;
+ }
+
+ if (!purchaseDate) {
+ showToast('Purchase date is required', 'error');
+ return;
+ }
+
+ if (!warrantyYears || warrantyYears <= 0) {
+ showToast('Warranty period must be greater than 0', 'error');
+ return;
+ }
+
+ // Create form data
+ const formData = new FormData();
+ formData.append('product_name', productName);
+ formData.append('purchase_date', purchaseDate);
+ formData.append('warranty_years', warrantyYears);
+
+ // Optional fields
+ const productUrl = document.getElementById('editProductUrl').value.trim();
+ if (productUrl) {
+ formData.append('product_url', productUrl);
+ }
+
+ const purchasePrice = document.getElementById('editPurchasePrice').value;
+ if (purchasePrice) {
+ formData.append('purchase_price', purchasePrice);
+ }
+
+ // Serial numbers
+ const serialInputs = document.querySelectorAll('#editSerialNumbersContainer input');
+ serialInputs.forEach(input => {
+ if (input.value.trim()) {
+ formData.append('serial_numbers', input.value.trim());
}
});
- // Update the tab button to show completion status
- const tabBtn = document.querySelector(`.edit-tab-btn[data-tab="${tabId}"]`);
- if (isValid) {
- tabBtn.classList.add('completed');
+ // Tags - add tag IDs as JSON string
+ if (editSelectedTags && editSelectedTags.length > 0) {
+ const tagIds = editSelectedTags.map(tag => tag.id);
+ formData.append('tag_ids', JSON.stringify(tagIds));
} else {
- tabBtn.classList.remove('completed');
+ // Send empty array to clear tags
+ formData.append('tag_ids', JSON.stringify([]));
}
- return isValid;
-}
-
-// Add this function for secure file access
-function openSecureFile(filePath) {
- if (!filePath || filePath === 'null') {
- console.error('Invalid file path:', filePath);
- showToast('Invalid file path', 'error');
- return false;
+ // Files
+ const invoiceFile = document.getElementById('editInvoice').files[0];
+ if (invoiceFile) {
+ formData.append('invoice', invoiceFile);
}
- console.log('Opening secure file:', filePath);
-
- // Get the file name from the path
- const fileName = filePath.split('/').pop();
+ const manualFile = document.getElementById('editManual').files[0];
+ if (manualFile) {
+ formData.append('manual', manualFile);
+ }
// Get auth token
- const token = window.auth.getToken();
+ const token = localStorage.getItem('auth_token');
if (!token) {
- showToast('Authentication error. Please log in again.', 'error');
- return false;
+ showToast('Authentication required', 'error');
+ return;
}
- // Use fetch with proper authorization header
- fetch(`/api/secure-file/${fileName}`, {
- method: 'GET',
+ showLoadingSpinner();
+
+ // Send request
+ fetch(`/api/warranties/${currentWarrantyId}`, {
+ method: 'PUT',
headers: {
- 'Authorization': `Bearer ${token}`
- }
+ 'Authorization': 'Bearer ' + token
+ },
+ body: formData
})
.then(response => {
if (!response.ok) {
- throw new Error(`Error: ${response.status} ${response.statusText}`);
+ return response.json().then(data => {
+ throw new Error(data.error || 'Failed to update warranty');
+ });
}
- return response.blob();
+ return response.json();
})
- .then(blob => {
- // Create a URL for the blob
- const blobUrl = window.URL.createObjectURL(blob);
-
- // Open in new tab
- window.open(blobUrl, '_blank');
+ .then(data => {
+ hideLoadingSpinner();
+ showToast('Warranty updated successfully', 'success');
+ closeModals();
+ loadWarranties();
})
.catch(error => {
- console.error('Error fetching file:', error);
- showToast('Error opening file: ' + error.message, 'error');
+ hideLoadingSpinner();
+ console.error('Error updating warranty:', error);
+ showToast(error.message || 'Failed to update warranty', 'error');
});
+}
+
+// Render the tags dropdown list for edit mode
+function renderEditTagsList(searchTerm = '') {
+ const editTagsList = document.getElementById('editTagsList');
+ if (!editTagsList) return;
- return false;
+ editTagsList.innerHTML = '';
+
+ // Filter tags based on search term
+ const filteredTags = allTags.filter(tag =>
+ !searchTerm || tag.name.toLowerCase().includes(searchTerm.toLowerCase())
+ );
+
+ // Add option to create new tag if search term is provided and not in list
+ if (searchTerm && !filteredTags.some(tag => tag.name.toLowerCase() === searchTerm.toLowerCase())) {
+ const createOption = document.createElement('div');
+ createOption.className = 'tag-option create-tag';
+ createOption.innerHTML = `<i class="fas fa-plus"></i> Create "${searchTerm}"`;
+ createOption.addEventListener('click', () => {
+ createTag(searchTerm);
+ editTagsList.classList.remove('show');
+ });
+ editTagsList.appendChild(createOption);
+ }
+
+ // Add existing tags to dropdown
+ filteredTags.forEach(tag => {
+ const option = document.createElement('div');
+ option.className = 'tag-option';
+
+ // Check if tag is already selected
+ const isSelected = editSelectedTags.some(selected => selected.id === tag.id);
+
+ option.innerHTML = `
+ <span class="tag-color" style="background-color: ${tag.color}"></span>
+ ${tag.name}
+ <span class="tag-status">${isSelected ? '<i class="fas fa-check"></i>' : ''}</span>
+ `;
+
+ option.addEventListener('click', () => {
+ if (isSelected) {
+ // Remove tag if already selected
+ editSelectedTags = editSelectedTags.filter(selected => selected.id !== tag.id);
+ } else {
+ // Add tag if not selected
+ editSelectedTags.push({
+ id: tag.id,
+ name: tag.name,
+ color: tag.color
+ });
+ }
+
+ // Use our helper function to render selected tags
+ renderEditSelectedTags();
+
+ renderEditTagsList(searchTerm);
+ });
+
+ editTagsList.appendChild(option);
+ });
+
+ // Show the dropdown
+ editTagsList.classList.add('show');
+}
+
+// Function to populate tag filter dropdown
+function populateTagFilter() {
+ const tagFilter = document.getElementById('tagFilter');
+ if (!tagFilter) return;
+
+ // Clear existing options (except "All Tags")
+ while (tagFilter.options.length > 1) {
+ tagFilter.remove(1);
+ }
+
+ // Create a Set to store unique tag names
+ const uniqueTags = new Set();
+
+ // Collect all unique tags from warranties
+ warranties.forEach(warranty => {
+ if (warranty.tags && Array.isArray(warranty.tags)) {
+ warranty.tags.forEach(tag => {
+ uniqueTags.add(JSON.stringify({id: tag.id, name: tag.name, color: tag.color}));
+ });
+ }
+ });
+
+ // Sort tags alphabetically by name
+ const sortedTags = Array.from(uniqueTags)
+ .map(tagJson => JSON.parse(tagJson))
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ // Add options to the dropdown
+ sortedTags.forEach(tag => {
+ const option = document.createElement('option');
+ option.value = tag.id;
+ option.textContent = tag.name;
+ option.style.backgroundColor = tag.color;
+ tagFilter.appendChild(option);
+ });
+}
+
+// Helper function to render the edit selected tags
+function renderEditSelectedTags() {
+ const editSelectedTagsContainer = document.getElementById('editSelectedTags');
+ if (!editSelectedTagsContainer) return;
+
+ editSelectedTagsContainer.innerHTML = '';
+
+ if (editSelectedTags.length > 0) {
+ editSelectedTags.forEach(tag => {
+ const tagElement = document.createElement('span');
+ tagElement.className = 'tag';
+ tagElement.style.backgroundColor = tag.color;
+ tagElement.style.color = getContrastColor(tag.color);
+
+ tagElement.innerHTML = `
+ ${tag.name}
+ <span class="remove-tag" data-id="${tag.id}">&times;</span>
+ `;
+
+ // Add event listener for removing tag
+ const removeButton = tagElement.querySelector('.remove-tag');
+ removeButton.addEventListener('click', (e) => {
+ e.stopPropagation();
+ e.preventDefault(); // Add this to prevent default action
+
+ // Prevent the event from bubbling up to parent elements
+ if (e.cancelBubble !== undefined) {
+ e.cancelBubble = true;
+ }
+
+ editSelectedTags = editSelectedTags.filter(t => t.id !== tag.id);
+
+ // Re-render just the tags
+ renderEditSelectedTags();
+ return false; // Add return false for older browsers
+ });
+
+ editSelectedTagsContainer.appendChild(tagElement);
+ });
+ } else {
+ const placeholder = document.createElement('span');
+ placeholder.className = 'no-tags-selected';
+ placeholder.textContent = 'No tags selected';
+ editSelectedTagsContainer.appendChild(placeholder);
+ }
}
\ No newline at end of file
diff --git a/frontend/style.css b/frontend/style.css
index 5d7c1fb..58593fe 100644
--- a/frontend/style.css
+++ b/frontend/style.css
@@ -9,6 +9,7 @@
--shadow-color: rgba(0, 0, 0, 0.1);
--primary-color: #3498db;
+ --primary-rgb: 52, 152, 219;
--primary-dark: #2980b9;
--secondary-color: #2ecc71;
--danger-color: #e74c3c;
@@ -38,6 +39,7 @@
--loading-backdrop: rgba(0, 0, 0, 0.8);
--shadow-color: rgba(0, 0, 0, 0.3);
--primary-color: #4dabf7;
+ --primary-rgb: 77, 171, 247;
--primary-dark: #339af0;
--secondary-color: #40c057;
--danger-color: #fa5252;
@@ -427,34 +429,92 @@ input.invalid {
}
.search-box {
+ display: flex;
+ align-items: center;
+ background-color: var(--search-bg);
+ border: 1px solid var(--border-color);
+ padding: 8px 15px;
+ width: 100%;
+ border-radius: 25px;
position: relative;
- margin-bottom: 0;
+ transition: all 0.3s ease;
+ box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}
-.search-box input {
+.search-box:focus-within {
+ box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
+ border-color: var(--primary-color);
width: 100%;
- padding: 8px 10px 8px 35px;
- border: 1px solid var(--border-color);
- border-radius: var(--border-radius);
- font-size: 0.95rem;
- background-color: var(--bg-color);
- color: var(--text-color);
- transition: var(--transition);
}
-.search-box input:focus {
- outline: none;
+.search-box.active-search {
+ box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
border-color: var(--primary-color);
- box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
+ background-color: rgba(var(--primary-rgb), 0.05);
+ width: 100%;
}
.search-box i {
- position: absolute;
- left: 12px;
- top: 50%;
- transform: translateY(-50%);
- color: var(--dark-gray);
+ color: var(--text-muted);
font-size: 1rem;
+ margin-right: 10px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 20px;
+ position: static; /* Override any absolute positioning */
+ transform: none; /* Reset any transform */
+ left: auto; /* Reset any left positioning */
+ top: auto; /* Reset any top positioning */
+}
+
+.search-box.active-search i {
+ color: var(--primary-color);
+ animation: search-pulse 1.5s ease-in-out infinite;
+}
+
+@keyframes search-pulse {
+ 0% { transform: scale(1); }
+ 50% { transform: scale(1.1); }
+ 100% { transform: scale(1); }
+}
+
+.search-box input {
+ border: none;
+ outline: none;
+ background: none;
+ width: 100%;
+ color: var(--text-color);
+ font-size: 0.95rem;
+ padding: 2px 0;
+}
+
+.search-box input::placeholder {
+ color: var(--text-muted);
+ opacity: 0.8;
+}
+
+.clear-search-btn {
+ background: none;
+ border: none;
+ outline: none;
+ cursor: pointer;
+ color: var(--text-muted);
+ font-size: 0.9rem;
+ opacity: 0.7;
+ transition: opacity 0.3s;
+ padding: 0;
+ margin-left: 5px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 20px;
+}
+
+.clear-search-btn:hover {
+ opacity: 1;
+ color: var(--primary-color);
}
.warranties-list {
@@ -652,6 +712,32 @@ input.invalid {
}
}
+/* Serial number input styling */
+.serial-number-input {
+ display: flex;
+ align-items: center;
+ margin-bottom: 10px;
+ gap: 10px;
+}
+
+.serial-number-input .form-control {
+ flex-grow: 1;
+}
+
+.serial-number-input .btn {
+ width: auto;
+ padding: 8px 10px;
+}
+
+.add-serial {
+ display: block;
+ width: 100%;
+ margin-top: 5px;
+ margin-bottom: 15px;
+}
+
+/* End serial number input styling */
+
.modal-header {
padding: 1rem;
border-bottom: 1px solid var(--border-color);
@@ -862,6 +948,13 @@ input.invalid {
width: 100%;
justify-content: center;
}
+
+ .search-box,
+ .search-box:focus-within,
+ .search-box.active-search {
+ width: 100%;
+ max-width: none;
+ }
}
/* ===== SETTINGS MENU ===== */
@@ -1666,35 +1759,53 @@ input.invalid {
border: 1px solid var(--border-color);
}
-.search-box {
+.search-container {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin-bottom: 15px;
+}
+
+.search-container .search-box {
+ flex: 1;
+}
+
+.search-container .export-btn {
+ margin-top: 0;
+ align-self: center;
+ height: 42px;
+ flex-shrink: 0;
+}
+
+/* Override any conflicting search box styles */
+.filter-controls .search-box {
position: relative;
margin-bottom: 0;
+ display: flex;
+ align-items: center;
}
-.search-box i {
- position: absolute;
- left: 12px;
- top: 50%;
- transform: translateY(-50%);
- color: var(--dark-gray);
- font-size: 1rem;
+.filter-controls .search-box i {
+ position: static;
+ left: auto;
+ top: auto;
+ transform: none;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ margin-right: 10px;
+ min-width: 20px;
+ color: var(--text-muted);
}
-.search-box input {
+.filter-controls .search-box input {
+ border: none;
+ outline: none;
+ background: none;
width: 100%;
- padding: 8px 10px 8px 35px;
- border: 1px solid var(--border-color);
- border-radius: var(--border-radius);
- font-size: 0.95rem;
- background-color: var(--bg-color);
color: var(--text-color);
- transition: var(--transition);
-}
-
-.search-box input:focus {
- outline: none;
- border-color: var(--primary-color);
- box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
+ font-size: 0.95rem;
+ padding: 2px 0;
}
.filter-options {
@@ -1785,6 +1896,37 @@ input.invalid {
width: 100%;
}
+ .search-container {
+ flex-direction: row;
+ flex-wrap: wrap;
+ gap: 10px;
+ }
+
+ .search-container .search-box {
+ width: calc(100% - 110px);
+ min-width: 200px;
+ }
+
+ .search-container .export-btn {
+ height: 42px;
+ width: 100px;
+ }
+
+ @media (max-width: 480px) {
+ .search-container {
+ flex-direction: column;
+ gap: 10px;
+ }
+
+ .search-container .search-box {
+ width: 100%;
+ }
+
+ .search-container .export-btn {
+ width: 100%;
+ }
+ }
+
.export-btn {
margin-top: 5px;
}
@@ -1894,6 +2036,21 @@ input.invalid {
margin-right: 15px;
}
+.list-view .warranty-card .tags-row {
+ display: flex;
+ flex-wrap: wrap;
+ padding: 12px 15px 12px;
+ margin-top: 0;
+ border-top: 1px solid var(--border-color);
+ width: 100%;
+}
+
+/* For list view, ensure tags are clearly visible */
+.list-view .tag {
+ margin-top: 4px;
+ margin-bottom: 4px;
+}
+
/* Table View */
.warranties-list.table-view {
display: table;
@@ -2691,4 +2848,93 @@ input.invalid {
:root[data-theme="dark"] .modal-backdrop {
background-color: rgba(0, 0, 0, 0.7);
+}
+
+/* Tags styling in warranty cards */
+.tag {
+ display: inline-flex;
+ align-items: center;
+ padding: 6px 10px;
+ border-radius: 16px;
+ font-size: 0.85rem;
+ font-weight: 500;
+ margin-right: 8px;
+ margin-bottom: 8px;
+ white-space: nowrap;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
+}
+
+.tag .remove-tag {
+ margin-left: 6px;
+ cursor: pointer;
+ font-size: 1.1rem;
+ line-height: 1;
+ opacity: 0.7;
+ transition: opacity 0.2s ease, transform 0.2s ease;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ background-color: rgba(0, 0, 0, 0.1);
+}
+
+.tag .remove-tag:hover {
+ opacity: 1;
+ transform: scale(1.2);
+ background-color: rgba(0, 0, 0, 0.2);
+}
+
+/* Make the remove-tag more prominent in the edit modal */
+#editSelectedTags .tag .remove-tag {
+ font-weight: bold;
+ background-color: rgba(0, 0, 0, 0.2);
+ border-radius: 50%;
+ width: 22px;
+ height: 22px;
+ margin-left: 8px;
+ font-size: 1.2rem;
+ opacity: 0.8;
+ /* Prevent text selection */
+ user-select: none;
+ -webkit-user-select: none;
+}
+
+#editSelectedTags .tag .remove-tag:hover {
+ opacity: 1;
+ transform: scale(1.2);
+ background-color: rgba(0, 0, 0, 0.3);
+}
+
+/* Use a more obvious pointer cursor */
+#editSelectedTags .tag .remove-tag {
+ cursor: pointer;
+}
+
+.warranty-card .tags-row {
+ display: flex;
+ flex-wrap: wrap;
+ margin-top: 10px;
+ padding: 12px 15px 12px;
+ border-top: 1px solid var(--border-color);
+}
+
+/* Tag styling for grid view */
+.grid-view .warranty-card .tags-row {
+ padding: 12px 15px 12px;
+}
+
+/* Tag styling for list view */
+.list-view .warranty-card .tags-row {
+ padding: 12px 15px 12px;
+}
+
+/* Tag styling for table view */
+.table-view .warranty-card .tags-row {
+ display: table-cell;
+ vertical-align: middle;
+ padding: 12px 15px;
+ width: 20%;
+ border-top: none;
}
\ No newline at end of file
diff --git a/frontend/styles.css b/frontend/styles.css
new file mode 100644
index 0000000..90e4b1e
--- /dev/null
+++ b/frontend/styles.css
@@ -0,0 +1,219 @@
+/* Tag Styles */
+.tags-container {
+ margin-bottom: 15px;
+}
+
+.selected-tags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-bottom: 10px;
+}
+
+.tag {
+ display: inline-flex;
+ align-items: center;
+ padding: 4px 8px;
+ border-radius: 16px;
+ font-size: 14px;
+ cursor: pointer;
+ transition: all 0.2s ease;
+ margin: 2px;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
+}
+
+.tag .remove-tag {
+ margin-left: 6px;
+ font-size: 12px;
+ opacity: 0.7;
+}
+
+.tag:hover .remove-tag {
+ opacity: 1;
+}
+
+.tags-dropdown {
+ position: relative;
+}
+
+.tags-list {
+ position: absolute;
+ top: 100%;
+ left: 0;
+ right: 0;
+ background: white;
+ border: 1px solid #ddd;
+ border-radius: 4px;
+ max-height: 200px;
+ overflow-y: auto;
+ z-index: 1000;
+ display: none;
+}
+
+.tags-list.show {
+ display: block;
+}
+
+.tag-option {
+ padding: 8px 12px;
+ cursor: pointer;
+}
+
+.tag-option:hover {
+ background-color: #f5f5f5;
+}
+
+/* Tag Management Modal */
+#tagManagementModal {
+ z-index: 1050;
+}
+
+.tag-form {
+ display: flex;
+ gap: 10px;
+ margin-bottom: 20px;
+}
+
+.tag-form input[type="color"] {
+ width: 50px;
+ padding: 0;
+ height: 38px;
+}
+
+.existing-tags {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.existing-tag {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 8px 12px;
+ background: var(--bg-secondary);
+ border-radius: 4px;
+}
+
+.existing-tag-info {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+
+.existing-tag-color {
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ border: 1px solid var(--border-color);
+}
+
+.existing-tag-actions {
+ display: flex;
+ gap: 8px;
+}
+
+.edit-tab-content .tags-container,
+.tab-content .tags-container {
+ background-color: var(--bg-secondary);
+ border-radius: 8px;
+ padding: 10px;
+ margin-bottom: 15px;
+}
+
+.edit-tab-content .selected-tags,
+.tab-content .selected-tags {
+ margin-bottom: 10px;
+}
+
+#editTagSearch, #tagSearch {
+ background-color: var(--bg-main);
+ color: var(--text-primary);
+ border: 1px solid var(--border-color);
+}
+
+/* Fix for the tag modal to appear on top of other modals */
+.modal {
+ display: none;
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: rgba(0, 0, 0, 0.5);
+ z-index: 1000;
+ overflow: auto;
+}
+
+.modal-content {
+ background-color: var(--bg-main);
+ margin: 50px auto;
+ padding: 0;
+ border-radius: 8px;
+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
+ width: 90%;
+ max-width: 600px;
+ max-height: 85vh;
+ overflow-y: auto;
+}
+
+.modal-header {
+ padding: 15px 20px;
+ border-bottom: 1px solid var(--border-color);
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ background-color: var(--bg-secondary);
+ border-radius: 8px 8px 0 0;
+}
+
+.modal-header h2 {
+ margin: 0;
+ font-size: 1.25rem;
+}
+
+.modal-body {
+ padding: 20px;
+}
+
+.modal-footer {
+ padding: 15px 20px;
+ border-top: 1px solid var(--border-color);
+ display: flex;
+ justify-content: flex-end;
+ gap: 10px;
+}
+
+.modal .close {
+ font-size: 24px;
+ font-weight: bold;
+ cursor: pointer;
+ color: var(--text-muted);
+}
+
+.modal .close:hover {
+ color: var(--text-primary);
+}
+
+/* Add tag indicator in warranty cards */
+.warranty-card .tags-row {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-top: 10px;
+ padding-top: 10px;
+ border-top: 1px solid #eee;
+}
+
+/* Modal z-index layering */
+.modal {
+ z-index: 1000;
+}
+
+#editModal, #deleteModal {
+ z-index: 1000;
+}
+
+#tagManagementModal {
+ z-index: 1050;
+}
\ No newline at end of file