Skip to content

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

Fix Apprise notification system, scheduler stability, and email configuration

sassanix60239bd637ad
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..274ea4d
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,13 @@
+# .dockerignore
+
+# Ignore git files
+.git
+.gitignore
+
+# Ignore developer scripts and tools
+scripts/
+
+# Ignore local development files
+*.pyc
+__pycache__/
+.env
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d4f04d5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,74 @@
+# --- Python ---
+# Byte-compiled / optimized / C extension files
+__pycache__/
+*.pyc
+*.pyo
+*.pyd
+
+# Distribution / packaging
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# Virtual Environments
+.env/
+.venv/
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# --- Project-Specific ---
+
+# Environment variables
+# CRITICAL: This file contains secrets and should NEVER be committed.
+# An example file (.env.example) should be used as a template instead.
+.env
+
+# User-uploaded files (receipts, manuals, photos)
+# This directory is stateful data and does not belong in version control.
+/uploads/
+
+# Docker-managed volumes for persistent data
+# These are stateful and should not be committed.
+/postgres_data/
+/warracker_uploads/
+
+# Developer/diagnostic scripts, not part of the core application.
+scripts/
+
+# --- IDE / Editor Configuration ---
+.idea/
+.vscode/
+*.swp
+*~
+
+# --- OS-generated files ---
+# macOS
+.DS_Store
+.AppleDouble
+.LSOverride
+
+# Windows
+Thumbs.db
+ehthumbs.db
+ehthumbs_vista.db
+*.stackdump
+
+# --- Log files ---
+*.log
+logs/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a647a2e..95dae03 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,7 +1,1178 @@
# Changelog
-## [0.9.9.8] - 2025-05-24
+## 0.10.1.9 - 2025-08-24
+
+### Fixed
+- **Critical Apprise Notification Fixes - RESOLVED ✅:** Successfully resolved five critical issues that were preventing scheduled Apprise notifications from being sent:
+ - **Configuration Reload Issue:** Added `apprise_handler.reload_configuration()` call in scheduled notification process to ensure the handler uses the latest settings from the database instead of stale startup configuration. This fixes the issue where enabling Apprise via the UI wouldn't trigger scheduled notifications.
+ - **Data Fetching Logic Issue:** Removed restrictive `email_notifications` filter from the `get_expiring_warranties` SQL query that was preventing Apprise-only users from receiving notifications. The query now correctly fetches expiring warranties for all active users regardless of their notification channel preference.
+ - **Notification Dispatch Logic Issue:** Completely refactored the `send_expiration_notifications` function to properly separate email and Apprise notification logic. The previous implementation failed to pass warranty data to the Apprise handler even when users were correctly identified as eligible. The new implementation uses dedicated helper functions (`is_notification_due`, `process_email_notifications`, `process_apprise_notifications`) that ensure warranty data flows correctly to both notification channels.
+ - **Handler Scope Issue:** Fixed the issue where the scheduled notification process was checking a local, uninitialized `apprise_handler` variable instead of the properly configured handler from the Flask application context. Modified `process_apprise_notifications()` to retrieve the handler using `current_app.config.get('APPRISE_HANDLER')`, ensuring the scheduler uses the same fully initialized instance as the rest of the application.
+ - **Application Context Issue:** Fixed the final critical issue where the background scheduler was executing jobs outside of the Flask application context, causing "Working outside of application context" errors. Modified `init_scheduler()` to accept the Flask app instance and wrap the scheduled job with `app.app_context()`, ensuring the background task has access to all application configurations and services. Updated all calls to `init_scheduler()` in `backend/__init__.py` and `backend/app.py` to pass the app object.
+ - **✅ VERIFICATION COMPLETE:** All fixes have been successfully implemented and tested. Scheduled Apprise notifications now work correctly for users configured with "Apprise only" or "Both" notification channels. The notification system is fully operational, production-ready, and follows Flask best practices for background task integration. Email notifications remain unaffected and continue to work as expected.
+ - _Files: `backend/notifications.py`, `backend/__init__.py`, `backend/app.py`_
+
+- **Email Configuration Enhancement:** Added support for `SMTP_FROM_ADDRESS` environment variable to allow customization of the email From address independently of the SMTP username. This provides better flexibility for email configuration, especially when using email services where the authentication username differs from the desired sender address. ([#115](https://github.com/clmcavaney/warracker/pull/115))
+ - _Files: `backend/notifications.py`_
+
+- **Critical Fix for Duplicate Scheduled Notifications:** Fixed critical issue where multiple identical notifications were being sent in 'optimized' and 'performance' modes due to multiple worker processes each running their own notification scheduler. The `should_run_scheduler()` function contained flawed logic with unsafe defaults that allowed multiple workers to incorrectly identify as the primary worker, leading to redundant schedulers and duplicate notifications.
+ - **Root Cause:** The function had multiple problematic fallback conditions including defaulting `GUNICORN_WORKER_ID` to '0' when not set, causing all workers to think they were the primary worker.
+ - **Solution:** Simplified and strengthened the logic to only allow worker ID '0' to run the scheduler, with no unsafe fallbacks. The function now strictly checks for `GUNICORN_WORKER_ID == '0'` and defaults to not running the scheduler if the worker ID cannot be determined.
+ - **Impact:** Users will now receive exactly one notification per scheduled event regardless of the memory mode (ultra-light, optimized, or performance). System efficiency is improved by eliminating redundant background processes.
+ - _Files: `backend/notifications.py`_
+
+- **Critical Fix for Scheduler Database Connection Handling:** Fixed critical issue where scheduled notifications were failing due to stale database connections that timed out between job executions, causing "server closed the connection unexpectedly" errors. The background scheduler was attempting to reuse database connections that had been closed by the server, preventing the notification process from fetching users and warranties.
+ - **Root Cause:** The scheduled job was not properly managing database connection lifecycle, leading to attempts to use stale connections that had timed out between job runs.
+ - **Solution:** Refactored the `send_expiration_notifications()` function to acquire a fresh database connection at the start of each job execution and ensure its proper release in a try/finally block. The connection is now managed for the entire job duration, preventing stale connection issues.
+ - **Impact:** Scheduled notifications (both Email and Apprise) now execute reliably without database connection errors. The notification system is more stable and robust for long-running background processes.
+ - _Files: `backend/notifications.py`_
+
+- **Definitive Fix for Notification Scheduler Logic Across All Memory Modes:** Fixed critical issue where the notification scheduler logic was not robust enough to handle all Gunicorn memory modes, resulting in either no notifications in single-worker mode ('ultra-light') or potential issues in multi-worker modes. The `should_run_scheduler()` function failed to properly distinguish between single-worker and multi-worker environments.
+ - **Root Cause:** The function incorrectly treated the absence of `GUNICORN_WORKER_ID` environment variable as a reason to NOT run the scheduler, when in single-worker mode this variable is not set and the scheduler should run.
+ - **Solution:** Implemented explicit logic to handle two distinct cases: (1) Multi-worker environment where `worker_id` is set - only worker '0' runs scheduler, (2) Single-worker environment where `worker_id` is None - the single worker must run the scheduler.
+ - **Impact:** The notification scheduler now works reliably across all memory modes: 'ultra-light' (single worker), 'optimized' (2 workers), and 'performance' (4 workers). Exactly one scheduler instance runs regardless of configuration, ensuring consistent notification delivery.
+ - _Files: `backend/notifications.py`_
+
+## 0.10.1.8 - 2025-07-22
+
+### Fixed
+- **Notification System Initialization:** Fixed critical issue where warranty expiration notifications were not working due to scheduler initialization failures in Docker ultra-light mode.
+ - **Root Cause:** The notification scheduler initialization code was located in `backend/app.py` but Gunicorn was using the application factory pattern from `backend/__init__.py`, causing the scheduler to never be initialized. Additionally, the scheduler detection logic incorrectly identified single-worker ultra-light mode as multi-worker, preventing scheduler startup. Missing API endpoints `/api/timezones` and `/api/locales` were causing frontend errors and preventing proper settings configuration.
+ - **Solution:** Moved scheduler initialization into the `create_app()` factory function to ensure it runs during application startup. Enhanced `should_run_scheduler()` detection logic to properly handle ultra-light mode with single sync worker. Added missing `/api/timezones` endpoint returning timezone data grouped by region (including America/Halifax) and `/api/locales` endpoint returning supported languages. Fixed timezone API to return array format expected by frontend and removed authentication requirement from locales endpoint for public access. Implemented comprehensive memory mode compatibility ensuring scheduler works correctly across all deployment configurations.
+ - **Impact:** Notification scheduler now properly initializes and runs in all Docker memory modes (ultra-light, optimized, and performance). In multi-worker modes, only worker-0 runs the scheduler to prevent conflicts and resource waste. Automatic warranty expiration notifications work correctly, checking every 2 minutes for warranties to notify about. Settings page timezone and language dropdowns now load properly. Admin "Check Scheduler Status" button shows `scheduler_running: true` and active notification jobs. Manual notification testing via admin panel now functions correctly across all memory configurations.
+ - _Files: `backend/__init__.py`, `backend/notifications.py`, `backend/warranties_routes.py`_
+
+- **Mobile Button Text Overflow:** Fixed an issue where the "Manage Tags" button text would overflow on smaller mobile screens. The text is now hidden on screens narrower than 480px, showing only the icon to save space.
+ - _Files: `frontend/mobile-header.css`_
+
+ - **Mobile List View Optimization:** Fixed oversized warranty cards in list view on mobile browsers that were causing poor user experience with excessive scrolling and large interface elements.
+ - **Root Cause:** The list view was using desktop-sized elements on mobile devices, including 180px × 180px product images, excessive padding, and large text that made warranty cards too large for mobile viewports.
+ - **Solution:** Implemented comprehensive mobile-specific CSS optimizations with progressive size reduction across different screen sizes. Added responsive image sizing (80px → 60px → 50px for 768px → 480px → 360px screens), reduced card spacing and padding, optimized text and icon sizes, changed warranty info layout from horizontal to vertical on mobile, and disabled hover transforms that caused layout jumping on touch devices.
+ - **Impact:** Warranty cards in list view are now significantly more compact and mobile-friendly. Users can now comfortably browse warranties on mobile devices without excessive scrolling. The interface adapts progressively to different mobile screen sizes while maintaining full functionality and readability.
+ - _Files: `frontend/mobile-header.css`, `frontend/style.css`_
+
+## 0.10.1.7 - 2025-07-20
+
+### Fixed
+- **Configuration Precedence Fix:** Fixed critical issue where environment variables were being ignored in favor of database settings on fresh installations, preventing proper configuration of OIDC, Apprise, and email settings via environment variables.
+ - **Root Cause:** The configuration loading logic was checking database settings first, and since migration scripts insert default values (e.g., `oidc_enabled: 'false'`), the code would use these database values instead of checking environment variables. This violated the expected precedence hierarchy and made it impossible to configure the application via `.env` files on fresh deployments. Additionally, the `/api/auth/oidc-status` endpoint was not using the same precedence logic, causing the frontend to show "SSO is not enabled" even when users configured OIDC in the GUI but had conflicting environment variables.
+ - **Solution:** Updated configuration loading in `init_oidc_client()`, `_load_configuration()`, email base URL handling, and OIDC status endpoint to follow proper precedence: Environment Variable > Database Setting > Hardcoded Default. Fixed all OIDC settings (`OIDC_ENABLED`, `OIDC_PROVIDER_NAME`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, `OIDC_ISSUER_URL`, `OIDC_SCOPE`), all Apprise settings (`APPRISE_ENABLED`, `APPRISE_URLS`, `APPRISE_EXPIRATION_DAYS`, `APPRISE_NOTIFICATION_TIME`, `APPRISE_TITLE_PREFIX`), and email base URL (`APP_BASE_URL`) to check environment variables first using proper `if env_var is not None:` logic. Updated the `get_oidc_status_route()` function to apply the same precedence logic as the backend initialization.
+ - **Impact:** Environment variables now take precedence over database settings as expected. Fresh installations can be properly configured using Docker `.env` files. OIDC SSO, Apprise notifications, and email links now work correctly when configured via environment variables. The frontend SSO button now correctly reflects the actual OIDC configuration state. Existing deployments using database settings continue to work unchanged.
+ - _Files: `backend/__init__.py`, `backend/apprise_handler.py`, `backend/auth_routes.py`, `backend/notifications.py`, `backend/oidc_handler.py`_
+
+- **PostgreSQL Migration Permission Fix:** Fixed migration failures on standard PostgreSQL user setups that don't have `CREATEROLE` privileges, preventing application startup with error "keine Berechtigung, um Rolle zu ändern" (no permission to alter role).
+ - **Root Cause:** Migrations `009z_grant_createrole_to_db_user.sql`, `010_configure_admin_roles.sql`, and `011_ensure_admin_permissions.sql` were attempting to grant `CREATEROLE` privileges and create admin roles, but these operations require superuser or `CREATEROLE` privileges that standard database users don't have. This caused migration failures on secure, standard PostgreSQL setups.
+ - **Solution:** Updated all role management migrations to use PostgreSQL `DO` blocks with exception handling. The migrations now attempt advanced role operations but gracefully continue with informative notices if permissions are insufficient. Core application functionality is preserved while optional advanced features are skipped when permissions don't allow them.
+ - **Impact:** Applications can now successfully start and run on standard PostgreSQL user setups without requiring elevated database privileges. The application works fully with basic user permissions while optional role management features are gracefully disabled when not available. Migration errors no longer prevent application startup.
+ - _Files: `backend/migrations/009z_grant_createrole_to_db_user.sql`, `backend/migrations/010_configure_admin_roles.sql`, `backend/migrations/011_ensure_admin_permissions.sql`_
+
+- **Warranty Routes Refactoring:** Extracted all warranty-related functionality from main application file into dedicated Flask Blueprint for improved code organization and maintainability.
+ - **Root Cause:** Warranty routes were contained within the main `app.py` file, making the codebase monolithic and harder to maintain as the application grew.
+ - **Solution:** Created new `warranties_routes.py` Blueprint containing all 9 warranty routes including CRUD operations, CSV import, global view, and tag management. Updated route decorators from `@app.route()` to `@warranties_bp.route()`, registered blueprint with `/api` prefix, and resolved import issues for both Docker and development environments.
+ - **Impact:** Reduced main application file by ~1,500 lines of code while maintaining 100% API compatibility. Warranty functionality is now properly isolated in a 1,589-line dedicated module, making future maintenance and feature development easier.
+ - _Files: `backend/warranties_routes.py` (new), `backend/app.py`, `Dockerfile`_
+
+- **Admin Routes Refactoring:** Extracted all administrative functionality from main application file into dedicated Flask Blueprint for improved code organization and maintainability.
+ - **Root Cause:** Admin routes were scattered throughout the main `app.py` file, making the codebase harder to maintain and reducing code modularity.
+ - **Solution:** Created new `admin_routes.py` Blueprint containing all 16 admin routes including user management, site settings, notifications, and Apprise integration. Updated route decorators from `@app.route()` to `@admin_bp.route()`, registered blueprint with `/api/admin` prefix, and ensured proper import handling for both Docker and development environments.
+ - **Impact:** Reduced main application file by ~635 lines of code while maintaining 100% API compatibility. Admin functionality is now properly isolated and modularized, making future maintenance and feature development easier.
+ - _Files: `backend/admin_routes.py` (new), `backend/app.py`, `Dockerfile`_
+
+- **Statistics Routes Refactoring:** Extracted statistics functionality from main application file into dedicated Flask Blueprint for improved code organization and maintainability.
+ - **Root Cause:** Statistics routes were embedded within the main `app.py` file, contributing to a monolithic codebase structure.
+ - **Solution:** Created new `statistics_routes.py` Blueprint containing both statistics routes (`/api/statistics` and `/api/statistics/global`) along with the `convert_decimals()` helper function. Updated route decorators from `@app.route()` to `@statistics_bp.route()`, registered blueprint with `/api` prefix, and ensured proper import handling for both Docker and development environments.
+ - **Impact:** Reduced main application file by ~390 lines of code while maintaining 100% API compatibility. Statistics functionality is now properly isolated, ensuring Status page dashboard continues working seamlessly.
+ - _Files: `backend/statistics_routes.py` (new), `backend/app.py`, `Dockerfile`_
+
+- **Tag Management Routes Refactoring:** Extracted all tag management functionality from main application files into dedicated Flask Blueprint for improved code organization and maintainability.
+ - **Root Cause:** Tag management routes were scattered across multiple files (`app.py` and `warranties_routes.py`), making tag-related functionality harder to maintain and reducing code modularity.
+ - **Solution:** Created new `tags_routes.py` Blueprint containing all 6 tag-related routes including direct tag management (`/api/tags` CRUD operations) and warranty-tag association (`/api/warranties/{id}/tags`). Updated route decorators from `@app.route()` and `@warranties_bp.route()` to `@tags_bp.route()`, registered blueprint with `/api` prefix, and ensured proper import handling for both Docker and development environments.
+ - **Impact:** Reduced main application files by ~323 lines of code while maintaining 100% API compatibility. Tag functionality is now properly consolidated in a single 336-line dedicated module, making tag management operations easier to maintain and extend.
+ - _Files: `backend/tags_routes.py` (new), `backend/app.py`, `backend/warranties_routes.py`, `Dockerfile`_
+
+- **File Handling Routes Refactoring:** Extracted all file handling and Paperless-ngx integration functionality from main application file into dedicated Flask Blueprint for improved code organization and maintainability.
+ - **Root Cause:** File handling routes and Paperless-ngx integration were embedded within the main `app.py` file, contributing to a monolithic codebase structure and making file-related functionality harder to maintain.
+ - **Solution:** Created new `file_routes.py` Blueprint containing all 13 file-related routes including local file serving (`/api/files/<path:filename>`, `/api/secure-file/<path:filename>`, `/api/paperless-file/<int:paperless_id>`) and Paperless-ngx integration (`/api/paperless/upload`, `/api/paperless/test`, `/api/paperless/search`, `/api/paperless/tags`, `/api/paperless/debug`, `/api/paperless/test-upload`, `/api/paperless/debug-document/<int:document_id>`, `/api/paperless/cleanup-invalid`, `/api/paperless-search-and-link`, `/api/paperless/url`). Created shared `utils.py` module with `allowed_file()` function. Updated route decorators from `@app.route()` to `@file_bp.route()`, registered blueprint with `/api` prefix, and cleaned up unused imports (`secure_filename`, `send_from_directory`, `mimetypes`).
+ - **Impact:** Reduced main application file by ~781 lines of code (from 1,769 to 988 lines) while maintaining 100% API compatibility. File handling and Paperless-ngx functionality is now properly isolated in a 933-line dedicated module, making file operations and third-party integrations easier to maintain and extend.
+ - _Files: `backend/file_routes.py` (new), `backend/utils.py` (new), `backend/app.py`, `backend/warranties_routes.py`, `Dockerfile`_
+
+- **Application Factory Pattern Implementation:** Implemented Flask Application Factory Pattern to transform the application architecture from a monolithic script to a professional, modular, and testable structure following Flask community best practices.
+ - **Root Cause:** The application used a global Flask app object created at import time, making it difficult to test, configure for different environments, and maintain as the codebase grew. Configuration was scattered throughout `app.py`, extensions were initialized directly in the main module, and the application couldn't be easily instantiated for testing purposes.
+ - **Solution:** Created centralized `config.py` with environment-specific configuration classes (Development, Production, Testing), unified `extensions.py` module for Flask extension initialization with lazy loading pattern, implemented `create_app()` factory function in `__init__.py` for on-demand application creation, and simplified `app.py` to a 42-line entry point that uses the factory. Updated Dockerfile to use `gunicorn "backend:create_app()"` command and fixed blueprint imports to use extensions module instead of the old app module.
+ - **Impact:** Reduced main application file by ~1,101 lines of code (from 1,143 to 42 lines) while maintaining 100% API compatibility. Application now supports multiple environments (development/production/testing), can be easily tested with isolated app instances, follows Flask best practices with proper extension management, and provides a clean separation of concerns between configuration, extensions, application creation, and entry point logic.
+ - _Files: `backend/config.py` (new), `backend/extensions.py` (enhanced), `backend/__init__.py` (enhanced), `backend/app.py` (simplified), `backend/auth_routes.py` (import fix), `Dockerfile`_
+
+- **Missing API Endpoints After Refactoring:** Restored critical API endpoints that were accidentally removed during the Application Factory Pattern implementation, causing 404 errors in the frontend.
+ - **Root Cause:** During the blueprint refactoring, two essential endpoints (`/api/currencies` and `/api/settings/global-view-status`) were removed from the application, causing the frontend to fail when loading currency data and checking global view permissions.
+ - **Solution:** Added missing `/api/currencies` endpoint to `warranties_routes.py` returning comprehensive list of 85+ world currencies with symbols, codes, and names. Added missing `/api/settings/global-view-status` endpoint to `statistics_routes.py` to check global view permissions based on user admin status and site settings. Updated frontend currency loading functions in `script.js` and `settings-new.js` to include authentication tokens in requests.
+ - **Impact:** Resolved 404 errors preventing currency dropdown population and global view functionality. Frontend now properly loads currency data and global view permissions with proper authentication.
+ - _Files: `backend/warranties_routes.py`, `backend/statistics_routes.py`, `frontend/script.js`, `frontend/settings-new.js`_
+
+- **Status Page Warranty Details Functionality:** Fixed status page warranty detail expansion that was failing due to missing API endpoint and frontend JavaScript errors.
+ - **Root Cause:** The status page was attempting to fetch detailed warranty information from `/api/debug/warranty/{id}` endpoint that didn't exist, and the toast notification system had a null reference error when trying to add event listeners.
+ - **Solution:** Added new `/api/debug/warranty/<int:warranty_id>` GET endpoint in `warranties_routes.py` that returns complete warranty details including serial numbers, tags, and user information with proper permission checks. Fixed toast function in `status.js` to safely check for element existence before adding event listeners. Enhanced status page to display both local and Paperless-ngx documents with proper visual indicators.
+ - **Impact:** Status page warranty rows now expand properly when clicked, showing detailed warranty information, documents, and serial numbers. Toast notifications work without JavaScript errors.
+ - _Files: `backend/warranties_routes.py`, `frontend/status.js`_
+
+- **Paperless-ngx Document Visibility on Warranty Cards:** Fixed issue where documents added from Paperless-ngx weren't appearing on warranty cards in the main view, despite being properly stored and visible in edit modals.
+ - **Root Cause:** The frontend logic for determining whether to show the document links section (`hasDocuments` calculation) only checked for local file paths but ignored Paperless-ngx document IDs. Status page document display also only showed local files.
+ - **Solution:** Enhanced `hasDocuments` calculation in `script.js` to include Paperless-ngx document IDs (`paperless_invoice_id`, `paperless_manual_id`, `paperless_photo_id`, `paperless_other_id`) alongside local file paths. Updated status page document display logic to show both local and Paperless-ngx documents with cloud icon indicators. Exposed `openPaperlessDocument` and `openSecureFile` functions to window object for global access.
+ - **Impact:** Warranty cards now properly display document links when Paperless-ngx documents are attached. Users can access both local files and Paperless-ngx documents from warranty cards and status page, with visual distinction between storage types.
+ - _Files: `frontend/script.js`, `frontend/status.js`_
+
+## 0.10.1.6 - 2025-07-13
+
+### Fixed
+- **Warranty Card Layout Improvement:** Moved warranty status row to the bottom of warranty cards in both grid and list views for better visual hierarchy and consistent card structure.
+ - **Root Cause:** Status information appeared in the middle of warranty cards, breaking visual flow.
+ - **Solution:** Relocated warranty status row to appear after document links and tags at the bottom of each card.
+ - **Impact:** Improved card readability and consistent layout across all view modes.
+ - _Files: `frontend/script.js`_
+
+- **Tag Management Real-Time Updates:** Fixed issue where tag changes (color updates, name changes) in the manage tags modal did not immediately reflect in warranty cards and UI elements.
+ - **Root Cause:** Tag updates only refreshed the management modal but not the main warranty display or related UI components.
+ - **Solution:** Enhanced updateTag() and deleteTag() functions to update all UI elements including warranty cards, selected tags, filter dropdowns, and edit forms.
+ - **Impact:** Tag changes now appear instantly throughout the application without requiring page refresh.
+ - _Files: `frontend/script.js`_
+
+- **Missing Tag-Related Translations:** Resolved issue where tag management success and error messages displayed as translation keys instead of localized text across all supported languages.
+ - **Root Cause:** Tag-related message keys (tag_updated_successfully, tag_created_successfully, etc.) were missing from translation files.
+ - **Solution:** Added complete set of tag management translations to all 17 language files including success messages, error messages, and validation text.
+ - **Impact:** Users now see properly localized tag management messages in their preferred language.
+ - **Languages Updated:** English, French, Spanish, German, Italian, Dutch, Russian, Czech, Portuguese, Japanese, Korean, Chinese (Simplified & Traditional), Hindi, Arabic, Persian, Ukrainian.
+ - _Files: All `locales/*/translation.json` files_
+
+- **Update Caching Issues:** Resolved errors during application updates caused by browser and service worker caching of outdated assets.
+ - Configured `nginx.conf` with no-cache headers for `sw.js` to ensure fresh service worker loads on updates.
+ - Updated service worker cache name in `frontend/sw.js` to 'warracker-cache-v20250119001' and added version parameters to all cached assets.
+ - Incremented version query parameters (?v=20250119001) across all HTML files to force cache busting for CSS, JS, and other assets.
+ - Temporarily added version parameter to service worker registration in `frontend/script.js`, removed after nginx configuration handles it going forward.
+ - Verified complete removal of previous version strings and consistent application across all frontend files.
+
+- **Database Migration Format String Errors:** Fixed critical migration failures preventing new Warracker instances from starting up due to PostgreSQL parameter format string conflicts in migration files.
+ - **Root Cause:** Migration files `011_ensure_admin_permissions.sql` and `031_add_owner_role.sql` contained mixed parameter format styles that caused psycopg2 to fail with "argument formats can't be mixed" and "too many parameters specified for RAISE" errors. The issue occurred when Python-style parameter placeholders (`%(db_user)s`) were mixed with PostgreSQL format specifiers (`%`) in `RAISE NOTICE` statements within the same SQL file.
+ - **Solution:** Fixed format string conflicts in `011_ensure_admin_permissions.sql` by escaping literal `%` characters as `%%` in `RAISE NOTICE` statements to avoid conflicts with Python parameter substitution. Fixed parameter count issues in `031_add_owner_role.sql` by correcting `RAISE NOTICE` statements to use proper single `%` for parameter placeholders instead of double `%%` which was causing parameter count mismatches.
+ - **Impact:** New Warracker instances can now start up successfully without migration failures. All 42 database migrations (000 through 042) now complete successfully, allowing proper creation of the `site_settings` table and elimination of "relation 'site_settings' does not exist" errors during startup.
+ - _Files: `backend/migrations/011_ensure_admin_permissions.sql`, `backend/migrations/031_add_owner_role.sql`_
+
+_Files: `nginx.conf`, `frontend/sw.js`, `frontend/script.js`, all frontend HTML files (index.html, status.html, settings-new.html, login.html, register.html, reset-password-request.html, reset-password.html, about.html, auth-redirect.html, debug-export.html)_
+
+- **Docker Compose Command Duplication Fix:** Resolved update issues by removing redundant migration and permission commands from the root `docker-compose.yml`, preventing duplicated execution and startup errors.
+
+_Files: `docker-compose.yml`_
+
+- **Flexible Date Parsing in CSV Import:** Enhanced CSV import to support multiple date formats for the PurchaseDate field using dateutil.parser, removing the strict YYYY-MM-DD requirement.
+ - **Root Cause:** Import required exact YYYY-MM-DD format, failing on other common formats.
+ - **Solution:** Replaced strict datetime.strptime with flexible dateutil.parser.parse in backend/app.py.
+ - **Impact:** Users can now import warranties with various date formats without manual reformatting.
+ - _Files: `backend/app.py`_
+
+- **Warranty Duration Selection Limit:** Fixed limitation preventing selection above 11 months for warranty durations. Removed backend validation caps on months (<12) and days (<366), increased years limit to 999, and updated frontend input maximums to 999 months and 9999 days for flexible entry. Added migration to adjust database constraints accordingly.
+ - _Files: `backend/app.py`, `frontend/index.html`, `frontend/status.html`, `backend/migrations/042_allow_higher_duration_components.sql`_
+- **Paperless-ngx Duplicate Document Handling:** Added detection of duplicate documents during upload to Paperless-ngx. When a duplicate is found, the system automatically links to the existing document and displays an informative message to the user.
+ - **Root Cause:** Previous implementation did not check for duplicates before upload, leading to generic error messages.
+ - **Solution:** Added checksum-based duplicate check before upload in backend/paperless_handler.py and handled linking in frontend/script.js.
+ - **Impact:** Users now get clear feedback about duplicates and automatic linking instead of upload failures.
+ - _Files: `backend/paperless_handler.py`, `backend/app.py`, `frontend/script.js`_
+
+ - **Database Migration Permission Fix:** Resolved 'no permission to create role' errors during initial setup by granting CREATEROLE privilege to the db_user in a new early migration and removing duplicate grants in later migrations. This ensures smooth database initialization without requiring superuser privileges.
+ - _Files: `backend/migrations/009z_grant_createrole_to_db_user.sql`, `backend/migrations/011_ensure_admin_permissions.sql`_
+
+- **Missing Translation for Warranty Addition Success Message:** Resolved issue where the success message displayed as a placeholder key ('messages.warranty_added_successfully') instead of the translated text.
+ - Added the key and appropriate translations to all supported languages in `translation.json` files.
+ - Updated English and French `.po` files for backend consistency.
+ - Ensures proper localized success messages appear when adding warranties in any language.
+
+ _Files: All `locales/*/translation.json`, `locales/en/LC_MESSAGES/messages.po`, `locales/fr/LC_MESSAGES/messages.po`_
+
+- **Product Photo Loading Fix:** Fixed issue where product photos would disappear when navigating between pages, specifically when returning from the status page to the homepage.
+ - **Root Cause:** The renderWarranties function was calling a non-existent `initializeSecureImages()` function, causing JavaScript errors that prevented secure image loading.
+ - **Solution:** Replaced the incorrect `initializeSecureImages()` function call with the correct `loadSecureImages()` function.
+ - **Impact:** Product photos now load consistently across all page navigation scenarios with proper authentication.
+ - _Files: `frontend/script.js`_
+
+## 0.10.1.5 - 2025-07-08
+
+### Enhanced
+- **Comprehensive Cache Busting Implementation:** Updated all frontend assets with consistent cache versioning to ensure users receive the latest files immediately.
+ - **Unified Cache Version:** Applied consistent cache busting version `v=20250118001` across all frontend assets:
+ - **CSS Files:** `style.css`, `settings-styles.css`, `header-fix.css`, `mobile-header.css`
+ - **JavaScript Files:** `script.js`, `auth.js`, `settings-new.js`, `status.js`, `theme-loader.js`, `footer-fix.js`, `footer-content.js`
+ - **Authentication Scripts:** `auth-redirect.js`, `registration-status.js`, `file-utils.js`, `include-auth-new.js`, `fix-auth-buttons-loader.js`
+ - **Internationalization:** `js/i18n.js`, `js/i18n-debug.js`, and all i18next library files
+ - **Chart Library:** `chart.js`
+ - **Complete HTML Coverage:** Updated cache busting across all application pages:
+ - **Main Pages:** `index.html`, `status.html`, `settings-new.html`
+ - **Authentication Pages:** `login.html`, `register.html`, `reset-password.html`, `reset-password-request.html`
+ - **Utility Pages:** `about.html`, `auth-redirect.html`, `debug-export.html`
+ - **Service Worker Integration:** Updated Progressive Web App caching with new cache name `warracker-cache-v20250118001`:
+ - **Cache Name Update:** Incremented service worker cache version to force cache refresh
+ - **Asset Registry:** Added all cache-busted files to service worker's cached asset list
+ - **Cache Invalidation:** Old cached versions automatically cleared on service worker activation
+ - **Performance Benefits:**
+ - **Immediate Updates:** Users automatically receive latest file versions without manual cache clearing
+ - **Consistent Experience:** Eliminates mixed version issues from partial cache updates
+ - **Developer Control:** Simplified cache management for future deployments
+ - **PWA Compatibility:** Service worker properly synchronized with new asset versions
+ - _Files: All HTML files, `frontend/sw.js`_
+
+### Added
+- **Multi-Language Support Expansion:** Warracker now provides comprehensive internationalization support with **17 languages**, making warranty management accessible to users worldwide.
+ - **Complete Localization Coverage:** Full application translation including UI elements, navigation, settings, status pages, and user messaging across all supported languages
+ - **Right-to-Left (RTL) Language Support:** Native RTL text direction support for Arabic and Persian languages with proper layout adjustments
+ - **Supported Languages:**
+ - **Arabic (ar)** – *RTL Support*
+ - **Czech (cs)** – Čeština
+ - **German (de)** – Deutsch
+ - **English (en)** – English *(Default)*
+ - **Spanish (es)** – Español
+ - **Persian (fa)** – فارسی *(RTL Support)*
+ - **French (fr)** – Français
+ - **Hindi (hi)** – हिन्दी
+ - **Italian (it)** – Italiano
+ - **Japanese (ja)** – 日本語
+ - **Korean (ko)** – 한국어
+ - **Dutch (nl)** – Nederlands
+ - **Portuguese (pt)** – Português
+ - **Russian (ru)** – Русский
+ - **Ukrainian (uk)** – Українська
+ - **Chinese (Simplified) (zh_CN)** – 简体中文
+ - **Chinese (Hong Kong) (zh_HK)** – 繁體中文 (香港)
+ - **Language Selection Features:**
+ - **Auto-Detection:** Browser language automatically detected on first visit
+ - **User Preference:** Individual language selection saved to user profile
+ - **Native Names:** Language dropdown displays options in their native scripts for better user recognition
+ - **Instant Switching:** Real-time language changes without page reload
+
+## Frontend Enhancements
+
+* Language dropdown updated to list all 17 languages using native names.
+* UI elements across navigation, settings, and status pages are fully localized.
+* Translation files updated with keys for status, warranties, and user settings.
+* Full support for pluralization and dynamic content in all languages.
+
+ * *Files: `frontend/js/i18n.js`, `frontend/settings-new.html`, `frontend/status.js`, `frontend/status.html`, `frontend/version-checker.js`*
+
+## Backend and Database Updates
+
+* Language code validation extended to all 17 languages in user preference APIs.
+* Database constraints updated to allow the new language codes.
+
+ * *Files: `backend/auth_routes.py`, `backend/app.py`, `backend/localization.py`, `backend/migrations/039_update_language_constraint.sql`, `backend/migrations/041_update_language_constraint_again.py`*
+
+## Translation Files
+
+* New translation files added for all supported languages under `locales/`.
+* All existing translation files updated to include standardized language names.
+* Gettext `.po` files updated to reflect new keys.
+
+ * *Files: `locales/*/translation.json`, `locales/*/LC_MESSAGES/messages.po`, `scripts/manage_translations.py`, `run_language_migration.py`*
+
+## Status Page Localization
+
+* Status dashboard, chart labels, and table headers are fully translatable.
+* Dynamic labels (e.g., warranty statuses, chart titles, empty states) now reflect the selected language.
+* Proper pluralization support implemented for all time-based units.
+* Missing or inconsistent keys added across all language files:
+
+ * `dashboard_title`, `global_dashboard_title`, `overview`
+ * `purchase_date`, `expiration_date`, `status`, `expiring_soon`
+ * `recent_expirations_empty`, `active`, and others
+ * *Files: `frontend/status.js`, `locales/*/translation.json`*
+
+### Fixed
+
+- **Paperless-ngx Auto-Linking After Add Warranty:** Fixed an issue where uploading invoices or manuals to Paperless-ngx when adding a new warranty did not automatically link the documents to the warranty (auto-link/search logic was not triggered). Now, after adding a warranty, any uploaded Paperless-ngx documents (invoice or manual) are automatically searched and linked, matching the behavior of the edit warranty modal. This works for both invoices and manuals, provided their storage is set to "paperless".
+ - **Root Cause:** The auto-link logic was running after the form reset, which cleared file inputs and prevented document linking.
+ - **Solution:** The auto-link logic now runs before the form reset, using pre-upload file info and storage type to ensure correct document association.
+ - **Impact:** Users can now add warranties and have their uploaded Paperless-ngx invoices/manuals automatically linked, just like in the edit modal.
+ - _Files: `frontend/script.js`_
+
+- **Toast Error Adding Warranty:** When skipping a missing field in a form, the application now displays only a single warning message instead of multiple repeated warnings. This improves user experience by preventing redundant alerts when required fields are missing or skipped.
+
+## 0.10.1.4 - 2025-06-24
+
+### Enhanced
+- **Warranty Card Information Display Improvements:** Redesigned warranty card layout with clean icon-based display and improved visual organization.
+ - **Icon-Based Information Display:** Added intuitive icons to warranty information for better visual scanning:
+ - 📅 Calendar icon for Product Age
+ - 📄 Document icon for Warranty Duration
+ - 🔧 Wrench icon for Warranty End Date
+ - 🪙 Coins icon for Purchase Price
+ - 📊 Barcode icon for Serial Number
+ - 🏪 Store icon for Vendor
+ - 🛡️ Shield icon for Warranty Type
+ - **Reorganized Information Order:** Reordered warranty details for logical information hierarchy:
+ - Age → Warranty Duration → Warranty End Date → Price → Serial Number → Vendor → Type
+ - **Layout Improvements:**
+ - Fixed text overlapping with product photo thumbnails by removing right-alignment
+ - Values now positioned close to labels with consistent spacing
+ - Applied improvements across all view modes (grid, list, table)
+ - **Visual Enhancements:**
+ - Added light grey background (#f5f5f5) to product photo thumbnails
+ - Dark mode photo backgrounds use #2a2a2a for proper contrast
+ - Improved serial number display - first serial shown inline, additional ones in list below
+ - _Files: `frontend/script.js`, `frontend/style.css`_
+
+### Added
+- **Paperless-ngx Document Browser:** Complete GUI interface for browsing and selecting documents from Paperless-ngx in warranty forms.
+ - **Interactive Document Browser:** Added comprehensive document browser modal accessible from warranty add/edit forms:
+ - **Browse Buttons:** Added "Browse Paperless" buttons for invoice and manual document selection in warranty forms
+ - **Search and Filter:** Full-text search across document titles and content with tag-based filtering capabilities
+ - **Pagination Support:** Efficient pagination for large document collections with configurable page sizes
+ - **Document Selection:** Single-click document selection with visual confirmation and selection state management
+ - **Backend API Enhancements (`backend/app.py`):** Added `/api/paperless/tags` endpoint for document filtering:
+ - **Tag Retrieval:** Fetches available tags from Paperless-ngx for filter dropdown population
+ - **Authentication:** Properly authenticated endpoint with user permission validation
+ - **Error Handling:** Comprehensive error handling for Paperless-ngx connection issues
+ - **Frontend Integration (`frontend/index.html`, `frontend/script.js`, `frontend/style.css`):**
+ - **Modal Interface:** Large, responsive document browser modal with search bar, filters, and document grid
+ - **Document Display:** Clean document cards showing title, creation date, tags, and selection status
+ - **Form Integration:** Selected documents automatically populate warranty form fields with document IDs
+ - **Mobile Responsive:** Optimized layout for mobile devices with appropriate touch targets
+ - **Visual Feedback:** Loading states, error messages, and success confirmations for all operations
+ - **User Experience Features:**
+ - **Conditional Visibility:** Browse buttons only appear when Paperless-ngx is enabled and configured
+ - **Real-time Search:** Instant search results as users type in the search field
+ - **Tag Filtering:** Multi-select tag filter for refined document discovery
+ - **Keyboard Navigation:** Full keyboard support for accessibility
+ - **Cache Management:** Intelligent caching of document lists and tags for improved performance
+ - _Files: `backend/app.py`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_
+- **Paperless-ngx Document Viewing Preference:** Added user preference to view Paperless documents within Warracker instead of opening in Paperless domain.
+ - **User Preference Setting:** Added "View Documents in Warracker" toggle in Paperless-ngx settings section:
+ - **Individual Choice:** Each user can choose their preferred document viewing method between Warracker interface or Paperless-ngx instance
+ - **Dual Viewing Options:** Users can view documents either within Warracker's interface or directly in the Paperless-ngx web interface
+ - **Persistent Setting:** Preference saved to user preferences database and localStorage
+ - **Immediate Effect:** Setting changes apply immediately without requiring page refresh
+ - **Database Schema (`backend/migrations/037_add_paperless_view_in_app_preference.sql`):** Added `paperless_view_in_app` boolean column to `user_preferences` table:
+ - **Default Value:** Set to FALSE (open in Paperless-ngx domain) for backward compatibility
+ - **User-Specific:** Each user maintains their own viewing preference independently
+ - **Backend API Integration (`backend/auth_routes.py`):** Enhanced user preferences endpoints:
+ - **GET /api/auth/preferences:** Returns paperless viewing preference with proper fallback handling
+ - **PUT /api/auth/preferences:** Validates and saves paperless viewing preference with boolean validation
+ - **Default Handling:** All preference responses include paperless_view_in_app with appropriate defaults
+ - **Frontend Implementation (`frontend/script.js`, `frontend/settings-new.html`, `frontend/settings-new.js`):**
+ - **Document Opening Logic:** Modified `openPaperlessDocument()` function to check user preference
+ - **Warracker Viewing:** When enabled, documents open via `/api/paperless-file/{id}` endpoint within Warracker interface
+ - **Paperless-ngx Viewing:** When disabled, documents open directly in the Paperless-ngx web interface at the configured instance URL
+ - **Authentication Handling:** Proper token authentication for in-app document viewing with query parameter support
+ - **Fallback Support:** Graceful fallback to Paperless-ngx domain if in-app viewing fails
+ - **Settings UI:** Toggle switch in Paperless-ngx settings section with clear description of both viewing options
+ - **Security Features:**
+ - **Token Authentication:** Documents accessed through Warracker maintain proper user authentication
+ - **Permission Validation:** Backend validates user access rights before serving documents
+ - **Secure Token Passing:** Authentication tokens properly encoded in query parameters for secure access
+ - _Files: `backend/migrations/037_add_paperless_view_in_app_preference.sql`, `backend/auth_routes.py`, `frontend/script.js`, `frontend/settings-new.html`, `frontend/settings-new.js`_
+
+## 0.10.1.3 - 2025-06-17
+
+### Added
+- **Paperless-ngx Document Management Integration:** Complete integration with Paperless-ngx for advanced document management and storage capabilities.
+ - **Settings Page Configuration:** Added Paperless-ngx configuration section in admin settings allowing administrators to:
+ - **Connection Setup:** Configure Paperless-ngx server URL and API token for secure integration
+ - **Test Connection:** Built-in connection testing to verify Paperless-ngx server accessibility and authentication
+ - **Enable/Disable Toggle:** Master switch to activate or deactivate Paperless-ngx integration across the application
+ - **Hybrid Storage System (`backend/app.py`):** Implemented intelligent document storage with per-document storage choice:
+ - **Storage Selection:** Users can choose between local storage and Paperless-ngx for each document type (invoice, manual, photos, other documents)
+ - **Smart File Handling:** Documents are stored exclusively in chosen location (prevents dual storage)
+ - **Database Integration:** Paperless document IDs properly tracked in database fields (`paperless_invoice_id`, `paperless_manual_id`, etc.)
+ - **Automatic Cleanup:** When switching storage methods, old files are automatically removed from previous location
+ - **Visual Document Identification:** Enhanced warranty cards with clear visual indicators for document storage location:
+ - **Cloud Icons:** Blue cloud icons (🌤️) appear next to documents stored in Paperless-ngx for instant recognition
+ - **Local Document Icons:** Standard document icons for locally stored files
+ - **Mixed Storage Support:** Warranties can have documents stored in both locations with appropriate visual indicators
+ - **Add/Edit Warranty Integration:** Full Paperless-ngx support in both add and edit warranty workflows:
+ - **Storage Option Selection:** Radio buttons for each document type allowing users to choose storage location
+ - **Seamless Upload Process:** Files uploaded to Paperless-ngx are automatically tagged and organized
+ - **Edit Modal Parity:** Edit warranty modal has identical Paperless-ngx functionality to add warranty modal
+ - **Document Access Integration:** Direct access to Paperless-ngx documents through warranty interface with secure authentication
+ - _Files: `backend/app.py`, `frontend/script.js`, `frontend/settings-new.html`, `frontend/settings-new.js`_
+
+### Fixed
+- **Application Loading Performance:** Eliminated empty warranty list flash during login by preventing premature rendering before data is loaded.
+ - **Loading State Management:** Added `warrantiesLoaded` flag to track when warranty data has been successfully fetched from the API
+ - **Render Prevention:** Modified `switchView()` function to skip rendering warranties until data is actually loaded from the server
+ - **Smooth User Experience:** Users now see warranties appear directly without the brief flash of empty content during authentication
+ - **State Synchronization:** Warranty loading flag properly reset on load start and error conditions to maintain accurate state
+ - **Initialization Flow:** View preference loading no longer triggers empty warranty rendering during page initialization
+ - _Files: `frontend/script.js`_
+
+- **Settings Page Horizontal Scrollbar:** Eliminated horizontal scrollbar issue on the settings page that was causing unwanted left-right scrolling.
+ - **Footer Overflow Fix:** Replaced problematic viewport width calculations (`100vw`) with standard width (`100%`) in `.warracker-footer` class to prevent horizontal overflow
+ - **Margin Calculation Fix:** Removed `calc(-50vw + 50%)` margin calculations that were causing overflow beyond viewport boundaries
+ - **Global Overflow Prevention:** Added `overflow-x: hidden` to `html`, `body`, and `.content-wrapper` elements to prevent any horizontal scrolling
+ - **Grid Responsiveness:** Reduced minimum column width from `200px` to `150px` in admin actions, apprise actions, and status grid layouts for better mobile compatibility
+ - **Text Handling:** Added `word-wrap: break-word` and `box-sizing: border-box` to form controls and cards to prevent text overflow
+ - **Cross-Device Compatibility:** Settings page now displays properly without horizontal scrollbars on all screen sizes and devices
+ - _Files: `frontend/settings-styles.css`_
+
+
+## 0.10.1.2 - 2025-06-16
+
+### Fixed
+- **First User Registration Issue on Fresh Instances:** Fixed critical bug preventing first user registration on newly deployed applications
+ - **Logger Import Fix (`backend/auth_routes.py`):** Fixed undefined logger error in registration endpoint that was causing 500 Internal Server Error during user creation
+ - **Database Migration Timing Fix (`backend/app.py`):** Enhanced owner existence check to handle cases where `is_owner` column doesn't exist yet during application startup, preventing column lookup errors during migration sequence
+ - **Graceful Migration Handling:** Added proper column existence verification and exception handling for migration timing edge cases
+ - **Error Resolution:** Eliminates "name 'logger' is not defined" and "column 'is_owner' does not exist" errors during fresh deployment registration
+
+## 0.10.1.1 - 2025-06-15
+
+### Added
+- **Export Debug Tools**: Comprehensive debugging system for troubleshooting warranty export issues
+ - **Debug Page**: Created `frontend/debug-export.html` for interactive export testing and analysis
+ - **Debug API**: Added `/api/debug/export` endpoint providing detailed warranty and association data
+ - **Enhanced Logging**: Added comprehensive debug logging to export and filter functions in `frontend/script.js`
+ - **Export Validation**: Real-time display of filter application and warranty count verification
+ - **Interactive Testing**: Browser-based tool to test export functionality with detailed console output
+ - **Filter Analysis**: Step-by-step debugging of each filter application to identify export count discrepancies
+- **Currency Position Control:** Enhanced currency display system to allow users to choose whether currency symbols appear on the left or right of numbers through the settings page.
+ - **Settings UI Enhancement (`frontend/settings-new.html`):** Added new "Currency Position" dropdown in Display Preferences section:
+ - **Left Position:** Traditional format like "$100.00" (default to maintain existing behavior)
+ - **Right Position:** European-style format like "100.00$"
+ - **Visual Examples:** Dropdown options show example formatting to clarify choice impact
+ - **Database Schema (`backend/migrations/034_add_currency_position_column.sql`):** Added `currency_position` column to `user_preferences` table:
+ - **Default Value:** Set to 'left' for backward compatibility with existing installations
+ - **Data Validation:** Check constraint ensures only 'left' or 'right' values are allowed
+ - **Migration Safety:** Handles existing data by setting NULL or invalid values to 'left' before applying constraint
+ - **Backend API Integration (`backend/auth_routes.py`):** Enhanced user preferences endpoints to handle currency position:
+ - **GET /api/auth/preferences:** Returns saved currency position preference with 'left' fallback for missing values
+ - **PUT /api/auth/preferences:** Validates and saves currency position with input validation for 'left'/'right' values
+ - **Default Handling:** All default preference objects include currency_position: 'left' for consistency
+ - **Frontend Dynamic Formatting (`frontend/script.js`):** Implemented responsive currency display system:
+ - **New Functions:** Added `getCurrencyPosition()` and `formatCurrencyHTML()` for position-aware currency formatting
+ - **Smart HTML Generation:** Currency symbols and amounts dynamically positioned based on user preference
+ - **CSS Integration:** Right-positioned symbols use `.currency-right` class for proper spacing
+ - **Live Updates:** Real-time updates when position preference changes without page refresh
+ - **Universal Application:** Currency position setting applies across all views and features:
+ - **Warranty Cards:** Grid, list, and table views all respect position preference
+ - **Price Displays:** Purchase price fields show currency in chosen position throughout application
+ - **Cross-Tab Sync:** Settings changes immediately reflect in all open browser tabs
+ - **User Experience Features:**
+ - **Immediate Preview:** Position changes apply instantly to warranty cards when settings are saved
+ - **Persistent Preference:** Setting saved per user in database and persists across sessions
+ - **Backward Compatible:** Existing users see no change (defaults to left position)
+ - **Storage Event Handling:** Settings page and main app stay synchronized when currency position changes
+ - **CSS Styling (`frontend/style.css`):** Added `.currency-right` class for proper margin spacing when symbols appear on the right
+ - **Form Currency Integration:** Enhanced warranty add/edit forms to respect currency position settings:
+ - **Dynamic Form Updates:** Price input fields in both add and edit warranty forms now show currency symbols in the user's preferred position
+ - **CSS Form Positioning:** Added `.price-input-wrapper.currency-right` styles to properly position currency symbols on the right side of input fields
+ - **Input Padding Adjustment:** Right-positioned currency symbols get appropriate padding to prevent text overlap
+ - **Dynamic Currency Positioning:** JavaScript-based dynamic positioning system that places right-side currency symbols immediately after the typed content, maintaining natural spacing regardless of input length
+ - **Modal Currency Positioning:** Enhanced currency positioning to work immediately when modals open, not just when users interact with input fields
+ - **Modal Integration:** Currency position updates automatically when forms are opened, ensuring immediate visual consistency
+ - **Summary Tab Enhancement:** Add warranty form summary tab now displays purchase price with correct currency positioning
+ - **Improved Dynamic Positioning:** Enhanced JavaScript positioning system with better timing and reliability:
+ - **Element Readiness Validation:** Added checks to ensure DOM elements are fully rendered before positioning calculations
+ - **Multiple Timing Mechanisms:** Uses `requestAnimationFrame()` with fallback timers for robust positioning across different browsers
+ - **Automatic Modal Triggers:** Currency positioning now activates immediately when modals open via simulated focus/blur events
+ - **Debug Logging:** Added console logging for positioning calculations to aid in troubleshooting
+ - **Retry Logic:** Automatic retry mechanism if elements aren't ready during initial positioning attempt
+ - _Files: `backend/migrations/034_add_currency_position_column.sql`, `backend/auth_routes.py`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/script.js`, `frontend/style.css`, `frontend/index.html`_
+- **OIDC-Only Login Mode:** Added administrator control to enforce OIDC-only authentication, hiding traditional username/password login forms.
+ - **Database Setting:** Added `oidc_only_mode` boolean setting to `site_settings` table with default value 'false' for backward compatibility
+ - **Backend API Enhancement (`backend/app.py`):**
+ - **Settings Management:** Added `oidc_only_mode` to site settings GET/PUT endpoints with proper boolean validation
+ - **OIDC Status API:** Enhanced `/api/settings/oidc-status` endpoint to include `oidc_only_mode` status for frontend consumption
+ - **OIDC Handler Update (`backend/oidc_handler.py`):** Updated `/api/auth/oidc-status` route to return OIDC-only mode status alongside provider information
+ - **Frontend Admin Controls (`frontend/settings-new.html`, `frontend/settings-new.js`):**
+ - **Settings UI:** Added "OIDC-Only Login Mode" toggle in OIDC SSO Configuration section with warning about proper configuration
+ - **Settings Persistence:** OIDC-only mode preference saved to backend and loaded with other OIDC settings
+ - **Element Management:** Added DOM element handling for the new toggle in both global and local scopes
+ - **Login Page Enhancement (`frontend/login.html`):**
+ - **Conditional UI:** Traditional username/password login form hidden when OIDC-only mode is enabled
+ - **Link Management:** Register and forgot password links hidden in OIDC-only mode as they're not applicable
+ - **Page Title Update:** Login page title changes to "Login with SSO" when in OIDC-only mode
+ - **Clean Interface:** OR separator and auth links section hidden when not needed
+ - **Security Benefits:** Enforces single sign-on authentication when enabled, preventing local account access and centralizing authentication through OIDC provider
+ - **Administrator Safety:** Includes warning message about ensuring OIDC is properly configured before enabling this mode to prevent lockouts
+ - _Files: `backend/app.py`, `backend/oidc_handler.py`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/login.html`_
+- **About Page Redesign:** Complete visual overhaul of the about page with modern design, improved layout, and enhanced community links.
+ - **Hero Section Enhancement:** Added gradient background hero section with prominent Warracker branding, version display, and descriptive text about the platform
+ - **Modern Card Layout:** Restructured content into three themed information cards:
+ - **Project Information Card:** GitHub repository and releases links with proper GitHub branding
+ - **Community & Support Card:** Discord community invitation and issue reporting links
+ - **Developer Information Card:** Developer profile and license information with appropriate icons
+ - **Discord Community Integration:** Added prominent Discord community link (https://discord.gg/PGxVS3U2Nw) with official Discord branding:
+ - **Discord Icon:** Proper `fab fa-discord` Font Awesome icon implementation
+ - **Brand Colors:** Discord's signature #5865f2 color scheme with hover effects
+ - **Community Focus:** Positioned prominently in Community & Support section
+ - **Enhanced Social Links:** Improved all external links with proper icons and brand-appropriate styling:
+ - **GitHub Links:** `fab fa-github` icons for repository and developer profile
+ - **Issue Reporting:** `fas fa-bug` icon with red accent color for bug reports
+ - **Releases:** `fas fa-tags` icon with blue accent color for version releases
+ - **License:** `fas fa-balance-scale` icon with green accent color for AGPL-3.0 license
+ - **Visual Improvements:** Modern design elements with enhanced user experience:
+ - **Hover Effects:** Smooth card lift animations and social link transitions
+ - **Responsive Design:** Grid layout that adapts to mobile devices with single-column layout
+ - **Dark Mode Support:** Proper styling for both light and dark themes with appropriate contrast
+ - **Color-Coded Interface:** Each social link uses brand-appropriate colors for visual consistency
+ - **Update Status Enhancement:** Redesigned update checker section with better visual hierarchy and icon integration
+ - **Support Section:** Improved "Buy me a coffee" section with better visual presentation and clear call-to-action
+ - **Mobile Optimization:** Responsive design with adjusted font sizes, centered layouts, and flexible social link sizing for optimal mobile experience
+ - _Files: `frontend/about.html`_
+- **Global View Photo Access:** Enhanced secure file access to allow users to view product photos from other users' warranties when global view is enabled.
+ - **Photo Sharing in Global View:** When global view is enabled for all users, product photo thumbnails and full-size images are now accessible across all warranties, not just user-owned ones
+ - **Selective File Access:** Only product photos are granted global view access - invoices, manuals, and other sensitive documents remain restricted to warranty owners and admins
+ - **Respects Global View Settings:** Photo access follows the same permission model as the global warranties feature:
+ - **Global View Enabled:** Photos accessible to all authenticated users when global view is active
+ - **Admin-Only Mode:** When global view is restricted to admins only, photo access is similarly restricted
+ - **Disabled Mode:** When global view is disabled, photos revert to owner-only access
+ - **Enhanced Security Logging:** Added comprehensive logging to secure file access endpoint for troubleshooting and security auditing of photo access requests
+ - **Backend Implementation (`backend/app.py`):** Modified `/api/secure-file/<path:filename>` endpoint with additional authorization logic:
+ - **Product Photo Detection:** Queries database to identify if requested file is a product photo vs other document types
+ - **Permission Validation:** Checks global view settings and user permissions before granting access
+ - **Maintains Existing Security:** All current access controls remain intact - admins and owners retain full access
+ - **User Experience:** Product photos now display properly in global view across all viewing modes (grid, list, table), enabling visual identification of products from all users
+ - _Files: `backend/app.py`_
+- **Super-Admin (Owner) Role with Ownership Transfer:** Implemented a comprehensive ownership management system with immutable owner role and secure ownership transfer functionality.
+ - **Database Schema Enhancement (`backend/migrations/031_add_owner_role.sql`):** Added `is_owner` boolean column to users table with automatic owner promotion for the first registered user
+ - **Backend API Protection (`backend/app.py`, `backend/auth_routes.py`, `backend/auth_utils.py`):**
+ - **Owner Protection Logic:** Prevents owner account deletion, demotion, or deactivation through all admin endpoints
+ - **Authentication Enhancement:** Added `is_owner` field to all authentication responses and token validation
+ - **Backward Compatibility:** Implemented graceful fallback handling for systems without the owner column
+ - **Transaction Rollback Handling:** Added proper PostgreSQL transaction rollback recovery for failed queries
+ - **Ownership Transfer API (`backend/app.py`):** New `/api/admin/transfer-ownership` endpoint with atomic transaction processing:
+ - **Security Validation:** Requires "TRANSFER" confirmation text and validates target user is an active admin
+ - **Atomic Operations:** Uses database transactions to ensure ownership transfer completes fully or rolls back entirely
+ - **Owner-Only Access:** Restricted to current owner with comprehensive permission checks
+ - **Frontend UI Implementation (`frontend/settings-new.html`, `frontend/settings-new.js`):**
+ - **Dedicated Ownership Section:** Separate "👑 Ownership Management" section in admin settings with crown icon branding
+ - **Visual Owner Indicators:** Crown icons (👑) displayed next to owner username in user management lists
+ - **Protected UI Elements:** Owner edit/delete buttons disabled with visual indicators and tooltips
+ - **Transfer Confirmation Modal:** Secure ownership transfer interface requiring "TRANSFER" text confirmation
+ - **Modern User Management:** Redesigned users list with professional styling, hover effects, and responsive design
+ - **Action Button Enhancement:** Improved edit/delete buttons with smooth animations and theme compatibility
+ - **Migration Safety:** Automatic owner assignment to first user during migration with comprehensive error handling
+ - **Security Features:** Owner cannot be deleted, demoted, or have ownership transferred without explicit confirmation
+ - _Files: `backend/migrations/031_add_owner_role.sql`, `backend/app.py`, `backend/auth_routes.py`, `backend/auth_utils.py`, `frontend/settings-new.html`, `frontend/settings-new.js`_
+
+- **Product Age Tracking and Sorting:** Enhanced warranty cards with product age display and sorting capabilities to help users track ownership duration.
+ - **Age Calculation (`frontend/script.js`):** Added `calculateProductAge()` function that computes time elapsed since purchase date with intelligent formatting:
+ - **Smart Display Format:** Shows age as "2 years, 3 months", "6 months", or "15 days" depending on duration
+ - **Edge Case Handling:** Gracefully handles invalid dates, future dates, and same-day purchases ("Today")
+ - **Precision Logic:** Shows days only for items less than a year old to avoid clutter
+ - **Visual Integration:** Product age now appears on all warranty cards across all view types:
+ - **Grid View:** Age displayed between purchase date and warranty duration for logical flow
+ - **List View:** Consistent placement maintaining card layout harmony
+ - **Table View:** Compact age display optimized for dense information presentation
+ - **Age-Based Sorting:** Added "Age" option to Sort By dropdown with dedicated sorting logic:
+ - **Oldest First:** Products sorted with longest-owned items appearing first
+ - **Precise Sorting:** Uses `calculateProductAgeInDays()` helper function for accurate day-level sorting
+ - **Invalid Date Handling:** Items with missing purchase dates treated as newest (0 days old)
+ - **User Benefits:** Enables users to track ownership duration, assess product lifecycle, and organize warranties by how long they've owned each item
+ - _Files: `frontend/index.html`, `frontend/script.js`_
+
+ - **Persistent View Scope (Global/Personal) with Auto-Loading:** The app now remembers the user's last selected view scope (global or personal) and automatically loads the correct data from the appropriate API endpoint on page load, not just updating the UI.
+ - **Seamless Experience:** Users no longer need to re-select their preferred view after a refresh; the correct data and UI are loaded immediately based on their last choice.
+ - **Consistent State:** Both the main warranties page and the status dashboard respect the saved preference and fetch from the correct endpoint (`/api/warranties/global` or `/api/warranties`, and `/api/statistics/global` or `/api/statistics`).
+ - **User-Specific Storage:** Preferences are stored per user/admin using the same prefix system as other settings.
+ - **Robustness:** The system defaults to personal view if no preference is found or on error, and always keeps the UI and data in sync.
+ - _Files: `frontend/script.js`, `frontend/status.js`_
+
+- **Authentication System Refactoring to Flask Blueprints:** Complete restructuring of authentication routes for improved code organization and maintainability.
+ - **Flask Blueprint Architecture:** Migrated all authentication routes from the monolithic `app.py` file to a dedicated Flask Blueprint (`auth_routes.py`)
+ - **Modular Code Organization:** Separated authentication logic into specialized modules:
+ - **`auth_utils.py`:** Authentication helper functions (`generate_token`, `decode_token`, `token_required`, `admin_required`, `is_valid_email`, `is_valid_password`)
+ - **`auth_routes.py`:** Authentication Blueprint containing all auth-related routes and handlers
+ - **Routes Migrated:** All authentication endpoints moved to Blueprint architecture:
+ - User registration and login (`/register`, `/login`, `/logout`)
+ - Token validation and user management (`/validate-token`, `/user`)
+ - Password management (`/password/reset-request`, `/password/reset`, `/password/change`)
+ - Profile and account management (`/profile`, `/account`, `/preferences`)
+ - Email management (`/change-email`, `/verify-email-change`)
+ - System status endpoints (`/registration-status`)
+ - **Backward Compatibility:** All API endpoints maintain identical URLs and functionality - zero breaking changes for existing clients
+ - **Import Optimization:** Reduced main application file size and improved code maintainability through separation of concerns
+ - **Docker Integration:** Updated Dockerfile to properly include new authentication modules in container builds
+ - _Files: `backend/auth_utils.py`, `backend/auth_routes.py`, `backend/app.py`, `Dockerfile`_
+
+- **Smart Currency Default Selection:** Enhanced add warranty form to automatically default to user's preferred currency from settings instead of always defaulting to USD.
+ - **Settings Integration:** Currency dropdown in add warranty modal now reads user's preferred currency from settings and auto-selects it as the default
+ - **Currency Code Storage:** Settings page now saves both currency symbol and currency code to localStorage for accurate currency identification
+ - **Intelligent Fallback:** System attempts to derive currency code from symbol if not explicitly saved, with USD as ultimate fallback
+ - **Form Reset Handling:** Add warranty modal properly restores user's preferred currency after form reset operations
+ - **Individual Override:** Users can still change currency for individual warranties while maintaining their preferred default
+ - **Seamless Experience:** Eliminates need to manually change currency from USD to preferred currency for every new warranty
+ - **Debug Logging:** Added comprehensive logging to track currency code detection and default selection process
+ - _Files: `frontend/script.js`, `frontend/settings-new.js`_
+
+### Enhanced
+- **Larger Product Photo Thumbnails:** Increased photo thumbnail sizes across all view modes for better product visibility and identification.
+ - **Grid View Enhancement:** Photo thumbnails increased from 60px × 60px to 80px × 80px for more prominent product images
+ - **List View Enhancement:** Photo thumbnails increased from 50px × 50px to 70px × 70px for improved visual clarity
+ - **Table View Enhancement:** Photo thumbnails increased from 40px × 40px to 55px × 55px for better readability in compact view
+ - **Mobile Responsive Updates:** Adjusted mobile photo sizes to maintain usability while providing larger images on smaller screens
+ - **Consistent Styling:** Maintained existing hover effects, border radius, and visual styling while increasing overall size
+ - **Better User Experience:** Larger photos make it easier to identify products at a glance across all viewing modes
+ - _Files: `frontend/style.css`, `frontend/script.js`_
+
+### Fixed
+- **CSV Import Currency Selection:** Fixed CSV import functionality that was incorrectly defaulting all imported warranties to USD currency instead of using the user's preferred currency from settings.
+ - **Root Cause:** CSV import function in `backend/app.py` was hardcoding `'USD'` for all imported warranties regardless of user preferences
+ - **Solution:** Enhanced import function to query user's preferred currency symbol from `user_preferences` table and convert it to appropriate currency code
+ - **Currency Mapping:** Implemented comprehensive symbol-to-code mapping for 30+ currencies (€→EUR, £→GBP, ¥→JPY, etc.) matching frontend logic
+ - **Intelligent Fallback:** Graceful fallback to USD for users without currency preferences or with unknown custom symbols
+ - **Enhanced Logging:** Added detailed logging to track currency preference detection and assignment during import process
+ - **Result:** Imported warranties now automatically use user's preferred currency (Euro, Pound, Yen, etc.) instead of always defaulting to USD
+ - _Files: `backend/app.py`_
+
+- **Export Function Debugging and Verification:** Resolved user reports of incomplete warranty exports by implementing comprehensive debugging tools and verifying export functionality
+ - **Root Cause Analysis:** Determined that export function was working correctly - all warranties were being exported as expected
+ - **Debug Implementation:** Added detailed console logging to export process showing step-by-step filter application and final export counts
+ - **Verification Tools:** Created interactive debug page (`frontend/debug-export.html`) and backend debug API (`/api/debug/export`) for troubleshooting
+ - **User Education:** Identified that perceived "missing" records were due to CSV viewer display issues with similar/duplicate entries rather than export functionality problems
+ - **Export Validation:** Confirmed all warranties are properly included in CSV output with correct data formatting and structure
+ - **Documentation:** Enhanced export process with real-time feedback showing actual number of warranties exported
+
+- **Critical User Preferences Persistence Bug:** Fixed date format and currency symbol settings not saving properly, causing user preferences to revert to defaults after page refresh.
+ - **Root Cause:** Backend API endpoints (`GET`/`PUT` `/api/auth/preferences`) were hardcoded to always return `currency_symbol: '$'` and `date_format: 'MDY'` instead of reading from/writing to the database columns
+ - **Database Verification:** Confirmed both `currency_symbol` and `date_format` columns exist in `user_preferences` table via migrations `006_add_currency_symbol_column.py` and `019_add_date_format_column.sql`
+ - **Backend API Fixes (`backend/auth_routes.py`):**
+ - **GET Route:** Added `currency_symbol, date_format` to SELECT queries and updated response mapping to use actual database values
+ - **PUT Route:** Added validation and processing for `currency_symbol` and `date_format` from request data
+ - **UPDATE Query:** Enhanced to include currency symbol and date format in SET clauses
+ - **INSERT Query:** Updated to save currency symbol and date format for new user preferences
+ - **Response Consistency:** All preference responses now return actual saved values instead of hardcoded defaults
+ - **Validation Added:** Currency symbol limited to 8 characters, date format restricted to valid options (`MDY`, `DMY`, `YMD`, `MDY_WORDS`, `DMY_WORDS`, `YMD_WORDS`)
+ - **Result:** Settings page now properly persists currency symbol (€, £, ¥, etc.) and date format preferences across page refreshes and sessions
+ - _Files: `backend/auth_routes.py`_
+
+- **Critical OIDC Login RecursionError Fix:** Resolved fatal `RecursionError: maximum recursion depth exceeded` preventing OIDC authentication with self-hosted providers like Authentik.
+ - **Root Cause:** Gunicorn's `gevent` worker type needs to monkey-patch standard libraries (like `ssl`) before they're imported, but `preload_app = True` was loading Flask dependencies before patching occurred
+ - **Solution:** Enhanced `gunicorn_config.py` with conditional early monkey patching that occurs at the very beginning of the configuration file, before any other imports
+ - **Intelligent Patching:** Monkey patching now only applies to memory modes that use gevent workers (`optimized` and `performance`), while `ultra-light` mode with sync workers skips patching entirely
+ - **Safety:** Uses try/catch block to gracefully handle environments without gevent installed, ensuring no impact on sync workers or development environments
+ - **Result:** OIDC providers now work correctly with gevent workers, eliminating SSL recursion errors and enabling SSO functionality across all deployment modes
+ - **Verification:** MonkeyPatchWarning no longer appears in startup logs, replaced with "✅ Early gevent monkey patch applied for SSL compatibility" confirmation
+ - _Files: `backend/gunicorn_config.py`_
+
+- **Critical OIDC HTTPS Callback URL Fix:** Resolved OIDC login failures when Warracker is accessed over HTTPS, where the application was generating incorrect `http://` callback URLs instead of `https://` URLs.
+ - **Root Cause:** Flask application running behind Nginx reverse proxy was not aware of the original HTTPS protocol, causing `url_for(_external=True)` to generate HTTP callback URLs that didn't match the OIDC provider's expected HTTPS URLs
+ - **Reverse Proxy Configuration:** While Nginx correctly sent `X-Forwarded-Proto: https` headers, Gunicorn and Flask were not configured to trust and use these forwarded headers
+ - **Gunicorn Fix (`backend/gunicorn_config.py`):** Added `forwarded_allow_ips = '*'` configuration to trust proxy headers from the containerized Nginx reverse proxy
+ - **Flask Middleware (`backend/app.py`):** Implemented `ProxyFix` middleware with `x_for=1, x_proto=1, x_host=1, x_prefix=1` to read forwarded headers and update Flask's request context
+ - **Header Processing:** Flask now correctly interprets `X-Forwarded-Proto` headers and generates HTTPS URLs when accessed through the reverse proxy
+ - **Result:** OIDC login flow now generates correct `https://warracker.domain.com/api/oidc/callback` URLs, eliminating provider callback mismatches and enabling successful SSO authentication over HTTPS
+ - **Standard Practice:** Implements industry-standard reverse proxy configuration for Flask applications behind SSL-terminating proxies
+ - _Files: `backend/gunicorn_config.py`, `backend/app.py`_
+
+- **Global vs. Individual Apprise Notification Mode:** Implemented flexible Apprise notification system allowing administrators to choose between consolidated global notifications or personalized individual notifications.
+ - **Database Migration (`backend/migrations/032_add_apprise_notification_mode.sql`):** Added `apprise_notification_mode` setting to `site_settings` table with default value 'global' for backward compatibility
+ - **Backend Notification Logic (`backend/notifications.py`):** Enhanced `send_expiration_notifications` function with mode-aware branching logic:
+ - **Global Mode:** Sends single consolidated notification summarizing all expiring warranties across all users to configured Apprise channels
+ - **Individual Mode:** Sends separate personalized notifications for each user with expiring warranties, grouped by user with targeted messaging
+ - **Smart User Filtering:** Respects user notification preferences and timing eligibility for both manual and scheduled notifications
+ - **Mode Detection:** Dynamically reads `apprise_notification_mode` setting from database using imported `get_site_setting` function
+ - **Apprise Handler Enhancement (`backend/apprise_handler.py`):** Added two new specialized notification methods:
+ - **`send_global_expiration_notification()`:** Creates summary notification with warranties grouped by user email for administrator overview
+ - **`send_individual_expiration_notification()`:** Generates personalized notifications with user-specific greeting and warranty details
+ - **Error Handling:** Comprehensive exception handling and logging for both notification modes
+ - **Frontend Admin Controls (`frontend/settings-new.html`, `frontend/settings-new.js`):**
+ - **Notification Mode Dropdown:** Added selection between "Global Summary" and "Per User" modes in Apprise settings section
+ - **Dynamic Description:** Real-time description updates explaining current mode behavior and implications
+ - **Settings Integration:** Mode preference saved to backend and persisted across sessions with proper loading and validation
+ - **Event Handling:** Immediate UI feedback when switching between notification modes
+ - **Backward Compatibility:** Existing installations default to 'global' mode, maintaining current notification behavior without disruption
+ - **Future Enhancement Ready:** Individual mode framework prepared for future per-user Apprise channel configuration
+ - _Files: `backend/migrations/032_add_apprise_notification_mode.sql`, `backend/notifications.py`, `backend/apprise_handler.py`, `frontend/settings-new.html`, `frontend/settings-new.js`_
+
+ - **Apprise Warranty Scope Control:** Added administrator control to choose which warranties are included in Apprise notifications, enabling both multi-user and personal notification scenarios.
+ - **Database Migration (`backend/migrations/033_add_apprise_warranty_scope.sql`):** Added `apprise_warranty_scope` setting to `site_settings` table with default value 'all' to maintain current behavior
+ - **Backend Warranty Filtering (`backend/notifications.py`):** Implemented warranty scope filtering logic in notification processing:
+ - **All Users Scope (Default):** Includes expiring warranties from all users in the system (current behavior)
+ - **Admin Only Scope:** Filters to only include warranties belonging to the admin/owner user for personal notifications
+ - **Smart Admin Detection:** Automatically identifies the primary admin by first checking for owner user, then falling back to first admin user
+ - **Scope Logging:** Comprehensive logging shows original vs filtered warranty counts for transparency and debugging
+ - **Frontend Warranty Scope Controls (`frontend/settings-new.html`, `frontend/settings-new.js`):**
+ - **Warranty Scope Dropdown:** Added selection between "All Users' Warranties" and "Admin's Warranties Only" in Apprise settings
+ - **Scope Description:** Real-time description updates explaining which warranties will be included in notifications
+ - **Settings Persistence:** Warranty scope preference saved to backend and properly loaded with other Apprise settings
+ - **Event Handling:** Immediate UI feedback when changing warranty scope selection
+ - **Flexible Combinations:** Works seamlessly with notification modes for complete control:
+ - **Global + All:** Single notification with all users' warranties (original behavior)
+ - **Global + Admin:** Single notification with only admin's warranties
+ - **Individual + All:** Separate notifications sent to each user with their warranties
+ - **Individual + Admin:** Notification sent only to admin with their warranties
+ - **Error Handling:** Graceful fallback to 'all' scope if admin user cannot be determined, with appropriate logging
+ - _Files: `backend/migrations/033_add_apprise_warranty_scope.sql`, `backend/notifications.py`, `frontend/settings-new.html`, `frontend/settings-new.js`_
+
+- **Enhanced Notification Settings with Apprise Integration:** Comprehensive enhancement of user notification preferences to support both email and Apprise notifications with individual timing control.
+ - **Backend User Preferences Enhancement (`backend/auth_routes.py`):** Fixed and expanded user preferences API to properly handle all notification fields:
+ - **Notification Channel Support:** Added proper handling for `notification_channel` field allowing users to choose between 'none', 'email', 'apprise', or 'both'
+ - **Apprise Timing Fields:** Added support for `apprise_notification_time`, `apprise_notification_frequency`, and `apprise_timezone` in user preferences
+ - **Database Persistence:** Fixed critical bug where notification channel and Apprise settings were hardcoded instead of being saved to/loaded from database
+ - **Validation:** Added proper validation for notification channel values and timing fields
+ - **API Consistency:** Both GET and PUT `/api/auth/preferences` endpoints now properly handle all notification-related fields
+ - **Frontend Notification Settings Redesign (`frontend/settings-new.html`, `frontend/settings-new.js`):**
+ - **Dual Notification Sections:** Separated user notification preferences from admin Apprise configuration for clarity
+ - **Dynamic Settings Display:** Notification settings section shows/hides email and Apprise fields based on selected notification channel
+ - **Individual Timing Control:** Users can set separate notification times and timezones for email vs Apprise notifications
+ - **Smart Field Management:** Apprise-specific fields (time, timezone, frequency) appear only when notification channel includes 'apprise' or 'both'
+ - **Timezone Loading:** Proper timezone dropdown population for both email and Apprise notification settings
+ - **Settings Persistence:** All notification preferences properly save to user preferences and persist across sessions
+ - **Scheduler Integration:** Enhanced notification scheduler to respect individual user notification channel preferences:
+ - **Channel-Aware Processing:** Scheduler checks each user's `notification_channel` setting to determine which notification types to send
+ - **Separate Timing:** Users can receive email notifications at one time and Apprise notifications at a different time
+ - **Preference Validation:** Only users with appropriate notification channels enabled receive corresponding notification types
+ - **User Experience Improvements:**
+ - **Clear Separation:** Admin Apprise configuration (URLs, global settings) separated from user notification preferences (timing, channels)
+ - **Intuitive Interface:** Notification channel dropdown with immediate visual feedback showing relevant settings
+ - **Flexible Scheduling:** Users can choose to receive only emails, only Apprise notifications, or both at different times
+ - _Files: `backend/auth_routes.py`, `frontend/settings-new.html`, `frontend/settings-new.js`_
+
+- **Apprise Notification Message Format Standardization:** Unified notification message format between scheduled and manual Apprise notifications for consistency.
+ - **Message Format Alignment (`backend/apprise_handler.py`):** Updated scheduled notification functions to match manual test notification format:
+ - **Consistent Titles:** All notifications now use format `"[Warracker] Warranties Expiring in X Days"` instead of generic summary titles
+ - **Urgency Indicators:** Added emoji prefixes based on expiration timeframe:
+ - 🚨 URGENT: for warranties expiring in 1 day
+ - ⚠️ IMPORTANT: for warranties expiring in ≤7 days
+ - 📅 REMINDER: for warranties expiring in >7 days
+ - **Grouped by Days:** Separate notifications sent for different expiration timeframes (7, 30, 365 days) instead of combined summary
+ - **Standardized Content:** Consistent bullet-point format, date formatting, and footer text across all notification types
+ - **Enhanced Notification Functions:**
+ - **`send_global_expiration_notification()`:** Now groups warranties by expiration days and sends separate notifications for each timeframe
+ - **`send_individual_expiration_notification()`:** Similarly updated to match manual test format with proper grouping
+ - **`_send_global_expiration_batch()` and `_send_individual_expiration_batch()`:** New helper functions that use identical formatting to manual test notifications
+ - **User Benefits:**
+ - **Consistent Experience:** Manual test notifications and scheduled notifications now look identical
+ - **Clear Urgency:** Emoji indicators immediately convey urgency level
+ - **Better Organization:** Separate notifications for different timeframes instead of overwhelming combined messages
+ - _Files: `backend/apprise_handler.py`_
+
+- **Apprise Settings UI Cleanup:** Streamlined Apprise configuration interface by removing non-functional decorative fields.
+ - **Removed Decorative Fields (`frontend/settings-new.html`, `frontend/settings-new.js`):** Eliminated unused time and timezone fields from admin Apprise configuration:
+ - **Notification Time Field:** Removed time input that was not used by the notification scheduler
+ - **Timezone Dropdown:** Removed timezone selection that was not used by the notification scheduler
+ - **Notification Frequency:** Renamed to "Check Frequency" with clearer description as a global system setting
+ - **JavaScript Cleanup:** Removed all references to unused fields including variable definitions, event listeners, and data loading functions
+ - **Status Display Cleanup:** Removed "Notification Time" from current status display since it's no longer relevant
+ - **Cache-Busting:** Updated version parameters from `v=20250529005` to `v=20250529006` to force browser cache refresh
+ - **Functional Clarity:** Apprise card now only contains settings that actually affect system behavior:
+ - ✅ Enable/Disable toggle, Notification Mode, Warranty Scope, Notification URLs, Notification Days, Check Frequency, Message Title Prefix
+ - ❌ Removed: Notification Time, Timezone (these are now properly handled in user notification preferences)
+ - **User Experience:** Clear separation between admin system configuration and user personal notification timing preferences
+ - _Files: `frontend/settings-new.html`, `frontend/settings-new.js`_
+
+### Code Quality & Maintenance
+- **Legacy OIDC Code Cleanup:** Removed ~290 lines of commented-out and orphaned OIDC code from main application file for improved maintainability.
+ - **Removed Components:**
+ - **Commented Route Definitions:** Eliminated ~150 lines of commented-out `/api/oidc/login` and `/api/oidc/callback` route definitions
+ - **Orphaned Callback Logic:** Removed ~140 lines of disconnected OIDC callback handling code including user provisioning, token handling, and error redirection logic
+ - **Dead Code Elimination:** Cleaned up legacy authentication code that was replaced by the Blueprint architecture
+ - **OIDC Functionality Preserved:** All OIDC functionality remains fully operational through the proper Blueprint architecture in `backend/oidc_handler.py`
+ - **File Size Reduction:** Reduced `backend/app.py` from ~3,477 lines to ~3,200 lines (~8% reduction)
+ - **Code Organization:** Improved code readability and maintainability by removing confusing commented-out legacy implementations
+ - **Blueprint Verification:** Confirmed `oidc_bp` Blueprint is properly registered and functional at `/api/oidc/*` endpoints
+ - _Files: `backend/app.py`_
+
+## 0.10.1.0 - 2025-06-10
+
+### Added
+- **Public Global Warranty View for All Users**
+ - Extended global warranty view access to all authenticated users (previously admin-only)
+ - **Regular Users**: Can view all warranties from all users but can only edit/delete their own
+ - **Admin Users**: Can edit/delete any warranty in global view, maintaining full administrative control
+ - Added read-only protection: edit/delete buttons are replaced with view-only eye icon for warranties not owned by current user (unless user is admin)
+ - Updated UI labels and tooltips to reflect the new public access model
+ - Maintains full admin functionality while providing transparency to all users
+
+- **Admin Global View Control Settings**
+ - Added admin setting to enable/disable the global view feature site-wide
+ - New "Global View Enabled" toggle in Site Settings section of admin panel
+ - New "Global View Admin Only" toggle to restrict global view access to administrators only
+ - When disabled, global view switcher is hidden from all users (including non-admins)
+ - When admin-only is enabled, only administrators can access global view feature
+ - Real-time enforcement: users automatically redirected to personal view if global view is disabled or restricted while they're using it
+ - Default enabled for backward compatibility with admin-only setting defaulted to false
+
+- **Global View for Status Dashboard**
+ - Extended global view functionality to the warranty status/analytics page
+ - Eligible users can now view warranty statistics and data from all users on the status dashboard
+ - Added view switcher (Personal/Global) to status page header with same permission controls as main page
+ - Global statistics include total counts, charts, and warranty tables from all users
+ - Owner information displayed in warranty tables when in global view mode
+ - Maintains same security model: admins can see all data, regular users see all data but with read-only access to others' warranties
+ - Seamless integration with existing global view settings and permissions
+- **Apprise Push Notifications Integration:** Comprehensive push notification system supporting 80+ services for warranty expiration alerts.
+ - **Backend Implementation:**
+ - **Apprise Handler (`backend/apprise_handler.py`):** Complete notification management system with configuration loading, URL validation, and multi-service support.
+ - **Database Migration (`backend/migrations/026_add_apprise_settings.sql`):** Added Apprise configuration settings to site_settings table.
+ - **API Endpoints (`backend/app.py`):** Full REST API for Apprise management including test notifications, URL validation, configuration reload, and manual triggers.
+ - **Scheduler Integration:** Enhanced existing notification scheduler to send both email and Apprise notifications simultaneously.
+ - **Environment Support:** Full environment variable support for Docker deployments with fallback to database configuration.
+ - **Frontend Implementation:**
+ - **Admin Settings UI (`frontend/settings-new.html`):** Complete Apprise configuration section with real-time status, URL management, and testing capabilities.
+ - **JavaScript Integration (`frontend/settings-new.js`):** Full frontend functionality for configuration management, URL validation, and notification testing.
+ - **Responsive Design (`frontend/settings-styles.css`):** Modern UI components including status badges, action grids, and mobile-responsive layouts.
+ - **Supported Services:** Discord, Slack, Telegram, Email (Gmail, Outlook), Microsoft Teams, Webhooks, Matrix, Pushover, Ntfy, Gotify, and 70+ more services.
+ - **Configuration Options:**
+ - **Multiple Notification URLs:** Support for comma-separated or line-separated notification service URLs
+ - **Flexible Timing:** Configurable notification days (e.g., 7,30 days before expiration) and daily notification time
+ - **Custom Branding:** Configurable title prefix for all notifications (e.g., "[Warracker]")
+ - **Test Functionality:** Send test notifications to verify configuration before enabling
+ - **URL Validation:** Real-time validation of Apprise notification URLs
+ - **Environment Configuration (`env.example`):** Complete example configuration file with detailed Apprise setup instructions and URL format examples.
+ - **Graceful Degradation:** System continues to function normally if Apprise is not installed, with appropriate admin notifications.
+ - _Files: `backend/apprise_handler.py`, `backend/migrations/026_add_apprise_settings.sql`, `backend/app.py`, `backend/db_handler.py`, `backend/requirements.txt`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/settings-styles.css`, `docker-compose.yml`, `env.example`_
+- **Warranty Type Filtering and Sorting:** Enhanced the home page with comprehensive warranty type filtering and sorting capabilities.
+ - **New Warranty Type Filter Dropdown:** Added a dedicated "Warranty Type" filter dropdown in the filter section, positioned between Vendor and Sort By filters.
+ - **Dynamic Filter Population:** The warranty type filter automatically populates with all unique warranty types found in existing warranties, sorted alphabetically.
+ - **Case-Insensitive Filtering:** Warranty type filtering works regardless of the case of the warranty type (e.g., "Standard", "standard", "STANDARD").
+ - **Sorting by Warranty Type:** Added "Warranty Type" as a sorting option in the Sort By dropdown, allowing users to sort warranties alphabetically by their warranty type.
+ - **Real-time Filtering:** Filter applies immediately when warranty type selection changes, working seamlessly with existing filters (Status, Tag, Vendor, Search).
+ - **Frontend Implementation:**
+ - Updated `frontend/index.html` to include warranty type filter dropdown and sort option
+ - Enhanced `frontend/script.js` with warranty type filtering logic, event listeners, and population function
+ - Added `populateWarrantyTypeFilter()` function to dynamically populate filter options from warranty data
+ - Integrated warranty type support into `currentFilters` object and `applyFilters()` function
+ - Added warranty type sorting logic to `renderWarranties()` function
+ - **Integration:** Works with the existing warranty type field that was previously added to add/edit forms, providing end-to-end warranty type management.
+ - _Files: `frontend/index.html`, `frontend/script.js`_
+
+- **Admin Global Warranty View:** Added a globe button for administrators to view all users' warranties alongside their own.
+ - **Backend API (`backend/app.py`):** New `/api/admin/warranties` endpoint that returns all warranties from all users with user information (username, email, display name).
+ - **Frontend UI (`frontend/index.html`):** Added admin-only "Scope" toggle with Personal/Global view buttons next to the existing view switcher.
+ - **Frontend Logic (`frontend/script.js`):**
+ - Added `isGlobalView` state management and view switching functions
+ - Enhanced warranty rendering to show owner information when in global view
+ - Automatic admin detection and UI initialization
+ - Dynamic title updates ("Your Warranties" vs "All Users' Warranties")
+ - **Styling (`frontend/style.css`):**
+ - Admin view switcher styling with primary color theme
+ - Owner information highlighting with colored border and background
+ - Responsive design for mobile devices
+ - **Security:** Admin-only access with proper permission checks and graceful fallbacks for non-admin users.
+ - _Files: `backend/app.py`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_
+
+- **Product Photo Thumbnails on Warranty Cards:** Enhanced warranty cards with visual product photo thumbnails for quick identification and easy access to full-size images.
+ - **Thumbnail Display:** Product photos now appear as small thumbnails in the top right corner of each warranty card, providing instant visual recognition of products.
+ - **Multi-View Support:** Photo thumbnails are displayed across all warranty viewing modes:
+ - **Grid View:** 60px thumbnails positioned elegantly in the card corner
+ - **List View:** 50px thumbnails for compact horizontal layouts
+ - **Table View:** 40px thumbnails optimized for dense data display
+ - **Interactive Photo Access:** Users can click on any product photo thumbnail to open the full-size image in a new browser tab for detailed viewing.
+ - **Secure Image Handling:** Product photos are served through secure authentication, ensuring only authorized users can view warranty images while maintaining fast loading performance.
+ - **Real-time Updates:** When users add or update product photos through the warranty edit forms, the thumbnail images immediately appear on warranty cards without requiring a page refresh.
+ - **Visual Feedback:** Photo thumbnails include hover effects and "Click to view full size image" tooltips to clearly indicate their interactive nature.
+ - **Responsive Design:** Photo thumbnails automatically scale and position appropriately across different screen sizes and device types.
+ - _Files: `frontend/script.js`, `frontend/style.css`_
+
+### Fixed
+- **Status Dashboard Chart.js Canvas Errors**
+ - Fixed "Canvas is already in use" errors on the status page that prevented charts from rendering properly
+ - **Chart Destruction**: Added proper chart destruction with error handling before creating new charts
+ - **Multiple Initialization Prevention**: Added initialization flags to prevent multiple dashboard initializations
+ - **DOM Event Protection**: Protected against duplicate DOM event handler attachments
+ - **Improved Error Handling**: Added try-catch blocks around chart creation and destruction operations
+ - **View Switching Stability**: Fixed chart recreation issues when switching between personal and global views
+ - **Result**: Status page charts now render reliably without canvas conflicts, multiple view switches work smoothly
+ - _Files: `frontend/status.js`_
+
+- **CSS Cache Busting for Domain Consistency**
+ - Added version parameters to CSS and JavaScript files across all major pages to prevent caching issues between local IP and domain access
+ - **CSS Files Updated:** `style.css?v=20250529005`, `header-fix.css?v=20250529005`, `mobile-header.css?v=20250529005`, `settings-styles.css?v=20250529005`
+ - **JavaScript Files Updated:** `script.js?v=20250529005`, `auth.js?v=20250529005`, `settings-new.js?v=20250529005`
+ - Updated Service Worker cache name to `warracker-cache-v2` and included all versioned files to force cache refresh
+ - Fixed styling inconsistencies where admin global warranty view and other features appeared differently between local IP and domain access
+ - Ensures all users get consistent styling and functionality across all pages including index, settings, and status pages
+ - _Files: `frontend/index.html`, `frontend/settings-new.html`, `frontend/status.html`, `frontend/script.js`, `frontend/sw.js`_
+- **Settings Page Admin Permission Issues:** Fixed critical database connection errors and 403 permission issues preventing regular users from accessing the settings page.
+ - **Backend Database Connection (`backend/app.py`):** Fixed inconsistent cursor variable usage in `delete_account()` function that was causing 500 errors when users attempted to delete their accounts (was using both `cursor` and `cur` variables inconsistently).
+ - **Frontend Admin Permission Checks (`frontend/settings-new.js`):** Added comprehensive admin permission checks to prevent non-admin users from triggering 403 errors:
+ - **Initial Load Protection:** Wrapped admin-only settings calls (`loadSiteSettings()`, `loadAppriseSettings()`, `loadAppriseSiteSettings()`) with user admin status checks during page initialization.
+ - **Deferred Load Protection:** Added admin checks for delayed Apprise settings loading to prevent unauthorized API calls.
+ - **Graceful 403 Handling:** Enhanced `loadSiteSettings()` function with proper 403 response handling that hides admin sections instead of showing error messages.
+ - **Improved Error Messaging:** Fixed misleading "Account cannot be deleted in offline mode" error by removing problematic nested try-catch that was masking actual API error messages. Users now see specific backend error messages instead of generic offline warnings.
+ - **Root Cause:** Settings page was unconditionally calling admin-only API endpoints for all users, causing 403 errors and confusing error messages for regular users.
+ - **Result:** Regular users can now access settings page without errors, see only relevant settings sections, and get clear error messages when actual issues occur. Admin users continue to see all settings sections as expected.
+ - _Files: `backend/app.py`, `frontend/settings-new.js`_
+
+- **Settings Persistence Critical Fixes:** Resolved major settings page persistence issues where user preferences would appear to save but revert to defaults when navigating away and returning.
+ - **Backend Settings UPDATE Logic (`backend/app.py`):** Fixed critical bug in `/api/auth/preferences` endpoint where Apprise notification settings weren't being properly saved to the database:
+ - **Column Detection Fix:** Changed condition from `if apprise_notification_time and has_apprise_notification_time_col:` to `if apprise_notification_time is not None and has_apprise_notification_time_col:` to handle empty string values properly
+ - **Complete Field Mapping:** Added missing Apprise fields (`notification_channel`, `apprise_notification_time`, `apprise_notification_frequency`, `apprise_timezone`) to SELECT query return fields
+ - **Preference Response Mapping:** Enhanced preference mapping to include all Apprise settings in API responses
+ - **Frontend Race Condition Fixes (`frontend/settings-new.js`):** Eliminated multiple simultaneous API calls that were causing preference loading conflicts:
+ - **Duplicate Request Prevention:** Fixed `loadPreferences()` being called 4 times simultaneously, causing race conditions
+ - **API Priority Logic:** Ensured API data takes precedence over localStorage when both exist
+ - **UI Synchronization:** Added proper dark mode toggle sync between API and UI state
+ - **Authentication Token Standardization:** Unified token usage pattern across all preference save functions
+ - **Root Cause:** Backend was silently failing to save Apprise settings due to strict conditional logic, while frontend race conditions were creating inconsistent data states
+ - **Result:** Settings now persist correctly across page navigations, with all notification preferences saving and loading reliably
+ - _Files: `backend/app.py`, `frontend/settings-new.js`_
+
+- **Notification System Comprehensive Overhaul:** Fixed critical timing and duplicate notification issues affecting both email and Apprise scheduled notifications.
+ - **Timing Logic Precision (`backend/notifications.py`):** Completely rewrote notification timing calculation for accurate delivery:
+ - **Precise Windows:** Changed from aggressive "send_window or next_miss_window" logic to exact "0 <= time_diff <= 2" minute windows
+ - **Post-Target Delivery:** Notifications now only send AFTER target time (not before) within 2-minute window to prevent early delivery
+ - **Enhanced Time Calculations:** Added comprehensive timezone handling with detailed debug logging showing exact time differences
+ - **Duplicate Prevention System (`backend/notifications.py`):** Implemented robust duplicate prevention using in-memory tracking:
+ - **Separate Tracking:** Independent tracking for `email_{user_id}_{date}` and `apprise_{user_id}_{date}` patterns
+ - **Daily Reset Logic:** Automatic cleanup for day rollover handling across different timezones
+ - **Collision Prevention:** Added 0.1s delay for manual triggers to prevent collision with scheduled jobs
+ - **Column Mismatch Fixes (`backend/notifications.py`):** Fixed database errors causing notification failures:
+ - **Error Handling:** Added try/catch around column unpacking at line 327 to handle schema mismatches
+ - **Variable Consistency:** Fixed missing `apprise_timezone` variable in debug logging sections
+ - **Graceful Degradation:** System continues operating even with partial database schema issues
+ - **Enhanced Debug Output (`backend/notifications.py`):** Added comprehensive logging for troubleshooting:
+ - **Time Difference Display:** Shows exact calculations like "email_time=08:20(diff:-61), apprise_time=23:28(diff:-976)"
+ - **Eligibility Reasons:** Clear logging explaining why users are/aren't eligible for notifications
+ - **Real-time Diagnostics:** Live timing calculations visible in Docker logs for debugging
+ - **Root Cause:** Overly aggressive timing windows caused duplicate emails, while backend save issues prevented Apprise settings from persisting, leading to notifications not being scheduled
+ - **Result:** Both email and Apprise notifications now work reliably with precise timing, no duplicates, and proper settings persistence
+ - _Files: `backend/notifications.py`, `backend/app.py`_
+
+
+
+#### Technical Implementation for Global View Features
+- **Backend (app.py):**
+ - Added new `/api/warranties/global` endpoint accessible to all authenticated users (not just admins)
+ - Added `global_view_enabled` setting to site settings with default value 'true'
+ - Added `global_view_admin_only` setting to site settings with default value 'false'
+ - Added `/api/settings/global-view-status` endpoint for checking global view availability per user
+ - Enhanced `/api/warranties/global` endpoint to check both global view settings and user admin status
+ - Added new `/api/statistics/global` endpoint for global warranty statistics with user information
+- **Frontend (script.js):**
+ - Renamed `initAdminViewControls()` to `initViewControls()` and removed admin-only restrictions
+ - Updated `switchToGlobalView()` to check global view setting before switching
+ - Added ownership and admin validation logic to conditionally render edit/delete buttons vs view-only placeholder
+ - Admins see edit/delete buttons for all warranties, regular users only for their own
+ - Modified API endpoint from `/api/admin/warranties` to `/api/warranties/global` for public access
+ - Added real-time global view status checking and automatic fallback to personal view
+- **Frontend (index.html):** Updated tooltips and labels to reflect public access
+- **Frontend (style.css):** Added styling for view-only placeholder button with eye icon
+- **Frontend (settings-new.html):** Added Global View Enabled and Global View Admin Only toggles in Site Settings section
+- **Frontend (settings-new.js):** Added loading and saving logic for both global view settings
+- **Frontend (status.html):** Added view switcher controls and owner column to warranty table for global view
+- **Frontend (status.js):** Added global view functionality with API switching, table column management, and permission checking
+
+#### Security Features
+- Backend endpoint still requires authentication (all users must be logged in)
+- Frontend validates warranty ownership and admin status before showing edit/delete buttons
+- **Regular users** can only modify warranties they own, even in global view
+- **Admin users** can modify any warranty in global view, maintaining administrative privileges
+- Maintains data privacy while providing transparency
+
+#### User Experience
+- Seamless view switching between personal and global views for all users
+- Clear visual indication (eye icon) when viewing others' warranties
+- Consistent UI patterns with existing admin functionality
+- Enhanced tooltips explaining read-only access for non-owned warranties
+
+### Enhanced
+- **Footer Links:** Updated all "Powered by Warracker" footer links across the application to point to `https://warracker.com` instead of the GitHub repository, providing users with direct access to the official website.
+ - **Files Updated:** `index.html`, `login.html`, `register.html`, `reset-password.html`, `reset-password-request.html`, `settings-new.html`, `status.html`, `auth-redirect.html`, and `about.html`
+ - **Result:** Consistent branding and improved user experience with direct access to the official Warracker website.
+
+- **PostgreSQL Security Hardening:** Removed unnecessary SUPERUSER privileges from the application database user, significantly improving security posture.
+ - **Security Improvement:** Eliminated SUPERUSER grants that provided excessive and unnecessary privileges to the application database user
+ - **Files Modified:**
+ - `backend/fix_permissions.sql`: Removed `ALTER ROLE %(db_user)s WITH SUPERUSER;`
+ - `backend/migrations/011_ensure_admin_permissions.sql`: Commented out SUPERUSER grant
+ - `Dockerfile`: Removed retry loop attempting to grant SUPERUSER privileges via psql
+ - **Principle of Least Privilege:** Application now operates with only the specific database privileges required for normal operation (CREATE/DROP/ALTER on tables, sequences, functions, etc.)
+ - **Testing Verified:** Full application functionality confirmed to work correctly without SUPERUSER privileges, including migrations, user management, and all admin operations
+ - **Security Benefit:** Significantly reduces attack surface - if the application is compromised, an attacker no longer has complete database administrative control
+ - **Result:** Maintained full application functionality while eliminating unnecessary security risks
+
+## 0.10.0.0 - 2025-06-4
+
+### Fixed
+- **View Preference Persistence Issue:** Fixed user view preferences (Grid, List, Table) not consistently persisting across logins.
+ - **Backend (`backend/app.py`):** Modified `/api/auth/login` endpoint to include `is_admin` flag in the returned user object, ensuring proper view preference key prefix calculation immediately after login.
+ - **Frontend (`frontend/script.js`):**
+ - Enhanced `switchView()` function with `saveToApi` parameter to control when view preferences are saved to the API, preventing unintended overwrites during initialization.
+ - Modified `loadViewPreference()` to call `switchView` with `saveToApi = false` to prevent overwriting user's actual preferences with defaults.
+ - Updated storage event listener for cross-tab synchronization to prevent redundant API saves when syncing view preferences between browser tabs.
+ - **Root Cause:** Missing `is_admin` flag caused incorrect localStorage prefix usage and race conditions where preferences were saved with wrong prefix then not found when correct prefix was established.
+ - **Result:** View preferences now properly persist across logins and synchronize between browser tabs for both admin and regular users.
+- **Password Management Issues:** Fixed critical password change and reset functionality problems.
+ - **Missing Password Change Endpoint (`backend/app.py`):** Implemented `/api/auth/password/change` endpoint to allow logged-in users to change their passwords through the Settings page. The endpoint validates current password, checks new password strength, and securely updates the user's password hash.
+ - **Frontend Error Handling (`frontend/settings-new.js`):** Fixed misleading "Password cannot be changed in offline mode" error by removing nested try-catch block that was masking real API error messages. Now properly displays specific backend error messages.
+ - **Password Reset Link Issue (`frontend/reset-password.html`):** Fixed "Invalid or Expired Link" error by removing premature token verification that was calling a non-existent `/api/auth/password/verify-token` endpoint. Token validity is now properly checked only during form submission.
+ - **Root Cause:** Backend endpoint was missing entirely, frontend had incorrect error handling, and reset page was making unnecessary token verification calls.
+ - **Result:** Users can now successfully change passwords while logged in and use password reset links without encountering false error messages.
+- **SMTP Port 587 (STARTTLS) Functionality:** Enhanced email sending to support both port 465 (SMTPS/SSL) and port 587 (STARTTLS) configurations.
+ - **Enhanced SMTP Connection Logic (`backend/app.py`):** Updated `send_password_reset_email()`, `send_expiration_notifications()`, and `send_email_change_verification_email()` functions with robust port-based SMTP logic.
+ - **Port 465:** Uses `smtplib.SMTP_SSL()` for direct SSL connection
+ - **Port 587:** Uses `smtplib.SMTP()` followed by `starttls()` for STARTTLS encryption
+ - **Other Ports:** Respects `SMTP_USE_TLS` environment variable for explicit STARTTLS control
+ - **Environment Variable Support:** Added intelligent defaults where `SMTP_USE_TLS` defaults to true for port 587 unless explicitly set to false, ensuring proper STARTTLS behavior.
+ - **Root Cause:** Previous logic used restrictive hostname-based conditions (`if smtp_host != 'localhost'`) instead of proper port-based SMTP configuration, causing STARTTLS failures with external SMTP servers on port 587.
+ - **Result:** Email sending now works reliably with both common SMTP configurations, supporting major email providers like Gmail, Office 365, and other services using port 587.
+- **Header Appearance Standardization (`frontend/reset-password-request.html`, `frontend/reset-password.html`):** Standardized headers to match consistent appearance across all pages.
+ - **Missing CSS Includes:** Added `header-fix.css` and `fix-auth-buttons-loader.js` to ensure consistent header styling and behavior.
+ - **Clickable Title:** Made "Warracker" title a clickable link to `index.html` for consistent navigation, matching other auth pages like `login.html` and `register.html`.
+ - **Registration Status Script:** Added `registration-status.js` for consistent functionality across auth pages.
+ - **Root Cause:** Pages were missing key CSS files and scripts that ensure header consistency, and the title was not a link unlike other pages.
+ - **Result:** Headers now have identical appearance, dimensions, and responsive behavior as other application pages, providing consistent user experience.
+### Enhanced
+- **Footer Links:** Updated all "Powered by Warracker" footer links across the application to point to `https://warracker.com` instead of the GitHub repository, providing users with direct access to the official website.
+ - **Files Updated:** `index.html`, `login.html`, `register.html`, `reset-password.html`, `reset-password-request.html`, `settings-new.html`, `status.html`, `auth-redirect.html`, and `about.html`
+ - **Result:** Consistent branding and improved user experience with direct access to the official Warracker website.
+
+## 0.9.9.9 - 2025-06-01
+
+### Added
+- **OIDC SSO (Single Sign-On) Integration:**
+ - Implemented OpenID Connect (OIDC) authentication flow using Authlib, allowing users to log in via external OIDC providers (e.g., Google, Keycloak).
+ - **Backend (`app.py`):**
+ - OIDC client configuration (Client ID, Secret, Issuer URL, Scope, Provider Name) is dynamically loaded from the `site_settings` database table at application startup.
+ - OIDC feature can be enabled/disabled globally via the `oidc_enabled` setting in the database.
+ - Added OIDC-specific routes: `/api/oidc/login` (initiates login) and `/api/oidc/callback` (handles redirect from IdP).
+ - User provisioning: If an OIDC user doesn't exist locally, a new user account is created. Existing OIDC users are logged in.
+ - Updated Admin Settings API (`/api/admin/settings`) to manage these OIDC parameters.
+ - Database migration `023_add_oidc_columns_to_users.sql` adds `oidc_sub`, `oidc_issuer` to `users` table and `login_method` to `user_sessions` table for linking local users to OIDC identities.
+ - **Frontend:**
+ - **Login Page (`login.html`, `auth.js`):** Added an "Login with SSO Provider" button that initiates the OIDC flow.
+ - **Admin Settings Page (`settings-new.html`, `settings-new.js`):** New "OIDC SSO Configuration" section for admins to enable/disable OIDC and configure provider details.
+ - **Auth Redirect Page (`auth-redirect.html`):** Handles the token received from the `/api/oidc/callback` and logs the user in.
+ - **Dependencies (`requirements.txt`):** Added `Authlib` and `requests`.
+ - _Files: `backend/app.py`, `backend/migrations/023_add_oidc_columns_to_users.sql`, `backend/requirements.txt`, `frontend/login.html`, `frontend/auth.js`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/auth-redirect.html`_
+- **SSO Registration Control:** When the site's registration setting is disabled, new users cannot register via SSO. Only existing users who already have accounts can use SSO to log in. This provides administrators with granular control over user registration while maintaining SSO functionality for existing users.
+ - **Backend:** Enhanced OIDC callback handler to check the `registration_enabled` site setting before creating new user accounts via SSO.
+ - **Frontend:** Added appropriate error message for users when SSO registration is blocked due to disabled registrations.
+ - First user registration via SSO is still allowed regardless of the setting (same as regular registration).
+ - _Files: `backend/oidc_handler.py`, `frontend/auth-redirect.html`_
+- **Provider-Specific SSO Button Branding:** Enhanced the SSO login button to show provider-specific branding and icons for well-known OIDC providers.
+ - **Supported Providers:** Google, GitHub, Microsoft/Azure, Facebook, Twitter, LinkedIn, Apple, Discord, GitLab, Bitbucket, Keycloak, and Okta.
+ - **Dynamic Button Text:** Shows "Login with Google", "Login with GitHub", etc., based on the configured `OIDC_PROVIDER_NAME`.
+ - **Provider Icons:** Uses appropriate Font Awesome icons for each provider (e.g., Google logo for Google, GitHub logo for GitHub).
+ - **Brand Colors:** Each provider button uses authentic brand colors with proper hover effects.
+ - **Fallback Support:** Unknown providers display the generic "Login with SSO Provider" button with default styling.
+ - **Environment Integration:** Works automatically with the `OIDC_PROVIDER_NAME` environment variable and database settings.
+ - _Files: `frontend/login.html`, `backend/oidc_handler.py`_
+- **Exact Expiration Date Input:** Enhanced warranty entry to support exact expiration dates as an alternative to duration-based input.
+ - **New Warranty Input Method:** Users can now choose between "Warranty Duration" (years/months/days) and "Exact Expiration Date" options when adding or editing warranties.
+ - **UI Enhancements:** Added radio button selection for warranty entry method with smooth form field transitions and validation.
+ - **Backend Support:** Both `add_warranty` and `update_warranty` API endpoints now handle `exact_expiration_date` parameter alongside duration fields.
+ - **Smart Duration Display:** Warranty cards automatically calculate and display duration text even when using exact expiration dates, eliminating "N/A" values.
+ - **Form Validation:** Enhanced validation ensures either exact date or duration is provided for non-lifetime warranties, with appropriate error messages.
+ - **Date Calculation:** Added robust date calculation helper function that properly handles different month lengths, leap years, and edge cases.
+ - _Files: `frontend/index.html`, `frontend/script.js`, `frontend/style.css`, `backend/app.py`_
+- **Complete Field Updates:** All warranty fields (product info, dates, serial numbers, tags, documents) update immediately in the interface.
+ - **Fallback Safety:** Maintains fallback to server reload if local update fails, ensuring data consistency.
+ - _Files: `frontend/script.js`_
+- **Memory Usage Optimization:** Significantly reduced RAM consumption for better performance on resource-constrained servers.
+ - **Dynamic Memory Modes:** Configurable via `WARRACKER_MEMORY_MODE` environment variable with "optimized" (default), "ultra-light", and "performance" options.
+ - **Optimized Mode:** 2 gevent workers with 128MB memory limits (~60-80MB total RAM usage).
+ - **Ultra-Light Mode:** 1 sync worker with 64MB memory limit (~40-50MB total RAM usage for minimal servers).
+ - **Performance Mode:** 4 gevent workers with 256MB memory limits (~150-200MB total RAM usage for high-performance servers).
+ - **Worker Configuration:** Added memory limits per worker, connection pooling optimization, and preload_app for memory sharing.
+ - **Database Pool:** Optimized connection pool from 10 to 4 maximum connections with memory-conscious settings.
+ - **Flask Configuration:** Added memory-efficient settings including disabled JSON sorting, optimized session handling, and file serving optimizations.
+ - **Dependency Addition:** Added gevent for more efficient async request handling compared to sync workers.
+ - **Expected Reduction:** RAM usage configurable from ~40MB (ultra-light) to ~200MB (performance) based on server specifications.
+ - _Files: `backend/gunicorn_config.py`, `backend/requirements.txt`, `backend/app.py`, `backend/db_handler.py`, `docker-compose.yml`_
+
+### Changed
+- **Environment Variables for OIDC (Docker):** While OIDC configuration is primarily managed via the database through the admin UI, the `docker-compose.yml` can include placeholder environment variables for initial setup or documentation:
+ - `OIDC_ENABLED` (e.g., `true` or `false`)
+ - `OIDC_PROVIDER_NAME` (e.g., `google`, `keycloak`)
+ - `OIDC_CLIENT_ID`
+ - `OIDC_CLIENT_SECRET`
+ - `OIDC_ISSUER_URL`
+ - `OIDC_SCOPE` (e.g., `openid email profile`)
+- **`FRONTEND_URL` Environment Variable:** Emphasized the importance of correctly setting the `FRONTEND_URL` environment variable for the backend service in `docker-compose.yml` to ensure correct OIDC callback redirects.
+ - _Files: `docker-compose.yml`, `Docker/docker-compose.yml`_
+
+### Fixed
+- Resolved various startup and runtime errors related to OIDC client initialization in a multi-worker (Gunicorn) environment, particularly concerning database connection pool stability and consistent loading of OIDC settings.
+- Corrected OIDC metadata fetching by ensuring the proper Issuer URL is used (e.g., `https://accounts.google.com` for Google).
+- Resolved `TypeError: Cannot read properties of null (reading 'classList')` during logout on `about.html` by ensuring the `loadingContainer` element is present and accessible to `script.js`'s `showLoading()` function. Modified `showLoading()` and `hideLoading()` to dynamically find the container if not initially available.
+- Fixed `SyntaxError: Identifier 'AuthManager' has already been declared` on `about.html` by removing a duplicate import of `auth.js` from the `<head>`, ensuring it is loaded only once at the end of the `<body>`.
+- Standardized the user menu dropdown button ID to `userMenuBtn` across `index.html`, `status.html`, and `about.html`. Consolidated user menu JavaScript logic into `auth.js`, removing redundant code from `settings-new.js` and `fix-auth-buttons.js` to ensure consistent dropdown behavior.
+ - _Files: `backend/app.py`, `frontend/about.html`, `frontend/script.js`, `frontend/index.html`, `frontend/status.html`, `frontend/auth.js`, `frontend/settings-new.js`, `frontend/fix-auth-buttons.js`_
+- **SSO Warranty Display Issue:** Fixed a critical timing problem where SSO users would see a blank warranty list after login. The issue was caused by a race condition where user preferences were loaded before user authentication was fully established.
+ - Enhanced `auth-redirect.html` to fetch and store user information immediately after SSO login, ensuring `user_info` is available when the main application loads.
+ - Fixed preference key prefix calculation to prevent mismatched user preference keys for SSO users.
+ - _Files: `frontend/auth-redirect.html`, `frontend/auth.js`, `frontend/script.js`_
+- **SSO Tag Creation Issue:** Resolved an issue where SSO users could not create new tags due to authentication token handling problems.
+ - Updated tag creation functions (`createTag`, `updateTag`, `deleteTag`) to use `window.auth.getToken()` instead of directly accessing localStorage.
+ - Added enhanced error handling and debugging for tag creation API calls.
+ - Ensured consistent token management across all tag-related operations.
+ - _Files: `frontend/script.js`_
+- **Database Tag Constraint Issue:** Fixed database constraint violation that prevented users from creating tags with names that already existed for other users.
+ - Created migration `024_fix_tags_constraint.sql` to update the database schema.
+ - Dropped the old `tags_name_key` unique constraint that only considered tag names.
+ - Added new `tags_name_user_id_key` constraint allowing the same tag name for different users.
+ - Added proper user_id foreign key constraint and performance index.
+ - _Files: `backend/migrations/024_fix_tags_constraint.sql`_
+- **About Page User Menu Issue:** Fixed user menu dropdown not functioning on the about page for SSO users.
+ - Resolved script loading order conflicts that prevented user menu event listeners from being attached.
+ - Moved inline authentication check from head to body to prevent timing conflicts with `auth.js`.
+ - Added backup user menu handler specifically for the about page with enhanced debugging.
+ - Fixed JavaScript error caused by `getEventListeners` function not being available in all browsers.
+ - _Files: `frontend/about.html`, `frontend/auth.js`_
+- **About Page Logout Issue:** Resolved logout functionality errors on the about page.
+ - Added safe loading spinner functions specifically for the about page to prevent `TypeError: Cannot read properties of null (reading 'classList')` error.
+ - Implemented backup logout handler with multiple fallback levels for reliability.
+ - Ensured logout works even when main auth system encounters errors.
+ - _Files: `frontend/about.html`, `frontend/script.js`_
+- **Immediate Warranty Updates:** Optimized warranty editing for instant UI updates without server reloads.
+ - **Performance Improvement:** Warranty changes now appear immediately in the UI instead of waiting for server data reload.
+ - **Local Data Sync:** Edit modal updates local warranty data instantly upon successful save, eliminating loading delays.
+ - **Robust Date Handling:** Enhanced date arithmetic for duration-based warranties with proper month/year overflow handling.
+ - **Complete Field Updates:** All warranty fields (product info, dates, serial numbers, tags, documents) update immediately in the interface.
+ - **Fallback Safety:** Maintains fallback to server reload if local update fails, ensuring data consistency.
+ - _Files: `frontend/script.js`_
+- **Warranty Entry Method Persistence:** Fixed warranty entry method selection not being remembered correctly in edit modal.
+ - **Issue:** When editing warranties that were created using "Exact Expiration Date" method, the edit modal would incorrectly switch to "Warranty Duration" method.
+ - **Root Cause:** Display logic was overwriting original duration values (0,0,0 for exact date method), making method detection impossible.
+ - **Solution:** Added `original_input_method` tracking to preserve the user's original warranty entry method choice.
+ - **Data Separation:** Implemented separate `display_duration_*` fields for warranty card display while preserving original duration values for method detection.
+ - **Enhanced Detection:** Edit modal now directly checks `original_input_method` field instead of guessing from duration data.
+ - **Result:** Users can now edit warranties and the modal correctly remembers whether they originally used "Warranty Duration" or "Exact Expiration Date" method.
+ - _Files: `frontend/script.js`_
+- **Notes Modal and Edit Modal Integration:** Fixed issues with notes editing workflow and seamless transition to warranty editing.
+ - **Notes Editing for Exact Date Warranties:** Resolved issue where warranties created with exact expiration dates couldn't have their notes edited via the notes-link modal due to invalid duration validation.
+ - **Stale Notes in Edit Modal:** Fixed problem where editing a warranty immediately after saving notes via the notes modal would show old note content instead of the newly saved content.
+ - **Notes Modal UI Issues:** Fixed "Edit Notes" button showing outdated note content when clicked after saving new notes in the same modal session.
+ - **Enhanced Notes Modal:** Added "Edit Warranty" button directly in the notes modal footer for seamless transition to full warranty editing without modal layering conflicts.
+ - **Immediate Data Sync:** Enhanced notes saving to immediately update the global warranties array, ensuring edit modal always shows current data.
+ - **Modal State Management:** Improved modal closing behavior when opening edit modal from notes modal to prevent UI conflicts.
+ - _Files: `frontend/script.js`_
+- **Status Page Edit Modal Consistency:** Fixed inconsistency between edit warranty modals on index.html and status.html pages.
+ - **Missing Warranty Entry Method Selection:** Added the "Warranty Entry Method" radio button selection to the status.html edit modal, allowing users to choose between "Warranty Duration" and "Exact Expiration Date" methods.
+ - **Missing Exact Expiration Field:** Added the hidden "Exact Expiration Date" input field that appears when the exact date method is selected.
+ - **Feature Parity:** The edit warranty modal on status.html now has identical functionality to the one on index.html, ensuring consistent user experience across both pages.
+ - **Complete Modal Structure:** All tabs (Product, Warranty, Documents, Tags), form fields, and functionality now match exactly between both pages.
+ - _Files: `frontend/status.html`_
+
+### Dependencies
+- **Updated Python Dependencies:** Resolved `pkg_resources` deprecation warning by updating backend dependencies to modern versions.
+ - **Gunicorn:** Updated from `20.1.0` to `23.0.0` - eliminates `pkg_resources` deprecation warning by using `importlib.metadata` instead.
+ - **Flask:** Updated from `2.0.1` to `3.0.3` - includes security patches and improved compatibility.
+ - **Werkzeug:** Updated from `2.0.1` to `3.0.3` - maintains compatibility with Flask 3.x.
+ - **Other Dependencies:** Updated `flask-cors`, `Flask-Login`, `PyJWT`, `email-validator`, `python-dateutil`, `Authlib`, `requests`, and `gevent` to latest stable versions.
+ - **Setuptools Protection:** Added `setuptools<81` pin to prevent future compatibility issues.
+ - _Files: `backend/requirements.txt`_
+
+### Frontend
+- **Chart.js Compatibility Fix:** Resolved "Chart is not defined" error on status page by replacing ES module version with UMD version.
+ - **Issue:** Status page charts failed to load with `ReferenceError: Chart is not defined` because the local `chart.js` file was in ES module format.
+ - **Root Cause:** ES modules require `<script type="module">` tags but the HTML was using regular `<script>` tags.
+ - **Solution:** Replaced ES module version with locally downloaded UMD (Universal Module Definition) version from Chart.js v4.4.9, eliminating CDN dependency.
+ - **Result:** Chart.js now loads properly with regular script tags and status page charts display correctly using the local file.
+ - _Files: `frontend/chart.js`_
+- **Product Name Hover Tooltips:** Added hover tooltips to display full product names when they are truncated with ellipsis.
+ - **Enhancement:** Long product names that get cut off with "..." now show the complete product name in a tooltip when hovered over.
+ - **Coverage:** Works across all warranty display modes (grid view, list view, table view) on the main warranties page and the status page table.
+ - **Implementation:** Added `title` attributes to warranty titles and product name cells using escaped HTML for security.
+ - **Result:** Users can now see full product names without having to edit or expand warranty details.
+ - _Files: `frontend/script.js`, `frontend/status.js`_
+- **Powered by Warracker Footer:** Added branded footer to all pages with dynamic theme support and GitHub repository link.
+ - **Feature:** Added "Powered by Warracker" footer to all application pages linking to the GitHub repository.
+ - **Theme Support:** Implemented JavaScript-based dynamic styling that automatically adapts to light/dark mode changes.
+ - **Light Mode:** Light gray background (`#f5f5f5`), dark text (`#333333`), blue links (`#3498db`) matching the logo.
+ - **Dark Mode:** Dark background (`#1a1a1a`), light text (`#e0e0e0`), light blue links (`#4dabf7`).
+ - **Real-time Updates:** Uses MutationObserver to detect theme changes and update footer styling automatically.
+ - **Cross-domain Compatibility:** Includes fallback inline styles and direct color values to ensure consistent display across different hosting environments.
+ - _Files: All frontend HTML pages, `frontend/style.css`_
+
+## [0.9.9.8] - 2025-05-24
### Added
- **Account Email Change:** Users can now change the email address associated with their account from the Settings page.
diff --git a/Docker/.env.example b/Docker/.env.example
new file mode 100644
index 0000000..0c5f823
--- /dev/null
+++ b/Docker/.env.example
@@ -0,0 +1,152 @@
+# Warracker Environment Variables Configuration
+# Copy this file to .env and customize the values for your deployment
+
+
+### ** Database Configuration**
+
+# Database connection settings
+DB_HOST=warrackerdb
+DB_NAME=warranty_db
+DB_USER=warranty_user
+DB_PASSWORD=warranty_password
+
+# Database admin credentials (used for migrations and setup)
+DB_ADMIN_USER=warracker_admin
+DB_ADMIN_PASSWORD=change_this_password_in_production
+
+# PostgreSQL-specific settings (for the database container)
+POSTGRES_DB=warranty_db
+POSTGRES_USER=warranty_user
+POSTGRES_PASSWORD=warranty_password
+
+
+### Security Configuration**
+
+# Application secret key for JWT tokens and Flask sessions
+# IMPORTANT: Generate a strong, unique secret key for production!
+SECRET_KEY=your_very_secret_flask_key_change_me
+
+# JWT token expiration time (in hours)
+JWT_EXPIRATION_HOURS=24
+
+
+### Email/SMTP Configuration**
+
+# SMTP server settings for sending notifications and password resets
+SMTP_HOST=smtp.gmail.com
+SMTP_PORT=587
+SMTP_PASSWORD=your_email_password
+
+# Optional SMTP settings
+SMTP_USE_TLS=true
+SMTP_USE_SSL=false
+
+
+### **URL Configuration**
+
+# Frontend URL (used for redirects and email links)
+# IMPORTANT: Must match your public-facing URL for OIDC and email links to work
+FRONTEND_URL=http://localhost:8005
+
+# Application base URL (used for links in emails and redirects)
+APP_BASE_URL=http://localhost:8005
+
+
+### **File Upload Configuration**
+
+# Maximum file upload size in megabytes
+MAX_UPLOAD_MB=32
+
+# Nginx maximum body size (should match or exceed MAX_UPLOAD_MB)
+NGINX_MAX_BODY_SIZE_VALUE=32M
+
+
+### **Performance & Memory Configuration**
+
+# Memory optimization mode
+# Options: optimized (default), ultra-light, performance
+# - optimized: 2 workers, ~60-80MB RAM usage (recommended for most deployments)
+# - ultra-light: 1 worker, ~40-50MB RAM usage (for very limited resources)
+# - performance: 4 workers, ~150-200MB RAM usage (for high-traffic deployments)
+WARRACKER_MEMORY_MODE=optimized
+
+
+### **OIDC/SSO Configuration (Optional)**
+
+# Enable/disable OIDC SSO functionality
+OIDC_ENABLED=false
+
+# OIDC Provider settings
+# Provider name (affects button branding: google, github, microsoft, keycloak, etc.)
+OIDC_PROVIDER_NAME=oidc
+
+# OIDC client credentials (obtain from your OIDC provider)
+OIDC_CLIENT_ID=
+OIDC_CLIENT_SECRET=
+
+# OIDC issuer URL (e.g., https://accounts.google.com)
+OIDC_ISSUER_URL=
+
+# OIDC scope (space-separated list of scopes)
+OIDC_SCOPE=openid email profile
+
+### **Development/Debugging Configuration (Optional)**
+
+# Flask environment (development/production)
+FLASK_ENV=production
+
+# Flask debug mode (true/false)
+FLASK_DEBUG=false
+
+# Flask run port (for development)
+FLASK_RUN_PORT=5000
+
+# Python unbuffered output (helpful for Docker logs)
+PYTHONUNBUFFERED=1
+
+
+### **Example Configurations**
+
+**Gmail SMTP:**
+```bash
+SMTP_HOST=smtp.gmail.com
+SMTP_PORT=587
+SMTP_PASSWORD=your_app_password
+SMTP_USE_TLS=true
+```
+
+**Google OIDC:**
+```bash
+OIDC_ENABLED=true
+OIDC_PROVIDER_NAME=google
+OIDC_CLIENT_ID=your_google_client_id.apps.googleusercontent.com
+OIDC_CLIENT_SECRET=your_google_client_secret
+OIDC_ISSUER_URL=https://accounts.google.com
+OIDC_SCOPE=openid email profile
+```
+
+**Production deployment:**
+```bash
+SECRET_KEY=super_long_random_string_generated_securely
+DB_PASSWORD=strong_database_password_123
+DB_ADMIN_PASSWORD=different_strong_admin_password_456
+FRONTEND_URL=https://warracker.yourdomain.com
+APP_BASE_URL=https://warracker.yourdomain.com
+SMTP_HOST=smtp.yourdomain.com
+MAX_UPLOAD_MB=64
+NGINX_MAX_BODY_SIZE_VALUE=64M
+WARRACKER_MEMORY_MODE=performance
+```
+
+## **How to Use**
+
+1. **Copy this configuration** into a file named `.env` in your Docker folder
+2. **Customize the values** according to your specific deployment needs
+3. **Generate strong passwords** for production use, especially for `SECRET_KEY`, `DB_PASSWORD`, and `DB_ADMIN_PASSWORD`
+4. **Set your domain URLs** correctly for `FRONTEND_URL` and `APP_BASE_URL` if deploying publicly
+5. **Configure SMTP** if you want email functionality for password resets and notifications
+6. **Set up OIDC/SSO** if you want single sign-on capabilities
\ No newline at end of file
diff --git a/Docker/docker-compose.yml b/Docker/docker-compose.yml
index a14d7f6..7113612 100644
--- a/Docker/docker-compose.yml
+++ b/Docker/docker-compose.yml
@@ -17,6 +17,19 @@ services:
- 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)
+ # OIDC SSO Configuration (User needs to set these based on their OIDC provider)
+ - OIDC_PROVIDER_NAME=${OIDC_PROVIDER_NAME:-oidc}
+ - OIDC_CLIENT_ID=${OIDC_CLIENT_ID:-} # e.g., your_oidc_client_id_from_provider
+ - OIDC_CLIENT_SECRET=${OIDC_CLIENT_SECRET:-} # e.g., your_oidc_client_secret_from_provider
+ - OIDC_ISSUER_URL=${OIDC_ISSUER_URL:-} # e.g., https://your-oidc-provider.com/auth/realms/your-realm
+ - OIDC_SCOPE=${OIDC_SCOPE:-openid email profile}
+ # URL settings (Important for OIDC redirects and email links)
+ # Ensure these point to the public-facing URL of your application
+ - FRONTEND_URL=${FRONTEND_URL:-http://localhost:8005}
+ - APP_BASE_URL=${APP_BASE_URL:-http://localhost:8005}
+ # Memory optimization settings
+ - WARRACKER_MEMORY_MODE=${WARRACKER_MEMORY_MODE:-optimized} # Options: optimized (default), ultra-light
+ - PYTHONUNBUFFERED=1
# - FLASK_DEBUG=0
depends_on:
warrackerdb:
@@ -41,4 +54,4 @@ services:
volumes:
postgres_data:
- warracker_uploads:
\ No newline at end of file
+ warracker_uploads:
diff --git a/Dockerfile b/Dockerfile
index ea0a60d..242c1aa 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -10,7 +10,10 @@ RUN apt-get update && \
curl \
postgresql-client \
supervisor \
- gettext-base && \
+ gettext-base \
+ libcurl4-openssl-dev \
+ libssl-dev \
+ ca-certificates && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
# (build-essential = C compiler + tools)
@@ -28,9 +31,31 @@ RUN pip install --no-cache-dir --upgrade pip
COPY backend/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
-# Copy backend code
+# Copy main application and config files to /app
COPY backend/app.py .
COPY backend/gunicorn_config.py .
+
+# Create the backend package directory in /app and copy modules into it
+RUN mkdir -p /app/backend
+COPY backend/__init__.py /app/backend/
+COPY backend/config.py /app/backend/
+COPY backend/auth_utils.py /app/backend/
+COPY backend/auth_routes.py /app/backend/
+COPY backend/db_handler.py /app/backend/
+COPY backend/extensions.py /app/backend/
+COPY backend/oidc_handler.py /app/backend/
+COPY backend/apprise_handler.py /app/backend/
+COPY backend/notifications.py /app/backend/
+COPY backend/paperless_handler.py /app/backend/
+COPY backend/localization.py /app/backend/
+COPY backend/warranties_routes.py /app/backend/
+COPY backend/admin_routes.py /app/backend/
+COPY backend/statistics_routes.py /app/backend/
+COPY backend/tags_routes.py /app/backend/
+COPY backend/utils.py /app/backend/
+COPY backend/file_routes.py /app/backend/
+
+# Copy other utility scripts and migrations
COPY backend/fix_permissions.py .
COPY backend/fix_permissions.sql .
COPY backend/migrations/ /app/migrations/
@@ -39,47 +64,32 @@ COPY backend/migrations/ /app/migrations/
COPY frontend/*.html /var/www/html/
COPY frontend/*.js /var/www/html/
COPY frontend/*.css /var/www/html/
+COPY frontend/manifest.json /var/www/html/manifest.json
# Add favicon and images
COPY frontend/favicon.ico /var/www/html/
COPY frontend/img/ /var/www/html/img/
+# Copy frontend JS directory for localization
+COPY frontend/js/ /var/www/html/js/
+
+# Copy localization files
+COPY locales/ /app/locales/
+COPY locales/ /var/www/html/locales/
+COPY babel.cfg /app/
# Configure nginx site
RUN rm /etc/nginx/sites-enabled/default
# Copy nginx.conf as a template
COPY nginx.conf /etc/nginx/conf.d/default.conf.template
-# Create startup script with database initialization
+# Create startup script with database initialization (SUPERUSER grant removed)
RUN echo '#!/bin/bash\n\
set -e # Exit immediately if a command exits with a non-zero status.\n\
echo "Running database migrations..."\n\
python /app/migrations/apply_migrations.py\n\
-echo "Ensuring admin role has proper permissions..."\n\
-# Retry logic for granting superuser privileges\n\
-max_attempts=5\n\
-attempt=0\n\
-while [ $attempt -lt $max_attempts ]; do\n\
- echo "Attempt $((attempt+1)) to grant superuser privileges..."\n\
- # Ensure DB variables are set (you might pass these at runtime)\n\
- if [ -z "$DB_PASSWORD" ] || [ -z "$DB_HOST" ] || [ -z "$DB_USER" ] || [ -z "$DB_NAME" ]; then\n\
- echo "Error: Database connection variables (DB_PASSWORD, DB_HOST, DB_USER, DB_NAME) are not set."\n\
- exit 1\n\
- fi\n\
- # Use timeout to prevent indefinite hanging if DB is not ready\n\
- if PGPASSWORD=$DB_PASSWORD psql -w -h $DB_HOST -U $DB_USER -d $DB_NAME -c "ALTER ROLE $DB_USER WITH SUPERUSER;" 2>/dev/null; then\n\
- echo "Successfully granted superuser privileges to $DB_USER"\n\
- break\n\
- else\n\
- echo "Failed to grant privileges (attempt $((attempt+1))), retrying in 5 seconds..."\n\
- sleep 5\n\
- attempt=$((attempt+1))\n\
- fi\n\
-done\n\
-if [ $attempt -eq $max_attempts ]; then\n\
- echo "Error: Failed to grant superuser privileges after $max_attempts attempts."\n\
- exit 1 # Exit if granting fails after retries\n\
-fi\n\
echo "Running fix permissions script..."\n\
python /app/fix_permissions.py\n\
+echo "Compiling translations..."\n\
+cd /app && python -c "import subprocess; subprocess.run([\"pybabel\", \"compile\", \"-d\", \"locales\"], check=False)"\n\
echo "Setup script finished successfully."\n\
# The actual services (gunicorn, nginx) will be started by Supervisor below\n\
exit 0 # Exit successfully, Supervisor takes over\n\
@@ -166,7 +176,7 @@ stderr_logfile_maxbytes=0
priority=10 ; Start after setup
[program:gunicorn]
-command=gunicorn --config /app/gunicorn_config.py app:app ; Start Gunicorn
+command=gunicorn --config /app/gunicorn_config.py "backend:create_app()" ; Start Gunicorn with Application Factory
directory=/app
autostart=true
autorestart=true ; Restart Gunicorn if it crashes
diff --git a/README.md b/README.md
index 73bd320..543a268 100644
--- a/README.md
+++ b/README.md
@@ -14,87 +14,80 @@ The easiest way to organize product warranties, monitor expiration dates, and st
<div align="center">
-<!-- ![GitHub forks](https://img.shields.io/github/forks/sassanix/Warracker?style=social) -->
![GitHub issues](https://img.shields.io/github/issues/sassanix/Warracker)
![GitHub license](https://img.shields.io/github/license/sassanix/Warracker)
![GitHub last commit](https://img.shields.io/github/last-commit/sassanix/Warracker)
![GitHub release](https://img.shields.io/github/v/release/sassanix/Warracker)
![GitHub contributors](https://img.shields.io/github/contributors/sassanix/Warracker)
-<!-- ![Downloads](https://img.shields.io/github/downloads/sassanix/Warracker/total) -->
+[![Discord](https://img.shields.io/badge/discord-chat-green?logo=discord)](https://discord.gg/PGxVS3U2Nw)
<p align="center">
- <img src="images/demo.gif" alt="Warracker Demo" width="600">
+ <img src="images/demo2.gif" alt="Warracker Demo" width="650">
</p>
#
+
+
</div>
+⭐ If you find Warracker helpful, we’d truly appreciate a star on GitHub! Your support motivates us to keep improving and building great new features.
-## 🌟 Overview
+#
-**Warracker** is a web-based application designed to simplify and centralize product warranty management.
+## 🌟Overview
-### 👨‍🔧 Why I Built This
+**Warracker** is a web-based application that simplifies the management of product warranties. It allows users to organize warranty information, monitor expiration dates, and securely store related documents.
-Warracker was born out of a frustrating and all-too-common experience: dealing with warranties.
-My father once called me for help with his broken dishwasher. We were confident it was still under warranty, especially since we had the invoice. But after countless back-and-forth with the manufacturer, they insisted it wasn’t covered due to a mismatch in the serial number. The truth? My father had unknowingly purchased **two** dishwashers, and we were referencing the wrong one.
+## 🔑 Key Features
-This wasn’t my first time running into warranty headaches, and I realized there had to be a better way. That’s when I decided to build **Warracker**, a simple tool to track purchases, receipts, and warranty periods in one place. Since then, Warracker has already saved me money by alerting me before my **car’s warranty expired**, allowing me to make necessary repairs just in time.
+| **Feature** | **Description** |
+| -------------------------------- | -------------------------------------------------------------------------------------------------------- |
+| 🗃️ **Centralized Management** | Track all your product warranties in one place |
+| 🧾 **Detailed Records** | Store purchase dates, durations, notes, and product photos with thumbnail previews |
+| 📄 **Document Storage** | Upload receipts, invoices, and manuals securely |
+| 🔔 **Proactive Alerts** | Get alerts for upcoming expirations via email or 100+ push services (Discord, Slack, etc.) using Apprise |
+| 🔍 **Quick Search and Filter** | Search by product name, serial number, vendor, tags, and more with real-time filtering |
+| #️⃣ **Multiple Serial Numbers** | Add and manage multiple serial numbers per product |
+| 🌍 **Global Warranty View** | Authenticated users can view global warranty data with role-based permissions |
+| 👥 **Multi-User Support** | Manage multiple accounts with admin controls and global access toggles |
+| 📤 **Data Export/Import** | Import/export warranty data via CSV |
+| ⚙️ **Customizable Settings** | Configure currency, date formats, notification timing, and branding |
+| 🌐 **Internationalization Support** | Support for multiple currencies and date formats tailored to regional preferences, enabling a seamless global user experience |
+| 🏷️ **Tagging** | Organize warranties using custom tags |
+| 🔐 **Password Reset** | Token-based, secure account recovery system |
+| 🔑 **OIDC SSO** | Single sign-on with providers like Google, GitHub, and Keycloak |
+| 📊 **Status Dashboard** | Visual analytics and stats with charts, tables, and global/user views |
+| 📱 **Responsive UI** | Mobile-friendly interface with admin tools and improved UX |
+| 📦 **Paperless-ngx Integration** | Store/manage documents directly in Paperless-ngx with file-level control |
+| 📖 **Localization Support** | [Full multilingual UI with 17 languages](https://github.com/sassanix/Warracker?tab=readme-ov-file#-localization-support), RTL support, instant language switching, and native name display |
-Inspired by [**Wallos**](https://github.com/ellite/Wallos), an app I used to track subscriptions, I thought, *why not do the same for warranties?* Now I want to make it available to anyone who has faced similar frustration.
+---
-Thank you for your support as I continue to improve Warracker.
+## Project Status
-## 🔑 Key Capabilities
+**Warracker is in active beta.**
+The essential features are reliable and ready for everyday use. Development is ongoing, with regular updates and improvements.
-* **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, 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, serial numbers, vendor, tags, or notes.
-* **Notes Support:** Add freeform notes to each warranty for extra context or reminders.
-* **Secure Access with Multi-User Support:** Create multiple user accounts for shared access; admins can enable or disable new user creation.
-* **System Status Dashboard:** Real-time system health and warranty summary.
-* **Data Export and Import:** Export warranty data to CSV, or import warranties from CSV files.
-* **Email Notifications:** Receive timely email reminders about upcoming expirations, configurable as daily, weekly, or monthly.
-* **Customizable Currency Symbols:** Display prices using your preferred currency symbol (\$, €, £, ¥, ₹, or a custom symbol).
-* **Customizable Dates:** Display dates based on your region.
-* **Tagging:** Organize warranties with flexible, multi-tag support.
-* **Password Reset:** Easily recover accounts through a secure, token-based password reset flow.
+* ✅ Stable core for tracking, notification , and managing warranty documents, files
+* ✅ Full support for self-hosted deployments
+* ⚒️ Advanced enhancements are still being worked on
+* ✍️ Your feedback and bug reports help shape the future of the app
-## 📸 Screenshots
+## 📸Screenshots
**Home Page**
-![image](https://github.com/user-attachments/assets/fa491480-4c75-4a1a-91d0-741141ca0183)
+<img width="1204" height="1019" alt="image" src="https://github.com/user-attachments/assets/bcb92f64-23fe-4a94-95c1-b55975abe94d" />
-
-![image](https://github.com/user-attachments/assets/67662203-b25b-46e5-920d-082537a02d42)
+<img width="1201" height="1012" alt="image" src="https://github.com/user-attachments/assets/52100483-fab8-4f4f-954b-64ff3a1bf496" />
**Status Dashboard**
-![image](https://github.com/user-attachments/assets/4c938b33-d6be-4787-a2d9-9153b0234ee2)
-
-## ✨ Features
-
-- **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, serial numbers, vendor, notes, or multiple tags.
-- **Multi-User Management:** Support for multiple user accounts; admin users can control whether new accounts can be created.
-- **Responsive Design:** Optimized for both desktop and mobile devices.
-- **Secure Login:** Safe and private authentication for all users.
-- **Password Reset:** Token-based secure password recovery flow.
-- **Email Alerts:** Customize how and when you receive expiration notifications.
-- **CSV Export/Import:** Full support for backing up and restoring warranty data.
-- **Currency Customization:** Personalize displayed prices with your preferred symbol.
+![image](https://github.com/user-attachments/assets/0f84cbcb-e434-42b9-9874-070f6a39292e)
-
-## 🛠️ Technology Stack
+## 🛠️Technology Stack
* **Frontend**: HTML, CSS, JavaScript
* **Backend**: Python with Flask
@@ -102,44 +95,30 @@ Thank you for your support as I continue to improve Warracker.
* **Containerization**: Docker and Docker Compose
* **Web Server**: Nginx
-## 🚀 Setup
+## 🗺️Roadmap
+
+* ✅ User Authentication
+* ✅ Settings Page
+* ✅ Status Page
+* ✅ Customizable Reminders
+* ✅ Email Notifications
+* ✅ Warranty Categories via Tags
+* ✅ CSV Import/Export
+* ✅ OIDC SSO Functionality
+* ✅ Advanced User/Admin Controls
+* ✅ Paperless-ngx integration
+* ✅ Localization Support
+* [ ] Audit trail
+* [ ] Warranty Claim Tracking
+* [ ] Calendar Integration
+
+## 🚀Setup
### Prerequisites
* Docker and Docker Compose installed on your system.
-* Git (for cloning the repository).
-
-### Fresh Installation 🆕
-1. Clone the repository:
- ```
- git clone https://github.com/sassanix/Warracker.git
- ```
-2. Navigate to the project directory:
- ```
- cd Warracker
- ```
-3. Start the application using Docker:
- ```
- docker compose up
- ```
-
-### Updating from a Previous Version ⬆️
-1. Pull the latest changes:
- ```
- git pull origin main
- ```
-2. Rebuild and restart the containers:
- ```
- docker compose down
- docker compose up --build
- ```
-3. **Access the Application:**
-
- Open your browser and navigate to `http://localhost:8005`.
-
-
-## 🐋 Pull Docker
+## 🐋Pull Docker
```
services:
@@ -149,34 +128,20 @@ services:
- "8005:80"
volumes:
- warracker_uploads:/data/uploads
- environment:
- - DB_HOST=warrackerdb
- - DB_NAME=warranty_db
- - DB_USER=warranty_user
- - DB_PASSWORD=${DB_PASSWORD:-warranty_password}
- - SMTP_HOST=smtp.email.com
- - 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
+ env_file:
+ - .env
depends_on:
warrackerdb:
condition: service_healthy
restart: unless-stopped
-
+
warrackerdb:
image: postgres:15-alpine
volumes:
- postgres_data:/var/lib/postgresql/data
- environment:
- - POSTGRES_DB=warranty_db
- - POSTGRES_USER=warranty_user
- - POSTGRES_PASSWORD=${DB_PASSWORD:-warranty_password}
+ env_file:
+ - .env
restart: unless-stopped
-
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 5s
@@ -188,9 +153,9 @@ volumes:
warracker_uploads:
```
-To get the docker compose file please go [here](https://github.com/sassanix/Warracker/tree/main/Docker)
+To get the docker compose file with environemts and .env example for warracker and the warrackerdb please go [here](https://github.com/sassanix/Warracker/tree/main/Docker)
-## 📝 Usage
+## 📝Usage
### Adding a Warranty
@@ -205,7 +170,7 @@ 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 CSV import
+## Product Information Entry Requirements for CSV import
| Field Name | Format / Example | Required? | Notes |
|----------------|-------------------------------------------|--------------------------------------------------------|-----------------------------------------------------------------------|
@@ -221,59 +186,51 @@ To get the docker compose file please go [here](https://github.com/sassanix/Warr
| **Vendor** | Text | ❌ No (Optional) | Name of the vendor or seller where the product was purchased. |
| **Tags** | Text (`tag1,tag2`) | ❌ No (Optional) | Use comma-separated values for multiple tags. |
+---
+## 🌐 Localization Support
-## 💻 Development
-
-### Local Development Environment
-
-1. Clone the repository.
-2. Make your changes.
-3. Build and run with Docker Compose:
+Warracker offers **full multilingual UI support** with **17 languages**, including **RTL (Right-to-Left) support**, instant language switching, and native name display.
- ```bash
- docker-compose build
- docker-compose up -d
- ```
+### Supported Languages
-### Project Structure
+| Language | Code | Native Name | Notes |
+|--------------------------|----------|----------------------|-----------------|
+| Arabic 🇸🇦 | ar | العربية | *RTL Support* |
+| Czech 🇨🇿 | cs | Čeština | |
+| German 🇩🇪 | de | Deutsch | |
+| English 🇬🇧 | en | English | *Default* |
+| Spanish 🇪🇸 | es | Español | |
+| Persian 🇮🇷 | fa | فارسی | *RTL Support* |
+| French 🇫🇷 | fr | Français | |
+| Hindi 🇮🇳 | hi | हिन्दी | |
+| Italian 🇮🇹 | it | Italiano | |
+| Japanese 🇯🇵 | ja | 日本語 | |
+| Korean 🇰🇷 | ko | 한국어 | |
+| Dutch 🇳🇱 | nl | Nederlands | |
+| Portuguese 🇵🇹 | pt | Português | |
+| Russian 🇷🇺 | ru | Русский | |
+| Ukrainian 🇺🇦 | uk | Українська | |
+| Chinese (Simplified) 🇨🇳 | zh_CN | 简体中文 | |
+| Chinese (Hong Kong) 🇭🇰 | zh_HK | 繁體中文 (香港) | |
-```
-warracker/
-├── backend/ # Python Flask backend
-│ ├── app.py # Main application logic
-│ ├── requirements.txt # Python dependencies
-│ └── init.sql # Database initialization
-├── frontend/ # Web frontend
-│ ├── index.html
-│ ├── script.js
-│ └── style.css
-├── docker-compose.yml # Docker configuration
-├── Dockerfile # Container definition
-└── nginx.conf # Web server configuration
-```
+### Language Selection Features
-## 🗺️ Roadmap
+- **Auto-Detection:** Automatically detects browser language on first visit
+- **User Preference:** Saves individual language choice to user profile
+- **Native Names:** Dropdown displays language names in native scripts for clarity
+- **Instant Switching:** Change languages in real-time without page reload
+---
-* User Authentication - **Completed ✅**
-* Settings Page - **Completed ✅**
-* Status Page - **Completed ✅**
-* Customizing Reminders to any day needed - **Completed ✅**
-* Email Reminders for Expiring Warranties - **Completed ✅**
-* Warranty Categories/Grouping through tags - **Completed ✅**
-* Warranty Data Import (CSV) - **Completed ✅**
-* Improved Search and Filtering - **Completed ✅**
-* Warranty claim tracking - **Planned**
-* Calendar Integration - **Planned**
+## Why I Built This
+Warracker was born from personal frustration with warranty confusion. When my father’s dishwasher broke, we had the invoice and assumed it was under warranty, only to find out we were referencing the wrong one, and the warranty had ended by a couple of months.
-## 🛠️ Troubleshooting
+That experience, along with others like it, made me realize how common and avoidable these issues are. So I built **Warracker**, a simple, organized way to track purchases, receipts, and warranties. It has already saved me money by reminding me to get car repairs done before my warranty expired.
-### Common Issues
+Inspired by [**Wallos**](https://github.com/ellite/Wallos), I wanted to bring the same clarity to warranties that it brought to subscriptions and share it with anyone who's ever been burned by missed coverage.
-* **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
+## Contributing
We welcome contributions and appreciate your interest in improving this project! To get started, please follow these steps:
@@ -289,7 +246,7 @@ We welcome contributions and appreciate your interest in improving this project!
`git push origin feature/amazing-feature`
5. **Open a Pull Request** with a clear explanation of your changes.
-### 📌 Contribution Guidelines
+### 📌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.
@@ -297,29 +254,45 @@ We welcome contributions and appreciate your interest in improving this project!
* **Follow project style**: Match the project's code style and naming conventions.
* **Be respectful**: We value inclusive and constructive collaboration.
-### Contributors:
-
-[<img src="https://avatars.githubusercontent.com/u/39465071?s=50&v=4" width="50"/>](https://github.com/sassanix)
-[<img src="https://avatars.githubusercontent.com/u/1223625?s=50&v=4" width="50"/>](https://github.com/humrochagf)
-[<img src="https://avatars.githubusercontent.com/u/5875512?s=50&v=4" width="50"/>](https://github.com/clmcavaney)
+### 🤝Contributors:
+<a href="https://github.com/sassanix/warracker/graphs/contributors">
+ <img src="https://contrib.rocks/image?repo=sassanix/warracker" />
+</a>
-### ❤️ Supporters:
+### ❤️Supporters:
[<img src="https://avatars.githubusercontent.com/u/8194208?u=7ee82feed0044f85bcfc39f001643fe81a188f66&v=4&s=50" width="50"/>](https://github.com/SirSpidey)
+[<img src="https://avatars.githubusercontent.com/u/6196195?v=4&s=50" width="50"/>](https://github.com/keithellis74)
+[<img src="https://avatars.githubusercontent.com/u/79404036?v=4&s=50" width="50"/>](https://github.com/CristianKerr)
+[<img src="https://avatars.githubusercontent.com/u/145632931?v=4&s=50" width="50"/>](https://github.com/rssmithtx)
+[<img src="https://avatars.githubusercontent.com/u/110860055?v=4&s=50" width="50"/>](https://github.com/Morethanevil)
+
+
[![Support Warracker](https://img.shields.io/badge/Support-Warracker-red?style=for-the-badge&logo=github-sponsors)](https://buymeacoffee.com/sassanix)
-## 📜 License
+
+## Join Our Community
+
+[![Join our Discord server!](https://invidget.switchblade.xyz/PGxVS3U2Nw)](https://discord.gg/PGxVS3U2Nw)
+
+Want to discuss the project or need help? Join our Discord community!
+
+## 📜License
This project is licensed under the GNU Affero General Public License v3.0 - see the [LICENSE](LICENSE) file for details.
-## 🙏 Acknowledgements
+## 🙏Acknowledgements
* Flask
* PostgreSQL
* Docker
+* Chart.js
+* Apprise
+* i18next
+
-## ⭐ Star History
+## ⭐Star History
<a href="https://star-history.com/#sassanix/Warracker&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=sassanix/Warracker&type=Date&theme=dark" />
diff --git a/babel.cfg b/babel.cfg
new file mode 100644
index 0000000..49f50b6
--- /dev/null
+++ b/babel.cfg
@@ -0,0 +1,3 @@
+[python: backend/**.py]
+[jinja2: **/templates/**.html]
+extensions=jinja2.ext.autoescape,jinja2.ext.with_
\ No newline at end of file
diff --git a/backend/__init__.py b/backend/__init__.py
new file mode 100644
index 0000000..1f4dbbd
--- /dev/null
+++ b/backend/__init__.py
@@ -0,0 +1,282 @@
+# backend/__init__.py
+import os
+import logging
+import psycopg2.errors
+from flask import Flask
+from werkzeug.middleware.proxy_fix import ProxyFix
+
+logger = logging.getLogger(__name__)
+
+def ensure_owner_exists():
+ """
+ Ensure that an application owner exists. This is a backup mechanism
+ in case the migration failed. Runs automatically on app startup.
+ """
+ from .db_handler import get_db_connection, release_db_connection
+
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # First check if the is_owner column exists (handles migration timing issue)
+ try:
+ cur.execute("""
+ SELECT column_name FROM information_schema.columns
+ WHERE table_name = 'users' AND column_name = 'is_owner'
+ """)
+ column_exists = cur.fetchone() is not None
+
+ if not column_exists:
+ logger.info("is_owner column not yet created, skipping owner check (migrations may still be running)")
+ return
+
+ # Check if any owner exists
+ cur.execute("SELECT COUNT(*) FROM users WHERE is_owner = TRUE")
+ owner_count = cur.fetchone()[0]
+ except psycopg2.errors.UndefinedColumn:
+ logger.info("is_owner column not yet created, skipping owner check (migrations may still be running)")
+ return
+
+ if owner_count == 0:
+ logger.info("No application owner found, attempting to promote first user...")
+
+ # Find the first user using multiple strategies
+ first_user_id = None
+
+ # Strategy 1: First user by created_at
+ try:
+ cur.execute("""
+ SELECT id FROM users
+ WHERE created_at IS NOT NULL
+ ORDER BY created_at ASC, id ASC
+ LIMIT 1
+ """)
+ result = cur.fetchone()
+ if result:
+ first_user_id = result[0]
+ except Exception as e:
+ logger.warning(f"Strategy 1 (created_at) failed: {e}")
+
+ # Strategy 2: First user by ID if Strategy 1 failed
+ if first_user_id is None:
+ try:
+ cur.execute("SELECT id FROM users ORDER BY id ASC LIMIT 1")
+ result = cur.fetchone()
+ if result:
+ first_user_id = result[0]
+ except Exception as e:
+ logger.warning(f"Strategy 2 (lowest ID) failed: {e}")
+
+ # Strategy 3: First admin user if other strategies failed
+ if first_user_id is None:
+ try:
+ cur.execute("SELECT id FROM users WHERE is_admin = TRUE ORDER BY id ASC LIMIT 1")
+ result = cur.fetchone()
+ if result:
+ first_user_id = result[0]
+ except Exception as e:
+ logger.warning(f"Strategy 3 (first admin) failed: {e}")
+
+ # Promote the user to owner if found
+ if first_user_id is not None:
+ try:
+ cur.execute("UPDATE users SET is_owner = TRUE WHERE id = %s", (first_user_id,))
+ conn.commit()
+ logger.info(f"✅ Automatically promoted user ID {first_user_id} to application owner")
+
+ # Log user info for confirmation
+ cur.execute("SELECT username, email FROM users WHERE id = %s", (first_user_id,))
+ user_info = cur.fetchone()
+ if user_info:
+ logger.info(f"Owner is now: {user_info[0]} ({user_info[1]})")
+ except Exception as e:
+ logger.error(f"Failed to promote user {first_user_id} to owner: {e}")
+ conn.rollback()
+ else:
+ logger.warning("No users found in system. First registered user will become owner.")
+ else:
+ # Log current owner for confirmation
+ cur.execute("SELECT id, username, email FROM users WHERE is_owner = TRUE")
+ owners = cur.fetchall()
+ logger.info(f"Application owner(s) confirmed: {[f'{o[1]} (ID:{o[0]})' for o in owners]}")
+
+ except Exception as e:
+ logger.error(f"Error in ensure_owner_exists: {e}")
+ if conn:
+ conn.rollback()
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+def init_oidc_client(current_app_instance, db_conn_func, db_release_func):
+ """Function to initialize OIDC client based on settings"""
+ from .extensions import oauth
+
+ logger.info("[FACTORY OIDC_INIT] Attempting to initialize OIDC client...")
+ conn = None
+ oidc_db_settings = {}
+ try:
+ conn = db_conn_func()
+ if conn:
+ with conn.cursor() as cur:
+ cur.execute("SELECT key, value FROM site_settings WHERE key LIKE 'oidc_%%'")
+ for row in cur.fetchall():
+ oidc_db_settings[row[0]] = row[1]
+ logger.info(f"[FACTORY OIDC_INIT] Fetched OIDC settings from DB: {oidc_db_settings}")
+ else:
+ logger.error("[FACTORY OIDC_INIT] Database connection failed, cannot fetch OIDC settings from DB.")
+ except Exception as e:
+ logger.error(f"[FACTORY OIDC_INIT] Error fetching OIDC settings from DB: {e}. Proceeding without DB settings.")
+ finally:
+ if conn:
+ db_release_func(conn)
+
+ # Priority: Environment Variable > Database Setting > Hardcoded Default
+ # Check Environment Variable first for OIDC enabled
+ oidc_enabled_from_env = os.environ.get('OIDC_ENABLED')
+ if oidc_enabled_from_env is not None:
+ # If the environment variable is set (even to 'false'), it takes highest priority
+ is_enabled = oidc_enabled_from_env.lower() == 'true'
+ else:
+ # If no environment variable, fall back to the database setting
+ oidc_enabled_from_db = oidc_db_settings.get('oidc_enabled', 'false') # Default to 'false' if not in DB
+ is_enabled = oidc_enabled_from_db.lower() == 'true'
+
+ current_app_instance.config['OIDC_ENABLED'] = is_enabled
+ logger.info(f"[FACTORY OIDC_INIT] OIDC enabled status: {is_enabled}")
+
+ if is_enabled:
+ # Apply same precedence logic to all OIDC settings
+ provider_name = os.environ.get('OIDC_PROVIDER_NAME', oidc_db_settings.get('oidc_provider_name', 'oidc'))
+ client_id = os.environ.get('OIDC_CLIENT_ID', oidc_db_settings.get('oidc_client_id', ''))
+ client_secret = os.environ.get('OIDC_CLIENT_SECRET', oidc_db_settings.get('oidc_client_secret', ''))
+ issuer_url = os.environ.get('OIDC_ISSUER_URL', oidc_db_settings.get('oidc_issuer_url', ''))
+ scope = os.environ.get('OIDC_SCOPE', oidc_db_settings.get('oidc_scope', 'openid email profile'))
+
+ current_app_instance.config['OIDC_PROVIDER_NAME'] = provider_name
+
+ if client_id and client_secret and issuer_url:
+ logger.info(f"[FACTORY OIDC_INIT] Registering OIDC client '{provider_name}' with Authlib.")
+ oauth.register(
+ name=provider_name,
+ client_id=client_id,
+ client_secret=client_secret,
+ server_metadata_url=f"{issuer_url.rstrip('/')}/.well-known/openid-configuration",
+ client_kwargs={'scope': scope},
+ override=True
+ )
+ logger.info(f"[FACTORY OIDC_INIT] OIDC client '{provider_name}' registered successfully.")
+ else:
+ logger.warning("[FACTORY OIDC_INIT] OIDC is enabled, but critical parameters are missing. OIDC login will be unavailable.")
+ current_app_instance.config['OIDC_ENABLED'] = False
+ else:
+ current_app_instance.config['OIDC_PROVIDER_NAME'] = None
+ logger.info("[FACTORY OIDC_INIT] OIDC is disabled.")
+
+def create_app(config_name=None):
+ """Create and configure an instance of the Flask application."""
+ # Configure logging FIRST
+ logging.basicConfig(level=logging.INFO)
+ logger.info("Starting application factory...")
+
+ # Determine configuration
+ if config_name is None:
+ config_name = os.environ.get('FLASK_CONFIG', 'default')
+
+ # Create Flask app instance
+ app = Flask(__name__)
+
+ # Apply ProxyFix middleware for reverse proxy support
+ app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
+
+ # Load configuration
+ try:
+ from .config import config
+ app.config.from_object(config[config_name])
+ config[config_name].init_app(app)
+ logger.info(f"Configuration '{config_name}' loaded successfully")
+ except ImportError:
+ try:
+ from config import config
+ app.config.from_object(config[config_name])
+ config[config_name].init_app(app)
+ logger.info(f"Configuration '{config_name}' loaded successfully")
+ except Exception as e:
+ logger.error(f"Failed to load configuration: {e}")
+ raise
+
+ # Initialize extensions
+ try:
+ from .extensions import initialize_extensions
+ initialize_extensions(app)
+ except ImportError:
+ from extensions import initialize_extensions
+ initialize_extensions(app)
+
+ # Register Blueprints within app context
+ with app.app_context():
+ try:
+ # Import blueprints
+ from .auth_routes import auth_bp
+ from .oidc_handler import oidc_bp
+ from .warranties_routes import warranties_bp
+ from .admin_routes import admin_bp
+ from .statistics_routes import statistics_bp
+ from .tags_routes import tags_bp
+ from .file_routes import file_bp
+ except ImportError:
+ # Fallback for development
+ from auth_routes import auth_bp
+ from oidc_handler import oidc_bp
+ from warranties_routes import warranties_bp
+ from admin_routes import admin_bp
+ from statistics_routes import statistics_bp
+ from tags_routes import tags_bp
+ from file_routes import file_bp
+
+ # Register blueprints
+ app.register_blueprint(auth_bp, url_prefix='/api/auth')
+ app.register_blueprint(oidc_bp, url_prefix='/api')
+ app.register_blueprint(warranties_bp, url_prefix='/api')
+ app.register_blueprint(admin_bp, url_prefix='/api/admin')
+ app.register_blueprint(statistics_bp, url_prefix='/api')
+ app.register_blueprint(tags_bp, url_prefix='/api')
+ app.register_blueprint(file_bp, url_prefix='/api')
+
+ logger.info("All blueprints registered successfully")
+
+ # Initialize OIDC client after extensions and blueprints
+ try:
+ from .db_handler import get_db_connection, release_db_connection
+ init_oidc_client(app, get_db_connection, release_db_connection)
+ except ImportError:
+ from db_handler import get_db_connection, release_db_connection
+ init_oidc_client(app, get_db_connection, release_db_connection)
+
+ # Ensure an owner exists on startup
+ ensure_owner_exists()
+
+ # Initialize the notification scheduler with the app context
+ try:
+ from .notifications import init_scheduler
+ from .db_handler import get_db_connection, release_db_connection
+
+ init_scheduler(app, get_db_connection, release_db_connection)
+ logger.info("✅ Notification scheduler initialized successfully in factory")
+ except ImportError:
+ try:
+ from notifications import init_scheduler
+ from db_handler import get_db_connection, release_db_connection
+
+ init_scheduler(app, get_db_connection, release_db_connection)
+ logger.info("✅ Notification scheduler initialized successfully in factory (dev mode)")
+ except Exception as e:
+ logger.error(f"❌ Failed to initialize notification scheduler: {e}")
+ # Continue without notifications - the app can still function
+ except Exception as e:
+ logger.error(f"❌ Failed to initialize notification scheduler: {e}")
+ # Continue without notifications - the app can still function
+
+ logger.info("Application factory completed successfully")
+
+ return app
diff --git a/backend/admin_routes.py b/backend/admin_routes.py
new file mode 100644
index 0000000..57260ea
--- /dev/null
+++ b/backend/admin_routes.py
@@ -0,0 +1,761 @@
+from flask import Blueprint, request, jsonify, current_app
+from datetime import datetime, date
+import os
+import logging
+
+# Use try-except pattern for imports to handle both Docker and development environments
+try:
+ from . import db_handler
+ from . import notifications
+ from .auth_utils import admin_required
+ from .apprise_handler import apprise_handler, APPRISE_AVAILABLE
+ from .db_handler import get_db_connection, release_db_connection
+except ImportError:
+ import db_handler
+ import notifications
+ from auth_utils import admin_required
+ from apprise_handler import apprise_handler, APPRISE_AVAILABLE
+ from db_handler import get_db_connection, release_db_connection
+
+# Create the admin blueprint
+admin_bp = Blueprint('admin_bp', __name__)
+
+# Set up logging
+logger = logging.getLogger(__name__)
+
+# Helper functions can be added here if needed
+
+# ============================
+# User Management Routes
+# ============================
+
+@admin_bp.route('/users', methods=['GET'])
+@admin_required
+def get_all_users():
+ """Get all users (admin only)"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Try to get users with is_owner column, fall back to without it if column doesn't exist
+ try:
+ cur.execute('''
+ SELECT id, username, email, first_name, last_name, is_active, is_admin, is_owner, created_at, last_login
+ FROM users
+ ORDER BY created_at DESC
+ ''')
+ users = cur.fetchall()
+ has_owner_column = True
+ except Exception as e:
+ # If the query fails (likely because is_owner column doesn't exist), rollback and try again
+ logger.warning(f"Failed to query with is_owner column in get_all_users, falling back: {e}")
+ conn.rollback() # Rollback the failed transaction
+ cur.execute('''
+ SELECT id, username, email, first_name, last_name, is_active, is_admin, created_at, last_login
+ FROM users
+ ORDER BY created_at DESC
+ ''')
+ users = cur.fetchall()
+ has_owner_column = False
+
+ columns = [desc[0] for desc in cur.description]
+ users_list = []
+
+ for row in users:
+ user_dict = dict(zip(columns, row))
+
+ # Add is_owner field if it wasn't included in the query
+ if not has_owner_column:
+ user_dict['is_owner'] = False
+
+ # Convert date objects to ISO format strings for JSON serialization
+ for key, value in user_dict.items():
+ if isinstance(value, (datetime, date)):
+ user_dict[key] = value.isoformat() if value else None
+
+ users_list.append(user_dict)
+
+ return jsonify(users_list), 200
+ except Exception as e:
+ logger.error(f"Error retrieving users: {e}")
+ return jsonify({"message": "Failed to retrieve users"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@admin_bp.route('/users/<int:user_id>', methods=['PUT'])
+@admin_required
+def update_user(user_id):
+ """Update user details (admin only)"""
+ conn = None
+ try:
+ # Prevent modifying self
+ if user_id == request.user['id']:
+ return jsonify({"message": "Cannot modify your own admin status"}), 403
+
+ data = request.get_json()
+
+ # Use regular connection since db_user now has superuser privileges
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if user exists and if they are the owner
+ try:
+ cur.execute('SELECT id, is_owner FROM users WHERE id = %s', (user_id,))
+ user = cur.fetchone()
+ is_owner = user[1] if user and len(user) > 1 else False
+ except Exception as e:
+ # If the query fails (likely because is_owner column doesn't exist), rollback and try again
+ logger.warning(f"Failed to query with is_owner column in update_user, falling back: {e}")
+ conn.rollback() # Rollback the failed transaction
+ cur.execute('SELECT id FROM users WHERE id = %s', (user_id,))
+ user = cur.fetchone()
+ is_owner = False
+
+ if not user:
+ return jsonify({"message": "User not found"}), 404
+
+ # Check if the user being updated is the owner
+ if is_owner:
+ # If the user is the owner, prevent demotion or deactivation
+ if 'is_admin' in data and data['is_admin'] is False:
+ return jsonify({"message": "The application owner cannot be demoted from admin status."}), 403
+ if 'is_active' in data and data['is_active'] is False:
+ return jsonify({"message": "The application owner's account cannot be deactivated."}), 403
+
+ # Update fields
+ updates = []
+ params = []
+
+ if 'is_admin' in data:
+ updates.append('is_admin = %s')
+ params.append(bool(data['is_admin']))
+
+ if 'is_active' in data:
+ updates.append('is_active = %s')
+ params.append(bool(data['is_active']))
+
+ if not updates:
+ return jsonify({"message": "No fields to update"}), 400
+
+ # Build and execute update query
+ query = f"UPDATE users SET {', '.join(updates)} WHERE id = %s"
+ params.append(user_id)
+
+ cur.execute(query, params)
+ conn.commit()
+
+ return jsonify({"message": "User updated successfully"}), 200
+ except Exception as e:
+ logger.error(f"Error updating user: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"message": f"Failed to update user: {str(e)}"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@admin_bp.route('/users/<int:user_id>', methods=['DELETE'])
+@admin_required
+def delete_user(user_id):
+ """Delete a user (admin only)"""
+ conn = None
+ try:
+ logger.info(f"Delete user request received for user_id: {user_id}")
+
+ # Prevent deleting self
+ if user_id == request.user['id']:
+ logger.warning(f"User {request.user['username']} attempted to delete their own account")
+ return jsonify({"message": "Cannot delete your own account through admin API"}), 403
+
+ # Use regular connection since db_user now has superuser privileges
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if user exists and if they are the owner
+ try:
+ cur.execute('SELECT id, username, is_owner FROM users WHERE id = %s', (user_id,))
+ user = cur.fetchone()
+ is_owner = user[2] if user and len(user) > 2 else False
+ except Exception as e:
+ # If the query fails (likely because is_owner column doesn't exist), rollback and try again
+ logger.warning(f"Failed to query with is_owner column in delete_user, falling back: {e}")
+ conn.rollback() # Rollback the failed transaction
+ cur.execute('SELECT id, username FROM users WHERE id = %s', (user_id,))
+ user = cur.fetchone()
+ is_owner = False
+
+ if not user:
+ logger.warning(f"User with ID {user_id} not found")
+ return jsonify({"message": "User not found"}), 404
+
+ # Check if the user to be deleted is the owner
+ if is_owner:
+ logger.warning(f"Admin {request.user['id']} attempted to delete the application owner (user_id: {user_id})")
+ return jsonify({"message": "The application owner cannot be deleted."}), 403
+
+ logger.info(f"Deleting user {user[1]} (ID: {user[0]})")
+
+ # Delete user's warranties first
+ cur.execute('DELETE FROM warranties WHERE user_id = %s', (user_id,))
+ warranties_deleted = cur.rowcount
+ logger.info(f"Deleted {warranties_deleted} warranties belonging to user {user_id}")
+
+ # Delete user's password reset tokens if any
+ cur.execute('DELETE FROM password_reset_tokens WHERE user_id = %s', (user_id,))
+ tokens_deleted = cur.rowcount
+ logger.info(f"Deleted {tokens_deleted} password reset tokens belonging to user {user_id}")
+
+ # Delete user's sessions if any
+ cur.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
+ sessions_deleted = cur.rowcount
+ logger.info(f"Deleted {sessions_deleted} sessions belonging to user {user_id}")
+
+ # Delete user's tags
+ cur.execute('DELETE FROM tags WHERE user_id = %s', (user_id,))
+ tags_deleted = cur.rowcount
+ logger.info(f"Deleted {tags_deleted} tags belonging to user {user_id}")
+
+ # Delete user
+ cur.execute('DELETE FROM users WHERE id = %s', (user_id,))
+ user_deleted = cur.rowcount
+ logger.info(f"Deleted user {user_id}, affected rows: {user_deleted}")
+
+ conn.commit()
+ logger.info(f"User {user_id} deleted successfully")
+
+ return jsonify({"message": "User deleted successfully"}), 200
+ except Exception as e:
+ logger.error(f"Error deleting user: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"message": f"Failed to delete user: {str(e)}"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@admin_bp.route('/transfer-ownership', methods=['POST'])
+@admin_required
+def transfer_ownership():
+ """Transfer application ownership to another admin user (owner only)"""
+ # 1. Security Check: Only the current owner can initiate a transfer.
+ # If is_owner column doesn't exist yet, this feature is not available
+ if not request.user.get('is_owner'):
+ return jsonify({"message": "Ownership transfer feature is not available. Please run the database migration first."}), 403
+
+ data = request.get_json()
+ new_owner_id = data.get('new_owner_id')
+ current_owner_id = request.user['id']
+
+ if not new_owner_id:
+ return jsonify({"message": "New owner ID is required."}), 400
+
+ if int(new_owner_id) == current_owner_id:
+ return jsonify({"message": "Cannot transfer ownership to yourself."}), 400
+
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # 2. Validate the new owner
+ cur.execute("SELECT id, is_admin, is_active FROM users WHERE id = %s", (new_owner_id,))
+ new_owner = cur.fetchone()
+
+ if not new_owner:
+ return jsonify({"message": "The selected user does not exist."}), 404
+
+ if not new_owner[1]: # is_admin is false
+ return jsonify({"message": "Ownership can only be transferred to another admin user."}), 400
+
+ if not new_owner[2]: # is_active is false
+ return jsonify({"message": "Cannot transfer ownership to an inactive user."}), 400
+
+ # 3. Perform the transfer within a database transaction
+ # This ensures both updates succeed or both fail.
+ logger.info(f"Ownership transfer initiated by user {current_owner_id} to user {new_owner_id}.")
+
+ # Demote current owner to a regular admin
+ try:
+ cur.execute("UPDATE users SET is_owner = FALSE WHERE id = %s", (current_owner_id,))
+
+ # Promote the new user to be the owner (and ensure they remain admin)
+ cur.execute("UPDATE users SET is_owner = TRUE, is_admin = TRUE WHERE id = %s", (new_owner_id,))
+ except Exception as e:
+ logger.error(f"Error updating ownership in database: {e}")
+ return jsonify({"message": "Ownership transfer feature is not available. Please run the database migration first."}), 500
+
+ conn.commit()
+
+ logger.info(f"Ownership successfully transferred from {current_owner_id} to {new_owner_id}.")
+ return jsonify({"message": "Ownership transferred successfully."}), 200
+
+ except Exception as e:
+ if conn:
+ conn.rollback()
+ logger.error(f"Error during ownership transfer: {e}")
+ return jsonify({"message": "An error occurred during ownership transfer. The operation has been rolled back."}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@admin_bp.route('/fix-owner-role', methods=['POST'])
+@admin_required
+def fix_owner_role():
+ """Temporary endpoint to manually fix owner role - can be removed after fix"""
+ try:
+ # Import ensure_owner_exists if available
+ try:
+ from .db_handler import ensure_owner_exists
+ except ImportError:
+ from db_handler import ensure_owner_exists
+
+ ensure_owner_exists()
+ return jsonify({'success': True, 'message': 'Owner role fix attempted. Check logs for results.'}), 200
+ except Exception as e:
+ logger.error(f"Error in fix_owner_role endpoint: {e}")
+ return jsonify({'success': False, 'message': f'Error: {str(e)}'}), 500
+
+# ============================
+# Site Settings Routes
+# ============================
+
+@admin_bp.route('/settings', methods=['GET'])
+@admin_required
+def get_site_settings():
+ """Get site settings (admin only)"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if settings table exists
+ cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'site_settings'
+ )
+ """)
+ table_exists = cur.fetchone()[0]
+
+ # Create settings table if it doesn't exist
+ if not table_exists:
+ cur.execute("""
+ CREATE TABLE site_settings (
+ key VARCHAR(255) PRIMARY KEY,
+ value TEXT,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )
+ """)
+ conn.commit()
+
+ # Get all settings
+ cur.execute('SELECT key, value FROM site_settings')
+ raw_settings = {row[0]: row[1] for row in cur.fetchall()}
+
+ # Define default values for all settings managed here
+ # OIDC Client Secret is write-only from admin UI, not directly exposed via GET
+ default_site_settings = {
+ 'registration_enabled': 'true',
+ 'email_base_url': os.environ.get('APP_BASE_URL', 'http://localhost:8080'), # Default to APP_BASE_URL
+ 'global_view_enabled': 'true', # Global warranty view feature
+ 'global_view_admin_only': 'false', # Restrict global view to admins only
+ 'oidc_enabled': 'false',
+ 'oidc_only_mode': 'false', # Force OIDC-only login (hide traditional login form)
+ 'oidc_provider_name': 'oidc',
+ 'oidc_client_id': '',
+ # 'oidc_client_secret': '', # Not returned
+ 'oidc_issuer_url': '',
+ 'oidc_scope': 'openid email profile',
+ # Apprise default settings
+ 'apprise_enabled': 'false',
+ 'apprise_urls': '',
+ 'apprise_expiration_days': '7,30',
+ 'apprise_notification_time': '09:00',
+ 'apprise_title_prefix': '[Warracker]',
+ # Paperless-ngx integration settings
+ 'paperless_enabled': 'false',
+ 'paperless_url': '',
+ # 'paperless_api_token': '', # Not returned directly
+ }
+
+ settings_to_return = {}
+ needs_commit = False
+
+ # First, add all existing settings from the database
+ for key, value in raw_settings.items():
+ # Skip returning sensitive secrets directly
+ if key in ['oidc_client_secret', 'paperless_api_token']:
+ continue
+
+ # For boolean-like string settings, ensure they are 'true' or 'false'
+ if key in ['registration_enabled', 'oidc_enabled', 'oidc_only_mode', 'apprise_enabled', 'global_view_enabled', 'global_view_admin_only', 'paperless_enabled']:
+ settings_to_return[key] = 'true' if value.lower() == 'true' else 'false'
+ else:
+ settings_to_return[key] = value
+
+ # Then, add defaults for any missing settings
+ for key, default_value in default_site_settings.items():
+ if key not in settings_to_return and key not in ['oidc_client_secret', 'paperless_api_token']:
+ settings_to_return[key] = default_value
+ # Insert default if missing (except for secrets)
+ cur.execute(
+ 'INSERT INTO site_settings (key, value) VALUES (%s, %s) ON CONFLICT (key) DO NOTHING',
+ (key, default_value)
+ )
+ needs_commit = True
+
+ # Indicate if secrets are set without revealing them
+ settings_to_return['oidc_client_secret_set'] = bool(raw_settings.get('oidc_client_secret'))
+ settings_to_return['paperless_api_token_set'] = bool(raw_settings.get('paperless_api_token'))
+
+ if needs_commit:
+ conn.commit()
+
+ return jsonify(settings_to_return), 200
+ except Exception as e:
+ logger.error(f"Error retrieving site settings: {e}")
+ return jsonify({"message": "Failed to retrieve site settings"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@admin_bp.route('/settings', methods=['PUT'])
+@admin_required
+def update_site_settings():
+ """Update site settings (admin only)"""
+ conn = None
+ try:
+ data = request.get_json()
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if settings table exists
+ cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'site_settings'
+ )
+ """)
+ table_exists = cur.fetchone()[0]
+
+ # Create settings table if it doesn't exist
+ if not table_exists:
+ cur.execute("""
+ CREATE TABLE site_settings (
+ key VARCHAR(255) PRIMARY KEY,
+ value TEXT,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )
+ """)
+
+ # Update settings
+ updated_keys = []
+ requires_restart = False
+ for key, value in data.items():
+ # Sanitize boolean-like string values
+ if key in ['registration_enabled', 'oidc_enabled', 'oidc_only_mode', 'global_view_enabled', 'global_view_admin_only', 'paperless_enabled']:
+ value = 'true' if str(value).lower() == 'true' else 'false'
+
+ # Check if it's an OIDC related key that requires restart
+ if key.startswith('oidc_'):
+ requires_restart = True
+
+ # For sensitive secrets, only update if a non-empty value is provided
+ # An empty string could mean "clear" or "no change" - admin UI should clarify
+ # For now, if key is a secret and value is empty, we skip update to avoid accidental clearing.
+ # The admin UI should send a specific placeholder if they intend to clear it, or not send the key.
+ if key in ['oidc_client_secret', 'paperless_api_token'] and not value: # If an empty secret is passed, don't update
+ logger.info(f"Skipping update for {key} as value is empty.")
+ continue
+
+
+ cur.execute("""
+ INSERT INTO site_settings (key, value, updated_at)
+ VALUES (%s, %s, CURRENT_TIMESTAMP)
+ ON CONFLICT (key)
+ DO UPDATE SET value = EXCLUDED.value, updated_at = CURRENT_TIMESTAMP
+ """, (key, str(value))) # Ensure value is string
+ updated_keys.append(key)
+
+ conn.commit()
+
+ response_message = "Settings updated successfully."
+ oidc_settings_changed = any(k.startswith('oidc_') for k in updated_keys)
+
+ if oidc_settings_changed:
+ logger.info("OIDC related settings changed, re-initializing OIDC client...")
+ try:
+ # Import init_oidc_client function
+ try:
+ from .oidc_handler import init_oidc_client
+ except ImportError:
+ from oidc_handler import init_oidc_client
+
+ with current_app.app_context(): # Ensure app context for init_oidc_client
+ init_oidc_client(current_app, get_db_connection, release_db_connection)
+ logger.info("OIDC client re-initialized successfully after settings update.")
+ response_message = "Settings updated successfully. OIDC configuration has been re-applied."
+ except Exception as oidc_reinit_err:
+ logger.error(f"Error re-initializing OIDC client after settings update: {oidc_reinit_err}")
+ response_message = "Settings updated, but OIDC re-configuration failed. A manual restart might be needed for OIDC changes to take effect."
+ elif requires_restart: # This case might be redundant if all oidc_ keys trigger the above
+ response_message += " An application restart is required for some settings to take full effect."
+
+ return jsonify({"message": response_message}), 200
+ except Exception as e:
+ logger.error(f"Error updating site settings: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"message": "Failed to update site settings"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+# ============================
+# Notification & Scheduler Routes
+# ============================
+
+@admin_bp.route('/send-notifications', methods=['POST'])
+@admin_required
+def trigger_notifications():
+ """
+ Admin-only endpoint to manually trigger warranty expiration notifications.
+ Useful for testing and for sending notifications outside the scheduled time.
+ """
+ try:
+ logger.info(f"Manual notification trigger requested by admin user {request.user['id']}")
+ result, status_code = notifications.trigger_notifications_manually(get_db_connection, release_db_connection)
+ return jsonify(result), status_code
+ except Exception as e:
+ error_msg = f"Error triggering notifications: {str(e)}"
+ logger.error(error_msg)
+ return jsonify({'message': 'Failed to trigger notifications', 'error': error_msg}), 500
+
+@admin_bp.route('/scheduler-status', methods=['GET'])
+@admin_required
+def get_scheduler_status():
+ """
+ Admin-only endpoint to check scheduler status and configuration.
+ """
+ try:
+ status = notifications.get_scheduler_status()
+ return jsonify(status), 200
+ except Exception as e:
+ logger.error(f"Error getting scheduler status: {e}")
+ return jsonify({'error': f'Failed to get scheduler status: {str(e)}'}), 500
+
+# ============================
+# Apprise Admin Routes
+# ============================
+
+@admin_bp.route('/apprise/test', methods=['POST'])
+@admin_required
+def test_apprise_notification():
+ """Send a test Apprise notification"""
+ if not APPRISE_AVAILABLE or apprise_handler is None:
+ return jsonify({'success': False, 'message': 'Apprise notifications are not available'}), 503
+
+ try:
+ data = request.get_json()
+ test_url = data.get('test_url') if data else None
+
+ success = apprise_handler.send_test_notification(test_url)
+
+ if success:
+ return jsonify({'success': True, 'message': 'Test notification sent successfully'}), 200
+ else:
+ return jsonify({'success': False, 'message': 'Failed to send test notification'}), 400
+
+ except Exception as e:
+ logger.error(f"Error sending test Apprise notification: {e}")
+ return jsonify({'success': False, 'message': f'Error: {str(e)}'}), 500
+
+@admin_bp.route('/apprise/validate-url', methods=['POST'])
+@admin_required
+def validate_apprise_url():
+ """Validate an Apprise notification URL"""
+ if not APPRISE_AVAILABLE or apprise_handler is None:
+ return jsonify({'valid': False, 'message': 'Apprise notifications are not available'}), 503
+
+ try:
+ data = request.get_json()
+ url = data.get('url')
+
+ if not url:
+ return jsonify({'valid': False, 'message': 'URL is required'}), 400
+
+ is_valid = apprise_handler.validate_url(url)
+
+ return jsonify({
+ 'valid': is_valid,
+ 'message': 'URL is valid' if is_valid else 'URL is invalid or unsupported'
+ }), 200
+
+ except Exception as e:
+ logger.error(f"Error validating Apprise URL: {e}")
+ return jsonify({'valid': False, 'message': f'Error: {str(e)}'}), 500
+
+@admin_bp.route('/apprise/supported-services', methods=['GET'])
+@admin_required
+def get_supported_apprise_services():
+ """Get list of supported Apprise services"""
+ if not APPRISE_AVAILABLE or apprise_handler is None:
+ return jsonify({'services': [], 'message': 'Apprise notifications are not available'}), 503
+
+ try:
+ services = apprise_handler.get_supported_services()
+ return jsonify({'services': services}), 200
+
+ except Exception as e:
+ logger.error(f"Error getting supported Apprise services: {e}")
+ return jsonify({'services': [], 'message': f'Error: {str(e)}'}), 500
+
+@admin_bp.route('/apprise/send-expiration', methods=['POST'])
+@admin_required
+def trigger_apprise_expiration_notifications():
+ """Manually trigger Apprise expiration notifications with warranty scope filtering"""
+ if not APPRISE_AVAILABLE or apprise_handler is None:
+ return jsonify({'success': False, 'message': 'Apprise notifications are not available'}), 503
+
+ try:
+ # Get warranty scope setting to determine which warranties to include
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ cur.execute("SELECT value FROM site_settings WHERE key = 'apprise_warranty_scope'")
+ result = cur.fetchone()
+ warranty_scope = result[0] if result else 'all'
+ except Exception as e:
+ logger.error(f"Error fetching warranty scope setting: {e}")
+ warranty_scope = 'all' # Default fallback
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+ # Get eligible user IDs based on warranty scope
+ eligible_user_ids = None # None means all users
+
+ if warranty_scope == 'admin':
+ # Get admin user ID (first check if there's an owner, otherwise find first admin)
+ admin_user_id = None
+ conn_scope = None
+ try:
+ conn_scope = get_db_connection()
+ with conn_scope.cursor() as cur:
+ # First try to find the owner
+ cur.execute("SELECT id FROM users WHERE is_owner = TRUE LIMIT 1")
+ owner_result = cur.fetchone()
+ if owner_result:
+ admin_user_id = owner_result[0]
+ else:
+ # Fallback to first admin if no owner found
+ cur.execute("SELECT id FROM users WHERE is_admin = TRUE ORDER BY id LIMIT 1")
+ admin_result = cur.fetchone()
+ if admin_result:
+ admin_user_id = admin_result[0]
+ except Exception as e:
+ logger.error(f"Error finding admin user ID for warranty scope filtering: {e}")
+ finally:
+ if conn_scope:
+ release_db_connection(conn_scope)
+
+ if admin_user_id:
+ eligible_user_ids = [admin_user_id]
+ logger.info(f"Warranty scope 'admin': Limiting notifications to admin user ID {admin_user_id}")
+ else:
+ logger.warning("Warranty scope 'admin' requested but no admin user found, including all users")
+
+ logger.info(f"Triggering Apprise notifications with warranty scope: '{warranty_scope}', eligible users: {eligible_user_ids}")
+
+ # Send notifications with user filtering
+ results = apprise_handler.send_expiration_notifications(eligible_user_ids=eligible_user_ids)
+
+ return jsonify({
+ 'success': True,
+ 'message': f'Notifications processed: {results["sent"]} sent, {results["errors"]} errors',
+ 'results': results,
+ 'warranty_scope': warranty_scope
+ }), 200
+
+ except Exception as e:
+ logger.error(f"Error triggering Apprise expiration notifications: {e}")
+ return jsonify({'success': False, 'message': f'Error: {str(e)}'}), 500
+
+@admin_bp.route('/apprise/reload-config', methods=['POST'])
+@admin_required
+def reload_apprise_configuration():
+ """Reload Apprise configuration from database and environment"""
+ if not APPRISE_AVAILABLE or apprise_handler is None:
+ return jsonify({'success': False, 'message': 'Apprise notifications are not available'}), 503
+
+ try:
+ apprise_handler.reload_configuration()
+
+ return jsonify({
+ 'success': True,
+ 'message': 'Apprise configuration reloaded successfully',
+ 'enabled': apprise_handler.enabled,
+ 'urls_configured': len(apprise_handler.notification_urls)
+ }), 200
+
+ except Exception as e:
+ logger.error(f"Error reloading Apprise configuration: {e}")
+ return jsonify({'success': False, 'message': f'Error: {str(e)}'}), 500
+
+@admin_bp.route('/apprise/send-custom', methods=['POST'])
+@admin_required
+def send_custom_apprise_notification():
+ """Send a custom Apprise notification"""
+ if not APPRISE_AVAILABLE or apprise_handler is None:
+ return jsonify({'success': False, 'message': 'Apprise notifications are not available'}), 503
+
+ try:
+ data = request.get_json()
+ title = data.get('title')
+ message = data.get('message')
+ urls = data.get('urls') # Optional: specific URLs to send to
+
+ if not title or not message:
+ return jsonify({'success': False, 'message': 'Title and message are required'}), 400
+
+ success = apprise_handler.send_custom_notification(title, message, urls)
+
+ if success:
+ return jsonify({'success': True, 'message': 'Custom notification sent successfully'}), 200
+ else:
+ return jsonify({'success': False, 'message': 'Failed to send custom notification'}), 400
+
+ except Exception as e:
+ logger.error(f"Error sending custom Apprise notification: {e}")
+ return jsonify({'success': False, 'message': f'Error: {str(e)}'}), 500
+
+@admin_bp.route('/apprise/status', methods=['GET'])
+@admin_required
+def get_apprise_status():
+ """Get current Apprise configuration status"""
+ if not APPRISE_AVAILABLE or apprise_handler is None:
+ return jsonify({
+ 'available': False,
+ 'enabled': False,
+ 'message': 'Apprise library is not installed or not available'
+ }), 503
+
+ try:
+ # Get detailed status from the handler
+ status = apprise_handler.get_status()
+
+ # Add additional fields for backward compatibility
+ status.update({
+ 'expiration_days': apprise_handler.expiration_days,
+ 'notification_time': apprise_handler.notification_time,
+ 'title_prefix': apprise_handler.title_prefix,
+ 'message': 'Apprise is available and configured' if status.get('available') else status.get('error', 'Unknown error')
+ })
+
+ return jsonify(status), 200
+
+ except Exception as e:
+ logger.error(f"Error getting Apprise status: {e}")
+ return jsonify({
+ 'available': False,
+ 'enabled': False,
+ 'message': f'Error: {str(e)}'
+ }), 500
\ No newline at end of file
diff --git a/backend/app.py b/backend/app.py
index 72fb617..d2ab702 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -1,4073 +1,64 @@
-from flask import Flask, request, jsonify, send_from_directory, session, redirect, url_for
-import psycopg2
-from psycopg2 import pool
+# backend/app.py
+# Updated: 2025-01-24 - Fixed scheduler detection for ultra-light mode
+"""
+Warracker Flask Application Entry Point
+
+This file creates the Flask application using the Application Factory pattern.
+The actual application configuration and initialization is handled by the factory.
+"""
import os
-from datetime import datetime, timedelta, date
-from werkzeug.utils import secure_filename
-from flask_cors import CORS
import logging
-import time
-from decimal import Decimal
-import jwt
-from flask_bcrypt import Bcrypt
-import re
-from functools import wraps
-import uuid
-import smtplib
-from email.mime.multipart import MIMEMultipart
-from email.mime.text import MIMEText
-from apscheduler.schedulers.background import BackgroundScheduler
-import atexit
-from pytz import timezone as pytz_timezone
-import pytz
-import threading
-import json
-import csv # Added for CSV import
-import io # Added for CSV import
-from dateutil.relativedelta import relativedelta
-
-app = Flask(__name__)
-CORS(app, supports_credentials=True) # Enable CORS with credentials
-bcrypt = Bcrypt(app)
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
-# Set a secret key for session and JWT
-app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'dev_secret_key_change_in_production')
-app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=7) # Token expiration time
-
-# Email change token settings
-EMAIL_CHANGE_TOKEN_EXPIRATION_HOURS = 24 # Token valid for 24 hours
-EMAIL_CHANGE_VERIFICATION_ENDPOINT = '/verify-email-change.html' # Frontend page for verification
-
-UPLOAD_FOLDER = '/data/uploads'
-ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg', 'zip', 'rar'}
-
-# Default max upload size in MB
-DEFAULT_MAX_UPLOAD_MB = 32
+# Create the app instance using the factory
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
-
-# PostgreSQL connection pool
-DB_HOST = os.environ.get('DB_HOST', 'warrackerdb')
-DB_NAME = os.environ.get('DB_NAME', 'warranty_db')
-DB_USER = os.environ.get('DB_USER', 'warranty_user')
-DB_PASSWORD = os.environ.get('DB_PASSWORD', 'warranty_password')
-DB_ADMIN_USER = os.environ.get('DB_ADMIN_USER', 'warracker_admin')
-DB_ADMIN_PASSWORD = os.environ.get('DB_ADMIN_PASSWORD', 'change_this_password_in_production')
-
-# Add connection retry logic
-def create_db_pool(max_retries=5, retry_delay=5):
- attempt = 0
- last_exception = None
-
- while attempt < max_retries:
- try:
- logger.info(f"Attempting to connect to database (attempt {attempt+1}/{max_retries})")
- connection_pool = pool.SimpleConnectionPool(
- 1, 10, # min, max connections
- host=DB_HOST,
- database=DB_NAME,
- user=DB_USER,
- password=DB_PASSWORD
- )
- logger.info("Database connection successful")
- return connection_pool
- except Exception as e:
- last_exception = e
- logger.error(f"Database connection error: {e}")
- logger.info(f"Retrying in {retry_delay} seconds...")
- time.sleep(retry_delay)
- attempt += 1
-
- # If we got here, all connection attempts failed
- logger.error(f"Failed to connect to database after {max_retries} attempts")
- raise last_exception
-
-# Create a connection pool with retry logic
-try:
- connection_pool = create_db_pool()
-except Exception as e:
- logger.error(f"Fatal database connection error: {e}")
- # Allow the app to start even if DB connection fails
- # This lets us serve static files while DB is unavailable
- connection_pool = None
-
-def get_db_connection():
- try:
- if connection_pool is None:
- raise Exception("Database connection pool not initialized")
- return connection_pool.getconn()
- except Exception as e:
- logger.error(f"Database connection error: {e}")
- raise
-
-def get_admin_db_connection():
- """Get a database connection with admin privileges for user management"""
- try:
- # Connect using the admin role for administrative tasks
- conn = psycopg2.connect(
- host=DB_HOST,
- database=DB_NAME,
- user=DB_ADMIN_USER,
- password=DB_ADMIN_PASSWORD
- )
- return conn
- except Exception as e:
- logger.error(f"Admin database connection error: {e}")
- raise
-
-def release_db_connection(conn):
- connection_pool.putconn(conn)
-
-def allowed_file(filename):
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
-
-# Initialize database
-def init_db():
- """Initialize the database with required tables"""
- try:
- conn = get_db_connection()
- cur = conn.cursor()
-
- # Create users table if it doesn't exist - Handled by migrations
- # cur.execute("""
- # CREATE TABLE IF NOT EXISTS users (
- # id SERIAL PRIMARY KEY,
- # username VARCHAR(50) UNIQUE NOT NULL,
- # email VARCHAR(100) UNIQUE NOT NULL,
- # password_hash VARCHAR(255) NOT NULL,
- # first_name VARCHAR(50),
- # last_name VARCHAR(50),
- # is_active BOOLEAN DEFAULT TRUE,
- # is_admin BOOLEAN DEFAULT FALSE,
- # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- # updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- # )
- # """)
-
- # Create user_preferences table if it doesn't exist - Handled by migrations
- # cur.execute("""
- # CREATE TABLE IF NOT EXISTS user_preferences (
- # id SERIAL PRIMARY KEY,
- # user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- # email_notifications BOOLEAN NOT NULL DEFAULT TRUE,
- # default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
- # theme VARCHAR(10) NOT NULL DEFAULT 'light',
- # expiring_soon_days INTEGER NOT NULL DEFAULT 30,
- # notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily',
- # notification_time VARCHAR(5) NOT NULL DEFAULT '09:00',
- # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- # updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- # UNIQUE(user_id)
- # )
- # """)
-
- # Check if timezone column exists and add if it doesn't - Handled by migrations (e.g., 008_add_timezone_column.sql)
- # cur.execute("""
- # DO $$
- # BEGIN
- # IF NOT EXISTS (
- # SELECT column_name
- # FROM information_schema.columns
- # WHERE table_name = 'user_preferences' AND column_name = 'timezone'
- # ) THEN
- # ALTER TABLE user_preferences
- # ADD COLUMN timezone VARCHAR(50) NOT NULL DEFAULT 'UTC';
- # RAISE NOTICE 'Added timezone column to user_preferences table';
- # END IF;
- # END $$;
- # """)
-
- # Create warranties table if it doesn't exist - Handled by migrations
- # cur.execute("""
- # CREATE TABLE IF NOT EXISTS warranties (
- # id SERIAL PRIMARY KEY,
- # user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- # item_name VARCHAR(100) NOT NULL,
- # purchase_date DATE NOT NULL,
- # expiration_date DATE NOT NULL,
- # purchase_price DECIMAL(10,2),
- # serial_number VARCHAR(100),
- # category VARCHAR(50),
- # notes TEXT,
- # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- # updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- # )
- # """)
-
- # Create warranty_documents table if it doesn't exist - Handled by migrations
- # cur.execute("""
- # CREATE TABLE IF NOT EXISTS warranty_documents (
- # id INTEGER PRIMARY KEY,
- # warranty_id INTEGER NOT NULL REFERENCES warranties(id) ON DELETE CASCADE,
- # file_name VARCHAR(255) NOT NULL,
- # file_path VARCHAR(255) NOT NULL,
- # file_type VARCHAR(50),
- # file_size INTEGER,
- # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- # )
- # """)
-
- # Create sequence if it doesn't exist - Handled by migrations
- # cur.execute("""
- # DO $$
- # BEGIN
- # IF NOT EXISTS (SELECT 1 FROM pg_sequences WHERE sequencename = 'warranty_documents_id_seq') THEN
- # CREATE SEQUENCE warranty_documents_id_seq;
- # END IF;
- # END $$;
- # """)
-
- # Alter table to use the sequence - Handled by migrations
- # cur.execute("""
- # ALTER TABLE warranty_documents
- # ALTER COLUMN id SET DEFAULT nextval('warranty_documents_id_seq');
- # """)
-
- # We might still need to commit if other operations were performed before the commented blocks
- conn.commit()
- cur.close()
- conn.close()
- logger.info("Database initialized successfully")
-
- except Exception as e:
- logger.error(f"Database initialization error: {str(e)}")
- raise
-
-# Authentication helper functions
-def generate_token(user_id):
- """Generate a JWT token for the user"""
- payload = {
- 'exp': datetime.utcnow() + app.config['JWT_EXPIRATION_DELTA'],
- 'iat': datetime.utcnow(),
- 'sub': user_id
- }
- return jwt.encode(payload, app.config['SECRET_KEY'], algorithm='HS256')
-
-def decode_token(token):
- """Decode a JWT token and return the user_id"""
- try:
- payload = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
- return payload['sub']
- except jwt.ExpiredSignatureError:
- return None # Token has expired
- except jwt.InvalidTokenError:
- return None # Invalid token
-
-def token_required(f):
- """Decorator to protect routes that require authentication"""
- @wraps(f)
- def decorated(*args, **kwargs):
- token = None
-
- # Get token from Authorization header
- auth_header = request.headers.get('Authorization')
- if auth_header and auth_header.startswith('Bearer '):
- token = auth_header.split(' ')[1]
-
- # If no token in header, check form data for POST requests
- if not token and request.method == 'POST':
- token = request.form.get('auth_token') # Check form data
-
- # If still no token, check URL query parameters
- if not token:
- token = request.args.get('token') # Check query parameters
-
- # If no token is provided
- if not token:
- logger.warning(f"Authentication attempt without token: {request.path}")
- return jsonify({'message': 'Authentication token is missing!'}), 401
-
- # Decode the token
- user_id = decode_token(token)
- if not user_id:
- logger.warning(f"Invalid token used for: {request.path}")
- return jsonify({'message': 'Invalid or expired token!'}), 401
-
- # Check if user exists
- conn = None
- try:
- conn = get_db_connection()
- with conn.cursor() as cur:
- cur.execute('SELECT id, username, email, is_admin FROM users WHERE id = %s AND is_active = TRUE', (user_id,))
- user = cur.fetchone()
-
- if not user:
- return jsonify({'message': 'User not found or inactive!'}), 401
-
- # Add user info to request context
- request.user = {
- 'id': user[0],
- 'username': user[1],
- 'email': user[2],
- 'is_admin': user[3]
- }
-
- return f(*args, **kwargs)
- except Exception as e:
- logger.error(f"Authentication error: {e}")
- return jsonify({'message': 'Authentication error!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
+ from . import create_app
+ from . import db_handler
- return decorated
-
-def admin_required(f):
- """Decorator to protect routes that require admin privileges"""
- @wraps(f)
- def decorated(*args, **kwargs):
- logger.info("Admin required check started")
- token_required_result = token_required(lambda: None)()
-
- if isinstance(token_required_result, tuple) and token_required_result[1] != 200:
- logger.error(f"Token validation failed: {token_required_result}")
- return token_required_result
-
- logger.info(f"User info: {request.user}")
- if not request.user.get('is_admin', False):
- logger.error(f"User {request.user.get('username')} is not an admin")
- return jsonify({'message': 'Admin privileges required!'}), 403
-
- logger.info(f"Admin check passed for user {request.user.get('username')}")
- return f(*args, **kwargs)
+ app = create_app(os.getenv('FLASK_CONFIG') or 'default')
+ logger.info("Application created successfully using factory pattern")
- return decorated
-
-def is_valid_email(email):
- """Validate email format"""
- pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
- return re.match(pattern, email) is not None
-
-def is_valid_password(password):
- """Validate password strength"""
- # At least 8 characters, 1 uppercase, 1 lowercase, 1 number
- if len(password) < 8:
- return False
- if not re.search(r'[A-Z]', password):
- return False
- if not re.search(r'[a-z]', password):
- return False
- if not re.search(r'[0-9]', password):
- return False
- return True
-
-def is_valid_timezone(tz):
- """Validate if a timezone string is valid"""
- try:
- pytz.timezone(tz)
- return True
- except pytz.exceptions.UnknownTimeZoneError:
- return False
-
-def convert_decimals(obj):
- """Recursively convert Decimal objects to float in dicts/lists for JSON serialization."""
- if isinstance(obj, dict):
- return {k: convert_decimals(v) for k, v in obj.items()}
- elif isinstance(obj, list):
- return [convert_decimals(i) for i in obj]
- elif isinstance(obj, Decimal):
- return float(obj)
- else:
- return obj
-
-# Authentication routes
[email protected]('/api/auth/register', methods=['POST'])
-def register():
- conn = None
- try:
- data = request.get_json()
-
- # Check if registration is enabled
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if settings table exists
- cur.execute("""
- SELECT EXISTS (
- SELECT FROM information_schema.tables
- WHERE table_name = 'site_settings'
- )
- """)
- table_exists = cur.fetchone()[0]
-
- registration_enabled = True
- if table_exists:
- # Get registration_enabled setting
- cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")
- result = cur.fetchone()
-
- if result:
- registration_enabled = result[0].lower() == 'true'
-
- # Check if there are any users (first user can register regardless of setting)
- cur.execute('SELECT COUNT(*) FROM users')
- user_count = cur.fetchone()[0]
-
- # If registration is disabled and this is not the first user, return error
- if not registration_enabled and user_count > 0:
- return jsonify({'message': 'Registration is currently disabled!'}), 403
-
- # Validate required fields
- required_fields = ['username', 'email', 'password']
- for field in required_fields:
- if field not in data or not data[field]:
- return jsonify({'message': f'{field} is required!'}), 400
-
- username = data['username']
- email = data['email']
- password = data['password']
- first_name = data.get('first_name', '')
- last_name = data.get('last_name', '')
-
- # Validate email format
- if not is_valid_email(email):
- return jsonify({'message': 'Invalid email format!'}), 400
-
- # Validate password strength
- if not is_valid_password(password):
- return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
-
- # Hash the password
- password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
-
- with conn.cursor() as cur:
- # Check if username or email already exists
- cur.execute('SELECT id FROM users WHERE username = %s OR email = %s', (username, email))
- existing_user = cur.fetchone()
-
- if existing_user:
- return jsonify({'message': 'Username or email already exists!'}), 409
-
- # Check if this is the first user (who will be an admin)
- cur.execute('SELECT COUNT(*) FROM users')
- user_count = cur.fetchone()[0]
- is_admin = user_count == 0
-
- # Insert new user
- cur.execute(
- 'INSERT INTO users (username, email, password_hash, first_name, last_name, is_admin) VALUES (%s, %s, %s, %s, %s, %s) RETURNING id',
- (username, email, password_hash, first_name, last_name, is_admin)
- )
- user_id = cur.fetchone()[0]
-
- # Generate token
- token = generate_token(user_id)
-
- # Update last login
- cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
-
- # Store session info
- ip_address = request.remote_addr
- user_agent = request.headers.get('User-Agent', '')
- session_token = str(uuid.uuid4())
- expires_at = datetime.utcnow() + app.config['JWT_EXPIRATION_DELTA']
-
- cur.execute(
- 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent) VALUES (%s, %s, %s, %s, %s)',
- (user_id, session_token, expires_at, ip_address, user_agent)
- )
-
- conn.commit()
-
- return jsonify({
- 'message': 'User registered successfully!',
- 'token': token,
- 'user': {
- 'id': user_id,
- 'username': username,
- 'email': email,
- 'is_admin': is_admin
- }
- }), 201
- except Exception as e:
- logger.error(f"Registration error: {e}")
- if conn:
- conn.rollback()
- return jsonify({'message': 'Registration failed!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/auth/login', methods=['POST'])
-def login():
- conn = None
- try:
- data = request.get_json()
-
- # Validate required fields
- if not data.get('username') or not data.get('password'):
- return jsonify({'message': 'Username and password are required!'}), 400
-
- username = data['username']
- password = data['password']
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if user exists
- cur.execute('SELECT id, username, email, password_hash, is_active FROM users WHERE username = %s OR email = %s', (username, username))
- user = cur.fetchone()
-
- if not user or not bcrypt.check_password_hash(user[3], password):
- return jsonify({'message': 'Invalid username or password!'}), 401
-
- if not user[4]: # is_active
- return jsonify({'message': 'Account is inactive!'}), 401
-
- user_id = user[0]
-
- # Generate token
- token = generate_token(user_id)
-
- # Update last login
- cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
-
- # Store session info
- ip_address = request.remote_addr
- user_agent = request.headers.get('User-Agent', '')
- session_token = str(uuid.uuid4())
- expires_at = datetime.utcnow() + app.config['JWT_EXPIRATION_DELTA']
-
- cur.execute(
- 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent) VALUES (%s, %s, %s, %s, %s)',
- (user_id, session_token, expires_at, ip_address, user_agent)
- )
-
- conn.commit()
-
- return jsonify({
- 'message': 'Login successful!',
- 'token': token,
- 'user': {
- 'id': user_id,
- 'username': user[1],
- 'email': user[2]
- }
- }), 200
- except Exception as e:
- logger.error(f"Login error: {e}")
- if conn:
- conn.rollback()
- return jsonify({'message': 'Login failed!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/auth/logout', methods=['POST'])
-@token_required
-def logout():
- conn = None
- try:
- auth_header = request.headers.get('Authorization')
- if auth_header and auth_header.startswith('Bearer '):
- token = auth_header.split(' ')[1]
- else:
- return jsonify({'message': 'No token provided!'}), 400
-
- user_id = request.user['id']
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Invalidate all sessions for this user
- cur.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
- conn.commit()
-
- return jsonify({'message': 'Logout successful!'}), 200
- except Exception as e:
- logger.error(f"Logout error: {e}")
- if conn:
- conn.rollback()
- return jsonify({'message': 'Logout failed!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/auth/validate-token', methods=['GET'])
-@token_required
-def validate_token():
- """Validate JWT token and return user info"""
- try:
- # If we got here, the token is valid (token_required decorator validated it)
- return jsonify({
- 'valid': True,
- 'user': {
- 'id': request.user['id'],
- 'username': request.user['username'],
- 'email': request.user['email'],
- 'is_admin': request.user['is_admin']
- },
- 'message': 'Token is valid'
- }), 200
- except Exception as e:
- logger.error(f"Token validation error: {e}")
- return jsonify({
- 'valid': False,
- 'message': 'Invalid token'
- }), 401
-
[email protected]('/api/auth/user', methods=['GET'])
-@token_required
-def get_user():
- conn = None
- try:
- user_id = request.user['id'] # Get user ID from the decorator
-
- # --- ADD DATABASE QUERY ---
- conn = get_db_connection()
- with conn.cursor() as cur:
- cur.execute(
- 'SELECT id, username, email, first_name, last_name, is_admin FROM users WHERE id = %s',
- (user_id,)
- )
- user_data = cur.fetchone()
- # --- END DATABASE QUERY ---
-
- if not user_data:
- return jsonify({'message': 'User not found!'}), 404
-
- # Map database columns to a dictionary
- columns = ['id', 'username', 'email', 'first_name', 'last_name', 'is_admin']
- user_info = dict(zip(columns, user_data))
-
- # Return the full user information
- return jsonify(user_info), 200
-
- except Exception as e:
- logger.error(f"Get user error: {e}")
- # Optionally rollback if there was an error during DB interaction
- # if conn:
- # conn.rollback() # Not strictly needed for SELECT, but good practice if errors occur
- return jsonify({'message': 'Failed to retrieve user information!'}), 500
- finally:
- # Release the connection back to the pool
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/auth/password/reset-request', methods=['POST'])
-def request_password_reset():
- conn = None
- try:
- data = request.get_json()
-
- if not data.get('email'):
- return jsonify({'message': 'Email is required!'}), 400
-
- email = data['email']
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if user exists
- cur.execute('SELECT id FROM users WHERE email = %s', (email,))
- user = cur.fetchone()
-
- if not user:
- # Don't reveal if email exists or not for security
- return jsonify({'message': 'If your email is registered, you will receive a password reset link.'}), 200
-
- user_id = user[0]
-
- # Generate reset token
- reset_token = str(uuid.uuid4())
- expires_at = datetime.utcnow() + timedelta(hours=24)
-
- # Delete any existing tokens for this user
- cur.execute('DELETE FROM password_reset_tokens WHERE user_id = %s', (user_id,))
-
- # Insert new token
- cur.execute(
- 'INSERT INTO password_reset_tokens (user_id, token, expires_at) VALUES (%s, %s, %s)',
- (user_id, reset_token, expires_at)
- )
-
- conn.commit()
-
- # Get email base URL from settings
- email_base_url = 'http://localhost:8080' # Default fallback
- try:
- cur.execute("SELECT value FROM site_settings WHERE key = 'email_base_url'")
- result = cur.fetchone()
- if result:
- email_base_url = result[0]
- else:
- logger.warning("email_base_url setting not found for password reset, using default.")
- except Exception as e:
- logger.error(f"Error fetching email_base_url from settings for password reset: {e}. Using default.")
-
- # Ensure base URL doesn't end with a slash
- email_base_url = email_base_url.rstrip('/')
-
- # Construct the full reset link
- reset_link = f"{email_base_url}/reset-password.html?token={reset_token}" # Use base URL and correct page
-
- # Send password reset email
- logger.info(f"Password reset requested for user {user_id}. Preparing to send email.")
- try:
- send_password_reset_email(email, reset_link)
- logger.info(f"Password reset email initiated for {email}")
- except Exception as e:
- logger.error(f"Failed to send password reset email to {email}: {e}")
- # Even if email fails, don't tell the user.
- # This prevents leaking information about registered emails or email server issues.
- # The user journey remains the same: "If registered, you'll get an email."
-
- # Always return success to the user, regardless of email success/failure
- return jsonify({
- 'message': 'If your email is registered, you will receive a password reset link.'
- }), 200
-
- except Exception as e:
- logger.error(f"Password reset request error: {e}")
- if conn:
- conn.rollback()
- return jsonify({'message': 'Password reset request failed!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
-# Note: The actual reset_password function is defined earlier in the file.
-# The duplicated block that caused the error has been removed.
-
-
-# Update existing endpoints to use authentication
-
[email protected]('/api/warranties', methods=['GET'])
-@token_required
-def get_warranties():
- conn = None
- try:
- user_id = request.user['id']
- # is_admin = request.user.get('is_admin', False) # Removed admin check
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Always fetch warranties belonging to the logged-in user
- # Removed the if is_admin: block
- # 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]
- warranties_list = []
-
- for row in warranties:
- warranty_dict = dict(zip(columns, row))
- # Convert date objects to ISO format strings for JSON serialization
- for key, value in warranty_dict.items():
- if isinstance(value, (datetime, date)):
- warranty_dict[key] = value.isoformat()
- # Convert Decimal objects to float for JSON serialization
- elif isinstance(value, Decimal):
- warranty_dict[key] = float(value)
-
- # Get serial numbers for this warranty
- warranty_id = warranty_dict['id']
- cur.execute('SELECT serial_number FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))
- serial_numbers = [row[0] for row in cur.fetchall()]
- warranty_dict['serial_numbers'] = serial_numbers
-
- # Get tags for this warranty (show all associated tags the user can see via warranty access)
- cur.execute('''
- SELECT t.id, t.name, t.color
- FROM tags t
- JOIN warranty_tags wt ON t.id = wt.tag_id
- WHERE wt.warranty_id = %s -- Removed user_id/is_admin filter here
- ORDER BY t.name
- ''', (warranty_id,))
- tags = [{'id': t[0], 'name': t[1], 'color': t[2]} for t in cur.fetchall()]
- warranty_dict['tags'] = tags
-
- warranties_list.append(warranty_dict)
-
- return jsonify(warranties_list)
- except Exception as e:
- logger.error(f"Error retrieving warranties: {e}")
- return jsonify({"error": "Failed to retrieve warranties"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/warranties', methods=['POST'])
-@token_required
-def add_warranty():
- conn = None
- try:
- # Validate input data
- if not request.form.get('product_name'):
- return jsonify({"error": "Product name is required"}), 400
-
- if not request.form.get('purchase_date'):
- return jsonify({"error": "Purchase date is required"}), 400
-
- # Handle lifetime warranty
- is_lifetime = request.form.get('is_lifetime', 'false').lower() == 'true'
- expiration_date = None
- warranty_duration_years = 0
- warranty_duration_months = 0
- warranty_duration_days = 0
-
- if not is_lifetime:
- try:
- # 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 duration components must be valid numbers."}), 400
-
- # Process the data
- product_name = request.form['product_name']
- purchase_date_str = request.form['purchase_date']
- serial_numbers = request.form.getlist('serial_numbers[]')
- product_url = request.form.get('product_url', '')
- user_id = request.user['id']
- notes = request.form.get('notes', '')
- vendor = request.form.get('vendor', None)
-
- # Get tag IDs if provided
- tag_ids = []
- if request.form.get('tag_ids'):
- try:
- tag_ids = json.loads(request.form.get('tag_ids'))
- if not isinstance(tag_ids, list):
- return jsonify({"error": "tag_ids must be a JSON array"}), 400
- except json.JSONDecodeError:
- return jsonify({"error": "tag_ids must be a valid JSON array"}), 400
-
- # Handle purchase price (optional)
- purchase_price = None
- if request.form.get('purchase_price'):
- try:
- purchase_price = float(request.form.get('purchase_price'))
- if purchase_price < 0:
- return jsonify({"error": "Purchase price cannot be negative"}), 400
- except ValueError:
- return jsonify({"error": "Purchase price must be a valid number"}), 400
-
- try:
- purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d').date()
- except ValueError:
- return jsonify({"error": "Invalid date format. Use YYYY-MM-DD"}), 400
-
- # Calculate expiration date only if not lifetime
- 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
- if 'invoice' in request.files:
- invoice = request.files['invoice']
- if invoice.filename != '':
- if not allowed_file(invoice.filename):
- return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
-
- filename = secure_filename(invoice.filename)
- filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
- invoice_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
-
- 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
- if 'manual' in request.files:
- manual = request.files['manual']
- if manual.filename != '':
- if not allowed_file(manual.filename):
- return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
-
- 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)
- 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, 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, %s, %s, %s)
- RETURNING id
- ''', (
- product_name, purchase_date, expiration_date,
- db_invoice_path, db_manual_path, db_other_document_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor,
- warranty_duration_years, warranty_duration_months, warranty_duration_days
- ))
- warranty_id = cur.fetchone()[0]
-
- # Insert serial numbers
- if serial_numbers:
- for serial_number in serial_numbers:
- if serial_number.strip(): # Only insert non-empty serial numbers
- cur.execute('''
- INSERT INTO serial_numbers (warranty_id, serial_number)
- VALUES (%s, %s)
- ''', (warranty_id, serial_number.strip()))
-
- # Insert tags if provided
- if tag_ids:
- for tag_id in tag_ids:
- # Verify tag exists
- cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
- if cur.fetchone():
- cur.execute('''
- INSERT INTO warranty_tags (warranty_id, tag_id)
- VALUES (%s, %s)
- ''', (warranty_id, tag_id))
- else:
- logger.warning(f"Skipping non-existent tag ID: {tag_id}")
-
- conn.commit()
-
- return jsonify({
- 'message': 'Warranty added successfully',
- 'id': warranty_id
- }), 201
-
- except Exception as e:
- logger.error(f"Error adding warranty: {e}")
- if conn:
- conn.rollback()
- return jsonify({"error": "Failed to add warranty"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/warranties/<int:warranty_id>', methods=['DELETE'])
-@token_required
-def delete_warranty(warranty_id):
- conn = None
- try:
- user_id = request.user['id']
- is_admin = request.user['is_admin']
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if warranty exists and belongs to the user
- if is_admin:
- cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
- else:
- cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s', (warranty_id, user_id))
-
- warranty = cur.fetchone()
-
- if not warranty:
- return jsonify({"error": "Warranty not found or you don't have permission to delete it"}), 404
-
- # 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,))
- deleted_rows = cur.rowcount
- conn.commit()
-
- # Delete the invoice file if it exists
- if invoice_path:
- full_path = os.path.join('/data', invoice_path)
- if os.path.exists(full_path):
- os.remove(full_path)
-
- # Delete the manual file if it exists
- if manual_path:
- full_path = os.path.join('/data', manual_path)
- 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:
- logger.error(f"Error deleting warranty: {e}")
- if conn:
- conn.rollback()
- return jsonify({"error": "Failed to delete warranty"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/warranties/<int:warranty_id>', methods=['PUT'])
-@token_required
-def update_warranty(warranty_id):
- # --- Log function entry ---
- logger.info(f"Entering update_warranty function for ID: {warranty_id}")
- conn = None
- try:
- user_id = request.user['id']
- is_admin = request.user['is_admin']
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if warranty exists and belongs to the user
- if is_admin:
- cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
- else:
- cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s', (warranty_id, user_id))
- warranty = cur.fetchone()
- if not warranty:
- return jsonify({"error": "Warranty not found or you don't have permission to update it"}), 404
-
- # --- PATCH: Support JSON-only notes update ---
- if request.is_json and 'notes' in request.json and len(request.json) == 1:
- notes = request.json.get('notes', None)
- cur.execute("UPDATE warranties SET notes = %s, updated_at = NOW() WHERE id = %s", (notes, warranty_id))
- conn.commit()
- return jsonify({"message": "Notes updated successfully"}), 200
-
- # --- Otherwise, continue with the original (form-based) update logic ---
- # Validate input data similar to the add_warranty route
- if not request.form.get('product_name'):
- return jsonify({"error": "Product name is required"}), 400
- if not request.form.get('purchase_date'):
- return jsonify({"error": "Purchase date is required"}), 400
- logger.info(f"Received update request for warranty {warranty_id}")
- 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']
- try:
- 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
-
- expiration_date = None
- warranty_duration_years = 0
- warranty_duration_months = 0
- warranty_duration_days = 0
-
- if not is_lifetime:
- try:
- # 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 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[]') # Ensure correct parsing for lists
- product_url = request.form.get('product_url', '')
- notes = request.form.get('notes', None)
- vendor = request.form.get('vendor', None)
- tag_ids = []
- if request.form.get('tag_ids'):
- try:
- tag_ids = json.loads(request.form.get('tag_ids'))
- if not isinstance(tag_ids, list):
- return jsonify({"error": "tag_ids must be a JSON array"}), 400
- except json.JSONDecodeError:
- return jsonify({"error": "tag_ids must be a valid JSON array"}), 400
- purchase_price = None
- if request.form.get('purchase_price'):
- try:
- purchase_price = float(request.form.get('purchase_price'))
- if purchase_price < 0:
- return jsonify({"error": "Purchase price cannot be negative"}), 400
- except ValueError:
- return jsonify({"error": "Purchase price must be a valid number"}), 400
- db_invoice_path = None
- if 'invoice' in request.files:
- invoice = request.files['invoice']
- if invoice.filename != '':
- if not allowed_file(invoice.filename):
- return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
- cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
- old_invoice_path = cur.fetchone()[0]
- if old_invoice_path:
- full_path = os.path.join('/data', old_invoice_path)
- if os.path.exists(full_path):
- try:
- os.remove(full_path)
- logger.info(f"Deleted old invoice: {full_path}")
- except Exception as e:
- logger.error(f"Error deleting old invoice: {e}")
- 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)
- 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]
- if old_invoice_path:
- full_path = os.path.join('/data', old_invoice_path)
- if os.path.exists(full_path):
- try:
- os.remove(full_path)
- logger.info(f"Deleted invoice (delete request): {full_path}")
- except Exception as e:
- logger.error(f"Error deleting invoice (delete request): {e}")
- db_invoice_path = None # Set to None to clear in DB
- db_manual_path = None
- if 'manual' in request.files:
- manual = request.files['manual']
- if manual.filename != '':
- if not allowed_file(manual.filename):
- return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
- cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))
- old_manual_path = cur.fetchone()[0]
- if old_manual_path:
- full_path = os.path.join('/data', old_manual_path)
- if os.path.exists(full_path):
- try:
- os.remove(full_path)
- logger.info(f"Deleted old manual: {full_path}")
- except Exception as e:
- logger.error(f"Error deleting old manual: {e}")
- 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)
- 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]
- if old_manual_path:
- full_path = os.path.join('/data', old_manual_path)
- if os.path.exists(full_path):
- try:
- os.remove(full_path)
- logger.info(f"Deleted manual (delete request): {full_path}")
- 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_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,
- 'vendor': vendor
- }
- sql_fields = []
- sql_values = []
- for key, value in update_params.items():
- sql_fields.append(f"{key} = %s")
- sql_values.append(value)
- if notes is not None:
- sql_fields.append("notes = %s")
- sql_values.append(notes)
- if db_invoice_path is not None:
- sql_fields.append("invoice_path = %s")
- sql_values.append(db_invoice_path)
- elif 'delete_invoice' in request.form and request.form.get('delete_invoice', 'false').lower() == 'true':
- sql_fields.append("invoice_path = NULL")
- if db_manual_path is not None:
- sql_fields.append("manual_path = %s")
- 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"
- cur.execute(update_sql, sql_values)
- logger.info(f"Updated warranty with SQL: {update_sql}")
- logger.info(f"Parameters: {sql_values}")
- cur.execute('DELETE FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))
- if serial_numbers:
- for serial_number in serial_numbers:
- if serial_number.strip(): # Only insert non-empty serial numbers
- cur.execute('''
- INSERT INTO serial_numbers (warranty_id, serial_number)
- VALUES (%s, %s)
- ''', (warranty_id, serial_number.strip()))
-
- # Update tags if provided
- if tag_ids is not None:
- # Remove existing tags
- cur.execute('DELETE FROM warranty_tags WHERE warranty_id = %s', (warranty_id,))
-
- # Add new tags
- for tag_id in tag_ids:
- # Verify tag exists
- cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
- if cur.fetchone():
- cur.execute('''
- INSERT INTO warranty_tags (warranty_id, tag_id)
- VALUES (%s, %s)
- ''', (warranty_id, tag_id))
- else:
- logger.warning(f"Skipping non-existent tag ID: {tag_id}")
-
- conn.commit()
-
- return jsonify({"message": "Warranty updated successfully"}), 200
-
- except Exception as e:
- logger.error(f"Error updating warranty: {e}")
- if conn:
- conn.rollback()
- return jsonify({"error": "Failed to update warranty"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/statistics', methods=['GET'])
-@token_required
-def get_statistics():
- user_id = request.user['id']
- conn = None
-
- try:
- conn = get_db_connection()
- today = date.today()
-
- # Fetch user preference for expiring soon days
- expiring_soon_days = 30 # Default value
- try:
- with conn.cursor() as cur:
- cur.execute("SELECT expiring_soon_days FROM user_preferences WHERE user_id = %s", (user_id,))
- result = cur.fetchone()
- if result and result[0] is not None:
- expiring_soon_days = result[0]
- logger.info(f"Using custom expiring soon days: {expiring_soon_days} for user {user_id}")
- else:
- logger.info(f"Using default expiring soon days: {expiring_soon_days} for user {user_id}")
- except Exception as pref_err:
- # Log error fetching preference but continue with default
- logger.error(f"Error fetching expiring_soon_days preference for user {user_id}: {pref_err}. Using default 30 days.")
-
- expiring_soon_date = today + timedelta(days=expiring_soon_days)
- ninety_days_later = today + timedelta(days=90) # Keep timeline fixed or make configurable? For now, keep at 90.
-
- # Build base query based on role
- from_clause = "FROM warranties w"
- where_clause = ""
- params = []
- active_where = "AND"
-
- if not request.user.get('is_admin', False):
- where_clause = "WHERE w.user_id = %s"
- params = [user_id]
- active_where = "AND"
- else:
- # Admin should only see their own warranties
- where_clause = "WHERE w.user_id = %s"
- params = [user_id]
- active_where = "AND"
-
- with conn.cursor() as cur:
- # Get total count
- cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause}", params)
- total_count = cur.fetchone()[0]
- logger.info(f"Total warranties: {total_count}")
-
- # Get active count (includes lifetime)
- cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} (w.is_lifetime = TRUE OR w.expiration_date > %s)", params + [today])
- active_count = cur.fetchone()[0]
- logger.info(f"Active warranties: {active_count}")
-
- # Get expired count (excludes lifetime)
- cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} w.is_lifetime = FALSE AND w.expiration_date <= %s", params + [today])
- expired_count = cur.fetchone()[0]
- logger.info(f"Expired warranties: {expired_count}")
-
- # Get expiring soon count (excludes lifetime) using user preference
- cur.execute(f"""SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'}
- w.is_lifetime = FALSE AND w.expiration_date > %s AND w.expiration_date <= %s""",
- params + [today, expiring_soon_date])
- expiring_soon_count = cur.fetchone()[0]
- logger.info(f"Expiring soon ({expiring_soon_days} days) warranties: {expiring_soon_count}")
-
- # Get expiration timeline (next 90 days, excluding lifetime)
- cur.execute(f"""
- SELECT
- EXTRACT(YEAR FROM expiration_date) as year,
- EXTRACT(MONTH FROM expiration_date) as month,
- COUNT(*) as count
- {from_clause}
- {where_clause} {active_where if where_clause else 'WHERE'}
- w.is_lifetime = FALSE AND w.expiration_date > %s AND w.expiration_date <= %s
- GROUP BY EXTRACT(YEAR FROM expiration_date), EXTRACT(MONTH FROM expiration_date)
- ORDER BY year, month
- """, params + [today, ninety_days_later])
-
- timeline = []
- for row in cur.fetchall():
- year = int(row[0])
- month = int(row[1])
- count = row[2]
- timeline.append({
- "year": year,
- "month": month,
- "count": count
- })
-
- # Get recent expiring warranties (using user preference +/- 30 days for range, excluding lifetime)
- # We'll keep the window around today somewhat fixed for 'recent', maybe +/- 30 days is still reasonable? Or should this also use expiring_soon_days?
- # Let's adjust the recent window based on the preference for now: N days ago to N days later
- days_ago_for_recent = today - timedelta(days=expiring_soon_days)
- days_later_for_recent = expiring_soon_date # Same as the expiring soon cutoff
- cur.execute(f"""
- SELECT
- id, product_name, purchase_date,
- warranty_duration_years, warranty_duration_months, warranty_duration_days,
- expiration_date, invoice_path, manual_path, other_document_path, product_url, purchase_price, is_lifetime
- {from_clause}
- {where_clause} {active_where if where_clause else 'WHERE'}
- w.is_lifetime = FALSE AND w.expiration_date >= %s AND w.expiration_date <= %s
- ORDER BY expiration_date
- LIMIT 10
- """, params + [days_ago_for_recent, days_later_for_recent])
-
- columns = [desc[0] for desc in cur.description]
- recent_warranties = []
-
- for row in cur.fetchall():
- warranty = dict(zip(columns, row))
-
- # Convert dates to string format
- if warranty['purchase_date']:
- warranty['purchase_date'] = warranty['purchase_date'].isoformat()
- if warranty['expiration_date']:
- warranty['expiration_date'] = warranty['expiration_date'].isoformat()
-
- # Convert Decimal objects to float for JSON serialization
- if warranty.get('purchase_price') and isinstance(warranty['purchase_price'], Decimal):
- warranty['purchase_price'] = float(warranty['purchase_price'])
-
- recent_warranties.append(warranty)
-
- # *** ADD CODE TO FETCH ALL WARRANTIES ***
- logger.info(f"Fetching all warranties for user {user_id}...")
- cur.execute(f"""
- SELECT
- id, product_name, purchase_date,
- warranty_duration_years, warranty_duration_months, warranty_duration_days,
- expiration_date, invoice_path, manual_path, other_document_path, product_url, purchase_price, is_lifetime
- {from_clause}
- {where_clause}
- ORDER BY expiration_date DESC
- """, params)
-
- all_columns = [desc[0] for desc in cur.description]
- all_warranties_list = []
-
- for row in cur.fetchall():
- warranty = dict(zip(all_columns, row))
-
- # Convert dates to string format
- if warranty.get('purchase_date') and isinstance(warranty['purchase_date'], date):
- warranty['purchase_date'] = warranty['purchase_date'].isoformat()
- if warranty.get('expiration_date') and isinstance(warranty['expiration_date'], date):
- warranty['expiration_date'] = warranty['expiration_date'].isoformat()
-
- # Convert Decimal objects to float for JSON serialization
- if warranty.get('purchase_price') and isinstance(warranty['purchase_price'], Decimal):
- warranty['purchase_price'] = float(warranty['purchase_price'])
-
- all_warranties_list.append(warranty)
- logger.info(f"Fetched {len(all_warranties_list)} total warranties.")
- # *** END OF ADDED CODE ***
-
- statistics = {
- 'total': total_count,
- 'active': active_count,
- 'expired': expired_count,
- 'expiring_soon': expiring_soon_count,
- 'timeline': timeline,
- 'recent_warranties': recent_warranties,
- 'all_warranties': all_warranties_list # <-- Add the new list here
- }
-
- return jsonify(convert_decimals(statistics))
-
- except Exception as e:
- logger.error(f"Error getting warranty statistics: {e}")
- return jsonify({"error": str(e)}), 500
-
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/test', methods=['GET'])
-def test_endpoint():
- """Simple test endpoint to check if the API is responding."""
- return jsonify({
- "status": "success",
- "message": "API is working",
- "timestamp": datetime.utcnow().isoformat()
- })
-
-# Public endpoint to check if authentication is required
[email protected]('/api/auth/status', methods=['GET'])
-def auth_status():
- return jsonify({
- "authentication_required": True,
- "message": "Authentication is required for most endpoints"
- })
-
[email protected]('/api/auth/profile', methods=['PUT'])
-@token_required
-def update_profile():
- user_id = request.user['id']
-
- try:
- # Get request data
- data = request.get_json()
- if not data:
- return jsonify({'message': 'No input data provided'}), 400
-
- # Extract fields
- first_name = data.get('first_name', '').strip()
- last_name = data.get('last_name', '').strip()
- new_email = data.get('email', '').strip()
-
- # Validate input
- if not first_name or not last_name:
- return jsonify({'message': 'First name and last name are required'}), 400
-
- # Get database connection
- conn = get_db_connection()
- cursor = conn.cursor()
-
- try:
- update_fields = ["first_name = %s", "last_name = %s"]
- update_params = [first_name, last_name]
-
- # Handle email change
- if new_email:
- if not is_valid_email(new_email):
- conn.rollback()
- return jsonify({'message': 'Invalid email format!'}), 400
-
- # Check if the new email is different from the current one
- cursor.execute("SELECT email FROM users WHERE id = %s", (user_id,))
- current_email_tuple = cursor.fetchone()
- if not current_email_tuple:
- conn.rollback()
- return jsonify({'message': 'User not found while fetching current email.'}), 404
- current_email = current_email_tuple[0]
-
- if new_email.lower() != current_email.lower():
- # Check if the new email is already in use by another user
- cursor.execute("SELECT id FROM users WHERE LOWER(email) = LOWER(%s) AND id != %s", (new_email, user_id))
- if cursor.fetchone():
- conn.rollback()
- return jsonify({'message': 'This email address is already in use by another account.'}), 409
- update_fields.append("email = %s")
- update_params.append(new_email)
-
- update_query_string = ", ".join(update_fields)
- final_query = f"""
- UPDATE users
- SET {update_query_string}
- WHERE id = %s
- RETURNING id, username, email, first_name, last_name, created_at
- """
- cursor.execute(final_query, tuple(update_params + [user_id]))
-
- # Get updated user data
- user_data = cursor.fetchone()
- if not user_data:
- conn.rollback()
- return jsonify({'message': 'User not found'}), 404
-
- conn.commit()
-
- user = {
- 'id': user_data[0],
- 'username': user_data[1],
- 'email': user_data[2],
- 'first_name': user_data[3],
- 'last_name': user_data[4],
- 'created_at': user_data[5].isoformat() if user_data[5] else None
- }
- return jsonify(user), 200
-
- except Exception as e:
- conn.rollback()
- logger.error(f"Database error in update_profile: {str(e)}")
- return jsonify({'message': 'Database error occurred'}), 500
- finally:
- cursor.close()
- release_db_connection(conn)
-
- except Exception as e:
- logger.error(f"Error in update_profile: {str(e)}")
- return jsonify({'message': 'An error occurred while updating profile'}), 500
-
[email protected]('/api/auth/account', methods=['DELETE'])
-@token_required
-def delete_account():
- user_id = request.user['id']
-
- try:
- # Get database connection
- conn = get_db_connection()
- cursor = conn.cursor()
-
- try:
- # Begin transaction
- cursor.execute("BEGIN")
-
- # Delete user's warranties
- cursor.execute("DELETE FROM warranties WHERE user_id = %s", (user_id,))
-
- # Delete user's reset tokens if any
- cursor.execute("DELETE FROM password_reset_tokens WHERE user_id = %s", (user_id,))
-
- # Delete user's sessions if any
- cur.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
- sessions_deleted = cur.rowcount
- logger.info(f"Deleted {sessions_deleted} sessions belonging to user {user_id}")
-
- # Delete user's tags
- cur.execute('DELETE FROM tags WHERE user_id = %s', (user_id,))
- tags_deleted = cur.rowcount
- logger.info(f"Deleted {tags_deleted} tags belonging to user {user_id}")
-
- # Delete user
- cursor.execute("DELETE FROM users WHERE id = %s", (user_id,))
- user_deleted = cur.rowcount
- logger.info(f"Deleted user {user_id}, affected rows: {user_deleted}")
-
- # Commit transaction
- cursor.execute("COMMIT")
-
- return jsonify({'message': 'Account deleted successfully'}), 200
-
- except Exception as e:
- cursor.execute("ROLLBACK")
- logger.error(f"Database error in delete_account: {str(e)}")
- return jsonify({'message': 'Database error occurred'}), 500
- finally:
- cursor.close()
- release_db_connection(conn)
-
- except Exception as e:
- logger.error(f"Error in delete_account: {str(e)}")
- return jsonify({'message': 'An error occurred while deleting account'}), 500
-
[email protected]('/api/auth/preferences', methods=['GET'])
-@token_required
-def get_preferences():
- user_id = request.user['id']
- try:
- conn = get_db_connection()
- cursor = conn.cursor()
- try:
- cursor.execute("""
- SELECT EXISTS (
- SELECT FROM information_schema.tables
- WHERE table_name = 'user_preferences'
- )
- """)
- table_exists = cursor.fetchone()[0]
- if not table_exists:
- cursor.execute("""
- CREATE TABLE user_preferences (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- email_notifications BOOLEAN NOT NULL DEFAULT TRUE,
- default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
- theme VARCHAR(10) NOT NULL DEFAULT 'light',
- expiring_soon_days INTEGER NOT NULL DEFAULT 30,
- notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily',
- notification_time VARCHAR(5) NOT NULL DEFAULT '09:00',
- timezone VARCHAR(50) NOT NULL DEFAULT 'UTC',
- currency_symbol VARCHAR(8) DEFAULT '$',
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- UNIQUE(user_id)
- )
- """)
- cursor.execute("""
- CREATE INDEX idx_user_preferences_user_id ON user_preferences(user_id)
- """)
- conn.commit()
- logger.info(f"Created user_preferences table")
- has_currency = has_currency_symbol_column(cursor)
-
- cursor.execute("SELECT column_name FROM information_schema.columns WHERE table_name='user_preferences' AND column_name='date_format'")
- has_date_format_col = cursor.fetchone() is not None
-
- # Build select list dynamically
- select_fields_list = ["email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
- if has_currency:
- select_fields_list.append("currency_symbol")
- if has_date_format_col:
- select_fields_list.append("date_format") # Add date_format if column exists
- select_fields = ", ".join(select_fields_list)
-
- cursor.execute(
- f"""
- SELECT {select_fields}
- FROM user_preferences
- WHERE user_id = %s
- """,
- (user_id,)
- )
- preferences_data = cursor.fetchone()
-
- if not preferences_data:
- # Build insert list dynamically
- insert_cols_list = ["user_id", "email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
- insert_vals = [user_id, True, 'grid', 'light', 30, 'daily', '09:00', 'UTC']
- if has_currency:
- insert_cols_list.append("currency_symbol")
- insert_vals.append('$')
- if has_date_format_col:
- insert_cols_list.append("date_format")
- insert_vals.append('MDY') # Default date format
-
- insert_cols = ", ".join(insert_cols_list)
- insert_vals_placeholders = ", ".join(["%s"] * len(insert_cols_list))
- return_fields = insert_cols # Return the same columns we inserted
-
- cursor.execute(
- f"""
- INSERT INTO user_preferences ({insert_cols})
- VALUES ({insert_vals_placeholders})
- RETURNING {return_fields}
- """,
- tuple(insert_vals)
- )
- preferences_data = cursor.fetchone()
- conn.commit()
-
- # Map returned data to dictionary using the dynamically determined fields
- returned_columns = [col.strip() for col in select_fields.split(',')]
- if preferences_data:
- pref_map = {col: i for i, col in enumerate(returned_columns)}
- preferences = {
- 'email_notifications': preferences_data[pref_map.get('email_notifications', 0)],
- 'default_view': preferences_data[pref_map.get('default_view', 1)],
- 'theme': preferences_data[pref_map.get('theme', 2)],
- 'expiring_soon_days': preferences_data[pref_map.get('expiring_soon_days', 3)],
- 'notification_frequency': preferences_data[pref_map.get('notification_frequency', 4)],
- 'notification_time': preferences_data[pref_map.get('notification_time', 5)],
- 'timezone': preferences_data[pref_map.get('timezone', 6)],
- 'currency_symbol': preferences_data[pref_map['currency_symbol']] if 'currency_symbol' in pref_map else '$', # Handle currency optionality
- 'date_format': preferences_data[pref_map['date_format']] if 'date_format' in pref_map else 'MDY' # Handle date_format optionality
- }
- else:
- # Fallback if even insert failed or returned nothing
- preferences = default_preferences.copy()
- preferences['date_format'] = 'MDY' # Ensure date_format is in fallback
-
- return jsonify(preferences), 200
- except Exception as e:
- conn.rollback()
- logger.error(f"Database error in get_preferences: {str(e)}")
- default_preferences = {
- 'email_notifications': True,
- 'default_view': 'grid',
- 'theme': 'light',
- 'expiring_soon_days': 30,
- 'notification_frequency': 'daily',
- 'notification_time': '09:00',
- 'timezone': 'UTC',
- 'currency_symbol': '$'
- }
- return jsonify(default_preferences), 200
- finally:
- cursor.close()
- release_db_connection(conn)
- except Exception as e:
- logger.error(f"Error in get_preferences: {str(e)}")
- default_preferences = {
- 'email_notifications': True,
- 'default_view': 'grid',
- 'theme': 'light',
- 'expiring_soon_days': 30,
- 'notification_frequency': 'daily',
- 'notification_time': '09:00',
- 'timezone': 'UTC',
- 'currency_symbol': '$'
- }
- return jsonify(default_preferences), 200
-
[email protected]('/api/auth/preferences', methods=['PUT'])
-@token_required
-def update_preferences():
- user_id = request.user['id']
- try:
- data = request.get_json()
- if not data:
- return jsonify({'message': 'No input data provided'}), 400
- email_notifications = data.get('email_notifications')
- default_view = data.get('default_view')
- theme = data.get('theme')
- expiring_soon_days = data.get('expiring_soon_days')
- notification_frequency = data.get('notification_frequency')
- notification_time = data.get('notification_time')
- timezone = data.get('timezone')
- currency_symbol = data.get('currency_symbol')
- date_format = data.get('date_format')
-
- if default_view and default_view not in ['grid', 'list', 'table']:
- return jsonify({'message': 'Invalid default view'}), 400
- if theme and theme not in ['light', 'dark']:
- return jsonify({'message': 'Invalid theme'}), 400
- if expiring_soon_days is not None:
- try:
- expiring_soon_days = int(expiring_soon_days)
- if expiring_soon_days < 1 or expiring_soon_days > 365:
- return jsonify({'message': 'Expiring soon days must be between 1 and 365'}), 400
- except ValueError:
- return jsonify({'message': 'Expiring soon days must be a valid number'}), 400
- if notification_frequency and notification_frequency not in ['daily', 'weekly', 'monthly']:
- return jsonify({'message': 'Invalid notification frequency'}), 400
- if notification_time and not re.match(r'^([01]?[0-9]|2[0-3]):[0-5][0-9]$', notification_time):
- return jsonify({'message': 'Invalid notification time format'}), 400
- if timezone and not is_valid_timezone(timezone):
- return jsonify({'message': 'Invalid timezone'}), 400
-
- # Add validation for date_format
- valid_date_formats = ['MDY', 'DMY', 'YMD', 'MDY_WORDS', 'DMY_WORDS', 'YMD_WORDS']
- if date_format and date_format not in valid_date_formats:
- return jsonify({'message': 'Invalid date format'}), 400
-
- conn = get_db_connection()
- cursor = conn.cursor()
- try:
- # Check if date_format column exists first to handle dynamic schema changes
- cursor.execute("SELECT column_name FROM information_schema.columns WHERE table_name='user_preferences' AND column_name='date_format'")
- has_date_format_col = cursor.fetchone() is not None
- has_currency = has_currency_symbol_column(cursor)
-
- cursor.execute(
- "SELECT 1 FROM user_preferences WHERE user_id = %s",
- (user_id,)
- )
- preferences_exist = cursor.fetchone() is not None
-
- if preferences_exist:
- update_fields = []
- update_values = []
- if email_notifications is not None:
- update_fields.append("email_notifications = %s")
- update_values.append(email_notifications)
- if default_view:
- update_fields.append("default_view = %s")
- update_values.append(default_view)
- if theme:
- update_fields.append("theme = %s")
- update_values.append(theme)
- if expiring_soon_days is not None:
- update_fields.append("expiring_soon_days = %s")
- update_values.append(expiring_soon_days)
- if notification_frequency:
- update_fields.append("notification_frequency = %s")
- update_values.append(notification_frequency)
- if notification_time:
- update_fields.append("notification_time = %s")
- update_values.append(notification_time)
- if timezone:
- update_fields.append("timezone = %s")
- update_values.append(timezone)
- if has_currency and currency_symbol is not None:
- update_fields.append("currency_symbol = %s")
- update_values.append(currency_symbol)
- # Add date_format to update only if the column exists
- if has_date_format_col and date_format:
- update_fields.append("date_format = %s")
- update_values.append(date_format)
-
- if update_fields:
- # Build the returning fields string dynamically based on existing columns
- return_fields_list = ["email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
- if has_currency:
- return_fields_list.append("currency_symbol")
- if has_date_format_col:
- return_fields_list.append("date_format")
- return_fields = ", ".join(return_fields_list)
-
- update_query = f"""
- UPDATE user_preferences
- SET {', '.join(update_fields)}
- WHERE user_id = %s
- RETURNING {return_fields}
- """
- cursor.execute(update_query, update_values + [user_id])
- preferences_data = cursor.fetchone()
- else:
- # If no fields to update, select existing data
- select_fields_list = ["email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
- if has_currency:
- select_fields_list.append("currency_symbol")
- if has_date_format_col:
- select_fields_list.append("date_format")
- select_fields = ", ".join(select_fields_list)
-
- cursor.execute(
- f"""
- SELECT {select_fields}
- FROM user_preferences
- WHERE user_id = %s
- """,
- (user_id,)
- )
- preferences_data = cursor.fetchone()
- else: # Insert new record
- # Build insert dynamically
- insert_cols_list = ["user_id", "email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
- insert_vals = [
- user_id,
- email_notifications if email_notifications is not None else True,
- default_view or 'grid',
- theme or 'light',
- expiring_soon_days if expiring_soon_days is not None else 30,
- notification_frequency or 'daily',
- notification_time or '09:00',
- timezone or 'UTC'
- ]
- if has_currency:
- insert_cols_list.append("currency_symbol")
- insert_vals.append(currency_symbol or '$')
- if has_date_format_col:
- insert_cols_list.append("date_format")
- insert_vals.append(date_format or 'MDY')
-
- insert_cols = ", ".join(insert_cols_list)
- insert_vals_placeholders = ", ".join(["%s"] * len(insert_cols_list))
- return_fields = insert_cols # Return the same columns we inserted
-
- cursor.execute(
- f"""
- INSERT INTO user_preferences ({insert_cols})
- VALUES ({insert_vals_placeholders})
- RETURNING {return_fields}
- """,
- tuple(insert_vals)
- )
- preferences_data = cursor.fetchone()
-
- # Map returned data to dictionary using the dynamically determined fields
- returned_columns = [col.strip() for col in return_fields.split(',')]
- pref_map = {col: i for i, col in enumerate(returned_columns)}
-
- preferences = {
- 'email_notifications': preferences_data[pref_map.get('email_notifications', 0)], # Default index 0 might be risky, but needed if column is missing
- 'default_view': preferences_data[pref_map.get('default_view', 1)],
- 'theme': preferences_data[pref_map.get('theme', 2)],
- 'expiring_soon_days': preferences_data[pref_map.get('expiring_soon_days', 3)],
- 'notification_frequency': preferences_data[pref_map.get('notification_frequency', 4)],
- 'notification_time': preferences_data[pref_map.get('notification_time', 5)],
- 'timezone': preferences_data[pref_map.get('timezone', 6)],
- 'currency_symbol': preferences_data[pref_map['currency_symbol']] if 'currency_symbol' in pref_map else '$', # Handle currency optionality
- 'date_format': preferences_data[pref_map['date_format']] if 'date_format' in pref_map else 'MDY' # Handle date_format optionality
- }
-
- conn.commit()
- return jsonify(preferences), 200
- except Exception as e:
- conn.rollback()
- logger.error(f"Database error in update_preferences: {str(e)}")
- fallback_preferences = {
- 'email_notifications': email_notifications if email_notifications is not None else True,
- 'default_view': default_view or 'grid',
- 'theme': theme or 'light',
- 'expiring_soon_days': expiring_soon_days if expiring_soon_days is not None else 30,
- 'notification_frequency': notification_frequency or 'daily',
- 'notification_time': notification_time or '09:00',
- 'timezone': timezone or 'UTC',
- 'currency_symbol': currency_symbol or '$',
- 'date_format': date_format or 'MDY' # Add to fallback
- }
- return jsonify(fallback_preferences), 200
- finally:
- cursor.close()
- release_db_connection(conn)
- except Exception as e:
- logger.error(f"Error in update_preferences: {str(e)}")
- default_preferences = {
- 'email_notifications': True,
- 'default_view': 'grid',
- 'theme': 'light',
- 'expiring_soon_days': 30,
- 'notification_frequency': 'daily',
- 'notification_time': '09:00',
- 'timezone': 'UTC',
- 'currency_symbol': '$'
- }
- return jsonify(default_preferences), 200
-
-# Admin User Management Endpoints
-
[email protected]('/api/admin/users', methods=['GET'])
-@admin_required
-def get_all_users():
- """Get all users (admin only)"""
- conn = None
- try:
- conn = get_db_connection()
- with conn.cursor() as cur:
- cur.execute('''
- SELECT id, username, email, first_name, last_name, is_active, is_admin, created_at, last_login
- FROM users
- ORDER BY created_at DESC
- ''')
- users = cur.fetchall()
- columns = [desc[0] for desc in cur.description]
- users_list = []
-
- for row in users:
- user_dict = dict(zip(columns, row))
- # Convert date objects to ISO format strings for JSON serialization
- for key, value in user_dict.items():
- if isinstance(value, (datetime, date)):
- user_dict[key] = value.isoformat() if value else None
-
- users_list.append(user_dict)
-
- return jsonify(users_list), 200
- except Exception as e:
- logger.error(f"Error retrieving users: {e}")
- return jsonify({"message": "Failed to retrieve users"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/admin/users/<int:user_id>', methods=['PUT'])
-@admin_required
-def update_user(user_id):
- """Update user details (admin only)"""
- conn = None
- try:
- # Prevent modifying self
- if user_id == request.user['id']:
- return jsonify({"message": "Cannot modify your own admin status"}), 403
-
- data = request.get_json()
-
- # Use regular connection since db_user now has superuser privileges
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if user exists
- cur.execute('SELECT id FROM users WHERE id = %s', (user_id,))
- user = cur.fetchone()
-
- if not user:
- return jsonify({"message": "User not found"}), 404
-
- # Update fields
- updates = []
- params = []
-
- if 'is_admin' in data:
- updates.append('is_admin = %s')
- params.append(bool(data['is_admin']))
-
- if 'is_active' in data:
- updates.append('is_active = %s')
- params.append(bool(data['is_active']))
-
- if not updates:
- return jsonify({"message": "No fields to update"}), 400
-
- # Build and execute update query
- query = f"UPDATE users SET {', '.join(updates)} WHERE id = %s"
- params.append(user_id)
-
- cur.execute(query, params)
- conn.commit()
-
- return jsonify({"message": "User updated successfully"}), 200
- except Exception as e:
- logger.error(f"Error updating user: {e}")
- if conn:
- conn.rollback()
- return jsonify({"message": f"Failed to update user: {str(e)}"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/admin/users/<int:user_id>', methods=['DELETE'])
-@admin_required
-def delete_user(user_id):
- """Delete a user (admin only)"""
- conn = None
- try:
- logger.info(f"Delete user request received for user_id: {user_id}")
-
- # Prevent deleting self
- if user_id == request.user['id']:
- logger.warning(f"User {request.user['username']} attempted to delete their own account")
- return jsonify({"message": "Cannot delete your own account through admin API"}), 403
-
- # Use regular connection since db_user now has superuser privileges
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if user exists
- cur.execute('SELECT id, username FROM users WHERE id = %s', (user_id,))
- user = cur.fetchone()
-
- if not user:
- logger.warning(f"User with ID {user_id} not found")
- return jsonify({"message": "User not found"}), 404
-
- logger.info(f"Deleting user {user[1]} (ID: {user[0]})")
-
- # Delete user's warranties first
- cur.execute('DELETE FROM warranties WHERE user_id = %s', (user_id,))
- warranties_deleted = cur.rowcount
- logger.info(f"Deleted {warranties_deleted} warranties belonging to user {user_id}")
-
- # Delete user's password reset tokens if any
- cur.execute('DELETE FROM password_reset_tokens WHERE user_id = %s', (user_id,))
- tokens_deleted = cur.rowcount
- logger.info(f"Deleted {tokens_deleted} password reset tokens belonging to user {user_id}")
-
- # Delete user's sessions if any
- cur.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
- sessions_deleted = cur.rowcount
- logger.info(f"Deleted {sessions_deleted} sessions belonging to user {user_id}")
-
- # Delete user's tags
- cur.execute('DELETE FROM tags WHERE user_id = %s', (user_id,))
- tags_deleted = cur.rowcount
- logger.info(f"Deleted {tags_deleted} tags belonging to user {user_id}")
-
- # Delete user
- cur.execute('DELETE FROM users WHERE id = %s', (user_id,))
- user_deleted = cur.rowcount
- logger.info(f"Deleted user {user_id}, affected rows: {user_deleted}")
-
- conn.commit()
- logger.info(f"User {user_id} deleted successfully")
-
- return jsonify({"message": "User deleted successfully"}), 200
- except Exception as e:
- logger.error(f"Error deleting user: {e}")
- if conn:
- conn.rollback()
- return jsonify({"message": f"Failed to delete user: {str(e)}"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
-# Site settings
[email protected]('/api/admin/settings', methods=['GET'])
-@admin_required
-def get_site_settings():
- """Get site settings (admin only)"""
- conn = None
- try:
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if settings table exists
- cur.execute("""
- SELECT EXISTS (
- SELECT FROM information_schema.tables
- WHERE table_name = 'site_settings'
- )
- """)
- table_exists = cur.fetchone()[0]
-
- # Create settings table if it doesn't exist
- if not table_exists:
- cur.execute("""
- CREATE TABLE site_settings (
- key VARCHAR(255) PRIMARY KEY,
- value TEXT,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- )
- """)
- conn.commit()
-
- # Get all settings
- cur.execute('SELECT key, value FROM site_settings')
- settings = {row[0]: row[1] for row in cur.fetchall()}
-
- # Set default values if not present
- if 'registration_enabled' not in settings:
- settings['registration_enabled'] = 'true'
- cur.execute(
- 'INSERT INTO site_settings (key, value) VALUES (%s, %s)',
- ('registration_enabled', 'true')
- )
- conn.commit()
-
- # Default email base URL if not set
- if 'email_base_url' not in settings:
- default_base_url = 'http://localhost:8080' # Default value
- settings['email_base_url'] = default_base_url
- cur.execute(
- 'INSERT INTO site_settings (key, value) VALUES (%s, %s) ON CONFLICT (key) DO NOTHING',
- ('email_base_url', default_base_url)
- )
- conn.commit()
-
- return jsonify(settings), 200
- except Exception as e:
- logger.error(f"Error retrieving site settings: {e}")
- return jsonify({"message": "Failed to retrieve site settings"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/admin/settings', methods=['PUT'])
-@admin_required
-def update_site_settings():
- """Update site settings (admin only)"""
- conn = None
- try:
- data = request.get_json()
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if settings table exists
- cur.execute("""
- SELECT EXISTS (
- SELECT FROM information_schema.tables
- WHERE table_name = 'site_settings'
- )
- """)
- table_exists = cur.fetchone()[0]
-
- # Create settings table if it doesn't exist
- if not table_exists:
- cur.execute("""
- CREATE TABLE site_settings (
- key VARCHAR(255) PRIMARY KEY,
- value TEXT,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- )
- """)
-
- # Update settings
- for key, value in data.items():
- # Convert boolean to string
- if isinstance(value, bool):
- value = str(value).lower()
-
- cur.execute("""
- INSERT INTO site_settings (key, value, updated_at)
- VALUES (%s, %s, CURRENT_TIMESTAMP)
- ON CONFLICT (key)
- DO UPDATE SET value = %s, updated_at = CURRENT_TIMESTAMP
- """, (key, value, value))
-
- conn.commit()
-
- return jsonify({"message": "Settings updated successfully"}), 200
- except Exception as e:
- logger.error(f"Error updating site settings: {e}")
- if conn:
- conn.rollback()
- return jsonify({"message": "Failed to update site settings"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
-# Modify the register endpoint to check if registration is enabled
[email protected]('/api/auth/registration-status', methods=['GET'])
-def check_registration_status():
- """Check if registration is enabled"""
- conn = None
+ # Initialize the notification scheduler with the created app context
try:
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if settings table exists
- cur.execute("""
- SELECT EXISTS (
- SELECT FROM information_schema.tables
- WHERE table_name = 'site_settings'
- )
- """)
- table_exists = cur.fetchone()[0]
-
- if not table_exists:
- # If table doesn't exist, registration is enabled by default
- return jsonify({"enabled": True}), 200
-
- # Get registration_enabled setting
- cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")
- result = cur.fetchone()
-
- if not result:
- # If setting doesn't exist, registration is enabled by default
- return jsonify({"enabled": True}), 200
-
- registration_enabled = result[0].lower() == 'true'
-
- return jsonify({"enabled": registration_enabled}), 200
- except Exception as e:
- logger.error(f"Error checking registration status: {e}")
- return jsonify({"enabled": True}), 200 # Default to enabled on error
- finally:
- if conn:
- release_db_connection(conn)
-
-# File serving endpoints
[email protected]('/api/files/<path:filename>', methods=['GET', 'POST'])
-@token_required
-def serve_file(filename):
- """Basic secure file serving with authentication."""
- try:
- logger.info(f"File access request for {filename} by user {request.user['id']}")
-
- if not filename.startswith('uploads/'):
- logger.warning(f"Attempted access to non-uploads file: {filename}")
- return jsonify({"message": "Access denied"}), 403
-
- # Remove 'uploads/' prefix for send_from_directory
- file_path = filename[8:] if filename.startswith('uploads/') else filename
+ from . import notifications
- return send_from_directory('/data/uploads', file_path)
+ with app.app_context():
+ notifications.init_scheduler(app, db_handler.get_db_connection, db_handler.release_db_connection)
+ logger.info("Notification scheduler initialized successfully")
except Exception as e:
- logger.error(f"Error serving file {filename}: {e}")
- return jsonify({"message": "Error accessing file"}), 500
-
[email protected]('/api/secure-file/<path:filename>', methods=['GET', 'POST'])
-@token_required
-def secure_file_access(filename):
- """Enhanced secure file serving with authorization checks."""
- try:
- # 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"[SECURE_FILE] Potential path traversal attempt detected: {filename} by user {request.user['id']}")
- return jsonify({"message": "Invalid file path"}), 400
-
- conn = get_db_connection()
- try:
- with conn.cursor() as cur:
- 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 OR w.other_document_path = %s
- """
- cur.execute(query, (db_search_path, db_search_path, db_search_path))
- results = cur.fetchall()
- 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
- logger.info(f"[SECURE_FILE] Initial authorization (is_admin={is_admin}): {authorized}")
-
- if not authorized and results:
- 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"[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
-
- 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"[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():
- """Get warranties that are expiring soon for notification purposes"""
- conn = None
- try:
- conn = get_db_connection()
- today = date.today()
-
- with conn.cursor() as cur:
- cur.execute("""
- SELECT
- u.id, -- Select user_id
- u.email,
- u.first_name,
- w.product_name,
- w.expiration_date,
- COALESCE(up.expiring_soon_days, 30) AS expiring_soon_days
- FROM
- warranties w
- JOIN
- users u ON w.user_id = u.id
- LEFT JOIN
- user_preferences up ON u.id = up.user_id
- WHERE
- w.is_lifetime = FALSE
- AND w.expiration_date > %s
- AND w.expiration_date <= (%s::date + (COALESCE(up.expiring_soon_days, 30) || ' days')::interval)::date
- AND u.is_active = TRUE
- AND COALESCE(up.email_notifications, TRUE) = TRUE;
- """, (today, today))
-
- expiring_warranties = []
- for row in cur.fetchall():
- user_id, email, first_name, product_name, expiration_date, expiring_soon_days = row # Include user_id
- expiration_date_str = expiration_date.strftime('%Y-%m-%d')
- expiring_warranties.append({
- 'user_id': user_id, # Add user_id to the dict
- 'email': email,
- 'first_name': first_name or 'User', # Default if first_name is NULL
- 'product_name': product_name,
- 'expiration_date': expiration_date_str,
- })
-
- return expiring_warranties
-
- except Exception as e:
- logger.error(f"Error retrieving expiring warranties: {e}")
- return [] # Return an empty list on error
- finally:
- if conn:
- release_db_connection(conn)
-
-def format_expiration_email(user, warranties):
- """
- Format an email notification for expiring warranties.
- Returns a MIMEMultipart email object with both text and HTML versions.
- """
- subject = "Warracker: Upcoming Warranty Expirations"
-
- # Get email base URL from settings
- conn = None
- email_base_url = 'http://localhost:8080' # Default fallback
- try:
- conn = get_db_connection()
- with conn.cursor() as cur:
- cur.execute("SELECT value FROM site_settings WHERE key = 'email_base_url'")
- result = cur.fetchone()
- if result:
- email_base_url = result[0]
- else:
- logger.warning("email_base_url setting not found, using default.")
- except Exception as e:
- logger.error(f"Error fetching email_base_url from settings: {e}. Using default.")
- finally:
- if conn:
- release_db_connection(conn)
-
- # Ensure base URL doesn't end with a slash
- email_base_url = email_base_url.rstrip('/')
+ logger.error(f"Failed to initialize notification scheduler: {e}")
+ # Continue without notifications - the app can still function
- # Create both plain text and HTML versions of the email body
- text_body = f"Hello {user['first_name']},\\n\\n"
- text_body += "The following warranties are expiring soon:\\n\\n"
+except ImportError:
+ # Fallback for development environment
+ from __init__ import create_app
+ import db_handler
- html_body = f"""\
- <html>
- <head></head>
- <body>
- <p>Hello {user['first_name']},</p>
- <p>The following warranties are expiring soon:</p>
- <table border="1" style="border-collapse: collapse;">
- <thead>
- <tr>
- <th style="padding: 8px; text-align: left;">Product Name</th>
- <th style="padding: 8px; text-align: left;">Expiration Date</th>
- </tr>
- </thead>
- <tbody>
- """
-
- for warranty in warranties:
- text_body += f"- {warranty['product_name']} (expires on {warranty['expiration_date']})\\n"
- html_body += f"""\
- <tr>
- <td style="padding: 8px;">{warranty['product_name']}</td>
- <td style="padding: 8px;">{warranty['expiration_date']}</td>
- </tr>
- """
-
- text_body += "\\nLog in to Warracker to view details:\\n"
- text_body += f"{email_base_url}\\n\\n" # Use configurable base URL
- text_body += "Manage your notification settings:\\n"
- text_body += f"{email_base_url}/settings-new.html\\n" # Use configurable base URL
-
- html_body += f"""\
- </tbody>
- </table>
- <p>Log in to <a href="{email_base_url}">Warracker</a> to view details.</p>
- <p>Manage your notification settings <a href="{email_base_url}/settings-new.html">here</a>.</p>
- </body>
- </html>
- """
-
- # Create a MIMEMultipart object for both text and HTML
- msg = MIMEMultipart('alternative')
- msg['Subject'] = subject
- msg['From'] = os.environ.get('SMTP_USERNAME', '[email protected]')
- msg['To'] = user['email']
-
- part1 = MIMEText(text_body, 'plain')
- part2 = MIMEText(html_body, 'html')
-
- msg.attach(part1)
- msg.attach(part2)
-
- return msg
-
-def send_password_reset_email(recipient_email, reset_link):
- """Sends the password reset email."""
- logger.info(f"Attempting to send password reset email to {recipient_email}")
-
- subject = "Warracker: Password Reset Request"
-
- # Basic text body
- text_body = f"""Hello,
-
-You requested a password reset for your Warracker account.
-
-Click the link below to set a new password:
-{reset_link}
-
-If you did not request this reset, please ignore this email. This link will expire in 24 hours.
-
-Thanks,
-The Warracker Team
-"""
-
- # Basic HTML body
- html_body = f"""<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Warracker Password Reset</title>
-</head>
-<body style="font-family: sans-serif; line-height: 1.6;">
- <h2>Warracker Password Reset Request</h2>
- <p>Hello,</p>
- <p>You requested a password reset for your Warracker account.</p>
- <p>Click the button below to set a new password:</p>
- <p style="margin: 25px 0;">
- <a href="{reset_link}" style="background-color: #007bff; color: white; padding: 12px 20px; text-decoration: none; border-radius: 5px; font-weight: bold;">
- Reset Your Password
- </a>
- </p>
- <p>If the button doesn't work, copy and paste this link into your browser:</p>
- <p><a href="{reset_link}">{reset_link}</a></p>
- <p>If you did not request this reset, please ignore this email. This link will expire in 24 hours.</p>
- <p>Thanks,<br>The Warracker Team</p>
-</body>
-</html>
-"""
-
- # Get SMTP settings from environment variables
- smtp_host = os.environ.get('SMTP_HOST', 'localhost')
- smtp_port = int(os.environ.get('SMTP_PORT', '1025'))
- smtp_username = os.environ.get('SMTP_USERNAME') # No default sender here, should be configured
- smtp_password = os.environ.get('SMTP_PASSWORD')
- # Use SMTP_USERNAME as sender if available, otherwise a default
- sender_email = smtp_username or '[email protected]'
-
- if not smtp_username:
- logger.warning("SMTP_USERNAME environment variable not set. Using default sender address.")
-
- # Create a MIMEMultipart object for both text and HTML
- msg = MIMEMultipart('alternative')
- msg['Subject'] = subject
- msg['From'] = sender_email
- msg['To'] = recipient_email
-
- part1 = MIMEText(text_body, 'plain', 'utf-8')
- part2 = MIMEText(html_body, 'html', 'utf-8')
-
- msg.attach(part1)
- msg.attach(part2)
-
- # Connect to SMTP server and send
- try:
- server = None # Initialize server to None
- if smtp_port == 465:
- logger.info(f"Using SMTP_SSL connection for port 465 to host {smtp_host}")
- server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=10) # Add timeout
- else:
- logger.info(f"Using standard SMTP connection for port {smtp_port} to host {smtp_host}")
- server = smtplib.SMTP(smtp_host, smtp_port, timeout=10) # Add timeout
- # Start TLS for security if not local debug server and not using SSL
- # Check if host suggests a non-local environment
- if smtp_host != 'localhost' and not smtp_host.startswith('127.'):
- logger.info("Attempting to start TLS")
- server.starttls()
-
- # Login if credentials are provided
- if smtp_username and smtp_password:
- logger.info(f"Logging in with username: {smtp_username}")
- server.login(smtp_username, smtp_password)
-
- # Send email
- logger.info(f"Sending email via {smtp_host}:{smtp_port} from {sender_email}")
- server.sendmail(sender_email, recipient_email, msg.as_string())
- logger.info(f"Password reset email successfully sent to {recipient_email}")
-
- except smtplib.SMTPAuthenticationError as e:
- logger.error(f"SMTP Authentication Error sending email to {recipient_email}: {e}")
- # Re-raise a more generic exception or handle appropriately
- raise Exception(f"SMTP Authentication failed for {smtp_username}") from e
- except Exception as e:
- logger.error(f"Failed to send password reset email to {recipient_email}: {e}")
- logger.error(f"SMTP details used - Host: {smtp_host}, Port: {smtp_port}, Username: {smtp_username}, Sender: {sender_email}")
- # Raise an exception to be caught by the calling function
- raise Exception("Failed to send password reset email") from e
- finally:
- if server:
- try:
- server.quit()
- logger.info("SMTP connection closed.")
- except Exception as e:
- logger.error(f"Error quitting SMTP connection: {e}")
-
-# Create a lock for the notification function
-notification_lock = threading.Lock()
-# Track when notifications were last sent to each user
-last_notification_sent = {}
-
-def send_expiration_notifications(manual_trigger=False):
- """
- Main function to send warranty expiration notifications.
- Retrieves expiring warranties, groups them by user, and sends emails.
+ app = create_app(os.getenv('FLASK_CONFIG') or 'default')
+ logger.info("Application created successfully using factory pattern (development mode)")
- Args:
- manual_trigger (bool): Whether this function was triggered manually (vs scheduled)
- If True, it ignores notification frequency/time preferences
- """
- # Use a lock to prevent concurrent executions
- if not notification_lock.acquire(blocking=False):
- logger.info("Notification job already running, skipping this execution")
- return
-
+ # Initialize the notification scheduler with the created app context
try:
- logger.info("Starting expiration notification process")
-
- # If not manually triggered, check if notifications should be sent today based on preferences
- if not manual_trigger:
- conn = None
- try:
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Get today's date and current time in UTC
- utc_now = datetime.utcnow()
-
- # Get user IDs that should receive notifications today
- eligible_users_query = """
- SELECT
- u.id,
- u.email,
- u.first_name,
- up.notification_time,
- up.timezone,
- up.notification_frequency
- FROM users u
- JOIN user_preferences up ON u.id = up.user_id
- WHERE u.is_active = TRUE
- AND up.email_notifications = TRUE
- """
- cur.execute(eligible_users_query)
- eligible_users = cur.fetchall()
-
- if not eligible_users:
- logger.info("No users are eligible for notifications")
- return
-
- # Check if we should send notifications based on time and timezone
- users_to_notify_now = set() # Changed variable name and type to set
- for user in eligible_users:
- user_id, email, first_name, notification_time, timezone, frequency = user
-
- try:
- # Convert UTC time to user's timezone
- user_tz = pytz_timezone(timezone or 'UTC')
- user_local_time = utc_now.replace(tzinfo=pytz.UTC).astimezone(user_tz)
-
- # Check if notification should be sent based on frequency
- should_send = False
-
- if frequency == 'daily':
- should_send = True
- elif frequency == 'weekly' and user_local_time.weekday() == 0: # Monday
- should_send = True
- elif frequency == 'monthly' and user_local_time.day == 1:
- should_send = True
-
- if should_send:
- # Parse notification time
- time_hour, time_minute = map(int, notification_time.split(':'))
-
- # Get current hour and minute in user's timezone
- current_hour = user_local_time.hour
- current_minute = user_local_time.minute
-
- # Calculate minutes difference
- user_minutes = time_hour * 60 + time_minute
- current_minutes = current_hour * 60 + current_minute
-
- # Calculate exact time difference (can be negative if current time is before notification time)
- time_diff = current_minutes - user_minutes
-
- # For notifications, we want to send:
- # 1. If current time is 0-2 minutes after scheduled time (11:27 → send between 11:27-11:29)
- # 2. Or, if the next scheduler run would miss the time (scheduler runs every 5 min)
- # For example, if it's 11:24 and notification is set for 11:27, next run is 11:29 so we should send now
- send_window = time_diff >= 0 and time_diff <= 2 # 0-2 minutes after scheduled time
- next_miss_window = time_diff < 0 and time_diff >= -3 # 1-3 minutes before scheduled time
-
- logger.info(f"Time check for {email}: scheduled={time_hour}:{time_minute:02d}, " +
- f"current={current_hour}:{current_minute:02d}, diff={time_diff} min, " +
- f"send_window={send_window}, next_miss_window={next_miss_window}")
-
- if send_window or next_miss_window:
- # Check if we've already sent a notification to this user recently
- now_timestamp = int(utc_now.timestamp())
- if email in last_notification_sent:
- last_sent = last_notification_sent[email]
- # Only send if it's been more than 10 minutes since the last notification
- # (longer than the 5-minute scheduler interval)
- if now_timestamp - last_sent > 600:
- users_to_notify_now.add(user_id) # Add user_id to the set
- logger.info(f"User {email} eligible for notification at their local time {notification_time} ({timezone})")
- else:
- logger.info(f"Skipping notification for {email} - already sent within the last 10 minutes (last sent: {datetime.fromtimestamp(last_sent).strftime('%Y-%m-%d %H:%M:%S')})")
- else:
- users_to_notify_now.add(user_id) # Add user_id to the set
- logger.info(f"User {email} eligible for notification at their local time {notification_time} ({timezone})")
-
- except Exception as e:
- logger.error(f"Error processing timezone for user {email}: {e}")
- continue
-
- if not users_to_notify_now: # Check the set now
- logger.info("No users are scheduled for notifications at their local time")
- return
-
- logger.info(f"Found {len(users_to_notify_now)} users eligible for notifications now")
- except Exception as e:
- logger.error(f"Error determining notification eligibility: {e}")
- return
- finally:
- if conn:
- release_db_connection(conn)
-
- expiring_warranties = get_expiring_warranties()
- if not expiring_warranties:
- logger.info("No expiring warranties found.")
- return
-
- # Group warranties by user
- users_warranties = {}
- for warranty in expiring_warranties:
- user_id = warranty['user_id'] # Get user_id
- email = warranty['email']
- if email not in users_warranties:
- users_warranties[email] = {
- 'user_id': user_id, # Store user_id
- 'first_name': warranty['first_name'],
- 'warranties': []
- }
- users_warranties[email]['warranties'].append(warranty)
+ import notifications
- # Get SMTP settings from environment variables with fallbacks
- smtp_host = os.environ.get('SMTP_HOST', 'localhost')
- smtp_port = int(os.environ.get('SMTP_PORT', '1025'))
- smtp_username = os.environ.get('SMTP_USERNAME', '[email protected]')
- smtp_password = os.environ.get('SMTP_PASSWORD', '')
-
- # Connect to SMTP server
- try:
- # Use SMTP_SSL for port 465, regular SMTP for other ports
- if smtp_port == 465:
- logger.info(f"Using SMTP_SSL connection for port 465")
- server = smtplib.SMTP_SSL(smtp_host, smtp_port)
- else:
- server = smtplib.SMTP(smtp_host, smtp_port)
- # Start TLS for security if not local debug server and not using SSL
- if smtp_host != 'localhost':
- server.starttls()
-
- # Login if credentials are provided
- if smtp_username and smtp_password:
- logger.info(f"Logging in with username: {smtp_username}")
- server.login(smtp_username, smtp_password)
-
- # Send emails to each user
- utc_now = datetime.utcnow()
- timestamp = int(utc_now.timestamp())
-
- emails_sent = 0
- for email, user_data in users_warranties.items():
- # ---> ADD CHECK HERE <-----
- user_id_to_check = user_data.get('user_id')
- if not manual_trigger and user_id_to_check not in users_to_notify_now:
- logger.debug(f"Skipping email for {email} (user_id: {user_id_to_check}) - not in current notification window.")
- continue # Skip sending if not in the set for scheduled notifications
-
- # For manual triggers, check if we've sent recently
- if manual_trigger and email in last_notification_sent:
- last_sent = last_notification_sent[email]
- # Only allow manual trigger to bypass the time limit if it's been more than 2 minutes
- # This prevents accidental double-clicks by admins
- if timestamp - last_sent < 120:
- logger.info(f"Manual trigger: Skipping notification for {email} - already sent within the last 2 minutes")
- continue
-
- msg = format_expiration_email(
- {'first_name': user_data['first_name'], 'email': email},
- user_data['warranties']
- )
- try:
- server.sendmail(smtp_username, email, msg.as_string())
- # Record timestamp when we sent the notification
- last_notification_sent[email] = timestamp
- emails_sent += 1
- logger.info(f"Expiration notification email sent to {email} for {len(user_data['warranties'])} warranties at {datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')}")
- except Exception as e:
- logger.error(f"Error sending email to {email}: {e}")
-
- logger.info(f"Email notification process completed. Sent {emails_sent} emails out of {len(users_warranties)} eligible users.")
- # Close the server connection
- server.quit()
-
- except Exception as e:
- logger.error(f"Error connecting to SMTP server: {e}")
- logger.error(f"SMTP details - Host: {smtp_host}, Port: {smtp_port}, Username: {smtp_username}")
-
+ with app.app_context():
+ notifications.init_scheduler(app, db_handler.get_db_connection, db_handler.release_db_connection)
+ logger.info("Notification scheduler initialized successfully")
except Exception as e:
- logger.error(f"Error in send_expiration_notifications: {e}")
- finally:
- notification_lock.release()
-
-# Initialize scheduler
-scheduler = BackgroundScheduler(
- job_defaults={
- 'coalesce': True, # Combine multiple executions into one
- 'max_instances': 1, # Only allow one instance of the job to run at a time
- 'misfire_grace_time': 300 # Allow 5 minutes for a misfired job (increased from 60 seconds)
- }
-)
+ logger.error(f"Failed to initialize notification scheduler: {e}")
+ # Continue without notifications - the app can still function
-# Helper to check if this is the main process that should run the scheduler
-def should_run_scheduler():
- # For gunicorn
- if os.environ.get('GUNICORN_WORKER_PROCESS_NAME') == 'worker-0' or \
- (os.environ.get('GUNICORN_WORKER_CLASS') and int(os.environ.get('GUNICORN_WORKER_ID', '0')) == 0):
- logger.info("Starting scheduler in Gunicorn worker 0")
- return True
- # For development server
- elif __name__ == '__main__':
- logger.info("Starting scheduler in development server")
- return True
- # Default case - don't start scheduler
- return False
+except Exception as e:
+ logger.critical(f"CRITICAL: Failed to create application: {e}")
+ raise
-# Only start the scheduler in the main process, not in workers
-if should_run_scheduler():
- # Check for scheduled notifications every 2 minutes for more precise timing
- scheduler.add_job(func=send_expiration_notifications, trigger="interval", minutes=2, id='notification_job')
- scheduler.start()
- logger.info("Email notification scheduler started - checking every 2 minutes")
-
- # Add a shutdown hook
- atexit.register(lambda: scheduler.shutdown())
-
-# Initialize the database when the application starts
-if __name__ != '__main__': # Only for production
- try:
- init_db()
- logger.info("Database initialized during application startup")
- except Exception as e:
- logger.error(f"Database initialization error during startup: {e}")
+# The app object is now ready for Gunicorn/Docker to use
+# For local development, you can run: flask run
+# For production, Gunicorn will use: gunicorn "backend:create_app()"
if __name__ == '__main__':
- try:
- app.run(debug=os.environ.get('FLASK_DEBUG', '0') == '1', host='0.0.0.0')
- except Exception as e:
- logger.error(f"Application startup error: {e}")
-
[email protected]('/api/admin/send-notifications', methods=['POST'])
-@admin_required
-def trigger_notifications():
- """
- Admin-only endpoint to manually trigger warranty expiration notifications.
- Useful for testing and for sending notifications outside the scheduled time.
- """
- try:
- logger.info(f"Manual notification trigger requested by admin user {request.user['id']}")
- send_expiration_notifications(manual_trigger=True)
- return jsonify({'message': 'Notifications triggered successfully'}), 200
- except Exception as e:
- error_msg = f"Error triggering notifications: {str(e)}"
- logger.error(error_msg)
- return jsonify({'message': 'Failed to trigger notifications', 'error': error_msg}), 500
-
[email protected]('/api/timezones', methods=['GET'])
-def get_timezones():
- """Get list of all available timezones"""
- try:
- # Get all timezones from pytz
- all_timezones = pytz.all_timezones
-
- # Group timezones by region
- timezone_groups = {}
- for tz in all_timezones:
- # Split timezone into parts (e.g., 'America/New_York' -> ['America', 'New_York'])
- parts = tz.split('/')
-
- if len(parts) > 1:
- region = parts[0]
- city = '/'.join(parts[1:]).replace('_', ' ')
-
- if region not in timezone_groups:
- timezone_groups[region] = []
-
- timezone_groups[region].append({
- 'value': tz,
- 'label': f"{city} ({tz})"
- })
- else:
- # Handle special cases like 'UTC'
- if 'Other' not in timezone_groups:
- timezone_groups['Other'] = []
- timezone_groups['Other'].append({
- 'value': tz,
- 'label': tz
- })
-
- # Convert to list of groups
- timezone_list = [
- {
- 'region': region,
- 'timezones': sorted(timezones, key=lambda x: x['label'])
- }
- for region, timezones in sorted(timezone_groups.items())
- ]
-
- return jsonify(timezone_list), 200
- except Exception as e:
- logger.error(f"Error getting timezones: {e}")
- return jsonify({'message': 'Failed to get timezones'}), 500
-
[email protected]('/api/debug/warranty/<int:warranty_id>', methods=['GET'])
-@token_required
-def debug_warranty(warranty_id):
- conn = None
- try:
- user_id = request.user['id']
- is_admin = request.user['is_admin']
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # If admin, can see any warranty, otherwise only user's warranties
- if is_admin:
- 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 id = %s
- ''', (warranty_id,))
- else:
- 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 id = %s AND user_id = %s
- ''', (warranty_id, user_id))
-
- warranty = cur.fetchone()
- if not warranty:
- return jsonify({"error": "Warranty not found or you don't have permission to view it"}), 404
-
- columns = [desc[0] for desc in cur.description]
- warranty_dict = dict(zip(columns, warranty))
-
- # Convert date objects to ISO format strings for JSON serialization
- for key, value in warranty_dict.items():
- if isinstance(value, (datetime, date)):
- warranty_dict[key] = value.isoformat()
- # Convert Decimal objects to float for JSON serialization
- elif isinstance(value, Decimal):
- warranty_dict[key] = float(value)
-
- # Get serial numbers for this warranty
- cur.execute('SELECT id, serial_number FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))
- serial_numbers = [{
- 'id': row[0],
- 'serial_number': row[1]
- } for row in cur.fetchall()]
- warranty_dict['serial_numbers'] = serial_numbers
-
- # Get tags for this warranty (same as /api/warranties)
- cur.execute('''
- SELECT t.id, t.name, t.color
- FROM tags t
- JOIN warranty_tags wt ON t.id = wt.tag_id
- WHERE wt.warranty_id = %s
- ORDER BY t.name
- ''', (warranty_id,))
- tags = [{'id': t[0], 'name': t[1], 'color': t[2]} for t in cur.fetchall()]
- warranty_dict['tags'] = tags
-
- return jsonify({
- 'warranty': warranty_dict,
- 'columns': columns
- })
- except Exception as e:
- logger.error(f"Error retrieving warranty debug info: {e}")
- return jsonify({"error": f"Failed to retrieve warranty debug info: {str(e)}"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/debug/file-check', methods=['GET'])
-@token_required
-def debug_file_check():
- if not request.user.get('is_admin', False):
- return jsonify({"error": "Admin access required"}), 403
-
- filepath = request.args.get('path')
- if not filepath:
- return jsonify({"error": "No file path provided"}), 400
-
- # Check if this is just a filename or a path
- if '/' not in filepath:
- filepath = os.path.join('uploads', filepath)
-
- # Prepend /data if it doesn't start with it
- if not filepath.startswith('/data'):
- full_path = os.path.join('/data', filepath)
- else:
- full_path = filepath
-
- result = {
- 'requested_path': filepath,
- 'full_path': full_path,
- 'exists': os.path.exists(full_path),
- 'is_file': os.path.isfile(full_path) if os.path.exists(full_path) else False,
- 'size_bytes': os.path.getsize(full_path) if os.path.exists(full_path) and os.path.isfile(full_path) else None,
- 'last_modified': None
- }
-
- if result['exists'] and result['is_file']:
- try:
- stat_info = os.stat(full_path)
- result['last_modified'] = datetime.fromtimestamp(stat_info.st_mtime).isoformat()
- result['size_human'] = f"{result['size_bytes'] / 1024:.2f} KB" if result['size_bytes'] else None
- except Exception as e:
- result['error'] = str(e)
-
- return jsonify(result)
-
[email protected]('/api/tags', methods=['GET'])
-@token_required
-def get_tags():
- """Get tags based on user role."""
- conn = None
- try:
- user_id = request.user['id']
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Fetch tags created by the currently logged-in user
- cur.execute('SELECT id, name, color, created_at FROM tags WHERE user_id = %s ORDER BY name', (user_id,))
-
- tags = cur.fetchall()
-
- result = []
- for tag in tags:
- result.append({
- 'id': tag[0],
- 'name': tag[1],
- 'color': tag[2],
- 'created_at': tag[3].isoformat() if tag[3] else None
- # Removed is_admin_tag comment
- })
-
- return jsonify(result), 200
- except Exception as e:
- logger.error(f"Error fetching tags: {e}")
- return jsonify({"error": "Failed to fetch tags"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/tags', methods=['POST'])
-@token_required
-def create_tag():
- """Create a new tag owned by the requesting user."""
- conn = None
- try:
- user_id = request.user['id'] # Get user ID
- data = request.json
-
- if not data or 'name' not in data:
- return jsonify({"error": "Tag name is required"}), 400
-
- name = data['name'].strip()
- color = data.get('color', '#808080')
-
- if not name:
- return jsonify({"error": "Tag name cannot be empty"}), 400
-
- # Validate color format (should be a hex color)
- if not re.match(r'^#[0-9A-Fa-f]{6}$', color):
- return jsonify({"error": "Invalid color format. Use hex format (e.g., #FF5733)"}), 400
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if tag with this name already exists FOR THIS USER
- cur.execute('SELECT id FROM tags WHERE name = %s AND user_id = %s', (name, user_id)) # Added user_id check
- existing_tag = cur.fetchone()
-
- if existing_tag:
- # Differentiate error message slightly
- return jsonify({"error": f"A tag with this name already exists for your account"}), 409 # Updated error message
-
- # Create new tag, setting user_id
- cur.execute(
- 'INSERT INTO tags (name, color, user_id) VALUES (%s, %s, %s) RETURNING id', # Added user_id
- (name, color, user_id) # Pass user_id here
- )
- tag_id = cur.fetchone()[0]
- conn.commit()
-
- return jsonify({
- "id": tag_id,
- "name": name,
- "color": color,
- "message": "Tag created successfully"
- }), 201
- except Exception as e:
- logger.error(f"Error creating tag: {e}")
- if conn:
- conn.rollback()
- return jsonify({"error": "Failed to create tag"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/tags/<int:tag_id>', methods=['PUT'])
-@token_required
-def update_tag(tag_id):
- """Update an existing tag, ensuring user can only update their own type of tag."""
- user_id = request.user['id']
- data = request.get_json()
- new_name = data.get('name')
- new_color = data.get('color')
-
- if not new_name:
- return jsonify({"error": "Tag name cannot be empty"}), 400
-
- # Validate color format (basic check)
- if new_color and not re.match(r'^#[0-9a-fA-F]{6}$', new_color):
- return jsonify({"error": "Invalid color format. Use hex (e.g., #RRGGBB)"}), 400
-
- conn = None
- try:
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if tag exists AND belongs to the user
- cur.execute('SELECT id, user_id FROM tags WHERE id = %s', (tag_id,)) # Check user_id
- tag = cur.fetchone()
- if not tag:
- return jsonify({"error": "Tag not found"}), 404
-
- tag_user_id = tag[1]
- if tag_user_id != user_id:
- # Prevent user from updating tag they don't own
- return jsonify({"error": "Permission denied to update this tag"}), 403
-
- # Check if new name conflicts with another tag FOR THIS USER
- cur.execute('SELECT id FROM tags WHERE name = %s AND id != %s AND user_id = %s',
- (new_name, tag_id, user_id)) # Added user_id check
- existing = cur.fetchone()
- if existing:
- # tag_type = "admin" if is_admin_updater else "user" # Removed
- return jsonify({"error": f"Another tag with this name already exists for your account"}), 409 # Updated error message
-
- # Update the tag
- cur.execute('UPDATE tags SET name = %s, color = %s, updated_at = NOW() WHERE id = %s RETURNING id, name, color', \
- (new_name, new_color, tag_id))
- updated_tag = cur.fetchone()
- # conn.commit() and return statement are part of the try block, outside the 'with' block.
- conn.commit()
- return jsonify({"id": updated_tag[0], "name": updated_tag[1], "color": updated_tag[2]}), 200
-
- except Exception as e:
- logger.error(f"Error updating tag {tag_id}: {e}")
- if conn:
- conn.rollback()
- return jsonify({"error": "Failed to update tag"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/tags/<int:tag_id>', methods=['DELETE'])
-@token_required
-def delete_tag_endpoint(tag_id):
- """Delete a tag owned by the requesting user and its associations."""
- user_id = request.user['id'] # Get user ID
- conn = None
- try:
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if tag exists AND belongs to the user
- cur.execute('SELECT id, user_id FROM tags WHERE id = %s', (tag_id,)) # Check user_id
- tag = cur.fetchone()
- if not tag:
- return jsonify({"error": "Tag not found"}), 404
-
- tag_user_id = tag[1]
- # Only allow deletion if the user owns the tag
- if tag_user_id != user_id:
- # Prevent users from deleting tags they don't own
- return jsonify({"error": "Permission denied to delete this tag"}), 403
-
- # Delete associations from warranty_tags first
- cur.execute('DELETE FROM warranty_tags WHERE tag_id = %s', (tag_id,))
-
- # Delete the tag itself
- cur.execute('DELETE FROM tags WHERE id = %s', (tag_id,))
-
- conn.commit()
-
- return jsonify({"message": "Tag deleted successfully"}), 200
-
- except Exception as e:
- logger.error(f"Error deleting tag {tag_id}: {e}")
- if conn:
- conn.rollback()
- return jsonify({"error": "Failed to delete tag"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/warranties/<int:warranty_id>/tags', methods=['GET'])
-@token_required
-def get_warranty_tags(warranty_id):
- # """Get tags associated with a specific warranty, filtered by user role.""" # Docstring update needed
- """Get tags associated with a specific warranty."""
- conn = None
- try:
- user_id = request.user['id']
- # is_admin = request.user.get('is_admin', False) # Removed
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # First check if the warranty exists and user has access to it
- # Simplified check: just check if warranty exists and belongs to the user
- cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s',
- (warranty_id, user_id))
-
- if cur.fetchone() is None:
- # Add admin check here if admins should be able to see tags for any warranty
- is_admin = request.user.get('is_admin', False)
- if is_admin:
- cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
- if cur.fetchone() is None:
- return jsonify({"error": "Warranty not found"}), 404
- else:
- return jsonify({"error": "Warranty not found or you don't have permission to access it"}), 404
-
- # Get tags for this warranty (show all associated tags)
- cur.execute('''
- SELECT t.id, t.name, t.color, t.created_at
- FROM tags t
- JOIN warranty_tags wt ON t.id = wt.tag_id
- WHERE wt.warranty_id = %s -- Removed user_id/is_admin filter
- ORDER BY t.name
- ''', (warranty_id,))
-
- tags = cur.fetchall()
-
- result = []
- for tag in tags:
- result.append({
- 'id': tag[0],
- 'name': tag[1],
- 'color': tag[2],
- 'created_at': tag[3].isoformat() if tag[3] else None
- })
-
- return jsonify(result), 200
- except Exception as e:
- logger.error(f"Error fetching tags for warranty {warranty_id}: {e}")
- return jsonify({"error": "Failed to fetch tags for this warranty"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/warranties/<int:warranty_id>/tags', methods=['POST'])
-@token_required
-def add_tags_to_warranty(warranty_id):
- # """Add tags to a warranty, ensuring tags match user role.""" # Docstring update needed
- """Add tags owned by the user to a warranty they own."""
- conn = None
- try:
- user_id = request.user['id']
- # is_admin = request.user.get('is_admin', False) # Removed
-
- data = request.json
- if not data or 'tag_ids' not in data:
- return jsonify({"error": "tag_ids array is required"}), 400
-
- tag_ids = data['tag_ids']
- if not isinstance(tag_ids, list):
- return jsonify({"error": "tag_ids must be an array of tag IDs"}), 400
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # First check if the warranty exists and user has access to it (owns it)
- cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s',
- (warranty_id, user_id))
-
- if cur.fetchone() is None:
- # Add admin check here if admins should modify any warranty tags
- is_admin = request.user.get('is_admin', False)
- if is_admin:
- cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
- if cur.fetchone() is None:
- return jsonify({"error": "Warranty not found"}), 404
- # Allow admin to proceed even if they don't own it
- else:
- return jsonify({"error": "Warranty not found or you don't have permission to modify it"}), 404
-
- # Validate tags before removing/adding
- valid_tag_ids = []
- if tag_ids: # Only validate if there are tags to add
- # Check if all provided tag IDs exist AND belong to the user
- placeholders = ', '.join(['%s'] * len(tag_ids))
- # Ensure the tags being added are owned by the user adding them
- sql = f'SELECT id, user_id FROM tags WHERE id IN ({placeholders}) AND user_id = %s'
- cur.execute(sql, tag_ids + [user_id]) # Check against current user_id
- found_tags = cur.fetchall()
-
- found_tag_map = {tag[0]: tag[1] for tag in found_tags}
-
- for tag_id in tag_ids:
- if tag_id not in found_tag_map: # This check also implicitly confirms ownership due to the query change
- conn.rollback() # Ensure transaction consistency
- return jsonify({"error": f"Tag with ID {tag_id} not found or not owned by you"}), 404
- # Removed the old is_admin check
- # if found_tag_map[tag_id] != is_admin:
- # conn.rollback()
- # tag_type_required = "admin" if is_admin else "user"
- # return jsonify({"error": f"Tag with ID {tag_id} is not a valid {tag_type_required} tag"}), 403
- valid_tag_ids.append(tag_id) # Keep track of validated tags
-
- # Remove ALL existing tags before adding new ones for simplicity
- # The old logic only removed tags of the same "type", which is no longer relevant
- cur.execute('DELETE FROM warranty_tags WHERE warranty_id = %s', (warranty_id,))
-
- # Add new (validated) tags
- if valid_tag_ids:
- values_placeholder = ', '.join(['(%s, %s)'] * len(valid_tag_ids))
- sql = f'INSERT INTO warranty_tags (warranty_id, tag_id) VALUES {values_placeholder}'
- params = []
- for tag_id in valid_tag_ids:
- params.extend([warranty_id, tag_id])
- cur.execute(sql, params)
-
- conn.commit()
- return jsonify({"message": "Tags updated successfully"}), 200
- except Exception as e:
- logger.error(f"Error updating tags for warranty {warranty_id}: {e}")
- if conn:
- conn.rollback()
- return jsonify({"error": "Failed to update tags"}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
-# --- CSV Import Endpoint ---
-# Updated CSV Headers for duration components
-REQUIRED_CSV_HEADERS = ['ProductName', 'PurchaseDate']
-OPTIONAL_CSV_HEADERS = [
- 'IsLifetime', 'PurchasePrice', 'SerialNumber', 'ProductURL', 'Tags', 'Vendor',
- 'WarrantyDurationYears', 'WarrantyDurationMonths', 'WarrantyDurationDays'
-]
-
[email protected]('/api/warranties/import', methods=['POST'])
-@token_required
-def import_warranties():
- if 'csv_file' not in request.files:
- return jsonify({"error": "No CSV file provided"}), 400
-
- file = request.files['csv_file']
-
- if file.filename == '':
- return jsonify({"error": "No selected file"}), 400
-
- if not file.filename.lower().endswith('.csv'):
- return jsonify({"error": "Invalid file type. Please upload a .csv file"}), 400
-
- user_id = request.user['id']
- conn = None
- imported_count = 0
- failed_rows = []
- row_number = 1 # Start from 1 for header
-
- try:
- # Read the file content
- stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
- csv_reader = csv.DictReader(stream)
-
- # Validate headers
- headers = csv_reader.fieldnames
- # Check required headers first
- missing_required = [h for h in REQUIRED_CSV_HEADERS if h not in headers]
- if missing_required:
- return jsonify({"error": f"Missing required CSV columns: {', '.join(missing_required)}"}), 400
-
- # Check for unknown headers
- known_headers = set(REQUIRED_CSV_HEADERS + OPTIONAL_CSV_HEADERS)
- unknown_headers = [h for h in headers if h not in known_headers]
- if unknown_headers:
- logger.warning(f"CSV file contains unknown headers which will be ignored: {', '.join(unknown_headers)}")
-
- conn = get_db_connection()
- conn.autocommit = False # Start transaction
-
- with conn.cursor() as cur:
- for row in csv_reader:
- row_number += 1 # Increment for each data row (header is row 1)
- errors = []
- processed_row = {}
-
- try:
- # --- Data Extraction and Basic Validation ---
- product_name = row.get('ProductName', '').strip()
- purchase_date_str = row.get('PurchaseDate', '').strip()
- is_lifetime_str = row.get('IsLifetime', 'false').strip().lower()
-
- # 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()
- tags_str = row.get('Tags', '').strip() # Get Tags string
- vendor = row.get('Vendor', '').strip() # Extract Vendor
-
- if not product_name:
- errors.append("ProductName is required.")
- if not purchase_date_str:
- errors.append("PurchaseDate is required.")
-
- # --- Type/Format Validation ---
- try:
- purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d').date()
- except ValueError:
- errors.append("Invalid PurchaseDate format. Use YYYY-MM-DD.")
- purchase_date = None # Set to None to prevent further errors
-
- is_lifetime = is_lifetime_str == 'true'
- expiration_date = None
- warranty_duration_years = 0
- warranty_duration_months = 0
- warranty_duration_days = 0
-
- if not is_lifetime:
- 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:
- try:
- purchase_price = float(purchase_price_str)
- if purchase_price < 0:
- errors.append("PurchasePrice cannot be negative.")
- except ValueError:
- errors.append("PurchasePrice must be a valid number.")
-
- # Calculate expiration date if valid
- 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 []
-
- # --- Process Tags ---
- tag_ids_to_link = []
- if tags_str:
- tag_names = [name.strip() for name in tags_str.split(',') if name.strip()]
- if tag_names:
- # Find existing tag IDs (case-insensitive) for THIS USER
- placeholders = ', '.join(['%s'] * len(tag_names))
- # Include user_id in the lookup
- sql = f"SELECT id, LOWER(name) FROM tags WHERE LOWER(name) IN ({placeholders}) AND user_id = %s"
- cur.execute(sql, [name.lower() for name in tag_names] + [user_id]) # Add user_id
- existing_tags = {name_lower: tag_id for tag_id, name_lower in cur.fetchall()}
-
- processed_tag_ids = []
- tags_to_create = []
-
- for name in tag_names:
- name_lower = name.lower()
- if name_lower in existing_tags:
- processed_tag_ids.append(existing_tags[name_lower])
- else:
- # Avoid queuing the same new tag multiple times within the same row
- if name_lower not in [t['name_lower'] for t in tags_to_create]:
- tags_to_create.append({'name': name, 'name_lower': name_lower})
-
- # Create tags that don't exist for this user
- if tags_to_create:
- default_color = '#808080' # Default color for new tags
- for tag_data in tags_to_create:
- try:
- # Insert new tag with default color, preserving original case for name, AND user_id
- cur.execute(
- "INSERT INTO tags (name, color, user_id) VALUES (%s, %s, %s) RETURNING id",
- (tag_data['name'], default_color, user_id) # Add user_id
- )
- new_tag_id = cur.fetchone()[0]
- processed_tag_ids.append(new_tag_id)
- logger.info(f"Created new tag '{(tag_data['name'])}' with ID {new_tag_id} for user {user_id} during CSV import.")
- except Exception as tag_insert_err:
- # If tag creation fails (e.g., unique constraint conflict due to race condition),
- # ensure the constraint includes user_id
- logger.error(f"Error creating tag '{(tag_data['name'])}' for user {user_id} during import: {tag_insert_err}")
- # Attempt to fetch the ID again in case it was created by another process
- cur.execute("SELECT id FROM tags WHERE LOWER(name) = %s AND user_id = %s", (tag_data['name_lower'], user_id))
- existing_id_result = cur.fetchone()
- if existing_id_result:
- processed_tag_ids.append(existing_id_result[0])
- else:
- # Add error to the row if tag creation failed and wasn't found
- errors.append(f"Failed to create or find tag: {(tag_data['name'])}")
-
- # Consolidate tag IDs to link
- if processed_tag_ids:
- tag_ids_to_link = list(set(processed_tag_ids)) # Ensure unique IDs
-
- # Removed the skipped tags warning as we now create them
- # if skipped_tags:
- # errors.append(f"Skipped non-existent tags: {', '.join(skipped_tags)}.")
-
- # --- Check for Duplicates ---
- if not errors and product_name and purchase_date:
- cur.execute("""
- SELECT id FROM warranties
- WHERE user_id = %s AND product_name = %s AND purchase_date = %s
- """, (user_id, product_name, purchase_date))
- if cur.fetchone(): # Correctly indented
- errors.append("Duplicate warranty found (same product name and purchase date).")
-
- # --- If errors, skip row ---
- if errors:
- failed_rows.append({"row": row_number, "errors": errors})
- continue
-
- # --- Insert into Database ---
- cur.execute("""
- INSERT INTO warranties (
- 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, %s, %s)
- RETURNING id
- """, (
- 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]
-
- # Insert serial numbers
- if serial_numbers:
- for serial_number in serial_numbers:
- cur.execute("""
- INSERT INTO serial_numbers (warranty_id, serial_number)
- VALUES (%s, %s)
- """, (warranty_id, serial_number))
-
- # Link tags
- if tag_ids_to_link:
- for tag_id in tag_ids_to_link:
- cur.execute("""
- INSERT INTO warranty_tags (warranty_id, tag_id)
- VALUES (%s, %s)
- ON CONFLICT (warranty_id, tag_id) DO NOTHING -- Avoid errors if somehow duplicated
- """, (warranty_id, tag_id))
-
- imported_count += 1
-
- except Exception as e:
- logger.error(f"Error processing CSV row {row_number}: {e}")
- failed_rows.append({"row": row_number, "errors": [f"Internal processing error: {str(e)}"]})
- # Don't rollback yet, just record failure
-
- # --- Transaction Commit/Rollback ---
- if failed_rows:
- conn.rollback() # Rollback if any row failed during processing or insertion
- # Reset imported count if we rollback
- final_success_count = 0
- # Modify errors for rows that might have been initially valid but failed due to rollback
- final_failure_count = row_number - 1 # Total data rows processed
- # Add a general error message
- return jsonify({
- "error": "Import failed due to errors in one or more rows. No warranties were imported.",
- "success_count": 0,
- "failure_count": final_failure_count,
- "errors": failed_rows
- }), 400
- else:
- conn.commit() # Commit transaction if all rows were processed successfully
- final_success_count = imported_count
- final_failure_count = len(failed_rows)
-
- return jsonify({
- "message": "CSV processed.",
- "success_count": final_success_count,
- "failure_count": final_failure_count,
- "errors": failed_rows
- }), 200
-
- except Exception as e:
- if conn:
- conn.rollback() # Rollback on general error
- logger.error(f"Error importing CSV: {e}")
- return jsonify({"error": f"Failed to import CSV: {str(e)}"}), 500
- finally:
- if conn:
- conn.autocommit = True # Reset autocommit
- release_db_connection(conn)
-
-# --- End CSV Import Endpoint ---
-
-# --- PATCH START: Currency Symbol Support ---
-# 1. Add a helper function to check if the currency_symbol column exists in user_preferences
-
-def has_currency_symbol_column(cursor):
- cursor.execute("""
- SELECT column_name FROM information_schema.columns
- WHERE table_name = 'user_preferences' AND column_name = 'currency_symbol'
- """)
- return cursor.fetchone() is not None
-
-# 2. Update GET /api/auth/preferences
-# - Add currency_symbol to CREATE TABLE, SELECT, INSERT, and response
-# - Default to '$' if not set
-#
-# 3. Update PUT /api/auth/preferences
-# - Accept currency_symbol from request data and update if provided
-# - Add currency_symbol to CREATE TABLE, SELECT, INSERT, UPDATE, and response
-# - Default to '$' if not set
-# --- PATCH END ---
-
[email protected]('/api/auth/password/reset', methods=['POST'])
-def reset_password():
- conn = None
- try:
- data = request.get_json()
-
- if not data.get('token') or not data.get('password'):
- return jsonify({'message': 'Token and password are required!'}), 400
-
- token = data['token']
- password = data['password']
-
- # Validate password strength
- if not is_valid_password(password):
- return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if token exists and is valid
- cur.execute('SELECT user_id, expires_at FROM password_reset_tokens WHERE token = %s', (token,))
- token_info = cur.fetchone()
-
- if not token_info or token_info[1] < datetime.utcnow():
- return jsonify({'message': 'Invalid or expired token!'}), 400
-
- user_id = token_info[0]
-
- # Hash the new password
- password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
-
- # Update user's password
- cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (password_hash, user_id))
-
- # Delete the used token
- cur.execute('DELETE FROM password_reset_tokens WHERE token = %s', (token,))
-
- conn.commit()
-
- return jsonify({'message': 'Password reset successful!'}), 200
- except Exception as e:
- logger.error(f"Password reset error: {e}")
- if conn:
- conn.rollback()
- return jsonify({'message': 'Password reset failed!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
-def send_email_change_verification_email(recipient_email, verification_link_path_with_token):
- """Sends an email with a link to verify the new email address."""
- try:
- smtp_host = os.environ.get('SMTP_HOST', 'localhost')
- smtp_port = int(os.environ.get('SMTP_PORT', 1025))
- smtp_username = os.environ.get('SMTP_USERNAME')
- smtp_password = os.environ.get('SMTP_PASSWORD')
- smtp_use_tls = os.environ.get('SMTP_USE_TLS', 'true').lower() == 'true'
- smtp_use_ssl = os.environ.get('SMTP_USE_SSL', 'false').lower() == 'true'
- sender_email = os.environ.get('SMTP_SENDER_EMAIL', '[email protected]')
- app_name = "Warracker" # Or get from config
-
- subject = f"Confirm Your New Email Address - {app_name}"
-
- app_base_url = os.environ.get('APP_BASE_URL', request.url_root.rstrip('/'))
- full_verification_link = f"{app_base_url}{verification_link_path_with_token}"
-
- html_content = None
- email_template_path = os.path.join(os.path.dirname(__file__), 'templates', 'email_change_verification.html')
- if os.path.exists(email_template_path):
- with open(email_template_path, 'r') as f:
- html_content = f.read()
- html_content = html_content.replace("{{verification_link}}", full_verification_link)
- html_content = html_content.replace("{{app_name}}", app_name)
- html_content = html_content.replace("{{expiration_hours}}", str(EMAIL_CHANGE_TOKEN_EXPIRATION_HOURS))
- else:
- logger.warning(f"Email template not found: {email_template_path}. Using basic HTML fallback.")
- html_content = f""" <html>
- <body>
- <p>Hello,</p>
- <p>Please click the link below to confirm your new email address for {app_name}:</p>
- <p><a href="{full_verification_link}">Confirm Email Change</a></p>
- <p>If you did not request this change, please ignore this email.</p>
- <p>This link will expire in {EMAIL_CHANGE_TOKEN_EXPIRATION_HOURS} hours.</p>
- <p>Thanks,<br>The {app_name} Team</p>
- </body>
- </html>
- """
-
- msg = MIMEMultipart('alternative')
- msg['Subject'] = subject
- msg['From'] = sender_email
- msg['To'] = recipient_email
- msg.attach(MIMEText(html_content, 'html'))
-
- logger.info(f"Attempting to send email change verification to {recipient_email} via {smtp_host}:{smtp_port}")
-
- if smtp_use_ssl:
- server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=10)
- else:
- server = smtplib.SMTP(smtp_host, smtp_port, timeout=10)
- if smtp_use_tls:
- server.starttls()
-
- if smtp_username and smtp_password:
- server.login(smtp_username, smtp_password)
-
- server.sendmail(sender_email, recipient_email, msg.as_string())
- server.quit()
- logger.info(f"Email change verification sent successfully to {recipient_email}")
- return True
- except smtplib.SMTPAuthenticationError as e:
- logger.error(f"SMTP Authentication Error sending email change verification: {e}")
- except Exception as e:
- logger.error(f"Error sending email change verification: {e}", exc_info=True)
- return False
-
-def generate_secure_token(length=40):
- """Generates a cryptographically secure random string token."""
- return uuid.uuid4().hex + uuid.uuid4().hex[:length-len(uuid.uuid4().hex)]
-
[email protected]('/api/auth/change-email', methods=['POST'])
-@token_required
-def request_email_change():
- current_user_id = request.user['id'] # Get user ID from decorator
- data = request.get_json()
- new_email = data.get('new_email')
- password = data.get('password')
-
- if not new_email or not password:
- return jsonify({'message': 'New email and password are required'}), 400
-
- if not is_valid_email(new_email):
- return jsonify({'message': 'Invalid new email format'}), 400
-
- conn = None
- try:
- conn = get_db_connection()
- cur = conn.cursor()
-
- # Fetch current user's password hash and current email
- cur.execute("SELECT password_hash, email FROM users WHERE id = %s", (current_user_id,))
- user_data = cur.fetchone()
-
- if not user_data:
- return jsonify({'message': 'User not found'}), 404 # Should not happen with @token_required
-
- current_password_hash, current_email = user_data
-
- if not bcrypt.check_password_hash(current_password_hash, password):
- return jsonify({'message': 'Incorrect password'}), 401
-
- if new_email.lower() == current_email.lower():
- return jsonify({'message': 'New email cannot be the same as the current email'}), 400
-
- # Check if the new email is already in use by another user
- cur.execute("SELECT id FROM users WHERE email = %s AND id != %s", (new_email.lower(), current_user_id))
- if cur.fetchone():
- return jsonify({'message': 'This email address is already in use by another account.'}), 409
-
- # Check for an existing, non-expired, non-used request for this user and new email
- cur.execute("""
- SELECT id, token_expires_at FROM email_change_requests
- WHERE user_id = %s AND new_email = %s AND is_used = FALSE AND token_expires_at > NOW()
- """, (current_user_id, new_email.lower()))
- existing_request = cur.fetchone()
-
- if existing_request:
- # Potentially resend email if requested soon after, or just inform user
- return jsonify({'message': 'An email change request for this address is already pending. Please check your inbox.'}), 409
-
- # Invalidate any older, unused tokens for this user to prevent multiple active links
- cur.execute("UPDATE email_change_requests SET is_used = TRUE, token_expires_at = NOW() WHERE user_id = %s AND is_used = FALSE", (current_user_id,))
-
-
- verification_token = generate_secure_token()
- token_expires_at = datetime.utcnow().replace(tzinfo=pytz.utc) + timedelta(hours=EMAIL_CHANGE_TOKEN_EXPIRATION_HOURS)
-
- # Get app base URL from environment or config
- app_base_url = os.environ.get('APP_BASE_URL', request.url_root.rstrip('/'))
- verification_link = f"{app_base_url}{EMAIL_CHANGE_VERIFICATION_ENDPOINT}?token={verification_token}"
-
- cur.execute("""
- INSERT INTO email_change_requests (user_id, new_email, verification_token, token_expires_at)
- VALUES (%s, %s, %s, %s)
- """, (current_user_id, new_email.lower(), verification_token, token_expires_at))
-
- conn.commit()
-
- if send_email_change_verification_email(new_email, verification_link):
- return jsonify({'message': f'Verification email sent to {new_email}. Please check your inbox to confirm.'}), 200
- else:
- # Rollback if email sending failed, to allow user to try again
- # Or, consider if the request should remain, and user can request resend.
- # For now, simple rollback.
- conn.rollback()
- return jsonify({'message': 'Failed to send verification email. Please try again later.'}), 500
-
- except psycopg2.Error as e:
- if conn:
- conn.rollback()
- logger.error(f"Database error during email change request: {e}")
- return jsonify({'message': 'Database error processing your request.'}), 500
- except Exception as e:
- if conn:
- conn.rollback()
- logger.error(f"Error requesting email change: {e}")
- return jsonify({'message': 'An unexpected error occurred.'}), 500
- finally:
- if conn:
- cur.close()
- release_db_connection(conn)
-
[email protected]('/api/auth/verify-email-change', methods=['POST'])
-# This endpoint might not need @token_required if the verification_token itself is the auth mechanism
-# However, if a user is already logged in on the browser where they click the link,
-# it might be good to associate, but the primary auth is the token from email.
-def verify_email_change():
- data = request.get_json()
- verification_token = data.get('token')
-
- if not verification_token:
- return jsonify({'message': 'Verification token is required'}), 400
-
- conn = None
- try:
- conn = get_db_connection()
- cur = conn.cursor()
-
- cur.execute("""
- SELECT id, user_id, new_email, token_expires_at
- FROM email_change_requests
- WHERE verification_token = %s AND is_used = FALSE
- """, (verification_token,))
- request_data = cur.fetchone()
-
- if not request_data:
- return jsonify({'message': 'Invalid or expired verification token.'}), 400
-
- req_id, user_id, new_email, token_expires_at = request_data
-
- # Ensure token_expires_at is timezone-aware for comparison
- if token_expires_at.tzinfo is None:
- token_expires_at = pytz.utc.localize(token_expires_at)
-
- if datetime.utcnow().replace(tzinfo=pytz.utc) > token_expires_at:
- # Mark as used/expired anyway
- cur.execute("UPDATE email_change_requests SET is_used = TRUE WHERE id = %s", (req_id,))
- conn.commit()
- return jsonify({'message': 'Verification token has expired.'}), 400
-
- # Check if the new email has been taken by another user *since the request was made*
- # This is a rare race condition but good to check.
- cur.execute("SELECT id FROM users WHERE email = %s AND id != %s", (new_email, user_id))
- if cur.fetchone():
- cur.execute("UPDATE email_change_requests SET is_used = TRUE WHERE id = %s", (req_id,)) # Invalidate token
- conn.commit()
- return jsonify({'message': 'This email address has recently been claimed by another account. Please try a different email.'}), 409
-
- # Update user's email
- cur.execute("UPDATE users SET email = %s, updated_at = NOW() WHERE id = %s", (new_email, user_id))
-
- # Mark token as used
- cur.execute("UPDATE email_change_requests SET is_used = TRUE WHERE id = %s", (req_id,))
-
- conn.commit()
-
- # Optionally, log the user out of other sessions for security.
- # This would require a session management mechanism (e.g., storing session IDs or using JWT blacklisting).
- # For now, we will skip this, but it's a good addition for production.
-
- # Optionally, send a notification to the OLD email address that the email has been changed.
- # old_email_query = "SELECT email FROM users WHERE id = %s" # This would get new email now
- # To get old email, it should have been selected before the update or passed through.
- # For simplicity, this step is omitted but recommended.
-
- return jsonify({'message': 'Email address updated successfully.'}), 200
-
- except psycopg2.Error as e:
- if conn:
- conn.rollback()
- logger.error(f"Database error during email verification: {e}")
- return jsonify({'message': 'Database error processing your request.'}), 500
- except Exception as e:
- if conn:
- conn.rollback()
- logger.error(f"Error verifying email change: {e}")
- return jsonify({'message': 'An unexpected error occurred.'}), 500
- finally:
- if conn:
- cur.close()
- release_db_connection(conn)
+ # This is only for local development
+ app.run(debug=True, host='0.0.0.0', port=5000)
diff --git a/backend/apprise_handler.py b/backend/apprise_handler.py
new file mode 100644
index 0000000..d95a9fd
--- /dev/null
+++ b/backend/apprise_handler.py
@@ -0,0 +1,583 @@
+"""
+Apprise Notification Handler for Warracker
+Handles sending notifications via Apprise for warranty expirations and other events
+"""
+
+import os
+import logging
+from datetime import datetime, timedelta
+from typing import List, Dict, Optional
+
+# Global flag to track Apprise availability
+APPRISE_AVAILABLE = False
+apprise = None
+
+# Try to import apprise with detailed error handling
+try:
+ import apprise
+ APPRISE_AVAILABLE = True
+ print("✅ Apprise successfully imported")
+except ImportError as e:
+ print(f"❌ Failed to import apprise: {e}")
+ print(" Apprise notifications will be disabled")
+except Exception as e:
+ print(f"❌ Unexpected error importing apprise: {e}")
+ print(" Apprise notifications will be disabled")
+
+# Import database functions with fallback
+DB_FUNCTIONS_IMPORTED = False
+try:
+ # Try backend.db_handler first (Docker environment)
+ from backend.db_handler import get_site_setting, get_expiring_warranties
+ DB_FUNCTIONS_IMPORTED = True
+ print("✅ Database functions imported from backend.db_handler")
+except ImportError:
+ try:
+ # Fallback to db_handler (development environment)
+ from db_handler import get_site_setting, get_expiring_warranties
+ DB_FUNCTIONS_IMPORTED = True
+ print("✅ Database functions imported from db_handler")
+ except ImportError as e:
+ print(f"❌ Failed to import database functions: {e}")
+ print(" Creating dummy functions - expiration notifications will not work")
+ # Create dummy functions to prevent app crash
+ def get_site_setting(key, default=None):
+ return default
+ def get_expiring_warranties(days):
+ print(f"⚠️ Dummy get_expiring_warranties called with days={days} - returning empty list")
+ return []
+
+logger = logging.getLogger(__name__)
+
+class AppriseNotificationHandler:
+ def __init__(self):
+ self.apprise_obj = None
+ self.enabled = False
+ self.notification_urls = []
+ self.expiration_days = [7, 30]
+ self.notification_time = "09:00"
+ self.title_prefix = "[Warracker]"
+
+ # Only initialize if Apprise is available
+ if APPRISE_AVAILABLE:
+ try:
+ self._load_configuration()
+ logger.info("Apprise notification handler initialized successfully")
+ except Exception as e:
+ logger.error(f"Failed to initialize Apprise notification handler: {e}")
+ self.enabled = False
+ else:
+ logger.warning("Apprise not available - notifications disabled")
+
+ def _load_configuration(self):
+ """Load Apprise configuration from database and environment variables"""
+ if not APPRISE_AVAILABLE:
+ logger.warning("Apprise not available, configuration loading skipped")
+ return
+
+ try:
+ # Priority: Environment Variable > Database Setting > Hardcoded Default
+
+ # Load APPRISE_ENABLED with correct precedence
+ env_enabled = os.getenv('APPRISE_ENABLED')
+ if env_enabled is not None:
+ self.enabled = env_enabled.lower() == 'true'
+ else:
+ self.enabled = get_site_setting('apprise_enabled', 'false').lower() == 'true'
+
+ # Load APPRISE_URLS with correct precedence
+ env_urls = os.getenv('APPRISE_URLS')
+ if env_urls is not None:
+ self.notification_urls = [url.strip() for url in env_urls.split(',') if url.strip()]
+ else:
+ urls_str = get_site_setting('apprise_urls', '')
+ if urls_str:
+ self.notification_urls = [url.strip() for url in urls_str.split(',') if url.strip()]
+
+ # Load APPRISE_EXPIRATION_DAYS with correct precedence
+ env_days = os.getenv('APPRISE_EXPIRATION_DAYS')
+ if env_days is not None:
+ try:
+ self.expiration_days = [int(day.strip()) for day in env_days.split(',') if day.strip()]
+ except ValueError:
+ logger.warning(f"Invalid environment expiration days: {env_days}")
+ self.expiration_days = [7, 30]
+ else:
+ expiration_days_str = get_site_setting('apprise_expiration_days', '7,30')
+ if expiration_days_str:
+ try:
+ self.expiration_days = [int(day.strip()) for day in expiration_days_str.split(',') if day.strip()]
+ except ValueError:
+ logger.warning(f"Invalid expiration days format: {expiration_days_str}, using defaults")
+ self.expiration_days = [7, 30]
+
+ # Load APPRISE_NOTIFICATION_TIME with correct precedence
+ env_time = os.getenv('APPRISE_NOTIFICATION_TIME')
+ if env_time is not None:
+ self.notification_time = env_time
+ else:
+ self.notification_time = get_site_setting('apprise_notification_time', '09:00')
+
+ # Load APPRISE_TITLE_PREFIX with correct precedence
+ env_prefix = os.getenv('APPRISE_TITLE_PREFIX')
+ if env_prefix is not None:
+ self.title_prefix = env_prefix
+ else:
+ self.title_prefix = get_site_setting('apprise_title_prefix', '[Warracker]')
+
+ # Initialize Apprise object if enabled
+ if self.enabled and self.notification_urls:
+ self._initialize_apprise()
+
+ logger.info(f"Apprise configuration loaded: enabled={self.enabled}, urls_count={len(self.notification_urls)}")
+
+ except Exception as e:
+ logger.error(f"Error loading Apprise configuration: {e}")
+ self.enabled = False
+
+ def _initialize_apprise(self):
+ """Initialize the Apprise object with configured URLs"""
+ if not APPRISE_AVAILABLE:
+ logger.warning("Apprise not available, initialization skipped")
+ return
+
+ try:
+ self.apprise_obj = apprise.Apprise()
+
+ for url in self.notification_urls:
+ if url:
+ result = self.apprise_obj.add(url)
+ if result:
+ logger.info(f"Successfully added Apprise URL: {url[:20]}...")
+ else:
+ logger.error(f"Failed to add Apprise URL: {url[:20]}...")
+
+ if len(self.apprise_obj) == 0:
+ logger.warning("No valid Apprise URLs configured")
+ self.enabled = False
+
+ except Exception as e:
+ logger.error(f"Error initializing Apprise: {e}")
+ self.enabled = False
+
+ def is_available(self):
+ """Check if Apprise is available and properly configured"""
+ return APPRISE_AVAILABLE and self.enabled and self.apprise_obj is not None
+
+ def get_status(self):
+ """Get detailed status information for debugging"""
+ if not APPRISE_AVAILABLE:
+ return {
+ "available": False,
+ "error": "Apprise library not installed or import failed",
+ "urls_configured": 0,
+ "enabled": False
+ }
+
+ return {
+ "available": True,
+ "enabled": self.enabled,
+ "urls_configured": len(self.notification_urls),
+ "apprise_object_ready": self.apprise_obj is not None,
+ "notification_time": self.notification_time,
+ "expiration_days": self.expiration_days
+ }
+
+ def reload_configuration(self):
+ """Reload configuration from database/environment"""
+ if APPRISE_AVAILABLE:
+ self._load_configuration()
+ else:
+ logger.warning("Cannot reload configuration - Apprise not available")
+
+ def send_test_notification(self, test_url: Optional[str] = None) -> bool:
+ """Send a test notification to verify configuration"""
+ if not APPRISE_AVAILABLE:
+ logger.error("Cannot send test notification - Apprise not available")
+ return False
+
+ try:
+ if test_url:
+ # Use specific test URL
+ test_apprise = apprise.Apprise()
+ if not test_apprise.add(test_url):
+ logger.error(f"Failed to add test URL: {test_url}")
+ return False
+
+ title = f"{self.title_prefix} Test Notification"
+ body = "This is a test notification from Warracker to verify your Apprise configuration is working correctly."
+
+ return test_apprise.notify(title=title, body=body)
+
+ elif self.enabled and self.apprise_obj:
+ # Use configured URLs
+ title = f"{self.title_prefix} Test Notification"
+ body = "This is a test notification from Warracker to verify your Apprise configuration is working correctly."
+
+ return self.apprise_obj.notify(title=title, body=body)
+ else:
+ logger.warning("Apprise not enabled or configured for test notification")
+ return False
+
+ except Exception as e:
+ logger.error(f"Error sending test notification: {e}")
+ return False
+
+ def send_expiration_notifications(self, eligible_user_ids: Optional[List[int]] = None) -> Dict[str, int]:
+ """Send notifications for warranties expiring within configured days
+
+ Args:
+ eligible_user_ids: List of user IDs that should receive Apprise notifications.
+ If None, all users with expiring warranties will be notified.
+ """
+ if not self.is_available():
+ logger.info("Apprise notifications disabled or not configured")
+ return {"sent": 0, "errors": 0}
+
+ if not DB_FUNCTIONS_IMPORTED:
+ logger.error("Database functions not available - cannot retrieve expiring warranties")
+ return {"sent": 0, "errors": 1}
+
+ results = {"sent": 0, "errors": 0}
+
+ try:
+ logger.info(f"Checking expiration notifications for days: {self.expiration_days}")
+ if eligible_user_ids is not None:
+ logger.info(f"Filtering notifications for {len(eligible_user_ids)} eligible users: {eligible_user_ids}")
+
+ for days in self.expiration_days:
+ logger.info(f"Getting warranties expiring in {days} days...")
+ expiring_warranties = get_expiring_warranties(days)
+ logger.info(f"Found {len(expiring_warranties)} warranties expiring in {days} days")
+
+ # Filter warranties by eligible user IDs if provided
+ if eligible_user_ids is not None:
+ original_count = len(expiring_warranties)
+ expiring_warranties = [w for w in expiring_warranties if w.get('user_id') in eligible_user_ids]
+ logger.info(f"Filtered from {original_count} to {len(expiring_warranties)} warranties for eligible users")
+
+ if expiring_warranties:
+ success = self._send_expiration_batch(expiring_warranties, days)
+ if success:
+ results["sent"] += 1
+ logger.info(f"Sent expiration notification for {len(expiring_warranties)} warranties expiring in {days} days")
+ else:
+ results["errors"] += 1
+ logger.error(f"Failed to send expiration notification for {days} days")
+ else:
+ logger.info(f"No eligible warranties expiring in {days} days")
+
+ except Exception as e:
+ logger.error(f"Error in send_expiration_notifications: {e}")
+ results["errors"] += 1
+
+ return results
+
+ def _send_expiration_batch(self, warranties: List[Dict], days: int) -> bool:
+ """Send notification for a batch of warranties expiring in X days"""
+ if not self.is_available():
+ return False
+
+ try:
+ if days == 1:
+ title = f"{self.title_prefix} Warranties Expiring Tomorrow!"
+ urgency = "🚨 URGENT: "
+ elif days <= 7:
+ title = f"{self.title_prefix} Warranties Expiring in {days} Days"
+ urgency = "⚠️ IMPORTANT: "
+ else:
+ title = f"{self.title_prefix} Warranties Expiring in {days} Days"
+ urgency = "📅 REMINDER: "
+
+ # Build notification body
+ body_lines = [
+ f"{urgency}You have {len(warranties)} warranty(ies) expiring in {days} day(s):",
+ ""
+ ]
+
+ for warranty in warranties[:10]: # Limit to first 10 to avoid very long messages
+ expiry_date = warranty.get('expiration_date', 'Unknown')
+ if isinstance(expiry_date, str):
+ try:
+ # Parse and format date if it's a string
+ parsed_date = datetime.fromisoformat(expiry_date.replace('Z', '+00:00'))
+ expiry_date = parsed_date.strftime('%Y-%m-%d')
+ except:
+ pass
+
+ body_lines.append(f"• {warranty.get('product_name', 'Unknown Product')} (expires: {expiry_date})")
+
+ if len(warranties) > 10:
+ body_lines.append(f"... and {len(warranties) - 10} more")
+
+ body_lines.extend([
+ "",
+ "Please review your warranties and take necessary action.",
+ "",
+ "Visit your Warracker dashboard to view details and manage your warranties."
+ ])
+
+ body = "\n".join(body_lines)
+
+ return self.apprise_obj.notify(title=title, body=body)
+
+ except Exception as e:
+ logger.error(f"Error sending expiration batch notification: {e}")
+ return False
+
+ def send_custom_notification(self, title: str, message: str, urls: Optional[List[str]] = None) -> bool:
+ """Send a custom notification"""
+ if not APPRISE_AVAILABLE:
+ logger.error("Cannot send custom notification - Apprise not available")
+ return False
+
+ try:
+ if urls:
+ # Use specific URLs
+ custom_apprise = apprise.Apprise()
+ for url in urls:
+ custom_apprise.add(url)
+
+ if len(custom_apprise) == 0:
+ logger.error("No valid URLs provided for custom notification")
+ return False
+
+ full_title = f"{self.title_prefix} {title}"
+ return custom_apprise.notify(title=full_title, body=message)
+
+ elif self.is_available():
+ # Use configured URLs
+ full_title = f"{self.title_prefix} {title}"
+ return self.apprise_obj.notify(title=full_title, body=message)
+ else:
+ logger.warning("No Apprise configuration available for custom notification")
+ return False
+
+ except Exception as e:
+ logger.error(f"Error sending custom notification: {e}")
+ return False
+
+ def validate_url(self, url: str) -> bool:
+ """Validate if an Apprise URL is properly formatted"""
+ if not APPRISE_AVAILABLE:
+ return False
+
+ try:
+ test_apprise = apprise.Apprise()
+ return test_apprise.add(url)
+ except Exception as e:
+ logger.error(f"Error validating URL: {e}")
+ return False
+
+ def get_supported_services(self) -> List[str]:
+ """Get a list of supported notification services"""
+ if not APPRISE_AVAILABLE:
+ return []
+
+ try:
+ # This is a simplified list - Apprise supports 80+ services
+ return [
+ "Discord", "Slack", "Microsoft Teams", "Telegram", "Signal",
+ "Email (SMTP)", "Gmail", "Outlook", "Yahoo Mail",
+ "Pushover", "Pushbullet", "Gotify", "ntfy",
+ "AWS SNS", "Twilio", "SMS", "WhatsApp",
+ "Matrix", "Rocket.Chat", "Mattermost",
+ "And 60+ more services..."
+ ]
+ except Exception:
+ return []
+
+ def send_global_expiration_notification(self, warranties: List[Dict]) -> bool:
+ """Sends a single, consolidated notification for all expiring warranties."""
+ if not self.is_available() or not warranties:
+ return False
+
+ logger.info(f"Sending GLOBAL Apprise notification for {len(warranties)} expiring items.")
+ try:
+ # Group warranties by expiration days to send separate notifications like manual test
+ warranties_by_days = {}
+ for w in warranties:
+ # Calculate days until expiration
+ expiry_date = w.get('expiration_date')
+ if expiry_date:
+ try:
+ if isinstance(expiry_date, str):
+ parsed_date = datetime.fromisoformat(expiry_date.replace('Z', '+00:00'))
+ else:
+ parsed_date = expiry_date
+
+ days_until_expiry = (parsed_date.date() - datetime.now().date()).days
+
+ if days_until_expiry not in warranties_by_days:
+ warranties_by_days[days_until_expiry] = []
+ warranties_by_days[days_until_expiry].append(w)
+ except Exception as e:
+ logger.warning(f"Error parsing expiration date {expiry_date}: {e}")
+ # Default to 365 days if parsing fails
+ if 365 not in warranties_by_days:
+ warranties_by_days[365] = []
+ warranties_by_days[365].append(w)
+
+ # Send separate notifications for each day group (like manual test)
+ success = True
+ for days, day_warranties in warranties_by_days.items():
+ if not self._send_global_expiration_batch(day_warranties, days):
+ success = False
+
+ return success
+ except Exception as e:
+ logger.error(f"Error sending global expiration notification: {e}")
+ return False
+
+ def _send_global_expiration_batch(self, warranties: List[Dict], days: int) -> bool:
+ """Send global notification for warranties expiring in X days (matches manual test format)"""
+ if not self.is_available():
+ return False
+
+ try:
+ # Use same title format as manual test
+ if days == 1:
+ title = f"{self.title_prefix} Warranties Expiring Tomorrow!"
+ urgency = "🚨 URGENT: "
+ elif days <= 7:
+ title = f"{self.title_prefix} Warranties Expiring in {days} Days"
+ urgency = "⚠️ IMPORTANT: "
+ else:
+ title = f"{self.title_prefix} Warranties Expiring in {days} Days"
+ urgency = "📅 REMINDER: "
+
+ # Use same body format as manual test
+ body_lines = [
+ f"{urgency}You have {len(warranties)} warranty(ies) expiring in {days} day(s):",
+ ""
+ ]
+
+ for warranty in warranties[:10]: # Limit to first 10 to avoid very long messages
+ expiry_date = warranty.get('expiration_date', 'Unknown')
+ if isinstance(expiry_date, str):
+ try:
+ # Parse and format date if it's a string
+ parsed_date = datetime.fromisoformat(expiry_date.replace('Z', '+00:00'))
+ expiry_date = parsed_date.strftime('%Y-%m-%d')
+ except:
+ pass
+
+ body_lines.append(f"• {warranty.get('product_name', 'Unknown Product')} (expires: {expiry_date})")
+
+ if len(warranties) > 10:
+ body_lines.append(f"... and {len(warranties) - 10} more")
+
+ body_lines.extend([
+ "",
+ "Please review your warranties and take necessary action.",
+ "",
+ "Visit your Warracker dashboard to view details and manage your warranties."
+ ])
+
+ body = "\n".join(body_lines)
+
+ return self.apprise_obj.notify(title=title, body=body)
+
+ except Exception as e:
+ logger.error(f"Error sending global expiration batch notification: {e}")
+ return False
+
+ def send_individual_expiration_notification(self, user_id: int, warranties: List[Dict], get_db_connection, release_db_connection) -> bool:
+ """Sends a personalized Apprise notification to a single user."""
+ if not self.is_available() or not warranties:
+ return False
+
+ try:
+ logger.info(f"Sending INDIVIDUAL Apprise notification for {len(warranties)} items to user {user_id}.")
+
+ # Group warranties by expiration days to send separate notifications like manual test
+ warranties_by_days = {}
+ for w in warranties:
+ # Calculate days until expiration
+ expiry_date = w.get('expiration_date')
+ if expiry_date:
+ try:
+ if isinstance(expiry_date, str):
+ parsed_date = datetime.fromisoformat(expiry_date.replace('Z', '+00:00'))
+ else:
+ parsed_date = expiry_date
+
+ days_until_expiry = (parsed_date.date() - datetime.now().date()).days
+
+ if days_until_expiry not in warranties_by_days:
+ warranties_by_days[days_until_expiry] = []
+ warranties_by_days[days_until_expiry].append(w)
+ except Exception as e:
+ logger.warning(f"Error parsing expiration date {expiry_date}: {e}")
+ # Default to 365 days if parsing fails
+ if 365 not in warranties_by_days:
+ warranties_by_days[365] = []
+ warranties_by_days[365].append(w)
+
+ # Send separate notifications for each day group (like manual test)
+ success = True
+ for days, day_warranties in warranties_by_days.items():
+ if not self._send_individual_expiration_batch(day_warranties, days, user_id):
+ success = False
+
+ return success
+
+ except Exception as e:
+ logger.error(f"Error sending individual expiration notification for user {user_id}: {e}")
+ return False
+
+ def _send_individual_expiration_batch(self, warranties: List[Dict], days: int, user_id: int) -> bool:
+ """Send individual notification for warranties expiring in X days (matches manual test format)"""
+ if not self.is_available():
+ return False
+
+ try:
+ # Use same title format as manual test
+ if days == 1:
+ title = f"{self.title_prefix} Warranties Expiring Tomorrow!"
+ urgency = "🚨 URGENT: "
+ elif days <= 7:
+ title = f"{self.title_prefix} Warranties Expiring in {days} Days"
+ urgency = "⚠️ IMPORTANT: "
+ else:
+ title = f"{self.title_prefix} Warranties Expiring in {days} Days"
+ urgency = "📅 REMINDER: "
+
+ # Use same body format as manual test
+ body_lines = [
+ f"{urgency}You have {len(warranties)} warranty(ies) expiring in {days} day(s):",
+ ""
+ ]
+
+ for warranty in warranties[:10]: # Limit to first 10 to avoid very long messages
+ expiry_date = warranty.get('expiration_date', 'Unknown')
+ if isinstance(expiry_date, str):
+ try:
+ # Parse and format date if it's a string
+ parsed_date = datetime.fromisoformat(expiry_date.replace('Z', '+00:00'))
+ expiry_date = parsed_date.strftime('%Y-%m-%d')
+ except:
+ pass
+
+ body_lines.append(f"• {warranty.get('product_name', 'Unknown Product')} (expires: {expiry_date})")
+
+ if len(warranties) > 10:
+ body_lines.append(f"... and {len(warranties) - 10} more")
+
+ body_lines.extend([
+ "",
+ "Please review your warranties and take necessary action.",
+ "",
+ "Visit your Warracker dashboard to view details and manage your warranties."
+ ])
+
+ body = "\n".join(body_lines)
+
+ return self.apprise_obj.notify(title=title, body=body)
+
+ except Exception as e:
+ logger.error(f"Error sending individual expiration batch notification: {e}")
+ return False
+
+# Global instance
+apprise_handler = AppriseNotificationHandler()
\ No newline at end of file
diff --git a/backend/auth_routes.py b/backend/auth_routes.py
new file mode 100644
index 0000000..0c5edaf
--- /dev/null
+++ b/backend/auth_routes.py
@@ -0,0 +1,1203 @@
+# backend/auth_routes.py
+# Updated: 2025-01-24 - Fixed API endpoints for notifications
+from flask import Blueprint, request, jsonify, current_app
+from datetime import datetime, timedelta
+import uuid
+import smtplib
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+import os
+import pytz
+import psycopg2
+
+# Use relative imports for project modules
+try:
+ from . import db_handler, notifications
+ from .auth_utils import generate_token, token_required, is_valid_email, is_valid_password
+ from .localization import SUPPORTED_LANGUAGES
+except ImportError:
+ # Fallback for development environment
+ import db_handler, notifications
+ from auth_utils import generate_token, token_required, is_valid_email, is_valid_password
+ from localization import SUPPORTED_LANGUAGES
+
+# Import bcrypt from extensions since it's initialized with the app
+try:
+ from .extensions import bcrypt
+except ImportError:
+ # Fallback for development environment
+ from extensions import bcrypt
+
+auth_bp = Blueprint('auth_bp', __name__)
+
+@auth_bp.route('/register', methods=['POST'])
+def register():
+ conn = None
+ try:
+ data = request.get_json()
+
+ # Check if registration is enabled
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Check if settings table exists
+ cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'site_settings'
+ )
+ """)
+ table_exists = cur.fetchone()[0]
+
+ registration_enabled = True
+ if table_exists:
+ # Get registration_enabled setting
+ cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")
+ result = cur.fetchone()
+
+ if result:
+ registration_enabled = result[0].lower() == 'true'
+
+ # Check if there are any users (first user can register regardless of setting)
+ cur.execute('SELECT COUNT(*) FROM users')
+ user_count = cur.fetchone()[0]
+
+ # If registration is disabled and this is not the first user, return error
+ if not registration_enabled and user_count > 0:
+ return jsonify({'message': 'Registration is currently disabled!'}), 403
+
+ # Validate required fields
+ required_fields = ['username', 'email', 'password']
+ for field in required_fields:
+ if field not in data or not data[field]:
+ return jsonify({'message': f'{field} is required!'}), 400
+
+ username = data['username']
+ email = data['email']
+ password = data['password']
+ first_name = data.get('first_name', '')
+ last_name = data.get('last_name', '')
+
+ # Validate email format
+ if not is_valid_email(email):
+ return jsonify({'message': 'Invalid email format!'}), 400
+
+ # Validate password strength
+ if not is_valid_password(password):
+ return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
+
+ # Hash the password
+ password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
+
+ with conn.cursor() as cur:
+ # Check if username or email already exists
+ cur.execute('SELECT id FROM users WHERE username = %s OR email = %s', (username, email))
+ existing_user = cur.fetchone()
+
+ if existing_user:
+ return jsonify({'message': 'Username or email already exists!'}), 409
+
+ # Check if this is the first user (who will be an admin and owner)
+ cur.execute('SELECT COUNT(*) FROM users')
+ user_count = cur.fetchone()[0]
+ is_admin = user_count == 0
+ is_owner = user_count == 0 # First user is also the owner
+
+ # Insert new user
+ cur.execute(
+ 'INSERT INTO users (username, email, password_hash, first_name, last_name, is_admin, is_owner) VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING id',
+ (username, email, password_hash, first_name, last_name, is_admin, is_owner)
+ )
+ user_id = cur.fetchone()[0]
+
+ # Log owner creation for transparency
+ if is_owner:
+ current_app.logger.info(f"✅ First user registered: {username} ({email}) - automatically set as admin and owner")
+
+ # Generate token
+ token = generate_token(user_id)
+
+ # Update last login
+ cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
+
+ # Store session info
+ ip_address = request.remote_addr
+ user_agent = request.headers.get('User-Agent', '')
+ session_token = str(uuid.uuid4())
+ expires_at = datetime.utcnow() + current_app.config['JWT_EXPIRATION_DELTA']
+
+ cur.execute(
+ 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent, login_method) VALUES (%s, %s, %s, %s, %s, %s)',
+ (user_id, session_token, expires_at, ip_address, user_agent, 'local')
+ )
+
+ conn.commit()
+
+ return jsonify({
+ 'message': 'User registered successfully!',
+ 'token': token,
+ 'user': {
+ 'id': user_id,
+ 'username': username,
+ 'email': email,
+ 'is_admin': is_admin
+ }
+ }), 201
+ except Exception as e:
+ current_app.logger.error(f"Registration error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Registration failed!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/login', methods=['POST'])
+def login():
+ conn = None
+ try:
+ data = request.get_json()
+
+ # Validate required fields
+ if not data.get('username') or not data.get('password'):
+ return jsonify({'message': 'Username and password are required!'}), 400
+
+ username = data['username']
+ password = data['password']
+
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Check if user exists - include is_admin in the query
+ cur.execute('SELECT id, username, email, password_hash, is_active, is_admin FROM users WHERE username = %s OR email = %s', (username, username))
+ user = cur.fetchone()
+
+ if not user or not bcrypt.check_password_hash(user[3], password):
+ return jsonify({'message': 'Invalid username or password!'}), 401
+
+ if not user[4]: # is_active
+ return jsonify({'message': 'Account is inactive!'}), 401
+
+ user_id = user[0]
+
+ # Generate token
+ token = generate_token(user_id)
+
+ # Update last login
+ cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
+
+ # Store session info
+ ip_address = request.remote_addr
+ user_agent = request.headers.get('User-Agent', '')
+ session_token = str(uuid.uuid4())
+ expires_at = datetime.utcnow() + current_app.config['JWT_EXPIRATION_DELTA']
+
+ cur.execute(
+ 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent, login_method) VALUES (%s, %s, %s, %s, %s, %s)',
+ (user_id, session_token, expires_at, ip_address, user_agent, 'local')
+ )
+
+ conn.commit()
+
+ return jsonify({
+ 'message': 'Login successful!',
+ 'token': token,
+ 'user': {
+ 'id': user_id,
+ 'username': user[1],
+ 'email': user[2],
+ 'is_admin': user[5] # Include is_admin flag
+ }
+ }), 200
+ except Exception as e:
+ current_app.logger.error(f"Login error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Login failed!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/logout', methods=['POST'])
+@token_required
+def logout():
+ conn = None
+ try:
+ auth_header = request.headers.get('Authorization')
+ if auth_header and auth_header.startswith('Bearer '):
+ token = auth_header.split(' ')[1]
+ else:
+ return jsonify({'message': 'No token provided!'}), 400
+
+ user_id = request.user['id']
+
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Invalidate all sessions for this user
+ cur.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
+ conn.commit()
+
+ return jsonify({'message': 'Logout successful!'}), 200
+ except Exception as e:
+ current_app.logger.error(f"Logout error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Logout failed!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/validate-token', methods=['GET'])
+@token_required
+def validate_token():
+ """Validate JWT token and return user info"""
+ try:
+ # If we got here, the token is valid (token_required decorator validated it)
+ return jsonify({
+ 'valid': True,
+ 'user': {
+ 'id': request.user['id'],
+ 'username': request.user['username'],
+ 'email': request.user['email'],
+ 'is_admin': request.user['is_admin'],
+ 'is_owner': request.user.get('is_owner', False)
+ },
+ 'message': 'Token is valid'
+ }), 200
+ except Exception as e:
+ current_app.logger.error(f"Token validation error: {e}")
+ return jsonify({
+ 'valid': False,
+ 'message': 'Invalid token'
+ }), 401
+
+@auth_bp.route('/user', methods=['GET'])
+@token_required
+def get_user():
+ conn = None
+ try:
+ user_id = request.user['id'] # Get user ID from the decorator
+
+ # --- ADD DATABASE QUERY ---
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Try to get user with is_owner column, fall back to without it if column doesn't exist
+ try:
+ cur.execute(
+ 'SELECT id, username, email, first_name, last_name, is_admin, is_owner FROM users WHERE id = %s',
+ (user_id,)
+ )
+ user_data = cur.fetchone()
+ has_owner_column = True
+ columns = ['id', 'username', 'email', 'first_name', 'last_name', 'is_admin', 'is_owner']
+ except Exception as e:
+ # If the query fails (likely because is_owner column doesn't exist), rollback and try again
+ current_app.logger.warning(f"Failed to query with is_owner column in get_user, falling back: {e}")
+ conn.rollback() # Rollback the failed transaction
+ cur.execute(
+ 'SELECT id, username, email, first_name, last_name, is_admin FROM users WHERE id = %s',
+ (user_id,)
+ )
+ user_data = cur.fetchone()
+ has_owner_column = False
+ columns = ['id', 'username', 'email', 'first_name', 'last_name', 'is_admin']
+ # --- END DATABASE QUERY ---
+
+ if not user_data:
+ return jsonify({'message': 'User not found!'}), 404
+
+ # Map database columns to a dictionary
+ user_info = dict(zip(columns, user_data))
+
+ # Add is_owner field if it wasn't included in the query
+ if not has_owner_column:
+ user_info['is_owner'] = False
+
+ # Return the full user information
+ return jsonify(user_info), 200
+
+ except Exception as e:
+ current_app.logger.error(f"Get user error: {e}")
+ return jsonify({'message': 'Failed to retrieve user information!'}), 500
+ finally:
+ # Release the connection back to the pool
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/password/reset-request', methods=['POST'])
+def request_password_reset():
+ conn = None
+ try:
+ data = request.get_json()
+
+ if not data.get('email'):
+ return jsonify({'message': 'Email is required!'}), 400
+
+ email = data['email']
+
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Check if user exists
+ cur.execute('SELECT id FROM users WHERE email = %s', (email,))
+ user = cur.fetchone()
+
+ if not user:
+ # Don't reveal if email exists or not for security
+ return jsonify({'message': 'If your email is registered, you will receive a password reset link.'}), 200
+
+ user_id = user[0]
+
+ # Generate reset token
+ reset_token = str(uuid.uuid4())
+ expires_at = datetime.utcnow() + timedelta(hours=24)
+
+ # Delete any existing tokens for this user
+ cur.execute('DELETE FROM password_reset_tokens WHERE user_id = %s', (user_id,))
+
+ # Insert new token
+ cur.execute(
+ 'INSERT INTO password_reset_tokens (user_id, token, expires_at) VALUES (%s, %s, %s)',
+ (user_id, reset_token, expires_at)
+ )
+
+ conn.commit()
+
+ # Get email base URL from settings with correct precedence
+ # Priority: Environment Variable > Database Setting > Hardcoded Default
+ email_base_url = os.environ.get('APP_BASE_URL')
+ if email_base_url is None:
+ # Fall back to database setting if environment variable is not set
+ email_base_url = 'http://localhost:8080' # Default fallback
+ try:
+ cur.execute("SELECT value FROM site_settings WHERE key = 'email_base_url'")
+ result = cur.fetchone()
+ if result:
+ email_base_url = result[0]
+ else:
+ current_app.logger.warning("email_base_url setting not found for password reset, using default.")
+ except Exception as e:
+ current_app.logger.error(f"Error fetching email_base_url from settings for password reset: {e}. Using default.")
+
+ # Ensure base URL doesn't end with a slash
+ email_base_url = email_base_url.rstrip('/')
+
+ # Construct the full reset link
+ reset_link = f"{email_base_url}/reset-password.html?token={reset_token}" # Use base URL and correct page
+
+ # Send password reset email
+ current_app.logger.info(f"Password reset requested for user {user_id}. Preparing to send email.")
+ try:
+ send_password_reset_email(email, reset_link)
+ current_app.logger.info(f"Password reset email initiated for {email}")
+ except Exception as e:
+ current_app.logger.error(f"Failed to send password reset email to {email}: {e}")
+ # Even if email fails, don't tell the user.
+ # This prevents leaking information about registered emails or email server issues.
+ # The user journey remains the same: "If registered, you'll get an email."
+
+ # Always return success to the user, regardless of email success/failure
+ return jsonify({
+ 'message': 'If your email is registered, you will receive a password reset link.'
+ }), 200
+
+ except Exception as e:
+ current_app.logger.error(f"Password reset request error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Password reset request failed!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/status', methods=['GET'])
+def auth_status():
+ return jsonify({
+ "authentication_required": True,
+ "message": "Authentication is required for most endpoints"
+ })
+
+@auth_bp.route('/profile', methods=['PUT'])
+@token_required
+def update_profile():
+ user_id = request.user['id']
+
+ try:
+ # Get request data
+ data = request.get_json()
+ if not data:
+ return jsonify({'message': 'No input data provided'}), 400
+
+ # Extract fields
+ first_name = data.get('first_name', '').strip()
+ last_name = data.get('last_name', '').strip()
+ new_email = data.get('email', '').strip()
+
+ # Validate input
+ if not first_name or not last_name:
+ return jsonify({'message': 'First name and last name are required'}), 400
+
+ # Get database connection
+ conn = db_handler.get_db_connection()
+ cursor = conn.cursor()
+
+ try:
+ update_fields = ["first_name = %s", "last_name = %s"]
+ update_params = [first_name, last_name]
+
+ # Handle email change
+ if new_email:
+ if not is_valid_email(new_email):
+ conn.rollback()
+ return jsonify({'message': 'Invalid email format!'}), 400
+
+ # Check if the new email is different from the current one
+ cursor.execute("SELECT email FROM users WHERE id = %s", (user_id,))
+ current_email_tuple = cursor.fetchone()
+ if not current_email_tuple:
+ conn.rollback()
+ return jsonify({'message': 'User not found while fetching current email.'}), 404
+ current_email = current_email_tuple[0]
+
+ if new_email.lower() != current_email.lower():
+ # Check if the new email is already in use by another user
+ cursor.execute("SELECT id FROM users WHERE LOWER(email) = LOWER(%s) AND id != %s", (new_email, user_id))
+ if cursor.fetchone():
+ conn.rollback()
+ return jsonify({'message': 'This email address is already in use by another account.'}), 409
+ update_fields.append("email = %s")
+ update_params.append(new_email)
+
+ update_query_string = ", ".join(update_fields)
+ final_query = f"""
+ UPDATE users
+ SET {update_query_string}
+ WHERE id = %s
+ RETURNING id, username, email, first_name, last_name, created_at
+ """
+ cursor.execute(final_query, tuple(update_params + [user_id]))
+
+ # Get updated user data
+ user_data = cursor.fetchone()
+ if not user_data:
+ conn.rollback()
+ return jsonify({'message': 'User not found'}), 404
+
+ conn.commit()
+
+ user = {
+ 'id': user_data[0],
+ 'username': user_data[1],
+ 'email': user_data[2],
+ 'first_name': user_data[3],
+ 'last_name': user_data[4],
+ 'created_at': user_data[5].isoformat() if user_data[5] else None
+ }
+ return jsonify(user), 200
+
+ except Exception as e:
+ conn.rollback()
+ current_app.logger.error(f"Database error in update_profile: {str(e)}")
+ return jsonify({'message': 'Database error occurred'}), 500
+ finally:
+ cursor.close()
+ db_handler.release_db_connection(conn)
+
+ except Exception as e:
+ current_app.logger.error(f"Error in update_profile: {str(e)}")
+ return jsonify({'message': 'An error occurred while updating profile'}), 500
+
+@auth_bp.route('/account', methods=['DELETE'])
+@token_required
+def delete_account():
+ user_id = request.user['id']
+
+ try:
+ # Get database connection
+ conn = db_handler.get_db_connection()
+ cursor = conn.cursor()
+
+ try:
+ # Begin transaction
+ cursor.execute("BEGIN")
+
+ # Check if the current user is the owner
+ try:
+ cursor.execute('SELECT is_owner FROM users WHERE id = %s', (user_id,))
+ user_data = cursor.fetchone()
+ is_owner = user_data[0] if user_data and len(user_data) > 0 else False
+ except Exception as e:
+ # If the query fails (likely because is_owner column doesn't exist), try without it
+ current_app.logger.warning(f"Failed to query with is_owner column in delete_account, falling back: {e}")
+ cursor.execute("ROLLBACK") # Rollback the failed transaction
+ cursor.execute("BEGIN") # Start a new transaction
+ is_owner = False
+
+ if is_owner:
+ cursor.execute("ROLLBACK")
+ return jsonify({'message': 'The application owner cannot delete their own account. Please transfer ownership first.'}), 403
+
+ # Delete user's warranties
+ cursor.execute("DELETE FROM warranties WHERE user_id = %s", (user_id,))
+
+ # Delete user's reset tokens if any
+ cursor.execute("DELETE FROM password_reset_tokens WHERE user_id = %s", (user_id,))
+
+ # Delete user's sessions if any
+ cursor.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
+ sessions_deleted = cursor.rowcount
+ current_app.logger.info(f"Deleted {sessions_deleted} sessions belonging to user {user_id}")
+
+ # Delete user's tags
+ cursor.execute('DELETE FROM tags WHERE user_id = %s', (user_id,))
+ tags_deleted = cursor.rowcount
+ current_app.logger.info(f"Deleted {tags_deleted} tags belonging to user {user_id}")
+
+ # Delete user
+ cursor.execute("DELETE FROM users WHERE id = %s", (user_id,))
+ user_deleted = cursor.rowcount
+ current_app.logger.info(f"Deleted user {user_id}, affected rows: {user_deleted}")
+
+ # Commit transaction
+ cursor.execute("COMMIT")
+
+ return jsonify({'message': 'Account deleted successfully'}), 200
+
+ except Exception as e:
+ cursor.execute("ROLLBACK")
+ current_app.logger.error(f"Database error in delete_account: {str(e)}")
+ return jsonify({'message': 'Database error occurred'}), 500
+ finally:
+ cursor.close()
+ db_handler.release_db_connection(conn)
+
+ except Exception as e:
+ current_app.logger.error(f"Error in delete_account: {str(e)}")
+ return jsonify({'message': 'An error occurred while deleting account'}), 500
+
+# Helper function for checking currency column
+def has_currency_symbol_column(cursor):
+ """Check if user_preferences table has currency_symbol column"""
+ try:
+ cursor.execute("""
+ SELECT column_name
+ FROM information_schema.columns
+ WHERE table_name='user_preferences'
+ AND column_name='currency_symbol'
+ """)
+ return cursor.fetchone() is not None
+ except Exception:
+ return False
+
+# Note: re and pytz are already imported at the top
+
+def is_valid_timezone(tz):
+ """Validate if a timezone string is valid"""
+ try:
+ pytz.timezone(tz)
+ return True
+ except pytz.exceptions.UnknownTimeZoneError:
+ return False
+
+@auth_bp.route('/registration-status', methods=['GET'])
+def check_registration_status():
+ """Check if registration is enabled"""
+ conn = None
+ try:
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Check if settings table exists
+ cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'site_settings'
+ )
+ """)
+ table_exists = cur.fetchone()[0]
+
+ if not table_exists:
+ # If table doesn't exist, registration is enabled by default
+ return jsonify({"enabled": True}), 200
+
+ # Get registration_enabled setting
+ cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")
+ result = cur.fetchone()
+
+ if not result:
+ # If setting doesn't exist, registration is enabled by default
+ return jsonify({"enabled": True}), 200
+
+ registration_enabled = result[0].lower() == 'true'
+
+ return jsonify({"enabled": registration_enabled}), 200
+ except Exception as e:
+ current_app.logger.error(f"Error checking registration status: {e}")
+ return jsonify({"enabled": True}), 200 # Default to enabled on error
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/password/reset', methods=['POST'])
+def reset_password():
+ conn = None
+ try:
+ data = request.get_json()
+
+ if not data.get('token') or not data.get('password'):
+ return jsonify({'message': 'Token and password are required!'}), 400
+
+ token = data['token']
+ password = data['password']
+
+ # Validate password strength
+ if not is_valid_password(password):
+ return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
+
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Check if token exists and is valid
+ cur.execute('SELECT user_id, expires_at FROM password_reset_tokens WHERE token = %s', (token,))
+ token_info = cur.fetchone()
+
+ if not token_info or token_info[1] < datetime.utcnow():
+ return jsonify({'message': 'Invalid or expired token!'}), 400
+
+ user_id = token_info[0]
+
+ # Hash the new password
+ password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
+
+ # Update user's password
+ cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (password_hash, user_id))
+
+ # Delete the used token
+ cur.execute('DELETE FROM password_reset_tokens WHERE token = %s', (token,))
+
+ conn.commit()
+
+ return jsonify({'message': 'Password reset successful!'}), 200
+ except Exception as e:
+ current_app.logger.error(f"Password reset error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Password reset failed!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/password/change', methods=['POST'])
+@token_required
+def change_password():
+ """Allow logged-in users to change their password"""
+ conn = None
+ try:
+ data = request.get_json()
+
+ if not data.get('current_password') or not data.get('new_password'):
+ return jsonify({'message': 'Current password and new password are required!'}), 400
+
+ current_password = data['current_password']
+ new_password = data['new_password']
+ user_id = request.user['id'] # Get user ID from the token_required decorator
+
+ # Validate new password strength
+ if not is_valid_password(new_password):
+ return jsonify({'message': 'New password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
+
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Get the user's current password hash
+ cur.execute('SELECT password_hash FROM users WHERE id = %s', (user_id,))
+ user_data = cur.fetchone()
+
+ if not user_data:
+ return jsonify({'message': 'User not found!'}), 404
+
+ current_password_hash = user_data[0]
+
+ # Verify the current password
+ if not bcrypt.check_password_hash(current_password_hash, current_password):
+ return jsonify({'message': 'Incorrect current password!'}), 401
+
+ # Hash the new password
+ new_password_hash = bcrypt.generate_password_hash(new_password).decode('utf-8')
+
+ # Update the password in the database
+ cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (new_password_hash, user_id))
+
+ conn.commit()
+
+ return jsonify({'message': 'Password changed successfully!'}), 200
+
+ except Exception as e:
+ current_app.logger.error(f"Password change error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Failed to change password!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+# Helper functions for email functionality
+def send_password_reset_email(recipient_email, reset_link):
+ """Sends the password reset email."""
+ current_app.logger.info(f"Attempting to send password reset email to {recipient_email}")
+
+ try:
+ smtp_host = os.environ.get('SMTP_HOST', 'localhost')
+ smtp_port = int(os.environ.get('SMTP_PORT', 1025))
+ smtp_username = os.environ.get('SMTP_USERNAME')
+ smtp_password = os.environ.get('SMTP_PASSWORD')
+ smtp_use_tls = os.environ.get('SMTP_USE_TLS', 'true').lower() == 'true'
+ smtp_use_ssl = os.environ.get('SMTP_USE_SSL', 'false').lower() == 'true'
+ sender_email = os.environ.get('SMTP_SENDER_EMAIL', '[email protected]')
+ app_name = "Warracker"
+
+ subject = f"Password Reset - {app_name}"
+
+ app_base_url = os.environ.get('APP_BASE_URL', request.url_root.rstrip('/'))
+
+ html_content = f"""
+ <html>
+ <body>
+ <p>Hello,</p>
+ <p>You have requested a password reset for your {app_name} account.</p>
+ <p>Please click the link below to reset your password:</p>
+ <p><a href="{reset_link}">Reset Password</a></p>
+ <p>If you did not request this password reset, please ignore this email.</p>
+ <p>This link will expire in 24 hours.</p>
+ <p>Thanks,<br>The {app_name} Team</p>
+ </body>
+ </html>
+ """
+
+ msg = MIMEMultipart('alternative')
+ msg['Subject'] = subject
+ msg['From'] = sender_email
+ msg['To'] = recipient_email
+ msg.attach(MIMEText(html_content, 'html'))
+
+ current_app.logger.info(f"Attempting to send password reset email to {recipient_email} via {smtp_host}:{smtp_port}")
+
+ server = None
+ current_app.logger.info(f"Attempting SMTP connection to {smtp_host}:{smtp_port}")
+ if smtp_port == 465:
+ current_app.logger.info("Using SMTP_SSL for port 465.")
+ server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=10)
+ else:
+ current_app.logger.info(f"Using SMTP for port {smtp_port}.")
+ server = smtplib.SMTP(smtp_host, smtp_port, timeout=10)
+ if smtp_use_tls:
+ current_app.logger.info("Attempting to start TLS (server.starttls()).")
+ server.starttls()
+ current_app.logger.info("STARTTLS successful.")
+
+ if smtp_username and smtp_password:
+ current_app.logger.info(f"Logging in with username: {smtp_username}")
+ server.login(smtp_username, smtp_password)
+ current_app.logger.info("SMTP login successful.")
+
+ server.sendmail(sender_email, recipient_email, msg.as_string())
+ server.quit()
+ current_app.logger.info(f"Password reset email sent successfully to {recipient_email}")
+ return True
+ except Exception as e:
+ current_app.logger.error(f"Error sending password reset email: {e}")
+ return False
+
+@auth_bp.route('/preferences', methods=['GET'])
+@token_required
+def get_preferences():
+ """Get user preferences with default values"""
+ user_id = request.user['id']
+ try:
+ conn = db_handler.get_db_connection()
+ cursor = conn.cursor()
+
+ try:
+ # Check if user_preferences table exists
+ cursor.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'user_preferences'
+ )
+ """)
+ table_exists = cursor.fetchone()[0]
+
+ if not table_exists:
+ # Return default preferences if table doesn't exist
+ default_preferences = {
+ 'email_notifications': True,
+ 'default_view': 'grid',
+ 'theme': 'light',
+ 'expiring_soon_days': 30,
+ 'notification_frequency': 'daily',
+ 'notification_time': '09:00',
+ 'timezone': 'UTC',
+ 'notification_channel': 'email',
+ 'currency_symbol': '$',
+ 'date_format': 'MDY',
+ 'paperless_view_in_app': False
+ }
+ return jsonify(default_preferences), 200
+
+ # Get user preferences with language preference from users table
+ cursor.execute("""
+ SELECT up.email_notifications, up.default_view, up.theme, up.expiring_soon_days,
+ up.notification_frequency, up.notification_time, up.timezone, up.currency_symbol, up.date_format, up.notification_channel, up.apprise_notification_time, up.apprise_notification_frequency, up.apprise_timezone, up.currency_position, up.paperless_view_in_app,
+ u.preferred_language
+ FROM user_preferences up
+ JOIN users u ON up.user_id = u.id
+ WHERE up.user_id = %s
+ """, (user_id,))
+
+ preferences_data = cursor.fetchone()
+
+ if preferences_data:
+ preferences = {
+ 'email_notifications': preferences_data[0],
+ 'default_view': preferences_data[1],
+ 'theme': preferences_data[2],
+ 'expiring_soon_days': preferences_data[3],
+ 'notification_frequency': preferences_data[4],
+ 'notification_time': preferences_data[5],
+ 'timezone': preferences_data[6],
+ 'currency_symbol': preferences_data[7] if preferences_data[7] else '$',
+ 'date_format': preferences_data[8] if preferences_data[8] else 'MDY',
+ 'notification_channel': preferences_data[9] if preferences_data[9] else 'email',
+ 'apprise_notification_time': preferences_data[10] if preferences_data[10] else '09:00',
+ 'apprise_notification_frequency': preferences_data[11] if preferences_data[11] else 'daily',
+ 'apprise_timezone': preferences_data[12] if preferences_data[12] else 'UTC',
+ 'currency_position': preferences_data[13] if preferences_data[13] else 'left',
+ 'paperless_view_in_app': preferences_data[14] if len(preferences_data) > 14 and preferences_data[14] is not None else False,
+ 'preferred_language': preferences_data[15] if len(preferences_data) > 15 and preferences_data[15] else 'en'
+ }
+ else:
+ # Create default preferences for user, but get language from users table
+ cursor.execute("SELECT preferred_language FROM users WHERE id = %s", (user_id,))
+ user_lang = cursor.fetchone()
+ preferred_language = user_lang[0] if user_lang and user_lang[0] else 'en'
+
+ default_preferences = {
+ 'email_notifications': True,
+ 'default_view': 'grid',
+ 'theme': 'light',
+ 'expiring_soon_days': 30,
+ 'notification_frequency': 'daily',
+ 'notification_time': '09:00',
+ 'timezone': 'UTC',
+ 'notification_channel': 'email',
+ 'currency_symbol': '$',
+ 'date_format': 'MDY',
+ 'currency_position': 'left',
+ 'paperless_view_in_app': False,
+ 'preferred_language': preferred_language
+ }
+ preferences = default_preferences
+
+ return jsonify(preferences), 200
+
+ except Exception as e:
+ current_app.logger.error(f"Database error in get_preferences: {str(e)}")
+ default_preferences = {
+ 'email_notifications': True,
+ 'default_view': 'grid',
+ 'theme': 'light',
+ 'expiring_soon_days': 30,
+ 'notification_frequency': 'daily',
+ 'notification_time': '09:00',
+ 'timezone': 'UTC',
+ 'notification_channel': 'email',
+ 'currency_symbol': '$',
+ 'date_format': 'MDY',
+ 'currency_position': 'left',
+ 'paperless_view_in_app': False,
+ 'preferred_language': 'en'
+ }
+ return jsonify(default_preferences), 200
+ finally:
+ cursor.close()
+ db_handler.release_db_connection(conn)
+
+ except Exception as e:
+ current_app.logger.error(f"Error in get_preferences: {str(e)}")
+ default_preferences = {
+ 'email_notifications': True,
+ 'default_view': 'grid',
+ 'theme': 'light',
+ 'expiring_soon_days': 30,
+ 'notification_frequency': 'daily',
+ 'notification_time': '09:00',
+ 'timezone': 'UTC',
+ 'notification_channel': 'email',
+ 'currency_symbol': '$',
+ 'date_format': 'MDY',
+ 'currency_position': 'left',
+ 'paperless_view_in_app': False,
+ 'preferred_language': 'en'
+ }
+ return jsonify(default_preferences), 200
+
+@auth_bp.route('/preferences', methods=['PUT'])
+@token_required
+def update_preferences():
+ """Update user preferences"""
+ user_id = request.user['id']
+ try:
+ data = request.get_json()
+ if not data:
+ return jsonify({'message': 'No input data provided'}), 400
+
+ # Basic validation
+ default_view = data.get('default_view')
+ theme = data.get('theme')
+ expiring_soon_days = data.get('expiring_soon_days')
+ currency_symbol = data.get('currency_symbol')
+ currency_position = data.get('currency_position')
+ date_format = data.get('date_format')
+ notification_channel = data.get('notification_channel')
+ notification_frequency = data.get('notification_frequency')
+ notification_time = data.get('notification_time')
+ apprise_notification_time = data.get('apprise_notification_time')
+ apprise_notification_frequency = data.get('apprise_notification_frequency')
+ timezone = data.get('timezone')
+ apprise_timezone = data.get('apprise_timezone')
+ paperless_view_in_app = data.get('paperless_view_in_app')
+ preferred_language = data.get('preferred_language')
+
+ if default_view and default_view not in ['grid', 'list', 'table']:
+ return jsonify({'message': 'Invalid default view'}), 400
+ if theme and theme not in ['light', 'dark']:
+ return jsonify({'message': 'Invalid theme'}), 400
+ if expiring_soon_days is not None:
+ try:
+ expiring_soon_days = int(expiring_soon_days)
+ if expiring_soon_days < 1 or expiring_soon_days > 365:
+ return jsonify({'message': 'Expiring soon days must be between 1 and 365'}), 400
+ except ValueError:
+ return jsonify({'message': 'Expiring soon days must be a valid number'}), 400
+ if currency_symbol and len(currency_symbol) > 8:
+ return jsonify({'message': 'Currency symbol must be 8 characters or less'}), 400
+ if currency_position and currency_position not in ['left', 'right']:
+ return jsonify({'message': 'Invalid currency position'}), 400
+ if date_format and date_format not in ['MDY', 'DMY', 'YMD', 'MDY_WORDS', 'DMY_WORDS', 'YMD_WORDS']:
+ return jsonify({'message': 'Invalid date format'}), 400
+ if notification_channel and notification_channel not in ['none', 'email', 'apprise', 'both']:
+ return jsonify({'message': 'Invalid notification channel'}), 400
+ if paperless_view_in_app is not None and not isinstance(paperless_view_in_app, bool):
+ return jsonify({'message': 'paperless_view_in_app must be a boolean'}), 400
+ if preferred_language and preferred_language not in SUPPORTED_LANGUAGES:
+ return jsonify({'message': 'Invalid language preference'}), 400
+
+ conn = db_handler.get_db_connection()
+ cursor = conn.cursor()
+
+ try:
+ # Check if preferences exist
+ cursor.execute("SELECT 1 FROM user_preferences WHERE user_id = %s", (user_id,))
+ preferences_exist = cursor.fetchone() is not None
+
+ if preferences_exist:
+ # Update existing preferences
+ update_fields = []
+ update_values = []
+
+ if default_view:
+ update_fields.append("default_view = %s")
+ update_values.append(default_view)
+ if theme:
+ update_fields.append("theme = %s")
+ update_values.append(theme)
+ if expiring_soon_days is not None:
+ update_fields.append("expiring_soon_days = %s")
+ update_values.append(expiring_soon_days)
+ if currency_symbol is not None:
+ update_fields.append("currency_symbol = %s")
+ update_values.append(currency_symbol)
+ if currency_position is not None:
+ update_fields.append("currency_position = %s")
+ update_values.append(currency_position)
+ if date_format is not None:
+ update_fields.append("date_format = %s")
+ update_values.append(date_format)
+ if notification_channel is not None:
+ update_fields.append("notification_channel = %s")
+ update_values.append(notification_channel)
+ if notification_frequency is not None:
+ update_fields.append("notification_frequency = %s")
+ update_values.append(notification_frequency)
+ if notification_time is not None:
+ update_fields.append("notification_time = %s")
+ update_values.append(notification_time)
+ if apprise_notification_time is not None:
+ update_fields.append("apprise_notification_time = %s")
+ update_values.append(apprise_notification_time)
+ if apprise_notification_frequency is not None:
+ update_fields.append("apprise_notification_frequency = %s")
+ update_values.append(apprise_notification_frequency)
+ if timezone is not None:
+ update_fields.append("timezone = %s")
+ update_values.append(timezone)
+ if apprise_timezone is not None:
+ update_fields.append("apprise_timezone = %s")
+ update_values.append(apprise_timezone)
+ if paperless_view_in_app is not None:
+ update_fields.append("paperless_view_in_app = %s")
+ update_values.append(paperless_view_in_app)
+
+ if update_fields:
+ update_query = f"UPDATE user_preferences SET {', '.join(update_fields)} WHERE user_id = %s"
+ cursor.execute(update_query, update_values + [user_id])
+
+ # Update language preference in users table separately
+ if preferred_language is not None:
+ cursor.execute("UPDATE users SET preferred_language = %s WHERE id = %s", (preferred_language, user_id))
+ else:
+ # Insert new preferences
+ cursor.execute("""
+ INSERT INTO user_preferences (user_id, default_view, theme, expiring_soon_days, currency_symbol, currency_position, date_format, notification_channel, notification_frequency, notification_time, apprise_notification_time, apprise_notification_frequency, timezone, apprise_timezone, paperless_view_in_app)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
+ """, (user_id, default_view or 'grid', theme or 'light', expiring_soon_days or 30, currency_symbol or '$', currency_position or 'left', date_format or 'MDY', notification_channel or 'email', notification_frequency or 'daily', notification_time or '09:00', apprise_notification_time or '09:00', apprise_notification_frequency or 'daily', timezone or 'UTC', apprise_timezone or 'UTC', paperless_view_in_app if paperless_view_in_app is not None else False))
+
+ # Update language preference in users table separately
+ if preferred_language is not None:
+ cursor.execute("UPDATE users SET preferred_language = %s WHERE id = %s", (preferred_language, user_id))
+
+ conn.commit()
+
+ # Return updated preferences with language preference
+ cursor.execute("""
+ SELECT up.email_notifications, up.default_view, up.theme, up.expiring_soon_days,
+ up.notification_frequency, up.notification_time, up.timezone, up.currency_symbol, up.date_format, up.notification_channel, up.apprise_notification_time, up.apprise_notification_frequency, up.apprise_timezone, up.currency_position, up.paperless_view_in_app,
+ u.preferred_language
+ FROM user_preferences up
+ JOIN users u ON up.user_id = u.id
+ WHERE up.user_id = %s
+ """, (user_id,))
+
+ preferences_data = cursor.fetchone()
+
+ if preferences_data:
+ preferences = {
+ 'email_notifications': preferences_data[0],
+ 'default_view': preferences_data[1],
+ 'theme': preferences_data[2],
+ 'expiring_soon_days': preferences_data[3],
+ 'notification_frequency': preferences_data[4],
+ 'notification_time': preferences_data[5],
+ 'timezone': preferences_data[6],
+ 'currency_symbol': preferences_data[7] if preferences_data[7] else '$',
+ 'date_format': preferences_data[8] if preferences_data[8] else 'MDY',
+ 'notification_channel': preferences_data[9] if preferences_data[9] else 'email',
+ 'apprise_notification_time': preferences_data[10] if preferences_data[10] else '09:00',
+ 'apprise_notification_frequency': preferences_data[11] if preferences_data[11] else 'daily',
+ 'apprise_timezone': preferences_data[12] if preferences_data[12] else 'UTC',
+ 'currency_position': preferences_data[13] if preferences_data[13] else 'left',
+ 'paperless_view_in_app': preferences_data[14] if len(preferences_data) > 14 and preferences_data[14] is not None else False,
+ 'preferred_language': preferences_data[15] if len(preferences_data) > 15 and preferences_data[15] else 'en'
+ }
+ else:
+ preferences = {
+ 'email_notifications': True,
+ 'default_view': default_view or 'grid',
+ 'theme': theme or 'light',
+ 'expiring_soon_days': expiring_soon_days or 30,
+ 'notification_frequency': notification_frequency or 'daily',
+ 'notification_time': notification_time or '09:00',
+ 'timezone': timezone or 'UTC',
+ 'notification_channel': notification_channel or 'email',
+ 'currency_symbol': currency_symbol or '$',
+ 'date_format': date_format or 'MDY',
+ 'currency_position': currency_position or 'left',
+ 'apprise_notification_time': apprise_notification_time or '09:00',
+ 'apprise_notification_frequency': apprise_notification_frequency or 'daily',
+ 'apprise_timezone': apprise_timezone or 'UTC',
+ 'paperless_view_in_app': paperless_view_in_app if paperless_view_in_app is not None else False,
+ 'preferred_language': preferred_language or 'en'
+ }
+
+ return jsonify(preferences), 200
+
+ except Exception as e:
+ conn.rollback()
+ current_app.logger.error(f"Database error in update_preferences: {str(e)}")
+ return jsonify({'message': 'Database error occurred'}), 500
+ finally:
+ cursor.close()
+ db_handler.release_db_connection(conn)
+
+ except Exception as e:
+ current_app.logger.error(f"Error in update_preferences: {str(e)}")
+ return jsonify({'message': 'An error occurred while updating preferences'}), 500
+
+# Additional helper functions for email changes
+def generate_secure_token(length=40):
+ """Generates a cryptographically secure random string token."""
+ return uuid.uuid4().hex + uuid.uuid4().hex[:length-len(uuid.uuid4().hex)]
+
+@auth_bp.route('/change-email', methods=['POST'])
+@token_required
+def request_email_change():
+ """Request email change with verification"""
+ current_user_id = request.user['id']
+ data = request.get_json()
+ new_email = data.get('new_email')
+ password = data.get('password')
+
+ if not new_email or not password:
+ return jsonify({'message': 'New email and password are required'}), 400
+
+ if not is_valid_email(new_email):
+ return jsonify({'message': 'Invalid new email format'}), 400
+
+ conn = None
+ try:
+ conn = db_handler.get_db_connection()
+ cur = conn.cursor()
+
+ # Fetch current user's password hash and current email
+ cur.execute("SELECT password_hash, email FROM users WHERE id = %s", (current_user_id,))
+ user_data = cur.fetchone()
+
+ if not user_data:
+ return jsonify({'message': 'User not found'}), 404
+
+ current_password_hash, current_email = user_data
+
+ if not bcrypt.check_password_hash(current_password_hash, password):
+ return jsonify({'message': 'Incorrect password'}), 401
+
+ if new_email.lower() == current_email.lower():
+ return jsonify({'message': 'New email cannot be the same as the current email'}), 400
+
+ # Check if the new email is already in use by another user
+ cur.execute("SELECT id FROM users WHERE email = %s AND id != %s", (new_email.lower(), current_user_id))
+ if cur.fetchone():
+ return jsonify({'message': 'This email address is already in use by another account.'}), 409
+
+ # For simplicity, just update the email directly without verification
+ # In a production system, you would implement email verification here
+ cur.execute("UPDATE users SET email = %s WHERE id = %s", (new_email, current_user_id))
+ conn.commit()
+
+ return jsonify({'message': 'Email address updated successfully.'}), 200
+
+ except Exception as e:
+ if conn:
+ conn.rollback()
+ current_app.logger.error(f"Error changing email: {e}")
+ return jsonify({'message': 'An unexpected error occurred.'}), 500
+ finally:
+ if conn:
+ cur.close()
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/verify-email-change', methods=['POST'])
+def verify_email_change():
+ """Verify email change (simplified version)"""
+ data = request.get_json()
+ verification_token = data.get('token')
+
+ if not verification_token:
+ return jsonify({'message': 'Verification token is required'}), 400
+
+ # For simplicity, return a basic response
+ # In a full implementation, this would verify the token and update the email
+ return jsonify({'message': 'Email verification functionality not fully implemented in this simplified version'}), 501
diff --git a/backend/auth_utils.py b/backend/auth_utils.py
new file mode 100644
index 0000000..02a75e1
--- /dev/null
+++ b/backend/auth_utils.py
@@ -0,0 +1,134 @@
+# backend/auth_utils.py
+import jwt
+from datetime import datetime, timedelta
+from flask import current_app, request, jsonify
+from functools import wraps
+import re
+
+# IMPORTANT: We need to import db_handler here for the decorators
+try:
+ from . import db_handler
+except ImportError:
+ import db_handler
+
+def generate_token(user_id):
+ """Generate a JWT token for the user"""
+ payload = {
+ 'exp': datetime.utcnow() + current_app.config['JWT_EXPIRATION_DELTA'],
+ 'iat': datetime.utcnow(),
+ 'sub': user_id
+ }
+ return jwt.encode(payload, current_app.config['SECRET_KEY'], algorithm='HS256')
+
+def decode_token(token):
+ """Decode a JWT token and return the user_id"""
+ try:
+ payload = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
+ return payload['sub']
+ except jwt.ExpiredSignatureError:
+ return None # Token has expired
+ except jwt.InvalidTokenError:
+ return None # Invalid token
+
+def token_required(f):
+ """Decorator to protect routes that require authentication"""
+ @wraps(f)
+ def decorated(*args, **kwargs):
+ token = None
+
+ # Get token from Authorization header
+ auth_header = request.headers.get('Authorization')
+ if auth_header and auth_header.startswith('Bearer '):
+ token = auth_header.split(' ')[1]
+
+ # If no token in header, check form data for POST requests
+ if not token and request.method == 'POST':
+ token = request.form.get('auth_token') # Check form data
+
+ # If still no token, check URL query parameters
+ if not token:
+ token = request.args.get('token') # Check query parameters
+
+ # If no token is provided
+ if not token:
+ current_app.logger.warning(f"Authentication attempt without token: {request.path}")
+ return jsonify({'message': 'Authentication token is missing!'}), 401
+
+ # Decode the token
+ user_id = decode_token(token)
+ if not user_id:
+ current_app.logger.warning(f"Invalid token used for: {request.path}")
+ return jsonify({'message': 'Invalid or expired token!'}), 401
+
+ # Check if user exists
+ conn = None
+ try:
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Try to get user with is_owner column, fall back to without it if column doesn't exist
+ try:
+ cur.execute('SELECT id, username, email, is_admin, is_owner FROM users WHERE id = %s AND is_active = TRUE', (user_id,))
+ user = cur.fetchone()
+ has_owner_column = True
+ except Exception as e:
+ # If the query fails (likely because is_owner column doesn't exist), rollback and try again
+ current_app.logger.warning(f"Failed to query with is_owner column, falling back: {e}")
+ conn.rollback() # Rollback the failed transaction
+ cur.execute('SELECT id, username, email, is_admin FROM users WHERE id = %s AND is_active = TRUE', (user_id,))
+ user = cur.fetchone()
+ has_owner_column = False
+
+ if not user:
+ return jsonify({'message': 'User not found or inactive!'}), 401
+
+ # Add user info to request context
+ request.user = {
+ 'id': user[0],
+ 'username': user[1],
+ 'email': user[2],
+ 'is_admin': user[3],
+ 'is_owner': user[4] if has_owner_column and len(user) > 4 else False
+ }
+
+ return f(*args, **kwargs)
+ except Exception as e:
+ current_app.logger.error(f"Authentication error: {e}")
+ return jsonify({'message': 'Authentication error!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+ return decorated
+
+def admin_required(f):
+ """Decorator to protect routes that require admin privileges"""
+ @wraps(f)
+ @token_required
+ def decorated(*args, **kwargs):
+ if not request.user.get('is_admin', False):
+ current_app.logger.error(f"User {request.user.get('username')} is not an admin")
+ return jsonify({'message': 'Admin privileges required!'}), 403
+
+ return f(*args, **kwargs)
+
+ return decorated
+
+def is_valid_email(email):
+ """Validate email format"""
+ pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
+ return re.match(pattern, email) is not None
+
+def is_valid_password(password):
+ """Validate password strength"""
+ # At least 8 characters, 1 uppercase, 1 lowercase, 1 number
+ if len(password) < 8:
+ return False
+ if not re.search(r'[A-Z]', password):
+ return False
+ if not re.search(r'[a-z]', password):
+ return False
+ if not re.search(r'[0-9]', password):
+ return False
+ return True
+
+
\ No newline at end of file
diff --git a/backend/config.py b/backend/config.py
new file mode 100644
index 0000000..686a7f6
--- /dev/null
+++ b/backend/config.py
@@ -0,0 +1,120 @@
+# backend/config.py
+import os
+import logging
+from datetime import timedelta
+
+logger = logging.getLogger(__name__)
+
+class Config:
+ """Base configuration class."""
+
+ # Flask Core Configuration
+ SECRET_KEY = os.environ.get('SECRET_KEY', 'your_default_secret_key_please_change_in_prod')
+ JWT_EXPIRATION_DELTA = timedelta(hours=int(os.environ.get('JWT_EXPIRATION_HOURS', '24')))
+
+ # Security Warning for Default Secret Key
+ @staticmethod
+ def _check_secret_key():
+ if Config.SECRET_KEY == 'your_default_secret_key_please_change_in_prod':
+ logger.warning("SECURITY WARNING: Using default SECRET_KEY. Please set a strong SECRET_KEY environment variable in production.")
+
+ # Database Configuration
+ DB_HOST = os.environ.get('DB_HOST', 'warrackerdb')
+ DB_NAME = os.environ.get('DB_NAME', 'warranty_db')
+ DB_USER = os.environ.get('DB_USER', 'warranty_user')
+ DB_PASSWORD = os.environ.get('DB_PASSWORD', 'warranty_password')
+ DB_ADMIN_USER = os.environ.get('DB_ADMIN_USER', 'warracker_admin')
+ DB_ADMIN_PASSWORD = os.environ.get('DB_ADMIN_PASSWORD', 'change_this_password_in_production')
+
+ # File Upload Configuration
+ UPLOAD_FOLDER = '/data/uploads'
+ DEFAULT_MAX_UPLOAD_MB = 32
+
+ @staticmethod
+ def _get_max_upload_mb():
+ try:
+ max_upload_mb = int(os.environ.get('MAX_UPLOAD_MB', Config.DEFAULT_MAX_UPLOAD_MB))
+ if max_upload_mb <= 0:
+ max_upload_mb = Config.DEFAULT_MAX_UPLOAD_MB
+ logger.warning(f"MAX_UPLOAD_MB was invalid, defaulting to {Config.DEFAULT_MAX_UPLOAD_MB}MB.")
+ except ValueError:
+ max_upload_mb = Config.DEFAULT_MAX_UPLOAD_MB
+ logger.warning(f"MAX_UPLOAD_MB was not a valid integer, defaulting to {Config.DEFAULT_MAX_UPLOAD_MB}MB.")
+
+ logger.info(f"Max upload file size set to: {max_upload_mb}MB")
+ return max_upload_mb
+
+ # Email Configuration
+ EMAIL_CHANGE_TOKEN_EXPIRATION_HOURS = 24
+ EMAIL_CHANGE_VERIFICATION_ENDPOINT = '/verify-email-change.html'
+
+ # Performance and Memory Optimization
+ JSON_SORT_KEYS = False
+ JSONIFY_PRETTYPRINT_REGULAR = False
+ SEND_FILE_MAX_AGE_DEFAULT = 31536000 # Cache static files for 1 year
+ PROPAGATE_EXCEPTIONS = True
+
+ # Session Configuration
+ SESSION_COOKIE_SECURE = False # Set to True in production with HTTPS
+ SESSION_COOKIE_HTTPONLY = True
+ SESSION_COOKIE_SAMESITE = 'Lax'
+ PERMANENT_SESSION_LIFETIME = 3600 # 1 hour session timeout
+
+ # Request Handling Optimization
+ MAX_COOKIE_SIZE = 4093 # Slightly under 4KB limit
+ USE_X_SENDFILE = True # Let nginx handle file serving
+
+ @staticmethod
+ def init_app(app):
+ """Initialize configuration-specific settings."""
+ Config._check_secret_key()
+
+ # Set upload configuration
+ max_upload_mb = Config._get_max_upload_mb()
+ app.config['MAX_CONTENT_LENGTH'] = max_upload_mb * 1024 * 1024
+
+ # Log configuration status
+ logger.info("Application configuration initialized successfully")
+
+class DevelopmentConfig(Config):
+ """Development configuration."""
+ DEBUG = True
+
+ @staticmethod
+ def init_app(app):
+ Config.init_app(app)
+ logger.info("Development configuration loaded")
+
+class ProductionConfig(Config):
+ """Production configuration."""
+ DEBUG = False
+
+ # Production-specific session settings
+ SESSION_COOKIE_SECURE = True # HTTPS only in production
+
+ @staticmethod
+ def init_app(app):
+ Config.init_app(app)
+ logger.info("Production configuration loaded")
+
+class TestingConfig(Config):
+ """Testing configuration."""
+ TESTING = True
+ DEBUG = True
+
+ # Use in-memory database for testing
+ DB_HOST = 'localhost'
+ DB_NAME = 'warranty_test'
+
+ @staticmethod
+ def init_app(app):
+ Config.init_app(app)
+ logger.info("Testing configuration loaded")
+
+# Configuration dictionary
+config = {
+ 'development': DevelopmentConfig,
+ 'production': ProductionConfig,
+ 'testing': TestingConfig,
+ 'default': DevelopmentConfig
+}
\ No newline at end of file
diff --git a/backend/db_handler.py b/backend/db_handler.py
new file mode 100644
index 0000000..3b59cba
--- /dev/null
+++ b/backend/db_handler.py
@@ -0,0 +1,249 @@
+# backend/db_handler.py
+import os
+import psycopg2
+from psycopg2 import pool
+import logging
+import time
+from datetime import datetime, timedelta
+from typing import List, Dict, Optional
+
+logger = logging.getLogger(__name__)
+
+# PostgreSQL connection details
+DB_HOST = os.environ.get('DB_HOST', 'warrackerdb')
+DB_NAME = os.environ.get('DB_NAME', 'warranty_db')
+DB_USER = os.environ.get('DB_USER', 'warranty_user')
+DB_PASSWORD = os.environ.get('DB_PASSWORD', 'warranty_password')
+
+connection_pool = None # Global connection pool for this module
+
+def init_db_pool(max_retries=5, retry_delay=5):
+ global connection_pool # Ensure we're modifying the global variable in this module
+ attempt = 0
+ last_exception = None
+
+ if connection_pool is not None:
+ logger.info("[DB_HANDLER] Database connection pool already initialized.")
+ return connection_pool
+
+ while attempt < max_retries:
+ try:
+ logger.info(f"[DB_HANDLER] Attempting to initialize database pool (attempt {attempt+1}/{max_retries})")
+ # Optimized connection pool for memory efficiency
+ connection_pool = pool.SimpleConnectionPool(
+ 1, 4, # Reduced from 1,10 to 1,4 for memory efficiency
+ host=DB_HOST,
+ database=DB_NAME,
+ user=DB_USER,
+ password=DB_PASSWORD,
+ # Memory optimization settings
+ connect_timeout=10, # Connection timeout
+ application_name='warracker_optimized' # Identify connections
+ )
+ logger.info("[DB_HANDLER] Database connection pool initialized successfully.")
+ return connection_pool # Return the pool for external check if needed
+ except Exception as e:
+ last_exception = e
+ logger.error(f"[DB_HANDLER] Database connection pool initialization error: {e}")
+ logger.info(f"[DB_HANDLER] Retrying in {retry_delay} seconds...")
+ time.sleep(retry_delay)
+ attempt += 1
+
+ logger.error(f"[DB_HANDLER] Failed to initialize database pool after {max_retries} attempts.")
+ if last_exception:
+ raise last_exception
+ else:
+ raise Exception("Unknown error creating database pool")
+
+def get_db_connection():
+ global connection_pool
+ if connection_pool is None:
+ logger.error("[DB_HANDLER] Database connection pool is None. Attempting to re-initialize.")
+ init_db_pool() # Attempt to initialize it
+ if connection_pool is None: # If still None after attempt
+ logger.critical("[DB_HANDLER] CRITICAL: Database pool re-initialization failed.")
+ raise Exception("Database connection pool is not initialized and could not be re-initialized.")
+ try:
+ return connection_pool.getconn()
+ except Exception as e:
+ logger.error(f"[DB_HANDLER] Error getting connection from pool: {e}")
+ raise
+
+def release_db_connection(conn):
+ global connection_pool
+ if connection_pool:
+ try:
+ connection_pool.putconn(conn)
+ except Exception as e:
+ logger.error(f"[DB_HANDLER] Error releasing connection to pool: {e}. Connection state: {conn.closed if conn else 'N/A'}")
+ # If putconn fails, the connection might be broken or the pool is in a bad state.
+ # Attempt to close the connection directly as a fallback.
+ if conn and not conn.closed:
+ try:
+ conn.close()
+ logger.info("[DB_HANDLER] Connection closed directly after putconn failure.")
+ except Exception as close_err:
+ logger.error(f"[DB_HANDLER] Error closing connection directly after putconn failed: {close_err}")
+ else:
+ logger.warning("[DB_HANDLER] Connection pool is None, cannot release connection to pool. Attempting to close directly.")
+ if conn and not conn.closed:
+ try:
+ conn.close()
+ except Exception as e:
+ logger.error(f"[DB_HANDLER] Error closing connection directly (pool was None): {e}")
+
+def get_site_setting(setting_name: str, default_value: str = '') -> str:
+ """Get a site setting value from the database"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ cursor.execute(
+ "SELECT value FROM site_settings WHERE key = %s",
+ (setting_name,)
+ )
+ result = cursor.fetchone()
+ cursor.close()
+
+ if result:
+ return result[0] if result[0] is not None else default_value
+ return default_value
+
+ except Exception as e:
+ logger.error(f"Error getting site setting {setting_name}: {e}")
+ return default_value
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+def get_expiring_warranties(days: int) -> List[Dict]:
+ """Get warranties expiring within the specified number of days"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # Calculate the date range
+ today = datetime.now().date()
+ end_date = today + timedelta(days=days)
+
+ # Query for non-lifetime warranties expiring within the specified days
+ # Include warranties expiring from today up to the target date
+ cursor.execute("""
+ SELECT
+ id, product_name, expiration_date, user_id,
+ purchase_date, vendor, warranty_type, notes
+ FROM warranties
+ WHERE is_lifetime = false
+ AND expiration_date BETWEEN %s AND %s
+ ORDER BY user_id, expiration_date, product_name
+ """, (today, end_date))
+
+ results = cursor.fetchall()
+ cursor.close()
+
+ warranties = []
+ for row in results:
+ warranty = {
+ 'id': row[0],
+ 'product_name': row[1],
+ 'expiration_date': row[2].isoformat() if row[2] else None,
+ 'user_id': row[3],
+ 'purchase_date': row[4].isoformat() if row[4] else None,
+ 'vendor': row[5],
+ 'warranty_type': row[6],
+ 'notes': row[7]
+ }
+ warranties.append(warranty)
+
+ logger.info(f"Found {len(warranties)} warranties expiring in {days} days")
+ return warranties
+
+ except Exception as e:
+ logger.error(f"Error getting expiring warranties for {days} days: {e}")
+ return []
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+def get_all_expiring_warranties(max_days: int = 30) -> Dict[int, List[Dict]]:
+ """Get all warranties expiring within max_days, grouped by days until expiration"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ today = datetime.now().date()
+ max_date = today + timedelta(days=max_days)
+
+ cursor.execute("""
+ SELECT
+ id, product_name, expiration_date, user_id,
+ purchase_date, vendor, warranty_type, notes,
+ (expiration_date - %s) as days_until_expiry
+ FROM warranties
+ WHERE is_lifetime = false
+ AND expiration_date BETWEEN %s AND %s
+ ORDER BY expiration_date, product_name
+ """, (today, today, max_date))
+
+ results = cursor.fetchall()
+ cursor.close()
+
+ # Group by days until expiry
+ grouped_warranties = {}
+ for row in results:
+ days_until = row[8].days if row[8] else 0
+
+ if days_until not in grouped_warranties:
+ grouped_warranties[days_until] = []
+
+ warranty = {
+ 'id': row[0],
+ 'product_name': row[1],
+ 'expiration_date': row[2].isoformat() if row[2] else None,
+ 'user_id': row[3],
+ 'purchase_date': row[4].isoformat() if row[4] else None,
+ 'vendor': row[5],
+ 'warranty_type': row[6],
+ 'notes': row[7],
+ 'days_until_expiry': days_until
+ }
+ grouped_warranties[days_until].append(warranty)
+
+ return grouped_warranties
+
+ except Exception as e:
+ logger.error(f"Error getting all expiring warranties: {e}")
+ return {}
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+def update_site_setting(setting_name: str, setting_value: str) -> bool:
+ """Update a site setting in the database"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ cursor.execute("""
+ INSERT INTO site_settings (key, value)
+ VALUES (%s, %s)
+ ON CONFLICT (key)
+ DO UPDATE SET value = EXCLUDED.value, updated_at = CURRENT_TIMESTAMP
+ """, (setting_name, setting_value))
+
+ conn.commit()
+ cursor.close()
+ return True
+
+ except Exception as e:
+ logger.error(f"Error updating site setting {setting_name}: {e}")
+ if conn:
+ conn.rollback()
+ return False
+ finally:
+ if conn:
+ release_db_connection(conn)
\ No newline at end of file
diff --git a/backend/extensions.py b/backend/extensions.py
new file mode 100644
index 0000000..bf1c4df
--- /dev/null
+++ b/backend/extensions.py
@@ -0,0 +1,78 @@
+# backend/extensions.py
+import logging
+from authlib.integrations.flask_client import OAuth
+from flask_cors import CORS
+from flask_bcrypt import Bcrypt
+
+logger = logging.getLogger(__name__)
+
+# Initialize extensions without app instance
+oauth = OAuth()
+cors = CORS()
+bcrypt = Bcrypt()
+babel = None # Will be initialized in initialize_extensions
+db_pool = None # Database connection pool
+
+def initialize_extensions(app):
+ """Initialize all extensions with the Flask app object."""
+ global babel, db_pool
+
+ logger.info("Initializing Flask extensions...")
+
+ # Initialize OAuth
+ oauth.init_app(app)
+ logger.info("OAuth initialized")
+
+ # Initialize CORS with credentials support
+ cors.init_app(app, supports_credentials=True)
+ logger.info("CORS initialized")
+
+ # Initialize Bcrypt
+ bcrypt.init_app(app)
+ logger.info("Bcrypt initialized")
+
+ # Initialize Babel for localization
+ try:
+ from .localization import init_babel, get_current_language
+ babel = init_babel(app)
+ logger.info("Babel localization initialized successfully")
+ except ImportError:
+ try:
+ from localization import init_babel, get_current_language
+ babel = init_babel(app)
+ logger.info("Babel localization initialized successfully")
+ except ImportError as e:
+ logger.error(f"Failed to initialize localization: {e}")
+ babel = None
+
+ # Initialize the database connection pool
+ try:
+ from .db_handler import init_db_pool
+ db_pool = init_db_pool()
+ logger.info("Database connection pool initialized successfully")
+ except ImportError:
+ try:
+ from db_handler import init_db_pool
+ db_pool = init_db_pool()
+ logger.info("Database connection pool initialized successfully")
+ except ImportError as e:
+ logger.critical(f"CRITICAL: Failed to initialize database pool: {e}")
+ raise
+
+ # Initialize Apprise notification handler
+ try:
+ try:
+ from .apprise_handler import AppriseNotificationHandler
+ except ImportError:
+ from apprise_handler import AppriseNotificationHandler
+
+ apprise_handler = AppriseNotificationHandler()
+ app.config['APPRISE_HANDLER'] = apprise_handler
+ app.config['APPRISE_AVAILABLE'] = True
+ logger.info("Apprise notification handler initialized successfully")
+ except ImportError as e:
+ app.config['APPRISE_HANDLER'] = None
+ app.config['APPRISE_AVAILABLE'] = False
+ logger.warning(f"Apprise not available: {e}. Notification features will be disabled.")
+
+ logger.info("All extensions initialized successfully")
\ No newline at end of file
diff --git a/backend/file_routes.py b/backend/file_routes.py
new file mode 100644
index 0000000..f8bb148
--- /dev/null
+++ b/backend/file_routes.py
@@ -0,0 +1,933 @@
+# backend/file_routes.py
+from flask import Blueprint, request, jsonify, current_app, send_from_directory, Response
+import os
+import mimetypes
+import logging
+
+# Use try-except pattern for imports to handle both Docker and development environments
+try:
+ from . import db_handler
+ from .auth_utils import token_required, admin_required
+ from .paperless_handler import get_paperless_handler
+ from .utils import allowed_file
+ from .db_handler import get_db_connection, release_db_connection
+except ImportError:
+ import db_handler
+ from auth_utils import token_required, admin_required
+ from paperless_handler import get_paperless_handler
+ from utils import allowed_file
+ from db_handler import get_db_connection, release_db_connection
+
+# Create the file routes blueprint
+file_bp = Blueprint('file_bp', __name__)
+
+# Set up logging
+logger = logging.getLogger(__name__)
+
+# ============================
+# Local File Serving Routes
+# ============================
+
+@file_bp.route('/files/<path:filename>', methods=['GET', 'POST'])
+@token_required
+def serve_file(filename):
+ """Basic secure file serving with authentication."""
+ try:
+ logger.info(f"File access request for {filename} by user {request.user['id']}")
+
+ if not filename.startswith('uploads/'):
+ logger.warning(f"Attempted access to non-uploads file: {filename}")
+ return jsonify({"message": "Access denied"}), 403
+
+ # Remove 'uploads/' prefix for send_from_directory
+ file_path = filename[8:] if filename.startswith('uploads/') else filename
+
+ return send_from_directory('/data/uploads', file_path)
+ except Exception as e:
+ logger.error(f"Error serving file {filename}: {e}")
+ return jsonify({"message": "Error accessing file"}), 500
+
+@file_bp.route('/secure-file/<path:filename>', methods=['GET', 'POST'])
+@token_required
+def secure_file_access(filename):
+ """Enhanced secure file serving with authorization checks and Paperless-ngx integration."""
+ conn = None
+ try:
+ # Check if this is a Paperless-ngx document ID request (paperless-{id})
+ if filename.startswith('paperless-'):
+ try:
+ paperless_id = int(filename.replace('paperless-', ''))
+ return serve_paperless_document(paperless_id)
+ except ValueError:
+ logger.warning(f"[SECURE_FILE] Invalid Paperless-ngx document ID format: {filename}")
+ return jsonify({"message": "Invalid Paperless document ID"}), 400
+
+ # Original local file serving logic
+ 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"[SECURE_FILE] Potential path traversal attempt detected: {filename} by user {request.user['id']}")
+ return jsonify({"message": "Invalid file path"}), 400
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ 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 OR w.other_document_path = %s OR w.product_photo_path = %s
+ """
+ cur.execute(query, (db_search_path, db_search_path, db_search_path, db_search_path))
+ results = cur.fetchall()
+ 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
+ logger.info(f"[SECURE_FILE] Initial authorization (is_admin={is_admin}): {authorized}")
+
+ # Check for ownership authorization
+ if not authorized and results:
+ 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
+
+ # Check global view permissions for product photos
+ if not authorized and results:
+ for warranty_id_db, warranty_user_id_db in results:
+ # Check if this file is a product photo
+ cur.execute('SELECT product_photo_path FROM warranties WHERE id = %s', (warranty_id_db,))
+ warranty_data = cur.fetchone()
+ if warranty_data and warranty_data[0] == db_search_path:
+ # This is a product photo - check global view settings
+ cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+
+ global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'
+ admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'
+
+ if global_view_enabled and (not admin_only or is_admin):
+ authorized = True
+ logger.info(f"[SECURE_FILE] Global view access granted for product photo: {filename}")
+ break
+
+ if not authorized:
+ 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
+
+ logger.info(f"[SECURE_FILE] User {user_id} authorized for file '{filename}'. Attempting to serve from /data/uploads.")
+
+ # Construct the full file path
+ target_file_path_for_send = os.path.join('/data/uploads', filename)
+ logger.info(f"[SECURE_FILE] Path for verification: '{target_file_path_for_send}' (repr: {repr(target_file_path_for_send)})")
+
+ # Enhanced file existence and readability checks
+ if not os.path.exists(target_file_path_for_send):
+ logger.error(f"[SECURE_FILE] File '{target_file_path_for_send}' does not exist")
+ 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 jsonify({"message": "File not found"}), 404
+
+ if not os.path.isfile(target_file_path_for_send):
+ logger.error(f"[SECURE_FILE] Path '{target_file_path_for_send}' exists but is not a file")
+ return jsonify({"message": "Invalid file"}), 400
+
+ # Check file size and readability
+ try:
+ file_size = os.path.getsize(target_file_path_for_send)
+ logger.info(f"[SECURE_FILE] File size: {file_size} bytes")
+
+ # Verify we can read the file
+ with open(target_file_path_for_send, 'rb') as f:
+ # Try to read first byte to ensure file is readable
+ f.read(1)
+ f.seek(0) # Reset file pointer
+
+ except (OSError, IOError) as e:
+ logger.error(f"[SECURE_FILE] Cannot read file '{target_file_path_for_send}': {e}")
+ return jsonify({"message": "File read error"}), 500
+
+ # Use Flask's send_from_directory with enhanced error handling
+ try:
+ # Get MIME type
+ mimetype, _ = mimetypes.guess_type(target_file_path_for_send)
+ if not mimetype:
+ mimetype = 'application/octet-stream'
+
+ logger.info(f"[SECURE_FILE] Serving file with size {file_size} bytes, mimetype: {mimetype}")
+
+ # Use streaming for ALL files to prevent Content-Length mismatches
+ logger.info(f"[SECURE_FILE] Using streaming response for file: {filename}")
+
+ def generate():
+ try:
+ with open(target_file_path_for_send, 'rb') as f:
+ chunk_size = 4096 # 4KB chunks
+ total_sent = 0
+ while True:
+ chunk = f.read(chunk_size)
+ if not chunk:
+ break
+ total_sent += len(chunk)
+ logger.debug(f"[SECURE_FILE] Streaming chunk: {len(chunk)} bytes, total sent: {total_sent}/{file_size}")
+ yield chunk
+ logger.info(f"[SECURE_FILE] Streaming completed: {total_sent}/{file_size} bytes sent")
+ except Exception as e:
+ logger.error(f"[SECURE_FILE] Error during streaming: {e}")
+ raise
+
+ response = Response(
+ generate(),
+ mimetype=mimetype,
+ headers={
+ 'Content-Length': str(file_size),
+ 'Content-Disposition': f'inline; filename="{os.path.basename(filename)}"',
+ 'Accept-Ranges': 'bytes',
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
+ 'Pragma': 'no-cache',
+ 'Expires': '0',
+ 'X-Content-Type-Options': 'nosniff',
+ 'Connection': 'close'
+ }
+ )
+ return response
+ except Exception as send_error:
+ logger.error(f"[SECURE_FILE] Error serving file: {send_error}")
+ return jsonify({"message": "Error serving file"}), 500
+
+ except Exception as 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
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@file_bp.route('/paperless-file/<int:paperless_id>', methods=['GET'])
+@token_required
+def serve_paperless_document(paperless_id: int):
+ """Serve a document from Paperless-ngx"""
+ conn = None
+ try:
+ user_id = request.user['id']
+ is_admin = request.user.get('is_admin', False)
+
+ # Get database connection
+ conn = get_db_connection()
+
+ # Find warranty that has this Paperless document ID
+ with conn.cursor() as cur:
+ cur.execute("""
+ SELECT w.id, w.user_id
+ FROM warranties w
+ WHERE w.paperless_invoice_id = %s OR w.paperless_manual_id = %s
+ OR w.paperless_photo_id = %s OR w.paperless_other_id = %s
+ """, (paperless_id, paperless_id, paperless_id, paperless_id))
+
+ results = cur.fetchall()
+
+ if not results:
+ logger.warning(f"[PAPERLESS_FILE] No warranty found with Paperless document ID {paperless_id}")
+ return jsonify({"message": "Document not found"}), 404
+
+ # Check authorization
+ authorized = is_admin
+ if not authorized:
+ for warranty_id_db, warranty_user_id_db in results:
+ if warranty_user_id_db == user_id:
+ authorized = True
+ break
+
+ # Check global view for photos
+ if not authorized:
+ cur.execute("""
+ SELECT w.id, w.user_id
+ FROM warranties w
+ WHERE w.paperless_photo_id = %s
+ """, (paperless_id,))
+ photo_results = cur.fetchall()
+
+ if photo_results:
+ # Get global view settings
+ cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+
+ global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'
+ admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'
+
+ if global_view_enabled and (not admin_only or is_admin):
+ authorized = True
+
+ if not authorized:
+ logger.warning(f"[PAPERLESS_FILE] Unauthorized access to Paperless document {paperless_id} by user {user_id}")
+ return jsonify({"message": "You are not authorized to access this document"}), 403
+
+ # Get Paperless handler and retrieve document
+ paperless_handler = get_paperless_handler(conn)
+ if not paperless_handler:
+ return jsonify({"message": "Paperless-ngx integration not available"}), 503
+
+ # Get document from Paperless-ngx
+ success, content, message, content_type = paperless_handler.get_document_preview(paperless_id)
+
+ if not success:
+ logger.error(f"[PAPERLESS_FILE] Failed to retrieve document {paperless_id}: {message}")
+ return jsonify({"message": message}), 404
+
+ # Stream the document content
+ def generate():
+ chunk_size = 4096
+ total_sent = 0
+ remaining = len(content)
+
+ while remaining > 0:
+ chunk_size_actual = min(chunk_size, remaining)
+ chunk = content[total_sent:total_sent + chunk_size_actual]
+ total_sent += chunk_size_actual
+ remaining -= chunk_size_actual
+ yield chunk
+
+ # Return streaming response
+ response = Response(
+ generate(),
+ mimetype=content_type or 'application/octet-stream',
+ headers={
+ 'Content-Length': str(len(content)),
+ 'Content-Disposition': f'inline; filename="paperless_document_{paperless_id}"',
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
+ 'Pragma': 'no-cache',
+ 'Expires': '0',
+ 'X-Content-Type-Options': 'nosniff'
+ }
+ )
+
+ logger.info(f"[PAPERLESS_FILE] Successfully served Paperless document {paperless_id} to user {user_id}")
+ return response
+
+ except Exception as e:
+ logger.error(f"[PAPERLESS_FILE] Error serving Paperless document {paperless_id}: {e}")
+ return jsonify({"message": "Error retrieving document"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+# ============================
+# Paperless-ngx Integration Routes
+# ============================
+
+@file_bp.route('/paperless/upload', methods=['POST'])
+@token_required
+def paperless_upload():
+ """
+ Proxy endpoint to upload files to Paperless-ngx
+ """
+ conn = None
+ try:
+ logger.info("Paperless upload endpoint called")
+
+ # Get Paperless handler
+ conn = get_db_connection()
+ logger.info("Database connection acquired")
+
+ paperless_handler = get_paperless_handler(conn)
+ logger.info(f"Paperless handler: {paperless_handler is not None}")
+
+ if not paperless_handler:
+ logger.warning("Paperless handler is None - integration not configured")
+ return jsonify({"error": "Paperless-ngx integration is not enabled or configured"}), 400
+
+ # Validate file upload
+ logger.info(f"Request files keys: {list(request.files.keys())}")
+ if 'file' not in request.files:
+ logger.warning("No 'file' key in request.files")
+ return jsonify({"error": "No file provided"}), 400
+
+ uploaded_file = request.files['file']
+ logger.info(f"Uploaded file: filename='{uploaded_file.filename}', content_type='{uploaded_file.content_type}'")
+
+ if uploaded_file.filename == '':
+ logger.warning("Empty filename")
+ return jsonify({"error": "No file selected"}), 400
+
+ # Validate file type
+ if not allowed_file(uploaded_file.filename):
+ logger.warning(f"File type not allowed: {uploaded_file.filename}")
+ return jsonify({"error": "File type not allowed"}), 400
+
+ # Get additional metadata
+ title = request.form.get('title', uploaded_file.filename)
+ document_type = request.form.get('document_type', 'warranty_document')
+ logger.info(f"Upload metadata: title='{title}', document_type='{document_type}'")
+
+ # Add Warracker-specific tags
+ tags = ['warracker', document_type]
+ if request.form.get('warranty_id'):
+ tags.append(f"warranty_{request.form.get('warranty_id')}")
+ logger.info(f"Upload tags: {tags}")
+
+ # Read file content
+ try:
+ file_content = uploaded_file.read()
+ logger.info(f"File content read successfully: {len(file_content)} bytes")
+ except Exception as file_read_error:
+ logger.error(f"Error reading file content: {file_read_error}")
+ return jsonify({"error": f"Error reading file: {str(file_read_error)}"}), 400
+
+ # Upload to Paperless-ngx
+ logger.info("Starting upload to Paperless-ngx")
+ try:
+ success, document_id, message = paperless_handler.upload_document(
+ file_content=file_content,
+ filename=uploaded_file.filename,
+ title=title,
+ tags=tags,
+ correspondent="Warracker"
+ )
+ logger.info(f"Upload result: success={success}, document_id={document_id}, message='{message}'")
+ except Exception as upload_error:
+ logger.error(f"Error during paperless upload: {upload_error}")
+ return jsonify({"error": f"Upload to Paperless-ngx failed: {str(upload_error)}"}), 500
+
+ if success:
+ logger.info("Upload successful")
+ return jsonify({
+ "success": True,
+ "document_id": document_id,
+ "message": message
+ }), 200
+ else:
+ logger.warning(f"Upload failed: {message}")
+ return jsonify({
+ "success": False,
+ "document_id": document_id,
+ "error": message
+ }), 200
+
+ except Exception as e:
+ logger.error(f"Error in Paperless upload: {e}")
+ return jsonify({"error": f"Upload failed: {str(e)}"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@file_bp.route('/paperless/test', methods=['POST'])
+@admin_required
+def test_paperless_connection():
+ """
+ Test connection to Paperless-ngx instance
+ """
+ conn = None
+ try:
+ conn = get_db_connection()
+ paperless_handler = get_paperless_handler(conn)
+
+ if not paperless_handler:
+ return jsonify({"error": "Paperless-ngx integration is not enabled or configured"}), 400
+
+ success, message = paperless_handler.test_connection()
+
+ if success:
+ return jsonify({
+ "success": True,
+ "message": message
+ }), 200
+ else:
+ return jsonify({
+ "success": False,
+ "error": message
+ }), 400
+
+ except Exception as e:
+ logger.error(f"Error testing Paperless connection: {e}")
+ return jsonify({"error": "Connection test failed"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@file_bp.route('/paperless/search', methods=['GET'])
+@token_required
+def paperless_search():
+ """
+ Search documents in Paperless-ngx
+ """
+ conn = None
+ try:
+ conn = get_db_connection()
+ paperless_handler = get_paperless_handler(conn)
+
+ if not paperless_handler:
+ return jsonify({'success': False, 'message': 'Paperless-ngx not configured'}), 400
+
+ # Get query parameters
+ ordering = request.args.get('ordering', '-created')
+ created_gte = request.args.get('created__gte')
+ search_query = request.args.get('query', '')
+
+ # Get pagination parameters (support both old and new formats)
+ limit = request.args.get('limit', request.args.get('page_size', '25'))
+ offset = request.args.get('offset', '0')
+ page = request.args.get('page', '1')
+
+ # Calculate page from offset if needed
+ try:
+ limit_int = int(limit)
+ offset_int = int(offset)
+ if offset_int > 0:
+ page = str((offset_int // limit_int) + 1)
+ except (ValueError, ZeroDivisionError):
+ page = '1'
+ limit = '25'
+
+ # Build search URL using paperless handler's configuration
+ search_url = f"{paperless_handler.base_url.rstrip('/')}/api/documents/"
+ params = {
+ 'ordering': ordering,
+ 'page_size': limit,
+ 'page': page
+ }
+
+ if created_gte:
+ # Convert ISO format to Paperless-ngx expected format
+ # Remove 'Z' and use format that Paperless-ngx accepts
+ try:
+ from datetime import datetime, timezone
+ # Parse the ISO format and convert to YYYY-MM-DD format
+ dt = datetime.fromisoformat(created_gte.replace('Z', '+00:00'))
+ # Use date only format for better compatibility
+ params['created__gte'] = dt.strftime('%Y-%m-%d')
+ logger.info(f"Converted date filter from {created_gte} to {params['created__gte']}")
+ except Exception as date_error:
+ logger.warning(f"Could not parse date {created_gte}: {date_error}")
+ # Fallback: use today's date
+ from datetime import datetime
+ params['created__gte'] = datetime.now().strftime('%Y-%m-%d')
+ if search_query:
+ params['query'] = search_query
+
+ # Add document type filter
+ document_type = request.args.get('document_type', '')
+ if document_type:
+ params['document_type'] = document_type
+
+ # Add tag filter
+ tags_filter = request.args.get('tags__id__in', '')
+ if tags_filter:
+ params['tags__id__in'] = tags_filter
+
+ logger.info(f"Searching Paperless documents with params: {params}")
+
+ # Make request to Paperless-ngx using the session from paperless handler
+ response = paperless_handler.session.get(
+ search_url,
+ params=params,
+ timeout=30
+ )
+
+ response.raise_for_status()
+ search_result = response.json()
+
+ logger.info(f"Paperless search returned {len(search_result.get('results', []))} documents")
+
+ return jsonify(search_result)
+
+ except Exception as e:
+ logger.error(f"Error searching Paperless documents: {e}")
+ return jsonify({'success': False, 'message': str(e)}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@file_bp.route('/paperless/tags', methods=['GET'])
+@token_required
+def paperless_tags():
+ """
+ Get tags from Paperless-ngx
+ """
+ conn = None
+ try:
+ conn = get_db_connection()
+ paperless_handler = get_paperless_handler(conn)
+
+ if not paperless_handler:
+ return jsonify({'success': False, 'message': 'Paperless-ngx integration not available'}), 400
+
+ # Make request to Paperless-ngx tags endpoint
+ response = paperless_handler.session.get(
+ f"{paperless_handler.paperless_url}/api/tags/",
+ timeout=30
+ )
+
+ response.raise_for_status()
+ tags_result = response.json()
+
+ logger.info(f"Paperless tags returned {len(tags_result.get('results', []))} tags")
+
+ return jsonify(tags_result)
+
+ except Exception as e:
+ logger.error(f"Error fetching Paperless tags: {e}")
+ return jsonify({'success': False, 'message': str(e)}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@file_bp.route('/paperless/debug', methods=['GET'])
+@token_required
+def paperless_debug():
+ """
+ Debug endpoint to test Paperless-ngx configuration
+ """
+ conn = None
+ try:
+ conn = get_db_connection()
+
+ # Check database settings
+ with conn.cursor() as cur:
+ cur.execute("""
+ SELECT key, value FROM site_settings
+ WHERE key IN ('paperless_enabled', 'paperless_url', 'paperless_api_token')
+ """)
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+
+ debug_info = {
+ "paperless_enabled": settings.get('paperless_enabled', 'false'),
+ "paperless_url": settings.get('paperless_url', ''),
+ "paperless_api_token_set": bool(settings.get('paperless_api_token', '').strip()),
+ "paperless_handler_available": False,
+ "test_connection_result": None
+ }
+
+ # Try to get paperless handler
+ try:
+ paperless_handler = get_paperless_handler(conn)
+ debug_info["paperless_handler_available"] = paperless_handler is not None
+
+ if paperless_handler:
+ # Test connection
+ try:
+ success, message = paperless_handler.test_connection()
+ debug_info["test_connection_result"] = {
+ "success": success,
+ "message": message
+ }
+ except Exception as test_error:
+ debug_info["test_connection_result"] = {
+ "success": False,
+ "error": str(test_error)
+ }
+ except Exception as handler_error:
+ debug_info["paperless_handler_error"] = str(handler_error)
+
+ return jsonify(debug_info), 200
+
+ except Exception as e:
+ logger.error(f"Error in Paperless debug: {e}")
+ return jsonify({"error": f"Debug failed: {str(e)}"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@file_bp.route('/paperless/test-upload', methods=['POST'])
+@token_required
+def test_file_upload():
+ """
+ Test file upload mechanism without Paperless-ngx
+ """
+ try:
+ logger.info("Test upload endpoint called")
+ logger.info(f"Request files keys: {list(request.files.keys())}")
+ logger.info(f"Request form keys: {list(request.form.keys())}")
+
+ if 'file' not in request.files:
+ return jsonify({"error": "No file provided"}), 400
+
+ uploaded_file = request.files['file']
+ logger.info(f"File: {uploaded_file.filename}, size: {uploaded_file.content_length}, type: {uploaded_file.content_type}")
+
+ # Read file content to test
+ file_content = uploaded_file.read()
+ logger.info(f"Successfully read {len(file_content)} bytes")
+
+ return jsonify({
+ "success": True,
+ "message": "File upload test successful",
+ "file_info": {
+ "filename": uploaded_file.filename,
+ "size": len(file_content),
+ "content_type": uploaded_file.content_type
+ }
+ }), 200
+
+ except Exception as e:
+ logger.error(f"Test upload error: {e}", exc_info=True)
+ return jsonify({"error": f"Test upload failed: {str(e)}"}), 500
+
+@file_bp.route('/paperless/debug-document/<int:document_id>', methods=['GET'])
+@token_required
+def paperless_debug_document(document_id: int):
+ """
+ Debug endpoint to check status of a specific Paperless-ngx document
+ """
+ conn = None
+ try:
+ conn = get_db_connection()
+ paperless_handler = get_paperless_handler(conn)
+
+ if not paperless_handler:
+ return jsonify({"error": "Paperless-ngx integration not available"}), 400
+
+ # Get debug information about the document
+ debug_info = paperless_handler.debug_document_status(document_id)
+
+ # Also check if this document ID exists in our database
+ with conn.cursor() as cur:
+ cur.execute("""
+ SELECT w.id, w.product_name, w.user_id,
+ CASE
+ WHEN w.paperless_invoice_id = %s THEN 'invoice'
+ WHEN w.paperless_manual_id = %s THEN 'manual'
+ WHEN w.paperless_photo_id = %s THEN 'photo'
+ WHEN w.paperless_other_id = %s THEN 'other'
+ ELSE 'unknown'
+ END as document_type
+ FROM warranties w
+ WHERE w.paperless_invoice_id = %s OR w.paperless_manual_id = %s
+ OR w.paperless_photo_id = %s OR w.paperless_other_id = %s
+ """, (document_id, document_id, document_id, document_id,
+ document_id, document_id, document_id, document_id))
+
+ db_results = cur.fetchall()
+ debug_info['database_references'] = [
+ {
+ 'warranty_id': row[0],
+ 'product_name': row[1],
+ 'user_id': row[2],
+ 'document_type': row[3]
+ }
+ for row in db_results
+ ]
+
+ return jsonify(debug_info), 200
+
+ except Exception as e:
+ logger.error(f"Error in Paperless document debug: {e}")
+ return jsonify({"error": f"Debug failed: {str(e)}"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@file_bp.route('/paperless/cleanup-invalid', methods=['POST'])
+@token_required
+def cleanup_invalid_paperless_documents():
+ """
+ Clean up invalid Paperless-ngx document references from the database
+ """
+ conn = None
+ try:
+ user_id = request.user['id']
+ is_admin = request.user.get('is_admin', False)
+
+ conn = get_db_connection()
+ paperless_handler = get_paperless_handler(conn)
+
+ if not paperless_handler:
+ return jsonify({"error": "Paperless-ngx integration not available"}), 400
+
+ cleanup_results = {
+ 'checked': 0,
+ 'invalid_found': 0,
+ 'cleaned_up': 0,
+ 'errors': []
+ }
+
+ with conn.cursor() as cur:
+ # Get all Paperless document IDs for this user (or all if admin)
+ if is_admin:
+ cur.execute("""
+ SELECT id, product_name, paperless_invoice_id, paperless_manual_id,
+ paperless_photo_id, paperless_other_id
+ FROM warranties
+ WHERE paperless_invoice_id IS NOT NULL
+ OR paperless_manual_id IS NOT NULL
+ OR paperless_photo_id IS NOT NULL
+ OR paperless_other_id IS NOT NULL
+ """)
+ else:
+ cur.execute("""
+ SELECT id, product_name, paperless_invoice_id, paperless_manual_id,
+ paperless_photo_id, paperless_other_id
+ FROM warranties
+ WHERE user_id = %s
+ AND (paperless_invoice_id IS NOT NULL
+ OR paperless_manual_id IS NOT NULL
+ OR paperless_photo_id IS NOT NULL
+ OR paperless_other_id IS NOT NULL)
+ """, (user_id,))
+
+ warranties = cur.fetchall()
+
+ for warranty in warranties:
+ warranty_id, product_name, invoice_id, manual_id, photo_id, other_id = warranty
+
+ # Check each document ID
+ document_fields = [
+ ('paperless_invoice_id', invoice_id),
+ ('paperless_manual_id', manual_id),
+ ('paperless_photo_id', photo_id),
+ ('paperless_other_id', other_id)
+ ]
+
+ for field_name, doc_id in document_fields:
+ if doc_id is not None:
+ cleanup_results['checked'] += 1
+
+ try:
+ if not paperless_handler.document_exists(doc_id):
+ cleanup_results['invalid_found'] += 1
+ logger.info(f"Found invalid Paperless document ID {doc_id} in warranty {warranty_id} ({product_name})")
+
+ # Clear the invalid reference
+ cur.execute(f"""
+ UPDATE warranties
+ SET {field_name} = NULL
+ WHERE id = %s
+ """, (warranty_id,))
+
+ cleanup_results['cleaned_up'] += 1
+ logger.info(f"Cleaned up invalid {field_name} reference for warranty {warranty_id}")
+
+ except Exception as e:
+ error_msg = f"Error checking document {doc_id}: {str(e)}"
+ cleanup_results['errors'].append(error_msg)
+ logger.error(error_msg)
+
+ conn.commit()
+
+ return jsonify({
+ "success": True,
+ "message": f"Cleanup complete. Checked {cleanup_results['checked']} documents, found {cleanup_results['invalid_found']} invalid, cleaned up {cleanup_results['cleaned_up']}.",
+ "details": cleanup_results
+ }), 200
+
+ except Exception as e:
+ logger.error(f"Error in Paperless cleanup: {e}")
+ return jsonify({"error": f"Cleanup failed: {str(e)}"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@file_bp.route('/paperless-search-and-link', methods=['POST'])
+@token_required
+def paperless_search_and_link():
+ """Search for a Paperless document by title and link it to a warranty."""
+
+ conn = None # Single connection for the full request lifecycle
+ try:
+ logger.info("paperless_search_and_link called by user: %s", request.user)
+
+ data = request.get_json() or {}
+ warranty_id = data.get("warranty_id")
+ document_type = data.get("document_type") # 'invoice', 'manual', 'photo', 'other'
+ search_title = data.get("search_title")
+
+ logger.info("Search request: warranty_id=%s, document_type=%s, search_title=%s", warranty_id, document_type, search_title)
+
+ if not all([warranty_id, document_type, search_title]):
+ return jsonify({"success": False, "message": "Missing required parameters"}), 400
+
+ # Validate document_type
+ valid_types = {
+ "invoice": "paperless_invoice_id",
+ "manual": "paperless_manual_id",
+ "photo": "paperless_photo_id",
+ "other": "paperless_other_id",
+ }
+
+ if document_type not in valid_types:
+ return jsonify({"success": False, "message": "Invalid document type"}), 400
+
+ # Get DB connection once and reuse it throughout
+ conn = get_db_connection()
+
+ # Obtain Paperless handler (uses same connection to fetch settings)
+ paperless_handler = get_paperless_handler(conn)
+ if not paperless_handler:
+ return jsonify({"success": False, "message": "Paperless-ngx not configured"}), 400
+
+ # Search for the document in Paperless-ngx
+ success, document_id, message = paperless_handler.find_document_by_title(search_title)
+ logger.info("Paperless search result: success=%s, document_id=%s, message=%s", success, document_id, message)
+
+ if not success or not document_id:
+ return jsonify({"success": False, "message": f"Document not found: {message}"}), 404
+
+ # Update warranty with the found document ID
+ db_field = valid_types[document_type]
+
+ with conn.cursor() as cursor:
+ logger.info(
+ "Updating warranty %s field %s with document ID %s for user %s",
+ warranty_id,
+ db_field,
+ document_id,
+ request.user["id"],
+ )
+
+ cursor.execute(
+ f"""
+ UPDATE warranties
+ SET {db_field} = %s
+ WHERE id = %s AND user_id = %s
+ """,
+ (document_id, warranty_id, request.user["id"]),
+ )
+
+ if cursor.rowcount == 0:
+ logger.warning("No warranty found with ID %s for user %s", warranty_id, request.user["id"])
+ conn.rollback()
+ return jsonify({"success": False, "message": "Warranty not found or access denied"}), 404
+
+ conn.commit()
+
+ logger.info("Successfully linked document %s to warranty %s", document_id, warranty_id)
+
+ return jsonify({"success": True, "message": "Document linked successfully", "document_id": document_id})
+
+ except Exception as e:
+ logger.error("Error in paperless_search_and_link: %s", e, exc_info=True)
+ return jsonify({"success": False, "message": "Internal server error"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@file_bp.route('/paperless/url', methods=['GET'])
+@token_required
+def get_paperless_url():
+ """Get the Paperless-ngx base URL for opening documents directly"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ paperless_handler = get_paperless_handler(conn)
+
+ if not paperless_handler:
+ return jsonify({'success': False, 'message': 'Paperless-ngx not configured'}), 400
+
+ return jsonify({
+ 'success': True,
+ 'url': paperless_handler.base_url
+ })
+
+ except Exception as e:
+ logger.error(f"Error getting Paperless URL: {e}")
+ return jsonify({'success': False, 'message': str(e)}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
\ No newline at end of file
diff --git a/backend/fix_notification_columns.py b/backend/fix_notification_columns.py
new file mode 100644
index 0000000..49845ae
--- /dev/null
+++ b/backend/fix_notification_columns.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python3
+"""
+Fix missing notification columns in user_preferences table.
+This script can be run manually to fix the notification column issues.
+"""
+
+import os
+import psycopg2
+import logging
+
+# Set up logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+# Database connection details from environment
+DB_HOST = os.environ.get('DB_HOST', 'localhost')
+DB_PORT = os.environ.get('DB_PORT', '5432')
+DB_NAME = os.environ.get('DB_NAME', 'warranty_db')
+DB_USER = os.environ.get('DB_USER', 'warranty_user')
+DB_PASSWORD = os.environ.get('DB_PASSWORD', 'warranty_password')
+
+def fix_notification_columns():
+ """Fix missing notification columns in user_preferences table."""
+ try:
+ logger.info("Connecting to database...")
+ conn = psycopg2.connect(
+ host=DB_HOST,
+ port=DB_PORT,
+ dbname=DB_NAME,
+ user=DB_USER,
+ password=DB_PASSWORD
+ )
+ conn.autocommit = False
+
+ with conn.cursor() as cur:
+ logger.info("Checking existing columns...")
+
+ # Check what columns exist
+ cur.execute("""
+ SELECT column_name FROM information_schema.columns
+ WHERE table_name='user_preferences'
+ AND column_name IN ('notification_channel', 'apprise_notification_time', 'apprise_notification_frequency')
+ """)
+ existing_columns = [row[0] for row in cur.fetchall()]
+ logger.info(f"Existing notification columns: {existing_columns}")
+
+ # Add notification_channel if missing
+ if 'notification_channel' not in existing_columns:
+ logger.info("Adding notification_channel column...")
+ cur.execute("""
+ ALTER TABLE user_preferences
+ ADD COLUMN notification_channel VARCHAR(10) NOT NULL DEFAULT 'email'
+ """)
+ logger.info("✓ Added notification_channel column")
+ else:
+ logger.info("✓ notification_channel column already exists")
+
+ # Add apprise_notification_time if missing
+ if 'apprise_notification_time' not in existing_columns:
+ logger.info("Adding apprise_notification_time column...")
+ cur.execute("""
+ ALTER TABLE user_preferences
+ ADD COLUMN apprise_notification_time VARCHAR(5) NOT NULL DEFAULT '09:00'
+ """)
+ logger.info("✓ Added apprise_notification_time column")
+ else:
+ logger.info("✓ apprise_notification_time column already exists")
+
+ # Add apprise_notification_frequency if missing
+ if 'apprise_notification_frequency' not in existing_columns:
+ logger.info("Adding apprise_notification_frequency column...")
+ cur.execute("""
+ ALTER TABLE user_preferences
+ ADD COLUMN apprise_notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily'
+ """)
+ logger.info("✓ Added apprise_notification_frequency column")
+ else:
+ logger.info("✓ apprise_notification_frequency column already exists")
+
+ conn.commit()
+ logger.info("✅ All notification columns are now properly configured!")
+
+ except Exception as e:
+ logger.error(f"❌ Error fixing notification columns: {e}")
+ if conn:
+ conn.rollback()
+ raise
+ finally:
+ if conn:
+ conn.close()
+
+if __name__ == "__main__":
+ fix_notification_columns()
\ No newline at end of file
diff --git a/backend/fix_permissions.sql b/backend/fix_permissions.sql
index 3cb4f1e..7337a66 100644
--- a/backend/fix_permissions.sql
+++ b/backend/fix_permissions.sql
@@ -1,9 +1,6 @@
-- Script to fix PostgreSQL permissions for db_user
--- Grant superuser privileges
-ALTER ROLE %(db_user)s WITH SUPERUSER;
-
--- Grant role management privileges
+-- Grant role management privileges (removed SUPERUSER)
ALTER ROLE %(db_user)s WITH CREATEROLE;
-- Ensure all database objects are accessible
diff --git a/backend/gunicorn_config.py b/backend/gunicorn_config.py
index 29324dc..59e9ab5 100644
--- a/backend/gunicorn_config.py
+++ b/backend/gunicorn_config.py
@@ -3,20 +3,77 @@
"""
Gunicorn configuration file for Warracker application.
-This ensures scheduler only runs in one worker process.
+Optimized for memory efficiency with configurable modes.
"""
import os
+
+# CRITICAL: Apply gevent monkey patching VERY EARLY to prevent SSL RecursionError
+# This must happen before any other imports that might use SSL
+memory_mode = os.environ.get('WARRACKER_MEMORY_MODE', 'optimized').lower()
+
+# Only apply monkey patching for modes that will use gevent workers
+if memory_mode in ('optimized', 'performance'):
+ try:
+ from gevent import monkey
+ monkey.patch_all()
+ print("✅ Early gevent monkey patch applied for SSL compatibility.")
+ except ImportError:
+ print("⚠️ Gevent not found, but gevent workers will be requested. This may cause issues.")
+
import multiprocessing
-# Server configurations
+# Server configurations - Dynamic based on memory mode
bind = "0.0.0.0:5000"
-workers = 4
-worker_class = "sync"
+forwarded_allow_ips = '*' # Trust proxy headers from any source (safe in containerized environment)
+
+# Determine worker class first, then apply appropriate monkey patching
+if memory_mode == 'ultra-light':
+ # Ultra-lightweight configuration for very memory-constrained environments
+ workers = 1 # Single worker for minimal memory usage (~40-50MB total)
+ worker_class = "sync" # Sync worker for lowest memory overhead
+ worker_connections = 50 # Reduced connections
+ max_requests = 500 # More frequent worker restarts to prevent memory leaks
+ worker_rlimit_as = 67108864 # 64MB per worker limit
+ print("Using ULTRA-LIGHT memory mode - minimal RAM usage, lower concurrency")
+elif memory_mode == 'performance':
+ # High-performance configuration for servers with plenty of RAM
+ workers = 4 # Original worker count for maximum concurrency
+ worker_class = "gevent" # Efficient async I/O handling
+ worker_connections = 200 # Higher connection limit per worker
+ max_requests = 2000 # Less frequent restarts for better performance
+ worker_rlimit_as = 268435456 # 256MB per worker limit
+ print("Using PERFORMANCE memory mode - maximum concurrency and performance")
+else:
+ # Default optimized configuration for balanced performance and memory usage
+ workers = 2 # Reduced from 4 to save ~75MB RAM
+ worker_class = "gevent" # More memory efficient than sync workers
+ worker_connections = 100 # Limit concurrent connections per worker
+ max_requests = 1000 # Restart workers after handling requests to prevent memory leaks
+ worker_rlimit_as = 134217728 # 128MB per worker limit
+ print("Using OPTIMIZED memory mode - balanced RAM usage and performance")
+
+# Note: Gevent monkey patching was applied early at top of file for SSL compatibility
+if worker_class == "gevent":
+ print(f"ℹ️ Using gevent workers with early monkey patching applied.")
+else:
+ print(f"ℹ️ Using {worker_class} workers - no monkey patching needed.")
+
+# Common settings for both modes
timeout = 120
keepalive = 5
+max_requests_jitter = 50 # Add randomness to prevent thundering herd
+
+# Enhanced settings for file handling to prevent Content-Length mismatches
+limit_request_line = 8190 # Increase request line limit
+limit_request_fields = 200 # Increase header fields limit
+limit_request_field_size = 8190 # Increase header field size limit
-# Set worker environment variables
+# Memory management (common to both modes)
+preload_app = True # Share memory between workers (saves RAM)
+worker_tmp_dir = "/dev/shm" # Use RAM disk for worker temporary files
+
+# Process management callbacks
def worker_int(worker):
"""Called just after a worker exited on SIGINT or SIGQUIT."""
print(f"Worker {worker.pid} received SIGINT/SIGQUIT")
@@ -31,18 +88,24 @@ def worker_exit(server, worker):
def on_starting(server):
"""Called just before the master process is initialized."""
- print("Server is starting")
+ print("Server is starting with memory-optimized configuration")
def post_fork(server, worker):
"""Called just after a worker has been forked."""
- os.environ["GUNICORN_WORKER_ID"] = str(worker.age - 1) # Worker ID starts at 0
+ os.environ["GUNICORN_WORKER_ID"] = str(worker.age - 1)
os.environ["GUNICORN_WORKER_PROCESS_NAME"] = f"worker-{worker.age - 1}"
os.environ["GUNICORN_WORKER_CLASS"] = worker_class
- print(f"Worker {worker.pid} (ID: {worker.age - 1}) forked")
+ print(f"Worker {worker.pid} (ID: {worker.age - 1}) forked with memory optimization")
def pre_fork(server, worker):
"""Called just before a worker is forked."""
print(f"Forking worker #{worker.age}")
-print(f"Gunicorn configuration loaded with {workers} workers")
\ No newline at end of file
+print(f"Gunicorn configuration loaded: {workers} {worker_class} workers in {memory_mode.upper()} mode")
+print(f"Memory limit per worker: {worker_rlimit_as // 1024 // 1024}MB, Max connections: {worker_connections if 'worker_connections' in locals() else 'N/A'}")
+
+# To switch memory modes, set WARRACKER_MEMORY_MODE environment variable:
+# - "optimized" (default): 2 gevent workers, balanced performance and memory usage (~60-80MB)
+# - "ultra-light": 1 sync worker, minimal memory usage (~40-50MB, lower concurrency)
+# - "performance": 4 gevent workers, high-performance mode (~200MB)
\ No newline at end of file
diff --git a/backend/localization.py b/backend/localization.py
new file mode 100644
index 0000000..8712401
--- /dev/null
+++ b/backend/localization.py
@@ -0,0 +1,190 @@
+"""
+Backend Localization Handler
+Manages server-side translations using Flask-Babel
+"""
+
+from flask import request, session
+from flask_babel import Babel, gettext, ngettext, lazy_gettext
+import os
+import logging
+
+logger = logging.getLogger(__name__)
+
+# Supported languages
+SUPPORTED_LANGUAGES = ['en', 'fr', 'es', 'de', 'it', 'cs', 'nl', 'hi', 'fa', 'ar', 'ru', 'uk', 'zh_CN', 'zh_HK', 'ja', 'pt', 'ko']
+DEFAULT_LANGUAGE = 'en'
+
+# Global babel instance
+babel = None
+
+def init_babel(app):
+ """Initialize Babel with Flask app"""
+ global babel
+
+ # Configure Babel
+ app.config['LANGUAGES'] = {
+ 'en': 'English',
+ 'fr': 'Français',
+ 'es': 'Español',
+ 'de': 'Deutsch',
+ 'it': 'Italiano',
+ 'cs': 'Čeština',
+ 'nl': 'Nederlands',
+ 'hi': 'हिन्दी',
+ 'fa': 'فارسی',
+ 'ar': 'العربية',
+ 'ru': 'Русский',
+ 'uk': 'Українська',
+ 'zh_CN': '简体中文',
+ 'zh_HK': '繁體中文',
+ 'ja': '日本語',
+ 'pt': 'Português',
+ 'ko': '한국어'
+ }
+ app.config['BABEL_DEFAULT_LOCALE'] = DEFAULT_LANGUAGE
+ app.config['BABEL_DEFAULT_TIMEZONE'] = 'UTC'
+
+ babel = Babel()
+ babel.init_app(app, locale_selector=get_current_language)
+
+ logger.info("Babel initialized successfully")
+ return babel
+
+def get_current_language():
+ """Get current language from various sources"""
+
+ # 1. Check URL parameter (for testing)
+ if request and request.args.get('lang') in SUPPORTED_LANGUAGES:
+ return request.args.get('lang')
+
+ # 2. Check cookie
+ if request and request.cookies.get('lang') in SUPPORTED_LANGUAGES:
+ return request.cookies.get('lang')
+
+ # 3. Check session
+ if session.get('language') in SUPPORTED_LANGUAGES:
+ return session.get('language')
+
+ # 4. Check user preferences (if authenticated)
+ try:
+ from backend.auth_utils import get_current_user_info
+ user_info = get_current_user_info()
+ if user_info and user_info.get('preferred_language') in SUPPORTED_LANGUAGES:
+ return user_info['preferred_language']
+ except:
+ pass # User not authenticated or error getting user info
+
+ # 5. Check Accept-Language header
+ if request:
+ browser_lang = request.accept_languages.best_match(SUPPORTED_LANGUAGES)
+ if browser_lang:
+ return browser_lang
+
+ # 6. Fallback to default
+ return DEFAULT_LANGUAGE
+
+def set_language(language):
+ """Set language for current session"""
+ if language in SUPPORTED_LANGUAGES:
+ session['language'] = language
+ return True
+ return False
+
+def get_supported_languages():
+ """Get list of supported languages"""
+ return SUPPORTED_LANGUAGES
+
+def is_supported_language(language):
+ """Check if language is supported"""
+ return language in SUPPORTED_LANGUAGES
+
+# Convenience functions for translations
+def _(text):
+ """Translate text (alias for gettext)"""
+ return gettext(text)
+
+def _n(singular, plural, num):
+ """Translate text with pluralization (alias for ngettext)"""
+ return ngettext(singular, plural, num)
+
+def _l(text):
+ """Lazy translation (alias for lazy_gettext)"""
+ return lazy_gettext(text)
+
+# Common translations for the application
+COMMON_TRANSLATIONS = {
+ # Authentication
+ 'login': _l('Login'),
+ 'logout': _l('Logout'),
+ 'register': _l('Register'),
+ 'username': _l('Username'),
+ 'password': _l('Password'),
+ 'email': _l('Email'),
+ 'first_name': _l('First Name'),
+ 'last_name': _l('Last Name'),
+
+ # Navigation
+ 'home': _l('Home'),
+ 'settings': _l('Settings'),
+ 'status': _l('Status'),
+ 'about': _l('About'),
+
+ # Common actions
+ 'save': _l('Save'),
+ 'cancel': _l('Cancel'),
+ 'delete': _l('Delete'),
+ 'edit': _l('Edit'),
+ 'search': _l('Search'),
+ 'export': _l('Export'),
+ 'import': _l('Import'),
+
+ # Messages
+ 'success': _l('Success'),
+ 'error': _l('Error'),
+ 'warning': _l('Warning'),
+ 'loading': _l('Loading...'),
+ 'saved_successfully': _l('Saved successfully'),
+ 'deleted_successfully': _l('Deleted successfully'),
+ 'invalid_request': _l('Invalid request'),
+ 'unauthorized': _l('Unauthorized'),
+ 'not_found': _l('Not found'),
+ 'server_error': _l('Server error'),
+
+ # Warranties
+ 'warranties': _l('Warranties'),
+ 'warranty': _l('Warranty'),
+ 'product_name': _l('Product Name'),
+ 'purchase_date': _l('Purchase Date'),
+ 'warranty_duration': _l('Warranty Duration'),
+ 'expiration_date': _l('Expiration Date'),
+ 'vendor': _l('Vendor'),
+ 'status': _l('Status'),
+ 'active': _l('Active'),
+ 'expired': _l('Expired'),
+ 'expiring_soon': _l('Expiring Soon'),
+ 'lifetime': _l('Lifetime'),
+}
+
+def get_translation(key, default=None):
+ """Get translation for a key with fallback"""
+ if key in COMMON_TRANSLATIONS:
+ return str(COMMON_TRANSLATIONS[key])
+ return default or key
+
+def format_error_message(error_type, details=None):
+ """Format error messages with localization"""
+ error_messages = {
+ 'validation_error': _('Validation error'),
+ 'authentication_error': _('Authentication error'),
+ 'authorization_error': _('Authorization error'),
+ 'not_found_error': _('Resource not found'),
+ 'server_error': _('Internal server error'),
+ 'file_too_large': _('File is too large'),
+ 'invalid_file_type': _('Invalid file type'),
+ }
+
+ message = error_messages.get(error_type, _('An error occurred'))
+ if details:
+ message += f": {details}"
+
+ return message
diff --git a/backend/messages.pot b/backend/messages.pot
new file mode 100644
index 0000000..4304ee4
--- /dev/null
+++ b/backend/messages.pot
@@ -0,0 +1,51 @@
+# Translations template for PROJECT.
+# Copyright (C) 2025 ORGANIZATION
+# This file is distributed under the same license as the PROJECT project.
+# FIRST AUTHOR <EMAIL@ADDRESS>, 2025.
+#
+#, fuzzy
+msgid ""
+msgstr ""
+"Project-Id-Version: PROJECT VERSION\n"
+"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
+"POT-Creation-Date: 2025-06-29 12:36-0300\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: LANGUAGE <[email protected]>\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=utf-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Generated-By: Babel 2.17.0\n"
+
+#: backend/localization.py:177
+msgid "Validation error"
+msgstr ""
+
+#: backend/localization.py:178
+msgid "Authentication error"
+msgstr ""
+
+#: backend/localization.py:179
+msgid "Authorization error"
+msgstr ""
+
+#: backend/localization.py:180
+msgid "Resource not found"
+msgstr ""
+
+#: backend/localization.py:181
+msgid "Internal server error"
+msgstr ""
+
+#: backend/localization.py:182
+msgid "File is too large"
+msgstr ""
+
+#: backend/localization.py:183
+msgid "Invalid file type"
+msgstr ""
+
+#: backend/localization.py:186
+msgid "An error occurred"
+msgstr ""
+
diff --git a/backend/migrations/009z_grant_createrole_to_db_user.sql b/backend/migrations/009z_grant_createrole_to_db_user.sql
new file mode 100644
index 0000000..63dbbab
--- /dev/null
+++ b/backend/migrations/009z_grant_createrole_to_db_user.sql
@@ -0,0 +1,16 @@
+-- Migration: Grant CREATEROLE to db_user before admin role configuration
+-- This is optional and will be skipped if the user doesn't have permission
+
+DO $$
+BEGIN
+ -- Try to grant CREATEROLE, but continue if it fails
+ BEGIN
+ ALTER ROLE %(db_user)s WITH CREATEROLE;
+ RAISE NOTICE 'Successfully granted CREATEROLE to %(db_user)s';
+ EXCEPTION WHEN insufficient_privilege THEN
+ RAISE NOTICE 'Insufficient privileges to grant CREATEROLE to %(db_user)s - this is optional and the application will work without it';
+ WHEN OTHERS THEN
+ RAISE NOTICE 'Could not grant CREATEROLE to %(db_user)s - this is optional and the application will work without it';
+ END;
+END
+$$;
\ No newline at end of file
diff --git a/backend/migrations/010_configure_admin_roles.sql b/backend/migrations/010_configure_admin_roles.sql
index b479541..834739d 100644
--- a/backend/migrations/010_configure_admin_roles.sql
+++ b/backend/migrations/010_configure_admin_roles.sql
@@ -1,24 +1,40 @@
-- Migration: Configure PostgreSQL Admin Role
+-- This is optional role management - will be skipped if permissions are insufficient
--- Create a new database role for admin operations
DO $$
BEGIN
- -- Check if the db_admin_user exists, if not create it
- IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '%(db_admin_user)s') THEN
- CREATE ROLE %(db_admin_user)s WITH LOGIN PASSWORD '%(db_admin_password)s';
- END IF;
+ -- Try to create admin role, but continue if it fails
+ BEGIN
+ -- Check if the db_admin_user exists, if not create it
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '%(db_admin_user)s') THEN
+ CREATE ROLE %(db_admin_user)s WITH LOGIN PASSWORD '%(db_admin_password)s';
+ RAISE NOTICE 'Successfully created admin role %(db_admin_user)s';
+ END IF;
+
+ -- Grant privileges to the admin role
+ GRANT ALL PRIVILEGES ON DATABASE %(db_name)s TO %(db_admin_user)s;
+ GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO %(db_admin_user)s;
+ GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO %(db_admin_user)s;
+ GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO %(db_admin_user)s;
+
+ -- Try to grant CREATEROLE, but continue if it fails
+ BEGIN
+ ALTER ROLE %(db_admin_user)s WITH CREATEROLE;
+ RAISE NOTICE 'Successfully granted CREATEROLE to %(db_admin_user)s';
+ EXCEPTION WHEN insufficient_privilege THEN
+ RAISE NOTICE 'Insufficient privileges to grant CREATEROLE to %(db_admin_user)s - role management features may be limited';
+ WHEN OTHERS THEN
+ RAISE NOTICE 'Could not grant CREATEROLE to %(db_admin_user)s - role management features may be limited';
+ END;
+
+ EXCEPTION WHEN insufficient_privilege THEN
+ RAISE NOTICE 'Insufficient privileges to create admin role %(db_admin_user)s - this is optional and the application will work without it';
+ WHEN OTHERS THEN
+ RAISE NOTICE 'Could not create admin role %(db_admin_user)s - this is optional and the application will work without it';
+ END;
END
$$;
--- Grant privileges to the admin role
-GRANT ALL PRIVILEGES ON DATABASE %(db_name)s TO %(db_admin_user)s;
-GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO %(db_admin_user)s;
-GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO %(db_admin_user)s;
-GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO %(db_admin_user)s;
-
--- Grant specific role management permissions
-ALTER ROLE %(db_admin_user)s WITH CREATEROLE;
-
-- Ensure the db_user can still access all application tables
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO %(db_user)s;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO %(db_user)s;
diff --git a/backend/migrations/011_ensure_admin_permissions.sql b/backend/migrations/011_ensure_admin_permissions.sql
index dd5fded..ad62eb1 100644
--- a/backend/migrations/011_ensure_admin_permissions.sql
+++ b/backend/migrations/011_ensure_admin_permissions.sql
@@ -1,43 +1,54 @@
-- Migration: Ensure Admin Permissions
+-- This migration ensures basic permissions are granted (advanced features are optional)
--- Grant superuser privileges to db_user
-ALTER ROLE %(db_user)s WITH SUPERUSER;
+DO $$
+BEGIN
+ -- Grant elevated privileges to db_user (removed SUPERUSER)
+ -- ALTER ROLE %(db_user)s WITH SUPERUSER;
--- Ensure all tables are accessible
-GRANT ALL PRIVILEGES ON DATABASE %(db_name)s TO %(db_user)s;
-GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO %(db_user)s;
-GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO %(db_user)s;
-GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO %(db_user)s;
+ -- Ensure all tables are accessible
+ BEGIN
+ GRANT ALL PRIVILEGES ON DATABASE %(db_name)s TO %(db_user)s;
+ GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO %(db_user)s;
+ GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO %(db_user)s;
+ GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO %(db_user)s;
+ RAISE NOTICE 'Successfully granted basic privileges to %(db_user)s';
+ EXCEPTION WHEN insufficient_privilege THEN
+ RAISE NOTICE 'Insufficient privileges to grant some permissions to %(db_user)s - this may limit some features';
+ WHEN OTHERS THEN
+ RAISE NOTICE 'Could not grant all privileges to %(db_user)s - this may limit some features';
+ END;
--- Ensure role can create and manage roles
-ALTER ROLE %(db_user)s WITH CREATEROLE;
+ -- Ensure role can create and manage roles (optional)
+ -- ALTER ROLE %(db_user)s WITH CREATEROLE;
--- Create a function to ensure the db_user is the owner of all database objects
-DO $$
-BEGIN
- -- Make db_user the owner of all tables
- EXECUTE (
- SELECT 'ALTER TABLE ' || quote_ident(tablename) || ' OWNER TO %(db_user)s;'
- FROM pg_tables
- WHERE schemaname = 'public'
- );
-
- -- Make db_user the owner of all sequences
- EXECUTE (
- SELECT 'ALTER SEQUENCE ' || quote_ident(sequencename) || ' OWNER TO %(db_user)s;'
- FROM pg_sequences
- WHERE schemaname = 'public'
- );
-
- -- Make db_user the owner of all functions
- EXECUTE (
- SELECT 'ALTER FUNCTION ' || quote_ident(proname) || '(' ||
- pg_get_function_arguments(p.oid) || ') OWNER TO %(db_user)s;'
- FROM pg_proc p
- JOIN pg_namespace n ON p.pronamespace = n.oid
- WHERE n.nspname = 'public'
- );
-EXCEPTION WHEN OTHERS THEN
- -- Log error but continue
- RAISE NOTICE 'Error setting ownership: %%', SQLERRM;
+ -- Try to make db_user the owner of all database objects (optional)
+ BEGIN
+ -- Make db_user the owner of all tables
+ EXECUTE (
+ SELECT 'ALTER TABLE ' || quote_ident(tablename) || ' OWNER TO %(db_user)s;'
+ FROM pg_tables
+ WHERE schemaname = 'public'
+ );
+
+ -- Make db_user the owner of all sequences
+ EXECUTE (
+ SELECT 'ALTER SEQUENCE ' || quote_ident(sequencename) || ' OWNER TO %(db_user)s;'
+ FROM pg_sequences
+ WHERE schemaname = 'public'
+ );
+
+ -- Make db_user the owner of all functions
+ EXECUTE (
+ SELECT 'ALTER FUNCTION ' || quote_ident(proname) || '(' ||
+ pg_get_function_arguments(p.oid) || ') OWNER TO %(db_user)s;'
+ FROM pg_proc p
+ JOIN pg_namespace n ON p.pronamespace = n.oid
+ WHERE n.nspname = 'public'
+ );
+ RAISE NOTICE 'Successfully set ownership of database objects to %(db_user)s';
+ EXCEPTION WHEN OTHERS THEN
+ -- Log error but continue
+ RAISE NOTICE 'Error setting ownership (this is optional): %%', SQLERRM;
+ END;
END $$;
diff --git a/backend/migrations/023_add_oidc_columns_to_users.sql b/backend/migrations/023_add_oidc_columns_to_users.sql
new file mode 100644
index 0000000..6304808
--- /dev/null
+++ b/backend/migrations/023_add_oidc_columns_to_users.sql
@@ -0,0 +1,31 @@
+-- Add oidc_sub and oidc_issuer columns to the users table
+ALTER TABLE users
+ADD COLUMN IF NOT EXISTS oidc_sub VARCHAR(255),
+ADD COLUMN IF NOT EXISTS oidc_issuer VARCHAR(255);
+
+-- Make password_hash nullable for OIDC-only users
+-- This assumes the column 'password_hash' exists.
+-- If it might not, the original DO $$ block with IF EXISTS for the column is safer.
+-- However, given it's a core user attribute, it should exist.
+ALTER TABLE users ALTER COLUMN password_hash DROP NOT NULL;
+
+-- Add a unique constraint for oidc_sub and oidc_issuer.
+-- This will fail if the constraint already exists, which is acceptable as the migration runner
+-- should catch the error and skip/log if the migration was already partially applied.
+-- A more robust way is to check information_schema, but we're simplifying due to `RAISE` issues.
+ALTER TABLE users ADD CONSTRAINT uq_users_oidc_sub_issuer UNIQUE (oidc_sub, oidc_issuer);
+
+-- Add login_method to user_sessions table
+ALTER TABLE user_sessions
+ADD COLUMN IF NOT EXISTS login_method VARCHAR(50) DEFAULT 'local';
+
+-- Update existing sessions to 'local' if login_method is NULL
+UPDATE user_sessions
+SET login_method = 'local'
+WHERE login_method IS NULL;
+
+-- Make login_method not nullable after updating existing rows
+-- This assumes the column 'login_method' now exists.
+ALTER TABLE user_sessions ALTER COLUMN login_method SET NOT NULL;
+
+-- End of migration
diff --git a/backend/migrations/024_fix_tags_constraint.sql b/backend/migrations/024_fix_tags_constraint.sql
new file mode 100644
index 0000000..d177a9a
--- /dev/null
+++ b/backend/migrations/024_fix_tags_constraint.sql
@@ -0,0 +1,52 @@
+-- Fix tags table constraints to allow per-user tag names
+DO $$
+BEGIN
+ -- Check if user_id column exists, if not add it
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_name = 'tags' AND column_name = 'user_id'
+ ) THEN
+ -- Add user_id column as nullable first
+ ALTER TABLE tags ADD COLUMN user_id INTEGER;
+
+ -- Update existing tags to have user_id = 1 (assuming admin user)
+ UPDATE tags SET user_id = 1 WHERE user_id IS NULL;
+
+ -- Make the column NOT NULL
+ ALTER TABLE tags ALTER COLUMN user_id SET NOT NULL;
+
+ -- Add foreign key constraint
+ ALTER TABLE tags ADD CONSTRAINT fk_tags_user_id
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;
+ END IF;
+
+ -- Drop the old unique constraint on name only (if it exists)
+ IF EXISTS (
+ SELECT 1 FROM information_schema.table_constraints
+ WHERE table_name = 'tags' AND constraint_name = 'tags_name_key'
+ ) THEN
+ ALTER TABLE tags DROP CONSTRAINT tags_name_key;
+ RAISE NOTICE 'Dropped old tags_name_key constraint';
+ END IF;
+
+ -- Add new unique constraint on name and user_id (if it doesn't exist)
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.table_constraints
+ WHERE table_name = 'tags' AND constraint_name = 'tags_name_user_id_key'
+ ) THEN
+ ALTER TABLE tags ADD CONSTRAINT tags_name_user_id_key
+ UNIQUE (name, user_id);
+ RAISE NOTICE 'Added new tags_name_user_id_key constraint';
+ END IF;
+
+ -- Create index for faster lookups (if it doesn't exist)
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE tablename = 'tags' AND indexname = 'idx_tags_user_id'
+ ) THEN
+ CREATE INDEX idx_tags_user_id ON tags (user_id);
+ RAISE NOTICE 'Created idx_tags_user_id index';
+ END IF;
+
+ RAISE NOTICE 'Tags table constraint fix completed successfully';
+END $$;
\ No newline at end of file
diff --git a/backend/migrations/025_add_warranty_type.sql b/backend/migrations/025_add_warranty_type.sql
new file mode 100644
index 0000000..3ed081c
--- /dev/null
+++ b/backend/migrations/025_add_warranty_type.sql
@@ -0,0 +1,23 @@
+-- Migration: Create site_settings table
+-- Description: Creates the site_settings table for storing application configuration
+
+-- Create site_settings table
+CREATE TABLE IF NOT EXISTS site_settings (
+ key VARCHAR(255) PRIMARY KEY,
+ value TEXT,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);
+
+-- Insert default values
+INSERT INTO site_settings (key, value) VALUES
+('registration_enabled', 'true'),
+('email_base_url', 'http://localhost:8080'),
+('global_view_enabled', 'true'),
+('global_view_admin_only', 'false'),
+('oidc_enabled', 'false'),
+('oidc_only_mode', 'false'),
+('oidc_provider_name', 'oidc'),
+('oidc_client_id', ''),
+('oidc_issuer_url', ''),
+('oidc_scope', 'openid email profile')
+ON CONFLICT (key) DO NOTHING;
\ No newline at end of file
diff --git a/backend/migrations/025a_add_warranty_type.sql b/backend/migrations/025a_add_warranty_type.sql
new file mode 100644
index 0000000..d113bfb
--- /dev/null
+++ b/backend/migrations/025a_add_warranty_type.sql
@@ -0,0 +1,5 @@
+-- Migration: Add warranty_type field to warranties table
+ALTER TABLE warranties ADD COLUMN IF NOT EXISTS warranty_type VARCHAR(255) DEFAULT NULL;
+
+-- Add an index for warranty type to improve search performance
+CREATE INDEX IF NOT EXISTS idx_warranty_type ON warranties(warranty_type);
\ No newline at end of file
diff --git a/backend/migrations/026_add_apprise_settings.sql b/backend/migrations/026_add_apprise_settings.sql
new file mode 100644
index 0000000..ba89bb8
--- /dev/null
+++ b/backend/migrations/026_add_apprise_settings.sql
@@ -0,0 +1,14 @@
+-- Migration: Add Apprise notification settings
+-- Description: Adds Apprise notification configuration options to site_settings table
+
+-- Add Apprise notification settings
+INSERT INTO site_settings (key, value) VALUES
+('apprise_enabled', 'false'),
+('apprise_urls', ''),
+('apprise_expiration_days', '7,30'),
+('apprise_notification_time', '09:00'),
+('apprise_title_prefix', '[Warracker]'),
+('apprise_test_url', '')
+ON CONFLICT (key) DO UPDATE SET
+ value = EXCLUDED.value,
+ updated_at = CURRENT_TIMESTAMP;
\ No newline at end of file
diff --git a/backend/migrations/027_add_notification_channel.sql b/backend/migrations/027_add_notification_channel.sql
new file mode 100644
index 0000000..b170039
--- /dev/null
+++ b/backend/migrations/027_add_notification_channel.sql
@@ -0,0 +1,8 @@
+-- Add notification_channel column to user_preferences table
+ALTER TABLE user_preferences ADD COLUMN IF NOT EXISTS notification_channel VARCHAR(10) NOT NULL DEFAULT 'email';
+
+-- Add apprise_notification_time column to user_preferences table
+ALTER TABLE user_preferences ADD COLUMN IF NOT EXISTS apprise_notification_time VARCHAR(5) NOT NULL DEFAULT '09:00';
+
+-- Add apprise_notification_frequency column to user_preferences table
+ALTER TABLE user_preferences ADD COLUMN IF NOT EXISTS apprise_notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily';
diff --git a/backend/migrations/028_fix_notification_columns.sql b/backend/migrations/028_fix_notification_columns.sql
new file mode 100644
index 0000000..958dc9f
--- /dev/null
+++ b/backend/migrations/028_fix_notification_columns.sql
@@ -0,0 +1,26 @@
+-- Migration 028: Fix missing notification columns
+-- Description: Ensure all required notification columns exist in user_preferences table
+
+-- Add notification_channel column if it doesn't exist
+DO $$
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='user_preferences' AND column_name='notification_channel') THEN
+ ALTER TABLE user_preferences ADD COLUMN notification_channel VARCHAR(10) NOT NULL DEFAULT 'email';
+ END IF;
+END $$;
+
+-- Add apprise_notification_time column if it doesn't exist
+DO $$
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='user_preferences' AND column_name='apprise_notification_time') THEN
+ ALTER TABLE user_preferences ADD COLUMN apprise_notification_time VARCHAR(5) NOT NULL DEFAULT '09:00';
+ END IF;
+END $$;
+
+-- Add apprise_notification_frequency column if it doesn't exist
+DO $$
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='user_preferences' AND column_name='apprise_notification_frequency') THEN
+ ALTER TABLE user_preferences ADD COLUMN apprise_notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily';
+ END IF;
+END $$;
\ No newline at end of file
diff --git a/backend/migrations/029_add_apprise_timezone.sql b/backend/migrations/029_add_apprise_timezone.sql
new file mode 100644
index 0000000..e39526c
--- /dev/null
+++ b/backend/migrations/029_add_apprise_timezone.sql
@@ -0,0 +1,10 @@
+-- Add the apprise_timezone column to the user_preferences table
+ALTER TABLE user_preferences
+ADD COLUMN apprise_timezone VARCHAR(50);
+
+-- Update existing rows to have a default value if the main timezone is set
+-- This ensures that users who have already configured a timezone will have it
+-- copied to the new Apprise-specific setting.
+UPDATE user_preferences
+SET apprise_timezone = timezone
+WHERE timezone IS NOT NULL;
diff --git a/backend/migrations/030_add_product_photo_path.sql b/backend/migrations/030_add_product_photo_path.sql
new file mode 100644
index 0000000..b9541b7
--- /dev/null
+++ b/backend/migrations/030_add_product_photo_path.sql
@@ -0,0 +1,7 @@
+-- Migration: Add product_photo_path column to warranties table
+-- This allows storing product photos for warranty cards
+
+ALTER TABLE warranties ADD COLUMN IF NOT EXISTS product_photo_path VARCHAR(255) DEFAULT NULL;
+
+-- Add index for better performance when filtering by photo existence
+CREATE INDEX IF NOT EXISTS idx_warranties_photo_path ON warranties(product_photo_path) WHERE product_photo_path IS NOT NULL;
\ No newline at end of file
diff --git a/backend/migrations/031_add_owner_role.sql b/backend/migrations/031_add_owner_role.sql
new file mode 100644
index 0000000..dc643f0
--- /dev/null
+++ b/backend/migrations/031_add_owner_role.sql
@@ -0,0 +1,48 @@
+-- Migration 031: Add the is_owner flag to the users table
+
+-- Add the is_owner column, defaulting to FALSE for all users.
+ALTER TABLE users ADD COLUMN IF NOT EXISTS is_owner BOOLEAN NOT NULL DEFAULT FALSE;
+
+-- Find the very first user created and promote them to be the initial application Owner
+-- This is a safe, one-time operation with robust fallbacks
+DO $$
+DECLARE
+ first_user_id INT;
+ owner_count INT;
+BEGIN
+ -- Check if any owner is currently set
+ SELECT COUNT(*) INTO owner_count FROM users WHERE is_owner = TRUE;
+
+ IF owner_count = 0 THEN
+ -- Try multiple strategies to find the first user
+
+ -- Strategy 1: Use created_at if available
+ SELECT id INTO first_user_id FROM users
+ WHERE created_at IS NOT NULL
+ ORDER BY created_at ASC, id ASC
+ LIMIT 1;
+
+ -- Strategy 2: Fallback to lowest ID if created_at approach fails
+ IF first_user_id IS NULL THEN
+ SELECT id INTO first_user_id FROM users ORDER BY id ASC LIMIT 1;
+ END IF;
+
+ -- Strategy 3: If still no user found, check for any admin user
+ IF first_user_id IS NULL THEN
+ SELECT id INTO first_user_id FROM users WHERE is_admin = TRUE ORDER BY id ASC LIMIT 1;
+ END IF;
+
+ -- If we found a user, make them the owner
+ IF first_user_id IS NOT NULL THEN
+ UPDATE users SET is_owner = TRUE WHERE id = first_user_id;
+ RAISE NOTICE 'Migration 031: User ID % has been set as the initial application owner.', first_user_id;
+ ELSE
+ RAISE NOTICE 'Migration 031: No users found, no owner set. The first user to register will become the owner.';
+ END IF;
+ ELSE
+ RAISE NOTICE 'Migration 031: An owner is already set (% owner(s) found). No changes made.', owner_count;
+ END IF;
+EXCEPTION
+ WHEN OTHERS THEN
+ RAISE NOTICE 'Migration 031: Error during owner promotion: %. Will be handled by application startup.', SQLERRM;
+END $$;
\ No newline at end of file
diff --git a/backend/migrations/032_add_apprise_notification_mode.sql b/backend/migrations/032_add_apprise_notification_mode.sql
new file mode 100644
index 0000000..3d3e662
--- /dev/null
+++ b/backend/migrations/032_add_apprise_notification_mode.sql
@@ -0,0 +1,8 @@
+-- Migration 032: Add Apprise notification mode setting
+
+-- Add the setting to control how Apprise notifications are sent.
+-- 'global': One summary notification for all expiring warranties.
+-- 'individual': Separate notifications sent to each user based on their preferences.
+INSERT INTO site_settings (key, value)
+VALUES ('apprise_notification_mode', 'global')
+ON CONFLICT (key) DO NOTHING;
\ No newline at end of file
diff --git a/backend/migrations/033_add_apprise_warranty_scope.sql b/backend/migrations/033_add_apprise_warranty_scope.sql
new file mode 100644
index 0000000..a4fa055
--- /dev/null
+++ b/backend/migrations/033_add_apprise_warranty_scope.sql
@@ -0,0 +1,8 @@
+-- Migration 033: Add Apprise warranty scope setting
+
+-- Add the setting to control which warranties are included in Apprise notifications.
+-- 'all': Include warranties from all users (current behavior).
+-- 'admin': Only include warranties belonging to the admin user.
+INSERT INTO site_settings (key, value)
+VALUES ('apprise_warranty_scope', 'all')
+ON CONFLICT (key) DO NOTHING;
\ No newline at end of file
diff --git a/backend/migrations/034_add_currency_position_column.sql b/backend/migrations/034_add_currency_position_column.sql
new file mode 100644
index 0000000..c8e02d7
--- /dev/null
+++ b/backend/migrations/034_add_currency_position_column.sql
@@ -0,0 +1,35 @@
+-- Migration: Add currency_position column to user_preferences
+-- This allows users to choose whether currency symbol appears on left or right of numbers
+
+-- Add currency_position column with default value 'left' to maintain existing behavior
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_name = 'user_preferences' AND column_name = 'currency_position'
+ ) THEN
+ ALTER TABLE user_preferences ADD COLUMN currency_position VARCHAR(10) DEFAULT 'left';
+ RAISE NOTICE 'Added currency_position column to user_preferences table';
+ ELSE
+ RAISE NOTICE 'currency_position column already exists in user_preferences table';
+ END IF;
+END $$;
+
+-- Update any existing NULL or invalid values to 'left' to ensure constraint compliance
+UPDATE user_preferences SET currency_position = 'left'
+WHERE currency_position IS NULL OR currency_position NOT IN ('left', 'right');
+
+-- Add constraint to ensure only valid values (only if constraint doesn't already exist)
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.table_constraints
+ WHERE constraint_name = 'chk_currency_position'
+ AND table_name = 'user_preferences'
+ ) THEN
+ ALTER TABLE user_preferences ADD CONSTRAINT chk_currency_position CHECK (currency_position IN ('left', 'right'));
+ RAISE NOTICE 'Added check constraint for currency_position column';
+ ELSE
+ RAISE NOTICE 'Check constraint for currency_position already exists';
+ END IF;
+END $$;
\ No newline at end of file
diff --git a/backend/migrations/035_add_currency_to_warranties.sql b/backend/migrations/035_add_currency_to_warranties.sql
new file mode 100644
index 0000000..93e6b55
--- /dev/null
+++ b/backend/migrations/035_add_currency_to_warranties.sql
@@ -0,0 +1,59 @@
+-- Migration: Add currency column to warranties table
+-- This allows each warranty to have its own currency instead of using the global currency symbol
+
+-- Add currency column with default value 'USD' to maintain compatibility
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_name = 'warranties' AND column_name = 'currency'
+ ) THEN
+ ALTER TABLE warranties ADD COLUMN currency VARCHAR(10) DEFAULT 'USD';
+ RAISE NOTICE 'Added currency column to warranties table';
+ ELSE
+ RAISE NOTICE 'currency column already exists in warranties table';
+ END IF;
+END $$;
+
+-- Set existing warranties to use USD as default currency
+UPDATE warranties SET currency = 'USD' WHERE currency IS NULL;
+
+-- Add check constraint to ensure valid currency codes (ISO 4217 standard)
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'chk_warranty_currency'
+ AND conrelid = 'warranties'::regclass
+ ) THEN
+ ALTER TABLE warranties ADD CONSTRAINT chk_warranty_currency
+ CHECK (currency IN (
+ 'USD', 'EUR', 'GBP', 'JPY', 'CNY', 'INR', 'KRW', 'CHF', 'CAD', 'AUD',
+ 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'HUF', 'BGN', 'RON', 'HRK', 'RUB',
+ 'BRL', 'MXN', 'ARS', 'CLP', 'COP', 'PEN', 'VES', 'ZAR', 'EGP', 'NGN',
+ 'KES', 'GHS', 'MAD', 'TND', 'AED', 'SAR', 'QAR', 'KWD', 'BHD', 'OMR',
+ 'JOD', 'LBP', 'ILS', 'TRY', 'IRR', 'PKR', 'BDT', 'LKR', 'NPR', 'BTN',
+ 'MMK', 'THB', 'VND', 'LAK', 'KHR', 'MYR', 'SGD', 'IDR', 'PHP', 'TWD',
+ 'HKD', 'MOP', 'KPW', 'MNT', 'KZT', 'UZS', 'TJS', 'KGS', 'TMT', 'AFN',
+ 'AMD', 'AZN', 'GEL', 'MDL', 'UAH', 'BYN', 'RSD', 'MKD', 'ALL', 'BAM',
+ 'ISK', 'FJD', 'PGK', 'SBD', 'TOP', 'VUV', 'WST', 'XPF', 'NZD'
+ ));
+ RAISE NOTICE 'Added check constraint for currency column';
+ ELSE
+ RAISE NOTICE 'Check constraint for currency already exists';
+ END IF;
+END $$;
+
+-- Add index for better performance when filtering by currency
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE indexname = 'idx_warranties_currency'
+ ) THEN
+ CREATE INDEX idx_warranties_currency ON warranties(currency);
+ RAISE NOTICE 'Added index for currency column';
+ ELSE
+ RAISE NOTICE 'Index for currency column already exists';
+ END IF;
+END $$;
\ No newline at end of file
diff --git a/backend/migrations/036_add_paperless_ngx_columns.sql b/backend/migrations/036_add_paperless_ngx_columns.sql
new file mode 100644
index 0000000..5e9fc1c
--- /dev/null
+++ b/backend/migrations/036_add_paperless_ngx_columns.sql
@@ -0,0 +1,14 @@
+-- Migration: Add Paperless-ngx document ID columns to warranties table
+-- This allows storing Paperless-ngx document IDs as an alternative to local file storage
+
+-- Add columns for storing Paperless-ngx document IDs
+ALTER TABLE warranties ADD COLUMN IF NOT EXISTS paperless_invoice_id INTEGER DEFAULT NULL;
+ALTER TABLE warranties ADD COLUMN IF NOT EXISTS paperless_manual_id INTEGER DEFAULT NULL;
+ALTER TABLE warranties ADD COLUMN IF NOT EXISTS paperless_photo_id INTEGER DEFAULT NULL;
+ALTER TABLE warranties ADD COLUMN IF NOT EXISTS paperless_other_id INTEGER DEFAULT NULL;
+
+-- Add indexes for better performance when filtering by Paperless-ngx document existence
+CREATE INDEX IF NOT EXISTS idx_warranties_paperless_invoice ON warranties(paperless_invoice_id) WHERE paperless_invoice_id IS NOT NULL;
+CREATE INDEX IF NOT EXISTS idx_warranties_paperless_manual ON warranties(paperless_manual_id) WHERE paperless_manual_id IS NOT NULL;
+CREATE INDEX IF NOT EXISTS idx_warranties_paperless_photo ON warranties(paperless_photo_id) WHERE paperless_photo_id IS NOT NULL;
+CREATE INDEX IF NOT EXISTS idx_warranties_paperless_other ON warranties(paperless_other_id) WHERE paperless_other_id IS NOT NULL;
\ No newline at end of file
diff --git a/backend/migrations/037_add_paperless_view_in_app_preference.sql b/backend/migrations/037_add_paperless_view_in_app_preference.sql
new file mode 100644
index 0000000..5e09e11
--- /dev/null
+++ b/backend/migrations/037_add_paperless_view_in_app_preference.sql
@@ -0,0 +1,8 @@
+-- Migration: Add paperless_view_in_app preference to user_preferences table
+-- This allows users to choose whether to view Paperless-ngx documents within Warracker or in the Paperless domain
+
+-- Add column for storing Paperless-ngx document viewing preference
+ALTER TABLE user_preferences ADD COLUMN IF NOT EXISTS paperless_view_in_app BOOLEAN DEFAULT FALSE;
+
+-- Add comment for documentation
+COMMENT ON COLUMN user_preferences.paperless_view_in_app IS 'Whether to view Paperless-ngx documents within Warracker interface instead of opening them in Paperless domain';
\ No newline at end of file
diff --git a/backend/migrations/038_add_preferred_language_column.sql b/backend/migrations/038_add_preferred_language_column.sql
new file mode 100644
index 0000000..ccb0d27
--- /dev/null
+++ b/backend/migrations/038_add_preferred_language_column.sql
@@ -0,0 +1,31 @@
+-- Migration: Add preferred_language column to users table
+-- Date: 2024-01-01
+-- Description: Add language preference support for internationalization
+
+-- Add preferred_language column to users table
+ALTER TABLE users
+ADD COLUMN IF NOT EXISTS preferred_language VARCHAR(5) DEFAULT 'en';
+
+-- Add index for better query performance
+CREATE INDEX IF NOT EXISTS idx_users_preferred_language ON users(preferred_language);
+
+-- Add constraint to ensure only valid language codes (with error handling)
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.table_constraints
+ WHERE constraint_name = 'chk_users_preferred_language'
+ AND table_name = 'users'
+ ) THEN
+ ALTER TABLE users
+ ADD CONSTRAINT chk_users_preferred_language
+ CHECK (preferred_language IN ('en', 'fr', 'es', 'de', 'it'));
+ END IF;
+END $$;
+
+COMMENT ON COLUMN users.preferred_language IS 'User preferred language for UI localization (ISO 639-1 code)';
+
+-- Set default language for existing users
+UPDATE users
+SET preferred_language = 'en'
+WHERE preferred_language IS NULL;
\ No newline at end of file
diff --git a/backend/migrations/039_update_language_constraint.sql b/backend/migrations/039_update_language_constraint.sql
new file mode 100644
index 0000000..b86b8c9
--- /dev/null
+++ b/backend/migrations/039_update_language_constraint.sql
@@ -0,0 +1,30 @@
+-- Migration: Update preferred_language constraint to include new languages
+-- Date: 2024-12-26
+-- Description: Update the constraint to allow new language codes: cs, nl, hi, fa, ar
+
+-- Drop the existing constraint
+DO $$
+BEGIN
+ IF EXISTS (
+ SELECT 1 FROM information_schema.table_constraints
+ WHERE constraint_name = 'chk_users_preferred_language'
+ AND table_name = 'users'
+ ) THEN
+ ALTER TABLE users DROP CONSTRAINT chk_users_preferred_language;
+ RAISE NOTICE 'Dropped existing preferred_language constraint';
+ ELSE
+ RAISE NOTICE 'preferred_language constraint does not exist, skipping drop';
+ END IF;
+END $$;
+
+-- Add updated constraint with all supported languages
+DO $$
+BEGIN
+ ALTER TABLE users
+ ADD CONSTRAINT chk_users_preferred_language
+ CHECK (preferred_language IN ('en', 'fr', 'es', 'de', 'it', 'cs', 'nl', 'hi', 'fa', 'ar'));
+ RAISE NOTICE 'Added updated preferred_language constraint with new languages';
+END $$;
+
+-- Update comment to reflect new supported languages
+COMMENT ON COLUMN users.preferred_language IS 'User preferred language for UI localization (ISO 639-1 code): en, fr, es, de, it, cs, nl, hi, fa, ar';
\ No newline at end of file
diff --git a/backend/migrations/041_update_language_constraint_again.py b/backend/migrations/041_update_language_constraint_again.py
new file mode 100644
index 0000000..0a3d4d7
--- /dev/null
+++ b/backend/migrations/041_update_language_constraint_again.py
@@ -0,0 +1,100 @@
+import os
+import sys
+import psycopg2
+
+# Add project root to the Python path
+project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
+sys.path.insert(0, project_root)
+
+try:
+ from backend.localization import SUPPORTED_LANGUAGES
+ from backend.db_handler import get_db_connection, release_db_connection
+except ImportError as e:
+ print(f"Error importing project modules: {e}")
+ # Provide a fallback for environments where the script is run directly
+ # This is a simplified example; a more robust solution might use a config file
+ SUPPORTED_LANGUAGES = ['en', 'fr', 'es', 'de', 'it', 'cs', 'nl', 'hi', 'fa', 'ar', 'ru', 'uk', 'zh_CN', 'zh_HK', 'ja', 'pt', 'ko']
+ # Define a dummy db_handler if not available
+ class DummyDBHandler:
+ def get_db_connection(self):
+ # This would need to be configured to connect to your database
+ # For example, using environment variables
+ return psycopg2.connect(
+ dbname=os.getenv("DB_NAME"),
+ user=os.getenv("DB_USER"),
+ password=os.getenv("DB_PASSWORD"),
+ host=os.getenv("DB_HOST")
+ )
+ def release_db_connection(self, conn):
+ if conn:
+ conn.close()
+ db_handler = DummyDBHandler()
+
+def apply_migration(conn):
+ """
+ Applies the database migration to update the language constraint.
+ """
+ cursor = conn.cursor()
+ try:
+ print("Applying migration: 040_update_language_constraint.py")
+
+ # Drop the existing constraint if it exists
+ print("Dropping existing constraint 'chk_users_preferred_language' if it exists...")
+ cursor.execute("""
+ DO $$
+ BEGIN
+ IF EXISTS (
+ SELECT 1 FROM information_schema.table_constraints
+ WHERE constraint_name = 'chk_users_preferred_language'
+ AND table_name = 'users'
+ ) THEN
+ ALTER TABLE users DROP CONSTRAINT chk_users_preferred_language;
+ RAISE NOTICE 'Dropped existing preferred_language constraint';
+ ELSE
+ RAISE NOTICE 'preferred_language constraint does not exist, skipping drop';
+ END IF;
+ END $$;
+ """)
+
+ # Create the new constraint dynamically
+ print("Creating new constraint with all supported languages...")
+ # Format the language list for the SQL IN clause
+ language_list_sql = ", ".join([f"'{lang}'" for lang in SUPPORTED_LANGUAGES])
+
+ constraint_sql = f"""
+ ALTER TABLE users
+ ADD CONSTRAINT chk_users_preferred_language
+ CHECK (preferred_language IN ({language_list_sql}));
+ """
+ cursor.execute(constraint_sql)
+ print("New constraint 'chk_users_preferred_language' created successfully.")
+
+ # Update the comment on the column
+ print("Updating column comment...")
+ comment_sql = f"""
+ COMMENT ON COLUMN users.preferred_language IS 'User preferred language for UI localization (ISO 639-1 code): {', '.join(SUPPORTED_LANGUAGES)}';
+ """
+ cursor.execute(comment_sql)
+ print("Column comment updated successfully.")
+
+ conn.commit()
+ print("Migration 040_update_language_constraint.py applied successfully.")
+ except Exception as e:
+ conn.rollback()
+ print(f"Error applying migration 040_update_language_constraint.py: {e}")
+ raise
+ finally:
+ cursor.close()
+
+if __name__ == "__main__":
+ # This allows the script to be run directly
+ connection = None
+ try:
+ # In a real application, you would get the connection details from a config file or environment variables
+ connection = db_handler.get_db_connection()
+ apply_migration(connection)
+ except Exception as e:
+ print(f"Migration failed: {e}")
+ finally:
+ if connection:
+ db_handler.release_db_connection(connection)
diff --git a/backend/migrations/042_allow_higher_duration_components.sql b/backend/migrations/042_allow_higher_duration_components.sql
new file mode 100644
index 0000000..f8aa81e
--- /dev/null
+++ b/backend/migrations/042_allow_higher_duration_components.sql
@@ -0,0 +1,13 @@
+-- Migration: Allow higher values for warranty duration months and days
+
+DO $$
+BEGIN
+ ALTER TABLE warranties DROP CONSTRAINT IF EXISTS chk_warranty_duration_months;
+ ALTER TABLE warranties ADD CONSTRAINT chk_warranty_duration_months CHECK (warranty_duration_months >= 0);
+
+ ALTER TABLE warranties DROP CONSTRAINT IF EXISTS chk_warranty_duration_days;
+ ALTER TABLE warranties ADD CONSTRAINT chk_warranty_duration_days CHECK (warranty_duration_days >= 0);
+
+ ALTER TABLE warranties DROP CONSTRAINT IF EXISTS chk_warranty_duration_years;
+ ALTER TABLE warranties ADD CONSTRAINT chk_warranty_duration_years CHECK (warranty_duration_years >= 0);
+END $$;
\ No newline at end of file
diff --git a/backend/migrations/apply_migrations.py b/backend/migrations/apply_migrations.py
index d1092c6..9ff92a2 100644
--- a/backend/migrations/apply_migrations.py
+++ b/backend/migrations/apply_migrations.py
@@ -115,22 +115,29 @@ def apply_migrations():
with open(migration_file, 'r') as f:
sql = f.read()
- cur.execute(
- sql,
- {
- "db_name": AsIs(DB_NAME),
- "db_user": AsIs(DB_USER),
- "db_admin_user": AsIs(DB_ADMIN_USER),
- "db_admin_password": AsIs(DB_ADMIN_PASSWORD),
- }
- )
+ # Check if the SQL has placeholders before passing parameters
+ if any(placeholder in sql for placeholder in ['%(db_name)s', '%(db_user)s', '%(db_admin_user)s', '%(db_admin_password)s']):
+ cur.execute(
+ sql,
+ {
+ "db_name": AsIs(DB_NAME),
+ "db_user": AsIs(DB_USER),
+ "db_admin_user": AsIs(DB_ADMIN_USER),
+ "db_admin_password": AsIs(DB_ADMIN_PASSWORD),
+ }
+ )
+ else:
+ # No placeholders, execute directly
+ cur.execute(sql)
elif migration_file.endswith('.py'):
# Apply Python migration
migration_module = load_python_migration(migration_file)
- if hasattr(migration_module, 'upgrade'):
+ if hasattr(migration_module, 'apply_migration'):
+ migration_module.apply_migration(conn)
+ elif hasattr(migration_module, 'upgrade'):
migration_module.upgrade(cur)
else:
- logger.warning(f"Python migration {filename} does not have an upgrade function, skipping.")
+ logger.warning(f"Python migration {filename} does not have an apply_migration or upgrade function, skipping.")
continue
# Record the migration as applied
@@ -165,4 +172,4 @@ if __name__ == "__main__":
logger.info("Migrations completed successfully")
except Exception as e:
logger.error(f"Migration process failed: {e}")
- sys.exit(1)
+ sys.exit(1)
diff --git a/backend/notifications.py b/backend/notifications.py
new file mode 100644
index 0000000..0e28fe1
--- /dev/null
+++ b/backend/notifications.py
@@ -0,0 +1,808 @@
+"""
+Warranty Expiration Notification System
+Updated: 2025-01-24 - Fixed scheduler initialization in application factory
+
+This module handles all notification-related functionality for the Warracker application,
+including email notifications, scheduling, and Apprise integration.
+"""
+
+import os
+import threading
+import time
+import atexit
+import smtplib
+import logging
+from datetime import datetime, date, timedelta
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+from threading import Lock
+from decimal import Decimal
+
+import pytz
+from pytz import timezone as pytz_timezone
+from flask import current_app
+
+try:
+ from apscheduler.schedulers.background import BackgroundScheduler
+ BACKGROUND_SCHEDULER_AVAILABLE = True
+except ImportError:
+ BACKGROUND_SCHEDULER_AVAILABLE = False
+ BackgroundScheduler = None
+
+try:
+ from apscheduler.schedulers.gevent import GeventScheduler
+ GEVENT_SCHEDULER_AVAILABLE = True
+except ImportError:
+ GEVENT_SCHEDULER_AVAILABLE = False
+ GeventScheduler = None
+
+# Import database functions
+try:
+ from .db_handler import get_site_setting
+ DB_HANDLER_IMPORTED = True
+except ImportError:
+ try:
+ from db_handler import get_site_setting
+ DB_HANDLER_IMPORTED = True
+ except ImportError:
+ DB_HANDLER_IMPORTED = False
+ def get_site_setting(key, default=None):
+ return default
+
+# Configure logging
+logger = logging.getLogger(__name__)
+
+# Global variables for notification management
+notification_lock = threading.Lock()
+last_notification_sent = {}
+scheduler = None
+scheduler_initialized = False
+scheduler_retry_attempted = False
+
+# Apprise integration (will be set by app.py if available)
+APPRISE_AVAILABLE = False
+apprise_handler = None
+
+def set_apprise_handler(handler):
+ """Set the Apprise handler if available"""
+ global APPRISE_AVAILABLE, apprise_handler
+ APPRISE_AVAILABLE = handler is not None
+ apprise_handler = handler
+
+def get_expiring_warranties(get_db_connection, release_db_connection):
+ """Get warranties that are expiring soon for notification purposes"""
+ conn = None
+ try:
+ # Add retry logic for database connections in scheduled context
+ max_retries = 3
+ retry_delay = 2
+
+ for attempt in range(max_retries):
+ try:
+ conn = get_db_connection()
+ # Test the connection
+ with conn.cursor() as test_cur:
+ test_cur.execute("SELECT 1")
+ test_cur.fetchone()
+ break # Connection is good, exit retry loop
+ except Exception as conn_error:
+ logger.warning(f"Database connection attempt {attempt + 1} failed in get_expiring_warranties: {conn_error}")
+ if conn:
+ try:
+ release_db_connection(conn)
+ except:
+ pass
+ conn = None
+
+ if attempt < max_retries - 1:
+ logger.info(f"Retrying database connection in {retry_delay} seconds...")
+ time.sleep(retry_delay)
+ else:
+ logger.error("All database connection attempts failed in get_expiring_warranties")
+ return []
+
+ today = date.today()
+
+ with conn.cursor() as cur:
+ cur.execute("""
+ SELECT
+ u.id, -- Select user_id
+ u.email,
+ u.first_name,
+ w.product_name,
+ w.expiration_date,
+ COALESCE(up.expiring_soon_days, 30) AS expiring_soon_days
+ FROM
+ warranties w
+ JOIN
+ users u ON w.user_id = u.id
+ LEFT JOIN
+ user_preferences up ON u.id = up.user_id
+ WHERE
+ w.is_lifetime = FALSE
+ AND w.expiration_date > %s
+ AND w.expiration_date <= (%s::date + (COALESCE(up.expiring_soon_days, 30) || ' days')::interval)::date
+ AND u.is_active = TRUE;
+ """, (today, today))
+
+ expiring_warranties = []
+ for row in cur.fetchall():
+ user_id, email, first_name, product_name, expiration_date, expiring_soon_days = row
+ expiration_date_str = expiration_date.strftime('%Y-%m-%d')
+ expiring_warranties.append({
+ 'user_id': user_id,
+ 'email': email,
+ 'first_name': first_name or 'User', # Default if first_name is NULL
+ 'product_name': product_name,
+ 'expiration_date': expiration_date_str,
+ })
+
+ return expiring_warranties
+
+ except Exception as e:
+ logger.error(f"Error retrieving expiring warranties: {e}")
+ return [] # Return an empty list on error
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+def format_expiration_email(user, warranties, get_db_connection, release_db_connection):
+ """
+ Format an email notification for expiring warranties.
+ Returns a MIMEMultipart email object with both text and HTML versions.
+ """
+ subject = "Warracker: Upcoming Warranty Expirations"
+
+ # Get email base URL from settings with correct precedence
+ # Priority: Environment Variable > Database Setting > Hardcoded Default
+ email_base_url = os.environ.get('APP_BASE_URL')
+ if email_base_url is None:
+ # Fall back to database setting if environment variable is not set
+ conn = None
+ email_base_url = 'http://localhost:8080' # Default fallback
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ cur.execute("SELECT value FROM site_settings WHERE key = 'email_base_url'")
+ result = cur.fetchone()
+ if result:
+ email_base_url = result[0]
+ else:
+ logger.warning("email_base_url setting not found, using default.")
+ except Exception as e:
+ logger.error(f"Error fetching email_base_url from settings: {e}. Using default.")
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+ # Ensure base URL doesn't end with a slash
+ email_base_url = email_base_url.rstrip('/')
+
+ # Create both plain text and HTML versions of the email body
+ text_body = f"Hello {user['first_name']},\\n\\n"
+ text_body += "The following warranties are expiring soon:\\n\\n"
+
+ html_body = f"""\
+ <html>
+ <head></head>
+ <body>
+ <p>Hello {user['first_name']},</p>
+ <p>The following warranties are expiring soon:</p>
+ <table border="1" style="border-collapse: collapse;">
+ <thead>
+ <tr>
+ <th style="padding: 8px; text-align: left;">Product Name</th>
+ <th style="padding: 8px; text-align: left;">Expiration Date</th>
+ </tr>
+ </thead>
+ <tbody>
+ """
+
+ for warranty in warranties:
+ text_body += f"- {warranty['product_name']} (expires on {warranty['expiration_date']})\\n"
+ html_body += f"""\
+ <tr>
+ <td style="padding: 8px;">{warranty['product_name']}</td>
+ <td style="padding: 8px;">{warranty['expiration_date']}</td>
+ </tr>
+ """
+
+ text_body += "\\nLog in to Warracker to view details:\\n"
+ text_body += f"{email_base_url}\\n\\n"
+ text_body += "Manage your notification settings:\\n"
+ text_body += f"{email_base_url}/settings-new.html\\n"
+
+ html_body += f"""\
+ </tbody>
+ </table>
+ <p>Log in to <a href="{email_base_url}">Warracker</a> to view details.</p>
+ <p>Manage your notification settings <a href="{email_base_url}/settings-new.html">here</a>.</p>
+ </body>
+ </html>
+ """
+
+ # Create a MIMEMultipart object for both text and HTML
+ msg = MIMEMultipart('alternative')
+ msg['Subject'] = subject
+ # use SMTP_FROM_ADDRESS if provided, otherwise use SMTP_USERNAME or a default value as below
+ _from_address = os.environ.get('SMTP_FROM_ADDRESS')
+ if _from_address is None:
+ _from_address = os.environ.get('SMTP_USERNAME', '[email protected]')
+ msg['From'] = _from_address
+ msg['To'] = user['email']
+
+ part1 = MIMEText(text_body, 'plain')
+ part2 = MIMEText(html_body, 'html')
+
+ msg.attach(part1)
+ msg.attach(part2)
+
+ return msg
+
+def is_notification_due(utc_now, notification_time, timezone, channel_name, user_id):
+ """Check if a notification is due for a user based on their timezone and preferences"""
+ try:
+ user_tz = pytz_timezone(timezone or 'UTC')
+ user_local_time = utc_now.replace(tzinfo=pytz.UTC).astimezone(user_tz)
+ time_hour, time_minute = map(int, notification_time.split(':'))
+
+ user_minutes = time_hour * 60 + time_minute
+ current_minutes = user_local_time.hour * 60 + user_local_time.minute
+ time_diff = current_minutes - user_minutes
+
+ # Handle day rollovers
+ if time_diff < -720: # More than 12 hours behind, probably crossed midnight
+ time_diff += 1440
+ elif time_diff > 720: # More than 12 hours ahead, probably went backward over midnight
+ time_diff -= 1440
+
+ if 0 <= time_diff <= 2:
+ current_date = user_local_time.strftime('%Y-%m-%d')
+ last_sent_key = f"{channel_name}_{user_id}_{current_date}"
+ if last_sent_key not in last_notification_sent:
+ last_notification_sent[last_sent_key] = True
+ logger.info(f"User {user_id} eligible for {channel_name} notification at their local time {notification_time} ({timezone}). Time diff: {time_diff} minutes")
+ return True
+ except Exception as e:
+ logger.error(f"Error processing timezone for user {user_id}: {e}")
+ return False
+
+def process_email_notifications(all_warranties, eligible_user_ids, is_manual, get_db_connection, release_db_connection):
+ """Process and send email notifications"""
+ logger.info(f"Processing email notifications for {len(eligible_user_ids)} eligible users")
+
+ # Group warranties by user
+ users_warranties = {}
+ for warranty in all_warranties:
+ user_id = warranty['user_id']
+ email = warranty['email']
+
+ # Check if user should receive notifications
+ if not is_manual and user_id not in eligible_user_ids:
+ continue
+
+ if email not in users_warranties:
+ users_warranties[email] = {
+ 'user_id': user_id,
+ 'first_name': warranty['first_name'],
+ 'warranties': []
+ }
+ users_warranties[email]['warranties'].append(warranty)
+
+ if not users_warranties:
+ logger.info("No users to notify via email")
+ return
+
+ # Get SMTP settings from environment variables
+ smtp_host = os.environ.get('SMTP_HOST', 'localhost')
+ smtp_port = int(os.environ.get('SMTP_PORT', '1025'))
+ smtp_username = os.environ.get('SMTP_USERNAME', '[email protected]')
+ smtp_password = os.environ.get('SMTP_PASSWORD', '')
+ smtp_use_tls_env = os.environ.get('SMTP_USE_TLS', 'not_set').lower()
+
+ # For manual triggers, check email preferences
+ email_enabled_users = set()
+ if is_manual:
+ conn_manual = None
+ try:
+ conn_manual = get_db_connection()
+ with conn_manual.cursor() as cur:
+ cur.execute("""
+ SELECT column_name FROM information_schema.columns
+ WHERE table_name='user_preferences' AND column_name='notification_channel'
+ """)
+ has_channel_column = bool(cur.fetchone())
+
+ if has_channel_column:
+ cur.execute("""
+ SELECT DISTINCT u.id
+ FROM users u
+ JOIN user_preferences up ON u.id = up.user_id
+ WHERE u.is_active = TRUE
+ AND up.notification_channel IN ('email', 'both')
+ """)
+ email_enabled_users = set(row[0] for row in cur.fetchall())
+ else:
+ email_enabled_users = set(user_data.get('user_id') for user_data in users_warranties.values())
+ except Exception as e:
+ logger.error(f"Error checking email preferences for manual trigger: {e}")
+ email_enabled_users = set(user_data.get('user_id') for user_data in users_warranties.values())
+ finally:
+ if conn_manual:
+ release_db_connection(conn_manual)
+
+ # Send emails
+ try:
+ logger.info(f"Attempting SMTP connection to {smtp_host}:{smtp_port}")
+ if smtp_port == 465:
+ server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=10)
+ else:
+ server = smtplib.SMTP(smtp_host, smtp_port, timeout=10)
+
+ should_use_starttls = False
+ if smtp_port == 587:
+ should_use_starttls = (smtp_use_tls_env != 'false')
+ elif smtp_use_tls_env == 'true':
+ should_use_starttls = True
+
+ if should_use_starttls:
+ server.starttls()
+
+ if smtp_username and smtp_password:
+ server.login(smtp_username, smtp_password)
+
+ emails_sent = 0
+ utc_now = datetime.utcnow()
+ timestamp = int(utc_now.timestamp())
+
+ for email, user_data in users_warranties.items():
+ user_id_to_check = user_data.get('user_id')
+
+ # For manual triggers, check if user has email notifications enabled
+ if is_manual and user_id_to_check not in email_enabled_users:
+ continue
+
+ # For manual triggers, check if we've sent recently
+ if is_manual and email in last_notification_sent:
+ last_sent = last_notification_sent[email]
+ if timestamp - last_sent < 120:
+ continue
+
+ msg = format_expiration_email(
+ {'first_name': user_data['first_name'], 'email': email},
+ user_data['warranties'],
+ get_db_connection,
+ release_db_connection
+ )
+ try:
+ server.sendmail(smtp_username, email, msg.as_string())
+ last_notification_sent[email] = timestamp
+ emails_sent += 1
+ logger.info(f"Email sent to {email} for {len(user_data['warranties'])} warranties")
+ except Exception as e:
+ logger.error(f"Error sending email to {email}: {e}")
+
+ logger.info(f"Email process completed. Sent {emails_sent} emails")
+ server.quit()
+
+ except Exception as e:
+ logger.error(f"Error connecting to SMTP server: {e}")
+
+def process_apprise_notifications(all_warranties, eligible_user_ids, is_manual, get_db_connection, release_db_connection):
+ """Process and send Apprise notifications"""
+ # ---> FIX: Get the handler from the application context <---
+ apprise_handler = current_app.config.get('APPRISE_HANDLER')
+
+ if not apprise_handler:
+ logger.info("Apprise handler not found in app config, skipping Apprise notifications.")
+ return
+
+ if is_manual:
+ logger.debug("Manual trigger: Skipping Apprise notifications (use dedicated Apprise endpoint for manual Apprise notifications)")
+ return
+
+ logger.info(f"Processing Apprise notifications for {len(eligible_user_ids)} eligible users.")
+
+ try:
+ # Reload configuration to ensure we have the latest settings from the database
+ apprise_handler.reload_configuration()
+
+ if not apprise_handler.is_available():
+ logger.info("Apprise is not enabled or configured, skipping.")
+ return
+
+ if not eligible_user_ids:
+ logger.info("No users eligible for Apprise notifications")
+ return
+
+ # Filter warranties for eligible users
+ warranties_for_apprise = [w for w in all_warranties if w['user_id'] in eligible_user_ids]
+
+ if not warranties_for_apprise:
+ logger.info("No expiring warranties for Apprise-eligible users.")
+ return
+
+ # Get the Apprise notification settings
+ notification_mode = get_site_setting('apprise_notification_mode', 'global')
+ warranty_scope = get_site_setting('apprise_warranty_scope', 'all')
+ logger.info(f"Apprise notification mode set to: '{notification_mode}', warranty scope: '{warranty_scope}'")
+
+ # Apply warranty scope filtering
+ if warranty_scope == 'admin':
+ admin_user_id = None
+ conn_scope = None
+ try:
+ conn_scope = get_db_connection()
+ with conn_scope.cursor() as cur:
+ cur.execute("SELECT id FROM users WHERE is_owner = TRUE LIMIT 1")
+ owner_result = cur.fetchone()
+ if owner_result:
+ admin_user_id = owner_result[0]
+ else:
+ cur.execute("SELECT id FROM users WHERE is_admin = TRUE ORDER BY id LIMIT 1")
+ admin_result = cur.fetchone()
+ if admin_result:
+ admin_user_id = admin_result[0]
+ except Exception as e:
+ logger.error(f"Error finding admin user ID for warranty scope filtering: {e}")
+ finally:
+ if conn_scope:
+ release_db_connection(conn_scope)
+
+ if admin_user_id:
+ original_count = len(warranties_for_apprise)
+ warranties_for_apprise = [w for w in warranties_for_apprise if w['user_id'] == admin_user_id]
+ logger.info(f"Warranty scope 'admin': Filtered from {original_count} to {len(warranties_for_apprise)} warranties")
+ else:
+ logger.warning("Warranty scope 'admin' requested but no admin user found, including all warranties")
+
+ if not warranties_for_apprise:
+ logger.info("No expiring warranties after scope filtering")
+ return
+
+ logger.info(f"Processing Apprise notifications in {notification_mode.upper()} mode for {len(warranties_for_apprise)} warranties")
+
+ if notification_mode == 'global':
+ # GLOBAL MODE: Send one consolidated notification
+ logger.info("Sending GLOBAL Apprise notification")
+ success = apprise_handler.send_global_expiration_notification(warranties_for_apprise)
+ logger.info(f"Global Apprise notification result: {'Success' if success else 'Failed'}")
+
+ elif notification_mode == 'individual':
+ # INDIVIDUAL MODE: Send one notification per user
+ logger.info("Sending INDIVIDUAL Apprise notifications")
+ sent_count = 0
+ error_count = 0
+
+ # Group warranties by user
+ user_warranties = {}
+ for w in warranties_for_apprise:
+ uid = w['user_id']
+ if uid not in user_warranties:
+ user_warranties[uid] = []
+ user_warranties[uid].append(w)
+
+ # Send notification for each user
+ for user_id, warranties in user_warranties.items():
+ try:
+ success = apprise_handler.send_individual_expiration_notification(user_id, warranties, get_db_connection, release_db_connection)
+ if success:
+ sent_count += 1
+ logger.info(f"Individual Apprise notification sent for user {user_id}")
+ else:
+ error_count += 1
+ logger.warning(f"Individual Apprise notification failed for user {user_id}")
+ except Exception as e:
+ logger.error(f"Error sending individual Apprise notification for user {user_id}: {e}")
+ error_count += 1
+
+ logger.info(f"Individual Apprise notifications completed: {sent_count} sent, {error_count} errors")
+
+ else:
+ logger.warning(f"Unknown Apprise notification mode: '{notification_mode}'. Skipping Apprise notifications.")
+
+ except Exception as e:
+ logger.error(f"Error sending Apprise notifications: {e}")
+
+def send_expiration_notifications(manual_trigger=False, get_db_connection=None, release_db_connection=None):
+ """
+ Main function to send warranty expiration notifications.
+ Refactored for better separation of email and Apprise notification logic.
+ Now properly manages database connections for the entire job execution.
+
+ Args:
+ manual_trigger (bool): Whether this function was triggered manually (vs scheduled)
+ get_db_connection: Database connection function
+ release_db_connection: Database connection release function
+ """
+ if get_db_connection is None or release_db_connection is None:
+ logger.error("Database connection functions not provided")
+ return
+
+ if not notification_lock.acquire(blocking=False):
+ logger.info("Notification job already running, skipping")
+ return
+
+ conn = None
+ try:
+ logger.info("Starting expiration notification process")
+ # Acquire a fresh database connection for this entire job run
+ conn = get_db_connection()
+
+ users_to_notify_email = set()
+ users_to_notify_apprise = set()
+
+ if not manual_trigger:
+ with conn.cursor() as cur:
+ utc_now = datetime.utcnow()
+
+ # Check if required columns exist for dynamic query building
+ cur.execute("""
+ SELECT column_name FROM information_schema.columns
+ WHERE table_name='user_preferences'
+ AND column_name IN ('notification_channel', 'apprise_notification_time', 'apprise_timezone')
+ """)
+ existing_columns = [row[0] for row in cur.fetchall()]
+
+ has_notification_channel = 'notification_channel' in existing_columns
+ has_apprise_notification_time = 'apprise_notification_time' in existing_columns
+ has_apprise_timezone = 'apprise_timezone' in existing_columns
+
+ # Build dynamic query based on available columns
+ select_fields = [
+ "u.id",
+ "u.email",
+ "up.notification_time",
+ "up.timezone",
+ "up.notification_frequency"
+ ]
+
+ if has_apprise_notification_time:
+ select_fields.append("up.apprise_notification_time")
+ else:
+ select_fields.append("up.notification_time as apprise_notification_time")
+
+ if has_apprise_timezone:
+ select_fields.append("up.apprise_timezone")
+ else:
+ select_fields.append("up.timezone as apprise_timezone")
+
+ if has_notification_channel:
+ select_fields.append("up.notification_channel")
+ where_clause = "WHERE u.is_active = TRUE AND up.notification_channel != 'none'"
+ else:
+ select_fields.append("'email' as notification_channel")
+ where_clause = "WHERE u.is_active = TRUE"
+
+ query = f"""
+ SELECT {', '.join(select_fields)}
+ FROM users u
+ JOIN user_preferences up ON u.id = up.user_id
+ {where_clause}
+ """
+ cur.execute(query)
+ eligible_users = cur.fetchall()
+
+ for user in eligible_users:
+ try:
+ user_id, email, email_time, tz, frequency, apprise_time, apprise_tz, channel = user
+
+ # Check Email Eligibility
+ if channel in ['email', 'both']:
+ # Check frequency
+ should_send = False
+ user_tz = pytz_timezone(tz or 'UTC')
+ user_local_time = utc_now.replace(tzinfo=pytz.UTC).astimezone(user_tz)
+
+ if frequency == 'daily':
+ should_send = True
+ elif frequency == 'weekly' and user_local_time.weekday() == 0:
+ should_send = True
+ elif frequency == 'monthly' and user_local_time.day == 1:
+ should_send = True
+
+ if should_send and is_notification_due(utc_now, email_time, tz, 'email', user_id):
+ users_to_notify_email.add(user_id)
+
+ # Check Apprise Eligibility
+ if channel in ['apprise', 'both']:
+ # Use separate frequency check for Apprise if available
+ should_send_apprise = True # Default to daily for now
+ if is_notification_due(utc_now, apprise_time, apprise_tz or tz, 'apprise', user_id):
+ users_to_notify_apprise.add(user_id)
+
+ except Exception as e:
+ logger.error(f"Error processing user {user}: {e}")
+ continue
+
+ if not users_to_notify_email and not users_to_notify_apprise and not manual_trigger:
+ logger.info("No users are scheduled for notifications at this time")
+ return
+
+ # Get expiring warranties using the connection functions
+ expiring_warranties = get_expiring_warranties(get_db_connection, release_db_connection)
+ if not expiring_warranties:
+ logger.info("No expiring warranties found.")
+ return
+
+ # --- Process Email Notifications ---
+ if manual_trigger or users_to_notify_email:
+ process_email_notifications(expiring_warranties, users_to_notify_email, manual_trigger, get_db_connection, release_db_connection)
+
+ # --- Process Apprise Notifications ---
+ if manual_trigger or users_to_notify_apprise:
+ process_apprise_notifications(expiring_warranties, users_to_notify_apprise, manual_trigger, get_db_connection, release_db_connection)
+
+ except Exception as e:
+ logger.error(f"Error in send_expiration_notifications: {e}")
+ finally:
+ # Ensure the connection is always released
+ if conn:
+ release_db_connection(conn)
+ notification_lock.release()
+
+def should_run_scheduler():
+ """Check if this is the main process that should run the scheduler."""
+ # This environment variable is set by the post_fork hook in gunicorn_config.py
+ worker_id = os.environ.get('GUNICORN_WORKER_ID')
+
+ # Case 1: Multi-worker environment (e.g., 'optimized', 'performance' modes).
+ # The worker_id is explicitly set. Only worker '0' should run the scheduler.
+ if worker_id is not None:
+ if worker_id == '0':
+ logger.info(f"✅ Scheduler will run in this primary worker (ID: {worker_id}).")
+ return True
+ else:
+ logger.info(f"ℹ️ Scheduler will NOT run in this secondary worker (ID: {worker_id}).")
+ return False
+
+ # Case 2: Single-worker environment (e.g., 'ultra-light' mode or Flask dev server).
+ # The worker_id is not set (is None). In this case, the single worker must run the scheduler.
+ logger.info(f"✅ Scheduler will run: Single-worker environment detected (Worker ID not set).")
+ return True
+
+def init_scheduler(app, get_db_connection, release_db_connection):
+ """Initialize the scheduler if this is the appropriate worker"""
+ global scheduler, scheduler_initialized
+
+ if should_run_scheduler():
+ try:
+ # Initialize scheduler if not already done
+ if scheduler is None:
+ # First try GeventScheduler if gevent is available and we're in a gevent worker
+ worker_class = os.environ.get('GUNICORN_WORKER_CLASS', '')
+
+ if GEVENT_SCHEDULER_AVAILABLE and worker_class == 'gevent':
+ try:
+ scheduler = GeventScheduler(
+ job_defaults={
+ 'coalesce': True,
+ 'max_instances': 1,
+ 'misfire_grace_time': 300
+ }
+ )
+ logger.info("Using GeventScheduler for gevent worker compatibility")
+ except Exception as gevent_error:
+ logger.warning(f"Failed to initialize GeventScheduler: {gevent_error}")
+ logger.info("Falling back to BackgroundScheduler")
+ if BACKGROUND_SCHEDULER_AVAILABLE:
+ scheduler = BackgroundScheduler(
+ job_defaults={
+ 'coalesce': True,
+ 'max_instances': 1,
+ 'misfire_grace_time': 300
+ }
+ )
+ logger.info("Using BackgroundScheduler (GeventScheduler fallback)")
+ else:
+ logger.error("BackgroundScheduler not available for fallback")
+ return False
+ else:
+ if BACKGROUND_SCHEDULER_AVAILABLE:
+ scheduler = BackgroundScheduler(
+ job_defaults={
+ 'coalesce': True,
+ 'max_instances': 1,
+ 'misfire_grace_time': 300
+ }
+ )
+ if worker_class == 'gevent':
+ logger.info("Using BackgroundScheduler with gevent worker (GeventScheduler not available)")
+ else:
+ logger.info(f"Using BackgroundScheduler with {worker_class} worker")
+ else:
+ logger.error("No scheduler available (BackgroundScheduler not found)")
+ return False
+
+ # ---> FIX: Create a wrapper that pushes an app context <---
+ def notification_job_with_context():
+ with app.app_context():
+ send_expiration_notifications(
+ manual_trigger=False,
+ get_db_connection=get_db_connection,
+ release_db_connection=release_db_connection
+ )
+
+ # Schedule the new context-aware wrapper
+ scheduler.add_job(func=notification_job_with_context, trigger="interval", minutes=2, id='notification_job')
+ scheduler.start()
+ logger.info("✅ Notification scheduler started - checking every 2 minutes")
+
+ # Add a shutdown hook
+ atexit.register(lambda: scheduler.shutdown())
+ scheduler_initialized = True
+ return True
+ except Exception as e:
+ logger.error(f"❌ Failed to start scheduler: {e}")
+ scheduler_initialized = False
+ return False
+ else:
+ logger.info("ℹ️ Scheduler not started in this worker")
+ scheduler_initialized = False
+ return False
+
+def ensure_scheduler_initialized(get_db_connection, release_db_connection):
+ """Ensure scheduler is initialized on the first request if it wasn't at startup"""
+ global scheduler_initialized, scheduler_retry_attempted
+ if not scheduler_initialized and not scheduler_retry_attempted:
+ logger.info("Retrying scheduler initialization on first request...")
+ scheduler_initialized = init_scheduler(get_db_connection, release_db_connection)
+ scheduler_retry_attempted = True
+
+def get_scheduler_status():
+ """Get current scheduler status for admin endpoints"""
+ global scheduler_initialized, scheduler_retry_attempted
+
+ worker_id = os.environ.get('GUNICORN_WORKER_ID', 'unknown')
+ worker_name = os.environ.get('GUNICORN_WORKER_PROCESS_NAME', 'unknown')
+ worker_class = os.environ.get('GUNICORN_WORKER_CLASS', 'unknown')
+
+ scheduler_jobs = []
+ scheduler_running = False
+
+ if scheduler and hasattr(scheduler, 'get_jobs'):
+ try:
+ jobs = scheduler.get_jobs()
+ scheduler_running = scheduler.running
+ scheduler_jobs = [
+ {
+ 'id': job.id,
+ 'next_run_time': job.next_run_time.isoformat() if job.next_run_time else None,
+ 'trigger': str(job.trigger)
+ }
+ for job in jobs
+ ]
+ except Exception as e:
+ logger.error(f"Error getting scheduler jobs: {e}")
+
+ return {
+ 'scheduler_initialized': scheduler_initialized,
+ 'scheduler_retry_attempted': scheduler_retry_attempted,
+ 'scheduler_running': scheduler_running,
+ 'scheduler_jobs': scheduler_jobs,
+ 'worker_info': {
+ 'worker_id': worker_id,
+ 'worker_name': worker_name,
+ 'worker_class': worker_class,
+ 'should_run_scheduler': should_run_scheduler()
+ },
+ 'environment_vars': {
+ key: value for key, value in os.environ.items()
+ if key.startswith('GUNICORN_') or key in ['WARRACKER_MEMORY_MODE']
+ }
+ }
+
+def trigger_notifications_manually(get_db_connection, release_db_connection):
+ """Manually trigger warranty expiration notifications"""
+ try:
+ logger.info("Manual notification trigger requested")
+ send_expiration_notifications(
+ manual_trigger=True,
+ get_db_connection=get_db_connection,
+ release_db_connection=release_db_connection
+ )
+ return {'message': 'Notifications triggered successfully'}, 200
+ except Exception as e:
+ error_msg = f"Error triggering notifications: {str(e)}"
+ logger.error(error_msg)
+ return {'message': 'Failed to trigger notifications', 'error': error_msg}, 500
diff --git a/backend/oidc_handler.py b/backend/oidc_handler.py
new file mode 100644
index 0000000..26f6c24
--- /dev/null
+++ b/backend/oidc_handler.py
@@ -0,0 +1,285 @@
+# backend/oidc_handler.py
+import os
+import uuid
+from datetime import datetime # Ensure timedelta is imported if used, though not in this snippet
+from flask import Blueprint, jsonify, redirect, url_for, current_app, request, session
+
+# Import shared extensions and utilities
+try:
+ # Try relative imports (when modules are in same directory)
+ from .extensions import oauth
+ from .db_handler import get_db_connection, release_db_connection
+ from .auth_utils import generate_token
+except ImportError:
+ # Fallback to direct imports
+ from extensions import oauth
+ from db_handler import get_db_connection, release_db_connection
+ from auth_utils import generate_token
+
+import logging
+logger = logging.getLogger(__name__) # Or use current_app.logger inside routes
+
+oidc_bp = Blueprint('oidc', __name__) # url_prefix will be set when registering in app.py
+
+@oidc_bp.route('/oidc/login') # Original path was /api/oidc/login
+def oidc_login_route():
+ if not current_app.config.get('OIDC_ENABLED'):
+ logger.warning("[OIDC_HANDLER] OIDC login attempt while OIDC is disabled.")
+ return jsonify({'message': 'OIDC (SSO) login is not enabled.'}), 403
+
+ oidc_provider_name = current_app.config.get('OIDC_PROVIDER_NAME')
+ if not oidc_provider_name:
+ logger.error("[OIDC_HANDLER] OIDC is enabled but provider name not configured.")
+ return jsonify({'message': 'OIDC provider not configured correctly.'}), 500
+
+ # Corrected url_for to use blueprint name
+ redirect_uri = url_for('oidc.oidc_callback_route', _external=True)
+
+ # HTTPS check for production
+ if os.environ.get('FLASK_ENV') == 'production' and not redirect_uri.startswith('https'):
+ redirect_uri = redirect_uri.replace('http://', 'https://', 1)
+
+ logger.info(f"[OIDC_HANDLER] /oidc/login redirect_uri: {redirect_uri}")
+ return oauth.create_client(oidc_provider_name).authorize_redirect(redirect_uri)
+
+@oidc_bp.route('/oidc/callback') # Original path was /api/oidc/callback
+def oidc_callback_route():
+ if not current_app.config.get('OIDC_ENABLED'):
+ logger.warning("[OIDC_HANDLER] OIDC callback received while OIDC is disabled.")
+ frontend_login_url = os.environ.get('FRONTEND_URL', current_app.config.get('APP_BASE_URL', 'http://localhost:8080')).rstrip('/') + "/login.html"
+ return redirect(f"{frontend_login_url}?oidc_error=oidc_disabled")
+
+ oidc_provider_name = current_app.config.get('OIDC_PROVIDER_NAME')
+ if not oidc_provider_name:
+ logger.error("[OIDC_HANDLER] OIDC provider name not configured for callback.")
+ frontend_login_url = os.environ.get('FRONTEND_URL', current_app.config.get('APP_BASE_URL', 'http://localhost:8080')).rstrip('/') + "/login.html"
+ return redirect(f"{frontend_login_url}?oidc_error=oidc_misconfigured")
+
+ client = oauth.create_client(oidc_provider_name)
+ try:
+ token_data = client.authorize_access_token()
+ except Exception as e:
+ logger.error(f"[OIDC_HANDLER] OIDC callback error authorizing access token: {e}")
+ frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
+ return redirect(f"{frontend_login_url}?oidc_error=token_exchange_failed")
+
+ if not token_data:
+ logger.error("[OIDC_HANDLER] OIDC callback: Failed to retrieve access token.")
+ frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
+ return redirect(f"{frontend_login_url}?oidc_error=token_missing")
+
+ userinfo = token_data.get('userinfo')
+ if not userinfo:
+ try:
+ userinfo = client.userinfo(token=token_data)
+ except Exception as e:
+ logger.error(f"[OIDC_HANDLER] OIDC callback error fetching userinfo: {e}")
+ frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
+ return redirect(f"{frontend_login_url}?oidc_error=userinfo_fetch_failed")
+
+ if not userinfo:
+ logger.error("[OIDC_HANDLER] OIDC callback: Failed to retrieve userinfo.")
+ frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
+ return redirect(f"{frontend_login_url}?oidc_error=userinfo_missing")
+
+ oidc_subject = userinfo.get('sub')
+ oidc_issuer = userinfo.get('iss')
+
+ if not oidc_subject:
+ logger.error("[OIDC_HANDLER] OIDC callback: 'sub' (subject) missing in userinfo.")
+ frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
+ return redirect(f"{frontend_login_url}?oidc_error=subject_missing")
+
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check for existing OIDC user
+ cur.execute("SELECT id, username, email, is_admin FROM users WHERE oidc_sub = %s AND oidc_issuer = %s AND is_active = TRUE",
+ (oidc_subject, oidc_issuer))
+ user_db_data = cur.fetchone()
+
+ user_id = None
+ is_new_user = False
+
+ if user_db_data:
+ user_id = user_db_data[0]
+ logger.info(f"[OIDC_HANDLER] Existing OIDC user found with ID {user_id} for sub {oidc_subject}")
+ else:
+ # Check if registration is enabled before creating new users
+ cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'site_settings'
+ )
+ """)
+ table_exists = cur.fetchone()[0]
+
+ registration_enabled = True
+ if table_exists:
+ # Get registration_enabled setting
+ cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")
+ result = cur.fetchone()
+
+ if result:
+ registration_enabled = result[0].lower() == 'true'
+
+ # Check if there are any users (first user can register regardless of setting)
+ cur.execute('SELECT COUNT(*) FROM users')
+ user_count = cur.fetchone()[0]
+
+ # If registration is disabled and this is not the first user, deny SSO signup
+ if not registration_enabled and user_count > 0:
+ logger.warning(f"[OIDC_HANDLER] New OIDC user registration denied - registrations are disabled. Subject: {oidc_subject}")
+ frontend_login_url = os.environ.get('FRONTEND_URL', current_app.config.get('APP_BASE_URL', 'http://localhost:8080')).rstrip('/') + "/login.html"
+ return redirect(f"{frontend_login_url}?oidc_error=registration_disabled")
+
+ # New user provisioning
+ is_new_user = True
+ email = userinfo.get('email')
+ if not email:
+ logger.error("[OIDC_HANDLER] 'email' missing in userinfo for new OIDC user.")
+ frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
+ return redirect(f"{frontend_login_url}?oidc_error=email_missing_for_new_user")
+
+ # Check for email conflict with local account
+ cur.execute("SELECT id FROM users WHERE email = %s AND (oidc_sub IS NULL OR oidc_issuer IS NULL)", (email,))
+ if cur.fetchone():
+ logger.warning(f"[OIDC_HANDLER] Email {email} already exists for a local account. OIDC user cannot be created.")
+ frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
+ return redirect(f"{frontend_login_url}?oidc_error=email_conflict_local_account")
+
+ username = userinfo.get('preferred_username') or userinfo.get('name') or email.split('@')[0]
+ # Ensure username uniqueness
+ cur.execute("SELECT id FROM users WHERE username = %s", (username,))
+ if cur.fetchone():
+ username = f"{username}_{str(uuid.uuid4())[:4]}" # Short random suffix
+
+ first_name = userinfo.get('given_name', '')
+ last_name = userinfo.get('family_name', '')
+
+ cur.execute('SELECT COUNT(*) FROM users')
+ user_count = cur.fetchone()[0]
+
+ # Determine admin status: first user OR email matches configured admin email
+ is_first_user_admin = (user_count == 0)
+
+ admin_email_from_env = current_app.config.get('ADMIN_EMAIL', '').lower()
+ oidc_user_email_lower = email.lower() if email else ''
+
+ is_email_match_admin = False
+ if admin_email_from_env and oidc_user_email_lower == admin_email_from_env:
+ is_email_match_admin = True
+ logger.info(f"[OIDC_HANDLER] New OIDC user email {oidc_user_email_lower} matches ADMIN_EMAIL {admin_email_from_env}.")
+
+ is_admin = is_first_user_admin or is_email_match_admin
+
+ if is_admin and not is_first_user_admin:
+ logger.info(f"[OIDC_HANDLER] Granting admin rights to new OIDC user {oidc_user_email_lower} based on email match.")
+ elif is_first_user_admin:
+ logger.info(f"[OIDC_HANDLER] Granting admin rights to new OIDC user {oidc_user_email_lower} as they are the first user.")
+
+
+ # Insert new OIDC user
+ cur.execute(
+ """INSERT INTO users (username, email, first_name, last_name, is_admin, oidc_sub, oidc_issuer, is_active)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, TRUE) RETURNING id""",
+ (username, email, first_name, last_name, is_admin, oidc_subject, oidc_issuer)
+ )
+ user_id = cur.fetchone()[0]
+ logger.info(f"[OIDC_HANDLER] New OIDC user created with ID {user_id} for sub {oidc_subject}")
+
+ if user_id:
+ app_session_token = generate_token(user_id) # Generate app-specific JWT
+
+ # Update last login timestamp
+ cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
+
+ # Log OIDC session in user_sessions table
+ ip_address = request.remote_addr
+ user_agent = request.headers.get('User-Agent', '')
+ # Use a different UUID for session_token in DB if needed, or re-use app_session_token if appropriate for your session model
+ db_session_token = str(uuid.uuid4())
+ expires_at = datetime.utcnow() + current_app.config['JWT_EXPIRATION_DELTA']
+
+ cur.execute(
+ 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent, login_method) VALUES (%s, %s, %s, %s, %s, %s)',
+ (user_id, db_session_token, expires_at, ip_address, user_agent, 'oidc')
+ )
+ conn.commit()
+
+ frontend_url = os.environ.get('FRONTEND_URL', current_app.config.get('APP_BASE_URL', 'http://localhost:8080')).rstrip('/')
+ redirect_target = f"{frontend_url}/auth-redirect.html?token={app_session_token}"
+ if is_new_user:
+ redirect_target += "&new_user=true"
+
+ logger.info(f"[OIDC_HANDLER] /oidc/callback redirecting to frontend: {redirect_target}")
+ return redirect(redirect_target)
+ else:
+ logger.error("[OIDC_HANDLER] /oidc/callback User ID not established after DB ops.")
+ frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
+ return redirect(f"{frontend_login_url}?oidc_error=user_processing_failed")
+
+ except Exception as e: # Catch more specific psycopg2.Error if preferred
+ logger.error(f"[OIDC_HANDLER] OIDC callback: Database or general error: {e}", exc_info=True)
+ if conn: conn.rollback()
+ frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
+ return redirect(f"{frontend_login_url}?oidc_error=internal_error")
+ finally:
+ if conn: release_db_connection(conn)
+
+@oidc_bp.route('/auth/oidc-status', methods=['GET']) # Path relative to blueprint's url_prefix
+def get_oidc_status_route():
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Get OIDC settings including the new oidc_only_mode
+ cur.execute("SELECT key, value FROM site_settings WHERE key IN ('oidc_enabled', 'oidc_only_mode', 'oidc_provider_name')")
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+
+ # Apply same precedence logic as init_oidc_client()
+ # Priority: Environment Variable > Database Setting > Hardcoded Default
+
+ # Check OIDC enabled status with correct precedence
+ oidc_enabled_from_env = os.environ.get('OIDC_ENABLED')
+ if oidc_enabled_from_env is not None:
+ oidc_is_enabled = oidc_enabled_from_env.lower() == 'true'
+ else:
+ oidc_is_enabled = settings.get('oidc_enabled', 'false').lower() == 'true'
+
+ # Check OIDC only mode with correct precedence
+ oidc_only_mode_from_env = os.environ.get('OIDC_ONLY_MODE')
+ if oidc_only_mode_from_env is not None:
+ oidc_only_mode = oidc_only_mode_from_env.lower() == 'true'
+ else:
+ oidc_only_mode = settings.get('oidc_only_mode', 'false').lower() == 'true'
+
+ # Check provider name with correct precedence
+ oidc_provider_name_from_env = os.environ.get('OIDC_PROVIDER_NAME')
+ if oidc_provider_name_from_env is not None:
+ oidc_provider_name = oidc_provider_name_from_env.capitalize()
+ else:
+ raw_name = settings.get('oidc_provider_name', 'SSO Provider')
+ oidc_provider_name = raw_name.capitalize() if raw_name else 'SSO Provider'
+
+ return jsonify({
+ "oidc_enabled": oidc_is_enabled,
+ "oidc_only_mode": oidc_only_mode,
+ "oidc_provider_display_name": oidc_provider_name
+ }), 200
+ except Exception as e:
+ logger.error(f"[OIDC_HANDLER] Error fetching OIDC status: {e}")
+ # On error, check environment variables as fallback
+ oidc_enabled_from_env = os.environ.get('OIDC_ENABLED')
+ oidc_only_mode_from_env = os.environ.get('OIDC_ONLY_MODE')
+ oidc_provider_name_from_env = os.environ.get('OIDC_PROVIDER_NAME')
+
+ return jsonify({
+ "oidc_enabled": oidc_enabled_from_env.lower() == 'true' if oidc_enabled_from_env else False,
+ "oidc_only_mode": oidc_only_mode_from_env.lower() == 'true' if oidc_only_mode_from_env else False,
+ "oidc_provider_display_name": oidc_provider_name_from_env.capitalize() if oidc_provider_name_from_env else "SSO Provider"
+ }), 200
+ finally:
+ if conn:
+ release_db_connection(conn)
diff --git a/backend/paperless_handler.py b/backend/paperless_handler.py
new file mode 100644
index 0000000..737693a
--- /dev/null
+++ b/backend/paperless_handler.py
@@ -0,0 +1,728 @@
+"""
+Paperless-ngx API Handler for Warracker
+
+This module provides functionality to interact with Paperless-ngx API
+for uploading, retrieving, and managing documents.
+"""
+
+import requests
+import logging
+from typing import Optional, Dict, Any, Tuple
+import os
+from io import BytesIO
+import hashlib
+
+logger = logging.getLogger(__name__)
+
+
+class PaperlessHandler:
+ """Handle interactions with Paperless-ngx API"""
+
+ def __init__(self, paperless_url: str, api_token: str):
+ """
+ Initialize Paperless handler
+
+ Args:
+ paperless_url: Base URL of Paperless-ngx instance (e.g., https://paperless.example.com)
+ api_token: API token for authentication
+ """
+ self.paperless_url = paperless_url.rstrip('/')
+ self.base_url = self.paperless_url # Add base_url alias for compatibility
+ self.api_token = api_token
+ self.session = requests.Session()
+ self.session.headers.update({
+ 'Authorization': f'Token {api_token}',
+ 'User-Agent': 'Warracker-PaperlessIntegration/1.0'
+ })
+
+ def test_connection(self) -> Tuple[bool, str]:
+ """
+ Test connection to Paperless-ngx instance
+
+ Returns:
+ (success: bool, message: str)
+ """
+ try:
+ response = self.session.get(f'{self.paperless_url}/api/documents/', params={'page_size': 1})
+ response.raise_for_status()
+ return True, "Connection successful"
+ except requests.exceptions.ConnectionError:
+ return False, "Cannot connect to Paperless-ngx instance. Check URL and network connectivity."
+ except requests.exceptions.Timeout:
+ return False, "Connection timeout. Paperless-ngx instance might be slow or unresponsive."
+ except requests.exceptions.HTTPError as e:
+ if e.response.status_code == 401:
+ return False, "Authentication failed. Check your API token."
+ elif e.response.status_code == 403:
+ return False, "Access forbidden. Check your API token permissions."
+ else:
+ return False, f"HTTP error: {e.response.status_code} - {e.response.reason}"
+ except Exception as e:
+ return False, f"Unexpected error: {str(e)}"
+
+ def find_document_by_checksum(self, checksum: str) -> Tuple[bool, Optional[int], str]:
+
+ """
+
+ Find a document by its checksum in Paperless-ngx
+
+
+
+ Args:
+
+ checksum: Document checksum to search for
+
+
+
+ Returns:
+
+ (success: bool, document_id: Optional[int], message: str)
+
+ """
+
+ try:
+
+ logger.info(f"Searching for document by checksum: {checksum}")
+
+
+
+ response = self.session.get(
+
+ f'{self.paperless_url}/api/documents/',
+
+ params={
+
+ 'checksum': checksum,
+
+ 'ordering': '-created',
+
+ 'page_size': 1
+
+ },
+
+ timeout=15
+
+ )
+
+
+
+ response.raise_for_status()
+
+ result = response.json()
+
+
+
+ if 'results' in result and result['results']:
+
+ document = result['results'][0]
+
+ document_id = document.get('id')
+
+ logger.info(f"Found existing document with checksum {checksum}: ID {document_id}")
+
+ return True, document_id, f"Found existing document: ID {document_id}"
+
+ else:
+
+ return False, None, "No document found with matching checksum"
+
+
+
+ except requests.exceptions.HTTPError as e:
+
+ logger.error(f"HTTP error searching by checksum: {e}")
+
+ return False, None, f"Search failed: HTTP {e.response.status_code}"
+
+ except Exception as e:
+
+ logger.error(f"Error searching by checksum: {e}")
+
+ return False, None, f"Search failed: {str(e)}"
+
+
+
+ def upload_document(self, file_content: bytes, filename: str, title: Optional[str] = None,
+
+ tags: Optional[list] = None, correspondent: Optional[str] = None) -> Tuple[bool, Optional[int], str]:
+
+ # Check for duplicate by checksum before uploading
+
+ checksum = hashlib.md5(file_content).hexdigest()
+
+ success, existing_id, msg = self.find_document_by_checksum(checksum)
+
+ if success:
+
+ return False, existing_id, "The file that is being uploaded to Paperless is a duplicate."
+
+
+
+ try:
+ # Detect MIME type from filename
+ import mimetypes
+ mime_type, _ = mimetypes.guess_type(filename)
+ if not mime_type:
+ mime_type = 'application/octet-stream'
+
+ # Prepare files for multipart upload
+ # Paperless-ngx expects the file under 'document' field
+ files = {
+ 'document': (filename, BytesIO(file_content), mime_type)
+ }
+
+ # Prepare form data - Paperless-ngx API requirements
+ # Note: Don't include 'document' in data, only in files
+ data = {}
+ if title:
+ data['title'] = title
+
+ # TODO: For future enhancement, implement proper tag/correspondent handling:
+ # - correspondent expects PK (ID) of existing correspondent, not string name
+ # - tags expects PKs (IDs) of existing tags, not string names
+ # For now, we'll skip these optional fields to get basic upload working
+
+ # if correspondent:
+ # # Would need to lookup/create correspondent ID first
+ # data['correspondent'] = correspondent_id
+ # if tags:
+ # # Would need to lookup/create tag IDs first
+ # data['tags'] = [tag_id1, tag_id2, ...]
+
+ logger.info(f"Uploading document to Paperless-ngx: {filename}")
+ logger.info(f"Upload data: {data}")
+ logger.info(f"MIME type: {mime_type}")
+
+ # Don't set Content-Type manually - let requests handle it
+ response = self.session.post(
+ f'{self.paperless_url}/api/documents/post_document/',
+ files=files,
+ headers={'Authorization': f'Token {self.api_token}'},
+ timeout=60 # Longer timeout for uploads
+ )
+
+ logger.info(f"Paperless-ngx upload response status: {response.status_code}")
+ logger.info(f"Paperless-ngx upload response text: {response.text[:500]}...") # First 500 chars
+
+ response.raise_for_status() # This will raise an exception for 4xx/5xx status codes
+
+ # Try to parse response as JSON first
+ try:
+ result = response.json()
+ logger.info(f"Paperless-ngx upload response: {result}")
+ except Exception as e:
+ logger.warning(f"Could not parse response as JSON: {e}")
+
+ # If Paperless returns plain text, it is often just the task UUID.
+ text_body = response.text.strip().strip('"') # paperless may wrap uuid in quotes
+
+ import re
+ uuid_pattern = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
+
+ if uuid_pattern.match(text_body):
+ # Treat as task ID and try to resolve the document ID
+ resolved_id = self._get_document_id_from_task(text_body)
+
+ if resolved_id:
+ return True, resolved_id, "Document uploaded and processed successfully"
+ else:
+ logger.info("Upload accepted; processing asynchronously (task %s)", text_body)
+ return True, None, f"Document uploaded successfully: {text_body}"
+
+ # If we can't recognise the content, still mark success but without ID
+ return True, None, "Document uploaded successfully"
+
+ # Handle different possible response formats from Paperless-ngx
+ document_id = None
+ if isinstance(result, dict):
+ # JSON object response
+ if 'task_id' in result:
+ # Task-based response (asynchronous processing)
+ task_id = result.get('task_id')
+ logger.info(f"Document upload task created: {task_id}")
+
+ # NEW: Poll Paperless-ngx task endpoint to resolve the final document ID.
+ resolved_id = self._get_document_id_from_task(task_id)
+
+ if resolved_id:
+ logger.info(f"Resolved task {task_id} to document ID {resolved_id}")
+ return True, resolved_id, "Document uploaded and processed successfully"
+ else:
+ logger.warning(
+ "Timed out waiting for Paperless-ngx to finish processing task %s", task_id
+ )
+ # Processing will still finish in background; caller can attempt later auto-link.
+ return True, None, "Document uploaded (processing asynchronously – link pending)"
+ elif 'id' in result:
+ # Direct document ID response (synchronous processing)
+ document_id = result.get('id')
+ logger.info(f"Document uploaded with ID: {document_id}")
+ return True, document_id, "Document uploaded successfully"
+ elif result.get('success') or response.status_code == 200:
+ # Generic success response
+ logger.info(f"Document uploaded successfully (generic success)")
+ return True, None, "Document uploaded successfully"
+ else:
+ logger.warning(f"Unexpected JSON response format from Paperless-ngx: {result}")
+ # Even if format is unexpected, if we got HTTP 200, it's likely successful
+ return True, None, "Document uploaded successfully (unknown JSON format)"
+ elif isinstance(result, str):
+ # String response - might contain an ID or just be a success message
+ logger.info(f"Document uploaded successfully (string response): {result}")
+ # Try to extract an ID from the string if it looks like one
+ import re
+ # Only match standalone numbers, not task IDs
+ id_match = re.search(r'"id"\s*:\s*(\d+)', result)
+ if id_match:
+ document_id = int(id_match.group(1))
+ logger.info(f"Extracted document ID from string: {document_id}")
+ return True, document_id, f"Document uploaded successfully: {result}"
+ else:
+ return True, None, f"Document uploaded successfully: {result}"
+ else:
+ # Other response type
+ logger.warning(f"Unexpected response type from Paperless-ngx: {type(result)} - {result}")
+ return True, None, "Document uploaded successfully (unknown response type)"
+
+ except requests.exceptions.Timeout:
+ return False, None, "Upload timeout. The file might be too large or the connection is slow."
+ except requests.exceptions.HTTPError as e:
+ error_msg = f"Upload failed: HTTP {e.response.status_code}"
+ try:
+ error_detail = e.response.json()
+ logger.error(f"Paperless-ngx detailed error: {error_detail}")
+
+ if 'detail' in error_detail:
+ error_msg += f" - {error_detail['detail']}"
+ elif isinstance(error_detail, dict):
+ # Handle field-specific errors
+ error_parts = []
+ for field, errors in error_detail.items():
+ if isinstance(errors, list):
+ error_parts.append(f"{field}: {', '.join(errors)}")
+ else:
+ error_parts.append(f"{field}: {errors}")
+ if error_parts:
+ error_msg += f" - {'; '.join(error_parts)}"
+ else:
+ error_msg += f" - {error_detail}"
+ except Exception as parse_error:
+ logger.error(f"Could not parse error response: {parse_error}")
+ error_msg += f" - {e.response.reason}"
+ return False, None, error_msg
+ except Exception as e:
+ logger.error(f"Error uploading document to Paperless-ngx: {e}")
+ return False, None, f"Upload failed: {str(e)}"
+
+ def get_document_preview(self, document_id: int) -> Tuple[bool, Optional[bytes], str, Optional[str]]:
+ """
+ Get document preview/content from Paperless-ngx
+
+ Args:
+ document_id: Paperless-ngx document ID
+
+ Returns:
+ (success: bool, content: Optional[bytes], message: str, content_type: Optional[str])
+ """
+ # Try multiple endpoints in order of preference
+ endpoints_to_try = [
+ ('preview', f'/api/documents/{document_id}/preview/'),
+ ('download', f'/api/documents/{document_id}/download/'),
+ ]
+
+ last_error = None
+
+ for endpoint_name, endpoint_path in endpoints_to_try:
+ try:
+ logger.info(f"Fetching document {endpoint_name} from Paperless-ngx: {document_id}")
+ response = self.session.get(
+ f'{self.paperless_url}{endpoint_path}',
+ timeout=30
+ )
+
+ response.raise_for_status()
+
+ content_type = response.headers.get('Content-Type', 'application/octet-stream')
+ logger.info(f"Successfully retrieved document {document_id} via {endpoint_name} endpoint")
+ return True, response.content, f"Document retrieved successfully via {endpoint_name}", content_type
+
+ except requests.exceptions.HTTPError as e:
+ logger.warning(f"Failed to retrieve document {document_id} via {endpoint_name}: HTTP {e.response.status_code}")
+ last_error = e
+ if e.response.status_code == 404:
+ continue # Try next endpoint
+ else:
+ # For non-404 errors, don't try other endpoints
+ return False, None, f"Failed to retrieve document: HTTP {e.response.status_code}", None
+ except Exception as e:
+ logger.warning(f"Error retrieving document {document_id} via {endpoint_name}: {e}")
+ last_error = e
+ continue # Try next endpoint
+
+ # If we get here, all endpoints failed
+ if last_error and isinstance(last_error, requests.exceptions.HTTPError) and last_error.response.status_code == 404:
+ return False, None, "Document not found in Paperless-ngx", None
+ else:
+ return False, None, f"Retrieval failed: {str(last_error) if last_error else 'All endpoints failed'}", None
+
+ def get_document_thumbnail(self, document_id: int) -> Tuple[bool, Optional[bytes], str]:
+ """
+ Get document thumbnail from Paperless-ngx
+
+ Args:
+ document_id: Paperless-ngx document ID
+
+ Returns:
+ (success: bool, content: Optional[bytes], message: str)
+ """
+ try:
+ response = self.session.get(
+ f'{self.paperless_url}/api/documents/{document_id}/thumb/',
+ timeout=15
+ )
+
+ response.raise_for_status()
+ return True, response.content, "Thumbnail retrieved successfully"
+
+ except requests.exceptions.HTTPError as e:
+ if e.response.status_code == 404:
+ return False, None, "Document or thumbnail not found"
+ else:
+ return False, None, f"Failed to retrieve thumbnail: HTTP {e.response.status_code}"
+ except Exception as e:
+ logger.error(f"Error retrieving thumbnail from Paperless-ngx: {e}")
+ return False, None, f"Thumbnail retrieval failed: {str(e)}"
+
+ def search_documents(self, query: str, limit: int = 25) -> Tuple[bool, Optional[list], str]:
+ """
+ Search documents in Paperless-ngx
+
+ Args:
+ query: Search query string
+ limit: Maximum number of results to return
+
+ Returns:
+ (success: bool, documents: Optional[list], message: str)
+ """
+ try:
+ params = {
+ 'query': query,
+ 'page_size': min(limit, 100) # Cap at 100 for performance
+ }
+
+ response = self.session.get(
+ f'{self.paperless_url}/api/documents/',
+ params=params,
+ timeout=15
+ )
+
+ response.raise_for_status()
+ result = response.json()
+
+ documents = result.get('results', [])
+ return True, documents, f"Found {len(documents)} documents"
+
+ except Exception as e:
+ logger.error(f"Error searching documents in Paperless-ngx: {e}")
+ return False, None, f"Search failed: {str(e)}"
+
+ def get_document_info(self, document_id: int) -> Tuple[bool, Optional[Dict[str, Any]], str]:
+ """
+ Get document information from Paperless-ngx
+
+ Args:
+ document_id: Paperless-ngx document ID
+
+ Returns:
+ (success: bool, document_info: Optional[Dict], message: str)
+ """
+ try:
+ response = self.session.get(
+ f'{self.paperless_url}/api/documents/{document_id}/',
+ timeout=15
+ )
+
+ response.raise_for_status()
+ document_info = response.json()
+
+ return True, document_info, "Document info retrieved successfully"
+
+ except requests.exceptions.HTTPError as e:
+ if e.response.status_code == 404:
+ return False, None, "Document not found"
+ else:
+ return False, None, f"Failed to retrieve document info: HTTP {e.response.status_code}"
+ except Exception as e:
+ logger.error(f"Error retrieving document info from Paperless-ngx: {e}")
+ return False, None, f"Info retrieval failed: {str(e)}"
+
+ def debug_document_status(self, document_id: int) -> Dict[str, Any]:
+ """
+ Debug method to check document status and available endpoints
+
+ Args:
+ document_id: Paperless-ngx document ID
+
+ Returns:
+ Dictionary with debug information
+ """
+ debug_info = {
+ 'document_id': document_id,
+ 'endpoints_tested': {},
+ 'document_exists': False,
+ 'document_info': None
+ }
+
+ # Test different endpoints
+ endpoints_to_test = [
+ ('info', f'/api/documents/{document_id}/'),
+ ('preview', f'/api/documents/{document_id}/preview/'),
+ ('download', f'/api/documents/{document_id}/download/'),
+ ('thumb', f'/api/documents/{document_id}/thumb/')
+ ]
+
+ for endpoint_name, endpoint_path in endpoints_to_test:
+ try:
+ logger.info(f"Testing endpoint: {self.paperless_url}{endpoint_path}")
+ response = self.session.get(f'{self.paperless_url}{endpoint_path}', timeout=15)
+
+ debug_info['endpoints_tested'][endpoint_name] = {
+ 'status_code': response.status_code,
+ 'success': response.status_code < 400,
+ 'content_type': response.headers.get('Content-Type', 'unknown'),
+ 'content_length': len(response.content) if response.content else 0
+ }
+
+ if endpoint_name == 'info' and response.status_code == 200:
+ debug_info['document_exists'] = True
+ try:
+ debug_info['document_info'] = response.json()
+ except:
+ debug_info['document_info'] = 'Could not parse JSON'
+
+ except Exception as e:
+ debug_info['endpoints_tested'][endpoint_name] = {
+ 'error': str(e),
+ 'success': False
+ }
+
+ # Also try to list recent documents to see if our document is there
+ try:
+ response = self.session.get(f'{self.paperless_url}/api/documents/',
+ params={'ordering': '-created', 'page_size': 10},
+ timeout=15)
+ if response.status_code == 200:
+ recent_docs = response.json().get('results', [])
+ debug_info['recent_documents'] = [
+ {'id': doc.get('id'), 'title': doc.get('title'), 'created': doc.get('created')}
+ for doc in recent_docs
+ ]
+ debug_info['document_in_recent'] = any(doc.get('id') == document_id for doc in recent_docs)
+ else:
+ debug_info['recent_documents'] = f'Error: {response.status_code}'
+ except Exception as e:
+ debug_info['recent_documents'] = f'Exception: {str(e)}'
+
+ return debug_info
+
+ def document_exists(self, document_id: int) -> bool:
+ """
+ Check if a document exists in Paperless-ngx
+
+ Args:
+ document_id: Paperless-ngx document ID
+
+ Returns:
+ True if document exists, False otherwise
+ """
+ try:
+ response = self.session.get(
+ f'{self.paperless_url}/api/documents/{document_id}/',
+ timeout=10
+ )
+ return response.status_code == 200
+ except Exception as e:
+ logger.warning(f"Error checking document existence {document_id}: {e}")
+ return False
+
+ def find_document_by_title(self, title: str) -> Tuple[bool, Optional[int], str]:
+ """
+ Find a document by its title in Paperless-ngx
+
+ Args:
+ title: Document title to search for
+
+ Returns:
+ (success: bool, document_id: Optional[int], message: str)
+ """
+ try:
+ logger.info(f"Searching for document by title: {title}")
+
+ # Search for documents with the given title
+ response = self.session.get(
+ f'{self.paperless_url}/api/documents/',
+ params={
+ 'title__icontains': title, # Case-insensitive partial match
+ 'ordering': '-created', # Most recent first
+ 'page_size': 10 # Limit results
+ },
+ timeout=15
+ )
+
+ response.raise_for_status()
+ result = response.json()
+
+ if 'results' in result and result['results']:
+ # Return the first (most recent) match
+ document = result['results'][0]
+ document_id = document.get('id')
+ document_title = document.get('title', 'Unknown')
+
+ logger.info(f"Found document: ID {document_id}, Title: {document_title}")
+ return True, document_id, f"Found document: {document_title}"
+ else:
+ logger.info(f"No document found with title containing: {title}")
+ return False, None, "Document not found"
+
+ except requests.exceptions.HTTPError as e:
+ logger.error(f"HTTP error searching for document: {e}")
+ return False, None, f"Search failed: HTTP {e.response.status_code}"
+ except Exception as e:
+ logger.error(f"Error searching for document: {e}")
+ return False, None, f"Search failed: {str(e)}"
+
+ # ---------------------------------------------------------------------
+ # Internal helpers
+ # ---------------------------------------------------------------------
+
+ def _get_document_id_from_task(
+ self,
+ task_id: str,
+ timeout_secs: int = 600, # increased to 10 minutes per user request
+ poll_interval: float = 5.0, # less frequent polling to reduce load
+ ) -> Optional[int]:
+ """Poll /api/tasks endpoint until the task completes and returns a document ID.
+
+ Args:
+ task_id: The UUID returned by the document upload request.
+ timeout_secs: Maximum time to wait before giving up.
+ poll_interval: Seconds between polls.
+
+ Returns:
+ The related document ID if the task completed successfully within the
+ timeout window; otherwise, ``None``.
+ """
+
+ import time
+
+ if not task_id:
+ return None
+
+ # Prefer the dedicated task endpoint (Paperless ≥2.3). Some older
+ # releases only support the list + filter variant. We therefore try the
+ # singular endpoint first and fall back to the legacy query if it 404s.
+
+ task_url_primary = f"{self.paperless_url}/api/tasks/{task_id}/"
+ task_url_legacy_list = f"{self.paperless_url}/api/tasks/"
+
+ deadline = time.time() + timeout_secs
+
+ while time.time() < deadline:
+ try:
+ try:
+ resp = self.session.get(task_url_primary, timeout=10)
+ if resp.status_code == 404:
+ # Fall back to legacy ?task_id=<uuid> filter
+ resp = self.session.get(task_url_legacy_list, params={"task_id": task_id}, timeout=10)
+ except requests.exceptions.HTTPError as http_err:
+ if http_err.response.status_code == 404 and http_err.response.url.rstrip('/') == task_url_primary.rstrip('/'):
+ # Primary endpoint not available, try legacy
+ resp = self.session.get(task_url_legacy_list, params={"task_id": task_id}, timeout=10)
+ else:
+ raise
+
+ resp.raise_for_status()
+
+ # Legacy endpoint returns a list
+ if isinstance(resp.json(), list):
+ task_info = resp.json()[0] if resp.json() else {}
+ else:
+ task_info = resp.json()
+
+ # In newer Paperless versions the field is called "state"; fall back to
+ # "status" for backwards-compatibility.
+ state = task_info.get("state") or task_info.get("status")
+ related_doc = task_info.get("related_document")
+
+ # Some Paperless versions don't fill related_document but embed the
+ # newly-created ID in the free-text "result" string, e.g.
+ # "Success. New document id 416 created" – see GH#3064.
+ if not related_doc and isinstance(task_info.get("result"), str):
+ import re
+ m = re.search(r"document id (\d+)", task_info["result"])
+ if m:
+ related_doc = m.group(1)
+
+ if state == "SUCCESS" and related_doc:
+ try:
+ return int(related_doc)
+ except (ValueError, TypeError):
+ logger.warning("Unexpected related_document value: %s", related_doc)
+ return None
+
+ if state in {"FAILURE", "REVOKED"}:
+ logger.error("Paperless task %s finished with state %s", task_id, state)
+ return None
+
+ # Task still running – wait and try again
+ time.sleep(poll_interval)
+
+ except Exception as poll_err:
+ # Transient network or parsing error – log and retry until deadline
+ logger.warning("Error polling task %s: %s", task_id, poll_err)
+ time.sleep(poll_interval)
+
+ # Timed out waiting for the task to finish
+ logger.warning(
+ "Timed out after %s seconds waiting for task %s (state pending) – will return None so frontend can attempt auto-link",
+ timeout_secs,
+ task_id,
+ )
+ return None
+
+
+def get_paperless_handler(conn) -> Optional[PaperlessHandler]:
+ """
+ Get a configured Paperless handler from site settings
+
+ Args:
+ conn: Database connection
+
+ Returns:
+ PaperlessHandler instance or None if not configured/enabled
+ """
+ try:
+ with conn.cursor() as cur:
+ cur.execute("""
+ SELECT key, value FROM site_settings
+ WHERE key IN ('paperless_enabled', 'paperless_url', 'paperless_api_token')
+ """)
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+
+ # Check if Paperless-ngx is enabled
+ if settings.get('paperless_enabled', 'false').lower() != 'true':
+ return None
+
+ # Check required settings
+ paperless_url = settings.get('paperless_url', '').strip()
+ paperless_token = settings.get('paperless_api_token', '').strip()
+
+ if not paperless_url or not paperless_token:
+ logger.warning("Paperless-ngx is enabled but URL or API token is missing")
+ return None
+
+ return PaperlessHandler(paperless_url, paperless_token)
+
+ except Exception as e:
+ logger.error(f"Error creating Paperless handler: {e}")
+ return None
\ No newline at end of file
diff --git a/backend/requirements.txt b/backend/requirements.txt
index 6b795a0..224c162 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -1,11 +1,18 @@
-Flask==2.0.1
-gunicorn==20.1.0
-psycopg2-binary==2.9.3
-Werkzeug==2.0.1
-flask-cors==3.0.10
-Flask-Login==0.6.2
+Flask==3.0.3
+gunicorn==23.0.0
+psycopg2-binary==2.9.9
+Werkzeug==3.0.3
+flask-cors==4.0.1
+Flask-Login==0.6.3
Flask-Bcrypt==1.0.1
-PyJWT==2.6.0
-email-validator==1.3.1
+PyJWT==2.8.0
+email-validator==2.1.1
APScheduler==3.10.4
-python-dateutil
\ No newline at end of file
+python-dateutil==2.9.0
+Authlib==1.3.1
+requests==2.32.3
+gevent==24.2.1
+setuptools<81
+apprise==1.9.3
+Flask-Babel==4.0.0
+Babel==2.16.0
diff --git a/backend/statistics_routes.py b/backend/statistics_routes.py
new file mode 100644
index 0000000..a430a72
--- /dev/null
+++ b/backend/statistics_routes.py
@@ -0,0 +1,473 @@
+from flask import Blueprint, request, jsonify, current_app
+from datetime import date, timedelta
+from decimal import Decimal
+import logging
+
+# Use try-except pattern for imports to handle both Docker and development environments
+try:
+ from . import db_handler
+ from .auth_utils import token_required
+ from .db_handler import get_db_connection, release_db_connection
+except ImportError:
+ import db_handler
+ from auth_utils import token_required
+ from db_handler import get_db_connection, release_db_connection
+
+# Create the statistics blueprint
+statistics_bp = Blueprint('statistics_bp', __name__)
+
+# Set up logging
+logger = logging.getLogger(__name__)
+
+# Helper function
+def convert_decimals(obj):
+ """Recursively convert Decimal objects to float in dicts/lists for JSON serialization."""
+ if isinstance(obj, dict):
+ return {k: convert_decimals(v) for k, v in obj.items()}
+ elif isinstance(obj, list):
+ return [convert_decimals(i) for i in obj]
+ elif isinstance(obj, Decimal):
+ return float(obj)
+ else:
+ return obj
+
+# ============================
+# Statistics Routes
+# ============================
+
+@statistics_bp.route('/statistics', methods=['GET'])
+@token_required
+def get_statistics():
+ user_id = request.user['id']
+ conn = None
+
+ try:
+ conn = get_db_connection()
+ today = date.today()
+
+ # Fetch user preference for expiring soon days
+ expiring_soon_days = 30 # Default value
+ try:
+ with conn.cursor() as cur:
+ cur.execute("SELECT expiring_soon_days FROM user_preferences WHERE user_id = %s", (user_id,))
+ result = cur.fetchone()
+ if result and result[0] is not None:
+ expiring_soon_days = result[0]
+ logger.info(f"Using custom expiring soon days: {expiring_soon_days} for user {user_id}")
+ else:
+ logger.info(f"Using default expiring soon days: {expiring_soon_days} for user {user_id}")
+ except Exception as pref_err:
+ # Log error fetching preference but continue with default
+ logger.error(f"Error fetching expiring_soon_days preference for user {user_id}: {pref_err}. Using default 30 days.")
+
+ expiring_soon_date = today + timedelta(days=expiring_soon_days)
+ ninety_days_later = today + timedelta(days=90) # Keep timeline fixed or make configurable? For now, keep at 90.
+
+ # Build base query based on role
+ from_clause = "FROM warranties w"
+ where_clause = ""
+ params = []
+ active_where = "AND"
+
+ if not request.user.get('is_admin', False):
+ where_clause = "WHERE w.user_id = %s"
+ params = [user_id]
+ active_where = "AND"
+ else:
+ # Admin should only see their own warranties
+ where_clause = "WHERE w.user_id = %s"
+ params = [user_id]
+ active_where = "AND"
+
+ with conn.cursor() as cur:
+ # Get total count
+ cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause}", params)
+ total_count = cur.fetchone()[0]
+ logger.info(f"Total warranties: {total_count}")
+
+ # Get active count (includes lifetime)
+ cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} (w.is_lifetime = TRUE OR w.expiration_date > %s)", params + [today])
+ active_count = cur.fetchone()[0]
+ logger.info(f"Active warranties: {active_count}")
+
+ # Get expired count (excludes lifetime)
+ cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} w.is_lifetime = FALSE AND w.expiration_date <= %s", params + [today])
+ expired_count = cur.fetchone()[0]
+ logger.info(f"Expired warranties: {expired_count}")
+
+ # Get expiring soon count (excludes lifetime) using user preference
+ cur.execute(f"""SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'}
+ w.is_lifetime = FALSE AND w.expiration_date > %s AND w.expiration_date <= %s""",
+ params + [today, expiring_soon_date])
+ expiring_soon_count = cur.fetchone()[0]
+ logger.info(f"Expiring soon ({expiring_soon_days} days) warranties: {expiring_soon_count}")
+
+ # Get expiration timeline (next 90 days, excluding lifetime)
+ cur.execute(f"""
+ SELECT
+ EXTRACT(YEAR FROM expiration_date) as year,
+ EXTRACT(MONTH FROM expiration_date) as month,
+ COUNT(*) as count
+ {from_clause}
+ {where_clause} {active_where if where_clause else 'WHERE'}
+ w.is_lifetime = FALSE AND w.expiration_date > %s AND w.expiration_date <= %s
+ GROUP BY EXTRACT(YEAR FROM expiration_date), EXTRACT(MONTH FROM expiration_date)
+ ORDER BY year, month
+ """, params + [today, ninety_days_later])
+
+ timeline = []
+ for row in cur.fetchall():
+ year = int(row[0])
+ month = int(row[1])
+ count = row[2]
+ timeline.append({
+ "year": year,
+ "month": month,
+ "count": count
+ })
+
+ # Get recent expiring warranties (using user preference +/- 30 days for range, excluding lifetime)
+ # We'll keep the window around today somewhat fixed for 'recent', maybe +/- 30 days is still reasonable? Or should this also use expiring_soon_days?
+ # Let's adjust the recent window based on the preference for now: N days ago to N days later
+ days_ago_for_recent = today - timedelta(days=expiring_soon_days)
+ days_later_for_recent = expiring_soon_date # Same as the expiring soon cutoff
+ cur.execute(f"""
+ SELECT
+ id, product_name, purchase_date,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days,
+ expiration_date, invoice_path, manual_path, other_document_path, product_url, purchase_price, is_lifetime
+ {from_clause}
+ {where_clause} {active_where if where_clause else 'WHERE'}
+ w.is_lifetime = FALSE AND w.expiration_date >= %s AND w.expiration_date <= %s
+ ORDER BY expiration_date
+ LIMIT 10
+ """, params + [days_ago_for_recent, days_later_for_recent])
+
+ columns = [desc[0] for desc in cur.description]
+ recent_warranties = []
+
+ for row in cur.fetchall():
+ warranty = dict(zip(columns, row))
+
+ # Convert dates to string format
+ if warranty['purchase_date']:
+ warranty['purchase_date'] = warranty['purchase_date'].isoformat()
+ if warranty['expiration_date']:
+ warranty['expiration_date'] = warranty['expiration_date'].isoformat()
+
+ # Convert Decimal objects to float for JSON serialization
+ if warranty.get('purchase_price') and isinstance(warranty['purchase_price'], Decimal):
+ warranty['purchase_price'] = float(warranty['purchase_price'])
+
+ recent_warranties.append(warranty)
+
+ # *** ADD CODE TO FETCH ALL WARRANTIES ***
+ logger.info(f"Fetching all warranties for user {user_id}...")
+ cur.execute(f"""
+ SELECT
+ id, product_name, purchase_date,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days,
+ expiration_date, invoice_path, manual_path, other_document_path, product_url, purchase_price, is_lifetime
+ {from_clause}
+ {where_clause}
+ ORDER BY expiration_date DESC
+ """, params)
+
+ all_columns = [desc[0] for desc in cur.description]
+ all_warranties_list = []
+
+ for row in cur.fetchall():
+ warranty = dict(zip(all_columns, row))
+
+ # Convert dates to string format
+ if warranty.get('purchase_date') and isinstance(warranty['purchase_date'], date):
+ warranty['purchase_date'] = warranty['purchase_date'].isoformat()
+ if warranty.get('expiration_date') and isinstance(warranty['expiration_date'], date):
+ warranty['expiration_date'] = warranty['expiration_date'].isoformat()
+
+ # Convert Decimal objects to float for JSON serialization
+ if warranty.get('purchase_price') and isinstance(warranty['purchase_price'], Decimal):
+ warranty['purchase_price'] = float(warranty['purchase_price'])
+
+ all_warranties_list.append(warranty)
+ logger.info(f"Fetched {len(all_warranties_list)} total warranties.")
+ # *** END OF ADDED CODE ***
+
+ statistics = {
+ 'total': total_count,
+ 'active': active_count,
+ 'expired': expired_count,
+ 'expiring_soon': expiring_soon_count,
+ 'timeline': timeline,
+ 'recent_warranties': recent_warranties,
+ 'all_warranties': all_warranties_list # <-- Add the new list here
+ }
+
+ return jsonify(convert_decimals(statistics))
+
+ except Exception as e:
+ logger.error(f"Error getting warranty statistics: {e}")
+ return jsonify({"error": str(e)}), 500
+
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@statistics_bp.route('/statistics/global', methods=['GET'])
+@token_required
+def get_global_statistics():
+ """Get global warranty statistics for all users (with proper permissions check)"""
+ conn = None
+ try:
+ # Check if global view is enabled for this user
+ user_is_admin = request.user.get('is_admin', False)
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Get both global view settings
+ cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+
+ # Check if global view is enabled at all
+ global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'
+ if not global_view_enabled:
+ return jsonify({"error": "Global view is disabled by administrator"}), 403
+
+ # Check if global view is restricted to admins only
+ admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'
+ if admin_only and not user_is_admin:
+ return jsonify({"error": "Global view is restricted to administrators only"}), 403
+
+ # Release the connection since we'll get a new one below
+ release_db_connection(conn)
+ conn = None
+
+ # Get user's expiring soon days preference (for consistency)
+ user_id = request.user['id']
+ expiring_soon_days = 30 # Default value
+
+ conn = get_db_connection()
+ try:
+ with conn.cursor() as cur:
+ cur.execute("SELECT expiring_soon_days FROM user_preferences WHERE user_id = %s", (user_id,))
+ result = cur.fetchone()
+ if result and result[0] is not None:
+ expiring_soon_days = result[0]
+ except Exception as pref_err:
+ logger.error(f"Error fetching expiring_soon_days preference for user {user_id}: {pref_err}. Using default 30 days.")
+
+ today = date.today()
+ expiring_soon_date = today + timedelta(days=expiring_soon_days)
+ ninety_days_later = today + timedelta(days=90)
+
+ with conn.cursor() as cur:
+ # Global statistics query - all warranties from all users
+
+ # Get total count
+ cur.execute("SELECT COUNT(*) FROM warranties w")
+ total_count = cur.fetchone()[0]
+
+ # Get active count (includes lifetime)
+ cur.execute("SELECT COUNT(*) FROM warranties w WHERE w.is_lifetime = TRUE OR w.expiration_date > %s", (today,))
+ active_count = cur.fetchone()[0]
+
+ # Get expired count (excludes lifetime)
+ cur.execute("SELECT COUNT(*) FROM warranties w WHERE w.is_lifetime = FALSE AND w.expiration_date <= %s", (today,))
+ expired_count = cur.fetchone()[0]
+
+ # Get expiring soon count (excludes lifetime)
+ cur.execute("""SELECT COUNT(*) FROM warranties w WHERE
+ w.is_lifetime = FALSE AND w.expiration_date > %s AND w.expiration_date <= %s""",
+ (today, expiring_soon_date))
+ expiring_soon_count = cur.fetchone()[0]
+
+ # Get expiration timeline (next 90 days, excluding lifetime)
+ cur.execute("""
+ SELECT
+ EXTRACT(YEAR FROM expiration_date) as year,
+ EXTRACT(MONTH FROM expiration_date) as month,
+ COUNT(*) as count
+ FROM warranties w
+ WHERE w.is_lifetime = FALSE AND w.expiration_date > %s AND w.expiration_date <= %s
+ GROUP BY EXTRACT(YEAR FROM expiration_date), EXTRACT(MONTH FROM expiration_date)
+ ORDER BY year, month
+ """, (today, ninety_days_later))
+
+ timeline = []
+ for row in cur.fetchall():
+ year = int(row[0])
+ month = int(row[1])
+ count = row[2]
+ timeline.append({
+ "year": year,
+ "month": month,
+ "count": count
+ })
+
+ # Get recent expiring warranties with user information
+ days_ago_for_recent = today - timedelta(days=expiring_soon_days)
+ days_later_for_recent = expiring_soon_date
+ cur.execute("""
+ SELECT
+ w.id, w.product_name, w.purchase_date,
+ w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days,
+ w.expiration_date, w.invoice_path, w.manual_path, w.other_document_path,
+ w.product_url, w.purchase_price, w.is_lifetime,
+ u.username, u.email, u.first_name, u.last_name
+ FROM warranties w
+ JOIN users u ON w.user_id = u.id
+ WHERE w.is_lifetime = FALSE AND w.expiration_date >= %s AND w.expiration_date <= %s
+ ORDER BY w.expiration_date
+ LIMIT 10
+ """, (days_ago_for_recent, days_later_for_recent))
+
+ columns = [desc[0] for desc in cur.description]
+ recent_warranties = []
+
+ for row in cur.fetchall():
+ warranty = dict(zip(columns, row))
+
+ # Convert dates to string format
+ if warranty['purchase_date']:
+ warranty['purchase_date'] = warranty['purchase_date'].isoformat()
+ if warranty['expiration_date']:
+ warranty['expiration_date'] = warranty['expiration_date'].isoformat()
+
+ # Convert Decimal objects to float for JSON serialization
+ if warranty.get('purchase_price') and isinstance(warranty['purchase_price'], Decimal):
+ warranty['purchase_price'] = float(warranty['purchase_price'])
+
+ # Add user display information
+ first_name = warranty.get('first_name', '').strip() if warranty.get('first_name') else ''
+ last_name = warranty.get('last_name', '').strip() if warranty.get('last_name') else ''
+ username = warranty.get('username', '').strip() if warranty.get('username') else ''
+
+ if first_name and last_name:
+ display_name = f"{first_name} {last_name}"
+ elif first_name:
+ display_name = first_name
+ elif username:
+ display_name = username
+ else:
+ display_name = 'Unknown User'
+
+ warranty['user_display_name'] = display_name
+
+ recent_warranties.append(warranty)
+
+ # Get all warranties with user information
+ cur.execute("""
+ SELECT
+ w.id, w.product_name, w.purchase_date,
+ w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days,
+ w.expiration_date, w.invoice_path, w.manual_path, w.other_document_path,
+ w.product_url, w.purchase_price, w.is_lifetime,
+ u.username, u.email, u.first_name, u.last_name
+ FROM warranties w
+ JOIN users u ON w.user_id = u.id
+ ORDER BY w.expiration_date DESC
+ """)
+
+ all_columns = [desc[0] for desc in cur.description]
+ all_warranties_list = []
+
+ for row in cur.fetchall():
+ warranty = dict(zip(all_columns, row))
+
+ # Convert dates to string format
+ if warranty.get('purchase_date') and isinstance(warranty['purchase_date'], date):
+ warranty['purchase_date'] = warranty['purchase_date'].isoformat()
+ if warranty.get('expiration_date') and isinstance(warranty['expiration_date'], date):
+ warranty['expiration_date'] = warranty['expiration_date'].isoformat()
+
+ # Convert Decimal objects to float for JSON serialization
+ if warranty.get('purchase_price') and isinstance(warranty['purchase_price'], Decimal):
+ warranty['purchase_price'] = float(warranty['purchase_price'])
+
+ # Add user display name for better UI
+ first_name = warranty.get('first_name', '').strip() if warranty.get('first_name') else ''
+ last_name = warranty.get('last_name', '').strip() if warranty.get('last_name') else ''
+ username = warranty.get('username', '').strip() if warranty.get('username') else ''
+
+ if first_name and last_name:
+ display_name = f"{first_name} {last_name}"
+ elif first_name:
+ display_name = first_name
+ elif username:
+ display_name = username
+ else:
+ display_name = 'Unknown User'
+
+ warranty['user_display_name'] = display_name
+
+ all_warranties_list.append(warranty)
+
+ statistics = {
+ 'total': total_count,
+ 'active': active_count,
+ 'expired': expired_count,
+ 'expiring_soon': expiring_soon_count,
+ 'timeline': timeline,
+ 'recent_warranties': recent_warranties,
+ 'all_warranties': all_warranties_list
+ }
+
+ return jsonify(convert_decimals(statistics))
+
+ except Exception as e:
+ logger.error(f"Error getting global warranty statistics: {e}")
+ return jsonify({"error": str(e)}), 500
+
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+
+@statistics_bp.route('/settings/global-view-status', methods=['GET'])
+@token_required
+def check_global_view_status():
+ """Check if global view is enabled for the current user"""
+ conn = None
+ try:
+ user_is_admin = request.user.get('is_admin', False)
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if settings table exists
+ cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'site_settings'
+ )
+ """)
+ table_exists = cur.fetchone()[0]
+
+ if not table_exists:
+ # If table doesn't exist, global view is enabled by default
+ return jsonify({"enabled": True}), 200
+
+ # Get both global view settings
+ cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+
+ # Check if global view is enabled at all
+ global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'
+ if not global_view_enabled:
+ return jsonify({"enabled": False}), 200
+
+ # Check if global view is restricted to admins only
+ admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'
+ if admin_only and not user_is_admin:
+ return jsonify({"enabled": False}), 200
+
+ # Global view is enabled for this user
+ return jsonify({"enabled": True}), 200
+
+ except Exception as e:
+ logger.error(f"Error checking global view status: {e}")
+ # Default to enabled on error for admins, disabled for non-admins
+ user_is_admin = request.user.get('is_admin', False)
+ return jsonify({"enabled": user_is_admin}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
\ No newline at end of file
diff --git a/backend/tags_routes.py b/backend/tags_routes.py
new file mode 100644
index 0000000..ae197e4
--- /dev/null
+++ b/backend/tags_routes.py
@@ -0,0 +1,350 @@
+# backend/tags_routes.py
+from flask import Blueprint, request, jsonify, current_app
+import re
+import json
+import logging
+
+# Use try-except pattern for imports to handle both Docker and development environments
+try:
+ from . import db_handler
+ from .auth_utils import token_required
+ from .db_handler import get_db_connection, release_db_connection
+except ImportError:
+ import db_handler
+ from auth_utils import token_required
+ from db_handler import get_db_connection, release_db_connection
+
+# Create the tags blueprint
+tags_bp = Blueprint('tags_bp', __name__)
+
+# Set up logging
+logger = logging.getLogger(__name__)
+
+# ============================
+# Direct Tag Management Routes
+# ============================
+
+@tags_bp.route('/tags', methods=['GET'])
+@token_required
+def get_tags():
+ """Get tags based on user role."""
+ conn = None
+ try:
+ user_id = request.user['id']
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Fetch tags created by the currently logged-in user
+ cur.execute('SELECT id, name, color, created_at FROM tags WHERE user_id = %s ORDER BY name', (user_id,))
+
+ tags = cur.fetchall()
+
+ result = []
+ for tag in tags:
+ result.append({
+ 'id': tag[0],
+ 'name': tag[1],
+ 'color': tag[2],
+ 'created_at': tag[3].isoformat() if tag[3] else None
+ # Removed is_admin_tag comment
+ })
+
+ return jsonify(result), 200
+ except Exception as e:
+ logger.error(f"Error fetching tags: {e}")
+ return jsonify({"error": "Failed to fetch tags"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@tags_bp.route('/tags', methods=['POST'])
+@token_required
+def create_tag():
+ """Create a new tag owned by the requesting user."""
+ conn = None
+ try:
+ user_id = request.user['id'] # Get user ID
+ data = request.json
+
+ if not data or 'name' not in data:
+ return jsonify({"error": "Tag name is required"}), 400
+
+ name = data['name'].strip()
+ color = data.get('color', '#808080')
+
+ if not name:
+ return jsonify({"error": "Tag name cannot be empty"}), 400
+
+ # Validate color format (should be a hex color)
+ if not re.match(r'^#[0-9A-Fa-f]{6}$', color):
+ return jsonify({"error": "Invalid color format. Use hex format (e.g., #FF5733)"}), 400
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if tag with this name already exists FOR THIS USER
+ cur.execute('SELECT id FROM tags WHERE name = %s AND user_id = %s', (name, user_id)) # Added user_id check
+ existing_tag = cur.fetchone()
+
+ if existing_tag:
+ # Differentiate error message slightly
+ return jsonify({"error": f"A tag with this name already exists for your account"}), 409 # Updated error message
+
+ # Create new tag, setting user_id
+ cur.execute(
+ 'INSERT INTO tags (name, color, user_id) VALUES (%s, %s, %s) RETURNING id', # Added user_id
+ (name, color, user_id) # Pass user_id here
+ )
+ tag_id = cur.fetchone()[0]
+ conn.commit()
+
+ return jsonify({
+ "id": tag_id,
+ "name": name,
+ "color": color,
+ "message": "Tag created successfully"
+ }), 201
+ except Exception as e:
+ logger.error(f"Error creating tag: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to create tag"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@tags_bp.route('/tags/<int:tag_id>', methods=['PUT'])
+@token_required
+def update_tag(tag_id):
+ """Update an existing tag, ensuring user can only update their own type of tag."""
+ user_id = request.user['id']
+ data = request.get_json()
+ new_name = data.get('name')
+ new_color = data.get('color')
+
+ if not new_name:
+ return jsonify({"error": "Tag name cannot be empty"}), 400
+
+ # Validate color format (basic check)
+ if new_color and not re.match(r'^#[0-9a-fA-F]{6}$', new_color):
+ return jsonify({"error": "Invalid color format. Use hex (e.g., #RRGGBB)"}), 400
+
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if tag exists AND belongs to the user
+ cur.execute('SELECT id, user_id FROM tags WHERE id = %s', (tag_id,)) # Check user_id
+ tag = cur.fetchone()
+ if not tag:
+ return jsonify({"error": "Tag not found"}), 404
+
+ tag_user_id = tag[1]
+ if tag_user_id != user_id:
+ # Prevent user from updating tag they don't own
+ return jsonify({"error": "Permission denied to update this tag"}), 403
+
+ # Check if new name conflicts with another tag FOR THIS USER
+ cur.execute('SELECT id FROM tags WHERE name = %s AND id != %s AND user_id = %s',
+ (new_name, tag_id, user_id)) # Added user_id check
+ existing = cur.fetchone()
+ if existing:
+ # tag_type = "admin" if is_admin_updater else "user" # Removed
+ return jsonify({"error": f"Another tag with this name already exists for your account"}), 409 # Updated error message
+
+ # Update the tag
+ cur.execute('UPDATE tags SET name = %s, color = %s, updated_at = NOW() WHERE id = %s RETURNING id, name, color', \
+ (new_name, new_color, tag_id))
+ updated_tag = cur.fetchone()
+ # conn.commit() and return statement are part of the try block, outside the 'with' block.
+ conn.commit()
+ return jsonify({"id": updated_tag[0], "name": updated_tag[1], "color": updated_tag[2]}), 200
+
+ except Exception as e:
+ logger.error(f"Error updating tag {tag_id}: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to update tag"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@tags_bp.route('/tags/<int:tag_id>', methods=['DELETE'])
+@token_required
+def delete_tag_endpoint(tag_id):
+ """Delete a tag owned by the requesting user and its associations."""
+ user_id = request.user['id'] # Get user ID
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if tag exists AND belongs to the user
+ cur.execute('SELECT id, user_id FROM tags WHERE id = %s', (tag_id,)) # Check user_id
+ tag = cur.fetchone()
+ if not tag:
+ return jsonify({"error": "Tag not found"}), 404
+
+ tag_user_id = tag[1]
+ # Only allow deletion if the user owns the tag
+ if tag_user_id != user_id:
+ # Prevent users from deleting tags they don't own
+ return jsonify({"error": "Permission denied to delete this tag"}), 403
+
+ # Delete associations from warranty_tags first
+ cur.execute('DELETE FROM warranty_tags WHERE tag_id = %s', (tag_id,))
+
+ # Delete the tag itself
+ cur.execute('DELETE FROM tags WHERE id = %s', (tag_id,))
+
+ conn.commit()
+
+ return jsonify({"message": "Tag deleted successfully"}), 200
+
+ except Exception as e:
+ logger.error(f"Error deleting tag {tag_id}: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to delete tag"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+# ===============================
+# Warranty-Tag Association Routes
+# ===============================
+
+@tags_bp.route('/warranties/<int:warranty_id>/tags', methods=['GET'])
+@token_required
+def get_warranty_tags(warranty_id):
+ # """Get tags associated with a specific warranty, filtered by user role.""" # Docstring update needed
+ """Get tags associated with a specific warranty."""
+ conn = None
+ try:
+ user_id = request.user['id']
+ # is_admin = request.user.get('is_admin', False) # Removed
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # First check if the warranty exists and user has access to it
+ # Simplified check: just check if warranty exists and belongs to the user
+ cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s',
+ (warranty_id, user_id))
+
+ if cur.fetchone() is None:
+ # Add admin check here if admins should be able to see tags for any warranty
+ is_admin = request.user.get('is_admin', False)
+ if is_admin:
+ cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
+ if cur.fetchone() is None:
+ return jsonify({"error": "Warranty not found"}), 404
+ else:
+ return jsonify({"error": "Warranty not found or you don't have permission to access it"}), 404
+
+ # Get tags for this warranty (show all associated tags)
+ cur.execute('''
+ SELECT t.id, t.name, t.color, t.created_at
+ FROM tags t
+ JOIN warranty_tags wt ON t.id = wt.tag_id
+ WHERE wt.warranty_id = %s -- Removed user_id/is_admin filter
+ ORDER BY t.name
+ ''', (warranty_id,))
+
+ tags = cur.fetchall()
+
+ result = []
+ for tag in tags:
+ result.append({
+ 'id': tag[0],
+ 'name': tag[1],
+ 'color': tag[2],
+ 'created_at': tag[3].isoformat() if tag[3] else None
+ })
+
+ return jsonify(result), 200
+ except Exception as e:
+ logger.error(f"Error fetching tags for warranty {warranty_id}: {e}")
+ return jsonify({"error": "Failed to fetch tags for this warranty"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@tags_bp.route('/warranties/<int:warranty_id>/tags', methods=['POST'])
+@token_required
+def add_tags_to_warranty(warranty_id):
+ # """Add tags to a warranty, ensuring tags match user role.""" # Docstring update needed
+ """Add tags owned by the user to a warranty they own."""
+ conn = None
+ try:
+ user_id = request.user['id']
+ # is_admin = request.user.get('is_admin', False) # Removed
+
+ data = request.json
+ if not data or 'tag_ids' not in data:
+ return jsonify({"error": "tag_ids array is required"}), 400
+
+ tag_ids = data['tag_ids']
+ if not isinstance(tag_ids, list):
+ return jsonify({"error": "tag_ids must be an array of tag IDs"}), 400
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # First check if the warranty exists and user has access to it (owns it)
+ cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s',
+ (warranty_id, user_id))
+
+ if cur.fetchone() is None:
+ # Add admin check here if admins should modify any warranty tags
+ is_admin = request.user.get('is_admin', False)
+ if is_admin:
+ cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
+ if cur.fetchone() is None:
+ return jsonify({"error": "Warranty not found"}), 404
+ # Allow admin to proceed even if they don't own it
+ else:
+ return jsonify({"error": "Warranty not found or you don't have permission to modify it"}), 404
+
+ # Validate tags before removing/adding
+ valid_tag_ids = []
+ if tag_ids: # Only validate if there are tags to add
+ # Check if all provided tag IDs exist AND belong to the user
+ placeholders = ', '.join(['%s'] * len(tag_ids))
+ # Ensure the tags being added are owned by the user adding them
+ sql = f'SELECT id, user_id FROM tags WHERE id IN ({placeholders}) AND user_id = %s'
+ cur.execute(sql, tag_ids + [user_id]) # Check against current user_id
+ found_tags = cur.fetchall()
+
+ found_tag_map = {tag[0]: tag[1] for tag in found_tags}
+
+ for tag_id in tag_ids:
+ if tag_id not in found_tag_map: # This check also implicitly confirms ownership due to the query change
+ conn.rollback() # Ensure transaction consistency
+ return jsonify({"error": f"Tag with ID {tag_id} not found or not owned by you"}), 404
+ # Removed the old is_admin check
+ # if found_tag_map[tag_id] != is_admin:
+ # conn.rollback()
+ # tag_type_required = "admin" if is_admin else "user"
+ # return jsonify({"error": f"Tag with ID {tag_id} is not a valid {tag_type_required} tag"}), 403
+ valid_tag_ids.append(tag_id) # Keep track of validated tags
+
+ # Remove ALL existing tags before adding new ones for simplicity
+ # The old logic only removed tags of the same "type", which is no longer relevant
+ cur.execute('DELETE FROM warranty_tags WHERE warranty_id = %s', (warranty_id,))
+
+ # Add new (validated) tags
+ if valid_tag_ids:
+ values_placeholder = ', '.join(['(%s, %s)'] * len(valid_tag_ids))
+ sql = f'INSERT INTO warranty_tags (warranty_id, tag_id) VALUES {values_placeholder}'
+ params = []
+ for tag_id in valid_tag_ids:
+ params.extend([warranty_id, tag_id])
+ cur.execute(sql, params)
+
+ conn.commit()
+ return jsonify({"message": "Tags updated successfully"}), 200
+ except Exception as e:
+ logger.error(f"Error updating tags for warranty {warranty_id}: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to update tags"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
\ No newline at end of file
diff --git a/backend/utils.py b/backend/utils.py
new file mode 100644
index 0000000..bd8361a
--- /dev/null
+++ b/backend/utils.py
@@ -0,0 +1,9 @@
+# backend/utils.py
+"""
+Shared utility functions for the Warracker application
+"""
+
+def allowed_file(filename):
+ """Check if the file extension is allowed"""
+ ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg', 'zip', 'rar', 'webp', 'gif'}
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
\ No newline at end of file
diff --git a/backend/warranties_routes.py b/backend/warranties_routes.py
new file mode 100644
index 0000000..79e4de4
--- /dev/null
+++ b/backend/warranties_routes.py
@@ -0,0 +1,1771 @@
+# backend/warranties_routes.py
+from flask import Blueprint, request, jsonify, current_app, send_from_directory
+from werkzeug.utils import secure_filename
+from datetime import datetime, date
+from decimal import Decimal
+import os
+import json
+import csv
+import io
+from dateutil.relativedelta import relativedelta
+from dateutil.parser import parse as date_parse
+import mimetypes
+from flask import Response
+
+# Add pytz import for timezone functionality
+import pytz
+
+# Use relative imports for project modules
+try:
+ from .db_handler import get_db_connection, release_db_connection
+ from .auth_utils import token_required, admin_required
+ from .paperless_handler import get_paperless_handler
+ from .utils import allowed_file
+except ImportError:
+ # Fallback for development environment
+ from db_handler import get_db_connection, release_db_connection
+ from auth_utils import token_required, admin_required
+ from paperless_handler import get_paperless_handler
+ from utils import allowed_file
+
+import logging
+logger = logging.getLogger(__name__)
+
+warranties_bp = Blueprint('warranties_bp', __name__)
+
+
+
+def convert_decimals(obj):
+ """Recursively convert Decimal objects to float in dicts/lists for JSON serialization."""
+ if isinstance(obj, dict):
+ return {k: convert_decimals(v) for k, v in obj.items()}
+ elif isinstance(obj, list):
+ return [convert_decimals(i) for i in obj]
+ elif isinstance(obj, Decimal):
+ return float(obj)
+ else:
+ return obj
+
+@warranties_bp.route('/warranties', methods=['GET'])
+@token_required
+def get_warranties():
+ conn = None
+ try:
+ user_id = request.user['id']
+ # is_admin = request.user.get('is_admin', False) # Removed admin check
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Always fetch warranties belonging to the logged-in user
+ # Removed the if is_admin: block
+ # 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_type,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days, product_photo_path, currency,
+ paperless_invoice_id, paperless_manual_id, paperless_photo_id, paperless_other_id
+ 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]
+ warranties_list = []
+
+ for row in warranties:
+ warranty_dict = dict(zip(columns, row))
+ # Convert date objects to ISO format strings for JSON serialization
+ for key, value in warranty_dict.items():
+ if isinstance(value, (datetime, date)):
+ warranty_dict[key] = value.isoformat()
+ # Convert Decimal objects to float for JSON serialization
+ elif isinstance(value, Decimal):
+ warranty_dict[key] = float(value)
+
+ # Get serial numbers for this warranty
+ warranty_id = warranty_dict['id']
+ cur.execute('SELECT serial_number FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))
+ serial_numbers = [row[0] for row in cur.fetchall()]
+ warranty_dict['serial_numbers'] = serial_numbers
+
+ # Get tags for this warranty (show all associated tags the user can see via warranty access)
+ cur.execute('''
+ SELECT t.id, t.name, t.color
+ FROM tags t
+ JOIN warranty_tags wt ON t.id = wt.tag_id
+ WHERE wt.warranty_id = %s -- Removed user_id/is_admin filter here
+ ORDER BY t.name
+ ''', (warranty_id,))
+ tags = [{'id': t[0], 'name': t[1], 'color': t[2]} for t in cur.fetchall()]
+ warranty_dict['tags'] = tags
+
+ warranties_list.append(warranty_dict)
+
+ return jsonify(warranties_list)
+ except Exception as e:
+ current_app.logger.error(f"Error retrieving warranties: {e}")
+ return jsonify({"error": "Failed to retrieve warranties"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@warranties_bp.route('/warranties', methods=['POST'])
+@token_required
+def add_warranty():
+ conn = None
+ try:
+ # Validate input data
+ if not request.form.get('product_name'):
+ return jsonify({"error": "Product name is required"}), 400
+
+ if not request.form.get('purchase_date'):
+ return jsonify({"error": "Purchase date is required"}), 400
+
+ # Handle lifetime warranty
+ is_lifetime = request.form.get('is_lifetime', 'false').lower() == 'true'
+ expiration_date = None
+ warranty_duration_years = 0
+ warranty_duration_months = 0
+ warranty_duration_days = 0
+
+ if not is_lifetime:
+ # Check if exact expiration date is provided
+ exact_expiration_date = request.form.get('exact_expiration_date')
+
+ if exact_expiration_date:
+ # Use exact expiration date provided by user
+ try:
+ expiration_date = datetime.strptime(exact_expiration_date, '%Y-%m-%d').date()
+ logger.info(f"Using exact expiration date: {expiration_date}")
+ # Set duration fields to 0 when using exact date
+ warranty_duration_years = 0
+ warranty_duration_months = 0
+ warranty_duration_days = 0
+ except ValueError:
+ return jsonify({"error": "Invalid exact expiration date format. Use YYYY-MM-DD"}), 400
+ else:
+ # Use duration-based calculation (existing logic)
+ try:
+ # 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_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 > 999:
+ return jsonify({"error": "Warranty years must be 999 or less"}), 400
+
+ except ValueError:
+ return jsonify({"error": "Warranty duration components must be valid numbers."}), 400
+
+ # Process the data
+ product_name = request.form['product_name']
+ purchase_date_str = request.form['purchase_date']
+ serial_numbers = request.form.getlist('serial_numbers[]')
+ product_url = request.form.get('product_url', '')
+ user_id = request.user['id']
+ notes = request.form.get('notes', '')
+ vendor = request.form.get('vendor', None)
+ warranty_type = request.form.get('warranty_type', None)
+
+ # Get tag IDs if provided
+ tag_ids = []
+ if request.form.get('tag_ids'):
+ try:
+ tag_ids = json.loads(request.form.get('tag_ids'))
+ if not isinstance(tag_ids, list):
+ return jsonify({"error": "tag_ids must be a JSON array"}), 400
+ except json.JSONDecodeError:
+ return jsonify({"error": "tag_ids must be a valid JSON array"}), 400
+
+ # Handle purchase price (optional)
+ purchase_price = None
+ if request.form.get('purchase_price'):
+ try:
+ purchase_price = float(request.form.get('purchase_price'))
+ if purchase_price < 0:
+ return jsonify({"error": "Purchase price cannot be negative"}), 400
+ except ValueError:
+ return jsonify({"error": "Purchase price must be a valid number"}), 400
+
+ # Handle currency (optional, defaults to USD)
+ currency = request.form.get('currency', 'USD')
+ # Validate currency code
+ valid_currencies = [
+ 'USD', 'EUR', 'GBP', 'JPY', 'CNY', 'INR', 'KRW', 'CHF', 'CAD', 'AUD',
+ 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'HUF', 'BGN', 'RON', 'HRK', 'RUB',
+ 'BRL', 'MXN', 'ARS', 'CLP', 'COP', 'PEN', 'VES', 'ZAR', 'EGP', 'NGN',
+ 'KES', 'GHS', 'MAD', 'TND', 'AED', 'SAR', 'QAR', 'KWD', 'BHD', 'OMR',
+ 'JOD', 'LBP', 'ILS', 'TRY', 'IRR', 'PKR', 'BDT', 'LKR', 'NPR', 'BTN',
+ 'MMK', 'THB', 'VND', 'LAK', 'KHR', 'MYR', 'SGD', 'IDR', 'PHP', 'TWD',
+ 'HKD', 'MOP', 'KPW', 'MNT', 'KZT', 'UZS', 'TJS', 'KGS', 'TMT', 'AFN',
+ 'AMD', 'AZN', 'GEL', 'MDL', 'UAH', 'BYN', 'RSD', 'MKD', 'ALL', 'BAM',
+ 'ISK', 'FJD', 'PGK', 'SBD', 'TOP', 'VUV', 'WST', 'XPF', 'NZD'
+ ]
+ if currency not in valid_currencies:
+ return jsonify({"error": f"Invalid currency code: {currency}"}), 400
+
+ try:
+ purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d').date()
+ except ValueError:
+ return jsonify({"error": "Invalid date format. Use YYYY-MM-DD"}), 400
+
+ # Calculate expiration date only if not lifetime
+ if not is_lifetime:
+ # Check if exact expiration date is provided
+ exact_expiration_date = request.form.get('exact_expiration_date')
+
+ if exact_expiration_date:
+ # Use exact expiration date provided by user
+ try:
+ expiration_date = datetime.strptime(exact_expiration_date, '%Y-%m-%d').date()
+ logger.info(f"Using exact expiration date: {expiration_date}")
+ except ValueError:
+ return jsonify({"error": "Invalid exact expiration date format. Use YYYY-MM-DD"}), 400
+ elif warranty_duration_years > 0 or warranty_duration_months > 0 or warranty_duration_days > 0:
+ # Use duration-based calculation
+ 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:
+ # Neither exact date nor duration provided
+ return jsonify({"error": "Either exact expiration date or warranty duration must be specified for non-lifetime warranties."}), 400
+
+ # Handle Paperless-ngx document IDs if provided (check before file uploads)
+ paperless_invoice_id = request.form.get('paperless_invoice_id')
+ paperless_manual_id = request.form.get('paperless_manual_id')
+ paperless_photo_id = request.form.get('paperless_photo_id')
+ paperless_other_id = request.form.get('paperless_other_id')
+
+ # Convert empty strings to None for database insertion
+ paperless_invoice_id = int(paperless_invoice_id) if paperless_invoice_id and paperless_invoice_id.strip() else None
+ paperless_manual_id = int(paperless_manual_id) if paperless_manual_id and paperless_manual_id.strip() else None
+ paperless_photo_id = int(paperless_photo_id) if paperless_photo_id and paperless_photo_id.strip() else None
+ paperless_other_id = int(paperless_other_id) if paperless_other_id and paperless_other_id.strip() else None
+
+ # Handle invoice file upload (only if not stored in Paperless-ngx)
+ db_invoice_path = None
+ if not paperless_invoice_id and 'invoice' in request.files:
+ invoice = request.files['invoice']
+ if invoice.filename != '':
+ if not allowed_file(invoice.filename):
+ return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
+
+ filename = secure_filename(invoice.filename)
+ filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
+ invoice_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
+
+ 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
+ elif paperless_invoice_id:
+ logger.info(f"Invoice stored in Paperless-ngx with ID: {paperless_invoice_id}")
+
+ # Handle manual file upload (only if not stored in Paperless-ngx)
+ db_manual_path = None
+ if not paperless_manual_id and 'manual' in request.files:
+ manual = request.files['manual']
+ if manual.filename != '':
+ if not allowed_file(manual.filename):
+ return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
+
+ filename = secure_filename(manual.filename)
+ filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_manual_{filename}"
+ manual_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
+ 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
+ elif paperless_manual_id:
+ logger.info(f"Manual stored in Paperless-ngx with ID: {paperless_manual_id}")
+
+ # Handle other_document file upload (only if not stored in Paperless-ngx)
+ db_other_document_path = None
+ if not paperless_other_id and '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(current_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
+ elif paperless_other_id:
+ logger.info(f"Other document stored in Paperless-ngx with ID: {paperless_other_id}")
+
+ # Handle product photo file upload (only if not stored in Paperless-ngx)
+ db_product_photo_path = None
+ if not paperless_photo_id and 'product_photo' in request.files:
+ product_photo = request.files['product_photo']
+ if product_photo.filename != '':
+ # Check if it's an image file
+ if not (product_photo.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.gif'))):
+ return jsonify({"error": "Product photo must be an image file (PNG, JPG, JPEG, WEBP, GIF)"}), 400
+
+ filename = secure_filename(product_photo.filename)
+ filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_photo_{filename}"
+ product_photo_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
+ logger.info(f"Attempting to save product_photo to: {product_photo_path_on_disk}")
+ try:
+ product_photo.save(product_photo_path_on_disk)
+ db_product_photo_path = os.path.join('uploads', filename)
+ logger.info(f"Successfully saved product_photo: {db_product_photo_path}")
+ except Exception as e:
+ logger.error(f"Error saving product_photo {filename} to {product_photo_path_on_disk}: {e}")
+ return jsonify({"error": f"Failed to save product_photo: {str(e)}"}), 500
+ elif paperless_photo_id:
+ logger.info(f"Product photo stored in Paperless-ngx with ID: {paperless_photo_id}")
+
+
+
+ # Save to database
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Insert warranty
+ cur.execute('''
+ INSERT INTO warranties (
+ product_name, purchase_date, expiration_date,
+ invoice_path, manual_path, other_document_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor, warranty_type,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days, product_photo_path, currency,
+ paperless_invoice_id, paperless_manual_id, paperless_photo_id, paperless_other_id
+ )
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
+ RETURNING id
+ ''', (
+ product_name, purchase_date, expiration_date,
+ db_invoice_path, db_manual_path, db_other_document_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor, warranty_type,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days, db_product_photo_path, currency,
+ paperless_invoice_id, paperless_manual_id, paperless_photo_id, paperless_other_id
+ ))
+ warranty_id = cur.fetchone()[0]
+
+ # Insert serial numbers
+ if serial_numbers:
+ for serial_number in serial_numbers:
+ if serial_number.strip(): # Only insert non-empty serial numbers
+ cur.execute('''
+ INSERT INTO serial_numbers (warranty_id, serial_number)
+ VALUES (%s, %s)
+ ''', (warranty_id, serial_number.strip()))
+
+ # Insert tags if provided
+ if tag_ids:
+ for tag_id in tag_ids:
+ # Verify tag exists
+ cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
+ if cur.fetchone():
+ cur.execute('''
+ INSERT INTO warranty_tags (warranty_id, tag_id)
+ VALUES (%s, %s)
+ ''', (warranty_id, tag_id))
+ else:
+ logger.warning(f"Skipping non-existent tag ID: {tag_id}")
+
+ conn.commit()
+
+ return jsonify({
+ 'message': 'Warranty added successfully',
+ 'id': warranty_id
+ }), 201
+
+ except Exception as e:
+ logger.error(f"Error adding warranty: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to add warranty"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@warranties_bp.route('/warranties/<int:warranty_id>', methods=['DELETE'])
+@token_required
+def delete_warranty(warranty_id):
+ conn = None
+ try:
+ user_id = request.user['id']
+ is_admin = request.user['is_admin']
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if warranty exists and belongs to the user
+ if is_admin:
+ cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
+ else:
+ cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s', (warranty_id, user_id))
+
+ warranty = cur.fetchone()
+
+ if not warranty:
+ return jsonify({"error": "Warranty not found or you don't have permission to delete it"}), 404
+
+ # First get the file paths to delete the files
+ cur.execute('SELECT invoice_path, manual_path, other_document_path, product_photo_path FROM warranties WHERE id = %s', (warranty_id,))
+ result = cur.fetchone()
+
+ invoice_path = result[0]
+ manual_path = result[1]
+ other_document_path = result[2]
+ product_photo_path = result[3]
+
+ # Delete the warranty from database
+ cur.execute('DELETE FROM warranties WHERE id = %s', (warranty_id,))
+ deleted_rows = cur.rowcount
+ conn.commit()
+
+ # Delete the invoice file if it exists
+ if invoice_path:
+ full_path = os.path.join('/data', invoice_path)
+ if os.path.exists(full_path):
+ os.remove(full_path)
+
+ # Delete the manual file if it exists
+ if manual_path:
+ full_path = os.path.join('/data', manual_path)
+ 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)
+
+ # Delete the product photo file if it exists
+ if product_photo_path:
+ full_path = os.path.join('/data', product_photo_path)
+ if os.path.exists(full_path):
+ os.remove(full_path)
+
+ return jsonify({"message": "Warranty deleted successfully"}), 200
+
+ except Exception as e:
+ logger.error(f"Error deleting warranty: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to delete warranty"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@warranties_bp.route('/warranties/<int:warranty_id>', methods=['PUT'])
+@token_required
+def update_warranty(warranty_id):
+ # --- Log function entry ---
+ logger.info(f"Entering update_warranty function for ID: {warranty_id}")
+ conn = None
+ try:
+ user_id = request.user['id']
+ is_admin = request.user['is_admin']
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if warranty exists and belongs to the user
+ if is_admin:
+ cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
+ else:
+ cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s', (warranty_id, user_id))
+ warranty = cur.fetchone()
+ if not warranty:
+ return jsonify({"error": "Warranty not found or you don't have permission to update it"}), 404
+
+ # --- PATCH: Support JSON-only notes update ---
+ if request.is_json and 'notes' in request.json and len(request.json) == 1:
+ notes = request.json.get('notes', None)
+ cur.execute("UPDATE warranties SET notes = %s, updated_at = NOW() WHERE id = %s", (notes, warranty_id))
+ conn.commit()
+ return jsonify({"message": "Notes updated successfully"}), 200
+
+ # --- Otherwise, continue with the original (form-based) update logic ---
+ # Validate input data similar to the add_warranty route
+ if not request.form.get('product_name'):
+ return jsonify({"error": "Product name is required"}), 400
+ if not request.form.get('purchase_date'):
+ return jsonify({"error": "Purchase date is required"}), 400
+ logger.info(f"Received update request for warranty {warranty_id}")
+ 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']
+ try:
+ 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
+
+ expiration_date = None
+ warranty_duration_years = 0
+ warranty_duration_months = 0
+ warranty_duration_days = 0
+
+ if not is_lifetime:
+ # Check if exact expiration date is provided
+ exact_expiration_date = request.form.get('exact_expiration_date')
+
+ if exact_expiration_date:
+ # Use exact expiration date provided by user
+ try:
+ expiration_date = datetime.strptime(exact_expiration_date, '%Y-%m-%d').date()
+ logger.info(f"Using exact expiration date: {expiration_date}")
+ # Set duration fields to 0 when using exact date
+ warranty_duration_years = 0
+ warranty_duration_months = 0
+ warranty_duration_days = 0
+ except ValueError:
+ return jsonify({"error": "Invalid exact expiration date format. Use YYYY-MM-DD"}), 400
+ else:
+ # Use duration-based calculation (existing logic)
+ try:
+ # 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_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 > 999:
+ return jsonify({"error": "Warranty years must be 999 or less"}), 400
+
+ except ValueError:
+ return jsonify({"error": "Warranty duration components must be valid numbers."}), 400
+
+ # Calculate expiration date based on duration only if exact date wasn't provided
+ if not exact_expiration_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"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:
+ return jsonify({"error": "Either exact expiration date or warranty duration must be specified for non-lifetime warranties."}), 400
+
+ 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[]') # Ensure correct parsing for lists
+ product_url = request.form.get('product_url', '')
+ notes = request.form.get('notes', None)
+ vendor = request.form.get('vendor', None)
+ warranty_type = request.form.get('warranty_type', None)
+ tag_ids = []
+ if request.form.get('tag_ids'):
+ try:
+ tag_ids = json.loads(request.form.get('tag_ids'))
+ if not isinstance(tag_ids, list):
+ return jsonify({"error": "tag_ids must be a JSON array"}), 400
+ except json.JSONDecodeError:
+ return jsonify({"error": "tag_ids must be a valid JSON array"}), 400
+ purchase_price = None
+ if request.form.get('purchase_price'):
+ try:
+ purchase_price = float(request.form.get('purchase_price'))
+ if purchase_price < 0:
+ return jsonify({"error": "Purchase price cannot be negative"}), 400
+ except ValueError:
+ return jsonify({"error": "Purchase price must be a valid number"}), 400
+
+ # Handle currency (optional, defaults to USD)
+ currency = request.form.get('currency', 'USD')
+ # Validate currency code
+ valid_currencies = [
+ 'USD', 'EUR', 'GBP', 'JPY', 'CNY', 'INR', 'KRW', 'CHF', 'CAD', 'AUD',
+ 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'HUF', 'BGN', 'RON', 'HRK', 'RUB',
+ 'BRL', 'MXN', 'ARS', 'CLP', 'COP', 'PEN', 'VES', 'ZAR', 'EGP', 'NGN',
+ 'KES', 'GHS', 'MAD', 'TND', 'AED', 'SAR', 'QAR', 'KWD', 'BHD', 'OMR',
+ 'JOD', 'LBP', 'ILS', 'TRY', 'IRR', 'PKR', 'BDT', 'LKR', 'NPR', 'BTN',
+ 'MMK', 'THB', 'VND', 'LAK', 'KHR', 'MYR', 'SGD', 'IDR', 'PHP', 'TWD',
+ 'HKD', 'MOP', 'KPW', 'MNT', 'KZT', 'UZS', 'TJS', 'KGS', 'TMT', 'AFN',
+ 'AMD', 'AZN', 'GEL', 'MDL', 'UAH', 'BYN', 'RSD', 'MKD', 'ALL', 'BAM',
+ 'ISK', 'FJD', 'PGK', 'SBD', 'TOP', 'VUV', 'WST', 'XPF', 'NZD'
+ ]
+ if currency not in valid_currencies:
+ return jsonify({"error": f"Invalid currency code: {currency}"}), 400
+
+ # Handle Paperless-ngx document IDs
+ paperless_invoice_id = request.form.get('paperless_invoice_id')
+ paperless_manual_id = request.form.get('paperless_manual_id')
+ paperless_photo_id = request.form.get('paperless_photo_id')
+ paperless_other_id = request.form.get('paperless_other_id')
+
+ logger.info(f"[UPDATE] Received Paperless IDs: invoice={paperless_invoice_id}, manual={paperless_manual_id}, photo={paperless_photo_id}, other={paperless_other_id}")
+
+ # Convert to integers if provided, otherwise None
+ paperless_invoice_id = int(paperless_invoice_id) if paperless_invoice_id and paperless_invoice_id.strip() else None
+ paperless_manual_id = int(paperless_manual_id) if paperless_manual_id and paperless_manual_id.strip() else None
+ paperless_photo_id = int(paperless_photo_id) if paperless_photo_id and paperless_photo_id.strip() else None
+ paperless_other_id = int(paperless_other_id) if paperless_other_id and paperless_other_id.strip() else None
+
+ logger.info(f"[UPDATE] Converted Paperless IDs: invoice={paperless_invoice_id}, manual={paperless_manual_id}, photo={paperless_photo_id}, other={paperless_other_id}")
+
+ # File handling for invoice
+ db_invoice_path = None
+ if not paperless_invoice_id and 'invoice' in request.files:
+ invoice = request.files['invoice']
+ if invoice.filename != '':
+ if not allowed_file(invoice.filename):
+ return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
+ cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_invoice_path = cur.fetchone()[0]
+ if old_invoice_path:
+ full_path = os.path.join('/data', old_invoice_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted old invoice: {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting old invoice: {e}")
+ filename = secure_filename(invoice.filename)
+ filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
+ invoice_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
+ 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 paperless_invoice_id:
+ logger.info(f"Invoice updated to Paperless-ngx with ID: {paperless_invoice_id}")
+ # Clear local path when storing in Paperless-ngx
+ cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_invoice_path = cur.fetchone()[0]
+ if old_invoice_path:
+ full_path = os.path.join('/data', old_invoice_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted old local invoice (moving to Paperless): {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting old local invoice: {e}")
+ db_invoice_path = None # Clear local path
+ 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]
+ if old_invoice_path:
+ full_path = os.path.join('/data', old_invoice_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted invoice (delete request): {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting invoice (delete request): {e}")
+ db_invoice_path = None # Set to None to clear in DB
+
+ # File handling for manual
+ db_manual_path = None
+ if not paperless_manual_id and 'manual' in request.files:
+ manual = request.files['manual']
+ if manual.filename != '':
+ if not allowed_file(manual.filename):
+ return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
+ cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_manual_path = cur.fetchone()[0]
+ if old_manual_path:
+ full_path = os.path.join('/data', old_manual_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted old manual: {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting old manual: {e}")
+ filename = secure_filename(manual.filename)
+ filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_manual_{filename}"
+ manual_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
+ 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 paperless_manual_id:
+ logger.info(f"Manual updated to Paperless-ngx with ID: {paperless_manual_id}")
+ # Clear local path when storing in Paperless-ngx
+ cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_manual_path = cur.fetchone()[0]
+ if old_manual_path:
+ full_path = os.path.join('/data', old_manual_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted old local manual (moving to Paperless): {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting old local manual: {e}")
+ db_manual_path = None # Clear local path
+ 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]
+ if old_manual_path:
+ full_path = os.path.join('/data', old_manual_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted manual (delete request): {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting manual (delete request): {e}")
+ db_manual_path = None # Set to None to clear in DB
+
+ # File handling for other document
+ db_other_document_path = None
+ if not paperless_other_id and '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(current_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 paperless_other_id:
+ logger.info(f"Other document updated to Paperless-ngx with ID: {paperless_other_id}")
+ # Clear local path when storing in Paperless-ngx
+ 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 local other_document (moving to Paperless): {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting old local other_document: {e}")
+ db_other_document_path = None # Clear local path
+ 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
+
+ # Handle product photo file upload (only if not stored in Paperless-ngx)
+ db_product_photo_path = None
+ if not paperless_photo_id and 'product_photo' in request.files:
+ product_photo = request.files['product_photo']
+ if product_photo.filename != '':
+ # Check if it's an image file
+ if not (product_photo.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.gif'))):
+ return jsonify({"error": "Product photo must be an image file (PNG, JPG, JPEG, WEBP, GIF)"}), 400
+
+ # Delete old photo if it exists
+ cur.execute('SELECT product_photo_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_product_photo_path = cur.fetchone()[0]
+ if old_product_photo_path:
+ full_path = os.path.join('/data', old_product_photo_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted old product_photo: {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting old product_photo: {e}")
+
+ filename = secure_filename(product_photo.filename)
+ filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_photo_{filename}"
+ product_photo_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
+ logger.info(f"Attempting to save updated product_photo to: {product_photo_path_on_disk}")
+ try:
+ product_photo.save(product_photo_path_on_disk)
+ db_product_photo_path = os.path.join('uploads', filename)
+ logger.info(f"Successfully saved updated product_photo: {db_product_photo_path}")
+ except Exception as e:
+ logger.error(f"Error saving updated product_photo {filename} to {product_photo_path_on_disk}: {e}")
+ return jsonify({"error": f"Failed to save updated product_photo: {str(e)}"}), 500
+ elif paperless_photo_id:
+ logger.info(f"Product photo updated to Paperless-ngx with ID: {paperless_photo_id}")
+ # Clear local path when storing in Paperless-ngx
+ cur.execute('SELECT product_photo_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_product_photo_path = cur.fetchone()[0]
+ if old_product_photo_path:
+ full_path = os.path.join('/data', old_product_photo_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted old local product_photo (moving to Paperless): {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting old local product_photo: {e}")
+ db_product_photo_path = None # Clear local path
+ elif request.form.get('delete_product_photo', 'false').lower() == 'true':
+ cur.execute('SELECT product_photo_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_product_photo_path = cur.fetchone()[0]
+ if old_product_photo_path:
+ full_path = os.path.join('/data', old_product_photo_path)
+ if os.path.exists(full_path):
+ try:
+ os.remove(full_path)
+ logger.info(f"Deleted product_photo (delete request): {full_path}")
+ except Exception as e:
+ logger.error(f"Error deleting product_photo (delete request): {e}")
+ db_product_photo_path = None # Set to None to clear in DB
+
+ # Prepare update parameters
+ update_params = {
+ 'product_name': product_name,
+ 'purchase_date': purchase_date,
+ 'is_lifetime': is_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,
+ 'vendor': vendor,
+ 'warranty_type': warranty_type,
+ 'currency': currency
+ }
+ sql_fields = []
+ sql_values = []
+ for key, value in update_params.items():
+ sql_fields.append(f"{key} = %s")
+ sql_values.append(value)
+ if notes is not None:
+ sql_fields.append("notes = %s")
+ sql_values.append(notes)
+ if db_invoice_path is not None:
+ sql_fields.append("invoice_path = %s")
+ sql_values.append(db_invoice_path)
+ elif 'delete_invoice' in request.form and request.form.get('delete_invoice', 'false').lower() == 'true':
+ sql_fields.append("invoice_path = NULL")
+ sql_fields.append("paperless_invoice_id = NULL") # Also clear Paperless ID
+ if db_manual_path is not None:
+ sql_fields.append("manual_path = %s")
+ 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")
+ sql_fields.append("paperless_manual_id = NULL") # Also clear Paperless ID
+ 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("paperless_other_id = NULL") # Also clear Paperless ID
+ if db_product_photo_path is not None:
+ sql_fields.append("product_photo_path = %s")
+ sql_values.append(db_product_photo_path)
+ elif 'delete_product_photo' in request.form and request.form.get('delete_product_photo', 'false').lower() == 'true':
+ sql_fields.append("product_photo_path = NULL")
+ sql_fields.append("paperless_photo_id = NULL") # Also clear Paperless ID
+
+ # Handle Paperless-ngx document IDs
+ if paperless_invoice_id is not None:
+ sql_fields.append("paperless_invoice_id = %s")
+ sql_values.append(paperless_invoice_id)
+ if paperless_manual_id is not None:
+ sql_fields.append("paperless_manual_id = %s")
+ sql_values.append(paperless_manual_id)
+ if paperless_photo_id is not None:
+ sql_fields.append("paperless_photo_id = %s")
+ sql_values.append(paperless_photo_id)
+ if paperless_other_id is not None:
+ sql_fields.append("paperless_other_id = %s")
+ sql_values.append(paperless_other_id)
+
+ 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"
+ cur.execute(update_sql, sql_values)
+ logger.info(f"Updated warranty with SQL: {update_sql}")
+ logger.info(f"Parameters: {sql_values}")
+
+ # Update serial numbers
+ cur.execute('DELETE FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))
+ if serial_numbers:
+ for serial_number in serial_numbers:
+ if serial_number.strip(): # Only insert non-empty serial numbers
+ cur.execute('''
+ INSERT INTO serial_numbers (warranty_id, serial_number)
+ VALUES (%s, %s)
+ ''', (warranty_id, serial_number.strip()))
+
+ # Update tags if provided
+ if tag_ids is not None:
+ # Remove existing tags
+ cur.execute('DELETE FROM warranty_tags WHERE warranty_id = %s', (warranty_id,))
+
+ # Add new tags
+ for tag_id in tag_ids:
+ # Verify tag exists
+ cur.execute('SELECT id FROM tags WHERE id = %s', (tag_id,))
+ if cur.fetchone():
+ cur.execute('''
+ INSERT INTO warranty_tags (warranty_id, tag_id)
+ VALUES (%s, %s)
+ ''', (warranty_id, tag_id))
+ else:
+ logger.warning(f"Skipping non-existent tag ID: {tag_id}")
+
+ conn.commit()
+
+ return jsonify({"message": "Warranty updated successfully"}), 200
+
+ except Exception as e:
+ logger.error(f"Error updating warranty: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"error": "Failed to update warranty"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@warranties_bp.route('/warranties/import', methods=['POST'])
+@token_required
+def import_warranties():
+ if 'csv_file' not in request.files:
+ return jsonify({"error": "No CSV file provided"}), 400
+
+ file = request.files['csv_file']
+
+ if file.filename == '':
+ return jsonify({"error": "No selected file"}), 400
+
+ if not file.filename.lower().endswith('.csv'):
+ return jsonify({"error": "Invalid file type. Please upload a .csv file"}), 400
+
+ user_id = request.user['id']
+ conn = None
+ imported_count = 0
+ failed_rows = []
+ row_number = 1 # Start from 1 for header
+
+ # Required and optional CSV headers
+ REQUIRED_CSV_HEADERS = ['ProductName', 'PurchaseDate']
+ OPTIONAL_CSV_HEADERS = [
+ 'IsLifetime', 'PurchasePrice', 'SerialNumber', 'ProductURL', 'Tags', 'Vendor', 'WarrantyType',
+ 'WarrantyDurationYears', 'WarrantyDurationMonths', 'WarrantyDurationDays'
+ ]
+
+ try:
+ # Read the file content
+ stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
+ csv_reader = csv.DictReader(stream)
+
+ # Validate headers
+ headers = csv_reader.fieldnames
+ # Check required headers first
+ missing_required = [h for h in REQUIRED_CSV_HEADERS if h not in headers]
+ if missing_required:
+ return jsonify({"error": f"Missing required CSV columns: {', '.join(missing_required)}"}), 400
+
+ # Check for unknown headers
+ known_headers = set(REQUIRED_CSV_HEADERS + OPTIONAL_CSV_HEADERS)
+ unknown_headers = [h for h in headers if h not in known_headers]
+ if unknown_headers:
+ logger.warning(f"CSV file contains unknown headers which will be ignored: {', '.join(unknown_headers)}")
+
+ conn = get_db_connection()
+ conn.autocommit = False # Start transaction
+
+ with conn.cursor() as cur:
+ for row in csv_reader:
+ row_number += 1 # Increment for each data row (header is row 1)
+ errors = []
+ processed_row = {}
+
+ try:
+ # --- Data Extraction and Basic Validation ---
+ product_name = row.get('ProductName', '').strip()
+ purchase_date_str = row.get('PurchaseDate', '').strip()
+ is_lifetime_str = row.get('IsLifetime', 'false').strip().lower()
+
+ # 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()
+ tags_str = row.get('Tags', '').strip() # Get Tags string
+ vendor = row.get('Vendor', '').strip() # Extract Vendor
+ warranty_type = row.get('WarrantyType', '').strip() # Extract Warranty Type
+
+ if not product_name:
+ errors.append("ProductName is required.")
+ if not purchase_date_str:
+ errors.append("PurchaseDate is required.")
+
+ # --- Type/Format Validation ---
+ try:
+ purchase_date_dt = date_parse(purchase_date_str)
+ purchase_date = purchase_date_dt.date()
+ except ValueError:
+ errors.append("Invalid PurchaseDate format.")
+ purchase_date = None # Set to None to prevent further errors
+
+ is_lifetime = is_lifetime_str == 'true'
+ expiration_date = None
+ warranty_duration_years = 0
+ warranty_duration_months = 0
+ warranty_duration_days = 0
+
+ if not is_lifetime:
+ 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_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 > 999:
+ errors.append("WarrantyDurationYears must be 999 or less.")
+ except ValueError:
+ errors.append("WarrantyDurationYears, WarrantyDurationMonths, WarrantyDurationDays must be valid numbers.")
+
+ purchase_price = None
+ if purchase_price_str:
+ try:
+ purchase_price = float(purchase_price_str)
+ if purchase_price < 0:
+ errors.append("PurchasePrice cannot be negative.")
+ except ValueError:
+ errors.append("PurchasePrice must be a valid number.")
+
+ # Calculate expiration date if valid
+ 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 []
+
+ # --- Process Tags ---
+ tag_ids_to_link = []
+ if tags_str:
+ tag_names = [name.strip() for name in tags_str.split(',') if name.strip()]
+ if tag_names:
+ # Find existing tag IDs (case-insensitive) for THIS USER
+ placeholders = ', '.join(['%s'] * len(tag_names))
+ # Include user_id in the lookup
+ sql = f"SELECT id, LOWER(name) FROM tags WHERE LOWER(name) IN ({placeholders}) AND user_id = %s"
+ cur.execute(sql, [name.lower() for name in tag_names] + [user_id]) # Add user_id
+ existing_tags = {name_lower: tag_id for tag_id, name_lower in cur.fetchall()}
+
+ processed_tag_ids = []
+ tags_to_create = []
+
+ for name in tag_names:
+ name_lower = name.lower()
+ if name_lower in existing_tags:
+ processed_tag_ids.append(existing_tags[name_lower])
+ else:
+ # Avoid queuing the same new tag multiple times within the same row
+ if name_lower not in [t['name_lower'] for t in tags_to_create]:
+ tags_to_create.append({'name': name, 'name_lower': name_lower})
+
+ # Create tags that don't exist for this user
+ if tags_to_create:
+ default_color = '#808080' # Default color for new tags
+ for tag_data in tags_to_create:
+ try:
+ # Insert new tag with default color, preserving original case for name, AND user_id
+ cur.execute(
+ "INSERT INTO tags (name, color, user_id) VALUES (%s, %s, %s) RETURNING id",
+ (tag_data['name'], default_color, user_id) # Add user_id
+ )
+ new_tag_id = cur.fetchone()[0]
+ processed_tag_ids.append(new_tag_id)
+ logger.info(f"Created new tag '{(tag_data['name'])}' with ID {new_tag_id} for user {user_id} during CSV import.")
+ except Exception as tag_insert_err:
+ # If tag creation fails (e.g., unique constraint conflict due to race condition),
+ # ensure the constraint includes user_id
+ logger.error(f"Error creating tag '{(tag_data['name'])}' for user {user_id} during import: {tag_insert_err}")
+ # Attempt to fetch the ID again in case it was created by another process
+ cur.execute("SELECT id FROM tags WHERE LOWER(name) = %s AND user_id = %s", (tag_data['name_lower'], user_id))
+ existing_id_result = cur.fetchone()
+ if existing_id_result:
+ processed_tag_ids.append(existing_id_result[0])
+ else:
+ # Add error to the row if tag creation failed and wasn't found
+ errors.append(f"Failed to create or find tag: {(tag_data['name'])}")
+
+ # Consolidate tag IDs to link
+ if processed_tag_ids:
+ tag_ids_to_link = list(set(processed_tag_ids)) # Ensure unique IDs
+
+ # --- Check for Duplicates ---
+ if not errors and product_name and purchase_date:
+ cur.execute("""
+ SELECT id FROM warranties
+ WHERE user_id = %s AND product_name = %s AND purchase_date = %s
+ """, (user_id, product_name, purchase_date))
+ if cur.fetchone(): # Correctly indented
+ errors.append("Duplicate warranty found (same product name and purchase date).")
+
+ # --- If errors, skip row ---
+ if errors:
+ failed_rows.append({"row": row_number, "errors": errors})
+ continue
+
+ # --- Get user's preferred currency code ---
+ user_currency_code = 'USD' # Default fallback
+ try:
+ # Get user's preferred currency symbol from their preferences
+ cur.execute("""
+ SELECT currency_symbol FROM user_preferences
+ WHERE user_id = %s
+ """, (user_id,))
+ currency_result = cur.fetchone()
+
+ if currency_result and currency_result[0]:
+ user_symbol = currency_result[0]
+ # Map common currency symbols to currency codes (same as frontend logic)
+ symbol_to_currency_map = {
+ '$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'JPY', '₹': 'INR', '₩': 'KRW',
+ 'CHF': 'CHF', 'C$': 'CAD', 'A$': 'AUD', 'kr': 'SEK', 'zł': 'PLN',
+ 'Kč': 'CZK', 'Ft': 'HUF', '₽': 'RUB', 'R$': 'BRL', '₦': 'NGN',
+ '₪': 'ILS', '₺': 'TRY', '₨': 'PKR', '৳': 'BDT', '฿': 'THB',
+ '₫': 'VND', 'RM': 'MYR', 'S$': 'SGD', 'Rp': 'IDR', '₱': 'PHP',
+ 'NT$': 'TWD', 'HK$': 'HKD', '₮': 'MNT', '₸': 'KZT', '₼': 'AZN',
+ '₾': 'GEL', '₴': 'UAH', 'NZ$': 'NZD'
+ }
+
+ if user_symbol in symbol_to_currency_map:
+ user_currency_code = symbol_to_currency_map[user_symbol]
+ logger.info(f"[Import] Using user's preferred currency: {user_symbol} -> {user_currency_code} for user {user_id}")
+ else:
+ logger.info(f"[Import] Unknown currency symbol '{user_symbol}' for user {user_id}, defaulting to USD")
+ else:
+ logger.info(f"[Import] No currency preference found for user {user_id}, defaulting to USD")
+ except Exception as currency_err:
+ logger.error(f"[Import] Error getting user currency preference: {currency_err}, defaulting to USD")
+
+ # --- Insert into Database ---
+ cur.execute("""
+ INSERT INTO warranties (
+ product_name, purchase_date, expiration_date,
+ product_url, purchase_price, user_id, is_lifetime, vendor, warranty_type,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days, currency
+ )
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
+ RETURNING id
+ """, (
+ product_name, purchase_date, expiration_date,
+ product_url, purchase_price, user_id, is_lifetime, vendor, warranty_type,
+ warranty_duration_years, warranty_duration_months, warranty_duration_days, user_currency_code
+ ))
+ warranty_id = cur.fetchone()[0]
+
+ # Insert serial numbers
+ if serial_numbers:
+ for serial_number in serial_numbers:
+ cur.execute("""
+ INSERT INTO serial_numbers (warranty_id, serial_number)
+ VALUES (%s, %s)
+ """, (warranty_id, serial_number))
+
+ # Link tags
+ if tag_ids_to_link:
+ for tag_id in tag_ids_to_link:
+ cur.execute("""
+ INSERT INTO warranty_tags (warranty_id, tag_id)
+ VALUES (%s, %s)
+ ON CONFLICT (warranty_id, tag_id) DO NOTHING -- Avoid errors if somehow duplicated
+ """, (warranty_id, tag_id))
+
+ imported_count += 1
+
+ except Exception as e:
+ logger.error(f"Error processing CSV row {row_number}: {e}")
+ failed_rows.append({"row": row_number, "errors": [f"Internal processing error: {str(e)}"]})
+ # Don't rollback yet, just record failure
+
+ # --- Transaction Commit/Rollback ---
+ if failed_rows:
+ conn.rollback() # Rollback if any row failed during processing or insertion
+ # Reset imported count if we rollback
+ final_success_count = 0
+ # Modify errors for rows that might have been initially valid but failed due to rollback
+ final_failure_count = row_number - 1 # Total data rows processed
+ # Add a general error message
+ return jsonify({
+ "error": "Import failed due to errors in one or more rows. No warranties were imported.",
+ "success_count": 0,
+ "failure_count": final_failure_count,
+ "errors": failed_rows
+ }), 400
+ else:
+ conn.commit() # Commit transaction if all rows were processed successfully
+ final_success_count = imported_count
+ final_failure_count = len(failed_rows)
+
+ return jsonify({
+ "message": "CSV processed.",
+ "success_count": final_success_count,
+ "failure_count": final_failure_count,
+ "errors": failed_rows
+ }), 200
+
+ except Exception as e:
+ if conn:
+ conn.rollback() # Rollback on general error
+ logger.error(f"Error importing CSV: {e}")
+ return jsonify({"error": f"Failed to import CSV: {str(e)}"}), 500
+ finally:
+ if conn:
+ conn.autocommit = True # Reset autocommit
+ release_db_connection(conn)
+
+@warranties_bp.route('/admin/warranties', methods=['GET'])
+@admin_required
+def get_all_warranties():
+ """Get all warranties from all users (admin only)"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Get all warranties from all users with user information
+ cur.execute('''
+ SELECT w.id, w.product_name, w.purchase_date, w.expiration_date, w.invoice_path, w.manual_path, w.other_document_path,
+ w.product_url, w.notes, w.purchase_price, w.user_id, w.created_at, w.updated_at, w.is_lifetime,
+ w.vendor, w.warranty_type, w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days, w.product_photo_path, w.currency,
+ u.username, u.email, u.first_name, u.last_name
+ FROM warranties w
+ JOIN users u ON w.user_id = u.id
+ ORDER BY u.username, CASE WHEN w.is_lifetime THEN 1 ELSE 0 END, w.expiration_date NULLS LAST, w.product_name
+ ''')
+
+ warranties = cur.fetchall()
+ columns = [desc[0] for desc in cur.description]
+ warranties_list = []
+
+ for row in warranties:
+ warranty_dict = dict(zip(columns, row))
+ # Convert date objects to ISO format strings for JSON serialization
+ for key, value in warranty_dict.items():
+ if isinstance(value, (datetime, date)):
+ warranty_dict[key] = value.isoformat()
+ # Convert Decimal objects to float for JSON serialization
+ elif isinstance(value, Decimal):
+ warranty_dict[key] = float(value)
+
+ # Get serial numbers for this warranty
+ warranty_id = warranty_dict['id']
+ cur.execute('SELECT serial_number FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))
+ serial_numbers = [row[0] for row in cur.fetchall()]
+ warranty_dict['serial_numbers'] = serial_numbers
+
+ # Get tags for this warranty
+ cur.execute('''
+ SELECT t.id, t.name, t.color
+ FROM tags t
+ JOIN warranty_tags wt ON t.id = wt.tag_id
+ WHERE wt.warranty_id = %s
+ ORDER BY t.name
+ ''', (warranty_id,))
+ tags = [{'id': t[0], 'name': t[1], 'color': t[2]} for t in cur.fetchall()]
+ warranty_dict['tags'] = tags
+
+ # Add user display name for better UI
+ first_name = warranty_dict.get('first_name', '').strip() if warranty_dict.get('first_name') else ''
+ last_name = warranty_dict.get('last_name', '').strip() if warranty_dict.get('last_name') else ''
+ username = warranty_dict.get('username', '').strip() if warranty_dict.get('username') else ''
+
+ if first_name and last_name:
+ warranty_dict['user_display_name'] = f"{first_name} {last_name}"
+ elif first_name:
+ warranty_dict['user_display_name'] = first_name
+ elif username:
+ warranty_dict['user_display_name'] = username
+ else:
+ warranty_dict['user_display_name'] = 'Unknown User'
+
+ warranties_list.append(warranty_dict)
+
+ return jsonify(warranties_list)
+ except Exception as e:
+ logger.error(f"Error retrieving all warranties: {e}")
+ return jsonify({"error": "Failed to retrieve all warranties"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@warranties_bp.route('/warranties/global', methods=['GET'])
+@token_required
+def get_global_warranties():
+ """Get all warranties from all users (public view for all authenticated users)"""
+ conn = None
+ try:
+ # Check if global view is enabled for this user
+ user_is_admin = request.user.get('is_admin', False)
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Get both global view settings
+ cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+
+ # Check if global view is enabled at all
+ global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'
+ if not global_view_enabled:
+ return jsonify({"error": "Global view is disabled by administrator"}), 403
+
+ # Check if global view is restricted to admins only
+ admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'
+ if admin_only and not user_is_admin:
+ return jsonify({"error": "Global view is restricted to administrators only"}), 403
+
+ # Release the connection since we'll get a new one below
+ release_db_connection(conn)
+ conn = None
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Get all warranties from all users with user information
+ cur.execute('''
+ SELECT w.id, w.product_name, w.purchase_date, w.expiration_date, w.invoice_path, w.manual_path, w.other_document_path,
+ w.product_url, w.notes, w.purchase_price, w.user_id, w.created_at, w.updated_at, w.is_lifetime,
+ w.vendor, w.warranty_type, w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days, w.product_photo_path, w.currency,
+ u.username, u.email, u.first_name, u.last_name
+ FROM warranties w
+ JOIN users u ON w.user_id = u.id
+ ORDER BY u.username, CASE WHEN w.is_lifetime THEN 1 ELSE 0 END, w.expiration_date NULLS LAST, w.product_name
+ ''')
+
+ warranties = cur.fetchall()
+ columns = [desc[0] for desc in cur.description]
+ warranties_list = []
+
+ for row in warranties:
+ warranty_dict = dict(zip(columns, row))
+ # Convert date objects to ISO format strings for JSON serialization
+ for key, value in warranty_dict.items():
+ if isinstance(value, (datetime, date)):
+ warranty_dict[key] = value.isoformat()
+ # Convert Decimal objects to float for JSON serialization
+ elif isinstance(value, Decimal):
+ warranty_dict[key] = float(value)
+
+ # Get serial numbers for this warranty
+ warranty_id = warranty_dict['id']
+ cur.execute('SELECT serial_number FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))
+ serial_numbers = [row[0] for row in cur.fetchall()]
+ warranty_dict['serial_numbers'] = serial_numbers
+
+ # Get tags for this warranty
+ cur.execute('''
+ SELECT t.id, t.name, t.color
+ FROM tags t
+ JOIN warranty_tags wt ON t.id = wt.tag_id
+ WHERE wt.warranty_id = %s
+ ORDER BY t.name
+ ''', (warranty_id,))
+ tags = [{'id': t[0], 'name': t[1], 'color': t[2]} for t in cur.fetchall()]
+ warranty_dict['tags'] = tags
+
+ # Add user display name for better UI
+ first_name = warranty_dict.get('first_name', '').strip() if warranty_dict.get('first_name') else ''
+ last_name = warranty_dict.get('last_name', '').strip() if warranty_dict.get('last_name') else ''
+ username = warranty_dict.get('username', '').strip() if warranty_dict.get('username') else ''
+
+ if first_name and last_name:
+ warranty_dict['user_display_name'] = f"{first_name} {last_name}"
+ elif first_name:
+ warranty_dict['user_display_name'] = first_name
+ elif username:
+ warranty_dict['user_display_name'] = username
+ else:
+ warranty_dict['user_display_name'] = 'Unknown User'
+
+ warranties_list.append(warranty_dict)
+
+ return jsonify(warranties_list)
+ except Exception as e:
+ logger.error(f"Error retrieving global warranties: {e}")
+ return jsonify({"error": "Failed to retrieve global warranties"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+
+@warranties_bp.route('/currencies', methods=['GET'])
+@token_required
+def get_currencies():
+ """Get list of available currencies with their symbols"""
+ try:
+ currencies = [
+ {'code': 'USD', 'name': 'US Dollar', 'symbol': '$'},
+ {'code': 'EUR', 'name': 'Euro', 'symbol': '€'},
+ {'code': 'GBP', 'name': 'British Pound', 'symbol': '£'},
+ {'code': 'JPY', 'name': 'Japanese Yen', 'symbol': '¥'},
+ {'code': 'CNY', 'name': 'Chinese Yuan', 'symbol': '¥'},
+ {'code': 'INR', 'name': 'Indian Rupee', 'symbol': '₹'},
+ {'code': 'KRW', 'name': 'South Korean Won', 'symbol': '₩'},
+ {'code': 'CHF', 'name': 'Swiss Franc', 'symbol': 'CHF'},
+ {'code': 'CAD', 'name': 'Canadian Dollar', 'symbol': 'C$'},
+ {'code': 'AUD', 'name': 'Australian Dollar', 'symbol': 'A$'},
+ {'code': 'SEK', 'name': 'Swedish Krona', 'symbol': 'kr'},
+ {'code': 'NOK', 'name': 'Norwegian Krone', 'symbol': 'kr'},
+ {'code': 'DKK', 'name': 'Danish Krone', 'symbol': 'kr'},
+ {'code': 'PLN', 'name': 'Polish Złoty', 'symbol': 'zł'},
+ {'code': 'CZK', 'name': 'Czech Koruna', 'symbol': 'Kč'},
+ {'code': 'HUF', 'name': 'Hungarian Forint', 'symbol': 'Ft'},
+ {'code': 'BGN', 'name': 'Bulgarian Lev', 'symbol': 'лв'},
+ {'code': 'RON', 'name': 'Romanian Leu', 'symbol': 'lei'},
+ {'code': 'HRK', 'name': 'Croatian Kuna', 'symbol': 'kn'},
+ {'code': 'RUB', 'name': 'Russian Ruble', 'symbol': '₽'},
+ {'code': 'BRL', 'name': 'Brazilian Real', 'symbol': 'R$'},
+ {'code': 'MXN', 'name': 'Mexican Peso', 'symbol': '$'},
+ {'code': 'ARS', 'name': 'Argentine Peso', 'symbol': '$'},
+ {'code': 'CLP', 'name': 'Chilean Peso', 'symbol': '$'},
+ {'code': 'COP', 'name': 'Colombian Peso', 'symbol': '$'},
+ {'code': 'PEN', 'name': 'Peruvian Sol', 'symbol': 'S/'},
+ {'code': 'VES', 'name': 'Venezuelan Bolívar', 'symbol': 'Bs'},
+ {'code': 'ZAR', 'name': 'South African Rand', 'symbol': 'R'},
+ {'code': 'EGP', 'name': 'Egyptian Pound', 'symbol': '£'},
+ {'code': 'NGN', 'name': 'Nigerian Naira', 'symbol': '₦'},
+ {'code': 'KES', 'name': 'Kenyan Shilling', 'symbol': 'KSh'},
+ {'code': 'GHS', 'name': 'Ghanaian Cedi', 'symbol': '₵'},
+ {'code': 'MAD', 'name': 'Moroccan Dirham', 'symbol': 'DH'},
+ {'code': 'TND', 'name': 'Tunisian Dinar', 'symbol': 'DT'},
+ {'code': 'AED', 'name': 'UAE Dirham', 'symbol': 'AED'},
+ {'code': 'SAR', 'name': 'Saudi Riyal', 'symbol': 'SR'},
+ {'code': 'QAR', 'name': 'Qatari Riyal', 'symbol': 'QR'},
+ {'code': 'KWD', 'name': 'Kuwaiti Dinar', 'symbol': 'KD'},
+ {'code': 'BHD', 'name': 'Bahraini Dinar', 'symbol': 'BD'},
+ {'code': 'OMR', 'name': 'Omani Rial', 'symbol': 'OR'},
+ {'code': 'JOD', 'name': 'Jordanian Dinar', 'symbol': 'JD'},
+ {'code': 'LBP', 'name': 'Lebanese Pound', 'symbol': 'LL'},
+ {'code': 'ILS', 'name': 'Israeli Shekel', 'symbol': '₪'},
+ {'code': 'TRY', 'name': 'Turkish Lira', 'symbol': '₺'},
+ {'code': 'IRR', 'name': 'Iranian Rial', 'symbol': '﷼'},
+ {'code': 'PKR', 'name': 'Pakistani Rupee', 'symbol': '₨'},
+ {'code': 'BDT', 'name': 'Bangladeshi Taka', 'symbol': '৳'},
+ {'code': 'LKR', 'name': 'Sri Lankan Rupee', 'symbol': 'Rs'},
+ {'code': 'NPR', 'name': 'Nepalese Rupee', 'symbol': 'Rs'},
+ {'code': 'BTN', 'name': 'Bhutanese Ngultrum', 'symbol': 'Nu'},
+ {'code': 'MMK', 'name': 'Myanmar Kyat', 'symbol': 'K'},
+ {'code': 'THB', 'name': 'Thai Baht', 'symbol': '฿'},
+ {'code': 'VND', 'name': 'Vietnamese Dong', 'symbol': '₫'},
+ {'code': 'LAK', 'name': 'Lao Kip', 'symbol': '₭'},
+ {'code': 'KHR', 'name': 'Cambodian Riel', 'symbol': '៛'},
+ {'code': 'MYR', 'name': 'Malaysian Ringgit', 'symbol': 'RM'},
+ {'code': 'SGD', 'name': 'Singapore Dollar', 'symbol': 'S$'},
+ {'code': 'IDR', 'name': 'Indonesian Rupiah', 'symbol': 'Rp'},
+ {'code': 'PHP', 'name': 'Philippine Peso', 'symbol': '₱'},
+ {'code': 'TWD', 'name': 'Taiwan Dollar', 'symbol': 'NT$'},
+ {'code': 'HKD', 'name': 'Hong Kong Dollar', 'symbol': 'HK$'},
+ {'code': 'MOP', 'name': 'Macanese Pataca', 'symbol': 'MOP'},
+ {'code': 'KPW', 'name': 'North Korean Won', 'symbol': '₩'},
+ {'code': 'MNT', 'name': 'Mongolian Tugrik', 'symbol': '₮'},
+ {'code': 'KZT', 'name': 'Kazakhstani Tenge', 'symbol': '₸'},
+ {'code': 'UZS', 'name': 'Uzbekistani Som', 'symbol': 'soʻm'},
+ {'code': 'TJS', 'name': 'Tajikistani Somoni', 'symbol': 'SM'},
+ {'code': 'KGS', 'name': 'Kyrgyzstani Som', 'symbol': 'с'},
+ {'code': 'TMT', 'name': 'Turkmenistani Manat', 'symbol': 'T'},
+ {'code': 'AFN', 'name': 'Afghan Afghani', 'symbol': '؋'},
+ {'code': 'AMD', 'name': 'Armenian Dram', 'symbol': '֏'},
+ {'code': 'AZN', 'name': 'Azerbaijani Manat', 'symbol': '₼'},
+ {'code': 'GEL', 'name': 'Georgian Lari', 'symbol': '₾'},
+ {'code': 'MDL', 'name': 'Moldovan Leu', 'symbol': 'L'},
+ {'code': 'UAH', 'name': 'Ukrainian Hryvnia', 'symbol': '₴'},
+ {'code': 'BYN', 'name': 'Belarusian Ruble', 'symbol': 'Br'},
+ {'code': 'RSD', 'name': 'Serbian Dinar', 'symbol': 'дин'},
+ {'code': 'MKD', 'name': 'Macedonian Denar', 'symbol': 'ден'},
+ {'code': 'ALL', 'name': 'Albanian Lek', 'symbol': 'L'},
+ {'code': 'BAM', 'name': 'Bosnia-Herzegovina Mark', 'symbol': 'KM'},
+ {'code': 'ISK', 'name': 'Icelandic Króna', 'symbol': 'kr'},
+ {'code': 'FJD', 'name': 'Fijian Dollar', 'symbol': 'FJ$'},
+ {'code': 'PGK', 'name': 'Papua New Guinea Kina', 'symbol': 'K'},
+ {'code': 'SBD', 'name': 'Solomon Islands Dollar', 'symbol': 'SI$'},
+ {'code': 'TOP', 'name': 'Tongan Paʻanga', 'symbol': 'T$'},
+ {'code': 'VUV', 'name': 'Vanuatu Vatu', 'symbol': 'VT'},
+ {'code': 'WST', 'name': 'Samoan Tala', 'symbol': 'WS$'},
+ {'code': 'XPF', 'name': 'CFP Franc', 'symbol': '₣'},
+ {'code': 'NZD', 'name': 'New Zealand Dollar', 'symbol': 'NZ$'}
+ ]
+
+ return jsonify(currencies)
+
+ except Exception as e:
+ logger.error(f"Error getting currencies: {e}")
+ return jsonify([{'code': 'USD', 'name': 'US Dollar', 'symbol': '$'}]), 500
+
+
+@warranties_bp.route('/debug/warranty/<int:warranty_id>', methods=['GET'])
+@token_required
+def get_warranty_debug(warranty_id):
+ """Get detailed information about a specific warranty (for debugging/status page)"""
+ conn = None
+ try:
+ user_id = request.user['id']
+ is_admin = request.user.get('is_admin', False)
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if warranty exists and user has access to it
+ if is_admin:
+ cur.execute('''
+ SELECT w.id, w.product_name, w.purchase_date, w.expiration_date, w.invoice_path, w.manual_path, w.other_document_path,
+ w.product_url, w.notes, w.purchase_price, w.user_id, w.created_at, w.updated_at, w.is_lifetime,
+ w.vendor, w.warranty_type, w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days,
+ w.product_photo_path, w.currency, w.paperless_invoice_id, w.paperless_manual_id, w.paperless_photo_id, w.paperless_other_id,
+ u.username, u.email, u.first_name, u.last_name
+ FROM warranties w
+ JOIN users u ON w.user_id = u.id
+ WHERE w.id = %s
+ ''', (warranty_id,))
+ else:
+ cur.execute('''
+ SELECT w.id, w.product_name, w.purchase_date, w.expiration_date, w.invoice_path, w.manual_path, w.other_document_path,
+ w.product_url, w.notes, w.purchase_price, w.user_id, w.created_at, w.updated_at, w.is_lifetime,
+ w.vendor, w.warranty_type, w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days,
+ w.product_photo_path, w.currency, w.paperless_invoice_id, w.paperless_manual_id, w.paperless_photo_id, w.paperless_other_id,
+ u.username, u.email, u.first_name, u.last_name
+ FROM warranties w
+ JOIN users u ON w.user_id = u.id
+ WHERE w.id = %s AND w.user_id = %s
+ ''', (warranty_id, user_id))
+
+ warranty = cur.fetchone()
+
+ if not warranty:
+ return jsonify({"error": "Warranty not found or you don't have permission to access it"}), 404
+
+ # Convert to dictionary
+ columns = [desc[0] for desc in cur.description]
+ warranty_dict = dict(zip(columns, warranty))
+
+ # Convert date objects to ISO format strings for JSON serialization
+ for key, value in warranty_dict.items():
+ if isinstance(value, (datetime, date)):
+ warranty_dict[key] = value.isoformat()
+ # Convert Decimal objects to float for JSON serialization
+ elif isinstance(value, Decimal):
+ warranty_dict[key] = float(value)
+
+ # Get serial numbers for this warranty
+ cur.execute('SELECT serial_number FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))
+ serial_numbers = [row[0] for row in cur.fetchall()]
+ warranty_dict['serial_numbers'] = serial_numbers
+
+ # Get tags for this warranty
+ cur.execute('''
+ SELECT t.id, t.name, t.color
+ FROM tags t
+ JOIN warranty_tags wt ON t.id = wt.tag_id
+ WHERE wt.warranty_id = %s
+ ORDER BY t.name
+ ''', (warranty_id,))
+ tags = [{'id': t[0], 'name': t[1], 'color': t[2]} for t in cur.fetchall()]
+ warranty_dict['tags'] = tags
+
+ # Add user display name for better UI (if admin is viewing)
+ if is_admin:
+ first_name = warranty_dict.get('first_name', '').strip() if warranty_dict.get('first_name') else ''
+ last_name = warranty_dict.get('last_name', '').strip() if warranty_dict.get('last_name') else ''
+ username = warranty_dict.get('username', '').strip() if warranty_dict.get('username') else ''
+
+ if first_name and last_name:
+ warranty_dict['user_display_name'] = f"{first_name} {last_name}"
+ elif first_name:
+ warranty_dict['user_display_name'] = first_name
+ elif username:
+ warranty_dict['user_display_name'] = username
+ else:
+ warranty_dict['user_display_name'] = 'Unknown User'
+
+ return jsonify(warranty_dict)
+
+ except Exception as e:
+ logger.error(f"Error retrieving warranty {warranty_id}: {e}")
+ return jsonify({"error": "Failed to retrieve warranty"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+@warranties_bp.route('/timezones', methods=['GET'])
+@token_required
+def get_timezones():
+ """Get list of available timezones grouped by region"""
+ try:
+ # Get all timezones and group them by region
+ all_timezones = pytz.all_timezones
+ grouped_timezones = {}
+
+ for tz in sorted(all_timezones):
+ # Skip deprecated/non-standard timezones
+ if '/' not in tz or tz.startswith(('Etc/', 'SystemV/', 'US/', 'posix/', 'right/')):
+ continue
+
+ region = tz.split('/')[0]
+ if region not in grouped_timezones:
+ grouped_timezones[region] = []
+
+ # Create display name (replace underscores with spaces)
+ display_name = tz.split('/', 1)[1].replace('_', ' ')
+ grouped_timezones[region].append({
+ 'value': tz,
+ 'label': display_name,
+ 'full_name': tz
+ })
+
+ # Convert to frontend expected format: array of objects with region and timezones
+ timezone_groups_array = []
+ for region, timezones in grouped_timezones.items():
+ timezone_groups_array.append({
+ 'region': region,
+ 'timezones': timezones
+ })
+
+ return jsonify(timezone_groups_array), 200
+
+ except Exception as e:
+ logger.error(f"Error getting timezones: {e}")
+ # Return a basic fallback list in correct format
+ fallback_timezones = [
+ {
+ 'region': 'UTC',
+ 'timezones': [{'value': 'UTC', 'label': 'UTC', 'full_name': 'UTC'}]
+ },
+ {
+ 'region': 'America',
+ 'timezones': [
+ {'value': 'America/New_York', 'label': 'New York', 'full_name': 'America/New_York'},
+ {'value': 'America/Chicago', 'label': 'Chicago', 'full_name': 'America/Chicago'},
+ {'value': 'America/Denver', 'label': 'Denver', 'full_name': 'America/Denver'},
+ {'value': 'America/Los_Angeles', 'label': 'Los Angeles', 'full_name': 'America/Los_Angeles'},
+ {'value': 'America/Halifax', 'label': 'Halifax', 'full_name': 'America/Halifax'}
+ ]
+ },
+ {
+ 'region': 'Europe',
+ 'timezones': [
+ {'value': 'Europe/London', 'label': 'London', 'full_name': 'Europe/London'},
+ {'value': 'Europe/Paris', 'label': 'Paris', 'full_name': 'Europe/Paris'},
+ {'value': 'Europe/Berlin', 'label': 'Berlin', 'full_name': 'Europe/Berlin'}
+ ]
+ }
+ ]
+ return jsonify(fallback_timezones), 200
+
+@warranties_bp.route('/locales', methods=['GET'])
+def get_locales():
+ """Get list of supported locales/languages"""
+ try:
+ # Import the supported languages from localization
+ try:
+ from .localization import SUPPORTED_LANGUAGES
+ except ImportError:
+ from localization import SUPPORTED_LANGUAGES
+
+ # Language code to name mapping
+ language_names = {
+ 'en': 'English',
+ 'fr': 'Français',
+ 'es': 'Español',
+ 'de': 'Deutsch',
+ 'it': 'Italiano',
+ 'cs': 'Čeština',
+ 'nl': 'Nederlands',
+ 'hi': 'हिन्दी',
+ 'fa': 'فارسی',
+ 'ar': 'العربية',
+ 'ru': 'Русский',
+ 'uk': 'Українська',
+ 'zh_CN': '简体中文',
+ 'zh_HK': '繁體中文',
+ 'ja': '日本語',
+ 'pt': 'Português',
+ 'ko': '한국어'
+ }
+
+ locales = []
+ for lang_code in SUPPORTED_LANGUAGES:
+ locales.append({
+ 'code': lang_code,
+ 'name': language_names.get(lang_code, lang_code),
+ 'native_name': language_names.get(lang_code, lang_code)
+ })
+
+ return jsonify(locales), 200
+
+ except ImportError:
+ # Fallback if localization module is not available
+ fallback_locales = [
+ {'code': 'en', 'name': 'English', 'native_name': 'English'},
+ {'code': 'fr', 'name': 'French', 'native_name': 'Français'},
+ {'code': 'es', 'name': 'Spanish', 'native_name': 'Español'},
+ {'code': 'de', 'name': 'German', 'native_name': 'Deutsch'}
+ ]
+ return jsonify(fallback_locales), 200
+ except Exception as e:
+ logger.error(f"Error getting locales: {e}")
+ return jsonify([{'code': 'en', 'name': 'English', 'native_name': 'English'}]), 500
+
+
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
index 998c1c2..9a2908f 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -19,16 +19,35 @@ services:
- SMTP_PORT=${SMTP_PORT:-1025}
- SMTP_USERNAME=${SMTP_USERNAME:[email protected]}
- SMTP_PASSWORD=${SMTP_PASSWORD:-}
+ # if SMTP_FROM_ADDRESS isn't defined, then SMTP_USERNAME will be used - but that may not always work
+ - SMTP_FROM_ADDRESS=${SMTP_FROM_ADDRESS:-}
+ - SECRET_KEY=${SECRET_KEY:-your_very_secret_flask_key_change_me} # For Flask session and JWT
+ # OIDC SSO Configuration (User needs to set these based on their OIDC provider)
+ - OIDC_PROVIDER_NAME=${OIDC_PROVIDER_NAME:-oidc}
+ - OIDC_CLIENT_ID=${OIDC_CLIENT_ID:-} # e.g., your_oidc_client_id
+ - OIDC_CLIENT_SECRET=${OIDC_CLIENT_SECRET:-} # e.g., your_oidc_client_secret
+ - OIDC_ISSUER_URL=${OIDC_ISSUER_URL:-} # e.g., https://your-oidc-provider.com/auth/realms/your-realm
+ - OIDC_SCOPE=${OIDC_SCOPE:-openid email profile}
+ # URL settings (Important for redirects and email links)
+ - FRONTEND_URL=${FRONTEND_URL:-http://localhost:8005} # Public URL of the frontend (matching the port mapping)
+ - APP_BASE_URL=${APP_BASE_URL:-http://localhost:8005} # Public base URL of the application for links
+ # Apprise Notification Configuration
+ - APPRISE_ENABLED=${APPRISE_ENABLED:-false} # Enable/disable Apprise notifications
+ - APPRISE_URLS=${APPRISE_URLS:-} # Comma-separated list of notification URLs (e.g., "mailto://user:[email protected],discord://webhook_id/webhook_token")
+ - APPRISE_EXPIRATION_DAYS=${APPRISE_EXPIRATION_DAYS:-7,30} # Days before expiration to send notifications (comma-separated)
+ - APPRISE_NOTIFICATION_TIME=${APPRISE_NOTIFICATION_TIME:-09:00} # Time of day to send notifications (HH:MM format)
+ - APPRISE_TITLE_PREFIX=${APPRISE_TITLE_PREFIX:-[Warracker]} # Prefix for notification titles
- PYTHONUNBUFFERED=1
+ # Memory optimization settings
+ - WARRACKER_MEMORY_MODE=${WARRACKER_MEMORY_MODE:-optimized} # Options: optimized (default), ultra-light, performance
+ - MAX_UPLOAD_MB=${MAX_UPLOAD_MB:-16} # Reduced from 32MB default for memory efficiency
+ - NGINX_MAX_BODY_SIZE_VALUE=${NGINX_MAX_BODY_SIZE_VALUE:-16M} # Match upload limit
depends_on:
warrackerdb:
condition: service_healthy
restart: unless-stopped
command: >
bash -c "
- cd /app && ls -la /app/migrations &&
- python /app/migrations/apply_migrations.py &&
- python /app/fix_permissions.py &&
exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf
"
diff --git a/env.example b/env.example
new file mode 100644
index 0000000..8a0cb8b
--- /dev/null
+++ b/env.example
@@ -0,0 +1,93 @@
+# Warracker Environment Configuration Example
+# Copy this file to .env and modify the values as needed
+
+# Database Configuration
+DB_PASSWORD=your_secure_database_password
+DB_ADMIN_PASSWORD=your_secure_admin_password
+
+# Application Security
+SECRET_KEY=your_very_secure_flask_secret_key_change_this_in_production
+
+# Email Configuration (for password resets and notifications)
+SMTP_HOST=smtp.gmail.com
+SMTP_PORT=587
+SMTP_USERNAME=your-email-username
+SMTP_PASSWORD=your-app-password
+SMTP_USE_TLS=true
+
+# Application URLs
+FRONTEND_URL=http://localhost:8005
+APP_BASE_URL=http://localhost:8005
+
+# OIDC SSO Configuration (Optional)
+OIDC_PROVIDER_NAME=oidc
+OIDC_CLIENT_ID=your_oidc_client_id
+OIDC_CLIENT_SECRET=your_oidc_client_secret
+OIDC_ISSUER_URL=https://your-oidc-provider.com/auth/realms/your-realm
+OIDC_SCOPE=openid email profile
+
+# Memory and Performance Settings
+WARRACKER_MEMORY_MODE=optimized
+MAX_UPLOAD_MB=16
+NGINX_MAX_BODY_SIZE_VALUE=16M
+
+# =====================
+# APPRISE NOTIFICATIONS
+# =====================
+
+# Enable/disable Apprise notifications
+APPRISE_ENABLED=false
+
+# Notification URLs (comma-separated)
+# Examples:
+# Email: mailto://user:[email protected]
+# Discord: discord://webhook_id/webhook_token
+# Slack: slack://TokenA/TokenB/TokenC/Channel
+# Telegram: telegram://BotToken/ChatID
+# Microsoft Teams: msteams://TokenA/TokenB/TokenC/
+# Webhooks: json://webhook.site/your-unique-id
+APPRISE_URLS=
+
+# Days before expiration to send notifications (comma-separated)
+APPRISE_EXPIRATION_DAYS=7,30
+
+# Time of day to send notifications (HH:MM format, 24-hour)
+APPRISE_NOTIFICATION_TIME=09:00
+
+# Prefix for notification titles
+APPRISE_TITLE_PREFIX=[Warracker]
+
+# =====================
+# APPRISE URL EXAMPLES
+# =====================
+
+# Gmail (using app password)
+# APPRISE_URLS=mailto://username:[email protected]
+
+# Discord Webhook
+# APPRISE_URLS=discord://webhook_id/webhook_token
+
+# Slack
+# APPRISE_URLS=slack://TokenA/TokenB/TokenC/Channel
+
+# Telegram Bot
+# APPRISE_URLS=telegram://BotToken/ChatID
+
+# Microsoft Teams
+# APPRISE_URLS=msteams://TokenA/TokenB/TokenC/
+
+# Multiple services (comma-separated)
+# APPRISE_URLS=mailto://user:[email protected],discord://webhook_id/webhook_token,telegram://BotToken/ChatID
+
+# Pushover
+# APPRISE_URLS=pover://user@token
+
+# Ntfy
+# APPRISE_URLS=ntfy://topic
+
+# Generic Webhook
+# APPRISE_URLS=json://webhook.site/your-unique-id
+
+# For more services and URL formats, visit:
+# https://github.com/caronc/apprise/wiki
diff --git a/frontend/about.html b/frontend/about.html
index ad9b8a4..8515a10 100644
--- a/frontend/about.html
+++ b/frontend/about.html
@@ -1,10 +1,10 @@
<!DOCTYPE html>
-<html lang="en">
+<html>
<head>
<!-- Basic Meta Tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>About - Warracker</title>
+ <title data-i18n="about.title">About - Warracker</title>
<!-- Favicons -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
@@ -14,33 +14,247 @@
<link rel="manifest" href="manifest.json">
<!-- Stylesheets -->
- <link rel="stylesheet" href="style.css"> <!-- Main stylesheet -->
- <link rel="stylesheet" href="styles.css"> <!-- Additional styles -->
+ <link rel="stylesheet" href="style.css?v=20250119001"> <!-- Main stylesheet -->
+ <link rel="stylesheet" href="styles.css?v=20250119001"> <!-- Additional styles -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> <!-- Font Awesome -->
- <link rel="stylesheet" href="header-fix.css"> <!-- Header specific styles -->
+ <link rel="stylesheet" href="header-fix.css?v=20250119001"> <!-- Header specific styles -->
<!-- Mobile Header specific styles -->
- <link rel="stylesheet" href="mobile-header.css">
+ <link rel="stylesheet" href="mobile-header.css?v=20250119001">
<!-- Scripts loaded in head -->
- <script src="theme-loader.js"></script> <!-- Apply theme early -->
- <script src="include-auth-new.js"></script> <!-- Handles auth state display -->
- <script src="fix-auth-buttons-loader.js"></script> <!-- Fixes auth button display timing -->
- <script src="auth.js"></script> <!-- Load auth.js early for authentication check -->
+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
+ <script src="include-auth-new.js?v=20250119001"></script> <!-- Handles auth state display -->
+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script> <!-- Fixes auth button display timing -->
+ <!-- i18next Local Scripts -->
+ <script src="js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <!-- i18n initialization script -->
+ <script src="js/i18n.js?v=20250119001"></script>
- <!-- Authentication Check -->
- <script>
- document.addEventListener('DOMContentLoaded', () => {
- // Check if user is authenticated
- const authToken = localStorage.getItem('auth_token');
- const userInfo = localStorage.getItem('user_info');
-
- if (!authToken || !userInfo) {
- // User is not authenticated, redirect to login page
- window.location.href = 'login.html';
- return;
+ <style>
+ .about-hero {
+ background: linear-gradient(135deg, var(--primary-color), var(--secondary-color, #4dabf7));
+ color: white;
+ padding: 60px 20px;
+ text-align: center;
+ border-radius: 12px;
+ margin: 20px 0;
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
+ }
+
+ .about-hero h1 {
+ font-size: 3rem;
+ margin-bottom: 10px;
+ font-weight: 700;
+ }
+
+ .about-hero .version {
+ font-size: 1.2rem;
+ opacity: 0.9;
+ margin-bottom: 20px;
+ }
+
+ .about-hero .description {
+ font-size: 1.1rem;
+ max-width: 600px;
+ margin: 0 auto;
+ opacity: 0.95;
+ line-height: 1.6;
+ }
+
+ .about-cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
+ gap: 20px;
+ margin: 30px 0;
+ }
+
+ .about-card {
+ background: var(--card-bg);
+ border-radius: 12px;
+ padding: 30px;
+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
+ transition: transform 0.3s ease, box-shadow 0.3s ease;
+ border: 1px solid var(--border-color);
+ }
+
+ .about-card:hover {
+ transform: translateY(-5px);
+ box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
+ }
+
+ .about-card h3 {
+ color: var(--primary-color);
+ font-size: 1.4rem;
+ margin-bottom: 20px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ }
+
+ .about-card h3 i {
+ font-size: 1.2rem;
+ }
+
+ .about-card p {
+ color: var(--text-color);
+ line-height: 1.6;
+ margin-bottom: 15px;
+ }
+
+ .social-links {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 15px;
+ margin-top: 20px;
+ }
+
+ .social-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 12px 20px;
+ background: var(--card-bg);
+ color: var(--text-color);
+ text-decoration: none;
+ border-radius: 8px;
+ border: 2px solid var(--border-color);
+ transition: all 0.3s ease;
+ font-weight: 500;
+ }
+
+ .social-link:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
+ }
+
+ .social-link.github {
+ border-color: #333;
+ color: #333;
+ }
+
+ .social-link.github:hover {
+ background: #333;
+ color: white;
+ }
+
+ .social-link.discord {
+ border-color: #5865f2;
+ color: #5865f2;
+ }
+
+ .social-link.discord:hover {
+ background: #5865f2;
+ color: white;
+ }
+
+ .social-link.license {
+ border-color: #28a745;
+ color: #28a745;
+ }
+
+ .social-link.license:hover {
+ background: #28a745;
+ color: white;
+ }
+
+ .social-link.issues {
+ border-color: #dc3545;
+ color: #dc3545;
+ }
+
+ .social-link.issues:hover {
+ background: #dc3545;
+ color: white;
+ }
+
+ .social-link.releases {
+ border-color: #17a2b8;
+ color: #17a2b8;
+ }
+
+ .social-link.releases:hover {
+ background: #17a2b8;
+ color: white;
+ }
+
+ .social-link i {
+ font-size: 1.1rem;
+ }
+
+ .update-status {
+ background: var(--card-bg);
+ border-radius: 8px;
+ padding: 20px;
+ margin: 20px 0;
+ border-left: 4px solid var(--primary-color);
+ }
+
+ .update-status h4 {
+ color: var(--primary-color);
+ margin-bottom: 10px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+
+ .coffee-section {
+ text-align: center;
+ background: var(--card-bg);
+ border-radius: 12px;
+ padding: 40px;
+ margin: 30px 0;
+ border: 2px dashed var(--border-color);
+ }
+
+ .coffee-section h3 {
+ color: var(--primary-color);
+ margin-bottom: 15px;
+ font-size: 1.5rem;
+ }
+
+ .coffee-section p {
+ color: var(--text-muted);
+ margin-bottom: 25px;
+ font-size: 1.1rem;
+ }
+
+ /* Dark mode adjustments */
+ [data-theme="dark"] .social-link.github {
+ border-color: #f0f6fc;
+ color: #f0f6fc;
+ }
+
+ [data-theme="dark"] .social-link.github:hover {
+ background: #f0f6fc;
+ color: #0d1117;
+ }
+
+ @media (max-width: 768px) {
+ .about-hero h1 {
+ font-size: 2.2rem;
}
- });
- </script>
+
+ .about-hero .version {
+ font-size: 1rem;
+ }
+
+ .about-cards {
+ grid-template-columns: 1fr;
+ }
+
+ .social-links {
+ justify-content: center;
+ }
+
+ .social-link {
+ flex: 1;
+ justify-content: center;
+ min-width: 140px;
+ }
+ }
+ </style>
</head>
<body>
@@ -53,12 +267,11 @@
</div>
<div class="nav-links">
<a href="index.html" class="nav-link">
- <i class="fas fa-home"></i> Home
+ <i class="fas fa-home"></i> <span data-i18n="nav.home">Home</span>
</a>
<a href="status.html" class="nav-link">
- <i class="fas fa-chart-pie"></i> Status
+ <i class="fas fa-chart-pie"></i> <span data-i18n="nav.status">Status</span>
</a>
- <!-- Consider adding an 'active' class to an 'About' link if created here -->
</div>
<!-- Group for right-aligned elements -->
<div class="header-right-group">
@@ -71,7 +284,7 @@
</a>
</div>
<div id="userMenu" class="user-menu" style="display: none;">
- <button id="userBtn" class="user-btn">
+ <button id="userMenuBtn" class="user-btn">
<i class="fas fa-user-circle"></i>
<span id="userDisplayName">User</span>
</button>
@@ -82,15 +295,15 @@
</div>
<div class="user-menu-item">
<a href="settings-new.html" style="color: inherit; text-decoration: none; display: block;">
- <i class="fas fa-cog"></i> Settings
+ <i class="fas fa-cog"></i> <span data-i18n="nav.settings">Settings</span>
</a>
</div>
<div class="user-menu-item">
<i class="fas fa-info-circle"></i>
- <a href="about.html" style="text-decoration: none; color: inherit;">About</a>
+ <a href="about.html" style="text-decoration: none; color: inherit;" data-i18n="nav.about">About</a>
</div>
<div class="user-menu-item" id="logoutMenuItem">
- <i class="fas fa-sign-out-alt"></i> Logout
+ <i class="fas fa-sign-out-alt"></i> <span data-i18n="auth.logout">Logout</span>
</div>
</div>
</div>
@@ -102,78 +315,315 @@
<div class="container" style="padding: 0;">
<div class="main-content" style="display: block;">
- <!-- Existing About Content, now wrapped -->
- <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.8</p>
-
- <div id="versionTracker" style="margin-bottom: 20px;">
- <p><strong>Update Status:</strong> <span id="updateStatus">Checking for updates...</span></p>
- <a id="updateLink" href="#" target="_blank" rel="noopener noreferrer" style="display: none; color: var(--link-color);">
- <i class="fa-solid fa-arrow-up-right-from-square"></i> Release Notes
- </a>
- </div>
-
- <p>
- <strong>GitHub Repository:</strong>
- <a href="https://github.com/sassanix/Warracker" target="_blank" rel="noopener noreferrer" style="color: var(--link-color);">
- https://github.com/sassanix/Warracker
- </a>
- </p>
-
- <p>
- <strong>Release Notes:</strong>
- <a href="https://github.com/sassanix/Warracker/releases" target="_blank" rel="noopener noreferrer" style="color: var(--link-color);">
- View Releases
- </a>
+ <!-- Hero Section -->
+ <div class="about-hero">
+ <h1><i class="fas fa-shield-alt"></i> Warracker</h1>
+ <div class="version" id="versionDisplay" data-i18n="about.version">Version v0.10.1.9</div>
+ <p class="description" data-i18n="about.description">
+ A comprehensive warranty management system designed to help you track, organize, and manage all your product warranties in one secure, user-friendly platform.
</p>
+ </div>
- <p>
- <strong>Author:</strong>
- <a href="https://github.com/sassanix" target="_blank" rel="noopener noreferrer" style="color: var(--link-color);">
- Sassanix
- </a>
- </p>
+ <!-- Update Status Card -->
+ <div class="update-status">
+ <h4><i class="fas fa-sync-alt"></i> <span data-i18n="about.update_status">Update Status</span></h4>
+ <p id="updateStatus" data-i18n="about.checking_updates">Checking for updates...</p>
+ <a id="updateLink" href="#" target="_blank" rel="noopener noreferrer" style="display: none; color: var(--primary-color); text-decoration: none;">
+ <i class="fas fa-external-link-alt"></i> <span data-i18n="about.view_release_notes">View Release Notes</span>
+ </a>
+ </div>
- <p>
- <strong>License:</strong>
- <a href="https://github.com/sassanix/Warracker/blob/main/LICENSE" target="_blank" rel="noopener noreferrer" style="color: var(--link-color);">
- AGPL-3.0
- </a>
- </p>
+ <!-- Information Cards -->
+ <div class="about-cards">
+ <!-- Project Information -->
+ <div class="about-card">
+ <h3><i class="fas fa-info-circle"></i> <span data-i18n="about.project_info">Project Information</span></h3>
+ <p data-i18n="about.project_description">Warracker is an open-source warranty management system built with modern web technologies. It provides a secure and intuitive way to manage product warranties, track expiration dates, and organize important documents.</p>
+
+ <div class="social-links">
+ <a href="https://github.com/sassanix/Warracker" target="_blank" rel="noopener noreferrer" class="social-link github">
+ <i class="fab fa-github"></i> <span data-i18n="about.github_repository">GitHub Repository</span>
+ </a>
+ <a href="https://github.com/sassanix/Warracker/releases" target="_blank" rel="noopener noreferrer" class="social-link releases">
+ <i class="fas fa-tags"></i> <span data-i18n="about.releases">Releases</span>
+ </a>
+ </div>
+ </div>
- <p>
- <strong>Issues & Feature Requests:</strong>
- <a href="https://github.com/sassanix/Warracker/issues" target="_blank" rel="noopener noreferrer" style="color: var(--link-color);">
- Report Bugs / Request Features
- </a>
- </p>
+ <!-- Community & Support -->
+ <div class="about-card">
+ <h3><i class="fas fa-users"></i> <span data-i18n="about.community_support">Community & Support</span></h3>
+ <p data-i18n="about.community_description">Join our community for support, discussions, and updates. Report bugs, request features, or get help from other users and contributors.</p>
+
+ <div class="social-links">
+ <a href="https://discord.gg/PGxVS3U2Nw" target="_blank" rel="noopener noreferrer" class="social-link discord">
+ <i class="fab fa-discord"></i> <span data-i18n="about.discord_community">Discord Community</span>
+ </a>
+ <a href="https://github.com/sassanix/Warracker/issues" target="_blank" rel="noopener noreferrer" class="social-link issues">
+ <i class="fas fa-bug"></i> <span data-i18n="about.report_issues">Report Issues</span>
+ </a>
+ </div>
+ </div>
- <!-- Buy Me A Coffee Button -->
- <div style="text-align: center; margin-top: 25px;">
- <script type="text/javascript" src="https://cdnjs.buymeacoffee.com/1.0.0/button.prod.min.js" data-name="bmc-button" data-slug="sassanix" data-color="#FFDD00" data-emoji="" data-font="Poppins" data-text="Buy me a coffee" data-outline-color="#000000" data-font-color="#000000" data-coffee-color="#ffffff" ></script>
+ <!-- Developer Information -->
+ <div class="about-card">
+ <h3><i class="fas fa-code"></i> <span data-i18n="about.developer_info">Developer Information</span></h3>
+ <p data-i18n="about.developer_description">Warracker is developed and maintained by Sassanix. The project is open-source and welcomes contributions from the community.</p>
+
+ <div class="social-links">
+ <a href="https://github.com/sassanix" target="_blank" rel="noopener noreferrer" class="social-link github">
+ <i class="fab fa-github"></i> <span data-i18n="about.sassanix">Sassanix</span>
+ </a>
+ <a href="https://github.com/sassanix/Warracker/blob/main/LICENSE" target="_blank" rel="noopener noreferrer" class="social-link license">
+ <i class="fas fa-balance-scale"></i> <span data-i18n="about.agpl_license">AGPL-3.0 License</span>
+ </a>
+ </div>
</div>
</div>
+ <!-- Support the Project -->
+ <div class="coffee-section">
+ <h3><i class="fas fa-coffee"></i> <span data-i18n="about.support_project">Support the Project</span></h3>
+ <p data-i18n="about.support_description">If you find Warracker useful, consider supporting its development!</p>
+ <script type="text/javascript" src="https://cdnjs.buymeacoffee.com/1.0.0/button.prod.min.js" data-name="bmc-button" data-slug="sassanix" data-color="#FFDD00" data-emoji="" data-font="Poppins" data-text="Buy me a coffee" data-outline-color="#000000" data-font-color="#000000" data-coffee-color="#ffffff" ></script>
+ </div>
+
</div>
</div>
<!-- Scripts loaded at the end of body -->
- <script src="auth.js"></script> <!-- Added for user menu and other auth interactions -->
- <script src="script.js"></script> <!-- Include main site script, might contain helpers -->
- <script src="version-checker.js"></script> <!-- Version checker script -->
+ <script src="auth.js?v=20250119001"></script>
+
+ <!-- Version Checker -->
+ <script src="version-checker.js?v=20250119001" defer></script> <!-- Version checker script -->
+
+ <!-- Footer Width Fix -->
+ <script src="footer-fix.js?v=20250119001"></script>
+
+ <!-- Footer Content Manager -->
+ <script src="footer-content.js?v=20250119001"></script>
+
+ <!-- Powered by Warracker Footer -->
+ <footer class="warracker-footer" id="warrackerFooter">
+ <!-- Content will be dynamically generated by footer-content.js -->
+ </footer>
<!-- Explicitly call setupUIEventListeners for this page -->
<script>
document.addEventListener('DOMContentLoaded', () => {
+ console.log('About page: DOMContentLoaded triggered');
+
+ // Update version display dynamically
+ const versionDisplay = document.getElementById('versionDisplay');
+ if (versionDisplay && window.i18next) {
+ const currentVersion = '0.10.1.4'; // This should match version-checker.js
+ versionDisplay.textContent = window.i18next.t('about.version') + ' v' + currentVersion;
+ }
+
+ // Add safe loading functions for about page
+ window.showLoading = function() {
+ const loadingContainer = document.getElementById('loadingContainer');
+ if (loadingContainer && loadingContainer.classList) {
+ loadingContainer.classList.add('active');
+ console.log('About page: Loading spinner shown');
+ } else {
+ console.log('About page: Loading container not found or unavailable');
+ }
+ };
+
+ window.hideLoading = function() {
+ const loadingContainer = document.getElementById('loadingContainer');
+ if (loadingContainer && loadingContainer.classList) {
+ loadingContainer.classList.remove('active');
+ console.log('About page: Loading spinner hidden');
+ } else {
+ console.log('About page: Loading container not found or unavailable');
+ }
+ };
+
// Keep theme initialization here if needed for specific timing
if (typeof initializeTheme === 'function') {
console.log('About page: Calling initializeTheme');
initializeTheme(); // Call theme initialization if it exists
}
+
+ // Add specific debugging for user menu elements
+ setTimeout(() => {
+ const userMenuBtn = document.getElementById('userMenuBtn');
+ const userMenuDropdown = document.getElementById('userMenuDropdown');
+
+ console.log('About page: User menu debug info:', {
+ userMenuBtn: !!userMenuBtn,
+ userMenuDropdown: !!userMenuDropdown,
+ userMenuBtnId: userMenuBtn ? userMenuBtn.id : 'not found',
+ dropdownId: userMenuDropdown ? userMenuDropdown.id : 'not found',
+ authModuleAvailable: !!window.auth,
+ isAuthenticated: window.auth ? window.auth.isAuthenticated() : 'auth not available'
+ });
+
+ if (userMenuBtn) {
+ console.log('About page: userMenuBtn element:', userMenuBtn);
+ console.log('About page: userMenuBtn element found, proceeding with backup handler setup');
+ }
+
+ // Add a backup user menu handler specifically for about page
+ if (userMenuBtn && userMenuDropdown) {
+ console.log('About page: Setting up backup user menu handler');
+ console.log('About page: Current dropdown classes:', userMenuDropdown.className);
+ console.log('About page: Current dropdown active state:', userMenuDropdown.classList.contains('active'));
+
+ // Test CSS rules by temporarily adding/removing active class
+ console.log('About page: Testing CSS rules...');
+ userMenuDropdown.classList.add('active');
+ const testDisplayActive = window.getComputedStyle(userMenuDropdown).display;
+ userMenuDropdown.classList.remove('active');
+ const testDisplayInactive = window.getComputedStyle(userMenuDropdown).display;
+ console.log('About page: CSS test results:', {
+ displayWhenActive: testDisplayActive,
+ displayWhenInactive: testDisplayInactive
+ });
+
+ // Remove any existing click listeners and add our own
+ const newUserMenuBtn = userMenuBtn.cloneNode(true);
+ userMenuBtn.parentNode.replaceChild(newUserMenuBtn, userMenuBtn);
+
+ newUserMenuBtn.addEventListener('click', (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('About page: Backup user menu clicked');
+ console.log('About page: Dropdown before toggle:', {
+ classes: userMenuDropdown.className,
+ hasActive: userMenuDropdown.classList.contains('active'),
+ style: userMenuDropdown.style.display
+ });
+
+ const isCurrentlyActive = userMenuDropdown.classList.contains('active');
+
+ if (isCurrentlyActive) {
+ userMenuDropdown.classList.remove('active');
+ console.log('About page: User menu closed');
+ } else {
+ userMenuDropdown.classList.add('active');
+ console.log('About page: User menu opened');
+ }
+
+ // Double-check the state after toggle
+ console.log('About page: Dropdown after toggle:', {
+ classes: userMenuDropdown.className,
+ hasActive: userMenuDropdown.classList.contains('active'),
+ computedStyle: window.getComputedStyle(userMenuDropdown).display
+ });
+ });
+
+ // Add global click listener to close menu when clicking outside
+ const outsideClickHandler = (e) => {
+ if (userMenuDropdown.classList.contains('active') &&
+ !userMenuDropdown.contains(e.target) &&
+ !newUserMenuBtn.contains(e.target)) {
+ userMenuDropdown.classList.remove('active');
+ console.log('About page: User menu closed by outside click');
+ }
+ };
+
+ // Use setTimeout to ensure this listener is added after any others
+ setTimeout(() => {
+ document.addEventListener('click', outsideClickHandler);
+ console.log('About page: Outside click handler added');
+ }, 10);
+
+ console.log('About page: Backup user menu handler set up successfully');
+
+ // Add specific logout handler for the about page
+ const logoutMenuItem = document.getElementById('logoutMenuItem');
+ if (logoutMenuItem) {
+ // Clone the logout menu item to remove any existing listeners
+ const newLogoutMenuItem = logoutMenuItem.cloneNode(true);
+ logoutMenuItem.parentNode.replaceChild(newLogoutMenuItem, logoutMenuItem);
+
+ newLogoutMenuItem.addEventListener('click', async (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('About page: Logout clicked (backup handler)');
+
+ // Close the user menu
+ userMenuDropdown.classList.remove('active');
+
+ try {
+ // Clear auth data manually since showLoading might fail
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+
+ // Try to call the auth manager logout if available
+ if (window.auth && typeof window.auth.logout === 'function') {
+ console.log('About page: Calling auth.logout()');
+ await window.auth.logout();
+ } else {
+ console.log('About page: Auth manager not available, redirecting manually');
+ // Redirect manually if auth manager fails
+ window.location.href = 'login.html';
+ }
+ } catch (error) {
+ console.error('About page: Logout error, falling back to manual redirect:', error);
+ // Clear auth data and redirect as fallback
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+ window.location.href = 'login.html';
+ }
+ });
+
+ console.log('About page: Backup logout handler set up');
+ }
+ } else {
+ console.error('About page: User menu elements not found!', {
+ userMenuBtn: !!userMenuBtn,
+ userMenuDropdown: !!userMenuDropdown
+ });
+ }
+ }, 200); // Delay to allow auth.js to complete setup
+
+ // Move authentication check here, after auth.js has had time to set up
+ setTimeout(() => {
+ // Check if user is authenticated (with a small delay to allow auth.js to process)
+ const authToken = localStorage.getItem('auth_token');
+ const userInfo = localStorage.getItem('user_info');
+
+ if (!authToken || !userInfo) {
+ // User is not authenticated, redirect to login page
+ console.log('About page: User not authenticated, redirecting to login');
+ window.location.href = 'login.html';
+ return;
+ }
+ }, 100); // Small delay to allow auth.js to complete setup
});
</script>
+ <!-- Loading Spinner -->
+ <div class="loading-container" id="loadingContainer">
+ <div class="loading-spinner"></div>
+ </div>
+
+ <script>
+ function applyFooterStyles() {
+ const footer = document.getElementById('warrackerFooter');
+ const link = document.getElementById('warrackerFooterLink');
+ const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark' || document.documentElement.classList.contains('dark-mode') || document.body.classList.contains('dark-mode');
+ if (footer) {
+ if (isDarkMode) {
+ // Dark mode styles - using same background as header (#2d2d2d)
+ footer.style.cssText = 'margin-top: 50px; padding: 20px; text-align: center; border-top: 1px solid #444; background-color: #2d2d2d; color: #e0e0e0; font-size: 0.9rem;';
+ if (link) link.style.cssText = 'color: #4dabf7; text-decoration: none; font-weight: 500;';
+ } else {
+ // Light mode styles - using same background as header (#ffffff)
+ footer.style.cssText = 'margin-top: 50px; padding: 20px; text-align: center; border-top: 1px solid #e0e0e0; background-color: #ffffff; color: #333333; font-size: 0.9rem;';
+ if (link) link.style.cssText = 'color: #3498db; text-decoration: none; font-weight: 500;';
+ }
+ }
+ }
+ document.addEventListener('DOMContentLoaded', applyFooterStyles);
+ const obs = new MutationObserver(applyFooterStyles);
+ obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'class'] });
+ obs.observe(document.body, { attributes: true, attributeFilter: ['class'] });
+ </script>
+
</body>
-</html>
\ No newline at end of file
+</html>
diff --git a/frontend/auth-redirect.html b/frontend/auth-redirect.html
new file mode 100644
index 0000000..5633dfa
--- /dev/null
+++ b/frontend/auth-redirect.html
@@ -0,0 +1,206 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Authenticating...</title>
+ <link rel="stylesheet" href="style.css?v=20250119001">
+ <script src="theme-loader.js?v=20250119001"></script>
+ <style>
+ body {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100vh;
+ margin: 0;
+ background-color: var(--bg-color);
+ color: var(--text-color);
+ font-family: sans-serif;
+ }
+ .container {
+ text-align: center;
+ padding: 20px;
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ box-shadow: 0 0 10px rgba(0,0,0,0.1);
+ }
+ .error-message {
+ color: #f44336; /* Red for errors */
+ margin-bottom: 15px;
+ }
+ a {
+ color: var(--primary-color);
+ }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <h2 id="statusMessage">Authenticating, please wait...</h2>
+ <div id="errorMessage" class="error-message" style="display: none;"></div>
+ <a href="login.html" id="loginLink" style="display: none;">Return to Login</a>
+ </div>
+
+ <script>
+ async function fetchUserInfoAndRedirect(token, isNewUser) {
+ const statusMessage = document.getElementById('statusMessage');
+ const errorMessageEl = document.getElementById('errorMessage');
+ const loginLink = document.getElementById('loginLink');
+
+ try {
+ statusMessage.textContent = 'Fetching user information...';
+
+ // Fetch user info using the token
+ const response = await fetch('/api/auth/validate-token', {
+ headers: { 'Authorization': `Bearer ${token}` }
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ if (data.valid && data.user && data.user.id) {
+ // Store user info in localStorage
+ localStorage.setItem('user_info', JSON.stringify(data.user));
+
+ // Update status message
+ if (isNewUser) {
+ statusMessage.textContent = 'Account created successfully! Redirecting...';
+ } else {
+ statusMessage.textContent = 'Login successful! Redirecting...';
+ }
+
+ // Redirect to the main application page
+ setTimeout(() => {
+ window.location.href = 'index.html';
+ }, 1500);
+ } else {
+ throw new Error('Invalid user data received');
+ }
+ } else {
+ throw new Error(`Failed to validate token: ${response.status}`);
+ }
+ } catch (error) {
+ console.error('Error fetching user info:', error);
+
+ // Clear potentially invalid token
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+
+ statusMessage.textContent = 'SSO Login Failed';
+ errorMessageEl.textContent = 'Failed to fetch user information. Please try logging in again.';
+ errorMessageEl.style.display = 'block';
+ loginLink.style.display = 'inline';
+ }
+ }
+
+ document.addEventListener('DOMContentLoaded', function() {
+ const statusMessage = document.getElementById('statusMessage');
+ const errorMessageEl = document.getElementById('errorMessage');
+ const loginLink = document.getElementById('loginLink');
+
+ const params = new URLSearchParams(window.location.search);
+ const token = params.get('token');
+ const oidcError = params.get('oidc_error');
+ const newUser = params.get('new_user');
+
+ if (oidcError) {
+ let message = 'An unknown error occurred during SSO login.';
+ switch (oidcError) {
+ case 'token_exchange_failed':
+ message = 'Failed to exchange authorization code for tokens with the SSO provider.';
+ break;
+ case 'token_missing':
+ message = 'Access token was not received from the SSO provider.';
+ break;
+ case 'userinfo_fetch_failed':
+ message = 'Failed to fetch user information from the SSO provider.';
+ break;
+ case 'userinfo_missing':
+ message = 'User information was not received from the SSO provider.';
+ break;
+ case 'subject_missing':
+ message = 'User subject identifier (sub) was missing from SSO provider response.';
+ break;
+ case 'email_missing_for_new_user':
+ message = 'Email address was not provided by SSO provider, which is required for new user registration.';
+ break;
+ case 'email_conflict_local_account':
+ message = 'The email address from your SSO provider is already associated with an existing local account. Please log in with your local credentials or contact support.';
+ break;
+ case 'registration_disabled':
+ message = 'New user registration via SSO is currently disabled. Only existing users can log in with SSO. Please contact your administrator if you need an account.';
+ break;
+ case 'user_processing_failed':
+ message = 'Failed to process user information after SSO login.';
+ break;
+ case 'db_error':
+ message = 'A database error occurred during SSO login. Please try again later.';
+ break;
+ case 'internal_error':
+ message = 'An internal server error occurred during SSO login. Please try again later.';
+ break;
+ }
+ statusMessage.textContent = 'SSO Login Failed';
+ errorMessageEl.textContent = message;
+ errorMessageEl.style.display = 'block';
+ loginLink.style.display = 'inline';
+ } else if (token) {
+ localStorage.setItem('auth_token', token);
+
+ // Fetch user info immediately after storing token to ensure it's available
+ // when the main app loads, preventing preference key mismatches
+ fetchUserInfoAndRedirect(token, newUser === 'true');
+ } else {
+ // No token and no error, unexpected state, redirect to login
+ statusMessage.textContent = 'Redirecting to login...';
+ setTimeout(() => {
+ window.location.href = 'login.html';
+ }, 1000);
+ }
+ });
+ </script>
+
+ <!-- i18next Local Scripts -->
+ <script src="js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+
+ <!-- i18n Configuration -->
+ <script src="js/i18n.js?v=20250119001"></script>
+
+ <script src="auth-redirect.js?v=20250119001"></script>
+
+ <!-- Footer Width Fix -->
+ <script src="footer-fix.js?v=20250119001"></script>
+
+ <!-- Footer Content Manager -->
+ <script src="footer-content.js?v=20250119001"></script>
+
+ <!-- Powered by Warracker Footer -->
+ <footer class="warracker-footer" id="warrackerFooter">
+ <!-- Content will be dynamically generated by footer-content.js -->
+ </footer>
+
+ <script>
+ function applyFooterStyles() {
+ const footer = document.getElementById('warrackerFooter');
+ const link = document.getElementById('warrackerFooterLink');
+ const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark' || document.documentElement.classList.contains('dark-mode') || document.body.classList.contains('dark-mode');
+ if (footer) {
+ if (isDarkMode) {
+ // Dark mode styles - using same background as header (#2d2d2d)
+ footer.style.cssText = 'margin-top: 50px; padding: 20px; text-align: center; border-top: 1px solid #444; background-color: #2d2d2d; color: #e0e0e0; font-size: 0.9rem;';
+ if (link) link.style.cssText = 'color: #4dabf7; text-decoration: none; font-weight: 500;';
+ } else {
+ // Light mode styles - using same background as header (#ffffff)
+ footer.style.cssText = 'margin-top: 50px; padding: 20px; text-align: center; border-top: 1px solid #e0e0e0; background-color: #ffffff; color: #333333; font-size: 0.9rem;';
+ if (link) link.style.cssText = 'color: #3498db; text-decoration: none; font-weight: 500;';
+ }
+ }
+ }
+ document.addEventListener('DOMContentLoaded', applyFooterStyles);
+ const obs = new MutationObserver(applyFooterStyles);
+ obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'class'] });
+ obs.observe(document.body, { attributes: true, attributeFilter: ['class'] });
+ </script>
+
+</body>
+</html>
diff --git a/frontend/auth.js b/frontend/auth.js
index cc03297..cd9ac8f 100644
--- a/frontend/auth.js
+++ b/frontend/auth.js
@@ -3,385 +3,362 @@
* Handles user login, logout, and authentication state management
*/
-// DOM Elements
-const authContainer = document.getElementById('authContainer');
-const userMenu = document.getElementById('userMenu');
-const userBtn = document.getElementById('userBtn');
-const userMenuDropdown = document.getElementById('userMenuDropdown');
-const userDisplayName = document.getElementById('userDisplayName');
-const userName = document.getElementById('userName');
-const userEmail = document.getElementById('userEmail');
-const logoutMenuItem = document.getElementById('logoutMenuItem');
-const profileMenuItem = document.getElementById('profileMenuItem');
+class AuthManager {
+ constructor() {
+ this.token = null;
+ this.currentUser = null;
+ this.onLogoutCallbacks = [];
-// New UI Elements (from screenshot)
-const loginButton = document.querySelector('a[href="login.html"]');
-const registerButton = document.querySelector('a[href="register.html"]');
-const usernameDisplay = document.querySelector('.user-name');
+ // Initial state load from localStorage
+ this.token = localStorage.getItem('auth_token');
+ const userInfoString = localStorage.getItem('user_info');
+ if (userInfoString) {
+ try {
+ this.currentUser = JSON.parse(userInfoString);
+ } catch (e) {
+ console.error('Auth.js: Corrupt user_info in localStorage. Clearing.');
+ this.currentUser = null;
+ localStorage.removeItem('user_info');
+ // Consider clearing token as well if user_info is corrupt
+ // localStorage.removeItem('auth_token');
+ // this.token = null;
+ }
+ }
+ console.log('[Auth.js] Initial state:', { token: this.token ? 'present' : 'null', currentUser: this.currentUser });
+ }
-// Authentication state
-let currentUser = null;
-let authToken = null;
+ isAuthenticated() {
+ // User is authenticated if both token and currentUser (with an id) are present
+ return !!(this.token && this.currentUser && this.currentUser.id);
+ }
-// Initialize authentication
-document.addEventListener('DOMContentLoaded', () => {
- // Initial check of authentication state
- checkAuthState();
-
- // Set up periodic check of auth state (every 30 seconds)
- // setInterval(checkAuthState, 30000); // Consider if needed, can cause flicker
-
- // --- USER MENU TOGGLE ---
- const userMenuBtn = document.getElementById('userMenuBtn');
- const userMenuDropdown = document.getElementById('userMenuDropdown');
- console.log('auth.js: Checking for user menu elements...', { userMenuBtn, userMenuDropdown }); // Debug log
- if (userMenuBtn && userMenuDropdown) {
- console.log('auth.js: User menu elements found, adding listener.'); // Debug log
- userMenuBtn.addEventListener('click', (e) => {
- console.log('auth.js: User menu button CLICKED!'); // *** ADDED LOG ***
- e.stopPropagation();
- userMenuDropdown.classList.toggle('active');
- console.log('auth.js: User menu dropdown toggled.', { active: userMenuDropdown.classList.contains('active') }); // *** ADDED LOG ***
- });
- } else {
- console.log('auth.js: User menu button or dropdown not found on this page.'); // Debug log
+ getCurrentUser() {
+ return this.currentUser;
}
-
- // --- SETTINGS GEAR MENU TOGGLE (Moved from settings-new.js) ---
- const settingsBtn = document.getElementById('settingsBtn'); // Gear icon button
- const settingsMenu = document.getElementById('settingsMenu'); // The dropdown menu itself
- console.log('auth.js: Checking for settings menu elements...', { settingsBtn, settingsMenu }); // Debug log
- if (settingsBtn && settingsMenu) {
- console.log('auth.js: Settings menu elements found, adding listeners.'); // Debug log
- // Toggle settings menu when settings button is clicked
- settingsBtn.addEventListener('click', function(e) {
- e.stopPropagation(); // Prevent click from closing menu immediately
- settingsMenu.classList.toggle('active');
- console.log('auth.js: Settings button clicked, menu toggled.', { active: settingsMenu.classList.contains('active') }); // Debug log
- });
- } else {
- console.log('auth.js: Settings button or menu not found on this page.'); // Debug log
+
+ getToken() {
+ // Always return the current state of this.token, which should be synced with localStorage
+ return this.token;
+ }
+
+ clearAuthData() {
+ console.log('[Auth.js] Clearing auth data.');
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+ this.token = null;
+ this.currentUser = null;
+ this.onLogoutCallbacks.forEach(cb => cb());
}
- // --- END SETTINGS GEAR MENU TOGGLE ---
- // Close menus when clicking outside
- document.addEventListener('click', (e) => {
- // Close user menu
- if (userMenuDropdown && userMenuBtn &&
- userMenuDropdown.classList.contains('active') &&
- !userMenuDropdown.contains(e.target) &&
- !userMenuBtn.contains(e.target)) {
- userMenuDropdown.classList.remove('active');
- }
- // Close settings menu
- if (settingsMenu && settingsBtn &&
- settingsMenu.classList.contains('active') &&
- !settingsMenu.contains(e.target) &&
- !settingsBtn.contains(e.target)) {
- settingsMenu.classList.remove('active');
- console.log('auth.js: Click outside closed settings menu.'); // Debug log
+ onLogout(callback) {
+ if (typeof callback === 'function') {
+ this.onLogoutCallbacks.push(callback);
}
- });
-
- // Logout functionality
- const logoutMenuItem = document.getElementById('logoutMenuItem');
- if (logoutMenuItem) {
- logoutMenuItem.addEventListener('click', logout);
}
-
- // Profile menu item link (assuming it's an <a> tag now)
- // const profileLink = document.querySelector('.user-menu-item a[href="settings-new.html"]');
- // No special listener needed if it's just a link
-});
-/**
- * Check if user is authenticated and update UI accordingly
- */
-function checkAuthState() {
- // Get latest token from localStorage
- authToken = localStorage.getItem('auth_token');
- const userInfo = localStorage.getItem('user_info');
-
- if (authToken && userInfo) {
- try {
- currentUser = JSON.parse(userInfo);
- updateUIForAuthenticatedUser();
- validateToken();
- } catch (error) {
- console.error('Error parsing user info:', error);
- clearAuthData();
- updateUIForUnauthenticatedUser();
+ async checkAuthState(isInitialLoad = false) {
+ console.log('[Auth.js] checkAuthState called. Initial load:', isInitialLoad);
+ this.token = localStorage.getItem('auth_token'); // Re-read token, might have changed (e.g. by auth-redirect.js)
+ const userInfoString = localStorage.getItem('user_info');
+
+ this.currentUser = null; // Reset before check
+
+ if (userInfoString) {
+ try {
+ this.currentUser = JSON.parse(userInfoString);
+ } catch (e) {
+ console.error('Auth.js: Failed to parse user_info from localStorage during checkAuthState. Clearing auth data.', e);
+ this.clearAuthData(); // Clear potentially corrupt data
+ this.updateUIBasedOnAuthState(); // Update UI to reflect logged-out state
+ return; // Exit early
+ }
}
- } else {
- updateUIForUnauthenticatedUser();
+
+ if (this.token) {
+ // If token exists, try to validate it and fetch/confirm user_info
+ // This is crucial if user_info was missing or to refresh/validate existing user_info
+ console.log('[Auth.js] Token found. Validating and fetching user info...');
+ try {
+ const response = await fetch('/api/auth/validate-token', {
+ headers: { 'Authorization': `Bearer ${this.token}` }
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ if (data.valid && data.user && data.user.id) {
+ this.currentUser = data.user;
+ localStorage.setItem('user_info', JSON.stringify(this.currentUser)); // Ensure localStorage is up-to-date
+ console.log('[Auth.js] Token validated, user_info updated/confirmed:', this.currentUser);
+ } else {
+ console.warn('[Auth.js] Token validation failed or user data invalid from API. Clearing auth data.');
+ this.clearAuthData();
+ }
+ } else {
+ console.warn(`[Auth.js] Token validation API call failed (status: ${response.status}). Clearing auth data.`);
+ this.clearAuthData();
+ }
+ } catch (error) {
+ console.error('[Auth.js] Error validating token / fetching user info:', error);
+ this.clearAuthData();
+ }
+ } else {
+ // No token, ensure everything is cleared
+ if (this.currentUser) { // If there was user_info but no token, clear user_info
+ console.log('[Auth.js] No token found, but user_info was present. Clearing user_info.');
+ this.clearAuthData();
+ }
+ }
+
+ this.updateUIBasedOnAuthState();
}
-}
-/**
- * Update UI elements for authenticated user
- */
-function updateUIForAuthenticatedUser() {
- // Fire a global event so other scripts (like script.js) can react to authentication being ready
- setTimeout(() => {
- console.log('[auth.js] Dispatching authStateReady event');
- window.dispatchEvent(new Event('authStateReady'));
- }, 0);
- console.log('auth.js: Updating UI for authenticated user');
+ updateUIBasedOnAuthState() {
+ const isAuthenticated = this.isAuthenticated();
+ this._updateDOMForAuthState(isAuthenticated, this.currentUser);
+ this.dispatchAuthStateEvent(isAuthenticated, this.currentUser);
+ }
- // Log the user data being used
- console.log('auth.js: Current user data from state:', currentUser);
- if (!currentUser) {
- console.error('auth.js: Cannot update UI, currentUser is null or undefined.');
- return;
+ _updateDOMForAuthState(isAuthenticated, user) {
+ const authContainer = document.getElementById('authContainer');
+ const userMenu = document.getElementById('userMenu');
+ const userDisplayName = document.getElementById('userDisplayName');
+ const userNameMenu = document.getElementById('userName');
+ const userEmailMenu = document.getElementById('userEmail');
+ const logoutMenuItem = document.getElementById('logoutMenuItem');
+
+ // Select all potential login/register buttons more broadly
+ const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn');
+ const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn');
+ const genericAuthButtonsContainers = document.querySelectorAll('.auth-buttons');
+
+
+ if (isAuthenticated && user) {
+ console.log('Auth.js: Updating UI for AUTHENTICATED user:', user);
+ if (authContainer) { authContainer.style.display = 'none'; authContainer.style.visibility = 'hidden'; }
+
+ if (userMenu) {
+ userMenu.style.display = 'block'; // Or 'flex' based on CSS
+ userMenu.style.visibility = 'visible';
+ const displayNameText = user.first_name || user.username || 'User';
+ const fullNameText = `${user.first_name || ''} ${user.last_name || ''}`.trim() || user.username || 'User Name';
+ if (userDisplayName) userDisplayName.textContent = displayNameText;
+ if (userNameMenu) userNameMenu.textContent = fullNameText;
+ if (userEmailMenu && user.email) userEmailMenu.textContent = user.email;
+ }
+ loginButtons.forEach(btn => { btn.style.display = 'none'; btn.style.visibility = 'hidden'; });
+ registerButtons.forEach(btn => { btn.style.display = 'none'; btn.style.visibility = 'hidden'; });
+ genericAuthButtonsContainers.forEach(container => {
+ if (container.id !== 'authContainer') { // Avoid double-hiding if authContainer also has .auth-buttons
+ container.style.display = 'none'; container.style.visibility = 'hidden';
+ }
+ });
+
+ if (logoutMenuItem) {
+ logoutMenuItem.style.display = 'flex'; // Assuming it's a flex item
+ // Ensure logout listener is attached (can be done once in constructor or DOMContentLoaded)
+ }
+ } else {
+ console.log('Auth.js: Updating UI for UNAUTHENTICATED user.');
+ if (authContainer) { authContainer.style.display = 'flex'; authContainer.style.visibility = 'visible'; }
+
+ if (userMenu) { userMenu.style.display = 'none'; userMenu.style.visibility = 'hidden'; }
+
+ // Reset user display names if they exist
+ if (userDisplayName) userDisplayName.textContent = 'User';
+ if (userNameMenu) userNameMenu.textContent = 'User Name';
+ if (userEmailMenu) userEmailMenu.textContent = '[email protected]';
+
+ loginButtons.forEach(btn => { btn.style.display = 'inline-block'; btn.style.visibility = 'visible'; });
+ registerButtons.forEach(btn => { btn.style.display = 'inline-block'; btn.style.visibility = 'visible'; });
+ genericAuthButtonsContainers.forEach(container => {
+ if (container.id !== 'authContainer') {
+ container.style.display = 'flex'; // Or 'block'
+ container.style.visibility = 'visible';
+ }
+ });
+ if (logoutMenuItem) { logoutMenuItem.style.display = 'none'; }
+ }
}
- // Hide login/register buttons
- if (authContainer) {
- console.log('auth.js: Hiding authContainer');
- authContainer.style.display = 'none';
- authContainer.style.visibility = 'hidden';
+ dispatchAuthStateEvent(isAuthenticated, user) {
+ console.log('[Auth.js] Dispatching authStateReady event', { isAuthenticated, user });
+ // Ensure this event is dispatched after the current call stack clears
+ setTimeout(() => {
+ window.dispatchEvent(new CustomEvent('authStateReady', {
+ detail: { isAuthenticated, user }
+ }));
+ }, 0);
}
-
- // Show user menu
- if (userMenu) {
- console.log('auth.js: Showing userMenu');
- userMenu.style.display = 'block';
- userMenu.style.visibility = 'visible';
+
+ async login(username, password) {
+ // Assuming showLoading/hideLoading are global or part of another module
+ if (typeof showLoading === 'function') showLoading();
+ try {
+ const response = await fetch('/api/auth/login', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ username, password })
+ });
+ const data = await response.json();
+ if (response.ok) {
+ this.token = data.token;
+ this.currentUser = data.user;
+ localStorage.setItem('auth_token', this.token);
+ localStorage.setItem('user_info', JSON.stringify(this.currentUser));
+ this.updateUIBasedOnAuthState();
+ return data; // Return data for login.js to handle redirect
+ } else {
+ throw new Error(data.message || 'Login failed');
+ }
+ } catch (error) {
+ this.clearAuthData(); // Ensure state is cleared on login failure
+ this.updateUIBasedOnAuthState();
+ throw error; // Re-throw for login.js to handle
+ } finally {
+ if (typeof hideLoading === 'function') hideLoading();
+ }
}
-
- // Update user info in the header menu
- let displayName = currentUser.username || 'User';
- const fullName = `${currentUser.first_name || ''} ${currentUser.last_name || ''}`.trim() || currentUser.username || 'User Name'; // Fallback added
- const email = currentUser.email || '[email protected]'; // Fallback added
-
- // Log the values being set
- console.log(`auth.js: Setting display name (short): [${displayName}]`);
- console.log(`auth.js: Setting full name (menu): [${fullName}]`);
- console.log(`auth.js: Setting email (menu): [${email}]`);
- if (userDisplayName) userDisplayName.textContent = displayName;
- if (userName) userName.textContent = fullName;
- if (userEmail) userEmail.textContent = email;
-
- // Hide all login and register buttons
- const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');
- const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');
-
- console.log('auth.js: Found login buttons:', loginButtons.length);
- console.log('auth.js: Found register buttons:', registerButtons.length);
-
- loginButtons.forEach(button => {
- console.log('auth.js: Hiding login button');
- button.style.display = 'none';
- button.style.visibility = 'hidden';
- });
-
- registerButtons.forEach(button => {
- console.log('auth.js: Hiding register button');
- button.style.display = 'none';
- button.style.visibility = 'hidden';
- });
-
- // Hide any containers with the auth-buttons class
- const authButtonsContainers = document.querySelectorAll('.auth-buttons');
- authButtonsContainers.forEach(container => {
- console.log('auth.js: Hiding auth buttons container');
- container.style.display = 'none';
- container.style.visibility = 'hidden';
- });
-}
+ async logout() {
+ if (typeof showLoading === 'function') showLoading();
+ const currentTokenForApiCall = this.token; // Use current token for API call
+
+ this.clearAuthData(); // Clear local state immediately
+ this.updateUIBasedOnAuthState(); // Update UI to logged-out state
-/**
- * Update UI elements for unauthenticated user
- */
-function updateUIForUnauthenticatedUser() {
- console.log('auth.js: Updating UI for unauthenticated user');
-
- // Show login/register buttons
- if (authContainer) {
- console.log('auth.js: Showing authContainer');
- authContainer.style.display = 'flex';
- authContainer.style.visibility = 'visible';
+ try {
+ if (currentTokenForApiCall) {
+ await fetch('/api/auth/logout', {
+ method: 'POST',
+ headers: { 'Authorization': `Bearer ${currentTokenForApiCall}` }
+ });
+ console.log('[Auth.js] Logout API call successful.');
+ }
+ } catch (error) {
+ console.error('[Auth.js] Logout API call failed, but user is logged out locally.', error);
+ } finally {
+ if (typeof hideLoading === 'function') hideLoading();
+ // Redirect to login page after all operations
+ if (window.location.pathname !== '/login.html') {
+ window.location.href = 'login.html';
+ }
+ }
}
- // Hide user menu
- if (userMenu) {
- console.log('auth.js: Hiding userMenu');
- userMenu.style.display = 'none';
- userMenu.style.visibility = 'hidden';
+ addAuthHeader(options = {}) {
+ const token = this.getToken();
+ if (!token) return options;
+
+ const headers = options.headers || {};
+ return { ...options, headers: { ...headers, 'Authorization': `Bearer ${token}`}};
}
-
- // Clear user info
- if (userDisplayName) userDisplayName.textContent = 'User';
- if (userName) userName.textContent = 'User Name';
- if (userEmail) userEmail.textContent = '[email protected]';
-
- // Show all login and register buttons
- const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');
- const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');
-
- loginButtons.forEach(button => {
- button.style.display = 'inline-block';
- button.style.visibility = 'visible';
- });
-
- registerButtons.forEach(button => {
- button.style.display = 'inline-block';
- button.style.visibility = 'visible';
- });
-
- // Show any containers with the auth-buttons class
- const authButtonsContainers = document.querySelectorAll('.auth-buttons');
- authButtonsContainers.forEach(container => {
- container.style.display = 'flex';
- container.style.visibility = 'visible';
- });
}
-/**
- * Logout user
- */
-async function logout() {
- try {
- showLoading();
+// Initialize and export
+window.auth = new AuthManager();
+
+// Initial check on DOMContentLoaded
+document.addEventListener('DOMContentLoaded', async () => {
+ console.log('[Auth.js] DOMContentLoaded - performing initial async auth state check.');
+ await window.auth.checkAuthState(true); // Ensure auth state is processed first
+
+ // Setup user menu toggle
+ const userMenuBtn_original = document.getElementById('userMenuBtn');
+ const userMenuDropdown = document.getElementById('userMenuDropdown');
+
+ if (userMenuBtn_original && userMenuDropdown) {
+ console.log('[Auth.js] Setting up user menu. Button:', userMenuBtn_original, 'Dropdown:', userMenuDropdown);
- // Call logout API
- const response = await fetch('/api/auth/logout', {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${authToken}`,
- 'Content-Type': 'application/json'
- }
+ // Robust listener attachment: clone the button to remove any prior listeners
+ const userMenuBtn = userMenuBtn_original.cloneNode(true);
+ userMenuBtn_original.parentNode.replaceChild(userMenuBtn, userMenuBtn_original);
+
+ userMenuBtn.addEventListener('click', (e) => {
+ e.stopPropagation(); // Prevent click from immediately closing due to document listener
+ console.log('[Auth.js] userMenuBtn clicked - DEBUG INFO:', {
+ userMenuDropdown: !!userMenuDropdown,
+ dropdownClassList: userMenuDropdown ? Array.from(userMenuDropdown.classList) : 'not found',
+ hasActiveClass: userMenuDropdown ? userMenuDropdown.classList.contains('active') : 'dropdown not found',
+ buttonId: userMenuBtn.id,
+ dropdownId: userMenuDropdown ? userMenuDropdown.id : 'not found'
+ });
+
+ userMenuDropdown.classList.toggle('active');
+
+ const isNowActive = userMenuDropdown.classList.contains('active');
+ console.log('[Auth.js] User menu toggled via userMenuBtn. Active:', isNowActive);
+
+ // Add a temporary debug check to see if it gets closed immediately
+ setTimeout(() => {
+ const stillActive = userMenuDropdown.classList.contains('active');
+ console.log('[Auth.js] User menu status after 100ms:', stillActive);
+ if (isNowActive && !stillActive) {
+ console.warn('[Auth.js] User menu was closed immediately! Possible global click interference.');
+ }
+ }, 100);
});
-
- // Clear auth data regardless of API response
- clearAuthData();
- updateUIForUnauthenticatedUser();
-
- // Show success message
- showToast('Logged out successfully', 'success');
-
- // Redirect to login page
- window.location.href = 'login.html';
-
- } catch (error) {
- console.error('Logout error:', error);
-
- // Still clear auth data even if API call fails
- clearAuthData();
- updateUIForUnauthenticatedUser();
-
- showToast('Logged out', 'info');
-
- // Redirect to login page even if there was an error
- window.location.href = 'login.html';
- } finally {
- hideLoading();
+ console.log('[Auth.js] User menu click listener attached to userMenuBtn.');
+ } else {
+ console.warn('[Auth.js] User menu button (userMenuBtn) or dropdown (userMenuDropdown) not found. Menu interactivity might be affected.');
}
-}
-/**
- * Clear authentication data from localStorage
- */
-function clearAuthData() {
- // Clear both localStorage and global variables
- localStorage.removeItem('auth_token');
- localStorage.removeItem('user_info');
- authToken = null;
- currentUser = null;
-}
+ // Setup settings gear menu toggle (if elements exist on the current page)
+ const settingsBtn_original = document.getElementById('settingsBtn');
+ const settingsMenu = document.getElementById('settingsMenu'); // The dropdown menu itself
+ if (settingsBtn_original && settingsMenu) {
+ const settingsBtn = settingsBtn_original.cloneNode(true);
+ settingsBtn_original.parentNode.replaceChild(settingsBtn, settingsBtn_original);
-/**
- * Validate token with the server
- */
-async function validateToken() {
- if (!authToken) {
- clearAuthData();
- updateUIForUnauthenticatedUser();
- return;
- }
-
- try {
- // Use the full URL to avoid path issues
- const apiUrl = window.location.origin + '/api/auth/validate-token';
-
- const response = await fetch(apiUrl, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${authToken}`
- }
+ settingsBtn.addEventListener('click', function(e) {
+ e.stopPropagation();
+ settingsMenu.classList.toggle('active');
+ console.log('[Auth.js] Settings menu toggled via settingsBtn.');
});
-
- if (!response.ok) {
- const errorData = await response.json();
- console.error('Token validation failed:', errorData.message);
- throw new Error(errorData.message || 'Invalid token');
- }
-
- // Token is valid, update last active time
- const data = await response.json();
- if (data.user) {
- currentUser = data.user;
- localStorage.setItem('user_info', JSON.stringify(currentUser));
- updateUIForAuthenticatedUser();
- }
-
- return true;
- } catch (error) {
- console.error('Token validation error:', error);
- clearAuthData();
- updateUIForUnauthenticatedUser();
-
- // Only show toast if we're on a page that requires authentication
- if (window.location.pathname !== '/login.html' &&
- window.location.pathname !== '/register.html' &&
- window.location.pathname !== '/reset-password.html' &&
- window.location.pathname !== '/reset-password-request.html') {
- showToast('Your session has expired. Please login again.', 'warning');
- }
-
- return false;
+ console.log('[Auth.js] Settings menu click listener attached to settingsBtn.');
}
-}
-/**
- * Add authorization header to fetch requests
- * @param {Object} options - Fetch options
- * @returns {Object} - Updated fetch options with auth header
- */
-function addAuthHeader(options = {}) {
- if (!authToken) return options;
-
- const headers = options.headers || {};
-
- return {
- ...options,
- headers: {
- ...headers,
- 'Authorization': `Bearer ${authToken}`
- }
- };
-}
+ // Global click listener to close dropdowns - ensure this is added only once
+ if (!window._authJsGlobalClickListenerAdded) {
+ document.addEventListener('click', (e) => {
+ console.log('[Auth.js] Global click detected on:', e.target);
+
+ // Re-fetch elements by ID inside the listener to ensure they are current
+ const currentDropdown = document.getElementById('userMenuDropdown');
+ const currentButton = document.getElementById('userMenuBtn'); // Use the standardized ID
-/**
- * Get the authentication token
- * @returns {string} - The authentication token
- */
-function getToken() {
- // Always get the latest token from localStorage and update global variable
- authToken = localStorage.getItem('auth_token');
- return authToken;
-}
+ if (currentDropdown && currentButton && currentDropdown.classList.contains('active')) {
+ console.log('[Auth.js] User menu is active, checking if click is outside...');
+ const isOutsideDropdown = !currentDropdown.contains(e.target);
+ const isOutsideButton = !currentButton.contains(e.target);
+ console.log('[Auth.js] Click outside dropdown:', isOutsideDropdown, 'outside button:', isOutsideButton);
+
+ if (isOutsideDropdown && isOutsideButton) {
+ currentDropdown.classList.remove('active');
+ console.log('[Auth.js] User menu closed by global click.');
+ }
+ }
+
+ const currentSettingsMenu = document.getElementById('settingsMenu');
+ const currentSettingsBtn = document.getElementById('settingsBtn');
+ if (currentSettingsMenu && currentSettingsBtn && currentSettingsMenu.classList.contains('active') &&
+ !currentSettingsMenu.contains(e.target) && !currentSettingsBtn.contains(e.target)) {
+ currentSettingsMenu.classList.remove('active');
+ console.log('[Auth.js] Settings menu closed by global click.');
+ }
+ });
+ window._authJsGlobalClickListenerAdded = true;
+ console.log('[Auth.js] Global click listener for dropdowns added.');
+ }
-// Export authentication functions for use in other scripts
-window.auth = {
- isAuthenticated: () => !!localStorage.getItem('auth_token'),
- getCurrentUser: () => {
- const userInfo = localStorage.getItem('user_info');
- return userInfo ? JSON.parse(userInfo) : null;
- },
- getToken: getToken,
- addAuthHeader,
- checkAuthState,
- logout
-};
+ // Attach logout listener to logout menu item
+ const logoutMenuItem_original = document.getElementById('logoutMenuItem');
+ if (logoutMenuItem_original) {
+ const logoutMenuItem = logoutMenuItem_original.cloneNode(true); // Ensures fresh listener
+ logoutMenuItem_original.parentNode.replaceChild(logoutMenuItem, logoutMenuItem_original);
+ logoutMenuItem.addEventListener('click', () => {
+ console.log('[Auth.js] Logout menu item clicked.');
+ window.auth.logout();
+ });
+ console.log('[Auth.js] Logout menu item listener attached.');
+ }
+});
diff --git a/frontend/chart.js b/frontend/chart.js
new file mode 100644
index 0000000..47cbcd9
--- /dev/null
+++ b/frontend/chart.js
@@ -0,0 +1,14 @@
+/*!
+ * Chart.js v4.4.9
+ * https://www.chartjs.org
+ * (c) 2025 Chart.js Contributors
+ * Released under the MIT License
+ */
+!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){"use strict";var t=Object.freeze({__proto__:null,get Colors(){return Zo},get Decimation(){return ta},get Filler(){return xa},get Legend(){return va},get SubTitle(){return Sa},get Title(){return wa},get Tooltip(){return Wa}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function o(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function a(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,c=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;a<r;a++)e.call(i,t[a],a);else if(o(t))for(l=Object.keys(t),r=l.length,a=0;a<r;a++)e.call(i,t[l[a]],l[a])}function f(t,e){let i,s,n,o;if(!t||!e||t.length!==e.length)return!1;for(i=0,s=t.length;i<s;++i)if(n=t[i],o=e[i],n.datasetIndex!==o.datasetIndex||n.index!==o.index)return!1;return!0}function g(t){if(n(t))return t.map(g);if(o(t)){const e=Object.create(null),i=Object.keys(t),s=i.length;let n=0;for(;n<s;++n)e[i[n]]=g(t[i[n]]);return e}return t}function p(t){return-1===["__proto__","prototype","constructor"].indexOf(t)}function m(t,e,i,s){if(!p(t))return;const n=e[t],a=i[t];o(n)&&o(a)?x(n,a,s):e[t]=g(a)}function x(t,e,i){const s=n(e)?e:[e],a=s.length;if(!o(t))return t;const r=(i=i||{}).merger||m;let l;for(let e=0;e<a;++e){if(l=s[e],!o(l))continue;const n=Object.keys(l);for(let e=0,s=n.length;e<s;++e)r(n[e],t,l,i)}return t}function b(t,e){return x(t,e,{merger:_})}function _(t,e,i){if(!p(t))return;const s=e[t],n=i[t];o(s)&&o(n)?b(s,n):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=g(n))}const y={"":t=>t,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>"function"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)<i}function B(t){const e=Math.round(t);t=V(t,e,t/1e3)?e:t;const i=Math.pow(10,Math.floor(z(t))),s=t/i;return(s<=1?1:s<=2?2:s<=5?5:10)*i}function W(t){const e=[],i=Math.sqrt(t);let s;for(s=1;s<i;s++)t%s==0&&(e.push(s),e.push(t/s));return i===(0|i)&&e.push(i),e.sort(((t,e)=>t-e)).pop(),e}function N(t){return!function(t){return"symbol"==typeof t||"object"==typeof t&&null!==t&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;s<n;s++)o=t[s][i],isNaN(o)||(e.min=Math.min(e.min,o),e.max=Math.max(e.max,o))}function $(t){return t*(C/180)}function Y(t){return t*(180/C)}function U(t){if(!a(t))return;let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}function X(t,e){const i=e.x-t.x,s=e.y-t.y,n=Math.sqrt(i*i+s*s);let o=Math.atan2(s,i);return o<-.5*C&&(o+=O),{angle:o,distance:n}}function q(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function K(t,e){return(t-e+A)%O-C}function G(t){return(t%O+O)%O}function Z(t,e,i,s){const n=G(t),o=G(e),a=G(i),r=G(o-n),l=G(a-n),h=G(n-o),c=G(n-a);return n===o||n===a||s&&o===a||r>l&&h<c}function J(t,e,i){return Math.max(e,Math.min(i,t))}function Q(t){return J(t,-32768,32767)}function tt(t,e,i,s=1e-6){return t>=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]<e);let s,n=t.length-1,o=0;for(;n-o>1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return n<i||n===i&&t[s+1][e]===i}:s=>t[s][e]<i),st=(t,e,i)=>et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;s<n&&t[s]<e;)s++;for(;n>s&&t[n-1]>i;)n--;return s>0||n<t.length?t.slice(s,n):t}const ot=["push","pop","shift","splice","unshift"];function at(t,e){t._chartjs?t._chartjs.listeners.push(e):(Object.defineProperty(t,"_chartjs",{configurable:!0,enumerable:!1,value:{listeners:[e]}}),ot.forEach((e=>{const i="_onData"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...e){const n=s.apply(this,e);return t._chartjs.listeners.forEach((t=>{"function"==typeof t[i]&&t[i](...e)})),n}})})))}function rt(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(ot.forEach((e=>{delete t[e]})),delete t._chartjs)}function lt(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const ht="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function ct(t,e){let i=[],s=!1;return function(...n){i=n,s||(s=!0,ht.call(window,(()=>{s=!1,t.apply(e,i)})))}}function dt(t,e){let i;return function(...s){return e?(clearTimeout(i),i=setTimeout(t,e,s)):t.apply(this,s),e}}const ut=t=>"start"===t?"left":"end"===t?"right":"center",ft=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2,gt=(t,e,i,s)=>t===(s?"left":"right")?i:"center"===t?(e+i)/2:e;function pt(t,e,i){const n=e.length;let o=0,a=n;if(t._sorted){const{iScale:r,vScale:l,_parsed:h}=t,c=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null,d=r.axis,{min:u,max:f,minDefined:g,maxDefined:p}=r.getUserBounds();if(g){if(o=Math.min(it(h,d,u).lo,i?n:it(e,d,r.getPixelForValue(u)).lo),c){const t=h.slice(0,o+1).reverse().findIndex((t=>!s(t[l.axis])));o-=Math.max(0,t)}o=J(o,0,n-1)}if(p){let t=Math.max(it(h,r.axis,f,!0).hi+1,i?0:it(e,d,r.getPixelForValue(f),!0).hi+1);if(c){const e=h.slice(t-1).findIndex((t=>!s(t[l.axis])));t+=Math.max(0,e)}a=J(t,o,n)-o}else a=n-o}return{start:o,count:a}}function mt(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.min,ymax:i.max};if(!s)return t._scaleRanges=n,!0;const o=s.xmin!==e.min||s.xmax!==e.max||s.ymin!==i.min||s.ymax!==i.max;return Object.assign(s,n),o}class xt{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,s){const n=e.listeners[s],o=e.duration;n.forEach((s=>s({chart:t,initial:e.initial,numSteps:o,currentStep:Math.min(i-e.start,o)})))}_refresh(){this._request||(this._running=!0,this._request=ht.call(window,(()=>{this._update(),this._request=null,this._running&&this._refresh()})))}_update(t=Date.now()){let e=0;this._charts.forEach(((i,s)=>{if(!i.running||!i.items.length)return;const n=i.items;let o,a=n.length-1,r=!1;for(;a>=0;--a)o=n[a],o._active?(o._total>i.duration&&(i.duration=o._total),o.tick(t),r=!0):(n[a]=n[n.length-1],n.pop());r&&(s.draw(),this._notify(s,i,t,"progress")),n.length||(i.running=!1,this._notify(s,i,t,"complete"),i.initial=!1),e+=n.length})),this._lastDate=t,0===e&&(this._running=!1)}_getAnims(t){const e=this._charts;let i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){const e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce(((t,e)=>Math.max(t,e._duration)),0),this._refresh())}running(t){if(!this._running)return!1;const e=this._charts.get(t);return!!(e&&e.running&&e.items.length)}stop(t){const e=this._charts.get(t);if(!e||!e.items.length)return;const i=e.items;let s=i.length-1;for(;s>=0;--s)i[s].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}}var bt=new xt;
+/*!
+ * @kurkle/color v0.3.2
+ * https://github.com/kurkle/color#readme
+ * (c) 2023 Jukka Kurkela
+ * Released under the MIT License
+ */function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[..."0123456789ABCDEF"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e<i?6:0):e===n?(i-t)/s+2:(t-e)/s+4}(e,i,s,h,n),r=60*r+.5),[0|r,l||0,a]}function zt(t,e,i,s){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,i,s)).map(Mt)}function Ft(t,e,i){return zt(Lt,t,e,i)}function Vt(t){return(t%360+360)%360}function Bt(t){const e=Tt.exec(t);let i,s=255;if(!e)return;e[5]!==i&&(s=e[6]?vt(+e[5]):Mt(+e[5]));const n=Vt(+e[2]),o=+e[3]/100,a=+e[4]/100;return i="hwb"===e[1]?function(t,e,i){return zt(Rt,t,e,i)}(n,o,a):"hsv"===e[1]?function(t,e,i){return zt(Et,t,e,i)}(n,o,a):Ft(n,o,a),{r:i[0],g:i[1],b:i[2],a:s}}const Wt={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},Nt={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};let Ht;function jt(t){Ht||(Ht=function(){const t={},e=Object.keys(Nt),i=Object.keys(Wt);let s,n,o,a,r;for(s=0;s<e.length;s++){for(a=r=e[s],n=0;n<i.length;n++)o=i[n],r=r.replace(o,Wt[o]);o=parseInt(Nt[a],16),t[r]=[o>>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=Ft(s),t.r=s[0],t.g=s[1],t.b=s[2]}}function qt(t,e){return t?Object.assign(e||{},t):t}function Kt(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=Mt(t[3]))):(e=qt(t,{r:0,g:0,b:0,a:1})).a=Mt(e.a),e}function Gt(t){return"r"===t.charAt(0)?function(t){const e=$t.exec(t);let i,s,n,o=255;if(e){if(e[7]!==i){const t=+e[7];o=e[8]?vt(t):yt(255*t,0,255)}return i=+e[1],s=+e[3],n=+e[5],i=255&(e[2]?vt(i):yt(i,0,255)),s=255&(e[4]?vt(s):yt(s,0,255)),n=255&(e[6]?vt(n):yt(n,0,255)),{r:i,g:s,b:n,a:o}}}(t):Bt(t)}class Zt{constructor(t){if(t instanceof Zt)return t;const e=typeof t;let i;var s,n,o;"object"===e?i=Kt(t):"string"===e&&(o=(s=t).length,"#"===s[0]&&(4===o||5===o?n={r:255&17*St[s[1]],g:255&17*St[s[2]],b:255&17*St[s[3]],a:5===o?17*St[s[4]]:255}:7!==o&&9!==o||(n={r:St[s[1]]<<4|St[s[2]],g:St[s[3]]<<4|St[s[4]],b:St[s[5]]<<4|St[s[6]],a:9===o?St[s[7]]<<4|St[s[8]]:255})),i=n||jt(t)||Gt(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=qt(this._rgb);return t&&(t.a=wt(t.a)),t}set rgb(t){this._rgb=Kt(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${wt(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):void 0;var t}hexString(){return this._valid?At(this._rgb):void 0}hslString(){return this._valid?function(t){if(!t)return;const e=It(t),i=e[0],s=kt(e[1]),n=kt(e[2]);return t.a<255?`hsla(${i}, ${s}%, ${n}%, ${wt(t.a)})`:`hsl(${i}, ${s}%, ${n}%)`}(this._rgb):void 0}mix(t,e){if(t){const i=this.rgb,s=t.rgb;let n;const o=e===n?.5:e,a=2*o-1,r=i.a-s.a,l=((a*r==-1?a:(a+r)/(1+a*r))+1)/2;n=1-l,i.r=255&l*i.r+n*s.r+.5,i.g=255&l*i.g+n*s.g+.5,i.b=255&l*i.b+n*s.b+.5,i.a=o*i.a+(1-o)*s.a,this.rgb=i}return this}interpolate(t,e){return t&&(this._rgb=function(t,e,i){const s=Ut(wt(t.r)),n=Ut(wt(t.g)),o=Ut(wt(t.b));return{r:Mt(Yt(s+i*(Ut(wt(e.r))-s))),g:Mt(Yt(n+i*(Ut(wt(e.g))-n))),b:Mt(Yt(o+i*(Ut(wt(e.b))-o))),a:t.a+i*(e.a-t.a)}}(this._rgb,t._rgb,e)),this}clone(){return new Zt(this.rgb)}alpha(t){return this._rgb.a=Mt(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=_t(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return Xt(this._rgb,2,t),this}darken(t){return Xt(this._rgb,2,-t),this}saturate(t){return Xt(this._rgb,1,t),this}desaturate(t){return Xt(this._rgb,1,-t),this}rotate(t){return function(t,e){var i=It(t);i[0]=Vt(i[0]+e),i=Ft(i),t.r=i[0],t.g=i[1],t.b=i[2]}(this._rgb,t),this}}function Jt(t){if(t&&"object"==typeof t){const e=t.toString();return"[object CanvasPattern]"===e||"[object CanvasGradient]"===e}return!1}function Qt(t){return Jt(t)?t:new Zt(t)}function te(t){return Jt(t)?t:new Zt(t).saturate(.5).darken(.1).hexString()}const ee=["x","y","borderWidth","radius","tension"],ie=["color","borderColor","backgroundColor"];const se=new Map;function ne(t,e,i){return function(t,e){e=e||{};const i=t+JSON.stringify(e);let s=se.get(i);return s||(s=new Intl.NumberFormat(t,e),se.set(i,s)),s}(e,i).format(t)}const oe={values:t=>n(t)?t:""+t,numeric(t,e,i){if(0===t)return"0";const s=this.chart.options.locale;let n,o=t;if(i.length>1){const e=Math.max(Math.abs(i[0].value),Math.abs(i[i.length-1].value));(e<1e-4||e>1e15)&&(n="scientific"),o=function(t,e){let i=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;Math.abs(i)>=1&&t!==Math.floor(t)&&(i=t-Math.floor(t));return i}(t,i)}const a=z(Math.abs(o)),r=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),l={notation:n,minimumFractionDigits:r,maximumFractionDigits:r};return Object.assign(l,this.options.ticks.format),ne(t,s,l)},logarithmic(t,e,i){if(0===t)return"0";const s=i[e].significand||t/Math.pow(10,Math.floor(z(t)));return[1,2,3,5,10,15].includes(s)||e>.8*i.length?oe.numeric.call(this,t,e,i):""}};var ae={formatters:oe};const re=Object.create(null),le=Object.create(null);function he(t,e){if(!e)return t;const i=e.split(".");for(let e=0,s=i.length;e<s;++e){const s=i[e];t=t[s]||(t[s]=Object.create(null))}return t}function ce(t,e,i){return"string"==typeof e?x(he(t,e),i):x(he(t,""),e)}class de{constructor(t,e){this.animation=void 0,this.backgroundColor="rgba(0,0,0,0.1)",this.borderColor="rgba(0,0,0,0.1)",this.color="#666",this.datasets={},this.devicePixelRatio=t=>t.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>te(e.backgroundColor),this.hoverBorderColor=(t,e)=>te(e.borderColor),this.hoverColor=(t,e)=>te(e.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return ce(this,t,e)}get(t){return he(this,t)}describe(t,e){return ce(le,t,e)}override(t,e){return ce(re,t,e)}route(t,e,i,s){const n=he(this,t),a=he(this,i),r="_"+e;Object.defineProperties(n,{[r]:{value:n[e],writable:!0},[e]:{enumerable:!0,get(){const t=this[r],e=a[s];return o(t)?Object.assign({},e,t):l(t,e)},set(t){this[r]=t}}})}apply(t){t.forEach((t=>t(this)))}}var ue=new de({_scriptable:t=>!t.startsWith("on"),_indexable:t=>"events"!==t,hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[function(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>"onProgress"!==t&&"onComplete"!==t&&"fn"!==t}),t.set("animations",{colors:{type:"color",properties:ie},numbers:{type:"number",properties:ee}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>0|t}}}})},function(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})},function(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:ae.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&"callback"!==t&&"parser"!==t,_indexable:t=>"borderDash"!==t&&"tickBorderDash"!==t&&"dash"!==t}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:t=>"backdropPadding"!==t&&"callback"!==t,_indexable:t=>"backdropPadding"!==t})}]);function fe(){return"undefined"!=typeof window&&"undefined"!=typeof document}function ge(t){let e=t.parentNode;return e&&"[object ShadowRoot]"===e.toString()&&(e=e.host),e}function pe(t,e,i){let s;return"string"==typeof t?(s=parseInt(t,10),-1!==t.indexOf("%")&&(s=s/100*e.parentNode[i])):s=t,s}const me=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function xe(t,e){return me(t).getPropertyValue(e)}const be=["top","right","bottom","left"];function _e(t,e,i){const s={};i=i?"-"+i:"";for(let n=0;n<4;n++){const o=be[n];s[o]=parseFloat(t[e+"-"+o+i])||0}return s.width=s.left+s.right,s.height=s.top+s.bottom,s}const ye=(t,e,i)=>(t>0||e>0)&&(!i||!i.shadowRoot);function ve(t,e){if("native"in t)return t;const{canvas:i,currentDevicePixelRatio:s}=e,n=me(i),o="border-box"===n.boxSizing,a=_e(n,"padding"),r=_e(n,"border","width"),{x:l,y:h,box:c}=function(t,e){const i=t.touches,s=i&&i.length?i[0]:t,{offsetX:n,offsetY:o}=s;let a,r,l=!1;if(ye(n,o,t.target))a=n,r=o;else{const t=e.getBoundingClientRect();a=s.clientX-t.left,r=s.clientY-t.top,l=!0}return{x:a,y:r,box:l}}(t,i),d=a.left+(c&&r.left),u=a.top+(c&&r.top);let{width:f,height:g}=e;return o&&(f-=a.width+r.width,g-=a.height+r.height),{x:Math.round((l-d)/f*i.width/s),y:Math.round((h-u)/g*i.height/s)}}const Me=t=>Math.round(10*t)/10;function we(t,e,i,s){const n=me(t),o=_e(n,"margin"),a=pe(n.maxWidth,t,"clientWidth")||T,r=pe(n.maxHeight,t,"clientHeight")||T,l=function(t,e,i){let s,n;if(void 0===e||void 0===i){const o=t&&ge(t);if(o){const t=o.getBoundingClientRect(),a=me(o),r=_e(a,"border","width"),l=_e(a,"padding");e=t.width-l.width-r.width,i=t.height-l.height-r.height,s=pe(a.maxWidth,o,"clientWidth"),n=pe(a.maxHeight,o,"clientHeight")}else e=t.clientWidth,i=t.clientHeight}return{width:e,height:i,maxWidth:s||T,maxHeight:n||T}}(t,e,i);let{width:h,height:c}=l;if("content-box"===n.boxSizing){const t=_e(n,"border","width"),e=_e(n,"padding");h-=e.width+t.width,c-=e.height+t.height}h=Math.max(0,h-o.width),c=Math.max(0,s?h/s:c-o.height),h=Me(Math.min(h,a,l.maxWidth)),c=Me(Math.min(c,r,l.maxHeight)),h&&!c&&(c=Me(h/2));return(void 0!==e||void 0!==i)&&s&&l.height&&c>l.height&&(c=l.height,h=Me(Math.floor(c*s))),{width:h,height:c}}function ke(t,e,i){const s=e||1,n=Math.floor(t.height*s),o=Math.floor(t.width*s);t.height=Math.floor(t.height),t.width=Math.floor(t.width);const a=t.canvas;return a.style&&(i||!a.style.height&&!a.style.width)&&(a.style.height=`${t.height}px`,a.style.width=`${t.width}px`),(t.currentDevicePixelRatio!==s||a.height!==n||a.width!==o)&&(t.currentDevicePixelRatio=s,a.height=n,a.width=o,t.ctx.setTransform(s,0,0,s,0,0),!0)}const Se=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};fe()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch(t){}return t}();function Pe(t,e){const i=xe(t,e),s=i&&i.match(/^(\d+)(\.\d+)?px$/);return s?+s[1]:void 0}function De(t){return!t||s(t.size)||s(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function Ce(t,e,i,s,n){let o=e[n];return o||(o=e[n]=t.measureText(n).width,i.push(n)),o>s&&(s=o),s}function Oe(t,e,i,s){let o=(s=s||{}).data=s.data||{},a=s.garbageCollect=s.garbageCollect||[];s.font!==e&&(o=s.data={},a=s.garbageCollect=[],s.font=e),t.save(),t.font=e;let r=0;const l=i.length;let h,c,d,u,f;for(h=0;h<l;h++)if(u=i[h],null==u||n(u)){if(n(u))for(c=0,d=u.length;c<d;c++)f=u[c],null==f||n(f)||(r=Ce(t,o,a,r,f))}else r=Ce(t,o,a,r,u);t.restore();const g=a.length/2;if(g>i.length){for(h=0;h<g;h++)delete o[a[h]];a.splice(0,g)}return r}function Ae(t,e,i){const s=t.currentDevicePixelRatio,n=0!==i?Math.max(i/2,.5):0;return Math.round((e-n)*s)/s+n}function Te(t,e){(e||t)&&((e=e||t.getContext("2d")).save(),e.resetTransform(),e.clearRect(0,0,t.width,t.height),e.restore())}function Le(t,e,i,s){Ee(t,e,i,s,null)}function Ee(t,e,i,s,n){let o,a,r,l,h,c,d,u;const f=e.pointStyle,g=e.rotation,p=e.radius;let m=(g||0)*L;if(f&&"object"==typeof f&&(o=f.toString(),"[object HTMLImageElement]"===o||"[object HTMLCanvasElement]"===o))return t.save(),t.translate(i,s),t.rotate(m),t.drawImage(f,-f.width/2,-f.height/2,f.width,f.height),void t.restore();if(!(isNaN(p)||p<=0)){switch(t.beginPath(),f){default:n?t.ellipse(i,s,n/2,p,0,0,O):t.arc(i,s,p,0,O),t.closePath();break;case"triangle":c=n?n/2:p,t.moveTo(i+Math.sin(m)*c,s-Math.cos(m)*p),m+=I,t.lineTo(i+Math.sin(m)*c,s-Math.cos(m)*p),m+=I,t.lineTo(i+Math.sin(m)*c,s-Math.cos(m)*p),t.closePath();break;case"rectRounded":h=.516*p,l=p-h,a=Math.cos(m+R)*l,d=Math.cos(m+R)*(n?n/2-h:l),r=Math.sin(m+R)*l,u=Math.sin(m+R)*(n?n/2-h:l),t.arc(i-d,s-r,h,m-C,m-E),t.arc(i+u,s-a,h,m-E,m),t.arc(i+d,s+r,h,m,m+E),t.arc(i-u,s+a,h,m+E,m+C),t.closePath();break;case"rect":if(!g){l=Math.SQRT1_2*p,c=n?n/2:l,t.rect(i-c,s-l,2*c,2*l);break}m+=R;case"rectRot":d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+u,s-a),t.lineTo(i+d,s+r),t.lineTo(i-u,s+a),t.closePath();break;case"crossRot":m+=R;case"cross":d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+d,s+r),t.moveTo(i+u,s-a),t.lineTo(i-u,s+a);break;case"star":d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+d,s+r),t.moveTo(i+u,s-a),t.lineTo(i-u,s+a),m+=R,d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+d,s+r),t.moveTo(i+u,s-a),t.lineTo(i-u,s+a);break;case"line":a=n?n/2:Math.cos(m)*p,r=Math.sin(m)*p,t.moveTo(i-a,s-r),t.lineTo(i+a,s+r);break;case"dash":t.moveTo(i,s),t.lineTo(i+Math.cos(m)*(n?n/2:p),s+Math.sin(m)*p);break;case!1:t.closePath()}t.fill(),e.borderWidth>0&&t.stroke()}}function Re(t,e,i){return i=i||.5,!e||t&&t.x>e.left-i&&t.x<e.right+i&&t.y>e.top-i&&t.y<e.bottom+i}function Ie(t,e){t.save(),t.beginPath(),t.rect(e.left,e.top,e.right-e.left,e.bottom-e.top),t.clip()}function ze(t){t.restore()}function Fe(t,e,i,s,n){if(!e)return t.lineTo(i.x,i.y);if("middle"===n){const s=(e.x+i.x)/2;t.lineTo(s,e.y),t.lineTo(s,i.y)}else"after"===n!=!!s?t.lineTo(e.x,i.y):t.lineTo(i.x,e.y);t.lineTo(i.x,i.y)}function Ve(t,e,i,s){if(!e)return t.lineTo(i.x,i.y);t.bezierCurveTo(s?e.cp1x:e.cp2x,s?e.cp1y:e.cp2y,s?i.cp2x:i.cp1x,s?i.cp2y:i.cp1y,i.x,i.y)}function Be(t,e,i,s,n){if(n.strikethrough||n.underline){const o=t.measureText(s),a=e-o.actualBoundingBoxLeft,r=e+o.actualBoundingBoxRight,l=i-o.actualBoundingBoxAscent,h=i+o.actualBoundingBoxDescent,c=n.strikethrough?(l+h)/2:h;t.strokeStyle=t.fillStyle,t.beginPath(),t.lineWidth=n.decorationWidth||2,t.moveTo(a,c),t.lineTo(r,c),t.stroke()}}function We(t,e){const i=t.fillStyle;t.fillStyle=e.color,t.fillRect(e.left,e.top,e.width,e.height),t.fillStyle=i}function Ne(t,e,i,o,a,r={}){const l=n(e)?e:[e],h=r.strokeWidth>0&&""!==r.strokeColor;let c,d;for(t.save(),t.font=a.string,function(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),s(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}(t,r),c=0;c<l.length;++c)d=l[c],r.backdrop&&We(t,r.backdrop),h&&(r.strokeColor&&(t.strokeStyle=r.strokeColor),s(r.strokeWidth)||(t.lineWidth=r.strokeWidth),t.strokeText(d,i,o,r.maxWidth)),t.fillText(d,i,o,r.maxWidth),Be(t,i,o,d,r),o+=Number(a.lineHeight);t.restore()}function He(t,e){const{x:i,y:s,w:n,h:o,radius:a}=e;t.arc(i+a.topLeft,s+a.topLeft,a.topLeft,1.5*C,C,!0),t.lineTo(i,s+o-a.bottomLeft),t.arc(i+a.bottomLeft,s+o-a.bottomLeft,a.bottomLeft,C,E,!0),t.lineTo(i+n-a.bottomRight,s+o),t.arc(i+n-a.bottomRight,s+o-a.bottomRight,a.bottomRight,E,0,!0),t.lineTo(i+n,s+a.topRight),t.arc(i+n-a.topRight,s+a.topRight,a.topRight,0,-E,!0),t.lineTo(i+a.topLeft,s)}function je(t,e=[""],i,s,n=(()=>t[0])){const o=i||t;void 0===s&&(s=ti("_fallback",t));const a={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:o,_fallback:s,_getTarget:n,override:i=>je([i,...t],e,o,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete e._keys,delete t[0][i],!0),get:(i,s)=>qe(i,s,(()=>function(t,e,i,s){let n;for(const o of e)if(n=ti(Ue(o,t),i),void 0!==n)return Xe(t,n)?Je(i,s,t,n):n}(s,e,t,i))),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(t[0]),has:(t,e)=>ei(t).includes(e),ownKeys:t=>ei(t),set(t,e,i){const s=t._storage||(t._storage=n());return t[e]=s[e]=i,delete t._keys,!0}})}function $e(t,e,i,s){const a={_cacheable:!1,_proxy:t,_context:e,_subProxy:i,_stack:new Set,_descriptors:Ye(t,s),setContext:e=>$e(t,e,i,s),override:n=>$e(t.override(n),e,i,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete t[i],!0),get:(t,e,i)=>qe(t,e,(()=>function(t,e,i){const{_proxy:s,_context:a,_subProxy:r,_descriptors:l}=t;let h=s[e];S(h)&&l.isScriptable(e)&&(h=function(t,e,i,s){const{_proxy:n,_context:o,_subProxy:a,_stack:r}=i;if(r.has(t))throw new Error("Recursion detected: "+Array.from(r).join("->")+"->"+t);r.add(t);let l=e(o,a||s);r.delete(t),Xe(t,l)&&(l=Je(n._scopes,n,t,l));return l}(e,h,t,i));n(h)&&h.length&&(h=function(t,e,i,s){const{_proxy:n,_context:a,_subProxy:r,_descriptors:l}=i;if(void 0!==a.index&&s(t))return e[a.index%e.length];if(o(e[0])){const i=e,s=n._scopes.filter((t=>t!==i));e=[];for(const o of i){const i=Je(s,n,t,o);e.push($e(i,a,r&&r[t],l))}}return e}(e,h,t,l.isIndexable));Xe(e,h)&&(h=$e(h,a,r&&r[e],l));return h}(t,e,i))),getOwnPropertyDescriptor:(e,i)=>e._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i),getPrototypeOf:()=>Reflect.getPrototypeOf(t),has:(e,i)=>Reflect.has(t,i),ownKeys:()=>Reflect.ownKeys(t),set:(e,i,s)=>(t[i]=s,delete e[i],!0)})}function Ye(t,e={scriptable:!0,indexable:!0}){const{_scriptable:i=e.scriptable,_indexable:s=e.indexable,_allKeys:n=e.allKeys}=t;return{allKeys:n,scriptable:i,indexable:s,isScriptable:S(i)?i:()=>i,isIndexable:S(s)?s:()=>s}}const Ue=(t,e)=>t?t+w(e):e,Xe=(t,e)=>o(e)&&"adapters"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function qe(t,e,i){if(Object.prototype.hasOwnProperty.call(t,e)||"constructor"===e)return t[e];const s=i();return t[e]=s,s}function Ke(t,e,i){return S(t)?t(e,i):t}const Ge=(t,e)=>!0===t?e:"string"==typeof t?M(e,t):void 0;function Ze(t,e,i,s,n){for(const o of e){const e=Ge(i,o);if(e){t.add(e);const o=Ke(e._fallback,i,n);if(void 0!==o&&o!==i&&o!==s)return o}else if(!1===e&&void 0!==s&&i!==s)return null}return!1}function Je(t,e,i,s){const a=e._rootScopes,r=Ke(e._fallback,i,s),l=[...t,...a],h=new Set;h.add(s);let c=Qe(h,l,i,r||i,s);return null!==c&&((void 0===r||r===i||(c=Qe(h,l,r,c,s),null!==c))&&je(Array.from(h),[""],a,r,(()=>function(t,e,i){const s=t._getTarget();e in s||(s[e]={});const a=s[e];if(n(a)&&o(i))return i;return a||{}}(e,i,s))))}function Qe(t,e,i,s,n){for(;i;)i=Ze(t,e,i,s,n);return i}function ti(t,e){for(const i of e){if(!i)continue;const e=i[t];if(void 0!==e)return e}}function ei(t){let e=t._keys;return e||(e=t._keys=function(t){const e=new Set;for(const i of t)for(const t of Object.keys(i).filter((t=>!t.startsWith("_"))))e.add(t);return Array.from(e)}(t._scopes)),e}function ii(t,e,i,s){const{iScale:n}=t,{key:o="r"}=this._parsing,a=new Array(s);let r,l,h,c;for(r=0,l=s;r<l;++r)h=r+i,c=e[h],a[r]={r:n.parse(M(c,o),h)};return a}const si=Number.EPSILON||1e-14,ni=(t,e)=>e<t.length&&!t[e].skip&&t[e],oi=t=>"x"===t?"y":"x";function ai(t,e,i,s){const n=t.skip?e:t,o=e,a=i.skip?e:i,r=q(o,n),l=q(a,o);let h=r/(r+l),c=l/(r+l);h=isNaN(h)?0:h,c=isNaN(c)?0:c;const d=s*h,u=s*c;return{previous:{x:o.x-d*(a.x-n.x),y:o.y-d*(a.y-n.y)},next:{x:o.x+u*(a.x-n.x),y:o.y+u*(a.y-n.y)}}}function ri(t,e="x"){const i=oi(e),s=t.length,n=Array(s).fill(0),o=Array(s);let a,r,l,h=ni(t,0);for(a=0;a<s;++a)if(r=l,l=h,h=ni(t,a+1),l){if(h){const t=h[e]-l[e];n[a]=0!==t?(h[i]-l[i])/t:0}o[a]=r?h?F(n[a-1])!==F(n[a])?0:(n[a-1]+n[a])/2:n[a-1]:n[a]}!function(t,e,i){const s=t.length;let n,o,a,r,l,h=ni(t,0);for(let c=0;c<s-1;++c)l=h,h=ni(t,c+1),l&&h&&(V(e[c],0,si)?i[c]=i[c+1]=0:(n=i[c]/e[c],o=i[c+1]/e[c],r=Math.pow(n,2)+Math.pow(o,2),r<=9||(a=3/Math.sqrt(r),i[c]=n*a*e[c],i[c+1]=o*a*e[c])))}(t,n,o),function(t,e,i="x"){const s=oi(i),n=t.length;let o,a,r,l=ni(t,0);for(let h=0;h<n;++h){if(a=r,r=l,l=ni(t,h+1),!r)continue;const n=r[i],c=r[s];a&&(o=(n-a[i])/3,r[`cp1${i}`]=n-o,r[`cp1${s}`]=c-o*e[h]),l&&(o=(l[i]-n)/3,r[`cp2${i}`]=n+o,r[`cp2${s}`]=c+o*e[h])}}(t,o,e)}function li(t,e,i){return Math.max(Math.min(t,i),e)}function hi(t,e,i,s,n){let o,a,r,l;if(e.spanGaps&&(t=t.filter((t=>!t.skip))),"monotone"===e.cubicInterpolationMode)ri(t,n);else{let i=s?t[t.length-1]:t[0];for(o=0,a=t.length;o<a;++o)r=t[o],l=ai(i,r,t[Math.min(o+1,a-(s?0:1))%a],e.tension),r.cp1x=l.previous.x,r.cp1y=l.previous.y,r.cp2x=l.next.x,r.cp2y=l.next.y,i=r}e.capBezierPoints&&function(t,e){let i,s,n,o,a,r=Re(t[0],e);for(i=0,s=t.length;i<s;++i)a=o,o=r,r=i<s-1&&Re(t[i+1],e),o&&(n=t[i],a&&(n.cp1x=li(n.cp1x,e.left,e.right),n.cp1y=li(n.cp1y,e.top,e.bottom)),r&&(n.cp2x=li(n.cp2x,e.left,e.right),n.cp2y=li(n.cp2y,e.top,e.bottom)))}(t,i)}const ci=t=>0===t||1===t,di=(t,e,i)=>-Math.pow(2,10*(t-=1))*Math.sin((t-e)*O/i),ui=(t,e,i)=>Math.pow(2,-10*t)*Math.sin((t-e)*O/i)+1,fi={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*E),easeOutSine:t=>Math.sin(t*E),easeInOutSine:t=>-.5*(Math.cos(C*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>ci(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>ci(t)?t:di(t,.075,.3),easeOutElastic:t=>ci(t)?t:ui(t,.075,.3),easeInOutElastic(t){const e=.1125;return ci(t)?t:t<.5?.5*di(2*t,e,.45):.5+.5*ui(2*t-1,e,.45)},easeInBack(t){const e=1.70158;return t*t*((e+1)*t-e)},easeOutBack(t){const e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-fi.easeOutBounce(1-t),easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},easeInOutBounce:t=>t<.5?.5*fi.easeInBounce(2*t):.5*fi.easeOutBounce(2*t-1)+.5};function gi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:t.y+i*(e.y-t.y)}}function pi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:"middle"===s?i<.5?t.y:e.y:"after"===s?i<1?t.y:e.y:i>0?e.y:t.y}}function mi(t,e,i,s){const n={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},a=gi(t,n,i),r=gi(n,o,i),l=gi(o,e,i),h=gi(a,r,i),c=gi(r,l,i);return gi(h,c,i)}const xi=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,bi=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function _i(t,e){const i=(""+t).match(xi);if(!i||"normal"===i[1])return 1.2*e;switch(t=+i[2],i[3]){case"px":return t;case"%":t/=100}return e*t}const yi=t=>+t||0;function vi(t,e){const i={},s=o(e),n=s?Object.keys(e):e,a=o(t)?s?i=>l(t[i],t[e[i]]):e=>t[e]:()=>t;for(const t of n)i[t]=yi(a(t));return i}function Mi(t){return vi(t,{top:"y",right:"x",bottom:"y",left:"x"})}function wi(t){return vi(t,["topLeft","topRight","bottomLeft","bottomRight"])}function ki(t){const e=Mi(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function Si(t,e){t=t||{},e=e||ue.font;let i=l(t.size,e.size);"string"==typeof i&&(i=parseInt(i,10));let s=l(t.style,e.style);s&&!(""+s).match(bi)&&(console.warn('Invalid font style specified: "'+s+'"'),s=void 0);const n={family:l(t.family,e.family),lineHeight:_i(l(t.lineHeight,e.lineHeight),i),size:i,style:s,weight:l(t.weight,e.weight),string:""};return n.string=De(n),n}function Pi(t,e,i,s){let o,a,r,l=!0;for(o=0,a=t.length;o<a;++o)if(r=t[o],void 0!==r&&(void 0!==e&&"function"==typeof r&&(r=r(e),l=!1),void 0!==i&&n(r)&&(r=r[i%r.length],l=!1),void 0!==r))return s&&!l&&(s.cacheable=!1),r}function Di(t,e,i){const{min:s,max:n}=t,o=c(e,(n-s)/2),a=(t,e)=>i&&0===t?0:t+e;return{min:a(s,-Math.abs(o)),max:a(n,o)}}function Ci(t,e){return Object.assign(Object.create(t),e)}function Oi(t,e,i){return t?function(t,e){return{x:i=>t+t+e-i,setWidth(t){e=t},textAlign:t=>"center"===t?t:"right"===t?"left":"right",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}}(e,i):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t}}function Ai(t,e){let i,s;"ltr"!==e&&"rtl"!==e||(i=t.canvas.style,s=[i.getPropertyValue("direction"),i.getPropertyPriority("direction")],i.setProperty("direction",e,"important"),t.prevTextDirection=s)}function Ti(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Li(t){return"angle"===t?{between:Z,compare:K,normalize:G}:{between:tt,compare:(t,e)=>t-e,normalize:t=>t}}function Ei({start:t,end:e,count:i,loop:s,style:n}){return{start:t%i,end:e%i,loop:s&&(e-t+1)%i==0,style:n}}function Ri(t,e,i){if(!i)return[t];const{property:s,start:n,end:o}=i,a=e.length,{compare:r,between:l,normalize:h}=Li(s),{start:c,end:d,loop:u,style:f}=function(t,e,i){const{property:s,start:n,end:o}=i,{between:a,normalize:r}=Li(s),l=e.length;let h,c,{start:d,end:u,loop:f}=t;if(f){for(d+=l,u+=l,h=0,c=l;h<c&&a(r(e[d%l][s]),n,o);++h)d--,u--;d%=l,u%=l}return u<d&&(u+=l),{start:d,end:u,loop:f,style:t.style}}(t,e,i),g=[];let p,m,x,b=!1,_=null;const y=()=>b||l(n,x,p)&&0!==r(n,x),v=()=>!b||0===r(o,p)||l(o,x,p);for(let t=c,i=c;t<=d;++t)m=e[t%a],m.skip||(p=h(m[s]),p!==x&&(b=l(p,n,o),null===_&&y()&&(_=0===r(p,n)?t:i),null!==_&&v()&&(g.push(Ei({start:_,end:t,loop:u,count:a,style:f})),_=null),i=t,x=p));return null!==_&&g.push(Ei({start:_,end:d,loop:u,count:a,style:f})),g}function Ii(t,e){const i=[],s=t.segments;for(let n=0;n<s.length;n++){const o=Ri(s[n],t.points,e);o.length&&i.push(...o)}return i}function zi(t,e){const i=t.points,s=t.options.spanGaps,n=i.length;if(!n)return[];const o=!!t._loop,{start:a,end:r}=function(t,e,i,s){let n=0,o=e-1;if(i&&!s)for(;n<e&&!t[n].skip;)n++;for(;n<e&&t[n].skip;)n++;for(n%=e,i&&(o+=n);o>n&&t[o%e].skip;)o--;return o%=e,{start:n,end:o}}(i,n,o,s);if(!0===s)return Fi(t,[{start:a,end:r,loop:o}],i,e);return Fi(t,function(t,e,i,s){const n=t.length,o=[];let a,r=e,l=t[e];for(a=e+1;a<=i;++a){const i=t[a%n];i.skip||i.stop?l.skip||(s=!1,o.push({start:e%n,end:(a-1)%n,loop:s}),e=r=i.stop?a:null):(r=a,l.skip&&(e=a)),l=i}return null!==r&&o.push({start:e%n,end:r%n,loop:s}),o}(i,a,r<a?r+n:r,!!t._fullLoop&&0===a&&r===n-1),i,e)}function Fi(t,e,i,s){return s&&s.setContext&&i?function(t,e,i,s){const n=t._chart.getContext(),o=Vi(t.options),{_datasetIndex:a,options:{spanGaps:r}}=t,l=i.length,h=[];let c=o,d=e[0].start,u=d;function f(t,e,s,n){const o=r?-1:1;if(t!==e){for(t+=l;i[t%l].skip;)t-=o;for(;i[e%l].skip;)e+=o;t%l!=e%l&&(h.push({start:t%l,end:e%l,loop:s,style:n}),c=n,d=e%l)}}for(const t of e){d=r?d:t.start;let e,o=i[d%l];for(u=d+1;u<=t.end;u++){const r=i[u%l];e=Vi(s.setContext(Ci(n,{type:"segment",p0:o,p1:r,p0DataIndex:(u-1)%l,p1DataIndex:u%l,datasetIndex:a}))),Bi(e,c)&&f(d,u-1,t.loop,c),o=r,c=e}d<u-1&&f(d,u-1,t.loop,c)}return h}(t,e,i,s):e}function Vi(t){return{backgroundColor:t.backgroundColor,borderCapStyle:t.borderCapStyle,borderDash:t.borderDash,borderDashOffset:t.borderDashOffset,borderJoinStyle:t.borderJoinStyle,borderWidth:t.borderWidth,borderColor:t.borderColor}}function Bi(t,e){if(!e)return!1;const i=[],s=function(t,e){return Jt(e)?(i.includes(e)||i.push(e),i.indexOf(e)):e};return JSON.stringify(t,s)!==JSON.stringify(e,s)}function Wi(t,e,i){return t.options.clip?t[i]:e[i]}function Ni(t,e){const i=e._clip;if(i.disabled)return!1;const s=function(t,e){const{xScale:i,yScale:s}=t;return i&&s?{left:Wi(i,e,"left"),right:Wi(i,e,"right"),top:Wi(s,e,"top"),bottom:Wi(s,e,"bottom")}:e}(e,t.chartArea);return{left:!1===i.left?0:s.left-(!0===i.left?0:i.left),right:!1===i.right?t.width:s.right+(!0===i.right?0:i.right),top:!1===i.top?0:s.top-(!0===i.top?0:i.top),bottom:!1===i.bottom?t.height:s.bottom+(!0===i.bottom?0:i.bottom)}}var Hi=Object.freeze({__proto__:null,HALF_PI:E,INFINITY:T,PI:C,PITAU:A,QUARTER_PI:R,RAD_PER_DEG:L,TAU:O,TWO_THIRDS_PI:I,_addGrace:Di,_alignPixel:Ae,_alignStartEnd:ft,_angleBetween:Z,_angleDiff:K,_arrayUnique:lt,_attachContext:$e,_bezierCurveTo:Ve,_bezierInterpolation:mi,_boundSegment:Ri,_boundSegments:Ii,_capitalize:w,_computeSegments:zi,_createResolver:je,_decimalPlaces:U,_deprecated:function(t,e,i,s){void 0!==e&&console.warn(t+': "'+i+'" is deprecated. Please use "'+s+'" instead')},_descriptors:Ye,_elementsEqual:f,_factorize:W,_filterBetween:nt,_getParentNode:ge,_getStartAndCountOfVisiblePoints:pt,_int16Range:Q,_isBetween:tt,_isClickEvent:D,_isDomSupported:fe,_isPointInArea:Re,_limitValue:J,_longestText:Oe,_lookup:et,_lookupByKey:it,_measureText:Ce,_merger:m,_mergerIf:_,_normalizeAngle:G,_parseObjectDataRadialScale:ii,_pointInLine:gi,_readValueToProps:vi,_rlookupByKey:st,_scaleRangesChanged:mt,_setMinAndMaxByKey:j,_splitKey:v,_steppedInterpolation:pi,_steppedLineTo:Fe,_textX:gt,_toLeftRightCenter:ut,_updateBezierControlPoints:hi,addRoundedRectPath:He,almostEquals:V,almostWhole:H,callback:d,clearCanvas:Te,clipArea:Ie,clone:g,color:Qt,createContext:Ci,debounce:dt,defined:k,distanceBetweenPoints:q,drawPoint:Le,drawPointLegend:Ee,each:u,easingEffects:fi,finiteOrDefault:r,fontString:function(t,e,i){return e+" "+t+"px "+i},formatNumber:ne,getAngleFromPoint:X,getDatasetClipArea:Ni,getHoverColor:te,getMaximumSize:we,getRelativePosition:ve,getRtlAdapter:Oi,getStyle:xe,isArray:n,isFinite:a,isFunction:S,isNullOrUndef:s,isNumber:N,isObject:o,isPatternOrGradient:Jt,listenArrayEvents:at,log10:z,merge:x,mergeIf:b,niceNum:B,noop:e,overrideTextDirection:Ai,readUsedSize:Pe,renderText:Ne,requestAnimFrame:ht,resolve:Pi,resolveObjectKey:M,restoreTextDirection:Ti,retinaScale:ke,setsEqual:P,sign:F,splineCurve:ai,splineCurveMonotone:ri,supportsEventListenerOptions:Se,throttled:ct,toDegrees:Y,toDimension:c,toFont:Si,toFontString:De,toLineHeight:_i,toPadding:ki,toPercentage:h,toRadians:$,toTRBL:Mi,toTRBLCorners:wi,uid:i,unclipArea:ze,unlistenArrayEvents:rt,valueOrDefault:l});function ji(t,e,i,n){const{controller:o,data:a,_sorted:r}=t,l=o._cachedMeta.iScale,h=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null;if(l&&e===l.axis&&"r"!==e&&r&&a.length){const r=l._reversePixels?st:it;if(!n){const n=r(a,e,i);if(h){const{vScale:e}=o._cachedMeta,{_parsed:i}=t,a=i.slice(0,n.lo+1).reverse().findIndex((t=>!s(t[e.axis])));n.lo-=Math.max(0,a);const r=i.slice(n.hi).findIndex((t=>!s(t[e.axis])));n.hi+=Math.max(0,r)}return n}if(o._sharedOptions){const t=a[0],s="function"==typeof t.getRange&&t.getRange(e);if(s){const t=r(a,e,i-s),n=r(a,e,i+s);return{lo:t.lo,hi:n.hi}}}}return{lo:0,hi:a.length-1}}function $i(t,e,i,s,n){const o=t.getSortedVisibleDatasetMetas(),a=i[e];for(let t=0,i=o.length;t<i;++t){const{index:i,data:r}=o[t],{lo:l,hi:h}=ji(o[t],e,a,n);for(let t=l;t<=h;++t){const e=r[t];e.skip||s(e,i,t)}}}function Yi(t,e,i,s,n){const o=[];if(!n&&!t.isPointInArea(e))return o;return $i(t,i,e,(function(i,a,r){(n||Re(i,t.chartArea,0))&&i.inRange(e.x,e.y,s)&&o.push({element:i,datasetIndex:a,index:r})}),!0),o}function Ui(t,e,i,s,n,o){let a=[];const r=function(t){const e=-1!==t.indexOf("x"),i=-1!==t.indexOf("y");return function(t,s){const n=e?Math.abs(t.x-s.x):0,o=i?Math.abs(t.y-s.y):0;return Math.sqrt(Math.pow(n,2)+Math.pow(o,2))}}(i);let l=Number.POSITIVE_INFINITY;return $i(t,i,e,(function(i,h,c){const d=i.inRange(e.x,e.y,n);if(s&&!d)return;const u=i.getCenterPoint(n);if(!(!!o||t.isPointInArea(u))&&!d)return;const f=r(e,u);f<l?(a=[{element:i,datasetIndex:h,index:c}],l=f):f===l&&a.push({element:i,datasetIndex:h,index:c})})),a}function Xi(t,e,i,s,n,o){return o||t.isPointInArea(e)?"r"!==i||s?Ui(t,e,i,s,n,o):function(t,e,i,s){let n=[];return $i(t,i,e,(function(t,i,o){const{startAngle:a,endAngle:r}=t.getProps(["startAngle","endAngle"],s),{angle:l}=X(t,{x:e.x,y:e.y});Z(l,a,r)&&n.push({element:t,datasetIndex:i,index:o})})),n}(t,e,i,n):[]}function qi(t,e,i,s,n){const o=[],a="x"===i?"inXRange":"inYRange";let r=!1;return $i(t,i,e,((t,s,l)=>{t[a]&&t[a](e[i],n)&&(o.push({element:t,datasetIndex:s,index:l}),r=r||t.inRange(e.x,e.y,n))})),s&&!r?[]:o}var Ki={evaluateInteractionItems:$i,modes:{index(t,e,i,s){const n=ve(e,t),o=i.axis||"x",a=i.includeInvisible||!1,r=i.intersect?Yi(t,n,o,s,a):Xi(t,n,o,!1,s,a),l=[];return r.length?(t.getSortedVisibleDatasetMetas().forEach((t=>{const e=r[0].index,i=t.data[e];i&&!i.skip&&l.push({element:i,datasetIndex:t.index,index:e})})),l):[]},dataset(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;let r=i.intersect?Yi(t,n,o,s,a):Xi(t,n,o,!1,s,a);if(r.length>0){const e=r[0].datasetIndex,i=t.getDatasetMeta(e).data;r=[];for(let t=0;t<i.length;++t)r.push({element:i[t],datasetIndex:e,index:t})}return r},point:(t,e,i,s)=>Yi(t,ve(e,t),i.axis||"xy",s,i.includeInvisible||!1),nearest(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;return Xi(t,n,o,i.intersect,s,a)},x:(t,e,i,s)=>qi(t,ve(e,t),"x",i.intersect,s),y:(t,e,i,s)=>qi(t,ve(e,t),"y",i.intersect,s)}};const Gi=["left","top","right","bottom"];function Zi(t,e){return t.filter((t=>t.pos===e))}function Ji(t,e){return t.filter((t=>-1===Gi.indexOf(t.pos)&&t.box.axis===e))}function Qi(t,e){return t.sort(((t,i)=>{const s=e?i:t,n=e?t:i;return s.weight===n.weight?s.index-n.index:s.weight-n.weight}))}function ts(t,e){const i=function(t){const e={};for(const i of t){const{stack:t,pos:s,stackWeight:n}=i;if(!t||!Gi.includes(s))continue;const o=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});o.count++,o.weight+=n}return e}(t),{vBoxMaxWidth:s,hBoxMaxHeight:n}=e;let o,a,r;for(o=0,a=t.length;o<a;++o){r=t[o];const{fullSize:a}=r.box,l=i[r.stack],h=l&&r.stackWeight/l.weight;r.horizontal?(r.width=h?h*s:a&&e.availableWidth,r.height=n):(r.width=s,r.height=h?h*n:a&&e.availableHeight)}return i}function es(t,e,i,s){return Math.max(t[i],e[i])+Math.max(t[s],e[s])}function is(t,e){t.top=Math.max(t.top,e.top),t.left=Math.max(t.left,e.left),t.bottom=Math.max(t.bottom,e.bottom),t.right=Math.max(t.right,e.right)}function ss(t,e,i,s){const{pos:n,box:a}=i,r=t.maxPadding;if(!o(n)){i.size&&(t[n]-=i.size);const e=s[i.stack]||{size:0,count:1};e.size=Math.max(e.size,i.horizontal?a.height:a.width),i.size=e.size/e.count,t[n]+=i.size}a.getPadding&&is(r,a.getPadding());const l=Math.max(0,e.outerWidth-es(r,t,"left","right")),h=Math.max(0,e.outerHeight-es(r,t,"top","bottom")),c=l!==t.w,d=h!==t.h;return t.w=l,t.h=h,i.horizontal?{same:c,other:d}:{same:d,other:c}}function ns(t,e){const i=e.maxPadding;function s(t){const s={left:0,top:0,right:0,bottom:0};return t.forEach((t=>{s[t]=Math.max(e[t],i[t])})),s}return s(t?["left","right"]:["top","bottom"])}function os(t,e,i,s){const n=[];let o,a,r,l,h,c;for(o=0,a=t.length,h=0;o<a;++o){r=t[o],l=r.box,l.update(r.width||e.w,r.height||e.h,ns(r.horizontal,e));const{same:a,other:d}=ss(e,i,r,s);h|=a&&n.length,c=c||d,l.fullSize||n.push(r)}return h&&os(n,e,i,s)||c}function as(t,e,i,s,n){t.top=i,t.left=e,t.right=e+s,t.bottom=i+n,t.width=s,t.height=n}function rs(t,e,i,s){const n=i.padding;let{x:o,y:a}=e;for(const r of t){const t=r.box,l=s[r.stack]||{count:1,placed:0,weight:1},h=r.stackWeight/l.weight||1;if(r.horizontal){const s=e.w*h,o=l.size||t.height;k(l.start)&&(a=l.start),t.fullSize?as(t,n.left,a,i.outerWidth-n.right-n.left,o):as(t,e.left+l.placed,a,s,o),l.start=a,l.placed+=s,a=t.bottom}else{const s=e.h*h,a=l.size||t.width;k(l.start)&&(o=l.start),t.fullSize?as(t,o,n.top,a,i.outerHeight-n.bottom-n.top):as(t,o,e.top+l.placed,a,s),l.start=o,l.placed+=s,o=t.right}}e.x=o,e.y=a}var ls={addBox(t,e){t.boxes||(t.boxes=[]),e.fullSize=e.fullSize||!1,e.position=e.position||"top",e.weight=e.weight||0,e._layers=e._layers||function(){return[{z:0,draw(t){e.draw(t)}}]},t.boxes.push(e)},removeBox(t,e){const i=t.boxes?t.boxes.indexOf(e):-1;-1!==i&&t.boxes.splice(i,1)},configure(t,e,i){e.fullSize=i.fullSize,e.position=i.position,e.weight=i.weight},update(t,e,i,s){if(!t)return;const n=ki(t.options.layout.padding),o=Math.max(e-n.width,0),a=Math.max(i-n.height,0),r=function(t){const e=function(t){const e=[];let i,s,n,o,a,r;for(i=0,s=(t||[]).length;i<s;++i)n=t[i],({position:o,options:{stack:a,stackWeight:r=1}}=n),e.push({index:i,box:n,pos:o,horizontal:n.isHorizontal(),weight:n.weight,stack:a&&o+a,stackWeight:r});return e}(t),i=Qi(e.filter((t=>t.box.fullSize)),!0),s=Qi(Zi(e,"left"),!0),n=Qi(Zi(e,"right")),o=Qi(Zi(e,"top"),!0),a=Qi(Zi(e,"bottom")),r=Ji(e,"x"),l=Ji(e,"y");return{fullSize:i,leftAndTop:s.concat(o),rightAndBottom:n.concat(l).concat(a).concat(r),chartArea:Zi(e,"chartArea"),vertical:s.concat(n).concat(l),horizontal:o.concat(a).concat(r)}}(t.boxes),l=r.vertical,h=r.horizontal;u(t.boxes,(t=>{"function"==typeof t.beforeLayout&&t.beforeLayout()}));const c=l.reduce(((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1),0)||1,d=Object.freeze({outerWidth:e,outerHeight:i,padding:n,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/c,hBoxMaxHeight:a/2}),f=Object.assign({},n);is(f,ki(s));const g=Object.assign({maxPadding:f,w:o,h:a,x:n.left,y:n.top},n),p=ts(l.concat(h),d);os(r.fullSize,g,d,p),os(l,g,d,p),os(h,g,d,p)&&os(l,g,d,p),function(t){const e=t.maxPadding;function i(i){const s=Math.max(e[i]-t[i],0);return t[i]+=s,s}t.y+=i("top"),t.x+=i("left"),i("right"),i("bottom")}(g),rs(r.leftAndTop,g,d,p),g.x+=g.w,g.y+=g.h,rs(r.rightAndBottom,g,d,p),t.chartArea={left:g.left,top:g.top,right:g.left+g.w,bottom:g.top+g.h,height:g.h,width:g.w},u(r.chartArea,(e=>{const i=e.box;Object.assign(i,t.chartArea),i.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})}))}};class hs{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,s){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,s?Math.floor(e/s):i)}}isAttached(t){return!0}updateConfig(t){}}class cs extends hs{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const ds="$chartjs",us={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},fs=t=>null===t||""===t;const gs=!!Se&&{passive:!0};function ps(t,e,i){t&&t.canvas&&t.canvas.removeEventListener(e,i,gs)}function ms(t,e){for(const i of t)if(i===e||i.contains(e))return!0}function xs(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||ms(i.addedNodes,s),e=e&&!ms(i.removedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}function bs(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||ms(i.removedNodes,s),e=e&&!ms(i.addedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}const _s=new Map;let ys=0;function vs(){const t=window.devicePixelRatio;t!==ys&&(ys=t,_s.forEach(((e,i)=>{i.currentDevicePixelRatio!==t&&e()})))}function Ms(t,e,i){const s=t.canvas,n=s&&ge(s);if(!n)return;const o=ct(((t,e)=>{const s=n.clientWidth;i(t,e),s<n.clientWidth&&i()}),window),a=new ResizeObserver((t=>{const e=t[0],i=e.contentRect.width,s=e.contentRect.height;0===i&&0===s||o(i,s)}));return a.observe(n),function(t,e){_s.size||window.addEventListener("resize",vs),_s.set(t,e)}(t,o),a}function ws(t,e,i){i&&i.disconnect(),"resize"===e&&function(t){_s.delete(t),_s.size||window.removeEventListener("resize",vs)}(t)}function ks(t,e,i){const s=t.canvas,n=ct((e=>{null!==t.ctx&&i(function(t,e){const i=us[t.type]||t.type,{x:s,y:n}=ve(t,e);return{type:i,chart:e,native:t,x:void 0!==s?s:null,y:void 0!==n?n:null}}(e,t))}),t);return function(t,e,i){t&&t.addEventListener(e,i,gs)}(s,e,n),n}class Ss extends hs{acquireContext(t,e){const i=t&&t.getContext&&t.getContext("2d");return i&&i.canvas===t?(function(t,e){const i=t.style,s=t.getAttribute("height"),n=t.getAttribute("width");if(t[ds]={initial:{height:s,width:n,style:{display:i.display,height:i.height,width:i.width}}},i.display=i.display||"block",i.boxSizing=i.boxSizing||"border-box",fs(n)){const e=Pe(t,"width");void 0!==e&&(t.width=e)}if(fs(s))if(""===t.style.height)t.height=t.width/(e||2);else{const e=Pe(t,"height");void 0!==e&&(t.height=e)}}(t,e),i):null}releaseContext(t){const e=t.canvas;if(!e[ds])return!1;const i=e[ds].initial;["height","width"].forEach((t=>{const n=i[t];s(n)?e.removeAttribute(t):e.setAttribute(t,n)}));const n=i.style||{};return Object.keys(n).forEach((t=>{e.style[t]=n[t]})),e.width=e.width,delete e[ds],!0}addEventListener(t,e,i){this.removeEventListener(t,e);const s=t.$proxies||(t.$proxies={}),n={attach:xs,detach:bs,resize:Ms}[e]||ks;s[e]=n(t,e,i)}removeEventListener(t,e){const i=t.$proxies||(t.$proxies={}),s=i[e];if(!s)return;({attach:ws,detach:ws,resize:ws}[e]||ps)(t,e,s),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,s){return we(t,e,i,s)}isAttached(t){const e=t&&ge(t);return!(!e||!e.isConnected)}}function Ps(t){return!fe()||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?cs:Ss}var Ds=Object.freeze({__proto__:null,BasePlatform:hs,BasicPlatform:cs,DomPlatform:Ss,_detectPlatform:Ps});const Cs="transparent",Os={boolean:(t,e,i)=>i>.5?e:t,color(t,e,i){const s=Qt(t||Cs),n=s.valid&&Qt(e||Cs);return n&&n.valid?n.mix(s,i).hexString():e},number:(t,e,i)=>t+(e-t)*i};class As{constructor(t,e,i,s){const n=e[i];s=Pi([t.to,s,n,t.from]);const o=Pi([t.from,n,s]);this._active=!0,this._fn=t.fn||Os[t.type||typeof o],this._easing=fi[t.easing]||fi.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=o,this._to=s,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);const s=this._target[this._prop],n=i-this._start,o=this._duration-n;this._start=i,this._duration=Math.floor(Math.max(o,t.duration)),this._total+=n,this._loop=!!t.loop,this._to=Pi([t.to,e,s,t.from]),this._from=Pi([t.from,s,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const e=t-this._start,i=this._duration,s=this._prop,n=this._from,o=this._loop,a=this._to;let r;if(this._active=n!==a&&(o||e<i),!this._active)return this._target[s]=a,void this._notify(!0);e<0?this._target[s]=n:(r=e/i%2,r=o&&r>1?2-r:r,r=this._easing(Math.min(1,Math.max(0,r))),this._target[s]=this._fn(n,a,r))}wait(){const t=this._promises||(this._promises=[]);return new Promise(((e,i)=>{t.push({res:e,rej:i})}))}_notify(t){const e=t?"res":"rej",i=this._promises||[];for(let t=0;t<i.length;t++)i[t][e]()}}class Ts{constructor(t,e){this._chart=t,this._properties=new Map,this.configure(e)}configure(t){if(!o(t))return;const e=Object.keys(ue.animation),i=this._properties;Object.getOwnPropertyNames(t).forEach((s=>{const a=t[s];if(!o(a))return;const r={};for(const t of e)r[t]=a[t];(n(a.properties)&&a.properties||[s]).forEach((t=>{t!==s&&i.has(t)||i.set(t,r)}))}))}_animateOptions(t,e){const i=e.options,s=function(t,e){if(!e)return;let i=t.options;if(!i)return void(t.options=e);i.$shared&&(t.options=i=Object.assign({},i,{$shared:!1,$animations:{}}));return i}(t,i);if(!s)return[];const n=this._createAnimations(s,i);return i.$shared&&function(t,e){const i=[],s=Object.keys(e);for(let e=0;e<s.length;e++){const n=t[s[e]];n&&n.active()&&i.push(n.wait())}return Promise.all(i)}(t.options.$animations,i).then((()=>{t.options=i}),(()=>{})),n}_createAnimations(t,e){const i=this._properties,s=[],n=t.$animations||(t.$animations={}),o=Object.keys(e),a=Date.now();let r;for(r=o.length-1;r>=0;--r){const l=o[r];if("$"===l.charAt(0))continue;if("options"===l){s.push(...this._animateOptions(t,e));continue}const h=e[l];let c=n[l];const d=i.get(l);if(c){if(d&&c.active()){c.update(d,h,a);continue}c.cancel()}d&&d.duration?(n[l]=c=new As(d,t,l,h),s.push(c)):t[l]=h}return s}update(t,e){if(0===this._properties.size)return void Object.assign(t,e);const i=this._createAnimations(t,e);return i.length?(bt.add(this._chart,i),!0):void 0}}function Ls(t,e){const i=t&&t.options||{},s=i.reverse,n=void 0===i.min?e:0,o=void 0===i.max?e:0;return{start:s?o:n,end:s?n:o}}function Es(t,e){const i=[],s=t._getSortedDatasetMetas(e);let n,o;for(n=0,o=s.length;n<o;++n)i.push(s[n].index);return i}function Rs(t,e,i,s={}){const n=t.keys,o="single"===s.mode;let r,l,h,c;if(null===e)return;let d=!1;for(r=0,l=n.length;r<l;++r){if(h=+n[r],h===i){if(d=!0,s.all)continue;break}c=t.values[h],a(c)&&(o||0===e||F(e)===F(c))&&(e+=c)}return d||s.all?e:0}function Is(t,e){const i=t&&t.options.stacked;return i||void 0===i&&void 0!==e.stack}function zs(t,e,i){const s=t[e]||(t[e]={});return s[i]||(s[i]={})}function Fs(t,e,i,s){for(const n of e.getMatchingVisibleMetas(s).reverse()){const e=t[n.index];if(i&&e>0||!i&&e<0)return n.index}return null}function Vs(t,e){const{chart:i,_cachedMeta:s}=t,n=i._stacks||(i._stacks={}),{iScale:o,vScale:a,index:r}=s,l=o.axis,h=a.axis,c=function(t,e,i){return`${t.id}.${e.id}.${i.stack||i.type}`}(o,a,s),d=e.length;let u;for(let t=0;t<d;++t){const i=e[t],{[l]:o,[h]:d}=i;u=(i._stacks||(i._stacks={}))[h]=zs(n,c,o),u[r]=d,u._top=Fs(u,a,!0,s.type),u._bottom=Fs(u,a,!1,s.type);(u._visualValues||(u._visualValues={}))[r]=d}}function Bs(t,e){const i=t.scales;return Object.keys(i).filter((t=>i[t].axis===e)).shift()}function Ws(t,e){const i=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const t of e){const e=t._stacks;if(!e||void 0===e[s]||void 0===e[s][i])return;delete e[s][i],void 0!==e[s]._visualValues&&void 0!==e[s]._visualValues[i]&&delete e[s]._visualValues[i]}}}const Ns=t=>"reset"===t||"none"===t,Hs=(t,e)=>e?t:Object.assign({},t);class js{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=Is(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Ws(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,i=this.getDataset(),s=(t,e,i,s)=>"x"===t?e:"r"===t?s:i,n=e.xAxisID=l(i.xAxisID,Bs(t,"x")),o=e.yAxisID=l(i.yAxisID,Bs(t,"y")),a=e.rAxisID=l(i.rAxisID,Bs(t,"r")),r=e.indexAxis,h=e.iAxisID=s(r,n,o,a),c=e.vAxisID=s(r,o,n,a);e.xScale=this.getScaleForId(n),e.yScale=this.getScaleForId(o),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(h),e.vScale=this.getScaleForId(c)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){const t=this._cachedMeta;this._data&&rt(this._data,this),t._stacked&&Ws(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(o(e)){const t=this._cachedMeta;this._data=function(t,e){const{iScale:i,vScale:s}=e,n="x"===i.axis?"x":"y",o="x"===s.axis?"x":"y",a=Object.keys(t),r=new Array(a.length);let l,h,c;for(l=0,h=a.length;l<h;++l)c=a[l],r[l]={[n]:c,[o]:t[c]};return r}(e,t)}else if(i!==e){if(i){rt(i,this);const t=this._cachedMeta;Ws(t),t._parsed=[]}e&&Object.isExtensible(e)&&at(e,this),this._syncList=[],this._data=e}}addElements(){const t=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(t.dataset=new this.datasetElementType)}buildOrUpdateElements(t){const e=this._cachedMeta,i=this.getDataset();let s=!1;this._dataCheck();const n=e._stacked;e._stacked=Is(e.vScale,e),e.stack!==i.stack&&(s=!0,Ws(e),e.stack=i.stack),this._resyncElements(t),(s||n!==e._stacked)&&(Vs(this,e._parsed),e._stacked=Is(e.vScale,e))}configure(){const t=this.chart.config,e=t.datasetScopeKeys(this._type),i=t.getOptionScopes(this.getDataset(),e,!0);this.options=t.createResolver(i,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(t,e){const{_cachedMeta:i,_data:s}=this,{iScale:a,_stacked:r}=i,l=a.axis;let h,c,d,u=0===t&&e===s.length||i._sorted,f=t>0&&i._parsed[t-1];if(!1===this._parsing)i._parsed=s,i._sorted=!0,d=s;else{d=n(s[t])?this.parseArrayData(i,s,t,e):o(s[t])?this.parseObjectData(i,s,t,e):this.parsePrimitiveData(i,s,t,e);const a=()=>null===c[l]||f&&c[l]<f[l];for(h=0;h<e;++h)i._parsed[h+t]=c=d[h],u&&(a()&&(u=!1),f=c);i._sorted=u}r&&Vs(this,d)}parsePrimitiveData(t,e,i,s){const{iScale:n,vScale:o}=t,a=n.axis,r=o.axis,l=n.getLabels(),h=n===o,c=new Array(s);let d,u,f;for(d=0,u=s;d<u;++d)f=d+i,c[d]={[a]:h||n.parse(l[f],f),[r]:o.parse(e[f],f)};return c}parseArrayData(t,e,i,s){const{xScale:n,yScale:o}=t,a=new Array(s);let r,l,h,c;for(r=0,l=s;r<l;++r)h=r+i,c=e[h],a[r]={x:n.parse(c[0],h),y:o.parse(c[1],h)};return a}parseObjectData(t,e,i,s){const{xScale:n,yScale:o}=t,{xAxisKey:a="x",yAxisKey:r="y"}=this._parsing,l=new Array(s);let h,c,d,u;for(h=0,c=s;h<c;++h)d=h+i,u=e[d],l[h]={x:n.parse(M(u,a),d),y:o.parse(M(u,r),d)};return l}getParsed(t){return this._cachedMeta._parsed[t]}getDataElement(t){return this._cachedMeta.data[t]}applyStack(t,e,i){const s=this.chart,n=this._cachedMeta,o=e[t.axis];return Rs({keys:Es(s,!0),values:e._stacks[t.axis]._visualValues},o,n.index,{mode:i})}updateRangeFromParsed(t,e,i,s){const n=i[e.axis];let o=null===n?NaN:n;const a=s&&i._stacks[e.axis];s&&a&&(s.values=a,o=Rs(s,n,this._cachedMeta.index)),t.min=Math.min(t.min,o),t.max=Math.max(t.max,o)}getMinMax(t,e){const i=this._cachedMeta,s=i._parsed,n=i._sorted&&t===i.iScale,o=s.length,r=this._getOtherScale(t),l=((t,e,i)=>t&&!e.hidden&&e._stacked&&{keys:Es(i,!0),values:null})(e,i,this.chart),h={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:c,max:d}=function(t){const{min:e,max:i,minDefined:s,maxDefined:n}=t.getUserBounds();return{min:s?e:Number.NEGATIVE_INFINITY,max:n?i:Number.POSITIVE_INFINITY}}(r);let u,f;function g(){f=s[u];const e=f[r.axis];return!a(f[t.axis])||c>e||d<e}for(u=0;u<o&&(g()||(this.updateRangeFromParsed(h,t,f,l),!n));++u);if(n)for(u=o-1;u>=0;--u)if(!g()){this.updateRangeFromParsed(h,t,f,l);break}return h}getAllParsedValues(t){const e=this._cachedMeta._parsed,i=[];let s,n,o;for(s=0,n=e.length;s<n;++s)o=e[s][t.axis],a(o)&&i.push(o);return i}getMaxOverflow(){return!1}getLabelAndValue(t){const e=this._cachedMeta,i=e.iScale,s=e.vScale,n=this.getParsed(t);return{label:i?""+i.getLabelForValue(n[i.axis]):"",value:s?""+s.getLabelForValue(n[s.axis]):""}}_update(t){const e=this._cachedMeta;this.update(t||"default"),e._clip=function(t){let e,i,s,n;return o(t)?(e=t.top,i=t.right,s=t.bottom,n=t.left):e=i=s=n=t,{top:e,right:i,bottom:s,left:n,disabled:!1===t}}(l(this.options.clip,function(t,e,i){if(!1===i)return!1;const s=Ls(t,i),n=Ls(e,i);return{top:n.end,right:s.end,bottom:n.start,left:s.start}}(e.xScale,e.yScale,this.getMaxOverflow())))}update(t){}draw(){const t=this._ctx,e=this.chart,i=this._cachedMeta,s=i.data||[],n=e.chartArea,o=[],a=this._drawStart||0,r=this._drawCount||s.length-a,l=this.options.drawActiveElementsOnTop;let h;for(i.dataset&&i.dataset.draw(t,n,a,r),h=a;h<a+r;++h){const e=s[h];e.hidden||(e.active&&l?o.push(e):e.draw(t,n))}for(h=0;h<o.length;++h)o[h].draw(t,n)}getStyle(t,e){const i=e?"active":"default";return void 0===t&&this._cachedMeta.dataset?this.resolveDatasetElementOptions(i):this.resolveDataElementOptions(t||0,i)}getContext(t,e,i){const s=this.getDataset();let n;if(t>=0&&t<this._cachedMeta.data.length){const e=this._cachedMeta.data[t];n=e.$context||(e.$context=function(t,e,i){return Ci(t,{active:!1,dataIndex:e,parsed:void 0,raw:void 0,element:i,index:e,mode:"default",type:"data"})}(this.getContext(),t,e)),n.parsed=this.getParsed(t),n.raw=s.data[t],n.index=n.dataIndex=t}else n=this.$context||(this.$context=function(t,e){return Ci(t,{active:!1,dataset:void 0,datasetIndex:e,index:e,mode:"default",type:"dataset"})}(this.chart.getContext(),this.index)),n.dataset=s,n.index=n.datasetIndex=this.index;return n.active=!!e,n.mode=i,n}resolveDatasetElementOptions(t){return this._resolveElementOptions(this.datasetElementType.id,t)}resolveDataElementOptions(t,e){return this._resolveElementOptions(this.dataElementType.id,e,t)}_resolveElementOptions(t,e="default",i){const s="active"===e,n=this._cachedDataOpts,o=t+"-"+e,a=n[o],r=this.enableOptionSharing&&k(i);if(a)return Hs(a,r);const l=this.chart.config,h=l.datasetElementScopeKeys(this._type,t),c=s?[`${t}Hover`,"hover",t,""]:[t,""],d=l.getOptionScopes(this.getDataset(),h),u=Object.keys(ue.elements[t]),f=l.resolveNamedOptions(d,u,(()=>this.getContext(i,s,e)),c);return f.$shared&&(f.$shared=r,n[o]=Object.freeze(Hs(f,r))),f}_resolveAnimations(t,e,i){const s=this.chart,n=this._cachedDataOpts,o=`animation-${e}`,a=n[o];if(a)return a;let r;if(!1!==s.options.animation){const s=this.chart.config,n=s.datasetAnimationScopeKeys(this._type,e),o=s.getOptionScopes(this.getDataset(),n);r=s.createResolver(o,this.getContext(t,i,e))}const l=new Ts(s,r&&r.animations);return r&&r._cacheable&&(n[o]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||Ns(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){const i=this.resolveDataElementOptions(t,e),s=this._sharedOptions,n=this.getSharedOptions(i),o=this.includeOptions(e,n)||n!==s;return this.updateSharedOptions(n,e,i),{sharedOptions:n,includeOptions:o}}updateElement(t,e,i,s){Ns(s)?Object.assign(t,i):this._resolveAnimations(e,s).update(t,i)}updateSharedOptions(t,e,i){t&&!Ns(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,s){t.active=s;const n=this.getStyle(e,s);this._resolveAnimations(e,i,s).update(t,{options:!s&&this.getSharedOptions(n)||n})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const e=this._data,i=this._cachedMeta.data;for(const[t,e,i]of this._syncList)this[t](e,i);this._syncList=[];const s=i.length,n=e.length,o=Math.min(n,s);o&&this.parse(0,o),n>s?this._insertElements(s,n-s,t):n<s&&this._removeElements(n,s-n)}_insertElements(t,e,i=!0){const s=this._cachedMeta,n=s.data,o=t+e;let a;const r=t=>{for(t.length+=e,a=t.length-1;a>=o;a--)t[a]=t[a-e]};for(r(n),a=t;a<o;++a)n[a]=new this.dataElementType;this._parsing&&r(s._parsed),this.parse(t,e),i&&this.updateElements(n,t,e,"reset")}updateElements(t,e,i,s){}_removeElements(t,e){const i=this._cachedMeta;if(this._parsing){const s=i._parsed.splice(t,e);i._stacked&&Ws(i,s)}i.data.splice(t,e)}_sync(t){if(this._parsing)this._syncList.push(t);else{const[e,i,s]=t;this[e](i,s)}this.chart._dataChanges.push([this.index,...t])}_onDataPush(){const t=arguments.length;this._sync(["_insertElements",this.getDataset().data.length-t,t])}_onDataPop(){this._sync(["_removeElements",this._cachedMeta.data.length-1,1])}_onDataShift(){this._sync(["_removeElements",0,1])}_onDataSplice(t,e){e&&this._sync(["_removeElements",t,e]);const i=arguments.length-2;i&&this._sync(["_insertElements",t,i])}_onDataUnshift(){this._sync(["_insertElements",0,arguments.length])}}class $s{static defaults={};static defaultRoutes=void 0;x;y;active=!1;options;$animations;tooltipPosition(t){const{x:e,y:i}=this.getProps(["x","y"],t);return{x:e,y:i}}hasValue(){return N(this.x)&&N(this.y)}getProps(t,e){const i=this.$animations;if(!e||!i)return this;const s={};return t.forEach((t=>{s[t]=i[t]&&i[t].active()?i[t]._to:this[t]})),s}}function Ys(t,e){const i=t.options.ticks,n=function(t){const e=t.options.offset,i=t._tickSize(),s=t._length/i+(e?0:1),n=t._maxLength/i;return Math.floor(Math.min(s,n))}(t),o=Math.min(i.maxTicksLimit||n,n),a=i.major.enabled?function(t){const e=[];let i,s;for(i=0,s=t.length;i<s;i++)t[i].major&&e.push(i);return e}(e):[],r=a.length,l=a[0],h=a[r-1],c=[];if(r>o)return function(t,e,i,s){let n,o=0,a=i[0];for(s=Math.ceil(s),n=0;n<t.length;n++)n===a&&(e.push(t[n]),o++,a=i[o*s])}(e,c,a,r/o),c;const d=function(t,e,i){const s=function(t){const e=t.length;let i,s;if(e<2)return!1;for(s=t[0],i=1;i<e;++i)if(t[i]-t[i-1]!==s)return!1;return s}(t),n=e.length/i;if(!s)return Math.max(n,1);const o=W(s);for(let t=0,e=o.length-1;t<e;t++){const e=o[t];if(e>n)return e}return Math.max(n,1)}(a,e,o);if(r>0){let t,i;const n=r>1?Math.round((h-l)/(r-1)):null;for(Us(e,c,d,s(n)?0:l-n,l),t=0,i=r-1;t<i;t++)Us(e,c,d,a[t],a[t+1]);return Us(e,c,d,h,s(n)?e.length:h+n),c}return Us(e,c,d),c}function Us(t,e,i,s,n){const o=l(s,0),a=Math.min(l(n,t.length),t.length);let r,h,c,d=0;for(i=Math.ceil(i),n&&(r=n-s,i=r/Math.floor(r/i)),c=o;c<0;)d++,c=Math.round(o+d*i);for(h=Math.max(o,0);h<a;h++)h===c&&(e.push(t[h]),d++,c=Math.round(o+d*i))}const Xs=(t,e,i)=>"top"===e||"left"===e?t[e]+i:t[e]-i,qs=(t,e)=>Math.min(e||t,t);function Ks(t,e){const i=[],s=t.length/e,n=t.length;let o=0;for(;o<n;o+=s)i.push(t[Math.floor(o)]);return i}function Gs(t,e,i){const s=t.ticks.length,n=Math.min(e,s-1),o=t._startPixel,a=t._endPixel,r=1e-6;let l,h=t.getPixelForTick(n);if(!(i&&(l=1===s?Math.max(h-o,a-h):0===e?(t.getPixelForTick(1)-h)/2:(h-t.getPixelForTick(n-1))/2,h+=n<e?l:-l,h<o-r||h>a+r)))return h}function Zs(t){return t.drawTicks?t.tickLength:0}function Js(t,e){if(!t.display)return 0;const i=Si(t.font,e),s=ki(t.padding);return(n(t.text)?t.text.length:1)*i.lineHeight+s.height}function Qs(t,e,i){let s=ut(t);return(i&&"right"!==e||!i&&"right"===e)&&(s=(t=>"left"===t?"right":"right"===t?"left":t)(s)),s}class tn extends $s{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:s}=this;return t=r(t,Number.POSITIVE_INFINITY),e=r(e,Number.NEGATIVE_INFINITY),i=r(i,Number.POSITIVE_INFINITY),s=r(s,Number.NEGATIVE_INFINITY),{min:r(t,i),max:r(e,s),minDefined:a(t),maxDefined:a(e)}}getMinMax(t){let e,{min:i,max:s,minDefined:n,maxDefined:o}=this.getUserBounds();if(n&&o)return{min:i,max:s};const a=this.getMatchingVisibleMetas();for(let r=0,l=a.length;r<l;++r)e=a[r].controller.getMinMax(this,t),n||(i=Math.min(i,e.min)),o||(s=Math.max(s,e.max));return i=o&&i>s?s:i,s=n&&i>s?i:s,{min:r(i,r(s,i)),max:r(s,r(i,s))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){d(this.options.beforeUpdate,[this])}update(t,e,i){const{beginAtZero:s,grace:n,ticks:o}=this.options,a=o.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Di(this,n,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const r=a<this.ticks.length;this._convertTicksToLabels(r?Ks(this.ticks,a):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),o.display&&(o.autoSkip||"auto"===o.source)&&(this.ticks=Ys(this,this.ticks),this._labelSizes=null,this.afterAutoSkip()),r&&this._convertTicksToLabels(this.ticks),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate()}configure(){let t,e,i=this.options.reverse;this.isHorizontal()?(t=this.left,e=this.right):(t=this.top,e=this.bottom,i=!i),this._startPixel=t,this._endPixel=e,this._reversePixels=i,this._length=e-t,this._alignToPixels=this.options.alignToPixels}afterUpdate(){d(this.options.afterUpdate,[this])}beforeSetDimensions(){d(this.options.beforeSetDimensions,[this])}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0}afterSetDimensions(){d(this.options.afterSetDimensions,[this])}_callHooks(t){this.chart.notifyPlugins(t,this.getContext()),d(this.options[t],[this])}beforeDataLimits(){this._callHooks("beforeDataLimits")}determineDataLimits(){}afterDataLimits(){this._callHooks("afterDataLimits")}beforeBuildTicks(){this._callHooks("beforeBuildTicks")}buildTicks(){return[]}afterBuildTicks(){this._callHooks("afterBuildTicks")}beforeTickToLabelConversion(){d(this.options.beforeTickToLabelConversion,[this])}generateTickLabels(t){const e=this.options.ticks;let i,s,n;for(i=0,s=t.length;i<s;i++)n=t[i],n.label=d(e.callback,[n.value,i,t],this)}afterTickToLabelConversion(){d(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){d(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const t=this.options,e=t.ticks,i=qs(this.ticks.length,t.ticks.maxTicksLimit),s=e.minRotation||0,n=e.maxRotation;let o,a,r,l=s;if(!this._isVisible()||!e.display||s>=n||i<=1||!this.isHorizontal())return void(this.labelRotation=s);const h=this._getLabelSizes(),c=h.widest.width,d=h.highest.height,u=J(this.chart.width-c,0,this.maxWidth);o=t.offset?this.maxWidth/i:u/(i-1),c+6>o&&(o=u/(i-(t.offset?.5:1)),a=this.maxHeight-Zs(t.grid)-e.padding-Js(t.title,this.chart.options.font),r=Math.sqrt(c*c+d*d),l=Y(Math.min(Math.asin(J((h.highest.height+6)/o,-1,1)),Math.asin(J(a/r,-1,1))-Math.asin(J(d/r,-1,1)))),l=Math.max(s,Math.min(n,l))),this.labelRotation=l}afterCalculateLabelRotation(){d(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){d(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:e,options:{ticks:i,title:s,grid:n}}=this,o=this._isVisible(),a=this.isHorizontal();if(o){const o=Js(s,e.options.font);if(a?(t.width=this.maxWidth,t.height=Zs(n)+o):(t.height=this.maxHeight,t.width=Zs(n)+o),i.display&&this.ticks.length){const{first:e,last:s,widest:n,highest:o}=this._getLabelSizes(),r=2*i.padding,l=$(this.labelRotation),h=Math.cos(l),c=Math.sin(l);if(a){const e=i.mirror?0:c*n.width+h*o.height;t.height=Math.min(this.maxHeight,t.height+e+r)}else{const e=i.mirror?0:h*n.width+c*o.height;t.width=Math.min(this.maxWidth,t.width+e+r)}this._calculatePadding(e,s,c,h)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,s){const{ticks:{align:n,padding:o},position:a}=this.options,r=0!==this.labelRotation,l="top"!==a&&"x"===this.axis;if(this.isHorizontal()){const a=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1);let c=0,d=0;r?l?(c=s*t.width,d=i*e.height):(c=i*t.height,d=s*e.width):"start"===n?d=e.width:"end"===n?c=t.width:"inner"!==n&&(c=t.width/2,d=e.width/2),this.paddingLeft=Math.max((c-a+o)*this.width/(this.width-a),0),this.paddingRight=Math.max((d-h+o)*this.width/(this.width-h),0)}else{let i=e.height/2,s=t.height/2;"start"===n?(i=0,s=t.height):"end"===n&&(i=e.height,s=0),this.paddingTop=i+o,this.paddingBottom=s+o}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){d(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:e}=this.options;return"top"===e||"bottom"===e||"x"===t}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){let e,i;for(this.beforeTickToLabelConversion(),this.generateTickLabels(t),e=0,i=t.length;e<i;e++)s(t[e].label)&&(t.splice(e,1),i--,e--);this.afterTickToLabelConversion()}_getLabelSizes(){let t=this._labelSizes;if(!t){const e=this.options.ticks.sampleSize;let i=this.ticks;e<i.length&&(i=Ks(i,e)),this._labelSizes=t=this._computeLabelSizes(i,i.length,this.options.ticks.maxTicksLimit)}return t}_computeLabelSizes(t,e,i){const{ctx:o,_longestTextCache:a}=this,r=[],l=[],h=Math.floor(e/qs(e,i));let c,d,f,g,p,m,x,b,_,y,v,M=0,w=0;for(c=0;c<e;c+=h){if(g=t[c].label,p=this._resolveTickFontOptions(c),o.font=m=p.string,x=a[m]=a[m]||{data:{},gc:[]},b=p.lineHeight,_=y=0,s(g)||n(g)){if(n(g))for(d=0,f=g.length;d<f;++d)v=g[d],s(v)||n(v)||(_=Ce(o,x.data,x.gc,_,v),y+=b)}else _=Ce(o,x.data,x.gc,_,g),y=b;r.push(_),l.push(y),M=Math.max(_,M),w=Math.max(y,w)}!function(t,e){u(t,(t=>{const i=t.gc,s=i.length/2;let n;if(s>e){for(n=0;n<s;++n)delete t.data[i[n]];i.splice(0,s)}}))}(a,e);const k=r.indexOf(M),S=l.indexOf(w),P=t=>({width:r[t]||0,height:l[t]||0});return{first:P(0),last:P(e-1),widest:P(k),highest:P(S),widths:r,heights:l}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const e=this._startPixel+t*this._length;return Q(this._alignToPixels?Ae(this.chart,e,0):e)}getDecimalForPixel(t){const e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){const e=this.ticks||[];if(t>=0&&t<e.length){const i=e[t];return i.$context||(i.$context=function(t,e,i){return Ci(t,{tick:i,index:e,type:"tick"})}(this.getContext(),t,i))}return this.$context||(this.$context=Ci(this.chart.getContext(),{scale:this,type:"scale"}))}_tickSize(){const t=this.options.ticks,e=$(this.labelRotation),i=Math.abs(Math.cos(e)),s=Math.abs(Math.sin(e)),n=this._getLabelSizes(),o=t.autoSkipPadding||0,a=n?n.widest.width+o:0,r=n?n.highest.height+o:0;return this.isHorizontal()?r*i>a*s?a/i:r/s:r*s<a*i?r/i:a/s}_isVisible(){const t=this.options.display;return"auto"!==t?!!t:this.getMatchingVisibleMetas().length>0}_computeGridLineItems(t){const e=this.axis,i=this.chart,s=this.options,{grid:n,position:a,border:r}=s,h=n.offset,c=this.isHorizontal(),d=this.ticks.length+(h?1:0),u=Zs(n),f=[],g=r.setContext(this.getContext()),p=g.display?g.width:0,m=p/2,x=function(t){return Ae(i,t,p)};let b,_,y,v,M,w,k,S,P,D,C,O;if("top"===a)b=x(this.bottom),w=this.bottom-u,S=b-m,D=x(t.top)+m,O=t.bottom;else if("bottom"===a)b=x(this.top),D=t.top,O=x(t.bottom)-m,w=b+m,S=this.top+u;else if("left"===a)b=x(this.right),M=this.right-u,k=b-m,P=x(t.left)+m,C=t.right;else if("right"===a)b=x(this.left),P=t.left,C=x(t.right)-m,M=b+m,k=this.left+u;else if("x"===e){if("center"===a)b=x((t.top+t.bottom)/2+.5);else if(o(a)){const t=Object.keys(a)[0],e=a[t];b=x(this.chart.scales[t].getPixelForValue(e))}D=t.top,O=t.bottom,w=b+m,S=w+u}else if("y"===e){if("center"===a)b=x((t.left+t.right)/2);else if(o(a)){const t=Object.keys(a)[0],e=a[t];b=x(this.chart.scales[t].getPixelForValue(e))}M=b-m,k=M-u,P=t.left,C=t.right}const A=l(s.ticks.maxTicksLimit,d),T=Math.max(1,Math.ceil(d/A));for(_=0;_<d;_+=T){const t=this.getContext(_),e=n.setContext(t),s=r.setContext(t),o=e.lineWidth,a=e.color,l=s.dash||[],d=s.dashOffset,u=e.tickWidth,g=e.tickColor,p=e.tickBorderDash||[],m=e.tickBorderDashOffset;y=Gs(this,_,h),void 0!==y&&(v=Ae(i,y,o),c?M=k=P=C=v:w=S=D=O=v,f.push({tx1:M,ty1:w,tx2:k,ty2:S,x1:P,y1:D,x2:C,y2:O,width:o,color:a,borderDash:l,borderDashOffset:d,tickWidth:u,tickColor:g,tickBorderDash:p,tickBorderDashOffset:m}))}return this._ticksLength=d,this._borderValue=b,f}_computeLabelItems(t){const e=this.axis,i=this.options,{position:s,ticks:a}=i,r=this.isHorizontal(),l=this.ticks,{align:h,crossAlign:c,padding:d,mirror:u}=a,f=Zs(i.grid),g=f+d,p=u?-d:g,m=-$(this.labelRotation),x=[];let b,_,y,v,M,w,k,S,P,D,C,O,A="middle";if("top"===s)w=this.bottom-p,k=this._getXAxisLabelAlignment();else if("bottom"===s)w=this.top+p,k=this._getXAxisLabelAlignment();else if("left"===s){const t=this._getYAxisLabelAlignment(f);k=t.textAlign,M=t.x}else if("right"===s){const t=this._getYAxisLabelAlignment(f);k=t.textAlign,M=t.x}else if("x"===e){if("center"===s)w=(t.top+t.bottom)/2+g;else if(o(s)){const t=Object.keys(s)[0],e=s[t];w=this.chart.scales[t].getPixelForValue(e)+g}k=this._getXAxisLabelAlignment()}else if("y"===e){if("center"===s)M=(t.left+t.right)/2-g;else if(o(s)){const t=Object.keys(s)[0],e=s[t];M=this.chart.scales[t].getPixelForValue(e)}k=this._getYAxisLabelAlignment(f).textAlign}"y"===e&&("start"===h?A="top":"end"===h&&(A="bottom"));const T=this._getLabelSizes();for(b=0,_=l.length;b<_;++b){y=l[b],v=y.label;const t=a.setContext(this.getContext(b));S=this.getPixelForTick(b)+a.labelOffset,P=this._resolveTickFontOptions(b),D=P.lineHeight,C=n(v)?v.length:1;const e=C/2,i=t.color,o=t.textStrokeColor,h=t.textStrokeWidth;let d,f=k;if(r?(M=S,"inner"===k&&(f=b===_-1?this.options.reverse?"left":"right":0===b?this.options.reverse?"right":"left":"center"),O="top"===s?"near"===c||0!==m?-C*D+D/2:"center"===c?-T.highest.height/2-e*D+D:-T.highest.height+D/2:"near"===c||0!==m?D/2:"center"===c?T.highest.height/2-e*D:T.highest.height-C*D,u&&(O*=-1),0===m||t.showLabelBackdrop||(M+=D/2*Math.sin(m))):(w=S,O=(1-C)*D/2),t.showLabelBackdrop){const e=ki(t.backdropPadding),i=T.heights[b],s=T.widths[b];let n=O-e.top,o=0-e.left;switch(A){case"middle":n-=i/2;break;case"bottom":n-=i}switch(k){case"center":o-=s/2;break;case"right":o-=s;break;case"inner":b===_-1?o-=s:b>0&&(o-=s/2)}d={left:o,top:n,width:s+e.width,height:i+e.height,color:t.backdropColor}}x.push({label:v,font:P,textOffset:O,options:{rotation:m,color:i,strokeColor:o,strokeWidth:h,textAlign:f,textBaseline:A,translation:[M,w],backdrop:d}})}return x}_getXAxisLabelAlignment(){const{position:t,ticks:e}=this.options;if(-$(this.labelRotation))return"top"===t?"left":"right";let i="center";return"start"===e.align?i="left":"end"===e.align?i="right":"inner"===e.align&&(i="inner"),i}_getYAxisLabelAlignment(t){const{position:e,ticks:{crossAlign:i,mirror:s,padding:n}}=this.options,o=t+n,a=this._getLabelSizes().widest.width;let r,l;return"left"===e?s?(l=this.right+n,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l+=a)):(l=this.right-o,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l=this.left)):"right"===e?s?(l=this.left+n,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l-=a)):(l=this.left+o,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l=this.right)):r="right",{textAlign:r,x:l}}_computeLabelArea(){if(this.options.ticks.mirror)return;const t=this.chart,e=this.options.position;return"left"===e||"right"===e?{top:0,left:this.left,bottom:t.height,right:this.right}:"top"===e||"bottom"===e?{top:this.top,left:0,bottom:this.bottom,right:t.width}:void 0}drawBackground(){const{ctx:t,options:{backgroundColor:e},left:i,top:s,width:n,height:o}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(i,s,n,o),t.restore())}getLineWidthForValue(t){const e=this.options.grid;if(!this._isVisible()||!e.display)return 0;const i=this.ticks.findIndex((e=>e.value===t));if(i>=0){return e.setContext(this.getContext(i)).lineWidth}return 0}drawGrid(t){const e=this.options.grid,i=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let n,o;const a=(t,e,s)=>{s.width&&s.color&&(i.save(),i.lineWidth=s.width,i.strokeStyle=s.color,i.setLineDash(s.borderDash||[]),i.lineDashOffset=s.borderDashOffset,i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(e.x,e.y),i.stroke(),i.restore())};if(e.display)for(n=0,o=s.length;n<o;++n){const t=s[n];e.drawOnChartArea&&a({x:t.x1,y:t.y1},{x:t.x2,y:t.y2},t),e.drawTicks&&a({x:t.tx1,y:t.ty1},{x:t.tx2,y:t.ty2},{color:t.tickColor,width:t.tickWidth,borderDash:t.tickBorderDash,borderDashOffset:t.tickBorderDashOffset})}}drawBorder(){const{chart:t,ctx:e,options:{border:i,grid:s}}=this,n=i.setContext(this.getContext()),o=i.display?n.width:0;if(!o)return;const a=s.setContext(this.getContext(0)).lineWidth,r=this._borderValue;let l,h,c,d;this.isHorizontal()?(l=Ae(t,this.left,o)-o/2,h=Ae(t,this.right,a)+a/2,c=d=r):(c=Ae(t,this.top,o)-o/2,d=Ae(t,this.bottom,a)+a/2,l=h=r),e.save(),e.lineWidth=n.width,e.strokeStyle=n.color,e.beginPath(),e.moveTo(l,c),e.lineTo(h,d),e.stroke(),e.restore()}drawLabels(t){if(!this.options.ticks.display)return;const e=this.ctx,i=this._computeLabelArea();i&&Ie(e,i);const s=this.getLabelItems(t);for(const t of s){const i=t.options,s=t.font;Ne(e,t.label,0,t.textOffset,s,i)}i&&ze(e)}drawTitle(){const{ctx:t,options:{position:e,title:i,reverse:s}}=this;if(!i.display)return;const a=Si(i.font),r=ki(i.padding),l=i.align;let h=a.lineHeight/2;"bottom"===e||"center"===e||o(e)?(h+=r.bottom,n(i.text)&&(h+=a.lineHeight*(i.text.length-1))):h+=r.top;const{titleX:c,titleY:d,maxWidth:u,rotation:f}=function(t,e,i,s){const{top:n,left:a,bottom:r,right:l,chart:h}=t,{chartArea:c,scales:d}=h;let u,f,g,p=0;const m=r-n,x=l-a;if(t.isHorizontal()){if(f=ft(s,a,l),o(i)){const t=Object.keys(i)[0],s=i[t];g=d[t].getPixelForValue(s)+m-e}else g="center"===i?(c.bottom+c.top)/2+m-e:Xs(t,i,e);u=l-a}else{if(o(i)){const t=Object.keys(i)[0],s=i[t];f=d[t].getPixelForValue(s)-x+e}else f="center"===i?(c.left+c.right)/2-x+e:Xs(t,i,e);g=ft(s,r,n),p="left"===i?-E:E}return{titleX:f,titleY:g,maxWidth:u,rotation:p}}(this,h,e,l);Ne(t,i.text,0,0,a,{color:i.color,maxWidth:u,rotation:f,textAlign:Qs(l,e,s),textBaseline:"middle",translation:[c,d]})}draw(t){this._isVisible()&&(this.drawBackground(),this.drawGrid(t),this.drawBorder(),this.drawTitle(),this.drawLabels(t))}_layers(){const t=this.options,e=t.ticks&&t.ticks.z||0,i=l(t.grid&&t.grid.z,-1),s=l(t.border&&t.border.z,0);return this._isVisible()&&this.draw===tn.prototype.draw?[{z:i,draw:t=>{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",s=[];let n,o;for(n=0,o=e.length;n<o;++n){const o=e[n];o[i]!==this.id||t&&o.type!==t||s.push(o)}return s}_resolveTickFontOptions(t){return Si(this.options.ticks.setContext(this.getContext(t)).font)}_maxDigits(){const t=this._resolveTickFontOptions(0).lineHeight;return(this.isHorizontal()?this.width:this.height)/t}}class en{constructor(t,e,i){this.type=t,this.scope=e,this.override=i,this.items=Object.create(null)}isForType(t){return Object.prototype.isPrototypeOf.call(this.type.prototype,t.prototype)}register(t){const e=Object.getPrototypeOf(t);let i;(function(t){return"id"in t&&"defaults"in t})(e)&&(i=this.register(e));const s=this.items,n=t.id,o=this.scope+"."+n;if(!n)throw new Error("class does not have id: "+t);return n in s||(s[n]=t,function(t,e,i){const s=x(Object.create(null),[i?ue.get(i):{},ue.get(e),t.defaults]);ue.set(e,s),t.defaultRoutes&&function(t,e){Object.keys(e).forEach((i=>{const s=i.split("."),n=s.pop(),o=[t].concat(s).join("."),a=e[i].split("."),r=a.pop(),l=a.join(".");ue.route(o,n,l,r)}))}(e,t.defaultRoutes);t.descriptors&&ue.describe(e,t.descriptors)}(t,o,i),this.override&&ue.override(t.id,t.overrides)),o}get(t){return this.items[t]}unregister(t){const e=this.items,i=t.id,s=this.scope;i in e&&delete e[i],s&&i in ue[s]&&(delete ue[s][i],this.override&&delete re[i])}}class sn{constructor(){this.controllers=new en(js,"datasets",!0),this.elements=new en($s,"elements"),this.plugins=new en(Object,"plugins"),this.scales=new en(tn,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(t,e,i){[...e].forEach((e=>{const s=i||this._getRegistryForType(e);i||s.isForType(e)||s===this.plugins&&e.id?this._exec(t,s,e):u(e,(e=>{const s=i||this._getRegistryForType(e);this._exec(t,s,e)}))}))}_exec(t,e,i){const s=w(t);d(i["before"+s],[],i),e[t](i),d(i["after"+s],[],i)}_getRegistryForType(t){for(let e=0;e<this._typedRegistries.length;e++){const i=this._typedRegistries[e];if(i.isForType(t))return i}return this.plugins}_get(t,e,i){const s=e.get(t);if(void 0===s)throw new Error('"'+t+'" is not a registered '+i+".");return s}}var nn=new sn;class on{constructor(){this._init=[]}notify(t,e,i,s){"beforeInit"===e&&(this._init=this._createDescriptors(t,!0),this._notify(this._init,t,"install"));const n=s?this._descriptors(t).filter(s):this._descriptors(t),o=this._notify(n,t,e,i);return"afterDestroy"===e&&(this._notify(n,t,"stop"),this._notify(this._init,t,"uninstall")),o}_notify(t,e,i,s){s=s||{};for(const n of t){const t=n.plugin;if(!1===d(t[i],[e,s,n.options],t)&&s.cancelable)return!1}return!0}invalidate(){s(this._cache)||(this._oldCache=this._cache,this._cache=void 0)}_descriptors(t){if(this._cache)return this._cache;const e=this._cache=this._createDescriptors(t);return this._notifyStateChanges(t),e}_createDescriptors(t,e){const i=t&&t.config,s=l(i.options&&i.options.plugins,{}),n=function(t){const e={},i=[],s=Object.keys(nn.plugins.items);for(let t=0;t<s.length;t++)i.push(nn.getPlugin(s[t]));const n=t.plugins||[];for(let t=0;t<n.length;t++){const s=n[t];-1===i.indexOf(s)&&(i.push(s),e[s.id]=!0)}return{plugins:i,localIds:e}}(i);return!1!==s||e?function(t,{plugins:e,localIds:i},s,n){const o=[],a=t.getContext();for(const r of e){const e=r.id,l=an(s[e],n);null!==l&&o.push({plugin:r,options:rn(t.config,{plugin:r,local:i[e]},l,a)})}return o}(t,n,s,e):[]}_notifyStateChanges(t){const e=this._oldCache||[],i=this._cache,s=(t,e)=>t.filter((t=>!e.some((e=>t.plugin.id===e.plugin.id))));this._notify(s(e,i),t,"stop"),this._notify(s(i,e),t,"start")}}function an(t,e){return e||!1!==t?!0===t?{}:t:null}function rn(t,{plugin:e,local:i},s,n){const o=t.pluginScopeKeys(e),a=t.getOptionScopes(s,o);return i&&e.defaults&&a.push(e.defaults),t.createResolver(a,n,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function ln(t,e){const i=ue.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||i.indexAxis||"x"}function hn(t){if("x"===t||"y"===t||"r"===t)return t}function cn(t,...e){if(hn(t))return t;for(const s of e){const e=s.axis||("top"===(i=s.position)||"bottom"===i?"x":"left"===i||"right"===i?"y":void 0)||t.length>1&&hn(t[0].toLowerCase());if(e)return e}var i;throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function dn(t,e,i){if(i[e+"AxisID"]===t)return{axis:e}}function un(t,e){const i=re[t.type]||{scales:{}},s=e.scales||{},n=ln(t.type,e),a=Object.create(null);return Object.keys(s).forEach((e=>{const r=s[e];if(!o(r))return console.error(`Invalid scale configuration for scale: ${e}`);if(r._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${e}`);const l=cn(e,r,function(t,e){if(e.data&&e.data.datasets){const i=e.data.datasets.filter((e=>e.xAxisID===t||e.yAxisID===t));if(i.length)return dn(t,"x",i[0])||dn(t,"y",i[0])}return{}}(e,t),ue.scales[r.type]),h=function(t,e){return t===e?"_index_":"_value_"}(l,n),c=i.scales||{};a[e]=b(Object.create(null),[{axis:l},r,c[l],c[h]])})),t.data.datasets.forEach((i=>{const n=i.type||t.type,o=i.indexAxis||ln(n,e),r=(re[n]||{}).scales||{};Object.keys(r).forEach((t=>{const e=function(t,e){let i=t;return"_index_"===t?i=e:"_value_"===t&&(i="x"===e?"y":"x"),i}(t,o),n=i[e+"AxisID"]||e;a[n]=a[n]||Object.create(null),b(a[n],[{axis:e},s[n],r[t]])}))})),Object.keys(a).forEach((t=>{const e=a[t];b(e,[ue.scales[e.type],ue.scale])})),a}function fn(t){const e=t.options||(t.options={});e.plugins=l(e.plugins,{}),e.scales=un(t,e)}function gn(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const pn=new Map,mn=new Set;function xn(t,e){let i=pn.get(t);return i||(i=e(),pn.set(t,i),mn.add(i)),i}const bn=(t,e,i)=>{const s=M(e,i);void 0!==s&&t.add(s)};class _n{constructor(t){this._config=function(t){return(t=t||{}).data=gn(t.data),fn(t),t}(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=gn(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),fn(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return xn(t,(()=>[[`datasets.${t}`,""]]))}datasetAnimationScopeKeys(t,e){return xn(`${t}.transition.${e}`,(()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]]))}datasetElementScopeKeys(t,e){return xn(`${t}-${e}`,(()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]]))}pluginScopeKeys(t){const e=t.id;return xn(`${this.type}-plugin-${e}`,(()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]]))}_cachedScopes(t,e){const i=this._scopeCache;let s=i.get(t);return s&&!e||(s=new Map,i.set(t,s)),s}getOptionScopes(t,e,i){const{options:s,type:n}=this,o=this._cachedScopes(t,i),a=o.get(e);if(a)return a;const r=new Set;e.forEach((e=>{t&&(r.add(t),e.forEach((e=>bn(r,t,e)))),e.forEach((t=>bn(r,s,t))),e.forEach((t=>bn(r,re[n]||{},t))),e.forEach((t=>bn(r,ue,t))),e.forEach((t=>bn(r,le,t)))}));const l=Array.from(r);return 0===l.length&&l.push(Object.create(null)),mn.has(e)&&o.set(e,l),l}chartOptionScopes(){const{options:t,type:e}=this;return[t,re[e]||{},ue.datasets[e]||{},{type:e},ue,le]}resolveNamedOptions(t,e,i,s=[""]){const o={$shared:!0},{resolver:a,subPrefixes:r}=yn(this._resolverCache,t,s);let l=a;if(function(t,e){const{isScriptable:i,isIndexable:s}=Ye(t);for(const o of e){const e=i(o),a=s(o),r=(a||e)&&t[o];if(e&&(S(r)||vn(r))||a&&n(r))return!0}return!1}(a,e)){o.$shared=!1;l=$e(a,i=S(i)?i():i,this.createResolver(t,i,r))}for(const t of e)o[t]=l[t];return o}createResolver(t,e,i=[""],s){const{resolver:n}=yn(this._resolverCache,t,i);return o(e)?$e(n,e,void 0,s):n}}function yn(t,e,i){let s=t.get(e);s||(s=new Map,t.set(e,s));const n=i.join();let o=s.get(n);if(!o){o={resolver:je(e,i),subPrefixes:i.filter((t=>!t.toLowerCase().includes("hover")))},s.set(n,o)}return o}const vn=t=>o(t)&&Object.getOwnPropertyNames(t).some((e=>S(t[e])));const Mn=["top","bottom","left","right","chartArea"];function wn(t,e){return"top"===t||"bottom"===t||-1===Mn.indexOf(t)&&"x"===e}function kn(t,e){return function(i,s){return i[t]===s[t]?i[e]-s[e]:i[t]-s[t]}}function Sn(t){const e=t.chart,i=e.options.animation;e.notifyPlugins("afterRender"),d(i&&i.onComplete,[t],e)}function Pn(t){const e=t.chart,i=e.options.animation;d(i&&i.onProgress,[t],e)}function Dn(t){return fe()&&"string"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const Cn={},On=t=>{const e=Dn(t);return Object.values(Cn).filter((t=>t.canvas===e)).pop()};function An(t,e,i){const s=Object.keys(t);for(const n of s){const s=+n;if(s>=e){const o=t[n];delete t[n],(i>0||s>e)&&(t[s+i]=o)}}}class Tn{static defaults=ue;static instances=Cn;static overrides=re;static registry=nn;static version="4.4.9";static getChart=On;static register(...t){nn.add(...t),Ln()}static unregister(...t){nn.remove(...t),Ln()}constructor(t,e){const s=this.config=new _n(e),n=Dn(t),o=On(n);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const a=s.createResolver(s.chartOptionScopes(),this.getContext());this.platform=new(s.platform||Ps(n)),this.platform.updateConfig(s);const r=this.platform.acquireContext(n,a.aspectRatio),l=r&&r.canvas,h=l&&l.height,c=l&&l.width;this.id=i(),this.ctx=r,this.canvas=l,this.width=c,this.height=h,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new on,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=dt((t=>this.update(t)),a.resizeDelay||0),this._dataChanges=[],Cn[this.id]=this,r&&l?(bt.listen(this,"complete",Sn),bt.listen(this,"progress",Pn),this._initialize(),this.attached&&this.update()):console.error("Failed to create chart: can't acquire context from the given item")}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:n,_aspectRatio:o}=this;return s(t)?e&&o?o:n?i/n:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return nn}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():ke(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Te(this.canvas,this.ctx),this}stop(){return bt.stop(this),this}resize(t,e){bt.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){const i=this.options,s=this.canvas,n=i.maintainAspectRatio&&this.aspectRatio,o=this.platform.getMaximumSize(s,t,e,n),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),r=this.width?"resize":"attach";this.width=o.width,this.height=o.height,this._aspectRatio=this.aspectRatio,ke(this,a,!0)&&(this.notifyPlugins("resize",{size:o}),d(i.onResize,[this,o],this),this.attached&&this._doResize(r)&&this.render())}ensureScalesHaveIDs(){u(this.options.scales||{},((t,e)=>{t.id=e}))}buildOrUpdateScales(){const t=this.options,e=t.scales,i=this.scales,s=Object.keys(i).reduce(((t,e)=>(t[e]=!1,t)),{});let n=[];e&&(n=n.concat(Object.keys(e).map((t=>{const i=e[t],s=cn(t,i),n="r"===s,o="x"===s;return{options:i,dposition:n?"chartArea":o?"bottom":"left",dtype:n?"radialLinear":o?"category":"linear"}})))),u(n,(e=>{const n=e.options,o=n.id,a=cn(o,n),r=l(n.type,e.dtype);void 0!==n.position&&wn(n.position,a)===wn(e.dposition)||(n.position=e.dposition),s[o]=!0;let h=null;if(o in i&&i[o].type===r)h=i[o];else{h=new(nn.getScale(r))({id:o,type:r,ctx:this.ctx,chart:this}),i[h.id]=h}h.init(n,t)})),u(s,((t,e)=>{t||delete i[e]})),u(i,(t=>{ls.configure(this,t,t.options),ls.addBox(this,t)}))}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort(((t,e)=>t.index-e.index)),i>e){for(let t=e;t<i;++t)this._destroyDatasetMeta(t);t.splice(e,i-e)}this._sortedMetasets=t.slice(0).sort(kn("order","index"))}_removeUnreferencedMetasets(){const{_metasets:t,data:{datasets:e}}=this;t.length>e.length&&delete this._stacks,t.forEach(((t,i)=>{0===e.filter((e=>e===t._dataset)).length&&this._destroyDatasetMeta(i)}))}buildOrUpdateControllers(){const t=[],e=this.data.datasets;let i,s;for(this._removeUnreferencedMetasets(),i=0,s=e.length;i<s;i++){const s=e[i];let n=this.getDatasetMeta(i);const o=s.type||this.config.type;if(n.type&&n.type!==o&&(this._destroyDatasetMeta(i),n=this.getDatasetMeta(i)),n.type=o,n.indexAxis=s.indexAxis||ln(o,this.options),n.order=s.order||0,n.index=i,n.label=""+s.label,n.visible=this.isDatasetVisible(i),n.controller)n.controller.updateIndex(i),n.controller.linkScales();else{const e=nn.getController(o),{datasetElementType:s,dataElementType:a}=ue.datasets[o];Object.assign(e,{dataElementType:nn.getElement(a),datasetElementType:s&&nn.getElement(s)}),n.controller=new e(this,i),t.push(n.controller)}}return this._updateMetasets(),t}_resetElements(){u(this.data.datasets,((t,e)=>{this.getDatasetMeta(e).controller.reset()}),this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const e=this.config;e.update();const i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1===this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0}))return;const n=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let o=0;for(let t=0,e=this.data.datasets.length;t<e;t++){const{controller:e}=this.getDatasetMeta(t),i=!s&&-1===n.indexOf(e);e.buildOrUpdateElements(i),o=Math.max(+e.getMaxOverflow(),o)}o=this._minPadding=i.layout.autoPadding?o:0,this._updateLayout(o),s||u(n,(t=>{t.reset()})),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(kn("z","_idx"));const{_active:a,_lastEvent:r}=this;r?this._eventHandler(r,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){u(this.scales,(t=>{ls.removeBox(this,t)})),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);P(e,i)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(const{method:i,start:s,count:n}of e){An(t,s,"_removeElements"===i?-n:n)}}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const e=this.data.datasets.length,i=e=>new Set(t.filter((t=>t[0]===e)).map(((t,e)=>e+","+t.splice(1).join(",")))),s=i(0);for(let t=1;t<e;t++)if(!P(s,i(t)))return;return Array.from(s).map((t=>t.split(","))).map((t=>({method:t[1],start:+t[2],count:+t[3]})))}_updateLayout(t){if(!1===this.notifyPlugins("beforeLayout",{cancelable:!0}))return;ls.update(this,this.width,this.height,t);const e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],u(this.boxes,(t=>{i&&"chartArea"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))}),this),this._layers.forEach(((t,e)=>{t._idx=e})),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(!1!==this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})){for(let t=0,e=this.data.datasets.length;t<e;++t)this.getDatasetMeta(t).controller.configure();for(let e=0,i=this.data.datasets.length;e<i;++e)this._updateDataset(e,S(t)?t({datasetIndex:e}):t);this.notifyPlugins("afterDatasetsUpdate",{mode:t})}}_updateDataset(t,e){const i=this.getDatasetMeta(t),s={meta:i,index:t,mode:e,cancelable:!0};!1!==this.notifyPlugins("beforeDatasetUpdate",s)&&(i.controller._update(e),s.cancelable=!1,this.notifyPlugins("afterDatasetUpdate",s))}render(){!1!==this.notifyPlugins("beforeRender",{cancelable:!0})&&(bt.has(this)?this.attached&&!bt.running(this)&&bt.start(this):(this.draw(),Sn({chart:this})))}draw(){let t;if(this._resizeBeforeDraw){const{width:t,height:e}=this._resizeBeforeDraw;this._resizeBeforeDraw=null,this._resize(t,e)}if(this.clear(),this.width<=0||this.height<=0)return;if(!1===this.notifyPlugins("beforeDraw",{cancelable:!0}))return;const e=this._layers;for(t=0;t<e.length&&e[t].z<=0;++t)e[t].draw(this.chartArea);for(this._drawDatasets();t<e.length;++t)e[t].draw(this.chartArea);this.notifyPlugins("afterDraw")}_getSortedDatasetMetas(t){const e=this._sortedMetasets,i=[];let s,n;for(s=0,n=e.length;s<n;++s){const n=e[s];t&&!n.visible||i.push(n)}return i}getSortedVisibleDatasetMetas(){return this._getSortedDatasetMetas(!0)}_drawDatasets(){if(!1===this.notifyPlugins("beforeDatasetsDraw",{cancelable:!0}))return;const t=this.getSortedVisibleDatasetMetas();for(let e=t.length-1;e>=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){const e=this.ctx,i={meta:t,index:t.index,cancelable:!0},s=Ni(this,t);!1!==this.notifyPlugins("beforeDatasetDraw",i)&&(s&&Ie(e,s),t.controller.draw(),s&&ze(e),i.cancelable=!1,this.notifyPlugins("afterDatasetDraw",i))}isPointInArea(t){return Re(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,i,s){const n=Ki.modes[e];return"function"==typeof n?n(this,t,i,s):[]}getDatasetMeta(t){const e=this.data.datasets[t],i=this._metasets;let s=i.filter((t=>t&&t._dataset===e)).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(s)),s}getContext(){return this.$context||(this.$context=Ci(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const e=this.data.datasets[t];if(!e)return!1;const i=this.getDatasetMeta(t);return"boolean"==typeof i.hidden?!i.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){const s=i?"show":"hide",n=this.getDatasetMeta(t),o=n.controller._resolveAnimations(void 0,s);k(e)?(n.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),o.update(n,{visible:i}),this.update((e=>e.datasetIndex===t?s:void 0)))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),bt.remove(this),t=0,e=this.data.datasets.length;t<e;++t)this._destroyDatasetMeta(t)}destroy(){this.notifyPlugins("beforeDestroy");const{canvas:t,ctx:e}=this;this._stop(),this.config.clearCache(),t&&(this.unbindEvents(),Te(t,e),this.platform.releaseContext(e),this.canvas=null,this.ctx=null),delete Cn[this.id],this.notifyPlugins("afterDestroy")}toBase64Image(...t){return this.canvas.toDataURL(...t)}bindEvents(){this.bindUserEvents(),this.options.responsive?this.bindResponsiveEvents():this.attached=!0}bindUserEvents(){const t=this._listeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(t,e,i)=>{t.offsetX=e,t.offsetY=i,this._eventHandler(t)};u(this.options.events,(t=>i(t,s)))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(i,s)=>{t[i]&&(e.removeEventListener(this,i,s),delete t[i])},n=(t,e)=>{this.canvas&&this.resize(t,e)};let o;const a=()=>{s("attach",a),this.attached=!0,this.resize(),i("resize",n),i("detach",o)};o=()=>{this.attached=!1,s("resize",n),this._stop(),this._resize(0,0),i("attach",a)},e.isAttached(this.canvas)?a():o()}unbindEvents(){u(this._listeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._listeners={},u(this._responsiveListeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){const s=i?"set":"remove";let n,o,a,r;for("dataset"===e&&(n=this.getDatasetMeta(t[0].datasetIndex),n.controller["_"+s+"DatasetHoverStyle"]()),a=0,r=t.length;a<r;++a){o=t[a];const e=o&&this.getDatasetMeta(o.datasetIndex).controller;e&&e[s+"HoverStyle"](o.element,o.datasetIndex,o.index)}}getActiveElements(){return this._active||[]}setActiveElements(t){const e=this._active||[],i=t.map((({datasetIndex:t,index:e})=>{const i=this.getDatasetMeta(t);if(!i)throw new Error("No dataset found at index "+t);return{datasetIndex:t,element:i.data[e],index:e}}));!f(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(t){return 1===this._plugins._cache.filter((e=>e.plugin.id===t)).length}_updateHoverStyles(t,e,i){const s=this.options.hover,n=(t,e)=>t.filter((t=>!e.some((e=>t.datasetIndex===e.datasetIndex&&t.index===e.index)))),o=n(e,t),a=i?t:n(t,e);o.length&&this.updateHoverStyle(o,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(t,e){const i={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},s=e=>(e.options.events||this.options.events).includes(t.native.type);if(!1===this.notifyPlugins("beforeEvent",i,s))return;const n=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins("afterEvent",i,s),(n||i.changed)&&this.render(),this}_handleEvent(t,e,i){const{_active:s=[],options:n}=this,o=e,a=this._getActiveElements(t,s,i,o),r=D(t),l=function(t,e,i,s){return i&&"mouseout"!==t.type?s?e:t:null}(t,this._lastEvent,i,r);i&&(this._lastEvent=null,d(n.onHover,[t,a,this],this),r&&d(n.onClick,[t,a,this],this));const h=!f(a,s);return(h||e)&&(this._active=a,this._updateHoverStyles(a,s,e)),this._lastEvent=l,h}_getActiveElements(t,e,i,s){if("mouseout"===t.type)return[];if(!i)return e;const n=this.options.hover;return this.getElementsAtEventForMode(t,n.mode,n,s)}}function Ln(){return u(Tn.instances,(t=>t._plugins.invalidate()))}function En(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class Rn{static override(t){Object.assign(Rn.prototype,t)}options;constructor(t){this.options=t||{}}init(){}formats(){return En()}parse(){return En()}format(){return En()}add(){return En()}diff(){return En()}startOf(){return En()}endOf(){return En()}}var In={_date:Rn};function zn(t){const e=t.iScale,i=function(t,e){if(!t._cache.$bar){const i=t.getMatchingVisibleMetas(e);let s=[];for(let e=0,n=i.length;e<n;e++)s=s.concat(i[e].controller.getAllParsedValues(t));t._cache.$bar=lt(s.sort(((t,e)=>t-e)))}return t._cache.$bar}(e,t.type);let s,n,o,a,r=e._length;const l=()=>{32767!==o&&-32768!==o&&(k(a)&&(r=Math.min(r,Math.abs(o-a)||r)),a=o)};for(s=0,n=i.length;s<n;++s)o=e.getPixelForValue(i[s]),l();for(a=void 0,s=0,n=e.ticks.length;s<n;++s)o=e.getPixelForTick(s),l();return r}function Fn(t,e,i,s){return n(t)?function(t,e,i,s){const n=i.parse(t[0],s),o=i.parse(t[1],s),a=Math.min(n,o),r=Math.max(n,o);let l=a,h=r;Math.abs(a)>Math.abs(r)&&(l=r,h=a),e[i.axis]=h,e._custom={barStart:l,barEnd:h,start:n,end:o,min:a,max:r}}(t,e,i,s):e[i.axis]=i.parse(t,s),e}function Vn(t,e,i,s){const n=t.iScale,o=t.vScale,a=n.getLabels(),r=n===o,l=[];let h,c,d,u;for(h=i,c=i+s;h<c;++h)u=e[h],d={},d[n.axis]=r||n.parse(a[h],h),l.push(Fn(u,d,o,h));return l}function Bn(t){return t&&void 0!==t.barStart&&void 0!==t.barEnd}function Wn(t,e,i,s){let n=e.borderSkipped;const o={};if(!n)return void(t.borderSkipped=o);if(!0===n)return void(t.borderSkipped={top:!0,right:!0,bottom:!0,left:!0});const{start:a,end:r,reverse:l,top:h,bottom:c}=function(t){let e,i,s,n,o;return t.horizontal?(e=t.base>t.x,i="left",s="right"):(e=t.base<t.y,i="bottom",s="top"),e?(n="end",o="start"):(n="start",o="end"),{start:i,end:s,reverse:e,top:n,bottom:o}}(t);"middle"===n&&i&&(t.enableBorderRadius=!0,(i._top||0)===s?n=h:(i._bottom||0)===s?n=c:(o[Nn(c,a,r,l)]=!0,n=h)),o[Nn(n,a,r,l)]=!0,t.borderSkipped=o}function Nn(t,e,i,s){var n,o,a;return s?(a=i,t=Hn(t=(n=t)===(o=e)?a:n===a?o:n,i,e)):t=Hn(t,e,i),t}function Hn(t,e,i){return"start"===t?e:"end"===t?i:t}function jn(t,{inflateAmount:e},i){t.inflateAmount="auto"===e?1===i?.33:0:e}class $n extends js{static id="doughnut";static defaults={datasetElementType:!1,dataElementType:"arc",animation:{animateRotate:!0,animateScale:!1},animations:{numbers:{type:"number",properties:["circumference","endAngle","innerRadius","outerRadius","startAngle","x","y","offset","borderWidth","spacing"]}},cutout:"50%",rotation:0,circumference:360,radius:"100%",spacing:0,indexAxis:"r"};static descriptors={_scriptable:t=>"spacing"!==t,_indexable:t=>"spacing"!==t&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}};constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,e){const i=this.getDataset().data,s=this._cachedMeta;if(!1===this._parsing)s._parsed=i;else{let n,a,r=t=>+i[t];if(o(i[t])){const{key:t="value"}=this._parsing;r=e=>+M(i[e],t)}for(n=t,a=t+e;n<a;++n)s._parsed[n]=r(n)}}_getRotation(){return $(this.options.rotation-90)}_getCircumference(){return $(this.options.circumference)}_getRotationExtents(){let t=O,e=-O;for(let i=0;i<this.chart.data.datasets.length;++i)if(this.chart.isDatasetVisible(i)&&this.chart.getDatasetMeta(i).type===this._type){const s=this.chart.getDatasetMeta(i).controller,n=s._getRotation(),o=s._getCircumference();t=Math.min(t,n),e=Math.max(e,n+o)}return{rotation:t,circumference:e-t}}update(t){const e=this.chart,{chartArea:i}=e,s=this._cachedMeta,n=s.data,o=this.getMaxBorderWidth()+this.getMaxOffset(n)+this.options.spacing,a=Math.max((Math.min(i.width,i.height)-o)/2,0),r=Math.min(h(this.options.cutout,a),1),l=this._getRingWeight(this.index),{circumference:d,rotation:u}=this._getRotationExtents(),{ratioX:f,ratioY:g,offsetX:p,offsetY:m}=function(t,e,i){let s=1,n=1,o=0,a=0;if(e<O){const r=t,l=r+e,h=Math.cos(r),c=Math.sin(r),d=Math.cos(l),u=Math.sin(l),f=(t,e,s)=>Z(t,r,l,!0)?1:Math.max(e,e*i,s,s*i),g=(t,e,s)=>Z(t,r,l,!0)?-1:Math.min(e,e*i,s,s*i),p=f(0,h,d),m=f(E,c,u),x=g(C,h,d),b=g(C+E,c,u);s=(p-x)/2,n=(m-b)/2,o=-(p+x)/2,a=-(m+b)/2}return{ratioX:s,ratioY:n,offsetX:o,offsetY:a}}(u,d,r),x=(i.width-o)/f,b=(i.height-o)/g,_=Math.max(Math.min(x,b)/2,0),y=c(this.options.radius,_),v=(y-Math.max(y*r,0))/this._getVisibleDatasetWeightTotal();this.offsetX=p*y,this.offsetY=m*y,s.total=this.calculateTotal(),this.outerRadius=y-v*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-v*l,0),this.updateElements(n,0,n.length,t)}_circumference(t,e){const i=this.options,s=this._cachedMeta,n=this._getCircumference();return e&&i.animation.animateRotate||!this.chart.getDataVisibility(t)||null===s._parsed[t]||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*n/O)}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.chartArea,r=o.options.animation,l=(a.left+a.right)/2,h=(a.top+a.bottom)/2,c=n&&r.animateScale,d=c?0:this.innerRadius,u=c?0:this.outerRadius,{sharedOptions:f,includeOptions:g}=this._getSharedOptions(e,s);let p,m=this._getRotation();for(p=0;p<e;++p)m+=this._circumference(p,n);for(p=e;p<e+i;++p){const e=this._circumference(p,n),i=t[p],o={x:l+this.offsetX,y:h+this.offsetY,startAngle:m,endAngle:m+e,circumference:e,outerRadius:u,innerRadius:d};g&&(o.options=f||this.resolveDataElementOptions(p,i.active?"active":s)),m+=e,this.updateElement(i,p,o,s)}}calculateTotal(){const t=this._cachedMeta,e=t.data;let i,s=0;for(i=0;i<e.length;i++){const n=t._parsed[i];null===n||isNaN(n)||!this.chart.getDataVisibility(i)||e[i].hidden||(s+=Math.abs(n))}return s}calculateCircumference(t){const e=this._cachedMeta.total;return e>0&&!isNaN(t)?O*(Math.abs(t)/e):0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t],i.options.locale);return{label:s[t]||"",value:n}}getMaxBorderWidth(t){let e=0;const i=this.chart;let s,n,o,a,r;if(!t)for(s=0,n=i.data.datasets.length;s<n;++s)if(i.isDatasetVisible(s)){o=i.getDatasetMeta(s),t=o.data,a=o.controller;break}if(!t)return 0;for(s=0,n=t.length;s<n;++s)r=a.resolveDataElementOptions(s),"inner"!==r.borderAlign&&(e=Math.max(e,r.borderWidth||0,r.hoverBorderWidth||0));return e}getMaxOffset(t){let e=0;for(let i=0,s=t.length;i<s;++i){const t=this.resolveDataElementOptions(i);e=Math.max(e,t.offset||0,t.hoverOffset||0)}return e}_getRingWeightOffset(t){let e=0;for(let i=0;i<t;++i)this.chart.isDatasetVisible(i)&&(e+=this._getRingWeight(i));return e}_getRingWeight(t){return Math.max(l(this.chart.data.datasets[t].weight,1),0)}_getVisibleDatasetWeightTotal(){return this._getRingWeightOffset(this.chart.data.datasets.length)||1}}class Yn extends js{static id="polarArea";static defaults={dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t].r,i.options.locale);return{label:s[t]||"",value:n}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){const t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach(((t,i)=>{const s=this.getParsed(i).r;!isNaN(s)&&this.chart.getDataVisibility(i)&&(s<e.min&&(e.min=s),s>e.max&&(e.max=s))})),e}_updateRadius(){const t=this.chart,e=t.chartArea,i=t.options,s=Math.min(e.right-e.left,e.bottom-e.top),n=Math.max(s/2,0),o=(n-Math.max(i.cutoutPercentage?n/100*i.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=n-o*this.index,this.innerRadius=this.outerRadius-o}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.options.animation,r=this._cachedMeta.rScale,l=r.xCenter,h=r.yCenter,c=r.getIndexAngle(0)-.5*C;let d,u=c;const f=360/this.countVisibleElements();for(d=0;d<e;++d)u+=this._computeAngle(d,s,f);for(d=e;d<e+i;d++){const e=t[d];let i=u,g=u+this._computeAngle(d,s,f),p=o.getDataVisibility(d)?r.getDistanceFromCenterForValue(this.getParsed(d).r):0;u=g,n&&(a.animateScale&&(p=0),a.animateRotate&&(i=g=c));const m={x:l,y:h,innerRadius:0,outerRadius:p,startAngle:i,endAngle:g,options:this.resolveDataElementOptions(d,e.active?"active":s)};this.updateElement(e,d,m,s)}}countVisibleElements(){const t=this._cachedMeta;let e=0;return t.data.forEach(((t,i)=>{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++})),e}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?$(this.resolveDataElementOptions(t,e).angle||i):0}}var Un=Object.freeze({__proto__:null,BarController:class extends js{static id="bar";static defaults={datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}};static overrides={scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}};parsePrimitiveData(t,e,i,s){return Vn(t,e,i,s)}parseArrayData(t,e,i,s){return Vn(t,e,i,s)}parseObjectData(t,e,i,s){const{iScale:n,vScale:o}=t,{xAxisKey:a="x",yAxisKey:r="y"}=this._parsing,l="x"===n.axis?a:r,h="x"===o.axis?a:r,c=[];let d,u,f,g;for(d=i,u=i+s;d<u;++d)g=e[d],f={},f[n.axis]=n.parse(M(g,l),d),c.push(Fn(M(g,h),f,o,d));return c}updateRangeFromParsed(t,e,i,s){super.updateRangeFromParsed(t,e,i,s);const n=i._custom;n&&e===this._cachedMeta.vScale&&(t.min=Math.min(t.min,n.min),t.max=Math.max(t.max,n.max))}getMaxOverflow(){return 0}getLabelAndValue(t){const e=this._cachedMeta,{iScale:i,vScale:s}=e,n=this.getParsed(t),o=n._custom,a=Bn(o)?"["+o.start+", "+o.end+"]":""+s.getLabelForValue(n[s.axis]);return{label:""+i.getLabelForValue(n[i.axis]),value:a}}initialize(){this.enableOptionSharing=!0,super.initialize();this._cachedMeta.stack=this.getDataset().stack}update(t){const e=this._cachedMeta;this.updateElements(e.data,0,e.data.length,t)}updateElements(t,e,i,n){const o="reset"===n,{index:a,_cachedMeta:{vScale:r}}=this,l=r.getBasePixel(),h=r.isHorizontal(),c=this._getRuler(),{sharedOptions:d,includeOptions:u}=this._getSharedOptions(e,n);for(let f=e;f<e+i;f++){const e=this.getParsed(f),i=o||s(e[r.axis])?{base:l,head:l}:this._calculateBarValuePixels(f),g=this._calculateBarIndexPixels(f,c),p=(e._stacks||{})[r.axis],m={horizontal:h,base:i.base,enableBorderRadius:!p||Bn(e._custom)||a===p._top||a===p._bottom,x:h?i.head:g.center,y:h?g.center:i.head,height:h?g.size:Math.abs(i.size),width:h?Math.abs(i.size):g.size};u&&(m.options=d||this.resolveDataElementOptions(f,t[f].active?"active":n));const x=m.options||t[f].options;Wn(m,x,p,a),jn(m,x,c.ratio),this.updateElement(t[f],f,m,n)}}_getStacks(t,e){const{iScale:i}=this._cachedMeta,n=i.getMatchingVisibleMetas(this._type).filter((t=>t.controller.options.grouped)),o=i.options.stacked,a=[],r=this._cachedMeta.controller.getParsed(e),l=r&&r[i.axis],h=t=>{const e=t._parsed.find((t=>t[i.axis]===l)),n=e&&e[t.vScale.axis];if(s(n)||isNaN(n))return!0};for(const i of n)if((void 0===e||!h(i))&&((!1===o||-1===a.indexOf(i.stack)||void 0===o&&void 0===i.stack)&&a.push(i.stack),i.index===t))break;return a.length||a.push(void 0),a}_getStackCount(t){return this._getStacks(void 0,t).length}_getStackIndex(t,e,i){const s=this._getStacks(t,i),n=void 0!==e?s.indexOf(e):-1;return-1===n?s.length-1:n}_getRuler(){const t=this.options,e=this._cachedMeta,i=e.iScale,s=[];let n,o;for(n=0,o=e.data.length;n<o;++n)s.push(i.getPixelForValue(this.getParsed(n)[i.axis],n));const a=t.barThickness;return{min:a||zn(e),pixels:s,start:i._startPixel,end:i._endPixel,stackCount:this._getStackCount(),scale:i,grouped:t.grouped,ratio:a?1:t.categoryPercentage*t.barPercentage}}_calculateBarValuePixels(t){const{_cachedMeta:{vScale:e,_stacked:i,index:n},options:{base:o,minBarLength:a}}=this,r=o||0,l=this.getParsed(t),h=l._custom,c=Bn(h);let d,u,f=l[e.axis],g=0,p=i?this.applyStack(e,l,i):f;p!==f&&(g=p-f,p=f),c&&(f=h.barStart,p=h.barEnd-h.barStart,0!==f&&F(f)!==F(h.barEnd)&&(g=0),g+=f);const m=s(o)||c?g:o;let x=e.getPixelForValue(m);if(d=this.chart.getDataVisibility(t)?e.getPixelForValue(g+p):x,u=d-x,Math.abs(u)<a){u=function(t,e,i){return 0!==t?F(t):(e.isHorizontal()?1:-1)*(e.min>=i?1:-1)}(u,e,r)*a,f===r&&(x-=u/2);const t=e.getPixelForDecimal(0),s=e.getPixelForDecimal(1),o=Math.min(t,s),h=Math.max(t,s);x=Math.max(Math.min(x,h),o),d=x+u,i&&!c&&(l._stacks[e.axis]._visualValues[n]=e.getValueForPixel(d)-e.getValueForPixel(x))}if(x===e.getPixelForValue(r)){const t=F(u)*e.getLineWidthForValue(r)/2;x+=t,u-=t}return{size:u,base:x,head:d,center:d+u/2}}_calculateBarIndexPixels(t,e){const i=e.scale,n=this.options,o=n.skipNull,a=l(n.maxBarThickness,1/0);let r,h;if(e.grouped){const i=o?this._getStackCount(t):e.stackCount,l="flex"===n.barThickness?function(t,e,i,s){const n=e.pixels,o=n[t];let a=t>0?n[t-1]:null,r=t<n.length-1?n[t+1]:null;const l=i.categoryPercentage;null===a&&(a=o-(null===r?e.end-e.start:r-o)),null===r&&(r=o+o-a);const h=o-(o-Math.min(a,r))/2*l;return{chunk:Math.abs(r-a)/2*l/s,ratio:i.barPercentage,start:h}}(t,e,n,i):function(t,e,i,n){const o=i.barThickness;let a,r;return s(o)?(a=e.min*i.categoryPercentage,r=i.barPercentage):(a=o*n,r=1),{chunk:a/n,ratio:r,start:e.pixels[t]-a/2}}(t,e,n,i),c=this._getStackIndex(this.index,this._cachedMeta.stack,o?t:void 0);r=l.start+l.chunk*c+l.chunk/2,h=Math.min(a,l.chunk*l.ratio)}else r=i.getPixelForValue(this.getParsed(t)[i.axis],t),h=Math.min(a,e.min*e.ratio);return{base:r-h/2,head:r+h/2,center:r,size:h}}draw(){const t=this._cachedMeta,e=t.vScale,i=t.data,s=i.length;let n=0;for(;n<s;++n)null===this.getParsed(n)[e.axis]||i[n].hidden||i[n].draw(this._ctx)}},BubbleController:class extends js{static id="bubble";static defaults={datasetElementType:!1,dataElementType:"point",animations:{numbers:{type:"number",properties:["x","y","borderWidth","radius"]}}};static overrides={scales:{x:{type:"linear"},y:{type:"linear"}}};initialize(){this.enableOptionSharing=!0,super.initialize()}parsePrimitiveData(t,e,i,s){const n=super.parsePrimitiveData(t,e,i,s);for(let t=0;t<n.length;t++)n[t]._custom=this.resolveDataElementOptions(t+i).radius;return n}parseArrayData(t,e,i,s){const n=super.parseArrayData(t,e,i,s);for(let t=0;t<n.length;t++){const s=e[i+t];n[t]._custom=l(s[2],this.resolveDataElementOptions(t+i).radius)}return n}parseObjectData(t,e,i,s){const n=super.parseObjectData(t,e,i,s);for(let t=0;t<n.length;t++){const s=e[i+t];n[t]._custom=l(s&&s.r&&+s.r,this.resolveDataElementOptions(t+i).radius)}return n}getMaxOverflow(){const t=this._cachedMeta.data;let e=0;for(let i=t.length-1;i>=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y),l=o._custom;return{label:i[t]||"",value:"("+a+", "+r+(l?", "+l:"")+")"}}update(t){const e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,s){const n="reset"===s,{iScale:o,vScale:a}=this._cachedMeta,{sharedOptions:r,includeOptions:l}=this._getSharedOptions(e,s),h=o.axis,c=a.axis;for(let d=e;d<e+i;d++){const e=t[d],i=!n&&this.getParsed(d),u={},f=u[h]=n?o.getPixelForDecimal(.5):o.getPixelForValue(i[h]),g=u[c]=n?a.getBasePixel():a.getPixelForValue(i[c]);u.skip=isNaN(f)||isNaN(g),l&&(u.options=r||this.resolveDataElementOptions(d,e.active?"active":s),n&&(u.options.radius=0)),this.updateElement(e,d,u,s)}}resolveDataElementOptions(t,e){const i=this.getParsed(t);let s=super.resolveDataElementOptions(t,e);s.$shared&&(s=Object.assign({},s,{$shared:!1}));const n=s.radius;return"active"!==e&&(s.radius=0),s.radius+=l(i&&i._custom,n),s}},DoughnutController:$n,LineController:class extends js{static id="line";static defaults={datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1};static overrides={scales:{_index_:{type:"category"},_value_:{type:"linear"}}};initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(t){const e=this._cachedMeta,{dataset:i,data:s=[],_dataset:n}=e,o=this.chart._animationsDisabled;let{start:a,count:r}=pt(e,s,o);this._drawStart=a,this._drawCount=r,mt(e)&&(a=0,r=s.length),i._chart=this.chart,i._datasetIndex=this.index,i._decimated=!!n._decimated,i.points=s;const l=this.resolveDatasetElementOptions(t);this.options.showLine||(l.borderWidth=0),l.segment=this.options.segment,this.updateElement(i,void 0,{animated:!o,options:l},t),this.updateElements(s,a,r,t)}updateElements(t,e,i,n){const o="reset"===n,{iScale:a,vScale:r,_stacked:l,_dataset:h}=this._cachedMeta,{sharedOptions:c,includeOptions:d}=this._getSharedOptions(e,n),u=a.axis,f=r.axis,{spanGaps:g,segment:p}=this.options,m=N(g)?g:Number.POSITIVE_INFINITY,x=this.chart._animationsDisabled||o||"none"===n,b=e+i,_=t.length;let y=e>0&&this.getParsed(e-1);for(let i=0;i<_;++i){const g=t[i],_=x?g:{};if(i<e||i>=b){_.skip=!0;continue}const v=this.getParsed(i),M=s(v[f]),w=_[u]=a.getPixelForValue(v[u],i),k=_[f]=o||M?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,v,l):v[f],i);_.skip=isNaN(w)||isNaN(k)||M,_.stop=i>0&&Math.abs(v[u]-y[u])>m,p&&(_.parsed=v,_.raw=h.data[i]),d&&(_.options=c||this.resolveDataElementOptions(i,g.active?"active":n)),x||this.updateElement(g,i,_,n),y=v}}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,s=t.data||[];if(!s.length)return i;const n=s[0].size(this.resolveDataElementOptions(0)),o=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(i,n,o)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}},PieController:class extends $n{static id="pie";static defaults={cutout:0,rotation:0,circumference:360,radius:"100%"}},PolarAreaController:Yn,RadarController:class extends js{static id="radar";static defaults={datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}};static overrides={aspectRatio:1,scales:{r:{type:"radialLinear"}}};getLabelAndValue(t){const e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta,i=e.dataset,s=e.data||[],n=e.iScale.getLabels();if(i.points=s,"resize"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);const o={_loop:!0,_fullLoop:n.length===s.length,options:e};this.updateElement(i,void 0,o,t)}this.updateElements(s,0,s.length,t)}updateElements(t,e,i,s){const n=this._cachedMeta.rScale,o="reset"===s;for(let a=e;a<e+i;a++){const e=t[a],i=this.resolveDataElementOptions(a,e.active?"active":s),r=n.getPointPositionForValue(a,this.getParsed(a).r),l=o?n.xCenter:r.x,h=o?n.yCenter:r.y,c={x:l,y:h,angle:r.angle,skip:isNaN(l)||isNaN(h),options:i};this.updateElement(e,a,c,s)}}},ScatterController:class extends js{static id="scatter";static defaults={datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1};static overrides={interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}};getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y);return{label:i[t]||"",value:"("+a+", "+r+")"}}update(t){const e=this._cachedMeta,{data:i=[]}=e,s=this.chart._animationsDisabled;let{start:n,count:o}=pt(e,i,s);if(this._drawStart=n,this._drawCount=o,mt(e)&&(n=0,o=i.length),this.options.showLine){this.datasetElementType||this.addElements();const{dataset:n,_dataset:o}=e;n._chart=this.chart,n._datasetIndex=this.index,n._decimated=!!o._decimated,n.points=i;const a=this.resolveDatasetElementOptions(t);a.segment=this.options.segment,this.updateElement(n,void 0,{animated:!s,options:a},t)}else this.datasetElementType&&(delete e.dataset,this.datasetElementType=!1);this.updateElements(i,n,o,t)}addElements(){const{showLine:t}=this.options;!this.datasetElementType&&t&&(this.datasetElementType=this.chart.registry.getElement("line")),super.addElements()}updateElements(t,e,i,n){const o="reset"===n,{iScale:a,vScale:r,_stacked:l,_dataset:h}=this._cachedMeta,c=this.resolveDataElementOptions(e,n),d=this.getSharedOptions(c),u=this.includeOptions(n,d),f=a.axis,g=r.axis,{spanGaps:p,segment:m}=this.options,x=N(p)?p:Number.POSITIVE_INFINITY,b=this.chart._animationsDisabled||o||"none"===n;let _=e>0&&this.getParsed(e-1);for(let c=e;c<e+i;++c){const e=t[c],i=this.getParsed(c),p=b?e:{},y=s(i[g]),v=p[f]=a.getPixelForValue(i[f],c),M=p[g]=o||y?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,i,l):i[g],c);p.skip=isNaN(v)||isNaN(M)||y,p.stop=c>0&&Math.abs(i[f]-_[f])>x,m&&(p.parsed=i,p.raw=h.data[c]),u&&(p.options=d||this.resolveDataElementOptions(c,e.active?"active":n)),b||this.updateElement(e,c,p,n),_=i}this.updateSharedOptions(d,n,c)}getMaxOverflow(){const t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let t=0;for(let i=e.length-1;i>=0;--i)t=Math.max(t,e[i].size(this.resolveDataElementOptions(i))/2);return t>0&&t}const i=t.dataset,s=i.options&&i.options.borderWidth||0;if(!e.length)return s;const n=e[0].size(this.resolveDataElementOptions(0)),o=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(s,n,o)/2}}});function Xn(t,e,i,s){const n=vi(t.options.borderRadius,["outerStart","outerEnd","innerStart","innerEnd"]);const o=(i-e)/2,a=Math.min(o,s*e/2),r=t=>{const e=(i-Math.min(o,t))*s/2;return J(t,0,Math.min(o,e))};return{outerStart:r(n.outerStart),outerEnd:r(n.outerEnd),innerStart:J(n.innerStart,0,a),innerEnd:J(n.innerEnd,0,a)}}function qn(t,e,i,s){return{x:i+t*Math.cos(e),y:s+t*Math.sin(e)}}function Kn(t,e,i,s,n,o){const{x:a,y:r,startAngle:l,pixelMargin:h,innerRadius:c}=e,d=Math.max(e.outerRadius+s+i-h,0),u=c>0?c+s+i+h:0;let f=0;const g=n-l;if(s){const t=((c>0?c-s:0)+(d>0?d-s:0))/2;f=(g-(0!==t?g*t/(t+s):g))/2}const p=(g-Math.max(.001,g*d-i/C)/d)/2,m=l+p+f,x=n-p-f,{outerStart:b,outerEnd:_,innerStart:y,innerEnd:v}=Xn(e,u,d,x-m),M=d-b,w=d-_,k=m+b/M,S=x-_/w,P=u+y,D=u+v,O=m+y/P,A=x-v/D;if(t.beginPath(),o){const e=(k+S)/2;if(t.arc(a,r,d,k,e),t.arc(a,r,d,e,S),_>0){const e=qn(w,S,a,r);t.arc(e.x,e.y,_,S,x+E)}const i=qn(D,x,a,r);if(t.lineTo(i.x,i.y),v>0){const e=qn(D,A,a,r);t.arc(e.x,e.y,v,x+E,A+Math.PI)}const s=(x-v/u+(m+y/u))/2;if(t.arc(a,r,u,x-v/u,s,!0),t.arc(a,r,u,s,m+y/u,!0),y>0){const e=qn(P,O,a,r);t.arc(e.x,e.y,y,O+Math.PI,m-E)}const n=qn(M,m,a,r);if(t.lineTo(n.x,n.y),b>0){const e=qn(M,k,a,r);t.arc(e.x,e.y,b,m-E,k)}}else{t.moveTo(a,r);const e=Math.cos(k)*d+a,i=Math.sin(k)*d+r;t.lineTo(e,i);const s=Math.cos(S)*d+a,n=Math.sin(S)*d+r;t.lineTo(s,n)}t.closePath()}function Gn(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r,options:l}=e,{borderWidth:h,borderJoinStyle:c,borderDash:d,borderDashOffset:u}=l,f="inner"===l.borderAlign;if(!h)return;t.setLineDash(d||[]),t.lineDashOffset=u,f?(t.lineWidth=2*h,t.lineJoin=c||"round"):(t.lineWidth=h,t.lineJoin=c||"bevel");let g=e.endAngle;if(o){Kn(t,e,i,s,g,n);for(let e=0;e<o;++e)t.stroke();isNaN(r)||(g=a+(r%O||O))}f&&function(t,e,i){const{startAngle:s,pixelMargin:n,x:o,y:a,outerRadius:r,innerRadius:l}=e;let h=n/r;t.beginPath(),t.arc(o,a,r,s-h,i+h),l>n?(h=n/l,t.arc(o,a,l,i+h,s-h,!0)):t.arc(o,a,n,i+E,s-E),t.closePath(),t.clip()}(t,e,g),o||(Kn(t,e,i,s,g,n),t.stroke())}function Zn(t,e,i=e){t.lineCap=l(i.borderCapStyle,e.borderCapStyle),t.setLineDash(l(i.borderDash,e.borderDash)),t.lineDashOffset=l(i.borderDashOffset,e.borderDashOffset),t.lineJoin=l(i.borderJoinStyle,e.borderJoinStyle),t.lineWidth=l(i.borderWidth,e.borderWidth),t.strokeStyle=l(i.borderColor,e.borderColor)}function Jn(t,e,i){t.lineTo(i.x,i.y)}function Qn(t,e,i={}){const s=t.length,{start:n=0,end:o=s-1}=i,{start:a,end:r}=e,l=Math.max(n,a),h=Math.min(o,r),c=n<a&&o<a||n>r&&o>r;return{count:s,start:l,loop:e.loop,ilen:h<l&&!c?s+h-l:h-l}}function to(t,e,i,s){const{points:n,options:o}=e,{count:a,start:r,loop:l,ilen:h}=Qn(n,i,s),c=function(t){return t.stepped?Fe:t.tension||"monotone"===t.cubicInterpolationMode?Ve:Jn}(o);let d,u,f,{move:g=!0,reverse:p}=s||{};for(d=0;d<=h;++d)u=n[(r+(p?h-d:d))%a],u.skip||(g?(t.moveTo(u.x,u.y),g=!1):c(t,f,u,p,o.stepped),f=u);return l&&(u=n[(r+(p?h:0))%a],c(t,f,u,p,o.stepped)),!!l}function eo(t,e,i,s){const n=e.points,{count:o,start:a,ilen:r}=Qn(n,i,s),{move:l=!0,reverse:h}=s||{};let c,d,u,f,g,p,m=0,x=0;const b=t=>(a+(h?r-t:t))%o,_=()=>{f!==g&&(t.lineTo(m,g),t.lineTo(m,f),t.lineTo(m,p))};for(l&&(d=n[b(0)],t.moveTo(d.x,d.y)),c=0;c<=r;++c){if(d=n[b(c)],d.skip)continue;const e=d.x,i=d.y,s=0|e;s===u?(i<f?f=i:i>g&&(g=i),m=(x*m+e)/++x):(_(),t.lineTo(e,i),u=s,x=0,f=g=i),p=i}_()}function io(t){const e=t.options,i=e.borderDash&&e.borderDash.length;return!(t._decimated||t._loop||e.tension||"monotone"===e.cubicInterpolationMode||e.stepped||i)?eo:to}const so="function"==typeof Path2D;function no(t,e,i,s){so&&!e.options.segment?function(t,e,i,s){let n=e._path;n||(n=e._path=new Path2D,e.path(n,i,s)&&n.closePath()),Zn(t,e.options),t.stroke(n)}(t,e,i,s):function(t,e,i,s){const{segments:n,options:o}=e,a=io(e);for(const r of n)Zn(t,o,r.style),t.beginPath(),a(t,e,r,{start:i,end:i+s-1})&&t.closePath(),t.stroke()}(t,e,i,s)}class oo extends $s{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t&&"fill"!==t};constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){const i=this.options;if((i.tension||"monotone"===i.cubicInterpolationMode)&&!i.stepped&&!this._pointsUpdated){const s=i.spanGaps?this._loop:this._fullLoop;hi(this._points,i,t,s,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=zi(this,this.options.segment))}first(){const t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){const t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){const i=this.options,s=t[e],n=this.points,o=Ii(this,{property:e,start:s,end:s});if(!o.length)return;const a=[],r=function(t){return t.stepped?pi:t.tension||"monotone"===t.cubicInterpolationMode?mi:gi}(i);let l,h;for(l=0,h=o.length;l<h;++l){const{start:h,end:c}=o[l],d=n[h],u=n[c];if(d===u){a.push(d);continue}const f=r(d,u,Math.abs((s-d[e])/(u[e]-d[e])),i.stepped);f[e]=t[e],a.push(f)}return 1===a.length?a[0]:a}pathSegment(t,e,i){return io(this)(t,this,e,i)}path(t,e,i){const s=this.segments,n=io(this);let o=this._loop;e=e||0,i=i||this.points.length-e;for(const a of s)o&=n(t,this,a,{start:e,end:e+i-1});return!!o}draw(t,e,i,s){const n=this.options||{};(this.points||[]).length&&n.borderWidth&&(t.save(),no(t,this,i,s),t.restore()),this.animated&&(this._pointsUpdated=!1,this._path=void 0)}}function ao(t,e,i,s){const n=t.options,{[i]:o}=t.getProps([i],s);return Math.abs(e-o)<n.radius+n.hitRadius}function ro(t,e){const{x:i,y:s,base:n,width:o,height:a}=t.getProps(["x","y","base","width","height"],e);let r,l,h,c,d;return t.horizontal?(d=a/2,r=Math.min(i,n),l=Math.max(i,n),h=s-d,c=s+d):(d=o/2,r=i-d,l=i+d,h=Math.min(s,n),c=Math.max(s,n)),{left:r,top:h,right:l,bottom:c}}function lo(t,e,i,s){return t?0:J(e,i,s)}function ho(t){const e=ro(t),i=e.right-e.left,s=e.bottom-e.top,n=function(t,e,i){const s=t.options.borderWidth,n=t.borderSkipped,o=Mi(s);return{t:lo(n.top,o.top,0,i),r:lo(n.right,o.right,0,e),b:lo(n.bottom,o.bottom,0,i),l:lo(n.left,o.left,0,e)}}(t,i/2,s/2),a=function(t,e,i){const{enableBorderRadius:s}=t.getProps(["enableBorderRadius"]),n=t.options.borderRadius,a=wi(n),r=Math.min(e,i),l=t.borderSkipped,h=s||o(n);return{topLeft:lo(!h||l.top||l.left,a.topLeft,0,r),topRight:lo(!h||l.top||l.right,a.topRight,0,r),bottomLeft:lo(!h||l.bottom||l.left,a.bottomLeft,0,r),bottomRight:lo(!h||l.bottom||l.right,a.bottomRight,0,r)}}(t,i/2,s/2);return{outer:{x:e.left,y:e.top,w:i,h:s,radius:a},inner:{x:e.left+n.l,y:e.top+n.t,w:i-n.l-n.r,h:s-n.t-n.b,radius:{topLeft:Math.max(0,a.topLeft-Math.max(n.t,n.l)),topRight:Math.max(0,a.topRight-Math.max(n.t,n.r)),bottomLeft:Math.max(0,a.bottomLeft-Math.max(n.b,n.l)),bottomRight:Math.max(0,a.bottomRight-Math.max(n.b,n.r))}}}}function co(t,e,i,s){const n=null===e,o=null===i,a=t&&!(n&&o)&&ro(t,s);return a&&(n||tt(e,a.left,a.right))&&(o||tt(i,a.top,a.bottom))}function uo(t,e){t.rect(e.x,e.y,e.w,e.h)}function fo(t,e,i={}){const s=t.x!==i.x?-e:0,n=t.y!==i.y?-e:0,o=(t.x+t.w!==i.x+i.w?e:0)-s,a=(t.y+t.h!==i.y+i.h?e:0)-n;return{x:t.x+s,y:t.y+n,w:t.w+o,h:t.h+a,radius:t.radius}}var go=Object.freeze({__proto__:null,ArcElement:class extends $s{static id="arc";static defaults={borderAlign:"center",borderColor:"#fff",borderDash:[],borderDashOffset:0,borderJoinStyle:void 0,borderRadius:0,borderWidth:2,offset:0,spacing:0,angle:void 0,circular:!0};static defaultRoutes={backgroundColor:"backgroundColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;constructor(t){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.getProps(["x","y"],i),{angle:n,distance:o}=X(s,{x:t,y:e}),{startAngle:a,endAngle:r,innerRadius:h,outerRadius:c,circumference:d}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),u=(this.options.spacing+this.options.borderWidth)/2,f=l(d,r-a),g=Z(n,a,r)&&a!==r,p=f>=O||g,m=tt(o,h+u,c+u);return p&&m}getCenterPoint(t){const{x:e,y:i,startAngle:s,endAngle:n,innerRadius:o,outerRadius:a}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],t),{offset:r,spacing:l}=this.options,h=(s+n)/2,c=(o+a+l+r)/2;return{x:e+Math.cos(h)*c,y:i+Math.sin(h)*c}}tooltipPosition(t){return this.getCenterPoint(t)}draw(t){const{options:e,circumference:i}=this,s=(e.offset||0)/4,n=(e.spacing||0)/2,o=e.circular;if(this.pixelMargin="inner"===e.borderAlign?.33:0,this.fullCircles=i>O?Math.floor(i/O):0,0===i||this.innerRadius<0||this.outerRadius<0)return;t.save();const a=(this.startAngle+this.endAngle)/2;t.translate(Math.cos(a)*s,Math.sin(a)*s);const r=s*(1-Math.sin(Math.min(C,i||0)));t.fillStyle=e.backgroundColor,t.strokeStyle=e.borderColor,function(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r}=e;let l=e.endAngle;if(o){Kn(t,e,i,s,l,n);for(let e=0;e<o;++e)t.fill();isNaN(r)||(l=a+(r%O||O))}Kn(t,e,i,s,l,n),t.fill()}(t,this,r,n,o),Gn(t,this,r,n,o),t.restore()}},BarElement:class extends $s{static id="bar";static defaults={borderSkipped:"start",borderWidth:0,borderRadius:0,inflateAmount:"auto",pointStyle:void 0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};constructor(t){super(),this.options=void 0,this.horizontal=void 0,this.base=void 0,this.width=void 0,this.height=void 0,this.inflateAmount=void 0,t&&Object.assign(this,t)}draw(t){const{inflateAmount:e,options:{borderColor:i,backgroundColor:s}}=this,{inner:n,outer:o}=ho(this),a=(r=o.radius).topLeft||r.topRight||r.bottomLeft||r.bottomRight?He:uo;var r;t.save(),o.w===n.w&&o.h===n.h||(t.beginPath(),a(t,fo(o,e,n)),t.clip(),a(t,fo(n,-e,o)),t.fillStyle=i,t.fill("evenodd")),t.beginPath(),a(t,fo(n,e)),t.fillStyle=s,t.fill(),t.restore()}inRange(t,e,i){return co(this,t,e,i)}inXRange(t,e){return co(this,t,null,e)}inYRange(t,e){return co(this,null,t,e)}getCenterPoint(t){const{x:e,y:i,base:s,horizontal:n}=this.getProps(["x","y","base","horizontal"],t);return{x:n?(e+s)/2:e,y:n?i:(i+s)/2}}getRange(t){return"x"===t?this.width/2:this.height/2}},LineElement:oo,PointElement:class extends $s{static id="point";parsed;skip;stop;static defaults={borderWidth:1,hitRadius:1,hoverBorderWidth:1,hoverRadius:4,pointStyle:"circle",radius:3,rotation:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};constructor(t){super(),this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.options,{x:n,y:o}=this.getProps(["x","y"],i);return Math.pow(t-n,2)+Math.pow(e-o,2)<Math.pow(s.hitRadius+s.radius,2)}inXRange(t,e){return ao(this,t,"x",e)}inYRange(t,e){return ao(this,t,"y",e)}getCenterPoint(t){const{x:e,y:i}=this.getProps(["x","y"],t);return{x:e,y:i}}size(t){let e=(t=t||this.options||{}).radius||0;e=Math.max(e,e&&t.hoverRadius||0);return 2*(e+(e&&t.borderWidth||0))}draw(t,e){const i=this.options;this.skip||i.radius<.1||!Re(this,e,this.size(i)/2)||(t.strokeStyle=i.borderColor,t.lineWidth=i.borderWidth,t.fillStyle=i.backgroundColor,Le(t,i,this.x,this.y))}getRange(){const t=this.options||{};return t.radius+t.hitRadius}}});function po(t,e,i,s){const n=t.indexOf(e);if(-1===n)return((t,e,i,s)=>("string"==typeof e?(i=t.push(e)-1,s.unshift({index:i,label:e})):isNaN(e)&&(i=null),i))(t,e,i,s);return n!==t.lastIndexOf(e)?i:n}function mo(t){const e=this.getLabels();return t>=0&&t<e.length?e[t]:t}function xo(t,e,{horizontal:i,minRotation:s}){const n=$(s),o=(i?Math.sin(n):Math.cos(n))||.001,a=.75*e*(""+t).length;return Math.min(e/o,a)}class bo extends tn{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(t,e){return s(t)||("number"==typeof t||t instanceof Number)&&!isFinite(+t)?null:+t}handleTickRangeOptions(){const{beginAtZero:t}=this.options,{minDefined:e,maxDefined:i}=this.getUserBounds();let{min:s,max:n}=this;const o=t=>s=e?s:t,a=t=>n=i?n:t;if(t){const t=F(s),e=F(n);t<0&&e<0?a(0):t>0&&e>0&&o(0)}if(s===n){let e=0===n?1:Math.abs(.05*n);a(n+e),t||o(s-e)}this.min=s,this.max=n}getTickLimit(){const t=this.options.ticks;let e,{maxTicksLimit:i,stepSize:s}=t;return s?(e=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,e>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${e} ticks. Limiting to 1000.`),e=1e3)):(e=this.computeTickLimit(),i=i||11),i&&(e=Math.min(i,e)),e}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,e=t.ticks;let i=this.getTickLimit();i=Math.max(2,i);const n=function(t,e){const i=[],{bounds:n,step:o,min:a,max:r,precision:l,count:h,maxTicks:c,maxDigits:d,includeBounds:u}=t,f=o||1,g=c-1,{min:p,max:m}=e,x=!s(a),b=!s(r),_=!s(h),y=(m-p)/(d+1);let v,M,w,k,S=B((m-p)/g/f)*f;if(S<1e-14&&!x&&!b)return[{value:p},{value:m}];k=Math.ceil(m/S)-Math.floor(p/S),k>g&&(S=B(k*S/g/f)*f),s(l)||(v=Math.pow(10,l),S=Math.ceil(S*v)/v),"ticks"===n?(M=Math.floor(p/S)*S,w=Math.ceil(m/S)*S):(M=p,w=m),x&&b&&o&&H((r-a)/o,S/1e3)?(k=Math.round(Math.min((r-a)/S,c)),S=(r-a)/k,M=a,w=r):_?(M=x?a:M,w=b?r:w,k=h-1,S=(w-M)/k):(k=(w-M)/S,k=V(k,Math.round(k),S/1e3)?Math.round(k):Math.ceil(k));const P=Math.max(U(S),U(M));v=Math.pow(10,s(l)?P:l),M=Math.round(M*v)/v,w=Math.round(w*v)/v;let D=0;for(x&&(u&&M!==a?(i.push({value:a}),M<a&&D++,V(Math.round((M+D*S)*v)/v,a,xo(a,y,t))&&D++):M<a&&D++);D<k;++D){const t=Math.round((M+D*S)*v)/v;if(b&&t>r)break;i.push({value:t})}return b&&u&&w!==r?i.length&&V(i[i.length-1].value,r,xo(r,y,t))?i[i.length-1].value=r:i.push({value:r}):b&&w!==r||i.push({value:w}),i}({maxTicks:i,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:!1!==e.includeBounds},this._range||this);return"ticks"===t.bounds&&j(n,this,"value"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}configure(){const t=this.ticks;let e=this.min,i=this.max;if(super.configure(),this.options.offset&&t.length){const s=(i-e)/Math.max(t.length-1,1)/2;e-=s,i+=s}this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return ne(t,this.chart.options.locale,this.options.ticks.format)}}class _o extends bo{static id="linear";static defaults={ticks:{callback:ae.formatters.numeric}};determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?t:0,this.max=a(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),e=t?this.width:this.height,i=$(this.options.ticks.minRotation),s=(t?Math.sin(i):Math.cos(i))||.001,n=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,n.lineHeight/s))}getPixelForValue(t){return null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}const yo=t=>Math.floor(z(t)),vo=(t,e)=>Math.pow(10,yo(t)+e);function Mo(t){return 1===t/Math.pow(10,yo(t))}function wo(t,e,i){const s=Math.pow(10,i),n=Math.floor(t/s);return Math.ceil(e/s)-n}function ko(t,{min:e,max:i}){e=r(t.min,e);const s=[],n=yo(e);let o=function(t,e){let i=yo(e-t);for(;wo(t,e,i)>10;)i++;for(;wo(t,e,i)<10;)i--;return Math.min(i,yo(t))}(e,i),a=o<0?Math.pow(10,Math.abs(o)):1;const l=Math.pow(10,o),h=n>o?Math.pow(10,n):0,c=Math.round((e-h)*a)/a,d=Math.floor((e-h)/l/10)*l*10;let u=Math.floor((c-d)/Math.pow(10,o)),f=r(t.min,Math.round((h+d+u*Math.pow(10,o))*a)/a);for(;f<i;)s.push({value:f,major:Mo(f),significand:u}),u>=10?u=u<15?15:20:u++,u>=20&&(o++,u=2,a=o>=0?1:a),f=Math.round((h+d+u*Math.pow(10,o))*a)/a;const g=r(t.max,f);return s.push({value:g,major:Mo(g),significand:u}),s}class So extends tn{static id="logarithmic";static defaults={ticks:{callback:ae.formatters.logarithmic,major:{enabled:!0}}};constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){const i=bo.prototype.parse.apply(this,[t,e]);if(0!==i)return a(i)&&i>0?i:null;this._zero=!0}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?Math.max(0,t):null,this.max=a(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!a(this._userMin)&&(this.min=t===vo(this.min,0)?vo(this.min,-1):vo(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let i=this.min,s=this.max;const n=e=>i=t?i:e,o=t=>s=e?s:t;i===s&&(i<=0?(n(1),o(10)):(n(vo(i,-1)),o(vo(s,1)))),i<=0&&n(vo(s,-1)),s<=0&&o(vo(i,1)),this.min=i,this.max=s}buildTicks(){const t=this.options,e=ko({min:this._userMin,max:this._userMax},this);return"ticks"===t.bounds&&j(e,this,"value"),t.reverse?(e.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),e}getLabelForValue(t){return void 0===t?"0":ne(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=z(t),this._valueRange=z(this.max)-z(t)}getPixelForValue(t){return void 0!==t&&0!==t||(t=this.min),null===t||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(z(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}}function Po(t){const e=t.ticks;if(e.display&&t.display){const t=ki(e.backdropPadding);return l(e.font&&e.font.size,ue.font.size)+t.height}return 0}function Do(t,e,i,s,n){return t===s||t===n?{start:e-i/2,end:e+i/2}:t<s||t>n?{start:e-i,end:e}:{start:e,end:e+i}}function Co(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},i=Object.assign({},e),s=[],o=[],a=t._pointLabels.length,r=t.options.pointLabels,l=r.centerPointLabels?C/a:0;for(let u=0;u<a;u++){const a=r.setContext(t.getPointLabelContext(u));o[u]=a.padding;const f=t.getPointPosition(u,t.drawingArea+o[u],l),g=Si(a.font),p=(h=t.ctx,c=g,d=n(d=t._pointLabels[u])?d:[d],{w:Oe(h,c.string,d),h:d.length*c.lineHeight});s[u]=p;const m=G(t.getIndexAngle(u)+l),x=Math.round(Y(m));Oo(i,e,m,Do(x,f.x,p.w,0,180),Do(x,f.y,p.h,90,270))}var h,c,d;t.setCenterPoint(e.l-i.l,i.r-e.r,e.t-i.t,i.b-e.b),t._pointLabelItems=function(t,e,i){const s=[],n=t._pointLabels.length,o=t.options,{centerPointLabels:a,display:r}=o.pointLabels,l={extra:Po(o)/2,additionalAngle:a?C/n:0};let h;for(let o=0;o<n;o++){l.padding=i[o],l.size=e[o];const n=Ao(t,o,l);s.push(n),"auto"===r&&(n.visible=To(n,h),n.visible&&(h=n))}return s}(t,s,o)}function Oo(t,e,i,s,n){const o=Math.abs(Math.sin(i)),a=Math.abs(Math.cos(i));let r=0,l=0;s.start<e.l?(r=(e.l-s.start)/o,t.l=Math.min(t.l,e.l-r)):s.end>e.r&&(r=(s.end-e.r)/o,t.r=Math.max(t.r,e.r+r)),n.start<e.t?(l=(e.t-n.start)/a,t.t=Math.min(t.t,e.t-l)):n.end>e.b&&(l=(n.end-e.b)/a,t.b=Math.max(t.b,e.b+l))}function Ao(t,e,i){const s=t.drawingArea,{extra:n,additionalAngle:o,padding:a,size:r}=i,l=t.getPointPosition(e,s+n+a,o),h=Math.round(Y(G(l.angle+E))),c=function(t,e,i){90===i||270===i?t-=e/2:(i>270||i<90)&&(t-=e);return t}(l.y,r.h,h),d=function(t){if(0===t||180===t)return"center";if(t<180)return"left";return"right"}(h),u=function(t,e,i){"right"===i?t-=e:"center"===i&&(t-=e/2);return t}(l.x,r.w,d);return{visible:!0,x:l.x,y:c,textAlign:d,left:u,top:c,right:u+r.w,bottom:c+r.h}}function To(t,e){if(!e)return!0;const{left:i,top:s,right:n,bottom:o}=t;return!(Re({x:i,y:s},e)||Re({x:i,y:o},e)||Re({x:n,y:s},e)||Re({x:n,y:o},e))}function Lo(t,e,i){const{left:n,top:o,right:a,bottom:r}=i,{backdropColor:l}=e;if(!s(l)){const i=wi(e.borderRadius),s=ki(e.backdropPadding);t.fillStyle=l;const h=n-s.left,c=o-s.top,d=a-n+s.width,u=r-o+s.height;Object.values(i).some((t=>0!==t))?(t.beginPath(),He(t,{x:h,y:c,w:d,h:u,radius:i}),t.fill()):t.fillRect(h,c,d,u)}}function Eo(t,e,i,s){const{ctx:n}=t;if(i)n.arc(t.xCenter,t.yCenter,e,0,O);else{let i=t.getPointPosition(0,e);n.moveTo(i.x,i.y);for(let o=1;o<s;o++)i=t.getPointPosition(o,e),n.lineTo(i.x,i.y)}}class Ro extends bo{static id="radialLinear";static defaults={display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:ae.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback:t=>t,padding:5,centerPointLabels:!1}};static defaultRoutes={"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"};static descriptors={angleLines:{_fallback:"grid"}};constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){const t=this._padding=ki(Po(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!1);this.min=a(t)&&!isNaN(t)?t:0,this.max=a(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/Po(this.options))}generateTickLabels(t){bo.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map(((t,e)=>{const i=d(this.options.pointLabels.callback,[t,e],this);return i||0===i?i:""})).filter(((t,e)=>this.chart.getDataVisibility(e)))}fit(){const t=this.options;t.display&&t.pointLabels.display?Co(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,s){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,s))}getIndexAngle(t){return G(t*(O/(this._pointLabels.length||1))+$(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if(s(t))return NaN;const e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(s(t))return NaN;const e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){const e=this._pointLabels||[];if(t>=0&&t<e.length){const i=e[t];return function(t,e,i){return Ci(t,{label:i,index:e,type:"pointLabel"})}(this.getContext(),t,i)}}getPointPosition(t,e,i=0){const s=this.getIndexAngle(t)-E+i;return{x:Math.cos(s)*e+this.xCenter,y:Math.sin(s)*e+this.yCenter,angle:s}}getPointPositionForValue(t,e){return this.getPointPosition(t,this.getDistanceFromCenterForValue(e))}getBasePosition(t){return this.getPointPositionForValue(t||0,this.getBaseValue())}getPointLabelPosition(t){const{left:e,top:i,right:s,bottom:n}=this._pointLabelItems[t];return{left:e,top:i,right:s,bottom:n}}drawBackground(){const{backgroundColor:t,grid:{circular:e}}=this.options;if(t){const i=this.ctx;i.save(),i.beginPath(),Eo(this,this.getDistanceFromCenterForValue(this._endValue),e,this._pointLabels.length),i.closePath(),i.fillStyle=t,i.fill(),i.restore()}}drawGrid(){const t=this.ctx,e=this.options,{angleLines:i,grid:s,border:n}=e,o=this._pointLabels.length;let a,r,l;if(e.pointLabels.display&&function(t,e){const{ctx:i,options:{pointLabels:s}}=t;for(let n=e-1;n>=0;n--){const e=t._pointLabelItems[n];if(!e.visible)continue;const o=s.setContext(t.getPointLabelContext(n));Lo(i,o,e);const a=Si(o.font),{x:r,y:l,textAlign:h}=e;Ne(i,t._pointLabels[n],r,l+a.lineHeight/2,a,{color:o.color,textAlign:h,textBaseline:"middle"})}}(this,o),s.display&&this.ticks.forEach(((t,e)=>{if(0!==e||0===e&&this.min<0){r=this.getDistanceFromCenterForValue(t.value);const i=this.getContext(e),a=s.setContext(i),l=n.setContext(i);!function(t,e,i,s,n){const o=t.ctx,a=e.circular,{color:r,lineWidth:l}=e;!a&&!s||!r||!l||i<0||(o.save(),o.strokeStyle=r,o.lineWidth=l,o.setLineDash(n.dash||[]),o.lineDashOffset=n.dashOffset,o.beginPath(),Eo(t,i,a,s),o.closePath(),o.stroke(),o.restore())}(this,a,r,o,l)}})),i.display){for(t.save(),a=o-1;a>=0;a--){const s=i.setContext(this.getPointLabelContext(a)),{color:n,lineWidth:o}=s;o&&n&&(t.lineWidth=o,t.strokeStyle=n,t.setLineDash(s.borderDash),t.lineDashOffset=s.borderDashOffset,r=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),l=this.getPointPosition(a,r),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(l.x,l.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;const s=this.getIndexAngle(0);let n,o;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(s),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach(((s,a)=>{if(0===a&&this.min>=0&&!e.reverse)return;const r=i.setContext(this.getContext(a)),l=Si(r.font);if(n=this.getDistanceFromCenterForValue(this.ticks[a].value),r.showLabelBackdrop){t.font=l.string,o=t.measureText(s.label).width,t.fillStyle=r.backdropColor;const e=ki(r.backdropPadding);t.fillRect(-o/2-e.left,-n-l.size/2-e.top,o+e.width,l.size+e.height)}Ne(t,s.label,0,-n,l,{color:r.color,strokeColor:r.textStrokeColor,strokeWidth:r.textStrokeWidth})})),t.restore()}drawTitle(){}}const Io={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},zo=Object.keys(Io);function Fo(t,e){return t-e}function Vo(t,e){if(s(e))return null;const i=t._adapter,{parser:n,round:o,isoWeekday:r}=t._parseOpts;let l=e;return"function"==typeof n&&(l=n(l)),a(l)||(l="string"==typeof n?i.parse(l,n):i.parse(l)),null===l?null:(o&&(l="week"!==o||!N(r)&&!0!==r?i.startOf(l,o):i.startOf(l,"isoWeek",r)),+l)}function Bo(t,e,i,s){const n=zo.length;for(let o=zo.indexOf(t);o<n-1;++o){const t=Io[zo[o]],n=t.steps?t.steps:Number.MAX_SAFE_INTEGER;if(t.common&&Math.ceil((i-e)/(n*t.size))<=s)return zo[o]}return zo[n-1]}function Wo(t,e,i){if(i){if(i.length){const{lo:s,hi:n}=et(i,e);t[i[s]>=e?i[s]:i[n]]=!0}}else t[e]=!0}function No(t,e,i){const s=[],n={},o=e.length;let a,r;for(a=0;a<o;++a)r=e[a],n[r]=a,s.push({value:r,major:!1});return 0!==o&&i?function(t,e,i,s){const n=t._adapter,o=+n.startOf(e[0].value,s),a=e[e.length-1].value;let r,l;for(r=o;r<=a;r=+n.add(r,1,s))l=i[r],l>=0&&(e[l].major=!0);return e}(t,s,n,i):s}class Ho extends tn{static id="time";static defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}};constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){const i=t.time||(t.time={}),s=this._adapter=new In._date(t.adapters.date);s.init(e),b(i.displayFormats,s.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return void 0===t?null:Vo(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,e=this._adapter,i=t.time.unit||"day";let{min:s,max:n,minDefined:o,maxDefined:r}=this.getUserBounds();function l(t){o||isNaN(t.min)||(s=Math.min(s,t.min)),r||isNaN(t.max)||(n=Math.max(n,t.max))}o&&r||(l(this._getLabelBounds()),"ticks"===t.bounds&&"labels"===t.ticks.source||l(this.getMinMax(!1))),s=a(s)&&!isNaN(s)?s:+e.startOf(Date.now(),i),n=a(n)&&!isNaN(n)?n:+e.endOf(Date.now(),i)+1,this.min=Math.min(s,n-1),this.max=Math.max(s+1,n)}_getLabelBounds(){const t=this.getLabelTimestamps();let e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){const t=this.options,e=t.time,i=t.ticks,s="labels"===i.source?this.getLabelTimestamps():this._generate();"ticks"===t.bounds&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const n=this.min,o=nt(s,n,this.max);return this._unit=e.unit||(i.autoSkip?Bo(e.minUnit,this.min,this.max,this._getLabelCapacity(n)):function(t,e,i,s,n){for(let o=zo.length-1;o>=zo.indexOf(i);o--){const i=zo[o];if(Io[i].common&&t._adapter.diff(n,s,i)>=e-1)return i}return zo[i?zo.indexOf(i):0]}(this,o.length,e.minUnit,this.min,this.max)),this._majorUnit=i.major.enabled&&"year"!==this._unit?function(t){for(let e=zo.indexOf(t)+1,i=zo.length;e<i;++e)if(Io[zo[e]].common)return zo[e]}(this._unit):void 0,this.initOffsets(s),t.reverse&&o.reverse(),No(this,o,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map((t=>+t.value)))}initOffsets(t=[]){let e,i,s=0,n=0;this.options.offset&&t.length&&(e=this.getDecimalForValue(t[0]),s=1===t.length?1-e:(this.getDecimalForValue(t[1])-e)/2,i=this.getDecimalForValue(t[t.length-1]),n=1===t.length?i:(i-this.getDecimalForValue(t[t.length-2]))/2);const o=t.length<3?.5:.25;s=J(s,0,o),n=J(n,0,o),this._offsets={start:s,end:n,factor:1/(s+1+n)}}_generate(){const t=this._adapter,e=this.min,i=this.max,s=this.options,n=s.time,o=n.unit||Bo(n.minUnit,e,i,this._getLabelCapacity(e)),a=l(s.ticks.stepSize,1),r="week"===o&&n.isoWeekday,h=N(r)||!0===r,c={};let d,u,f=e;if(h&&(f=+t.startOf(f,"isoWeek",r)),f=+t.startOf(f,h?"day":o),t.diff(i,e,o)>1e5*a)throw new Error(e+" and "+i+" are too far apart with stepSize of "+a+" "+o);const g="data"===s.ticks.source&&this.getDataTimestamps();for(d=f,u=0;d<i;d=+t.add(d,a,o),u++)Wo(c,d,g);return d!==i&&"ticks"!==s.bounds&&1!==u||Wo(c,d,g),Object.keys(c).sort(Fo).map((t=>+t))}getLabelForValue(t){const e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){const i=this.options.time.displayFormats,s=this._unit,n=e||i[s];return this._adapter.format(t,n)}_tickFormatFunction(t,e,i,s){const n=this.options,o=n.ticks.callback;if(o)return d(o,[t,e,i],this);const a=n.time.displayFormats,r=this._unit,l=this._majorUnit,h=r&&a[r],c=l&&a[l],u=i[e],f=l&&c&&u&&u.major;return this._adapter.format(t,s||(f?c:h))}generateTickLabels(t){let e,i,s;for(e=0,i=t.length;e<i;++e)s=t[e],s.label=this._tickFormatFunction(s.value,e,t)}getDecimalForValue(t){return null===t?NaN:(t-this.min)/(this.max-this.min)}getPixelForValue(t){const e=this._offsets,i=this.getDecimalForValue(t);return this.getPixelForDecimal((e.start+i)*e.factor)}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return this.min+i*(this.max-this.min)}_getLabelSize(t){const e=this.options.ticks,i=this.ctx.measureText(t).width,s=$(this.isHorizontal()?e.maxRotation:e.minRotation),n=Math.cos(s),o=Math.sin(s),a=this._resolveTickFontOptions(0).size;return{w:i*n+a*o,h:i*o+a*n}}_getLabelCapacity(t){const e=this.options.time,i=e.displayFormats,s=i[e.unit]||i.millisecond,n=this._tickFormatFunction(t,0,No(this,[t],this._majorUnit),s),o=this._getLabelSize(n),a=Math.floor(this.isHorizontal()?this.width/o.w:this.height/o.h)-1;return a>0?a:1}getDataTimestamps(){let t,e,i=this._cache.data||[];if(i.length)return i;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(t=0,e=s.length;t<e;++t)i=i.concat(s[t].controller.getAllParsedValues(this));return this._cache.data=this.normalize(i)}getLabelTimestamps(){const t=this._cache.labels||[];let e,i;if(t.length)return t;const s=this.getLabels();for(e=0,i=s.length;e<i;++e)t.push(Vo(this,s[e]));return this._cache.labels=this._normalized?t:this.normalize(t)}normalize(t){return lt(t.sort(Fo))}}function jo(t,e,i){let s,n,o,a,r=0,l=t.length-1;i?(e>=t[r].pos&&e<=t[l].pos&&({lo:r,hi:l}=it(t,"pos",e)),({pos:s,time:o}=t[r]),({pos:n,time:a}=t[l])):(e>=t[r].time&&e<=t[l].time&&({lo:r,hi:l}=it(t,"time",e)),({time:s,pos:o}=t[r]),({time:n,pos:a}=t[l]));const h=n-s;return h?o+(a-o)*(e-s)/h:o}var $o=Object.freeze({__proto__:null,CategoryScale:class extends tn{static id="category";static defaults={ticks:{callback:mo}};constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const e=this._addedLabels;if(e.length){const t=this.getLabels();for(const{index:i,label:s}of e)t[i]===s&&t.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(s(t))return null;const i=this.getLabels();return((t,e)=>null===t?null:J(Math.round(t),0,e))(e=isFinite(e)&&i[e]===t?e:po(i,t,l(e,t),this._addedLabels),i.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:i,max:s}=this.getMinMax(!0);"ticks"===this.options.bounds&&(t||(i=0),e||(s=this.getLabels().length-1)),this.min=i,this.max=s}buildTicks(){const t=this.min,e=this.max,i=this.options.offset,s=[];let n=this.getLabels();n=0===t&&e===n.length-1?n:n.slice(t,e+1),this._valueRange=Math.max(n.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let i=t;i<=e;i++)s.push({value:i});return s}getLabelForValue(t){return mo.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return"number"!=typeof t&&(t=this.parse(t)),null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}},LinearScale:_o,LogarithmicScale:So,RadialLinearScale:Ro,TimeScale:Ho,TimeSeriesScale:class extends Ho{static id="timeseries";static defaults=Ho.defaults;constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=jo(e,this.min),this._tableRange=jo(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:i}=this,s=[],n=[];let o,a,r,l,h;for(o=0,a=t.length;o<a;++o)l=t[o],l>=e&&l<=i&&s.push(l);if(s.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(o=0,a=s.length;o<a;++o)h=s[o+1],r=s[o-1],l=s[o],Math.round((h+r)/2)!==l&&n.push({time:l,pos:o/(a-1)});return n}_generate(){const t=this.min,e=this.max;let i=super.getDataTimestamps();return i.includes(t)&&i.length||i.splice(0,0,t),i.includes(e)&&1!==i.length||i.push(e),i.sort(((t,e)=>t-e))}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;const e=this.getDataTimestamps(),i=this.getLabelTimestamps();return t=e.length&&i.length?this.normalize(e.concat(i)):e.length?e:i,t=this._cache.all=t,t}getDecimalForValue(t){return(jo(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return jo(this._table,i*this._tableRange+this._minPos,!0)}}});const Yo=["rgb(54, 162, 235)","rgb(255, 99, 132)","rgb(255, 159, 64)","rgb(255, 205, 86)","rgb(75, 192, 192)","rgb(153, 102, 255)","rgb(201, 203, 207)"],Uo=Yo.map((t=>t.replace("rgb(","rgba(").replace(")",", 0.5)")));function Xo(t){return Yo[t%Yo.length]}function qo(t){return Uo[t%Uo.length]}function Ko(t){let e=0;return(i,s)=>{const n=t.getDatasetMeta(s).controller;n instanceof $n?e=function(t,e){return t.backgroundColor=t.data.map((()=>Xo(e++))),e}(i,e):n instanceof Yn?e=function(t,e){return t.backgroundColor=t.data.map((()=>qo(e++))),e}(i,e):n&&(e=function(t,e){return t.borderColor=Xo(e),t.backgroundColor=qo(e),++e}(i,e))}}function Go(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return!0;return!1}var Zo={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,i){if(!i.enabled)return;const{data:{datasets:s},options:n}=t.config,{elements:o}=n,a=Go(s)||(r=n)&&(r.borderColor||r.backgroundColor)||o&&Go(o)||"rgba(0,0,0,0.1)"!==ue.borderColor||"rgba(0,0,0,0.1)"!==ue.backgroundColor;var r;if(!i.forceOverride&&a)return;const l=Ko(t);s.forEach(l)}};function Jo(t){if(t._decimated){const e=t._data;delete t._decimated,delete t._data,Object.defineProperty(t,"data",{configurable:!0,enumerable:!0,writable:!0,value:e})}}function Qo(t){t.data.datasets.forEach((t=>{Jo(t)}))}var ta={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(t,e,i)=>{if(!i.enabled)return void Qo(t);const n=t.width;t.data.datasets.forEach(((e,o)=>{const{_data:a,indexAxis:r}=e,l=t.getDatasetMeta(o),h=a||e.data;if("y"===Pi([r,t.options.indexAxis]))return;if(!l.controller.supportsDecimation)return;const c=t.scales[l.xAxisID];if("linear"!==c.type&&"time"!==c.type)return;if(t.options.parsing)return;let{start:d,count:u}=function(t,e){const i=e.length;let s,n=0;const{iScale:o}=t,{min:a,max:r,minDefined:l,maxDefined:h}=o.getUserBounds();return l&&(n=J(it(e,o.axis,a).lo,0,i-1)),s=h?J(it(e,o.axis,r).hi+1,n,i)-n:i-n,{start:n,count:s}}(l,h);if(u<=(i.threshold||4*n))return void Jo(e);let f;switch(s(a)&&(e._data=h,delete e.data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),i.algorithm){case"lttb":f=function(t,e,i,s,n){const o=n.samples||s;if(o>=i)return t.slice(e,e+i);const a=[],r=(i-2)/(o-2);let l=0;const h=e+i-1;let c,d,u,f,g,p=e;for(a[l++]=t[p],c=0;c<o-2;c++){let s,n=0,o=0;const h=Math.floor((c+1)*r)+1+e,m=Math.min(Math.floor((c+2)*r)+1,i)+e,x=m-h;for(s=h;s<m;s++)n+=t[s].x,o+=t[s].y;n/=x,o/=x;const b=Math.floor(c*r)+1+e,_=Math.min(Math.floor((c+1)*r)+1,i)+e,{x:y,y:v}=t[p];for(u=f=-1,s=b;s<_;s++)f=.5*Math.abs((y-n)*(t[s].y-v)-(y-t[s].x)*(o-v)),f>u&&(u=f,d=t[s],g=s);a[l++]=d,p=g}return a[l++]=t[h],a}(h,d,u,n,i);break;case"min-max":f=function(t,e,i,n){let o,a,r,l,h,c,d,u,f,g,p=0,m=0;const x=[],b=e+i-1,_=t[e].x,y=t[b].x-_;for(o=e;o<e+i;++o){a=t[o],r=(a.x-_)/y*n,l=a.y;const e=0|r;if(e===h)l<f?(f=l,c=o):l>g&&(g=l,d=o),p=(m*p+a.x)/++m;else{const i=o-1;if(!s(c)&&!s(d)){const e=Math.min(c,d),s=Math.max(c,d);e!==u&&e!==i&&x.push({...t[e],x:p}),s!==u&&s!==i&&x.push({...t[s],x:p})}o>0&&i!==u&&x.push(t[i]),x.push(a),h=e,m=0,f=g=l,c=d=u=o}}return x}(h,d,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${i.algorithm}'`)}e._decimated=f}))},destroy(t){Qo(t)}};function ea(t,e,i,s){if(s)return;let n=e[t],o=i[t];return"angle"===t&&(n=G(n),o=G(o)),{property:t,start:n,end:o}}function ia(t,e,i){for(;e>t;e--){const t=i[e];if(!isNaN(t.x)&&!isNaN(t.y))break}return e}function sa(t,e,i,s){return t&&e?s(t[i],e[i]):t?t[i]:e?e[i]:0}function na(t,e){let i=[],s=!1;return n(t)?(s=!0,i=t):i=function(t,e){const{x:i=null,y:s=null}=t||{},n=e.points,o=[];return e.segments.forEach((({start:t,end:e})=>{e=ia(t,e,n);const a=n[t],r=n[e];null!==s?(o.push({x:a.x,y:s}),o.push({x:r.x,y:s})):null!==i&&(o.push({x:i,y:a.y}),o.push({x:i,y:r.y}))})),o}(t,e),i.length?new oo({points:i,options:{tension:0},_loop:s,_fullLoop:s}):null}function oa(t){return t&&!1!==t.fill}function aa(t,e,i){let s=t[e].fill;const n=[e];let o;if(!i)return s;for(;!1!==s&&-1===n.indexOf(s);){if(!a(s))return s;if(o=t[s],!o)return!1;if(o.visible)return s;n.push(s),s=o.fill}return!1}function ra(t,e,i){const s=function(t){const e=t.options,i=e.fill;let s=l(i&&i.target,i);void 0===s&&(s=!!e.backgroundColor);if(!1===s||null===s)return!1;if(!0===s)return"origin";return s}(t);if(o(s))return!isNaN(s.value)&&s;let n=parseFloat(s);return a(n)&&Math.floor(n)===n?function(t,e,i,s){"-"!==t&&"+"!==t||(i=e+i);if(i===e||i<0||i>=s)return!1;return i}(s[0],e,n,i):["origin","start","end","stack","shape"].indexOf(s)>=0&&s}function la(t,e,i){const s=[];for(let n=0;n<i.length;n++){const o=i[n],{first:a,last:r,point:l}=ha(o,e,"x");if(!(!l||a&&r))if(a)s.unshift(l);else if(t.push(l),!r)break}t.push(...s)}function ha(t,e,i){const s=t.interpolate(e,i);if(!s)return{};const n=s[i],o=t.segments,a=t.points;let r=!1,l=!1;for(let t=0;t<o.length;t++){const e=o[t],s=a[e.start][i],h=a[e.end][i];if(tt(n,s,h)){r=n===s,l=n===h;break}}return{first:r,last:l,point:s}}class ca{constructor(t){this.x=t.x,this.y=t.y,this.radius=t.radius}pathSegment(t,e,i){const{x:s,y:n,radius:o}=this;return e=e||{start:0,end:O},t.arc(s,n,o,e.end,e.start,!0),!i.bounds}interpolate(t){const{x:e,y:i,radius:s}=this,n=t.angle;return{x:e+Math.cos(n)*s,y:i+Math.sin(n)*s,angle:n}}}function da(t){const{chart:e,fill:i,line:s}=t;if(a(i))return function(t,e){const i=t.getDatasetMeta(e),s=i&&t.isDatasetVisible(e);return s?i.dataset:null}(e,i);if("stack"===i)return function(t){const{scale:e,index:i,line:s}=t,n=[],o=s.segments,a=s.points,r=function(t,e){const i=[],s=t.getMatchingVisibleMetas("line");for(let t=0;t<s.length;t++){const n=s[t];if(n.index===e)break;n.hidden||i.unshift(n.dataset)}return i}(e,i);r.push(na({x:null,y:e.bottom},s));for(let t=0;t<o.length;t++){const e=o[t];for(let t=e.start;t<=e.end;t++)la(n,a[t],r)}return new oo({points:n,options:{}})}(t);if("shape"===i)return!0;const n=function(t){const e=t.scale||{};if(e.getPointPositionForValue)return function(t){const{scale:e,fill:i}=t,s=e.options,n=e.getLabels().length,a=s.reverse?e.max:e.min,r=function(t,e,i){let s;return s="start"===t?i:"end"===t?e.options.reverse?e.min:e.max:o(t)?t.value:e.getBaseValue(),s}(i,e,a),l=[];if(s.grid.circular){const t=e.getPointPositionForValue(0,a);return new ca({x:t.x,y:t.y,radius:e.getDistanceFromCenterForValue(r)})}for(let t=0;t<n;++t)l.push(e.getPointPositionForValue(t,r));return l}(t);return function(t){const{scale:e={},fill:i}=t,s=function(t,e){let i=null;return"start"===t?i=e.bottom:"end"===t?i=e.top:o(t)?i=e.getPixelForValue(t.value):e.getBasePixel&&(i=e.getBasePixel()),i}(i,e);if(a(s)){const t=e.isHorizontal();return{x:t?s:null,y:t?null:s}}return null}(t)}(t);return n instanceof ca?n:na(n,s)}function ua(t,e,i){const s=da(e),{chart:n,index:o,line:a,scale:r,axis:l}=e,h=a.options,c=h.fill,d=h.backgroundColor,{above:u=d,below:f=d}=c||{},g=n.getDatasetMeta(o),p=Ni(n,g);s&&a.points.length&&(Ie(t,i),function(t,e){const{line:i,target:s,above:n,below:o,area:a,scale:r,clip:l}=e,h=i._loop?"angle":e.axis;t.save(),"x"===h&&o!==n&&(fa(t,s,a.top),ga(t,{line:i,target:s,color:n,scale:r,property:h,clip:l}),t.restore(),t.save(),fa(t,s,a.bottom));ga(t,{line:i,target:s,color:o,scale:r,property:h,clip:l}),t.restore()}(t,{line:a,target:s,above:u,below:f,area:i,scale:r,axis:l,clip:p}),ze(t))}function fa(t,e,i){const{segments:s,points:n}=e;let o=!0,a=!1;t.beginPath();for(const r of s){const{start:s,end:l}=r,h=n[s],c=n[ia(s,l,n)];o?(t.moveTo(h.x,h.y),o=!1):(t.lineTo(h.x,i),t.lineTo(h.x,h.y)),a=!!e.pathSegment(t,r,{move:a}),a?t.closePath():t.lineTo(c.x,i)}t.lineTo(e.first().x,i),t.closePath(),t.clip()}function ga(t,e){const{line:i,target:s,property:n,color:o,scale:a,clip:r}=e,l=function(t,e,i){const s=t.segments,n=t.points,o=e.points,a=[];for(const t of s){let{start:s,end:r}=t;r=ia(s,r,n);const l=ea(i,n[s],n[r],t.loop);if(!e.segments){a.push({source:t,target:l,start:n[s],end:n[r]});continue}const h=Ii(e,l);for(const e of h){const s=ea(i,o[e.start],o[e.end],e.loop),r=Ri(t,n,s);for(const t of r)a.push({source:t,target:e,start:{[i]:sa(l,s,"start",Math.max)},end:{[i]:sa(l,s,"end",Math.min)}})}}return a}(i,s,n);for(const{source:e,target:h,start:c,end:d}of l){const{style:{backgroundColor:l=o}={}}=e,u=!0!==s;t.save(),t.fillStyle=l,pa(t,a,r,u&&ea(n,c,d)),t.beginPath();const f=!!i.pathSegment(t,e);let g;if(u){f?t.closePath():ma(t,s,d,n);const e=!!s.pathSegment(t,h,{move:f,reverse:!0});g=f&&e,g||ma(t,s,c,n)}t.closePath(),t.fill(g?"evenodd":"nonzero"),t.restore()}}function pa(t,e,i,s){const n=e.chart.chartArea,{property:o,start:a,end:r}=s||{};if("x"===o||"y"===o){let e,s,l,h;"x"===o?(e=a,s=n.top,l=r,h=n.bottom):(e=n.left,s=a,l=n.right,h=r),t.beginPath(),i&&(e=Math.max(e,i.left),l=Math.min(l,i.right),s=Math.max(s,i.top),h=Math.min(h,i.bottom)),t.rect(e,s,l-e,h-s),t.clip()}}function ma(t,e,i,s){const n=e.interpolate(i,s);n&&t.lineTo(n.x,n.y)}var xa={id:"filler",afterDatasetsUpdate(t,e,i){const s=(t.data.datasets||[]).length,n=[];let o,a,r,l;for(a=0;a<s;++a)o=t.getDatasetMeta(a),r=o.dataset,l=null,r&&r.options&&r instanceof oo&&(l={visible:t.isDatasetVisible(a),index:a,fill:ra(r,a,s),chart:t,axis:o.controller.options.indexAxis,scale:o.vScale,line:r}),o.$filler=l,n.push(l);for(a=0;a<s;++a)l=n[a],l&&!1!==l.fill&&(l.fill=aa(n,a,i.propagate))},beforeDraw(t,e,i){const s="beforeDraw"===i.drawTime,n=t.getSortedVisibleDatasetMetas(),o=t.chartArea;for(let e=n.length-1;e>=0;--e){const i=n[e].$filler;i&&(i.line.updateControlPoints(o,i.axis),s&&i.fill&&ua(t.ctx,i,o))}},beforeDatasetsDraw(t,e,i){if("beforeDatasetsDraw"!==i.drawTime)return;const s=t.getSortedVisibleDatasetMetas();for(let e=s.length-1;e>=0;--e){const i=s[e].$filler;oa(i)&&ua(t.ctx,i,t.chartArea)}},beforeDatasetDraw(t,e,i){const s=e.meta.$filler;oa(s)&&"beforeDatasetDraw"===i.drawTime&&ua(t.ctx,s,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const ba=(t,e)=>{let{boxHeight:i=e,boxWidth:s=e}=t;return t.usePointStyle&&(i=Math.min(i,e),s=t.pointStyleWidth||Math.min(s,e)),{boxWidth:s,boxHeight:i,itemHeight:Math.max(e,i)}};class _a extends $s{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let e=d(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter((e=>t.filter(e,this.chart.data)))),t.sort&&(e=e.sort(((e,i)=>t.sort(e,i,this.chart.data)))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){const{options:t,ctx:e}=this;if(!t.display)return void(this.width=this.height=0);const i=t.labels,s=Si(i.font),n=s.size,o=this._computeTitleHeight(),{boxWidth:a,itemHeight:r}=ba(i,n);let l,h;e.font=s.string,this.isHorizontal()?(l=this.maxWidth,h=this._fitRows(o,n,a,r)+10):(h=this.maxHeight,l=this._fitCols(o,s,a,r)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(h,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,s){const{ctx:n,maxWidth:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.lineWidths=[0],h=s+a;let c=t;n.textAlign="left",n.textBaseline="middle";let d=-1,u=-h;return this.legendItems.forEach(((t,f)=>{const g=i+e/2+n.measureText(t.text).width;(0===f||l[l.length-1]+g+2*a>o)&&(c+=h,l[l.length-(f>0?0:1)]=0,u+=h,d++),r[f]={left:0,top:u,row:d,width:g,height:s},l[l.length-1]+=g+a})),c}_fitCols(t,e,i,s){const{ctx:n,maxHeight:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.columnSizes=[],h=o-t;let c=a,d=0,u=0,f=0,g=0;return this.legendItems.forEach(((t,o)=>{const{itemWidth:p,itemHeight:m}=function(t,e,i,s,n){const o=function(t,e,i,s){let n=t.text;n&&"string"!=typeof n&&(n=n.reduce(((t,e)=>t.length>e.length?t:e)));return e+i.size/2+s.measureText(n).width}(s,t,e,i),a=function(t,e,i){let s=t;"string"!=typeof e.text&&(s=ya(e,i));return s}(n,s,e.lineHeight);return{itemWidth:o,itemHeight:a}}(i,e,n,t,s);o>0&&u+m+2*a>h&&(c+=d+a,l.push({width:d,height:u}),f+=d+a,g++,d=u=0),r[o]={left:f,top:u,col:g,width:p,height:m},d=Math.max(d,p),u+=m+a})),c+=d,l.push({width:d,height:u}),c}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:s},rtl:n}}=this,o=Oi(n,this.left,this.width);if(this.isHorizontal()){let n=0,a=ft(i,this.left+s,this.right-this.lineWidths[n]);for(const r of e)n!==r.row&&(n=r.row,a=ft(i,this.left+s,this.right-this.lineWidths[n])),r.top+=this.top+t+s,r.left=o.leftForLtr(o.x(a),r.width),a+=r.width+s}else{let n=0,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height);for(const r of e)r.col!==n&&(n=r.col,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height)),r.top=a,r.left+=this.left+s,r.left=o.leftForLtr(o.x(r.left),r.width),a+=r.height+s}}isHorizontal(){return"top"===this.options.position||"bottom"===this.options.position}draw(){if(this.options.display){const t=this.ctx;Ie(t,this),this._draw(),ze(t)}}_draw(){const{options:t,columnSizes:e,lineWidths:i,ctx:s}=this,{align:n,labels:o}=t,a=ue.color,r=Oi(t.rtl,this.left,this.width),h=Si(o.font),{padding:c}=o,d=h.size,u=d/2;let f;this.drawTitle(),s.textAlign=r.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=h.string;const{boxWidth:g,boxHeight:p,itemHeight:m}=ba(o,d),x=this.isHorizontal(),b=this._computeTitleHeight();f=x?{x:ft(n,this.left+c,this.right-i[0]),y:this.top+c+b,line:0}:{x:this.left+c,y:ft(n,this.top+b+c,this.bottom-e[0].height),line:0},Ai(this.ctx,t.textDirection);const _=m+c;this.legendItems.forEach(((y,v)=>{s.strokeStyle=y.fontColor,s.fillStyle=y.fontColor;const M=s.measureText(y.text).width,w=r.textAlign(y.textAlign||(y.textAlign=o.textAlign)),k=g+u+M;let S=f.x,P=f.y;r.setWidth(this.width),x?v>0&&S+k+c>this.right&&(P=f.y+=_,f.line++,S=f.x=ft(n,this.left+c,this.right-i[f.line])):v>0&&P+_>this.bottom&&(S=f.x=S+e[f.line].width+c,f.line++,P=f.y=ft(n,this.top+b+c,this.bottom-e[f.line].height));if(function(t,e,i){if(isNaN(g)||g<=0||isNaN(p)||p<0)return;s.save();const n=l(i.lineWidth,1);if(s.fillStyle=l(i.fillStyle,a),s.lineCap=l(i.lineCap,"butt"),s.lineDashOffset=l(i.lineDashOffset,0),s.lineJoin=l(i.lineJoin,"miter"),s.lineWidth=n,s.strokeStyle=l(i.strokeStyle,a),s.setLineDash(l(i.lineDash,[])),o.usePointStyle){const a={radius:p*Math.SQRT2/2,pointStyle:i.pointStyle,rotation:i.rotation,borderWidth:n},l=r.xPlus(t,g/2);Ee(s,a,l,e+u,o.pointStyleWidth&&g)}else{const o=e+Math.max((d-p)/2,0),a=r.leftForLtr(t,g),l=wi(i.borderRadius);s.beginPath(),Object.values(l).some((t=>0!==t))?He(s,{x:a,y:o,w:g,h:p,radius:l}):s.rect(a,o,g,p),s.fill(),0!==n&&s.stroke()}s.restore()}(r.x(S),P,y),S=gt(w,S+g+u,x?S+k:this.right,t.rtl),function(t,e,i){Ne(s,i.text,t,e+m/2,h,{strikethrough:i.hidden,textAlign:r.textAlign(i.textAlign)})}(r.x(S),P,y),x)f.x+=k+c;else if("string"!=typeof y.text){const t=h.lineHeight;f.y+=ya(y,t)+c}else f.y+=_})),Ti(this.ctx,t.textDirection)}drawTitle(){const t=this.options,e=t.title,i=Si(e.font),s=ki(e.padding);if(!e.display)return;const n=Oi(t.rtl,this.left,this.width),o=this.ctx,a=e.position,r=i.size/2,l=s.top+r;let h,c=this.left,d=this.width;if(this.isHorizontal())d=Math.max(...this.lineWidths),h=this.top+l,c=ft(t.align,c,this.right-d);else{const e=this.columnSizes.reduce(((t,e)=>Math.max(t,e.height)),0);h=l+ft(t.align,this.top,this.bottom-e-t.labels.padding-this._computeTitleHeight())}const u=ft(a,c,c+d);o.textAlign=n.textAlign(ut(a)),o.textBaseline="middle",o.strokeStyle=e.color,o.fillStyle=e.color,o.font=i.string,Ne(o,e.text,u,h,i)}_computeTitleHeight(){const t=this.options.title,e=Si(t.font),i=ki(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,s,n;if(tt(t,this.left,this.right)&&tt(e,this.top,this.bottom))for(n=this.legendHitBoxes,i=0;i<n.length;++i)if(s=n[i],tt(t,s.left,s.left+s.width)&&tt(e,s.top,s.top+s.height))return this.legendItems[i];return null}handleEvent(t){const e=this.options;if(!function(t,e){if(("mousemove"===t||"mouseout"===t)&&(e.onHover||e.onLeave))return!0;if(e.onClick&&("click"===t||"mouseup"===t))return!0;return!1}(t.type,e))return;const i=this._getLegendItemAt(t.x,t.y);if("mousemove"===t.type||"mouseout"===t.type){const o=this._hoveredItem,a=(n=i,null!==(s=o)&&null!==n&&s.datasetIndex===n.datasetIndex&&s.index===n.index);o&&!a&&d(e.onLeave,[t,o,this],this),this._hoveredItem=i,i&&!a&&d(e.onHover,[t,i,this],this)}else i&&d(e.onClick,[t,i,this],this);var s,n}}function ya(t,e){return e*(t.text?t.text.length:0)}var va={id:"legend",_element:_a,start(t,e,i){const s=t.legend=new _a({ctx:t.ctx,options:i,chart:t});ls.configure(t,s,i),ls.addBox(t,s)},stop(t){ls.removeBox(t,t.legend),delete t.legend},beforeUpdate(t,e,i){const s=t.legend;ls.configure(t,s,i),s.options=i},afterUpdate(t){const e=t.legend;e.buildLabels(),e.adjustHitBoxes()},afterEvent(t,e){e.replay||t.legend.handleEvent(e.event)},defaults:{display:!0,position:"top",align:"center",fullSize:!0,reverse:!1,weight:1e3,onClick(t,e,i){const s=e.datasetIndex,n=i.chart;n.isDatasetVisible(s)?(n.hide(s),e.hidden=!0):(n.show(s),e.hidden=!1)},onHover:null,onLeave:null,labels:{color:t=>t.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:i,pointStyle:s,textAlign:n,color:o,useBorderRadius:a,borderRadius:r}}=t.legend.options;return t._getSortedDatasetMetas().map((t=>{const l=t.controller.getStyle(i?0:void 0),h=ki(l.borderWidth);return{text:e[t.index].label,fillStyle:l.backgroundColor,fontColor:o,hidden:!t.visible,lineCap:l.borderCapStyle,lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:(h.width+h.height)/4,strokeStyle:l.borderColor,pointStyle:s||l.pointStyle,rotation:l.rotation,textAlign:n||l.textAlign,borderRadius:a&&(r||l.borderRadius),datasetIndex:t.index}}),this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class Ma extends $s{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){const i=this.options;if(this.left=0,this.top=0,!i.display)return void(this.width=this.height=this.right=this.bottom=0);this.width=this.right=t,this.height=this.bottom=e;const s=n(i.text)?i.text.length:1;this._padding=ki(i.padding);const o=s*Si(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const t=this.options.position;return"top"===t||"bottom"===t}_drawArgs(t){const{top:e,left:i,bottom:s,right:n,options:o}=this,a=o.align;let r,l,h,c=0;return this.isHorizontal()?(l=ft(a,i,n),h=e+t,r=n-i):("left"===o.position?(l=i+t,h=ft(a,s,e),c=-.5*C):(l=n-t,h=ft(a,e,s),c=.5*C),r=s-e),{titleX:l,titleY:h,maxWidth:r,rotation:c}}draw(){const t=this.ctx,e=this.options;if(!e.display)return;const i=Si(e.font),s=i.lineHeight/2+this._padding.top,{titleX:n,titleY:o,maxWidth:a,rotation:r}=this._drawArgs(s);Ne(t,e.text,0,0,i,{color:e.color,maxWidth:a,rotation:r,textAlign:ut(e.align),textBaseline:"middle",translation:[n,o]})}}var wa={id:"title",_element:Ma,start(t,e,i){!function(t,e){const i=new Ma({ctx:t.ctx,options:e,chart:t});ls.configure(t,i,e),ls.addBox(t,i),t.titleBlock=i}(t,i)},stop(t){const e=t.titleBlock;ls.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,i){const s=t.titleBlock;ls.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const ka=new WeakMap;var Sa={id:"subtitle",start(t,e,i){const s=new Ma({ctx:t.ctx,options:i,chart:t});ls.configure(t,s,i),ls.addBox(t,s),ka.set(t,s)},stop(t){ls.removeBox(t,ka.get(t)),ka.delete(t)},beforeUpdate(t,e,i){const s=ka.get(t);ls.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Pa={average(t){if(!t.length)return!1;let e,i,s=new Set,n=0,o=0;for(e=0,i=t.length;e<i;++e){const i=t[e].element;if(i&&i.hasValue()){const t=i.tooltipPosition();s.add(t.x),n+=t.y,++o}}if(0===o||0===s.size)return!1;return{x:[...s].reduce(((t,e)=>t+e))/s.size,y:n/o}},nearest(t,e){if(!t.length)return!1;let i,s,n,o=e.x,a=e.y,r=Number.POSITIVE_INFINITY;for(i=0,s=t.length;i<s;++i){const s=t[i].element;if(s&&s.hasValue()){const t=q(e,s.getCenterPoint());t<r&&(r=t,n=s)}}if(n){const t=n.tooltipPosition();o=t.x,a=t.y}return{x:o,y:a}}};function Da(t,e){return e&&(n(e)?Array.prototype.push.apply(t,e):t.push(e)),t}function Ca(t){return("string"==typeof t||t instanceof String)&&t.indexOf("\n")>-1?t.split("\n"):t}function Oa(t,e){const{element:i,datasetIndex:s,index:n}=e,o=t.getDatasetMeta(s).controller,{label:a,value:r}=o.getLabelAndValue(n);return{chart:t,label:a,parsed:o.getParsed(n),raw:t.data.datasets[s].data[n],formattedValue:r,dataset:o.getDataset(),dataIndex:n,datasetIndex:s,element:i}}function Aa(t,e){const i=t.chart.ctx,{body:s,footer:n,title:o}=t,{boxWidth:a,boxHeight:r}=e,l=Si(e.bodyFont),h=Si(e.titleFont),c=Si(e.footerFont),d=o.length,f=n.length,g=s.length,p=ki(e.padding);let m=p.height,x=0,b=s.reduce(((t,e)=>t+e.before.length+e.lines.length+e.after.length),0);if(b+=t.beforeBody.length+t.afterBody.length,d&&(m+=d*h.lineHeight+(d-1)*e.titleSpacing+e.titleMarginBottom),b){m+=g*(e.displayColors?Math.max(r,l.lineHeight):l.lineHeight)+(b-g)*l.lineHeight+(b-1)*e.bodySpacing}f&&(m+=e.footerMarginTop+f*c.lineHeight+(f-1)*e.footerSpacing);let _=0;const y=function(t){x=Math.max(x,i.measureText(t).width+_)};return i.save(),i.font=h.string,u(t.title,y),i.font=l.string,u(t.beforeBody.concat(t.afterBody),y),_=e.displayColors?a+2+e.boxPadding:0,u(s,(t=>{u(t.before,y),u(t.lines,y),u(t.after,y)})),_=0,i.font=c.string,u(t.footer,y),i.restore(),x+=p.width,{width:x,height:m}}function Ta(t,e,i,s){const{x:n,width:o}=i,{width:a,chartArea:{left:r,right:l}}=t;let h="center";return"center"===s?h=n<=(r+l)/2?"left":"right":n<=o/2?h="left":n>=a-o/2&&(h="right"),function(t,e,i,s){const{x:n,width:o}=s,a=i.caretSize+i.caretPadding;return"left"===t&&n+o+a>e.width||"right"===t&&n-o-a<0||void 0}(h,t,e,i)&&(h="center"),h}function La(t,e,i){const s=i.yAlign||e.yAlign||function(t,e){const{y:i,height:s}=e;return i<s/2?"top":i>t.height-s/2?"bottom":"center"}(t,i);return{xAlign:i.xAlign||e.xAlign||Ta(t,e,i,s),yAlign:s}}function Ea(t,e,i,s){const{caretSize:n,caretPadding:o,cornerRadius:a}=t,{xAlign:r,yAlign:l}=i,h=n+o,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(a);let g=function(t,e){let{x:i,width:s}=t;return"right"===e?i-=s:"center"===e&&(i-=s/2),i}(e,r);const p=function(t,e,i){let{y:s,height:n}=t;return"top"===e?s+=i:s-="bottom"===e?n+i:n/2,s}(e,l,h);return"center"===l?"left"===r?g+=h:"right"===r&&(g-=h):"left"===r?g-=Math.max(c,u)+n:"right"===r&&(g+=Math.max(d,f)+n),{x:J(g,0,s.width-e.width),y:J(p,0,s.height-e.height)}}function Ra(t,e,i){const s=ki(i.padding);return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-s.right:t.x+s.left}function Ia(t){return Da([],Ca(t))}function za(t,e){const i=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return i?t.override(i):t}const Fa={beforeTitle:e,title(t){if(t.length>0){const e=t[0],i=e.chart.data.labels,s=i?i.length:0;if(this&&this.options&&"dataset"===this.options.mode)return e.dataset.label||"";if(e.label)return e.label;if(s>0&&e.dataIndex<s)return i[e.dataIndex]}return""},afterTitle:e,beforeBody:e,beforeLabel:e,label(t){if(this&&this.options&&"dataset"===this.options.mode)return t.label+": "+t.formattedValue||t.formattedValue;let e=t.dataset.label||"";e&&(e+=": ");const i=t.formattedValue;return s(i)||(e+=i),e},labelColor(t){const e=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{borderColor:e.borderColor,backgroundColor:e.backgroundColor,borderWidth:e.borderWidth,borderDash:e.borderDash,borderDashOffset:e.borderDashOffset,borderRadius:0}},labelTextColor(){return this.options.bodyColor},labelPointStyle(t){const e=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{pointStyle:e.pointStyle,rotation:e.rotation}},afterLabel:e,afterBody:e,beforeFooter:e,footer:e,afterFooter:e};function Va(t,e,i,s){const n=t[e].call(i,s);return void 0===n?Fa[e].call(i,s):n}class Ba extends $s{static positioners=Pa;constructor(t){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=t.chart,this.options=t.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(t){this.options=t,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const t=this._cachedAnimations;if(t)return t;const e=this.chart,i=this.options.setContext(this.getContext()),s=i.enabled&&e.options.animation&&i.animations,n=new Ts(this.chart,s);return s._cacheable&&(this._cachedAnimations=Object.freeze(n)),n}getContext(){return this.$context||(this.$context=(t=this.chart.getContext(),e=this,i=this._tooltipItems,Ci(t,{tooltip:e,tooltipItems:i,type:"tooltip"})));var t,e,i}getTitle(t,e){const{callbacks:i}=e,s=Va(i,"beforeTitle",this,t),n=Va(i,"title",this,t),o=Va(i,"afterTitle",this,t);let a=[];return a=Da(a,Ca(s)),a=Da(a,Ca(n)),a=Da(a,Ca(o)),a}getBeforeBody(t,e){return Ia(Va(e.callbacks,"beforeBody",this,t))}getBody(t,e){const{callbacks:i}=e,s=[];return u(t,(t=>{const e={before:[],lines:[],after:[]},n=za(i,t);Da(e.before,Ca(Va(n,"beforeLabel",this,t))),Da(e.lines,Va(n,"label",this,t)),Da(e.after,Ca(Va(n,"afterLabel",this,t))),s.push(e)})),s}getAfterBody(t,e){return Ia(Va(e.callbacks,"afterBody",this,t))}getFooter(t,e){const{callbacks:i}=e,s=Va(i,"beforeFooter",this,t),n=Va(i,"footer",this,t),o=Va(i,"afterFooter",this,t);let a=[];return a=Da(a,Ca(s)),a=Da(a,Ca(n)),a=Da(a,Ca(o)),a}_createItems(t){const e=this._active,i=this.chart.data,s=[],n=[],o=[];let a,r,l=[];for(a=0,r=e.length;a<r;++a)l.push(Oa(this.chart,e[a]));return t.filter&&(l=l.filter(((e,s,n)=>t.filter(e,s,n,i)))),t.itemSort&&(l=l.sort(((e,s)=>t.itemSort(e,s,i)))),u(l,(e=>{const i=za(t.callbacks,e);s.push(Va(i,"labelColor",this,e)),n.push(Va(i,"labelPointStyle",this,e)),o.push(Va(i,"labelTextColor",this,e))})),this.labelColors=s,this.labelPointStyles=n,this.labelTextColors=o,this.dataPoints=l,l}update(t,e){const i=this.options.setContext(this.getContext()),s=this._active;let n,o=[];if(s.length){const t=Pa[i.position].call(this,s,this._eventPosition);o=this._createItems(i),this.title=this.getTitle(o,i),this.beforeBody=this.getBeforeBody(o,i),this.body=this.getBody(o,i),this.afterBody=this.getAfterBody(o,i),this.footer=this.getFooter(o,i);const e=this._size=Aa(this,i),a=Object.assign({},t,e),r=La(this.chart,i,a),l=Ea(i,a,r,this.chart);this.xAlign=r.xAlign,this.yAlign=r.yAlign,n={opacity:1,x:l.x,y:l.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(n={opacity:0});this._tooltipItems=o,this.$context=void 0,n&&this._resolveAnimations().update(this,n),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,s){const n=this.getCaretPosition(t,i,s);e.lineTo(n.x1,n.y1),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3)}getCaretPosition(t,e,i){const{xAlign:s,yAlign:n}=this,{caretSize:o,cornerRadius:a}=i,{topLeft:r,topRight:l,bottomLeft:h,bottomRight:c}=wi(a),{x:d,y:u}=t,{width:f,height:g}=e;let p,m,x,b,_,y;return"center"===n?(_=u+g/2,"left"===s?(p=d,m=p-o,b=_+o,y=_-o):(p=d+f,m=p+o,b=_-o,y=_+o),x=p):(m="left"===s?d+Math.max(r,h)+o:"right"===s?d+f-Math.max(l,c)-o:this.caretX,"top"===n?(b=u,_=b-o,p=m-o,x=m+o):(b=u+g,_=b+o,p=m+o,x=m-o),y=b),{x1:p,x2:m,x3:x,y1:b,y2:_,y3:y}}drawTitle(t,e,i){const s=this.title,n=s.length;let o,a,r;if(n){const l=Oi(i.rtl,this.x,this.width);for(t.x=Ra(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",o=Si(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=o.string,r=0;r<n;++r)e.fillText(s[r],l.x(t.x),t.y+o.lineHeight/2),t.y+=o.lineHeight+a,r+1===n&&(t.y+=i.titleMarginBottom-a)}}_drawColorBox(t,e,i,s,n){const a=this.labelColors[i],r=this.labelPointStyles[i],{boxHeight:l,boxWidth:h}=n,c=Si(n.bodyFont),d=Ra(this,"left",n),u=s.x(d),f=l<c.lineHeight?(c.lineHeight-l)/2:0,g=e.y+f;if(n.usePointStyle){const e={radius:Math.min(h,l)/2,pointStyle:r.pointStyle,rotation:r.rotation,borderWidth:1},i=s.leftForLtr(u,h)+h/2,o=g+l/2;t.strokeStyle=n.multiKeyBackground,t.fillStyle=n.multiKeyBackground,Le(t,e,i,o),t.strokeStyle=a.borderColor,t.fillStyle=a.backgroundColor,Le(t,e,i,o)}else{t.lineWidth=o(a.borderWidth)?Math.max(...Object.values(a.borderWidth)):a.borderWidth||1,t.strokeStyle=a.borderColor,t.setLineDash(a.borderDash||[]),t.lineDashOffset=a.borderDashOffset||0;const e=s.leftForLtr(u,h),i=s.leftForLtr(s.xPlus(u,1),h-2),r=wi(a.borderRadius);Object.values(r).some((t=>0!==t))?(t.beginPath(),t.fillStyle=n.multiKeyBackground,He(t,{x:e,y:g,w:h,h:l,radius:r}),t.fill(),t.stroke(),t.fillStyle=a.backgroundColor,t.beginPath(),He(t,{x:i,y:g+1,w:h-2,h:l-2,radius:r}),t.fill()):(t.fillStyle=n.multiKeyBackground,t.fillRect(e,g,h,l),t.strokeRect(e,g,h,l),t.fillStyle=a.backgroundColor,t.fillRect(i,g+1,h-2,l-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){const{body:s}=this,{bodySpacing:n,bodyAlign:o,displayColors:a,boxHeight:r,boxWidth:l,boxPadding:h}=i,c=Si(i.bodyFont);let d=c.lineHeight,f=0;const g=Oi(i.rtl,this.x,this.width),p=function(i){e.fillText(i,g.x(t.x+f),t.y+d/2),t.y+=d+n},m=g.textAlign(o);let x,b,_,y,v,M,w;for(e.textAlign=o,e.textBaseline="middle",e.font=c.string,t.x=Ra(this,m,i),e.fillStyle=i.bodyColor,u(this.beforeBody,p),f=a&&"right"!==m?"center"===o?l/2+h:l+2+h:0,y=0,M=s.length;y<M;++y){for(x=s[y],b=this.labelTextColors[y],e.fillStyle=b,u(x.before,p),_=x.lines,a&&_.length&&(this._drawColorBox(e,t,y,g,i),d=Math.max(c.lineHeight,r)),v=0,w=_.length;v<w;++v)p(_[v]),d=c.lineHeight;u(x.after,p)}f=0,d=c.lineHeight,u(this.afterBody,p),t.y-=n}drawFooter(t,e,i){const s=this.footer,n=s.length;let o,a;if(n){const r=Oi(i.rtl,this.x,this.width);for(t.x=Ra(this,i.footerAlign,i),t.y+=i.footerMarginTop,e.textAlign=r.textAlign(i.footerAlign),e.textBaseline="middle",o=Si(i.footerFont),e.fillStyle=i.footerColor,e.font=o.string,a=0;a<n;++a)e.fillText(s[a],r.x(t.x),t.y+o.lineHeight/2),t.y+=o.lineHeight+i.footerSpacing}}drawBackground(t,e,i,s){const{xAlign:n,yAlign:o}=this,{x:a,y:r}=t,{width:l,height:h}=i,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(s.cornerRadius);e.fillStyle=s.backgroundColor,e.strokeStyle=s.borderColor,e.lineWidth=s.borderWidth,e.beginPath(),e.moveTo(a+c,r),"top"===o&&this.drawCaret(t,e,i,s),e.lineTo(a+l-d,r),e.quadraticCurveTo(a+l,r,a+l,r+d),"center"===o&&"right"===n&&this.drawCaret(t,e,i,s),e.lineTo(a+l,r+h-f),e.quadraticCurveTo(a+l,r+h,a+l-f,r+h),"bottom"===o&&this.drawCaret(t,e,i,s),e.lineTo(a+u,r+h),e.quadraticCurveTo(a,r+h,a,r+h-u),"center"===o&&"left"===n&&this.drawCaret(t,e,i,s),e.lineTo(a,r+c),e.quadraticCurveTo(a,r,a+c,r),e.closePath(),e.fill(),s.borderWidth>0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,i=this.$animations,s=i&&i.x,n=i&&i.y;if(s||n){const i=Pa[t.position].call(this,this._active,this._eventPosition);if(!i)return;const o=this._size=Aa(this,t),a=Object.assign({},i,this._size),r=La(e,t,a),l=Ea(t,a,r,e);s._to===l.x&&n._to===l.y||(this.xAlign=r.xAlign,this.yAlign=r.yAlign,this.width=o.width,this.height=o.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,l))}}_willRender(){return!!this.opacity}draw(t){const e=this.options.setContext(this.getContext());let i=this.opacity;if(!i)return;this._updateAnimationTarget(e);const s={width:this.width,height:this.height},n={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;const o=ki(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(n,t,s,e),Ai(t,e.textDirection),n.y+=o.top,this.drawTitle(n,t,e),this.drawBody(n,t,e),this.drawFooter(n,t,e),Ti(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){const i=this._active,s=t.map((({datasetIndex:t,index:e})=>{const i=this.chart.getDatasetMeta(t);if(!i)throw new Error("Cannot find a dataset at index "+t);return{datasetIndex:t,element:i.data[e],index:e}})),n=!f(i,s),o=this._positionChanged(s,e);(n||o)&&(this._active=s,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,n=this._active||[],o=this._getActiveElements(t,n,e,i),a=this._positionChanged(o,t),r=e||!f(o,n)||a;return r&&(this._active=o,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),r}_getActiveElements(t,e,i,s){const n=this.options;if("mouseout"===t.type)return[];if(!s)return e.filter((t=>this.chart.data.datasets[t.datasetIndex]&&void 0!==this.chart.getDatasetMeta(t.datasetIndex).controller.getParsed(t.index)));const o=this.chart.getElementsAtEventForMode(t,n.mode,n,i);return n.reverse&&o.reverse(),o}_positionChanged(t,e){const{caretX:i,caretY:s,options:n}=this,o=Pa[n.position].call(this,t,e);return!1!==o&&(i!==o.x||s!==o.y)}}var Wa={id:"tooltip",_element:Ba,positioners:Pa,afterInit(t,e,i){i&&(t.tooltip=new Ba({chart:t,options:i}))},beforeUpdate(t,e,i){t.tooltip&&t.tooltip.initialize(i)},reset(t,e,i){t.tooltip&&t.tooltip.initialize(i)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const i={tooltip:e};if(!1===t.notifyPlugins("beforeTooltipDraw",{...i,cancelable:!0}))return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",i)}},afterEvent(t,e){if(t.tooltip){const i=e.replay;t.tooltip.handleEvent(e.event,i,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:Fa},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>"filter"!==t&&"itemSort"!==t&&"external"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};return Tn.register(Un,$o,go,t),Tn.helpers={...Hi},Tn._adapters=In,Tn.Animation=As,Tn.Animations=Ts,Tn.animator=bt,Tn.controllers=nn.controllers.items,Tn.DatasetController=js,Tn.Element=$s,Tn.elements=go,Tn.Interaction=Ki,Tn.layouts=ls,Tn.platforms=Ds,Tn.Scale=tn,Tn.Ticks=ae,Object.assign(Tn,Un,$o,go,t,Ds),Tn.Chart=Tn,"undefined"!=typeof window&&(window.Chart=Tn),Tn}));
+//# sourceMappingURL=chart.umd.js.map
diff --git a/frontend/debug-export.html b/frontend/debug-export.html
new file mode 100644
index 0000000..f681e50
--- /dev/null
+++ b/frontend/debug-export.html
@@ -0,0 +1,266 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Export Debug - Warracker</title>
+ <style>
+ body {
+ font-family: Arial, sans-serif;
+ margin: 20px;
+ background-color: #f5f5f5;
+ }
+ .container {
+ max-width: 1200px;
+ margin: 0 auto;
+ background: white;
+ padding: 20px;
+ border-radius: 8px;
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
+ }
+ .debug-section {
+ margin-bottom: 30px;
+ padding: 15px;
+ border: 1px solid #ddd;
+ border-radius: 5px;
+ }
+ .debug-section h3 {
+ margin-top: 0;
+ color: #333;
+ }
+ .warranty-list {
+ max-height: 300px;
+ overflow-y: auto;
+ border: 1px solid #eee;
+ padding: 10px;
+ background: #f9f9f9;
+ }
+ .warranty-item {
+ padding: 5px;
+ border-bottom: 1px solid #eee;
+ font-size: 14px;
+ }
+ .warranty-item:last-child {
+ border-bottom: none;
+ }
+ .btn {
+ background: #007bff;
+ color: white;
+ border: none;
+ padding: 10px 20px;
+ border-radius: 4px;
+ cursor: pointer;
+ margin: 5px;
+ }
+ .btn:hover {
+ background: #0056b3;
+ }
+ .filters-display {
+ background: #e9ecef;
+ padding: 10px;
+ border-radius: 4px;
+ font-family: monospace;
+ }
+ .error {
+ color: red;
+ font-weight: bold;
+ }
+ .success {
+ color: green;
+ font-weight: bold;
+ }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <h1>Export Debug Tool</h1>
+ <p>This page helps debug warranty export issues by showing what data is loaded and what filters are applied.</p>
+
+ <div class="debug-section">
+ <h3>Authentication Status</h3>
+ <div id="authStatus">Checking...</div>
+ </div>
+
+ <div class="debug-section">
+ <h3>Loaded Warranties</h3>
+ <div>Total warranties loaded: <span id="totalWarranties">0</span></div>
+ <button class="btn" onclick="loadWarrantiesDebug()">Load Warranties</button>
+ <div id="warrantiesList" class="warranty-list"></div>
+ </div>
+
+ <div class="debug-section">
+ <h3>Current Filters</h3>
+ <div id="currentFilters" class="filters-display">No filters loaded</div>
+ </div>
+
+ <div class="debug-section">
+ <h3>Export Test</h3>
+ <button class="btn" onclick="testExport()">Test Export (with debug)</button>
+ <div id="exportResults"></div>
+ </div>
+
+ <div class="debug-section">
+ <h3>Console Logs</h3>
+ <p>Check the browser console (F12) for detailed debug information when you click the buttons above.</p>
+ </div>
+ </div>
+
+ <!-- i18next Local Scripts -->
+ <script src="js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+
+ <!-- i18n Configuration -->
+ <script src="js/i18n.js?v=20250119001"></script>
+
+ <script>
+ let warranties = [];
+ let currentFilters = {
+ status: 'all',
+ tag: 'all',
+ search: '',
+ sortBy: 'expiration',
+ vendor: 'all',
+ warranty_type: 'all'
+ };
+
+ // Check authentication status
+ function checkAuth() {
+ const token = localStorage.getItem('auth_token');
+ const userInfo = localStorage.getItem('user_info');
+
+ if (token && userInfo) {
+ document.getElementById('authStatus').innerHTML = `
+ <span class="success">✓ Authenticated</span><br>
+ Token: ${token.substring(0, 20)}...<br>
+ User: ${JSON.parse(userInfo).username || 'Unknown'}
+ `;
+ return true;
+ } else {
+ document.getElementById('authStatus').innerHTML = '<span class="error">✗ Not authenticated</span>';
+ return false;
+ }
+ }
+
+ // Load warranties with debug info
+ async function loadWarrantiesDebug() {
+ if (!checkAuth()) {
+ alert('Please log in first');
+ return;
+ }
+
+ try {
+ const token = localStorage.getItem('auth_token');
+ const response = await fetch('/api/warranties', {
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+ warranties = Array.isArray(data) ? data : [];
+
+ console.log('[DEBUG] Loaded warranties:', warranties);
+
+ document.getElementById('totalWarranties').textContent = warranties.length;
+
+ const listHtml = warranties.map(w =>
+ `<div class="warranty-item">
+ ID: ${w.id} | ${w.product_name} | Status: ${w.status || 'N/A'} | Vendor: ${w.vendor || 'N/A'}
+ </div>`
+ ).join('');
+
+ document.getElementById('warrantiesList').innerHTML = listHtml;
+
+ // Update filters display
+ document.getElementById('currentFilters').textContent = JSON.stringify(currentFilters, null, 2);
+
+ } catch (error) {
+ console.error('Error loading warranties:', error);
+ document.getElementById('warrantiesList').innerHTML = `<div class="error">Error: ${error.message}</div>`;
+ }
+ }
+
+ // Test export with debug
+ function testExport() {
+ if (warranties.length === 0) {
+ alert('Please load warranties first');
+ return;
+ }
+
+ console.log('[EXPORT DEBUG] Starting export test');
+ console.log('[EXPORT DEBUG] Total warranties:', warranties.length);
+ console.log('[EXPORT DEBUG] Current filters:', currentFilters);
+
+ let warrantiesToExport = [...warranties];
+ console.log('[EXPORT DEBUG] Initial warranties to export:', warrantiesToExport.length);
+
+ // Apply filters (same logic as main app)
+ if (currentFilters.search) {
+ const searchTerm = currentFilters.search.toLowerCase();
+ console.log('[EXPORT DEBUG] Applying search filter:', searchTerm);
+ warrantiesToExport = warrantiesToExport.filter(warranty => {
+ const productNameMatch = warranty.product_name && warranty.product_name.toLowerCase().includes(searchTerm);
+ const tagMatch = warranty.tags && Array.isArray(warranty.tags) &&
+ warranty.tags.some(tag => tag.name && tag.name.toLowerCase().includes(searchTerm));
+ const vendorMatch = warranty.vendor && warranty.vendor.toLowerCase().includes(searchTerm);
+ return productNameMatch || tagMatch || vendorMatch;
+ });
+ console.log('[EXPORT DEBUG] After search filter:', warrantiesToExport.length);
+ }
+
+ if (currentFilters.status !== 'all') {
+ console.log('[EXPORT DEBUG] Applying status filter:', currentFilters.status);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ warranty.status === currentFilters.status
+ );
+ console.log('[EXPORT DEBUG] After status filter:', warrantiesToExport.length);
+ }
+
+ if (currentFilters.tag !== 'all') {
+ const tagId = parseInt(currentFilters.tag);
+ console.log('[EXPORT DEBUG] Applying tag filter:', tagId);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ warranty.tags && Array.isArray(warranty.tags) &&
+ warranty.tags.some(tag => tag.id === tagId)
+ );
+ console.log('[EXPORT DEBUG] After tag filter:', warrantiesToExport.length);
+ }
+
+ if (currentFilters.vendor !== 'all') {
+ console.log('[EXPORT DEBUG] Applying vendor filter:', currentFilters.vendor);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ (warranty.vendor || '').toLowerCase() === currentFilters.vendor.toLowerCase()
+ );
+ console.log('[EXPORT DEBUG] After vendor filter:', warrantiesToExport.length);
+ }
+
+ if (currentFilters.warranty_type !== 'all') {
+ console.log('[EXPORT DEBUG] Applying warranty type filter:', currentFilters.warranty_type);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ (warranty.warranty_type || '').toLowerCase() === currentFilters.warranty_type.toLowerCase()
+ );
+ console.log('[EXPORT DEBUG] After warranty type filter:', warrantiesToExport.length);
+ }
+
+ console.log('[EXPORT DEBUG] Final warranties to export:', warrantiesToExport.length);
+ console.log('[EXPORT DEBUG] Warranty IDs being exported:', warrantiesToExport.map(w => w.id));
+
+ document.getElementById('exportResults').innerHTML = `
+ <div class="success">Export test completed!</div>
+ <div>Total warranties loaded: ${warranties.length}</div>
+ <div>Warranties that would be exported: ${warrantiesToExport.length}</div>
+ <div>Check console for detailed logs</div>
+ `;
+ }
+
+ // Initialize
+ checkAuth();
+ </script>
+</body>
+</html>
diff --git a/frontend/fix-auth-buttons.js b/frontend/fix-auth-buttons.js
index c4575bf..d6eead0 100644
--- a/frontend/fix-auth-buttons.js
+++ b/frontend/fix-auth-buttons.js
@@ -9,7 +9,7 @@ console.log('fix-auth-buttons.js loaded and executing');
// Function to check if user is authenticated
function isAuthenticated() {
const token = localStorage.getItem('auth_token');
- console.log('Auth token check:', !!token);
+ // console.log('Auth token check:', !!token); // Keep console logs minimal here if auth.js is primary
return !!token;
}
@@ -21,165 +21,56 @@ function getElementsByText(selector, text) {
// Function to hide login and register buttons if user is authenticated
function updateAuthButtons() {
- console.log('updateAuthButtons executing...');
-
- // Check if user is authenticated
+ // console.log('fix-auth-buttons.js: updateAuthButtons executing...'); // Keep console logs minimal here
if (isAuthenticated()) {
- console.log('User is authenticated, hiding login/register buttons');
-
- // Find login and register buttons using valid selectors
+ // console.log('fix-auth-buttons.js: User is authenticated, hiding login/register buttons');
const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');
const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');
-
- // Find buttons by text content
- const loginButtonsByText = getElementsByText('a, button', 'Login');
- const registerButtonsByText = getElementsByText('a, button', 'Register');
-
- const allLoginButtons = [...loginButtons, ...loginButtonsByText];
- const allRegisterButtons = [...registerButtons, ...registerButtonsByText];
-
- console.log('Found login buttons:', allLoginButtons.length);
- console.log('Found register buttons:', allRegisterButtons.length);
-
- // Hide buttons if they exist
- allLoginButtons.forEach(button => {
- console.log('Hiding login button:', button);
- button.style.display = 'none';
- button.style.visibility = 'hidden';
- });
-
- allRegisterButtons.forEach(button => {
- console.log('Hiding register button:', button);
- button.style.display = 'none';
- button.style.visibility = 'hidden';
- });
-
- // Hide auth container if it exists
const authContainer = document.getElementById('authContainer');
- if (authContainer) {
- console.log('Hiding auth container');
- authContainer.style.display = 'none';
- authContainer.style.visibility = 'hidden';
- }
-
- // Also try to hide by class
- const authButtonsContainers = document.querySelectorAll('.auth-buttons');
- console.log('Found auth buttons containers:', authButtonsContainers.length);
- authButtonsContainers.forEach(container => {
- console.log('Hiding auth buttons container');
- container.style.display = 'none';
- container.style.visibility = 'hidden';
- });
-
- // Show user menu if it exists
- const userMenu = document.getElementById('userMenu');
- if (userMenu) {
- console.log('Showing user menu');
- userMenu.style.display = 'block';
- userMenu.style.visibility = 'visible';
- }
-
- // Show username if it exists
+ const userMenu = document.getElementById('userMenu'); // Ensure this ID is consistent or use userMenuBtn's parent
+
+ loginButtons.forEach(button => { button.style.display = 'none'; button.style.visibility = 'hidden'; });
+ registerButtons.forEach(button => { button.style.display = 'none'; button.style.visibility = 'hidden'; });
+ if (authContainer) { authContainer.style.display = 'none'; authContainer.style.visibility = 'hidden';}
+ if (userMenu) { userMenu.style.display = 'block'; userMenu.style.visibility = 'visible'; }
+
const userInfo = localStorage.getItem('user_info');
if (userInfo) {
try {
const user = JSON.parse(userInfo);
- const username = user.username || 'User';
- console.log('Setting username to:', username);
-
- // Find username display elements
- const usernameDisplays = document.querySelectorAll('.user-name, #userDisplayName, #userName');
- usernameDisplays.forEach(display => {
- if (display) {
- display.textContent = username;
- display.style.display = 'inline-block';
- }
- });
-
- // Set user email if element exists
- const userEmail = document.getElementById('userEmail');
- if (userEmail && user.email) {
- userEmail.textContent = user.email;
+ const displayName = user.first_name || user.username || 'User';
+ const userDisplayName = document.getElementById('userDisplayName');
+ if (userDisplayName) userDisplayName.textContent = displayName;
+
+ const userNameMenu = document.getElementById('userName');
+ if (userNameMenu) {
+ userNameMenu.textContent = `${user.first_name || ''} ${user.last_name || ''}`.trim() || user.username || 'User Name';
}
- } catch (error) {
- console.error('Error parsing user info:', error);
- }
+ const userEmailMenu = document.getElementById('userEmail');
+ if (userEmailMenu && user.email) userEmailMenu.textContent = user.email;
+ } catch (error) { /* console.error('fix-auth-buttons.js: Error parsing user info:', error); */ }
}
} else {
- console.log('User is not authenticated, showing login/register buttons');
-
- // Find login and register buttons in the new UI
+ // console.log('fix-auth-buttons.js: User is not authenticated, showing login/register buttons');
const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');
const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');
-
- // Show buttons if they exist
- loginButtons.forEach(button => {
- button.style.display = 'inline-block';
- button.style.visibility = 'visible';
- });
-
- registerButtons.forEach(button => {
- button.style.display = 'inline-block';
- button.style.visibility = 'visible';
- });
-
- // Show auth container if it exists
const authContainer = document.getElementById('authContainer');
- if (authContainer) {
- authContainer.style.display = 'flex';
- authContainer.style.visibility = 'visible';
- }
-
- // Also try to show by class
- const authButtonsContainers = document.querySelectorAll('.auth-buttons');
- authButtonsContainers.forEach(container => {
- container.style.display = 'flex';
- container.style.visibility = 'visible';
- });
-
- // Hide user menu if it exists
const userMenu = document.getElementById('userMenu');
- if (userMenu) {
- userMenu.style.display = 'none';
- userMenu.style.visibility = 'hidden';
- }
- }
-}
-// --- USER MENU DROPDOWN UNIVERSAL FIX (IMPROVED) ---
-function setupUserMenuDropdown() {
- const userMenuBtn = document.getElementById('userMenuBtn') || document.getElementById('userBtn');
- const userMenuDropdown = document.getElementById('userMenuDropdown');
- if (userMenuBtn && userMenuDropdown) {
- // Remove all previous click listeners by replacing the node
- const newBtn = userMenuBtn.cloneNode(true);
- userMenuBtn.parentNode.replaceChild(newBtn, userMenuBtn);
- newBtn.addEventListener('click', function(e) {
- e.stopPropagation();
- userMenuDropdown.classList.toggle('active');
- });
- // Only add one document-level listener
- if (!window._userMenuDropdownListenerAdded) {
- document.addEventListener('click', function(e) {
- if (userMenuDropdown.classList.contains('active') &&
- !userMenuDropdown.contains(e.target) &&
- !newBtn.contains(e.target)) {
- userMenuDropdown.classList.remove('active');
- }
- });
- window._userMenuDropdownListenerAdded = true;
- }
+ loginButtons.forEach(button => { button.style.display = 'inline-block'; button.style.visibility = 'visible'; });
+ registerButtons.forEach(button => { button.style.display = 'inline-block'; button.style.visibility = 'visible'; });
+ if (authContainer) { authContainer.style.display = 'flex'; authContainer.style.visibility = 'visible'; }
+ if (userMenu) { userMenu.style.display = 'none'; userMenu.style.visibility = 'hidden'; }
}
}
// Run immediately
-console.log('Running updateAuthButtons immediately');
+// console.log('Running updateAuthButtons immediately from fix-auth-buttons.js');
updateAuthButtons();
-setupUserMenuDropdown();
// Update auth buttons when page loads
document.addEventListener('DOMContentLoaded', () => {
- console.log('DOMContentLoaded event triggered, updating auth buttons');
+ // console.log('DOMContentLoaded event triggered in fix-auth-buttons.js, updating auth buttons');
updateAuthButtons();
- setupUserMenuDropdown();
+ // REMOVE: setupUserMenuDropdown();
});
\ No newline at end of file
diff --git a/frontend/footer-content.js b/frontend/footer-content.js
new file mode 100644
index 0000000..362d6ef
--- /dev/null
+++ b/frontend/footer-content.js
@@ -0,0 +1,131 @@
+/**
+ * Footer Content Manager - Universal
+ * Manages the "Powered by" footer content across all pages
+ * Easy to customize footer text, links, and branding from one place
+ */
+
+(function() {
+ 'use strict';
+
+ // === FOOTER CONFIGURATION ===
+ // Edit these values to change footer content across all pages
+ const FOOTER_CONFIG = {
+ // Main footer text
+ text: 'Powered by',
+
+ // Link configuration
+ link: {
+ text: 'Warracker',
+ url: 'https://warracker.com',
+ target: '_blank',
+ rel: 'noopener noreferrer'
+ },
+
+ // Optional: Additional links or text
+ // Uncomment and customize as needed
+ /*
+ additionalContent: [
+ { type: 'text', content: ' | ' },
+ { type: 'link', text: 'Privacy Policy', url: '/privacy.html' },
+ { type: 'text', content: ' | ' },
+ { type: 'link', text: 'Terms of Service', url: '/terms.html' }
+ ]
+ */
+ };
+
+ // === FOOTER CONTENT GENERATION ===
+ function generateFooterContent() {
+ let footerHTML = `${FOOTER_CONFIG.text} `;
+
+ // Add main link
+ footerHTML += `<a href="${FOOTER_CONFIG.link.url}" target="${FOOTER_CONFIG.link.target}" rel="${FOOTER_CONFIG.link.rel}" id="warrackerFooterLink">${FOOTER_CONFIG.link.text}</a>`;
+
+ // Add additional content if configured
+ if (FOOTER_CONFIG.additionalContent) {
+ FOOTER_CONFIG.additionalContent.forEach(item => {
+ if (item.type === 'text') {
+ footerHTML += item.content;
+ } else if (item.type === 'link') {
+ const target = item.target || '_self';
+ const rel = item.rel || '';
+ footerHTML += `<a href="${item.url}" target="${target}" rel="${rel}">${item.text}</a>`;
+ }
+ });
+ }
+
+ return footerHTML;
+ }
+
+ // === FOOTER INITIALIZATION ===
+ function initFooterContent() {
+ const footer = document.getElementById('warrackerFooter');
+
+ if (!footer) {
+ console.warn('Footer element with ID "warrackerFooter" not found');
+ return;
+ }
+
+ // Generate and inject footer content
+ const footerContent = generateFooterContent();
+ footer.innerHTML = `<p>${footerContent}</p>`;
+
+ console.log('Footer content initialized successfully');
+ }
+
+ // === DYNAMIC FOOTER CREATION ===
+ // If no footer exists, create one
+ function createFooterIfMissing() {
+ let footer = document.getElementById('warrackerFooter');
+
+ if (!footer) {
+ footer = document.createElement('footer');
+ footer.className = 'warracker-footer';
+ footer.id = 'warrackerFooter';
+
+ // Insert before closing body tag
+ document.body.appendChild(footer);
+ console.log('Footer element created dynamically');
+ }
+
+ return footer;
+ }
+
+ // === PUBLIC API ===
+ // Expose functions for manual updates if needed
+ window.FooterContent = {
+ // Update footer content dynamically
+ update: function(newConfig) {
+ Object.assign(FOOTER_CONFIG, newConfig);
+ initFooterContent();
+ },
+
+ // Get current configuration
+ getConfig: function() {
+ return { ...FOOTER_CONFIG };
+ },
+
+ // Reinitialize footer
+ reinit: function() {
+ initFooterContent();
+ }
+ };
+
+ // === AUTO-INITIALIZATION ===
+ function init() {
+ // Ensure footer element exists
+ createFooterIfMissing();
+
+ // Initialize footer content
+ initFooterContent();
+ }
+
+ // Initialize when DOM is ready
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ // DOM is already loaded
+ init();
+ }
+
+ console.log('Footer Content Manager loaded');
+})();
\ No newline at end of file
diff --git a/frontend/footer-fix.js b/frontend/footer-fix.js
new file mode 100644
index 0000000..46ceb96
--- /dev/null
+++ b/frontend/footer-fix.js
@@ -0,0 +1,103 @@
+/**
+ * Footer Width Fix - Universal
+ * Ensures the Warracker footer spans full width across all pages
+ * Handles both light and dark themes automatically
+ */
+
+(function() {
+ 'use strict';
+
+ // Apply footer styles based on theme
+ function applyFooterStyles() {
+ const footer = document.getElementById('warrackerFooter');
+ const link = document.getElementById('warrackerFooterLink');
+
+ if (!footer) return; // Exit if footer doesn't exist on this page
+
+ // Detect dark mode
+ const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark' ||
+ document.documentElement.classList.contains('dark-mode') ||
+ document.body.classList.contains('dark-mode');
+
+ if (isDarkMode) {
+ // Dark mode styles with full width override
+ footer.style.cssText = `
+ width: 100vw !important;
+ margin-top: 50px !important;
+ margin-left: calc(-50vw + 50%) !important;
+ margin-right: calc(-50vw + 50%) !important;
+ padding: 20px !important;
+ text-align: center !important;
+ border-top: 1px solid #444 !important;
+ background-color: #2d2d2d !important;
+ color: #e0e0e0 !important;
+ font-size: 0.9rem !important;
+ position: relative !important;
+ left: 0 !important;
+ right: 0 !important;
+ max-width: none !important;
+ box-sizing: border-box !important;
+ `;
+ if (link) {
+ link.style.cssText = 'color: #4dabf7 !important; text-decoration: none !important; font-weight: 500 !important;';
+ }
+ } else {
+ // Light mode styles with full width override
+ footer.style.cssText = `
+ width: 100vw !important;
+ margin-top: 50px !important;
+ margin-left: calc(-50vw + 50%) !important;
+ margin-right: calc(-50vw + 50%) !important;
+ padding: 20px !important;
+ text-align: center !important;
+ border-top: 1px solid #e0e0e0 !important;
+ background-color: #ffffff !important;
+ color: #333333 !important;
+ font-size: 0.9rem !important;
+ position: relative !important;
+ left: 0 !important;
+ right: 0 !important;
+ max-width: none !important;
+ box-sizing: border-box !important;
+ `;
+ if (link) {
+ link.style.cssText = 'color: #3498db !important; text-decoration: none !important; font-weight: 500 !important;';
+ }
+ }
+ }
+
+ // Initialize footer styles when DOM is ready
+ function initFooterFix() {
+ applyFooterStyles();
+
+ // Watch for theme changes on document.documentElement
+ const observer = new MutationObserver(applyFooterStyles);
+ observer.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: ['data-theme', 'class']
+ });
+
+ // Also watch body for theme changes (fallback)
+ observer.observe(document.body, {
+ attributes: true,
+ attributeFilter: ['class']
+ });
+
+ // Listen for custom theme change events if they exist
+ document.addEventListener('themeChanged', applyFooterStyles);
+ window.addEventListener('themeChanged', applyFooterStyles);
+ }
+
+ // Auto-initialize when DOM is loaded
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', initFooterFix);
+ } else {
+ // DOM is already loaded
+ initFooterFix();
+ }
+
+ // Expose function globally in case manual calls are needed
+ window.applyFooterFix = applyFooterStyles;
+
+ console.log('Footer Fix loaded - Footer will span full width on all pages');
+})();
\ No newline at end of file
diff --git a/frontend/index.html b/frontend/index.html
index 79bc6fe..3c08958 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -1,14 +1,14 @@
<!DOCTYPE html>
-<html lang="en">
+<html>
<head>
<!-- Authentication redirect script -->
- <script src="auth-redirect.js" data-protected="true"></script>
+ <script src="auth-redirect.js?v=20250119001" data-protected="true"></script>
<!-- Include authentication script first to handle login state immediately -->
- <script src="include-auth-new.js"></script>
+ <script src="include-auth-new.js?v=20250119001"></script>
<!-- File utilities script for secure file handling -->
- <script src="file-utils.js"></script>
+ <script src="file-utils.js?v=20250119001"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -22,17 +22,25 @@
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
<link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
<link rel="manifest" href="manifest.json">
- <link rel="stylesheet" href="style.css">
- <script src="theme-loader.js"></script> <!-- Apply theme early -->
+ <link rel="stylesheet" href="style.css?v=20250119001">
+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Load header fix styles to ensure consistent header styling -->
- <link rel="stylesheet" href="header-fix.css">
+ <link rel="stylesheet" href="header-fix.css?v=20250119001">
<!-- Load fix for auth buttons -->
- <script src="fix-auth-buttons-loader.js"></script>
+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
<!-- Mobile Header specific styles -->
- <link rel="stylesheet" href="mobile-header.css">
+ <link rel="stylesheet" href="mobile-header.css?v=20250119001">
+
+ <!-- i18next Local Scripts -->
+ <script src="js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+
+ <!-- i18n Configuration -->
+ <script src="js/i18n.js?v=20250119001"></script>
<!-- Immediate authentication check script -->
<script>
@@ -86,8 +94,8 @@
})();
</script>
- <!-- Registration status check script -->
- <script src="registration-status.js"></script>
+ <!-- Registration status check script -->
+ <script src="registration-status.js?v=20250119001"></script>
</head>
<body>
<!-- Header -->
@@ -99,24 +107,24 @@
</div>
<div class="nav-links">
<a href="index.html" class="nav-link active">
- <i class="fas fa-home"></i> Home
+ <i class="fas fa-home"></i> <span data-i18n="nav.home">Home</span>
</a>
<a href="status.html" class="nav-link">
- <i class="fas fa-chart-pie"></i> Status
+ <i class="fas fa-chart-pie"></i> <span data-i18n="nav.status">Status</span>
</a>
</div>
<!-- Group for right-aligned elements -->
<div class="header-right-group">
<div id="authContainer" class="auth-buttons">
<a href="login.html" class="auth-btn login-btn">
- <i class="fas fa-sign-in-alt"></i> Login
+ <i class="fas fa-sign-in-alt"></i> <span data-i18n="auth.login">Login</span>
</a>
<a href="register.html" class="auth-btn register-btn">
- <i class="fas fa-user-plus"></i> Register
+ <i class="fas fa-user-plus"></i> <span data-i18n="auth.register">Register</span>
</a>
</div>
<div id="userMenu" class="user-menu" style="display: none;">
- <button id="userBtn" class="user-btn">
+ <button id="userMenuBtn" class="user-btn">
<i class="fas fa-user-circle"></i>
<span id="userDisplayName">User</span>
</button>
@@ -127,15 +135,15 @@
</div>
<div class="user-menu-item">
<a href="settings-new.html" style="color: inherit; text-decoration: none; display: block;">
- <i class="fas fa-cog"></i> Settings
+ <i class="fas fa-cog"></i> <span data-i18n="nav.settings">Settings</span>
</a>
</div>
<div class="user-menu-item">
<i class="fas fa-info-circle"></i>
- <a href="about.html" style="text-decoration: none; color: inherit;">About</a>
+ <a href="about.html" style="text-decoration: none; color: inherit;" data-i18n="nav.about">About</a>
</div>
<div class="user-menu-item" id="logoutMenuItem">
- <i class="fas fa-sign-out-alt"></i> Logout
+ <i class="fas fa-sign-out-alt"></i> <span data-i18n="auth.logout">Logout</span>
</div>
</div>
</div>
@@ -151,15 +159,15 @@
<div class="warranties-panel">
<!-- Panel Header -->
<div class="panel-header">
- <h2>Your Warranties</h2>
+ <h2 id="warrantiesPanelTitle" data-i18n="warranties.title">Your Warranties</h2>
<!-- ADD BUTTON CONTAINER AND REFRESH BUTTON WRAPPER HERE -->
<div class="panel-header-actions">
<div class="add-warranty-button-container">
<button id="showAddWarrantyBtn" class="btn btn-primary btn-sm">
- <i class="fas fa-plus"></i> Add New Warranty
+ <i class="fas fa-plus"></i> <span data-i18n="warranties.add_new">Add New Warranty</span>
</button>
</div>
- <button id="refreshBtn" class="btn btn-secondary btn-sm" title="Refresh List">
+ <button id="refreshBtn" class="btn btn-secondary btn-sm" data-i18n-title="actions.refresh" title="Refresh List">
<i class="fas fa-sync-alt"></i>
</button>
</div>
@@ -172,20 +180,20 @@
<button id="searchBtn" class="search-btn" title="Search">
<i class="fas fa-search"></i>
</button>
- <input type="text" id="searchWarranties" placeholder="Find by name, vendors, notes, tag, or serial number..." style="width: 100%; min-width: 200px;">
+ <input type="text" id="searchWarranties" data-i18n-placeholder="warranties.search_placeholder" placeholder="Find by name, vendors, notes, tag, or serial number..." style="width: 100%; min-width: 200px;">
<button id="clearSearch" class="clear-search-btn" title="Clear search" style="display: none;">
<i class="fas fa-times"></i>
</button>
</div>
<div style="display: flex; gap: 8px; flex-wrap: nowrap; flex-shrink: 0; min-width: 0;">
<button id="exportBtn" class="export-btn" title="Export warranties" style="white-space: nowrap;">
- <i class="fas fa-file-export"></i> Export
+ <i class="fas fa-file-export"></i> <span data-i18n="actions.export">Export</span>
</button>
<button id="importBtn" class="import-btn" title="Import warranties from CSV" style="white-space: nowrap;">
- <i class="fas fa-file-import"></i> Import
+ <i class="fas fa-file-import"></i> <span data-i18n="actions.import">Import</span>
</button>
<button id="globalManageTagsBtn" class="export-btn" title="Manage all tags" style="white-space: nowrap;">
- <i class="fas fa-tags"></i> Manage Tags
+ <i class="fas fa-tags"></i> <span data-i18n="actions.manage_tags">Manage Tags</span>
</button>
</div>
<input type="file" id="csvFileInput" accept=".csv" style="display: none;">
@@ -193,43 +201,53 @@
<div class="filter-options">
<div class="filter-group">
- <label class="filter-label">Status</label>
+ <label class="filter-label" data-i18n="filters.status">Status</label>
<select id="statusFilter" class="filter-select">
- <option value="all">All Status</option>
- <option value="active">Active</option>
- <option value="expiring">Expiring Soon</option>
- <option value="expired">Expired</option>
+ <option value="all" data-i18n="filters.all_status">All Status</option>
+ <option value="active" data-i18n="warranties.active">Active</option>
+ <option value="expiring" data-i18n="warranties.expiring_soon">Expiring Soon</option>
+ <option value="expired" data-i18n="warranties.expired">Expired</option>
</select>
</div>
<div class="filter-group">
- <label class="filter-label">Tag</label>
+ <label class="filter-label" data-i18n="filters.tags">Tag</label>
<select id="tagFilter" class="filter-select">
- <option value="all">All Tags</option>
+ <option value="all" data-i18n="filters.all_tags">All Tags</option>
<!-- Tag options will be populated by JavaScript -->
</select>
</div>
<div class="filter-group">
- <label class="filter-label">Vendor</label>
+ <label class="filter-label" data-i18n="filters.vendor">Vendor</label>
<select id="vendorFilter" class="filter-select">
- <option value="all">All Vendors</option>
+ <option value="all" data-i18n="filters.all_vendors">All Vendors</option>
<!-- Vendor options will be populated by JavaScript -->
</select>
</div>
<div class="filter-group">
- <label class="filter-label">Sort By</label>
+ <label class="filter-label" data-i18n="filters.warranty_type">Warranty Type</label>
+ <select id="warrantyTypeFilter" class="filter-select">
+ <option value="all" data-i18n="filters.all_types">All Types</option>
+ <!-- Warranty type options will be populated by JavaScript -->
+ </select>
+ </div>
+
+ <div class="filter-group">
+ <label class="filter-label" data-i18n="filters.sort_by">Sort By</label>
<select id="sortBy" class="filter-select">
- <option value="expiration">Expiration Date</option>
- <option value="purchase">Purchase Date</option>
- <option value="name">Product Name</option>
- <option value="vendor">Vendor</option>
+ <option value="expiration" data-i18n="filters.sort_expiration">Expiration Date</option>
+ <option value="purchase" data-i18n="filters.sort_purchase">Purchase Date</option>
+ <option value="age" data-i18n="filters.sort_age">Age</option>
+ <option value="name" data-i18n="filters.sort_name">Product Name</option>
+ <option value="vendor" data-i18n="filters.sort_vendor">Vendor</option>
+ <option value="warranty_type" data-i18n="filters.sort_warranty_type">Warranty Type</option>
</select>
</div>
<div class="view-switcher">
- <label class="filter-label">View</label>
+ <label class="filter-label" data-i18n="filters.view">View</label>
<div class="view-buttons">
<button id="gridViewBtn" class="view-btn active" title="Grid View">
<i class="fas fa-th-large"></i>
@@ -242,6 +260,19 @@
</button>
</div>
</div>
+
+ <!-- Scope View Toggle -->
+ <div class="admin-view-switcher" id="adminViewSwitcher" style="display: none;">
+ <label class="filter-label" data-i18n="filters.scope">Scope</label>
+ <div class="view-buttons">
+ <button id="personalViewBtn" class="view-btn active" title="View your warranties only">
+ <i class="fas fa-user"></i>
+ </button>
+ <button id="globalViewBtn" class="view-btn" title="View all users' warranties (read-only for others)">
+ <i class="fas fa-globe"></i>
+ </button>
+ </div>
+ </div>
</div>
</div>
@@ -249,18 +280,18 @@
<!-- Table headers for table view -->
<div class="table-view-header">
<tr>
- <th>Product</th>
- <th>Purchase Date</th>
- <th>Expiration</th>
- <th>Status</th>
- <th>Actions</th>
+ <th data-i18n="warranties.product">Product</th>
+ <th data-i18n="warranties.purchase_date">Purchase Date</th>
+ <th data-i18n="warranties.expiration">Expiration</th>
+ <th data-i18n="warranties.status">Status</th>
+ <th data-i18n="warranties.actions">Actions</th>
</tr>
</div>
<!-- Warranties will be loaded here -->
<div class="empty-state" style="display: none;">
<i class="fas fa-box-open"></i>
- <h3>No warranties yet</h3>
- <p>Add your first warranty to get started</p>
+ <h3 data-i18n="warranties.no_warranties_title">No warranties yet</h3>
+ <p data-i18n="warranties.no_warranties_desc">Add your first warranty to get started</p>
</div>
</div>
</div>
@@ -270,7 +301,7 @@
<div id="addWarrantyModal" class="modal-backdrop">
<div class="modal" style="max-width: 700px;"> <!-- Adjusted max-width for the wizard -->
<div class="modal-header">
- <h3 class="modal-title">Add New Warranty</h3>
+ <h3 class="modal-title" data-i18n="warranties.add_new">Add New Warranty</h3>
<button class="close-btn" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
@@ -279,51 +310,51 @@
<!-- Form Tabs -->
<div class="form-tabs" data-step="0">
<div class="form-tab active" data-tab="product-info" id="productInfoTabBtn">
- <i class="fas fa-box"></i> Product
+ <i class="fas fa-box"></i> <span data-i18n="warranties.product">Product</span>
</div>
<div class="form-tab" data-tab="warranty-details" id="warrantyDetailsTabBtn">
- <i class="fas fa-shield-alt"></i> Warranty
+ <i class="fas fa-shield-alt"></i> <span data-i18n="warranties.warranty">Warranty</span>
</div>
<div class="form-tab" data-tab="documents" id="documentsTabBtn">
- <i class="fas fa-file-alt"></i> Documents
+ <i class="fas fa-file-alt"></i> <span data-i18n="warranties.documents">Documents</span>
</div>
<div class="form-tab" data-tab="tags" id="tagsTabBtn">
- <i class="fas fa-tags"></i> Tags
+ <i class="fas fa-tags"></i> <span data-i18n="warranties.tags">Tags</span>
</div>
<div class="form-tab" data-tab="summary" id="summaryTabBtn">
- <i class="fas fa-check-circle"></i> Summary
+ <i class="fas fa-check-circle"></i> <span data-i18n="warranties.summary">Summary</span>
</div>
</div>
<!-- Warranty Form -->
- <form id="warrantyForm">
+ <form id="warrantyForm" novalidate>
<!-- Product Information Tab -->
<div class="tab-content active" id="product-info">
<div class="form-group">
- <label for="productName">Product Name</label>
+ <label for="productName" data-i18n="warranties.product_name">Product Name</label>
<input type="text" id="productName" name="product_name" class="form-control" required>
</div>
<div class="form-group">
- <label for="productUrl">Product URL (Optional)</label>
- <input type="text" id="productUrl" name="product_url" class="form-control" placeholder="https://example.com/product">
+ <label for="productUrl" data-i18n="warranties.product_url_optional">Product URL (Optional)</label>
+ <input type="text" id="productUrl" name="product_url" class="form-control" data-i18n-placeholder="warranties.product_url_placeholder" placeholder="https://example.com/product">
</div>
<div class="form-group">
- <label>Serial Numbers</label>
+ <label data-i18n="warranties.serial_numbers">Serial Numbers</label>
<div id="serialNumbersContainer">
<!-- Serial number inputs will be added dynamically -->
- <input type="text" name="serial_numbers[]" class="form-control" style="margin-bottom: 8px;" placeholder="Enter serial number">
+ <input type="text" name="serial_numbers[]" class="form-control" style="margin-bottom: 8px;" data-i18n-placeholder="warranties.enter_serial_number" placeholder="Enter serial number">
</div>
</div>
<div class="form-group">
- <label for="vendor">Vendor (Optional)</label>
- <input type="text" id="vendor" name="vendor" class="form-control" placeholder="e.g. Amazon, Best Buy, etc.">
+ <label for="vendor" data-i18n="warranties.vendor_optional">Vendor (Optional)</label>
+ <input type="text" id="vendor" name="vendor" class="form-control" data-i18n-placeholder="warranties.vendor_placeholder" placeholder="e.g. Amazon, Best Buy, etc.">
</div>
</div>
<!-- Warranty Details Tab -->
<div class="tab-content" id="warranty-details">
<div class="form-group">
- <label for="purchaseDate">Purchase Date</label>
+ <label for="purchaseDate" data-i18n="warranties.purchase_date">Purchase Date</label>
<input type="date" id="purchaseDate" name="purchase_date" class="form-control" required>
</div>
@@ -331,82 +362,211 @@
<div class="form-group">
<label class="lifetime-label">
<input type="checkbox" id="isLifetime" name="is_lifetime" value="true">
- Lifetime Warranty
+ <span data-i18n="warranties.lifetime_warranty">Lifetime Warranty</span>
</label>
</div>
<!-- End Lifetime Checkbox -->
+ <!-- Warranty Entry Method Selection -->
+ <div class="form-group" id="warrantyEntryMethod">
+ <label data-i18n="warranties.warranty_entry_method">Warranty Entry Method</label>
+ <div class="warranty-method-options">
+ <label class="radio-option">
+ <input type="radio" id="durationMethod" name="warranty_method" value="duration" checked>
+ <span data-i18n="warranties.warranty_duration_option">Warranty Duration</span>
+ </label>
+ <label class="radio-option">
+ <input type="radio" id="exactDateMethod" name="warranty_method" value="exact_date">
+ <span data-i18n="warranties.exact_expiration_option">Exact Expiration Date</span>
+ </label>
+ </div>
+ </div>
+
<div id="warrantyDurationFields">
<div class="form-group">
- <label for="warrantyDurationYears">Warranty Period</label>
+ <label for="warrantyDurationYears" data-i18n="warranties.warranty_period">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>
+ <input type="number" id="warrantyDurationYears" name="warranty_duration_years" class="form-control" min="0" max="999" data-i18n-placeholder="warranties.years_placeholder" placeholder="Years">
+ <small data-i18n="warranties.years">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>
+ <input type="number" id="warrantyDurationMonths" name="warranty_duration_months" class="form-control" min="0" max="999" data-i18n-placeholder="warranties.months_placeholder" placeholder="Months">
+ <small data-i18n="warranties.months">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>
+ <input type="number" id="warrantyDurationDays" name="warranty_duration_days" class="form-control" min="0" max="9999" data-i18n-placeholder="warranties.days_placeholder" placeholder="Days">
+ <small data-i18n="warranties.days">Days</small>
</div>
</div>
</div>
</div>
- <div class="form-group">
- <label for="purchasePrice">Purchase Price (Optional)</label>
- <div class="price-input-wrapper">
- <span class="currency-symbol">$</span>
- <input type="number" id="purchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">
+ <div id="exactExpirationField" style="display: none;">
+ <div class="form-group">
+ <label for="exactExpirationDate" data-i18n="warranties.expiration_date_label">Expiration Date</label>
+ <input type="date" id="exactExpirationDate" name="exact_expiration_date" class="form-control">
</div>
</div>
+
<div class="form-group">
- <label for="notes">Notes (Optional)</label>
- <textarea id="notes" name="notes" class="form-control" rows="3" placeholder="Add any notes about this warranty..."></textarea>
+ <label for="warrantyType" data-i18n="warranties.warranty_type_optional">Warranty Type (Optional)</label>
+ <select id="warrantyType" name="warranty_type" class="form-control">
+ <option value="" data-i18n="warranties.select_warranty_type">Select warranty type...</option>
+ <option value="Standard" data-i18n="warranties.standard">Standard</option>
+ <option value="Extended" data-i18n="warranties.extended">Extended</option>
+ <option value="Manufacturer" data-i18n="warranties.manufacturer">Manufacturer</option>
+ <option value="Third Party" data-i18n="warranties.third_party">Third Party</option>
+ <option value="Store" data-i18n="warranties.store">Store</option>
+ <option value="Premium" data-i18n="warranties.premium">Premium</option>
+ <option value="Limited" data-i18n="warranties.limited">Limited</option>
+ <option value="Full" data-i18n="warranties.full">Full</option>
+ <option value="Parts Only" data-i18n="warranties.parts_only">Parts Only</option>
+ <option value="Labor Only" data-i18n="warranties.labor_only">Labor Only</option>
+ <option value="International" data-i18n="warranties.international">International</option>
+ <option value="Accidental Damage" data-i18n="warranties.accidental_damage">Accidental Damage</option>
+ <option value="other" data-i18n="warranties.other_custom">Other (Custom)</option>
+ </select>
+ <input type="text" id="warrantyTypeCustom" name="warranty_type_custom" class="form-control" style="display: none; margin-top: 8px;" data-i18n-placeholder="warranties.enter_custom_warranty_type_placeholder" placeholder="Enter custom warranty type">
+ </div>
+ <div class="form-group">
+ <label for="currency" data-i18n="warranties.currency">Currency</label>
+ <select id="currency" name="currency" class="form-control">
+ <option value="USD">USD - US Dollar ($)</option>
+ <!-- Currency options will be populated by JavaScript -->
+ </select>
+ </div>
+ <div class="form-group">
+ <label for="purchasePrice" data-i18n="warranties.purchase_price_optional">Purchase Price (Optional)</label>
+ <div class="price-input-wrapper" id="addPriceInputWrapper">
+ <span class="currency-symbol" id="addCurrencySymbol">$</span>
+ <input type="number" id="purchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">
+ </div>
+ </div>
+ <div class="form-group">
+ <label for="notes" data-i18n="warranties.notes_optional">Notes (Optional)</label>
+ <textarea id="notes" name="notes" class="form-control" rows="3" data-i18n-placeholder="warranties.add_any_notes_placeholder" placeholder="Add any notes about this warranty..."></textarea>
</div>
</div>
<!-- Documents Tab -->
<div class="tab-content" id="documents">
+ <!-- Paperless-ngx Info Alert (hidden by default, shown when enabled) -->
+ <div id="paperlessInfoAlert" class="alert alert-info" style="display: none;">
+ <i class="fas fa-info-circle"></i>
+ <strong>Paperless-ngx Integration Enabled!</strong> You can now choose to store documents in your Paperless-ngx instance instead of locally.
+ </div>
+
+ <div class="form-group">
+ <label data-i18n="warranties.product_photo_optional">Product Photo (Optional)</label>
+ <div class="file-input-wrapper">
+ <label for="productPhoto" class="file-input-label">
+ <i class="fas fa-camera"></i> <span data-i18n="warranties.choose_photo">Choose Photo</span>
+ </label>
+ <input type="file" id="productPhoto" name="product_photo" class="file-input" accept=".png,.jpg,.jpeg,.webp">
+ </div>
+ <div id="productPhotoFileName" class="file-name"></div>
+ <div id="productPhotoPreview" class="photo-preview" style="display: none;">
+ <img id="productPhotoImg" src="" alt="Product Photo Preview" style="max-width: 200px; max-height: 200px; border-radius: 8px; margin-top: 10px;">
+ </div>
+
+ </div>
+
<div class="form-group">
- <label>Invoice/Receipt</label>
+ <label data-i18n="warranties.invoice_receipt">Invoice/Receipt</label>
+ <!-- Storage Selection -->
+ <div id="invoiceStorageSelection" class="storage-selection" style="display: none;">
+ <div class="storage-options">
+ <label class="storage-option">
+ <input type="radio" name="invoiceStorage" value="local" checked>
+ <span class="storage-label">
+ <i class="fas fa-hdd"></i> <span data-i18n="warranties.store_locally">Store Locally</span>
+ </span>
+ </label>
+ <label class="storage-option">
+ <input type="radio" name="invoiceStorage" value="paperless">
+ <span class="storage-label">
+ <i class="fas fa-cloud"></i> <span data-i18n="warranties.store_in_paperless">Store in Paperless-ngx</span>
+ </span>
+ </label>
+ </div>
+ </div>
<div class="file-input-wrapper">
<label for="invoice" class="file-input-label">
- <i class="fas fa-upload"></i> Choose File
+ <i class="fas fa-upload"></i> <span data-i18n="warranties.choose_file">Choose File</span>
</label>
<input type="file" id="invoice" name="invoice" class="file-input" accept=".pdf,.png,.jpg,.jpeg">
</div>
<div id="fileName" class="file-name"></div>
+ <!-- Paperless Browse Button -->
+ <div id="invoicePaperlessBrowse" class="paperless-browse-section" style="display: none;">
+ <button type="button" class="btn btn-secondary btn-sm" onclick="openPaperlessBrowser('invoice')">
+ <i class="fas fa-search"></i> <span data-i18n="warranties.browse_paperless">Browse Paperless-ngx Documents</span>
+ </button>
+ <div id="selectedInvoiceFromPaperless" class="selected-paperless-doc" style="display: none;">
+ <span class="selected-doc-name"></span>
+ <button type="button" class="btn btn-danger btn-xs" onclick="clearPaperlessSelection('invoice')">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
</div>
<div class="form-group">
- <label>Product Manual (Optional)</label>
+ <label data-i18n="warranties.product_manual_optional">Product Manual (Optional)</label>
+ <!-- Storage Selection -->
+ <div id="manualStorageSelection" class="storage-selection" style="display: none;">
+ <div class="storage-options">
+ <label class="storage-option">
+ <input type="radio" name="manualStorage" value="local" checked>
+ <span class="storage-label">
+ <i class="fas fa-hdd"></i> <span data-i18n="warranties.store_locally">Store Locally</span>
+ </span>
+ </label>
+ <label class="storage-option">
+ <input type="radio" name="manualStorage" value="paperless">
+ <span class="storage-label">
+ <i class="fas fa-cloud"></i> <span data-i18n="warranties.store_in_paperless">Store in Paperless-ngx</span>
+ </span>
+ </label>
+ </div>
+ </div>
<div class="file-input-wrapper">
<label for="manual" class="file-input-label">
- <i class="fas fa-upload"></i> Choose File
+ <i class="fas fa-upload"></i> <span data-i18n="warranties.choose_file">Choose File</span>
</label>
<input type="file" id="manual" name="manual" class="file-input" accept=".pdf,.png,.jpg,.jpeg">
</div>
<div id="manualFileName" class="file-name"></div>
+ <!-- Paperless Browse Button -->
+ <div id="manualPaperlessBrowse" class="paperless-browse-section" style="display: none;">
+ <button type="button" class="btn btn-secondary btn-sm" onclick="openPaperlessBrowser('manual')">
+ <i class="fas fa-search"></i> <span data-i18n="warranties.browse_paperless">Browse Paperless-ngx Documents</span>
+ </button>
+ <div id="selectedManualFromPaperless" class="selected-paperless-doc" style="display: none;">
+ <span class="selected-doc-name"></span>
+ <button type="button" class="btn btn-danger btn-xs" onclick="clearPaperlessSelection('manual')">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
</div>
<div class="form-group">
- <label>Files (ZIP/RAR, Optional)</label>
+ <label data-i18n="warranties.files_zip_rar_optional">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
+ <i class="fas fa-upload"></i> <span data-i18n="warranties.choose_file">Choose File</span>
</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">
<div class="form-group">
- <label>Add Tags</label>
- <p class="text-muted">Tags help you organize and filter your warranties</p>
+ <label data-i18n="warranties.add_tags">Add Tags</label>
+ <p class="text-muted" data-i18n="warranties.add_tags_desc">Tags help you organize and filter your warranties</p>
<div class="tags-container">
<div class="selected-tags" id="selectedTags">
@@ -414,7 +574,7 @@
</div>
<div class="tags-dropdown">
- <input type="text" id="tagSearch" class="form-control" placeholder="Search or add new tag...">
+ <input type="text" id="tagSearch" class="form-control" data-i18n-placeholder="warranties.search_or_add_tag" placeholder="Search or add new tag...">
<div class="tags-list" id="tagsList">
<!-- Tag options will be populated by JavaScript -->
</div>
@@ -422,7 +582,7 @@
<div class="mt-10">
<button type="button" id="manageTagsBtn" class="btn btn-secondary btn-sm">
- <i class="fas fa-cog"></i> Manage Tags
+ <i class="fas fa-cog"></i> <span data-i18n="actions.manage_tags">Manage Tags</span>
</button>
</div>
</div>
@@ -432,73 +592,81 @@
<div class="tab-content" id="summary">
<div class="summary-container">
<div class="summary-section">
- <h4><i class="fas fa-box"></i> Product Information</h4>
+ <h4><i class="fas fa-box"></i> <span data-i18n="warranties.product_information">Product Information</span></h4>
<div class="summary-item">
- <span class="summary-label">Product Name:</span>
+ <span class="summary-label" data-i18n="warranties.product_name">Product Name:</span>
<span id="summary-product-name" class="summary-value">-</span>
</div>
<div class="summary-item">
- <span class="summary-label">Product URL:</span>
+ <span class="summary-label" data-i18n="warranties.product_url">Product URL:</span>
<span id="summary-product-url" class="summary-value">-</span>
</div>
<div class="summary-item">
- <span class="summary-label">Serial Numbers:</span>
+ <span class="summary-label" data-i18n="warranties.serial_numbers">Serial Numbers:</span>
<span id="summary-serial-numbers" class="summary-value">-</span>
</div>
<div class="summary-item">
- <span class="summary-label">Vendor:</span>
+ <span class="summary-label" data-i18n="warranties.vendor">Vendor:</span>
<span id="summary-vendor" class="summary-value">-</span>
</div>
</div>
<div class="summary-section">
- <h4><i class="fas fa-shield-alt"></i> Warranty Details</h4>
+ <h4><i class="fas fa-shield-alt"></i> <span data-i18n="warranties.warranty_details">Warranty Details</span></h4>
<div class="summary-item">
- <span class="summary-label">Purchase Date:</span>
+ <span class="summary-label" data-i18n="warranties.purchase_date">Purchase Date:</span>
<span id="summary-purchase-date" class="summary-value">-</span>
</div>
<div class="summary-item">
- <span class="summary-label">Warranty Period:</span>
+ <span class="summary-label" data-i18n="warranties.warranty_period">Warranty Period:</span>
<span id="summary-warranty-duration" class="summary-value">-</span>
</div>
<div class="summary-item">
- <span class="summary-label">Purchase Price:</span>
+ <span class="summary-label" data-i18n="warranties.warranty_type">Warranty Type:</span>
+ <span id="summary-warranty-type" class="summary-value">-</span>
+ </div>
+ <div class="summary-item">
+ <span class="summary-label" data-i18n="warranties.purchase_price">Purchase Price:</span>
<span id="summary-purchase-price" class="summary-value">-</span>
</div>
</div>
<div class="summary-section">
- <h4><i class="fas fa-file-alt"></i> Documents</h4>
+ <h4><i class="fas fa-file-alt"></i> <span data-i18n="warranties.documents">Documents</span></h4>
+ <div class="summary-item">
+ <span class="summary-label" data-i18n="warranties.product_photo">Product Photo:</span>
+ <span id="summary-product-photo" class="summary-value">-</span>
+ </div>
<div class="summary-item">
- <span class="summary-label">Invoice/Receipt:</span>
+ <span class="summary-label" data-i18n="warranties.invoice_receipt">Invoice/Receipt:</span>
<span id="summary-invoice" class="summary-value">-</span>
</div>
<div class="summary-item">
- <span class="summary-label">Product Manual:</span>
+ <span class="summary-label" data-i18n="warranties.product_manual">Product Manual:</span>
<span id="summary-manual" class="summary-value">-</span>
</div>
<div class="summary-item">
- <span class="summary-label">Files:</span>
+ <span class="summary-label" data-i18n="warranties.files">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>
+ <h4><i class="fas fa-tags"></i> <span data-i18n="warranties.tags">Tags</span></h4>
<div class="summary-item">
- <span class="summary-label">Selected Tags:</span>
+ <span class="summary-label" data-i18n="warranties.selected_tags">Selected Tags:</span>
<div id="summary-tags" class="summary-value">-</div>
</div>
</div>
</div>
<div class="form-group">
- <button type="submit" class="btn btn-primary" id="submitWarrantyBtn">Add Warranty</button>
+ <button type="submit" class="btn btn-primary" id="submitWarrantyBtn" data-i18n="warranties.add_warranty">Add Warranty</button>
</div>
</div>
<!-- Tab Navigation -->
<div class="tab-navigation">
<button type="button" class="btn btn-secondary prev-tab" id="prevTabBtn">
- <i class="fas fa-arrow-left"></i> Previous
+ <i class="fas fa-arrow-left"></i> <span data-i18n="warranties.previous_tab">Previous</span>
</button>
<button type="button" class="btn btn-primary next-tab" id="nextTabBtn">
- Next <i class="fas fa-arrow-right"></i>
+ <span data-i18n="warranties.next_tab">Next</span> <i class="fas fa-arrow-right"></i>
</button>
</div>
</form>
@@ -517,57 +685,57 @@
<div id="editModal" class="modal-backdrop">
<div class="modal">
<div class="modal-header">
- <h3 class="modal-title">Edit Warranty</h3>
+ <h3 class="modal-title" data-i18n="warranties.edit_warranty">Edit Warranty</h3>
<button class="close-btn" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body">
<!-- Tab Navigation -->
<div class="edit-tabs-nav">
<button type="button" class="edit-tab-btn active" data-tab="edit-product-info">
- <i class="fas fa-box"></i> Product
+ <i class="fas fa-box"></i> <span data-i18n="warranties.product">Product</span>
</button>
<button type="button" class="edit-tab-btn" data-tab="edit-warranty-details">
- <i class="fas fa-shield-alt"></i> Warranty
+ <i class="fas fa-shield-alt"></i> <span data-i18n="warranties.warranty">Warranty</span>
</button>
<button type="button" class="edit-tab-btn" data-tab="edit-documents">
- <i class="fas fa-file-alt"></i> Documents
+ <i class="fas fa-file-alt"></i> <span data-i18n="warranties.documents">Documents</span>
</button>
<button type="button" class="edit-tab-btn" data-tab="edit-tags">
- <i class="fas fa-tags"></i> Tags
+ <i class="fas fa-tags"></i> <span data-i18n="warranties.tags">Tags</span>
</button>
</div>
- <form id="editWarrantyForm">
+ <form id="editWarrantyForm" novalidate>
<input type="hidden" id="editWarrantyId">
<!-- Product Info Tab -->
<div class="edit-tab-content active" id="edit-product-info">
<div class="form-group">
- <label for="editProductName">Product Name</label>
+ <label for="editProductName" data-i18n="warranties.product_name">Product Name</label>
<input type="text" id="editProductName" name="product_name" class="form-control" required>
</div>
<div class="form-group">
- <label for="editProductUrl">Product URL (Optional)</label>
- <input type="text" id="editProductUrl" name="product_url" class="form-control" placeholder="https://example.com/product">
+ <label for="editProductUrl" data-i18n="warranties.product_url_optional">Product URL (Optional)</label>
+ <input type="text" id="editProductUrl" name="product_url" class="form-control" data-i18n-placeholder="warranties.product_url_placeholder" placeholder="https://example.com/product">
</div>
<div class="form-group">
- <label>Serial Numbers</label>
+ <label data-i18n="warranties.serial_numbers">Serial Numbers</label>
<div id="editSerialNumbersContainer">
<!-- Serial number inputs will be added dynamically -->
</div>
</div>
<div class="form-group">
- <label for="editVendor">Vendor (Optional)</label>
- <input type="text" id="editVendor" name="vendor" class="form-control" placeholder="e.g. Amazon, Best Buy, etc.">
+ <label for="editVendor" data-i18n="warranties.vendor_optional">Vendor (Optional)</label>
+ <input type="text" id="editVendor" name="vendor" class="form-control" data-i18n-placeholder="warranties.vendor_placeholder" placeholder="e.g. Amazon, Best Buy, etc.">
</div>
</div>
<!-- Warranty Details Tab -->
<div class="edit-tab-content" id="edit-warranty-details">
<div class="form-group">
- <label for="editPurchaseDate">Purchase Date</label>
+ <label for="editPurchaseDate" data-i18n="warranties.purchase_date">Purchase Date</label>
<input type="date" id="editPurchaseDate" name="purchase_date" class="form-control" required>
</div>
@@ -575,89 +743,215 @@
<div class="form-group">
<label class="lifetime-label">
<input type="checkbox" id="editIsLifetime" name="is_lifetime" value="true">
- Lifetime Warranty
+ <span data-i18n="warranties.lifetime_warranty">Lifetime Warranty</span>
</label>
</div>
<!-- End Lifetime Checkbox -->
+ <!-- Warranty Entry Method Selection -->
+ <div class="form-group" id="editWarrantyEntryMethod">
+ <label data-i18n="warranties.warranty_entry_method">Warranty Entry Method</label>
+ <div class="warranty-method-options">
+ <label class="radio-option">
+ <input type="radio" id="editDurationMethod" name="edit_warranty_method" value="duration" checked>
+ <span data-i18n="warranties.warranty_duration_option">Warranty Duration</span>
+ </label>
+ <label class="radio-option">
+ <input type="radio" id="editExactDateMethod" name="edit_warranty_method" value="exact_date">
+ <span data-i18n="warranties.exact_expiration_option">Exact Expiration Date</span>
+ </label>
+ </div>
+ </div>
+
<div id="editWarrantyDurationFields">
<div class="form-group">
- <label for="editWarrantyDurationYears">Warranty Period</label>
+ <label for="editWarrantyDurationYears" data-i18n="warranties.warranty_period">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>
+ <input type="number" id="editWarrantyDurationYears" name="warranty_duration_years" class="form-control" min="0" max="999" data-i18n-placeholder="warranties.years_placeholder" placeholder="Years">
+ <small data-i18n="warranties.years">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>
+ <input type="number" id="editWarrantyDurationMonths" name="warranty_duration_months" class="form-control" min="0" max="999" data-i18n-placeholder="warranties.months_placeholder" placeholder="Months">
+ <small data-i18n="warranties.months">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>
+ <input type="number" id="editWarrantyDurationDays" name="warranty_duration_days" class="form-control" min="0" max="9999" data-i18n-placeholder="warranties.days_placeholder" placeholder="Days">
+ <small data-i18n="warranties.days">Days</small>
</div>
</div>
</div>
</div>
+ <div id="editExactExpirationField" style="display: none;">
+ <div class="form-group">
+ <label for="editExactExpirationDate" data-i18n="warranties.expiration_date_label">Expiration Date</label>
+ <input type="date" id="editExactExpirationDate" name="exact_expiration_date" class="form-control">
+ </div>
+ </div>
+
+ <div class="form-group">
+ <label for="editWarrantyType" data-i18n="warranties.warranty_type_optional">Warranty Type (Optional)</label>
+ <select id="editWarrantyType" name="warranty_type" class="form-control">
+ <option value="" data-i18n="warranties.select_warranty_type">Select warranty type...</option>
+ <option value="Standard" data-i18n="warranties.standard">Standard</option>
+ <option value="Extended" data-i18n="warranties.extended">Extended</option>
+ <option value="Manufacturer" data-i18n="warranties.manufacturer">Manufacturer</option>
+ <option value="Third Party" data-i18n="warranties.third_party">Third Party</option>
+ <option value="Store" data-i18n="warranties.store">Store</option>
+ <option value="Premium" data-i18n="warranties.premium">Premium</option>
+ <option value="Limited" data-i18n="warranties.limited">Limited</option>
+ <option value="Full" data-i18n="warranties.full">Full</option>
+ <option value="Parts Only" data-i18n="warranties.parts_only">Parts Only</option>
+ <option value="Labor Only" data-i18n="warranties.labor_only">Labor Only</option>
+ <option value="International" data-i18n="warranties.international">International</option>
+ <option value="Accidental Damage" data-i18n="warranties.accidental_damage">Accidental Damage</option>
+ <option value="other" data-i18n="warranties.other_custom">Other (Custom)</option>
+ </select>
+ <input type="text" id="editWarrantyTypeCustom" name="warranty_type_custom" class="form-control" style="display: none; margin-top: 8px;" data-i18n-placeholder="warranties.enter_custom_warranty_type_placeholder" placeholder="Enter custom warranty type">
+ </div>
+ <div class="form-group">
+ <label for="editCurrency" data-i18n="warranties.currency">Currency</label>
+ <select id="editCurrency" name="currency" class="form-control">
+ <option value="USD">USD - US Dollar ($)</option>
+ <!-- Currency options will be populated by JavaScript -->
+ </select>
+ </div>
<div class="form-group">
- <label for="editPurchasePrice">Purchase Price (Optional)</label>
- <div class="price-input-wrapper">
- <span class="currency-symbol">$</span>
+ <label for="editPurchasePrice" data-i18n="warranties.purchase_price_optional">Purchase Price (Optional)</label>
+ <div class="price-input-wrapper" id="editPriceInputWrapper">
+ <span class="currency-symbol" id="editCurrencySymbol">$</span>
<input type="number" id="editPurchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">
</div>
</div>
<div class="form-group">
- <label for="editNotes">Notes (Optional)</label>
- <textarea id="editNotes" name="notes" class="form-control" rows="3" placeholder="Add any notes about this warranty..."></textarea>
+ <label for="editNotes" data-i18n="warranties.notes_optional">Notes (Optional)</label>
+ <textarea id="editNotes" name="notes" class="form-control" rows="3" data-i18n-placeholder="warranties.add_any_notes_placeholder" placeholder="Add any notes about this warranty..."></textarea>
</div>
</div>
<!-- Documents Tab -->
<div class="edit-tab-content" id="edit-documents">
<div class="form-group">
- <label>Invoice/Receipt</label>
+ <label data-i18n="warranties.product_photo_optional">Product Photo (Optional)</label>
+ <div class="file-input-wrapper">
+ <label for="editProductPhoto" class="file-input-label">
+ <i class="fas fa-camera"></i> <span data-i18n="warranties.choose_photo">Choose Photo</span>
+ </label>
+ <input type="file" id="editProductPhoto" name="product_photo" class="file-input" accept=".png,.jpg,.jpeg,.webp">
+ </div>
+ <div id="editProductPhotoFileName" class="file-name"></div>
+ <div id="editProductPhotoPreview" class="photo-preview" style="display: none;">
+ <img id="editProductPhotoImg" src="" alt="Product Photo Preview" style="max-width: 200px; max-height: 200px; border-radius: 8px; margin-top: 10px;">
+ </div>
+ <div id="currentProductPhoto" class="mt-10"></div>
+ <button type="button" id="deleteProductPhotoBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> <span data-i18n="warranties.delete_photo">Delete Photo</span></button>
+
+ </div>
+
+ <div class="form-group">
+ <label data-i18n="warranties.invoice_receipt">Invoice/Receipt</label>
+ <!-- Storage Selection -->
+ <div id="editInvoiceStorageSelection" class="storage-selection" style="display: none;">
+ <div class="storage-options">
+ <label class="storage-option">
+ <input type="radio" name="editInvoiceStorage" value="local" checked>
+ <span class="storage-label">
+ <i class="fas fa-hdd"></i> <span data-i18n="warranties.store_locally">Store Locally</span>
+ </span>
+ </label>
+ <label class="storage-option">
+ <input type="radio" name="editInvoiceStorage" value="paperless">
+ <span class="storage-label">
+ <i class="fas fa-cloud"></i> <span data-i18n="warranties.store_in_paperless">Store in Paperless-ngx</span>
+ </span>
+ </label>
+ </div>
+ </div>
<div class="file-input-wrapper">
<label for="editInvoice" class="file-input-label">
- <i class="fas fa-upload"></i> Choose File
+ <i class="fas fa-upload"></i> <span data-i18n="warranties.choose_file">Choose File</span>
</label>
<input type="file" id="editInvoice" name="invoice" class="file-input" accept=".pdf,.png,.jpg,.jpeg">
</div>
<div id="editFileName" class="file-name"></div>
<div id="currentInvoice" class="mt-10"></div>
- <button type="button" id="deleteInvoiceBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Invoice</button>
+ <button type="button" id="deleteInvoiceBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> <span data-i18n="warranties.delete_invoice">Delete Invoice</span></button>
+ <!-- Paperless Browse Button -->
+ <div id="editInvoicePaperlessBrowse" class="paperless-browse-section" style="display: none;">
+ <button type="button" class="btn btn-secondary btn-sm" onclick="openPaperlessBrowser('edit_invoice')">
+ <i class="fas fa-search"></i> <span data-i18n="warranties.browse_paperless">Browse Paperless-ngx Documents</span>
+ </button>
+ <div id="selectedEditInvoiceFromPaperless" class="selected-paperless-doc" style="display: none;">
+ <span class="selected-doc-name"></span>
+ <button type="button" class="btn btn-danger btn-xs" onclick="clearPaperlessSelection('edit_invoice')">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
</div>
+
<div class="form-group">
- <label>Product Manual (Optional)</label>
+ <label data-i18n="warranties.product_manual_optional">Product Manual (Optional)</label>
+ <!-- Storage Selection -->
+ <div id="editManualStorageSelection" class="storage-selection" style="display: none;">
+ <div class="storage-options">
+ <label class="storage-option">
+ <input type="radio" name="editManualStorage" value="local" checked>
+ <span class="storage-label">
+ <i class="fas fa-hdd"></i> <span data-i18n="warranties.store_locally">Store Locally</span>
+ </span>
+ </label>
+ <label class="storage-option">
+ <input type="radio" name="editManualStorage" value="paperless">
+ <span class="storage-label">
+ <i class="fas fa-cloud"></i> <span data-i18n="warranties.store_in_paperless">Store in Paperless-ngx</span>
+ </span>
+ </label>
+ </div>
+ </div>
<div class="file-input-wrapper">
<label for="editManual" class="file-input-label">
- <i class="fas fa-upload"></i> Choose File
+ <i class="fas fa-upload"></i> <span data-i18n="warranties.choose_file">Choose File</span>
</label>
<input type="file" id="editManual" name="manual" class="file-input" accept=".pdf,.png,.jpg,.jpeg">
</div>
<div id="editManualFileName" class="file-name"></div>
<div id="currentManual" class="mt-10"></div>
- <button type="button" id="deleteManualBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Manual</button>
+ <button type="button" id="deleteManualBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> <span data-i18n="warranties.delete_manual">Delete Manual</span></button>
+ <!-- Paperless Browse Button -->
+ <div id="editManualPaperlessBrowse" class="paperless-browse-section" style="display: none;">
+ <button type="button" class="btn btn-secondary btn-sm" onclick="openPaperlessBrowser('edit_manual')">
+ <i class="fas fa-search"></i> <span data-i18n="warranties.browse_paperless">Browse Paperless-ngx Documents</span>
+ </button>
+ <div id="selectedEditManualFromPaperless" class="selected-paperless-doc" style="display: none;">
+ <span class="selected-doc-name"></span>
+ <button type="button" class="btn btn-danger btn-xs" onclick="clearPaperlessSelection('edit_manual')">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
</div>
<div class="form-group">
- <label>Files (ZIP/RAR, Optional)</label>
+ <label data-i18n="warranties.files_zip_rar_optional">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
+ <i class="fas fa-upload"></i> <span data-i18n="warranties.choose_file">Choose File</span>
</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>
+ <button type="button" id="deleteOtherDocumentBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> <span data-i18n="warranties.delete_files">Delete Files</span></button>
+
</div>
</div>
<!-- Tags Tab -->
<div class="edit-tab-content" id="edit-tags">
<div class="form-group">
- <label>Add Tags</label>
- <p class="text-muted">Tags help you organize and filter your warranties</p>
+ <label data-i18n="warranties.add_tags">Add Tags</label>
+ <p class="text-muted" data-i18n="warranties.add_tags_desc">Tags help you organize and filter your warranties</p>
<div class="tags-container">
<div class="selected-tags" id="editSelectedTags">
@@ -665,7 +959,7 @@
</div>
<div class="tags-dropdown">
- <input type="text" id="editTagSearch" class="form-control" placeholder="Search or add new tag...">
+ <input type="text" id="editTagSearch" class="form-control" data-i18n-placeholder="warranties.search_or_add_new_tag" placeholder="Search or add new tag...">
<div class="tags-list" id="editTagsList">
<!-- Tag options will be populated by JavaScript -->
</div>
@@ -673,7 +967,7 @@
<div class="mt-10">
<button type="button" id="editManageTagsBtn" class="btn btn-secondary btn-sm">
- <i class="fas fa-cog"></i> Manage Tags
+ <i class="fas fa-cog"></i> <span data-i18n="actions.manage_tags">Manage Tags</span>
</button>
</div>
</div>
@@ -682,26 +976,26 @@
</form>
</div>
<div class="modal-footer">
- <button class="btn btn-danger" data-dismiss="modal">Cancel</button>
- <button id="saveWarrantyBtn" class="btn btn-primary">Save Changes</button>
+ <button class="btn btn-danger" data-dismiss="modal" data-i18n="actions.cancel">Cancel</button>
+ <button id="saveWarrantyBtn" class="btn btn-primary" data-i18n="warranties.save_changes">Save Changes</button>
</div>
</div>
- </div>
+ </div>
<!-- Confirm Delete Modal -->
<div id="deleteModal" class="modal-backdrop">
<div class="modal">
<div class="modal-header">
- <h3 class="modal-title">Confirm Delete</h3>
+ <h3 class="modal-title" data-i18n="warranties.confirm_delete">Confirm Delete</h3>
<button class="close-btn" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body">
- <p>Are you sure you want to delete this warranty? This action cannot be undone.</p>
- <p><strong>Product:</strong> <span id="deleteProductName"></span></p>
+ <p data-i18n="warranties.confirm_delete_message">Are you sure you want to delete this warranty? This action cannot be undone.</p>
+ <p><strong><span data-i18n="warranties.product">Product</span>:</strong> <span id="deleteProductName"></span></p>
</div>
<div class="modal-footer">
- <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
- <button id="confirmDeleteBtn" class="btn btn-danger">Delete</button>
+ <button class="btn btn-secondary" data-dismiss="modal" data-i18n="actions.cancel">Cancel</button>
+ <button id="confirmDeleteBtn" class="btn btn-danger" data-i18n="actions.delete">Delete</button>
</div>
</div>
</div>
@@ -710,23 +1004,80 @@
<div id="tagManagementModal" class="modal-backdrop">
<div class="modal">
<div class="modal-header">
- <h3 class="modal-title">Manage Tags</h3>
+ <h3 class="modal-title" data-i18n="actions.manage_tags">Manage Tags</h3>
<button class="close-btn" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body">
<form id="newTagForm" class="tag-form">
- <input type="text" id="newTagName" class="form-control" placeholder="New tag name" required>
+ <input type="text" id="newTagName" class="form-control" data-i18n-placeholder="warranties.new_tag_name" placeholder="New tag name" required>
<input type="color" id="newTagColor" value="#808080">
- <button type="submit" class="btn btn-primary">Add Tag</button>
+ <button type="submit" class="btn btn-primary" data-i18n="warranties.add_tag">Add Tag</button>
</form>
- <h4 class="mt-20">Existing Tags</h4>
+ <h4 class="mt-20" data-i18n="warranties.existing_tags">Existing Tags</h4>
<div id="existingTags" class="existing-tags">
<!-- Tags will be populated here by JavaScript -->
</div>
</div>
<div class="modal-footer">
- <button class="btn btn-secondary" data-dismiss="modal">Close</button>
+ <button class="btn btn-secondary" data-dismiss="modal" data-i18n="actions.close">Close</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Paperless Document Browser Modal -->
+ <div id="paperlessBrowserModal" class="modal-backdrop">
+ <div class="modal modal-large">
+ <div class="modal-header">
+ <h3 class="modal-title">Browse Paperless-ngx Documents</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <div class="paperless-browser-controls">
+ <div class="search-section">
+ <input type="text" id="paperlessSearchInput" class="form-control" placeholder="Search documents by title, content, or tags...">
+ <button type="button" class="btn btn-primary" id="paperlessSearchBtn">
+ <i class="fas fa-search"></i> Search
+ </button>
+ <button type="button" class="btn btn-secondary" id="paperlessShowAllBtn">
+ <i class="fas fa-list"></i> Show All
+ </button>
+ </div>
+ <div class="filter-section">
+ <select id="paperlessTypeFilter" class="form-control">
+ <option value="">All Document Types</option>
+ <option value="application/pdf">PDF Documents</option>
+ <option value="image/jpeg,image/jpg,image/png">Images</option>
+ <option value="application/zip">Archives</option>
+ </select>
+ <select id="paperlessTagFilter" class="form-control">
+ <option value="">All Tags</option>
+ <!-- Tags will be populated dynamically -->
+ </select>
+ </div>
+ </div>
+
+ <div id="paperlessDocumentsList" class="paperless-documents-list">
+ <div class="loading-message" style="text-align: center; padding: 20px;">
+ <i class="fas fa-spinner fa-spin"></i> Loading documents...
+ </div>
+ </div>
+
+ <div class="pagination-controls" id="paperlessPagination" style="display: none;">
+ <button type="button" class="btn btn-secondary" id="prevPageBtn" onclick="changePage(-1)">
+ <i class="fas fa-chevron-left"></i> Previous
+ </button>
+ <span id="pageInfo">Page 1 of 1</span>
+ <button type="button" class="btn btn-secondary" id="nextPageBtn" onclick="changePage(1)">
+ Next <i class="fas fa-chevron-right"></i>
+ </button>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
+ <button id="selectPaperlessDocBtn" class="btn btn-primary" style="display: none;">
+ <i class="fas fa-check"></i> Select Document
+ </button>
</div>
</div>
</div>
@@ -739,8 +1090,58 @@
<div class="loading-spinner"></div>
</div>
- <script src="auth.js"></script>
- <script src="script.js"></script>
+ <script src="auth.js?v=20250119001"></script>
+ <script src="script.js?v=20250119001"></script>
+
+ <!-- Footer Width Fix -->
+ <script src="footer-fix.js?v=20250119001"></script>
+
+ <!-- Footer Content Manager -->
+ <script src="footer-content.js?v=20250119001"></script>
+
+ <!-- Powered by Warracker Footer -->
+ <footer class="warracker-footer" id="warrackerFooter">
+ <!-- Content will be dynamically generated by footer-content.js -->
+ </footer>
+
+ <script>
+ // Apply footer styles based on theme
+ function applyFooterStyles() {
+ const footer = document.getElementById('warrackerFooter');
+ const link = document.getElementById('warrackerFooterLink');
+ const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark' ||
+ document.documentElement.classList.contains('dark-mode') ||
+ document.body.classList.contains('dark-mode');
+
+ if (footer) {
+ if (isDarkMode) {
+ // Dark mode styles - using same background as header (#2d2d2d)
+ footer.style.cssText = 'margin-top: 50px; padding: 20px; text-align: center; border-top: 1px solid #444; background-color: #2d2d2d; color: #e0e0e0; font-size: 0.9rem;';
+ if (link) link.style.cssText = 'color: #4dabf7; text-decoration: none; font-weight: 500;';
+ } else {
+ // Light mode styles - using same background as header (#ffffff)
+ footer.style.cssText = 'margin-top: 50px; padding: 20px; text-align: center; border-top: 1px solid #e0e0e0; background-color: #ffffff; color: #333333; font-size: 0.9rem;';
+ if (link) link.style.cssText = 'color: #3498db; text-decoration: none; font-weight: 500;';
+ }
+ }
+ }
+
+ // Apply styles when page loads
+ document.addEventListener('DOMContentLoaded', applyFooterStyles);
+
+ // Watch for theme changes
+ const observer = new MutationObserver(applyFooterStyles);
+ observer.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: ['data-theme', 'class']
+ });
+
+ // Also watch body for theme changes
+ observer.observe(document.body, {
+ attributes: true,
+ attributeFilter: ['class']
+ });
+ </script>
</body>
</html>
diff --git a/frontend/js/i18n-debug.js b/frontend/js/i18n-debug.js
new file mode 100644
index 0000000..d3684af
--- /dev/null
+++ b/frontend/js/i18n-debug.js
@@ -0,0 +1,36 @@
+// Debug script to test i18next CDN loading
+console.log('=== i18next Debug Script ===');
+
+// Check if CDN scripts are loaded
+setTimeout(() => {
+ console.log('Checking i18next libraries:');
+ console.log('- i18next:', typeof i18next !== 'undefined' ? 'LOADED' : 'NOT LOADED');
+ console.log('- i18nextHttpBackend:', typeof i18nextHttpBackend !== 'undefined' ? 'LOADED' : 'NOT LOADED');
+ console.log('- i18nextBrowserLanguageDetector:', typeof i18nextBrowserLanguageDetector !== 'undefined' ? 'LOADED' : 'NOT LOADED');
+
+ // Test basic fetch to translation file
+ fetch('/locales/en/translation.json')
+ .then(response => {
+ console.log('Translation file fetch status:', response.status);
+ return response.json();
+ })
+ .then(data => {
+ console.log('Translation file loaded successfully, keys:', Object.keys(data).slice(0, 5));
+ })
+ .catch(error => {
+ console.error('Failed to load translation file:', error);
+ });
+
+ // Test API endpoint
+ fetch('/api/locales')
+ .then(response => {
+ console.log('Locales API status:', response.status);
+ return response.json();
+ })
+ .then(data => {
+ console.log('Locales API response:', data);
+ })
+ .catch(error => {
+ console.error('Failed to load locales API:', error);
+ });
+}, 2000); // Wait 2 seconds for CDN scripts to load
\ No newline at end of file
diff --git a/frontend/js/i18n.js b/frontend/js/i18n.js
new file mode 100644
index 0000000..46d5c5a
--- /dev/null
+++ b/frontend/js/i18n.js
@@ -0,0 +1,416 @@
+/**
+ * i18next Configuration and Initialization
+ * Handles frontend localization with offline support
+ */
+
+// Global i18n object to make translation functions available
+window.i18n = {};
+
+// Supported languages
+const SUPPORTED_LANGUAGES = ['en', 'fr', 'es', 'de', 'it', 'cs', 'nl', 'hi', 'fa', 'ar', 'ru', 'uk', 'zh_CN', 'zh_HK', 'ja', 'pt', 'ko'];
+const DEFAULT_LANGUAGE = 'en';
+const RTL_LANGUAGES = ['ar', 'fa']; // Arabic and Persian are RTL languages
+
+/**
+ * Initialize i18next with configuration
+ */
+async function initializeI18n() {
+ console.log('Initializing i18next...');
+
+ // Debug: Check if required libraries are loaded
+ if (typeof i18next === 'undefined') {
+ console.error('i18next library not loaded');
+ return;
+ }
+
+ console.log('i18next library loaded successfully');
+
+ // Check optional libraries
+ const hasHttpBackend = typeof i18nextHttpBackend !== 'undefined';
+ const hasLanguageDetector = typeof i18nextBrowserLanguageDetector !== 'undefined';
+
+ console.log('Optional libraries:', {
+ httpBackend: hasHttpBackend,
+ languageDetector: hasLanguageDetector
+ });
+
+ try {
+ // Get current language from various sources
+ const savedLanguage = getCurrentLanguage();
+ console.log('Initial language detected:', savedLanguage);
+
+ // Load translations manually since HttpBackend might not be available
+ const translations = await loadTranslations(savedLanguage);
+
+ // Configure i18next with or without plugins
+ let i18nextInstance = i18next;
+
+ if (hasLanguageDetector) {
+ i18nextInstance = i18nextInstance.use(i18nextBrowserLanguageDetector);
+ }
+
+ await i18nextInstance.init({
+ fallbackLng: DEFAULT_LANGUAGE,
+ supportedLngs: SUPPORTED_LANGUAGES,
+ debug: false,
+
+ // Set initial language and resources
+ lng: savedLanguage,
+ resources: translations,
+
+ // Language detection configuration (only if detector is available)
+ ...(hasLanguageDetector && {
+ detection: {
+ order: ['cookie', 'localStorage', 'navigator', 'htmlTag'],
+ lookupCookie: 'lang',
+ lookupLocalStorage: 'preferred_language',
+ caches: ['cookie', 'localStorage'],
+ cookieOptions: {
+ path: '/',
+ maxAge: 365 * 24 * 60 * 60 // 1 year
+ }
+ }
+ }),
+
+ // Interpolation options
+ interpolation: {
+ escapeValue: false
+ }
+ });
+
+ // Store translation function globally
+ window.i18n.t = i18next.t.bind(i18next);
+ window.i18n.changeLanguage = changeLanguage;
+ window.i18n.getCurrentLanguage = getCurrentLanguage;
+ window.i18n.getSupportedLanguages = () => SUPPORTED_LANGUAGES;
+
+ // Initialize page translations
+ translatePage();
+
+ // Set initial page direction
+ updatePageDirection(i18next.language);
+
+ // Set up language change listener
+ i18next.on('languageChanged', (lng) => {
+ console.log('Language changed to:', lng);
+ translatePage();
+ updateLanguageAttribute(lng);
+ updatePageDirection(lng);
+ });
+
+ console.log('i18next initialized successfully with language:', i18next.language);
+
+ // Dispatch event to notify other scripts that i18n is ready
+ window.dispatchEvent(new CustomEvent('i18nReady', {
+ detail: {
+ language: i18next.language,
+ t: window.i18n.t
+ }
+ }));
+
+ } catch (error) {
+ console.error('Failed to initialize i18next:', error);
+ // Fallback to default language without i18next
+ window.i18n.t = (key) => key; // Return key as fallback
+ window.i18n.changeLanguage = () => {};
+ window.i18n.getCurrentLanguage = () => DEFAULT_LANGUAGE;
+ window.i18n.getSupportedLanguages = () => SUPPORTED_LANGUAGES;
+
+ // Still dispatch event so other scripts know i18n is "ready" (even with fallback)
+ window.dispatchEvent(new CustomEvent('i18nReady', {
+ detail: {
+ language: DEFAULT_LANGUAGE,
+ t: window.i18n.t,
+ fallback: true
+ }
+ }));
+ }
+}
+
+/**
+ * Load translations for a specific language
+ */
+async function loadTranslations(language) {
+ const translations = {};
+
+ try {
+ // Load primary language
+ const response = await fetch(`/locales/${language}/translation.json?v=${Date.now()}`);
+ if (response.ok) {
+ const data = await response.json();
+ translations[language] = { translation: data };
+ console.log(`Loaded translations for ${language}:`, Object.keys(data).slice(0, 5));
+ } else {
+ console.warn(`Failed to load translations for ${language}, status: ${response.status}`);
+ }
+ } catch (error) {
+ console.error(`Error loading translations for ${language}:`, error);
+ }
+
+ // Always load fallback language if different
+ if (language !== DEFAULT_LANGUAGE) {
+ try {
+ const fallbackResponse = await fetch(`/locales/${DEFAULT_LANGUAGE}/translation.json?v=${Date.now()}`);
+ if (fallbackResponse.ok) {
+ const fallbackData = await fallbackResponse.json();
+ translations[DEFAULT_LANGUAGE] = { translation: fallbackData };
+ console.log(`Loaded fallback translations for ${DEFAULT_LANGUAGE}`);
+ }
+ } catch (error) {
+ console.error(`Error loading fallback translations:`, error);
+ }
+ }
+
+ return translations;
+}
+
+/**
+ * Get current language from storage or user preferences
+ */
+function getCurrentLanguage() {
+ // Check cookie first
+ const cookieLang = getCookie('lang');
+ if (cookieLang && SUPPORTED_LANGUAGES.includes(cookieLang)) {
+ return cookieLang;
+ }
+
+ // Check localStorage
+ const storedLang = localStorage.getItem('preferred_language');
+ if (storedLang && SUPPORTED_LANGUAGES.includes(storedLang)) {
+ return storedLang;
+ }
+
+ // Check user preferences from API if authenticated
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ if (userInfo.preferred_language && SUPPORTED_LANGUAGES.includes(userInfo.preferred_language)) {
+ return userInfo.preferred_language;
+ }
+
+ // Fallback to browser language or default
+ const browserLang = navigator.language?.split('-')[0];
+ return SUPPORTED_LANGUAGES.includes(browserLang) ? browserLang : DEFAULT_LANGUAGE;
+}
+
+/**
+ * Change language and persist preference
+ */
+async function changeLanguage(language) {
+ if (!SUPPORTED_LANGUAGES.includes(language)) {
+ console.warn('Unsupported language:', language);
+ return;
+ }
+
+ try {
+ // Load translations for the new language
+ const translations = await loadTranslations(language);
+
+ // Add new language resources to i18next
+ for (const [lng, resources] of Object.entries(translations)) {
+ i18next.addResourceBundle(lng, 'translation', resources.translation, true, true);
+ }
+
+ // Change language in i18next
+ await i18next.changeLanguage(language);
+
+ // Persist to cookie and localStorage
+ setCookie('lang', language, 365);
+ localStorage.setItem('preferred_language', language);
+
+ // Update user preference in backend if authenticated
+ if (localStorage.getItem('auth_token')) {
+ try {
+ await saveLanguagePreference(language);
+ } catch (error) {
+ console.warn('Failed to save language preference to backend:', error);
+ }
+ }
+
+ // Dispatch event for other components
+ window.dispatchEvent(new CustomEvent('languageChanged', { detail: { language } }));
+
+ } catch (error) {
+ console.error('Failed to change language:', error);
+ }
+}
+
+/**
+ * Save language preference to backend
+ */
+async function saveLanguagePreference(language) {
+ const token = localStorage.getItem('auth_token');
+ if (!token) return;
+
+ const response = await fetch('/api/user/language-preference', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ preferred_language: language })
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to save language preference');
+ }
+}
+
+/**
+ * Translate all elements on the current page
+ */
+function translatePage() {
+ if (!window.i18n.t) {
+ console.warn('Translation function not available, skipping translation');
+ return;
+ }
+
+ console.log('Starting page translation...');
+ let translatedCount = 0;
+
+ // Update dynamic titles that are set by JavaScript
+ updateDynamicTitles();
+
+ // Translate elements with data-i18n attribute
+ document.querySelectorAll('[data-i18n]').forEach(element => {
+ const key = element.getAttribute('data-i18n');
+ const translation = window.i18n.t(key);
+
+ if (translation && translation !== key) {
+ if (element.tagName === 'INPUT' && (element.type === 'text' || element.type === 'email' || element.type === 'password')) {
+ element.placeholder = translation;
+ } else if (element.hasAttribute('title')) {
+ element.title = translation;
+ } else {
+ element.textContent = translation;
+ }
+ translatedCount++;
+ } else {
+ console.warn(`No translation found for key: ${key}`);
+ }
+ });
+
+ // Translate elements with data-i18n-html attribute (allows HTML content)
+ document.querySelectorAll('[data-i18n-html]').forEach(element => {
+ const key = element.getAttribute('data-i18n-html');
+ const translation = window.i18n.t(key);
+ element.innerHTML = translation;
+ });
+
+ // Translate elements with data-i18n-title attribute
+ document.querySelectorAll('[data-i18n-title]').forEach(element => {
+ const key = element.getAttribute('data-i18n-title');
+ const translation = window.i18n.t(key);
+ element.title = translation;
+ });
+
+ // Translate elements with data-i18n-placeholder attribute
+ document.querySelectorAll('[data-i18n-placeholder]').forEach(element => {
+ const key = element.getAttribute('data-i18n-placeholder');
+ const translation = window.i18n.t(key);
+ if (translation && translation !== key) {
+ element.placeholder = translation;
+ translatedCount++;
+ }
+ });
+
+ console.log(`Page translation completed. Translated ${translatedCount} elements.`);
+
+ // Re-process warranties to update status text and labels if warranties exist
+ if (typeof warranties !== 'undefined' && warranties && warranties.length > 0) {
+ console.log(`[i18n.js] Re-processing ${warranties.length} warranties after language change`);
+ // Re-process each warranty to update status text with new language
+ warranties = warranties.map(warranty => {
+ if (typeof processWarrantyData === 'function') {
+ return processWarrantyData(warranty);
+ }
+ return warranty;
+ });
+ // Re-render warranties with new translations
+ if (typeof applyFilters === 'function') {
+ applyFilters();
+ }
+ }
+}
+
+/**
+ * Update dynamic titles that are set by JavaScript
+ */
+function updateDynamicTitles() {
+ // Update warranties panel title on index.html
+ if (typeof updateWarrantiesPanelTitle === 'function' && typeof isGlobalView !== 'undefined') {
+ updateWarrantiesPanelTitle(isGlobalView);
+ }
+
+ // Update dashboard title on status.html
+ if (typeof updateDashboardTitle === 'function') {
+ updateDashboardTitle();
+ }
+
+ // Re-process warranty cards if they exist (for dynamic status text)
+ if (typeof processAllWarranties === 'function') {
+ processAllWarranties();
+ }
+}
+
+/**
+ * Update HTML lang attribute
+ */
+function updateLanguageAttribute(language) {
+ document.documentElement.lang = language;
+}
+
+/**
+ * Update page direction for RTL languages
+ */
+function updatePageDirection(language) {
+ const isRTL = RTL_LANGUAGES.includes(language);
+ const htmlElement = document.documentElement;
+ const bodyElement = document.body;
+
+ if (isRTL) {
+ htmlElement.dir = 'rtl';
+ htmlElement.setAttribute('data-rtl', 'true');
+ bodyElement.classList.add('rtl');
+ console.log(`Applied RTL direction for language: ${language}`);
+ } else {
+ htmlElement.dir = 'ltr';
+ htmlElement.removeAttribute('data-rtl');
+ bodyElement.classList.remove('rtl');
+ console.log(`Applied LTR direction for language: ${language}`);
+ }
+}
+
+/**
+ * Utility function to get cookie value
+ */
+function getCookie(name) {
+ const value = `; ${document.cookie}`;
+ const parts = value.split(`; ${name}=`);
+ if (parts.length === 2) return parts.pop().split(';').shift();
+ return null;
+}
+
+/**
+ * Utility function to set cookie
+ */
+function setCookie(name, value, days) {
+ const expires = new Date();
+ expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
+ document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/`;
+}
+
+/**
+ * Add translation helper for dynamic content
+ */
+function t(key, options = {}) {
+ return window.i18n.t ? window.i18n.t(key, options) : key;
+}
+
+// Expose translation function globally
+window.t = t;
+
+// Initialize when DOM is ready
+if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', initializeI18n);
+} else {
+ initializeI18n();
+}
diff --git a/frontend/login.html b/frontend/login.html
index 285d8b4..0cbe57e 100644
--- a/frontend/login.html
+++ b/frontend/login.html
@@ -1,26 +1,32 @@
<!DOCTYPE html>
-<html lang="en">
+<html>
<head>
<!-- Authentication redirect script -->
- <script src="auth-redirect.js" data-protected="false"></script>
+ <script src="auth-redirect.js?v=20250119001" data-protected="false"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Login - Warracker</title>
+ <title data-i18n="auth.login">Login - Warracker</title>
<!-- Favicons -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
<link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
<link rel="manifest" href="manifest.json">
- <link rel="stylesheet" href="style.css">
- <script src="theme-loader.js"></script> <!-- Apply theme early -->
+ <link rel="stylesheet" href="style.css?v=20250119001">
+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Load header fix styles to ensure consistent header styling -->
- <link rel="stylesheet" href="header-fix.css">
+ <link rel="stylesheet" href="header-fix.css?v=20250119001">
+ <!-- i18next Local Scripts -->
+ <script src="js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <!-- i18n initialization script -->
+ <script src="js/i18n.js?v=20250119001"></script>
<!-- Load fix for auth buttons -->
- <script src="fix-auth-buttons-loader.js"></script>
+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
<style>
.auth-container {
max-width: 400px;
@@ -95,10 +101,155 @@
color: var(--text-muted);
cursor: pointer;
}
+
+ /* Provider-specific SSO button styles */
+ .btn-google {
+ background-color: #4285f4;
+ border-color: #4285f4;
+ color: white;
+ }
+
+ .btn-google:hover, .btn-google:focus {
+ background-color: #357ae8;
+ border-color: #357ae8;
+ color: white;
+ }
+
+ .btn-github {
+ background-color: #333;
+ border-color: #333;
+ color: white;
+ }
+
+ .btn-github:hover, .btn-github:focus {
+ background-color: #24292e;
+ border-color: #24292e;
+ color: white;
+ }
+
+ .btn-microsoft {
+ background-color: #0078d4;
+ border-color: #0078d4;
+ color: white;
+ }
+
+ .btn-microsoft:hover, .btn-microsoft:focus {
+ background-color: #106ebe;
+ border-color: #106ebe;
+ color: white;
+ }
+
+ .btn-facebook {
+ background-color: #1877f2;
+ border-color: #1877f2;
+ color: white;
+ }
+
+ .btn-facebook:hover, .btn-facebook:focus {
+ background-color: #166fe5;
+ border-color: #166fe5;
+ color: white;
+ }
+
+ .btn-twitter {
+ background-color: #1da1f2;
+ border-color: #1da1f2;
+ color: white;
+ }
+
+ .btn-twitter:hover, .btn-twitter:focus {
+ background-color: #0d95e8;
+ border-color: #0d95e8;
+ color: white;
+ }
+
+ .btn-linkedin {
+ background-color: #0077b5;
+ border-color: #0077b5;
+ color: white;
+ }
+
+ .btn-linkedin:hover, .btn-linkedin:focus {
+ background-color: #005885;
+ border-color: #005885;
+ color: white;
+ }
+
+ .btn-apple {
+ background-color: #000;
+ border-color: #000;
+ color: white;
+ }
+
+ .btn-apple:hover, .btn-apple:focus {
+ background-color: #333;
+ border-color: #333;
+ color: white;
+ }
+
+ .btn-discord {
+ background-color: #5865f2;
+ border-color: #5865f2;
+ color: white;
+ }
+
+ .btn-discord:hover, .btn-discord:focus {
+ background-color: #4752c4;
+ border-color: #4752c4;
+ color: white;
+ }
+
+ .btn-gitlab {
+ background-color: #fca326;
+ border-color: #fca326;
+ color: white;
+ }
+
+ .btn-gitlab:hover, .btn-gitlab:focus {
+ background-color: #fc9403;
+ border-color: #fc9403;
+ color: white;
+ }
+
+ .btn-bitbucket {
+ background-color: #0052cc;
+ border-color: #0052cc;
+ color: white;
+ }
+
+ .btn-bitbucket:hover, .btn-bitbucket:focus {
+ background-color: #0047b3;
+ border-color: #0047b3;
+ color: white;
+ }
+
+ .btn-keycloak {
+ background-color: #4d4d4d;
+ border-color: #4d4d4d;
+ color: white;
+ }
+
+ .btn-keycloak:hover, .btn-keycloak:focus {
+ background-color: #333;
+ border-color: #333;
+ color: white;
+ }
+
+ .btn-okta {
+ background-color: #007dc1;
+ border-color: #007dc1;
+ color: white;
+ }
+
+ .btn-okta:hover, .btn-okta:focus {
+ background-color: #005a8b;
+ border-color: #005a8b;
+ color: white;
+ }
</style>
<!-- Registration status check script -->
- <script src="registration-status.js"></script>
+ <script src="registration-status.js?v=20250119001"></script>
</head>
<body>
<!-- Header -->
@@ -114,18 +265,18 @@
<!-- Main Content -->
<div class="container">
<div class="auth-container">
- <h2 class="auth-title">Login to Your Account</h2>
+ <h2 class="auth-title" data-i18n="auth.login">Login to Your Account</h2>
<div id="authMessage" class="auth-message"></div>
<form id="loginForm" class="auth-form">
<div class="form-group">
- <label for="username">Username or Email</label>
- <input type="text" id="username" name="username" class="form-control" required>
+ <label for="username" data-i18n="auth.username">Username or Email</label>
+ <input type="text" id="username" name="username" class="form-control" data-i18n-placeholder="auth.username" placeholder="Username or Email" required>
</div>
<div class="form-group">
- <label for="password">Password</label>
+ <label for="password" data-i18n="auth.password">Password</label>
<div class="password-container">
<input type="password" id="password" name="password" class="form-control" required>
<button type="button" class="password-toggle" title="Show/Hide Password">
@@ -135,21 +286,219 @@
</div>
<button type="submit" class="btn btn-primary btn-block">
- <i class="fas fa-sign-in-alt"></i> Login
+ <i class="fas fa-sign-in-alt"></i> <span data-i18n="auth.login">Login</span>
</button>
</form>
+
+ <div style="text-align: center; margin: 20px 0; color: var(--text-muted);">
+ <hr style="border-top: 1px solid var(--border-color); margin-bottom: 10px;">
+ OR
+ </div>
+
+ <a href="/api/oidc/login" id="oidcLoginButton" class="btn btn-secondary btn-block" style="text-decoration: none; display: flex; align-items: center; justify-content: center;">
+ <i class="fab fa-openid" style="margin-right: 8px;"></i> Login with SSO Provider
+ </a>
- <div class="auth-links">
- <a href="register.html">Create Account</a>
- <a href="reset-password-request.html">Forgot Password?</a>
+ <div class="auth-links" style="margin-top: 30px;">
+ <a href="register.html" data-i18n="auth.register">Create Account</a>
+ <a href="reset-password-request.html" data-i18n="auth.forgot_password">Forgot Password?</a>
</div>
</div>
</div>
<!-- Script for authentication -->
- <script src="auth.js"></script>
+ <script src="auth.js?v=20250119001"></script>
+
+ <!-- Footer Width Fix -->
+ <script src="footer-fix.js?v=20250119001"></script>
+
+ <!-- Footer Content Manager -->
+ <script src="footer-content.js?v=20250119001"></script>
+
+ <!-- Powered by Warracker Footer -->
+ <footer class="warracker-footer" id="warrackerFooter">
+ <!-- Content will be dynamically generated by footer-content.js -->
+ </footer>
+
<script>
document.addEventListener('DOMContentLoaded', function() {
+ // Check for OIDC errors in URL parameters and display them
+ const urlParams = new URLSearchParams(window.location.search);
+ const oidcError = urlParams.get('oidc_error');
+
+ if (oidcError) {
+ let errorMessage = 'An unknown error occurred during SSO login.';
+ switch (oidcError) {
+ case 'oidc_disabled':
+ errorMessage = 'SSO login is currently disabled.';
+ break;
+ case 'oidc_misconfigured':
+ errorMessage = 'SSO is not properly configured. Please contact your administrator.';
+ break;
+ case 'token_exchange_failed':
+ errorMessage = 'Failed to exchange authorization code for tokens with the SSO provider.';
+ break;
+ case 'token_missing':
+ errorMessage = 'Access token was not received from the SSO provider.';
+ break;
+ case 'userinfo_fetch_failed':
+ errorMessage = 'Failed to fetch user information from the SSO provider.';
+ break;
+ case 'userinfo_missing':
+ errorMessage = 'User information was not received from the SSO provider.';
+ break;
+ case 'subject_missing':
+ errorMessage = 'User subject identifier (sub) was missing from SSO provider response.';
+ break;
+ case 'email_missing_for_new_user':
+ errorMessage = 'Email address was not provided by SSO provider, which is required for new user registration.';
+ break;
+ case 'email_conflict_local_account':
+ errorMessage = 'The email address from your SSO provider is already associated with an existing local account. Please log in with your local credentials or contact support.';
+ break;
+ case 'registration_disabled':
+ errorMessage = 'New user registration via SSO is currently disabled. Only existing users can log in with SSO. Please contact your administrator if you need an account.';
+ break;
+ case 'user_processing_failed':
+ errorMessage = 'Failed to process user information after SSO login.';
+ break;
+ case 'db_error':
+ errorMessage = 'A database error occurred during SSO login. Please try again later.';
+ break;
+ case 'internal_error':
+ errorMessage = 'An internal server error occurred during SSO login. Please try again later.';
+ break;
+ }
+ showMessage(errorMessage, 'error');
+
+ // Clean up the URL by removing the oidc_error parameter
+ const newUrl = new URL(window.location);
+ newUrl.searchParams.delete('oidc_error');
+ window.history.replaceState({}, document.title, newUrl);
+ }
+
+ // Fetch OIDC status and customize button based on provider
+ fetch('/api/auth/oidc-status')
+ .then(response => response.json())
+ .then(data => {
+ const oidcButton = document.getElementById('oidcLoginButton');
+ const orSeparator = document.querySelector('.auth-form + div[style*="text-align: center"]');
+ const loginForm = document.getElementById('loginForm');
+ const authLinks = document.querySelector('.auth-links');
+
+ if (!data.oidc_enabled) {
+ if (oidcButton) oidcButton.style.display = 'none';
+ if (orSeparator) orSeparator.style.display = 'none';
+ return;
+ }
+
+ // Handle OIDC-only mode
+ if (data.oidc_only_mode) {
+ // Hide traditional login form and related elements
+ if (loginForm) loginForm.style.display = 'none';
+ if (orSeparator) orSeparator.style.display = 'none';
+ if (authLinks) {
+ // Hide register and forgot password links in OIDC-only mode
+ const registerLink = authLinks.querySelector('a[href="register.html"]');
+ const forgotPasswordLink = authLinks.querySelector('a[href="reset-password-request.html"]');
+ if (registerLink) registerLink.style.display = 'none';
+ if (forgotPasswordLink) forgotPasswordLink.style.display = 'none';
+
+ // If all links are hidden, hide the entire auth-links section
+ const visibleLinks = Array.from(authLinks.querySelectorAll('a')).filter(link =>
+ link.style.display !== 'none'
+ );
+ if (visibleLinks.length === 0) {
+ authLinks.style.display = 'none';
+ }
+ }
+
+ // Update page title to reflect OIDC-only mode
+ const authTitle = document.querySelector('.auth-title');
+ if (authTitle) {
+ authTitle.textContent = 'Login with SSO';
+ }
+ }
+
+ // Customize button based on provider
+ if (oidcButton && data.oidc_provider_display_name) {
+ const providerName = data.oidc_provider_display_name.toLowerCase();
+ let buttonText = `Login with ${data.oidc_provider_display_name}`;
+ let iconClass = 'fab fa-openid'; // Default icon
+ let buttonClass = 'btn-secondary'; // Default class
+
+ // Provider-specific customizations
+ switch (providerName) {
+ case 'google':
+ iconClass = 'fab fa-google';
+ buttonClass = 'btn-google';
+ break;
+ case 'github':
+ iconClass = 'fab fa-github';
+ buttonClass = 'btn-github';
+ break;
+ case 'microsoft':
+ case 'azure':
+ case 'office365':
+ iconClass = 'fab fa-microsoft';
+ buttonClass = 'btn-microsoft';
+ break;
+ case 'facebook':
+ iconClass = 'fab fa-facebook-f';
+ buttonClass = 'btn-facebook';
+ break;
+ case 'twitter':
+ iconClass = 'fab fa-twitter';
+ buttonClass = 'btn-twitter';
+ break;
+ case 'linkedin':
+ iconClass = 'fab fa-linkedin-in';
+ buttonClass = 'btn-linkedin';
+ break;
+ case 'apple':
+ iconClass = 'fab fa-apple';
+ buttonClass = 'btn-apple';
+ break;
+ case 'discord':
+ iconClass = 'fab fa-discord';
+ buttonClass = 'btn-discord';
+ break;
+ case 'gitlab':
+ iconClass = 'fab fa-gitlab';
+ buttonClass = 'btn-gitlab';
+ break;
+ case 'bitbucket':
+ iconClass = 'fab fa-bitbucket';
+ buttonClass = 'btn-bitbucket';
+ break;
+ case 'keycloak':
+ iconClass = 'fas fa-key';
+ buttonClass = 'btn-keycloak';
+ break;
+ case 'okta':
+ iconClass = 'fas fa-shield-alt';
+ buttonClass = 'btn-okta';
+ break;
+ default:
+ // Keep generic styling for unknown providers
+ buttonText = `Login with ${data.oidc_provider_display_name}`;
+ break;
+ }
+
+ // Update button styling and content
+ oidcButton.className = `btn ${buttonClass} btn-block`;
+ oidcButton.innerHTML = `<i class="${iconClass}" style="margin-right: 8px;"></i> ${buttonText}`;
+ }
+ })
+ .catch(error => {
+ console.error('Error fetching OIDC status:', error);
+ // Hide button on error as a safe default
+ const oidcButton = document.getElementById('oidcLoginButton');
+ const orSeparator = document.querySelector('.auth-form + div[style*="text-align: center"]');
+ if (oidcButton) oidcButton.style.display = 'none';
+ if (orSeparator) orSeparator.style.display = 'none';
+ });
+
// Toggle password visibility
const passwordToggle = document.querySelector('.password-toggle');
const passwordInput = document.getElementById('password');
@@ -166,7 +515,6 @@
// Handle form submission
const loginForm = document.getElementById('loginForm');
- const authMessage = document.getElementById('authMessage');
loginForm.addEventListener('submit', async function(e) {
e.preventDefault();
@@ -229,12 +577,19 @@
// Helper function to show messages
function showMessage(message, type) {
+ const authMessage = document.getElementById('authMessage');
authMessage.textContent = message;
authMessage.className = 'auth-message';
authMessage.classList.add(type);
authMessage.style.display = 'block';
}
});
+
+ // Footer styling (this will be replaced by footer-fix.js but kept for compatibility)
+ function applyFooterStyles() {
+ // Footer-fix.js will handle this, but this is a fallback
+ }
+ document.addEventListener('DOMContentLoaded', applyFooterStyles);
</script>
</body>
</html>
diff --git a/frontend/mobile-header.css b/frontend/mobile-header.css
index 9f66f3e..70fd79a 100644
--- a/frontend/mobile-header.css
+++ b/frontend/mobile-header.css
@@ -376,9 +376,22 @@
.search-container .import-btn,
.search-container #globalManageTagsBtn {
flex: 1 1 calc(33.333% - 5px) !important;
- min-width: 90px !important;
+ min-width: 50px !important;
padding: 10px 8px !important;
- font-size: 0.8rem !important;
+ font-size: 0.9rem !important;
+ }
+
+ /* Hide text on small screens for action buttons */
+ .search-container .export-btn span,
+ .search-container .import-btn span,
+ .search-container #globalManageTagsBtn span {
+ display: none;
+ }
+
+ .search-container .export-btn i,
+ .search-container .import-btn i,
+ .search-container #globalManageTagsBtn i {
+ margin-right: 0 !important;
}
}
@@ -700,4 +713,252 @@
.status-card .card-content .count {
font-size: 1.5rem !important;
}
+}
+
+@media (max-width: 768px) {
+ .warranties-list.list-view {
+ display: block !important;
+ }
+
+ .warranties-list.list-view .warranty-card {
+ display: block !important;
+ margin-bottom: 15px !important;
+ }
+
+ /* ===== MOBILE LIST VIEW OPTIMIZATIONS ===== */
+
+ /* Reduce padding and margins for mobile list view cards */
+ .list-view .warranty-card {
+ margin-bottom: 10px !important;
+ border-radius: 6px !important;
+ }
+
+ /* Optimize product name header for mobile */
+ .list-view .product-name-header {
+ padding: 10px 12px !important;
+ font-size: 1rem !important;
+ }
+
+ .list-view .product-name-header .warranty-title {
+ font-size: 1rem !important;
+ line-height: 1.3 !important;
+ white-space: normal !important; /* Allow wrapping on mobile */
+ overflow: visible !important;
+ text-overflow: clip !important;
+ max-width: calc(100% - 70px) !important; /* Make room for action buttons */
+ }
+
+ /* Optimize warranty content padding */
+ .list-view .warranty-content {
+ padding: 10px 12px !important;
+ flex-direction: column !important;
+ align-items: flex-start !important;
+ }
+
+ /* Optimize warranty info layout for mobile */
+ .list-view .warranty-info {
+ display: flex !important;
+ flex-direction: column !important;
+ gap: 8px !important;
+ width: 100% !important;
+ margin-bottom: 10px !important;
+ }
+
+ .list-view .warranty-info > div {
+ margin-right: 0 !important;
+ margin-bottom: 0 !important;
+ font-size: 0.9rem !important;
+ display: flex !important;
+ align-items: center !important;
+ }
+
+ .list-view .warranty-info > div i {
+ width: 18px !important;
+ margin-right: 6px !important;
+ font-size: 0.85rem !important;
+ flex-shrink: 0 !important;
+ }
+
+ .list-view .warranty-info > div span {
+ margin-left: 4px !important;
+ font-weight: 500 !important;
+ }
+
+ /* Optimize product photo for mobile list view */
+ .list-view .product-photo-thumbnail {
+ position: static !important;
+ margin-bottom: 10px !important;
+ text-align: center !important;
+ width: 100% !important;
+ }
+
+ .list-view .product-photo-thumbnail img {
+ width: 80px !important;
+ height: 80px !important;
+ border-radius: 6px !important;
+ object-fit: cover !important;
+ }
+
+ /* Optimize warranty status row */
+ .list-view .warranty-status-row {
+ padding: 8px 12px !important;
+ margin: 0 !important;
+ font-size: 0.9rem !important;
+ font-weight: 600 !important;
+ }
+
+ /* Optimize document links for mobile list view */
+ .list-view .document-links-row {
+ padding: 8px 12px !important;
+ gap: 8px !important;
+ flex-direction: row !important;
+ flex-wrap: wrap !important;
+ justify-content: flex-start !important;
+ }
+
+ .list-view .document-links-row a {
+ font-size: 0.85rem !important;
+ padding: 4px 8px !important;
+ margin-bottom: 4px !important;
+ white-space: nowrap !important;
+ }
+
+ /* Optimize tags row for mobile list view */
+ .list-view .warranty-card .tags-row {
+ padding: 8px 12px !important;
+ gap: 6px !important;
+ }
+
+ .list-view .tag {
+ font-size: 0.8rem !important;
+ padding: 3px 8px !important;
+ margin: 2px !important;
+ }
+
+ /* Serial numbers optimization for mobile list view */
+ .list-view .serial-numbers {
+ margin-top: 0 !important;
+ font-size: 0.9rem !important;
+ }
+
+ .list-view .serial-numbers ul {
+ margin: 5px 0 0 0 !important;
+ padding-left: 18px !important;
+ }
+
+ .list-view .serial-numbers li {
+ margin-bottom: 2px !important;
+ font-size: 0.85rem !important;
+ }
+}
+
+/* ===== MOBILE LIST VIEW - SMALLER SCREENS ===== */
+@media (max-width: 480px) {
+ /* Further optimize for very small screens */
+ .list-view .warranty-card {
+ margin-bottom: 8px !important;
+ }
+
+ .list-view .product-name-header {
+ padding: 8px 10px !important;
+ }
+
+ .list-view .product-name-header .warranty-title {
+ font-size: 0.95rem !important;
+ max-width: calc(100% - 60px) !important;
+ }
+
+ .list-view .warranty-content {
+ padding: 8px 10px !important;
+ }
+
+ .list-view .warranty-info {
+ gap: 6px !important;
+ }
+
+ .list-view .warranty-info > div {
+ font-size: 0.85rem !important;
+ }
+
+ .list-view .warranty-info > div i {
+ width: 16px !important;
+ margin-right: 5px !important;
+ font-size: 0.8rem !important;
+ }
+
+ .list-view .product-photo-thumbnail img {
+ width: 60px !important;
+ height: 60px !important;
+ }
+
+ .list-view .warranty-status-row {
+ padding: 6px 10px !important;
+ font-size: 0.85rem !important;
+ }
+
+ .list-view .document-links-row {
+ padding: 6px 10px !important;
+ gap: 6px !important;
+ }
+
+ .list-view .document-links-row a {
+ font-size: 0.8rem !important;
+ padding: 3px 6px !important;
+ }
+
+ .list-view .warranty-card .tags-row {
+ padding: 6px 10px !important;
+ gap: 4px !important;
+ }
+
+ .list-view .tag {
+ font-size: 0.75rem !important;
+ padding: 2px 6px !important;
+ margin: 1px !important;
+ }
+}
+
+/* ===== MOBILE LIST VIEW - VERY SMALL SCREENS ===== */
+@media (max-width: 360px) {
+ /* Ultra-compact for tiny screens */
+ .list-view .warranty-card {
+ margin-bottom: 6px !important;
+ }
+
+ .list-view .product-name-header {
+ padding: 6px 8px !important;
+ }
+
+ .list-view .product-name-header .warranty-title {
+ font-size: 0.9rem !important;
+ max-width: calc(100% - 55px) !important;
+ }
+
+ .list-view .warranty-content {
+ padding: 6px 8px !important;
+ }
+
+ .list-view .warranty-info > div {
+ font-size: 0.8rem !important;
+ }
+
+ .list-view .product-photo-thumbnail img {
+ width: 50px !important;
+ height: 50px !important;
+ }
+
+ .list-view .warranty-status-row {
+ padding: 5px 8px !important;
+ font-size: 0.8rem !important;
+ }
+
+ .list-view .document-links-row {
+ padding: 5px 8px !important;
+ gap: 4px !important;
+ }
+
+ .list-view .document-links-row a {
+ font-size: 0.75rem !important;
+ padding: 2px 5px !important;
+ }
}
\ No newline at end of file
diff --git a/frontend/register.html b/frontend/register.html
index 6f82ec6..e470f95 100644
--- a/frontend/register.html
+++ b/frontend/register.html
@@ -1,26 +1,32 @@
<!DOCTYPE html>
-<html lang="en">
+<html>
<head>
<!-- Authentication redirect script -->
- <script src="auth-redirect.js" data-protected="false"></script>
+ <script src="auth-redirect.js?v=20250119001" data-protected="false"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Register - Warracker</title>
+ <title data-i18n="auth.register">Register - Warracker</title>
<!-- Favicons -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
<link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
<link rel="manifest" href="manifest.json">
- <link rel="stylesheet" href="style.css">
- <script src="theme-loader.js"></script> <!-- Apply theme early -->
+ <link rel="stylesheet" href="style.css?v=20250119001">
+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Load header fix styles to ensure consistent header styling -->
- <link rel="stylesheet" href="header-fix.css">
+ <link rel="stylesheet" href="header-fix.css?v=20250119001">
+ <!-- i18next Local Scripts -->
+ <script src="js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <!-- i18n initialization script -->
+ <script src="js/i18n.js?v=20250119001"></script>
<!-- Load fix for auth buttons -->
- <script src="fix-auth-buttons-loader.js"></script>
+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
<style>
.auth-container {
max-width: 500px;
@@ -228,7 +234,7 @@
</style>
<!-- Registration status check script -->
- <script src="registration-status.js"></script>
+ <script src="registration-status.js?v=20250119001"></script>
<script>
// Additional handling for the register page
document.addEventListener('DOMContentLoaded', function() {
@@ -244,10 +250,10 @@
authMessage.className = 'auth-message error';
authMessage.style.display = 'block';
authMessage.innerHTML = `
- <h3><i class="fas fa-exclamation-triangle"></i> Registration Disabled</h3>
- <p>The administrator has temporarily disabled new account registration.</p>
- <p>If you need an account, please contact the site administrator.</p>
- <p><a href="login.html" class="btn btn-primary btn-sm mt-2">Go to Login</a></p>
+ <h3 data-i18n="auth.registration_disabled_title"><i class="fas fa-exclamation-triangle"></i> Registration Disabled</h3>
+ <p data-i18n="auth.registration_disabled_message">The administrator has temporarily disabled new account registration.</p>
+ <p data-i18n="auth.registration_disabled_contact">If you need an account, please contact the site administrator.</p>
+ <p><a href="login.html" class="btn btn-primary btn-sm mt-2" data-i18n="auth.back_to_login">Go to Login</a></p>
`;
}
@@ -285,65 +291,65 @@
<!-- Main Content -->
<div class="container">
<div class="auth-container">
- <h2 class="auth-title">Create Your Account</h2>
+ <h2 class="auth-title" data-i18n="auth.create_account_title">Create Your Account</h2>
<div id="authMessage" class="auth-message"></div>
<form id="registerForm" class="auth-form">
<div class="form-row">
<div class="form-group">
- <label for="firstName">First Name (Optional)</label>
+ <label for="firstName" data-i18n="auth.first_name_optional">First Name (Optional)</label>
<input type="text" id="firstName" name="first_name" class="form-control">
</div>
<div class="form-group">
- <label for="lastName">Last Name (Optional)</label>
+ <label for="lastName" data-i18n="auth.last_name_optional">Last Name (Optional)</label>
<input type="text" id="lastName" name="last_name" class="form-control">
</div>
</div>
<div class="form-group">
- <label for="username">Username</label>
- <input type="text" id="username" name="username" class="form-control" required>
- <small class="form-text text-muted">Username must be unique and will be used for login.</small>
+ <label for="username" data-i18n="auth.username">Username</label>
+ <input type="text" id="username" name="username" class="form-control" data-i18n-placeholder="auth.username" placeholder="Username" required>
+ <small class="form-text text-muted" data-i18n="auth.username_hint">Username must be unique and will be used for login.</small>
</div>
<div class="form-group">
- <label for="email">Email Address</label>
- <input type="email" id="email" name="email" class="form-control" required>
+ <label for="email" data-i18n="auth.email_address">Email Address</label>
+ <input type="email" id="email" name="email" class="form-control" data-i18n-placeholder="auth.email_address" placeholder="Email Address" required>
</div>
<div class="form-group">
- <label for="password">Password</label>
+ <label for="password" data-i18n="auth.password">Password</label>
<div class="password-container">
<input type="password" id="password" name="password" class="form-control" required>
- <button type="button" class="password-toggle" title="Show/Hide Password">
+ <button type="button" class="password-toggle" title="Show/Hide Password" data-i18n-title="auth.toggle_password">
<i class="fas fa-eye"></i>
</button>
</div>
<div class="password-strength" id="passwordStrength"></div>
<div class="password-strength-text" id="passwordStrengthText"></div>
- <small class="form-text text-muted">Password must be at least 8 characters and include uppercase, lowercase, and numbers.</small>
+ <small class="form-text text-muted" data-i18n="auth.password_hint_simple">Password must be at least 8 characters and include uppercase, lowercase, and numbers.</small>
<!-- Password Requirements List -->
<div id="passwordRequirements" class="password-requirements" style="display: none;">
- <h5>Password Requirements:</h5>
+ <h5 data-i18n="auth.password_requirements">Password Requirements:</h5>
<ul>
- <li id="req-length">At least 8 characters</li>
- <li id="req-uppercase">At least 1 uppercase letter</li>
- <li id="req-lowercase">At least 1 lowercase letter</li>
- <li id="req-number">At least 1 number</li>
- <li id="req-special">At least 1 special character</li>
+ <li id="req-length" data-i18n="auth.req_length">At least 8 characters</li>
+ <li id="req-uppercase" data-i18n="auth.req_uppercase">At least 1 uppercase letter</li>
+ <li id="req-lowercase" data-i18n="auth.req_lowercase">At least 1 lowercase letter</li>
+ <li id="req-number" data-i18n="auth.req_number">At least 1 number</li>
+ <li id="req-special" data-i18n="auth.req_special">At least 1 special character</li>
</ul>
</div>
<div id="passwordFeedback" class="password-feedback"></div>
</div>
<div class="form-group">
- <label for="confirmPassword">Confirm Password</label>
+ <label for="confirmPassword" data-i18n="auth.confirm_password">Confirm Password</label>
<div class="password-container">
<input type="password" id="confirmPassword" name="confirmPassword" class="form-control" required>
- <button type="button" class="password-toggle" title="Show/Hide Password">
+ <button type="button" class="password-toggle" title="Show/Hide Password" data-i18n-title="auth.toggle_password">
<i class="fas fa-eye"></i>
</button>
</div>
@@ -351,19 +357,19 @@
</div>
<button type="submit" class="btn btn-primary btn-block">
- <i class="fas fa-user-plus"></i> Create Account
+ <i class="fas fa-user-plus"></i> <span data-i18n="auth.create_account">Create Account</span>
</button>
</form>
<div class="auth-links">
- <span>Already have an account?</span>
- <a href="login.html">Login</a>
+ <span data-i18n="auth.already_have_account">Already have an account?</span>
+ <a href="login.html" data-i18n="auth.login">Login</a>
</div>
</div>
</div>
<!-- Script for authentication -->
- <script src="auth.js"></script>
+ <script src="auth.js?v=20250119001"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
const registerForm = document.getElementById('registerForm');
@@ -603,5 +609,16 @@
// Initialize theme when page loads
document.addEventListener('DOMContentLoaded', initializeTheme);
</script>
+
+ <!-- Footer Width Fix -->
+ <script src="footer-fix.js?v=20250119001"></script>
+
+ <!-- Footer Content Manager -->
+ <script src="footer-content.js?v=20250119001"></script>
+
+ <!-- Powered by Warracker Footer -->
+ <footer class="warracker-footer" id="warrackerFooter">
+ <!-- Content will be dynamically generated by footer-content.js -->
+ </footer>
</body>
</html>
diff --git a/frontend/reset-password-request.html b/frontend/reset-password-request.html
index 9fdb5da..fad8a6b 100644
--- a/frontend/reset-password-request.html
+++ b/frontend/reset-password-request.html
@@ -1,19 +1,29 @@
<!DOCTYPE html>
-<html lang="en">
+<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Warracker - Reset Password</title>
+ <title data-i18n="auth.reset_password_title">Warracker - Reset Password</title>
<!-- Favicons -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
<link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
<link rel="manifest" href="manifest.json">
- <link rel="stylesheet" href="style.css">
- <script src="theme-loader.js"></script> <!-- Apply theme early -->
+ <link rel="stylesheet" href="style.css?v=20250119001">
+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
+ <!-- Load header fix styles to ensure consistent header styling -->
+ <link rel="stylesheet" href="header-fix.css?v=20250119001">
+ <!-- i18next Local Scripts -->
+ <script src="js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <!-- i18n initialization script -->
+ <script src="js/i18n.js?v=20250119001"></script>
+ <!-- Load fix for auth buttons -->
+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
<style>
.auth-container {
max-width: 400px;
@@ -82,6 +92,9 @@
line-height: 1.5;
}
</style>
+
+ <!-- Registration status check script -->
+ <script src="registration-status.js?v=20250119001"></script>
</head>
<body>
<!-- Header -->
@@ -89,7 +102,7 @@
<div class="container">
<div class="app-title">
<i class="fas fa-shield-alt"></i>
- <h1>Warracker</h1>
+ <h1><a href="index.html" style="color: inherit; text-decoration: none; cursor: pointer;">Warracker</a></h1>
</div>
</div>
</header>
@@ -97,9 +110,9 @@
<!-- Main Content -->
<div class="container">
<div class="auth-container">
- <h2 class="auth-title">Reset Your Password</h2>
+ <h2 class="auth-title" data-i18n="auth.reset_your_password">Reset Your Password</h2>
- <p class="auth-info">
+ <p class="auth-info" data-i18n="auth.reset_password_info">
Enter your email address below and we'll send you a link to reset your password.
</p>
@@ -107,17 +120,17 @@
<form id="resetRequestForm" class="auth-form">
<div class="form-group">
- <label for="email">Email Address</label>
- <input type="email" id="email" name="email" class="form-control" required>
+ <label for="email" data-i18n="auth.email_address">Email Address</label>
+ <input type="email" id="email" name="email" class="form-control" data-i18n-placeholder="auth.email_address" placeholder="Email Address" required>
</div>
<button type="submit" class="btn btn-primary btn-block">
- <i class="fas fa-paper-plane"></i> Send Reset Link
+ <i class="fas fa-paper-plane"></i> <span data-i18n="auth.send_reset_link">Send Reset Link</span>
</button>
</form>
<div class="auth-links">
- <a href="login.html">Back to Login</a>
+ <a href="login.html" data-i18n="auth.back_to_login">Back to Login</a>
</div>
</div>
</div>
@@ -237,5 +250,42 @@
// Initialize theme when page loads
document.addEventListener('DOMContentLoaded', initializeTheme);
</script>
+
+ <script src="auth.js?v=20250119001"></script>
+
+ <!-- Footer Width Fix -->
+ <script src="footer-fix.js?v=20250119001"></script>
+
+ <!-- Footer Content Manager -->
+ <script src="footer-content.js?v=20250119001"></script>
+
+ <!-- Powered by Warracker Footer -->
+ <footer class="warracker-footer" id="warrackerFooter">
+ <!-- Content will be dynamically generated by footer-content.js -->
+ </footer>
+
+ <script>
+ function applyFooterStyles() {
+ const footer = document.getElementById('warrackerFooter');
+ const link = document.getElementById('warrackerFooterLink');
+ const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark' || document.documentElement.classList.contains('dark-mode') || document.body.classList.contains('dark-mode');
+ if (footer) {
+ if (isDarkMode) {
+ // Dark mode styles - using same background as header (#2d2d2d)
+ footer.style.cssText = 'margin-top: 50px; padding: 20px; text-align: center; border-top: 1px solid #444; background-color: #2d2d2d; color: #e0e0e0; font-size: 0.9rem;';
+ if (link) link.style.cssText = 'color: #4dabf7; text-decoration: none; font-weight: 500;';
+ } else {
+ // Light mode styles - using same background as header (#ffffff)
+ footer.style.cssText = 'margin-top: 50px; padding: 20px; text-align: center; border-top: 1px solid #e0e0e0; background-color: #ffffff; color: #333333; font-size: 0.9rem;';
+ if (link) link.style.cssText = 'color: #3498db; text-decoration: none; font-weight: 500;';
+ }
+ }
+ }
+ document.addEventListener('DOMContentLoaded', applyFooterStyles);
+ const obs = new MutationObserver(applyFooterStyles);
+ obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'class'] });
+ obs.observe(document.body, { attributes: true, attributeFilter: ['class'] });
+ </script>
+
</body>
</html>
diff --git a/frontend/reset-password.html b/frontend/reset-password.html
index 862fda7..19148fd 100644
--- a/frontend/reset-password.html
+++ b/frontend/reset-password.html
@@ -1,19 +1,29 @@
<!DOCTYPE html>
-<html lang="en">
+<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Warracker - Set New Password</title>
+ <title data-i18n="auth.set_new_password_title">Warracker - Set New Password</title>
<!-- Favicons -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
<link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
<link rel="manifest" href="manifest.json">
- <link rel="stylesheet" href="style.css">
- <script src="theme-loader.js"></script> <!-- Apply theme early -->
+ <link rel="stylesheet" href="style.css?v=20250119001">
+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
+ <!-- Load header fix styles to ensure consistent header styling -->
+ <link rel="stylesheet" href="header-fix.css?v=20250119001">
+ <!-- i18next Local Scripts -->
+ <script src="js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <!-- i18n initialization script -->
+ <script src="js/i18n.js?v=20250119001"></script>
+ <!-- Load fix for auth buttons -->
+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
<style>
.auth-container {
max-width: 400px;
@@ -139,6 +149,9 @@
margin-bottom: 15px;
}
</style>
+
+ <!-- Registration status check script -->
+ <script src="registration-status.js?v=20250119001"></script>
</head>
<body>
<!-- Header -->
@@ -146,7 +159,7 @@
<div class="container">
<div class="app-title">
<i class="fas fa-shield-alt"></i>
- <h1>Warracker</h1>
+ <h1><a href="index.html" style="color: inherit; text-decoration: none; cursor: pointer;">Warracker</a></h1>
</div>
</div>
</header>
@@ -155,29 +168,29 @@
<div class="container">
<div class="auth-container">
<div id="resetForm">
- <h2 class="auth-title">Set New Password</h2>
+ <h2 class="auth-title" data-i18n="auth.set_new_password">Set New Password</h2>
<div id="authMessage" class="auth-message"></div>
<form id="passwordResetForm" class="auth-form">
<div class="form-group">
- <label for="password">New Password</label>
+ <label for="password" data-i18n="auth.new_password">New Password</label>
<div class="password-container">
<input type="password" id="password" name="password" class="form-control" required>
- <button type="button" class="password-toggle" title="Show/Hide Password">
+ <button type="button" class="password-toggle" title="Show/Hide Password" data-i18n-title="auth.toggle_password">
<i class="fas fa-eye"></i>
</button>
</div>
<div class="password-strength" id="passwordStrength"></div>
<div class="password-strength-text" id="passwordStrengthText"></div>
- <small class="form-text text-muted">Password must be at least 8 characters and include uppercase, lowercase, and numbers.</small>
+ <small class="form-text text-muted" data-i18n="auth.password_hint_simple">Password must be at least 8 characters and include uppercase, lowercase, and numbers.</small>
</div>
<div class="form-group">
- <label for="confirmPassword">Confirm New Password</label>
+ <label for="confirmPassword" data-i18n="auth.confirm_new_password">Confirm New Password</label>
<div class="password-container">
<input type="password" id="confirmPassword" name="confirmPassword" class="form-control" required>
- <button type="button" class="password-toggle" title="Show/Hide Password">
+ <button type="button" class="password-toggle" title="Show/Hide Password" data-i18n-title="auth.toggle_password">
<i class="fas fa-eye"></i>
</button>
</div>
@@ -186,20 +199,20 @@
<input type="hidden" id="token" name="token">
<button type="submit" class="btn btn-primary btn-block">
- <i class="fas fa-lock"></i> Reset Password
+ <i class="fas fa-lock"></i> <span data-i18n="auth.reset_password">Reset Password</span>
</button>
</form>
<div class="auth-links">
- <a href="login.html">Back to Login</a>
+ <a href="login.html" data-i18n="auth.back_to_login">Back to Login</a>
</div>
</div>
<div id="tokenInvalid" class="token-invalid">
<i class="fas fa-exclamation-circle"></i>
- <h3>Invalid or Expired Link</h3>
- <p>The password reset link you clicked is invalid or has expired.</p>
- <a href="reset-password-request.html" class="btn btn-primary">Request New Reset Link</a>
+ <h3 data-i18n="auth.invalid_or_expired_link">Invalid or Expired Link</h3>
+ <p data-i18n="auth.invalid_link_info">The password reset link you clicked is invalid or has expired.</p>
+ <a href="reset-password-request.html" class="btn btn-primary" data-i18n="auth.request_new_reset_link">Request New Reset Link</a>
</div>
</div>
</div>
@@ -238,8 +251,9 @@
// Set token in hidden field
document.getElementById('token').value = tokenToUse;
- // Verify token validity
- verifyToken(tokenToUse);
+ // Show the reset form directly if token is present (validity will be checked on submission)
+ document.getElementById('resetForm').style.display = 'block';
+ document.getElementById('tokenInvalid').style.display = 'none';
// Toggle password visibility
const passwordToggles = document.querySelectorAll('.password-toggle');
@@ -377,29 +391,6 @@
authMessage.style.display = 'block';
}
- // Function to verify token validity
- async function verifyToken(token) {
- try {
- const response = await fetch(`/api/auth/password/verify-token?token=${token}`);
- const data = await response.json();
-
- if (!response.ok) {
- throw new Error(data.message || 'Invalid token');
- }
-
- // Token is valid, show the form
- document.getElementById('resetForm').style.display = 'block';
- document.getElementById('tokenInvalid').style.display = 'none';
-
- } catch (error) {
- console.error('Token verification error:', error);
-
- // Token is invalid, show error message
- document.getElementById('resetForm').style.display = 'none';
- document.getElementById('tokenInvalid').style.display = 'block';
- }
- }
-
// No longer check for 'enabled' value. Theme is handled by theme-loader.js and below.
});
@@ -425,5 +416,43 @@
// Initialize theme when page loads
document.addEventListener('DOMContentLoaded', initializeTheme);
</script>
+
+ <!-- Scripts -->
+ <script src="auth.js?v=20250119001"></script>
+
+ <!-- Footer Width Fix -->
+ <script src="footer-fix.js?v=20250119001"></script>
+
+ <!-- Footer Content Manager -->
+ <script src="footer-content.js?v=20250119001"></script>
+
+ <!-- Powered by Warracker Footer -->
+ <footer class="warracker-footer" id="warrackerFooter">
+ <!-- Content will be dynamically generated by footer-content.js -->
+ </footer>
+
+ <script>
+ function applyFooterStyles() {
+ const footer = document.getElementById('warrackerFooter');
+ const link = document.getElementById('warrackerFooterLink');
+ const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark' || document.documentElement.classList.contains('dark-mode') || document.body.classList.contains('dark-mode');
+ if (footer) {
+ if (isDarkMode) {
+ // Dark mode styles - using same background as header (#2d2d2d)
+ footer.style.cssText = 'margin-top: 50px; padding: 20px; text-align: center; border-top: 1px solid #444; background-color: #2d2d2d; color: #e0e0e0; font-size: 0.9rem;';
+ if (link) link.style.cssText = 'color: #4dabf7; text-decoration: none; font-weight: 500;';
+ } else {
+ // Light mode styles - using same background as header (#ffffff)
+ footer.style.cssText = 'margin-top: 50px; padding: 20px; text-align: center; border-top: 1px solid #e0e0e0; background-color: #ffffff; color: #333333; font-size: 0.9rem;';
+ if (link) link.style.cssText = 'color: #3498db; text-decoration: none; font-weight: 500;';
+ }
+ }
+ }
+ document.addEventListener('DOMContentLoaded', applyFooterStyles);
+ const obs = new MutationObserver(applyFooterStyles);
+ obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'class'] });
+ obs.observe(document.body, { attributes: true, attributeFilter: ['class'] });
+ </script>
+
</body>
</html>
diff --git a/frontend/script.js b/frontend/script.js
index cbd333a..dfd39da 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -1,19 +1,24 @@
-// alert('script.js loaded!'); // Remove alert after confirming script loads
+console.log('[SCRIPT VERSION] 20250529-005 - Added CSS cache busting for consistent styling across domains');
console.log('[DEBUG] script.js loaded and running');
+// alert('script.js loaded!'); // Remove alert after confirming script loads
+
// Global variables
let warranties = [];
+let warrantiesLoaded = false; // Track if warranties have been loaded from API
let currentTabIndex = 0;
let tabContents = []; // Initialize as empty array
let editMode = false;
let currentWarrantyId = null;
let userPreferencePrefix = null; // <<< ADDED GLOBAL PREFIX VARIABLE
+let isGlobalView = false; // Track if admin is viewing all users' warranties
let currentFilters = {
status: 'all',
tag: 'all',
search: '',
sortBy: 'expiration',
- vendor: 'all' // Added vendor filter
+ vendor: 'all', // Added vendor filter
+ warranty_type: 'all' // Added warranty type filter
};
// Tag related variables
@@ -35,11 +40,18 @@ const clearSearchBtn = document.getElementById('clearSearch');
const statusFilter = document.getElementById('statusFilter');
const sortBySelect = document.getElementById('sortBy');
const vendorFilter = document.getElementById('vendorFilter'); // Added vendor filter select
+const warrantyTypeFilter = document.getElementById('warrantyTypeFilter'); // Added warranty type filter select
const exportBtn = document.getElementById('exportBtn');
const gridViewBtn = document.getElementById('gridViewBtn');
const listViewBtn = document.getElementById('listViewBtn');
const tableViewBtn = document.getElementById('tableViewBtn');
const tableViewHeader = document.querySelector('.table-view-header');
+
+// Admin view controls
+const adminViewSwitcher = document.getElementById('adminViewSwitcher');
+const personalViewBtn = document.getElementById('personalViewBtn');
+const globalViewBtn = document.getElementById('globalViewBtn');
+const warrantiesPanelTitle = document.getElementById('warrantiesPanelTitle');
const fileInput = document.getElementById('invoice');
const fileName = document.getElementById('fileName');
const manualInput = document.getElementById('manual');
@@ -84,9 +96,30 @@ const editWarrantyDurationYearsInput = document.getElementById('editWarrantyDura
const editWarrantyDurationMonthsInput = document.getElementById('editWarrantyDurationMonths');
const editWarrantyDurationDaysInput = document.getElementById('editWarrantyDurationDays');
+// Warranty Type DOM Elements
+const warrantyTypeInput = document.getElementById('warrantyType');
+const warrantyTypeCustomInput = document.getElementById('warrantyTypeCustom');
+const editWarrantyTypeInput = document.getElementById('editWarrantyType');
+const editWarrantyTypeCustomInput = document.getElementById('editWarrantyTypeCustom');
+
+// Warranty method selection elements
+const durationMethodRadio = document.getElementById('durationMethod');
+const exactDateMethodRadio = document.getElementById('exactDateMethod');
+const exactExpirationField = document.getElementById('exactExpirationField');
+const exactExpirationDateInput = document.getElementById('exactExpirationDate');
+
+const editDurationMethodRadio = document.getElementById('editDurationMethod');
+const editExactDateMethodRadio = document.getElementById('editExactDateMethod');
+const editExactExpirationField = document.getElementById('editExactExpirationField');
+const editExactExpirationDateInput = document.getElementById('editExactExpirationDate');
+
// Add near other DOM Element declarations
const showAddWarrantyBtn = document.getElementById('showAddWarrantyBtn');
const addWarrantyModal = document.getElementById('addWarrantyModal');
+
+// Currency dropdown elements
+const currencySelect = document.getElementById('currency');
+const editCurrencySelect = document.getElementById('editCurrency');
const serialNumbersContainer = document.getElementById('serialNumbersContainer'); // Ensure this is defined
/**
@@ -103,6 +136,189 @@ function getUserType() {
}
}
+/**
+ * Initialize view controls for all authenticated users
+ */
+async function initViewControls() {
+ // Check if global view is enabled
+ try {
+ const response = await fetch('/api/settings/global-view-status', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.ok) {
+ const result = await response.json();
+ if (result.enabled && adminViewSwitcher) {
+ // Global view is enabled, show view switcher
+ adminViewSwitcher.style.display = 'flex';
+
+ // Add event listeners for view buttons
+ if (personalViewBtn) {
+ personalViewBtn.addEventListener('click', () => switchToPersonalView());
+ }
+ if (globalViewBtn) {
+ globalViewBtn.addEventListener('click', () => switchToGlobalView());
+ }
+
+ // Load and apply saved view scope preference
+ const savedScope = loadViewScopePreference();
+ if (savedScope === 'global') {
+ // Apply global view silently without saving preference again
+ isGlobalView = true;
+ personalViewBtn.classList.remove('active');
+ globalViewBtn.classList.add('active');
+ updateWarrantiesPanelTitle(true);
+ } else {
+ // Apply personal view (default)
+ isGlobalView = false;
+ personalViewBtn.classList.add('active');
+ globalViewBtn.classList.remove('active');
+ updateWarrantiesPanelTitle(false);
+ }
+ } else if (adminViewSwitcher) {
+ // Global view is disabled, hide view switcher
+ adminViewSwitcher.style.display = 'none';
+
+ // If currently in global view, switch back to personal view
+ if (isGlobalView) {
+ isGlobalView = false;
+ updateWarrantiesPanelTitle(false);
+ // Reload warranties
+ await loadWarranties(true);
+ applyFilters();
+ }
+ }
+ } else {
+ console.error('Failed to check global view status');
+ // Default to showing view switcher if check fails
+ if (adminViewSwitcher) {
+ adminViewSwitcher.style.display = 'flex';
+
+ // Add event listeners for view buttons
+ if (personalViewBtn) {
+ personalViewBtn.addEventListener('click', () => switchToPersonalView());
+ }
+ if (globalViewBtn) {
+ globalViewBtn.addEventListener('click', () => switchToGlobalView());
+ }
+ }
+ }
+ } catch (error) {
+ console.error('Error checking global view status:', error);
+ // Default to showing view switcher if check fails
+ if (adminViewSwitcher) {
+ adminViewSwitcher.style.display = 'flex';
+
+ // Add event listeners for view buttons
+ if (personalViewBtn) {
+ personalViewBtn.addEventListener('click', () => switchToPersonalView());
+ }
+ if (globalViewBtn) {
+ globalViewBtn.addEventListener('click', () => switchToGlobalView());
+ }
+ }
+ }
+}
+
+/**
+ * Switch to personal view (user's own warranties)
+ */
+async function switchToPersonalView() {
+ if (!personalViewBtn || !globalViewBtn) return;
+
+ isGlobalView = false;
+ personalViewBtn.classList.add('active');
+ globalViewBtn.classList.remove('active');
+
+ // Save view preference
+ saveViewScopePreference('personal');
+
+ // Update title
+ updateWarrantiesPanelTitle(false);
+
+ // Reload warranties
+ try {
+ const token = window.auth.getToken();
+ if (token) {
+ await loadWarranties(true);
+ applyFilters();
+ }
+ } catch (error) {
+ console.error('Error switching to personal view:', error);
+ showToast(window.t('messages.error_loading_personal_warranties'), 'error');
+ }
+}
+
+/**
+ * Switch to global view (all users' warranties) - available to all users
+ */
+async function switchToGlobalView() {
+ if (!personalViewBtn || !globalViewBtn) return;
+
+ // Check if global view is still enabled
+ try {
+ const response = await fetch('/api/settings/global-view-status', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.ok) {
+ const result = await response.json();
+ if (!result.enabled) {
+ showToast(window.t('messages.global_view_disabled'), 'error');
+ return;
+ }
+ }
+ } catch (error) {
+ console.error('Error checking global view status:', error);
+ }
+
+ isGlobalView = true;
+ personalViewBtn.classList.remove('active');
+ globalViewBtn.classList.add('active');
+
+ // Save view preference
+ saveViewScopePreference('global');
+
+ // Update title
+ updateWarrantiesPanelTitle(true);
+
+ // Reload warranties
+ try {
+ const token = window.auth.getToken();
+ if (token) {
+ await loadWarranties(true);
+ applyFilters();
+ }
+ } catch (error) {
+ console.error('Error switching to global view:', error);
+ showToast(window.t('messages.error_loading_global_warranties'), 'error');
+ }
+}
+
+/**
+ * Update warranties panel title with proper translation
+ * @param {boolean} isGlobal - Whether to show global or personal title
+ */
+function updateWarrantiesPanelTitle(isGlobal = false) {
+ if (warrantiesPanelTitle) {
+ if (window.i18next && window.i18next.t) {
+ warrantiesPanelTitle.textContent = isGlobal ?
+ window.i18next.t('warranties.title_global') :
+ window.i18next.t('warranties.title');
+ } else {
+ warrantiesPanelTitle.textContent = isGlobal ? 'All Users\' Warranties' : 'Your Warranties';
+ }
+ }
+}
+
/**
* Get the appropriate localStorage key prefix based on user type
* @returns {string} The prefix to use for localStorage keys
@@ -111,6 +327,36 @@ function getPreferenceKeyPrefix() {
return getUserType() === 'admin' ? 'admin_' : 'user_';
}
+/**
+ * Save view scope preference to localStorage
+ * @param {string} scope - 'personal' or 'global'
+ */
+function saveViewScopePreference(scope) {
+ try {
+ const prefix = getPreferenceKeyPrefix();
+ localStorage.setItem(`${prefix}viewScope`, scope);
+ console.log(`Saved view scope preference: ${scope} with prefix: ${prefix}`);
+ } catch (error) {
+ console.error('Error saving view scope preference:', error);
+ }
+}
+
+/**
+ * Load view scope preference from localStorage
+ * @returns {string} The saved preference ('personal', 'global', or 'personal' as default)
+ */
+function loadViewScopePreference() {
+ try {
+ const prefix = getPreferenceKeyPrefix();
+ const savedScope = localStorage.getItem(`${prefix}viewScope`);
+ console.log(`Loaded view scope preference: ${savedScope} with prefix: ${prefix}`);
+ return savedScope || 'personal'; // Default to personal view
+ } catch (error) {
+ console.error('Error loading view scope preference:', error);
+ return 'personal'; // Default to personal view on error
+ }
+}
+
// Theme Management - Simplified
function setTheme(isDark) {
const theme = isDark ? 'dark' : 'light';
@@ -196,7 +442,7 @@ document.addEventListener('DOMContentLoaded', function() {
const name = tagNameInput ? tagNameInput.value.trim() : '';
const color = tagColorInput ? tagColorInput.value : '#808080';
if (!name) {
- showToast('Tag name is required', 'error');
+ showToast(window.t('messages.tag_name_required'), 'error');
return;
}
// Use the existing createTag function if available
@@ -208,10 +454,10 @@ document.addEventListener('DOMContentLoaded', function() {
renderExistingTags && renderExistingTags();
})
.catch((err) => {
- showToast((err && err.message) || 'Failed to create tag', 'error');
+ showToast((err && err.message) || window.t('messages.failed_to_create_tag'), 'error');
});
} else {
- showToast('Tag creation function not found', 'error');
+ showToast(window.t('messages.tag_creation_function_not_found'), 'error');
}
});
}
@@ -271,34 +517,70 @@ document.addEventListener('DOMContentLoaded', function() {
handleLifetimeChange({ target: lifetimeCheckbox }); // Initial check
}
- // --- LOAD WARRANTIES AFTER AUTH ---
- // Listen for an event from auth.js indicating authentication is complete and user context is ready.
- // ** IMPORTANT: Replace 'authStateReady' with the actual event name fired by auth.js **
- window.addEventListener('authStateReady', async function handleAuthReady() { // <-- Make handler async
- console.log('[DEBUG] authStateReady handler called');
- console.log("Auth state ready event received. Preparing preferences and warranties...");
- // Ensure this listener runs only once
- window.removeEventListener('authStateReady', handleAuthReady);
+ // Initialize warranty method selection handlers
+ if (durationMethodRadio && exactDateMethodRadio) {
+ durationMethodRadio.addEventListener('change', handleWarrantyMethodChange);
+ exactDateMethodRadio.addEventListener('change', handleWarrantyMethodChange);
+ handleWarrantyMethodChange(); // Initial setup
+ }
+
+ if (editDurationMethodRadio && editExactDateMethodRadio) {
+ editDurationMethodRadio.addEventListener('change', handleEditWarrantyMethodChange);
+ editExactDateMethodRadio.addEventListener('change', handleEditWarrantyMethodChange);
+ handleEditWarrantyMethodChange(); // Initial setup for edit form
+ }
+
+ // --- LOAD WARRANTIES AFTER AUTH ---
+ let authStateHandled = false;
+
+ async function runAuthenticatedTasks(isAuthenticated) { // Added isAuthenticated parameter
+ if (!isAuthenticated) {
+ console.log('[DEBUG] runAuthenticatedTasks: Called with isAuthenticated = false. Not running tasks yet.');
+ // Do not set authStateHandled = true here, allow a subsequent call with true.
+ return;
+ }
+ // If we reach here, isAuthenticated is true.
+ if (authStateHandled) {
+ console.log('[DEBUG] runAuthenticatedTasks: Tasks already handled (or in progress by another call).');
+ return;
+ }
+ authStateHandled = true; // Set flag only when tasks are actually starting with isAuthenticated = true.
+ console.log('[DEBUG] runAuthenticatedTasks: Executing with isAuthenticated = true.');
// Set prefix
userPreferencePrefix = getPreferenceKeyPrefix();
- console.log(`[authStateReady] Determined and stored global prefix: ${userPreferencePrefix}`);
+ console.log(`[runAuthenticatedTasks] Determined and stored global prefix: ${userPreferencePrefix}`);
+
+ // Re-check auth status just before critical data loads
+ const currentAuthStatus = window.auth && window.auth.isAuthenticated();
+ console.log(`[runAuthenticatedTasks] Current auth status before loading prefs/warranties: ${currentAuthStatus}`);
- // Load preferences
- await loadAndApplyUserPreferences();
- await loadTags(); // Ensure all available tags are loaded after authentication
+ if (currentAuthStatus) {
+ await loadAndApplyUserPreferences(true); // Pass true, as we've confirmed auth
+ await loadTags(); // Ensure all available tags are loaded
+ await loadCurrencies(); // Load currencies for dropdowns
+
+ // Initialize Paperless-ngx integration
+ await initPaperlessNgxIntegration();
+
+ // Initialize view controls for all users
+ initViewControls();
- // Load warranty data (fetches, processes, populates global array)
- if (document.getElementById('warrantiesList')) {
- console.log("[authStateReady] Loading warranty data...");
- await loadWarranties(); // Waits for fetch/process
- console.log('[DEBUG] After loadWarranties, warranties array:', warranties);
+ if (document.getElementById('warrantiesList')) {
+ console.log("[runAuthenticatedTasks] Loading warranty data...");
+ await loadWarranties(true); // Pass true
+ console.log('[DEBUG] After loadWarranties, warranties array:', warranties);
+ } else {
+ console.log("[runAuthenticatedTasks] Warranties list element not found.");
+ }
} else {
- console.log("[authStateReady] Warranties list element not found.");
+ console.warn("[runAuthenticatedTasks] Auth status became false before loading data. Aborting data load.");
+ // Optionally, reset authStateHandled if we want to allow another attempt
+ // authStateHandled = false;
}
// Now that data and preferences are ready, apply view/currency and render via applyFilters
- console.log("[authStateReady] Applying preferences and rendering...");
+ console.log("[runAuthenticatedTasks] Applying preferences and rendering...");
loadViewPreference(); // Sets currentView and UI classes/buttons
updateCurrencySymbols(); // Update symbols
@@ -306,8 +588,27 @@ document.addEventListener('DOMContentLoaded', function() {
if (document.getElementById('warrantiesList')) {
applyFilters();
}
+ }
+
+ // Listener for the 'authStateReady' event
+ window.addEventListener('authStateReady', async function handleAuthEvent(event) {
+ console.log('[DEBUG] authStateReady event received in script.js. Detail:', event.detail);
+ // Pass the isAuthenticated status from the event detail to runAuthenticatedTasks
+ await runAuthenticatedTasks(event.detail && event.detail.isAuthenticated);
+ }); // Removed { once: true } to allow re-evaluation if auth state changes
- }, { once: true }); // Use { once: true } as a fallback if removeEventListener isn't reliable across scripts
+ // Proactive check after a brief delay to allow auth.js to initialize
+ setTimeout(async () => {
+ console.log('[DEBUG] Proactive auth check in script.js (after timeout).');
+ if (window.auth) {
+ // Pass the current authentication status to runAuthenticatedTasks
+ await runAuthenticatedTasks(window.auth.isAuthenticated());
+ } else {
+ console.log('[DEBUG] Proactive check: window.auth not available. Event listener should handle it.');
+ // Call with false if auth module isn't ready, to avoid tasks running prematurely.
+ await runAuthenticatedTasks(false);
+ }
+ }, 500); // Delay
// --- END LOAD WARRANTIES AFTER AUTH ---
// updateCurrencySymbols(); // Call removed, rely on loadWarranties triggering render with correct symbol
@@ -331,6 +632,19 @@ let expiringSoonDays = 30; // Default value, will be updated from user preferenc
// API URL
const API_URL = '/api/warranties';
+// Utility function to escape HTML
+function escapeHtml(text) {
+ if (typeof text !== 'string') return text;
+ const map = {
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#039;'
+ };
+ return text.replace(/[&<>"']/g, function(m) { return map[m]; });
+}
+
// Form tab navigation variables (simplified)
let formTabs = []; // Changed from const to let, initialized as empty
// Removed const formTabsElements = document.querySelectorAll('.form-tab');
@@ -354,7 +668,7 @@ let formTabs = []; // Changed from const to let, initialized as empty
// Get auth token
const token = localStorage.getItem('auth_token');
if (!token) {
- showToast('Authentication required', 'error');
+ showToast(window.t('messages.authentication_required'), 'error');
return;
}
showLoadingSpinner();
@@ -369,6 +683,17 @@ let formTabs = []; // Changed from const to let, initialized as empty
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 all duration fields are 0 but we have an expiration date, this was created with exact date method
+ const isExactDateWarranty = (notesModalWarrantyObj.warranty_duration_years || 0) === 0 &&
+ (notesModalWarrantyObj.warranty_duration_months || 0) === 0 &&
+ (notesModalWarrantyObj.warranty_duration_days || 0) === 0 &&
+ notesModalWarrantyObj.expiration_date;
+
+ if (isExactDateWarranty) {
+ // For exact date warranties, send the expiration date as exact_expiration_date
+ formData.append('exact_expiration_date', notesModalWarrantyObj.expiration_date.split('T')[0]);
+ }
}
if (notesModalWarrantyObj.product_url) {
formData.append('product_url', notesModalWarrantyObj.product_url);
@@ -376,6 +701,12 @@ let formTabs = []; // Changed from const to let, initialized as empty
if (notesModalWarrantyObj.purchase_price !== null && notesModalWarrantyObj.purchase_price !== undefined) {
formData.append('purchase_price', notesModalWarrantyObj.purchase_price);
}
+ if (notesModalWarrantyObj.vendor) {
+ formData.append('vendor', notesModalWarrantyObj.vendor);
+ }
+ if (notesModalWarrantyObj.warranty_type) {
+ formData.append('warranty_type', notesModalWarrantyObj.warranty_type);
+ }
if (notesModalWarrantyObj.serial_numbers && Array.isArray(notesModalWarrantyObj.serial_numbers)) {
notesModalWarrantyObj.serial_numbers.forEach(sn => {
if (sn && sn.trim() !== '') {
@@ -405,7 +736,7 @@ let formTabs = []; // Changed from const to let, initialized as empty
throw new Error(data.error || 'Failed to update notes');
}
hideLoadingSpinner();
- showToast('Notes updated successfully', 'success');
+ showToast(window.t('messages.notes_updated_successfully'), 'success');
// Close the modal
const notesModal = document.getElementById('notesModal');
if (notesModal) notesModal.style.display = 'none';
@@ -415,7 +746,7 @@ let formTabs = []; // Changed from const to let, initialized as empty
} catch (error) {
hideLoadingSpinner();
console.error('Error updating notes:', error);
- showToast(error.message || 'Failed to update notes', 'error');
+ showToast(error.message || window.t('messages.failed_to_update_notes'), 'error');
}
};
}
@@ -607,23 +938,25 @@ function updateCompletedTabs() {
// Validate a specific tab
function validateTab(tabIndex) {
const tabContent = tabContents[tabIndex];
- // Get all relevant form controls within the tab
const controls = tabContent.querySelectorAll('input, textarea, select');
let isTabValid = true;
controls.forEach(control => {
- // Check the native HTML5 validity state
- if (!control.validity.valid) {
+ // Clear previous validation state
+ control.classList.remove('invalid');
+ let validationMessageElement = control.nextElementSibling;
+ if (validationMessageElement && validationMessageElement.classList.contains('validation-message')) {
+ validationMessageElement.remove();
+ }
+
+ // Manual validation for required fields
+ if (control.hasAttribute('required') && control.value.trim() === '') {
+ isTabValid = false;
+ control.classList.add('invalid');
+ // Mark as invalid, message will be added by showValidationErrors
+ } else if (!control.validity.valid) { // For other HTML5 validation issues (e.g., type mismatch)
isTabValid = false;
control.classList.add('invalid');
- // Ensure a validation message placeholder exists or is updated by showValidationErrors
- } else {
- control.classList.remove('invalid');
- // Remove validation message if control is now valid and message exists
- let validationMessageElement = control.nextElementSibling;
- if (validationMessageElement && validationMessageElement.classList.contains('validation-message')) {
- validationMessageElement.remove();
- }
}
});
return isTabValid;
@@ -634,6 +967,7 @@ function showValidationErrors(tabIndex) {
const tabContent = tabContents[tabIndex];
const controls = tabContent.querySelectorAll('input, textarea, select');
let firstInvalidControl = null;
+ let validationToast = document.querySelector('.validation-toast'); // Check for existing validation toast
controls.forEach(control => {
if (!control.validity.valid) {
@@ -647,7 +981,11 @@ function showValidationErrors(tabIndex) {
validationMessageElement.className = 'validation-message';
control.parentNode.insertBefore(validationMessageElement, control.nextSibling);
}
- validationMessageElement.textContent = control.validationMessage || 'This field is invalid.';
+ if (control.hasAttribute('required') && control.value.trim() === '') {
+ validationMessageElement.textContent = window.i18next ? window.i18next.t('messages.please_fill_out_this_field') : 'Please fill out this field.';
+ } else {
+ validationMessageElement.textContent = control.validationMessage || (window.i18next ? window.i18next.t('messages.field_is_invalid') : 'This field is invalid.');
+ }
} else {
// Ensure invalid class is removed if somehow missed by validateTab (shouldn't happen)
control.classList.remove('invalid');
@@ -661,7 +999,15 @@ function showValidationErrors(tabIndex) {
// The browser will attempt to focus the first invalid field when form submission is prevented.
// Switching to the tab containing the error (done by handleFormSubmit) is key.
- showToast('Please correct the errors in the current tab.', 'error');
+
+ // Manage a single validation toast
+ if (!validationToast) {
+ validationToast = showToast(window.t('messages.correct_errors_in_tab'), 'error', 0); // 0 duration = persistent
+ validationToast.classList.add('validation-toast'); // Add a class to identify it
+ } else {
+ // Update existing toast message if needed (optional)
+ validationToast.querySelector('span').textContent = window.t('messages.correct_errors_in_tab');
+ }
}
// Update summary tab with current form values
@@ -729,31 +1075,70 @@ function updateSummary() {
const summaryWarrantyDuration = document.getElementById('summary-warranty-duration'); // Use new ID
if (summaryWarrantyDuration) {
- if (isLifetime) {
- summaryWarrantyDuration.textContent = 'Lifetime';
+ if (isLifetime) {
+ summaryWarrantyDuration.textContent = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';
} else {
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' : ''}`);
-
+ if (years > 0) {
+ const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;
+ durationParts.push(`${years} ${yearText}`);
+ }
+ if (months > 0) {
+ const monthText = window.i18next ? window.i18next.t('warranties.month', {count: months}) : `month${months !== 1 ? 's' : ''}`;
+ durationParts.push(`${months} ${monthText}`);
+ }
+ if (days > 0) {
+ const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;
+ durationParts.push(`${days} ${dayText}`);
+ }
+
summaryWarrantyDuration.textContent = durationParts.length > 0 ? durationParts.join(', ') : '-';
}
}
+ // Warranty type - handle dropdown and custom input
+ const warrantyTypeSelect = document.getElementById('warrantyType');
+ const warrantyTypeCustom = document.getElementById('warrantyTypeCustom');
+ const summaryWarrantyType = document.getElementById('summary-warranty-type');
+ if (summaryWarrantyType) {
+ let warrantyTypeText = 'Not specified';
+ if (warrantyTypeSelect && warrantyTypeSelect.value) {
+ if (warrantyTypeSelect.value === 'other' && warrantyTypeCustom && warrantyTypeCustom.value.trim()) {
+ warrantyTypeText = warrantyTypeCustom.value.trim();
+ } else if (warrantyTypeSelect.value !== 'other') {
+ warrantyTypeText = warrantyTypeSelect.value;
+ }
+ }
+ summaryWarrantyType.textContent = warrantyTypeText;
+ }
+
// Purchase price
const purchasePrice = document.getElementById('purchasePrice')?.value;
+ const currency = document.getElementById('currency')?.value;
const summaryPurchasePrice = document.getElementById('summary-purchase-price');
if (summaryPurchasePrice) {
- summaryPurchasePrice.textContent = purchasePrice ?
- `$${parseFloat(purchasePrice).toFixed(2)}` : 'Not specified';
+ if (purchasePrice) {
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ const amount = parseFloat(purchasePrice).toFixed(2);
+ summaryPurchasePrice.innerHTML = formatCurrencyHTML(amount, symbol, position);
+ } else {
+ summaryPurchasePrice.textContent = 'Not specified';
+ }
}
// Documents
+ const productPhotoFile = document.getElementById('productPhoto')?.files[0];
+ const summaryProductPhoto = document.getElementById('summary-product-photo');
+ if (summaryProductPhoto) {
+ summaryProductPhoto.textContent = productPhotoFile ?
+ productPhotoFile.name : 'No photo selected';
+ }
+
const invoiceFile = document.getElementById('invoice')?.files[0];
const summaryInvoice = document.getElementById('summary-invoice');
if (summaryInvoice) {
@@ -831,18 +1216,32 @@ function resetForm() {
switchToTab(0);
// Clear any file input displays
+ const productPhotoFileName = document.getElementById('productPhotoFileName');
+ if (productPhotoFileName) productPhotoFileName.textContent = '';
fileName.textContent = '';
manualFileName.textContent = '';
- if (otherDocumentFileName) otherDocumentFileName.textContent = '';
+ if (otherDocumentFileName) otherDocumentFileName.textContent = '';
+
+ // Reset photo preview
+ const productPhotoPreview = document.getElementById('productPhotoPreview');
+ if (productPhotoPreview) {
+ productPhotoPreview.style.display = 'none';
+ }
}
async function exportWarranties() {
+ console.log('[EXPORT DEBUG] Starting export process');
+ console.log('[EXPORT DEBUG] Total warranties in memory:', warranties.length);
+ console.log('[EXPORT DEBUG] Current filters:', currentFilters);
+
// Get filtered warranties
let warrantiesToExport = [...warranties];
+ console.log('[EXPORT DEBUG] Initial warranties to export:', warrantiesToExport.length);
// Apply current filters
if (currentFilters.search) {
const searchTerm = currentFilters.search.toLowerCase();
+ console.log('[EXPORT DEBUG] Applying search filter:', searchTerm);
warrantiesToExport = warrantiesToExport.filter(warranty => {
// Check if product name contains search term
const productNameMatch = warranty.product_name.toLowerCase().includes(searchTerm);
@@ -857,23 +1256,49 @@ async function exportWarranties() {
// Return true if either product name, tag name, or vendor name matches
return productNameMatch || tagMatch || vendorMatch;
});
+ console.log('[EXPORT DEBUG] After search filter:', warrantiesToExport.length);
}
if (currentFilters.status !== 'all') {
+ console.log('[EXPORT DEBUG] Applying status filter:', currentFilters.status);
warrantiesToExport = warrantiesToExport.filter(warranty =>
warranty.status === currentFilters.status
);
+ console.log('[EXPORT DEBUG] After status filter:', warrantiesToExport.length);
}
// Apply tag filter
if (currentFilters.tag !== 'all') {
const tagId = parseInt(currentFilters.tag);
+ console.log('[EXPORT DEBUG] Applying tag filter:', tagId);
warrantiesToExport = warrantiesToExport.filter(warranty =>
warranty.tags && Array.isArray(warranty.tags) &&
warranty.tags.some(tag => tag.id === tagId)
);
+ console.log('[EXPORT DEBUG] After tag filter:', warrantiesToExport.length);
+ }
+
+ // Apply vendor filter
+ if (currentFilters.vendor !== 'all') {
+ console.log('[EXPORT DEBUG] Applying vendor filter:', currentFilters.vendor);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ (warranty.vendor || '').toLowerCase() === currentFilters.vendor.toLowerCase()
+ );
+ console.log('[EXPORT DEBUG] After vendor filter:', warrantiesToExport.length);
+ }
+
+ // Apply warranty type filter
+ if (currentFilters.warranty_type !== 'all') {
+ console.log('[EXPORT DEBUG] Applying warranty type filter:', currentFilters.warranty_type);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ (warranty.warranty_type || '').toLowerCase() === currentFilters.warranty_type.toLowerCase()
+ );
+ console.log('[EXPORT DEBUG] After warranty type filter:', warrantiesToExport.length);
}
+ console.log('[EXPORT DEBUG] Final warranties to export:', warrantiesToExport.length);
+ console.log('[EXPORT DEBUG] Warranty IDs being exported:', warrantiesToExport.map(w => w.id));
+
// Create CSV content
let csvContent = "data:text/csv;charset=utf-8,";
@@ -927,11 +1352,11 @@ async function exportWarranties() {
document.body.removeChild(link);
// Show success notification
- showToast('Warranties exported successfully', 'success');
+ showToast(window.t('messages.exported_warranties_successfully', {count: warrantiesToExport.length}), 'success');
}
// Switch view of warranties list
-async function switchView(viewType) { // Added async
+async function switchView(viewType, saveToApi = true) { // Added saveToApi parameter with default true
console.log(`Switching to view: ${viewType}`);
currentView = viewType;
@@ -950,8 +1375,8 @@ async function switchView(viewType) { // Added async
console.log(`View preference (${viewKey}) already set to ${viewType} in localStorage.`);
}
- // --- BEGIN ADDED: Save preference to API ---
- if (window.auth && window.auth.isAuthenticated()) {
+ // --- MODIFIED: Only save preference to API if saveToApi is true ---
+ if (saveToApi && window.auth && window.auth.isAuthenticated()) {
const token = window.auth.getToken();
if (token) {
try {
@@ -981,10 +1406,12 @@ async function switchView(viewType) { // Added async
} else {
console.warn('Cannot save view preference to API: No auth token found.');
}
+ } else if (!saveToApi) {
+ console.log('Skipping API save as saveToApi is false (likely called from loadViewPreference).');
} else {
console.warn('Cannot save view preference to API: User not authenticated or auth module not loaded.');
}
- // --- END ADDED: Save preference to API ---
+ // --- END MODIFIED: Save preference to API ---
// Make sure warrantiesList exists before modifying classes
if (warrantiesList) {
@@ -1008,8 +1435,8 @@ async function switchView(viewType) { // Added async
tableViewHeader.classList.toggle('visible', viewType === 'table');
}
- // Re-render warranties only if warrantiesList exists
- if (warrantiesList) {
+ // Re-render warranties only if warrantiesList exists AND warranties have been loaded from API
+ if (warrantiesList && warrantiesLoaded) {
renderWarranties(filterWarranties()); // Assuming filterWarranties() returns the correct array
}
}
@@ -1040,10 +1467,10 @@ function loadViewPreference() {
// Default to grid view if no preference is saved
savedView = savedView || 'grid';
- console.log(`Applying view preference: ${savedView}`);
+ console.log(`Applying view preference from loadViewPreference: ${savedView}`);
// Switch view only if view buttons exist (implying it's the main page)
if (gridViewBtn || listViewBtn || tableViewBtn) {
- switchView(savedView);
+ switchView(savedView, false); // Pass false to prevent API save on initial load
}
}
@@ -1080,7 +1507,11 @@ function addSerialNumberInput(container = serialNumbersContainer) {
input.type = 'text';
input.className = 'form-control';
input.name = 'serial_numbers[]';
- input.placeholder = 'Enter serial number';
+ input.placeholder = window.i18next ? window.i18next.t('warranties.enter_serial_number') : 'Enter serial number';
+ console.log('i18next available for serial number placeholder:', !!window.i18next);
+ if (window.i18next) {
+ console.log('Translation for warranties.enter_serial_number:', window.i18next.t('warranties.enter_serial_number'));
+ }
// Check if this is the first serial number input
const isFirstInput = container.querySelectorAll('.serial-number-input').length === 0;
@@ -1116,7 +1547,11 @@ function addSerialNumberInput(container = serialNumbersContainer) {
const addButton = document.createElement('button');
addButton.type = 'button';
addButton.className = 'btn btn-sm btn-secondary add-serial';
- addButton.innerHTML = '<i class="fas fa-plus"></i> Add Serial Number';
+ addButton.innerHTML = '<i class="fas fa-plus"></i> ' + (window.i18next ? window.i18next.t('warranties.add_serial_number') : 'Add Serial Number');
+ console.log('i18next available in addSerialNumberInput:', !!window.i18next);
+ if (window.i18next) {
+ console.log('Translation for warranties.add_serial_number:', window.i18next.t('warranties.add_serial_number'));
+ }
addButton.addEventListener('click', function() {
addSerialNumberInput(container);
@@ -1128,48 +1563,110 @@ function addSerialNumberInput(container = serialNumbersContainer) {
// Functions
function showLoading() {
- loadingContainer.classList.add('active');
+ let localLoadingContainer = window.loadingContainer || document.getElementById('loadingContainer');
+ if (localLoadingContainer) {
+ localLoadingContainer.classList.add('active');
+ window.loadingContainer = localLoadingContainer; // Update global reference if found
+ } else {
+ console.error('WarrackerDebug: loadingContainer element not found by showLoading(). Ensure it exists in the HTML and script.js is loaded after it.');
+ }
}
function hideLoading() {
- loadingContainer.classList.remove('active');
+ let localLoadingContainer = window.loadingContainer || document.getElementById('loadingContainer');
+ if (localLoadingContainer) {
+ localLoadingContainer.classList.remove('active');
+ window.loadingContainer = localLoadingContainer; // Update global reference if found
+ } else {
+ console.error('WarrackerDebug: loadingContainer element not found by hideLoading().');
+ }
}
-function showToast(message, type = 'info') {
+function showToast(message, type = 'info', duration = 5000) {
+ // Check if a toast with the same message and type already exists
+ const existingToasts = document.querySelectorAll(`.toast.toast-${type}`);
+ for (let i = 0; i < existingToasts.length; i++) {
+ const span = existingToasts[i].querySelector('span');
+ if (span && span.textContent === message) {
+ return existingToasts[i]; // Don't create a new one
+ }
+ }
+
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
- toast.innerHTML = `
- ${message}
- <button class="toast-close">&times;</button>
- `;
- // Add close event
- toast.querySelector('.toast-close').addEventListener('click', () => {
- toast.remove();
- });
+ 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);
- // Auto remove after 3 seconds
- setTimeout(() => {
- if (toast.parentElement) {
+ // Add a method to remove the toast
+ toast.remove = function() {
+ toast.classList.add('toast-fade-out');
+ setTimeout(() => {
+ if (toast.parentNode) {
+ toast.parentNode.removeChild(toast);
+ }
+ }, 300);
+ };
+
+ // Auto-hide toast after specified duration (if not 0)
+ if (duration > 0) {
+ setTimeout(() => {
toast.remove();
- }
- }, 3000);
+ }, duration);
+ }
+
+ return toast;
}
// Update file name display when a file is selected
function updateFileName(event, inputId = 'invoice', outputId = 'fileName') {
- const input = event ? event.target : document.getElementById(inputId);
+ const file = event.target.files[0];
const output = document.getElementById(outputId);
- if (!input || !output) return;
-
- if (input.files && input.files[0]) {
- output.textContent = input.files[0].name;
- } else {
+ if (file && output) {
+ output.textContent = file.name;
+ } else if (output) {
output.textContent = '';
}
+
+ // Handle photo preview for product photo
+ if (inputId === 'productPhoto' || inputId === 'editProductPhoto') {
+ const previewId = inputId === 'productPhoto' ? 'productPhotoPreview' : 'editProductPhotoPreview';
+ const imgId = inputId === 'productPhoto' ? 'productPhotoImg' : 'editProductPhotoImg';
+ const preview = document.getElementById(previewId);
+ const img = document.getElementById(imgId);
+
+ if (file && file.type.startsWith('image/')) {
+ const reader = new FileReader();
+ reader.onload = function(e) {
+ img.src = e.target.result;
+ preview.style.display = 'block';
+ };
+ reader.readAsDataURL(file);
+ } else {
+ preview.style.display = 'none';
+ }
+ }
}
// Helper function to process warranty data
@@ -1233,7 +1730,7 @@ function processWarrantyData(warranty) {
// --- Lifetime Handling ---
if (processedWarranty.is_lifetime) {
processedWarranty.status = 'active';
- processedWarranty.statusText = 'Lifetime';
+ processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';
processedWarranty.daysRemaining = Infinity;
// Ensure duration components are 0 for lifetime
processedWarranty.warranty_duration_years = 0;
@@ -1250,17 +1747,64 @@ function processWarrantyData(warranty) {
if (daysRemaining < 0) {
processedWarranty.status = 'expired';
- processedWarranty.statusText = 'Expired';
+ processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.expired') : 'Expired';
} else if (daysRemaining < expiringSoonDays) {
processedWarranty.status = 'expiring';
- processedWarranty.statusText = `Expiring Soon (${daysRemaining} day${daysRemaining !== 1 ? 's' : ''})`;
+ const dayText = window.i18next ?
+ window.i18next.t('warranties.day', {count: daysRemaining}) :
+ `day${daysRemaining !== 1 ? 's' : ''}`;
+ processedWarranty.statusText = window.i18next ?
+ window.i18next.t('warranties.days_remaining', {days: daysRemaining, dayText: dayText}) :
+ `${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining`;
} else {
processedWarranty.status = 'active';
- processedWarranty.statusText = `${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining`;
+ const dayText = window.i18next ?
+ window.i18next.t('warranties.day', {count: daysRemaining}) :
+ `day${daysRemaining !== 1 ? 's' : ''}`;
+ processedWarranty.statusText = window.i18next ?
+ window.i18next.t('warranties.days_remaining', {days: daysRemaining, dayText: dayText}) :
+ `${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining`;
+ }
+
+ // Preserve original duration values to detect input method
+ const originalYears = processedWarranty.warranty_duration_years || 0;
+ const originalMonths = processedWarranty.warranty_duration_months || 0;
+ const originalDays = processedWarranty.warranty_duration_days || 0;
+
+ // Track the original input method based on duration values
+ const wasExactDateMethod = originalYears === 0 && originalMonths === 0 && originalDays === 0;
+ processedWarranty.original_input_method = wasExactDateMethod ? 'exact_date' : 'duration';
+
+ // Calculate duration from dates if all duration components are 0 (exact date method was used)
+ const hasNoDuration = originalYears === 0 && originalMonths === 0 && originalDays === 0;
+
+ if (hasNoDuration && purchaseDateObj && processedWarranty.expirationDate) {
+ console.log('[DEBUG] Calculating duration from dates for exact date warranty');
+ const calculatedDuration = calculateDurationFromDates(
+ purchaseDateObj.toISOString().split('T')[0],
+ processedWarranty.expirationDate.toISOString().split('T')[0]
+ );
+ if (calculatedDuration) {
+ // Store calculated duration for display purposes
+ processedWarranty.display_duration_years = calculatedDuration.years;
+ processedWarranty.display_duration_months = calculatedDuration.months;
+ processedWarranty.display_duration_days = calculatedDuration.days;
+ console.log('[DEBUG] Calculated duration:', calculatedDuration);
+
+ // Keep original values at 0 to preserve input method detection
+ processedWarranty.warranty_duration_years = 0;
+ processedWarranty.warranty_duration_months = 0;
+ processedWarranty.warranty_duration_days = 0;
+ }
+ } else {
+ // Use original duration values for display
+ processedWarranty.display_duration_years = originalYears;
+ processedWarranty.display_duration_months = originalMonths;
+ processedWarranty.display_duration_days = originalDays;
}
} else {
processedWarranty.status = 'unknown';
- processedWarranty.statusText = 'Unknown Status';
+ processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.unknown_status') : 'Unknown Status';
processedWarranty.daysRemaining = null;
}
@@ -1277,13 +1821,17 @@ function processAllWarranties() {
console.log('Processed warranties:', warranties);
}
-async function loadWarranties() {
+async function loadWarranties(isAuthenticated) { // Added isAuthenticated parameter
// +++ REMOVED: Ensure Preferences are loaded FIRST (Now handled by authStateReady) +++
// await loadAndApplyUserPreferences();
// +++ Preferences Loaded +++
try {
- console.log('[DEBUG] Entered loadWarranties');
+ console.log('[DEBUG] Entered loadWarranties, isAuthenticated:', isAuthenticated);
+
+ // Reset the flag when starting to load warranties
+ warrantiesLoaded = false;
+
showLoading();
// Fetch user preferences (including date format) before loading warranties
@@ -1351,13 +1899,20 @@ async function loadWarranties() {
*/
// --- END REDUNDANT PREFERENCE FETCH ---
- // Use the full URL to avoid path issues
- const apiUrl = window.location.origin + '/api/warranties';
+ // Check saved view scope preference to determine which API endpoint to use
+ const savedScope = loadViewScopePreference();
+ const shouldUseGlobalView = savedScope === 'global';
+
+ // Use the appropriate API endpoint based on saved preference
+ const baseUrl = window.location.origin;
+ const apiUrl = shouldUseGlobalView ? `${baseUrl}/api/warranties/global` : `${baseUrl}/api/warranties`;
+
+ console.log(`[DEBUG] Using API endpoint based on saved preference '${savedScope}': ${apiUrl}`);
- // Check if auth is available and user is authenticated
- if (!window.auth || !window.auth.isAuthenticated()) {
- console.log('[DEBUG] Early return: User not authenticated');
- renderEmptyState('Please log in to view your warranties.');
+ // Check if auth is available and user is authenticated using the passed parameter
+ if (!isAuthenticated) {
+ console.log('[DEBUG] loadWarranties: Early return - User not authenticated based on passed parameter.');
+ renderEmptyState(window.t('messages.login_to_view_warranties'));
hideLoading();
return;
}
@@ -1365,7 +1920,7 @@ async function loadWarranties() {
const token = window.auth.getToken();
if (!token) {
console.log('[DEBUG] Early return: No auth token available');
- renderEmptyState('Authentication error. Please log in again.');
+ renderEmptyState(window.t('messages.authentication_error_login_again'));
hideLoading();
return;
}
@@ -1391,6 +1946,10 @@ async function loadWarranties() {
if (!Array.isArray(data)) {
console.error('[DEBUG] API did not return an array! Data:', data);
}
+
+ // Update isGlobalView to match the loaded data
+ isGlobalView = shouldUseGlobalView;
+ console.log(`[DEBUG] Set isGlobalView to: ${isGlobalView}`);
// Process each warranty to calculate status and days remaining
warranties = Array.isArray(data) ? data.map(warranty => {
const processed = processWarrantyData(warranty);
@@ -1398,22 +1957,29 @@ async function loadWarranties() {
return processed;
}) : [];
console.log('[DEBUG] Final warranties array:', warranties);
+ console.log('[DEBUG] Total warranties loaded:', warranties.length);
+ console.log('[DEBUG] Warranty IDs loaded:', warranties.map(w => w.id));
+
+ // Set flag to indicate warranties have been loaded from API
+ warrantiesLoaded = true;
if (warranties.length === 0) {
console.log('No warranties found, showing empty state');
- renderEmptyState('No warranties found. Add your first warranty using the form.');
+ renderEmptyState(window.t('messages.no_warranties_found_add_first'));
} else {
console.log('Applying filters to display warranties');
// Populate tag filter dropdown with tags from warranties
populateTagFilter();
populateVendorFilter(); // Added call to populate vendor filter
+ populateWarrantyTypeFilter(); // Added call to populate warranty type filter
// REMOVED: applyFilters(); // Now called from authStateReady after data and prefs are loaded
}
} catch (error) {
console.error('[DEBUG] Error loading warranties:', error);
- renderEmptyState('Error loading warranties. Please try again later.');
+ warrantiesLoaded = false; // Reset flag on error
+ renderEmptyState(window.t('messages.error_loading_warranties_try_again'));
} finally {
hideLoading();
}
@@ -1481,6 +2047,83 @@ function formatDateYYYYMMDD(date) {
return `${year}-${month}-${day}`;
}
+/**
+ * Calculate the age of a product from purchase date to now
+ * @param {string|Date} purchaseDate - The purchase date
+ * @returns {string} - Formatted age string (e.g., "2 years, 3 months", "6 months", "15 days")
+ */
+function calculateProductAge(purchaseDate) {
+ if (!purchaseDate) return 'Unknown';
+
+ const purchase = new Date(purchaseDate);
+ const now = new Date();
+
+ if (isNaN(purchase.getTime()) || purchase > now) {
+ return 'Unknown';
+ }
+
+ // Calculate the difference
+ let years = now.getFullYear() - purchase.getFullYear();
+ let months = now.getMonth() - purchase.getMonth();
+ let days = now.getDate() - purchase.getDate();
+
+ // Adjust for negative days
+ if (days < 0) {
+ months--;
+ const lastMonth = new Date(now.getFullYear(), now.getMonth(), 0);
+ days += lastMonth.getDate();
+ }
+
+ // Adjust for negative months
+ if (months < 0) {
+ years--;
+ months += 12;
+ }
+
+ // Format the result
+ const parts = [];
+ if (years > 0) {
+ const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;
+ parts.push(`${years} ${yearText}`);
+ }
+ if (months > 0) {
+ const monthText = window.i18next ? window.i18next.t('warranties.month', {count: months}) : `month${months !== 1 ? 's' : ''}`;
+ parts.push(`${months} ${monthText}`);
+ }
+ if (days > 0 && years === 0) { // Only show days if less than a year old
+ const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;
+ parts.push(`${days} ${dayText}`);
+ }
+
+ if (parts.length === 0) {
+ return 'Today'; // Purchased today
+ }
+
+ return parts.join(', ');
+}
+
+/**
+ * Calculate the age of a product in days for sorting purposes
+ * @param {string|Date} purchaseDate - The purchase date
+ * @returns {number} - Age in days (0 if invalid date)
+ */
+function calculateProductAgeInDays(purchaseDate) {
+ if (!purchaseDate) return 0;
+
+ const purchase = new Date(purchaseDate);
+ const now = new Date();
+
+ if (isNaN(purchase.getTime()) || purchase > now) {
+ return 0;
+ }
+
+ // Calculate difference in milliseconds and convert to days
+ const diffTime = now.getTime() - purchase.getTime();
+ const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
+
+ return diffDays;
+}
+
async function renderWarranties(warrantiesToRender) {
console.log('renderWarranties called with:', warrantiesToRender);
@@ -1498,7 +2141,7 @@ async function renderWarranties(warrantiesToRender) {
}
const today = new Date();
- const symbol = getCurrencySymbol(); // Get the correct symbol HERE
+ const globalSymbol = getCurrencySymbol(); // Get the global symbol as fallback
warrantiesList.innerHTML = '';
@@ -1509,8 +2152,12 @@ async function renderWarranties(warrantiesToRender) {
return (a.product_name || '').toLowerCase().localeCompare((b.product_name || '').toLowerCase());
case 'purchase':
return new Date(b.purchase_date || 0) - new Date(a.purchase_date || 0);
+ case 'age': // Added age sorting
+ return calculateProductAgeInDays(b.purchase_date) - calculateProductAgeInDays(a.purchase_date); // Oldest first
case 'vendor': // Added vendor sorting
return (a.vendor || '').toLowerCase().localeCompare((b.vendor || '').toLowerCase());
+ case 'warranty_type': // Added warranty type sorting
+ return (a.warranty_type || '').toLowerCase().localeCompare((b.warranty_type || '').toLowerCase());
case 'expiration':
default:
const dateA = new Date(a.expiration_date || 0);
@@ -1552,28 +2199,74 @@ async function renderWarranties(warrantiesToRender) {
const statusClass = warranty.status || 'unknown';
const statusText = warranty.statusText || 'Unknown Status';
// Format warranty duration text
- let warrantyDurationText = 'N/A';
+ let warrantyDurationText = window.i18next ? window.i18next.t('warranties.na') : 'N/A';
if (isLifetime) {
- warrantyDurationText = 'Lifetime';
+ warrantyDurationText = window.i18next ? window.i18next.t('warranties.lifetime') : '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)
- ? warranty.serial_numbers.filter(sn => sn && typeof sn === 'string' && sn.trim() !== '')
- : [];
- // Prepare tags HTML
- const tagsHtml = warranty.tags && warranty.tags.length > 0
+ // Use display_duration values if available, otherwise fall back to warranty_duration values
+ const years = warranty.display_duration_years !== undefined ? warranty.display_duration_years : (warranty.warranty_duration_years || 0);
+ const months = warranty.display_duration_months !== undefined ? warranty.display_duration_months : (warranty.warranty_duration_months || 0);
+ const days = warranty.display_duration_days !== undefined ? warranty.display_duration_days : (warranty.warranty_duration_days || 0);
+
+ // If all duration fields are 0 but we have expiration date, calculate from dates
+ if (years === 0 && months === 0 && days === 0 && warranty.expiration_date && warranty.purchase_date) {
+ const calculatedDuration = calculateDurationFromDates(warranty.purchase_date, warranty.expiration_date);
+ if (calculatedDuration) {
+ let parts = [];
+ if (calculatedDuration.years > 0) {
+ const yearText = window.i18next ? window.i18next.t('warranties.year', {count: calculatedDuration.years}) : `year${calculatedDuration.years !== 1 ? 's' : ''}`;
+ parts.push(`${calculatedDuration.years} ${yearText}`);
+ }
+ if (calculatedDuration.months > 0) {
+ const monthText = window.i18next ? window.i18next.t('warranties.month', {count: calculatedDuration.months}) : `month${calculatedDuration.months !== 1 ? 's' : ''}`;
+ parts.push(`${calculatedDuration.months} ${monthText}`);
+ }
+ if (calculatedDuration.days > 0) {
+ const dayText = window.i18next ? window.i18next.t('warranties.day', {count: calculatedDuration.days}) : `day${calculatedDuration.days !== 1 ? 's' : ''}`;
+ parts.push(`${calculatedDuration.days} ${dayText}`);
+ }
+ if (parts.length > 0) {
+ warrantyDurationText = parts.join(', ');
+ }
+ }
+ } else {
+ // Use the stored/calculated duration fields
+ let parts = [];
+ if (years > 0) {
+ const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;
+ parts.push(`${years} ${yearText}`);
+ }
+ if (months > 0) {
+ const monthText = window.i18next ? window.i18next.t('warranties.month', {count: months}) : `month${months !== 1 ? 's' : ''}`;
+ parts.push(`${months} ${monthText}`);
+ }
+ if (days > 0) {
+ const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;
+ parts.push(`${days} ${dayText}`);
+ }
+ if (parts.length > 0) {
+ warrantyDurationText = parts.join(', ');
+ }
+ }
+ }
+ const expirationDateText = isLifetime ? (window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime') : formatDate(expirationDate);
+
+ // Calculate product age
+ const productAge = calculateProductAge(warranty.purchase_date);
+
+ // Make sure serial numbers array exists and is valid
+ const validSerialNumbers = Array.isArray(warranty.serial_numbers)
+ ? warranty.serial_numbers.filter(sn => sn && typeof sn === 'string' && sn.trim() !== '')
+ : [];
+ // Prepare user info HTML for global view
+ let userInfoHtml = '';
+ if (isGlobalView && warranty.user_display_name) {
+ const ownerLabel = window.i18next ? window.i18next.t('warranties.owner') : 'Owner';
+ userInfoHtml = `<div><strong>${ownerLabel}:</strong> <span>${warranty.user_display_name}</span></div>`;
+ }
+
+ // Prepare tags HTML
+ const tagsHtml = warranty.tags && warranty.tags.length > 0
? `<div class="tags-row">
${warranty.tags.map(tag =>
`<span class="tag" style="background-color: ${tag.color}; color: ${getContrastColor(tag.color)}">
@@ -1588,173 +2281,226 @@ async function renderWarranties(warrantiesToRender) {
// Remove the button, and instead prepare a notes link for document-links-row
let notesLinkHtml = '';
if (hasNotes) {
- notesLinkHtml = `<a href="#" class="notes-link" data-id="${warranty.id}" title="View Notes"><i class='fas fa-sticky-note'></i> Notes</a>`;
+ const notesLabel = window.i18next ? window.i18next.t('warranties.notes') : 'Notes';
+ notesLinkHtml = `<a href="#" class="notes-link" data-id="${warranty.id}" title="View Notes"><i class='fas fa-sticky-note'></i> ${notesLabel}</a>`;
}
+ const hasDocuments = warranty.product_url || warranty.invoice_path || warranty.manual_path || warranty.other_document_path ||
+ warranty.paperless_invoice_id || warranty.paperless_manual_id || warranty.paperless_photo_id || warranty.paperless_other_id || hasNotes;
+
+ // Get current user ID to check warranty ownership
+ const currentUserId = (() => {
+ try {
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ return userInfo.id;
+ } catch (e) {
+ return null;
+ }
+ })();
+
+ // Check if current user can edit/delete this warranty
+ // Allow if: not in global view, user owns the warranty, or user is admin
+ const isAdmin = getUserType() === 'admin';
+ const canEdit = !isGlobalView || (warranty.user_id === currentUserId) || isAdmin;
+
+ // Generate action buttons HTML based on permissions
+ const actionButtonsHtml = canEdit ? `
+ <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
+ <i class="fas fa-edit"></i>
+ </button>
+ <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">
+ <i class="fas fa-trash"></i>
+ </button>
+ ` : `
+ <span class="action-btn-placeholder" title="View only - not your warranty">
+ <i class="fas fa-eye" style="color: #666;"></i>
+ </span>
+ `;
+
const cardElement = document.createElement('div');
cardElement.className = `warranty-card ${statusClass === 'expired' ? 'expired' : statusClass === 'expiring' ? 'expiring-soon' : 'active'}`;
if (currentView === 'grid') {
// Grid view HTML structure
+ const photoThumbnailHtml = warranty.product_photo_path && warranty.product_photo_path !== 'null' ? `
+ <div class="product-photo-thumbnail">
+ <a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">
+ <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"
+ style="width: 80px; height: 80px; object-fit: cover; border-radius: 8px; border: 2px solid var(--border-color); cursor: pointer;"
+ onerror="this.style.display='none'" class="secure-image">
+ </a>
+ </div>
+ ` : '';
+
cardElement.innerHTML = `
<div class="product-name-header">
- <h3 class="warranty-title">${warranty.product_name || 'Unnamed Product'}</h3>
+ <h3 class="warranty-title" title="${warranty.product_name || 'Unnamed Product'}">${warranty.product_name || 'Unnamed Product'}</h3>
<div class="warranty-actions">
- <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
- <i class="fas fa-edit"></i>
- </button>
- <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">
- <i class="fas fa-trash"></i>
- </button>
+ ${actionButtonsHtml}
</div>
</div>
<div class="warranty-content">
+ ${photoThumbnailHtml}
<div class="warranty-info">
- <div>Purchased: <span>${formatDate(purchaseDate)}</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>` : ''}
+ ${userInfoHtml}
+ <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>
+ <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>
+ <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>
+ ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}
${validSerialNumbers.length > 0 ? `
- <div class="serial-numbers">
- <strong>Serial Numbers:</strong>
- <ul>
- ${validSerialNumbers.map(sn => `<li>${sn}</li>`).join('')}
- </ul>
- </div>
+ <div><i class="fas fa-barcode"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>
+ ${validSerialNumbers.length > 1 ? `
+ <div style="margin-left: 28px;">
+ <ul style="margin-top: 5px;">
+ ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}
+ </ul>
+ </div>
+ ` : ''}
` : ''}
+ ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}
+ ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}
</div>
</div>
- <div class="warranty-status-row status-${statusClass}">
- <span>${statusText}</span>
- </div>
+ ${hasDocuments ? `
<div class="document-links-row">
<div class="document-links-inner-container">
${warranty.product_url ? `
<a href="${warranty.product_url}" class="product-link" target="_blank">
- <i class="fas fa-globe"></i> Product Website
+ <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}
</a>
` : ''}
- ${warranty.invoice_path && warranty.invoice_path !== 'null' ? `
- <a href="#" onclick="openSecureFile('${warranty.invoice_path}'); return false;" class="invoice-link">
- <i class="fas fa-file-invoice"></i> Invoice
- </a>` : ''}
- ${warranty.manual_path && warranty.manual_path !== 'null' ? `
- <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>` : ''}
+ ${generateDocumentLink(warranty, 'invoice')}
+ ${generateDocumentLink(warranty, 'manual')}
+ ${generateDocumentLink(warranty, 'other')}
${notesLinkHtml}
</div>
</div>
+ ` : ''}
${tagsHtml}
+ <div class="warranty-status-row status-${statusClass}">
+ <span>${statusText}</span>
+ </div>
`;
} else if (currentView === 'list') {
// List view HTML structure
+ const photoThumbnailHtml = warranty.product_photo_path && warranty.product_photo_path !== 'null' ? `
+ <div class="product-photo-thumbnail">
+ <a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">
+ <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"
+ style="width: 180px; height: 180px; object-fit: cover; border-radius: 6px; border: 2px solid var(--border-color); cursor: pointer;"
+ onerror="this.style.display='none'" class="secure-image">
+ </a>
+ </div>
+ ` : '';
+
cardElement.innerHTML = `
<div class="product-name-header">
- <h3 class="warranty-title">${warranty.product_name || 'Unnamed Product'}</h3>
+ <h3 class="warranty-title" title="${warranty.product_name || 'Unnamed Product'}">${warranty.product_name || 'Unnamed Product'}</h3>
<div class="warranty-actions">
- <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
- <i class="fas fa-edit"></i>
- </button>
- <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">
- <i class="fas fa-trash"></i>
- </button>
+ ${actionButtonsHtml}
</div>
</div>
<div class="warranty-content">
+ ${photoThumbnailHtml}
<div class="warranty-info">
- <div>Purchased: <span>${formatDate(purchaseDate)}</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>` : ''}
+ ${userInfoHtml}
+ <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>
+ <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>
+ <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>
+ ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}
${validSerialNumbers.length > 0 ? `
- <div class="serial-numbers">
- <strong>Serial Numbers:</strong>
- <ul>
- ${validSerialNumbers.map(sn => `<li>${sn}</li>`).join('')}
- </ul>
- </div>
+ <div><i class="fas fa-barcode"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>
+ ${validSerialNumbers.length > 1 ? `
+ <div style="margin-left: 28px;">
+ <ul style="margin-top: 5px;">
+ ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}
+ </ul>
+ </div>
+ ` : ''}
` : ''}
+ ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}
+ ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}
</div>
</div>
- <div class="warranty-status-row status-${statusClass}">
- <span>${statusText}</span>
- </div>
+ ${hasDocuments ? `
<div class="document-links-row">
<div class="document-links-inner-container">
${warranty.product_url ? `
<a href="${warranty.product_url}" class="product-link" target="_blank">
- <i class="fas fa-globe"></i> Product Website
+ <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}
</a>
` : ''}
- ${warranty.invoice_path && warranty.invoice_path !== 'null' ? `
- <a href="#" onclick="openSecureFile('${warranty.invoice_path}'); return false;" class="invoice-link">
- <i class="fas fa-file-invoice"></i> Invoice
- </a>` : ''}
- ${warranty.manual_path && warranty.manual_path !== 'null' ? `
- <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>` : ''}
+ ${generateDocumentLink(warranty, 'invoice')}
+ ${generateDocumentLink(warranty, 'manual')}
+ ${generateDocumentLink(warranty, 'other')}
${notesLinkHtml}
</div>
</div>
+ ` : ''}
${tagsHtml}
+ <div class="warranty-status-row status-${statusClass}">
+ <span>${statusText}</span>
+ </div>
`;
} else if (currentView === 'table') {
// Table view HTML structure
+ const photoThumbnailHtml = warranty.product_photo_path && warranty.product_photo_path !== 'null' ? `
+ <div class="product-photo-thumbnail">
+ <a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">
+ <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"
+ style="width: 55px; height: 55px; object-fit: cover; border-radius: 4px; border: 1px solid var(--border-color); cursor: pointer;"
+ onerror="this.style.display='none'" class="secure-image">
+ </a>
+ </div>
+ ` : '';
+
cardElement.innerHTML = `
<div class="product-name-header">
- <h3 class="warranty-title">${warranty.product_name || 'Unnamed Product'}</h3>
+ <h3 class="warranty-title" title="${warranty.product_name || 'Unnamed Product'}">${warranty.product_name || 'Unnamed Product'}</h3>
<div class="warranty-actions">
- <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
- <i class="fas fa-edit"></i>
- </button>
- <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">
- <i class="fas fa-trash"></i>
- </button>
+ ${actionButtonsHtml}
</div>
</div>
<div class="warranty-content">
+ ${photoThumbnailHtml}
<div class="warranty-info">
- <div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
- <div>Expires: <span>${expirationDateText}</span></div>
+ ${userInfoHtml}
+ <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>
+ <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>
+ <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>
+ ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}
+ ${validSerialNumbers.length > 0 ? `
+ <div><i class="fas fa-barcode"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>
+ ${validSerialNumbers.length > 1 ? `
+ <div style="margin-left: 28px;">
+ <ul style="margin-top: 5px;">
+ ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}
+ </ul>
+ </div>
+ ` : ''}
+ ` : ''}
+ ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}
+ ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}
</div>
</div>
<div class="warranty-status-row status-${statusClass}">
<span>${statusText}</span>
</div>
+ ${hasDocuments ? `
<div class="document-links-row">
<div class="document-links-inner-container">
${warranty.product_url ? `
<a href="${warranty.product_url}" class="product-link" target="_blank">
- <i class="fas fa-globe"></i> Product Website
+ <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}
</a>
` : ''}
- ${warranty.invoice_path && warranty.invoice_path !== 'null' ? `
- <a href="#" onclick="openSecureFile('${warranty.invoice_path}'); return false;" class="invoice-link">
- <i class="fas fa-file-invoice"></i> Invoice
- </a>` : ''}
- ${warranty.manual_path && warranty.manual_path !== 'null' ? `
- <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>` : ''}
+ ${generateDocumentLink(warranty, 'invoice')}
+ ${generateDocumentLink(warranty, 'manual')}
+ ${generateDocumentLink(warranty, 'other')}
${notesLinkHtml}
</div>
</div>
+ ` : ''}
${tagsHtml}
`;
}
@@ -1762,24 +2508,99 @@ async function renderWarranties(warrantiesToRender) {
// Add event listeners
warrantiesList.appendChild(cardElement);
- // Edit button event listener
- cardElement.querySelector('.edit-btn').addEventListener('click', () => {
- openEditModal(warranty);
- });
-
- // Delete button event listener
- cardElement.querySelector('.delete-btn').addEventListener('click', () => {
- openDeleteModal(warranty.id, warranty.product_name);
- });
+ // Add event listeners only if user can edit (buttons exist)
+ if (canEdit) {
+ // Edit button event listener
+ const editBtn = cardElement.querySelector('.edit-btn');
+ if (editBtn) {
+ editBtn.addEventListener('click', async () => {
+ console.log('[DEBUG] Edit button clicked for warranty ID:', warranty.id);
+ // Find the current warranty data instead of using the potentially stale warranty object
+ const currentWarranty = warranties.find(w => w.id === warranty.id);
+ console.log('[DEBUG] Found current warranty:', currentWarranty ? 'Yes' : 'No', currentWarranty?.notes);
+ if (currentWarranty) {
+ await openEditModal(currentWarranty);
+ } else {
+ showToast(window.t('messages.warranty_not_found_refresh'), 'error');
+ }
+ });
+ }
+
+ // Delete button event listener
+ const deleteBtn = cardElement.querySelector('.delete-btn');
+ if (deleteBtn) {
+ deleteBtn.addEventListener('click', () => {
+ openDeleteModal(warranty.id, warranty.product_name);
+ });
+ }
+ }
// View notes button event listener
const notesLink = cardElement.querySelector('.notes-link');
if (notesLink) {
notesLink.addEventListener('click', (e) => {
e.preventDefault();
- showNotesModal(warranty.notes, warranty);
+ // Find the current warranty data instead of using the potentially stale warranty object
+ const currentWarranty = warranties.find(w => w.id === warranty.id);
+ if (currentWarranty) {
+ showNotesModal(currentWarranty.notes, currentWarranty);
+ } else {
+ showToast(window.t('messages.warranty_not_found_refresh'), 'error');
+ }
});
}
});
+
+ // Load secure images with authentication after rendering
+ loadSecureImages();
+
+ // Improved: Align card heights after all images have loaded
+ if (currentView === 'grid') {
+ const cards = warrantiesList.querySelectorAll('.warranty-card');
+ if (cards.length > 0) {
+ const images = warrantiesList.querySelectorAll('.secure-image');
+ let loadedCount = 0;
+ const totalImages = images.length;
+
+ const alignHeights = () => {
+ let maxHeight = 0;
+ cards.forEach(card => {
+ card.style.minHeight = ''; // Reset
+ const height = card.getBoundingClientRect().height;
+ if (height > maxHeight) maxHeight = height;
+ });
+ cards.forEach(card => {
+ card.style.minHeight = `${maxHeight}px`;
+ });
+ };
+
+ if (totalImages === 0) {
+ alignHeights(); // No images, align immediately
+ } else {
+ images.forEach(img => {
+ if (img.complete) {
+ loadedCount++;
+ if (loadedCount === totalImages) alignHeights();
+ } else {
+ img.addEventListener('load', () => {
+ loadedCount++;
+ if (loadedCount === totalImages) alignHeights();
+ });
+ img.addEventListener('error', () => {
+ loadedCount++;
+ if (loadedCount === totalImages) alignHeights();
+ });
+ }
+ });
+ }
+ }
+ }
+
+ // Update the timeline chart if on the status page or appropriate
+ if (typeof updateTimelineChart === 'function') {
+ updateTimelineChart();
+ }
+
+ console.log('Warranties rendered successfully');
}
function filterWarranties() {
@@ -1840,7 +2661,8 @@ function filterWarranties() {
}
function applyFilters() {
- console.log('Applying filters with:', currentFilters);
+ console.log('[FILTER DEBUG] Applying filters with:', currentFilters);
+ console.log('[FILTER DEBUG] Total warranties before filtering:', warranties.length);
// Filter warranties based on currentFilters
const filtered = warranties.filter(warranty => {
@@ -1864,6 +2686,11 @@ function applyFilters() {
return false;
}
+ // Warranty type filter
+ if (currentFilters.warranty_type !== 'all' && (warranty.warranty_type || '').toLowerCase() !== currentFilters.warranty_type.toLowerCase()) {
+ return false;
+ }
+
// Search filter
if (currentFilters.search) {
const searchTerm = currentFilters.search.toLowerCase();
@@ -1888,15 +2715,24 @@ function applyFilters() {
return true;
});
- console.log('Filtered warranties:', filtered);
+ console.log('[FILTER DEBUG] Filtered warranties:', filtered.length);
+ console.log('[FILTER DEBUG] Filtered warranty IDs:', filtered.map(w => w.id));
// Render the filtered warranties
renderWarranties(filtered);
}
-function openEditModal(warranty) {
+async function openEditModal(warranty) {
+ // Close any existing modals first
+ closeModals();
+
currentWarrantyId = warranty.id;
+ // Load currencies for the dropdown and wait for it to complete
+ await loadCurrencies();
+
+ console.log('[DEBUG] Opening edit modal for warranty:', warranty.id, 'with notes:', warranty.notes);
+
// Populate form fields
document.getElementById('editProductName').value = warranty.product_name;
document.getElementById('editProductUrl').value = warranty.product_url || '';
@@ -1907,8 +2743,39 @@ function openEditModal(warranty) {
document.getElementById('editWarrantyDurationDays').value = warranty.warranty_duration_days || 0;
document.getElementById('editPurchasePrice').value = warranty.purchase_price || '';
+
+ // Set currency dropdown
+ const editCurrencySelect = document.getElementById('editCurrency');
+ if (editCurrencySelect && warranty.currency) {
+ editCurrencySelect.value = warranty.currency;
+ }
document.getElementById('editVendor').value = warranty.vendor || '';
+ // Handle warranty type - check if it's a predefined option or custom
+ const editWarrantyTypeSelect = document.getElementById('editWarrantyType');
+ const editWarrantyTypeCustom = document.getElementById('editWarrantyTypeCustom');
+ if (editWarrantyTypeSelect && warranty.warranty_type) {
+ // Check if the warranty type exists as an option in the dropdown
+ const options = Array.from(editWarrantyTypeSelect.options);
+ const matchingOption = options.find(option => option.value === warranty.warranty_type);
+
+ if (matchingOption) {
+ // It's a predefined option
+ editWarrantyTypeSelect.value = warranty.warranty_type;
+ if (editWarrantyTypeCustom) editWarrantyTypeCustom.style.display = 'none';
+ } else {
+ // It's a custom value
+ editWarrantyTypeSelect.value = 'other';
+ if (editWarrantyTypeCustom) {
+ editWarrantyTypeCustom.style.display = 'block';
+ editWarrantyTypeCustom.value = warranty.warranty_type;
+ }
+ }
+ } else if (editWarrantyTypeSelect) {
+ editWarrantyTypeSelect.value = '';
+ if (editWarrantyTypeCustom) editWarrantyTypeCustom.style.display = 'none';
+ }
+
// Clear existing serial number inputs
const editSerialNumbersContainer = document.getElementById('editSerialNumbersContainer');
editSerialNumbersContainer.innerHTML = '';
@@ -1939,9 +2806,9 @@ function openEditModal(warranty) {
const firstInput = document.createElement('div');
firstInput.className = 'serial-number-input';
firstInput.innerHTML = `
- <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number" value="${validSerialNumbers[0]}">
+ <input type="text" name="serial_numbers[]" class="form-control" placeholder="${i18next.t('warranties.enter_serial_number')}" value="${validSerialNumbers[0]}">
<button type="button" class="btn btn-sm btn-primary add-serial-number">
- <i class="fas fa-plus"></i> Add Another
+ <i class="fas fa-plus"></i> ${i18next.t('warranties.add_serial_number')}
</button>
`;
@@ -1958,9 +2825,9 @@ function openEditModal(warranty) {
const newInput = document.createElement('div');
newInput.className = 'serial-number-input';
newInput.innerHTML = `
- <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number" value="${validSerialNumbers[i]}">
+ <input type="text" name="serial_numbers[]" class="form-control" placeholder="${i18next.t('warranties.enter_serial_number')}" value="${validSerialNumbers[i]}">
<button type="button" class="btn btn-sm btn-danger remove-serial-number">
- <i class="fas fa-minus"></i> Remove
+ <i class="fas fa-minus"></i> ${i18next.t('actions.delete')}
</button>
`;
@@ -1977,24 +2844,36 @@ function openEditModal(warranty) {
const currentInvoiceElement = document.getElementById('currentInvoice');
const deleteInvoiceBtn = document.getElementById('deleteInvoiceBtn');
if (currentInvoiceElement && deleteInvoiceBtn) {
- if (warranty.invoice_path && warranty.invoice_path !== 'null') {
+ const hasLocalInvoice = warranty.invoice_path && warranty.invoice_path !== 'null';
+ const hasPaperlessInvoice = warranty.paperless_invoice_id && warranty.paperless_invoice_id !== null;
+
+ if (hasLocalInvoice) {
currentInvoiceElement.innerHTML = `
<span class="text-success">
- <i class="fas fa-check-circle"></i> Current invoice:
+ <i class="fas fa-check-circle"></i> ${i18next.t('warranties.current_invoice')}:
<a href="#" class="view-document-link" onclick="openSecureFile('${warranty.invoice_path}'); return false;">View</a>
- (Upload a new file to replace)
+ (${i18next.t('warranties.upload_new_file_replace')})
+ </span>
+ `;
+ deleteInvoiceBtn.style.display = '';
+ } else if (hasPaperlessInvoice) {
+ currentInvoiceElement.innerHTML = `
+ <span class="text-success">
+ <i class="fas fa-check-circle"></i> ${i18next.t('warranties.current_invoice')}:
+ <a href="#" class="view-document-link" onclick="openPaperlessDocument(${warranty.paperless_invoice_id}); return false;">View</a>
+ <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i> (${i18next.t('warranties.upload_new_file_replace')})
</span>
`;
deleteInvoiceBtn.style.display = '';
} else {
- currentInvoiceElement.innerHTML = '<span>No invoice uploaded</span>';
+ currentInvoiceElement.innerHTML = `<span>${i18next.t('warranties.no_invoice_uploaded')}</span>`;
deleteInvoiceBtn.style.display = 'none';
}
// Reset delete state
deleteInvoiceBtn.dataset.delete = 'false';
deleteInvoiceBtn.onclick = function() {
deleteInvoiceBtn.dataset.delete = 'true';
- currentInvoiceElement.innerHTML = '<span class="text-danger">Invoice will be deleted on save</span>';
+ currentInvoiceElement.innerHTML = `<span class="text-danger">${i18next.t('warranties.invoice_will_be_deleted')}</span>`;
deleteInvoiceBtn.style.display = 'none';
};
}
@@ -2002,63 +2881,189 @@ function openEditModal(warranty) {
const currentManualElement = document.getElementById('currentManual');
const deleteManualBtn = document.getElementById('deleteManualBtn');
if (currentManualElement && deleteManualBtn) {
- if (warranty.manual_path && warranty.manual_path !== 'null') {
+ const hasLocalManual = warranty.manual_path && warranty.manual_path !== 'null';
+ const hasPaperlessManual = warranty.paperless_manual_id && warranty.paperless_manual_id !== null;
+
+ if (hasLocalManual) {
currentManualElement.innerHTML = `
<span class="text-success">
- <i class="fas fa-check-circle"></i> Current manual:
+ <i class="fas fa-check-circle"></i> ${i18next.t('warranties.current_manual')}:
<a href="#" class="view-document-link" onclick="openSecureFile('${warranty.manual_path}'); return false;">View</a>
- (Upload a new file to replace)
+ (${i18next.t('warranties.upload_new_file_replace')})
+ </span>
+ `;
+ deleteManualBtn.style.display = '';
+ } else if (hasPaperlessManual) {
+ currentManualElement.innerHTML = `
+ <span class="text-success">
+ <i class="fas fa-check-circle"></i> ${i18next.t('warranties.current_manual')}:
+ <a href="#" class="view-document-link" onclick="openPaperlessDocument(${warranty.paperless_manual_id}); return false;">View</a>
+ <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i> (${i18next.t('warranties.upload_new_file_replace')})
</span>
`;
deleteManualBtn.style.display = '';
} else {
- currentManualElement.innerHTML = '<span>No manual uploaded</span>';
+ currentManualElement.innerHTML = `<span>${i18next.t('warranties.no_manual_uploaded')}</span>`;
deleteManualBtn.style.display = 'none';
}
// Reset delete state
deleteManualBtn.dataset.delete = 'false';
deleteManualBtn.onclick = function() {
deleteManualBtn.dataset.delete = 'true';
- currentManualElement.innerHTML = '<span class="text-danger">Manual will be deleted on save</span>';
+ currentManualElement.innerHTML = `<span class="text-danger">${i18next.t('warranties.manual_will_be_deleted')}</span>`;
deleteManualBtn.style.display = 'none';
};
}
+ // Show current product photo if exists
+ const currentProductPhotoElement = document.getElementById('currentProductPhoto');
+ const deleteProductPhotoBtn = document.getElementById('deleteProductPhotoBtn');
+ if (currentProductPhotoElement && deleteProductPhotoBtn) {
+ const hasLocalPhoto = warranty.product_photo_path && warranty.product_photo_path !== 'null';
+ const hasPaperlessPhoto = warranty.paperless_photo_id && warranty.paperless_photo_id !== null;
+
+ if (hasLocalPhoto) {
+ currentProductPhotoElement.innerHTML = `
+ <span class="text-success">
+ <i class="fas fa-check-circle"></i> ${i18next.t('warranties.current_photo')}:
+ <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Current Photo" class="secure-image"
+ style="max-width: 100px; max-height: 100px; object-fit: cover; border-radius: 8px; margin-left: 10px; border: 2px solid var(--border-color);"
+ onerror="this.style.display='none'">
+ <br><small>(${i18next.t('warranties.upload_new_photo_replace')})</small>
+ </span>
+ `;
+ deleteProductPhotoBtn.style.display = '';
+ } else if (hasPaperlessPhoto) {
+ currentProductPhotoElement.innerHTML = `
+ <span class="text-success">
+ <i class="fas fa-check-circle"></i> ${i18next.t('warranties.current_photo')}:
+ <a href="#" class="view-document-link" onclick="openPaperlessDocument(${warranty.paperless_photo_id}); return false;">View</a>
+ <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i>
+ <br><small>(${i18next.t('warranties.upload_new_photo_replace')})</small>
+ </span>
+ `;
+ deleteProductPhotoBtn.style.display = '';
+ } else {
+ currentProductPhotoElement.innerHTML = `<span>${i18next.t('warranties.no_photo_uploaded')}</span>`;
+ deleteProductPhotoBtn.style.display = 'none';
+ }
+ // Reset delete state
+ deleteProductPhotoBtn.dataset.delete = 'false';
+ deleteProductPhotoBtn.onclick = function() {
+ deleteProductPhotoBtn.dataset.delete = 'true';
+ currentProductPhotoElement.innerHTML = `<span class="text-danger">${i18next.t('warranties.photo_will_be_deleted')}</span>`;
+ deleteProductPhotoBtn.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') {
+ const hasLocalOther = warranty.other_document_path && warranty.other_document_path !== 'null';
+ const hasPaperlessOther = warranty.paperless_other_id && warranty.paperless_other_id !== null;
+
+ if (hasLocalOther) {
currentOtherDocumentElement.innerHTML = `
<span class="text-success">
- <i class="fas fa-check-circle"></i> Current other document:
+ <i class="fas fa-check-circle"></i> ${i18next.t('warranties.current_other_document')}:
<a href="#" class="view-document-link" onclick="openSecureFile('${warranty.other_document_path}'); return false;">View</a>
- (Upload a new file to replace)
+ (${i18next.t('warranties.upload_new_file_replace')})
+ </span>
+ `;
+ deleteOtherDocumentBtn.style.display = '';
+ } else if (hasPaperlessOther) {
+ currentOtherDocumentElement.innerHTML = `
+ <span class="text-success">
+ <i class="fas fa-check-circle"></i> ${i18next.t('warranties.current_other_document')}:
+ <a href="#" class="view-document-link" onclick="openPaperlessDocument(${warranty.paperless_other_id}); return false;">View</a>
+ <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i> (${i18next.t('warranties.upload_new_file_replace')})
</span>
`;
deleteOtherDocumentBtn.style.display = '';
} else {
- currentOtherDocumentElement.innerHTML = '<span>No other document uploaded</span>';
+ currentOtherDocumentElement.innerHTML = `<span>${i18next.t('warranties.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>';
+ currentOtherDocumentElement.innerHTML = `<span class="text-danger">${i18next.t('warranties.other_document_will_be_deleted')}</span>`;
deleteOtherDocumentBtn.style.display = 'none';
};
}
// Reset file inputs
+ document.getElementById('editProductPhoto').value = '';
document.getElementById('editInvoice').value = '';
document.getElementById('editManual').value = '';
document.getElementById('editOtherDocument').value = '';
+ document.getElementById('editProductPhotoFileName').textContent = '';
document.getElementById('editFileName').textContent = '';
document.getElementById('editManualFileName').textContent = '';
- document.getElementById('editOtherDocumentFileName').textContent = '';
+ document.getElementById('editOtherDocumentFileName').textContent = '';
+
+ // Reset photo preview
+ const editPhotoPreview = document.getElementById('editProductPhotoPreview');
+ if (editPhotoPreview) {
+ editPhotoPreview.style.display = 'none';
+ }
+
+ // Set storage options based on current document storage
+ if (paperlessNgxEnabled) {
+ // Set product photo storage option
+ const editProductPhotoStorageRadios = document.getElementsByName('editProductPhotoStorage');
+ if (editProductPhotoStorageRadios.length > 0) {
+ const isPaperlessPhoto = warranty.paperless_photo_id && warranty.paperless_photo_id !== null;
+ editProductPhotoStorageRadios.forEach(radio => {
+ radio.checked = isPaperlessPhoto ? (radio.value === 'paperless') : (radio.value === 'local');
+ });
+ }
+
+ // Set invoice storage option
+ const editInvoiceStorageRadios = document.getElementsByName('editInvoiceStorage');
+ if (editInvoiceStorageRadios.length > 0) {
+ const isPaperlessInvoice = warranty.paperless_invoice_id && warranty.paperless_invoice_id !== null;
+ editInvoiceStorageRadios.forEach(radio => {
+ radio.checked = isPaperlessInvoice ? (radio.value === 'paperless') : (radio.value === 'local');
+ });
+ }
+
+ // Set manual storage option
+ const editManualStorageRadios = document.getElementsByName('editManualStorage');
+ if (editManualStorageRadios.length > 0) {
+ const isPaperlessManual = warranty.paperless_manual_id && warranty.paperless_manual_id !== null;
+ editManualStorageRadios.forEach(radio => {
+ radio.checked = isPaperlessManual ? (radio.value === 'paperless') : (radio.value === 'local');
+ });
+ }
+
+ // Set other document storage option
+ const editOtherDocumentStorageRadios = document.getElementsByName('editOtherDocumentStorage');
+ if (editOtherDocumentStorageRadios.length > 0) {
+ const isPaperlessOther = warranty.paperless_other_id && warranty.paperless_other_id !== null;
+ editOtherDocumentStorageRadios.forEach(radio => {
+ radio.checked = isPaperlessOther ? (radio.value === 'paperless') : (radio.value === 'local');
+ });
+ }
+
+ console.log('[Edit Modal] Storage options set based on current document storage:', {
+ photo: warranty.paperless_photo_id ? 'paperless' : 'local',
+ invoice: warranty.paperless_invoice_id ? 'paperless' : 'local',
+ manual: warranty.paperless_manual_id ? 'paperless' : 'local',
+ other: warranty.paperless_other_id ? 'paperless' : 'local'
+ });
+ }
// Initialize file input event listeners
+ const editProductPhotoInput = document.getElementById('editProductPhoto');
+ if (editProductPhotoInput) {
+ editProductPhotoInput.addEventListener('change', function(event) {
+ updateFileName(event, 'editProductPhoto', 'editProductPhotoFileName');
+ });
+ }
+
const editInvoiceInput = document.getElementById('editInvoice');
if (editInvoiceInput) {
editInvoiceInput.addEventListener('change', function(event) {
@@ -2183,11 +3188,81 @@ function openEditModal(warranty) {
console.error("Lifetime warranty elements or duration fields not found in edit form");
}
+ // --- Set Warranty Method Selection ---
+ if (editDurationMethodRadio && editExactDateMethodRadio && editExactExpirationDateInput) {
+ console.log('[DEBUG Edit Modal] Warranty method detection:', {
+ originalInputMethod: warranty.original_input_method,
+ isLifetime: warranty.is_lifetime,
+ expirationDate: warranty.expiration_date,
+ warrantyDurationYears: warranty.warranty_duration_years,
+ warrantyDurationMonths: warranty.warranty_duration_months,
+ warrantyDurationDays: warranty.warranty_duration_days
+ });
+
+ // Use the original input method if available, otherwise fall back to previous logic
+ if (!warranty.is_lifetime) {
+ if (warranty.original_input_method === 'exact_date') {
+ // Use exact date method
+ editExactDateMethodRadio.checked = true;
+ editDurationMethodRadio.checked = false;
+ editExactExpirationDateInput.value = warranty.expiration_date.split('T')[0];
+ console.log('[DEBUG Edit Modal] Selected exact date method based on original_input_method');
+ } else {
+ // Use duration method (either explicitly set or fallback)
+ editDurationMethodRadio.checked = true;
+ editExactDateMethodRadio.checked = false;
+ editExactExpirationDateInput.value = '';
+ console.log('[DEBUG Edit Modal] Selected duration method based on original_input_method or fallback');
+ }
+ }
+
+ // Set up event listeners for warranty method change
+ editDurationMethodRadio.removeEventListener('change', handleEditWarrantyMethodChange);
+ editExactDateMethodRadio.removeEventListener('change', handleEditWarrantyMethodChange);
+ editDurationMethodRadio.addEventListener('change', handleEditWarrantyMethodChange);
+ editExactDateMethodRadio.addEventListener('change', handleEditWarrantyMethodChange);
+
+ console.log('[DEBUG Edit Modal] Event listeners attached to warranty method radio buttons');
+ console.log('[DEBUG Edit Modal] Initial radio states:', {
+ durationChecked: editDurationMethodRadio.checked,
+ exactDateChecked: editExactDateMethodRadio.checked
+ });
+
+ // Call handler to set initial state
+ handleEditWarrantyMethodChange();
+ }
+
// Set notes
const notesInput = document.getElementById('editNotes');
if (notesInput) {
notesInput.value = warranty.notes || '';
}
+
+ // Update currency symbols and positioning for the edit form
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ updateFormCurrencyPosition(symbol, position);
+
+ // Trigger currency positioning after modal is visible
+ setTimeout(() => {
+ if (position === 'right') {
+ const editPriceInput = document.getElementById('editPurchasePrice');
+ const editCurrencySymbol = document.getElementById('editCurrencySymbol');
+ if (editPriceInput && editCurrencySymbol) {
+ // Force update the currency position now that modal is visible
+ const wrapper = editPriceInput.closest('.price-input-wrapper');
+ if (wrapper && wrapper.classList.contains('currency-right')) {
+ const updateEvent = new Event('focus');
+ editPriceInput.dispatchEvent(updateEvent);
+ const blurEvent = new Event('blur');
+ editPriceInput.dispatchEvent(blurEvent);
+ }
+ }
+ }
+ }, 200);
+
+ // Load secure images with authentication for the edit modal
+ setTimeout(() => loadSecureImages(), 100); // Small delay to ensure DOM is updated
}
function openDeleteModal(warrantyId, productName) {
@@ -2246,32 +3321,58 @@ function validateFileSize(formData, maxSizeMB = 32) {
}
// Submit form function - event handler for form submit
-function handleFormSubmit(event) { // Renamed from submitForm
+async function handleFormSubmit(event) { // Made async to properly await paperless uploads
event.preventDefault();
const isLifetime = isLifetimeCheckbox.checked;
+ const isDurationMethod = durationMethodRadio && durationMethodRadio.checked;
const years = parseInt(warrantyDurationYearsInput.value || 0);
const months = parseInt(warrantyDurationMonthsInput.value || 0);
const days = parseInt(warrantyDurationDaysInput.value || 0);
+ const exactDate = exactExpirationDateInput ? exactExpirationDateInput.value : '';
- // --- 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
- // 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');
+ // --- Updated Lifetime and Method Check ---
+ if (!isLifetime) {
+ if (isDurationMethod) {
+ // Validate duration fields
+ if (years === 0 && months === 0 && days === 0) {
+ showValidationErrors(1);
+ switchToTab(1); // Switch to warranty details tab
+ // 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 {
+ // Validate exact expiration date
+ if (!exactDate) {
+ showValidationErrors(1);
+ switchToTab(1); // Switch to warranty details tab
+ if (exactExpirationDateInput) exactExpirationDateInput.focus();
+ return;
+ }
+
+ // Validate that expiration date is in the future relative to purchase date
+ const purchaseDate = document.getElementById('purchaseDate').value;
+ if (purchaseDate && exactDate <= purchaseDate) {
+ showToast(window.t('messages.expiration_date_after_purchase_date'), 'error');
+ switchToTab(1);
+ if (exactExpirationDateInput) exactExpirationDateInput.focus();
+ return;
+ }
+ }
}
+ // Remove invalid duration class if validation passes
+ if (warrantyDurationFields) warrantyDurationFields.classList.remove('invalid-duration');
+
// Validate all tabs
for (let i = 0; i < tabContents.length; i++) {
if (!validateTab(i)) {
// Switch to the first invalid tab
switchToTab(i);
+ showValidationErrors(i);
return;
}
}
@@ -2279,6 +3380,20 @@ function handleFormSubmit(event) { // Renamed from submitForm
// Create form data object
const formData = new FormData(warrantyForm);
+ // Handle warranty type - use custom value if "other" is selected
+ const warrantyTypeSelect = document.getElementById('warrantyType');
+ const warrantyTypeCustom = document.getElementById('warrantyTypeCustom');
+ if (warrantyTypeSelect && warrantyTypeSelect.value === 'other' && warrantyTypeCustom && warrantyTypeCustom.value.trim()) {
+ formData.set('warranty_type', warrantyTypeCustom.value.trim());
+ }
+
+ // Debug: Log all form data entries
+ console.log('=== DEBUG: Form Data Contents ===');
+ for (let [key, value] of formData.entries()) {
+ console.log(`${key}: ${value}`);
+ }
+ console.log('=== END DEBUG ===');
+
// Product URL handling
let productUrlValue = formData.get('product_url');
if (productUrlValue && typeof productUrlValue === 'string') {
@@ -2322,6 +3437,15 @@ function handleFormSubmit(event) { // Renamed from submitForm
// We need to explicitly add 'false' if it's not checked.
if (!isLifetimeCheckbox.checked) {
formData.append('is_lifetime', 'false');
+
+ // Add warranty method and exact expiration date if using exact date method
+ if (!isDurationMethod && exactDate) {
+ formData.append('exact_expiration_date', exactDate);
+ // Ensure duration fields are 0 when using exact date
+ formData.set('warranty_duration_years', '0');
+ formData.set('warranty_duration_months', '0');
+ formData.set('warranty_duration_days', '0');
+ }
} else {
// Ensure duration fields are 0 if lifetime is checked
formData.set('warranty_duration_years', '0');
@@ -2329,51 +3453,146 @@ function handleFormSubmit(event) { // Renamed from submitForm
formData.set('warranty_duration_days', '0');
}
- // Add other_document file
- const otherDocumentFile = document.getElementById('otherDocument').files[0];
- if (otherDocumentFile) {
- formData.append('other_document', otherDocumentFile);
- }
+ // Add other_document file (always, as no storage selection for this)
+ const otherDocumentFile = document.getElementById('otherDocument').files[0];
+ if (otherDocumentFile) {
+ formData.append('other_document', otherDocumentFile);
+ }
+
+ // --- Only append invoice/manual files to FormData if storage is 'local' ---
+ const invoiceFile = document.getElementById('invoice')?.files[0];
+ const manualFile = document.getElementById('manual')?.files[0];
+ let invoiceStorage = 'local';
+ let manualStorage = 'local';
+ const invoiceStorageRadio = document.querySelector('input[name="invoiceStorage"]:checked');
+ const manualStorageRadio = document.querySelector('input[name="manualStorage"]:checked');
+ if (invoiceStorageRadio) invoiceStorage = invoiceStorageRadio.value;
+ if (manualStorageRadio) manualStorage = manualStorageRadio.value;
+ formData.set('invoiceStorage', invoiceStorage);
+ formData.set('manualStorage', manualStorage);
+ console.log('[DEBUG] Invoice storage:', invoiceStorage, 'Manual storage:', manualStorage);
+ console.log('[DEBUG] Invoice file:', invoiceFile);
+ console.log('[DEBUG] Manual file:', manualFile);
+ if (invoiceStorage === 'local' && invoiceFile) {
+ console.log('[DEBUG] Appending invoice file to FormData (local storage)');
+ formData.append('invoice', invoiceFile);
+ }
+ if (manualStorage === 'local' && manualFile) {
+ console.log('[DEBUG] Appending manual file to FormData (local storage)');
+ formData.append('manual', manualFile);
+ }
+ if (invoiceStorage === 'paperless') {
+ console.log('[DEBUG] Invoice should be uploaded to Paperless-ngx');
+ }
+ if (manualStorage === 'paperless') {
+ console.log('[DEBUG] Manual should be uploaded to Paperless-ngx');
+ }
+
+ // Add selected Paperless documents (for linking existing docs, not uploads)
+ const selectedPaperlessProductPhoto = document.getElementById('selectedPaperlessProductPhoto');
+ const selectedPaperlessInvoice = document.getElementById('selectedPaperlessInvoice');
+ const selectedPaperlessManual = document.getElementById('selectedPaperlessManual');
+ const selectedPaperlessOtherDocument = document.getElementById('selectedPaperlessOtherDocument');
+ if (selectedPaperlessProductPhoto && selectedPaperlessProductPhoto.value) {
+ formData.append('paperless_photo_id', selectedPaperlessProductPhoto.value);
+ }
+ if (selectedPaperlessInvoice && selectedPaperlessInvoice.value) {
+ formData.append('paperless_invoice_id', selectedPaperlessInvoice.value);
+ }
+ if (selectedPaperlessManual && selectedPaperlessManual.value) {
+ formData.append('paperless_manual_id', selectedPaperlessManual.value);
+ }
+ if (selectedPaperlessOtherDocument && selectedPaperlessOtherDocument.value) {
+ formData.append('paperless_other_id', selectedPaperlessOtherDocument.value);
+ }
// Show loading spinner
showLoadingSpinner();
- // Send the form data to the server
- fetch('/api/warranties', {
- method: 'POST',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token')
- },
- body: formData
- })
- .then(response => {
+ try {
+ // Process Paperless-ngx uploads if enabled
+ const paperlessUploads = await processPaperlessNgxUploads(formData);
+
+ // Add Paperless-ngx document IDs to form data
+ Object.keys(paperlessUploads).forEach(key => {
+ formData.append(key, paperlessUploads[key]);
+ });
+
+ // Send the form data to the server
+ const response = await fetch('/api/warranties', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token')
+ },
+ body: formData
+ });
+
if (!response.ok) {
- return response.json().then(data => {
- throw new Error(data.error || 'Failed to add warranty');
- });
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to add warranty');
}
- return response.json();
- })
- .then(data => {
+
+ const data = await response.json();
hideLoadingSpinner();
- showToast('Warranty added successfully', 'success');
+ showToast(window.t('messages.warranty_added_successfully'), 'success');
- // --- Close and reset the modal on success ---
+ // Store the new warranty ID for auto-linking
+ const newWarrantyId = data.id;
+
+ // --- Store file info and storage type before upload for auto-link logic ---
+ const invoiceFileInput = document.getElementById('invoice');
+ const manualFileInput = document.getElementById('manual');
+ const invoiceFilePre = invoiceFileInput?.files[0];
+ const manualFilePre = manualFileInput?.files[0];
+ const invoiceStoragePre = formData.get('invoiceStorage');
+ const manualStoragePre = formData.get('manualStorage');
+
+ // Auto-link any documents that were uploaded to Paperless-ngx (match edit modal behavior)
+ const autoLinkTypes = [];
+ const fileInfo = {};
+ if (invoiceStoragePre === 'paperless' && invoiceFilePre) {
+ autoLinkTypes.push('invoice');
+ fileInfo.invoice = invoiceFilePre.name;
+ }
+ if (manualStoragePre === 'paperless' && manualFilePre) {
+ autoLinkTypes.push('manual');
+ fileInfo.manual = manualFilePre.name;
+ }
+ // Other document does not have a storage option, so skip unless you add support
+ // If you want to support auto-linking for 'other', add logic here
+ console.log('[Auto-Link DEBUG] newWarrantyId:', newWarrantyId, 'autoLinkTypes:', autoLinkTypes, 'fileInfo:', fileInfo, 'invoiceStorage:', invoiceStoragePre, 'manualStorage:', manualStoragePre);
+ if (autoLinkTypes.length > 0 && newWarrantyId) {
+ console.log('[Auto-Link] Starting automatic document linking after warranty creation (Paperless-ngx uploads only)', autoLinkTypes, fileInfo);
+ setTimeout(() => {
+ console.log('[Auto-Link DEBUG] Calling autoLinkRecentDocuments with:', newWarrantyId, autoLinkTypes, fileInfo);
+ autoLinkRecentDocuments(newWarrantyId, autoLinkTypes, 10, 10000, fileInfo);
+ }, 3000); // Wait 3 seconds for Paperless-ngx to process the documents
+ }
+
+ // Close and reset the modal on success
if (addWarrantyModal) {
addWarrantyModal.classList.remove('active');
}
resetAddWarrantyWizard(); // Reset the wizard form
- // --- End modification ---
- loadWarranties().then(() => {
+ try {
+ await loadWarranties(true);
+ console.log('Warranties reloaded after adding new warranty');
applyFilters();
- }); // Reload the list and update UI
- })
- .catch(error => {
+
+ // Load secure images for the new cards
+ setTimeout(() => {
+ console.log('Loading secure images for new warranty cards');
+ loadSecureImages();
+ }, 200);
+ } catch (error) {
+ console.error('Error reloading warranties after adding:', error);
+ }
+ } catch (error) {
hideLoadingSpinner();
console.error('Error adding warranty:', error);
- showToast(error.message || 'Failed to add warranty', 'error');
- });
+ showToast(error.message || window.t('messages.failed_to_add_warranty'), 'error');
+ }
}
// Initialize page
@@ -2507,13 +3726,7 @@ function validateEditTab(tabId) {
// Add this function for secure file access
function openSecureFile(filePath) {
- if (!filePath || filePath === 'null') {
- console.error('Invalid file path:', filePath);
- showToast('Invalid file path', 'error');
- return false;
- }
-
- console.log('Opening secure file:', filePath);
+ console.log(`[openSecureFile] Opening file: ${filePath}`);
// Get the file name from the path, handling both uploads/ prefix and direct filenames
let fileName = filePath;
@@ -2523,47 +3736,185 @@ function openSecureFile(filePath) {
fileName = filePath.substring(9); // Remove '/uploads/' prefix
}
- // Get auth token
- const token = window.auth.getToken();
+ console.log(`[openSecureFile] Processed filename: ${fileName}`);
+
+ const token = auth.getToken();
+
if (!token) {
- showToast('Authentication error. Please log in again.', 'error');
+ showToast(window.t('messages.login_to_access_files'), 'error');
return false;
}
- // Use fetch with proper authorization header
- fetch(`/api/secure-file/${fileName}`, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`
- }
- })
- .then(response => {
- if (!response.ok) {
- 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();
- })
- .then(blob => {
- // Create a URL for the blob
+ // Enhanced fetch with retry logic and better error handling
+ const fetchWithRetry = async (url, options, retries = 2) => {
+ for (let i = 0; i <= retries; i++) {
+ try {
+ console.log(`[openSecureFile] Attempt ${i + 1} to fetch: ${url}`);
+ const response = await fetch(url, options);
+
+ if (!response.ok) {
+ if (response.status === 401) {
+ throw new Error('Authentication error. Please log in again.');
+ } else if (response.status === 403) {
+ throw new Error('You are not authorized to access this file.');
+ } else if (response.status === 404) {
+ throw new Error('File not found. It may have been deleted.');
+ } else {
+ throw new Error(`Server error: ${response.status} ${response.statusText}`);
+ }
+ }
+
+ // Check if response has content-length header
+ const contentLength = response.headers.get('content-length');
+ console.log(`[openSecureFile] Response Content-Length: ${contentLength}`);
+
+ // Convert to blob with error handling
+ const blob = await response.blob();
+ console.log(`[openSecureFile] Blob size: ${blob.size} bytes`);
+
+ // Verify blob size matches content-length if available
+ if (contentLength && parseInt(contentLength) !== blob.size) {
+ console.warn(`[openSecureFile] Content-Length mismatch: header=${contentLength}, blob=${blob.size}`);
+ if (i < retries) {
+ console.log(`[openSecureFile] Retrying due to content-length mismatch...`);
+ await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second before retry
+ continue;
+ } else {
+ console.error(`[openSecureFile] Final attempt failed with content-length mismatch`);
+ }
+ }
+
+ return blob;
+
+ } catch (error) {
+ console.error(`[openSecureFile] Attempt ${i + 1} failed:`, error);
+
+ // If this is a content-length mismatch or network error, retry
+ if (i < retries && (
+ error.message.includes('content-length') ||
+ error.message.includes('Failed to fetch') ||
+ error.name === 'TypeError'
+ )) {
+ console.log(`[openSecureFile] Retrying after error: ${error.message}`);
+ await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); // Exponential backoff
+ continue;
+ }
+
+ throw error;
+ }
+ }
+ };
+
+ fetchWithRetry(`/api/secure-file/${fileName}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
+ 'Pragma': 'no-cache'
+ }
+ })
+ .then(blob => {
+ console.log(`[openSecureFile] Successfully received blob of size: ${blob.size}`);
+
+ // Create a URL for the blob
const blobUrl = window.URL.createObjectURL(blob);
// Open in new tab
- window.open(blobUrl, '_blank');
+ const newWindow = window.open(blobUrl, '_blank');
+
+ // Clean up the blob URL after a delay to prevent memory leaks
+ setTimeout(() => {
+ window.URL.revokeObjectURL(blobUrl);
+ }, 10000); // Clean up after 10 seconds
+
+ // Check if window was blocked by popup blocker
+ if (!newWindow || newWindow.closed || typeof newWindow.closed === 'undefined') {
+ showToast(window.t('messages.popup_blocked'), 'warning');
+ window.URL.revokeObjectURL(blobUrl); // Clean up immediately if blocked
+ }
})
.catch(error => {
console.error('Error fetching file:', error);
- showToast('Error opening file: ' + error.message, 'error');
+
+ // Provide more specific error messages
+ let errorMessage = 'Error opening file';
+ if (error.message.includes('Authentication')) {
+ errorMessage = 'Authentication error. Please refresh and try again.';
+ } else if (error.message.includes('authorized')) {
+ errorMessage = 'You are not authorized to access this file.';
+ } else if (error.message.includes('not found')) {
+ errorMessage = 'File not found. It may have been deleted.';
+ } else if (error.message.includes('Failed to fetch') || error.name === 'TypeError') {
+ errorMessage = 'Network error. Please check your connection and try again.';
+ } else {
+ errorMessage = `Error opening file: ${error.message}`;
+ }
+
+ showToast(errorMessage, 'error');
});
return false;
}
+/**
+ * Open a Paperless-ngx document by ID
+ */
+
+/**
+ * Generate document link HTML for both local and Paperless-ngx documents
+ */
+function generateDocumentLink(warranty, docType) {
+ const docConfig = {
+ invoice: {
+ localPath: warranty.invoice_path,
+ paperlessId: warranty.paperless_invoice_id,
+ icon: 'fas fa-file-invoice',
+ label: 'Invoice',
+ className: 'invoice-link'
+ },
+ manual: {
+ localPath: warranty.manual_path,
+ paperlessId: warranty.paperless_manual_id,
+ icon: 'fas fa-book',
+ label: 'Manual',
+ className: 'manual-link'
+ },
+ other: {
+ localPath: warranty.other_document_path,
+ paperlessId: warranty.paperless_other_id,
+ icon: 'fas fa-file-alt',
+ label: 'Files',
+ className: 'other-document-link'
+ },
+ photo: {
+ localPath: warranty.product_photo_path,
+ paperlessId: warranty.paperless_photo_id,
+ icon: 'fas fa-image',
+ label: 'Photo',
+ className: 'photo-link'
+ }
+ };
+
+ const config = docConfig[docType];
+ if (!config) return '';
+
+ const hasLocal = config.localPath && config.localPath !== 'null';
+ const hasPaperless = config.paperlessId && config.paperlessId !== null;
+
+
+ if (hasLocal) {
+ return `<a href="#" onclick="openSecureFile('${config.localPath}'); return false;" class="${config.className}">
+ <i class="${config.icon}"></i> ${config.label}
+ </a>`;
+ } else if (hasPaperless) {
+ return `<a href="#" onclick="openPaperlessDocument(${config.paperlessId}); return false;" class="${config.className}">
+ <i class="${config.icon}"></i> ${config.label} <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i>
+ </a>`;
+ }
+
+ return '';
+}
+
// Initialize the warranty form and all its components
function initWarrantyForm() {
// Initialize form tabs
@@ -2575,6 +3926,12 @@ function initWarrantyForm() {
addSerialNumberInput();
// Initialize file input display
+ if (document.getElementById('productPhoto')) {
+ document.getElementById('productPhoto').addEventListener('change', function(event) {
+ updateFileName(event, 'productPhoto', 'productPhotoFileName');
+ });
+ }
+
if (document.getElementById('invoice')) {
document.getElementById('invoice').addEventListener('change', function(event) {
updateFileName(event, 'invoice', 'fileName');
@@ -2926,10 +4283,27 @@ function renderEditSelectedTags() {
// Update createTag to return a Promise
function createTag(name) {
return new Promise((resolve, reject) => {
- const token = localStorage.getItem('auth_token');
+ // Enhanced auth manager availability check
+ if (!window.auth) {
+ console.error('[createTag] Auth manager not available');
+ reject(new Error('Authentication system not ready. Please try again.'));
+ return;
+ }
+
+ // Use auth manager's getToken method instead of directly accessing localStorage
+ const token = window.auth.getToken();
+ console.log('[createTag] Debug info:', {
+ hasToken: !!token,
+ tokenLength: token ? token.length : 0,
+ hasUserInfo: !!localStorage.getItem('user_info'),
+ authManagerAvailable: !!window.auth,
+ isAuthenticated: window.auth.isAuthenticated(),
+ tokenSource: 'auth.getToken()'
+ });
+
if (!token) {
- console.error('No authentication token found');
- reject(new Error('No authentication token found'));
+ console.error('[createTag] No authentication token found');
+ reject(new Error('No authentication token found. Please try logging in again.'));
return;
}
// Generate a random color for the tag
@@ -2947,12 +4321,34 @@ function createTag(name) {
})
.then(response => {
if (!response.ok) {
- if (response.status === 409) {
- reject(new Error('A tag with this name already exists'));
- return;
- }
- reject(new Error('Failed to create tag'));
- return;
+ // Enhanced error handling to capture specific error details
+ return response.json().then(errorData => {
+ console.error('[createTag] API Error Response:', {
+ status: response.status,
+ statusText: response.statusText,
+ errorData: errorData
+ });
+
+ if (response.status === 409) {
+ reject(new Error('A tag with this name already exists'));
+ return;
+ }
+ if (response.status === 401) {
+ reject(new Error('Authentication failed. Please try logging in again.'));
+ return;
+ }
+ if (response.status === 403) {
+ reject(new Error('Permission denied. You may not have access to create tags.'));
+ return;
+ }
+
+ const errorMsg = errorData?.error || errorData?.message || 'Failed to create tag';
+ reject(new Error(errorMsg));
+ }).catch(() => {
+ // If response body is not JSON or is empty
+ console.error('[createTag] Non-JSON error response:', response.status, response.statusText);
+ reject(new Error(`Failed to create tag (${response.status})`));
+ });
}
return response.json();
})
@@ -2966,12 +4362,12 @@ function createTag(name) {
allTags.push(newTag);
renderExistingTags();
populateTagFilter();
- showToast('Tag created successfully', 'success');
+ showToast(window.t('messages.tag_created_successfully'), 'success');
resolve(newTag);
})
.catch(error => {
console.error('Error creating tag:', error);
- showToast(error.message || 'Failed to create tag', 'error');
+ showToast(error.message || window.t('messages.failed_to_create_tag'), 'error');
reject(error);
});
});
@@ -3081,7 +4477,7 @@ function editTag(tag) {
const newColor = tagInfoElement.querySelector('.edit-tag-color').value;
if (!newName) {
- showToast('Tag name is required', 'error');
+ showToast(window.t('messages.tag_name_required'), 'error');
return;
}
@@ -3096,7 +4492,7 @@ function editTag(tag) {
// Update a tag
function updateTag(id, name, color) {
- const token = localStorage.getItem('auth_token');
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
if (!token) {
console.error('No authentication token found');
return;
@@ -3137,20 +4533,46 @@ function updateTag(id, name, color) {
selectedTags[selectedIndex].color = color;
}
+ // Update tag in editSelectedTags if present
+ const editSelectedIndex = editSelectedTags.findIndex(tag => tag.id === id);
+ if (editSelectedIndex !== -1) {
+ editSelectedTags[editSelectedIndex].name = name;
+ editSelectedTags[editSelectedIndex].color = color;
+ }
+
+ // Update tags in warranties array
+ warranties.forEach(warranty => {
+ if (warranty.tags && Array.isArray(warranty.tags)) {
+ warranty.tags.forEach(tag => {
+ if (tag.id === id) {
+ tag.name = name;
+ tag.color = color;
+ }
+ });
+ }
+ });
+
// Rerender existing tags and selected tags
renderExistingTags();
renderSelectedTags();
+ renderEditSelectedTags();
// Update summary if needed
if (document.getElementById('summary-tags')) {
updateSummary();
}
- showToast('Tag updated successfully', 'success');
+ // Update tag filter dropdown
+ populateTagFilter();
+
+ // Re-render warranty cards to show updated tag colors
+ renderWarranties(warranties);
+
+ showToast(window.t('messages.tag_updated_successfully'), 'success');
})
.catch(error => {
console.error('Error updating tag:', error);
- showToast(error.message || 'Failed to update tag', 'error');
+ showToast(error.message || window.t('messages.failed_to_update_tag'), 'error');
});
}
@@ -3163,7 +4585,7 @@ function deleteTag(id) {
const token = localStorage.getItem('auth_token');
if (!token) {
console.error('No authentication token found');
- showToast('Authentication required', 'error'); // Added toast for better feedback
+ showToast(window.t('messages.authentication_required'), 'error'); // Added toast for better feedback
return;
}
@@ -3197,18 +4619,26 @@ function deleteTag(id) {
selectedTags = selectedTags.filter(tag => tag.id !== id);
editSelectedTags = editSelectedTags.filter(tag => tag.id !== id);
+ // Remove tag from warranties array
+ warranties.forEach(warranty => {
+ if (warranty.tags && Array.isArray(warranty.tags)) {
+ warranty.tags = warranty.tags.filter(tag => tag.id !== id);
+ }
+ });
+
// --- FIX: Re-render UI elements ---
renderExistingTags(); // Update the list in the modal
renderSelectedTags(); // Update selected tags in the add form
renderEditSelectedTags(); // Update selected tags in the edit form
populateTagFilter(); // Update the filter dropdown on the main page
+ renderWarranties(warranties); // Update warranty cards to remove deleted tag
// --- END FIX ---
- showToast('Tag deleted successfully', 'success');
+ showToast(window.t('messages.tag_deleted_successfully'), 'success');
})
.catch(error => {
console.error('Error deleting tag:', error);
- showToast(error.message || 'Failed to delete tag', 'error'); // Show specific error message
+ showToast(error.message || window.t('messages.failed_to_delete_tag'), 'error'); // Show specific error message
})
.finally(() => {
hideLoadingSpinner(); // Hide loading indicator
@@ -3291,22 +4721,25 @@ function setupUIEventListeners() {
const vendorFilter = document.getElementById('vendorFilter'); // Added vendor filter select
if (searchInput) {
+ // Debounce logic: only apply filters after user stops typing for 300ms
+ let searchDebounceTimeout;
searchInput.addEventListener('input', () => {
currentFilters.search = searchInput.value.toLowerCase();
-
// Show/hide clear button based on search input
if (clearSearchBtn) {
clearSearchBtn.style.display = searchInput.value ? 'flex' : 'none';
}
-
// Add visual feedback class to search box when active
if (searchInput.value) {
searchInput.parentElement.classList.add('active-search');
} else {
searchInput.parentElement.classList.remove('active-search');
}
-
- applyFilters();
+ // Debounce applyFilters
+ if (searchDebounceTimeout) clearTimeout(searchDebounceTimeout);
+ searchDebounceTimeout = setTimeout(() => {
+ applyFilters();
+ }, 300);
});
}
@@ -3344,6 +4777,13 @@ function setupUIEventListeners() {
});
}
+ if (warrantyTypeFilter) { // Added event listener for warranty type filter
+ warrantyTypeFilter.addEventListener('change', () => {
+ currentFilters.warranty_type = warrantyTypeFilter.value;
+ applyFilters();
+ });
+ }
+
if (sortBySelect) {
sortBySelect.addEventListener('change', () => {
currentFilters.sortBy = sortBySelect.value;
@@ -3380,6 +4820,35 @@ function setupUIEventListeners() {
const refreshBtn = document.getElementById('refreshBtn');
if (refreshBtn) refreshBtn.addEventListener('click', loadWarranties);
+ // Warranty Type dropdown handlers for custom option
+ if (warrantyTypeInput && warrantyTypeCustomInput) {
+ warrantyTypeInput.addEventListener('change', () => {
+ if (warrantyTypeInput.value === 'other') {
+ warrantyTypeCustomInput.style.display = 'block';
+ warrantyTypeCustomInput.focus();
+ } else {
+ warrantyTypeCustomInput.style.display = 'none';
+ warrantyTypeCustomInput.value = '';
+ }
+ updateSummary(); // Update summary when warranty type changes
+ });
+
+ // Also update summary when custom warranty type changes
+ warrantyTypeCustomInput.addEventListener('input', updateSummary);
+ }
+
+ if (editWarrantyTypeInput && editWarrantyTypeCustomInput) {
+ editWarrantyTypeInput.addEventListener('change', () => {
+ if (editWarrantyTypeInput.value === 'other') {
+ editWarrantyTypeCustomInput.style.display = 'block';
+ editWarrantyTypeCustomInput.focus();
+ } else {
+ editWarrantyTypeCustomInput.style.display = 'none';
+ editWarrantyTypeCustomInput.value = '';
+ }
+ });
+ }
+
// Save warranty changes
const saveWarrantyBtn = document.getElementById('saveWarrantyBtn');
if (saveWarrantyBtn) {
@@ -3441,10 +4910,166 @@ function hideLoadingSpinner() {
}
}
+// Paperless upload loading functions
+function showPaperlessUploadLoading(documentType) {
+ // Create or show the Paperless upload overlay
+ let overlay = document.getElementById('paperless-upload-overlay');
+ if (!overlay) {
+ overlay = document.createElement('div');
+ overlay.id = 'paperless-upload-overlay';
+ overlay.innerHTML = `
+ <div class="paperless-upload-modal">
+ <div class="paperless-upload-content">
+ <div class="paperless-upload-spinner"></div>
+ <h3>Uploading to Paperless-ngx</h3>
+ <p id="paperless-upload-status">Uploading document...</p>
+ <div class="paperless-upload-progress">
+ <div class="paperless-upload-progress-bar" id="paperless-progress-bar"></div>
+ </div>
+ </div>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+
+ // Add CSS styles
+ const style = document.createElement('style');
+ style.textContent = `
+ #paperless-upload-overlay {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: rgba(0, 0, 0, 0.7);
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ z-index: 10000;
+ backdrop-filter: blur(2px);
+ }
+
+ .paperless-upload-modal {
+ background: var(--card-bg, #fff);
+ border-radius: 12px;
+ padding: 2rem;
+ max-width: 400px;
+ width: 90%;
+ text-align: center;
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
+ border: 1px solid var(--border-color, #ddd);
+ }
+
+ .paperless-upload-content h3 {
+ margin: 1rem 0 0.5rem 0;
+ color: var(--text-color, #333);
+ font-size: 1.2rem;
+ }
+
+ .paperless-upload-content p {
+ margin: 0.5rem 0 1.5rem 0;
+ color: var(--text-secondary, #666);
+ font-size: 0.9rem;
+ }
+
+ .paperless-upload-spinner {
+ width: 40px;
+ height: 40px;
+ border: 4px solid var(--border-color, #ddd);
+ border-top: 4px solid var(--primary-color, #007bff);
+ border-radius: 50%;
+ animation: paperless-spin 1s linear infinite;
+ margin: 0 auto 1rem auto;
+ }
+
+ @keyframes paperless-spin {
+ 0% { transform: rotate(0deg); }
+ 100% { transform: rotate(360deg); }
+ }
+
+ .paperless-upload-progress {
+ width: 100%;
+ height: 6px;
+ background: var(--border-color, #ddd);
+ border-radius: 3px;
+ overflow: hidden;
+ margin-top: 1rem;
+ }
+
+ .paperless-upload-progress-bar {
+ height: 100%;
+ background: linear-gradient(90deg, var(--primary-color, #007bff), var(--success-color, #28a745));
+ border-radius: 3px;
+ width: 0%;
+ transition: width 0.3s ease;
+ animation: paperless-progress-pulse 2s ease-in-out infinite;
+ }
+
+ @keyframes paperless-progress-pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.7; }
+ }
+ `;
+ document.head.appendChild(style);
+ }
+
+ overlay.style.display = 'flex';
+
+ // Update status text
+ const statusEl = document.getElementById('paperless-upload-status');
+ if (statusEl) {
+ statusEl.textContent = `Uploading ${documentType} to Paperless-ngx...`;
+ }
+
+ // Animate progress bar
+ const progressBar = document.getElementById('paperless-progress-bar');
+ if (progressBar) {
+ progressBar.style.width = '30%';
+ setTimeout(() => {
+ progressBar.style.width = '60%';
+ }, 1000);
+ setTimeout(() => {
+ progressBar.style.width = '80%';
+ }, 2000);
+ }
+}
+
+function updatePaperlessUploadStatus(message, isProcessing = false) {
+ const statusEl = document.getElementById('paperless-upload-status');
+ const progressBar = document.getElementById('paperless-progress-bar');
+
+ if (statusEl) {
+ statusEl.textContent = message;
+ }
+
+ if (isProcessing && progressBar) {
+ progressBar.style.width = '90%';
+ }
+}
+
+function hidePaperlessUploadLoading() {
+ const overlay = document.getElementById('paperless-upload-overlay');
+ if (overlay) {
+ // Complete the progress bar first
+ const progressBar = document.getElementById('paperless-progress-bar');
+ if (progressBar) {
+ progressBar.style.width = '100%';
+ }
+
+ // Hide after a short delay to show completion
+ setTimeout(() => {
+ overlay.style.display = 'none';
+ // Reset progress bar for next use
+ if (progressBar) {
+ progressBar.style.width = '0%';
+ }
+ }, 500);
+ }
+}
+
// Delete warranty function
function deleteWarranty() {
if (!currentWarrantyId) {
- showToast('No warranty selected for deletion', 'error');
+ showToast(window.t('messages.no_warranty_selected_for_deletion'), 'error');
return;
}
@@ -3494,7 +5119,7 @@ function deleteWarranty() {
function saveWarranty() {
console.log("[script.js] CORE saveWarranty (original from script.js) EXECUTING.");
if (!currentWarrantyId) {
- showToast('No warranty selected for update', 'error');
+ showToast(window.t('messages.no_warranty_selected_for_update'), 'error');
return;
}
@@ -3502,36 +5127,58 @@ function saveWarranty() {
const productName = document.getElementById('editProductName').value.trim();
const purchaseDate = document.getElementById('editPurchaseDate').value;
const isLifetime = document.getElementById('editIsLifetime').checked;
+ const isDurationMethod = editDurationMethodRadio && editDurationMethodRadio.checked;
// 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);
+ const exactDate = editExactExpirationDateInput ? editExactExpirationDateInput.value : '';
// Basic validation
if (!productName) {
- showToast('Product name is required', 'error');
+ showToast(window.t('messages.product_name_required'), 'error');
return;
}
if (!purchaseDate) {
- showToast('Purchase date is required', 'error');
+ showToast(window.t('messages.purchase_date_required'), 'error');
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');
+ if (!isLifetime) {
+ if (isDurationMethod) {
+ // Validate duration fields
+ if (years === 0 && months === 0 && days === 0) {
+ showToast(window.t('messages.warranty_duration_required'), '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 {
+ // Validate exact expiration date
+ if (!exactDate) {
+ showToast(window.t('messages.exact_expiration_date_required'), 'error');
+ if (editExactExpirationDateInput) editExactExpirationDateInput.focus();
+ return;
+ }
+
+ // Validate that expiration date is in the future relative to purchase date
+ if (purchaseDate && exactDate <= purchaseDate) {
+ showToast(window.t('messages.expiration_date_after_purchase_date'), 'error');
+ if (editExactExpirationDateInput) editExactExpirationDateInput.focus();
+ return;
+ }
}
- return;
- } else {
- if (editWarrantyDurationFields) editWarrantyDurationFields.classList.remove('invalid-duration');
}
+
+ // Remove invalid duration class if validation passes
+ if (editWarrantyDurationFields) editWarrantyDurationFields.classList.remove('invalid-duration');
// --- End Updated Validation ---
// Create form data
@@ -3549,9 +5196,13 @@ function saveWarranty() {
}
const purchasePrice = document.getElementById('editPurchasePrice').value;
+ const currency = document.getElementById('editCurrency').value;
if (purchasePrice) {
formData.append('purchase_price', purchasePrice);
}
+ if (currency) {
+ formData.append('currency', currency);
+ }
// Serial numbers (use correct name 'serial_numbers[]')
const serialInputs = document.querySelectorAll('#editSerialNumbersContainer input[name="serial_numbers[]"]');
@@ -3588,6 +5239,12 @@ function saveWarranty() {
formData.append('other_document', otherDocumentFile);
}
+ // Product photo
+ const productPhotoFile = document.getElementById('editProductPhoto').files[0];
+ if (productPhotoFile) {
+ formData.append('product_photo', productPhotoFile);
+ }
+
// Document deletion flags
const deleteInvoiceBtn = document.getElementById('deleteInvoiceBtn');
if (deleteInvoiceBtn && deleteInvoiceBtn.dataset.delete === 'true') {
@@ -3600,14 +5257,27 @@ function saveWarranty() {
const deleteOtherDocumentBtn = document.getElementById('deleteOtherDocumentBtn');
if (deleteOtherDocumentBtn && deleteOtherDocumentBtn.dataset.delete === 'true') {
formData.append('delete_other_document', 'true');
+ }
+ const deleteProductPhotoBtn = document.getElementById('deleteProductPhotoBtn');
+ if (deleteProductPhotoBtn && deleteProductPhotoBtn.dataset.delete === 'true') {
+ formData.append('delete_product_photo', 'true');
}
// --- Append is_lifetime and duration components ---
formData.append('is_lifetime', isLifetime.toString());
if (!isLifetime) {
- formData.append('warranty_duration_years', years);
- formData.append('warranty_duration_months', months);
- formData.append('warranty_duration_days', days);
+ if (isDurationMethod) {
+ formData.append('warranty_duration_years', years);
+ formData.append('warranty_duration_months', months);
+ formData.append('warranty_duration_days', days);
+ } else {
+ // Using exact date method
+ formData.append('exact_expiration_date', exactDate);
+ // Ensure duration fields are 0 when using exact date
+ formData.append('warranty_duration_years', 0);
+ formData.append('warranty_duration_months', 0);
+ formData.append('warranty_duration_days', 0);
+ }
} else {
// Ensure duration is 0 if lifetime
formData.append('warranty_duration_years', 0);
@@ -3627,6 +5297,50 @@ function saveWarranty() {
const editVendorInput = document.getElementById('editVendor'); // Use the correct ID
formData.append('vendor', editVendorInput ? editVendorInput.value.trim() : ''); // Use the correct variable
+ // Add warranty type to form data - handle custom type
+ const editWarrantyTypeInput = document.getElementById('editWarrantyType');
+ const editWarrantyTypeCustomInput = document.getElementById('editWarrantyTypeCustom');
+ let warrantyTypeValue = '';
+ if (editWarrantyTypeInput) {
+ if (editWarrantyTypeInput.value === 'other' && editWarrantyTypeCustomInput && editWarrantyTypeCustomInput.value.trim()) {
+ warrantyTypeValue = editWarrantyTypeCustomInput.value.trim();
+ } else {
+ warrantyTypeValue = editWarrantyTypeInput.value.trim();
+ }
+ }
+ formData.append('warranty_type', warrantyTypeValue);
+
+ // Add selected Paperless documents for edit form
+ const selectedEditPaperlessProductPhoto = document.getElementById('selectedEditPaperlessProductPhoto');
+ const selectedEditPaperlessInvoice = document.getElementById('selectedEditPaperlessInvoice');
+ const selectedEditPaperlessManual = document.getElementById('selectedEditPaperlessManual');
+ const selectedEditPaperlessOtherDocument = document.getElementById('selectedEditPaperlessOtherDocument');
+
+ if (selectedEditPaperlessProductPhoto && selectedEditPaperlessProductPhoto.value) {
+ formData.append('paperless_photo_id', selectedEditPaperlessProductPhoto.value);
+ }
+ if (selectedEditPaperlessInvoice && selectedEditPaperlessInvoice.value) {
+ formData.append('paperless_invoice_id', selectedEditPaperlessInvoice.value);
+ }
+ if (selectedEditPaperlessManual && selectedEditPaperlessManual.value) {
+ formData.append('paperless_manual_id', selectedEditPaperlessManual.value);
+ }
+ if (selectedEditPaperlessOtherDocument && selectedEditPaperlessOtherDocument.value) {
+ formData.append('paperless_other_id', selectedEditPaperlessOtherDocument.value);
+ }
+
+ // DEBUG: Log what we're sending to the backend
+ console.log('[DEBUG saveWarranty] Form data being sent:');
+ console.log('[DEBUG saveWarranty] isLifetime:', isLifetime);
+ console.log('[DEBUG saveWarranty] isDurationMethod:', isDurationMethod);
+ console.log('[DEBUG saveWarranty] exactDate:', exactDate);
+ console.log('[DEBUG saveWarranty] years/months/days:', years, months, days);
+
+ // Log all form data entries
+ for (let [key, value] of formData.entries()) {
+ console.log(`[DEBUG saveWarranty] FormData: ${key} = ${value}`);
+ }
+
// Get auth token
const token = localStorage.getItem('auth_token');
if (!token) {
@@ -3636,90 +5350,71 @@ function saveWarranty() {
showLoadingSpinner();
- // Send request
- fetch(`/api/warranties/${currentWarrantyId}`, {
- method: 'PUT',
- headers: {
- 'Authorization': 'Bearer ' + token
- },
- body: formData
- })
- .then(response => {
- if (!response.ok) {
- return response.json().then(data => {
- throw new Error(data.error || 'Failed to update warranty');
+ // Process Paperless-ngx uploads if enabled
+ processEditPaperlessNgxUploads(formData)
+ .then(paperlessUploads => {
+ // Add Paperless-ngx document IDs to form data
+ Object.keys(paperlessUploads).forEach(key => {
+ formData.append(key, paperlessUploads[key]);
});
- }
- return response.json();
- })
- .then(data => {
- hideLoadingSpinner();
- showToast('Warranty updated successfully', 'success');
- closeModals();
- // Instantly reload and re-render the warranties list
- loadWarranties().then(() => {
+
+ // Send request
+ return fetch(`/api/warranties/${currentWarrantyId}`, {
+ method: 'PUT',
+ headers: {
+ 'Authorization': 'Bearer ' + token
+ },
+ body: formData
+ });
+ })
+ .then(response => {
+ if (!response.ok) {
+ return response.json().then(data => {
+ throw new Error(data.error || 'Failed to update warranty');
+ });
+ }
+ return response.json();
+ })
+ .then(data => {
+ hideLoadingSpinner();
+ showToast('Warranty updated successfully', 'success');
+ closeModals();
+
+ // Always reload from server to ensure we get the latest data including product photo paths
+ console.log('Reloading warranties after edit to ensure latest data including product photos');
+ loadWarranties(true).then(() => {
+ console.log('Warranties reloaded after editing warranty');
applyFilters();
+ // Load secure images for the updated cards - additional call to ensure they load
+ setTimeout(() => {
+ console.log('Loading secure images for updated warranty cards');
+ loadSecureImages();
+ }, 200); // Slightly longer delay to ensure everything is rendered
+
// Always close the notes modal if open, to ensure UI is in sync
const notesModal = document.getElementById('notesModal');
if (notesModal && notesModal.style.display === 'block') {
notesModal.style.display = 'none';
}
-
- // --- NEW: Refresh expanded details row if open and keep it open ---
- // Find the row with details-expanded class (if any)
- let expandedWarrantyId = null;
- const expandedRow = document.querySelector('tr.details-expanded');
- if (expandedRow) {
- // Try to get the warranty id from the row (assume data-warranty-id or from first cell if needed)
- expandedWarrantyId = expandedRow.dataset.warrantyId;
- if (!expandedWarrantyId) {
- // Fallback: try to get from first cell if id is rendered there
- const firstCell = expandedRow.querySelector('td');
- if (firstCell && firstCell.dataset && firstCell.dataset.warrantyId) {
- expandedWarrantyId = firstCell.dataset.warrantyId;
- }
- }
- // If still not found, try to match by product name and purchase date (less robust)
- if (!expandedWarrantyId && typeof allWarranties !== 'undefined') {
- const productName = expandedRow.cells[0]?.textContent?.trim();
- const purchaseDate = expandedRow.cells[1]?.textContent?.trim();
- const match = allWarranties.find(w => w.product_name === productName && w.purchase_date && purchaseDate && w.purchase_date.startsWith(purchaseDate));
- if (match) expandedWarrantyId = match.id;
- }
- }
-
- // After re-render, re-expand the row for the same warranty ID
- if (expandedWarrantyId) {
- // Wait for DOM update (next tick)
+
+ console.log('Warranty updated and reloaded from server');
+
+ // Auto-link any documents that were uploaded to Paperless-ngx
+ if ((invoiceFile || manualFile || otherDocumentFile) && currentWarrantyId) {
+ console.log('[Auto-Link] Starting automatic document linking after warranty update');
+
+ // Collect filename information for intelligent searching
+ const fileInfo = {};
+ if (invoiceFile) fileInfo.invoice = invoiceFile.name;
+ if (manualFile) fileInfo.manual = manualFile.name;
+ if (otherDocumentFile) fileInfo.other = otherDocumentFile.name;
+
setTimeout(() => {
- // Find the new row for this warranty ID
- // Try by data-warranty-id attribute
- let newRow = document.querySelector(`tr[data-warranty-id="${expandedWarrantyId}"]`);
- // If not found, try to match by product name and purchase date (fallback)
- if (!newRow) {
- const allRows = document.querySelectorAll('tr');
- for (const row of allRows) {
- const productName = row.cells?.[0]?.textContent?.trim();
- const purchaseDate = row.cells?.[1]?.textContent?.trim();
- const match = allWarranties.find(w => w.id == expandedWarrantyId && w.product_name === productName && w.purchase_date && purchaseDate && w.purchase_date.startsWith(purchaseDate));
- if (match) {
- newRow = row;
- break;
- }
- }
- }
- if (newRow) {
- // Expand the details for this row
- if (typeof window.toggleWarrantyDetails === 'function') {
- window.toggleWarrantyDetails(expandedWarrantyId, newRow);
- } else if (typeof toggleWarrantyDetails === 'function') {
- toggleWarrantyDetails(expandedWarrantyId, newRow);
- }
- newRow.classList.add('details-expanded');
- }
- }, 0);
+ autoLinkRecentDocuments(currentWarrantyId, ['invoice', 'manual', 'other'], 10, 10000, fileInfo);
+ }, 3000); // Wait 3 seconds for Paperless-ngx to process the documents
}
- // --- END NEW ---
+ }).catch(error => {
+ console.error('Error reloading warranties after edit:', error);
});
})
.catch(error => {
@@ -3803,6 +5498,39 @@ function populateVendorFilter() {
});
}
+// Function to populate warranty type filter dropdown
+function populateWarrantyTypeFilter() {
+ const warrantyTypeFilterElement = document.getElementById('warrantyTypeFilter');
+ if (!warrantyTypeFilterElement) return;
+
+ // Clear existing options (except "All Types")
+ while (warrantyTypeFilterElement.options.length > 1) {
+ warrantyTypeFilterElement.remove(1);
+ }
+
+ // Create a Set to store unique warranty types (case-insensitive)
+ const uniqueWarrantyTypes = new Set();
+
+ // Collect all unique, non-empty warranty types from warranties
+ warranties.forEach(warranty => {
+ if (warranty.warranty_type && warranty.warranty_type.trim() !== '') {
+ uniqueWarrantyTypes.add(warranty.warranty_type.trim().toLowerCase());
+ }
+ });
+
+ // Sort warranty types alphabetically
+ const sortedWarrantyTypes = Array.from(uniqueWarrantyTypes).sort((a, b) => a.localeCompare(b));
+
+ // Add options to the dropdown
+ sortedWarrantyTypes.forEach(warrantyType => {
+ const option = document.createElement('option');
+ option.value = warrantyType; // Use lowercase for value consistency
+ // Capitalize first letter for display
+ option.textContent = warrantyType.charAt(0).toUpperCase() + warrantyType.slice(1);
+ warrantyTypeFilterElement.appendChild(option);
+ });
+}
+
// --- Updated Function ---
function handleLifetimeChange(event) {
const checkbox = event ? event.target : isLifetimeCheckbox;
@@ -3810,6 +5538,7 @@ function handleLifetimeChange(event) {
const yearsInput = warrantyDurationYearsInput;
const monthsInput = warrantyDurationMonthsInput;
const daysInput = warrantyDurationDaysInput;
+ const warrantyEntryMethod = document.getElementById('warrantyEntryMethod');
if (!checkbox || !durationFields || !yearsInput || !monthsInput || !daysInput) {
console.error("Lifetime or duration elements not found in add form");
@@ -3817,21 +5546,25 @@ function handleLifetimeChange(event) {
}
if (checkbox.checked) {
+ // Hide warranty method selection and both input methods
+ if (warrantyEntryMethod) warrantyEntryMethod.style.display = 'none';
durationFields.style.display = 'none';
- // Clear and make duration fields not required
+ if (exactExpirationField) exactExpirationField.style.display = 'none';
+
+ // Clear and make fields not required
yearsInput.required = false;
monthsInput.required = false;
daysInput.required = false;
yearsInput.value = '';
monthsInput.value = '';
daysInput.value = '';
+ if (exactExpirationDateInput) exactExpirationDateInput.value = '';
} else {
- 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;
+ // Show warranty method selection
+ if (warrantyEntryMethod) warrantyEntryMethod.style.display = 'block';
+
+ // Call method change handler to show appropriate fields
+ handleWarrantyMethodChange();
}
}
@@ -3842,6 +5575,7 @@ function handleEditLifetimeChange(event) {
const yearsInput = editWarrantyDurationYearsInput;
const monthsInput = editWarrantyDurationMonthsInput;
const daysInput = editWarrantyDurationDaysInput;
+ const editWarrantyEntryMethod = document.getElementById('editWarrantyEntryMethod');
if (!checkbox || !durationFields || !yearsInput || !monthsInput || !daysInput) {
console.error("Lifetime or duration elements not found in edit form");
@@ -3849,20 +5583,25 @@ function handleEditLifetimeChange(event) {
}
if (checkbox.checked) {
+ // Hide warranty method selection and both input methods
+ if (editWarrantyEntryMethod) editWarrantyEntryMethod.style.display = 'none';
durationFields.style.display = 'none';
- // Clear and make duration fields not required
+ if (editExactExpirationField) editExactExpirationField.style.display = 'none';
+
+ // Clear and make fields not required
yearsInput.required = false;
monthsInput.required = false;
daysInput.required = false;
yearsInput.value = '';
monthsInput.value = '';
daysInput.value = '';
+ if (editExactExpirationDateInput) editExactExpirationDateInput.value = '';
} else {
- 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;
+ // Show warranty method selection
+ if (editWarrantyEntryMethod) editWarrantyEntryMethod.style.display = 'block';
+
+ // Call method change handler to show appropriate fields
+ handleEditWarrantyMethodChange();
}
}
@@ -3872,6 +5611,15 @@ function resetAddWarrantyWizard() {
// Reset the form fields
if (warrantyForm) {
warrantyForm.reset();
+
+ // Explicitly set storage options to 'local'
+ const storageTypes = ['invoice', 'manual'];
+ storageTypes.forEach(type => {
+ const localRadio = document.querySelector(`input[name="${type}Storage"][value="local"]`);
+ if (localRadio) {
+ localRadio.checked = true;
+ }
+ });
}
// Reset serial numbers container (remove all but the first input structure)
@@ -3885,13 +5633,15 @@ function resetAddWarrantyWizard() {
if (manualFileName) manualFileName.textContent = '';
if (otherDocumentFileName) otherDocumentFileName.textContent = '';
+ // Clear Paperless document selections (only for invoice and manual)
+ clearPaperlessSelection('invoice');
+ clearPaperlessSelection('manual');
+
// Reset selected tags
selectedTags = [];
console.log('Resetting Add Warranty Wizard...');
- // Reset the form fields
- if (warrantyForm) {
- warrantyForm.reset();
- }
+
+ // No need to reset the form again as we already did it above
// Reset serial numbers container (remove all but the first input structure)
if (serialNumbersContainer) {
@@ -3939,6 +5689,36 @@ function setupModalTriggers() {
addWarrantyModal.classList.add('active');
initFormTabs(); // Initialize tabs only when modal is shown
switchToTab(0); // Ensure the first tab content is displayed correctly after reset
+
+ // Set currency dropdown to user's preferred currency after form reset
+ const preferredCurrencyCode = getCurrencyCode();
+ if (currencySelect && preferredCurrencyCode) {
+ currencySelect.value = preferredCurrencyCode;
+ console.log(`[Modal Open] Set currency dropdown to user preference: ${preferredCurrencyCode}`);
+ }
+
+ // Update currency symbols and positioning for the add form
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ updateFormCurrencyPosition(symbol, position);
+
+ // Trigger currency positioning after modal is visible
+ setTimeout(() => {
+ if (position === 'right') {
+ const addPriceInput = document.getElementById('purchasePrice');
+ const addCurrencySymbol = document.getElementById('addCurrencySymbol');
+ if (addPriceInput && addCurrencySymbol) {
+ // Force update the currency position now that modal is visible
+ const wrapper = addPriceInput.closest('.price-input-wrapper');
+ if (wrapper && wrapper.classList.contains('currency-right')) {
+ const updateEvent = new Event('focus');
+ addPriceInput.dispatchEvent(updateEvent);
+ const blurEvent = new Event('blur');
+ addPriceInput.dispatchEvent(blurEvent);
+ }
+ }
+ }
+ }, 200);
});
}
@@ -4059,7 +5839,7 @@ async function handleImport(file) {
await new Promise(resolve => setTimeout(resolve, 500));
// Await the warranties load to ensure UI is updated
- await loadWarranties();
+ await loadWarranties(true);
// Force a UI refresh by reapplying filters
applyFilters();
@@ -4086,23 +5866,23 @@ async function handleImport(file) {
// --- Add Storage Event Listener for Real-time Sync ---
window.addEventListener('storage', (event) => {
- const prefix = getPreferenceKeyPrefix();
- const viewKeys = [
- `${prefix}defaultView`,
+ const currentPrefix = getPreferenceKeyPrefix(); // Re-calculate prefix
+ const viewKeysToWatch = [
+ `${currentPrefix}defaultView`,
'viewPreference',
- `${prefix}warrantyView`,
- // Add `${prefix}viewPreference` if still used/relevant
- `${prefix}viewPreference`
+ `${currentPrefix}warrantyView`,
+ // Add `${currentPrefix}viewPreference` if still used/relevant
+ `${currentPrefix}viewPreference`
];
// Check for view preference changes
- if (viewKeys.includes(event.key) && event.newValue) {
+ if (viewKeysToWatch.includes(event.key) && event.newValue) {
console.log(`Storage event detected for view preference (${event.key}). New value: ${event.newValue}`);
// Check if the new value is different from the current view to avoid loops
if (event.newValue !== currentView) {
// Ensure view buttons exist before switching (we're on the main page)
if (gridViewBtn || listViewBtn || tableViewBtn) {
- switchView(event.newValue);
+ switchView(event.newValue, false); // Apply change, don't re-save to API
}
} else {
console.log('Storage event value matches current view, ignoring.');
@@ -4121,8 +5901,8 @@ window.addEventListener('storage', (event) => {
// --- End Added Check ---
// --- Added: Check for currency symbol changes ---
- if (event.key === `${prefix}currencySymbol` && event.newValue) {
- console.log(`Storage event detected for ${prefix}currencySymbol. New value: ${event.newValue}`);
+ if (event.key === `${currentPrefix}currencySymbol` && event.newValue) {
+ console.log(`Storage event detected for ${currentPrefix}currencySymbol. New value: ${event.newValue}`);
if (warrantiesList) { // Only apply if on the main page
updateCurrencySymbols(); // Update symbols outside cards (e.g., in forms if they exist)
applyFilters(); // Re-render cards to update symbols inside them
@@ -4149,7 +5929,8 @@ if (!document.getElementById('notesModal')) {
<textarea id="notesModalTextarea" style="display:none;width:100%;min-height:100px;"></textarea>
</div>
<div class="modal-footer" id="notesModalFooter">
- <button class="btn btn-secondary" id="editNotesBtn">Edit</button>
+ <button class="btn btn-secondary" id="editNotesBtn">Edit Notes</button>
+ <button class="btn btn-info" id="editWarrantyBtn">Edit Warranty</button>
<button class="btn btn-primary" id="saveNotesBtn" style="display:none;">Save</button>
<button class="btn btn-danger" id="cancelEditNotesBtn" style="display:none;">Cancel</button>
</div>
@@ -4159,6 +5940,21 @@ if (!document.getElementById('notesModal')) {
document.getElementById('closeNotesModal').addEventListener('click', () => {
notesModal.classList.remove('active');
});
+
+ // Add event listener for Edit Warranty button
+ document.getElementById('editWarrantyBtn').addEventListener('click', async () => {
+ // Find the current warranty data from the global array
+ const currentWarranty = warranties.find(w => w.id === notesModalWarrantyId);
+ if (currentWarranty) {
+ console.log('[DEBUG] Edit Warranty button clicked, opening edit modal with warranty:', currentWarranty.id, 'notes:', currentWarranty.notes);
+ // Close the notes modal first
+ notesModal.classList.remove('active');
+ // Open the edit modal with current data
+ await openEditModal(currentWarranty);
+ } else {
+ showToast(window.t('messages.warranty_not_found_refresh'), 'error');
+ }
+ });
}
// Add global to track which warranty is being edited in the notes modal
@@ -4195,7 +5991,8 @@ function showNotesModal(notes, warrantyOrId = null) {
editBtn.onclick = function() {
notesModalContent.style.display = 'none';
notesModalTextarea.style.display = '';
- notesModalTextarea.value = notes;
+ // Use the current content from the modal display instead of the stale notes parameter
+ notesModalTextarea.value = notesModalContent.textContent;
editBtn.style.display = 'none';
saveBtn.style.display = '';
cancelBtn.style.display = '';
@@ -4213,7 +6010,8 @@ function showNotesModal(notes, warrantyOrId = null) {
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) {
+ (parseInt(notesModalWarrantyObj.warranty_duration_days) || 0) === 0 &&
+ !notesModalWarrantyObj.expiration_date) {
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
}
@@ -4232,6 +6030,17 @@ function showNotesModal(notes, warrantyOrId = null) {
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 all duration fields are 0 but we have an expiration date, this was created with exact date method
+ const isExactDateWarranty = (notesModalWarrantyObj.warranty_duration_years || 0) === 0 &&
+ (notesModalWarrantyObj.warranty_duration_months || 0) === 0 &&
+ (notesModalWarrantyObj.warranty_duration_days || 0) === 0 &&
+ notesModalWarrantyObj.expiration_date;
+
+ if (isExactDateWarranty) {
+ // For exact date warranties, send the expiration date as exact_expiration_date
+ formData.append('exact_expiration_date', notesModalWarrantyObj.expiration_date.split('T')[0]);
+ }
}
if (notesModalWarrantyObj.product_url) {
formData.append('product_url', notesModalWarrantyObj.product_url);
@@ -4284,6 +6093,12 @@ function showNotesModal(notes, warrantyOrId = null) {
hideLoadingSpinner();
showToast('Note updated', 'success');
+ // Update the warranty in the global warranties array immediately
+ const warrantyIndex = warranties.findIndex(w => w.id === notesModalWarrantyId);
+ if (warrantyIndex !== -1) {
+ warranties[warrantyIndex].notes = newNote;
+ }
+
// --- Updated UI logic ---
if (newNote === '') {
// If the note is now empty, close the modal
@@ -4304,7 +6119,7 @@ function showNotesModal(notes, warrantyOrId = null) {
// --- End Updated UI logic ---
// Refresh warranties list and THEN update UI
- await loadWarranties(); // Wait for data refresh
+ await loadWarranties(true); // Wait for data refresh
applyFilters(); // Re-render the list with updated data
} catch (e) {
@@ -4367,15 +6182,292 @@ function getCurrencySymbol() {
return symbol;
}
+// Function to get user's preferred currency code
+function getCurrencyCode() {
+ // Use the global prefix determined after auth ready
+ let prefix = userPreferencePrefix;
+ if (!prefix) {
+ console.warn('[getCurrencyCode] User preference prefix not set yet, defaulting prefix to user_');
+ prefix = 'user_';
+ }
+ console.log(`[getCurrencyCode] Using determined prefix: ${prefix}`);
+
+ // Default to USD
+ let currencyCode = 'USD';
+
+ // Try to get currency code from localStorage
+ const rawValue = localStorage.getItem(`${prefix}currencyCode`);
+ console.log(`[getCurrencyCode Debug] Raw value read from localStorage key '${prefix}currencyCode':`, rawValue);
+
+ if (rawValue) {
+ currencyCode = rawValue;
+ console.log(`[getCurrencyCode] Loaded currency code from individual key (${prefix}currencyCode): ${currencyCode}`);
+ return currencyCode;
+ }
+
+ // Fallback: Try to derive currency code from symbol
+ const symbol = getCurrencySymbol();
+ const symbolToCurrencyMap = {
+ '$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'JPY', '₹': 'INR', '₩': 'KRW',
+ 'CHF': 'CHF', 'C$': 'CAD', 'A$': 'AUD', 'kr': 'SEK', 'zł': 'PLN',
+ 'Kč': 'CZK', 'Ft': 'HUF', '₽': 'RUB', 'R$': 'BRL', '₦': 'NGN',
+ '₪': 'ILS', '₺': 'TRY', '₨': 'PKR', '৳': 'BDT', '฿': 'THB',
+ '₫': 'VND', 'RM': 'MYR', 'S$': 'SGD', 'Rp': 'IDR', '₱': 'PHP',
+ 'NT$': 'TWD', 'HK$': 'HKD', '₮': 'MNT', '₸': 'KZT', '₼': 'AZN',
+ '₾': 'GEL', '₴': 'UAH', 'NZ$': 'NZD'
+ };
+
+ if (symbolToCurrencyMap[symbol]) {
+ currencyCode = symbolToCurrencyMap[symbol];
+ console.log(`[getCurrencyCode] Derived currency code from symbol '${symbol}': ${currencyCode}`);
+ } else {
+ console.log(`[getCurrencyCode] Could not derive currency code from symbol '${symbol}', using default: ${currencyCode}`);
+ }
+
+ return currencyCode;
+}
+
+// Function to load currencies from API and populate dropdowns
+async function loadCurrencies() {
+ try {
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ const response = await fetch('/api/currencies', {
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ });
+ if (!response.ok) {
+ throw new Error('Failed to fetch currencies');
+ }
+
+ const currencies = await response.json();
+
+ // Get user's preferred currency code for default selection
+ const preferredCurrencyCode = getCurrencyCode();
+
+ // Populate add warranty currency dropdown
+ if (currencySelect) {
+ currencySelect.innerHTML = '';
+ currencies.forEach(currency => {
+ const option = document.createElement('option');
+ option.value = currency.code;
+ option.textContent = `${currency.code} - ${currency.name} (${currency.symbol})`;
+ currencySelect.appendChild(option);
+ });
+
+ // Set default selection to user's preferred currency
+ console.log(`[loadCurrencies] Preferred currency code: ${preferredCurrencyCode}`);
+ console.log(`[loadCurrencies] Available currency options:`, Array.from(currencySelect.options).map(opt => opt.value));
+
+ if (preferredCurrencyCode) {
+ // Use setTimeout to ensure DOM is fully updated
+ setTimeout(() => {
+ currencySelect.value = preferredCurrencyCode;
+ console.log(`[loadCurrencies] Set add warranty currency default to: ${preferredCurrencyCode}`);
+ console.log(`[loadCurrencies] Current selected value: ${currencySelect.value}`);
+
+ // Trigger change event to update any dependent UI
+ const changeEvent = new Event('change', { bubbles: true });
+ currencySelect.dispatchEvent(changeEvent);
+ }, 10);
+ } else {
+ console.log(`[loadCurrencies] No preferred currency code found, keeping default USD`);
+ }
+ }
+
+ // Populate edit warranty currency dropdown
+ if (editCurrencySelect) {
+ editCurrencySelect.innerHTML = '';
+ currencies.forEach(currency => {
+ const option = document.createElement('option');
+ option.value = currency.code;
+ option.textContent = `${currency.code} - ${currency.name} (${currency.symbol})`;
+ editCurrencySelect.appendChild(option);
+ });
+ }
+
+ console.log('Currencies loaded successfully');
+ } catch (error) {
+ console.error('Error loading currencies:', error);
+ // Fallback to USD if loading fails
+ if (currencySelect) {
+ currencySelect.innerHTML = '<option value="USD">USD - US Dollar ($)</option>';
+ }
+ if (editCurrencySelect) {
+ editCurrencySelect.innerHTML = '<option value="USD">USD - US Dollar ($)</option>';
+ }
+ }
+}
+
+function getCurrencySymbolByCode(currencyCode) {
+ const currencyMap = {
+ 'USD': '$', 'EUR': '€', 'GBP': '£', 'JPY': '¥', 'CNY': '¥', 'INR': '₹', 'KRW': '₩',
+ 'CHF': 'CHF', 'CAD': 'C$', 'AUD': 'A$', 'SEK': 'kr', 'NOK': 'kr', 'DKK': 'kr',
+ 'PLN': 'zł', 'CZK': 'Kč', 'HUF': 'Ft', 'BGN': 'лв', 'RON': 'lei', 'HRK': 'kn',
+ 'RUB': '₽', 'BRL': 'R$', 'MXN': '$', 'ARS': '$', 'CLP': '$', 'COP': '$',
+ 'PEN': 'S/', 'VES': 'Bs', 'ZAR': 'R', 'EGP': '£', 'NGN': '₦', 'KES': 'KSh',
+ 'GHS': '₵', 'MAD': 'DH', 'TND': 'DT', 'AED': 'AED', 'SAR': 'SR', 'QAR': 'QR',
+ 'KWD': 'KD', 'BHD': 'BD', 'OMR': 'OR', 'JOD': 'JD', 'LBP': 'LL', 'ILS': '₪',
+ 'TRY': '₺', 'IRR': '﷼', 'PKR': '₨', 'BDT': '৳', 'LKR': 'Rs', 'NPR': 'Rs',
+ 'BTN': 'Nu', 'MMK': 'K', 'THB': '฿', 'VND': '₫', 'LAK': '₭', 'KHR': '៛',
+ 'MYR': 'RM', 'SGD': 'S$', 'IDR': 'Rp', 'PHP': '₱', 'TWD': 'NT$', 'HKD': 'HK$',
+ 'MOP': 'MOP', 'KPW': '₩', 'MNT': '₮', 'KZT': '₸', 'UZS': 'soʻm', 'TJS': 'SM',
+ 'KGS': 'с', 'TMT': 'T', 'AFN': '؋', 'AMD': '֏', 'AZN': '₼', 'GEL': '₾',
+ 'MDL': 'L', 'UAH': '₴', 'BYN': 'Br', 'RSD': 'дин', 'MKD': 'ден', 'ALL': 'L',
+ 'BAM': 'KM', 'ISK': 'kr', 'FJD': 'FJ$', 'PGK': 'K', 'SBD': 'SI$', 'TOP': 'T$',
+ 'VUV': 'VT', 'WST': 'WS$', 'XPF': '₣', 'NZD': 'NZ$'
+ };
+ return currencyMap[currencyCode] || currencyCode;
+}
+
+function getCurrencyPosition() {
+ let prefix = userPreferencePrefix;
+ if (!prefix) {
+ console.warn('[getCurrencyPosition] User preference prefix not set yet, defaulting prefix to user_');
+ prefix = 'user_';
+ }
+
+ let position = 'left'; // Default position
+ const rawValue = localStorage.getItem(`${prefix}currencyPosition`);
+ console.log(`[getCurrencyPosition] Raw value from localStorage (${prefix}currencyPosition):`, rawValue);
+
+ if (rawValue) {
+ position = rawValue;
+ console.log(`[getCurrencyPosition] Loaded position from localStorage: ${position}`);
+ } else {
+ console.log(`[getCurrencyPosition] No position found, using default: ${position}`);
+ }
+
+ return position;
+}
+
+function formatCurrencyHTML(amount, symbol, position) {
+ const formattedAmount = parseFloat(amount).toFixed(2);
+
+ if (position === 'right') {
+ return `<span>${formattedAmount}</span><span class="currency-symbol currency-right">${symbol}</span>`;
+ } else {
+ return `<span class="currency-symbol">${symbol}</span><span>${formattedAmount}</span>`;
+ }
+}
+
function updateCurrencySymbols() {
const symbol = getCurrencySymbol();
- console.log(`Updating currency symbols to: ${symbol}`); // Log the symbol being applied
+ const position = getCurrencyPosition();
+ console.log(`Updating currency symbols to: ${symbol}, position: ${position}`);
+
+ // Update all currency symbols
const elements = document.querySelectorAll('.currency-symbol');
- console.log(`Found ${elements.length} elements with class 'currency-symbol'.`); // Log how many elements are found
+ console.log(`Found ${elements.length} elements with class 'currency-symbol'.`);
elements.forEach(el => {
- // console.log('Updating element:', el); // Optional: Log each element being updated
el.textContent = symbol;
});
+
+ // Update form currency positioning
+ updateFormCurrencyPosition(symbol, position);
+}
+
+function updateFormCurrencyPosition(symbol, position) {
+ // Handle add warranty form
+ const addPriceWrapper = document.getElementById('addPriceInputWrapper');
+ const addCurrencySymbol = document.getElementById('addCurrencySymbol');
+ const addPriceInput = document.getElementById('purchasePrice');
+
+ if (addPriceWrapper && addCurrencySymbol) {
+ addCurrencySymbol.textContent = symbol;
+ if (position === 'right') {
+ addPriceWrapper.classList.add('currency-right');
+ // Set up dynamic positioning for right-aligned currency
+ if (addPriceInput) {
+ setupDynamicCurrencyPosition(addPriceInput, addCurrencySymbol);
+ }
+ } else {
+ addPriceWrapper.classList.remove('currency-right');
+ // Reset any dynamic positioning
+ if (addCurrencySymbol) {
+ addCurrencySymbol.style.right = '';
+ }
+ }
+ console.log(`Updated add form currency position: ${position}`);
+ }
+
+ // Handle edit warranty form
+ const editPriceWrapper = document.getElementById('editPriceInputWrapper');
+ const editCurrencySymbol = document.getElementById('editCurrencySymbol');
+ const editPriceInput = document.getElementById('editPurchasePrice');
+
+ if (editPriceWrapper && editCurrencySymbol) {
+ editCurrencySymbol.textContent = symbol;
+ if (position === 'right') {
+ editPriceWrapper.classList.add('currency-right');
+ // Set up dynamic positioning for right-aligned currency
+ if (editPriceInput) {
+ setupDynamicCurrencyPosition(editPriceInput, editCurrencySymbol);
+ }
+ } else {
+ editPriceWrapper.classList.remove('currency-right');
+ // Reset any dynamic positioning
+ if (editCurrencySymbol) {
+ editCurrencySymbol.style.right = '';
+ }
+ }
+ console.log(`Updated edit form currency position: ${position}`);
+ }
+}
+
+function setupDynamicCurrencyPosition(input, currencySymbol) {
+ if (!input || !currencySymbol) return;
+
+ function updatePosition() {
+ const wrapper = input.closest('.price-input-wrapper');
+ if (!wrapper || !wrapper.classList.contains('currency-right')) return;
+
+ // Wait for elements to be fully rendered
+ if (wrapper.offsetWidth === 0) {
+ setTimeout(updatePosition, 50);
+ return;
+ }
+
+ // Get the input value or placeholder
+ const text = input.value || input.placeholder || '0.00';
+
+ // Create a temporary element to measure text width
+ const tempSpan = document.createElement('span');
+ tempSpan.style.visibility = 'hidden';
+ tempSpan.style.position = 'absolute';
+ tempSpan.style.fontSize = window.getComputedStyle(input).fontSize;
+ tempSpan.style.fontFamily = window.getComputedStyle(input).fontFamily;
+ tempSpan.style.fontWeight = window.getComputedStyle(input).fontWeight;
+ tempSpan.style.letterSpacing = window.getComputedStyle(input).letterSpacing;
+ tempSpan.textContent = text;
+
+ document.body.appendChild(tempSpan);
+ const textWidth = tempSpan.offsetWidth;
+ document.body.removeChild(tempSpan);
+
+ // Calculate position: input padding + text width + small gap
+ const inputPaddingLeft = parseInt(window.getComputedStyle(input).paddingLeft) || 12;
+ const gap = 4; // Small gap between text and currency symbol
+ const wrapperWidth = wrapper.offsetWidth;
+ const rightPosition = Math.max(8, wrapperWidth - inputPaddingLeft - textWidth - gap - 20);
+
+ currencySymbol.style.right = rightPosition + 'px';
+ console.log(`[Dynamic Currency] Positioned currency symbol at ${rightPosition}px from right for text: "${text}"`);
+ }
+
+ // Update position on various events
+ input.addEventListener('input', updatePosition);
+ input.addEventListener('focus', updatePosition);
+ input.addEventListener('blur', updatePosition);
+
+ // Initial positioning with better timing
+ // Use requestAnimationFrame to ensure DOM is ready
+ requestAnimationFrame(() => {
+ updatePosition();
+ // Also set up additional fallback timers
+ setTimeout(updatePosition, 100);
+ setTimeout(updatePosition, 300);
+ });
}
// If you want to update currency symbols live when storage changes (e.g. settings page open in another tab):
@@ -4386,10 +6478,22 @@ window.addEventListener('storage', function(e) {
console.log(`Storage event detected for ${prefix}preferences. Updating currency symbols.`);
updateCurrencySymbols();
}
+ // Also update when currency position changes
+ if (e.key === `${prefix}currencyPosition`) {
+ console.log(`Storage event detected for ${prefix}currencyPosition. Re-rendering warranties to update currency position.`);
+ // Update forms immediately
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ updateFormCurrencyPosition(symbol, position);
+ // Re-render warranties to apply new currency position
+ if (typeof processAllWarranties === 'function') {
+ processAllWarranties();
+ }
+ }
});
// +++ NEW FUNCTION TO LOAD PREFS AND SAVE TO LOCALSTORAGE +++
-async function loadAndApplyUserPreferences() {
+async function loadAndApplyUserPreferences(isAuthenticated) { // Added isAuthenticated parameter
// Use the global prefix determined after auth ready
let prefix = userPreferencePrefix; // <<< CHANGED const to let
if (!prefix) {
@@ -4399,16 +6503,17 @@ async function loadAndApplyUserPreferences() {
// For now, let's try defaulting, but this might need review.
prefix = 'user_';
}
- console.log(`[Prefs Loader] Attempting to load preferences using prefix: ${prefix}`);
+ console.log(`[Prefs Loader] Attempting to load preferences using prefix: ${prefix}, isAuthenticated: ${isAuthenticated}`);
- if (window.auth && window.auth.isAuthenticated()) {
- const token = window.auth.getToken();
+ if (isAuthenticated && window.auth) { // Use passed isAuthenticated and check if window.auth exists
+ const token = window.auth.getToken(); // Still need token for the API call
if (!token) {
- console.error('[Prefs Loader] Cannot load preferences: No auth token found.');
+ console.error('[Prefs Loader] Cannot load preferences: No auth token found, even though isAuthenticated was true.');
return; // Exit if no token
}
try {
+ console.log('[Prefs Loader] Fetching /api/auth/preferences with token.');
const response = await fetch('/api/auth/preferences', {
headers: {
'Authorization': `Bearer ${token}`
@@ -4424,6 +6529,10 @@ async function loadAndApplyUserPreferences() {
localStorage.setItem(`${prefix}currencySymbol`, apiPrefs.currency_symbol);
console.log(`[Prefs Loader] Saved ${prefix}currencySymbol: ${apiPrefs.currency_symbol}`);
}
+ if (apiPrefs.currency_position) {
+ localStorage.setItem(`${prefix}currencyPosition`, apiPrefs.currency_position);
+ console.log(`[Prefs Loader] Saved ${prefix}currencyPosition: ${apiPrefs.currency_position}`);
+ }
if (apiPrefs.default_view) {
localStorage.setItem(`${prefix}defaultView`, apiPrefs.default_view);
console.log(`[Prefs Loader] Saved ${prefix}defaultView: ${apiPrefs.default_view}`);
@@ -4467,3 +6576,1911 @@ async function loadAndApplyUserPreferences() {
}
}
// +++ END NEW FUNCTION +++
+
+// Warranty method change handlers
+function handleWarrantyMethodChange() {
+ console.log('[DEBUG] handleWarrantyMethodChange called');
+ const isLifetime = isLifetimeCheckbox && isLifetimeCheckbox.checked;
+ const isDurationMethod = durationMethodRadio && durationMethodRadio.checked;
+
+ console.log('[DEBUG] isLifetime:', isLifetime, 'isDurationMethod:', isDurationMethod);
+ console.log('[DEBUG] Elements found:', {
+ warrantyDurationFields: !!warrantyDurationFields,
+ exactExpirationField: !!exactExpirationField,
+ exactExpirationDateInput: !!exactExpirationDateInput
+ });
+
+ if (isLifetime) {
+ // Hide both methods when lifetime is selected
+ console.log('[DEBUG] Lifetime selected, hiding both methods');
+ if (warrantyDurationFields) warrantyDurationFields.style.display = 'none';
+ if (exactExpirationField) exactExpirationField.style.display = 'none';
+ return;
+ }
+
+ if (isDurationMethod) {
+ console.log('[DEBUG] Duration method selected');
+ if (warrantyDurationFields) warrantyDurationFields.style.display = 'block';
+ if (exactExpirationField) exactExpirationField.style.display = 'none';
+ // Clear exact date when switching to duration
+ if (exactExpirationDateInput) exactExpirationDateInput.value = '';
+ } else {
+ console.log('[DEBUG] Exact date method selected');
+ if (warrantyDurationFields) warrantyDurationFields.style.display = 'none';
+ if (exactExpirationField) exactExpirationField.style.display = 'block';
+ // Clear duration fields when switching to exact date
+ if (warrantyDurationYearsInput) warrantyDurationYearsInput.value = '';
+ if (warrantyDurationMonthsInput) warrantyDurationMonthsInput.value = '';
+ if (warrantyDurationDaysInput) warrantyDurationDaysInput.value = '';
+ }
+}
+
+function handleEditWarrantyMethodChange() {
+ console.log('[DEBUG] handleEditWarrantyMethodChange called');
+ const isLifetime = editIsLifetimeCheckbox && editIsLifetimeCheckbox.checked;
+ const isDurationMethod = editDurationMethodRadio && editDurationMethodRadio.checked;
+
+ console.log('[DEBUG Edit] isLifetime:', isLifetime, 'isDurationMethod:', isDurationMethod);
+ console.log('[DEBUG Edit] Radio button states:', {
+ editDurationMethodRadio: editDurationMethodRadio ? editDurationMethodRadio.checked : 'element not found',
+ editExactDateMethodRadio: editExactDateMethodRadio ? editExactDateMethodRadio.checked : 'element not found'
+ });
+ console.log('[DEBUG Edit] Elements found:', {
+ editWarrantyDurationFields: !!editWarrantyDurationFields,
+ editExactExpirationField: !!editExactExpirationField,
+ editExactExpirationDateInput: !!editExactExpirationDateInput
+ });
+
+ if (isLifetime) {
+ // Hide both methods when lifetime is selected
+ console.log('[DEBUG Edit] Lifetime selected, hiding both methods');
+ if (editWarrantyDurationFields) editWarrantyDurationFields.style.display = 'none';
+ if (editExactExpirationField) editExactExpirationField.style.display = 'none';
+ return;
+ }
+
+ if (isDurationMethod) {
+ console.log('[DEBUG Edit] Duration method selected');
+ if (editWarrantyDurationFields) {
+ editWarrantyDurationFields.style.display = 'block';
+ console.log('[DEBUG Edit] Set duration fields to block');
+ }
+ if (editExactExpirationField) {
+ editExactExpirationField.style.display = 'none';
+ console.log('[DEBUG Edit] Set exact date field to none');
+ }
+ // Clear exact date when switching to duration
+ if (editExactExpirationDateInput) editExactExpirationDateInput.value = '';
+ } else {
+ console.log('[DEBUG Edit] Exact date method selected');
+ if (editWarrantyDurationFields) {
+ editWarrantyDurationFields.style.display = 'none';
+ console.log('[DEBUG Edit] Set duration fields to none');
+ }
+ if (editExactExpirationField) {
+ editExactExpirationField.style.display = 'block';
+ console.log('[DEBUG Edit] Set exact date field to block');
+ }
+ // Clear duration fields when switching to exact date
+ if (editWarrantyDurationYearsInput) editWarrantyDurationYearsInput.value = '';
+ if (editWarrantyDurationMonthsInput) editWarrantyDurationMonthsInput.value = '';
+ if (editWarrantyDurationDaysInput) editWarrantyDurationDaysInput.value = '';
+ }
+}
+
+// Function to calculate duration between two dates
+function calculateDurationFromDates(startDate, endDate) {
+ if (!startDate || !endDate) return null;
+
+ try {
+ const start = new Date(startDate);
+ const end = new Date(endDate);
+
+ if (isNaN(start.getTime()) || isNaN(end.getTime())) return null;
+
+ let years = end.getFullYear() - start.getFullYear();
+ let months = end.getMonth() - start.getMonth();
+ let days = end.getDate() - start.getDate();
+
+ // Adjust for negative days
+ if (days < 0) {
+ months--;
+ const prevMonth = new Date(end.getFullYear(), end.getMonth(), 0);
+ days += prevMonth.getDate();
+ }
+
+ // Adjust for negative months
+ if (months < 0) {
+ years--;
+ months += 12;
+ }
+
+ return { years, months, days };
+ } catch (error) {
+ console.error('Error calculating duration:', error);
+ return null;
+ }
+}
+
+/**
+ * Load secure images with authentication
+ */
+async function loadSecureImages() {
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.log('[DEBUG] No auth token available for secure image loading');
+ return;
+ }
+
+ // Also find images that may already have src but need to be refreshed
+ const secureImages = document.querySelectorAll('img.secure-image[data-secure-src]');
+ console.log(`[DEBUG] Found ${secureImages.length} secure images to load/refresh`);
+
+ for (const img of secureImages) {
+ try {
+ const secureUrl = img.getAttribute('data-secure-src');
+ console.log(`[DEBUG] Loading secure image: ${secureUrl}`);
+
+ // Clean up existing blob URL if present
+ const existingBlobUrl = img.getAttribute('data-blob-url');
+ if (existingBlobUrl) {
+ URL.revokeObjectURL(existingBlobUrl);
+ img.removeAttribute('data-blob-url');
+ }
+
+ const response = await fetch(secureUrl, {
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ });
+
+ if (response.ok) {
+ const blob = await response.blob();
+ const blobUrl = URL.createObjectURL(blob);
+ img.src = blobUrl;
+
+ // Clean up blob URL when image is removed from DOM
+ img.addEventListener('load', () => {
+ console.log(`[DEBUG] Secure image loaded successfully: ${secureUrl}`);
+ }, { once: true });
+
+ // Store blob URL for cleanup
+ img.setAttribute('data-blob-url', blobUrl);
+ } else {
+ console.error(`[DEBUG] Failed to load secure image: ${secureUrl}, status: ${response.status}`);
+ img.style.display = 'none';
+ }
+ } catch (error) {
+ console.error(`[DEBUG] Error loading secure image:`, error);
+ img.style.display = 'none';
+ }
+ }
+}
+
+// ============================================================================
+// Paperless-ngx Integration Functions
+// ============================================================================
+
+// Global variable to store Paperless-ngx enabled state
+let paperlessNgxEnabled = false;
+
+/**
+ * Check if Paperless-ngx integration is enabled
+ */
+async function checkPaperlessNgxStatus() {
+ try {
+ const token = localStorage.getItem('auth_token');
+ if (!token) return false;
+
+ const response = await fetch('/api/admin/settings', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.ok) {
+ const settings = await response.json();
+ paperlessNgxEnabled = settings.paperless_enabled === 'true';
+ window.paperlessNgxEnabled = paperlessNgxEnabled; // Set global variable
+ console.log('[Paperless-ngx] Integration status:', paperlessNgxEnabled);
+ return paperlessNgxEnabled;
+ }
+ } catch (error) {
+ console.error('[Paperless-ngx] Error checking status:', error);
+ }
+ return false;
+}
+
+/**
+ * Initialize Paperless-ngx integration UI
+ */
+async function initPaperlessNgxIntegration() {
+ // Check if Paperless-ngx is enabled
+ const isEnabled = await checkPaperlessNgxStatus();
+
+ if (isEnabled) {
+ // Show the info alert
+ const infoAlert = document.getElementById('paperlessInfoAlert');
+ if (infoAlert) {
+ infoAlert.style.display = 'block';
+ }
+
+ // Show storage selection options for add modal (only invoice and manual)
+ const storageSelections = [
+ 'invoiceStorageSelection',
+ 'manualStorageSelection'
+ ];
+
+ storageSelections.forEach(id => {
+ const element = document.getElementById(id);
+ if (element) {
+ element.style.display = 'block';
+ }
+ });
+
+ // Show storage selection options for edit modal (only invoice and manual)
+ const editStorageSelections = [
+ 'editInvoiceStorageSelection',
+ 'editManualStorageSelection'
+ ];
+
+ editStorageSelections.forEach(id => {
+ const element = document.getElementById(id);
+ if (element) {
+ element.style.display = 'block';
+ }
+ });
+
+ // Show Paperless browse sections
+ console.log('[Paperless-ngx] Calling togglePaperlessBrowseSections...');
+ togglePaperlessBrowseSections();
+
+ console.log('[Paperless-ngx] UI elements initialized and shown');
+ } else {
+ console.log('[Paperless-ngx] Integration disabled, hiding UI elements');
+
+ // Hide Paperless browse sections
+ console.log('[Paperless-ngx] Calling togglePaperlessBrowseSections (disabled)...');
+ togglePaperlessBrowseSections();
+ }
+}
+
+/**
+ * Get selected storage option for a document type
+ * @param {string} documentType - The document type (productPhoto, invoice, manual, otherDocument)
+ * @param {boolean} isEdit - Whether this is for the edit modal
+ * @returns {string} - 'local' or 'paperless'
+ */
+function getStorageOption(documentType, isEdit = false) {
+ // Only allow Paperless-ngx storage for invoices and manuals
+ const paperlessAllowedTypes = ['invoice', 'manual'];
+
+ if (!paperlessAllowedTypes.includes(documentType)) {
+ return 'local'; // Force local storage for productPhoto and otherDocument
+ }
+
+ const prefix = isEdit ? 'edit' : '';
+ const capitalizedType = documentType.charAt(0).toUpperCase() + documentType.slice(1);
+ const name = `${prefix}${capitalizedType}Storage`;
+ const radio = document.querySelector(`input[name="${name}"]:checked`);
+ return radio ? radio.value : 'local';
+}
+
+/**
+ * Upload file to Paperless-ngx
+ * @param {File} file - The file to upload
+ * @param {string} documentType - The type of document for tagging
+ * @returns {Promise<Object>} - Upload result with document ID
+ */
+async function uploadToPaperlessNgx(file, documentType) {
+ try {
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ throw new Error('Authentication token not available');
+ }
+
+ // Show upload loading screen
+ showPaperlessUploadLoading(documentType);
+
+ const formData = new FormData();
+ formData.append('file', file);
+ formData.append('document_type', documentType);
+ formData.append('title', `Warracker ${documentType} - ${file.name}`);
+
+ // Add tags for organization
+ const tags = ['warracker', documentType];
+ formData.append('tags', tags.join(','));
+
+ console.log('[Paperless-ngx] Upload FormData contents:');
+ console.log(' - file:', file.name, '(' + file.size + ' bytes, ' + file.type + ')');
+ console.log(' - document_type:', documentType);
+ console.log(' - title:', `Warracker ${documentType} - ${file.name}`);
+ console.log(' - tags:', tags.join(','));
+
+ updatePaperlessUploadStatus('Uploading file to Paperless-ngx...');
+
+ const response = await fetch('/api/paperless/upload', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ },
+ body: formData
+ });
+
+ if (!response.ok) {
+ let errorMessage = 'Failed to upload to Paperless-ngx';
+ try {
+ const errorData = await response.json();
+ errorMessage = errorData.error || errorData.message || errorMessage;
+ console.error('[Paperless-ngx] Server error details:', errorData);
+ } catch (parseError) {
+ console.error('[Paperless-ngx] Could not parse error response:', parseError);
+ errorMessage = `HTTP ${response.status}: ${response.statusText}`;
+ }
+ hidePaperlessUploadLoading();
+ throw new Error(errorMessage);
+ }
+
+ const result = await response.json();
+ console.log('[Paperless-ngx] Upload successful:', result);
+
+ // Update status based on result
+ if (result.document_id) {
+ updatePaperlessUploadStatus('Document uploaded and ready!');
+ } else {
+ updatePaperlessUploadStatus('Document uploaded, processing...', true);
+ }
+
+ return {
+ success: true,
+ document_id: result.document_id,
+ message: result.message,
+ error: result.error // Add this
+ };
+
+ } catch (error) {
+ console.error('[Paperless-ngx] Upload error:', error);
+ hidePaperlessUploadLoading();
+ return {
+ success: false,
+ error: error.message
+ };
+ }
+}
+
+/**
+ * Handle warranty form submission with Paperless-ngx integration
+ * This extends the existing saveWarranty function
+ */
+async function processPaperlessNgxUploads(formData) {
+ if (!paperlessNgxEnabled) {
+ return {}; // Return empty object if not enabled
+ }
+
+ const uploads = {};
+ // Only process invoice and manual for Paperless-ngx uploads
+ const documentTypes = ['invoice', 'manual'];
+
+ for (const docType of documentTypes) {
+ // Use storage option from formData, not DOM
+ const storageKey = docType + 'Storage';
+ const storageOption = formData.get(storageKey) || 'local';
+ const fileInput = document.getElementById(docType);
+ const file = fileInput?.files[0];
+ console.log(`[DEBUG][processPaperlessNgxUploads] docType:`, docType, '| storageOption (from formData):', storageOption, '| file:', file);
+ if (storageOption === 'paperless') {
+ if (file) {
+ console.log(`[Paperless-ngx] Uploading ${docType} to Paperless-ngx`);
+ // Upload to Paperless-ngx
+ const uploadResult = await uploadToPaperlessNgx(file, docType);
+ console.log(`[DEBUG][processPaperlessNgxUploads] uploadResult for ${docType}:`, uploadResult);
+ if (uploadResult.success || (uploadResult.error && uploadResult.error.includes("duplicate") && uploadResult.document_id)) {
+ // Map frontend document types to database column names
+ const fieldMapping = {
+ 'productPhoto': 'paperless_photo_id',
+ 'invoice': 'paperless_invoice_id',
+ 'manual': 'paperless_manual_id',
+ 'otherDocument': 'paperless_other_id'
+ };
+ const dbField = fieldMapping[docType];
+ if (dbField && uploadResult.document_id) {
+ uploads[dbField] = uploadResult.document_id;
+ console.log(`[Paperless-ngx] ${docType} uploaded/linked successfully, ID: ${uploadResult.document_id}, stored as: ${dbField}`);
+ // Hide loading screen immediately for direct uploads
+ hidePaperlessUploadLoading();
+ if (uploadResult.error && uploadResult.error.includes("duplicate")) {
+ showToast("Duplicate document detected in Paperless-ngx. Linked to existing document.", 'info');
+ }
+ } else if (dbField && !uploadResult.document_id) {
+ console.log(`[Paperless-ngx] ${docType} uploaded successfully but no document ID received (async processing). Not storing reference.`);
+ // Don't hide loading screen yet - auto-link will handle it
+ updatePaperlessUploadStatus('Document processing, searching for link...', true);
+ }
+ // ALWAYS remove the file from FormData since it's been uploaded to Paperless-ngx
+ // This prevents the backend from also saving it locally
+ if (formData.has(docType)) {
+ formData.delete(docType);
+ console.log(`[Paperless-ngx] Removed ${docType} from FormData to prevent local storage`);
+ }
+ } else {
+ console.error(`[Paperless-ngx] Failed to upload ${docType} to Paperless-ngx:`, uploadResult.error);
+ throw new Error(`Failed to upload ${docType} to Paperless-ngx: ${uploadResult.error}`);
+ }
+ } else {
+ console.log(`[DEBUG][processPaperlessNgxUploads] No file found for ${docType} with paperless storage option.`);
+ }
+ } else {
+ console.log(`[DEBUG][processPaperlessNgxUploads] Skipping ${docType}, storageOption is not paperless.`);
+ }
+ }
+
+ return uploads;
+}
+
+/**
+ * Handle warranty edit form submission with Paperless-ngx integration
+ * This extends the existing edit warranty functionality
+ */
+async function processEditPaperlessNgxUploads(formData) {
+ if (!paperlessNgxEnabled) {
+ return {}; // Return empty object if not enabled
+ }
+
+ const uploads = {};
+ // Only process invoice and manual for Paperless-ngx uploads
+ const documentTypes = ['invoice', 'manual'];
+
+ for (const docType of documentTypes) {
+ const storageOption = getStorageOption(docType, true); // true for edit modal
+
+ if (storageOption === 'paperless') {
+ const fileInput = document.getElementById(`edit${docType.charAt(0).toUpperCase() + docType.slice(1)}`);
+ const file = fileInput?.files[0];
+
+ if (file) {
+ console.log(`[Paperless-ngx] Uploading ${docType} to Paperless-ngx (edit mode)`);
+
+ // Upload to Paperless-ngx
+ const uploadResult = await uploadToPaperlessNgx(file, docType);
+
+ if (uploadResult.success || (uploadResult.error && uploadResult.error.includes("duplicate") && uploadResult.document_id)) {
+ // Map frontend document types to database column names
+ const fieldMapping = {
+ 'productPhoto': 'paperless_photo_id',
+ 'invoice': 'paperless_invoice_id',
+ 'manual': 'paperless_manual_id',
+ 'otherDocument': 'paperless_other_id'
+ };
+
+ const dbField = fieldMapping[docType];
+ if (dbField && uploadResult.document_id) {
+ uploads[dbField] = uploadResult.document_id;
+ console.log(`[Paperless-ngx] ${docType} uploaded/linked successfully (edit), ID: ${uploadResult.document_id}, stored as: ${dbField}`);
+ // Hide loading screen immediately for direct uploads
+ hidePaperlessUploadLoading();
+ if (uploadResult.error && uploadResult.error.includes("duplicate")) {
+ showToast("Duplicate document detected in Paperless-ngx. Linked to existing document.", 'info');
+ }
+ } else if (dbField && !uploadResult.document_id) {
+ console.log(`[Paperless-ngx] ${docType} uploaded successfully (edit) but no document ID received (async processing). Not storing reference.`);
+ // Don't hide loading screen yet - auto-link will handle it
+ updatePaperlessUploadStatus('Document processing, searching for link...', true);
+ }
+
+ // ALWAYS remove the file from FormData since it's been uploaded to Paperless-ngx
+ // This prevents the backend from also saving it locally
+ // Note: In edit mode, the form field names don't have 'edit' prefix in FormData
+ if (formData.has(docType)) {
+ formData.delete(docType);
+ console.log(`[Paperless-ngx] Removed ${docType} from FormData to prevent local storage`);
+ }
+ } else {
+ throw new Error(`Failed to upload ${docType} to Paperless-ngx: ${uploadResult.error}`);
+ }
+ }
+ }
+ }
+
+ return uploads;
+}
+
+// Initialize Paperless-ngx integration when the page loads
+document.addEventListener('DOMContentLoaded', function() {
+ // Initialize after a short delay to ensure other components are loaded
+ setTimeout(() => {
+ initPaperlessNgxIntegration();
+ }, 1000);
+});
+
+/**
+ * Debug Paperless-ngx configuration
+ */
+async function debugPaperlessConfiguration() {
+ try {
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('[Paperless Debug] No auth token found');
+ return null;
+ }
+
+ console.log('[Paperless Debug] Checking configuration...');
+
+ const response = await fetch('/api/paperless/debug', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ console.error('[Paperless Debug] Debug endpoint failed:', response.status, response.statusText);
+ const errorText = await response.text();
+ console.error('[Paperless Debug] Error response:', errorText);
+ return null;
+ }
+
+ const result = await response.json();
+ console.log('[Paperless Debug] Configuration:', result);
+
+ return result;
+ } catch (error) {
+ console.error('[Paperless Debug] Error:', error);
+ return null;
+ }
+}
+
+/**
+ * Open a Paperless-ngx document either in Warracker interface or in Paperless-ngx directly
+ */
+async function openPaperlessDocument(paperlessId) {
+ console.log(`[openPaperlessDocument] Opening Paperless document: ${paperlessId}`);
+
+ // First, debug the Paperless configuration
+ const debugInfo = await debugPaperlessConfiguration();
+ if (debugInfo) {
+ console.log('[openPaperlessDocument] Debug info:', debugInfo);
+
+ if (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false') {
+ showToast('Paperless-ngx integration is not enabled', 'error');
+ return;
+ }
+
+ if (!debugInfo.paperless_handler_available) {
+ showToast('Paperless-ngx is not properly configured. Please check the settings.', 'error');
+ console.error('[openPaperlessDocument] Paperless handler not available');
+ if (debugInfo.paperless_handler_error) {
+ console.error('[openPaperlessDocument] Handler error:', debugInfo.paperless_handler_error);
+ }
+ return;
+ }
+
+ if (debugInfo.test_connection_result && !debugInfo.test_connection_result.success) {
+ showToast(`Paperless-ngx connection failed: ${debugInfo.test_connection_result.message || debugInfo.test_connection_result.error}`, 'error');
+ return;
+ }
+ }
+
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('[openPaperlessDocument] No auth token available');
+ showToast('Authentication required', 'error');
+ return;
+ }
+
+ // Check user preference for viewing documents
+ const viewInApp = await getUserPaperlessViewPreference();
+ console.log(`[openPaperlessDocument] User preference view in app: ${viewInApp}`);
+
+ if (viewInApp) {
+ // Open document in Warracker interface
+ console.log(`[openPaperlessDocument] Opening document ${paperlessId} in Warracker interface`);
+ const documentUrl = `/api/paperless-file/${paperlessId}?token=${encodeURIComponent(token)}`;
+
+ const newTab = window.open(documentUrl, '_blank');
+ if (!newTab) {
+ showToast('Please allow popups to view documents', 'warning');
+ } else {
+ showToast('Opening document in Warracker...', 'info');
+ }
+ return;
+ }
+
+ // Default behavior: open in Paperless-ngx interface
+ try {
+ // Get the Paperless-ngx base URL
+ const response = await fetch('/api/paperless/url', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ console.error('[openPaperlessDocument] URL endpoint failed:', response.status, errorText);
+ throw new Error(`Failed to get Paperless-ngx URL: ${response.status}`);
+ }
+
+ const result = await response.json();
+ if (!result.success) {
+ throw new Error(result.message || 'Failed to get Paperless-ngx URL');
+ }
+
+ // Construct the direct link to the document in Paperless-ngx
+ const paperlessUrl = result.url.replace(/\/$/, ''); // Remove trailing slash
+ const documentUrl = `${paperlessUrl}/documents/${paperlessId}/details`;
+
+ console.log(`[openPaperlessDocument] Opening Paperless-ngx document at: ${documentUrl}`);
+
+ // Open the document directly in Paperless-ngx interface
+ const newTab = window.open(documentUrl, '_blank');
+ if (!newTab) {
+ showToast('Please allow popups to view documents in Paperless-ngx', 'warning');
+ } else {
+ showToast('Opening document in Paperless-ngx...', 'info');
+ }
+
+ } catch (error) {
+ console.error('Error opening Paperless document:', error);
+ showToast(`Error opening document: ${error.message}`, 'error');
+
+ // Try to determine the base URL from debug info for fallback
+ if (debugInfo && debugInfo.paperless_url) {
+ const fallbackUrl = `${debugInfo.paperless_url.replace(/\/$/, '')}/documents/${paperlessId}/details`;
+ console.log(`[openPaperlessDocument] Trying fallback URL: ${fallbackUrl}`);
+
+ const fallbackTab = window.open(fallbackUrl, '_blank');
+ if (fallbackTab) {
+ showToast('Opened with fallback URL - please check if Paperless-ngx is accessible', 'warning');
+ }
+ } else {
+ // Last resort fallback
+ const genericFallbackUrl = `${window.location.protocol}//${window.location.hostname}:8000/documents/${paperlessId}/details`;
+ console.log(`[openPaperlessDocument] Trying generic fallback URL: ${genericFallbackUrl}`);
+
+ const genericTab = window.open(genericFallbackUrl, '_blank');
+ if (genericTab) {
+ showToast('Opened with generic fallback URL', 'warning');
+ }
+ }
+ }
+}
+
+/**
+ * Get user preference for viewing Paperless documents in app
+ */
+async function getUserPaperlessViewPreference() {
+ // First check localStorage
+ const prefix = getPreferenceKeyPrefix();
+ const localPreference = localStorage.getItem(`${prefix}paperlessViewInApp`);
+ if (localPreference !== null) {
+ return localPreference === 'true';
+ }
+
+ // If not in localStorage, check API
+ if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
+ try {
+ const response = await fetch('/api/auth/preferences', {
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ });
+ if (response.ok) {
+ const prefs = await response.json();
+ return prefs.paperless_view_in_app || false;
+ }
+ } catch (e) {
+ console.warn('Failed to load preferences from API:', e);
+ }
+ }
+
+ // Default to false (open in Paperless-ngx)
+ return false;
+}
+
+/**
+ * Debug function to test Paperless document status
+ */
+async function debugPaperlessDocument(paperlessId) {
+ console.log(`[debugPaperlessDocument] Debugging Paperless document: ${paperlessId}`);
+
+ const token = auth.getToken();
+ if (!token) {
+ console.error('[debugPaperlessDocument] No auth token available');
+ return;
+ }
+
+ try {
+ const response = await fetch(`/api/paperless/debug-document/${paperlessId}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ console.error(`[debugPaperlessDocument] HTTP ${response.status}: ${errorText}`);
+ return;
+ }
+
+ const debugInfo = await response.json();
+ console.log(`[debugPaperlessDocument] Debug info for document ${paperlessId}:`, debugInfo);
+
+ // Show debug info in a more readable format
+ let debugMessage = `Debug info for Paperless document ${paperlessId}:\n\n`;
+ debugMessage += `Document exists: ${debugInfo.document_exists}\n`;
+ debugMessage += `Database references: ${debugInfo.database_references?.length || 0}\n\n`;
+
+ debugMessage += 'Endpoint test results:\n';
+ for (const [endpoint, result] of Object.entries(debugInfo.endpoints_tested || {})) {
+ debugMessage += `- ${endpoint}: ${result.success ? 'SUCCESS' : 'FAILED'} (${result.status_code || result.error})\n`;
+ }
+
+ if (debugInfo.recent_documents && Array.isArray(debugInfo.recent_documents)) {
+ debugMessage += `\nDocument in recent list: ${debugInfo.document_in_recent}\n`;
+ debugMessage += `Recent documents: ${debugInfo.recent_documents.map(d => `${d.id}: ${d.title}`).join(', ')}\n`;
+ }
+
+ alert(debugMessage);
+
+ } catch (error) {
+ console.error('Error debugging Paperless document:', error);
+ alert(`Debug failed: ${error.message}`);
+ }
+}
+
+/**
+ * Clean up invalid Paperless-ngx document references
+ */
+async function cleanupInvalidPaperlessDocuments() {
+ console.log('[cleanupInvalidPaperlessDocuments] Starting cleanup...');
+
+ const token = auth.getToken();
+ if (!token) {
+ console.error('[cleanupInvalidPaperlessDocuments] No auth token available');
+ return;
+ }
+
+ try {
+ const response = await fetch('/api/paperless/cleanup-invalid', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ console.error(`[cleanupInvalidPaperlessDocuments] HTTP ${response.status}: ${errorText}`);
+ return;
+ }
+
+ const result = await response.json();
+ console.log('[cleanupInvalidPaperlessDocuments] Cleanup result:', result);
+
+ // Show result to user
+ let message = result.message || 'Cleanup completed';
+ if (result.details) {
+ message += `\n\nDetails:\n`;
+ message += `- Documents checked: ${result.details.checked}\n`;
+ message += `- Invalid documents found: ${result.details.invalid_found}\n`;
+ message += `- References cleaned up: ${result.details.cleaned_up}\n`;
+
+ if (result.details.errors && result.details.errors.length > 0) {
+ message += `\nErrors:\n${result.details.errors.join('\n')}`;
+ }
+ }
+
+ alert(message);
+
+ // Reload warranties to reflect changes
+ if (result.details && result.details.cleaned_up > 0) {
+ console.log('[cleanupInvalidPaperlessDocuments] Reloading warranties after cleanup...');
+ await loadWarranties(true);
+ }
+
+ } catch (error) {
+ console.error('Error cleaning up Paperless documents:', error);
+ alert(`Cleanup failed: ${error.message}`);
+ }
+}
+
+/**
+ * Search for and link a Paperless document by title
+ * Used when documents were uploaded with async processing and we lost the document ID
+ */
+async function searchAndLinkPaperlessDocument(warrantyId, documentType, searchTitle) {
+ try {
+ console.log(`[Paperless-ngx] Searching for document: ${searchTitle}`);
+
+ const response = await fetch('/api/paperless-search-and-link', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
+ },
+ body: JSON.stringify({
+ warranty_id: warrantyId,
+ document_type: documentType,
+ search_title: searchTitle
+ })
+ });
+
+ const result = await response.json();
+
+ if (result.success) {
+ console.log(`[Paperless-ngx] Document linked successfully: ID ${result.document_id}`);
+ showToast('Document linked successfully! Refreshing...', 'success');
+
+ // Reload warranties to show the updated document links
+ setTimeout(async () => {
+ console.log('🔄 [Search&Link] Reloading warranties to show updated document links...');
+ await loadWarranties(true); // Pass isAuthenticated parameter
+
+ // Force re-render of the warranty cards
+ applyFilters();
+
+ // Also reload secure images to update cloud icons
+ await loadSecureImages();
+
+ console.log('✅ [Search&Link] Warranties reloaded and UI updated');
+ }, 1000);
+
+ return { success: true, document_id: result.document_id };
+ } else {
+ console.error(`[Paperless-ngx] Failed to link document: ${result.message}`);
+ showToast(`Failed to link document: ${result.message}`, 'error');
+ return { success: false, message: result.message };
+ }
+ } catch (error) {
+ console.error(`[Paperless-ngx] Error searching for document:`, error);
+ showToast('Error searching for document', 'error');
+ return { success: false, message: error.message };
+ }
+}
+
+/**
+ * Automatically search for and link recently uploaded documents
+ * This handles the case where Paperless-ngx async processing returns task_id instead of document_id
+ */
+async function autoLinkRecentDocuments(warrantyId, documentTypes = ['invoice', 'manual'], maxRetries = 10, retryDelay = 10000, fileInfo = {}) {
+ console.log(`[Auto-Link] Starting automatic document linking for warranty ${warrantyId}`);
+
+ const token = auth.getToken();
+ if (!token) {
+ console.error('[Auto-Link] No auth token available');
+ return;
+ }
+
+ let attempt = 0;
+ let linkedDocuments = [];
+
+ const tryLinking = async () => {
+ attempt++;
+ console.log(`[Auto-Link] Attempt ${attempt}/${maxRetries} for warranty ${warrantyId}`);
+
+ try {
+ // First check if Paperless-ngx is properly configured
+ const debugInfo = await debugPaperlessConfiguration();
+ if (!debugInfo) {
+ console.error('[Auto-Link] Could not get Paperless debug info');
+ return;
+ }
+
+ if (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false') {
+ console.log('[Auto-Link] Paperless-ngx integration is not enabled, skipping auto-link');
+ return;
+ }
+
+ if (!debugInfo.paperless_handler_available) {
+ console.error('[Auto-Link] Paperless handler not available:', debugInfo.paperless_handler_error || 'Unknown error');
+ return;
+ }
+
+ if (debugInfo.test_connection_result && !debugInfo.test_connection_result.success) {
+ console.error('[Auto-Link] Paperless connection test failed:', debugInfo.test_connection_result.message || debugInfo.test_connection_result.error);
+ return;
+ }
+
+ console.log(`[Auto-Link] Using intelligent filename-based search. File info:`, fileInfo);
+
+ // Strategy 1: Search by exact filename (most reliable)
+ let candidateDocuments = [];
+
+ for (const [docType, filename] of Object.entries(fileInfo)) {
+ if (!documentTypes.includes(docType)) continue;
+
+ console.log(`[Auto-Link] Searching for ${docType} with filename: "${filename}"`);
+
+ // Remove file extension for searching
+ const baseFilename = filename.replace(/\.[^/.]+$/, '');
+
+ // Try multiple search strategies
+ const searchQueries = [
+ filename, // Exact filename with extension
+ baseFilename, // Filename without extension
+ `"${filename}"`, // Quoted exact match
+ `"${baseFilename}"`, // Quoted base filename
+ `Warracker ${docType} - ${baseFilename}` // Warracker format
+ ];
+
+ for (const query of searchQueries) {
+ try {
+ console.log(`[Auto-Link] Trying search query: "${query}"`);
+
+ const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(query)}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.ok) {
+ const result = await response.json();
+ const docs = result.results || [];
+
+ console.log(`[Auto-Link] Query "${query}" found ${docs.length} documents`);
+
+ if (docs.length > 0) {
+ // Filter for recent documents (last 24 hours)
+ const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
+ const recentDocs = docs.filter(doc => {
+ try {
+ const docDate = new Date(doc.created);
+ return docDate > oneDayAgo;
+ } catch {
+ return true; // Include if we can't parse the date
+ }
+ });
+
+ if (recentDocs.length > 0) {
+ console.log(`[Auto-Link] Found ${recentDocs.length} recent documents for ${docType}`);
+ candidateDocuments.push({
+ docType,
+ filename,
+ documents: recentDocs,
+ searchQuery: query
+ });
+ break; // Found documents, no need to try other queries for this file
+ } else if (docs.length > 0) {
+ // If no recent docs but we found some documents, include them anyway
+ console.log(`[Auto-Link] Found ${docs.length} older documents for ${docType}, including them anyway`);
+ candidateDocuments.push({
+ docType,
+ filename,
+ documents: docs.slice(0, 3), // Take up to 3 most recent
+ searchQuery: query
+ });
+ break;
+ }
+ }
+ }
+ } catch (error) {
+ console.error(`[Auto-Link] Error searching with query "${query}":`, error);
+ }
+ }
+ }
+
+ // Strategy 2: Fallback to Warracker tag search if filename search fails
+ if (candidateDocuments.length === 0) {
+ console.log('[Auto-Link] No documents found by filename, trying Warracker tag search...');
+
+ const response = await fetch('/api/paperless/search?ordering=-created&created__gte=' +
+ new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.ok) {
+ const searchResult = await response.json();
+ let recentDocs = searchResult.results || [];
+
+ // Filter for Warracker documents
+ const warrackerDocs = recentDocs.filter(doc =>
+ doc.title && doc.title.includes('Warracker')
+ );
+
+ console.log(`[Auto-Link] Found ${warrackerDocs.length} Warracker documents from last 2 hours`);
+
+ // Group by document type
+ for (const docType of documentTypes) {
+ const typeDocs = warrackerDocs.filter(doc =>
+ doc.title && doc.title.includes(docType)
+ );
+
+ if (typeDocs.length > 0) {
+ candidateDocuments.push({
+ docType,
+ filename: fileInfo[docType] || `${docType} document`,
+ documents: typeDocs,
+ searchQuery: `Warracker ${docType}`
+ });
+ }
+ }
+ }
+ }
+
+ // Debug: Show what candidate documents we found
+ if (candidateDocuments.length > 0) {
+ console.log('[Auto-Link] Candidate documents found:');
+ candidateDocuments.forEach(candidate => {
+ console.log(` ${candidate.docType}: ${candidate.documents.length} documents found with query "${candidate.searchQuery}"`);
+ candidate.documents.forEach((doc, i) => {
+ console.log(` ${i+1}. ID: ${doc.id}, Title: "${doc.title}", Created: ${doc.created}`);
+ });
+ });
+ }
+
+ // Try to link the best candidate for each document type
+ for (const candidate of candidateDocuments) {
+ // Use the most recent document (first in the ordered list)
+ const doc = candidate.documents[0];
+
+ console.log(`[Auto-Link] Attempting to link ${candidate.docType}: ${doc.title} (ID: ${doc.id})`);
+
+ try {
+ const linkResponse = await fetch('/api/paperless-search-and-link', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
+ },
+ body: JSON.stringify({
+ warranty_id: warrantyId,
+ document_type: candidate.docType,
+ search_title: doc.title.replace('Warracker ' + candidate.docType + ' - ', '')
+ })
+ });
+
+ const linkResult = await linkResponse.json();
+
+ if (linkResult.success) {
+ console.log(`[Auto-Link] Successfully linked ${candidate.docType}: ${doc.title}`);
+ linkedDocuments.push({
+ type: candidate.docType,
+ title: doc.title,
+ id: doc.id,
+ filename: candidate.filename
+ });
+ } else {
+ console.log(`[Auto-Link] Failed to link ${candidate.docType}: ${linkResult.message}`);
+ }
+ } catch (error) {
+ console.error(`[Auto-Link] Error linking ${candidate.docType}:`, error);
+ }
+ }
+
+ // If we found and linked documents, we're done
+ if (linkedDocuments.length > 0) {
+ console.log(`[Auto-Link] Successfully linked ${linkedDocuments.length} documents:`, linkedDocuments);
+
+ // Update loading screen to show success
+ updatePaperlessUploadStatus('Documents linked successfully!');
+
+ // Show success message with filenames
+ const docInfo = linkedDocuments.map(d => `${d.type} (${d.filename || d.title})`).join(', ');
+ showToast(`Automatically linked ${linkedDocuments.length} document(s): ${docInfo}`, 'success');
+
+ // Reload warranties to show the updated document links
+ setTimeout(async () => {
+ console.log('🔄 [Auto-Link] Reloading warranties to show updated document links...');
+ await loadWarranties(true); // Pass isAuthenticated parameter
+
+ // Force re-render of the warranty cards
+ applyFilters();
+
+ // Also reload secure images to update cloud icons
+ await loadSecureImages();
+
+ console.log('✅ [Auto-Link] Warranties reloaded and UI updated');
+
+ // Hide loading screen after successful completion
+ hidePaperlessUploadLoading();
+ }, 1000);
+
+ return true;
+ }
+
+ // If no documents found and we have retries left, try again
+ if (attempt < maxRetries) {
+ console.log(`[Auto-Link] No documents found, retrying in ${retryDelay}ms...`);
+ updatePaperlessUploadStatus(`Searching for documents (attempt ${attempt + 1}/${maxRetries})...`, true);
+ setTimeout(tryLinking, retryDelay);
+ } else {
+ console.log(`[Auto-Link] No documents found after ${maxRetries} attempts`);
+ updatePaperlessUploadStatus('Document uploaded but could not auto-link');
+ showToast('Document uploaded to Paperless-ngx but could not be automatically linked. You can manually link it later.', 'warning');
+ // Hide loading screen after failed auto-link
+ setTimeout(() => {
+ hidePaperlessUploadLoading();
+ }, 2000);
+ }
+
+ } catch (error) {
+ console.error(`[Auto-Link] Error in attempt ${attempt}:`, error);
+
+ if (attempt < maxRetries) {
+ console.log(`[Auto-Link] Retrying in ${retryDelay}ms...`);
+ updatePaperlessUploadStatus(`Error occurred, retrying (${attempt + 1}/${maxRetries})...`, true);
+ setTimeout(tryLinking, retryDelay);
+ } else {
+ updatePaperlessUploadStatus('Upload completed with errors');
+ showToast('Document uploaded but auto-linking failed due to errors. You can manually link it later.', 'warning');
+ // Hide loading screen after final error
+ setTimeout(() => {
+ hidePaperlessUploadLoading();
+ }, 2000);
+ }
+ }
+ };
+
+ // Start the linking process
+ tryLinking();
+}
+
+// Make debug and cleanup functions available globally for console testing
+window.debugPaperlessDocument = debugPaperlessDocument;
+window.cleanupInvalidPaperlessDocuments = cleanupInvalidPaperlessDocuments;
+window.searchAndLinkPaperlessDocument = searchAndLinkPaperlessDocument;
+window.autoLinkRecentDocuments = autoLinkRecentDocuments;
+
+// Helper function to manually link a specific document by title
+window.manualLinkDocument = async function(warrantyId, documentType, titleSearchTerm) {
+ console.log(`🔗 Manually linking document for warranty ${warrantyId}`);
+ console.log(` Document type: ${documentType}`);
+ console.log(` Searching for title containing: "${titleSearchTerm}"`);
+
+ const token = auth.getToken();
+ if (!token) {
+ console.error('❌ No auth token available');
+ return;
+ }
+
+ try {
+ // Search for documents containing the search term
+ const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(titleSearchTerm)}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ console.error(`❌ Search failed: ${response.status}`);
+ return;
+ }
+
+ const result = await response.json();
+ const docs = result.results || [];
+
+ console.log(`📄 Found ${docs.length} documents matching "${titleSearchTerm}"`);
+
+ if (docs.length === 0) {
+ console.log('❌ No documents found. The document might still be processing in Paperless-ngx.');
+ return;
+ }
+
+ // Show all matching documents
+ docs.forEach((doc, index) => {
+ console.log(` ${index + 1}. ID: ${doc.id}, Title: "${doc.title}", Created: ${doc.created}`);
+ });
+
+ // Try to link the first matching document
+ const docToLink = docs[0];
+ console.log(`🔗 Attempting to link document ID ${docToLink.id}: "${docToLink.title}"`);
+
+ const linkResponse = await fetch('/api/paperless-search-and-link', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${token}`
+ },
+ body: JSON.stringify({
+ warranty_id: warrantyId,
+ document_type: documentType,
+ search_title: docToLink.title.replace('Warracker ' + documentType + ' - ', '')
+ })
+ });
+
+ const linkResult = await linkResponse.json();
+
+ if (linkResult.success) {
+ console.log(`✅ Successfully linked ${documentType}: ${docToLink.title}`);
+ showToast(`Document linked successfully: ${documentType}`, 'success');
+
+ // Reload warranties to show the updated document links
+ setTimeout(async () => {
+ console.log('🔄 Reloading warranties to show updated document links...');
+ await loadWarranties(true); // Pass isAuthenticated parameter
+
+ // Force re-render of the warranty cards
+ applyFilters();
+
+ // Also reload secure images to update cloud icons
+ await loadSecureImages();
+
+ console.log('✅ Warranties reloaded and UI updated');
+ }, 1000);
+ } else {
+ console.error(`❌ Failed to link ${documentType}: ${linkResult.message}`);
+ }
+
+ return docToLink;
+
+ } catch (error) {
+ console.error('❌ Error in manual linking:', error);
+ }
+};
+
+// Helper function to search for documents in Paperless-ngx (debug function)
+window.debugSearchPaperlessDocuments = async function(searchTerm = 'Warracker', limit = 10) {
+ console.log(`🔍 Searching for documents containing: "${searchTerm}"`);
+
+ const token = auth.getToken();
+ if (!token) {
+ console.error('❌ No auth token available');
+ return;
+ }
+
+ try {
+ const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(searchTerm)}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ console.error(`❌ Search failed: ${response.status}`);
+ return;
+ }
+
+ const result = await response.json();
+ const docs = result.results || [];
+
+ console.log(`📄 Found ${docs.length} documents:`);
+ docs.slice(0, limit).forEach((doc, index) => {
+ console.log(` ${index + 1}. ID: ${doc.id}, Title: "${doc.title}", Created: ${doc.created}`);
+ });
+
+ if (docs.length > limit) {
+ console.log(` ... and ${docs.length - limit} more documents`);
+ }
+
+ return docs;
+ } catch (error) {
+ console.error('❌ Error searching documents:', error);
+ }
+};
+
+// Helper function for users to debug Paperless-ngx configuration
+window.debugPaperlessSetup = async function() {
+ console.log('🔍 Debugging Paperless-ngx setup...');
+
+ const debugInfo = await debugPaperlessConfiguration();
+ if (!debugInfo) {
+ console.error('❌ Could not get debug information');
+ return;
+ }
+
+ console.log('📋 Paperless-ngx Configuration:');
+ console.log(` Enabled: ${debugInfo.paperless_enabled}`);
+ console.log(` URL: ${debugInfo.paperless_url || 'Not set'}`);
+ console.log(` API Token Set: ${debugInfo.paperless_api_token_set}`);
+ console.log(` Handler Available: ${debugInfo.paperless_handler_available}`);
+
+ if (debugInfo.paperless_handler_error) {
+ console.error(` Handler Error: ${debugInfo.paperless_handler_error}`);
+ }
+
+ if (debugInfo.test_connection_result) {
+ console.log(` Connection Test: ${debugInfo.test_connection_result.success ? '✅ Success' : '❌ Failed'}`);
+ console.log(` Message: ${debugInfo.test_connection_result.message || debugInfo.test_connection_result.error}`);
+ }
+
+ // Provide recommendations
+ console.log('\n💡 Recommendations:');
+
+ if (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false') {
+ console.log(' - Enable Paperless-ngx integration in Settings');
+ }
+
+ if (!debugInfo.paperless_url) {
+ console.log(' - Set Paperless-ngx URL in Settings (e.g., http://paperless:8000)');
+ }
+
+ if (!debugInfo.paperless_api_token_set) {
+ console.log(' - Set API token in Settings (generate from Paperless-ngx → Settings → API Tokens)');
+ }
+
+ if (debugInfo.test_connection_result && !debugInfo.test_connection_result.success) {
+ console.log(' - Check if Paperless-ngx is running and accessible');
+ console.log(' - Verify URL and API token are correct');
+ console.log(' - Check network connectivity between Warracker and Paperless-ngx');
+ }
+
+ return debugInfo;
+};
+
+// ===== PAPERLESS DOCUMENT BROWSER FUNCTIONALITY =====
+
+// Global variables for paperless browser
+let currentPaperlessDocuments = [];
+let selectedPaperlessDocument = null;
+let currentPaperlessPage = 1;
+let totalPaperlessPages = 1;
+let currentDocumentType = '';
+let paperlessSearchQuery = '';
+
+/**
+ * Open the Paperless document browser modal
+ * @param {string} documentType - Type of document being selected (invoice, manual, product_photo, other_document)
+ */
+function openPaperlessBrowser(documentType) {
+ currentDocumentType = documentType;
+ selectedPaperlessDocument = null;
+
+ // Reset pagination state
+ currentPaperlessPage = 1;
+ totalPaperlessPages = 1;
+ paperlessSearchQuery = '';
+
+ // Show the modal
+ const modal = document.getElementById('paperlessBrowserModal');
+ modal.classList.add('active');
+
+ // Reset search and filters
+ document.getElementById('paperlessSearchInput').value = '';
+ document.getElementById('paperlessTypeFilter').value = '';
+ document.getElementById('paperlessTagFilter').value = '';
+
+ // Load documents
+ loadAllPaperlessDocuments();
+
+ // Load tags for filter
+ loadPaperlessTags();
+
+ // Hide select button initially
+ const selectBtn = document.getElementById('selectPaperlessDocBtn');
+ if (selectBtn) {
+ selectBtn.style.display = 'none';
+ }
+}
+
+/**
+ * Load all Paperless documents
+ */
+async function loadAllPaperlessDocuments() {
+ try {
+ showPaperlessLoading();
+
+ const params = new URLSearchParams();
+ const offset = (currentPaperlessPage - 1) * 25;
+ params.append('limit', '25');
+ params.append('offset', offset.toString());
+
+ const response = await fetch(`/api/paperless/search?${params.toString()}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ const data = await response.json();
+ currentPaperlessDocuments = data.results || [];
+ totalPaperlessPages = Math.ceil(data.count / 25) || 1;
+
+ renderPaperlessDocuments();
+ updatePaperlessPagination();
+
+ } catch (error) {
+ console.error('Error loading Paperless documents:', error);
+ showPaperlessError('Failed to load documents from Paperless-ngx');
+ }
+}
+
+/**
+ * Search Paperless documents
+ */
+async function searchPaperlessDocuments() {
+ const searchInput = document.getElementById('paperlessSearchInput');
+ const typeFilter = document.getElementById('paperlessTypeFilter');
+ const tagFilter = document.getElementById('paperlessTagFilter');
+
+ paperlessSearchQuery = searchInput.value.trim();
+
+ try {
+ showPaperlessLoading();
+
+ const params = new URLSearchParams();
+ if (paperlessSearchQuery) {
+ params.append('query', paperlessSearchQuery);
+ }
+ if (typeFilter.value) {
+ params.append('document_type', typeFilter.value);
+ }
+ if (tagFilter.value) {
+ params.append('tags__id__in', tagFilter.value);
+ }
+
+ // Add pagination
+ const offset = (currentPaperlessPage - 1) * 25;
+ params.append('limit', '25');
+ params.append('offset', offset.toString());
+
+ const response = await fetch(`/api/paperless/search?${params.toString()}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ const data = await response.json();
+ currentPaperlessDocuments = data.results || [];
+ totalPaperlessPages = Math.ceil(data.count / 25) || 1;
+
+ renderPaperlessDocuments();
+ updatePaperlessPagination();
+
+ } catch (error) {
+ console.error('Error searching Paperless documents:', error);
+ showPaperlessError('Failed to search documents');
+ }
+}
+
+/**
+ * Load Paperless tags for filter dropdown
+ */
+async function loadPaperlessTags() {
+ try {
+ const response = await fetch('/api/paperless/tags', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ const tagFilter = document.getElementById('paperlessTagFilter');
+
+ // Clear existing options except the first one
+ tagFilter.innerHTML = '<option value="">All Tags</option>';
+
+ // Add tag options
+ if (data.results) {
+ data.results.forEach(tag => {
+ const option = document.createElement('option');
+ option.value = tag.id;
+ option.textContent = tag.name;
+ tagFilter.appendChild(option);
+ });
+ }
+ }
+ } catch (error) {
+ console.error('Error loading Paperless tags:', error);
+ }
+}
+
+/**
+ * Render the list of Paperless documents
+ */
+function renderPaperlessDocuments() {
+ const container = document.getElementById('paperlessDocumentsList');
+
+ if (currentPaperlessDocuments.length === 0) {
+ container.innerHTML = `
+ <div class="no-documents-message">
+ <i class="fas fa-file-alt"></i>
+ <h4>No documents found</h4>
+ <p>Try adjusting your search terms or filters.</p>
+ </div>
+ `;
+ return;
+ }
+
+ const documentsHtml = currentPaperlessDocuments.map(doc => {
+ const createdDate = new Date(doc.created).toLocaleDateString();
+ const fileType = doc.mime_type || 'Unknown';
+ const tags = doc.tags || [];
+
+ return `
+ <div class="paperless-document-item" data-id="${doc.id}" onclick="selectPaperlessDocument(${doc.id})">
+ <div class="document-title">${escapeHtml(doc.title)}</div>
+ <div class="document-meta">
+ <span><i class="fas fa-calendar"></i> ${createdDate}</span>
+ <span><i class="fas fa-file"></i> ${fileType}</span>
+ ${doc.correspondent ? `<span><i class="fas fa-user"></i> ${escapeHtml(doc.correspondent)}</span>` : ''}
+ </div>
+ ${tags.length > 0 ? `
+ <div class="document-tags">
+ ${tags.map(tag => `<span class="document-tag">${escapeHtml(tag)}</span>`).join('')}
+ </div>
+ ` : ''}
+ </div>
+ `;
+ }).join('');
+
+ container.innerHTML = documentsHtml;
+}
+
+/**
+ * Select a Paperless document
+ * @param {number} documentId - ID of the document to select
+ */
+function selectPaperlessDocument(documentId) {
+ // Remove previous selection
+ document.querySelectorAll('.paperless-document-item').forEach(item => {
+ item.classList.remove('selected');
+ });
+
+ // Add selection to clicked item
+ const selectedItem = document.querySelector(`[data-id="${documentId}"]`);
+ if (selectedItem) {
+ selectedItem.classList.add('selected');
+ selectedPaperlessDocument = currentPaperlessDocuments.find(doc => doc.id === documentId);
+
+ // Show select button
+ const selectBtn = document.getElementById('selectPaperlessDocBtn');
+ selectBtn.style.display = 'inline-block';
+ selectBtn.onclick = () => confirmPaperlessSelection();
+ }
+}
+
+/**
+ * Confirm the selection of a Paperless document
+ */
+function confirmPaperlessSelection() {
+ if (!selectedPaperlessDocument) return;
+
+ // Update the UI to show the selected document
+ updatePaperlessSelectionUI();
+
+ // Close the modal
+ closePaperlessBrowser();
+}
+
+/**
+ * Update the UI to show the selected Paperless document
+ */
+function updatePaperlessSelectionUI() {
+ if (!selectedPaperlessDocument || !currentDocumentType) return;
+
+ const docName = selectedPaperlessDocument.title;
+ const docId = selectedPaperlessDocument.id;
+
+ // Map document types to their UI elements (only for invoice and manual)
+ const typeMapping = {
+ 'invoice': {
+ selectedDiv: 'selectedInvoiceFromPaperless',
+ hiddenInput: 'selectedPaperlessInvoice'
+ },
+ 'manual': {
+ selectedDiv: 'selectedManualFromPaperless',
+ hiddenInput: 'selectedPaperlessManual'
+ },
+ // Edit modal versions
+ 'edit_invoice': {
+ selectedDiv: 'selectedEditInvoiceFromPaperless',
+ hiddenInput: 'selectedEditPaperlessInvoice'
+ },
+ 'edit_manual': {
+ selectedDiv: 'selectedEditManualFromPaperless',
+ hiddenInput: 'selectedEditPaperlessManual'
+ }
+ };
+
+ const mapping = typeMapping[currentDocumentType];
+ if (!mapping) return;
+
+ // Show the selected document
+ const selectedDiv = document.getElementById(mapping.selectedDiv);
+ if (selectedDiv) {
+ selectedDiv.style.display = 'flex';
+ selectedDiv.querySelector('.selected-doc-name').textContent = docName;
+ }
+
+ // Create or update hidden input to store the document ID
+ let hiddenInput = document.getElementById(mapping.hiddenInput);
+ if (!hiddenInput) {
+ hiddenInput = document.createElement('input');
+ hiddenInput.type = 'hidden';
+ hiddenInput.id = mapping.hiddenInput;
+ hiddenInput.name = mapping.hiddenInput;
+ document.body.appendChild(hiddenInput);
+ }
+ hiddenInput.value = docId;
+}
+
+/**
+ * Clear the Paperless document selection
+ * @param {string} documentType - Type of document to clear
+ */
+function clearPaperlessSelection(documentType) {
+ const typeMapping = {
+ 'invoice': {
+ selectedDiv: 'selectedInvoiceFromPaperless',
+ hiddenInput: 'selectedPaperlessInvoice'
+ },
+ 'manual': {
+ selectedDiv: 'selectedManualFromPaperless',
+ hiddenInput: 'selectedPaperlessManual'
+ },
+ // Edit modal versions
+ 'edit_invoice': {
+ selectedDiv: 'selectedEditInvoiceFromPaperless',
+ hiddenInput: 'selectedEditPaperlessInvoice'
+ },
+ 'edit_manual': {
+ selectedDiv: 'selectedEditManualFromPaperless',
+ hiddenInput: 'selectedEditPaperlessManual'
+ }
+ };
+
+ const mapping = typeMapping[documentType];
+ if (!mapping) return;
+
+ // Hide the selected document display
+ const selectedDiv = document.getElementById(mapping.selectedDiv);
+ if (selectedDiv) {
+ selectedDiv.style.display = 'none';
+ }
+
+ // Clear the hidden input
+ const hiddenInput = document.getElementById(mapping.hiddenInput);
+ if (hiddenInput) {
+ hiddenInput.value = '';
+ }
+}
+
+/**
+ * Close the Paperless browser modal
+ */
+function closePaperlessBrowser() {
+ const modal = document.getElementById('paperlessBrowserModal');
+ modal.classList.remove('active');
+
+ // Reset state
+ selectedPaperlessDocument = null;
+ currentDocumentType = '';
+
+ // Hide select button
+ const selectBtn = document.getElementById('selectPaperlessDocBtn');
+ selectBtn.style.display = 'none';
+}
+
+/**
+ * Change page in Paperless document browser
+ * @param {number} direction - Direction to change page (-1 for previous, 1 for next)
+ */
+function changePage(direction) {
+ const newPage = currentPaperlessPage + direction;
+ if (newPage < 1 || newPage > totalPaperlessPages) return;
+
+ currentPaperlessPage = newPage;
+
+ // Check if we have any active filters
+ const searchInput = document.getElementById('paperlessSearchInput');
+ const typeFilter = document.getElementById('paperlessTypeFilter');
+ const tagFilter = document.getElementById('paperlessTagFilter');
+
+ const hasFilters = (searchInput && searchInput.value.trim()) ||
+ (typeFilter && typeFilter.value) ||
+ (tagFilter && tagFilter.value);
+
+ if (hasFilters) {
+ searchPaperlessDocuments();
+ } else {
+ loadAllPaperlessDocuments();
+ }
+}
+
+/**
+ * Update pagination controls
+ */
+function updatePaperlessPagination() {
+ const paginationDiv = document.getElementById('paperlessPagination');
+ const prevBtn = document.getElementById('prevPageBtn');
+ const nextBtn = document.getElementById('nextPageBtn');
+ const pageInfo = document.getElementById('pageInfo');
+
+ if (totalPaperlessPages <= 1) {
+ paginationDiv.style.display = 'none';
+ return;
+ }
+
+ paginationDiv.style.display = 'flex';
+ prevBtn.disabled = currentPaperlessPage <= 1;
+ nextBtn.disabled = currentPaperlessPage >= totalPaperlessPages;
+ pageInfo.textContent = `Page ${currentPaperlessPage} of ${totalPaperlessPages}`;
+}
+
+/**
+ * Show loading state in Paperless browser
+ */
+function showPaperlessLoading() {
+ const container = document.getElementById('paperlessDocumentsList');
+ container.innerHTML = `
+ <div class="loading-message" style="text-align: center; padding: 40px;">
+ <i class="fas fa-spinner fa-spin"></i> Loading documents...
+ </div>
+ `;
+}
+
+/**
+ * Show error message in Paperless browser
+ * @param {string} message - Error message to display
+ */
+function showPaperlessError(message) {
+ const container = document.getElementById('paperlessDocumentsList');
+ container.innerHTML = `
+ <div class="no-documents-message">
+ <i class="fas fa-exclamation-triangle"></i>
+ <h4>Error</h4>
+ <p>${escapeHtml(message)}</p>
+ </div>
+ `;
+}
+
+/**
+ * Show/hide Paperless browse sections based on Paperless-ngx availability
+ */
+function togglePaperlessBrowseSections() {
+ const paperlessEnabled = window.paperlessNgxEnabled || false;
+ console.log('[togglePaperlessBrowseSections] Paperless enabled:', paperlessEnabled);
+
+ // List of paperless browse section IDs (only for invoice and manual)
+ const browseSectionIds = [
+ 'invoicePaperlessBrowse',
+ 'manualPaperlessBrowse',
+ 'editInvoicePaperlessBrowse',
+ 'editManualPaperlessBrowse'
+ ];
+
+ let foundSections = 0;
+ browseSectionIds.forEach(id => {
+ const section = document.getElementById(id);
+ if (section) {
+ foundSections++;
+ section.style.display = paperlessEnabled ? 'block' : 'none';
+ console.log(`[togglePaperlessBrowseSections] ${id}: ${paperlessEnabled ? 'shown' : 'hidden'}`);
+ } else {
+ console.warn(`[togglePaperlessBrowseSections] Section not found: ${id}`);
+ }
+ });
+
+ console.log(`[togglePaperlessBrowseSections] Found ${foundSections} of ${browseSectionIds.length} sections`);
+}
+
+// Initialize Paperless browser functionality when DOM is loaded
+document.addEventListener('DOMContentLoaded', function() {
+ // Add event listeners for modal close buttons
+ const paperlessModal = document.getElementById('paperlessBrowserModal');
+ if (paperlessModal) {
+ // Close on backdrop click
+ paperlessModal.addEventListener('click', function(e) {
+ if (e.target === paperlessModal) {
+ closePaperlessBrowser();
+ }
+ });
+
+ // Close on close button click
+ const closeBtn = paperlessModal.querySelector('.close-btn');
+ if (closeBtn) {
+ closeBtn.addEventListener('click', closePaperlessBrowser);
+ }
+
+ // Close on cancel button click - but only the Cancel button, not all secondary buttons
+ const cancelBtn = paperlessModal.querySelector('.modal-footer .btn-secondary');
+ if (cancelBtn) {
+ cancelBtn.addEventListener('click', closePaperlessBrowser);
+ }
+ }
+
+ // Add event listeners for search and filters
+ const searchInput = document.getElementById('paperlessSearchInput');
+ if (searchInput) {
+ // Search on Enter key
+ searchInput.addEventListener('keypress', function(e) {
+ if (e.key === 'Enter') {
+ currentPaperlessPage = 1; // Reset to first page
+ searchPaperlessDocuments();
+ }
+ });
+
+ // Search on input change (with debounce)
+ let searchTimeout;
+ searchInput.addEventListener('input', function() {
+ clearTimeout(searchTimeout);
+ searchTimeout = setTimeout(() => {
+ currentPaperlessPage = 1; // Reset to first page
+ searchPaperlessDocuments();
+ }, 500);
+ });
+ }
+
+ // Add event listeners for filter dropdowns
+ const typeFilter = document.getElementById('paperlessTypeFilter');
+ if (typeFilter) {
+ typeFilter.addEventListener('change', function() {
+ currentPaperlessPage = 1; // Reset to first page
+ searchPaperlessDocuments();
+ });
+ }
+
+ const tagFilter = document.getElementById('paperlessTagFilter');
+ if (tagFilter) {
+ tagFilter.addEventListener('change', function() {
+ currentPaperlessPage = 1; // Reset to first page
+ searchPaperlessDocuments();
+ });
+ }
+
+ // Add event listener for search button
+ const searchBtn = document.getElementById('paperlessSearchBtn');
+ if (searchBtn) {
+ searchBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ currentPaperlessPage = 1; // Reset to first page
+ searchPaperlessDocuments();
+ });
+ }
+
+ // Add event listener for "Show All" button
+ const showAllBtn = document.getElementById('paperlessShowAllBtn');
+ if (showAllBtn) {
+ showAllBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+
+ // Clear all filters
+ if (searchInput) searchInput.value = '';
+ if (typeFilter) typeFilter.value = '';
+ if (tagFilter) tagFilter.value = '';
+
+ // Reset page and load all documents
+ currentPaperlessPage = 1;
+ paperlessSearchQuery = '';
+ loadAllPaperlessDocuments();
+ });
+ }
+
+ // Toggle browse sections will be handled by initPaperlessNgxIntegration()
+ // togglePaperlessBrowseSections();
+});
+
+// Make functions available globally
+window.openPaperlessBrowser = openPaperlessBrowser;
+window.loadAllPaperlessDocuments = loadAllPaperlessDocuments;
+window.selectPaperlessDocument = selectPaperlessDocument;
+window.clearPaperlessSelection = clearPaperlessSelection;
+window.changePage = changePage;
+window.openPaperlessDocument = openPaperlessDocument;
+window.openSecureFile = openSecureFile;
+
+// ===== END PAPERLESS BROWSER FUNCTIONALITY =====
diff --git a/frontend/settings-new.html b/frontend/settings-new.html
index ef880f4..2c69380 100644
--- a/frontend/settings-new.html
+++ b/frontend/settings-new.html
@@ -1,11 +1,11 @@
<!DOCTYPE html>
-<html lang="en">
+<html>
<head>
<!-- Authentication redirect script -->
- <script src="auth-redirect.js" data-protected="true"></script>
+ <script src="auth-redirect.js?v=20250119001" data-protected="true"></script>
<!-- Include authentication script first to handle login state immediately -->
- <script src="include-auth-new.js"></script>
+ <script src="include-auth-new.js?v=20250119001"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -17,19 +17,30 @@
<link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
<link rel="manifest" href="manifest.json">
<!-- Load the main site styles first -->
- <link rel="stylesheet" href="style.css">
+ <link rel="stylesheet" href="style.css?v=20250119001">
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Then load settings-specific styles -->
- <link rel="stylesheet" href="settings-styles.css">
+ <link rel="stylesheet" href="settings-styles.css?v=20250119001">
<!-- Apply theme immediately -->
- <script src="theme-loader.js"></script>
+ <script src="theme-loader.js?v=20250119001"></script>
<!-- Load header fix styles last to override any conflicting styles -->
- <link rel="stylesheet" href="header-fix.css">
+ <link rel="stylesheet" href="header-fix.css?v=20250119001">
<!-- Mobile Header specific styles -->
- <link rel="stylesheet" href="mobile-header.css">
+ <link rel="stylesheet" href="mobile-header.css?v=20250119001">
<!-- Load fix for auth buttons -->
- <script src="fix-auth-buttons-loader.js"></script>
+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
+
+ <!-- i18next Local Scripts -->
+ <script src="js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+
+ <!-- i18n Configuration -->
+ <script src="js/i18n.js?v=20250119001"></script>
+
+ <!-- Temporary debug script -->
+ <script src="js/i18n-debug.js?v=20250119001"></script>
<!-- Immediate authentication check script -->
<script>
@@ -93,13 +104,13 @@
</div>
<div class="nav-links">
<a href="index.html" class="nav-link">
- <i class="fas fa-home"></i> Home
+ <i class="fas fa-home"></i> <span data-i18n="nav.home">Home</span>
</a>
<a href="status.html" class="nav-link">
- <i class="fas fa-chart-pie"></i> Status
+ <i class="fas fa-chart-pie"></i> <span data-i18n="nav.status">Status</span>
</a>
<a href="settings-new.html" class="nav-link active">
- <i class="fas fa-cog"></i> Settings
+ <i class="fas fa-cog"></i> <span data-i18n="nav.settings">Settings</span>
</a>
</div>
<!-- Group for right-aligned elements -->
@@ -116,15 +127,15 @@
</div>
<div class="user-menu-item">
<a href="settings-new.html" style="color: inherit; text-decoration: none; display: block;">
- <i class="fas fa-cog"></i> Settings
+ <i class="fas fa-cog"></i> <span data-i18n="nav.settings">Settings</span>
</a>
</div>
<div class="user-menu-item">
<i class="fas fa-info-circle"></i>
- <a href="about.html" style="text-decoration: none; color: inherit;">About</a>
+ <a href="about.html" style="text-decoration: none; color: inherit;" data-i18n="nav.about">About</a>
</div>
<div class="user-menu-item" id="logoutMenuItem">
- <i class="fas fa-sign-out-alt"></i> Logout
+ <i class="fas fa-sign-out-alt"></i> <span data-i18n="auth.logout">Logout</span>
</div>
</div>
</div>
@@ -140,51 +151,81 @@
<!-- Main Content -->
<div class="container">
<div class="content-wrapper">
- <h2>Settings</h2>
+ <h2 data-i18n="settings.title">Settings</h2>
<!-- Account Settings -->
- <div class="card">
- <div class="card-header">
- <h3>Account Settings</h3>
+ <div class="card collapsible-card">
+ <div class="card-header collapsible-header" data-target="accountSettingsContent">
+ <h3 data-i18n="settings.account_settings">Account Settings</h3>
+ <i class="fas fa-chevron-down collapse-icon"></i>
</div>
- <div class="card-body">
+ <div class="card-body collapsible-content" id="accountSettingsContent">
<div id="currentUserInfoDisplay" class="current-user-info" style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid var(--border-color);">
- <p style="margin: 0; font-size: 1.1rem;"><strong>Editing Profile for:</strong> <span id="currentUserNameDisplay" style="font-weight: normal;">Loading...</span></p>
- <p style="margin: 5px 0 0 0; font-size: 0.9rem; color: var(--text-muted);">Your email: <span id="currentUserEmailDisplay">Loading...</span></p>
+ <p style="margin: 0; font-size: 1.1rem;"><strong data-i18n="settings.current_user">Editing Profile for:</strong> <span id="currentUserNameDisplay" style="font-weight: normal;">Loading...</span></p>
+ <p style="margin: 5px 0 0 0; font-size: 0.9rem; color: var(--text-muted);"><span data-i18n="settings.your_email">Your email:</span> <span id="currentUserEmailDisplay">Loading...</span></p>
</div>
<form id="profileForm">
<div class="form-group">
- <label for="firstName">First Name</label>
+ <label for="firstName" data-i18n="settings.first_name">First Name</label>
<input type="text" id="firstName" name="firstName" class="form-control">
</div>
<div class="form-group">
- <label for="lastName">Last Name</label>
+ <label for="lastName" data-i18n="settings.last_name">Last Name</label>
<input type="text" id="lastName" name="lastName" class="form-control">
</div>
<div class="form-group">
- <label for="email">Email</label>
+ <label for="email" data-i18n="settings.email">Email</label>
<input type="email" id="email" name="email" class="form-control">
</div>
- <button type="button" id="saveProfileBtn" class="btn btn-primary">Save Changes</button>
+ <button type="button" id="saveProfileBtn" class="btn btn-primary" data-i18n="settings.save_profile">Save Changes</button>
</form>
</div>
</div>
<!-- Preferences -->
- <div class="card">
- <div class="card-header">
- <h3>Preferences</h3>
+ <div class="card collapsible-card">
+ <div class="card-header collapsible-header" data-target="preferencesContent">
+ <h3 data-i18n="settings.preferences">Preferences</h3>
+ <i class="fas fa-chevron-down collapse-icon"></i>
</div>
- <div class="card-body">
+ <div class="card-body collapsible-content" id="preferencesContent">
<form id="preferencesForm">
<div class="form-group">
<div class="preference-item">
<div>
- <label>Dark Mode</label>
- <p class="text-muted">Switch between light and dark theme</p>
+ <label data-i18n="settings.language">Language</label>
+ <p class="text-muted" data-i18n="settings.select_language">Select your preferred language</p>
+ </div>
+ <select id="languageSelect" class="form-control" style="max-width: 200px;">
+ <option value="en">English</option>
+ <option value="fr">Français</option>
+ <option value="es">Español</option>
+ <option value="de">Deutsch</option>
+ <option value="it">Italiano</option>
+ <option value="cs">Čeština</option>
+ <option value="nl">Nederlands</option>
+ <option value="hi">हिन्दी</option>
+ <option value="fa">فارسی</option>
+ <option value="ar">العربية</option>
+ <option value="ru">Русский</option>
+ <option value="uk">Українська</option>
+ <option value="zh_CN">简体中文</option>
+ <option value="zh_HK">繁體中文</option>
+ <option value="ja">日本語</option>
+ <option value="pt">Português</option>
+ <option value="ko">한국어</option>
+ </select>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.dark_mode">Dark Mode</label>
+ <p class="text-muted" data-i18n="settings.dark_mode_desc">Switch between light and dark theme</p>
</div>
<label class="toggle-switch">
<input type="checkbox" id="darkModeToggleSetting">
@@ -196,13 +237,13 @@
<div class="form-group">
<div class="preference-item">
<div>
- <label>Default View</label>
- <p class="text-muted">Choose your preferred view for warranties</p>
+ <label data-i18n="settings.default_view">Default View</label>
+ <p class="text-muted" data-i18n="settings.default_view_desc">Choose your preferred view for warranties</p>
</div>
<select id="defaultView" class="form-control">
- <option value="grid">Grid View</option>
- <option value="list">List View</option>
- <option value="table">Table View</option>
+ <option value="grid" data-i18n="settings.grid_view">Grid View</option>
+ <option value="list" data-i18n="settings.list_view">List View</option>
+ <option value="table" data-i18n="settings.table_view">Table View</option>
</select>
</div>
</div>
@@ -210,20 +251,11 @@
<div class="form-group">
<div class="preference-item">
<div>
- <label>Currency Symbol</label>
- <p class="text-muted">Choose the symbol to display for prices</p>
+ <label data-i18n="settings.currency_symbol">Currency Symbol</label>
+ <p class="text-muted" data-i18n="settings.currency_symbol_desc">Choose the symbol to display for prices</p>
</div>
<select id="currencySymbolSelect" class="form-control" style="width: 120px; font-size: 1.1em;">
- <option value="$">$ (USD)</option>
- <option value="€">€ (EUR)</option>
- <option value="£">£ (GBP)</option>
- <option value="¥">¥ (JPY/CNY)</option>
- <option value="₹">₹ (INR)</option>
- <option value="₩">₩ (KRW)</option>
- <option value="CHF">CHF (Swiss Franc)</option>
- <option value="CAD">CAD (Canadian Dollar)</option>
- <option value="AUD">AUD (Australian Dollar)</option>
- <option value="other">Other...</option>
+ <option value="">Loading currencies...</option>
</select>
<input type="text" id="currencySymbolCustom" class="form-control" maxlength="6" style="width: 70px; text-align: center; font-size: 1.2em; display: none; margin-left: 10px;" placeholder="Custom">
</div>
@@ -232,8 +264,22 @@
<div class="form-group">
<div class="preference-item">
<div>
- <label>Expiring Soon Days</label>
- <p class="text-muted">Number of days before warranty expiration to mark as "Expiring Soon"</p>
+ <label data-i18n="settings.currency_position">Currency Position</label>
+ <p class="text-muted" data-i18n="settings.currency_position_desc">Choose whether currency symbol appears on the left or right of numbers</p>
+ </div>
+ <select id="currencyPositionSelect" class="form-control" style="width: 150px;">
+ <option value="left">Left ($100.00)</option>
+ <option value="right">Right (100.00$)</option>
+ </select>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.expiring_soon_days">Expiring Soon Days</label>
+ <p class="text-muted" data-i18n="settings.expiring_soon_days_desc">Number of days before expiration to show warnings</p>
+ <p class="text-muted" data-i18n="settings.expiring_soon_days_desc">Number of days before warranty expiration to mark as "Expiring Soon"</p>
</div>
<input type="number" id="expiringSoonDays" class="form-control" min="1" max="365" value="30">
</div>
@@ -242,8 +288,8 @@
<div class="form-group">
<div class="preference-item">
<div>
- <label for="dateFormat">Date Format</label>
- <p class="text-muted">Choose how dates are displayed</p>
+ <label for="dateFormat" data-i18n="settings.date_format">Date Format</label>
+ <p class="text-muted" data-i18n="settings.date_format_desc">Choose how dates are displayed</p>
</div>
<select id="dateFormat" class="form-control">
<option value="MDY">Month/Day/Year (e.g., 12/31/2024)</option>
@@ -256,67 +302,112 @@
</div>
</div>
- <button type="button" id="savePreferencesBtn" class="btn btn-primary">Save Preferences</button>
+ <button type="button" id="savePreferencesBtn" class="btn btn-primary" data-i18n="settings.save_preferences">Save Preferences</button>
</form>
</div>
</div>
- <!-- Email Settings -->
- <div class="card">
- <div class="card-header">
- <h3>Email Settings</h3>
+ <!-- Notification Settings -->
+ <div class="card collapsible-card">
+ <div class="card-header collapsible-header" data-target="notificationSettingsContent">
+ <h3 data-i18n="settings.notification_settings">Notification Settings</h3>
+ <i class="fas fa-chevron-down collapse-icon"></i>
</div>
- <div class="card-body">
- <form id="emailPreferencesForm"> <!-- Consider if a separate form/save button is needed, or if settings.js handles this -->
+ <div class="card-body collapsible-content" id="notificationSettingsContent">
+ <form id="notificationPreferencesForm">
<div class="form-group">
<div class="preference-item">
<div>
- <label>Email Notifications</label>
- <p class="text-muted">Receive email alerts for warranty expirations</p>
+ <label data-i18n="settings.notification_channel">Notification Channel</label>
+ <p class="text-muted" data-i18n="settings.notification_channel_desc">Choose how you want to receive notifications.</p>
</div>
- <label class="toggle-switch">
- <input type="checkbox" id="emailNotifications">
- <span class="toggle-slider"></span>
- </label>
+ <select id="notificationChannel" class="form-control">
+ <option value="none" data-i18n="settings.notification_disabled">Disabled</option>
+ <option value="email" data-i18n="settings.notification_email">Email</option>
+ <option value="apprise" data-i18n="settings.notification_apprise">Apprise</option>
+ <option value="both" data-i18n="settings.notification_both">Both</option>
+ </select>
</div>
</div>
- <div class="form-group">
- <div class="preference-item">
- <div>
- <label>Notification Frequency</label>
- <p class="text-muted">How often to receive email notifications</p>
+ <div id="emailSettingsContainer" style="display: none;">
+ <h4 data-i18n="settings.email_settings">Email Settings</h4>
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.notification_frequency">Notification Frequency</label>
+ <p class="text-muted" data-i18n="settings.notification_frequency_desc">How often to receive email notifications</p>
+ </div>
+ <select id="notificationFrequency" class="form-control">
+ <option value="daily" data-i18n="settings.daily">Daily</option>
+ <option value="weekly" data-i18n="settings.weekly">Weekly</option>
+ <option value="monthly" data-i18n="settings.monthly">Monthly</option>
+ </select>
</div>
- <select id="notificationFrequency" class="form-control">
- <option value="daily">Daily</option>
- <option value="weekly">Weekly</option>
- <option value="monthly">Monthly</option>
- </select>
</div>
- </div>
- <div class="form-group">
- <div class="preference-item">
- <div>
- <label>Notification Time</label>
- <p class="text-muted">Time of day to receive notifications (in 24-hour format)</p>
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.notification_time">Notification Time</label>
+ <p class="text-muted" data-i18n="settings.time_of_day_notification">Time of day to receive notifications (in 24-hour format)</p>
+ </div>
+ <input type="time" id="notificationTime" class="form-control" value="09:00">
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.timezone">Timezone</label>
+ <p class="text-muted" data-i18n="settings.timezone_desc">Your local timezone for notifications</p>
+ </div>
+ <select id="timezone" class="form-control">
+ <option value="">Loading timezones...</option>
+ </select>
</div>
- <input type="time" id="notificationTime" class="form-control" value="09:00">
</div>
</div>
- <div class="form-group">
- <div class="preference-item">
- <div>
- <label>Timezone</label>
- <p class="text-muted">Your local timezone for notifications</p>
+ <div id="userAppriseSettingsContainer" style="display: none;">
+ <h4 data-i18n="settings.apprise_settings">Apprise Settings</h4>
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.apprise_frequency">Apprise Notification Frequency</label>
+ <p class="text-muted" data-i18n="settings.apprise_frequency_desc">How often to receive Apprise notifications</p>
+ </div>
+ <select id="userAppriseNotificationFrequency" class="form-control">
+ <option value="daily" data-i18n="settings.daily">Daily</option>
+ <option value="weekly" data-i18n="settings.weekly">Weekly</option>
+ <option value="monthly" data-i18n="settings.monthly">Monthly</option>
+ </select>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.apprise_time">Apprise Notification Time</label>
+ <p class="text-muted" data-i18n="settings.time_of_day_notification">Time of day to receive Apprise notifications (in 24-hour format)</p>
+ </div>
+ <input type="time" id="userAppriseNotificationTime" class="form-control" value="09:00">
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.apprise_timezone">Apprise Timezone</label>
+ <p class="text-muted" data-i18n="settings.apprise_timezone_desc">Your local timezone for Apprise notifications</p>
+ </div>
+ <select id="userAppriseTimezone" class="form-control">
+ <option value="">Loading timezones...</option>
+ </select>
</div>
- <select id="timezone" class="form-control">
- <option value="">Loading timezones...</option>
- </select>
</div>
</div>
- <button type="button" id="saveEmailSettingsBtn" class="btn btn-primary">Save Email Settings</button>
+ <button type="button" id="saveNotificationSettingsBtn" class="btn btn-primary" data-i18n="settings.save_notification_settings">Save Notification Settings</button>
</form>
</div>
</div>
@@ -324,36 +415,36 @@
<!-- Security -->
<div class="card">
<div class="card-header">
- <h3>Security</h3>
+ <h3 data-i18n="settings.security">Security</h3>
</div>
<div class="card-body">
<div class="preference-item">
<div>
- <label>Change Password</label>
- <p class="text-muted">Update your account password</p>
+ <label data-i18n="settings.change_password">Change Password</label>
+ <p class="text-muted" data-i18n="settings.change_password_desc">Update your account password</p>
</div>
- <button id="changePasswordBtn" class="btn btn-outline-primary">Change</button>
+ <button id="changePasswordBtn" class="btn btn-outline-primary" data-i18n="settings.change">Change</button>
</div>
<div id="passwordChangeForm" style="display: none; margin-top: 20px;">
<div class="form-group">
- <label for="currentPassword">Current Password</label>
+ <label for="currentPassword" data-i18n="settings.current_password">Current Password</label>
<input type="password" id="currentPassword" name="currentPassword" class="form-control">
</div>
<div class="form-group">
- <label for="newPassword">New Password</label>
+ <label for="newPassword" data-i18n="settings.new_password">New Password</label>
<input type="password" id="newPassword" name="newPassword" class="form-control">
</div>
<div class="form-group">
- <label for="confirmPassword">Confirm New Password</label>
+ <label for="confirmPassword" data-i18n="settings.confirm_password">Confirm New Password</label>
<input type="password" id="confirmPassword" name="confirmPassword" class="form-control">
</div>
<div class="button-group">
- <button type="button" id="savePasswordBtn" class="btn btn-primary">Update Password</button>
- <button type="button" id="cancelPasswordBtn" class="btn btn-secondary">Cancel</button>
+ <button type="button" id="savePasswordBtn" class="btn btn-primary" data-i18n="settings.update_password">Update Password</button>
+ <button type="button" id="cancelPasswordBtn" class="btn btn-secondary" data-i18n="settings.cancel">Cancel</button>
</div>
</div>
</div>
@@ -362,66 +453,71 @@
<!-- Danger Zone -->
<div class="card danger-card">
<div class="card-header">
- <h3>Danger Zone</h3>
+ <h3 data-i18n="settings.danger_zone">Danger Zone</h3>
</div>
<div class="card-body">
<div class="preference-item">
<div>
- <label>Delete Account</label>
- <p class="text-muted">Permanently delete your account and all data</p>
+ <label data-i18n="settings.delete_account">Delete Account</label>
+ <p class="text-muted" data-i18n="settings.delete_account_desc">Permanently delete your account and all data</p>
</div>
- <button id="deleteAccountBtn" class="btn btn-danger">Delete Account</button>
+ <button id="deleteAccountBtn" class="btn btn-danger" data-i18n="settings.delete_account">Delete Account</button>
</div>
</div>
</div>
<!-- Admin Section - Only visible to admins -->
<div id="adminSection" class="admin-section" style="display: none;">
- <h2>Admin Settings</h2>
+ <h2 data-i18n="settings.admin_settings">Admin Settings</h2>
<!-- Admin Actions -->
<div class="card">
<div class="card-header">
- <h3>Admin Actions</h3>
+ <h3 data-i18n="settings.admin_actions">Admin Actions</h3>
</div>
<div class="card-body">
<div class="admin-actions-grid">
<button id="refreshUsersBtn" class="admin-action-btn">
<i class="fas fa-sync-alt"></i>
- <span>Refresh Data</span>
+ <span data-i18n="settings.refresh_data">Refresh Data</span>
</button>
<button id="checkAdminBtn" class="admin-action-btn">
<i class="fas fa-user-shield"></i>
- <span>Check Admin Status</span>
+ <span data-i18n="settings.check_admin_status">Check Admin Status</span>
</button>
<button id="showUsersBtn" class="admin-action-btn">
<i class="fas fa-users"></i>
- <span>Show Users List</span>
+ <span data-i18n="settings.show_users_list">Show Users List</span>
</button>
<button id="testApiBtn" class="admin-action-btn">
<i class="fas fa-vial"></i>
- <span>Test API</span>
+ <span data-i18n="settings.test_api">Test API</span>
</button>
<button id="triggerNotificationsBtn" class="admin-action-btn">
<i class="fas fa-envelope"></i>
- <span>Send Warranty Notifications</span>
+ <span data-i18n="settings.send_notifications">Send Warranty Notifications</span>
+ </button>
+ <button id="schedulerStatusBtn" class="admin-action-btn">
+ <i class="fas fa-clock"></i>
+ <span data-i18n="settings.check_scheduler">Check Scheduler Status</span>
</button>
</div>
</div>
</div>
<!-- Site Settings -->
- <div class="card">
- <div class="card-header">
- <h3>Site Settings</h3>
+ <div class="card collapsible-card">
+ <div class="card-header collapsible-header" data-target="siteSettingsContent">
+ <h3 data-i18n="settings.site_settings">Site Settings</h3>
+ <i class="fas fa-chevron-down collapse-icon"></i>
</div>
- <div class="card-body">
+ <div class="card-body collapsible-content" id="siteSettingsContent">
<form id="siteSettingsForm">
<div class="form-group">
<div class="preference-item">
<div>
- <label>Registration Enabled</label>
- <p class="text-muted">Allow new users to register</p>
+ <label data-i18n="settings.registration_enabled">Registration Enabled</label>
+ <p class="text-muted" data-i18n="settings.registration_enabled_desc">Allow new users to register</p>
</div>
<label class="toggle-switch">
<input type="checkbox" id="registrationEnabled">
@@ -434,17 +530,390 @@
<div class="form-group">
<div class="preference-item">
<div>
- <label for="emailBaseUrl">Email Base URL</label>
+ <label for="emailBaseUrl" data-i18n="settings.email_base_url">Email Base URL</label>
<p class="text-muted">The base URL (e.g., http://yourdomain.com) used for links in emails. No trailing slash.</p>
</div>
<input type="text" id="emailBaseUrl" class="form-control" placeholder="http://localhost:8080">
</div>
</div>
+
+ <!-- Global View Setting -->
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.global_view_enabled">Global View Enabled</label>
+ <p class="text-muted">Allow users to view all warranties from all users (read-only for non-owners)</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="globalViewEnabled">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
+ <!-- Global View Admin Only Setting -->
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.global_view_admin_only">Global View Admin Only</label>
+ <p class="text-muted">Restrict global view access to administrators only (requires Global View to be enabled)</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="globalViewAdminOnly">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
+ <button type="button" id="saveSiteSettingsBtn" class="btn btn-primary" data-i18n="settings.save_site_settings">Save Site Settings</button>
+ </form>
+ </div>
+ </div>
+
+ <!-- OIDC SSO Configuration Card -->
+ <div class="card collapsible-card">
+ <div class="card-header collapsible-header" data-target="oidcSettingsContent">
+ <h3 data-i18n="settings.oidc_configuration">OIDC SSO Configuration</h3>
+ <i class="fas fa-chevron-down collapse-icon"></i>
+ </div>
+ <div class="card-body collapsible-content" id="oidcSettingsContent">
+ <form id="oidcSettingsForm">
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label for="oidcEnabled" data-i18n="settings.enable_oidc">Enable OIDC SSO</label>
+ <p class="text-muted" data-i18n="settings.oidc_sso_desc">Allow users to log in via an OIDC provider.</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="oidcEnabled">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label for="oidcOnlyMode" data-i18n="settings.oidc_only_mode">OIDC-Only Login Mode</label>
+ <p class="text-muted" data-i18n="settings.oidc_only_mode_desc">Hide traditional username/password login form and only allow OIDC login. <strong>Warning:</strong> Ensure OIDC is properly configured before enabling this option.</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="oidcOnlyMode">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <label for="oidcProviderName" data-i18n="settings.oidc_provider_name">OIDC Provider Name</label>
+ <input type="text" id="oidcProviderName" class="form-control" placeholder="e.g., oidc, keycloak, google">
+ <small class="text-muted" data-i18n="settings.oidc_provider_name_desc">Internal name for the OIDC client (e.g., 'oidc').</small>
+ </div>
+
+ <div class="form-group">
+ <label for="oidcClientId" data-i18n="settings.client_id">Client ID</label>
+ <input type="text" id="oidcClientId" class="form-control" placeholder="Enter OIDC Client ID">
+ </div>
+
+ <div class="form-group">
+ <label for="oidcClientSecret" data-i18n="settings.client_secret">Client Secret</label>
+ <input type="password" id="oidcClientSecret" class="form-control" placeholder="Enter new secret or leave blank to keep existing">
+ <small class="text-muted" data-i18n="settings.client_secret_desc">Sensitive value. Stored in the database. An application restart is required for changes to take effect.</small>
+ </div>
+
+ <div class="form-group">
+ <label for="oidcIssuerUrl" data-i18n="settings.issuer_url">Issuer URL</label>
+ <input type="url" id="oidcIssuerUrl" class="form-control" placeholder="e.g., https://your-provider.com/realms/your-realm">
+ <small class="text-muted" data-i18n="settings.issuer_url_desc">The base URL of your OIDC provider.</small>
+ </div>
+
+ <div class="form-group">
+ <label for="oidcScope" data-i18n="settings.scope">Scope</label>
+ <input type="text" id="oidcScope" class="form-control" placeholder="e.g., openid email profile">
+ <small class="text-muted" data-i18n="settings.scope_desc">Space-separated OIDC scopes.</small>
+ </div>
- <button type="button" id="saveSiteSettingsBtn" class="btn btn-primary">Save Site Settings</button>
+ <button type="button" id="saveOidcSettingsBtn" class="btn btn-primary" data-i18n="settings.save_oidc_settings">Save OIDC Settings</button>
+ <p id="oidcRestartMessage" class="text-muted" style="margin-top: 10px; display: none;" data-i18n="settings.oidc_restart_message">Application restart is required for OIDC settings to take full effect.</p>
</form>
</div>
</div>
+
+ <!-- Paperless-ngx Integration Configuration Card -->
+ <div class="card collapsible-card">
+ <div class="card-header collapsible-header" data-target="paperlessSettingsContent">
+ <h3 data-i18n="settings.paperless_ngx_settings">Paperless-ngx Integration</h3>
+ <i class="fas fa-chevron-down collapse-icon"></i>
+ </div>
+ <div class="card-body collapsible-content" id="paperlessSettingsContent">
+ <div class="alert alert-info" style="margin-bottom: 20px;">
+ <i class="fas fa-info-circle"></i>
+ <strong data-i18n="settings.paperless_ngx_about_title">About Paperless-ngx Integration:</strong>
+ <span data-i18n="settings.paperless_ngx_about_desc">This optional feature allows you to store warranty documents in your self-hosted Paperless-ngx instance instead of locally.
+ When enabled, users can choose where to store each document: locally or in Paperless-ngx.</span>
+ </div>
+
+ <form id="paperlessSettingsForm">
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.enable_paperless">Enable Paperless-ngx Integration</label>
+ <p class="text-muted" data-i18n="settings.paperless_ngx_desc">Allow users to store warranty documents in Paperless-ngx</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="paperlessEnabled">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
+ <div id="paperlessSettingsContainer" style="display: none;">
+ <div class="form-group">
+ <label for="paperlessUrl" data-i18n="settings.paperless_url">Paperless-ngx URL</label>
+ <input type="url" id="paperlessUrl" class="form-control" placeholder="https://paperless.yourdomain.com">
+ <small class="text-muted" data-i18n="settings.paperless_url_desc">The base URL of your Paperless-ngx instance (without trailing slash).</small>
+ </div>
+
+ <div class="form-group">
+ <label for="paperlessApiToken" data-i18n="settings.paperless_token">API Token</label>
+ <input type="password" id="paperlessApiToken" class="form-control" placeholder="Enter API token or leave blank to keep existing">
+ <small class="text-muted" data-i18n="settings.paperless_token_desc_generate">Generate an API token from your Paperless-ngx instance (Settings → API Tokens).</small>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.paperless_view_in_app">View Documents in Warracker</label>
+ <p class="text-muted" data-i18n="settings.paperless_view_in_app_desc">View Paperless-ngx documents within Warracker instead of opening them in Paperless domain</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="paperlessViewInApp">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
+ <div class="form-group" style="margin-top: 20px;">
+ <label data-i18n="settings.connection_testing">Connection Testing</label>
+ <div class="paperless-button-group">
+ <button type="button" id="testPaperlessConnectionBtn" class="btn btn-secondary">
+ <i class="fas fa-plug"></i> <span data-i18n="settings.test_paperless">Test Connection</span>
+ </button>
+ <button type="button" id="debugPaperlessBtn" class="btn btn-info">
+ <i class="fas fa-bug"></i> <span data-i18n="settings.debug_config">Debug Config</span>
+ </button>
+ <button type="button" id="testFileUploadBtn" class="btn btn-warning">
+ <i class="fas fa-upload"></i> <span data-i18n="settings.test_upload">Test Upload</span>
+ </button>
+ </div>
+ <div id="paperlessConnectionStatus" class="paperless-status-message"></div>
+ </div>
+ </div>
+
+ <button type="button" id="savePaperlessSettingsBtn" class="btn btn-primary" style="margin-top: 15px;">
+ <i class="fas fa-save"></i> <span data-i18n="settings.save_paperless_settings">Save Paperless-ngx Settings</span>
+ </button>
+ </form>
+ </div>
+ </div>
+
+ <!-- Apprise Notifications Configuration Card -->
+ <div class="card collapsible-card">
+ <div class="card-header collapsible-header" data-target="appriseNotificationsContent">
+ <h3 data-i18n="settings.apprise_notifications">Apprise Notifications</h3> <span class="badge" id="appriseStatusBadge" data-i18n="settings.loading">Loading...</span>
+ <i class="fas fa-chevron-down collapse-icon"></i>
+ </div>
+ <div class="card-body collapsible-content" id="appriseNotificationsContent">
+ <div id="appriseNotAvailable" class="alert alert-warning" style="display: none;">
+ <i class="fas fa-exclamation-triangle"></i>
+ <strong data-i18n="settings.apprise_not_available_title">Apprise Not Available:</strong> <span data-i18n="settings.apprise_not_available_desc">The Apprise notification library is not installed or available. Notification features are disabled.</span>
+ </div>
+
+ <form id="appriseSettingsForm">
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.enable_apprise">Enable Apprise Notifications</label>
+ <p class="text-muted" data-i18n="settings.apprise_desc_system_wide">Enable or disable Apprise notifications system-wide</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="appriseEnabled">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
+ <div id="appriseSettingsContainer" style="display: none;">
+ <h4 data-i18n="settings.apprise_settings">Apprise Settings</h4>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.apprise_mode">Notification Mode</label>
+ <p class="text-muted" data-i18n="settings.apprise_mode_desc">Choose how Apprise notifications are sent.</p>
+ </div>
+ <select id="appriseNotificationMode" class="form-control" style="max-width: 200px;">
+ <option value="global" data-i18n="settings.apprise_mode_global">Global Summary</option>
+ <option value="individual" data-i18n="settings.apprise_mode_individual">Per User</option>
+ </select>
+ </div>
+ <div class="mode-description text-muted" id="appriseModeDescription" style="margin-top: 5px; padding-left: 10px; border-left: 2px solid var(--border-color);">
+ <!-- Description will be updated by JS -->
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.apprise_warranty_scope">Warranty Scope</label>
+ <p class="text-muted" data-i18n="settings.apprise_warranty_scope_desc">Choose which warranties to include in notifications.</p>
+ </div>
+ <select id="appriseWarrantyScope" class="form-control" style="max-width: 200px;">
+ <option value="all" data-i18n="settings.all_users_warranties">All Users' Warranties</option>
+ <option value="admin" data-i18n="settings.admin_warranties_only">Admin's Warranties Only</option>
+ </select>
+ </div>
+ <div class="scope-description text-muted" id="appriseScopeDescription" style="margin-top: 5px; padding-left: 10px; border-left: 2px solid var(--border-color);">
+ <!-- Description will be updated by JS -->
+ </div>
+ </div>
+
+ <div class="form-group">
+ <label for="appriseUrls" data-i18n="settings.apprise_url">Notification URLs</label>
+ <textarea id="appriseUrls" class="form-control" rows="4" placeholder="Enter Apprise notification URLs, one per line or comma-separated:&#10;&#10;mailto://user:[email protected]&#10;discord://webhook_id/webhook_token&#10;slack://TokenA/TokenB/TokenC/Channel&#10;telegram://BotToken/ChatID"></textarea>
+ <small class="text-muted" data-i18n="settings.apprise_url_desc">
+ Configure notification services using Apprise URL format.
+ <a href="https://github.com/caronc/apprise/wiki" target="_blank" rel="noopener">View supported services and URL formats</a>
+ </small>
+ </div>
+
+ <div class="form-group">
+ <label for="appriseExpirationDays" data-i18n="settings.apprise_notification_days">Notification Days</label>
+ <input type="text" id="appriseExpirationDays" class="form-control" placeholder="7,30" value="7,30">
+ <small class="text-muted" data-i18n="settings.apprise_notification_days_desc">Days before expiration to send notifications (comma-separated, e.g., "7,30" for 7 days and 30 days before)</small>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label data-i18n="settings.apprise_check_frequency">Check Frequency</label>
+ <p class="text-muted" data-i18n="settings.apprise_check_frequency_desc">How often the system checks for expiring warranties (global setting)</p>
+ </div>
+ <select id="appriseNotificationFrequency" class="form-control">
+ <option value="daily" data-i18n="settings.daily">Daily</option>
+ <option value="weekly" data-i18n="settings.weekly">Weekly</option>
+ <option value="monthly" data-i18n="settings.monthly">Monthly</option>
+ </select>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <label for="appriseTitlePrefix" data-i18n="settings.apprise_title_prefix">Message Title Prefix</label>
+ <input type="text" id="appriseTitlePrefix" class="form-control" placeholder="[Warracker]" value="[Warracker]">
+ <small class="text-muted" data-i18n="settings.apprise_title_prefix_desc">Prefix added to notification titles (e.g., "[Warracker]" results in "[Warracker] Warranties Expiring Soon")</small>
+ </div>
+
+ <div class="form-group">
+ <label for="appriseTestUrl" data-i18n="settings.apprise_test_url">Test URL (Optional)</label>
+ <input type="text" id="appriseTestUrl" class="form-control" placeholder="mailto://[email protected] or discord://webhook_id/webhook_token">
+ <small class="text-muted" data-i18n="settings.apprise_test_url_desc">Optional: URL for sending test notifications only (won't be saved to main configuration)</small>
+ </div>
+
+ <div class="apprise-actions" style="margin-top: 20px;">
+ <button type="button" id="saveAppriseSettingsBtn" class="btn btn-primary">
+ <i class="fas fa-save"></i> <span data-i18n="settings.save_apprise_settings">Save Apprise Settings</span>
+ </button>
+ <button type="button" id="testAppriseBtn" class="btn btn-secondary">
+ <i class="fas fa-paper-plane"></i> <span data-i18n="settings.test_apprise">Send Test Notification</span>
+ </button>
+ <button type="button" id="validateAppriseUrlBtn" class="btn btn-info">
+ <i class="fas fa-check-circle"></i> <span data-i18n="settings.validate_urls">Validate URLs</span>
+ </button>
+ <button type="button" id="triggerAppriseNotificationsBtn" class="btn btn-warning">
+ <i class="fas fa-bell"></i> <span data-i18n="settings.send_expiration_notifications_now">Send Expiration Notifications Now</span>
+ </button>
+ </div>
+
+ <div id="appriseCurrentStatus" class="mt-3" style="margin-top: 15px;">
+ <h4 data-i18n="settings.apprise_current_status">Current Status</h4>
+ <div class="status-grid">
+ <div class="status-item">
+ <span class="status-label" data-i18n="settings.apprise_urls_configured">URLs Configured:</span>
+ <span id="appriseUrlsCount" class="status-value">0</span>
+ </div>
+ <div class="status-item">
+ <span class="status-label" data-i18n="settings.apprise_notification_days">Notification Days:</span>
+ <span id="currentAppriseExpirationDays" class="status-value">-</span>
+ </div>
+
+ </div>
+ </div>
+
+ <div id="appriseSupportedServices" class="mt-3" style="margin-top: 15px;">
+ <h4 data-i18n="settings.apprise_supported_services">Supported Services</h4>
+ <div class="services-info">
+ <p class="text-muted" data-i18n="settings.apprise_supported_services_desc">
+ Apprise supports 80+ notification services including:
+ Discord, Slack, Telegram, Email (Gmail, Outlook), Webhooks, Microsoft Teams,
+ Matrix, Pushover, Ntfy, Gotify, and many more.
+ </p>
+ <button type="button" id="viewSupportedServicesBtn" class="btn btn-link">
+ <i class="fas fa-external-link-alt"></i> <span data-i18n="settings.view_full_list_of_supported_services">View Full List of Supported Services</span>
+ </button>
+ </div>
+ </div>
+ </form>
+ </div>
+ </div>
+
+ </div>
+
+ <!-- Ownership Management Section - Only visible to the owner -->
+ <div id="ownershipSection" class="ownership-section" style="display: none;">
+ <h2><i class="fas fa-crown" style="color: #f39c12; margin-right: 8px;"></i><span data-i18n="settings.ownership_management">Ownership Management</span></h2>
+
+ <div id="ownershipCard" class="card danger-card">
+ <div class="card-header">
+ <h3 data-i18n="settings.transfer_ownership">Transfer Ownership</h3>
+ </div>
+ <div class="card-body">
+ <p class="text-danger"><strong data-i18n="settings.warning_title">Warning:</strong> <span data-i18n="settings.transfer_ownership_warning">Transfer application ownership to another admin user. This action is irreversible.</span></p>
+ <p data-i18n="settings.transfer_ownership_desc">Once ownership is transferred, you will become a regular admin and the new owner will have ultimate control over the application.</p>
+ <div class="form-group">
+ <label for="newOwnerSelect" data-i18n="settings.select_new_owner">Select New Owner (must be an admin)</label>
+ <select id="newOwnerSelect" class="form-control">
+ <option value="" data-i18n="settings.select_admin_user">Select an admin user...</option>
+ </select>
+ </div>
+ <button id="transferOwnershipBtn" class="btn btn-danger" disabled data-i18n="settings.transfer_ownership_button">Transfer Ownership</button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Transfer Ownership Confirmation Modal -->
+ <div id="transferOwnershipModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3 class="modal-title"><i class="fas fa-crown" style="color: #f39c12; margin-right: 8px;"></i><span data-i18n="settings.transfer_ownership">Transfer Ownership</span></h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <p class="text-danger"><strong data-i18n="settings.warning_title">Warning:</strong> <span data-i18n="settings.transfer_ownership_irreversible">This action cannot be undone.</span></p>
+ <p><span data-i18n="settings.transfer_ownership_confirmation">You are about to transfer application ownership to</span> <strong><span id="transferTargetUsername"></span></strong>.</p>
+ <p data-i18n="settings.after_this_transfer">After this transfer:</p>
+ <ul>
+ <li data-i18n="settings.transfer_ownership_consequence_1">You will become a regular admin</li>
+ <li data-i18n="settings.transfer_ownership_consequence_2">The new owner will have ultimate control over the application</li>
+ <li data-i18n="settings.transfer_ownership_consequence_3">Only the new owner can transfer ownership again</li>
+ </ul>
+ <p data-i18n="settings.transfer_ownership_type_to_confirm">To confirm, please type <strong>"TRANSFER"</strong> in the field below:</p>
+ <input type="text" id="transferConfirmInput" class="form-control" placeholder="Type TRANSFER to confirm">
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" data-dismiss="modal" data-i18n="actions.cancel">Cancel</button>
+ <button id="confirmTransferOwnershipBtn" class="btn btn-danger" disabled data-i18n="settings.transfer_ownership_button">Transfer Ownership</button>
</div>
</div>
</div>
@@ -608,6 +1077,39 @@
</div>
</div>
+ <!-- Users List Modal (Admin) -->
+ <div id="usersModal" class="modal-backdrop">
+ <div class="modal" style="max-width: 90%; width: 1000px;">
+ <div class="modal-header">
+ <h3 class="modal-title">Users List</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body" style="padding: 0;">
+ <div style="overflow-x: auto;">
+ <table style="width: 100%; border-collapse: collapse; margin: 0;">
+ <thead>
+ <tr style="background-color: var(--card-bg); border-bottom: 2px solid var(--border-color);">
+ <th style="padding: 12px 8px; text-align: left; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 40px;">ID</th>
+ <th style="padding: 12px 8px; text-align: left; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 120px;">Username</th>
+ <th style="padding: 12px 8px; text-align: left; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 180px;">Email</th>
+ <th style="padding: 12px 8px; text-align: left; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 120px;">Name</th>
+ <th style="padding: 12px 8px; text-align: center; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 80px;">Admin</th>
+ <th style="padding: 12px 8px; text-align: center; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 80px;">Active</th>
+ <th style="padding: 12px 8px; text-align: center; font-weight: 600; color: var(--text-color); min-width: 100px;">Actions</th>
+ </tr>
+ </thead>
+ <tbody id="usersTableBody">
+ <!-- Users will be populated here by loadUsers() -->
+ </tbody>
+ </table>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" data-dismiss="modal">Close</button>
+ </div>
+ </div>
+ </div>
+
<!-- Loading Container -->
<div id="loadingContainer" class="loading-container">
<div class="spinner"></div>
@@ -617,7 +1119,19 @@
<div id="toastContainer" class="toast-container"></div>
<!-- Scripts -->
- <script src="auth.js"></script>
- <script src="settings-new.js"></script>
+ <script src="auth.js?v=20250119001"></script>
+ <script src="settings-new.js?v=20250119001"></script>
+
+ <!-- Footer Width Fix -->
+ <script src="footer-fix.js?v=20250119001"></script>
+
+ <!-- Footer Content Manager -->
+ <script src="footer-content.js?v=20250119001"></script>
+
+<!-- Powered by Warracker Footer -->
+<footer class="warracker-footer" id="warrackerFooter">
+ <!-- Content will be dynamically generated by footer-content.js -->
+</footer>
+
</body>
</html>
diff --git a/frontend/settings-new.js b/frontend/settings-new.js
index d8b8823..e226130 100644
--- a/frontend/settings-new.js
+++ b/frontend/settings-new.js
@@ -1,16 +1,20 @@
// DOM Elements
const darkModeToggle = document.getElementById('darkModeToggle');
const darkModeToggleSetting = document.getElementById('darkModeToggleSetting');
+const languageSelect = document.getElementById('languageSelect');
const defaultViewSelect = document.getElementById('defaultView');
-const emailNotificationsToggle = document.getElementById('emailNotifications');
const expiringSoonDaysInput = document.getElementById('expiringSoonDays');
+const notificationChannel = document.getElementById('notificationChannel');
const notificationFrequencySelect = document.getElementById('notificationFrequency');
const notificationTimeInput = document.getElementById('notificationTime');
const timezoneSelect = document.getElementById('timezone');
const saveProfileBtn = document.getElementById('saveProfileBtn');
const savePreferencesBtn = document.getElementById('savePreferencesBtn');
-const saveEmailSettingsBtn = document.getElementById('saveEmailSettingsBtn');
+const saveNotificationSettingsBtn = document.getElementById('saveNotificationSettingsBtn');
const changePasswordBtn = document.getElementById('changePasswordBtn');
+const emailSettingsContainer = document.getElementById('emailSettingsContainer');
+const appriseSettingsContainer = document.getElementById('appriseSettingsContainer');
+const userAppriseSettingsContainer = document.getElementById('userAppriseSettingsContainer');
const passwordChangeForm = document.getElementById('passwordChangeForm');
const savePasswordBtn = document.getElementById('savePasswordBtn');
const cancelPasswordBtn = document.getElementById('cancelPasswordBtn');
@@ -25,6 +29,14 @@ const settingsBtn = document.getElementById('settingsBtn');
const settingsMenu = document.getElementById('settingsMenu');
const usersTableBody = document.getElementById('usersTableBody');
+// Edit User Modal Elements
+const editUserModal = document.getElementById('editUserModal');
+const editUserId = document.getElementById('editUserId');
+const editUsername = document.getElementById('editUsername');
+const editEmail = document.getElementById('editEmail');
+const editUserActive = document.getElementById('editUserActive');
+const editUserAdmin = document.getElementById('editUserAdmin');
+
// Form fields
const firstNameInput = document.getElementById('firstName');
const lastNameInput = document.getElementById('lastName');
@@ -40,16 +52,158 @@ const checkAdminBtn = document.getElementById('checkAdminBtn');
const showUsersBtn = document.getElementById('showUsersBtn');
const testApiBtn = document.getElementById('testApiBtn');
const triggerNotificationsBtn = document.getElementById('triggerNotificationsBtn');
+const schedulerStatusBtn = document.getElementById('schedulerStatusBtn');
const registrationEnabled = document.getElementById('registrationEnabled');
const saveSiteSettingsBtn = document.getElementById('saveSiteSettingsBtn');
const emailBaseUrlInput = document.getElementById('emailBaseUrl'); // Added for email base URL
+
+// OIDC Settings DOM Elements
+const oidcEnabledToggle = document.getElementById('oidcEnabled');
+const oidcOnlyModeToggle = document.getElementById('oidcOnlyMode');
+const oidcProviderNameInput = document.getElementById('oidcProviderName');
+const oidcClientIdInput = document.getElementById('oidcClientId');
+const oidcClientSecretInput = document.getElementById('oidcClientSecret');
+const oidcIssuerUrlInput = document.getElementById('oidcIssuerUrl');
+const oidcScopeInput = document.getElementById('oidcScope');
+const saveOidcSettingsBtn = document.getElementById('saveOidcSettingsBtn');
+const oidcRestartMessage = document.getElementById('oidcRestartMessage');
+
+// Apprise Settings DOM Elements
+const appriseEnabledToggle = document.getElementById('appriseEnabled');
+const appriseNotificationModeSelect = document.getElementById('appriseNotificationMode');
+const appriseModeDescription = document.getElementById('appriseModeDescription');
+const appriseWarrantyScopeSelect = document.getElementById('appriseWarrantyScope');
+const appriseScopeDescription = document.getElementById('appriseScopeDescription');
+const appriseUrlsTextarea = document.getElementById('appriseUrls');
+const appriseExpirationDaysInput = document.getElementById('appriseExpirationDays');
+const appriseNotificationFrequency = document.getElementById('appriseNotificationFrequency');
+
+// User-specific Apprise settings (in notification settings section)
+const userAppriseNotificationTimeInput = document.getElementById('userAppriseNotificationTime');
+const userAppriseTimezoneSelect = document.getElementById('userAppriseTimezone');
+const userAppriseNotificationFrequency = document.getElementById('userAppriseNotificationFrequency');
+const appriseTitlePrefixInput = document.getElementById('appriseTitlePrefix');
+const appriseTestUrlInput = document.getElementById('appriseTestUrl');
+const saveAppriseSettingsBtn = document.getElementById('saveAppriseSettingsBtn');
+const testAppriseBtn = document.getElementById('testAppriseBtn');
+const validateAppriseUrlBtn = document.getElementById('validateAppriseUrlBtn');
+const triggerAppriseNotificationsBtn = document.getElementById('triggerAppriseNotificationsBtn');
+const appriseStatusBadge = document.getElementById('appriseStatusBadge');
+const appriseUrlsCount = document.getElementById('appriseUrlsCount');
+const currentAppriseExpirationDays = document.getElementById('currentAppriseExpirationDays');
+
+const viewSupportedServicesBtn = document.getElementById('viewSupportedServicesBtn');
+const appriseNotAvailable = document.getElementById('appriseNotAvailable');
+
const currencySymbolInput = document.getElementById('currencySymbol');
const currencySymbolSelect = document.getElementById('currencySymbolSelect');
const currencySymbolCustom = document.getElementById('currencySymbolCustom');
+const currencyPositionSelect = document.getElementById('currencyPositionSelect');
// Add dateFormatSelect near other DOM element declarations if not already there
const dateFormatSelect = document.getElementById('dateFormat');
+// Paperless-ngx Settings DOM Elements
+const paperlessEnabledToggle = document.getElementById('paperlessEnabled');
+const paperlessUrlInput = document.getElementById('paperlessUrl');
+const paperlessApiTokenInput = document.getElementById('paperlessApiToken');
+const paperlessViewInAppToggle = document.getElementById('paperlessViewInApp');
+const paperlessSettingsContainer = document.getElementById('paperlessSettingsContainer');
+const testPaperlessConnectionBtn = document.getElementById('testPaperlessConnectionBtn');
+const savePaperlessSettingsBtn = document.getElementById('savePaperlessSettingsBtn');
+const paperlessConnectionStatus = document.getElementById('paperlessConnectionStatus');
+
+// Global variable to store currencies data for currency code lookup
+let globalCurrenciesData = [];
+
+/**
+ * Load currencies from the API and populate the currency dropdown
+ */
+async function loadCurrenciesForSettings() {
+ try {
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ const response = await fetch('/api/currencies', {
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ });
+ if (!response.ok) {
+ throw new Error('Failed to fetch currencies');
+ }
+
+ const currencies = await response.json();
+
+ // Store currencies data globally for currency code lookup
+ globalCurrenciesData = currencies;
+
+ // Populate currency symbol dropdown
+ if (currencySymbolSelect) {
+ // Clear existing options
+ currencySymbolSelect.innerHTML = '';
+
+ // Add currencies from API
+ currencies.forEach(currency => {
+ const option = document.createElement('option');
+ option.value = currency.symbol;
+ option.textContent = `${currency.symbol} (${currency.code} - ${currency.name})`;
+ currencySymbolSelect.appendChild(option);
+ });
+
+ // Add "Other..." option at the end
+ const otherOption = document.createElement('option');
+ otherOption.value = 'other';
+ otherOption.textContent = 'Other...';
+ currencySymbolSelect.appendChild(otherOption);
+ }
+
+ console.log('Currencies loaded successfully for settings page');
+ } catch (error) {
+ console.error('Error loading currencies for settings:', error);
+ // Fallback to default currencies if loading fails
+ if (currencySymbolSelect) {
+ currencySymbolSelect.innerHTML = `
+ <option value="$">$ (USD - US Dollar)</option>
+ <option value="€">€ (EUR - Euro)</option>
+ <option value="£">£ (GBP - British Pound)</option>
+ <option value="¥">¥ (JPY - Japanese Yen)</option>
+ <option value="other">Other...</option>
+ `;
+ }
+ }
+}
+
+/**
+ * Initialize language selector
+ */
+function initLanguageSelector() {
+ if (!languageSelect) return;
+
+ // Get current language
+ const currentLang = window.i18n?.getCurrentLanguage() || 'en';
+ languageSelect.value = currentLang;
+
+ // Add event listener for language changes
+ languageSelect.addEventListener('change', async function() {
+ const selectedLanguage = this.value;
+ console.log('Language changed to:', selectedLanguage);
+
+ if (window.i18n?.changeLanguage) {
+ try {
+ await window.i18n.changeLanguage(selectedLanguage);
+ showToast(window.t('messages.saved') || 'Language changed successfully', 'success');
+
+ // Reload page after a short delay to apply all translations
+ setTimeout(() => {
+ window.location.reload();
+ }, 1000);
+ } catch (error) {
+ console.error('Failed to change language:', error);
+ showToast(window.t('messages.error') || 'Failed to change language', 'error');
+ }
+ }
+ });
+}
+
/**
* Set theme (dark/light) - Unified and persistent
* @param {boolean} isDark - Whether to use dark mode
@@ -137,6 +291,13 @@ function initDarkModeToggle() {
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM fully loaded, initializing settings page');
+ // DEBUG: Check current user data
+ const debugCurrentUser = window.auth && window.auth.getCurrentUser ? window.auth.getCurrentUser() : null;
+ console.log('DEBUG: Current user data:', debugCurrentUser);
+ if (debugCurrentUser) {
+ console.log('DEBUG: User has is_owner field:', 'is_owner' in debugCurrentUser, 'Value:', debugCurrentUser.is_owner);
+ }
+
// Set up event listeners
setupEventListeners(); // Ensure this doesn't also try to init settings menu
@@ -170,6 +331,46 @@ document.addEventListener('DOMContentLoaded', function() {
// --- ADD THIS LINE TO INITIALIZE MODALS ---
initModals();
+
+ // Initialize collapsible cards
+ initCollapsibleCards();
+
+ // Load admin-only settings if user is admin
+ // Note: These will also be loaded later in loadUserData() with proper checks
+ // This is a redundant call that should be conditional
+ const currentUser = window.auth && window.auth.getCurrentUser ? window.auth.getCurrentUser() : null;
+ if (currentUser && currentUser.is_admin) {
+ // Load site settings (for admins) - includes OIDC settings
+ loadSiteSettings();
+
+ // Load Apprise settings
+ loadAppriseSettings();
+
+ // Load Apprise site settings (also loads overall Apprise settings)
+ loadAppriseSiteSettings();
+
+ // Initialize ownership management if user is owner
+ if (currentUser.is_owner) {
+ console.log('DEBUG: User is owner, initializing ownership management');
+ setTimeout(() => {
+ const ownershipSection = document.getElementById('ownershipSection');
+ if (ownershipSection) {
+ ownershipSection.style.display = 'block';
+ console.log('DEBUG: Ownership section made visible');
+ }
+ // Don't load users here - wait for modal to open
+ console.log('DEBUG: Ownership management initialized, users will load when modal opens');
+ }, 500); // Wait for DOM to be ready
+ }
+ } else {
+ console.log('User is not admin, skipping admin-only settings load during initialization');
+ }
+
+ // Setup Apprise event listeners
+ setupAppriseEventListeners();
+
+ // Initialize delete button handling
+ setupDeleteButton();
});
/**
@@ -178,6 +379,9 @@ document.addEventListener('DOMContentLoaded', function() {
function initPage() {
console.log('Initializing settings page');
+ // Initialize language selector
+ initLanguageSelector();
+
// Check authentication
if (window.auth) {
window.auth.checkAuthState();
@@ -346,14 +550,7 @@ async function loadUserData() {
if (userEmailDisplay) userEmailDisplay.textContent = currentUser.email || 'N/A';
// --- END UPDATE ---
- // Check if user is admin and show admin section
- if (currentUser.is_admin) {
- if (adminSection) adminSection.style.display = 'block';
- if (adminSection && adminSection.style.display === 'block') {
- if (usersTableBody) loadUsers();
- if (registrationEnabled) loadSiteSettings();
- }
- }
+ // Admin section visibility will be determined after API call
}
// Fetch fresh user data from API
@@ -384,13 +581,24 @@ async function loadUserData() {
if (userEmailDisplay) userEmailDisplay.textContent = userData.email || 'N/A';
// --- END UPDATE ---
- // Show admin section if user is admin
+ // Show admin section if user is admin and load admin-specific data
if (userData.is_admin) {
- if (adminSection) adminSection.style.display = 'block';
- if (adminSection && adminSection.style.display === 'block') {
- if (usersTableBody) loadUsers();
- if (registrationEnabled) loadSiteSettings();
+ if (adminSection) {
+ adminSection.style.display = 'block';
+ // Ensure admin-specific data is loaded AFTER section is visible
+ if (usersTableBody) loadUsers();
+ // Check for site settings elements directly to avoid cache timing issues
+ const hasRegistrationToggle = document.getElementById('registrationEnabled');
+ const hasOidcToggle = document.getElementById('oidcEnabled');
+ if (hasRegistrationToggle || hasOidcToggle) {
+ console.log('Admin settings elements found, loading site settings...');
+ loadSiteSettings();
+ } else {
+ console.warn('Admin settings elements not found - this might be a timing/cache issue');
+ }
}
+ } else {
+ if (adminSection) adminSection.style.display = 'none';
}
// Update localStorage ONLY if data has changed
@@ -466,17 +674,27 @@ function getPreferenceKeyPrefix() {
return getUserType() === 'admin' ? 'admin_' : 'user_';
}
+// Prevent multiple simultaneous preference loads
+let isLoadingPreferences = false;
+
/**
* Load user preferences
*/
async function loadPreferences() {
+ // Prevent multiple simultaneous loads
+ if (isLoadingPreferences) {
+ console.log('Preferences already loading, skipping duplicate call');
+ return;
+ }
+
+ isLoadingPreferences = true;
console.log('Loading preferences...');
const prefix = getPreferenceKeyPrefix();
console.log('Loading preferences with prefix:', prefix);
- let darkModeFromAPI = null;
let apiPrefs = null;
- // Try to load preferences from backend if authenticated
+
+ // FIXED: Load all preferences from API first, then apply to UI
if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
try {
const response = await fetch('/api/auth/preferences', {
@@ -486,19 +704,41 @@ async function loadPreferences() {
});
if (response.ok) {
apiPrefs = await response.json();
+ console.log('API preferences loaded:', apiPrefs);
+
+ // Apply theme from API immediately (highest priority)
if (apiPrefs && apiPrefs.theme) {
- darkModeFromAPI = apiPrefs.theme === 'dark';
- setTheme(darkModeFromAPI);
- // Sync localStorage
- localStorage.setItem('darkMode', darkModeFromAPI);
+ const isDark = apiPrefs.theme === 'dark';
+ console.log('Applying theme from API:', apiPrefs.theme, 'isDark:', isDark);
+ setTheme(isDark);
+ // Sync localStorage to match API
+ localStorage.setItem('darkMode', isDark);
+ // Ensure the dark mode toggle reflects the API setting
+ if (darkModeToggleSetting) {
+ darkModeToggleSetting.checked = isDark;
+ console.log('Synced dark mode toggle to API value:', isDark);
+ }
+ } else {
+ console.log('No theme in API preferences, using localStorage fallback');
+ const storedDarkMode = localStorage.getItem('darkMode') === 'true';
+ setTheme(storedDarkMode);
+ if (darkModeToggleSetting) {
+ darkModeToggleSetting.checked = storedDarkMode;
+ }
}
+ } else {
+ console.warn('API preferences request failed, using localStorage');
+ const storedDarkMode = localStorage.getItem('darkMode') === 'true';
+ setTheme(storedDarkMode);
}
} catch (e) {
console.warn('Failed to load preferences from backend:', e);
+ // Fallback to localStorage
+ const storedDarkMode = localStorage.getItem('darkMode') === 'true';
+ setTheme(storedDarkMode);
}
- }
- // Fallback: use localStorage if not authenticated or API fails
- if (darkModeFromAPI === null) {
+ } else {
+ console.log('Not authenticated, using localStorage for theme');
const storedDarkMode = localStorage.getItem('darkMode') === 'true';
setTheme(storedDarkMode);
}
@@ -523,8 +763,12 @@ async function loadPreferences() {
console.log(`${prefix}defaultView not found, defaulting view to grid`);
}
- // Currency Symbol
+ // Currency Symbol - Load stored preference first
const storedCurrency = localStorage.getItem(`${prefix}currencySymbol`);
+
+ // Load currencies from API and set the saved preference
+ await loadCurrenciesForSettings();
+
if (storedCurrency) {
if (currencySymbolSelect) {
// Check if the stored symbol is a standard option
@@ -532,6 +776,7 @@ async function loadPreferences() {
if (standardOption) {
currencySymbolSelect.value = storedCurrency;
if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
+ console.log(`Set currency dropdown to stored value: ${storedCurrency}`);
} else {
// It's a custom symbol
currencySymbolSelect.value = 'other';
@@ -539,6 +784,7 @@ async function loadPreferences() {
currencySymbolCustom.value = storedCurrency;
currencySymbolCustom.style.display = 'inline-block';
}
+ console.log(`Set currency to custom value: ${storedCurrency}`);
}
console.log(`Loaded currency symbol from ${prefix}currencySymbol: ${storedCurrency}`);
}
@@ -549,6 +795,16 @@ async function loadPreferences() {
console.log(`${prefix}currencySymbol not found, defaulting to $`);
}
+ // Currency Position
+ const storedCurrencyPosition = localStorage.getItem(`${prefix}currencyPosition`);
+ if (storedCurrencyPosition && currencyPositionSelect) {
+ currencyPositionSelect.value = storedCurrencyPosition;
+ console.log(`Loaded currency position from ${prefix}currencyPosition: ${storedCurrencyPosition}`);
+ } else if (currencyPositionSelect) {
+ currencyPositionSelect.value = 'left'; // Default
+ console.log(`${prefix}currencyPosition not found, defaulting to left`);
+ }
+
// Expiring Soon Days
const storedExpiringDays = localStorage.getItem(`${prefix}expiringSoonDays`);
if (storedExpiringDays && expiringSoonDaysInput) {
@@ -559,19 +815,19 @@ async function loadPreferences() {
console.log(`${prefix}expiringSoonDays not found, defaulting to 30`);
}
- // Now, try fetching preferences from API to override/confirm
- if (window.auth && window.auth.isAuthenticated()) {
- try {
- const token = window.auth.getToken();
- const response = await fetch('/api/auth/preferences', {
- headers: {
- 'Authorization': `Bearer ${token}`
- }
- });
+ // Paperless View in App
+ const storedPaperlessViewInApp = localStorage.getItem(`${prefix}paperlessViewInApp`);
+ if (storedPaperlessViewInApp !== null && paperlessViewInAppToggle) {
+ paperlessViewInAppToggle.checked = storedPaperlessViewInApp === 'true';
+ console.log(`Loaded Paperless view in app from ${prefix}paperlessViewInApp: ${storedPaperlessViewInApp}`);
+ } else if (paperlessViewInAppToggle) {
+ paperlessViewInAppToggle.checked = false; // Default
+ console.log(`${prefix}paperlessViewInApp not found, defaulting to false`);
+ }
- if (response.ok) {
- const apiPrefs = await response.json();
- console.log('Preferences loaded from API:', apiPrefs);
+ // Apply API preferences to form elements (apiPrefs already loaded above)
+ if (apiPrefs) {
+ console.log('Applying API preferences to form elements:', apiPrefs);
// Update UI elements with API data where available
if (apiPrefs.default_view && defaultViewSelect) {
@@ -606,6 +862,18 @@ async function loadPreferences() {
}
}
// --- END MODIFIED CURRENCY SYMBOL HANDLING ---
+
+ // --- CURRENCY POSITION HANDLING ---
+ const storedCurrencyPosition = localStorage.getItem(`${prefix}currencyPosition`);
+ if (apiPrefs.currency_position && currencyPositionSelect) {
+ if (!storedCurrencyPosition || apiPrefs.currency_position !== storedCurrencyPosition) {
+ console.log(`API currency_position (${apiPrefs.currency_position}) differs from localStorage (${storedCurrencyPosition}). Updating UI.`);
+ currencyPositionSelect.value = apiPrefs.currency_position;
+ } else {
+ console.log(`API currency_position (${apiPrefs.currency_position}) matches localStorage (${storedCurrencyPosition}). Skipping UI update.`);
+ }
+ }
+ // --- END CURRENCY POSITION HANDLING ---
if (apiPrefs.expiring_soon_days && expiringSoonDaysInput) {
// Only update if different from localStorage value (or if localStorage was empty)
const storedExpiringDays = localStorage.getItem(`${prefix}expiringSoonDays`) || '30'; // Default if null
@@ -625,9 +893,19 @@ async function loadPreferences() {
}
// --- End Date Format Check ---
+ // --- Update Paperless View in App from API Prefs ---
+ if (apiPrefs.paperless_view_in_app !== undefined && paperlessViewInAppToggle) {
+ paperlessViewInAppToggle.checked = apiPrefs.paperless_view_in_app;
+ console.log(`Set Paperless view in app from API: ${apiPrefs.paperless_view_in_app}`);
+ }
+ // --- End Paperless View in App from API Prefs ---
+
// Update Email Settings from API
- if (emailNotificationsToggle) {
- emailNotificationsToggle.checked = apiPrefs.email_notifications !== false; // Default true if null/undefined
+ if (notificationChannel) {
+ const channelValue = apiPrefs.notification_channel || 'email'; // Default to email if not present
+ notificationChannel.value = channelValue;
+ toggleNotificationSettings(channelValue);
+ console.log('Set notification channel to:', channelValue);
}
if (notificationFrequencySelect && apiPrefs.notification_frequency) {
notificationFrequencySelect.value = apiPrefs.notification_frequency;
@@ -635,6 +913,28 @@ async function loadPreferences() {
if (notificationTimeInput && apiPrefs.notification_time) {
notificationTimeInput.value = apiPrefs.notification_time.substring(0, 5); // HH:MM format
}
+ // Admin Apprise settings (in Apprise card)
+ if (appriseNotificationFrequency && apiPrefs.apprise_notification_frequency) {
+ appriseNotificationFrequency.value = apiPrefs.apprise_notification_frequency;
+ }
+
+ // User-specific Apprise settings (in notification settings section)
+ if (userAppriseNotificationTimeInput && apiPrefs.apprise_notification_time) {
+ userAppriseNotificationTimeInput.value = apiPrefs.apprise_notification_time.substring(0, 5);
+ }
+ if (userAppriseTimezoneSelect && apiPrefs.apprise_timezone) {
+ if (Array.from(userAppriseTimezoneSelect.options).some(option => option.value === apiPrefs.apprise_timezone)) {
+ userAppriseTimezoneSelect.value = apiPrefs.apprise_timezone;
+ } else {
+ console.warn(`User Apprise timezone '${apiPrefs.apprise_timezone}' from API not found in dropdown.`);
+ }
+ }
+ if (userAppriseNotificationFrequency && apiPrefs.apprise_notification_frequency) {
+ userAppriseNotificationFrequency.value = apiPrefs.apprise_notification_frequency;
+ }
+
+ // Update Apprise timezone display
+ updateAppriseTimezoneDisplay(apiPrefs.timezone);
// Load and set timezone from API
if (timezoneSelect && apiPrefs.timezone) {
console.log('API provided timezone:', apiPrefs.timezone);
@@ -642,6 +942,9 @@ async function loadPreferences() {
if (Array.from(timezoneSelect.options).some(option => option.value === apiPrefs.timezone)) {
timezoneSelect.value = apiPrefs.timezone;
console.log('Applied timezone from API:', timezoneSelect.value, 'Current select value:', timezoneSelect.value);
+
+ // Update Apprise timezone display when timezone is loaded
+ updateAppriseTimezoneDisplay(apiPrefs.timezone);
} else {
console.warn(`Timezone '${apiPrefs.timezone}' from API not found in dropdown.`);
}
@@ -649,12 +952,83 @@ async function loadPreferences() {
console.log('No timezone preference found in API or timezone select element missing.');
}
- } else {
- const errorData = await response.json().catch(() => ({}));
- console.warn(`Failed to load preferences from API: ${response.status}`, errorData.message || '');
+ // Load and set language preference
+ if (apiPrefs.preferred_language && languageSelect) {
+ console.log('API provided language:', apiPrefs.preferred_language);
+ // Ensure the option exists before setting
+ if (Array.from(languageSelect.options).some(option => option.value === apiPrefs.preferred_language)) {
+ languageSelect.value = apiPrefs.preferred_language;
+ console.log('Applied language from API:', languageSelect.value);
+
+ // Trigger language change if different from current
+ if (window.i18n?.changeLanguage && window.i18n?.getCurrentLanguage) {
+ const currentLang = window.i18n.getCurrentLanguage();
+ if (apiPrefs.preferred_language !== currentLang) {
+ console.log(`Language preference (${apiPrefs.preferred_language}) differs from current (${currentLang}), changing language`);
+ window.i18n.changeLanguage(apiPrefs.preferred_language).catch(error => {
+ console.error('Failed to change language from API preference:', error);
+ });
+ }
+ }
+ } else {
+ console.warn(`Language '${apiPrefs.preferred_language}' from API not found in dropdown.`);
+ }
+ } else {
+ // Load from localStorage if no API preference
+ const storedLanguage = localStorage.getItem('preferred_language') || 'en';
+ if (languageSelect) {
+ languageSelect.value = storedLanguage;
+ console.log('Applied language from localStorage:', storedLanguage);
+
+ // Trigger language change if different from current
+ if (window.i18n?.changeLanguage && window.i18n?.getCurrentLanguage) {
+ const currentLang = window.i18n.getCurrentLanguage();
+ if (storedLanguage !== currentLang) {
+ console.log(`Stored language (${storedLanguage}) differs from current (${currentLang}), changing language`);
+ window.i18n.changeLanguage(storedLanguage).catch(error => {
+ console.error('Failed to change language from localStorage:', error);
+ });
+ }
+ }
+ }
+ }
+ } else {
+ // No API preferences, load language from localStorage
+ const storedLanguage = localStorage.getItem('preferred_language') || 'en';
+ if (languageSelect) {
+ languageSelect.value = storedLanguage;
+ console.log('Applied language from localStorage (no API):', storedLanguage);
+
+ // Trigger language change if different from current
+ if (window.i18n?.changeLanguage && window.i18n?.getCurrentLanguage) {
+ const currentLang = window.i18n.getCurrentLanguage();
+ if (storedLanguage !== currentLang) {
+ console.log(`Stored language (${storedLanguage}) differs from current (${currentLang}), changing language`);
+ window.i18n.changeLanguage(storedLanguage).catch(error => {
+ console.error('Failed to change language from localStorage (no API):', error);
+ });
+ }
}
- } catch (error) {
- console.error('Error fetching preferences from API:', error);
+ }
+ }
+
+ // Reset the loading flag
+ isLoadingPreferences = false;
+ console.log('Preferences loading completed');
+}
+
+/**
+ * Update the Apprise timezone display to show which timezone will be used
+ */
+function updateAppriseTimezoneDisplay(timezone) {
+ const appriseTimezoneDisplay = document.getElementById('appriseTimezoneDisplay');
+ if (appriseTimezoneDisplay) {
+ if (timezone) {
+ appriseTimezoneDisplay.textContent = `(using timezone: ${timezone})`;
+ appriseTimezoneDisplay.style.display = 'inline';
+ } else {
+ appriseTimezoneDisplay.textContent = '(timezone not set)';
+ appriseTimezoneDisplay.style.display = 'inline';
}
}
}
@@ -666,27 +1040,23 @@ function setupEventListeners() {
console.log('Setting up event listeners');
// Set up user menu button click handler
- const userMenuBtn = document.getElementById('userMenuBtn');
- const userMenuDropdown = document.getElementById('userMenuDropdown');
-
- if (userMenuBtn && userMenuDropdown) {
- console.log('Setting up user menu button click handler');
-
- // Toggle dropdown when user button is clicked
- userMenuBtn.addEventListener('click', function(e) {
- e.stopPropagation();
- userMenuDropdown.classList.toggle('active');
- });
-
- // Close dropdown when clicking outside
- document.addEventListener('click', function(e) {
- if (userMenuDropdown.classList.contains('active') &&
- !userMenuDropdown.contains(e.target) &&
- !userMenuBtn.contains(e.target)) {
- userMenuDropdown.classList.remove('active');
- }
- });
- }
+ // const userMenuBtn = document.getElementById('userMenuBtn'); // REMOVE/COMMENT OUT
+ // const userMenuDropdown = document.getElementById('userMenuDropdown'); // REMOVE/COMMENT OUT
+
+ // if (userMenuBtn && userMenuDropdown) { // REMOVE/COMMENT OUT THIS ENTIRE BLOCK
+ // console.log('Setting up user menu button click handler');
+ // userMenuBtn.addEventListener('click', function(e) {
+ // e.stopPropagation();
+ // userMenuDropdown.classList.toggle('active');
+ // });
+ // document.addEventListener('click', function(e) {
+ // if (userMenuDropdown.classList.contains('active') &&
+ // !userMenuDropdown.contains(e.target) &&
+ // !userMenuBtn.contains(e.target)) {
+ // userMenuDropdown.classList.remove('active');
+ // }
+ // });
+ // }
// Dark mode toggle in header (no longer exists)
if (darkModeToggle) {
@@ -788,7 +1158,16 @@ function setupEventListeners() {
if (showUsersBtn) {
showUsersBtn.addEventListener('click', function() {
- showUsersList();
+ console.log('Show Users List button clicked');
+ // Open the proper users modal that has crown icons and ownership management
+ const usersModal = document.getElementById('usersModal');
+ if (usersModal) {
+ openModal(usersModal);
+ loadUsers(); // This will populate the table with crown icons
+ } else {
+ console.error('usersModal not found, falling back to showUsersList');
+ showUsersList();
+ }
});
}
@@ -804,16 +1183,105 @@ function setupEventListeners() {
});
}
+ if (schedulerStatusBtn) {
+ schedulerStatusBtn.addEventListener('click', function() {
+ checkSchedulerStatus();
+ });
+ }
+
// Site settings save button
if (saveSiteSettingsBtn) {
saveSiteSettingsBtn.addEventListener('click', function() {
- saveSiteSettings();
+ saveSiteSettings(); // This will now also handle non-OIDC site settings
+ });
+ }
+
+ // Save OIDC settings button
+ if (saveOidcSettingsBtn) {
+ saveOidcSettingsBtn.addEventListener('click', function() {
+ saveOidcSettings();
});
}
// Save email settings button
- if (saveEmailSettingsBtn) {
- saveEmailSettingsBtn.addEventListener('click', saveEmailSettings);
+ if (saveNotificationSettingsBtn) {
+ saveNotificationSettingsBtn.addEventListener('click', saveNotificationSettings);
+ }
+
+ // Save user changes button (Edit User Modal)
+ const saveUserBtn = document.getElementById('saveUserBtn');
+ if (saveUserBtn) {
+ saveUserBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ console.log('Save User button clicked');
+ saveUserChanges();
+ });
+ }
+
+ // Add timezone change listener to update Apprise timezone display
+ const timezoneSelect = document.getElementById('timezone');
+ if (timezoneSelect) {
+ timezoneSelect.addEventListener('change', function() {
+ updateAppriseTimezoneDisplay(this.value);
+ });
+ }
+
+
+
+ if (userAppriseTimezoneSelect) {
+ loadTimezonesIntoSelect(userAppriseTimezoneSelect);
+ }
+
+ if (notificationChannel) {
+ notificationChannel.addEventListener('change', (e) => {
+ toggleNotificationSettings(e.target.value);
+ });
+ }
+
+ // Paperless-ngx event listeners
+ if (paperlessEnabledToggle) {
+ paperlessEnabledToggle.addEventListener('change', function() {
+ togglePaperlessSettings(this.checked);
+ });
+ }
+
+ if (testPaperlessConnectionBtn) {
+ testPaperlessConnectionBtn.addEventListener('click', testPaperlessConnection);
+ }
+
+ if (savePaperlessSettingsBtn) {
+ savePaperlessSettingsBtn.addEventListener('click', savePaperlessSettings);
+ }
+
+ // Add debug button event listener
+ const debugPaperlessBtn = document.getElementById('debugPaperlessBtn');
+ if (debugPaperlessBtn) {
+ debugPaperlessBtn.addEventListener('click', debugPaperlessConfiguration);
+ }
+
+ // Add test upload button event listener
+ const testFileUploadBtn = document.getElementById('testFileUploadBtn');
+ if (testFileUploadBtn) {
+ testFileUploadBtn.addEventListener('click', testFileUpload);
+ }
+
+ // Clear status message when inputs are changed
+ if (paperlessUrlInput) {
+ paperlessUrlInput.addEventListener('input', function() {
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.className = 'paperless-status-message';
+ paperlessConnectionStatus.innerHTML = '';
+ }
+ });
+ }
+
+ if (paperlessApiTokenInput) {
+ paperlessApiTokenInput.addEventListener('input', function() {
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.className = 'paperless-status-message';
+ paperlessConnectionStatus.innerHTML = '';
+ }
+ });
}
console.log('Event listeners setup complete');
@@ -869,6 +1337,61 @@ function initModals() {
} else {
console.error('deleteUserModal not found in initModals');
}
+
+ // Set up transfer ownership modal close handlers
+ const transferOwnershipModal = document.getElementById('transferOwnershipModal');
+ if (transferOwnershipModal) {
+ const transferConfirmInput = document.getElementById('transferConfirmInput');
+ const confirmTransferBtn = document.getElementById('confirmTransferOwnershipBtn');
+
+ if (transferConfirmInput && confirmTransferBtn) {
+ transferConfirmInput.addEventListener('input', function() {
+ confirmTransferBtn.disabled = this.value.toUpperCase() !== 'TRANSFER';
+ });
+ }
+ }
+}
+
+/**
+ * Initialize collapsible cards functionality
+ */
+function initCollapsibleCards() {
+ console.log('Initializing collapsible cards...');
+
+ // Get all collapsible headers
+ const collapsibleHeaders = document.querySelectorAll('.collapsible-header');
+
+ // Retrieve saved states from localStorage
+ const savedStates = JSON.parse(localStorage.getItem('collapsibleStates') || '{}');
+
+ collapsibleHeaders.forEach(header => {
+ const targetId = header.getAttribute('data-target');
+ const card = header.closest('.collapsible-card');
+
+ // Apply saved state or default to expanded
+ const isCollapsed = savedStates[targetId] === true;
+ if (isCollapsed) {
+ card.classList.add('collapsed');
+ }
+
+ // Add click event listener
+ header.addEventListener('click', function() {
+ const targetId = this.getAttribute('data-target');
+ const card = this.closest('.collapsible-card');
+
+ // Toggle collapsed state
+ card.classList.toggle('collapsed');
+
+ // Save state to localStorage
+ const currentStates = JSON.parse(localStorage.getItem('collapsibleStates') || '{}');
+ currentStates[targetId] = card.classList.contains('collapsed');
+ localStorage.setItem('collapsibleStates', JSON.stringify(currentStates));
+
+ console.log(`Toggled ${targetId}: ${card.classList.contains('collapsed') ? 'collapsed' : 'expanded'}`);
+ });
+ });
+
+ console.log('Collapsible cards initialized');
}
/**
@@ -1001,34 +1524,58 @@ async function savePreferences() {
console.log('Saving preferences...');
const prefix = getPreferenceKeyPrefix();
+ // Get current UI state FIRST (before building preferencesToSave)
+ const isDark = darkModeToggleSetting ? darkModeToggleSetting.checked : false;
+ console.log(`Current dark mode UI state: ${isDark}`);
+
// --- Prepare data to save --- Add dateFormat and dark mode
const preferencesToSave = {
default_view: defaultViewSelect ? defaultViewSelect.value : 'grid',
expiring_soon_days: expiringSoonDaysInput ? parseInt(expiringSoonDaysInput.value) : 30,
date_format: dateFormatSelect ? dateFormatSelect.value : 'MDY',
- theme: (localStorage.getItem('darkMode') === 'true') ? 'dark' : 'light',
+ theme: isDark ? 'dark' : 'light', // Use current UI state, not old localStorage
+ paperless_view_in_app: paperlessViewInAppToggle ? paperlessViewInAppToggle.checked : false,
+ preferred_language: languageSelect ? languageSelect.value : 'en', // Include language preference
};
// Handle currency symbol (standard or custom)
let currencySymbol = '$'; // Default
+ let currencyCode = 'USD'; // Default
if (currencySymbolSelect) {
if (currencySymbolSelect.value === 'other' && currencySymbolCustom) {
currencySymbol = currencySymbolCustom.value.trim() || '$'; // Use custom or default to $ if empty
+ // For custom symbols, try to derive currency code or default to USD
+ currencyCode = 'USD'; // Default for custom symbols
} else {
currencySymbol = currencySymbolSelect.value;
+ // Find the currency code for the selected symbol
+ const selectedCurrency = globalCurrenciesData.find(currency => currency.symbol === currencySymbol);
+ if (selectedCurrency) {
+ currencyCode = selectedCurrency.code;
+ }
}
}
preferencesToSave.currency_symbol = currencySymbol;
+
+ // Handle currency position
+ let currencyPosition = 'left'; // Default
+ if (currencyPositionSelect) {
+ currencyPosition = currencyPositionSelect.value;
+ }
+ preferencesToSave.currency_position = currencyPosition;
// --- End data preparation ---
// +++ ADDED DEBUG LOGGING +++
console.log(`[SavePrefs Debug] Currency Select Value: ${currencySymbolSelect ? currencySymbolSelect.value : 'N/A'}`);
console.log(`[SavePrefs Debug] Custom Input Value: ${currencySymbolCustom ? currencySymbolCustom.value : 'N/A'}`);
console.log(`[SavePrefs Debug] Final currencySymbol value determined: ${currencySymbol}`);
+ console.log(`[SavePrefs Debug] Final currencyCode value determined: ${currencyCode}`);
+ console.log(`[SavePrefs Debug] Currency Position Value: ${currencyPosition}`);
+ console.log(`[SavePrefs Debug] Theme being saved: ${preferencesToSave.theme} (from isDark: ${isDark})`);
+ console.log(`[SavePrefs Debug] Language being saved: ${preferencesToSave.preferred_language}`);
// +++ END DEBUG LOGGING +++
- // Save Dark Mode separately (using the single source of truth)
- const isDark = darkModeToggleSetting ? darkModeToggleSetting.checked : false;
+ // Apply the theme to the UI (this updates localStorage too)
setTheme(isDark);
console.log(`Saved dark mode: ${isDark}`);
@@ -1036,16 +1583,21 @@ async function savePreferences() {
localStorage.setItem('dateFormat', preferencesToSave.date_format); // Added
localStorage.setItem(`${prefix}defaultView`, preferencesToSave.default_view);
localStorage.setItem(`${prefix}currencySymbol`, preferencesToSave.currency_symbol);
+ localStorage.setItem(`${prefix}currencyCode`, currencyCode); // Save currency code
+ localStorage.setItem(`${prefix}currencyPosition`, preferencesToSave.currency_position);
localStorage.setItem(`${prefix}expiringSoonDays`, preferencesToSave.expiring_soon_days);
+ localStorage.setItem(`${prefix}paperlessViewInApp`, preferencesToSave.paperless_view_in_app);
+ localStorage.setItem('preferred_language', preferencesToSave.preferred_language); // Save language preference
console.log('Preferences saved to localStorage (prefix:', prefix, '):', preferencesToSave);
console.log(`Value of dateFormat in localStorage: ${localStorage.getItem('dateFormat')}`);
// Try saving to API
- if (window.auth && window.auth.isAuthenticated()) {
+ if (window.auth && window.auth.isAuthenticated()) {
try {
showLoading();
const token = window.auth.getToken();
+ console.log('Saving preferences with token:', token ? 'present' : 'missing');
const response = await fetch('/api/auth/preferences', {
method: 'PUT',
headers: {
@@ -1059,8 +1611,31 @@ async function savePreferences() {
if (response.ok) {
showToast('Preferences saved successfully.', 'success');
console.log('Preferences successfully saved to API.');
+
+ // If language was changed, trigger the actual language change
+ if (preferencesToSave.preferred_language && window.i18n?.changeLanguage) {
+ const currentLang = window.i18n.getCurrentLanguage ? window.i18n.getCurrentLanguage() : 'en';
+ if (preferencesToSave.preferred_language !== currentLang) {
+ console.log(`Language changed from ${currentLang} to ${preferencesToSave.preferred_language}, triggering page translation`);
+ try {
+ await window.i18n.changeLanguage(preferencesToSave.preferred_language);
+ // Reload page after a short delay to apply all translations
+ setTimeout(() => {
+ window.location.reload();
+ }, 1000);
+ } catch (error) {
+ console.error('Failed to change language after saving preferences:', error);
+ }
+ }
+ }
} else {
- const errorData = await response.json().catch(() => ({}));
+ console.error('Preferences save failed. Response status:', response.status);
+ console.error('Response headers:', Object.fromEntries(response.headers.entries()));
+ const errorData = await response.json().catch((e) => {
+ console.error('Failed to parse error response as JSON:', e);
+ return {};
+ });
+ console.error('Error response data:', errorData);
throw new Error(errorData.message || `Failed to save preferences to API: ${response.status}`);
}
} catch (error) {
@@ -1098,39 +1673,34 @@ async function changePassword() {
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
- })
- });
+ 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';
- 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');
+ // Show success modal
+ openModal(passwordSuccessModal);
+ } else {
+ // Handle error
+ const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
+ throw new Error(errorData.message || 'Failed to change password');
}
} catch (error) {
console.error('Error changing password:', error);
- showToast('Failed to change password. Please try again.', 'error');
+ showToast(`Failed to change password: ${error.message}`, 'error');
} finally {
hideLoading();
}
@@ -1148,42 +1718,50 @@ async function deleteAccount() {
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');
+ const response = await fetch('/api/auth/account', {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
}
- } catch (apiError) {
- console.warn('API error, showing offline message:', apiError);
- showToast('Account cannot be deleted in offline mode', 'warning');
+ });
+
+ 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 - show the actual error message from the API
+ let errorMessage = 'Failed to delete account';
+ try {
+ const errorData = await response.json();
+ errorMessage = errorData.message || errorMessage;
+ } catch (parseError) {
+ console.warn('Could not parse error response:', parseError);
+ }
+
+ console.error('API error response:', errorMessage);
+ showToast(errorMessage, 'error');
}
} catch (error) {
- console.error('Error deleting account:', error);
- showToast('Failed to delete account. Please try again.', 'error');
+ console.error('Network error deleting account:', error);
+ // Only show offline message for actual network errors
+ if (error.name === 'TypeError' && error.message.includes('fetch')) {
+ showToast('Account cannot be deleted in offline mode', 'warning');
+ } else {
+ showToast('Failed to delete account. Please try again.', 'error');
+ }
} finally {
hideLoading();
@@ -1287,60 +1865,164 @@ async function loadUsers() {
if (response.ok) {
const users = await response.json();
+ // DEBUG: Check users data
+ console.log('DEBUG: Users data from API:', users);
+ users.forEach((user, index) => {
+ console.log(`DEBUG: User ${index} (${user.username}):`, {
+ id: user.id,
+ is_owner: user.is_owner,
+ is_admin: user.is_admin
+ });
+ });
+
// Clear table
usersTableBody.innerHTML = '';
// Add users to table
users.forEach(user => {
const row = document.createElement('tr');
+ row.style.borderBottom = '1px solid var(--border-color)';
+ row.style.transition = 'background-color 0.2s ease';
- // Username
+ // Add hover effect
+ row.addEventListener('mouseenter', () => {
+ row.style.backgroundColor = 'var(--hover-bg, rgba(0,0,0,0.05))';
+ });
+ row.addEventListener('mouseleave', () => {
+ row.style.backgroundColor = 'transparent';
+ });
+
+ // ID
+ const idCell = document.createElement('td');
+ idCell.textContent = user.id;
+ idCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-weight: 500;';
+ row.appendChild(idCell);
+
+ // Username with crown
const usernameCell = document.createElement('td');
- usernameCell.textContent = user.username;
+ const crownIcon = user.is_owner ? ' <i class="fas fa-crown" title="Application Owner" style="color: #f39c12; margin-left: 5px;"></i>' : '';
+ console.log(`DEBUG: User ${user.username} (ID: ${user.id}) - is_owner: ${user.is_owner}, adding crown: ${!!user.is_owner}`);
+ usernameCell.innerHTML = user.username + crownIcon;
+ usernameCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-weight: 500;';
row.appendChild(usernameCell);
// Email
const emailCell = document.createElement('td');
emailCell.textContent = user.email;
+ emailCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-size: 0.9em;';
row.appendChild(emailCell);
// Name
const nameCell = document.createElement('td');
const fullName = `${user.first_name || ''} ${user.last_name || ''}`.trim();
nameCell.textContent = fullName || '-';
+ nameCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color);';
row.appendChild(nameCell);
- // Status
- const statusCell = document.createElement('td');
- const statusBadge = document.createElement('span');
- statusBadge.className = `badge ${user.is_active ? 'badge-success' : 'badge-danger'}`;
- statusBadge.textContent = user.is_active ? 'Active' : 'Inactive';
- statusCell.appendChild(statusBadge);
- row.appendChild(statusCell);
-
// Admin
const adminCell = document.createElement('td');
const adminBadge = document.createElement('span');
- adminBadge.className = `badge ${user.is_admin ? 'badge-primary' : 'badge-secondary'}`;
- adminBadge.textContent = user.is_admin ? 'Admin' : 'User';
+ adminBadge.className = `badge ${user.is_admin ? 'badge-success' : 'badge-secondary'}`;
+ adminBadge.textContent = user.is_admin ? 'Yes' : 'No';
+ adminBadge.style.cssText = 'padding: 4px 8px; border-radius: 12px; font-size: 0.75em; font-weight: 600;';
adminCell.appendChild(adminBadge);
+ adminCell.style.cssText = 'padding: 12px 8px; text-align: center; border-right: 1px solid var(--border-color);';
row.appendChild(adminCell);
+ // Active Status
+ const statusCell = document.createElement('td');
+ const statusBadge = document.createElement('span');
+ statusBadge.className = `badge ${user.is_active ? 'badge-success' : 'badge-danger'}`;
+ statusBadge.textContent = user.is_active ? 'Yes' : 'No';
+ statusBadge.style.cssText = 'padding: 4px 8px; border-radius: 12px; font-size: 0.75em; font-weight: 600;';
+ statusCell.appendChild(statusBadge);
+ statusCell.style.cssText = 'padding: 12px 8px; text-align: center; border-right: 1px solid var(--border-color);';
+ row.appendChild(statusCell);
+
// Actions
const actionsCell = document.createElement('td');
+ actionsCell.style.cssText = 'padding: 12px 8px; text-align: center;';
+
+ // Create button container for better spacing
+ const buttonContainer = document.createElement('div');
+ buttonContainer.style.cssText = 'display: flex; gap: 6px; justify-content: center; align-items: center;';
// Edit button
const editBtn = document.createElement('button');
- editBtn.className = 'btn btn-sm btn-outline-primary mr-2';
+ editBtn.className = 'btn btn-sm';
editBtn.innerHTML = '<i class="fas fa-edit"></i>';
editBtn.title = 'Edit User';
+ editBtn.style.cssText = `
+ padding: 8px 10px;
+ border-radius: 6px;
+ border: 1px solid var(--primary-color, #007bff);
+ background-color: transparent;
+ color: var(--primary-color, #007bff);
+ transition: all 0.2s ease;
+ cursor: pointer;
+ min-width: 36px;
+ height: 36px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ `;
+
+ // Edit button hover effects
+ editBtn.addEventListener('mouseenter', () => {
+ if (!editBtn.disabled) {
+ editBtn.style.backgroundColor = 'var(--primary-color, #007bff)';
+ editBtn.style.color = 'white';
+ editBtn.style.transform = 'translateY(-1px)';
+ editBtn.style.boxShadow = '0 2px 4px rgba(0,123,255,0.3)';
+ }
+ });
+ editBtn.addEventListener('mouseleave', () => {
+ if (!editBtn.disabled) {
+ editBtn.style.backgroundColor = 'transparent';
+ editBtn.style.color = 'var(--primary-color, #007bff)';
+ editBtn.style.transform = 'translateY(0)';
+ editBtn.style.boxShadow = 'none';
+ }
+ });
editBtn.addEventListener('click', () => openEditUserModal(user));
// Delete button
const deleteBtn = document.createElement('button');
- deleteBtn.className = 'btn btn-sm btn-outline-danger';
+ deleteBtn.className = 'btn btn-sm';
deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i>';
deleteBtn.title = 'Delete User';
+ deleteBtn.style.cssText = `
+ padding: 8px 10px;
+ border-radius: 6px;
+ border: 1px solid var(--danger-color, #dc3545);
+ background-color: transparent;
+ color: var(--danger-color, #dc3545);
+ transition: all 0.2s ease;
+ cursor: pointer;
+ min-width: 36px;
+ height: 36px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ `;
+
+ // Delete button hover effects
+ deleteBtn.addEventListener('mouseenter', () => {
+ if (!deleteBtn.disabled) {
+ deleteBtn.style.backgroundColor = 'var(--danger-color, #dc3545)';
+ deleteBtn.style.color = 'white';
+ deleteBtn.style.transform = 'translateY(-1px)';
+ deleteBtn.style.boxShadow = '0 2px 4px rgba(220,53,69,0.3)';
+ }
+ });
+ deleteBtn.addEventListener('mouseleave', () => {
+ if (!deleteBtn.disabled) {
+ deleteBtn.style.backgroundColor = 'transparent';
+ deleteBtn.style.color = 'var(--danger-color, #dc3545)';
+ deleteBtn.style.transform = 'translateY(0)';
+ deleteBtn.style.boxShadow = 'none';
+ }
+ });
// Add multiple event handlers for redundancy
deleteBtn.addEventListener('click', (event) => {
@@ -1359,24 +2041,50 @@ async function loadUsers() {
return false;
};
- // Don't allow editing or deleting self
+ // Don't allow editing or deleting self, and disable actions for the owner
const currentUser = window.auth.getCurrentUser();
- if (user.id === currentUser.id) {
+ const isOwner = user.is_owner;
+ const isCurrentUser = (user.id === currentUser.id);
+
+ console.log(`DEBUG: Button logic for ${user.username} - isOwner: ${isOwner}, isCurrentUser: ${isCurrentUser}, currentUser.id: ${currentUser?.id}, user.id: ${user.id}`);
+
+ if (isOwner || isCurrentUser) {
editBtn.disabled = true;
deleteBtn.disabled = true;
- editBtn.title = 'Cannot edit yourself';
- deleteBtn.title = 'Cannot delete yourself';
- console.log('Disabled edit/delete for current user:', currentUser.id);
+ editBtn.title = isOwner ? 'Cannot edit the application owner' : 'Cannot edit yourself';
+ deleteBtn.title = isOwner ? 'Cannot delete the application owner' : 'Cannot delete yourself';
+
+ // Enhanced disabled styling
+ editBtn.style.opacity = '0.4';
+ editBtn.style.cursor = 'not-allowed';
+ editBtn.style.border = '1px solid var(--text-muted, #6c757d)';
+ editBtn.style.color = 'var(--text-muted, #6c757d)';
+
+ deleteBtn.style.opacity = '0.4';
+ deleteBtn.style.cursor = 'not-allowed';
+ deleteBtn.style.border = '1px solid var(--text-muted, #6c757d)';
+ deleteBtn.style.color = 'var(--text-muted, #6c757d)';
+
+ console.log('DEBUG: Disabled edit/delete for', isOwner ? 'owner' : 'current user', ':', user.id);
+ } else {
+ console.log('DEBUG: Buttons enabled for user:', user.id);
}
- actionsCell.appendChild(editBtn);
- actionsCell.appendChild(deleteBtn);
+ // Add buttons to container
+ buttonContainer.appendChild(editBtn);
+ buttonContainer.appendChild(deleteBtn);
+
+ // Add container to cell
+ actionsCell.appendChild(buttonContainer);
row.appendChild(actionsCell);
usersTableBody.appendChild(row);
});
console.log('Users loaded successfully:', users.length);
+
+ // Set up ownership management after loading users
+ setupOwnershipManagement(users);
} else {
console.error('Failed to load users:', response.status);
showToast('Failed to load users', 'error');
@@ -1678,6 +2386,157 @@ function deleteUser() {
console.log('=== DELETE USER FUNCTION COMPLETED ===');
}
+/**
+ * Set up ownership management functionality
+ * @param {Array} users - List of all users
+ */
+function setupOwnershipManagement(users) {
+ const currentUser = window.auth.getCurrentUser();
+ const ownershipCard = document.getElementById('ownershipCard');
+ const newOwnerSelect = document.getElementById('newOwnerSelect');
+ const transferOwnershipBtn = document.getElementById('transferOwnershipBtn');
+
+ // DEBUG: Check ownership management setup
+ console.log('DEBUG: setupOwnershipManagement called');
+ console.log('DEBUG: currentUser:', currentUser);
+ console.log('DEBUG: currentUser.is_owner:', currentUser ? currentUser.is_owner : 'no currentUser');
+ console.log('DEBUG: ownershipCard element:', ownershipCard);
+
+ if (!currentUser || !currentUser.is_owner) {
+ // Hide ownership section if user is not the owner
+ console.log('DEBUG: Hiding ownership section - user is not owner');
+ const ownershipSection = document.getElementById('ownershipSection');
+ if (ownershipSection) {
+ ownershipSection.style.display = 'none';
+ }
+ return;
+ }
+
+ // Show ownership section for the owner
+ const ownershipSection = document.getElementById('ownershipSection');
+ if (ownershipSection) {
+ ownershipSection.style.display = 'block';
+ }
+
+ // Populate the select dropdown with admin users (excluding current owner)
+ if (newOwnerSelect) {
+ newOwnerSelect.innerHTML = '<option value="">Select an admin user...</option>';
+
+ users.forEach(user => {
+ if (user.is_admin && user.id !== currentUser.id && user.is_active && !user.is_owner) {
+ const option = document.createElement('option');
+ option.value = user.id;
+ option.textContent = `${user.username} (${user.email})`;
+ newOwnerSelect.appendChild(option);
+ }
+ });
+
+ // Enable/disable transfer button based on selection
+ newOwnerSelect.addEventListener('change', function() {
+ if (transferOwnershipBtn) {
+ transferOwnershipBtn.disabled = !this.value;
+ }
+ });
+ }
+
+ // Set up transfer button click handler
+ if (transferOwnershipBtn) {
+ transferOwnershipBtn.addEventListener('click', function() {
+ const selectedUserId = newOwnerSelect.value;
+ if (!selectedUserId) {
+ showToast('Please select a user to transfer ownership to', 'error');
+ return;
+ }
+
+ const selectedUser = users.find(u => u.id == selectedUserId);
+ if (selectedUser) {
+ openTransferOwnershipModal(selectedUser);
+ }
+ });
+ }
+}
+
+/**
+ * Open the transfer ownership confirmation modal
+ * @param {Object} targetUser - The user to transfer ownership to
+ */
+function openTransferOwnershipModal(targetUser) {
+ const modal = document.getElementById('transferOwnershipModal');
+ const targetUsernameSpan = document.getElementById('transferTargetUsername');
+ const confirmInput = document.getElementById('transferConfirmInput');
+ const confirmBtn = document.getElementById('confirmTransferOwnershipBtn');
+
+ if (!modal || !targetUsernameSpan || !confirmInput || !confirmBtn) {
+ showToast('Error: Transfer ownership modal elements not found', 'error');
+ return;
+ }
+
+ // Set target username
+ targetUsernameSpan.textContent = targetUser.username;
+
+ // Clear and set up confirm input
+ confirmInput.value = '';
+ confirmInput.addEventListener('input', function() {
+ confirmBtn.disabled = this.value.toUpperCase() !== 'TRANSFER';
+ });
+
+ // Set up confirm button
+ confirmBtn.disabled = true;
+ confirmBtn.onclick = function() {
+ if (confirmInput.value.toUpperCase() === 'TRANSFER') {
+ performOwnershipTransfer(targetUser.id);
+ }
+ };
+
+ // Show modal
+ modal.style.display = 'flex';
+}
+
+/**
+ * Perform the actual ownership transfer
+ * @param {number} newOwnerId - ID of the user to transfer ownership to
+ */
+async function performOwnershipTransfer(newOwnerId) {
+ const modal = document.getElementById('transferOwnershipModal');
+
+ try {
+ showLoading();
+
+ const response = await fetch('/api/admin/transfer-ownership', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ new_owner_id: newOwnerId
+ })
+ });
+
+ if (response.ok) {
+ showToast('Ownership transferred successfully! Refreshing page...', 'success');
+
+ // Close modal
+ if (modal) {
+ modal.style.display = 'none';
+ }
+
+ // Refresh the page after a short delay to allow the user to see the success message
+ setTimeout(() => {
+ window.location.reload();
+ }, 2000);
+ } else {
+ const errorData = await response.json();
+ showToast(errorData.message || 'Failed to transfer ownership', 'error');
+ }
+ } catch (error) {
+ console.error('Error transferring ownership:', error);
+ showToast('Failed to transfer ownership. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
/**
* Super emergency delete function for user deletion
* @param {string|number} userId - The user ID or username to delete
@@ -2374,17 +3233,30 @@ function closeAllModals() {
*/
async function loadSiteSettings() {
console.log('Loading site settings...');
- const adminSection = document.getElementById('adminSection');
- const registrationToggle = document.getElementById('registrationEnabled');
- const emailBaseUrlField = document.getElementById('emailBaseUrl'); // Correct variable name
-
- // // Check if admin section exists
- // if (!adminSection) {
- // console.log('Admin section not found, skipping site settings load');
- // return;
- // }
+
+ // Enhanced debugging for element availability
+ console.log('[SiteSettings Debug] DOM readiness check:');
+ console.log(' - document.readyState:', document.readyState);
+ console.log(' - adminSection exists:', !!document.getElementById('adminSection'));
+ console.log(' - registrationEnabled exists:', !!document.getElementById('registrationEnabled'));
+ console.log(' - oidcEnabled exists:', !!document.getElementById('oidcEnabled'));
+ console.log(' - oidcProviderName exists:', !!document.getElementById('oidcProviderName'));
+ console.log(' - oidcClientId exists:', !!document.getElementById('oidcClientId'));
+
+ // Query elements locally within this function scope for population
+ const registrationToggleElem = document.getElementById('registrationEnabled');
+ const emailBaseUrlFieldElem = document.getElementById('emailBaseUrl');
+ const globalViewToggleElem = document.getElementById('globalViewEnabled');
+ const globalViewAdminOnlyToggleElem = document.getElementById('globalViewAdminOnly');
+ const oidcEnabledToggleElem = document.getElementById('oidcEnabled');
+ const oidcOnlyModeToggleElem = document.getElementById('oidcOnlyMode');
+ const oidcProviderNameInputElem = document.getElementById('oidcProviderName');
+ const oidcClientIdInputElem = document.getElementById('oidcClientId');
+ const oidcClientSecretInputElem = document.getElementById('oidcClientSecret');
+ const oidcIssuerUrlInputElem = document.getElementById('oidcIssuerUrl');
+ const oidcScopeInputElem = document.getElementById('oidcScope');
- try { // Correct structure: try block starts
+ try {
showLoading();
const response = await fetch('/api/admin/settings', {
@@ -2395,80 +3267,172 @@ async function loadSiteSettings() {
}
});
+ if (response.status === 403) {
+ // User is not admin, hide admin settings sections
+ console.log('User is not admin, hiding admin settings sections');
+ const adminSection = document.getElementById('adminSection');
+ if (adminSection) {
+ adminSection.style.display = 'none';
+ }
+ return;
+ }
+
if (!response.ok) {
throw new Error(`Failed to load site settings: ${response.status} ${response.statusText}`);
}
const settings = await response.json();
+ console.log('[SiteSettings] Raw settings received from API:', settings);
- if (registrationToggle) {
- registrationToggle.checked = settings.registration_enabled === 'true';
+ if (registrationToggleElem) {
+ registrationToggleElem.checked = settings.registration_enabled === 'true';
+ } else {
+ console.error('[SiteSettings] registrationEnabled element NOT FOUND locally.');
}
- if (emailBaseUrlField) { // Use correct variable name
- emailBaseUrlField.value = settings.email_base_url || 'http://localhost:8080'; // Set the value
+ if (emailBaseUrlFieldElem) {
+ emailBaseUrlFieldElem.value = settings.email_base_url || 'http://localhost:8080';
+ } else {
+ console.error('[SiteSettings] emailBaseUrl element NOT FOUND locally.');
+ }
+
+ if (globalViewToggleElem) {
+ globalViewToggleElem.checked = settings.global_view_enabled === 'true';
+ } else {
+ console.error('[SiteSettings] globalViewEnabled element NOT FOUND locally.');
+ }
+
+ if (globalViewAdminOnlyToggleElem) {
+ globalViewAdminOnlyToggleElem.checked = settings.global_view_admin_only === 'true';
+ } else {
+ console.error('[SiteSettings] globalViewAdminOnly element NOT FOUND locally.');
+ }
+
+ // Populate OIDC settings using locally-scoped element variables
+ if (oidcEnabledToggleElem) {
+ console.log('[OIDC Settings] Found oidcEnabledToggleElem. Setting checked to:', settings.oidc_enabled === 'true');
+ oidcEnabledToggleElem.checked = settings.oidc_enabled === 'true';
+ } else {
+ console.error('[OIDC Settings] oidcEnabledToggleElem element NOT FOUND locally.');
+ }
+
+ if (oidcOnlyModeToggleElem) {
+ console.log('[OIDC Settings] Found oidcOnlyModeToggleElem. Setting checked to:', settings.oidc_only_mode === 'true');
+ oidcOnlyModeToggleElem.checked = settings.oidc_only_mode === 'true';
+ } else {
+ console.error('[OIDC Settings] oidcOnlyModeToggleElem element NOT FOUND locally.');
+ }
+
+ if (oidcProviderNameInputElem) {
+ console.log('[OIDC Settings] Found oidcProviderNameInputElem. Setting value to:', settings.oidc_provider_name || 'oidc');
+ oidcProviderNameInputElem.value = settings.oidc_provider_name || 'oidc';
+ } else {
+ console.error('[OIDC Settings] oidcProviderNameInputElem element NOT FOUND locally.');
+ }
+
+ if (oidcClientIdInputElem) {
+ console.log('[OIDC Settings] Found oidcClientIdInputElem. Setting value to:', settings.oidc_client_id || '');
+ oidcClientIdInputElem.value = settings.oidc_client_id || '';
+ } else {
+ console.error('[OIDC Settings] oidcClientIdInputElem element NOT FOUND locally.');
+ }
+
+ if (oidcClientSecretInputElem) {
+ console.log('[OIDC Settings] Found oidcClientSecretInputElem. Setting placeholder based on oidc_client_secret_set:', settings.oidc_client_secret_set);
+ oidcClientSecretInputElem.value = ''; // Always clear on load
+ oidcClientSecretInputElem.placeholder = settings.oidc_client_secret_set ? '******** (Set - Enter new to change)' : 'Enter OIDC Client Secret';
+ } else {
+ console.error('[OIDC Settings] oidcClientSecretInputElem element NOT FOUND locally.');
+ }
+
+ if (oidcIssuerUrlInputElem) {
+ console.log('[OIDC Settings] Found oidcIssuerUrlInputElem. Setting value to:', settings.oidc_issuer_url || '');
+ oidcIssuerUrlInputElem.value = settings.oidc_issuer_url || '';
+ } else {
+ console.error('[OIDC Settings] oidcIssuerUrlInputElem element NOT FOUND locally.');
+ }
+
+ if (oidcScopeInputElem) {
+ console.log('[OIDC Settings] Found oidcScopeInputElem. Setting value to:', settings.oidc_scope || 'openid email profile');
+ oidcScopeInputElem.value = settings.oidc_scope || 'openid email profile';
+ } else {
+ console.error('[OIDC Settings] oidcScopeInputElem element NOT FOUND locally.');
}
- console.log('Site settings loaded successfully', settings);
+ console.log('Site and OIDC settings loaded and population attempted using locally queried elements.');
- } catch (error) { // Correct structure: catch block follows try
- console.error('Error loading site settings:', error);
+ } catch (error) {
+ console.error('Error loading or populating site settings:', error);
showToast('Failed to load site settings. Please try again.', 'error');
- } finally { // Correct structure: finally block follows catch
+ } finally {
hideLoading();
}
}
/**
- * Save site settings
+ * Save site settings (non-OIDC part)
*/
async function saveSiteSettings() {
- console.log('Saving site settings...');
+ console.log('Saving site settings (non-OIDC)...');
const registrationToggle = document.getElementById('registrationEnabled');
- const emailBaseUrlField = document.getElementById('emailBaseUrl'); // Get the new field
+ const emailBaseUrlField = document.getElementById('emailBaseUrl');
+ const globalViewToggle = document.getElementById('globalViewEnabled');
+ const globalViewAdminOnlyToggle = document.getElementById('globalViewAdminOnly');
- const settings = {};
+ const settingsToSave = {};
if (registrationToggle) {
- settings.registration_enabled = registrationToggle.checked; // Boolean value will be converted to string in backend
+ settingsToSave.registration_enabled = registrationToggle.checked;
+ }
+
+ if (globalViewToggle) {
+ settingsToSave.global_view_enabled = globalViewToggle.checked;
+ }
+
+ if (globalViewAdminOnlyToggle) {
+ settingsToSave.global_view_admin_only = globalViewAdminOnlyToggle.checked;
}
if (emailBaseUrlField) {
let baseUrl = emailBaseUrlField.value.trim();
- // Basic validation: check if it looks somewhat like a URL
if (baseUrl && (baseUrl.startsWith('http://') || baseUrl.startsWith('https://'))) {
- // Remove trailing slash if present
if (baseUrl.endsWith('/')) {
baseUrl = baseUrl.slice(0, -1);
}
- settings.email_base_url = baseUrl;
+ settingsToSave.email_base_url = baseUrl;
} else if (baseUrl) {
showToast('Invalid Email Base URL format. It should start with http:// or https://', 'error');
- return; // Stop saving if format is invalid
+ return;
} else {
- settings.email_base_url = 'http://localhost:8080'; // Use default if empty
- emailBaseUrlField.value = settings.email_base_url; // Update field with default
+ settingsToSave.email_base_url = 'http://localhost:8080';
+ emailBaseUrlField.value = settingsToSave.email_base_url;
}
}
-
+
+ if (Object.keys(settingsToSave).length === 0) {
+ showToast('No site settings to save.', 'info');
+ return;
+ }
try {
showLoading();
-
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ console.log('Saving site settings with token:', token ? 'present' : 'missing');
+
const response = await fetch('/api/admin/settings', {
method: 'PUT',
headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
- body: JSON.stringify(settings)
+ body: JSON.stringify(settingsToSave)
});
+ const result = await response.json();
if (response.ok) {
- showToast('Site settings saved successfully', 'success');
+ showToast(result.message || 'Site settings saved successfully', 'success');
} else {
- const errorData = await response.json();
- showToast(errorData.message || 'Failed to save site settings', 'error');
+ showToast(result.message || 'Failed to save site settings', 'error');
}
} catch (error) {
console.error('Error saving site settings:', error);
@@ -2478,6 +3442,63 @@ async function saveSiteSettings() {
}
}
+
+/**
+ * Save OIDC settings
+ */
+async function saveOidcSettings() {
+ console.log('Saving OIDC settings...');
+ const oidcSettingsPayload = {
+ oidc_enabled: oidcEnabledToggle ? oidcEnabledToggle.checked : false,
+ oidc_only_mode: oidcOnlyModeToggle ? oidcOnlyModeToggle.checked : false,
+ oidc_provider_name: oidcProviderNameInput ? oidcProviderNameInput.value.trim() : 'oidc',
+ oidc_client_id: oidcClientIdInput ? oidcClientIdInput.value.trim() : '',
+ oidc_issuer_url: oidcIssuerUrlInput ? oidcIssuerUrlInput.value.trim() : '',
+ oidc_scope: oidcScopeInput ? oidcScopeInput.value.trim() : 'openid email profile',
+ };
+
+ // Only include client_secret if a new value is entered
+ if (oidcClientSecretInput && oidcClientSecretInput.value) {
+ oidcSettingsPayload.oidc_client_secret = oidcClientSecretInput.value;
+ }
+
+ try {
+ showLoading();
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ console.log('Saving OIDC settings with token:', token ? 'present' : 'missing');
+
+ const response = await fetch('/api/admin/settings', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(oidcSettingsPayload)
+ });
+
+ const result = await response.json();
+ if (response.ok) {
+ showToast(result.message || 'OIDC settings saved successfully.', 'success');
+ if (result.message && result.message.includes("restart is required")) {
+ if(oidcRestartMessage) oidcRestartMessage.style.display = 'block';
+ } else {
+ if(oidcRestartMessage) oidcRestartMessage.style.display = 'none';
+ }
+ // Clear the secret field after attempting to save
+ if (oidcClientSecretInput) oidcClientSecretInput.value = '';
+ // Reload settings to get the oidc_client_secret_set flag updated
+ loadSiteSettings();
+ } else {
+ showToast(result.message || 'Failed to save OIDC settings.', 'error');
+ }
+ } catch (error) {
+ console.error('Error saving OIDC settings:', error);
+ showToast('Failed to save OIDC settings. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
/**
* Set up the delete button for user deletion
*/
@@ -2769,12 +3790,91 @@ async function triggerWarrantyNotifications() {
}
}
+/**
+ * Check scheduler status (admin only)
+ */
+async function checkSchedulerStatus() {
+ console.log('Checking scheduler status...');
+
+ try {
+ showLoading();
+
+ const response = await fetch('/api/admin/scheduler-status', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({ message: 'Unknown error occurred' }));
+ throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
+ }
+
+ const status = await response.json();
+ console.log('Scheduler status:', status);
+
+ // Format the status information for display
+ let message = '📊 Scheduler Status Report\n\n';
+ message += `🚀 Initialized: ${status.scheduler_initialized ? '✅ Yes' : '❌ No'}\n`;
+ message += `🔄 Running: ${status.scheduler_running ? '✅ Yes' : '❌ No'}\n`;
+ message += `📋 Active Jobs: ${status.scheduler_jobs.length}\n`;
+
+ if (status.scheduler_jobs.length > 0) {
+ message += '\n📅 Scheduled Jobs:\n';
+ status.scheduler_jobs.forEach(job => {
+ const nextRun = job.next_run_time ?
+ new Date(job.next_run_time).toLocaleString() :
+ 'Not scheduled';
+ message += `• ${job.id}: ${nextRun}\n`;
+ message += ` Trigger: ${job.trigger}\n`;
+ });
+ }
+
+ message += `\n🔧 Worker Information:\n`;
+ message += `• Worker ID: ${status.worker_info.worker_id}\n`;
+ message += `• Worker Name: ${status.worker_info.worker_name}\n`;
+ message += `• Worker Class: ${status.worker_info.worker_class}\n`;
+ message += `• Should Run Scheduler: ${status.worker_info.should_run_scheduler ? '✅ Yes' : '❌ No'}\n`;
+
+ if (status.environment_vars && Object.keys(status.environment_vars).length > 0) {
+ message += `\n🌍 Environment Variables:\n`;
+ Object.entries(status.environment_vars).forEach(([key, value]) => {
+ message += `• ${key}: ${value}\n`;
+ });
+ }
+
+ // Show in alert dialog
+ alert(message);
+
+ // Also show a toast with a summary
+ const summary = status.scheduler_running ?
+ '✅ Scheduler is running normally' :
+ '⚠️ Scheduler is not running - notifications may not be sent automatically';
+ showToast(summary, status.scheduler_running ? 'success' : 'warning', 8000);
+
+ } catch (error) {
+ console.error('Error checking scheduler status:', error);
+ showToast(`Error checking scheduler status: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
/**
* Load available timezones from the API
* @returns {Promise} A promise that resolves when timezones are loaded
*/
function loadTimezones() {
- console.log('Loading timezones...');
+ return loadTimezonesIntoSelect(timezoneSelect);
+}
+
+function loadTimezonesIntoSelect(selectElement) {
+ if (!selectElement) {
+ return Promise.reject('Select element not provided to loadTimezonesIntoSelect');
+ }
+ console.log(`Loading timezones into ${selectElement.id}...`);
return new Promise((resolve, reject) => {
fetch('/api/timezones', {
method: 'GET',
@@ -2791,7 +3891,7 @@ function loadTimezones() {
})
.then(timezoneGroups => {
// Clear loading option
- timezoneSelect.innerHTML = '';
+ selectElement.innerHTML = '';
// Add timezone groups and their options
timezoneGroups.forEach(group => {
@@ -2805,7 +3905,7 @@ function loadTimezones() {
optgroup.appendChild(option);
});
- timezoneSelect.appendChild(optgroup);
+ selectElement.appendChild(optgroup);
});
// Set the current timezone from preferences
@@ -2820,8 +3920,8 @@ function loadTimezones() {
});
if (savedPreferences.timezone) {
- timezoneSelect.value = savedPreferences.timezone;
- console.log('Set timezone select to:', savedPreferences.timezone, 'Current value:', timezoneSelect.value);
+ selectElement.value = savedPreferences.timezone;
+ console.log(`Set ${selectElement.id} to:`, savedPreferences.timezone, 'Current value:', selectElement.value);
resolve();
} else {
// If no timezone preference found in localStorage, load from API as backup
@@ -2838,8 +3938,8 @@ function loadTimezones() {
// API returns preferences directly, not nested
if (data && data.timezone) {
console.log('Received timezone from API:', data.timezone);
- timezoneSelect.value = data.timezone;
- console.log('Set timezone select to:', data.timezone, 'Current value:', timezoneSelect.value);
+ selectElement.value = data.timezone;
+ console.log(`Set ${selectElement.id} to:`, data.timezone, 'Current value:', selectElement.value);
}
resolve();
})
@@ -2851,7 +3951,7 @@ function loadTimezones() {
})
.catch(error => {
console.error('Error loading timezones:', error);
- timezoneSelect.innerHTML = '<option value="UTC">UTC (Coordinated Universal Time)</option>';
+ selectElement.innerHTML = '<option value="UTC">UTC (Coordinated Universal Time)</option>';
reject(error);
});
});
@@ -2860,73 +3960,51 @@ function loadTimezones() {
/**
* Save email settings
*/
-function saveEmailSettings() {
+function toggleNotificationSettings(channel) {
+ if (emailSettingsContainer) {
+ emailSettingsContainer.style.display = (channel === 'email' || channel === 'both') ? 'block' : 'none';
+ }
+ if (userAppriseSettingsContainer) {
+ userAppriseSettingsContainer.style.display = (channel === 'apprise' || channel === 'both') ? 'block' : 'none';
+ }
+}
+
+async function saveNotificationSettings() {
showLoading();
try {
- // Get values
- const emailNotifications = emailNotificationsToggle.checked;
- const notificationFrequency = notificationFrequencySelect.value;
- const notificationTime = notificationTimeInput.value;
- const timezone = timezoneSelect.value;
-
- // Validate inputs
- if (!timezone) {
- showToast('Please select a timezone', 'error');
- hideLoading();
- return;
- }
-
- // Create preferences object
const preferences = {
- email_notifications: emailNotifications,
- notification_frequency: notificationFrequency,
- notification_time: notificationTime,
- timezone: timezone
+ notification_channel: notificationChannel.value,
+ notification_frequency: notificationFrequencySelect.value,
+ notification_time: notificationTimeInput.value,
+ apprise_notification_time: userAppriseNotificationTimeInput ? userAppriseNotificationTimeInput.value : '09:00',
+ apprise_notification_frequency: userAppriseNotificationFrequency ? userAppriseNotificationFrequency.value : 'daily',
+ timezone: timezoneSelect.value,
+ apprise_timezone: userAppriseTimezoneSelect ? userAppriseTimezoneSelect.value : 'UTC'
};
+
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ console.log('Saving notification settings with token:', token ? 'present' : 'missing');
- // Save to API
- fetch('/api/auth/preferences', {
+ const response = await fetch('/api/auth/preferences', {
method: 'PUT',
headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(preferences)
- })
- .then(response => {
- if (!response.ok) {
- throw new Error('Failed to save email settings');
- }
- return response.json();
- })
- .then(data => {
- // Save to localStorage
- const prefix = getPreferenceKeyPrefix();
- localStorage.setItem(`${prefix}emailNotifications`, emailNotifications);
- localStorage.setItem(`${prefix}notificationFrequency`, notificationFrequency);
- localStorage.setItem(`${prefix}notificationTime`, notificationTime);
- localStorage.setItem(`${prefix}timezone`, timezone);
-
- showToast('Email settings saved successfully', 'success');
- })
- .catch(error => {
- console.error('Error saving email settings:', error);
- showToast('Error saving email settings', 'error');
-
- // Save to localStorage as fallback
- const prefix = getPreferenceKeyPrefix();
- localStorage.setItem(`${prefix}emailNotifications`, emailNotifications);
- localStorage.setItem(`${prefix}notificationFrequency`, notificationFrequency);
- localStorage.setItem(`${prefix}notificationTime`, notificationTime);
- localStorage.setItem(`${prefix}timezone`, timezone);
- })
- .finally(() => {
- hideLoading();
});
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.message || 'Failed to save notification settings');
+ }
+
+ showToast('Notification settings saved successfully', 'success');
} catch (error) {
- console.error('Error in saveEmailSettings:', error);
- showToast('Error saving email settings', 'error');
+ console.error('Error saving notification settings:', error);
+ showToast(`Error saving notification settings: ${error.message}`, 'error');
+ } finally {
hideLoading();
}
}
@@ -3007,6 +4085,15 @@ window.addEventListener('storage', (event) => {
}
}
+ // Add check for currencyPosition
+ if (event.key === `${prefix}currencyPosition`) {
+ console.log(`[Settings Storage Listener] ${prefix}currencyPosition changed to ${event.newValue}`);
+ if (event.newValue && currencyPositionSelect && currencyPositionSelect.value !== event.newValue) {
+ currencyPositionSelect.value = event.newValue;
+ console.log('[Settings Storage Listener] Updated settings currency position dropdown via storage event.');
+ }
+ }
+
});
// --- End Storage Event Listener ---
@@ -3021,4 +4108,924 @@ if (currencySymbolSelect && currencySymbolCustom) {
currencySymbolCustom.value = '';
}
});
-}
\ No newline at end of file
+}
+
+// =====================
+// APPRISE NOTIFICATIONS FUNCTIONALITY
+// =====================
+
+/**
+ * Load Apprise settings and status
+ */
+async function loadAppriseSettings() {
+ try {
+ // Get current Apprise status
+ const statusResponse = await fetch('/api/admin/apprise/status', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (statusResponse.status === 403) {
+ // User is not admin, hide Apprise section
+ const appriseCard = document.querySelector('.card:has(#appriseStatusBadge)');
+ if (appriseCard) {
+ appriseCard.style.display = 'none';
+ }
+ return;
+ }
+
+ if (statusResponse.status === 503) {
+ // Apprise not available
+ if (appriseNotAvailable) appriseNotAvailable.style.display = 'block';
+ if (appriseStatusBadge) appriseStatusBadge.textContent = 'Not Available';
+ if (appriseStatusBadge) appriseStatusBadge.className = 'badge badge-danger';
+ return;
+ }
+
+ const statusData = await statusResponse.json();
+
+ // Update status badge
+ if (appriseStatusBadge) {
+ if (statusData.available && statusData.enabled) {
+ appriseStatusBadge.textContent = 'Active';
+ appriseStatusBadge.className = 'badge badge-success';
+ } else if (statusData.available) {
+ appriseStatusBadge.textContent = 'Disabled';
+ appriseStatusBadge.className = 'badge badge-warning';
+ } else {
+ appriseStatusBadge.textContent = 'Not Available';
+ appriseStatusBadge.className = 'badge badge-danger';
+ }
+ }
+
+ // Update status display
+ if (appriseUrlsCount) appriseUrlsCount.textContent = statusData.urls_configured || 0;
+ if (currentAppriseExpirationDays) currentAppriseExpirationDays.textContent = statusData.expiration_days ? statusData.expiration_days.join(', ') : '-';
+
+ // Load settings from site settings
+ await loadAppriseSiteSettings();
+
+ } catch (error) {
+ console.error('Error loading Apprise settings:', error);
+ if (appriseStatusBadge) {
+ appriseStatusBadge.textContent = 'Error';
+ appriseStatusBadge.className = 'badge badge-danger';
+ }
+ }
+}
+
+/**
+ * Load Apprise site settings
+ */
+async function loadAppriseSiteSettings() {
+ try {
+ console.log('📥 Loading Apprise site settings...');
+ const response = await fetch('/api/admin/settings', {
+ method: 'GET',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ console.log('📥 Load response status:', response.status);
+
+ if (!response.ok) {
+ console.warn('⚠️ Load response not OK, skipping settings load');
+ return;
+ }
+
+ const data = await response.json();
+ console.log('📥 Loaded settings data:', data);
+
+ // Check if Apprise settings exist in the data
+ const appriseKeys = Object.keys(data).filter(key => key.startsWith('apprise_'));
+ console.log('📥 Found Apprise keys:', appriseKeys);
+
+ // Update form fields
+ if (appriseEnabledToggle && data.apprise_enabled !== undefined) {
+ appriseEnabledToggle.checked = data.apprise_enabled === 'true';
+ console.log('✅ Set appriseEnabled:', data.apprise_enabled);
+
+ // Show/hide settings container based on enabled state
+ const settingsContainer = document.getElementById('appriseSettingsContainer');
+ if (settingsContainer) {
+ settingsContainer.style.display = data.apprise_enabled === 'true' ? 'block' : 'none';
+ }
+ } else {
+ console.log('⚠️ appriseEnabled element not found or apprise_enabled data missing');
+ }
+
+ if (appriseUrlsTextarea && data.apprise_urls) {
+ appriseUrlsTextarea.value = data.apprise_urls.replace(/,/g, '\n');
+ console.log('✅ Set appriseUrls:', data.apprise_urls);
+ } else {
+ console.log('⚠️ appriseUrlsTextarea element not found or apprise_urls data missing');
+ }
+
+ if (appriseExpirationDaysInput && data.apprise_expiration_days) {
+ appriseExpirationDaysInput.value = data.apprise_expiration_days;
+ console.log('✅ Set appriseExpirationDays:', data.apprise_expiration_days);
+ } else {
+ console.log('⚠️ appriseExpirationDaysInput element not found or data missing');
+ }
+
+
+
+ if (appriseTitlePrefixInput && data.apprise_title_prefix) {
+ appriseTitlePrefixInput.value = data.apprise_title_prefix;
+ console.log('✅ Set appriseTitlePrefix:', data.apprise_title_prefix);
+ } else {
+ console.log('⚠️ appriseTitlePrefixInput element not found or data missing');
+ }
+
+ if (appriseNotificationModeSelect && data.apprise_notification_mode) {
+ appriseNotificationModeSelect.value = data.apprise_notification_mode;
+ updateAppriseModeDescription(data.apprise_notification_mode);
+ console.log('✅ Set appriseNotificationMode:', data.apprise_notification_mode);
+ } else {
+ console.log('⚠️ appriseNotificationModeSelect element not found or data missing');
+ // Set default mode if not found
+ if (appriseNotificationModeSelect) {
+ appriseNotificationModeSelect.value = 'global';
+ updateAppriseModeDescription('global');
+ }
+ }
+
+ if (appriseWarrantyScopeSelect && data.apprise_warranty_scope) {
+ appriseWarrantyScopeSelect.value = data.apprise_warranty_scope;
+ updateAppriseScopeDescription(data.apprise_warranty_scope);
+ console.log('✅ Set appriseWarrantyScope:', data.apprise_warranty_scope);
+ } else {
+ console.log('⚠️ appriseWarrantyScopeSelect element not found or data missing');
+ // Set default scope if not found
+ if (appriseWarrantyScopeSelect) {
+ appriseWarrantyScopeSelect.value = 'all';
+ updateAppriseScopeDescription('all');
+ }
+ }
+
+ } catch (error) {
+ console.error('❌ Error loading Apprise site settings:', error);
+ }
+}
+
+/**
+ * Save Apprise settings
+ */
+async function saveAppriseSettings() {
+ try {
+ console.log('🔍 Starting saveAppriseSettings...');
+ showLoading();
+
+ // Process URLs - convert newlines to commas and clean up
+ const urlsText = appriseUrlsTextarea ? appriseUrlsTextarea.value : '';
+ const urls = urlsText.split(/[\n,]/)
+ .map(url => url.trim())
+ .filter(url => url.length > 0)
+ .join(',');
+
+ const settings = {
+ apprise_enabled: appriseEnabledToggle ? appriseEnabledToggle.checked.toString() : 'false',
+ apprise_notification_mode: appriseNotificationModeSelect ? appriseNotificationModeSelect.value : 'global',
+ apprise_warranty_scope: appriseWarrantyScopeSelect ? appriseWarrantyScopeSelect.value : 'all',
+ apprise_urls: urls,
+ apprise_expiration_days: appriseExpirationDaysInput ? appriseExpirationDaysInput.value : '7,30',
+ apprise_title_prefix: appriseTitlePrefixInput ? appriseTitlePrefixInput.value : '[Warracker]'
+ };
+
+ console.log('📋 Settings to save:', settings);
+
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+ console.log('📡 Saving Apprise settings with token:', token ? 'present' : 'missing');
+
+ const response = await fetch('/api/admin/settings', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(settings)
+ });
+
+ console.log('📡 Response status:', response.status);
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ console.error('❌ Response error:', errorData);
+ throw new Error(errorData.message || 'Failed to save Apprise settings');
+ }
+
+ const responseData = await response.json();
+ console.log('✅ Save response:', responseData);
+
+ // Reload configuration
+ console.log('🔄 Reloading Apprise configuration...');
+ const reloadResponse = await fetch('/api/admin/apprise/reload-config', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ console.log('🔄 Reload response status:', reloadResponse.status);
+
+ showToast('Apprise settings saved successfully', 'success');
+
+ // Reload status
+ console.log('📱 Reloading Apprise settings...');
+ await loadAppriseSettings();
+
+ } catch (error) {
+ console.error('❌ Error saving Apprise settings:', error);
+ showToast(`Error saving Apprise settings: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Send test Apprise notification
+ */
+async function sendTestAppriseNotification() {
+ try {
+ showLoading();
+
+ const testUrl = appriseTestUrlInput ? appriseTestUrlInput.value.trim() : null;
+
+ const payload = testUrl ? { test_url: testUrl } : {};
+
+ const response = await fetch('/api/admin/apprise/test', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(payload)
+ });
+
+ const data = await response.json();
+
+ if (data.success) {
+ showToast('Test notification sent successfully', 'success');
+ } else {
+ showToast(`Failed to send test notification: ${data.message}`, 'error');
+ }
+
+ } catch (error) {
+ console.error('Error sending test notification:', error);
+ showToast(`Error sending test notification: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Validate Apprise URLs
+ */
+async function validateAppriseUrls() {
+ try {
+ showLoading();
+
+ const urlsText = appriseUrlsTextarea ? appriseUrlsTextarea.value : '';
+ const urls = urlsText.split(/[\n,]/)
+ .map(url => url.trim())
+ .filter(url => url.length > 0);
+
+ if (urls.length === 0) {
+ showToast('No URLs to validate', 'warning');
+ hideLoading();
+ return;
+ }
+
+ let validCount = 0;
+ let invalidUrls = [];
+
+ for (const url of urls) {
+ try {
+ const response = await fetch('/api/admin/apprise/validate-url', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ url: url })
+ });
+
+ const data = await response.json();
+
+ if (data.valid) {
+ validCount++;
+ } else {
+ invalidUrls.push(url);
+ }
+ } catch (error) {
+ invalidUrls.push(url);
+ }
+ }
+
+ let message = `Validation complete: ${validCount}/${urls.length} URLs are valid`;
+ if (invalidUrls.length > 0) {
+ message += `\nInvalid URLs: ${invalidUrls.join(', ')}`;
+ showToast(message, 'warning');
+ } else {
+ showToast(message, 'success');
+ }
+
+ } catch (error) {
+ console.error('Error validating URLs:', error);
+ showToast(`Error validating URLs: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Trigger Apprise expiration notifications
+ */
+async function triggerAppriseExpirationNotifications() {
+ try {
+ showLoading();
+
+ const response = await fetch('/api/admin/apprise/send-expiration', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ const data = await response.json();
+
+ if (data.success) {
+ showToast(data.message, 'success');
+ } else {
+ showToast(`Failed to trigger notifications: ${data.message}`, 'error');
+ }
+
+ } catch (error) {
+ console.error('Error triggering Apprise notifications:', error);
+ showToast(`Error triggering notifications: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * View supported services
+ */
+function viewSupportedAppriseServices() {
+ window.open('https://github.com/caronc/apprise/wiki', '_blank', 'noopener,noreferrer');
+}
+
+/**
+ * Save just the Apprise enabled/disabled state
+ */
+async function saveAppriseEnabledState(enabled) {
+ try {
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+
+ const response = await fetch('/api/admin/settings', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ apprise_enabled: enabled.toString()
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.message || 'Failed to save Apprise enabled state');
+ }
+
+ // Reload configuration
+ const reloadResponse = await fetch('/api/admin/apprise/reload-config', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ console.log('✅ Apprise enabled state saved:', enabled);
+
+ // Update status badge
+ await loadAppriseSettings();
+
+ } catch (error) {
+ console.error('❌ Error saving Apprise enabled state:', error);
+ showToast(`Error updating Apprise setting: ${error.message}`, 'error');
+
+ // Revert the toggle if save failed
+ if (appriseEnabledToggle) {
+ appriseEnabledToggle.checked = !enabled;
+ }
+ }
+}
+
+/**
+ * Update Apprise mode description text
+ */
+function updateAppriseModeDescription(mode) {
+ if (!appriseModeDescription) return;
+
+ if (mode === 'global') {
+ appriseModeDescription.textContent = 'A single, consolidated notification will be sent to the global Apprise channels defined below.';
+ } else if (mode === 'individual') {
+ appriseModeDescription.textContent = 'A separate notification will be sent for each user with expiring warranties. (Note: This currently uses the global channels. Per-user channels can be a future enhancement.)';
+ }
+}
+
+/**
+ * Update Apprise warranty scope description text
+ */
+function updateAppriseScopeDescription(scope) {
+ if (!appriseScopeDescription) return;
+
+ if (scope === 'all') {
+ appriseScopeDescription.textContent = 'Notifications will include expiring warranties from all users in the system.';
+ } else if (scope === 'admin') {
+ appriseScopeDescription.textContent = 'Notifications will only include expiring warranties belonging to the admin/owner user.';
+ }
+}
+
+/**
+ * Setup Apprise event listeners
+ */
+function setupAppriseEventListeners() {
+ // Enable/disable toggle
+ if (appriseEnabledToggle) {
+ appriseEnabledToggle.addEventListener('change', async function() {
+ const settingsContainer = document.getElementById('appriseSettingsContainer');
+ if (settingsContainer) {
+ settingsContainer.style.display = this.checked ? 'block' : 'none';
+ }
+
+ // Auto-save the enabled state
+ await saveAppriseEnabledState(this.checked);
+ });
+ }
+
+ // Notification mode change
+ if (appriseNotificationModeSelect) {
+ appriseNotificationModeSelect.addEventListener('change', (e) => {
+ updateAppriseModeDescription(e.target.value);
+ });
+ }
+
+ // Warranty scope change
+ if (appriseWarrantyScopeSelect) {
+ appriseWarrantyScopeSelect.addEventListener('change', (e) => {
+ updateAppriseScopeDescription(e.target.value);
+ });
+ }
+
+ // Save settings
+ if (saveAppriseSettingsBtn) {
+ saveAppriseSettingsBtn.addEventListener('click', saveAppriseSettings);
+ }
+
+ // Test notification
+ if (testAppriseBtn) {
+ testAppriseBtn.addEventListener('click', sendTestAppriseNotification);
+ }
+
+ // Validate URLs
+ if (validateAppriseUrlBtn) {
+ validateAppriseUrlBtn.addEventListener('click', validateAppriseUrls);
+ }
+
+ // Trigger expiration notifications
+ if (triggerAppriseNotificationsBtn) {
+ triggerAppriseNotificationsBtn.addEventListener('click', triggerAppriseExpirationNotifications);
+ }
+
+ // View supported services
+ if (viewSupportedServicesBtn) {
+ viewSupportedServicesBtn.addEventListener('click', viewSupportedAppriseServices);
+ }
+}
+
+// Initialize Apprise functionality
+document.addEventListener('DOMContentLoaded', function() {
+ setupAppriseEventListeners();
+
+ // Load Apprise settings after auth is ready (admin only)
+ setTimeout(() => {
+ if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
+ const currentUser = window.auth.getCurrentUser();
+ if (currentUser && currentUser.is_admin) {
+ loadAppriseSettings();
+ loadPaperlessSettings(); // Also load Paperless-ngx settings for admin
+ } else {
+ console.log('User is not admin, skipping Apprise settings load in deferred initialization');
+ }
+ }
+ }, 1000);
+});
+
+// ============================================================================
+// Paperless-ngx Integration Functions
+// ============================================================================
+
+/**
+ * Toggle the visibility of Paperless-ngx settings based on enabled state
+ * @param {boolean} enabled - Whether Paperless-ngx is enabled
+ */
+function togglePaperlessSettings(enabled) {
+ if (paperlessSettingsContainer) {
+ paperlessSettingsContainer.style.display = enabled ? 'block' : 'none';
+ }
+}
+
+/**
+ * Load Paperless-ngx settings from the server
+ */
+async function loadPaperlessSettings() {
+ try {
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+
+ const response = await fetch('/api/admin/settings', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to load settings');
+ }
+
+ const settings = await response.json();
+
+ // Update Paperless-ngx settings UI
+ if (paperlessEnabledToggle) {
+ const isEnabled = settings.paperless_enabled === 'true';
+ paperlessEnabledToggle.checked = isEnabled;
+ togglePaperlessSettings(isEnabled);
+ }
+
+ if (paperlessUrlInput && settings.paperless_url) {
+ paperlessUrlInput.value = settings.paperless_url;
+ }
+
+ // Update API token field placeholder to indicate if token is saved
+ if (paperlessApiTokenInput) {
+ if (settings.paperless_api_token_set === 'true') {
+ paperlessApiTokenInput.placeholder = 'API token saved (hidden for security) - Leave blank to keep existing';
+ } else {
+ paperlessApiTokenInput.placeholder = 'Enter API token';
+ }
+ }
+
+ console.log('✅ Paperless-ngx settings loaded successfully');
+
+ } catch (error) {
+ console.error('❌ Error loading Paperless-ngx settings:', error);
+ showToast(`Error loading Paperless-ngx settings: ${error.message}`, 'error');
+ }
+}
+
+/**
+ * Save Paperless-ngx settings to the server
+ */
+async function savePaperlessSettings() {
+ try {
+ showLoading();
+
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+
+ // Validate URL format
+ const url = paperlessUrlInput.value.trim();
+ if (url && !isValidUrl(url)) {
+ showToast('Please enter a valid URL (e.g., https://paperless.yourdomain.com)', 'error');
+ return;
+ }
+
+ // Prepare settings data
+ const settingsData = {
+ paperless_enabled: paperlessEnabledToggle.checked.toString(),
+ paperless_url: url
+ };
+
+ // Only include API token if it's provided (not empty)
+ const apiToken = paperlessApiTokenInput.value.trim();
+ if (apiToken) {
+ settingsData.paperless_api_token = apiToken;
+ }
+
+ // Save admin settings first
+ const response = await fetch('/api/admin/settings', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(settingsData)
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.message || 'Failed to save Paperless-ngx settings');
+ }
+
+ // Also save the user preference for viewing documents in app
+ const paperlessViewInApp = paperlessViewInAppToggle ? paperlessViewInAppToggle.checked : false;
+ const preferencesData = {
+ paperless_view_in_app: paperlessViewInApp
+ };
+
+ const preferencesResponse = await fetch('/api/auth/preferences', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(preferencesData)
+ });
+
+ if (!preferencesResponse.ok) {
+ console.warn('Failed to save paperless view preference, but admin settings were saved');
+ }
+
+ // Update localStorage for the preference
+ const prefix = getPreferenceKeyPrefix();
+ localStorage.setItem(`${prefix}paperlessViewInApp`, paperlessViewInApp);
+
+ showToast('Paperless-ngx settings saved successfully!', 'success');
+
+ // Clear the API token input for security
+ if (paperlessApiTokenInput) {
+ paperlessApiTokenInput.value = '';
+ paperlessApiTokenInput.placeholder = 'API token saved (hidden for security) - Leave blank to keep existing';
+ }
+
+ console.log('✅ Paperless-ngx settings saved successfully');
+
+ } catch (error) {
+ console.error('❌ Error saving Paperless-ngx settings:', error);
+ showToast(`Error saving Paperless-ngx settings: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Test connection to Paperless-ngx instance
+ */
+async function testPaperlessConnection() {
+ try {
+ showLoading();
+
+ // Clear previous status
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.innerHTML = '';
+ paperlessConnectionStatus.className = 'paperless-status-message';
+ }
+
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+
+ // Get current values from the form
+ const url = paperlessUrlInput.value.trim();
+ const apiToken = paperlessApiTokenInput.value.trim();
+
+ if (!url) {
+ showToast('Please enter a Paperless-ngx URL first', 'warning');
+ return;
+ }
+
+ // Check if API token is provided in form, otherwise use stored settings
+ if (!apiToken && paperlessApiTokenInput.placeholder.includes('saved')) {
+ // API token is already saved, test with stored settings
+ const response = await fetch('/api/paperless/test', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ const result = await response.json();
+
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.classList.add('show');
+ if (result.success) {
+ paperlessConnectionStatus.className = 'paperless-status-message show success';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>✅ Connection Successful!</strong><br>
+ ${result.message}
+ ${result.server_info ? `<br><small>Server: ${result.server_info}</small>` : ''}
+ `;
+ showToast('Paperless-ngx connection test successful!', 'success');
+ } else {
+ paperlessConnectionStatus.className = 'paperless-status-message show error';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>❌ Connection Failed!</strong><br>
+ ${result.message}
+ `;
+ showToast('Paperless-ngx connection test failed', 'error');
+ }
+ }
+
+ return;
+ }
+
+ if (!apiToken) {
+ showToast('Please enter an API token to test the connection', 'warning');
+ return;
+ }
+
+ const response = await fetch('/api/paperless/test', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ url: url,
+ api_token: apiToken
+ })
+ });
+
+ const result = await response.json();
+
+ if (paperlessConnectionStatus) {
+ if (result.success) {
+ paperlessConnectionStatus.classList.add('show');
+ paperlessConnectionStatus.className = 'paperless-status-message show success';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>✅ Connection Successful!</strong><br>
+ ${result.message}
+ ${result.server_info ? `<br><small>Server: ${result.server_info}</small>` : ''}
+ `;
+ showToast('Paperless-ngx connection test successful!', 'success');
+ } else {
+ paperlessConnectionStatus.classList.add('show');
+ paperlessConnectionStatus.className = 'paperless-status-message show error';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>❌ Connection Failed!</strong><br>
+ ${result.message}
+ `;
+ showToast('Paperless-ngx connection test failed', 'error');
+ }
+ }
+
+ } catch (error) {
+ console.error('❌ Error testing Paperless-ngx connection:', error);
+
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.classList.add('show');
+ paperlessConnectionStatus.className = 'paperless-status-message show error';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>❌ Connection Error!</strong><br>
+ ${error.message}
+ `;
+ }
+
+ showToast(`Error testing connection: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Debug Paperless-ngx configuration
+ */
+async function debugPaperlessConfiguration() {
+ try {
+ showLoading();
+
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+
+ const response = await fetch('/api/paperless/debug', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ const result = await response.json();
+
+ // Display debug information
+ console.log('🔍 Paperless-ngx Debug Information:', result);
+
+ let debugHtml = '<h5>📋 Paperless-ngx Debug Information</h5>';
+ debugHtml += `<strong>Enabled:</strong> ${result.paperless_enabled}<br>`;
+ debugHtml += `<strong>URL:</strong> ${result.paperless_url || 'Not set'}<br>`;
+ debugHtml += `<strong>API Token Set:</strong> ${result.paperless_api_token_set}<br>`;
+ debugHtml += `<strong>Handler Available:</strong> ${result.paperless_handler_available}<br>`;
+
+ if (result.test_connection_result) {
+ debugHtml += `<strong>Connection Test:</strong> ${result.test_connection_result.success ? '✅ Success' : '❌ Failed'}<br>`;
+ debugHtml += `<strong>Message:</strong> ${result.test_connection_result.message || result.test_connection_result.error}<br>`;
+ }
+
+ if (result.paperless_handler_error) {
+ debugHtml += `<strong>Handler Error:</strong> ${result.paperless_handler_error}<br>`;
+ }
+
+ // Show in connection status area or create a temporary area
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.classList.add('show');
+ paperlessConnectionStatus.className = 'paperless-status-message show info';
+ paperlessConnectionStatus.innerHTML = debugHtml;
+ } else {
+ // Create temporary debug display
+ const debugArea = document.createElement('div');
+ debugArea.innerHTML = debugHtml;
+ document.body.appendChild(debugArea);
+ setTimeout(() => debugArea.remove(), 10000); // Remove after 10 seconds
+ }
+
+ showToast('Debug information logged to console', 'info');
+
+ } catch (error) {
+ console.error('❌ Error running Paperless debug:', error);
+ showToast(`Debug error: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Test basic file upload mechanism
+ */
+async function testFileUpload() {
+ try {
+ showLoading();
+
+ // Create a simple test file
+ const testContent = 'This is a test file for Paperless-ngx upload debugging';
+ const testFile = new File([testContent], 'test.txt', { type: 'text/plain' });
+
+ const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
+
+ const formData = new FormData();
+ formData.append('file', testFile);
+ formData.append('document_type', 'test');
+
+ const response = await fetch('/api/paperless/test-upload', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ },
+ body: formData
+ });
+
+ const result = await response.json();
+
+ console.log('🧪 File Upload Test Result:', result);
+
+ if (result.success) {
+ showToast('File upload test successful!', 'success');
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.classList.add('show');
+ paperlessConnectionStatus.className = 'paperless-status-message show success';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>✅ File Upload Test Successful!</strong><br>
+ ${result.message}<br>
+ <small>File: ${result.file_info.filename} (${result.file_info.size} bytes)</small>
+ `;
+ }
+ } else {
+ showToast('File upload test failed', 'error');
+ if (paperlessConnectionStatus) {
+ paperlessConnectionStatus.classList.add('show');
+ paperlessConnectionStatus.className = 'paperless-status-message show error';
+ paperlessConnectionStatus.innerHTML = `
+ <strong>❌ File Upload Test Failed!</strong><br>
+ ${result.error}
+ `;
+ }
+ }
+
+ } catch (error) {
+ console.error('❌ Error testing file upload:', error);
+ showToast(`File upload test error: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Validate if a string is a valid URL
+ * @param {string} string - The string to validate
+ * @returns {boolean} - Whether the string is a valid URL
+ */
+function isValidUrl(string) {
+ try {
+ const url = new URL(string);
+ return url.protocol === 'http:' || url.protocol === 'https:';
+ } catch (_) {
+ return false;
+ }
+}
diff --git a/frontend/settings-styles.css b/frontend/settings-styles.css
index 6adf2c9..a40b4fc 100644
--- a/frontend/settings-styles.css
+++ b/frontend/settings-styles.css
@@ -6,12 +6,17 @@
--hover-bg: rgba(0, 0, 0, 0.05);
}
+html {
+ overflow-x: hidden;
+}
+
body {
background-color: var(--bg-color);
color: var(--text-color);
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
transition: background-color 0.3s ease, color 0.3s ease;
+ overflow-x: hidden;
}
/* Header Styles */
@@ -177,6 +182,7 @@ header .container {
max-width: 1200px !important;
margin: 0 auto !important;
padding: 20px !important;
+ overflow-x: hidden;
}
.content-wrapper h2 {
@@ -447,6 +453,8 @@ input:checked + .toggle-slider:before {
border: 1px solid var(--border-color);
border-radius: 0.25rem;
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+ box-sizing: border-box;
+ word-wrap: break-word;
}
.form-control:focus {
@@ -535,6 +543,7 @@ input:checked + .toggle-slider:before {
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
margin-bottom: 20px;
overflow: hidden;
+ word-wrap: break-word;
}
.card-header {
@@ -842,7 +851,7 @@ input:checked + .toggle-slider:before {
/* Admin Actions Grid */
.admin-actions-grid {
display: grid;
- grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 20px;
margin-bottom: 20px;
}
@@ -950,4 +959,408 @@ input:checked + .toggle-slider:before {
:root[data-theme="dark"] .current-user-info strong {
color: var(--primary-color);
-}
\ No newline at end of file
+}
+
+/* Apprise Notifications Styles */
+.badge {
+ display: inline-block;
+ padding: 2px 8px;
+ font-size: 0.75rem;
+ font-weight: 600;
+ border-radius: 12px;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+}
+
+.badge-success {
+ background-color: #28a745;
+ color: white;
+}
+
+.badge-warning {
+ background-color: #ffc107;
+ color: #212529;
+}
+
+.badge-danger {
+ background-color: #dc3545;
+ color: white;
+}
+
+.alert {
+ padding: 12px 16px;
+ margin-bottom: 20px;
+ border: 1px solid transparent;
+ border-radius: 6px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+
+.alert-warning {
+ color: #856404;
+ background-color: #fff3cd;
+ border-color: #ffeaa7;
+}
+
+.dark-mode .alert-warning {
+ color: #ffc107;
+ background-color: rgba(255, 193, 7, 0.1);
+ border-color: rgba(255, 193, 7, 0.3);
+}
+
+.apprise-actions {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
+ gap: 10px;
+ margin-top: 20px;
+}
+
+.apprise-actions .btn {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ padding: 10px 16px;
+ font-size: 0.9rem;
+}
+
+.status-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
+ gap: 15px;
+ margin-top: 10px;
+}
+
+.status-item {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 12px 16px;
+ background-color: rgba(0, 0, 0, 0.02);
+ border-radius: 6px;
+ border-left: 4px solid var(--primary-color);
+}
+
+.dark-mode .status-item {
+ background-color: rgba(255, 255, 255, 0.05);
+}
+
+.status-label {
+ font-weight: 600;
+ color: var(--text-color);
+}
+
+.status-value {
+ color: var(--primary-color);
+ font-weight: 500;
+}
+
+.services-info {
+ padding: 15px;
+ background-color: rgba(0, 0, 0, 0.02);
+ border-radius: 6px;
+ border-left: 4px solid var(--primary-color);
+}
+
+.dark-mode .services-info {
+ background-color: rgba(255, 255, 255, 0.05);
+}
+
+.services-info p {
+ margin: 0 0 10px 0;
+ line-height: 1.5;
+}
+
+.btn-link {
+ color: var(--primary-color);
+ text-decoration: none;
+ background: none;
+ border: none;
+ padding: 0;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ font-size: 0.9rem;
+}
+
+.btn-link:hover {
+ text-decoration: underline;
+}
+
+.btn-info {
+ background-color: #17a2b8;
+ color: white;
+ border: 1px solid #17a2b8;
+}
+
+.btn-info:hover {
+ background-color: #138496;
+ border-color: #117a8b;
+}
+
+textarea.form-control {
+ resize: vertical;
+ min-height: 100px;
+}
+
+@media (max-width: 768px) {
+ .apprise-actions {
+ grid-template-columns: 1fr;
+ }
+
+ .status-grid {
+ grid-template-columns: 1fr;
+ }
+
+ .status-item {
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 5px;
+ }
+}
+
+/* Dark mode link styling for text-muted elements */
+.dark-mode .text-muted a {
+ color: var(--primary-color);
+ text-decoration: underline;
+}
+
+.dark-mode .text-muted a:hover {
+ color: #6db4ff;
+ text-decoration: underline;
+}
+
+/* General link styling for better dark mode visibility */
+:root[data-theme="dark"] .text-muted a {
+ color: var(--primary-color);
+ text-decoration: underline;
+}
+
+:root[data-theme="dark"] .text-muted a:hover {
+ color: #6db4ff;
+ text-decoration: underline;
+}
+
+/* Collapsible Cards */
+.collapsible-card {
+ transition: all 0.3s ease;
+}
+
+.collapsible-header {
+ cursor: pointer;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ user-select: none;
+ transition: background-color 0.3s ease;
+}
+
+.collapsible-header:hover {
+ background-color: rgba(0, 0, 0, 0.05);
+}
+
+.dark-mode .collapsible-header:hover {
+ background-color: rgba(255, 255, 255, 0.05);
+}
+
+.collapse-icon {
+ transition: transform 0.3s ease;
+ color: var(--text-color);
+ opacity: 0.7;
+}
+
+.collapsible-header:hover .collapse-icon {
+ opacity: 1;
+}
+
+.collapsible-card.collapsed .collapse-icon {
+ transform: rotate(-90deg);
+}
+
+.collapsible-content {
+ overflow: hidden;
+ transition: max-height 0.3s ease, opacity 0.3s ease, padding 0.3s ease;
+ max-height: 2000px; /* Large enough to show all content */
+ opacity: 1;
+}
+
+.collapsible-card.collapsed .collapsible-content {
+ max-height: 0;
+ opacity: 0;
+ padding-top: 0;
+ padding-bottom: 0;
+}
+
+/* Ensure smooth transitions for nested elements */
+.collapsible-content * {
+ transition: none; /* Prevent nested transitions from interfering */
+}
+
+@media (max-width: 768px) {
+ .apprise-actions {
+ grid-template-columns: 1fr;
+ }
+
+ .status-grid {
+ grid-template-columns: 1fr;
+ }
+
+ .status-item {
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 5px;
+ }
+}
+
+/* Footer Overrides - Ensure footer spans full width without causing horizontal scroll */
+.warracker-footer {
+ width: 100% !important;
+ max-width: none !important;
+ margin-left: 0 !important;
+ margin-right: 0 !important;
+ position: relative !important;
+ left: 0 !important;
+ right: 0 !important;
+}
+
+/* Additional mobile responsive styles if needed */
+@media (max-width: 768px) {
+ .warracker-footer {
+ width: 100% !important;
+ margin-left: 0 !important;
+ margin-right: 0 !important;
+ }
+}
+
+/* Paperless-ngx Integration Styles */
+.paperless-button-group {
+ display: flex;
+ gap: 10px;
+ flex-wrap: wrap;
+ margin-top: 10px;
+}
+
+.paperless-button-group .btn {
+ flex: 0 0 auto;
+ min-width: 150px;
+}
+
+.paperless-status-message {
+ margin-top: 15px;
+ padding: 10px;
+ border-radius: 5px;
+ background-color: var(--light-gray);
+ color: var(--text-color);
+ font-size: 0.9rem;
+ display: none;
+}
+
+.paperless-status-message.show {
+ display: block;
+}
+
+.paperless-status-message.success {
+ background-color: rgba(40, 167, 69, 0.1);
+ color: #155724;
+ border: 1px solid rgba(40, 167, 69, 0.3);
+}
+
+.paperless-status-message.error {
+ background-color: rgba(220, 53, 69, 0.1);
+ color: #721c24;
+ border: 1px solid rgba(220, 53, 69, 0.3);
+}
+
+.paperless-status-message.info {
+ background-color: rgba(23, 162, 184, 0.1);
+ color: #0c5460;
+ border: 1px solid rgba(23, 162, 184, 0.3);
+}
+
+.dark-mode .paperless-status-message {
+ background-color: rgba(255, 255, 255, 0.05);
+}
+
+.dark-mode .paperless-status-message.success {
+ background-color: rgba(40, 167, 69, 0.2);
+ color: #5cb85c;
+}
+
+.dark-mode .paperless-status-message.error {
+ background-color: rgba(220, 53, 69, 0.2);
+ color: #d9534f;
+}
+
+.dark-mode .paperless-status-message.info {
+ background-color: rgba(23, 162, 184, 0.2);
+ color: #5bc0de;
+}
+
+/* Responsive design for paperless buttons */
+@media (max-width: 576px) {
+ .paperless-button-group {
+ flex-direction: column;
+ }
+
+ .paperless-button-group .btn {
+ width: 100%;
+ min-width: unset;
+ }
+}
+
+
+
+/* RTL Language Support for Settings */
+[dir=\
+rtl\] .settings-container {
+ text-align: right;
+}
+
+[dir=\rtl\] .collapsible-card {
+ text-align: right;
+}
+
+[dir=\rtl\] .collapsible-header {
+ justify-content: space-between;
+ text-align: right;
+}
+
+[dir=\rtl\] .collapse-icon {
+ order: -1;
+ margin-left: 0;
+ margin-right: 10px;
+}
+
+[dir=\rtl\] .form-group label {
+ text-align: right;
+}
+
+[dir=\rtl\] .text-muted {
+ text-align: right;
+}
+
+[dir=\rtl\] .toggle-group {
+ flex-direction: row-reverse;
+}
+
+[dir=\rtl\] .preference-item {
+ text-align: right;
+}
+
+[dir=\rtl\] .preference-item > div:first-child {
+ text-align: right;
+}
+
+[dir=\rtl\] .current-user-info {
+ text-align: right;
+}
+
+[dir=\rtl\] .admin-section {
+ text-align: right;
+}
+
+[dir=\rtl\] .danger-zone {
+ text-align: right;
+}
diff --git a/frontend/status.html b/frontend/status.html
index dde94eb..ea73dad 100644
--- a/frontend/status.html
+++ b/frontend/status.html
@@ -1,35 +1,42 @@
<!DOCTYPE html>
-<html lang="en">
+<html>
<head>
<!-- Authentication redirect script -->
- <script src="auth-redirect.js" data-protected="true"></script>
+ <script src="auth-redirect.js?v=20250119001" data-protected="true"></script>
<!-- Include authentication script first to handle login state immediately -->
- <script src="include-auth-new.js"></script>
+ <script src="include-auth-new.js?v=20250119001"></script>
<!-- File utilities script for secure file handling -->
- <script src="file-utils.js"></script>
+ <script src="file-utils.js?v=20250119001"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Status - Warracker</title>
+ <title data-i18n="status.title">Status - Warracker</title>
<!-- Favicons -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">
<link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
<link rel="manifest" href="manifest.json">
- <link rel="stylesheet" href="style.css">
- <script src="theme-loader.js"></script> <!-- Apply theme early -->
+ <link rel="stylesheet" href="style.css?v=20250119001">
+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Load header fix styles to ensure consistent header styling -->
- <link rel="stylesheet" href="header-fix.css">
+ <link rel="stylesheet" href="header-fix.css?v=20250119001">
<!-- Chart.js for visualizations -->
- <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
+ <script src="chart.js?v=20250119001"></script>
+ <!-- i18next Local Scripts -->
+ <script src="js/lib/i18next.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>
+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>
+ <!-- i18n initialization script -->
+ <script src="js/i18n.js?v=20250119001"></script>
<!-- Load fix for auth buttons -->
- <script src="fix-auth-buttons-loader.js"></script>
- <script src="script.js" defer></script> <!-- Added script.js -->
+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script>
+ <script src="script.js?v=20250119001" defer></script> <!-- Added script.js -->
+ <script src="status.js?v=20250119001" defer></script> <!-- Status page specific functionality -->
<style>
.user-menu {
position: relative;
@@ -160,6 +167,87 @@
display: none;
}
}
+
+ /* Dashboard header styles */
+ .dashboard-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 2rem;
+ flex-wrap: wrap;
+ }
+
+ .dashboard-controls {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ }
+
+ /* View switcher styles */
+ .view-switcher {
+ display: flex;
+ align-items: center;
+ }
+
+ .toggle-group {
+ display: flex;
+ background-color: var(--card-bg);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ overflow: hidden;
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
+ }
+
+ .toggle-btn {
+ background: none;
+ border: none;
+ padding: 8px 16px;
+ cursor: pointer;
+ font-size: 0.9rem;
+ transition: all 0.3s ease;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--text-color);
+ min-width: 100px;
+ justify-content: center;
+ }
+
+ .toggle-btn:hover {
+ background-color: var(--hover-bg);
+ }
+
+ .toggle-btn.active {
+ background-color: var(--primary-color);
+ color: white;
+ }
+
+ .toggle-btn.active:hover {
+ background-color: var(--primary-dark);
+ }
+
+ .toggle-btn i {
+ font-size: 0.8rem;
+ }
+
+ @media (max-width: 768px) {
+ .dashboard-header {
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 1rem;
+ }
+
+ .dashboard-controls {
+ width: 100%;
+ justify-content: space-between;
+ }
+
+ .toggle-btn {
+ min-width: 80px;
+ padding: 6px 12px;
+ font-size: 0.8rem;
+ }
+ }
</style>
<!-- Immediate authentication check script -->
@@ -224,10 +312,10 @@
</div>
<div class="nav-links">
<a href="index.html" class="nav-link">
- <i class="fas fa-home"></i> Home
+ <i class="fas fa-home"></i> <span data-i18n="nav.home">Home</span>
</a>
<a href="status.html" class="nav-link active">
- <i class="fas fa-chart-pie"></i> Status
+ <i class="fas fa-chart-pie"></i> <span data-i18n="nav.status">Status</span>
</a>
</div>
<!-- Group for right-aligned elements -->
@@ -241,7 +329,7 @@
</a>
</div>
<div id="userMenu" class="user-menu" style="display: none;">
- <button id="userBtn" class="user-btn">
+ <button id="userMenuBtn" class="user-btn">
<i class="fas fa-user-circle"></i>
<span id="userDisplayName">User</span>
</button>
@@ -252,15 +340,15 @@
</div>
<div class="user-menu-item">
<a href="settings-new.html" style="color: inherit; text-decoration: none; display: block;">
- <i class="fas fa-cog"></i> Settings
+ <i class="fas fa-cog"></i> <span data-i18n="nav.settings">Settings</span>
</a>
</div>
<div class="user-menu-item">
<i class="fas fa-info-circle"></i>
- <a href="about.html" style="text-decoration: none; color: inherit;">About</a>
+ <a href="about.html" style="text-decoration: none; color: inherit;" data-i18n="nav.about">About</a>
</div>
<div class="user-menu-item" id="logoutMenuItem">
- <i class="fas fa-sign-out-alt"></i> Logout
+ <i class="fas fa-sign-out-alt"></i> <span data-i18n="auth.logout">Logout</span>
</div>
</div>
</div>
@@ -272,10 +360,23 @@
<div class="container">
<div class="status-content">
<div class="dashboard-header">
- <h2>Warranty Status Dashboard</h2>
- <button id="refreshDashboardBtn" class="refresh-btn" title="Refresh dashboard">
- <i class="fas fa-sync-alt"></i>
- </button>
+ <h2 id="dashboardTitle" data-i18n="status.dashboard_title">Warranty Status Dashboard</h2>
+ <div class="dashboard-controls">
+ <!-- Global View Controls (hidden by default, shown for eligible users) -->
+ <div id="viewSwitcher" class="view-switcher" style="display: none;">
+ <div class="toggle-group">
+ <button id="personalViewBtn" class="toggle-btn active">
+ <i class="fas fa-user"></i>
+ </button>
+ <button id="globalViewBtn" class="toggle-btn">
+ <i class="fas fa-globe"></i>
+ </button>
+ </div>
+ </div>
+ <button id="refreshDashboardBtn" class="refresh-btn" title="Refresh dashboard">
+ <i class="fas fa-sync-alt"></i>
+ </button>
+ </div>
</div>
<!-- Loading Indicator -->
@@ -300,7 +401,7 @@
<i class="fas fa-check-circle"></i>
</div>
<div class="card-content">
- <h3>Active</h3>
+ <h3 data-i18n="status.active_warranties">Active</h3>
<p class="count" id="activeCount">0</p>
</div>
</div>
@@ -310,7 +411,7 @@
<i class="fas fa-exclamation-circle"></i>
</div>
<div class="card-content">
- <h3>Expiring Soon</h3>
+ <h3 data-i18n="status.expiring_soon">Expiring Soon</h3>
<p class="count" id="expiringCount">0</p>
</div>
</div>
@@ -320,7 +421,7 @@
<i class="fas fa-times-circle"></i>
</div>
<div class="card-content">
- <h3>Expired</h3>
+ <h3 data-i18n="status.expired_warranties">Expired</h3>
<p class="count" id="expiredCount">0</p>
</div>
</div>
@@ -330,7 +431,7 @@
<i class="fas fa-shield-alt"></i>
</div>
<div class="card-content">
- <h3>Total</h3>
+ <h3 data-i18n="status.total_warranties">Total</h3>
<p class="count" id="totalCount">0</p>
</div>
</div>
@@ -339,14 +440,14 @@
<!-- Charts Section -->
<div class="charts-container">
<div class="chart-card">
- <h3>Warranty Status Distribution</h3>
+ <h3 data-i18n="status.warranty_distribution">Warranty Status Distribution</h3>
<div class="chart-container">
<canvas id="statusChart"></canvas>
</div>
</div>
<div class="chart-card">
- <h3>Expiration Timeline</h3>
+ <h3 data-i18n="status.expiration_timeline">Expiration Timeline</h3>
<div class="chart-container">
<canvas id="timelineChart"></canvas>
</div>
@@ -356,33 +457,34 @@
<!-- Recent Expirations -->
<div class="recent-expirations">
<div class="table-header">
- <h3>Recently Expired or Expiring Soon</h3>
+ <h3 data-i18n="status.recent_expirations">Recently Expired or Expiring Soon</h3>
<div class="table-actions">
<div class="search-box">
<i class="fas fa-search"></i>
- <input type="text" id="searchWarranties" placeholder="Search warranties...">
+ <input type="text" id="searchWarranties" placeholder="Search warranties..." data-i18n="[placeholder]warranties.search_placeholder">
</div>
<div class="filter-options">
<select id="statusFilter" class="filter-select">
- <option value="all">All Statuses</option>
- <option value="active">Active</option>
- <option value="expiring">Expiring Soon</option>
- <option value="expired">Expired</option>
+ <option value="all" data-i18n="filters.all_status">All Statuses</option>
+ <option value="active" data-i18n="warranties.active">Active</option>
+ <option value="expiring" data-i18n="warranties.expiring_soon">Expiring Soon</option>
+ <option value="expired" data-i18n="warranties.expired">Expired</option>
</select>
</div>
<button id="exportBtn" class="export-btn" title="Export data">
- <i class="fas fa-download"></i> <span class="export-text">Export</span>
+ <i class="fas fa-download"></i> <span class="export-text" data-i18n="actions.export">Export</span>
</button>
</div>
</div>
<div class="table-responsive">
<table id="recentExpirationsTable">
<thead>
- <tr>
- <th class="sortable" data-sort="product">Product <i class="fas fa-sort"></i></th>
- <th class="sortable" data-sort="purchase">Purchase Date <i class="fas fa-sort"></i></th>
- <th class="sortable" data-sort="expiration">Expiration Date <i class="fas fa-sort"></i></th>
- <th class="sortable" data-sort="status">Status <i class="fas fa-sort"></i></th>
+ <tr id="tableHeader">
+ <th class="sortable" data-sort="product"><span data-i18n="warranties.product">Product</span> <i class="fas fa-sort"></i></th>
+ <th class="sortable" data-sort="purchase"><span data-i18n="warranties.purchase_date">Purchase Date</span> <i class="fas fa-sort"></i></th>
+ <th class="sortable" data-sort="expiration"><span data-i18n="warranties.expiration_date">Expiration Date</span> <i class="fas fa-sort"></i></th>
+ <th class="sortable" data-sort="status"><span data-i18n="warranties.status">Status</span> <i class="fas fa-sort"></i></th>
+ <th id="ownerHeader" class="sortable" data-sort="owner" style="display: none;"><span data-i18n="warranties.owner">Owner</span> <i class="fas fa-sort"></i></th>
</tr>
</thead>
<tbody id="recentExpirationsBody">
@@ -402,23 +504,23 @@
<div id="editModal" class="modal-backdrop">
<div class="modal">
<div class="modal-header">
- <h3 class="modal-title">Edit Warranty</h3>
+ <h3 class="modal-title" data-i18n="warranties.edit_warranty">Edit Warranty</h3>
<button class="close-btn" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body">
<!-- Tab Navigation -->
<div class="edit-tabs-nav">
<button type="button" class="edit-tab-btn active" data-tab="edit-product-info">
- <i class="fas fa-box"></i> Product
+ <i class="fas fa-box"></i> <span data-i18n="warranties.product">Product</span>
</button>
<button type="button" class="edit-tab-btn" data-tab="edit-warranty-details">
- <i class="fas fa-shield-alt"></i> Warranty
+ <i class="fas fa-shield-alt"></i> <span data-i18n="warranties.warranty">Warranty</span>
</button>
<button type="button" class="edit-tab-btn" data-tab="edit-documents">
- <i class="fas fa-file-alt"></i> Documents
+ <i class="fas fa-file-alt"></i> <span data-i18n="warranties.documents">Documents</span>
</button>
<button type="button" class="edit-tab-btn" data-tab="edit-tags">
- <i class="fas fa-tags"></i> Tags
+ <i class="fas fa-tags"></i> <span data-i18n="warranties.tags">Tags</span>
</button>
</div>
@@ -428,31 +530,31 @@
<!-- Product Info Tab -->
<div class="edit-tab-content active" id="edit-product-info">
<div class="form-group">
- <label for="editProductName">Product Name</label>
+ <label for="editProductName" data-i18n="warranties.product_name">Product Name</label>
<input type="text" id="editProductName" name="product_name" class="form-control" required>
</div>
<div class="form-group">
- <label for="editProductUrl">Product URL (Optional)</label>
+ <label for="editProductUrl" data-i18n="warranties.product_url_optional">Product URL (Optional)</label>
<input type="text" id="editProductUrl" name="product_url" class="form-control" placeholder="https://example.com/product">
</div>
<div class="form-group">
- <label>Serial Numbers</label>
+ <label data-i18n="warranties.serial_numbers">Serial Numbers</label>
<div id="editSerialNumbersContainer">
<!-- Serial number inputs will be added dynamically -->
</div>
</div>
<div class="form-group">
- <label for="editVendor">Vendor (Optional)</label>
- <input type="text" id="editVendor" name="vendor" class="form-control" placeholder="e.g. Amazon, Best Buy, etc.">
+ <label for="editVendor" data-i18n="warranties.vendor_optional">Vendor (Optional)</label>
+ <input type="text" id="editVendor" name="vendor" class="form-control" data-i18n-placeholder="warranties.vendor_placeholder" placeholder="e.g. Amazon, Best Buy, etc.">
</div>
</div>
<!-- Warranty Details Tab -->
<div class="edit-tab-content" id="edit-warranty-details">
<div class="form-group">
- <label for="editPurchaseDate">Purchase Date</label>
+ <label for="editPurchaseDate" data-i18n="warranties.purchase_date">Purchase Date</label>
<input type="date" id="editPurchaseDate" name="purchase_date" class="form-control" required>
</div>
@@ -460,89 +562,153 @@
<div class="form-group">
<label class="lifetime-label">
<input type="checkbox" id="editIsLifetime" name="is_lifetime" value="true">
- Lifetime Warranty
+ <span data-i18n="warranties.lifetime_warranty">Lifetime Warranty</span>
</label>
</div>
<!-- End Lifetime Checkbox -->
+ <!-- Warranty Entry Method Selection -->
+ <div class="form-group" id="editWarrantyEntryMethod">
+ <label data-i18n="warranties.warranty_entry_method">Warranty Entry Method</label>
+ <div class="warranty-method-options">
+ <label class="radio-option">
+ <input type="radio" id="editDurationMethod" name="edit_warranty_method" value="duration" checked>
+ <span data-i18n="warranties.warranty_duration_option">Warranty Duration</span>
+ </label>
+ <label class="radio-option">
+ <input type="radio" id="editExactDateMethod" name="edit_warranty_method" value="exact_date">
+ <span data-i18n="warranties.exact_expiration_option">Exact Expiration Date</span>
+ </label>
+ </div>
+ </div>
+
<div id="editWarrantyDurationFields">
<div class="form-group">
- <label for="editWarrantyDurationYears">Warranty Period</label>
+ <label for="editWarrantyDurationYears" data-i18n="warranties.warranty_period">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>
+ <input type="number" id="editWarrantyDurationYears" name="warranty_duration_years" class="form-control" min="0" max="999" data-i18n-placeholder="warranties.years" placeholder="Years">
+ <small data-i18n="warranties.years">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>
+ <input type="number" id="editWarrantyDurationMonths" name="warranty_duration_months" class="form-control" min="0" max="999" data-i18n-placeholder="warranties.months" placeholder="Months">
+ <small data-i18n="warranties.months">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>
+ <input type="number" id="editWarrantyDurationDays" name="warranty_duration_days" class="form-control" min="0" max="9999" data-i18n-placeholder="warranties.days" placeholder="Days">
+ <small data-i18n="warranties.days">Days</small>
</div>
</div>
</div>
</div>
+ <div id="editExactExpirationField" style="display: none;">
+ <div class="form-group">
+ <label for="editExactExpirationDate" data-i18n="warranties.expiration_date_label">Expiration Date</label>
+ <input type="date" id="editExactExpirationDate" name="exact_expiration_date" class="form-control">
+ </div>
+ </div>
+
<div class="form-group">
- <label for="editPurchasePrice">Purchase Price (Optional)</label>
- <div class="price-input-wrapper">
- <span class="currency-symbol">$</span>
+ <label for="editWarrantyType" data-i18n="warranties.warranty_type_optional">Warranty Type (Optional)</label>
+ <select id="editWarrantyType" name="warranty_type" class="form-control">
+ <option value="" data-i18n="warranties.select_warranty_type">Select warranty type...</option>
+ <option value="Standard" data-i18n="warranties.warranty_type_standard">Standard</option>
+ <option value="Extended" data-i18n="warranties.warranty_type_extended">Extended</option>
+ <option value="Manufacturer" data-i18n="warranties.warranty_type_manufacturer">Manufacturer</option>
+ <option value="Third Party" data-i18n="warranties.warranty_type_third_party">Third Party</option>
+ <option value="Store" data-i18n="warranties.warranty_type_store">Store</option>
+ <option value="Premium" data-i18n="warranties.warranty_type_premium">Premium</option>
+ <option value="Limited" data-i18n="warranties.warranty_type_limited">Limited</option>
+ <option value="Full" data-i18n="warranties.warranty_type_full">Full</option>
+ <option value="Parts Only" data-i18n="warranties.warranty_type_parts_only">Parts Only</option>
+ <option value="Labor Only" data-i18n="warranties.warranty_type_labor_only">Labor Only</option>
+ <option value="International" data-i18n="warranties.warranty_type_international">International</option>
+ <option value="Accidental Damage" data-i18n="warranties.warranty_type_accidental_damage">Accidental Damage</option>
+ <option value="other" data-i18n="warranties.warranty_type_other">Other (Custom)</option>
+ </select>
+ <input type="text" id="editWarrantyTypeCustom" name="warranty_type_custom" class="form-control" style="display: none; margin-top: 8px;" data-i18n-placeholder="warranties.warranty_type_custom_placeholder" placeholder="Enter custom warranty type">
+ </div>
+ <div class="form-group">
+ <label for="editCurrency" data-i18n="warranties.currency">Currency</label>
+ <select id="editCurrency" name="currency" class="form-control">
+ <option value="USD">USD - US Dollar ($)</option>
+ <!-- Currency options will be populated by JavaScript -->
+ </select>
+ </div>
+ <div class="form-group">
+ <label for="editPurchasePrice" data-i18n="warranties.purchase_price_optional">Purchase Price (Optional)</label>
+ <div class="price-input-wrapper" id="editPriceInputWrapper">
+ <span class="currency-symbol" id="editCurrencySymbol">$</span>
<input type="number" id="editPurchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">
</div>
</div>
<div class="form-group">
- <label for="editNotes">Notes (Optional)</label>
- <textarea id="editNotes" name="notes" class="form-control" rows="3" placeholder="Add any notes about this warranty..."></textarea>
+ <label for="editNotes" data-i18n="warranties.notes_optional">Notes (Optional)</label>
+ <textarea id="editNotes" name="notes" class="form-control" rows="3" data-i18n-placeholder="warranties.notes_placeholder" placeholder="Add any notes about this warranty..."></textarea>
</div>
</div>
<!-- Documents Tab -->
<div class="edit-tab-content" id="edit-documents">
<div class="form-group">
- <label>Invoice/Receipt</label>
+ <label data-i18n="warranties.product_photo_optional">Product Photo (Optional)</label>
+ <div class="file-input-wrapper">
+ <label for="editProductPhoto" class="file-input-label">
+ <i class="fas fa-upload"></i> <span data-i18n="warranties.choose_photo">Choose Photo</span>
+ </label>
+ <input type="file" id="editProductPhoto" name="product_photo" class="file-input" accept=".png,.jpg,.jpeg,.webp">
+ </div>
+ <div id="editProductPhotoFileName" class="file-name"></div>
+ <div id="editProductPhotoPreview" class="photo-preview" style="display: none;">
+ <img id="editProductPhotoImg" src="" alt="Product Photo Preview" style="max-width: 200px; max-height: 200px; border-radius: 8px; margin-top: 10px;">
+ </div>
+ <div id="currentProductPhoto" class="mt-10"></div>
+ <button type="button" id="deleteProductPhotoBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> <span data-i18n="warranties.delete_photo">Delete Photo</span></button>
+ </div>
+ <div class="form-group">
+ <label data-i18n="warranties.invoice_receipt">Invoice/Receipt</label>
<div class="file-input-wrapper">
<label for="editInvoice" class="file-input-label">
- <i class="fas fa-upload"></i> Choose File
+ <i class="fas fa-upload"></i> <span data-i18n="warranties.choose_file">Choose File</span>
</label>
<input type="file" id="editInvoice" name="invoice" class="file-input" accept=".pdf,.png,.jpg,.jpeg">
</div>
<div id="editFileName" class="file-name"></div>
<div id="currentInvoice" class="mt-10"></div>
- <button type="button" id="deleteInvoiceBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Invoice</button>
+ <button type="button" id="deleteInvoiceBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> <span data-i18n="warranties.delete_invoice">Delete Invoice</span></button>
</div>
<div class="form-group">
- <label>Product Manual (Optional)</label>
+ <label data-i18n="warranties.product_manual_optional">Product Manual (Optional)</label>
<div class="file-input-wrapper">
<label for="editManual" class="file-input-label">
- <i class="fas fa-upload"></i> Choose File
+ <i class="fas fa-upload"></i> <span data-i18n="warranties.choose_file">Choose File</span>
</label>
<input type="file" id="editManual" name="manual" class="file-input" accept=".pdf,.png,.jpg,.jpeg">
</div>
<div id="editManualFileName" class="file-name"></div>
<div id="currentManual" class="mt-10"></div>
- <button type="button" id="deleteManualBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Manual</button>
+ <button type="button" id="deleteManualBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> <span data-i18n="warranties.delete_manual">Delete Manual</span></button>
</div>
<div class="form-group">
- <label>Files (ZIP/RAR, Optional)</label>
+ <label data-i18n="warranties.files_optional">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
+ <i class="fas fa-upload"></i> <span data-i18n="warranties.choose_file">Choose File</span>
</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>
+ <button type="button" id="deleteOtherDocumentBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> <span data-i18n="warranties.delete_files">Delete Files</span></button>
</div>
</div>
<!-- Tags Tab -->
<div class="edit-tab-content" id="edit-tags">
<div class="form-group">
- <label>Add Tags</label>
- <p class="text-muted">Tags help you organize and filter your warranties</p>
+ <label data-i18n="warranties.add_tags">Add Tags</label>
+ <p class="text-muted" data-i18n="warranties.tags_help_text">Tags help you organize and filter your warranties</p>
<div class="tags-container">
<div class="selected-tags" id="editSelectedTags">
@@ -550,7 +716,7 @@
</div>
<div class="tags-dropdown">
- <input type="text" id="editTagSearch" class="form-control" placeholder="Search or add new tag...">
+ <input type="text" id="editTagSearch" class="form-control" data-i18n-placeholder="warranties.search_add_tag_placeholder" placeholder="Search or add new tag...">
<div class="tags-list" id="editTagsList">
<!-- Tag options will be populated by JavaScript -->
</div>
@@ -558,7 +724,7 @@
<div class="mt-10">
<button type="button" id="editManageTagsBtn" class="btn btn-secondary btn-sm">
- <i class="fas fa-cog"></i> Manage Tags
+ <i class="fas fa-cog"></i> <span data-i18n="warranties.manage_tags">Manage Tags</span>
</button>
</div>
</div>
@@ -567,8 +733,8 @@
</form>
</div>
<div class="modal-footer">
- <button class="btn btn-danger" data-dismiss="modal">Cancel</button>
- <button id="saveWarrantyBtn" class="btn btn-primary">Save Changes</button>
+ <button class="btn btn-danger" data-dismiss="modal" data-i18n="actions.cancel">Cancel</button>
+ <button id="saveWarrantyBtn" class="btn btn-primary" data-i18n="actions.save_changes">Save Changes</button>
</div>
</div>
</div>
@@ -577,16 +743,16 @@
<div id="deleteModal" class="modal-backdrop">
<div class="modal">
<div class="modal-header">
- <h3 class="modal-title">Confirm Delete</h3>
+ <h3 class="modal-title" data-i18n="warranties.confirm_delete">Confirm Delete</h3>
<button class="close-btn" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body">
- <p>Are you sure you want to delete this warranty? This action cannot be undone.</p>
- <p><strong>Product:</strong> <span id="deleteProductName"></span></p>
+ <p data-i18n="warranties.confirm_delete_message">Are you sure you want to delete this warranty? This action cannot be undone.</p>
+ <p><strong data-i18n="warranties.product">Product:</strong> <span id="deleteProductName"></span></p>
</div>
<div class="modal-footer">
- <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
- <button id="confirmDeleteBtn" class="btn btn-danger">Delete</button>
+ <button class="btn btn-secondary" data-dismiss="modal" data-i18n="actions.cancel">Cancel</button>
+ <button id="confirmDeleteBtn" class="btn btn-danger" data-i18n="actions.delete">Delete</button>
</div>
</div>
</div>
@@ -595,23 +761,23 @@
<div id="tagManagementModal" class="modal-backdrop">
<div class="modal">
<div class="modal-header">
- <h3 class="modal-title">Manage Tags</h3>
+ <h3 class="modal-title" data-i18n="warranties.manage_tags">Manage Tags</h3>
<button class="close-btn" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body">
<form id="newTagForm" class="tag-form">
- <input type="text" id="newTagName" class="form-control" placeholder="New tag name" required>
+ <input type="text" id="newTagName" class="form-control" data-i18n-placeholder="warranties.new_tag_name" placeholder="New tag name" required>
<input type="color" id="newTagColor" value="#808080">
- <button type="submit" class="btn btn-primary">Add Tag</button>
+ <button type="submit" class="btn btn-primary" data-i18n="warranties.add_tag">Add Tag</button>
</form>
- <h4 class="mt-20">Existing Tags</h4>
+ <h4 class="mt-20" data-i18n="warranties.existing_tags">Existing Tags</h4>
<div id="existingTags" class="existing-tags">
<!-- Tags will be populated here by JavaScript -->
</div>
</div>
<div class="modal-footer">
- <button class="btn btn-secondary" data-dismiss="modal">Close</button>
+ <button class="btn btn-secondary" data-dismiss="modal" data-i18n="actions.close">Close</button>
</div>
</div>
</div>
@@ -621,7 +787,45 @@
<div class="loading-spinner"></div>
</div>
- <script src="auth.js"></script>
- <script src="status.js" defer></script>
+ <script src="auth.js?v=20250119001"></script>
+ <script src="status.js?v=20250119001" defer></script>
+
+ <!-- Footer Width Fix -->
+ <script src="footer-fix.js?v=20250119001"></script>
+
+ <!-- Footer Content Manager -->
+ <script src="footer-content.js?v=20250119001"></script>
+
+ <!-- Powered by Warracker Footer -->
+ <footer class="warracker-footer" id="warrackerFooter">
+ <!-- Content will be dynamically generated by footer-content.js -->
+ </footer>
+
+ <script>
+ // Apply footer styles based on theme
+ function applyFooterStyles() {
+ const footer = document.getElementById('warrackerFooter');
+ const link = document.getElementById('warrackerFooterLink');
+ const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark' ||
+ document.documentElement.classList.contains('dark-mode') ||
+ document.body.classList.contains('dark-mode');
+
+ if (footer) {
+ if (isDarkMode) {
+ footer.style.cssText = 'margin-top: 50px; padding: 20px; text-align: center; border-top: 1px solid #444; background-color: #2d2d2d; color: #e0e0e0; font-size: 0.9rem;';
+ if (link) link.style.cssText = 'color: #4dabf7; text-decoration: none; font-weight: 500;';
+ } else {
+ footer.style.cssText = 'margin-top: 50px; padding: 20px; text-align: center; border-top: 1px solid #e0e0e0; background-color: #ffffff; color: #333333; font-size: 0.9rem;';
+ if (link) link.style.cssText = 'color: #3498db; text-decoration: none; font-weight: 500;';
+ }
+ }
+ }
+
+ document.addEventListener('DOMContentLoaded', applyFooterStyles);
+ const observer = new MutationObserver(applyFooterStyles);
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'class'] });
+ observer.observe(document.body, { attributes: true, attributeFilter: ['class'] });
+ </script>
+
</body>
-</html>
\ No newline at end of file
+</html>
diff --git a/frontend/status.js b/frontend/status.js
index b265212..eef9565 100644
--- a/frontend/status.js
+++ b/frontend/status.js
@@ -15,7 +15,9 @@
// Configuration
const STATUS_PAGE_API_BASE_URL = '/api/statistics';
+ const GLOBAL_STATUS_PAGE_API_BASE_URL = '/api/statistics/global';
const STATISTICS_API_URL = window.location.origin + STATUS_PAGE_API_BASE_URL;
+ const GLOBAL_STATISTICS_API_URL = window.location.origin + GLOBAL_STATUS_PAGE_API_BASE_URL;
let EXPIRING_SOON_DAYS = 30;
// IIFE-local variables
@@ -26,6 +28,11 @@
let currentStatusData = null;
let currentTimelineData = null;
let userCurrencySymbol = '$'; // Default currency symbol
+ let isGlobalView = false; // Track current view mode
+ let isViewControlsInitialized = false;
+ let isDashboardInitialized = false; // Prevent multiple initializations
+ let isDOMHandlerAttached = false; // Prevent multiple DOM handlers
+ let initDashboardPromise = null; // Track ongoing initialization
function setTheme(isDark) {
const theme = isDark ? 'dark' : 'light';
@@ -47,19 +54,25 @@
function redrawChartsWithNewTheme() {
console.log("Theme changed, redrawing charts from status.js IIFE...");
- if (statusChart && typeof statusChart.destroy === 'function') {
- statusChart.destroy();
- statusChart = null;
- }
- if (timelineChart && typeof timelineChart.destroy === 'function') {
- timelineChart.destroy();
- timelineChart = null;
- }
- if (currentStatusData) {
- createStatusChart(currentStatusData);
- }
- if (currentTimelineData) {
- createTimelineChart(currentTimelineData);
+ try {
+ if (statusChart && typeof statusChart.destroy === 'function') {
+ statusChart.destroy();
+ statusChart = null;
+ console.log('Destroyed status chart for theme change');
+ }
+ if (timelineChart && typeof timelineChart.destroy === 'function') {
+ timelineChart.destroy();
+ timelineChart = null;
+ console.log('Destroyed timeline chart for theme change');
+ }
+ if (currentStatusData) {
+ createStatusChart(currentStatusData);
+ }
+ if (currentTimelineData) {
+ createTimelineChart(currentTimelineData);
+ }
+ } catch (e) {
+ console.error('Error redrawing charts with new theme:', e);
}
}
@@ -99,12 +112,25 @@
method: 'GET',
headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json'}
};
- console.log('Fetching statistics from:', STATISTICS_API_URL);
- const response = await fetch(STATISTICS_API_URL, options);
+
+ // Check saved view scope preference to determine which API endpoint to use
+ const savedScope = loadViewScopePreference();
+ const shouldUseGlobalView = savedScope === 'global';
+
+ // Choose API endpoint based on saved preference
+ const apiUrl = shouldUseGlobalView ? GLOBAL_STATISTICS_API_URL : STATISTICS_API_URL;
+ console.log('Fetching statistics from:', apiUrl, '(Global view preference:', savedScope, ')');
+
+ const response = await fetch(apiUrl, options);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to fetch statistics: ${response.status} ${errorText}`);
}
+
+ // Update isGlobalView to match the loaded data
+ isGlobalView = shouldUseGlobalView;
+ console.log(`[DEBUG] Set isGlobalView to: ${isGlobalView}`);
+
return await response.json();
} catch (error) {
console.error('Error fetching statistics (status.js IIFE):', error);
@@ -118,11 +144,244 @@
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.innerHTML = `${message} <button class="toast-close">&times;</button>`;
- toast.querySelector('.toast-close').addEventListener('click', () => toast.remove());
+ const closeButton = toast.querySelector('.toast-close');
+ if (closeButton) {
+ closeButton.addEventListener('click', () => toast.remove());
+ }
toastContainer.appendChild(toast);
setTimeout(() => { if (toast.parentElement) toast.remove(); }, 3000);
}
+ // Global view functions
+ async function initViewControls() {
+ if (isViewControlsInitialized) return;
+
+ try {
+ // Check if global view is enabled for this user
+ const token = window.auth.getToken();
+ if (!token) return;
+
+ const response = await fetch('/api/settings/global-view-status', {
+ method: 'GET',
+ headers: { 'Authorization': `Bearer ${token}` }
+ });
+
+ if (response.ok) {
+ const result = await response.json();
+ if (result.enabled) {
+ showViewSwitcher();
+ setupViewSwitcherListeners();
+
+ // Load and apply saved view scope preference
+ const savedScope = loadViewScopePreference();
+ if (savedScope === 'global') {
+ // Apply global view silently without saving preference again
+ isGlobalView = true;
+ updateViewButtons();
+ updateDashboardTitle();
+ updateTableColumns();
+ } else {
+ // Apply personal view (default)
+ isGlobalView = false;
+ updateViewButtons();
+ updateDashboardTitle();
+ updateTableColumns();
+ }
+
+ isViewControlsInitialized = true;
+ }
+ }
+ } catch (error) {
+ console.error('Error checking global view status:', error);
+ // Default to showing view switcher if error occurs (for admins)
+ if (getUserType() === 'admin') {
+ showViewSwitcher();
+ setupViewSwitcherListeners();
+
+ // Load and apply saved view scope preference
+ const savedScope = loadViewScopePreference();
+ if (savedScope === 'global') {
+ // Apply global view silently without saving preference again
+ isGlobalView = true;
+ updateViewButtons();
+ updateDashboardTitle();
+ updateTableColumns();
+ } else {
+ // Apply personal view (default)
+ isGlobalView = false;
+ updateViewButtons();
+ updateDashboardTitle();
+ updateTableColumns();
+ }
+
+ isViewControlsInitialized = true;
+ }
+ }
+ }
+
+ function getUserType() {
+ try {
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ return userInfo.is_admin ? 'admin' : 'user';
+ } catch {
+ return 'user';
+ }
+ }
+
+ /**
+ * Get the appropriate localStorage key prefix based on user type
+ * @returns {string} The prefix to use for localStorage keys
+ */
+ function getPreferenceKeyPrefix() {
+ return getUserType() === 'admin' ? 'admin_' : 'user_';
+ }
+
+ /**
+ * Save view scope preference to localStorage
+ * @param {string} scope - 'personal' or 'global'
+ */
+ function saveViewScopePreference(scope) {
+ try {
+ const prefix = getPreferenceKeyPrefix();
+ localStorage.setItem(`${prefix}viewScope`, scope);
+ console.log(`Saved view scope preference: ${scope} with prefix: ${prefix}`);
+ } catch (error) {
+ console.error('Error saving view scope preference:', error);
+ }
+ }
+
+ /**
+ * Load view scope preference from localStorage
+ * @returns {string} The saved preference ('personal', 'global', or 'personal' as default)
+ */
+ function loadViewScopePreference() {
+ try {
+ const prefix = getPreferenceKeyPrefix();
+ const savedScope = localStorage.getItem(`${prefix}viewScope`);
+ console.log(`Loaded view scope preference: ${savedScope} with prefix: ${prefix}`);
+ return savedScope || 'personal'; // Default to personal view
+ } catch (error) {
+ console.error('Error loading view scope preference:', error);
+ return 'personal'; // Default to personal view on error
+ }
+ }
+
+ function showViewSwitcher() {
+ const viewSwitcher = document.getElementById('viewSwitcher');
+ if (viewSwitcher) {
+ viewSwitcher.style.display = 'flex';
+ }
+ }
+
+ function hideViewSwitcher() {
+ const viewSwitcher = document.getElementById('viewSwitcher');
+ if (viewSwitcher) {
+ viewSwitcher.style.display = 'none';
+ }
+ }
+
+ function setupViewSwitcherListeners() {
+ const personalViewBtn = document.getElementById('personalViewBtn');
+ const globalViewBtn = document.getElementById('globalViewBtn');
+
+ if (personalViewBtn) {
+ personalViewBtn.addEventListener('click', () => switchToPersonalView());
+ }
+ if (globalViewBtn) {
+ globalViewBtn.addEventListener('click', () => switchToGlobalView());
+ }
+ }
+
+ async function switchToPersonalView() {
+ if (!isGlobalView) return; // Already in personal view
+
+ isGlobalView = false;
+ updateViewButtons();
+ updateDashboardTitle();
+ updateTableColumns();
+
+ // Save view preference
+ saveViewScopePreference('personal');
+
+ isDashboardInitialized = false; // Reset to allow refresh with new view
+ await initDashboard();
+ }
+
+ async function switchToGlobalView() {
+ if (isGlobalView) return; // Already in global view
+
+ try {
+ // Check if global view is still available
+ const token = window.auth.getToken();
+ const response = await fetch('/api/settings/global-view-status', {
+ method: 'GET',
+ headers: { 'Authorization': `Bearer ${token}` }
+ });
+
+ if (response.ok) {
+ const result = await response.json();
+ if (result.enabled) {
+ isGlobalView = true;
+ updateViewButtons();
+ updateDashboardTitle();
+ updateTableColumns();
+
+ // Save view preference
+ saveViewScopePreference('global');
+
+ isDashboardInitialized = false; // Reset to allow refresh with new view
+ await initDashboard();
+ } else {
+ showToast('Global view is not available', 'error');
+ // Switch back to personal view if global is disabled
+ await switchToPersonalView();
+ }
+ } else {
+ throw new Error('Failed to check global view status');
+ }
+ } catch (error) {
+ console.error('Error switching to global view:', error);
+ showToast('Unable to switch to global view', 'error');
+ // Switch back to personal view on error
+ await switchToPersonalView();
+ }
+ }
+
+ function updateViewButtons() {
+ const personalViewBtn = document.getElementById('personalViewBtn');
+ const globalViewBtn = document.getElementById('globalViewBtn');
+
+ if (personalViewBtn && globalViewBtn) {
+ if (isGlobalView) {
+ personalViewBtn.classList.remove('active');
+ globalViewBtn.classList.add('active');
+ } else {
+ personalViewBtn.classList.add('active');
+ globalViewBtn.classList.remove('active');
+ }
+ }
+ }
+
+ function updateDashboardTitle() {
+ const dashboardTitle = document.getElementById('dashboardTitle');
+ if (dashboardTitle) {
+ if (window.i18next && window.i18next.t) {
+ dashboardTitle.textContent = isGlobalView ?
+ window.i18next.t('status.global_dashboard_title') :
+ window.i18next.t('status.dashboard_title');
+ } else {
+ dashboardTitle.textContent = isGlobalView ? 'Global Warranty Status Dashboard' : 'Warranty Status Dashboard';
+ }
+ }
+ }
+
+ function updateTableColumns() {
+ const ownerHeader = document.getElementById('ownerHeader');
+ if (ownerHeader) {
+ ownerHeader.style.display = isGlobalView ? 'table-cell' : 'none';
+ }
+ }
+
function updateSummaryCounts(statusData) {
const totalEl = document.getElementById('totalCount');
const activeEl = document.getElementById('activeCount');
@@ -137,26 +396,76 @@
function createStatusChart(stats) {
const ctxEl = document.getElementById('statusChart');
if (!ctxEl) { console.warn("statusChart canvas not found"); return; }
+
+ // Properly destroy existing chart
+ if (statusChart && typeof statusChart.destroy === 'function') {
+ try {
+ statusChart.destroy();
+ statusChart = null;
+ console.log('Destroyed existing status chart');
+ } catch (e) {
+ console.warn('Error destroying status chart:', e);
+ statusChart = null;
+ }
+ }
+
+ // Additional check: Clear any Chart.js instances on this canvas
+ const chartInstance = Chart.getChart(ctxEl);
+ if (chartInstance) {
+ console.log('Found existing Chart.js instance on statusChart canvas, destroying it');
+ chartInstance.destroy();
+ }
+
const ctx = ctxEl.getContext('2d');
if (!stats || typeof stats !== 'object') stats = { active: 0, expiring_soon: 0, expired: 0, total: 0 }; // Added total for safety
const active = stats.active || 0;
const expiringSoon = stats.expiring_soon || 0;
const expired = stats.expired || 0;
const trulyActive = Math.max(0, active - expiringSoon);
- if (statusChart && typeof statusChart.destroy === 'function') statusChart.destroy();
- statusChart = new Chart(ctx, {
- type: 'doughnut',
- data: {
- labels: ['Active', 'Expiring Soon', 'Expired'],
- datasets: [{ data: [trulyActive, expiringSoon, expired], backgroundColor: ['#4CAF50', '#FF9800', '#F44336'], borderWidth: 1 }]
- },
- options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom' } } }
- });
+
+ try {
+ // Get translated labels for chart
+ const activeLabel = i18next.t('warranties.active');
+ const expiringSoonLabel = i18next.t('warranties.expiring_soon');
+ const expiredLabel = i18next.t('warranties.expired');
+
+ statusChart = new Chart(ctx, {
+ type: 'doughnut',
+ data: {
+ labels: [activeLabel, expiringSoonLabel, expiredLabel],
+ datasets: [{ data: [trulyActive, expiringSoon, expired], backgroundColor: ['#4CAF50', '#FF9800', '#F44336'], borderWidth: 1 }]
+ },
+ options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom' } } }
+ });
+ console.log('Created new status chart');
+ } catch (e) {
+ console.error('Error creating status chart:', e);
+ }
}
function createTimelineChart(timelineData) {
const ctxEl = document.getElementById('timelineChart');
if (!ctxEl) { console.warn("timelineChart canvas not found"); return; }
+
+ // Properly destroy existing chart
+ if (timelineChart && typeof timelineChart.destroy === 'function') {
+ try {
+ timelineChart.destroy();
+ timelineChart = null;
+ console.log('Destroyed existing timeline chart');
+ } catch (e) {
+ console.warn('Error destroying timeline chart:', e);
+ timelineChart = null;
+ }
+ }
+
+ // Additional check: Clear any Chart.js instances on this canvas
+ const chartInstance = Chart.getChart(ctxEl);
+ if (chartInstance) {
+ console.log('Found existing Chart.js instance on timelineChart canvas, destroying it');
+ chartInstance.destroy();
+ }
+
const ctx = ctxEl.getContext('2d');
let labels = [];
let counts = [];
@@ -189,15 +498,22 @@
counts = timelineData.map(item => item.count || 0);
}
- if (timelineChart && typeof timelineChart.destroy === 'function') timelineChart.destroy();
- timelineChart = new Chart(ctx, {
- type: 'bar',
- data: {
- labels: labels,
- datasets: [{ label: 'Warranties Expiring', data: counts, backgroundColor: '#3498db', borderWidth: 1 }]
- },
- options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, ticks: { precision: 0 } } } }
- });
+ try {
+ // Get translated label for timeline chart
+ const timelineLabel = i18next.t('status.expiration_timeline');
+
+ timelineChart = new Chart(ctx, {
+ type: 'bar',
+ data: {
+ labels: labels,
+ datasets: [{ label: timelineLabel, data: counts, backgroundColor: '#3498db', borderWidth: 1 }]
+ },
+ options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, ticks: { precision: 0 } } } }
+ });
+ console.log('Created new timeline chart');
+ } catch (e) {
+ console.error('Error creating timeline chart:', e);
+ }
}
function updateRecentExpirations(recentWarrantiesData) {
@@ -218,7 +534,12 @@
serial_numbers: warranty.serial_numbers || [],
notes: warranty.notes,
manual_path: warranty.manual_path || null,
- other_document_path: warranty.other_document_path || null
+ other_document_path: warranty.other_document_path || null,
+ // Add user fields for global view
+ user_display_name: warranty.user_display_name,
+ username: warranty.username,
+ first_name: warranty.first_name,
+ last_name: warranty.last_name
}));
}
filterAndSortWarranties(); // This will render the table
@@ -234,7 +555,9 @@
tableBody.innerHTML = '';
if (!allWarranties || allWarranties.length === 0) {
- tableBody.innerHTML = '<tr><td colspan="4" style="text-align:center; padding: 20px;">No recently expired or expiring warranties.</td></tr>';
+ const colspan = isGlobalView ? 5 : 4;
+ const noWarrantiesMessage = i18next.t('status.recent_expirations_empty', 'No recently expired or expiring warranties.');
+ tableBody.innerHTML = `<tr><td colspan="${colspan}" style="text-align:center; padding: 20px;">${noWarrantiesMessage}</td></tr>`;
return;
}
@@ -296,7 +619,9 @@
});
if (displayWarranties.length === 0) {
- tableBody.innerHTML = '<tr><td colspan="4" style="text-align:center; padding: 20px;">No warranties match your search criteria.</td></tr>';
+ const colspan = isGlobalView ? 5 : 4;
+ const noMatchMessage = i18next.t('messages.no_results', 'No results found');
+ tableBody.innerHTML = `<tr><td colspan="${colspan}" style="text-align:center; padding: 20px;">${noMatchMessage}</td></tr>`;
return;
}
@@ -309,27 +634,45 @@
const todayForStatus = new Date(); todayForStatus.setHours(0,0,0,0);
if (warranty.is_lifetime) {
- statusText = 'Lifetime';
+ statusText = i18next.t('warranties.lifetime');
statusClass = 'status-lifetime';
} else {
const expirationDate = new Date(warranty.expiration_date);
expirationDate.setHours(0,0,0,0);
- if (expirationDate <= todayForStatus) { statusText = 'Expired'; statusClass = 'status-expired'; }
- else {
+ if (expirationDate <= todayForStatus) {
+ statusText = i18next.t('warranties.expired');
+ statusClass = 'status-expired';
+ } else {
const timeDiff = expirationDate - todayForStatus;
const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
- if (daysDiff <= EXPIRING_SOON_DAYS) { statusText = 'Expiring Soon'; statusClass = 'status-expiring'; }
- else { statusText = 'Active'; statusClass = 'status-active'; }
+ if (daysDiff <= EXPIRING_SOON_DAYS) {
+ statusText = i18next.t('warranties.expiring_soon');
+ statusClass = 'status-expiring';
+ } else {
+ statusText = i18next.t('warranties.active');
+ statusClass = 'status-active';
+ }
}
}
row.className = statusClass;
- row.innerHTML = `
- <td>${escapeHTML(warranty.product_name)}</td>
- <td>${warranty.purchase_date ? formatDateYYYYMMDD(new Date(warranty.purchase_date)) : 'N/A'}</td>
- <td>${warranty.is_lifetime ? 'Lifetime' : (warranty.expiration_date ? formatDateYYYYMMDD(new Date(warranty.expiration_date)) : 'N/A')}</td>
+ // Build row HTML based on current view mode
+ const lifetimeText = i18next.t('warranties.lifetime');
+ const naText = i18next.t('warranties.na', 'N/A');
+ let rowHTML = `
+ <td title="${escapeHTML(warranty.product_name)}">${escapeHTML(warranty.product_name)}</td>
+ <td>${warranty.purchase_date ? formatDateYYYYMMDD(new Date(warranty.purchase_date)) : naText}</td>
+ <td>${warranty.is_lifetime ? lifetimeText : (warranty.expiration_date ? formatDateYYYYMMDD(new Date(warranty.expiration_date)) : naText)}</td>
<td><span class="${statusClass}">${statusText}</span></td>
- `; // Make sure escapeHTML is used on all string data from warranty
+ `;
+
+ // Add owner column if in global view
+ if (isGlobalView) {
+ const ownerDisplay = warranty.user_display_name || warranty.username || 'Unknown User';
+ rowHTML += `<td title="${escapeHTML(ownerDisplay)}">${escapeHTML(ownerDisplay)}</td>`;
+ }
+
+ row.innerHTML = rowHTML; // Make sure escapeHTML is used on all string data from warranty
row.addEventListener('click', () => toggleWarrantyDetails(warranty.id, row));
});
}
@@ -424,12 +767,38 @@
dHtml += '<div style="flex: 1 1 300px;"><h4>Core Information</h4>';
dHtml += `<p><strong>Product URL:</strong> ${warrantyDetails.product_url ? `<a href="${warrantyDetails.product_url}" target="_blank" rel="noopener noreferrer">${escapeHTML(warrantyDetails.product_url)}</a>` : 'N/A'}</p>`;
dHtml += `<p><strong>Purchase Price:</strong> ${warrantyDetails.purchase_price !== null && warrantyDetails.purchase_price !== undefined ? escapeHTML(userCurrencySymbol) + parseFloat(warrantyDetails.purchase_price).toFixed(2) : 'N/A'}</p>`;
- dHtml += `<p><strong>Vendor:</strong> ${escapeHTML(warrantyDetails.vendor || '') || 'N/A'}</p></div>`;
+ dHtml += `<p><strong>Vendor:</strong> ${escapeHTML(warrantyDetails.vendor || '') || 'N/A'}</p>`;
+ dHtml += `<p><strong>Warranty Type:</strong> ${escapeHTML(warrantyDetails.warranty_type || '') || 'N/A'}</p></div>`;
dHtml += '<div style="flex: 1 1 300px;"><h4>Documents & Files</h4>';
- if(warrantyDetails.invoice_path) dHtml += `<p><strong>Invoice:</strong> <a href="#" onclick="window.openSecureFile('${escapeHTML(warrantyDetails.invoice_path)}'); return false;">View Invoice</a></p>`; else dHtml += '<p><strong>Invoice:</strong> N/A</p>';
- if(warrantyDetails.manual_path) dHtml += `<p><strong>Manual:</strong> <a href="#" onclick="window.openSecureFile('${escapeHTML(warrantyDetails.manual_path)}'); return false;">View Manual</a></p>`; else dHtml += '<p><strong>Manual:</strong> N/A</p>';
- if(warrantyDetails.other_document_path) dHtml += `<p><strong>Other Files:</strong> <a href="#" onclick="window.openSecureFile('${escapeHTML(warrantyDetails.other_document_path)}'); return false;">View Files</a></p>`; else dHtml += '<p><strong>Other Files:</strong> N/A</p>';
+
+ // Invoice - check both local and Paperless-ngx
+ if(warrantyDetails.invoice_path) {
+ dHtml += `<p><strong data-i18n="warranties.invoice_receipt_short">Invoice:</strong> <a href="#" onclick="window.openSecureFile('${escapeHTML(warrantyDetails.invoice_path)}'); return false;">View Invoice</a></p>`;
+ } else if(warrantyDetails.paperless_invoice_id) {
+ dHtml += `<p><strong data-i18n="warranties.invoice_receipt_short">Invoice:</strong> <a href="#" onclick="window.openPaperlessDocument(${warrantyDetails.paperless_invoice_id}); return false;">View Invoice</a> <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i></p>`;
+ } else {
+ dHtml += `<p><strong data-i18n="warranties.invoice_receipt_short">Invoice:</strong> N/A</p>`;
+ }
+
+ // Manual - check both local and Paperless-ngx
+ if(warrantyDetails.manual_path) {
+ dHtml += `<p><strong data-i18n="warranties.product_manual_short">Manual:</strong> <a href="#" onclick="window.openSecureFile('${escapeHTML(warrantyDetails.manual_path)}'); return false;">View Manual</a></p>`;
+ } else if(warrantyDetails.paperless_manual_id) {
+ dHtml += `<p><strong data-i18n="warranties.product_manual_short">Manual:</strong> <a href="#" onclick="window.openPaperlessDocument(${warrantyDetails.paperless_manual_id}); return false;">View Manual</a> <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i></p>`;
+ } else {
+ dHtml += `<p><strong data-i18n="warranties.product_manual_short">Manual:</strong> N/A</p>`;
+ }
+
+ // Other Files - check both local and Paperless-ngx
+ if(warrantyDetails.other_document_path) {
+ dHtml += `<p><strong data-i18n="warranties.files_short">Other Files:</strong> <a href="#" onclick="window.openSecureFile('${escapeHTML(warrantyDetails.other_document_path)}'); return false;">View Files</a></p>`;
+ } else if(warrantyDetails.paperless_other_id) {
+ dHtml += `<p><strong data-i18n="warranties.files_short">Other Files:</strong> <a href="#" onclick="window.openPaperlessDocument(${warrantyDetails.paperless_other_id}); return false;">View Files</a> <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i></p>`;
+ } else {
+ dHtml += `<p><strong data-i18n="warranties.files_short">Other Files:</strong> N/A</p>`;
+ }
+
dHtml += '</div>';
// DEBUG: Log serial numbers before rendering them in details view
@@ -468,6 +837,8 @@
function refreshDashboard() {
console.log("Refreshing dashboard from status.js IIFE...");
+ isDashboardInitialized = false; // Reset flag to allow refresh
+ initDashboardPromise = null; // Clear any existing promise
if (refreshDashboardBtn) refreshDashboardBtn.classList.add('loading');
initDashboard().finally(() => {
if (refreshDashboardBtn) refreshDashboardBtn.classList.remove('loading');
@@ -475,115 +846,139 @@
}
async function initDashboard() {
+ // If already initialized and not being refreshed, skip
+ if (isDashboardInitialized && !initDashboardPromise) {
+ console.log('Dashboard already initialized, skipping...');
+ return;
+ }
+
+ // If currently initializing, wait for the existing promise
+ if (initDashboardPromise) {
+ console.log('Dashboard initialization already in progress, waiting...');
+ return initDashboardPromise;
+ }
+
console.log('Initializing dashboard (status.js IIFE)...');
- try {
- showLoading();
- await loadUserPreferences();
- const data = await fetchStatistics();
- hideError();
-
- // 1. Use data.all_warranties for the main table content
- updateRecentExpirations(data.all_warranties || []);
-
- // 2. Construct the status_distribution object for charts and summary
- const statusDistributionData = {
- active: data.active || 0,
- expiring_soon: data.expiring_soon || 0,
- expired: data.expired || 0,
- total: data.total || 0
- };
-
- if (Object.keys(statusDistributionData).length > 0 && statusDistributionData.total > 0) {
- currentStatusData = statusDistributionData;
- updateSummaryCounts(statusDistributionData);
- createStatusChart(statusDistributionData);
- } else {
- console.warn("Status distribution data from API is incomplete or zero. Displaying empty/default chart/summary.");
- updateSummaryCounts({});
- createStatusChart({});
- }
-
- // --- BEGIN: Expiration Timeline Chart Fix ---
- // Instead of using only API timeline, generate a comprehensive timeline from all warranties
- let allWarrantiesForTimeline = [];
+
+ // Create promise to track initialization
+ initDashboardPromise = (async () => {
try {
- // Try to fetch all warranties for a complete timeline
- const token = window.auth && window.auth.getToken ? window.auth.getToken() : null;
- if (token) {
- const allWarrantiesResponse = await fetch('/api/warranties', {
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
+ showLoading();
+ await loadUserPreferences();
+ await initViewControls(); // Initialize view controls before fetching data
+ const data = await fetchStatistics();
+ hideError();
+
+ // 1. Use data.all_warranties for the main table content
+ updateRecentExpirations(data.all_warranties || []);
+
+ // 2. Construct the status_distribution object for charts and summary
+ const statusDistributionData = {
+ active: data.active || 0,
+ expiring_soon: data.expiring_soon || 0,
+ expired: data.expired || 0,
+ total: data.total || 0
+ };
+
+ if (Object.keys(statusDistributionData).length > 0 && statusDistributionData.total > 0) {
+ currentStatusData = statusDistributionData;
+ updateSummaryCounts(statusDistributionData);
+ createStatusChart(statusDistributionData);
+ } else {
+ console.warn("Status distribution data from API is incomplete or zero. Displaying empty/default chart/summary.");
+ updateSummaryCounts({});
+ createStatusChart({});
+ }
+
+ // --- BEGIN: Expiration Timeline Chart Fix ---
+ // Instead of using only API timeline, generate a comprehensive timeline from all warranties
+ let allWarrantiesForTimeline = [];
+ try {
+ // Try to fetch all warranties for a complete timeline
+ const token = window.auth && window.auth.getToken ? window.auth.getToken() : null;
+ if (token) {
+ const allWarrantiesResponse = await fetch('/api/warranties', {
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+ if (allWarrantiesResponse.ok) {
+ allWarrantiesForTimeline = await allWarrantiesResponse.json();
+ } else {
+ console.warn('Could not fetch all warranties for timeline, falling back to data.all_warranties');
+ allWarrantiesForTimeline = data.all_warranties || [];
}
- });
- if (allWarrantiesResponse.ok) {
- allWarrantiesForTimeline = await allWarrantiesResponse.json();
} else {
- console.warn('Could not fetch all warranties for timeline, falling back to data.all_warranties');
allWarrantiesForTimeline = data.all_warranties || [];
}
- } else {
+ } catch (err) {
+ console.error('Error fetching all warranties for timeline:', err);
allWarrantiesForTimeline = data.all_warranties || [];
}
- } catch (err) {
- console.error('Error fetching all warranties for timeline:', err);
- allWarrantiesForTimeline = data.all_warranties || [];
- }
-
- // Helper: Extract timeline data from all warranties
- function extractTimelineData(warranties) {
- // Map: { 'YYYY-MM': count }
- const timelineMap = {};
- warranties.forEach(w => {
- if (w.is_lifetime) return; // Skip lifetime warranties
- if (!w.expiration_date) return;
- let expDate = w.expiration_date;
- if (typeof expDate === 'string') {
- // Accept both 'YYYY-MM-DD' and ISO
- expDate = expDate.split('T')[0];
- const [year, month] = expDate.split('-');
- if (year && month) {
+
+ // Helper: Extract timeline data from all warranties
+ function extractTimelineData(warranties) {
+ // Map: { 'YYYY-MM': count }
+ const timelineMap = {};
+ warranties.forEach(w => {
+ if (w.is_lifetime) return; // Skip lifetime warranties
+ if (!w.expiration_date) return;
+ let expDate = w.expiration_date;
+ if (typeof expDate === 'string') {
+ // Accept both 'YYYY-MM-DD' and ISO
+ expDate = expDate.split('T')[0];
+ const [year, month] = expDate.split('-');
+ if (year && month) {
+ const key = `${year}-${month}`;
+ timelineMap[key] = (timelineMap[key] || 0) + 1;
+ }
+ } else if (expDate instanceof Date && !isNaN(expDate.getTime())) {
+ const year = expDate.getFullYear();
+ const month = (expDate.getMonth() + 1).toString().padStart(2, '0');
const key = `${year}-${month}`;
timelineMap[key] = (timelineMap[key] || 0) + 1;
}
- } else if (expDate instanceof Date && !isNaN(expDate.getTime())) {
- const year = expDate.getFullYear();
- const month = (expDate.getMonth() + 1).toString().padStart(2, '0');
- const key = `${year}-${month}`;
- timelineMap[key] = (timelineMap[key] || 0) + 1;
- }
- });
- // Convert to array sorted by date ascending
- const timelineArr = Object.entries(timelineMap)
- .map(([key, count]) => {
- const [year, month] = key.split('-');
- return { year: parseInt(year), month: parseInt(month), count };
- })
- .sort((a, b) => (a.year !== b.year) ? a.year - b.year : a.month - b.month);
- return timelineArr;
- }
-
- let timelineData = [];
- if (Array.isArray(allWarrantiesForTimeline) && allWarrantiesForTimeline.length > 0) {
- timelineData = extractTimelineData(allWarrantiesForTimeline);
- }
- if (timelineData.length > 0) {
- currentTimelineData = timelineData;
- createTimelineChart(timelineData);
- } else if (data.timeline && Array.isArray(data.timeline)) {
- // Fallback to API timeline if extraction fails
- currentTimelineData = data.timeline;
- createTimelineChart(data.timeline);
- } else {
- createTimelineChart([]);
+ });
+ // Convert to array sorted by date ascending
+ const timelineArr = Object.entries(timelineMap)
+ .map(([key, count]) => {
+ const [year, month] = key.split('-');
+ return { year: parseInt(year), month: parseInt(month), count };
+ })
+ .sort((a, b) => (a.year !== b.year) ? a.year - b.year : a.month - b.month);
+ return timelineArr;
+ }
+
+ let timelineData = [];
+ if (Array.isArray(allWarrantiesForTimeline) && allWarrantiesForTimeline.length > 0) {
+ timelineData = extractTimelineData(allWarrantiesForTimeline);
+ }
+ if (timelineData.length > 0) {
+ currentTimelineData = timelineData;
+ createTimelineChart(timelineData);
+ } else if (data.timeline && Array.isArray(data.timeline)) {
+ // Fallback to API timeline if extraction fails
+ currentTimelineData = data.timeline;
+ createTimelineChart(data.timeline);
+ } else {
+ createTimelineChart([]);
+ }
+ // --- END: Expiration Timeline Chart Fix ---
+
+ isDashboardInitialized = true;
+
+ } catch (error) {
+ console.error('Failed to initialize dashboard (status.js IIFE):', error);
+ showError('Failed to load dashboard data.', error.message);
+ isDashboardInitialized = false; // Allow retry on error
+ } finally {
+ hideLoading();
+ initDashboardPromise = null; // Clear the promise
}
- // --- END: Expiration Timeline Chart Fix ---
- } catch (error) {
- console.error('Failed to initialize dashboard (status.js IIFE):', error);
- showError('Failed to load dashboard data.', error.message);
- } finally {
- hideLoading();
- }
+ })();
+
+ return initDashboardPromise;
}
async function loadUserPreferences() {
@@ -764,7 +1159,7 @@
if (typeof window.openEditModal === 'function') {
window.currentEditingWarrantyIdStatusPage = warrantyId; // For observer
- window.openEditModal(finalWarrantyForModal);
+ await window.openEditModal(finalWarrantyForModal);
} else {
showToast('Edit modal functionality is not available.', 'error');
console.error("window.openEditModal is not a function. Ensure script.js is loaded and exposes it.");
@@ -845,8 +1240,14 @@
}
// DOMContentLoaded listener to initialize the dashboard and event listeners
- document.addEventListener('DOMContentLoaded', () => {
- console.log('Status page DOM loaded (status.js IIFE). Initializing dashboard and listeners.');
+ function initStatusPage() {
+ if (isDOMHandlerAttached) {
+ console.log('Status page DOM handler already attached, skipping...');
+ return;
+ }
+
+ isDOMHandlerAttached = true;
+ console.log('Status page DOM loaded (status.js IIFE). Waiting for i18n initialization...');
const headerDarkModeToggle = document.getElementById('darkModeToggle');
if (headerDarkModeToggle) {
@@ -858,7 +1259,29 @@
console.log('Header darkModeToggle not found by status.js for direct listener attachment. Theme changes via localStorage/theme-loader.js should still work.');
}
- initDashboard(); // Call IIFE's initDashboard
+ // Wait for i18n to be ready before initializing dashboard
+ function waitForI18nAndInit() {
+ if (window.i18n && window.i18n.t) {
+ console.log('i18n is ready, initializing dashboard...');
+ initDashboard(); // Call IIFE's initDashboard
+ } else {
+ console.log('Waiting for i18n ready event...');
+ window.addEventListener('i18nReady', function(event) {
+ console.log('i18n ready event received, initializing dashboard...', event.detail);
+ initDashboard(); // Call IIFE's initDashboard
+ }, { once: true });
+
+ // Fallback timeout in case i18n event doesn't fire
+ setTimeout(() => {
+ if (!window.i18n || !window.i18n.t) {
+ console.warn('i18n initialization timeout, proceeding anyway...');
+ initDashboard();
+ }
+ }, 5000);
+ }
+ }
+
+ waitForI18nAndInit();
// Setup event listeners for status page specific controls
if (refreshDashboardBtn) refreshDashboardBtn.addEventListener('click', refreshDashboard);
@@ -889,5 +1312,13 @@
console.warn(`(STATUS.JS) DOMContentLoaded/setTimeout: window.saveWarranty found, but NOT WRAPPED (flag: ${window.saveWarrantyObserverAttachedByStatus}). Observer NOT attached.`);
}
}, 500); // Delay by 500ms
- });
+ }
+
+ // Add event listener with protection against multiple calls
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', initStatusPage, { once: true });
+ } else {
+ // DOM is already loaded
+ setTimeout(initStatusPage, 0);
+ }
})();
diff --git a/frontend/style.css b/frontend/style.css
index f48b3c5..005c18e 100644
--- a/frontend/style.css
+++ b/frontend/style.css
@@ -27,6 +27,43 @@
border-color: var(--primary-dark) !important;
}
/* ===== GLOBAL STYLES ===== */
+:root {
+ /* Icon spacing for LTR/RTL: applies to icons next to text */
+}
+
+/* Consistent icon spacing and alignment for all languages */
+[class*="fa-"],
+.fa, .fas, .far, .fal, .fab, .icon-next {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ direction: ltr;
+ vertical-align: middle;
+ isolation: isolate;
+ position: relative;
+}
+
+/* Universal spacing for icons next to text */
+[class*="fa-"]:not(:only-child),
+.fa:not(:only-child),
+.fas:not(:only-child),
+.far:not(:only-child),
+.fal:not(:only-child),
+.fab:not(:only-child),
+.icon-next:not(:only-child) {
+ margin-inline: 0.5em;
+}
+
+/* Remove margin when icon is alone */
+[class*="fa-"]:only-child,
+.fa:only-child,
+.fas:only-child,
+.far:only-child,
+.fal:only-child,
+.fab:only-child,
+.icon-next:only-child {
+ margin-inline: 0;
+}
:root[data-theme="light"] {
--bg-color: #f5f5f5;
--card-bg: #ffffff;
@@ -617,6 +654,7 @@ input.invalid {
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 20px;
margin-top: 20px;
+ align-items: stretch; /* Explicitly set to ensure equal heights */
}
.warranty-card {
@@ -628,7 +666,7 @@ input.invalid {
border: 1px solid var(--border-color);
display: flex;
flex-direction: column;
- height: auto; /* Allow height to be determined by content */
+ /* height: auto; */ /* Remove to allow grid stretch */
}
.warranty-card:hover {
@@ -655,6 +693,7 @@ input.invalid {
padding: 15px;
background-color: rgba(0, 0, 0, 0.03);
border-bottom: 1px solid var(--border-color);
+ position: relative;
}
.warranty-title {
@@ -2278,13 +2317,109 @@ input.invalid {
color: white;
}
+/* Admin View Switcher - reuse the same styling pattern */
+.admin-view-switcher {
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+ min-width: 120px;
+ margin-left: 15px; /* Add some spacing from the regular view switcher */
+}
+
+.admin-view-switcher .view-buttons {
+ display: flex;
+ border: 1px solid var(--primary-color);
+ border-radius: var(--border-radius);
+ overflow: hidden;
+}
+
+.admin-view-switcher .view-btn {
+ background-color: var(--bg-color);
+ border: none;
+ color: var(--primary-color);
+ padding: 8px 12px;
+ cursor: pointer;
+ transition: var(--transition);
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-weight: 500;
+}
+
+.admin-view-switcher .view-btn:not(:last-child) {
+ border-right: 1px solid var(--primary-color);
+}
+
+.admin-view-switcher .view-btn:hover {
+ background-color: rgba(var(--primary-rgb), 0.1);
+ color: var(--primary-dark);
+}
+
+.admin-view-switcher .view-btn.active {
+ background-color: var(--primary-color);
+ color: white;
+}
+
+/* View-only placeholder for non-owned warranties in global view */
+.action-btn-placeholder {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 32px;
+ border: 1px solid #ddd;
+ border-radius: 4px;
+ background-color: transparent;
+ color: #666;
+ cursor: default;
+ opacity: 0.5;
+}
+
+.action-btn-placeholder:hover {
+ background-color: rgba(0, 0, 0, 0.05);
+}
+
+[data-theme="dark"] .action-btn-placeholder {
+ border-color: #555;
+ color: #999;
+}
+
+[data-theme="dark"] .action-btn-placeholder:hover {
+ background-color: rgba(255, 255, 255, 0.05);
+}
+
+/* User info styling for global view */
+.warranty-info div:has(strong:contains("Owner")) {
+ background-color: rgba(var(--primary-rgb), 0.1);
+ border-left: 3px solid var(--primary-color);
+ padding: 4px 8px;
+ margin-bottom: 8px;
+ border-radius: 4px;
+ font-weight: 500;
+}
+
+/* Alternative approach for better browser support */
+.warranty-info div strong:contains("Owner") {
+ color: var(--primary-color);
+}
+
+.warranty-info div:first-child:has(strong) {
+ background-color: rgba(var(--primary-rgb), 0.1);
+ border-left: 3px solid var(--primary-color);
+ padding: 4px 8px;
+ margin-bottom: 8px;
+ border-radius: 4px;
+ font-weight: 500;
+}
+
/* Grid View (Default) */
.warranties-list.grid-view {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 20px;
margin-top: 20px;
- grid-auto-flow: row dense; /* Optimize grid item placement */
+ align-items: stretch; /* Explicitly set to ensure equal heights */
}
/* Make cards in grid view dynamic height based on content */
@@ -2525,6 +2660,12 @@ input.invalid {
width: 100%;
}
+ .admin-view-switcher {
+ margin-left: 0;
+ margin-top: 10px;
+ width: 100%;
+ }
+
/* Convert table view to card-like view on mobile */
.warranties-list.table-view {
display: block;
@@ -2614,6 +2755,13 @@ input.invalid {
z-index: 1;
}
+/* Currency symbol on the right side of input */
+.price-input-wrapper.currency-right .currency-symbol {
+ left: auto;
+ right: 12px;
+ pointer-events: none; /* Prevent interference with input */
+}
+
/* Default style for currency symbols (e.g., on cards) */
.currency-symbol {
display: inline; /* Ensure it stays inline */
@@ -2621,10 +2769,22 @@ input.invalid {
/* Remove absolute positioning properties if they were here */
}
+/* Currency symbol on the right side of numbers */
+.currency-symbol.currency-right {
+ margin-right: 0;
+ margin-left: 0.2em; /* Add space before the symbol when on the right */
+}
+
.price-input-wrapper .form-control {
padding-left: 25px;
}
+/* Adjust padding for right-positioned currency symbol */
+.price-input-wrapper.currency-right .form-control {
+ padding-left: 12px;
+ padding-right: 25px;
+}
+
/* Product name header at the top of cards */
.product-name-header {
width: 100%;
@@ -2698,30 +2858,65 @@ input.invalid {
display: flex;
padding: 15px;
flex: 1;
+ position: relative;
}
.warranty-info {
flex: 0 1 auto; /* Allow natural sizing */
display: flex;
flex-direction: column;
+ gap: 10px;
}
.warranty-info > div {
- margin-bottom: 8px;
+ display: flex;
+ align-items: center;
+ margin-bottom: 0;
}
.warranty-info > div:last-child {
margin-bottom: 0;
}
+.warranty-info > div i {
+ width: 20px;
+ margin-right: 8px;
+ color: #666;
+ font-size: 14px;
+ text-align: center;
+}
+
+.warranty-info > div span {
+ margin-left: 5px;
+ font-weight: 500;
+ color: var(--text-color);
+}
+
+:root[data-theme="dark"] .warranty-info > div i {
+ color: #999;
+}
+
/* Serial numbers section */
.serial-numbers {
- margin-top: 10px;
+ display: flex;
+ align-items: flex-start;
+ margin-top: 0;
+}
+
+.serial-numbers strong {
+ margin-right: 8px;
+ flex-shrink: 0;
+}
+
+.serial-numbers span {
+ margin-left: 5px;
+ font-weight: 500;
}
.serial-numbers ul {
margin: 5px 0 0 0;
padding-left: 20px;
+ flex: 1;
}
.serial-numbers li {
@@ -2750,6 +2945,18 @@ input.invalid {
.list-view .warranty-info > div {
margin-bottom: 0;
margin-right: 15px;
+ display: flex;
+ align-items: center;
+}
+
+.list-view .warranty-info > div i {
+ width: auto;
+ margin-right: 5px;
+}
+
+.list-view .warranty-info > div span {
+ margin-left: 5px;
+ font-weight: 500;
}
/* Document links row */
@@ -2779,6 +2986,22 @@ input.invalid {
flex-direction: column;
gap: 5px;
}
+
+ /* Additional mobile list view optimizations */
+ .warranties-list.list-view {
+ gap: 10px !important;
+ margin-top: 15px !important;
+ }
+
+ .list-view .warranty-card {
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
+ border: 1px solid var(--border-color) !important;
+ }
+
+ .list-view .warranty-card:hover {
+ transform: none !important; /* Disable hover transform on mobile */
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
+ }
}
/* GitHub link styling */
@@ -2866,15 +3089,30 @@ input.invalid {
.table-view .warranty-info > div {
margin-bottom: 4px;
font-size: 0.9rem;
+ display: flex;
+ align-items: center;
}
.table-view .warranty-info > div:last-child {
margin-bottom: 0;
}
+.table-view .warranty-info > div i {
+ width: auto;
+ margin-right: 5px;
+ font-size: 0.85rem;
+}
+
+.table-view .warranty-info > div span {
+ margin-left: 5px;
+}
+
/* Improve serial numbers display in table view */
.table-view .serial-numbers {
- margin-top: 5px;
+ margin-top: 0;
+ display: flex;
+ align-items: flex-start;
+ font-size: 0.9rem;
}
.table-view .serial-numbers ul {
@@ -3676,3 +3914,574 @@ input.invalid {
gap: 10px;
align-items: center;
}
+
+/* Style for the warranty duration group when hidden (due to lifetime checkbox) */
+#warrantyDurationFields.hidden {
+ display: none;
+}
+
+/* Warranty Entry Method Styling */
+.warranty-method-options {
+ display: flex !important;
+ flex-direction: row !important;
+ gap: 20px;
+ margin-top: 8px;
+ flex-wrap: wrap;
+}
+
+.warranty-method-options .radio-option {
+ display: flex !important;
+ flex-direction: row !important;
+ align-items: center;
+ cursor: pointer;
+ font-weight: normal;
+ margin: 0;
+ white-space: nowrap;
+}
+
+.warranty-method-options .radio-option input[type="radio"] {
+ margin-right: 8px;
+ cursor: pointer;
+ flex-shrink: 0;
+}
+
+.warranty-method-options .radio-option span {
+ user-select: none;
+ cursor: pointer;
+}
+
+/* Ensure both add and edit modal warranty methods display horizontally */
+#warrantyEntryMethod .warranty-method-options,
+#editWarrantyEntryMethod .warranty-method-options {
+ display: flex !important;
+ flex-direction: row !important;
+ gap: 20px;
+ flex-wrap: wrap;
+ align-items: center;
+}
+
+/* Mobile responsive - stack vertically only on very small screens if needed */
+@media (max-width: 480px) {
+ .warranty-method-options {
+ flex-direction: column !important;
+ gap: 10px;
+ }
+
+ .warranty-method-options .radio-option {
+ justify-content: flex-start;
+ }
+}
+
+/* Powered by Warracker footer */
+.warracker-footer {
+ margin-top: 50px;
+ padding: 20px;
+ text-align: center;
+ border-top: 1px solid #e0e0e0;
+ background-color: var(--card-bg) !important;
+ color: var(--text-color);
+ font-size: 0.9rem;
+}
+
+.warracker-footer a {
+ color: #3498db;
+ text-decoration: none;
+ font-weight: 500;
+}
+
+.warracker-footer a:hover {
+ color: #2980b9;
+ text-decoration: underline;
+}
+
+/* Dark theme styles */
+[data-theme="dark"] .warracker-footer {
+ border-top-color: #444;
+}
+
+[data-theme="dark"] .warracker-footer a {
+ color: #4dabf7;
+}
+
+[data-theme="dark"] .warracker-footer a:hover {
+ color: #339af0;
+}
+
+/* Also support html.dark-mode for older implementations */
+html.dark-mode .warracker-footer {
+ border-top-color: #444;
+}
+
+html.dark-mode .warracker-footer a {
+ color: #4dabf7;
+}
+
+html.dark-mode .warracker-footer a:hover {
+ color: #339af0;
+}
+
+@media (max-width: 768px) {
+ .warracker-footer {
+ margin-top: 30px;
+ padding: 15px;
+ font-size: 0.85rem;
+ }
+}
+
+/* ===== PRODUCT PHOTO STYLES ===== */
+.product-photo-thumbnail {
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 10;
+}
+
+/* RTL positioning for product photos */
+[dir="rtl"] .product-photo-thumbnail {
+ right: auto;
+ left: 8px;
+}
+
+.product-photo-thumbnail img {
+ border: 2px solid var(--border-color);
+ border-radius: 8px;
+ object-fit: cover;
+ transition: transform 0.2s ease, box-shadow 0.2s ease;
+ background-color: #f5f5f5;
+}
+
+.product-photo-thumbnail img:hover {
+ transform: scale(1.05);
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
+}
+
+.product-photo-thumbnail a {
+ display: block;
+ text-decoration: none;
+}
+
+.product-photo-thumbnail a:hover {
+ text-decoration: none;
+}
+
+.photo-preview {
+ margin-top: 10px;
+ text-align: center;
+}
+
+.photo-preview img {
+ border: 2px solid var(--border-color);
+ border-radius: 8px;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
+}
+
+/* Grid view photo positioning */
+.grid-view .product-photo-thumbnail img {
+ width: 80px;
+ height: 80px;
+}
+
+/* List view photo positioning */
+.list-view .product-photo-thumbnail img {
+ width: 180px;
+ height: 180px;
+}
+
+/* Table view photo positioning */
+.table-view .product-photo-thumbnail img {
+ width: 55px;
+ height: 55px;
+}
+
+/* Dark mode adjustments */
+:root[data-theme="dark"] .product-photo-thumbnail img {
+ border-color: var(--border-color);
+ background-color: #2a2a2a;
+}
+
+:root[data-theme="dark"] .photo-preview img {
+ border-color: var(--border-color);
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
+}
+
+/* Mobile responsiveness */
+@media (max-width: 768px) {
+ .grid-view .product-photo-thumbnail img {
+ width: 60px;
+ height: 60px;
+ }
+
+ .list-view .product-photo-thumbnail img {
+ width: 120px;
+ height: 120px;
+ }
+
+ .table-view .product-photo-thumbnail img {
+ width: 50px;
+ height: 50px;
+ }
+
+ .product-photo-thumbnail {
+ top: 6px;
+ right: 6px;
+ }
+
+ /* RTL mobile positioning */
+ [dir="rtl"] .product-photo-thumbnail {
+ right: auto;
+ left: 6px;
+ }
+}
+
+@media (max-width: 768px) {
+ .grid-view .product-photo-thumbnail img {
+ width: 30px;
+ height: 30px;
+ }
+ .list-view .product-photo-thumbnail img {
+ width: 25px;
+ height: 25px;
+ }
+ .table-view .product-photo-thumbnail img {
+ width: 20px;
+ height: 20px;
+ }
+ .product-photo-thumbnail {
+ margin-right: 5px;
+ }
+
+ /* RTL mobile margins */
+ [dir="rtl"] .product-photo-thumbnail {
+ margin-right: 0;
+ margin-left: 5px;
+ }
+}
+
+/* ===== PAPERLESS BROWSER STYLES ===== */
+.modal-large {
+ max-width: 90vw;
+ width: 900px;
+}
+
+.paperless-browse-section {
+ margin-top: 10px;
+ padding: 10px;
+ background-color: var(--light-gray);
+ border-radius: var(--border-radius);
+ border: 1px solid var(--border-color);
+}
+
+:root[data-theme="dark"] .paperless-browse-section {
+ background-color: var(--medium-gray);
+ border-color: var(--border-color);
+}
+
+.selected-paperless-doc {
+ margin-top: 8px;
+ padding: 8px 12px;
+ background-color: var(--primary-color);
+ color: white;
+ border-radius: 4px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.selected-paperless-doc .selected-doc-name {
+ font-weight: 500;
+ flex-grow: 1;
+}
+
+.selected-paperless-doc .btn-xs {
+ padding: 2px 6px;
+ font-size: 0.8em;
+ margin-left: 10px;
+}
+
+.paperless-browser-controls {
+ margin-bottom: 20px;
+}
+
+.search-section {
+ display: flex;
+ gap: 10px;
+ margin-bottom: 15px;
+ align-items: center;
+}
+
+.search-section input {
+ flex: 1;
+ min-width: 250px;
+ padding: 10px 12px;
+ font-size: 1rem;
+}
+
+.filter-section {
+ display: flex;
+ gap: 10px;
+}
+
+.filter-section select {
+ flex: 1;
+}
+
+.paperless-documents-list {
+ max-height: 400px;
+ overflow-y: auto;
+ border: 1px solid var(--border-color);
+ border-radius: var(--border-radius);
+ background-color: var(--card-bg);
+}
+
+.paperless-document-item {
+ padding: 12px 16px;
+ border-bottom: 1px solid var(--border-color);
+ cursor: pointer;
+ transition: background-color 0.2s;
+}
+
+.paperless-document-item:last-child {
+ border-bottom: none;
+}
+
+.paperless-document-item:hover {
+ background-color: var(--light-gray);
+}
+
+:root[data-theme="dark"] .paperless-document-item:hover {
+ background-color: var(--medium-gray);
+}
+
+.paperless-document-item.selected {
+ background-color: var(--primary-color);
+ color: white;
+}
+
+.paperless-document-item.selected:hover {
+ background-color: var(--primary-dark);
+}
+
+.document-title {
+ font-weight: 600;
+ font-size: 1.1em;
+ margin-bottom: 4px;
+}
+
+.document-meta {
+ font-size: 0.9em;
+ color: var(--dark-gray);
+ display: flex;
+ gap: 15px;
+ flex-wrap: wrap;
+}
+
+.paperless-document-item.selected .document-meta {
+ color: rgba(255, 255, 255, 0.8);
+}
+
+.document-tags {
+ display: flex;
+ gap: 4px;
+ flex-wrap: wrap;
+ margin-top: 6px;
+}
+
+.document-tag {
+ background-color: var(--medium-gray);
+ color: var(--text-color);
+ padding: 2px 6px;
+ border-radius: 12px;
+ font-size: 0.75em;
+}
+
+.paperless-document-item.selected .document-tag {
+ background-color: rgba(255, 255, 255, 0.2);
+ color: white;
+}
+
+.pagination-controls {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ gap: 15px;
+ margin-top: 15px;
+ padding: 10px;
+ flex-wrap: nowrap;
+}
+
+.pagination-controls button {
+ white-space: nowrap;
+ min-width: fit-content;
+ padding: 8px 12px;
+}
+
+.pagination-controls button:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+#pageInfo {
+ font-weight: 500;
+ color: var(--text-color);
+ white-space: nowrap;
+ min-width: fit-content;
+}
+
+.loading-message {
+ color: var(--dark-gray);
+ font-style: italic;
+}
+
+.no-documents-message {
+ text-align: center;
+ padding: 40px 20px;
+ color: var(--dark-gray);
+}
+
+.no-documents-message i {
+ font-size: 3em;
+ margin-bottom: 15px;
+ opacity: 0.5;
+}
+
+.no-documents-message h4 {
+ margin-bottom: 10px;
+ color: var(--text-color);
+}
+
+/* Mobile responsiveness for paperless browser */
+@media (max-width: 768px) {
+ .modal-large {
+ max-width: 95vw;
+ width: 95vw;
+ }
+
+ .search-section {
+ flex-direction: column;
+ }
+
+ .filter-section {
+ flex-direction: column;
+ }
+
+ .paperless-documents-list {
+ max-height: 300px;
+ }
+
+ .document-meta {
+ flex-direction: column;
+ gap: 5px;
+ }
+
+ .pagination-controls {
+ flex-direction: row;
+ gap: 10px;
+ flex-wrap: nowrap;
+ }
+}
+
+
+/* RTL Language Support */
+[dir="rtl"] {
+ text-align: right;
+}
+
+[dir="rtl"] .container {
+ direction: rtl;
+}
+
+[dir="rtl"] .header-right-group {
+ flex-direction: row-reverse;
+}
+
+[dir="rtl"] .nav-links {
+ flex-direction: row-reverse;
+}
+
+[dir="rtl"] .nav-link {
+ margin-left: 0;
+ margin-right: 20px;
+}
+
+[dir="rtl"] .nav-link:last-child {
+ margin-right: 0;
+}
+
+[dir="rtl"] .form-group {
+ text-align: right;
+}
+
+[dir="rtl"] .form-control {
+ text-align: right;
+}
+
+[dir="rtl"] .btn {
+ text-align: center;
+}
+
+[dir="rtl"] .card {
+ text-align: right;
+}
+
+[dir="rtl"] .card-header {
+ text-align: right;
+}
+
+[dir="rtl"] .user-menu {
+ margin-left: 0;
+ margin-right: 15px;
+}
+
+[dir="rtl"] .user-menu-dropdown {
+ left: 0;
+ right: auto;
+}
+
+[dir="rtl"] .auth-buttons {
+ flex-direction: row-reverse;
+}
+
+[dir="rtl"] .social-links {
+ justify-content: flex-end;
+}
+
+[dir="rtl"] .about-card h3 {
+ flex-direction: row-reverse;
+}
+
+[dir="rtl"] .about-card h3 i {
+ margin-left: 10px;
+ margin-right: 0;
+}
+
+[dir="rtl"] .social-link {
+ flex-direction: row-reverse;
+}
+
+[dir="rtl"] .social-link i {
+ margin-left: 8px;
+ margin-right: 0;
+}
+
+[dir="rtl"] .preference-item {
+ text-align: right;
+}
+
+[dir="rtl"] .preference-item label {
+ text-align: right;
+}
+
+[dir="rtl"] .collapsible-header {
+ text-align: right;
+}
+
+[dir="rtl"] .collapse-icon {
+ transform: rotate(180deg);
+}
+
+[dir="rtl"] .collapse-icon.rotated {
+ transform: rotate(0deg);
+}
diff --git a/frontend/styles.css b/frontend/styles.css
index 90e4b1e..925f78a 100644
--- a/frontend/styles.css
+++ b/frontend/styles.css
@@ -216,4 +216,112 @@
#tagManagementModal {
z-index: 1050;
-}
\ No newline at end of file
+}
+
+/* ============================================================================
+ Paperless-ngx Integration Styles
+ ============================================================================ */
+
+/* Storage Selection Styles */
+.storage-selection {
+ margin-bottom: 15px;
+ padding: 12px;
+ background-color: var(--bg-secondary);
+ border-radius: 8px;
+ border: 1px solid var(--border-color);
+}
+
+.storage-options {
+ display: flex;
+ gap: 20px;
+ flex-wrap: wrap;
+}
+
+.storage-option {
+ display: flex;
+ align-items: center;
+ cursor: pointer;
+ padding: 8px 12px;
+ border-radius: 6px;
+ transition: all 0.2s ease;
+ border: 1px solid transparent;
+ background-color: var(--bg-main);
+}
+
+.storage-option:hover {
+ background-color: var(--bg-accent);
+ border-color: var(--border-color);
+}
+
+.storage-option input[type="radio"] {
+ margin: 0;
+ margin-right: 8px;
+}
+
+.storage-label {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-weight: 500;
+ color: var(--text-primary);
+}
+
+.storage-label i {
+ font-size: 14px;
+ width: 16px;
+ text-align: center;
+}
+
+.storage-option input[type="radio"]:checked + .storage-label {
+ color: var(--accent-color);
+}
+
+.storage-option input[type="radio"]:checked + .storage-label i {
+ color: var(--accent-color);
+}
+
+/* Paperless-ngx info alert */
+.alert {
+ padding: 12px 16px;
+ margin-bottom: 20px;
+ border-radius: 6px;
+ border: 1px solid transparent;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+
+.alert-info {
+ background-color: #e7f3ff;
+ border-color: #b8d4f0;
+ color: #31708f;
+}
+
+.alert-info i {
+ color: #31708f;
+}
+
+/* Dark mode support for Paperless-ngx elements */
+.dark-mode .storage-selection {
+ background-color: var(--bg-secondary);
+ border-color: var(--border-color);
+}
+
+.dark-mode .storage-option {
+ background-color: var(--bg-main);
+ color: var(--text-primary);
+}
+
+.dark-mode .storage-option:hover {
+ background-color: var(--bg-accent);
+}
+
+.dark-mode .alert-info {
+ background-color: rgba(49, 112, 143, 0.1);
+ border-color: rgba(49, 112, 143, 0.3);
+ color: #a8c8e1;
+}
+
+.dark-mode .alert-info i {
+ color: #a8c8e1;
+}
\ No newline at end of file
diff --git a/frontend/sw.js b/frontend/sw.js
index 9bc952d..11a4c21 100644
--- a/frontend/sw.js
+++ b/frontend/sw.js
@@ -1,9 +1,21 @@
-const CACHE_NAME = 'warracker-cache-v1';
+const CACHE_NAME = 'warracker-cache-v20250119001';
const urlsToCache = [
'./',
'./index.html',
- './style.css',
- './script.js',
+ './settings-new.html',
+ './status.html',
+ './style.css?v=20250119001',
+ './settings-styles.css?v=20250119001',
+ './header-fix.css?v=20250119001',
+ './mobile-header.css?v=20250119001',
+ './script.js?v=20250119001',
+ './auth.js?v=20250119001',
+ './settings-new.js?v=20250119001',
+ './status.js?v=20250119001',
+ './theme-loader.js?v=20250119001',
+ './footer-fix.js?v=20250119001',
+ './footer-content.js?v=20250119001',
+ './js/i18n.js?v=20250119001',
'./manifest.json',
'./img/favicon-16x16.png',
'./img/favicon-32x32.png',
diff --git a/frontend/temp-toast-debug.js b/frontend/temp-toast-debug.js
new file mode 100644
index 0000000..96e68ee
--- /dev/null
+++ b/frontend/temp-toast-debug.js
@@ -0,0 +1,28 @@
+// Temporary toast notification enhancement for debugging
+// Add this to browser console to make success messages more visible
+
+(function() {
+ console.log('🍞 Toast Debug Enhancement Loaded');
+
+ // Override showToast to make it more visible
+ const originalShowToast = window.showToast;
+
+ window.showToast = function(message, type = 'info', duration = 5000) {
+ console.log(`🍞 TOAST NOTIFICATION: ${message} (Type: ${type})`);
+
+ // Call original function
+ if (originalShowToast) {
+ originalShowToast.call(this, message, type, duration);
+ }
+
+ // Also show an alert for debugging (remove this in production)
+ if (type === 'success') {
+ alert(`SUCCESS: ${message}`);
+ }
+
+ // Add a visible console message
+ console.log(`%c${message}`, `color: ${type === 'success' ? 'green' : type === 'error' ? 'red' : 'blue'}; font-weight: bold; font-size: 16px;`);
+ };
+
+ console.log('Toast notifications will now be more visible with alerts');
+})();
\ No newline at end of file
diff --git a/frontend/version-checker.js b/frontend/version-checker.js
index f3f20ab..369c624 100644
--- a/frontend/version-checker.js
+++ b/frontend/version-checker.js
@@ -1,8 +1,9 @@
// Version checker for Warracker
document.addEventListener('DOMContentLoaded', () => {
- const currentVersion = '0.9.9.8'; // Current version of the application
+ const currentVersion = '0.10.1.9'; // Current version of the application
const updateStatus = document.getElementById('updateStatus');
const updateLink = document.getElementById('updateLink');
+ const versionDisplay = document.getElementById('versionDisplay');
// Function to compare versions
function compareVersions(v1, v2) {
@@ -32,22 +33,50 @@ document.addEventListener('DOMContentLoaded', () => {
if (comparison > 0) {
// New version available
- updateStatus.textContent = `New version ${data.tag_name} available!`;
+ if (window.i18next && window.i18next.t) {
+ updateStatus.textContent = window.i18next.t('about.new_version_available', { version: data.tag_name });
+ } else {
+ updateStatus.textContent = `New version ${data.tag_name} available!`;
+ }
updateStatus.style.color = 'var(--success-color)';
updateLink.href = data.html_url;
updateLink.style.display = 'inline-block';
} else {
// Up to date
- updateStatus.textContent = 'You are using the latest version';
+ if (window.i18next && window.i18next.t) {
+ updateStatus.textContent = window.i18next.t('about.latest_version');
+ } else {
+ updateStatus.textContent = 'You are using the latest version';
+ }
updateStatus.style.color = 'var(--success-color)';
}
} catch (error) {
console.error('Error checking for updates:', error);
- updateStatus.textContent = 'Failed to check for updates';
+ if (window.i18next && window.i18next.t) {
+ updateStatus.textContent = window.i18next.t('about.update_check_failed');
+ } else {
+ updateStatus.textContent = 'Failed to check for updates';
+ }
updateStatus.style.color = 'var(--error-color)';
}
}
+ // Update version display if element exists
+ if (versionDisplay) {
+ // Wait for i18next to be ready
+ const updateVersionDisplay = () => {
+ if (window.i18next && window.i18next.t) {
+ versionDisplay.textContent = window.i18next.t('about.version') + ' v' + currentVersion;
+ } else {
+ versionDisplay.textContent = 'Version v' + currentVersion;
+ }
+ };
+
+ // Try immediately and also after a delay for i18next
+ updateVersionDisplay();
+ setTimeout(updateVersionDisplay, 500);
+ }
+
// Check for updates when the page loads
checkForUpdates();
});
\ No newline at end of file
diff --git a/images/demo.gif b/images/demo.gif
deleted file mode 100644
index a3deba2..0000000
Binary files a/images/demo.gif and /dev/null differ
diff --git a/images/demo2.gif b/images/demo2.gif
new file mode 100644
index 0000000..9f4ef5f
Binary files /dev/null and b/images/demo2.gif differ
diff --git a/locales/ar/translation.json b/locales/ar/translation.json
new file mode 100644
index 0000000..bc24b42
--- /dev/null
+++ b/locales/ar/translation.json
@@ -0,0 +1,568 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "متتبع الضمان",
+ "nav": {
+ "home": "الرئيسية",
+ "status": "الحالة",
+ "settings": "الإعدادات",
+ "about": "حول"
+ },
+ "auth": {
+ "login": "تسجيل الدخول",
+ "logout": "تسجيل الخروج",
+ "register": "التسجيل",
+ "username": "اسم المستخدم",
+ "password": "كلمة المرور",
+ "email": "البريد الإلكتروني",
+ "first_name": "الاسم الأول",
+ "last_name": "اسم العائلة",
+ "forgot_password": "نسيت كلمة المرور؟",
+ "reset_password": "إعادة تعيين كلمة المرور",
+ "confirm_password": "تأكيد كلمة المرور",
+ "create_account_title": "إنشاء حسابك",
+ "first_name_optional": "الاسم الأول (اختياري)",
+ "last_name_optional": "اسم العائلة (اختياري)",
+ "username_hint": "يجب أن يكون اسم المستخدم فريدًا وسيتم استخدامه لتسجيل الدخول.",
+ "email_address": "عنوان البريد الإلكتروني",
+ "toggle_password": "إظهار/إخفاء كلمة المرور",
+ "password_hint_simple": "يجب أن تتكون كلمة المرور من 8 أحرف على الأقل وتتضمن أحرفًا كبيرة وصغيرة وأرقامًا.",
+ "password_requirements": "متطلبات كلمة المرور:",
+ "req_length": "8 أحرف على الأقل",
+ "req_uppercase": "حرف كبير واحد على الأقل",
+ "req_lowercase": "حرف صغير واحد على الأقل",
+ "req_number": "رقم واحد على الأقل",
+ "req_special": "حرف خاص واحد على الأقل",
+ "create_account": "إنشاء حساب",
+ "already_have_account": "هل لديك حساب بالفعل؟",
+ "reset_password_title": "Warracker - إعادة تعيين كلمة المرور",
+ "reset_your_password": "إعادة تعيين كلمة المرور الخاصة بك",
+ "reset_password_info": "أدخل عنوان بريدك الإلكتروني أدناه وسنرسل لك رابطًا لإعادة تعيين كلمة المرور الخاصة بك.",
+ "send_reset_link": "إرسال رابط إعادة التعيين",
+ "back_to_login": "العودة إلى تسجيل الدخول",
+ "set_new_password_title": "Warracker - تعيين كلمة مرور جديدة",
+ "set_new_password": "تعيين كلمة مرور جديدة",
+ "new_password": "كلمة المرور الجديدة",
+ "confirm_new_password": "تأكيد كلمة المرور الجديدة",
+ "invalid_or_expired_link": "رابط غير صالح أو منتهي الصلاحية",
+ "invalid_link_info": "رابط إعادة تعيين كلمة المرور الذي نقرت عليه غير صالح أو انتهت صلاحيته.",
+ "request_new_reset_link": "طلب رابط إعادة تعيين جديد"
+ },
+ "warranties": {
+ "title": "الضمانات",
+ "title_global": "ضمانات جميع المستخدمين",
+ "add_new": "إضافة ضمان جديد",
+ "edit": "تحرير الضمان",
+ "delete": "حذف الضمان",
+ "product_name": "اسم المنتج",
+ "purchase_date": "تاريخ الشراء",
+ "warranty_duration": "مدة الضمان",
+ "years": "سنوات",
+ "months": "شهور",
+ "days": "أيام",
+ "vendor": "البائع",
+ "serial_numbers": "الأرقام التسلسلية",
+ "purchase_price": "سعر الشراء",
+ "notes": "الملاحظات",
+ "tags": "العلامات",
+ "status": "الحالة",
+ "expiration_date": "تاريخ انتهاء الصلاحية",
+ "active": "نشط",
+ "expired": "منتهي الصلاحية",
+ "expiring_soon": "تنتهي قريباً",
+ "lifetime": "مدى الحياة",
+ "no_warranties": "لا توجد ضمانات حتى الآن. أضف ضمانك الأول للبدء.",
+ "search_placeholder": "البحث بالاسم، البائعين، الملاحظات، العلامة، أو الرقم التسلسلي...",
+ "warranty_type": "نوع الضمان",
+ "other_document": "مستند آخر",
+ "product": "المنتج",
+ "expiration": "انتهاء الصلاحية",
+ "actions": "الإجراءات",
+ "no_warranties_title": "لا توجد ضمانات",
+ "no_warranties_desc": "ليس لديك أي ضمانات حتى الآن. أضف ضمانك الأول!",
+ "add_warranty": "إضافة ضمان",
+ "warranty_entry_method": "طريقة إدخال الضمان",
+ "warranty_duration_option": "مدة الضمان",
+ "exact_expiration_option": "تاريخ انتهاء دقيق",
+ "warranty_period": "فترة الضمان",
+ "expiration_date_label": "تاريخ الانتهاء",
+ "currency": "العملة",
+ "add_tags": "إضافة علامات",
+ "add_tags_desc": "تساعدك العلامات على تنظيم وتصفية ضماناتك",
+ "save_changes": "حفظ التغييرات",
+ "confirm_delete": "تأكيد الحذف",
+ "manage_tags": "إدارة العلامات",
+ "add_tag": "إضافة علامة",
+ "unknown_status": "حالة غير معروفة",
+ "expiring_soon_days": "تنتهي قريباً ({{days}} {{dayText}})",
+ "days_remaining": "{{days}} {{dayText}} متبقي",
+ "day_one": "يوم",
+ "day_two": "يومان",
+ "day_few": "أيام",
+ "day_many": "يومًا",
+ "day_other": "أيام",
+ "month_one": "شهر",
+ "month_two": "شهران",
+ "month_few": "أشهر",
+ "month_many": "شهرًا",
+ "month_other": "أشهر",
+ "year_one": "سنة",
+ "year_two": "سنتان",
+ "year_few": "سنوات",
+ "year_many": "سنة",
+ "year_other": "سنوات",
+ "na": "غير متاح",
+ "age": "العمر",
+ "warranty": "الضمان",
+ "warranty_ends": "ينتهي الضمان",
+ "price": "السعر",
+ "serial_number": "الرقم التسلسلي",
+ "type": "النوع",
+ "owner": "المالك",
+ "product_website": "موقع المنتج",
+ "existing_tags": "العلامات الموجودة",
+ "edit_warranty": "تحرير الضمان",
+ "warranty_type_standard": "قياسي",
+ "warranty_type_extended": "ممدد",
+ "warranty_type_manufacturer": "الشركة المصنعة",
+ "warranty_type_third_party": "طرف ثالث",
+ "warranty_type_store": "متجر",
+ "warranty_type_premium": "مميز",
+ "warranty_type_limited": "محدود",
+ "warranty_type_full": "كامل",
+ "warranty_type_parts_only": "قطع الغيار فقط",
+ "warranty_type_labor_only": "العمالة فقط",
+ "warranty_type_international": "دولي",
+ "warranty_type_accidental_damage": "ضرر عرضي",
+ "warranty_type_other": "أخرى (مخصص)",
+ "warranty_type_custom_placeholder": "أدخل نوع ضمان مخصص",
+ "notes_placeholder": "ملاحظات إضافية حول هذا الضمان...",
+ "tags_help_text": "العلامات تساعدك في تنظيم وتصفية ضماناتك",
+ "search_add_tag_placeholder": "البحث أو إضافة علامة جديدة...",
+ "upload_new_file_replace": "تحميل ملف جديد للاستبدال",
+ "current_other_document": "المستند الحالي",
+ "no_other_document_uploaded": "لم يتم تحميل مستند آخر",
+ "other_document_will_be_deleted": "سيتم حذف المستند الآخر عند الحفظ",
+ "files_optional": "ملفات (ZIP/RAR، اختياري)",
+ "invoice_receipt_short": "فاتورة",
+ "product_manual_short": "كتيب",
+ "files_short": "ملفات",
+ "summary": "ملخص",
+ "product_url_optional": "رابط المنتج (اختياري)",
+ "enter_serial_number": "أدخل الرقم التسلسلي",
+ "vendor_optional": "البائع (اختياري)",
+ "vendor_placeholder": "مثل Amazon، Best Buy، إلخ",
+ "lifetime_warranty": "ضمان مدى الحياة",
+ "warranty_type_optional": "نوع الضمان (اختياري)",
+ "select_warranty_type": "اختر نوع الضمان...",
+ "standard": "عادي",
+ "extended": "ممدد",
+ "manufacturer": "الشركة المصنعة",
+ "third_party": "طرف ثالث",
+ "store": "متجر",
+ "premium": "مميز",
+ "limited": "محدود",
+ "full": "كامل",
+ "parts_only": "قطع فقط",
+ "labor_only": "عمالة فقط",
+ "international": "دولي",
+ "accidental_damage": "ضرر عرضي",
+ "other_custom": "أخرى (مخصص)",
+ "enter_custom_warranty_type": "أدخل نوع ضمان مخصص",
+ "purchase_price_optional": "سعر الشراء (اختياري)",
+ "notes_optional": "ملاحظات (اختياري)",
+ "add_any_notes": "أضف أي ملاحظات حول هذا الضمان...",
+ "product_photo_optional": "صورة المنتج (اختياري)",
+ "choose_photo": "اختر صورة",
+ "invoice_receipt": "فاتورة/إيصال",
+ "store_locally": "حفظ محلياً",
+ "store_in_paperless": "حفظ في Paperless-ngx",
+ "choose_file": "اختر ملف",
+ "browse_paperless": "تصفح مستندات Paperless-ngx",
+ "product_manual_optional": "دليل المنتج (اختياري)",
+ "files_zip_rar_optional": "ملفات (ZIP/RAR، اختياري)",
+ "search_or_add_tag": "ابحث أو أضف علامة جديدة...",
+ "product_information": "معلومات المنتج",
+ "product_url": "رابط المنتج",
+ "warranty_details": "تفاصيل الضمان",
+ "product_photo": "صورة المنتج",
+ "product_manual": "دليل المنتج",
+ "files": "ملفات",
+ "documents": "مستندات",
+ "selected_tags": "العلامات المحددة",
+ "previous_tab": "السابق",
+ "next_tab": "التالي",
+ "delete_photo": "حذف الصورة",
+ "delete_invoice": "حذف الفاتورة",
+ "delete_manual": "حذف الدليل",
+ "delete_files": "حذف الملفات",
+ "current_photo": "الصورة الحالية:",
+ "current_invoice": "الفاتورة الحالية:",
+ "current_manual": "الدليل الحالي:",
+ "current_document": "المستند الحالي:",
+ "upload_new_photo_replace": "(ارفع صورة جديدة للاستبدال)",
+ "no_photo_uploaded": "لم يتم رفع أي صورة",
+ "no_invoice_uploaded": "لم يتم رفع أي فاتورة",
+ "no_manual_uploaded": "لم يتم رفع أي دليل",
+ "no_document_uploaded": "لم يتم رفع أي مستند آخر",
+ "photo_will_be_deleted": "سيتم حذف الصورة عند الحفظ",
+ "invoice_will_be_deleted": "سيتم حذف الفاتورة عند الحفظ",
+ "manual_will_be_deleted": "سيتم حذف الدليل عند الحفظ",
+ "document_will_be_deleted": "سيتم حذف المستند الآخر عند الحفظ",
+ "confirm_delete_message": "هل أنت متأكد من أنك تريد حذف هذا الضمان؟ لا يمكن التراجع عن هذا الإجراء.",
+ "new_tag_name": "اسم العلامة الجديدة",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "سنوات",
+ "months_placeholder": "شهور",
+ "days_placeholder": "أيام",
+ "add_any_notes_placeholder": "أضف أي ملاحظات حول هذه الضمانة...",
+ "enter_serial_number": "أدخل الرقم التسلسلي",
+ "add_serial_number": "إضافة رقم تسلسلي آخر"
+ },
+ "settings": {
+ "title": "الإعدادات",
+ "account_settings": "إعدادات الحساب",
+ "preferences": "التفضيلات",
+ "language": "اللغة",
+ "select_language": "اختر لغتك المفضلة",
+ "dark_mode": "الوضع المظلم",
+ "dark_mode_desc": "التبديل بين السمة الفاتحة والمظلمة",
+ "currency": "العملة",
+ "timezone": "المنطقة الزمنية",
+ "date_format": "تنسيق التاريخ",
+ "expiring_soon_days": "أيام انتهاء الصلاحية قريباً",
+ "save_changes": "حفظ التغييرات",
+ "current_user": "تحرير الملف الشخصي لـ:",
+ "your_email": "بريدك الإلكتروني:",
+ "first_name": "الاسم الأول",
+ "last_name": "اسم العائلة",
+ "email": "البريد الإلكتروني",
+ "save_profile": "حفظ الملف الشخصي",
+ "default_view": "العرض الافتراضي",
+ "default_view_desc": "اختر العرض المفضل للضمانات",
+ "grid_view": "عرض الشبكة",
+ "list_view": "عرض القائمة",
+ "table_view": "عرض الجدول",
+ "currency_symbol": "رمز العملة",
+ "currency_symbol_desc": "اختر الرمز لعرض الأسعار",
+ "currency_position": "موضع العملة",
+ "currency_position_desc": "اختر ما إذا كان رمز العملة يظهر على يسار أو يمين الأرقام",
+ "expiring_soon_days_desc": "عدد الأيام قبل انتهاء الضمان للتمييز كـ \"تنتهي قريباً\"",
+ "date_format_desc": "اختر كيفية عرض التواريخ",
+ "save_preferences": "حفظ التفضيلات",
+ "notification_settings": "إعدادات الإشعارات",
+ "notification_channel": "قناة الإشعارات",
+ "notification_channel_desc": "اختر كيفية تلقي الإشعارات",
+ "notification_disabled": "معطل",
+ "notification_email": "البريد الإلكتروني",
+ "notification_apprise": "Apprise",
+ "notification_both": "كلاهما",
+ "email_settings": "إعدادات البريد الإلكتروني",
+ "notification_frequency": "تكرار الإشعارات",
+ "notification_frequency_desc": "كم مرة تتلقى إشعارات البريد الإلكتروني",
+ "daily": "يومياً",
+ "weekly": "أسبوعياً",
+ "monthly": "شهرياً",
+ "notification_time": "وقت الإشعار",
+ "timezone_desc": "منطقتك الزمنية المحلية للإشعارات",
+ "apprise_settings": "إعدادات Apprise",
+ "apprise_frequency": "تكرار إشعارات Apprise",
+ "apprise_frequency_desc": "كم مرة تتلقى إشعارات Apprise",
+ "apprise_time": "وقت إشعار Apprise",
+ "apprise_timezone": "المنطقة الزمنية لـ Apprise",
+ "apprise_timezone_desc": "منطقتك الزمنية المحلية لإشعارات Apprise",
+ "save_notification_settings": "حفظ إعدادات الإشعار",
+ "security": "الأمان",
+ "change_password": "تغيير كلمة المرور",
+ "change_password_desc": "حدث كلمة المرور الخاصة بك",
+ "change": "تغيير",
+ "current_password": "كلمة المرور الحالية",
+ "new_password": "كلمة المرور الجديدة",
+ "confirm_password": "تأكيد كلمة المرور",
+ "update_password": "تحديث كلمة المرور",
+ "cancel": "إلغاء",
+ "danger_zone": "منطقة الخطر",
+ "delete_account": "حذف الحساب",
+ "delete_account_desc": "احذف حسابك وجميع بياناتك بشكل دائم",
+ "admin_settings": "إعدادات المدير",
+ "admin_actions": "إجراءات المدير",
+ "refresh_data": "تحديث البيانات",
+ "check_admin_status": "فحص حالة المدير",
+ "show_users_list": "عرض قائمة المستخدمين",
+ "test_api": "اختبار API",
+ "send_notifications": "إرسال إشعارات الضمان",
+ "check_scheduler": "التحقق من حالة المجدول",
+ "site_settings": "إعدادات الموقع",
+ "registration_enabled": "التسجيل مفعل",
+ "registration_enabled_desc": "السماح للمستخدمين الجدد بالتسجيل",
+ "email_base_url": "عنوان URL الأساسي للبريد الإلكتروني",
+ "global_view_enabled": "العرض العام مفعل",
+ "global_view_admin_only": "العرض العام للمسؤول فقط",
+ "save_site_settings": "حفظ إعدادات الموقع",
+ "oidc_configuration": "تكوين OIDC SSO",
+ "enable_oidc": "تمكين OIDC SSO",
+ "oidc_provider_name": "اسم مزود OIDC",
+ "client_id": "معرف العميل",
+ "client_secret": "سر العميل",
+ "issuer_url": "عنوان URL للمصدر",
+ "scope": "النطاق",
+ "save_oidc_settings": "حفظ إعدادات OIDC",
+ "oidc_sso_desc": "السماح للمستخدمين بتسجيل الدخول عبر موفر OIDC.",
+ "oidc_only_mode": "وضع تسجيل الدخول OIDC فقط",
+ "oidc_only_mode_desc": "إخفاء نموذج تسجيل الدخول التقليدي باسم المستخدم/كلمة المرور والسماح فقط بتسجيل الدخول عبر OIDC. <strong>تحذير:</strong> تأكد من تكوين OIDC بشكل صحيح قبل تمكين هذا الخيار.",
+ "oidc_provider_name_desc": "الاسم الداخلي لعميل OIDC (على سبيل المثال، 'oidc').",
+ "client_secret_desc": "قيمة حساسة. مخزنة في قاعدة البيانات. يلزم إعادة تشغيل التطبيق حتى تدخل التغييرات حيز التنفيذ.",
+ "issuer_url_desc": "عنوان URL الأساسي لموفر OIDC الخاص بك.",
+ "scope_desc": "نطاقات OIDC مفصولة بمسافات.",
+ "oidc_restart_message": "يلزم إعادة تشغيل التطبيق حتى تدخل إعدادات OIDC حيز التنفيذ بالكامل.",
+ "api_token": "رمز API",
+ "view_documents": "عرض المستندات في Warracker",
+ "connection_testing": "اختبار الاتصال",
+ "apprise_notifications": "إشعارات Apprise",
+ "enable_apprise": "تمكين إشعارات Apprise",
+ "loading": "جار التحميل...",
+ "time_of_day_notification": "وقت اليوم لتلقي الإشعارات (بتنسيق 24 ساعة)",
+ "paperless_ngx_settings": "إعدادات Paperless-ngx",
+ "paperless_ngx_about_title": "حول تكامل Paperless-ngx:",
+ "paperless_ngx_about_desc": "تتيح لك هذه الميزة الاختيارية تخزين مستندات الضمان في مثيل Paperless-ngx المستضاف ذاتيًا بدلاً من تخزينها محليًا. عند التمكين، يمكن للمستخدمين اختيار مكان تخزين كل مستند: محليًا أو في Paperless-ngx.",
+ "paperless_ngx_desc": "تكوين التكامل مع نظام إدارة المستندات Paperless-ngx",
+ "enable_paperless": "تمكين تكامل Paperless-ngx",
+ "paperless_url": "عنوان URL لـ Paperless-ngx",
+ "paperless_token": "رمز API",
+ "paperless_token_desc": "رمز مصادقة API الخاص بك في Paperless-ngx",
+ "paperless_token_desc_generate": "أنشئ رمز API من مثيل Paperless-ngx الخاص بك (الإعدادات → رموز API).",
+ "paperless_view_in_app": "عرض المستندات في التطبيق",
+ "paperless_view_in_app_desc": "فتح المستندات داخل التطبيق بدلاً من علامة تبويب جديدة",
+ "debug_config": "تكوين التصحيح",
+ "test_upload": "اختبار التحميل",
+ "save_paperless_settings": "حفظ إعدادات Paperless-ngx",
+ "apprise_desc": "تكوين Apprise لتسليم الإشعارات المتقدمة إلى خدمات متعددة",
+ "apprise_desc_system_wide": "تمكين أو تعطيل إشعارات Apprise على مستوى النظام",
+ "apprise_not_available_title": "Apprise غير متوفر:",
+ "apprise_not_available_desc": "مكتبة إشعارات Apprise غير مثبتة أو غير متوفرة. ميزات الإشعارات معطلة.",
+ "apprise_url": "عنوان URL لـ Apprise",
+ "apprise_url_desc": "عنوان URL لخدمة إشعارات Apprise الخاصة بك",
+ "apprise_mode": "وضع الإشعارات",
+ "apprise_mode_desc": "اختر متى يتم إرسال إشعارات Apprise",
+ "apprise_mode_global": "ملخص عالمي",
+ "apprise_mode_individual": "لكل مستخدم",
+ "test_paperless": "اختبار اتصال Paperless",
+ "test_apprise": "اختبار اتصال Apprise",
+ "apprise_warranty_scope": "نطاق الضمان",
+ "apprise_warranty_scope_desc": "اختر الضمانات التي سيتم تضمينها في الإشعارات",
+ "all_warranties": "جميع الضمانات",
+ "personal_warranties": "الضمانات الشخصية فقط",
+ "all_users_warranties": "ضمانات جميع المستخدمين",
+ "admin_warranties_only": "ضمانات المسؤول فقط",
+ "apprise_notification_days": "أيام الإشعار",
+ "apprise_notification_days_desc": "أيام قبل انتهاء الصلاحية لإرسال الإشعارات (مفصولة بفواصل، على سبيل المثال، \"7,30\" لمدة 7 أيام و 30 يومًا قبل)",
+ "apprise_check_frequency": "تردد التحقق",
+ "apprise_check_frequency_desc": "كم مرة يتحقق النظام من الضمانات التي تنتهي صلاحيتها (إعداد عالمي)",
+ "apprise_title_prefix": "بادئة عنوان الرسالة",
+ "apprise_title_prefix_desc": "بادئة تضاف إلى عناوين الإشعارات (على سبيل المثال، ينتج عن \"[Warracker]\" \"[Warracker] ضمانات تنتهي صلاحيتها قريبًا\")",
+ "apprise_test_url": "عنوان URL للاختبار (اختياري)",
+ "apprise_test_url_desc": "اختياري: عنوان URL لإرسال إشعارات الاختبار فقط (لن يتم حفظه في التكوين الرئيسي)",
+ "save_apprise_settings": "حفظ إعدادات Apprise",
+ "validate_urls": "التحقق من صحة عناوين URL",
+ "send_expiration_notifications_now": "إرسال إشعارات انتهاء الصلاحية الآن",
+ "apprise_current_status": "الحالة الحالية",
+ "apprise_urls_configured": "عناوين URL التي تم تكوينها:",
+ "apprise_supported_services": "الخدمات المدعومة",
+ "apprise_supported_services_desc": "يدعم Apprise أكثر من 80 خدمة إعلامية بما في ذلك: Discord و Slack و Telegram والبريد الإلكتروني (Gmail و Outlook) و Webhooks و Microsoft Teams و Matrix و Pushover و Ntfy و Gotify وغيرها الكثير.",
+ "view_full_list_of_supported_services": "عرض القائمة الكاملة للخدمات المدعومة",
+ "ownership_management": "إدارة الملكية",
+ "transfer_ownership": "نقل الملكية",
+ "warning_title": "تحذير:",
+ "transfer_ownership_warning": "نقل ملكية التطبيق إلى مستخدم مسؤول آخر. هذا الإجراء لا رجعة فيه.",
+ "transfer_ownership_desc": "بمجرد نقل الملكية، ستصبح مسؤولاً عادياً وسيكون للمالك الجديد السيطرة النهائية على التطبيق.",
+ "select_new_owner": "حدد المالك الجديد (يجب أن يكون مسؤولاً)",
+ "select_admin_user": "حدد مستخدمًا مسؤولاً...",
+ "transfer_ownership_button": "نقل الملكية",
+ "transfer_ownership_irreversible": "هذا الإجراء لا يمكن التراجع عنه.",
+ "transfer_ownership_confirmation": "أنت على وشك نقل ملكية التطبيق إلى",
+ "after_this_transfer": "بعد هذا النقل:",
+ "transfer_ownership_consequence_1": "سوف تصبح مسؤولاً عادياً",
+ "transfer_ownership_consequence_2": "سيكون للمالك الجديد السيطرة النهائية على التطبيق",
+ "transfer_ownership_consequence_3": "فقط المالك الجديد يمكنه نقل الملكية مرة أخرى",
+ "transfer_ownership_type_to_confirm": "للتأكيد، يرجى كتابة \"TRANSFER\" في الحقل أدناه:"
+ },
+ "actions": {
+ "save": "حفظ",
+ "cancel": "إلغاء",
+ "delete": "حذف",
+ "edit": "تحرير",
+ "export": "تصدير",
+ "import": "استيراد",
+ "refresh": "تحديث",
+ "search": "بحث",
+ "clear": "مسح",
+ "upload": "تحميل",
+ "download": "تنزيل",
+ "manage_tags": "إدارة العلامات",
+ "close": "إغلاق",
+ "save_changes": "حفظ التغييرات"
+ },
+ "filters": {
+ "all_status": "كل الحالات",
+ "all_tags": "كل العلامات",
+ "all_vendors": "كل البائعين",
+ "all_types": "كل الأنواع",
+ "sort_by": "فرز حسب",
+ "sort_expiration": "تاريخ الانتهاء",
+ "sort_purchase": "تاريخ الشراء",
+ "sort_age": "العمر",
+ "sort_name": "اسم المنتج",
+ "sort_vendor": "البائع",
+ "sort_warranty_type": "نوع الضمان",
+ "status": "الحالة",
+ "tags": "العلامات",
+ "vendor": "البائع",
+ "warranty_type": "نوع الضمان",
+ "view": "العرض",
+ "scope": "النطاق"
+ },
+ "messages": {
+ "success": "نجاح",
+ "error": "خطأ",
+ "warning": "تحذير",
+ "loading": "جار التحميل...",
+ "saved": "تم حفظ التغييرات بنجاح",
+ "deleted": "تم حذف العنصر بنجاح",
+ "confirm_delete": "هل أنت متأكد أنك تريد حذف هذا العنصر؟",
+ "no_results": "لم يتم العثور على نتائج",
+ "file_too_large": "الملف كبير جدا",
+ "invalid_file_type": "نوع الملف غير صالح",
+ "fill_first_last_name": "يرجى ملء الاسم الأول والأخير",
+ "email_cannot_be_empty": "عنوان البريد الإلكتروني لا يمكن أن يكون فارغًا.",
+ "enter_valid_email": "يرجى إدخال عنوان بريد إلكتروني صالح.",
+ "profile_updated_successfully": "تم تحديث الملف الشخصي بنجاح",
+ "preferences_saved_successfully": "تم حفظ التفضيلات بنجاح.",
+ "fill_password_fields": "يرجى ملء جميع حقول كلمة المرور",
+ "passwords_do_not_match": "كلمات المرور الجديدة غير متطابقة",
+ "password_min_length": "يجب أن تكون كلمة المرور 8 أحرف على الأقل",
+ "type_delete_to_confirm": "يرجى كتابة DELETE للتأكيد",
+ "account_deleted_successfully": "تم حذف الحساب بنجاح",
+ "account_cannot_delete_offline": "لا يمكن حذف الحساب في وضع عدم الاتصال",
+ "failed_delete_account": "فشل في حذف الحساب. يرجى المحاولة مرة أخرى.",
+ "user_updated_successfully": "تم تحديث المستخدم بنجاح",
+ "user_deleted_successfully": "تم حذف المستخدم بنجاح",
+ "user_id_missing": "معرف المستخدم مفقود",
+ "failed_load_users": "فشل في تحميل المستخدمين",
+ "error_loading_users": "خطأ في تحميل المستخدمين",
+ "select_user_transfer_ownership": "يرجى تحديد مستخدم لنقل الملكية إليه",
+ "ownership_transferred_successfully": "تم نقل الملكية بنجاح! جارٍ تحديث الصفحة...",
+ "failed_load_site_settings": "فشل في تحميل إعدادات الموقع. يرجى المحاولة مرة أخرى.",
+ "invalid_email_base_url": "تنسيق URL أساسي للبريد الإلكتروني غير صالح. يجب أن يبدأ بـ http:// أو https://",
+ "no_site_settings_to_save": "لا توجد إعدادات موقع لحفظها.",
+ "site_settings_saved_successfully": "تم حفظ إعدادات الموقع بنجاح",
+ "failed_save_site_settings": "فشل في حفظ إعدادات الموقع",
+ "oidc_settings_saved_successfully": "تم حفظ إعدادات OIDC بنجاح.",
+ "failed_save_oidc_settings": "فشل في حفظ إعدادات OIDC.",
+ "api_endpoint_accessible": "نقطة نهاية API قابلة للوصول",
+ "api_endpoint_not_accessible": "نقطة نهاية API غير قابلة للوصول. الحالة: ",
+ "only_admins_send_notifications": "يمكن للمسؤولين فقط إرسال إشعارات الضمان",
+ "notifications_triggered_successfully": "تم تشغيل الإشعارات بنجاح",
+ "notification_settings_saved_successfully": "تم حفظ إعدادات الإشعارات بنجاح",
+ "apprise_settings_saved_successfully": "تم حفظ إعدادات Apprise بنجاح",
+ "test_notification_sent_successfully": "تم إرسال إشعار الاختبار بنجاح",
+ "no_urls_to_validate": "لا توجد عناوين URL للتحقق من صحتها",
+ "paperless_settings_saved_successfully": "تم حفظ إعدادات Paperless-ngx بنجاح!",
+ "enter_valid_paperless_url": "يرجى إدخال عنوان URL صالح (مثل https://paperless.yourdomain.com)",
+ "enter_paperless_url_first": "يرجى إدخال عنوان URL لـ Paperless-ngx أولاً",
+ "paperless_connection_test_successful": "نجح اختبار اتصال Paperless-ngx!",
+ "paperless_connection_test_failed": "فشل اختبار اتصال Paperless-ngx",
+ "enter_api_token_test_connection": "يرجى إدخال رمز API لاختبار الاتصال",
+ "failed_load_user_data": "فشل في تحميل بيانات المستخدم. يرجى المحاولة مرة أخرى.",
+ "could_not_connect_user_data": "لا يمكن الاتصال لاسترداد بيانات المستخدم. عرض المعلومات المحفوظة مؤقتًا.",
+ "preferences_saved_locally_failed_sync": "تم حفظ التفضيلات محليًا، لكن فشل في المزامنة مع الخادم: ",
+ "preferences_saved_locally": "تم حفظ التفضيلات محليًا.",
+ "correct_errors_in_tab": "يرجى تصحيح الأخطاء في التبويب المظلل قبل المتابعة.",
+ "please_fill_out_this_field": "يرجى ملء هذا الحقل.",
+ "warranty_added_successfully": "تم إضافة الضمان بنجاح",
+ "tag_name_required": "اسم العلامة مطلوب",
+ "tag_creation_function_not_found": "وظيفة إنشاء العلامة غير موجودة",
+ "tag_created_successfully": "تم إنشاء العلامة بنجاح",
+ "tag_updated_successfully": "تم تحديث العلامة بنجاح",
+ "tag_deleted_successfully": "تم حذف العلامة بنجاح",
+ "failed_to_create_tag": "فشل في إنشاء العلامة",
+ "failed_to_update_tag": "فشل في تحديث العلامة",
+ "failed_to_delete_tag": "فشل في حذف العلامة"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية",
+ "ru": "Русский",
+ "uk": "Українська",
+ "zh_CN": "简体中文",
+ "zh_HK": "繁體中文",
+ "ja": "日本語",
+ "pt": "Português",
+ "ko": "한국어"
+ },
+ "status": {
+ "title": "حالة النظام",
+ "dashboard_title": "لوحة معلومات حالة الضمان",
+ "global_dashboard_title": "لوحة معلومات حالة الضمان العالمية",
+ "overview": "نظرة عامة",
+ "statistics": "الإحصائيات",
+ "total_warranties": "إجمالي الضمانات",
+ "active_warranties": "الضمانات النشطة",
+ "expiring_soon": "تنتهي قريباً",
+ "expired_warranties": "الضمانات المنتهية",
+ "warranty_distribution": "توزيع الضمانات",
+ "expiration_timeline": "الجدول الزمني للانتهاء",
+ "recent_activity": "النشاط الأخير",
+ "recent_expirations": "منتهية الصلاحية مؤخراً أو ستنتهي قريباً",
+ "recent_expirations_empty": "لا توجد ضمانات منتهية الصلاحية مؤخراً أو ستنتهي قريباً.",
+ "system_health": "صحة النظام",
+ "database_status": "حالة قاعدة البيانات",
+ "connected": "متصل",
+ "version": "الإصدار",
+ "uptime": "وقت التشغيل"
+ },
+ "about": {
+ "title": "حول Warracker",
+ "description": "نظام شامل لإدارة الضمانات مصمم لمساعدتك في تتبع وتنظيم وإدارة جميع ضمانات منتجاتك في منصة واحدة آمنة وسهلة الاستخدام.",
+ "version": "الإصدار",
+ "update_status": "حالة التحديث",
+ "checking_updates": "جارٍ التحقق من وجود تحديثات...",
+ "view_release_notes": "عرض ملاحظات الإصدار",
+ "project_info": "معلومات المشروع",
+ "project_description": "Warracker هو نظام إدارة ضمانات مفتوح المصدر مبني بتقنيات الويب الحديثة. يوفر طريقة آمنة وبديهية لإدارة ضمانات المنتجات وتتبع تواريخ انتهاء الصلاحية وتنظيم المستندات المهمة.",
+ "github_repository": "مستودع GitHub",
+ "releases": "الإصدارات",
+ "community_support": "المجتمع والدعم",
+ "community_description": "انضم إلى مجتمعنا للحصول على الدعم والمناقشات والتحديثات. أبلغ عن الأخطاء، واطلب الميزات، أو احصل على المساعدة من المستخدمين والمساهمين الآخرين.",
+ "discord_community": "مجتمع Discord",
+ "report_issues": "الإبلاغ عن المشكلات",
+ "developer_info": "معلومات المطور",
+ "developer_description": "تم تطوير وصيانة Warracker بواسطة Sassanix. المشروع مفتوح المصدر ويرحب بمساهمات المجتمع.",
+ "sassanix": "Sassanix",
+ "agpl_license": "رخصة AGPL-3.0",
+ "support_project": "ادعم المشروع",
+ "support_description": "إذا وجدت Warracker مفيدًا، ففكر في دعم تطويره!",
+ "new_version_available": "إصدار جديد {{version}} متوفر!",
+ "latest_version": "أنت تستخدم أحدث إصدار",
+ "update_check_failed": "فشل التحقق من وجود تحديثات",
+ "features": "الميزات",
+ "feature_track": "تتبع ضمانات المنتج",
+ "feature_notifications": "الحصول على إشعارات انتهاء الصلاحية",
+ "feature_documents": "تخزين مستندات الضمان",
+ "feature_reports": "إنشاء تقارير الضمان",
+ "feature_tags": "التنظيم باستخدام العلامات",
+ "feature_export": "تصدير بيانات الضمان",
+ "support": "الدعم",
+ "documentation": "التوثيق",
+ "github": "GitHub",
+ "license": "الترخيص",
+ "copyright": "حقوق الطبع والنشر",
+ "developed_by": "طور بواسطة"
+ }
+}
diff --git a/locales/cs/translation.json b/locales/cs/translation.json
new file mode 100644
index 0000000..b642242
--- /dev/null
+++ b/locales/cs/translation.json
@@ -0,0 +1,566 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "Sledovač záruk",
+ "nav": {
+ "home": "Domů",
+ "status": "Stav",
+ "settings": "Nastavení",
+ "about": "O aplikaci"
+ },
+ "auth": {
+ "login": "Přihlásit se",
+ "logout": "Odhlásit se",
+ "register": "Registrovat",
+ "username": "Uživatelské jméno",
+ "password": "Heslo",
+ "email": "E-mail",
+ "first_name": "Jméno",
+ "last_name": "Příjmení",
+ "forgot_password": "Zapomenuté heslo?",
+ "reset_password": "Resetovat heslo",
+ "confirm_password": "Potvrdit heslo",
+ "create_account_title": "Vytvořit si účet",
+ "first_name_optional": "Jméno (volitelné)",
+ "last_name_optional": "Příjmení (volitelné)",
+ "username_hint": "Uživatelské jméno musí být jedinečné a bude použito pro přihlášení.",
+ "email_address": "E-mailová adresa",
+ "toggle_password": "Zobrazit/skrýt heslo",
+ "password_hint_simple": "Heslo musí mít alespoň 8 znaků a obsahovat velká písmena, malá písmena a číslice.",
+ "password_requirements": "Požadavky na heslo:",
+ "req_length": "Alespoň 8 znaků",
+ "req_uppercase": "Alespoň 1 velké písmeno",
+ "req_lowercase": "Alespoň 1 malé písmeno",
+ "req_number": "Alespoň 1 číslice",
+ "req_special": "Alespoň 1 speciální znak",
+ "create_account": "Vytvořit účet",
+ "already_have_account": "Už máte účet?",
+ "reset_password_title": "Warracker - Resetovat heslo",
+ "reset_your_password": "Resetujte si heslo",
+ "reset_password_info": "Zadejte níže svou e-mailovou adresu a my vám zašleme odkaz pro resetování hesla.",
+ "send_reset_link": "Odeslat odkaz pro resetování",
+ "back_to_login": "Zpět na přihlášení",
+ "set_new_password_title": "Warracker - Nastavit nové heslo",
+ "set_new_password": "Nastavit nové heslo",
+ "new_password": "Nové heslo",
+ "confirm_new_password": "Potvrdit nové heslo",
+ "invalid_or_expired_link": "Neplatný nebo prošlý odkaz",
+ "invalid_link_info": "Odkaz pro resetování hesla, na který jste klikli, je neplatný nebo prošlý.",
+ "request_new_reset_link": "Požádat o nový odkaz pro resetování"
+ },
+ "warranties": {
+ "title": "Vaše záruky",
+ "title_global": "Záruky všech uživatelů",
+ "add_new": "Přidat novou záruku",
+ "edit": "Upravit záruku",
+ "delete": "Smazat záruku",
+ "product_name": "Název produktu",
+ "purchase_date": "Datum nákupu",
+ "warranty_duration": "Doba záruky",
+ "years": "Roky",
+ "months": "Měsíce",
+ "days": "Dny",
+ "vendor": "Prodejce",
+ "serial_numbers": "Sériová čísla",
+ "purchase_price": "Nákupní cena",
+ "notes": "Poznámky",
+ "tags": "Tagy",
+ "status": "Stav",
+ "expiration_date": "Datum vypršení",
+ "active": "Aktivní",
+ "expired": "Vypršelá",
+ "expiring_soon": "Brzy vyprší",
+ "lifetime": "Doživotní",
+ "no_warranties": "Zatím žádné záruky. Přidejte svou první záruku, abyste mohli začít.",
+ "search_placeholder": "Hledat podle názvu, prodejce, poznámek, tagu nebo sériového čísla...",
+ "warranty_type": "Typ záruky",
+ "other_document": "Jiný dokument",
+ "product": "Produkt",
+ "expiration": "Vypršení",
+ "actions": "Akce",
+ "no_warranties_title": "Zatím žádné záruky",
+ "no_warranties_desc": "Přidejte svou první záruku, abyste mohli začít",
+ "add_warranty": "Přidat záruku",
+ "warranty_entry_method": "Metoda zadání záruky",
+ "warranty_duration_option": "Doba záruky",
+ "exact_expiration_option": "Přesné datum vypršení",
+ "warranties_period": "Záruční doba",
+ "expiration_date_label": "Datum vypršení",
+ "currency": "Měna",
+ "add_tags": "Přidat tagy",
+ "add_tags_desc": "Tagy vám pomohou organizovat a filtrovat vaše záruky",
+ "save_changes": "Uložit změny",
+ "confirm_delete": "Potvrdit smazání",
+ "manage_tags": "Spravovat tagy",
+ "add_tag": "Přidat tag",
+ "unknown_status": "Neznámý stav",
+ "expiring_soon_days": "Brzy vyprší ({{days}} {{dayText}})",
+ "days_remaining": "Zbývá {{days}} {{dayText}}",
+ "day_one": "den",
+ "day_few": "dny",
+ "day_many": "dní",
+ "day_other": "dny",
+ "month_one": "měsíc",
+ "month_few": "měsíce",
+ "month_many": "měsíců",
+ "month_other": "měsíce",
+ "year_one": "rok",
+ "year_few": "roky",
+ "year_many": "let",
+ "year_other": "roky",
+ "na": "N/A",
+ "age": "Stáří",
+ "warranty": "Záruka",
+ "warranty_ends": "Záruka končí",
+ "price": "Cena",
+ "serial_number": "Sériové číslo",
+ "type": "Typ",
+ "owner": "Vlastník",
+ "product_website": "Webová stránka produktu",
+ "documents": "Dokumenty",
+ "summary": "Shrnutí",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "Roky",
+ "months_placeholder": "Měsíce",
+ "days_placeholder": "Dny",
+ "add_any_notes_placeholder": "Přidejte poznámky k této záruce...",
+ "product_url_optional": "URL produktu (volitelné)",
+ "enter_serial_number": "Zadejte sériové číslo",
+ "vendor_optional": "Prodejce (volitelné)",
+ "vendor_placeholder": "např. Amazon, Best Buy atd.",
+ "lifetime_warranty": "Doživotní záruka",
+ "warranty_type_optional": "Typ záruky (volitelné)",
+ "select_warranty_type": "Vyberte typ záruky...",
+ "standard": "Standardní",
+ "extended": "Prodloužená",
+ "manufacturer": "Výrobce",
+ "third_party": "Třetí strana",
+ "store": "Obchod",
+ "premium": "Prémiová",
+ "limited": "Omezená",
+ "full": "Plná",
+ "parts_only": "Pouze díly",
+ "labor_only": "Pouze práce",
+ "international": "Mezinárodní",
+ "accidental_damage": "Náhodné poškození",
+ "other_custom": "Jiné (vlastní)",
+ "enter_custom_warranty_type": "Zadejte vlastní typ záruky",
+ "purchase_price_optional": "Nákupní cena (volitelné)",
+ "notes_optional": "Poznámky (volitelné)",
+ "add_any_notes": "Přidejte jakékoli poznámky k této záruce...",
+ "product_photo_optional": "Fotografie produktu (volitelné)",
+ "choose_photo": "Vybrat fotografii",
+ "invoice_receipt": "Faktura/Účtenka",
+ "store_locally": "Uložit lokálně",
+ "store_in_paperless": "Uložit v Paperless-ngx",
+ "choose_file": "Vybrat soubor",
+ "browse_paperless": "Procházet dokumenty Paperless-ngx",
+ "product_manual_optional": "Návod k produktu (volitelné)",
+ "files_zip_rar_optional": "Soubory (ZIP/RAR, volitelné)",
+ "search_or_add_new_tag": "Hledat nebo přidat nový tag...",
+ "product_information": "Informace o produktu",
+ "product_url": "URL produktu",
+ "warranty_details": "Detaily záruky",
+ "product_photo": "Fotografie produktu",
+ "product_manual": "Návod k produktu",
+ "files": "Soubory",
+ "selected_tags": "Vybrané tagy",
+ "previous_tab": "Předchozí",
+ "next_tab": "Další",
+ "delete_photo": "Smazat fotografii",
+ "delete_invoice": "Smazat fakturu",
+ "delete_manual": "Smazat návod",
+ "delete_files": "Smazat soubory",
+ "current_photo": "Aktuální fotografie:",
+ "current_invoice": "Aktuální faktura:",
+ "current_manual": "Aktuální návod:",
+ "current_document": "Aktuální dokument:",
+ "upload_new_photo_replace": "(Nahrát novou fotografii pro nahrazení)",
+ "no_photo_uploaded": "Žádná fotografie nebyla nahrána",
+ "no_invoice_uploaded": "Žádná faktura nebyla nahrána",
+ "no_manual_uploaded": "Žádný návod nebyl nahrán",
+ "no_document_uploaded": "Žádný jiný dokument nebyl nahrán",
+ "photo_will_be_deleted": "Fotografie bude při uložení smazána",
+ "invoice_will_be_deleted": "Faktura bude při uložení smazána",
+ "manual_will_be_deleted": "Návod bude při uložení smazán",
+ "document_will_be_deleted": "Jiný dokument bude při uložení smazán",
+ "confirm_delete_message": "Jste si jisti, že chcete smazat tuto záruku? Tuto akci nelze vrátit.",
+ "new_tag_name": "Nový název tagu",
+ "existing_tags": "Existující tagy",
+ "edit_warranty": "Upravit záruku",
+ "warranty_type_standard": "Standardní",
+ "warranty_type_extended": "Prodloužená",
+ "warranty_type_manufacturer": "Výrobce",
+ "warranty_type_third_party": "Třetí strana",
+ "warranty_type_store": "Obchod",
+ "warranty_type_premium": "Prémiová",
+ "warranty_type_limited": "Omezená",
+ "warranty_type_full": "Plná",
+ "warranty_type_parts_only": "Pouze díly",
+ "warranty_type_labor_only": "Pouze práce",
+ "warranty_type_international": "Mezinárodní",
+ "warranty_type_accidental_damage": "Náhodné poškození",
+ "warranty_type_other": "Jiné (vlastní)",
+ "warranty_type_custom_placeholder": "Zadejte vlastní typ záruky",
+ "notes_placeholder": "Další poznámky k této záruce...",
+ "tags_help_text": "Tagy vám pomohou organizovat a filtrovat vaše záruky",
+ "search_add_tag_placeholder": "Hledat nebo přidat nový tag...",
+ "upload_new_file_replace": "Nahrát nový soubor pro nahrazení",
+ "current_other_document": "Aktuální jiný dokument",
+ "no_other_document_uploaded": "Žádný jiný dokument nebyl nahrán",
+ "other_document_will_be_deleted": "Jiný dokument bude při uložení smazán",
+ "files_optional": "Soubory (ZIP/RAR, volitelné)",
+ "invoice_receipt_short": "Faktura",
+ "product_manual_short": "Návod",
+ "files_short": "Soubory",
+ "enter_serial_number": "Zadejte sériové číslo",
+ "add_serial_number": "Přidat další sériové číslo"
+ },
+ "settings": {
+ "title": "Nastavení",
+ "account_settings": "Nastavení účtu",
+ "preferences": "Předvolby",
+ "language": "Jazyk",
+ "select_language": "Vyberte jazyk",
+ "dark_mode": "Tmavý režim",
+ "dark_mode_desc": "Přepínání mezi světlým a tmavým motivem",
+ "currency": "Měna",
+ "timezone": "Časové pásmo",
+ "date_format": "Formát data",
+ "expiring_soon_days": "Dny do vypršení",
+ "save_changes": "Uložit změny",
+ "current_user": "Úprava profilu pro:",
+ "your_email": "Váš e-mail:",
+ "first_name": "Jméno",
+ "last_name": "Příjmení",
+ "email": "E-mail",
+ "save_profile": "Uložit změny",
+ "default_view": "Výchozí zobrazení",
+ "default_view_desc": "Vyberte si preferované zobrazení pro záruky",
+ "grid_view": "Mřížka",
+ "list_view": "Seznam",
+ "table_view": "Tabulka",
+ "currency_symbol": "Symbol měny",
+ "currency_symbol_desc": "Vyberte symbol pro zobrazení cen",
+ "currency_position": "Pozice měny",
+ "currency_position_desc": "Vyberte, zda se symbol měny zobrazí vlevo nebo vpravo od čísel",
+ "expiring_soon_days_desc": "Počet dní před vypršením pro zobrazení varování",
+ "date_format_desc": "Vyberte, jak se budou zobrazovat data",
+ "save_preferences": "Uložit předvolby",
+ "notification_settings": "Nastavení oznámení",
+ "notification_channel": "Kanál oznámení",
+ "notification_channel_desc": "Vyberte, jak chcete dostávat oznámení",
+ "notification_disabled": "Vypnuto",
+ "notification_email": "E-mail",
+ "notification_apprise": "Apprise",
+ "notification_both": "Obojí",
+ "email_settings": "Nastavení e-mailu",
+ "notification_frequency": "Frekvence oznámení",
+ "notification_frequency_desc": "Jak často dostávat e-mailová oznámení",
+ "daily": "Denně",
+ "weekly": "Týdně",
+ "monthly": "Měsíčně",
+ "notification_time": "Čas oznámení",
+ "timezone_desc": "Vaše místní časové pásmo pro oznámení",
+ "apprise_settings": "Nastavení Apprise",
+ "apprise_frequency": "Frekvence oznámení Apprise",
+ "apprise_frequency_desc": "Jak často dostávat oznámení Apprise",
+ "apprise_time": "Čas oznámení Apprise",
+ "apprise_timezone": "Časové pásmo Apprise",
+ "apprise_timezone_desc": "Vaše místní časové pásmo pro oznámení Apprise",
+ "save_notification_settings": "Uložit nastavení oznámení",
+ "security": "Zabezpečení",
+ "change_password": "Změnit heslo",
+ "change_password_desc": "Aktualizujte heslo svého účtu",
+ "change": "Změnit",
+ "current_password": "Současné heslo",
+ "new_password": "Nové heslo",
+ "confirm_password": "Potvrdit nové heslo",
+ "update_password": "Aktualizovat heslo",
+ "cancel": "Zrušit",
+ "danger_zone": "Nebezpečná zóna",
+ "delete_account": "Smazat účet",
+ "delete_account_desc": "Trvale smazat váš účet a všechna data",
+ "admin_settings": "Nastavení administrátora",
+ "admin_actions": "Akce administrátora",
+ "refresh_data": "Aktualizovat data",
+ "check_admin_status": "Zkontrolovat stav administrátora",
+ "show_users_list": "Zobrazit seznam uživatelů",
+ "test_api": "Testovat API",
+ "send_notifications": "Odeslat oznámení o záruce",
+ "check_scheduler": "Zkontrolovat stav plánovače",
+ "site_settings": "Nastavení webu",
+ "registration_enabled": "Registrace povolena",
+ "registration_enabled_desc": "Povolit novým uživatelům registraci",
+ "email_base_url": "Základní URL e-mailu",
+ "global_view_enabled": "Globální zobrazení povoleno",
+ "global_view_admin_only": "Globální zobrazení pouze pro administrátory",
+ "save_site_settings": "Uložit nastavení webu",
+ "oidc_configuration": "Konfigurace OIDC SSO",
+ "enable_oidc": "Povolit OIDC SSO",
+ "oidc_provider_name": "Název poskytovatele OIDC",
+ "client_id": "ID klienta",
+ "client_secret": "Tajný klíč klienta",
+ "issuer_url": "URL vydavatele",
+ "scope": "Rozsah",
+ "save_oidc_settings": "Uložit nastavení OIDC",
+ "oidc_sso_desc": "Povolit uživatelům přihlášení přes poskytovatele OIDC.",
+ "oidc_only_mode": "Režim přihlášení pouze přes OIDC",
+ "oidc_only_mode_desc": "Skrýt tradiční formulář pro přihlášení pomocí uživatelského jména/hesla a povolit pouze přihlášení přes OIDC. <strong>Varování:</strong> Před povolením této možnosti se ujistěte, že je OIDC správně nakonfigurován.",
+ "oidc_provider_name_desc": "Interní název pro klienta OIDC (např. 'oidc').",
+ "client_secret_desc": "Citlivá hodnota. Uloženo v databázi. Pro projevení změn je nutný restart aplikace.",
+ "issuer_url_desc": "Základní URL vašeho poskytovatele OIDC.",
+ "scope_desc": "Rozsahy OIDC oddělené mezerami.",
+ "oidc_restart_message": "Pro plné projevení nastavení OIDC je nutný restart aplikace.",
+ "api_token": "API token",
+ "view_documents": "Zobrazit dokumenty ve Warrackeru",
+ "connection_testing": "Testování připojení",
+ "apprise_notifications": "Oznámení Apprise",
+ "enable_apprise": "Povolit oznámení Apprise",
+ "loading": "Načítání...",
+ "time_of_day_notification": "Čas dne pro příjem oznámení (ve 24hodinovém formátu)",
+ "paperless_ngx_settings": "Nastavení Paperless-ngx",
+ "paperless_ngx_about_title": "O integraci Paperless-ngx:",
+ "paperless_ngx_about_desc": "Tato volitelná funkce vám umožňuje ukládat záruční dokumenty do vaší vlastní instance Paperless-ngx namísto lokálního úložiště. Po povolení si uživatelé mohou vybrat, kam chtějí každý dokument uložit: lokálně nebo do Paperless-ngx.",
+ "paperless_ngx_desc": "Nakonfigurujte integraci se systémem pro správu dokumentů Paperless-ngx",
+ "enable_paperless": "Povolit integraci Paperless-ngx",
+ "paperless_url": "URL Paperless-ngx",
+ "paperless_url_desc": "Základní URL vaší instance Paperless-ngx",
+ "paperless_token": "API token",
+ "paperless_token_desc": "Váš API autentizační token Paperless-ngx",
+ "paperless_token_desc_generate": "Vygenerujte API token z vaší instance Paperless-ngx (Nastavení → API tokeny).",
+ "paperless_view_in_app": "Zobrazit dokumenty v aplikaci",
+ "paperless_view_in_app_desc": "Otevírat dokumenty v aplikaci namísto nové karty",
+ "debug_config": "Konfigurace ladění",
+ "test_upload": "Testovat nahrávání",
+ "save_paperless_settings": "Uložit nastavení Paperless-ngx",
+ "apprise_desc": "Nakonfigurujte Apprise pro pokročilé doručování oznámení do více služeb",
+ "apprise_desc_system_wide": "Povolit nebo zakázat oznámení Apprise v celém systému",
+ "apprise_not_available_title": "Apprise není k dispozici:",
+ "apprise_not_available_desc": "Knihovna oznámení Apprise není nainstalována nebo není k dispozici. Funkce oznámení jsou zakázány.",
+ "apprise_url": "URL Apprise",
+ "apprise_url_desc": "URL vaší služby oznámení Apprise",
+ "apprise_mode": "Režim oznámení",
+ "apprise_mode_desc": "Vyberte, kdy se mají odesílat oznámení Apprise",
+ "apprise_mode_global": "Globální shrnutí",
+ "apprise_mode_individual": "Na uživatele",
+ "test_paperless": "Testovat připojení Paperless",
+ "test_apprise": "Testovat připojení Apprise",
+ "apprise_warranty_scope": "Rozsah záruky",
+ "apprise_warranty_scope_desc": "Vyberte, které záruky zahrnout do oznámení",
+ "all_warranties": "Všechny záruky",
+ "personal_warranties": "Pouze osobní záruky",
+ "all_users_warranties": "Záruky všech uživatelů",
+ "admin_warranties_only": "Pouze záruky administrátora",
+ "apprise_notification_days": "Dny oznámení",
+ "apprise_notification_days_desc": "Dny před vypršením pro odeslání oznámení (oddělené čárkou, např. \"7,30\" pro 7 a 30 dní předem)",
+ "apprise_check_frequency": "Frekvence kontroly",
+ "apprise_check_frequency_desc": "Jak často systém kontroluje vypršení záruk (globální nastavení)",
+ "apprise_title_prefix": "Předpona názvu zprávy",
+ "apprise_title_prefix_desc": "Předpona přidaná k názvům oznámení (např. \"[Warracker]\" má za následek \"[Warracker] Záruky brzy vyprší\")",
+ "apprise_test_url": "Testovací URL (volitelné)",
+ "apprise_test_url_desc": "Volitelné: URL pro odesílání pouze testovacích oznámení (nebude uloženo do hlavní konfigurace)",
+ "save_apprise_settings": "Uložit nastavení Apprise",
+ "validate_urls": "Ověřit URL",
+ "send_expiration_notifications_now": "Odeslat oznámení o vypršení nyní",
+ "apprise_current_status": "Aktuální stav",
+ "apprise_urls_configured": "Nakonfigurované URL:",
+ "apprise_supported_services": "Podporované služby",
+ "apprise_supported_services_desc": "Apprise podporuje více než 80 oznamovacích služeb, včetně: Discord, Slack, Telegram, Email (Gmail, Outlook), Webhooks, Microsoft Teams, Matrix, Pushover, Ntfy, Gotify a mnoho dalších.",
+ "view_full_list_of_supported_services": "Zobrazit úplný seznam podporovaných služeb",
+ "ownership_management": "Správa vlastnictví",
+ "transfer_ownership": "Převést vlastnictví",
+ "warning_title": "Varování:",
+ "transfer_ownership_warning": "Převést vlastnictví aplikace na jiného administrátora. Tato akce je nevratná.",
+ "transfer_ownership_desc": "Jakmile je vlastnictví převedeno, stanete se běžným administrátorem a nový vlastník bude mít konečnou kontrolu nad aplikací.",
+ "select_new_owner": "Vyberte nového vlastníka (musí být administrátor)",
+ "select_admin_user": "Vyberte administrátora...",
+ "transfer_ownership_button": "Převést vlastnictví",
+ "transfer_ownership_irreversible": "Tuto akci nelze vrátit.",
+ "transfer_ownership_confirmation": "Chystáte se převést vlastnictví aplikace na",
+ "after_this_transfer": "Po tomto převodu:",
+ "transfer_ownership_consequence_1": "Stanete se běžným administrátorem",
+ "transfer_ownership_consequence_2": "Nový vlastník bude mít konečnou kontrolu nad aplikací",
+ "transfer_ownership_consequence_3": "Pouze nový vlastník může znovu převést vlastnictví",
+ "transfer_ownership_type_to_confirm": "Pro potvrzení zadejte \"TRANSFER\" do pole níže:"
+ },
+ "actions": {
+ "save": "Uložit",
+ "cancel": "Zrušit",
+ "delete": "Smazat",
+ "edit": "Upravit",
+ "export": "Exportovat",
+ "import": "Importovat",
+ "refresh": "Aktualizovat",
+ "search": "Hledat",
+ "clear": "Vymazat",
+ "upload": "Nahrát",
+ "download": "Stáhnout",
+ "manage_tags": "Spravovat tagy",
+ "close": "Zavřít",
+ "save_changes": "Uložit změny"
+ },
+ "filters": {
+ "all_status": "Všechny stavy",
+ "all_tags": "Všechny tagy",
+ "all_vendors": "Všichni prodejci",
+ "all_types": "Všechny typy",
+ "sort_by": "Seřadit podle",
+ "sort_expiration": "Datum vypršení",
+ "sort_purchase": "Datum nákupu",
+ "sort_age": "Stáří",
+ "sort_name": "Název produktu",
+ "sort_vendor": "Prodejce",
+ "sort_warranty_type": "Typ záruky",
+ "status": "Stav",
+ "tags": "Tagy",
+ "vendor": "Prodejce",
+ "warranty_type": "Typ záruky",
+ "view": "Zobrazení",
+ "scope": "Rozsah"
+ },
+ "messages": {
+ "success": "Úspěch",
+ "error": "Chyba",
+ "warning": "Varování",
+ "loading": "Načítání...",
+ "saved": "Změny úspěšně uloženy",
+ "deleted": "Položka úspěšně smazána",
+ "confirm_delete": "Jste si jisti, že chcete tuto položku smazat?",
+ "no_results": "Nebyly nalezeny žádné výsledky",
+ "file_too_large": "Soubor je příliš velký",
+ "invalid_file_type": "Neplatný typ souboru",
+ "fill_first_last_name": "Vyplňte prosím jméno a příjmení",
+ "email_cannot_be_empty": "E-mailová adresa nemůže být prázdná.",
+ "enter_valid_email": "Zadejte prosím platnou e-mailovou adresu.",
+ "profile_updated_successfully": "Profil úspěšně aktualizován",
+ "preferences_saved_successfully": "Předvolby úspěšně uloženy.",
+ "fill_password_fields": "Vyplňte prosím všechna pole hesla",
+ "passwords_do_not_match": "Nová hesla se neshodují",
+ "password_min_length": "Heslo musí mít alespoň 8 znaků",
+ "type_delete_to_confirm": "Pro potvrzení zadejte DELETE",
+ "account_deleted_successfully": "Účet úspěšně smazán",
+ "account_cannot_delete_offline": "Účet nelze smazat v offline režimu",
+ "failed_delete_account": "Nepodařilo se smazat účet. Zkuste to prosím znovu.",
+ "user_updated_successfully": "Uživatel úspěšně aktualizován",
+ "user_deleted_successfully": "Uživatel úspěšně smazán",
+ "user_id_missing": "Chybí ID uživatele",
+ "failed_load_users": "Nepodařilo se načíst uživatele",
+ "error_loading_users": "Chyba při načítání uživatelů",
+ "select_user_transfer_ownership": "Vyberte prosím uživatele, na kterého chcete převést vlastnictví",
+ "ownership_transferred_successfully": "Vlastnictví úspěšně převedeno! Obnovuji stránku...",
+ "failed_load_site_settings": "Nepodařilo se načíst nastavení webu. Zkuste to prosím znovu.",
+ "invalid_email_base_url": "Neplatný formát základní URL e-mailu. Musí začínat http:// nebo https://",
+ "no_site_settings_to_save": "Žádná nastavení webu k uložení.",
+ "site_settings_saved_successfully": "Nastavení webu úspěšně uložena",
+ "failed_save_site_settings": "Nepodařilo se uložit nastavení webu",
+ "oidc_settings_saved_successfully": "Nastavení OIDC úspěšně uložena.",
+ "failed_save_oidc_settings": "Nepodařilo se uložit nastavení OIDC.",
+ "api_endpoint_accessible": "API koncový bod je dostupný",
+ "api_endpoint_not_accessible": "API koncový bod není dostupný. Stav: ",
+ "only_admins_send_notifications": "Pouze administrátoři mohou odesílat oznámení o záruce",
+ "notifications_triggered_successfully": "Oznámení úspěšně spuštěna",
+ "notification_settings_saved_successfully": "Nastavení oznámení úspěšně uložena",
+ "apprise_settings_saved_successfully": "Nastavení Apprise úspěšně uložena",
+ "test_notification_sent_successfully": "Testovací oznámení úspěšně odesláno",
+ "no_urls_to_validate": "Žádné URL k ověření",
+ "paperless_settings_saved_successfully": "Nastavení Paperless-ngx úspěšně uložena!",
+ "enter_valid_paperless_url": "Zadejte prosím platnou URL (např. https://paperless.vasedomena.com)",
+ "enter_paperless_url_first": "Zadejte prosím nejprve URL Paperless-ngx",
+ "paperless_connection_test_successful": "Test připojení Paperless-ngx úspěšný!",
+ "paperless_connection_test_failed": "Test připojení Paperless-ngx selhal",
+ "enter_api_token_test_connection": "Zadejte prosím API token pro testování připojení",
+ "failed_load_user_data": "Nepodařilo se načíst uživatelská data. Zkuste to prosím znovu.",
+ "could_not_connect_user_data": "Nepodařilo se připojit k načtení uživatelských dat. Zobrazují se data z mezipaměti.",
+ "preferences_saved_locally_failed_sync": "Předvolby byly uloženy lokálně, ale nepodařilo se je synchronizovat se serverem: ",
+ "preferences_saved_locally": "Předvolby byly uloženy lokálně.",
+ "correct_errors_in_tab": "Před pokračováním opravte chyby v zvýrazněné záložce.",
+ "please_fill_out_this_field": "Prosím vyplňte toto pole.",
+ "warranty_added_successfully": "Záruka byla úspěšně přidána",
+ "tag_name_required": "Název tagu je vyžadován",
+ "tag_creation_function_not_found": "Funkce pro vytvoření tagu nebyla nalezena",
+ "tag_created_successfully": "Tag byl úspěšně vytvořen",
+ "tag_updated_successfully": "Tag byl úspěšně aktualizován",
+ "tag_deleted_successfully": "Tag byl úspěšně smazán",
+ "failed_to_create_tag": "Chyba při vytváření tagu",
+ "failed_to_update_tag": "Chyba při aktualizaci tagu",
+ "failed_to_delete_tag": "Chyba při mazání tagu"
+ },
+ "languages": {
+ "en": "Angličtina",
+ "fr": "Francouzština",
+ "es": "Španělština",
+ "de": "Němčina",
+ "it": "Italština",
+ "cs": "Čeština",
+ "nl": "Nizozemština",
+ "hi": "Hindština",
+ "fa": "Perština",
+ "ar": "Arabština",
+ "ru": "Ruština",
+ "uk": "Ukrajinština",
+ "zh_CN": "Čínština (zjednodušená)",
+ "zh_HK": "Čínština (tradiční)",
+ "ja": "Japonština",
+ "pt": "Portugalština",
+ "ko": "Korejština"
+ },
+ "status": {
+ "title": "Stav systému",
+ "dashboard_title": "Přehled stavu záruk",
+ "global_dashboard_title": "Globální přehled stavu záruk",
+ "overview": "Přehled",
+ "statistics": "Statistiky",
+ "total_warranties": "Celkem záruk",
+ "active_warranties": "Aktivní záruky",
+ "expiring_soon": "Brzy vyprší",
+ "expired_warranties": "Vypršelé záruky",
+ "warranty_distribution": "Rozložení záruk",
+ "expiration_timeline": "Časová osa vypršení",
+ "recent_activity": "Nedávná aktivita",
+ "recent_expirations": "Nedávno vypršelé nebo brzy vyprší",
+ "recent_expirations_empty": "Žádné nedávno vypršelé nebo brzy vyprší záruky.",
+ "system_health": "Stav systému",
+ "database_status": "Stav databáze",
+ "connected": "Připojeno",
+ "version": "Verze",
+ "uptime": "Doba provozu"
+ },
+ "about": {
+ "title": "O aplikaci Warracker",
+ "description": "Komplexní systém pro správu záruk navržený tak, aby vám pomohl sledovat, organizovat a spravovat všechny vaše záruky na produkty na jedné bezpečné a uživatelsky přívětivé platformě.",
+ "version": "Verze",
+ "update_status": "Stav aktualizace",
+ "checking_updates": "Kontrola aktualizací...",
+ "view_release_notes": "Zobrazit poznámky k vydání",
+ "project_info": "Informace o projektu",
+ "project_description": "Warracker je open-source systém pro správu záruk postavený na moderních webových technologiích. Poskytuje bezpečný a intuitivní způsob správy záruk na produkty, sledování dat vypršení a organizaci důležitých dokumentů.",
+ "github_repository": "Repozitář GitHub",
+ "releases": "Vydání",
+ "community_support": "Komunita a podpora",
+ "community_description": "Připojte se k naší komunitě pro podporu, diskuze a aktualizace. Hlášení chyb, žádosti o funkce nebo pomoc od ostatních uživatelů a přispěvatelů.",
+ "discord_community": "Komunita Discord",
+ "report_issues": "Nahlásit problémy",
+ "developer_info": "Informace o vývojáři",
+ "developer_description": "Warracker je vyvíjen a udržován společností Sassanix. Projekt je open-source a vítá příspěvky od komunity.",
+ "sassanix": "Sassanix",
+ "agpl_license": "Licence AGPL-3.0",
+ "support_project": "Podpořte projekt",
+ "support_description": "Pokud vám Warracker přijde užitečný, zvažte podporu jeho vývoje!",
+ "new_version_available": "Je k dispozici nová verze {{version}}!",
+ "latest_version": "Používáte nejnovější verzi",
+ "update_check_failed": "Nepodařilo se zkontrolovat aktualizace",
+ "features": "Funkce",
+ "feature_track": "Sledování záruk na produkty",
+ "feature_notifications": "Dostávat oznámení o vypršení",
+ "feature_documents": "Ukládat záruční dokumenty",
+ "feature_reports": "Generovat zprávy o zárukách",
+ "feature_tags": "Organizovat pomocí tagů",
+ "feature_export": "Exportovat data o zárukách",
+ "support": "Podpora",
+ "documentation": "Dokumentace",
+ "github": "GitHub",
+ "license": "Licence",
+ "copyright": "Autorská práva",
+ "developed_by": "Vyvinuto"
+ }
+}
\ No newline at end of file
diff --git a/locales/de/translation.json b/locales/de/translation.json
new file mode 100644
index 0000000..a41870a
--- /dev/null
+++ b/locales/de/translation.json
@@ -0,0 +1,560 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "Garantie-Tracker",
+ "nav": {
+ "home": "Startseite",
+ "status": "Status",
+ "settings": "Einstellungen",
+ "about": "Über"
+ },
+ "auth": {
+ "login": "Anmelden",
+ "logout": "Abmelden",
+ "register": "Registrieren",
+ "username": "Benutzername",
+ "password": "Passwort",
+ "email": "E-Mail",
+ "first_name": "Vorname",
+ "last_name": "Nachname",
+ "forgot_password": "Passwort vergessen?",
+ "reset_password": "Passwort zurücksetzen",
+ "confirm_password": "Passwort bestätigen",
+ "create_account_title": "Konto erstellen",
+ "first_name_optional": "Vorname (optional)",
+ "last_name_optional": "Nachname (optional)",
+ "username_hint": "Der Benutzername muss eindeutig sein und wird für die Anmeldung verwendet.",
+ "email_address": "E-Mail-Adresse",
+ "toggle_password": "Passwort anzeigen/ausblenden",
+ "password_hint_simple": "Das Passwort muss mindestens 8 Zeichen lang sein und Großbuchstaben, Kleinbuchstaben und Zahlen enthalten.",
+ "password_requirements": "Passwortanforderungen:",
+ "req_length": "Mindestens 8 Zeichen",
+ "req_uppercase": "Mindestens 1 Großbuchstabe",
+ "req_lowercase": "Mindestens 1 Kleinbuchstabe",
+ "req_number": "Mindestens 1 Zahl",
+ "req_special": "Mindestens 1 Sonderzeichen",
+ "create_account": "Konto erstellen",
+ "already_have_account": "Haben Sie bereits ein Konto?",
+ "reset_password_title": "Warracker - Passwort zurücksetzen",
+ "reset_your_password": "Passwort zurücksetzen",
+ "reset_password_info": "Geben Sie unten Ihre E-Mail-Adresse ein und wir senden Ihnen einen Link zum Zurücksetzen Ihres Passworts.",
+ "send_reset_link": "Link zum Zurücksetzen senden",
+ "back_to_login": "Zurück zur Anmeldung",
+ "set_new_password_title": "Warracker - Neues Passwort festlegen",
+ "set_new_password": "Neues Passwort festlegen",
+ "new_password": "Neues Passwort",
+ "confirm_new_password": "Neues Passwort bestätigen",
+ "invalid_or_expired_link": "Ungültiger oder abgelaufener Link",
+ "invalid_link_info": "Der von Ihnen angeklickte Link zum Zurücksetzen des Passworts ist ungültig oder abgelaufen.",
+ "request_new_reset_link": "Neuen Link zum Zurücksetzen anfordern"
+ },
+ "warranties": {
+ "title": "Ihre Garantien",
+ "title_global": "Garantien aller Benutzer",
+ "add_new": "Neue Garantie hinzufügen",
+ "edit": "Garantie bearbeiten",
+ "delete": "Garantie löschen",
+ "product_name": "Produktname",
+ "purchase_date": "Kaufdatum",
+ "warranty_duration": "Garantiedauer",
+ "years": "Jahre",
+ "months": "Monate",
+ "days": "Tage",
+ "vendor": "Anbieter",
+ "serial_numbers": "Seriennummern",
+ "purchase_price": "Kaufpreis",
+ "notes": "Notizen",
+ "tags": "Tags",
+ "status": "Status",
+ "expiration_date": "Ablaufdatum",
+ "active": "Aktiv",
+ "expired": "Abgelaufen",
+ "expiring_soon": "Läuft bald ab",
+ "lifetime": "Lebenslänglich",
+ "no_warranties": "Noch keine Garantien vorhanden. Fügen Sie Ihre erste Garantie hinzu, um zu beginnen.",
+ "search_placeholder": "Suche nach Name, Anbieter, Notizen, Tag oder Seriennummer...",
+ "warranty_type": "Garantietyp",
+ "other_document": "Anderes Dokument",
+ "product": "Produkt",
+ "expiration": "Ablauf",
+ "actions": "Aktionen",
+ "no_warranties_title": "Noch keine Garantien",
+ "no_warranties_desc": "Fügen Sie Ihre erste Garantie hinzu, um zu beginnen",
+ "add_warranty": "Garantie hinzufügen",
+ "warranty_entry_method": "Garantie-Eingabemethode",
+ "warranty_duration_option": "Garantiedauer",
+ "exact_expiration_option": "Genaues Ablaufdatum",
+ "warranty_period": "Garantiezeitraum",
+ "expiration_date_label": "Ablaufdatum",
+ "currency": "Währung",
+ "add_tags": "Tags hinzufügen",
+ "add_tags_desc": "Tags helfen Ihnen, Ihre Garantien zu organisieren und zu filtern",
+ "save_changes": "Änderungen speichern",
+ "confirm_delete": "Löschen bestätigen",
+ "manage_tags": "Tags verwalten",
+ "add_tag": "Tag hinzufügen",
+ "unknown_status": "Unbekannter Status",
+ "expiring_soon_days": "Läuft bald ab ({{days}} {{dayText}})",
+ "days_remaining": "{{days}} {{dayText}} verbleibend",
+ "day_one": "Tag",
+ "day_other": "Tage",
+ "month_one": "Monat",
+ "month_other": "Monate",
+ "year_one": "Jahr",
+ "year_other": "Jahre",
+ "na": "N/A",
+ "age": "Alter",
+ "warranty": "Garantie",
+ "warranty_ends": "Garantie endet",
+ "price": "Preis",
+ "serial_number": "Seriennummer",
+ "type": "Typ",
+ "owner": "Besitzer",
+ "product_website": "Produkt-Website",
+ "documents": "Dokumente",
+ "summary": "Zusammenfassung",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "Jahre",
+ "months_placeholder": "Monate",
+ "days_placeholder": "Tage",
+ "add_any_notes_placeholder": "Fügen Sie Notizen zu dieser Garantie hinzu...",
+ "product_url_optional": "Produkt-URL (optional)",
+ "enter_serial_number": "Seriennummer eingeben",
+ "vendor_optional": "Anbieter (optional)",
+ "vendor_placeholder": "z.B. Amazon, Best Buy, etc.",
+ "lifetime_warranty": "Lebenslange Garantie",
+ "warranty_type_optional": "Garantietyp (optional)",
+ "select_warranty_type": "Garantietyp auswählen...",
+ "standard": "Standard",
+ "extended": "Erweitert",
+ "manufacturer": "Hersteller",
+ "third_party": "Drittanbieter",
+ "store": "Geschäft",
+ "premium": "Premium",
+ "limited": "Begrenzt",
+ "full": "Voll",
+ "parts_only": "Nur Teile",
+ "labor_only": "Nur Arbeit",
+ "international": "International",
+ "accidental_damage": "Unfallschaden",
+ "other_custom": "Andere (benutzerdefiniert)",
+ "enter_custom_warranty_type": "Benutzerdefinierten Garantietyp eingeben",
+ "purchase_price_optional": "Kaufpreis (optional)",
+ "notes_optional": "Notizen (optional)",
+ "add_any_notes": "Fügen Sie Notizen zu dieser Garantie hinzu...",
+ "product_photo_optional": "Produktfoto (optional)",
+ "choose_photo": "Foto auswählen",
+ "invoice_receipt": "Rechnung/Beleg",
+ "store_locally": "Lokal speichern",
+ "store_in_paperless": "In Paperless-ngx speichern",
+ "choose_file": "Datei auswählen",
+ "browse_paperless": "Paperless-ngx-Dokumente durchsuchen",
+ "product_manual_optional": "Produkthandbuch (optional)",
+ "files_zip_rar_optional": "Dateien (ZIP/RAR, optional)",
+ "search_or_add_new_tag": "Suchen oder neuen Tag hinzufügen...",
+ "product_information": "Produktinformationen",
+ "product_url": "Produkt-URL",
+ "warranty_details": "Garantiedetails",
+ "product_photo": "Produktfoto",
+ "product_manual": "Produkthandbuch",
+ "files": "Dateien",
+ "selected_tags": "Ausgewählte Tags",
+ "previous_tab": "Zurück",
+ "next_tab": "Weiter",
+ "delete_photo": "Foto löschen",
+ "delete_invoice": "Rechnung löschen",
+ "delete_manual": "Handbuch löschen",
+ "delete_files": "Dateien löschen",
+ "current_photo": "Aktuelles Foto:",
+ "current_invoice": "Aktuelle Rechnung:",
+ "current_manual": "Aktuelles Handbuch:",
+ "current_document": "Aktuelles Dokument:",
+ "upload_new_photo_replace": "(Neues Foto zum Ersetzen hochladen)",
+ "no_photo_uploaded": "Kein Foto hochgeladen",
+ "no_invoice_uploaded": "Keine Rechnung hochgeladen",
+ "no_manual_uploaded": "Kein Handbuch hochgeladen",
+ "no_document_uploaded": "Kein anderes Dokument hochgeladen",
+ "photo_will_be_deleted": "Foto wird beim Speichern gelöscht",
+ "invoice_will_be_deleted": "Rechnung wird beim Speichern gelöscht",
+ "manual_will_be_deleted": "Handbuch wird beim Speichern gelöscht",
+ "document_will_be_deleted": "Anderes Dokument wird beim Speichern gelöscht",
+ "confirm_delete_message": "Sind Sie sicher, dass Sie diese Garantie löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.",
+ "new_tag_name": "Neuer Tag-Name",
+ "existing_tags": "Bestehende Tags",
+ "edit_warranty": "Garantie bearbeiten",
+ "warranty_type_standard": "Standard",
+ "warranty_type_extended": "Erweitert",
+ "warranty_type_manufacturer": "Hersteller",
+ "warranty_type_third_party": "Drittanbieter",
+ "warranty_type_store": "Geschäft",
+ "warranty_type_premium": "Premium",
+ "warranty_type_limited": "Begrenzt",
+ "warranty_type_full": "Voll",
+ "warranty_type_parts_only": "Nur Teile",
+ "warranty_type_labor_only": "Nur Arbeit",
+ "warranty_type_international": "International",
+ "warranty_type_accidental_damage": "Unfallschaden",
+ "warranty_type_other": "Andere (benutzerdefiniert)",
+ "warranty_type_custom_placeholder": "Benutzerdefinierten Garantietyp eingeben",
+ "notes_placeholder": "Zusätzliche Notizen zu dieser Garantie...",
+ "tags_help_text": "Tags helfen Ihnen, Ihre Garantien zu organisieren und zu filtern",
+ "search_add_tag_placeholder": "Suchen oder neuen Tag hinzufügen...",
+ "upload_new_file_replace": "Neue Datei zum Ersetzen hochladen",
+ "current_other_document": "Aktuelles anderes Dokument",
+ "no_other_document_uploaded": "Kein anderes Dokument hochgeladen",
+ "other_document_will_be_deleted": "Anderes Dokument wird beim Speichern gelöscht",
+ "files_optional": "Dateien (ZIP/RAR, optional)",
+ "invoice_receipt_short": "Rechnung",
+ "product_manual_short": "Handbuch",
+ "files_short": "Dateien",
+ "enter_serial_number": "Seriennummer eingeben",
+ "add_serial_number": "Weitere Seriennummer hinzufügen"
+ },
+ "settings": {
+ "title": "Einstellungen",
+ "account_settings": "Kontoeinstellungen",
+ "preferences": "Präferenzen",
+ "language": "Sprache",
+ "select_language": "Sprache auswählen",
+ "dark_mode": "Dunkelmodus",
+ "dark_mode_desc": "Zwischen hellem und dunklem Thema wechseln",
+ "currency": "Währung",
+ "timezone": "Zeitzone",
+ "date_format": "Datumsformat",
+ "expiring_soon_days": "Tage bis zum Ablauf",
+ "save_changes": "Änderungen speichern",
+ "current_user": "Profil bearbeiten für:",
+ "your_email": "Ihre E-Mail:",
+ "first_name": "Vorname",
+ "last_name": "Nachname",
+ "email": "E-Mail",
+ "save_profile": "Änderungen speichern",
+ "default_view": "Standardansicht",
+ "default_view_desc": "Wählen Sie Ihre bevorzugte Ansicht für Garantien",
+ "grid_view": "Gitteransicht",
+ "list_view": "Listenansicht",
+ "table_view": "Tabellenansicht",
+ "currency_symbol": "Währungssymbol",
+ "currency_symbol_desc": "Wählen Sie das Symbol zur Anzeige von Preisen",
+ "currency_position": "Währungsposition",
+ "currency_position_desc": "Wählen Sie, ob das Währungssymbol links oder rechts von den Zahlen angezeigt wird",
+ "expiring_soon_days_desc": "Anzahl der Tage vor Ablauf, um Warnungen anzuzeigen",
+ "date_format_desc": "Wählen Sie, wie Daten angezeigt werden",
+ "save_preferences": "Präferenzen speichern",
+ "notification_settings": "Benachrichtigungseinstellungen",
+ "notification_channel": "Benachrichtigungskanal",
+ "notification_channel_desc": "Wählen Sie, wie Sie Benachrichtigungen erhalten möchten",
+ "notification_disabled": "Deaktiviert",
+ "notification_email": "E-Mail",
+ "notification_apprise": "Apprise",
+ "notification_both": "Beide",
+ "email_settings": "E-Mail-Einstellungen",
+ "notification_frequency": "Benachrichtigungshäufigkeit",
+ "notification_frequency_desc": "Wie oft E-Mail-Benachrichtigungen erhalten werden sollen",
+ "daily": "Täglich",
+ "weekly": "Wöchentlich",
+ "monthly": "Monatlich",
+ "notification_time": "Benachrichtigungszeit",
+ "timezone_desc": "Ihre lokale Zeitzone für Benachrichtigungen",
+ "apprise_settings": "Apprise-Einstellungen",
+ "apprise_frequency": "Apprise-Benachrichtigungshäufigkeit",
+ "apprise_frequency_desc": "Wie oft Apprise-Benachrichtigungen erhalten werden sollen",
+ "apprise_time": "Apprise-Benachrichtigungszeit",
+ "apprise_timezone": "Apprise-Zeitzone",
+ "apprise_timezone_desc": "Ihre lokale Zeitzone für Apprise-Benachrichtigungen",
+ "save_notification_settings": "Benachrichtigungseinstellungen speichern",
+ "security": "Sicherheit",
+ "change_password": "Passwort ändern",
+ "change_password_desc": "Aktualisieren Sie Ihr Kontopasswort",
+ "change": "Ändern",
+ "current_password": "Aktuelles Passwort",
+ "new_password": "Neues Passwort",
+ "confirm_password": "Neues Passwort bestätigen",
+ "update_password": "Passwort aktualisieren",
+ "cancel": "Abbrechen",
+ "danger_zone": "Gefahrenzone",
+ "delete_account": "Konto löschen",
+ "delete_account_desc": "Löschen Sie Ihr Konto und alle Daten dauerhaft",
+ "admin_settings": "Admin-Einstellungen",
+ "admin_actions": "Admin-Aktionen",
+ "refresh_data": "Daten aktualisieren",
+ "check_admin_status": "Admin-Status prüfen",
+ "show_users_list": "Benutzerliste anzeigen",
+ "test_api": "API testen",
+ "send_notifications": "Garantiebenachrichtigungen senden",
+ "check_scheduler": "Scheduler-Status prüfen",
+ "site_settings": "Site-Einstellungen",
+ "registration_enabled": "Registrierung aktiviert",
+ "registration_enabled_desc": "Neuen Benutzern die Registrierung erlauben",
+ "email_base_url": "E-Mail-Basis-URL",
+ "global_view_enabled": "Globale Ansicht aktiviert",
+ "global_view_admin_only": "Globale Ansicht nur für Admins",
+ "save_site_settings": "Site-Einstellungen speichern",
+ "oidc_configuration": "OIDC-SSO-Konfiguration",
+ "enable_oidc": "OIDC-SSO aktivieren",
+ "oidc_provider_name": "OIDC-Anbietername",
+ "client_id": "Client-ID",
+ "client_secret": "Client-Geheimnis",
+ "issuer_url": "Aussteller-URL",
+ "scope": "Umfang",
+ "save_oidc_settings": "OIDC-Einstellungen speichern",
+ "oidc_sso_desc": "Benutzern die Anmeldung über einen OIDC-Anbieter ermöglichen.",
+ "oidc_only_mode": "Nur-OIDC-Anmeldemodus",
+ "oidc_only_mode_desc": "Traditionelles Anmeldeformular für Benutzername/Passwort ausblenden und nur OIDC-Anmeldung zulassen. <strong>Warnung:</strong> Stellen Sie sicher, dass OIDC ordnungsgemäß konfiguriert ist, bevor Sie diese Option aktivieren.",
+ "oidc_provider_name_desc": "Interner Name für den OIDC-Client (z. B. 'oidc').",
+ "client_secret_desc": "Sensibler Wert. In der Datenbank gespeichert. Ein Neustart der Anwendung ist erforderlich, damit die Änderungen wirksam werden.",
+ "issuer_url_desc": "Die Basis-URL Ihres OIDC-Anbieters.",
+ "scope_desc": "Durch Leerzeichen getrennte OIDC-Bereiche.",
+ "oidc_restart_message": "Ein Neustart der Anwendung ist erforderlich, damit die OIDC-Einstellungen vollständig wirksam werden.",
+ "api_token": "API-Token",
+ "view_documents": "Dokumente in Warracker anzeigen",
+ "connection_testing": "Verbindung testen",
+ "apprise_notifications": "Apprise-Benachrichtigungen",
+ "enable_apprise": "Apprise-Benachrichtigungen aktivieren",
+ "loading": "Wird geladen...",
+ "time_of_day_notification": "Tageszeit für den Empfang von Benachrichtigungen (im 24-Stunden-Format)",
+ "paperless_ngx_settings": "Paperless-ngx-Einstellungen",
+ "paperless_ngx_about_title": "Über die Paperless-ngx-Integration:",
+ "paperless_ngx_about_desc": "Diese optionale Funktion ermöglicht es Ihnen, Garantiedokumente in Ihrer selbst gehosteten Paperless-ngx-Instanz anstelle von lokal zu speichern. Wenn aktiviert, können Benutzer wählen, wo sie jedes Dokument speichern möchten: lokal oder in Paperless-ngx.",
+ "paperless_ngx_desc": "Integration mit dem Dokumentenmanagementsystem Paperless-ngx konfigurieren",
+ "enable_paperless": "Paperless-ngx-Integration aktivieren",
+ "paperless_url": "Paperless-ngx-URL",
+ "paperless_url_desc": "Basis-URL Ihrer Paperless-ngx-Instanz",
+ "paperless_token": "API-Token",
+ "paperless_token_desc": "Ihr Paperless-ngx-API-Authentifizierungstoken",
+ "paperless_token_desc_generate": "Generieren Sie ein API-Token aus Ihrer Paperless-ngx-Instanz (Einstellungen → API-Token).",
+ "paperless_view_in_app": "Dokumente in der App anzeigen",
+ "paperless_view_in_app_desc": "Dokumente in der App anstelle eines neuen Tabs öffnen",
+ "debug_config": "Debug-Konfiguration",
+ "test_upload": "Upload testen",
+ "save_paperless_settings": "Paperless-ngx-Einstellungen speichern",
+ "apprise_desc": "Konfigurieren Sie Apprise für die erweiterte Zustellung von Benachrichtigungen an mehrere Dienste",
+ "apprise_desc_system_wide": "Apprise-Benachrichtigungen systemweit aktivieren oder deaktivieren",
+ "apprise_not_available_title": "Apprise nicht verfügbar:",
+ "apprise_not_available_desc": "Die Apprise-Benachrichtigungsbibliothek ist nicht installiert oder verfügbar. Benachrichtigungsfunktionen sind deaktiviert.",
+ "apprise_url": "Apprise-URL",
+ "apprise_url_desc": "Ihre Apprise-Benachrichtigungsdienst-URL",
+ "apprise_mode": "Benachrichtigungsmodus",
+ "apprise_mode_desc": "Wählen Sie, wann Apprise-Benachrichtigungen gesendet werden sollen",
+ "apprise_mode_global": "Globale Zusammenfassung",
+ "apprise_mode_individual": "Pro Benutzer",
+ "test_paperless": "Paperless-Verbindung testen",
+ "test_apprise": "Apprise-Verbindung testen",
+ "apprise_warranty_scope": "Garantieumfang",
+ "apprise_warranty_scope_desc": "Wählen Sie, welche Garantien in Benachrichtigungen enthalten sein sollen",
+ "all_warranties": "Alle Garantien",
+ "personal_warranties": "Nur persönliche Garantien",
+ "all_users_warranties": "Garantien aller Benutzer",
+ "admin_warranties_only": "Nur Garantien des Administrators",
+ "apprise_notification_days": "Benachrichtigungstage",
+ "apprise_notification_days_desc": "Tage vor Ablauf, um Benachrichtigungen zu senden (durch Komma getrennt, z. B. \"7,30\" für 7 Tage und 30 Tage vorher)",
+ "apprise_check_frequency": "Prüffrequenz",
+ "apprise_check_frequency_desc": "Wie oft das System nach ablaufenden Garantien sucht (globale Einstellung)",
+ "apprise_title_prefix": "Nachrichtentitel-Präfix",
+ "apprise_title_prefix_desc": "Präfix, das den Benachrichtigungstiteln hinzugefügt wird (z. B. führt \"[Warracker]\" zu \"[Warracker] Garantien laufen bald ab\")",
+ "apprise_test_url": "Test-URL (optional)",
+ "apprise_test_url_desc": "Optional: URL nur zum Senden von Testbenachrichtigungen (wird nicht in der Hauptkonfiguration gespeichert)",
+ "save_apprise_settings": "Apprise-Einstellungen speichern",
+ "validate_urls": "URLs validieren",
+ "send_expiration_notifications_now": "Ablaufbenachrichtigungen jetzt senden",
+ "apprise_current_status": "Aktueller Status",
+ "apprise_urls_configured": "Konfigurierte URLs:",
+ "apprise_supported_services": "Unterstützte Dienste",
+ "apprise_supported_services_desc": "Apprise unterstützt über 80 Benachrichtigungsdienste, darunter: Discord, Slack, Telegram, E-Mail (Gmail, Outlook), Webhooks, Microsoft Teams, Matrix, Pushover, Ntfy, Gotify und viele mehr.",
+ "view_full_list_of_supported_services": "Vollständige Liste der unterstützten Dienste anzeigen",
+ "ownership_management": "Eigentumsverwaltung",
+ "transfer_ownership": "Eigentum übertragen",
+ "warning_title": "Warnung:",
+ "transfer_ownership_warning": "Anwendungseigentum auf einen anderen Admin-Benutzer übertragen. Diese Aktion ist unumkehrbar.",
+ "transfer_ownership_desc": "Sobald das Eigentum übertragen ist, werden Sie ein normaler Administrator und der neue Eigentümer hat die endgültige Kontrolle über die Anwendung.",
+ "select_new_owner": "Neuen Eigentümer auswählen (muss ein Administrator sein)",
+ "select_admin_user": "Admin-Benutzer auswählen...",
+ "transfer_ownership_button": "Eigentum übertragen",
+ "transfer_ownership_irreversible": "Diese Aktion kann nicht rückgängig gemacht werden.",
+ "transfer_ownership_confirmation": "Sie sind dabei, das Anwendungseigentum zu übertragen an",
+ "after_this_transfer": "Nach dieser Übertragung:",
+ "transfer_ownership_consequence_1": "Sie werden ein normaler Administrator",
+ "transfer_ownership_consequence_2": "Der neue Eigentümer hat die endgültige Kontrolle über die Anwendung",
+ "transfer_ownership_consequence_3": "Nur der neue Eigentümer kann das Eigentum erneut übertragen",
+ "transfer_ownership_type_to_confirm": "Zur Bestätigung geben Sie bitte \"TRANSFER\" in das Feld unten ein:"
+ },
+ "actions": {
+ "save": "Speichern",
+ "cancel": "Abbrechen",
+ "delete": "Löschen",
+ "edit": "Bearbeiten",
+ "export": "Exportieren",
+ "import": "Importieren",
+ "refresh": "Aktualisieren",
+ "search": "Suchen",
+ "clear": "Löschen",
+ "upload": "Hochladen",
+ "download": "Herunterladen",
+ "manage_tags": "Tags verwalten",
+ "close": "Schließen",
+ "save_changes": "Änderungen speichern"
+ },
+ "filters": {
+ "all_status": "Alle Status",
+ "all_tags": "Alle Tags",
+ "all_vendors": "Alle Anbieter",
+ "all_types": "Alle Typen",
+ "sort_by": "Sortieren nach",
+ "sort_expiration": "Ablaufdatum",
+ "sort_purchase": "Kaufdatum",
+ "sort_age": "Alter",
+ "sort_name": "Produktname",
+ "sort_vendor": "Anbieter",
+ "sort_warranty_type": "Garantietyp",
+ "status": "Status",
+ "tags": "Tags",
+ "vendor": "Anbieter",
+ "warranty_type": "Garantietyp",
+ "view": "Ansicht",
+ "scope": "Umfang"
+ },
+ "messages": {
+ "success": "Erfolg",
+ "error": "Fehler",
+ "warning": "Warnung",
+ "loading": "Wird geladen...",
+ "saved": "Änderungen erfolgreich gespeichert",
+ "deleted": "Element erfolgreich gelöscht",
+ "confirm_delete": "Sind Sie sicher, dass Sie dieses Element löschen möchten?",
+ "no_results": "Keine Ergebnisse gefunden",
+ "file_too_large": "Datei ist zu groß",
+ "invalid_file_type": "Ungültiger Dateityp",
+ "fill_first_last_name": "Bitte geben Sie Vor- und Nachnamen ein",
+ "email_cannot_be_empty": "E-Mail-Adresse darf nicht leer sein.",
+ "enter_valid_email": "Bitte geben Sie eine gültige E-Mail-Adresse ein.",
+ "profile_updated_successfully": "Profil erfolgreich aktualisiert",
+ "preferences_saved_successfully": "Präferenzen erfolgreich gespeichert.",
+ "fill_password_fields": "Bitte füllen Sie alle Passwortfelder aus",
+ "passwords_do_not_match": "Neue Passwörter stimmen nicht überein",
+ "password_min_length": "Das Passwort muss mindestens 8 Zeichen lang sein",
+ "type_delete_to_confirm": "Bitte geben Sie DELETE ein, um zu bestätigen",
+ "account_deleted_successfully": "Konto erfolgreich gelöscht",
+ "account_cannot_delete_offline": "Konto kann im Offline-Modus nicht gelöscht werden",
+ "failed_delete_account": "Konto konnte nicht gelöscht werden. Bitte versuchen Sie es erneut.",
+ "user_updated_successfully": "Benutzer erfolgreich aktualisiert",
+ "user_deleted_successfully": "Benutzer erfolgreich gelöscht",
+ "user_id_missing": "Benutzer-ID fehlt",
+ "failed_load_users": "Benutzer konnten nicht geladen werden",
+ "error_loading_users": "Fehler beim Laden der Benutzer",
+ "select_user_transfer_ownership": "Bitte wählen Sie einen Benutzer aus, an den das Eigentum übertragen werden soll",
+ "ownership_transferred_successfully": "Eigentum erfolgreich übertragen! Seite wird aktualisiert...",
+ "failed_load_site_settings": "Site-Einstellungen konnten nicht geladen werden. Bitte versuchen Sie es erneut.",
+ "invalid_email_base_url": "Ungültiges E-Mail-Basis-URL-Format. Es sollte mit http:// oder https:// beginnen",
+ "no_site_settings_to_save": "Keine Site-Einstellungen zum Speichern.",
+ "site_settings_saved_successfully": "Site-Einstellungen erfolgreich gespeichert",
+ "failed_save_site_settings": "Site-Einstellungen konnten nicht gespeichert werden",
+ "oidc_settings_saved_successfully": "OIDC-Einstellungen erfolgreich gespeichert.",
+ "failed_save_oidc_settings": "OIDC-Einstellungen konnten nicht gespeichert werden.",
+ "api_endpoint_accessible": "API-Endpunkt ist erreichbar",
+ "api_endpoint_not_accessible": "API-Endpunkt ist nicht erreichbar. Status: ",
+ "only_admins_send_notifications": "Nur Administratoren können Garantiebenachrichtigungen senden",
+ "notifications_triggered_successfully": "Benachrichtigungen erfolgreich ausgelöst",
+ "notification_settings_saved_successfully": "Benachrichtigungseinstellungen erfolgreich gespeichert",
+ "apprise_settings_saved_successfully": "Apprise-Einstellungen erfolgreich gespeichert",
+ "test_notification_sent_successfully": "Testbenachrichtigung erfolgreich gesendet",
+ "no_urls_to_validate": "Keine URLs zum Validieren",
+ "paperless_settings_saved_successfully": "Paperless-ngx-Einstellungen erfolgreich gespeichert!",
+ "enter_valid_paperless_url": "Bitte geben Sie eine gültige URL ein (z. B. https://paperless.ihredomain.com)",
+ "enter_paperless_url_first": "Bitte geben Sie zuerst eine Paperless-ngx-URL ein",
+ "paperless_connection_test_successful": "Paperless-ngx-Verbindungstest erfolgreich!",
+ "paperless_connection_test_failed": "Paperless-ngx-Verbindungstest fehlgeschlagen",
+ "enter_api_token_test_connection": "Bitte geben Sie ein API-Token ein, um die Verbindung zu testen",
+ "failed_load_user_data": "Benutzerdaten konnten nicht geladen werden. Bitte versuchen Sie es erneut.",
+ "could_not_connect_user_data": "Konnte keine Verbindung herstellen, um Benutzerdaten abzurufen. Angezeigte zwischengespeicherte Informationen.",
+ "preferences_saved_locally_failed_sync": "Präferenzen lokal gespeichert, aber Synchronisierung mit dem Server fehlgeschlagen: ",
+ "preferences_saved_locally": "Präferenzen lokal gespeichert.",
+ "correct_errors_in_tab": "Bitte korrigieren Sie die Fehler im hervorgehobenen Tab, bevor Sie fortfahren.",
+ "please_fill_out_this_field": "Bitte füllen Sie dieses Feld aus.",
+ "warranty_added_successfully": "Garantie erfolgreich hinzugefügt",
+ "tag_name_required": "Tag-Name ist erforderlich",
+ "tag_creation_function_not_found": "Tag-Erstellungsfunktion nicht gefunden",
+ "tag_created_successfully": "Tag erfolgreich erstellt",
+ "tag_updated_successfully": "Tag erfolgreich aktualisiert",
+ "tag_deleted_successfully": "Tag erfolgreich gelöscht",
+ "failed_to_create_tag": "Fehler beim Erstellen des Tags",
+ "failed_to_update_tag": "Fehler beim Aktualisieren des Tags",
+ "failed_to_delete_tag": "Fehler beim Löschen des Tags"
+ },
+ "languages": {
+ "en": "Englisch",
+ "fr": "Französisch",
+ "es": "Spanisch",
+ "de": "Deutsch",
+ "it": "Italienisch",
+ "cs": "Tschechisch",
+ "nl": "Niederländisch",
+ "hi": "Hindi",
+ "fa": "Persisch",
+ "ar": "Arabisch",
+ "ru": "Russisch",
+ "uk": "Ukrainisch",
+ "zh_CN": "Chinesisch (vereinfacht)",
+ "zh_HK": "Chinesisch (traditionell)",
+ "ja": "Japanisch",
+ "pt": "Portugiesisch",
+ "ko": "Koreanisch"
+ },
+ "status": {
+ "title": "Systemstatus",
+ "dashboard_title": "Garantie-Status-Dashboard",
+ "global_dashboard_title": "Globales Garantie-Status-Dashboard",
+ "overview": "Übersicht",
+ "statistics": "Statistiken",
+ "total_warranties": "Gesamtzahl der Garantien",
+ "active_warranties": "Aktive Garantien",
+ "expiring_soon": "Läuft bald ab",
+ "expired_warranties": "Abgelaufene Garantien",
+ "warranty_distribution": "Garantieverteilung",
+ "expiration_timeline": "Ablauf-Zeitleiste",
+ "recent_activity": "Letzte Aktivität",
+ "recent_expirations": "Kürzlich abgelaufen oder bald ablaufend",
+ "recent_expirations_empty": "Keine kürzlich abgelaufenen oder bald ablaufenden Garantien.",
+ "system_health": "Systemzustand",
+ "database_status": "Datenbankstatus",
+ "connected": "Verbunden",
+ "version": "Version",
+ "uptime": "Betriebszeit"
+ },
+ "about": {
+ "title": "Über Warracker",
+ "description": "Ein umfassendes Garantiemanagementsystem, das Ihnen hilft, alle Ihre Produktgarantien auf einer sicheren, benutzerfreundlichen Plattform zu verfolgen, zu organisieren und zu verwalten.",
+ "version": "Version",
+ "update_status": "Update-Status",
+ "checking_updates": "Auf Updates wird geprüft...",
+ "view_release_notes": "Versionshinweise anzeigen",
+ "project_info": "Projektinformationen",
+ "project_description": "Warracker ist ein Open-Source-Garantiemanagementsystem, das mit modernen Web-Technologien erstellt wurde. Es bietet eine sichere und intuitive Möglichkeit, Produktgarantien zu verwalten, Ablaufdaten zu verfolgen und wichtige Dokumente zu organisieren.",
+ "github_repository": "GitHub-Repository",
+ "releases": "Versionen",
+ "community_support": "Community & Support",
+ "community_description": "Treten Sie unserer Community bei, um Unterstützung, Diskussionen und Updates zu erhalten. Melden Sie Fehler, fordern Sie Funktionen an oder erhalten Sie Hilfe von anderen Benutzern und Mitwirkenden.",
+ "discord_community": "Discord-Community",
+ "report_issues": "Probleme melden",
+ "developer_info": "Entwicklerinformationen",
+ "developer_description": "Warracker wird von Sassanix entwickelt und gewartet. Das Projekt ist Open-Source und begrüßt Beiträge aus der Community.",
+ "sassanix": "Sassanix",
+ "agpl_license": "AGPL-3.0-Lizenz",
+ "support_project": "Das Projekt unterstützen",
+ "support_description": "Wenn Sie Warracker nützlich finden, sollten Sie die Entwicklung unterstützen!",
+ "new_version_available": "Neue Version {{version}} verfügbar!",
+ "latest_version": "Sie verwenden die neueste Version",
+ "update_check_failed": "Update-Prüfung fehlgeschlagen",
+ "features": "Funktionen",
+ "feature_track": "Produktgarantien verfolgen",
+ "feature_notifications": "Ablaufbenachrichtigungen erhalten",
+ "feature_documents": "Garantiedokumente speichern",
+ "feature_reports": "Garantieberichte erstellen",
+ "feature_tags": "Mit Tags organisieren",
+ "feature_export": "Garantiedaten exportieren",
+ "support": "Support",
+ "documentation": "Dokumentation",
+ "github": "GitHub-Repository",
+ "license": "Lizenz",
+ "copyright": "Copyright",
+ "developed_by": "Entwickelt von"
+ }
+}
\ No newline at end of file
diff --git a/locales/en/LC_MESSAGES/messages.mo b/locales/en/LC_MESSAGES/messages.mo
new file mode 100644
index 0000000..69add51
Binary files /dev/null and b/locales/en/LC_MESSAGES/messages.mo differ
diff --git a/locales/en/LC_MESSAGES/messages.po b/locales/en/LC_MESSAGES/messages.po
new file mode 100644
index 0000000..835ec3e
--- /dev/null
+++ b/locales/en/LC_MESSAGES/messages.po
@@ -0,0 +1,180 @@
+# English translations for Warracker
+# Copyright (C) 2024 Warracker
+# This file is distributed under the same license as the Warracker project.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: Warracker 1.0\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2025-06-29 12:36-0300\n"
+"PO-Revision-Date: 2024-01-01 12:00+0000\n"
+"Last-Translator: \n"
+"Language: en\n"
+"Language-Team: English\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=utf-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Generated-By: Babel 2.17.0\n"
+
+# Error messages
+#: backend/localization.py:177
+msgid "Validation error"
+msgstr "Validation error"
+
+#: backend/localization.py:178
+msgid "Authentication error"
+msgstr "Authentication error"
+
+#: backend/localization.py:179
+msgid "Authorization error"
+msgstr "Authorization error"
+
+#: backend/localization.py:180
+msgid "Resource not found"
+msgstr "Resource not found"
+
+#: backend/localization.py:181
+msgid "Internal server error"
+msgstr "Internal server error"
+
+#: backend/localization.py:182
+msgid "File is too large"
+msgstr "File is too large"
+
+#: backend/localization.py:183
+msgid "Invalid file type"
+msgstr "Invalid file type"
+
+#: backend/localization.py:186
+msgid "An error occurred"
+msgstr "An error occurred"
+
+# Authentication
+#~ msgid "Login"
+#~ msgstr "Login"
+
+#~ msgid "Logout"
+#~ msgstr "Logout"
+
+#~ msgid "Register"
+#~ msgstr "Register"
+
+#~ msgid "Username"
+#~ msgstr "Username"
+
+#~ msgid "Password"
+#~ msgstr "Password"
+
+#~ msgid "Email"
+#~ msgstr "Email"
+
+#~ msgid "First Name"
+#~ msgstr "First Name"
+
+#~ msgid "Last Name"
+#~ msgstr "Last Name"
+
+# Navigation
+#~ msgid "Home"
+#~ msgstr "Home"
+
+#~ msgid "Settings"
+#~ msgstr "Settings"
+
+#~ msgid "Status"
+#~ msgstr "Status"
+
+#~ msgid "About"
+#~ msgstr "About"
+
+# Common actions
+#~ msgid "Save"
+#~ msgstr "Save"
+
+#~ msgid "Cancel"
+#~ msgstr "Cancel"
+
+#~ msgid "Delete"
+#~ msgstr "Delete"
+
+#~ msgid "Edit"
+#~ msgstr "Edit"
+
+#~ msgid "Search"
+#~ msgstr "Search"
+
+#~ msgid "Export"
+#~ msgstr "Export"
+
+#~ msgid "Import"
+#~ msgstr "Import"
+
+# Messages
+#~ msgid "Success"
+#~ msgstr "Success"
+
+#~ msgid "Error"
+#~ msgstr "Error"
+
+#~ msgid "Warning"
+#~ msgstr "Warning"
+
+#~ msgid "Loading..."
+#~ msgstr "Loading..."
+
+#~ msgid "Saved successfully"
+#~ msgstr "Saved successfully"
+
+#~ msgid "Deleted successfully"
+#~ msgstr "Deleted successfully"
+
+#~ msgid "Invalid request"
+#~ msgstr "Invalid request"
+
+#~ msgid "Unauthorized"
+#~ msgstr "Unauthorized"
+
+#~ msgid "Not found"
+#~ msgstr "Not found"
+
+#~ msgid "Server error"
+#~ msgstr "Server error"
+
+# Warranties
+#~ msgid "Warranties"
+#~ msgstr "Warranties"
+
+#~ msgid "Warranty"
+#~ msgstr "Warranty"
+
+#~ msgid "Product Name"
+#~ msgstr "Product Name"
+
+#~ msgid "Purchase Date"
+#~ msgstr "Purchase Date"
+
+#~ msgid "Warranty Duration"
+#~ msgstr "Warranty Duration"
+
+#~ msgid "Expiration Date"
+#~ msgstr "Expiration Date"
+
+#~ msgid "Vendor"
+#~ msgstr "Vendor"
+
+#~ msgid "Active"
+#~ msgstr "Active"
+
+#~ msgid "Expired"
+#~ msgstr "Expired"
+
+#~ msgid "Expiring Soon"
+#~ msgstr "Expiring Soon"
+
+#~ msgid "Lifetime"
+#~ msgstr "Lifetime"
+
+msgid "warranty_added_successfully"
+msgstr "Warranty added successfully"
+
diff --git a/locales/en/translation.json b/locales/en/translation.json
new file mode 100644
index 0000000..623f7cb
--- /dev/null
+++ b/locales/en/translation.json
@@ -0,0 +1,563 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "Warranty Tracker",
+ "nav": {
+ "home": "Home",
+ "status": "Status",
+ "settings": "Settings",
+ "about": "About"
+ },
+ "auth": {
+ "login": "Login",
+ "logout": "Logout",
+ "register": "Register",
+ "username": "Username",
+ "password": "Password",
+ "email": "Email",
+ "first_name": "First Name",
+ "last_name": "Last Name",
+ "forgot_password": "Forgot Password?",
+ "reset_password": "Reset Password",
+ "confirm_password": "Confirm Password",
+ "create_account_title": "Create Your Account",
+ "first_name_optional": "First Name (Optional)",
+ "last_name_optional": "Last Name (Optional)",
+ "username_hint": "Username must be unique and will be used for login.",
+ "email_address": "Email Address",
+ "toggle_password": "Show/Hide Password",
+ "password_hint_simple": "Password must be at least 8 characters and include uppercase, lowercase, and numbers.",
+ "password_requirements": "Password Requirements:",
+ "req_length": "At least 8 characters",
+ "req_uppercase": "At least 1 uppercase letter",
+ "req_lowercase": "At least 1 lowercase letter",
+ "req_number": "At least 1 number",
+ "req_special": "At least 1 special character",
+ "create_account": "Create Account",
+ "already_have_account": "Already have an account?",
+ "reset_password_title": "Warracker - Reset Password",
+ "reset_your_password": "Reset Your Password",
+ "reset_password_info": "Enter your email address below and we'll send you a link to reset your password.",
+ "send_reset_link": "Send Reset Link",
+ "back_to_login": "Back to Login",
+ "set_new_password_title": "Warracker - Set New Password",
+ "set_new_password": "Set New Password",
+ "new_password": "New Password",
+ "confirm_new_password": "Confirm New Password",
+ "invalid_or_expired_link": "Invalid or Expired Link",
+ "invalid_link_info": "The password reset link you clicked is invalid or has expired.",
+ "request_new_reset_link": "Request New Reset Link"
+ },
+ "warranties": {
+ "title": "Your Warranties",
+ "title_global": "All Users' Warranties",
+ "add_new": "Add New Warranty",
+ "edit": "Edit Warranty",
+ "delete": "Delete Warranty",
+ "product_name": "Product Name",
+ "purchase_date": "Purchase Date",
+ "warranty_duration": "Warranty Duration",
+ "years": "Years",
+ "months": "Months",
+ "days": "Days",
+ "vendor": "Vendor",
+ "serial_numbers": "Serial Numbers",
+ "purchase_price": "Purchase Price",
+ "notes": "Notes",
+ "tags": "Tags",
+ "status": "Status",
+ "expiration_date": "Expiration Date",
+ "active": "Active",
+ "expired": "Expired",
+ "expiring_soon": "Expiring Soon",
+ "lifetime": "Lifetime",
+ "no_warranties": "No warranties yet. Add your first warranty to get started.",
+ "search_placeholder": "Find by name, vendors, notes, tag, or serial number...",
+ "warranty_type": "Warranty Type",
+ "other_document": "Other Document",
+ "product": "Product",
+ "expiration": "Expiration",
+ "actions": "Actions",
+ "no_warranties_title": "No warranties yet",
+ "no_warranties_desc": "Add your first warranty to get started",
+ "add_warranty": "Add Warranty",
+ "warranty_entry_method": "Warranty Entry Method",
+ "warranty_duration_option": "Warranty Duration",
+ "exact_expiration_option": "Exact Expiration Date",
+ "warranty_period": "Warranty Period",
+ "expiration_date_label": "Expiration Date",
+ "currency": "Currency",
+ "add_tags": "Add Tags",
+ "add_tags_desc": "Tags help you organize and filter your warranties",
+ "save_changes": "Save Changes",
+ "confirm_delete": "Confirm Delete",
+ "manage_tags": "Manage Tags",
+ "add_tag": "Add Tag",
+ "unknown_status": "Unknown Status",
+ "expiring_soon_days": "Expiring Soon ({{days}} {{dayText}})",
+ "days_remaining": "{{days}} {{dayText}} remaining",
+ "day_one": "day",
+ "day_other": "days",
+ "month_one": "month",
+ "month_other": "months",
+ "year_one": "year",
+ "year_other": "years",
+ "na": "N/A",
+ "age": "Age",
+ "warranty": "Warranty",
+ "warranty_ends": "Warranty Ends",
+ "price": "Price",
+ "serial_number": "Serial Number",
+ "vendor": "Vendor",
+ "type": "Type",
+ "owner": "Owner",
+ "product_website": "Product Website",
+ "notes": "Notes",
+ "documents": "Documents",
+ "summary": "Summary",
+ "product_url_optional": "Product URL (Optional)",
+ "enter_serial_number": "Enter serial number",
+ "vendor_optional": "Vendor (Optional)",
+ "vendor_placeholder": "e.g. Amazon, Best Buy, etc.",
+ "lifetime_warranty": "Lifetime Warranty",
+ "warranty_type_optional": "Warranty Type (Optional)",
+ "select_warranty_type": "Select warranty type...",
+ "standard": "Standard",
+ "extended": "Extended",
+ "manufacturer": "Manufacturer",
+ "third_party": "Third Party",
+ "store": "Store",
+ "premium": "Premium",
+ "limited": "Limited",
+ "full": "Full",
+ "parts_only": "Parts Only",
+ "labor_only": "Labor Only",
+ "international": "International",
+ "accidental_damage": "Accidental Damage",
+ "other_custom": "Other (Custom)",
+ "enter_custom_warranty_type": "Enter custom warranty type",
+ "purchase_price_optional": "Purchase Price (Optional)",
+ "notes_optional": "Notes (Optional)",
+ "add_any_notes": "Add any notes about this warranty...",
+ "product_photo_optional": "Product Photo (Optional)",
+ "choose_photo": "Choose Photo",
+ "invoice_receipt": "Invoice/Receipt",
+ "store_locally": "Store Locally",
+ "store_in_paperless": "Store in Paperless-ngx",
+ "choose_file": "Choose File",
+ "browse_paperless": "Browse Paperless-ngx Documents",
+ "product_manual_optional": "Product Manual (Optional)",
+ "files_zip_rar_optional": "Files (ZIP/RAR, Optional)",
+ "search_or_add_new_tag": "Search or add new tag...",
+ "product_information": "Product Information",
+ "product_url": "Product URL",
+ "warranty_details": "Warranty Details",
+ "product_photo": "Product Photo",
+ "product_manual": "Product Manual",
+ "files": "Files",
+ "selected_tags": "Selected Tags",
+ "previous_tab": "Previous",
+ "next_tab": "Next",
+ "delete_photo": "Delete Photo",
+ "delete_invoice": "Delete Invoice",
+ "delete_manual": "Delete Manual",
+ "delete_files": "Delete Files",
+ "current_photo": "Current photo:",
+ "current_invoice": "Current invoice:",
+ "current_manual": "Current manual:",
+ "current_document": "Current document:",
+ "upload_new_photo_replace": "(Upload a new photo to replace)",
+ "no_photo_uploaded": "No photo uploaded",
+ "no_invoice_uploaded": "No invoice uploaded",
+ "no_manual_uploaded": "No manual uploaded",
+ "no_document_uploaded": "No other document uploaded",
+ "photo_will_be_deleted": "Photo will be deleted on save",
+ "invoice_will_be_deleted": "Invoice will be deleted on save",
+ "manual_will_be_deleted": "Manual will be deleted on save",
+ "document_will_be_deleted": "Other document will be deleted on save",
+ "confirm_delete_message": "Are you sure you want to delete this warranty? This action cannot be undone.",
+ "new_tag_name": "New tag name",
+ "existing_tags": "Existing Tags",
+ "edit_warranty": "Edit Warranty",
+ "warranty_type_standard": "Standard",
+ "warranty_type_extended": "Extended",
+ "warranty_type_manufacturer": "Manufacturer",
+ "warranty_type_third_party": "Third Party",
+ "warranty_type_store": "Store",
+ "warranty_type_premium": "Premium",
+ "warranty_type_limited": "Limited",
+ "warranty_type_full": "Full",
+ "warranty_type_parts_only": "Parts Only",
+ "warranty_type_labor_only": "Labor Only",
+ "warranty_type_international": "International",
+ "warranty_type_accidental_damage": "Accidental Damage",
+ "warranty_type_other": "Other (Custom)",
+ "warranty_type_custom_placeholder": "Enter custom warranty type",
+ "notes_placeholder": "Additional notes about this warranty...",
+ "tags_help_text": "Tags help you organize and filter your warranties",
+ "search_add_tag_placeholder": "Search or add new tag...",
+ "upload_new_file_replace": "Upload a new file to replace",
+ "current_other_document": "Current other document",
+ "no_other_document_uploaded": "No other document uploaded",
+ "other_document_will_be_deleted": "Other document will be deleted on save",
+ "files_optional": "Files (ZIP/RAR, Optional)",
+ "invoice_receipt_short": "Invoice",
+ "product_manual_short": "Manual",
+ "files_short": "Files",
+ "product_manual_short": "Manual",
+ "files_short": "Files",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "Years",
+ "months_placeholder": "Months",
+ "days_placeholder": "Days",
+ "add_any_notes_placeholder": "Add any notes about this warranty...",
+ "add_serial_number": "Add another serial number"
+ },
+ "settings": {
+ "title": "Settings",
+ "account_settings": "Account Settings",
+ "preferences": "Preferences",
+ "language": "Language",
+ "select_language": "Select Language",
+ "dark_mode": "Dark Mode",
+ "dark_mode_desc": "Switch between light and dark theme",
+ "currency": "Currency",
+ "timezone": "Timezone",
+ "date_format": "Date Format",
+ "expiring_soon_days": "Expiring Soon Days",
+ "save_changes": "Save Changes",
+ "current_user": "Editing Profile for:",
+ "your_email": "Your email:",
+ "first_name": "First Name",
+ "last_name": "Last Name",
+ "email": "Email",
+ "save_profile": "Save Changes",
+ "default_view": "Default View",
+ "default_view_desc": "Choose your preferred view for warranties",
+ "grid_view": "Grid View",
+ "list_view": "List View",
+ "table_view": "Table View",
+ "currency_symbol": "Currency Symbol",
+ "currency_symbol_desc": "Choose the symbol to display for prices",
+ "currency_position": "Currency Position",
+ "currency_position_desc": "Choose whether currency symbol appears on the left or right of numbers",
+ "expiring_soon_days_desc": "Number of days before expiration to show warnings",
+ "date_format_desc": "Choose how dates are displayed",
+ "save_preferences": "Save Preferences",
+ "notification_settings": "Notification Settings",
+ "notification_channel": "Notification Channel",
+ "notification_channel_desc": "Choose how you want to receive notifications",
+ "notification_disabled": "Disabled",
+ "notification_email": "Email",
+ "notification_apprise": "Apprise",
+ "notification_both": "Both",
+ "email_settings": "Email Settings",
+ "notification_frequency": "Notification Frequency",
+ "notification_frequency_desc": "How often to receive email notifications",
+ "daily": "Daily",
+ "weekly": "Weekly",
+ "monthly": "Monthly",
+ "notification_time": "Notification Time",
+ "timezone_desc": "Your local timezone for notifications",
+ "apprise_settings": "Apprise Settings",
+ "apprise_frequency": "Apprise Notification Frequency",
+ "apprise_frequency_desc": "How often to receive Apprise notifications",
+ "apprise_time": "Apprise Notification Time",
+ "apprise_timezone": "Apprise Timezone",
+ "apprise_timezone_desc": "Your local timezone for Apprise notifications",
+ "save_notification_settings": "Save Notification Settings",
+ "security": "Security",
+ "change_password": "Change Password",
+ "change_password_desc": "Update your account password",
+ "change": "Change",
+ "current_password": "Current Password",
+ "new_password": "New Password",
+ "confirm_password": "Confirm New Password",
+ "update_password": "Update Password",
+ "cancel": "Cancel",
+ "danger_zone": "Danger Zone",
+ "delete_account": "Delete Account",
+ "delete_account_desc": "Permanently delete your account and all data",
+ "admin_settings": "Admin Settings",
+ "admin_actions": "Admin Actions",
+ "refresh_data": "Refresh Data",
+ "check_admin_status": "Check Admin Status",
+ "show_users_list": "Show Users List",
+ "test_api": "Test API",
+ "send_notifications": "Send Warranty Notifications",
+ "check_scheduler": "Check Scheduler Status",
+ "site_settings": "Site Settings",
+ "registration_enabled": "Registration Enabled",
+ "registration_enabled_desc": "Allow new users to register",
+ "email_base_url": "Email Base URL",
+ "global_view_enabled": "Global View Enabled",
+ "global_view_admin_only": "Global View Admin Only",
+ "save_site_settings": "Save Site Settings",
+ "oidc_configuration": "OIDC SSO Configuration",
+ "enable_oidc": "Enable OIDC SSO",
+ "oidc_provider_name": "OIDC Provider Name",
+ "client_id": "Client ID",
+ "client_secret": "Client Secret",
+ "issuer_url": "Issuer URL",
+ "scope": "Scope",
+ "save_oidc_settings": "Save OIDC Settings",
+ "oidc_sso_desc": "Allow users to log in via an OIDC provider.",
+ "oidc_only_mode": "OIDC-Only Login Mode",
+ "oidc_only_mode_desc": "Hide traditional username/password login form and only allow OIDC login. <strong>Warning:</strong> Ensure OIDC is properly configured before enabling this option.",
+ "oidc_provider_name_desc": "Internal name for the OIDC client (e.g., 'oidc').",
+ "client_secret_desc": "Sensitive value. Stored in the database. An application restart is required for changes to take effect.",
+ "issuer_url_desc": "The base URL of your OIDC provider.",
+ "scope_desc": "Space-separated OIDC scopes.",
+ "oidc_restart_message": "Application restart is required for OIDC settings to take full effect.",
+ "api_token": "API Token",
+ "view_documents": "View Documents in Warracker",
+ "connection_testing": "Connection Testing",
+ "apprise_notifications": "Apprise Notifications",
+ "enable_apprise": "Enable Apprise Notifications",
+ "loading": "Loading...",
+ "time_of_day_notification": "Time of day to receive notifications (in 24-hour format)",
+ "paperless_ngx_settings": "Paperless-ngx Settings",
+ "paperless_ngx_about_title": "About Paperless-ngx Integration:",
+ "paperless_ngx_about_desc": "This optional feature allows you to store warranty documents in your self-hosted Paperless-ngx instance instead of locally. When enabled, users can choose where to store each document: locally or in Paperless-ngx.",
+ "paperless_ngx_desc": "Configure integration with Paperless-ngx document management system",
+ "enable_paperless": "Enable Paperless-ngx Integration",
+ "paperless_url": "Paperless-ngx URL",
+ "paperless_url_desc": "Base URL of your Paperless-ngx instance",
+ "paperless_token": "API Token",
+ "paperless_token_desc": "Your Paperless-ngx API authentication token",
+ "paperless_token_desc_generate": "Generate an API token from your Paperless-ngx instance (Settings → API Tokens).",
+ "paperless_view_in_app": "View documents in app",
+ "paperless_view_in_app_desc": "Open documents within the app instead of in a new tab",
+ "debug_config": "Debug Config",
+ "test_upload": "Test Upload",
+ "save_paperless_settings": "Save Paperless-ngx Settings",
+ "apprise_desc": "Configure Apprise for advanced notification delivery to multiple services",
+ "apprise_desc_system_wide": "Enable or disable Apprise notifications system-wide",
+ "apprise_not_available_title": "Apprise Not Available:",
+ "apprise_not_available_desc": "The Apprise notification library is not installed or available. Notification features are disabled.",
+ "apprise_url": "Apprise URL",
+ "apprise_url_desc": "Your Apprise notification service URL",
+ "apprise_mode": "Notification Mode",
+ "apprise_mode_desc": "Choose when to send Apprise notifications",
+ "apprise_mode_global": "Global Summary",
+ "apprise_mode_individual": "Per User",
+ "test_paperless": "Test Paperless Connection",
+ "test_apprise": "Test Apprise Connection",
+ "apprise_warranty_scope": "Warranty Scope",
+ "apprise_warranty_scope_desc": "Choose which warranties to include in notifications",
+ "all_warranties": "All Warranties",
+ "personal_warranties": "Personal Warranties Only",
+ "all_users_warranties": "All Users' Warranties",
+ "admin_warranties_only": "Admin's Warranties Only",
+ "apprise_notification_days": "Notification Days",
+ "apprise_notification_days_desc": "Days before expiration to send notifications (comma-separated, e.g., \"7,30\" for 7 days and 30 days before)",
+ "apprise_check_frequency": "Check Frequency",
+ "apprise_check_frequency_desc": "How often the system checks for expiring warranties (global setting)",
+ "apprise_title_prefix": "Message Title Prefix",
+ "apprise_title_prefix_desc": "Prefix added to notification titles (e.g., \"[Warracker]\" results in \"[Warracker] Warranties Expiring Soon\")",
+ "apprise_test_url": "Test URL (Optional)",
+ "apprise_test_url_desc": "Optional: URL for sending test notifications only (won't be saved to main configuration)",
+ "save_apprise_settings": "Save Apprise Settings",
+ "validate_urls": "Validate URLs",
+ "send_expiration_notifications_now": "Send Expiration Notifications Now",
+ "apprise_current_status": "Current Status",
+ "apprise_urls_configured": "URLs Configured:",
+ "apprise_supported_services": "Supported Services",
+ "apprise_supported_services_desc": "Apprise supports 80+ notification services including: Discord, Slack, Telegram, Email (Gmail, Outlook), Webhooks, Microsoft Teams, Matrix, Pushover, Ntfy, Gotify, and many more.",
+ "view_full_list_of_supported_services": "View Full List of Supported Services",
+ "ownership_management": "Ownership Management",
+ "transfer_ownership": "Transfer Ownership",
+ "warning_title": "Warning:",
+ "transfer_ownership_warning": "Transfer application ownership to another admin user. This action is irreversible.",
+ "transfer_ownership_desc": "Once ownership is transferred, you will become a regular admin and the new owner will have ultimate control over the application.",
+ "select_new_owner": "Select New Owner (must be an admin)",
+ "select_admin_user": "Select an admin user...",
+ "transfer_ownership_button": "Transfer Ownership",
+ "transfer_ownership_irreversible": "This action cannot be undone.",
+ "transfer_ownership_confirmation": "You are about to transfer application ownership to",
+ "after_this_transfer": "After this transfer:",
+ "transfer_ownership_consequence_1": "You will become a regular admin",
+ "transfer_ownership_consequence_2": "The new owner will have ultimate control over the application",
+ "transfer_ownership_consequence_3": "Only the new owner can transfer ownership again",
+ "transfer_ownership_type_to_confirm": "To confirm, please type \"TRANSFER\" in the field below:"
+ },
+ "actions": {
+ "save": "Save",
+ "cancel": "Cancel",
+ "delete": "Delete",
+ "edit": "Edit",
+ "export": "Export",
+ "import": "Import",
+ "refresh": "Refresh",
+ "search": "Search",
+ "clear": "Clear",
+ "upload": "Upload",
+ "download": "Download",
+ "manage_tags": "Manage Tags",
+ "close": "Close",
+ "save_changes": "Save Changes"
+ },
+ "filters": {
+ "all_status": "All Status",
+ "all_tags": "All Tags",
+ "all_vendors": "All Vendors",
+ "all_types": "All Types",
+ "sort_by": "Sort By",
+ "sort_expiration": "Expiration Date",
+ "sort_purchase": "Purchase Date",
+ "sort_age": "Age",
+ "sort_name": "Product Name",
+ "sort_vendor": "Vendor",
+ "sort_warranty_type": "Warranty Type",
+ "status": "Status",
+ "tags": "Tags",
+ "vendor": "Vendor",
+ "warranty_type": "Warranty Type",
+ "view": "View",
+ "scope": "Scope"
+ },
+ "messages": {
+ "success": "Success",
+ "error": "Error",
+ "warning": "Warning",
+ "loading": "Loading...",
+ "saved": "Changes saved successfully",
+ "deleted": "Item deleted successfully",
+ "confirm_delete": "Are you sure you want to delete this item?",
+ "no_results": "No results found",
+ "file_too_large": "File is too large",
+ "invalid_file_type": "Invalid file type",
+ "fill_first_last_name": "Please fill in First Name and Last Name",
+ "email_cannot_be_empty": "Email address cannot be empty.",
+ "enter_valid_email": "Please enter a valid email address.",
+ "profile_updated_successfully": "Profile updated successfully",
+ "preferences_saved_successfully": "Preferences saved successfully.",
+ "fill_password_fields": "Please fill in all password fields",
+ "passwords_do_not_match": "New passwords do not match",
+ "password_min_length": "Password must be at least 8 characters long",
+ "type_delete_to_confirm": "Please type DELETE to confirm",
+ "account_deleted_successfully": "Account deleted successfully",
+ "account_cannot_delete_offline": "Account cannot be deleted in offline mode",
+ "failed_delete_account": "Failed to delete account. Please try again.",
+ "user_updated_successfully": "User updated successfully",
+ "user_deleted_successfully": "User deleted successfully",
+ "user_id_missing": "User ID is missing",
+ "failed_load_users": "Failed to load users",
+ "error_loading_users": "Error loading users",
+ "select_user_transfer_ownership": "Please select a user to transfer ownership to",
+ "ownership_transferred_successfully": "Ownership transferred successfully! Refreshing page...",
+ "failed_load_site_settings": "Failed to load site settings. Please try again.",
+ "invalid_email_base_url": "Invalid Email Base URL format. It should start with http:// or https://",
+ "no_site_settings_to_save": "No site settings to save.",
+ "site_settings_saved_successfully": "Site settings saved successfully",
+ "failed_save_site_settings": "Failed to save site settings",
+ "oidc_settings_saved_successfully": "OIDC settings saved successfully.",
+ "failed_save_oidc_settings": "Failed to save OIDC settings.",
+ "api_endpoint_accessible": "API endpoint is accessible",
+ "api_endpoint_not_accessible": "API endpoint is not accessible. Status: ",
+ "only_admins_send_notifications": "Only administrators can send warranty notifications",
+ "notifications_triggered_successfully": "Notifications triggered successfully",
+ "notification_settings_saved_successfully": "Notification settings saved successfully",
+ "apprise_settings_saved_successfully": "Apprise settings saved successfully",
+ "test_notification_sent_successfully": "Test notification sent successfully",
+ "no_urls_to_validate": "No URLs to validate",
+ "paperless_settings_saved_successfully": "Paperless-ngx settings saved successfully!",
+ "enter_valid_paperless_url": "Please enter a valid URL (e.g., https://paperless.yourdomain.com)",
+ "enter_paperless_url_first": "Please enter a Paperless-ngx URL first",
+ "paperless_connection_test_successful": "Paperless-ngx connection test successful!",
+ "paperless_connection_test_failed": "Paperless-ngx connection test failed",
+ "enter_api_token_test_connection": "Please enter an API token to test the connection",
+ "failed_load_user_data": "Failed to load user data. Please try again.",
+ "could_not_connect_user_data": "Could not connect to fetch user data. Displaying cached info.",
+ "preferences_saved_locally_failed_sync": "Preferences saved locally, but failed to sync with server: ",
+ "preferences_saved_locally": "Preferences saved locally.",
+ "correct_errors_in_tab": "Please correct the errors in the highlighted tab before continuing.",
+ "please_fill_out_this_field": "Please fill out this field.",
+ "warranty_added_successfully": "Warranty added successfully",
+ "tag_name_required": "Tag name is required",
+ "tag_creation_function_not_found": "Tag creation function not found",
+ "tag_created_successfully": "Tag created successfully",
+ "tag_updated_successfully": "Tag updated successfully",
+ "tag_deleted_successfully": "Tag deleted successfully",
+ "failed_to_create_tag": "Failed to create tag",
+ "failed_to_update_tag": "Failed to update tag",
+ "failed_to_delete_tag": "Failed to delete tag"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية",
+ "ru": "Русский",
+ "uk": "Українська",
+ "zh_CN": "简体中文",
+ "zh_HK": "繁體中文",
+ "ja": "日本語",
+ "pt": "Português",
+ "ko": "한국어"
+ },
+ "status": {
+ "title": "System Status",
+ "dashboard_title": "Warranty Status Dashboard",
+ "global_dashboard_title": "Global Warranty Status Dashboard",
+ "overview": "Overview",
+ "statistics": "Statistics",
+ "total_warranties": "Total Warranties",
+ "active_warranties": "Active Warranties",
+ "expiring_soon": "Expiring Soon",
+ "expired_warranties": "Expired Warranties",
+ "warranty_distribution": "Warranty Distribution",
+ "expiration_timeline": "Expiration Timeline",
+ "recent_activity": "Recent Activity",
+ "recent_expirations": "Recently Expired or Expiring Soon",
+ "recent_expirations_empty": "No recently expired or expiring warranties.",
+ "system_health": "System Health",
+ "database_status": "Database Status",
+ "connected": "Connected",
+ "version": "Version",
+ "uptime": "Uptime"
+ },
+ "about": {
+ "title": "About Warracker",
+ "description": "A comprehensive warranty management system designed to help you track, organize, and manage all your product warranties in one secure, user-friendly platform.",
+ "version": "Version",
+ "update_status": "Update Status",
+ "checking_updates": "Checking for updates...",
+ "view_release_notes": "View Release Notes",
+ "project_info": "Project Information",
+ "project_description": "Warracker is an open-source warranty management system built with modern web technologies. It provides a secure and intuitive way to manage product warranties, track expiration dates, and organize important documents.",
+ "github_repository": "GitHub Repository",
+ "releases": "Releases",
+ "community_support": "Community & Support",
+ "community_description": "Join our community for support, discussions, and updates. Report bugs, request features, or get help from other users and contributors.",
+ "discord_community": "Discord Community",
+ "report_issues": "Report Issues",
+ "developer_info": "Developer Information",
+ "developer_description": "Warracker is developed and maintained by Sassanix. The project is open-source and welcomes contributions from the community.",
+ "sassanix": "Sassanix",
+ "agpl_license": "AGPL-3.0 License",
+ "support_project": "Support the Project",
+ "support_description": "If you find Warracker useful, consider supporting its development!",
+ "new_version_available": "New version {{version}} available!",
+ "latest_version": "You are using the latest version",
+ "update_check_failed": "Failed to check for updates",
+ "features": "Features",
+ "feature_track": "Track product warranties",
+ "feature_notifications": "Get expiration notifications",
+ "feature_documents": "Store warranty documents",
+ "feature_reports": "Generate warranty reports",
+ "feature_tags": "Organize with tags",
+ "feature_export": "Export warranty data",
+ "support": "Support",
+ "documentation": "Documentation",
+ "github": "GitHub Repository",
+ "license": "License",
+ "copyright": "Copyright",
+ "developed_by": "Developed by"
+ }
+}
diff --git a/locales/es/translation.json b/locales/es/translation.json
new file mode 100644
index 0000000..afbf6bc
--- /dev/null
+++ b/locales/es/translation.json
@@ -0,0 +1,562 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "Seguimiento de Garantías",
+ "nav": {
+ "home": "Inicio",
+ "status": "Estado",
+ "settings": "Configuración",
+ "about": "Acerca de"
+ },
+ "auth": {
+ "login": "Iniciar Sesión",
+ "logout": "Cerrar Sesión",
+ "register": "Registrarse",
+ "username": "Nombre de Usuario",
+ "password": "Contraseña",
+ "email": "Correo Electrónico",
+ "first_name": "Nombre",
+ "last_name": "Apellido",
+ "forgot_password": "¿Olvidaste tu contraseña?",
+ "reset_password": "Restablecer Contraseña",
+ "confirm_password": "Confirmar Contraseña",
+ "create_account_title": "Crea tu cuenta",
+ "first_name_optional": "Nombre (opcional)",
+ "last_name_optional": "Apellido (opcional)",
+ "username_hint": "El nombre de usuario debe ser único y se utilizará para iniciar sesión.",
+ "email_address": "Dirección de correo electrónico",
+ "toggle_password": "Mostrar/Ocultar contraseña",
+ "password_hint_simple": "La contraseña debe tener al menos 8 caracteres e incluir mayúsculas, minúsculas y números.",
+ "password_requirements": "Requisitos de la contraseña:",
+ "req_length": "Al menos 8 caracteres",
+ "req_uppercase": "Al menos 1 letra mayúscula",
+ "req_lowercase": "Al menos 1 letra minúscula",
+ "req_number": "Al menos 1 número",
+ "req_special": "Al menos 1 carácter especial",
+ "create_account": "Crear cuenta",
+ "already_have_account": "¿Ya tienes una cuenta?",
+ "reset_password_title": "Warracker - Restablecer contraseña",
+ "reset_your_password": "Restablece tu contraseña",
+ "reset_password_info": "Introduce tu dirección de correo electrónico a continuación y te enviaremos un enlace para restablecer tu contraseña.",
+ "send_reset_link": "Enviar enlace de restablecimiento",
+ "back_to_login": "Volver a iniciar sesión",
+ "set_new_password_title": "Warracker - Establecer nueva contraseña",
+ "set_new_password": "Establecer nueva contraseña",
+ "new_password": "Nueva contraseña",
+ "confirm_new_password": "Confirmar nueva contraseña",
+ "invalid_or_expired_link": "Enlace no válido o caducado",
+ "invalid_link_info": "El enlace para restablecer la contraseña en el que has hecho clic no es válido o ha caducado.",
+ "request_new_reset_link": "Solicitar nuevo enlace de restablecimiento"
+ },
+ "warranties": {
+ "title": "Tus Garantías",
+ "title_global": "Garantías de Todos los Usuarios",
+ "add_new": "Agregar Nueva Garantía",
+ "edit": "Editar Garantía",
+ "delete": "Eliminar Garantía",
+ "product_name": "Nombre del Producto",
+ "purchase_date": "Fecha de Compra",
+ "warranty_duration": "Duración de Garantía",
+ "years": "Años",
+ "months": "Meses",
+ "days": "Días",
+ "vendor": "Proveedor",
+ "serial_numbers": "Números de Serie",
+ "purchase_price": "Precio de Compra",
+ "notes": "Notas",
+ "tags": "Etiquetas",
+ "status": "Estado",
+ "expiration_date": "Fecha de Vencimiento",
+ "active": "Activo",
+ "expired": "Vencido",
+ "expiring_soon": "Vence Pronto",
+ "lifetime": "De por Vida",
+ "no_warranties": "Aún no hay garantías. Agrega tu primera garantía para comenzar.",
+ "search_placeholder": "Buscar por nombre, proveedores, notas, etiqueta o número de serie...",
+ "warranty_type": "Tipo de Garantía",
+ "other_document": "Otro Documento",
+ "product": "Producto",
+ "expiration": "Vencimiento",
+ "actions": "Acciones",
+ "no_warranties_title": "Aún no hay garantías",
+ "no_warranties_desc": "Agrega tu primera garantía para comenzar",
+ "add_warranty": "Agregar Garantía",
+ "warranty_entry_method": "Método de Entrada de Garantía",
+ "warranty_duration_option": "Duración de Garantía",
+ "exact_expiration_option": "Fecha de Vencimiento Exacta",
+ "warranty_period": "Período de Garantía",
+ "expiration_date_label": "Fecha de Vencimiento",
+ "currency": "Moneda",
+ "add_tags": "Agregar Etiquetas",
+ "add_tags_desc": "Las etiquetas te ayudan a organizar y filtrar tus garantías",
+ "save_changes": "Guardar Cambios",
+ "confirm_delete": "Confirmar Eliminación",
+ "manage_tags": "Gestionar Etiquetas",
+ "add_tag": "Agregar Etiqueta",
+ "unknown_status": "Estado Desconocido",
+ "expiring_soon_days": "Vence Pronto ({{days}} {{dayText}})",
+ "days_remaining": "{{days}} {{dayText}} restantes",
+ "day_one": "día",
+ "day_other": "días",
+ "month_one": "mes",
+ "month_other": "meses",
+ "year_one": "año",
+ "year_other": "años",
+ "na": "N/A",
+ "age": "Edad",
+ "warranty": "Garantía",
+ "warranty_ends": "Fin de Garantía",
+ "price": "Precio",
+ "serial_number": "Número de Serie",
+ "vendor": "Proveedor",
+ "type": "Tipo",
+ "owner": "Propietario",
+ "product_website": "Sitio Web del Producto",
+ "notes": "Notas",
+ "documents": "Documentos",
+ "summary": "Resumen",
+ "product_url_placeholder": "https://example.com/product",
+ "product_url_optional": "URL del producto (opcional)",
+ "enter_serial_number": "Introduzca el número de serie",
+ "vendor_optional": "Vendedor (opcional)",
+ "vendor_placeholder": "p. ej., Amazon, Best Buy, etc.",
+ "lifetime_warranty": "Garantía de por vida",
+ "warranty_type_optional": "Tipo de garantía (opcional)",
+ "select_warranty_type": "Seleccione el tipo de garantía...",
+ "standard": "Estándar",
+ "extended": "Extendida",
+ "manufacturer": "Fabricante",
+ "third_party": "Terceros",
+ "store": "Tienda",
+ "premium": "Premium",
+ "limited": "Limitada",
+ "full": "Completa",
+ "parts_only": "Solo piezas",
+ "labor_only": "Solo mano de obra",
+ "international": "Internacional",
+ "accidental_damage": "Daños accidentales",
+ "other_custom": "Otro (personalizado)",
+ "enter_custom_warranty_type": "Introduzca un tipo de garantía personalizado",
+ "purchase_price_optional": "Precio de compra (opcional)",
+ "notes_optional": "Notas (opcional)",
+ "add_any_notes": "Añada cualquier nota sobre esta garantía...",
+ "product_photo_optional": "Foto del producto (opcional)",
+ "choose_photo": "Elegir foto",
+ "invoice_receipt": "Factura/Recibo",
+ "store_locally": "Almacenar localmente",
+ "store_in_paperless": "Almacenar en Paperless-ngx",
+ "choose_file": "Elegir archivo",
+ "browse_paperless": "Explorar documentos de Paperless-ngx",
+ "product_manual_optional": "Manual del producto (opcional)",
+ "files_zip_rar_optional": "Archivos (ZIP/RAR, opcional)",
+ "search_or_add_new_tag": "Buscar o añadir nueva etiqueta...",
+ "product_information": "Información del producto",
+ "product_url": "URL del producto",
+ "warranty_details": "Detalles de la garantía",
+ "product_photo": "Foto del producto",
+ "product_manual": "Manual del producto",
+ "files": "Archivos",
+ "selected_tags": "Etiquetas seleccionadas",
+ "previous_tab": "Anterior",
+ "next_tab": "Siguiente",
+ "delete_photo": "Eliminar foto",
+ "delete_invoice": "Eliminar factura",
+ "delete_manual": "Eliminar manual",
+ "delete_files": "Eliminar archivos",
+ "current_photo": "Foto actual:",
+ "current_invoice": "Factura actual:",
+ "current_manual": "Manual actual:",
+ "current_document": "Documento actual:",
+ "upload_new_photo_replace": "(Sube una nueva foto para reemplazar)",
+ "no_photo_uploaded": "No se ha subido ninguna foto",
+ "no_invoice_uploaded": "No se ha subido ninguna factura",
+ "no_manual_uploaded": "No se ha subido ningún manual",
+ "no_document_uploaded": "No se ha subido ningún otro documento",
+ "photo_will_be_deleted": "La foto se eliminará al guardar",
+ "invoice_will_be_deleted": "La factura se eliminará al guardar",
+ "manual_will_be_deleted": "El manual se eliminará al guardar",
+ "document_will_be_deleted": "El otro documento se eliminará al guardar",
+ "confirm_delete_message": "¿Está seguro de que desea eliminar esta garantía? Esta acción no se puede deshacer.",
+ "new_tag_name": "Nuevo nombre de etiqueta",
+ "existing_tags": "Etiquetas existentes",
+ "edit_warranty": "Editar Garantía",
+ "warranty_type_standard": "Estándar",
+ "warranty_type_extended": "Extendida",
+ "warranty_type_manufacturer": "Fabricante",
+ "warranty_type_third_party": "Terceros",
+ "warranty_type_store": "Tienda",
+ "warranty_type_premium": "Premium",
+ "warranty_type_limited": "Limitada",
+ "warranty_type_full": "Completa",
+ "warranty_type_parts_only": "Solo Piezas",
+ "warranty_type_labor_only": "Solo Mano de Obra",
+ "warranty_type_international": "Internacional",
+ "warranty_type_accidental_damage": "Daños Accidentales",
+ "warranty_type_other": "Otro (Personalizado)",
+ "warranty_type_custom_placeholder": "Ingrese tipo de garantía personalizado",
+ "notes_placeholder": "Notas adicionales sobre esta garantía...",
+ "tags_help_text": "Las etiquetas te ayudan a organizar y filtrar tus garantías",
+ "search_add_tag_placeholder": "Buscar o agregar nueva etiqueta...",
+ "upload_new_file_replace": "Subir un nuevo archivo para reemplazar",
+ "current_other_document": "Documento actual",
+ "no_other_document_uploaded": "No se ha subido ningún otro documento",
+ "other_document_will_be_deleted": "El otro documento se eliminará al guardar",
+ "files_optional": "Archivos (ZIP/RAR, Opcional)",
+ "invoice_receipt_short": "Factura",
+ "product_manual_short": "Manual",
+ "files_short": "Archivos",
+ "years_placeholder": "Años",
+ "months_placeholder": "Meses",
+ "days_placeholder": "Días",
+ "add_any_notes_placeholder": "Agregar notas sobre esta garantía...",
+ "enter_serial_number": "Introducir número de serie",
+ "add_serial_number": "Agregar otro número de serie"
+ },
+ "settings": {
+ "title": "Configuración",
+ "account_settings": "Configuración de Cuenta",
+ "preferences": "Preferencias",
+ "language": "Idioma",
+ "select_language": "Seleccionar Idioma",
+ "dark_mode": "Modo Oscuro",
+ "dark_mode_desc": "Cambiar entre tema claro y oscuro",
+ "currency": "Moneda",
+ "timezone": "Zona Horaria",
+ "date_format": "Formato de Fecha",
+ "expiring_soon_days": "Días de Vencimiento Próximo",
+ "save_changes": "Guardar Cambios",
+ "current_user": "Editando Perfil para:",
+ "your_email": "Tu correo:",
+ "first_name": "Nombre",
+ "last_name": "Apellido",
+ "email": "Email",
+ "save_profile": "Guardar Cambios",
+ "default_view": "Vista Predeterminada",
+ "default_view_desc": "Elige tu vista preferida para las garantías",
+ "grid_view": "Vista de Cuadrícula",
+ "list_view": "Vista de Lista",
+ "table_view": "Vista de Tabla",
+ "currency_symbol": "Símbolo de Moneda",
+ "currency_symbol_desc": "Elige el símbolo a mostrar para los precios",
+ "currency_position": "Posición de Moneda",
+ "currency_position_desc": "Elige si el símbolo de moneda aparece a la izquierda o derecha de los números",
+ "expiring_soon_days_desc": "Número de días antes de la expiración para mostrar advertencias",
+ "date_format_desc": "Elige cómo se muestran las fechas",
+ "save_preferences": "Guardar Preferencias",
+ "notification_settings": "Configuración de Notificaciones",
+ "notification_channel": "Canal de Notificación",
+ "notification_channel_desc": "Elige cómo quieres recibir notificaciones",
+ "notification_disabled": "Deshabilitado",
+ "notification_email": "Email",
+ "notification_apprise": "Apprise",
+ "notification_both": "Ambos",
+ "email_settings": "Configuración de Email",
+ "notification_frequency": "Frecuencia de Notificación",
+ "notification_frequency_desc": "Con qué frecuencia recibir notificaciones por email",
+ "daily": "Diario",
+ "weekly": "Semanal",
+ "monthly": "Mensual",
+ "notification_time": "Hora de Notificación",
+ "timezone_desc": "Tu zona horaria local para notificaciones",
+ "apprise_settings": "Configuración de Apprise",
+ "apprise_frequency": "Frecuencia de Notificación Apprise",
+ "apprise_frequency_desc": "Con qué frecuencia recibir notificaciones Apprise",
+ "apprise_time": "Hora de Notificación Apprise",
+ "apprise_timezone": "Zona Horaria Apprise",
+ "apprise_timezone_desc": "Tu zona horaria local para notificaciones Apprise",
+ "save_notification_settings": "Guardar Configuración de Notificaciones",
+ "security": "Seguridad",
+ "change_password": "Cambiar Contraseña",
+ "change_password_desc": "Actualizar la contraseña de tu cuenta",
+ "change": "Cambiar",
+ "current_password": "Contraseña Actual",
+ "new_password": "Nueva Contraseña",
+ "confirm_password": "Confirmar Nueva Contraseña",
+ "update_password": "Actualizar Contraseña",
+ "cancel": "Cancelar",
+ "danger_zone": "Zona de Peligro",
+ "delete_account": "Eliminar Cuenta",
+ "delete_account_desc": "Eliminar permanentemente tu cuenta y todos los datos",
+ "admin_settings": "Configuración de Administrador",
+ "admin_actions": "Acciones de Administrador",
+ "refresh_data": "Actualizar Datos",
+ "check_admin_status": "Verificar Estado de Administrador",
+ "show_users_list": "Mostrar Lista de Usuarios",
+ "test_api": "Probar API",
+ "send_notifications": "Enviar Notificaciones de Garantía",
+ "check_scheduler": "Verificar Estado del Programador",
+ "site_settings": "Configuración del Sitio",
+ "registration_enabled": "Registro Habilitado",
+ "registration_enabled_desc": "Permitir que nuevos usuarios se registren",
+ "email_base_url": "URL Base de Email",
+ "global_view_enabled": "Vista Global Habilitada",
+ "global_view_admin_only": "Vista Global Solo Admin",
+ "save_site_settings": "Guardar Configuración del Sitio",
+ "oidc_configuration": "Configuración OIDC SSO",
+ "enable_oidc": "Habilitar OIDC SSO",
+ "oidc_provider_name": "Nombre del Proveedor OIDC",
+ "client_id": "ID de Cliente",
+ "client_secret": "Secreto de Cliente",
+ "issuer_url": "URL del Emisor",
+ "scope": "Alcance",
+ "save_oidc_settings": "Guardar Configuración OIDC",
+ "oidc_sso_desc": "Permitir a los usuarios iniciar sesión a través de un proveedor OIDC.",
+ "oidc_only_mode": "Modo de inicio de sesión solo OIDC",
+ "oidc_only_mode_desc": "Ocultar el formulario de inicio de sesión tradicional de nombre de usuario/contraseña y permitir solo el inicio de sesión OIDC. <strong>Advertencia:</strong> Asegúrese de que OIDC esté configurado correctamente antes de habilitar esta opción.",
+ "oidc_provider_name_desc": "Nombre interno para el cliente OIDC (por ejemplo, 'oidc').",
+ "client_secret_desc": "Valor sensible. Almacenado en la base de datos. Se requiere un reinicio de la aplicación para que los cambios surtan efecto.",
+ "issuer_url_desc": "La URL base de su proveedor OIDC.",
+ "scope_desc": "Alcances de OIDC separados por espacios.",
+ "oidc_restart_message": "Se requiere un reinicio de la aplicación para que la configuración de OIDC surta pleno efecto.",
+ "api_token": "Token de API",
+ "view_documents": "Ver Documentos en Warracker",
+ "connection_testing": "Prueba de Conexión",
+ "apprise_notifications": "Notificaciones Apprise",
+ "enable_apprise": "Habilitar Notificaciones Apprise",
+ "loading": "Cargando...",
+ "time_of_day_notification": "Hora del día para recibir notificaciones (formato 24h)",
+ "paperless_ngx_settings": "Configuración Paperless-ngx",
+ "paperless_ngx_about_title": "Acerca de la integración de Paperless-ngx:",
+ "paperless_ngx_about_desc": "Esta función opcional le permite almacenar documentos de garantía en su instancia autoalojada de Paperless-ngx en lugar de localmente. Cuando está habilitada, los usuarios pueden elegir dónde almacenar cada documento: localmente o en Paperless-ngx.",
+ "paperless_ngx_desc": "Configurar integración con el sistema de gestión de documentos Paperless-ngx",
+ "enable_paperless": "Habilitar Integración Paperless-ngx",
+ "paperless_url": "URL Paperless-ngx",
+ "paperless_url_desc": "URL base de su instancia Paperless-ngx",
+ "paperless_token": "Token API",
+ "paperless_token_desc": "Su token de autenticación API Paperless-ngx",
+ "paperless_token_desc_generate": "Genere un token de API desde su instancia de Paperless-ngx (Configuración → Tokens de API).",
+ "paperless_view_in_app": "Ver documentos en la app",
+ "paperless_view_in_app_desc": "Abrir documentos dentro de la aplicación en lugar de una nueva pestaña",
+ "debug_config": "Configuración de depuración",
+ "test_upload": "Prueba de carga",
+ "save_paperless_settings": "Guardar configuración de Paperless-ngx",
+ "apprise_desc": "Configurar Apprise para entrega avanzada de notificaciones a múltiples servicios",
+ "apprise_desc_system_wide": "Habilitar o deshabilitar las notificaciones de Apprise en todo el sistema",
+ "apprise_not_available_title": "Apprise no disponible:",
+ "apprise_not_available_desc": "La biblioteca de notificaciones de Apprise no está instalada o no está disponible. Las funciones de notificación están deshabilitadas.",
+ "apprise_url": "URL Apprise",
+ "apprise_url_desc": "URL de su servicio de notificación Apprise",
+ "apprise_mode": "Modo de Notificación",
+ "apprise_mode_desc": "Elegir cuándo enviar notificaciones Apprise",
+ "apprise_mode_global": "Resumen global",
+ "apprise_mode_individual": "Por usuario",
+ "test_paperless": "Probar Conexión Paperless",
+ "test_apprise": "Probar Conexión Apprise",
+ "apprise_warranty_scope": "Alcance de Garantías",
+ "apprise_warranty_scope_desc": "Elegir qué garantías incluir en las notificaciones",
+ "all_warranties": "Todas las Garantías",
+ "personal_warranties": "Solo Garantías Personales",
+ "all_users_warranties": "Garantías de todos los usuarios",
+ "admin_warranties_only": "Solo garantías del administrador",
+ "apprise_notification_days": "Días de notificación",
+ "apprise_notification_days_desc": "Días antes del vencimiento para enviar notificaciones (separados por comas, por ejemplo, \"7,30\" para 7 días y 30 días antes)",
+ "apprise_check_frequency": "Frecuencia de verificación",
+ "apprise_check_frequency_desc": "Con qué frecuencia el sistema comprueba si hay garantías que vencen (configuración global)",
+ "apprise_title_prefix": "Prefijo del título del mensaje",
+ "apprise_title_prefix_desc": "Prefijo agregado a los títulos de las notificaciones (por ejemplo, \"[Warracker]\" da como resultado \"[Warracker] Garantías que vencen pronto\")",
+ "apprise_test_url": "URL de prueba (opcional)",
+ "apprise_test_url_desc": "Opcional: URL para enviar solo notificaciones de prueba (no se guardará en la configuración principal)",
+ "save_apprise_settings": "Guardar configuración de Apprise",
+ "validate_urls": "Validar URL",
+ "send_expiration_notifications_now": "Enviar notificaciones de vencimiento ahora",
+ "apprise_current_status": "Estado actual",
+ "apprise_urls_configured": "URL configuradas:",
+ "apprise_supported_services": "Servicios compatibles",
+ "apprise_supported_services_desc": "Apprise admite más de 80 servicios de notificación, incluidos: Discord, Slack, Telegram, correo electrónico (Gmail, Outlook), webhooks, Microsoft Teams, Matrix, Pushover, Ntfy, Gotify y muchos más.",
+ "view_full_list_of_supported_services": "Ver la lista completa de servicios compatibles",
+ "ownership_management": "Gestión de la propiedad",
+ "transfer_ownership": "Transferir propiedad",
+ "warning_title": "Advertencia:",
+ "transfer_ownership_warning": "Transfiera la propiedad de la aplicación a otro usuario administrador. Esta acción es irreversible.",
+ "transfer_ownership_desc": "Una vez que se transfiera la propiedad, se convertirá en un administrador normal y el nuevo propietario tendrá el control final sobre la aplicación.",
+ "select_new_owner": "Seleccionar nuevo propietario (debe ser un administrador)",
+ "select_admin_user": "Seleccionar un usuario administrador...",
+ "transfer_ownership_button": "Transferir propiedad",
+ "transfer_ownership_irreversible": "Esta acción no se puede deshacer.",
+ "transfer_ownership_confirmation": "Está a punto de transferir la propiedad de la aplicación a",
+ "after_this_transfer": "Después de esta transferencia:",
+ "transfer_ownership_consequence_1": "Se convertirá en un administrador normal",
+ "transfer_ownership_consequence_2": "El nuevo propietario tendrá el control final sobre la aplicación",
+ "transfer_ownership_consequence_3": "Solo el nuevo propietario puede volver a transferir la propiedad",
+ "transfer_ownership_type_to_confirm": "Para confirmar, escriba \"TRANSFER\" en el campo a continuación:"
+ },
+ "actions": {
+ "save": "Guardar",
+ "cancel": "Cancelar",
+ "delete": "Eliminar",
+ "edit": "Editar",
+ "export": "Exportar",
+ "import": "Importar",
+ "refresh": "Actualizar",
+ "search": "Buscar",
+ "clear": "Limpiar",
+ "upload": "Subir",
+ "download": "Descargar",
+ "manage_tags": "Gestionar Etiquetas",
+ "close": "Cerrar",
+ "save_changes": "Guardar Cambios"
+ },
+ "filters": {
+ "all_status": "Todos los Estados",
+ "all_tags": "Todas las Etiquetas",
+ "all_vendors": "Todos los Proveedores",
+ "all_types": "Todos los Tipos",
+ "sort_by": "Ordenar por",
+ "sort_expiration": "Fecha de Vencimiento",
+ "sort_purchase": "Fecha de Compra",
+ "sort_age": "Edad",
+ "sort_name": "Nombre del Producto",
+ "sort_vendor": "Proveedor",
+ "sort_warranty_type": "Tipo de Garantía",
+ "status": "Estado",
+ "tags": "Etiquetas",
+ "vendor": "Proveedor",
+ "warranty_type": "Tipo de Garantía",
+ "view": "Vista",
+ "scope": "Alcance"
+ },
+ "messages": {
+ "success": "Éxito",
+ "error": "Error",
+ "warning": "Advertencia",
+ "loading": "Cargando...",
+ "saved": "Cambios guardados exitosamente",
+ "deleted": "Elemento eliminado exitosamente",
+ "confirm_delete": "¿Estás seguro de que quieres eliminar este elemento?",
+ "no_results": "No se encontraron resultados",
+ "file_too_large": "El archivo es demasiado grande",
+ "invalid_file_type": "Tipo de archivo inválido",
+ "fill_first_last_name": "Por favor complete el nombre y apellido",
+ "email_cannot_be_empty": "La dirección de correo electrónico no puede estar vacía.",
+ "enter_valid_email": "Por favor ingrese una dirección de correo electrónico válida.",
+ "profile_updated_successfully": "Perfil actualizado exitosamente",
+ "preferences_saved_successfully": "Preferencias guardadas exitosamente.",
+ "fill_password_fields": "Por favor complete todos los campos de contraseña",
+ "passwords_do_not_match": "Las nuevas contraseñas no coinciden",
+ "password_min_length": "La contraseña debe tener al menos 8 caracteres",
+ "type_delete_to_confirm": "Por favor escriba DELETE para confirmar",
+ "account_deleted_successfully": "Cuenta eliminada exitosamente",
+ "account_cannot_delete_offline": "La cuenta no puede ser eliminada en modo sin conexión",
+ "failed_delete_account": "Error al eliminar la cuenta. Por favor intente nuevamente.",
+ "user_updated_successfully": "Usuario actualizado exitosamente",
+ "user_deleted_successfully": "Usuario eliminado exitosamente",
+ "user_id_missing": "ID de usuario faltante",
+ "failed_load_users": "Error al cargar usuarios",
+ "error_loading_users": "Error al cargar usuarios",
+ "select_user_transfer_ownership": "Por favor seleccione un usuario al cual transferir la propiedad",
+ "ownership_transferred_successfully": "Propiedad transferida exitosamente! Actualizando página...",
+ "failed_load_site_settings": "Error al cargar configuraciones del sitio. Por favor intente nuevamente.",
+ "invalid_email_base_url": "Formato de URL base de correo inválido. Debe comenzar con http:// o https://",
+ "no_site_settings_to_save": "No hay configuraciones de sitio para guardar.",
+ "site_settings_saved_successfully": "Configuraciones del sitio guardadas exitosamente",
+ "failed_save_site_settings": "Error al guardar configuraciones del sitio",
+ "oidc_settings_saved_successfully": "Configuraciones OIDC guardadas exitosamente.",
+ "failed_save_oidc_settings": "Error al guardar configuraciones OIDC.",
+ "api_endpoint_accessible": "El endpoint de API es accesible",
+ "api_endpoint_not_accessible": "El endpoint de API no es accesible. Estado: ",
+ "only_admins_send_notifications": "Solo los administradores pueden enviar notificaciones de garantía",
+ "notifications_triggered_successfully": "Notificaciones activadas exitosamente",
+ "notification_settings_saved_successfully": "Configuraciones de notificación guardadas exitosamente",
+ "apprise_settings_saved_successfully": "Configuraciones de Apprise guardadas exitosamente",
+ "test_notification_sent_successfully": "Notificación de prueba enviada exitosamente",
+ "no_urls_to_validate": "No hay URLs para validar",
+ "paperless_settings_saved_successfully": "¡Configuraciones de Paperless-ngx guardadas exitosamente!",
+ "enter_valid_paperless_url": "Por favor ingrese una URL válida (ej. https://paperless.sudominio.com)",
+ "enter_paperless_url_first": "Por favor ingrese primero una URL de Paperless-ngx",
+ "paperless_connection_test_successful": "¡Prueba de conexión de Paperless-ngx exitosa!",
+ "paperless_connection_test_failed": "Prueba de conexión de Paperless-ngx falló",
+ "enter_api_token_test_connection": "Por favor ingrese un token de API para probar la conexión",
+ "failed_load_user_data": "Error al cargar datos del usuario. Por favor intente nuevamente.",
+ "could_not_connect_user_data": "No se pudo conectar para recuperar datos del usuario. Mostrando información en caché.",
+ "preferences_saved_locally_failed_sync": "Preferencias guardadas localmente, pero falló la sincronización con el servidor: ",
+ "preferences_saved_locally": "Preferencias guardadas localmente.",
+ "correct_errors_in_tab": "Por favor, corrija los errores en la pestaña resaltada antes de continuar.",
+ "please_fill_out_this_field": "Por favor, complete este campo.",
+ "warranty_added_successfully": "Garantía agregada con éxito",
+ "tag_name_required": "El nombre de la etiqueta es requerido",
+ "tag_creation_function_not_found": "Función de creación de etiquetas no encontrada",
+ "tag_created_successfully": "Etiqueta creada con éxito",
+ "tag_updated_successfully": "Etiqueta actualizada con éxito",
+ "tag_deleted_successfully": "Etiqueta eliminada con éxito",
+ "failed_to_create_tag": "Error al crear etiqueta",
+ "failed_to_update_tag": "Error al actualizar etiqueta",
+ "failed_to_delete_tag": "Error al eliminar etiqueta"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية",
+ "ru": "Русский",
+ "uk": "Українська",
+ "zh_CN": "简体中文",
+ "zh_HK": "繁體中文",
+ "ja": "日本語",
+ "pt": "Português",
+ "ko": "한국어"
+ },
+ "status": {
+ "title": "Estado del Sistema",
+ "dashboard_title": "Panel de Estado de Garantías",
+ "global_dashboard_title": "Panel Global de Estado de Garantías",
+ "overview": "Resumen",
+ "statistics": "Estadísticas",
+ "total_warranties": "Total de Garantías",
+ "active_warranties": "Garantías Activas",
+ "expiring_soon": "Expira Pronto",
+ "expired_warranties": "Garantías Expiradas",
+ "warranty_distribution": "Distribución de Garantías",
+ "expiration_timeline": "Cronología de Expiración",
+ "recent_activity": "Actividad Reciente",
+ "recent_expirations": "Recientemente Expiradas o Expirando Pronto",
+ "recent_expirations_empty": "No hay garantías recientemente expiradas o expirando pronto.",
+ "system_health": "Salud del Sistema",
+ "database_status": "Estado de la Base de Datos",
+ "connected": "Conectado",
+ "version": "Versión",
+ "uptime": "Tiempo de Actividad"
+ },
+ "about": {
+ "title": "Acerca de Warracker",
+ "description": "Un sistema completo de gestión de garantías diseñado para ayudarte a rastrear, organizar y gestionar todas las garantías de tus productos en una plataforma segura y fácil de usar.",
+ "version": "Versión",
+ "update_status": "Estado de Actualizaciones",
+ "checking_updates": "Verificando actualizaciones...",
+ "view_release_notes": "Ver Notas de Versión",
+ "project_info": "Información del Proyecto",
+ "project_description": "Warracker es un sistema de gestión de garantías de código abierto construido con tecnologías web modernas. Proporciona una forma segura e intuitiva de gestionar garantías de productos, rastrear fechas de vencimiento y organizar documentos importantes.",
+ "github_repository": "Repositorio GitHub",
+ "releases": "Versiones",
+ "community_support": "Comunidad y Soporte",
+ "community_description": "Únete a nuestra comunidad para soporte, discusiones y actualizaciones. Reporta errores, solicita características u obtén ayuda de otros usuarios y colaboradores.",
+ "discord_community": "Comunidad Discord",
+ "report_issues": "Reportar Problemas",
+ "developer_info": "Información del Desarrollador",
+ "developer_description": "Warracker es desarrollado y mantenido por Sassanix. El proyecto es de código abierto y acepta contribuciones de la comunidad.",
+ "sassanix": "Sassanix",
+ "agpl_license": "Licencia AGPL-3.0",
+ "support_project": "Apoyar el Proyecto",
+ "support_description": "¡Si encuentras Warracker útil, considera apoyar su desarrollo!",
+ "new_version_available": "¡Nueva versión {{version}} disponible!",
+ "latest_version": "Estás usando la última versión",
+ "update_check_failed": "Error al verificar actualizaciones",
+ "features": "Características",
+ "feature_track": "Seguir garantías de productos",
+ "feature_notifications": "Recibir notificaciones de expiración",
+ "feature_documents": "Almacenar documentos de garantía",
+ "feature_reports": "Generar informes de garantía",
+ "feature_tags": "Organizar con etiquetas",
+ "feature_export": "Exportar datos de garantía",
+ "support": "Soporte",
+ "documentation": "Documentación",
+ "github": "Repositorio GitHub",
+ "license": "Licencia",
+ "copyright": "Derechos de Autor",
+ "developed_by": "Desarrollado por"
+ }
+}
diff --git a/locales/fa/translation.json b/locales/fa/translation.json
new file mode 100644
index 0000000..5119918
--- /dev/null
+++ b/locales/fa/translation.json
@@ -0,0 +1,561 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "ردیاب گارانتی",
+ "nav": {
+ "home": "خانه",
+ "status": "وضعیت",
+ "settings": "تنظیمات",
+ "about": "درباره"
+ },
+ "auth": {
+ "login": "ورود",
+ "logout": "خروج",
+ "register": "ثبت نام",
+ "username": "نام کاربری",
+ "password": "رمز عبور",
+ "email": "ایمیل",
+ "first_name": "نام",
+ "last_name": "نام خانوادگی",
+ "forgot_password": "فراموشی رمز عبور؟",
+ "reset_password": "بازنشانی رمز عبور",
+ "confirm_password": "تأیید رمز عبور",
+ "create_account_title": "ایجاد حساب کاربری",
+ "first_name_optional": "نام (اختیاری)",
+ "last_name_optional": "نام خانوادگی (اختیاری)",
+ "username_hint": "نام کاربری باید منحصر به فرد باشد و برای ورود استفاده خواهد شد.",
+ "email_address": "آدرس ایمیل",
+ "toggle_password": "نمایش/پنهان کردن رمز عبور",
+ "password_hint_simple": "رمز عبور باید حداقل 8 کاراکتر داشته باشد و شامل حروف بزرگ، حروف کوچک و اعداد باشد.",
+ "password_requirements": "الزامات رمز عبور:",
+ "req_length": "حداقل 8 کاراکتر",
+ "req_uppercase": "حداقل 1 حرف بزرگ",
+ "req_lowercase": "حداقل 1 حرف کوچک",
+ "req_number": "حداقل 1 عدد",
+ "req_special": "حداقل 1 کاراکتر خاص",
+ "create_account": "ایجاد حساب",
+ "already_have_account": "قبلاً حساب کاربری ساخته‌اید؟",
+ "reset_password_title": "Warracker - بازنشانی رمز عبور",
+ "reset_your_password": "رمز عبور خود را بازنشانی کنید",
+ "reset_password_info": "آدرس ایمیل خود را در زیر وارد کنید تا لینک بازنشانی رمز عبور را برای شما ارسال کنیم.",
+ "send_reset_link": "ارسال لینک بازنشانی",
+ "back_to_login": "بازگشت به صفحه ورود",
+ "set_new_password_title": "Warracker - تنظیم رمز عبور جدید",
+ "set_new_password": "تنظیم رمز عبور جدید",
+ "new_password": "رمز عبور جدید",
+ "confirm_new_password": "تأیید رمز عبور جدید",
+ "invalid_or_expired_link": "لینک نامعتبر یا منقضی شده",
+ "invalid_link_info": "لینک بازنشانی رمز عبوری که کلیک کرده‌اید نامعتبر یا منقضی شده است.",
+ "request_new_reset_link": "درخواست لینک بازنشانی جدید"
+ },
+ "warranties": {
+ "title": "گارانتی‌های شما",
+ "title_global": "گارانتی‌های همه کاربران",
+ "add_new": "افزودن گارانتی جدید",
+ "edit": "ویرایش گارانتی",
+ "delete": "حذف گارانتی",
+ "product_name": "نام محصول",
+ "purchase_date": "تاریخ خرید",
+ "warranty_duration": "مدت گارانتی",
+ "years": "سال",
+ "months": "ماه",
+ "days": "روز",
+ "vendor": "فروشنده",
+ "serial_numbers": "شماره سریال‌ها",
+ "purchase_price": "قیمت خرید",
+ "notes": "یادداشت‌ها",
+ "tags": "برچسب‌ها",
+ "status": "وضعیت",
+ "expiration_date": "تاریخ انقضا",
+ "active": "فعال",
+ "expired": "منقضی شده",
+ "expiring_soon": "به زودی منقضی می‌شود",
+ "lifetime": "مادام‌العمر",
+ "no_warranties": "هنوز هیچ گارانتی وجود ندارد. برای شروع اولین گارانتی خود را اضافه کنید.",
+ "search_placeholder": "جستجو بر اساس نام، فروشندگان، یادداشت‌ها، برچسب یا شماره سریال...",
+ "warranty_type": "نوع گارانتی",
+ "other_document": "سند دیگر",
+ "product": "محصول",
+ "expiration": "انقضا",
+ "actions": "اقدامات",
+ "no_warranties_title": "هنوز هیچ گارانتی وجود ندارد",
+ "no_warranties_desc": "اولین گارانتی خود را اضافه کنید تا شروع کنید",
+ "add_warranty": "افزودن گارانتی",
+ "warranty_entry_method": "روش ورود گارانتی",
+ "warranty_duration_option": "مدت گارانتی",
+ "exact_expiration_option": "تاریخ انقضای دقیق",
+ "warranty_period": "دوره گارانتی",
+ "expiration_date_label": "تاریخ انقضا",
+ "currency": "ارز",
+ "add_tags": "افزودن برچسب",
+ "add_tags_desc": "برچسب‌ها به شما کمک می‌کنند تا گارانتی‌های خود را سازماندهی و فیلتر کنید",
+ "save_changes": "ذخیره تغییرات",
+ "confirm_delete": "تأیید حذف",
+ "manage_tags": "مدیریت برچسب‌ها",
+ "add_tag": "افزودن برچسب",
+ "unknown_status": "وضعیت نامشخص",
+ "expiring_soon_days": "به زودی منقضی می‌شود ({{days}} {{dayText}})",
+ "days_remaining": "{{days}} {{dayText}} باقی مانده",
+ "day_one": "روز",
+ "day_other": "روز",
+ "month_one": "ماه",
+ "month_other": "ماه",
+ "year_one": "سال",
+ "year_other": "سال",
+ "na": "N/A",
+ "age": "سن",
+ "warranty": "گارانتی",
+ "warranty_ends": "پایان گارانتی",
+ "price": "قیمت",
+ "serial_number": "شماره سریال",
+ "type": "نوع",
+ "owner": "مالک",
+ "product_website": "وب‌سایت محصول",
+ "documents": "اسناد",
+ "summary": "خلاصه",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "سال",
+ "months_placeholder": "ماه",
+ "days_placeholder": "روز",
+ "add_any_notes_placeholder": "یادداشت‌هایی درباره این گارانتی اضافه کنید...",
+
+ "product_url_optional": "URL محصول (اختیاری)",
+ "enter_serial_number": "شماره سریال را وارد کنید",
+ "vendor_optional": "فروشنده (اختیاری)",
+ "vendor_placeholder": "مثلاً آمازون، بست بای و غیره",
+ "lifetime_warranty": "گارانتی مادام‌العمر",
+ "warranty_type_optional": "نوع گارانتی (اختیاری)",
+ "select_warranty_type": "نوع گارانتی را انتخاب کنید...",
+ "standard": "استاندارد",
+ "extended": "تمدید شده",
+ "manufacturer": "سازنده",
+ "third_party": "شخص ثالث",
+ "store": "فروشگاه",
+ "premium": "پریمیوم",
+ "limited": "محدود",
+ "full": "کامل",
+ "parts_only": "فقط قطعات",
+ "labor_only": "فقط نیروی کار",
+ "international": "بین‌المللی",
+ "accidental_damage": "آسیب تصادفی",
+ "other_custom": "سایر (سفارشی)",
+ "enter_custom_warranty_type": "نوع گارانتی سفارشی را وارد کنید",
+ "purchase_price_optional": "قیمت خرید (اختیاری)",
+ "notes_optional": "یادداشت‌ها (اختیاری)",
+ "add_any_notes": "هرگونه یادداشتی در مورد این گارانتی اضافه کنید...",
+ "product_photo_optional": "عکس محصول (اختیاری)",
+ "choose_photo": "انتخاب عکس",
+ "invoice_receipt": "فاکتور/رسید",
+ "store_locally": "ذخیره محلی",
+ "store_in_paperless": "ذخیره در Paperless-ngx",
+ "choose_file": "انتخاب فایل",
+ "browse_paperless": "مرور اسناد Paperless-ngx",
+ "product_manual_optional": "دفترچه راهنمای محصول (اختیاری)",
+ "files_zip_rar_optional": "فایل‌ها (ZIP/RAR، اختیاری)",
+ "search_or_add_new_tag": "جستجو یا افزودن برچسب جدید...",
+ "product_information": "اطلاعات محصول",
+ "product_url": "URL محصول",
+ "warranty_details": "جزئیات گارانتی",
+ "product_photo": "عکس محصول",
+ "product_manual": "دفترچه راهنمای محصول",
+ "files": "فایل‌ها",
+ "selected_tags": "برچسب‌های انتخاب شده",
+ "previous_tab": "قبلی",
+ "next_tab": "بعدی",
+ "delete_photo": "حذف عکس",
+ "delete_invoice": "حذف فاکتور",
+ "delete_manual": "حذف دفترچه راهنما",
+ "delete_files": "حذف فایل‌ها",
+ "current_photo": "عکس فعلی:",
+ "current_invoice": "فاکتور فعلی:",
+ "current_manual": "دفترچه راهنمای فعلی:",
+ "current_document": "سند فعلی:",
+ "upload_new_photo_replace": "(برای جایگزینی عکس جدید آپلود کنید)",
+ "no_photo_uploaded": "هیچ عکسی آپلود نشده است",
+ "no_invoice_uploaded": "هیچ فاکتوری آپلود نشده است",
+ "no_manual_uploaded": "هیچ دفترچه راهنمایی آپلود نشده است",
+ "no_document_uploaded": "هیچ سند دیگری آپلود نشده است",
+ "photo_will_be_deleted": "عکس هنگام ذخیره حذف خواهد شد",
+ "invoice_will_be_deleted": "فاکتور هنگام ذخیره حذف خواهد شد",
+ "manual_will_be_deleted": "دفترچه راهنما هنگام ذخیره حذف خواهد شد",
+ "document_will_be_deleted": "سند دیگر هنگام ذخیره حذف خواهد شد",
+ "confirm_delete_message": "آیا از حذف این گارانتی مطمئن هستید؟ این عمل قابل بازگشت نیست.",
+ "new_tag_name": "نام برچسب جدید",
+ "existing_tags": "برچسب‌های موجود",
+ "edit_warranty": "ویرایش گارانتی",
+ "warranty_type_standard": "استاندارد",
+ "warranty_type_extended": "تمدید شده",
+ "warranty_type_manufacturer": "سازنده",
+ "warranty_type_third_party": "شخص ثالث",
+ "warranty_type_store": "فروشگاه",
+ "warranty_type_premium": "پریمیوم",
+ "warranty_type_limited": "محدود",
+ "warranty_type_full": "کامل",
+ "warranty_type_parts_only": "فقط قطعات",
+ "warranty_type_labor_only": "فقط نیروی کار",
+ "warranty_type_international": "بین‌المللی",
+ "warranty_type_accidental_damage": "آسیب تصادفی",
+ "warranty_type_other": "سایر (سفارشی)",
+ "warranty_type_custom_placeholder": "نوع گارانتی سفارشی را وارد کنید",
+ "notes_placeholder": "یادداشت‌های اضافی درباره این گارانتی...",
+ "tags_help_text": "برچسب‌ها به شما کمک می‌کنند گارانتی‌هایتان را سازماندهی و فیلتر کنید",
+ "search_add_tag_placeholder": "جستجو یا افزودن برچسب جدید...",
+ "upload_new_file_replace": "فایل جدید برای جایگزینی آپلود کنید",
+ "current_other_document": "سند دیگر فعلی",
+ "no_other_document_uploaded": "هیچ سند دیگری آپلود نشده است",
+ "other_document_will_be_deleted": "سند دیگر هنگام ذخیره حذف خواهد شد",
+ "files_optional": "فایل‌ها (ZIP/RAR، اختیاری)",
+ "invoice_receipt_short": "فاکتور",
+ "product_manual_short": "دفترچه راهنما",
+ "files_short": "فایل‌ها",
+ "enter_serial_number": "شماره سریال را وارد کنید",
+ "add_serial_number": "شماره سریال دیگری اضافه کنید"
+ },
+ "settings": {
+ "title": "تنظیمات",
+ "account_settings": "تنظیمات حساب کاربری",
+ "preferences": "ترجیحات",
+ "language": "زبان",
+ "select_language": "زبان را انتخاب کنید",
+ "dark_mode": "حالت تاریک",
+ "dark_mode_desc": "تغییر بین تم روشن و تاریک",
+ "currency": "ارز",
+ "timezone": "منطقه زمانی",
+ "date_format": "فرمت تاریخ",
+ "expiring_soon_days": "روزهای نزدیک به انقضا",
+ "save_changes": "ذخیره تغییرات",
+ "current_user": "در حال ویرایش پروفایل برای:",
+ "your_email": "ایمیل شما:",
+ "first_name": "نام",
+ "last_name": "نام خانوادگی",
+ "email": "ایمیل",
+ "save_profile": "ذخیره تغییرات",
+ "default_view": "نمای پیش‌فرض",
+ "default_view_desc": "نمای مورد نظر خود را برای گارانتی‌ها انتخاب کنید",
+ "grid_view": "نمای شبکه‌ای",
+ "list_view": "نمای لیستی",
+ "table_view": "نمای جدولی",
+ "currency_symbol": "نماد ارز",
+ "currency_symbol_desc": "نماد نمایش قیمت‌ها را انتخاب کنید",
+ "currency_position": "موقعیت ارز",
+ "currency_position_desc": "انتخاب کنید که نماد ارز در سمت چپ یا راست اعداد نمایش داده شود",
+ "expiring_soon_days_desc": "تعداد روزهای قبل از انقضا برای نمایش هشدارها",
+ "date_format_desc": "نحوه نمایش تاریخ‌ها را انتخاب کنید",
+ "save_preferences": "ذخیره ترجیحات",
+ "notification_settings": "تنظیمات اعلان",
+ "notification_channel": "کانال اعلان",
+ "notification_channel_desc": "نحوه دریافت اعلان‌ها را انتخاب کنید",
+ "notification_disabled": "غیرفعال",
+ "notification_email": "ایمیل",
+ "notification_apprise": "Apprise",
+ "notification_both": "هر دو",
+ "email_settings": "تنظیمات ایمیل",
+ "notification_frequency": "فرکانس اعلان",
+ "notification_frequency_desc": "هر چند وقت یکبار اعلان‌های ایمیل را دریافت کنید",
+ "daily": "روزانه",
+ "weekly": "هفتگی",
+ "monthly": "ماهانه",
+ "notification_time": "زمان اعلان",
+ "timezone_desc": "منطقه زمانی محلی شما برای اعلان‌ها",
+ "apprise_settings": "تنظیمات Apprise",
+ "apprise_frequency": "فرکانس اعلان Apprise",
+ "apprise_frequency_desc": "هر چند وقت یکبار اعلان‌های Apprise را دریافت کنید",
+ "apprise_time": "زمان اعلان Apprise",
+ "apprise_timezone": "منطقه زمانی Apprise",
+ "apprise_timezone_desc": "منطقه زمانی محلی شما برای اعلان‌های Apprise",
+ "save_notification_settings": "ذخیره تنظیمات اعلان",
+ "security": "امنیت",
+ "change_password": "تغییر رمز عبور",
+ "change_password_desc": "رمز عبور حساب خود را به‌روز کنید",
+ "change": "تغییر",
+ "current_password": "رمز عبور فعلی",
+ "new_password": "رمز عبور جدید",
+ "confirm_password": "تأیید رمز عبور جدید",
+ "update_password": "به‌روزرسانی رمز عبور",
+ "cancel": "لغو",
+ "danger_zone": "منطقه خطر",
+ "delete_account": "حذف حساب",
+ "delete_account_desc": "حساب و تمام داده‌های خود را برای همیشه حذف کنید",
+ "admin_settings": "تنظیمات مدیر",
+ "admin_actions": "اقدامات مدیر",
+ "refresh_data": "تازه‌سازی داده‌ها",
+ "check_admin_status": "بررسی وضعیت مدیر",
+ "show_users_list": "نمایش لیست کاربران",
+ "test_api": "تست API",
+ "send_notifications": "ارسال اعلان‌های گارانتی",
+ "check_scheduler": "بررسی وضعیت زمان‌بندی",
+ "site_settings": "تنظیمات سایت",
+ "registration_enabled": "ثبت‌نام فعال است",
+ "registration_enabled_desc": "به کاربران جدید اجازه ثبت‌نام دهید",
+ "email_base_url": "URL پایه ایمیل",
+ "global_view_enabled": "نمای جهانی فعال است",
+ "global_view_admin_only": "نمای جهانی فقط برای مدیران",
+ "save_site_settings": "ذخیره تنظیمات سایت",
+ "oidc_configuration": "پیکربندی OIDC SSO",
+ "enable_oidc": "فعال کردن OIDC SSO",
+ "oidc_provider_name": "نام ارائه‌دهنده OIDC",
+ "client_id": "شناسه مشتری",
+ "client_secret": "راز مشتری",
+ "issuer_url": "URL صادرکننده",
+ "scope": "محدوده",
+ "save_oidc_settings": "ذخیره تنظیمات OIDC",
+ "oidc_sso_desc": "به کاربران اجازه دهید از طریق ارائه‌دهنده OIDC وارد شوند.",
+ "oidc_only_mode": "حالت ورود فقط با OIDC",
+ "oidc_only_mode_desc": "فرم ورود سنتی با نام کاربری/رمز عبور را پنهان کنید و فقط اجازه ورود با OIDC را بدهید. <strong>هشدار:</strong> قبل از فعال کردن این گزینه، از پیکربندی صحیح OIDC اطمینان حاصل کنید.",
+ "oidc_provider_name_desc": "نام داخلی برای مشتری OIDC (مثلاً 'oidc').",
+ "client_secret_desc": "مقدار حساس. در پایگاه داده ذخیره شده است. برای اعمال تغییرات، راه‌اندازی مجدد برنامه لازم است.",
+ "issuer_url_desc": "URL پایه ارائه‌دهنده OIDC شما.",
+ "scope_desc": "محدوده‌های OIDC با فاصله از هم جدا شده‌اند.",
+ "oidc_restart_message": "برای اعمال کامل تنظیمات OIDC، راه‌اندازی مجدد برنامه لازم است.",
+ "api_token": "توکن API",
+ "view_documents": "مشاهده اسناد در Warracker",
+ "connection_testing": "تست اتصال",
+ "apprise_notifications": "اعلان‌های Apprise",
+ "enable_apprise": "فعال کردن اعلان‌های Apprise",
+ "loading": "در حال بارگذاری...",
+ "time_of_day_notification": "زمان دریافت اعلان‌ها (در قالب 24 ساعته)",
+ "paperless_ngx_settings": "تنظیمات Paperless-ngx",
+ "paperless_ngx_about_title": "درباره ادغام Paperless-ngx:",
+ "paperless_ngx_about_desc": "این ویژگی اختیاری به شما امکان می‌دهد اسناد گارانتی را به جای ذخیره محلی، در نمونه Paperless-ngx خود میزبان ذخیره کنید. در صورت فعال بودن، کاربران می‌توانند انتخاب کنند که هر سند را کجا ذخیره کنند: محلی یا در Paperless-ngx.",
+ "paperless_ngx_desc": "پیکربندی ادغام با سیستم مدیریت اسناد Paperless-ngx",
+ "enable_paperless": "فعال کردن ادغام Paperless-ngx",
+ "paperless_url": "URL Paperless-ngx",
+ "paperless_url_desc": "URL پایه نمونه Paperless-ngx شما",
+ "paperless_token": "توکن API",
+ "paperless_token_desc": "توکن احراز هویت API Paperless-ngx شما",
+ "paperless_token_desc_generate": "یک توکن API از نمونه Paperless-ngx خود ایجاد کنید (تنظیمات → توکن‌های API).",
+ "paperless_view_in_app": "مشاهده اسناد در برنامه",
+ "paperless_view_in_app_desc": "اسناد را به جای برگه جدید، در داخل برنامه باز کنید",
+ "debug_config": "پیکربندی اشکال‌زدایی",
+ "test_upload": "تست آپلود",
+ "save_paperless_settings": "ذخیره تنظیمات Paperless-ngx",
+ "apprise_desc": "پیکربندی Apprise برای تحویل اعلان پیشرفته به چندین سرویس",
+ "apprise_desc_system_wide": "فعال یا غیرفعال کردن اعلان‌های Apprise در سطح سیستم",
+ "apprise_not_available_title": "Apprise در دسترس نیست:",
+ "apprise_not_available_desc": "کتابخانه اعلان Apprise نصب نشده یا در دسترس نیست. ویژگی‌های اعلان غیرفعال هستند.",
+ "apprise_url": "URL Apprise",
+ "apprise_url_desc": "URL سرویس اعلان Apprise شما",
+ "apprise_mode": "حالت اعلان",
+ "apprise_mode_desc": "انتخاب کنید چه زمانی اعلان‌های Apprise ارسال شوند",
+ "apprise_mode_global": "خلاصه جهانی",
+ "apprise_mode_individual": "برای هر کاربر",
+ "test_paperless": "تست اتصال Paperless",
+ "test_apprise": "تست اتصال Apprise",
+ "apprise_warranty_scope": "محدوده گارانتی",
+ "apprise_warranty_scope_desc": "انتخاب کنید کدام گارانتی‌ها در اعلان‌ها گنجانده شوند",
+ "all_warranties": "همه گارانتی‌ها",
+ "personal_warranties": "فقط گارانتی‌های شخصی",
+ "all_users_warranties": "گارانتی‌های همه کاربران",
+ "admin_warranties_only": "فقط گارانتی‌های مدیر",
+ "apprise_notification_days": "روزهای اعلان",
+ "apprise_notification_days_desc": "روزهای قبل از انقضا برای ارسال اعلان‌ها (با کاما از هم جدا شده، به عنوان مثال، \"7,30\" برای 7 روز و 30 روز قبل)",
+ "apprise_check_frequency": "فرکانس بررسی",
+ "apprise_check_frequency_desc": "سیستم هر چند وقت یکبار گارانتی‌های در حال انقضا را بررسی می‌کند (تنظیم جهانی)",
+ "apprise_title_prefix": "پیشوند عنوان پیام",
+ "apprise_title_prefix_desc": "پیشوند اضافه شده به عناوین اعلان (به عنوان مثال، \"[Warracker]\" منجر به \"[Warracker] گارانتی‌ها به زودی منقضی می‌شوند\")",
+ "apprise_test_url": "URL تست (اختیاری)",
+ "apprise_test_url_desc": "اختیاری: URL فقط برای ارسال اعلان‌های تست (در پیکربندی اصلی ذخیره نخواهد شد)",
+ "save_apprise_settings": "ذخیره تنظیمات Apprise",
+ "validate_urls": "اعتبارسنجی URLها",
+ "send_expiration_notifications_now": "اکنون اعلان‌های انقضا را ارسال کنید",
+ "apprise_current_status": "وضعیت فعلی",
+ "apprise_urls_configured": "URLهای پیکربندی شده:",
+ "apprise_supported_services": "سرویس‌های پشتیبانی شده",
+ "apprise_supported_services_desc": "Apprise از بیش از 80 سرویس اعلان پشتیبانی می‌کند، از جمله: Discord، Slack، Telegram، ایمیل (Gmail، Outlook)، Webhooks، Microsoft Teams، Matrix، Pushover، Ntfy، Gotify و بسیاری دیگر.",
+ "view_full_list_of_supported_services": "مشاهده لیست کامل سرویس‌های پشتیبانی شده",
+ "ownership_management": "مدیریت مالکیت",
+ "transfer_ownership": "انتقال مالکیت",
+ "warning_title": "هشدار:",
+ "transfer_ownership_warning": "مالکیت برنامه را به کاربر مدیر دیگری منتقل کنید. این عمل غیرقابل بازگشت است.",
+ "transfer_ownership_desc": "پس از انتقال مالکیت، شما به یک مدیر عادی تبدیل خواهید شد و مالک جدید کنترل نهایی برنامه را خواهد داشت.",
+ "select_new_owner": "مالک جدید را انتخاب کنید (باید مدیر باشد)",
+ "select_admin_user": "یک کاربر مدیر را انتخاب کنید...",
+ "transfer_ownership_button": "انتقال مالکیت",
+ "transfer_ownership_irreversible": "این عمل قابل بازگشت نیست.",
+ "transfer_ownership_confirmation": "شما در حال انتقال مالکیت برنامه به",
+ "after_this_transfer": "پس از این انتقال:",
+ "transfer_ownership_consequence_1": "شما به یک مدیر عادی تبدیل خواهید شد",
+ "transfer_ownership_consequence_2": "مالک جدید کنترل نهایی برنامه را خواهد داشت",
+ "transfer_ownership_consequence_3": "فقط مالک جدید می‌تواند دوباره مالکیت را منتقل کند",
+ "transfer_ownership_type_to_confirm": "برای تأیید، لطفاً \"TRANSFER\" را در قسمت زیر تایپ کنید:"
+ },
+ "actions": {
+ "save": "ذخیره",
+ "cancel": "لغو",
+ "delete": "حذف",
+ "edit": "ویرایش",
+ "export": "صادرات",
+ "import": "واردات",
+ "refresh": "بازخوانی",
+ "search": "جستجو",
+ "clear": "پاک کردن",
+ "upload": "آپلود",
+ "download": "دانلود",
+ "manage_tags": "مدیریت برچسب‌ها",
+ "close": "بستن",
+ "save_changes": "ذخیره تغییرات"
+ },
+ "filters": {
+ "all_status": "همه وضعیت‌ها",
+ "all_tags": "همه برچسب‌ها",
+ "all_vendors": "همه فروشندگان",
+ "all_types": "همه انواع",
+ "sort_by": "مرتب‌سازی بر اساس",
+ "sort_expiration": "تاریخ انقضا",
+ "sort_purchase": "تاریخ خرید",
+ "sort_age": "سن",
+ "sort_name": "نام محصول",
+ "sort_vendor": "فروشنده",
+ "sort_warranty_type": "نوع گارانتی",
+ "status": "وضعیت",
+ "tags": "برچسب‌ها",
+ "vendor": "فروشنده",
+ "warranty_type": "نوع گارانتی",
+ "view": "نما",
+ "scope": "محدوده"
+ },
+ "messages": {
+ "success": "موفقیت",
+ "error": "خطا",
+ "warning": "هشدار",
+ "loading": "در حال بارگذاری...",
+ "saved": "تغییرات با موفقیت ذخیره شد",
+ "deleted": "مورد با موفقیت حذف شد",
+ "confirm_delete": "آیا از حذف این مورد اطمینان دارید؟",
+ "no_results": "هیچ نتیجه‌ای یافت نشد",
+ "file_too_large": "فایل بیش از حد بزرگ است",
+ "invalid_file_type": "نوع فایل نامعتبر است",
+ "fill_first_last_name": "لطفاً نام و نام خانوادگی را پر کنید",
+ "email_cannot_be_empty": "آدرس ایمیل نمی‌تواند خالی باشد.",
+ "enter_valid_email": "لطفاً آدرس ایمیل معتبر وارد کنید.",
+ "profile_updated_successfully": "پروفایل با موفقیت به‌روزرسانی شد",
+ "preferences_saved_successfully": "تنظیمات با موفقیت ذخیره شد.",
+ "fill_password_fields": "لطفاً همه فیلدهای رمز عبور را پر کنید",
+ "passwords_do_not_match": "رمزهای عبور جدید مطابقت ندارند",
+ "password_min_length": "رمز عبور باید حداقل ۸ کاراکتر باشد",
+ "type_delete_to_confirm": "لطفاً DELETE را تایپ کنید تا تأیید شود",
+ "account_deleted_successfully": "حساب کاربری با موفقیت حذف شد",
+ "account_cannot_delete_offline": "حساب کاربری در حالت آفلاین قابل حذف نیست",
+ "failed_delete_account": "حذف حساب کاربری ناموفق بود. دوباره تلاش کنید.",
+ "user_updated_successfully": "کاربر با موفقیت به‌روزرسانی شد",
+ "user_deleted_successfully": "کاربر با موفقیت حذف شد",
+ "user_id_missing": "شناسه کاربر موجود نیست",
+ "failed_load_users": "بارگذاری کاربران ناموفق بود",
+ "error_loading_users": "خطا در بارگذاری کاربران",
+ "select_user_transfer_ownership": "لطفاً کاربری را برای انتقال مالکیت انتخاب کنید",
+ "ownership_transferred_successfully": "مالکیت با موفقیت منتقل شد! در حال بازخوانی صفحه...",
+ "failed_load_site_settings": "بارگذاری تنظیمات سایت ناموفق بود. دوباره تلاش کنید.",
+ "invalid_email_base_url": "فرمت URL پایه ایمیل نامعتبر است. باید با http:// یا https:// شروع شود",
+ "no_site_settings_to_save": "تنظیمات سایتی برای ذخیره وجود ندارد.",
+ "site_settings_saved_successfully": "تنظیمات سایت با موفقیت ذخیره شد",
+ "failed_save_site_settings": "ذخیره تنظیمات سایت ناموفق بود",
+ "oidc_settings_saved_successfully": "تنظیمات OIDC با موفقیت ذخیره شد.",
+ "failed_save_oidc_settings": "ذخیره تنظیمات OIDC ناموفق بود.",
+ "api_endpoint_accessible": "نقطه پایانی API قابل دسترس است",
+ "api_endpoint_not_accessible": "نقطه پایانی API قابل دسترس نیست. وضعیت: ",
+ "only_admins_send_notifications": "فقط مدیران می‌توانند اعلان‌های گارانتی ارسال کنند",
+ "notifications_triggered_successfully": "اعلان‌ها با موفقیت فعال شد",
+ "notification_settings_saved_successfully": "تنظیمات اعلان با موفقیت ذخیره شد",
+ "apprise_settings_saved_successfully": "تنظیمات Apprise با موفقیت ذخیره شد",
+ "test_notification_sent_successfully": "اعلان آزمایشی با موفقیت ارسال شد",
+ "no_urls_to_validate": "URL برای اعتبارسنجی وجود ندارد",
+ "paperless_settings_saved_successfully": "تنظیمات Paperless-ngx با موفقیت ذخیره شد!",
+ "enter_valid_paperless_url": "لطفاً URL معتبر وارد کنید (مثال: https://paperless.yourdomain.com)",
+ "enter_paperless_url_first": "لطفاً ابتدا URL Paperless-ngx وارد کنید",
+ "paperless_connection_test_successful": "آزمایش اتصال Paperless-ngx موفق بود!",
+ "paperless_connection_test_failed": "آزمایش اتصال Paperless-ngx ناموفق بود",
+ "enter_api_token_test_connection": "لطفاً یک توکن API برای آزمایش اتصال وارد کنید",
+ "failed_load_user_data": "بارگذاری داده‌های کاربر ناموفق بود. دوباره تلاش کنید.",
+ "could_not_connect_user_data": "اتصال برای دریافت داده‌های کاربر ممکن نیست. نمایش اطلاعات حافظه موقت.",
+ "preferences_saved_locally_failed_sync": "تنظیمات محلی ذخیره شد، اما همگام‌سازی با سرور ناموفق بود: ",
+ "preferences_saved_locally": "تنظیمات محلی ذخیره شد.",
+ "correct_errors_in_tab": "لطفاً خطاهای موجود در تب برجسته شده را قبل از ادامه تصحیح کنید.",
+ "please_fill_out_this_field": "لطفاً این فیلد را پر کنید.",
+ "warranty_added_successfully": "گارانتی با موفقیت اضافه شد",
+ "tag_name_required": "نام برچسب الزامی است",
+ "tag_creation_function_not_found": "تابع ایجاد برچسب پیدا نشد",
+ "tag_created_successfully": "برچسب با موفقیت ایجاد شد",
+ "tag_updated_successfully": "برچسب با موفقیت به‌روزرسانی شد",
+ "tag_deleted_successfully": "برچسب با موفقیت حذف شد",
+ "failed_to_create_tag": "ایجاد برچسب ناموفق بود",
+ "failed_to_update_tag": "به‌روزرسانی برچسب ناموفق بود",
+ "failed_to_delete_tag": "حذف برچسب ناموفق بود"
+ },
+ "languages": {
+ "en": "انگلیسی",
+ "fr": "فرانسوی",
+ "es": "اسپانیایی",
+ "de": "آلمانی",
+ "it": "ایتالیایی",
+ "cs": "چکی",
+ "nl": "هلندی",
+ "hi": "هندی",
+ "fa": "فارسی",
+ "ar": "عربی",
+ "ru": "روسی",
+ "uk": "اوکراینی",
+ "zh_CN": "چینی ساده شده",
+ "zh_HK": "چینی سنتی",
+ "ja": "ژاپنی",
+ "pt": "پرتغالی",
+ "ko": "کره‌ای"
+ },
+ "status": {
+ "title": "وضعیت سیستم",
+ "dashboard_title": "داشبورد وضعیت گارانتی",
+ "global_dashboard_title": "داشبورد جهانی وضعیت گارانتی",
+ "overview": "نمای کلی",
+ "statistics": "آمار",
+ "total_warranties": "کل گارانتی‌ها",
+ "active_warranties": "گارانتی‌های فعال",
+ "expiring_soon": "به زودی منقضی می‌شود",
+ "expired_warranties": "گارانتی‌های منقضی شده",
+ "warranty_distribution": "توزیع گارانتی",
+ "expiration_timeline": "جدول زمانی انقضا",
+ "recent_activity": "فعالیت‌های اخیر",
+ "recent_expirations": "اخیراً منقضی شده یا به زودی منقضی می‌شود",
+ "recent_expirations_empty": "هیچ گارانتی اخیراً منقضی شده یا به زودی منقضی نمی‌شود.",
+ "system_health": "سلامت سیستم",
+ "database_status": "وضعیت پایگاه داده",
+ "connected": "متصل",
+ "version": "نسخه",
+ "uptime": "مدت فعالیت"
+ },
+ "about": {
+ "title": "درباره Warracker",
+ "description": "یک سیستم جامع مدیریت گارانتی که برای کمک به شما در ردیابی، سازماندهی و مدیریت تمام گارانتی‌های محصول خود در یک پلتفرم امن و کاربرپسند طراحی شده است.",
+ "version": "نسخه",
+ "update_status": "وضعیت به‌روزرسانی",
+ "checking_updates": "در حال بررسی برای به‌روزرسانی‌ها...",
+ "view_release_notes": "مشاهده یادداشت‌های انتشار",
+ "project_info": "اطلاعات پروژه",
+ "project_description": "Warracker یک سیستم مدیریت گارانتی منبع باز است که با فناوری‌های وب مدرن ساخته شده است. این یک روش امن و بصری برای مدیریت گارانتی‌های محصول، ردیابی تاریخ‌های انقضا و سازماندهی اسناد مهم فراهم می‌کند.",
+ "github_repository": "مخزن GitHub",
+ "releases": "انتشارها",
+ "community_support": "جامعه و پشتیبانی",
+ "community_description": "برای پشتیبانی، بحث و به‌روزرسانی به جامعه ما بپیوندید. اشکالات را گزارش دهید، ویژگی‌ها را درخواست کنید یا از سایر کاربران و مشارکت‌کنندگان کمک بگیرید.",
+ "discord_community": "جامعه دیسکورد",
+ "report_issues": "گزارش مشکلات",
+ "developer_info": "اطلاعات توسعه‌دهنده",
+ "developer_description": "Warracker توسط Sassanix توسعه و نگهداری می‌شود. این پروژه منبع باز است و از مشارکت‌های جامعه استقبال می‌کند.",
+ "sassanix": "Sassanix",
+ "agpl_license": "مجوز AGPL-3.0",
+ "support_project": "حمایت از پروژه",
+ "support_description": "اگر Warracker را مفید می‌دانید، حمایت از توسعه آن را در نظر بگیرید!",
+ "new_version_available": "نسخه جدید {{version}} در دسترس است!",
+ "latest_version": "شما از آخرین نسخه استفاده می‌کنید",
+ "update_check_failed": "بررسی برای به‌روزرسانی‌ها ناموفق بود",
+ "features": "ویژگی‌ها",
+ "feature_track": "ردیابی گارانتی‌های محصول",
+ "feature_notifications": "دریافت اعلان‌های انقضا",
+ "feature_documents": "ذخیره اسناد گارانتی",
+ "feature_reports": "تولید گزارش‌های گارانتی",
+ "feature_tags": "سازماندهی با برچسب‌ها",
+ "feature_export": "صادرات داده‌های گارانتی",
+ "support": "پشتیبانی",
+ "documentation": "مستندات",
+ "github": "مخزن GitHub",
+ "license": "مجوز",
+ "copyright": "حق نشر",
+ "developed_by": "توسعه یافته توسط"
+ }
+}
\ No newline at end of file
diff --git a/locales/fr/LC_MESSAGES/messages.mo b/locales/fr/LC_MESSAGES/messages.mo
new file mode 100644
index 0000000..e3e4851
Binary files /dev/null and b/locales/fr/LC_MESSAGES/messages.mo differ
diff --git a/locales/fr/LC_MESSAGES/messages.po b/locales/fr/LC_MESSAGES/messages.po
new file mode 100644
index 0000000..59f26ec
--- /dev/null
+++ b/locales/fr/LC_MESSAGES/messages.po
@@ -0,0 +1,180 @@
+# French translations for Warracker
+# Copyright (C) 2024 Warracker
+# This file is distributed under the same license as the Warracker project.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: Warracker 1.0\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2025-06-29 12:36-0300\n"
+"PO-Revision-Date: 2024-01-01 12:00+0000\n"
+"Last-Translator: \n"
+"Language: fr\n"
+"Language-Team: French\n"
+"Plural-Forms: nplurals=2; plural=(n > 1);\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=utf-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Generated-By: Babel 2.17.0\n"
+
+# Error messages
+#: backend/localization.py:177
+msgid "Validation error"
+msgstr "Erreur de validation"
+
+#: backend/localization.py:178
+msgid "Authentication error"
+msgstr "Erreur d'authentification"
+
+#: backend/localization.py:179
+msgid "Authorization error"
+msgstr "Erreur d'autorisation"
+
+#: backend/localization.py:180
+msgid "Resource not found"
+msgstr "Ressource introuvable"
+
+#: backend/localization.py:181
+msgid "Internal server error"
+msgstr "Erreur interne du serveur"
+
+#: backend/localization.py:182
+msgid "File is too large"
+msgstr "Le fichier est trop volumineux"
+
+#: backend/localization.py:183
+msgid "Invalid file type"
+msgstr "Type de fichier invalide"
+
+#: backend/localization.py:186
+msgid "An error occurred"
+msgstr "Une erreur s'est produite"
+
+# Authentication
+#~ msgid "Login"
+#~ msgstr "Connexion"
+
+#~ msgid "Logout"
+#~ msgstr "Déconnexion"
+
+#~ msgid "Register"
+#~ msgstr "S'inscrire"
+
+#~ msgid "Username"
+#~ msgstr "Nom d'utilisateur"
+
+#~ msgid "Password"
+#~ msgstr "Mot de passe"
+
+#~ msgid "Email"
+#~ msgstr "E-mail"
+
+#~ msgid "First Name"
+#~ msgstr "Prénom"
+
+#~ msgid "Last Name"
+#~ msgstr "Nom"
+
+# Navigation
+#~ msgid "Home"
+#~ msgstr "Accueil"
+
+#~ msgid "Settings"
+#~ msgstr "Paramètres"
+
+#~ msgid "Status"
+#~ msgstr "Statut"
+
+#~ msgid "About"
+#~ msgstr "À propos"
+
+# Common actions
+#~ msgid "Save"
+#~ msgstr "Enregistrer"
+
+#~ msgid "Cancel"
+#~ msgstr "Annuler"
+
+#~ msgid "Delete"
+#~ msgstr "Supprimer"
+
+#~ msgid "Edit"
+#~ msgstr "Modifier"
+
+#~ msgid "Search"
+#~ msgstr "Rechercher"
+
+#~ msgid "Export"
+#~ msgstr "Exporter"
+
+#~ msgid "Import"
+#~ msgstr "Importer"
+
+# Messages
+#~ msgid "Success"
+#~ msgstr "Succès"
+
+#~ msgid "Error"
+#~ msgstr "Erreur"
+
+#~ msgid "Warning"
+#~ msgstr "Avertissement"
+
+#~ msgid "Loading..."
+#~ msgstr "Chargement..."
+
+#~ msgid "Saved successfully"
+#~ msgstr "Enregistré avec succès"
+
+#~ msgid "Deleted successfully"
+#~ msgstr "Supprimé avec succès"
+
+#~ msgid "Invalid request"
+#~ msgstr "Demande invalide"
+
+#~ msgid "Unauthorized"
+#~ msgstr "Non autorisé"
+
+#~ msgid "Not found"
+#~ msgstr "Introuvable"
+
+#~ msgid "Server error"
+#~ msgstr "Erreur serveur"
+
+# Warranties
+#~ msgid "Warranties"
+#~ msgstr "Garanties"
+
+#~ msgid "Warranty"
+#~ msgstr "Garantie"
+
+#~ msgid "Product Name"
+#~ msgstr "Nom du produit"
+
+#~ msgid "Purchase Date"
+#~ msgstr "Date d'achat"
+
+#~ msgid "Warranty Duration"
+#~ msgstr "Durée de garantie"
+
+#~ msgid "Expiration Date"
+#~ msgstr "Date d'expiration"
+
+#~ msgid "Vendor"
+#~ msgstr "Fournisseur"
+
+#~ msgid "Active"
+#~ msgstr "Actif"
+
+#~ msgid "Expired"
+#~ msgstr "Expiré"
+
+#~ msgid "Expiring Soon"
+#~ msgstr "Expire bientôt"
+
+#~ msgid "Lifetime"
+#~ msgstr "À vie"
+
+msgid "warranty_added_successfully"
+msgstr "Garantie ajoutée avec succès"
+
diff --git a/locales/fr/translation.json b/locales/fr/translation.json
new file mode 100644
index 0000000..cbdc80b
--- /dev/null
+++ b/locales/fr/translation.json
@@ -0,0 +1,562 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "Suivi des Garanties",
+ "nav": {
+ "home": "Accueil",
+ "status": "Statut",
+ "settings": "Paramètres",
+ "about": "À propos"
+ },
+ "auth": {
+ "login": "Connexion",
+ "logout": "Déconnexion",
+ "register": "S'inscrire",
+ "username": "Nom d'utilisateur",
+ "password": "Mot de passe",
+ "email": "E-mail",
+ "first_name": "Prénom",
+ "last_name": "Nom",
+ "forgot_password": "Mot de passe oublié ?",
+ "reset_password": "Réinitialiser le mot de passe",
+ "confirm_password": "Confirmer le mot de passe",
+ "create_account_title": "Créez votre compte",
+ "first_name_optional": "Prénom (facultatif)",
+ "last_name_optional": "Nom (facultatif)",
+ "username_hint": "Le nom d'utilisateur doit être unique et sera utilisé pour la connexion.",
+ "email_address": "Adresse e-mail",
+ "toggle_password": "Afficher/Masquer le mot de passe",
+ "password_hint_simple": "Le mot de passe doit comporter au moins 8 caractères et inclure des majuscules, des minuscules et des chiffres.",
+ "password_requirements": "Exigences du mot de passe :",
+ "req_length": "Au moins 8 caractères",
+ "req_uppercase": "Au moins 1 majuscule",
+ "req_lowercase": "Au moins 1 minuscule",
+ "req_number": "Au moins 1 chiffre",
+ "req_special": "Au moins 1 caractère spécial",
+ "create_account": "Créer un compte",
+ "already_have_account": "Vous avez déjà un compte ?",
+ "reset_password_title": "Warracker - Réinitialiser le mot de passe",
+ "reset_your_password": "Réinitialisez votre mot de passe",
+ "reset_password_info": "Saisissez votre adresse e-mail ci-dessous et nous vous enverrons un lien pour réinitialiser votre mot de passe.",
+ "send_reset_link": "Envoyer le lien de réinitialisation",
+ "back_to_login": "Retour à la connexion",
+ "set_new_password_title": "Warracker - Définir un nouveau mot de passe",
+ "set_new_password": "Définir un nouveau mot de passe",
+ "new_password": "Nouveau mot de passe",
+ "confirm_new_password": "Confirmer le nouveau mot de passe",
+ "invalid_or_expired_link": "Lien non valide ou expiré",
+ "invalid_link_info": "Le lien de réinitialisation de mot de passe sur lequel vous avez cliqué n'est pas valide ou a expiré.",
+ "request_new_reset_link": "Demander un nouveau lien de réinitialisation"
+ },
+ "warranties": {
+ "title": "Vos Garanties",
+ "title_global": "Garanties de Tous les Utilisateurs",
+ "add_new": "Ajouter une Nouvelle Garantie",
+ "edit": "Modifier la Garantie",
+ "delete": "Supprimer la Garantie",
+ "product_name": "Nom du Produit",
+ "purchase_date": "Date d'Achat",
+ "warranty_duration": "Durée de Garantie",
+ "years": "Années",
+ "months": "Mois",
+ "days": "Jours",
+ "vendor": "Fournisseur",
+ "serial_numbers": "Numéros de Série",
+ "purchase_price": "Prix d'Achat",
+ "notes": "Notes",
+ "tags": "Étiquettes",
+ "status": "Statut",
+ "expiration_date": "Date d'Expiration",
+ "active": "Actif",
+ "expired": "Expiré",
+ "expiring_soon": "Expire Bientôt",
+ "lifetime": "À Vie",
+ "no_warranties": "Aucune garantie pour le moment. Ajoutez votre première garantie pour commencer.",
+ "search_placeholder": "Rechercher par nom, fournisseurs, notes, étiquette ou numéro de série...",
+ "warranty_type": "Type de Garantie",
+ "other_document": "Autre Document",
+ "product": "Produit",
+ "expiration": "Expiration",
+ "actions": "Actions",
+ "no_warranties_title": "Aucune garantie pour le moment",
+ "no_warranties_desc": "Ajoutez votre première garantie pour commencer",
+ "add_warranty": "Ajouter une Garantie",
+ "warranty_entry_method": "Méthode de Saisie de Garantie",
+ "warranty_duration_option": "Durée de Garantie",
+ "exact_expiration_option": "Date d'Expiration Exacte",
+ "warranty_period": "Période de Garantie",
+ "expiration_date_label": "Date d'Expiration",
+ "currency": "Devise",
+ "add_tags": "Ajouter des Étiquettes",
+ "add_tags_desc": "Les étiquettes vous aident à organiser et filtrer vos garanties",
+ "save_changes": "Enregistrer les Modifications",
+ "confirm_delete": "Confirmer la Suppression",
+ "manage_tags": "Gérer les Étiquettes",
+ "add_tag": "Ajouter une Étiquette",
+ "unknown_status": "Statut Inconnu",
+ "expiring_soon_days": "Expire Bientôt ({{days}} {{dayText}})",
+ "days_remaining": "{{days}} {{dayText}} restants",
+ "day_one": "jour",
+ "day_other": "jours",
+ "month_one": "mois",
+ "month_other": "mois",
+ "year_one": "an",
+ "year_other": "ans",
+ "na": "N/A",
+ "age": "Âge",
+ "warranty": "Garantie",
+ "warranty_ends": "Fin de Garantie",
+ "price": "Prix",
+ "serial_number": "Numéro de Série",
+ "vendor": "Fournisseur",
+ "type": "Type",
+ "owner": "Propriétaire",
+ "product_website": "Site Web du Produit",
+ "notes": "Notes",
+ "documents": "Documents",
+ "summary": "Résumé",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "Années",
+ "months_placeholder": "Mois",
+ "days_placeholder": "Jours",
+ "add_any_notes_placeholder": "Ajouter des notes sur cette garantie...",
+ "product_url_optional": "URL du produit (facultatif)",
+ "enter_serial_number": "Entrez le numéro de série",
+ "vendor_optional": "Fournisseur (facultatif)",
+ "vendor_placeholder": "par exemple, Amazon, Best Buy, etc.",
+ "lifetime_warranty": "Garantie à vie",
+ "warranty_type_optional": "Type de garantie (facultatif)",
+ "select_warranty_type": "Sélectionnez le type de garantie...",
+ "standard": "Standard",
+ "extended": "Étendue",
+ "manufacturer": "Fabricant",
+ "third_party": "Tiers",
+ "store": "Magasin",
+ "premium": "Premium",
+ "limited": "Limitée",
+ "full": "Complète",
+ "parts_only": "Pièces uniquement",
+ "labor_only": "Main-d'œuvre uniquement",
+ "international": "Internationale",
+ "accidental_damage": "Dommages accidentels",
+ "other_custom": "Autre (personnalisé)",
+ "enter_custom_warranty_type": "Entrez un type de garantie personnalisé",
+ "purchase_price_optional": "Prix d'achat (facultatif)",
+ "notes_optional": "Notes (facultatif)",
+ "add_any_notes": "Ajoutez des notes sur cette garantie...",
+ "product_photo_optional": "Photo du produit (facultatif)",
+ "choose_photo": "Choisir une photo",
+ "invoice_receipt": "Facture/Reçu",
+ "store_locally": "Stocker localement",
+ "store_in_paperless": "Stocker dans Paperless-ngx",
+ "choose_file": "Choisir un fichier",
+ "browse_paperless": "Parcourir les documents Paperless-ngx",
+ "product_manual_optional": "Manuel du produit (facultatif)",
+ "files_zip_rar_optional": "Fichiers (ZIP/RAR, facultatif)",
+ "search_or_add_new_tag": "Rechercher ou ajouter une nouvelle étiquette...",
+ "product_information": "Informations sur le produit",
+ "product_url": "URL du produit",
+ "warranty_details": "Détails de la garantie",
+ "product_photo": "Photo du produit",
+ "product_manual": "Manuel du produit",
+ "files": "Fichiers",
+ "selected_tags": "Étiquettes sélectionnées",
+ "previous_tab": "Précédent",
+ "next_tab": "Suivant",
+ "delete_photo": "Supprimer la photo",
+ "delete_invoice": "Supprimer la facture",
+ "delete_manual": "Supprimer le manuel",
+ "delete_files": "Supprimer les fichiers",
+ "current_photo": "Photo actuelle :",
+ "current_invoice": "Facture actuelle :",
+ "current_manual": "Manuel actuel :",
+ "current_document": "Document actuel :",
+ "upload_new_photo_replace": "(Téléchargez une nouvelle photo pour remplacer)",
+ "no_photo_uploaded": "Aucune photo téléchargée",
+ "no_invoice_uploaded": "Aucune facture téléchargée",
+ "no_manual_uploaded": "Aucun manuel téléchargé",
+ "no_document_uploaded": "Aucun autre document téléchargé",
+ "photo_will_be_deleted": "La photo sera supprimée lors de la sauvegarde",
+ "invoice_will_be_deleted": "La facture sera supprimée lors de la sauvegarde",
+ "manual_will_be_deleted": "Le manuel sera supprimé lors de la sauvegarde",
+ "document_will_be_deleted": "L'autre document sera supprimé lors de la sauvegarde",
+ "confirm_delete_message": "Êtes-vous sûr de vouloir supprimer cette garantie ? Cette action ne peut pas être annulée.",
+ "new_tag_name": "Nouveau nom d'étiquette",
+ "existing_tags": "Étiquettes existantes",
+ "edit_warranty": "Modifier la Garantie",
+ "warranty_type_standard": "Standard",
+ "warranty_type_extended": "Étendue",
+ "warranty_type_manufacturer": "Fabricant",
+ "warranty_type_third_party": "Tiers",
+ "warranty_type_store": "Magasin",
+ "warranty_type_premium": "Premium",
+ "warranty_type_limited": "Limitée",
+ "warranty_type_full": "Complète",
+ "warranty_type_parts_only": "Pièces uniquement",
+ "warranty_type_labor_only": "Main-d'œuvre uniquement",
+ "warranty_type_international": "Internationale",
+ "warranty_type_accidental_damage": "Dommages accidentels",
+ "warranty_type_other": "Autre (Personnalisé)",
+ "warranty_type_custom_placeholder": "Entrez un type de garantie personnalisé",
+ "notes_placeholder": "Notes supplémentaires sur cette garantie...",
+ "tags_help_text": "Les étiquettes vous aident à organiser et filtrer vos garanties",
+ "search_add_tag_placeholder": "Rechercher ou ajouter une nouvelle étiquette...",
+ "upload_new_file_replace": "Télécharger un nouveau fichier pour remplacer",
+ "current_other_document": "Document actuel",
+ "no_other_document_uploaded": "Aucun autre document téléchargé",
+ "other_document_will_be_deleted": "L'autre document sera supprimé lors de la sauvegarde",
+ "files_optional": "Fichiers (ZIP/RAR, Optionnel)",
+ "invoice_receipt_short": "Facture",
+ "product_manual_short": "Manuel",
+ "files_short": "Fichiers",
+ "enter_serial_number": "Entrer le numéro de série",
+ "add_serial_number": "Ajouter un autre numéro de série"
+ },
+ "settings": {
+ "title": "Paramètres",
+ "account_settings": "Paramètres du Compte",
+ "preferences": "Préférences",
+ "language": "Langue",
+ "select_language": "Sélectionner la Langue",
+ "dark_mode": "Mode Sombre",
+ "dark_mode_desc": "Basculer entre le thème clair et sombre",
+ "currency": "Devise",
+ "timezone": "Fuseau Horaire",
+ "date_format": "Format de Date",
+ "expiring_soon_days": "Jours d'Expiration Proche",
+ "save_changes": "Enregistrer les Modifications",
+ "current_user": "Modification du Profil pour :",
+ "your_email": "Votre e-mail :",
+ "first_name": "Prénom",
+ "last_name": "Nom de Famille",
+ "email": "Email",
+ "save_profile": "Enregistrer les Modifications",
+ "default_view": "Vue par Défaut",
+ "default_view_desc": "Choisissez votre vue préférée pour les garanties",
+ "grid_view": "Vue Grille",
+ "list_view": "Vue Liste",
+ "table_view": "Vue Tableau",
+ "currency_symbol": "Symbole de Devise",
+ "currency_symbol_desc": "Choisissez le symbole à afficher pour les prix",
+ "currency_position": "Position de la Devise",
+ "currency_position_desc": "Choisissez si le symbole de devise apparaît à gauche ou à droite des nombres",
+ "expiring_soon_days_desc": "Nombre de jours avant expiration pour afficher les avertissements",
+ "date_format_desc": "Choisissez comment les dates sont affichées",
+ "save_preferences": "Enregistrer les Préférences",
+ "notification_settings": "Paramètres de Notification",
+ "notification_channel": "Canal de Notification",
+ "notification_channel_desc": "Choisissez comment vous voulez recevoir les notifications",
+ "notification_disabled": "Désactivé",
+ "notification_email": "Email",
+ "notification_apprise": "Apprise",
+ "notification_both": "Les Deux",
+ "email_settings": "Paramètres Email",
+ "notification_frequency": "Fréquence de Notification",
+ "notification_frequency_desc": "À quelle fréquence recevoir les notifications par email",
+ "daily": "Quotidien",
+ "weekly": "Hebdomadaire",
+ "monthly": "Mensuel",
+ "notification_time": "Heure de Notification",
+ "timezone_desc": "Votre fuseau horaire local pour les notifications",
+ "apprise_settings": "Paramètres Apprise",
+ "apprise_frequency": "Fréquence de Notification Apprise",
+ "apprise_frequency_desc": "À quelle fréquence recevoir les notifications Apprise",
+ "apprise_time": "Heure de Notification Apprise",
+ "apprise_timezone": "Fuseau Horaire Apprise",
+ "apprise_timezone_desc": "Votre fuseau horaire local pour les notifications Apprise",
+ "save_notification_settings": "Enregistrer les Paramètres de Notification",
+ "security": "Sécurité",
+ "change_password": "Changer le Mot de Passe",
+ "change_password_desc": "Mettre à jour le mot de passe de votre compte",
+ "change": "Changer",
+ "current_password": "Mot de Passe Actuel",
+ "new_password": "Nouveau Mot de Passe",
+ "confirm_password": "Confirmer le Nouveau Mot de Passe",
+ "update_password": "Mettre à Jour le Mot de Passe",
+ "cancel": "Annuler",
+ "danger_zone": "Zone de Danger",
+ "delete_account": "Supprimer le Compte",
+ "delete_account_desc": "Supprimer définitivement votre compte et toutes les données",
+ "admin_settings": "Paramètres Administrateur",
+ "admin_actions": "Actions Administrateur",
+ "refresh_data": "Actualiser les Données",
+ "check_admin_status": "Vérifier le Statut Administrateur",
+ "show_users_list": "Afficher la Liste des Utilisateurs",
+ "test_api": "Tester l'API",
+ "send_notifications": "Envoyer les Notifications de Garantie",
+ "check_scheduler": "Vérifier le Statut du Planificateur",
+ "site_settings": "Paramètres du Site",
+ "registration_enabled": "Inscription Activée",
+ "registration_enabled_desc": "Permettre aux nouveaux utilisateurs de s'inscrire",
+ "email_base_url": "URL de Base Email",
+ "global_view_enabled": "Vue Globale Activée",
+ "global_view_admin_only": "Vue Globale Admin Seulement",
+ "save_site_settings": "Enregistrer les Paramètres du Site",
+ "oidc_configuration": "Configuration OIDC SSO",
+ "enable_oidc": "Activer OIDC SSO",
+ "oidc_provider_name": "Nom du Fournisseur OIDC",
+ "client_id": "ID Client",
+ "client_secret": "Secret Client",
+ "issuer_url": "URL de l'Émetteur",
+ "scope": "Portée",
+ "save_oidc_settings": "Enregistrer les Paramètres OIDC",
+ "oidc_sso_desc": "Permettre aux utilisateurs de se connecter via un fournisseur OIDC.",
+ "oidc_only_mode": "Mode de connexion OIDC uniquement",
+ "oidc_only_mode_desc": "Masquer le formulaire de connexion traditionnel nom d'utilisateur/mot de passe et n'autoriser que la connexion OIDC. <strong>Avertissement :</strong> Assurez-vous que l'OIDC est correctement configuré avant d'activer cette option.",
+ "oidc_provider_name_desc": "Nom interne du client OIDC (par exemple, 'oidc').",
+ "client_secret_desc": "Valeur sensible. Stockée dans la base de données. Un redémarrage de l'application est nécessaire pour que les modifications prennent effet.",
+ "issuer_url_desc": "L'URL de base de votre fournisseur OIDC.",
+ "scope_desc": "Portées OIDC séparées par des espaces.",
+ "oidc_restart_message": "Un redémarrage de l'application est nécessaire pour que les paramètres OIDC prennent pleinement effet.",
+ "api_token": "Jeton API",
+ "view_documents": "Voir les Documents dans Warracker",
+ "connection_testing": "Test de Connexion",
+ "apprise_notifications": "Notifications Apprise",
+ "enable_apprise": "Activer les Notifications Apprise",
+ "loading": "Chargement...",
+ "time_of_day_notification": "Heure de la journée pour recevoir les notifications (format 24h)",
+ "paperless_ngx_settings": "Paramètres Paperless-ngx",
+ "paperless_ngx_about_title": "À propos de l'intégration Paperless-ngx :",
+ "paperless_ngx_about_desc": "Cette fonctionnalité optionnelle vous permet de stocker des documents de garantie dans votre instance Paperless-ngx auto-hébergée au lieu de les stocker localement. Lorsqu'elle est activée, les utilisateurs peuvent choisir où stocker chaque document : localement ou dans Paperless-ngx.",
+ "paperless_ngx_desc": "Configurer l'intégration avec le système de gestion de documents Paperless-ngx",
+ "enable_paperless": "Activer l'Intégration Paperless-ngx",
+ "paperless_url": "URL Paperless-ngx",
+ "paperless_url_desc": "URL de base de votre instance Paperless-ngx",
+ "paperless_token": "Jeton API",
+ "paperless_token_desc": "Votre jeton d'authentification API Paperless-ngx",
+ "paperless_token_desc_generate": "Générez un jeton d'API à partir de votre instance Paperless-ngx (Paramètres → Jetons d'API).",
+ "paperless_view_in_app": "Voir les documents dans l'app",
+ "paperless_view_in_app_desc": "Ouvrir les documents dans l'application au lieu d'un nouvel onglet",
+ "debug_config": "Configuration de débogage",
+ "test_upload": "Test de téléversement",
+ "save_paperless_settings": "Enregistrer les paramètres de Paperless-ngx",
+ "apprise_desc": "Configurer Apprise pour la livraison avancée de notifications vers plusieurs services",
+ "apprise_desc_system_wide": "Activer ou désactiver les notifications Apprise à l'échelle du système",
+ "apprise_not_available_title": "Apprise non disponible :",
+ "apprise_not_available_desc": "La bibliothèque de notifications Apprise n'est pas installée ou disponible. Les fonctionnalités de notification sont désactivées.",
+ "apprise_url": "URL Apprise",
+ "apprise_url_desc": "URL de votre service de notification Apprise",
+ "apprise_mode": "Mode de Notification",
+ "apprise_mode_desc": "Choisir quand envoyer les notifications Apprise",
+ "apprise_mode_global": "Résumé global",
+ "apprise_mode_individual": "Par utilisateur",
+ "test_paperless": "Tester la Connexion Paperless",
+ "test_apprise": "Tester la Connexion Apprise",
+ "apprise_warranty_scope": "Portée des Garanties",
+ "apprise_warranty_scope_desc": "Choisir quelles garanties inclure dans les notifications",
+ "all_warranties": "Toutes les Garanties",
+ "personal_warranties": "Garanties Personnelles Seulement",
+ "all_users_warranties": "Garanties de tous les utilisateurs",
+ "admin_warranties_only": "Garanties de l'administrateur uniquement",
+ "apprise_notification_days": "Jours de notification",
+ "apprise_notification_days_desc": "Jours avant l'expiration pour envoyer des notifications (séparés par des virgules, par exemple, \"7,30\" pour 7 jours et 30 jours avant)",
+ "apprise_check_frequency": "Fréquence de vérification",
+ "apprise_check_frequency_desc": "Fréquence à laquelle le système vérifie les garanties expirant (paramètre global)",
+ "apprise_title_prefix": "Préfixe du titre du message",
+ "apprise_title_prefix_desc": "Préfixe ajouté aux titres des notifications (par exemple, \"[Warracker]\" donne \"[Warracker] Garanties expirant bientôt\")",
+ "apprise_test_url": "URL de test (facultatif)",
+ "apprise_test_url_desc": "Facultatif : URL pour envoyer uniquement des notifications de test (ne sera pas enregistré dans la configuration principale)",
+ "save_apprise_settings": "Enregistrer les paramètres Apprise",
+ "validate_urls": "Valider les URL",
+ "send_expiration_notifications_now": "Envoyer les notifications d'expiration maintenant",
+ "apprise_current_status": "État actuel",
+ "apprise_urls_configured": "URL configurées :",
+ "apprise_supported_services": "Services pris en charge",
+ "apprise_supported_services_desc": "Apprise prend en charge plus de 80 services de notification, notamment : Discord, Slack, Telegram, Email (Gmail, Outlook), Webhooks, Microsoft Teams, Matrix, Pushover, Ntfy, Gotify, et bien d'autres.",
+ "view_full_list_of_supported_services": "Voir la liste complète des services pris en charge",
+ "ownership_management": "Gestion de la propriété",
+ "transfer_ownership": "Transférer la propriété",
+ "warning_title": "Avertissement :",
+ "transfer_ownership_warning": "Transférer la propriété de l'application à un autre utilisateur administrateur. Cette action est irréversible.",
+ "transfer_ownership_desc": "Une fois la propriété transférée, vous deviendrez un administrateur ordinaire et le nouveau propriétaire aura le contrôle ultime sur l'application.",
+ "select_new_owner": "Sélectionner un nouveau propriétaire (doit être un administrateur)",
+ "select_admin_user": "Sélectionner un utilisateur administrateur...",
+ "transfer_ownership_button": "Transférer la propriété",
+ "transfer_ownership_irreversible": "Cette action ne peut pas être annulée.",
+ "transfer_ownership_confirmation": "Vous êtes sur le point de transférer la propriété de l'application à",
+ "after_this_transfer": "Après ce transfert :",
+ "transfer_ownership_consequence_1": "Vous deviendrez un administrateur ordinaire",
+ "transfer_ownership_consequence_2": "Le nouveau propriétaire aura le contrôle ultime sur l'application",
+ "transfer_ownership_consequence_3": "Seul le nouveau propriétaire peut à nouveau transférer la propriété",
+ "transfer_ownership_type_to_confirm": "Pour confirmer, veuillez taper \"TRANSFER\" dans le champ ci-dessous :"
+ },
+ "actions": {
+ "save": "Enregistrer",
+ "cancel": "Annuler",
+ "delete": "Supprimer",
+ "edit": "Modifier",
+ "export": "Exporter",
+ "import": "Importer",
+ "refresh": "Actualiser",
+ "search": "Rechercher",
+ "clear": "Effacer",
+ "upload": "Téléverser",
+ "download": "Télécharger",
+ "manage_tags": "Gérer les Étiquettes",
+ "close": "Fermer",
+ "save_changes": "Enregistrer les Modifications"
+ },
+ "filters": {
+ "all_status": "Tous les Statuts",
+ "all_tags": "Toutes les Étiquettes",
+ "all_vendors": "Tous les Fournisseurs",
+ "all_types": "Tous les Types",
+ "sort_by": "Trier par",
+ "sort_expiration": "Date d'Expiration",
+ "sort_purchase": "Date d'Achat",
+ "sort_age": "Âge",
+ "sort_name": "Nom du Produit",
+ "sort_vendor": "Fournisseur",
+ "sort_warranty_type": "Type de Garantie",
+ "status": "Statut",
+ "tags": "Étiquettes",
+ "vendor": "Fournisseur",
+ "warranty_type": "Type de Garantie",
+ "view": "Vue",
+ "scope": "Portée"
+ },
+ "messages": {
+ "success": "Succès",
+ "error": "Erreur",
+ "warning": "Avertissement",
+ "loading": "Chargement...",
+ "saved": "Modifications enregistrées avec succès",
+ "deleted": "Élément supprimé avec succès",
+ "confirm_delete": "Êtes-vous sûr de vouloir supprimer cet élément ?",
+ "no_results": "Aucun résultat trouvé",
+ "file_too_large": "Le fichier est trop volumineux",
+ "invalid_file_type": "Type de fichier invalide",
+ "fill_first_last_name": "Veuillez remplir le prénom et le nom de famille",
+ "email_cannot_be_empty": "L'adresse e-mail ne peut pas être vide.",
+ "enter_valid_email": "Veuillez saisir une adresse e-mail valide.",
+ "profile_updated_successfully": "Profil mis à jour avec succès",
+ "preferences_saved_successfully": "Préférences enregistrées avec succès.",
+ "fill_password_fields": "Veuillez remplir tous les champs de mot de passe",
+ "passwords_do_not_match": "Les nouveaux mots de passe ne correspondent pas",
+ "password_min_length": "Le mot de passe doit comporter au moins 8 caractères",
+ "type_delete_to_confirm": "Veuillez taper DELETE pour confirmer",
+ "account_deleted_successfully": "Compte supprimé avec succès",
+ "account_cannot_delete_offline": "Le compte ne peut pas être supprimé en mode hors ligne",
+ "failed_delete_account": "Échec de la suppression du compte. Veuillez réessayer.",
+ "user_updated_successfully": "Utilisateur mis à jour avec succès",
+ "user_deleted_successfully": "Utilisateur supprimé avec succès",
+ "user_id_missing": "ID utilisateur manquant",
+ "failed_load_users": "Échec du chargement des utilisateurs",
+ "error_loading_users": "Erreur lors du chargement des utilisateurs",
+ "select_user_transfer_ownership": "Veuillez sélectionner un utilisateur à qui transférer la propriété",
+ "ownership_transferred_successfully": "Propriété transférée avec succès ! Actualisation de la page...",
+ "failed_load_site_settings": "Échec du chargement des paramètres du site. Veuillez réessayer.",
+ "invalid_email_base_url": "Format d'URL de base d'e-mail invalide. Doit commencer par http:// ou https://",
+ "no_site_settings_to_save": "Aucun paramètre de site à enregistrer.",
+ "site_settings_saved_successfully": "Paramètres du site enregistrés avec succès",
+ "failed_save_site_settings": "Échec de l'enregistrement des paramètres du site",
+ "oidc_settings_saved_successfully": "Paramètres OIDC enregistrés avec succès.",
+ "failed_save_oidc_settings": "Échec de l'enregistrement des paramètres OIDC.",
+ "api_endpoint_accessible": "Le point de terminaison API est accessible",
+ "api_endpoint_not_accessible": "Le point de terminaison API n'est pas accessible. Statut : ",
+ "only_admins_send_notifications": "Seuls les administrateurs peuvent envoyer des notifications de garantie",
+ "notifications_triggered_successfully": "Notifications déclenchées avec succès",
+ "notification_settings_saved_successfully": "Paramètres de notification enregistrés avec succès",
+ "apprise_settings_saved_successfully": "Paramètres Apprise enregistrés avec succès",
+ "test_notification_sent_successfully": "Notification de test envoyée avec succès",
+ "no_urls_to_validate": "Aucune URL à valider",
+ "paperless_settings_saved_successfully": "Paramètres Paperless-ngx enregistrés avec succès !",
+ "enter_valid_paperless_url": "Veuillez saisir une URL valide (ex. https://paperless.votredomaine.com)",
+ "enter_paperless_url_first": "Veuillez d'abord saisir une URL Paperless-ngx",
+ "paperless_connection_test_successful": "Test de connexion Paperless-ngx réussi !",
+ "paperless_connection_test_failed": "Test de connexion Paperless-ngx échoué",
+ "enter_api_token_test_connection": "Veuillez saisir un jeton API pour tester la connexion",
+ "failed_load_user_data": "Échec du chargement des données utilisateur. Veuillez réessayer.",
+ "could_not_connect_user_data": "Impossible de se connecter pour récupérer les données utilisateur. Affichage des informations en cache.",
+ "preferences_saved_locally_failed_sync": "Préférences enregistrées localement, mais échec de la synchronisation avec le serveur : ",
+ "preferences_saved_locally": "Préférences enregistrées localement.",
+ "correct_errors_in_tab": "Veuillez corriger les erreurs dans l'onglet mis en évidence avant de continuer.",
+ "please_fill_out_this_field": "Veuillez remplir ce champ.",
+ "warranty_added_successfully": "Garantie ajoutée avec succès",
+ "tag_name_required": "Le nom du tag est requis",
+ "tag_creation_function_not_found": "Fonction de création de tag non trouvée",
+ "tag_created_successfully": "Tag créé avec succès",
+ "tag_updated_successfully": "Tag mis à jour avec succès",
+ "tag_deleted_successfully": "Tag supprimé avec succès",
+ "failed_to_create_tag": "Échec de la création du tag",
+ "failed_to_update_tag": "Échec de la mise à jour du tag",
+ "failed_to_delete_tag": "Échec de la suppression du tag"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية",
+ "ru": "Русский",
+ "uk": "Українська",
+ "zh_CN": "简体中文",
+ "zh_HK": "繁體中文",
+ "ja": "日本語",
+ "pt": "Português",
+ "ko": "한국어"
+ },
+ "status": {
+ "title": "État du Système",
+ "dashboard_title": "Tableau de Bord des Garanties",
+ "global_dashboard_title": "Tableau de Bord Global des Garanties",
+ "overview": "Aperçu",
+ "statistics": "Statistiques",
+ "total_warranties": "Total des Garanties",
+ "active_warranties": "Garanties Actives",
+ "expiring_soon": "Expire Bientôt",
+ "expired_warranties": "Garanties Expirées",
+ "warranty_distribution": "Répartition des Garanties",
+ "expiration_timeline": "Chronologie d'Expiration",
+ "recent_activity": "Activité Récente",
+ "recent_expirations": "Récemment Expirées ou Expirant Bientôt",
+ "recent_expirations_empty": "Aucune garantie récemment expirée ou expirant bientôt.",
+ "system_health": "Santé du Système",
+ "database_status": "État de la Base de Données",
+ "connected": "Connecté",
+ "version": "Version",
+ "uptime": "Temps de Fonctionnement"
+ },
+ "about": {
+ "title": "À Propos de Warracker",
+ "description": "Un système complet de gestion de garanties conçu pour vous aider à suivre, organiser et gérer toutes vos garanties de produits sur une plateforme sécurisée et conviviale.",
+ "version": "Version",
+ "update_status": "État des Mises à Jour",
+ "checking_updates": "Vérification des mises à jour...",
+ "view_release_notes": "Voir les Notes de Version",
+ "project_info": "Informations du Projet",
+ "project_description": "Warracker est un système de gestion de garanties open-source construit avec des technologies web modernes. Il fournit un moyen sécurisé et intuitif de gérer les garanties de produits, suivre les dates d'expiration et organiser les documents importants.",
+ "github_repository": "Dépôt GitHub",
+ "releases": "Versions",
+ "community_support": "Communauté et Support",
+ "community_description": "Rejoignez notre communauté pour le support, les discussions et les mises à jour. Signalez des bugs, demandez des fonctionnalités ou obtenez de l'aide d'autres utilisateurs et contributeurs.",
+ "discord_community": "Communauté Discord",
+ "report_issues": "Signaler des Problèmes",
+ "developer_info": "Informations du Développeur",
+ "developer_description": "Warracker est développé et maintenu par Sassanix. Le projet est open-source et accueille les contributions de la communauté.",
+ "sassanix": "Sassanix",
+ "agpl_license": "Licence AGPL-3.0",
+ "support_project": "Soutenir le Projet",
+ "support_description": "Si vous trouvez Warracker utile, considérez soutenir son développement !",
+ "new_version_available": "Nouvelle version {{version}} disponible !",
+ "latest_version": "Vous utilisez la dernière version",
+ "update_check_failed": "Échec de la vérification des mises à jour",
+ "features": "Fonctionnalités",
+ "feature_track": "Suivre les garanties de produits",
+ "feature_notifications": "Recevoir des notifications d'expiration",
+ "feature_documents": "Stocker les documents de garantie",
+ "feature_reports": "Générer des rapports de garantie",
+ "feature_tags": "Organiser avec des étiquettes",
+ "feature_export": "Exporter les données de garantie",
+ "support": "Support",
+ "documentation": "Documentation",
+ "github": "Dépôt GitHub",
+ "license": "Licence",
+ "copyright": "Droits d'Auteur",
+ "developed_by": "Développé par"
+ }
+}
\ No newline at end of file
diff --git a/locales/hi/translation.json b/locales/hi/translation.json
new file mode 100644
index 0000000..eab76f3
--- /dev/null
+++ b/locales/hi/translation.json
@@ -0,0 +1,559 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "वारंटी ट्रैकर",
+ "nav": {
+ "home": "होम",
+ "status": "स्थिति",
+ "settings": "सेटिंग्स",
+ "about": "के बारे में"
+ },
+ "auth": {
+ "login": "लॉगिन",
+ "logout": "लॉगआउट",
+ "register": "पंजीकरण",
+ "username": "उपयोगकर्ता नाम",
+ "password": "पासवर्ड",
+ "email": "ईमेल",
+ "first_name": "पहला नाम",
+ "last_name": "अंतिम नाम",
+ "forgot_password": "पासवर्ड भूल गए?",
+ "reset_password": "पासवर्ड रीसेट करें",
+ "confirm_password": "पासवर्ड की पुष्टि करें",
+ "create_account_title": "अपना खाता बनाएं",
+ "first_name_optional": "पहला नाम (वैकल्पिक)",
+ "last_name_optional": "अंतिम नाम (वैकल्पिक)",
+ "username_hint": "उपयोगकर्ता नाम अद्वितीय होना चाहिए और लॉगिन के लिए उपयोग किया जाएगा।",
+ "email_address": "ईमेल पता",
+ "toggle_password": "पासवर्ड दिखाएं/छिपाएं",
+ "password_hint_simple": "पासवर्ड में कम से कम 8 अक्षर होने चाहिए और इसमें अपरकेस, लोअरकेस और संख्याएं शामिल होनी चाहिए।",
+ "password_requirements": "पासवर्ड आवश्यकताएँ:",
+ "req_length": "कम से कम 8 अक्षर",
+ "req_uppercase": "कम से कम 1 अपरकेस अक्षर",
+ "req_lowercase": "कम से कम 1 लोअरकेस अक्षर",
+ "req_number": "कम से कम 1 संख्या",
+ "req_special": "कम से कम 1 विशेष वर्ण",
+ "create_account": "खाता बनाएं",
+ "already_have_account": "क्या आपके पास पहले से एक खाता है?",
+ "reset_password_title": "Warracker - पासवर्ड रीसेट करें",
+ "reset_your_password": "अपना पासवर्ड रीसेट करें",
+ "reset_password_info": "नीचे अपना ईमेल पता दर्ज करें और हम आपको अपना पासवर्ड रीसेट करने के लिए एक लिंक भेजेंगे।",
+ "send_reset_link": "रीसेट लिंक भेजें",
+ "back_to_login": "लॉगिन पर वापस जाएं",
+ "set_new_password_title": "Warracker - नया पासवर्ड सेट करें",
+ "set_new_password": "नया पासवर्ड सेट करें",
+ "new_password": "नया पासवर्ड",
+ "confirm_new_password": "नए पासवर्ड की पुष्टि करें",
+ "invalid_or_expired_link": "अमान्य या समाप्त हो चुका लिंक",
+ "invalid_link_info": "आपके द्वारा क्लिक किया गया पासवर्ड रीसेट लिंक अमान्य है या समाप्त हो गया है।",
+ "request_new_reset_link": "नया रीसेट लिंक अनुरोध करें"
+ },
+ "warranties": {
+ "title": "आपकी वारंटी",
+ "title_global": "सभी उपयोगकर्ताओं की वारंटी",
+ "add_new": "नई वारंटी जोड़ें",
+ "edit": "वारंटी संपादित करें",
+ "delete": "वारंटी हटाएं",
+ "product_name": "उत्पाद का नाम",
+ "purchase_date": "खरीद की तारीख",
+ "warranty_duration": "वारंटी अवधि",
+ "years": "वर्ष",
+ "months": "महीने",
+ "days": "दिन",
+ "vendor": "विक्रेता",
+ "serial_numbers": "सीरियल नंबर",
+ "purchase_price": "खरीद मूल्य",
+ "notes": "नोट्स",
+ "tags": "टैग",
+ "status": "स्थिति",
+ "expiration_date": "समाप्ति तिथि",
+ "active": "सक्रिय",
+ "expired": "समाप्त",
+ "expiring_soon": "जल्द समाप्त होने वाली",
+ "lifetime": "आजीवन",
+ "no_warranties": "अभी तक कोई वारंटी नहीं। शुरू करने के लिए अपनी पहली वारंटी जोड़ें।",
+ "search_placeholder": "नाम, विक्रेता, नोट्स, टैग या सीरियल नंबर से खोजें...",
+ "warranty_type": "वारंटी प्रकार",
+ "other_document": "अन्य दस्तावेज़",
+ "product": "उत्पाद",
+ "expiration": "समाप्ति",
+ "actions": "कार्य",
+ "no_warranties_title": "अभी तक कोई वारंटी नहीं",
+ "no_warranties_desc": "शुरू करने के लिए अपनी पहली वारंटी जोड़ें",
+ "add_warranty": "वारंटी जोड़ें",
+ "warranty_entry_method": "वारंटी प्रविष्टि विधि",
+ "warranty_duration_option": "वारंटी अवधि",
+ "exact_expiration_option": "सटीक समाप्ति तिथि",
+ "warranty_period": "वारंटी अवधि",
+ "expiration_date_label": "समाप्ति तिथि",
+ "currency": "मुद्रा",
+ "add_tags": "टैग जोड़ें",
+ "add_tags_desc": "टैग आपकी वारंटी को व्यवस्थित और फ़िल्टर करने में मदद करते हैं",
+ "save_changes": "परिवर्तन सहेजें",
+ "confirm_delete": "हटाने की पुष्टि करें",
+ "manage_tags": "टैग प्रबंधित करें",
+ "add_tag": "टैग जोड़ें",
+ "unknown_status": "अज्ञात स्थिति",
+ "expiring_soon_days": "जल्द समाप्त होने वाली ({{days}} {{dayText}})",
+ "days_remaining": "{{days}} {{dayText}} शेष",
+ "day_one": "दिन",
+ "day_other": "दिन",
+ "month_one": "महीना",
+ "month_other": "महीने",
+ "year_one": "साल",
+ "year_other": "साल",
+ "na": "लागू नहीं",
+ "age": "आयु",
+ "warranty": "वारंटी",
+ "warranty_ends": "वारंटी समाप्त",
+ "price": "कीमत",
+ "serial_number": "सीरियल नंबर",
+ "type": "प्रकार",
+ "owner": "स्वामी",
+ "product_website": "उत्पाद वेबसाइट",
+ "documents": "दस्तावेज़",
+ "summary": "सारांश",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "वर्ष",
+ "months_placeholder": "महीने",
+ "days_placeholder": "दिन",
+ "add_any_notes_placeholder": "इस वारंटी के बारे में कोई नोट्स जोड़ें...",
+ "product_url_optional": "उत्पाद URL (वैकल्पिक)",
+ "enter_serial_number": "सीरियल नंबर दर्ज करें",
+ "vendor_optional": "विक्रेता (वैकल्पिक)",
+ "vendor_placeholder": "जैसे Amazon, Best Buy, आदि।",
+ "lifetime_warranty": "आजीवन वारंटी",
+ "warranty_type_optional": "वारंटी प्रकार (वैकल्पिक)",
+ "select_warranty_type": "वारंटी प्रकार चुनें...",
+ "standard": "मानक",
+ "extended": "विस्तारित",
+ "manufacturer": "निर्माता",
+ "third_party": "तृतीय पक्ष",
+ "store": "स्टोर",
+ "premium": "प्रीमियम",
+ "limited": "सीमित",
+ "full": "पूर्ण",
+ "parts_only": "केवल पुर्जे",
+ "labor_only": "केवल श्रम",
+ "international": "अंतर्राष्ट्रीय",
+ "accidental_damage": "आकस्मिक क्षति",
+ "other_custom": "अन्य (कस्टम)",
+ "enter_custom_warranty_type": "कस्टम वारंटी प्रकार दर्ज करें",
+ "purchase_price_optional": "खरीद मूल्य (वैकल्पिक)",
+ "notes_optional": "नोट्स (वैकल्पिक)",
+ "add_any_notes": "इस वारंटी के बारे में कोई नोट्स जोड़ें...",
+ "product_photo_optional": "उत्पाद फोटो (वैकल्पिक)",
+ "choose_photo": "फोटो चुनें",
+ "invoice_receipt": "चालान/रसीद",
+ "store_locally": "स्थानीय रूप से स्टोर करें",
+ "store_in_paperless": "Paperless-ngx में स्टोर करें",
+ "choose_file": "फ़ाइल चुनें",
+ "browse_paperless": "Paperless-ngx दस्तावेज़ ब्राउज़ करें",
+ "product_manual_optional": "उत्पाद मैनुअल (वैकल्पिक)",
+ "files_zip_rar_optional": "फाइलें (ZIP/RAR, वैकल्पिक)",
+ "search_or_add_new_tag": "खोजें या नया टैग जोड़ें...",
+ "product_information": "उत्पाद जानकारी",
+ "product_url": "उत्पाद URL",
+ "warranty_details": "वारंटी विवरण",
+ "product_photo": "उत्पाद फोटो",
+ "product_manual": "उत्पाद मैनुअल",
+ "files": "फाइलें",
+ "selected_tags": "चयनित टैग",
+ "previous_tab": "पिछला",
+ "next_tab": "अगला",
+ "delete_photo": "फोटो हटाएं",
+ "delete_invoice": "चालान हटाएं",
+ "delete_manual": "मैनुअल हटाएं",
+ "delete_files": "फाइलें हटाएं",
+ "current_photo": "वर्तमान फोटो:",
+ "current_invoice": "वर्तमान चालान:",
+ "current_manual": "वर्तमान मैनुअल:",
+ "current_document": "वर्तमान दस्तावेज़:",
+ "upload_new_photo_replace": "(बदलने के लिए नई फोटो अपलोड करें)",
+ "no_photo_uploaded": "कोई फोटो अपलोड नहीं की गई",
+ "no_invoice_uploaded": "कोई चालान अपलोड नहीं किया गया",
+ "no_manual_uploaded": "कोई मैनुअल अपलोड नहीं किया गया",
+ "no_document_uploaded": "कोई अन्य दस्तावेज़ अपलोड नहीं किया गया",
+ "photo_will_be_deleted": "सेव करने पर फोटो हटा दी जाएगी",
+ "invoice_will_be_deleted": "सेव करने पर चालान हटा दिया जाएगा",
+ "manual_will_be_deleted": "सेव करने पर मैनुअल हटा दिया जाएगा",
+ "document_will_be_deleted": "सेव करने पर अन्य दस्तावेज़ हटा दिया जाएगा",
+ "confirm_delete_message": "क्या आप वाकई इस वारंटी को हटाना चाहते हैं? यह क्रिया पूर्ववत नहीं की जा सकती।",
+ "new_tag_name": "नया टैग नाम",
+ "existing_tags": "मौजूदा टैग",
+ "edit_warranty": "वारंटी संपादित करें",
+ "warranty_type_standard": "मानक",
+ "warranty_type_extended": "विस्तारित",
+ "warranty_type_manufacturer": "निर्माता",
+ "warranty_type_third_party": "तृतीय पक्ष",
+ "warranty_type_store": "स्टोर",
+ "warranty_type_premium": "प्रीमियम",
+ "warranty_type_limited": "सीमित",
+ "warranty_type_full": "पूर्ण",
+ "warranty_type_parts_only": "केवल पुर्जे",
+ "warranty_type_labor_only": "केवल श्रम",
+ "warranty_type_international": "अंतर्राष्ट्रीय",
+ "warranty_type_accidental_damage": "आकस्मिक क्षति",
+ "warranty_type_other": "अन्य (कस्टम)",
+ "warranty_type_custom_placeholder": "कस्टम वारंटी प्रकार दर्ज करें",
+ "notes_placeholder": "इस वारंटी के बारे में अतिरिक्त नोट्स...",
+ "tags_help_text": "टैग आपको अपनी वारंटी को व्यवस्थित और फ़िल्टर करने में मदद करते हैं",
+ "search_add_tag_placeholder": "खोजें या नया टैग जोड़ें...",
+ "upload_new_file_replace": "बदलने के लिए नई फ़ाइल अपलोड करें",
+ "current_other_document": "वर्तमान अन्य दस्तावेज़",
+ "no_other_document_uploaded": "कोई अन्य दस्तावेज़ अपलोड नहीं किया गया",
+ "other_document_will_be_deleted": "अन्य दस्तावेज़ सेव करने पर हटा दिया जाएगा",
+ "files_optional": "फाइलें (ZIP/RAR, वैकल्पिक)",
+ "invoice_receipt_short": "चालान",
+ "product_manual_short": "मैनुअल",
+ "files_short": "फाइलें",
+ "enter_serial_number": "सीरियल नंबर दर्ज करें",
+ "add_serial_number": "अन्य सीरियल नंबर जोड़ें"
+ },
+ "settings": {
+ "title": "सेटिंग्स",
+ "account_settings": "खाता सेटिंग्स",
+ "preferences": "प्राथमिकताएं",
+ "language": "भाषा",
+ "select_language": "अपनी पसंदीदा भाषा चुनें",
+ "dark_mode": "डार्क मोड",
+ "dark_mode_desc": "लाइट और डार्क थीम के बीच स्विच करें",
+ "currency": "मुद्रा",
+ "timezone": "समय क्षेत्र",
+ "date_format": "दिनांक प्रारूप",
+ "expiring_soon_days": "जल्द समाप्त होने के दिन",
+ "save_changes": "परिवर्तन सहेजें",
+ "current_user": "प्रोफ़ाइल संपादित करना:",
+ "your_email": "आपका ईमेल:",
+ "first_name": "पहला नाम",
+ "last_name": "अंतिम नाम",
+ "email": "ईमेल",
+ "save_profile": "प्रोफ़ाइल सहेजें",
+ "default_view": "डिफ़ॉल्ट दृश्य",
+ "default_view_desc": "वारंटी के लिए अपना पसंदीदा दृश्य चुनें",
+ "grid_view": "ग्रिड दृश्य",
+ "list_view": "सूची दृश्य",
+ "table_view": "तालिका दृश्य",
+ "currency_symbol": "मुद्रा चिह्न",
+ "currency_symbol_desc": "कीमतों के प्रदर्शन के लिए चिह्न चुनें",
+ "currency_position": "मुद्रा स्थिति",
+ "currency_position_desc": "चुनें कि मुद्रा चिह्न संख्याओं के बाएं या दाएं दिखाई दे",
+ "expiring_soon_days_desc": "वारंटी समाप्ति से पहले के दिनों की संख्या \"जल्द समाप्त होने वाली\" के रूप में चिह्नित करने के लिए",
+ "date_format_desc": "चुनें कि दिनांक कैसे प्रदर्शित हों",
+ "save_preferences": "प्राथमिकताएं सहेजें",
+ "notification_settings": "नोटिफिकेशन सेटिंग्स",
+ "notification_channel": "नोटिफिकेशन चैनल",
+ "notification_channel_desc": "चुनें कि आप नोटिफिकेशन कैसे प्राप्त करना चाहते हैं",
+ "notification_disabled": "अक्षम",
+ "notification_email": "ईमेल",
+ "notification_apprise": "Apprise",
+ "notification_both": "दोनों",
+ "email_settings": "ईमेल सेटिंग्स",
+ "notification_frequency": "नोटिफिकेशन आवृत्ति",
+ "notification_frequency_desc": "ईमेल नोटिफिकेशन कितनी बार प्राप्त करें",
+ "daily": "दैनिक",
+ "weekly": "साप्ताहिक",
+ "monthly": "मासिक",
+ "notification_time": "नोटिफिकेशन समय",
+ "timezone_desc": "नोटिफिकेशन के लिए आपका स्थानीय समय क्षेत्र",
+ "apprise_settings": "Apprise सेटिंग्स",
+ "apprise_frequency": "Apprise नोटिफिकेशन आवृत्ति",
+ "apprise_frequency_desc": "Apprise नोटिफिकेशन कितनी बार प्राप्त करें",
+ "apprise_time": "Apprise नोटिफिकेशन समय",
+ "apprise_timezone": "Apprise समय क्षेत्र",
+ "apprise_timezone_desc": "Apprise नोटिफिकेशन के लिए आपका स्थानीय समय क्षेत्र",
+ "save_notification_settings": "नोटिफिकेशन सेटिंग्स सहेजें",
+ "security": "सुरक्षा",
+ "change_password": "पासवर्ड बदलें",
+ "change_password_desc": "अपना पासवर्ड अपडेट करें",
+ "change": "बदलें",
+ "current_password": "वर्तमान पासवर्ड",
+ "new_password": "नया पासवर्ड",
+ "confirm_password": "पासवर्ड की पुष्टि करें",
+ "update_password": "पासवर्ड अपडेट करें",
+ "cancel": "रद्द करें",
+ "danger_zone": "खतरा क्षेत्र",
+ "delete_account": "खाता हटाएं",
+ "delete_account_desc": "अपना खाता और सभी डेटा स्थायी रूप से हटाएं",
+ "admin_settings": "व्यवस्थापक सेटिंग्स",
+ "admin_actions": "व्यवस्थापक कार्य",
+ "refresh_data": "डेटा रीफ्रेश करें",
+ "check_admin_status": "व्यवस्थापक स्थिति जांचें",
+ "show_users_list": "उपयोगकर्ता सूची दिखाएं",
+ "test_api": "API परीक्षण करें",
+ "send_notifications": "वारंटी सूचनाएं भेजें",
+ "check_scheduler": "शेड्यूलर स्थिति जांचें",
+ "site_settings": "साइट सेटिंग्स",
+ "registration_enabled": "पंजीकरण सक्षम",
+ "registration_enabled_desc": "नए उपयोगकर्ताओं को पंजीकरण करने की अनुमति दें",
+ "email_base_url": "ईमेल बेस यूआरएल",
+ "global_view_enabled": "वैश्विक दृश्य सक्षम",
+ "global_view_admin_only": "वैश्विक दृश्य केवल व्यवस्थापक के लिए",
+ "save_site_settings": "साइट सेटिंग्स सहेजें",
+ "oidc_configuration": "ओआईडीसी एसएसओ कॉन्फ़िगरेशन",
+ "enable_oidc": "ओआईडीसी एसएसओ सक्षम करें",
+ "oidc_provider_name": "ओआईडीसी प्रदाता का नाम",
+ "client_id": "क्लाइंट आईडी",
+ "client_secret": "क्लाइंट सीक्रेट",
+ "issuer_url": "जारीकर्ता यूआरएल",
+ "scope": "स्कोप",
+ "save_oidc_settings": "ओआईडीसी सेटिंग्स सहेजें",
+ "oidc_sso_desc": "उपयोगकर्ताओं को एक OIDC प्रदाता के माध्यम से लॉगिन करने की अनुमति दें।",
+ "oidc_only_mode": "केवल-OIDC लॉगिन मोड",
+ "oidc_only_mode_desc": "पारंपरिक उपयोगकर्ता नाम/पासवर्ड लॉगिन फ़ॉर्म छिपाएं और केवल OIDC लॉगिन की अनुमति दें। <strong>चेतावनी:</strong> इस विकल्प को सक्षम करने से पहले सुनिश्चित करें कि OIDC ठीक से कॉन्फ़िगर किया गया है।",
+ "oidc_provider_name_desc": "OIDC क्लाइंट के लिए आंतरिक नाम (जैसे, 'oidc')।",
+ "client_secret_desc": "संवेदनशील मान। डेटाबेस में संग्रहीत। परिवर्तनों को प्रभावी होने के लिए एप्लिकेशन को पुनरारंभ करना आवश्यक है।",
+ "issuer_url_desc": "आपके OIDC प्रदाता का आधार URL।",
+ "scope_desc": "अंतरिक्ष-पृथक्कृत OIDC स्कोप।",
+ "oidc_restart_message": "OIDC सेटिंग्स को पूरी तरह से प्रभावी होने के लिए एप्लिकेशन को पुनरारंभ करना आवश्यक है।",
+ "api_token": "एपीआई टोकन",
+ "view_documents": "Warracker में दस्तावेज़ देखें",
+ "connection_testing": "कनेक्शन परीक्षण",
+ "apprise_notifications": "Apprise नोटिफिकेशन",
+ "enable_apprise": "Apprise नोटिफिकेशन सक्षम करें",
+ "loading": "लोड हो रहा है...",
+ "time_of_day_notification": "नोटिफिकेशन प्राप्त करने का दिन का समय (24-घंटे प्रारूप में)",
+ "paperless_ngx_settings": "Paperless-ngx सेटिंग्स",
+ "paperless_ngx_about_title": "Paperless-ngx एकीकरण के बारे में:",
+ "paperless_ngx_about_desc": "यह वैकल्पिक सुविधा आपको वारंटी दस्तावेज़ों को स्थानीय रूप से संग्रहीत करने के बजाय आपके स्व-होस्ट किए गए Paperless-ngx इंस्टेंस में संग्रहीत करने की अनुमति देती है। सक्षम होने पर, उपयोगकर्ता प्रत्येक दस्तावेज़ को कहाँ संग्रहीत करना है, यह चुन सकते हैं: स्थानीय रूप से या Paperless-ngx में।",
+ "paperless_ngx_desc": "Paperless-ngx दस्तावेज़ प्रबंधन प्रणाली के साथ एकीकरण कॉन्फ़िगर करें",
+ "enable_paperless": "Paperless-ngx एकीकरण सक्षम करें",
+ "paperless_url": "Paperless-ngx यूआरएल",
+ "paperless_token": "एपीआई टोकन",
+ "paperless_token_desc": "आपका Paperless-ngx एपीआई प्रमाणीकरण टोकन",
+ "paperless_token_desc_generate": "अपने Paperless-ngx इंस्टेंस से एक API टोकन उत्पन्न करें (सेटिंग्स → API टोकन)।",
+ "paperless_view_in_app": "ऐप में दस्तावेज़ देखें",
+ "paperless_view_in_app_desc": "दस्तावेज़ों को नए टैब के बजाय ऐप के भीतर खोलें",
+ "debug_config": "डीबग कॉन्फ़िग",
+ "test_upload": "अपलोड का परीक्षण करें",
+ "save_paperless_settings": "Paperless-ngx सेटिंग्स सहेजें",
+ "apprise_desc": "कई सेवाओं के लिए उन्नत अधिसूचना वितरण के लिए Apprise कॉन्फ़िगर करें",
+ "apprise_desc_system_wide": "सिस्टम-व्यापी Apprise सूचनाएं सक्षम या अक्षम करें",
+ "apprise_not_available_title": "Apprise उपलब्ध नहीं है:",
+ "apprise_not_available_desc": "Apprise अधिसूचना पुस्तकालय स्थापित या उपलब्ध नहीं है। अधिसूचना सुविधाएँ अक्षम हैं।",
+ "apprise_url": "Apprise यूआरएल",
+ "apprise_url_desc": "आपकी Apprise अधिसूचना सेवा यूआरएल",
+ "apprise_mode": "अधिसूचना मोड",
+ "apprise_mode_desc": "Apprise सूचनाएं कब भेजनी हैं, यह चुनें",
+ "apprise_mode_global": "वैश्विक सारांश",
+ "apprise_mode_individual": "प्रति उपयोगकर्ता",
+ "test_paperless": "पेपरलेस कनेक्शन का परीक्षण करें",
+ "test_apprise": "Apprise कनेक्शन का परीक्षण करें",
+ "apprise_warranty_scope": "वारंटी स्कोप",
+ "apprise_warranty_scope_desc": "सूचनाओं में कौन सी वारंटी शामिल करनी हैं, यह चुनें",
+ "all_warranties": "सभी वारंटी",
+ "personal_warranties": "केवल व्यक्तिगत वारंटी",
+ "all_users_warranties": "सभी उपयोगकर्ताओं की वारंटी",
+ "admin_warranties_only": "केवल व्यवस्थापक की वारंटी",
+ "apprise_notification_days": "अधिसूचना दिन",
+ "apprise_notification_days_desc": "समाप्ति से पहले सूचनाएं भेजने के लिए दिन (अल्पविराम से अलग, जैसे, 7 और 30 दिन पहले के लिए \"7,30\")",
+ "apprise_check_frequency": "आवृत्ति जांचें",
+ "apprise_check_frequency_desc": "सिस्टम कितनी बार समाप्त हो रही वारंटी की जांच करता है (वैश्विक सेटिंग)",
+ "apprise_title_prefix": "संदेश शीर्षक उपसर्ग",
+ "apprise_title_prefix_desc": "अधिसूचना शीर्षकों में जोड़ा गया उपसर्ग (जैसे, \"[Warracker]\" का परिणाम \"[Warracker] वारंटी जल्द ही समाप्त हो रही है\")",
+ "apprise_test_url": "परीक्षण URL (वैकल्पिक)",
+ "apprise_test_url_desc": "वैकल्पिक: केवल परीक्षण सूचनाएं भेजने के लिए URL (मुख्य कॉन्फ़िगरेशन में सहेजा नहीं जाएगा)",
+ "save_apprise_settings": "Apprise सेटिंग्स सहेजें",
+ "validate_urls": "URL मान्य करें",
+ "send_expiration_notifications_now": "अब समाप्ति सूचनाएं भेजें",
+ "apprise_current_status": "वर्तमान स्थिति",
+ "apprise_urls_configured": "कॉन्फ़िगर किए गए URL:",
+ "apprise_supported_services": "समर्थित सेवाएं",
+ "apprise_supported_services_desc": "Apprise 80+ अधिसूचना सेवाओं का समर्थन करता है जिनमें शामिल हैं: Discord, Slack, Telegram, Email (Gmail, Outlook), Webhooks, Microsoft Teams, Matrix, Pushover, Ntfy, Gotify, और बहुत कुछ।",
+ "view_full_list_of_supported_services": "समर्थित सेवाओं की पूरी सूची देखें",
+ "ownership_management": "स्वामित्व प्रबंधन",
+ "transfer_ownership": "स्वामित्व स्थानांतरित करें",
+ "warning_title": "चेतावनी:",
+ "transfer_ownership_warning": "एप्लिकेशन का स्वामित्व किसी अन्य व्यवस्थापक उपयोगकर्ता को स्थानांतरित करें। यह क्रिया अपरिवर्तनीय है।",
+ "transfer_ownership_desc": "एक बार स्वामित्व स्थानांतरित हो जाने के बाद, आप एक नियमित व्यवस्थापक बन जाएंगे और नए मालिक का एप्लिकेशन पर अंतिम नियंत्रण होगा।",
+ "select_new_owner": "नया स्वामी चुनें (एक व्यवस्थापक होना चाहिए)",
+ "select_admin_user": "एक व्यवस्थापक उपयोगकर्ता चुनें...",
+ "transfer_ownership_button": "स्वामित्व स्थानांतरित करें",
+ "transfer_ownership_irreversible": "यह क्रिया पूर्ववत नहीं की जा सकती।",
+ "transfer_ownership_confirmation": "आप एप्लिकेशन का स्वामित्व स्थानांतरित करने वाले हैं",
+ "after_this_transfer": "इस स्थानांतरण के बाद:",
+ "transfer_ownership_consequence_1": "आप एक नियमित व्यवस्थापक बन जाएंगे",
+ "transfer_ownership_consequence_2": "नए मालिक का एप्लिकेशन पर अंतिम नियंत्रण होगा",
+ "transfer_ownership_consequence_3": "केवल नया मालिक ही फिर से स्वामित्व स्थानांतरित कर सकता है",
+ "transfer_ownership_type_to_confirm": "पुष्टि करने के लिए, कृपया नीचे दिए गए फ़ील्ड में \"TRANSFER\" टाइप करें:"
+ },
+ "actions": {
+ "save": "सहेजें",
+ "cancel": "रद्द करें",
+ "delete": "हटाएं",
+ "edit": "संपादित करें",
+ "export": "निर्यात",
+ "import": "आयात",
+ "refresh": "रीफ्रेश",
+ "search": "खोजें",
+ "clear": "साफ़ करें",
+ "upload": "अपलोड",
+ "download": "डाउनलोड",
+ "manage_tags": "टैग प्रबंधित करें",
+ "close": "बंद करें",
+ "save_changes": "परिवर्तन सहेजें"
+ },
+ "filters": {
+ "all_status": "सभी स्थितियाँ",
+ "all_tags": "सभी टैग",
+ "all_vendors": "सभी विक्रेता",
+ "all_types": "सभी प्रकार",
+ "sort_by": "इसके अनुसार क्रमबद्ध करें",
+ "sort_expiration": "समाप्ति तिथि",
+ "sort_purchase": "खरीद की तारीख",
+ "sort_age": "आयु",
+ "sort_name": "उत्पाद का नाम",
+ "sort_vendor": "विक्रेता",
+ "sort_warranty_type": "वारंटी प्रकार",
+ "status": "स्थिति",
+ "tags": "टैग",
+ "vendor": "विक्रेता",
+ "warranty_type": "वारंटी प्रकार",
+ "view": "दृश्य",
+ "scope": "दायरा"
+ },
+ "messages": {
+ "success": "सफलता",
+ "error": "त्रुटि",
+ "warning": "चेतावनी",
+ "loading": "लोड हो रहा है...",
+ "saved": "परिवर्तन सफलतापूर्वक सहेजे गए",
+ "deleted": "आइटम सफलतापूर्वक हटा दिया गया",
+ "confirm_delete": "क्या आप वाकई इस आइटम को हटाना चाहते हैं?",
+ "no_results": "कोई परिणाम नहीं मिला",
+ "file_too_large": "फ़ाइल बहुत बड़ी है",
+ "invalid_file_type": "अमान्य फ़ाइल प्रकार",
+ "fill_first_last_name": "कृपया नाम और उपनाम भरें",
+ "email_cannot_be_empty": "ईमेल पता खाली नहीं हो सकता।",
+ "enter_valid_email": "कृपया एक वैध ईमेल पता दर्ज करें।",
+ "profile_updated_successfully": "प्रोफ़ाइल सफलतापूर्वक अपडेट की गई",
+ "preferences_saved_successfully": "प्राथमिकताएं सफलतापूर्वक सहेजी गईं।",
+ "fill_password_fields": "कृपया सभी पासवर्ड फ़ील्ड भरें",
+ "passwords_do_not_match": "नए पासवर्ड मेल नहीं खाते",
+ "password_min_length": "पासवर्ड कम से कम 8 अक्षर लंबा होना चाहिए",
+ "type_delete_to_confirm": "पुष्टि के लिए कृपया DELETE टाइप करें",
+ "account_deleted_successfully": "खाता सफलतापूर्वक हटा दिया गया",
+ "account_cannot_delete_offline": "ऑफ़लाइन मोड में खाता हटाया नहीं जा सकता",
+ "failed_delete_account": "खाता हटाने में विफल। कृपया फिर से कोशिश करें।",
+ "user_updated_successfully": "उपयोगकर्ता सफलतापूर्वक अपडेट किया गया",
+ "user_deleted_successfully": "उपयोगकर्ता सफलतापूर्वक हटा दिया गया",
+ "user_id_missing": "उपयोगकर्ता ID गायब है",
+ "failed_load_users": "उपयोगकर्ता लोड करने में विफल",
+ "error_loading_users": "उपयोगकर्ता लोड करने में त्रुटि",
+ "select_user_transfer_ownership": "स्वामित्व स्थानांतरित करने के लिए कृपया एक उपयोगकर्ता चुनें",
+ "ownership_transferred_successfully": "स्वामित्व सफलतापूर्वक स्थानांतरित! पृष्ठ को रीफ्रेश कर रहा है...",
+ "failed_load_site_settings": "साइट सेटिंग्स लोड करने में विफल। कृपया फिर से कोशिश करें।",
+ "invalid_email_base_url": "अमान्य ईमेल बेस URL प्रारूप। यह http:// या https:// से शुरू होना चाहिए",
+ "no_site_settings_to_save": "सहेजने के लिए कोई साइट सेटिंग्स नहीं।",
+ "site_settings_saved_successfully": "साइट सेटिंग्स सफलतापूर्वक सहेजी गईं",
+ "failed_save_site_settings": "साइट सेटिंग्स सहेजने में विफल",
+ "oidc_settings_saved_successfully": "OIDC सेटिंग्स सफलतापूर्वक सहेजी गईं।",
+ "failed_save_oidc_settings": "OIDC सेटिंग्स सहेजने में विफल।",
+ "api_endpoint_accessible": "API एंडपॉइंट पहुंच योग्य है",
+ "api_endpoint_not_accessible": "API एंडपॉइंट पहुंच योग्य नहीं है। स्थिति: ",
+ "only_admins_send_notifications": "केवल व्यवस्थापक वारंटी सूचनाएं भेज सकते हैं",
+ "notifications_triggered_successfully": "सूचनाएं सफलतापूर्वक ट्रिगर की गईं",
+ "notification_settings_saved_successfully": "सूचना सेटिंग्स सफलतापूर्वक सहेजी गईं",
+ "apprise_settings_saved_successfully": "Apprise सेटिंग्स सफलतापूर्वक सहेजी गईं",
+ "test_notification_sent_successfully": "परीक्षण सूचना सफलतापूर्वक भेजी गई",
+ "no_urls_to_validate": "सत्यापित करने के लिए कोई URL नहीं",
+ "paperless_settings_saved_successfully": "Paperless-ngx सेटिंग्स सफलतापूर्वक सहेजी गईं!",
+ "enter_valid_paperless_url": "कृपया एक वैध URL दर्ज करें (उदा: https://paperless.yourdomain.com)",
+ "enter_paperless_url_first": "कृपया पहले Paperless-ngx URL दर्ज करें",
+ "paperless_connection_test_successful": "Paperless-ngx कनेक्शन टेस्ट सफल!",
+ "paperless_connection_test_failed": "Paperless-ngx कनेक्शन टेस्ट विफल",
+ "enter_api_token_test_connection": "कनेक्शन टेस्ट करने के लिए कृपया API टोकन दर्ज करें",
+ "failed_load_user_data": "उपयोगकर्ता डेटा लोड करने में विफल। कृपया फिर से कोशिश करें।",
+ "could_not_connect_user_data": "उपयोगकर्ता डेटा प्राप्त करने के लिए कनेक्ट नहीं हो सका। कैश्ड जानकारी प्रदर्शित कर रहा है।",
+ "preferences_saved_locally_failed_sync": "प्राथमिकताएं स्थानीय रूप से सहेजी गईं, लेकिन सर्वर के साथ सिंक करने में विफल: ",
+ "preferences_saved_locally": "प्राथमिकताएं स्थानीय रूप से सहेजी गईं।",
+ "correct_errors_in_tab": "कृपया जारी रखने से पहले हाइलाइट किए गए टैब में त्रुटियों को सुधारें।",
+ "please_fill_out_this_field": "कृपया इस फ़ील्ड को भरें।",
+ "warranty_added_successfully": "वारंटी सफलतापूर्वक जोड़ी गई",
+ "tag_name_required": "टैग नाम आवश्यक है",
+ "tag_creation_function_not_found": "टैग निर्माण फ़ंक्शन नहीं मिला",
+ "tag_created_successfully": "टैग सफलतापूर्वक बनाया गया",
+ "tag_updated_successfully": "टैग सफलतापूर्वक अपडेट किया गया",
+ "tag_deleted_successfully": "टैग सफलतापूर्वक हटाया गया",
+ "failed_to_create_tag": "टैग बनाने में विफल",
+ "failed_to_update_tag": "टैग अपडेट करने में विफल",
+ "failed_to_delete_tag": "टैग हटाने में विफल"
+ },
+ "languages": {
+ "en": "अंग्रेज़ी",
+ "fr": "फ़्रेंच",
+ "es": "स्पेनिश",
+ "de": "जर्मन",
+ "it": "इतालवी",
+ "cs": "चेक",
+ "nl": "डच",
+ "hi": "हिन्दी",
+ "fa": "फ़ारसी",
+ "ar": "अरबी",
+ "ru": "रूसी",
+ "uk": "यूक्रेनी",
+ "zh_CN": "सरलीकृत चीनी",
+ "zh_HK": "पारंपरिक चीनी",
+ "ja": "जापानी",
+ "pt": "पुर्तगाली",
+ "ko": "कोरियाई"
+ },
+ "status": {
+ "title": "सिस्टम स्थिति",
+ "dashboard_title": "वारंटी स्थिति डैशबोर्ड",
+ "global_dashboard_title": "वैश्विक वारंटी स्थिति डैशबोर्ड",
+ "overview": "अवलोकन",
+ "statistics": "आंकड़े",
+ "total_warranties": "कुल वारंटी",
+ "active_warranties": "सक्रिय वारंटी",
+ "expiring_soon": "जल्द समाप्त होने वाली",
+ "expired_warranties": "समाप्त हो चुकी वारंटी",
+ "warranty_distribution": "वारंटी वितरण",
+ "expiration_timeline": "समाप्ति समयरेखा",
+ "recent_activity": "हाल की गतिविधि",
+ "recent_expirations": "हाल ही में समाप्त या जल्द समाप्त होने वाली",
+ "recent_expirations_empty": "कोई हाल ही में समाप्त या जल्द समाप्त होने वाली वारंटी नहीं।",
+ "system_health": "सिस्टम स्वास्थ्य",
+ "database_status": "डेटाबेस स्थिति",
+ "connected": "जुड़ा हुआ",
+ "version": "संस्करण",
+ "uptime": "अपटाइम"
+ },
+ "about": {
+ "title": "Warracker के बारे में",
+ "description": "एक व्यापक वारंटी प्रबंधन प्रणाली जो आपको अपने सभी उत्पाद वारंटी को एक सुरक्षित, उपयोगकर्ता-अनुकूल मंच पर ट्रैक, व्यवस्थित और प्रबंधित करने में मदद करने के लिए डिज़ाइन की गई है।",
+ "version": "संस्करण",
+ "update_status": "अद्यतन स्थिति",
+ "checking_updates": "अद्यतनों के लिए जाँच हो रही है...",
+ "view_release_notes": "रिलीज नोट्स देखें",
+ "project_info": "परियोजना की जानकारी",
+ "project_description": "Warracker एक ओपन-सोर्स वारंटी प्रबंधन प्रणाली है जिसे आधुनिक वेब प्रौद्योगिकियों के साथ बनाया गया है। यह उत्पाद वारंटी का प्रबंधन करने, समाप्ति तिथियों को ट्रैक करने और महत्वपूर्ण दस्तावेजों को व्यवस्थित करने का एक सुरक्षित और सहज तरीका प्रदान करता है।",
+ "github_repository": "GitHub रिपोजिटरी",
+ "releases": "रिलीज",
+ "community_support": "समुदाय और सहायता",
+ "community_description": "समर्थन, चर्चाओं और अपडेट के लिए हमारे समुदाय में शामिल हों। बग की रिपोर्ट करें, सुविधाओं का अनुरोध करें, या अन्य उपयोगकर्ताओं और योगदानकर्ताओं से सहायता प्राप्त करें।",
+ "discord_community": "डिस्कॉर्ड समुदाय",
+ "report_issues": "समस्याओं की रिपोर्ट करें",
+ "developer_info": "डेवलपर जानकारी",
+ "developer_description": "Warracker को Sassanix द्वारा विकसित और बनाए रखा गया है। यह परियोजना ओपन-सोर्स है और समुदाय से योगदान का स्वागत करती है।",
+ "sassanix": "Sassanix",
+ "agpl_license": "AGPL-3.0 लाइसेंस",
+ "support_project": "परियोजना का समर्थन करें",
+ "support_description": "यदि आपको Warracker उपयोगी लगता है, तो इसके विकास का समर्थन करने पर विचार करें!",
+ "new_version_available": "नया संस्करण {{version}} उपलब्ध है!",
+ "latest_version": "आप नवीनतम संस्करण का उपयोग कर रहे हैं",
+ "update_check_failed": "अद्यतनों के लिए जाँच करने में विफल",
+ "features": "सुविधाएं",
+ "feature_track": "उत्पाद वारंटी ट्रैक करें",
+ "feature_notifications": "समाप्ति सूचनाएं प्राप्त करें",
+ "feature_documents": "वारंटी दस्तावेज़ संग्रहीत करें",
+ "feature_reports": "वारंटी रिपोर्ट तैयार करें",
+ "feature_tags": "टैग के साथ व्यवस्थित करें",
+ "feature_export": "वारंटी डेटा निर्यात करें",
+ "support": "सहायता",
+ "documentation": "दस्तावेज़ीकरण",
+ "github": "GitHub",
+ "license": "लाइसेंस",
+ "copyright": "कॉपीराइट",
+ "developed_by": "द्वारा विकसित"
+ }
+}
\ No newline at end of file
diff --git a/locales/it/translation.json b/locales/it/translation.json
new file mode 100644
index 0000000..692ecdc
--- /dev/null
+++ b/locales/it/translation.json
@@ -0,0 +1,615 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "Gestore Garanzie",
+ "nav": {
+ "home": "Home",
+ "status": "Stato",
+ "settings": "Impostazioni",
+ "about": "Informazioni"
+ },
+ "auth": {
+ "login": "Accedi",
+ "logout": "Esci",
+ "register": "Registrati",
+ "username": "Nome utente",
+ "password": "Password",
+ "email": "Email",
+ "first_name": "Nome",
+ "last_name": "Cognome",
+ "forgot_password": "Password dimenticata?",
+ "reset_password": "Reimposta password",
+ "confirm_password": "Conferma password",
+ "create_account_title": "Crea il tuo account",
+ "first_name_optional": "Nome (opzionale)",
+ "last_name_optional": "Cognome (opzionale)",
+ "username_hint": "Il nome utente deve essere unico e verrà utilizzato per l'accesso.",
+ "email_address": "Indirizzo email",
+ "toggle_password": "Mostra/Nascondi password",
+ "password_hint_simple": "La password deve contenere almeno 8 caratteri e includere lettere maiuscole, minuscole e numeri.",
+ "password_requirements": "Requisiti della password:",
+ "req_length": "Almeno 8 caratteri",
+ "req_uppercase": "Almeno 1 lettera maiuscola",
+ "req_lowercase": "Almeno 1 lettera minuscola",
+ "req_number": "Almeno 1 numero",
+ "req_special": "Almeno 1 carattere speciale",
+ "create_account": "Crea account",
+ "already_have_account": "Hai già un account?",
+ "reset_password_title": "Warracker - Reimposta password",
+ "reset_your_password": "Reimposta la tua password",
+ "reset_password_info": "Inserisci il tuo indirizzo email qui sotto e ti invieremo un link per reimpostare la tua password.",
+ "send_reset_link": "Invia link di ripristino",
+ "back_to_login": "Torna al login",
+ "set_new_password_title": "Warracker - Imposta nuova password",
+ "set_new_password": "Imposta nuova password",
+ "new_password": "Nuova password",
+ "confirm_new_password": "Conferma nuova password",
+ "invalid_or_expired_link": "Link non valido o scaduto",
+ "invalid_link_info": "Il link per la reimpostazione della password che hai cliccato non è valido o è scaduto.",
+ "request_new_reset_link": "Richiedi nuovo link di ripristino"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية"
+ },
+ "status": {
+ "title": "Stato del sistema",
+ "dashboard_title": "Dashboard Stato Garanzie",
+ "global_dashboard_title": "Dashboard Globale Stato Garanzie",
+ "overview": "Panoramica",
+ "statistics": "Statistiche",
+ "total_warranties": "Garanzie totali",
+ "active_warranties": "Garanzie attive",
+ "expiring_soon": "In scadenza",
+ "expired_warranties": "Garanzie scadute",
+ "warranty_distribution": "Distribuzione garanzie",
+ "expiration_timeline": "Timeline di scadenza",
+ "recent_activity": "Attività recente",
+ "recent_expirations": "Recentemente Scadute o In Scadenza",
+ "recent_expirations_empty": "Nessuna garanzia recentemente scaduta o in scadenza.",
+ "system_health": "Salute del sistema",
+ "database_status": "Stato database",
+ "connected": "Connesso",
+ "version": "Versione",
+ "uptime": "Tempo di attività"
+ },
+ "about": {
+ "title": "Informazioni su Warracker",
+ "description": "Un sistema completo di gestione garanzie progettato per aiutarti a tracciare, organizzare e gestire tutte le garanzie dei tuoi prodotti in un'unica piattaforma sicura e user-friendly.",
+ "version": "Versione",
+ "update_status": "Stato Aggiornamenti",
+ "checking_updates": "Controllo aggiornamenti...",
+ "view_release_notes": "Visualizza Note di Rilascio",
+ "project_info": "Informazioni Progetto",
+ "project_description": "Warracker è un sistema open-source di gestione garanzie costruito con tecnologie web moderne. Fornisce un modo sicuro e intuitivo per gestire garanzie prodotti, tracciare date di scadenza e organizzare documenti importanti.",
+ "github_repository": "Repository GitHub",
+ "releases": "Rilasci",
+ "community_support": "Comunità e Supporto",
+ "community_description": "Unisciti alla nostra comunità per supporto, discussioni e aggiornamenti. Segnala bug, richiedi funzionalità o ottieni aiuto da altri utenti e contributori.",
+ "discord_community": "Comunità Discord",
+ "report_issues": "Segnala Problemi",
+ "developer_info": "Informazioni Sviluppatore",
+ "developer_description": "Warracker è sviluppato e mantenuto da Sassanix. Il progetto è open-source e accoglie contributi dalla comunità.",
+ "sassanix": "Sassanix",
+ "agpl_license": "Licenza AGPL-3.0",
+ "support_project": "Supporta il Progetto",
+ "support_description": "Se trovi Warracker utile, considera di supportare il suo sviluppo!",
+ "new_version_available": "Nuova versione {{version}} disponibile!",
+ "latest_version": "Stai usando l'ultima versione",
+ "update_check_failed": "Controllo aggiornamenti fallito",
+ "features": "Caratteristiche",
+ "feature_track": "Traccia garanzie prodotti",
+ "feature_notifications": "Ricevi notifiche di scadenza",
+ "feature_documents": "Archivia documenti garanzie",
+ "feature_reports": "Genera report garanzie",
+ "feature_tags": "Organizza con tag",
+ "feature_export": "Esporta dati garanzie",
+ "support": "Supporto",
+ "documentation": "Documentazione",
+ "github": "Repository GitHub",
+ "license": "Licenza",
+ "copyright": "Copyright",
+ "developed_by": "Sviluppato da"
+ },
+ "settings": {
+ "title": "Impostazioni",
+ "general": "Generale",
+ "profile": "Profilo",
+ "preferences": "Preferenze",
+ "language": "Lingua",
+ "select_language": "Seleziona la tua lingua preferita",
+ "dark_mode": "Modalità scura",
+ "dark_mode_desc": "Passa tra tema chiaro e scuro",
+ "default_view": "Vista predefinita",
+ "default_view_desc": "Scegli la vista preferita per le garanzie",
+ "grid_view": "Vista griglia",
+ "list_view": "Vista elenco",
+ "table_view": "Vista tabella",
+ "currency_symbol": "Simbolo valuta",
+ "currency_symbol_desc": "Scegli il simbolo per visualizzare i prezzi",
+ "currency_position": "Posizione valuta",
+ "currency_position_desc": "Scegli se il simbolo della valuta appare a sinistra o a destra dei numeri",
+ "expiring_soon_days": "Giorni di scadenza prossima",
+ "expiring_soon_days_desc": "Numero di giorni prima della scadenza della garanzia per contrassegnare come \"In scadenza\"",
+ "date_format": "Formato data",
+ "date_format_desc": "Scegli come vengono visualizzate le date",
+ "notification_settings": "Impostazioni notifiche",
+ "notification_channel": "Canale notifiche",
+ "notification_channel_desc": "Scegli come ricevere le notifiche",
+ "notification_disabled": "Disabilitato",
+ "notification_email": "Email",
+ "notification_apprise": "Apprise",
+ "notification_both": "Entrambi",
+ "email_settings": "Impostazioni email",
+ "notification_frequency": "Frequenza notifiche",
+ "notification_frequency_desc": "Quanto spesso ricevere notifiche email",
+ "daily": "Giornaliero",
+ "weekly": "Settimanale",
+ "monthly": "Mensile",
+ "notification_time": "Orario notifiche",
+ "time_of_day_notification": "Orario del giorno per ricevere notifiche (in formato 24 ore)",
+ "timezone": "Fuso orario",
+ "timezone_desc": "Il tuo fuso orario locale per le notifiche",
+ "apprise_settings": "Impostazioni Apprise",
+ "apprise_frequency": "Frequenza notifiche Apprise",
+ "apprise_frequency_desc": "Quanto spesso ricevere notifiche Apprise",
+ "apprise_time": "Orario notifiche Apprise",
+ "apprise_timezone": "Fuso orario Apprise",
+ "apprise_timezone_desc": "Il tuo fuso orario locale per le notifiche Apprise",
+ "paperless_settings": "Impostazioni Paperless-ngx",
+ "paperless_desc": "Integrazione con Paperless-ngx per la gestione dei documenti",
+ "enable_paperless": "Abilita Paperless-ngx",
+ "paperless_url": "URL Paperless-ngx",
+ "paperless_api_token": "Token API Paperless-ngx",
+ "paperless_view_in_app": "Visualizza nell'app",
+ "test_paperless": "Testa connessione",
+ "apprise_notifications": "Notifiche Apprise",
+ "apprise_desc": "Configura Apprise per le notifiche push",
+ "apprise_notification_mode": "Modalità notifica",
+ "apprise_warranty_scope": "Ambito garanzie",
+ "apprise_url": "URL Apprise",
+ "test_apprise": "Testa Apprise",
+ "security": "Sicurezza",
+ "change_password": "Cambia password",
+ "change_password_desc": "Aggiorna la tua password",
+ "current_password": "Password attuale",
+ "new_password": "Nuova password",
+ "confirm_password": "Conferma password",
+ "admin_settings": "Impostazioni amministratore",
+ "admin_actions": "Azioni amministratore",
+ "refresh_data": "Aggiorna dati",
+ "check_admin_status": "Controlla stato amministratore",
+ "show_users_list": "Mostra elenco utenti",
+ "test_api": "Testa API",
+ "oidc_configuration": "Configurazione OIDC",
+ "enable_oidc": "Abilita OIDC",
+ "client_id": "ID cliente",
+ "client_secret": "Segreto cliente",
+ "issuer_url": "URL emittente",
+ "scope": "Ambito",
+ "save_preferences": "Salva preferenze",
+ "account_settings": "Impostazioni Account",
+ "current_user": "Modifica Profilo per:",
+ "your_email": "La tua email:",
+ "currency": "Valuta",
+ "timezone": "Fuso Orario",
+ "date_format": "Formato Data",
+ "save_changes": "Salva Modifiche",
+ "change": "Cambia",
+ "update_password": "Aggiorna Password",
+ "cancel": "Annulla",
+ "danger_zone": "Zona Pericolosa",
+ "delete_account": "Elimina Account",
+ "delete_account_desc": "Elimina permanentemente il tuo account e tutti i dati",
+ "send_notifications": "Invia Notifiche Garanzie",
+ "check_scheduler": "Controlla Stato Scheduler",
+ "site_settings": "Impostazioni Sito",
+ "registration_enabled": "Registrazione Abilitata",
+ "registration_enabled_desc": "Consenti ai nuovi utenti di registrarsi",
+ "email_base_url": "URL Base Email",
+ "global_view_enabled": "Vista Globale Abilitata",
+ "global_view_admin_only": "Vista Globale Solo Admin",
+ "save_site_settings": "Salva Impostazioni Sito",
+ "oidc_provider_name": "Nome Provider OIDC",
+ "save_oidc_settings": "Salva Impostazioni OIDC",
+ "api_token": "Token API",
+ "view_documents": "Visualizza Documenti in Warracker",
+ "connection_testing": "Test Connessione",
+ "enable_apprise": "Abilita Notifiche Apprise",
+ "loading": "Caricamento...",
+ "paperless_ngx_settings": "Impostazioni Paperless-ngx",
+ "paperless_ngx_desc": "Configura integrazione con sistema di gestione documenti Paperless-ngx",
+ "enable_paperless": "Abilita Integrazione Paperless-ngx",
+ "paperless_url_desc": "URL base della tua istanza Paperless-ngx",
+ "paperless_token": "Token API",
+ "paperless_token_desc": "Il tuo token di autenticazione API Paperless-ngx",
+ "paperless_view_in_app_desc": "Apri documenti nell'app invece che in una nuova scheda",
+ "apprise_url_desc": "URL del tuo servizio di notifica Apprise",
+ "apprise_mode": "Modalità Notifica",
+ "apprise_mode_desc": "Scegli quando inviare notifiche Apprise",
+ "apprise_warranty_scope_desc": "Scegli quali garanzie includere nelle notifiche",
+ "all_warranties": "Tutte le Garanzie",
+ "personal_warranties": "Solo Garanzie Personali",
+ "save_notification_settings": "Salva Impostazioni Notifiche",
+ "first_name": "Nome",
+ "last_name": "Cognome",
+ "email": "Email",
+ "save_profile": "Salva profilo"
+ },
+ "warranties": {
+ "title": "Garanzie",
+ "title_global": "Garanzie di Tutti gli Utenti",
+ "add_new": "Aggiungi Nuova Garanzia",
+ "edit": "Modifica Garanzia",
+ "delete": "Elimina Garanzia",
+ "product_name": "Nome Prodotto",
+ "purchase_date": "Data di Acquisto",
+ "warranty_duration": "Durata Garanzia",
+ "years": "Anni",
+ "months": "Mesi",
+ "days": "Giorni",
+ "vendor": "Fornitore",
+ "serial_numbers": "Numeri di Serie",
+ "purchase_price": "Prezzo di Acquisto",
+ "notes": "Note",
+ "tags": "Tag",
+ "status": "Stato",
+ "expiration_date": "Data di Scadenza",
+ "active": "Attiva",
+ "expired": "Scaduta",
+ "expiring_soon": "In Scadenza",
+ "lifetime": "A vita",
+ "no_warranties": "Nessuna garanzia ancora. Aggiungi la tua prima garanzia per iniziare.",
+ "search_placeholder": "Cerca per nome, fornitore, note, tag o numero di serie...",
+ "warranty_type": "Tipo di Garanzia",
+ "other_document": "Altro Documento",
+ "product": "Prodotto",
+ "expiration": "Scadenza",
+ "actions": "Azioni",
+ "no_warranties_title": "Nessuna garanzia",
+ "no_warranties_desc": "Non hai ancora garanzie. Aggiungi la tua prima garanzia!",
+ "add_warranty": "Aggiungi garanzia",
+ "warranty_entry_method": "Metodo inserimento garanzia",
+ "warranty_duration_option": "Durata garanzia",
+ "exact_expiration_option": "Data di scadenza esatta",
+ "warranty_period": "Periodo di garanzia",
+ "expiration_date_label": "Data di Scadenza",
+ "currency": "Valuta",
+ "add_tags": "Aggiungi Tag",
+ "add_tags_desc": "I tag ti aiutano a organizzare e filtrare le tue garanzie",
+ "save_changes": "Salva modifiche",
+ "confirm_delete": "Conferma eliminazione",
+ "manage_tags": "Gestisci tag",
+ "add_tag": "Aggiungi tag",
+ "unknown_status": "Stato sconosciuto",
+ "expiring_soon_days": "In scadenza ({{days}} {{dayText}})",
+ "days_remaining": "{{count}} giorni rimanenti",
+ "day_one": "giorno",
+ "day_other": "giorni",
+ "month_one": "mese",
+ "month_other": "mesi",
+ "year_one": "anno",
+ "year_other": "anni",
+ "na": "N/D",
+ "age": "Età",
+ "warranty": "Garanzia",
+ "warranty_ends": "Garanzia termina",
+ "price": "Prezzo",
+ "serial_number": "Numero di serie",
+ "type": "Tipo",
+ "owner": "Proprietario",
+ "product_website": "Sito web prodotto",
+ "notes": "Note",
+ "existing_tags": "Tag Esistenti",
+ "edit_warranty": "Modifica Garanzia",
+ "warranty_type_standard": "Standard",
+ "warranty_type_extended": "Estesa",
+ "warranty_type_manufacturer": "Produttore",
+ "warranty_type_third_party": "Terze Parti",
+ "warranty_type_store": "Negozio",
+ "warranty_type_premium": "Premium",
+ "warranty_type_limited": "Limitata",
+ "warranty_type_full": "Completa",
+ "warranty_type_parts_only": "Solo Parti",
+ "warranty_type_labor_only": "Solo Manodopera",
+ "warranty_type_international": "Internazionale",
+ "warranty_type_accidental_damage": "Danni Accidentali",
+ "warranty_type_other": "Altro (Personalizzato)",
+ "warranty_type_custom_placeholder": "Inserisci tipo di garanzia personalizzato",
+ "notes_placeholder": "Note aggiuntive su questa garanzia...",
+ "tags_help_text": "I tag ti aiutano a organizzare e filtrare le tue garanzie",
+ "search_add_tag_placeholder": "Cerca o aggiungi nuovo tag...",
+ "upload_new_file_replace": "Carica un nuovo file per sostituire",
+ "current_other_document": "Documento attuale",
+ "no_other_document_uploaded": "Nessun altro documento caricato",
+ "other_document_will_be_deleted": "L'altro documento verrà eliminato al salvataggio",
+ "files_optional": "File (ZIP/RAR, Opzionale)",
+ "invoice_receipt_short": "Fattura",
+ "product_manual_short": "Manuale",
+ "files_short": "File",
+ "summary": "Riepilogo",
+ "product_url_optional": "URL Prodotto (Opzionale)",
+ "enter_serial_number": "Inserisci numero di serie",
+ "vendor_optional": "Fornitore (Opzionale)",
+ "vendor_placeholder": "es. Amazon, Best Buy, ecc.",
+ "lifetime_warranty": "Garanzia a Vita",
+ "warranty_type_optional": "Tipo di Garanzia (Opzionale)",
+ "select_warranty_type": "Seleziona tipo di garanzia...",
+ "standard": "Standard",
+ "extended": "Estesa",
+ "manufacturer": "Produttore",
+ "third_party": "Terze Parti",
+ "store": "Negozio",
+ "premium": "Premium",
+ "limited": "Limitata",
+ "full": "Completa",
+ "parts_only": "Solo Parti",
+ "labor_only": "Solo Manodopera",
+ "international": "Internazionale",
+ "accidental_damage": "Danni Accidentali",
+ "other_custom": "Altro (Personalizzato)",
+ "enter_custom_warranty_type": "Inserisci tipo di garanzia personalizzato",
+ "purchase_price_optional": "Prezzo di Acquisto (Opzionale)",
+ "notes_optional": "Note (Opzionali)",
+ "add_any_notes": "Aggiungi note su questa garanzia...",
+ "product_photo_optional": "Foto Prodotto (Opzionale)",
+ "choose_photo": "Scegli Foto",
+ "invoice_receipt": "Fattura/Ricevuta",
+ "store_locally": "Memorizza Localmente",
+ "store_in_paperless": "Memorizza in Paperless-ngx",
+ "choose_file": "Scegli File",
+ "browse_paperless": "Sfoglia Documenti Paperless-ngx",
+ "product_manual_optional": "Manuale Prodotto (Opzionale)",
+ "files_zip_rar_optional": "File (ZIP/RAR, Opzionale)",
+ "search_or_add_tag": "Cerca o aggiungi nuovo tag...",
+ "product_information": "Informazioni Prodotto",
+ "product_url": "URL Prodotto",
+ "warranty_details": "Dettagli Garanzia",
+ "product_photo": "Foto Prodotto",
+ "product_manual": "Manuale Prodotto",
+ "files": "File",
+ "documents": "Documenti",
+ "selected_tags": "Tag Selezionati",
+ "previous_tab": "Precedente",
+ "next_tab": "Successivo",
+ "delete_photo": "Elimina Foto",
+ "delete_invoice": "Elimina Fattura",
+ "delete_manual": "Elimina Manuale",
+ "delete_files": "Elimina File",
+ "current_photo": "Foto attuale:",
+ "current_invoice": "Fattura attuale:",
+ "current_manual": "Manuale attuale:",
+ "current_document": "Documento attuale:",
+ "upload_new_photo_replace": "(Carica una nuova foto per sostituire)",
+ "no_photo_uploaded": "Nessuna foto caricata",
+ "no_invoice_uploaded": "Nessuna fattura caricata",
+ "no_manual_uploaded": "Nessun manuale caricato",
+ "no_document_uploaded": "Nessun altro documento caricato",
+ "photo_will_be_deleted": "La foto verrà eliminata al salvataggio",
+ "invoice_will_be_deleted": "La fattura verrà eliminata al salvataggio",
+ "manual_will_be_deleted": "Il manuale verrà eliminato al salvataggio",
+ "document_will_be_deleted": "L'altro documento verrà eliminato al salvataggio",
+ "confirm_delete_message": "Sei sicuro di voler eliminare questa garanzia? Questa azione non può essere annullata.",
+ "new_tag_name": "Nuovo nome tag",
+ "existing_tags": "Tag Esistenti",
+ "edit_warranty": "Modifica Garanzia",
+ "warranty_type_standard": "Standard",
+ "warranty_type_extended": "Estesa",
+ "warranty_type_manufacturer": "Produttore",
+ "warranty_type_third_party": "Terze Parti",
+ "warranty_type_store": "Negozio",
+ "warranty_type_premium": "Premium",
+ "warranty_type_limited": "Limitata",
+ "warranty_type_full": "Completa",
+ "parts_only": "Solo Parti",
+ "labor_only": "Solo Manodopera",
+ "international": "Internazionale",
+ "accidental_damage": "Danni Accidentali",
+ "warranty_type_other": "Altro (Personalizzato)",
+ "warranty_type_custom_placeholder": "Inserisci tipo di garanzia personalizzato",
+ "notes_placeholder": "Note aggiuntive su questa garanzia...",
+ "tags_help_text": "I tag ti aiutano a organizzare e filtrare le tue garanzie",
+ "search_add_tag_placeholder": "Cerca o aggiungi nuovo tag...",
+ "upload_new_file_replace": "Carica un nuovo file per sostituire",
+ "current_other_document": "Documento attuale",
+ "no_other_document_uploaded": "Nessun altro documento caricato",
+ "other_document_will_be_deleted": "L'altro documento verrà eliminato al salvataggio",
+ "files_optional": "File (ZIP/RAR, Opzionale)",
+ "invoice_receipt_short": "Fattura",
+ "product_manual_short": "Manuale",
+ "files_short": "File",
+ "enter_serial_number": "Inserisci numero di serie",
+ "add_serial_number": "Aggiungi un altro numero di serie",
+ "years_placeholder": "Anni",
+ "months_placeholder": "Mesi",
+ "days_placeholder": "Giorni",
+ "add_any_notes_placeholder": "Aggiungi note su questa garanzia..."
+ },
+ "actions": {
+ "save": "Salva",
+ "cancel": "Annulla",
+ "delete": "Elimina",
+ "edit": "Modifica",
+ "export": "Esporta",
+ "import": "Importa",
+ "refresh": "Aggiorna",
+ "search": "Cerca",
+ "clear": "Cancella",
+ "upload": "Carica",
+ "download": "Scarica",
+ "manage_tags": "Gestisci Tag",
+ "close": "Chiudi",
+ "save_changes": "Salva Modifiche"
+ },
+ "filters": {
+ "all_status": "Tutti gli Stati",
+ "all_tags": "Tutti i Tag",
+ "all_vendors": "Tutti i Fornitori",
+ "all_types": "Tutti i Tipi",
+ "sort_by": "Ordina Per",
+ "sort_expiration": "Data di Scadenza",
+ "sort_purchase": "Data di Acquisto",
+ "sort_age": "Età",
+ "sort_name": "Nome Prodotto",
+ "sort_vendor": "Fornitore",
+ "sort_warranty_type": "Tipo Garanzia",
+ "status": "Stato",
+ "tags": "Tag",
+ "vendor": "Fornitore",
+ "warranty_type": "Tipo garanzia",
+ "view": "Vista",
+ "scope": "Ambito"
+ },
+ "messages": {
+ "success": "Successo",
+ "error": "Errore",
+ "warning": "Avviso",
+ "loading": "Caricamento...",
+ "saved": "Modifiche salvate con successo",
+ "deleted": "Elemento eliminato con successo",
+ "confirm_delete": "Sei sicuro di voler eliminare questo elemento?",
+ "no_results": "Nessun risultato trovato",
+ "file_too_large": "File troppo grande",
+ "invalid_file_type": "Tipo di file non valido",
+ "fill_first_last_name": "Si prega di compilare Nome e Cognome",
+ "email_cannot_be_empty": "L'indirizzo email non può essere vuoto.",
+ "enter_valid_email": "Si prega di inserire un indirizzo email valido.",
+ "profile_updated_successfully": "Profilo aggiornato con successo",
+ "preferences_saved_successfully": "Preferenze salvate con successo.",
+ "fill_password_fields": "Si prega di compilare tutti i campi password",
+ "passwords_do_not_match": "Le nuove password non corrispondono",
+ "password_min_length": "La password deve essere lunga almeno 8 caratteri",
+ "type_delete_to_confirm": "Si prega di digitare DELETE per confermare",
+ "account_deleted_successfully": "Account eliminato con successo",
+ "account_cannot_delete_offline": "L'account non può essere eliminato in modalità offline",
+ "failed_delete_account": "Impossibile eliminare l'account. Si prega di riprovare.",
+ "user_updated_successfully": "Utente aggiornato con successo",
+ "user_deleted_successfully": "Utente eliminato con successo",
+ "user_id_missing": "ID utente mancante",
+ "failed_load_users": "Impossibile caricare gli utenti",
+ "error_loading_users": "Errore nel caricamento degli utenti",
+ "select_user_transfer_ownership": "Si prega di selezionare un utente a cui trasferire la proprietà",
+ "ownership_transferred_successfully": "Proprietà trasferita con successo! Aggiornamento della pagina...",
+ "failed_load_site_settings": "Impossibile caricare le impostazioni del sito. Si prega di riprovare.",
+ "invalid_email_base_url": "Formato URL base email non valido. Dovrebbe iniziare con http:// o https://",
+ "no_site_settings_to_save": "Nessuna impostazione del sito da salvare.",
+ "site_settings_saved_successfully": "Impostazioni del sito salvate con successo",
+ "failed_save_site_settings": "Impossibile salvare le impostazioni del sito",
+ "oidc_settings_saved_successfully": "Impostazioni OIDC salvate con successo.",
+ "failed_save_oidc_settings": "Impossibile salvare le impostazioni OIDC.",
+ "api_endpoint_accessible": "L'endpoint API è accessibile",
+ "api_endpoint_not_accessible": "L'endpoint API non è accessibile. Stato: ",
+ "only_admins_send_notifications": "Solo gli amministratori possono inviare notifiche di garanzia",
+ "notifications_triggered_successfully": "Notifiche attivate con successo",
+ "notification_settings_saved_successfully": "Impostazioni di notifica salvate con successo",
+ "apprise_settings_saved_successfully": "Impostazioni Apprise salvate con successo",
+ "test_notification_sent_successfully": "Notifica di test inviata con successo",
+ "no_urls_to_validate": "Nessun URL da validare",
+ "paperless_settings_saved_successfully": "Impostazioni Paperless-ngx salvate con successo!",
+ "enter_valid_paperless_url": "Si prega di inserire un URL valido (es. https://paperless.tuodominio.com)",
+ "enter_paperless_url_first": "Si prega di inserire prima un URL Paperless-ngx",
+ "paperless_connection_test_successful": "Test di connessione Paperless-ngx riuscito!",
+ "paperless_connection_test_failed": "Test di connessione Paperless-ngx fallito",
+ "enter_api_token_test_connection": "Si prega di inserire un token API per testare la connessione",
+ "failed_load_user_data": "Impossibile caricare i dati utente. Si prega di riprovare.",
+ "could_not_connect_user_data": "Impossibile connettersi per recuperare i dati utente. Visualizzazione delle informazioni in cache.",
+ "preferences_saved_locally_failed_sync": "Preferenze salvate localmente, ma impossibile sincronizzare con il server: ",
+ "preferences_saved_locally": "Preferenze salvate localmente.",
+ "correct_errors_in_tab": "Si prega di correggere gli errori nella scheda evidenziata prima di continuare.",
+ "please_fill_out_this_field": "Si prega di compilare questo campo.",
+ "warranty_added_successfully": "Garanzia aggiunta con successo",
+ "tag_name_required": "Il nome del tag è richiesto",
+ "tag_creation_function_not_found": "Funzione di creazione tag non trovata",
+ "tag_created_successfully": "Tag creato con successo",
+ "tag_updated_successfully": "Tag aggiornato con successo",
+ "tag_deleted_successfully": "Tag eliminato con successo",
+ "failed_to_create_tag": "Errore nella creazione del tag",
+ "failed_to_update_tag": "Errore nell'aggiornamento del tag",
+ "failed_to_delete_tag": "Errore nell'eliminazione del tag"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية",
+ "ru": "Русский",
+ "uk": "Українська",
+ "zh_CN": "简体中文",
+ "zh_HK": "繁體中文",
+ "ja": "日本語",
+ "pt": "Português",
+ "ko": "한국어"
+ },
+ "status": {
+ "title": "Stato del Sistema",
+ "dashboard_title": "Dashboard Stato Garanzie",
+ "global_dashboard_title": "Dashboard Globale Stato Garanzie",
+ "overview": "Panoramica",
+ "statistics": "Statistiche",
+ "total_warranties": "Garanzie Totali",
+ "active_warranties": "Garanzie Attive",
+ "expiring_soon": "In Scadenza",
+ "expired_warranties": "Garanzie Scadute",
+ "warranty_distribution": "Distribuzione Garanzie",
+ "expiration_timeline": "Timeline Scadenze",
+ "recent_activity": "Attività Recente",
+ "recent_expirations": "Recentemente Scadute o In Scadenza",
+ "recent_expirations_empty": "Nessuna garanzia recentemente scaduta o in scadenza.",
+ "system_health": "Salute del Sistema",
+ "database_status": "Stato Database",
+ "connected": "Connesso",
+ "version": "Versione",
+ "uptime": "Tempo di Attività"
+ },
+ "about": {
+ "title": "Informazioni su Warracker",
+ "description": "Un sistema completo di gestione garanzie progettato per aiutarti a tracciare, organizzare e gestire tutte le garanzie dei tuoi prodotti in un'unica piattaforma sicura e facile da usare.",
+ "version": "Versione",
+ "update_status": "Stato Aggiornamenti",
+ "checking_updates": "Controllo aggiornamenti...",
+ "view_release_notes": "Visualizza Note di Rilascio",
+ "project_info": "Informazioni Progetto",
+ "project_description": "Warracker è un sistema di gestione garanzie open-source costruito con tecnologie web moderne. Fornisce un modo sicuro e intuitivo per gestire le garanzie dei prodotti, tracciare le date di scadenza e organizzare documenti importanti.",
+ "github_repository": "Repository GitHub",
+ "releases": "Rilasci",
+ "community_support": "Comunità e Supporto",
+ "community_description": "Unisciti alla nostra comunità per supporto, discussioni e aggiornamenti. Segnala bug, richiedi funzionalità o ottieni aiuto da altri utenti e contributori.",
+ "discord_community": "Comunità Discord",
+ "report_issues": "Segnala Problemi",
+ "developer_info": "Informazioni Sviluppatore",
+ "developer_description": "Warracker è sviluppato e mantenuto da Sassanix. Il progetto è open-source e accoglie contributi dalla comunità.",
+ "sassanix": "Sassanix",
+ "agpl_license": "Licenza AGPL-3.0",
+ "support_project": "Supporta il Progetto",
+ "support_description": "Se trovi Warracker utile, considera di supportare il suo sviluppo!",
+ "new_version_available": "Nuova versione {{version}} disponibile!",
+ "latest_version": "Stai usando l'ultima versione",
+ "update_check_failed": "Controllo aggiornamenti fallito",
+ "features": "Caratteristiche",
+ "feature_track": "Traccia garanzie prodotti",
+ "feature_notifications": "Ricevi notifiche di scadenza",
+ "feature_documents": "Archivia documenti garanzia",
+ "feature_reports": "Genera report garanzie",
+ "feature_tags": "Organizza con tag",
+ "feature_export": "Esporta dati garanzie",
+ "support": "Supporto",
+ "documentation": "Documentazione",
+ "github": "Repository GitHub",
+ "license": "Licenza",
+ "copyright": "Copyright",
+ "developed_by": "Sviluppato da"
+ }
+}
diff --git a/locales/ja/translation.json b/locales/ja/translation.json
new file mode 100644
index 0000000..dfd7cbf
--- /dev/null
+++ b/locales/ja/translation.json
@@ -0,0 +1,560 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "保証トラッカー",
+ "nav": {
+ "home": "ホーム",
+ "status": "ステータス",
+ "settings": "設定",
+ "about": "概要"
+ },
+ "auth": {
+ "login": "ログイン",
+ "logout": "ログアウト",
+ "register": "登録",
+ "username": "ユーザー名",
+ "password": "パスワード",
+ "email": "Eメール",
+ "first_name": "名",
+ "last_name": "姓",
+ "forgot_password": "パスワードをお忘れですか?",
+ "reset_password": "パスワードをリセット",
+ "confirm_password": "パスワードを確認",
+ "create_account_title": "アカウントを作成",
+ "first_name_optional": "名(任意)",
+ "last_name_optional": "姓(任意)",
+ "username_hint": "ユーザー名は一意である必要があり、ログインに使用されます。",
+ "email_address": "メールアドレス",
+ "toggle_password": "パスワードの表示/非表示",
+ "password_hint_simple": "パスワードは8文字以上で、大文字、小文字、数字を含む必要があります。",
+ "password_requirements": "パスワードの要件:",
+ "req_length": "8文字以上",
+ "req_uppercase": "大文字1文字以上",
+ "req_lowercase": "小文字1文字以上",
+ "req_number": "数字1文字以上",
+ "req_special": "特殊文字1文字以上",
+ "create_account": "アカウントを作成",
+ "already_have_account": "すでにアカウントをお持ちですか?",
+ "reset_password_title": "Warracker - パスワードをリセット",
+ "reset_your_password": "パスワードをリセット",
+ "reset_password_info": "以下にメールアドレスを入力してください。パスワードをリセットするためのリンクを送信します。",
+ "send_reset_link": "リセットリンクを送信",
+ "back_to_login": "ログインに戻る",
+ "set_new_password_title": "Warracker - 新しいパスワードを設定",
+ "set_new_password": "新しいパスワードを設定",
+ "new_password": "新しいパスワード",
+ "confirm_new_password": "新しいパスワードを確認",
+ "invalid_or_expired_link": "無効または期限切れのリンク",
+ "invalid_link_info": "クリックしたパスワードリセットリンクは無効または期限切れです。",
+ "request_new_reset_link": "新しいリセットリンクをリクエスト"
+ },
+ "warranties": {
+ "title": "あなたの保証",
+ "title_global": "すべてのユーザーの保証",
+ "add_new": "新しい保証を追加",
+ "edit": "保証を編集",
+ "delete": "保証を削除",
+ "product_name": "製品名",
+ "purchase_date": "購入日",
+ "warranty_duration": "保証期間",
+ "years": "年",
+ "months": "月",
+ "days": "日",
+ "vendor": "ベンダー",
+ "serial_numbers": "シリアル番号",
+ "purchase_price": "購入価格",
+ "notes": "メモ",
+ "tags": "タグ",
+ "status": "ステータス",
+ "expiration_date": "有効期限",
+ "active": "有効",
+ "expired": "期限切れ",
+ "expiring_soon": "まもなく期限切れ",
+ "lifetime": "生涯",
+ "no_warranties": "まだ保証はありません。最初の保証を追加して始めましょう。",
+ "search_placeholder": "名前、ベンダー、メモ、タグ、またはシリアル番号で検索...",
+ "warranty_type": "保証タイプ",
+ "other_document": "その他のドキュメント",
+ "product": "製品",
+ "expiration": "有効期限",
+ "actions": "アクション",
+ "no_warranties_title": "まだ保証はありません",
+ "no_warranties_desc": "最初の保証を追加して始めましょう",
+ "add_warranty": "保証を追加",
+ "warranty_entry_method": "保証入力方法",
+ "warranty_duration_option": "保証期間",
+ "exact_expiration_option": "正確な有効期限",
+ "warranty_period": "保証期間",
+ "expiration_date_label": "有効期限",
+ "currency": "通貨",
+ "add_tags": "タグを追加",
+ "add_tags_desc": "タグは保証の整理とフィルタリングに役立ちます",
+ "save_changes": "変更を保存",
+ "confirm_delete": "削除の確認",
+ "manage_tags": "タグを管理",
+ "add_tag": "タグを追加",
+ "unknown_status": "不明なステータス",
+ "expiring_soon_days": "まもなく期限切れ({{days}} {{dayText}})",
+ "days_remaining": "残り {{days}} {{dayText}}",
+ "day_one": "日",
+ "day_other": "日",
+ "month_one": "月",
+ "month_other": "月",
+ "year_one": "年",
+ "year_other": "年",
+ "na": "N/A",
+ "age": "経過期間",
+ "warranty": "保証",
+ "warranty_ends": "保証終了日",
+ "price": "価格",
+ "serial_number": "シリアル番号",
+ "vendor": "ベンダー",
+ "type": "タイプ",
+ "owner": "所有者",
+ "product_website": "製品ウェブサイト",
+ "documents": "ドキュメント",
+ "summary": "概要",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "年",
+ "months_placeholder": "月",
+ "days_placeholder": "日",
+ "add_any_notes_placeholder": "この保証に関するメモを追加...",
+ "product_url_optional": "製品URL(オプション)",
+ "enter_serial_number": "シリアル番号を入力",
+ "vendor_optional": "ベンダー(オプション)",
+ "vendor_placeholder": "例:Amazon、Best Buyなど",
+ "lifetime_warranty": "生涯保証",
+ "warranty_type_optional": "保証タイプ(オプション)",
+ "select_warranty_type": "保証タイプを選択...",
+ "standard": "標準",
+ "extended": "延長",
+ "manufacturer": "メーカー",
+ "third_party": "サードパーティ",
+ "store": "店舗",
+ "premium": "プレミアム",
+ "limited": "限定",
+ "full": "完全",
+ "parts_only": "部品のみ",
+ "labor_only": "作業のみ",
+ "international": "国際",
+ "accidental_damage": "偶発的損害",
+ "other_custom": "その他(カスタム)",
+ "enter_custom_warranty_type": "カスタム保証タイプを入力",
+ "purchase_price_optional": "購入価格(オプション)",
+ "notes_optional": "メモ(オプション)",
+ "add_any_notes": "この保証に関するメモを追加...",
+ "product_photo_optional": "製品写真(オプション)",
+ "choose_photo": "写真を選択",
+ "invoice_receipt": "請求書/領収書",
+ "store_locally": "ローカルに保存",
+ "store_in_paperless": "Paperless-ngxに保存",
+ "choose_file": "ファイルを選択",
+ "browse_paperless": "Paperless-ngxドキュメントを閲覧",
+ "product_manual_optional": "製品マニュアル(オプション)",
+ "files_zip_rar_optional": "ファイル(ZIP/RAR、オプション)",
+ "search_or_add_new_tag": "新しいタグを検索または追加...",
+ "product_information": "製品情報",
+ "product_url": "製品URL",
+ "warranty_details": "保証の詳細",
+ "product_photo": "製品写真",
+ "product_manual": "製品マニュアル",
+ "files": "ファイル",
+ "selected_tags": "選択されたタグ",
+ "previous_tab": "前へ",
+ "next_tab": "次へ",
+ "delete_photo": "写真を削除",
+ "delete_invoice": "請求書を削除",
+ "delete_manual": "マニュアルを削除",
+ "delete_files": "ファイルを削除",
+ "current_photo": "現在の写真:",
+ "current_invoice": "現在の請求書:",
+ "current_manual": "現在のマニュアル:",
+ "current_document": "現在のドキュメント:",
+ "upload_new_photo_replace": "(新しい写真をアップロードして置き換える)",
+ "no_photo_uploaded": "写真がアップロードされていません",
+ "no_invoice_uploaded": "請求書がアップロードされていません",
+ "no_manual_uploaded": "マニュアルがアップロードされていません",
+ "no_document_uploaded": "その他のドキュメントがアップロードされていません",
+ "photo_will_be_deleted": "保存時に写真は削除されます",
+ "invoice_will_be_deleted": "保存時に請求書は削除されます",
+ "manual_will_be_deleted": "保存時にマニュアルは削除されます",
+ "document_will_be_deleted": "保存時にその他のドキュメントは削除されます",
+ "confirm_delete_message": "この保証を削除してもよろしいですか?この操作は元に戻せません。",
+ "new_tag_name": "新しいタグ名",
+ "existing_tags": "既存のタグ",
+ "edit_warranty": "保証を編集",
+ "warranty_type_standard": "標準",
+ "warranty_type_extended": "延長",
+ "warranty_type_manufacturer": "メーカー",
+ "warranty_type_third_party": "サードパーティ",
+ "warranty_type_store": "店舗",
+ "warranty_type_premium": "プレミアム",
+ "warranty_type_limited": "限定",
+ "warranty_type_full": "完全",
+ "warranty_type_parts_only": "部品のみ",
+ "warranty_type_labor_only": "作業のみ",
+ "warranty_type_international": "国際",
+ "warranty_type_accidental_damage": "偶発的損害",
+ "warranty_type_other": "その他(カスタム)",
+ "warranty_type_custom_placeholder": "カスタム保証タイプを入力",
+ "notes_placeholder": "この保証に関する追加のメモ...",
+ "tags_help_text": "タグは保証の整理とフィルタリングに役立ちます",
+ "search_add_tag_placeholder": "新しいタグを検索または追加...",
+ "upload_new_file_replace": "新しいファイルをアップロードして置き換える",
+ "current_other_document": "現在のその他のドキュメント",
+ "no_other_document_uploaded": "その他のドキュメントがアップロードされていません",
+ "other_document_will_be_deleted": "保存時にその他のドキュメントは削除されます",
+ "files_optional": "ファイル(ZIP/RAR、オプション)",
+ "invoice_receipt_short": "請求書",
+ "product_manual_short": "マニュアル",
+ "files_short": "ファイル",
+ "enter_serial_number": "シリアル番号を入力",
+ "add_serial_number": "別のシリアル番号を追加"
+ },
+ "settings": {
+ "title": "設定",
+ "account_settings": "アカウント設定",
+ "preferences": "環境設定",
+ "language": "言語",
+ "select_language": "言語を選択",
+ "dark_mode": "ダークモード",
+ "dark_mode_desc": "ライトテーマとダークテーマを切り替える",
+ "currency": "通貨",
+ "timezone": "タイムゾーン",
+ "date_format": "日付形式",
+ "expiring_soon_days": "まもなく期限切れの日数",
+ "save_changes": "変更を保存",
+ "current_user": "プロファイル編集中:",
+ "your_email": "あなたのEメール:",
+ "first_name": "名",
+ "last_name": "姓",
+ "email": "Eメール",
+ "save_profile": "変更を保存",
+ "default_view": "デフォルトビュー",
+ "default_view_desc": "保証の優先ビューを選択",
+ "grid_view": "グリッドビュー",
+ "list_view": "リストビュー",
+ "table_view": "テーブルビュー",
+ "currency_symbol": "通貨記号",
+ "currency_symbol_desc": "価格に表示する記号を選択",
+ "currency_position": "通貨の位置",
+ "currency_position_desc": "通貨記号を数字の左または右に表示するかを選択",
+ "expiring_soon_days_desc": "警告を表示する有効期限までの日数",
+ "date_format_desc": "日付の表示方法を選択",
+ "save_preferences": "環境設定を保存",
+ "notification_settings": "通知設定",
+ "notification_channel": "通知チャネル",
+ "notification_channel_desc": "通知の受信方法を選択",
+ "notification_disabled": "無効",
+ "notification_email": "Eメール",
+ "notification_apprise": "Apprise",
+ "notification_both": "両方",
+ "email_settings": "Eメール設定",
+ "notification_frequency": "通知頻度",
+ "notification_frequency_desc": "Eメール通知の受信頻度",
+ "daily": "毎日",
+ "weekly": "毎週",
+ "monthly": "毎月",
+ "notification_time": "通知時間",
+ "timezone_desc": "通知用のローカルタイムゾーン",
+ "apprise_settings": "Apprise設定",
+ "apprise_frequency": "Apprise通知頻度",
+ "apprise_frequency_desc": "Apprise通知の受信頻度",
+ "apprise_time": "Apprise通知時間",
+ "apprise_timezone": "Appriseタイムゾーン",
+ "apprise_timezone_desc": "Apprise通知用のローカルタイムゾーン",
+ "save_notification_settings": "通知設定を保存",
+ "security": "セキュリティ",
+ "change_password": "パスワードを変更",
+ "change_password_desc": "アカウントのパスワードを更新",
+ "change": "変更",
+ "current_password": "現在のパスワード",
+ "new_password": "新しいパスワード",
+ "confirm_password": "新しいパスワードを確認",
+ "update_password": "パスワードを更新",
+ "cancel": "キャンセル",
+ "danger_zone": "危険区域",
+ "delete_account": "アカウントを削除",
+ "delete_account_desc": "アカウントとすべてのデータを永久に削除",
+ "admin_settings": "管理者設定",
+ "admin_actions": "管理者アクション",
+ "refresh_data": "データを更新",
+ "check_admin_status": "管理者ステータスを確認",
+ "show_users_list": "ユーザーリストを表示",
+ "test_api": "APIをテスト",
+ "send_notifications": "保証通知を送信",
+ "check_scheduler": "スケジューラーステータスを確認",
+ "site_settings": "サイト設定",
+ "registration_enabled": "登録を有効にする",
+ "registration_enabled_desc": "新規ユーザーの登録を許可",
+ "email_base_url": "EメールベースURL",
+ "global_view_enabled": "グローバルビューを有効にする",
+ "global_view_admin_only": "グローバルビューは管理者のみ",
+ "save_site_settings": "サイト設定を保存",
+ "oidc_configuration": "OIDC SSO設定",
+ "enable_oidc": "OIDC SSOを有効にする",
+ "oidc_provider_name": "OIDCプロバイダー名",
+ "client_id": "クライアントID",
+ "client_secret": "クライアントシークレット",
+ "issuer_url": "発行者URL",
+ "scope": "スコープ",
+ "save_oidc_settings": "OIDC設定を保存",
+ "oidc_sso_desc": "ユーザーがOIDCプロバイダー経由でログインできるようにする。",
+ "oidc_only_mode": "OIDCのみのログインモード",
+ "oidc_only_mode_desc": "従来のユーザー名/パスワードログインフォームを非表示にし、OIDCログインのみを許可します。<strong>警告:</strong>このオプションを有効にする前に、OIDCが正しく設定されていることを確認してください。",
+ "oidc_provider_name_desc": "OIDCクライアントの内部名(例:「oidc」)。",
+ "client_secret_desc": "機密情報。データベースに保存されます。変更を有効にするにはアプリケーションの再起動が必要です。",
+ "issuer_url_desc": "OIDCプロバイダーのベースURL。",
+ "scope_desc": "スペースで区切られたOIDCスコープ。",
+ "oidc_restart_message": "OIDC設定を完全に有効にするには、アプリケーションの再起動が必要です。",
+ "api_token": "APIトークン",
+ "view_documents": "Warrackerでドキュメントを表示",
+ "connection_testing": "接続テスト",
+ "apprise_notifications": "Apprise通知",
+ "enable_apprise": "Apprise通知を有効にする",
+ "loading": "読み込み中...",
+ "time_of_day_notification": "通知を受信する時間(24時間形式)",
+ "paperless_ngx_settings": "Paperless-ngx設定",
+ "paperless_ngx_about_title": "Paperless-ngx統合について:",
+ "paperless_ngx_about_desc": "このオプション機能により、保証ドキュメントをローカルではなく、自己ホスト型のPaperless-ngxインスタンスに保存できます。有効にすると、ユーザーは各ドキュメントをローカルまたはPaperless-ngxに保存するかを選択できます。",
+ "paperless_ngx_desc": "Paperless-ngxドキュメント管理システムとの統合を設定",
+ "enable_paperless": "Paperless-ngx統合を有効にする",
+ "paperless_url": "Paperless-ngx URL",
+ "paperless_url_desc": "Paperless-ngxインスタンスのベースURL",
+ "paperless_token": "APIトークン",
+ "paperless_token_desc": "Paperless-ngx API認証トークン",
+ "paperless_token_desc_generate": "Paperless-ngxインスタンスからAPIトークンを生成します(設定→APIトークン)。",
+ "paperless_view_in_app": "アプリ内でドキュメントを表示",
+ "paperless_view_in_app_desc": "新しいタブではなくアプリ内でドキュメントを開く",
+ "debug_config": "デバッグ設定",
+ "test_upload": "アップロードをテスト",
+ "save_paperless_settings": "Paperless-ngx設定を保存",
+ "apprise_desc": "複数のサービスへの高度な通知配信のためにAppriseを設定",
+ "apprise_desc_system_wide": "システム全体でApprise通知を有効または無効にする",
+ "apprise_not_available_title": "Appriseは利用できません:",
+ "apprise_not_available_desc": "Apprise通知ライブラリがインストールされていないか、利用できません。通知機能は無効になっています。",
+ "apprise_url": "Apprise URL",
+ "apprise_url_desc": "Apprise通知サービスURL",
+ "apprise_mode": "通知モード",
+ "apprise_mode_desc": "Apprise通知を送信するタイミングを選択",
+ "apprise_mode_global": "グローバルサマリー",
+ "apprise_mode_individual": "ユーザーごと",
+ "test_paperless": "Paperless接続をテスト",
+ "test_apprise": "Apprise接続をテスト",
+ "apprise_warranty_scope": "保証範囲",
+ "apprise_warranty_scope_desc": "通知に含める保証を選択",
+ "all_warranties": "すべての保証",
+ "personal_warranties": "個人保証のみ",
+ "all_users_warranties": "すべてのユーザーの保証",
+ "admin_warranties_only": "管理者保証のみ",
+ "apprise_notification_days": "通知日数",
+ "apprise_notification_days_desc": "有効期限の何日前に通知を送信するか(カンマ区切り、例:「7,30」は7日前と30日前)",
+ "apprise_check_frequency": "チェック頻度",
+ "apprise_check_frequency_desc": "システムが期限切れの保証をチェックする頻度(グローバル設定)",
+ "apprise_title_prefix": "メッセージタイトルのプレフィックス",
+ "apprise_title_prefix_desc": "通知タイトルに追加されるプレフィックス(例:「[Warracker]」は「[Warracker] 保証期限切れ間近」になります)",
+ "apprise_test_url": "テストURL(オプション)",
+ "apprise_test_url_desc": "オプション:テスト通知のみを送信するためのURL(メイン設定には保存されません)",
+ "save_apprise_settings": "Apprise設定を保存",
+ "validate_urls": "URLを検証",
+ "send_expiration_notifications_now": "有効期限通知を今すぐ送信",
+ "apprise_current_status": "現在のステータス",
+ "apprise_urls_configured": "設定されたURL:",
+ "apprise_supported_services": "サポートされているサービス",
+ "apprise_supported_services_desc": "Appriseは、Discord、Slack、Telegram、Eメール(Gmail、Outlook)、Webhooks、Microsoft Teams、Matrix、Pushover、Ntfy、Gotifyなど、80以上の通知サービスをサポートしています。",
+ "view_full_list_of_supported_services": "サポートされているサービスの完全なリストを表示",
+ "ownership_management": "所有権管理",
+ "transfer_ownership": "所有権を譲渡",
+ "warning_title": "警告:",
+ "transfer_ownership_warning": "アプリケーションの所有権を別の管理者ユーザーに譲渡します。この操作は元に戻せません。",
+ "transfer_ownership_desc": "所有権が譲渡されると、あなたは通常の管理者になり、新しい所有者がアプリケーションの最終的な制御権を持ちます。",
+ "select_new_owner": "新しい所有者を選択(管理者である必要があります)",
+ "select_admin_user": "管理者ユーザーを選択...",
+ "transfer_ownership_button": "所有権を譲渡",
+ "transfer_ownership_irreversible": "この操作は元に戻せません。",
+ "transfer_ownership_confirmation": "アプリケーションの所有権を譲渡しようとしています",
+ "after_this_transfer": "この譲渡後:",
+ "transfer_ownership_consequence_1": "あなたは通常の管理者になります",
+ "transfer_ownership_consequence_2": "新しい所有者がアプリケーションの最終的な制御権を持ちます",
+ "transfer_ownership_consequence_3": "新しい所有者のみが再度所有権を譲渡できます",
+ "transfer_ownership_type_to_confirm": "確認するには、以下のフィールドに「TRANSFER」と入力してください:"
+ },
+ "actions": {
+ "save": "保存",
+ "cancel": "キャンセル",
+ "delete": "削除",
+ "edit": "編集",
+ "export": "エクスポート",
+ "import": "インポート",
+ "refresh": "更新",
+ "search": "検索",
+ "clear": "クリア",
+ "upload": "アップロード",
+ "download": "ダウンロード",
+ "manage_tags": "タグを管理",
+ "close": "閉じる",
+ "save_changes": "変更を保存"
+ },
+ "filters": {
+ "all_status": "すべてのステータス",
+ "all_tags": "すべてのタグ",
+ "all_vendors": "すべてのベンダー",
+ "all_types": "すべてのタイプ",
+ "sort_by": "並べ替え",
+ "sort_expiration": "有効期限",
+ "sort_purchase": "購入日",
+ "sort_age": "経過期間",
+ "sort_name": "製品名",
+ "sort_vendor": "ベンダー",
+ "sort_warranty_type": "保証タイプ",
+ "status": "ステータス",
+ "tags": "タグ",
+ "vendor": "ベンダー",
+ "warranty_type": "保証タイプ",
+ "view": "ビュー",
+ "scope": "範囲"
+ },
+ "messages": {
+ "success": "成功",
+ "error": "エラー",
+ "warning": "警告",
+ "loading": "読み込み中...",
+ "saved": "変更が正常に保存されました",
+ "deleted": "アイテムが正常に削除されました",
+ "confirm_delete": "このアイテムを削除してもよろしいですか?",
+ "no_results": "結果が見つかりません",
+ "file_too_large": "ファイルが大きすぎます",
+ "invalid_file_type": "無効なファイルタイプ",
+ "fill_first_last_name": "姓名を入力してください",
+ "email_cannot_be_empty": "メールアドレスを空にすることはできません。",
+ "enter_valid_email": "有効なメールアドレスを入力してください。",
+ "profile_updated_successfully": "プロファイルが正常に更新されました",
+ "preferences_saved_successfully": "環境設定が正常に保存されました。",
+ "fill_password_fields": "すべてのパスワードフィールドを入力してください",
+ "passwords_do_not_match": "新しいパスワードが一致しません",
+ "password_min_length": "パスワードは8文字以上である必要があります",
+ "type_delete_to_confirm": "確認のためにDELETEと入力してください",
+ "account_deleted_successfully": "アカウントが正常に削除されました",
+ "account_cannot_delete_offline": "オフラインモードではアカウントを削除できません",
+ "failed_delete_account": "アカウントの削除に失敗しました。もう一度お試しください。",
+ "user_updated_successfully": "ユーザーが正常に更新されました",
+ "user_deleted_successfully": "ユーザーが正常に削除されました",
+ "user_id_missing": "ユーザーIDが不足しています",
+ "failed_load_users": "ユーザーの読み込みに失敗しました",
+ "error_loading_users": "ユーザーの読み込み中にエラーが発生しました",
+ "select_user_transfer_ownership": "所有権を譲渡するユーザーを選択してください",
+ "ownership_transferred_successfully": "所有権が正常に譲渡されました!ページを更新中...",
+ "failed_load_site_settings": "サイト設定の読み込みに失敗しました。もう一度お試しください。",
+ "invalid_email_base_url": "無効なメールベースURL形式です。http://またはhttps://で始まる必要があります",
+ "no_site_settings_to_save": "保存するサイト設定がありません。",
+ "site_settings_saved_successfully": "サイト設定が正常に保存されました",
+ "failed_save_site_settings": "サイト設定の保存に失敗しました",
+ "oidc_settings_saved_successfully": "OIDC設定が正常に保存されました。",
+ "failed_save_oidc_settings": "OIDC設定の保存に失敗しました。",
+ "api_endpoint_accessible": "APIエンドポイントにアクセス可能です",
+ "api_endpoint_not_accessible": "APIエンドポイントにアクセスできません。ステータス:",
+ "only_admins_send_notifications": "管理者のみが保証通知を送信できます",
+ "notifications_triggered_successfully": "通知が正常にトリガーされました",
+ "notification_settings_saved_successfully": "通知設定が正常に保存されました",
+ "apprise_settings_saved_successfully": "Apprise設定が正常に保存されました",
+ "test_notification_sent_successfully": "テスト通知が正常に送信されました",
+ "no_urls_to_validate": "検証するURLがありません",
+ "paperless_settings_saved_successfully": "Paperless-ngx設定が正常に保存されました!",
+ "enter_valid_paperless_url": "有効なURLを入力してください(例:https://paperless.yourdomain.com)",
+ "enter_paperless_url_first": "最初にPaperless-ngx URLを入力してください",
+ "paperless_connection_test_successful": "Paperless-ngx接続テストが成功しました!",
+ "paperless_connection_test_failed": "Paperless-ngx接続テストが失敗しました",
+ "enter_api_token_test_connection": "接続をテストするためにAPIトークンを入力してください",
+ "failed_load_user_data": "ユーザーデータの読み込みに失敗しました。もう一度お試しください。",
+ "could_not_connect_user_data": "ユーザーデータを取得するために接続できませんでした。キャッシュ情報を表示しています。",
+ "preferences_saved_locally_failed_sync": "環境設定はローカルに保存されましたが、サーバーとの同期に失敗しました:",
+ "preferences_saved_locally": "環境設定がローカルに保存されました。",
+ "correct_errors_in_tab": "続行する前に、ハイライトされたタブのエラーを修正してください。",
+ "please_fill_out_this_field": "このフィールドを入力してください。",
+ "warranty_added_successfully": "保証が正常に追加されました",
+ "tag_name_required": "タグ名は必須です",
+ "tag_creation_function_not_found": "タグ作成機能が見つかりません",
+ "tag_created_successfully": "タグが正常に作成されました",
+ "tag_updated_successfully": "タグが正常に更新されました",
+ "tag_deleted_successfully": "タグが正常に削除されました",
+ "failed_to_create_tag": "タグの作成に失敗しました",
+ "failed_to_update_tag": "タグの更新に失敗しました",
+ "failed_to_delete_tag": "タグの削除に失敗しました"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية",
+ "ru": "Русский",
+ "uk": "Українська",
+ "zh_CN": "简体中文",
+ "zh_HK": "繁體中文",
+ "ja": "日本語",
+ "pt": "Português"
+ },
+ "status": {
+ "title": "システムステータス",
+ "dashboard_title": "保証ステータスダッシュボード",
+ "global_dashboard_title": "グローバル保証ステータスダッシュボード",
+ "overview": "概要",
+ "statistics": "統計",
+ "total_warranties": "総保証数",
+ "active_warranties": "有効な保証",
+ "expiring_soon": "まもなく期限切れ",
+ "expired_warranties": "期限切れの保証",
+ "warranty_distribution": "保証の分布",
+ "expiration_timeline": "有効期限タイムライン",
+ "recent_activity": "最近のアクティビティ",
+ "recent_expirations": "最近期限切れまたはまもなく期限切れ",
+ "recent_expirations_empty": "最近期限切れまたはまもなく期限切れの保証はありません。",
+ "system_health": "システムヘルス",
+ "database_status": "データベースステータス",
+ "connected": "接続済み",
+ "version": "バージョン",
+ "uptime": "稼働時間"
+ },
+ "about": {
+ "title": "Warrackerについて",
+ "description": "すべての製品保証を1つの安全で使いやすいプラットフォームで追跡、整理、管理するのに役立つ包括的な保証管理システム。",
+ "version": "バージョン",
+ "update_status": "更新ステータス",
+ "checking_updates": "更新を確認中...",
+ "view_release_notes": "リリースノートを表示",
+ "project_info": "プロジェクト情報",
+ "project_description": "Warrackerは、最新のWeb技術で構築されたオープンソースの保証管理システムです。製品保証の管理、有効期限の追跡、重要書類の整理を安全かつ直感的に行う方法を提供します。",
+ "github_repository": "GitHubリポジトリ",
+ "releases": "リリース",
+ "community_support": "コミュニティとサポート",
+ "community_description": "サポート、ディスカッション、アップデートのために私たちのコミュニティに参加してください。バグの報告、機能のリクエスト、他のユーザーや貢献者からの助けを得ることができます。",
+ "discord_community": "Discordコミュニティ",
+ "report_issues": "問題を報告",
+ "developer_info": "開発者情報",
+ "developer_description": "WarrackerはSassanixによって開発および保守されています。このプロジェクトはオープンソースであり、コミュニティからの貢献を歓迎します。",
+ "sassanix": "Sassanix",
+ "agpl_license": "AGPL-3.0ライセンス",
+ "support_project": "プロジェクトをサポート",
+ "support_description": "Warrackerが役立つと思われた場合は、その開発をサポートすることを検討してください!",
+ "new_version_available": "新しいバージョン{{version}}が利用可能です!",
+ "latest_version": "最新バージョンを使用しています",
+ "update_check_failed": "更新の確認に失敗しました",
+ "features": "機能",
+ "feature_track": "製品保証を追跡",
+ "feature_notifications": "有効期限通知を取得",
+ "feature_documents": "保証ドキュメントを保存",
+ "feature_reports": "保証レポートを生成",
+ "feature_tags": "タグで整理",
+ "feature_export": "保証データをエクスポート",
+ "support": "サポート",
+ "documentation": "ドキュメント",
+ "github": "GitHubリポジトリ",
+ "license": "ライセンス",
+ "copyright": "著作権",
+ "developed_by": "開発者"
+ }
+}
diff --git a/locales/ko/translation.json b/locales/ko/translation.json
new file mode 100644
index 0000000..15e6ee1
--- /dev/null
+++ b/locales/ko/translation.json
@@ -0,0 +1,561 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "보증 추적기",
+ "nav": {
+ "home": "홈",
+ "status": "상태",
+ "settings": "설정",
+ "about": "정보"
+ },
+ "auth": {
+ "login": "로그인",
+ "logout": "로그아웃",
+ "register": "등록",
+ "username": "사용자 이름",
+ "password": "비밀번호",
+ "email": "이메일",
+ "first_name": "이름",
+ "last_name": "성",
+ "forgot_password": "비밀번호를 잊으셨나요?",
+ "reset_password": "비밀번호 재설정",
+ "confirm_password": "비밀번호 확인",
+ "create_account_title": "계정 만들기",
+ "first_name_optional": "이름 (선택 사항)",
+ "last_name_optional": "성 (선택 사항)",
+ "username_hint": "사용자 이름은 고유해야 하며 로그인에 사용됩니다.",
+ "email_address": "이메일 주소",
+ "toggle_password": "비밀번호 표시/숨기기",
+ "password_hint_simple": "비밀번호는 8자 이상이어야 하며 대문자, 소문자, 숫자를 포함해야 합니다.",
+ "password_requirements": "비밀번호 요구 사항:",
+ "req_length": "8자 이상",
+ "req_uppercase": "대문자 1개 이상",
+ "req_lowercase": "소문자 1개 이상",
+ "req_number": "숫자 1개 이상",
+ "req_special": "특수 문자 1개 이상",
+ "create_account": "계정 만들기",
+ "already_have_account": "이미 계정이 있으신가요?",
+ "reset_password_title": "Warracker - 비밀번호 재설정",
+ "reset_your_password": "비밀번호 재설정",
+ "reset_password_info": "아래에 이메일 주소를 입력하시면 비밀번호 재설정 링크를 보내드립니다.",
+ "send_reset_link": "재설정 링크 보내기",
+ "back_to_login": "로그인으로 돌아가기",
+ "set_new_password_title": "Warracker - 새 비밀번호 설정",
+ "set_new_password": "새 비밀번호 설정",
+ "new_password": "새 비밀번호",
+ "confirm_new_password": "새 비밀번호 확인",
+ "invalid_or_expired_link": "잘못되었거나 만료된 링크",
+ "invalid_link_info": "클릭하신 비밀번호 재설정 링크가 잘못되었거나 만료되었습니다.",
+ "request_new_reset_link": "새 재설정 링크 요청"
+ },
+ "warranties": {
+ "title": "내 보증",
+ "title_global": "모든 사용자의 보증",
+ "add_new": "새 보증 추가",
+ "edit": "보증 편집",
+ "delete": "보증 삭제",
+ "product_name": "제품명",
+ "purchase_date": "구매 날짜",
+ "warranty_duration": "보증 기간",
+ "years": "년",
+ "months": "개월",
+ "days": "일",
+ "vendor": "판매업체",
+ "serial_numbers": "시리얼 번호",
+ "purchase_price": "구매 가격",
+ "notes": "메모",
+ "tags": "태그",
+ "status": "상태",
+ "expiration_date": "만료 날짜",
+ "active": "활성",
+ "expired": "만료됨",
+ "expiring_soon": "곧 만료",
+ "lifetime": "평생",
+ "no_warranties": "아직 보증이 없습니다. 첫 보증을 추가하여 시작하세요.",
+ "search_placeholder": "이름, 판매업체, 메모, 태그 또는 시리얼 번호로 검색...",
+ "warranty_type": "보증 유형",
+ "other_document": "기타 문서",
+ "product": "제품",
+ "expiration": "만료",
+ "actions": "작업",
+ "no_warranties_title": "아직 보증이 없습니다",
+ "no_warranties_desc": "첫 보증을 추가하여 시작하세요",
+ "add_warranty": "보증 추가",
+ "warranty_entry_method": "보증 입력 방법",
+ "warranty_duration_option": "보증 기간",
+ "exact_expiration_option": "정확한 만료 날짜",
+ "warranty_period": "보증 기간",
+ "expiration_date_label": "만료 날짜",
+ "currency": "통화",
+ "add_tags": "태그 추가",
+ "add_tags_desc": "태그는 보증을 정리하고 필터링하는 데 도움이 됩니다",
+ "save_changes": "변경 사항 저장",
+ "confirm_delete": "삭제 확인",
+ "manage_tags": "태그 관리",
+ "add_tag": "태그 추가",
+ "unknown_status": "알 수 없는 상태",
+ "expiring_soon_days": "곧 만료 ({{days}} {{dayText}})",
+ "days_remaining": "{{days}} {{dayText}} 남음",
+ "day_one": "일",
+ "day_other": "일",
+ "month_one": "개월",
+ "month_other": "개월",
+ "year_one": "년",
+ "year_other": "년",
+ "na": "해당 없음",
+ "age": "경과 기간",
+ "warranty": "보증",
+ "warranty_ends": "보증 종료",
+ "price": "가격",
+ "serial_number": "시리얼 번호",
+ "vendor": "판매업체",
+ "type": "유형",
+ "owner": "소유자",
+ "product_website": "제품 웹사이트",
+ "documents": "문서",
+ "summary": "요약",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "년",
+ "months_placeholder": "개월",
+ "days_placeholder": "일",
+ "add_any_notes_placeholder": "이 보증에 대한 메모를 추가하세요...",
+ "product_url_optional": "제품 URL (선택 사항)",
+ "enter_serial_number": "시리얼 번호 입력",
+ "vendor_optional": "판매업체 (선택 사항)",
+ "vendor_placeholder": "예: Amazon, Best Buy 등",
+ "lifetime_warranty": "평생 보증",
+ "warranty_type_optional": "보증 유형 (선택 사항)",
+ "select_warranty_type": "보증 유형 선택...",
+ "standard": "표준",
+ "extended": "연장",
+ "manufacturer": "제조사",
+ "third_party": "타사",
+ "store": "상점",
+ "premium": "프리미엄",
+ "limited": "제한",
+ "full": "전체",
+ "parts_only": "부품만",
+ "labor_only": "공임만",
+ "international": "국제",
+ "accidental_damage": "우발적 손상",
+ "other_custom": "기타 (사용자 지정)",
+ "enter_custom_warranty_type": "사용자 지정 보증 유형 입력",
+ "purchase_price_optional": "구매 가격 (선택 사항)",
+ "notes_optional": "메모 (선택 사항)",
+ "add_any_notes": "이 보증에 대한 메모 추가...",
+ "product_photo_optional": "제품 사진 (선택 사항)",
+ "choose_photo": "사진 선택",
+ "invoice_receipt": "송장/영수증",
+ "store_locally": "로컬에 저장",
+ "store_in_paperless": "Paperless-ngx에 저장",
+ "choose_file": "파일 선택",
+ "browse_paperless": "Paperless-ngx 문서 찾아보기",
+ "product_manual_optional": "제품 설명서 (선택 사항)",
+ "files_zip_rar_optional": "파일 (ZIP/RAR, 선택 사항)",
+ "search_or_add_new_tag": "새 태그 검색 또는 추가...",
+ "product_information": "제품 정보",
+ "product_url": "제품 URL",
+ "warranty_details": "보증 세부 정보",
+ "product_photo": "제품 사진",
+ "product_manual": "제품 설명서",
+ "files": "파일",
+ "selected_tags": "선택된 태그",
+ "previous_tab": "이전",
+ "next_tab": "다음",
+ "delete_photo": "사진 삭제",
+ "delete_invoice": "송장 삭제",
+ "delete_manual": "설명서 삭제",
+ "delete_files": "파일 삭제",
+ "current_photo": "현재 사진:",
+ "current_invoice": "현재 송장:",
+ "current_manual": "현재 설명서:",
+ "current_document": "현재 문서:",
+ "upload_new_photo_replace": "(새 사진을 업로드하여 교체)",
+ "no_photo_uploaded": "업로드된 사진 없음",
+ "no_invoice_uploaded": "업로드된 송장 없음",
+ "no_manual_uploaded": "업로드된 설명서 없음",
+ "no_document_uploaded": "업로드된 기타 문서 없음",
+ "photo_will_be_deleted": "저장 시 사진이 삭제됩니다",
+ "invoice_will_be_deleted": "저장 시 송장이 삭제됩니다",
+ "manual_will_be_deleted": "저장 시 설명서가 삭제됩니다",
+ "document_will_be_deleted": "저장 시 기타 문서가 삭제됩니다",
+ "confirm_delete_message": "이 보증을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.",
+ "new_tag_name": "새 태그 이름",
+ "existing_tags": "기존 태그",
+ "edit_warranty": "보증 편집",
+ "warranty_type_standard": "표준",
+ "warranty_type_extended": "연장",
+ "warranty_type_manufacturer": "제조사",
+ "warranty_type_third_party": "타사",
+ "warranty_type_store": "상점",
+ "warranty_type_premium": "프리미엄",
+ "warranty_type_limited": "제한",
+ "warranty_type_full": "전체",
+ "warranty_type_parts_only": "부품만",
+ "warranty_type_labor_only": "공임만",
+ "warranty_type_international": "국제",
+ "warranty_type_accidental_damage": "우발적 손상",
+ "warranty_type_other": "기타 (사용자 지정)",
+ "warranty_type_custom_placeholder": "사용자 지정 보증 유형 입력",
+ "notes_placeholder": "이 보증에 대한 추가 메모...",
+ "tags_help_text": "태그는 보증을 정리하고 필터링하는 데 도움이 됩니다",
+ "search_add_tag_placeholder": "새 태그 검색 또는 추가...",
+ "upload_new_file_replace": "새 파일을 업로드하여 교체",
+ "current_other_document": "현재 기타 문서",
+ "no_other_document_uploaded": "업로드된 기타 문서 없음",
+ "other_document_will_be_deleted": "저장 시 기타 문서가 삭제됩니다",
+ "files_optional": "파일 (ZIP/RAR, 선택 사항)",
+ "invoice_receipt_short": "송장",
+ "product_manual_short": "설명서",
+ "files_short": "파일",
+ "enter_serial_number": "시리얼 번호 입력",
+ "add_serial_number": "다른 시리얼 번호 추가"
+ },
+ "settings": {
+ "title": "설정",
+ "account_settings": "계정 설정",
+ "preferences": "기본 설정",
+ "language": "언어",
+ "select_language": "언어 선택",
+ "dark_mode": "다크 모드",
+ "dark_mode_desc": "라이트 테마와 다크 테마 간 전환",
+ "currency": "통화",
+ "timezone": "시간대",
+ "date_format": "날짜 형식",
+ "expiring_soon_days": "곧 만료될 날짜",
+ "save_changes": "변경 사항 저장",
+ "current_user": "프로필 편집:",
+ "your_email": "내 이메일:",
+ "first_name": "이름",
+ "last_name": "성",
+ "email": "이메일",
+ "save_profile": "변경 사항 저장",
+ "default_view": "기본 보기",
+ "default_view_desc": "보증에 대한 기본 보기 선택",
+ "grid_view": "그리드 보기",
+ "list_view": "목록 보기",
+ "table_view": "표 보기",
+ "currency_symbol": "통화 기호",
+ "currency_symbol_desc": "가격에 표시할 기호 선택",
+ "currency_position": "통화 위치",
+ "currency_position_desc": "숫자의 왼쪽 또는 오른쪽에 통화 기호를 표시할지 선택",
+ "expiring_soon_days_desc": "경고를 표시할 만료 전 일수",
+ "date_format_desc": "날짜 표시 방법 선택",
+ "save_preferences": "기본 설정 저장",
+ "notification_settings": "알림 설정",
+ "notification_channel": "알림 채널",
+ "notification_channel_desc": "알림 수신 방법 선택",
+ "notification_disabled": "비활성화됨",
+ "notification_email": "이메일",
+ "notification_apprise": "Apprise",
+ "notification_both": "둘 다",
+ "email_settings": "이메일 설정",
+ "notification_frequency": "알림 빈도",
+ "notification_frequency_desc": "이메일 알림 수신 빈도",
+ "daily": "매일",
+ "weekly": "매주",
+ "monthly": "매월",
+ "notification_time": "알림 시간",
+ "timezone_desc": "알림을 위한 현지 시간대",
+ "apprise_settings": "Apprise 설정",
+ "apprise_frequency": "Apprise 알림 빈도",
+ "apprise_frequency_desc": "Apprise 알림 수신 빈도",
+ "apprise_time": "Apprise 알림 시간",
+ "apprise_timezone": "Apprise 시간대",
+ "apprise_timezone_desc": "Apprise 알림을 위한 현지 시간대",
+ "save_notification_settings": "알림 설정 저장",
+ "security": "보안",
+ "change_password": "비밀번호 변경",
+ "change_password_desc": "계정 비밀번호 업데이트",
+ "change": "변경",
+ "current_password": "현재 비밀번호",
+ "new_password": "새 비밀번호",
+ "confirm_password": "새 비밀번호 확인",
+ "update_password": "비밀번호 업데이트",
+ "cancel": "취소",
+ "danger_zone": "위험 구역",
+ "delete_account": "계정 삭제",
+ "delete_account_desc": "계정과 모든 데이터를 영구적으로 삭제",
+ "admin_settings": "관리자 설정",
+ "admin_actions": "관리자 작업",
+ "refresh_data": "데이터 새로고침",
+ "check_admin_status": "관리자 상태 확인",
+ "show_users_list": "사용자 목록 표시",
+ "test_api": "API 테스트",
+ "send_notifications": "보증 알림 보내기",
+ "check_scheduler": "스케줄러 상태 확인",
+ "site_settings": "사이트 설정",
+ "registration_enabled": "등록 활성화",
+ "registration_enabled_desc": "새 사용자 등록 허용",
+ "email_base_url": "이메일 기본 URL",
+ "global_view_enabled": "전체 보기 활성화",
+ "global_view_admin_only": "관리자만 전체 보기",
+ "save_site_settings": "사이트 설정 저장",
+ "oidc_configuration": "OIDC SSO 구성",
+ "enable_oidc": "OIDC SSO 활성화",
+ "oidc_provider_name": "OIDC 공급자 이름",
+ "client_id": "클라이언트 ID",
+ "client_secret": "클라이언트 시크릿",
+ "issuer_url": "발급자 URL",
+ "scope": "범위",
+ "save_oidc_settings": "OIDC 설정 저장",
+ "oidc_sso_desc": "사용자가 OIDC 공급자를 통해 로그인하도록 허용합니다.",
+ "oidc_only_mode": "OIDC 전용 로그인 모드",
+ "oidc_only_mode_desc": "기존 사용자 이름/비밀번호 로그인 양식을 숨기고 OIDC 로그인만 허용합니다. <strong>경고:</strong> 이 옵션을 활성화하기 전에 OIDC가 올바르게 구성되었는지 확인하십시오.",
+ "oidc_provider_name_desc": "OIDC 클라이언트의 내부 이름 (예: 'oidc').",
+ "client_secret_desc": "민감한 값. 데이터베이스에 저장됩니다. 변경 사항을 적용하려면 애플리케이션을 다시 시작해야 합니다.",
+ "issuer_url_desc": "OIDC 공급자의 기본 URL.",
+ "scope_desc": "공백으로 구분된 OIDC 범위.",
+ "oidc_restart_message": "OIDC 설정을 완전히 적용하려면 애플리케이션을 다시 시작해야 합니다.",
+ "api_token": "API 토큰",
+ "view_documents": "Warracker에서 문서 보기",
+ "connection_testing": "연결 테스트",
+ "apprise_notifications": "Apprise 알림",
+ "enable_apprise": "Apprise 알림 활성화",
+ "loading": "로드 중...",
+ "time_of_day_notification": "알림 수신 시간 (24시간 형식)",
+ "paperless_ngx_settings": "Paperless-ngx 설정",
+ "paperless_ngx_about_title": "Paperless-ngx 통합 정보:",
+ "paperless_ngx_about_desc": "이 선택적 기능을 사용하면 보증 문서를 로컬 대신 자체 호스팅된 Paperless-ngx 인스턴스에 저장할 수 있습니다. 활성화하면 사용자는 각 문서를 로컬 또는 Paperless-ngx에 저장할 위치를 선택할 수 있습니다.",
+ "paperless_ngx_desc": "Paperless-ngx 문서 관리 시스템과의 통합 구성",
+ "enable_paperless": "Paperless-ngx 통합 활성화",
+ "paperless_url": "Paperless-ngx URL",
+ "paperless_url_desc": "Paperless-ngx 인스턴스의 기본 URL",
+ "paperless_token": "API 토큰",
+ "paperless_token_desc": "Paperless-ngx API 인증 토큰",
+ "paperless_token_desc_generate": "Paperless-ngx 인스턴스에서 API 토큰 생성 (설정 → API 토큰).",
+ "paperless_view_in_app": "앱에서 문서 보기",
+ "paperless_view_in_app_desc": "새 탭 대신 앱 내에서 문서 열기",
+ "debug_config": "디버그 구성",
+ "test_upload": "업로드 테스트",
+ "save_paperless_settings": "Paperless-ngx 설정 저장",
+ "apprise_desc": "여러 서비스에 대한 고급 알림 전달을 위해 Apprise 구성",
+ "apprise_desc_system_wide": "시스템 전체에서 Apprise 알림 활성화 또는 비활성화",
+ "apprise_not_available_title": "Apprise를 사용할 수 없음:",
+ "apprise_not_available_desc": "Apprise 알림 라이브러리가 설치되지 않았거나 사용할 수 없습니다. 알림 기능이 비활성화되었습니다.",
+ "apprise_url": "Apprise URL",
+ "apprise_url_desc": "Apprise 알림 서비스 URL",
+ "apprise_mode": "알림 모드",
+ "apprise_mode_desc": "Apprise 알림 전송 시기 선택",
+ "apprise_mode_global": "전체 요약",
+ "apprise_mode_individual": "사용자별",
+ "test_paperless": "Paperless 연결 테스트",
+ "test_apprise": "Apprise 연결 테스트",
+ "apprise_warranty_scope": "보증 범위",
+ "apprise_warranty_scope_desc": "알림에 포함할 보증 선택",
+ "all_warranties": "모든 보증",
+ "personal_warranties": "개인 보증만",
+ "all_users_warranties": "모든 사용자의 보증",
+ "admin_warranties_only": "관리자 보증만",
+ "apprise_notification_days": "알림 일수",
+ "apprise_notification_days_desc": "만료 전 알림을 보낼 일수 (쉼표로 구분, 예: \"7,30\"은 7일 및 30일 전)",
+ "apprise_check_frequency": "확인 빈도",
+ "apprise_check_frequency_desc": "시스템이 만료되는 보증을 확인하는 빈도 (전체 설정)",
+ "apprise_title_prefix": "메시지 제목 접두사",
+ "apprise_title_prefix_desc": "알림 제목에 추가되는 접두사 (예: \"[Warracker]\"는 \"[Warracker] 곧 만료되는 보증\"이 됨)",
+ "apprise_test_url": "테스트 URL (선택 사항)",
+ "apprise_test_url_desc": "선택 사항: 테스트 알림만 보내기 위한 URL (기본 구성에 저장되지 않음)",
+ "save_apprise_settings": "Apprise 설정 저장",
+ "validate_urls": "URL 유효성 검사",
+ "send_expiration_notifications_now": "지금 만료 알림 보내기",
+ "apprise_current_status": "현재 상태",
+ "apprise_urls_configured": "구성된 URL:",
+ "apprise_supported_services": "지원되는 서비스",
+ "apprise_supported_services_desc": "Apprise는 Discord, Slack, Telegram, 이메일(Gmail, Outlook), 웹훅, Microsoft Teams, Matrix, Pushover, Ntfy, Gotify 등 80개 이상의 알림 서비스를 지원합니다.",
+ "view_full_list_of_supported_services": "지원되는 서비스 전체 목록 보기",
+ "ownership_management": "소유권 관리",
+ "transfer_ownership": "소유권 이전",
+ "warning_title": "경고:",
+ "transfer_ownership_warning": "애플리케이션 소유권을 다른 관리자 사용자에게 이전합니다. 이 작업은 되돌릴 수 없습니다.",
+ "transfer_ownership_desc": "소유권이 이전되면 일반 관리자가 되며 새 소유자가 애플리케이션을 완전히 제어하게 됩니다.",
+ "select_new_owner": "새 소유자 선택 (관리자여야 함)",
+ "select_admin_user": "관리자 사용자 선택...",
+ "transfer_ownership_button": "소유권 이전",
+ "transfer_ownership_irreversible": "이 작업은 되돌릴 수 없습니다.",
+ "transfer_ownership_confirmation": "애플리케이션 소유권을 다음 사용자에게 이전하려고 합니다.",
+ "after_this_transfer": "이전 후:",
+ "transfer_ownership_consequence_1": "일반 관리자가 됩니다",
+ "transfer_ownership_consequence_2": "새 소유자가 애플리케이션을 완전히 제어하게 됩니다",
+ "transfer_ownership_consequence_3": "새 소유자만 소유권을 다시 이전할 수 있습니다",
+ "transfer_ownership_type_to_confirm": "확인하려면 아래 필드에 \"TRANSFER\"를 입력하십시오."
+ },
+ "actions": {
+ "save": "저장",
+ "cancel": "취소",
+ "delete": "삭제",
+ "edit": "편집",
+ "export": "내보내기",
+ "import": "가져오기",
+ "refresh": "새로고침",
+ "search": "검색",
+ "clear": "지우기",
+ "upload": "업로드",
+ "download": "다운로드",
+ "manage_tags": "태그 관리",
+ "close": "닫기",
+ "save_changes": "변경 사항 저장"
+ },
+ "filters": {
+ "all_status": "모든 상태",
+ "all_tags": "모든 태그",
+ "all_vendors": "모든 판매업체",
+ "all_types": "모든 유형",
+ "sort_by": "정렬 기준",
+ "sort_expiration": "만료 날짜",
+ "sort_purchase": "구매 날짜",
+ "sort_age": "경과 기간",
+ "sort_name": "제품명",
+ "sort_vendor": "판매업체",
+ "sort_warranty_type": "보증 유형",
+ "status": "상태",
+ "tags": "태그",
+ "vendor": "판매업체",
+ "warranty_type": "보증 유형",
+ "view": "보기",
+ "scope": "범위"
+ },
+ "messages": {
+ "success": "성공",
+ "error": "오류",
+ "warning": "경고",
+ "loading": "로드 중...",
+ "saved": "변경 사항이 성공적으로 저장되었습니다",
+ "deleted": "항목이 성공적으로 삭제되었습니다",
+ "confirm_delete": "이 항목을 삭제하시겠습니까?",
+ "no_results": "결과를 찾을 수 없습니다",
+ "file_too_large": "파일이 너무 큽니다",
+ "invalid_file_type": "잘못된 파일 형식",
+ "fill_first_last_name": "성과 이름을 입력해주세요",
+ "email_cannot_be_empty": "이메일 주소는 비워둘 수 없습니다.",
+ "enter_valid_email": "유효한 이메일 주소를 입력해주세요.",
+ "profile_updated_successfully": "프로필이 성공적으로 업데이트되었습니다",
+ "preferences_saved_successfully": "환경설정이 성공적으로 저장되었습니다.",
+ "fill_password_fields": "모든 비밀번호 필드를 입력해주세요",
+ "passwords_do_not_match": "새 비밀번호가 일치하지 않습니다",
+ "password_min_length": "비밀번호는 최소 8자 이상이어야 합니다",
+ "type_delete_to_confirm": "확인하려면 DELETE를 입력하세요",
+ "account_deleted_successfully": "계정이 성공적으로 삭제되었습니다",
+ "account_cannot_delete_offline": "오프라인 모드에서는 계정을 삭제할 수 없습니다",
+ "failed_delete_account": "계정 삭제에 실패했습니다. 다시 시도해주세요.",
+ "user_updated_successfully": "사용자가 성공적으로 업데이트되었습니다",
+ "user_deleted_successfully": "사용자가 성공적으로 삭제되었습니다",
+ "user_id_missing": "사용자 ID가 없습니다",
+ "failed_load_users": "사용자 로드에 실패했습니다",
+ "error_loading_users": "사용자 로딩 중 오류가 발생했습니다",
+ "select_user_transfer_ownership": "소유권을 이전할 사용자를 선택해주세요",
+ "ownership_transferred_successfully": "소유권이 성공적으로 이전되었습니다! 페이지를 새로고침합니다...",
+ "failed_load_site_settings": "사이트 설정 로드에 실패했습니다. 다시 시도해주세요.",
+ "invalid_email_base_url": "잘못된 이메일 기본 URL 형식입니다. http:// 또는 https://로 시작해야 합니다",
+ "no_site_settings_to_save": "저장할 사이트 설정이 없습니다.",
+ "site_settings_saved_successfully": "사이트 설정이 성공적으로 저장되었습니다",
+ "failed_save_site_settings": "사이트 설정 저장에 실패했습니다",
+ "oidc_settings_saved_successfully": "OIDC 설정이 성공적으로 저장되었습니다.",
+ "failed_save_oidc_settings": "OIDC 설정 저장에 실패했습니다.",
+ "api_endpoint_accessible": "API 엔드포인트에 접근할 수 있습니다",
+ "api_endpoint_not_accessible": "API 엔드포인트에 접근할 수 없습니다. 상태: ",
+ "only_admins_send_notifications": "관리자만 보증 알림을 보낼 수 있습니다",
+ "notifications_triggered_successfully": "알림이 성공적으로 트리거되었습니다",
+ "notification_settings_saved_successfully": "알림 설정이 성공적으로 저장되었습니다",
+ "apprise_settings_saved_successfully": "Apprise 설정이 성공적으로 저장되었습니다",
+ "test_notification_sent_successfully": "테스트 알림이 성공적으로 전송되었습니다",
+ "no_urls_to_validate": "검증할 URL이 없습니다",
+ "paperless_settings_saved_successfully": "Paperless-ngx 설정이 성공적으로 저장되었습니다!",
+ "enter_valid_paperless_url": "유효한 URL을 입력해주세요 (예: https://paperless.yourdomain.com)",
+ "enter_paperless_url_first": "먼저 Paperless-ngx URL을 입력해주세요",
+ "paperless_connection_test_successful": "Paperless-ngx 연결 테스트가 성공했습니다!",
+ "paperless_connection_test_failed": "Paperless-ngx 연결 테스트가 실패했습니다",
+ "enter_api_token_test_connection": "연결을 테스트하려면 API 토큰을 입력해주세요",
+ "failed_load_user_data": "사용자 데이터 로드에 실패했습니다. 다시 시도해주세요.",
+ "could_not_connect_user_data": "사용자 데이터를 가져오기 위해 연결할 수 없습니다. 캐시된 정보를 표시합니다.",
+ "preferences_saved_locally_failed_sync": "환경설정이 로컬에 저장되었지만 서버와 동기화에 실패했습니다: ",
+ "preferences_saved_locally": "환경설정이 로컬에 저장되었습니다.",
+ "correct_errors_in_tab": "계속하기 전에 강조 표시된 탭의 오류를 수정해 주세요.",
+ "please_fill_out_this_field": "이 필드를 채워주세요.",
+ "warranty_added_successfully": "보증이 성공적으로 추가되었습니다",
+ "tag_name_required": "태그 이름이 필요합니다",
+ "tag_creation_function_not_found": "태그 생성 기능을 찾을 수 없습니다",
+ "tag_created_successfully": "태그가 성공적으로 생성되었습니다",
+ "tag_updated_successfully": "태그가 성공적으로 업데이트되었습니다",
+ "tag_deleted_successfully": "태그가 성공적으로 삭제되었습니다",
+ "failed_to_create_tag": "태그 생성에 실패했습니다",
+ "failed_to_update_tag": "태그 업데이트에 실패했습니다",
+ "failed_to_delete_tag": "태그 삭제에 실패했습니다"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية",
+ "ru": "Русский",
+ "uk": "Українська",
+ "zh_CN": "简体中文",
+ "zh_HK": "繁體中文",
+ "ja": "日本語",
+ "pt": "Português",
+ "ko": "한국어"
+ },
+ "status": {
+ "title": "시스템 상태",
+ "dashboard_title": "보증 상태 대시보드",
+ "global_dashboard_title": "전체 보증 상태 대시보드",
+ "overview": "개요",
+ "statistics": "통계",
+ "total_warranties": "총 보증 수",
+ "active_warranties": "활성 보증",
+ "expiring_soon": "곧 만료",
+ "expired_warranties": "만료된 보증",
+ "warranty_distribution": "보증 분포",
+ "expiration_timeline": "만료 타임라인",
+ "recent_activity": "최근 활동",
+ "recent_expirations": "최근 만료 또는 곧 만료",
+ "recent_expirations_empty": "최근 만료되거나 곧 만료될 보증이 없습니다.",
+ "system_health": "시스템 상태",
+ "database_status": "데이터베이스 상태",
+ "connected": "연결됨",
+ "version": "버전",
+ "uptime": "가동 시간"
+ },
+ "about": {
+ "title": "Warracker 정보",
+ "description": "모든 제품 보증을 하나의 안전하고 사용하기 쉬운 플랫폼에서 추적, 정리 및 관리할 수 있도록 설계된 포괄적인 보증 관리 시스템입니다.",
+ "version": "버전",
+ "update_status": "업데이트 상태",
+ "checking_updates": "업데이트 확인 중...",
+ "view_release_notes": "릴리스 노트 보기",
+ "project_info": "프로젝트 정보",
+ "project_description": "Warracker는 최신 웹 기술로 구축된 오픈 소스 보증 관리 시스템입니다. 제품 보증을 관리하고, 만료 날짜를 추적하며, 중요한 문서를 안전하고 직관적인 방법으로 정리할 수 있습니다.",
+ "github_repository": "GitHub 리포지토리",
+ "releases": "릴리스",
+ "community_support": "커뮤니티 및 지원",
+ "community_description": "지원, 토론 및 업데이트를 위해 커뮤니티에 가입하십시오. 버그를 보고하고, 기능을 요청하거나 다른 사용자 및 기여자로부터 도움을 받으십시오.",
+ "discord_community": "Discord 커뮤니티",
+ "report_issues": "문제 보고",
+ "developer_info": "개발자 정보",
+ "developer_description": "Warracker는 Sassanix에 의해 개발 및 유지 관리됩니다. 이 프로젝트는 오픈 소스이며 커뮤니티의 기여를 환영합니다.",
+ "sassanix": "Sassanix",
+ "agpl_license": "AGPL-3.0 라이선스",
+ "support_project": "프로젝트 지원",
+ "support_description": "Warracker가 유용하다고 생각되면 개발을 지원하는 것을 고려해 보십시오!",
+ "new_version_available": "새 버전 {{version}}을 사용할 수 있습니다!",
+ "latest_version": "최신 버전을 사용하고 있습니다",
+ "update_check_failed": "업데이트 확인 실패",
+ "features": "기능",
+ "feature_track": "제품 보증 추적",
+ "feature_notifications": "만료 알림 받기",
+ "feature_documents": "보증 문서 저장",
+ "feature_reports": "보증 보고서 생성",
+ "feature_tags": "태그로 정리",
+ "feature_export": "보증 데이터 내보내기",
+ "support": "지원",
+ "documentation": "문서",
+ "github": "GitHub 리포지토리",
+ "license": "라이선스",
+ "copyright": "저작권",
+ "developed_by": "개발자"
+ }
+}
\ No newline at end of file
diff --git a/locales/nl/translation.json b/locales/nl/translation.json
new file mode 100644
index 0000000..0f4f8e2
--- /dev/null
+++ b/locales/nl/translation.json
@@ -0,0 +1,560 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "Garantie Tracker",
+ "nav": {
+ "home": "Home",
+ "status": "Status",
+ "settings": "Instellingen",
+ "about": "Over"
+ },
+ "auth": {
+ "login": "Inloggen",
+ "logout": "Uitloggen",
+ "register": "Registreren",
+ "username": "Gebruikersnaam",
+ "password": "Wachtwoord",
+ "email": "E-mail",
+ "first_name": "Voornaam",
+ "last_name": "Achternaam",
+ "forgot_password": "Wachtwoord vergeten?",
+ "reset_password": "Wachtwoord resetten",
+ "confirm_password": "Wachtwoord bevestigen",
+ "create_account_title": "Maak uw account aan",
+ "first_name_optional": "Voornaam (optioneel)",
+ "last_name_optional": "Achternaam (optioneel)",
+ "username_hint": "Gebruikersnaam moet uniek zijn en wordt gebruikt om in te loggen.",
+ "email_address": "E-mailadres",
+ "toggle_password": "Wachtwoord tonen/verbergen",
+ "password_hint_simple": "Wachtwoord moet minimaal 8 tekens lang zijn en hoofdletters, kleine letters en cijfers bevatten.",
+ "password_requirements": "Wachtwoordvereisten:",
+ "req_length": "Minstens 8 tekens",
+ "req_uppercase": "Minstens 1 hoofdletter",
+ "req_lowercase": "Minstens 1 kleine letter",
+ "req_number": "Minstens 1 cijfer",
+ "req_special": "Minstens 1 speciaal teken",
+ "create_account": "Account aanmaken",
+ "already_have_account": "Heeft u al een account?",
+ "reset_password_title": "Warracker - Wachtwoord resetten",
+ "reset_your_password": "Reset uw wachtwoord",
+ "reset_password_info": "Voer hieronder uw e-mailadres in en we sturen u een link om uw wachtwoord te resetten.",
+ "send_reset_link": "Verstuur reset link",
+ "back_to_login": "Terug naar inloggen",
+ "set_new_password_title": "Warracker - Nieuw wachtwoord instellen",
+ "set_new_password": "Nieuw wachtwoord instellen",
+ "new_password": "Nieuw wachtwoord",
+ "confirm_new_password": "Bevestig nieuw wachtwoord",
+ "invalid_or_expired_link": "Ongeldige of verlopen link",
+ "invalid_link_info": "De link voor het opnieuw instellen van het wachtwoord waarop u hebt geklikt, is ongeldig of is verlopen.",
+ "request_new_reset_link": "Vraag nieuwe reset link aan"
+ },
+ "warranties": {
+ "title": "Uw garanties",
+ "title_global": "Garanties van alle gebruikers",
+ "add_new": "Nieuwe garantie toevoegen",
+ "edit": "Garantie bewerken",
+ "delete": "Garantie verwijderen",
+ "product_name": "Productnaam",
+ "purchase_date": "Aankoopdatum",
+ "warranty_duration": "Garantieduur",
+ "years": "Jaren",
+ "months": "Maanden",
+ "days": "Dagen",
+ "vendor": "Leverancier",
+ "serial_numbers": "Serienummers",
+ "purchase_price": "Aankoopprijs",
+ "notes": "Notities",
+ "tags": "Tags",
+ "status": "Status",
+ "expiration_date": "Vervaldatum",
+ "active": "Actief",
+ "expired": "Verlopen",
+ "expiring_soon": "Verloopt binnenkort",
+ "lifetime": "Levenslang",
+ "no_warranties": "Nog geen garanties. Voeg uw eerste garantie toe om te beginnen.",
+ "search_placeholder": "Zoeken op naam, leverancier, notities, tag of serienummer...",
+ "warranty_type": "Garantietype",
+ "other_document": "Ander document",
+ "product": "Product",
+ "expiration": "Vervaldatum",
+ "actions": "Acties",
+ "no_warranties_title": "Nog geen garanties",
+ "no_warranties_desc": "Voeg uw eerste garantie toe om te beginnen",
+ "add_warranty": "Garantie toevoegen",
+ "warranty_entry_method": "Garantie-invoermethode",
+ "warranty_duration_option": "Garantieduur",
+ "exact_expiration_option": "Exacte vervaldatum",
+ "warranty_period": "Garantieperiode",
+ "expiration_date_label": "Vervaldatum",
+ "currency": "Valuta",
+ "add_tags": "Tags toevoegen",
+ "add_tags_desc": "Tags helpen u uw garanties te organiseren en te filteren",
+ "save_changes": "Wijzigingen opslaan",
+ "confirm_delete": "Verwijderen bevestigen",
+ "manage_tags": "Tags beheren",
+ "add_tag": "Tag toevoegen",
+ "unknown_status": "Onbekende status",
+ "expiring_soon_days": "Verloopt binnenkort ({{days}} {{dayText}})",
+ "days_remaining": "{{days}} {{dayText}} resterend",
+ "day_one": "dag",
+ "day_other": "dagen",
+ "month_one": "maand",
+ "month_other": "maanden",
+ "year_one": "jaar",
+ "year_other": "jaren",
+ "na": "N.v.t.",
+ "age": "Leeftijd",
+ "warranty": "Garantie",
+ "warranty_ends": "Garantie eindigt",
+ "price": "Prijs",
+ "serial_number": "Serienummer",
+ "type": "Type",
+ "owner": "Eigenaar",
+ "product_website": "Productwebsite",
+ "documents": "Documenten",
+ "summary": "Samenvatting",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "Jaren",
+ "months_placeholder": "Maanden",
+ "days_placeholder": "Dagen",
+ "add_any_notes_placeholder": "Voeg notities over deze garantie toe...",
+ "product_url_optional": "Product-URL (optioneel)",
+ "enter_serial_number": "Voer serienummer in",
+ "vendor_optional": "Leverancier (optioneel)",
+ "vendor_placeholder": "bijv. Amazon, Best Buy, etc.",
+ "lifetime_warranty": "Levenslange garantie",
+ "warranty_type_optional": "Garantietype (optioneel)",
+ "select_warranty_type": "Selecteer garantietype...",
+ "standard": "Standaard",
+ "extended": "Uitgebreid",
+ "manufacturer": "Fabrikant",
+ "third_party": "Derde partij",
+ "store": "Winkel",
+ "premium": "Premium",
+ "limited": "Beperkt",
+ "full": "Volledig",
+ "parts_only": "Alleen onderdelen",
+ "labor_only": "Alleen arbeid",
+ "international": "Internationaal",
+ "accidental_damage": "Onopzettelijke schade",
+ "other_custom": "Anders (aangepast)",
+ "enter_custom_warranty_type": "Voer aangepast garantietype in",
+ "purchase_price_optional": "Aankoopprijs (optioneel)",
+ "notes_optional": "Notities (optioneel)",
+ "add_any_notes": "Voeg notities over deze garantie toe...",
+ "product_photo_optional": "Productfoto (optioneel)",
+ "choose_photo": "Kies foto",
+ "invoice_receipt": "Factuur/Bon",
+ "store_locally": "Lokaal opslaan",
+ "store_in_paperless": "Opslaan in Paperless-ngx",
+ "choose_file": "Kies bestand",
+ "browse_paperless": "Blader door Paperless-ngx-documenten",
+ "product_manual_optional": "Producthandleiding (optioneel)",
+ "files_zip_rar_optional": "Bestanden (ZIP/RAR, optioneel)",
+ "search_or_add_new_tag": "Zoek of voeg nieuwe tag toe...",
+ "product_information": "Productinformatie",
+ "product_url": "Product-URL",
+ "warranty_details": "Garantiedetails",
+ "product_photo": "Productfoto",
+ "product_manual": "Producthandleiding",
+ "files": "Bestanden",
+ "selected_tags": "Geselecteerde tags",
+ "previous_tab": "Vorige",
+ "next_tab": "Volgende",
+ "delete_photo": "Foto verwijderen",
+ "delete_invoice": "Factuur verwijderen",
+ "delete_manual": "Handleiding verwijderen",
+ "delete_files": "Bestanden verwijderen",
+ "current_photo": "Huidige foto:",
+ "current_invoice": "Huidige factuur:",
+ "current_manual": "Huidige handleiding:",
+ "current_document": "Huidig document:",
+ "upload_new_photo_replace": "(Upload een nieuwe foto om te vervangen)",
+ "no_photo_uploaded": "Geen foto geüpload",
+ "no_invoice_uploaded": "Geen factuur geüpload",
+ "no_manual_uploaded": "Geen handleiding geüpload",
+ "no_document_uploaded": "Geen ander document geüpload",
+ "photo_will_be_deleted": "Foto wordt bij opslaan verwijderd",
+ "invoice_will_be_deleted": "Factuur wordt bij opslaan verwijderd",
+ "manual_will_be_deleted": "Handleiding wordt bij opslaan verwijderd",
+ "document_will_be_deleted": "Ander document wordt bij opslaan verwijderd",
+ "confirm_delete_message": "Weet u zeker dat u deze garantie wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.",
+ "new_tag_name": "Nieuwe tagnaam",
+ "existing_tags": "Bestaande tags",
+ "edit_warranty": "Garantie bewerken",
+ "warranty_type_standard": "Standaard",
+ "warranty_type_extended": "Uitgebreid",
+ "warranty_type_manufacturer": "Fabrikant",
+ "warranty_type_third_party": "Derde partij",
+ "warranty_type_store": "Winkel",
+ "warranty_type_premium": "Premium",
+ "warranty_type_limited": "Beperkt",
+ "warranty_type_full": "Volledig",
+ "warranty_type_parts_only": "Alleen onderdelen",
+ "warranty_type_labor_only": "Alleen arbeid",
+ "warranty_type_international": "Internationaal",
+ "warranty_type_accidental_damage": "Onopzettelijke schade",
+ "warranty_type_other": "Anders (aangepast)",
+ "warranty_type_custom_placeholder": "Voer aangepast garantietype in",
+ "notes_placeholder": "Aanvullende notities over deze garantie...",
+ "tags_help_text": "Tags helpen u uw garanties te organiseren en te filteren",
+ "search_add_tag_placeholder": "Zoek of voeg nieuwe tag toe...",
+ "upload_new_file_replace": "Upload een nieuw bestand om te vervangen",
+ "current_other_document": "Huidig ander document",
+ "no_other_document_uploaded": "Geen ander document geüpload",
+ "other_document_will_be_deleted": "Ander document wordt bij opslaan verwijderd",
+ "files_optional": "Bestanden (ZIP/RAR, optioneel)",
+ "invoice_receipt_short": "Factuur",
+ "product_manual_short": "Handleiding",
+ "files_short": "Bestanden",
+ "enter_serial_number": "Serienummer invoeren",
+ "add_serial_number": "Nog een serienummer toevoegen"
+ },
+ "settings": {
+ "title": "Instellingen",
+ "account_settings": "Accountinstellingen",
+ "preferences": "Voorkeuren",
+ "language": "Taal",
+ "select_language": "Selecteer taal",
+ "dark_mode": "Donkere modus",
+ "dark_mode_desc": "Schakelen tussen licht en donker thema",
+ "currency": "Valuta",
+ "timezone": "Tijdzone",
+ "date_format": "Datumnotatie",
+ "expiring_soon_days": "Dagen tot verval",
+ "save_changes": "Wijzigingen opslaan",
+ "current_user": "Profiel bewerken voor:",
+ "your_email": "Uw e-mail:",
+ "first_name": "Voornaam",
+ "last_name": "Achternaam",
+ "email": "E-mail",
+ "save_profile": "Wijzigingen opslaan",
+ "default_view": "Standaardweergave",
+ "default_view_desc": "Kies uw voorkeursweergave voor garanties",
+ "grid_view": "Rasterweergave",
+ "list_view": "Lijstweergave",
+ "table_view": "Tabelweergave",
+ "currency_symbol": "Valutasymbool",
+ "currency_symbol_desc": "Kies het symbool om voor prijzen weer te geven",
+ "currency_position": "Valutapositie",
+ "currency_position_desc": "Kies of het valutasymbool links of rechts van de getallen verschijnt",
+ "expiring_soon_days_desc": "Aantal dagen voor verval om waarschuwingen weer te geven",
+ "date_format_desc": "Kies hoe datums worden weergegeven",
+ "save_preferences": "Voorkeuren opslaan",
+ "notification_settings": "Meldingsinstellingen",
+ "notification_channel": "Meldingskanaal",
+ "notification_channel_desc": "Kies hoe u meldingen wilt ontvangen",
+ "notification_disabled": "Uitgeschakeld",
+ "notification_email": "E-mail",
+ "notification_apprise": "Apprise",
+ "notification_both": "Beide",
+ "email_settings": "E-mailinstellingen",
+ "notification_frequency": "Meldingsfrequentie",
+ "notification_frequency_desc": "Hoe vaak e-mailmeldingen ontvangen",
+ "daily": "Dagelijks",
+ "weekly": "Wekelijks",
+ "monthly": "Maandelijks",
+ "notification_time": "Meldingstijd",
+ "timezone_desc": "Uw lokale tijdzone voor meldingen",
+ "apprise_settings": "Apprise-instellingen",
+ "apprise_frequency": "Apprise-meldingsfrequentie",
+ "apprise_frequency_desc": "Hoe vaak Apprise-meldingen ontvangen",
+ "apprise_time": "Apprise-meldingstijd",
+ "apprise_timezone": "Apprise-tijdzone",
+ "apprise_timezone_desc": "Uw lokale tijdzone voor Apprise-meldingen",
+ "save_notification_settings": "Meldingsinstellingen opslaan",
+ "security": "Beveiliging",
+ "change_password": "Wachtwoord wijzigen",
+ "change_password_desc": "Update uw accountwachtwoord",
+ "change": "Wijzigen",
+ "current_password": "Huidig wachtwoord",
+ "new_password": "Nieuw wachtwoord",
+ "confirm_password": "Bevestig nieuw wachtwoord",
+ "update_password": "Wachtwoord bijwerken",
+ "cancel": "Annuleren",
+ "danger_zone": "Gevarenzone",
+ "delete_account": "Account verwijderen",
+ "delete_account_desc": "Verwijder uw account en alle gegevens permanent",
+ "admin_settings": "Beheerdersinstellingen",
+ "admin_actions": "Beheerdersacties",
+ "refresh_data": "Gegevens vernieuwen",
+ "check_admin_status": "Beheerdersstatus controleren",
+ "show_users_list": "Gebruikerslijst weergeven",
+ "test_api": "API testen",
+ "send_notifications": "Garantienotificaties verzenden",
+ "check_scheduler": "Scheduler-status controleren",
+ "site_settings": "Site-instellingen",
+ "registration_enabled": "Registratie ingeschakeld",
+ "registration_enabled_desc": "Nieuwe gebruikers toestaan zich te registreren",
+ "email_base_url": "E-mail basis-URL",
+ "global_view_enabled": "Globale weergave ingeschakeld",
+ "global_view_admin_only": "Globale weergave alleen voor beheerders",
+ "save_site_settings": "Site-instellingen opslaan",
+ "oidc_configuration": "OIDC SSO-configuratie",
+ "enable_oidc": "OIDC SSO inschakelen",
+ "oidc_provider_name": "OIDC-providernaam",
+ "client_id": "Client-ID",
+ "client_secret": "Clientgeheim",
+ "issuer_url": "Uitgever-URL",
+ "scope": "Bereik",
+ "save_oidc_settings": "OIDC-instellingen opslaan",
+ "oidc_sso_desc": "Gebruikers toestaan in te loggen via een OIDC-provider.",
+ "oidc_only_mode": "Alleen-OIDC-inlogmodus",
+ "oidc_only_mode_desc": "Verberg het traditionele gebruikersnaam/wachtwoord-inlogformulier en sta alleen OIDC-inloggen toe. <strong>Waarschuwing:</strong> Zorg ervoor dat OIDC correct is geconfigureerd voordat u deze optie inschakelt.",
+ "oidc_provider_name_desc": "Interne naam voor de OIDC-client (bijv. 'oidc').",
+ "client_secret_desc": "Gevoelige waarde. Opgeslagen in de database. Een herstart van de applicatie is vereist om wijzigingen door te voeren.",
+ "issuer_url_desc": "De basis-URL van uw OIDC-provider.",
+ "scope_desc": "Door spaties gescheiden OIDC-bereiken.",
+ "oidc_restart_message": "Een herstart van de applicatie is vereist om de OIDC-instellingen volledig van kracht te laten worden.",
+ "api_token": "API-token",
+ "view_documents": "Documenten bekijken in Warracker",
+ "connection_testing": "Verbinding testen",
+ "apprise_notifications": "Apprise-meldingen",
+ "enable_apprise": "Apprise-meldingen inschakelen",
+ "loading": "Laden...",
+ "time_of_day_notification": "Tijdstip van de dag om meldingen te ontvangen (in 24-uursnotatie)",
+ "paperless_ngx_settings": "Paperless-ngx-instellingen",
+ "paperless_ngx_about_title": "Over de Paperless-ngx-integratie:",
+ "paperless_ngx_about_desc": "Met deze optionele functie kunt u garantiedocumenten opslaan in uw zelf-gehoste Paperless-ngx-instantie in plaats van lokaal. Indien ingeschakeld, kunnen gebruikers kiezen waar ze elk document willen opslaan: lokaal of in Paperless-ngx.",
+ "paperless_ngx_desc": "Configureer de integratie met het Paperless-ngx-documentbeheersysteem",
+ "enable_paperless": "Paperless-ngx-integratie inschakelen",
+ "paperless_url": "Paperless-ngx-URL",
+ "paperless_url_desc": "Basis-URL van uw Paperless-ngx-instantie",
+ "paperless_token": "API-token",
+ "paperless_token_desc": "Uw Paperless-ngx API-authenticatietoken",
+ "paperless_token_desc_generate": "Genereer een API-token vanuit uw Paperless-ngx-instantie (Instellingen → API-tokens).",
+ "paperless_view_in_app": "Documenten in de app bekijken",
+ "paperless_view_in_app_desc": "Documenten in de app openen in plaats van in een nieuw tabblad",
+ "debug_config": "Foutopsporingsconfiguratie",
+ "test_upload": "Upload testen",
+ "save_paperless_settings": "Paperless-ngx-instellingen opslaan",
+ "apprise_desc": "Configureer Apprise voor geavanceerde meldingenlevering aan meerdere services",
+ "apprise_desc_system_wide": "Apprise-meldingen systeembreed in- of uitschakelen",
+ "apprise_not_available_title": "Apprise niet beschikbaar:",
+ "apprise_not_available_desc": "De Apprise-meldingsbibliotheek is niet geïnstalleerd of beschikbaar. Meldingsfuncties zijn uitgeschakeld.",
+ "apprise_url": "Apprise-URL",
+ "apprise_url_desc": "Uw Apprise-meldingsservice-URL",
+ "apprise_mode": "Meldingsmodus",
+ "apprise_mode_desc": "Kies wanneer Apprise-meldingen moeten worden verzonden",
+ "apprise_mode_global": "Globaal overzicht",
+ "apprise_mode_individual": "Per gebruiker",
+ "test_paperless": "Paperless-verbinding testen",
+ "test_apprise": "Apprise-verbinding testen",
+ "apprise_warranty_scope": "Garantiebereik",
+ "apprise_warranty_scope_desc": "Kies welke garanties in meldingen moeten worden opgenomen",
+ "all_warranties": "Alle garanties",
+ "personal_warranties": "Alleen persoonlijke garanties",
+ "all_users_warranties": "Garanties van alle gebruikers",
+ "admin_warranties_only": "Alleen garanties van de beheerder",
+ "apprise_notification_days": "Meldingsdagen",
+ "apprise_notification_days_desc": "Dagen voor verval om meldingen te verzenden (door komma's gescheiden, bijv. \"7,30\" voor 7 dagen en 30 dagen van tevoren)",
+ "apprise_check_frequency": "Controlefrequentie",
+ "apprise_check_frequency_desc": "Hoe vaak het systeem controleert op verlopende garanties (globale instelling)",
+ "apprise_title_prefix": "Berichtkop-prefix",
+ "apprise_title_prefix_desc": "Prefix toegevoegd aan meldingstitels (bijv. \"[Warracker]\" resulteert in \"[Warracker] Garanties verlopen binnenkort\")",
+ "apprise_test_url": "Test-URL (optioneel)",
+ "apprise_test_url_desc": "Optioneel: URL voor het alleen verzenden van testmeldingen (wordt niet opgeslagen in de hoofdconfiguratie)",
+ "save_apprise_settings": "Apprise-instellingen opslaan",
+ "validate_urls": "URL's valideren",
+ "send_expiration_notifications_now": "Vervaldatummeldingen nu verzenden",
+ "apprise_current_status": "Huidige status",
+ "apprise_urls_configured": "Geconfigureerde URL's:",
+ "apprise_supported_services": "Ondersteunde services",
+ "apprise_supported_services_desc": "Apprise ondersteunt meer dan 80 meldingsservices, waaronder: Discord, Slack, Telegram, E-mail (Gmail, Outlook), Webhooks, Microsoft Teams, Matrix, Pushover, Ntfy, Gotify en nog veel meer.",
+ "view_full_list_of_supported_services": "Volledige lijst van ondersteunde services bekijken",
+ "ownership_management": "Eigendomsbeheer",
+ "transfer_ownership": "Eigendom overdragen",
+ "warning_title": "Waarschuwing:",
+ "transfer_ownership_warning": "Applicatie-eigendom overdragen aan een andere beheerdersgebruiker. Deze actie is onomkeerbaar.",
+ "transfer_ownership_desc": "Zodra het eigendom is overgedragen, wordt u een gewone beheerder en heeft de nieuwe eigenaar de uiteindelijke controle over de applicatie.",
+ "select_new_owner": "Selecteer nieuwe eigenaar (moet een beheerder zijn)",
+ "select_admin_user": "Selecteer een beheerdersgebruiker...",
+ "transfer_ownership_button": "Eigendom overdragen",
+ "transfer_ownership_irreversible": "Deze actie kan niet ongedaan worden gemaakt.",
+ "transfer_ownership_confirmation": "U staat op het punt het applicatie-eigendom over te dragen aan",
+ "after_this_transfer": "Na deze overdracht:",
+ "transfer_ownership_consequence_1": "U wordt een gewone beheerder",
+ "transfer_ownership_consequence_2": "De nieuwe eigenaar heeft de uiteindelijke controle over de applicatie",
+ "transfer_ownership_consequence_3": "Alleen de nieuwe eigenaar kan het eigendom opnieuw overdragen",
+ "transfer_ownership_type_to_confirm": "Typ \"TRANSFER\" in het onderstaande veld om te bevestigen:"
+ },
+ "actions": {
+ "save": "Opslaan",
+ "cancel": "Annuleren",
+ "delete": "Verwijderen",
+ "edit": "Bewerken",
+ "export": "Exporteren",
+ "import": "Importeren",
+ "refresh": "Vernieuwen",
+ "search": "Zoeken",
+ "clear": "Wissen",
+ "upload": "Uploaden",
+ "download": "Downloaden",
+ "manage_tags": "Tags beheren",
+ "close": "Sluiten",
+ "save_changes": "Wijzigingen opslaan"
+ },
+ "filters": {
+ "all_status": "Alle statussen",
+ "all_tags": "Alle tags",
+ "all_vendors": "Alle leveranciers",
+ "all_types": "Alle typen",
+ "sort_by": "Sorteren op",
+ "sort_expiration": "Vervaldatum",
+ "sort_purchase": "Aankoopdatum",
+ "sort_age": "Leeftijd",
+ "sort_name": "Productnaam",
+ "sort_vendor": "Leverancier",
+ "sort_warranty_type": "Garantietype",
+ "status": "Status",
+ "tags": "Tags",
+ "vendor": "Leverancier",
+ "warranty_type": "Garantietype",
+ "view": "Weergave",
+ "scope": "Bereik"
+ },
+ "messages": {
+ "success": "Succes",
+ "error": "Fout",
+ "warning": "Waarschuwing",
+ "loading": "Laden...",
+ "saved": "Wijzigingen succesvol opgeslagen",
+ "deleted": "Item succesvol verwijderd",
+ "confirm_delete": "Weet u zeker dat u dit item wilt verwijderen?",
+ "no_results": "Geen resultaten gevonden",
+ "file_too_large": "Bestand is te groot",
+ "invalid_file_type": "Ongeldig bestandstype",
+ "fill_first_last_name": "Vul a.u.b. voornaam en achternaam in",
+ "email_cannot_be_empty": "E-mailadres kan niet leeg zijn.",
+ "enter_valid_email": "Voer a.u.b. een geldig e-mailadres in.",
+ "profile_updated_successfully": "Profiel succesvol bijgewerkt",
+ "preferences_saved_successfully": "Voorkeuren succesvol opgeslagen.",
+ "fill_password_fields": "Vul a.u.b. alle wachtwoordvelden in",
+ "passwords_do_not_match": "De nieuwe wachtwoorden komen niet overeen",
+ "password_min_length": "Wachtwoord moet minstens 8 tekens lang zijn",
+ "type_delete_to_confirm": "Typ a.u.b. DELETE om te bevestigen",
+ "account_deleted_successfully": "Account succesvol verwijderd",
+ "account_cannot_delete_offline": "Account kan niet offline worden verwijderd",
+ "failed_delete_account": "Kon account niet verwijderen. Probeer opnieuw.",
+ "user_updated_successfully": "Gebruiker succesvol bijgewerkt",
+ "user_deleted_successfully": "Gebruiker succesvol verwijderd",
+ "user_id_missing": "Gebruikers-ID ontbreekt",
+ "failed_load_users": "Kon gebruikers niet laden",
+ "error_loading_users": "Fout bij het laden van gebruikers",
+ "select_user_transfer_ownership": "Selecteer a.u.b. een gebruiker om eigendom naar over te dragen",
+ "ownership_transferred_successfully": "Eigendom succesvol overgedragen! Pagina wordt vernieuwd...",
+ "failed_load_site_settings": "Kon site-instellingen niet laden. Probeer opnieuw.",
+ "invalid_email_base_url": "Ongeldig e-mail basis URL formaat. Moet beginnen met http:// of https://",
+ "no_site_settings_to_save": "Geen site-instellingen om op te slaan.",
+ "site_settings_saved_successfully": "Site-instellingen succesvol opgeslagen",
+ "failed_save_site_settings": "Kon site-instellingen niet opslaan",
+ "oidc_settings_saved_successfully": "OIDC-instellingen succesvol opgeslagen.",
+ "failed_save_oidc_settings": "Kon OIDC-instellingen niet opslaan.",
+ "api_endpoint_accessible": "API-eindpunt is toegankelijk",
+ "api_endpoint_not_accessible": "API-eindpunt is niet toegankelijk. Status: ",
+ "only_admins_send_notifications": "Alleen beheerders kunnen garantienotificaties verzenden",
+ "notifications_triggered_successfully": "Meldingen succesvol geactiveerd",
+ "notification_settings_saved_successfully": "Meldingsinstellingen succesvol opgeslagen",
+ "apprise_settings_saved_successfully": "Apprise-instellingen succesvol opgeslagen",
+ "test_notification_sent_successfully": "Testmelding succesvol verzonden",
+ "no_urls_to_validate": "Geen URL's om te valideren",
+ "paperless_settings_saved_successfully": "Paperless-ngx instellingen succesvol opgeslagen!",
+ "enter_valid_paperless_url": "Voer a.u.b. een geldige URL in (bijv. https://paperless.uwdomein.com)",
+ "enter_paperless_url_first": "Voer eerst a.u.b. een Paperless-ngx URL in",
+ "paperless_connection_test_successful": "Paperless-ngx verbindingstest succesvol!",
+ "paperless_connection_test_failed": "Paperless-ngx verbindingstest mislukt",
+ "enter_api_token_test_connection": "Voer a.u.b. een API-token in om de verbinding te testen",
+ "failed_load_user_data": "Kon gebruikersgegevens niet laden. Probeer opnieuw.",
+ "could_not_connect_user_data": "Kon geen verbinding maken om gebruikersgegevens op te halen. Gecachte informatie wordt weergegeven.",
+ "preferences_saved_locally_failed_sync": "Voorkeuren lokaal opgeslagen, maar kon niet synchroniseren met server: ",
+ "preferences_saved_locally": "Voorkeuren lokaal opgeslagen.",
+ "correct_errors_in_tab": "Corrigeer de fouten in het gemarkeerde tabblad voordat u doorgaat.",
+ "please_fill_out_this_field": "Vul dit veld in.",
+ "warranty_added_successfully": "Garantie succesvol toegevoegd",
+ "tag_name_required": "Tag naam is vereist",
+ "tag_creation_function_not_found": "Tag aanmaak functie niet gevonden",
+ "tag_created_successfully": "Tag succesvol aangemaakt",
+ "tag_updated_successfully": "Tag succesvol bijgewerkt",
+ "tag_deleted_successfully": "Tag succesvol verwijderd",
+ "failed_to_create_tag": "Fout bij aanmaken tag",
+ "failed_to_update_tag": "Fout bij bijwerken tag",
+ "failed_to_delete_tag": "Fout bij verwijderen tag"
+ },
+ "languages": {
+ "en": "Engels",
+ "fr": "Frans",
+ "es": "Spaans",
+ "de": "Duits",
+ "it": "Italiaans",
+ "cs": "Tsjechisch",
+ "nl": "Nederlands",
+ "hi": "Hindi",
+ "fa": "Perzisch",
+ "ar": "Arabisch",
+ "ru": "Russisch",
+ "uk": "Oekraïens",
+ "zh_CN": "Chinees (vereenvoudigd)",
+ "zh_HK": "Chinees (traditioneel)",
+ "ja": "Japans",
+ "pt": "Portugees",
+ "ko": "Koreaans"
+ },
+ "status": {
+ "title": "Systeemstatus",
+ "dashboard_title": "Garantiestatusdashboard",
+ "global_dashboard_title": "Globaal Garantiestatusdashboard",
+ "overview": "Overzicht",
+ "statistics": "Statistieken",
+ "total_warranties": "Totaal aantal garanties",
+ "active_warranties": "Actieve garanties",
+ "expiring_soon": "Verloopt binnenkort",
+ "expired_warranties": "Verlopen garanties",
+ "warranty_distribution": "Garantieverdeling",
+ "expiration_timeline": "Vervaltijdlijn",
+ "recent_activity": "Recente activiteit",
+ "recent_expirations": "Recent verlopen of binnenkort verlopend",
+ "recent_expirations_empty": "Geen recent verlopen of binnenkort verlopende garanties.",
+ "system_health": "Systeemgezondheid",
+ "database_status": "Database-status",
+ "connected": "Verbonden",
+ "version": "Versie",
+ "uptime": "Uptime"
+ },
+ "about": {
+ "title": "Over Warracker",
+ "description": "Een uitgebreid garantiebeheersysteem dat is ontworpen om u te helpen al uw productgaranties op één veilig, gebruiksvriendelijk platform te volgen, organiseren en beheren.",
+ "version": "Versie",
+ "update_status": "Updatestatus",
+ "checking_updates": "Controleren op updates...",
+ "view_release_notes": "Release-opmerkingen bekijken",
+ "project_info": "Projectinformatie",
+ "project_description": "Warracker is een open-source garantiebeheersysteem gebouwd met moderne webtechnologieën. Het biedt een veilige en intuïtieve manier om productgaranties te beheren, vervaldata te volgen en belangrijke documenten te organiseren.",
+ "github_repository": "GitHub-repository",
+ "releases": "Releases",
+ "community_support": "Community & Ondersteuning",
+ "community_description": "Word lid van onze community voor ondersteuning, discussies en updates. Meld bugs, vraag functies aan of krijg hulp van andere gebruikers en bijdragers.",
+ "discord_community": "Discord-community",
+ "report_issues": "Problemen melden",
+ "developer_info": "Ontwikkelaarsinformatie",
+ "developer_description": "Warracker wordt ontwikkeld en onderhouden door Sassanix. Het project is open-source en verwelkomt bijdragen van de community.",
+ "sassanix": "Sassanix",
+ "agpl_license": "AGPL-3.0-licentie",
+ "support_project": "Steun het project",
+ "support_description": "Als u Warracker nuttig vindt, overweeg dan om de ontwikkeling ervan te ondersteunen!",
+ "new_version_available": "Nieuwe versie {{version}} beschikbaar!",
+ "latest_version": "U gebruikt de nieuwste versie",
+ "update_check_failed": "Kon niet controleren op updates",
+ "features": "Functies",
+ "feature_track": "Productgaranties volgen",
+ "feature_notifications": "Vervalmeldingen ontvangen",
+ "feature_documents": "Garantiedocumenten opslaan",
+ "feature_reports": "Garantierapporten genereren",
+ "feature_tags": "Organiseren met tags",
+ "feature_export": "Garantiegegevens exporteren",
+ "support": "Ondersteuning",
+ "documentation": "Documentatie",
+ "github": "GitHub",
+ "license": "Licentie",
+ "copyright": "Copyright",
+ "developed_by": "Ontwikkeld door"
+ }
+}
\ No newline at end of file
diff --git a/locales/pt/translation.json b/locales/pt/translation.json
new file mode 100644
index 0000000..7abc738
--- /dev/null
+++ b/locales/pt/translation.json
@@ -0,0 +1,560 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "Rastreador de Garantias",
+ "nav": {
+ "home": "Início",
+ "status": "Status",
+ "settings": "Configurações",
+ "about": "Sobre"
+ },
+ "auth": {
+ "login": "Login",
+ "logout": "Sair",
+ "register": "Registrar",
+ "username": "Nome de usuário",
+ "password": "Senha",
+ "email": "E-mail",
+ "first_name": "Nome",
+ "last_name": "Sobrenome",
+ "forgot_password": "Esqueceu a senha?",
+ "reset_password": "Redefinir senha",
+ "confirm_password": "Confirmar senha",
+ "create_account_title": "Crie sua conta",
+ "first_name_optional": "Nome (opcional)",
+ "last_name_optional": "Sobrenome (opcional)",
+ "username_hint": "O nome de usuário deve ser único e será usado para o login.",
+ "email_address": "Endereço de e-mail",
+ "toggle_password": "Mostrar/Ocultar senha",
+ "password_hint_simple": "A senha deve ter pelo menos 8 caracteres e incluir letras maiúsculas, minúsculas e números.",
+ "password_requirements": "Requisitos da senha:",
+ "req_length": "Pelo menos 8 caracteres",
+ "req_uppercase": "Pelo menos 1 letra maiúscula",
+ "req_lowercase": "Pelo menos 1 letra minúscula",
+ "req_number": "Pelo menos 1 número",
+ "req_special": "Pelo menos 1 caractere especial",
+ "create_account": "Criar conta",
+ "already_have_account": "Já tem uma conta?",
+ "reset_password_title": "Warracker - Redefinir senha",
+ "reset_your_password": "Redefina sua senha",
+ "reset_password_info": "Digite seu endereço de e-mail abaixo e enviaremos um link para redefinir sua senha.",
+ "send_reset_link": "Enviar link de redefinição",
+ "back_to_login": "Voltar para o login",
+ "set_new_password_title": "Warracker - Definir nova senha",
+ "set_new_password": "Definir nova senha",
+ "new_password": "Nova senha",
+ "confirm_new_password": "Confirmar nova senha",
+ "invalid_or_expired_link": "Link inválido ou expirado",
+ "invalid_link_info": "O link de redefinição de senha que você clicou é inválido ou expirou.",
+ "request_new_reset_link": "Solicitar novo link de redefinição"
+ },
+ "warranties": {
+ "title": "Suas Garantias",
+ "title_global": "Garantias de Todos os Usuários",
+ "add_new": "Adicionar Nova Garantia",
+ "edit": "Editar Garantia",
+ "delete": "Excluir Garantia",
+ "product_name": "Nome do Produto",
+ "purchase_date": "Data da Compra",
+ "warranty_duration": "Duração da Garantia",
+ "years": "Anos",
+ "months": "Meses",
+ "days": "Dias",
+ "vendor": "Fornecedor",
+ "serial_numbers": "Números de Série",
+ "purchase_price": "Preço de Compra",
+ "notes": "Notas",
+ "tags": "Etiquetas",
+ "status": "Status",
+ "expiration_date": "Data de Expiração",
+ "active": "Ativa",
+ "expired": "Expirada",
+ "expiring_soon": "Expirando em Breve",
+ "lifetime": "Vitalícia",
+ "no_warranties": "Nenhuma garantia ainda. Adicione sua primeira garantia para começar.",
+ "search_placeholder": "Encontre por nome, fornecedores, notas, etiqueta ou número de série...",
+ "warranty_type": "Tipo de Garantia",
+ "other_document": "Outro Documento",
+ "product": "Produto",
+ "expiration": "Expiração",
+ "actions": "Ações",
+ "no_warranties_title": "Nenhuma garantia ainda",
+ "no_warranties_desc": "Adicione sua primeira garantia para começar",
+ "add_warranty": "Adicionar Garantia",
+ "warranty_entry_method": "Método de Entrada da Garantia",
+ "warranty_duration_option": "Duração da Garantia",
+ "exact_expiration_option": "Data de Expiração Exata",
+ "warranty_period": "Período de Garantia",
+ "expiration_date_label": "Data de Expiração",
+ "currency": "Moeda",
+ "add_tags": "Adicionar Etiquetas",
+ "add_tags_desc": "Etiquetas ajudam a organizar e filtrar suas garantias",
+ "save_changes": "Salvar Alterações",
+ "confirm_delete": "Confirmar Exclusão",
+ "manage_tags": "Gerenciar Etiquetas",
+ "add_tag": "Adicionar Etiqueta",
+ "unknown_status": "Status Desconhecido",
+ "expiring_soon_days": "Expirando em Breve ({{days}} {{dayText}})",
+ "days_remaining": "Restam {{days}} {{dayText}}",
+ "day_one": "dia",
+ "day_other": "dias",
+ "month_one": "mês",
+ "month_other": "meses",
+ "year_one": "ano",
+ "year_other": "anos",
+ "na": "N/A",
+ "age": "Idade",
+ "warranty": "Garantia",
+ "warranty_ends": "A Garantia Termina",
+ "price": "Preço",
+ "serial_number": "Número de Série",
+ "vendor": "Fornecedor",
+ "type": "Tipo",
+ "owner": "Proprietário",
+ "product_website": "Site do Produto",
+ "documents": "Documentos",
+ "summary": "Resumo",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "Anos",
+ "months_placeholder": "Meses",
+ "days_placeholder": "Dias",
+ "add_any_notes_placeholder": "Adicionar notas sobre esta garantia...",
+ "product_url_optional": "URL do Produto (Opcional)",
+ "enter_serial_number": "Digite o número de série",
+ "vendor_optional": "Fornecedor (Opcional)",
+ "vendor_placeholder": "ex: Amazon, Best Buy, etc.",
+ "lifetime_warranty": "Garantia Vitalícia",
+ "warranty_type_optional": "Tipo de Garantia (Opcional)",
+ "select_warranty_type": "Selecione o tipo de garantia...",
+ "standard": "Padrão",
+ "extended": "Estendida",
+ "manufacturer": "Fabricante",
+ "third_party": "Terceiros",
+ "store": "Loja",
+ "premium": "Premium",
+ "limited": "Limitada",
+ "full": "Completa",
+ "parts_only": "Apenas Peças",
+ "labor_only": "Apenas Mão de Obra",
+ "international": "Internacional",
+ "accidental_damage": "Danos Acidentais",
+ "other_custom": "Outro (Personalizado)",
+ "enter_custom_warranty_type": "Digite o tipo de garantia personalizado",
+ "purchase_price_optional": "Preço de Compra (Opcional)",
+ "notes_optional": "Notas (Opcional)",
+ "add_any_notes": "Adicione qualquer nota sobre esta garantia...",
+ "product_photo_optional": "Foto do Produto (Opcional)",
+ "choose_photo": "Escolher Foto",
+ "invoice_receipt": "Fatura/Recibo",
+ "store_locally": "Armazenar Localmente",
+ "store_in_paperless": "Armazenar no Paperless-ngx",
+ "choose_file": "Escolher Arquivo",
+ "browse_paperless": "Navegar nos Documentos do Paperless-ngx",
+ "product_manual_optional": "Manual do Produto (Opcional)",
+ "files_zip_rar_optional": "Arquivos (ZIP/RAR, Opcional)",
+ "search_or_add_new_tag": "Pesquisar ou adicionar nova etiqueta...",
+ "product_information": "Informações do Produto",
+ "product_url": "URL do Produto",
+ "warranty_details": "Detalhes da Garantia",
+ "product_photo": "Foto do Produto",
+ "product_manual": "Manual do Produto",
+ "files": "Arquivos",
+ "selected_tags": "Etiquetas Selecionadas",
+ "previous_tab": "Anterior",
+ "next_tab": "Próximo",
+ "delete_photo": "Excluir Foto",
+ "delete_invoice": "Excluir Fatura",
+ "delete_manual": "Excluir Manual",
+ "delete_files": "Excluir Arquivos",
+ "current_photo": "Foto atual:",
+ "current_invoice": "Fatura atual:",
+ "current_manual": "Manual atual:",
+ "current_document": "Documento atual:",
+ "upload_new_photo_replace": "(Carregue uma nova foto para substituir)",
+ "no_photo_uploaded": "Nenhuma foto carregada",
+ "no_invoice_uploaded": "Nenhuma fatura carregada",
+ "no_manual_uploaded": "Nenhum manual carregado",
+ "no_document_uploaded": "Nenhum outro documento carregado",
+ "photo_will_be_deleted": "A foto será excluída ao salvar",
+ "invoice_will_be_deleted": "A fatura será excluída ao salvar",
+ "manual_will_be_deleted": "O manual será excluído ao salvar",
+ "document_will_be_deleted": "O outro documento será excluído ao salvar",
+ "confirm_delete_message": "Tem certeza de que deseja excluir esta garantia? Esta ação não pode ser desfeita.",
+ "new_tag_name": "Novo nome da etiqueta",
+ "existing_tags": "Etiquetas Existentes",
+ "edit_warranty": "Editar Garantia",
+ "warranty_type_standard": "Padrão",
+ "warranty_type_extended": "Estendida",
+ "warranty_type_manufacturer": "Fabricante",
+ "warranty_type_third_party": "Terceiros",
+ "warranty_type_store": "Loja",
+ "warranty_type_premium": "Premium",
+ "warranty_type_limited": "Limitada",
+ "warranty_type_full": "Completa",
+ "warranty_type_parts_only": "Apenas Peças",
+ "warranty_type_labor_only": "Apenas Mão de Obra",
+ "warranty_type_international": "Internacional",
+ "warranty_type_accidental_damage": "Danos Acidentais",
+ "warranty_type_other": "Outro (Personalizado)",
+ "warranty_type_custom_placeholder": "Digite o tipo de garantia personalizado",
+ "notes_placeholder": "Notas adicionais sobre esta garantia...",
+ "tags_help_text": "Etiquetas ajudam a organizar e filtrar suas garantias",
+ "search_add_tag_placeholder": "Pesquisar ou adicionar nova etiqueta...",
+ "upload_new_file_replace": "Carregue um novo arquivo para substituir",
+ "current_other_document": "Outro documento atual",
+ "no_other_document_uploaded": "Nenhum outro documento carregado",
+ "other_document_will_be_deleted": "O outro documento será excluído ao salvar",
+ "files_optional": "Arquivos (ZIP/RAR, Opcional)",
+ "invoice_receipt_short": "Fatura",
+ "product_manual_short": "Manual",
+ "files_short": "Arquivos",
+ "enter_serial_number": "Inserir número de série",
+ "add_serial_number": "Adicionar outro número de série"
+ },
+ "settings": {
+ "title": "Configurações",
+ "account_settings": "Configurações da Conta",
+ "preferences": "Preferências",
+ "language": "Idioma",
+ "select_language": "Selecione o Idioma",
+ "dark_mode": "Modo Escuro",
+ "dark_mode_desc": "Alternar entre tema claro e escuro",
+ "currency": "Moeda",
+ "timezone": "Fuso Horário",
+ "date_format": "Formato da Data",
+ "expiring_soon_days": "Dias para Expirar em Breve",
+ "save_changes": "Salvar Alterações",
+ "current_user": "Editando Perfil de:",
+ "your_email": "Seu e-mail:",
+ "first_name": "Nome",
+ "last_name": "Sobrenome",
+ "email": "E-mail",
+ "save_profile": "Salvar Alterações",
+ "default_view": "Visualização Padrão",
+ "default_view_desc": "Escolha sua visualização preferida para garantias",
+ "grid_view": "Visualização em Grade",
+ "list_view": "Visualização em Lista",
+ "table_view": "Visualização em Tabela",
+ "currency_symbol": "Símbolo da Moeda",
+ "currency_symbol_desc": "Escolha o símbolo a ser exibido para preços",
+ "currency_position": "Posição da Moeda",
+ "currency_position_desc": "Escolha se o símbolo da moeda aparece à esquerda ou à direita dos números",
+ "expiring_soon_days_desc": "Número de dias antes da expiração para mostrar avisos",
+ "date_format_desc": "Escolha como as datas são exibidas",
+ "save_preferences": "Salvar Preferências",
+ "notification_settings": "Configurações de Notificação",
+ "notification_channel": "Canal de Notificação",
+ "notification_channel_desc": "Escolha como deseja receber notificações",
+ "notification_disabled": "Desativado",
+ "notification_email": "E-mail",
+ "notification_apprise": "Apprise",
+ "notification_both": "Ambos",
+ "email_settings": "Configurações de E-mail",
+ "notification_frequency": "Frequência de Notificação",
+ "notification_frequency_desc": "Com que frequência receber notificações por e-mail",
+ "daily": "Diariamente",
+ "weekly": "Semanalmente",
+ "monthly": "Mensalmente",
+ "notification_time": "Hora da Notificação",
+ "timezone_desc": "Seu fuso horário local para notificações",
+ "apprise_settings": "Configurações do Apprise",
+ "apprise_frequency": "Frequência de Notificação do Apprise",
+ "apprise_frequency_desc": "Com que frequência receber notificações do Apprise",
+ "apprise_time": "Hora da Notificação do Apprise",
+ "apprise_timezone": "Fuso Horário do Apprise",
+ "apprise_timezone_desc": "Seu fuso horário local para notificações do Apprise",
+ "save_notification_settings": "Salvar Configurações de Notificação",
+ "security": "Segurança",
+ "change_password": "Alterar Senha",
+ "change_password_desc": "Atualize a senha da sua conta",
+ "change": "Alterar",
+ "current_password": "Senha Atual",
+ "new_password": "Nova Senha",
+ "confirm_password": "Confirmar Nova Senha",
+ "update_password": "Atualizar Senha",
+ "cancel": "Cancelar",
+ "danger_zone": "Zona de Perigo",
+ "delete_account": "Excluir Conta",
+ "delete_account_desc": "Excluir permanentemente sua conta e todos os dados",
+ "admin_settings": "Configurações de Administrador",
+ "admin_actions": "Ações de Administrador",
+ "refresh_data": "Atualizar Dados",
+ "check_admin_status": "Verificar Status de Administrador",
+ "show_users_list": "Mostrar Lista de Usuários",
+ "test_api": "Testar API",
+ "send_notifications": "Enviar Notificações de Garantia",
+ "check_scheduler": "Verificar Status do Agendador",
+ "site_settings": "Configurações do Site",
+ "registration_enabled": "Registro Habilitado",
+ "registration_enabled_desc": "Permitir que novos usuários se registrem",
+ "email_base_url": "URL Base do E-mail",
+ "global_view_enabled": "Visualização Global Habilitada",
+ "global_view_admin_only": "Visualização Global Apenas para Administradores",
+ "save_site_settings": "Salvar Configurações do Site",
+ "oidc_configuration": "Configuração OIDC SSO",
+ "enable_oidc": "Habilitar OIDC SSO",
+ "oidc_provider_name": "Nome do Provedor OIDC",
+ "client_id": "ID do Cliente",
+ "client_secret": "Segredo do Cliente",
+ "issuer_url": "URL do Emissor",
+ "scope": "Escopo",
+ "save_oidc_settings": "Salvar Configurações OIDC",
+ "oidc_sso_desc": "Permitir que os usuários façam login através de um provedor OIDC.",
+ "oidc_only_mode": "Modo de Login Apenas OIDC",
+ "oidc_only_mode_desc": "Ocultar o formulário de login tradicional de nome de usuário/senha e permitir apenas o login OIDC. <strong>Aviso:</strong> Certifique-se de que o OIDC esteja configurado corretamente antes de habilitar esta opção.",
+ "oidc_provider_name_desc": "Nome interno para o cliente OIDC (ex: 'oidc').",
+ "client_secret_desc": "Valor sensível. Armazenado no banco de dados. É necessário reiniciar a aplicação para que as alterações entrem em vigor.",
+ "issuer_url_desc": "A URL base do seu provedor OIDC.",
+ "scope_desc": "Escopos OIDC separados por espaço.",
+ "oidc_restart_message": "É necessário reiniciar a aplicação para que as configurações OIDC entrem em vigor completamente.",
+ "api_token": "Token da API",
+ "view_documents": "Visualizar Documentos no Warracker",
+ "connection_testing": "Teste de Conexão",
+ "apprise_notifications": "Notificações do Apprise",
+ "enable_apprise": "Habilitar Notificações do Apprise",
+ "loading": "Carregando...",
+ "time_of_day_notification": "Hora do dia para receber notificações (formato 24 horas)",
+ "paperless_ngx_settings": "Configurações do Paperless-ngx",
+ "paperless_ngx_about_title": "Sobre a Integração com o Paperless-ngx:",
+ "paperless_ngx_about_desc": "Este recurso opcional permite que você armazene documentos de garantia em sua instância auto-hospedada do Paperless-ngx em vez de localmente. Quando habilitado, os usuários podem escolher onde armazenar cada documento: localmente ou no Paperless-ngx.",
+ "paperless_ngx_desc": "Configure a integração com o sistema de gerenciamento de documentos Paperless-ngx",
+ "enable_paperless": "Habilitar Integração com o Paperless-ngx",
+ "paperless_url": "URL do Paperless-ngx",
+ "paperless_url_desc": "URL base da sua instância do Paperless-ngx",
+ "paperless_token": "Token da API",
+ "paperless_token_desc": "Seu token de autenticação da API do Paperless-ngx",
+ "paperless_token_desc_generate": "Gere um token de API em sua instância do Paperless-ngx (Configurações → Tokens de API).",
+ "paperless_view_in_app": "Visualizar documentos no aplicativo",
+ "paperless_view_in_app_desc": "Abrir documentos dentro do aplicativo em vez de em uma nova aba",
+ "debug_config": "Configuração de Depuração",
+ "test_upload": "Testar Upload",
+ "save_paperless_settings": "Salvar Configurações do Paperless-ngx",
+ "apprise_desc": "Configure o Apprise para entrega avançada de notificações para múltiplos serviços",
+ "apprise_desc_system_wide": "Habilitar ou desabilitar as notificações do Apprise em todo o sistema",
+ "apprise_not_available_title": "Apprise Não Disponível:",
+ "apprise_not_available_desc": "A biblioteca de notificações Apprise não está instalada ou disponível. Os recursos de notificação estão desativados.",
+ "apprise_url": "URL do Apprise",
+ "apprise_url_desc": "A URL do seu serviço de notificação Apprise",
+ "apprise_mode": "Modo de Notificação",
+ "apprise_mode_desc": "Escolha quando enviar notificações do Apprise",
+ "apprise_mode_global": "Resumo Global",
+ "apprise_mode_individual": "Por Usuário",
+ "test_paperless": "Testar Conexão com o Paperless",
+ "test_apprise": "Testar Conexão com o Apprise",
+ "apprise_warranty_scope": "Escopo da Garantia",
+ "apprise_warranty_scope_desc": "Escolha quais garantias incluir nas notificações",
+ "all_warranties": "Todas as Garantias",
+ "personal_warranties": "Apenas Garantias Pessoais",
+ "all_users_warranties": "Garantias de Todos os Usuários",
+ "admin_warranties_only": "Apenas Garantias do Administrador",
+ "apprise_notification_days": "Dias de Notificação",
+ "apprise_notification_days_desc": "Dias antes da expiração para enviar notificações (separados por vírgula, ex: \"7,30\" para 7 e 30 dias antes)",
+ "apprise_check_frequency": "Frequência de Verificação",
+ "apprise_check_frequency_desc": "Com que frequência o sistema verifica garantias expirando (configuração global)",
+ "apprise_title_prefix": "Prefixo do Título da Mensagem",
+ "apprise_title_prefix_desc": "Prefixo adicionado aos títulos das notificações (ex: \"[Warracker]\" resulta em \"[Warracker] Garantias Expirando em Breve\")",
+ "apprise_test_url": "URL de Teste (Opcional)",
+ "apprise_test_url_desc": "Opcional: URL para enviar apenas notificações de teste (não será salvo na configuração principal)",
+ "save_apprise_settings": "Salvar Configurações do Apprise",
+ "validate_urls": "Validar URLs",
+ "send_expiration_notifications_now": "Enviar Notificações de Expiração Agora",
+ "apprise_current_status": "Status Atual",
+ "apprise_urls_configured": "URLs Configurados:",
+ "apprise_supported_services": "Serviços Suportados",
+ "apprise_supported_services_desc": "O Apprise suporta mais de 80 serviços de notificação, incluindo: Discord, Slack, Telegram, E-mail (Gmail, Outlook), Webhooks, Microsoft Teams, Matrix, Pushover, Ntfy, Gotify e muitos outros.",
+ "view_full_list_of_supported_services": "Ver Lista Completa de Serviços Suportados",
+ "ownership_management": "Gerenciamento de Propriedade",
+ "transfer_ownership": "Transferir Propriedade",
+ "warning_title": "Aviso:",
+ "transfer_ownership_warning": "Transferir a propriedade da aplicação para outro usuário administrador. Esta ação é irreversível.",
+ "transfer_ownership_desc": "Uma vez que a propriedade seja transferida, você se tornará um administrador regular e o novo proprietário terá controle total sobre a aplicação.",
+ "select_new_owner": "Selecione o Novo Proprietário (deve ser um administrador)",
+ "select_admin_user": "Selecione um usuário administrador...",
+ "transfer_ownership_button": "Transferir Propriedade",
+ "transfer_ownership_irreversible": "Esta ação não pode ser desfeita.",
+ "transfer_ownership_confirmation": "Você está prestes a transferir a propriedade da aplicação para",
+ "after_this_transfer": "Após esta transferência:",
+ "transfer_ownership_consequence_1": "Você se tornará um administrador regular",
+ "transfer_ownership_consequence_2": "O novo proprietário terá controle total sobre a aplicação",
+ "transfer_ownership_consequence_3": "Apenas o novo proprietário poderá transferir a propriedade novamente",
+ "transfer_ownership_type_to_confirm": "Para confirmar, digite \"TRANSFER\" no campo abaixo:"
+ },
+ "actions": {
+ "save": "Salvar",
+ "cancel": "Cancelar",
+ "delete": "Excluir",
+ "edit": "Editar",
+ "export": "Exportar",
+ "import": "Importar",
+ "refresh": "Atualizar",
+ "search": "Pesquisar",
+ "clear": "Limpar",
+ "upload": "Carregar",
+ "download": "Baixar",
+ "manage_tags": "Gerenciar Etiquetas",
+ "close": "Fechar",
+ "save_changes": "Salvar Alterações"
+ },
+ "filters": {
+ "all_status": "Todos os Status",
+ "all_tags": "Todas as Etiquetas",
+ "all_vendors": "Todos os Fornecedores",
+ "all_types": "Todos os Tipos",
+ "sort_by": "Ordenar por",
+ "sort_expiration": "Data de Expiração",
+ "sort_purchase": "Data de Compra",
+ "sort_age": "Idade",
+ "sort_name": "Nome do Produto",
+ "sort_vendor": "Fornecedor",
+ "sort_warranty_type": "Tipo de Garantia",
+ "status": "Status",
+ "tags": "Etiquetas",
+ "vendor": "Fornecedor",
+ "warranty_type": "Tipo de Garantia",
+ "view": "Visualização",
+ "scope": "Escopo"
+ },
+ "messages": {
+ "success": "Sucesso",
+ "error": "Erro",
+ "warning": "Aviso",
+ "loading": "Carregando...",
+ "saved": "Alterações salvas com sucesso",
+ "deleted": "Item excluído com sucesso",
+ "confirm_delete": "Tem certeza de que deseja excluir este item?",
+ "no_results": "Nenhum resultado encontrado",
+ "file_too_large": "O arquivo é muito grande",
+ "invalid_file_type": "Tipo de arquivo inválido",
+ "fill_first_last_name": "Por favor, preencha o Nome e Sobrenome",
+ "email_cannot_be_empty": "O endereço de email não pode estar vazio.",
+ "enter_valid_email": "Por favor, insira um endereço de email válido.",
+ "profile_updated_successfully": "Perfil atualizado com sucesso",
+ "preferences_saved_successfully": "Preferências salvas com sucesso.",
+ "fill_password_fields": "Por favor, preencha todos os campos de senha",
+ "passwords_do_not_match": "As novas senhas não coincidem",
+ "password_min_length": "A senha deve ter pelo menos 8 caracteres",
+ "type_delete_to_confirm": "Por favor, digite DELETE para confirmar",
+ "account_deleted_successfully": "Conta excluída com sucesso",
+ "account_cannot_delete_offline": "A conta não pode ser excluída no modo offline",
+ "failed_delete_account": "Falha ao excluir a conta. Tente novamente.",
+ "user_updated_successfully": "Usuário atualizado com sucesso",
+ "user_deleted_successfully": "Usuário excluído com sucesso",
+ "user_id_missing": "ID do usuário está faltando",
+ "failed_load_users": "Falha ao carregar usuários",
+ "error_loading_users": "Erro ao carregar usuários",
+ "select_user_transfer_ownership": "Por favor, selecione um usuário para transferir a propriedade",
+ "ownership_transferred_successfully": "Propriedade transferida com sucesso! Atualizando página...",
+ "failed_load_site_settings": "Falha ao carregar configurações do site. Tente novamente.",
+ "invalid_email_base_url": "Formato de URL base de email inválido. Deve começar com http:// ou https://",
+ "no_site_settings_to_save": "Nenhuma configuração do site para salvar.",
+ "site_settings_saved_successfully": "Configurações do site salvas com sucesso",
+ "failed_save_site_settings": "Falha ao salvar configurações do site",
+ "oidc_settings_saved_successfully": "Configurações OIDC salvas com sucesso.",
+ "failed_save_oidc_settings": "Falha ao salvar configurações OIDC.",
+ "api_endpoint_accessible": "Endpoint da API está acessível",
+ "api_endpoint_not_accessible": "Endpoint da API não está acessível. Status: ",
+ "only_admins_send_notifications": "Apenas administradores podem enviar notificações de garantia",
+ "notifications_triggered_successfully": "Notificações disparadas com sucesso",
+ "notification_settings_saved_successfully": "Configurações de notificação salvas com sucesso",
+ "apprise_settings_saved_successfully": "Configurações do Apprise salvas com sucesso",
+ "test_notification_sent_successfully": "Notificação de teste enviada com sucesso",
+ "no_urls_to_validate": "Nenhuma URL para validar",
+ "paperless_settings_saved_successfully": "Configurações do Paperless-ngx salvas com sucesso!",
+ "enter_valid_paperless_url": "Por favor, insira uma URL válida (ex: https://paperless.yourdomain.com)",
+ "enter_paperless_url_first": "Por favor, insira primeiro a URL do Paperless-ngx",
+ "paperless_connection_test_successful": "Teste de conexão do Paperless-ngx bem-sucedido!",
+ "paperless_connection_test_failed": "Teste de conexão do Paperless-ngx falhou",
+ "enter_api_token_test_connection": "Por favor, insira um token de API para testar a conexão",
+ "failed_load_user_data": "Falha ao carregar dados do usuário. Tente novamente.",
+ "could_not_connect_user_data": "Não foi possível conectar para buscar dados do usuário. Exibindo informações em cache.",
+ "preferences_saved_locally_failed_sync": "Preferências salvas localmente, mas falha ao sincronizar com o servidor: ",
+ "preferences_saved_locally": "Preferências salvas localmente.",
+ "correct_errors_in_tab": "Por favor, corrija os erros na aba destacada antes de continuar.",
+ "please_fill_out_this_field": "Por favor, preencha este campo.",
+ "warranty_added_successfully": "Garantia adicionada com sucesso",
+ "tag_name_required": "Nome da tag é obrigatório",
+ "tag_creation_function_not_found": "Função de criação de tag não encontrada",
+ "tag_created_successfully": "Tag criada com sucesso",
+ "tag_updated_successfully": "Tag atualizada com sucesso",
+ "tag_deleted_successfully": "Tag excluída com sucesso",
+ "failed_to_create_tag": "Falha ao criar tag",
+ "failed_to_update_tag": "Falha ao atualizar tag",
+ "failed_to_delete_tag": "Falha ao excluir tag"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية",
+ "ru": "Русский",
+ "uk": "Українська",
+ "zh_CN": "简体中文",
+ "zh_HK": "繁體中文",
+ "ja": "日本語",
+ "pt": "Português"
+ },
+ "status": {
+ "title": "Status do Sistema",
+ "dashboard_title": "Painel de Status da Garantia",
+ "global_dashboard_title": "Painel de Status da Garantia Global",
+ "overview": "Visão Geral",
+ "statistics": "Estatísticas",
+ "total_warranties": "Total de Garantias",
+ "active_warranties": "Garantias Ativas",
+ "expiring_soon": "Expirando em Breve",
+ "expired_warranties": "Garantias Expiradas",
+ "warranty_distribution": "Distribuição de Garantias",
+ "expiration_timeline": "Linha do Tempo de Expiração",
+ "recent_activity": "Atividade Recente",
+ "recent_expirations": "Expiradas Recentemente ou Expirando em Breve",
+ "recent_expirations_empty": "Nenhuma garantia expirada recentemente ou expirando em breve.",
+ "system_health": "Saúde do Sistema",
+ "database_status": "Status do Banco de Dados",
+ "connected": "Conectado",
+ "version": "Versão",
+ "uptime": "Tempo de Atividade"
+ },
+ "about": {
+ "title": "Sobre o Warracker",
+ "description": "Um sistema abrangente de gerenciamento de garantias projetado para ajudá-lo a rastrear, organizar e gerenciar todas as garantias de seus produtos em uma plataforma segura e fácil de usar.",
+ "version": "Versão",
+ "update_status": "Status da Atualização",
+ "checking_updates": "Verificando atualizações...",
+ "view_release_notes": "Ver Notas de Lançamento",
+ "project_info": "Informações do Projeto",
+ "project_description": "Warracker é um sistema de gerenciamento de garantias de código aberto construído com tecnologias web modernas. Ele fornece uma maneira segura e intuitiva de gerenciar garantias de produtos, rastrear datas de expiração e organizar documentos importantes.",
+ "github_repository": "Repositório GitHub",
+ "releases": "Lançamentos",
+ "community_support": "Comunidade e Suporte",
+ "community_description": "Junte-se à nossa comunidade para suporte, discussões e atualizações. Relate bugs, solicite recursos ou obtenha ajuda de outros usuários e contribuidores.",
+ "discord_community": "Comunidade Discord",
+ "report_issues": "Relatar Problemas",
+ "developer_info": "Informações do Desenvolvedor",
+ "developer_description": "Warracker é desenvolvido e mantido por Sassanix. O projeto é de código aberto e acolhe contribuições da comunidade.",
+ "sassanix": "Sassanix",
+ "agpl_license": "Licença AGPL-3.0",
+ "support_project": "Apoie o Projeto",
+ "support_description": "Se você acha o Warracker útil, considere apoiar seu desenvolvimento!",
+ "new_version_available": "Nova versão {{version}} disponível!",
+ "latest_version": "Você está usando a versão mais recente",
+ "update_check_failed": "Falha ao verificar atualizações",
+ "features": "Recursos",
+ "feature_track": "Rastrear garantias de produtos",
+ "feature_notifications": "Receber notificações de expiração",
+ "feature_documents": "Armazenar documentos de garantia",
+ "feature_reports": "Gerar relatórios de garantia",
+ "feature_tags": "Organizar com etiquetas",
+ "feature_export": "Exportar dados de garantia",
+ "support": "Suporte",
+ "documentation": "Documentação",
+ "github": "Repositório GitHub",
+ "license": "Licença",
+ "copyright": "Direitos Autorais",
+ "developed_by": "Desenvolvido por"
+ }
+}
diff --git a/locales/ru/translation.json b/locales/ru/translation.json
new file mode 100644
index 0000000..789a1f2
--- /dev/null
+++ b/locales/ru/translation.json
@@ -0,0 +1,567 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "Трекер гарантий",
+ "nav": {
+ "home": "Главная",
+ "status": "Статус",
+ "settings": "Настройки",
+ "about": "О программе"
+ },
+ "auth": {
+ "login": "Войти",
+ "logout": "Выйти",
+ "register": "Регистрация",
+ "username": "Имя пользователя",
+ "password": "Пароль",
+ "email": "Электронная почта",
+ "first_name": "Имя",
+ "last_name": "Фамилия",
+ "forgot_password": "Забыли пароль?",
+ "reset_password": "Сбросить пароль",
+ "confirm_password": "Подтвердите пароль",
+ "create_account_title": "Создать аккаунт",
+ "first_name_optional": "Имя (необязательно)",
+ "last_name_optional": "Фамилия (необязательно)",
+ "username_hint": "Имя пользователя должно быть уникальным и будет использоваться для входа.",
+ "email_address": "Адрес электронной почты",
+ "toggle_password": "Показать/скрыть пароль",
+ "password_hint_simple": "Пароль должен содержать не менее 8 символов, включая заглавные и строчные буквы, а также цифры.",
+ "password_requirements": "Требования к паролю:",
+ "req_length": "Не менее 8 символов",
+ "req_uppercase": "Не менее 1 заглавной буквы",
+ "req_lowercase": "Не менее 1 строчной буквы",
+ "req_number": "Не менее 1 цифры",
+ "req_special": "Не менее 1 специального символа",
+ "create_account": "Создать аккаунт",
+ "already_have_account": "Уже есть аккаунт?",
+ "reset_password_title": "Warracker - Сброс пароля",
+ "reset_your_password": "Сбросить ваш пароль",
+ "reset_password_info": "Введите свой адрес электронной почты ниже, и мы вышлем вам ссылку для сброса пароля.",
+ "send_reset_link": "Отправить ссылку для сброса",
+ "back_to_login": "Вернуться ко входу",
+ "set_new_password_title": "Warracker - Установить новый пароль",
+ "set_new_password": "Установить новый пароль",
+ "new_password": "Новый пароль",
+ "confirm_new_password": "Подтвердите новый пароль",
+ "invalid_or_expired_link": "Неверная или истекшая ссылка",
+ "invalid_link_info": "Ссылка для сброса пароля, по которой вы перешли, недействительна или истекла.",
+ "request_new_reset_link": "Запросить новую ссылку для сброса"
+ },
+ "warranties": {
+ "title": "Ваши гарантии",
+ "title_global": "Гарантии всех пользователей",
+ "add_new": "Добавить новую гарантию",
+ "edit": "Редактировать гарантию",
+ "delete": "Удалить гарантию",
+ "product_name": "Название продукта",
+ "purchase_date": "Дата покупки",
+ "warranty_duration": "Срок гарантии",
+ "years": "Годы",
+ "months": "Месяцы",
+ "days": "Дни",
+ "vendor": "Продавец",
+ "serial_numbers": "Серийные номера",
+ "purchase_price": "Цена покупки",
+ "notes": "Заметки",
+ "tags": "Теги",
+ "status": "Статус",
+ "expiration_date": "Дата окончания",
+ "active": "Активна",
+ "expired": "Истекла",
+ "expiring_soon": "Скоро истекает",
+ "lifetime": "Пожизненная",
+ "no_warranties": "Гарантий пока нет. Добавьте свою первую гарантию, чтобы начать.",
+ "search_placeholder": "Поиск по названию, продавцам, заметкам, тегу или серийному номеру...",
+ "warranty_type": "Тип гарантии",
+ "other_document": "Другой документ",
+ "product": "Продукт",
+ "expiration": "Окончание",
+ "actions": "Действия",
+ "no_warranties_title": "Гарантий пока нет",
+ "no_warranties_desc": "Добавьте свою первую гарантию, чтобы начать",
+ "add_warranty": "Добавить гарантию",
+ "warranty_entry_method": "Метод ввода гарантии",
+ "warranty_duration_option": "Срок гарантии",
+ "exact_expiration_option": "Точная дата окончания",
+ "warranty_period": "Гарантийный период",
+ "expiration_date_label": "Дата окончания",
+ "currency": "Валюта",
+ "add_tags": "Добавить теги",
+ "add_tags_desc": "Теги помогают упорядочивать и фильтровать ваши гарантии",
+ "save_changes": "Сохранить изменения",
+ "confirm_delete": "Подтвердить удаление",
+ "manage_tags": "Управление тегами",
+ "add_tag": "Добавить тег",
+ "unknown_status": "Неизвестный статус",
+ "expiring_soon_days": "Скоро истекает ({{days}} {{dayText}})",
+ "days_remaining": "Осталось {{days}} {{dayText}}",
+ "day_one": "день",
+ "day_few": "дня",
+ "day_many": "дней",
+ "day_other": "дня",
+ "month_one": "месяц",
+ "month_few": "месяца",
+ "month_many": "месяцев",
+ "month_other": "месяца",
+ "year_one": "год",
+ "year_few": "года",
+ "year_many": "лет",
+ "year_other": "года",
+ "na": "Н/Д",
+ "age": "Возраст",
+ "warranty": "Гарантия",
+ "warranty_ends": "Гарантия заканчивается",
+ "price": "Цена",
+ "serial_number": "Серийный номер",
+ "vendor": "Продавец",
+ "type": "Тип",
+ "owner": "Владелец",
+ "product_website": "Сайт продукта",
+ "documents": "Документы",
+ "summary": "Сводка",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "Годы",
+ "months_placeholder": "Месяцы",
+ "days_placeholder": "Дни",
+ "add_any_notes_placeholder": "Добавьте заметки об этой гарантии...",
+ "product_url_optional": "URL продукта (необязательно)",
+ "enter_serial_number": "Введите серийный номер",
+ "vendor_optional": "Продавец (необязательно)",
+ "vendor_placeholder": "например, Amazon, Best Buy и т.д.",
+ "lifetime_warranty": "Пожизненная гарантия",
+ "warranty_type_optional": "Тип гарантии (необязательно)",
+ "select_warranty_type": "Выберите тип гарантии...",
+ "standard": "Стандартная",
+ "extended": "Расширенная",
+ "manufacturer": "От производителя",
+ "third_party": "От третьей стороны",
+ "store": "Магазинная",
+ "premium": "Премиум",
+ "limited": "Ограниченная",
+ "full": "Полная",
+ "parts_only": "Только на запчасти",
+ "labor_only": "Только на работы",
+ "international": "Международная",
+ "accidental_damage": "От случайных повреждений",
+ "other_custom": "Другой (пользовательский)",
+ "enter_custom_warranty_type": "Введите пользовательский тип гарантии",
+ "purchase_price_optional": "Цена покупки (необязательно)",
+ "notes_optional": "Заметки (необязательно)",
+ "add_any_notes": "Добавьте любые заметки об этой гарантии...",
+ "product_photo_optional": "Фото продукта (необязательно)",
+ "choose_photo": "Выберите фото",
+ "invoice_receipt": "Счет/Чек",
+ "store_locally": "Хранить локально",
+ "store_in_paperless": "Хранить в Paperless-ngx",
+ "choose_file": "Выберите файл",
+ "browse_paperless": "Обзор документов Paperless-ngx",
+ "product_manual_optional": "Руководство по продукту (необязательно)",
+ "files_zip_rar_optional": "Файлы (ZIP/RAR, необязательно)",
+ "search_or_add_new_tag": "Искать или добавить новый тег...",
+ "product_information": "Информация о продукте",
+ "product_url": "URL продукта",
+ "warranty_details": "Детали гарантии",
+ "product_photo": "Фото продукта",
+ "product_manual": "Руководство по продукту",
+ "files": "Файлы",
+ "selected_tags": "Выбранные теги",
+ "previous_tab": "Назад",
+ "next_tab": "Далее",
+ "delete_photo": "Удалить фото",
+ "delete_invoice": "Удалить счет",
+ "delete_manual": "Удалить руководство",
+ "delete_files": "Удалить файлы",
+ "current_photo": "Текущее фото:",
+ "current_invoice": "Текущий счет:",
+ "current_manual": "Текущее руководство:",
+ "current_document": "Текущий документ:",
+ "upload_new_photo_replace": "(Загрузите новое фото для замены)",
+ "no_photo_uploaded": "Фото не загружено",
+ "no_invoice_uploaded": "Счет не загружен",
+ "no_manual_uploaded": "Руководство не загружено",
+ "no_document_uploaded": "Другой документ не загружен",
+ "photo_will_be_deleted": "Фото будет удалено при сохранении",
+ "invoice_will_be_deleted": "Счет будет удален при сохранении",
+ "manual_will_be_deleted": "Руководство будет удалено при сохранении",
+ "document_will_be_deleted": "Другой документ будет удален при сохранении",
+ "confirm_delete_message": "Вы уверены, что хотите удалить эту гарантию? Это действие нельзя отменить.",
+ "new_tag_name": "Новое имя тега",
+ "existing_tags": "Существующие теги",
+ "edit_warranty": "Редактировать гарантию",
+ "warranty_type_standard": "Стандартная",
+ "warranty_type_extended": "Расширенная",
+ "warranty_type_manufacturer": "От производителя",
+ "warranty_type_third_party": "От третьей стороны",
+ "warranty_type_store": "Магазинная",
+ "warranty_type_premium": "Премиум",
+ "warranty_type_limited": "Ограниченная",
+ "warranty_type_full": "Полная",
+ "warranty_type_parts_only": "Только на запчасти",
+ "warranty_type_labor_only": "Только на работы",
+ "warranty_type_international": "Международная",
+ "warranty_type_accidental_damage": "От случайных повреждений",
+ "warranty_type_other": "Другой (пользовательский)",
+ "warranty_type_custom_placeholder": "Введите пользовательский тип гарантии",
+ "notes_placeholder": "Дополнительные заметки об этой гарантии...",
+ "tags_help_text": "Теги помогают упорядочивать и фильтровать ваши гарантии",
+ "search_add_tag_placeholder": "Искать или добавить новый тег...",
+ "upload_new_file_replace": "Загрузите новый файл для замены",
+ "current_other_document": "Текущий другой документ",
+ "no_other_document_uploaded": "Другой документ не загружен",
+ "other_document_will_be_deleted": "Другой документ будет удален при сохранении",
+ "files_optional": "Файлы (ZIP/RAR, необязательно)",
+ "invoice_receipt_short": "Счет",
+ "product_manual_short": "Руководство",
+ "files_short": "Файлы",
+ "enter_serial_number": "Введите серийный номер",
+ "add_serial_number": "Добавить еще один серийный номер"
+ },
+ "settings": {
+ "title": "Настройки",
+ "account_settings": "Настройки аккаунта",
+ "preferences": "Предпочтения",
+ "language": "Язык",
+ "select_language": "Выберите язык",
+ "dark_mode": "Темный режим",
+ "dark_mode_desc": "Переключение между светлой и темной темой",
+ "currency": "Валюта",
+ "timezone": "Часовой пояс",
+ "date_format": "Формат даты",
+ "expiring_soon_days": "Дни до истечения срока",
+ "save_changes": "Сохранить изменения",
+ "current_user": "Редактирование профиля для:",
+ "your_email": "Ваш email:",
+ "first_name": "Имя",
+ "last_name": "Фамилия",
+ "email": "Электронная почта",
+ "save_profile": "Сохранить изменения",
+ "default_view": "Вид по умолчанию",
+ "default_view_desc": "Выберите предпочитаемый вид для гарантий",
+ "grid_view": "Сетка",
+ "list_view": "Список",
+ "table_view": "Таблица",
+ "currency_symbol": "Символ валюты",
+ "currency_symbol_desc": "Выберите символ для отображения цен",
+ "currency_position": "Позиция валюты",
+ "currency_position_desc": "Выберите, где будет отображаться символ валюты",
+ "expiring_soon_days_desc": "Количество дней до истечения срока для отображения предупреждений",
+ "date_format_desc": "Выберите, как будут отображаться даты",
+ "save_preferences": "Сохранить предпочтения",
+ "notification_settings": "Настройки уведомлений",
+ "notification_channel": "Канал уведомлений",
+ "notification_channel_desc": "Выберите, как вы хотите получать уведомления",
+ "notification_disabled": "Отключено",
+ "notification_email": "Электронная почта",
+ "notification_apprise": "Apprise",
+ "notification_both": "Оба",
+ "email_settings": "Настройки электронной почты",
+ "notification_frequency": "Частота уведомлений",
+ "notification_frequency_desc": "Как часто получать уведомления по электронной почте",
+ "daily": "Ежедневно",
+ "weekly": "Еженедельно",
+ "monthly": "Ежемесячно",
+ "notification_time": "Время уведомлений",
+ "timezone_desc": "Ваш местный часовой пояс для уведомлений",
+ "apprise_settings": "Настройки Apprise",
+ "apprise_frequency": "Частота уведомлений Apprise",
+ "apprise_frequency_desc": "Как часто получать уведомления Apprise",
+ "apprise_time": "Время уведомлений Apprise",
+ "apprise_timezone": "Часовой пояс Apprise",
+ "apprise_timezone_desc": "Ваш местный часовой пояс для уведомлений Apprise",
+ "save_notification_settings": "Сохранить настройки уведомлений",
+ "security": "Безопасность",
+ "change_password": "Изменить пароль",
+ "change_password_desc": "Обновите пароль вашей учетной записи",
+ "change": "Изменить",
+ "current_password": "Текущий пароль",
+ "new_password": "Новый пароль",
+ "confirm_password": "Подтвердите новый пароль",
+ "update_password": "Обновить пароль",
+ "cancel": "Отмена",
+ "danger_zone": "Опасная зона",
+ "delete_account": "Удалить аккаунт",
+ "delete_account_desc": "Навсегда удалить вашу учетную запись и все данные",
+ "admin_settings": "Настройки администратора",
+ "admin_actions": "Действия администратора",
+ "refresh_data": "Обновить данные",
+ "check_admin_status": "Проверить статус администратора",
+ "show_users_list": "Показать список пользователей",
+ "test_api": "Тестировать API",
+ "send_notifications": "Отправить уведомления о гарантиях",
+ "check_scheduler": "Проверить статус планировщика",
+ "site_settings": "Настройки сайта",
+ "registration_enabled": "Регистрация включена",
+ "registration_enabled_desc": "Разрешить новым пользователям регистрироваться",
+ "email_base_url": "Базовый URL для email",
+ "global_view_enabled": "Глобальный вид включен",
+ "global_view_admin_only": "Глобальный вид только для администраторов",
+ "save_site_settings": "Сохранить настройки сайта",
+ "oidc_configuration": "Конфигурация OIDC SSO",
+ "enable_oidc": "Включить OIDC SSO",
+ "oidc_provider_name": "Имя провайдера OIDC",
+ "client_id": "ID клиента",
+ "client_secret": "Секрет клиента",
+ "issuer_url": "URL издателя",
+ "scope": "Область",
+ "save_oidc_settings": "Сохранить настройки OIDC",
+ "oidc_sso_desc": "Разрешить пользователям входить через провайдера OIDC.",
+ "oidc_only_mode": "Режим входа только через OIDC",
+ "oidc_only_mode_desc": "Скрыть традиционную форму входа с именем пользователя/паролем и разрешить вход только через OIDC. <strong>Внимание:</strong> Убедитесь, что OIDC правильно настроен, прежде чем включать эту опцию.",
+ "oidc_provider_name_desc": "Внутреннее имя для клиента OIDC (например, 'oidc').",
+ "client_secret_desc": "Конфиденциальное значение. Хранится в базе данных. Для вступления изменений в силу требуется перезапуск приложения.",
+ "issuer_url_desc": "Базовый URL вашего провайдера OIDC.",
+ "scope_desc": "Области OIDC, разделенные пробелами.",
+ "oidc_restart_message": "Для полного вступления настроек OIDC в силу требуется перезапуск приложения.",
+ "api_token": "API токен",
+ "view_documents": "Просмотр документов в Warracker",
+ "connection_testing": "Тестирование соединения",
+ "apprise_notifications": "Уведомления Apprise",
+ "enable_apprise": "Включить уведомления Apprise",
+ "loading": "Загрузка...",
+ "time_of_day_notification": "Время суток для получения уведомлений (в 24-часовом формате)",
+ "paperless_ngx_settings": "Настройки Paperless-ngx",
+ "paperless_ngx_about_title": "Об интеграции с Paperless-ngx:",
+ "paperless_ngx_about_desc": "Эта необязательная функция позволяет хранить гарантийные документы в вашем собственном экземпляре Paperless-ngx вместо локального хранения. При включении пользователи могут выбирать, где хранить каждый документ: локально или в Paperless-ngx.",
+ "paperless_ngx_desc": "Настройте интеграцию с системой управления документами Paperless-ngx",
+ "enable_paperless": "Включить интеграцию с Paperless-ngx",
+ "paperless_url": "URL Paperless-ngx",
+ "paperless_url_desc": "Базовый URL вашего экземпляра Paperless-ngx",
+ "paperless_token": "API токен",
+ "paperless_token_desc": "Ваш токен аутентификации API Paperless-ngx",
+ "paperless_token_desc_generate": "Создайте токен API в вашем экземпляре Paperless-ngx (Настройки → API токены).",
+ "paperless_view_in_app": "Просмотр документов в приложении",
+ "paperless_view_in_app_desc": "Открывать документы внутри приложения вместо новой вкладки",
+ "debug_config": "Отладочная конфигурация",
+ "test_upload": "Тестовая загрузка",
+ "save_paperless_settings": "Сохранить настройки Paperless-ngx",
+ "apprise_desc": "Настройте Apprise для расширенной доставки уведомлений в несколько сервисов",
+ "apprise_desc_system_wide": "Включить или отключить уведомления Apprise для всей системы",
+ "apprise_not_available_title": "Apprise недоступен:",
+ "apprise_not_available_desc": "Библиотека уведомлений Apprise не установлена или недоступна. Функции уведомлений отключены.",
+ "apprise_url": "URL Apprise",
+ "apprise_url_desc": "URL вашего сервиса уведомлений Apprise",
+ "apprise_mode": "Режим уведомлений",
+ "apprise_mode_desc": "Выберите, когда отправлять уведомления Apprise",
+ "apprise_mode_global": "Глобальная сводка",
+ "apprise_mode_individual": "Для каждого пользователя",
+ "test_paperless": "Тестировать соединение с Paperless",
+ "test_apprise": "Тестировать соединение с Apprise",
+ "apprise_warranty_scope": "Область гарантий",
+ "apprise_warranty_scope_desc": "Выберите, какие гарантии включать в уведомления",
+ "all_warranties": "Все гарантии",
+ "personal_warranties": "Только личные гарантии",
+ "all_users_warranties": "Гарантии всех пользователей",
+ "admin_warranties_only": "Только гарантии администратора",
+ "apprise_notification_days": "Дни уведомлений",
+ "apprise_notification_days_desc": "Дни до истечения срока для отправки уведомлений (через запятую, например, \"7,30\" для 7 и 30 дней до)",
+ "apprise_check_frequency": "Частота проверки",
+ "apprise_check_frequency_desc": "Как часто система проверяет истекающие гарантии (глобальная настройка)",
+ "apprise_title_prefix": "Префикс заголовка сообщения",
+ "apprise_title_prefix_desc": "Префикс, добавляемый к заголовкам уведомлений (например, \"[Warracker]\" приведет к \"[Warracker] Гарантии скоро истекают\")",
+ "apprise_test_url": "Тестовый URL (необязательно)",
+ "apprise_test_url_desc": "Необязательно: URL для отправки только тестовых уведомлений (не будет сохранен в основной конфигурации)",
+ "save_apprise_settings": "Сохранить настройки Apprise",
+ "validate_urls": "Проверить URL",
+ "send_expiration_notifications_now": "Отправить уведомления об истечении срока сейчас",
+ "apprise_current_status": "Текущий статус",
+ "apprise_urls_configured": "Настроенные URL:",
+ "apprise_supported_services": "Поддерживаемые сервисы",
+ "apprise_supported_services_desc": "Apprise поддерживает более 80 сервисов уведомлений, включая: Discord, Slack, Telegram, Email (Gmail, Outlook), Webhooks, Microsoft Teams, Matrix, Pushover, Ntfy, Gotify и многие другие.",
+ "view_full_list_of_supported_services": "Посмотреть полный список поддерживаемых сервисов",
+ "ownership_management": "Управление владением",
+ "transfer_ownership": "Передать владение",
+ "warning_title": "Внимание:",
+ "transfer_ownership_warning": "Передать владение приложением другому администратору. Это действие необратимо.",
+ "transfer_ownership_desc": "После передачи владения вы станете обычным администратором, а новый владелец получит полный контроль над приложением.",
+ "select_new_owner": "Выберите нового владельца (должен быть администратором)",
+ "select_admin_user": "Выберите пользователя-администратора...",
+ "transfer_ownership_button": "Передать владение",
+ "transfer_ownership_irreversible": "Это действие нельзя отменить.",
+ "transfer_ownership_confirmation": "Вы собираетесь передать владение приложением",
+ "after_this_transfer": "После этой передачи:",
+ "transfer_ownership_consequence_1": "Вы станете обычным администратором",
+ "transfer_ownership_consequence_2": "Новый владелец получит полный контроль над приложением",
+ "transfer_ownership_consequence_3": "Только новый владелец сможет снова передать владение",
+ "transfer_ownership_type_to_confirm": "Для подтверждения введите \"TRANSFER\" в поле ниже:"
+ },
+ "actions": {
+ "save": "Сохранить",
+ "cancel": "Отмена",
+ "delete": "Удалить",
+ "edit": "Редактировать",
+ "export": "Экспорт",
+ "import": "Импорт",
+ "refresh": "Обновить",
+ "search": "Поиск",
+ "clear": "Очистить",
+ "upload": "Загрузить",
+ "download": "Скачать",
+ "manage_tags": "Управление тегами",
+ "close": "Закрыть",
+ "save_changes": "Сохранить изменения"
+ },
+ "filters": {
+ "all_status": "Все статусы",
+ "all_tags": "Все теги",
+ "all_vendors": "Все продавцы",
+ "all_types": "Все типы",
+ "sort_by": "Сортировать по",
+ "sort_expiration": "Дата окончания",
+ "sort_purchase": "Дата покупки",
+ "sort_age": "Возраст",
+ "sort_name": "Название продукта",
+ "sort_vendor": "Продавец",
+ "sort_warranty_type": "Тип гарантии",
+ "status": "Статус",
+ "tags": "Теги",
+ "vendor": "Продавец",
+ "warranty_type": "Тип гарантии",
+ "view": "Вид",
+ "scope": "Область"
+ },
+ "messages": {
+ "success": "Успех",
+ "error": "Ошибка",
+ "warning": "Предупреждение",
+ "loading": "Загрузка...",
+ "saved": "Изменения успешно сохранены",
+ "deleted": "Элемент успешно удален",
+ "confirm_delete": "Вы уверены, что хотите удалить этот элемент?",
+ "no_results": "Результатов не найдено",
+ "file_too_large": "Файл слишком большой",
+ "invalid_file_type": "Неверный тип файла",
+ "fill_first_last_name": "Пожалуйста, заполните имя и фамилию",
+ "email_cannot_be_empty": "Адрес электронной почты не может быть пустым.",
+ "enter_valid_email": "Пожалуйста, введите действительный адрес электронной почты.",
+ "profile_updated_successfully": "Профиль успешно обновлен",
+ "preferences_saved_successfully": "Настройки успешно сохранены.",
+ "fill_password_fields": "Пожалуйста, заполните все поля пароля",
+ "passwords_do_not_match": "Новые пароли не совпадают",
+ "password_min_length": "Пароль должен содержать не менее 8 символов",
+ "type_delete_to_confirm": "Пожалуйста, введите DELETE для подтверждения",
+ "account_deleted_successfully": "Аккаунт успешно удален",
+ "account_cannot_delete_offline": "Аккаунт нельзя удалить в автономном режиме",
+ "failed_delete_account": "Не удалось удалить аккаунт. Пожалуйста, попробуйте еще раз.",
+ "user_updated_successfully": "Пользователь успешно обновлен",
+ "user_deleted_successfully": "Пользователь успешно удален",
+ "user_id_missing": "Отсутствует ID пользователя",
+ "failed_load_users": "Не удалось загрузить пользователей",
+ "error_loading_users": "Ошибка при загрузке пользователей",
+ "select_user_transfer_ownership": "Пожалуйста, выберите пользователя для передачи владения",
+ "ownership_transferred_successfully": "Владение успешно передано! Обновление страницы...",
+ "failed_load_site_settings": "Не удалось загрузить настройки сайта. Пожалуйста, попробуйте еще раз.",
+ "invalid_email_base_url": "Неверный формат базового URL электронной почты. Должен начинаться с http:// или https://",
+ "no_site_settings_to_save": "Нет настроек сайта для сохранения.",
+ "site_settings_saved_successfully": "Настройки сайта успешно сохранены",
+ "failed_save_site_settings": "Не удалось сохранить настройки сайта",
+ "oidc_settings_saved_successfully": "Настройки OIDC успешно сохранены.",
+ "failed_save_oidc_settings": "Не удалось сохранить настройки OIDC.",
+ "api_endpoint_accessible": "API-конечная точка доступна",
+ "api_endpoint_not_accessible": "API-конечная точка недоступна. Статус: ",
+ "only_admins_send_notifications": "Только администраторы могут отправлять уведомления о гарантиях",
+ "notifications_triggered_successfully": "Уведомления успешно запущены",
+ "notification_settings_saved_successfully": "Настройки уведомлений успешно сохранены",
+ "apprise_settings_saved_successfully": "Настройки Apprise успешно сохранены",
+ "test_notification_sent_successfully": "Тестовое уведомление успешно отправлено",
+ "no_urls_to_validate": "Нет URL для проверки",
+ "paperless_settings_saved_successfully": "Настройки Paperless-ngx успешно сохранены!",
+ "enter_valid_paperless_url": "Пожалуйста, введите действительный URL (например, https://paperless.ваш-домен.com)",
+ "enter_paperless_url_first": "Пожалуйста, сначала введите URL Paperless-ngx",
+ "paperless_connection_test_successful": "Тест подключения Paperless-ngx успешен!",
+ "paperless_connection_test_failed": "Тест подключения Paperless-ngx не удался",
+ "enter_api_token_test_connection": "Пожалуйста, введите API-токен для тестирования подключения",
+ "failed_load_user_data": "Не удалось загрузить данные пользователя. Пожалуйста, попробуйте еще раз.",
+ "could_not_connect_user_data": "Не удается подключиться для получения данных пользователя. Отображение кэшированной информации.",
+ "preferences_saved_locally_failed_sync": "Настройки сохранены локально, но не удалось синхронизировать с сервером: ",
+ "preferences_saved_locally": "Настройки сохранены локально.",
+ "correct_errors_in_tab": "Пожалуйста, исправьте ошибки в выделенной вкладке перед продолжением.",
+ "please_fill_out_this_field": "Пожалуйста, заполните это поле.",
+ "warranty_added_successfully": "Гарантия успешно добавлена",
+ "tag_name_required": "Имя тега обязательно",
+ "tag_creation_function_not_found": "Функция создания тега не найдена",
+ "tag_created_successfully": "Тег успешно создан",
+ "tag_updated_successfully": "Тег успешно обновлен",
+ "tag_deleted_successfully": "Тег успешно удален",
+ "failed_to_create_tag": "Ошибка создания тега",
+ "failed_to_update_tag": "Ошибка обновления тега",
+ "failed_to_delete_tag": "Ошибка удаления тега"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية",
+ "ru": "Русский",
+ "uk": "Українська",
+ "zh_CN": "简体中文",
+ "zh_HK": "繁體中文",
+ "ja": "日本語",
+ "pt": "Português",
+ "ko": "한국어"
+ },
+ "status": {
+ "title": "Статус системы",
+ "dashboard_title": "Панель состояния гарантий",
+ "global_dashboard_title": "Глобальная панель состояния гарантий",
+ "overview": "Обзор",
+ "statistics": "Статистика",
+ "total_warranties": "Всего гарантий",
+ "active_warranties": "Активные гарантии",
+ "expiring_soon": "Скоро истекают",
+ "expired_warranties": "Истекшие гарантии",
+ "warranty_distribution": "Распределение гарантий",
+ "expiration_timeline": "Временная шкала истечения",
+ "recent_activity": "Недавняя активность",
+ "recent_expirations": "Недавно истекшие или скоро истекающие",
+ "recent_expirations_empty": "Нет недавно истекших или скоро истекающих гарантий.",
+ "system_health": "Состояние системы",
+ "database_status": "Статус базы данных",
+ "connected": "Подключено",
+ "version": "Версия",
+ "uptime": "Время работы"
+ },
+ "about": {
+ "title": "О Warracker",
+ "description": "Комплексная система управления гарантиями, разработанная для отслеживания, организации и управления всеми вашими гарантиями на продукты на одной безопасной и удобной платформе.",
+ "version": "Версия",
+ "update_status": "Статус обновления",
+ "checking_updates": "Проверка обновлений...",
+ "view_release_notes": "Посмотреть примечания к выпуску",
+ "project_info": "Информация о проекте",
+ "project_description": "Warracker - это система управления гарантиями с открытым исходным кодом, созданная с использованием современных веб-технологий. Она обеспечивает безопасный и интуитивно понятный способ управления гарантиями на продукты, отслеживания дат истечения и организации важных документов.",
+ "github_repository": "Репозиторий GitHub",
+ "releases": "Релизы",
+ "community_support": "Сообщество и поддержка",
+ "community_description": "Присоединяйтесь к нашему сообществу для поддержки, обсуждений и обновлений. Сообщайте об ошибках, запрашивайте новые функции или получайте помощь от других пользователей и участников.",
+ "discord_community": "Сообщество Discord",
+ "report_issues": "Сообщить о проблемах",
+ "developer_info": "Информация о разработчике",
+ "developer_description": "Warracker разработан и поддерживается Sassanix. Проект является открытым и приветствует вклад сообщества.",
+ "sassanix": "Sassanix",
+ "agpl_license": "Лицензия AGPL-3.0",
+ "support_project": "Поддержать проект",
+ "support_description": "Если вы находите Warracker полезным, рассмотрите возможность поддержки его разработки!",
+ "new_version_available": "Доступна новая версия {{version}}!",
+ "latest_version": "Вы используете последнюю версию",
+ "update_check_failed": "Не удалось проверить наличие обновлений",
+ "features": "Возможности",
+ "feature_track": "Отслеживание гарантий на продукты",
+ "feature_notifications": "Получение уведомлений об истечении срока",
+ "feature_documents": "Хранение гарантийных документов",
+ "feature_reports": "Создание отчетов о гарантиях",
+ "feature_tags": "Организация с помощью тегов",
+ "feature_export": "Экспорт данных о гарантиях",
+ "support": "Поддержка",
+ "documentation": "Документация",
+ "github": "Репозиторий GitHub",
+ "license": "Лицензия",
+ "copyright": "Авторское право",
+ "developed_by": "Разработано"
+ }
+}
diff --git a/locales/uk/translation.json b/locales/uk/translation.json
new file mode 100644
index 0000000..9efa2ac
--- /dev/null
+++ b/locales/uk/translation.json
@@ -0,0 +1,567 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "Трекер гарантій",
+ "nav": {
+ "home": "Головна",
+ "status": "Статус",
+ "settings": "Налаштування",
+ "about": "Про програму"
+ },
+ "auth": {
+ "login": "Увійти",
+ "logout": "Вийти",
+ "register": "Реєстрація",
+ "username": "Ім'я користувача",
+ "password": "Пароль",
+ "email": "Електронна пошта",
+ "first_name": "Ім'я",
+ "last_name": "Прізвище",
+ "forgot_password": "Забули пароль?",
+ "reset_password": "Скинути пароль",
+ "confirm_password": "Підтвердіть пароль",
+ "create_account_title": "Створити обліковий запис",
+ "first_name_optional": "Ім'я (необов'язково)",
+ "last_name_optional": "Прізвище (необов'язково)",
+ "username_hint": "Ім'я користувача має бути унікальним і використовуватиметься для входу.",
+ "email_address": "Адреса електронної пошти",
+ "toggle_password": "Показати/сховати пароль",
+ "password_hint_simple": "Пароль повинен містити щонайменше 8 символів, включаючи великі та малі літери, а також цифри.",
+ "password_requirements": "Вимоги до пароля:",
+ "req_length": "Щонайменше 8 символів",
+ "req_uppercase": "Щонайменше 1 велика літера",
+ "req_lowercase": "Щонайменше 1 мала літера",
+ "req_number": "Щонайменше 1 цифра",
+ "req_special": "Щонайменше 1 спеціальний символ",
+ "create_account": "Створити обліковий запис",
+ "already_have_account": "Вже є обліковий запис?",
+ "reset_password_title": "Warracker - Скидання пароля",
+ "reset_your_password": "Скинути ваш пароль",
+ "reset_password_info": "Введіть свою адресу електронної пошти нижче, і ми надішлемо вам посилання для скидання пароля.",
+ "send_reset_link": "Надіслати посилання для скидання",
+ "back_to_login": "Повернутися до входу",
+ "set_new_password_title": "Warracker - Встановити новий пароль",
+ "set_new_password": "Встановити новий пароль",
+ "new_password": "Новий пароль",
+ "confirm_new_password": "Підтвердьте новий пароль",
+ "invalid_or_expired_link": "Недійсне або застаріле посилання",
+ "invalid_link_info": "Посилання для скидання пароля, за яким ви перейшли, є недійсним або застарілим.",
+ "request_new_reset_link": "Запросити нове посилання для скидання"
+ },
+ "warranties": {
+ "title": "Ваші гарантії",
+ "title_global": "Гарантії всіх користувачів",
+ "add_new": "Додати нову гарантію",
+ "edit": "Редагувати гарантію",
+ "delete": "Видалити гарантію",
+ "product_name": "Назва продукту",
+ "purchase_date": "Дата покупки",
+ "warranty_duration": "Термін гарантії",
+ "years": "Роки",
+ "months": "Місяці",
+ "days": "Дні",
+ "vendor": "Продавець",
+ "serial_numbers": "Серійні номери",
+ "purchase_price": "Ціна покупки",
+ "notes": "Нотатки",
+ "tags": "Теги",
+ "status": "Статус",
+ "expiration_date": "Дата закінчення",
+ "active": "Активна",
+ "expired": "Закінчилась",
+ "expiring_soon": "Скоро закінчується",
+ "lifetime": "Довічна",
+ "no_warranties": "Гарантій ще немає. Додайте свою першу гарантію, щоб почати.",
+ "search_placeholder": "Пошук за назвою, продавцями, нотатками, тегом або серійним номером...",
+ "warranty_type": "Тип гарантії",
+ "other_document": "Інший документ",
+ "product": "Продукт",
+ "expiration": "Закінчення",
+ "actions": "Дії",
+ "no_warranties_title": "Гарантій ще немає",
+ "no_warranties_desc": "Додайте свою першу гарантію, щоб почати",
+ "add_warranty": "Додати гарантію",
+ "warranty_entry_method": "Метод введення гарантії",
+ "warranty_duration_option": "Термін гарантії",
+ "exact_expiration_option": "Точна дата закінчення",
+ "warranty_period": "Гарантійний період",
+ "expiration_date_label": "Дата закінчення",
+ "currency": "Валюта",
+ "add_tags": "Додати теги",
+ "add_tags_desc": "Теги допомагають упорядковувати та фільтрувати ваші гарантії",
+ "save_changes": "Зберегти зміни",
+ "confirm_delete": "Підтвердити видалення",
+ "manage_tags": "Керування тегами",
+ "add_tag": "Додати тег",
+ "unknown_status": "Невідомий статус",
+ "expiring_soon_days": "Скоро закінчується ({{days}} {{dayText}})",
+ "days_remaining": "Залишилось {{days}} {{dayText}}",
+ "day_one": "день",
+ "day_few": "дні",
+ "day_many": "днів",
+ "day_other": "дні",
+ "month_one": "місяць",
+ "month_few": "місяці",
+ "month_many": "місяців",
+ "month_other": "місяці",
+ "year_one": "рік",
+ "year_few": "роки",
+ "year_many": "років",
+ "year_other": "роки",
+ "na": "Н/Д",
+ "age": "Вік",
+ "warranty": "Гарантія",
+ "warranty_ends": "Гарантія закінчується",
+ "price": "Ціна",
+ "serial_number": "Серійний номер",
+ "vendor": "Продавець",
+ "type": "Тип",
+ "owner": "Власник",
+ "product_website": "Сайт продукту",
+ "documents": "Документи",
+ "summary": "Зведення",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "Роки",
+ "months_placeholder": "Місяці",
+ "days_placeholder": "Дні",
+ "add_any_notes_placeholder": "Додайте нотатки про цю гарантію...",
+ "product_url_optional": "URL продукту (необов'язково)",
+ "enter_serial_number": "Введіть серійний номер",
+ "vendor_optional": "Продавець (необов'язково)",
+ "vendor_placeholder": "наприклад, Amazon, Best Buy тощо.",
+ "lifetime_warranty": "Довічна гарантія",
+ "warranty_type_optional": "Тип гарантії (необов'язково)",
+ "select_warranty_type": "Виберіть тип гарантії...",
+ "standard": "Стандартна",
+ "extended": "Розширена",
+ "manufacturer": "Від виробника",
+ "third_party": "Від третьої сторони",
+ "store": "Магазинна",
+ "premium": "Преміум",
+ "limited": "Обмежена",
+ "full": "Повна",
+ "parts_only": "Тільки на запчастини",
+ "labor_only": "Тільки на роботи",
+ "international": "Міжнародна",
+ "accidental_damage": "Від випадкових пошкоджень",
+ "other_custom": "Інший (користувацький)",
+ "enter_custom_warranty_type": "Введіть користувацький тип гарантії",
+ "purchase_price_optional": "Ціна покупки (необов'язково)",
+ "notes_optional": "Нотатки (необов'язково)",
+ "add_any_notes": "Додайте будь-які нотатки про цю гарантію...",
+ "product_photo_optional": "Фото продукту (необов'язково)",
+ "choose_photo": "Виберіть фото",
+ "invoice_receipt": "Рахунок/Чек",
+ "store_locally": "Зберігати локально",
+ "store_in_paperless": "Зберігати в Paperless-ngx",
+ "choose_file": "Виберіть файл",
+ "browse_paperless": "Огляд документів Paperless-ngx",
+ "product_manual_optional": "Посібник з продукту (необов'язково)",
+ "files_zip_rar_optional": "Файли (ZIP/RAR, необов'язково)",
+ "search_or_add_new_tag": "Шукати або додати новий тег...",
+ "product_information": "Інформація про продукт",
+ "product_url": "URL продукту",
+ "warranty_details": "Деталі гарантії",
+ "product_photo": "Фото продукту",
+ "product_manual": "Посібник з продукту",
+ "files": "Файли",
+ "selected_tags": "Вибрані теги",
+ "previous_tab": "Назад",
+ "next_tab": "Далі",
+ "delete_photo": "Видалити фото",
+ "delete_invoice": "Видалити рахунок",
+ "delete_manual": "Видалити посібник",
+ "delete_files": "Видалити файли",
+ "current_photo": "Поточне фото:",
+ "current_invoice": "Поточний рахунок:",
+ "current_manual": "Поточний посібник:",
+ "current_document": "Поточний документ:",
+ "upload_new_photo_replace": "(Завантажте нове фото для заміни)",
+ "no_photo_uploaded": "Фото не завантажено",
+ "no_invoice_uploaded": "Рахунок не завантажено",
+ "no_manual_uploaded": "Посібник не завантажено",
+ "no_document_uploaded": "Інший документ не завантажено",
+ "photo_will_be_deleted": "Фото буде видалено при збереженні",
+ "invoice_will_be_deleted": "Рахунок буде видалено при збереженні",
+ "manual_will_be_deleted": "Посібник буде видалено при збереженні",
+ "document_will_be_deleted": "Інший документ буде видалено при збереженні",
+ "confirm_delete_message": "Ви впевнені, що хочете видалити цю гарантію? Цю дію не можна скасувати.",
+ "new_tag_name": "Нова назва тегу",
+ "existing_tags": "Існуючі теги",
+ "edit_warranty": "Редагувати гарантію",
+ "warranty_type_standard": "Стандартна",
+ "warranty_type_extended": "Розширена",
+ "warranty_type_manufacturer": "Від виробника",
+ "warranty_type_third_party": "Від третьої сторони",
+ "warranty_type_store": "Магазинна",
+ "warranty_type_premium": "Преміум",
+ "warranty_type_limited": "Обмежена",
+ "warranty_type_full": "Повна",
+ "warranty_type_parts_only": "Тільки на запчастини",
+ "warranty_type_labor_only": "Тільки на роботи",
+ "warranty_type_international": "Міжнародна",
+ "warranty_type_accidental_damage": "Від випадкових пошкоджень",
+ "warranty_type_other": "Інший (користувацький)",
+ "warranty_type_custom_placeholder": "Введіть користувацький тип гарантії",
+ "notes_placeholder": "Додаткові нотатки про цю гарантію...",
+ "tags_help_text": "Теги допомагають упорядковувати та фільтрувати ваші гарантії",
+ "search_add_tag_placeholder": "Шукати або додати новий тег...",
+ "upload_new_file_replace": "Завантажте новий файл для заміни",
+ "current_other_document": "Поточний інший документ",
+ "no_other_document_uploaded": "Інший документ не завантажено",
+ "other_document_will_be_deleted": "Інший документ буде видалено при збереженні",
+ "files_optional": "Файли (ZIP/RAR, необов'язково)",
+ "invoice_receipt_short": "Рахунок",
+ "product_manual_short": "Посібник",
+ "files_short": "Файли",
+ "enter_serial_number": "Введіть серійний номер",
+ "add_serial_number": "Додати ще один серійний номер"
+ },
+ "settings": {
+ "title": "Налаштування",
+ "account_settings": "Налаштування облікового запису",
+ "preferences": "Переваги",
+ "language": "Мова",
+ "select_language": "Виберіть мову",
+ "dark_mode": "Темний режим",
+ "dark_mode_desc": "Перемикання між світлою та темною темою",
+ "currency": "Валюта",
+ "timezone": "Часовий пояс",
+ "date_format": "Формат дати",
+ "expiring_soon_days": "Дні до закінчення терміну",
+ "save_changes": "Зберегти зміни",
+ "current_user": "Редагування профілю для:",
+ "your_email": "Ваш email:",
+ "first_name": "Ім'я",
+ "last_name": "Прізвище",
+ "email": "Електронна пошта",
+ "save_profile": "Зберегти зміни",
+ "default_view": "Вигляд за замовчуванням",
+ "default_view_desc": "Виберіть бажаний вигляд для гарантій",
+ "grid_view": "Сітка",
+ "list_view": "Список",
+ "table_view": "Таблиця",
+ "currency_symbol": "Символ валюти",
+ "currency_symbol_desc": "Виберіть символ для відображення цін",
+ "currency_position": "Позиція валюти",
+ "currency_position_desc": "Виберіть, де буде відображатися символ валюти",
+ "expiring_soon_days_desc": "Кількість днів до закінчення терміну для відображення попереджень",
+ "date_format_desc": "Виберіть, як будуть відображатися дати",
+ "save_preferences": "Зберегти переваги",
+ "notification_settings": "Налаштування сповіщень",
+ "notification_channel": "Канал сповіщень",
+ "notification_channel_desc": "Виберіть, як ви хочете отримувати сповіщення",
+ "notification_disabled": "Вимкнено",
+ "notification_email": "Електронна пошта",
+ "notification_apprise": "Apprise",
+ "notification_both": "Обидва",
+ "email_settings": "Налаштування електронної пошти",
+ "notification_frequency": "Частота сповіщень",
+ "notification_frequency_desc": "Як часто отримувати сповіщення електронною поштою",
+ "daily": "Щодня",
+ "weekly": "Щотижня",
+ "monthly": "Щомісяця",
+ "notification_time": "Час сповіщень",
+ "timezone_desc": "Ваш місцевий часовий пояс для сповіщень",
+ "apprise_settings": "Налаштування Apprise",
+ "apprise_frequency": "Частота сповіщень Apprise",
+ "apprise_frequency_desc": "Як часто отримувати сповіщення Apprise",
+ "apprise_time": "Час сповіщень Apprise",
+ "apprise_timezone": "Часовий пояс Apprise",
+ "apprise_timezone_desc": "Ваш місцевий часовий пояс для сповіщень Apprise",
+ "save_notification_settings": "Зберегти налаштування сповіщень",
+ "security": "Безпека",
+ "change_password": "Змінити пароль",
+ "change_password_desc": "Оновіть пароль вашого облікового запису",
+ "change": "Змінити",
+ "current_password": "Поточний пароль",
+ "new_password": "Новий пароль",
+ "confirm_password": "Підтвердіть новий пароль",
+ "update_password": "Оновити пароль",
+ "cancel": "Скасувати",
+ "danger_zone": "Небезпечна зона",
+ "delete_account": "Видалити обліковий запис",
+ "delete_account_desc": "Назавжди видалити ваш обліковий запис і всі дані",
+ "admin_settings": "Налаштування адміністратора",
+ "admin_actions": "Дії адміністратора",
+ "refresh_data": "Оновити дані",
+ "check_admin_status": "Перевірити статус адміністратора",
+ "show_users_list": "Показати список користувачів",
+ "test_api": "Тестувати API",
+ "send_notifications": "Надіслати сповіщення про гарантії",
+ "check_scheduler": "Перевірити статус планувальника",
+ "site_settings": "Налаштування сайту",
+ "registration_enabled": "Реєстрація увімкнена",
+ "registration_enabled_desc": "Дозволити новим користувачам реєструватися",
+ "email_base_url": "Базовий URL для email",
+ "global_view_enabled": "Глобальний вигляд увімкнено",
+ "global_view_admin_only": "Глобальний вигляд тільки для адміністраторів",
+ "save_site_settings": "Зберегти налаштування сайту",
+ "oidc_configuration": "Конфігурація OIDC SSO",
+ "enable_oidc": "Увімкнути OIDC SSO",
+ "oidc_provider_name": "Назва провайдера OIDC",
+ "client_id": "ID клієнта",
+ "client_secret": "Секрет клієнта",
+ "issuer_url": "URL видавця",
+ "scope": "Область",
+ "save_oidc_settings": "Зберегти налаштування OIDC",
+ "oidc_sso_desc": "Дозволити користувачам входити через провайдера OIDC.",
+ "oidc_only_mode": "Режим входу тільки через OIDC",
+ "oidc_only_mode_desc": "Приховати традиційну форму входу з ім'ям користувача/паролем і дозволити вхід тільки через OIDC. <strong>Увага:</strong> Переконайтеся, що OIDC правильно налаштований, перш ніж вмикати цю опцію.",
+ "oidc_provider_name_desc": "Внутрішня назва для клієнта OIDC (наприклад, 'oidc').",
+ "client_secret_desc": "Конфіденційне значення. Зберігається в базі даних. Для набуття чинності змін потрібен перезапуск програми.",
+ "issuer_url_desc": "Базовий URL вашого провайдера OIDC.",
+ "scope_desc": "Області OIDC, розділені пробілами.",
+ "oidc_restart_message": "Для повного набуття чинності налаштувань OIDC потрібен перезапуск програми.",
+ "api_token": "API токен",
+ "view_documents": "Перегляд документів у Warracker",
+ "connection_testing": "Тестування з'єднання",
+ "apprise_notifications": "Сповіщення Apprise",
+ "enable_apprise": "Увімкнути сповіщення Apprise",
+ "loading": "Завантаження...",
+ "time_of_day_notification": "Час доби для отримання сповіщень (у 24-годинному форматі)",
+ "paperless_ngx_settings": "Налаштування Paperless-ngx",
+ "paperless_ngx_about_title": "Про інтеграцію з Paperless-ngx:",
+ "paperless_ngx_about_desc": "Ця необов'язкова функція дозволяє зберігати гарантійні документи у вашому власному екземплярі Paperless-ngx замість локального зберігання. При увімкненні користувачі можуть вибирати, де зберігати кожен документ: локально або в Paperless-ngx.",
+ "paperless_ngx_desc": "Налаштуйте інтеграцію з системою управління документами Paperless-ngx",
+ "enable_paperless": "Увімкнути інтеграцію з Paperless-ngx",
+ "paperless_url": "URL Paperless-ngx",
+ "paperless_url_desc": "Базовий URL вашого екземпляра Paperless-ngx",
+ "paperless_token": "API токен",
+ "paperless_token_desc": "Ваш токен автентифікації API Paperless-ngx",
+ "paperless_token_desc_generate": "Створіть токен API у вашому екземплярі Paperless-ngx (Налаштування → API токени).",
+ "paperless_view_in_app": "Перегляд документів у додатку",
+ "paperless_view_in_app_desc": "Відкривати документи всередині програми замість нової вкладки",
+ "debug_config": "Відлагоджувальна конфігурація",
+ "test_upload": "Тестове завантаження",
+ "save_paperless_settings": "Зберегти налаштування Paperless-ngx",
+ "apprise_desc": "Налаштуйте Apprise для розширеної доставки сповіщень у кілька сервісів",
+ "apprise_desc_system_wide": "Увімкнути або вимкнути сповіщення Apprise для всієї системи",
+ "apprise_not_available_title": "Apprise недоступний:",
+ "apprise_not_available_desc": "Бібліотека сповіщень Apprise не встановлена або недоступна. Функції сповіщень вимкнені.",
+ "apprise_url": "URL Apprise",
+ "apprise_url_desc": "URL вашого сервісу сповіщень Apprise",
+ "apprise_mode": "Режим сповіщень",
+ "apprise_mode_desc": "Виберіть, коли надсилати сповіщення Apprise",
+ "apprise_mode_global": "Глобальний звіт",
+ "apprise_mode_individual": "Для кожного користувача",
+ "test_paperless": "Тестувати з'єднання з Paperless",
+ "test_apprise": "Тестувати з'єднання з Apprise",
+ "apprise_warranty_scope": "Область гарантій",
+ "apprise_warranty_scope_desc": "Виберіть, які гарантії включати у сповіщення",
+ "all_warranties": "Всі гарантії",
+ "personal_warranties": "Тільки особисті гарантії",
+ "all_users_warranties": "Гарантії всіх користувачів",
+ "admin_warranties_only": "Тільки гарантії адміністратора",
+ "apprise_notification_days": "Дні сповіщень",
+ "apprise_notification_days_desc": "Дні до закінчення терміну для надсилання сповіщень (через кому, наприклад, \"7,30\" для 7 і 30 днів до)",
+ "apprise_check_frequency": "Частота перевірки",
+ "apprise_check_frequency_desc": "Як часто система перевіряє гарантії, що закінчуються (глобальне налаштування)",
+ "apprise_title_prefix": "Префікс заголовка повідомлення",
+ "apprise_title_prefix_desc": "Префікс, що додається до заголовків сповіщень (наприклад, \"[Warracker]\" призведе до \"[Warracker] Гарантії скоро закінчуються\")",
+ "apprise_test_url": "Тестовий URL (необов'язково)",
+ "apprise_test_url_desc": "Необов'язково: URL для надсилання тільки тестових сповіщень (не буде збережено в основній конфігурації)",
+ "save_apprise_settings": "Зберегти налаштування Apprise",
+ "validate_urls": "Перевірити URL",
+ "send_expiration_notifications_now": "Надіслати сповіщення про закінчення терміну зараз",
+ "apprise_current_status": "Поточний статус",
+ "apprise_urls_configured": "Налаштовані URL:",
+ "apprise_supported_services": "Підтримувані сервіси",
+ "apprise_supported_services_desc": "Apprise підтримує понад 80 сервісів сповіщень, включаючи: Discord, Slack, Telegram, Email (Gmail, Outlook), Webhooks, Microsoft Teams, Matrix, Pushover, Ntfy, Gotify та багато інших.",
+ "view_full_list_of_supported_services": "Переглянути повний список підтримуваних сервісів",
+ "ownership_management": "Управління власністю",
+ "transfer_ownership": "Передати власність",
+ "warning_title": "Увага:",
+ "transfer_ownership_warning": "Передати власність над додатком іншому адміністратору. Ця дія незворотна.",
+ "transfer_ownership_desc": "Після передачі власності ви станете звичайним адміністратором, а новий власник отримає повний контроль над додатком.",
+ "select_new_owner": "Виберіть нового власника (повинен бути адміністратором)",
+ "select_admin_user": "Виберіть користувача-адміністратора...",
+ "transfer_ownership_button": "Передати власність",
+ "transfer_ownership_irreversible": "Цю дію не можна скасувати.",
+ "transfer_ownership_confirmation": "Ви збираєтеся передати власність над додатком",
+ "after_this_transfer": "Після цієї передачі:",
+ "transfer_ownership_consequence_1": "Ви станете звичайним адміністратором",
+ "transfer_ownership_consequence_2": "Новий власник отримає повний контроль над додатком",
+ "transfer_ownership_consequence_3": "Тільки новий власник зможе знову передати власність",
+ "transfer_ownership_type_to_confirm": "Для підтвердження введіть \"TRANSFER\" у поле нижче:"
+ },
+ "actions": {
+ "save": "Зберегти",
+ "cancel": "Скасувати",
+ "delete": "Видалити",
+ "edit": "Редагувати",
+ "export": "Експорт",
+ "import": "Імпорт",
+ "refresh": "Оновити",
+ "search": "Пошук",
+ "clear": "Очистити",
+ "upload": "Завантажити",
+ "download": "Завантажити",
+ "manage_tags": "Керування тегами",
+ "close": "Закрити",
+ "save_changes": "Зберегти зміни"
+ },
+ "filters": {
+ "all_status": "Всі статуси",
+ "all_tags": "Всі теги",
+ "all_vendors": "Всі продавці",
+ "all_types": "Всі типи",
+ "sort_by": "Сортувати за",
+ "sort_expiration": "Дата закінчення",
+ "sort_purchase": "Дата покупки",
+ "sort_age": "Вік",
+ "sort_name": "Назва продукту",
+ "sort_vendor": "Продавець",
+ "sort_warranty_type": "Тип гарантії",
+ "status": "Статус",
+ "tags": "Теги",
+ "vendor": "Продавець",
+ "warranty_type": "Тип гарантії",
+ "view": "Вигляд",
+ "scope": "Область"
+ },
+ "messages": {
+ "success": "Успіх",
+ "error": "Помилка",
+ "warning": "Попередження",
+ "loading": "Завантаження...",
+ "saved": "Зміни успішно збережено",
+ "deleted": "Елемент успішно видалено",
+ "confirm_delete": "Ви впевнені, що хочете видалити цей елемент?",
+ "no_results": "Результатів не знайдено",
+ "file_too_large": "Файл занадто великий",
+ "invalid_file_type": "Невірний тип файлу",
+ "fill_first_last_name": "Будь ласка, заповніть Ім'я та Прізвище",
+ "email_cannot_be_empty": "Адреса електронної пошти не може бути порожньою.",
+ "enter_valid_email": "Будь ласка, введіть дійсну адресу електронної пошти.",
+ "profile_updated_successfully": "Профіль успішно оновлено",
+ "preferences_saved_successfully": "Налаштування успішно збережено.",
+ "fill_password_fields": "Будь ласка, заповніть всі поля паролю",
+ "passwords_do_not_match": "Нові паролі не збігаються",
+ "password_min_length": "Пароль повинен містити щонайменше 8 символів",
+ "type_delete_to_confirm": "Будь ласка, введіть DELETE для підтвердження",
+ "account_deleted_successfully": "Обліковий запис успішно видалено",
+ "account_cannot_delete_offline": "Обліковий запис не можна видалити в офлайн режимі",
+ "failed_delete_account": "Не вдалося видалити обліковий запис. Спробуйте ще раз.",
+ "user_updated_successfully": "Користувача успішно оновлено",
+ "user_deleted_successfully": "Користувача успішно видалено",
+ "user_id_missing": "Відсутній ID користувача",
+ "failed_load_users": "Не вдалося завантажити користувачів",
+ "error_loading_users": "Помилка завантаження користувачів",
+ "select_user_transfer_ownership": "Будь ласка, виберіть користувача для передачі власності",
+ "ownership_transferred_successfully": "Власність успішно передано! Оновлення сторінки...",
+ "failed_load_site_settings": "Не вдалося завантажити налаштування сайту. Спробуйте ще раз.",
+ "invalid_email_base_url": "Недійсний формат базового URL електронної пошти. Повинен починатися з http:// або https://",
+ "no_site_settings_to_save": "Немає налаштувань сайту для збереження.",
+ "site_settings_saved_successfully": "Налаштування сайту успішно збережено",
+ "failed_save_site_settings": "Не вдалося зберегти налаштування сайту",
+ "oidc_settings_saved_successfully": "Налаштування OIDC успішно збережено.",
+ "failed_save_oidc_settings": "Не вдалося зберегти налаштування OIDC.",
+ "api_endpoint_accessible": "API кінцева точка доступна",
+ "api_endpoint_not_accessible": "API кінцева точка недоступна. Статус: ",
+ "only_admins_send_notifications": "Тільки адміністратори можуть надсилати сповіщення про гарантії",
+ "notifications_triggered_successfully": "Сповіщення успішно запущено",
+ "notification_settings_saved_successfully": "Налаштування сповіщень успішно збережено",
+ "apprise_settings_saved_successfully": "Налаштування Apprise успішно збережено",
+ "test_notification_sent_successfully": "Тестове сповіщення успішно надіслано",
+ "no_urls_to_validate": "Немає URL для перевірки",
+ "paperless_settings_saved_successfully": "Налаштування Paperless-ngx успішно збережено!",
+ "enter_valid_paperless_url": "Будь ласка, введіть дійсний URL (наприклад: https://paperless.yourdomain.com)",
+ "enter_paperless_url_first": "Спочатку введіть URL Paperless-ngx",
+ "paperless_connection_test_successful": "Тест підключення Paperless-ngx успішний!",
+ "paperless_connection_test_failed": "Тест підключення Paperless-ngx не вдався",
+ "enter_api_token_test_connection": "Будь ласка, введіть API токен для тестування підключення",
+ "failed_load_user_data": "Не вдалося завантажити дані користувача. Спробуйте ще раз.",
+ "could_not_connect_user_data": "Не вдалося підключитися для отримання даних користувача. Відображення кешованої інформації.",
+ "preferences_saved_locally_failed_sync": "Налаштування збережено локально, але не вдалося синхронізувати з сервером: ",
+ "preferences_saved_locally": "Налаштування збережено локально.",
+ "correct_errors_in_tab": "Будь ласка, виправте помилки у виділеній вкладці перед продовженням.",
+ "please_fill_out_this_field": "Будь ласка, заповніть це поле.",
+ "warranty_added_successfully": "Гарантія успішно додана",
+ "tag_name_required": "Назва тегу обов'язкова",
+ "tag_creation_function_not_found": "Функція створення тегу не знайдена",
+ "tag_created_successfully": "Тег успішно створено",
+ "tag_updated_successfully": "Тег успішно оновлено",
+ "tag_deleted_successfully": "Тег успішно видалено",
+ "failed_to_create_tag": "Не вдалося створити тег",
+ "failed_to_update_tag": "Не вдалося оновити тег",
+ "failed_to_delete_tag": "Не вдалося видалити тег"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية",
+ "ru": "Русский",
+ "uk": "Українська",
+ "zh_CN": "简体中文",
+ "zh_HK": "繁體中文",
+ "ja": "日本語",
+ "pt": "Português",
+ "ko": "한국어"
+ },
+ "status": {
+ "title": "Статус системи",
+ "dashboard_title": "Панель стану гарантій",
+ "global_dashboard_title": "Глобальна панель стану гарантій",
+ "overview": "Огляд",
+ "statistics": "Статистика",
+ "total_warranties": "Всього гарантій",
+ "active_warranties": "Активні гарантії",
+ "expiring_soon": "Скоро закінчуються",
+ "expired_warranties": "Прострочені гарантії",
+ "warranty_distribution": "Розподіл гарантій",
+ "expiration_timeline": "Часова шкала закінчення",
+ "recent_activity": "Недавня активність",
+ "recent_expirations": "Нещодавно прострочені або скоро закінчуються",
+ "recent_expirations_empty": "Немає нещодавно прострочених або скоро закінчуються гарантій.",
+ "system_health": "Стан системи",
+ "database_status": "Статус бази даних",
+ "connected": "Підключено",
+ "version": "Версія",
+ "uptime": "Час роботи"
+ },
+ "about": {
+ "title": "Про Warracker",
+ "description": "Комплексна система управління гарантіями, розроблена для відстеження, організації та управління всіма вашими гарантіями на продукти на одній безпечній та зручній платформі.",
+ "version": "Версія",
+ "update_status": "Статус оновлення",
+ "checking_updates": "Перевірка оновлень...",
+ "view_release_notes": "Переглянути примітки до випуску",
+ "project_info": "Інформація про проект",
+ "project_description": "Warracker - це система управління гарантіями з відкритим вихідним кодом, створена з використанням сучасних веб-технологій. Вона забезпечує безпечний та інтуїтивно зрозумілий спосіб управління гарантіями на продукти, відстеження дат закінчення та організації важливих документів.",
+ "github_repository": "Репозиторій GitHub",
+ "releases": "Релізи",
+ "community_support": "Спільнота та підтримка",
+ "community_description": "Приєднуйтесь до нашої спільноти для підтримки, обговорень та оновлень. Повідомляйте про помилки, запитуйте нові функції або отримуйте допомогу від інших користувачів та учасників.",
+ "discord_community": "Спільнота Discord",
+ "report_issues": "Повідомити про проблеми",
+ "developer_info": "Інформація про розробника",
+ "developer_description": "Warracker розроблений та підтримується Sassanix. Проект є відкритим та вітає внесок спільноти.",
+ "sassanix": "Sassanix",
+ "agpl_license": "Ліцензія AGPL-3.0",
+ "support_project": "Підтримати проект",
+ "support_description": "Якщо ви вважаєте Warracker корисним, розгляньте можливість підтримки його розробки!",
+ "new_version_available": "Доступна нова версія {{version}}!",
+ "latest_version": "Ви використовуєте останню версію",
+ "update_check_failed": "Не вдалося перевірити наявність оновлень",
+ "features": "Можливості",
+ "feature_track": "Відстеження гарантій на продукти",
+ "feature_notifications": "Отримання сповіщень про закінчення терміну",
+ "feature_documents": "Зберігання гарантійних документів",
+ "feature_reports": "Створення звітів про гарантії",
+ "feature_tags": "Організація за допомогою тегів",
+ "feature_export": "Експорт даних про гарантії",
+ "support": "Підтримка",
+ "documentation": "Документація",
+ "github": "Репозиторій GitHub",
+ "license": "Ліцензія",
+ "copyright": "Авторське право",
+ "developed_by": "Розроблено"
+ }
+}
diff --git a/locales/zh_CN/translation.json b/locales/zh_CN/translation.json
new file mode 100644
index 0000000..c7ef3fa
--- /dev/null
+++ b/locales/zh_CN/translation.json
@@ -0,0 +1,561 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "保修追踪器",
+ "nav": {
+ "home": "主页",
+ "status": "状态",
+ "settings": "设置",
+ "about": "关于"
+ },
+ "auth": {
+ "login": "登录",
+ "logout": "登出",
+ "register": "注册",
+ "username": "用户名",
+ "password": "密码",
+ "email": "电子邮件",
+ "first_name": "名",
+ "last_name": "姓",
+ "forgot_password": "忘记密码?",
+ "reset_password": "重置密码",
+ "confirm_password": "确认密码",
+ "create_account_title": "创建您的帐户",
+ "first_name_optional": "名(可选)",
+ "last_name_optional": "姓(可选)",
+ "username_hint": "用户名必须是唯一的,并将用于登录。",
+ "email_address": "电子邮件地址",
+ "toggle_password": "显示/隐藏密码",
+ "password_hint_simple": "密码必须至少包含8个字符,并包括大写字母、小写字母和数字。",
+ "password_requirements": "密码要求:",
+ "req_length": "至少8个字符",
+ "req_uppercase": "至少1个大写字母",
+ "req_lowercase": "至少1个小写字母",
+ "req_number": "至少1个数字",
+ "req_special": "至少1个特殊字符",
+ "create_account": "创建帐户",
+ "already_have_account": "已经有帐户了?",
+ "reset_password_title": "Warracker - 重置密码",
+ "reset_your_password": "重置您的密码",
+ "reset_password_info": "在下方输入您的电子邮件地址,我们将向您发送一个重置密码的链接。",
+ "send_reset_link": "发送重置链接",
+ "back_to_login": "返回登录",
+ "set_new_password_title": "Warracker - 设置新密码",
+ "set_new_password": "设置新密码",
+ "new_password": "新密码",
+ "confirm_new_password": "确认新密码",
+ "invalid_or_expired_link": "链接无效或已过期",
+ "invalid_link_info": "您点击的密码重置链接无效或已过期。",
+ "request_new_reset_link": "请求新的重置链接"
+ },
+ "warranties": {
+ "title": "您的保修",
+ "title_global": "所有用户的保修",
+ "add_new": "添加新保修",
+ "edit": "编辑保修",
+ "delete": "删除保修",
+ "product_name": "产品名称",
+ "purchase_date": "购买日期",
+ "warranty_duration": "保修期",
+ "years": "年",
+ "months": "月",
+ "days": "天",
+ "vendor": "供应商",
+ "serial_numbers": "序列号",
+ "purchase_price": "购买价格",
+ "notes": "备注",
+ "tags": "标签",
+ "status": "状态",
+ "expiration_date": "到期日期",
+ "active": "有效",
+ "expired": "已过期",
+ "expiring_soon": "即将过期",
+ "lifetime": "终身",
+ "no_warranties": "暂无保修。添加您的第一个保修以开始。",
+ "search_placeholder": "按名称、供应商、备注、标签或序列号查找...",
+ "warranty_type": "保修类型",
+ "other_document": "其他文件",
+ "product": "产品",
+ "expiration": "到期",
+ "actions": "操作",
+ "no_warranties_title": "暂无保修",
+ "no_warranties_desc": "添加您的第一个保修以开始",
+ "add_warranty": "添加保修",
+ "warranty_entry_method": "保修录入方式",
+ "warranty_duration_option": "保修期",
+ "exact_expiration_option": "确切到期日期",
+ "warranty_period": "保修期",
+ "expiration_date_label": "到期日期",
+ "currency": "货币",
+ "add_tags": "添加标签",
+ "add_tags_desc": "标签可帮助您整理和筛选保修",
+ "save_changes": "保存更改",
+ "confirm_delete": "确认删除",
+ "manage_tags": "管理标签",
+ "add_tag": "添加标签",
+ "unknown_status": "未知状态",
+ "expiring_soon_days": "即将过期({{days}} {{dayText}})",
+ "days_remaining": "剩余 {{days}} {{dayText}}",
+ "day_one": "天",
+ "day_other": "天",
+ "month_one": "月",
+ "month_other": "月",
+ "year_one": "年",
+ "year_other": "年",
+ "na": "不适用",
+ "age": "年龄",
+ "warranty": "保修",
+ "warranty_ends": "保修结束",
+ "price": "价格",
+ "serial_number": "序列号",
+ "vendor": "供应商",
+ "type": "类型",
+ "owner": "所有者",
+ "product_website": "产品网站",
+ "documents": "文件",
+ "summary": "摘要",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "年",
+ "months_placeholder": "月",
+ "days_placeholder": "天",
+ "add_any_notes_placeholder": "添加关于此保修的任何备注...",
+ "product_url_optional": "产品URL(可选)",
+ "enter_serial_number": "输入序列号",
+ "vendor_optional": "供应商(可选)",
+ "vendor_placeholder": "例如亚马逊、百思买等",
+ "lifetime_warranty": "终身保修",
+ "warranty_type_optional": "保修类型(可选)",
+ "select_warranty_type": "选择保修类型...",
+ "standard": "标准",
+ "extended": "延长",
+ "manufacturer": "制造商",
+ "third_party": "第三方",
+ "store": "商店",
+ "premium": "高级",
+ "limited": "有限",
+ "full": "全面",
+ "parts_only": "仅零件",
+ "labor_only": "仅人工",
+ "international": "国际",
+ "accidental_damage": "意外损坏",
+ "other_custom": "其他(自定义)",
+ "enter_custom_warranty_type": "输入自定义保修类型",
+ "purchase_price_optional": "购买价格(可选)",
+ "notes_optional": "备注(可选)",
+ "add_any_notes": "添加关于此保修的任何备注...",
+ "product_photo_optional": "产品照片(可选)",
+ "choose_photo": "选择照片",
+ "invoice_receipt": "发票/收据",
+ "store_locally": "本地存储",
+ "store_in_paperless": "存储在Paperless-ngx",
+ "choose_file": "选择文件",
+ "browse_paperless": "浏览Paperless-ngx文件",
+ "product_manual_optional": "产品手册(可选)",
+ "files_zip_rar_optional": "文件(ZIP/RAR,可选)",
+ "search_or_add_new_tag": "搜索或添加新标签...",
+ "product_information": "产品信息",
+ "product_url": "产品URL",
+ "warranty_details": "保修详情",
+ "product_photo": "产品照片",
+ "product_manual": "产品手册",
+ "files": "文件",
+ "selected_tags": "已选标签",
+ "previous_tab": "上一步",
+ "next_tab": "下一步",
+ "delete_photo": "删除照片",
+ "delete_invoice": "删除发票",
+ "delete_manual": "删除手册",
+ "delete_files": "删除文件",
+ "current_photo": "当前照片:",
+ "current_invoice": "当前发票:",
+ "current_manual": "当前手册:",
+ "current_document": "当前文件:",
+ "upload_new_photo_replace": "(上传新照片以替换)",
+ "no_photo_uploaded": "未上传照片",
+ "no_invoice_uploaded": "未上传发票",
+ "no_manual_uploaded": "未上传手册",
+ "no_document_uploaded": "未上传其他文件",
+ "photo_will_be_deleted": "照片将在保存时删除",
+ "invoice_will_be_deleted": "发票将在保存时删除",
+ "manual_will_be_deleted": "手册将在保存时删除",
+ "document_will_be_deleted": "其他文件将在保存时删除",
+ "confirm_delete_message": "您确定要删除此保修吗?此操作无法撤销。",
+ "new_tag_name": "新标签名称",
+ "existing_tags": "现有标签",
+ "edit_warranty": "编辑保修",
+ "warranty_type_standard": "标准",
+ "warranty_type_extended": "延长",
+ "warranty_type_manufacturer": "制造商",
+ "warranty_type_third_party": "第三方",
+ "warranty_type_store": "商店",
+ "warranty_type_premium": "高级",
+ "warranty_type_limited": "有限",
+ "warranty_type_full": "全面",
+ "warranty_type_parts_only": "仅零件",
+ "warranty_type_labor_only": "仅人工",
+ "warranty_type_international": "国际",
+ "warranty_type_accidental_damage": "意外损坏",
+ "warranty_type_other": "其他(自定义)",
+ "warranty_type_custom_placeholder": "输入自定义保修类型",
+ "notes_placeholder": "关于此保修的其他备注...",
+ "tags_help_text": "标签可帮助您整理和筛选保修",
+ "search_add_tag_placeholder": "搜索或添加新标签...",
+ "upload_new_file_replace": "上传新文件以替换",
+ "current_other_document": "当前其他文件",
+ "no_other_document_uploaded": "未上传其他文件",
+ "other_document_will_be_deleted": "其他文件将在保存时删除",
+ "files_optional": "文件(ZIP/RAR,可选)",
+ "invoice_receipt_short": "发票",
+ "product_manual_short": "手册",
+ "files_short": "文件",
+ "enter_serial_number": "输入序列号",
+ "add_serial_number": "添加另一个序列号"
+ },
+ "settings": {
+ "title": "设置",
+ "account_settings": "账户设置",
+ "preferences": "偏好设置",
+ "language": "语言",
+ "select_language": "选择语言",
+ "dark_mode": "深色模式",
+ "dark_mode_desc": "在浅色和深色主题之间切换",
+ "currency": "货币",
+ "timezone": "时区",
+ "date_format": "日期格式",
+ "expiring_soon_days": "即将过期天数",
+ "save_changes": "保存更改",
+ "current_user": "正在编辑的个人资料:",
+ "your_email": "您的电子邮件:",
+ "first_name": "名",
+ "last_name": "姓",
+ "email": "电子邮件",
+ "save_profile": "保存更改",
+ "default_view": "默认视图",
+ "default_view_desc": "选择您偏好的保修视图",
+ "grid_view": "网格视图",
+ "list_view": "列表视图",
+ "table_view": "表格视图",
+ "currency_symbol": "货币符号",
+ "currency_symbol_desc": "选择用于显示价格的符号",
+ "currency_position": "货币位置",
+ "currency_position_desc": "选择货币符号显示在数字的左侧还是右侧",
+ "expiring_soon_days_desc": "到期前多少天显示警告",
+ "date_format_desc": "选择日期的显示方式",
+ "save_preferences": "保存偏好设置",
+ "notification_settings": "通知设置",
+ "notification_channel": "通知渠道",
+ "notification_channel_desc": "选择您希望如何接收通知",
+ "notification_disabled": "已禁用",
+ "notification_email": "电子邮件",
+ "notification_apprise": "Apprise",
+ "notification_both": "两者",
+ "email_settings": "电子邮件设置",
+ "notification_frequency": "通知频率",
+ "notification_frequency_desc": "接收电子邮件通知的频率",
+ "daily": "每日",
+ "weekly": "每周",
+ "monthly": "每月",
+ "notification_time": "通知时间",
+ "timezone_desc": "您当地的通知时区",
+ "apprise_settings": "Apprise设置",
+ "apprise_frequency": "Apprise通知频率",
+ "apprise_frequency_desc": "接收Apprise通知的频率",
+ "apprise_time": "Apprise通知时间",
+ "apprise_timezone": "Apprise时区",
+ "apprise_timezone_desc": "您当地的Apprise通知时区",
+ "save_notification_settings": "保存通知设置",
+ "security": "安全",
+ "change_password": "更改密码",
+ "change_password_desc": "更新您的账户密码",
+ "change": "更改",
+ "current_password": "当前密码",
+ "new_password": "新密码",
+ "confirm_password": "确认新密码",
+ "update_password": "更新密码",
+ "cancel": "取消",
+ "danger_zone": "危险区域",
+ "delete_account": "删除账户",
+ "delete_account_desc": "永久删除您的账户和所有数据",
+ "admin_settings": "管理员设置",
+ "admin_actions": "管理员操作",
+ "refresh_data": "刷新数据",
+ "check_admin_status": "检查管理员状态",
+ "show_users_list": "显示用户列表",
+ "test_api": "测试API",
+ "send_notifications": "发送保修通知",
+ "check_scheduler": "检查计划任务状态",
+ "site_settings": "站点设置",
+ "registration_enabled": "已启用注册",
+ "registration_enabled_desc": "允许新用户注册",
+ "email_base_url": "电子邮件基础URL",
+ "global_view_enabled": "已启用全局视图",
+ "global_view_admin_only": "全局视图仅限管理员",
+ "save_site_settings": "保存站点设置",
+ "oidc_configuration": "OIDC SSO配置",
+ "enable_oidc": "启用OIDC SSO",
+ "oidc_provider_name": "OIDC提供商名称",
+ "client_id": "客户端ID",
+ "client_secret": "客户端密钥",
+ "issuer_url": "发行者URL",
+ "scope": "范围",
+ "save_oidc_settings": "保存OIDC设置",
+ "oidc_sso_desc": "允许用户通过OIDC提供商登录。",
+ "oidc_only_mode": "仅OIDC登录模式",
+ "oidc_only_mode_desc": "隐藏传统的用户名/密码登录表单,仅允许OIDC登录。<strong>警告:</strong>在启用此选项之前,请确保OIDC已正确配置。",
+ "oidc_provider_name_desc": "OIDC客户端的内部名称(例如'oidc')。",
+ "client_secret_desc": "敏感值。存储在数据库中。更改生效需要重新启动应用程序。",
+ "issuer_url_desc": "您的OIDC提供商的基础URL。",
+ "scope_desc": "以空格分隔的OIDC范围。",
+ "oidc_restart_message": "OIDC设置需要重新启动应用程序才能完全生效。",
+ "api_token": "API令牌",
+ "view_documents": "在Warracker中查看文件",
+ "connection_testing": "连接测试",
+ "apprise_notifications": "Apprise通知",
+ "enable_apprise": "启用Apprise通知",
+ "loading": "加载中...",
+ "time_of_day_notification": "接收通知的时间(24小时格式)",
+ "paperless_ngx_settings": "Paperless-ngx设置",
+ "paperless_ngx_about_title": "关于Paperless-ngx集成:",
+ "paperless_ngx_about_desc": "此可选功能允许您将保修文件存储在自托管的Paperless-ngx实例中,而不是本地存储。启用后,用户可以选择将每个文件存储在本地还是Paperless-ngx中。",
+ "paperless_ngx_desc": "配置与Paperless-ngx文档管理系统的集成",
+ "enable_paperless": "启用Paperless-ngx集成",
+ "paperless_url": "Paperless-ngx URL",
+ "paperless_url_desc": "您的Paperless-ngx实例的基础URL",
+ "paperless_token": "API令牌",
+ "paperless_token_desc": "您的Paperless-ngx API身份验证令牌",
+ "paperless_token_desc_generate": "从您的Paperless-ngx实例生成API令牌(设置→API令牌)。",
+ "paperless_view_in_app": "在应用内查看文件",
+ "paperless_view_in_app_desc": "在应用内打开文件,而不是在新标签页中",
+ "debug_config": "调试配置",
+ "test_upload": "测试上传",
+ "save_paperless_settings": "保存Paperless-ngx设置",
+ "apprise_desc": "配置Apprise以实现向多个服务的高级通知传递",
+ "apprise_desc_system_wide": "在系统范围内启用或禁用Apprise通知",
+ "apprise_not_available_title": "Apprise不可用:",
+ "apprise_not_available_desc": "Apprise通知库未安装或不可用。通知功能已禁用。",
+ "apprise_url": "Apprise URL",
+ "apprise_url_desc": "您的Apprise通知服务URL",
+ "apprise_mode": "通知模式",
+ "apprise_mode_desc": "选择何时发送Apprise通知",
+ "apprise_mode_global": "全局摘要",
+ "apprise_mode_individual": "按用户",
+ "test_paperless": "测试Paperless连接",
+ "test_apprise": "测试Apprise连接",
+ "apprise_warranty_scope": "保修范围",
+ "apprise_warranty_scope_desc": "选择要在通知中包含的保修",
+ "all_warranties": "所有保修",
+ "personal_warranties": "仅个人保修",
+ "all_users_warranties": "所有用户的保修",
+ "admin_warranties_only": "仅管理员的保修",
+ "apprise_notification_days": "通知天数",
+ "apprise_notification_days_desc": "到期前多少天发送通知(以逗号分隔,例如“7,30”表示提前7天和30天)",
+ "apprise_check_frequency": "检查频率",
+ "apprise_check_frequency_desc": "系统检查即将到期的保修的频率(全局设置)",
+ "apprise_title_prefix": "消息标题前缀",
+ "apprise_title_prefix_desc": "添加到通知标题的前缀(例如,“[Warracker]”将导致“[Warracker]保修即将到期”)",
+ "apprise_test_url": "测试URL(可选)",
+ "apprise_test_url_desc": "可选:仅用于发送测试通知的URL(不会保存到主配置中)",
+ "save_apprise_settings": "保存Apprise设置",
+ "validate_urls": "验证URL",
+ "send_expiration_notifications_now": "立即发送到期通知",
+ "apprise_current_status": "当前状态",
+ "apprise_urls_configured": "已配置的URL:",
+ "apprise_supported_services": "支持的服务",
+ "apprise_supported_services_desc": "Apprise支持80多种通知服务,包括:Discord、Slack、Telegram、电子邮件(Gmail、Outlook)、Webhooks、Microsoft Teams、Matrix、Pushover、Ntfy、Gotify等等。",
+ "view_full_list_of_supported_services": "查看支持的服务的完整列表",
+ "ownership_management": "所有权管理",
+ "transfer_ownership": "转移所有权",
+ "warning_title": "警告:",
+ "transfer_ownership_warning": "将应用程序所有权转移给另一位管理员用户。此操作不可逆。",
+ "transfer_ownership_desc": "所有权转移后,您将成为普通管理员,新所有者将拥有对应用程序的最终控制权。",
+ "select_new_owner": "选择新所有者(必须是管理员)",
+ "select_admin_user": "选择管理员用户...",
+ "transfer_ownership_button": "转移所有权",
+ "transfer_ownership_irreversible": "此操作无法撤销。",
+ "transfer_ownership_confirmation": "您即将将应用程序所有权转移给",
+ "after_this_transfer": "此次转移后:",
+ "transfer_ownership_consequence_1": "您将成为普通管理员",
+ "transfer_ownership_consequence_2": "新所有者将拥有对应用程序的最终控制权",
+ "transfer_ownership_consequence_3": "只有新所有者才能再次转移所有权",
+ "transfer_ownership_type_to_confirm": "要确认,请在下面的字段中输入“TRANSFER”:"
+ },
+ "actions": {
+ "save": "保存",
+ "cancel": "取消",
+ "delete": "删除",
+ "edit": "编辑",
+ "export": "导出",
+ "import": "导入",
+ "refresh": "刷新",
+ "search": "搜索",
+ "clear": "清除",
+ "upload": "上传",
+ "download": "下载",
+ "manage_tags": "管理标签",
+ "close": "关闭",
+ "save_changes": "保存更改"
+ },
+ "filters": {
+ "all_status": "所有状态",
+ "all_tags": "所有标签",
+ "all_vendors": "所有供应商",
+ "all_types": "所有类型",
+ "sort_by": "排序方式",
+ "sort_expiration": "到期日期",
+ "sort_purchase": "购买日期",
+ "sort_age": "年龄",
+ "sort_name": "产品名称",
+ "sort_vendor": "供应商",
+ "sort_warranty_type": "保修类型",
+ "status": "状态",
+ "tags": "标签",
+ "vendor": "供应商",
+ "warranty_type": "保修类型",
+ "view": "视图",
+ "scope": "范围"
+ },
+ "messages": {
+ "success": "成功",
+ "error": "错误",
+ "warning": "警告",
+ "loading": "加载中...",
+ "saved": "更改已成功保存",
+ "deleted": "项目已成功删除",
+ "confirm_delete": "您确定要删除此项目吗?",
+ "no_results": "未找到结果",
+ "file_too_large": "文件太大",
+ "invalid_file_type": "无效的文件类型",
+ "fill_first_last_name": "请填写姓名",
+ "email_cannot_be_empty": "电子邮件地址不能为空。",
+ "enter_valid_email": "请输入有效的电子邮件地址。",
+ "profile_updated_successfully": "个人资料更新成功",
+ "preferences_saved_successfully": "偏好设置保存成功。",
+ "fill_password_fields": "请填写所有密码字段",
+ "passwords_do_not_match": "新密码不匹配",
+ "password_min_length": "密码必须至少8个字符",
+ "type_delete_to_confirm": "请输入DELETE以确认",
+ "account_deleted_successfully": "账户删除成功",
+ "account_cannot_delete_offline": "无法在离线模式下删除账户",
+ "failed_delete_account": "删除账户失败。请重试。",
+ "user_updated_successfully": "用户更新成功",
+ "user_deleted_successfully": "用户删除成功",
+ "user_id_missing": "用户ID缺失",
+ "failed_load_users": "加载用户失败",
+ "error_loading_users": "加载用户时出错",
+ "select_user_transfer_ownership": "请选择要转移所有权的用户",
+ "ownership_transferred_successfully": "所有权转移成功!正在刷新页面...",
+ "failed_load_site_settings": "加载站点设置失败。请重试。",
+ "invalid_email_base_url": "电子邮件基础URL格式无效。应以http://或https://开头",
+ "no_site_settings_to_save": "没有要保存的站点设置。",
+ "site_settings_saved_successfully": "站点设置保存成功",
+ "failed_save_site_settings": "保存站点设置失败",
+ "oidc_settings_saved_successfully": "OIDC设置保存成功。",
+ "failed_save_oidc_settings": "保存OIDC设置失败。",
+ "api_endpoint_accessible": "API端点可访问",
+ "api_endpoint_not_accessible": "API端点不可访问。状态:",
+ "only_admins_send_notifications": "只有管理员可以发送保修通知",
+ "notifications_triggered_successfully": "通知触发成功",
+ "notification_settings_saved_successfully": "通知设置保存成功",
+ "apprise_settings_saved_successfully": "Apprise设置保存成功",
+ "test_notification_sent_successfully": "测试通知发送成功",
+ "no_urls_to_validate": "没有要验证的URL",
+ "paperless_settings_saved_successfully": "Paperless-ngx设置保存成功!",
+ "enter_valid_paperless_url": "请输入有效的URL(例如https://paperless.yourdomain.com)",
+ "enter_paperless_url_first": "请先输入Paperless-ngx URL",
+ "paperless_connection_test_successful": "Paperless-ngx连接测试成功!",
+ "paperless_connection_test_failed": "Paperless-ngx连接测试失败",
+ "enter_api_token_test_connection": "请输入API令牌以测试连接",
+ "failed_load_user_data": "加载用户数据失败。请重试。",
+ "could_not_connect_user_data": "无法连接以检索用户数据。显示缓存信息。",
+ "preferences_saved_locally_failed_sync": "偏好设置已本地保存,但与服务器同步失败:",
+ "preferences_saved_locally": "偏好设置已本地保存。",
+ "correct_errors_in_tab": "请在继续之前更正突出显示的选项卡中的错误。",
+ "please_fill_out_this_field": "请填写此字段。",
+ "warranty_added_successfully": "保修添加成功",
+ "tag_name_required": "标签名称是必需的",
+ "tag_creation_function_not_found": "未找到标签创建功能",
+ "tag_created_successfully": "标签创建成功",
+ "tag_updated_successfully": "标签更新成功",
+ "tag_deleted_successfully": "标签删除成功",
+ "failed_to_create_tag": "创建标签失败",
+ "failed_to_update_tag": "更新标签失败",
+ "failed_to_delete_tag": "删除标签失败"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية",
+ "ru": "Русский",
+ "uk": "Українська",
+ "zh_CN": "简体中文",
+ "zh_HK": "繁體中文",
+ "ja": "日本語",
+ "pt": "Português",
+ "ko": "한국어"
+ },
+ "status": {
+ "title": "系统状态",
+ "dashboard_title": "保修状态仪表板",
+ "global_dashboard_title": "全局保修状态仪表板",
+ "overview": "概览",
+ "statistics": "统计",
+ "total_warranties": "总保修数",
+ "active_warranties": "有效保修",
+ "expiring_soon": "即将过期",
+ "expired_warranties": "已过期保修",
+ "warranty_distribution": "保修分布",
+ "expiration_timeline": "到期时间线",
+ "recent_activity": "最近活动",
+ "recent_expirations": "最近过期或即将过期",
+ "recent_expirations_empty": "没有最近过期或即将到期的保修。",
+ "system_health": "系统健康",
+ "database_status": "数据库状态",
+ "connected": "已连接",
+ "version": "版本",
+ "uptime": "正常运行时间"
+ },
+ "about": {
+ "title": "关于Warracker",
+ "description": "一个全面的保修管理系统,旨在帮助您在一个安全、用户友好的平台中跟踪、整理和管理所有产品保修。",
+ "version": "版本",
+ "update_status": "更新状态",
+ "checking_updates": "正在检查更新...",
+ "view_release_notes": "查看发行说明",
+ "project_info": "项目信息",
+ "project_description": "Warracker是一个使用现代Web技术构建的开源保修管理系统。它提供了一种安全直观的方式来管理产品保修、跟踪到期日期和整理重要文件。",
+ "github_repository": "GitHub仓库",
+ "releases": "发行版",
+ "community_support": "社区与支持",
+ "community_description": "加入我们的社区以获得支持、讨论和更新。报告错误、请求功能或从其他用户和贡献者那里获得帮助。",
+ "discord_community": "Discord社区",
+ "report_issues": "报告问题",
+ "developer_info": "开发者信息",
+ "developer_description": "Warracker由Sassanix开发和维护。该项目是开源的,欢迎社区的贡献。",
+ "sassanix": "Sassanix",
+ "agpl_license": "AGPL-3.0许可证",
+ "support_project": "支持项目",
+ "support_description": "如果您觉得Warracker有用,请考虑支持其开发!",
+ "new_version_available": "新版本{{version}}可用!",
+ "latest_version": "您正在使用最新版本",
+ "update_check_failed": "检查更新失败",
+ "features": "功能",
+ "feature_track": "跟踪产品保修",
+ "feature_notifications": "获取到期通知",
+ "feature_documents": "存储保修文件",
+ "feature_reports": "生成保修报告",
+ "feature_tags": "使用标签整理",
+ "feature_export": "导出保修数据",
+ "support": "支持",
+ "documentation": "文档",
+ "github": "GitHub仓库",
+ "license": "许可证",
+ "copyright": "版权",
+ "developed_by": "开发者"
+ }
+}
diff --git a/locales/zh_HK/translation.json b/locales/zh_HK/translation.json
new file mode 100644
index 0000000..545e61a
--- /dev/null
+++ b/locales/zh_HK/translation.json
@@ -0,0 +1,561 @@
+{
+ "app_title": "Warracker",
+ "subtitle": "保養追蹤器",
+ "nav": {
+ "home": "主頁",
+ "status": "狀態",
+ "settings": "設定",
+ "about": "關於"
+ },
+ "auth": {
+ "login": "登入",
+ "logout": "登出",
+ "register": "註冊",
+ "username": "使用者名稱",
+ "password": "密碼",
+ "email": "電子郵件",
+ "first_name": "名字",
+ "last_name": "姓氏",
+ "forgot_password": "忘記密碼?",
+ "reset_password": "重設密碼",
+ "confirm_password": "確認密碼",
+ "create_account_title": "建立您的帳戶",
+ "first_name_optional": "名字(可選)",
+ "last_name_optional": "姓氏(可選)",
+ "username_hint": "使用者名稱必須是唯一的,並將用於登入。",
+ "email_address": "電子郵件地址",
+ "toggle_password": "顯示/隱藏密碼",
+ "password_hint_simple": "密碼必須至少包含8個字元,並包括大寫字母、小寫字母和數字。",
+ "password_requirements": "密碼要求:",
+ "req_length": "至少8個字元",
+ "req_uppercase": "至少1個大寫字母",
+ "req_lowercase": "至少1個小寫字母",
+ "req_number": "至少1個數字",
+ "req_special": "至少1個特殊字元",
+ "create_account": "建立帳戶",
+ "already_have_account": "已經有帳戶了?",
+ "reset_password_title": "Warracker - 重設密碼",
+ "reset_your_password": "重設您的密碼",
+ "reset_password_info": "在下方輸入您的電子郵件地址,我們將向您傳送一個重設密碼的連結。",
+ "send_reset_link": "傳送重設連結",
+ "back_to_login": "返回登入",
+ "set_new_password_title": "Warracker - 設定新密碼",
+ "set_new_password": "設定新密碼",
+ "new_password": "新密碼",
+ "confirm_new_password": "確認新密碼",
+ "invalid_or_expired_link": "連結無效或已過期",
+ "invalid_link_info": "您點擊的密碼重設連結無效或已過期。",
+ "request_new_reset_link": "請求新的重設連結"
+ },
+ "warranties": {
+ "title": "您的保養",
+ "title_global": "所有使用者的保養",
+ "add_new": "新增保養",
+ "edit": "編輯保養",
+ "delete": "刪除保養",
+ "product_name": "產品名稱",
+ "purchase_date": "購買日期",
+ "warranty_duration": "保養期",
+ "years": "年",
+ "months": "月",
+ "days": "天",
+ "vendor": "供應商",
+ "serial_numbers": "序號",
+ "purchase_price": "購買價格",
+ "notes": "備註",
+ "tags": "標籤",
+ "status": "狀態",
+ "expiration_date": "到期日期",
+ "active": "有效",
+ "expired": "已過期",
+ "expiring_soon": "即將到期",
+ "lifetime": "終身",
+ "no_warranties": "暫無保養。新增您的第一個保養以開始。",
+ "search_placeholder": "按名稱、供應商、備註、標籤或序號尋找...",
+ "warranty_type": "保養類型",
+ "other_document": "其他文件",
+ "product": "產品",
+ "expiration": "到期",
+ "actions": "操作",
+ "no_warranties_title": "暫無保養",
+ "no_warranties_desc": "新增您的第一個保養以開始",
+ "add_warranty": "新增保養",
+ "warranty_entry_method": "保養登錄方式",
+ "warranty_duration_option": "保養期",
+ "exact_expiration_option": "確切到期日期",
+ "warranty_period": "保養期",
+ "expiration_date_label": "到期日期",
+ "currency": "貨幣",
+ "add_tags": "新增標籤",
+ "add_tags_desc": "標籤可幫助您整理和篩選保養",
+ "save_changes": "儲存變更",
+ "confirm_delete": "確認刪除",
+ "manage_tags": "管理標籤",
+ "add_tag": "新增標籤",
+ "unknown_status": "未知狀態",
+ "expiring_soon_days": "即將到期({{days}} {{dayText}})",
+ "days_remaining": "剩餘 {{days}} {{dayText}}",
+ "day_one": "天",
+ "day_other": "天",
+ "month_one": "月",
+ "month_other": "月",
+ "year_one": "年",
+ "year_other": "年",
+ "na": "不適用",
+ "age": "年齡",
+ "warranty": "保養",
+ "warranty_ends": "保養結束",
+ "price": "價格",
+ "serial_number": "序號",
+ "vendor": "供應商",
+ "type": "類型",
+ "owner": "所有者",
+ "product_website": "產品網站",
+ "documents": "文件",
+ "summary": "摘要",
+ "product_url_placeholder": "https://example.com/product",
+ "years_placeholder": "年",
+ "months_placeholder": "月",
+ "days_placeholder": "天",
+ "add_any_notes_placeholder": "新增關於此保養的任何備註...",
+ "product_url_optional": "產品URL(可選)",
+ "enter_serial_number": "輸入序號",
+ "vendor_optional": "供應商(可選)",
+ "vendor_placeholder": "例如Amazon、Best Buy等",
+ "lifetime_warranty": "終身保養",
+ "warranty_type_optional": "保養類型(可選)",
+ "select_warranty_type": "選擇保養類型...",
+ "standard": "標準",
+ "extended": "延長",
+ "manufacturer": "製造商",
+ "third_party": "第三方",
+ "store": "商店",
+ "premium": "高級",
+ "limited": "有限",
+ "full": "全面",
+ "parts_only": "僅零件",
+ "labor_only": "僅人工",
+ "international": "國際",
+ "accidental_damage": "意外損壞",
+ "other_custom": "其他(自訂)",
+ "enter_custom_warranty_type": "輸入自訂保養類型",
+ "purchase_price_optional": "購買價格(可選)",
+ "notes_optional": "備註(可選)",
+ "add_any_notes": "新增關於此保養的任何備註...",
+ "product_photo_optional": "產品照片(可選)",
+ "choose_photo": "選擇照片",
+ "invoice_receipt": "發票/收據",
+ "store_locally": "本地儲存",
+ "store_in_paperless": "儲存在Paperless-ngx",
+ "choose_file": "選擇檔案",
+ "browse_paperless": "瀏覽Paperless-ngx文件",
+ "product_manual_optional": "產品手冊(可選)",
+ "files_zip_rar_optional": "檔案(ZIP/RAR,可選)",
+ "search_or_add_new_tag": "搜尋或新增標籤...",
+ "product_information": "產品資訊",
+ "product_url": "產品URL",
+ "warranty_details": "保養詳情",
+ "product_photo": "產品照片",
+ "product_manual": "產品手冊",
+ "files": "檔案",
+ "selected_tags": "已選標籤",
+ "previous_tab": "上一步",
+ "next_tab": "下一步",
+ "delete_photo": "刪除照片",
+ "delete_invoice": "刪除發票",
+ "delete_manual": "刪除手冊",
+ "delete_files": "刪除檔案",
+ "current_photo": "目前照片:",
+ "current_invoice": "目前發票:",
+ "current_manual": "目前手冊:",
+ "current_document": "目前文件:",
+ "upload_new_photo_replace": "(上傳新照片以取代)",
+ "no_photo_uploaded": "未上傳照片",
+ "no_invoice_uploaded": "未上傳發票",
+ "no_manual_uploaded": "未上傳手冊",
+ "no_document_uploaded": "未上傳其他文件",
+ "photo_will_be_deleted": "照片將在儲存時刪除",
+ "invoice_will_be_deleted": "發票將在儲存時刪除",
+ "manual_will_be_deleted": "手冊將在儲存時刪除",
+ "document_will_be_deleted": "其他文件將在儲存時刪除",
+ "confirm_delete_message": "您確定要刪除此保養嗎?此操作無法復原。",
+ "new_tag_name": "新標籤名稱",
+ "existing_tags": "現有標籤",
+ "edit_warranty": "編輯保養",
+ "warranty_type_standard": "標準",
+ "warranty_type_extended": "延長",
+ "warranty_type_manufacturer": "製造商",
+ "warranty_type_third_party": "第三方",
+ "warranty_type_store": "商店",
+ "warranty_type_premium": "高級",
+ "warranty_type_limited": "有限",
+ "warranty_type_full": "全面",
+ "warranty_type_parts_only": "僅零件",
+ "warranty_type_labor_only": "僅人工",
+ "warranty_type_international": "國際",
+ "warranty_type_accidental_damage": "意外損壞",
+ "warranty_type_other": "其他(自訂)",
+ "warranty_type_custom_placeholder": "輸入自訂保養類型",
+ "notes_placeholder": "關於此保養的其他備註...",
+ "tags_help_text": "標籤可幫助您整理和篩選保養",
+ "search_add_tag_placeholder": "搜尋或新增標籤...",
+ "upload_new_file_replace": "上傳新檔案以取代",
+ "current_other_document": "目前其他文件",
+ "no_other_document_uploaded": "未上傳其他文件",
+ "other_document_will_be_deleted": "其他文件將在儲存時刪除",
+ "files_optional": "檔案(ZIP/RAR,可選)",
+ "invoice_receipt_short": "發票",
+ "product_manual_short": "手冊",
+ "files_short": "檔案",
+ "enter_serial_number": "輸入序列號",
+ "add_serial_number": "新增另一個序列號"
+ },
+ "settings": {
+ "title": "設定",
+ "account_settings": "帳戶設定",
+ "preferences": "偏好設定",
+ "language": "語言",
+ "select_language": "選擇語言",
+ "dark_mode": "深色模式",
+ "dark_mode_desc": "在淺色和深色主題之間切換",
+ "currency": "貨幣",
+ "timezone": "時區",
+ "date_format": "日期格式",
+ "expiring_soon_days": "即將到期天數",
+ "save_changes": "儲存變更",
+ "current_user": "正在編輯的個人資料:",
+ "your_email": "您的電子郵件:",
+ "first_name": "名字",
+ "last_name": "姓氏",
+ "email": "電子郵件",
+ "save_profile": "儲存變更",
+ "default_view": "預設檢視",
+ "default_view_desc": "選擇您偏好的保養檢視",
+ "grid_view": "網格檢視",
+ "list_view": "清單檢視",
+ "table_view": "表格檢視",
+ "currency_symbol": "貨幣符號",
+ "currency_symbol_desc": "選擇用於顯示價格的符號",
+ "currency_position": "貨幣位置",
+ "currency_position_desc": "選擇貨幣符號顯示在數字的左側還是右側",
+ "expiring_soon_days_desc": "到期前多少天顯示警告",
+ "date_format_desc": "選擇日期的顯示方式",
+ "save_preferences": "儲存偏好設定",
+ "notification_settings": "通知設定",
+ "notification_channel": "通知管道",
+ "notification_channel_desc": "選擇您希望如何接收通知",
+ "notification_disabled": "已停用",
+ "notification_email": "電子郵件",
+ "notification_apprise": "Apprise",
+ "notification_both": "兩者",
+ "email_settings": "電子郵件設定",
+ "notification_frequency": "通知頻率",
+ "notification_frequency_desc": "接收電子郵件通知的頻率",
+ "daily": "每日",
+ "weekly": "每週",
+ "monthly": "每月",
+ "notification_time": "通知時間",
+ "timezone_desc": "您當地的通知時區",
+ "apprise_settings": "Apprise設定",
+ "apprise_frequency": "Apprise通知頻率",
+ "apprise_frequency_desc": "接收Apprise通知的頻率",
+ "apprise_time": "Apprise通知時間",
+ "apprise_timezone": "Apprise時區",
+ "apprise_timezone_desc": "您當地的Apprise通知時區",
+ "save_notification_settings": "儲存通知設定",
+ "security": "安全",
+ "change_password": "變更密碼",
+ "change_password_desc": "更新您的帳戶密碼",
+ "change": "變更",
+ "current_password": "目前密碼",
+ "new_password": "新密碼",
+ "confirm_password": "確認新密碼",
+ "update_password": "更新密碼",
+ "cancel": "取消",
+ "danger_zone": "危險區域",
+ "delete_account": "刪除帳戶",
+ "delete_account_desc": "永久刪除您的帳戶和所有資料",
+ "admin_settings": "管理員設定",
+ "admin_actions": "管理員操作",
+ "refresh_data": "重新整理資料",
+ "check_admin_status": "檢查管理員狀態",
+ "show_users_list": "顯示使用者清單",
+ "test_api": "測試API",
+ "send_notifications": "傳送保養通知",
+ "check_scheduler": "檢查排程器狀態",
+ "site_settings": "網站設定",
+ "registration_enabled": "已啟用註冊",
+ "registration_enabled_desc": "允許新使用者註冊",
+ "email_base_url": "電子郵件基礎URL",
+ "global_view_enabled": "已啟用全域檢視",
+ "global_view_admin_only": "全域檢視僅限管理員",
+ "save_site_settings": "儲存網站設定",
+ "oidc_configuration": "OIDC SSO設定",
+ "enable_oidc": "啟用OIDC SSO",
+ "oidc_provider_name": "OIDC提供者名稱",
+ "client_id": "用戶端ID",
+ "client_secret": "用戶端密鑰",
+ "issuer_url": "發行者URL",
+ "scope": "範圍",
+ "save_oidc_settings": "儲存OIDC設定",
+ "oidc_sso_desc": "允許使用者透過OIDC提供者登入。",
+ "oidc_only_mode": "僅OIDC登入模式",
+ "oidc_only_mode_desc": "隱藏傳統的使用者名稱/密碼登入表單,僅允許OIDC登入。<strong>警告:</strong>在啟用此選項之前,請確保OIDC已正確設定。",
+ "oidc_provider_name_desc": "OIDC用戶端的內部名稱(例如'oidc')。",
+ "client_secret_desc": "敏感值。儲存在資料庫中。變更生效需要重新啟動應用程式。",
+ "issuer_url_desc": "您的OIDC提供者的基礎URL。",
+ "scope_desc": "以空格分隔的OIDC範圍。",
+ "oidc_restart_message": "OIDC設定需要重新啟動應用程式才能完全生效。",
+ "api_token": "API權杖",
+ "view_documents": "在Warracker中檢視文件",
+ "connection_testing": "連線測試",
+ "apprise_notifications": "Apprise通知",
+ "enable_apprise": "啟用Apprise通知",
+ "loading": "載入中...",
+ "time_of_day_notification": "接收通知的時間(24小時格式)",
+ "paperless_ngx_settings": "Paperless-ngx設定",
+ "paperless_ngx_about_title": "關於Paperless-ngx整合:",
+ "paperless_ngx_about_desc": "此可選功能允許您將保養文件儲存在自託管的Paperless-ngx執行個體中,而不是本地儲存。啟用後,使用者可以選擇將每個文件儲存在本地還是Paperless-ngx中。",
+ "paperless_ngx_desc": "設定與Paperless-ngx文件管理系統的整合",
+ "enable_paperless": "啟用Paperless-ngx整合",
+ "paperless_url": "Paperless-ngx URL",
+ "paperless_url_desc": "您的Paperless-ngx執行個體的基礎URL",
+ "paperless_token": "API權杖",
+ "paperless_token_desc": "您的Paperless-ngx API驗證權杖",
+ "paperless_token_desc_generate": "從您的Paperless-ngx執行個體產生API權杖(設定→API權杖)。",
+ "paperless_view_in_app": "在應用程式內檢視文件",
+ "paperless_view_in_app_desc": "在應用程式內開啟文件,而不是在新分頁中",
+ "debug_config": "偵錯設定",
+ "test_upload": "測試上傳",
+ "save_paperless_settings": "儲存Paperless-ngx設定",
+ "apprise_desc": "設定Apprise以實現向多個服務的進階通知傳遞",
+ "apprise_desc_system_wide": "在系統範圍內啟用或停用Apprise通知",
+ "apprise_not_available_title": "Apprise不可用:",
+ "apprise_not_available_desc": "Apprise通知庫未安裝或不可用。通知功能已停用。",
+ "apprise_url": "Apprise URL",
+ "apprise_url_desc": "您的Apprise通知服務URL",
+ "apprise_mode": "通知模式",
+ "apprise_mode_desc": "選擇何時傳送Apprise通知",
+ "apprise_mode_global": "全域摘要",
+ "apprise_mode_individual": "按使用者",
+ "test_paperless": "測試Paperless連線",
+ "test_apprise": "測試Apprise連線",
+ "apprise_warranty_scope": "保養範圍",
+ "apprise_warranty_scope_desc": "選擇要在通知中包含的保養",
+ "all_warranties": "所有保養",
+ "personal_warranties": "僅個人保養",
+ "all_users_warranties": "所有使用者的保養",
+ "admin_warranties_only": "僅管理員的保養",
+ "apprise_notification_days": "通知天數",
+ "apprise_notification_days_desc": "到期前多少天傳送通知(以逗號分隔,例如“7,30”表示提前7天和30天)",
+ "apprise_check_frequency": "檢查頻率",
+ "apprise_check_frequency_desc": "系統檢查即將到期的保養的頻率(全域設定)",
+ "apprise_title_prefix": "訊息標題前置詞",
+ "apprise_title_prefix_desc": "新增到通知標題的前置詞(例如,“[Warracker]”將導致“[Warracker]保養即將到期”)",
+ "apprise_test_url": "測試URL(可選)",
+ "apprise_test_url_desc": "可選:僅用於傳送測試通知的URL(不會儲存到主設定中)",
+ "save_apprise_settings": "儲存Apprise設定",
+ "validate_urls": "驗證URL",
+ "send_expiration_notifications_now": "立即傳送到期通知",
+ "apprise_current_status": "目前狀態",
+ "apprise_urls_configured": "已設定的URL:",
+ "apprise_supported_services": "支援的服務",
+ "apprise_supported_services_desc": "Apprise支援80多種通知服務,包括:Discord、Slack、Telegram、電子郵件(Gmail、Outlook)、Webhooks、Microsoft Teams、Matrix、Pushover、Ntfy、Gotify等等。",
+ "view_full_list_of_supported_services": "檢視支援的服務的完整清單",
+ "ownership_management": "所有權管理",
+ "transfer_ownership": "轉移所有權",
+ "warning_title": "警告:",
+ "transfer_ownership_warning": "將應用程式所有權轉移給另一位管理員使用者。此操作不可逆。",
+ "transfer_ownership_desc": "所有權轉移後,您將成為普通管理員,新所有者將擁有對應用程式的最終控制權。",
+ "select_new_owner": "選擇新所有者(必須是管理員)",
+ "select_admin_user": "選擇管理員使用者...",
+ "transfer_ownership_button": "轉移所有權",
+ "transfer_ownership_irreversible": "此操作無法復原。",
+ "transfer_ownership_confirmation": "您即將將應用程式所有權轉移給",
+ "after_this_transfer": "此次轉移後:",
+ "transfer_ownership_consequence_1": "您將成為普通管理員",
+ "transfer_ownership_consequence_2": "新所有者將擁有對應用程式的最終控制權",
+ "transfer_ownership_consequence_3": "只有新所有者才能再次轉移所有權",
+ "transfer_ownership_type_to_confirm": "要確認,請在下面的欄位中輸入“TRANSFER”:"
+ },
+ "actions": {
+ "save": "儲存",
+ "cancel": "取消",
+ "delete": "刪除",
+ "edit": "編輯",
+ "export": "匯出",
+ "import": "匯入",
+ "refresh": "重新整理",
+ "search": "搜尋",
+ "clear": "清除",
+ "upload": "上傳",
+ "download": "下載",
+ "manage_tags": "管理標籤",
+ "close": "關閉",
+ "save_changes": "儲存變更"
+ },
+ "filters": {
+ "all_status": "所有狀態",
+ "all_tags": "所有標籤",
+ "all_vendors": "所有供應商",
+ "all_types": "所有類型",
+ "sort_by": "排序方式",
+ "sort_expiration": "到期日期",
+ "sort_purchase": "購買日期",
+ "sort_age": "年齡",
+ "sort_name": "產品名稱",
+ "sort_vendor": "供應商",
+ "sort_warranty_type": "保養類型",
+ "status": "狀態",
+ "tags": "標籤",
+ "vendor": "供應商",
+ "warranty_type": "保養類型",
+ "view": "檢視",
+ "scope": "範圍"
+ },
+ "messages": {
+ "success": "成功",
+ "error": "錯誤",
+ "warning": "警告",
+ "loading": "載入中...",
+ "saved": "變更已成功儲存",
+ "deleted": "項目已成功刪除",
+ "confirm_delete": "您確定要刪除此項目嗎?",
+ "no_results": "未找到結果",
+ "file_too_large": "檔案太大",
+ "invalid_file_type": "無效的檔案類型",
+ "fill_first_last_name": "請填寫名字和姓氏",
+ "email_cannot_be_empty": "電子郵件地址不能為空。",
+ "enter_valid_email": "請輸入有效的電子郵件地址。",
+ "profile_updated_successfully": "個人資料更新成功",
+ "preferences_saved_successfully": "偏好設定已成功儲存。",
+ "fill_password_fields": "請填寫所有密碼欄位",
+ "passwords_do_not_match": "新密碼不匹配",
+ "password_min_length": "密碼必須至少8個字符長",
+ "type_delete_to_confirm": "請輸入DELETE以確認",
+ "account_deleted_successfully": "帳戶已成功刪除",
+ "account_cannot_delete_offline": "離線模式下無法刪除帳戶",
+ "failed_delete_account": "刪除帳戶失敗。請重試。",
+ "user_updated_successfully": "用戶更新成功",
+ "user_deleted_successfully": "用戶刪除成功",
+ "user_id_missing": "用戶ID缺失",
+ "failed_load_users": "載入用戶失敗",
+ "error_loading_users": "載入用戶時出錯",
+ "select_user_transfer_ownership": "請選擇要轉移所有權的用戶",
+ "ownership_transferred_successfully": "所有權轉移成功!正在刷新頁面...",
+ "failed_load_site_settings": "載入網站設定失敗。請重試。",
+ "invalid_email_base_url": "無效的電子郵件基礎URL格式。應以http://或https://開頭",
+ "no_site_settings_to_save": "沒有網站設定需要儲存。",
+ "site_settings_saved_successfully": "網站設定儲存成功",
+ "failed_save_site_settings": "儲存網站設定失敗",
+ "oidc_settings_saved_successfully": "OIDC設定儲存成功。",
+ "failed_save_oidc_settings": "儲存OIDC設定失敗。",
+ "api_endpoint_accessible": "API端點可訪問",
+ "api_endpoint_not_accessible": "API端點不可訪問。狀態:",
+ "only_admins_send_notifications": "只有管理員可以發送保固通知",
+ "notifications_triggered_successfully": "通知觸發成功",
+ "notification_settings_saved_successfully": "通知設定儲存成功",
+ "apprise_settings_saved_successfully": "Apprise設定儲存成功",
+ "test_notification_sent_successfully": "測試通知發送成功",
+ "no_urls_to_validate": "沒有URL需要驗證",
+ "paperless_settings_saved_successfully": "Paperless-ngx設定儲存成功!",
+ "enter_valid_paperless_url": "請輸入有效的URL(例:https://paperless.yourdomain.com)",
+ "enter_paperless_url_first": "請先輸入Paperless-ngx URL",
+ "paperless_connection_test_successful": "Paperless-ngx連接測試成功!",
+ "paperless_connection_test_failed": "Paperless-ngx連接測試失敗",
+ "enter_api_token_test_connection": "請輸入API令牌以測試連接",
+ "failed_load_user_data": "載入用戶數據失敗。請重試。",
+ "could_not_connect_user_data": "無法連接以獲取用戶數據。顯示緩存信息。",
+ "preferences_saved_locally_failed_sync": "偏好設定已本地儲存,但與服務器同步失敗:",
+ "preferences_saved_locally": "偏好設定已本地儲存。",
+ "correct_errors_in_tab": "請在繼續之前更正突出顯示的分頁中的錯誤。",
+ "please_fill_out_this_field": "請填寫此欄位。",
+ "warranty_added_successfully": "保修已成功新增",
+ "tag_name_required": "標籤名稱是必需的",
+ "tag_creation_function_not_found": "未找到標籤創建功能",
+ "tag_created_successfully": "標籤創建成功",
+ "tag_updated_successfully": "標籤更新成功",
+ "tag_deleted_successfully": "標籤刪除成功",
+ "failed_to_create_tag": "創建標籤失敗",
+ "failed_to_update_tag": "更新標籤失敗",
+ "failed_to_delete_tag": "刪除標籤失敗"
+ },
+ "languages": {
+ "en": "English",
+ "fr": "Français",
+ "es": "Español",
+ "de": "Deutsch",
+ "it": "Italiano",
+ "cs": "Čeština",
+ "nl": "Nederlands",
+ "hi": "हिन्दी",
+ "fa": "فارسی",
+ "ar": "العربية",
+ "ru": "Русский",
+ "uk": "Українська",
+ "zh_CN": "简体中文",
+ "zh_HK": "繁體中文",
+ "ja": "日本語",
+ "pt": "Português",
+ "ko": "한국어"
+ },
+ "status": {
+ "title": "系統狀態",
+ "dashboard_title": "保養狀態儀表板",
+ "global_dashboard_title": "全域保養狀態儀表板",
+ "overview": "概觀",
+ "statistics": "統計",
+ "total_warranties": "總保養數",
+ "active_warranties": "有效保養",
+ "expiring_soon": "即將到期",
+ "expired_warranties": "已過期保養",
+ "warranty_distribution": "保養分佈",
+ "expiration_timeline": "到期時間軸",
+ "recent_activity": "最近活動",
+ "recent_expirations": "最近過期或即將到期",
+ "recent_expirations_empty": "沒有最近過期或即將到期的保養。",
+ "system_health": "系統健康",
+ "database_status": "資料庫狀態",
+ "connected": "已連線",
+ "version": "版本",
+ "uptime": "正常執行時間"
+ },
+ "about": {
+ "title": "關於Warracker",
+ "description": "一個全面的保養管理系統,旨在幫助您在一個安全、使用者友善的平台中追蹤、整理和管理所有產品保養。",
+ "version": "版本",
+ "update_status": "更新狀態",
+ "checking_updates": "正在檢查更新...",
+ "view_release_notes": "檢視發行說明",
+ "project_info": "專案資訊",
+ "project_description": "Warracker是一個使用現代Web技術建置的開源保養管理系統。它提供了一種安全直觀的方式來管理產品保養、追蹤到期日期和整理重要文件。",
+ "github_repository": "GitHub儲存庫",
+ "releases": "發行版",
+ "community_support": "社群與支援",
+ "community_description": "加入我們的社群以獲得支援、討論和更新。報告錯誤、請求功能或從其他使用者和貢獻者那裡獲得幫助。",
+ "discord_community": "Discord社群",
+ "report_issues": "報告問題",
+ "developer_info": "開發者資訊",
+ "developer_description": "Warracker由Sassanix開發和維護。該專案是開源的,歡迎社群的貢獻。",
+ "sassanix": "Sassanix",
+ "agpl_license": "AGPL-3.0授權",
+ "support_project": "支援專案",
+ "support_description": "如果您覺得Warracker有用,請考慮支援其開發!",
+ "new_version_available": "新版本{{version}}可用!",
+ "latest_version": "您正在使用最新版本",
+ "update_check_failed": "檢查更新失敗",
+ "features": "功能",
+ "feature_track": "追蹤產品保養",
+ "feature_notifications": "獲取到期通知",
+ "feature_documents": "儲存保養文件",
+ "feature_reports": "產生保養報告",
+ "feature_tags": "使用標籤整理",
+ "feature_export": "匯出保養資料",
+ "support": "支援",
+ "documentation": "文件",
+ "github": "GitHub儲存庫",
+ "license": "授權",
+ "copyright": "版權",
+ "developed_by": "開發者"
+ }
+}
diff --git a/nginx.conf b/nginx.conf
index b07097f..84da578 100644
--- a/nginx.conf
+++ b/nginx.conf
@@ -31,6 +31,17 @@ server {
image/svg+xml svg svgz;
application/pdf pdf;
image/x-icon ico;
+ application/json json;
+ application/manifest+json webmanifest manifest;
+ }
+
+ # Specific location for locales JSON files
+ location /locales/ {
+ alias /var/www/html/locales/;
+ try_files $uri =404;
+ add_header Content-Type "application/json; charset=utf-8";
+ add_header Cache-Control "no-cache, no-store, must-revalidate";
+ expires -1;
}
# API requests - proxy to backend (fixed upstream host)
@@ -46,6 +57,17 @@ server {
# Pass Authorization header to backend
proxy_set_header Authorization $http_authorization;
+ # Enhanced proxy settings for file handling
+ proxy_buffering off; # Disable buffering for file downloads to prevent content-length mismatches
+ proxy_request_buffering off; # Disable request buffering for uploads
+ proxy_read_timeout 300s; # Increased timeout for large file transfers
+ proxy_connect_timeout 30s;
+ proxy_send_timeout 300s;
+
+ # Prevent proxy from modifying response headers that could cause issues
+ proxy_set_header Connection "";
+ proxy_http_version 1.1;
+
# Add debug headers to see what's happening
add_header X-Debug-Message "API request proxied to backend" always;
@@ -86,6 +108,13 @@ server {
add_header Cache-Control "public, max-age=604800";
}
+ # Service Worker - no cache to ensure updates
+ location = /sw.js {
+ try_files $uri =404;
+ add_header Cache-Control "no-cache, no-store, must-revalidate";
+ expires -1;
+ }
+
# Static assets (CSS, JS, images)
location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg)$ {
try_files $uri =404;
@@ -98,6 +127,21 @@ server {
add_header Content-Type text/plain;
return 200 "Uploads directory exists: $document_root\n";
}
+
+ # Specific handling for manifest.json
+ location = /manifest.json {
+ alias /var/www/html/manifest.json; # Serve from this specific path
+ # The global types block should set the correct Content-Type
+ # (application/manifest+json for 'manifest' extension)
+ # If not found by alias, it will result in a 404, which is correct.
+ # No need for try_files here if alias is used and file must exist.
+ # If you want to be explicit about 404 if alias target doesn't exist:
+ # if (!-f /var/www/html/manifest.json) { return 404; }
+ # However, alias itself should handle this.
+ # Add caching headers if desired, e.g.:
+ # expires 1d;
+ # add_header Cache-Control "public, must-revalidate";
+ }
# Default location
location / {