Skip to content

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

My project so far

sassanix82f70164d220
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..49c1745
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,116 @@
+# 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 \
+ && apt-get clean \
+ && rm -rf /var/lib/apt/lists/*
+
+# Set working directory
+WORKDIR /app
+
+# Install Python dependencies
+COPY backend/requirements.txt .
+RUN pip install --no-cache-dir -r requirements.txt
+
+# Copy backend code
+COPY backend/app.py .
+
+# Create directory for uploads
+RUN mkdir -p /data/uploads
+
+# Copy frontend files
+COPY frontend/index.html /var/www/html/
+COPY frontend/script.js /var/www/html/
+COPY frontend/style.css /var/www/html/
+
+# Configure nginx
+RUN rm /etc/nginx/sites-enabled/default
+COPY nginx.conf /etc/nginx/conf.d/default.conf
+
+# Create startup script
+RUN echo '#!/bin/bash\n\
+nginx\n\
+gunicorn --bind 0.0.0.0:5000 --workers 4 app:app\n\
+' > /app/start.sh && chmod +x /app/start.sh
+
+# Create nginx configuration
+RUN echo 'server {\n\
+ listen 80;\n\
+ server_name localhost;\n\
+ root /var/www/html;\n\
+ index index.html;\n\
+ \n\
+ # Enable gzip compression\n\
+ gzip on;\n\
+ gzip_types text/plain text/css application/javascript application/json;\n\
+ \n\
+ location / {\n\
+ try_files $uri $uri/ /index.html;\n\
+ }\n\
+ \n\
+ # Proxy API requests to backend\n\
+ location /api/ {\n\
+ proxy_pass http://localhost:5000;\n\
+ proxy_set_header Host $host;\n\
+ proxy_set_header X-Real-IP $remote_addr;\n\
+ }\n\
+ \n\
+ # Proxy uploads to backend\n\
+ location /uploads/ {\n\
+ proxy_pass http://localhost:5000;\n\
+ proxy_set_header Host $host;\n\
+ proxy_set_header X-Real-IP $remote_addr;\n\
+ }\n\
+ \n\
+ # Cache static assets\n\
+ location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg)$ {\n\
+ expires 7d;\n\
+ add_header Cache-Control "public, max-age=604800";\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 \
+ CMD curl -f http://localhost/api/warranties || 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
+RUN mkdir -p /var/log/supervisor
+
+# Create supervisor configuration
+COPY <<EOF /etc/supervisor/conf.d/supervisord.conf
+[supervisord]
+nodaemon=true
+user=root
+
+[program:nginx]
+command=nginx -g "daemon off;"
+autostart=true
+autorestart=true
+stdout_logfile=/dev/stdout
+stdout_logfile_maxbytes=0
+stderr_logfile=/dev/stderr
+stderr_logfile_maxbytes=0
+
+[program:gunicorn]
+command=gunicorn --bind 0.0.0.0:5000 --workers 4 app:app
+directory=/app
+autostart=true
+autorestart=true
+stdout_logfile=/dev/stdout
+stdout_logfile_maxbytes=0
+stderr_logfile=/dev/stderr
+stderr_logfile_maxbytes=0
+EOF
+
+# Start supervisor
+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
new file mode 100644
index 0000000..426d02c
--- /dev/null
+++ b/backend/app.py
@@ -0,0 +1,322 @@
+from flask import Flask, request, jsonify, send_from_directory
+import psycopg2
+from psycopg2 import pool
+import os
+from datetime import datetime, timedelta
+from werkzeug.utils import secure_filename
+from flask_cors import CORS
+import logging
+
+app = Flask(__name__)
+CORS(app) # Enable CORS
+
+# Configure logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+UPLOAD_FOLDER = '/data/uploads'
+ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg'}
+MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16MB max upload
+
+app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
+app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH
+
+# PostgreSQL connection pool
+DB_HOST = os.environ.get('DB_HOST', 'db')
+DB_NAME = os.environ.get('DB_NAME', 'warranty_db')
+DB_USER = os.environ.get('DB_USER', 'warranty_user')
+DB_PASSWORD = os.environ.get('DB_PASSWORD', 'warranty_password')
+
+# Create a connection pool
+connection_pool = pool.SimpleConnectionPool(
+ 1, 10, # min, max connections
+ host=DB_HOST,
+ database=DB_NAME,
+ user=DB_USER,
+ password=DB_PASSWORD
+)
+
+def get_db_connection():
+ try:
+ return connection_pool.getconn()
+ except Exception as e:
+ logger.error(f"Database connection error: {e}")
+ raise
+
+def release_db_connection(conn):
+ connection_pool.putconn(conn)
+
+def allowed_file(filename):
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
+
+# Initialize database
+def init_db():
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Add indexes to frequently queried fields
+ cur.execute('''
+ CREATE TABLE IF NOT EXISTS warranties (
+ id SERIAL PRIMARY KEY,
+ product_name TEXT NOT NULL,
+ purchase_date DATE NOT NULL,
+ warranty_years INTEGER NOT NULL,
+ expiration_date DATE,
+ invoice_path TEXT,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )
+ ''')
+
+ # Add indexes for faster queries
+ cur.execute('CREATE INDEX IF NOT EXISTS idx_expiration_date ON warranties(expiration_date)')
+ cur.execute('CREATE INDEX IF NOT EXISTS idx_product_name ON warranties(product_name)')
+
+ conn.commit()
+ logger.info("Database initialized successfully")
+ except Exception as e:
+ logger.error(f"Database initialization error: {e}")
+ if conn:
+ conn.rollback()
+ raise
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/warranties', methods=['GET'])
+def get_warranties():
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ cur.execute('SELECT * FROM warranties ORDER BY expiration_date')
+ warranties = cur.fetchall()
+ columns = [desc[0] for desc in cur.description]
+ warranties_list = []
+
+ for row in warranties:
+ warranty_dict = dict(zip(columns, row))
+ # Convert date objects to ISO format strings for JSON serialization
+ for key, value in warranty_dict.items():
+ if isinstance(value, datetime.date):
+ warranty_dict[key] = value.isoformat()
+ warranties_list.append(warranty_dict)
+
+ return jsonify(warranties_list)
+ except Exception as e:
+ logger.error(f"Error retrieving warranties: {e}")
+ return jsonify({"error": "Failed to retrieve warranties"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/warranties', methods=['POST'])
+def add_warranty():
+ conn = None
+ try:
+ # Validate input data
+ if not request.form.get('product_name'):
+ return jsonify({"error": "Product name is required"}), 400
+
+ if not request.form.get('purchase_date'):
+ return jsonify({"error": "Purchase date is required"}), 400
+
+ try:
+ warranty_years = int(request.form.get('warranty_years', '0'))
+ if warranty_years <= 0 or warranty_years > 100: # Set reasonable limits
+ return jsonify({"error": "Warranty years must be between 1 and 100"}), 400
+ except ValueError:
+ return jsonify({"error": "Warranty years must be a valid number"}), 400
+
+ # Process the data
+ product_name = request.form['product_name']
+ purchase_date_str = request.form['purchase_date']
+
+ try:
+ purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d')
+ except ValueError:
+ return jsonify({"error": "Invalid date format. Use YYYY-MM-DD"}), 400
+
+ expiration_date = purchase_date + timedelta(days=warranty_years * 365)
+
+ # Handle file upload
+ db_invoice_path = None
+ if 'invoice' in request.files:
+ invoice = request.files['invoice']
+ if invoice.filename != '':
+ if not allowed_file(invoice.filename):
+ return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
+
+ filename = secure_filename(invoice.filename)
+ # Make filename unique by adding timestamp
+ filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
+ invoice_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
+
+ # Ensure directory exists
+ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
+
+ invoice.save(invoice_path)
+ db_invoice_path = os.path.join('uploads', filename)
+
+ # Save to database
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ cur.execute('''
+ INSERT INTO warranties (product_name, purchase_date, warranty_years, expiration_date, invoice_path)
+ VALUES (%s, %s, %s, %s, %s)
+ RETURNING id
+ ''', (product_name, purchase_date, warranty_years, expiration_date, db_invoice_path))
+ warranty_id = cur.fetchone()[0]
+ conn.commit()
+
+ return jsonify({
+ 'message': 'Warranty added successfully',
+ 'id': warranty_id
+ }), 201
+
+ except Exception as e:
+ logger.error(f"Error adding warranty: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to add warranty"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/warranties/<int:warranty_id>', methods=['DELETE'])
+def delete_warranty(warranty_id):
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # First get the invoice path to delete the file
+ cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
+ result = cur.fetchone()
+
+ if not result:
+ return jsonify({"error": "Warranty not found"}), 404
+
+ invoice_path = result[0]
+
+ # Delete the warranty from database
+ cur.execute('DELETE FROM warranties WHERE id = %s', (warranty_id,))
+ deleted_rows = cur.rowcount
+ conn.commit()
+
+ # Delete the invoice file if it exists
+ if invoice_path:
+ full_path = os.path.join('/data', invoice_path)
+ if os.path.exists(full_path):
+ os.remove(full_path)
+
+ return jsonify({"message": "Warranty deleted successfully"}), 200
+
+ except Exception as e:
+ logger.error(f"Error deleting warranty: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to delete warranty"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/warranties/<int:warranty_id>', methods=['PUT'])
+def update_warranty(warranty_id):
+ conn = None
+ try:
+ # Validate input data similar to the add_warranty route
+ if not request.form.get('product_name'):
+ return jsonify({"error": "Product name is required"}), 400
+
+ if not request.form.get('purchase_date'):
+ return jsonify({"error": "Purchase date is required"}), 400
+
+ try:
+ warranty_years = int(request.form.get('warranty_years', '0'))
+ if warranty_years <= 0 or warranty_years > 100:
+ return jsonify({"error": "Warranty years must be between 1 and 100"}), 400
+ except ValueError:
+ return jsonify({"error": "Warranty years must be a valid number"}), 400
+
+ # Process the data
+ product_name = request.form['product_name']
+ purchase_date_str = request.form['purchase_date']
+
+ try:
+ purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d')
+ except ValueError:
+ return jsonify({"error": "Invalid date format. Use YYYY-MM-DD"}), 400
+
+ expiration_date = purchase_date + timedelta(days=warranty_years * 365)
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if warranty exists
+ cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
+ result = cur.fetchone()
+
+ if not result:
+ return jsonify({"error": "Warranty not found"}), 404
+
+ old_invoice_path = result[0]
+
+ # Handle file upload if new file is provided
+ db_invoice_path = old_invoice_path
+ if 'invoice' in request.files:
+ invoice = request.files['invoice']
+ if invoice.filename != '':
+ if not allowed_file(invoice.filename):
+ return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
+
+ filename = secure_filename(invoice.filename)
+ filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
+ invoice_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
+
+ invoice.save(invoice_path)
+ db_invoice_path = os.path.join('uploads', filename)
+
+ # Remove old invoice file if exists and different from new one
+ 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)
+
+ # Update the warranty in database
+ cur.execute('''
+ UPDATE warranties
+ SET product_name = %s, purchase_date = %s, warranty_years = %s,
+ expiration_date = %s, invoice_path = %s
+ WHERE id = %s
+ ''', (product_name, purchase_date, warranty_years, expiration_date,
+ db_invoice_path, warranty_id))
+
+ conn.commit()
+ return jsonify({"message": "Warranty updated successfully"}), 200
+
+ except Exception as e:
+ logger.error(f"Error updating warranty: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to update warranty"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/uploads/<filename>')
+def uploaded_file(filename):
+ try:
+ return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
+ except Exception as e:
+ logger.error(f"Error serving file {filename}: {e}")
+ return jsonify({"error": "File not found"}), 404
+
+def request_entity_too_large(error):
+ return jsonify({"error": "File too large. Maximum size is 16MB"}), 413
+
+if __name__ == '__main__':
+ try:
+ init_db()
+ app.run(debug=os.environ.get('FLASK_DEBUG', '0') == '1', host='0.0.0.0')
+ except Exception as e:
+ logger.critical(f"Failed to start application: {e}")
\ No newline at end of file
diff --git a/backend/requirements.txt b/backend/requirements.txt
new file mode 100644
index 0000000..a1fe701
--- /dev/null
+++ b/backend/requirements.txt
@@ -0,0 +1,5 @@
+Flask==2.0.1
+gunicorn==20.1.0
+psycopg2-binary==2.9.3
+Werkzeug==2.0.1
+flask-cors==3.0.10
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 0000000..a49c5f3
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,35 @@
+version: '3.8'
+services:
+ app:
+ build: .
+ ports:
+ - "8005:80"
+ volumes:
+ - ./uploads:/data/uploads
+ environment:
+ - DB_HOST=db
+ - DB_NAME=warranty_db
+ - DB_USER=warranty_user
+ - DB_PASSWORD=${DB_PASSWORD:-warranty_password}
+ depends_on:
+ - db
+ restart: unless-stopped
+
+ db:
+ image: "postgres:15-alpine"
+ volumes:
+ - postgres_data:/var/lib/postgresql/data
+ - ./backend/init.sql:/docker-entrypoint-initdb.d/init.sql
+ environment:
+ - POSTGRES_DB=warranty_db
+ - POSTGRES_USER=warranty_user
+ - POSTGRES_PASSWORD=${DB_PASSWORD:-warranty_password}
+ restart: unless-stopped
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U warranty_user -d warranty_db"]
+ interval: 10s
+ timeout: 5s
+ retries: 5
+
+volumes:
+ postgres_data:
\ No newline at end of file
diff --git a/frontend/index.html b/frontend/index.html
new file mode 100644
index 0000000..7f4aeed
--- /dev/null
+++ b/frontend/index.html
@@ -0,0 +1,158 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Warranty Tracker</title>
+ <link rel="stylesheet" href="style.css">
+ <!-- Font Awesome for icons -->
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
+</head>
+<body>
+ <!-- Header -->
+ <header>
+ <div class="container">
+ <div class="app-title">
+ <i class="fas fa-shield-alt"></i>
+ <h1>Warranty Tracker</h1>
+ </div>
+ </div>
+ </header>
+
+ <!-- Main Content -->
+ <div class="container">
+ <div class="main-content">
+ <!-- Form Panel -->
+ <div class="form-panel">
+ <h2>Add New Warranty</h2>
+ <form id="warrantyForm">
+ <div class="form-group">
+ <label for="productName">Product Name</label>
+ <input type="text" id="productName" name="product_name" class="form-control" required>
+ </div>
+
+ <div class="form-group">
+ <label for="purchaseDate">Purchase Date</label>
+ <input type="date" id="purchaseDate" name="purchase_date" class="form-control" required>
+ </div>
+
+ <div class="form-group">
+ <label for="warrantyYears">Warranty Period (Years)</label>
+ <input type="number" id="warrantyYears" name="warranty_years" class="form-control" min="1" max="100" required>
+ </div>
+
+ <div class="form-group">
+ <label>Invoice/Receipt</label>
+ <div class="file-input-wrapper">
+ <label for="invoice" class="file-input-label">
+ <i class="fas fa-upload"></i> Choose File
+ </label>
+ <input type="file" id="invoice" name="invoice" class="file-input" accept=".pdf,.png,.jpg,.jpeg">
+ </div>
+ <div id="fileName" class="file-name"></div>
+ </div>
+
+ <button type="submit" class="btn btn-primary">Add Warranty</button>
+ </form>
+ </div>
+
+ <!-- Warranties List Panel -->
+ <div class="warranties-panel">
+ <h2>
+ Your Warranties
+ <button id="refreshBtn" class="refresh-btn" title="Refresh list">
+ <i class="fas fa-sync-alt"></i>
+ </button>
+ </h2>
+
+ <div class="search-box">
+ <i class="fas fa-search"></i>
+ <input type="text" id="searchWarranties" placeholder="Search warranties...">
+ </div>
+
+ <div id="warrantiesList" class="warranties-list">
+ <!-- Warranties will be loaded here -->
+ <div class="empty-state">
+ <i class="fas fa-box-open"></i>
+ <h3>No warranties yet</h3>
+ <p>Add your first warranty to get started</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Edit Warranty Modal -->
+ <div id="editModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3 class="modal-title">Edit Warranty</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <form id="editWarrantyForm">
+ <input type="hidden" id="editWarrantyId">
+ <div class="form-group">
+ <label for="editProductName">Product Name</label>
+ <input type="text" id="editProductName" name="product_name" class="form-control" required>
+ </div>
+
+ <div class="form-group">
+ <label for="editPurchaseDate">Purchase Date</label>
+ <input type="date" id="editPurchaseDate" name="purchase_date" class="form-control" required>
+ </div>
+
+ <div class="form-group">
+ <label for="editWarrantyYears">Warranty Period (Years)</label>
+ <input type="number" id="editWarrantyYears" name="warranty_years" class="form-control" min="1" max="100" required>
+ </div>
+
+ <div class="form-group">
+ <label>Invoice/Receipt</label>
+ <div class="file-input-wrapper">
+ <label for="editInvoice" class="file-input-label">
+ <i class="fas fa-upload"></i> Choose File
+ </label>
+ <input type="file" id="editInvoice" name="invoice" class="file-input" accept=".pdf,.png,.jpg,.jpeg">
+ </div>
+ <div id="editFileName" class="file-name"></div>
+ <div id="currentInvoice" class="mt-10"></div>
+ </div>
+ </form>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-danger" data-dismiss="modal">Cancel</button>
+ <button id="saveWarrantyBtn" class="btn btn-primary">Save Changes</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Confirm Delete Modal -->
+ <div id="deleteModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3 class="modal-title">Confirm Delete</h3>
+ <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>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
+ <button id="confirmDeleteBtn" class="btn btn-danger">Delete</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Toast Notifications -->
+ <div class="toast-container" id="toastContainer"></div>
+
+ <!-- Loading Spinner -->
+ <div class="loading-container" id="loadingContainer">
+ <div class="loading-spinner"></div>
+ </div>
+
+ <script src="script.js"></script>
+</body>
+</html>
\ No newline at end of file
diff --git a/frontend/script.js b/frontend/script.js
new file mode 100644
index 0000000..26fc1a9
--- /dev/null
+++ b/frontend/script.js
@@ -0,0 +1,380 @@
+// DOM Elements
+const warrantyForm = document.getElementById('warrantyForm');
+const warrantiesList = document.getElementById('warrantiesList');
+const refreshBtn = document.getElementById('refreshBtn');
+const searchInput = document.getElementById('searchWarranties');
+const fileInput = document.getElementById('invoice');
+const fileName = document.getElementById('fileName');
+const editModal = document.getElementById('editModal');
+const deleteModal = document.getElementById('deleteModal');
+const editWarrantyForm = document.getElementById('editWarrantyForm');
+const saveWarrantyBtn = document.getElementById('saveWarrantyBtn');
+const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
+const loadingContainer = document.getElementById('loadingContainer');
+const toastContainer = document.getElementById('toastContainer');
+
+// Variables
+let warranties = [];
+let currentWarrantyId = null;
+
+// API URL
+const API_URL = 'http://localhost:5000/api/warranties';
+
+// Event Listeners
+document.addEventListener('DOMContentLoaded', () => {
+ loadWarranties();
+
+ // Close modals when clicking outside or on close button
+ document.querySelectorAll('.modal-backdrop, [data-dismiss="modal"]').forEach(element => {
+ element.addEventListener('click', (e) => {
+ if (e.target === element) {
+ closeModals();
+ }
+ });
+ });
+
+ // Prevent modal content clicks from closing the modal
+ document.querySelectorAll('.modal').forEach(modal => {
+ modal.addEventListener('click', (e) => {
+ e.stopPropagation();
+ });
+ });
+});
+
+// File input change event
+fileInput.addEventListener('change', updateFileName);
+document.getElementById('editInvoice').addEventListener('change', () => {
+ updateFileName(null, 'editInvoice', 'editFileName');
+});
+
+// Form submission
+warrantyForm.addEventListener('submit', addWarranty);
+
+// Refresh button
+refreshBtn.addEventListener('click', loadWarranties);
+
+// Search input
+searchInput.addEventListener('input', filterWarranties);
+
+// Save warranty changes
+saveWarrantyBtn.addEventListener('click', updateWarranty);
+
+// Confirm delete button
+confirmDeleteBtn.addEventListener('click', deleteWarranty);
+
+// Functions
+function showLoading() {
+ loadingContainer.classList.add('active');
+}
+
+function hideLoading() {
+ loadingContainer.classList.remove('active');
+}
+
+function showToast(message, type = 'info') {
+ const toast = document.createElement('div');
+ toast.className = `toast toast-${type}`;
+ toast.innerHTML = `
+ ${message}
+ <button class="toast-close">&times;</button>
+ `;
+
+ // Add close event
+ toast.querySelector('.toast-close').addEventListener('click', () => {
+ toast.remove();
+ });
+
+ toastContainer.appendChild(toast);
+
+ // Auto remove after 3 seconds
+ setTimeout(() => {
+ if (toast.parentElement) {
+ toast.remove();
+ }
+ }, 3000);
+}
+
+function updateFileName(event, inputId = 'invoice', outputId = 'fileName') {
+ const input = document.getElementById(inputId);
+ const output = document.getElementById(outputId);
+
+ if (input.files.length > 0) {
+ output.textContent = input.files[0].name;
+ } else {
+ output.textContent = '';
+ }
+}
+
+async function loadWarranties() {
+ showLoading();
+
+ try {
+ const response = await fetch(API_URL);
+ if (!response.ok) {
+ throw new Error('Failed to load warranties');
+ }
+
+ warranties = await response.json();
+ renderWarranties();
+ } catch (error) {
+ showToast(error.message, 'error');
+ console.error('Error loading warranties:', error);
+ renderEmptyState('Could not load warranties. Please try again.');
+ } finally {
+ hideLoading();
+ }
+}
+
+function renderEmptyState(message = 'No warranties yet. Add your first warranty to get started.') {
+ warrantiesList.innerHTML = `
+ <div class="empty-state">
+ <i class="fas fa-box-open"></i>
+ <h3>No warranties found</h3>
+ <p>${message}</p>
+ </div>
+ `;
+}
+
+function renderWarranties(filteredWarranties = null) {
+ const warrantiesToRender = filteredWarranties || warranties;
+
+ if (warrantiesToRender.length === 0) {
+ renderEmptyState();
+ return;
+ }
+
+ const today = new Date();
+
+ warrantiesList.innerHTML = '';
+
+ // Sort warranties: expiring soon first, then active, then expired
+ warrantiesToRender.sort((a, b) => {
+ const dateA = new Date(a.expiration_date);
+ const dateB = new Date(b.expiration_date);
+
+ const isExpiredA = dateA < today;
+ const isExpiredB = dateB < today;
+
+ if (isExpiredA && !isExpiredB) return 1;
+ if (!isExpiredA && isExpiredB) return -1;
+
+ // Both active or both expired, sort by date
+ return dateA - dateB;
+ });
+
+ warrantiesToRender.forEach(warranty => {
+ const purchaseDate = new Date(warranty.purchase_date);
+ const expirationDate = new Date(warranty.expiration_date);
+ const daysRemaining = Math.floor((expirationDate - today) / (1000 * 60 * 60 * 24));
+
+ let statusClass = 'active';
+ let statusText = 'Active';
+
+ if (daysRemaining < 0) {
+ statusClass = 'expired';
+ statusText = 'Expired';
+ } else if (daysRemaining < 30) {
+ statusClass = 'expiring';
+ statusText = `Expiring Soon (${daysRemaining} days)`;
+ } else {
+ statusText = `${daysRemaining} days remaining`;
+ }
+
+ const cardElement = document.createElement('div');
+ cardElement.className = `warranty-card ${statusClass === 'expired' ? 'expired' : statusClass === 'expiring' ? 'expiring-soon' : ''}`;
+ cardElement.innerHTML = `
+ <div class="warranty-header">
+ <h3 class="warranty-title">${warranty.product_name}</h3>
+ <div class="warranty-actions">
+ <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
+ <i class="fas fa-edit"></i>
+<button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
+ <i class="fas fa-edit"></i>
+ </button>
+ <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">
+ <i class="fas fa-trash"></i>
+ </button>
+ </div>
+ </div>
+ <div class="warranty-details">
+ <div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
+ <div>Warranty: <span>${warranty.warranty_years} ${warranty.warranty_years > 1 ? 'years' : 'year'}</span></div>
+ <div>Expires: <span>${formatDate(expirationDate)}</span></div>
+ <span class="warranty-status status-${statusClass}">${statusText}</span>
+ ${warranty.invoice_path ? `
+ <div>
+ <a href="${warranty.invoice_path}" class="invoice-link" target="_blank">
+ <i class="fas fa-file-invoice"></i> View Invoice
+ </a>
+ </div>
+ ` : ''}
+ </div>
+ `;
+
+ // Add event listeners
+ warrantiesList.appendChild(cardElement);
+
+ // Edit button event listener
+ cardElement.querySelector('.edit-btn').addEventListener('click', () => {
+ openEditModal(warranty);
+ });
+
+ // Delete button event listener
+ cardElement.querySelector('.delete-btn').addEventListener('click', () => {
+ openDeleteModal(warranty.id);
+ });
+ });
+}
+
+function filterWarranties() {
+ const searchTerm = searchInput.value.toLowerCase();
+
+ if (!searchTerm) {
+ renderWarranties();
+ return;
+ }
+
+ const filtered = warranties.filter(warranty =>
+ warranty.product_name.toLowerCase().includes(searchTerm)
+ );
+
+ renderWarranties(filtered);
+}
+
+function formatDate(date) {
+ return new Date(date).toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric'
+ });
+}
+
+async function addWarranty(event) {
+ event.preventDefault();
+ showLoading();
+
+ const formData = new FormData(warrantyForm);
+
+ try {
+ const response = await fetch(API_URL, {
+ method: 'POST',
+ body: formData
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to add warranty');
+ }
+
+ const result = await response.json();
+ showToast('Warranty added successfully!', 'success');
+
+ // Reset form
+ warrantyForm.reset();
+ fileName.textContent = '';
+
+ // Reload warranties
+ loadWarranties();
+ } catch (error) {
+ showToast(error.message, 'error');
+ console.error('Error adding warranty:', error);
+ } finally {
+ hideLoading();
+ }
+}
+
+function openEditModal(warranty) {
+ currentWarrantyId = warranty.id;
+
+ // Populate form fields
+ document.getElementById('editWarrantyId').value = warranty.id;
+ document.getElementById('editProductName').value = warranty.product_name;
+ document.getElementById('editPurchaseDate').value = new Date(warranty.purchase_date).toISOString().split('T')[0];
+ document.getElementById('editWarrantyYears').value = warranty.warranty_years;
+
+ // Show current invoice if exists
+ const currentInvoiceElement = document.getElementById('currentInvoice');
+ if (warranty.invoice_path) {
+ currentInvoiceElement.innerHTML = `
+ <span class="text-success">
+ <i class="fas fa-check-circle"></i> Current invoice:
+ <a href="${warranty.invoice_path}" target="_blank">View</a>
+ (Upload a new file to replace)
+ </span>
+ `;
+ } else {
+ currentInvoiceElement.innerHTML = '<span>No invoice uploaded</span>';
+ }
+
+ // Reset file input display
+ document.getElementById('editFileName').textContent = '';
+
+ // Show modal
+ editModal.classList.add('active');
+}
+
+function openDeleteModal(warrantyId) {
+ currentWarrantyId = warrantyId;
+ deleteModal.classList.add('active');
+}
+
+function closeModals() {
+ editModal.classList.remove('active');
+ deleteModal.classList.remove('active');
+ currentWarrantyId = null;
+}
+
+async function updateWarranty() {
+ if (!currentWarrantyId) return;
+
+ showLoading();
+
+ const formData = new FormData(editWarrantyForm);
+
+ try {
+ const response = await fetch(`${API_URL}/${currentWarrantyId}`, {
+ method: 'PUT',
+ body: formData
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to update warranty');
+ }
+
+ showToast('Warranty updated successfully!', 'success');
+ closeModals();
+ loadWarranties();
+ } catch (error) {
+ showToast(error.message, 'error');
+ console.error('Error updating warranty:', error);
+ } finally {
+ hideLoading();
+ }
+}
+
+async function deleteWarranty() {
+ if (!currentWarrantyId) return;
+
+ showLoading();
+
+ try {
+ const response = await fetch(`${API_URL}/${currentWarrantyId}`, {
+ method: 'DELETE'
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to delete warranty');
+ }
+
+ showToast('Warranty deleted successfully!', 'success');
+ closeModals();
+ loadWarranties();
+ } catch (error) {
+ showToast(error.message, 'error');
+ console.error('Error deleting warranty:', error);
+ } finally {
+ hideLoading();
+ }
+}
\ No newline at end of file
diff --git a/frontend/style.css b/frontend/style.css
new file mode 100644
index 0000000..5d04ce1
--- /dev/null
+++ b/frontend/style.css
@@ -0,0 +1,656 @@
+/* ===== GLOBAL STYLES ===== */
+:root {
+ --primary-color: #3498db;
+ --primary-dark: #2980b9;
+ --secondary-color: #2ecc71;
+ --danger-color: #e74c3c;
+ --text-color: #333333;
+ --light-gray: #f5f5f5;
+ --medium-gray: #e0e0e0;
+ --dark-gray: #777777;
+ --white: #ffffff;
+ --shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
+ --border-radius: 8px;
+ --transition: all 0.3s ease;
+}
+
+* {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+}
+
+body {
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
+ line-height: 1.6;
+ color: var(--text-color);
+ background-color: var(--light-gray);
+ padding: 0;
+ margin: 0;
+}
+
+.container {
+ max-width: 1200px;
+ margin: 0 auto;
+ padding: 20px;
+}
+
+/* ===== HEADER ===== */
+header {
+ background-color: var(--white);
+ box-shadow: var(--shadow);
+ padding: 20px 0;
+ margin-bottom: 30px;
+}
+
+.app-title {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.app-title h1 {
+ color: var(--primary-color);
+ font-size: 2.2rem;
+ margin: 0;
+}
+
+.app-title i {
+ font-size: 2rem;
+ margin-right: 15px;
+ color: var(--primary-color);
+}
+
+/* ===== MAIN CONTENT ===== */
+.main-content {
+ display: grid;
+ grid-template-columns: 1fr 2fr;
+ gap: 30px;
+}
+
+@media (max-width: 768px) {
+ .main-content {
+ grid-template-columns: 1fr;
+ }
+}
+
+/* ===== FORM PANEL ===== */
+.form-panel {
+ background-color: var(--white);
+ border-radius: var(--border-radius);
+ box-shadow: var(--shadow);
+ padding: 25px;
+}
+
+.form-panel h2 {
+ color: var(--primary-color);
+ margin-bottom: 20px;
+ font-size: 1.5rem;
+ border-bottom: 2px solid var(--medium-gray);
+ padding-bottom: 10px;
+}
+
+.form-group {
+ margin-bottom: 20px;
+}
+
+.form-group label {
+ display: block;
+ margin-bottom: 8px;
+ font-weight: 500;
+ color: var(--text-color);
+}
+
+.form-control {
+ width: 100%;
+ padding: 12px;
+ border: 1px solid var(--medium-gray);
+ border-radius: var(--border-radius);
+ font-size: 1rem;
+ transition: var(--transition);
+}
+
+.form-control:focus {
+ outline: none;
+ border-color: var(--primary-color);
+ box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.25);
+}
+
+.file-input-wrapper {
+ position: relative;
+ overflow: hidden;
+ display: inline-block;
+ width: 100%;
+}
+
+.file-input-label {
+ display: block;
+ background-color: var(--primary-color);
+ color: var(--white);
+ text-align: center;
+ padding: 12px;
+ border-radius: var(--border-radius);
+ cursor: pointer;
+ transition: var(--transition);
+}
+
+.file-input-label:hover {
+ background-color: var(--primary-dark);
+}
+
+.file-input-label i {
+ margin-right: 8px;
+}
+
+.file-input {
+ position: absolute;
+ font-size: 100px;
+ opacity: 0;
+ right: 0;
+ top: 0;
+ cursor: pointer;
+}
+
+.file-name {
+ margin-top: 8px;
+ font-size: 0.9rem;
+ color: var(--dark-gray);
+ word-break: break-all;
+}
+
+.btn {
+ display: inline-block;
+ font-weight: 500;
+ text-align: center;
+ white-space: nowrap;
+ vertical-align: middle;
+ user-select: none;
+ border: none;
+ padding: 12px 25px;
+ font-size: 1rem;
+ line-height: 1.5;
+ border-radius: var(--border-radius);
+ transition: var(--transition);
+ cursor: pointer;
+ width: 100%;
+}
+
+.btn-primary {
+ color: var(--white);
+ background-color: var(--primary-color);
+}
+
+.btn-primary:hover {
+ background-color: var(--primary-dark);
+}
+
+.btn-secondary {
+ color: var(--white);
+ background-color: var(--secondary-color);
+}
+
+.btn-secondary:hover {
+ background-color: #27ae60;
+}
+
+.btn-danger {
+ color: var(--white);
+ background-color: var(--danger-color);
+}
+
+.btn-danger:hover {
+ background-color: #c0392b;
+}
+
+/* ===== WARRANTIES LIST ===== */
+.warranties-panel {
+ background-color: var(--white);
+ border-radius: var(--border-radius);
+ box-shadow: var(--shadow);
+ padding: 25px;
+}
+
+.warranties-panel h2 {
+ color: var(--primary-color);
+ margin-bottom: 20px;
+ font-size: 1.5rem;
+ border-bottom: 2px solid var(--medium-gray);
+ padding-bottom: 10px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.refresh-btn {
+ background: none;
+ border: none;
+ color: var(--primary-color);
+ cursor: pointer;
+ font-size: 1.2rem;
+ transition: var(--transition);
+}
+
+.refresh-btn:hover {
+ transform: rotate(90deg);
+}
+
+.search-box {
+ margin-bottom: 20px;
+ position: relative;
+}
+
+.search-box input {
+ width: 100%;
+ padding: 12px 15px 12px 40px;
+ border: 1px solid var(--medium-gray);
+ border-radius: var(--border-radius);
+ font-size: 1rem;
+ transition: var(--transition);
+}
+
+.search-box input:focus {
+ outline: none;
+ border-color: var(--primary-color);
+ box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.25);
+}
+
+.search-box i {
+ position: absolute;
+ left: 15px;
+ top: 50%;
+ transform: translateY(-50%);
+ color: var(--dark-gray);
+}
+
+.warranties-list {
+ max-height: 600px;
+ overflow-y: auto;
+}
+
+.warranty-card {
+ background-color: var(--white);
+ border-radius: var(--border-radius);
+ box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
+ padding: 15px;
+ margin-bottom: 15px;
+ transition: var(--transition);
+ border-left: 4px solid var(--primary-color);
+ position: relative;
+}
+
+.warranty-card:hover {
+ box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
+ transform: translateY(-2px);
+}
+
+.warranty-card.expired {
+ border-left-color: var(--danger-color);
+}
+
+.warranty-card.expiring-soon {
+ border-left-color: #f39c12;
+}
+
+.warranty-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-start;
+ margin-bottom: 10px;
+}
+
+.warranty-title {
+ font-size: 1.2rem;
+ font-weight: 600;
+ color: var(--text-color);
+ margin: 0;
+}
+
+.warranty-actions {
+ display: flex;
+ gap: 10px;
+}
+
+.action-btn {
+ background: none;
+ border: none;
+ font-size: 1rem;
+ cursor: pointer;
+ color: var(--dark-gray);
+ transition: var(--transition);
+}
+
+.edit-btn:hover {
+ color: var(--primary-color);
+}
+
+.delete-btn:hover {
+ color: var(--danger-color);
+}
+
+.warranty-details {
+ color: var(--dark-gray);
+ font-size: 0.9rem;
+}
+
+.warranty-details div {
+ margin-bottom: 5px;
+}
+
+.warranty-details span {
+ font-weight: 500;
+ color: var(--text-color);
+}
+
+.warranty-status {
+ display: inline-block;
+ padding: 3px 10px;
+ border-radius: 20px;
+ font-size: 0.75rem;
+ font-weight: 500;
+ margin-top: 10px;
+}
+
+.status-active {
+ background-color: rgba(46, 204, 113, 0.15);
+ color: #27ae60;
+}
+
+.status-expired {
+ background-color: rgba(231, 76, 60, 0.15);
+ color: #c0392b;
+}
+
+.status-expiring {
+ background-color: rgba(243, 156, 18, 0.15);
+ color: #d35400;
+}
+
+.invoice-link {
+ display: inline-flex;
+ align-items: center;
+ color: var(--primary-color);
+ text-decoration: none;
+ font-weight: 500;
+ margin-top: 10px;
+ transition: var(--transition);
+}
+
+.invoice-link i {
+ margin-right: 5px;
+}
+
+.invoice-link:hover {
+ color: var(--primary-dark);
+ text-decoration: underline;
+}
+
+/* ===== MODAL ===== */
+.modal-backdrop {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: rgba(0, 0, 0, 0.5);
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ z-index: 1000;
+ opacity: 0;
+ visibility: hidden;
+ transition: var(--transition);
+}
+
+.modal-backdrop.active {
+ opacity: 1;
+ visibility: visible;
+}
+
+.modal {
+ background-color: var(--white);
+ border-radius: var(--border-radius);
+ box-shadow: var(--shadow);
+ width: 90%;
+ max-width: 500px;
+ transform: translateY(-20px);
+ transition: var(--transition);
+}
+
+.modal-backdrop.active .modal {
+ transform: translateY(0);
+}
+
+.modal-header {
+ padding: 20px;
+ border-bottom: 1px solid var(--medium-gray);
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.modal-title {
+ font-size: 1.2rem;
+ color: var(--text-color);
+ margin: 0;
+}
+
+.close-btn {
+ background: none;
+ border: none;
+ font-size: 1.5rem;
+ line-height: 1;
+ cursor: pointer;
+ color: var(--dark-gray);
+ transition: var(--transition);
+}
+
+.close-btn:hover {
+ color: var(--danger-color);
+}
+
+.modal-body {
+ padding: 20px;
+}
+
+.modal-footer {
+ padding: 15px 20px;
+ border-top: 1px solid var(--medium-gray);
+ display: flex;
+ justify-content: flex-end;
+ gap: 10px;
+}
+
+.modal-footer .btn {
+ width: auto;
+}
+
+/* ===== TOAST NOTIFICATIONS ===== */
+.toast-container {
+ position: fixed;
+ top: 20px;
+ right: 20px;
+ z-index: 1001;
+}
+
+.toast {
+ min-width: 250px;
+ margin-bottom: 10px;
+ padding: 15px 20px;
+ border-radius: var(--border-radius);
+ box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ animation: slide-in 0.3s ease, fade-out 0.3s ease 2.7s forwards;
+}
+
+@keyframes slide-in {
+ from { transform: translateX(100%); opacity: 0; }
+ to { transform: translateX(0); opacity: 1; }
+}
+
+@keyframes fade-out {
+ from { opacity: 1; }
+ to { opacity: 0; }
+}
+
+.toast-success {
+ background-color: var(--secondary-color);
+ color: var(--white);
+}
+
+.toast-error {
+ background-color: var(--danger-color);
+ color: var(--white);
+}
+
+.toast-warning {
+ background-color: #f39c12;
+ color: var(--white);
+}
+
+.toast-info {
+ background-color: var(--primary-color);
+ color: var(--white);
+}
+
+.toast-close {
+ background: none;
+ border: none;
+ color: var(--white);
+ opacity: 0.7;
+ cursor: pointer;
+ font-size: 1.2rem;
+ transition: var(--transition);
+}
+
+.toast-close:hover {
+ opacity: 1;
+}
+
+/* ===== LOADING SPINNER ===== */
+.loading-spinner {
+ display: inline-block;
+ position: relative;
+ width: 80px;
+ height: 80px;
+}
+
+.loading-spinner:after {
+ content: " ";
+ display: block;
+ border-radius: 50%;
+ width: 0;
+ height: 0;
+ margin: 8px;
+ box-sizing: border-box;
+ border: 32px solid var(--primary-color);
+ border-color: var(--primary-color) transparent var(--primary-color) transparent;
+ animation: loading-spinner 1.2s infinite;
+}
+
+@keyframes loading-spinner {
+ 0% { transform: rotate(0); animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); }
+ 50% { transform: rotate(180deg); animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); }
+ 100% { transform: rotate(360deg); }
+}
+
+.loading-container {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width
+.loading-container {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: rgba(255, 255, 255, 0.8);
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ z-index: 1002;
+ opacity: 0;
+ visibility: hidden;
+ transition: var(--transition);
+}
+
+.loading-container.active {
+ opacity: 1;
+ visibility: visible;
+}
+
+/* ===== EMPTY STATE ===== */
+.empty-state {
+ text-align: center;
+ padding: 40px 20px;
+ color: var(--dark-gray);
+}
+
+.empty-state i {
+ font-size: 3rem;
+ margin-bottom: 15px;
+ opacity: 0.3;
+}
+
+.empty-state h3 {
+ font-size: 1.2rem;
+ margin-bottom: 10px;
+}
+
+.empty-state p {
+ font-size: 0.9rem;
+}
+
+/* ===== RESPONSIVE ADJUSTMENTS ===== */
+@media (max-width: 768px) {
+ .main-content {
+ grid-template-columns: 1fr;
+ }
+
+ .form-panel, .warranties-panel {
+ margin-bottom: 20px;
+ }
+
+ .warranty-header {
+ flex-direction: column;
+ }
+
+ .warranty-actions {
+ margin-top: 10px;
+ }
+}
+
+/* ===== UTILITIES ===== */
+.text-danger {
+ color: var(--danger-color);
+}
+
+.text-warning {
+ color: #f39c12;
+}
+
+.text-success {
+ color: var(--secondary-color);
+}
+
+.text-center {
+ text-align: center;
+}
+
+.mt-10 {
+ margin-top: 10px;
+}
+
+.mt-20 {
+ margin-top: 20px;
+}
+
+.mb-10 {
+ margin-bottom: 10px;
+}
+
+.mb-20 {
+ margin-bottom: 20px;
+}
\ No newline at end of file
diff --git a/nginx.conf b/nginx.conf
new file mode 100644
index 0000000..d034c90
--- /dev/null
+++ b/nginx.conf
@@ -0,0 +1,48 @@
+server {
+ listen 80;
+ server_name localhost;
+ root /usr/share/nginx/html;
+ index index.html;
+
+ # Enable gzip compression
+ gzip on;
+ gzip_types text/plain text/css application/javascript application/json;
+
+ # Add CORS headers
+ add_header 'Access-Control-Allow-Origin' '*';
+ add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
+ add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
+
+ location / {
+ try_files $uri $uri/ /index.html;
+ }
+
+ # Proxy API requests to backend
+ location /api/ {
+ proxy_pass http://backend:5000;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ }
+
+ # Proxy uploads to backend
+ location /uploads/ {
+ proxy_pass http://backend:5000;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ }
+
+ # Cache static assets
+ location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg)$ {
+ expires 7d;
+ add_header Cache-Control "public, max-age=604800";
+ }
+
+ # Error handling
+ error_page 404 /index.html;
+ error_page 500 502 503 504 /50x.html;
+ location = /50x.html {
+ root /usr/share/nginx/html;
+ }
+}
\ No newline at end of file