Skip to content

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

Add collapsible warranty details, inline editing on Status page, vendor filter/sort; various fixes

sassanix92ffb07aa156
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5354ff9..5d8b7c6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,36 @@
# Changelog
+
+## [0.9.9.7] - 2025-05-16
+
+### Added
+- **Status Page - Collapsible Warranty Details**: Users can now click on a warranty row in the "Recently Expired or Expiring Soon" table on the Status page to expand a details section inline. This section displays more comprehensive information about the warranty, including Product URL, Purchase Price, Vendor, links to documents (Invoice, Manual, Other Files), Serial Numbers, and Notes.
+ - Clicking the same row again collapses the details view.
+ - Only one warranty's details can be expanded at a time.
+ _Files: `frontend/status.js`, `frontend/style.css`_
+- **Edit Warranty from Status Page**: You can now edit warranty details directly from the status page by clicking the "Edit Warranty" button in the expanded details section. This opens the edit modal with all warranty information pre-filled for editing.
+ _Files: `frontend/status.js`, `frontend/script.js`, `frontend/style.css`_
+- Added vendor column to sort options on the main warranty list.
+ _Files: `frontend/index.html`, `frontend/script.js`_
+- Added vendor filter dropdown to the main warranty list.
+ _Files: `frontend/index.html`, `frontend/script.js`_
+
+### Changed
+- **Status Page Table**: Modified the Status page table to no longer link product names directly to a separate details page (related to the collapsible details feature).
+ _Files: `frontend/status.js`_
+- Updated CSV export functionality to format dates as YYYY-MM-DD.
+ _Files: `frontend/script.js`, `frontend/status.js`_
+
+### Fixed
+- Fixed a console error "An invalid form control with name='product_url' is not focusable" that occurred when entering a product URL without a scheme (e.g., "example.com") in a hidden tab.
+ - Changed `productUrl` and `editProductUrl` input types from `url` to `text` in `frontend/index.html` to prevent premature browser validation conflicts with the tabbed interface.
+ - Enhanced `validateTab`, `showValidationErrors`, and `validateEditTab` in `frontend/script.js` to more reliably use HTML5 `control.validity.valid` and `control.validationMessage`, ensuring that if a field is invalid, its tab is shown and JavaScript-driven error messages are displayed.
+ _Files: `frontend/script.js`_
+- Resolved issue where the edit modal would close on backdrop click; it now only closes via the 'X' or 'Cancel' buttons.
+ _Files: `frontend/script.js`_
+- Resolved an issue where database migrations could fail if a custom `DB_NAME` was used. The hardcoded database name has been removed from migration files to support custom database names. (Thanks to @humrochagf for the contribution!)
+ _Files: `backend/migrations/010_configure_admin_roles.sql`, `backend/migrations/011_ensure_admin_permissions.sql`_
+
## [0.9.9.6] - 2025-05-11
### Added
@@ -298,546 +329,4 @@
- **Layout:** Updated `.panel-header` CSS to use Flexbox for aligning the title (`h2`) to the left and action buttons (`.panel-header-actions` containing Add Warranty and Refresh buttons) to the right (`frontend/style.css`).
- **Layout:** Removed the `border-bottom` style from the `.panel-header` / `.warranties-panel h2` for a cleaner look (`frontend/style.css`).
- **Branding:** Updated the website `<title>` to include "Warracker" (`frontend/index.html`).
-- **UI:** Added an "Add New Warranty" button (`#showAddWarrantyBtn`) to trigger the new modal (`frontend/index.html`).
-- **Branding:** Added a `<link>` tag to include a favicon (`/img/favicon.png`) in the website's `<head>` (`frontend/index.html`).
-- Site setting for configurable Email Base URL (Admin only).
-- Admins can now set the base URL used in password reset and notification emails via Settings > Admin Settings > Site Settings.
-
-### Changed
-- **UI:** Ensured header structure, styling, and interactive elements (user menu, settings/dark mode toggle) are consistent across `index.html`, `status.html`, `settings-new.html`, and the new `about.html`.
- - Refactored `about.html` to include standard header HTML and necessary CSS/JS files (`style.css`, `header-fix.css`, `auth.js`, `script.js`, `auth-new.js`, etc.).
- - Added inline script to `about.html` to explicitly initialize header JavaScript functions (`setupUIEventListeners`, `initializeTheme`) after DOM content loads.
-- **UI/UX:** Refactored the "Add New Warranty" form into a modal dialog (`#addWarrantyModal`) triggered by a button click, instead of being always visible on the main page (`frontend/index.html`, `frontend/script.js`, `frontend/style.css`).
- - The modal is initially hidden and displayed using JavaScript.
- - Added event listeners to show/hide the modal on button click, close button click, and backdrop click.
- - Implemented `resetAddWarrantyWizard` function to clear the form, reset tabs, tags, and file inputs when the modal is closed or submitted successfully.
- - Modified form submission (`submitForm`) to close and reset the modal upon success.
-- **UI:** Moved the "Add New Warranty" button (`#showAddWarrantyBtn`) from the top of the main content area into the header of the "Your Warranties" panel (`.panel-header`) for better context (`frontend/index.html`).
-- **Layout:** Adjusted the `.warranties-panel` CSS to span the full width (`grid-column: 1 / -1;`) after the form was moved out of the main grid flow (`frontend/style.css`).
-- **Layout:** Updated `.panel-header` CSS to use Flexbox for aligning the title (`h2`) to the left and action buttons (`.panel-header-actions` containing Add Warranty and Refresh buttons) to the right (`frontend/style.css`).
-- **Layout:** Removed the `border-bottom` style from the `.panel-header` / `.warranties-panel h2` for a cleaner look (`frontend/style.css`).
-- **Branding:** Updated the website `<title>` to include "Warracker" (`frontend/index.html`).
-- Password reset and warranty expiration emails now use the configured Email Base URL setting.
-- Changed "Registration Enabled" setting in Admin Settings to use a toggle switch for consistency.
-
-### Fixed
-- Fixed minor inconsistencies in settings page UI elements.
-- Resolved issues with file permissions for database operations.
-- Corrected CORS configuration to allow credentials.
-- Fixed notification preferences saving issue.
-- Ensured admin role permissions are correctly applied.
-- Resolved issue where editing a warranty to 'Lifetime' was failing due to validation errors and missing database columns (`updated_at`).
-
-### Added
-- Functionality to edit existing warranties to have a lifetime duration.
-
-# [0.9.9.0] - 2025-04-06
-
-### Fixed
-- **Tag Management:** Resolved issues with adding and deleting tags.
- - **Backend:** Added the missing `DELETE /api/tags/<tag_id>` API endpoint (`backend/app.py`) to handle tag deletion requests, including removing associations from the `warranty_tags` table.
- - **Frontend:** Corrected the `deleteTag` function (`frontend/script.js`) to use the `DELETE` method and the correct API endpoint.
- - **Frontend:** Improved UI feedback for tag operations:
- - The tag list in the "Manage Tags" modal now updates immediately after adding or deleting a tag (`renderExistingTags`).
- - The tag input fields in the modal are cleared after successfully adding a tag.
- - The tag filter dropdown on the main page updates after adding or deleting tags (`populateTagFilter`).
- - Selected tags display in the add/edit warranty forms update correctly after a tag is deleted (`renderSelectedTags`, `renderEditSelectedTags`).
- - Added loading spinners and improved toast notifications/error messages for tag creation and deletion.
-
-### Added
-- **Lifetime Warranty Support**
- - Added lifetime warranty option for both new and existing warranties
- - Implemented database migration to add `is_lifetime` column to warranties table
- - Added lifetime warranty checkbox in add/edit warranty forms
- - Modified warranty display to show "Lifetime" instead of expiration date for lifetime warranties
- - Enhanced warranty status handling to properly manage lifetime warranties
- - Updated statistics and expiring notifications to exclude lifetime warranties
- - Added dynamic form behaviour to hide warranty years input when lifetime is selected
-
-### Changed
-- **Backend API**
- - Modified warranty-related endpoints to handle lifetime warranty flag
- - Updated warranty validation to make warranty years optional for lifetime warranties
- - Enhanced warranty processing to handle lifetime warranties differently in statistics
- - Modified expiring warranty notifications to exclude lifetime warranties
- - Updated warranty retrieval to properly sort and display lifetime warranties
-
-### UI/UX Improvements
-- Added visual indicators for lifetime warranty status in all view modes (grid, list, table)
-- Enhanced form validation to handle lifetime warranty scenarios
-- Updated warranty summary view to clearly display lifetime warranty status
-- Improved warranty filtering to properly handle lifetime warranties
-- Corrected an issue where elements in Dark Mode had sharp corners instead of rounded ones like in Light Mode. Added the missing `--border-radius: 8px;` CSS variable to the `:root[data-theme="dark"]` definition in `frontend/style.css`.
-
-
-## [0.9.8.9] - 2025-04-03
-
-### Added
-- **Settings Page:** Added a new display section within the "Account Settings" card (`settings-new.html`) to show the current user's First Name, Last Name, and Email.
-
-### Changed
-- **Settings Page:** The new user information display now updates instantly when the user saves changes to their profile (First/Last Name) without requiring a page refresh (`settings-new.js`).
-- **Backend API:** Modified the `/api/auth/user` GET endpoint (`backend/app.py`) to query the database and return the full user profile, including `first_name` and `last_name`, instead of just the basic information available from the authentication token. This ensures the settings page can display the complete, up-to-date user details.
-- **Styling:** Added optional CSS rules (`settings-styles.css`) to style the new user information display area on the settings page.
-
-## [0.9.8.8] - 2025-04-03
-
-### Fixed
-- Resolved database error ("column updated_at does not exist") occurring when updating user profile (first/last name) or user preferences.
- - Modified SQL UPDATE statements in `backend/app.py` (within `update_profile` function and `/api/auth/preferences` endpoint) to remove references to the non-existent `updated_at` column in `users` and `user_preferences` tables.
-
-## [0.9.8.7] - 2025-04-03
-
-### Fixed
-- **Migration System Overhaul:** Refactored the database migration system for improved reliability and consistency.
- - Standardized on `backend/migrations/apply_migrations.py` for applying migrations.
- - Removed obsolete top-level `migrations/` directory and `backend/run_migrations.py` script.
- - Simplified `backend/init.sql` to only handle initial role alterations, removing table creation logic.
- - Corrected `docker-compose.yml` volume mounts and command to use the new migration path (`backend/migrations`).
- - Cleaned up `Dockerfile` by removing redundant migration script calls and ensuring correct migration directory copying.
- - Resolved conflicting `user_preferences` table creation by removing the SQL version and relying on the Python migration.
- - Renamed and renumbered all migration files sequentially (000 to 010) in `backend/migrations/` for clear execution order.
- - Added `000_create_warranties_table.sql` migration to ensure the base table exists before other migrations reference it.
- - Verified and ensured idempotency (`CREATE/ALTER ... IF NOT EXISTS`) for all migration scripts, preventing errors on re-runs.
- - Corrected `fix_permissions.py` execution by ensuring `fix_permissions.sql` is copied into the Docker image.
-
-## [0.9.8.6] - 2025-04-01
-
-### Added
- - Added tags to warranties, you can create and manage them
- - Choose different colours to tags
- - Search by tags
- - Added tags to the warranty cards
- - You can also edit current warranties to add tags
-
-### Changed
- - Removed docker and docker compose from making data/uploads
-
-### Current bugs with this release
-
- - Status page recently expired or expiring soon section will only work when a warranty is expiring.
- - Currently tags are for all users, if an admin creates a tag, it will show up for the users as well.
-
-
-## [0.9.8.5] - 2025-03-29
-
-### Changed
-- **Settings Page Improvements**
- - Separated email settings into their own section with a dedicated save button
- - Added independent saving functionality for email preferences
- - Improved user experience by making email settings management more intuitive
- - Enhanced feedback when saving email preferences
-
-## [0.9.8.4] - 2025-03-26
-
-
-- Fixed database migration system issues
- - Resolved issue with missing user_preferences table causing notification preference errors
- - Enhanced migration system to support both SQL and Python-based migrations
- - Added idempotent execution of SQL migrations with existence checks
- - Created improved migration tracking to prevent duplicate migration attempts
- - Updated Docker configuration for proper migration script execution
- - Fixed missing columns by adding timezone and expiring_soon_days columns
-
-
-## [0.9.8.3] - 2025-03-26
-
-### Added
-
-* **Authentication:** Users are now automatically logged in after successful registration, removing an extra step in the onboarding process.
-* **Notifications:** Introduced email notifications for warranty expiration alerts.
-* **Notifications:** Added user preferences to customize notification frequency (daily, weekly, monthly), preferred delivery time, and timezone.
-* **Admin:** Added controls for administrators to manually trigger notifications, useful for testing.
-
-### Changed
-
-* **Notifications:** Improved the reliability and processing efficiency of the backend notification system.
-* **UI:** Standardized the header's appearance and layout across all pages (home, status, settings) for a consistent look and feel.
-
-### Fixed
-
-* **Charts:** Resolved an issue where the status page timeline chart initially displayed incomplete data, requiring a theme toggle to show all months correctly. The chart now loads with complete data.
-* **Preferences:** Corrected an issue where preference changes made by an admin could unintentionally affect regular users' settings. Preferences are now stored separately based on user type.
-* **Preferences:** Fixed synchronization issues ensuring that view preferences set in the settings page are consistently applied throughout the application.
-* **File Access:** Resolved authentication errors ("Authentication token is missing!") that occurred when attempting to open attached invoice or manual files. Secure file access now correctly uses authentication tokens.
-* **File Uploads:** Corrected a critical bug where uploading only one document type (e.g., just an invoice) could inadvertently delete the existing document of the other type (e.g., the manual). Both documents are now preserved correctly during updates.
-
-
-## [0.9.8.2] - 2025-03-22
-
-- **Edit Warranty Modal Improvements**
- - Added tabbed interface for the edit warranty modal with three sections:
- - Product Info: Product name, URL, and serial numbers
- - Warranty Details: Purchase date, warranty period, and price
- - Documents: Invoice and manual uploads
-- Visual indicators for active tabs
-- Improved dark mode support for the edit modal
-- Better form organization and user experience
-
-
-## [0.9.8.1] - 2025-03-21
-
-
-- **UI Improvements**
- - **User Menu Refinement**
- - Removed the Profile button from the username dropdown menu
- - Simplified the user menu interface by removing unimplemented functionality
- - Improved user interface clarity by removing the "Profile page coming soon" placeholder
- - Updated all HTML templates (index.html, status.html, settings-new.html) for consistency
-
-- **Bug Fixes**
- - **Add Warranty Form Wizard**
- - Fixed issue where clicking the "Next" button sometimes skipped the "Documents" tab
- - Removed duplicate DOMContentLoaded event listeners in script.js to prevent multiple form initializations
- - Implemented clone-and-replace technique to ensure clean event listener attachment
- - Added comprehensive logging for tab navigation to assist future debugging
- - Enhanced form validation to ensure a smoother user experience
- - Improved error handling when navigating between form tabs
-
- - **Warranty Filtering**
- - Fixed "ReferenceError: applyFilters is not defined" error in script.js
- - Added missing applyFilters function that was referenced but not implemented
- - Restored filter functionality for the warranty list on the main page
- - Enhanced console logging to provide better debugging information
-
-- **Upload Size Increase**
- - Increased maximum file upload size from 16MB to 32MB for invoices and manuals
- - Updated `MAX_CONTENT_LENGTH` in Flask configuration from 16MB to 32MB
- - Added `client_max_body_size 32M` directive to Nginx configuration
- - Enhanced fallback Nginx configuration in Dockerfile with upload size limits
- - Added frontend validation to prevent oversized file uploads
- - Improved error handling for 413 Request Entity Too Large errors
- - Added detailed error messages with file size information
-
-- **UI Consistency Improvements**
- - **Settings Page Header**
- - Fixed settings page header to match the structure and appearance of the home page
- - Standardized navigation menu appearance across all application pages
- - Removed duplicate settings container from the header for cleaner UI
- - Added proper "active" class to the current page in the navigation menu
- - **JavaScript Enhancements**
- - Improved error handling in settings-new.js with proper null checking
- - Enhanced preferences saving functionality with graceful fallbacks
- - Fixed dark mode toggle to work without the header settings container
- - Prevented console errors when UI elements were changed or removed
-
-## [0.9.8.0] - 2025-03-21
-
-- **Feature Added**
- - **Expiring Soon Preferences:** Number of days before warranty expiration to mark as "Expiring Soon" now added to the settings page.
-
-- **UI Improvements**
- - **Cleanup**
- - Removed test-related buttons from the settings gear menu in index.html and status.html
- - Kept only the Test API button in the Admin section of settings page
- - Removed redundant "Old Settings" link from settings page gear menu
- - **General Refinements**
- - Streamlined user interface by removing development/testing elements
- - Improved overall UI professionalism and user experience
-
-- **Bug Fixes**
- - **Expiring Soon Preferences**
- - Fixed issue where "expiring soon" preference set in settings didn't affect warranty status on the main dashboard
- - Resolved inconsistency between token key names (`authToken` vs `auth_token`) causing authorization failures
- - Improved preferences loading in `script.js` to properly await API responses
- - Enhanced initialization sequence to ensure preferences are loaded before processing warranties
- - Implemented real-time reprocessing of warranties when preferences change
- - Added detailed logging to track preference values during warranty processing
- - Updated DOM initialization to avoid duplicate warranty loading
- - **Status Filter in Dashboard**
- - Fixed issue where status dropdown filter on status page showed "No warranties match your search criteria" when selecting specific statuses
- - Modified dashboard to fetch complete warranty data for comprehensive filtering instead of only using pre-filtered recent warranties
- - Added null checks and fallback values to prevent errors with incomplete warranty data
- - Enhanced filtering logic to properly handle all warranty status types
- - Fixed sort header click handler to use the correct data attribute
- - Improved error handling and feedback messages when no warranties match filter criteria
-
-## [0.9.7.9] - 2025-03-21
-
- - **API Security Improvements**
- - Fixed "Authentication attempt without token" warnings in logs
- - Updated Dockerfile health check to use root URL instead of protected API endpoint
- - Modified test-api.js to include authentication tokens with requests
-
-## [0.9.7.8] - 2025-03-20
-
-- **Security Enhancements**
- - **Secure File Access System**
- - Implemented comprehensive security controls for uploaded files (invoices, manuals)
- - Added two secure file serving endpoints with authentication and authorization
- - Created client-side utility functions for secure file handling
- - Blocked direct access to the uploads directory via nginx configuration
- - Added ownership verification to ensure users can only access their own files
- - Implemented protection against path traversal attacks
- - Enhanced logging for all file access attempts
- - **Frontend Security Integration**
- - Created new file-utils.js with secureFilePath and openSecureFile functions
- - Updated all file links to use secure handling methods
- - Added proper authentication token handling for file downloads
-
-## [0.9.7.7] - 2025-03-15
-- **Fixes**
- - Status of warranties are now centred in list view
-
-## [0.9.7.5] - 2025-03-14
-- **Fixes**
- - Removed remember me
- - Fixed admin settings, admins can now remove users
- - Admins can now disable registrations
-
-
-## [0.9.7] - 2025-03-13
-
-- **Authentication Enhancements**
- - Added "Remember Me" functionality to the login page, allowing users to stay logged in across sessions.
- - Implemented auto-login feature that checks for a valid session cookie and automatically logs in users if they have opted for "Remember Me".
- - Updated the login endpoint to accept a `remember_me` parameter and set a persistent session cookie when checked.
- - Created a new `/api/auth/auto-login` endpoint to handle auto-login requests.
-
-- **User Management Improvements**
- - Enhanced user registration process to validate email format and password strength.
- - Added functionality to check if registration is enabled or disabled via the `/api/auth/registration-status` endpoint.
- - Implemented user profile update functionality, allowing users to change their first and last names.
- - Added admin-only endpoints for managing user accounts, including viewing, updating, and deleting users.
- - **User Deletion Functionality**
- - Enhanced modal functionality for user deletion, including improved error checking and logging.
- - Improved `deleteUser` function with better error handling and user ID retrieval.
- - Added support for handling both numeric IDs and usernames in the deletion process.
- - Created diagnostic functions to test modal functionality and user deletion processes.
- - Improved event handling for user-related actions, ensuring proper setup of event listeners.
-
-- **Admin Management**
- - View Users: Admins can view a list of all registered users, including their details such as usernames, email addresses, and account statuses.
- - Delete User Accounts: Admins have the ability to delete user accounts, removing them from the system entirely.
- - Monitor System Health: Admins can check the health of the application and server, ensuring that everything is running smoothly.
-
-- **Settings Page Updates**
- - Created a settings page for users to manage their preferences, including email notifications and default view settings.
- - Implemented backend support for retrieving and updating user preferences via the `/api/auth/preferences` endpoint.
- - Added validation for user preferences to ensure only valid values are accepted.
-
-- **Database Enhancements**
- - Updated database schema to include user sessions and password reset tokens for improved security and functionality.
- - Added indexes to improve query performance for user and warranty data.
- - Implemented error handling and logging for database operations to facilitate easier debugging and maintenance.
-
-- **UI/UX Improvements**
- - Enhanced the login form with a "Remember Me" checkbox and improved styling for better user experience.
- - Added loading indicators and toast notifications for better feedback during authentication processes.
- - Improved the overall layout and design of the settings and authentication pages for a more cohesive look.
- - Added a "Show Users List" button to the admin controls for easy access to user management.
-
-- **Security Enhancements**
- - Implemented secure cookie handling for session tokens to prevent XSS attacks.
- - Added validation checks for user input to prevent SQL injection and other common vulnerabilities.
- - Ensured that sensitive operations are protected by authentication and authorization checks.
-
-- **What's not working**
- - The menu still needs work done, the gear icon is not consistent
- - When putting in the wrong password, you will need to refresh the page and try again manually.
- - Email notification still doesn't work
- - Users can't delete their own account, but admins can
-
-
-## [0.5.2] - 2025-03-09
-
-### Changed
-- Enhanced user interface consistency and dark mode support
- - Fixed alignment issues between search field and status dropdown
- - Improved empty state display in both light and dark modes
- - Standardized padding and sizing for search and filter controls
- - Better vertical alignment of form controls in table header
-
-### Fixed
-- Proper centering of "No warranties" message in the dashboard table
- - Implemented responsive overlay for empty state messages
- - Fixed background colors in dark mode for empty state displays
- - Ensured consistent text color across all themes
- - Improved mobile responsiveness for empty state messages
-
-## [0.5.1] - 2025-03-08
-
-### Changed
-- Improved warranty status display
- - Status information now consistently displayed at the bottom of warranty cards
- - Better visual hierarchy with status as the last item before document links
- - Enhanced color-coding for different status types (active, expiring, expired)
- - Consistent status positioning across all view types (grid, list, table)
-
-### Fixed
-- Table view layout and display issues
- - Fixed product names being truncated in table view
- - Improved column width distribution for better content display
- - Prevented document links from overflowing their container
- - Enhanced mobile responsiveness for table view
- - Better alignment of table headers with content
- - Improved styling of links in table view for better readability
- - Fixed vertical stacking of document links on smaller screens
-
-
-## [0.5.0] - 2025-03-07
-
-### Added
-- Enhanced filtering and sorting capabilities
- - Status filter (All, Active, Expiring Soon, Expired)
- - Multiple sorting options (Expiration Date, Purchase Date, Name)
- - Export filtered warranties as CSV
- - Improved filter controls layout
- - Mobile-responsive filter design
-- Multiple view options for warranty display
- - Grid view with card layout (default)
- - List view for compact horizontal display
- - Table view for structured data presentation
- - View preference saved between sessions
- - Responsive design for all view types
-- Optional purchase price tracking
- - Users can now add purchase prices to warranties
- - Price information displayed in warranty cards
- - Currency formatting with dollar sign
- - Included in warranty summary and exports
-
-### Changed
-- Completely redesigned user interface
- - Modern card-based layout for warranties
- - Enhanced filter controls with improved styling
- - Better visual hierarchy with labeled filter groups
- - Custom dropdown styling with intuitive icons
- - Improved spacing and alignment throughout
- - Consistent color scheme and visual feedback
- - Responsive grid layout for warranty cards
-
-### Fixed
-- Status indicator borders now correctly displayed for all warranty states
- - Green border for active warranties
- - Orange border for warranties expiring soon
- - Red border for expired warranties
-- Consistent status styling across all warranty cards
-- Form now resets to first tab after successful warranty submission
-- Manual filename now properly cleared when form is reset
-
-## [0.4.0] - 2025-03-07
-
-### Added
-- Improved warranty creation process
- - Multi-step form with intuitive navigation
- - Progress indicator showing completion status
- - Enhanced validation with clear error messages
- - Summary review step before submission
- - Expiration date preview in summary
- - Responsive design for all device sizes
-
-### Fixed
-- Progress indicator alignment issue in multi-step form
- - Contained indicator within form boundaries
- - Prevented overflow with improved CSS approach
- - Ensured consistent tab widths for better alignment
-- Improved tab navigation visual feedback
-
-## [0.3.0] - 2025-03-07
-
-### Added
-- Product manual upload support
- - Users can now upload a second document for product manuals
- - Manual documents are displayed alongside invoices in the warranty details
- - Both add and edit forms support manual uploads
-- Product URL support
- - Users can now add website URLs for products
- - Links to product websites displayed in warranty cards
- - Easy access to product support and information pages
-
-### Changed
-- Improved document link styling for consistency
- - Enhanced visual appearance of document links
- - Consistent styling between invoice and manual links
- - Better hover effects for document links
- - Fixed styling inconsistencies between document links
-- Improved warranty card layout
- - Document links now displayed side by side for better space utilization
- - Responsive design adapts to different screen sizes
- - More compact and organized appearance
-
-### Fixed
-- Styling inconsistency between View Invoice and View Manual buttons
-- Removed unused CSS file to prevent styling conflicts
-
-## [0.2.5-beta] - 2025-03-07
-
-### Added
-- Product manual upload support
- - Users can now upload a second document for product manuals
- - Manual documents are displayed alongside invoices in the warranty details
- - Both add and edit forms support manual uploads
-
-### Changed
-- Improved document link styling for consistency
- - Enhanced visual appearance of document links
- - Consistent styling between invoice and manual links
- - Better hover effects for document links
- - Fixed styling inconsistencies between document links
-
-### Fixed
-- Styling inconsistency between View Invoice and View Manual buttons
-- Removed unused CSS file to prevent styling conflicts
-
-
-## [0.2.0-beta] - 2025-03-06
-
-### Added
-- Export functionality for warranty data as CSV
-- Refresh button for manual data updates
-- Search and filtering options for warranty list
-- Enhanced mobile responsiveness
-
-### Changed
-- Removed Debug Information panel from status page
-- Improved error handling and data validation across all dashboard functions
-- Enhanced chart creation with support for various data formats
-- Streamlined user interface by removing development elements
-- Improved data normalization for warranty information
-- Added fallback mechanisms for missing or invalid data
-- Updated status chart calculations for better accuracy
-
-### Fixed
-- API connection error handling
-- Chart instance memory leaks
-- Invalid data structure handling from API responses
-- Negative value calculations in status charts
-
-[0.2.0-beta]: [https://github.com/username/warracker/releases/tag/v0.05.2-beta](https://github.com/sassanix/Warracker/releases/tag/0.2.0)
-
-## [0.1.0] - New Features and enhancements
-
-### Added
-- Basic warranty tracking functionality
-- Dashboard with warranty statistics
-- Timeline visualization
-- Status overview chart
-- Recent expirations list
-
-## [0.05.2-beta] - 2025-03-05
-
-### Added
-- Multiple serial numbers support for warranties
- - Users can now add multiple serial numbers per warranty item
- - Dynamic form fields for adding/removing serial numbers
- - Database schema updated to support multiple serial numbers
-
-### Changed
-- Enhanced warranty management interface
- - Improved form handling for serial numbers
- - Better organization of warranty details
-- Optimized database queries with new indexes
- - Added index for serial numbers lookup
- - Added index for warranty ID relationships
-
-### Technical
-- Database schema improvements
- - New `serial_numbers` table with proper foreign key constraints
- - Added indexes for better query performance
- - Implemented cascading deletes for warranty-serial number relationships
-
-### Fixed
-- Form validation and handling for multiple serial numbers
-- Database connection management and resource cleanup
-
-[0.05.2-beta]: https://github.com/username/warracker/releases/tag/v0.05.2-beta
+- **UI:** Added an "Add New Warranty" button (`#showAddWarrantyBtn`) to trigger the new modal (`frontend/index.html`
\ No newline at end of file
diff --git a/README.md b/README.md
index 335255e..646ec3c 100644
--- a/README.md
+++ b/README.md
@@ -174,7 +174,7 @@ To get the docker compose file please go [here](https://github.com/sassanix/Warr
### Adding a Warranty
-1. Fill in the product details on the left panel.
+1. Fill in the product details by clicking on add warranty.
2. Enter the purchase date and warranty duration.
3. Optionally upload receipt/documentation.
4. Click the "Add Warranty" button.
diff --git a/backend/app.py b/backend/app.py
index ff5fc75..47728a8 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -1517,7 +1517,7 @@ def get_statistics():
SELECT
id, product_name, purchase_date,
warranty_duration_years, warranty_duration_months, warranty_duration_days,
- expiration_date, invoice_path, manual_path, product_url, purchase_price, is_lifetime
+ 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
@@ -1549,7 +1549,7 @@ def get_statistics():
SELECT
id, product_name, purchase_date,
warranty_duration_years, warranty_duration_months, warranty_duration_days,
- expiration_date, invoice_path, manual_path, product_url, purchase_price, is_lifetime
+ expiration_date, invoice_path, manual_path, other_document_path, product_url, purchase_price, is_lifetime
{from_clause}
{where_clause}
ORDER BY expiration_date DESC
@@ -3064,14 +3064,14 @@ def debug_warranty(warranty_id):
# 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, product_url, notes,
+ 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, product_url, notes,
+ 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
@@ -3099,6 +3099,17 @@ def debug_warranty(warranty_id):
'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,
diff --git a/frontend/about.html b/frontend/about.html
index 58131c6..03586d2 100644
--- a/frontend/about.html
+++ b/frontend/about.html
@@ -106,7 +106,7 @@
<div class="about-container" style="background-color: var(--card-bg); color: var(--text-color); padding: 20px; border-radius: 8px; margin-top: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); width: 100%; box-sizing: border-box;">
<h1 style="color: var(--primary-color); margin-bottom: 20px;">About Warracker</h1>
- <p><strong>Version:</strong> v0.9.9.6</p>
+ <p><strong>Version:</strong> v0.9.9.7</p>
<div id="versionTracker" style="margin-bottom: 20px;">
<p><strong>Update Status:</strong> <span id="updateStatus">Checking for updates...</span></p>
diff --git a/frontend/index.html b/frontend/index.html
index bfdd895..89e4356 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -202,12 +202,21 @@
</select>
</div>
+ <div class="filter-group">
+ <label class="filter-label">Vendor</label>
+ <select id="vendorFilter" class="filter-select">
+ <option value="all">All Vendors</option>
+ <!-- Vendor options will be populated by JavaScript -->
+ </select>
+ </div>
+
<div class="filter-group">
<label class="filter-label">Sort By</label>
<select id="sortBy" class="filter-select">
<option value="expiration">Expiration Date</option>
<option value="purchase">Purchase Date</option>
<option value="name">Product Name</option>
+ <option value="vendor">Vendor</option>
</select>
</div>
@@ -289,7 +298,7 @@
<div class="form-group">
<label for="productUrl">Product URL (Optional)</label>
- <input type="url" id="productUrl" name="product_url" class="form-control" placeholder="https://example.com/product">
+ <input type="text" id="productUrl" name="product_url" class="form-control" placeholder="https://example.com/product">
</div>
<div class="form-group">
@@ -533,7 +542,7 @@
<div class="form-group">
<label for="editProductUrl">Product URL (Optional)</label>
- <input type="url" id="editProductUrl" name="product_url" class="form-control" placeholder="https://example.com/product">
+ <input type="text" id="editProductUrl" name="product_url" class="form-control" placeholder="https://example.com/product">
</div>
<div class="form-group">
diff --git a/frontend/script.js b/frontend/script.js
index 907a43b..27f38d2 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -12,7 +12,8 @@ let currentFilters = {
status: 'all',
tag: 'all',
search: '',
- sortBy: 'expiration'
+ sortBy: 'expiration',
+ vendor: 'all' // Added vendor filter
};
// Tag related variables
@@ -33,6 +34,7 @@ const searchInput = document.getElementById('searchWarranties');
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 exportBtn = document.getElementById('exportBtn');
const gridViewBtn = document.getElementById('gridViewBtn');
const listViewBtn = document.getElementById('listViewBtn');
@@ -132,54 +134,73 @@ document.addEventListener('DOMContentLoaded', function() {
console.log('[DEBUG] Registering authStateReady event handler');
// ... other initialization ...
- // REMOVE call to undefined checkLoginStatus - Handled by auth.js
- // checkLoginStatus();
+ // --- BEGIN REFACTORED TAG MODAL AND MAIN FORM TAG UI SETUP ---
+ const globalTagManagementModal = document.getElementById('tagManagementModal');
+ const globalNewTagForm = document.getElementById('newTagForm'); // Inside tagManagementModal
+ const mainTagSearchInput = document.getElementById('tagSearch'); // For the main "Add Warranty" form's tag search
+ const warrantyFormElement = document.getElementById('warrantyForm'); // The main add warranty form
+
+ // 1. ALWAYS Initialize listeners for the global Tag Management Modal IF IT EXISTS
+ if (globalTagManagementModal) {
+ if (globalNewTagForm) {
+ // Ensure the event listener is attached only once, or manage it if DOMContentLoaded could fire multiple times (not typical)
+ // For simplicity, assuming DOMContentLoaded runs once per page load.
+ globalNewTagForm.addEventListener('submit', (e) => {
+ e.preventDefault();
+ createNewTag();
+ });
+ }
- // --- DEFERRED WARRANTY LOADING ---
- // Don't load warranties immediately. Wait for authentication.
- // if (document.getElementById('warrantiesList')) {
- // loadWarranties(); // <<< OLD CALL - REMOVED
- // }
- // --- END DEFERRED WARRANTY LOADING ---
+ const closeButtons = globalTagManagementModal.querySelectorAll('[data-dismiss="modal"]');
+ closeButtons.forEach(button => {
+ button.addEventListener('click', (event) => {
+ globalTagManagementModal.style.display = 'none';
+ event.stopPropagation(); // This was the fix from before, ensuring it's applied
+ });
+ });
+ console.log('Global Tag Management Modal listeners initialized directly in DOMContentLoaded.');
+ }
- // Setup form submission (assuming addWarrantyForm exists)
- const form = document.getElementById('addWarrantyForm');
- if (form) {
- form.addEventListener('submit', handleFormSubmit);
+ // 2. Initialize Tag functionality FOR THE MAIN ADD WARRANTY FORM (if its specific tag search input exists)
+ // initTagFunctionality is now refactored to be specific to the main form's tag UI.
+ if (mainTagSearchInput) {
+ initTagFunctionality(); // Sets up main form tag search, its manage button, etc.
+ // Also calls loadTags() if needed for the main form.
+ }
+ // --- END REFACTORED TAG MODAL AND MAIN FORM TAG UI SETUP ---
+
+
+ // Setup form submission (assuming addWarrantyForm exists - this is 'warrantyFormElement')
+ // const form = document.getElementById('addWarrantyForm'); // Old selector
+ if (warrantyFormElement) { // Use the variable defined above
+ warrantyFormElement.addEventListener('submit', handleFormSubmit);
// Initialize form tabs if the form exists
- initFormTabs();
+ // initFormTabs(); // This should be called when the ADD MODAL is SHOWN, not globally here.
+ // It's correctly in setupModalTriggers for the addWarrantyModal.
}
- // REMOVED setupSettingsMenu - Handled by auth.js
- // setupSettingsMenu();
// Initialize theme toggle state *after* DOM is loaded
- // ... (theme toggle init logic) ...
+ // ... (theme toggle init logic remains) ...
// Setup view switcher (assuming view switcher elements exist)
if (document.getElementById('gridViewBtn')) {
// setupViewSwitcher(); // Removed undefined function
- loadViewPreference();
+ loadViewPreference(); // This is fine here, loads initial view preference.
}
// Setup filter controls (assuming filter controls exist)
if (document.getElementById('filterControls')) {
// setupFilterControls(); // Removed: function not defined
- populateTagFilter();
+ // populateTagFilter(); // This should be called AFTER warranties (and their tags) are loaded.
+ // It's called in loadWarranties -> processAllWarranties or similar flow.
}
- // Initialize modal interactions
- // initializeModals(); // Removed: function not defined, handled by setupModalTriggers
- setupModalTriggers();
-
- // Initialize Tag functionality (assuming tag elements exist)
- if (document.getElementById('tagSearch')) { // Check for tagSearch instead of non-existent tagSearchInput
- initTagFunctionality();
- loadTags();
- }
+ // Initialize modal interactions (general modal triggers like close buttons, backdrop)
+ setupModalTriggers(); // This sets up general modal behaviors and specific triggers for add/edit.
- // Initialize form-specific lifetime checkbox handler
- const lifetimeCheckbox = document.getElementById('isLifetime');
+ // Initialize form-specific lifetime checkbox handler FOR THE MAIN ADD FORM
+ const lifetimeCheckbox = document.getElementById('isLifetime'); // Main form's checkbox
if (lifetimeCheckbox) {
lifetimeCheckbox.addEventListener('change', handleLifetimeChange);
handleLifetimeChange({ target: lifetimeCheckbox }); // Initial check
@@ -200,6 +221,7 @@ document.addEventListener('DOMContentLoaded', function() {
// Load preferences
await loadAndApplyUserPreferences();
+ await loadTags(); // Ensure all available tags are loaded after authentication
// Load warranty data (fetches, processes, populates global array)
if (document.getElementById('warrantiesList')) {
@@ -520,49 +542,61 @@ function updateCompletedTabs() {
// Validate a specific tab
function validateTab(tabIndex) {
const tabContent = tabContents[tabIndex];
- const requiredInputs = tabContent.querySelectorAll('input[required]');
-
- // If there are no required inputs in this tab, it's automatically valid
- if (requiredInputs.length === 0) {
- return true;
- }
-
- let isValid = true;
-
- requiredInputs.forEach(input => {
- if (!input.value.trim()) {
- isValid = false;
- input.classList.add('invalid');
+ // 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) {
+ isTabValid = false;
+ control.classList.add('invalid');
+ // Ensure a validation message placeholder exists or is updated by showValidationErrors
} else {
- input.classList.remove('invalid');
+ 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 isValid;
+ return isTabValid;
}
// Show validation errors for a specific tab
function showValidationErrors(tabIndex) {
const tabContent = tabContents[tabIndex];
- const requiredInputs = tabContent.querySelectorAll('input[required]');
-
- requiredInputs.forEach(input => {
- if (!input.value.trim()) {
- input.classList.add('invalid');
-
- // Add validation message if not already present
- let validationMessage = input.nextElementSibling;
- if (!validationMessage || !validationMessage.classList.contains('validation-message')) {
- validationMessage = document.createElement('div');
- validationMessage.className = 'validation-message';
- validationMessage.textContent = 'This field is required';
- input.parentNode.insertBefore(validationMessage, input.nextSibling);
+ const controls = tabContent.querySelectorAll('input, textarea, select');
+ let firstInvalidControl = null;
+
+ controls.forEach(control => {
+ if (!control.validity.valid) {
+ if (!firstInvalidControl) firstInvalidControl = control;
+ control.classList.add('invalid');
+
+ // Add or update validation message
+ let validationMessageElement = control.nextElementSibling;
+ if (!validationMessageElement || !validationMessageElement.classList.contains('validation-message')) {
+ validationMessageElement = document.createElement('div');
+ validationMessageElement.className = 'validation-message';
+ control.parentNode.insertBefore(validationMessageElement, control.nextSibling);
+ }
+ validationMessageElement.textContent = control.validationMessage || 'This field is invalid.';
+ } else {
+ // Ensure invalid class is removed if somehow missed by validateTab (shouldn't happen)
+ control.classList.remove('invalid');
+ // Remove validation message if control is now valid
+ let validationMessageElement = control.nextElementSibling;
+ if (validationMessageElement && validationMessageElement.classList.contains('validation-message')) {
+ validationMessageElement.remove();
}
}
});
-
- // Show toast message
- showToast('Please fill in all required fields', 'error');
+
+ // 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');
}
// Update summary tab with current form values
@@ -796,12 +830,12 @@ async function exportWarranties() {
// Format row data - Updated for duration components
const row = [
warranty.product_name || '',
- formatDate(new Date(warranty.purchase_date)),
+ formatDateYYYYMMDD(new Date(warranty.purchase_date)),
warranty.is_lifetime ? 'TRUE' : 'FALSE',
warranty.warranty_duration_years || 0,
warranty.warranty_duration_months || 0,
warranty.warranty_duration_days || 0,
- warranty.is_lifetime ? '' : formatDate(new Date(warranty.expiration_date)), // Expiration date empty for lifetime
+ warranty.is_lifetime ? '' : formatDateYYYYMMDD(new Date(warranty.expiration_date)), // Expiration date empty for lifetime
warranty.status || '',
warranty.purchase_price || '',
serialNumbers,
@@ -1308,6 +1342,7 @@ async function loadWarranties() {
// Populate tag filter dropdown with tags from warranties
populateTagFilter();
+ populateVendorFilter(); // Added call to populate vendor filter
// REMOVED: applyFilters(); // Now called from authStateReady after data and prefs are loaded
}
@@ -1369,10 +1404,31 @@ function formatDate(date) {
}
}
+function formatDateYYYYMMDD(date) {
+ if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
+ return 'N/A';
+ }
+
+ const year = date.getUTCFullYear();
+ const month = String(date.getUTCMonth() + 1).padStart(2, '0');
+ const day = String(date.getUTCDate()).padStart(2, '0');
+
+ return `${year}-${month}-${day}`;
+}
+
async function renderWarranties(warrantiesToRender) {
console.log('renderWarranties called with:', warrantiesToRender);
+
+ // Guard clause: If the main warrantiesList element doesn't exist on the current page, exit.
+ // This can happen if saveWarranty -> applyFilters -> renderWarranties is called from a page
+ // that doesn't have the main list view (e.g., the status page).
+ if (!warrantiesList) {
+ console.warn('renderWarranties: warrantiesList element not found. Aborting render. This might be normal if not on the main warranties page.');
+ return;
+ }
+
if (!warrantiesToRender || warrantiesToRender.length === 0) {
- renderEmptyState();
+ renderEmptyState(); // renderEmptyState should also check for warrantiesList or its specific container
return;
}
@@ -1385,9 +1441,11 @@ async function renderWarranties(warrantiesToRender) {
const sortedWarranties = [...warrantiesToRender].sort((a, b) => {
switch (currentFilters.sortBy) {
case 'name':
- return a.product_name.localeCompare(b.product_name);
+ 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 'vendor': // Added vendor sorting
+ return (a.vendor || '').toLowerCase().localeCompare((b.vendor || '').toLowerCase());
case 'expiration':
default:
const dateA = new Date(a.expiration_date || 0);
@@ -1735,6 +1793,11 @@ function applyFilters() {
return false;
}
}
+
+ // Vendor filter
+ if (currentFilters.vendor !== 'all' && (warranty.vendor || '').toLowerCase() !== currentFilters.vendor.toLowerCase()) {
+ return false;
+ }
// Search filter
if (currentFilters.search) {
@@ -1784,18 +1847,25 @@ function openEditModal(warranty) {
// Clear existing serial number inputs
const editSerialNumbersContainer = document.getElementById('editSerialNumbersContainer');
editSerialNumbersContainer.innerHTML = '';
-
+
+ // Normalize serial_numbers to array of strings if needed
+ if (Array.isArray(warranty.serial_numbers) && warranty.serial_numbers.length > 0 && typeof warranty.serial_numbers[0] === 'object') {
+ warranty.serial_numbers = warranty.serial_numbers
+ .map(snObj => snObj && snObj.serial_number)
+ .filter(sn => typeof sn === 'string' && sn.trim() !== '');
+ }
+
// Add event listener for adding new serial number inputs in edit modal
editSerialNumbersContainer.addEventListener('click', (e) => {
if (e.target.closest('.add-serial-number')) {
addSerialNumberInput(editSerialNumbersContainer);
}
});
-
+
const validSerialNumbers = Array.isArray(warranty.serial_numbers)
? warranty.serial_numbers.filter(sn => sn && typeof sn === 'string' && sn.trim() !== '')
: [];
-
+
if (validSerialNumbers.length === 0) {
// Add a single empty input if there are no serial numbers
addSerialNumberInput(editSerialNumbersContainer);
@@ -1809,15 +1879,15 @@ function openEditModal(warranty) {
<i class="fas fa-plus"></i> Add Another
</button>
`;
-
+
// Add event listener for the Add button
firstInput.querySelector('.add-serial-number').addEventListener('click', function(e) {
e.stopPropagation(); // Stop event from bubbling up
addSerialNumberInput(editSerialNumbersContainer);
});
-
+
editSerialNumbersContainer.appendChild(firstInput);
-
+
// Add the rest of the serial numbers with "Remove" buttons
for (let i = 1; i < validSerialNumbers.length; i++) {
const newInput = document.createElement('div');
@@ -1828,12 +1898,12 @@ function openEditModal(warranty) {
<i class="fas fa-minus"></i> Remove
</button>
`;
-
+
// Add remove button functionality
newInput.querySelector('.remove-serial-number').addEventListener('click', function() {
this.parentElement.remove();
});
-
+
editSerialNumbersContainer.appendChild(newInput);
}
}
@@ -1846,7 +1916,7 @@ function openEditModal(warranty) {
currentInvoiceElement.innerHTML = `
<span class="text-success">
<i class="fas fa-check-circle"></i> Current invoice:
- <a href="#" onclick="openSecureFile('${warranty.invoice_path}'); return false;">View</a>
+ <a href="#" class="view-document-link" onclick="openSecureFile('${warranty.invoice_path}'); return false;">View</a>
(Upload a new file to replace)
</span>
`;
@@ -1871,7 +1941,7 @@ function openEditModal(warranty) {
currentManualElement.innerHTML = `
<span class="text-success">
<i class="fas fa-check-circle"></i> Current manual:
- <a href="#" onclick="openSecureFile('${warranty.manual_path}'); return false;">View</a>
+ <a href="#" class="view-document-link" onclick="openSecureFile('${warranty.manual_path}'); return false;">View</a>
(Upload a new file to replace)
</span>
`;
@@ -1897,7 +1967,7 @@ function openEditModal(warranty) {
currentOtherDocumentElement.innerHTML = `
<span class="text-success">
<i class="fas fa-check-circle"></i> Current other document:
- <a href="#" onclick="openSecureFile('${warranty.other_document_path}'); return false;">View</a>
+ <a href="#" class="view-document-link" onclick="openSecureFile('${warranty.other_document_path}'); return false;">View</a>
(Upload a new file to replace)
</span>
`;
@@ -2144,6 +2214,18 @@ function handleFormSubmit(event) { // Renamed from submitForm
// Create form data object
const formData = new FormData(warrantyForm);
+ // Product URL handling
+ let productUrlValue = formData.get('product_url');
+ if (productUrlValue && typeof productUrlValue === 'string') {
+ productUrlValue = productUrlValue.trim();
+ if (productUrlValue && !productUrlValue.startsWith('http://') && !productUrlValue.startsWith('https://')) {
+ formData.set('product_url', 'https://' + productUrlValue);
+ } else if (productUrlValue) {
+ // Ensure trimmed value is set back if it was already valid
+ formData.set('product_url', productUrlValue);
+ }
+ }
+
// Remove old warranty_years if it exists in formData (it shouldn't if HTML is correct)
formData.delete('warranty_years');
@@ -2325,30 +2407,37 @@ function initEditTabs() {
// Update validateEditTabs function
function validateEditTab(tabId) {
const tab = document.getElementById(tabId);
- let isValid = true;
-
- // Get all required inputs in this tab
- const requiredInputs = tab.querySelectorAll('input[required]');
-
- // Check if all required fields are filled
- requiredInputs.forEach(input => {
- if (!input.value) {
- isValid = false;
- input.classList.add('invalid');
+ if (!tab) {
+ console.warn('validateEditTab: Could not find tab with ID:', tabId);
+ return false; // Or true, depending on desired behavior for missing tabs
+ }
+ let isTabValid = true;
+
+ // Get all relevant form controls within the tab
+ const controls = tab.querySelectorAll('input, textarea, select');
+
+ controls.forEach(control => {
+ // Check the native HTML5 validity state
+ if (!control.validity.valid) {
+ isTabValid = false;
+ control.classList.add('invalid');
+ // Optionally, you could add logic here to display specific messages
+ // or rely on browser default behavior if the form is submitted.
} else {
- input.classList.remove('invalid');
+ control.classList.remove('invalid');
}
});
-
+
// Update the tab button to show completion status
const tabBtn = document.querySelector(`.edit-tab-btn[data-tab="${tabId}"]`);
- if (isValid) {
- tabBtn.classList.add('completed');
- } else {
- tabBtn.classList.remove('completed');
+ if (tabBtn) {
+ if (isTabValid) {
+ tabBtn.classList.add('completed');
+ } else {
+ tabBtn.classList.remove('completed');
+ }
}
-
- return isValid;
+ return isTabValid;
}
// Add this function for secure file access
@@ -2458,100 +2547,95 @@ function initWarrantyForm() {
// Initialize tag functionality
function initTagFunctionality() {
- // Skip if tag elements don't exist
- if (!tagSearch || !tagsList || !manageTagsBtn || !selectedTagsContainer) {
- console.log('Tag elements not found, skipping tag initialization');
+ // This function now ONLY sets up listeners for the main "Add Warranty" form's tag interface.
+ // Assumes globalTagManagementModal listeners (new tag form, close buttons) are set up separately if the modal exists.
+
+ // Get main form tag elements
+ const mainFormTagSearch = document.getElementById('tagSearch');
+ const mainFormTagsList = document.getElementById('tagsList'); // Dropdown for search in main form
+ const mainFormManageTagsBtn = document.getElementById('manageTagsBtn'); // "Manage Tags" button in main form
+ const mainFormSelectedTagsContainer = document.getElementById('selectedTags'); // Container for selected tags in main form
+
+ // Skip if main form specific tag elements don't exist
+ if (!mainFormTagSearch || !mainFormTagsList || !mainFormManageTagsBtn || !mainFormSelectedTagsContainer) {
+ console.log('Main form tag UI elements (tagSearch, tagsList, manageTagsBtn, or selectedTagsContainer) not found, skipping main form tag UI initialization.');
return;
}
- // Load tags from API if not already loaded
+ console.log('Initializing main form tag UI functionality (search, selection, manage button).');
+
+ // Load allTags if not already loaded (needed for search suggestions in the main form)
if (allTags.length === 0) {
- loadTags();
+ loadTags(); // loadTags is async
}
-
- // Tag search input
- tagSearch.addEventListener('focus', () => {
- renderTagsList();
- tagsList.classList.add('show');
+
+ mainFormTagSearch.addEventListener('focus', () => {
+ renderTagsList(); // Renders suggestions into mainFormTagsList based on allTags
+ mainFormTagsList.classList.add('show');
});
-
- tagSearch.addEventListener('input', () => {
- renderTagsList(tagSearch.value);
+
+ mainFormTagSearch.addEventListener('input', () => {
+ renderTagsList(mainFormTagSearch.value); // Filters suggestions
});
-
+
+ // Hide main form's tag suggestion dropdown when clicking outside
document.addEventListener('click', (e) => {
- if (!tagSearch.contains(e.target) && !tagsList.contains(e.target)) {
- tagsList.classList.remove('show');
+ // Check if mainFormTagSearch and mainFormTagsList are still valid (e.g. not removed from DOM)
+ if (mainFormTagSearch && mainFormTagsList &&
+ !mainFormTagSearch.contains(e.target) &&
+ !mainFormTagsList.contains(e.target)) {
+ mainFormTagsList.classList.remove('show');
}
});
-
- // Manage tags button
- manageTagsBtn.addEventListener('click', (e) => {
+
+ // "Manage Tags" button in the main form opens the global tagManagementModal
+ mainFormManageTagsBtn.addEventListener('click', (e) => {
e.preventDefault();
- openTagManagementModal();
+ openTagManagementModal(); // This function shows the global modal
});
-
- // Tag management form
- if (newTagForm) {
- newTagForm.addEventListener('submit', (e) => {
- e.preventDefault();
- createNewTag();
- });
- }
-
- // Close modal buttons
- if (tagManagementModal) {
- const closeButtons = tagManagementModal.querySelectorAll('[data-dismiss="modal"]');
- closeButtons.forEach(button => {
- button.addEventListener('click', () => {
- tagManagementModal.style.display = 'none';
- });
- });
- }
+
+ // Initial rendering of selected tags for the main form (if any are pre-selected or loaded)
+ renderSelectedTags(); // Renders into mainFormSelectedTagsContainer
}
// Function to load all tags
async function loadTags() {
+ console.log('[script.js] loadTags() called. Current page:', window.location.pathname);
+
+ // Check if tags are already loaded and reasonably populated
+ if (allTags && allTags.length > 0) {
+ console.log('[script.js] Tags already loaded in allTags global. Skipping fetch. Count:', allTags.length);
+ // Optionally, re-dispatch the event if other components might need it on subsequent (though now less likely) calls
+ // document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: allTags }));
+ return;
+ }
+
try {
- const token = localStorage.getItem('auth_token');
+ const token = auth.getToken();
if (!token) {
- console.error('No auth token found');
+ console.warn('[script.js] No token available for loadTags. User might not be authenticated yet.');
+ allTags = []; // Ensure allTags is empty if we can't load
return;
}
-
- showLoadingSpinner();
-
const response = await fetch('/api/tags', {
- headers: {
- 'Authorization': `Bearer ${token}`
- }
+ headers: { 'Authorization': `Bearer ${token}` }
});
-
if (!response.ok) {
- throw new Error(`Failed to load tags: ${response.status}`);
- }
-
- const data = await response.json();
- console.log('Loaded tags:', data);
-
- // Store tags globally
- allTags = data;
-
- // Populate the tag filter
- populateTagFilter();
-
- // Render selected tags if any
- if (selectedTagsContainer) {
- renderSelectedTags();
+ const errorText = await response.text();
+ console.error('[script.js] Failed to load tags:', response.status, errorText);
+ allTags = []; // Default to empty on error
+ return;
}
-
- hideLoadingSpinner();
-
- return data;
+ const fetchedTags = await response.json();
+ // Assuming fetchedTags is an array of {id, name, color, ...} as expected by other functions
+ allTags = fetchedTags;
+ console.log('[script.js] All tags loaded into global allTags variable:', allTags.length, 'tags. Sample:', allTags.slice(0,2));
+ // Dispatch event for any components that might be waiting for tags (e.g., Tagify instances)
+ document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: allTags }));
+
} catch (error) {
- console.error('Error loading tags:', error);
- hideLoadingSpinner();
- return [];
+ console.error('[script.js] Error in loadTags():', error);
+ allTags = []; // Default to empty on critical error
}
}
@@ -3082,9 +3166,9 @@ function setupUIEventListeners() {
if (modalToClose) {
// *** MODIFIED CHECK ***
// If the click target is the backdrop itself (not a dismiss button)
- // AND the modal is the 'addWarrantyModal', then DO NOTHING.
- if (modalToClose.id === 'addWarrantyModal' && e.target === modalToClose) {
- return; // Ignore backdrop click for addWarrantyModal
+ // AND the modal is the 'addWarrantyModal' or 'editModal', then DO NOTHING.
+ if ((modalToClose.id === 'addWarrantyModal' || modalToClose.id === 'editModal') && e.target === modalToClose) {
+ return; // Ignore backdrop click for addWarrantyModal and editModal
}
// *** END MODIFIED CHECK ***
@@ -3119,6 +3203,7 @@ function setupUIEventListeners() {
const statusFilter = document.getElementById('statusFilter');
const tagFilter = document.getElementById('tagFilter');
const sortBySelect = document.getElementById('sortBy');
+ const vendorFilter = document.getElementById('vendorFilter'); // Added vendor filter select
if (searchInput) {
searchInput.addEventListener('input', () => {
@@ -3167,6 +3252,13 @@ function setupUIEventListeners() {
});
}
+ if (vendorFilter) { // Added event listener for vendor filter
+ vendorFilter.addEventListener('change', () => {
+ currentFilters.vendor = vendorFilter.value;
+ applyFilters();
+ });
+ }
+
if (sortBySelect) {
sortBySelect.addEventListener('change', () => {
currentFilters.sortBy = sortBySelect.value;
@@ -3205,7 +3297,42 @@ function setupUIEventListeners() {
// Save warranty changes
const saveWarrantyBtn = document.getElementById('saveWarrantyBtn');
- if (saveWarrantyBtn) saveWarrantyBtn.addEventListener('click', saveWarranty);
+ if (saveWarrantyBtn) {
+ let functionToAttachOnClick = saveWarranty; // Default to the original saveWarranty from script.js
+
+ // Check if the observer setup function from status.js is available
+ if (typeof window.setupSaveWarrantyObserver === 'function') {
+ console.log('[script.js] window.setupSaveWarrantyObserver (from status.js) was FOUND. Attempting to wrap local saveWarranty function.');
+ try {
+ // Call the observer setup function, passing it the original saveWarranty from this script.
+ // The observer setup function is expected to return a new function that wraps the original.
+ functionToAttachOnClick = window.setupSaveWarrantyObserver(saveWarranty);
+
+ // Optional: A flag to let status.js know that script.js has handled the wrapping.
+ // This can be useful if status.js has any fallback/polling logic to prevent double-wrapping.
+ window.saveWarrantyObserverAttachedByScriptJS = true;
+ console.log('[script.js] Local saveWarranty function has been successfully WRAPPED by the observer from status.js.');
+ } catch (e) {
+ console.error('[script.js] An error occurred while trying to wrap saveWarranty with the observer from status.js:', e);
+ // If an error occurs during wrapping, functionToAttachOnClick will remain the original saveWarranty.
+ }
+ } else {
+ console.log('[script.js] window.setupSaveWarrantyObserver (from status.js) was NOT FOUND. Using the original saveWarranty function for the button.');
+ }
+
+ // Add the event listener using the (potentially) wrapped function.
+ saveWarrantyBtn.addEventListener('click', () => {
+ console.log('[script.js] Save button (saveWarrantyBtn) clicked. Invoking the determined save function (functionToAttachOnClick).');
+ if (typeof functionToAttachOnClick === 'function') {
+ functionToAttachOnClick(); // Execute the determined save function
+ } else {
+ console.error('[script.js] CRITICAL: functionToAttachOnClick is not a function when save button was clicked!');
+ }
+ });
+
+ } else {
+ console.warn('[script.js] saveWarrantyBtn DOM element not found. Cannot attach click listener.');
+ }
// Confirm delete button
const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
@@ -3280,6 +3407,7 @@ function deleteWarranty() {
// Save warranty updates
function saveWarranty() {
+ console.log("[script.js] CORE saveWarranty (original from script.js) EXECUTING.");
if (!currentWarrantyId) {
showToast('No warranty selected for update', 'error');
return;
@@ -3327,8 +3455,11 @@ function saveWarranty() {
formData.append('purchase_date', purchaseDate);
// Optional fields
- const productUrl = document.getElementById('editProductUrl').value.trim();
+ let productUrl = document.getElementById('editProductUrl').value.trim();
if (productUrl) {
+ if (!productUrl.startsWith('http://') && !productUrl.startsWith('https://')) {
+ productUrl = 'https://' + productUrl;
+ }
formData.append('product_url', productUrl);
}
@@ -3448,6 +3579,62 @@ function saveWarranty() {
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)
+ 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);
+ }
+ // --- END NEW ---
});
})
.catch(error => {
@@ -3496,6 +3683,41 @@ function populateTagFilter() {
});
}
+// Function to populate vendor filter dropdown
+function populateVendorFilter() {
+ const vendorFilterElement = document.getElementById('vendorFilter');
+ if (!vendorFilterElement) return;
+
+ // Clear existing options (except "All Vendors")
+ while (vendorFilterElement.options.length > 1) {
+ vendorFilterElement.remove(1);
+ }
+
+ // Create a Set to store unique vendor names (case-insensitive)
+ const uniqueVendors = new Set();
+
+ // Collect all unique, non-empty vendors from warranties
+ warranties.forEach(warranty => {
+ if (warranty.vendor && warranty.vendor.trim() !== '') {
+ uniqueVendors.add(warranty.vendor.trim().toLowerCase());
+ }
+ });
+
+ // Sort vendors alphabetically (after converting back to original case for display if needed, or just use lowercase)
+ // For simplicity, we'll sort the lowercase versions and display them as is.
+ // If original casing is important, a map could be used to store original values.
+ const sortedVendors = Array.from(uniqueVendors).sort((a, b) => a.localeCompare(b));
+
+ // Add options to the dropdown
+ sortedVendors.forEach(vendor => {
+ const option = document.createElement('option');
+ option.value = vendor; // Use lowercase for value consistency
+ // Capitalize first letter for display
+ option.textContent = vendor.charAt(0).toUpperCase() + vendor.slice(1);
+ vendorFilterElement.appendChild(option);
+ });
+}
+
// --- Updated Function ---
function handleLifetimeChange(event) {
const checkbox = event ? event.target : isLifetimeCheckbox;
@@ -3667,9 +3889,9 @@ function setupModalTriggers() {
// Find the closest modal backdrop to the element clicked
const modalToClose = e.target.closest('.modal-backdrop');
if (modalToClose) {
- // *** ADD CHECK: Do NOT close addWarrantyModal via this general listener ***
- if (modalToClose.id === 'addWarrantyModal') {
- return; // Ignore backdrop clicks for the add modal here
+ // *** ADD CHECK: Do NOT close addWarrantyModal or editModal via this general listener for backdrop clicks ***
+ if ((modalToClose.id === 'addWarrantyModal' || modalToClose.id === 'editModal') && e.target === modalToClose) {
+ return; // Ignore backdrop clicks for the add and edit modals here
}
// *** END ADD CHECK ***
diff --git a/frontend/status.html b/frontend/status.html
index f4f4cfc..dde94eb 100644
--- a/frontend/status.html
+++ b/frontend/status.html
@@ -29,7 +29,7 @@
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- Load fix for auth buttons -->
<script src="fix-auth-buttons-loader.js"></script>
- <script data-cfasync="false" src="/javascript.js"></script> <!-- Cloudflare compatibility -->
+ <script src="script.js" defer></script> <!-- Added script.js -->
<style>
.user-menu {
position: relative;
@@ -398,12 +398,230 @@
<!-- Toast Notifications -->
<div class="toast-container" id="toastContainer"></div>
+ <!-- Edit Warranty Modal -->
+ <div id="editModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3 class="modal-title">Edit Warranty</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <!-- 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
+ </button>
+ <button type="button" class="edit-tab-btn" data-tab="edit-warranty-details">
+ <i class="fas fa-shield-alt"></i> Warranty
+ </button>
+ <button type="button" class="edit-tab-btn" data-tab="edit-documents">
+ <i class="fas fa-file-alt"></i> Documents
+ </button>
+ <button type="button" class="edit-tab-btn" data-tab="edit-tags">
+ <i class="fas fa-tags"></i> Tags
+ </button>
+ </div>
+
+ <form id="editWarrantyForm">
+ <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>
+ <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">
+ </div>
+
+ <div class="form-group">
+ <label>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.">
+ </div>
+ </div>
+
+ <!-- Warranty Details Tab -->
+ <div class="edit-tab-content" id="edit-warranty-details">
+ <div class="form-group">
+ <label for="editPurchaseDate">Purchase Date</label>
+ <input type="date" id="editPurchaseDate" name="purchase_date" class="form-control" required>
+ </div>
+
+ <!-- Add Lifetime Checkbox -->
+ <div class="form-group">
+ <label class="lifetime-label">
+ <input type="checkbox" id="editIsLifetime" name="is_lifetime" value="true">
+ Lifetime Warranty
+ </label>
+ </div>
+ <!-- End Lifetime Checkbox -->
+
+ <div id="editWarrantyDurationFields">
+ <div class="form-group">
+ <label for="editWarrantyDurationYears">Warranty Period</label>
+ <div class="duration-inputs">
+ <div>
+ <input type="number" id="editWarrantyDurationYears" name="warranty_duration_years" class="form-control" min="0" max="100" placeholder="Years">
+ <small>Years</small>
+ </div>
+ <div>
+ <input type="number" id="editWarrantyDurationMonths" name="warranty_duration_months" class="form-control" min="0" max="11" placeholder="Months">
+ <small>Months</small>
+ </div>
+ <div>
+ <input type="number" id="editWarrantyDurationDays" name="warranty_duration_days" class="form-control" min="0" max="365" placeholder="Days">
+ <small>Days</small>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <label for="editPurchasePrice">Purchase Price (Optional)</label>
+ <div class="price-input-wrapper">
+ <span class="currency-symbol">$</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>
+ </div>
+ </div>
+
+ <!-- Documents Tab -->
+ <div class="edit-tab-content" id="edit-documents">
+ <div class="form-group">
+ <label>Invoice/Receipt</label>
+ <div class="file-input-wrapper">
+ <label for="editInvoice" class="file-input-label">
+ <i class="fas fa-upload"></i> Choose File
+ </label>
+ <input type="file" id="editInvoice" name="invoice" class="file-input" accept=".pdf,.png,.jpg,.jpeg">
+ </div>
+ <div id="editFileName" class="file-name"></div>
+ <div id="currentInvoice" class="mt-10"></div>
+ <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>
+ </div>
+ <div class="form-group">
+ <label>Product Manual (Optional)</label>
+ <div class="file-input-wrapper">
+ <label for="editManual" class="file-input-label">
+ <i class="fas fa-upload"></i> Choose File
+ </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>
+ </div>
+ <div class="form-group">
+ <label>Files (ZIP/RAR, Optional)</label>
+ <div class="file-input-wrapper">
+ <label for="editOtherDocument" class="file-input-label">
+ <i class="fas fa-upload"></i> Choose File
+ </label>
+ <input type="file" id="editOtherDocument" name="other_document" class="file-input" accept=".zip,.rar">
+ </div>
+ <div id="editOtherDocumentFileName" class="file-name"></div>
+ <div id="currentOtherDocument" class="mt-10"></div>
+ <button type="button" id="deleteOtherDocumentBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> Delete Files</button>
+ </div>
+ </div>
+
+ <!-- Tags Tab -->
+ <div class="edit-tab-content" id="edit-tags">
+ <div class="form-group">
+ <label>Add Tags</label>
+ <p class="text-muted">Tags help you organize and filter your warranties</p>
+
+ <div class="tags-container">
+ <div class="selected-tags" id="editSelectedTags">
+ <!-- Selected tags will be displayed here -->
+ </div>
+
+ <div class="tags-dropdown">
+ <input type="text" id="editTagSearch" class="form-control" placeholder="Search or add new tag...">
+ <div class="tags-list" id="editTagsList">
+ <!-- Tag options will be populated by JavaScript -->
+ </div>
+ </div>
+
+ <div class="mt-10">
+ <button type="button" id="editManageTagsBtn" class="btn btn-secondary btn-sm">
+ <i class="fas fa-cog"></i> Manage Tags
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </form>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-danger" data-dismiss="modal">Cancel</button>
+ <button id="saveWarrantyBtn" class="btn btn-primary">Save Changes</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Confirm Delete Modal -->
+ <div id="deleteModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3 class="modal-title">Confirm Delete</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <p>Are you sure you want to delete this warranty? This action cannot be undone.</p>
+ <p><strong>Product:</strong> <span id="deleteProductName"></span></p>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
+ <button id="confirmDeleteBtn" class="btn btn-danger">Delete</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Tag Management Modal -->
+ <div id="tagManagementModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3 class="modal-title">Manage Tags</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <form id="newTagForm" class="tag-form">
+ <input type="text" id="newTagName" class="form-control" placeholder="New tag name" required>
+ <input type="color" id="newTagColor" value="#808080">
+ <button type="submit" class="btn btn-primary">Add Tag</button>
+ </form>
+
+ <h4 class="mt-20">Existing Tags</h4>
+ <div id="existingTags" class="existing-tags">
+ <!-- Tags will be populated here by JavaScript -->
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" data-dismiss="modal">Close</button>
+ </div>
+ </div>
+ </div>
+
<!-- Loading Spinner -->
<div class="loading-container" id="loadingContainer">
<div class="loading-spinner"></div>
</div>
-
+
<script src="auth.js"></script>
- <script src="status.js"></script>
+ <script src="status.js" defer></script>
</body>
</html>
\ No newline at end of file
diff --git a/frontend/status.js b/frontend/status.js
index 39f4e48..b265212 100644
--- a/frontend/status.js
+++ b/frontend/status.js
@@ -1,979 +1,893 @@
-// DOM Elements
-const settingsBtn = document.getElementById('settingsBtn');
-const settingsMenu = document.getElementById('settingsMenu');
-const darkModeToggle = document.getElementById('darkModeToggle');
-const loadingIndicator = document.getElementById('loadingIndicator');
-const errorContainer = document.getElementById('errorContainer');
-const errorMessage = document.getElementById('errorMessage');
-const errorDetails = document.getElementById('errorDetails');
-const dashboardContent = document.getElementById('dashboardContent');
-const refreshDashboardBtn = document.getElementById('refreshDashboardBtn');
-const searchWarranties = document.getElementById('searchWarranties');
-const statusFilter = document.getElementById('statusFilter');
-const sortableHeaders = document.querySelectorAll('.sortable');
-const exportBtn = document.getElementById('exportBtn');
-
-// Configuration
-const API_BASE_URL = '/api/statistics'; // Base URL for statistics endpoint
-const API_URL = window.location.origin + API_BASE_URL; // Full URL for statistics endpoint
-let EXPIRING_SOON_DAYS = 30; // Default value, will be updated from user preferences
-
-// Global variables for sorting and filtering
-let currentSort = { column: 'expiration', direction: 'asc' };
-let allWarranties = []; // Store all warranties for filtering/sorting
-
-// Global variables for chart instances and data
-let statusChart = null;
-let timelineChart = null;
-let currentStatusData = null; // To store data for redraws
-let currentTimelineData = null; // To store data for redraws
-
-// Theme Management - Simplified
-function setTheme(isDark) {
- const theme = isDark ? 'dark' : 'light';
- console.log('Setting theme to:', theme, 'from status.js');
-
- // 1. Apply theme attribute to document root
- document.documentElement.setAttribute('data-theme', theme);
-
- // 2. Save the single source of truth to localStorage
- localStorage.setItem('darkMode', isDark);
-
- // Update toggle state if the toggle exists on this page
- if (darkModeToggle) {
- darkModeToggle.checked = isDark;
- }
-}
-
-// Function to redraw charts after theme change
-function redrawChartsWithNewTheme() {
- console.log("Theme changed, redrawing charts...");
- // Destroy existing charts if they exist - USE CORRECT VARIABLE NAMES
- if (statusChart && typeof statusChart.destroy === 'function') {
- statusChart.destroy();
- statusChart = null; // Reset variable
- }
- if (timelineChart && typeof timelineChart.destroy === 'function') {
- timelineChart.destroy();
- timelineChart = null; // Reset variable
- }
- // Re-create charts with current data which will use new theme colors
- if (currentStatusData) {
- createStatusChart(currentStatusData);
+(function() {
+ // DOM Elements
+ const loadingIndicator = document.getElementById('loadingIndicator');
+ const errorContainer = document.getElementById('errorContainer');
+ const errorMessage = document.getElementById('errorMessage');
+ const errorDetails = document.getElementById('errorDetails');
+ const dashboardContent = document.getElementById('dashboardContent');
+ const refreshDashboardBtn = document.getElementById('refreshDashboardBtn');
+
+ // Elements specific to status page's own filtering/sorting UI - Activated
+ const searchWarranties = document.getElementById('searchWarranties');
+ const statusFilter = document.getElementById('statusFilter');
+ const exportBtn = document.getElementById('exportBtn');
+ // sortableHeaders will be queried inside attachSortListeners
+
+ // Configuration
+ const STATUS_PAGE_API_BASE_URL = '/api/statistics';
+ const STATISTICS_API_URL = window.location.origin + STATUS_PAGE_API_BASE_URL;
+ let EXPIRING_SOON_DAYS = 30;
+
+ // IIFE-local variables
+ let currentSort = { column: 'expiration_date', direction: 'asc' };
+ let allWarranties = [];
+ let statusChart = null;
+ let timelineChart = null;
+ let currentStatusData = null;
+ let currentTimelineData = null;
+ let userCurrencySymbol = '$'; // Default currency symbol
+
+ function setTheme(isDark) {
+ const theme = isDark ? 'dark' : 'light';
+ console.log('Setting theme from status.js IIFE to:', theme);
+ document.documentElement.setAttribute('data-theme', theme);
+ localStorage.setItem('darkMode', isDark);
+ // The visual state of any shared header toggle is handled by other scripts (e.g., script.js or auth.js)
}
- if (currentTimelineData) {
- createTimelineChart(currentTimelineData);
- }
-}
-
-// Loading indicator functions
-function showLoading() {
- if (loadingIndicator) {
- loadingIndicator.classList.add('active');
- dashboardContent.style.opacity = '0.5';
- }
-}
-function hideLoading() {
- if (loadingIndicator) {
- loadingIndicator.classList.remove('active');
- dashboardContent.style.opacity = '1';
+ function formatDateYYYYMMDD(date) {
+ if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
+ return 'N/A';
+ }
+ const year = date.getUTCFullYear();
+ const month = String(date.getUTCMonth() + 1).padStart(2, '0');
+ const day = String(date.getUTCDate()).padStart(2, '0');
+ return `${year}-${month}-${day}`;
}
-}
-
-// Show error message
-function showError(message, details = '') {
- errorMessage.textContent = message;
- errorDetails.textContent = details;
- errorContainer.style.display = 'block';
- dashboardContent.style.display = 'none';
-}
-
-// Hide error message
-function hideError() {
- errorContainer.style.display = 'none';
- dashboardContent.style.display = 'block';
-}
-
-// Fetch statistics from API
-async function fetchStatistics() {
- try {
- console.log('Checking authentication status...');
- console.log('window.auth exists:', !!window.auth);
-
- // Check if auth is available and user is authenticated
- if (!window.auth) {
- console.error('Auth object not available. Make sure auth.js is loaded before status.js');
- throw new Error('Authentication system not available. Please refresh the page.');
+
+ function redrawChartsWithNewTheme() {
+ console.log("Theme changed, redrawing charts from status.js IIFE...");
+ if (statusChart && typeof statusChart.destroy === 'function') {
+ statusChart.destroy();
+ statusChart = null;
}
-
- console.log('User is authenticated:', window.auth.isAuthenticated());
- if (!window.auth.isAuthenticated()) {
- throw new Error('Authentication required. Please log in to view statistics.');
+ if (timelineChart && typeof timelineChart.destroy === 'function') {
+ timelineChart.destroy();
+ timelineChart = null;
}
-
- // Get the auth token
- const token = window.auth.getToken();
- console.log('Auth token available:', !!token);
- if (!token) {
- throw new Error('Authentication token not available. Please log in again.');
+ if (currentStatusData) {
+ createStatusChart(currentStatusData);
}
-
- // Create request with auth header
- const options = {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- };
-
- console.log('Fetching statistics from:', API_URL);
- const response = await fetch(API_URL, options);
-
- if (!response.ok) {
- const errorText = await response.text();
- throw new Error(`Failed to fetch statistics: ${response.status} ${errorText}`);
+ if (currentTimelineData) {
+ createTimelineChart(currentTimelineData);
}
-
- // Parse JSON only once
- const data = await response.json();
- return data;
- } catch (error) {
- console.error('Error fetching statistics:', error);
- throw error;
}
-}
-
-// Show a toast notification
-function showToast(message, type = 'info') {
- const toastContainer = document.getElementById('toastContainer');
- const toast = document.createElement('div');
- toast.className = `toast toast-${type}`;
- toast.innerHTML = `
- ${message}
- <button class="toast-close">&times;</button>
- `;
-
- // Add close event
- toast.querySelector('.toast-close').addEventListener('click', () => {
- toast.remove();
- });
-
- toastContainer.appendChild(toast);
-
- // Auto remove after 3 seconds
- setTimeout(() => {
- if (toast.parentElement) {
- toast.remove();
- }
- }, 3000);
-}
-
-// Update the summary counts
-function updateSummaryCounts(statusData) {
- // Check if the elements exist before trying to set textContent
- const totalEl = document.getElementById('totalCount');
- const activeEl = document.getElementById('activeCount');
- const expiringEl = document.getElementById('expiringCount');
- const expiredEl = document.getElementById('expiredCount');
-
- if (totalEl) totalEl.textContent = statusData.total || 0;
- if (activeEl) activeEl.textContent = statusData.active || 0;
- if (expiringEl) expiringEl.textContent = statusData.expiring_soon || 0;
- if (expiredEl) expiredEl.textContent = statusData.expired || 0;
-}
-
-// Create the status distribution chart
-function createStatusChart(stats) {
- const ctx = document.getElementById('statusChart').getContext('2d');
-
- // Ensure we have valid stats
- if (!stats || typeof stats !== 'object') {
- console.error('Invalid stats data:', stats);
- stats = { active: 0, expiring_soon: 0, expired: 0, total: 0 };
+
+ function showLoading() {
+ if (loadingIndicator) loadingIndicator.classList.add('active');
+ if (dashboardContent) dashboardContent.style.opacity = '0.5';
}
-
- // Set default values for missing properties
- const active = stats.active || 0;
- const expiringSoon = stats.expiring_soon || 0;
- const expired = stats.expired || 0;
-
- // Calculate truly active (not expiring soon)
- const trulyActive = Math.max(0, active - expiringSoon);
-
- // Destroy existing chart if it exists - USE CORRECT VARIABLE NAME
- if (statusChart && typeof statusChart.destroy === 'function') {
- statusChart.destroy();
+
+ function hideLoading() {
+ if (loadingIndicator) loadingIndicator.classList.remove('active');
+ if (dashboardContent) dashboardContent.style.opacity = '1';
}
-
- statusChart = new Chart(ctx, {
- type: 'doughnut',
- data: {
- labels: ['Active', 'Expiring Soon', 'Expired'],
- datasets: [{
- data: [
- trulyActive,
- expiringSoon,
- expired
- ],
- backgroundColor: [
- '#4CAF50', // Green for active
- '#FF9800', // Orange for expiring soon
- '#F44336' // Red for expired
- ],
- borderWidth: 1
- }]
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- plugins: {
- legend: {
- position: 'bottom'
- }
- }
- }
- });
-}
-// Create the timeline chart
-function createTimelineChart(timeline) {
- const ctx = document.getElementById('timelineChart').getContext('2d');
-
- // Ensure timeline is an array
- if (!Array.isArray(timeline)) {
- console.error('Timeline data is not an array:', timeline);
- timeline = [];
+ function showError(message, details = '') {
+ if (errorMessage) errorMessage.textContent = message;
+ if (errorDetails) errorDetails.textContent = details;
+ if (errorContainer) errorContainer.style.display = 'block';
+ if (dashboardContent) dashboardContent.style.display = 'none';
}
-
- // Format labels as "Month Year"
- const formattedLabels = timeline.map(item => {
+
+ function hideError() {
+ if (errorContainer) errorContainer.style.display = 'none';
+ if (dashboardContent) dashboardContent.style.display = 'block';
+ }
+
+ async function fetchStatistics() {
try {
- // Handle different possible formats
- let year, month;
-
- if (item.year !== undefined && item.month !== undefined) {
- year = item.year;
- month = item.month - 1; // JavaScript months are 0-indexed
- } else if (item.date) {
- const date = new Date(item.date);
- year = date.getFullYear();
- month = date.getMonth();
- } else {
- // Default to current month if data format is unknown
- const date = new Date();
- year = date.getFullYear();
- month = date.getMonth();
+ console.log('Checking authentication status... (status.js IIFE)');
+ if (!window.auth || !window.auth.isAuthenticated()) {
+ throw new Error('Authentication required.');
}
-
- const date = new Date(year, month, 1);
- return date.toLocaleDateString(undefined, { month: 'short', year: 'numeric' });
+ const token = window.auth.getToken();
+ if (!token) {
+ throw new Error('Authentication token not available.');
+ }
+ const options = {
+ 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);
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`Failed to fetch statistics: ${response.status} ${errorText}`);
+ }
+ return await response.json();
} catch (error) {
- console.error('Error formatting timeline label:', error);
- return 'Unknown';
- }
- });
-
- // Get count values, defaulting to 0 if not present
- const counts = timeline.map(item => {
- return item.count !== undefined ? item.count : 0;
- });
-
- // If we have no data, create a default dataset
- if (timeline.length === 0) {
- const currentDate = new Date();
- const currentYear = currentDate.getFullYear();
- const currentMonth = currentDate.getMonth();
-
- // Create labels for the last 3 months
- for (let i = 2; i >= 0; i--) {
- const date = new Date(currentYear, currentMonth - i, 1);
- formattedLabels.push(date.toLocaleDateString(undefined, { month: 'short', year: 'numeric' }));
- counts.push(0);
+ console.error('Error fetching statistics (status.js IIFE):', error);
+ throw error;
}
}
-
- // Destroy existing chart if it exists - USE CORRECT VARIABLE NAME
- if (timelineChart && typeof timelineChart.destroy === 'function') {
- timelineChart.destroy();
+
+ function showToast(message, type = 'info') {
+ const toastContainer = document.getElementById('toastContainer');
+ if (!toastContainer) return;
+ 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());
+ toastContainer.appendChild(toast);
+ setTimeout(() => { if (toast.parentElement) toast.remove(); }, 3000);
}
-
- timelineChart = new Chart(ctx, {
- type: 'bar',
- data: {
- labels: formattedLabels,
- datasets: [{
- label: 'Warranties Expiring',
- data: counts,
- backgroundColor: '#3498db',
- borderColor: '#2980b9',
- borderWidth: 1
- }]
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- scales: {
- y: {
- beginAtZero: true,
- ticks: {
- precision: 0 // Only show integer values
+
+ function updateSummaryCounts(statusData) {
+ const totalEl = document.getElementById('totalCount');
+ const activeEl = document.getElementById('activeCount');
+ const expiringEl = document.getElementById('expiringCount');
+ const expiredEl = document.getElementById('expiredCount');
+ if (totalEl) totalEl.textContent = statusData.total || 0;
+ if (activeEl) activeEl.textContent = statusData.active || 0;
+ if (expiringEl) expiringEl.textContent = statusData.expiring_soon || 0;
+ if (expiredEl) expiredEl.textContent = statusData.expired || 0;
+ }
+
+ function createStatusChart(stats) {
+ const ctxEl = document.getElementById('statusChart');
+ if (!ctxEl) { console.warn("statusChart canvas not found"); return; }
+ 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' } } }
+ });
+ }
+
+ function createTimelineChart(timelineData) {
+ const ctxEl = document.getElementById('timelineChart');
+ if (!ctxEl) { console.warn("timelineChart canvas not found"); return; }
+ const ctx = ctxEl.getContext('2d');
+ let labels = [];
+ let counts = [];
+
+ if (!Array.isArray(timelineData) || timelineData.length === 0) {
+ console.warn('Timeline data is empty or not an array. Displaying default empty chart.');
+ const currentDate = new Date();
+ for (let i = 2; i >= 0; i--) { // Last 3 months
+ const d = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1);
+ labels.push(d.toLocaleDateString(undefined, { month: 'short', year: 'numeric' }));
+ counts.push(0);
+ }
+ } else {
+ labels = timelineData.map(item => {
+ try {
+ let year, monthVal;
+ if (item.year !== undefined && item.month !== undefined) {
+ year = item.year; monthVal = item.month - 1; // JS month is 0-indexed
+ } else if (item.date) { // Assuming item.date is a parsable date string
+ const d = new Date(item.date); year = d.getFullYear(); monthVal = d.getMonth();
+ } else { // Fallback if structure is unknown
+ const d = new Date(); year = d.getFullYear(); monthVal = d.getMonth();
}
+ return new Date(year, monthVal, 1).toLocaleDateString(undefined, { month: 'short', year: 'numeric' });
+ } catch (e) {
+ console.error("Error formatting timeline label item:", item, e);
+ return 'Unknown';
}
- }
+ });
+ counts = timelineData.map(item => item.count || 0);
}
- });
-}
-
-// Update the recent expirations table
-function updateRecentExpirations(recentWarranties) {
- // Ensure we have an array
- if (!Array.isArray(recentWarranties)) {
- console.error('Recent warranties data is not an array:', recentWarranties);
- recentWarranties = [];
- }
-
- // Normalize the data format
- const normalizedWarranties = recentWarranties.map(warranty => {
- // Create a standardized warranty object
- return {
- id: warranty.id || Math.random().toString(36).substr(2, 9), // Generate ID if not present
- product_name: warranty.product_name || warranty.name || 'Unknown Product',
- purchase_date: warranty.purchase_date || new Date().toISOString().split('T')[0],
- expiration_date: warranty.expiration_date || new Date().toISOString().split('T')[0],
- invoice_path: warranty.invoice_path || null
- };
- });
-
- // Apply initial filtering and sorting
- filterAndSortWarranties();
-}
-
-// Filter and sort warranties based on current settings
-function filterAndSortWarranties() {
- const searchTerm = searchWarranties.value.toLowerCase();
- const statusValue = statusFilter.value;
- const tableBody = document.getElementById('recentExpirationsBody');
-
- // Clear the table
- tableBody.innerHTML = '';
-
- if (!allWarranties || allWarranties.length === 0) {
- // Create a full-width, centered overlay message instead of using table structure
- const tableContainer = document.querySelector('.table-responsive');
- const emptyMessage = document.createElement('div');
-
- // Apply styles directly to ensure centering
- emptyMessage.style.position = 'absolute';
- emptyMessage.style.top = '0';
- emptyMessage.style.left = '0';
- emptyMessage.style.width = '100%';
- emptyMessage.style.height = '300px';
- emptyMessage.style.display = 'flex';
- emptyMessage.style.justifyContent = 'center';
- emptyMessage.style.alignItems = 'center';
- emptyMessage.style.fontSize = '1.2em';
- emptyMessage.style.color = 'var(--text-color)';
- emptyMessage.style.backgroundColor = 'var(--card-bg)';
- emptyMessage.style.zIndex = '1'; // Ensure it's on top
-
- // Add the message text
- emptyMessage.textContent = 'No recently expired or expiring warranties.';
-
- // Make sure table container has position relative
- tableContainer.style.position = 'relative';
-
- // Clear any existing error messages
- const existingMessages = tableContainer.querySelectorAll('.empty-message-overlay');
- existingMessages.forEach(msg => msg.remove());
-
- // Add class for easier removal later
- emptyMessage.classList.add('empty-message-overlay');
-
- // Add to the table container
- tableContainer.appendChild(emptyMessage);
-
- // Add a blank row to maintain table structure
- const row = document.createElement('tr');
- row.innerHTML = '<td colspan="5" style="height: 300px;"></td>';
- tableBody.appendChild(row);
-
- return;
+
+ 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 } } } }
+ });
}
- const today = new Date();
-
- // Filter warranties
- let filteredWarranties = allWarranties.filter(warranty => {
- // Skip warranties without proper dates
- if (!warranty.expiration_date) return false;
-
- // Apply search filter
- const productName = (warranty.product_name || '').toLowerCase();
- const matchesSearch = searchTerm === '' || productName.includes(searchTerm);
-
- // Apply status filter
- if (statusValue === 'all') {
- return matchesSearch;
- }
-
- const expirationDate = new Date(warranty.expiration_date);
-
- if (statusValue === 'expired') {
- return expirationDate <= today && matchesSearch;
- } else if (statusValue === 'expiring') {
- const timeDiff = expirationDate - today;
- const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
- return expirationDate > today && daysDiff <= EXPIRING_SOON_DAYS && matchesSearch;
- } else if (statusValue === 'active') {
- const timeDiff = expirationDate - today;
- const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
- return expirationDate > today && daysDiff > EXPIRING_SOON_DAYS && matchesSearch;
- }
-
- return matchesSearch;
- });
-
- // Sort warranties
- filteredWarranties.sort((a, b) => {
- let valueA, valueB;
-
- switch (currentSort.column) {
- case 'product':
- valueA = a.product_name || '';
- valueB = b.product_name || '';
- break;
- case 'purchase':
- valueA = new Date(a.purchase_date || 0);
- valueB = new Date(b.purchase_date || 0);
- break;
- case 'expiration':
- valueA = new Date(a.expiration_date || 0);
- valueB = new Date(b.expiration_date || 0);
- break;
- case 'status':
- // Sort by status priority: active, expiring, expired
- const statusA = getStatusPriority(a.expiration_date, today);
- const statusB = getStatusPriority(b.expiration_date, today);
- valueA = statusA;
- valueB = statusB;
- break;
- default:
- valueA = new Date(a.expiration_date || 0);
- valueB = new Date(b.expiration_date || 0);
- }
-
- // Compare values based on sort direction
- if (currentSort.direction === 'asc') {
- if (valueA instanceof Date && valueB instanceof Date) {
- return valueA.getTime() - valueB.getTime();
- } else {
- return valueA > valueB ? 1 : valueA < valueB ? -1 : 0;
- }
+ function updateRecentExpirations(recentWarrantiesData) {
+ if (!Array.isArray(recentWarrantiesData)) {
+ console.error('Recent warranties data is not an array (status.js IIFE):', recentWarrantiesData);
+ allWarranties = [];
} else {
- if (valueA instanceof Date && valueB instanceof Date) {
- return valueB.getTime() - valueA.getTime();
- } else {
- return valueA < valueB ? 1 : valueA > valueB ? -1 : 0;
- }
+ allWarranties = recentWarrantiesData.map(warranty => ({
+ id: warranty.id || String(Math.random()).slice(2, 11), // Ensure ID is a string for consistency
+ product_name: warranty.product_name || warranty.name || 'Unknown Product',
+ purchase_date: warranty.purchase_date,
+ expiration_date: warranty.expiration_date,
+ is_lifetime: warranty.is_lifetime || false,
+ invoice_path: warranty.invoice_path || null,
+ product_url: warranty.product_url,
+ purchase_price: warranty.purchase_price,
+ vendor: warranty.vendor,
+ serial_numbers: warranty.serial_numbers || [],
+ notes: warranty.notes,
+ manual_path: warranty.manual_path || null,
+ other_document_path: warranty.other_document_path || null
+ }));
}
- });
-
- // Render filtered and sorted warranties
- if (filteredWarranties.length === 0) {
- // Create a full-width, centered overlay message instead of using table structure
- const tableContainer = document.querySelector('.table-responsive');
- const emptyMessage = document.createElement('div');
-
- // Apply styles directly to ensure centering
- emptyMessage.style.position = 'absolute';
- emptyMessage.style.top = '0';
- emptyMessage.style.left = '0';
- emptyMessage.style.width = '100%';
- emptyMessage.style.height = '300px';
- emptyMessage.style.display = 'flex';
- emptyMessage.style.justifyContent = 'center';
- emptyMessage.style.alignItems = 'center';
- emptyMessage.style.fontSize = '1.2em';
- emptyMessage.style.color = 'var(--text-color)';
- emptyMessage.style.backgroundColor = 'var(--card-bg)';
- emptyMessage.style.zIndex = '1'; // Ensure it's on top
-
- // Add the message text
- emptyMessage.textContent = 'No warranties match your search criteria.';
-
- // Make sure table container has position relative
- tableContainer.style.position = 'relative';
-
- // Clear any existing error messages
- const existingMessages = tableContainer.querySelectorAll('.empty-message-overlay');
- existingMessages.forEach(msg => msg.remove());
-
- // Add class for easier removal later
- emptyMessage.classList.add('empty-message-overlay');
-
- // Add to the table container
- tableContainer.appendChild(emptyMessage);
-
- // Add a blank row to maintain table structure
- const row = document.createElement('tr');
- row.innerHTML = '<td colspan="5" style="height: 300px;"></td>';
- tableBody.appendChild(row);
-
- return;
+ filterAndSortWarranties(); // This will render the table
}
-
- filteredWarranties.forEach(warranty => {
- const row = document.createElement('tr');
-
- // Make sure we have valid data to work with
- if (!warranty.expiration_date) return;
+
+ function filterAndSortWarranties() {
+ const tableBody = document.getElementById('recentExpirationsBody');
+ if (!tableBody) { console.warn("recentExpirationsBody not found for rendering warranties."); return; }
- // Determine status
- const expirationDate = new Date(warranty.expiration_date);
- let status = 'active';
+ const currentSearchTerm = searchWarranties && searchWarranties.value ? searchWarranties.value.toLowerCase() : '';
+ const currentStatusValue = statusFilter && statusFilter.value ? statusFilter.value : 'all';
- if (expirationDate <= today) {
- status = 'expired';
- } else {
+ 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>';
+ return;
+ }
+
+ const today = new Date();
+ today.setHours(0,0,0,0); // Normalize today to start of day for consistent comparisons
+
+ let displayWarranties = allWarranties.filter(w => {
+ const productName = (w.product_name || '').toLowerCase();
+ if (currentSearchTerm && !productName.includes(currentSearchTerm)) return false;
+
+ if (w.is_lifetime) {
+ if (currentStatusValue === 'expired' || currentStatusValue === 'expiring') return false;
+ return true; // Included in 'all' and 'active'
+ }
+
+ if (!w.expiration_date) return false; // Non-lifetime must have an expiration date
+ const expirationDate = new Date(w.expiration_date);
+ expirationDate.setHours(0,0,0,0); // Normalize for comparison
+
+ if (currentStatusValue === 'all') return true;
+ if (currentStatusValue === 'expired') return expirationDate <= today;
+
const timeDiff = expirationDate - today;
const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
+
+ if (currentStatusValue === 'expiring') return expirationDate > today && daysDiff <= EXPIRING_SOON_DAYS;
+ if (currentStatusValue === 'active') return expirationDate > today && daysDiff > EXPIRING_SOON_DAYS;
- if (daysDiff <= EXPIRING_SOON_DAYS) {
- status = 'expiring';
+ return true; // Should ideally not be reached if statusValue is one of the handled ones
+ });
+
+ displayWarranties.sort((a, b) => {
+ let valA, valB;
+ const aIsLifetime = a.is_lifetime;
+ const bIsLifetime = b.is_lifetime;
+
+ // Prioritize lifetime sort or handle them based on specific column
+ if (currentSort.column === 'status') {
+ valA = getStatusPriority(a.expiration_date, today, aIsLifetime);
+ valB = getStatusPriority(b.expiration_date, today, bIsLifetime);
+ } else {
+ if (aIsLifetime && !bIsLifetime) return -1;
+ if (!aIsLifetime && bIsLifetime) return 1;
+ if (aIsLifetime && bIsLifetime) {
+ valA = (a.product_name || '').toLowerCase();
+ valB = (b.product_name || '').toLowerCase();
+ } else {
+ switch (currentSort.column) {
+ case 'product': valA = (a.product_name || '').toLowerCase(); valB = (b.product_name || '').toLowerCase(); break;
+ case 'purchase': valA = new Date(a.purchase_date || 0); valB = new Date(b.purchase_date || 0); break;
+ default: valA = new Date(a.expiration_date || 0); valB = new Date(b.expiration_date || 0); // Default is expiration
+ }
+ }
}
+ if (valA instanceof Date && valB instanceof Date) return currentSort.direction === 'asc' ? valA.getTime() - valB.getTime() : valB.getTime() - valA.getTime();
+ if (typeof valA === 'number' && typeof valB === 'number') return currentSort.direction === 'asc' ? valA - valB : valB - valA;
+ if (typeof valA === 'string' && typeof valB === 'string') return currentSort.direction === 'asc' ? valA.localeCompare(valB) : valB.localeCompare(valA);
+ return 0;
+ });
+
+ if (displayWarranties.length === 0) {
+ tableBody.innerHTML = '<tr><td colspan="4" style="text-align:center; padding: 20px;">No warranties match your search criteria.</td></tr>';
+ return;
}
-
- row.className = `status-${status}`;
-
- // Format dates
- const purchaseDate = warranty.purchase_date ? new Date(warranty.purchase_date).toLocaleDateString() : 'N/A';
- const formattedExpirationDate = expirationDate.toLocaleDateString();
-
- // Status display
- let statusText = status === 'expired' ? 'Expired' : status === 'expiring' ? 'Expiring Soon' : 'Active';
- let statusClass = `status-${status}`;
-
- // Create table cells with proper structure
- row.innerHTML = `
- <td>${warranty.product_name || 'Unknown Product'}</td>
- <td>${purchaseDate}</td>
- <td>${formattedExpirationDate}</td>
- <td><span class="${statusClass}">${statusText}</span></td>
- `;
-
- tableBody.appendChild(row);
- });
-}
-// Get status priority for sorting (1: active, 2: expiring, 3: expired)
-function getStatusPriority(expirationDateStr, today) {
- const expirationDate = new Date(expirationDateStr);
+ displayWarranties.forEach(warranty => {
+ const row = tableBody.insertRow();
+ row.setAttribute('data-warranty-id', String(warranty.id)); // Ensure ID is string for dataset
+ row.style.cursor = 'pointer';
+
+ let statusText, statusClass;
+ const todayForStatus = new Date(); todayForStatus.setHours(0,0,0,0);
+
+ if (warranty.is_lifetime) {
+ statusText = '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 {
+ 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'; }
+ }
+ }
+ 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>
+ <td><span class="${statusClass}">${statusText}</span></td>
+ `; // Make sure escapeHTML is used on all string data from warranty
+ row.addEventListener('click', () => toggleWarrantyDetails(warranty.id, row));
+ });
+ }
- if (expirationDate <= today) {
- return 3; // Expired
- } else {
- const timeDiff = expirationDate - today;
+ function getStatusPriority(expirationDateStr, today, isLifetime = false) {
+ if (isLifetime) return 0;
+ if (!expirationDateStr) return 4;
+ const expirationDate = new Date(expirationDateStr);
+ expirationDate.setHours(0,0,0,0);
+ const todayNormalized = new Date(today); // Ensure today is also normalized if not already
+ todayNormalized.setHours(0,0,0,0);
+
+ if (isNaN(expirationDate.getTime())) return 4;
+ if (expirationDate <= todayNormalized) return 3;
+ const timeDiff = expirationDate - todayNormalized;
const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
-
- if (daysDiff <= EXPIRING_SOON_DAYS) {
- return 2; // Expiring soon
- } else {
- return 1; // Active
- }
+ if (daysDiff <= EXPIRING_SOON_DAYS) return 2;
+ return 1;
}
-}
-// Refresh the dashboard
-function refreshDashboard() {
- // Add loading animation to refresh button
- refreshDashboardBtn.classList.add('loading');
-
- // Initialize the dashboard
- initDashboard().finally(() => {
- // Remove loading animation
- refreshDashboardBtn.classList.remove('loading');
- });
-}
-
-// Initialize the dashboard
-async function initDashboard() {
- console.log('Initializing dashboard');
- try {
- showLoading();
- await loadUserPreferences(); // Load preferences first
-
- // Fetch data using the statistics endpoint
- const data = await fetchStatistics();
-
- // Log the raw response
- console.log('Raw API Response for /api/statistics:', data);
- if (data && typeof data === 'object') {
- console.log('API Response type:', typeof data);
- console.log('API Response keys:', Object.keys(data));
- } else {
- console.log('API Response type:', typeof data);
+ async function toggleWarrantyDetails(warrantyId, clickedRow, forceRefetch = false) {
+ const existingDetailsRow = clickedRow.nextElementSibling;
+ if (existingDetailsRow && existingDetailsRow.classList.contains('warranty-details-row')) {
+ existingDetailsRow.remove();
+ clickedRow.classList.remove('details-expanded');
+ return;
}
+ document.querySelectorAll('.warranty-details-row').forEach(r => r.remove());
+ document.querySelectorAll('tr.details-expanded').forEach(r => r.classList.remove('details-expanded'));
+ clickedRow.classList.add('details-expanded');
+ showLoading();
+ try {
+ let warrantyDetails = null;
- // *** UPDATED VALIDATION ***
- // Check for required top-level keys directly on the data object
- if (!data || typeof data !== 'object' || !('active' in data) || !('expired' in data)) {
- throw new Error(`Invalid data structure received from statistics API. Missing required keys (active, expired). Received: ${JSON.stringify(data)}`);
- }
+ if (!forceRefetch) {
+ warrantyDetails = allWarranties.find(w => String(w.id) === String(warrantyId));
+ }
- // *** USE DATA DIRECTLY (No 'summary' object) ***
- const recentWarranties = data.recent_warranties || [];
- const allWarrantiesData = data.all_warranties || recentWarranties; // Use all_warranties if available
+ // If forcing a refetch, or if cache lookup failed, or if cached data is deemed incomplete (e.g., missing notes)
+ if (forceRefetch || !warrantyDetails || !warrantyDetails.notes) {
+ if (forceRefetch) {
+ console.log(`[toggleWarrantyDetails] Force refetching details for warranty ID: ${warrantyId}`);
+ } else if (!warrantyDetails) {
+ console.warn(`[toggleWarrantyDetails] Warranty ID: ${warrantyId} not found in local cache. Fetching.`);
+ } else { // Implies !warrantyDetails.notes or other incompleteness checks in future
+ console.warn(`[toggleWarrantyDetails] Warranty details for ID: ${warrantyId} in cache are incomplete. Fetching.`);
+ }
- // *** ADD LOGGING HERE ***
- console.log('API Data received:', JSON.stringify(data, null, 2)); // Log the whole data object
- console.log('Does data have all_warranties?', data.hasOwnProperty('all_warranties'));
- if (data.hasOwnProperty('all_warranties')) {
- console.log('Length of data.all_warranties:', data.all_warranties ? data.all_warranties.length : 'null/undefined');
- }
- console.log('Length of data.recent_warranties:', recentWarranties.length);
- console.log('Content being assigned to global allWarranties:', JSON.stringify(allWarrantiesData, null, 2));
- // *** END LOGGING ***
-
- // Store data for potential redraws, directly from 'data'
- currentStatusData = {
- active: data.active || 0,
- expiring_soon: data.expiring_soon || 0,
- expired: data.expired || 0,
- total: data.total || 0 // Include total if needed
- };
- currentTimelineData = extractTimelineData(allWarrantiesData); // Use all warranties for timeline
-
- // Update UI using the structured data
- updateSummaryCounts(currentStatusData); // Pass the structured status data
- createStatusChart(currentStatusData); // Pass the structured status data
- createTimelineChart(currentTimelineData);
- allWarranties = allWarrantiesData; // Store for filtering
- console.log('Global allWarranties length AFTER assignment:', allWarranties.length); // Log length after assignment
- filterAndSortWarranties(); // Apply initial filters/sort to the table
-
- // Attach sort listeners *after* initial render
- attachSortListeners();
-
- // Re-add other listeners previously in setupEventListeners
- const searchInput = document.getElementById('searchWarranties');
- const filterSelect = document.getElementById('statusFilter');
- const exportDataBtn = document.getElementById('exportBtn');
- const refreshBtn = document.getElementById('refreshDashboardBtn'); // Use the correct ID
-
- if (refreshBtn) {
- // Avoid adding multiple listeners if initDashboard is called again
- if (!refreshBtn.hasAttribute('data-listener-added')) {
- refreshBtn.addEventListener('click', refreshDashboard); // Call the refresh wrapper
- refreshBtn.setAttribute('data-listener-added', 'true');
+ const token = window.auth.getToken();
+ if (!token) throw new Error('Authentication token not available.');
+ const response = await fetch(`/api/debug/warranty/${warrantyId}`, { headers: { 'Authorization': `Bearer ${token}` }});
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to fetch full warranty details for toggle.');
+ }
+ const fetchedData = await response.json();
+ if (!fetchedData) throw new Error('Warranty data not found in fetch response for toggle.');
+
+ // API might return { warranty: {...} } or just {...}
+ warrantyDetails = fetchedData.warranty ? fetchedData.warranty : fetchedData;
+
+ // Update allWarranties cache in status.js with this fresh data
+ const index = allWarranties.findIndex(w => String(w.id) === String(warrantyId));
+ if (index !== -1) {
+ // Merge to preserve any local-only properties if necessary, though fetched should be canonical here
+ allWarranties[index] = {...allWarranties[index], ...warrantyDetails};
+ console.log(`[toggleWarrantyDetails] Updated allWarranties cache for ID ${warrantyId} with fetched details.`);
+ } else {
+ allWarranties.push(warrantyDetails); // Should be rare if initDashboard ran
+ console.log(`[toggleWarrantyDetails] Added fetched details for ID ${warrantyId} to allWarranties cache as it was not found.`);
+ }
}
- }
- if (searchInput) {
- if (!searchInput.hasAttribute('data-listener-added')) {
- searchInput.addEventListener('input', filterAndSortWarranties);
- searchInput.setAttribute('data-listener-added', 'true');
+
+ // At this point, warrantyDetails should be the one we want to render.
+ // If forceRefetch was true, it's the data just fetched.
+ // If forceRefetch was false, it's from cache.
+ console.log('[toggleWarrantyDetails] FINAL warrantyDetails object to be rendered:', JSON.parse(JSON.stringify(warrantyDetails)));
+
+ // Normalize paths in warrantyDetails, regardless of source (cache or fetch)
+ warrantyDetails.invoice_path = warrantyDetails.invoice_path || null;
+ warrantyDetails.manual_path = warrantyDetails.manual_path || null;
+ warrantyDetails.other_document_path = warrantyDetails.other_document_path || null;
+
+ const detailsRow = document.createElement('tr');
+ detailsRow.classList.add('warranty-details-row');
+ const detailsCell = document.createElement('td');
+ detailsCell.colSpan = clickedRow.cells.length;
+ detailsCell.style.padding = '15px';
+ detailsCell.style.backgroundColor = 'var(--details-bg, #f9f9f9)';
+
+ let dHtml = '<div class="warranty-details-content" style="display: flex; flex-wrap: wrap; gap: 20px;">';
+ 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 += '<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>';
+ dHtml += '</div>';
+
+ // DEBUG: Log serial numbers before rendering them in details view
+ console.log('[toggleWarrantyDetails] Serial numbers in warrantyDetails before rendering HTML:', JSON.parse(JSON.stringify(warrantyDetails.serial_numbers || [])));
+
+ if (warrantyDetails.serial_numbers && warrantyDetails.serial_numbers.length > 0) {
+ dHtml += '<div style="flex: 1 1 300px;"><h4>Serial Numbers</h4><ul>';
+ warrantyDetails.serial_numbers.forEach(sn => { // Assuming sn is an object {serial_number: "value"}
+ dHtml += `<li>${escapeHTML(sn.serial_number || sn)}</li>`; // Handle if sn is string or object
+ });
+ dHtml += '</ul></div>';
}
- }
- if (filterSelect) {
- if (!filterSelect.hasAttribute('data-listener-added')) {
- filterSelect.addEventListener('change', filterAndSortWarranties);
- filterSelect.setAttribute('data-listener-added', 'true');
+ if (warrantyDetails.notes && String(warrantyDetails.notes).trim() !== '') {
+ dHtml += '<div style="flex: 1 1 100%; margin-top: 10px;"><h4>Notes</h4>';
+ dHtml += `<pre style="white-space: pre-wrap; word-wrap: break-word; background-color: var(--notes-bg, #efefef); padding: 10px; border-radius: 4px;">${escapeHTML(warrantyDetails.notes)}</pre></div>`;
}
+ dHtml += '</div>'; // end warranty-details-content
+ dHtml += '<div class="warranty-details-actions" style="margin-top: 15px; text-align: right;">';
+ dHtml += `<button class="btn btn-primary edit-warranty-status-btn" data-warranty-id="${warrantyDetails.id}">Edit Warranty</button></div>`;
+
+ detailsCell.innerHTML = dHtml;
+ detailsRow.appendChild(detailsCell);
+ clickedRow.parentNode.insertBefore(detailsRow, clickedRow.nextSibling);
+ } catch (error) {
+ console.error('Error in toggleWarrantyDetails (status.js IIFE):', error);
+ showToast(`Error: ${error.message}`, 'error');
+ } finally {
+ hideLoading();
}
- if (exportDataBtn) {
- if (!exportDataBtn.hasAttribute('data-listener-added')) {
- exportDataBtn.addEventListener('click', exportWarrantyData);
- exportDataBtn.setAttribute('data-listener-added', 'true');
+ }
+
+ function escapeHTML(str) {
+ if (str === null || str === undefined) return '';
+ return String(str).replace(/[&<>"'\/]/g, s => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;','/':'&#x2F;'})[s]);
+ }
+
+ function refreshDashboard() {
+ console.log("Refreshing dashboard from status.js IIFE...");
+ if (refreshDashboardBtn) refreshDashboardBtn.classList.add('loading');
+ initDashboard().finally(() => {
+ if (refreshDashboardBtn) refreshDashboardBtn.classList.remove('loading');
+ });
+ }
+
+ async function initDashboard() {
+ 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 = [];
+ 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 || [];
+ }
+ } else {
+ 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) {
+ 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([]);
+ }
+ // --- 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();
}
- console.log("Attached other listeners (search, filter, export, refresh).")
-
- hideLoading();
- } catch (error) {
- console.error('Error initializing dashboard:', error);
- // Display error appropriately using showError function
- showError(error.message || 'Failed to load dashboard', error.stack);
- } finally {
- hideLoading(); // Ensure loading is hidden even on error
}
-}
-// Helper function to extract timeline data from warranties
-function extractTimelineData(warranties) {
- // Create a map to store counts by month and year
- const timelineMap = new Map();
-
- // Get current date for reference
- const today = new Date();
-
- // Process each warranty
- warranties.forEach(warranty => {
- if (warranty.expiration_date) {
- const expDate = new Date(warranty.expiration_date);
- const month = expDate.getMonth() + 1; // 1-12
- const year = expDate.getFullYear();
-
- // Create a key for this month/year
- const key = `${year}-${month}`;
-
- // Increment the count for this month/year
- if (timelineMap.has(key)) {
- timelineMap.set(key, timelineMap.get(key) + 1);
+ async function loadUserPreferences() {
+ try {
+ if (!window.auth || !window.auth.getToken()) { console.warn('Auth or token not available for prefs in status.js'); return; }
+ const token = window.auth.getToken();
+ const response = await fetch('/api/auth/preferences', { headers: { 'Authorization': `Bearer ${token}` } });
+ if (response.ok) {
+ const prefs = await response.json();
+ if (prefs && prefs.expiring_soon_days !== undefined) { // Check for undefined specifically
+ EXPIRING_SOON_DAYS = parseInt(prefs.expiring_soon_days, 10);
+ console.log('Loaded EXPIRING_SOON_DAYS from prefs (status.js IIFE):', EXPIRING_SOON_DAYS);
+ }
+ if (prefs && prefs.currency_symbol) {
+ userCurrencySymbol = prefs.currency_symbol;
+ console.log('Loaded currency_symbol from prefs (status.js IIFE):', userCurrencySymbol);
+ }
} else {
- timelineMap.set(key, 1);
+ console.warn("Failed to load user preferences in status.js, status:", response.status);
}
- }
- });
-
- // Convert the map to an array of objects
- const timeline = Array.from(timelineMap.entries()).map(([key, count]) => {
- const [year, month] = key.split('-').map(Number);
- return { year, month, count };
- });
-
- // Sort by date
- timeline.sort((a, b) => {
- if (a.year !== b.year) return a.year - b.year;
- return a.month - b.month;
- });
+ } catch (error) { console.error('Error loading user preferences (status.js IIFE):', error); }
+ }
- return timeline;
-}
-
-// Function to load user preferences
-async function loadUserPreferences() {
- try {
- // Get the auth token
- const token = localStorage.getItem('auth_token');
- if (!token) return;
-
- // Get preferences from API
- const response = await fetch('/api/auth/preferences', {
- headers: {
- 'Authorization': `Bearer ${token}`
+ function attachSortListeners() { // DEFINITION ENSURED INSIDE IIFE
+ const headers = document.querySelectorAll('#recentExpirationsTable th.sortable');
+ headers.forEach(header => {
+ const newHeader = header.cloneNode(true); // Re-clone to ensure clean listeners
+ if (header.parentNode) {
+ header.parentNode.replaceChild(newHeader, header);
+ } else {
+ console.warn("Header's parentNode is null, cannot attach sort listener:", header);
+ return; // Skip if header isn't properly in DOM
}
+ newHeader.addEventListener('click', () => {
+ const column = newHeader.getAttribute('data-sort');
+ if (currentSort.column === column) {
+ currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
+ } else {
+ currentSort.column = column;
+ currentSort.direction = 'asc';
+ }
+ // TODO: Implement updateSortHeaderClasses() to visually show sort direction
+ filterAndSortWarranties();
+ });
});
-
- if (response.ok) {
- const data = await response.json();
- if (data && data.expiring_soon_days) {
- EXPIRING_SOON_DAYS = data.expiring_soon_days;
- console.log('Loaded expiring soon days from preferences:', EXPIRING_SOON_DAYS);
- }
- }
- } catch (error) {
- console.error('Error loading user preferences:', error);
+ console.log("Attached sort listeners (status.js IIFE). Found headers:", headers.length);
}
-}
+
+ document.addEventListener('click', async function(event) {
+ if (event.target && event.target.classList.contains('edit-warranty-status-btn')) {
+ const warrantyId = event.target.dataset.warrantyId;
+ if (!warrantyId) { showToast('Cannot edit warranty: ID is missing.', 'error'); return; }
+ console.log(`Edit button clicked for warranty ID (status.js IIFE): ${warrantyId}`);
+ showLoading();
+ let finalWarrantyForModal = null;
+
+ try {
+ // ALWAYS fetch fresh details when editing from the status page to ensure modal has latest data.
+ console.log(`[DEBUG status.js] Edit from status page for warranty ${warrantyId}. ALWAYS fetching fresh details from /api/debug/warranty/:id.`);
+ showLoadingSpinner(); // Show spinner for this specific fetch
+ const token = localStorage.getItem('auth_token') || (window.auth && window.auth.getToken());
+ if (!token) throw new Error('Authentication token not available for fetching fresh details.');
+
+ const response = await fetch(`/api/debug/warranty/${warrantyId}`, {
+ method: 'GET',
+ headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.message || `Failed to fetch fresh warranty details: ${response.status}`);
+ }
-// Update the sort header classes
-function updateSortHeaderClasses() {
- sortableHeaders.forEach(header => {
- const column = header.getAttribute('data-sort');
- header.classList.remove('sort-asc', 'sort-desc');
-
- if (column === currentSort.column) {
- header.classList.add(currentSort.direction === 'asc' ? 'sort-asc' : 'sort-desc');
- }
- });
-}
-
-// Function to display overall status counts
-function displayStatus(data) {
- document.getElementById('totalCount').textContent = data.total_count;
- document.getElementById('activeCount').textContent = data.active_count;
- document.getElementById('expiringCount').textContent = data.expiring_soon_count;
- document.getElementById('expiredCount').textContent = data.expired_count;
-}
-
-// Function to display errors
-function displayError(error) {
- const statusContent = document.getElementById('statusContent'); // Assuming a main container
- if (!statusContent) return;
- statusContent.innerHTML = `
- <div class="error-message">
- <i class="fas fa-exclamation-triangle"></i>
- <h3>Failed to Load Status</h3>
- <p>Could not retrieve warranty status data. Please try again later.</p>
- <p>Error: ${error.message}</p>
- </div>
- `;
-}
-
-// Function to display recently expired/expiring warranties in the table
-function displayRecentExpirations(expirations) {
- const tableBody = document.getElementById('recentExpirationsTableBody');
- if (!tableBody) return;
-
- tableBody.innerHTML = ''; // Clear existing rows
-
- if (!expirations || expirations.length === 0) {
- tableBody.innerHTML = '<tr class="empty-row"><td colspan="5" class="no-data">No warranties expiring soon or recently expired.</td></tr>';
- return;
- }
+ let freshlyFetchedWarranty = await response.json();
+ // IMPORTANT: Check if the API nests the warranty object (e.g., under a 'warranty' key)
+ if (freshlyFetchedWarranty && freshlyFetchedWarranty.warranty && typeof freshlyFetchedWarranty.warranty === 'object') {
+ freshlyFetchedWarranty = freshlyFetchedWarranty.warranty;
+ }
- expirations.forEach(warranty => {
- const row = tableBody.insertRow();
- const statusClass = warranty.status.toLowerCase().replace('_', '-'); // e.g., expiring-soon
- row.classList.add(`status-${statusClass}`);
+ hideLoadingSpinner();
+ console.log(`[DEBUG status.js] Freshly fetched warranty data (from /api/debug/warranty):`, JSON.parse(JSON.stringify(freshlyFetchedWarranty)));
+
+ // Start with freshly fetched data as the base
+ finalWarrantyForModal = { ...freshlyFetchedWarranty };
+
+ // Attempt to get from cache just for potentially more complete local-only properties if needed (e.g. if API is sometimes slow to update derived fields)
+ // This is a cautious approach; ideally, freshlyFetchedWarranty is canonical.
+ let cachedWarranty = allWarranties.find(w => String(w.id) === String(warrantyId));
+ if (cachedWarranty) {
+ console.log(`[DEBUG status.js] Also found cached warranty for ID ${warrantyId}:`, JSON.parse(JSON.stringify(cachedWarranty)));
+ // Merge tags: Prioritize tags from cachedWarranty if available and fresh data lacks them or has empty
+ if (Array.isArray(cachedWarranty.tags) && cachedWarranty.tags.length > 0 &&
+ (!finalWarrantyForModal.hasOwnProperty('tags') || (Array.isArray(finalWarrantyForModal.tags) && finalWarrantyForModal.tags.length === 0))) {
+ console.log(`[DEBUG status.js] Using tags from cachedWarranty. Tags from cache:`, cachedWarranty.tags);
+ finalWarrantyForModal.tags = cachedWarranty.tags;
+ } else if (!finalWarrantyForModal.hasOwnProperty('tags') || !Array.isArray(finalWarrantyForModal.tags)) {
+ console.log(`[DEBUG status.js] No valid 'tags' property in fresh or cached. Defaulting to empty array. Current final.tags:`, finalWarrantyForModal.tags);
+ finalWarrantyForModal.tags = [];
+ }
- // Calculate days remaining/past
- let daysText = 'N/A';
- if (warranty.days_remaining !== null) {
- if (warranty.days_remaining < 0) {
- daysText = `${Math.abs(warranty.days_remaining)} days ago`;
- } else {
- daysText = `in ${warranty.days_remaining} days`;
+ // Merge/Format serial_numbers: Prioritize cached if simple array and fresh data has objects or is missing.
+ // This logic might need refinement based on consistent API output for serials.
+ const cachedSerialsAreSimpleArray = Array.isArray(cachedWarranty.serial_numbers) &&
+ (cachedWarranty.serial_numbers.length === 0 || typeof cachedWarranty.serial_numbers[0] === 'string');
+
+ if (cachedSerialsAreSimpleArray && cachedWarranty.serial_numbers.length > 0 &&
+ (!Array.isArray(finalWarrantyForModal.serial_numbers) || typeof finalWarrantyForModal.serial_numbers[0] === 'object')) {
+ console.log(`[DEBUG status.js] Using serial_numbers from cachedWarranty (simple array). Serials:`, cachedWarranty.serial_numbers);
+ finalWarrantyForModal.serial_numbers = cachedWarranty.serial_numbers;
+ } else if (Array.isArray(finalWarrantyForModal.serial_numbers) && finalWarrantyForModal.serial_numbers.length > 0 && typeof finalWarrantyForModal.serial_numbers[0] === 'object') {
+ console.log(`[DEBUG status.js] Freshly fetched serial_numbers are objects. Mapping to strings. Original:`, finalWarrantyForModal.serial_numbers);
+ finalWarrantyForModal.serial_numbers = finalWarrantyForModal.serial_numbers
+ .map(snObj => snObj && snObj.serial_number)
+ .filter(sn => typeof sn === 'string' && sn.trim() !== '');
+ } else if (!Array.isArray(finalWarrantyForModal.serial_numbers) ||
+ (Array.isArray(finalWarrantyForModal.serial_numbers) && finalWarrantyForModal.serial_numbers.length > 0 && typeof finalWarrantyForModal.serial_numbers[0] !== 'string')){
+ console.log(`[DEBUG status.js] serial_numbers in final object is not a simple array of strings. Defaulting to empty array. Current serials:`, finalWarrantyForModal.serial_numbers);
+ finalWarrantyForModal.serial_numbers = [];
+ }
+
+ // Vendor: Prioritize cached if available and fresh data lacks it or is empty
+ if (typeof cachedWarranty.vendor === 'string' && cachedWarranty.vendor.trim() !== '' &&
+ (typeof finalWarrantyForModal.vendor !== 'string' || finalWarrantyForModal.vendor.trim() === '')) {
+ console.log(`[DEBUG status.js] Using vendor from cachedWarranty. Vendor:`, cachedWarranty.vendor);
+ finalWarrantyForModal.vendor = cachedWarranty.vendor;
+ }
+ }
+ // Ensure vendor is at least an empty string if null/undefined after merging attempts
+ if (typeof finalWarrantyForModal.vendor !== 'string') {
+ console.log(`[DEBUG status.js] Vendor in final object is not a string after potential merge. Defaulting to empty string. Current vendor:`, finalWarrantyForModal.vendor);
+ finalWarrantyForModal.vendor = '';
+ }
+
+ if (!finalWarrantyForModal) {
+ throw new Error('Failed to prepare warranty data for the modal.');
+ }
+
+ // --- Date Formatting - CRITICAL: Ensure dates are YYYY-MM-DD strings for the modal ---
+ console.log(`[DEBUG status.js] Before date formatting - Purchase Date: ${finalWarrantyForModal.purchase_date}, Type: ${typeof finalWarrantyForModal.purchase_date}`);
+ console.log(`[DEBUG status.js] Before date formatting - Expiration Date: ${finalWarrantyForModal.expiration_date}, Type: ${typeof finalWarrantyForModal.expiration_date}`);
+
+ if (finalWarrantyForModal.purchase_date) {
+ try {
+ finalWarrantyForModal.purchase_date = formatDateYYYYMMDD(new Date(finalWarrantyForModal.purchase_date));
+ } catch (e) {
+ console.error(`Error formatting purchase_date ('${finalWarrantyForModal.purchase_date}'):`, e);
+ // Decide on fallback: keep as is, or set to null/empty string if critical for modal
+ // For now, let's log and keep it, openEditModal might handle it or throw error.
+ }
+ }
+
+ if (finalWarrantyForModal.is_lifetime) {
+ finalWarrantyForModal.expiration_date = null; // Lifetime warranties shouldn't have an expiration date for the form
+ } else if (finalWarrantyForModal.expiration_date) {
+ try {
+ finalWarrantyForModal.expiration_date = formatDateYYYYMMDD(new Date(finalWarrantyForModal.expiration_date));
+ } catch (e) {
+ console.error(`Error formatting expiration_date ('${finalWarrantyForModal.expiration_date}'):`, e);
+ }
+ }
+ // Ensure all essential fields for the modal are present, even if null
+ finalWarrantyForModal.product_name = finalWarrantyForModal.product_name || '';
+ finalWarrantyForModal.tags = finalWarrantyForModal.tags || [];
+ finalWarrantyForModal.serial_numbers = finalWarrantyForModal.serial_numbers || [];
+ finalWarrantyForModal.vendor = finalWarrantyForModal.vendor || ''; // Added explicit fallback for vendor
+ finalWarrantyForModal.warranty_duration_years = finalWarrantyForModal.warranty_duration_years || 0;
+ finalWarrantyForModal.warranty_duration_months = finalWarrantyForModal.warranty_duration_months || 0;
+ finalWarrantyForModal.warranty_duration_days = finalWarrantyForModal.warranty_duration_days || 0;
+ // Ensure file paths are present, default to null if not
+ finalWarrantyForModal.invoice_path = finalWarrantyForModal.invoice_path || null;
+ finalWarrantyForModal.manual_path = finalWarrantyForModal.manual_path || null;
+ finalWarrantyForModal.other_document_path = finalWarrantyForModal.other_document_path || null;
+
+ console.log('[DEBUG status.js] Final warranty object being passed to openEditModal (full object):', JSON.parse(JSON.stringify(finalWarrantyForModal)));
+ console.log(`[DEBUG status.js] Final Tags:`, JSON.stringify(finalWarrantyForModal.tags));
+ console.log(`[DEBUG status.js] Final Serial Numbers:`, JSON.stringify(finalWarrantyForModal.serial_numbers));
+ console.log(`[DEBUG status.js] Final Vendor: '${finalWarrantyForModal.vendor}'`);
+
+ if (typeof window.openEditModal === 'function') {
+ window.currentEditingWarrantyIdStatusPage = warrantyId; // For observer
+ 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.");
+ }
+
+ } catch (error) {
+ console.error('Error preparing for editing (status.js IIFE):', error);
+ showToast(`Error: ${error.message || 'Could not load warranty details for editing.'}`, 'error');
+ } finally {
+ hideLoading(); // Hide main page loading, spinner for fetch is handled separately
}
}
-
- row.innerHTML = `
- <td>${warranty.product_name}</td>
- <td>${new Date(warranty.purchase_date).toLocaleDateString()}</td>
- <td>${new Date(warranty.expiration_date).toLocaleDateString()} (${daysText})</td>
- <td><span class="status-${statusClass}">${warranty.status.replace('_', ' ')}</span></td>
- `;
});
-}
-
-// Export warranty data as CSV
-function exportWarrantyData() {
- // Get filtered and sorted warranties based on current view state
- const searchTerm = document.getElementById('searchWarranties').value.toLowerCase();
- const statusValue = document.getElementById('statusFilter').value;
- const today = new Date();
+
+ // Save Warranty Observer logic (for refreshing after edit)
+ if (typeof window.setupSaveWarrantyObserver !== 'function') { // Define only if not already defined (e.g. by script.js)
+ window.setupSaveWarrantyObserver = (originalSaveFunction) => {
+ return async function() { // This is the wrapper function
+ const originalArguments = arguments; // Capture original arguments for the save function
+ let warrantyIdToReopen = null;
+
+ // Check if the edit was initiated from the status page *before* saving
+ if (window.currentEditingWarrantyIdStatusPage) {
+ warrantyIdToReopen = window.currentEditingWarrantyIdStatusPage;
+ console.log(`[Observer status.js] Edit initiated from status page. Captured warrantyIdToReopen: ${warrantyIdToReopen}`);
+ } else {
+ console.log(`[Observer status.js] Edit NOT initiated from status page (window.currentEditingWarrantyIdStatusPage is falsy).`);
+ }
+
+ // Call the original save function (e.g., window.saveWarranty from script.js)
+ const result = await originalSaveFunction.apply(this, originalArguments);
+ console.log(`[Observer status.js] Original save function completed. Result:`, result);
+
+ // After the save is complete and if it was a status page edit:
+ console.log(`[Observer status.js] Checking condition to refresh dashboard. warrantyIdToReopen value: "${warrantyIdToReopen}"`);
+ if (warrantyIdToReopen) {
+ console.log(`[Observer status.js] Condition PASSED. Warranty ID ${warrantyIdToReopen} found. Refreshing dashboard and scheduling details re-open.`);
+ console.log(`[Observer status.js] Warranty update detected for ID: ${warrantyIdToReopen}. Refreshing dashboard.`);
+ showToast('Warranty updated. Refreshing list...', 'success');
+
+ // Refresh the dashboard (which re-fetches and re-renders the table)
+ await initDashboard();
+
+ // After dashboard refresh, find and re-open the details for the edited warranty
+ // Use a timeout to allow the DOM to fully update after initDashboard
+ setTimeout(() => {
+ console.log(`[Observer status.js] setTimeout: Attempting to re-open details for ID: ${warrantyIdToReopen}`);
+ if (!warrantyIdToReopen) {
+ console.error("[Observer status.js] setTimeout: warrantyIdToReopen is NULL or undefined! Cannot re-open.");
+ delete window.currentEditingWarrantyIdStatusPage;
+ return;
+ }
+
+ const rowSelector = `#recentExpirationsBody tr[data-warranty-id="${warrantyIdToReopen}"]`;
+ console.log(`[Observer status.js] setTimeout: Looking for row with selector: "${rowSelector}"`);
+ const rowToReopen = document.querySelector(rowSelector);
+
+ if (rowToReopen) {
+ console.log(`[Observer status.js] setTimeout: Found row for warranty ID: ${warrantyIdToReopen}. Calling toggleWarrantyDetails.`);
+ try {
+ toggleWarrantyDetails(warrantyIdToReopen, rowToReopen, true); // Pass true for forceRefetch
+ console.log(`[Observer status.js] setTimeout: toggleWarrantyDetails called successfully for ID: ${warrantyIdToReopen}`);
+ } catch (e) {
+ console.error(`[Observer status.js] setTimeout: Error calling toggleWarrantyDetails for ID ${warrantyIdToReopen}:`, e);
+ }
+ } else {
+ console.warn(`[Observer status.js] setTimeout: Could NOT find row for warranty ID ${warrantyIdToReopen} after refresh. Selector used: "${rowSelector}"`);
+ }
+ // It's crucial to clean up the global flag after we're done with it.
+ delete window.currentEditingWarrantyIdStatusPage;
+ console.log(`[Observer status.js] Cleaned up window.currentEditingWarrantyIdStatusPage for ID: ${warrantyIdToReopen}`);
+ }, 100); // 100ms delay, can be adjusted if necessary
+
+ }
+ return result; // Return the result of the original save function
+ };
+ };
+ }
- // Filter warranties (similar logic to filterAndSortWarranties)
- let filteredWarranties = allWarranties.filter(warranty => {
- const productName = (warranty.product_name || '').toLowerCase();
- const matchesSearch = searchTerm === '' || productName.includes(searchTerm);
- if (!matchesSearch) return false;
-
- if (statusValue === 'all') return true;
- if (!warranty.expiration_date) return false;
-
- const expirationDate = new Date(warranty.expiration_date);
- if (statusValue === 'expired') return expirationDate <= today;
+ // 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.');
- const timeDiff = expirationDate - today;
- const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
-
- if (statusValue === 'expiring') return expirationDate > today && daysDiff <= EXPIRING_SOON_DAYS;
- if (statusValue === 'active') return expirationDate > today && daysDiff > EXPIRING_SOON_DAYS;
-
- return false; // Should not happen if statusValue is valid
- });
-
- // Sort warranties based on current sort settings
- filteredWarranties.sort((a, b) => {
- let valueA, valueB;
- switch (currentSort.column) {
- case 'product': valueA = a.product_name || ''; valueB = b.product_name || ''; break;
- case 'purchase': valueA = new Date(a.purchase_date || 0); valueB = new Date(b.purchase_date || 0); break;
- case 'status': valueA = getStatusPriority(a.expiration_date, today); valueB = getStatusPriority(b.expiration_date, today); break;
- default: valueA = new Date(a.expiration_date || 0); valueB = new Date(b.expiration_date || 0); // Default to expiration
- }
- if (currentSort.direction === 'asc') {
- return valueA > valueB ? 1 : valueA < valueB ? -1 : 0;
+ const headerDarkModeToggle = document.getElementById('darkModeToggle');
+ if (headerDarkModeToggle) {
+ headerDarkModeToggle.addEventListener('change', function() {
+ setTheme(this.checked); // IIFE's setTheme (manages data-theme and localStorage)
+ redrawChartsWithNewTheme(); // IIFE's redraw (manages status page charts)
+ });
} else {
- return valueA < valueB ? 1 : valueA > valueB ? -1 : 0;
+ console.log('Header darkModeToggle not found by status.js for direct listener attachment. Theme changes via localStorage/theme-loader.js should still work.');
}
- });
-
- if (filteredWarranties.length === 0) {
- showToast('No data to export based on current filters', 'warning');
- return;
- }
-
- // Create CSV content
- let csvContent = 'Product,Purchase Date,Expiration Date,Status\n';
- filteredWarranties.forEach(warranty => {
- const purchaseDate = warranty.purchase_date ? new Date(warranty.purchase_date).toLocaleDateString() : 'N/A';
- const expirationDate = warranty.expiration_date ? new Date(warranty.expiration_date).toLocaleDateString() : 'N/A';
- const status = getStatusText(warranty.expiration_date, today);
- const escapedProductName = (warranty.product_name || '').includes(',')
- ? `"${warranty.product_name}"`
- : warranty.product_name;
- csvContent += `${escapedProductName},${purchaseDate},${expirationDate},${status}\n`;
- });
-
- // Create download link
- const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
- const url = URL.createObjectURL(blob);
- const link = document.createElement('a');
- link.setAttribute('href', url);
- link.setAttribute('download', 'warranty_status_export.csv');
- link.style.visibility = 'hidden';
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- URL.revokeObjectURL(url); // Clean up blob URL
- showToast('Data exported successfully', 'success');
-}
-
-// Helper to get status text
-function getStatusText(expirationDateStr, today) {
- if (!expirationDateStr) return 'Unknown';
- const expirationDate = new Date(expirationDateStr);
- if (expirationDate <= today) return 'Expired';
- const timeDiff = expirationDate - today;
- const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
- if (daysDiff <= EXPIRING_SOON_DAYS) return 'Expiring Soon';
- return 'Active';
-}
-
-// Define attachSortListeners globally within the script scope
-function attachSortListeners() {
- const headers = document.querySelectorAll('.sortable');
- headers.forEach(header => {
- // Clear potentially existing listener to prevent duplicates if this is called multiple times
- // A more robust way might involve checking if a listener already exists, but this is simpler
- const newHeader = header.cloneNode(true);
- header.parentNode.replaceChild(newHeader, header);
-
- newHeader.addEventListener('click', () => {
- const column = newHeader.getAttribute('data-sort');
- if (currentSort.column === column) {
- currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
+
+ initDashboard(); // Call IIFE's initDashboard
+
+ // Setup event listeners for status page specific controls
+ if (refreshDashboardBtn) refreshDashboardBtn.addEventListener('click', refreshDashboard);
+ if (searchWarranties) searchWarranties.addEventListener('input', filterAndSortWarranties);
+ if (statusFilter) statusFilter.addEventListener('change', filterAndSortWarranties);
+ if (exportBtn) {
+ exportBtn.addEventListener('click', function() {
+ console.log("Status page export button clicked (status.js IIFE).");
+ // Placeholder for actual export logic for status page data
+ showToast('Export for status page table not fully implemented yet.', 'info');
+ });
+ }
+ attachSortListeners(); // Call IIFE's attachSortListeners
+
+ // Simplified attempt to wrap saveWarranty from script.js, within DOMContentLoaded
+ setTimeout(() => {
+ if (typeof window.saveWarranty === 'function' && window.saveWarrantyObserverAttachedByStatus !== true) {
+ console.log('(STATUS.JS) Attempting to wrap window.saveWarranty via DOMContentLoaded/setTimeout.');
+ const originalSave = window.saveWarranty;
+ window.saveWarranty = window.setupSaveWarrantyObserver(originalSave);
+ window.saveWarrantyObserverAttachedByStatus = true;
+ console.log('(STATUS.JS) window.saveWarranty hopefully WRAPPED by DOMContentLoaded/setTimeout.');
+ } else if (window.saveWarrantyObserverAttachedByStatus === true) {
+ console.log('(STATUS.JS) window.saveWarranty ALREADY WRAPPED (checked in DOMContentLoaded/setTimeout).');
+ } else if (typeof window.saveWarranty !== 'function') {
+ console.warn(`(STATUS.JS) DOMContentLoaded/setTimeout: window.saveWarranty NOT FOUND. Observer NOT attached.`);
} else {
- currentSort.column = column;
- currentSort.direction = 'asc';
+ console.warn(`(STATUS.JS) DOMContentLoaded/setTimeout: window.saveWarranty found, but NOT WRAPPED (flag: ${window.saveWarrantyObserverAttachedByStatus}). Observer NOT attached.`);
}
- updateSortHeaderClasses();
- filterAndSortWarranties();
- });
+ }, 500); // Delay by 500ms
});
- console.log("Attached sort listeners.");
-}
-
-// --- Initialization ---
-// IMPORTANT: Ensure ALL function definitions are ABOVE this listener
-document.addEventListener('DOMContentLoaded', () => {
- console.log('Status page DOM loaded');
- // showLoading(); // Loading is shown inside initDashboard
-
- // Initialize theme toggle state *after* DOM is loaded
- if (darkModeToggle) {
- const currentTheme = document.documentElement.getAttribute('data-theme');
- darkModeToggle.checked = currentTheme === 'dark';
- darkModeToggle.addEventListener('change', function() {
- setTheme(this.checked);
- redrawChartsWithNewTheme();
- });
- console.log(`Initialized theme toggle to: ${darkModeToggle.checked ? 'dark' : 'light'}`);
- }
-
- // Initialize the main dashboard logic
- initDashboard();
-
- // Setup event listeners for search/filter/export/sort
- // setupEventListeners(); // Removed: listeners now attached in initDashboard
-
- // Setup settings menu (assuming it's part of the shared header)
- // if (typeof setupSettingsMenu === 'function') {
- // setupSettingsMenu();
- // } else if (window.auth && typeof window.auth.setupSettingsMenu === 'function') {
- // window.auth.setupSettingsMenu();
- // }
-});
\ No newline at end of file
+})();
diff --git a/frontend/style.css b/frontend/style.css
index 2f0a6de..3b6a795 100644
--- a/frontend/style.css
+++ b/frontend/style.css
@@ -1,3 +1,31 @@
+/* Center the Edit Warranty button in the status page details row */
+.warranty-details-actions {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ margin-top: 15px;
+}
+/* Make the Edit Warranty button on the status page details row minimal: blue outline, no fill, only around text */
+.edit-warranty-status-btn {
+ background: transparent !important;
+ color: var(--primary-color) !important;
+ border: 2px solid var(--primary-color) !important;
+ border-radius: 6px !important;
+ font-size: 1rem !important;
+ font-weight: 500;
+ padding: 4px 18px !important;
+ min-width: unset !important;
+ width: auto !important;
+ height: auto !important;
+ box-shadow: none !important;
+ transition: background 0.2s, color 0.2s, border-color 0.2s;
+ display: inline-block;
+}
+.edit-warranty-status-btn:hover, .edit-warranty-status-btn:focus {
+ background: var(--primary-color) !important;
+ color: #fff !important;
+ border-color: var(--primary-dark) !important;
+}
/* ===== GLOBAL STYLES ===== */
:root[data-theme="light"] {
--bg-color: #f5f5f5;
@@ -22,6 +50,12 @@
--border-radius: 8px;
--transition: all 0.3s ease;
+ /* New variables for details row */
+ --details-bg: #f8f9fa; /* Light background for details */
+ --details-text-color: var(--text-color);
+ --details-border-color: #dee2e6;
+ --notes-bg: #e9ecef; /* Slightly different background for notes */
+
/* Ensure warranty card title is white in table view light mode */
.table-view .warranty-title {
color: #FFFFFF; /* White text for better contrast */
@@ -62,6 +96,12 @@
--input-background: #1a1a1a;
--border-radius: 8px; /* Added missing border radius for dark theme */
+ /* New variables for details row */
+ --details-bg: #2c3034; /* Darker background for details */
+ --details-text-color: var(--text-color);
+ --details-border-color: #454a4f;
+ --notes-bg: #343a40; /* Slightly different dark background for notes */
+
/* Ensure warranty card title is white in table view dark mode */
.table-view .warranty-title {
color: #FFFFFF; /* White text for better contrast */
@@ -992,7 +1032,7 @@ input.invalid {
header .app-title i {
font-size: 1.6rem !important; /* Slightly reduce icon size */
- margin-right: 10px !important;
+ margin-right: 10px !important; /* Slightly reduce icon size */
}
header .nav-links {
@@ -3206,3 +3246,104 @@ input.invalid {
justify-content: center !important;
}
}
+
+/* Styling for the main row when details are expanded */
+#recentExpirationsTable tr.details-expanded {
+ background-color: var(--medium-gray) !important; /* Use important to override existing hover or status colors if needed, or make more specific */
+ /* color: var(--primary-color); /* Optional: change text color of expanded row */
+}
+
+/* Styling for the new details row */
+.warranty-details-row td {
+ padding: 20px !important; /* Ensure padding is applied */
+ background-color: var(--details-bg);
+ color: var(--details-text-color);
+ border-top: 1px solid var(--details-border-color);
+ border-bottom: 1px solid var(--details-border-color);
+}
+
+.warranty-details-content {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 25px; /* Increased gap */
+}
+
+.warranty-details-content > div { /* Direct children divs (sections) */
+ flex: 1 1 280px; /* Allow wrapping with a minimum width */
+ padding: 10px;
+}
+
+.warranty-details-content h4 {
+ margin-top: 0;
+ margin-bottom: 12px;
+ font-size: 1.1rem;
+ color: var(--primary-color);
+ border-bottom: 1px solid var(--details-border-color);
+ padding-bottom: 8px;
+}
+
+.warranty-details-content p {
+ margin-bottom: 8px;
+ font-size: 0.95rem;
+ line-height: 1.5;
+}
+
+.warranty-details-content p strong {
+ color: var(--details-text-color);
+ margin-right: 5px;
+}
+
+.warranty-details-content a {
+ color: var(--primary-color);
+ text-decoration: none;
+}
+
+.warranty-details-content a:hover {
+ text-decoration: underline;
+}
+
+.warranty-details-content ul {
+ list-style-type: disc;
+ margin-left: 20px;
+ padding-left: 0;
+}
+
+.warranty-details-content li {
+ margin-bottom: 5px;
+}
+
+.warranty-details-content pre {
+ background-color: var(--notes-bg);
+ color: var(--details-text-color);
+ padding: 15px;
+ border-radius: var(--border-radius);
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ font-family: monospace;
+ font-size: 0.9rem;
+ border: 1px solid var(--details-border-color);
+}
+
+/* ... existing code ... */
+
+/* Ensure view document links in modals are styled consistently, especially in dark mode */
+[data-theme="dark"] .view-document-link {
+ color: var(--primary-color); /* Or your specific dark mode link color variable */
+ text-decoration: underline;
+}
+
+[data-theme="dark"] .view-document-link:hover,
+[data-theme="dark"] .view-document-link:focus {
+ color: var(--primary-light); /* Or a slightly lighter/different hover color */
+ text-decoration: none;
+}
+
+/* If the text-success class interferes, this can provide higher specificity */
+[data-theme="dark"] .text-success .view-document-link {
+ color: var(--primary-color); /* Ensure override if text-success sets link color */
+}
+
+[data-theme="dark"] .text-success .view-document-link:hover,
+[data-theme="dark"] .text-success .view-document-link:focus {
+ color: var(--primary-light);
+}
diff --git a/frontend/version-checker.js b/frontend/version-checker.js
index 920334f..a8cc521 100644
--- a/frontend/version-checker.js
+++ b/frontend/version-checker.js
@@ -1,6 +1,6 @@
// Version checker for Warracker
document.addEventListener('DOMContentLoaded', () => {
- const currentVersion = '0.9.9.6'; // Current version of the application
+ const currentVersion = '0.9.9.7'; // Current version of the application
const updateStatus = document.getElementById('updateStatus');
const updateLink = document.getElementById('updateLink');