Skip to content

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

Status page added

sassanix8f62a166a686
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f9a8273..471a6d6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,38 @@
# Changelog
-## [0.05.2-beta] - 2024-03-05
+## [0.2.0] - 2025-03-06
+
+### Added
+- Export functionality for warranty data as CSV
+- Refresh button for manual data updates
+- Search and filtering options for warranty list
+- Enhanced mobile responsiveness
+
+### Changed
+- Removed Debug Information panel from status page
+- Improved error handling and data validation across all dashboard functions
+- Enhanced chart creation with support for various data formats
+- Streamlined user interface by removing development elements
+- Improved data normalization for warranty information
+- Added fallback mechanisms for missing or invalid data
+- Updated status chart calculations for better accuracy
+
+### Fixed
+- API connection error handling
+- Chart instance memory leaks
+- Invalid data structure handling from API responses
+- Negative value calculations in status charts
+
+## [0.1.0] - New Features and enhancements
+
+### Added
+- Basic warranty tracking functionality
+- Dashboard with warranty statistics
+- Timeline visualization
+- Status overview chart
+- Recent expirations list
+
+## [0.05.2-beta] - 2025-03-05
### Added
- Multiple serial numbers support for warranties
diff --git a/Dockerfile b/Dockerfile
index 0b04b29..43dcb03 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -22,15 +22,17 @@ COPY backend/app.py .
RUN mkdir -p /data/uploads && chmod 777 /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/
+COPY frontend/*.html /var/www/html/
+COPY frontend/*.js /var/www/html/
+COPY frontend/*.css /var/www/html/
COPY test.html /var/www/html/
# Configure nginx
RUN rm /etc/nginx/sites-enabled/default
COPY nginx.conf /etc/nginx/conf.d/default.conf
+# Add MIME type configuration - this is now included in nginx.conf
+
# Create startup script with directory permission check
RUN echo '#!/bin/bash\n\
echo "Checking /data/uploads directory:"\n\
diff --git a/backend/app.py b/backend/app.py
index 2ebd860..874d3da 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -395,6 +395,121 @@ def uploaded_file(filename):
def request_entity_too_large(error):
return jsonify({"error": "File too large. Maximum size is 16MB"}), 413
[email protected]('/api/statistics', methods=['GET'])
+def get_statistics():
+ conn = None
+ cursor = None
+ try:
+ logger.info("Statistics endpoint called")
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # Calculate expiration ranges
+ today = date.today()
+ logger.info(f"Current date: {today}")
+ thirty_days_later = today + timedelta(days=30)
+ ninety_days_later = today + timedelta(days=90)
+
+ # Get total count
+ cursor.execute("SELECT COUNT(*) FROM warranties")
+ total_count = cursor.fetchone()[0]
+ logger.info(f"Total warranties: {total_count}")
+
+ # Get active count
+ cursor.execute("SELECT COUNT(*) FROM warranties WHERE expiration_date > %s", (today,))
+ active_count = cursor.fetchone()[0]
+ logger.info(f"Active warranties: {active_count}")
+
+ # Get expired count
+ cursor.execute("SELECT COUNT(*) FROM warranties WHERE expiration_date <= %s", (today,))
+ expired_count = cursor.fetchone()[0]
+ logger.info(f"Expired warranties: {expired_count}")
+
+ # Get expiring soon count (30 days)
+ cursor.execute("SELECT COUNT(*) FROM warranties WHERE expiration_date > %s AND expiration_date <= %s",
+ (today, thirty_days_later))
+ expiring_soon_count = cursor.fetchone()[0]
+ logger.info(f"Expiring soon warranties: {expiring_soon_count}")
+
+ # Get expiration timeline (next 90 days, grouped by month)
+ cursor.execute("""
+ SELECT
+ EXTRACT(YEAR FROM expiration_date) as year,
+ EXTRACT(MONTH FROM expiration_date) as month,
+ COUNT(*) as count
+ FROM warranties
+ WHERE expiration_date > %s AND expiration_date <= %s
+ GROUP BY EXTRACT(YEAR FROM expiration_date), EXTRACT(MONTH FROM expiration_date)
+ ORDER BY year, month
+ """, (today, ninety_days_later))
+
+ timeline = []
+ for row in cursor.fetchall():
+ year = int(row[0])
+ month = int(row[1])
+ count = row[2]
+ timeline.append({
+ "year": year,
+ "month": month,
+ "count": count
+ })
+
+ # Get recent expiring warranties (30 days before and after today)
+ thirty_days_ago = today - timedelta(days=30)
+ cursor.execute("""
+ SELECT
+ id, product_name, purchase_date, warranty_years,
+ expiration_date, invoice_path
+ FROM warranties
+ WHERE expiration_date >= %s AND expiration_date <= %s
+ ORDER BY expiration_date
+ LIMIT 10
+ """, (thirty_days_ago, thirty_days_later))
+
+ columns = [desc[0] for desc in cursor.description]
+ recent_warranties = []
+
+ for row in cursor.fetchall():
+ warranty = dict(zip(columns, row))
+
+ # Convert dates to string format
+ if warranty['purchase_date']:
+ warranty['purchase_date'] = warranty['purchase_date'].isoformat()
+ if warranty['expiration_date']:
+ warranty['expiration_date'] = warranty['expiration_date'].isoformat()
+
+ recent_warranties.append(warranty)
+
+ statistics = {
+ 'total': total_count,
+ 'active': active_count,
+ 'expired': expired_count,
+ 'expiring_soon': expiring_soon_count,
+ 'timeline': timeline,
+ 'recent_warranties': recent_warranties
+ }
+
+ return jsonify(statistics)
+
+ except Exception as e:
+ logger.error(f"Error getting warranty statistics: {e}")
+ return jsonify({"error": str(e)}), 500
+
+ finally:
+ if cursor and cursor.closed is False:
+ cursor.close()
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/test', methods=['GET'])
+def test_endpoint():
+ """Simple test endpoint to check if the API is responding."""
+ return jsonify({
+ "status": "success",
+ "message": "API is responding correctly",
+ "timestamp": datetime.now().isoformat()
+ })
+
if __name__ == '__main__':
try:
init_db()
diff --git a/frontend/api-test.html b/frontend/api-test.html
new file mode 100644
index 0000000..25252eb
--- /dev/null
+++ b/frontend/api-test.html
@@ -0,0 +1,147 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>API Test Page</title>
+ <link rel="stylesheet" href="style.css">
+ <style>
+ body {
+ font-family: Arial, sans-serif;
+ padding: 20px;
+ }
+ h1, h2 {
+ color: #333;
+ }
+ .test-container {
+ margin-bottom: 30px;
+ padding: 20px;
+ background-color: #f9f9f9;
+ border-radius: 8px;
+ box-shadow: 0 2px 5px rgba(0,0,0,0.1);
+ }
+ button {
+ padding: 10px 15px;
+ background-color: #4CAF50;
+ color: white;
+ border: none;
+ border-radius: 4px;
+ cursor: pointer;
+ margin-right: 10px;
+ margin-bottom: 10px;
+ }
+ button:hover {
+ background-color: #45a049;
+ }
+ pre {
+ background-color: #f5f5f5;
+ padding: 15px;
+ border-radius: 4px;
+ overflow-x: auto;
+ margin-top: 10px;
+ }
+ .success {
+ color: #4CAF50;
+ font-weight: bold;
+ }
+ .error {
+ color: #F44336;
+ font-weight: bold;
+ }
+ .navbar {
+ display: flex;
+ gap: 10px;
+ margin-bottom: 20px;
+ }
+ .navbar a {
+ padding: 10px 15px;
+ background-color: #3498db;
+ color: white;
+ text-decoration: none;
+ border-radius: 4px;
+ }
+ </style>
+</head>
+<body>
+ <div class="navbar">
+ <a href="index.html">Home</a>
+ <a href="status.html">Status Page</a>
+ <a href="simple-status.html">Simple Test</a>
+ <a href="status-simple.html">Chart Test</a>
+ <a href="api-test.html" style="background-color: #2980b9;">API Test</a>
+ <a href="page-test.html">Page Test</a>
+ </div>
+
+ <h1>API Test Page</h1>
+ <p>Use this page to test various API endpoints and see if they're responding correctly.</p>
+
+ <div class="test-container">
+ <h2>Test Simple API Endpoint</h2>
+ <button id="testSimpleBtn">Test /api/test</button>
+ <pre id="testSimpleResults">Results will appear here</pre>
+ </div>
+
+ <div class="test-container">
+ <h2>Test Warranties API Endpoint</h2>
+ <button id="testWarrantiesBtn">Test /api/warranties</button>
+ <pre id="testWarrantiesResults">Results will appear here</pre>
+ </div>
+
+ <div class="test-container">
+ <h2>Test Statistics API Endpoint</h2>
+ <button id="testStatisticsBtn">Test /api/statistics</button>
+ <pre id="testStatisticsResults">Results will appear here</pre>
+ </div>
+
+ <script>
+ // Helper function to handle API calls
+ async function callApi(url, resultsElement) {
+ resultsElement.textContent = 'Testing...';
+ resultsElement.className = '';
+
+ try {
+ console.log(`Testing ${url}...`);
+ const response = await fetch(url, {
+ method: 'GET',
+ headers: {
+ 'Accept': 'application/json'
+ }
+ });
+
+ let responseText;
+ const contentType = response.headers.get('content-type');
+ if (contentType && contentType.includes('application/json')) {
+ responseText = JSON.stringify(await response.json(), null, 2);
+ } else {
+ responseText = await response.text();
+ }
+
+ if (!response.ok) {
+ throw new Error(`HTTP Error: ${response.status} - ${responseText}`);
+ }
+
+ resultsElement.innerHTML = `<span class="success">SUCCESS (${response.status})</span>\n\n${responseText}`;
+
+ } catch (error) {
+ console.error(`API test failed for ${url}:`, error);
+ resultsElement.innerHTML = `<span class="error">ERROR</span>\n\n${error.message}`;
+ }
+ }
+
+ // Test simple endpoint
+ document.getElementById('testSimpleBtn').addEventListener('click', () => {
+ callApi('/api/test', document.getElementById('testSimpleResults'));
+ });
+
+ // Test warranties endpoint
+ document.getElementById('testWarrantiesBtn').addEventListener('click', () => {
+ callApi('/api/warranties', document.getElementById('testWarrantiesResults'));
+ });
+
+ // Test statistics endpoint
+ document.getElementById('testStatisticsBtn').addEventListener('click', () => {
+ callApi('/api/statistics', document.getElementById('testStatisticsResults'));
+ });
+ </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/frontend/copy-html-files.sh b/frontend/copy-html-files.sh
new file mode 100644
index 0000000..ec284c4
--- /dev/null
+++ b/frontend/copy-html-files.sh
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+# This script creates symbolic links for HTML files instead of copies
+# This helps nginx properly recognize the content types
+
+echo "Creating SPA-friendly HTML symlinks..."
+
+# Get all HTML files in the current directory
+HTML_FILES=$(find . -maxdepth 1 -type f -name "*.html")
+
+# Remove existing symlinks first to prevent issues
+find . -maxdepth 1 -type l -delete
+
+# Create symbolic links without .html extension
+for file in $HTML_FILES; do
+ base_name=$(basename "$file" .html)
+ echo "Creating symlink $file -> $base_name"
+
+ # Symbolically link the .html file
+ ln -sf "$file" "$base_name"
+done
+
+echo "Done! Created HTML symlinks for clean URLs."
\ No newline at end of file
diff --git a/frontend/index.html b/frontend/index.html
index 5bdac4b..7611043 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -16,6 +16,14 @@
<i class="fas fa-shield-alt"></i>
<h1>Warranty Tracker</h1>
</div>
+ <div class="nav-links">
+ <a href="index.html" class="nav-link active">
+ <i class="fas fa-home"></i> Home
+ </a>
+ <a href="status.html" class="nav-link">
+ <i class="fas fa-chart-pie"></i> Status
+ </a>
+ </div>
<div class="settings-container">
<button id="settingsBtn" class="settings-btn" aria-label="Settings">
<i class="fas fa-cog"></i>
@@ -28,6 +36,21 @@
<span class="toggle-slider"></span>
</label>
</div>
+ <div class="settings-item">
+ <a href="simple-status.html" class="settings-link">
+ <i class="fas fa-vial"></i> Simple Test
+ </a>
+ </div>
+ <div class="settings-item">
+ <a href="api-test.html" class="settings-link">
+ <i class="fas fa-terminal"></i> API Test
+ </a>
+ </div>
+ <div class="settings-item">
+ <a href="page-test.html" class="settings-link">
+ <i class="fas fa-sitemap"></i> Page Test
+ </a>
+ </div>
</div>
</div>
</div>
diff --git a/frontend/page-test.html b/frontend/page-test.html
new file mode 100644
index 0000000..767d3e4
--- /dev/null
+++ b/frontend/page-test.html
@@ -0,0 +1,160 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Page Navigation Test</title>
+ <style>
+ body {
+ font-family: Arial, sans-serif;
+ max-width: 800px;
+ margin: 0 auto;
+ padding: 20px;
+ }
+ h1 {
+ color: #2c3e50;
+ border-bottom: 2px solid #ecf0f1;
+ padding-bottom: 10px;
+ }
+ .test-links {
+ margin: 20px 0;
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: 15px;
+ }
+ .link-card {
+ border: 1px solid #e0e0e0;
+ border-radius: 5px;
+ padding: 15px;
+ display: flex;
+ flex-direction: column;
+ box-shadow: 0 2px 5px rgba(0,0,0,0.1);
+ }
+ .link-card h3 {
+ margin-top: 0;
+ color: #3498db;
+ }
+ .link-card p {
+ margin-bottom: 15px;
+ flex-grow: 1;
+ }
+ .direct-link, .iframe-test {
+ display: inline-block;
+ padding: 8px 15px;
+ background-color: #3498db;
+ color: white;
+ text-decoration: none;
+ border-radius: 4px;
+ margin-right: 10px;
+ border: none;
+ cursor: pointer;
+ font-size: 14px;
+ }
+ .direct-link:hover, .iframe-test:hover {
+ background-color: #2980b9;
+ }
+ .test-frame {
+ width: 100%;
+ height: 300px;
+ border: 1px solid #e0e0e0;
+ border-radius: 5px;
+ margin-top: 20px;
+ display: none;
+ }
+ .message {
+ padding: 10px;
+ margin: 10px 0;
+ border-radius: 4px;
+ }
+ .success {
+ background-color: #d4edda;
+ color: #155724;
+ border: 1px solid #c3e6cb;
+ }
+ .error {
+ background-color: #f8d7da;
+ color: #721c24;
+ border: 1px solid #f5c6cb;
+ }
+ </style>
+</head>
+<body>
+ <h1>Page Navigation Test</h1>
+ <p>This page helps test if direct navigation to different pages in your application works correctly.</p>
+
+ <div id="message" style="display: none;" class="message"></div>
+
+ <div class="test-links">
+ <div class="link-card">
+ <h3>Home Page</h3>
+ <p>The main dashboard page of the application.</p>
+ <a href="index.html" class="direct-link">Direct Link</a>
+ <button class="iframe-test" data-page="index.html">Test in iframe</button>
+ </div>
+
+ <div class="link-card">
+ <h3>Status Page</h3>
+ <p>The warranty status dashboard.</p>
+ <a href="status.html" class="direct-link">Direct Link</a>
+ <button class="iframe-test" data-page="status.html">Test in iframe</button>
+ </div>
+
+ <div class="link-card">
+ <h3>Simple Status Test</h3>
+ <p>A simplified test page with no JavaScript.</p>
+ <a href="simple-status.html" class="direct-link">Direct Link</a>
+ <button class="iframe-test" data-page="simple-status.html">Test in iframe</button>
+ </div>
+
+ <div class="link-card">
+ <h3>Chart Test Page</h3>
+ <p>A page that tests Chart.js rendering.</p>
+ <a href="status-simple.html" class="direct-link">Direct Link</a>
+ <button class="iframe-test" data-page="status-simple.html">Test in iframe</button>
+ </div>
+
+ <div class="link-card">
+ <h3>API Test Page</h3>
+ <p>A page that tests API endpoints.</p>
+ <a href="api-test.html" class="direct-link">Direct Link</a>
+ <button class="iframe-test" data-page="api-test.html">Test in iframe</button>
+ </div>
+
+ <div class="link-card">
+ <h3>This Test Page</h3>
+ <p>The current page you're viewing.</p>
+ <a href="page-test.html" class="direct-link">Direct Link</a>
+ <button class="iframe-test" data-page="page-test.html">Test in iframe</button>
+ </div>
+ </div>
+
+ <iframe id="testFrame" class="test-frame" title="Test frame"></iframe>
+
+ <script>
+ document.querySelectorAll('.iframe-test').forEach(button => {
+ button.addEventListener('click', function() {
+ const pagePath = this.getAttribute('data-page');
+ const frame = document.getElementById('testFrame');
+ const message = document.getElementById('message');
+
+ // Show the frame
+ frame.style.display = 'block';
+ frame.src = pagePath;
+
+ // Listen for load or error
+ frame.onload = function() {
+ message.className = 'message success';
+ message.textContent = `Success! Page "${pagePath}" loaded correctly in the iframe.`;
+ message.style.display = 'block';
+ };
+
+ frame.onerror = function() {
+ message.className = 'message error';
+ message.textContent = `Error! Page "${pagePath}" failed to load in the iframe.`;
+ message.style.display = 'block';
+ };
+ });
+ });
+ </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/frontend/simple-status.html b/frontend/simple-status.html
new file mode 100644
index 0000000..fc4977e
--- /dev/null
+++ b/frontend/simple-status.html
@@ -0,0 +1,35 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Simple Status Page</title>
+ <style>
+ body {
+ font-family: Arial, sans-serif;
+ text-align: center;
+ padding: 50px;
+ }
+ .success {
+ color: green;
+ font-size: 24px;
+ margin: 20px 0;
+ }
+ a {
+ display: inline-block;
+ padding: 10px 20px;
+ background-color: #4CAF50;
+ color: white;
+ text-decoration: none;
+ border-radius: 4px;
+ margin-top: 20px;
+ }
+ </style>
+</head>
+<body>
+ <h1>Simple Status Page</h1>
+ <p class="success">If you can see this, basic navigation to the status page is working!</p>
+ <p>This is a minimal test page with no JavaScript or external dependencies.</p>
+ <a href="index.html">Back to Home</a>
+</body>
+</html>
\ No newline at end of file
diff --git a/frontend/status-simple.html b/frontend/status-simple.html
new file mode 100644
index 0000000..9cf4b83
--- /dev/null
+++ b/frontend/status-simple.html
@@ -0,0 +1,109 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Simple Status Page with Chart.js</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">
+ <!-- Chart.js for visualizations -->
+ <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
+ <style>
+ .chart-container {
+ width: 400px;
+ height: 400px;
+ margin: 50px auto;
+ }
+ </style>
+</head>
+<body>
+ <!-- Header -->
+ <header>
+ <div class="container">
+ <div class="app-title">
+ <i class="fas fa-shield-alt"></i>
+ <h1>Warranty Tracker</h1>
+ </div>
+ <div class="nav-links">
+ <a href="index.html" class="nav-link">
+ <i class="fas fa-home"></i> Home
+ </a>
+ <a href="status.html" class="nav-link">
+ <i class="fas fa-chart-pie"></i> Status
+ </a>
+ <a href="simple-status.html" class="nav-link">
+ <i class="fas fa-vial"></i> Simple Test
+ </a>
+ <a href="status-simple.html" class="nav-link active">
+ <i class="fas fa-chart-line"></i> Simple Chart
+ </a>
+ <a href="page-test.html" class="nav-link">
+ <i class="fas fa-sitemap"></i> Page Test
+ </a>
+ </div>
+ </div>
+ </header>
+
+ <!-- Main Content -->
+ <div class="container">
+ <div class="status-content">
+ <h2>Simple Chart.js Test</h2>
+
+ <div class="chart-container">
+ <canvas id="sampleChart"></canvas>
+ </div>
+
+ <div style="text-align: center; margin-top: 20px;">
+ <a href="index.html" class="btn btn-primary">Back to Home</a>
+ </div>
+ </div>
+ </div>
+
+ <!-- Footer -->
+ <footer>
+ <div class="container">
+ <p>&copy; 2023 Warracker. All rights reserved.</p>
+ </div>
+ </footer>
+
+ <script>
+ // Create a simple chart when the page loads
+ document.addEventListener('DOMContentLoaded', function() {
+ // Get the canvas element
+ const ctx = document.getElementById('sampleChart').getContext('2d');
+
+ // Sample data
+ const data = {
+ labels: ['Active', 'Expiring Soon', 'Expired'],
+ datasets: [{
+ data: [12, 5, 3],
+ backgroundColor: [
+ '#4CAF50', // Green for active
+ '#FF9800', // Orange for expiring soon
+ '#F44336' // Red for expired
+ ],
+ borderWidth: 1
+ }]
+ };
+
+ // Create and render the chart
+ const myChart = new Chart(ctx, {
+ type: 'doughnut',
+ data: data,
+ options: {
+ responsive: true,
+ maintainAspectRatio: false,
+ plugins: {
+ legend: {
+ position: 'bottom'
+ }
+ }
+ }
+ });
+
+ console.log('Chart rendered successfully!');
+ });
+ </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/frontend/status-test.html b/frontend/status-test.html
new file mode 100644
index 0000000..938fa6d
--- /dev/null
+++ b/frontend/status-test.html
@@ -0,0 +1,79 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Status API Test</title>
+ <style>
+ body {
+ font-family: Arial, sans-serif;
+ line-height: 1.6;
+ padding: 20px;
+ max-width: 800px;
+ margin: 0 auto;
+ }
+ pre {
+ background-color: #f5f5f5;
+ padding: 10px;
+ border-radius: 5px;
+ overflow-x: auto;
+ }
+ button {
+ padding: 10px 15px;
+ background-color: #4CAF50;
+ color: white;
+ border: none;
+ border-radius: 4px;
+ cursor: pointer;
+ margin: 10px 0;
+ }
+ .error {
+ color: #F44336;
+ font-weight: bold;
+ }
+ </style>
+</head>
+<body>
+ <h1>Status API Test</h1>
+ <p>This page tests if the statistics API endpoint is working correctly.</p>
+
+ <button id="testBtn">Test Statistics API</button>
+
+ <h2>Results:</h2>
+ <pre id="results">Click the button to test the API</pre>
+
+ <script>
+ document.getElementById('testBtn').addEventListener('click', async () => {
+ const resultsElement = document.getElementById('results');
+ resultsElement.textContent = 'Testing...';
+
+ try {
+ // Test with fetch API
+ console.log('Testing /api/statistics endpoint...');
+ const response = await fetch('/api/statistics');
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`HTTP Error: ${response.status} - ${errorText}`);
+ }
+
+ const data = await response.json();
+
+ // Display results
+ resultsElement.textContent = 'SUCCESS! Statistics API returned:\n\n' +
+ JSON.stringify(data, null, 2);
+
+ // Create a direct link to main status page
+ const linkElement = document.createElement('p');
+ linkElement.innerHTML = '<a href="status.html">Go to Status Dashboard</a>';
+ document.body.appendChild(linkElement);
+
+ } catch (error) {
+ console.error('API test failed:', error);
+ resultsElement.innerHTML = `<span class="error">ERROR: ${error.message}</span>\n\n` +
+ 'Check browser console for more details.';
+ }
+ });
+ </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/frontend/status.html b/frontend/status.html
new file mode 100644
index 0000000..3839d08
--- /dev/null
+++ b/frontend/status.html
@@ -0,0 +1,195 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Warranty Status Dashboard</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">
+ <!-- Chart.js for visualizations -->
+ <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
+</head>
+<body>
+ <!-- Header -->
+ <header>
+ <div class="container">
+ <div class="app-title">
+ <i class="fas fa-shield-alt"></i>
+ <h1>Warranty Tracker</h1>
+ </div>
+ <div class="nav-links">
+ <a href="index.html" class="nav-link">
+ <i class="fas fa-home"></i> Home
+ </a>
+ <a href="status.html" class="nav-link active">
+ <i class="fas fa-chart-pie"></i> Status
+ </a>
+ </div>
+ <div class="settings-container">
+ <button id="settingsBtn" class="settings-btn" aria-label="Settings">
+ <i class="fas fa-cog"></i>
+ </button>
+ <div id="settingsMenu" class="settings-menu">
+ <div class="settings-item">
+ <span>Dark Mode</span>
+ <label class="toggle-switch" title="Toggle dark mode">
+ <input type="checkbox" id="darkModeToggle">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ <div class="settings-item">
+ <a href="simple-status.html" class="settings-link">
+ <i class="fas fa-vial"></i> Simple Test
+ </a>
+ </div>
+ <div class="settings-item">
+ <a href="api-test.html" class="settings-link">
+ <i class="fas fa-terminal"></i> API Test
+ </a>
+ </div>
+ <div class="settings-item">
+ <a href="page-test.html" class="settings-link">
+ <i class="fas fa-sitemap"></i> Page Test
+ </a>
+ </div>
+ </div>
+ </div>
+ </div>
+ </header>
+
+ <!-- Main Content -->
+ <div class="container">
+ <div class="status-content">
+ <div class="dashboard-header">
+ <h2>Warranty Status Dashboard</h2>
+ <button id="refreshDashboardBtn" class="refresh-btn" title="Refresh dashboard">
+ <i class="fas fa-sync-alt"></i>
+ </button>
+ </div>
+
+ <!-- Loading Indicator -->
+ <div id="loadingIndicator" class="loading-container active">
+ <div class="loading-spinner"></div>
+ </div>
+
+ <!-- Error Message Container -->
+ <div id="errorContainer" style="display: none;" class="error-message">
+ <i class="fas fa-exclamation-circle"></i>
+ <h3>Error Loading Dashboard</h3>
+ <p id="errorMessage">There was a problem loading the warranty statistics. Please try refreshing the page.</p>
+ <p id="errorDetails" class="error-details"></p>
+ </div>
+
+ <!-- Dashboard Content -->
+ <div id="dashboardContent">
+ <!-- Summary Cards -->
+ <div class="status-cards">
+ <div class="status-card" data-status="active">
+ <div class="card-icon">
+ <i class="fas fa-check-circle"></i>
+ </div>
+ <div class="card-content">
+ <h3>Active</h3>
+ <p class="count" id="activeCount">0</p>
+ </div>
+ </div>
+
+ <div class="status-card" data-status="expiring">
+ <div class="card-icon">
+ <i class="fas fa-exclamation-circle"></i>
+ </div>
+ <div class="card-content">
+ <h3>Expiring Soon</h3>
+ <p class="count" id="expiringCount">0</p>
+ </div>
+ </div>
+
+ <div class="status-card" data-status="expired">
+ <div class="card-icon">
+ <i class="fas fa-times-circle"></i>
+ </div>
+ <div class="card-content">
+ <h3>Expired</h3>
+ <p class="count" id="expiredCount">0</p>
+ </div>
+ </div>
+
+ <div class="status-card" data-status="total">
+ <div class="card-icon">
+ <i class="fas fa-shield-alt"></i>
+ </div>
+ <div class="card-content">
+ <h3>Total</h3>
+ <p class="count" id="totalCount">0</p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Charts Section -->
+ <div class="charts-container">
+ <div class="chart-card">
+ <h3>Warranty Status Distribution</h3>
+ <div class="chart-container">
+ <canvas id="statusChart"></canvas>
+ </div>
+ </div>
+
+ <div class="chart-card">
+ <h3>Expiration Timeline</h3>
+ <div class="chart-container">
+ <canvas id="timelineChart"></canvas>
+ </div>
+ </div>
+ </div>
+
+ <!-- Recent Expirations -->
+ <div class="recent-expirations">
+ <div class="table-header">
+ <h3>Recently Expired or Expiring Soon</h3>
+ <div class="table-actions">
+ <div class="search-box">
+ <i class="fas fa-search"></i>
+ <input type="text" id="searchWarranties" placeholder="Search warranties...">
+ </div>
+ <div class="filter-options">
+ <select id="statusFilter" class="filter-select">
+ <option value="all">All Statuses</option>
+ <option value="active">Active</option>
+ <option value="expiring">Expiring Soon</option>
+ <option value="expired">Expired</option>
+ </select>
+ </div>
+ <button id="exportBtn" class="export-btn" title="Export data">
+ <i class="fas fa-download"></i> Export
+ </button>
+ </div>
+ </div>
+ <div class="table-responsive">
+ <table id="recentExpirationsTable">
+ <thead>
+ <tr>
+ <th class="sortable" data-sort="product">Product <i class="fas fa-sort"></i></th>
+ <th class="sortable" data-sort="purchase">Purchase Date <i class="fas fa-sort"></i></th>
+ <th class="sortable" data-sort="expiration">Expiration Date <i class="fas fa-sort"></i></th>
+ <th class="sortable" data-sort="status">Status <i class="fas fa-sort"></i></th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody id="recentExpirationsBody">
+ <!-- Data will be filled by JavaScript -->
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Toast Notifications -->
+ <div class="toast-container" id="toastContainer"></div>
+
+ <!-- Load status.js script after page is processed -->
+ <script src="status.js"></script>
+</body>
+</html>
\ No newline at end of file
diff --git a/frontend/status.js b/frontend/status.js
new file mode 100644
index 0000000..63293e7
--- /dev/null
+++ b/frontend/status.js
@@ -0,0 +1,836 @@
+// DOM Elements
+const settingsBtn = document.getElementById('settingsBtn');
+const settingsMenu = document.getElementById('settingsMenu');
+const darkModeToggle = document.getElementById('darkModeToggle');
+const loadingIndicator = document.getElementById('loadingIndicator');
+const errorContainer = document.getElementById('errorContainer');
+const errorMessage = document.getElementById('errorMessage');
+const errorDetails = document.getElementById('errorDetails');
+const dashboardContent = document.getElementById('dashboardContent');
+const refreshDashboardBtn = document.getElementById('refreshDashboardBtn');
+const searchWarranties = document.getElementById('searchWarranties');
+const statusFilter = document.getElementById('statusFilter');
+const sortableHeaders = document.querySelectorAll('.sortable');
+const exportBtn = document.getElementById('exportBtn');
+
+// Configuration
+const API_URL = '/api/statistics'; // Full URL for statistics endpoint
+const EXPIRING_SOON_DAYS = 30; // Number of days to consider "expiring soon"
+
+// Global variables for sorting and filtering
+let currentSort = { column: 'expiration', direction: 'asc' };
+let allWarranties = []; // Store all warranties for filtering/sorting
+
+// Chart instances
+window.statusChart = null;
+window.timelineChart = null;
+
+// Theme Management
+function setTheme(isDark) {
+ document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');
+ localStorage.setItem('darkMode', isDark);
+ darkModeToggle.checked = isDark;
+}
+
+// Initialize theme based on user preference or system preference
+function initializeTheme() {
+ const savedTheme = localStorage.getItem('darkMode');
+
+ if (savedTheme !== null) {
+ // Use saved preference
+ setTheme(savedTheme === 'true');
+ } else {
+ // Check for system preference
+ const prefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+ setTheme(prefersDarkMode);
+ }
+}
+
+// Initialize theme when page loads
+initializeTheme();
+
+// Settings menu toggle
+settingsBtn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ settingsMenu.classList.toggle('active');
+});
+
+// Close settings menu when clicking outside
+document.addEventListener('click', (e) => {
+ if (!settingsMenu.contains(e.target) && !settingsBtn.contains(e.target)) {
+ settingsMenu.classList.remove('active');
+ }
+});
+
+// Dark mode toggle
+darkModeToggle.addEventListener('change', (e) => {
+ setTheme(e.target.checked);
+});
+
+// Refresh dashboard button
+refreshDashboardBtn.addEventListener('click', () => {
+ refreshDashboard();
+});
+
+// Search input event listener
+searchWarranties.addEventListener('input', () => {
+ filterAndSortWarranties();
+});
+
+// Status filter change event listener
+statusFilter.addEventListener('change', () => {
+ filterAndSortWarranties();
+});
+
+// Add click event listeners to sortable headers
+sortableHeaders.forEach(header => {
+ header.addEventListener('click', () => {
+ const column = header.getAttribute('data-sort');
+
+ // Toggle sort direction if clicking the same column
+ if (currentSort.column === column) {
+ currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
+ } else {
+ currentSort.column = column;
+ currentSort.direction = 'asc';
+ }
+
+ // Update header classes
+ updateSortHeaderClasses();
+
+ // Re-sort the table
+ filterAndSortWarranties();
+ });
+});
+
+// Update the sort header classes
+function updateSortHeaderClasses() {
+ sortableHeaders.forEach(header => {
+ const column = header.getAttribute('data-sort');
+ header.classList.remove('sort-asc', 'sort-desc');
+
+ if (column === currentSort.column) {
+ header.classList.add(currentSort.direction === 'asc' ? 'sort-asc' : 'sort-desc');
+ }
+ });
+}
+
+// Show loading indicator
+function showLoading() {
+ loadingIndicator.classList.add('active');
+ dashboardContent.style.opacity = '0.5';
+}
+
+// Hide loading indicator
+function hideLoading() {
+ loadingIndicator.classList.remove('active');
+ dashboardContent.style.opacity = '1';
+}
+
+// Show error message
+function showError(message, details = '') {
+ errorMessage.textContent = message;
+ errorDetails.textContent = details;
+ errorContainer.style.display = 'block';
+ dashboardContent.style.display = 'none';
+}
+
+// Hide error message
+function hideError() {
+ errorContainer.style.display = 'none';
+ dashboardContent.style.display = 'block';
+}
+
+// Fetch statistics from API
+async function fetchStatistics() {
+ try {
+ const response = await fetch(API_URL);
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`Failed to fetch statistics: ${response.status} ${errorText}`);
+ }
+
+ // Parse JSON only once
+ const data = await response.json();
+ return data;
+ } catch (error) {
+ console.error('Error fetching statistics:', error);
+ throw error;
+ }
+}
+
+// Show a toast notification
+function showToast(message, type = 'info') {
+ const toastContainer = document.getElementById('toastContainer');
+ 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);
+}
+
+// Update the summary counts
+function updateSummaryCounts(stats) {
+ document.getElementById('activeCount').textContent = stats.active;
+ document.getElementById('expiringCount').textContent = stats.expiring_soon;
+ document.getElementById('expiredCount').textContent = stats.expired;
+ document.getElementById('totalCount').textContent = stats.total;
+}
+
+// Create the status distribution chart
+function createStatusChart(stats) {
+ const ctx = document.getElementById('statusChart').getContext('2d');
+
+ // Ensure we have valid stats
+ if (!stats || typeof stats !== 'object') {
+ console.error('Invalid stats data:', stats);
+ stats = { active: 0, expiring_soon: 0, expired: 0, total: 0 };
+ }
+
+ // Set default values for missing properties
+ const active = stats.active || 0;
+ const expiringSoon = stats.expiring_soon || 0;
+ const expired = stats.expired || 0;
+
+ // Calculate truly active (not expiring soon)
+ const trulyActive = Math.max(0, active - expiringSoon);
+
+ // Destroy existing chart if it exists
+ if (window.statusChart) {
+ window.statusChart.destroy();
+ }
+
+ window.statusChart = new Chart(ctx, {
+ type: 'doughnut',
+ data: {
+ labels: ['Active', 'Expiring Soon', 'Expired'],
+ datasets: [{
+ data: [
+ trulyActive,
+ expiringSoon,
+ expired
+ ],
+ backgroundColor: [
+ '#4CAF50', // Green for active
+ '#FF9800', // Orange for expiring soon
+ '#F44336' // Red for expired
+ ],
+ borderWidth: 1
+ }]
+ },
+ options: {
+ responsive: true,
+ maintainAspectRatio: false,
+ plugins: {
+ legend: {
+ position: 'bottom'
+ }
+ }
+ }
+ });
+}
+
+// Create the timeline chart
+function createTimelineChart(timeline) {
+ const ctx = document.getElementById('timelineChart').getContext('2d');
+
+ // Ensure timeline is an array
+ if (!Array.isArray(timeline)) {
+ console.error('Timeline data is not an array:', timeline);
+ timeline = [];
+ }
+
+ // Format labels as "Month Year"
+ const formattedLabels = timeline.map(item => {
+ try {
+ // Handle different possible formats
+ let year, month;
+
+ if (item.year !== undefined && item.month !== undefined) {
+ year = item.year;
+ month = item.month - 1; // JavaScript months are 0-indexed
+ } else if (item.date) {
+ const date = new Date(item.date);
+ year = date.getFullYear();
+ month = date.getMonth();
+ } else {
+ // Default to current month if data format is unknown
+ const date = new Date();
+ year = date.getFullYear();
+ month = date.getMonth();
+ }
+
+ const date = new Date(year, month, 1);
+ return date.toLocaleDateString(undefined, { month: 'short', year: 'numeric' });
+ } catch (error) {
+ console.error('Error formatting timeline label:', error);
+ return 'Unknown';
+ }
+ });
+
+ // Get count values, defaulting to 0 if not present
+ const counts = timeline.map(item => {
+ return item.count !== undefined ? item.count : 0;
+ });
+
+ // If we have no data, create a default dataset
+ if (timeline.length === 0) {
+ const currentDate = new Date();
+ const currentYear = currentDate.getFullYear();
+ const currentMonth = currentDate.getMonth();
+
+ // Create labels for the last 3 months
+ for (let i = 2; i >= 0; i--) {
+ const date = new Date(currentYear, currentMonth - i, 1);
+ formattedLabels.push(date.toLocaleDateString(undefined, { month: 'short', year: 'numeric' }));
+ counts.push(0);
+ }
+ }
+
+ // Destroy existing chart if it exists
+ if (window.timelineChart) {
+ window.timelineChart.destroy();
+ }
+
+ window.timelineChart = new Chart(ctx, {
+ type: 'bar',
+ data: {
+ labels: formattedLabels,
+ datasets: [{
+ label: 'Warranties Expiring',
+ data: counts,
+ backgroundColor: '#3498db',
+ borderColor: '#2980b9',
+ borderWidth: 1
+ }]
+ },
+ options: {
+ responsive: true,
+ maintainAspectRatio: false,
+ scales: {
+ y: {
+ beginAtZero: true,
+ ticks: {
+ precision: 0 // Only show integer values
+ }
+ }
+ }
+ }
+ });
+}
+
+// Update the recent expirations table
+function updateRecentExpirations(recentWarranties) {
+ // Ensure we have an array
+ if (!Array.isArray(recentWarranties)) {
+ console.error('Recent warranties data is not an array:', recentWarranties);
+ recentWarranties = [];
+ }
+
+ // Normalize the data format
+ const normalizedWarranties = recentWarranties.map(warranty => {
+ // Create a standardized warranty object
+ return {
+ id: warranty.id || Math.random().toString(36).substr(2, 9), // Generate ID if not present
+ product_name: warranty.product_name || warranty.name || 'Unknown Product',
+ purchase_date: warranty.purchase_date || new Date().toISOString().split('T')[0],
+ expiration_date: warranty.expiration_date || new Date().toISOString().split('T')[0],
+ invoice_path: warranty.invoice_path || null
+ };
+ });
+
+ // Store all warranties for filtering/sorting
+ allWarranties = normalizedWarranties;
+
+ // Apply initial filtering and sorting
+ filterAndSortWarranties();
+}
+
+// Filter and sort warranties based on current settings
+function filterAndSortWarranties() {
+ const searchTerm = searchWarranties.value.toLowerCase();
+ const statusValue = statusFilter.value;
+ const tableBody = document.getElementById('recentExpirationsBody');
+
+ // Clear the table
+ tableBody.innerHTML = '';
+
+ if (!allWarranties || allWarranties.length === 0) {
+ const row = document.createElement('tr');
+ row.innerHTML = '<td colspan="5" class="no-data">No recently expired or expiring warranties.</td>';
+ tableBody.appendChild(row);
+ return;
+ }
+
+ const today = new Date();
+
+ // Filter warranties
+ let filteredWarranties = allWarranties.filter(warranty => {
+ // Apply search filter
+ const productName = warranty.product_name.toLowerCase();
+ const matchesSearch = searchTerm === '' || productName.includes(searchTerm);
+
+ // Apply status filter
+ if (statusValue === 'all') {
+ return matchesSearch;
+ }
+
+ const expirationDate = new Date(warranty.expiration_date);
+
+ if (statusValue === 'expired') {
+ return expirationDate <= today && matchesSearch;
+ } else if (statusValue === 'expiring') {
+ const timeDiff = expirationDate - today;
+ const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
+ return expirationDate > today && daysDiff <= EXPIRING_SOON_DAYS && matchesSearch;
+ } else if (statusValue === 'active') {
+ const timeDiff = expirationDate - today;
+ const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
+ return expirationDate > today && daysDiff > EXPIRING_SOON_DAYS && matchesSearch;
+ }
+
+ return matchesSearch;
+ });
+
+ // Sort warranties
+ filteredWarranties.sort((a, b) => {
+ let valueA, valueB;
+
+ switch (currentSort.column) {
+ case 'product':
+ valueA = a.product_name;
+ valueB = b.product_name;
+ break;
+ case 'purchase':
+ valueA = new Date(a.purchase_date);
+ valueB = new Date(b.purchase_date);
+ break;
+ case 'expiration':
+ valueA = new Date(a.expiration_date);
+ valueB = new Date(b.expiration_date);
+ break;
+ case 'status':
+ // Sort by status priority: active, expiring, expired
+ const statusA = getStatusPriority(a.expiration_date, today);
+ const statusB = getStatusPriority(b.expiration_date, today);
+ valueA = statusA;
+ valueB = statusB;
+ break;
+ default:
+ valueA = new Date(a.expiration_date);
+ valueB = new Date(b.expiration_date);
+ }
+
+ // Compare values based on sort direction
+ if (currentSort.direction === 'asc') {
+ return valueA > valueB ? 1 : valueA < valueB ? -1 : 0;
+ } else {
+ return valueA < valueB ? 1 : valueA > valueB ? -1 : 0;
+ }
+ });
+
+ // Render filtered and sorted warranties
+ if (filteredWarranties.length === 0) {
+ const row = document.createElement('tr');
+ row.innerHTML = '<td colspan="5" class="no-data">No warranties match your search criteria.</td>';
+ tableBody.appendChild(row);
+ return;
+ }
+
+ filteredWarranties.forEach(warranty => {
+ const row = document.createElement('tr');
+
+ // Determine status
+ const expirationDate = new Date(warranty.expiration_date);
+ let status = 'active';
+
+ if (expirationDate <= today) {
+ status = 'expired';
+ } else {
+ const timeDiff = expirationDate - today;
+ const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
+
+ if (daysDiff <= EXPIRING_SOON_DAYS) {
+ status = 'expiring';
+ }
+ }
+
+ row.className = `status-${status}`;
+
+ // Format dates
+ const purchaseDate = new Date(warranty.purchase_date).toLocaleDateString();
+ const formattedExpirationDate = expirationDate.toLocaleDateString();
+
+ // Status display
+ let statusText = status === 'expired' ? 'Expired' : status === 'expiring' ? 'Expiring Soon' : 'Active';
+ let statusClass = `status-${status}`;
+
+ // Create table cells with proper structure
+ row.innerHTML = `
+ <td>${warranty.product_name}</td>
+ <td>${purchaseDate}</td>
+ <td>${formattedExpirationDate}</td>
+ <td><span class="${statusClass}">${statusText}</span></td>
+ <td>
+ <a href="index.html?edit=${warranty.id}" class="action-btn edit-btn" title="Edit">
+ <i class="fas fa-edit"></i>
+ </a>
+ <a href="${warranty.invoice_path}" target="_blank" class="action-btn view-btn" title="View Invoice" ${!warranty.invoice_path ? 'style="display: none;"' : ''}>
+ <i class="fas fa-file-alt"></i>
+ </a>
+ </td>
+ `;
+
+ tableBody.appendChild(row);
+ });
+}
+
+// Get status priority for sorting (1: active, 2: expiring, 3: expired)
+function getStatusPriority(expirationDateStr, today) {
+ const expirationDate = new Date(expirationDateStr);
+
+ if (expirationDate <= today) {
+ return 3; // Expired
+ } else {
+ const timeDiff = expirationDate - today;
+ const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
+
+ if (daysDiff <= EXPIRING_SOON_DAYS) {
+ return 2; // Expiring soon
+ } else {
+ return 1; // Active
+ }
+ }
+}
+
+// Refresh the dashboard
+function refreshDashboard() {
+ // Add loading animation to refresh button
+ refreshDashboardBtn.classList.add('loading');
+
+ // Initialize the dashboard
+ initDashboard().finally(() => {
+ // Remove loading animation
+ refreshDashboardBtn.classList.remove('loading');
+ });
+}
+
+// Initialize the dashboard
+async function initDashboard() {
+ showLoading();
+ hideError();
+
+ try {
+ const data = await fetchStatistics();
+ console.log('API Response:', data); // Log the actual response for debugging
+
+ // Handle different possible API response structures
+ let summary, timeline, recentWarranties;
+
+ // Check if data is directly the summary object
+ if (data && typeof data === 'object' && 'active' in data && 'expired' in data) {
+ summary = data;
+ timeline = data.timeline || [];
+ recentWarranties = data.recent_warranties || [];
+ }
+ // Check if data has summary as a property
+ else if (data && typeof data === 'object' && data.summary && typeof data.summary === 'object') {
+ summary = data.summary;
+ timeline = data.timeline || [];
+ recentWarranties = data.recent_warranties || [];
+ }
+ // If we can't find a valid structure, throw an error
+ else {
+ console.error('Unexpected API response structure:', data);
+ throw new Error('Invalid data structure received from API. Expected summary data with active and expired counts.');
+ }
+
+ // Ensure summary has all required properties
+ if (!('active' in summary) || !('expired' in summary)) {
+ throw new Error('API response missing required summary fields (active, expired)');
+ }
+
+ // Set default values for any missing properties
+ summary.expiring_soon = summary.expiring_soon || 0;
+ summary.total = summary.total || (summary.active + summary.expired);
+
+ // Update summary counts
+ updateSummaryCounts(summary);
+
+ // Create charts
+ createStatusChart(summary);
+
+ // Handle timeline data
+ if (Array.isArray(timeline) && timeline.length > 0) {
+ createTimelineChart(timeline);
+ } else {
+ // Create default timeline if none provided
+ createTimelineChart([
+ { month: 1, year: new Date().getFullYear(), count: 0 },
+ { month: 2, year: new Date().getFullYear(), count: 0 },
+ { month: 3, year: new Date().getFullYear(), count: 0 }
+ ]);
+ }
+
+ // Update recent expirations table
+ if (Array.isArray(recentWarranties)) {
+ updateRecentExpirations(recentWarranties);
+ } else {
+ updateRecentExpirations([]);
+ }
+
+ showToast('Dashboard updated successfully', 'success');
+ } catch (error) {
+ console.error('Error initializing dashboard:', error);
+ showError(
+ 'There was a problem loading the warranty statistics. Please try refreshing the page.',
+ error.message
+ );
+
+ // Fallback to static data for demonstration if API fails
+ document.getElementById('activeCount').textContent = '10';
+ document.getElementById('expiringCount').textContent = '5';
+ document.getElementById('expiredCount').textContent = '3';
+ document.getElementById('totalCount').textContent = '18';
+
+ // Create a simple chart with static data
+ try {
+ const ctx = document.getElementById('statusChart').getContext('2d');
+ if (window.statusChart) window.statusChart.destroy();
+
+ window.statusChart = new Chart(ctx, {
+ type: 'doughnut',
+ data: {
+ labels: ['Active', 'Expiring Soon', 'Expired'],
+ datasets: [{
+ data: [10, 5, 3],
+ backgroundColor: [
+ '#4CAF50',
+ '#FF9800',
+ '#F44336'
+ ],
+ borderWidth: 1
+ }]
+ },
+ options: {
+ responsive: true,
+ maintainAspectRatio: false,
+ plugins: {
+ legend: {
+ position: 'bottom'
+ }
+ }
+ }
+ });
+
+ // Create a simple timeline chart
+ const timelineCtx = document.getElementById('timelineChart').getContext('2d');
+ if (window.timelineChart) window.timelineChart.destroy();
+
+ window.timelineChart = new Chart(timelineCtx, {
+ type: 'bar',
+ data: {
+ labels: ['Jan 2023', 'Feb 2023', 'Mar 2023'],
+ datasets: [{
+ label: 'Warranties Expiring',
+ data: [2, 3, 4],
+ backgroundColor: '#3498db',
+ borderColor: '#2980b9',
+ borderWidth: 1
+ }]
+ },
+ options: {
+ responsive: true,
+ maintainAspectRatio: false,
+ scales: {
+ y: {
+ beginAtZero: true,
+ ticks: {
+ precision: 0
+ }
+ }
+ }
+ }
+ });
+
+ // Add some sample data to the table
+ const sampleWarranties = [
+ {
+ id: 1,
+ product_name: 'Sample Product 1',
+ purchase_date: '2022-01-01',
+ expiration_date: '2023-01-01',
+ invoice_path: null
+ },
+ {
+ id: 2,
+ product_name: 'Sample Product 2',
+ purchase_date: '2022-01-01',
+ expiration_date: '2023-06-15',
+ invoice_path: null
+ }
+ ];
+
+ // Update the table with sample data
+ updateRecentExpirations(sampleWarranties);
+
+ } catch (chartError) {
+ console.error('Error creating fallback charts:', chartError);
+ }
+
+ showToast('Using demo data - API connection failed', 'warning');
+ } finally {
+ hideLoading();
+ }
+}
+
+// Initialize the dashboard when the page loads
+document.addEventListener('DOMContentLoaded', initDashboard);
+
+// Export button event listener
+exportBtn.addEventListener('click', () => {
+ exportWarrantyData();
+});
+
+// Export warranty data as CSV
+function exportWarrantyData() {
+ // Get filtered and sorted warranties
+ const searchTerm = searchWarranties.value.toLowerCase();
+ const statusValue = statusFilter.value;
+ const today = new Date();
+
+ // Filter warranties
+ let filteredWarranties = allWarranties.filter(warranty => {
+ // Apply search filter
+ const productName = warranty.product_name.toLowerCase();
+ const matchesSearch = searchTerm === '' || productName.includes(searchTerm);
+
+ // Apply status filter
+ if (statusValue === 'all') {
+ return matchesSearch;
+ }
+
+ const expirationDate = new Date(warranty.expiration_date);
+
+ if (statusValue === 'expired') {
+ return expirationDate <= today && matchesSearch;
+ } else if (statusValue === 'expiring') {
+ const timeDiff = expirationDate - today;
+ const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
+ return expirationDate > today && daysDiff <= EXPIRING_SOON_DAYS && matchesSearch;
+ } else if (statusValue === 'active') {
+ const timeDiff = expirationDate - today;
+ const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
+ return expirationDate > today && daysDiff > EXPIRING_SOON_DAYS && matchesSearch;
+ }
+
+ return matchesSearch;
+ });
+
+ // Sort warranties based on current sort settings
+ filteredWarranties.sort((a, b) => {
+ let valueA, valueB;
+
+ switch (currentSort.column) {
+ case 'product':
+ valueA = a.product_name;
+ valueB = b.product_name;
+ break;
+ case 'purchase':
+ valueA = new Date(a.purchase_date);
+ valueB = new Date(b.purchase_date);
+ break;
+ case 'expiration':
+ valueA = new Date(a.expiration_date);
+ valueB = new Date(b.expiration_date);
+ break;
+ case 'status':
+ // Sort by status priority: active, expiring, expired
+ const statusA = getStatusPriority(a.expiration_date, today);
+ const statusB = getStatusPriority(b.expiration_date, today);
+ valueA = statusA;
+ valueB = statusB;
+ break;
+ default:
+ valueA = new Date(a.expiration_date);
+ valueB = new Date(b.expiration_date);
+ }
+
+ // Compare values based on sort direction
+ if (currentSort.direction === 'asc') {
+ return valueA > valueB ? 1 : valueA < valueB ? -1 : 0;
+ } else {
+ return valueA < valueB ? 1 : valueA > valueB ? -1 : 0;
+ }
+ });
+
+ // If no warranties to export
+ if (filteredWarranties.length === 0) {
+ showToast('No data to export', 'warning');
+ return;
+ }
+
+ // Create CSV content
+ let csvContent = 'Product,Purchase Date,Expiration Date,Status\n';
+
+ filteredWarranties.forEach(warranty => {
+ const purchaseDate = new Date(warranty.purchase_date).toLocaleDateString();
+ const expirationDate = new Date(warranty.expiration_date).toLocaleDateString();
+
+ // Determine status
+ const today = new Date();
+ const expDate = new Date(warranty.expiration_date);
+ let status = 'Active';
+
+ if (expDate <= today) {
+ status = 'Expired';
+ } else {
+ const timeDiff = expDate - today;
+ const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
+
+ if (daysDiff <= EXPIRING_SOON_DAYS) {
+ status = 'Expiring Soon';
+ }
+ }
+
+ // Escape commas in product name
+ const escapedProductName = warranty.product_name.includes(',')
+ ? `"${warranty.product_name}"`
+ : warranty.product_name;
+
+ csvContent += `${escapedProductName},${purchaseDate},${expirationDate},${status}\n`;
+ });
+
+ // Create download link
+ const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+
+ // Set link properties
+ link.setAttribute('href', url);
+ link.setAttribute('download', 'warranty_data.csv');
+ link.style.visibility = 'hidden';
+
+ // Add to document, click and remove
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+
+ showToast('Data exported successfully', 'success');
+}
\ No newline at end of file
diff --git a/frontend/style.css b/frontend/style.css
index 85cbf6c..b1df543 100644
--- a/frontend/style.css
+++ b/frontend/style.css
@@ -342,16 +342,31 @@ header .container {
}
.action-btn {
+ color: var(--primary-color);
+ margin-right: 8px;
+ font-size: 1.1rem;
+ transition: var(--transition);
background: none;
border: none;
- font-size: 1rem;
cursor: pointer;
- color: var(--dark-gray);
- transition: var(--transition);
+ padding: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ text-decoration: none;
+}
+
+.action-btn:hover {
+ color: var(--primary-dark);
+ transform: scale(1.1);
}
.edit-btn:hover {
- color: var(--primary-color);
+ color: var(--primary-dark);
+}
+
+.view-btn:hover {
+ color: var(--secondary-color);
}
.delete-btn:hover {
@@ -381,19 +396,27 @@ header .container {
margin-top: 10px;
}
+.status-expired, .status-expiring, .status-active {
+ display: inline-block;
+ padding: 4px 8px;
+ border-radius: 4px;
+ font-size: 0.85rem;
+ font-weight: 600;
+}
+
.status-active {
- background-color: rgba(46, 204, 113, 0.15);
- color: #27ae60;
+ background-color: rgba(76, 175, 80, 0.2);
+ color: #4CAF50;
}
.status-expired {
- background-color: rgba(231, 76, 60, 0.15);
- color: #c0392b;
+ background-color: rgba(244, 67, 54, 0.2);
+ color: #F44336;
}
.status-expiring {
- background-color: rgba(243, 156, 18, 0.15);
- color: #d35400;
+ background-color: rgba(255, 152, 0, 0.2);
+ color: #FF9800;
}
.invoice-link {
@@ -820,4 +843,455 @@ input:checked + .toggle-slider:after {
.mb-20 {
margin-bottom: 20px;
+}
+
+/* Navigation Links */
+.nav-links {
+ display: flex;
+ gap: 20px;
+ margin: 0 20px;
+}
+
+.nav-link {
+ text-decoration: none;
+ color: var(--text-color);
+ padding: 8px 12px;
+ border-radius: 4px;
+ transition: background-color 0.3s;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.nav-link:hover {
+ background-color: rgba(0, 0, 0, 0.05);
+}
+
+.nav-link.active {
+ background-color: rgba(0, 0, 0, 0.05);
+ font-weight: 600;
+}
+
+.nav-link i {
+ font-size: 1rem;
+}
+
+/* Status Page Styles */
+.status-content {
+ width: 100%;
+ max-width: 1200px;
+ margin: 0 auto;
+ padding: 20px;
+}
+
+.status-cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+ gap: 20px;
+ margin-bottom: 30px;
+}
+
+.status-card {
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ padding: 20px;
+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
+ display: flex;
+ align-items: center;
+ transition: transform 0.3s, box-shadow 0.3s;
+}
+
+.status-card:hover {
+ transform: translateY(-5px);
+ box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
+}
+
+.status-card[data-status="active"] .card-icon {
+ color: #4CAF50;
+}
+
+.status-card[data-status="expiring"] .card-icon {
+ color: #FF9800;
+}
+
+.status-card[data-status="expired"] .card-icon {
+ color: #F44336;
+}
+
+.status-card[data-status="total"] .card-icon {
+ color: #3498db;
+}
+
+.card-icon {
+ font-size: 2.5rem;
+ margin-right: 15px;
+}
+
+.card-content h3 {
+ margin: 0 0 5px 0;
+ font-size: 1rem;
+ color: var(--dark-gray);
+}
+
+.card-content .count {
+ font-size: 2rem;
+ font-weight: 700;
+ margin: 0;
+ color: var(--text-color);
+}
+
+.charts-container {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
+ gap: 30px;
+ margin-bottom: 30px;
+}
+
+.chart-card {
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ padding: 20px;
+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
+}
+
+.chart-card h3 {
+ margin-top: 0;
+ margin-bottom: 15px;
+ font-size: 1.2rem;
+ color: var(--text-color);
+}
+
+.chart-container {
+ height: 300px;
+ position: relative;
+}
+
+.recent-expirations {
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ padding: 20px;
+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
+ margin-bottom: 30px;
+}
+
+.recent-expirations h3 {
+ margin-top: 0;
+ margin-bottom: 15px;
+ font-size: 1.2rem;
+ color: var(--text-color);
+ text-align: left;
+}
+
+.table-responsive {
+ overflow-x: auto;
+ width: 100%;
+}
+
+#recentExpirationsTable {
+ width: 100%;
+ border-collapse: collapse;
+ table-layout: fixed;
+}
+
+#recentExpirationsTable th,
+#recentExpirationsTable td {
+ padding: 12px 15px;
+ text-align: left;
+ border-bottom: 1px solid var(--border-color);
+}
+
+/* Define column widths */
+#recentExpirationsTable th:nth-child(1),
+#recentExpirationsTable td:nth-child(1) {
+ width: 25%;
+ text-align: left;
+}
+
+#recentExpirationsTable th:nth-child(2),
+#recentExpirationsTable td:nth-child(2) {
+ width: 20%;
+ text-align: left;
+}
+
+#recentExpirationsTable th:nth-child(3),
+#recentExpirationsTable td:nth-child(3) {
+ width: 20%;
+ text-align: left;
+}
+
+#recentExpirationsTable th:nth-child(4),
+#recentExpirationsTable td:nth-child(4) {
+ width: 20%;
+ text-align: left;
+}
+
+#recentExpirationsTable th:nth-child(5),
+#recentExpirationsTable td:nth-child(5) {
+ width: 15%;
+ text-align: left;
+}
+
+#recentExpirationsTable thead th {
+ background-color: rgba(0, 0, 0, 0.03);
+ color: var(--text-color);
+ font-weight: 600;
+ position: sticky;
+ top: 0;
+ z-index: 10;
+}
+
+#recentExpirationsTable tbody tr:hover {
+ background-color: rgba(0, 0, 0, 0.03);
+}
+
+#recentExpirationsTable .no-data {
+ text-align: center;
+ color: var(--dark-gray);
+ padding: 30px;
+}
+
+/* Status styling */
+.status-expired {
+ color: #F44336;
+ padding: 4px 8px;
+ border-radius: 4px;
+ background-color: rgba(244, 67, 54, 0.1);
+ display: inline-block;
+}
+
+.status-expiring {
+ color: #FF9800;
+ padding: 4px 8px;
+ border-radius: 4px;
+ background-color: rgba(255, 152, 0, 0.1);
+ display: inline-block;
+}
+
+.status-active {
+ color: #4CAF50;
+ padding: 4px 8px;
+ border-radius: 4px;
+ background-color: rgba(76, 175, 80, 0.1);
+ display: inline-block;
+}
+
+tr.status-expired {
+ background-color: rgba(244, 67, 54, 0.05);
+}
+
+tr.status-expiring {
+ background-color: rgba(255, 152, 0, 0.05);
+}
+
+@media (max-width: 768px) {
+ .status-cards {
+ grid-template-columns: repeat(2, 1fr);
+ }
+
+ .charts-container {
+ grid-template-columns: 1fr;
+ }
+
+ .chart-container {
+ height: 250px;
+ }
+
+ #recentExpirationsTable th:nth-child(2),
+ #recentExpirationsTable td:nth-child(2) {
+ display: none;
+ }
+}
+
+@media (max-width: 480px) {
+ .status-cards {
+ grid-template-columns: 1fr;
+ }
+
+ #recentExpirationsTable th:nth-child(3),
+ #recentExpirationsTable td:nth-child(3) {
+ display: none;
+ }
+}
+
+/* Error message on status page */
+.error-message {
+ text-align: center;
+ padding: 40px 20px;
+ background-color: rgba(244, 67, 54, 0.05);
+ border-radius: 8px;
+ margin: 20px 0;
+}
+
+.error-message i {
+ font-size: 3rem;
+ color: #F44336;
+ margin-bottom: 15px;
+}
+
+.error-message h3 {
+ font-size: 1.5rem;
+ margin-bottom: 10px;
+ color: #F44336;
+}
+
+.error-message p {
+ color: var(--text-color);
+ margin-bottom: 10px;
+}
+
+.error-message p:last-child {
+ font-family: monospace;
+ background-color: rgba(0, 0, 0, 0.05);
+ padding: 10px;
+ border-radius: 4px;
+ max-width: 100%;
+ overflow-x: auto;
+ font-size: 0.9rem;
+}
+
+/* Fix for table alignment */
+.recent-expirations table {
+ width: 100%;
+ margin: 0 auto;
+}
+
+.recent-expirations thead,
+.recent-expirations tbody,
+.recent-expirations tr,
+.recent-expirations th,
+.recent-expirations td {
+ display: revert;
+ text-align: left;
+}
+
+.settings-link {
+ display: flex;
+ align-items: center;
+ text-decoration: none;
+ color: var(--text-color);
+ padding: 5px 0;
+ transition: var(--transition);
+ width: 100%;
+}
+
+.settings-link i {
+ margin-right: 10px;
+ font-size: 1rem;
+ width: 20px;
+ text-align: center;
+}
+
+.settings-link:hover {
+ color: var(--primary-color);
+}
+
+.dashboard-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 20px;
+}
+
+.dashboard-header h2 {
+ margin: 0;
+ font-size: 1.5rem;
+ color: var(--text-color);
+}
+
+.table-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ flex-wrap: wrap;
+ margin-bottom: 15px;
+}
+
+.table-header h3 {
+ margin: 0;
+ font-size: 1.2rem;
+ color: var(--text-color);
+}
+
+.table-actions {
+ display: flex;
+ gap: 10px;
+ align-items: center;
+}
+
+.filter-options {
+ min-width: 150px;
+}
+
+.filter-select {
+ width: 100%;
+ padding: 8px 10px;
+ border-radius: var(--border-radius);
+ border: 1px solid var(--border-color);
+ background-color: var(--card-bg);
+ color: var(--text-color);
+ font-size: 0.9rem;
+ cursor: pointer;
+ transition: var(--transition);
+}
+
+.filter-select:focus {
+ outline: none;
+ border-color: var(--primary-color);
+ box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
+}
+
+.sortable {
+ cursor: pointer;
+ position: relative;
+ user-select: none;
+}
+
+.sortable i {
+ font-size: 0.8rem;
+ margin-left: 5px;
+ opacity: 0.5;
+ transition: var(--transition);
+}
+
+.sortable:hover i {
+ opacity: 1;
+}
+
+.sortable.sort-asc i:before {
+ content: "\f0de"; /* fa-sort-up */
+}
+
+.sortable.sort-desc i:before {
+ content: "\f0dd"; /* fa-sort-down */
+}
+
+/* Export button */
+.export-btn {
+ background-color: var(--card-bg);
+ border: 1px solid var(--border-color);
+ color: var(--text-color);
+ padding: 6px 12px;
+ border-radius: var(--border-radius);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ font-size: 0.9rem;
+ transition: var(--transition);
+}
+
+.export-btn:hover {
+ background-color: var(--primary-color);
+ color: white;
+ border-color: var(--primary-color);
+}
+
+/* Animation for refresh button */
+@keyframes spin {
+ 0% { transform: rotate(0deg); }
+ 100% { transform: rotate(360deg); }
+}
+
+.refresh-btn.loading i {
+ animation: spin 1s linear infinite;
}
\ No newline at end of file
diff --git a/nginx.conf b/nginx.conf
index 19c1eea..c2cb505 100644
--- a/nginx.conf
+++ b/nginx.conf
@@ -8,71 +8,86 @@ server {
error_log /var/log/nginx/error.log debug;
access_log /var/log/nginx/access.log;
- # Enable gzip compression
+ # Global settings
gzip on;
gzip_types text/plain text/css application/javascript application/json;
- # Add CORS headers
+ # Add CORS headers globally
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';
- # A test location to debug directory paths
- location = /test-uploads {
- add_header Content-Type text/plain;
- return 200 "Uploads directory exists: $document_root\n";
+ # MIME types - fixed duplicate js entry
+ types {
+ text/html html htm shtml;
+ text/css css;
+ application/javascript js;
+ image/png png;
+ image/jpeg jpg jpeg;
+ image/gif gif;
+ image/svg+xml svg svgz;
+ application/pdf pdf;
}
- location / {
- try_files $uri $uri/ /index.html;
- }
-
- # Proxy API requests to backend
+ # API requests - proxy to backend (fixed upstream host)
location /api/ {
- proxy_pass http://warracker:5000;
+ proxy_pass http://127.0.0.1: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;
+
+ # Add debug headers to see what's happening
+ add_header X-Debug-Message "API request proxied to backend" always;
+
+ # CORS for API
+ add_header 'Access-Control-Allow-Origin' '*' always;
+ add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
+ add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
+
+ # CORS preflight
+ if ($request_method = 'OPTIONS') {
+ add_header 'Access-Control-Allow-Origin' '*' always;
+ add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
+ add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
+ add_header 'Access-Control-Max-Age' 1728000 always;
+ add_header 'Content-Type' 'text/plain charset=UTF-8' always;
+ add_header 'Content-Length' 0 always;
+ return 204;
+ }
}
- # Simpler uploads location - using alias instead of root
+ # Uploads - serve files from uploads directory
location /uploads/ {
alias /data/uploads/;
autoindex on;
- # Set appropriate MIME types
- types {
- image/png png PNG;
- image/jpeg jpg jpeg JPG JPEG;
- application/pdf pdf PDF;
- text/plain txt TXT;
- }
-
- # Disable caching for testing
+ # No caching
add_header Cache-Control "no-cache, no-store, must-revalidate";
add_header Pragma "no-cache";
add_header Expires "0";
}
- # Cache static assets - skip uploads
+ # HTML files - ensure proper content type
+ location ~ \.html$ {
+ add_header Content-Type "text/html; charset=utf-8";
+ add_header Cache-Control "no-cache, no-store, must-revalidate";
+ }
+
+ # Static assets (CSS, JS, images)
location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg)$ {
- # Skip this location if the request is for /uploads/
- if ($request_uri ~* "^/uploads/") {
- return 404;
- }
-
expires 7d;
add_header Cache-Control "public, max-age=604800";
}
- # Don't redirect 404s for uploads to index.html
- location ~ ^/uploads/ {
- try_files $uri =404;
+ # Test uploads path
+ location = /test-uploads {
+ add_header Content-Type text/plain;
+ return 200 "Uploads directory exists: $document_root\n";
}
- # Error handling - for everything except uploads
+ # Default location
location / {
- error_page 404 = /index.html;
+ try_files $uri $uri/ /index.html;
}
}
\ No newline at end of file