Skip to content

πŸ›‘οΈ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Granular warranty duration input, file uploads, and env-based config

sassanix2b4bf1ae266d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 19dcd0e..5354ff9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,45 @@
# Changelog
+## [0.9.9.6] - 2025-05-11
+
+### Added
+- **Warranty Duration Input:** Replaced the single "Warranty Period (Years)" input field with separate fields for Years, Months, and Days when adding or editing warranties.
+ - Allows for more precise warranty duration entry (e.g., 2 years, 6 months, 15 days).
+ - Updated Add/Edit forms (`frontend/index.html`), JavaScript logic (`frontend/script.js`), CSS styling (`frontend/style.css`), backend API (`backend/app.py`), and database schema (`backend/migrations/021_change_warranty_duration_to_components.sql`).
+ - Warranty display on cards and summaries now shows the formatted duration (e.g., "2 years, 6 months").
+ - CSV import/export updated to use `WarrantyDurationYears`, `WarrantyDurationMonths`, `WarrantyDurationDays` columns.
+ - Backend validation ensures at least one duration component is provided for non-lifetime warranties.
+ - Fixed backend logic to correctly handle empty duration inputs, treating them as 0.
+ _Files: `backend/app.py`, `backend/migrations/021_change_warranty_duration_to_components.sql`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_
+- **Files Upload:** Users can now upload an additional ZIP/RAR file (e.g., for extended warranty documents, photos, or other related files) when adding or editing a warranty.
+ - This document is stored securely and can be accessed from the warranty card.
+ - _Files: `backend/app.py`, `backend/migrations/022_add_other_document_path.sql`, `frontend/index.html`, `frontend/script.js`_
+- **Configurable JWT Secret Key:**
+ - The application's JWT and session secret key can now be configured via the `SECRET_KEY` environment variable.
+ - It is strongly recommended to set a unique, strong secret key in production environments. Defaults to a development key if not set.
+ - _Relevant File: `backend/app.py` (for usage), `docker-compose.yml` (for setting)_
+- **Configurable File Upload Limits:**
+ - Maximum file upload sizes for both the backend application and the Nginx reverse proxy are now configurable via environment variables.
+ - **Application (Flask):** Set `MAX_UPLOAD_MB` (e.g., `MAX_UPLOAD_MB=64`) to define the limit in megabytes. Defaults to 32MB.
+ - **Nginx:** Set `NGINX_MAX_BODY_SIZE_VALUE` (e.g., `NGINX_MAX_BODY_SIZE_VALUE=64M`) to define the limit for Nginx (value must include unit like M or G). Defaults to "32M".
+ - The `Dockerfile` and `nginx.conf` have been updated to support this.
+ - _Files: `backend/app.py`, `nginx.conf`, `Dockerfile`_
+- **Security key can be used in environment:**
+ - **SECRET_KEY=** is now usuable in docker-compose for jwt secret.
+ - _Files: `Docker/docker-compose.yml`_
+
+### Fixed
+- **Backend Indentation Error:** Corrected an `IndentationError` in `backend/app.py` within the CSV import logic that prevented the backend from starting correctly.
+ _Files: `backend/app.py`_
+- **Migration Script Error:** Fixed an error in migration `021_change_warranty_duration_to_components.sql` where it incorrectly referenced `lifetime_warranty` instead of the correct `is_lifetime` column.
+ _Files: `backend/migrations/021_change_warranty_duration_to_components.sql`_
+- **smtplib import duplicate:** Removed line from app.py that re-imported smtplib with a pull request.
+- _Files: `backend/app.py`_
+
+### House Cleaning
+- **Old Settings files:** Removed all older settings pages , and related files.
+- _Files: `frontend/settings.html`,`frontend/settings.script.js`,`frontend/settings_redirect.html`_
+
## [0.9.9.5] - 2025-05-07
### Changed
diff --git a/Docker/docker-compose.yml b/Docker/docker-compose.yml
index ed7fb06..a14d7f6 100644
--- a/Docker/docker-compose.yml
+++ b/Docker/docker-compose.yml
@@ -14,6 +14,10 @@ services:
- SMTP_PORT=465
- SMTP_PASSWORD=password
+ - SECRET_KEY=${APP_SECRET_KEY:-your_strong_default_secret_key_here}
+ - MAX_UPLOAD_MB=32 # Example: Set max upload size to 32MB
+ - NGINX_MAX_BODY_SIZE_VALUE=32M # For Nginx, ensure this matches MAX_UPLOAD_MB in concept (e.g., 32M)
+ # - FLASK_DEBUG=0
depends_on:
warrackerdb:
condition: service_healthy
diff --git a/Dockerfile b/Dockerfile
index b597cad..d43d0a8 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -9,15 +9,15 @@ RUN apt-get update && \
nginx \
curl \
postgresql-client \
- supervisor && \
+ supervisor \
+ gettext-base && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
# (build-essential = C compiler + tools)
# (libpq-dev = provides pg_config for psycopg2)
-# Ensure nginx runs in foreground
-RUN sed -i '1i daemon off;' /etc/nginx/nginx.conf
+# Nginx will be started with "daemon off;" via supervisor, so no need to sed the main nginx.conf
WORKDIR /app
@@ -45,7 +45,8 @@ COPY frontend/img/ /var/www/html/img/
# Configure nginx site
RUN rm /etc/nginx/sites-enabled/default
-COPY nginx.conf /etc/nginx/conf.d/default.conf
+# Copy nginx.conf as a template
+COPY nginx.conf /etc/nginx/conf.d/default.conf.template
# Create startup script with database initialization
RUN echo '#!/bin/bash\n\
@@ -84,37 +85,33 @@ echo "Setup script finished successfully."\n\
exit 0 # Exit successfully, Supervisor takes over\n\
' > /app/start.sh && chmod +x /app/start.sh
-# This is just a fallback Nginx config echo, the copied nginx.conf is primary
-# Note: Removed the /uploads/ location block from here.
-# Ensure your actual nginx.conf doesn't reference it if not needed.
-RUN echo 'server {\n\
- listen 80;\n\
- server_name localhost;\n\
- root /var/www/html;\n\
- index index.html;\n\
- \n\
- # Enable detailed error logging\n\
- error_log /var/log/nginx/error.log debug;\n\
- access_log /var/log/nginx/access.log;\n\
- \n\
- # Enable gzip compression\n\
- gzip on;\n\
- gzip_types text/plain text/css application/javascript application/json;\n\
- client_max_body_size 32M;\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://127.0.0.1:5000;\n\
- proxy_set_header Host $host;\n\
- proxy_set_header X-Real-IP $remote_addr;\n\
- client_max_body_size 32M;\n\
- }\n\
- \n\
-}' > /etc/nginx/conf.d/default.conf
+# Create a wrapper script for starting Nginx with sed for placeholder replacement
+RUN echo '#!/bin/sh' > /app/start_nginx_wrapper.sh && \
+ echo 'set -e' >> /app/start_nginx_wrapper.sh && \
+ echo '' >> /app/start_nginx_wrapper.sh && \
+ echo '# Read the environment variable, which the user sets in docker-compose.yml' >> /app/start_nginx_wrapper.sh && \
+ echo 'EFFECTIVE_SIZE="${NGINX_MAX_BODY_SIZE_VALUE}"' >> /app/start_nginx_wrapper.sh && \
+ echo '' >> /app/start_nginx_wrapper.sh && \
+ echo '# Validate EFFECTIVE_SIZE or set default' >> /app/start_nginx_wrapper.sh && \
+ echo 'if ! echo "${EFFECTIVE_SIZE}" | grep -Eq "^[0-9]+[mMkKgG]?$"; then' >> /app/start_nginx_wrapper.sh && \
+ echo " echo \"Warning: NGINX_MAX_BODY_SIZE_VALUE ('\${EFFECTIVE_SIZE}') is invalid or empty. Defaulting to 32M.\"" >> /app/start_nginx_wrapper.sh && \
+ echo " EFFECTIVE_SIZE='32M'" >> /app/start_nginx_wrapper.sh && \
+ echo 'fi' >> /app/start_nginx_wrapper.sh && \
+ echo '' >> /app/start_nginx_wrapper.sh && \
+ echo '# Substitute the placeholder in the template file with the effective size' >> /app/start_nginx_wrapper.sh && \
+ echo '# Using | as sed delimiter to avoid issues if EFFECTIVE_SIZE somehow contained /' >> /app/start_nginx_wrapper.sh && \
+ echo "sed \"s|__NGINX_MAX_BODY_SIZE_CONFIG_VALUE__|\${EFFECTIVE_SIZE}|g\" /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" >> /app/start_nginx_wrapper.sh && \
+ echo '' >> /app/start_nginx_wrapper.sh && \
+ echo "# Print the processed config for debugging" >> /app/start_nginx_wrapper.sh && \
+ echo "echo '--- Start of Processed Nginx default.conf ---'" >> /app/start_nginx_wrapper.sh && \
+ echo "cat /etc/nginx/conf.d/default.conf" >> /app/start_nginx_wrapper.sh && \
+ echo "echo '--- End of Processed Nginx default.conf ---'" >> /app/start_nginx_wrapper.sh && \
+ echo '' >> /app/start_nginx_wrapper.sh && \
+ echo "# Execute Nginx" >> /app/start_nginx_wrapper.sh && \
+ echo "exec /usr/sbin/nginx -g 'daemon off;'" >> /app/start_nginx_wrapper.sh && \
+ chmod +x /app/start_nginx_wrapper.sh
+
+# REMOVED: The RUN echo command that overwrites the nginx.conf, as we now use a template.
# Expose port
EXPOSE 80
@@ -156,7 +153,8 @@ stderr_logfile_maxbytes=0
priority=5 ; Run before nginx and gunicorn
[program:nginx]
-command=/usr/sbin/nginx ; Run nginx reading default config (with 'daemon off;' added)
+# Command now executes the wrapper script
+command=/app/start_nginx_wrapper.sh
autostart=true
autorestart=true ; Restart nginx if it crashes
startsecs=5 ; Give setup some time before starting nginx
diff --git a/README.md b/README.md
index 538796a..2c35256 100644
--- a/README.md
+++ b/README.md
@@ -31,7 +31,7 @@ Warracker is an open-source warranty tracker application designed to help you ef
- **Centralized Warranty Management:** Track and manage all your product warranties in one place.
- **Detailed Records:** Save essential details like purchase dates, durations, and notes.
-- **Document Storage:** Upload and securely store receipts, invoices, and product manuals.
+- **Document Storage:** Upload and securely store receipts, invoices, product manuals, and other related files (e.g., ZIP, RAR archives).
- **Proactive Alerts:** Visual notifications for active, expiring (customizable from 1 to 365 days), and expired warranties.
- **Quick Search and Filter:** Instantly find warranties by product name, tags, or notes.
- **Notes Support:** Add freeform notes to each warranty for extra context or reminders.
@@ -60,6 +60,7 @@ Warracker is an open-source warranty tracker application designed to help you ef
- **Warranty Management:** Add, edit, and delete warranty information easily.
- **Document Storage:** Upload and manage receipts, invoices, and product manuals securely.
+- **Extended Document Storage:** Securely upload and store additional product-related documents or files in ZIP or RAR format.
- **Status Tracking:** Visual indicators for warranty status (active, expiring soon, expired).
- **Notes:** Add detailed notes for each warranty, viewable and editable via a dedicated notes modal.
- **Search and Tagging:** Find warranties quickly using product names, notes, or multiple tags.
@@ -120,7 +121,7 @@ Warracker is an open-source warranty tracker application designed to help you ef
```
-services:
+ services:
warracker:
image: ghcr.io/sassanix/warracker/main:latest
ports:
@@ -136,6 +137,10 @@ services:
- SMTP_PORT=465
- SMTP_PASSWORD=password
+ - SECRET_KEY=${APP_SECRET_KEY:-your_strong_default_secret_key_here}
+ - MAX_UPLOAD_MB=32 # Example: Set max upload size to 32MB
+ - NGINX_MAX_BODY_SIZE_VALUE=32M # For Nginx, ensure this matches MAX_UPLOAD_MB in concept (e.g., 32M)
+ # - FLASK_DEBUG=0
depends_on:
warrackerdb:
condition: service_healthy
@@ -168,7 +173,7 @@ To get the docker compose file please go [here](https://github.com/sassanix/Warr
### Adding a Warranty
-1. Click add new warranty button then fill in the product details .
+1. Fill in the product details on the left panel.
2. Enter the purchase date and warranty duration.
3. Optionally upload receipt/documentation.
4. Click the "Add Warranty" button.
@@ -179,14 +184,16 @@ To get the docker compose file please go [here](https://github.com/sassanix/Warr
* Click the edit icon to modify warranty details.
* Click the delete icon to remove a warranty.
-## πŸ“¦ Product Information Entry Requirements for import
+## πŸ“¦ Product Information Entry Requirements for CSV import
| Field Name | Format / Example | Required? | Notes |
|----------------|-------------------------------------------|--------------------------------------------------------|-----------------------------------------------------------------------|
| **ProductName** | Text | βœ… Yes | Provide the name of the product. |
| **PurchaseDate** | Date (`YYYY-MM-DD`, e.g., `2024-05-21`) | βœ… Yes | Use ISO format only. |
-| **WarrantyYears** | Whole Number (`1`, `3`, `10`) | βœ… Yes, unless `IsLifetime` is `TRUE` | Must be between `1` and `100` if provided. |
-| **IsLifetime** | `TRUE` or `FALSE` (case-insensitive) | ❌ No (Optional) | If omitted, defaults to `FALSE`. |
+| **WarrantyDurationYears** | Whole Number (`0`, `1`, `5`) | βœ… Yes, if `IsLifetime` is `FALSE` and Months/Days are 0/blank. At least one duration field (Years, Months, Days) must be non-zero if not lifetime. | Represents the years part of the warranty. Can be combined with Months and Days. |
+| **WarrantyDurationMonths** | Whole Number (`0`, `6`, `18`) | βœ… Yes, if `IsLifetime` is `FALSE` and Years/Days are 0/blank. At least one duration field (Years, Months, Days) must be non-zero if not lifetime. | Represents the months part of the warranty. Can be combined with Years and Days. Max 11 if Years also provided. |
+| **WarrantyDurationDays** | Whole Number (`0`, `15`, `90`) | βœ… Yes, if `IsLifetime` is `FALSE` and Years/Months are 0/blank. At least one duration field (Years, Months, Days) must be non-zero if not lifetime. | Represents the days part of the warranty. Can be combined with Years and Months. Max 29/30 if Months also provided. |
+| **IsLifetime** | `TRUE` or `FALSE` (case-insensitive) | ❌ No (Optional) | If omitted, defaults to `FALSE`. If `TRUE`, duration fields are ignored. |
| **PurchasePrice** | Number (`199.99`, `50`) | ❌ No (Optional) | Cannot be negative if provided. |
| **SerialNumber** | Text (`SN123`, `SN123,SN456`) | ❌ No (Optional) | For multiple values, separate with commas. |
| **ProductURL** | Text (URL format) | ❌ No (Optional) | Full URL to product page (optional field). https://producturl.com |
@@ -245,31 +252,15 @@ warracker/
* **Connection Refused Error**: Ensure all containers are running (`docker-compose ps`). Verify the backend is correctly connected to the database.
* **Database Errors**: If schema issues arise, double-check that the database initialization script (`init.sql`) matches the expected schema in `app.py`.
----
-
## 🀝 Contributing
-We welcome contributions and appreciate your interest in improving this project! To get started, please follow these steps:
-
-### How to Contribute
-
-1. **Fork** the repository.
-2. **Create a branch** for your changes:
- `git checkout -b feature/amazing-feature`
-3. **Commit** your changes:
- `git commit -m "Add: amazing feature"`
-4. **Push** to your forked repository:
- `git push origin feature/amazing-feature`
-5. **Open a Pull Request** with a clear explanation of your changes.
-
-### πŸ“Œ Contribution Guidelines
-
-* **Start with an issue**: Before submitting a Pull Request, ensure the change has been discussed in an issue.
-* **Help is welcome**: Check the [issues](../../issues) for open discussions or areas where help is needed.
-* **Keep it focused**: Each Pull Request should focus on a single change or feature.
-* **Follow project style**: Match the project's code style and naming conventions.
-* **Be respectful**: We value inclusive and constructive collaboration.
+Contributions are welcome! We encourage you to submit a Pull Request.
+1. Fork the repository.
+2. Create your feature branch (`git checkout -b feature/amazing-feature`).
+3. Commit your changes (`git commit -m 'Add some amazing feature'`).
+4. Push to the branch (`git push origin feature/amazing-feature`).
+5. Open a Pull Request.
## πŸ“œ License
diff --git a/backend/app.py b/backend/app.py
index 2f9be3f..ff5fc75 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -39,8 +39,21 @@ app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'dev_secret_key_change_i
app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=7) # Token expiration time
UPLOAD_FOLDER = '/data/uploads'
-ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg'}
-MAX_CONTENT_LENGTH = 32 * 1024 * 1024 # 32MB max upload
+ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg', 'zip', 'rar'}
+
+# Default max upload size in MB
+DEFAULT_MAX_UPLOAD_MB = 32
+try:
+ MAX_UPLOAD_MB = int(os.environ.get('MAX_UPLOAD_MB', DEFAULT_MAX_UPLOAD_MB))
+ if MAX_UPLOAD_MB <= 0:
+ MAX_UPLOAD_MB = DEFAULT_MAX_UPLOAD_MB
+ logger.warning(f"MAX_UPLOAD_MB was invalid, defaulting to {DEFAULT_MAX_UPLOAD_MB}MB.")
+except ValueError:
+ MAX_UPLOAD_MB = DEFAULT_MAX_UPLOAD_MB
+ logger.warning(f"MAX_UPLOAD_MB was not a valid integer, defaulting to {DEFAULT_MAX_UPLOAD_MB}MB.")
+
+MAX_CONTENT_LENGTH = MAX_UPLOAD_MB * 1024 * 1024 # Convert MB to bytes
+logger.info(f"Max upload file size set to: {MAX_UPLOAD_MB}MB ({MAX_CONTENT_LENGTH} bytes)")
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH
@@ -771,7 +784,15 @@ def get_warranties():
with conn.cursor() as cur:
# Always fetch warranties belonging to the logged-in user
# Removed the if is_admin: block
- cur.execute('SELECT * FROM warranties WHERE user_id = %s ORDER BY CASE WHEN is_lifetime THEN 1 ELSE 0 END, expiration_date NULLS LAST, product_name', (user_id,))
+ # Replaced warranty_years with warranty_duration_years, warranty_duration_months, warranty_duration_days
+ cur.execute('''
+ SELECT id, product_name, purchase_date, expiration_date, invoice_path, manual_path, other_document_path, product_url, notes,
+ purchase_price, user_id, created_at, updated_at, is_lifetime, vendor,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days
+ FROM warranties
+ WHERE user_id = %s
+ ORDER BY CASE WHEN is_lifetime THEN 1 ELSE 0 END, expiration_date NULLS LAST, product_name
+ ''', (user_id,))
warranties = cur.fetchall()
columns = [desc[0] for desc in cur.description]
@@ -828,18 +849,36 @@ def add_warranty():
# Handle lifetime warranty
is_lifetime = request.form.get('is_lifetime', 'false').lower() == 'true'
- warranty_years = None
expiration_date = None
+ warranty_duration_years = 0
+ warranty_duration_months = 0
+ warranty_duration_days = 0
if not is_lifetime:
- if not request.form.get('warranty_years'):
- return jsonify({"error": "Warranty period (years) is required unless it's a lifetime warranty"}), 400
try:
- warranty_years = float(request.form.get('warranty_years'))
- if warranty_years < 0.1 or warranty_years > 100:
- return jsonify({"error": "Warranty years must be between 0.1 and 100"}), 400
+ # Handle empty strings explicitly, default to 0
+ years_str = request.form.get('warranty_duration_years', '0')
+ months_str = request.form.get('warranty_duration_months', '0')
+ days_str = request.form.get('warranty_duration_days', '0')
+
+ warranty_duration_years = int(years_str) if years_str else 0
+ warranty_duration_months = int(months_str) if months_str else 0
+ warranty_duration_days = int(days_str) if days_str else 0
+
+ if warranty_duration_years < 0 or warranty_duration_months < 0 or warranty_duration_days < 0:
+ return jsonify({"error": "Warranty duration components cannot be negative."}), 400
+ if warranty_duration_months >= 12:
+ return jsonify({"error": "Warranty months must be less than 12."}), 400
+ # Add a reasonable upper limit for days, e.g., 365, though relativedelta handles it.
+ if warranty_duration_days >= 366: # A bit more than a typical month
+ return jsonify({"error": "Warranty days seem too high."}), 400
+ if warranty_duration_years == 0 and warranty_duration_months == 0 and warranty_duration_days == 0:
+ return jsonify({"error": "Warranty duration must be specified for non-lifetime warranties."}), 400
+ if warranty_duration_years > 100: # Keep a reasonable upper limit for years
+ return jsonify({"error": "Warranty years must be 100 or less"}), 400
+
except ValueError:
- return jsonify({"error": "Warranty years must be a valid number"}), 400
+ return jsonify({"error": "Warranty duration components must be valid numbers."}), 400
# Process the data
product_name = request.form['product_name']
@@ -876,24 +915,20 @@ def add_warranty():
return jsonify({"error": "Invalid date format. Use YYYY-MM-DD"}), 400
# Calculate expiration date only if not lifetime
- if not is_lifetime and warranty_years is not None:
- # Decompose fractional years into years, months, days
- try:
- years_float = float(warranty_years)
- total_months_float = years_float * 12
- years_int = int(years_float)
- remaining_months_float = total_months_float - (years_int * 12)
- months_int = int(remaining_months_float)
- # Approximate remaining days based on fraction of a month
- remaining_days_float = (remaining_months_float - months_int) * (365.2425 / 12)
- days_int = int(round(remaining_days_float)) # Round to nearest day
-
- expiration_date = purchase_date + relativedelta(years=years_int, months=months_int, days=days_int)
- logger.info(f"Calculated relativedelta for {warranty_years} years: years={years_int}, months={months_int}, days={days_int}")
- except Exception as calc_err:
- logger.error(f"Error calculating expiration date from warranty_years={warranty_years}: {calc_err}")
- # Fallback or re-raise depending on desired behavior. Let's return error for now.
- return jsonify({"error": "Failed to calculate expiration date from warranty years"}), 500
+ if not is_lifetime:
+ if warranty_duration_years > 0 or warranty_duration_months > 0 or warranty_duration_days > 0:
+ try:
+ expiration_date = purchase_date + relativedelta(
+ years=warranty_duration_years,
+ months=warranty_duration_months,
+ days=warranty_duration_days
+ )
+ logger.info(f"Calculated expiration date: {expiration_date} from years={warranty_duration_years}, months={warranty_duration_months}, days={warranty_duration_days}")
+ except Exception as calc_err:
+ logger.error(f"Error calculating expiration date: {calc_err}")
+ return jsonify({"error": "Failed to calculate expiration date from duration components"}), 500
+ else: # Should have been caught by earlier validation
+ return jsonify({"error": "Warranty duration must be specified for non-lifetime warranties."}), 400
# Handle invoice file upload
db_invoice_path = None
@@ -907,9 +942,15 @@ def add_warranty():
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)
- logger.info(f"New invoice uploaded: {db_invoice_path}")
+ logger.info(f"Attempting to save invoice to: {invoice_path}")
+ try:
+ invoice.save(invoice_path)
+ db_invoice_path = os.path.join('uploads', filename)
+ logger.info(f"Successfully saved invoice: {db_invoice_path}")
+ except Exception as e:
+ logger.error(f"Error saving invoice {filename} to {invoice_path}: {e}")
+ # Optionally, decide if you want to return an error here or continue
+ return jsonify({"error": f"Failed to save invoice: {str(e)}"}), 500
# Handle manual file upload
db_manual_path = None
@@ -922,25 +963,51 @@ def add_warranty():
filename = secure_filename(manual.filename)
filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_manual_{filename}"
manual_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
-
- manual.save(manual_path)
- db_manual_path = os.path.join('uploads', filename)
- logger.info(f"New manual uploaded: {db_manual_path}")
-
+ logger.info(f"Attempting to save manual to: {manual_path}")
+ try:
+ manual.save(manual_path)
+ db_manual_path = os.path.join('uploads', filename)
+ logger.info(f"Successfully saved manual: {db_manual_path}")
+ except Exception as e:
+ logger.error(f"Error saving manual {filename} to {manual_path}: {e}")
+ return jsonify({"error": f"Failed to save manual: {str(e)}"}), 500
+
+ # Handle other_document file upload
+ db_other_document_path = None
+ if 'other_document' in request.files:
+ other_document = request.files['other_document']
+ if other_document.filename != '':
+ if not allowed_file(other_document.filename):
+ return jsonify({"error": "File type not allowed for other document. Use PDF, PNG, JPG, JPEG, ZIP, or RAR"}), 400
+
+ filename = secure_filename(other_document.filename)
+ filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_other_{filename}"
+ other_document_path_on_disk = os.path.join(app.config['UPLOAD_FOLDER'], filename)
+ logger.info(f"Attempting to save other_document to: {other_document_path_on_disk}")
+ try:
+ other_document.save(other_document_path_on_disk)
+ db_other_document_path = os.path.join('uploads', filename)
+ logger.info(f"Successfully saved other_document: {db_other_document_path}")
+ except Exception as e:
+ logger.error(f"Error saving other_document {filename} to {other_document_path_on_disk}: {e}")
+ return jsonify({"error": f"Failed to save other_document: {str(e)}"}), 500
+
# Save to database
conn = get_db_connection()
with conn.cursor() as cur:
# Insert warranty
cur.execute('''
INSERT INTO warranties (
- product_name, purchase_date, warranty_years, expiration_date,
- invoice_path, manual_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor
+ product_name, purchase_date, expiration_date,
+ invoice_path, manual_path, other_document_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days
)
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
''', (
- product_name, purchase_date, warranty_years, expiration_date,
- db_invoice_path, db_manual_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor
+ product_name, purchase_date, expiration_date,
+ db_invoice_path, db_manual_path, db_other_document_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days
))
warranty_id = cur.fetchone()[0]
@@ -1003,12 +1070,13 @@ def delete_warranty(warranty_id):
if not warranty:
return jsonify({"error": "Warranty not found or you don't have permission to delete it"}), 404
- # First get the invoice path to delete the file
- cur.execute('SELECT invoice_path, manual_path FROM warranties WHERE id = %s', (warranty_id,))
+ # First get the file paths to delete the files
+ cur.execute('SELECT invoice_path, manual_path, other_document_path FROM warranties WHERE id = %s', (warranty_id,))
result = cur.fetchone()
invoice_path = result[0]
manual_path = result[1]
+ other_document_path = result[2]
# Delete the warranty from database
cur.execute('DELETE FROM warranties WHERE id = %s', (warranty_id,))
@@ -1027,6 +1095,12 @@ def delete_warranty(warranty_id):
if os.path.exists(full_path):
os.remove(full_path)
+ # Delete the other_document file if it exists
+ if other_document_path:
+ full_path = os.path.join('/data', other_document_path)
+ if os.path.exists(full_path):
+ os.remove(full_path)
+
return jsonify({"message": "Warranty deleted successfully"}), 200
except Exception as e:
@@ -1072,7 +1146,7 @@ def update_warranty(warranty_id):
if not request.form.get('purchase_date'):
return jsonify({"error": "Purchase date is required"}), 400
logger.info(f"Received update request for warranty {warranty_id}")
- logger.info(f"Form data received: is_lifetime={request.form.get('is_lifetime')}, warranty_years={request.form.get('warranty_years')}")
+ logger.info(f"Received update request for warranty {warranty_id}")
is_lifetime = request.form.get('is_lifetime', 'false').lower() == 'true'
logger.info(f"Parsed is_lifetime as: {is_lifetime}")
purchase_date_str = request.form['purchase_date']
@@ -1080,34 +1154,49 @@ def update_warranty(warranty_id):
purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d').date() # Use .date()
except ValueError:
return jsonify({"error": "Invalid date format for purchase date. Use YYYY-MM-DD"}), 400
- warranty_years = None
+
expiration_date = None
+ warranty_duration_years = 0
+ warranty_duration_months = 0
+ warranty_duration_days = 0
+
if not is_lifetime:
- warranty_years_str = request.form.get('warranty_years')
- if not warranty_years_str:
- return jsonify({"error": "Warranty years is required for non-lifetime warranties"}), 400
try:
- warranty_years = float(warranty_years_str)
- if warranty_years < 0.1 or warranty_years > 100:
- return jsonify({"error": "Warranty years must be between 0.1 and 100 for non-lifetime warranties"}), 400
- try:
- years_float = float(warranty_years)
- total_months_float = years_float * 12
- years_int = int(years_float)
- remaining_months_float = total_months_float - (years_int * 12)
- months_int = int(remaining_months_float)
- remaining_days_float = (remaining_months_float - months_int) * (365.2425 / 12)
- days_int = int(round(remaining_days_float)) # Round to nearest day
- expiration_date = purchase_date + relativedelta(years=years_int, months=months_int, days=days_int)
- logger.info(f"Calculated relativedelta for {warranty_years} years: years={years_int}, months={months_int}, days={days_int}")
- except Exception as calc_err:
- logger.error(f"Error calculating expiration date from warranty_years={warranty_years}: {calc_err}")
- return jsonify({"error": "Failed to calculate expiration date from warranty years"}), 500
+ # Handle empty strings explicitly, default to 0
+ years_str = request.form.get('warranty_duration_years', '0')
+ months_str = request.form.get('warranty_duration_months', '0')
+ days_str = request.form.get('warranty_duration_days', '0')
+
+ warranty_duration_years = int(years_str) if years_str else 0
+ warranty_duration_months = int(months_str) if months_str else 0
+ warranty_duration_days = int(days_str) if days_str else 0
+
+ if warranty_duration_years < 0 or warranty_duration_months < 0 or warranty_duration_days < 0:
+ return jsonify({"error": "Warranty duration components cannot be negative."}), 400
+ if warranty_duration_months >= 12:
+ return jsonify({"error": "Warranty months must be less than 12."}), 400
+ if warranty_duration_days >= 366:
+ return jsonify({"error": "Warranty days seem too high."}), 400
+ if warranty_duration_years == 0 and warranty_duration_months == 0 and warranty_duration_days == 0:
+ return jsonify({"error": "Warranty duration must be specified for non-lifetime warranties."}), 400
+ if warranty_duration_years > 100:
+ return jsonify({"error": "Warranty years must be 100 or less"}), 400
+
+ expiration_date = purchase_date + relativedelta(
+ years=warranty_duration_years,
+ months=warranty_duration_months,
+ days=warranty_duration_days
+ )
+ logger.info(f"Calculated expiration date: {expiration_date} from years={warranty_duration_years}, months={warranty_duration_months}, days={warranty_duration_days}")
except ValueError:
- return jsonify({"error": "Warranty years must be a valid number"}), 400
- logger.info(f"Calculated values: warranty_years={warranty_years}, expiration_date={expiration_date}")
+ return jsonify({"error": "Warranty duration components must be valid numbers."}), 400
+ except Exception as calc_err:
+ logger.error(f"Error calculating expiration date: {calc_err}")
+ return jsonify({"error": "Failed to calculate expiration date from duration components"}), 500
+
+ logger.info(f"Calculated values: Y={warranty_duration_years}, M={warranty_duration_months}, D={warranty_duration_days}, expiration_date={expiration_date}")
product_name = request.form['product_name']
- serial_numbers = request.form.getlist('serial_numbers')
+ serial_numbers = request.form.getlist('serial_numbers[]') # Ensure correct parsing for lists
product_url = request.form.get('product_url', '')
notes = request.form.get('notes', None)
vendor = request.form.get('vendor', None)
@@ -1146,9 +1235,14 @@ def update_warranty(warranty_id):
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)
- logger.info(f"New invoice uploaded: {db_invoice_path}")
+ logger.info(f"Attempting to save updated invoice to: {invoice_path}")
+ try:
+ invoice.save(invoice_path)
+ db_invoice_path = os.path.join('uploads', filename)
+ logger.info(f"Successfully saved updated invoice: {db_invoice_path}")
+ except Exception as e:
+ logger.error(f"Error saving updated invoice {filename} to {invoice_path}: {e}")
+ return jsonify({"error": f"Failed to save updated invoice: {str(e)}"}), 500
elif request.form.get('delete_invoice', 'false').lower() == 'true':
cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
old_invoice_path = cur.fetchone()[0]
@@ -1180,9 +1274,14 @@ def update_warranty(warranty_id):
filename = secure_filename(manual.filename)
filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_manual_{filename}"
manual_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
- manual.save(manual_path)
- db_manual_path = os.path.join('uploads', filename)
- logger.info(f"New manual uploaded: {db_manual_path}")
+ logger.info(f"Attempting to save updated manual to: {manual_path}")
+ try:
+ manual.save(manual_path)
+ db_manual_path = os.path.join('uploads', filename)
+ logger.info(f"Successfully saved updated manual: {db_manual_path}")
+ except Exception as e:
+ logger.error(f"Error saving updated manual {filename} to {manual_path}: {e}")
+ return jsonify({"error": f"Failed to save updated manual: {str(e)}"}), 500
elif request.form.get('delete_manual', 'false').lower() == 'true':
cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))
old_manual_path = cur.fetchone()[0]
@@ -1195,11 +1294,54 @@ def update_warranty(warranty_id):
except Exception as e:
logger.error(f"Error deleting manual (delete request): {e}")
db_manual_path = None # Set to None to clear in DB
+
+ db_other_document_path = None
+ if 'other_document' in request.files:
+ other_document = request.files['other_document']
+ if other_document.filename != '':
+ if not allowed_file(other_document.filename):
+ return jsonify({"error": "File type not allowed for other document. Use PDF, PNG, JPG, JPEG, ZIP, or RAR"}), 400
+ cur.execute('SELECT other_document_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_other_document_path = cur.fetchone()[0]
+ if old_other_document_path:
+ full_path = os.path.join('/data', old_other_document_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted old other_document: {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting old other_document: {e}")
+ filename = secure_filename(other_document.filename)
+ filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_other_{filename}"
+ other_document_path_on_disk = os.path.join(app.config['UPLOAD_FOLDER'], filename)
+ logger.info(f"Attempting to save updated other_document to: {other_document_path_on_disk}")
+ try:
+ other_document.save(other_document_path_on_disk)
+ db_other_document_path = os.path.join('uploads', filename)
+ logger.info(f"Successfully saved updated other_document: {db_other_document_path}")
+ except Exception as e:
+ logger.error(f"Error saving updated other_document {filename} to {other_document_path_on_disk}: {e}")
+ return jsonify({"error": f"Failed to save updated other_document: {str(e)}"}), 500
+ elif request.form.get('delete_other_document', 'false').lower() == 'true':
+ cur.execute('SELECT other_document_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_other_document_path = cur.fetchone()[0]
+ if old_other_document_path:
+ full_path = os.path.join('/data', old_other_document_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted other_document (delete request): {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting other_document (delete request): {e}")
+ db_other_document_path = None # Set to None to clear in DB
+
update_params = {
'product_name': product_name,
'purchase_date': purchase_date,
'is_lifetime': is_lifetime,
- 'warranty_years': warranty_years, # Will be None if lifetime
+ 'warranty_duration_years': warranty_duration_years,
+ 'warranty_duration_months': warranty_duration_months,
+ 'warranty_duration_days': warranty_duration_days,
'expiration_date': expiration_date, # Will be None if lifetime
'product_url': product_url,
'purchase_price': purchase_price,
@@ -1223,6 +1365,13 @@ def update_warranty(warranty_id):
sql_values.append(db_manual_path)
elif 'delete_manual' in request.form and request.form.get('delete_manual', 'false').lower() == 'true':
sql_fields.append("manual_path = NULL")
+
+ if db_other_document_path is not None:
+ sql_fields.append("other_document_path = %s")
+ sql_values.append(db_other_document_path)
+ elif 'delete_other_document' in request.form and request.form.get('delete_other_document', 'false').lower() == 'true':
+ sql_fields.append("other_document_path = NULL")
+
sql_fields.append("updated_at = NOW()") # Use SQL function, no parameter needed
sql_values.append(warranty_id)
update_sql = f"UPDATE warranties SET {', '.join(sql_fields)} WHERE id = %s"
@@ -1366,7 +1515,8 @@ def get_statistics():
days_later_for_recent = expiring_soon_date # Same as the expiring soon cutoff
cur.execute(f"""
SELECT
- id, product_name, purchase_date, warranty_years,
+ id, product_name, purchase_date,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days,
expiration_date, invoice_path, manual_path, product_url, purchase_price, is_lifetime
{from_clause}
{where_clause} {active_where if where_clause else 'WHERE'}
@@ -1397,7 +1547,8 @@ def get_statistics():
logger.info(f"Fetching all warranties for user {user_id}...")
cur.execute(f"""
SELECT
- id, product_name, purchase_date, warranty_years,
+ id, product_name, purchase_date,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days,
expiration_date, invoice_path, manual_path, product_url, purchase_price, is_lifetime
{from_clause}
{where_clause}
@@ -2259,48 +2410,71 @@ def serve_file(filename):
def secure_file_access(filename):
"""Enhanced secure file serving with authorization checks."""
try:
- logger.info(f"Secure file access request for {filename} by user {request.user['id']}")
-
+ # ADD EXTRA LOGGING HERE
+ logger.info(f"[SECURE_FILE] Raw filename from route: '{filename}' (len: {len(filename)})")
+ logger.info(f"[SECURE_FILE] repr(filename): {repr(filename)}")
+
# Security check for path traversal
if '..' in filename or filename.startswith('/'):
- logger.warning(f"Potential path traversal attempt detected: {filename} by user {request.user['id']}")
+ logger.warning(f"[SECURE_FILE] Potential path traversal attempt detected: {filename} by user {request.user['id']}")
return jsonify({"message": "Invalid file path"}), 400
-
- # Check if user is authorized to access this file
+
conn = get_db_connection()
try:
with conn.cursor() as cur:
- # Find warranties that reference this file
+ db_search_path = f"uploads/{filename}"
+ logger.info(f"[SECURE_FILE] Searching DB for paths like: '{db_search_path}' (repr: {repr(db_search_path)})")
query = """
- SELECT w.id, w.user_id
- FROM warranties w
- WHERE w.invoice_path = %s OR w.manual_path = %s
+ SELECT w.id, w.user_id
+ FROM warranties w
+ WHERE w.invoice_path = %s OR w.manual_path = %s OR w.other_document_path = %s
"""
- cur.execute(query, (f"uploads/{filename}", f"uploads/{filename}"))
+ cur.execute(query, (db_search_path, db_search_path, db_search_path))
results = cur.fetchall()
-
- # Check if user owns any of these warranties or is admin
+ logger.info(f"[SECURE_FILE] DB query results for '{db_search_path}': {results}")
+
user_id = request.user['id']
is_admin = request.user.get('is_admin', False)
-
- authorized = is_admin # Admins can access all files
-
+ authorized = is_admin
+ logger.info(f"[SECURE_FILE] Initial authorization (is_admin={is_admin}): {authorized}")
+
if not authorized and results:
- for warranty_id, warranty_user_id in results:
- if warranty_user_id == user_id:
+ for warranty_id_db, warranty_user_id_db in results:
+ logger.info(f"[SECURE_FILE] Checking ownership: warranty_id={warranty_id_db}, owner_id={warranty_user_id_db}, current_user_id={user_id}")
+ if warranty_user_id_db == user_id:
authorized = True
+ logger.info(f"[SECURE_FILE] Ownership confirmed for warranty_id={warranty_id_db}")
break
if not authorized:
- logger.warning(f"Unauthorized file access attempt: {filename} by user {user_id}")
+ logger.warning(f"[SECURE_FILE] Unauthorized file access attempt: '{filename}' (repr: {repr(filename)}) by user {user_id}. DB results count: {len(results) if results else 'None'}")
return jsonify({"message": "You are not authorized to access this file"}), 403
- # Serve the file securely
+ logger.info(f"[SECURE_FILE] User {user_id} authorized for file '{filename}'. Attempting to serve from /data/uploads.")
+
+ # Log the exact path that will be checked by send_from_directory
+ # and perform an explicit os.path.isfile check here for comparison
+ target_file_path_for_send = os.path.join('/data/uploads', filename)
+ logger.info(f"[SECURE_FILE] Path for os.path.isfile check (constructed for send_from_directory): '{target_file_path_for_send}' (repr: {repr(target_file_path_for_send)})")
+
+ is_file_check_result = os.path.isfile(target_file_path_for_send)
+ logger.info(f"[SECURE_FILE] os.path.isfile('{target_file_path_for_send}') result: {is_file_check_result}")
+
+ if not is_file_check_result:
+ logger.error(f"[SECURE_FILE] File '{target_file_path_for_send}' not found or not a file by os.path.isfile, despite authorization. This will likely lead to a 404 from send_from_directory.")
+ # Listing directory contents for debugging if file not found
+ try:
+ dir_contents = os.listdir('/data/uploads')
+ logger.info(f"[SECURE_FILE] Contents of /data/uploads: {dir_contents}")
+ except Exception as list_err:
+ logger.error(f"[SECURE_FILE] Error listing /data/uploads: {list_err}")
+
+
return send_from_directory('/data/uploads', filename)
finally:
release_db_connection(conn)
except Exception as e:
- logger.error(f"Error in secure file access for {filename}: {e}")
+ logger.error(f"[SECURE_FILE] Error in secure file access for '{filename}' (repr: {repr(filename)}): {e}", exc_info=True)
return jsonify({"message": "Error accessing file"}), 500
def get_expiring_warranties():
@@ -2889,10 +3063,19 @@ def debug_warranty(warranty_id):
with conn.cursor() as cur:
# If admin, can see any warranty, otherwise only user's warranties
if is_admin:
- cur.execute('SELECT * FROM warranties WHERE id = %s', (warranty_id,))
+ cur.execute('''
+ SELECT id, product_name, purchase_date, expiration_date, invoice_path, manual_path, product_url, notes,
+ purchase_price, user_id, created_at, updated_at, is_lifetime, vendor,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days
+ FROM warranties WHERE id = %s
+ ''', (warranty_id,))
else:
- cur.execute('SELECT * FROM warranties WHERE id = %s AND user_id = %s',
- (warranty_id, user_id))
+ cur.execute('''
+ SELECT id, product_name, purchase_date, expiration_date, invoice_path, manual_path, product_url, notes,
+ purchase_price, user_id, created_at, updated_at, is_lifetime, vendor,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days
+ FROM warranties WHERE id = %s AND user_id = %s
+ ''', (warranty_id, user_id))
warranty = cur.fetchone()
if not warranty:
@@ -3290,13 +3473,12 @@ def add_tags_to_warranty(warranty_id):
release_db_connection(conn)
# --- CSV Import Endpoint ---
-EXPECTED_CSV_HEADERS = [
- 'ProductName', 'PurchaseDate', 'WarrantyYears', 'IsLifetime',
- 'PurchasePrice', 'SerialNumber', 'ProductURL'
-]
-# Add Tags as an optional header
-OPTIONAL_CSV_HEADERS = ['WarrantyYears', 'IsLifetime', 'PurchasePrice', 'SerialNumber', 'ProductURL', 'Tags', 'Vendor'] # Added Vendor
+# Updated CSV Headers for duration components
REQUIRED_CSV_HEADERS = ['ProductName', 'PurchaseDate']
+OPTIONAL_CSV_HEADERS = [
+ 'IsLifetime', 'PurchasePrice', 'SerialNumber', 'ProductURL', 'Tags', 'Vendor',
+ 'WarrantyDurationYears', 'WarrantyDurationMonths', 'WarrantyDurationDays'
+]
@app.route('/api/warranties/import', methods=['POST'])
@token_required
@@ -3350,7 +3532,12 @@ def import_warranties():
product_name = row.get('ProductName', '').strip()
purchase_date_str = row.get('PurchaseDate', '').strip()
is_lifetime_str = row.get('IsLifetime', 'false').strip().lower()
- warranty_years_str = row.get('WarrantyYears', '').strip()
+
+ # New duration fields
+ warranty_duration_years_str = row.get('WarrantyDurationYears', '0').strip()
+ warranty_duration_months_str = row.get('WarrantyDurationMonths', '0').strip()
+ warranty_duration_days_str = row.get('WarrantyDurationDays', '0').strip()
+
purchase_price_str = row.get('PurchasePrice', '').strip()
serial_numbers_str = row.get('SerialNumber', '').strip()
product_url = row.get('ProductURL', '').strip()
@@ -3370,19 +3557,29 @@ def import_warranties():
purchase_date = None # Set to None to prevent further errors
is_lifetime = is_lifetime_str == 'true'
- warranty_years = None
expiration_date = None
+ warranty_duration_years = 0
+ warranty_duration_months = 0
+ warranty_duration_days = 0
if not is_lifetime:
- if not warranty_years_str:
- errors.append("WarrantyYears is required unless IsLifetime is TRUE.")
- else:
- try:
- warranty_years = float(warranty_years_str)
- if warranty_years < 0.1 or warranty_years > 100:
- errors.append("WarrantyYears must be between 0.1 and 100.")
- except ValueError:
- errors.append("WarrantyYears must be a valid number.")
+ try:
+ warranty_duration_years = int(warranty_duration_years_str) if warranty_duration_years_str else 0
+ warranty_duration_months = int(warranty_duration_months_str) if warranty_duration_months_str else 0
+ warranty_duration_days = int(warranty_duration_days_str) if warranty_duration_days_str else 0
+
+ if warranty_duration_years < 0 or warranty_duration_months < 0 or warranty_duration_days < 0:
+ errors.append("Warranty duration components cannot be negative.")
+ if warranty_duration_months >= 12:
+ errors.append("WarrantyDurationMonths must be less than 12.")
+ if warranty_duration_days >= 366: # Basic check
+ errors.append("WarrantyDurationDays seems too high.")
+ if warranty_duration_years == 0 and warranty_duration_months == 0 and warranty_duration_days == 0:
+ errors.append("Warranty duration (Years, Months, or Days) is required unless IsLifetime is TRUE.")
+ if warranty_duration_years > 100:
+ errors.append("WarrantyDurationYears must be 100 or less.")
+ except ValueError:
+ errors.append("WarrantyDurationYears, WarrantyDurationMonths, WarrantyDurationDays must be valid numbers.")
purchase_price = None
if purchase_price_str:
@@ -3394,24 +3591,20 @@ def import_warranties():
errors.append("PurchasePrice must be a valid number.")
# Calculate expiration date if valid
- if not errors and not is_lifetime and warranty_years and purchase_date:
- # Decompose fractional years into years, months, days
- try:
- years_float = float(warranty_years)
- total_months_float = years_float * 12
- years_int = int(years_float)
- remaining_months_float = total_months_float - (years_int * 12)
- months_int = int(remaining_months_float)
- # Approximate remaining days based on fraction of a month
- remaining_days_float = (remaining_months_float - months_int) * (365.2425 / 12)
- days_int = int(round(remaining_days_float)) # Round to nearest day
-
- expiration_date = purchase_date + relativedelta(years=years_int, months=months_int, days=days_int)
- logger.info(f"[Import] Calculated relativedelta for {warranty_years} years: years={years_int}, months={months_int}, days={days_int}")
- except Exception as calc_err:
- logger.error(f"[Import] Error calculating expiration date for row {row_number} from warranty_years={warranty_years}: {calc_err}")
- errors.append("Failed to calculate expiration date from WarrantyYears.")
- expiration_date = None # Ensure expiration_date is None if calculation fails
+ if not errors and not is_lifetime and purchase_date:
+ if warranty_duration_years > 0 or warranty_duration_months > 0 or warranty_duration_days > 0:
+ try:
+ expiration_date = purchase_date + relativedelta(
+ years=warranty_duration_years,
+ months=warranty_duration_months,
+ days=warranty_duration_days
+ )
+ logger.info(f"[Import] Calculated expiration date: {expiration_date} for row {row_number}")
+ except Exception as calc_err:
+ logger.error(f"[Import] Error calculating expiration date for row {row_number}: {calc_err}")
+ errors.append("Failed to calculate expiration date from duration components.")
+ expiration_date = None
+ # No else needed here, error for missing duration already handled
# Split serial numbers
serial_numbers = [sn.strip() for sn in serial_numbers_str.split(',') if sn.strip()] if serial_numbers_str else []
@@ -3491,14 +3684,16 @@ def import_warranties():
# --- Insert into Database ---
cur.execute("""
INSERT INTO warranties (
- product_name, purchase_date, warranty_years, expiration_date,
- product_url, purchase_price, user_id, is_lifetime, vendor
+ product_name, purchase_date, expiration_date,
+ product_url, purchase_price, user_id, is_lifetime, vendor,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days
)
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""", (
- product_name, purchase_date, warranty_years, expiration_date,
- product_url, purchase_price, user_id, is_lifetime, vendor
+ product_name, purchase_date, expiration_date,
+ product_url, purchase_price, user_id, is_lifetime, vendor,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days
))
warranty_id = cur.fetchone()[0]
@@ -3631,4 +3826,3 @@ def reset_password():
finally:
if conn:
release_db_connection(conn)
-
diff --git a/backend/migrations/021_change_warranty_duration_to_components.sql b/backend/migrations/021_change_warranty_duration_to_components.sql
new file mode 100644
index 0000000..e93ce34
--- /dev/null
+++ b/backend/migrations/021_change_warranty_duration_to_components.sql
@@ -0,0 +1,84 @@
+-- Migration: Change warranty_years to separate year, month, and day components (Revised Logic)
+DO $$
+DECLARE
+ warranty_years_exists BOOLEAN;
+BEGIN
+ -- Check if the old warranty_years column exists
+ SELECT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_name = 'warranties' AND column_name = 'warranty_years'
+ ) INTO warranty_years_exists;
+
+ -- Add new columns for duration components if they don't exist
+ ALTER TABLE warranties
+ ADD COLUMN IF NOT EXISTS warranty_duration_years INTEGER,
+ ADD COLUMN IF NOT EXISTS warranty_duration_months INTEGER,
+ ADD COLUMN IF NOT EXISTS warranty_duration_days INTEGER;
+
+ -- Populate new columns ONLY IF warranty_years exists
+ IF warranty_years_exists THEN
+ RAISE NOTICE 'warranty_years column exists. Populating new duration columns...';
+
+ -- Populate from existing warranty_years data where it's not NULL
+ -- This assumes warranty_years was NUMERIC(5,2)
+ UPDATE warranties
+ SET
+ warranty_duration_years = FLOOR(warranty_years),
+ warranty_duration_months = ROUND((warranty_years - FLOOR(warranty_years)) * 12),
+ warranty_duration_days = 0 -- Initialize days to 0 for existing data
+ WHERE warranty_years IS NOT NULL; -- Only for non-lifetime warranties if they used warranty_years
+
+ -- Set default values for new columns for rows where warranty_years might have been NULL
+ -- (e.g., for lifetime warranties)
+ UPDATE warranties
+ SET
+ warranty_duration_years = COALESCE(warranty_duration_years, 0),
+ warranty_duration_months = COALESCE(warranty_duration_months, 0),
+ warranty_duration_days = COALESCE(warranty_duration_days, 0)
+ WHERE is_lifetime = TRUE OR warranty_years IS NULL;
+
+ ELSE
+ RAISE NOTICE 'warranty_years column does not exist. Skipping population based on it.';
+ END IF;
+
+ -- Ensure any remaining NULLs in new columns are set to 0 (covers partial runs or cases where warranty_years was already dropped)
+ RAISE NOTICE 'Ensuring new duration columns have default values...';
+ UPDATE warranties
+ SET
+ warranty_duration_years = COALESCE(warranty_duration_years, 0),
+ warranty_duration_months = COALESCE(warranty_duration_months, 0),
+ warranty_duration_days = COALESCE(warranty_duration_days, 0)
+ WHERE warranty_duration_years IS NULL OR warranty_duration_months IS NULL OR warranty_duration_days IS NULL;
+
+ -- Add NOT NULL constraints and DEFAULT values to the new columns
+ -- These are safe to run even if they already exist (Postgres handles it)
+ RAISE NOTICE 'Applying constraints and defaults to new duration columns...';
+ ALTER TABLE warranties
+ ALTER COLUMN warranty_duration_years SET DEFAULT 0,
+ ALTER COLUMN warranty_duration_years SET NOT NULL,
+ ALTER COLUMN warranty_duration_months SET DEFAULT 0,
+ ALTER COLUMN warranty_duration_months SET NOT NULL,
+ ALTER COLUMN warranty_duration_days SET DEFAULT 0,
+ ALTER COLUMN warranty_duration_days SET NOT NULL;
+
+ -- Add check constraints to ensure non-negative values
+ -- Use IF NOT EXISTS for constraints to make it idempotent
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'chk_warranty_duration_years' AND conrelid = 'warranties'::regclass) THEN
+ ALTER TABLE warranties ADD CONSTRAINT chk_warranty_duration_years CHECK (warranty_duration_years >= 0);
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'chk_warranty_duration_months' AND conrelid = 'warranties'::regclass) THEN
+ ALTER TABLE warranties ADD CONSTRAINT chk_warranty_duration_months CHECK (warranty_duration_months >= 0 AND warranty_duration_months < 12); -- Months should be less than 12
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'chk_warranty_duration_days' AND conrelid = 'warranties'::regclass) THEN
+ ALTER TABLE warranties ADD CONSTRAINT chk_warranty_duration_days CHECK (warranty_duration_days >= 0 AND warranty_duration_days < 366); -- Days reasonable upper limit
+ END IF;
+
+ -- Drop the old warranty_years column ONLY IF it existed at the start
+ IF warranty_years_exists THEN
+ RAISE NOTICE 'Dropping old warranty_years column...';
+ ALTER TABLE warranties DROP COLUMN warranty_years;
+ END IF;
+
+ RAISE NOTICE 'Migration 021 completed successfully.';
+
+END $$;
diff --git a/backend/migrations/022_add_other_document_path.sql b/backend/migrations/022_add_other_document_path.sql
new file mode 100644
index 0000000..5ba4823
--- /dev/null
+++ b/backend/migrations/022_add_other_document_path.sql
@@ -0,0 +1,2 @@
+ALTER TABLE warranties
+ADD COLUMN other_document_path VARCHAR(255) DEFAULT NULL;
diff --git a/frontend/about.html b/frontend/about.html
index 2713186..58131c6 100644
--- a/frontend/about.html
+++ b/frontend/about.html
@@ -106,7 +106,7 @@
<div class="about-container" style="background-color: var(--card-bg); color: var(--text-color); padding: 20px; border-radius: 8px; margin-top: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); width: 100%; box-sizing: border-box;">
<h1 style="color: var(--primary-color); margin-bottom: 20px;">About Warracker</h1>
- <p><strong>Version:</strong> v0.9.9.5</p>
+ <p><strong>Version:</strong> v0.9.9.6</p>
<div id="versionTracker" style="margin-bottom: 20px;">
<p><strong>Update Status:</strong> <span id="updateStatus">Checking for updates...</span></p>
diff --git a/frontend/index.html b/frontend/index.html
index 1fc2799..bfdd895 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -320,9 +320,24 @@
</div>
<!-- End Lifetime Checkbox -->
- <div class="form-group" id="warrantyYearsGroup">
- <label for="warrantyYears">Warranty Period (Years)</label>
- <input type="number" id="warrantyYears" name="warranty_years" class="form-control" min="0.1" max="100" step="any" required>
+ <div id="warrantyDurationFields">
+ <div class="form-group">
+ <label for="warrantyDurationYears">Warranty Period</label>
+ <div class="duration-inputs">
+ <div>
+ <input type="number" id="warrantyDurationYears" name="warranty_duration_years" class="form-control" min="0" max="100" placeholder="Years">
+ <small>Years</small>
+ </div>
+ <div>
+ <input type="number" id="warrantyDurationMonths" name="warranty_duration_months" class="form-control" min="0" max="11" placeholder="Months">
+ <small>Months</small>
+ </div>
+ <div>
+ <input type="number" id="warrantyDurationDays" name="warranty_duration_days" class="form-control" min="0" max="365" placeholder="Days">
+ <small>Days</small>
+ </div>
+ </div>
+ </div>
</div>
<div class="form-group">
@@ -360,6 +375,16 @@
</div>
<div id="manualFileName" class="file-name"></div>
</div>
+ <div class="form-group">
+ <label>Files (ZIP/RAR, Optional)</label>
+ <div class="file-input-wrapper">
+ <label for="otherDocument" class="file-input-label">
+ <i class="fas fa-upload"></i> Choose File
+ </label>
+ <input type="file" id="otherDocument" name="other_document" class="file-input" accept=".zip,.rar">
+ </div>
+ <div id="otherDocumentFileName" class="file-name"></div>
+ </div>
</div>
<!-- Tags Tab -->
<div class="tab-content" id="tags">
@@ -417,7 +442,7 @@
</div>
<div class="summary-item">
<span class="summary-label">Warranty Period:</span>
- <span id="summary-warranty-years" class="summary-value">-</span>
+ <span id="summary-warranty-duration" class="summary-value">-</span>
</div>
<div class="summary-item">
<span class="summary-label">Purchase Price:</span>
@@ -434,6 +459,10 @@
<span class="summary-label">Product Manual:</span>
<span id="summary-manual" class="summary-value">-</span>
</div>
+ <div class="summary-item">
+ <span class="summary-label">Files:</span>
+ <span id="summary-other-document" class="summary-value">-</span>
+ </div>
</div>
<div class="summary-section">
<h4><i class="fas fa-tags"></i> Tags</h4>
@@ -535,9 +564,24 @@
</div>
<!-- End Lifetime Checkbox -->
- <div class="form-group" id="editWarrantyYearsGroup">
- <label for="editWarrantyYears">Warranty Period (Years)</label>
- <input type="number" id="editWarrantyYears" name="warranty_years" class="form-control" min="0.1" max="100" step="any" required>
+ <div id="editWarrantyDurationFields">
+ <div class="form-group">
+ <label for="editWarrantyDurationYears">Warranty Period</label>
+ <div class="duration-inputs">
+ <div>
+ <input type="number" id="editWarrantyDurationYears" name="warranty_duration_years" class="form-control" min="0" max="100" placeholder="Years">
+ <small>Years</small>
+ </div>
+ <div>
+ <input type="number" id="editWarrantyDurationMonths" name="warranty_duration_months" class="form-control" min="0" max="11" placeholder="Months">
+ <small>Months</small>
+ </div>
+ <div>
+ <input type="number" id="editWarrantyDurationDays" name="warranty_duration_days" class="form-control" min="0" max="365" placeholder="Days">
+ <small>Days</small>
+ </div>
+ </div>
+ </div>
</div>
<div class="form-group">
@@ -579,6 +623,18 @@
<div id="currentManual" class="mt-10"></div>
<button type="button" id="deleteManualBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Manual</button>
</div>
+ <div class="form-group">
+ <label>Files (ZIP/RAR, Optional)</label>
+ <div class="file-input-wrapper">
+ <label for="editOtherDocument" class="file-input-label">
+ <i class="fas fa-upload"></i> Choose File
+ </label>
+ <input type="file" id="editOtherDocument" name="other_document" class="file-input" accept=".zip,.rar">
+ </div>
+ <div id="editOtherDocumentFileName" class="file-name"></div>
+ <div id="currentOtherDocument" class="mt-10"></div>
+ <button type="button" id="deleteOtherDocumentBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Files</button>
+ </div>
</div>
<!-- Tags Tab -->
diff --git a/frontend/manifest.json b/frontend/manifest.json
index 82723fa..93d137d 100644
--- a/frontend/manifest.json
+++ b/frontend/manifest.json
@@ -12,4 +12,4 @@
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#ffffff"
-}
\ No newline at end of file
+}
diff --git a/frontend/script.js b/frontend/script.js
index d7b1afd..907a43b 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -42,6 +42,8 @@ const fileInput = document.getElementById('invoice');
const fileName = document.getElementById('fileName');
const manualInput = document.getElementById('manual');
const manualFileName = document.getElementById('manualFileName');
+const otherDocumentInput = document.getElementById('otherDocument');
+const otherDocumentFileName = document.getElementById('otherDocumentFileName');
const editModal = document.getElementById('editModal');
const deleteModal = document.getElementById('deleteModal');
const editWarrantyForm = document.getElementById('editWarrantyForm');
@@ -69,15 +71,21 @@ const existingTagsContainer = document.getElementById('existingTags');
// --- Add near other DOM Element declarations ---
const isLifetimeCheckbox = document.getElementById('isLifetime');
-const warrantyYearsGroup = document.getElementById('warrantyYearsGroup');
-const warrantyYearsInput = document.getElementById('warrantyYears');
+const warrantyDurationFields = document.getElementById('warrantyDurationFields'); // New container
+const warrantyDurationYearsInput = document.getElementById('warrantyDurationYears');
+const warrantyDurationMonthsInput = document.getElementById('warrantyDurationMonths');
+const warrantyDurationDaysInput = document.getElementById('warrantyDurationDays');
+
const editIsLifetimeCheckbox = document.getElementById('editIsLifetime');
-const editWarrantyYearsGroup = document.getElementById('editWarrantyYearsGroup');
-const editWarrantyYearsInput = document.getElementById('editWarrantyYears');
+const editWarrantyDurationFields = document.getElementById('editWarrantyDurationFields'); // New container
+const editWarrantyDurationYearsInput = document.getElementById('editWarrantyDurationYears');
+const editWarrantyDurationMonthsInput = document.getElementById('editWarrantyDurationMonths');
+const editWarrantyDurationDaysInput = document.getElementById('editWarrantyDurationDays');
// Add near other DOM Element declarations
const showAddWarrantyBtn = document.getElementById('showAddWarrantyBtn');
const addWarrantyModal = document.getElementById('addWarrantyModal');
+const serialNumbersContainer = document.getElementById('serialNumbersContainer'); // Ensure this is defined
/**
* Get current user type (admin or user)
@@ -165,7 +173,7 @@ document.addEventListener('DOMContentLoaded', function() {
setupModalTriggers();
// Initialize Tag functionality (assuming tag elements exist)
- if (document.getElementById('tagSearchInput')) {
+ if (document.getElementById('tagSearch')) { // Check for tagSearch instead of non-existent tagSearchInput
initTagFunctionality();
loadTags();
}
@@ -243,8 +251,8 @@ let formTabs = []; // Changed from const to let, initialized as empty
// Removed const tabContentsElements = document.querySelectorAll('.tab-content');
// Removed tabContents assignment here
-const nextButton = document.querySelector('.next-tab'); // Keep these if needed globally, otherwise might remove
-const prevButton = document.querySelector('.prev-tab'); // Keep these if needed globally, otherwise might remove
+// const nextButton = document.querySelector('.next-tab'); // Keep these if needed globally, otherwise might remove
+// const prevButton = document.querySelector('.prev-tab'); // Keep these if needed globally, otherwise might remove
// --- Add near other DOM Element declarations ---
// ... existing code ...
@@ -270,7 +278,10 @@ const prevButton = document.querySelector('.prev-tab'); // Keep these if needed
formData.append('purchase_date', (notesModalWarrantyObj.purchase_date || '').split('T')[0]);
formData.append('is_lifetime', notesModalWarrantyObj.is_lifetime ? 'true' : 'false');
if (!notesModalWarrantyObj.is_lifetime) {
- formData.append('warranty_years', notesModalWarrantyObj.warranty_years || '');
+ // Append duration components instead of warranty_years
+ formData.append('warranty_duration_years', notesModalWarrantyObj.warranty_duration_years || 0);
+ formData.append('warranty_duration_months', notesModalWarrantyObj.warranty_duration_months || 0);
+ formData.append('warranty_duration_days', notesModalWarrantyObj.warranty_duration_days || 0);
}
if (notesModalWarrantyObj.product_url) {
formData.append('product_url', notesModalWarrantyObj.product_url);
@@ -281,11 +292,12 @@ const prevButton = document.querySelector('.prev-tab'); // Keep these if needed
if (notesModalWarrantyObj.serial_numbers && Array.isArray(notesModalWarrantyObj.serial_numbers)) {
notesModalWarrantyObj.serial_numbers.forEach(sn => {
if (sn && sn.trim() !== '') {
- formData.append('serial_numbers', sn);
+ formData.append('serial_numbers[]', sn); // Use [] for arrays
}
});
- } else if (!formData.has('serial_numbers')) {
- formData.append('serial_numbers', JSON.stringify([]));
+ } else if (!formData.has('serial_numbers[]')) {
+ // Send empty array if none exist
+ // formData.append('serial_numbers[]', ''); // Sending empty string might not work as expected, better to not send if empty
}
if (notesModalWarrantyObj.tags && Array.isArray(notesModalWarrantyObj.tags)) {
const tagIds = notesModalWarrantyObj.tags.map(tag => tag.id);
@@ -615,34 +627,23 @@ function updateSummary() {
// --- Handle Lifetime in Summary ---
const isLifetime = isLifetimeCheckbox ? isLifetimeCheckbox.checked : false;
- const warrantyYears = warrantyYearsInput ? warrantyYearsInput.value : null;
- const summaryWarrantyYears = document.getElementById('summary-warranty-years');
+ const summaryWarrantyDuration = document.getElementById('summary-warranty-duration'); // Use new ID
- if (summaryWarrantyYears) {
+ if (summaryWarrantyDuration) {
if (isLifetime) {
- summaryWarrantyYears.textContent = 'Lifetime';
- } else if (warrantyYears) {
- const yearsNum = parseFloat(warrantyYears);
- summaryWarrantyYears.textContent = `${yearsNum} ${yearsNum === 1 ? 'year' : 'years'}`;
+ summaryWarrantyDuration.textContent = 'Lifetime';
} else {
- summaryWarrantyYears.textContent = '-';
- }
- }
-
- // Calculate and display expiration date
- const summaryExpirationDate = document.getElementById('summary-expiration-date');
- if (summaryExpirationDate && purchaseDateStr && warrantyYears) {
- const expirationDate = new Date(Date.UTC(parseInt(purchaseDateStr.split('-')[0]), parseInt(purchaseDateStr.split('-')[1]) - 1, parseInt(purchaseDateStr.split('-')[2])));
- const yearsNum = parseFloat(warrantyYears);
- if (!isNaN(yearsNum)) {
- expirationDate.setFullYear(expirationDate.getFullYear() + Math.floor(yearsNum));
- expirationDate.setMonth(expirationDate.getMonth() + Math.round((yearsNum % 1) * 12));
- summaryExpirationDate.textContent = expirationDate.toLocaleDateString();
- } else {
- summaryExpirationDate.textContent = '-';
+ const years = parseInt(warrantyDurationYearsInput?.value || 0);
+ const months = parseInt(warrantyDurationMonthsInput?.value || 0);
+ const days = parseInt(warrantyDurationDaysInput?.value || 0);
+
+ let durationParts = [];
+ if (years > 0) durationParts.push(`${years} year${years !== 1 ? 's' : ''}`);
+ if (months > 0) durationParts.push(`${months} month${months !== 1 ? 's' : ''}`);
+ if (days > 0) durationParts.push(`${days} day${days !== 1 ? 's' : ''}`);
+
+ summaryWarrantyDuration.textContent = durationParts.length > 0 ? durationParts.join(', ') : '-';
}
- } else if (summaryExpirationDate) {
- summaryExpirationDate.textContent = '-';
}
// Purchase price
@@ -667,6 +668,13 @@ function updateSummary() {
summaryManual.textContent = manualFile ?
manualFile.name : 'No file selected';
}
+
+ const otherDocumentFile = document.getElementById('otherDocument')?.files[0];
+ const summaryOtherDocument = document.getElementById('summary-other-document');
+ if (summaryOtherDocument) {
+ summaryOtherDocument.textContent = otherDocumentFile ?
+ otherDocumentFile.name : 'No file selected';
+ }
// Tags
const summaryTags = document.getElementById('summary-tags');
@@ -726,6 +734,7 @@ function resetForm() {
// Clear any file input displays
fileName.textContent = '';
manualFileName.textContent = '';
+ if (otherDocumentFileName) otherDocumentFileName.textContent = '';
}
async function exportWarranties() {
@@ -769,8 +778,8 @@ async function exportWarranties() {
// Create CSV content
let csvContent = "data:text/csv;charset=utf-8,";
- // Add headers
- csvContent += "Product Name,Purchase Date,Warranty Period,Expiration Date,Status,Serial Numbers,Tags,Vendor\n";
+ // Add headers - Updated for duration components
+ csvContent += "ProductName,PurchaseDate,IsLifetime,WarrantyDurationYears,WarrantyDurationMonths,WarrantyDurationDays,ExpirationDate,Status,PurchasePrice,SerialNumber,ProductURL,Tags,Vendor\n";
// Add data rows
warrantiesToExport.forEach(warranty => {
@@ -784,14 +793,19 @@ async function exportWarranties() {
? warranty.tags.map(tag => tag.name).join(', ')
: '';
- // Format row data
+ // Format row data - Updated for duration components
const row = [
warranty.product_name || '',
formatDate(new Date(warranty.purchase_date)),
- `${warranty.warranty_years || 0} ${warranty.warranty_years === 1 ? 'year' : 'years'}`,
- formatDate(new Date(warranty.expiration_date)),
+ warranty.is_lifetime ? 'TRUE' : 'FALSE',
+ warranty.warranty_duration_years || 0,
+ warranty.warranty_duration_months || 0,
+ warranty.warranty_duration_days || 0,
+ warranty.is_lifetime ? '' : formatDate(new Date(warranty.expiration_date)), // Expiration date empty for lifetime
warranty.status || '',
+ warranty.purchase_price || '',
serialNumbers,
+ warranty.product_url || '',
tags,
warranty.vendor || ''
];
@@ -1122,6 +1136,10 @@ function processWarrantyData(warranty) {
processedWarranty.status = 'active';
processedWarranty.statusText = 'Lifetime';
processedWarranty.daysRemaining = Infinity;
+ // Ensure duration components are 0 for lifetime
+ processedWarranty.warranty_duration_years = 0;
+ processedWarranty.warranty_duration_months = 0;
+ processedWarranty.warranty_duration_days = 0;
} else if (processedWarranty.expirationDate && !isNaN(processedWarranty.expirationDate.getTime())) {
// Existing logic for dated warranties
const expirationDateOnly = new Date(processedWarranty.expirationDate);
@@ -1330,7 +1348,7 @@ function formatDate(date) {
const dayPadded = day.toString().padStart(2, '0');
// Abbreviated month names
- const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const monthAbbr = monthNames[monthIndex];
@@ -1410,7 +1428,22 @@ async function renderWarranties(warrantiesToRender) {
const isLifetime = warranty.is_lifetime;
const statusClass = warranty.status || 'unknown';
const statusText = warranty.statusText || 'Unknown Status';
- const warrantyYearsText = isLifetime ? 'Lifetime' : (warranty.warranty_years !== undefined ? `${warranty.warranty_years} ${warranty.warranty_years === 1 ? 'year' : 'years'}` : 'N/A');
+ // Format warranty duration text
+ let warrantyDurationText = 'N/A';
+ if (isLifetime) {
+ warrantyDurationText = 'Lifetime';
+ } else {
+ const years = warranty.warranty_duration_years || 0;
+ const months = warranty.warranty_duration_months || 0;
+ const days = warranty.warranty_duration_days || 0;
+ let parts = [];
+ if (years > 0) parts.push(`${years} year${years !== 1 ? 's' : ''}`);
+ if (months > 0) parts.push(`${months} month${months !== 1 ? 's' : ''}`);
+ if (days > 0) parts.push(`${days} day${days !== 1 ? 's' : ''}`);
+ if (parts.length > 0) {
+ warrantyDurationText = parts.join(', ');
+ }
+ }
const expirationDateText = isLifetime ? 'Lifetime' : formatDate(expirationDate);
// Make sure serial numbers array exists and is valid
const validSerialNumbers = Array.isArray(warranty.serial_numbers)
@@ -1455,7 +1488,7 @@ async function renderWarranties(warrantiesToRender) {
<div class="warranty-content">
<div class="warranty-info">
<div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
- <div>Warranty: <span>${warrantyYearsText}</span></div>
+ <div>Warranty: <span>${warrantyDurationText}</span></div>
<div>Expires: <span>${expirationDateText}</span></div>
${warranty.purchase_price ? `<div><span>Price: </span><span class="currency-symbol">${symbol}</span><span>${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
${warranty.vendor ? `<div>Vendor: <span>${warranty.vendor}</span></div>` : ''}
@@ -1487,6 +1520,10 @@ async function renderWarranties(warrantiesToRender) {
<a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;" class="manual-link">
<i class="fas fa-book"></i> Manual
</a>` : ''}
+ ${warranty.other_document_path && warranty.other_document_path !== 'null' ? `
+ <a href="#" onclick="openSecureFile('${warranty.other_document_path}'); return false;" class="other-document-link">
+ <i class="fas fa-file-alt"></i> Files
+ </a>` : ''}
${notesLinkHtml}
</div>
</div>
@@ -1509,7 +1546,7 @@ async function renderWarranties(warrantiesToRender) {
<div class="warranty-content">
<div class="warranty-info">
<div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
- <div>Warranty: <span>${warrantyYearsText}</span></div>
+ <div>Warranty: <span>${warrantyDurationText}</span></div>
<div>Expires: <span>${expirationDateText}</span></div>
${warranty.purchase_price ? `<div><span>Price: </span><span class="currency-symbol">${symbol}</span><span>${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
${warranty.vendor ? `<div>Vendor: <span>${warranty.vendor}</span></div>` : ''}
@@ -1541,6 +1578,10 @@ async function renderWarranties(warrantiesToRender) {
<a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;" class="manual-link">
<i class="fas fa-book"></i> Manual
</a>` : ''}
+ ${warranty.other_document_path && warranty.other_document_path !== 'null' ? `
+ <a href="#" onclick="openSecureFile('${warranty.other_document_path}'); return false;" class="other-document-link">
+ <i class="fas fa-file-alt"></i> Files
+ </a>` : ''}
${notesLinkHtml}
</div>
</div>
@@ -1584,6 +1625,10 @@ async function renderWarranties(warrantiesToRender) {
<a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;" class="manual-link">
<i class="fas fa-book"></i> Manual
</a>` : ''}
+ ${warranty.other_document_path && warranty.other_document_path !== 'null' ? `
+ <a href="#" onclick="openSecureFile('${warranty.other_document_path}'); return false;" class="other-document-link">
+ <i class="fas fa-file-alt"></i> Files
+ </a>` : ''}
${notesLinkHtml}
</div>
</div>
@@ -1728,7 +1773,11 @@ function openEditModal(warranty) {
document.getElementById('editProductName').value = warranty.product_name;
document.getElementById('editProductUrl').value = warranty.product_url || '';
document.getElementById('editPurchaseDate').value = warranty.purchase_date.split('T')[0];
- document.getElementById('editWarrantyYears').value = warranty.warranty_years;
+ // Populate new duration fields
+ document.getElementById('editWarrantyDurationYears').value = warranty.warranty_duration_years || 0;
+ document.getElementById('editWarrantyDurationMonths').value = warranty.warranty_duration_months || 0;
+ document.getElementById('editWarrantyDurationDays').value = warranty.warranty_duration_days || 0;
+
document.getElementById('editPurchasePrice').value = warranty.purchase_price || '';
document.getElementById('editVendor').value = warranty.vendor || '';
@@ -1839,12 +1888,40 @@ function openEditModal(warranty) {
deleteManualBtn.style.display = 'none';
};
}
+
+ // Show current other document if exists
+ const currentOtherDocumentElement = document.getElementById('currentOtherDocument');
+ const deleteOtherDocumentBtn = document.getElementById('deleteOtherDocumentBtn');
+ if (currentOtherDocumentElement && deleteOtherDocumentBtn) {
+ if (warranty.other_document_path && warranty.other_document_path !== 'null') {
+ currentOtherDocumentElement.innerHTML = `
+ <span class="text-success">
+ <i class="fas fa-check-circle"></i> Current other document:
+ <a href="#" onclick="openSecureFile('${warranty.other_document_path}'); return false;">View</a>
+ (Upload a new file to replace)
+ </span>
+ `;
+ deleteOtherDocumentBtn.style.display = '';
+ } else {
+ currentOtherDocumentElement.innerHTML = '<span>No other document uploaded</span>';
+ deleteOtherDocumentBtn.style.display = 'none';
+ }
+ // Reset delete state
+ deleteOtherDocumentBtn.dataset.delete = 'false';
+ deleteOtherDocumentBtn.onclick = function() {
+ deleteOtherDocumentBtn.dataset.delete = 'true';
+ currentOtherDocumentElement.innerHTML = '<span class="text-danger">Other document will be deleted on save</span>';
+ deleteOtherDocumentBtn.style.display = 'none';
+ };
+ }
// Reset file inputs
document.getElementById('editInvoice').value = '';
document.getElementById('editManual').value = '';
+ document.getElementById('editOtherDocument').value = '';
document.getElementById('editFileName').textContent = '';
document.getElementById('editManualFileName').textContent = '';
+ document.getElementById('editOtherDocumentFileName').textContent = '';
// Initialize file input event listeners
const editInvoiceInput = document.getElementById('editInvoice');
@@ -1860,6 +1937,13 @@ function openEditModal(warranty) {
updateFileName(event, 'editManual', 'editManualFileName');
});
}
+
+ const editOtherDocumentInput = document.getElementById('editOtherDocument');
+ if (editOtherDocumentInput) {
+ editOtherDocumentInput.addEventListener('change', function(event) {
+ updateFileName(event, 'editOtherDocument', 'editOtherDocumentFileName');
+ });
+ }
// Show edit modal
const modalBackdrop = document.getElementById('editModal');
@@ -1940,8 +2024,8 @@ function openEditModal(warranty) {
});
});
- // --- Set Lifetime Checkbox and Toggle Years Input ---
- if (editIsLifetimeCheckbox && editWarrantyYearsGroup && editWarrantyYearsInput) {
+ // --- Set Lifetime Checkbox and Toggle Duration Fields ---
+ if (editIsLifetimeCheckbox && editWarrantyDurationFields) {
editIsLifetimeCheckbox.checked = warranty.is_lifetime || false;
handleEditLifetimeChange(); // Call handler to set initial state
@@ -1950,10 +2034,18 @@ function openEditModal(warranty) {
// Add new listener
editIsLifetimeCheckbox.addEventListener('change', handleEditLifetimeChange);
- // Set years value only if NOT lifetime
- editWarrantyYearsInput.value = warranty.is_lifetime ? '' : (warranty.warranty_years || '');
+ // Set duration values only if NOT lifetime
+ if (!warranty.is_lifetime) {
+ document.getElementById('editWarrantyDurationYears').value = warranty.warranty_duration_years || 0;
+ document.getElementById('editWarrantyDurationMonths').value = warranty.warranty_duration_months || 0;
+ document.getElementById('editWarrantyDurationDays').value = warranty.warranty_duration_days || 0;
+ } else {
+ document.getElementById('editWarrantyDurationYears').value = '';
+ document.getElementById('editWarrantyDurationMonths').value = '';
+ document.getElementById('editWarrantyDurationDays').value = '';
+ }
} else {
- console.error("Lifetime warranty elements not found in edit form");
+ console.error("Lifetime warranty elements or duration fields not found in edit form");
}
// Set notes
@@ -1996,6 +2088,10 @@ function validateFileSize(formData, maxSizeMB = 32) {
if (formData.has('manual') && formData.get('manual').size > 0) {
totalSize += formData.get('manual').size;
}
+
+ if (formData.has('other_document') && formData.get('other_document').size > 0) {
+ totalSize += formData.get('other_document').size;
+ }
// Convert bytes to MB for comparison and display
const totalSizeMB = totalSize / (1024 * 1024);
@@ -2015,16 +2111,25 @@ function validateFileSize(formData, maxSizeMB = 32) {
}
// Submit form function - event handler for form submit
-function submitForm(event) {
+function handleFormSubmit(event) { // Renamed from submitForm
event.preventDefault();
- // --- Add Lifetime Check ---
- if (!isLifetimeCheckbox.checked && (!warrantyYearsInput.value || parseFloat(warrantyYearsInput.value) <= 0)) {
- showToast('Warranty period (years) is required and must be greater than 0 unless it\'s a lifetime warranty', 'error');
+ const isLifetime = isLifetimeCheckbox.checked;
+ const years = parseInt(warrantyDurationYearsInput.value || 0);
+ const months = parseInt(warrantyDurationMonthsInput.value || 0);
+ const days = parseInt(warrantyDurationDaysInput.value || 0);
+
+ // --- Updated Lifetime Check ---
+ if (!isLifetime && years === 0 && months === 0 && days === 0) {
+ showToast('Warranty duration (years, months, or days) is required unless it\'s a lifetime warranty', 'error');
switchToTab(1); // Switch to warranty details tab
- warrantyYearsInput.focus();
- warrantyYearsInput.classList.add('invalid');
+ // Optionally focus the first duration input
+ if (warrantyDurationYearsInput) warrantyDurationYearsInput.focus();
+ // Add invalid class to the container or individual inputs if needed
+ if (warrantyDurationFields) warrantyDurationFields.classList.add('invalid-duration'); // Example
return;
+ } else {
+ if (warrantyDurationFields) warrantyDurationFields.classList.remove('invalid-duration');
}
// Validate all tabs
@@ -2039,11 +2144,21 @@ function submitForm(event) {
// Create form data object
const formData = new FormData(warrantyForm);
- // Add serial numbers to form data
- const serialInputs = document.querySelectorAll('#serialNumbersContainer input');
+ // Remove old warranty_years if it exists in formData (it shouldn't if HTML is correct)
+ formData.delete('warranty_years');
+
+ // Append new duration fields (already handled by FormData constructor if names match)
+ // formData.append('warranty_duration_years', years);
+ // formData.append('warranty_duration_months', months);
+ // formData.append('warranty_duration_days', days);
+
+ // Add serial numbers to form data (using correct name 'serial_numbers[]')
+ const serialInputs = document.querySelectorAll('#serialNumbersContainer input[name="serial_numbers[]"]');
+ // Clear existing serial_numbers[] from formData before appending new ones
+ formData.delete('serial_numbers[]');
serialInputs.forEach(input => {
if (input.value.trim()) {
- formData.append('serial_numbers', input.value.trim());
+ formData.append('serial_numbers[]', input.value.trim()); // Use [] for arrays
}
});
@@ -2051,12 +2166,27 @@ function submitForm(event) {
if (selectedTags && selectedTags.length > 0) {
const tagIds = selectedTags.map(tag => tag.id);
formData.append('tag_ids', JSON.stringify(tagIds));
+ } else {
+ formData.append('tag_ids', JSON.stringify([])); // Send empty array if no tags
}
// --- Ensure is_lifetime is correctly added ---
+ // FormData already includes it if the checkbox is checked. If not checked, it's omitted.
+ // We need to explicitly add 'false' if it's not checked.
if (!isLifetimeCheckbox.checked) {
formData.append('is_lifetime', 'false');
+ } else {
+ // Ensure duration fields are 0 if lifetime is checked
+ formData.set('warranty_duration_years', '0');
+ formData.set('warranty_duration_months', '0');
+ formData.set('warranty_duration_days', '0');
}
+
+ // Add other_document file
+ const otherDocumentFile = document.getElementById('otherDocument').files[0];
+ if (otherDocumentFile) {
+ formData.append('other_document', otherDocumentFile);
+ }
// Show loading spinner
showLoadingSpinner();
@@ -2127,7 +2257,7 @@ document.addEventListener('DOMContentLoaded', function() {
// Setup form submission
const form = document.getElementById('addWarrantyForm');
if (form) {
- form.addEventListener('submit', handleFormSubmit);
+ form.addEventListener('submit', handleFormSubmit); // Use renamed handler
}
// Setup settings menu toggle
@@ -2231,8 +2361,13 @@ function openSecureFile(filePath) {
console.log('Opening secure file:', filePath);
- // Get the file name from the path
- const fileName = filePath.split('/').pop();
+ // Get the file name from the path, handling both uploads/ prefix and direct filenames
+ let fileName = filePath;
+ if (filePath.startsWith('uploads/')) {
+ fileName = filePath.substring(8); // Remove 'uploads/' prefix
+ } else if (filePath.startsWith('/uploads/')) {
+ fileName = filePath.substring(9); // Remove '/uploads/' prefix
+ }
// Get auth token
const token = window.auth.getToken();
@@ -2250,7 +2385,13 @@ function openSecureFile(filePath) {
})
.then(response => {
if (!response.ok) {
- throw new Error(`Error: ${response.status} ${response.statusText}`);
+ if (response.status === 404) {
+ throw new Error('File not found. It may have been deleted or moved.');
+ } else if (response.status === 401) {
+ throw new Error('Authentication error. Please log in again.');
+ } else {
+ throw new Error(`Error: ${response.status} ${response.statusText}`);
+ }
}
return response.blob();
})
@@ -2291,21 +2432,27 @@ function initWarrantyForm() {
updateFileName(event, 'manual', 'manualFileName');
});
}
+
+ if (document.getElementById('otherDocument')) {
+ document.getElementById('otherDocument').addEventListener('change', function(event) {
+ updateFileName(event, 'otherDocument', 'otherDocumentFileName');
+ });
+ }
// Initialize tag functionality
initTagFunctionality();
// Form submission
if (warrantyForm) {
- warrantyForm.addEventListener('submit', submitForm);
+ warrantyForm.addEventListener('submit', handleFormSubmit); // Use renamed handler
}
// Initialize lifetime checkbox listener
- if (isLifetimeCheckbox && warrantyYearsGroup && warrantyYearsInput) {
+ if (isLifetimeCheckbox && warrantyDurationFields) { // Check for new container
isLifetimeCheckbox.addEventListener('change', handleLifetimeChange);
handleLifetimeChange(); // Initial check
} else {
- console.error("Lifetime warranty elements not found in add form");
+ console.error("Lifetime warranty elements or duration fields not found in add form");
}
}
@@ -3142,7 +3289,10 @@ function saveWarranty() {
const productName = document.getElementById('editProductName').value.trim();
const purchaseDate = document.getElementById('editPurchaseDate').value;
const isLifetime = document.getElementById('editIsLifetime').checked;
- const warrantyYears = document.getElementById('editWarrantyYears').value; // Declare only once
+ // Get new duration values
+ const years = parseInt(document.getElementById('editWarrantyDurationYears').value || 0);
+ const months = parseInt(document.getElementById('editWarrantyDurationMonths').value || 0);
+ const days = parseInt(document.getElementById('editWarrantyDurationDays').value || 0);
// Basic validation
if (!productName) {
@@ -3155,20 +3305,21 @@ function saveWarranty() {
return;
}
- // --- Modified Validation ---
- if (!isLifetime) {
- if (!warrantyYears || parseFloat(warrantyYears) <= 0) {
- showToast('Warranty period (years) must be greater than 0 for non-lifetime warranties', 'error');
- // Optional: focus the years input again
- const yearsInput = document.getElementById('editWarrantyYears');
- if (yearsInput) { // Check if element exists
- yearsInput.focus();
- yearsInput.classList.add('invalid');
- }
- return;
+ // --- Updated Validation ---
+ if (!isLifetime && years === 0 && months === 0 && days === 0) {
+ showToast('Warranty duration (years, months, or days) is required unless it\'s a lifetime warranty', 'error');
+ // Optional: focus the years input again
+ const yearsInput = document.getElementById('editWarrantyDurationYears');
+ if (yearsInput) { // Check if element exists
+ yearsInput.focus();
+ // Add invalid class to container or inputs
+ if (editWarrantyDurationFields) editWarrantyDurationFields.classList.add('invalid-duration');
}
+ return;
+ } else {
+ if (editWarrantyDurationFields) editWarrantyDurationFields.classList.remove('invalid-duration');
}
- // --- End Modified Validation ---
+ // --- End Updated Validation ---
// Create form data
const formData = new FormData();
@@ -3186,11 +3337,13 @@ function saveWarranty() {
formData.append('purchase_price', purchasePrice);
}
- // Serial numbers
- const serialInputs = document.querySelectorAll('#editSerialNumbersContainer input');
+ // Serial numbers (use correct name 'serial_numbers[]')
+ const serialInputs = document.querySelectorAll('#editSerialNumbersContainer input[name="serial_numbers[]"]');
+ // Clear existing before appending
+ formData.delete('serial_numbers[]');
serialInputs.forEach(input => {
if (input.value.trim()) {
- formData.append('serial_numbers', input.value.trim());
+ formData.append('serial_numbers[]', input.value.trim()); // Use []
}
});
@@ -3213,6 +3366,11 @@ function saveWarranty() {
if (manualFile) {
formData.append('manual', manualFile);
}
+
+ const otherDocumentFile = document.getElementById('editOtherDocument').files[0];
+ if (otherDocumentFile) {
+ formData.append('other_document', otherDocumentFile);
+ }
// Document deletion flags
const deleteInvoiceBtn = document.getElementById('deleteInvoiceBtn');
@@ -3223,11 +3381,22 @@ function saveWarranty() {
if (deleteManualBtn && deleteManualBtn.dataset.delete === 'true') {
formData.append('delete_manual', 'true');
}
+ const deleteOtherDocumentBtn = document.getElementById('deleteOtherDocumentBtn');
+ if (deleteOtherDocumentBtn && deleteOtherDocumentBtn.dataset.delete === 'true') {
+ formData.append('delete_other_document', 'true');
+ }
- // --- Append is_lifetime and warranty_years ---
+ // --- Append is_lifetime and duration components ---
formData.append('is_lifetime', isLifetime.toString());
if (!isLifetime) {
- formData.append('warranty_years', warrantyYears);
+ formData.append('warranty_duration_years', years);
+ formData.append('warranty_duration_months', months);
+ formData.append('warranty_duration_days', days);
+ } else {
+ // Ensure duration is 0 if lifetime
+ formData.append('warranty_duration_years', 0);
+ formData.append('warranty_duration_months', 0);
+ formData.append('warranty_duration_days', 0);
}
// Add notes
const notes = document.getElementById('editNotes').value;
@@ -3327,39 +3496,66 @@ function populateTagFilter() {
});
}
-// --- Add New Function ---
+// --- Updated Function ---
function handleLifetimeChange(event) {
const checkbox = event ? event.target : isLifetimeCheckbox;
- const group = warrantyYearsGroup;
- const input = warrantyYearsInput;
+ const durationFields = warrantyDurationFields; // Use new container ID
+ const yearsInput = warrantyDurationYearsInput;
+ const monthsInput = warrantyDurationMonthsInput;
+ const daysInput = warrantyDurationDaysInput;
- if (!checkbox || !group || !input) return;
+ if (!checkbox || !durationFields || !yearsInput || !monthsInput || !daysInput) {
+ console.error("Lifetime or duration elements not found in add form");
+ return;
+ }
if (checkbox.checked) {
- group.style.display = 'none';
- input.required = false;
- input.value = '';
+ durationFields.style.display = 'none';
+ // Clear and make duration fields not required
+ yearsInput.required = false;
+ monthsInput.required = false;
+ daysInput.required = false;
+ yearsInput.value = '';
+ monthsInput.value = '';
+ daysInput.value = '';
} else {
- group.style.display = 'block';
- input.required = true;
+ durationFields.style.display = 'block';
+ // Make duration fields required (or handle validation differently)
+ // Note: Backend validation ensures at least one is > 0 if not lifetime
+ yearsInput.required = false; // Let backend handle combined validation
+ monthsInput.required = false;
+ daysInput.required = false;
}
}
-// --- Add New Function ---
+// --- Updated Function ---
function handleEditLifetimeChange(event) {
const checkbox = event ? event.target : editIsLifetimeCheckbox;
- const group = editWarrantyYearsGroup;
- const input = editWarrantyYearsInput;
+ const durationFields = editWarrantyDurationFields; // Use new container ID
+ const yearsInput = editWarrantyDurationYearsInput;
+ const monthsInput = editWarrantyDurationMonthsInput;
+ const daysInput = editWarrantyDurationDaysInput;
- if (!checkbox || !group || !input) return;
+ if (!checkbox || !durationFields || !yearsInput || !monthsInput || !daysInput) {
+ console.error("Lifetime or duration elements not found in edit form");
+ return;
+ }
if (checkbox.checked) {
- group.style.display = 'none';
- input.required = false;
- input.value = '';
+ durationFields.style.display = 'none';
+ // Clear and make duration fields not required
+ yearsInput.required = false;
+ monthsInput.required = false;
+ daysInput.required = false;
+ yearsInput.value = '';
+ monthsInput.value = '';
+ daysInput.value = '';
} else {
- group.style.display = 'block';
- input.required = true;
+ durationFields.style.display = 'block';
+ // Make duration fields required (or handle validation differently)
+ yearsInput.required = false; // Let backend handle combined validation
+ monthsInput.required = false;
+ daysInput.required = false;
}
}
@@ -3379,7 +3575,8 @@ function resetAddWarrantyWizard() {
// Reset file input displays
if (fileName) fileName.textContent = '';
- if (manualFileName) fileName.textContent = '';
+ if (manualFileName) manualFileName.textContent = '';
+ if (otherDocumentFileName) otherDocumentFileName.textContent = '';
// Reset selected tags
selectedTags = [];
@@ -3397,7 +3594,8 @@ function resetAddWarrantyWizard() {
// Reset file input displays
if (fileName) fileName.textContent = '';
- if (manualFileName) fileName.textContent = '';
+ if (manualFileName) manualFileName.textContent = '';
+ if (otherDocumentFileName) otherDocumentFileName.textContent = '';
// Reset selected tags
selectedTags = [];
@@ -3703,6 +3901,16 @@ function showNotesModal(notes, warrantyOrId = null) {
showToast('No warranty selected for note update', 'error');
return;
}
+
+ // Frontend check for invalid duration before attempting to save notes
+ if (!notesModalWarrantyObj.is_lifetime &&
+ (parseInt(notesModalWarrantyObj.warranty_duration_years) || 0) === 0 &&
+ (parseInt(notesModalWarrantyObj.warranty_duration_months) || 0) === 0 &&
+ (parseInt(notesModalWarrantyObj.warranty_duration_days) || 0) === 0) {
+ showToast('Cannot save notes: The warranty has an invalid duration. Please edit the full warranty details to set a valid duration first.', 'error', 7000); // Longer toast duration
+ return; // Prevent API call
+ }
+
// Save note via API, sending all required fields
try {
showLoadingSpinner();
@@ -3713,7 +3921,10 @@ function showNotesModal(notes, warrantyOrId = null) {
formData.append('purchase_date', (notesModalWarrantyObj.purchase_date || '').split('T')[0]);
formData.append('is_lifetime', notesModalWarrantyObj.is_lifetime ? 'true' : 'false');
if (!notesModalWarrantyObj.is_lifetime) {
- formData.append('warranty_years', notesModalWarrantyObj.warranty_years || ''); // Use empty string if null/undefined
+ // Append duration components instead of warranty_years
+ formData.append('warranty_duration_years', notesModalWarrantyObj.warranty_duration_years || 0);
+ formData.append('warranty_duration_months', notesModalWarrantyObj.warranty_duration_months || 0);
+ formData.append('warranty_duration_days', notesModalWarrantyObj.warranty_duration_days || 0);
}
if (notesModalWarrantyObj.product_url) {
formData.append('product_url', notesModalWarrantyObj.product_url);
@@ -3721,17 +3932,17 @@ function showNotesModal(notes, warrantyOrId = null) {
if (notesModalWarrantyObj.purchase_price !== null && notesModalWarrantyObj.purchase_price !== undefined) { // Check for null/undefined
formData.append('purchase_price', notesModalWarrantyObj.purchase_price);
}
+ // Correctly append serial numbers
if (notesModalWarrantyObj.serial_numbers && Array.isArray(notesModalWarrantyObj.serial_numbers)) {
notesModalWarrantyObj.serial_numbers.forEach(sn => {
- if (sn && sn.trim() !== '') {
- formData.append('serial_numbers', sn);
+ // Ensure sn is treated as a string before trim, and append with [] for array
+ if (sn && String(sn).trim() !== '') {
+ formData.append('serial_numbers[]', String(sn).trim());
}
});
}
- // Send empty array if no serial numbers exist or are provided
- else if (!formData.has('serial_numbers')) {
- formData.append('serial_numbers', JSON.stringify([]));
- }
+ // If notesModalWarrantyObj.serial_numbers is empty or not an array,
+ // no 'serial_numbers[]' fields will be appended, which is typically interpreted as an empty list by backends.
if (notesModalWarrantyObj.tags && Array.isArray(notesModalWarrantyObj.tags)) {
const tagIds = notesModalWarrantyObj.tags.map(tag => tag.id);
diff --git a/frontend/settings-redirect.html b/frontend/settings-redirect.html
deleted file mode 100644
index 353b7d8..0000000
--- a/frontend/settings-redirect.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="refresh" content="0;url=settings-new.html">
- <title>Redirecting to Settings</title>
- <script src="theme-loader.js"></script> <!-- Apply theme early -->
- <style>
- body {
- font-family: Arial, sans-serif;
- text-align: center;
- padding: 50px;
- background-color: #f5f5f5;
- }
- .container {
- max-width: 600px;
- margin: 0 auto;
- background-color: white;
- padding: 30px;
- border-radius: 8px;
- box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
- }
- h1 {
- color: #333;
- }
- p {
- color: #666;
- margin-bottom: 20px;
- }
- a {
- color: #007bff;
- text-decoration: none;
- }
- a:hover {
- text-decoration: underline;
- }
- </style>
-</head>
-<body>
- <div class="container">
- <h1>Redirecting to Settings</h1>
- <p>You are being redirected to the new settings page.</p>
- <p>If you are not redirected automatically, <a href="settings-new.html">click here</a>.</p>
- </div>
- <script>
- // JavaScript redirect as a fallback
- window.location.href = "settings-new.html";
- </script>
-</body>
-</html>
\ No newline at end of file
diff --git a/frontend/settings.html b/frontend/settings.html
deleted file mode 100644
index 9308013..0000000
--- a/frontend/settings.html
+++ /dev/null
@@ -1,54 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="refresh" content="0;url=settings-new.html">
- <title>Redirecting to Settings</title>
- <style>
- body {
- font-family: Arial, sans-serif;
- text-align: center;
- padding: 50px;
- background-color: #f5f5f5;
- }
- .container {
- max-width: 600px;
- margin: 0 auto;
- background-color: white;
- padding: 30px;
- border-radius: 8px;
- box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
- }
- h1 {
- color: #333;
- }
- p {
- color: #666;
- margin-bottom: 20px;
- }
- a {
- color: #007bff;
- text-decoration: none;
- }
- a:hover {
- text-decoration: underline;
- }
- </style>
- <link rel="stylesheet" href="settings-styles.css">
- <script src="theme-loader.js"></script> <!-- Apply theme early -->
-
- <!-- Font Awesome -->
-</head>
-<body>
- <div class="container">
- <h1>Redirecting to Settings</h1>
- <p>You are being redirected to the new settings page.</p>
- <p>If you are not redirected automatically, <a href="settings-new.html">click here</a>.</p>
- </div>
- <script>
- // JavaScript redirect as a fallback
- window.location.href = "settings-new.html";
- </script>
-</body>
-</html>
\ No newline at end of file
diff --git a/frontend/settings.js b/frontend/settings.js
deleted file mode 100644
index 84099f2..0000000
--- a/frontend/settings.js
+++ /dev/null
@@ -1,518 +0,0 @@
-// DOM Elements
-const darkModeToggle = document.getElementById('darkModeToggle');
-const darkModeToggleSetting = document.getElementById('darkModeToggleSetting');
-const defaultViewSelect = document.getElementById('defaultView');
-const emailNotificationsToggle = document.getElementById('emailNotifications');
-const saveProfileBtn = document.getElementById('saveProfileBtn');
-const savePreferencesBtn = document.getElementById('savePreferencesBtn');
-const changePasswordBtn = document.getElementById('changePasswordBtn');
-const passwordChangeForm = document.getElementById('passwordChangeForm');
-const savePasswordBtn = document.getElementById('savePasswordBtn');
-const cancelPasswordBtn = document.getElementById('cancelPasswordBtn');
-const deleteAccountBtn = document.getElementById('deleteAccountBtn');
-const deleteAccountModal = document.getElementById('deleteAccountModal');
-const deleteConfirmInput = document.getElementById('deleteConfirmInput');
-const confirmDeleteAccountBtn = document.getElementById('confirmDeleteAccountBtn');
-const passwordSuccessModal = document.getElementById('passwordSuccessModal');
-const loadingContainer = document.getElementById('loadingContainer');
-const toastContainer = document.getElementById('toastContainer');
-
-// Form fields
-const firstNameInput = document.getElementById('firstName');
-const lastNameInput = document.getElementById('lastName');
-const emailInput = document.getElementById('email');
-const currentPasswordInput = document.getElementById('currentPassword');
-const newPasswordInput = document.getElementById('newPassword');
-const confirmPasswordInput = document.getElementById('confirmPassword');
-
-// Initialize settings page
-document.addEventListener('DOMContentLoaded', () => {
- // Check authentication
- if (window.auth) {
- window.auth.checkAuthState();
-
- // Redirect to login if not authenticated
- if (!window.auth.isAuthenticated()) {
- window.location.href = 'login.html';
- return;
- }
- } else {
- // Auth module not loaded
- console.error('Auth module not loaded');
- window.location.href = 'login.html';
- return;
- }
-
- // Load user data and preferences
- loadUserData();
- loadPreferences();
-
- // Setup event listeners
- setupEventListeners();
-
- // Initialize modals
- initModals();
-});
-
-/**
- * Load user data from localStorage and API
- */
-async function loadUserData() {
- showLoading();
-
- try {
- // Get user from localStorage first
- const currentUser = window.auth.getCurrentUser();
-
- if (currentUser) {
- // Populate form fields
- firstNameInput.value = currentUser.first_name || '';
- lastNameInput.value = currentUser.last_name || '';
- emailInput.value = currentUser.email || '';
- }
-
- // Fetch fresh user data from API
- const response = await fetch('/api/auth/user', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`
- }
- });
-
- if (response.ok) {
- const userData = await response.json();
-
- // Update form fields with fresh data
- firstNameInput.value = userData.first_name || '';
- lastNameInput.value = userData.last_name || '';
- emailInput.value = userData.email || '';
-
- // Update localStorage
- localStorage.setItem('user_info', JSON.stringify(userData));
- } else {
- // Handle error
- const errorData = await response.json();
- showToast(errorData.message || 'Failed to load user data', 'error');
- }
- } catch (error) {
- console.error('Error loading user data:', error);
- showToast('Failed to load user data. Please try again.', 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Load user preferences from localStorage
- */
-function loadPreferences() {
- // Load dark mode preference
- const darkMode = localStorage.getItem('darkMode') === 'true';
- darkModeToggle.checked = darkMode;
- darkModeToggleSetting.checked = darkMode;
-
- // Load default view preference
- const defaultView = localStorage.getItem('defaultView') || 'grid';
- defaultViewSelect.value = defaultView;
-
- // Load email notifications preference (default to true if not set)
- const emailNotifications = localStorage.getItem('emailNotifications') !== 'false';
- emailNotificationsToggle.checked = emailNotifications;
-}
-
-/**
- * Setup event listeners for the settings page
- */
-function setupEventListeners() {
- // Dark mode toggle
- darkModeToggle.addEventListener('change', () => {
- const isDark = darkModeToggle.checked;
- setTheme(isDark);
- darkModeToggleSetting.checked = isDark;
- });
-
- darkModeToggleSetting.addEventListener('change', () => {
- const isDark = darkModeToggleSetting.checked;
- setTheme(isDark);
- darkModeToggle.checked = isDark;
- });
-
- // Save profile button
- saveProfileBtn.addEventListener('click', saveProfile);
-
- // Save preferences button
- savePreferencesBtn.addEventListener('click', savePreferences);
-
- // Change password button
- changePasswordBtn.addEventListener('click', () => {
- passwordChangeForm.style.display = 'block';
- changePasswordBtn.style.display = 'none';
- });
-
- // Cancel password change
- cancelPasswordBtn.addEventListener('click', () => {
- passwordChangeForm.style.display = 'none';
- changePasswordBtn.style.display = 'block';
- resetPasswordForm();
- });
-
- // Save password button
- savePasswordBtn.addEventListener('click', changePassword);
-
- // Delete account button
- deleteAccountBtn.addEventListener('click', () => {
- openModal(deleteAccountModal);
- });
-
- // Delete confirm input
- deleteConfirmInput.addEventListener('input', () => {
- confirmDeleteAccountBtn.disabled = deleteConfirmInput.value !== 'DELETE';
- });
-
- // Confirm delete account button
- confirmDeleteAccountBtn.addEventListener('click', deleteAccount);
-}
-
-/**
- * Initialize modals
- */
-function initModals() {
- // Close modal when clicking on X or outside
- document.querySelectorAll('.close-btn, [data-dismiss="modal"]').forEach(closeBtn => {
- closeBtn.addEventListener('click', () => {
- document.querySelectorAll('.modal-backdrop').forEach(modal => {
- modal.style.display = 'none';
- });
-
- // Reset delete confirm input
- if (deleteConfirmInput) {
- deleteConfirmInput.value = '';
- confirmDeleteAccountBtn.disabled = true;
- }
-
- // Reset password form
- resetPasswordForm();
- });
- });
-
- // Close modal when clicking outside
- window.addEventListener('click', (event) => {
- document.querySelectorAll('.modal-backdrop').forEach(modal => {
- if (event.target === modal) {
- modal.style.display = 'none';
-
- // Reset delete confirm input
- if (deleteConfirmInput) {
- deleteConfirmInput.value = '';
- confirmDeleteAccountBtn.disabled = true;
- }
-
- // Reset password form
- resetPasswordForm();
- }
- });
- });
-}
-
-/**
- * Open a modal
- * @param {HTMLElement} modal - The modal to open
- */
-function openModal(modal) {
- modal.style.display = 'flex';
-}
-
-/**
- * Reset password form
- */
-function resetPasswordForm() {
- currentPasswordInput.value = '';
- newPasswordInput.value = '';
- confirmPasswordInput.value = '';
-}
-
-/**
- * Set theme (dark/light)
- * @param {boolean} isDark - Whether to use dark mode
- */
-function setTheme(isDark) {
- document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');
- localStorage.setItem('darkMode', isDark);
-}
-
-/**
- * Save user profile
- */
-async function saveProfile() {
- // Validate form
- if (!firstNameInput.value.trim() || !lastNameInput.value.trim()) {
- showToast('Please fill in all required fields', 'error');
- return;
- }
-
- showLoading();
-
- try {
- // Try to update profile via API
- try {
- const response = await fetch('/api/auth/profile', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- first_name: firstNameInput.value.trim(),
- last_name: lastNameInput.value.trim()
- })
- });
-
- if (response.ok) {
- const userData = await response.json();
-
- // Update localStorage
- const currentUser = window.auth.getCurrentUser();
- const updatedUser = {
- ...currentUser,
- first_name: userData.first_name,
- last_name: userData.last_name
- };
-
- localStorage.setItem('user_info', JSON.stringify(updatedUser));
-
- // Update UI
- if (window.auth.checkAuthState) {
- window.auth.checkAuthState();
- }
-
- showToast('Profile updated successfully', 'success');
- } else {
- // Handle error from API
- const errorData = await response.json();
- throw new Error(errorData.message || 'Failed to update profile');
- }
- } catch (apiError) {
- console.warn('API error, falling back to localStorage:', apiError);
-
- // Fallback to localStorage if API is not available
- const currentUser = window.auth.getCurrentUser();
- if (currentUser) {
- const updatedUser = {
- ...currentUser,
- first_name: firstNameInput.value.trim(),
- last_name: lastNameInput.value.trim()
- };
-
- localStorage.setItem('user_info', JSON.stringify(updatedUser));
-
- // Update UI
- if (window.auth.checkAuthState) {
- window.auth.checkAuthState();
- }
-
- showToast('Profile updated successfully (offline mode)', 'success');
- } else {
- throw new Error('User not found in localStorage');
- }
- }
- } catch (error) {
- console.error('Error updating profile:', error);
- showToast('Failed to update profile. Please try again.', 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Save user preferences
- */
-function savePreferences() {
- // Save dark mode
- const isDark = darkModeToggle.checked;
- setTheme(isDark);
-
- // Save default view
- localStorage.setItem('defaultView', defaultViewSelect.value);
-
- // Save email notifications
- localStorage.setItem('emailNotifications', emailNotificationsToggle.checked);
-
- showToast('Preferences saved successfully', 'success');
-}
-
-/**
- * Change user password
- */
-async function changePassword() {
- // Validate form
- if (!currentPasswordInput.value || !newPasswordInput.value || !confirmPasswordInput.value) {
- showToast('Please fill in all password fields', 'error');
- return;
- }
-
- if (newPasswordInput.value !== confirmPasswordInput.value) {
- showToast('New passwords do not match', 'error');
- return;
- }
-
- // Validate password strength
- if (newPasswordInput.value.length < 8) {
- showToast('Password must be at least 8 characters long', 'error');
- return;
- }
-
- showLoading();
-
- try {
- try {
- const response = await fetch('/api/auth/password/change', {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- current_password: currentPasswordInput.value,
- new_password: newPasswordInput.value
- })
- });
-
- if (response.ok) {
- // Reset form and hide it
- resetPasswordForm();
- passwordChangeForm.style.display = 'none';
- changePasswordBtn.style.display = 'block';
-
- // Show success modal
- openModal(passwordSuccessModal);
- } else {
- // Handle error
- const errorData = await response.json();
- throw new Error(errorData.message || 'Failed to change password');
- }
- } catch (apiError) {
- console.warn('API error, showing offline message:', apiError);
- showToast('Password cannot be changed in offline mode', 'warning');
- }
- } catch (error) {
- console.error('Error changing password:', error);
- showToast('Failed to change password. Please try again.', 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Delete user account
- */
-async function deleteAccount() {
- if (deleteConfirmInput.value !== 'DELETE') {
- showToast('Please type DELETE to confirm', 'error');
- return;
- }
-
- showLoading();
-
- try {
- try {
- const response = await fetch('/api/auth/account', {
- method: 'DELETE',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`
- }
- });
-
- if (response.ok) {
- // Clear auth data
- if (window.auth.logout) {
- window.auth.logout();
- } else {
- localStorage.removeItem('auth_token');
- localStorage.removeItem('user_info');
- }
-
- // Show success message
- showToast('Account deleted successfully', 'success');
-
- // Redirect to home page after a short delay
- setTimeout(() => {
- window.location.href = 'index.html';
- }, 2000);
- } else {
- // Handle error
- const errorData = await response.json();
- throw new Error(errorData.message || 'Failed to delete account');
- }
- } catch (apiError) {
- console.warn('API error, showing offline message:', apiError);
- showToast('Account cannot be deleted in offline mode', 'warning');
- }
- } catch (error) {
- console.error('Error deleting account:', error);
- showToast('Failed to delete account. Please try again.', 'error');
- } finally {
- hideLoading();
-
- // Close modal
- deleteAccountModal.style.display = 'none';
-
- // Reset delete confirm input
- deleteConfirmInput.value = '';
- confirmDeleteAccountBtn.disabled = true;
- }
-}
-
-/**
- * Show loading spinner
- */
-function showLoading() {
- loadingContainer.style.display = 'flex';
-}
-
-/**
- * Hide loading spinner
- */
-function hideLoading() {
- loadingContainer.style.display = 'none';
-}
-
-/**
- * Show toast message
- * @param {string} message - Message to display
- * @param {string} type - Toast type (success, error, info, warning)
- */
-function showToast(message, type = 'info') {
- const toast = document.createElement('div');
- toast.className = `toast toast-${type}`;
-
- const icon = document.createElement('i');
- switch (type) {
- case 'success':
- icon.className = 'fas fa-check-circle';
- break;
- case 'error':
- icon.className = 'fas fa-exclamation-circle';
- break;
- case 'warning':
- icon.className = 'fas fa-exclamation-triangle';
- break;
- default:
- icon.className = 'fas fa-info-circle';
- }
-
- const messageSpan = document.createElement('span');
- messageSpan.textContent = message;
-
- toast.appendChild(icon);
- toast.appendChild(messageSpan);
-
- toastContainer.appendChild(toast);
-
- // Remove toast after 5 seconds
- setTimeout(() => {
- toast.classList.add('toast-fade-out');
- setTimeout(() => {
- toastContainer.removeChild(toast);
- }, 300);
- }, 5000);
-}
\ No newline at end of file
diff --git a/frontend/style.css b/frontend/style.css
index af6a573..2f0a6de 100644
--- a/frontend/style.css
+++ b/frontend/style.css
@@ -1711,7 +1711,7 @@ tr.status-expiring {
border-top: 1px solid var(--border-color);
}
-.invoice-link, .manual-link, .product-link, .notes-link { /* Added .notes-link here */
+.invoice-link, .manual-link, .product-link, .notes-link, .other-document-link { /* Added .notes-link here */
display: inline-flex; /* Remove !important */
align-items: center !important; /* Keep important if needed for vertical icon align */
color: var(--primary-color) !important; /* Keep appearance */
@@ -1726,12 +1726,12 @@ tr.status-expiring {
white-space: nowrap !important; /* Keep appearance */
}
-.invoice-link i, .manual-link i, .product-link i, .notes-link i { /* Added .notes-link here */
+.invoice-link i, .manual-link i, .product-link i, .notes-link i, .other-document-link i { /* Added .notes-link here */
margin-right: 5px !important;
font-size: 1rem !important;
}
-.invoice-link:hover, .manual-link:hover, .product-link:hover, .notes-link:hover {
+.invoice-link:hover, .manual-link:hover, .product-link:hover, .notes-link:hover, .other-document-link:hover {
text-decoration: none !important;
background-color: var(--medium-gray) !important;
color: var(--primary-dark) !important;
@@ -2707,26 +2707,27 @@ input.invalid {
}
@media (max-width: 768px) {
- .edit-tabs-nav {
- justify-content: space-between;
- }
-
- .edit-tab-btn {
- padding: 0.5rem;
- font-size: 0.85rem;
- }
-
- .edit-tab-btn i {
- margin-right: 0.25rem;
- }
+ .document-links-row .notes-link,
+ .document-links-row .invoice-link,
+ .document-links-row .manual-link,
+ .document-links-row .product-link,
+ .document-links-row .other-document-link {
+ margin-right: 5px !important;
+ margin-left: 0 !important;
+ }
}
-#editModal .modal-body {
- background-color: var(--modal-background, #ffffff);
- padding: 1.5rem;
- padding-top: 0.5rem;
- max-height: 70vh;
- overflow-y: auto;
+@media (max-width: 768px) {
+ .document-links-row {
+ display: flex !important;
+ flex-direction: column !important;
+ align-items: center !important;
+ gap: 5px !important;
+ }
+ .invoice-link, .manual-link, .product-link, .notes-link, .other-document-link {
+ width: auto !important;
+ justify-content: center !important;
+ }
}
.edit-tab-content {
@@ -2953,11 +2954,42 @@ input.invalid {
accent-color: var(--primary-color);
}
-/* Style for the warranty years group when hidden */
-#warrantyYearsGroup[style*="display: none"],
-#editWarrantyYearsGroup[style*="display: none"] {
+/* Style for the warranty duration fields container */
+.duration-inputs {
+ display: flex;
+ gap: 15px; /* Adjust spacing between inputs */
+ align-items: flex-start; /* Align items to the top */
+}
+
+.duration-inputs > div {
+ flex: 1; /* Allow each input group to take equal space */
+ display: flex;
+ flex-direction: column; /* Stack input and label vertically */
+ align-items: center; /* Center items horizontally within their div */
+}
+
+.duration-inputs input[type="number"].form-control {
+ text-align: center; /* Center the number inside the input */
+ margin-bottom: 5px; /* Space between input and label */
+ /* Inherits padding, border, etc. from .form-control */
+}
+
+.duration-inputs small {
+ font-size: 0.85rem;
+ color: var(--dark-gray);
+}
+
+/* Style for the warranty duration group when hidden (due to lifetime checkbox) */
+#warrantyDurationFields[style*="display: none"],
+#editWarrantyDurationFields[style*="display: none"] {
opacity: 0.5;
transition: opacity 0.3s ease;
+ /* Optionally add height transition if needed */
+ /* max-height: 0; */
+ /* overflow: hidden; */
+ /* padding-top: 0; */
+ /* padding-bottom: 0; */
+ /* margin-bottom: 0; */
}
/* Add CSS for the tags cell in table view */
diff --git a/frontend/version-checker.js b/frontend/version-checker.js
index dac9588..920334f 100644
--- a/frontend/version-checker.js
+++ b/frontend/version-checker.js
@@ -1,6 +1,6 @@
// Version checker for Warracker
document.addEventListener('DOMContentLoaded', () => {
- const currentVersion = '0.9.9.5'; // Current version of the application
+ const currentVersion = '0.9.9.6'; // Current version of the application
const updateStatus = document.getElementById('updateStatus');
const updateLink = document.getElementById('updateLink');
diff --git a/nginx.conf b/nginx.conf
index 35155d8..b07097f 100644
--- a/nginx.conf
+++ b/nginx.conf
@@ -2,8 +2,8 @@ server {
listen 80;
listen [::]:80;
server_name localhost;
- # Point root to the frontend directory where static assets reside
- root /d/Project/warracker/Warracker Beta/frontend;
+ # Point root to the frontend directory where static assets reside inside the container
+ root /var/www/html;
index index.html;
# Enable detailed error logging
@@ -13,7 +13,7 @@ server {
# Global settings
gzip on;
gzip_types text/plain text/css application/javascript application/json;
- client_max_body_size 32M;
+ client_max_body_size __NGINX_MAX_BODY_SIZE_CONFIG_VALUE__; # Configurable global limit
# Add CORS headers globally
add_header 'Access-Control-Allow-Origin' '*';
@@ -34,13 +34,14 @@ server {
}
# API requests - proxy to backend (fixed upstream host)
- location /api/ {
- proxy_pass http://127.0.0.1:5000/;
+ # Using ^~ to ensure this prefix match takes precedence over regex extension matches
+ location ^~ /api/ {
+ proxy_pass http://127.0.0.1:5000; # Removed trailing slash to pass /api/ prefix
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;
- client_max_body_size 32M;
+ client_max_body_size __NGINX_MAX_BODY_SIZE_CONFIG_VALUE__; # Configurable limit for API location
# Pass Authorization header to backend
proxy_set_header Authorization $http_authorization;