Skip to content

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

feat: Add currency controls, owner role, OIDC-only mode & key enhancements

sassanix47a42fb388c6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e5e4d53..a6158ca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,766 +1,1980 @@
# Changelog
-## 0.10.1.0 - 2025-06-10
+## 0\.10.1.1 - 2025-06-15
### Added
-- **Public Global Warranty View for All Users**
- - Extended global warranty view access to all authenticated users (previously admin-only)
- - **Regular Users**: Can view all warranties from all users but can only edit/delete their own
- - **Admin Users**: Can edit/delete any warranty in global view, maintaining full administrative control
- - Added read-only protection: edit/delete buttons are replaced with view-only eye icon for warranties not owned by current user (unless user is admin)
- - Updated UI labels and tooltips to reflect the new public access model
- - Maintains full admin functionality while providing transparency to all users
-
-- **Admin Global View Control Settings**
- - Added admin setting to enable/disable the global view feature site-wide
- - New "Global View Enabled" toggle in Site Settings section of admin panel
- - New "Global View Admin Only" toggle to restrict global view access to administrators only
- - When disabled, global view switcher is hidden from all users (including non-admins)
- - When admin-only is enabled, only administrators can access global view feature
- - Real-time enforcement: users automatically redirected to personal view if global view is disabled or restricted while they're using it
- - Default enabled for backward compatibility with admin-only setting defaulted to false
-
-- **Global View for Status Dashboard**
- - Extended global view functionality to the warranty status/analytics page
- - Eligible users can now view warranty statistics and data from all users on the status dashboard
- - Added view switcher (Personal/Global) to status page header with same permission controls as main page
- - Global statistics include total counts, charts, and warranty tables from all users
- - Owner information displayed in warranty tables when in global view mode
- - Maintains same security model: admins can see all data, regular users see all data but with read-only access to others' warranties
- - Seamless integration with existing global view settings and permissions
-- **Apprise Push Notifications Integration:** Comprehensive push notification system supporting 80+ services for warranty expiration alerts.
- - **Backend Implementation:**
- - **Apprise Handler (`backend/apprise_handler.py`):** Complete notification management system with configuration loading, URL validation, and multi-service support.
- - **Database Migration (`backend/migrations/026_add_apprise_settings.sql`):** Added Apprise configuration settings to site_settings table.
- - **API Endpoints (`backend/app.py`):** Full REST API for Apprise management including test notifications, URL validation, configuration reload, and manual triggers.
- - **Scheduler Integration:** Enhanced existing notification scheduler to send both email and Apprise notifications simultaneously.
- - **Environment Support:** Full environment variable support for Docker deployments with fallback to database configuration.
- - **Frontend Implementation:**
- - **Admin Settings UI (`frontend/settings-new.html`):** Complete Apprise configuration section with real-time status, URL management, and testing capabilities.
- - **JavaScript Integration (`frontend/settings-new.js`):** Full frontend functionality for configuration management, URL validation, and notification testing.
- - **Responsive Design (`frontend/settings-styles.css`):** Modern UI components including status badges, action grids, and mobile-responsive layouts.
- - **Supported Services:** Discord, Slack, Telegram, Email (Gmail, Outlook), Microsoft Teams, Webhooks, Matrix, Pushover, Ntfy, Gotify, and 70+ more services.
- - **Configuration Options:**
- - **Multiple Notification URLs:** Support for comma-separated or line-separated notification service URLs
- - **Flexible Timing:** Configurable notification days (e.g., 7,30 days before expiration) and daily notification time
- - **Custom Branding:** Configurable title prefix for all notifications (e.g., "[Warracker]")
- - **Test Functionality:** Send test notifications to verify configuration before enabling
- - **URL Validation:** Real-time validation of Apprise notification URLs
- - **Environment Configuration (`env.example`):** Complete example configuration file with detailed Apprise setup instructions and URL format examples.
- - **Graceful Degradation:** System continues to function normally if Apprise is not installed, with appropriate admin notifications.
- - _Files: `backend/apprise_handler.py`, `backend/migrations/026_add_apprise_settings.sql`, `backend/app.py`, `backend/db_handler.py`, `backend/requirements.txt`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/settings-styles.css`, `docker-compose.yml`, `env.example`_
-- **Warranty Type Filtering and Sorting:** Enhanced the home page with comprehensive warranty type filtering and sorting capabilities.
- - **New Warranty Type Filter Dropdown:** Added a dedicated "Warranty Type" filter dropdown in the filter section, positioned between Vendor and Sort By filters.
- - **Dynamic Filter Population:** The warranty type filter automatically populates with all unique warranty types found in existing warranties, sorted alphabetically.
- - **Case-Insensitive Filtering:** Warranty type filtering works regardless of the case of the warranty type (e.g., "Standard", "standard", "STANDARD").
- - **Sorting by Warranty Type:** Added "Warranty Type" as a sorting option in the Sort By dropdown, allowing users to sort warranties alphabetically by their warranty type.
- - **Real-time Filtering:** Filter applies immediately when warranty type selection changes, working seamlessly with existing filters (Status, Tag, Vendor, Search).
- - **Frontend Implementation:**
- - Updated `frontend/index.html` to include warranty type filter dropdown and sort option
- - Enhanced `frontend/script.js` with warranty type filtering logic, event listeners, and population function
- - Added `populateWarrantyTypeFilter()` function to dynamically populate filter options from warranty data
- - Integrated warranty type support into `currentFilters` object and `applyFilters()` function
- - Added warranty type sorting logic to `renderWarranties()` function
- - **Integration:** Works with the existing warranty type field that was previously added to add/edit forms, providing end-to-end warranty type management.
- - _Files: `frontend/index.html`, `frontend/script.js`_
-
-- **Admin Global Warranty View:** Added a globe button for administrators to view all users' warranties alongside their own.
- - **Backend API (`backend/app.py`):** New `/api/admin/warranties` endpoint that returns all warranties from all users with user information (username, email, display name).
- - **Frontend UI (`frontend/index.html`):** Added admin-only "Scope" toggle with Personal/Global view buttons next to the existing view switcher.
- - **Frontend Logic (`frontend/script.js`):**
- - Added `isGlobalView` state management and view switching functions
- - Enhanced warranty rendering to show owner information when in global view
- - Automatic admin detection and UI initialization
- - Dynamic title updates ("Your Warranties" vs "All Users' Warranties")
- - **Styling (`frontend/style.css`):**
- - Admin view switcher styling with primary color theme
- - Owner information highlighting with colored border and background
- - Responsive design for mobile devices
- - **Security:** Admin-only access with proper permission checks and graceful fallbacks for non-admin users.
- - _Files: `backend/app.py`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_
-
-- **Product Photo Thumbnails on Warranty Cards:** Enhanced warranty cards with visual product photo thumbnails for quick identification and easy access to full-size images.
- - **Thumbnail Display:** Product photos now appear as small thumbnails in the top right corner of each warranty card, providing instant visual recognition of products.
- - **Multi-View Support:** Photo thumbnails are displayed across all warranty viewing modes:
- - **Grid View:** 60px thumbnails positioned elegantly in the card corner
- - **List View:** 50px thumbnails for compact horizontal layouts
- - **Table View:** 40px thumbnails optimized for dense data display
- - **Interactive Photo Access:** Users can click on any product photo thumbnail to open the full-size image in a new browser tab for detailed viewing.
- - **Secure Image Handling:** Product photos are served through secure authentication, ensuring only authorized users can view warranty images while maintaining fast loading performance.
- - **Real-time Updates:** When users add or update product photos through the warranty edit forms, the thumbnail images immediately appear on warranty cards without requiring a page refresh.
- - **Visual Feedback:** Photo thumbnails include hover effects and "Click to view full size image" tooltips to clearly indicate their interactive nature.
- - **Responsive Design:** Photo thumbnails automatically scale and position appropriately across different screen sizes and device types.
- - _Files: `frontend/script.js`, `frontend/style.css`_
+
+* **Export Debug Tools**: Comprehensive debugging system for troubleshooting warranty export issues
+
+ * **Debug Page**: Created `frontend/debug-export.html` for interactive export testing and analysis
+
+ * **Debug API**: Added `/api/debug/export` endpoint providing detailed warranty and association data
+
+ * **Enhanced Logging**: Added comprehensive debug logging to export and filter functions in `frontend/script.js`
+
+ * **Export Validation**: Real-time display of filter application and warranty count verification
+
+ * **Interactive Testing**: Browser-based tool to test export functionality with detailed console output
+
+ * **Filter Analysis**: Step-by-step debugging of each filter application to identify export count discrepancies
+
+* **Currency Position Control:** Enhanced currency display system to allow users to choose whether currency symbols appear on the left or right of numbers through the settings page.
+
+ * **Settings UI Enhancement (`frontend/settings-new.html`):** Added new "Currency Position" dropdown in Display Preferences section:
+
+ * **Left Position:** Traditional format like "$100.00" (default to maintain existing behavior)
+
+ * **Right Position:** European-style format like "100.00$"
+
+ * **Visual Examples:** Dropdown options show example formatting to clarify choice impact
+
+ * **Database Schema (`backend/migrations/034\_add\_currency\_position\_column.sql`):** Added `currency\_position` column to `user\_preferences` table:
+
+ * **Default Value:** Set to 'left' for backward compatibility with existing installations
+
+ * **Data Validation:** Check constraint ensures only 'left' or 'right' values are allowed
+
+ * **Migration Safety:** Handles existing data by setting NULL or invalid values to 'left' before applying constraint
+
+ * **Backend API Integration (`backend/auth\_routes.py`):** Enhanced user preferences endpoints to handle currency position:
+
+ * **GET /api/auth/preferences:** Returns saved currency position preference with 'left' fallback for missing values
+
+ * **PUT /api/auth/preferences:** Validates and saves currency position with input validation for 'left'/'right' values
+
+ * **Default Handling:** All default preference objects include currency\_position: 'left' for consistency
+
+ * **Frontend Dynamic Formatting (`frontend/script.js`):** Implemented responsive currency display system:
+
+ * **New Functions:** Added `getCurrencyPosition()` and `formatCurrencyHTML()` for position-aware currency formatting
+
+ * **Smart HTML Generation:** Currency symbols and amounts dynamically positioned based on user preference
+
+ * **CSS Integration:** Right-positioned symbols use `.currency-right` class for proper spacing
+
+ * **Live Updates:** Real-time updates when position preference changes without page refresh
+
+ * **Universal Application:** Currency position setting applies across all views and features:
+
+ * **Warranty Cards:** Grid, list, and table views all respect position preference
+
+ * **Price Displays:** Purchase price fields show currency in chosen position throughout application
+
+ * **Cross-Tab Sync:** Settings changes immediately reflect in all open browser tabs
+
+ * **User Experience Features:**
+
+ * **Immediate Preview:** Position changes apply instantly to warranty cards when settings are saved
+
+ * **Persistent Preference:** Setting saved per user in database and persists across sessions
+
+ * **Backward Compatible:** Existing users see no change (defaults to left position)
+
+ * **Storage Event Handling:** Settings page and main app stay synchronized when currency position changes
+
+ * **CSS Styling (`frontend/style.css`):** Added `.currency-right` class for proper margin spacing when symbols appear on the right
+
+ * **Form Currency Integration:** Enhanced warranty add/edit forms to respect currency position settings:
+
+ * **Dynamic Form Updates:** Price input fields in both add and edit warranty forms now show currency symbols in the user's preferred position
+
+ * **CSS Form Positioning:** Added `.price-input-wrapper.currency-right` styles to properly position currency symbols on the right side of input fields
+
+ * **Input Padding Adjustment:** Right-positioned currency symbols get appropriate padding to prevent text overlap
+
+ * **Dynamic Currency Positioning:** JavaScript-based dynamic positioning system that places right-side currency symbols immediately after the typed content, maintaining natural spacing regardless of input length
+
+ * **Modal Currency Positioning:** Enhanced currency positioning to work immediately when modals open, not just when users interact with input fields
+
+ * **Modal Integration:** Currency position updates automatically when forms are opened, ensuring immediate visual consistency
+
+ * **Summary Tab Enhancement:** Add warranty form summary tab now displays purchase price with correct currency positioning
+
+ * **Improved Dynamic Positioning:** Enhanced JavaScript positioning system with better timing and reliability:
+
+ * **Element Readiness Validation:** Added checks to ensure DOM elements are fully rendered before positioning calculations
+
+ * **Multiple Timing Mechanisms:** Uses `requestAnimationFrame()` with fallback timers for robust positioning across different browsers
+
+ * **Automatic Modal Triggers:** Currency positioning now activates immediately when modals open via simulated focus/blur events
+
+ * **Debug Logging:** Added console logging for positioning calculations to aid in troubleshooting
+
+ * **Retry Logic:** Automatic retry mechanism if elements aren't ready during initial positioning attempt
+
+ * *Files: `backend/migrations/034\_add\_currency\_position\_column.sql`, `backend/auth\_routes.py`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/script.js`, `frontend/style.css`, `frontend/index.html`*
+
+* **OIDC-Only Login Mode:** Added administrator control to enforce OIDC-only authentication, hiding traditional username/password login forms.
+
+ * **Database Setting:** Added `oidc\_only\_mode` boolean setting to `site\_settings` table with default value 'false' for backward compatibility
+
+ * **Backend API Enhancement (`backend/app.py`):**
+
+ * **Settings Management:** Added `oidc\_only\_mode` to site settings GET/PUT endpoints with proper boolean validation
+
+ * **OIDC Status API:** Enhanced `/api/settings/oidc-status` endpoint to include `oidc\_only\_mode` status for frontend consumption
+
+ * **OIDC Handler Update (`backend/oidc\_handler.py`):** Updated `/api/auth/oidc-status` route to return OIDC-only mode status alongside provider information
+
+ * **Frontend Admin Controls (`frontend/settings-new.html`, `frontend/settings-new.js`):**
+
+ * **Settings UI:** Added "OIDC-Only Login Mode" toggle in OIDC SSO Configuration section with warning about proper configuration
+
+ * **Settings Persistence:** OIDC-only mode preference saved to backend and loaded with other OIDC settings
+
+ * **Element Management:** Added DOM element handling for the new toggle in both global and local scopes
+
+ * **Login Page Enhancement (`frontend/login.html`):**
+
+ * **Conditional UI:** Traditional username/password login form hidden when OIDC-only mode is enabled
+
+ * **Link Management:** Register and forgot password links hidden in OIDC-only mode as they're not applicable
+
+ * **Page Title Update:** Login page title changes to "Login with SSO" when in OIDC-only mode
+
+ * **Clean Interface:** OR separator and auth links section hidden when not needed
+
+ * **Security Benefits:** Enforces single sign-on authentication when enabled, preventing local account access and centralizing authentication through OIDC provider
+
+ * **Administrator Safety:** Includes warning message about ensuring OIDC is properly configured before enabling this mode to prevent lockouts
+
+ * *Files: `backend/app.py`, `backend/oidc\_handler.py`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/login.html`*
+
+* **About Page Redesign:** Complete visual overhaul of the about page with modern design, improved layout, and enhanced community links.
+
+ * **Hero Section Enhancement:** Added gradient background hero section with prominent Warracker branding, version display, and descriptive text about the platform
+
+ * **Modern Card Layout:** Restructured content into three themed information cards:
+
+ * **Project Information Card:** GitHub repository and releases links with proper GitHub branding
+
+ * **Community \& Support Card:** Discord community invitation and issue reporting links
+
+ * **Developer Information Card:** Developer profile and license information with appropriate icons
+
+ * **Discord Community Integration:** Added prominent Discord community link (https://discord.gg/PGxVS3U2Nw) with official Discord branding:
+
+ * **Discord Icon:** Proper `fab fa-discord` Font Awesome icon implementation
+
+ * **Brand Colors:** Discord's signature #5865f2 color scheme with hover effects
+
+ * **Community Focus:** Positioned prominently in Community \& Support section
+
+ * **Enhanced Social Links:** Improved all external links with proper icons and brand-appropriate styling:
+
+ * **GitHub Links:** `fab fa-github` icons for repository and developer profile
+
+ * **Issue Reporting:** `fas fa-bug` icon with red accent color for bug reports
+
+ * **Releases:** `fas fa-tags` icon with blue accent color for version releases
+
+ * **License:** `fas fa-balance-scale` icon with green accent color for AGPL-3.0 license
+
+ * **Visual Improvements:** Modern design elements with enhanced user experience:
+
+ * **Hover Effects:** Smooth card lift animations and social link transitions
+
+ * **Responsive Design:** Grid layout that adapts to mobile devices with single-column layout
+
+ * **Dark Mode Support:** Proper styling for both light and dark themes with appropriate contrast
+
+ * **Color-Coded Interface:** Each social link uses brand-appropriate colors for visual consistency
+
+ * **Update Status Enhancement:** Redesigned update checker section with better visual hierarchy and icon integration
+
+ * **Support Section:** Improved "Buy me a coffee" section with better visual presentation and clear call-to-action
+
+ * **Mobile Optimization:** Responsive design with adjusted font sizes, centered layouts, and flexible social link sizing for optimal mobile experience
+
+ * *Files: `frontend/about.html`*
+
+* **Global View Photo Access:** Enhanced secure file access to allow users to view product photos from other users' warranties when global view is enabled.
+
+ * **Photo Sharing in Global View:** When global view is enabled for all users, product photo thumbnails and full-size images are now accessible across all warranties, not just user-owned ones
+
+ * **Selective File Access:** Only product photos are granted global view access - invoices, manuals, and other sensitive documents remain restricted to warranty owners and admins
+
+ * **Respects Global View Settings:** Photo access follows the same permission model as the global warranties feature:
+
+ * **Global View Enabled:** Photos accessible to all authenticated users when global view is active
+
+ * **Admin-Only Mode:** When global view is restricted to admins only, photo access is similarly restricted
+
+ * **Disabled Mode:** When global view is disabled, photos revert to owner-only access
+
+ * **Enhanced Security Logging:** Added comprehensive logging to secure file access endpoint for troubleshooting and security auditing of photo access requests
+
+ * **Backend Implementation (`backend/app.py`):** Modified `/api/secure-file/<path:filename>` endpoint with additional authorization logic:
+
+ * **Product Photo Detection:** Queries database to identify if requested file is a product photo vs other document types
+
+ * **Permission Validation:** Checks global view settings and user permissions before granting access
+
+ * **Maintains Existing Security:** All current access controls remain intact - admins and owners retain full access
+
+ * **User Experience:** Product photos now display properly in global view across all viewing modes (grid, list, table), enabling visual identification of products from all users
+
+ * *Files: `backend/app.py`*
+
+* **Super-Admin (Owner) Role with Ownership Transfer:** Implemented a comprehensive ownership management system with immutable owner role and secure ownership transfer functionality.
+
+ * **Database Schema Enhancement (`backend/migrations/031\_add\_owner\_role.sql`):** Added `is\_owner` boolean column to users table with automatic owner promotion for the first registered user
+
+ * **Backend API Protection (`backend/app.py`, `backend/auth\_routes.py`, `backend/auth\_utils.py`):**
+
+ * **Owner Protection Logic:** Prevents owner account deletion, demotion, or deactivation through all admin endpoints
+
+ * **Authentication Enhancement:** Added `is\_owner` field to all authentication responses and token validation
+
+ * **Backward Compatibility:** Implemented graceful fallback handling for systems without the owner column
+
+ * **Transaction Rollback Handling:** Added proper PostgreSQL transaction rollback recovery for failed queries
+
+ * **Ownership Transfer API (`backend/app.py`):** New `/api/admin/transfer-ownership` endpoint with atomic transaction processing:
+
+ * **Security Validation:** Requires "TRANSFER" confirmation text and validates target user is an active admin
+
+ * **Atomic Operations:** Uses database transactions to ensure ownership transfer completes fully or rolls back entirely
+
+ * **Owner-Only Access:** Restricted to current owner with comprehensive permission checks
+
+ * **Frontend UI Implementation (`frontend/settings-new.html`, `frontend/settings-new.js`):**
+
+ * **Dedicated Ownership Section:** Separate "👑 Ownership Management" section in admin settings with crown icon branding
+
+ * **Visual Owner Indicators:** Crown icons (👑) displayed next to owner username in user management lists
+
+ * **Protected UI Elements:** Owner edit/delete buttons disabled with visual indicators and tooltips
+
+ * **Transfer Confirmation Modal:** Secure ownership transfer interface requiring "TRANSFER" text confirmation
+
+ * **Modern User Management:** Redesigned users list with professional styling, hover effects, and responsive design
+
+ * **Action Button Enhancement:** Improved edit/delete buttons with smooth animations and theme compatibility
+
+ * **Migration Safety:** Automatic owner assignment to first user during migration with comprehensive error handling
+
+ * **Security Features:** Owner cannot be deleted, demoted, or have ownership transferred without explicit confirmation
+
+ * *Files: `backend/migrations/031\_add\_owner\_role.sql`, `backend/app.py`, `backend/auth\_routes.py`, `backend/auth\_utils.py`, `frontend/settings-new.html`, `frontend/settings-new.js`*
+
+* **Product Age Tracking and Sorting:** Enhanced warranty cards with product age display and sorting capabilities to help users track ownership duration.
+
+ * **Age Calculation (`frontend/script.js`):** Added `calculateProductAge()` function that computes time elapsed since purchase date with intelligent formatting:
+
+ * **Smart Display Format:** Shows age as "2 years, 3 months", "6 months", or "15 days" depending on duration
+
+ * **Edge Case Handling:** Gracefully handles invalid dates, future dates, and same-day purchases ("Today")
+
+ * **Precision Logic:** Shows days only for items less than a year old to avoid clutter
+
+ * **Visual Integration:** Product age now appears on all warranty cards across all view types:
+
+ * **Grid View:** Age displayed between purchase date and warranty duration for logical flow
+
+ * **List View:** Consistent placement maintaining card layout harmony
+
+ * **Table View:** Compact age display optimized for dense information presentation
+
+ * **Age-Based Sorting:** Added "Age" option to Sort By dropdown with dedicated sorting logic:
+
+ * **Oldest First:** Products sorted with longest-owned items appearing first
+
+ * **Precise Sorting:** Uses `calculateProductAgeInDays()` helper function for accurate day-level sorting
+
+ * **Invalid Date Handling:** Items with missing purchase dates treated as newest (0 days old)
+
+ * **User Benefits:** Enables users to track ownership duration, assess product lifecycle, and organize warranties by how long they've owned each item
+
+ * *Files: `frontend/index.html`, `frontend/script.js`*
+
+ * **Persistent View Scope (Global/Personal) with Auto-Loading:** The app now remembers the user's last selected view scope (global or personal) and automatically loads the correct data from the appropriate API endpoint on page load, not just updating the UI.
+
+ * **Seamless Experience:** Users no longer need to re-select their preferred view after a refresh; the correct data and UI are loaded immediately based on their last choice.
+
+ * **Consistent State:** Both the main warranties page and the status dashboard respect the saved preference and fetch from the correct endpoint (`/api/warranties/global` or `/api/warranties`, and `/api/statistics/global` or `/api/statistics`).
+
+ * **User-Specific Storage:** Preferences are stored per user/admin using the same prefix system as other settings.
+
+ * **Robustness:** The system defaults to personal view if no preference is found or on error, and always keeps the UI and data in sync.
+
+ * *Files: `frontend/script.js`, `frontend/status.js`*
+
+* **Authentication System Refactoring to Flask Blueprints:** Complete restructuring of authentication routes for improved code organization and maintainability.
+
+ * **Flask Blueprint Architecture:** Migrated all authentication routes from the monolithic `app.py` file to a dedicated Flask Blueprint (`auth\_routes.py`)
+
+ * **Modular Code Organization:** Separated authentication logic into specialized modules:
+
+ * **`auth\_utils.py`:** Authentication helper functions (`generate\_token`, `decode\_token`, `token\_required`, `admin\_required`, `is\_valid\_email`, `is\_valid\_password`)
+
+ * **`auth\_routes.py`:** Authentication Blueprint containing all auth-related routes and handlers
+
+ * **Routes Migrated:** All authentication endpoints moved to Blueprint architecture:
+
+ * User registration and login (`/register`, `/login`, `/logout`)
+
+ * Token validation and user management (`/validate-token`, `/user`)
+
+ * Password management (`/password/reset-request`, `/password/reset`, `/password/change`)
+
+ * Profile and account management (`/profile`, `/account`, `/preferences`)
+
+ * Email management (`/change-email`, `/verify-email-change`)
+
+ * System status endpoints (`/registration-status`)
+
+ * **Backward Compatibility:** All API endpoints maintain identical URLs and functionality - zero breaking changes for existing clients
+
+ * **Import Optimization:** Reduced main application file size and improved code maintainability through separation of concerns
+
+ * **Docker Integration:** Updated Dockerfile to properly include new authentication modules in container builds
+
+ * *Files: `backend/auth\_utils.py`, `backend/auth\_routes.py`, `backend/app.py`, `Dockerfile`*
+
+* **Smart Currency Default Selection:** Enhanced add warranty form to automatically default to user's preferred currency from settings instead of always defaulting to USD.
+
+ * **Settings Integration:** Currency dropdown in add warranty modal now reads user's preferred currency from settings and auto-selects it as the default
+
+ * **Currency Code Storage:** Settings page now saves both currency symbol and currency code to localStorage for accurate currency identification
+
+ * **Intelligent Fallback:** System attempts to derive currency code from symbol if not explicitly saved, with USD as ultimate fallback
+
+ * **Form Reset Handling:** Add warranty modal properly restores user's preferred currency after form reset operations
+
+ * **Individual Override:** Users can still change currency for individual warranties while maintaining their preferred default
+
+ * **Seamless Experience:** Eliminates need to manually change currency from USD to preferred currency for every new warranty
+
+ * **Debug Logging:** Added comprehensive logging to track currency code detection and default selection process
+
+ * *Files: `frontend/script.js`, `frontend/settings-new.js`*
+
+### Enhanced
+
+* **Larger Product Photo Thumbnails:** Increased photo thumbnail sizes across all view modes for better product visibility and identification.
+
+ * **Grid View Enhancement:** Photo thumbnails increased from 60px × 60px to 80px × 80px for more prominent product images
+
+ * **List View Enhancement:** Photo thumbnails increased from 50px × 50px to 70px × 70px for improved visual clarity
+
+ * **Table View Enhancement:** Photo thumbnails increased from 40px × 40px to 55px × 55px for better readability in compact view
+
+ * **Mobile Responsive Updates:** Adjusted mobile photo sizes to maintain usability while providing larger images on smaller screens
+
+ * **Consistent Styling:** Maintained existing hover effects, border radius, and visual styling while increasing overall size
+
+ * **Better User Experience:** Larger photos make it easier to identify products at a glance across all viewing modes
+
+ * *Files: `frontend/style.css`, `frontend/script.js`*
+
+### Fixed
+
+* **CSV Import Currency Selection:** Fixed CSV import functionality that was incorrectly defaulting all imported warranties to USD currency instead of using the user's preferred currency from settings.
+
+ * **Root Cause:** CSV import function in `backend/app.py` was hardcoding `'USD'` for all imported warranties regardless of user preferences
+
+ * **Solution:** Enhanced import function to query user's preferred currency symbol from `user\_preferences` table and convert it to appropriate currency code
+
+ * **Currency Mapping:** Implemented comprehensive symbol-to-code mapping for 30+ currencies (€→EUR, £→GBP, ¥→JPY, etc.) matching frontend logic
+
+ * **Intelligent Fallback:** Graceful fallback to USD for users without currency preferences or with unknown custom symbols
+
+ * **Enhanced Logging:** Added detailed logging to track currency preference detection and assignment during import process
+
+ * **Result:** Imported warranties now automatically use user's preferred currency (Euro, Pound, Yen, etc.) instead of always defaulting to USD
+
+ * *Files: `backend/app.py`*
+
+* **Export Function Debugging and Verification:** Resolved user reports of incomplete warranty exports by implementing comprehensive debugging tools and verifying export functionality
+
+ * **Root Cause Analysis:** Determined that export function was working correctly - all warranties were being exported as expected
+
+ * **Debug Implementation:** Added detailed console logging to export process showing step-by-step filter application and final export counts
+
+ * **Verification Tools:** Created interactive debug page (`frontend/debug-export.html`) and backend debug API (`/api/debug/export`) for troubleshooting
+
+ * **User Education:** Identified that perceived "missing" records were due to CSV viewer display issues with similar/duplicate entries rather than export functionality problems
+
+ * **Export Validation:** Confirmed all warranties are properly included in CSV output with correct data formatting and structure
+
+ * **Documentation:** Enhanced export process with real-time feedback showing actual number of warranties exported
+
+* **Critical User Preferences Persistence Bug:** Fixed date format and currency symbol settings not saving properly, causing user preferences to revert to defaults after page refresh.
+
+ * **Root Cause:** Backend API endpoints (`GET`/`PUT` `/api/auth/preferences`) were hardcoded to always return `currency\_symbol: '$'` and `date\_format: 'MDY'` instead of reading from/writing to the database columns
+
+ * **Database Verification:** Confirmed both `currency\_symbol` and `date\_format` columns exist in `user\_preferences` table via migrations `006\_add\_currency\_symbol\_column.py` and `019\_add\_date\_format\_column.sql`
+
+ * **Backend API Fixes (`backend/auth\_routes.py`):**
+
+ * **GET Route:** Added `currency\_symbol, date\_format` to SELECT queries and updated response mapping to use actual database values
+
+ * **PUT Route:** Added validation and processing for `currency\_symbol` and `date\_format` from request data
+
+ * **UPDATE Query:** Enhanced to include currency symbol and date format in SET clauses
+
+ * **INSERT Query:** Updated to save currency symbol and date format for new user preferences
+
+ * **Response Consistency:** All preference responses now return actual saved values instead of hardcoded defaults
+
+ * **Validation Added:** Currency symbol limited to 8 characters, date format restricted to valid options (`MDY`, `DMY`, `YMD`, `MDY\_WORDS`, `DMY\_WORDS`, `YMD\_WORDS`)
+
+ * **Result:** Settings page now properly persists currency symbol (€, £, ¥, etc.) and date format preferences across page refreshes and sessions
+
+ * *Files: `backend/auth\_routes.py`*
+
+* **Critical OIDC Login RecursionError Fix:** Resolved fatal `RecursionError: maximum recursion depth exceeded` preventing OIDC authentication with self-hosted providers like Authentik.
+
+ * **Root Cause:** Gunicorn's `gevent` worker type needs to monkey-patch standard libraries (like `ssl`) before they're imported, but `preload\_app = True` was loading Flask dependencies before patching occurred
+
+ * **Solution:** Enhanced `gunicorn\_config.py` with conditional early monkey patching that occurs at the very beginning of the configuration file, before any other imports
+
+ * **Intelligent Patching:** Monkey patching now only applies to memory modes that use gevent workers (`optimized` and `performance`), while `ultra-light` mode with sync workers skips patching entirely
+
+ * **Safety:** Uses try/catch block to gracefully handle environments without gevent installed, ensuring no impact on sync workers or development environments
+
+ * **Result:** OIDC providers now work correctly with gevent workers, eliminating SSL recursion errors and enabling SSO functionality across all deployment modes
+
+ * **Verification:** MonkeyPatchWarning no longer appears in startup logs, replaced with "✅ Early gevent monkey patch applied for SSL compatibility" confirmation
+
+ * *Files: `backend/gunicorn\_config.py`*
+
+* **Critical OIDC HTTPS Callback URL Fix:** Resolved OIDC login failures when Warracker is accessed over HTTPS, where the application was generating incorrect `http://` callback URLs instead of `https://` URLs.
+
+ * **Root Cause:** Flask application running behind Nginx reverse proxy was not aware of the original HTTPS protocol, causing `url\_for(\_external=True)` to generate HTTP callback URLs that didn't match the OIDC provider's expected HTTPS URLs
+
+ * **Reverse Proxy Configuration:** While Nginx correctly sent `X-Forwarded-Proto: https` headers, Gunicorn and Flask were not configured to trust and use these forwarded headers
+
+ * **Gunicorn Fix (`backend/gunicorn\_config.py`):** Added `forwarded\_allow\_ips = '\*'` configuration to trust proxy headers from the containerized Nginx reverse proxy
+
+ * **Flask Middleware (`backend/app.py`):** Implemented `ProxyFix` middleware with `x\_for=1, x\_proto=1, x\_host=1, x\_prefix=1` to read forwarded headers and update Flask's request context
+
+ * **Header Processing:** Flask now correctly interprets `X-Forwarded-Proto` headers and generates HTTPS URLs when accessed through the reverse proxy
+
+ * **Result:** OIDC login flow now generates correct `https://warracker.domain.com/api/oidc/callback` URLs, eliminating provider callback mismatches and enabling successful SSO authentication over HTTPS
+
+ * **Standard Practice:** Implements industry-standard reverse proxy configuration for Flask applications behind SSL-terminating proxies
+
+ * *Files: `backend/gunicorn\_config.py`, `backend/app.py`*
+
+* **Global vs. Individual Apprise Notification Mode:** Implemented flexible Apprise notification system allowing administrators to choose between consolidated global notifications or personalized individual notifications.
+
+ * **Database Migration (`backend/migrations/032\_add\_apprise\_notification\_mode.sql`):** Added `apprise\_notification\_mode` setting to `site\_settings` table with default value 'global' for backward compatibility
+
+ * **Backend Notification Logic (`backend/notifications.py`):** Enhanced `send\_expiration\_notifications` function with mode-aware branching logic:
+
+ * **Global Mode:** Sends single consolidated notification summarizing all expiring warranties across all users to configured Apprise channels
+
+ * **Individual Mode:** Sends separate personalized notifications for each user with expiring warranties, grouped by user with targeted messaging
+
+ * **Smart User Filtering:** Respects user notification preferences and timing eligibility for both manual and scheduled notifications
+
+ * **Mode Detection:** Dynamically reads `apprise\_notification\_mode` setting from database using imported `get\_site\_setting` function
+
+ * **Apprise Handler Enhancement (`backend/apprise\_handler.py`):** Added two new specialized notification methods:
+
+ * **`send\_global\_expiration\_notification()`:** Creates summary notification with warranties grouped by user email for administrator overview
+
+ * **`send\_individual\_expiration\_notification()`:** Generates personalized notifications with user-specific greeting and warranty details
+
+ * **Error Handling:** Comprehensive exception handling and logging for both notification modes
+
+ * **Frontend Admin Controls (`frontend/settings-new.html`, `frontend/settings-new.js`):**
+
+ * **Notification Mode Dropdown:** Added selection between "Global Summary" and "Per User" modes in Apprise settings section
+
+ * **Dynamic Description:** Real-time description updates explaining current mode behavior and implications
+
+ * **Settings Integration:** Mode preference saved to backend and persisted across sessions with proper loading and validation
+
+ * **Event Handling:** Immediate UI feedback when switching between notification modes
+
+ * **Backward Compatibility:** Existing installations default to 'global' mode, maintaining current notification behavior without disruption
+
+ * **Future Enhancement Ready:** Individual mode framework prepared for future per-user Apprise channel configuration
+
+ * *Files: `backend/migrations/032\_add\_apprise\_notification\_mode.sql`, `backend/notifications.py`, `backend/apprise\_handler.py`, `frontend/settings-new.html`, `frontend/settings-new.js`*
+
+ * **Apprise Warranty Scope Control:** Added administrator control to choose which warranties are included in Apprise notifications, enabling both multi-user and personal notification scenarios.
+
+ * **Database Migration (`backend/migrations/033\_add\_apprise\_warranty\_scope.sql`):** Added `apprise\_warranty\_scope` setting to `site\_settings` table with default value 'all' to maintain current behavior
+
+ * **Backend Warranty Filtering (`backend/notifications.py`):** Implemented warranty scope filtering logic in notification processing:
+
+ * **All Users Scope (Default):** Includes expiring warranties from all users in the system (current behavior)
+
+ * **Admin Only Scope:** Filters to only include warranties belonging to the admin/owner user for personal notifications
+
+ * **Smart Admin Detection:** Automatically identifies the primary admin by first checking for owner user, then falling back to first admin user
+
+ * **Scope Logging:** Comprehensive logging shows original vs filtered warranty counts for transparency and debugging
+
+ * **Frontend Warranty Scope Controls (`frontend/settings-new.html`, `frontend/settings-new.js`):**
+
+ * **Warranty Scope Dropdown:** Added selection between "All Users' Warranties" and "Admin's Warranties Only" in Apprise settings
+
+ * **Scope Description:** Real-time description updates explaining which warranties will be included in notifications
+
+ * **Settings Persistence:** Warranty scope preference saved to backend and properly loaded with other Apprise settings
+
+ * **Event Handling:** Immediate UI feedback when changing warranty scope selection
+
+ * **Flexible Combinations:** Works seamlessly with notification modes for complete control:
+
+ * **Global + All:** Single notification with all users' warranties (original behavior)
+
+ * **Global + Admin:** Single notification with only admin's warranties
+
+ * **Individual + All:** Separate notifications sent to each user with their warranties
+
+ * **Individual + Admin:** Notification sent only to admin with their warranties
+
+ * **Error Handling:** Graceful fallback to 'all' scope if admin user cannot be determined, with appropriate logging
+
+ * *Files: `backend/migrations/033\_add\_apprise\_warranty\_scope.sql`, `backend/notifications.py`, `frontend/settings-new.html`, `frontend/settings-new.js`*
+
+* **Enhanced Notification Settings with Apprise Integration:** Comprehensive enhancement of user notification preferences to support both email and Apprise notifications with individual timing control.
+
+ * **Backend User Preferences Enhancement (`backend/auth\_routes.py`):** Fixed and expanded user preferences API to properly handle all notification fields:
+
+ * **Notification Channel Support:** Added proper handling for `notification\_channel` field allowing users to choose between 'none', 'email', 'apprise', or 'both'
+
+ * **Apprise Timing Fields:** Added support for `apprise\_notification\_time`, `apprise\_notification\_frequency`, and `apprise\_timezone` in user preferences
+
+ * **Database Persistence:** Fixed critical bug where notification channel and Apprise settings were hardcoded instead of being saved to/loaded from database
+
+ * **Validation:** Added proper validation for notification channel values and timing fields
+
+ * **API Consistency:** Both GET and PUT `/api/auth/preferences` endpoints now properly handle all notification-related fields
+
+ * **Frontend Notification Settings Redesign (`frontend/settings-new.html`, `frontend/settings-new.js`):**
+
+ * **Dual Notification Sections:** Separated user notification preferences from admin Apprise configuration for clarity
+
+ * **Dynamic Settings Display:** Notification settings section shows/hides email and Apprise fields based on selected notification channel
+
+ * **Individual Timing Control:** Users can set separate notification times and timezones for email vs Apprise notifications
+
+ * **Smart Field Management:** Apprise-specific fields (time, timezone, frequency) appear only when notification channel includes 'apprise' or 'both'
+
+ * **Timezone Loading:** Proper timezone dropdown population for both email and Apprise notification settings
+
+ * **Settings Persistence:** All notification preferences properly save to user preferences and persist across sessions
+
+ * **Scheduler Integration:** Enhanced notification scheduler to respect individual user notification channel preferences:
+
+ * **Channel-Aware Processing:** Scheduler checks each user's `notification\_channel` setting to determine which notification types to send
+
+ * **Separate Timing:** Users can receive email notifications at one time and Apprise notifications at a different time
+
+ * **Preference Validation:** Only users with appropriate notification channels enabled receive corresponding notification types
+
+ * **User Experience Improvements:**
+
+ * **Clear Separation:** Admin Apprise configuration (URLs, global settings) separated from user notification preferences (timing, channels)
+
+ * **Intuitive Interface:** Notification channel dropdown with immediate visual feedback showing relevant settings
+
+ * **Flexible Scheduling:** Users can choose to receive only emails, only Apprise notifications, or both at different times
+
+ * *Files: `backend/auth\_routes.py`, `frontend/settings-new.html`, `frontend/settings-new.js`*
+
+* **Apprise Notification Message Format Standardization:** Unified notification message format between scheduled and manual Apprise notifications for consistency.
+
+ * **Message Format Alignment (`backend/apprise\_handler.py`):** Updated scheduled notification functions to match manual test notification format:
+
+ * **Consistent Titles:** All notifications now use format `"\[Warracker] Warranties Expiring in X Days"` instead of generic summary titles
+
+ * **Urgency Indicators:** Added emoji prefixes based on expiration timeframe:
+
+ * 🚨 URGENT: for warranties expiring in 1 day
+
+ * ⚠️ IMPORTANT: for warranties expiring in ≤7 days
+
+ * 📅 REMINDER: for warranties expiring in >7 days
+
+ * **Grouped by Days:** Separate notifications sent for different expiration timeframes (7, 30, 365 days) instead of combined summary
+
+ * **Standardized Content:** Consistent bullet-point format, date formatting, and footer text across all notification types
+
+ * **Enhanced Notification Functions:**
+
+ * **`send\_global\_expiration\_notification()`:** Now groups warranties by expiration days and sends separate notifications for each timeframe
+
+ * **`send\_individual\_expiration\_notification()`:** Similarly updated to match manual test format with proper grouping
+
+ * **`\_send\_global\_expiration\_batch()` and `\_send\_individual\_expiration\_batch()`:** New helper functions that use identical formatting to manual test notifications
+
+ * **User Benefits:**
+
+ * **Consistent Experience:** Manual test notifications and scheduled notifications now look identical
+
+ * **Clear Urgency:** Emoji indicators immediately convey urgency level
+
+ * **Better Organization:** Separate notifications for different timeframes instead of overwhelming combined messages
+
+ * *Files: `backend/apprise\_handler.py`*
+
+* **Apprise Settings UI Cleanup:** Streamlined Apprise configuration interface by removing non-functional decorative fields.
+
+ * **Removed Decorative Fields (`frontend/settings-new.html`, `frontend/settings-new.js`):** Eliminated unused time and timezone fields from admin Apprise configuration:
+
+ * **Notification Time Field:** Removed time input that was not used by the notification scheduler
+
+ * **Timezone Dropdown:** Removed timezone selection that was not used by the notification scheduler
+
+ * **Notification Frequency:** Renamed to "Check Frequency" with clearer description as a global system setting
+
+ * **JavaScript Cleanup:** Removed all references to unused fields including variable definitions, event listeners, and data loading functions
+
+ * **Status Display Cleanup:** Removed "Notification Time" from current status display since it's no longer relevant
+
+ * **Cache-Busting:** Updated version parameters from `v=20250529005` to `v=20250529006` to force browser cache refresh
+
+ * **Functional Clarity:** Apprise card now only contains settings that actually affect system behavior:
+
+ * ✅ Enable/Disable toggle, Notification Mode, Warranty Scope, Notification URLs, Notification Days, Check Frequency, Message Title Prefix
+
+ * ❌ Removed: Notification Time, Timezone (these are now properly handled in user notification preferences)
+
+ * **User Experience:** Clear separation between admin system configuration and user personal notification timing preferences
+
+ * *Files: `frontend/settings-new.html`, `frontend/settings-new.js`*
+
+### Code Quality \& Maintenance
+
+* **Legacy OIDC Code Cleanup:** Removed ~290 lines of commented-out and orphaned OIDC code from main application file for improved maintainability.
+
+ * **Removed Components:**
+
+ * **Commented Route Definitions:** Eliminated ~150 lines of commented-out `/api/oidc/login` and `/api/oidc/callback` route definitions
+
+ * **Orphaned Callback Logic:** Removed ~140 lines of disconnected OIDC callback handling code including user provisioning, token handling, and error redirection logic
+
+ * **Dead Code Elimination:** Cleaned up legacy authentication code that was replaced by the Blueprint architecture
+
+ * **OIDC Functionality Preserved:** All OIDC functionality remains fully operational through the proper Blueprint architecture in `backend/oidc\_handler.py`
+
+ * **File Size Reduction:** Reduced `backend/app.py` from ~3,477 lines to ~3,200 lines (~8% reduction)
+
+ * **Code Organization:** Improved code readability and maintainability by removing confusing commented-out legacy implementations
+
+ * **Blueprint Verification:** Confirmed `oidc\_bp` Blueprint is properly registered and functional at `/api/oidc/\*` endpoints
+
+ * *Files: `backend/app.py`*
+
+
+
+## 0\.10.1.0 - 2025-06-10
+
+### Added
+
+* **Public Global Warranty View for All Users**
+
+ * Extended global warranty view access to all authenticated users (previously admin-only)
+
+ * **Regular Users**: Can view all warranties from all users but can only edit/delete their own
+
+ * **Admin Users**: Can edit/delete any warranty in global view, maintaining full administrative control
+
+ * Added read-only protection: edit/delete buttons are replaced with view-only eye icon for warranties not owned by current user (unless user is admin)
+
+ * Updated UI labels and tooltips to reflect the new public access model
+
+ * Maintains full admin functionality while providing transparency to all users
+
+* **Admin Global View Control Settings**
+
+ * Added admin setting to enable/disable the global view feature site-wide
+
+ * New "Global View Enabled" toggle in Site Settings section of admin panel
+
+ * New "Global View Admin Only" toggle to restrict global view access to administrators only
+
+ * When disabled, global view switcher is hidden from all users (including non-admins)
+
+ * When admin-only is enabled, only administrators can access global view feature
+
+ * Real-time enforcement: users automatically redirected to personal view if global view is disabled or restricted while they're using it
+
+ * Default enabled for backward compatibility with admin-only setting defaulted to false
+
+* **Global View for Status Dashboard**
+
+ * Extended global view functionality to the warranty status/analytics page
+
+ * Eligible users can now view warranty statistics and data from all users on the status dashboard
+
+ * Added view switcher (Personal/Global) to status page header with same permission controls as main page
+
+ * Global statistics include total counts, charts, and warranty tables from all users
+
+ * Owner information displayed in warranty tables when in global view mode
+
+ * Maintains same security model: admins can see all data, regular users see all data but with read-only access to others' warranties
+
+ * Seamless integration with existing global view settings and permissions
+
+* **Apprise Push Notifications Integration:** Comprehensive push notification system supporting 80+ services for warranty expiration alerts.
+
+ * **Backend Implementation:**
+
+ * **Apprise Handler (`backend/apprise\_handler.py`):** Complete notification management system with configuration loading, URL validation, and multi-service support.
+
+ * **Database Migration (`backend/migrations/026\_add\_apprise\_settings.sql`):** Added Apprise configuration settings to site\_settings table.
+
+ * **API Endpoints (`backend/app.py`):** Full REST API for Apprise management including test notifications, URL validation, configuration reload, and manual triggers.
+
+ * **Scheduler Integration:** Enhanced existing notification scheduler to send both email and Apprise notifications simultaneously.
+
+ * **Environment Support:** Full environment variable support for Docker deployments with fallback to database configuration.
+
+ * **Frontend Implementation:**
+
+ * **Admin Settings UI (`frontend/settings-new.html`):** Complete Apprise configuration section with real-time status, URL management, and testing capabilities.
+
+ * **JavaScript Integration (`frontend/settings-new.js`):** Full frontend functionality for configuration management, URL validation, and notification testing.
+
+ * **Responsive Design (`frontend/settings-styles.css`):** Modern UI components including status badges, action grids, and mobile-responsive layouts.
+
+ * **Supported Services:** Discord, Slack, Telegram, Email (Gmail, Outlook), Microsoft Teams, Webhooks, Matrix, Pushover, Ntfy, Gotify, and 70+ more services.
+
+ * **Configuration Options:**
+
+ * **Multiple Notification URLs:** Support for comma-separated or line-separated notification service URLs
+
+ * **Flexible Timing:** Configurable notification days (e.g., 7,30 days before expiration) and daily notification time
+
+ * **Custom Branding:** Configurable title prefix for all notifications (e.g., "\[Warracker]")
+
+ * **Test Functionality:** Send test notifications to verify configuration before enabling
+
+ * **URL Validation:** Real-time validation of Apprise notification URLs
+
+ * **Environment Configuration (`env.example`):** Complete example configuration file with detailed Apprise setup instructions and URL format examples.
+
+ * **Graceful Degradation:** System continues to function normally if Apprise is not installed, with appropriate admin notifications.
+
+ * *Files: `backend/apprise\_handler.py`, `backend/migrations/026\_add\_apprise\_settings.sql`, `backend/app.py`, `backend/db\_handler.py`, `backend/requirements.txt`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/settings-styles.css`, `docker-compose.yml`, `env.example`*
+
+* **Warranty Type Filtering and Sorting:** Enhanced the home page with comprehensive warranty type filtering and sorting capabilities.
+
+ * **New Warranty Type Filter Dropdown:** Added a dedicated "Warranty Type" filter dropdown in the filter section, positioned between Vendor and Sort By filters.
+
+ * **Dynamic Filter Population:** The warranty type filter automatically populates with all unique warranty types found in existing warranties, sorted alphabetically.
+
+ * **Case-Insensitive Filtering:** Warranty type filtering works regardless of the case of the warranty type (e.g., "Standard", "standard", "STANDARD").
+
+ * **Sorting by Warranty Type:** Added "Warranty Type" as a sorting option in the Sort By dropdown, allowing users to sort warranties alphabetically by their warranty type.
+
+ * **Real-time Filtering:** Filter applies immediately when warranty type selection changes, working seamlessly with existing filters (Status, Tag, Vendor, Search).
+
+ * **Frontend Implementation:**
+
+ * Updated `frontend/index.html` to include warranty type filter dropdown and sort option
+
+ * Enhanced `frontend/script.js` with warranty type filtering logic, event listeners, and population function
+
+ * Added `populateWarrantyTypeFilter()` function to dynamically populate filter options from warranty data
+
+ * Integrated warranty type support into `currentFilters` object and `applyFilters()` function
+
+ * Added warranty type sorting logic to `renderWarranties()` function
+
+ * **Integration:** Works with the existing warranty type field that was previously added to add/edit forms, providing end-to-end warranty type management.
+
+ * *Files: `frontend/index.html`, `frontend/script.js`*
+
+* **Admin Global Warranty View:** Added a globe button for administrators to view all users' warranties alongside their own.
+
+ * **Backend API (`backend/app.py`):** New `/api/admin/warranties` endpoint that returns all warranties from all users with user information (username, email, display name).
+
+ * **Frontend UI (`frontend/index.html`):** Added admin-only "Scope" toggle with Personal/Global view buttons next to the existing view switcher.
+
+ * **Frontend Logic (`frontend/script.js`):**
+
+ * Added `isGlobalView` state management and view switching functions
+
+ * Enhanced warranty rendering to show owner information when in global view
+
+ * Automatic admin detection and UI initialization
+
+ * Dynamic title updates ("Your Warranties" vs "All Users' Warranties")
+
+ * **Styling (`frontend/style.css`):**
+
+ * Admin view switcher styling with primary color theme
+
+ * Owner information highlighting with colored border and background
+
+ * Responsive design for mobile devices
+
+ * **Security:** Admin-only access with proper permission checks and graceful fallbacks for non-admin users.
+
+ * *Files: `backend/app.py`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`*
+
+* **Product Photo Thumbnails on Warranty Cards:** Enhanced warranty cards with visual product photo thumbnails for quick identification and easy access to full-size images.
+
+ * **Thumbnail Display:** Product photos now appear as small thumbnails in the top right corner of each warranty card, providing instant visual recognition of products.
+
+ * **Multi-View Support:** Photo thumbnails are displayed across all warranty viewing modes:
+
+ * **Grid View:** 60px thumbnails positioned elegantly in the card corner
+
+ * **List View:** 50px thumbnails for compact horizontal layouts
+
+ * **Table View:** 40px thumbnails optimized for dense data display
+
+ * **Interactive Photo Access:** Users can click on any product photo thumbnail to open the full-size image in a new browser tab for detailed viewing.
+
+ * **Secure Image Handling:** Product photos are served through secure authentication, ensuring only authorized users can view warranty images while maintaining fast loading performance.
+
+ * **Real-time Updates:** When users add or update product photos through the warranty edit forms, the thumbnail images immediately appear on warranty cards without requiring a page refresh.
+
+ * **Visual Feedback:** Photo thumbnails include hover effects and "Click to view full size image" tooltips to clearly indicate their interactive nature.
+
+ * **Responsive Design:** Photo thumbnails automatically scale and position appropriately across different screen sizes and device types.
+
+ * *Files: `frontend/script.js`, `frontend/style.css`*
+
+### Fixed
+
+* **Status Dashboard Chart.js Canvas Errors**
+
+ * Fixed "Canvas is already in use" errors on the status page that prevented charts from rendering properly
+
+ * **Chart Destruction**: Added proper chart destruction with error handling before creating new charts
+
+ * **Multiple Initialization Prevention**: Added initialization flags to prevent multiple dashboard initializations
+
+ * **DOM Event Protection**: Protected against duplicate DOM event handler attachments
+
+ * **Improved Error Handling**: Added try-catch blocks around chart creation and destruction operations
+
+ * **View Switching Stability**: Fixed chart recreation issues when switching between personal and global views
+
+ * **Result**: Status page charts now render reliably without canvas conflicts, multiple view switches work smoothly
+
+ * *Files: `frontend/status.js`*
+
+* **CSS Cache Busting for Domain Consistency**
+
+ * Added version parameters to CSS and JavaScript files across all major pages to prevent caching issues between local IP and domain access
+
+ * **CSS Files Updated:** `style.css?v=20250529005`, `header-fix.css?v=20250529005`, `mobile-header.css?v=20250529005`, `settings-styles.css?v=20250529005`
+
+ * **JavaScript Files Updated:** `script.js?v=20250529005`, `auth.js?v=20250529005`, `settings-new.js?v=20250529005`
+
+ * Updated Service Worker cache name to `warracker-cache-v2` and included all versioned files to force cache refresh
+
+ * Fixed styling inconsistencies where admin global warranty view and other features appeared differently between local IP and domain access
+
+ * Ensures all users get consistent styling and functionality across all pages including index, settings, and status pages
+
+ * *Files: `frontend/index.html`, `frontend/settings-new.html`, `frontend/status.html`, `frontend/script.js`, `frontend/sw.js`*
+
+* **Settings Page Admin Permission Issues:** Fixed critical database connection errors and 403 permission issues preventing regular users from accessing the settings page.
+
+ * **Backend Database Connection (`backend/app.py`):** Fixed inconsistent cursor variable usage in `delete\_account()` function that was causing 500 errors when users attempted to delete their accounts (was using both `cursor` and `cur` variables inconsistently).
+
+ * **Frontend Admin Permission Checks (`frontend/settings-new.js`):** Added comprehensive admin permission checks to prevent non-admin users from triggering 403 errors:
+
+ * **Initial Load Protection:** Wrapped admin-only settings calls (`loadSiteSettings()`, `loadAppriseSettings()`, `loadAppriseSiteSettings()`) with user admin status checks during page initialization.
+
+ * **Deferred Load Protection:** Added admin checks for delayed Apprise settings loading to prevent unauthorized API calls.
+
+ * **Graceful 403 Handling:** Enhanced `loadSiteSettings()` function with proper 403 response handling that hides admin sections instead of showing error messages.
+
+ * **Improved Error Messaging:** Fixed misleading "Account cannot be deleted in offline mode" error by removing problematic nested try-catch that was masking actual API error messages. Users now see specific backend error messages instead of generic offline warnings.
+
+ * **Root Cause:** Settings page was unconditionally calling admin-only API endpoints for all users, causing 403 errors and confusing error messages for regular users.
+
+ * **Result:** Regular users can now access settings page without errors, see only relevant settings sections, and get clear error messages when actual issues occur. Admin users continue to see all settings sections as expected.
+
+ * *Files: `backend/app.py`, `frontend/settings-new.js`*
+
+* **Settings Persistence Critical Fixes:** Resolved major settings page persistence issues where user preferences would appear to save but revert to defaults when navigating away and returning.
+
+ * **Backend Settings UPDATE Logic (`backend/app.py`):** Fixed critical bug in `/api/auth/preferences` endpoint where Apprise notification settings weren't being properly saved to the database:
+
+ * **Column Detection Fix:** Changed condition from `if apprise\_notification\_time and has\_apprise\_notification\_time\_col:` to `if apprise\_notification\_time is not None and has\_apprise\_notification\_time\_col:` to handle empty string values properly
+
+ * **Complete Field Mapping:** Added missing Apprise fields (`notification\_channel`, `apprise\_notification\_time`, `apprise\_notification\_frequency`, `apprise\_timezone`) to SELECT query return fields
+
+ * **Preference Response Mapping:** Enhanced preference mapping to include all Apprise settings in API responses
+
+ * **Frontend Race Condition Fixes (`frontend/settings-new.js`):** Eliminated multiple simultaneous API calls that were causing preference loading conflicts:
+
+ * **Duplicate Request Prevention:** Fixed `loadPreferences()` being called 4 times simultaneously, causing race conditions
+
+ * **API Priority Logic:** Ensured API data takes precedence over localStorage when both exist
+
+ * **UI Synchronization:** Added proper dark mode toggle sync between API and UI state
+
+ * **Authentication Token Standardization:** Unified token usage pattern across all preference save functions
+
+ * **Root Cause:** Backend was silently failing to save Apprise settings due to strict conditional logic, while frontend race conditions were creating inconsistent data states
+
+ * **Result:** Settings now persist correctly across page navigations, with all notification preferences saving and loading reliably
+
+ * *Files: `backend/app.py`, `frontend/settings-new.js`*
+
+* **Notification System Comprehensive Overhaul:** Fixed critical timing and duplicate notification issues affecting both email and Apprise scheduled notifications.
+
+ * **Timing Logic Precision (`backend/notifications.py`):** Completely rewrote notification timing calculation for accurate delivery:
+
+ * **Precise Windows:** Changed from aggressive "send\_window or next\_miss\_window" logic to exact "0 <= time\_diff <= 2" minute windows
+
+ * **Post-Target Delivery:** Notifications now only send AFTER target time (not before) within 2-minute window to prevent early delivery
+
+ * **Enhanced Time Calculations:** Added comprehensive timezone handling with detailed debug logging showing exact time differences
+
+ * **Duplicate Prevention System (`backend/notifications.py`):** Implemented robust duplicate prevention using in-memory tracking:
+
+ * **Separate Tracking:** Independent tracking for `email\_user\_id\_date` and `apprise\_user\_id\_date` patterns
+
+ * **Daily Reset Logic:** Automatic cleanup for day rollover handling across different timezones
+
+ * **Collision Prevention:** Added 0.1s delay for manual triggers to prevent collision with scheduled jobs
+
+ * **Column Mismatch Fixes (`backend/notifications.py`):** Fixed database errors causing notification failures:
+
+ * **Error Handling:** Added try/catch around column unpacking at line 327 to handle schema mismatches
+
+ * **Variable Consistency:** Fixed missing `apprise\_timezone` variable in debug logging sections
+
+ * **Graceful Degradation:** System continues operating even with partial database schema issues
+
+ * **Enhanced Debug Output (`backend/notifications.py`):** Added comprehensive logging for troubleshooting:
+
+ * **Time Difference Display:** Shows exact calculations like "email\_time=08:20(diff:-61), apprise\_time=23:28(diff:-976)"
+
+ * **Eligibility Reasons:** Clear logging explaining why users are/aren't eligible for notifications
+
+ * **Real-time Diagnostics:** Live timing calculations visible in Docker logs for debugging
+
+ * **Root Cause:** Overly aggressive timing windows caused duplicate emails, while backend save issues prevented Apprise settings from persisting, leading to notifications not being scheduled
+
+ * **Result:** Both email and Apprise notifications now work reliably with precise timing, no duplicates, and proper settings persistence
+
+ * *Files: `backend/notifications.py`, `backend/app.py`*
+
+
+
+#### Technical Implementation for Global View Features
+
+* **Backend (app.py):**
+
+ * Added new `/api/warranties/global` endpoint accessible to all authenticated users (not just admins)
+
+ * Added `global\_view\_enabled` setting to site settings with default value 'true'
+
+ * Added `global\_view\_admin\_only` setting to site settings with default value 'false'
+
+ * Added `/api/settings/global-view-status` endpoint for checking global view availability per user
+
+ * Enhanced `/api/warranties/global` endpoint to check both global view settings and user admin status
+
+ * Added new `/api/statistics/global` endpoint for global warranty statistics with user information
+
+* **Frontend (script.js):**
+
+ * Renamed `initAdminViewControls()` to `initViewControls()` and removed admin-only restrictions
+
+ * Updated `switchToGlobalView()` to check global view setting before switching
+
+ * Added ownership and admin validation logic to conditionally render edit/delete buttons vs view-only placeholder
+
+ * Admins see edit/delete buttons for all warranties, regular users only for their own
+
+ * Modified API endpoint from `/api/admin/warranties` to `/api/warranties/global` for public access
+
+ * Added real-time global view status checking and automatic fallback to personal view
+
+* **Frontend (index.html):** Updated tooltips and labels to reflect public access
+
+* **Frontend (style.css):** Added styling for view-only placeholder button with eye icon
+
+* **Frontend (settings-new.html):** Added Global View Enabled and Global View Admin Only toggles in Site Settings section
+
+* **Frontend (settings-new.js):** Added loading and saving logic for both global view settings
+
+* **Frontend (status.html):** Added view switcher controls and owner column to warranty table for global view
+
+* **Frontend (status.js):** Added global view functionality with API switching, table column management, and permission checking
+
+#### Security Features
+
+* Backend endpoint still requires authentication (all users must be logged in)
+
+* Frontend validates warranty ownership and admin status before showing edit/delete buttons
+
+* **Regular users** can only modify warranties they own, even in global view
+
+* **Admin users** can modify any warranty in global view, maintaining administrative privileges
+
+* Maintains data privacy while providing transparency
+
+#### User Experience
+
+* Seamless view switching between personal and global views for all users
+
+* Clear visual indication (eye icon) when viewing others' warranties
+
+* Consistent UI patterns with existing admin functionality
+
+* Enhanced tooltips explaining read-only access for non-owned warranties
+
+### Enhanced
+
+* **Footer Links:** Updated all "Powered by Warracker" footer links across the application to point to `https://warracker.com` instead of the GitHub repository, providing users with direct access to the official website.
+
+ * **Files Updated:** `index.html`, `login.html`, `register.html`, `reset-password.html`, `reset-password-request.html`, `settings-new.html`, `status.html`, `auth-redirect.html`, and `about.html`
+
+ * **Result:** Consistent branding and improved user experience with direct access to the official Warracker website.
+
+* **PostgreSQL Security Hardening:** Removed unnecessary SUPERUSER privileges from the application database user, significantly improving security posture.
+
+ * **Security Improvement:** Eliminated SUPERUSER grants that provided excessive and unnecessary privileges to the application database user
+
+ * **Files Modified:**
+
+ * `backend/fix\_permissions.sql`: Removed `ALTER ROLE %(db\_user)s WITH SUPERUSER;`
+
+ * `backend/migrations/011\_ensure\_admin\_permissions.sql`: Commented out SUPERUSER grant
+
+ * `Dockerfile`: Removed retry loop attempting to grant SUPERUSER privileges via psql
+
+ * **Principle of Least Privilege:** Application now operates with only the specific database privileges required for normal operation (CREATE/DROP/ALTER on tables, sequences, functions, etc.)
+
+ * **Testing Verified:** Full application functionality confirmed to work correctly without SUPERUSER privileges, including migrations, user management, and all admin operations
+
+ * **Security Benefit:** Significantly reduces attack surface - if the application is compromised, an attacker no longer has complete database administrative control
+
+ * **Result:** Maintained full application functionality while eliminating unnecessary security risks
+
+## 0\.10.0.0 - 2025-06-4
+
+### Fixed
+
+* **View Preference Persistence Issue:** Fixed user view preferences (Grid, List, Table) not consistently persisting across logins.
+
+ * **Backend (`backend/app.py`):** Modified `/api/auth/login` endpoint to include `is\_admin` flag in the returned user object, ensuring proper view preference key prefix calculation immediately after login.
+
+ * **Frontend (`frontend/script.js`):**
+
+ * Enhanced `switchView()` function with `saveToApi` parameter to control when view preferences are saved to the API, preventing unintended overwrites during initialization.
+
+ * Modified `loadViewPreference()` to call `switchView` with `saveToApi = false` to prevent overwriting user's actual preferences with defaults.
+
+ * Updated storage event listener for cross-tab synchronization to prevent redundant API saves when syncing view preferences between browser tabs.
+
+ * **Root Cause:** Missing `is\_admin` flag caused incorrect localStorage prefix usage and race conditions where preferences were saved with wrong prefix then not found when correct prefix was established.
+
+ * **Result:** View preferences now properly persist across logins and synchronize between browser tabs for both admin and regular users.
+
+* **Password Management Issues:** Fixed critical password change and reset functionality problems.
+
+ * **Missing Password Change Endpoint (`backend/app.py`):** Implemented `/api/auth/password/change` endpoint to allow logged-in users to change their passwords through the Settings page. The endpoint validates current password, checks new password strength, and securely updates the user's password hash.
+
+ * **Frontend Error Handling (`frontend/settings-new.js`):** Fixed misleading "Password cannot be changed in offline mode" error by removing nested try-catch block that was masking real API error messages. Now properly displays specific backend error messages.
+
+ * **Password Reset Link Issue (`frontend/reset-password.html`):** Fixed "Invalid or Expired Link" error by removing premature token verification that was calling a non-existent `/api/auth/password/verify-token` endpoint. Token validity is now properly checked only during form submission.
+
+ * **Root Cause:** Backend endpoint was missing entirely, frontend had incorrect error handling, and reset page was making unnecessary token verification calls.
+
+ * **Result:** Users can now successfully change passwords while logged in and use password reset links without encountering false error messages.
+
+* **SMTP Port 587 (STARTTLS) Functionality:** Enhanced email sending to support both port 465 (SMTPS/SSL) and port 587 (STARTTLS) configurations.
+
+ * **Enhanced SMTP Connection Logic (`backend/app.py`):** Updated `send\_password\_reset\_email()`, `send\_expiration\_notifications()`, and `send\_email\_change\_verification\_email()` functions with robust port-based SMTP logic.
+
+ * **Port 465:** Uses `smtplib.SMTP\_SSL()` for direct SSL connection
+
+ * **Port 587:** Uses `smtplib.SMTP()` followed by `starttls()` for STARTTLS encryption
+
+ * **Other Ports:** Respects `SMTP\_USE\_TLS` environment variable for explicit STARTTLS control
+
+ * **Environment Variable Support:** Added intelligent defaults where `SMTP\_USE\_TLS` defaults to true for port 587 unless explicitly set to false, ensuring proper STARTTLS behavior.
+
+ * **Root Cause:** Previous logic used restrictive hostname-based conditions (`if smtp\_host != 'localhost'`) instead of proper port-based SMTP configuration, causing STARTTLS failures with external SMTP servers on port 587.
+
+ * **Result:** Email sending now works reliably with both common SMTP configurations, supporting major email providers like Gmail, Office 365, and other services using port 587.
+
+* **Header Appearance Standardization (`frontend/reset-password-request.html`, `frontend/reset-password.html`):** Standardized headers to match consistent appearance across all pages.
+
+ * **Missing CSS Includes:** Added `header-fix.css` and `fix-auth-buttons-loader.js` to ensure consistent header styling and behavior.
+
+ * **Clickable Title:** Made "Warracker" title a clickable link to `index.html` for consistent navigation, matching other auth pages like `login.html` and `register.html`.
+
+ * **Registration Status Script:** Added `registration-status.js` for consistent functionality across auth pages.
+
+ * **Root Cause:** Pages were missing key CSS files and scripts that ensure header consistency, and the title was not a link unlike other pages.
+
+ * **Result:** Headers now have identical appearance, dimensions, and responsive behavior as other application pages, providing consistent user experience.
+
+### Enhanced
+
+* **Footer Links:** Updated all "Powered by Warracker" footer links across the application to point to `https://warracker.com` instead of the GitHub repository, providing users with direct access to the official website.
+
+ * **Files Updated:** `index.html`, `login.html`, `register.html`, `reset-password.html`, `reset-password-request.html`, `settings-new.html`, `status.html`, `auth-redirect.html`, and `about.html`
+
+ * **Result:** Consistent branding and improved user experience with direct access to the official Warracker website.
+
+## 0\.9.9.9 - 2025-06-01
+
+### Added
+
+* **OIDC SSO (Single Sign-On) Integration:**
+
+ * Implemented OpenID Connect (OIDC) authentication flow using Authlib, allowing users to log in via external OIDC providers (e.g., Google, Keycloak).
+
+ * **Backend (`app.py`):**
+
+ * OIDC client configuration (Client ID, Secret, Issuer URL, Scope, Provider Name) is dynamically loaded from the `site\_settings` database table at application startup.
+
+ * OIDC feature can be enabled/disabled globally via the `oidc\_enabled` setting in the database.
+
+ * Added OIDC-specific routes: `/api/oidc/login` (initiates login) and `/api/oidc/callback` (handles redirect from IdP).
+
+ * User provisioning: If an OIDC user doesn't exist locally, a new user account is created. Existing OIDC users are logged in.
+
+ * Updated Admin Settings API (`/api/admin/settings`) to manage these OIDC parameters.
+
+ * Database migration `023\_add\_oidc\_columns\_to\_users.sql` adds `oidc\_sub`, `oidc\_issuer` to `users` table and `login\_method` to `user\_sessions` table for linking local users to OIDC identities.
+
+ * **Frontend:**
+
+ * **Login Page (`login.html`, `auth.js`):** Added an "Login with SSO Provider" button that initiates the OIDC flow.
+
+ * **Admin Settings Page (`settings-new.html`, `settings-new.js`):** New "OIDC SSO Configuration" section for admins to enable/disable OIDC and configure provider details.
+
+ * **Auth Redirect Page (`auth-redirect.html`):** Handles the token received from the `/api/oidc/callback` and logs the user in.
+
+ * **Dependencies (`requirements.txt`):** Added `Authlib` and `requests`.
+
+ * *Files: `backend/app.py`, `backend/migrations/023\_add\_oidc\_columns\_to\_users.sql`, `backend/requirements.txt`, `frontend/login.html`, `frontend/auth.js`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/auth-redirect.html`*
+
+* **SSO Registration Control:** When the site's registration setting is disabled, new users cannot register via SSO. Only existing users who already have accounts can use SSO to log in. This provides administrators with granular control over user registration while maintaining SSO functionality for existing users.
+
+ * **Backend:** Enhanced OIDC callback handler to check the `registration\_enabled` site setting before creating new user accounts via SSO.
+
+ * **Frontend:** Added appropriate error message for users when SSO registration is blocked due to disabled registrations.
+
+ * First user registration via SSO is still allowed regardless of the setting (same as regular registration).
+
+ * *Files: `backend/oidc\_handler.py`, `frontend/auth-redirect.html`*
+
+* **Provider-Specific SSO Button Branding:** Enhanced the SSO login button to show provider-specific branding and icons for well-known OIDC providers.
+
+ * **Supported Providers:** Google, GitHub, Microsoft/Azure, Facebook, Twitter, LinkedIn, Apple, Discord, GitLab, Bitbucket, Keycloak, and Okta.
+
+ * **Dynamic Button Text:** Shows "Login with Google", "Login with GitHub", etc., based on the configured `OIDC\_PROVIDER\_NAME`.
+
+ * **Provider Icons:** Uses appropriate Font Awesome icons for each provider (e.g., Google logo for Google, GitHub logo for GitHub).
+
+ * **Brand Colors:** Each provider button uses authentic brand colors with proper hover effects.
+
+ * **Fallback Support:** Unknown providers display the generic "Login with SSO Provider" button with default styling.
+
+ * **Environment Integration:** Works automatically with the `OIDC\_PROVIDER\_NAME` environment variable and database settings.
+
+ * *Files: `frontend/login.html`, `backend/oidc\_handler.py`*
+
+* **Exact Expiration Date Input:** Enhanced warranty entry to support exact expiration dates as an alternative to duration-based input.
+
+ * **New Warranty Input Method:** Users can now choose between "Warranty Duration" (years/months/days) and "Exact Expiration Date" options when adding or editing warranties.
+
+ * **UI Enhancements:** Added radio button selection for warranty entry method with smooth form field transitions and validation.
+
+ * **Backend Support:** Both `add\_warranty` and `update\_warranty` API endpoints now handle `exact\_expiration\_date` parameter alongside duration fields.
+
+ * **Smart Duration Display:** Warranty cards automatically calculate and display duration text even when using exact expiration dates, eliminating "N/A" values.
+
+ * **Form Validation:** Enhanced validation ensures either exact date or duration is provided for non-lifetime warranties, with appropriate error messages.
+
+ * **Date Calculation:** Added robust date calculation helper function that properly handles different month lengths, leap years, and edge cases.
+
+ * *Files: `frontend/index.html`, `frontend/script.js`, `frontend/style.css`, `backend/app.py`*
+
+* **Complete Field Updates:** All warranty fields (product info, dates, serial numbers, tags, documents) update immediately in the interface.
+
+ * **Fallback Safety:** Maintains fallback to server reload if local update fails, ensuring data consistency.
+
+ * *Files: `frontend/script.js`*
+
+* **Memory Usage Optimization:** Significantly reduced RAM consumption for better performance on resource-constrained servers.
+
+ * **Dynamic Memory Modes:** Configurable via `WARRACKER\_MEMORY\_MODE` environment variable with "optimized" (default), "ultra-light", and "performance" options.
+
+ * **Optimized Mode:** 2 gevent workers with 128MB memory limits (~60-80MB total RAM usage).
+
+ * **Ultra-Light Mode:** 1 sync worker with 64MB memory limit (~40-50MB total RAM usage for minimal servers).
+
+ * **Performance Mode:** 4 gevent workers with 256MB memory limits (~150-200MB total RAM usage for high-performance servers).
+
+ * **Worker Configuration:** Added memory limits per worker, connection pooling optimization, and preload\_app for memory sharing.
+
+ * **Database Pool:** Optimized connection pool from 10 to 4 maximum connections with memory-conscious settings.
+
+ * **Flask Configuration:** Added memory-efficient settings including disabled JSON sorting, optimized session handling, and file serving optimizations.
+
+ * **Dependency Addition:** Added gevent for more efficient async request handling compared to sync workers.
+
+ * **Expected Reduction:** RAM usage configurable from ~40MB (ultra-light) to ~200MB (performance) based on server specifications.
+
+ * *Files: `backend/gunicorn\_config.py`, `backend/requirements.txt`, `backend/app.py`, `backend/db\_handler.py`, `docker-compose.yml`*
+
+### Changed
+
+* **Environment Variables for OIDC (Docker):** While OIDC configuration is primarily managed via the database through the admin UI, the `docker-compose.yml` can include placeholder environment variables for initial setup or documentation:
+
+ * `OIDC\_ENABLED` (e.g., `true` or `false`)
+
+ * `OIDC\_PROVIDER\_NAME` (e.g., `google`, `keycloak`)
+
+ * `OIDC\_CLIENT\_ID`
+
+ * `OIDC\_CLIENT\_SECRET`
+
+ * `OIDC\_ISSUER\_URL`
+
+ * `OIDC\_SCOPE` (e.g., `openid email profile`)
+
+* **`FRONTEND\_URL` Environment Variable:** Emphasized the importance of correctly setting the `FRONTEND\_URL` environment variable for the backend service in `docker-compose.yml` to ensure correct OIDC callback redirects.
+
+ * *Files: `docker-compose.yml`, `Docker/docker-compose.yml`*
### Fixed
-- **Status Dashboard Chart.js Canvas Errors**
- - Fixed "Canvas is already in use" errors on the status page that prevented charts from rendering properly
- - **Chart Destruction**: Added proper chart destruction with error handling before creating new charts
- - **Multiple Initialization Prevention**: Added initialization flags to prevent multiple dashboard initializations
- - **DOM Event Protection**: Protected against duplicate DOM event handler attachments
- - **Improved Error Handling**: Added try-catch blocks around chart creation and destruction operations
- - **View Switching Stability**: Fixed chart recreation issues when switching between personal and global views
- - **Result**: Status page charts now render reliably without canvas conflicts, multiple view switches work smoothly
- - _Files: `frontend/status.js`_
-
-- **CSS Cache Busting for Domain Consistency**
- - Added version parameters to CSS and JavaScript files across all major pages to prevent caching issues between local IP and domain access
- - **CSS Files Updated:** `style.css?v=20250529005`, `header-fix.css?v=20250529005`, `mobile-header.css?v=20250529005`, `settings-styles.css?v=20250529005`
- - **JavaScript Files Updated:** `script.js?v=20250529005`, `auth.js?v=20250529005`, `settings-new.js?v=20250529005`
- - Updated Service Worker cache name to `warracker-cache-v2` and included all versioned files to force cache refresh
- - Fixed styling inconsistencies where admin global warranty view and other features appeared differently between local IP and domain access
- - Ensures all users get consistent styling and functionality across all pages including index, settings, and status pages
- - _Files: `frontend/index.html`, `frontend/settings-new.html`, `frontend/status.html`, `frontend/script.js`, `frontend/sw.js`_
-- **Settings Page Admin Permission Issues:** Fixed critical database connection errors and 403 permission issues preventing regular users from accessing the settings page.
- - **Backend Database Connection (`backend/app.py`):** Fixed inconsistent cursor variable usage in `delete_account()` function that was causing 500 errors when users attempted to delete their accounts (was using both `cursor` and `cur` variables inconsistently).
- - **Frontend Admin Permission Checks (`frontend/settings-new.js`):** Added comprehensive admin permission checks to prevent non-admin users from triggering 403 errors:
- - **Initial Load Protection:** Wrapped admin-only settings calls (`loadSiteSettings()`, `loadAppriseSettings()`, `loadAppriseSiteSettings()`) with user admin status checks during page initialization.
- - **Deferred Load Protection:** Added admin checks for delayed Apprise settings loading to prevent unauthorized API calls.
- - **Graceful 403 Handling:** Enhanced `loadSiteSettings()` function with proper 403 response handling that hides admin sections instead of showing error messages.
- - **Improved Error Messaging:** Fixed misleading "Account cannot be deleted in offline mode" error by removing problematic nested try-catch that was masking actual API error messages. Users now see specific backend error messages instead of generic offline warnings.
- - **Root Cause:** Settings page was unconditionally calling admin-only API endpoints for all users, causing 403 errors and confusing error messages for regular users.
- - **Result:** Regular users can now access settings page without errors, see only relevant settings sections, and get clear error messages when actual issues occur. Admin users continue to see all settings sections as expected.
- - _Files: `backend/app.py`, `frontend/settings-new.js`_
-
-- **Settings Persistence Critical Fixes:** Resolved major settings page persistence issues where user preferences would appear to save but revert to defaults when navigating away and returning.
- - **Backend Settings UPDATE Logic (`backend/app.py`):** Fixed critical bug in `/api/auth/preferences` endpoint where Apprise notification settings weren't being properly saved to the database:
- - **Column Detection Fix:** Changed condition from `if apprise_notification_time and has_apprise_notification_time_col:` to `if apprise_notification_time is not None and has_apprise_notification_time_col:` to handle empty string values properly
- - **Complete Field Mapping:** Added missing Apprise fields (`notification_channel`, `apprise_notification_time`, `apprise_notification_frequency`, `apprise_timezone`) to SELECT query return fields
- - **Preference Response Mapping:** Enhanced preference mapping to include all Apprise settings in API responses
- - **Frontend Race Condition Fixes (`frontend/settings-new.js`):** Eliminated multiple simultaneous API calls that were causing preference loading conflicts:
- - **Duplicate Request Prevention:** Fixed `loadPreferences()` being called 4 times simultaneously, causing race conditions
- - **API Priority Logic:** Ensured API data takes precedence over localStorage when both exist
- - **UI Synchronization:** Added proper dark mode toggle sync between API and UI state
- - **Authentication Token Standardization:** Unified token usage pattern across all preference save functions
- - **Root Cause:** Backend was silently failing to save Apprise settings due to strict conditional logic, while frontend race conditions were creating inconsistent data states
- - **Result:** Settings now persist correctly across page navigations, with all notification preferences saving and loading reliably
- - _Files: `backend/app.py`, `frontend/settings-new.js`_
-
-- **Notification System Comprehensive Overhaul:** Fixed critical timing and duplicate notification issues affecting both email and Apprise scheduled notifications.
- - **Timing Logic Precision (`backend/notifications.py`):** Completely rewrote notification timing calculation for accurate delivery:
- - **Precise Windows:** Changed from aggressive "send_window or next_miss_window" logic to exact "0 <= time_diff <= 2" minute windows
- - **Post-Target Delivery:** Notifications now only send AFTER target time (not before) within 2-minute window to prevent early delivery
- - **Enhanced Time Calculations:** Added comprehensive timezone handling with detailed debug logging showing exact time differences
- - **Duplicate Prevention System (`backend/notifications.py`):** Implemented robust duplicate prevention using in-memory tracking:
- - **Separate Tracking:** Independent tracking for `email_{user_id}_{date}` and `apprise_{user_id}_{date}` patterns
- - **Daily Reset Logic:** Automatic cleanup for day rollover handling across different timezones
- - **Collision Prevention:** Added 0.1s delay for manual triggers to prevent collision with scheduled jobs
- - **Column Mismatch Fixes (`backend/notifications.py`):** Fixed database errors causing notification failures:
- - **Error Handling:** Added try/catch around column unpacking at line 327 to handle schema mismatches
- - **Variable Consistency:** Fixed missing `apprise_timezone` variable in debug logging sections
- - **Graceful Degradation:** System continues operating even with partial database schema issues
- - **Enhanced Debug Output (`backend/notifications.py`):** Added comprehensive logging for troubleshooting:
- - **Time Difference Display:** Shows exact calculations like "email_time=08:20(diff:-61), apprise_time=23:28(diff:-976)"
- - **Eligibility Reasons:** Clear logging explaining why users are/aren't eligible for notifications
- - **Real-time Diagnostics:** Live timing calculations visible in Docker logs for debugging
- - **Root Cause:** Overly aggressive timing windows caused duplicate emails, while backend save issues prevented Apprise settings from persisting, leading to notifications not being scheduled
- - **Result:** Both email and Apprise notifications now work reliably with precise timing, no duplicates, and proper settings persistence
- - _Files: `backend/notifications.py`, `backend/app.py`_
+* Resolved various startup and runtime errors related to OIDC client initialization in a multi-worker (Gunicorn) environment, particularly concerning database connection pool stability and consistent loading of OIDC settings.
+
+* Corrected OIDC metadata fetching by ensuring the proper Issuer URL is used (e.g., `https://accounts.google.com` for Google).
+
+* Resolved `TypeError: Cannot read properties of null (reading 'classList')` during logout on `about.html` by ensuring the `loadingContainer` element is present and accessible to `script.js`'s `showLoading()` function. Modified `showLoading()` and `hideLoading()` to dynamically find the container if not initially available.
+
+* Fixed `SyntaxError: Identifier 'AuthManager' has already been declared` on `about.html` by removing a duplicate import of `auth.js` from the `<head>`, ensuring it is loaded only once at the end of the `<body>`.
+
+* Standardized the user menu dropdown button ID to `userMenuBtn` across `index.html`, `status.html`, and `about.html`. Consolidated user menu JavaScript logic into `auth.js`, removing redundant code from `settings-new.js` and `fix-auth-buttons.js` to ensure consistent dropdown behavior.
+
+ * *Files: `backend/app.py`, `frontend/about.html`, `frontend/script.js`, `frontend/index.html`, `frontend/status.html`, `frontend/auth.js`, `frontend/settings-new.js`, `frontend/fix-auth-buttons.js`*
+
+* **SSO Warranty Display Issue:** Fixed a critical timing problem where SSO users would see a blank warranty list after login. The issue was caused by a race condition where user preferences were loaded before user authentication was fully established.
+
+ * Enhanced `auth-redirect.html` to fetch and store user information immediately after SSO login, ensuring `user\_info` is available when the main application loads.
+
+ * Fixed preference key prefix calculation to prevent mismatched user preference keys for SSO users.
+
+ * *Files: `frontend/auth-redirect.html`, `frontend/auth.js`, `frontend/script.js`*
+
+* **SSO Tag Creation Issue:** Resolved an issue where SSO users could not create new tags due to authentication token handling problems.
+
+ * Updated tag creation functions (`createTag`, `updateTag`, `deleteTag`) to use `window.auth.getToken()` instead of directly accessing localStorage.
+
+ * Added enhanced error handling and debugging for tag creation API calls.
+
+ * Ensured consistent token management across all tag-related operations.
+
+ * *Files: `frontend/script.js`*
+
+* **Database Tag Constraint Issue:** Fixed database constraint violation that prevented users from creating tags with names that already existed for other users.
+
+ * Created migration `024\_fix\_tags\_constraint.sql` to update the database schema.
+
+ * Dropped the old `tags\_name\_key` unique constraint that only considered tag names.
+
+ * Added new `tags\_name\_user\_id\_key` constraint allowing the same tag name for different users.
+
+ * Added proper user\_id foreign key constraint and performance index.
+
+ * *Files: `backend/migrations/024\_fix\_tags\_constraint.sql`*
+
+* **About Page User Menu Issue:** Fixed user menu dropdown not functioning on the about page for SSO users.
+
+ * Resolved script loading order conflicts that prevented user menu event listeners from being attached.
+
+ * Moved inline authentication check from head to body to prevent timing conflicts with `auth.js`.
+
+ * Added backup user menu handler specifically for the about page with enhanced debugging.
+
+ * Fixed JavaScript error caused by `getEventListeners` function not being available in all browsers.
+
+ * *Files: `frontend/about.html`, `frontend/auth.js`*
+
+* **About Page Logout Issue:** Resolved logout functionality errors on the about page.
+
+ * Added safe loading spinner functions specifically for the about page to prevent `TypeError: Cannot read properties of null (reading 'classList')` error.
+
+ * Implemented backup logout handler with multiple fallback levels for reliability.
+
+ * Ensured logout works even when main auth system encounters errors.
+
+ * *Files: `frontend/about.html`, `frontend/script.js`*
+
+* **Immediate Warranty Updates:** Optimized warranty editing for instant UI updates without server reloads.
+
+ * **Performance Improvement:** Warranty changes now appear immediately in the UI instead of waiting for server data reload.
+
+ * **Local Data Sync:** Edit modal updates local warranty data instantly upon successful save, eliminating loading delays.
+
+ * **Robust Date Handling:** Enhanced date arithmetic for duration-based warranties with proper month/year overflow handling.
+ * **Complete Field Updates:** All warranty fields (product info, dates, serial numbers, tags, documents) update immediately in the interface.
-#### Technical Implementation for Global View Features
-- **Backend (app.py):**
- - Added new `/api/warranties/global` endpoint accessible to all authenticated users (not just admins)
- - Added `global_view_enabled` setting to site settings with default value 'true'
- - Added `global_view_admin_only` setting to site settings with default value 'false'
- - Added `/api/settings/global-view-status` endpoint for checking global view availability per user
- - Enhanced `/api/warranties/global` endpoint to check both global view settings and user admin status
- - Added new `/api/statistics/global` endpoint for global warranty statistics with user information
-- **Frontend (script.js):**
- - Renamed `initAdminViewControls()` to `initViewControls()` and removed admin-only restrictions
- - Updated `switchToGlobalView()` to check global view setting before switching
- - Added ownership and admin validation logic to conditionally render edit/delete buttons vs view-only placeholder
- - Admins see edit/delete buttons for all warranties, regular users only for their own
- - Modified API endpoint from `/api/admin/warranties` to `/api/warranties/global` for public access
- - Added real-time global view status checking and automatic fallback to personal view
-- **Frontend (index.html):** Updated tooltips and labels to reflect public access
-- **Frontend (style.css):** Added styling for view-only placeholder button with eye icon
-- **Frontend (settings-new.html):** Added Global View Enabled and Global View Admin Only toggles in Site Settings section
-- **Frontend (settings-new.js):** Added loading and saving logic for both global view settings
-- **Frontend (status.html):** Added view switcher controls and owner column to warranty table for global view
-- **Frontend (status.js):** Added global view functionality with API switching, table column management, and permission checking
+ * **Fallback Safety:** Maintains fallback to server reload if local update fails, ensuring data consistency.
-#### Security Features
-- Backend endpoint still requires authentication (all users must be logged in)
-- Frontend validates warranty ownership and admin status before showing edit/delete buttons
-- **Regular users** can only modify warranties they own, even in global view
-- **Admin users** can modify any warranty in global view, maintaining administrative privileges
-- Maintains data privacy while providing transparency
+ * *Files: `frontend/script.js`*
-#### User Experience
-- Seamless view switching between personal and global views for all users
-- Clear visual indication (eye icon) when viewing others' warranties
-- Consistent UI patterns with existing admin functionality
-- Enhanced tooltips explaining read-only access for non-owned warranties
-
-### Enhanced
-- **Footer Links:** Updated all "Powered by Warracker" footer links across the application to point to `https://warracker.com` instead of the GitHub repository, providing users with direct access to the official website.
- - **Files Updated:** `index.html`, `login.html`, `register.html`, `reset-password.html`, `reset-password-request.html`, `settings-new.html`, `status.html`, `auth-redirect.html`, and `about.html`
- - **Result:** Consistent branding and improved user experience with direct access to the official Warracker website.
-
-- **PostgreSQL Security Hardening:** Removed unnecessary SUPERUSER privileges from the application database user, significantly improving security posture.
- - **Security Improvement:** Eliminated SUPERUSER grants that provided excessive and unnecessary privileges to the application database user
- - **Files Modified:**
- - `backend/fix_permissions.sql`: Removed `ALTER ROLE %(db_user)s WITH SUPERUSER;`
- - `backend/migrations/011_ensure_admin_permissions.sql`: Commented out SUPERUSER grant
- - `Dockerfile`: Removed retry loop attempting to grant SUPERUSER privileges via psql
- - **Principle of Least Privilege:** Application now operates with only the specific database privileges required for normal operation (CREATE/DROP/ALTER on tables, sequences, functions, etc.)
- - **Testing Verified:** Full application functionality confirmed to work correctly without SUPERUSER privileges, including migrations, user management, and all admin operations
- - **Security Benefit:** Significantly reduces attack surface - if the application is compromised, an attacker no longer has complete database administrative control
- - **Result:** Maintained full application functionality while eliminating unnecessary security risks
-
-## 0.10.0.0 - 2025-06-4
+* **Warranty Entry Method Persistence:** Fixed warranty entry method selection not being remembered correctly in edit modal.
-### Fixed
-- **View Preference Persistence Issue:** Fixed user view preferences (Grid, List, Table) not consistently persisting across logins.
- - **Backend (`backend/app.py`):** Modified `/api/auth/login` endpoint to include `is_admin` flag in the returned user object, ensuring proper view preference key prefix calculation immediately after login.
- - **Frontend (`frontend/script.js`):**
- - Enhanced `switchView()` function with `saveToApi` parameter to control when view preferences are saved to the API, preventing unintended overwrites during initialization.
- - Modified `loadViewPreference()` to call `switchView` with `saveToApi = false` to prevent overwriting user's actual preferences with defaults.
- - Updated storage event listener for cross-tab synchronization to prevent redundant API saves when syncing view preferences between browser tabs.
- - **Root Cause:** Missing `is_admin` flag caused incorrect localStorage prefix usage and race conditions where preferences were saved with wrong prefix then not found when correct prefix was established.
- - **Result:** View preferences now properly persist across logins and synchronize between browser tabs for both admin and regular users.
-- **Password Management Issues:** Fixed critical password change and reset functionality problems.
- - **Missing Password Change Endpoint (`backend/app.py`):** Implemented `/api/auth/password/change` endpoint to allow logged-in users to change their passwords through the Settings page. The endpoint validates current password, checks new password strength, and securely updates the user's password hash.
- - **Frontend Error Handling (`frontend/settings-new.js`):** Fixed misleading "Password cannot be changed in offline mode" error by removing nested try-catch block that was masking real API error messages. Now properly displays specific backend error messages.
- - **Password Reset Link Issue (`frontend/reset-password.html`):** Fixed "Invalid or Expired Link" error by removing premature token verification that was calling a non-existent `/api/auth/password/verify-token` endpoint. Token validity is now properly checked only during form submission.
- - **Root Cause:** Backend endpoint was missing entirely, frontend had incorrect error handling, and reset page was making unnecessary token verification calls.
- - **Result:** Users can now successfully change passwords while logged in and use password reset links without encountering false error messages.
-- **SMTP Port 587 (STARTTLS) Functionality:** Enhanced email sending to support both port 465 (SMTPS/SSL) and port 587 (STARTTLS) configurations.
- - **Enhanced SMTP Connection Logic (`backend/app.py`):** Updated `send_password_reset_email()`, `send_expiration_notifications()`, and `send_email_change_verification_email()` functions with robust port-based SMTP logic.
- - **Port 465:** Uses `smtplib.SMTP_SSL()` for direct SSL connection
- - **Port 587:** Uses `smtplib.SMTP()` followed by `starttls()` for STARTTLS encryption
- - **Other Ports:** Respects `SMTP_USE_TLS` environment variable for explicit STARTTLS control
- - **Environment Variable Support:** Added intelligent defaults where `SMTP_USE_TLS` defaults to true for port 587 unless explicitly set to false, ensuring proper STARTTLS behavior.
- - **Root Cause:** Previous logic used restrictive hostname-based conditions (`if smtp_host != 'localhost'`) instead of proper port-based SMTP configuration, causing STARTTLS failures with external SMTP servers on port 587.
- - **Result:** Email sending now works reliably with both common SMTP configurations, supporting major email providers like Gmail, Office 365, and other services using port 587.
-- **Header Appearance Standardization (`frontend/reset-password-request.html`, `frontend/reset-password.html`):** Standardized headers to match consistent appearance across all pages.
- - **Missing CSS Includes:** Added `header-fix.css` and `fix-auth-buttons-loader.js` to ensure consistent header styling and behavior.
- - **Clickable Title:** Made "Warracker" title a clickable link to `index.html` for consistent navigation, matching other auth pages like `login.html` and `register.html`.
- - **Registration Status Script:** Added `registration-status.js` for consistent functionality across auth pages.
- - **Root Cause:** Pages were missing key CSS files and scripts that ensure header consistency, and the title was not a link unlike other pages.
- - **Result:** Headers now have identical appearance, dimensions, and responsive behavior as other application pages, providing consistent user experience.
-### Enhanced
-- **Footer Links:** Updated all "Powered by Warracker" footer links across the application to point to `https://warracker.com` instead of the GitHub repository, providing users with direct access to the official website.
- - **Files Updated:** `index.html`, `login.html`, `register.html`, `reset-password.html`, `reset-password-request.html`, `settings-new.html`, `status.html`, `auth-redirect.html`, and `about.html`
- - **Result:** Consistent branding and improved user experience with direct access to the official Warracker website.
-
-## 0.9.9.9 - 2025-06-01
+ * **Issue:** When editing warranties that were created using "Exact Expiration Date" method, the edit modal would incorrectly switch to "Warranty Duration" method.
-### Added
-- **OIDC SSO (Single Sign-On) Integration:**
- - Implemented OpenID Connect (OIDC) authentication flow using Authlib, allowing users to log in via external OIDC providers (e.g., Google, Keycloak).
- - **Backend (`app.py`):**
- - OIDC client configuration (Client ID, Secret, Issuer URL, Scope, Provider Name) is dynamically loaded from the `site_settings` database table at application startup.
- - OIDC feature can be enabled/disabled globally via the `oidc_enabled` setting in the database.
- - Added OIDC-specific routes: `/api/oidc/login` (initiates login) and `/api/oidc/callback` (handles redirect from IdP).
- - User provisioning: If an OIDC user doesn't exist locally, a new user account is created. Existing OIDC users are logged in.
- - Updated Admin Settings API (`/api/admin/settings`) to manage these OIDC parameters.
- - Database migration `023_add_oidc_columns_to_users.sql` adds `oidc_sub`, `oidc_issuer` to `users` table and `login_method` to `user_sessions` table for linking local users to OIDC identities.
- - **Frontend:**
- - **Login Page (`login.html`, `auth.js`):** Added an "Login with SSO Provider" button that initiates the OIDC flow.
- - **Admin Settings Page (`settings-new.html`, `settings-new.js`):** New "OIDC SSO Configuration" section for admins to enable/disable OIDC and configure provider details.
- - **Auth Redirect Page (`auth-redirect.html`):** Handles the token received from the `/api/oidc/callback` and logs the user in.
- - **Dependencies (`requirements.txt`):** Added `Authlib` and `requests`.
- - _Files: `backend/app.py`, `backend/migrations/023_add_oidc_columns_to_users.sql`, `backend/requirements.txt`, `frontend/login.html`, `frontend/auth.js`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/auth-redirect.html`_
-- **SSO Registration Control:** When the site's registration setting is disabled, new users cannot register via SSO. Only existing users who already have accounts can use SSO to log in. This provides administrators with granular control over user registration while maintaining SSO functionality for existing users.
- - **Backend:** Enhanced OIDC callback handler to check the `registration_enabled` site setting before creating new user accounts via SSO.
- - **Frontend:** Added appropriate error message for users when SSO registration is blocked due to disabled registrations.
- - First user registration via SSO is still allowed regardless of the setting (same as regular registration).
- - _Files: `backend/oidc_handler.py`, `frontend/auth-redirect.html`_
-- **Provider-Specific SSO Button Branding:** Enhanced the SSO login button to show provider-specific branding and icons for well-known OIDC providers.
- - **Supported Providers:** Google, GitHub, Microsoft/Azure, Facebook, Twitter, LinkedIn, Apple, Discord, GitLab, Bitbucket, Keycloak, and Okta.
- - **Dynamic Button Text:** Shows "Login with Google", "Login with GitHub", etc., based on the configured `OIDC_PROVIDER_NAME`.
- - **Provider Icons:** Uses appropriate Font Awesome icons for each provider (e.g., Google logo for Google, GitHub logo for GitHub).
- - **Brand Colors:** Each provider button uses authentic brand colors with proper hover effects.
- - **Fallback Support:** Unknown providers display the generic "Login with SSO Provider" button with default styling.
- - **Environment Integration:** Works automatically with the `OIDC_PROVIDER_NAME` environment variable and database settings.
- - _Files: `frontend/login.html`, `backend/oidc_handler.py`_
-- **Exact Expiration Date Input:** Enhanced warranty entry to support exact expiration dates as an alternative to duration-based input.
- - **New Warranty Input Method:** Users can now choose between "Warranty Duration" (years/months/days) and "Exact Expiration Date" options when adding or editing warranties.
- - **UI Enhancements:** Added radio button selection for warranty entry method with smooth form field transitions and validation.
- - **Backend Support:** Both `add_warranty` and `update_warranty` API endpoints now handle `exact_expiration_date` parameter alongside duration fields.
- - **Smart Duration Display:** Warranty cards automatically calculate and display duration text even when using exact expiration dates, eliminating "N/A" values.
- - **Form Validation:** Enhanced validation ensures either exact date or duration is provided for non-lifetime warranties, with appropriate error messages.
- - **Date Calculation:** Added robust date calculation helper function that properly handles different month lengths, leap years, and edge cases.
- - _Files: `frontend/index.html`, `frontend/script.js`, `frontend/style.css`, `backend/app.py`_
-- **Complete Field Updates:** All warranty fields (product info, dates, serial numbers, tags, documents) update immediately in the interface.
- - **Fallback Safety:** Maintains fallback to server reload if local update fails, ensuring data consistency.
- - _Files: `frontend/script.js`_
-- **Memory Usage Optimization:** Significantly reduced RAM consumption for better performance on resource-constrained servers.
- - **Dynamic Memory Modes:** Configurable via `WARRACKER_MEMORY_MODE` environment variable with "optimized" (default), "ultra-light", and "performance" options.
- - **Optimized Mode:** 2 gevent workers with 128MB memory limits (~60-80MB total RAM usage).
- - **Ultra-Light Mode:** 1 sync worker with 64MB memory limit (~40-50MB total RAM usage for minimal servers).
- - **Performance Mode:** 4 gevent workers with 256MB memory limits (~150-200MB total RAM usage for high-performance servers).
- - **Worker Configuration:** Added memory limits per worker, connection pooling optimization, and preload_app for memory sharing.
- - **Database Pool:** Optimized connection pool from 10 to 4 maximum connections with memory-conscious settings.
- - **Flask Configuration:** Added memory-efficient settings including disabled JSON sorting, optimized session handling, and file serving optimizations.
- - **Dependency Addition:** Added gevent for more efficient async request handling compared to sync workers.
- - **Expected Reduction:** RAM usage configurable from ~40MB (ultra-light) to ~200MB (performance) based on server specifications.
- - _Files: `backend/gunicorn_config.py`, `backend/requirements.txt`, `backend/app.py`, `backend/db_handler.py`, `docker-compose.yml`_
+ * **Root Cause:** Display logic was overwriting original duration values (0,0,0 for exact date method), making method detection impossible.
-### Changed
-- **Environment Variables for OIDC (Docker):** While OIDC configuration is primarily managed via the database through the admin UI, the `docker-compose.yml` can include placeholder environment variables for initial setup or documentation:
- - `OIDC_ENABLED` (e.g., `true` or `false`)
- - `OIDC_PROVIDER_NAME` (e.g., `google`, `keycloak`)
- - `OIDC_CLIENT_ID`
- - `OIDC_CLIENT_SECRET`
- - `OIDC_ISSUER_URL`
- - `OIDC_SCOPE` (e.g., `openid email profile`)
-- **`FRONTEND_URL` Environment Variable:** Emphasized the importance of correctly setting the `FRONTEND_URL` environment variable for the backend service in `docker-compose.yml` to ensure correct OIDC callback redirects.
- - _Files: `docker-compose.yml`, `Docker/docker-compose.yml`_
+ * **Solution:** Added `original\_input\_method` tracking to preserve the user's original warranty entry method choice.
-### Fixed
-- Resolved various startup and runtime errors related to OIDC client initialization in a multi-worker (Gunicorn) environment, particularly concerning database connection pool stability and consistent loading of OIDC settings.
-- Corrected OIDC metadata fetching by ensuring the proper Issuer URL is used (e.g., `https://accounts.google.com` for Google).
-- Resolved `TypeError: Cannot read properties of null (reading 'classList')` during logout on `about.html` by ensuring the `loadingContainer` element is present and accessible to `script.js`'s `showLoading()` function. Modified `showLoading()` and `hideLoading()` to dynamically find the container if not initially available.
-- Fixed `SyntaxError: Identifier 'AuthManager' has already been declared` on `about.html` by removing a duplicate import of `auth.js` from the `<head>`, ensuring it is loaded only once at the end of the `<body>`.
-- Standardized the user menu dropdown button ID to `userMenuBtn` across `index.html`, `status.html`, and `about.html`. Consolidated user menu JavaScript logic into `auth.js`, removing redundant code from `settings-new.js` and `fix-auth-buttons.js` to ensure consistent dropdown behavior.
- - _Files: `backend/app.py`, `frontend/about.html`, `frontend/script.js`, `frontend/index.html`, `frontend/status.html`, `frontend/auth.js`, `frontend/settings-new.js`, `frontend/fix-auth-buttons.js`_
-- **SSO Warranty Display Issue:** Fixed a critical timing problem where SSO users would see a blank warranty list after login. The issue was caused by a race condition where user preferences were loaded before user authentication was fully established.
- - Enhanced `auth-redirect.html` to fetch and store user information immediately after SSO login, ensuring `user_info` is available when the main application loads.
- - Fixed preference key prefix calculation to prevent mismatched user preference keys for SSO users.
- - _Files: `frontend/auth-redirect.html`, `frontend/auth.js`, `frontend/script.js`_
-- **SSO Tag Creation Issue:** Resolved an issue where SSO users could not create new tags due to authentication token handling problems.
- - Updated tag creation functions (`createTag`, `updateTag`, `deleteTag`) to use `window.auth.getToken()` instead of directly accessing localStorage.
- - Added enhanced error handling and debugging for tag creation API calls.
- - Ensured consistent token management across all tag-related operations.
- - _Files: `frontend/script.js`_
-- **Database Tag Constraint Issue:** Fixed database constraint violation that prevented users from creating tags with names that already existed for other users.
- - Created migration `024_fix_tags_constraint.sql` to update the database schema.
- - Dropped the old `tags_name_key` unique constraint that only considered tag names.
- - Added new `tags_name_user_id_key` constraint allowing the same tag name for different users.
- - Added proper user_id foreign key constraint and performance index.
- - _Files: `backend/migrations/024_fix_tags_constraint.sql`_
-- **About Page User Menu Issue:** Fixed user menu dropdown not functioning on the about page for SSO users.
- - Resolved script loading order conflicts that prevented user menu event listeners from being attached.
- - Moved inline authentication check from head to body to prevent timing conflicts with `auth.js`.
- - Added backup user menu handler specifically for the about page with enhanced debugging.
- - Fixed JavaScript error caused by `getEventListeners` function not being available in all browsers.
- - _Files: `frontend/about.html`, `frontend/auth.js`_
-- **About Page Logout Issue:** Resolved logout functionality errors on the about page.
- - Added safe loading spinner functions specifically for the about page to prevent `TypeError: Cannot read properties of null (reading 'classList')` error.
- - Implemented backup logout handler with multiple fallback levels for reliability.
- - Ensured logout works even when main auth system encounters errors.
- - _Files: `frontend/about.html`, `frontend/script.js`_
-- **Immediate Warranty Updates:** Optimized warranty editing for instant UI updates without server reloads.
- - **Performance Improvement:** Warranty changes now appear immediately in the UI instead of waiting for server data reload.
- - **Local Data Sync:** Edit modal updates local warranty data instantly upon successful save, eliminating loading delays.
- - **Robust Date Handling:** Enhanced date arithmetic for duration-based warranties with proper month/year overflow handling.
- - **Complete Field Updates:** All warranty fields (product info, dates, serial numbers, tags, documents) update immediately in the interface.
- - **Fallback Safety:** Maintains fallback to server reload if local update fails, ensuring data consistency.
- - _Files: `frontend/script.js`_
-- **Warranty Entry Method Persistence:** Fixed warranty entry method selection not being remembered correctly in edit modal.
- - **Issue:** When editing warranties that were created using "Exact Expiration Date" method, the edit modal would incorrectly switch to "Warranty Duration" method.
- - **Root Cause:** Display logic was overwriting original duration values (0,0,0 for exact date method), making method detection impossible.
- - **Solution:** Added `original_input_method` tracking to preserve the user's original warranty entry method choice.
- - **Data Separation:** Implemented separate `display_duration_*` fields for warranty card display while preserving original duration values for method detection.
- - **Enhanced Detection:** Edit modal now directly checks `original_input_method` field instead of guessing from duration data.
- - **Result:** Users can now edit warranties and the modal correctly remembers whether they originally used "Warranty Duration" or "Exact Expiration Date" method.
- - _Files: `frontend/script.js`_
-- **Notes Modal and Edit Modal Integration:** Fixed issues with notes editing workflow and seamless transition to warranty editing.
- - **Notes Editing for Exact Date Warranties:** Resolved issue where warranties created with exact expiration dates couldn't have their notes edited via the notes-link modal due to invalid duration validation.
- - **Stale Notes in Edit Modal:** Fixed problem where editing a warranty immediately after saving notes via the notes modal would show old note content instead of the newly saved content.
- - **Notes Modal UI Issues:** Fixed "Edit Notes" button showing outdated note content when clicked after saving new notes in the same modal session.
- - **Enhanced Notes Modal:** Added "Edit Warranty" button directly in the notes modal footer for seamless transition to full warranty editing without modal layering conflicts.
- - **Immediate Data Sync:** Enhanced notes saving to immediately update the global warranties array, ensuring edit modal always shows current data.
- - **Modal State Management:** Improved modal closing behavior when opening edit modal from notes modal to prevent UI conflicts.
- - _Files: `frontend/script.js`_
-- **Status Page Edit Modal Consistency:** Fixed inconsistency between edit warranty modals on index.html and status.html pages.
- - **Missing Warranty Entry Method Selection:** Added the "Warranty Entry Method" radio button selection to the status.html edit modal, allowing users to choose between "Warranty Duration" and "Exact Expiration Date" methods.
- - **Missing Exact Expiration Field:** Added the hidden "Exact Expiration Date" input field that appears when the exact date method is selected.
- - **Feature Parity:** The edit warranty modal on status.html now has identical functionality to the one on index.html, ensuring consistent user experience across both pages.
- - **Complete Modal Structure:** All tabs (Product, Warranty, Documents, Tags), form fields, and functionality now match exactly between both pages.
- - _Files: `frontend/status.html`_
+ * **Data Separation:** Implemented separate `display\_duration\_\*` fields for warranty card display while preserving original duration values for method detection.
+
+ * **Enhanced Detection:** Edit modal now directly checks `original\_input\_method` field instead of guessing from duration data.
+
+ * **Result:** Users can now edit warranties and the modal correctly remembers whether they originally used "Warranty Duration" or "Exact Expiration Date" method.
+
+ * *Files: `frontend/script.js`*
+
+* **Notes Modal and Edit Modal Integration:** Fixed issues with notes editing workflow and seamless transition to warranty editing.
+
+ * **Notes Editing for Exact Date Warranties:** Resolved issue where warranties created with exact expiration dates couldn't have their notes edited via the notes-link modal due to invalid duration validation.
+
+ * **Stale Notes in Edit Modal:** Fixed problem where editing a warranty immediately after saving notes via the notes modal would show old note content instead of the newly saved content.
+
+ * **Notes Modal UI Issues:** Fixed "Edit Notes" button showing outdated note content when clicked after saving new notes in the same modal session.
+
+ * **Enhanced Notes Modal:** Added "Edit Warranty" button directly in the notes modal footer for seamless transition to full warranty editing without modal layering conflicts.
+
+ * **Immediate Data Sync:** Enhanced notes saving to immediately update the global warranties array, ensuring edit modal always shows current data.
+
+ * **Modal State Management:** Improved modal closing behavior when opening edit modal from notes modal to prevent UI conflicts.
+
+ * *Files: `frontend/script.js`*
+
+* **Status Page Edit Modal Consistency:** Fixed inconsistency between edit warranty modals on index.html and status.html pages.
+
+ * **Missing Warranty Entry Method Selection:** Added the "Warranty Entry Method" radio button selection to the status.html edit modal, allowing users to choose between "Warranty Duration" and "Exact Expiration Date" methods.
+
+ * **Missing Exact Expiration Field:** Added the hidden "Exact Expiration Date" input field that appears when the exact date method is selected.
+
+ * **Feature Parity:** The edit warranty modal on status.html now has identical functionality to the one on index.html, ensuring consistent user experience across both pages.
+
+ * **Complete Modal Structure:** All tabs (Product, Warranty, Documents, Tags), form fields, and functionality now match exactly between both pages.
+
+ * *Files: `frontend/status.html`*
### Dependencies
-- **Updated Python Dependencies:** Resolved `pkg_resources` deprecation warning by updating backend dependencies to modern versions.
- - **Gunicorn:** Updated from `20.1.0` to `23.0.0` - eliminates `pkg_resources` deprecation warning by using `importlib.metadata` instead.
- - **Flask:** Updated from `2.0.1` to `3.0.3` - includes security patches and improved compatibility.
- - **Werkzeug:** Updated from `2.0.1` to `3.0.3` - maintains compatibility with Flask 3.x.
- - **Other Dependencies:** Updated `flask-cors`, `Flask-Login`, `PyJWT`, `email-validator`, `python-dateutil`, `Authlib`, `requests`, and `gevent` to latest stable versions.
- - **Setuptools Protection:** Added `setuptools<81` pin to prevent future compatibility issues.
- - _Files: `backend/requirements.txt`_
+
+* **Updated Python Dependencies:** Resolved `pkg\_resources` deprecation warning by updating backend dependencies to modern versions.
+
+ * **Gunicorn:** Updated from `20.1.0` to `23.0.0` - eliminates `pkg\_resources` deprecation warning by using `importlib.metadata` instead.
+
+ * **Flask:** Updated from `2.0.1` to `3.0.3` - includes security patches and improved compatibility.
+
+ * **Werkzeug:** Updated from `2.0.1` to `3.0.3` - maintains compatibility with Flask 3.x.
+
+ * **Other Dependencies:** Updated `flask-cors`, `Flask-Login`, `PyJWT`, `email-validator`, `python-dateutil`, `Authlib`, `requests`, and `gevent` to latest stable versions.
+
+ * **Setuptools Protection:** Added `setuptools<81` pin to prevent future compatibility issues.
+
+ * *Files: `backend/requirements.txt`*
### Frontend
-- **Chart.js Compatibility Fix:** Resolved "Chart is not defined" error on status page by replacing ES module version with UMD version.
- - **Issue:** Status page charts failed to load with `ReferenceError: Chart is not defined` because the local `chart.js` file was in ES module format.
- - **Root Cause:** ES modules require `<script type="module">` tags but the HTML was using regular `<script>` tags.
- - **Solution:** Replaced ES module version with locally downloaded UMD (Universal Module Definition) version from Chart.js v4.4.9, eliminating CDN dependency.
- - **Result:** Chart.js now loads properly with regular script tags and status page charts display correctly using the local file.
- - _Files: `frontend/chart.js`_
-- **Product Name Hover Tooltips:** Added hover tooltips to display full product names when they are truncated with ellipsis.
- - **Enhancement:** Long product names that get cut off with "..." now show the complete product name in a tooltip when hovered over.
- - **Coverage:** Works across all warranty display modes (grid view, list view, table view) on the main warranties page and the status page table.
- - **Implementation:** Added `title` attributes to warranty titles and product name cells using escaped HTML for security.
- - **Result:** Users can now see full product names without having to edit or expand warranty details.
- - _Files: `frontend/script.js`, `frontend/status.js`_
-- **Powered by Warracker Footer:** Added branded footer to all pages with dynamic theme support and GitHub repository link.
- - **Feature:** Added "Powered by Warracker" footer to all application pages linking to the GitHub repository.
- - **Theme Support:** Implemented JavaScript-based dynamic styling that automatically adapts to light/dark mode changes.
- - **Light Mode:** Light gray background (`#f5f5f5`), dark text (`#333333`), blue links (`#3498db`) matching the logo.
- - **Dark Mode:** Dark background (`#1a1a1a`), light text (`#e0e0e0`), light blue links (`#4dabf7`).
- - **Real-time Updates:** Uses MutationObserver to detect theme changes and update footer styling automatically.
- - **Cross-domain Compatibility:** Includes fallback inline styles and direct color values to ensure consistent display across different hosting environments.
- - _Files: All frontend HTML pages, `frontend/style.css`_
-
-## [0.9.9.8] - 2025-05-24
+
+* **Chart.js Compatibility Fix:** Resolved "Chart is not defined" error on status page by replacing ES module version with UMD version.
+
+ * **Issue:** Status page charts failed to load with `ReferenceError: Chart is not defined` because the local `chart.js` file was in ES module format.
+
+ * **Root Cause:** ES modules require `<script type="module">` tags but the HTML was using regular `<script>` tags.
+
+ * **Solution:** Replaced ES module version with locally downloaded UMD (Universal Module Definition) version from Chart.js v4.4.9, eliminating CDN dependency.
+
+ * **Result:** Chart.js now loads properly with regular script tags and status page charts display correctly using the local file.
+
+ * *Files: `frontend/chart.js`*
+
+* **Product Name Hover Tooltips:** Added hover tooltips to display full product names when they are truncated with ellipsis.
+
+ * **Enhancement:** Long product names that get cut off with "..." now show the complete product name in a tooltip when hovered over.
+
+ * **Coverage:** Works across all warranty display modes (grid view, list view, table view) on the main warranties page and the status page table.
+
+ * **Implementation:** Added `title` attributes to warranty titles and product name cells using escaped HTML for security.
+
+ * **Result:** Users can now see full product names without having to edit or expand warranty details.
+
+ * *Files: `frontend/script.js`, `frontend/status.js`*
+
+* **Powered by Warracker Footer:** Added branded footer to all pages with dynamic theme support and GitHub repository link.
+
+ * **Feature:** Added "Powered by Warracker" footer to all application pages linking to the GitHub repository.
+
+ * **Theme Support:** Implemented JavaScript-based dynamic styling that automatically adapts to light/dark mode changes.
+
+ * **Light Mode:** Light gray background (`#f5f5f5`), dark text (`#333333`), blue links (`#3498db`) matching the logo.
+
+ * **Dark Mode:** Dark background (`#1a1a1a`), light text (`#e0e0e0`), light blue links (`#4dabf7`).
+
+ * **Real-time Updates:** Uses MutationObserver to detect theme changes and update footer styling automatically.
+
+ * **Cross-domain Compatibility:** Includes fallback inline styles and direct color values to ensure consistent display across different hosting environments.
+
+ * *Files: All frontend HTML pages, `frontend/style.css`*
+
+## \[0.9.9.8] - 2025-05-24
### Added
-- **Account Email Change:** Users can now change the email address associated with their account from the Settings page.
- - The email field in Account Settings is now editable.
- - Client-side and backend validation ensure the new email is valid and not already in use by another account.
- - The backend prevents duplicate emails and returns clear error messages for conflicts or invalid formats.
- - On successful change, the new email is reflected in the UI and localStorage, and users must use the new email to log in.
- - _Files: `frontend/settings-new.html`, `frontend/settings-new.js`, `backend/app.py`_
-- **Progressive Web App (PWA) Support:** Enabled the application to be installed on Android devices.
- - Added and configured `manifest.json` with necessary properties (name, short_name, icons, start_url, display, orientation, theme_color, background_color, description).
- - Implemented a basic service worker (`sw.js`) with a cache-first strategy for core assets (HTML, CSS, JS, manifest, icons) to enable offline access and faster loading.
- - Registered the service worker in `script.js`.
- - Ensured `index.html` links to the `manifest.json` file.
- - Updated icon set in `manifest.json` and `sw.js` to use 16x16, 32x32, and 512x512 favicons.
- - _Files: `frontend/manifest.json`, `frontend/sw.js`, `frontend/script.js`, `frontend/index.html`_
-- **Manage Tags Button on Index Page:** Added a "Manage Tags" button to the filter controls section on the main warranties page (`index.html`).
- - Clicking this button opens the tag management modal, which is now centered on the screen.
- - _Files: `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_
+
+* **Account Email Change:** Users can now change the email address associated with their account from the Settings page.
+
+ * The email field in Account Settings is now editable.
+
+ * Client-side and backend validation ensure the new email is valid and not already in use by another account.
+
+ * The backend prevents duplicate emails and returns clear error messages for conflicts or invalid formats.
+
+ * On successful change, the new email is reflected in the UI and localStorage, and users must use the new email to log in.
+
+ * *Files: `frontend/settings-new.html`, `frontend/settings-new.js`, `backend/app.py`*
+
+* **Progressive Web App (PWA) Support:** Enabled the application to be installed on Android devices.
+
+ * Added and configured `manifest.json` with necessary properties (name, short\_name, icons, start\_url, display, orientation, theme\_color, background\_color, description).
+
+ * Implemented a basic service worker (`sw.js`) with a cache-first strategy for core assets (HTML, CSS, JS, manifest, icons) to enable offline access and faster loading.
+
+ * Registered the service worker in `script.js`.
+
+ * Ensured `index.html` links to the `manifest.json` file.
+
+ * Updated icon set in `manifest.json` and `sw.js` to use 16x16, 32x32, and 512x512 favicons.
+
+ * *Files: `frontend/manifest.json`, `frontend/sw.js`, `frontend/script.js`, `frontend/index.html`*
+
+* **Manage Tags Button on Index Page:** Added a "Manage Tags" button to the filter controls section on the main warranties page (`index.html`).
+
+ * Clicking this button opens the tag management modal, which is now centered on the screen.
+
+ * *Files: `frontend/index.html`, `frontend/script.js`, `frontend/style.css`*
### Changed
-- **Mobile/Tablet Responsiveness:** Updated `index.html` , `status.html` and associated CSS to improve the layout and usability of grid and list views on mobile and tablet devices.
- - _Files: `frontend/index.html`, `frontend/status.html`, `frontend/style.css` , `frontend/mobile-header.css`_
-- **Database Credential Handling (Contribution by @humrochagf):** Replaced hardcoded database credentials with environment variable references for improved security and maintainability (Commit: 20997e9).
- - Removed hardcoded `db_user`, `db_admin_user`, and `db_admin_password` values.
- - Updated Dockerfile to eliminate redundant superuser credential checks.
- - Ensured `DB_ADMIN_PASSWORD` is configurable via Docker Compose environment variables, removing manual post-deployment steps.
- - Adjusted scripts to rely on dynamic credentials set in the environment.
- - _Files: `Dockerfile`, `backend/app.py`, `backend/fix_permissions.py`, `backend/fix_permissions.sql`, `backend/migrations/010_configure_admin_roles.sql`, `backend/migrations/011_ensure_admin_permissions.sql`, `backend/migrations/apply_migrations.py`, `docker-compose.yml`_
-## [0.9.9.7] - 2025-05-16
+* **Mobile/Tablet Responsiveness:** Updated `index.html` , `status.html` and associated CSS to improve the layout and usability of grid and list views on mobile and tablet devices.
+
+ * *Files: `frontend/index.html`, `frontend/status.html`, `frontend/style.css` , `frontend/mobile-header.css`*
+
+* **Database Credential Handling (Contribution by @humrochagf):** Replaced hardcoded database credentials with environment variable references for improved security and maintainability (Commit: 20997e9).
+
+ * Removed hardcoded `db\_user`, `db\_admin\_user`, and `db\_admin\_password` values.
+
+ * Updated Dockerfile to eliminate redundant superuser credential checks.
+
+ * Ensured `DB\_ADMIN\_PASSWORD` is configurable via Docker Compose environment variables, removing manual post-deployment steps.
+
+ * Adjusted scripts to rely on dynamic credentials set in the environment.
+
+ * *Files: `Dockerfile`, `backend/app.py`, `backend/fix\_permissions.py`, `backend/fix\_permissions.sql`, `backend/migrations/010\_configure\_admin\_roles.sql`, `backend/migrations/011\_ensure\_admin\_permissions.sql`, `backend/migrations/apply\_migrations.py`, `docker-compose.yml`*
+
+## \[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`_
+
+* **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`_
+
+* **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
+* 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
-- **Warranty Duration Input:** Replaced the single "Warranty Period (Years)" input field with separate fields for Years, Months, and Days when adding or editing warranties.
- - Allows for more precise warranty duration entry (e.g., 2 years, 6 months, 15 days).
- - Updated Add/Edit forms (`frontend/index.html`), JavaScript logic (`frontend/script.js`), CSS styling (`frontend/style.css`), backend API (`backend/app.py`), and database schema (`backend/migrations/021_change_warranty_duration_to_components.sql`).
- - Warranty display on cards and summaries now shows the formatted duration (e.g., "2 years, 6 months").
- - CSV import/export updated to use `WarrantyDurationYears`, `WarrantyDurationMonths`, `WarrantyDurationDays` columns.
- - Backend validation ensures at least one duration component is provided for non-lifetime warranties.
- - Fixed backend logic to correctly handle empty duration inputs, treating them as 0.
- _Files: `backend/app.py`, `backend/migrations/021_change_warranty_duration_to_components.sql`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_
-- **Files Upload:** Users can now upload an additional ZIP/RAR file (e.g., for extended warranty documents, photos, or other related files) when adding or editing a warranty.
- - This document is stored securely and can be accessed from the warranty card.
- - _Files: `backend/app.py`, `backend/migrations/022_add_other_document_path.sql`, `frontend/index.html`, `frontend/script.js`_
-- **Configurable JWT Secret Key:**
- - The application's JWT and session secret key can now be configured via the `SECRET_KEY` environment variable.
- - It is strongly recommended to set a unique, strong secret key in production environments. Defaults to a development key if not set.
- - _Relevant File: `backend/app.py` (for usage), `docker-compose.yml` (for setting)_
-- **Configurable File Upload Limits:**
- - Maximum file upload sizes for both the backend application and the Nginx reverse proxy are now configurable via environment variables.
- - **Application (Flask):** Set `MAX_UPLOAD_MB` (e.g., `MAX_UPLOAD_MB=64`) to define the limit in megabytes. Defaults to 32MB.
- - **Nginx:** Set `NGINX_MAX_BODY_SIZE_VALUE` (e.g., `NGINX_MAX_BODY_SIZE_VALUE=64M`) to define the limit for Nginx (value must include unit like M or G). Defaults to "32M".
- - The `Dockerfile` and `nginx.conf` have been updated to support this.
- - _Files: `backend/app.py`, `nginx.conf`, `Dockerfile`_
-- **Security key can be used in environment:**
- - **SECRET_KEY=** is now usuable in docker-compose for jwt secret.
- - _Files: `Docker/docker-compose.yml`_
+
+* **Warranty Duration Input:** Replaced the single "Warranty Period (Years)" input field with separate fields for Years, Months, and Days when adding or editing warranties.
+
+ * Allows for more precise warranty duration entry (e.g., 2 years, 6 months, 15 days).
+
+ * Updated Add/Edit forms (`frontend/index.html`), JavaScript logic (`frontend/script.js`), CSS styling (`frontend/style.css`), backend API (`backend/app.py`), and database schema (`backend/migrations/021\_change\_warranty\_duration\_to\_components.sql`).
+
+ * Warranty display on cards and summaries now shows the formatted duration (e.g., "2 years, 6 months").
+
+ * CSV import/export updated to use `WarrantyDurationYears`, `WarrantyDurationMonths`, `WarrantyDurationDays` columns.
+
+ * Backend validation ensures at least one duration component is provided for non-lifetime warranties.
+
+ * Fixed backend logic to correctly handle empty duration inputs, treating them as 0.
+ *Files: `backend/app.py`, `backend/migrations/021\_change\_warranty\_duration\_to\_components.sql`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`*
+
+* **Files Upload:** Users can now upload an additional ZIP/RAR file (e.g., for extended warranty documents, photos, or other related files) when adding or editing a warranty.
+
+ * This document is stored securely and can be accessed from the warranty card.
+
+ * *Files: `backend/app.py`, `backend/migrations/022\_add\_other\_document\_path.sql`, `frontend/index.html`, `frontend/script.js`*
+
+* **Configurable JWT Secret Key:**
+
+ * The application's JWT and session secret key can now be configured via the `SECRET\_KEY` environment variable.
+
+ * It is strongly recommended to set a unique, strong secret key in production environments. Defaults to a development key if not set.
+
+ * *Relevant File: `backend/app.py` (for usage), `docker-compose.yml` (for setting)*
+
+* **Configurable File Upload Limits:**
+
+ * Maximum file upload sizes for both the backend application and the Nginx reverse proxy are now configurable via environment variables.
+
+ * **Application (Flask):** Set `MAX\_UPLOAD\_MB` (e.g., `MAX\_UPLOAD\_MB=64`) to define the limit in megabytes. Defaults to 32MB.
+
+ * **Nginx:** Set `NGINX\_MAX\_BODY\_SIZE\_VALUE` (e.g., `NGINX\_MAX\_BODY\_SIZE\_VALUE=64M`) to define the limit for Nginx (value must include unit like M or G). Defaults to "32M".
+
+ * The `Dockerfile` and `nginx.conf` have been updated to support this.
+
+ * *Files: `backend/app.py`, `nginx.conf`, `Dockerfile`*
+
+* **Security key can be used in environment:**
+
+ * **SECRET\_KEY=** is now usuable in docker-compose for jwt secret.
+
+ * *Files: `Docker/docker-compose.yml`*
### Fixed
-- **Backend Indentation Error:** Corrected an `IndentationError` in `backend/app.py` within the CSV import logic that prevented the backend from starting correctly.
- _Files: `backend/app.py`_
-- **Migration Script Error:** Fixed an error in migration `021_change_warranty_duration_to_components.sql` where it incorrectly referenced `lifetime_warranty` instead of the correct `is_lifetime` column.
- _Files: `backend/migrations/021_change_warranty_duration_to_components.sql`_
-- **smtplib import duplicate:** Removed line from app.py that re-imported smtplib with a pull request.
-- _Files: `backend/app.py`_
+
+* **Backend Indentation Error:** Corrected an `IndentationError` in `backend/app.py` within the CSV import logic that prevented the backend from starting correctly.
+ *Files: `backend/app.py`*
+
+* **Migration Script Error:** Fixed an error in migration `021\_change\_warranty\_duration\_to\_components.sql` where it incorrectly referenced `lifetime\_warranty` instead of the correct `is\_lifetime` column.
+ *Files: `backend/migrations/021\_change\_warranty\_duration\_to\_components.sql`*
+
+* **smtplib import duplicate:** Removed line from app.py that re-imported smtplib with a pull request.
+
+* *Files: `backend/app.py`*
### House Cleaning
-- **Old Settings files:** Removed all older settings pages , and related files.
-- _Files: `frontend/settings.html`,`frontend/settings.script.js`,`frontend/settings_redirect.html`_
-## [0.9.9.5] - 2025-05-07
+* **Old Settings files:** Removed all older settings pages , and related files.
+
+* *Files: `frontend/settings.html`,`frontend/settings.script.js`,`frontend/settings\_redirect.html`*
+
+## \[0.9.9.5] - 2025-05-07
### Changed
-- **Header Branding Improvement:**
- - Made the "Warracker" text in the header of the Status, Settings, and About pages a clickable link to the home page (`index.html`) for improved navigation and consistency.
- _Files: `frontend/status.html`, `frontend/settings-new.html`, `frontend/about.html`_
-- **Tag Dropdown Color Removal:**
- - Removed all background and text colours from the tags dropdown in both dark mode and light mode for a cleaner, more consistent appearance.
- _Files: `frontend/style.css`, `frontend/script.js`, and any related tag dropdown CSS/JS._
+* **Header Branding Improvement:**
+
+ * Made the "Warracker" text in the header of the Status, Settings, and About pages a clickable link to the home page (`index.html`) for improved navigation and consistency.
+ *Files: `frontend/status.html`, `frontend/settings-new.html`, `frontend/about.html`*
+
+* **Tag Dropdown Color Removal:**
-- **Docker Base Image Update:**
- - Updated the `Dockerfile` to use Python 3.12 and Debian 12 (bookworm) as the base image for the container, ensuring improved compatibility and security.
- _File: `Dockerfile`_
+ * Removed all background and text colours from the tags dropdown in both dark mode and light mode for a cleaner, more consistent appearance.
+ *Files: `frontend/style.css`, `frontend/script.js`, and any related tag dropdown CSS/JS.*
+* **Docker Base Image Update:**
-## [0.9.9.4] - 2025-05-04
+ * Updated the `Dockerfile` to use Python 3.12 and Debian 12 (bookworm) as the base image for the container, ensuring improved compatibility and security.
+ *File: `Dockerfile`*
+
+
+\[0.9.9.4] - 2025-05-04
+---
### Fixed
-- **Theme Persistence & Consistency:**
- - Refactored dark mode logic to use only a single `localStorage` key (`darkMode`) as the source of truth for theme preference across all pages.
- - Removed all legacy and user-prefixed theme keys (e.g., `user_darkMode`, `admin_darkMode`, `${prefix}darkMode`).
- - Ensured all theme toggles and settings update only the `darkMode` key, and all pages read only this key for theme initialization.
- - Verified that `theme-loader.js` is included early in every HTML file to prevent flashes of incorrect theme.
- - Cleaned up redundant or conflicting theme logic in all frontend scripts and HTML files.
- - Theme preference now persists reliably across logins, logouts, and browser sessions (except in incognito/private mode, where localStorage is temporary by design).
- _Files: `frontend/script.js`, `frontend/settings-new.js`, `frontend/status.js`, `frontend/register.html`, `frontend/reset-password.html`, `frontend/reset-password-request.html`, `frontend/theme-loader.js`, all main HTML files._
+
+* **Theme Persistence \& Consistency:**
+
+ * Refactored dark mode logic to use only a single `localStorage` key (`darkMode`) as the source of truth for theme preference across all pages.
+
+ * Removed all legacy and user-prefixed theme keys (e.g., `user\_darkMode`, `admin\_darkMode`, `$prefixdarkMode`).
+
+ * Ensured all theme toggles and settings update only the `darkMode` key, and all pages read only this key for theme initialization.
+
+ * Verified that `theme-loader.js` is included early in every HTML file to prevent flashes of incorrect theme.
+
+ * Cleaned up redundant or conflicting theme logic in all frontend scripts and HTML files.
+
+ * Theme preference now persists reliably across logins, logouts, and browser sessions (except in incognito/private mode, where localStorage is temporary by design).
+ *Files: `frontend/script.js`, `frontend/settings-new.js`, `frontend/status.js`, `frontend/register.html`, `frontend/reset-password.html`, `frontend/reset-password-request.html`, `frontend/theme-loader.js`, all main HTML files.*
### Added
-- **Admin/User Tag Separation:**
- - Implemented distinct tags for Admins and regular Users.
- - Tags created by an Admin are only visible to other Admins.
- - Tags created by a User are only visible to other Users.
- - Added `is_admin_tag` boolean column to the `tags` table via migration (`backend/migrations/009_add_admin_flag_to_tags.sql`).
- - Backend API endpoints (`/api/tags`, `/api/warranties`, `/api/warranties/<id>/tags`) updated to filter tags based on the logged-in user's role (`is_admin`).
- - Tag creation (`POST /api/tags`) now automatically sets the `is_admin_tag` flag based on the creator's role.
- - Tag update (`PUT /api/tags/<id>`) and deletion (`DELETE /api/tags/<id>`) endpoints now prevent users/admins from modifying tags belonging to the other role.
- _Files: `backend/app.py`, `backend/migrations/009_add_admin_flag_to_tags.sql`_
-
- - **Version Check:**
-
- - Added a version checker to the About page (`frontend/about.html`) that compares the current version with the latest GitHub release and displays the update status.
- _Files: `frontend/about.html`, `frontend/version-checker.js`_
-
-- **Mobile Home Screen Icon Support:**
- - Added support for mobile devices to display the app icon when added to the home screen.
- - Included `<link rel="apple-touch-icon" sizes="180x180">` for iOS devices, referencing a new 512x512 PNG icon.
- - Added a web app manifest (`manifest.json`) referencing the 512x512 icon for Android/Chrome home screen support.
- - Updated all main HTML files to include these tags for consistent experience across devices.
- _Files: `frontend/index.html`, `frontend/login.html`, `frontend/register.html`, `frontend/about.html`, `frontend/reset-password.html`, `frontend/reset-password-request.html`, `frontend/status.html`, `frontend/settings-new.html`, `frontend/manifest.json`, `frontend/img/favicon-512x512.png`_
-
-- **Optional Vendor Field for Warranties:**
- - Users can now specify the vendor (e.g., Amazon, Best Buy) where a product was purchased, as an optional informational field for each warranty.
- - The field is available when adding a new warranty and when editing an existing warranty.
- - The vendor is displayed on warranty cards and in the summary tab of the add warranty wizard.
- - The vendor field is now searchable alongside product name, notes, and tags.
- - Backend API and database updated to support this field, including a migration to add the column to the warranties table.
- - Editing a warranty now correctly updates the vendor field.
- _Files: `backend/app.py`, `backend/migrations/017_add_vendor_to_warranties.sql`, `frontend/index.html`, `frontend/script.js`_
-
-- **Serial Number Search:**
- - Enhanced search functionality to include serial numbers.
- - Updated search input placeholder text to reflect serial number search capability.
- _Files: `frontend/script.js`, `frontend/index.html`_
-
-- **CSV Import Vendor Field:**
- - Added support for importing the `Vendor` field via CSV file upload.
- - The CSV header should be `Vendor`.
- _Files: `backend/app.py`, `frontend/script.js`_
-
-- **Date Format Customization:**
- - Users can now choose their preferred date display format in Settings > Preferences.
- - Available formats include:
- - Month/Day/Year (e.g., 12/31/2024)
- - Day/Month/Year (e.g., 31/12/2024)
- - Year-Month-Day (e.g., 2024-12-31)
- - Mon Day, Year (e.g., Dec 31, 2024)
- - Day Mon Year (e.g., 31 Dec 2024)
- - Year Mon Day (e.g., 2024 Dec 31)
- - The selected format is applied to purchase and expiration dates on warranty cards.
- - The setting persists across sessions and is synchronized between open tabs.
- _Files: `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/script.js`_
-
-- **IPv6 Support:** Added `listen [::]:80;` directive to the Nginx configuration (`nginx.conf`) to enable listening on IPv6 interfaces alongside IPv4.
- _Files: `nginx.conf`_
-
-- **Cloudflare Compatibility:** Added `<script data-cfasync="false" src="/javascript.js">` to the `<head>` of the status page (`frontend/status.html`) to ensure proper loading when behind Cloudflare.
- _Files: `frontend/status.html`_
+
+* **Admin/User Tag Separation:**
+
+ * Implemented distinct tags for Admins and regular Users.
+
+ * Tags created by an Admin are only visible to other Admins.
+
+ * Tags created by a User are only visible to other Users.
+
+ * Added `is\_admin\_tag` boolean column to the `tags` table via migration (`backend/migrations/009\_add\_admin\_flag\_to\_tags.sql`).
+
+ * Backend API endpoints (`/api/tags`, `/api/warranties`, `/api/warranties/<id>/tags`) updated to filter tags based on the logged-in user's role (`is\_admin`).
+
+ * Tag creation (`POST /api/tags`) now automatically sets the `is\_admin\_tag` flag based on the creator's role.
+
+ * Tag update (`PUT /api/tags/<id>`) and deletion (`DELETE /api/tags/<id>`) endpoints now prevent users/admins from modifying tags belonging to the other role.
+ *Files: `backend/app.py`, `backend/migrations/009\_add\_admin\_flag\_to\_tags.sql`*
+
+ * **Version Check:**
+
+ * Added a version checker to the About page (`frontend/about.html`) that compares the current version with the latest GitHub release and displays the update status.
+ *Files: `frontend/about.html`, `frontend/version-checker.js`*
+
+* **Mobile Home Screen Icon Support:**
+
+ * Added support for mobile devices to display the app icon when added to the home screen.
+
+ * Included `<link rel="apple-touch-icon" sizes="180x180">` for iOS devices, referencing a new 512x512 PNG icon.
+
+ * Added a web app manifest (`manifest.json`) referencing the 512x512 icon for Android/Chrome home screen support.
+
+ * Updated all main HTML files to include these tags for consistent experience across devices.
+ *Files: `frontend/index.html`, `frontend/login.html`, `frontend/register.html`, `frontend/about.html`, `frontend/reset-password.html`, `frontend/reset-password-request.html`, `frontend/status.html`, `frontend/settings-new.html`, `frontend/manifest.json`, `frontend/img/favicon-512x512.png`*
+
+* **Optional Vendor Field for Warranties:**
+
+ * Users can now specify the vendor (e.g., Amazon, Best Buy) where a product was purchased, as an optional informational field for each warranty.
+
+ * The field is available when adding a new warranty and when editing an existing warranty.
+
+ * The vendor is displayed on warranty cards and in the summary tab of the add warranty wizard.
+
+ * The vendor field is now searchable alongside product name, notes, and tags.
+
+ * Backend API and database updated to support this field, including a migration to add the column to the warranties table.
+
+ * Editing a warranty now correctly updates the vendor field.
+ *Files: `backend/app.py`, `backend/migrations/017\_add\_vendor\_to\_warranties.sql`, `frontend/index.html`, `frontend/script.js`*
+
+* **Serial Number Search:**
+
+ * Enhanced search functionality to include serial numbers.
+
+ * Updated search input placeholder text to reflect serial number search capability.
+ *Files: `frontend/script.js`, `frontend/index.html`*
+
+* **CSV Import Vendor Field:**
+
+ * Added support for importing the `Vendor` field via CSV file upload.
+
+ * The CSV header should be `Vendor`.
+ *Files: `backend/app.py`, `frontend/script.js`*
+
+* **Date Format Customization:**
+
+ * Users can now choose their preferred date display format in Settings > Preferences.
+
+ * Available formats include:
+
+ * Month/Day/Year (e.g., 12/31/2024)
+
+ * Day/Month/Year (e.g., 31/12/2024)
+
+ * Year-Month-Day (e.g., 2024-12-31)
+
+ * Mon Day, Year (e.g., Dec 31, 2024)
+
+ * Day Mon Year (e.g., 31 Dec 2024)
+
+ * Year Mon Day (e.g., 2024 Dec 31)
+
+ * The selected format is applied to purchase and expiration dates on warranty cards.
+
+ * The setting persists across sessions and is synchronized between open tabs.
+ *Files: `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/script.js`*
+
+* **IPv6 Support:** Added `listen \[::]:80;` directive to the Nginx configuration (`nginx.conf`) to enable listening on IPv6 interfaces alongside IPv4.
+ *Files: `nginx.conf`*
+
+* **Cloudflare Compatibility:** Added `<script data-cfasync="false" src="/javascript.js">` to the `<head>` of the status page (`frontend/status.html`) to ensure proper loading when behind Cloudflare.
+ *Files: `frontend/status.html`*
### Changed
- - **Migration System Overhaul:** Refactored the database migration system for improved reliability and consistency.
- - **House cleaning**: Removed redundant files such as migrations, .env, and uploads folder.
- - **Warranty Listing:** Admins now only see their own warranties on the main warranty list (`/api/warranties`).
- - **Warranty Visibility:** Fixed issue where admins could see all users' warranties. Now both admins and regular users only see their own warranties on all pages.
- _Files: `backend/app.py`_
+
+ * **Migration System Overhaul:** Refactored the database migration system for improved reliability and consistency.
+
+ * **House cleaning**: Removed redundant files such as migrations, .env, and uploads folder.
+
+ * **Warranty Listing:** Admins now only see their own warranties on the main warranty list (`/api/warranties`).
+
+ * **Warranty Visibility:** Fixed issue where admins could see all users' warranties. Now both admins and regular users only see their own warranties on all pages.
+ *Files: `backend/app.py`*
**Bug Fixes:**
-* **Date Handling:** Fixed issues causing warranty purchase and expiration dates to display incorrectly (off by one day) due to timezone differences:
- * **Backend:** Corrected expiration date calculation in `backend/app.py` by removing the inaccurate `timedelta` fallback logic and ensuring the `python-dateutil` library (using `relativedelta`) is consistently used for accurate year addition.
- * **Backend:** Added `python-dateutil` to `backend/requirements.txt` dependencies.
- * **Frontend:** Updated date parsing in `frontend/script.js` (`processWarrantyData`) to use `Date.UTC()` when creating `Date` objects from `YYYY-MM-DD` strings, preventing local timezone interpretation.
- * **Frontend:** Simplified and corrected date formatting in `frontend/script.js` (`formatDate`) to always use UTC date components (`getUTCFullYear`, etc.) for display, bypassing potential `toLocaleDateString` timezone issues.
- * **Frontend:** Fixed purchase date display in the "Add Warranty" summary tab (`updateSummary` in `frontend/script.js`) by applying the same UTC-based parsing and formatting used elsewhere, resolving the off-by-one-day error during summary view.
-* **Fractional Warranty Years & Date Accuracy:** Corrected the backend expiration date calculation (`backend/app.py`) to accurately handle fractional warranty years (e.g., 1.5 years) and prevent off-by-one-day errors.
- * The initial fix for fractional years used an approximation (`timedelta`) which sometimes resulted in dates being a day early.
- * The calculation now uses `dateutil.relativedelta` after decomposing the fractional years into integer years, months, and days, ensuring correct handling of leap years and month lengths.
-* **UI:** Fixed toasts overlapping header menu due to z-index conflict (`style.css`).
-* **API:** Fixed bug preventing updates to user preferences if only the timezone was changed (`app.py`).
-* **Settings:** Resolved issue where opening the settings page in multiple tabs could cause both tabs to refresh continuously and potentially log the user out. This involved:
- * Preventing `settings-new.js` from unnecessarily updating `user_info` in `localStorage` on load.
- * Changing the `storage` event listener in `include-auth-new.js` to update the UI directly instead of reloading the page when auth data changes.
- * Removing redundant checks (`setInterval`) and `storage` listener from `fix-auth-buttons.js` to prevent conflicts.
-
-**New Features & Enhancements:**
-
-* **API:** Added `/api/timezones` endpoint to provide a structured list of timezones grouped by region (`app.py`).
+* **Date Handling:** Fixed issues causing warranty purchase and expiration dates to display incorrectly (off by one day) due to timezone differences:
+
+ * **Backend:** Corrected expiration date calculation in `backend/app.py` by removing the inaccurate `timedelta` fallback logic and ensuring the `python-dateutil` library (using `relativedelta`) is consistently used for accurate year addition.
+
+ * **Backend:** Added `python-dateutil` to `backend/requirements.txt` dependencies.
+
+ * **Frontend:** Updated date parsing in `frontend/script.js` (`processWarrantyData`) to use `Date.UTC()` when creating `Date` objects from `YYYY-MM-DD` strings, preventing local timezone interpretation.
+
+ * **Frontend:** Simplified and corrected date formatting in `frontend/script.js` (`formatDate`) to always use UTC date components (`getUTCFullYear`, etc.) for display, bypassing potential `toLocaleDateString` timezone issues.
+
+ * **Frontend:** Fixed purchase date display in the "Add Warranty" summary tab (`updateSummary` in `frontend/script.js`) by applying the same UTC-based parsing and formatting used elsewhere, resolving the off-by-one-day error during summary view.
+
+* **Fractional Warranty Years \& Date Accuracy:** Corrected the backend expiration date calculation (`backend/app.py`) to accurately handle fractional warranty years (e.g., 1.5 years) and prevent off-by-one-day errors.
+
+ * The initial fix for fractional years used an approximation (`timedelta`) which sometimes resulted in dates being a day early.
+
+ * The calculation now uses `dateutil.relativedelta` after decomposing the fractional years into integer years, months, and days, ensuring correct handling of leap years and month lengths.
+
+* **UI:** Fixed toasts overlapping header menu due to z-index conflict (`style.css`).
+
+* **API:** Fixed bug preventing updates to user preferences if only the timezone was changed (`app.py`).
+
+* **Settings:** Resolved issue where opening the settings page in multiple tabs could cause both tabs to refresh continuously and potentially log the user out. This involved:
+
+ * Preventing `settings-new.js` from unnecessarily updating `user\_info` in `localStorage` on load.
+
+ * Changing the `storage` event listener in `include-auth-new.js` to update the UI directly instead of reloading the page when auth data changes.
+
+ * Removing redundant checks (`setInterval`) and `storage` listener from `fix-auth-buttons.js` to prevent conflicts.
+
+**New Features \& Enhancements:**
+
+* **API:** Added `/api/timezones` endpoint to provide a structured list of timezones grouped by region (`app.py`).
### Fixed
-- **Tag Visibility:** Fixed an issue where tag visibility was incorrectly reversed between Admins and Users (Users saw Admin tags and vice-versa). Adjusted backend logic to correctly display tags based on role.
- _Files: `backend/app.py`_
-- Fixed currency symbol not persisting after browser restart/re-login:
- - Prevented main warranty list from rendering before user authentication and preferences are fully loaded.
- - Ensured preferences (currency, date format, etc.) are fetched from API and saved to localStorage immediately after login.
- - Corrected inconsistent user type prefix (`user_` vs `admin_`) determination during initial page load.
-## [0.9.9.3] - 2025-04-27
+* **Tag Visibility:** Fixed an issue where tag visibility was incorrectly reversed between Admins and Users (Users saw Admin tags and vice-versa). Adjusted backend logic to correctly display tags based on role.
+ *Files: `backend/app.py`*
+
+* Fixed currency symbol not persisting after browser restart/re-login:
+
+ * Prevented main warranty list from rendering before user authentication and preferences are fully loaded.
+
+ * Ensured preferences (currency, date format, etc.) are fetched from API and saved to localStorage immediately after login.
+
+ * Corrected inconsistent user type prefix (`user\_` vs `admin\_`) determination during initial page load.
+
+## \[0.9.9.3] - 2025-04-27
### Added
- - **Document Deletion in Edit Warranty:**
- - Users can now delete uploaded documents (Invoice/Receipt and Product Manual) when editing an existing warranty.
- - The edit modal now displays "Delete Invoice" and "Delete Manual" buttons if a document is present. Clicking these marks the document for deletion, which is processed when saving changes.
- - Backend and database are updated to remove the file from storage and clear the reference in the database.
- _Files: `backend/app.py`, `frontend/index.html`, `frontend/script.js`_
-
- - **Notes for Warranties:**
- - Users can now add, view, and edit freeform notes for each warranty.
- - Notes can be entered when adding or editing a warranty, and are accessible from the warranty card via a dedicated "Notes" link.
- - A modal dialog allows users to view and edit notes in place, with support for multi-line text and instant updates.
- - Notes are searchable and filterable alongside product names and tags.
- - Backend and database support for notes has been added, including migration and API changes.
- - UI includes clear styling for notes links and modal, with full support for both light and dark themes.
- _Files: `backend/app.py`, `backend/migrations/014_add_notes_to_warranties.sql`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_
-
- - **Currency Symbol Customization:**
- - Users can now select their preferred currency symbol ($, €, £, ¥, ₹, or a custom one) in the settings page.
- - The selected symbol is now displayed next to purchase prices on warranty cards on the main page (`index.html`).
- _Files: `backend/app.py`, `backend/migrations/006_add_currency_symbol_column.py`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_
-
- - **Password Reset Functionality:**
- - Users can now reset their password via a secure, token-based email workflow.
- - Added a "Forgot Password?" link on the login page that initiates the process.
- - Users receive an email with a unique link to set a new password.
- - Implemented frontend pages for requesting the reset and setting the new password.
- - Backend handles token generation, validation, email sending, and password updates.
- _Files: `backend/app.py`, `frontend/login.html`, `frontend/reset-password-request.html`, `frontend/reset-password.html`, `backend/migrations/003_add_users_table.sql` (or similar migration)_
+* **Document Deletion in Edit Warranty:**
+
+ * Users can now delete uploaded documents (Invoice/Receipt and Product Manual) when editing an existing warranty.
+
+ * The edit modal now displays "Delete Invoice" and "Delete Manual" buttons if a document is present. Clicking these marks the document for deletion, which is processed when saving changes.
+
+ * Backend and database are updated to remove the file from storage and clear the reference in the database.
+ *Files: `backend/app.py`, `frontend/index.html`, `frontend/script.js`*
+
+* **Notes for Warranties:**
+
+ * Users can now add, view, and edit freeform notes for each warranty.
+
+ * Notes can be entered when adding or editing a warranty, and are accessible from the warranty card via a dedicated "Notes" link.
+
+ * A modal dialog allows users to view and edit notes in place, with support for multi-line text and instant updates.
+
+ * Notes are searchable and filterable alongside product names and tags.
+
+ * Backend and database support for notes has been added, including migration and API changes.
+
+ * UI includes clear styling for notes links and modal, with full support for both light and dark themes.
+ *Files: `backend/app.py`, `backend/migrations/014\_add\_notes\_to\_warranties.sql`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`*
+
+* **Currency Symbol Customization:**
+
+ * Users can now select their preferred currency symbol ($, €, £, ¥, ₹, or a custom one) in the settings page.
+
+ * The selected symbol is now displayed next to purchase prices on warranty cards on the main page (`index.html`).
+ *Files: `backend/app.py`, `backend/migrations/006\_add\_currency\_symbol\_column.py`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/index.html`, `frontend/script.js`, `frontend/style.css`*
+
+* **Password Reset Functionality:**
+
+ * Users can now reset their password via a secure, token-based email workflow.
+
+ * Added a "Forgot Password?" link on the login page that initiates the process.
+
+ * Users receive an email with a unique link to set a new password.
+
+ * Implemented frontend pages for requesting the reset and setting the new password.
+
+ * Backend handles token generation, validation, email sending, and password updates.
+ *Files: `backend/app.py`, `frontend/login.html`, `frontend/reset-password-request.html`, `frontend/reset-password.html`, `backend/migrations/003\_add\_users\_table.sql` (or similar migration)*
### Changed
-- **Status Page Table:** Removed the "Actions" column (and its buttons) from the "Recently Expired or Expiring Soon" table on `status.html` for a cleaner look.
-- **Table Layout:** Updated the table and CSS to use dynamic column widths, eliminating empty space after the Status column and ensuring the table fills the available space naturally.
-- **UI Polish:** Fixed awkward right-side spacing in the table and removed all flex styling and fixed-width rules for the last column, so the table now adapts responsively to its content.
-- **CSS Cleanup:** Cleaned up and removed obsolete or conflicting CSS rules for the recent expirations table, resolving layout and syntax errors.
-- **Status Page Table Sorting:**
- - Fixed date comparison logic in the sort function to correctly handle `Date` objects.
- - Refactored event listener attachment for sortable table headers to prevent duplicate listeners being added, resolving issues where sorting only worked once or behaved erratically.
- - Ensured all event listeners (sort, filter, search, export, refresh) are attached reliably after initial data load and rendering.
- _Files: `frontend/status.html`, `frontend/status.js`, `frontend/style.css`_
-
-- **Mobile Export Button:** On mobile devices, the export button at the bottom of the status page now only displays the icon (no text), for a cleaner and more compact UI. The text remains visible on desktop.
-- **Mobile Search Functionality:** The search box for recent expirations at the bottom of the status page now works correctly on mobile, with event listeners properly initialized to ensure filtering works as expected on all devices.
- _Files: `frontend/status.html`, `frontend/status.js`, `frontend/style.css`_
+
+* **Status Page Table:** Removed the "Actions" column (and its buttons) from the "Recently Expired or Expiring Soon" table on `status.html` for a cleaner look.
+
+* **Table Layout:** Updated the table and CSS to use dynamic column widths, eliminating empty space after the Status column and ensuring the table fills the available space naturally.
+
+* **UI Polish:** Fixed awkward right-side spacing in the table and removed all flex styling and fixed-width rules for the last column, so the table now adapts responsively to its content.
+
+* **CSS Cleanup:** Cleaned up and removed obsolete or conflicting CSS rules for the recent expirations table, resolving layout and syntax errors.
+
+* **Status Page Table Sorting:**
+
+ * Fixed date comparison logic in the sort function to correctly handle `Date` objects.
+
+ * Refactored event listener attachment for sortable table headers to prevent duplicate listeners being added, resolving issues where sorting only worked once or behaved erratically.
+
+ * Ensured all event listeners (sort, filter, search, export, refresh) are attached reliably after initial data load and rendering.
+ *Files: `frontend/status.html`, `frontend/status.js`, `frontend/style.css`*
+
+* **Mobile Export Button:** On mobile devices, the export button at the bottom of the status page now only displays the icon (no text), for a cleaner and more compact UI. The text remains visible on desktop.
+
+* **Mobile Search Functionality:** The search box for recent expirations at the bottom of the status page now works correctly on mobile, with event listeners properly initialized to ensure filtering works as expected on all devices.
+ *Files: `frontend/status.html`, `frontend/status.js`, `frontend/style.css`*
### Fixed
-- **Settings Toggle Size:** Fixed inconsistent toggle switch sizing on mobile views, ensuring all toggles render at the correct dimensions (`47x24px`).
- _File: `frontend/settings-styles.css`_
-- **Username Display:** Resolved an issue where user interface elements sometimes incorrectly displayed the username instead of the first name (or vice versa).
- _Files: `frontend/settings-new.js`, `frontend/auth.js`
-- **List/Table View:** Implemented updates and fixes for the warranty list and table views, improving layout and data presentation.
- _Files: `frontend/index.html`, `frontend/script.js`, `frontend/style.css`_
-## [0.9.9.2] - 2025-04-20
+* **Settings Toggle Size:** Fixed inconsistent toggle switch sizing on mobile views, ensuring all toggles render at the correct dimensions (`47x24px`).
+ *File: `frontend/settings-styles.css`*
+
+* **Username Display:** Resolved an issue where user interface elements sometimes incorrectly displayed the username instead of the first name (or vice versa).
+ \_Files: `frontend/settings-new.js`, `frontend/auth.js`
+
+* **List/Table View:** Implemented updates and fixes for the warranty list and table views, improving layout and data presentation.
+ *Files: `frontend/index.html`, `frontend/script.js`, `frontend/style.css`*
+
+## \[0.9.9.2] - 2025-04-20
### Added
-- **Warranty Years (Fractional Support):**
- - You can now enter fractional (decimal) values for warranty periods (e.g., 1.5 years) when adding or editing warranties.
- - The backend, frontend UI, and CSV import/export all support decimal warranty years.
- - Validation and expiration date calculations have been updated to handle decimal years correctly.
- - The UI now allows decimal input for warranty years and displays fractional years in summaries and warranty lists.
- _Files: `backend/app.py`, `frontend/index.html`, `frontend/script.js`_
-- **Import** button added, and functional. Must use CSV file format.
- - ## 📦 Product Information Entry Requirements
+
+* **Warranty Years (Fractional Support):**
+
+ * You can now enter fractional (decimal) values for warranty periods (e.g., 1.5 years) when adding or editing warranties.
+
+ * The backend, frontend UI, and CSV import/export all support decimal warranty years.
+
+ * Validation and expiration date calculations have been updated to handle decimal years correctly.
+
+ * The UI now allows decimal input for warranty years and displays fractional years in summaries and warranty lists.
+ *Files: `backend/app.py`, `frontend/index.html`, `frontend/script.js`*
+
+* **Import** button added, and functional. Must use CSV file format.
+
+ * ## 📦 Product Information Entry Requirements
| Field Name | Format / Example | Required? | Notes |
|----------------|-------------------------------------------|--------------------------------------------------------|-----------------------------------------------------------------------|
-| **ProductName** | Text | ✅ Yes | Provide the name of the product. |
-| **PurchaseDate** | Date (`YYYY-MM-DD`, e.g., `2024-05-21`) | ✅ Yes | Use ISO format only. |
-| **WarrantyYears** | Whole Number (`1`, `3`, `10`) | ✅ Yes, unless `IsLifetime` is `TRUE` | Must be between `1` and `100` if provided. |
-| **IsLifetime** | `TRUE` or `FALSE` (case-insensitive) | ❌ No (Optional) | If omitted, defaults to `FALSE`. |
-| **PurchasePrice** | Number (`199.99`, `50`) | ❌ No (Optional) | Cannot be negative if provided. |
-| **SerialNumber** | Text (`SN123`, `SN123,SN456`) | ❌ No (Optional) | For multiple values, separate with commas. |
-| **ProductURL** | Text (URL format) | ❌ No (Optional) | Full URL to product page (optional field). |
-| **Tags** | Text (`tag1,tag2`) | ❌ No (Optional) | Use comma-separated values for multiple tags. |
+| \*\*ProductName\*\* | Text | ✅ Yes | Provide the name of the product. |
+| \*\*PurchaseDate\*\* | Date (`YYYY-MM-DD`, e.g., `2024-05-21`) | ✅ Yes | Use ISO format only. |
+| \*\*WarrantyYears\*\* | Whole Number (`1`, `3`, `10`) | ✅ Yes, unless `IsLifetime` is `TRUE` | Must be between `1` and `100` if provided. |
+| \*\*IsLifetime\*\* | `TRUE` or `FALSE` (case-insensitive) | ❌ No (Optional) | If omitted, defaults to `FALSE`. |
+| \*\*PurchasePrice\*\* | Number (`199.99`, `50`) | ❌ No (Optional) | Cannot be negative if provided. |
+| \*\*SerialNumber\*\* | Text (`SN123`, `SN123,SN456`) | ❌ No (Optional) | For multiple values, separate with commas. |
+| \*\*ProductURL\*\* | Text (URL format) | ❌ No (Optional) | Full URL to product page (optional field). |
+| \*\*Tags\*\* | Text (`tag1,tag2`) | ❌ No (Optional) | Use comma-separated values for multiple tags. |
-### Changed
-- **Theme:** Unified theme persistence using a single `localStorage` key (`darkMode`) and centralized the loading logic in `theme-loader.js` to enhance consistency and eliminate theme-flashing on load.
- _Files: `frontend/theme-loader.js`, `frontend/script.js`, `frontend/status.js`, `frontend/settings-new.js`, `frontend/settings-new.html`_
+Changed
+---
+
+* **Theme:** Unified theme persistence using a single `localStorage` key (`darkMode`) and centralized the loading logic in `theme-loader.js` to enhance consistency and eliminate theme-flashing on load.
+ *Files: `frontend/theme-loader.js`, `frontend/script.js`, `frontend/status.js`, `frontend/settings-new.js`, `frontend/settings-new.html`*
-- **UI/UX:** Updated the "Add Warranty" modal behavior to only close when the internal 'X' button is clicked. Clicking the backdrop no longer closes the modal. This change is specific to this modal—others retain default backdrop behavior.
- _File: `frontend/script.js`_
+* **UI/UX:** Updated the "Add Warranty" modal behavior to only close when the internal 'X' button is clicked. Clicking the backdrop no longer closes the modal. This change is specific to this modal—others retain default backdrop behavior.
+ *File: `frontend/script.js`*
### Fixed
-- **Wizard Navigation:**
- - Ensured the summary tab in the "Add Warranty" wizard displays and updates correctly.
- - Resolved JS errors (`TypeError: Assignment to constant variable`, `ReferenceError: tabs is not defined`) that affected tab functionality.
- - Fixed scope issues with backdrop click handlers impacting modal behavior.
- _File: `frontend/script.js`_
-- **Header Layout (Desktop):** Standardized header layout across pages by wrapping elements in a `.header-right-group` container and applying consistent styles.
- _Files: `index.html`, `status.html`, `about.html`, `settings-new.html`, `frontend/header-fix.css`_
+* **Wizard Navigation:**
+
+ * Ensured the summary tab in the "Add Warranty" wizard displays and updates correctly.
+
+ * Resolved JS errors (`TypeError: Assignment to constant variable`, `ReferenceError: tabs is not defined`) that affected tab functionality.
+
+ * Fixed scope issues with backdrop click handlers impacting modal behavior.
+ *File: `frontend/script.js`*
+
+* **Header Layout (Desktop):** Standardized header layout across pages by wrapping elements in a `.header-right-group` container and applying consistent styles.
+ *Files: `index.html`, `status.html`, `about.html`, `settings-new.html`, `frontend/header-fix.css`*
-- **Header Layout (Mobile):** Corrected alignment of header elements—title is now left-aligned, user/settings icons right-aligned, and navigation links centered below. Used `!important` to resolve conflicts with desktop styles.
- _File: `frontend/mobile-header.css`_
+* **Header Layout (Mobile):** Corrected alignment of header elements—title is now left-aligned, user/settings icons right-aligned, and navigation links centered below. Used `!important` to resolve conflicts with desktop styles.
+ *File: `frontend/mobile-header.css`*
-- **Theme:** Fixed site-wide dark/light mode persistence. Changes made on one page now reflect consistently across all pages. Standardized use of `darkMode` and `${prefix}darkMode` keys in relevant scripts.
- _Files: `frontend/status.js`, others using `setTheme` / `initializeTheme`_
+* **Theme:** Fixed site-wide dark/light mode persistence. Changes made on one page now reflect consistently across all pages. Standardized use of `darkMode` and `$prefixdarkMode` keys in relevant scripts.
+ *Files: `frontend/status.js`, others using `setTheme` / `initializeTheme`*
-- **User Menu:** Fixed dropdown not opening due to a variable typo. Centralized gear menu toggle logic into `auth.js` for consistent behavior, removing redundant initializations.
- _Files: `frontend/auth.js`, `frontend/script.js`, `frontend/settings-new.js`_
+* **User Menu:** Fixed dropdown not opening due to a variable typo. Centralized gear menu toggle logic into `auth.js` for consistent behavior, removing redundant initializations.
+ *Files: `frontend/auth.js`, `frontend/script.js`, `frontend/settings-new.js`*
-- **JavaScript Errors:** Addressed multiple errors (`ReferenceError`, `TypeError`) related to function order, missing element checks, and incorrect variable usage—primarily impacting `status.html` and pages using `script.js`.
- _Files: `frontend/script.js`, `frontend/status.js`_
+* **JavaScript Errors:** Addressed multiple errors (`ReferenceError`, `TypeError`) related to function order, missing element checks, and incorrect variable usage—primarily impacting `status.html` and pages using `script.js`.
+ *Files: `frontend/script.js`, `frontend/status.js`*
-- **API Integration:** Fixed parsing logic for `/api/statistics` response to correctly interpret the API structure.
- _File: `frontend/status.js`_
+* **API Integration:** Fixed parsing logic for `/api/statistics` response to correctly interpret the API structure.
+ *File: `frontend/status.js`*
### Removed
-- **Settings Gear Icon:** The settings gear icon button and its menu have been removed from the header in all main pages for a cleaner and less redundant UI.
- _Files: `frontend/index.html`, `frontend/status.html`, `frontend/about.html`_
+* **Settings Gear Icon:** The settings gear icon button and its menu have been removed from the header in all main pages for a cleaner and less redundant UI.
+ *Files: `frontend/index.html`, `frontend/status.html`, `frontend/about.html`*
-## [0.9.9.1] - 2025-04-13
+
+\[0.9.9.1] - 2025-04-13
+---
### Added
-- **About Page:** Added a new "About" page accessible via `/about.html` (`frontend/about.html`).
- - Displays application version, links to GitHub repository, releases, author profile, license (AGPL-3.0), and issue tracker.
-- **UI:** Added an "About" link to the user menu dropdown in the header, appearing after "Settings" (`frontend/index.html`, `frontend/status.html`, `frontend/settings-new.html`).
-- **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`).
-- **UI:** Added an "Add New Warranty" button (`#showAddWarrantyBtn`) to trigger the new modal (`frontend/index.html`
+
+* **About Page:** Added a new "About" page accessible via `/about.html` (`frontend/about.html`).
+
+ * Displays application version, links to GitHub repository, releases, author profile, license (AGPL-3.0), and issue tracker.
+
+* **UI:** Added an "About" link to the user menu dropdown in the header, appearing after "Settings" (`frontend/index.html`, `frontend/status.html`, `frontend/settings-new.html`).
+
+* **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`).
+
+**UI:** Added an "Add New Warranty" button (`#showAddWarrantyBtn`) to trigger the new modal (`frontend/index.html`
+
diff --git a/Dockerfile b/Dockerfile
index 14b6a30..1a74412 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -39,6 +39,7 @@ COPY backend/gunicorn_config.py .
RUN mkdir -p /app/backend
COPY backend/__init__.py /app/backend/
COPY backend/auth_utils.py /app/backend/
+COPY backend/auth_routes.py /app/backend/
COPY backend/db_handler.py /app/backend/
COPY backend/extensions.py /app/backend/
COPY backend/oidc_handler.py /app/backend/
diff --git a/backend/app.py b/backend/app.py
index ae525cc..e222fc0 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -1,12 +1,16 @@
from flask import Flask, request, jsonify, send_from_directory, session, redirect, url_for, Response
+from werkzeug.middleware.proxy_fix import ProxyFix
try:
# Try relative import for Docker environment
from backend.extensions import oauth
from backend.db_handler import init_db_pool, get_db_connection, release_db_connection
+ # Import the NEW auth_utils instead of having helpers in app.py
+ from backend.auth_utils import generate_token, decode_token, token_required, admin_required, is_valid_email, is_valid_password
except ImportError:
# Fallback to direct import for development
from extensions import oauth
from db_handler import init_db_pool, get_db_connection, release_db_connection
+ from auth_utils import generate_token, decode_token, token_required, admin_required, is_valid_email, is_valid_password
import psycopg2 # Added import
import os
from datetime import datetime, timedelta, date
@@ -36,6 +40,13 @@ import mimetypes
app = Flask(__name__)
+# Configure Flask to trust forwarded headers from reverse proxy (Nginx)
+# This middleware makes the app aware of being behind a proxy
+# It reads X-Forwarded-Proto (for https) and other headers
+app.wsgi_app = ProxyFix(
+ app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1
+)
+
# Memory optimization configurations
app.config['JSON_SORT_KEYS'] = False # Disable JSON key sorting to save CPU/memory
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False # Disable pretty printing in production
@@ -86,10 +97,10 @@ app.config['JWT_EXPIRATION_DELTA'] = timedelta(hours=int(os.environ.get('JWT_EXP
if app.config['SECRET_KEY'] == 'your_default_secret_key_please_change_in_prod':
logger.warning("SECURITY WARNING: Using default SECRET_KEY. Please set a strong SECRET_KEY environment variable in production.")
-# Initialize DB Pool (this will set the global connection_pool in db_handler.py)
+# Initialize database connection pool via db_handler
try:
- init_db_pool() # Call the function from db_handler
- logger.info("Database connection pool initialization attempted from app.py.")
+ init_db_pool()
+ logger.info("Database connection pool initialized successfully.")
except Exception as e:
logger.critical(f"CRITICAL: Failed to initialize database pool on startup: {e}. Application might not function correctly.")
# Depending on your requirements, you might want to exit or attempt to run in a degraded mode.
@@ -119,24 +130,12 @@ logger.info(f"Max upload file size set to: {MAX_UPLOAD_MB}MB ({MAX_CONTENT_LENGT
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH
-# PostgreSQL connection pool
+# Database environment variables for admin connections only
DB_HOST = os.environ.get('DB_HOST', 'warrackerdb')
DB_NAME = os.environ.get('DB_NAME', 'warranty_db')
-DB_USER = os.environ.get('DB_USER', 'warranty_user')
-DB_PASSWORD = os.environ.get('DB_PASSWORD', 'warranty_password')
DB_ADMIN_USER = os.environ.get('DB_ADMIN_USER', 'warracker_admin')
DB_ADMIN_PASSWORD = os.environ.get('DB_ADMIN_PASSWORD', 'change_this_password_in_production')
-# Create a connection pool with retry logic
-# This block is now moved earlier, before get_db_connection is defined.
-# The actual initialization of the global 'connection_pool' variable
-# and the call to 'init_oidc_client' will happen after all necessary
-# function definitions.
-
-# Old position of create_db_pool, get_db_connection, release_db_connection
-# and the try/except block for connection_pool and init_oidc_client call.
-# These are now defined *before* this spot.
-
# Function to initialize OIDC client based on settings
def init_oidc_client(current_app_instance, db_conn_func, db_release_func): # Keep parameters
logger.info("[APP.PY OIDC_INIT] Attempting to initialize OIDC client...")
@@ -192,193 +191,115 @@ def init_oidc_client(current_app_instance, db_conn_func, db_release_func): # Kee
current_app_instance.config['OIDC_PROVIDER_NAME'] = None
logger.info("[APP.PY OIDC_INIT] OIDC is disabled.")
-# Initialize DB Pool and then OIDC client (this is the new placement for the try/except block)
-with app.app_context(): # Ensure app context is available for url_for, etc. if used by init_oidc_client indirectly
- init_oidc_client(app, get_db_connection, release_db_connection) # Pass the actual DB functions
+# Initialize OIDC client after DB handler is ready
+with app.app_context():
+ init_oidc_client(app, get_db_connection, release_db_connection)
-# Initialize database (definition of init_db, not the call)
def init_db():
"""Initialize the database with required tables"""
+ # Database table creation is now handled by migration files in backend/migrations/
+ # This function is kept for compatibility but does not perform any operations
try:
conn = get_db_connection()
- cur = conn.cursor()
-
- # Create users table if it doesn't exist - Handled by migrations
- # cur.execute("""
- # CREATE TABLE IF NOT EXISTS users (
- # id SERIAL PRIMARY KEY,
- # username VARCHAR(50) UNIQUE NOT NULL,
- # email VARCHAR(100) UNIQUE NOT NULL,
- # password_hash VARCHAR(255) NOT NULL,
- # first_name VARCHAR(50),
- # last_name VARCHAR(50),
- # is_active BOOLEAN DEFAULT TRUE,
- # is_admin BOOLEAN DEFAULT FALSE,
- # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- # updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- # )
- # """)
-
- # Create user_preferences table if it doesn't exist - Handled by migrations
- # cur.execute("""
- # CREATE TABLE IF NOT EXISTS user_preferences (
- # id SERIAL PRIMARY KEY,
- # user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- # email_notifications BOOLEAN NOT NULL DEFAULT TRUE,
- # default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
- # theme VARCHAR(10) NOT NULL DEFAULT 'light',
- # expiring_soon_days INTEGER NOT NULL DEFAULT 30,
- # notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily',
- # notification_time VARCHAR(5) NOT NULL DEFAULT '09:00',
- # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- # updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- # UNIQUE(user_id)
- # )
- # """)
-
- # Check if timezone column exists and add if it doesn't - Handled by migrations (e.g., 008_add_timezone_column.sql)
- # cur.execute("""
- # DO $$
- # BEGIN
- # IF NOT EXISTS (
- # SELECT column_name
- # FROM information_schema.columns
- # WHERE table_name = 'user_preferences' AND column_name = 'timezone'
- # ) THEN
- # ALTER TABLE user_preferences
- # ADD COLUMN timezone VARCHAR(50) NOT NULL DEFAULT 'UTC';
- # RAISE NOTICE 'Added timezone column to user_preferences table';
- # END IF;
- # END $$;
- # """)
-
- # Create warranties table if it doesn't exist - Handled by migrations
- # cur.execute("""
- # CREATE TABLE IF NOT EXISTS warranties (
- # id SERIAL PRIMARY KEY,
- # user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- # item_name VARCHAR(100) NOT NULL,
- # purchase_date DATE NOT NULL,
- # expiration_date DATE NOT NULL,
- # purchase_price DECIMAL(10,2),
- # serial_number VARCHAR(100),
- # category VARCHAR(50),
- # notes TEXT,
- # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- # updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- # )
- # """)
+ if conn:
+ conn.commit()
- # Create warranty_documents table if it doesn't exist - Handled by migrations
- # cur.execute("""
- # CREATE TABLE IF NOT EXISTS warranty_documents (
- # id INTEGER PRIMARY KEY,
- # warranty_id INTEGER NOT NULL REFERENCES warranties(id) ON DELETE CASCADE,
- # file_name VARCHAR(255) NOT NULL,
- # file_path VARCHAR(255) NOT NULL,
- # )
- # """)
+ # Ensure owner role is properly set (backup to migration)
+ ensure_owner_exists()
- conn.commit() # Commit any changes if init_db did anything
- cur.close()
+ logger.info("Database initialization completed - using migration system")
except Exception as e:
- logger.error(f"Database initialization error in init_db: {str(e)}")
- # Decide if to raise, for now, just log as per original short init_db
+ logger.error(f"Database initialization error: {str(e)}")
finally:
- if conn: # conn might not be defined if get_db_connection failed
+ if conn:
release_db_connection(conn)
+def ensure_owner_exists():
+ """
+ Ensure that an application owner exists. This is a backup mechanism
+ in case the migration failed. Runs automatically on app startup.
+ """
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if any owner exists
+ cur.execute("SELECT COUNT(*) FROM users WHERE is_owner = TRUE")
+ owner_count = cur.fetchone()[0]
+
+ if owner_count == 0:
+ logger.info("No application owner found, attempting to promote first user...")
+
+ # Find the first user using multiple strategies
+ first_user_id = None
+
+ # Strategy 1: First user by created_at
+ try:
+ cur.execute("""
+ SELECT id FROM users
+ WHERE created_at IS NOT NULL
+ ORDER BY created_at ASC, id ASC
+ LIMIT 1
+ """)
+ result = cur.fetchone()
+ if result:
+ first_user_id = result[0]
+ except Exception as e:
+ logger.warning(f"Strategy 1 (created_at) failed: {e}")
+
+ # Strategy 2: First user by ID if Strategy 1 failed
+ if first_user_id is None:
+ try:
+ cur.execute("SELECT id FROM users ORDER BY id ASC LIMIT 1")
+ result = cur.fetchone()
+ if result:
+ first_user_id = result[0]
+ except Exception as e:
+ logger.warning(f"Strategy 2 (lowest ID) failed: {e}")
+
+ # Strategy 3: First admin user if other strategies failed
+ if first_user_id is None:
+ try:
+ cur.execute("SELECT id FROM users WHERE is_admin = TRUE ORDER BY id ASC LIMIT 1")
+ result = cur.fetchone()
+ if result:
+ first_user_id = result[0]
+ except Exception as e:
+ logger.warning(f"Strategy 3 (first admin) failed: {e}")
+
+ # Promote the user to owner if found
+ if first_user_id is not None:
+ try:
+ cur.execute("UPDATE users SET is_owner = TRUE WHERE id = %s", (first_user_id,))
+ conn.commit()
+ logger.info(f"✅ Automatically promoted user ID {first_user_id} to application owner")
+
+ # Log user info for confirmation
+ cur.execute("SELECT username, email FROM users WHERE id = %s", (first_user_id,))
+ user_info = cur.fetchone()
+ if user_info:
+ logger.info(f"Owner is now: {user_info[0]} ({user_info[1]})")
+ except Exception as e:
+ logger.error(f"Failed to promote user {first_user_id} to owner: {e}")
+ conn.rollback()
+ else:
+ logger.warning("No users found in system. First registered user will become owner.")
+ else:
+ # Log current owner for confirmation
+ cur.execute("SELECT id, username, email FROM users WHERE is_owner = TRUE")
+ owners = cur.fetchall()
+ logger.info(f"Application owner(s) confirmed: {[f'{o[1]} (ID:{o[0]})' for o in owners]}")
+
+ except Exception as e:
+ logger.error(f"Error in ensure_owner_exists: {e}")
+ if conn:
+ conn.rollback()
+ finally:
+ if conn:
+ release_db_connection(conn)
-# Authentication helper functions
-# ... (generate_token, decode_token, token_required, admin_required, etc. remain the same)
-# They use get_db_connection, which should now work.
-
-# --- Ensure create_db_pool was defined before this point ---
-# The following is the original position of the try-except block that initialized connection_pool
-# and called init_oidc_client. It has been moved up.
-
-# Original try-except block for connection_pool and init_oidc_client:
-# try:
-# connection_pool = create_db_pool()
-# # Initialize OIDC client after app and DB pool are available
-# # This ensures DB can be queried for settings.
-# if connection_pool: # Only if DB connection is likely
-# with app.app_context(): # Needed if get_db_connection uses app context implicitly or for safety
-# init_oidc_client(app, get_db_connection, release_db_connection)
-# else:
-# logger.error("Database connection pool not available. OIDC client initialization might be incomplete or use defaults/env vars only.")
-# # Fallback or minimal OIDC init if DB is not available at startup
-# with app.app_context():
-# init_oidc_client(app, lambda: None, lambda conn: None) # Pass dummy DB funcs
-#
-# except Exception as e:
-# logger.error(f"Fatal database connection error during startup: {e}")
-# connection_pool = None
-# logger.warning("Database connection pool failed. OIDC client initialization might be incomplete or use defaults/env vars only.")
-# with app.app_context():
-# init_oidc_client(app, lambda: None, lambda conn: None)
-
-
-# def get_db_connection(): # Original position, now moved up
-# ...
-
-# def release_db_connection(conn): # Original position, now moved up
-# ...
-
-# def allowed_file(filename): # Original position, can stay or move with other helpers
-# ...
-
-# def init_db(): # Original position, now moved up (definition)
-# ... (rest of the file)
-# The actual call to init_db() for production is at the end of the file, that's fine.
-# Example of where create_db_pool was defined:
-# def create_db_pool(max_retries=5, retry_delay=5):
-# attempt = 0
-# last_exception = None
-#
-# while attempt < max_retries:
-# try:
-# logger.info(f"Attempting to connect to database (attempt {attempt+1}/{max_retries})")
-# connection_pool = pool.SimpleConnectionPool(
-# 1, 10, # min, max connections
-# host=DB_HOST,
-# database=DB_NAME,
-# user=DB_USER,
-# password=DB_PASSWORD
-# )
-# logger.info("Database connection successful")
-# return connection_pool
-# except Exception as e:
-# last_exception = e
-# logger.error(f"Database connection error: {e}")
-# logger.info(f"Retrying in {retry_delay} seconds...")
-# time.sleep(retry_delay)
-# attempt += 1
-#
-# # If we got here, all connection attempts failed
-# logger.error(f"Failed to connect to database after {max_retries} attempts")
-# raise last_exception
-
-# Create a connection pool with retry logic
-# try:
-# connection_pool = create_db_pool()
-# # Initialize OIDC client after app and DB pool are available
-# # This ensures DB can be queried for settings.
-# if connection_pool: # Only if DB connection is likely
-# with app.app_context(): # Needed if get_db_connection uses app context implicitly or for safety
-# init_oidc_client(app, get_db_connection, release_db_connection)
-# else:
-# logger.error("Database connection pool not available. OIDC client initialization might be incomplete or use defaults/env vars only.")
-# # Fallback or minimal OIDC init if DB is not available at startup
-# with app.app_context():
-# init_oidc_client(app, lambda: None, lambda conn: None) # Pass dummy DB funcs
-#
-# except Exception as e:
-# logger.error(f"Fatal database connection error during startup: {e}")
-# connection_pool = None
-# logger.warning("Database connection pool failed. OIDC client initialization might be incomplete or use defaults/env vars only.")
-# with app.app_context():
-# init_oidc_client(app, lambda: None, lambda conn: None)
+
+# Helper functions
def get_admin_db_connection():
@@ -399,215 +320,9 @@ def get_admin_db_connection():
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
-# Initialize database
-def init_db():
- """Initialize the database with required tables"""
- try:
- conn = get_db_connection()
- cur = conn.cursor()
-
- # Create users table if it doesn't exist - Handled by migrations
- # cur.execute("""
- # CREATE TABLE IF NOT EXISTS users (
- # id SERIAL PRIMARY KEY,
- # username VARCHAR(50) UNIQUE NOT NULL,
- # email VARCHAR(100) UNIQUE NOT NULL,
- # password_hash VARCHAR(255) NOT NULL,
- # first_name VARCHAR(50),
- # last_name VARCHAR(50),
- # is_active BOOLEAN DEFAULT TRUE,
- # is_admin BOOLEAN DEFAULT FALSE,
- # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- # updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- # )
- # """)
-
- # Create user_preferences table if it doesn't exist - Handled by migrations
- # cur.execute("""
- # CREATE TABLE IF NOT EXISTS user_preferences (
- # id SERIAL PRIMARY KEY,
- # user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- # email_notifications BOOLEAN NOT NULL DEFAULT TRUE,
- # default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
- # theme VARCHAR(10) NOT NULL DEFAULT 'light',
- # expiring_soon_days INTEGER NOT NULL DEFAULT 30,
- # notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily',
- # notification_time VARCHAR(5) NOT NULL DEFAULT '09:00',
- # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- # updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- # UNIQUE(user_id)
- # )
- # """)
-
- # Check if timezone column exists and add if it doesn't - Handled by migrations (e.g., 008_add_timezone_column.sql)
- # cur.execute("""
- # DO $$
- # BEGIN
- # IF NOT EXISTS (
- # SELECT column_name
- # FROM information_schema.columns
- # WHERE table_name = 'user_preferences' AND column_name = 'timezone'
- # ) THEN
- # ALTER TABLE user_preferences
- # ADD COLUMN timezone VARCHAR(50) NOT NULL DEFAULT 'UTC';
- # RAISE NOTICE 'Added timezone column to user_preferences table';
- # END IF;
- # END $$;
- # """)
-
- # Create warranties table if it doesn't exist - Handled by migrations
- # cur.execute("""
- # CREATE TABLE IF NOT EXISTS warranties (
- # id SERIAL PRIMARY KEY,
- # user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- # item_name VARCHAR(100) NOT NULL,
- # purchase_date DATE NOT NULL,
- # expiration_date DATE NOT NULL,
- # purchase_price DECIMAL(10,2),
- # serial_number VARCHAR(100),
- # category VARCHAR(50),
- # notes TEXT,
- # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- # updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- # )
- # """)
-
- # Create warranty_documents table if it doesn't exist - Handled by migrations
- # cur.execute("""
- # CREATE TABLE IF NOT EXISTS warranty_documents (
- # id INTEGER PRIMARY KEY,
- # warranty_id INTEGER NOT NULL REFERENCES warranties(id) ON DELETE CASCADE,
- # file_name VARCHAR(255) NOT NULL,
- # file_path VARCHAR(255) NOT NULL,
- # )
- # """)
-
- conn.commit() # Commit any changes if init_db did anything
- cur.close()
- except Exception as e:
- logger.error(f"Database initialization error in init_db: {str(e)}")
- # Decide if to raise, for now, just log as per original short init_db
- finally:
- if conn: # conn might not be defined if get_db_connection failed
- release_db_connection(conn)
-
-# Authentication helper functions
-def generate_token(user_id):
- """Generate a JWT token for the user"""
- payload = {
- 'exp': datetime.utcnow() + app.config['JWT_EXPIRATION_DELTA'],
- 'iat': datetime.utcnow(),
- 'sub': user_id
- }
- return jwt.encode(payload, app.config['SECRET_KEY'], algorithm='HS256')
-
-def decode_token(token):
- """Decode a JWT token and return the user_id"""
- try:
- payload = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
- return payload['sub']
- except jwt.ExpiredSignatureError:
- return None # Token has expired
- except jwt.InvalidTokenError:
- return None # Invalid token
-
-def token_required(f):
- """Decorator to protect routes that require authentication"""
- @wraps(f)
- def decorated(*args, **kwargs):
- token = None
-
- # Get token from Authorization header
- auth_header = request.headers.get('Authorization')
- if auth_header and auth_header.startswith('Bearer '):
- token = auth_header.split(' ')[1]
-
- # If no token in header, check form data for POST requests
- if not token and request.method == 'POST':
- token = request.form.get('auth_token') # Check form data
-
- # If still no token, check URL query parameters
- if not token:
- token = request.args.get('token') # Check query parameters
-
- # If no token is provided
- if not token:
- logger.warning(f"Authentication attempt without token: {request.path}")
- return jsonify({'message': 'Authentication token is missing!'}), 401
-
- # Decode the token
- user_id = decode_token(token)
- if not user_id:
- logger.warning(f"Invalid token used for: {request.path}")
- return jsonify({'message': 'Invalid or expired token!'}), 401
-
- # Check if user exists
- conn = None
- try:
- conn = get_db_connection()
- with conn.cursor() as cur:
- cur.execute('SELECT id, username, email, is_admin FROM users WHERE id = %s AND is_active = TRUE', (user_id,))
- user = cur.fetchone()
-
- if not user:
- return jsonify({'message': 'User not found or inactive!'}), 401
-
- # Add user info to request context
- request.user = {
- 'id': user[0],
- 'username': user[1],
- 'email': user[2],
- 'is_admin': user[3]
- }
-
- return f(*args, **kwargs)
- except Exception as e:
- logger.error(f"Authentication error: {e}")
- return jsonify({'message': 'Authentication error!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
- return decorated
-
-def admin_required(f):
- """Decorator to protect routes that require admin privileges"""
- @wraps(f)
- def decorated(*args, **kwargs):
- logger.info("Admin required check started")
- token_required_result = token_required(lambda: None)()
-
- if isinstance(token_required_result, tuple) and token_required_result[1] != 200:
- logger.error(f"Token validation failed: {token_required_result}")
- return token_required_result
-
- logger.info(f"User info: {request.user}")
- if not request.user.get('is_admin', False):
- logger.error(f"User {request.user.get('username')} is not an admin")
- return jsonify({'message': 'Admin privileges required!'}), 403
-
- logger.info(f"Admin check passed for user {request.user.get('username')}")
- return f(*args, **kwargs)
-
- return decorated
-def is_valid_email(email):
- """Validate email format"""
- pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
- return re.match(pattern, email) is not None
-def is_valid_password(password):
- """Validate password strength"""
- # At least 8 characters, 1 uppercase, 1 lowercase, 1 number
- if len(password) < 8:
- return False
- if not re.search(r'[A-Z]', password):
- return False
- if not re.search(r'[a-z]', password):
- return False
- if not re.search(r'[0-9]', password):
- return False
- return True
+# Authentication helper functions moved to auth_utils.py
def is_valid_timezone(tz):
"""Validate if a timezone string is valid"""
@@ -628,569 +343,7 @@ def convert_decimals(obj):
else:
return obj
-# OIDC Routes
-# These routes are now handled by the oidc_bp Blueprint in backend/oidc_handler.py
-
-# @app.route('/api/oidc/login')
-# def oidc_login():
-# if not app.config.get('OIDC_ENABLED'):
-# logger.warning("OIDC login attempt while OIDC is disabled in settings.")
-# # Optionally redirect to login with a message, or just return an error
-# return jsonify({'message': 'OIDC (SSO) login is not enabled.'}), 403 # Forbidden or 503 Service Unavailable
-#
-# oidc_provider_name_from_config = app.config.get('OIDC_PROVIDER_NAME')
-# if not oidc_provider_name_from_config:
-# logger.error("OIDC is enabled but provider name not configured in app.config.")
-# return jsonify({'message': 'OIDC provider not configured correctly.'}), 500
-#
-# # Construct the redirect_uri. Ensure your OIDC provider has this exact URI whitelisted.
-# # It should point to your backend's callback endpoint.
-# # For local development, this might be http://localhost:5000/api/oidc/callback
-# # For production, it will be your production URL.
-# # Using url_for with _external=True helps generate the full URL.
-# # The frontend will redirect to this /api/oidc/login, which then redirects to the IdP.
-# redirect_uri = url_for('oidc_callback', _external=True) # This would refer to the callback in this file if not removed
-#
-# # Ensure the redirect_uri uses HTTPS in production if your app is served over HTTPS
-# # This might require checking request.scheme or an environment variable.
-# if os.environ.get('FLASK_ENV') == 'production' and not redirect_uri.startswith('https'):
-# redirect_uri = redirect_uri.replace('http://', 'https://', 1)
-#
-# logger.info(f"OIDC login redirect_uri: {redirect_uri}")
-# return oauth.create_client(oidc_provider_name_from_config).authorize_redirect(redirect_uri)
-
-# @app.route('/api/oidc/callback')
-# def oidc_callback():
-# if not app.config.get('OIDC_ENABLED'):
-# logger.warning("OIDC callback received while OIDC is disabled in settings.")
- frontend_login_url = os.environ.get('FRONTEND_URL', app.config.get('APP_BASE_URL', 'http://localhost:8080')).rstrip('/') + "/login.html"
- return redirect(f"{frontend_login_url}?oidc_error=oidc_disabled")
-
- oidc_provider_name_from_config = app.config.get('OIDC_PROVIDER_NAME')
- if not oidc_provider_name_from_config:
- logger.error("OIDC is enabled but provider name not configured in app.config for callback.")
- frontend_login_url = os.environ.get('FRONTEND_URL', app.config.get('APP_BASE_URL', 'http://localhost:8080')).rstrip('/') + "/login.html"
- return redirect(f"{frontend_login_url}?oidc_error=oidc_misconfigured")
-
- client = oauth.create_client(oidc_provider_name_from_config)
- try:
- token = client.authorize_access_token()
- except Exception as e:
- logger.error(f"OIDC callback error authorizing access token: {e}")
- # Redirect to frontend login page with error
- # This URL should be configurable or a known frontend path
- frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
- return redirect(f"{frontend_login_url}?oidc_error=token_exchange_failed")
-
- if not token:
- logger.error("OIDC callback: Failed to retrieve access token.")
- frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
- return redirect(f"{frontend_login_url}?oidc_error=token_missing")
-
- userinfo = token.get('userinfo')
- if not userinfo:
- # If userinfo is not directly in the token, try fetching it
- try:
- userinfo = client.userinfo(token=token) # Authlib 0.15+
- except Exception as e:
- logger.error(f"OIDC callback error fetching userinfo: {e}")
- frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
- return redirect(f"{frontend_login_url}?oidc_error=userinfo_fetch_failed")
-
- if not userinfo:
- logger.error("OIDC callback: Failed to retrieve userinfo.")
- frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
- return redirect(f"{frontend_login_url}?oidc_error=userinfo_missing")
-
- # --- User Provisioning/Login Logic ---
- # This is a critical part and needs careful implementation.
- # 1. Extract OIDC subject (sub) and issuer (iss) from userinfo or token.
- # These uniquely identify the user at the OIDC provider.
- oidc_subject = userinfo.get('sub')
- oidc_issuer = userinfo.get('iss') # Or from token['iss'] if available
-
- if not oidc_subject:
- logger.error("OIDC callback: 'sub' (subject) missing in userinfo.")
- frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
- return redirect(f"{frontend_login_url}?oidc_error=subject_missing")
-
- conn = None
- try:
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if a user with this OIDC subject and issuer already exists
- # You'll need to add oidc_sub and oidc_issuer columns to your users table.
- # For now, we'll assume these columns exist.
- # A migration will be needed for this.
- cur.execute("SELECT id, username, email, is_admin FROM users WHERE oidc_sub = %s AND oidc_issuer = %s AND is_active = TRUE",
- (oidc_subject, oidc_issuer))
- user_db_data = cur.fetchone()
-
- user_id = None
- is_new_user = False
-
- if user_db_data:
- user_id = user_db_data[0]
- logger.info(f"OIDC Login: Existing user found with ID {user_id} for sub {oidc_subject}")
- else:
- # User does not exist, provision a new one
- is_new_user = True
- email = userinfo.get('email')
- if not email:
- logger.error("OIDC callback: 'email' missing in userinfo for new user.")
- frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
- return redirect(f"{frontend_login_url}?oidc_error=email_missing_for_new_user")
-
- # Check if email is already in use by a non-OIDC account
- cur.execute("SELECT id FROM users WHERE email = %s AND (oidc_sub IS NULL OR oidc_issuer IS NULL)", (email,))
- existing_local_user = cur.fetchone()
- if existing_local_user:
- logger.warning(f"OIDC Signup: Email {email} already exists for a local account. OIDC user cannot be created.")
- # This is a conflict. Decide how to handle:
- # - Ask user to link accounts (complex)
- # - Deny OIDC signup
- frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
- return redirect(f"{frontend_login_url}?oidc_error=email_conflict_local_account")
-
- username = userinfo.get('preferred_username') or userinfo.get('name') or email.split('@')[0]
- # Ensure username is unique if your system requires it
- # This might involve appending a random string if a conflict occurs
-
- # Check if username already exists
- cur.execute("SELECT id FROM users WHERE username = %s", (username,))
- if cur.fetchone():
- username = f"{username}_{str(uuid.uuid4())[:8]}" # Append random chars for uniqueness
-
- first_name = userinfo.get('given_name', '')
- last_name = userinfo.get('family_name', '')
-
- # For OIDC users, we don't store a local password_hash, or store a placeholder.
- # The 'password_hash' column in 'users' table must allow NULL or have a default.
- # Or, add a flag 'is_oidc_user' to users table.
- # For now, let's assume password_hash can be NULL.
-
- # Check if this is the first user (who will be an admin)
- cur.execute('SELECT COUNT(*) FROM users')
- user_count = cur.fetchone()[0]
- is_admin = user_count == 0
-
- cur.execute(
- """INSERT INTO users (username, email, first_name, last_name, is_admin, oidc_sub, oidc_issuer, is_active)
- VALUES (%s, %s, %s, %s, %s, %s, %s, TRUE) RETURNING id""",
- (username, email, first_name, last_name, is_admin, oidc_subject, oidc_issuer)
- )
- user_id = cur.fetchone()[0]
- logger.info(f"OIDC Signup: New user created with ID {user_id} for sub {oidc_subject}")
-
- if user_id:
- # Generate your application's session token
- app_token = generate_token(user_id)
-
- # Update last login
- cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
-
- # Store session info (optional, if you use user_sessions table for OIDC too)
- ip_address = request.remote_addr
- user_agent = request.headers.get('User-Agent', '')
- session_token_uuid = str(uuid.uuid4()) # Different from app_token
- expires_at = datetime.utcnow() + app.config['JWT_EXPIRATION_DELTA']
-
- cur.execute(
- 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent, login_method) VALUES (%s, %s, %s, %s, %s, %s)',
- (user_id, session_token_uuid, expires_at, ip_address, user_agent, 'oidc')
- )
-
- conn.commit()
-
- # Redirect to frontend with the token.
- # The frontend should then store this token and use it for API calls.
- frontend_url = os.environ.get('FRONTEND_URL', app.config.get('APP_BASE_URL', 'http://localhost:8080')).rstrip('/')
- # A dedicated redirect handler page on the frontend is good practice.
- redirect_target = f"{frontend_url}/auth-redirect.html?token={app_token}"
- if is_new_user:
- redirect_target += "&new_user=true"
-
- logger.info(f"[OIDC_CALLBACK] Attempting to redirect to frontend target: {redirect_target}")
- return redirect(redirect_target)
- else:
- logger.error("[OIDC_CALLBACK] User ID not established after DB operations.")
- frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
- return redirect(f"{frontend_login_url}?oidc_error=user_processing_failed")
-
- except psycopg2.Error as db_err:
- logger.error(f"OIDC callback: Database error: {db_err}")
- if conn:
- conn.rollback()
- frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
- return redirect(f"{frontend_login_url}?oidc_error=db_error")
- except Exception as e:
- logger.error(f"OIDC callback: General error: {e}", exc_info=True)
- if conn:
- conn.rollback()
- frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"
- return redirect(f"{frontend_login_url}?oidc_error=internal_error")
- finally:
- if conn:
- release_db_connection(conn)
-
-# Authentication routes
[email protected]('/api/auth/register', methods=['POST'])
-def register():
- conn = None
- try:
- data = request.get_json()
-
- # Check if registration is enabled
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if settings table exists
- cur.execute("""
- SELECT EXISTS (
- SELECT FROM information_schema.tables
- WHERE table_name = 'site_settings'
- )
- """)
- table_exists = cur.fetchone()[0]
-
- registration_enabled = True
- if table_exists:
- # Get registration_enabled setting
- cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")
- result = cur.fetchone()
-
- if result:
- registration_enabled = result[0].lower() == 'true'
-
- # Check if there are any users (first user can register regardless of setting)
- cur.execute('SELECT COUNT(*) FROM users')
- user_count = cur.fetchone()[0]
-
- # If registration is disabled and this is not the first user, return error
- if not registration_enabled and user_count > 0:
- return jsonify({'message': 'Registration is currently disabled!'}), 403
-
- # Validate required fields
- required_fields = ['username', 'email', 'password']
- for field in required_fields:
- if field not in data or not data[field]:
- return jsonify({'message': f'{field} is required!'}), 400
-
- username = data['username']
- email = data['email']
- password = data['password']
- first_name = data.get('first_name', '')
- last_name = data.get('last_name', '')
-
- # Validate email format
- if not is_valid_email(email):
- return jsonify({'message': 'Invalid email format!'}), 400
-
- # Validate password strength
- if not is_valid_password(password):
- return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
-
- # Hash the password
- password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
-
- with conn.cursor() as cur:
- # Check if username or email already exists
- cur.execute('SELECT id FROM users WHERE username = %s OR email = %s', (username, email))
- existing_user = cur.fetchone()
-
- if existing_user:
- return jsonify({'message': 'Username or email already exists!'}), 409
-
- # Check if this is the first user (who will be an admin)
- cur.execute('SELECT COUNT(*) FROM users')
- user_count = cur.fetchone()[0]
- is_admin = user_count == 0
-
- # Insert new user
- cur.execute(
- 'INSERT INTO users (username, email, password_hash, first_name, last_name, is_admin) VALUES (%s, %s, %s, %s, %s, %s) RETURNING id',
- (username, email, password_hash, first_name, last_name, is_admin)
- )
- user_id = cur.fetchone()[0]
-
- # Generate token
- token = generate_token(user_id)
-
- # Update last login
- cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
-
- # Store session info
- ip_address = request.remote_addr
- user_agent = request.headers.get('User-Agent', '')
- session_token = str(uuid.uuid4())
- expires_at = datetime.utcnow() + app.config['JWT_EXPIRATION_DELTA']
-
- cur.execute(
- 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent, login_method) VALUES (%s, %s, %s, %s, %s, %s)',
- (user_id, session_token, expires_at, ip_address, user_agent, 'local')
- )
-
- conn.commit()
-
- return jsonify({
- 'message': 'User registered successfully!',
- 'token': token,
- 'user': {
- 'id': user_id,
- 'username': username,
- 'email': email,
- 'is_admin': is_admin
- }
- }), 201
- except Exception as e:
- logger.error(f"Registration error: {e}")
- if conn:
- conn.rollback()
- return jsonify({'message': 'Registration failed!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/auth/login', methods=['POST'])
-def login():
- conn = None
- try:
- data = request.get_json()
-
- # Validate required fields
- if not data.get('username') or not data.get('password'):
- return jsonify({'message': 'Username and password are required!'}), 400
-
- username = data['username']
- password = data['password']
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if user exists - include is_admin in the query
- cur.execute('SELECT id, username, email, password_hash, is_active, is_admin FROM users WHERE username = %s OR email = %s', (username, username))
- user = cur.fetchone()
-
- if not user or not bcrypt.check_password_hash(user[3], password):
- return jsonify({'message': 'Invalid username or password!'}), 401
-
- if not user[4]: # is_active
- return jsonify({'message': 'Account is inactive!'}), 401
-
- user_id = user[0]
-
- # Generate token
- token = generate_token(user_id)
-
- # Update last login
- cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
-
- # Store session info
- ip_address = request.remote_addr
- user_agent = request.headers.get('User-Agent', '')
- session_token = str(uuid.uuid4())
- expires_at = datetime.utcnow() + app.config['JWT_EXPIRATION_DELTA']
-
- cur.execute(
- 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent, login_method) VALUES (%s, %s, %s, %s, %s, %s)',
- (user_id, session_token, expires_at, ip_address, user_agent, 'local')
- )
-
- conn.commit()
-
- return jsonify({
- 'message': 'Login successful!',
- 'token': token,
- 'user': {
- 'id': user_id,
- 'username': user[1],
- 'email': user[2],
- 'is_admin': user[5] # Include is_admin flag
- }
- }), 200
- except Exception as e:
- logger.error(f"Login error: {e}")
- if conn:
- conn.rollback()
- return jsonify({'message': 'Login failed!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/auth/logout', methods=['POST'])
-@token_required
-def logout():
- conn = None
- try:
- auth_header = request.headers.get('Authorization')
- if auth_header and auth_header.startswith('Bearer '):
- token = auth_header.split(' ')[1]
- else:
- return jsonify({'message': 'No token provided!'}), 400
-
- user_id = request.user['id']
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Invalidate all sessions for this user
- cur.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
- conn.commit()
-
- return jsonify({'message': 'Logout successful!'}), 200
- except Exception as e:
- logger.error(f"Logout error: {e}")
- if conn:
- conn.rollback()
- return jsonify({'message': 'Logout failed!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/auth/validate-token', methods=['GET'])
-@token_required
-def validate_token():
- """Validate JWT token and return user info"""
- try:
- # If we got here, the token is valid (token_required decorator validated it)
- return jsonify({
- 'valid': True,
- 'user': {
- 'id': request.user['id'],
- 'username': request.user['username'],
- 'email': request.user['email'],
- 'is_admin': request.user['is_admin']
- },
- 'message': 'Token is valid'
- }), 200
- except Exception as e:
- logger.error(f"Token validation error: {e}")
- return jsonify({
- 'valid': False,
- 'message': 'Invalid token'
- }), 401
-
[email protected]('/api/auth/user', methods=['GET'])
-@token_required
-def get_user():
- conn = None
- try:
- user_id = request.user['id'] # Get user ID from the decorator
-
- # --- ADD DATABASE QUERY ---
- conn = get_db_connection()
- with conn.cursor() as cur:
- cur.execute(
- 'SELECT id, username, email, first_name, last_name, is_admin FROM users WHERE id = %s',
- (user_id,)
- )
- user_data = cur.fetchone()
- # --- END DATABASE QUERY ---
-
- if not user_data:
- return jsonify({'message': 'User not found!'}), 404
-
- # Map database columns to a dictionary
- columns = ['id', 'username', 'email', 'first_name', 'last_name', 'is_admin']
- user_info = dict(zip(columns, user_data))
-
- # Return the full user information
- return jsonify(user_info), 200
-
- except Exception as e:
- logger.error(f"Get user error: {e}")
- # Optionally rollback if there was an error during DB interaction
- # if conn:
- # conn.rollback() # Not strictly needed for SELECT, but good practice if errors occur
- return jsonify({'message': 'Failed to retrieve user information!'}), 500
- finally:
- # Release the connection back to the pool
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/auth/password/reset-request', methods=['POST'])
-def request_password_reset():
- conn = None
- try:
- data = request.get_json()
-
- if not data.get('email'):
- return jsonify({'message': 'Email is required!'}), 400
-
- email = data['email']
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if user exists
- cur.execute('SELECT id FROM users WHERE email = %s', (email,))
- user = cur.fetchone()
-
- if not user:
- # Don't reveal if email exists or not for security
- return jsonify({'message': 'If your email is registered, you will receive a password reset link.'}), 200
-
- user_id = user[0]
-
- # Generate reset token
- reset_token = str(uuid.uuid4())
- expires_at = datetime.utcnow() + timedelta(hours=24)
-
- # Delete any existing tokens for this user
- cur.execute('DELETE FROM password_reset_tokens WHERE user_id = %s', (user_id,))
-
- # Insert new token
- cur.execute(
- 'INSERT INTO password_reset_tokens (user_id, token, expires_at) VALUES (%s, %s, %s)',
- (user_id, reset_token, expires_at)
- )
-
- conn.commit()
-
- # Get email base URL from settings
- email_base_url = 'http://localhost:8080' # Default fallback
- try:
- cur.execute("SELECT value FROM site_settings WHERE key = 'email_base_url'")
- result = cur.fetchone()
- if result:
- email_base_url = result[0]
- else:
- logger.warning("email_base_url setting not found for password reset, using default.")
- except Exception as e:
- logger.error(f"Error fetching email_base_url from settings for password reset: {e}. Using default.")
-
- # Ensure base URL doesn't end with a slash
- email_base_url = email_base_url.rstrip('/')
-
- # Construct the full reset link
- reset_link = f"{email_base_url}/reset-password.html?token={reset_token}" # Use base URL and correct page
-
- # Send password reset email
- logger.info(f"Password reset requested for user {user_id}. Preparing to send email.")
- try:
- send_password_reset_email(email, reset_link)
- logger.info(f"Password reset email initiated for {email}")
- except Exception as e:
- logger.error(f"Failed to send password reset email to {email}: {e}")
- # Even if email fails, don't tell the user.
- # This prevents leaking information about registered emails or email server issues.
- # The user journey remains the same: "If registered, you'll get an email."
-
- # Always return success to the user, regardless of email success/failure
- return jsonify({
- 'message': 'If your email is registered, you will receive a password reset link.'
- }), 200
-
- except Exception as e:
- logger.error(f"Password reset request error: {e}")
- if conn:
- conn.rollback()
- return jsonify({'message': 'Password reset request failed!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
-# Note: The actual reset_password function is defined earlier in the file.
-# The duplicated block that caused the error has been removed.
-
-
-# Update existing endpoints to use authentication
+# OIDC functionality is handled by the oidc_bp Blueprint in backend/oidc_handler.py
@app.route('/api/warranties', methods=['GET'])
@token_required
@@ -1208,7 +361,7 @@ def get_warranties():
cur.execute('''
SELECT id, product_name, purchase_date, expiration_date, invoice_path, manual_path, other_document_path, product_url, notes,
purchase_price, user_id, created_at, updated_at, is_lifetime, vendor, warranty_type,
- warranty_duration_years, warranty_duration_months, warranty_duration_days, product_photo_path
+ warranty_duration_years, warranty_duration_months, warranty_duration_days, product_photo_path, currency
FROM warranties
WHERE user_id = %s
ORDER BY CASE WHEN is_lifetime THEN 1 ELSE 0 END, expiration_date NULLS LAST, product_name
@@ -1346,6 +499,23 @@ def add_warranty():
except ValueError:
return jsonify({"error": "Purchase price must be a valid number"}), 400
+ # Handle currency (optional, defaults to USD)
+ currency = request.form.get('currency', 'USD')
+ # Validate currency code
+ valid_currencies = [
+ 'USD', 'EUR', 'GBP', 'JPY', 'CNY', 'INR', 'KRW', 'CHF', 'CAD', 'AUD',
+ 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'HUF', 'BGN', 'RON', 'HRK', 'RUB',
+ 'BRL', 'MXN', 'ARS', 'CLP', 'COP', 'PEN', 'VES', 'ZAR', 'EGP', 'NGN',
+ 'KES', 'GHS', 'MAD', 'TND', 'AED', 'SAR', 'QAR', 'KWD', 'BHD', 'OMR',
+ 'JOD', 'LBP', 'ILS', 'TRY', 'IRR', 'PKR', 'BDT', 'LKR', 'NPR', 'BTN',
+ 'MMK', 'THB', 'VND', 'LAK', 'KHR', 'MYR', 'SGD', 'IDR', 'PHP', 'TWD',
+ 'HKD', 'MOP', 'KPW', 'MNT', 'KZT', 'UZS', 'TJS', 'KGS', 'TMT', 'AFN',
+ 'AMD', 'AZN', 'GEL', 'MDL', 'UAH', 'BYN', 'RSD', 'MKD', 'ALL', 'BAM',
+ 'ISK', 'FJD', 'PGK', 'SBD', 'TOP', 'VUV', 'WST', 'XPF', 'NZD'
+ ]
+ if currency not in valid_currencies:
+ return jsonify({"error": f"Invalid currency code: {currency}"}), 400
+
try:
purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d').date()
except ValueError:
@@ -1470,14 +640,14 @@ def add_warranty():
INSERT INTO warranties (
product_name, purchase_date, expiration_date,
invoice_path, manual_path, other_document_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor, warranty_type,
- warranty_duration_years, warranty_duration_months, warranty_duration_days, product_photo_path
+ warranty_duration_years, warranty_duration_months, warranty_duration_days, product_photo_path, currency
)
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
''', (
product_name, purchase_date, expiration_date,
db_invoice_path, db_manual_path, db_other_document_path, product_url, purchase_price, user_id, is_lifetime, notes, vendor, warranty_type,
- warranty_duration_years, warranty_duration_months, warranty_duration_days, db_product_photo_path
+ warranty_duration_years, warranty_duration_months, warranty_duration_days, db_product_photo_path, currency
))
warranty_id = cur.fetchone()[0]
@@ -1718,6 +888,23 @@ def update_warranty(warranty_id):
return jsonify({"error": "Purchase price cannot be negative"}), 400
except ValueError:
return jsonify({"error": "Purchase price must be a valid number"}), 400
+
+ # Handle currency (optional, defaults to USD)
+ currency = request.form.get('currency', 'USD')
+ # Validate currency code
+ valid_currencies = [
+ 'USD', 'EUR', 'GBP', 'JPY', 'CNY', 'INR', 'KRW', 'CHF', 'CAD', 'AUD',
+ 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'HUF', 'BGN', 'RON', 'HRK', 'RUB',
+ 'BRL', 'MXN', 'ARS', 'CLP', 'COP', 'PEN', 'VES', 'ZAR', 'EGP', 'NGN',
+ 'KES', 'GHS', 'MAD', 'TND', 'AED', 'SAR', 'QAR', 'KWD', 'BHD', 'OMR',
+ 'JOD', 'LBP', 'ILS', 'TRY', 'IRR', 'PKR', 'BDT', 'LKR', 'NPR', 'BTN',
+ 'MMK', 'THB', 'VND', 'LAK', 'KHR', 'MYR', 'SGD', 'IDR', 'PHP', 'TWD',
+ 'HKD', 'MOP', 'KPW', 'MNT', 'KZT', 'UZS', 'TJS', 'KGS', 'TMT', 'AFN',
+ 'AMD', 'AZN', 'GEL', 'MDL', 'UAH', 'BYN', 'RSD', 'MKD', 'ALL', 'BAM',
+ 'ISK', 'FJD', 'PGK', 'SBD', 'TOP', 'VUV', 'WST', 'XPF', 'NZD'
+ ]
+ if currency not in valid_currencies:
+ return jsonify({"error": f"Invalid currency code: {currency}"}), 400
db_invoice_path = None
if 'invoice' in request.files:
invoice = request.files['invoice']
@@ -1893,7 +1080,8 @@ def update_warranty(warranty_id):
'product_url': product_url,
'purchase_price': purchase_price,
'vendor': vendor,
- 'warranty_type': warranty_type
+ 'warranty_type': warranty_type,
+ 'currency': currency
}
sql_fields = []
sql_values = []
@@ -2365,644 +1553,6 @@ def test_endpoint():
"timestamp": datetime.utcnow().isoformat()
})
-# Public endpoint to check if authentication is required
[email protected]('/api/auth/status', methods=['GET'])
-def auth_status():
- return jsonify({
- "authentication_required": True,
- "message": "Authentication is required for most endpoints"
- })
-
[email protected]('/api/auth/profile', methods=['PUT'])
-@token_required
-def update_profile():
- user_id = request.user['id']
-
- try:
- # Get request data
- data = request.get_json()
- if not data:
- return jsonify({'message': 'No input data provided'}), 400
-
- # Extract fields
- first_name = data.get('first_name', '').strip()
- last_name = data.get('last_name', '').strip()
- new_email = data.get('email', '').strip()
-
- # Validate input
- if not first_name or not last_name:
- return jsonify({'message': 'First name and last name are required'}), 400
-
- # Get database connection
- conn = get_db_connection()
- cursor = conn.cursor()
-
- try:
- update_fields = ["first_name = %s", "last_name = %s"]
- update_params = [first_name, last_name]
-
- # Handle email change
- if new_email:
- if not is_valid_email(new_email):
- conn.rollback()
- return jsonify({'message': 'Invalid email format!'}), 400
-
- # Check if the new email is different from the current one
- cursor.execute("SELECT email FROM users WHERE id = %s", (user_id,))
- current_email_tuple = cur.fetchone()
- if not current_email_tuple:
- conn.rollback()
- return jsonify({'message': 'User not found while fetching current email.'}), 404
- current_email = current_email_tuple[0]
-
- if new_email.lower() != current_email.lower():
- # Check if the new email is already in use by another user
- cursor.execute("SELECT id FROM users WHERE LOWER(email) = LOWER(%s) AND id != %s", (new_email, user_id))
- if cursor.fetchone():
- conn.rollback()
- return jsonify({'message': 'This email address is already in use by another account.'}), 409
- update_fields.append("email = %s")
- update_params.append(new_email)
-
- update_query_string = ", ".join(update_fields)
- final_query = f"""
- UPDATE users
- SET {update_query_string}
- WHERE id = %s
- RETURNING id, username, email, first_name, last_name, created_at
- """
- cursor.execute(final_query, tuple(update_params + [user_id]))
-
- # Get updated user data
- user_data = cursor.fetchone()
- if not user_data:
- conn.rollback()
- return jsonify({'message': 'User not found'}), 404
-
- conn.commit()
-
- user = {
- 'id': user_data[0],
- 'username': user_data[1],
- 'email': user_data[2],
- 'first_name': user_data[3],
- 'last_name': user_data[4],
- 'created_at': user_data[5].isoformat() if user_data[5] else None
- }
- return jsonify(user), 200
-
- except Exception as e:
- conn.rollback()
- logger.error(f"Database error in update_profile: {str(e)}")
- return jsonify({'message': 'Database error occurred'}), 500
- finally:
- cursor.close()
- release_db_connection(conn)
-
- except Exception as e:
- logger.error(f"Error in update_profile: {str(e)}")
- return jsonify({'message': 'An error occurred while updating profile'}), 500
-
[email protected]('/api/auth/account', methods=['DELETE'])
-@token_required
-def delete_account():
- user_id = request.user['id']
-
- try:
- # Get database connection
- conn = get_db_connection()
- cursor = conn.cursor()
-
- try:
- # Begin transaction
- cursor.execute("BEGIN")
-
- # Delete user's warranties
- cursor.execute("DELETE FROM warranties WHERE user_id = %s", (user_id,))
-
- # Delete user's reset tokens if any
- cursor.execute("DELETE FROM password_reset_tokens WHERE user_id = %s", (user_id,))
-
- # Delete user's sessions if any
- cursor.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
- sessions_deleted = cursor.rowcount
- logger.info(f"Deleted {sessions_deleted} sessions belonging to user {user_id}")
-
- # Delete user's tags
- cursor.execute('DELETE FROM tags WHERE user_id = %s', (user_id,))
- tags_deleted = cur.rowcount
- logger.info(f"Deleted {tags_deleted} tags belonging to user {user_id}")
-
- # Delete user
- cursor.execute("DELETE FROM users WHERE id = %s", (user_id,))
- user_deleted = cur.rowcount
- logger.info(f"Deleted user {user_id}, affected rows: {user_deleted}")
-
- # Commit transaction
- cursor.execute("COMMIT")
-
- return jsonify({'message': 'Account deleted successfully'}), 200
-
- except Exception as e:
- cursor.execute("ROLLBACK")
- logger.error(f"Database error in delete_account: {str(e)}")
- return jsonify({'message': 'Database error occurred'}), 500
- finally:
- cursor.close()
- release_db_connection(conn)
-
- except Exception as e:
- logger.error(f"Error in delete_account: {str(e)}")
- return jsonify({'message': 'An error occurred while deleting account'}), 500
-
[email protected]('/api/auth/preferences', methods=['GET'])
-@token_required
-def get_preferences():
- user_id = request.user['id']
- try:
- conn = get_db_connection()
- cursor = conn.cursor()
- try:
- # Check for notification columns
- cursor.execute("""
- SELECT column_name FROM information_schema.columns
- WHERE table_name='user_preferences'
- AND column_name IN ('notification_channel', 'apprise_notification_time', 'apprise_notification_frequency', 'apprise_timezone')
- """)
- existing_columns = [row[0] for row in cursor.fetchall()]
-
- cursor.execute("""
- SELECT EXISTS (
- SELECT FROM information_schema.tables
- WHERE table_name = 'user_preferences'
- )
- """)
- table_exists = cursor.fetchone()[0]
- if not table_exists:
- cursor.execute("""
- CREATE TABLE user_preferences (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- email_notifications BOOLEAN NOT NULL DEFAULT TRUE,
- default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
- theme VARCHAR(10) NOT NULL DEFAULT 'light',
- expiring_soon_days INTEGER NOT NULL DEFAULT 30,
- notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily',
- notification_time VARCHAR(5) NOT NULL DEFAULT '09:00',
- timezone VARCHAR(50) NOT NULL DEFAULT 'UTC',
- currency_symbol VARCHAR(8) DEFAULT '$',
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- UNIQUE(user_id)
- )
- """)
- cursor.execute("""
- CREATE INDEX idx_user_preferences_user_id ON user_preferences(user_id)
- """)
- conn.commit()
- logger.info(f"Created user_preferences table")
- has_currency = has_currency_symbol_column(cursor)
-
- cursor.execute("SELECT column_name FROM information_schema.columns WHERE table_name='user_preferences' AND column_name='date_format'")
- has_date_format_col = cursor.fetchone() is not None
-
- has_notification_channel = 'notification_channel' in existing_columns
- has_apprise_notification_time = 'apprise_notification_time' in existing_columns
- has_apprise_notification_frequency = 'apprise_notification_frequency' in existing_columns
-
- # Build select list dynamically
- select_fields_list = ["email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
- if has_notification_channel:
- select_fields_list.append("notification_channel")
- has_apprise_notification_time = 'apprise_notification_time' in existing_columns
- if has_apprise_notification_time:
- select_fields_list.append("apprise_notification_time")
- if 'apprise_timezone' in existing_columns:
- select_fields_list.append("apprise_timezone")
- has_apprise_notification_frequency = 'apprise_notification_frequency' in existing_columns
- if has_apprise_notification_frequency:
- select_fields_list.append("apprise_notification_frequency")
- if has_currency:
- select_fields_list.append("currency_symbol")
- if has_date_format_col:
- select_fields_list.append("date_format") # Add date_format if column exists
- select_fields = ", ".join(select_fields_list)
-
- cursor.execute(
- f"""
- SELECT {select_fields}
- FROM user_preferences
- WHERE user_id = %s
- """,
- (user_id,)
- )
- preferences_data = cursor.fetchone()
-
- if not preferences_data:
- # Build insert list dynamically
- insert_cols_list = ["user_id", "email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
- insert_vals = [user_id, True, 'grid', 'light', 30, 'daily', '09:00', 'UTC']
- if has_notification_channel:
- insert_cols_list.append("notification_channel")
- insert_vals.append('email') # Default to email notifications
- if has_apprise_notification_time:
- insert_cols_list.append("apprise_notification_time")
- insert_vals.append('09:00')
- if has_apprise_notification_frequency:
- insert_cols_list.append("apprise_notification_frequency")
- insert_vals.append('daily')
- if has_currency:
- insert_cols_list.append("currency_symbol")
- insert_vals.append('$')
- if has_date_format_col:
- insert_cols_list.append("date_format")
- insert_vals.append('MDY') # Default date format
-
- insert_cols = ", ".join(insert_cols_list)
- insert_vals_placeholders = ", ".join(["%s"] * len(insert_cols_list))
- return_fields = insert_cols # Return the same columns we inserted
-
- cursor.execute(
- f"""
- INSERT INTO user_preferences ({insert_cols})
- VALUES ({insert_vals_placeholders})
- RETURNING {return_fields}
- """,
- tuple(insert_vals)
- )
- preferences_data = cursor.fetchone()
- conn.commit()
-
- # Map returned data to dictionary using the dynamically determined fields
- returned_columns = [col.strip() for col in select_fields.split(',')]
- if preferences_data:
- pref_map = {col: i for i, col in enumerate(returned_columns)}
- preferences = {
- 'email_notifications': preferences_data[pref_map.get('email_notifications', 0)],
- 'default_view': preferences_data[pref_map.get('default_view', 1)],
- 'theme': preferences_data[pref_map.get('theme', 2)],
- 'expiring_soon_days': preferences_data[pref_map.get('expiring_soon_days', 3)],
- 'notification_frequency': preferences_data[pref_map.get('notification_frequency', 4)],
- 'notification_time': preferences_data[pref_map.get('notification_time', 5)],
- 'timezone': preferences_data[pref_map.get('timezone', 6)],
- 'notification_channel': preferences_data[pref_map['notification_channel']] if 'notification_channel' in pref_map else 'email',
- 'apprise_notification_time': preferences_data[pref_map['apprise_notification_time']] if 'apprise_notification_time' in pref_map else '09:00',
- 'apprise_timezone': preferences_data[pref_map['apprise_timezone']] if 'apprise_timezone' in pref_map else 'UTC',
- 'apprise_notification_frequency': preferences_data[pref_map['apprise_notification_frequency']] if 'apprise_notification_frequency' in pref_map else 'daily',
- 'currency_symbol': preferences_data[pref_map['currency_symbol']] if 'currency_symbol' in pref_map else '$', # Handle currency optionality
- 'date_format': preferences_data[pref_map['date_format']] if 'date_format' in pref_map else 'MDY' # Handle date_format optionality
- }
- else:
- # Fallback if even insert failed or returned nothing
- preferences = {
- 'email_notifications': True,
- 'default_view': 'grid',
- 'theme': 'light',
- 'expiring_soon_days': 30,
- 'notification_frequency': 'daily',
- 'notification_time': '09:00',
- 'timezone': 'UTC',
- 'notification_channel': 'email',
- 'apprise_notification_time': '09:00',
- 'apprise_notification_frequency': 'daily',
- 'currency_symbol': '$',
- 'date_format': 'MDY'
- }
-
- return jsonify(preferences), 200
- except Exception as e:
- conn.rollback()
- logger.error(f"Database error in get_preferences: {str(e)}")
- default_preferences = {
- 'email_notifications': True,
- 'default_view': 'grid',
- 'theme': 'light',
- 'expiring_soon_days': 30,
- 'notification_frequency': 'daily',
- 'notification_time': '09:00',
- 'timezone': 'UTC',
- 'notification_channel': 'email',
- 'apprise_notification_time': '09:00',
- 'apprise_notification_frequency': 'daily',
- 'currency_symbol': '$',
- 'date_format': 'MDY'
- }
- return jsonify(default_preferences), 200
- finally:
- cursor.close()
- release_db_connection(conn)
- except Exception as e:
- logger.error(f"Error in get_preferences: {str(e)}")
- default_preferences = {
- 'email_notifications': True,
- 'default_view': 'grid',
- 'theme': 'light',
- 'expiring_soon_days': 30,
- 'notification_frequency': 'daily',
- 'notification_time': '09:00',
- 'timezone': 'UTC',
- 'notification_channel': 'email',
- 'apprise_notification_time': '09:00',
- 'apprise_notification_frequency': 'daily',
- 'currency_symbol': '$',
- 'date_format': 'MDY'
- }
- return jsonify(default_preferences), 200
-
[email protected]('/api/auth/preferences', methods=['PUT'])
-@token_required
-def update_preferences():
- user_id = request.user['id']
- try:
- data = request.get_json()
- if not data:
- return jsonify({'message': 'No input data provided'}), 400
-
- # Debug logging for theme issue
- logger.info(f"Update preferences input data: {data}")
-
- notification_channel = data.get('notification_channel')
- default_view = data.get('default_view')
- theme = data.get('theme')
- expiring_soon_days = data.get('expiring_soon_days')
- notification_frequency = data.get('notification_frequency')
- notification_time = data.get('notification_time')
- apprise_notification_time = data.get('apprise_notification_time')
- apprise_notification_frequency = data.get('apprise_notification_frequency')
- timezone = data.get('timezone')
- apprise_timezone = data.get('apprise_timezone')
- currency_symbol = data.get('currency_symbol')
- date_format = data.get('date_format')
-
- logger.info(f"Update preferences parsed theme: {theme}")
-
- if notification_channel and notification_channel not in ['none', 'email', 'apprise', 'both']:
- return jsonify({'message': 'Invalid notification channel'}), 400
- if default_view and default_view not in ['grid', 'list', 'table']:
- return jsonify({'message': 'Invalid default view'}), 400
- if theme and theme not in ['light', 'dark']:
- return jsonify({'message': 'Invalid theme'}), 400
- if expiring_soon_days is not None:
- try:
- expiring_soon_days = int(expiring_soon_days)
- if expiring_soon_days < 1 or expiring_soon_days > 365:
- return jsonify({'message': 'Expiring soon days must be between 1 and 365'}), 400
- except ValueError:
- return jsonify({'message': 'Expiring soon days must be a valid number'}), 400
- if notification_frequency and notification_frequency not in ['daily', 'weekly', 'monthly']:
- return jsonify({'message': 'Invalid notification frequency'}), 400
- if notification_time and not re.match(r'^([01]?[0-9]|2[0-3]):[0-5][0-9]$', notification_time):
- return jsonify({'message': 'Invalid notification time format'}), 400
- if timezone and not is_valid_timezone(timezone):
- return jsonify({'message': 'Invalid timezone'}), 400
- if apprise_timezone and not is_valid_timezone(apprise_timezone):
- return jsonify({'message': 'Invalid Apprise timezone'}), 400
-
- # Add validation for date_format
- valid_date_formats = ['MDY', 'DMY', 'YMD', 'MDY_WORDS', 'DMY_WORDS', 'YMD_WORDS']
- if date_format and date_format not in valid_date_formats:
- return jsonify({'message': 'Invalid date format'}), 400
-
- conn = get_db_connection()
- cursor = conn.cursor()
- try:
- # Check if columns exist first to handle dynamic schema changes
- cursor.execute("""
- SELECT column_name FROM information_schema.columns
- WHERE table_name='user_preferences'
- AND column_name IN ('date_format', 'notification_channel', 'apprise_notification_time', 'apprise_notification_frequency', 'apprise_timezone')
- """)
- existing_cols = [row[0] for row in cursor.fetchall()]
- has_date_format_col = 'date_format' in existing_cols
- has_notification_channel_col = 'notification_channel' in existing_cols
- has_apprise_notification_time_col = 'apprise_notification_time' in existing_cols
- has_apprise_notification_frequency_col = 'apprise_notification_frequency' in existing_cols
- has_currency = has_currency_symbol_column(cursor)
-
- # Debug logging for Apprise settings
- logger.info(f"Update preferences debug - apprise_notification_time: {apprise_notification_time}")
- logger.info(f"Update preferences debug - has_apprise_notification_time_col: {has_apprise_notification_time_col}")
- logger.info(f"Update preferences debug - existing_cols: {existing_cols}")
-
- cursor.execute(
- "SELECT 1 FROM user_preferences WHERE user_id = %s",
- (user_id,)
- )
- preferences_exist = cursor.fetchone() is not None
-
- if preferences_exist:
- update_fields = []
- update_values = []
- if notification_channel and has_notification_channel_col:
- update_fields.append("notification_channel = %s")
- update_values.append(notification_channel)
- if default_view:
- update_fields.append("default_view = %s")
- update_values.append(default_view)
- if theme:
- update_fields.append("theme = %s")
- update_values.append(theme)
- if expiring_soon_days is not None:
- update_fields.append("expiring_soon_days = %s")
- update_values.append(expiring_soon_days)
- if notification_frequency:
- update_fields.append("notification_frequency = %s")
- update_values.append(notification_frequency)
- if notification_time:
- update_fields.append("notification_time = %s")
- update_values.append(notification_time)
- if apprise_notification_time is not None and has_apprise_notification_time_col:
- update_fields.append("apprise_notification_time = %s")
- update_values.append(apprise_notification_time)
- if apprise_notification_frequency is not None and has_apprise_notification_frequency_col:
- update_fields.append("apprise_notification_frequency = %s")
- update_values.append(apprise_notification_frequency)
- if timezone:
- update_fields.append("timezone = %s")
- update_values.append(timezone)
- if apprise_timezone and 'apprise_timezone' in existing_cols:
- update_fields.append("apprise_timezone = %s")
- update_values.append(apprise_timezone)
- if has_currency and currency_symbol is not None:
- update_fields.append("currency_symbol = %s")
- update_values.append(currency_symbol)
- # Add date_format to update only if the column exists
- if has_date_format_col and date_format:
- update_fields.append("date_format = %s")
- update_values.append(date_format)
-
- if update_fields:
- # Build the returning fields string dynamically based on existing columns
- # IMPORTANT: Always SELECT all fields, don't rely on UPDATE RETURNING subset
- return_fields_list = ["email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
- if has_notification_channel_col:
- return_fields_list.append("notification_channel")
- if has_apprise_notification_time_col:
- return_fields_list.append("apprise_notification_time")
- if has_apprise_notification_frequency_col:
- return_fields_list.append("apprise_notification_frequency")
- if 'apprise_timezone' in existing_cols:
- return_fields_list.append("apprise_timezone")
- if has_currency:
- return_fields_list.append("currency_symbol")
- if has_date_format_col:
- return_fields_list.append("date_format")
- return_fields = ", ".join(return_fields_list)
-
- # First do the UPDATE
- update_query = f"""
- UPDATE user_preferences
- SET {', '.join(update_fields)}
- WHERE user_id = %s
- """
- cursor.execute(update_query, update_values + [user_id])
-
- # Then SELECT all fields to get complete data
- cursor.execute(
- f"""
- SELECT {return_fields}
- FROM user_preferences
- WHERE user_id = %s
- """,
- (user_id,)
- )
- preferences_data = cursor.fetchone()
- else:
- # If no fields to update, select existing data
- select_fields_list = ["email_notifications", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
- if has_notification_channel_col:
- select_fields_list.append("notification_channel")
- if has_apprise_notification_time_col:
- select_fields_list.append("apprise_notification_time")
- if has_apprise_notification_frequency_col:
- select_fields_list.append("apprise_notification_frequency")
- if 'apprise_timezone' in existing_cols:
- select_fields_list.append("apprise_timezone")
- if has_currency:
- select_fields_list.append("currency_symbol")
- if has_date_format_col:
- select_fields_list.append("date_format")
- select_fields = ", ".join(select_fields_list)
-
- cursor.execute(
- f"""
- SELECT {select_fields}
- FROM user_preferences
- WHERE user_id = %s
- """,
- (user_id,)
- )
- preferences_data = cursor.fetchone()
- else: # Insert new record
- # Build insert dynamically
- insert_cols_list = ["user_id", "default_view", "theme", "expiring_soon_days", "notification_frequency", "notification_time", "timezone"]
- insert_vals = [
- user_id,
- default_view or 'grid',
- theme or 'light',
- expiring_soon_days if expiring_soon_days is not None else 30,
- notification_frequency or 'daily',
- notification_time or '09:00',
- timezone or 'UTC'
- ]
- if has_notification_channel_col:
- insert_cols_list.append("notification_channel")
- insert_vals.append(notification_channel or 'email')
- if has_apprise_notification_time_col:
- insert_cols_list.append("apprise_notification_time")
- insert_vals.append(apprise_notification_time or '09:00')
- if has_apprise_notification_frequency_col:
- insert_cols_list.append("apprise_notification_frequency")
- insert_vals.append(apprise_notification_frequency or 'daily')
- if has_currency:
- insert_cols_list.append("currency_symbol")
- insert_vals.append(currency_symbol or '$')
- if has_date_format_col:
- insert_cols_list.append("date_format")
- insert_vals.append(date_format or 'MDY')
-
- insert_cols = ", ".join(insert_cols_list)
- insert_vals_placeholders = ", ".join(["%s"] * len(insert_cols_list))
- return_fields = insert_cols # Return the same columns we inserted
-
- cursor.execute(
- f"""
- INSERT INTO user_preferences ({insert_cols})
- VALUES ({insert_vals_placeholders})
- RETURNING {return_fields}
- """,
- tuple(insert_vals)
- )
- preferences_data = cursor.fetchone()
-
- # Map returned data to dictionary using the dynamically determined fields
- returned_columns = [col.strip() for col in return_fields.split(',')]
- if preferences_data:
- pref_map = {col: i for i, col in enumerate(returned_columns)}
-
- # Log debug info for theme issues
- logger.info(f"Update preferences debug - returned_columns: {returned_columns}")
- logger.info(f"Update preferences debug - pref_map: {pref_map}")
- logger.info(f"Update preferences debug - preferences_data: {preferences_data}")
- logger.info(f"Update preferences debug - theme column index: {pref_map.get('theme', 'NOT_FOUND')}")
-
- preferences = {
- 'email_notifications': preferences_data[pref_map['email_notifications']] if 'email_notifications' in pref_map else True,
- 'default_view': preferences_data[pref_map['default_view']] if 'default_view' in pref_map else 'grid',
- 'theme': preferences_data[pref_map['theme']] if 'theme' in pref_map else 'light',
- 'expiring_soon_days': preferences_data[pref_map['expiring_soon_days']] if 'expiring_soon_days' in pref_map else 30,
- 'notification_frequency': preferences_data[pref_map['notification_frequency']] if 'notification_frequency' in pref_map else 'daily',
- 'notification_time': preferences_data[pref_map['notification_time']] if 'notification_time' in pref_map else '09:00',
- 'timezone': preferences_data[pref_map['timezone']] if 'timezone' in pref_map else 'UTC',
- 'notification_channel': preferences_data[pref_map['notification_channel']] if 'notification_channel' in pref_map else 'email',
- 'apprise_notification_time': preferences_data[pref_map['apprise_notification_time']] if 'apprise_notification_time' in pref_map else '09:00',
- 'apprise_notification_frequency': preferences_data[pref_map['apprise_notification_frequency']] if 'apprise_notification_frequency' in pref_map else 'daily',
- 'apprise_timezone': preferences_data[pref_map['apprise_timezone']] if 'apprise_timezone' in pref_map else 'UTC',
- 'currency_symbol': preferences_data[pref_map['currency_symbol']] if 'currency_symbol' in pref_map else '$',
- 'date_format': preferences_data[pref_map['date_format']] if 'date_format' in pref_map else 'MDY'
- }
-
- logger.info(f"Update preferences debug - final theme value: {preferences.get('theme')}")
- else:
- # Fallback if no data returned
- preferences = {}
-
-
- conn.commit()
- return jsonify(preferences), 200
- except Exception as e:
- conn.rollback()
- logger.error(f"Database error in update_preferences: {str(e)}")
- fallback_preferences = {
- 'email_notifications': True, # Fixed: Set default value instead of undefined variable
- 'default_view': default_view or 'grid',
- 'theme': theme or 'light',
- 'expiring_soon_days': expiring_soon_days if expiring_soon_days is not None else 30,
- 'notification_frequency': notification_frequency or 'daily',
- 'notification_time': notification_time or '09:00',
- 'timezone': timezone or 'UTC',
- 'currency_symbol': currency_symbol or '$',
- 'date_format': date_format or 'MDY' # Add to fallback
- }
- return jsonify(fallback_preferences), 200
- finally:
- cursor.close()
- release_db_connection(conn)
- except Exception as e:
- logger.error(f"Error in update_preferences: {str(e)}")
- default_preferences = {
- 'email_notifications': True,
- 'default_view': 'grid',
- 'theme': 'light',
- 'expiring_soon_days': 30,
- 'notification_frequency': 'daily',
- 'notification_time': '09:00',
- 'timezone': 'UTC',
- 'currency_symbol': '$',
- 'date_format': 'MDY' # Fixed: Added missing date_format to defaults
- }
- return jsonify(default_preferences), 200
-
# Admin User Management Endpoints
@app.route('/api/admin/users', methods=['GET'])
@@ -3013,17 +1563,37 @@ def get_all_users():
try:
conn = get_db_connection()
with conn.cursor() as cur:
- cur.execute('''
- SELECT id, username, email, first_name, last_name, is_active, is_admin, created_at, last_login
- FROM users
- ORDER BY created_at DESC
- ''')
- users = cur.fetchall()
+ # Try to get users with is_owner column, fall back to without it if column doesn't exist
+ try:
+ cur.execute('''
+ SELECT id, username, email, first_name, last_name, is_active, is_admin, is_owner, created_at, last_login
+ FROM users
+ ORDER BY created_at DESC
+ ''')
+ users = cur.fetchall()
+ has_owner_column = True
+ except Exception as e:
+ # If the query fails (likely because is_owner column doesn't exist), rollback and try again
+ logger.warning(f"Failed to query with is_owner column in get_all_users, falling back: {e}")
+ conn.rollback() # Rollback the failed transaction
+ cur.execute('''
+ SELECT id, username, email, first_name, last_name, is_active, is_admin, created_at, last_login
+ FROM users
+ ORDER BY created_at DESC
+ ''')
+ users = cur.fetchall()
+ has_owner_column = False
+
columns = [desc[0] for desc in cur.description]
users_list = []
for row in users:
user_dict = dict(zip(columns, row))
+
+ # Add is_owner field if it wasn't included in the query
+ if not has_owner_column:
+ user_dict['is_owner'] = False
+
# Convert date objects to ISO format strings for JSON serialization
for key, value in user_dict.items():
if isinstance(value, (datetime, date)):
@@ -3054,13 +1624,30 @@ def update_user(user_id):
# Use regular connection since db_user now has superuser privileges
conn = get_db_connection()
with conn.cursor() as cur:
- # Check if user exists
- cur.execute('SELECT id FROM users WHERE id = %s', (user_id,))
- user = cur.fetchone()
+ # Check if user exists and if they are the owner
+ try:
+ cur.execute('SELECT id, is_owner FROM users WHERE id = %s', (user_id,))
+ user = cur.fetchone()
+ is_owner = user[1] if user and len(user) > 1 else False
+ except Exception as e:
+ # If the query fails (likely because is_owner column doesn't exist), rollback and try again
+ logger.warning(f"Failed to query with is_owner column in update_user, falling back: {e}")
+ conn.rollback() # Rollback the failed transaction
+ cur.execute('SELECT id FROM users WHERE id = %s', (user_id,))
+ user = cur.fetchone()
+ is_owner = False
if not user:
return jsonify({"message": "User not found"}), 404
+ # Check if the user being updated is the owner
+ if is_owner:
+ # If the user is the owner, prevent demotion or deactivation
+ if 'is_admin' in data and data['is_admin'] is False:
+ return jsonify({"message": "The application owner cannot be demoted from admin status."}), 403
+ if 'is_active' in data and data['is_active'] is False:
+ return jsonify({"message": "The application owner's account cannot be deactivated."}), 403
+
# Update fields
updates = []
params = []
@@ -3109,14 +1696,28 @@ def delete_user(user_id):
# Use regular connection since db_user now has superuser privileges
conn = get_db_connection()
with conn.cursor() as cur:
- # Check if user exists
- cur.execute('SELECT id, username FROM users WHERE id = %s', (user_id,))
- user = cur.fetchone()
+ # Check if user exists and if they are the owner
+ try:
+ cur.execute('SELECT id, username, is_owner FROM users WHERE id = %s', (user_id,))
+ user = cur.fetchone()
+ is_owner = user[2] if user and len(user) > 2 else False
+ except Exception as e:
+ # If the query fails (likely because is_owner column doesn't exist), rollback and try again
+ logger.warning(f"Failed to query with is_owner column in delete_user, falling back: {e}")
+ conn.rollback() # Rollback the failed transaction
+ cur.execute('SELECT id, username FROM users WHERE id = %s', (user_id,))
+ user = cur.fetchone()
+ is_owner = False
if not user:
logger.warning(f"User with ID {user_id} not found")
return jsonify({"message": "User not found"}), 404
+ # Check if the user to be deleted is the owner
+ if is_owner:
+ logger.warning(f"Admin {request.user['id']} attempted to delete the application owner (user_id: {user_id})")
+ return jsonify({"message": "The application owner cannot be deleted."}), 403
+
logger.info(f"Deleting user {user[1]} (ID: {user[0]})")
# Delete user's warranties first
@@ -3157,6 +1758,70 @@ def delete_user(user_id):
if conn:
release_db_connection(conn)
[email protected]('/api/admin/transfer-ownership', methods=['POST'])
+@admin_required
+def transfer_ownership():
+ """Transfer application ownership to another admin user (owner only)"""
+ # 1. Security Check: Only the current owner can initiate a transfer.
+ # If is_owner column doesn't exist yet, this feature is not available
+ if not request.user.get('is_owner'):
+ return jsonify({"message": "Ownership transfer feature is not available. Please run the database migration first."}), 403
+
+ data = request.get_json()
+ new_owner_id = data.get('new_owner_id')
+ current_owner_id = request.user['id']
+
+ if not new_owner_id:
+ return jsonify({"message": "New owner ID is required."}), 400
+
+ if int(new_owner_id) == current_owner_id:
+ return jsonify({"message": "Cannot transfer ownership to yourself."}), 400
+
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # 2. Validate the new owner
+ cur.execute("SELECT id, is_admin, is_active FROM users WHERE id = %s", (new_owner_id,))
+ new_owner = cur.fetchone()
+
+ if not new_owner:
+ return jsonify({"message": "The selected user does not exist."}), 404
+
+ if not new_owner[1]: # is_admin is false
+ return jsonify({"message": "Ownership can only be transferred to another admin user."}), 400
+
+ if not new_owner[2]: # is_active is false
+ return jsonify({"message": "Cannot transfer ownership to an inactive user."}), 400
+
+ # 3. Perform the transfer within a database transaction
+ # This ensures both updates succeed or both fail.
+ logger.info(f"Ownership transfer initiated by user {current_owner_id} to user {new_owner_id}.")
+
+ # Demote current owner to a regular admin
+ try:
+ cur.execute("UPDATE users SET is_owner = FALSE WHERE id = %s", (current_owner_id,))
+
+ # Promote the new user to be the owner (and ensure they remain admin)
+ cur.execute("UPDATE users SET is_owner = TRUE, is_admin = TRUE WHERE id = %s", (new_owner_id,))
+ except Exception as e:
+ logger.error(f"Error updating ownership in database: {e}")
+ return jsonify({"message": "Ownership transfer feature is not available. Please run the database migration first."}), 500
+
+ conn.commit()
+
+ logger.info(f"Ownership successfully transferred from {current_owner_id} to {new_owner_id}.")
+ return jsonify({"message": "Ownership transferred successfully."}), 200
+
+ except Exception as e:
+ if conn:
+ conn.rollback()
+ logger.error(f"Error during ownership transfer: {e}")
+ return jsonify({"message": "An error occurred during ownership transfer. The operation has been rolled back."}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
# Site settings
@app.route('/api/admin/settings', methods=['GET'])
@admin_required
@@ -3198,6 +1863,7 @@ def get_site_settings():
'global_view_enabled': 'true', # Global warranty view feature
'global_view_admin_only': 'false', # Restrict global view to admins only
'oidc_enabled': 'false',
+ 'oidc_only_mode': 'false', # Force OIDC-only login (hide traditional login form)
'oidc_provider_name': 'oidc',
'oidc_client_id': '',
# 'oidc_client_secret': '', # Not returned
@@ -3221,7 +1887,7 @@ def get_site_settings():
continue
# For boolean-like string settings, ensure they are 'true' or 'false'
- if key in ['registration_enabled', 'oidc_enabled', 'apprise_enabled', 'global_view_enabled', 'global_view_admin_only']:
+ if key in ['registration_enabled', 'oidc_enabled', 'oidc_only_mode', 'apprise_enabled', 'global_view_enabled', 'global_view_admin_only']:
settings_to_return[key] = 'true' if value.lower() == 'true' else 'false'
else:
settings_to_return[key] = value
@@ -3285,7 +1951,7 @@ def update_site_settings():
requires_restart = False
for key, value in data.items():
# Sanitize boolean-like string values
- if key in ['registration_enabled', 'oidc_enabled', 'global_view_enabled', 'global_view_admin_only']:
+ if key in ['registration_enabled', 'oidc_enabled', 'oidc_only_mode', 'global_view_enabled', 'global_view_admin_only']:
value = 'true' if str(value).lower() == 'true' else 'false'
# Check if it's an OIDC related key that requires restart
@@ -3363,64 +2029,26 @@ def check_global_view_status():
# Get both global view settings
cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")
- settings = {row[0]: row[1] for row in cur.fetchall()}
-
- # Check if global view is enabled at all
- global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'
- if not global_view_enabled:
- return jsonify({"enabled": False}), 200
-
- # Check if global view is restricted to admins only
- admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'
- if admin_only and not user_is_admin:
- return jsonify({"enabled": False}), 200
-
- # Global view is enabled for this user
- return jsonify({"enabled": True}), 200
-
- except Exception as e:
- logger.error(f"Error checking global view status: {e}")
- # Default to enabled on error for admins, disabled for non-admins
- user_is_admin = request.user.get('is_admin', False)
- return jsonify({"enabled": user_is_admin}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/auth/registration-status', methods=['GET'])
-def check_registration_status():
- """Check if registration is enabled"""
- conn = None
- try:
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if settings table exists
- cur.execute("""
- SELECT EXISTS (
- SELECT FROM information_schema.tables
- WHERE table_name = 'site_settings'
- )
- """)
- table_exists = cur.fetchone()[0]
-
- if not table_exists:
- # If table doesn't exist, registration is enabled by default
- return jsonify({"enabled": True}), 200
+ settings = {row[0]: row[1] for row in cur.fetchall()}
- # Get registration_enabled setting
- cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")
- result = cur.fetchone()
+ # Check if global view is enabled at all
+ global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'
+ if not global_view_enabled:
+ return jsonify({"enabled": False}), 200
- if not result:
- # If setting doesn't exist, registration is enabled by default
- return jsonify({"enabled": True}), 200
+ # Check if global view is restricted to admins only
+ admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'
+ if admin_only and not user_is_admin:
+ return jsonify({"enabled": False}), 200
- registration_enabled = result[0].lower() == 'true'
+ # Global view is enabled for this user
+ return jsonify({"enabled": True}), 200
- return jsonify({"enabled": registration_enabled}), 200
except Exception as e:
- logger.error(f"Error checking registration status: {e}")
- return jsonify({"enabled": True}), 200 # Default to enabled on error
+ logger.error(f"Error checking global view status: {e}")
+ # Default to enabled on error for admins, disabled for non-admins
+ user_is_admin = request.user.get('is_admin', False)
+ return jsonify({"enabled": user_is_admin}), 500
finally:
if conn:
release_db_connection(conn)
@@ -3478,6 +2106,7 @@ def secure_file_access(filename):
authorized = is_admin
logger.info(f"[SECURE_FILE] Initial authorization (is_admin={is_admin}): {authorized}")
+ # Check for ownership authorization
if not authorized and results:
for warranty_id_db, warranty_user_id_db in results:
logger.info(f"[SECURE_FILE] Checking ownership: warranty_id={warranty_id_db}, owner_id={warranty_user_id_db}, current_user_id={user_id}")
@@ -3485,6 +2114,38 @@ def secure_file_access(filename):
authorized = True
logger.info(f"[SECURE_FILE] Ownership confirmed for warranty_id={warranty_id_db}")
break
+
+ # Check for global view authorization for product photos
+ if not authorized and results:
+ # Check if this file is a product photo by looking at which column matched
+ cur.execute("""
+ SELECT w.id, w.user_id
+ FROM warranties w
+ WHERE w.product_photo_path = %s
+ """, (db_search_path,))
+ photo_results = cur.fetchall()
+
+ if photo_results:
+ logger.info(f"[SECURE_FILE] File is a product photo, checking global view permissions")
+
+ # Get global view settings
+ cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+
+ # Check if global view is enabled at all
+ global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'
+ logger.info(f"[SECURE_FILE] Global view enabled: {global_view_enabled}")
+
+ if global_view_enabled:
+ # Check if global view is restricted to admins only
+ admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'
+ logger.info(f"[SECURE_FILE] Global view admin only: {admin_only}")
+
+ if not admin_only or is_admin:
+ authorized = True
+ logger.info(f"[SECURE_FILE] Global view photo access authorized for user {user_id}")
+ else:
+ logger.info(f"[SECURE_FILE] Global view restricted to admins only, user {user_id} is not admin")
if not authorized:
logger.warning(f"[SECURE_FILE] Unauthorized file access attempt: '{filename}' (repr: {repr(filename)}) by user {user_id}. DB results count: {len(results) if results else 'None'}")
@@ -3745,6 +2406,13 @@ if __name__ == '__main__':
except Exception as e:
logger.error(f"Database initialization error during startup: {e}")
+# Always ensure owner exists regardless of how the app is started (dev vs production)
+try:
+ logger.info("Ensuring application owner exists on startup...")
+ ensure_owner_exists()
+except Exception as e:
+ logger.error(f"Error ensuring owner exists during startup: {e}")
+
@app.route('/api/admin/send-notifications', methods=['POST'])
@admin_required
def trigger_notifications():
@@ -3821,6 +2489,202 @@ def get_timezones():
logger.error(f"Error getting timezones: {e}")
return jsonify({'message': 'Failed to get timezones'}), 500
[email protected]('/api/currencies', methods=['GET'])
+def get_currencies():
+ """Get list of available currencies with their symbols"""
+ try:
+ currencies = [
+ {'code': 'USD', 'name': 'US Dollar', 'symbol': '$'},
+ {'code': 'EUR', 'name': 'Euro', 'symbol': '€'},
+ {'code': 'GBP', 'name': 'British Pound', 'symbol': '£'},
+ {'code': 'JPY', 'name': 'Japanese Yen', 'symbol': '¥'},
+ {'code': 'CNY', 'name': 'Chinese Yuan', 'symbol': '¥'},
+ {'code': 'INR', 'name': 'Indian Rupee', 'symbol': '₹'},
+ {'code': 'KRW', 'name': 'South Korean Won', 'symbol': '₩'},
+ {'code': 'CHF', 'name': 'Swiss Franc', 'symbol': 'CHF'},
+ {'code': 'CAD', 'name': 'Canadian Dollar', 'symbol': 'C$'},
+ {'code': 'AUD', 'name': 'Australian Dollar', 'symbol': 'A$'},
+ {'code': 'SEK', 'name': 'Swedish Krona', 'symbol': 'kr'},
+ {'code': 'NOK', 'name': 'Norwegian Krone', 'symbol': 'kr'},
+ {'code': 'DKK', 'name': 'Danish Krone', 'symbol': 'kr'},
+ {'code': 'PLN', 'name': 'Polish Złoty', 'symbol': 'zł'},
+ {'code': 'CZK', 'name': 'Czech Koruna', 'symbol': 'Kč'},
+ {'code': 'HUF', 'name': 'Hungarian Forint', 'symbol': 'Ft'},
+ {'code': 'BGN', 'name': 'Bulgarian Lev', 'symbol': 'лв'},
+ {'code': 'RON', 'name': 'Romanian Leu', 'symbol': 'lei'},
+ {'code': 'HRK', 'name': 'Croatian Kuna', 'symbol': 'kn'},
+ {'code': 'RUB', 'name': 'Russian Ruble', 'symbol': '₽'},
+ {'code': 'BRL', 'name': 'Brazilian Real', 'symbol': 'R$'},
+ {'code': 'MXN', 'name': 'Mexican Peso', 'symbol': '$'},
+ {'code': 'ARS', 'name': 'Argentine Peso', 'symbol': '$'},
+ {'code': 'CLP', 'name': 'Chilean Peso', 'symbol': '$'},
+ {'code': 'COP', 'name': 'Colombian Peso', 'symbol': '$'},
+ {'code': 'PEN', 'name': 'Peruvian Sol', 'symbol': 'S/'},
+ {'code': 'VES', 'name': 'Venezuelan Bolívar', 'symbol': 'Bs'},
+ {'code': 'ZAR', 'name': 'South African Rand', 'symbol': 'R'},
+ {'code': 'EGP', 'name': 'Egyptian Pound', 'symbol': '£'},
+ {'code': 'NGN', 'name': 'Nigerian Naira', 'symbol': '₦'},
+ {'code': 'KES', 'name': 'Kenyan Shilling', 'symbol': 'KSh'},
+ {'code': 'GHS', 'name': 'Ghanaian Cedi', 'symbol': '₵'},
+ {'code': 'MAD', 'name': 'Moroccan Dirham', 'symbol': 'DH'},
+ {'code': 'TND', 'name': 'Tunisian Dinar', 'symbol': 'DT'},
+ {'code': 'AED', 'name': 'UAE Dirham', 'symbol': 'AED'},
+ {'code': 'SAR', 'name': 'Saudi Riyal', 'symbol': 'SR'},
+ {'code': 'QAR', 'name': 'Qatari Riyal', 'symbol': 'QR'},
+ {'code': 'KWD', 'name': 'Kuwaiti Dinar', 'symbol': 'KD'},
+ {'code': 'BHD', 'name': 'Bahraini Dinar', 'symbol': 'BD'},
+ {'code': 'OMR', 'name': 'Omani Rial', 'symbol': 'OR'},
+ {'code': 'JOD', 'name': 'Jordanian Dinar', 'symbol': 'JD'},
+ {'code': 'LBP', 'name': 'Lebanese Pound', 'symbol': 'LL'},
+ {'code': 'ILS', 'name': 'Israeli Shekel', 'symbol': '₪'},
+ {'code': 'TRY', 'name': 'Turkish Lira', 'symbol': '₺'},
+ {'code': 'IRR', 'name': 'Iranian Rial', 'symbol': '﷼'},
+ {'code': 'PKR', 'name': 'Pakistani Rupee', 'symbol': '₨'},
+ {'code': 'BDT', 'name': 'Bangladeshi Taka', 'symbol': '৳'},
+ {'code': 'LKR', 'name': 'Sri Lankan Rupee', 'symbol': 'Rs'},
+ {'code': 'NPR', 'name': 'Nepalese Rupee', 'symbol': 'Rs'},
+ {'code': 'BTN', 'name': 'Bhutanese Ngultrum', 'symbol': 'Nu'},
+ {'code': 'MMK', 'name': 'Myanmar Kyat', 'symbol': 'K'},
+ {'code': 'THB', 'name': 'Thai Baht', 'symbol': '฿'},
+ {'code': 'VND', 'name': 'Vietnamese Dong', 'symbol': '₫'},
+ {'code': 'LAK', 'name': 'Lao Kip', 'symbol': '₭'},
+ {'code': 'KHR', 'name': 'Cambodian Riel', 'symbol': '៛'},
+ {'code': 'MYR', 'name': 'Malaysian Ringgit', 'symbol': 'RM'},
+ {'code': 'SGD', 'name': 'Singapore Dollar', 'symbol': 'S$'},
+ {'code': 'IDR', 'name': 'Indonesian Rupiah', 'symbol': 'Rp'},
+ {'code': 'PHP', 'name': 'Philippine Peso', 'symbol': '₱'},
+ {'code': 'TWD', 'name': 'Taiwan Dollar', 'symbol': 'NT$'},
+ {'code': 'HKD', 'name': 'Hong Kong Dollar', 'symbol': 'HK$'},
+ {'code': 'MOP', 'name': 'Macanese Pataca', 'symbol': 'MOP'},
+ {'code': 'KPW', 'name': 'North Korean Won', 'symbol': '₩'},
+ {'code': 'MNT', 'name': 'Mongolian Tugrik', 'symbol': '₮'},
+ {'code': 'KZT', 'name': 'Kazakhstani Tenge', 'symbol': '₸'},
+ {'code': 'UZS', 'name': 'Uzbekistani Som', 'symbol': 'soʻm'},
+ {'code': 'TJS', 'name': 'Tajikistani Somoni', 'symbol': 'SM'},
+ {'code': 'KGS', 'name': 'Kyrgyzstani Som', 'symbol': 'с'},
+ {'code': 'TMT', 'name': 'Turkmenistani Manat', 'symbol': 'T'},
+ {'code': 'AFN', 'name': 'Afghan Afghani', 'symbol': '؋'},
+ {'code': 'AMD', 'name': 'Armenian Dram', 'symbol': '֏'},
+ {'code': 'AZN', 'name': 'Azerbaijani Manat', 'symbol': '₼'},
+ {'code': 'GEL', 'name': 'Georgian Lari', 'symbol': '₾'},
+ {'code': 'MDL', 'name': 'Moldovan Leu', 'symbol': 'L'},
+ {'code': 'UAH', 'name': 'Ukrainian Hryvnia', 'symbol': '₴'},
+ {'code': 'BYN', 'name': 'Belarusian Ruble', 'symbol': 'Br'},
+ {'code': 'RSD', 'name': 'Serbian Dinar', 'symbol': 'дин'},
+ {'code': 'MKD', 'name': 'Macedonian Denar', 'symbol': 'ден'},
+ {'code': 'ALL', 'name': 'Albanian Lek', 'symbol': 'L'},
+ {'code': 'BAM', 'name': 'Bosnia-Herzegovina Mark', 'symbol': 'KM'},
+ {'code': 'ISK', 'name': 'Icelandic Króna', 'symbol': 'kr'},
+ {'code': 'FJD', 'name': 'Fijian Dollar', 'symbol': 'FJ$'},
+ {'code': 'PGK', 'name': 'Papua New Guinea Kina', 'symbol': 'K'},
+ {'code': 'SBD', 'name': 'Solomon Islands Dollar', 'symbol': 'SI$'},
+ {'code': 'TOP', 'name': 'Tongan Paʻanga', 'symbol': 'T$'},
+ {'code': 'VUV', 'name': 'Vanuatu Vatu', 'symbol': 'VT'},
+ {'code': 'WST', 'name': 'Samoan Tala', 'symbol': 'WS$'},
+ {'code': 'XPF', 'name': 'CFP Franc', 'symbol': '₣'},
+ {'code': 'NZD', 'name': 'New Zealand Dollar', 'symbol': 'NZ$'}
+ ]
+
+ return jsonify(currencies)
+
+ except Exception as e:
+ logger.error(f"Error getting currencies: {e}")
+ return jsonify([{'code': 'USD', 'name': 'US Dollar', 'symbol': '$'}]), 500
+
[email protected]('/api/debug/export', methods=['GET'])
+@token_required
+def debug_export():
+ """Debug endpoint to help troubleshoot export issues"""
+ conn = None
+ try:
+ user_id = request.user['id']
+ is_admin = request.user.get('is_admin', False)
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Get basic warranty count
+ cur.execute('SELECT COUNT(*) FROM warranties WHERE user_id = %s', (user_id,))
+ personal_count = cur.fetchone()[0]
+
+ # Get all warranty IDs for this user
+ cur.execute('SELECT id, product_name, is_lifetime, expiration_date FROM warranties WHERE user_id = %s ORDER BY id', (user_id,))
+ personal_warranties = cur.fetchall()
+
+ # Get global count if admin
+ global_count = 0
+ global_warranties = []
+ if is_admin:
+ cur.execute('SELECT COUNT(*) FROM warranties')
+ global_count = cur.fetchone()[0]
+
+ cur.execute('SELECT id, product_name, is_lifetime, expiration_date, user_id FROM warranties ORDER BY id')
+ global_warranties = cur.fetchall()
+
+ # Get tag associations
+ cur.execute('''
+ SELECT w.id, t.id as tag_id, t.name as tag_name
+ FROM warranties w
+ LEFT JOIN warranty_tags wt ON w.id = wt.warranty_id
+ LEFT JOIN tags t ON wt.tag_id = t.id
+ WHERE w.user_id = %s
+ ORDER BY w.id, t.name
+ ''', (user_id,))
+ tag_associations = cur.fetchall()
+
+ # Get serial number associations
+ cur.execute('''
+ SELECT w.id, sn.serial_number
+ FROM warranties w
+ LEFT JOIN serial_numbers sn ON w.id = sn.warranty_id
+ WHERE w.user_id = %s
+ ORDER BY w.id
+ ''', (user_id,))
+ serial_associations = cur.fetchall()
+
+ return jsonify({
+ 'user_id': user_id,
+ 'is_admin': is_admin,
+ 'personal_warranty_count': personal_count,
+ 'global_warranty_count': global_count,
+ 'personal_warranties': [
+ {
+ 'id': w[0],
+ 'product_name': w[1],
+ 'is_lifetime': w[2],
+ 'expiration_date': w[3].isoformat() if w[3] else None
+ } for w in personal_warranties
+ ],
+ 'global_warranties': [
+ {
+ 'id': w[0],
+ 'product_name': w[1],
+ 'is_lifetime': w[2],
+ 'expiration_date': w[3].isoformat() if w[3] else None,
+ 'user_id': w[4]
+ } for w in global_warranties
+ ] if is_admin else [],
+ 'tag_associations': [
+ {
+ 'warranty_id': t[0],
+ 'tag_id': t[1],
+ 'tag_name': t[2]
+ } for t in tag_associations if t[1] is not None
+ ],
+ 'serial_associations': [
+ {
+ 'warranty_id': s[0],
+ 'serial_number': s[1]
+ } for s in serial_associations if s[1] is not None
+ ]
+ })
+
+ except Exception as e:
+ logger.error(f"Error in debug export endpoint: {e}")
+ return jsonify({"error": f"Debug failed: {str(e)}"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
@app.route('/api/debug/warranty/<int:warranty_id>', methods=['GET'])
@token_required
def debug_warranty(warranty_id):
@@ -4462,19 +3326,52 @@ def import_warranties():
failed_rows.append({"row": row_number, "errors": errors})
continue
+ # --- Get user's preferred currency code ---
+ user_currency_code = 'USD' # Default fallback
+ try:
+ # Get user's preferred currency symbol from their preferences
+ cur.execute("""
+ SELECT currency_symbol FROM user_preferences
+ WHERE user_id = %s
+ """, (user_id,))
+ currency_result = cur.fetchone()
+
+ if currency_result and currency_result[0]:
+ user_symbol = currency_result[0]
+ # Map common currency symbols to currency codes (same as frontend logic)
+ symbol_to_currency_map = {
+ '$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'JPY', '₹': 'INR', '₩': 'KRW',
+ 'CHF': 'CHF', 'C$': 'CAD', 'A$': 'AUD', 'kr': 'SEK', 'zł': 'PLN',
+ 'Kč': 'CZK', 'Ft': 'HUF', '₽': 'RUB', 'R$': 'BRL', '₦': 'NGN',
+ '₪': 'ILS', '₺': 'TRY', '₨': 'PKR', '৳': 'BDT', '฿': 'THB',
+ '₫': 'VND', 'RM': 'MYR', 'S$': 'SGD', 'Rp': 'IDR', '₱': 'PHP',
+ 'NT$': 'TWD', 'HK$': 'HKD', '₮': 'MNT', '₸': 'KZT', '₼': 'AZN',
+ '₾': 'GEL', '₴': 'UAH', 'NZ$': 'NZD'
+ }
+
+ if user_symbol in symbol_to_currency_map:
+ user_currency_code = symbol_to_currency_map[user_symbol]
+ logger.info(f"[Import] Using user's preferred currency: {user_symbol} -> {user_currency_code} for user {user_id}")
+ else:
+ logger.info(f"[Import] Unknown currency symbol '{user_symbol}' for user {user_id}, defaulting to USD")
+ else:
+ logger.info(f"[Import] No currency preference found for user {user_id}, defaulting to USD")
+ except Exception as currency_err:
+ logger.error(f"[Import] Error getting user currency preference: {currency_err}, defaulting to USD")
+
# --- Insert into Database ---
cur.execute("""
INSERT INTO warranties (
product_name, purchase_date, expiration_date,
product_url, purchase_price, user_id, is_lifetime, vendor, warranty_type,
- warranty_duration_years, warranty_duration_months, warranty_duration_days
+ warranty_duration_years, warranty_duration_months, warranty_duration_days, currency
)
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""", (
product_name, purchase_date, expiration_date,
product_url, purchase_price, user_id, is_lifetime, vendor, warranty_type,
- warranty_duration_years, warranty_duration_months, warranty_duration_days
+ warranty_duration_years, warranty_duration_months, warranty_duration_days, user_currency_code
))
warranty_id = cur.fetchone()[0]
@@ -4543,416 +3440,40 @@ def import_warranties():
# --- PATCH START: Currency Symbol Support ---
# 1. Add a helper function to check if the currency_symbol column exists in user_preferences
-def has_currency_symbol_column(cursor):
- cursor.execute("""
- SELECT column_name FROM information_schema.columns
- WHERE table_name = 'user_preferences' AND column_name = 'currency_symbol'
- """)
- return cursor.fetchone() is not None
-
-# 2. Update GET /api/auth/preferences
-# - Add currency_symbol to CREATE TABLE, SELECT, INSERT, and response
-# - Default to '$' if not set
-#
-# 3. Update PUT /api/auth/preferences
-# - Accept currency_symbol from request data and update if provided
-# - Add currency_symbol to CREATE TABLE, SELECT, INSERT, UPDATE, and response
-# - Default to '$' if not set
-# --- PATCH END ---
-
[email protected]('/api/auth/password/reset', methods=['POST'])
-def reset_password():
- conn = None
- try:
- data = request.get_json()
-
- if not data.get('token') or not data.get('password'):
- return jsonify({'message': 'Token and password are required!'}), 400
-
- token = data['token']
- password = data['password']
-
- # Validate password strength
- if not is_valid_password(password):
- return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if token exists and is valid
- cur.execute('SELECT user_id, expires_at FROM password_reset_tokens WHERE token = %s', (token,))
- token_info = cur.fetchone()
-
- if not token_info or token_info[1] < datetime.utcnow():
- return jsonify({'message': 'Invalid or expired token!'}), 400
-
- user_id = token_info[0]
-
- # Hash the new password
- password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
-
- # Update user's password
- cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (password_hash, user_id))
-
- # Delete the used token
- cur.execute('DELETE FROM password_reset_tokens WHERE token = %s', (token,))
-
- conn.commit()
-
- return jsonify({'message': 'Password reset successful!'}), 200
- except Exception as e:
- logger.error(f"Password reset error: {e}")
- if conn:
- conn.rollback()
- return jsonify({'message': 'Password reset failed!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
[email protected]('/api/auth/password/change', methods=['POST'])
-@token_required
-def change_password():
- """Allow logged-in users to change their password"""
- conn = None
- try:
- data = request.get_json()
-
- if not data.get('current_password') or not data.get('new_password'):
- return jsonify({'message': 'Current password and new password are required!'}), 400
-
- current_password = data['current_password']
- new_password = data['new_password']
- user_id = request.user['id'] # Get user ID from the token_required decorator
-
- # Validate new password strength
- if not is_valid_password(new_password):
- return jsonify({'message': 'New password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Get the user's current password hash
- cur.execute('SELECT password_hash FROM users WHERE id = %s', (user_id,))
- user_data = cur.fetchone()
-
- if not user_data:
- return jsonify({'message': 'User not found!'}), 404
-
- current_password_hash = user_data[0]
-
- # Verify the current password
- if not bcrypt.check_password_hash(current_password_hash, current_password):
- return jsonify({'message': 'Incorrect current password!'}), 401
-
- # Hash the new password
- new_password_hash = bcrypt.generate_password_hash(new_password).decode('utf-8')
-
- # Update the password in the database
- cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (new_password_hash, user_id))
-
- conn.commit()
-
- return jsonify({'message': 'Password changed successfully!'}), 200
-
- except Exception as e:
- logger.error(f"Password change error: {e}")
- if conn:
- conn.rollback()
- return jsonify({'message': 'Failed to change password!'}), 500
- finally:
- if conn:
- release_db_connection(conn)
-
-def send_email_change_verification_email(recipient_email, verification_link_path_with_token):
- """Sends an email with a link to verify the new email address."""
- try:
- smtp_host = os.environ.get('SMTP_HOST', 'localhost')
- smtp_port = int(os.environ.get('SMTP_PORT', 1025))
- smtp_username = os.environ.get('SMTP_USERNAME')
- smtp_password = os.environ.get('SMTP_PASSWORD')
- smtp_use_tls = os.environ.get('SMTP_USE_TLS', 'true').lower() == 'true'
- smtp_use_ssl = os.environ.get('SMTP_USE_SSL', 'false').lower() == 'true'
- sender_email = os.environ.get('SMTP_SENDER_EMAIL', '[email protected]')
- app_name = "Warracker" # Or get from config
-
- # Explicit SMTP_USE_TLS from environment, defaulting to true if port is 587
- # and not explicitly set to false.
- smtp_use_tls_env = os.environ.get('SMTP_USE_TLS', 'not_set').lower()
-
- subject = f"Confirm Your New Email Address - {app_name}"
-
- app_base_url = os.environ.get('APP_BASE_URL', request.url_root.rstrip('/'))
- full_verification_link = f"{app_base_url}{verification_link_path_with_token}"
-
- html_content = None
- email_template_path = os.path.join(os.path.dirname(__file__), 'templates', 'email_change_verification.html')
- if os.path.exists(email_template_path):
- with open(email_template_path, 'r') as f:
- html_content = f.read()
- html_content = html_content.replace("{{verification_link}}", full_verification_link)
- html_content = html_content.replace("{{app_name}}", app_name)
- html_content = html_content.replace("{{expiration_hours}}", str(EMAIL_CHANGE_TOKEN_EXPIRATION_HOURS))
- else:
- logger.warning(f"Email template not found: {email_template_path}. Using basic HTML fallback.")
- html_content = f""" <html>
- <body>
- <p>Hello,</p>
- <p>Please click the link below to confirm your new email address for {app_name}:</p>
- <p><a href="{full_verification_link}">Confirm Email Change</a></p>
- <p>If you did not request this change, please ignore this email.</p>
- <p>This link will expire in {EMAIL_CHANGE_TOKEN_EXPIRATION_HOURS} hours.</p>
- <p>Thanks,<br>The {app_name} Team</p>
- </body>
- </html>
- """
-
- msg = MIMEMultipart('alternative')
- msg['Subject'] = subject
- msg['From'] = sender_email
- msg['To'] = recipient_email
- msg.attach(MIMEText(html_content, 'html'))
-
- logger.info(f"Attempting to send email change verification to {recipient_email} via {smtp_host}:{smtp_port}")
-
- server = None
- logger.info(f"Attempting SMTP connection to {smtp_host}:{smtp_port}")
- if smtp_port == 465:
- logger.info("Using SMTP_SSL for port 465.")
- server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=10)
- else:
- logger.info(f"Using SMTP for port {smtp_port}.")
- server = smtplib.SMTP(smtp_host, smtp_port, timeout=10)
- # For port 587, STARTTLS is standard.
- # For other ports, allow SMTP_USE_TLS to explicitly enable/disable it.
- # If SMTP_USE_TLS is 'not_set', default to True for port 587.
- should_use_starttls = False
- if smtp_port == 587:
- should_use_starttls = (smtp_use_tls_env != 'false') # True unless explicitly 'false'
- logger.info(f"Port is 587. SMTP_USE_TLS set to '{smtp_use_tls_env}'. should_use_starttls: {should_use_starttls}")
- elif smtp_use_tls_env == 'true':
- should_use_starttls = True
- logger.info(f"Port is {smtp_port}. SMTP_USE_TLS explicitly 'true'. should_use_starttls: {should_use_starttls}")
- else:
- logger.info(f"Port is {smtp_port}. SMTP_USE_TLS set to '{smtp_use_tls_env}'. should_use_starttls: {should_use_starttls}")
-
- if should_use_starttls:
- logger.info("Attempting to start TLS (server.starttls()).")
- server.starttls()
- logger.info("STARTTLS successful.")
- else:
- logger.info("Not using STARTTLS based on port and SMTP_USE_TLS setting.")
-
- if smtp_username and smtp_password:
- logger.info(f"Logging in with username: {smtp_username}")
- server.login(smtp_username, smtp_password)
- logger.info("SMTP login successful.")
-
- server.sendmail(sender_email, recipient_email, msg.as_string())
- server.quit()
- logger.info(f"Email change verification sent successfully to {recipient_email}")
- return True
- except smtplib.SMTPAuthenticationError as e:
- logger.error(f"SMTP Authentication Error sending email change verification: {e}")
- except Exception as e:
- logger.error(f"Error sending email change verification: {e}", exc_info=True)
- return False
-
-def generate_secure_token(length=40):
- """Generates a cryptographically secure random string token."""
- return uuid.uuid4().hex + uuid.uuid4().hex[:length-len(uuid.uuid4().hex)]
-
[email protected]('/api/auth/change-email', methods=['POST'])
-@token_required
-def request_email_change():
- current_user_id = request.user['id'] # Get user ID from decorator
- data = request.get_json()
- new_email = data.get('new_email')
- password = data.get('password')
-
- if not new_email or not password:
- return jsonify({'message': 'New email and password are required'}), 400
-
- if not is_valid_email(new_email):
- return jsonify({'message': 'Invalid new email format'}), 400
-
- conn = None
- try:
- conn = get_db_connection()
- cur = conn.cursor()
-
- # Fetch current user's password hash and current email
- cur.execute("SELECT password_hash, email FROM users WHERE id = %s", (current_user_id,))
- user_data = cur.fetchone()
-
- if not user_data:
- return jsonify({'message': 'User not found'}), 404 # Should not happen with @token_required
-
- current_password_hash, current_email = user_data
-
- if not bcrypt.check_password_hash(current_password_hash, password):
- return jsonify({'message': 'Incorrect password'}), 401
-
- if new_email.lower() == current_email.lower():
- return jsonify({'message': 'New email cannot be the same as the current email'}), 400
-
- # Check if the new email is already in use by another user
- cur.execute("SELECT id FROM users WHERE email = %s AND id != %s", (new_email.lower(), current_user_id))
- if cur.fetchone():
- return jsonify({'message': 'This email address is already in use by another account.'}), 409
-
- # Check for an existing, non-expired, non-used request for this user and new email
- cur.execute("""
- SELECT id, token_expires_at FROM email_change_requests
- WHERE user_id = %s AND new_email = %s AND is_used = FALSE AND token_expires_at > NOW()
- """, (current_user_id, new_email.lower()))
- existing_request = cur.fetchone()
-
- if existing_request:
- # Potentially resend email if requested soon after, or just inform user
- return jsonify({'message': 'An email change request for this address is already pending. Please check your inbox.'}), 409
-
- # Invalidate any older, unused tokens for this user to prevent multiple active links
- cur.execute("UPDATE email_change_requests SET is_used = TRUE, token_expires_at = NOW() WHERE user_id = %s AND is_used = FALSE", (current_user_id,))
-
-
- verification_token = generate_secure_token()
- token_expires_at = datetime.utcnow().replace(tzinfo=pytz.utc) + timedelta(hours=EMAIL_CHANGE_TOKEN_EXPIRATION_HOURS)
-
- # Get app base URL from environment or config
- app_base_url = os.environ.get('APP_BASE_URL', request.url_root.rstrip('/'))
- verification_link = f"{app_base_url}{EMAIL_CHANGE_VERIFICATION_ENDPOINT}?token={verification_token}"
-
- cur.execute("""
- INSERT INTO email_change_requests (user_id, new_email, verification_token, token_expires_at)
- VALUES (%s, %s, %s, %s)
- """, (current_user_id, new_email.lower(), verification_token, token_expires_at))
-
- conn.commit()
-
- if send_email_change_verification_email(new_email, verification_link):
- return jsonify({'message': f'Verification email sent to {new_email}. Please check your inbox to confirm.'}), 200
- else:
- # Rollback if email sending failed, to allow user to try again
- # Or, consider if the request should remain, and user can request resend.
- # For now, simple rollback.
- conn.rollback()
- return jsonify({'message': 'Failed to send verification email. Please try again later.'}), 500
-
- except psycopg2.Error as e:
- if conn:
- conn.rollback()
- logger.error(f"Database error during email change request: {e}")
- return jsonify({'message': 'Database error processing your request.'}), 500
- except Exception as e:
- if conn:
- conn.rollback()
- logger.error(f"Error requesting email change: {e}")
- return jsonify({'message': 'An unexpected error occurred.'}), 500
- finally:
- if conn:
- cur.close()
- release_db_connection(conn)
-
[email protected]('/api/auth/verify-email-change', methods=['POST'])
-# This endpoint might not need @token_required if the verification_token itself is the auth mechanism
-# However, if a user is already logged in on the browser where they click the link,
-# it might be good to associate, but the primary auth is the token from email.
-def verify_email_change():
- data = request.get_json()
- verification_token = data.get('token')
-
- if not verification_token:
- return jsonify({'message': 'Verification token is required'}), 400
-
- conn = None
- try:
- conn = get_db_connection()
- cur = conn.cursor()
-
- cur.execute("""
- SELECT id, user_id, new_email, token_expires_at
- FROM email_change_requests
- WHERE verification_token = %s AND is_used = FALSE
- """, (verification_token,))
- request_data = cur.fetchone()
-
- if not request_data:
- return jsonify({'message': 'Invalid or expired verification token.'}), 400
-
- req_id, user_id, new_email, token_expires_at = request_data
-
- # Ensure token_expires_at is timezone-aware for comparison
- if token_expires_at.tzinfo is None:
- token_expires_at = pytz.utc.localize(token_expires_at)
-
- if datetime.utcnow().replace(tzinfo=pytz.utc) > token_expires_at:
- # Mark as used/expired anyway
- cur.execute("UPDATE email_change_requests SET is_used = TRUE WHERE id = %s", (req_id,))
- conn.commit()
- return jsonify({'message': 'Verification token has expired.'}), 400
-
- # Check if the new email has been taken by another user *since the request was made*
- # This is a rare race condition but good to check.
- cur.execute("SELECT id FROM users WHERE email = %s AND id != %s", (new_email, user_id))
- if cur.fetchone():
- cur.execute("UPDATE email_change_requests SET is_used = TRUE WHERE id = %s", (req_id,)) # Invalidate token
- conn.commit()
- return jsonify({'message': 'This email address has recently been claimed by another account. Please try a different email.'}), 409
-
- # Update user's email
- cur.execute("UPDATE users SET email = %s, updated_at = NOW() WHERE id = %s", (new_email, user_id))
-
- # Mark token as used
- cur.execute("UPDATE email_change_requests SET is_used = TRUE WHERE id = %s", (req_id,))
-
- conn.commit()
-
- # Optionally, log the user out of other sessions for security.
- # This would require a session management mechanism (e.g., storing session IDs or using JWT blacklisting).
- # For now, we will skip this, but it's a good addition for production.
-
- # Optionally, send a notification to the OLD email address that the email has been changed.
- # old_email_query = "SELECT email FROM users WHERE id = %s" # This would get new email now
- # To get old email, it should have been selected before the update or passed through.
- # For simplicity, this step is omitted but recommended.
-
- return jsonify({'message': 'Email address updated successfully.'}), 200
-
- except psycopg2.Error as e:
- if conn:
- conn.rollback()
- logger.error(f"Database error during email verification: {e}")
- return jsonify({'message': 'Database error processing your request.'}), 500
- except Exception as e:
- if conn:
- conn.rollback()
- logger.error(f"Error verifying email change: {e}")
- return jsonify({'message': 'An unexpected error occurred.'}), 500
- finally:
- if conn:
- cur.close()
- release_db_connection(conn)
-
@app.route('/api/settings/oidc-status', methods=['GET'])
def get_oidc_status():
- """Public endpoint to check if OIDC is enabled."""
+ """Public endpoint to check if OIDC is enabled and if OIDC-only mode is active."""
conn = None
try:
conn = get_db_connection()
with conn.cursor() as cur:
- cur.execute("SELECT value FROM site_settings WHERE key = 'oidc_enabled'")
- result = cur.fetchone()
+ # Get both OIDC enabled and OIDC-only mode settings
+ cur.execute("SELECT key, value FROM site_settings WHERE key IN ('oidc_enabled', 'oidc_only_mode')")
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+
oidc_enabled = False
- if result and result[0].lower() == 'true':
+ if settings.get('oidc_enabled') and settings['oidc_enabled'].lower() == 'true':
oidc_enabled = True
# Also check app.config as a fallback, though DB should be primary
- if not result and app.config.get('OIDC_ENABLED'):
+ if not settings.get('oidc_enabled') and app.config.get('OIDC_ENABLED'):
oidc_enabled = True
+
+ oidc_only_mode = False
+ if settings.get('oidc_only_mode') and settings['oidc_only_mode'].lower() == 'true':
+ oidc_only_mode = True
- return jsonify({'oidc_enabled': oidc_enabled}), 200
+ return jsonify({
+ 'oidc_enabled': oidc_enabled,
+ 'oidc_only_mode': oidc_only_mode
+ }), 200
except Exception as e:
logger.error(f"Error fetching OIDC status: {e}")
# Fallback to app.config or default to false if DB error
- return jsonify({'oidc_enabled': app.config.get('OIDC_ENABLED', False)}), 200
+ return jsonify({
+ 'oidc_enabled': app.config.get('OIDC_ENABLED', False),
+ 'oidc_only_mode': False
+ }), 200
finally:
if conn:
release_db_connection(conn)
@@ -5026,17 +3547,69 @@ def get_supported_apprise_services():
@app.route('/api/admin/apprise/send-expiration', methods=['POST'])
@admin_required
def trigger_apprise_expiration_notifications():
- """Manually trigger Apprise expiration notifications"""
+ """Manually trigger Apprise expiration notifications with warranty scope filtering"""
if not APPRISE_AVAILABLE or apprise_handler is None:
return jsonify({'success': False, 'message': 'Apprise notifications are not available'}), 503
try:
- results = apprise_handler.send_expiration_notifications()
+ # Get warranty scope setting to determine which warranties to include
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ cur.execute("SELECT value FROM site_settings WHERE key = 'apprise_warranty_scope'")
+ result = cur.fetchone()
+ warranty_scope = result[0] if result else 'all'
+ except Exception as e:
+ logger.error(f"Error fetching warranty scope setting: {e}")
+ warranty_scope = 'all' # Default fallback
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+ # Get eligible user IDs based on warranty scope
+ eligible_user_ids = None # None means all users
+
+ if warranty_scope == 'admin':
+ # Get admin user ID (first check if there's an owner, otherwise find first admin)
+ admin_user_id = None
+ conn_scope = None
+ try:
+ conn_scope = get_db_connection()
+ with conn_scope.cursor() as cur:
+ # First try to find the owner
+ cur.execute("SELECT id FROM users WHERE is_owner = TRUE LIMIT 1")
+ owner_result = cur.fetchone()
+ if owner_result:
+ admin_user_id = owner_result[0]
+ else:
+ # Fallback to first admin if no owner found
+ cur.execute("SELECT id FROM users WHERE is_admin = TRUE ORDER BY id LIMIT 1")
+ admin_result = cur.fetchone()
+ if admin_result:
+ admin_user_id = admin_result[0]
+ except Exception as e:
+ logger.error(f"Error finding admin user ID for warranty scope filtering: {e}")
+ finally:
+ if conn_scope:
+ release_db_connection(conn_scope)
+
+ if admin_user_id:
+ eligible_user_ids = [admin_user_id]
+ logger.info(f"Warranty scope 'admin': Limiting notifications to admin user ID {admin_user_id}")
+ else:
+ logger.warning("Warranty scope 'admin' requested but no admin user found, including all users")
+
+ logger.info(f"Triggering Apprise notifications with warranty scope: '{warranty_scope}', eligible users: {eligible_user_ids}")
+
+ # Send notifications with user filtering
+ results = apprise_handler.send_expiration_notifications(eligible_user_ids=eligible_user_ids)
return jsonify({
'success': True,
'message': f'Notifications processed: {results["sent"]} sent, {results["errors"]} errors',
- 'results': results
+ 'results': results,
+ 'warranty_scope': warranty_scope
}), 200
except Exception as e:
@@ -5136,7 +3709,7 @@ def get_all_warranties():
cur.execute('''
SELECT w.id, w.product_name, w.purchase_date, w.expiration_date, w.invoice_path, w.manual_path, w.other_document_path,
w.product_url, w.notes, w.purchase_price, w.user_id, w.created_at, w.updated_at, w.is_lifetime,
- w.vendor, w.warranty_type, w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days, w.product_photo_path,
+ w.vendor, w.warranty_type, w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days, w.product_photo_path, w.currency,
u.username, u.email, u.first_name, u.last_name
FROM warranties w
JOIN users u ON w.user_id = u.id
@@ -5232,7 +3805,7 @@ def get_global_warranties():
cur.execute('''
SELECT w.id, w.product_name, w.purchase_date, w.expiration_date, w.invoice_path, w.manual_path, w.other_document_path,
w.product_url, w.notes, w.purchase_price, w.user_id, w.created_at, w.updated_at, w.is_lifetime,
- w.vendor, w.warranty_type, w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days, w.product_photo_path,
+ w.vendor, w.warranty_type, w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days, w.product_photo_path, w.currency,
u.username, u.email, u.first_name, u.last_name
FROM warranties w
JOIN users u ON w.user_id = u.id
@@ -5298,12 +3871,26 @@ def get_global_warranties():
try:
# Try Docker environment path first
from backend.oidc_handler import oidc_bp
+ from backend.auth_routes import auth_bp
except ImportError:
# Fallback to development path
from oidc_handler import oidc_bp
+ from auth_routes import auth_bp
app.register_blueprint(oidc_bp, url_prefix='/api')
+app.register_blueprint(auth_bp, url_prefix='/api/auth')
# Note: Scheduler is already set up earlier in the file with 2-minute intervals
# The main scheduler setup is around line 3642-3655 with precise user-timezone timing
# This duplicate scheduler setup has been removed to prevent conflicts
+
[email protected]('/api/admin/fix-owner-role', methods=['POST'])
+@admin_required
+def fix_owner_role():
+ """Temporary endpoint to manually fix owner role - can be removed after fix"""
+ try:
+ ensure_owner_exists()
+ return jsonify({'success': True, 'message': 'Owner role fix attempted. Check logs for results.'}), 200
+ except Exception as e:
+ logger.error(f"Error in fix_owner_role endpoint: {e}")
+ return jsonify({'success': False, 'message': f'Error: {str(e)}'}), 500
diff --git a/backend/apprise_handler.py b/backend/apprise_handler.py
index a93ada1..5043d34 100644
--- a/backend/apprise_handler.py
+++ b/backend/apprise_handler.py
@@ -381,5 +381,197 @@ class AppriseNotificationHandler:
except Exception:
return []
+ def send_global_expiration_notification(self, warranties: List[Dict]) -> bool:
+ """Sends a single, consolidated notification for all expiring warranties."""
+ if not self.is_available() or not warranties:
+ return False
+
+ logger.info(f"Sending GLOBAL Apprise notification for {len(warranties)} expiring items.")
+ try:
+ # Group warranties by expiration days to send separate notifications like manual test
+ warranties_by_days = {}
+ for w in warranties:
+ # Calculate days until expiration
+ expiry_date = w.get('expiration_date')
+ if expiry_date:
+ try:
+ if isinstance(expiry_date, str):
+ parsed_date = datetime.fromisoformat(expiry_date.replace('Z', '+00:00'))
+ else:
+ parsed_date = expiry_date
+
+ days_until_expiry = (parsed_date.date() - datetime.now().date()).days
+
+ if days_until_expiry not in warranties_by_days:
+ warranties_by_days[days_until_expiry] = []
+ warranties_by_days[days_until_expiry].append(w)
+ except Exception as e:
+ logger.warning(f"Error parsing expiration date {expiry_date}: {e}")
+ # Default to 365 days if parsing fails
+ if 365 not in warranties_by_days:
+ warranties_by_days[365] = []
+ warranties_by_days[365].append(w)
+
+ # Send separate notifications for each day group (like manual test)
+ success = True
+ for days, day_warranties in warranties_by_days.items():
+ if not self._send_global_expiration_batch(day_warranties, days):
+ success = False
+
+ return success
+ except Exception as e:
+ logger.error(f"Error sending global expiration notification: {e}")
+ return False
+
+ def _send_global_expiration_batch(self, warranties: List[Dict], days: int) -> bool:
+ """Send global notification for warranties expiring in X days (matches manual test format)"""
+ if not self.is_available():
+ return False
+
+ try:
+ # Use same title format as manual test
+ if days == 1:
+ title = f"{self.title_prefix} Warranties Expiring Tomorrow!"
+ urgency = "🚨 URGENT: "
+ elif days <= 7:
+ title = f"{self.title_prefix} Warranties Expiring in {days} Days"
+ urgency = "⚠️ IMPORTANT: "
+ else:
+ title = f"{self.title_prefix} Warranties Expiring in {days} Days"
+ urgency = "📅 REMINDER: "
+
+ # Use same body format as manual test
+ body_lines = [
+ f"{urgency}You have {len(warranties)} warranty(ies) expiring in {days} day(s):",
+ ""
+ ]
+
+ for warranty in warranties[:10]: # Limit to first 10 to avoid very long messages
+ expiry_date = warranty.get('expiration_date', 'Unknown')
+ if isinstance(expiry_date, str):
+ try:
+ # Parse and format date if it's a string
+ parsed_date = datetime.fromisoformat(expiry_date.replace('Z', '+00:00'))
+ expiry_date = parsed_date.strftime('%Y-%m-%d')
+ except:
+ pass
+
+ body_lines.append(f"• {warranty.get('product_name', 'Unknown Product')} (expires: {expiry_date})")
+
+ if len(warranties) > 10:
+ body_lines.append(f"... and {len(warranties) - 10} more")
+
+ body_lines.extend([
+ "",
+ "Please review your warranties and take necessary action.",
+ "",
+ "Visit your Warracker dashboard to view details and manage your warranties."
+ ])
+
+ body = "\n".join(body_lines)
+
+ return self.apprise_obj.notify(title=title, body=body)
+
+ except Exception as e:
+ logger.error(f"Error sending global expiration batch notification: {e}")
+ return False
+
+ def send_individual_expiration_notification(self, user_id: int, warranties: List[Dict], get_db_connection, release_db_connection) -> bool:
+ """Sends a personalized Apprise notification to a single user."""
+ if not self.is_available() or not warranties:
+ return False
+
+ try:
+ logger.info(f"Sending INDIVIDUAL Apprise notification for {len(warranties)} items to user {user_id}.")
+
+ # Group warranties by expiration days to send separate notifications like manual test
+ warranties_by_days = {}
+ for w in warranties:
+ # Calculate days until expiration
+ expiry_date = w.get('expiration_date')
+ if expiry_date:
+ try:
+ if isinstance(expiry_date, str):
+ parsed_date = datetime.fromisoformat(expiry_date.replace('Z', '+00:00'))
+ else:
+ parsed_date = expiry_date
+
+ days_until_expiry = (parsed_date.date() - datetime.now().date()).days
+
+ if days_until_expiry not in warranties_by_days:
+ warranties_by_days[days_until_expiry] = []
+ warranties_by_days[days_until_expiry].append(w)
+ except Exception as e:
+ logger.warning(f"Error parsing expiration date {expiry_date}: {e}")
+ # Default to 365 days if parsing fails
+ if 365 not in warranties_by_days:
+ warranties_by_days[365] = []
+ warranties_by_days[365].append(w)
+
+ # Send separate notifications for each day group (like manual test)
+ success = True
+ for days, day_warranties in warranties_by_days.items():
+ if not self._send_individual_expiration_batch(day_warranties, days, user_id):
+ success = False
+
+ return success
+
+ except Exception as e:
+ logger.error(f"Error sending individual expiration notification for user {user_id}: {e}")
+ return False
+
+ def _send_individual_expiration_batch(self, warranties: List[Dict], days: int, user_id: int) -> bool:
+ """Send individual notification for warranties expiring in X days (matches manual test format)"""
+ if not self.is_available():
+ return False
+
+ try:
+ # Use same title format as manual test
+ if days == 1:
+ title = f"{self.title_prefix} Warranties Expiring Tomorrow!"
+ urgency = "🚨 URGENT: "
+ elif days <= 7:
+ title = f"{self.title_prefix} Warranties Expiring in {days} Days"
+ urgency = "⚠️ IMPORTANT: "
+ else:
+ title = f"{self.title_prefix} Warranties Expiring in {days} Days"
+ urgency = "📅 REMINDER: "
+
+ # Use same body format as manual test
+ body_lines = [
+ f"{urgency}You have {len(warranties)} warranty(ies) expiring in {days} day(s):",
+ ""
+ ]
+
+ for warranty in warranties[:10]: # Limit to first 10 to avoid very long messages
+ expiry_date = warranty.get('expiration_date', 'Unknown')
+ if isinstance(expiry_date, str):
+ try:
+ # Parse and format date if it's a string
+ parsed_date = datetime.fromisoformat(expiry_date.replace('Z', '+00:00'))
+ expiry_date = parsed_date.strftime('%Y-%m-%d')
+ except:
+ pass
+
+ body_lines.append(f"• {warranty.get('product_name', 'Unknown Product')} (expires: {expiry_date})")
+
+ if len(warranties) > 10:
+ body_lines.append(f"... and {len(warranties) - 10} more")
+
+ body_lines.extend([
+ "",
+ "Please review your warranties and take necessary action.",
+ "",
+ "Visit your Warracker dashboard to view details and manage your warranties."
+ ])
+
+ body = "\n".join(body_lines)
+
+ return self.apprise_obj.notify(title=title, body=body)
+
+ except Exception as e:
+ logger.error(f"Error sending individual expiration batch notification: {e}")
+ return False
+
# Global instance
apprise_handler = AppriseNotificationHandler()
\ No newline at end of file
diff --git a/backend/auth_routes.py b/backend/auth_routes.py
new file mode 100644
index 0000000..f6e0255
--- /dev/null
+++ b/backend/auth_routes.py
@@ -0,0 +1,1153 @@
+# backend/auth_routes.py
+from flask import Blueprint, request, jsonify, current_app
+from datetime import datetime, timedelta
+import uuid
+import smtplib
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+import os
+import pytz
+import psycopg2
+
+# Use relative imports for project modules
+from . import db_handler, notifications
+from .auth_utils import generate_token, token_required, is_valid_email, is_valid_password
+
+# Import bcrypt from app since it's initialized with the app
+try:
+ from .app import bcrypt
+except ImportError:
+ # Fallback for development environment
+ from app import bcrypt
+
+auth_bp = Blueprint('auth_bp', __name__)
+
+@auth_bp.route('/register', methods=['POST'])
+def register():
+ conn = None
+ try:
+ data = request.get_json()
+
+ # Check if registration is enabled
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Check if settings table exists
+ cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'site_settings'
+ )
+ """)
+ table_exists = cur.fetchone()[0]
+
+ registration_enabled = True
+ if table_exists:
+ # Get registration_enabled setting
+ cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")
+ result = cur.fetchone()
+
+ if result:
+ registration_enabled = result[0].lower() == 'true'
+
+ # Check if there are any users (first user can register regardless of setting)
+ cur.execute('SELECT COUNT(*) FROM users')
+ user_count = cur.fetchone()[0]
+
+ # If registration is disabled and this is not the first user, return error
+ if not registration_enabled and user_count > 0:
+ return jsonify({'message': 'Registration is currently disabled!'}), 403
+
+ # Validate required fields
+ required_fields = ['username', 'email', 'password']
+ for field in required_fields:
+ if field not in data or not data[field]:
+ return jsonify({'message': f'{field} is required!'}), 400
+
+ username = data['username']
+ email = data['email']
+ password = data['password']
+ first_name = data.get('first_name', '')
+ last_name = data.get('last_name', '')
+
+ # Validate email format
+ if not is_valid_email(email):
+ return jsonify({'message': 'Invalid email format!'}), 400
+
+ # Validate password strength
+ if not is_valid_password(password):
+ return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
+
+ # Hash the password
+ password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
+
+ with conn.cursor() as cur:
+ # Check if username or email already exists
+ cur.execute('SELECT id FROM users WHERE username = %s OR email = %s', (username, email))
+ existing_user = cur.fetchone()
+
+ if existing_user:
+ return jsonify({'message': 'Username or email already exists!'}), 409
+
+ # Check if this is the first user (who will be an admin and owner)
+ cur.execute('SELECT COUNT(*) FROM users')
+ user_count = cur.fetchone()[0]
+ is_admin = user_count == 0
+ is_owner = user_count == 0 # First user is also the owner
+
+ # Insert new user
+ cur.execute(
+ 'INSERT INTO users (username, email, password_hash, first_name, last_name, is_admin, is_owner) VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING id',
+ (username, email, password_hash, first_name, last_name, is_admin, is_owner)
+ )
+ user_id = cur.fetchone()[0]
+
+ # Log owner creation for transparency
+ if is_owner:
+ logger.info(f"✅ First user registered: {username} ({email}) - automatically set as admin and owner")
+
+ # Generate token
+ token = generate_token(user_id)
+
+ # Update last login
+ cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
+
+ # Store session info
+ ip_address = request.remote_addr
+ user_agent = request.headers.get('User-Agent', '')
+ session_token = str(uuid.uuid4())
+ expires_at = datetime.utcnow() + current_app.config['JWT_EXPIRATION_DELTA']
+
+ cur.execute(
+ 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent, login_method) VALUES (%s, %s, %s, %s, %s, %s)',
+ (user_id, session_token, expires_at, ip_address, user_agent, 'local')
+ )
+
+ conn.commit()
+
+ return jsonify({
+ 'message': 'User registered successfully!',
+ 'token': token,
+ 'user': {
+ 'id': user_id,
+ 'username': username,
+ 'email': email,
+ 'is_admin': is_admin
+ }
+ }), 201
+ except Exception as e:
+ current_app.logger.error(f"Registration error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Registration failed!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/login', methods=['POST'])
+def login():
+ conn = None
+ try:
+ data = request.get_json()
+
+ # Validate required fields
+ if not data.get('username') or not data.get('password'):
+ return jsonify({'message': 'Username and password are required!'}), 400
+
+ username = data['username']
+ password = data['password']
+
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Check if user exists - include is_admin in the query
+ cur.execute('SELECT id, username, email, password_hash, is_active, is_admin FROM users WHERE username = %s OR email = %s', (username, username))
+ user = cur.fetchone()
+
+ if not user or not bcrypt.check_password_hash(user[3], password):
+ return jsonify({'message': 'Invalid username or password!'}), 401
+
+ if not user[4]: # is_active
+ return jsonify({'message': 'Account is inactive!'}), 401
+
+ user_id = user[0]
+
+ # Generate token
+ token = generate_token(user_id)
+
+ # Update last login
+ cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
+
+ # Store session info
+ ip_address = request.remote_addr
+ user_agent = request.headers.get('User-Agent', '')
+ session_token = str(uuid.uuid4())
+ expires_at = datetime.utcnow() + current_app.config['JWT_EXPIRATION_DELTA']
+
+ cur.execute(
+ 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent, login_method) VALUES (%s, %s, %s, %s, %s, %s)',
+ (user_id, session_token, expires_at, ip_address, user_agent, 'local')
+ )
+
+ conn.commit()
+
+ return jsonify({
+ 'message': 'Login successful!',
+ 'token': token,
+ 'user': {
+ 'id': user_id,
+ 'username': user[1],
+ 'email': user[2],
+ 'is_admin': user[5] # Include is_admin flag
+ }
+ }), 200
+ except Exception as e:
+ current_app.logger.error(f"Login error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Login failed!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/logout', methods=['POST'])
+@token_required
+def logout():
+ conn = None
+ try:
+ auth_header = request.headers.get('Authorization')
+ if auth_header and auth_header.startswith('Bearer '):
+ token = auth_header.split(' ')[1]
+ else:
+ return jsonify({'message': 'No token provided!'}), 400
+
+ user_id = request.user['id']
+
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Invalidate all sessions for this user
+ cur.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
+ conn.commit()
+
+ return jsonify({'message': 'Logout successful!'}), 200
+ except Exception as e:
+ current_app.logger.error(f"Logout error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Logout failed!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/validate-token', methods=['GET'])
+@token_required
+def validate_token():
+ """Validate JWT token and return user info"""
+ try:
+ # If we got here, the token is valid (token_required decorator validated it)
+ return jsonify({
+ 'valid': True,
+ 'user': {
+ 'id': request.user['id'],
+ 'username': request.user['username'],
+ 'email': request.user['email'],
+ 'is_admin': request.user['is_admin'],
+ 'is_owner': request.user.get('is_owner', False)
+ },
+ 'message': 'Token is valid'
+ }), 200
+ except Exception as e:
+ current_app.logger.error(f"Token validation error: {e}")
+ return jsonify({
+ 'valid': False,
+ 'message': 'Invalid token'
+ }), 401
+
+@auth_bp.route('/user', methods=['GET'])
+@token_required
+def get_user():
+ conn = None
+ try:
+ user_id = request.user['id'] # Get user ID from the decorator
+
+ # --- ADD DATABASE QUERY ---
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Try to get user with is_owner column, fall back to without it if column doesn't exist
+ try:
+ cur.execute(
+ 'SELECT id, username, email, first_name, last_name, is_admin, is_owner FROM users WHERE id = %s',
+ (user_id,)
+ )
+ user_data = cur.fetchone()
+ has_owner_column = True
+ columns = ['id', 'username', 'email', 'first_name', 'last_name', 'is_admin', 'is_owner']
+ except Exception as e:
+ # If the query fails (likely because is_owner column doesn't exist), rollback and try again
+ current_app.logger.warning(f"Failed to query with is_owner column in get_user, falling back: {e}")
+ conn.rollback() # Rollback the failed transaction
+ cur.execute(
+ 'SELECT id, username, email, first_name, last_name, is_admin FROM users WHERE id = %s',
+ (user_id,)
+ )
+ user_data = cur.fetchone()
+ has_owner_column = False
+ columns = ['id', 'username', 'email', 'first_name', 'last_name', 'is_admin']
+ # --- END DATABASE QUERY ---
+
+ if not user_data:
+ return jsonify({'message': 'User not found!'}), 404
+
+ # Map database columns to a dictionary
+ user_info = dict(zip(columns, user_data))
+
+ # Add is_owner field if it wasn't included in the query
+ if not has_owner_column:
+ user_info['is_owner'] = False
+
+ # Return the full user information
+ return jsonify(user_info), 200
+
+ except Exception as e:
+ current_app.logger.error(f"Get user error: {e}")
+ return jsonify({'message': 'Failed to retrieve user information!'}), 500
+ finally:
+ # Release the connection back to the pool
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/password/reset-request', methods=['POST'])
+def request_password_reset():
+ conn = None
+ try:
+ data = request.get_json()
+
+ if not data.get('email'):
+ return jsonify({'message': 'Email is required!'}), 400
+
+ email = data['email']
+
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Check if user exists
+ cur.execute('SELECT id FROM users WHERE email = %s', (email,))
+ user = cur.fetchone()
+
+ if not user:
+ # Don't reveal if email exists or not for security
+ return jsonify({'message': 'If your email is registered, you will receive a password reset link.'}), 200
+
+ user_id = user[0]
+
+ # Generate reset token
+ reset_token = str(uuid.uuid4())
+ expires_at = datetime.utcnow() + timedelta(hours=24)
+
+ # Delete any existing tokens for this user
+ cur.execute('DELETE FROM password_reset_tokens WHERE user_id = %s', (user_id,))
+
+ # Insert new token
+ cur.execute(
+ 'INSERT INTO password_reset_tokens (user_id, token, expires_at) VALUES (%s, %s, %s)',
+ (user_id, reset_token, expires_at)
+ )
+
+ conn.commit()
+
+ # Get email base URL from settings
+ email_base_url = 'http://localhost:8080' # Default fallback
+ try:
+ cur.execute("SELECT value FROM site_settings WHERE key = 'email_base_url'")
+ result = cur.fetchone()
+ if result:
+ email_base_url = result[0]
+ else:
+ current_app.logger.warning("email_base_url setting not found for password reset, using default.")
+ except Exception as e:
+ current_app.logger.error(f"Error fetching email_base_url from settings for password reset: {e}. Using default.")
+
+ # Ensure base URL doesn't end with a slash
+ email_base_url = email_base_url.rstrip('/')
+
+ # Construct the full reset link
+ reset_link = f"{email_base_url}/reset-password.html?token={reset_token}" # Use base URL and correct page
+
+ # Send password reset email
+ current_app.logger.info(f"Password reset requested for user {user_id}. Preparing to send email.")
+ try:
+ send_password_reset_email(email, reset_link)
+ current_app.logger.info(f"Password reset email initiated for {email}")
+ except Exception as e:
+ current_app.logger.error(f"Failed to send password reset email to {email}: {e}")
+ # Even if email fails, don't tell the user.
+ # This prevents leaking information about registered emails or email server issues.
+ # The user journey remains the same: "If registered, you'll get an email."
+
+ # Always return success to the user, regardless of email success/failure
+ return jsonify({
+ 'message': 'If your email is registered, you will receive a password reset link.'
+ }), 200
+
+ except Exception as e:
+ current_app.logger.error(f"Password reset request error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Password reset request failed!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/status', methods=['GET'])
+def auth_status():
+ return jsonify({
+ "authentication_required": True,
+ "message": "Authentication is required for most endpoints"
+ })
+
+@auth_bp.route('/profile', methods=['PUT'])
+@token_required
+def update_profile():
+ user_id = request.user['id']
+
+ try:
+ # Get request data
+ data = request.get_json()
+ if not data:
+ return jsonify({'message': 'No input data provided'}), 400
+
+ # Extract fields
+ first_name = data.get('first_name', '').strip()
+ last_name = data.get('last_name', '').strip()
+ new_email = data.get('email', '').strip()
+
+ # Validate input
+ if not first_name or not last_name:
+ return jsonify({'message': 'First name and last name are required'}), 400
+
+ # Get database connection
+ conn = db_handler.get_db_connection()
+ cursor = conn.cursor()
+
+ try:
+ update_fields = ["first_name = %s", "last_name = %s"]
+ update_params = [first_name, last_name]
+
+ # Handle email change
+ if new_email:
+ if not is_valid_email(new_email):
+ conn.rollback()
+ return jsonify({'message': 'Invalid email format!'}), 400
+
+ # Check if the new email is different from the current one
+ cursor.execute("SELECT email FROM users WHERE id = %s", (user_id,))
+ current_email_tuple = cursor.fetchone()
+ if not current_email_tuple:
+ conn.rollback()
+ return jsonify({'message': 'User not found while fetching current email.'}), 404
+ current_email = current_email_tuple[0]
+
+ if new_email.lower() != current_email.lower():
+ # Check if the new email is already in use by another user
+ cursor.execute("SELECT id FROM users WHERE LOWER(email) = LOWER(%s) AND id != %s", (new_email, user_id))
+ if cursor.fetchone():
+ conn.rollback()
+ return jsonify({'message': 'This email address is already in use by another account.'}), 409
+ update_fields.append("email = %s")
+ update_params.append(new_email)
+
+ update_query_string = ", ".join(update_fields)
+ final_query = f"""
+ UPDATE users
+ SET {update_query_string}
+ WHERE id = %s
+ RETURNING id, username, email, first_name, last_name, created_at
+ """
+ cursor.execute(final_query, tuple(update_params + [user_id]))
+
+ # Get updated user data
+ user_data = cursor.fetchone()
+ if not user_data:
+ conn.rollback()
+ return jsonify({'message': 'User not found'}), 404
+
+ conn.commit()
+
+ user = {
+ 'id': user_data[0],
+ 'username': user_data[1],
+ 'email': user_data[2],
+ 'first_name': user_data[3],
+ 'last_name': user_data[4],
+ 'created_at': user_data[5].isoformat() if user_data[5] else None
+ }
+ return jsonify(user), 200
+
+ except Exception as e:
+ conn.rollback()
+ current_app.logger.error(f"Database error in update_profile: {str(e)}")
+ return jsonify({'message': 'Database error occurred'}), 500
+ finally:
+ cursor.close()
+ db_handler.release_db_connection(conn)
+
+ except Exception as e:
+ current_app.logger.error(f"Error in update_profile: {str(e)}")
+ return jsonify({'message': 'An error occurred while updating profile'}), 500
+
+@auth_bp.route('/account', methods=['DELETE'])
+@token_required
+def delete_account():
+ user_id = request.user['id']
+
+ try:
+ # Get database connection
+ conn = db_handler.get_db_connection()
+ cursor = conn.cursor()
+
+ try:
+ # Begin transaction
+ cursor.execute("BEGIN")
+
+ # Check if the current user is the owner
+ try:
+ cursor.execute('SELECT is_owner FROM users WHERE id = %s', (user_id,))
+ user_data = cursor.fetchone()
+ is_owner = user_data[0] if user_data and len(user_data) > 0 else False
+ except Exception as e:
+ # If the query fails (likely because is_owner column doesn't exist), try without it
+ current_app.logger.warning(f"Failed to query with is_owner column in delete_account, falling back: {e}")
+ cursor.execute("ROLLBACK") # Rollback the failed transaction
+ cursor.execute("BEGIN") # Start a new transaction
+ is_owner = False
+
+ if is_owner:
+ cursor.execute("ROLLBACK")
+ return jsonify({'message': 'The application owner cannot delete their own account. Please transfer ownership first.'}), 403
+
+ # Delete user's warranties
+ cursor.execute("DELETE FROM warranties WHERE user_id = %s", (user_id,))
+
+ # Delete user's reset tokens if any
+ cursor.execute("DELETE FROM password_reset_tokens WHERE user_id = %s", (user_id,))
+
+ # Delete user's sessions if any
+ cursor.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
+ sessions_deleted = cursor.rowcount
+ current_app.logger.info(f"Deleted {sessions_deleted} sessions belonging to user {user_id}")
+
+ # Delete user's tags
+ cursor.execute('DELETE FROM tags WHERE user_id = %s', (user_id,))
+ tags_deleted = cursor.rowcount
+ current_app.logger.info(f"Deleted {tags_deleted} tags belonging to user {user_id}")
+
+ # Delete user
+ cursor.execute("DELETE FROM users WHERE id = %s", (user_id,))
+ user_deleted = cursor.rowcount
+ current_app.logger.info(f"Deleted user {user_id}, affected rows: {user_deleted}")
+
+ # Commit transaction
+ cursor.execute("COMMIT")
+
+ return jsonify({'message': 'Account deleted successfully'}), 200
+
+ except Exception as e:
+ cursor.execute("ROLLBACK")
+ current_app.logger.error(f"Database error in delete_account: {str(e)}")
+ return jsonify({'message': 'Database error occurred'}), 500
+ finally:
+ cursor.close()
+ db_handler.release_db_connection(conn)
+
+ except Exception as e:
+ current_app.logger.error(f"Error in delete_account: {str(e)}")
+ return jsonify({'message': 'An error occurred while deleting account'}), 500
+
+# Helper function for checking currency column
+def has_currency_symbol_column(cursor):
+ """Check if user_preferences table has currency_symbol column"""
+ try:
+ cursor.execute("""
+ SELECT column_name
+ FROM information_schema.columns
+ WHERE table_name='user_preferences'
+ AND column_name='currency_symbol'
+ """)
+ return cursor.fetchone() is not None
+ except Exception:
+ return False
+
+# Note: re and pytz are already imported at the top
+
+def is_valid_timezone(tz):
+ """Validate if a timezone string is valid"""
+ try:
+ pytz.timezone(tz)
+ return True
+ except pytz.exceptions.UnknownTimeZoneError:
+ return False
+
+@auth_bp.route('/registration-status', methods=['GET'])
+def check_registration_status():
+ """Check if registration is enabled"""
+ conn = None
+ try:
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Check if settings table exists
+ cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'site_settings'
+ )
+ """)
+ table_exists = cur.fetchone()[0]
+
+ if not table_exists:
+ # If table doesn't exist, registration is enabled by default
+ return jsonify({"enabled": True}), 200
+
+ # Get registration_enabled setting
+ cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")
+ result = cur.fetchone()
+
+ if not result:
+ # If setting doesn't exist, registration is enabled by default
+ return jsonify({"enabled": True}), 200
+
+ registration_enabled = result[0].lower() == 'true'
+
+ return jsonify({"enabled": registration_enabled}), 200
+ except Exception as e:
+ current_app.logger.error(f"Error checking registration status: {e}")
+ return jsonify({"enabled": True}), 200 # Default to enabled on error
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/password/reset', methods=['POST'])
+def reset_password():
+ conn = None
+ try:
+ data = request.get_json()
+
+ if not data.get('token') or not data.get('password'):
+ return jsonify({'message': 'Token and password are required!'}), 400
+
+ token = data['token']
+ password = data['password']
+
+ # Validate password strength
+ if not is_valid_password(password):
+ return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
+
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Check if token exists and is valid
+ cur.execute('SELECT user_id, expires_at FROM password_reset_tokens WHERE token = %s', (token,))
+ token_info = cur.fetchone()
+
+ if not token_info or token_info[1] < datetime.utcnow():
+ return jsonify({'message': 'Invalid or expired token!'}), 400
+
+ user_id = token_info[0]
+
+ # Hash the new password
+ password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
+
+ # Update user's password
+ cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (password_hash, user_id))
+
+ # Delete the used token
+ cur.execute('DELETE FROM password_reset_tokens WHERE token = %s', (token,))
+
+ conn.commit()
+
+ return jsonify({'message': 'Password reset successful!'}), 200
+ except Exception as e:
+ current_app.logger.error(f"Password reset error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Password reset failed!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/password/change', methods=['POST'])
+@token_required
+def change_password():
+ """Allow logged-in users to change their password"""
+ conn = None
+ try:
+ data = request.get_json()
+
+ if not data.get('current_password') or not data.get('new_password'):
+ return jsonify({'message': 'Current password and new password are required!'}), 400
+
+ current_password = data['current_password']
+ new_password = data['new_password']
+ user_id = request.user['id'] # Get user ID from the token_required decorator
+
+ # Validate new password strength
+ if not is_valid_password(new_password):
+ return jsonify({'message': 'New password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
+
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Get the user's current password hash
+ cur.execute('SELECT password_hash FROM users WHERE id = %s', (user_id,))
+ user_data = cur.fetchone()
+
+ if not user_data:
+ return jsonify({'message': 'User not found!'}), 404
+
+ current_password_hash = user_data[0]
+
+ # Verify the current password
+ if not bcrypt.check_password_hash(current_password_hash, current_password):
+ return jsonify({'message': 'Incorrect current password!'}), 401
+
+ # Hash the new password
+ new_password_hash = bcrypt.generate_password_hash(new_password).decode('utf-8')
+
+ # Update the password in the database
+ cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (new_password_hash, user_id))
+
+ conn.commit()
+
+ return jsonify({'message': 'Password changed successfully!'}), 200
+
+ except Exception as e:
+ current_app.logger.error(f"Password change error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Failed to change password!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+# Helper functions for email functionality
+def send_password_reset_email(recipient_email, reset_link):
+ """Sends the password reset email."""
+ current_app.logger.info(f"Attempting to send password reset email to {recipient_email}")
+
+ try:
+ smtp_host = os.environ.get('SMTP_HOST', 'localhost')
+ smtp_port = int(os.environ.get('SMTP_PORT', 1025))
+ smtp_username = os.environ.get('SMTP_USERNAME')
+ smtp_password = os.environ.get('SMTP_PASSWORD')
+ smtp_use_tls = os.environ.get('SMTP_USE_TLS', 'true').lower() == 'true'
+ smtp_use_ssl = os.environ.get('SMTP_USE_SSL', 'false').lower() == 'true'
+ sender_email = os.environ.get('SMTP_SENDER_EMAIL', '[email protected]')
+ app_name = "Warracker"
+
+ subject = f"Password Reset - {app_name}"
+
+ app_base_url = os.environ.get('APP_BASE_URL', request.url_root.rstrip('/'))
+
+ html_content = f"""
+ <html>
+ <body>
+ <p>Hello,</p>
+ <p>You have requested a password reset for your {app_name} account.</p>
+ <p>Please click the link below to reset your password:</p>
+ <p><a href="{reset_link}">Reset Password</a></p>
+ <p>If you did not request this password reset, please ignore this email.</p>
+ <p>This link will expire in 24 hours.</p>
+ <p>Thanks,<br>The {app_name} Team</p>
+ </body>
+ </html>
+ """
+
+ msg = MIMEMultipart('alternative')
+ msg['Subject'] = subject
+ msg['From'] = sender_email
+ msg['To'] = recipient_email
+ msg.attach(MIMEText(html_content, 'html'))
+
+ current_app.logger.info(f"Attempting to send password reset email to {recipient_email} via {smtp_host}:{smtp_port}")
+
+ server = None
+ current_app.logger.info(f"Attempting SMTP connection to {smtp_host}:{smtp_port}")
+ if smtp_port == 465:
+ current_app.logger.info("Using SMTP_SSL for port 465.")
+ server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=10)
+ else:
+ current_app.logger.info(f"Using SMTP for port {smtp_port}.")
+ server = smtplib.SMTP(smtp_host, smtp_port, timeout=10)
+ if smtp_use_tls:
+ current_app.logger.info("Attempting to start TLS (server.starttls()).")
+ server.starttls()
+ current_app.logger.info("STARTTLS successful.")
+
+ if smtp_username and smtp_password:
+ current_app.logger.info(f"Logging in with username: {smtp_username}")
+ server.login(smtp_username, smtp_password)
+ current_app.logger.info("SMTP login successful.")
+
+ server.sendmail(sender_email, recipient_email, msg.as_string())
+ server.quit()
+ current_app.logger.info(f"Password reset email sent successfully to {recipient_email}")
+ return True
+ except Exception as e:
+ current_app.logger.error(f"Error sending password reset email: {e}")
+ return False
+
+@auth_bp.route('/preferences', methods=['GET'])
+@token_required
+def get_preferences():
+ """Get user preferences with default values"""
+ user_id = request.user['id']
+ try:
+ conn = db_handler.get_db_connection()
+ cursor = conn.cursor()
+
+ try:
+ # Check if user_preferences table exists
+ cursor.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'user_preferences'
+ )
+ """)
+ table_exists = cursor.fetchone()[0]
+
+ if not table_exists:
+ # Return default preferences if table doesn't exist
+ default_preferences = {
+ 'email_notifications': True,
+ 'default_view': 'grid',
+ 'theme': 'light',
+ 'expiring_soon_days': 30,
+ 'notification_frequency': 'daily',
+ 'notification_time': '09:00',
+ 'timezone': 'UTC',
+ 'notification_channel': 'email',
+ 'currency_symbol': '$',
+ 'date_format': 'MDY'
+ }
+ return jsonify(default_preferences), 200
+
+ # Get user preferences
+ cursor.execute("""
+ SELECT email_notifications, default_view, theme, expiring_soon_days,
+ notification_frequency, notification_time, timezone, currency_symbol, date_format, notification_channel, apprise_notification_time, apprise_notification_frequency, apprise_timezone, currency_position
+ FROM user_preferences
+ WHERE user_id = %s
+ """, (user_id,))
+
+ preferences_data = cursor.fetchone()
+
+ if preferences_data:
+ preferences = {
+ 'email_notifications': preferences_data[0],
+ 'default_view': preferences_data[1],
+ 'theme': preferences_data[2],
+ 'expiring_soon_days': preferences_data[3],
+ 'notification_frequency': preferences_data[4],
+ 'notification_time': preferences_data[5],
+ 'timezone': preferences_data[6],
+ 'currency_symbol': preferences_data[7] if preferences_data[7] else '$',
+ 'date_format': preferences_data[8] if preferences_data[8] else 'MDY',
+ 'notification_channel': preferences_data[9] if preferences_data[9] else 'email',
+ 'apprise_notification_time': preferences_data[10] if preferences_data[10] else '09:00',
+ 'apprise_notification_frequency': preferences_data[11] if preferences_data[11] else 'daily',
+ 'apprise_timezone': preferences_data[12] if preferences_data[12] else 'UTC',
+ 'currency_position': preferences_data[13] if preferences_data[13] else 'left'
+ }
+ else:
+ # Create default preferences for user
+ default_preferences = {
+ 'email_notifications': True,
+ 'default_view': 'grid',
+ 'theme': 'light',
+ 'expiring_soon_days': 30,
+ 'notification_frequency': 'daily',
+ 'notification_time': '09:00',
+ 'timezone': 'UTC',
+ 'notification_channel': 'email',
+ 'currency_symbol': '$',
+ 'date_format': 'MDY',
+ 'currency_position': 'left'
+ }
+ preferences = default_preferences
+
+ return jsonify(preferences), 200
+
+ except Exception as e:
+ current_app.logger.error(f"Database error in get_preferences: {str(e)}")
+ default_preferences = {
+ 'email_notifications': True,
+ 'default_view': 'grid',
+ 'theme': 'light',
+ 'expiring_soon_days': 30,
+ 'notification_frequency': 'daily',
+ 'notification_time': '09:00',
+ 'timezone': 'UTC',
+ 'notification_channel': 'email',
+ 'currency_symbol': '$',
+ 'date_format': 'MDY',
+ 'currency_position': 'left'
+ }
+ return jsonify(default_preferences), 200
+ finally:
+ cursor.close()
+ db_handler.release_db_connection(conn)
+
+ except Exception as e:
+ current_app.logger.error(f"Error in get_preferences: {str(e)}")
+ default_preferences = {
+ 'email_notifications': True,
+ 'default_view': 'grid',
+ 'theme': 'light',
+ 'expiring_soon_days': 30,
+ 'notification_frequency': 'daily',
+ 'notification_time': '09:00',
+ 'timezone': 'UTC',
+ 'notification_channel': 'email',
+ 'currency_symbol': '$',
+ 'date_format': 'MDY',
+ 'currency_position': 'left'
+ }
+ return jsonify(default_preferences), 200
+
+@auth_bp.route('/preferences', methods=['PUT'])
+@token_required
+def update_preferences():
+ """Update user preferences"""
+ user_id = request.user['id']
+ try:
+ data = request.get_json()
+ if not data:
+ return jsonify({'message': 'No input data provided'}), 400
+
+ # Basic validation
+ default_view = data.get('default_view')
+ theme = data.get('theme')
+ expiring_soon_days = data.get('expiring_soon_days')
+ currency_symbol = data.get('currency_symbol')
+ currency_position = data.get('currency_position')
+ date_format = data.get('date_format')
+ notification_channel = data.get('notification_channel')
+ notification_frequency = data.get('notification_frequency')
+ notification_time = data.get('notification_time')
+ apprise_notification_time = data.get('apprise_notification_time')
+ apprise_notification_frequency = data.get('apprise_notification_frequency')
+ timezone = data.get('timezone')
+ apprise_timezone = data.get('apprise_timezone')
+
+ if default_view and default_view not in ['grid', 'list', 'table']:
+ return jsonify({'message': 'Invalid default view'}), 400
+ if theme and theme not in ['light', 'dark']:
+ return jsonify({'message': 'Invalid theme'}), 400
+ if expiring_soon_days is not None:
+ try:
+ expiring_soon_days = int(expiring_soon_days)
+ if expiring_soon_days < 1 or expiring_soon_days > 365:
+ return jsonify({'message': 'Expiring soon days must be between 1 and 365'}), 400
+ except ValueError:
+ return jsonify({'message': 'Expiring soon days must be a valid number'}), 400
+ if currency_symbol and len(currency_symbol) > 8:
+ return jsonify({'message': 'Currency symbol must be 8 characters or less'}), 400
+ if currency_position and currency_position not in ['left', 'right']:
+ return jsonify({'message': 'Invalid currency position'}), 400
+ if date_format and date_format not in ['MDY', 'DMY', 'YMD', 'MDY_WORDS', 'DMY_WORDS', 'YMD_WORDS']:
+ return jsonify({'message': 'Invalid date format'}), 400
+ if notification_channel and notification_channel not in ['none', 'email', 'apprise', 'both']:
+ return jsonify({'message': 'Invalid notification channel'}), 400
+
+ conn = db_handler.get_db_connection()
+ cursor = conn.cursor()
+
+ try:
+ # Check if preferences exist
+ cursor.execute("SELECT 1 FROM user_preferences WHERE user_id = %s", (user_id,))
+ preferences_exist = cursor.fetchone() is not None
+
+ if preferences_exist:
+ # Update existing preferences
+ update_fields = []
+ update_values = []
+
+ if default_view:
+ update_fields.append("default_view = %s")
+ update_values.append(default_view)
+ if theme:
+ update_fields.append("theme = %s")
+ update_values.append(theme)
+ if expiring_soon_days is not None:
+ update_fields.append("expiring_soon_days = %s")
+ update_values.append(expiring_soon_days)
+ if currency_symbol is not None:
+ update_fields.append("currency_symbol = %s")
+ update_values.append(currency_symbol)
+ if currency_position is not None:
+ update_fields.append("currency_position = %s")
+ update_values.append(currency_position)
+ if date_format is not None:
+ update_fields.append("date_format = %s")
+ update_values.append(date_format)
+ if notification_channel is not None:
+ update_fields.append("notification_channel = %s")
+ update_values.append(notification_channel)
+ if notification_frequency is not None:
+ update_fields.append("notification_frequency = %s")
+ update_values.append(notification_frequency)
+ if notification_time is not None:
+ update_fields.append("notification_time = %s")
+ update_values.append(notification_time)
+ if apprise_notification_time is not None:
+ update_fields.append("apprise_notification_time = %s")
+ update_values.append(apprise_notification_time)
+ if apprise_notification_frequency is not None:
+ update_fields.append("apprise_notification_frequency = %s")
+ update_values.append(apprise_notification_frequency)
+ if timezone is not None:
+ update_fields.append("timezone = %s")
+ update_values.append(timezone)
+ if apprise_timezone is not None:
+ update_fields.append("apprise_timezone = %s")
+ update_values.append(apprise_timezone)
+
+ if update_fields:
+ update_query = f"UPDATE user_preferences SET {', '.join(update_fields)} WHERE user_id = %s"
+ cursor.execute(update_query, update_values + [user_id])
+ else:
+ # Insert new preferences
+ cursor.execute("""
+ INSERT INTO user_preferences (user_id, default_view, theme, expiring_soon_days, currency_symbol, currency_position, date_format, notification_channel, notification_frequency, notification_time, apprise_notification_time, apprise_notification_frequency, timezone, apprise_timezone)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
+ """, (user_id, default_view or 'grid', theme or 'light', expiring_soon_days or 30, currency_symbol or '$', currency_position or 'left', date_format or 'MDY', notification_channel or 'email', notification_frequency or 'daily', notification_time or '09:00', apprise_notification_time or '09:00', apprise_notification_frequency or 'daily', timezone or 'UTC', apprise_timezone or 'UTC'))
+
+ conn.commit()
+
+ # Return updated preferences
+ cursor.execute("""
+ SELECT email_notifications, default_view, theme, expiring_soon_days,
+ notification_frequency, notification_time, timezone, currency_symbol, date_format, notification_channel, apprise_notification_time, apprise_notification_frequency, apprise_timezone, currency_position
+ FROM user_preferences
+ WHERE user_id = %s
+ """, (user_id,))
+
+ preferences_data = cursor.fetchone()
+
+ if preferences_data:
+ preferences = {
+ 'email_notifications': preferences_data[0],
+ 'default_view': preferences_data[1],
+ 'theme': preferences_data[2],
+ 'expiring_soon_days': preferences_data[3],
+ 'notification_frequency': preferences_data[4],
+ 'notification_time': preferences_data[5],
+ 'timezone': preferences_data[6],
+ 'currency_symbol': preferences_data[7] if preferences_data[7] else '$',
+ 'date_format': preferences_data[8] if preferences_data[8] else 'MDY',
+ 'notification_channel': preferences_data[9] if preferences_data[9] else 'email',
+ 'apprise_notification_time': preferences_data[10] if preferences_data[10] else '09:00',
+ 'apprise_notification_frequency': preferences_data[11] if preferences_data[11] else 'daily',
+ 'apprise_timezone': preferences_data[12] if preferences_data[12] else 'UTC',
+ 'currency_position': preferences_data[13] if preferences_data[13] else 'left'
+ }
+ else:
+ preferences = {
+ 'email_notifications': True,
+ 'default_view': default_view or 'grid',
+ 'theme': theme or 'light',
+ 'expiring_soon_days': expiring_soon_days or 30,
+ 'notification_frequency': notification_frequency or 'daily',
+ 'notification_time': notification_time or '09:00',
+ 'timezone': timezone or 'UTC',
+ 'notification_channel': notification_channel or 'email',
+ 'currency_symbol': currency_symbol or '$',
+ 'date_format': date_format or 'MDY',
+ 'currency_position': currency_position or 'left',
+ 'apprise_notification_time': apprise_notification_time or '09:00',
+ 'apprise_notification_frequency': apprise_notification_frequency or 'daily',
+ 'apprise_timezone': apprise_timezone or 'UTC'
+ }
+
+ return jsonify(preferences), 200
+
+ except Exception as e:
+ conn.rollback()
+ current_app.logger.error(f"Database error in update_preferences: {str(e)}")
+ return jsonify({'message': 'Database error occurred'}), 500
+ finally:
+ cursor.close()
+ db_handler.release_db_connection(conn)
+
+ except Exception as e:
+ current_app.logger.error(f"Error in update_preferences: {str(e)}")
+ return jsonify({'message': 'An error occurred while updating preferences'}), 500
+
+# Additional helper functions for email changes
+def generate_secure_token(length=40):
+ """Generates a cryptographically secure random string token."""
+ return uuid.uuid4().hex + uuid.uuid4().hex[:length-len(uuid.uuid4().hex)]
+
+@auth_bp.route('/change-email', methods=['POST'])
+@token_required
+def request_email_change():
+ """Request email change with verification"""
+ current_user_id = request.user['id']
+ data = request.get_json()
+ new_email = data.get('new_email')
+ password = data.get('password')
+
+ if not new_email or not password:
+ return jsonify({'message': 'New email and password are required'}), 400
+
+ if not is_valid_email(new_email):
+ return jsonify({'message': 'Invalid new email format'}), 400
+
+ conn = None
+ try:
+ conn = db_handler.get_db_connection()
+ cur = conn.cursor()
+
+ # Fetch current user's password hash and current email
+ cur.execute("SELECT password_hash, email FROM users WHERE id = %s", (current_user_id,))
+ user_data = cur.fetchone()
+
+ if not user_data:
+ return jsonify({'message': 'User not found'}), 404
+
+ current_password_hash, current_email = user_data
+
+ if not bcrypt.check_password_hash(current_password_hash, password):
+ return jsonify({'message': 'Incorrect password'}), 401
+
+ if new_email.lower() == current_email.lower():
+ return jsonify({'message': 'New email cannot be the same as the current email'}), 400
+
+ # Check if the new email is already in use by another user
+ cur.execute("SELECT id FROM users WHERE email = %s AND id != %s", (new_email.lower(), current_user_id))
+ if cur.fetchone():
+ return jsonify({'message': 'This email address is already in use by another account.'}), 409
+
+ # For simplicity, just update the email directly without verification
+ # In a production system, you would implement email verification here
+ cur.execute("UPDATE users SET email = %s WHERE id = %s", (new_email, current_user_id))
+ conn.commit()
+
+ return jsonify({'message': 'Email address updated successfully.'}), 200
+
+ except Exception as e:
+ if conn:
+ conn.rollback()
+ current_app.logger.error(f"Error changing email: {e}")
+ return jsonify({'message': 'An unexpected error occurred.'}), 500
+ finally:
+ if conn:
+ cur.close()
+ db_handler.release_db_connection(conn)
+
+@auth_bp.route('/verify-email-change', methods=['POST'])
+def verify_email_change():
+ """Verify email change (simplified version)"""
+ data = request.get_json()
+ verification_token = data.get('token')
+
+ if not verification_token:
+ return jsonify({'message': 'Verification token is required'}), 400
+
+ # For simplicity, return a basic response
+ # In a full implementation, this would verify the token and update the email
+ return jsonify({'message': 'Email verification functionality not fully implemented in this simplified version'}), 501
\ No newline at end of file
diff --git a/backend/auth_utils.py b/backend/auth_utils.py
index 1cfd4bf..f1476a4 100644
--- a/backend/auth_utils.py
+++ b/backend/auth_utils.py
@@ -1,7 +1,12 @@
# backend/auth_utils.py
import jwt
from datetime import datetime, timedelta
-from flask import current_app # To access app.config
+from flask import current_app, request, jsonify
+from functools import wraps
+import re
+
+# IMPORTANT: We need to import db_handler here for the decorators
+from backend import db_handler
def generate_token(user_id):
"""Generate a JWT token for the user"""
@@ -12,8 +17,115 @@ def generate_token(user_id):
}
return jwt.encode(payload, current_app.config['SECRET_KEY'], algorithm='HS256')
-# Note: You can later move decode_token, token_required, admin_required here too.
-# For token_required and admin_required, you'll also need:
-# from functools import wraps
-# from flask import request, jsonify
-# And you'd need to import get_db_connection, release_db_connection from your db_handler.
\ No newline at end of file
+def decode_token(token):
+ """Decode a JWT token and return the user_id"""
+ try:
+ payload = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
+ return payload['sub']
+ except jwt.ExpiredSignatureError:
+ return None # Token has expired
+ except jwt.InvalidTokenError:
+ return None # Invalid token
+
+def token_required(f):
+ """Decorator to protect routes that require authentication"""
+ @wraps(f)
+ def decorated(*args, **kwargs):
+ token = None
+
+ # Get token from Authorization header
+ auth_header = request.headers.get('Authorization')
+ if auth_header and auth_header.startswith('Bearer '):
+ token = auth_header.split(' ')[1]
+
+ # If no token in header, check form data for POST requests
+ if not token and request.method == 'POST':
+ token = request.form.get('auth_token') # Check form data
+
+ # If still no token, check URL query parameters
+ if not token:
+ token = request.args.get('token') # Check query parameters
+
+ # If no token is provided
+ if not token:
+ current_app.logger.warning(f"Authentication attempt without token: {request.path}")
+ return jsonify({'message': 'Authentication token is missing!'}), 401
+
+ # Decode the token
+ user_id = decode_token(token)
+ if not user_id:
+ current_app.logger.warning(f"Invalid token used for: {request.path}")
+ return jsonify({'message': 'Invalid or expired token!'}), 401
+
+ # Check if user exists
+ conn = None
+ try:
+ conn = db_handler.get_db_connection()
+ with conn.cursor() as cur:
+ # Try to get user with is_owner column, fall back to without it if column doesn't exist
+ try:
+ cur.execute('SELECT id, username, email, is_admin, is_owner FROM users WHERE id = %s AND is_active = TRUE', (user_id,))
+ user = cur.fetchone()
+ has_owner_column = True
+ except Exception as e:
+ # If the query fails (likely because is_owner column doesn't exist), rollback and try again
+ current_app.logger.warning(f"Failed to query with is_owner column, falling back: {e}")
+ conn.rollback() # Rollback the failed transaction
+ cur.execute('SELECT id, username, email, is_admin FROM users WHERE id = %s AND is_active = TRUE', (user_id,))
+ user = cur.fetchone()
+ has_owner_column = False
+
+ if not user:
+ return jsonify({'message': 'User not found or inactive!'}), 401
+
+ # Add user info to request context
+ request.user = {
+ 'id': user[0],
+ 'username': user[1],
+ 'email': user[2],
+ 'is_admin': user[3],
+ 'is_owner': user[4] if has_owner_column and len(user) > 4 else False
+ }
+
+ return f(*args, **kwargs)
+ except Exception as e:
+ current_app.logger.error(f"Authentication error: {e}")
+ return jsonify({'message': 'Authentication error!'}), 500
+ finally:
+ if conn:
+ db_handler.release_db_connection(conn)
+
+ return decorated
+
+def admin_required(f):
+ """Decorator to protect routes that require admin privileges"""
+ @wraps(f)
+ @token_required
+ def decorated(*args, **kwargs):
+ if not request.user.get('is_admin', False):
+ current_app.logger.error(f"User {request.user.get('username')} is not an admin")
+ return jsonify({'message': 'Admin privileges required!'}), 403
+
+ return f(*args, **kwargs)
+
+ return decorated
+
+def is_valid_email(email):
+ """Validate email format"""
+ pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
+ return re.match(pattern, email) is not None
+
+def is_valid_password(password):
+ """Validate password strength"""
+ # At least 8 characters, 1 uppercase, 1 lowercase, 1 number
+ if len(password) < 8:
+ return False
+ if not re.search(r'[A-Z]', password):
+ return False
+ if not re.search(r'[a-z]', password):
+ return False
+ if not re.search(r'[0-9]', password):
+ return False
+ return True
+
+
\ No newline at end of file
diff --git a/backend/gunicorn_config.py b/backend/gunicorn_config.py
index 0a2a945..59e9ab5 100644
--- a/backend/gunicorn_config.py
+++ b/backend/gunicorn_config.py
@@ -7,14 +7,27 @@ Optimized for memory efficiency with configurable modes.
"""
import os
+
+# CRITICAL: Apply gevent monkey patching VERY EARLY to prevent SSL RecursionError
+# This must happen before any other imports that might use SSL
+memory_mode = os.environ.get('WARRACKER_MEMORY_MODE', 'optimized').lower()
+
+# Only apply monkey patching for modes that will use gevent workers
+if memory_mode in ('optimized', 'performance'):
+ try:
+ from gevent import monkey
+ monkey.patch_all()
+ print("✅ Early gevent monkey patch applied for SSL compatibility.")
+ except ImportError:
+ print("⚠️ Gevent not found, but gevent workers will be requested. This may cause issues.")
+
import multiprocessing
# Server configurations - Dynamic based on memory mode
bind = "0.0.0.0:5000"
+forwarded_allow_ips = '*' # Trust proxy headers from any source (safe in containerized environment)
-# Check memory mode from environment variable
-memory_mode = os.environ.get('WARRACKER_MEMORY_MODE', 'optimized').lower()
-
+# Determine worker class first, then apply appropriate monkey patching
if memory_mode == 'ultra-light':
# Ultra-lightweight configuration for very memory-constrained environments
workers = 1 # Single worker for minimal memory usage (~40-50MB total)
@@ -40,6 +53,12 @@ else:
worker_rlimit_as = 134217728 # 128MB per worker limit
print("Using OPTIMIZED memory mode - balanced RAM usage and performance")
+# Note: Gevent monkey patching was applied early at top of file for SSL compatibility
+if worker_class == "gevent":
+ print(f"ℹ️ Using gevent workers with early monkey patching applied.")
+else:
+ print(f"ℹ️ Using {worker_class} workers - no monkey patching needed.")
+
# Common settings for both modes
timeout = 120
keepalive = 5
diff --git a/backend/migrations/025_add_warranty_type.sql b/backend/migrations/025_add_warranty_type.sql
index d113bfb..3ed081c 100644
--- a/backend/migrations/025_add_warranty_type.sql
+++ b/backend/migrations/025_add_warranty_type.sql
@@ -1,5 +1,23 @@
--- Migration: Add warranty_type field to warranties table
-ALTER TABLE warranties ADD COLUMN IF NOT EXISTS warranty_type VARCHAR(255) DEFAULT NULL;
+-- Migration: Create site_settings table
+-- Description: Creates the site_settings table for storing application configuration
--- Add an index for warranty type to improve search performance
-CREATE INDEX IF NOT EXISTS idx_warranty_type ON warranties(warranty_type);
\ No newline at end of file
+-- Create site_settings table
+CREATE TABLE IF NOT EXISTS site_settings (
+ key VARCHAR(255) PRIMARY KEY,
+ value TEXT,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);
+
+-- Insert default values
+INSERT INTO site_settings (key, value) VALUES
+('registration_enabled', 'true'),
+('email_base_url', 'http://localhost:8080'),
+('global_view_enabled', 'true'),
+('global_view_admin_only', 'false'),
+('oidc_enabled', 'false'),
+('oidc_only_mode', 'false'),
+('oidc_provider_name', 'oidc'),
+('oidc_client_id', ''),
+('oidc_issuer_url', ''),
+('oidc_scope', 'openid email profile')
+ON CONFLICT (key) DO NOTHING;
\ No newline at end of file
diff --git a/backend/migrations/025a_add_warranty_type.sql b/backend/migrations/025a_add_warranty_type.sql
new file mode 100644
index 0000000..d113bfb
--- /dev/null
+++ b/backend/migrations/025a_add_warranty_type.sql
@@ -0,0 +1,5 @@
+-- Migration: Add warranty_type field to warranties table
+ALTER TABLE warranties ADD COLUMN IF NOT EXISTS warranty_type VARCHAR(255) DEFAULT NULL;
+
+-- Add an index for warranty type to improve search performance
+CREATE INDEX IF NOT EXISTS idx_warranty_type ON warranties(warranty_type);
\ No newline at end of file
diff --git a/backend/migrations/031_add_owner_role.sql b/backend/migrations/031_add_owner_role.sql
new file mode 100644
index 0000000..dc643f0
--- /dev/null
+++ b/backend/migrations/031_add_owner_role.sql
@@ -0,0 +1,48 @@
+-- Migration 031: Add the is_owner flag to the users table
+
+-- Add the is_owner column, defaulting to FALSE for all users.
+ALTER TABLE users ADD COLUMN IF NOT EXISTS is_owner BOOLEAN NOT NULL DEFAULT FALSE;
+
+-- Find the very first user created and promote them to be the initial application Owner
+-- This is a safe, one-time operation with robust fallbacks
+DO $$
+DECLARE
+ first_user_id INT;
+ owner_count INT;
+BEGIN
+ -- Check if any owner is currently set
+ SELECT COUNT(*) INTO owner_count FROM users WHERE is_owner = TRUE;
+
+ IF owner_count = 0 THEN
+ -- Try multiple strategies to find the first user
+
+ -- Strategy 1: Use created_at if available
+ SELECT id INTO first_user_id FROM users
+ WHERE created_at IS NOT NULL
+ ORDER BY created_at ASC, id ASC
+ LIMIT 1;
+
+ -- Strategy 2: Fallback to lowest ID if created_at approach fails
+ IF first_user_id IS NULL THEN
+ SELECT id INTO first_user_id FROM users ORDER BY id ASC LIMIT 1;
+ END IF;
+
+ -- Strategy 3: If still no user found, check for any admin user
+ IF first_user_id IS NULL THEN
+ SELECT id INTO first_user_id FROM users WHERE is_admin = TRUE ORDER BY id ASC LIMIT 1;
+ END IF;
+
+ -- If we found a user, make them the owner
+ IF first_user_id IS NOT NULL THEN
+ UPDATE users SET is_owner = TRUE WHERE id = first_user_id;
+ RAISE NOTICE 'Migration 031: User ID % has been set as the initial application owner.', first_user_id;
+ ELSE
+ RAISE NOTICE 'Migration 031: No users found, no owner set. The first user to register will become the owner.';
+ END IF;
+ ELSE
+ RAISE NOTICE 'Migration 031: An owner is already set (% owner(s) found). No changes made.', owner_count;
+ END IF;
+EXCEPTION
+ WHEN OTHERS THEN
+ RAISE NOTICE 'Migration 031: Error during owner promotion: %. Will be handled by application startup.', SQLERRM;
+END $$;
\ No newline at end of file
diff --git a/backend/migrations/032_add_apprise_notification_mode.sql b/backend/migrations/032_add_apprise_notification_mode.sql
new file mode 100644
index 0000000..3d3e662
--- /dev/null
+++ b/backend/migrations/032_add_apprise_notification_mode.sql
@@ -0,0 +1,8 @@
+-- Migration 032: Add Apprise notification mode setting
+
+-- Add the setting to control how Apprise notifications are sent.
+-- 'global': One summary notification for all expiring warranties.
+-- 'individual': Separate notifications sent to each user based on their preferences.
+INSERT INTO site_settings (key, value)
+VALUES ('apprise_notification_mode', 'global')
+ON CONFLICT (key) DO NOTHING;
\ No newline at end of file
diff --git a/backend/migrations/033_add_apprise_warranty_scope.sql b/backend/migrations/033_add_apprise_warranty_scope.sql
new file mode 100644
index 0000000..a4fa055
--- /dev/null
+++ b/backend/migrations/033_add_apprise_warranty_scope.sql
@@ -0,0 +1,8 @@
+-- Migration 033: Add Apprise warranty scope setting
+
+-- Add the setting to control which warranties are included in Apprise notifications.
+-- 'all': Include warranties from all users (current behavior).
+-- 'admin': Only include warranties belonging to the admin user.
+INSERT INTO site_settings (key, value)
+VALUES ('apprise_warranty_scope', 'all')
+ON CONFLICT (key) DO NOTHING;
\ No newline at end of file
diff --git a/backend/migrations/034_add_currency_position_column.sql b/backend/migrations/034_add_currency_position_column.sql
new file mode 100644
index 0000000..c8e02d7
--- /dev/null
+++ b/backend/migrations/034_add_currency_position_column.sql
@@ -0,0 +1,35 @@
+-- Migration: Add currency_position column to user_preferences
+-- This allows users to choose whether currency symbol appears on left or right of numbers
+
+-- Add currency_position column with default value 'left' to maintain existing behavior
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_name = 'user_preferences' AND column_name = 'currency_position'
+ ) THEN
+ ALTER TABLE user_preferences ADD COLUMN currency_position VARCHAR(10) DEFAULT 'left';
+ RAISE NOTICE 'Added currency_position column to user_preferences table';
+ ELSE
+ RAISE NOTICE 'currency_position column already exists in user_preferences table';
+ END IF;
+END $$;
+
+-- Update any existing NULL or invalid values to 'left' to ensure constraint compliance
+UPDATE user_preferences SET currency_position = 'left'
+WHERE currency_position IS NULL OR currency_position NOT IN ('left', 'right');
+
+-- Add constraint to ensure only valid values (only if constraint doesn't already exist)
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.table_constraints
+ WHERE constraint_name = 'chk_currency_position'
+ AND table_name = 'user_preferences'
+ ) THEN
+ ALTER TABLE user_preferences ADD CONSTRAINT chk_currency_position CHECK (currency_position IN ('left', 'right'));
+ RAISE NOTICE 'Added check constraint for currency_position column';
+ ELSE
+ RAISE NOTICE 'Check constraint for currency_position already exists';
+ END IF;
+END $$;
\ No newline at end of file
diff --git a/backend/migrations/035_add_currency_to_warranties.sql b/backend/migrations/035_add_currency_to_warranties.sql
new file mode 100644
index 0000000..93e6b55
--- /dev/null
+++ b/backend/migrations/035_add_currency_to_warranties.sql
@@ -0,0 +1,59 @@
+-- Migration: Add currency column to warranties table
+-- This allows each warranty to have its own currency instead of using the global currency symbol
+
+-- Add currency column with default value 'USD' to maintain compatibility
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_name = 'warranties' AND column_name = 'currency'
+ ) THEN
+ ALTER TABLE warranties ADD COLUMN currency VARCHAR(10) DEFAULT 'USD';
+ RAISE NOTICE 'Added currency column to warranties table';
+ ELSE
+ RAISE NOTICE 'currency column already exists in warranties table';
+ END IF;
+END $$;
+
+-- Set existing warranties to use USD as default currency
+UPDATE warranties SET currency = 'USD' WHERE currency IS NULL;
+
+-- Add check constraint to ensure valid currency codes (ISO 4217 standard)
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'chk_warranty_currency'
+ AND conrelid = 'warranties'::regclass
+ ) THEN
+ ALTER TABLE warranties ADD CONSTRAINT chk_warranty_currency
+ CHECK (currency IN (
+ 'USD', 'EUR', 'GBP', 'JPY', 'CNY', 'INR', 'KRW', 'CHF', 'CAD', 'AUD',
+ 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'HUF', 'BGN', 'RON', 'HRK', 'RUB',
+ 'BRL', 'MXN', 'ARS', 'CLP', 'COP', 'PEN', 'VES', 'ZAR', 'EGP', 'NGN',
+ 'KES', 'GHS', 'MAD', 'TND', 'AED', 'SAR', 'QAR', 'KWD', 'BHD', 'OMR',
+ 'JOD', 'LBP', 'ILS', 'TRY', 'IRR', 'PKR', 'BDT', 'LKR', 'NPR', 'BTN',
+ 'MMK', 'THB', 'VND', 'LAK', 'KHR', 'MYR', 'SGD', 'IDR', 'PHP', 'TWD',
+ 'HKD', 'MOP', 'KPW', 'MNT', 'KZT', 'UZS', 'TJS', 'KGS', 'TMT', 'AFN',
+ 'AMD', 'AZN', 'GEL', 'MDL', 'UAH', 'BYN', 'RSD', 'MKD', 'ALL', 'BAM',
+ 'ISK', 'FJD', 'PGK', 'SBD', 'TOP', 'VUV', 'WST', 'XPF', 'NZD'
+ ));
+ RAISE NOTICE 'Added check constraint for currency column';
+ ELSE
+ RAISE NOTICE 'Check constraint for currency already exists';
+ END IF;
+END $$;
+
+-- Add index for better performance when filtering by currency
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE indexname = 'idx_warranties_currency'
+ ) THEN
+ CREATE INDEX idx_warranties_currency ON warranties(currency);
+ RAISE NOTICE 'Added index for currency column';
+ ELSE
+ RAISE NOTICE 'Index for currency column already exists';
+ END IF;
+END $$;
\ No newline at end of file
diff --git a/backend/migrations/apply_migrations.py b/backend/migrations/apply_migrations.py
index d1092c6..bcaa17d 100644
--- a/backend/migrations/apply_migrations.py
+++ b/backend/migrations/apply_migrations.py
@@ -115,15 +115,20 @@ def apply_migrations():
with open(migration_file, 'r') as f:
sql = f.read()
- cur.execute(
- sql,
- {
- "db_name": AsIs(DB_NAME),
- "db_user": AsIs(DB_USER),
- "db_admin_user": AsIs(DB_ADMIN_USER),
- "db_admin_password": AsIs(DB_ADMIN_PASSWORD),
- }
- )
+ # Check if the SQL has placeholders before passing parameters
+ if any(placeholder in sql for placeholder in ['%(db_name)s', '%(db_user)s', '%(db_admin_user)s', '%(db_admin_password)s']):
+ cur.execute(
+ sql,
+ {
+ "db_name": AsIs(DB_NAME),
+ "db_user": AsIs(DB_USER),
+ "db_admin_user": AsIs(DB_ADMIN_USER),
+ "db_admin_password": AsIs(DB_ADMIN_PASSWORD),
+ }
+ )
+ else:
+ # No placeholders, execute directly
+ cur.execute(sql)
elif migration_file.endswith('.py'):
# Apply Python migration
migration_module = load_python_migration(migration_file)
diff --git a/backend/notifications.py b/backend/notifications.py
index 82b32cb..75bfd04 100644
--- a/backend/notifications.py
+++ b/backend/notifications.py
@@ -11,13 +11,41 @@ import time
import atexit
import smtplib
import logging
-from datetime import datetime, date
+from datetime import datetime, date, timedelta
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
+from threading import Lock
+from decimal import Decimal
import pytz
from pytz import timezone as pytz_timezone
-from apscheduler.schedulers.background import BackgroundScheduler
+
+try:
+ from apscheduler.schedulers.background import BackgroundScheduler
+ BACKGROUND_SCHEDULER_AVAILABLE = True
+except ImportError:
+ BACKGROUND_SCHEDULER_AVAILABLE = False
+ BackgroundScheduler = None
+
+try:
+ from apscheduler.schedulers.gevent import GeventScheduler
+ GEVENT_SCHEDULER_AVAILABLE = True
+except ImportError:
+ GEVENT_SCHEDULER_AVAILABLE = False
+ GeventScheduler = None
+
+# Import database functions
+try:
+ from .db_handler import get_site_setting
+ DB_HANDLER_IMPORTED = True
+except ImportError:
+ try:
+ from db_handler import get_site_setting
+ DB_HANDLER_IMPORTED = True
+ except ImportError:
+ DB_HANDLER_IMPORTED = False
+ def get_site_setting(key, default=None):
+ return default
# Configure logging
logger = logging.getLogger(__name__)
@@ -627,12 +655,18 @@ def send_expiration_notifications(manual_trigger=False, get_db_connection=None,
logger.error(f"Error connecting to SMTP server: {e}")
logger.error(f"SMTP details - Host: {smtp_host}, Port: {smtp_port}, Username: {smtp_username}")
- # Send Apprise notifications if available and enabled
- if APPRISE_AVAILABLE and apprise_handler is not None:
+ # Send Apprise notifications if available and enabled (but not for manual triggers)
+ # Manual Apprise notifications should use the dedicated /api/admin/apprise/send-expiration endpoint
+ if APPRISE_AVAILABLE and apprise_handler is not None and not manual_trigger:
try:
+ # Get the Apprise notification settings
+ notification_mode = get_site_setting('apprise_notification_mode', 'global')
+ warranty_scope = get_site_setting('apprise_warranty_scope', 'all')
+ logger.info(f"Apprise notification mode set to: '{notification_mode}', warranty scope: '{warranty_scope}'")
+
+ # Filter warranties for users eligible for Apprise at this time
if manual_trigger:
- # For manual triggers, we still need to respect user notification preferences
- # Get users who have Apprise notifications enabled
+ # For manual triggers, get users who have Apprise notifications enabled
conn = None
try:
conn = get_db_connection()
@@ -653,32 +687,110 @@ def send_expiration_notifications(manual_trigger=False, get_db_connection=None,
WHERE u.is_active = TRUE
AND up.notification_channel IN ('apprise', 'both')
""")
- apprise_enabled_users = [row[0] for row in cur.fetchall()]
-
- if apprise_enabled_users:
- logger.info(f"Manual trigger: Attempting to send Apprise notifications to {len(apprise_enabled_users)} users with Apprise enabled")
- apprise_results = apprise_handler.send_expiration_notifications(eligible_user_ids=apprise_enabled_users)
- else:
- logger.info("Manual trigger: No users have Apprise notifications enabled")
- apprise_results = {"sent": 0, "errors": 0, "skipped": "No users with Apprise enabled"}
+ apprise_eligible_user_ids = [row[0] for row in cur.fetchall()]
else:
# Fallback for installations without notification_channel column
- logger.info("Manual trigger: notification_channel column not found, sending to all users (fallback mode)")
- apprise_results = apprise_handler.send_expiration_notifications()
+ apprise_eligible_user_ids = list(users_warranties.keys())
+ logger.info("Manual trigger: notification_channel column not found, enabling for all users (fallback mode)")
finally:
if conn:
release_db_connection(conn)
else:
- if users_to_notify_apprise:
- logger.info(f"Attempting to send Apprise notifications to {len(users_to_notify_apprise)} eligible users")
- apprise_results = apprise_handler.send_expiration_notifications(eligible_user_ids=list(users_to_notify_apprise))
+ # For scheduled notifications, use users_to_notify_apprise
+ apprise_eligible_user_ids = list(users_to_notify_apprise)
+
+ if not apprise_eligible_user_ids:
+ logger.info("No users eligible for Apprise notifications")
+ apprise_results = {"sent": 0, "errors": 0, "skipped": "No eligible users"}
+ else:
+ # Filter expiring warranties for eligible users
+ warranties_for_apprise_users = [w for w in expiring_warranties if w['user_id'] in apprise_eligible_user_ids]
+
+ # Apply warranty scope filtering
+ if warranty_scope == 'admin':
+ # Get admin user ID (first check if there's an owner, otherwise find first admin)
+ admin_user_id = None
+ conn_scope = None
+ try:
+ conn_scope = get_db_connection()
+ with conn_scope.cursor() as cur:
+ # First try to find the owner
+ cur.execute("SELECT id FROM users WHERE is_owner = TRUE LIMIT 1")
+ owner_result = cur.fetchone()
+ if owner_result:
+ admin_user_id = owner_result[0]
+ else:
+ # Fallback to first admin if no owner found
+ cur.execute("SELECT id FROM users WHERE is_admin = TRUE ORDER BY id LIMIT 1")
+ admin_result = cur.fetchone()
+ if admin_result:
+ admin_user_id = admin_result[0]
+ except Exception as e:
+ logger.error(f"Error finding admin user ID for warranty scope filtering: {e}")
+ finally:
+ if conn_scope:
+ release_db_connection(conn_scope)
+
+ if admin_user_id:
+ original_count = len(warranties_for_apprise_users)
+ warranties_for_apprise_users = [w for w in warranties_for_apprise_users if w['user_id'] == admin_user_id]
+ logger.info(f"Warranty scope 'admin': Filtered from {original_count} to {len(warranties_for_apprise_users)} warranties (admin user ID: {admin_user_id})")
+ else:
+ logger.warning("Warranty scope 'admin' requested but no admin user found, including all warranties")
+ elif warranty_scope == 'all':
+ logger.info(f"Warranty scope 'all': Including all {len(warranties_for_apprise_users)} eligible warranties")
+ else:
+ logger.warning(f"Unknown warranty scope '{warranty_scope}', defaulting to 'all' warranties")
+
+ if not warranties_for_apprise_users:
+ logger.info("No expiring warranties for users eligible for Apprise at this time")
+ apprise_results = {"sent": 0, "errors": 0, "skipped": "No expiring warranties for eligible users"}
else:
- logger.info("No users eligible for Apprise notifications at this time")
- apprise_results = {"sent": 0, "errors": 0, "skipped": "No eligible users"}
+ logger.info(f"Processing Apprise notifications in {notification_mode.upper()} mode for {len(warranties_for_apprise_users)} warranties")
+
+ if notification_mode == 'global':
+ # GLOBAL MODE: Send one consolidated notification
+ logger.info("Sending GLOBAL Apprise notification")
+ success = apprise_handler.send_global_expiration_notification(warranties_for_apprise_users)
+ apprise_results = {"sent": 1 if success else 0, "errors": 0 if success else 1, "mode": "global"}
+
+ elif notification_mode == 'individual':
+ # INDIVIDUAL MODE: Send one notification per user
+ logger.info("Sending INDIVIDUAL Apprise notifications")
+ sent_count = 0
+ error_count = 0
+
+ # Group warranties by user
+ user_warranties = {}
+ for w in warranties_for_apprise_users:
+ uid = w['user_id']
+ if uid not in user_warranties:
+ user_warranties[uid] = []
+ user_warranties[uid].append(w)
+
+ # Send notification for each user
+ for user_id, warranties in user_warranties.items():
+ try:
+ success = apprise_handler.send_individual_expiration_notification(user_id, warranties, get_db_connection, release_db_connection)
+ if success:
+ sent_count += 1
+ else:
+ error_count += 1
+ except Exception as e:
+ logger.error(f"Error sending individual Apprise notification for user {user_id}: {e}")
+ error_count += 1
+
+ apprise_results = {"sent": sent_count, "errors": error_count, "mode": "individual"}
+
+ else:
+ logger.warning(f"Unknown Apprise notification mode: '{notification_mode}'. Skipping Apprise notifications.")
+ apprise_results = {"sent": 0, "errors": 1, "skipped": f"Unknown mode: {notification_mode}"}
logger.info(f"Apprise notification process completed. Results: {apprise_results}")
except Exception as e:
logger.error(f"Error sending Apprise notifications: {e}")
+ elif manual_trigger:
+ logger.debug("Manual trigger: Skipping Apprise notifications (use dedicated Apprise endpoint for manual Apprise notifications)")
else:
logger.debug("Apprise notifications not available, skipping")
@@ -716,13 +828,50 @@ def init_scheduler(get_db_connection, release_db_connection):
try:
# Initialize scheduler if not already done
if scheduler is None:
- scheduler = BackgroundScheduler(
- job_defaults={
- 'coalesce': True,
- 'max_instances': 1,
- 'misfire_grace_time': 300
- }
- )
+ # First try GeventScheduler if gevent is available and we're in a gevent worker
+ worker_class = os.environ.get('GUNICORN_WORKER_CLASS', '')
+
+ if GEVENT_SCHEDULER_AVAILABLE and worker_class == 'gevent':
+ try:
+ scheduler = GeventScheduler(
+ job_defaults={
+ 'coalesce': True,
+ 'max_instances': 1,
+ 'misfire_grace_time': 300
+ }
+ )
+ logger.info("Using GeventScheduler for gevent worker compatibility")
+ except Exception as gevent_error:
+ logger.warning(f"Failed to initialize GeventScheduler: {gevent_error}")
+ logger.info("Falling back to BackgroundScheduler")
+ if BACKGROUND_SCHEDULER_AVAILABLE:
+ scheduler = BackgroundScheduler(
+ job_defaults={
+ 'coalesce': True,
+ 'max_instances': 1,
+ 'misfire_grace_time': 300
+ }
+ )
+ logger.info("Using BackgroundScheduler (GeventScheduler fallback)")
+ else:
+ logger.error("BackgroundScheduler not available for fallback")
+ return False
+ else:
+ if BACKGROUND_SCHEDULER_AVAILABLE:
+ scheduler = BackgroundScheduler(
+ job_defaults={
+ 'coalesce': True,
+ 'max_instances': 1,
+ 'misfire_grace_time': 300
+ }
+ )
+ if worker_class == 'gevent':
+ logger.info("Using BackgroundScheduler with gevent worker (GeventScheduler not available)")
+ else:
+ logger.info(f"Using BackgroundScheduler with {worker_class} worker")
+ else:
+ logger.error("No scheduler available (BackgroundScheduler not found)")
+ return False
# Create a wrapper function that includes the database functions
def notification_wrapper():
diff --git a/backend/oidc_handler.py b/backend/oidc_handler.py
index 78a7adb..6d360df 100644
--- a/backend/oidc_handler.py
+++ b/backend/oidc_handler.py
@@ -234,27 +234,36 @@ def get_oidc_status_route():
try:
conn = get_db_connection()
with conn.cursor() as cur:
- cur.execute("SELECT value FROM site_settings WHERE key = 'oidc_enabled'")
- result = cur.fetchone()
+ # Get OIDC settings including the new oidc_only_mode
+ cur.execute("SELECT key, value FROM site_settings WHERE key IN ('oidc_enabled', 'oidc_only_mode', 'oidc_provider_name')")
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+
oidc_is_enabled = False
- if result and result[0] is not None:
- oidc_is_enabled = str(result[0]).lower() == 'true'
+ if settings.get('oidc_enabled') and str(settings['oidc_enabled']).lower() == 'true':
+ oidc_is_enabled = True
+
+ oidc_only_mode = False
+ if settings.get('oidc_only_mode') and str(settings['oidc_only_mode']).lower() == 'true':
+ oidc_only_mode = True
- cur.execute("SELECT value FROM site_settings WHERE key = 'oidc_provider_name'")
- provider_name_result = cur.fetchone()
oidc_provider_name = 'SSO Provider' # Default button text
- if provider_name_result and provider_name_result[0]:
- raw_name = provider_name_result[0]
+ if settings.get('oidc_provider_name'):
+ raw_name = settings['oidc_provider_name']
# Simple capitalization for display
oidc_provider_name = raw_name.capitalize() if raw_name else 'SSO Provider'
return jsonify({
"oidc_enabled": oidc_is_enabled,
+ "oidc_only_mode": oidc_only_mode,
"oidc_provider_display_name": oidc_provider_name
}), 200
except Exception as e:
logger.error(f"[OIDC_HANDLER] Error fetching OIDC status: {e}")
- return jsonify({"oidc_enabled": False, "oidc_provider_display_name": "SSO Provider"}), 200 # Default to false on error
+ return jsonify({
+ "oidc_enabled": False,
+ "oidc_only_mode": False,
+ "oidc_provider_display_name": "SSO Provider"
+ }), 200 # Default to false on error
finally:
if conn:
release_db_connection(conn)
diff --git a/env.example b/env.example
new file mode 100644
index 0000000..ac23683
--- /dev/null
+++ b/env.example
@@ -0,0 +1,92 @@
+# Warracker Environment Configuration Example
+# Copy this file to .env and modify the values as needed
+
+# Database Configuration
+DB_PASSWORD=your_secure_database_password
+DB_ADMIN_PASSWORD=your_secure_admin_password
+
+# Application Security
+SECRET_KEY=your_very_secure_flask_secret_key_change_this_in_production
+
+# Email Configuration (for password resets and notifications)
+SMTP_HOST=smtp.gmail.com
+SMTP_PORT=587
+SMTP_PASSWORD=your-app-password
+SMTP_USE_TLS=true
+
+# Application URLs
+FRONTEND_URL=http://localhost:8005
+APP_BASE_URL=http://localhost:8005
+
+# OIDC SSO Configuration (Optional)
+OIDC_PROVIDER_NAME=oidc
+OIDC_CLIENT_ID=your_oidc_client_id
+OIDC_CLIENT_SECRET=your_oidc_client_secret
+OIDC_ISSUER_URL=https://your-oidc-provider.com/auth/realms/your-realm
+OIDC_SCOPE=openid email profile
+
+# Memory and Performance Settings
+WARRACKER_MEMORY_MODE=optimized
+MAX_UPLOAD_MB=16
+NGINX_MAX_BODY_SIZE_VALUE=16M
+
+# =====================
+# APPRISE NOTIFICATIONS
+# =====================
+
+# Enable/disable Apprise notifications
+APPRISE_ENABLED=false
+
+# Notification URLs (comma-separated)
+# Examples:
+# Email: mailto://user:[email protected]
+# Discord: discord://webhook_id/webhook_token
+# Slack: slack://TokenA/TokenB/TokenC/Channel
+# Telegram: telegram://BotToken/ChatID
+# Microsoft Teams: msteams://TokenA/TokenB/TokenC/
+# Webhooks: json://webhook.site/your-unique-id
+APPRISE_URLS=
+
+# Days before expiration to send notifications (comma-separated)
+APPRISE_EXPIRATION_DAYS=7,30
+
+# Time of day to send notifications (HH:MM format, 24-hour)
+APPRISE_NOTIFICATION_TIME=09:00
+
+# Prefix for notification titles
+APPRISE_TITLE_PREFIX=[Warracker]
+
+# =====================
+# APPRISE URL EXAMPLES
+# =====================
+
+# Gmail (using app password)
+# APPRISE_URLS=mailto://username:[email protected]
+
+# Discord Webhook
+# APPRISE_URLS=discord://webhook_id/webhook_token
+
+# Slack
+# APPRISE_URLS=slack://TokenA/TokenB/TokenC/Channel
+
+# Telegram Bot
+# APPRISE_URLS=telegram://BotToken/ChatID
+
+# Microsoft Teams
+# APPRISE_URLS=msteams://TokenA/TokenB/TokenC/
+
+# Multiple services (comma-separated)
+# APPRISE_URLS=mailto://user:[email protected],discord://webhook_id/webhook_token,telegram://BotToken/ChatID
+
+# Pushover
+# APPRISE_URLS=pover://user@token
+
+# Ntfy
+# APPRISE_URLS=ntfy://topic
+
+# Generic Webhook
+# APPRISE_URLS=json://webhook.site/your-unique-id
+
+# For more services and URL formats, visit:
+# https://github.com/caronc/apprise/wiki
\ No newline at end of file
diff --git a/frontend/about.html b/frontend/about.html
index 6d7eb1f..8160454 100644
--- a/frontend/about.html
+++ b/frontend/about.html
@@ -26,6 +26,230 @@
<script src="include-auth-new.js"></script> <!-- Handles auth state display -->
<script src="fix-auth-buttons-loader.js"></script> <!-- Fixes auth button display timing -->
+ <style>
+ .about-hero {
+ background: linear-gradient(135deg, var(--primary-color), var(--secondary-color, #4dabf7));
+ color: white;
+ padding: 60px 20px;
+ text-align: center;
+ border-radius: 12px;
+ margin: 20px 0;
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
+ }
+
+ .about-hero h1 {
+ font-size: 3rem;
+ margin-bottom: 10px;
+ font-weight: 700;
+ }
+
+ .about-hero .version {
+ font-size: 1.2rem;
+ opacity: 0.9;
+ margin-bottom: 20px;
+ }
+
+ .about-hero .description {
+ font-size: 1.1rem;
+ max-width: 600px;
+ margin: 0 auto;
+ opacity: 0.95;
+ line-height: 1.6;
+ }
+
+ .about-cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
+ gap: 20px;
+ margin: 30px 0;
+ }
+
+ .about-card {
+ background: var(--card-bg);
+ border-radius: 12px;
+ padding: 30px;
+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
+ transition: transform 0.3s ease, box-shadow 0.3s ease;
+ border: 1px solid var(--border-color);
+ }
+
+ .about-card:hover {
+ transform: translateY(-5px);
+ box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
+ }
+
+ .about-card h3 {
+ color: var(--primary-color);
+ font-size: 1.4rem;
+ margin-bottom: 20px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ }
+
+ .about-card h3 i {
+ font-size: 1.2rem;
+ }
+
+ .about-card p {
+ color: var(--text-color);
+ line-height: 1.6;
+ margin-bottom: 15px;
+ }
+
+ .social-links {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 15px;
+ margin-top: 20px;
+ }
+
+ .social-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 12px 20px;
+ background: var(--card-bg);
+ color: var(--text-color);
+ text-decoration: none;
+ border-radius: 8px;
+ border: 2px solid var(--border-color);
+ transition: all 0.3s ease;
+ font-weight: 500;
+ }
+
+ .social-link:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
+ }
+
+ .social-link.github {
+ border-color: #333;
+ color: #333;
+ }
+
+ .social-link.github:hover {
+ background: #333;
+ color: white;
+ }
+
+ .social-link.discord {
+ border-color: #5865f2;
+ color: #5865f2;
+ }
+
+ .social-link.discord:hover {
+ background: #5865f2;
+ color: white;
+ }
+
+ .social-link.license {
+ border-color: #28a745;
+ color: #28a745;
+ }
+
+ .social-link.license:hover {
+ background: #28a745;
+ color: white;
+ }
+
+ .social-link.issues {
+ border-color: #dc3545;
+ color: #dc3545;
+ }
+
+ .social-link.issues:hover {
+ background: #dc3545;
+ color: white;
+ }
+
+ .social-link.releases {
+ border-color: #17a2b8;
+ color: #17a2b8;
+ }
+
+ .social-link.releases:hover {
+ background: #17a2b8;
+ color: white;
+ }
+
+ .social-link i {
+ font-size: 1.1rem;
+ }
+
+ .update-status {
+ background: var(--card-bg);
+ border-radius: 8px;
+ padding: 20px;
+ margin: 20px 0;
+ border-left: 4px solid var(--primary-color);
+ }
+
+ .update-status h4 {
+ color: var(--primary-color);
+ margin-bottom: 10px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+
+ .coffee-section {
+ text-align: center;
+ background: var(--card-bg);
+ border-radius: 12px;
+ padding: 40px;
+ margin: 30px 0;
+ border: 2px dashed var(--border-color);
+ }
+
+ .coffee-section h3 {
+ color: var(--primary-color);
+ margin-bottom: 15px;
+ font-size: 1.5rem;
+ }
+
+ .coffee-section p {
+ color: var(--text-muted);
+ margin-bottom: 25px;
+ font-size: 1.1rem;
+ }
+
+ /* Dark mode adjustments */
+ [data-theme="dark"] .social-link.github {
+ border-color: #f0f6fc;
+ color: #f0f6fc;
+ }
+
+ [data-theme="dark"] .social-link.github:hover {
+ background: #f0f6fc;
+ color: #0d1117;
+ }
+
+ @media (max-width: 768px) {
+ .about-hero h1 {
+ font-size: 2.2rem;
+ }
+
+ .about-hero .version {
+ font-size: 1rem;
+ }
+
+ .about-cards {
+ grid-template-columns: 1fr;
+ }
+
+ .social-links {
+ justify-content: center;
+ }
+
+ .social-link {
+ flex: 1;
+ justify-content: center;
+ min-width: 140px;
+ }
+ }
+ </style>
+
</head>
<body>
<!-- Standard Header (Copied from index.html) -->
@@ -42,7 +266,6 @@
<a href="status.html" class="nav-link">
<i class="fas fa-chart-pie"></i> Status
</a>
- <!-- Consider adding an 'active' class to an 'About' link if created here -->
</div>
<!-- Group for right-aligned elements -->
<div class="header-right-group">
@@ -86,60 +309,79 @@
<div class="container" style="padding: 0;">
<div class="main-content" style="display: block;">
- <!-- Existing About Content, now wrapped -->
- <div class="about-container" style="background-color: var(--card-bg); color: var(--text-color); padding: 20px; border-radius: 8px; margin-top: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); width: 100%; box-sizing: border-box;">
- <h1 style="color: var(--primary-color); margin-bottom: 20px;">About Warracker</h1>
-
- <p><strong>Version:</strong> v0.10.1.0</p>
-
- <div id="versionTracker" style="margin-bottom: 20px;">
- <p><strong>Update Status:</strong> <span id="updateStatus">Checking for updates...</span></p>
- <a id="updateLink" href="#" target="_blank" rel="noopener noreferrer" style="display: none; color: var(--link-color);">
- <i class="fa-solid fa-arrow-up-right-from-square"></i> Release Notes
- </a>
- </div>
-
- <p>
- <strong>GitHub Repository:</strong>
- <a href="https://github.com/sassanix/Warracker" target="_blank" rel="noopener noreferrer" style="color: var(--link-color);">
- https://github.com/sassanix/Warracker
- </a>
- </p>
-
- <p>
- <strong>Release Notes:</strong>
- <a href="https://github.com/sassanix/Warracker/releases" target="_blank" rel="noopener noreferrer" style="color: var(--link-color);">
- View Releases
- </a>
+ <!-- Hero Section -->
+ <div class="about-hero">
+ <h1><i class="fas fa-shield-alt"></i> Warracker</h1>
+ <div class="version">Version v0.10.1.1</div>
+ <p class="description">
+ A comprehensive warranty management system designed to help you track, organize, and manage all your product warranties in one secure, user-friendly platform.
</p>
+ </div>
- <p>
- <strong>Author:</strong>
- <a href="https://github.com/sassanix" target="_blank" rel="noopener noreferrer" style="color: var(--link-color);">
- Sassanix
- </a>
- </p>
+ <!-- Update Status Card -->
+ <div class="update-status">
+ <h4><i class="fas fa-sync-alt"></i> Update Status</h4>
+ <p id="updateStatus">Checking for updates...</p>
+ <a id="updateLink" href="#" target="_blank" rel="noopener noreferrer" style="display: none; color: var(--primary-color); text-decoration: none;">
+ <i class="fas fa-external-link-alt"></i> View Release Notes
+ </a>
+ </div>
- <p>
- <strong>License:</strong>
- <a href="https://github.com/sassanix/Warracker/blob/main/LICENSE" target="_blank" rel="noopener noreferrer" style="color: var(--link-color);">
- AGPL-3.0
- </a>
- </p>
+ <!-- Information Cards -->
+ <div class="about-cards">
+ <!-- Project Information -->
+ <div class="about-card">
+ <h3><i class="fas fa-info-circle"></i> Project Information</h3>
+ <p>Warracker is an open-source warranty management system built with modern web technologies. It provides a secure and intuitive way to manage product warranties, track expiration dates, and organize important documents.</p>
+
+ <div class="social-links">
+ <a href="https://github.com/sassanix/Warracker" target="_blank" rel="noopener noreferrer" class="social-link github">
+ <i class="fab fa-github"></i> GitHub Repository
+ </a>
+ <a href="https://github.com/sassanix/Warracker/releases" target="_blank" rel="noopener noreferrer" class="social-link releases">
+ <i class="fas fa-tags"></i> Releases
+ </a>
+ </div>
+ </div>
- <p>
- <strong>Issues & Feature Requests:</strong>
- <a href="https://github.com/sassanix/Warracker/issues" target="_blank" rel="noopener noreferrer" style="color: var(--link-color);">
- Report Bugs / Request Features
- </a>
- </p>
+ <!-- Community & Support -->
+ <div class="about-card">
+ <h3><i class="fas fa-users"></i> Community & Support</h3>
+ <p>Join our community for support, discussions, and updates. Report bugs, request features, or get help from other users and contributors.</p>
+
+ <div class="social-links">
+ <a href="https://discord.gg/PGxVS3U2Nw" target="_blank" rel="noopener noreferrer" class="social-link discord">
+ <i class="fab fa-discord"></i> Discord Community
+ </a>
+ <a href="https://github.com/sassanix/Warracker/issues" target="_blank" rel="noopener noreferrer" class="social-link issues">
+ <i class="fas fa-bug"></i> Report Issues
+ </a>
+ </div>
+ </div>
- <!-- Buy Me A Coffee Button -->
- <div style="text-align: center; margin-top: 25px;">
- <script type="text/javascript" src="https://cdnjs.buymeacoffee.com/1.0.0/button.prod.min.js" data-name="bmc-button" data-slug="sassanix" data-color="#FFDD00" data-emoji="" data-font="Poppins" data-text="Buy me a coffee" data-outline-color="#000000" data-font-color="#000000" data-coffee-color="#ffffff" ></script>
+ <!-- Developer Information -->
+ <div class="about-card">
+ <h3><i class="fas fa-code"></i> Developer Information</h3>
+ <p>Warracker is developed and maintained by Sassanix. The project is open-source and welcomes contributions from the community.</p>
+
+ <div class="social-links">
+ <a href="https://github.com/sassanix" target="_blank" rel="noopener noreferrer" class="social-link github">
+ <i class="fab fa-github"></i> Sassanix
+ </a>
+ <a href="https://github.com/sassanix/Warracker/blob/main/LICENSE" target="_blank" rel="noopener noreferrer" class="social-link license">
+ <i class="fas fa-balance-scale"></i> AGPL-3.0 License
+ </a>
+ </div>
</div>
</div>
+ <!-- Support the Project -->
+ <div class="coffee-section">
+ <h3><i class="fas fa-coffee"></i> Support the Project</h3>
+ <p>If you find Warracker useful, consider supporting its development!</p>
+ <script type="text/javascript" src="https://cdnjs.buymeacoffee.com/1.0.0/button.prod.min.js" data-name="bmc-button" data-slug="sassanix" data-color="#FFDD00" data-emoji="" data-font="Poppins" data-text="Buy me a coffee" data-outline-color="#000000" data-font-color="#000000" data-coffee-color="#ffffff" ></script>
+ </div>
+
</div>
</div>
diff --git a/frontend/debug-export.html b/frontend/debug-export.html
new file mode 100644
index 0000000..1cd507a
--- /dev/null
+++ b/frontend/debug-export.html
@@ -0,0 +1,258 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Export Debug - Warracker</title>
+ <style>
+ body {
+ font-family: Arial, sans-serif;
+ margin: 20px;
+ background-color: #f5f5f5;
+ }
+ .container {
+ max-width: 1200px;
+ margin: 0 auto;
+ background: white;
+ padding: 20px;
+ border-radius: 8px;
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
+ }
+ .debug-section {
+ margin-bottom: 30px;
+ padding: 15px;
+ border: 1px solid #ddd;
+ border-radius: 5px;
+ }
+ .debug-section h3 {
+ margin-top: 0;
+ color: #333;
+ }
+ .warranty-list {
+ max-height: 300px;
+ overflow-y: auto;
+ border: 1px solid #eee;
+ padding: 10px;
+ background: #f9f9f9;
+ }
+ .warranty-item {
+ padding: 5px;
+ border-bottom: 1px solid #eee;
+ font-size: 14px;
+ }
+ .warranty-item:last-child {
+ border-bottom: none;
+ }
+ .btn {
+ background: #007bff;
+ color: white;
+ border: none;
+ padding: 10px 20px;
+ border-radius: 4px;
+ cursor: pointer;
+ margin: 5px;
+ }
+ .btn:hover {
+ background: #0056b3;
+ }
+ .filters-display {
+ background: #e9ecef;
+ padding: 10px;
+ border-radius: 4px;
+ font-family: monospace;
+ }
+ .error {
+ color: red;
+ font-weight: bold;
+ }
+ .success {
+ color: green;
+ font-weight: bold;
+ }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <h1>Export Debug Tool</h1>
+ <p>This page helps debug warranty export issues by showing what data is loaded and what filters are applied.</p>
+
+ <div class="debug-section">
+ <h3>Authentication Status</h3>
+ <div id="authStatus">Checking...</div>
+ </div>
+
+ <div class="debug-section">
+ <h3>Loaded Warranties</h3>
+ <div>Total warranties loaded: <span id="totalWarranties">0</span></div>
+ <button class="btn" onclick="loadWarrantiesDebug()">Load Warranties</button>
+ <div id="warrantiesList" class="warranty-list"></div>
+ </div>
+
+ <div class="debug-section">
+ <h3>Current Filters</h3>
+ <div id="currentFilters" class="filters-display">No filters loaded</div>
+ </div>
+
+ <div class="debug-section">
+ <h3>Export Test</h3>
+ <button class="btn" onclick="testExport()">Test Export (with debug)</button>
+ <div id="exportResults"></div>
+ </div>
+
+ <div class="debug-section">
+ <h3>Console Logs</h3>
+ <p>Check the browser console (F12) for detailed debug information when you click the buttons above.</p>
+ </div>
+ </div>
+
+ <script>
+ let warranties = [];
+ let currentFilters = {
+ status: 'all',
+ tag: 'all',
+ search: '',
+ sortBy: 'expiration',
+ vendor: 'all',
+ warranty_type: 'all'
+ };
+
+ // Check authentication status
+ function checkAuth() {
+ const token = localStorage.getItem('auth_token');
+ const userInfo = localStorage.getItem('user_info');
+
+ if (token && userInfo) {
+ document.getElementById('authStatus').innerHTML = `
+ <span class="success">✓ Authenticated</span><br>
+ Token: ${token.substring(0, 20)}...<br>
+ User: ${JSON.parse(userInfo).username || 'Unknown'}
+ `;
+ return true;
+ } else {
+ document.getElementById('authStatus').innerHTML = '<span class="error">✗ Not authenticated</span>';
+ return false;
+ }
+ }
+
+ // Load warranties with debug info
+ async function loadWarrantiesDebug() {
+ if (!checkAuth()) {
+ alert('Please log in first');
+ return;
+ }
+
+ try {
+ const token = localStorage.getItem('auth_token');
+ const response = await fetch('/api/warranties', {
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+ warranties = Array.isArray(data) ? data : [];
+
+ console.log('[DEBUG] Loaded warranties:', warranties);
+
+ document.getElementById('totalWarranties').textContent = warranties.length;
+
+ const listHtml = warranties.map(w =>
+ `<div class="warranty-item">
+ ID: ${w.id} | ${w.product_name} | Status: ${w.status || 'N/A'} | Vendor: ${w.vendor || 'N/A'}
+ </div>`
+ ).join('');
+
+ document.getElementById('warrantiesList').innerHTML = listHtml;
+
+ // Update filters display
+ document.getElementById('currentFilters').textContent = JSON.stringify(currentFilters, null, 2);
+
+ } catch (error) {
+ console.error('Error loading warranties:', error);
+ document.getElementById('warrantiesList').innerHTML = `<div class="error">Error: ${error.message}</div>`;
+ }
+ }
+
+ // Test export with debug
+ function testExport() {
+ if (warranties.length === 0) {
+ alert('Please load warranties first');
+ return;
+ }
+
+ console.log('[EXPORT DEBUG] Starting export test');
+ console.log('[EXPORT DEBUG] Total warranties:', warranties.length);
+ console.log('[EXPORT DEBUG] Current filters:', currentFilters);
+
+ let warrantiesToExport = [...warranties];
+ console.log('[EXPORT DEBUG] Initial warranties to export:', warrantiesToExport.length);
+
+ // Apply filters (same logic as main app)
+ if (currentFilters.search) {
+ const searchTerm = currentFilters.search.toLowerCase();
+ console.log('[EXPORT DEBUG] Applying search filter:', searchTerm);
+ warrantiesToExport = warrantiesToExport.filter(warranty => {
+ const productNameMatch = warranty.product_name && warranty.product_name.toLowerCase().includes(searchTerm);
+ const tagMatch = warranty.tags && Array.isArray(warranty.tags) &&
+ warranty.tags.some(tag => tag.name && tag.name.toLowerCase().includes(searchTerm));
+ const vendorMatch = warranty.vendor && warranty.vendor.toLowerCase().includes(searchTerm);
+ return productNameMatch || tagMatch || vendorMatch;
+ });
+ console.log('[EXPORT DEBUG] After search filter:', warrantiesToExport.length);
+ }
+
+ if (currentFilters.status !== 'all') {
+ console.log('[EXPORT DEBUG] Applying status filter:', currentFilters.status);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ warranty.status === currentFilters.status
+ );
+ console.log('[EXPORT DEBUG] After status filter:', warrantiesToExport.length);
+ }
+
+ if (currentFilters.tag !== 'all') {
+ const tagId = parseInt(currentFilters.tag);
+ console.log('[EXPORT DEBUG] Applying tag filter:', tagId);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ warranty.tags && Array.isArray(warranty.tags) &&
+ warranty.tags.some(tag => tag.id === tagId)
+ );
+ console.log('[EXPORT DEBUG] After tag filter:', warrantiesToExport.length);
+ }
+
+ if (currentFilters.vendor !== 'all') {
+ console.log('[EXPORT DEBUG] Applying vendor filter:', currentFilters.vendor);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ (warranty.vendor || '').toLowerCase() === currentFilters.vendor.toLowerCase()
+ );
+ console.log('[EXPORT DEBUG] After vendor filter:', warrantiesToExport.length);
+ }
+
+ if (currentFilters.warranty_type !== 'all') {
+ console.log('[EXPORT DEBUG] Applying warranty type filter:', currentFilters.warranty_type);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ (warranty.warranty_type || '').toLowerCase() === currentFilters.warranty_type.toLowerCase()
+ );
+ console.log('[EXPORT DEBUG] After warranty type filter:', warrantiesToExport.length);
+ }
+
+ console.log('[EXPORT DEBUG] Final warranties to export:', warrantiesToExport.length);
+ console.log('[EXPORT DEBUG] Warranty IDs being exported:', warrantiesToExport.map(w => w.id));
+
+ document.getElementById('exportResults').innerHTML = `
+ <div class="success">Export test completed!</div>
+ <div>Total warranties loaded: ${warranties.length}</div>
+ <div>Warranties that would be exported: ${warrantiesToExport.length}</div>
+ <div>Check console for detailed logs</div>
+ `;
+ }
+
+ // Initialize
+ checkAuth();
+ </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/frontend/index.html b/frontend/index.html
index 7a163f7..758c65a 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -231,6 +231,7 @@
<select id="sortBy" class="filter-select">
<option value="expiration">Expiration Date</option>
<option value="purchase">Purchase Date</option>
+ <option value="age">Age</option>
<option value="name">Product Name</option>
<option value="vendor">Vendor</option>
<option value="warranty_type">Warranty Type</option>
@@ -420,13 +421,20 @@
</select>
<input type="text" id="warrantyTypeCustom" name="warranty_type_custom" class="form-control" style="display: none; margin-top: 8px;" placeholder="Enter custom warranty type">
</div>
- <div class="form-group">
- <label for="purchasePrice">Purchase Price (Optional)</label>
- <div class="price-input-wrapper">
- <span class="currency-symbol">$</span>
- <input type="number" id="purchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">
- </div>
- </div>
+ <div class="form-group">
+ <label for="currency">Currency</label>
+ <select id="currency" name="currency" class="form-control">
+ <option value="USD">USD - US Dollar ($)</option>
+ <!-- Currency options will be populated by JavaScript -->
+ </select>
+ </div>
+ <div class="form-group">
+ <label for="purchasePrice">Purchase Price (Optional)</label>
+ <div class="price-input-wrapper" id="addPriceInputWrapper">
+ <span class="currency-symbol" id="addCurrencySymbol">$</span>
+ <input type="number" id="purchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">
+ </div>
+ </div>
<div class="form-group">
<label for="notes">Notes (Optional)</label>
<textarea id="notes" name="notes" class="form-control" rows="3" placeholder="Add any notes about this warranty..."></textarea>
@@ -728,10 +736,17 @@
</select>
<input type="text" id="editWarrantyTypeCustom" name="warranty_type_custom" class="form-control" style="display: none; margin-top: 8px;" placeholder="Enter custom warranty type">
</div>
+ <div class="form-group">
+ <label for="editCurrency">Currency</label>
+ <select id="editCurrency" name="currency" class="form-control">
+ <option value="USD">USD - US Dollar ($)</option>
+ <!-- Currency options will be populated by JavaScript -->
+ </select>
+ </div>
<div class="form-group">
<label for="editPurchasePrice">Purchase Price (Optional)</label>
- <div class="price-input-wrapper">
- <span class="currency-symbol">$</span>
+ <div class="price-input-wrapper" id="editPriceInputWrapper">
+ <span class="currency-symbol" id="editCurrencySymbol">$</span>
<input type="number" id="editPurchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">
</div>
</div>
diff --git a/frontend/login.html b/frontend/login.html
index f74a422..8d9e9ce 100644
--- a/frontend/login.html
+++ b/frontend/login.html
@@ -377,6 +377,8 @@
.then(data => {
const oidcButton = document.getElementById('oidcLoginButton');
const orSeparator = document.querySelector('.auth-form + div[style*="text-align: center"]');
+ const loginForm = document.getElementById('loginForm');
+ const authLinks = document.querySelector('.auth-links');
if (!data.oidc_enabled) {
if (oidcButton) oidcButton.style.display = 'none';
@@ -384,6 +386,34 @@
return;
}
+ // Handle OIDC-only mode
+ if (data.oidc_only_mode) {
+ // Hide traditional login form and related elements
+ if (loginForm) loginForm.style.display = 'none';
+ if (orSeparator) orSeparator.style.display = 'none';
+ if (authLinks) {
+ // Hide register and forgot password links in OIDC-only mode
+ const registerLink = authLinks.querySelector('a[href="register.html"]');
+ const forgotPasswordLink = authLinks.querySelector('a[href="reset-password-request.html"]');
+ if (registerLink) registerLink.style.display = 'none';
+ if (forgotPasswordLink) forgotPasswordLink.style.display = 'none';
+
+ // If all links are hidden, hide the entire auth-links section
+ const visibleLinks = Array.from(authLinks.querySelectorAll('a')).filter(link =>
+ link.style.display !== 'none'
+ );
+ if (visibleLinks.length === 0) {
+ authLinks.style.display = 'none';
+ }
+ }
+
+ // Update page title to reflect OIDC-only mode
+ const authTitle = document.querySelector('.auth-title');
+ if (authTitle) {
+ authTitle.textContent = 'Login with SSO';
+ }
+ }
+
// Customize button based on provider
if (oidcButton && data.oidc_provider_display_name) {
const providerName = data.oidc_provider_display_name.toLowerCase();
diff --git a/frontend/script.js b/frontend/script.js
index 758d97c..bac5463 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -115,6 +115,10 @@ const editExactExpirationDateInput = document.getElementById('editExactExpiratio
// Add near other DOM Element declarations
const showAddWarrantyBtn = document.getElementById('showAddWarrantyBtn');
const addWarrantyModal = document.getElementById('addWarrantyModal');
+
+// Currency dropdown elements
+const currencySelect = document.getElementById('currency');
+const editCurrencySelect = document.getElementById('editCurrency');
const serialNumbersContainer = document.getElementById('serialNumbersContainer'); // Ensure this is defined
/**
@@ -158,6 +162,26 @@ async function initViewControls() {
if (globalViewBtn) {
globalViewBtn.addEventListener('click', () => switchToGlobalView());
}
+
+ // Load and apply saved view scope preference
+ const savedScope = loadViewScopePreference();
+ if (savedScope === 'global') {
+ // Apply global view silently without saving preference again
+ isGlobalView = true;
+ personalViewBtn.classList.remove('active');
+ globalViewBtn.classList.add('active');
+ if (warrantiesPanelTitle) {
+ warrantiesPanelTitle.textContent = 'All Users\' Warranties';
+ }
+ } else {
+ // Apply personal view (default)
+ isGlobalView = false;
+ personalViewBtn.classList.add('active');
+ globalViewBtn.classList.remove('active');
+ if (warrantiesPanelTitle) {
+ warrantiesPanelTitle.textContent = 'Your Warranties';
+ }
+ }
} else if (adminViewSwitcher) {
// Global view is disabled, hide view switcher
adminViewSwitcher.style.display = 'none';
@@ -215,6 +239,9 @@ async function switchToPersonalView() {
personalViewBtn.classList.add('active');
globalViewBtn.classList.remove('active');
+ // Save view preference
+ saveViewScopePreference('personal');
+
// Update title
if (warrantiesPanelTitle) {
warrantiesPanelTitle.textContent = 'Your Warranties';
@@ -264,6 +291,9 @@ async function switchToGlobalView() {
personalViewBtn.classList.remove('active');
globalViewBtn.classList.add('active');
+ // Save view preference
+ saveViewScopePreference('global');
+
// Update title
if (warrantiesPanelTitle) {
warrantiesPanelTitle.textContent = 'All Users\' Warranties';
@@ -290,6 +320,36 @@ function getPreferenceKeyPrefix() {
return getUserType() === 'admin' ? 'admin_' : 'user_';
}
+/**
+ * Save view scope preference to localStorage
+ * @param {string} scope - 'personal' or 'global'
+ */
+function saveViewScopePreference(scope) {
+ try {
+ const prefix = getPreferenceKeyPrefix();
+ localStorage.setItem(`${prefix}viewScope`, scope);
+ console.log(`Saved view scope preference: ${scope} with prefix: ${prefix}`);
+ } catch (error) {
+ console.error('Error saving view scope preference:', error);
+ }
+}
+
+/**
+ * Load view scope preference from localStorage
+ * @returns {string} The saved preference ('personal', 'global', or 'personal' as default)
+ */
+function loadViewScopePreference() {
+ try {
+ const prefix = getPreferenceKeyPrefix();
+ const savedScope = localStorage.getItem(`${prefix}viewScope`);
+ console.log(`Loaded view scope preference: ${savedScope} with prefix: ${prefix}`);
+ return savedScope || 'personal'; // Default to personal view
+ } catch (error) {
+ console.error('Error loading view scope preference:', error);
+ return 'personal'; // Default to personal view on error
+ }
+}
+
// Theme Management - Simplified
function setTheme(isDark) {
const theme = isDark ? 'dark' : 'light';
@@ -491,6 +551,7 @@ document.addEventListener('DOMContentLoaded', function() {
if (currentAuthStatus) {
await loadAndApplyUserPreferences(true); // Pass true, as we've confirmed auth
await loadTags(); // Ensure all available tags are loaded
+ await loadCurrencies(); // Load currencies for dropdowns
// Initialize view controls for all users
initViewControls();
@@ -1010,10 +1071,17 @@ function updateSummary() {
// Purchase price
const purchasePrice = document.getElementById('purchasePrice')?.value;
+ const currency = document.getElementById('currency')?.value;
const summaryPurchasePrice = document.getElementById('summary-purchase-price');
if (summaryPurchasePrice) {
- summaryPurchasePrice.textContent = purchasePrice ?
- `$${parseFloat(purchasePrice).toFixed(2)}` : 'Not specified';
+ if (purchasePrice) {
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ const amount = parseFloat(purchasePrice).toFixed(2);
+ summaryPurchasePrice.innerHTML = formatCurrencyHTML(amount, symbol, position);
+ } else {
+ summaryPurchasePrice.textContent = 'Not specified';
+ }
}
// Documents
@@ -1115,12 +1183,18 @@ function resetForm() {
}
async function exportWarranties() {
+ console.log('[EXPORT DEBUG] Starting export process');
+ console.log('[EXPORT DEBUG] Total warranties in memory:', warranties.length);
+ console.log('[EXPORT DEBUG] Current filters:', currentFilters);
+
// Get filtered warranties
let warrantiesToExport = [...warranties];
+ console.log('[EXPORT DEBUG] Initial warranties to export:', warrantiesToExport.length);
// Apply current filters
if (currentFilters.search) {
const searchTerm = currentFilters.search.toLowerCase();
+ console.log('[EXPORT DEBUG] Applying search filter:', searchTerm);
warrantiesToExport = warrantiesToExport.filter(warranty => {
// Check if product name contains search term
const productNameMatch = warranty.product_name.toLowerCase().includes(searchTerm);
@@ -1135,23 +1209,49 @@ async function exportWarranties() {
// Return true if either product name, tag name, or vendor name matches
return productNameMatch || tagMatch || vendorMatch;
});
+ console.log('[EXPORT DEBUG] After search filter:', warrantiesToExport.length);
}
if (currentFilters.status !== 'all') {
+ console.log('[EXPORT DEBUG] Applying status filter:', currentFilters.status);
warrantiesToExport = warrantiesToExport.filter(warranty =>
warranty.status === currentFilters.status
);
+ console.log('[EXPORT DEBUG] After status filter:', warrantiesToExport.length);
}
// Apply tag filter
if (currentFilters.tag !== 'all') {
const tagId = parseInt(currentFilters.tag);
+ console.log('[EXPORT DEBUG] Applying tag filter:', tagId);
warrantiesToExport = warrantiesToExport.filter(warranty =>
warranty.tags && Array.isArray(warranty.tags) &&
warranty.tags.some(tag => tag.id === tagId)
);
+ console.log('[EXPORT DEBUG] After tag filter:', warrantiesToExport.length);
+ }
+
+ // Apply vendor filter
+ if (currentFilters.vendor !== 'all') {
+ console.log('[EXPORT DEBUG] Applying vendor filter:', currentFilters.vendor);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ (warranty.vendor || '').toLowerCase() === currentFilters.vendor.toLowerCase()
+ );
+ console.log('[EXPORT DEBUG] After vendor filter:', warrantiesToExport.length);
+ }
+
+ // Apply warranty type filter
+ if (currentFilters.warranty_type !== 'all') {
+ console.log('[EXPORT DEBUG] Applying warranty type filter:', currentFilters.warranty_type);
+ warrantiesToExport = warrantiesToExport.filter(warranty =>
+ (warranty.warranty_type || '').toLowerCase() === currentFilters.warranty_type.toLowerCase()
+ );
+ console.log('[EXPORT DEBUG] After warranty type filter:', warrantiesToExport.length);
}
+ console.log('[EXPORT DEBUG] Final warranties to export:', warrantiesToExport.length);
+ console.log('[EXPORT DEBUG] Warranty IDs being exported:', warrantiesToExport.map(w => w.id));
+
// Create CSV content
let csvContent = "data:text/csv;charset=utf-8,";
@@ -1205,7 +1305,7 @@ async function exportWarranties() {
document.body.removeChild(link);
// Show success notification
- showToast('Warranties exported successfully', 'success');
+ showToast(`Exported ${warrantiesToExport.length} warranties successfully`, 'success');
}
// Switch view of warranties list
@@ -1697,9 +1797,15 @@ async function loadWarranties(isAuthenticated) { // Added isAuthenticated parame
*/
// --- END REDUNDANT PREFERENCE FETCH ---
- // Use the appropriate API endpoint based on view mode
+ // Check saved view scope preference to determine which API endpoint to use
+ const savedScope = loadViewScopePreference();
+ const shouldUseGlobalView = savedScope === 'global';
+
+ // Use the appropriate API endpoint based on saved preference
const baseUrl = window.location.origin;
- const apiUrl = isGlobalView ? `${baseUrl}/api/warranties/global` : `${baseUrl}/api/warranties`;
+ const apiUrl = shouldUseGlobalView ? `${baseUrl}/api/warranties/global` : `${baseUrl}/api/warranties`;
+
+ console.log(`[DEBUG] Using API endpoint based on saved preference '${savedScope}': ${apiUrl}`);
// Check if auth is available and user is authenticated using the passed parameter
if (!isAuthenticated) {
@@ -1738,6 +1844,10 @@ async function loadWarranties(isAuthenticated) { // Added isAuthenticated parame
if (!Array.isArray(data)) {
console.error('[DEBUG] API did not return an array! Data:', data);
}
+
+ // Update isGlobalView to match the loaded data
+ isGlobalView = shouldUseGlobalView;
+ console.log(`[DEBUG] Set isGlobalView to: ${isGlobalView}`);
// Process each warranty to calculate status and days remaining
warranties = Array.isArray(data) ? data.map(warranty => {
const processed = processWarrantyData(warranty);
@@ -1745,6 +1855,8 @@ async function loadWarranties(isAuthenticated) { // Added isAuthenticated parame
return processed;
}) : [];
console.log('[DEBUG] Final warranties array:', warranties);
+ console.log('[DEBUG] Total warranties loaded:', warranties.length);
+ console.log('[DEBUG] Warranty IDs loaded:', warranties.map(w => w.id));
if (warranties.length === 0) {
console.log('No warranties found, showing empty state');
@@ -1829,6 +1941,80 @@ function formatDateYYYYMMDD(date) {
return `${year}-${month}-${day}`;
}
+/**
+ * Calculate the age of a product from purchase date to now
+ * @param {string|Date} purchaseDate - The purchase date
+ * @returns {string} - Formatted age string (e.g., "2 years, 3 months", "6 months", "15 days")
+ */
+function calculateProductAge(purchaseDate) {
+ if (!purchaseDate) return 'Unknown';
+
+ const purchase = new Date(purchaseDate);
+ const now = new Date();
+
+ if (isNaN(purchase.getTime()) || purchase > now) {
+ return 'Unknown';
+ }
+
+ // Calculate the difference
+ let years = now.getFullYear() - purchase.getFullYear();
+ let months = now.getMonth() - purchase.getMonth();
+ let days = now.getDate() - purchase.getDate();
+
+ // Adjust for negative days
+ if (days < 0) {
+ months--;
+ const lastMonth = new Date(now.getFullYear(), now.getMonth(), 0);
+ days += lastMonth.getDate();
+ }
+
+ // Adjust for negative months
+ if (months < 0) {
+ years--;
+ months += 12;
+ }
+
+ // Format the result
+ const parts = [];
+ if (years > 0) {
+ parts.push(`${years} year${years !== 1 ? 's' : ''}`);
+ }
+ if (months > 0) {
+ parts.push(`${months} month${months !== 1 ? 's' : ''}`);
+ }
+ if (days > 0 && years === 0) { // Only show days if less than a year old
+ parts.push(`${days} day${days !== 1 ? 's' : ''}`);
+ }
+
+ if (parts.length === 0) {
+ return 'Today'; // Purchased today
+ }
+
+ return parts.join(', ');
+}
+
+/**
+ * Calculate the age of a product in days for sorting purposes
+ * @param {string|Date} purchaseDate - The purchase date
+ * @returns {number} - Age in days (0 if invalid date)
+ */
+function calculateProductAgeInDays(purchaseDate) {
+ if (!purchaseDate) return 0;
+
+ const purchase = new Date(purchaseDate);
+ const now = new Date();
+
+ if (isNaN(purchase.getTime()) || purchase > now) {
+ return 0;
+ }
+
+ // Calculate difference in milliseconds and convert to days
+ const diffTime = now.getTime() - purchase.getTime();
+ const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
+
+ return diffDays;
+}
+
async function renderWarranties(warrantiesToRender) {
console.log('renderWarranties called with:', warrantiesToRender);
@@ -1846,7 +2032,7 @@ async function renderWarranties(warrantiesToRender) {
}
const today = new Date();
- const symbol = getCurrencySymbol(); // Get the correct symbol HERE
+ const globalSymbol = getCurrencySymbol(); // Get the global symbol as fallback
warrantiesList.innerHTML = '';
@@ -1857,6 +2043,8 @@ async function renderWarranties(warrantiesToRender) {
return (a.product_name || '').toLowerCase().localeCompare((b.product_name || '').toLowerCase());
case 'purchase':
return new Date(b.purchase_date || 0) - new Date(a.purchase_date || 0);
+ case 'age': // Added age sorting
+ return calculateProductAgeInDays(b.purchase_date) - calculateProductAgeInDays(a.purchase_date); // Oldest first
case 'vendor': // Added vendor sorting
return (a.vendor || '').toLowerCase().localeCompare((b.vendor || '').toLowerCase());
case 'warranty_type': // Added warranty type sorting
@@ -1935,6 +2123,10 @@ async function renderWarranties(warrantiesToRender) {
}
}
const expirationDateText = isLifetime ? 'Lifetime' : formatDate(expirationDate);
+
+ // Calculate product age
+ const productAge = calculateProductAge(warranty.purchase_date);
+
// Make sure serial numbers array exists and is valid
const validSerialNumbers = Array.isArray(warranty.serial_numbers)
? warranty.serial_numbers.filter(sn => sn && typeof sn === 'string' && sn.trim() !== '')
@@ -2002,7 +2194,7 @@ async function renderWarranties(warrantiesToRender) {
<div class="product-photo-thumbnail">
<a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">
<img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"
- style="width: 60px; height: 60px; object-fit: cover; border-radius: 8px; border: 2px solid var(--border-color); cursor: pointer;"
+ style="width: 80px; height: 80px; object-fit: cover; border-radius: 8px; border: 2px solid var(--border-color); cursor: pointer;"
onerror="this.style.display='none'" class="secure-image">
</a>
</div>
@@ -2020,9 +2212,10 @@ async function renderWarranties(warrantiesToRender) {
<div class="warranty-info">
${userInfoHtml}
<div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
+ <div>Age: <span>${productAge}</span></div>
<div>Warranty: <span>${warrantyDurationText}</span></div>
<div>Expires: <span>${expirationDateText}</span></div>
- ${warranty.purchase_price ? `<div><span>Price: </span><span class="currency-symbol">${symbol}</span><span>${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
+ ${warranty.purchase_price ? `<div><span>Price: </span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</div>` : ''}
${warranty.vendor ? `<div>Vendor: <span>${warranty.vendor}</span></div>` : ''}
${warranty.warranty_type ? `<div>Type: <span>${warranty.warranty_type}</span></div>` : ''}
${validSerialNumbers.length > 0 ? `
@@ -2068,7 +2261,7 @@ async function renderWarranties(warrantiesToRender) {
<div class="product-photo-thumbnail">
<a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">
<img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"
- style="width: 50px; height: 50px; object-fit: cover; border-radius: 6px; border: 2px solid var(--border-color); cursor: pointer;"
+ style="width: 70px; height: 70px; object-fit: cover; border-radius: 6px; border: 2px solid var(--border-color); cursor: pointer;"
onerror="this.style.display='none'" class="secure-image">
</a>
</div>
@@ -2086,9 +2279,10 @@ async function renderWarranties(warrantiesToRender) {
<div class="warranty-info">
${userInfoHtml}
<div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
+ <div>Age: <span>${productAge}</span></div>
<div>Warranty: <span>${warrantyDurationText}</span></div>
<div>Expires: <span>${expirationDateText}</span></div>
- ${warranty.purchase_price ? `<div><span>Price: </span><span class="currency-symbol">${symbol}</span><span>${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
+ ${warranty.purchase_price ? `<div><span>Price: </span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</div>` : ''}
${warranty.vendor ? `<div>Vendor: <span>${warranty.vendor}</span></div>` : ''}
${warranty.warranty_type ? `<div>Type: <span>${warranty.warranty_type}</span></div>` : ''}
${validSerialNumbers.length > 0 ? `
@@ -2134,7 +2328,7 @@ async function renderWarranties(warrantiesToRender) {
<div class="product-photo-thumbnail">
<a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">
<img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"
- style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px; border: 1px solid var(--border-color); cursor: pointer;"
+ style="width: 55px; height: 55px; object-fit: cover; border-radius: 4px; border: 1px solid var(--border-color); cursor: pointer;"
onerror="this.style.display='none'" class="secure-image">
</a>
</div>
@@ -2152,7 +2346,9 @@ async function renderWarranties(warrantiesToRender) {
<div class="warranty-info">
${userInfoHtml}
<div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
+ <div>Age: <span>${productAge}</span></div>
<div>Expires: <span>${expirationDateText}</span></div>
+ ${warranty.purchase_price ? `<div><span>Price: </span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</div>` : ''}
</div>
</div>
<div class="warranty-status-row status-${statusClass}">
@@ -2192,13 +2388,13 @@ async function renderWarranties(warrantiesToRender) {
// Edit button event listener
const editBtn = cardElement.querySelector('.edit-btn');
if (editBtn) {
- editBtn.addEventListener('click', () => {
+ editBtn.addEventListener('click', async () => {
console.log('[DEBUG] Edit button clicked for warranty ID:', warranty.id);
// Find the current warranty data instead of using the potentially stale warranty object
const currentWarranty = warranties.find(w => w.id === warranty.id);
console.log('[DEBUG] Found current warranty:', currentWarranty ? 'Yes' : 'No', currentWarranty?.notes);
if (currentWarranty) {
- openEditModal(currentWarranty);
+ await openEditModal(currentWarranty);
} else {
showToast('Warranty not found. Please refresh the page.', 'error');
}
@@ -2291,7 +2487,8 @@ function filterWarranties() {
}
function applyFilters() {
- console.log('Applying filters with:', currentFilters);
+ console.log('[FILTER DEBUG] Applying filters with:', currentFilters);
+ console.log('[FILTER DEBUG] Total warranties before filtering:', warranties.length);
// Filter warranties based on currentFilters
const filtered = warranties.filter(warranty => {
@@ -2344,18 +2541,22 @@ function applyFilters() {
return true;
});
- console.log('Filtered warranties:', filtered);
+ console.log('[FILTER DEBUG] Filtered warranties:', filtered.length);
+ console.log('[FILTER DEBUG] Filtered warranty IDs:', filtered.map(w => w.id));
// Render the filtered warranties
renderWarranties(filtered);
}
-function openEditModal(warranty) {
+async function openEditModal(warranty) {
// Close any existing modals first
closeModals();
currentWarrantyId = warranty.id;
+ // Load currencies for the dropdown and wait for it to complete
+ await loadCurrencies();
+
console.log('[DEBUG] Opening edit modal for warranty:', warranty.id, 'with notes:', warranty.notes);
// Populate form fields
@@ -2368,6 +2569,12 @@ function openEditModal(warranty) {
document.getElementById('editWarrantyDurationDays').value = warranty.warranty_duration_days || 0;
document.getElementById('editPurchasePrice').value = warranty.purchase_price || '';
+
+ // Set currency dropdown
+ const editCurrencySelect = document.getElementById('editCurrency');
+ if (editCurrencySelect && warranty.currency) {
+ editCurrencySelect.value = warranty.currency;
+ }
document.getElementById('editVendor').value = warranty.vendor || '';
// Handle warranty type - check if it's a predefined option or custom
@@ -2762,6 +2969,29 @@ function openEditModal(warranty) {
notesInput.value = warranty.notes || '';
}
+ // Update currency symbols and positioning for the edit form
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ updateFormCurrencyPosition(symbol, position);
+
+ // Trigger currency positioning after modal is visible
+ setTimeout(() => {
+ if (position === 'right') {
+ const editPriceInput = document.getElementById('editPurchasePrice');
+ const editCurrencySymbol = document.getElementById('editCurrencySymbol');
+ if (editPriceInput && editCurrencySymbol) {
+ // Force update the currency position now that modal is visible
+ const wrapper = editPriceInput.closest('.price-input-wrapper');
+ if (wrapper && wrapper.classList.contains('currency-right')) {
+ const updateEvent = new Event('focus');
+ editPriceInput.dispatchEvent(updateEvent);
+ const blurEvent = new Event('blur');
+ editPriceInput.dispatchEvent(blurEvent);
+ }
+ }
+ }
+ }, 200);
+
// Load secure images with authentication for the edit modal
setTimeout(() => loadSecureImages(), 100); // Small delay to ensure DOM is updated
}
@@ -4357,9 +4587,13 @@ function saveWarranty() {
}
const purchasePrice = document.getElementById('editPurchasePrice').value;
+ const currency = document.getElementById('editCurrency').value;
if (purchasePrice) {
formData.append('purchase_price', purchasePrice);
}
+ if (currency) {
+ formData.append('currency', currency);
+ }
// Serial numbers (use correct name 'serial_numbers[]')
const serialInputs = document.querySelectorAll('#editSerialNumbersContainer input[name="serial_numbers[]"]');
@@ -4792,6 +5026,36 @@ function setupModalTriggers() {
addWarrantyModal.classList.add('active');
initFormTabs(); // Initialize tabs only when modal is shown
switchToTab(0); // Ensure the first tab content is displayed correctly after reset
+
+ // Set currency dropdown to user's preferred currency after form reset
+ const preferredCurrencyCode = getCurrencyCode();
+ if (currencySelect && preferredCurrencyCode) {
+ currencySelect.value = preferredCurrencyCode;
+ console.log(`[Modal Open] Set currency dropdown to user preference: ${preferredCurrencyCode}`);
+ }
+
+ // Update currency symbols and positioning for the add form
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ updateFormCurrencyPosition(symbol, position);
+
+ // Trigger currency positioning after modal is visible
+ setTimeout(() => {
+ if (position === 'right') {
+ const addPriceInput = document.getElementById('purchasePrice');
+ const addCurrencySymbol = document.getElementById('addCurrencySymbol');
+ if (addPriceInput && addCurrencySymbol) {
+ // Force update the currency position now that modal is visible
+ const wrapper = addPriceInput.closest('.price-input-wrapper');
+ if (wrapper && wrapper.classList.contains('currency-right')) {
+ const updateEvent = new Event('focus');
+ addPriceInput.dispatchEvent(updateEvent);
+ const blurEvent = new Event('blur');
+ addPriceInput.dispatchEvent(blurEvent);
+ }
+ }
+ }
+ }, 200);
});
}
@@ -5015,7 +5279,7 @@ if (!document.getElementById('notesModal')) {
});
// Add event listener for Edit Warranty button
- document.getElementById('editWarrantyBtn').addEventListener('click', () => {
+ document.getElementById('editWarrantyBtn').addEventListener('click', async () => {
// Find the current warranty data from the global array
const currentWarranty = warranties.find(w => w.id === notesModalWarrantyId);
if (currentWarranty) {
@@ -5023,7 +5287,7 @@ if (!document.getElementById('notesModal')) {
// Close the notes modal first
notesModal.classList.remove('active');
// Open the edit modal with current data
- openEditModal(currentWarranty);
+ await openEditModal(currentWarranty);
} else {
showToast('Warranty not found. Please refresh the page.', 'error');
}
@@ -5255,15 +5519,287 @@ function getCurrencySymbol() {
return symbol;
}
+// Function to get user's preferred currency code
+function getCurrencyCode() {
+ // Use the global prefix determined after auth ready
+ let prefix = userPreferencePrefix;
+ if (!prefix) {
+ console.warn('[getCurrencyCode] User preference prefix not set yet, defaulting prefix to user_');
+ prefix = 'user_';
+ }
+ console.log(`[getCurrencyCode] Using determined prefix: ${prefix}`);
+
+ // Default to USD
+ let currencyCode = 'USD';
+
+ // Try to get currency code from localStorage
+ const rawValue = localStorage.getItem(`${prefix}currencyCode`);
+ console.log(`[getCurrencyCode Debug] Raw value read from localStorage key '${prefix}currencyCode':`, rawValue);
+
+ if (rawValue) {
+ currencyCode = rawValue;
+ console.log(`[getCurrencyCode] Loaded currency code from individual key (${prefix}currencyCode): ${currencyCode}`);
+ return currencyCode;
+ }
+
+ // Fallback: Try to derive currency code from symbol
+ const symbol = getCurrencySymbol();
+ const symbolToCurrencyMap = {
+ '$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'JPY', '₹': 'INR', '₩': 'KRW',
+ 'CHF': 'CHF', 'C$': 'CAD', 'A$': 'AUD', 'kr': 'SEK', 'zł': 'PLN',
+ 'Kč': 'CZK', 'Ft': 'HUF', '₽': 'RUB', 'R$': 'BRL', '₦': 'NGN',
+ '₪': 'ILS', '₺': 'TRY', '₨': 'PKR', '৳': 'BDT', '฿': 'THB',
+ '₫': 'VND', 'RM': 'MYR', 'S$': 'SGD', 'Rp': 'IDR', '₱': 'PHP',
+ 'NT$': 'TWD', 'HK$': 'HKD', '₮': 'MNT', '₸': 'KZT', '₼': 'AZN',
+ '₾': 'GEL', '₴': 'UAH', 'NZ$': 'NZD'
+ };
+
+ if (symbolToCurrencyMap[symbol]) {
+ currencyCode = symbolToCurrencyMap[symbol];
+ console.log(`[getCurrencyCode] Derived currency code from symbol '${symbol}': ${currencyCode}`);
+ } else {
+ console.log(`[getCurrencyCode] Could not derive currency code from symbol '${symbol}', using default: ${currencyCode}`);
+ }
+
+ return currencyCode;
+}
+
+// Function to load currencies from API and populate dropdowns
+async function loadCurrencies() {
+ try {
+ const response = await fetch('/api/currencies');
+ if (!response.ok) {
+ throw new Error('Failed to fetch currencies');
+ }
+
+ const currencies = await response.json();
+
+ // Get user's preferred currency code for default selection
+ const preferredCurrencyCode = getCurrencyCode();
+
+ // Populate add warranty currency dropdown
+ if (currencySelect) {
+ currencySelect.innerHTML = '';
+ currencies.forEach(currency => {
+ const option = document.createElement('option');
+ option.value = currency.code;
+ option.textContent = `${currency.code} - ${currency.name} (${currency.symbol})`;
+ currencySelect.appendChild(option);
+ });
+
+ // Set default selection to user's preferred currency
+ console.log(`[loadCurrencies] Preferred currency code: ${preferredCurrencyCode}`);
+ console.log(`[loadCurrencies] Available currency options:`, Array.from(currencySelect.options).map(opt => opt.value));
+
+ if (preferredCurrencyCode) {
+ // Use setTimeout to ensure DOM is fully updated
+ setTimeout(() => {
+ currencySelect.value = preferredCurrencyCode;
+ console.log(`[loadCurrencies] Set add warranty currency default to: ${preferredCurrencyCode}`);
+ console.log(`[loadCurrencies] Current selected value: ${currencySelect.value}`);
+
+ // Trigger change event to update any dependent UI
+ const changeEvent = new Event('change', { bubbles: true });
+ currencySelect.dispatchEvent(changeEvent);
+ }, 10);
+ } else {
+ console.log(`[loadCurrencies] No preferred currency code found, keeping default USD`);
+ }
+ }
+
+ // Populate edit warranty currency dropdown
+ if (editCurrencySelect) {
+ editCurrencySelect.innerHTML = '';
+ currencies.forEach(currency => {
+ const option = document.createElement('option');
+ option.value = currency.code;
+ option.textContent = `${currency.code} - ${currency.name} (${currency.symbol})`;
+ editCurrencySelect.appendChild(option);
+ });
+ }
+
+ console.log('Currencies loaded successfully');
+ } catch (error) {
+ console.error('Error loading currencies:', error);
+ // Fallback to USD if loading fails
+ if (currencySelect) {
+ currencySelect.innerHTML = '<option value="USD">USD - US Dollar ($)</option>';
+ }
+ if (editCurrencySelect) {
+ editCurrencySelect.innerHTML = '<option value="USD">USD - US Dollar ($)</option>';
+ }
+ }
+}
+
+function getCurrencySymbolByCode(currencyCode) {
+ const currencyMap = {
+ 'USD': '$', 'EUR': '€', 'GBP': '£', 'JPY': '¥', 'CNY': '¥', 'INR': '₹', 'KRW': '₩',
+ 'CHF': 'CHF', 'CAD': 'C$', 'AUD': 'A$', 'SEK': 'kr', 'NOK': 'kr', 'DKK': 'kr',
+ 'PLN': 'zł', 'CZK': 'Kč', 'HUF': 'Ft', 'BGN': 'лв', 'RON': 'lei', 'HRK': 'kn',
+ 'RUB': '₽', 'BRL': 'R$', 'MXN': '$', 'ARS': '$', 'CLP': '$', 'COP': '$',
+ 'PEN': 'S/', 'VES': 'Bs', 'ZAR': 'R', 'EGP': '£', 'NGN': '₦', 'KES': 'KSh',
+ 'GHS': '₵', 'MAD': 'DH', 'TND': 'DT', 'AED': 'AED', 'SAR': 'SR', 'QAR': 'QR',
+ 'KWD': 'KD', 'BHD': 'BD', 'OMR': 'OR', 'JOD': 'JD', 'LBP': 'LL', 'ILS': '₪',
+ 'TRY': '₺', 'IRR': '﷼', 'PKR': '₨', 'BDT': '৳', 'LKR': 'Rs', 'NPR': 'Rs',
+ 'BTN': 'Nu', 'MMK': 'K', 'THB': '฿', 'VND': '₫', 'LAK': '₭', 'KHR': '៛',
+ 'MYR': 'RM', 'SGD': 'S$', 'IDR': 'Rp', 'PHP': '₱', 'TWD': 'NT$', 'HKD': 'HK$',
+ 'MOP': 'MOP', 'KPW': '₩', 'MNT': '₮', 'KZT': '₸', 'UZS': 'soʻm', 'TJS': 'SM',
+ 'KGS': 'с', 'TMT': 'T', 'AFN': '؋', 'AMD': '֏', 'AZN': '₼', 'GEL': '₾',
+ 'MDL': 'L', 'UAH': '₴', 'BYN': 'Br', 'RSD': 'дин', 'MKD': 'ден', 'ALL': 'L',
+ 'BAM': 'KM', 'ISK': 'kr', 'FJD': 'FJ$', 'PGK': 'K', 'SBD': 'SI$', 'TOP': 'T$',
+ 'VUV': 'VT', 'WST': 'WS$', 'XPF': '₣', 'NZD': 'NZ$'
+ };
+ return currencyMap[currencyCode] || currencyCode;
+}
+
+function getCurrencyPosition() {
+ let prefix = userPreferencePrefix;
+ if (!prefix) {
+ console.warn('[getCurrencyPosition] User preference prefix not set yet, defaulting prefix to user_');
+ prefix = 'user_';
+ }
+
+ let position = 'left'; // Default position
+ const rawValue = localStorage.getItem(`${prefix}currencyPosition`);
+ console.log(`[getCurrencyPosition] Raw value from localStorage (${prefix}currencyPosition):`, rawValue);
+
+ if (rawValue) {
+ position = rawValue;
+ console.log(`[getCurrencyPosition] Loaded position from localStorage: ${position}`);
+ } else {
+ console.log(`[getCurrencyPosition] No position found, using default: ${position}`);
+ }
+
+ return position;
+}
+
+function formatCurrencyHTML(amount, symbol, position) {
+ const formattedAmount = parseFloat(amount).toFixed(2);
+
+ if (position === 'right') {
+ return `<span>${formattedAmount}</span><span class="currency-symbol currency-right">${symbol}</span>`;
+ } else {
+ return `<span class="currency-symbol">${symbol}</span><span>${formattedAmount}</span>`;
+ }
+}
+
function updateCurrencySymbols() {
const symbol = getCurrencySymbol();
- console.log(`Updating currency symbols to: ${symbol}`); // Log the symbol being applied
+ const position = getCurrencyPosition();
+ console.log(`Updating currency symbols to: ${symbol}, position: ${position}`);
+
+ // Update all currency symbols
const elements = document.querySelectorAll('.currency-symbol');
- console.log(`Found ${elements.length} elements with class 'currency-symbol'.`); // Log how many elements are found
+ console.log(`Found ${elements.length} elements with class 'currency-symbol'.`);
elements.forEach(el => {
- // console.log('Updating element:', el); // Optional: Log each element being updated
el.textContent = symbol;
});
+
+ // Update form currency positioning
+ updateFormCurrencyPosition(symbol, position);
+}
+
+function updateFormCurrencyPosition(symbol, position) {
+ // Handle add warranty form
+ const addPriceWrapper = document.getElementById('addPriceInputWrapper');
+ const addCurrencySymbol = document.getElementById('addCurrencySymbol');
+ const addPriceInput = document.getElementById('purchasePrice');
+
+ if (addPriceWrapper && addCurrencySymbol) {
+ addCurrencySymbol.textContent = symbol;
+ if (position === 'right') {
+ addPriceWrapper.classList.add('currency-right');
+ // Set up dynamic positioning for right-aligned currency
+ if (addPriceInput) {
+ setupDynamicCurrencyPosition(addPriceInput, addCurrencySymbol);
+ }
+ } else {
+ addPriceWrapper.classList.remove('currency-right');
+ // Reset any dynamic positioning
+ if (addCurrencySymbol) {
+ addCurrencySymbol.style.right = '';
+ }
+ }
+ console.log(`Updated add form currency position: ${position}`);
+ }
+
+ // Handle edit warranty form
+ const editPriceWrapper = document.getElementById('editPriceInputWrapper');
+ const editCurrencySymbol = document.getElementById('editCurrencySymbol');
+ const editPriceInput = document.getElementById('editPurchasePrice');
+
+ if (editPriceWrapper && editCurrencySymbol) {
+ editCurrencySymbol.textContent = symbol;
+ if (position === 'right') {
+ editPriceWrapper.classList.add('currency-right');
+ // Set up dynamic positioning for right-aligned currency
+ if (editPriceInput) {
+ setupDynamicCurrencyPosition(editPriceInput, editCurrencySymbol);
+ }
+ } else {
+ editPriceWrapper.classList.remove('currency-right');
+ // Reset any dynamic positioning
+ if (editCurrencySymbol) {
+ editCurrencySymbol.style.right = '';
+ }
+ }
+ console.log(`Updated edit form currency position: ${position}`);
+ }
+}
+
+function setupDynamicCurrencyPosition(input, currencySymbol) {
+ if (!input || !currencySymbol) return;
+
+ function updatePosition() {
+ const wrapper = input.closest('.price-input-wrapper');
+ if (!wrapper || !wrapper.classList.contains('currency-right')) return;
+
+ // Wait for elements to be fully rendered
+ if (wrapper.offsetWidth === 0) {
+ setTimeout(updatePosition, 50);
+ return;
+ }
+
+ // Get the input value or placeholder
+ const text = input.value || input.placeholder || '0.00';
+
+ // Create a temporary element to measure text width
+ const tempSpan = document.createElement('span');
+ tempSpan.style.visibility = 'hidden';
+ tempSpan.style.position = 'absolute';
+ tempSpan.style.fontSize = window.getComputedStyle(input).fontSize;
+ tempSpan.style.fontFamily = window.getComputedStyle(input).fontFamily;
+ tempSpan.style.fontWeight = window.getComputedStyle(input).fontWeight;
+ tempSpan.style.letterSpacing = window.getComputedStyle(input).letterSpacing;
+ tempSpan.textContent = text;
+
+ document.body.appendChild(tempSpan);
+ const textWidth = tempSpan.offsetWidth;
+ document.body.removeChild(tempSpan);
+
+ // Calculate position: input padding + text width + small gap
+ const inputPaddingLeft = parseInt(window.getComputedStyle(input).paddingLeft) || 12;
+ const gap = 4; // Small gap between text and currency symbol
+ const wrapperWidth = wrapper.offsetWidth;
+ const rightPosition = Math.max(8, wrapperWidth - inputPaddingLeft - textWidth - gap - 20);
+
+ currencySymbol.style.right = rightPosition + 'px';
+ console.log(`[Dynamic Currency] Positioned currency symbol at ${rightPosition}px from right for text: "${text}"`);
+ }
+
+ // Update position on various events
+ input.addEventListener('input', updatePosition);
+ input.addEventListener('focus', updatePosition);
+ input.addEventListener('blur', updatePosition);
+
+ // Initial positioning with better timing
+ // Use requestAnimationFrame to ensure DOM is ready
+ requestAnimationFrame(() => {
+ updatePosition();
+ // Also set up additional fallback timers
+ setTimeout(updatePosition, 100);
+ setTimeout(updatePosition, 300);
+ });
}
// If you want to update currency symbols live when storage changes (e.g. settings page open in another tab):
@@ -5274,6 +5810,18 @@ window.addEventListener('storage', function(e) {
console.log(`Storage event detected for ${prefix}preferences. Updating currency symbols.`);
updateCurrencySymbols();
}
+ // Also update when currency position changes
+ if (e.key === `${prefix}currencyPosition`) {
+ console.log(`Storage event detected for ${prefix}currencyPosition. Re-rendering warranties to update currency position.`);
+ // Update forms immediately
+ const symbol = getCurrencySymbol();
+ const position = getCurrencyPosition();
+ updateFormCurrencyPosition(symbol, position);
+ // Re-render warranties to apply new currency position
+ if (typeof processAllWarranties === 'function') {
+ processAllWarranties();
+ }
+ }
});
// +++ NEW FUNCTION TO LOAD PREFS AND SAVE TO LOCALSTORAGE +++
@@ -5313,6 +5861,10 @@ async function loadAndApplyUserPreferences(isAuthenticated) { // Added isAuthent
localStorage.setItem(`${prefix}currencySymbol`, apiPrefs.currency_symbol);
console.log(`[Prefs Loader] Saved ${prefix}currencySymbol: ${apiPrefs.currency_symbol}`);
}
+ if (apiPrefs.currency_position) {
+ localStorage.setItem(`${prefix}currencyPosition`, apiPrefs.currency_position);
+ console.log(`[Prefs Loader] Saved ${prefix}currencyPosition: ${apiPrefs.currency_position}`);
+ }
if (apiPrefs.default_view) {
localStorage.setItem(`${prefix}defaultView`, apiPrefs.default_view);
console.log(`[Prefs Loader] Saved ${prefix}defaultView: ${apiPrefs.default_view}`);
diff --git a/frontend/settings-new.html b/frontend/settings-new.html
index 6bd6bd6..aec3d11 100644
--- a/frontend/settings-new.html
+++ b/frontend/settings-new.html
@@ -17,17 +17,17 @@
<link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">
<link rel="manifest" href="manifest.json">
<!-- Load the main site styles first -->
- <link rel="stylesheet" href="style.css?v=20250529005">
+ <link rel="stylesheet" href="style.css?v=20250529006">
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Then load settings-specific styles -->
- <link rel="stylesheet" href="settings-styles.css?v=20250529005">
+ <link rel="stylesheet" href="settings-styles.css?v=20250529006">
<!-- Apply theme immediately -->
<script src="theme-loader.js"></script>
<!-- Load header fix styles last to override any conflicting styles -->
- <link rel="stylesheet" href="header-fix.css?v=20250529005">
+ <link rel="stylesheet" href="header-fix.css?v=20250529006">
<!-- Mobile Header specific styles -->
- <link rel="stylesheet" href="mobile-header.css?v=20250529005">
+ <link rel="stylesheet" href="mobile-header.css?v=20250529006">
<!-- Load fix for auth buttons -->
<script src="fix-auth-buttons-loader.js"></script>
@@ -216,21 +216,25 @@
<p class="text-muted">Choose the symbol to display for prices</p>
</div>
<select id="currencySymbolSelect" class="form-control" style="width: 120px; font-size: 1.1em;">
- <option value="$">$ (USD)</option>
- <option value="€">€ (EUR)</option>
- <option value="£">£ (GBP)</option>
- <option value="¥">¥ (JPY/CNY)</option>
- <option value="₹">₹ (INR)</option>
- <option value="₩">₩ (KRW)</option>
- <option value="CHF">CHF (Swiss Franc)</option>
- <option value="CAD">CAD (Canadian Dollar)</option>
- <option value="AUD">AUD (Australian Dollar)</option>
- <option value="other">Other...</option>
+ <option value="">Loading currencies...</option>
</select>
<input type="text" id="currencySymbolCustom" class="form-control" maxlength="6" style="width: 70px; text-align: center; font-size: 1.2em; display: none; margin-left: 10px;" placeholder="Custom">
</div>
</div>
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Currency Position</label>
+ <p class="text-muted">Choose whether currency symbol appears on the left or right of numbers</p>
+ </div>
+ <select id="currencyPositionSelect" class="form-control" style="width: 150px;">
+ <option value="left">Left ($100.00)</option>
+ <option value="right">Right (100.00$)</option>
+ </select>
+ </div>
+ </div>
+
<div class="form-group">
<div class="preference-item">
<div>
@@ -324,6 +328,45 @@
</div>
</div>
</div>
+
+ <div id="userAppriseSettingsContainer" style="display: none;">
+ <h4>Apprise Settings</h4>
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Apprise Notification Frequency</label>
+ <p class="text-muted">How often to receive Apprise notifications</p>
+ </div>
+ <select id="userAppriseNotificationFrequency" class="form-control">
+ <option value="daily">Daily</option>
+ <option value="weekly">Weekly</option>
+ <option value="monthly">Monthly</option>
+ </select>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Apprise Notification Time</label>
+ <p class="text-muted">Time of day to receive Apprise notifications (in 24-hour format)</p>
+ </div>
+ <input type="time" id="userAppriseNotificationTime" class="form-control" value="09:00">
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Apprise Timezone</label>
+ <p class="text-muted">Your local timezone for Apprise notifications</p>
+ </div>
+ <select id="userAppriseTimezone" class="form-control">
+ <option value="">Loading timezones...</option>
+ </select>
+ </div>
+ </div>
+ </div>
<button type="button" id="saveNotificationSettingsBtn" class="btn btn-primary">Save Notification Settings</button>
</form>
</div>
@@ -508,6 +551,19 @@
</div>
</div>
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label for="oidcOnlyMode">OIDC-Only Login Mode</label>
+ <p class="text-muted">Hide traditional username/password login form and only allow OIDC login. <strong>Warning:</strong> Ensure OIDC is properly configured before enabling this option.</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="oidcOnlyMode">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
<div class="form-group">
<label for="oidcProviderName">OIDC Provider Name</label>
<input type="text" id="oidcProviderName" class="form-control" placeholder="e.g., oidc, keycloak, google">
@@ -571,6 +627,39 @@
<div id="appriseSettingsContainer" style="display: none;">
<h4>Apprise Settings</h4>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Notification Mode</label>
+ <p class="text-muted">Choose how Apprise notifications are sent.</p>
+ </div>
+ <select id="appriseNotificationMode" class="form-control" style="max-width: 200px;">
+ <option value="global">Global Summary</option>
+ <option value="individual">Per User</option>
+ </select>
+ </div>
+ <div class="mode-description text-muted" id="appriseModeDescription" style="margin-top: 5px; padding-left: 10px; border-left: 2px solid var(--border-color);">
+ <!-- Description will be updated by JS -->
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Warranty Scope</label>
+ <p class="text-muted">Choose which warranties to include in notifications.</p>
+ </div>
+ <select id="appriseWarrantyScope" class="form-control" style="max-width: 200px;">
+ <option value="all">All Users' Warranties</option>
+ <option value="admin">Admin's Warranties Only</option>
+ </select>
+ </div>
+ <div class="scope-description text-muted" id="appriseScopeDescription" style="margin-top: 5px; padding-left: 10px; border-left: 2px solid var(--border-color);">
+ <!-- Description will be updated by JS -->
+ </div>
+ </div>
+
<div class="form-group">
<label for="appriseUrls">Notification URLs</label>
<textarea id="appriseUrls" class="form-control" rows="4" placeholder="Enter Apprise notification URLs, one per line or comma-separated:&#10;&#10;mailto://user:[email protected]&#10;discord://webhook_id/webhook_token&#10;slack://TokenA/TokenB/TokenC/Channel&#10;telegram://BotToken/ChatID"></textarea>
@@ -586,31 +675,11 @@
<small class="text-muted">Days before expiration to send notifications (comma-separated, e.g., "7,30" for 7 days and 30 days before)</small>
</div>
- <div class="form-group">
- <label for="appriseNotificationTime">Notification Time</label>
- <input type="time" id="appriseNotificationTime" class="form-control" value="09:00">
- <small class="text-muted">
- Time of day to send notifications (24-hour format)
- </small>
- </div>
-
- <div class="form-group">
- <div class="preference-item">
- <div>
- <label>Timezone</label>
- <p class="text-muted">Your local timezone for Apprise notifications</p>
- </div>
- <select id="appriseTimezone" class="form-control">
- <option value="">Loading timezones...</option>
- </select>
- </div>
- </div>
-
<div class="form-group">
<div class="preference-item">
<div>
- <label>Notification Frequency</label>
- <p class="text-muted">How often to receive email notifications</p>
+ <label>Check Frequency</label>
+ <p class="text-muted">How often the system checks for expiring warranties (global setting)</p>
</div>
<select id="appriseNotificationFrequency" class="form-control">
<option value="daily">Daily</option>
@@ -658,10 +727,7 @@
<span class="status-label">Notification Days:</span>
<span id="currentAppriseExpirationDays" class="status-value">-</span>
</div>
- <div class="status-item">
- <span class="status-label">Notification Time:</span>
- <span id="currentAppriseNotificationTime" class="status-value">-</span>
- </div>
+
</div>
</div>
@@ -681,6 +747,55 @@
</form>
</div>
</div>
+
+ </div>
+
+ <!-- Ownership Management Section - Only visible to the owner -->
+ <div id="ownershipSection" class="ownership-section" style="display: none;">
+ <h2><i class="fas fa-crown" style="color: #f39c12; margin-right: 8px;"></i>Ownership Management</h2>
+
+ <div id="ownershipCard" class="card danger-card">
+ <div class="card-header">
+ <h3>Transfer Ownership</h3>
+ </div>
+ <div class="card-body">
+ <p class="text-danger"><strong>Warning:</strong> Transfer application ownership to another admin user. This action is irreversible.</p>
+ <p>Once ownership is transferred, you will become a regular admin and the new owner will have ultimate control over the application.</p>
+ <div class="form-group">
+ <label for="newOwnerSelect">Select New Owner (must be an admin)</label>
+ <select id="newOwnerSelect" class="form-control">
+ <option value="">Select an admin user...</option>
+ </select>
+ </div>
+ <button id="transferOwnershipBtn" class="btn btn-danger" disabled>Transfer Ownership</button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Transfer Ownership Confirmation Modal -->
+ <div id="transferOwnershipModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3 class="modal-title"><i class="fas fa-crown" style="color: #f39c12; margin-right: 8px;"></i>Transfer Ownership</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <p class="text-danger"><strong>Warning: This action cannot be undone.</strong></p>
+ <p>You are about to transfer application ownership to <strong><span id="transferTargetUsername"></span></strong>.</p>
+ <p>After this transfer:</p>
+ <ul>
+ <li>You will become a regular admin</li>
+ <li>The new owner will have ultimate control over the application</li>
+ <li>Only the new owner can transfer ownership again</li>
+ </ul>
+ <p>To confirm, please type <strong>"TRANSFER"</strong> in the field below:</p>
+ <input type="text" id="transferConfirmInput" class="form-control" placeholder="Type TRANSFER to confirm">
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
+ <button id="confirmTransferOwnershipBtn" class="btn btn-danger" disabled>Transfer Ownership</button>
</div>
</div>
</div>
@@ -843,6 +958,39 @@
</div>
</div>
</div>
+
+ <!-- Users List Modal (Admin) -->
+ <div id="usersModal" class="modal-backdrop">
+ <div class="modal" style="max-width: 90%; width: 1000px;">
+ <div class="modal-header">
+ <h3 class="modal-title">Users List</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body" style="padding: 0;">
+ <div style="overflow-x: auto;">
+ <table style="width: 100%; border-collapse: collapse; margin: 0;">
+ <thead>
+ <tr style="background-color: var(--card-bg); border-bottom: 2px solid var(--border-color);">
+ <th style="padding: 12px 8px; text-align: left; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 40px;">ID</th>
+ <th style="padding: 12px 8px; text-align: left; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 120px;">Username</th>
+ <th style="padding: 12px 8px; text-align: left; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 180px;">Email</th>
+ <th style="padding: 12px 8px; text-align: left; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 120px;">Name</th>
+ <th style="padding: 12px 8px; text-align: center; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 80px;">Admin</th>
+ <th style="padding: 12px 8px; text-align: center; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 80px;">Active</th>
+ <th style="padding: 12px 8px; text-align: center; font-weight: 600; color: var(--text-color); min-width: 100px;">Actions</th>
+ </tr>
+ </thead>
+ <tbody id="usersTableBody">
+ <!-- Users will be populated here by loadUsers() -->
+ </tbody>
+ </table>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" data-dismiss="modal">Close</button>
+ </div>
+ </div>
+ </div>
<!-- Loading Container -->
<div id="loadingContainer" class="loading-container">
@@ -853,8 +1001,8 @@
<div id="toastContainer" class="toast-container"></div>
<!-- Scripts -->
- <script src="auth.js?v=20250529005"></script>
- <script src="settings-new.js?v=20250529005"></script>
+ <script src="auth.js?v=20250529006"></script>
+ <script src="settings-new.js?v=20250529006"></script>
<!-- Footer Width Fix -->
<script src="footer-fix.js"></script>
diff --git a/frontend/settings-new.js b/frontend/settings-new.js
index c719715..aa4d319 100644
--- a/frontend/settings-new.js
+++ b/frontend/settings-new.js
@@ -13,6 +13,7 @@ const saveNotificationSettingsBtn = document.getElementById('saveNotificationSet
const changePasswordBtn = document.getElementById('changePasswordBtn');
const emailSettingsContainer = document.getElementById('emailSettingsContainer');
const appriseSettingsContainer = document.getElementById('appriseSettingsContainer');
+const userAppriseSettingsContainer = document.getElementById('userAppriseSettingsContainer');
const passwordChangeForm = document.getElementById('passwordChangeForm');
const savePasswordBtn = document.getElementById('savePasswordBtn');
const cancelPasswordBtn = document.getElementById('cancelPasswordBtn');
@@ -27,6 +28,14 @@ const settingsBtn = document.getElementById('settingsBtn');
const settingsMenu = document.getElementById('settingsMenu');
const usersTableBody = document.getElementById('usersTableBody');
+// Edit User Modal Elements
+const editUserModal = document.getElementById('editUserModal');
+const editUserId = document.getElementById('editUserId');
+const editUsername = document.getElementById('editUsername');
+const editEmail = document.getElementById('editEmail');
+const editUserActive = document.getElementById('editUserActive');
+const editUserAdmin = document.getElementById('editUserAdmin');
+
// Form fields
const firstNameInput = document.getElementById('firstName');
const lastNameInput = document.getElementById('lastName');
@@ -49,6 +58,7 @@ const emailBaseUrlInput = document.getElementById('emailBaseUrl'); // Added for
// OIDC Settings DOM Elements
const oidcEnabledToggle = document.getElementById('oidcEnabled');
+const oidcOnlyModeToggle = document.getElementById('oidcOnlyMode');
const oidcProviderNameInput = document.getElementById('oidcProviderName');
const oidcClientIdInput = document.getElementById('oidcClientId');
const oidcClientSecretInput = document.getElementById('oidcClientSecret');
@@ -59,11 +69,18 @@ const oidcRestartMessage = document.getElementById('oidcRestartMessage');
// Apprise Settings DOM Elements
const appriseEnabledToggle = document.getElementById('appriseEnabled');
+const appriseNotificationModeSelect = document.getElementById('appriseNotificationMode');
+const appriseModeDescription = document.getElementById('appriseModeDescription');
+const appriseWarrantyScopeSelect = document.getElementById('appriseWarrantyScope');
+const appriseScopeDescription = document.getElementById('appriseScopeDescription');
const appriseUrlsTextarea = document.getElementById('appriseUrls');
const appriseExpirationDaysInput = document.getElementById('appriseExpirationDays');
-const appriseNotificationTimeInput = document.getElementById('appriseNotificationTime');
-const appriseTimezoneSelect = document.getElementById('appriseTimezone');
const appriseNotificationFrequency = document.getElementById('appriseNotificationFrequency');
+
+// User-specific Apprise settings (in notification settings section)
+const userAppriseNotificationTimeInput = document.getElementById('userAppriseNotificationTime');
+const userAppriseTimezoneSelect = document.getElementById('userAppriseTimezone');
+const userAppriseNotificationFrequency = document.getElementById('userAppriseNotificationFrequency');
const appriseTitlePrefixInput = document.getElementById('appriseTitlePrefix');
const appriseTestUrlInput = document.getElementById('appriseTestUrl');
const saveAppriseSettingsBtn = document.getElementById('saveAppriseSettingsBtn');
@@ -73,17 +90,72 @@ const triggerAppriseNotificationsBtn = document.getElementById('triggerAppriseNo
const appriseStatusBadge = document.getElementById('appriseStatusBadge');
const appriseUrlsCount = document.getElementById('appriseUrlsCount');
const currentAppriseExpirationDays = document.getElementById('currentAppriseExpirationDays');
-const currentAppriseNotificationTime = document.getElementById('currentAppriseNotificationTime');
+
const viewSupportedServicesBtn = document.getElementById('viewSupportedServicesBtn');
const appriseNotAvailable = document.getElementById('appriseNotAvailable');
const currencySymbolInput = document.getElementById('currencySymbol');
const currencySymbolSelect = document.getElementById('currencySymbolSelect');
const currencySymbolCustom = document.getElementById('currencySymbolCustom');
+const currencyPositionSelect = document.getElementById('currencyPositionSelect');
// Add dateFormatSelect near other DOM element declarations if not already there
const dateFormatSelect = document.getElementById('dateFormat');
+// Global variable to store currencies data for currency code lookup
+let globalCurrenciesData = [];
+
+/**
+ * Load currencies from the API and populate the currency dropdown
+ */
+async function loadCurrenciesForSettings() {
+ try {
+ const response = await fetch('/api/currencies');
+ if (!response.ok) {
+ throw new Error('Failed to fetch currencies');
+ }
+
+ const currencies = await response.json();
+
+ // Store currencies data globally for currency code lookup
+ globalCurrenciesData = currencies;
+
+ // Populate currency symbol dropdown
+ if (currencySymbolSelect) {
+ // Clear existing options
+ currencySymbolSelect.innerHTML = '';
+
+ // Add currencies from API
+ currencies.forEach(currency => {
+ const option = document.createElement('option');
+ option.value = currency.symbol;
+ option.textContent = `${currency.symbol} (${currency.code} - ${currency.name})`;
+ currencySymbolSelect.appendChild(option);
+ });
+
+ // Add "Other..." option at the end
+ const otherOption = document.createElement('option');
+ otherOption.value = 'other';
+ otherOption.textContent = 'Other...';
+ currencySymbolSelect.appendChild(otherOption);
+ }
+
+ console.log('Currencies loaded successfully for settings page');
+ } catch (error) {
+ console.error('Error loading currencies for settings:', error);
+ // Fallback to default currencies if loading fails
+ if (currencySymbolSelect) {
+ currencySymbolSelect.innerHTML = `
+ <option value="$">$ (USD - US Dollar)</option>
+ <option value="€">€ (EUR - Euro)</option>
+ <option value="£">£ (GBP - British Pound)</option>
+ <option value="¥">¥ (JPY - Japanese Yen)</option>
+ <option value="other">Other...</option>
+ `;
+ }
+ }
+}
+
/**
* Set theme (dark/light) - Unified and persistent
* @param {boolean} isDark - Whether to use dark mode
@@ -171,6 +243,13 @@ function initDarkModeToggle() {
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM fully loaded, initializing settings page');
+ // DEBUG: Check current user data
+ const debugCurrentUser = window.auth && window.auth.getCurrentUser ? window.auth.getCurrentUser() : null;
+ console.log('DEBUG: Current user data:', debugCurrentUser);
+ if (debugCurrentUser) {
+ console.log('DEBUG: User has is_owner field:', 'is_owner' in debugCurrentUser, 'Value:', debugCurrentUser.is_owner);
+ }
+
// Set up event listeners
setupEventListeners(); // Ensure this doesn't also try to init settings menu
@@ -221,6 +300,20 @@ document.addEventListener('DOMContentLoaded', function() {
// Load Apprise site settings (also loads overall Apprise settings)
loadAppriseSiteSettings();
+
+ // Initialize ownership management if user is owner
+ if (currentUser.is_owner) {
+ console.log('DEBUG: User is owner, initializing ownership management');
+ setTimeout(() => {
+ const ownershipSection = document.getElementById('ownershipSection');
+ if (ownershipSection) {
+ ownershipSection.style.display = 'block';
+ console.log('DEBUG: Ownership section made visible');
+ }
+ // Don't load users here - wait for modal to open
+ console.log('DEBUG: Ownership management initialized, users will load when modal opens');
+ }, 500); // Wait for DOM to be ready
+ }
} else {
console.log('User is not admin, skipping admin-only settings load during initialization');
}
@@ -619,8 +712,12 @@ async function loadPreferences() {
console.log(`${prefix}defaultView not found, defaulting view to grid`);
}
- // Currency Symbol
+ // Currency Symbol - Load stored preference first
const storedCurrency = localStorage.getItem(`${prefix}currencySymbol`);
+
+ // Load currencies from API and set the saved preference
+ await loadCurrenciesForSettings();
+
if (storedCurrency) {
if (currencySymbolSelect) {
// Check if the stored symbol is a standard option
@@ -628,6 +725,7 @@ async function loadPreferences() {
if (standardOption) {
currencySymbolSelect.value = storedCurrency;
if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
+ console.log(`Set currency dropdown to stored value: ${storedCurrency}`);
} else {
// It's a custom symbol
currencySymbolSelect.value = 'other';
@@ -635,6 +733,7 @@ async function loadPreferences() {
currencySymbolCustom.value = storedCurrency;
currencySymbolCustom.style.display = 'inline-block';
}
+ console.log(`Set currency to custom value: ${storedCurrency}`);
}
console.log(`Loaded currency symbol from ${prefix}currencySymbol: ${storedCurrency}`);
}
@@ -645,6 +744,16 @@ async function loadPreferences() {
console.log(`${prefix}currencySymbol not found, defaulting to $`);
}
+ // Currency Position
+ const storedCurrencyPosition = localStorage.getItem(`${prefix}currencyPosition`);
+ if (storedCurrencyPosition && currencyPositionSelect) {
+ currencyPositionSelect.value = storedCurrencyPosition;
+ console.log(`Loaded currency position from ${prefix}currencyPosition: ${storedCurrencyPosition}`);
+ } else if (currencyPositionSelect) {
+ currencyPositionSelect.value = 'left'; // Default
+ console.log(`${prefix}currencyPosition not found, defaulting to left`);
+ }
+
// Expiring Soon Days
const storedExpiringDays = localStorage.getItem(`${prefix}expiringSoonDays`);
if (storedExpiringDays && expiringSoonDaysInput) {
@@ -692,6 +801,18 @@ async function loadPreferences() {
}
}
// --- END MODIFIED CURRENCY SYMBOL HANDLING ---
+
+ // --- CURRENCY POSITION HANDLING ---
+ const storedCurrencyPosition = localStorage.getItem(`${prefix}currencyPosition`);
+ if (apiPrefs.currency_position && currencyPositionSelect) {
+ if (!storedCurrencyPosition || apiPrefs.currency_position !== storedCurrencyPosition) {
+ console.log(`API currency_position (${apiPrefs.currency_position}) differs from localStorage (${storedCurrencyPosition}). Updating UI.`);
+ currencyPositionSelect.value = apiPrefs.currency_position;
+ } else {
+ console.log(`API currency_position (${apiPrefs.currency_position}) matches localStorage (${storedCurrencyPosition}). Skipping UI update.`);
+ }
+ }
+ // --- END CURRENCY POSITION HANDLING ---
if (apiPrefs.expiring_soon_days && expiringSoonDaysInput) {
// Only update if different from localStorage value (or if localStorage was empty)
const storedExpiringDays = localStorage.getItem(`${prefix}expiringSoonDays`) || '30'; // Default if null
@@ -724,22 +845,28 @@ async function loadPreferences() {
if (notificationTimeInput && apiPrefs.notification_time) {
notificationTimeInput.value = apiPrefs.notification_time.substring(0, 5); // HH:MM format
}
- if (appriseNotificationTimeInput && apiPrefs.apprise_notification_time) {
- appriseNotificationTimeInput.value = apiPrefs.apprise_notification_time.substring(0, 5);
+ // Admin Apprise settings (in Apprise card)
+ if (appriseNotificationFrequency && apiPrefs.apprise_notification_frequency) {
+ appriseNotificationFrequency.value = apiPrefs.apprise_notification_frequency;
+ }
+
+ // User-specific Apprise settings (in notification settings section)
+ if (userAppriseNotificationTimeInput && apiPrefs.apprise_notification_time) {
+ userAppriseNotificationTimeInput.value = apiPrefs.apprise_notification_time.substring(0, 5);
}
- if (appriseTimezoneSelect && apiPrefs.apprise_timezone) {
- if (Array.from(appriseTimezoneSelect.options).some(option => option.value === apiPrefs.apprise_timezone)) {
- appriseTimezoneSelect.value = apiPrefs.apprise_timezone;
+ if (userAppriseTimezoneSelect && apiPrefs.apprise_timezone) {
+ if (Array.from(userAppriseTimezoneSelect.options).some(option => option.value === apiPrefs.apprise_timezone)) {
+ userAppriseTimezoneSelect.value = apiPrefs.apprise_timezone;
} else {
- console.warn(`Apprise timezone '${apiPrefs.apprise_timezone}' from API not found in dropdown.`);
+ console.warn(`User Apprise timezone '${apiPrefs.apprise_timezone}' from API not found in dropdown.`);
}
}
+ if (userAppriseNotificationFrequency && apiPrefs.apprise_notification_frequency) {
+ userAppriseNotificationFrequency.value = apiPrefs.apprise_notification_frequency;
+ }
// Update Apprise timezone display
updateAppriseTimezoneDisplay(apiPrefs.timezone);
- if (appriseNotificationFrequency && apiPrefs.apprise_notification_frequency) {
- appriseNotificationFrequency.value = apiPrefs.apprise_notification_frequency;
- }
// Load and set timezone from API
if (timezoneSelect && apiPrefs.timezone) {
console.log('API provided timezone:', apiPrefs.timezone);
@@ -904,7 +1031,16 @@ function setupEventListeners() {
if (showUsersBtn) {
showUsersBtn.addEventListener('click', function() {
- showUsersList();
+ console.log('Show Users List button clicked');
+ // Open the proper users modal that has crown icons and ownership management
+ const usersModal = document.getElementById('usersModal');
+ if (usersModal) {
+ openModal(usersModal);
+ loadUsers(); // This will populate the table with crown icons
+ } else {
+ console.error('usersModal not found, falling back to showUsersList');
+ showUsersList();
+ }
});
}
@@ -944,6 +1080,16 @@ function setupEventListeners() {
if (saveNotificationSettingsBtn) {
saveNotificationSettingsBtn.addEventListener('click', saveNotificationSettings);
}
+
+ // Save user changes button (Edit User Modal)
+ const saveUserBtn = document.getElementById('saveUserBtn');
+ if (saveUserBtn) {
+ saveUserBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ console.log('Save User button clicked');
+ saveUserChanges();
+ });
+ }
// Add timezone change listener to update Apprise timezone display
const timezoneSelect = document.getElementById('timezone');
@@ -953,8 +1099,10 @@ function setupEventListeners() {
});
}
- if (appriseTimezoneSelect) {
- loadTimezonesIntoSelect(appriseTimezoneSelect);
+
+
+ if (userAppriseTimezoneSelect) {
+ loadTimezonesIntoSelect(userAppriseTimezoneSelect);
}
if (notificationChannel) {
@@ -1016,6 +1164,19 @@ function initModals() {
} else {
console.error('deleteUserModal not found in initModals');
}
+
+ // Set up transfer ownership modal close handlers
+ const transferOwnershipModal = document.getElementById('transferOwnershipModal');
+ if (transferOwnershipModal) {
+ const transferConfirmInput = document.getElementById('transferConfirmInput');
+ const confirmTransferBtn = document.getElementById('confirmTransferOwnershipBtn');
+
+ if (transferConfirmInput && confirmTransferBtn) {
+ transferConfirmInput.addEventListener('input', function() {
+ confirmTransferBtn.disabled = this.value.toUpperCase() !== 'TRANSFER';
+ });
+ }
+ }
}
/**
@@ -1204,20 +1365,37 @@ async function savePreferences() {
// Handle currency symbol (standard or custom)
let currencySymbol = '$'; // Default
+ let currencyCode = 'USD'; // Default
if (currencySymbolSelect) {
if (currencySymbolSelect.value === 'other' && currencySymbolCustom) {
currencySymbol = currencySymbolCustom.value.trim() || '$'; // Use custom or default to $ if empty
+ // For custom symbols, try to derive currency code or default to USD
+ currencyCode = 'USD'; // Default for custom symbols
} else {
currencySymbol = currencySymbolSelect.value;
+ // Find the currency code for the selected symbol
+ const selectedCurrency = globalCurrenciesData.find(currency => currency.symbol === currencySymbol);
+ if (selectedCurrency) {
+ currencyCode = selectedCurrency.code;
+ }
}
}
preferencesToSave.currency_symbol = currencySymbol;
+
+ // Handle currency position
+ let currencyPosition = 'left'; // Default
+ if (currencyPositionSelect) {
+ currencyPosition = currencyPositionSelect.value;
+ }
+ preferencesToSave.currency_position = currencyPosition;
// --- End data preparation ---
// +++ ADDED DEBUG LOGGING +++
console.log(`[SavePrefs Debug] Currency Select Value: ${currencySymbolSelect ? currencySymbolSelect.value : 'N/A'}`);
console.log(`[SavePrefs Debug] Custom Input Value: ${currencySymbolCustom ? currencySymbolCustom.value : 'N/A'}`);
console.log(`[SavePrefs Debug] Final currencySymbol value determined: ${currencySymbol}`);
+ console.log(`[SavePrefs Debug] Final currencyCode value determined: ${currencyCode}`);
+ console.log(`[SavePrefs Debug] Currency Position Value: ${currencyPosition}`);
console.log(`[SavePrefs Debug] Theme being saved: ${preferencesToSave.theme} (from isDark: ${isDark})`);
// +++ END DEBUG LOGGING +++
@@ -1229,6 +1407,8 @@ async function savePreferences() {
localStorage.setItem('dateFormat', preferencesToSave.date_format); // Added
localStorage.setItem(`${prefix}defaultView`, preferencesToSave.default_view);
localStorage.setItem(`${prefix}currencySymbol`, preferencesToSave.currency_symbol);
+ localStorage.setItem(`${prefix}currencyCode`, currencyCode); // Save currency code
+ localStorage.setItem(`${prefix}currencyPosition`, preferencesToSave.currency_position);
localStorage.setItem(`${prefix}expiringSoonDays`, preferencesToSave.expiring_soon_days);
console.log('Preferences saved to localStorage (prefix:', prefix, '):', preferencesToSave);
@@ -1490,60 +1670,164 @@ async function loadUsers() {
if (response.ok) {
const users = await response.json();
+ // DEBUG: Check users data
+ console.log('DEBUG: Users data from API:', users);
+ users.forEach((user, index) => {
+ console.log(`DEBUG: User ${index} (${user.username}):`, {
+ id: user.id,
+ is_owner: user.is_owner,
+ is_admin: user.is_admin
+ });
+ });
+
// Clear table
usersTableBody.innerHTML = '';
// Add users to table
users.forEach(user => {
const row = document.createElement('tr');
+ row.style.borderBottom = '1px solid var(--border-color)';
+ row.style.transition = 'background-color 0.2s ease';
- // Username
+ // Add hover effect
+ row.addEventListener('mouseenter', () => {
+ row.style.backgroundColor = 'var(--hover-bg, rgba(0,0,0,0.05))';
+ });
+ row.addEventListener('mouseleave', () => {
+ row.style.backgroundColor = 'transparent';
+ });
+
+ // ID
+ const idCell = document.createElement('td');
+ idCell.textContent = user.id;
+ idCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-weight: 500;';
+ row.appendChild(idCell);
+
+ // Username with crown
const usernameCell = document.createElement('td');
- usernameCell.textContent = user.username;
+ const crownIcon = user.is_owner ? ' <i class="fas fa-crown" title="Application Owner" style="color: #f39c12; margin-left: 5px;"></i>' : '';
+ console.log(`DEBUG: User ${user.username} (ID: ${user.id}) - is_owner: ${user.is_owner}, adding crown: ${!!user.is_owner}`);
+ usernameCell.innerHTML = user.username + crownIcon;
+ usernameCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-weight: 500;';
row.appendChild(usernameCell);
// Email
const emailCell = document.createElement('td');
emailCell.textContent = user.email;
+ emailCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-size: 0.9em;';
row.appendChild(emailCell);
// Name
const nameCell = document.createElement('td');
const fullName = `${user.first_name || ''} ${user.last_name || ''}`.trim();
nameCell.textContent = fullName || '-';
+ nameCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color);';
row.appendChild(nameCell);
- // Status
- const statusCell = document.createElement('td');
- const statusBadge = document.createElement('span');
- statusBadge.className = `badge ${user.is_active ? 'badge-success' : 'badge-danger'}`;
- statusBadge.textContent = user.is_active ? 'Active' : 'Inactive';
- statusCell.appendChild(statusBadge);
- row.appendChild(statusCell);
-
// Admin
const adminCell = document.createElement('td');
const adminBadge = document.createElement('span');
- adminBadge.className = `badge ${user.is_admin ? 'badge-primary' : 'badge-secondary'}`;
- adminBadge.textContent = user.is_admin ? 'Admin' : 'User';
+ adminBadge.className = `badge ${user.is_admin ? 'badge-success' : 'badge-secondary'}`;
+ adminBadge.textContent = user.is_admin ? 'Yes' : 'No';
+ adminBadge.style.cssText = 'padding: 4px 8px; border-radius: 12px; font-size: 0.75em; font-weight: 600;';
adminCell.appendChild(adminBadge);
+ adminCell.style.cssText = 'padding: 12px 8px; text-align: center; border-right: 1px solid var(--border-color);';
row.appendChild(adminCell);
+ // Active Status
+ const statusCell = document.createElement('td');
+ const statusBadge = document.createElement('span');
+ statusBadge.className = `badge ${user.is_active ? 'badge-success' : 'badge-danger'}`;
+ statusBadge.textContent = user.is_active ? 'Yes' : 'No';
+ statusBadge.style.cssText = 'padding: 4px 8px; border-radius: 12px; font-size: 0.75em; font-weight: 600;';
+ statusCell.appendChild(statusBadge);
+ statusCell.style.cssText = 'padding: 12px 8px; text-align: center; border-right: 1px solid var(--border-color);';
+ row.appendChild(statusCell);
+
// Actions
const actionsCell = document.createElement('td');
+ actionsCell.style.cssText = 'padding: 12px 8px; text-align: center;';
+
+ // Create button container for better spacing
+ const buttonContainer = document.createElement('div');
+ buttonContainer.style.cssText = 'display: flex; gap: 6px; justify-content: center; align-items: center;';
// Edit button
const editBtn = document.createElement('button');
- editBtn.className = 'btn btn-sm btn-outline-primary mr-2';
+ editBtn.className = 'btn btn-sm';
editBtn.innerHTML = '<i class="fas fa-edit"></i>';
editBtn.title = 'Edit User';
+ editBtn.style.cssText = `
+ padding: 8px 10px;
+ border-radius: 6px;
+ border: 1px solid var(--primary-color, #007bff);
+ background-color: transparent;
+ color: var(--primary-color, #007bff);
+ transition: all 0.2s ease;
+ cursor: pointer;
+ min-width: 36px;
+ height: 36px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ `;
+
+ // Edit button hover effects
+ editBtn.addEventListener('mouseenter', () => {
+ if (!editBtn.disabled) {
+ editBtn.style.backgroundColor = 'var(--primary-color, #007bff)';
+ editBtn.style.color = 'white';
+ editBtn.style.transform = 'translateY(-1px)';
+ editBtn.style.boxShadow = '0 2px 4px rgba(0,123,255,0.3)';
+ }
+ });
+ editBtn.addEventListener('mouseleave', () => {
+ if (!editBtn.disabled) {
+ editBtn.style.backgroundColor = 'transparent';
+ editBtn.style.color = 'var(--primary-color, #007bff)';
+ editBtn.style.transform = 'translateY(0)';
+ editBtn.style.boxShadow = 'none';
+ }
+ });
editBtn.addEventListener('click', () => openEditUserModal(user));
// Delete button
const deleteBtn = document.createElement('button');
- deleteBtn.className = 'btn btn-sm btn-outline-danger';
+ deleteBtn.className = 'btn btn-sm';
deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i>';
deleteBtn.title = 'Delete User';
+ deleteBtn.style.cssText = `
+ padding: 8px 10px;
+ border-radius: 6px;
+ border: 1px solid var(--danger-color, #dc3545);
+ background-color: transparent;
+ color: var(--danger-color, #dc3545);
+ transition: all 0.2s ease;
+ cursor: pointer;
+ min-width: 36px;
+ height: 36px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ `;
+
+ // Delete button hover effects
+ deleteBtn.addEventListener('mouseenter', () => {
+ if (!deleteBtn.disabled) {
+ deleteBtn.style.backgroundColor = 'var(--danger-color, #dc3545)';
+ deleteBtn.style.color = 'white';
+ deleteBtn.style.transform = 'translateY(-1px)';
+ deleteBtn.style.boxShadow = '0 2px 4px rgba(220,53,69,0.3)';
+ }
+ });
+ deleteBtn.addEventListener('mouseleave', () => {
+ if (!deleteBtn.disabled) {
+ deleteBtn.style.backgroundColor = 'transparent';
+ deleteBtn.style.color = 'var(--danger-color, #dc3545)';
+ deleteBtn.style.transform = 'translateY(0)';
+ deleteBtn.style.boxShadow = 'none';
+ }
+ });
// Add multiple event handlers for redundancy
deleteBtn.addEventListener('click', (event) => {
@@ -1562,24 +1846,50 @@ async function loadUsers() {
return false;
};
- // Don't allow editing or deleting self
+ // Don't allow editing or deleting self, and disable actions for the owner
const currentUser = window.auth.getCurrentUser();
- if (user.id === currentUser.id) {
+ const isOwner = user.is_owner;
+ const isCurrentUser = (user.id === currentUser.id);
+
+ console.log(`DEBUG: Button logic for ${user.username} - isOwner: ${isOwner}, isCurrentUser: ${isCurrentUser}, currentUser.id: ${currentUser?.id}, user.id: ${user.id}`);
+
+ if (isOwner || isCurrentUser) {
editBtn.disabled = true;
deleteBtn.disabled = true;
- editBtn.title = 'Cannot edit yourself';
- deleteBtn.title = 'Cannot delete yourself';
- console.log('Disabled edit/delete for current user:', currentUser.id);
+ editBtn.title = isOwner ? 'Cannot edit the application owner' : 'Cannot edit yourself';
+ deleteBtn.title = isOwner ? 'Cannot delete the application owner' : 'Cannot delete yourself';
+
+ // Enhanced disabled styling
+ editBtn.style.opacity = '0.4';
+ editBtn.style.cursor = 'not-allowed';
+ editBtn.style.border = '1px solid var(--text-muted, #6c757d)';
+ editBtn.style.color = 'var(--text-muted, #6c757d)';
+
+ deleteBtn.style.opacity = '0.4';
+ deleteBtn.style.cursor = 'not-allowed';
+ deleteBtn.style.border = '1px solid var(--text-muted, #6c757d)';
+ deleteBtn.style.color = 'var(--text-muted, #6c757d)';
+
+ console.log('DEBUG: Disabled edit/delete for', isOwner ? 'owner' : 'current user', ':', user.id);
+ } else {
+ console.log('DEBUG: Buttons enabled for user:', user.id);
}
- actionsCell.appendChild(editBtn);
- actionsCell.appendChild(deleteBtn);
+ // Add buttons to container
+ buttonContainer.appendChild(editBtn);
+ buttonContainer.appendChild(deleteBtn);
+
+ // Add container to cell
+ actionsCell.appendChild(buttonContainer);
row.appendChild(actionsCell);
usersTableBody.appendChild(row);
});
console.log('Users loaded successfully:', users.length);
+
+ // Set up ownership management after loading users
+ setupOwnershipManagement(users);
} else {
console.error('Failed to load users:', response.status);
showToast('Failed to load users', 'error');
@@ -1881,6 +2191,157 @@ function deleteUser() {
console.log('=== DELETE USER FUNCTION COMPLETED ===');
}
+/**
+ * Set up ownership management functionality
+ * @param {Array} users - List of all users
+ */
+function setupOwnershipManagement(users) {
+ const currentUser = window.auth.getCurrentUser();
+ const ownershipCard = document.getElementById('ownershipCard');
+ const newOwnerSelect = document.getElementById('newOwnerSelect');
+ const transferOwnershipBtn = document.getElementById('transferOwnershipBtn');
+
+ // DEBUG: Check ownership management setup
+ console.log('DEBUG: setupOwnershipManagement called');
+ console.log('DEBUG: currentUser:', currentUser);
+ console.log('DEBUG: currentUser.is_owner:', currentUser ? currentUser.is_owner : 'no currentUser');
+ console.log('DEBUG: ownershipCard element:', ownershipCard);
+
+ if (!currentUser || !currentUser.is_owner) {
+ // Hide ownership section if user is not the owner
+ console.log('DEBUG: Hiding ownership section - user is not owner');
+ const ownershipSection = document.getElementById('ownershipSection');
+ if (ownershipSection) {
+ ownershipSection.style.display = 'none';
+ }
+ return;
+ }
+
+ // Show ownership section for the owner
+ const ownershipSection = document.getElementById('ownershipSection');
+ if (ownershipSection) {
+ ownershipSection.style.display = 'block';
+ }
+
+ // Populate the select dropdown with admin users (excluding current owner)
+ if (newOwnerSelect) {
+ newOwnerSelect.innerHTML = '<option value="">Select an admin user...</option>';
+
+ users.forEach(user => {
+ if (user.is_admin && user.id !== currentUser.id && user.is_active && !user.is_owner) {
+ const option = document.createElement('option');
+ option.value = user.id;
+ option.textContent = `${user.username} (${user.email})`;
+ newOwnerSelect.appendChild(option);
+ }
+ });
+
+ // Enable/disable transfer button based on selection
+ newOwnerSelect.addEventListener('change', function() {
+ if (transferOwnershipBtn) {
+ transferOwnershipBtn.disabled = !this.value;
+ }
+ });
+ }
+
+ // Set up transfer button click handler
+ if (transferOwnershipBtn) {
+ transferOwnershipBtn.addEventListener('click', function() {
+ const selectedUserId = newOwnerSelect.value;
+ if (!selectedUserId) {
+ showToast('Please select a user to transfer ownership to', 'error');
+ return;
+ }
+
+ const selectedUser = users.find(u => u.id == selectedUserId);
+ if (selectedUser) {
+ openTransferOwnershipModal(selectedUser);
+ }
+ });
+ }
+}
+
+/**
+ * Open the transfer ownership confirmation modal
+ * @param {Object} targetUser - The user to transfer ownership to
+ */
+function openTransferOwnershipModal(targetUser) {
+ const modal = document.getElementById('transferOwnershipModal');
+ const targetUsernameSpan = document.getElementById('transferTargetUsername');
+ const confirmInput = document.getElementById('transferConfirmInput');
+ const confirmBtn = document.getElementById('confirmTransferOwnershipBtn');
+
+ if (!modal || !targetUsernameSpan || !confirmInput || !confirmBtn) {
+ showToast('Error: Transfer ownership modal elements not found', 'error');
+ return;
+ }
+
+ // Set target username
+ targetUsernameSpan.textContent = targetUser.username;
+
+ // Clear and set up confirm input
+ confirmInput.value = '';
+ confirmInput.addEventListener('input', function() {
+ confirmBtn.disabled = this.value.toUpperCase() !== 'TRANSFER';
+ });
+
+ // Set up confirm button
+ confirmBtn.disabled = true;
+ confirmBtn.onclick = function() {
+ if (confirmInput.value.toUpperCase() === 'TRANSFER') {
+ performOwnershipTransfer(targetUser.id);
+ }
+ };
+
+ // Show modal
+ modal.style.display = 'flex';
+}
+
+/**
+ * Perform the actual ownership transfer
+ * @param {number} newOwnerId - ID of the user to transfer ownership to
+ */
+async function performOwnershipTransfer(newOwnerId) {
+ const modal = document.getElementById('transferOwnershipModal');
+
+ try {
+ showLoading();
+
+ const response = await fetch('/api/admin/transfer-ownership', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ new_owner_id: newOwnerId
+ })
+ });
+
+ if (response.ok) {
+ showToast('Ownership transferred successfully! Refreshing page...', 'success');
+
+ // Close modal
+ if (modal) {
+ modal.style.display = 'none';
+ }
+
+ // Refresh the page after a short delay to allow the user to see the success message
+ setTimeout(() => {
+ window.location.reload();
+ }, 2000);
+ } else {
+ const errorData = await response.json();
+ showToast(errorData.message || 'Failed to transfer ownership', 'error');
+ }
+ } catch (error) {
+ console.error('Error transferring ownership:', error);
+ showToast('Failed to transfer ownership. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
/**
* Super emergency delete function for user deletion
* @param {string|number} userId - The user ID or username to delete
@@ -2593,6 +3054,7 @@ async function loadSiteSettings() {
const globalViewToggleElem = document.getElementById('globalViewEnabled');
const globalViewAdminOnlyToggleElem = document.getElementById('globalViewAdminOnly');
const oidcEnabledToggleElem = document.getElementById('oidcEnabled');
+ const oidcOnlyModeToggleElem = document.getElementById('oidcOnlyMode');
const oidcProviderNameInputElem = document.getElementById('oidcProviderName');
const oidcClientIdInputElem = document.getElementById('oidcClientId');
const oidcClientSecretInputElem = document.getElementById('oidcClientSecret');
@@ -2659,6 +3121,13 @@ async function loadSiteSettings() {
console.error('[OIDC Settings] oidcEnabledToggleElem element NOT FOUND locally.');
}
+ if (oidcOnlyModeToggleElem) {
+ console.log('[OIDC Settings] Found oidcOnlyModeToggleElem. Setting checked to:', settings.oidc_only_mode === 'true');
+ oidcOnlyModeToggleElem.checked = settings.oidc_only_mode === 'true';
+ } else {
+ console.error('[OIDC Settings] oidcOnlyModeToggleElem element NOT FOUND locally.');
+ }
+
if (oidcProviderNameInputElem) {
console.log('[OIDC Settings] Found oidcProviderNameInputElem. Setting value to:', settings.oidc_provider_name || 'oidc');
oidcProviderNameInputElem.value = settings.oidc_provider_name || 'oidc';
@@ -2786,6 +3255,7 @@ async function saveOidcSettings() {
console.log('Saving OIDC settings...');
const oidcSettingsPayload = {
oidc_enabled: oidcEnabledToggle ? oidcEnabledToggle.checked : false,
+ oidc_only_mode: oidcOnlyModeToggle ? oidcOnlyModeToggle.checked : false,
oidc_provider_name: oidcProviderNameInput ? oidcProviderNameInput.value.trim() : 'oidc',
oidc_client_id: oidcClientIdInput ? oidcClientIdInput.value.trim() : '',
oidc_issuer_url: oidcIssuerUrlInput ? oidcIssuerUrlInput.value.trim() : '',
@@ -3299,8 +3769,8 @@ function toggleNotificationSettings(channel) {
if (emailSettingsContainer) {
emailSettingsContainer.style.display = (channel === 'email' || channel === 'both') ? 'block' : 'none';
}
- if (appriseSettingsContainer) {
- appriseSettingsContainer.style.display = (channel === 'apprise' || channel === 'both') ? 'block' : 'none';
+ if (userAppriseSettingsContainer) {
+ userAppriseSettingsContainer.style.display = (channel === 'apprise' || channel === 'both') ? 'block' : 'none';
}
}
@@ -3312,10 +3782,10 @@ async function saveNotificationSettings() {
notification_channel: notificationChannel.value,
notification_frequency: notificationFrequencySelect.value,
notification_time: notificationTimeInput.value,
- apprise_notification_time: appriseNotificationTimeInput.value,
- apprise_notification_frequency: appriseNotificationFrequency.value,
+ apprise_notification_time: userAppriseNotificationTimeInput ? userAppriseNotificationTimeInput.value : '09:00',
+ apprise_notification_frequency: userAppriseNotificationFrequency ? userAppriseNotificationFrequency.value : 'daily',
timezone: timezoneSelect.value,
- apprise_timezone: appriseTimezoneSelect.value
+ apprise_timezone: userAppriseTimezoneSelect ? userAppriseTimezoneSelect.value : 'UTC'
};
const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
@@ -3420,6 +3890,15 @@ window.addEventListener('storage', (event) => {
}
}
+ // Add check for currencyPosition
+ if (event.key === `${prefix}currencyPosition`) {
+ console.log(`[Settings Storage Listener] ${prefix}currencyPosition changed to ${event.newValue}`);
+ if (event.newValue && currencyPositionSelect && currencyPositionSelect.value !== event.newValue) {
+ currencyPositionSelect.value = event.newValue;
+ console.log('[Settings Storage Listener] Updated settings currency position dropdown via storage event.');
+ }
+ }
+
});
// --- End Storage Event Listener ---
@@ -3490,7 +3969,6 @@ async function loadAppriseSettings() {
// Update status display
if (appriseUrlsCount) appriseUrlsCount.textContent = statusData.urls_configured || 0;
if (currentAppriseExpirationDays) currentAppriseExpirationDays.textContent = statusData.expiration_days ? statusData.expiration_days.join(', ') : '-';
- if (currentAppriseNotificationTime) currentAppriseNotificationTime.textContent = statusData.notification_time || '-';
// Load settings from site settings
await loadAppriseSiteSettings();
@@ -3560,12 +4038,7 @@ async function loadAppriseSiteSettings() {
console.log('⚠️ appriseExpirationDaysInput element not found or data missing');
}
- if (appriseNotificationTimeInput && data.apprise_notification_time) {
- appriseNotificationTimeInput.value = data.apprise_notification_time;
- console.log('✅ Set appriseNotificationTime:', data.apprise_notification_time);
- } else {
- console.log('⚠️ appriseNotificationTimeInput element not found or data missing');
- }
+
if (appriseTitlePrefixInput && data.apprise_title_prefix) {
appriseTitlePrefixInput.value = data.apprise_title_prefix;
@@ -3573,6 +4046,32 @@ async function loadAppriseSiteSettings() {
} else {
console.log('⚠️ appriseTitlePrefixInput element not found or data missing');
}
+
+ if (appriseNotificationModeSelect && data.apprise_notification_mode) {
+ appriseNotificationModeSelect.value = data.apprise_notification_mode;
+ updateAppriseModeDescription(data.apprise_notification_mode);
+ console.log('✅ Set appriseNotificationMode:', data.apprise_notification_mode);
+ } else {
+ console.log('⚠️ appriseNotificationModeSelect element not found or data missing');
+ // Set default mode if not found
+ if (appriseNotificationModeSelect) {
+ appriseNotificationModeSelect.value = 'global';
+ updateAppriseModeDescription('global');
+ }
+ }
+
+ if (appriseWarrantyScopeSelect && data.apprise_warranty_scope) {
+ appriseWarrantyScopeSelect.value = data.apprise_warranty_scope;
+ updateAppriseScopeDescription(data.apprise_warranty_scope);
+ console.log('✅ Set appriseWarrantyScope:', data.apprise_warranty_scope);
+ } else {
+ console.log('⚠️ appriseWarrantyScopeSelect element not found or data missing');
+ // Set default scope if not found
+ if (appriseWarrantyScopeSelect) {
+ appriseWarrantyScopeSelect.value = 'all';
+ updateAppriseScopeDescription('all');
+ }
+ }
} catch (error) {
console.error('❌ Error loading Apprise site settings:', error);
@@ -3596,9 +4095,10 @@ async function saveAppriseSettings() {
const settings = {
apprise_enabled: appriseEnabledToggle ? appriseEnabledToggle.checked.toString() : 'false',
+ apprise_notification_mode: appriseNotificationModeSelect ? appriseNotificationModeSelect.value : 'global',
+ apprise_warranty_scope: appriseWarrantyScopeSelect ? appriseWarrantyScopeSelect.value : 'all',
apprise_urls: urls,
apprise_expiration_days: appriseExpirationDaysInput ? appriseExpirationDaysInput.value : '7,30',
- apprise_notification_time: appriseNotificationTimeInput ? appriseNotificationTimeInput.value : '09:00',
apprise_title_prefix: appriseTitlePrefixInput ? appriseTitlePrefixInput.value : '[Warracker]'
};
@@ -3835,6 +4335,32 @@ async function saveAppriseEnabledState(enabled) {
}
}
+/**
+ * Update Apprise mode description text
+ */
+function updateAppriseModeDescription(mode) {
+ if (!appriseModeDescription) return;
+
+ if (mode === 'global') {
+ appriseModeDescription.textContent = 'A single, consolidated notification will be sent to the global Apprise channels defined below.';
+ } else if (mode === 'individual') {
+ appriseModeDescription.textContent = 'A separate notification will be sent for each user with expiring warranties. (Note: This currently uses the global channels. Per-user channels can be a future enhancement.)';
+ }
+}
+
+/**
+ * Update Apprise warranty scope description text
+ */
+function updateAppriseScopeDescription(scope) {
+ if (!appriseScopeDescription) return;
+
+ if (scope === 'all') {
+ appriseScopeDescription.textContent = 'Notifications will include expiring warranties from all users in the system.';
+ } else if (scope === 'admin') {
+ appriseScopeDescription.textContent = 'Notifications will only include expiring warranties belonging to the admin/owner user.';
+ }
+}
+
/**
* Setup Apprise event listeners
*/
@@ -3852,6 +4378,20 @@ function setupAppriseEventListeners() {
});
}
+ // Notification mode change
+ if (appriseNotificationModeSelect) {
+ appriseNotificationModeSelect.addEventListener('change', (e) => {
+ updateAppriseModeDescription(e.target.value);
+ });
+ }
+
+ // Warranty scope change
+ if (appriseWarrantyScopeSelect) {
+ appriseWarrantyScopeSelect.addEventListener('change', (e) => {
+ updateAppriseScopeDescription(e.target.value);
+ });
+ }
+
// Save settings
if (saveAppriseSettingsBtn) {
saveAppriseSettingsBtn.addEventListener('click', saveAppriseSettings);
diff --git a/frontend/status.html b/frontend/status.html
index 3061768..5a1821e 100644
--- a/frontend/status.html
+++ b/frontend/status.html
@@ -623,10 +623,17 @@
</select>
<input type="text" id="editWarrantyTypeCustom" name="warranty_type_custom" class="form-control" style="display: none; margin-top: 8px;" placeholder="Enter custom warranty type">
</div>
+ <div class="form-group">
+ <label for="editCurrency">Currency</label>
+ <select id="editCurrency" name="currency" class="form-control">
+ <option value="USD">USD - US Dollar ($)</option>
+ <!-- Currency options will be populated by JavaScript -->
+ </select>
+ </div>
<div class="form-group">
<label for="editPurchasePrice">Purchase Price (Optional)</label>
- <div class="price-input-wrapper">
- <span class="currency-symbol">$</span>
+ <div class="price-input-wrapper" id="editPriceInputWrapper">
+ <span class="currency-symbol" id="editCurrencySymbol">$</span>
<input type="number" id="editPurchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">
</div>
</div>
diff --git a/frontend/status.js b/frontend/status.js
index a3f8c87..a3d2611 100644
--- a/frontend/status.js
+++ b/frontend/status.js
@@ -113,15 +113,24 @@
headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json'}
};
- // Choose API endpoint based on current view
- const apiUrl = isGlobalView ? GLOBAL_STATISTICS_API_URL : STATISTICS_API_URL;
- console.log('Fetching statistics from:', apiUrl, '(Global view:', isGlobalView, ')');
+ // Check saved view scope preference to determine which API endpoint to use
+ const savedScope = loadViewScopePreference();
+ const shouldUseGlobalView = savedScope === 'global';
+
+ // Choose API endpoint based on saved preference
+ const apiUrl = shouldUseGlobalView ? GLOBAL_STATISTICS_API_URL : STATISTICS_API_URL;
+ console.log('Fetching statistics from:', apiUrl, '(Global view preference:', savedScope, ')');
const response = await fetch(apiUrl, options);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to fetch statistics: ${response.status} ${errorText}`);
}
+
+ // Update isGlobalView to match the loaded data
+ isGlobalView = shouldUseGlobalView;
+ console.log(`[DEBUG] Set isGlobalView to: ${isGlobalView}`);
+
return await response.json();
} catch (error) {
console.error('Error fetching statistics (status.js IIFE):', error);
@@ -159,6 +168,23 @@
if (result.enabled) {
showViewSwitcher();
setupViewSwitcherListeners();
+
+ // Load and apply saved view scope preference
+ const savedScope = loadViewScopePreference();
+ if (savedScope === 'global') {
+ // Apply global view silently without saving preference again
+ isGlobalView = true;
+ updateViewButtons();
+ updateDashboardTitle();
+ updateTableColumns();
+ } else {
+ // Apply personal view (default)
+ isGlobalView = false;
+ updateViewButtons();
+ updateDashboardTitle();
+ updateTableColumns();
+ }
+
isViewControlsInitialized = true;
}
}
@@ -168,6 +194,23 @@
if (getUserType() === 'admin') {
showViewSwitcher();
setupViewSwitcherListeners();
+
+ // Load and apply saved view scope preference
+ const savedScope = loadViewScopePreference();
+ if (savedScope === 'global') {
+ // Apply global view silently without saving preference again
+ isGlobalView = true;
+ updateViewButtons();
+ updateDashboardTitle();
+ updateTableColumns();
+ } else {
+ // Apply personal view (default)
+ isGlobalView = false;
+ updateViewButtons();
+ updateDashboardTitle();
+ updateTableColumns();
+ }
+
isViewControlsInitialized = true;
}
}
@@ -182,6 +225,44 @@
}
}
+ /**
+ * Get the appropriate localStorage key prefix based on user type
+ * @returns {string} The prefix to use for localStorage keys
+ */
+ function getPreferenceKeyPrefix() {
+ return getUserType() === 'admin' ? 'admin_' : 'user_';
+ }
+
+ /**
+ * Save view scope preference to localStorage
+ * @param {string} scope - 'personal' or 'global'
+ */
+ function saveViewScopePreference(scope) {
+ try {
+ const prefix = getPreferenceKeyPrefix();
+ localStorage.setItem(`${prefix}viewScope`, scope);
+ console.log(`Saved view scope preference: ${scope} with prefix: ${prefix}`);
+ } catch (error) {
+ console.error('Error saving view scope preference:', error);
+ }
+ }
+
+ /**
+ * Load view scope preference from localStorage
+ * @returns {string} The saved preference ('personal', 'global', or 'personal' as default)
+ */
+ function loadViewScopePreference() {
+ try {
+ const prefix = getPreferenceKeyPrefix();
+ const savedScope = localStorage.getItem(`${prefix}viewScope`);
+ console.log(`Loaded view scope preference: ${savedScope} with prefix: ${prefix}`);
+ return savedScope || 'personal'; // Default to personal view
+ } catch (error) {
+ console.error('Error loading view scope preference:', error);
+ return 'personal'; // Default to personal view on error
+ }
+ }
+
function showViewSwitcher() {
const viewSwitcher = document.getElementById('viewSwitcher');
if (viewSwitcher) {
@@ -215,6 +296,10 @@
updateViewButtons();
updateDashboardTitle();
updateTableColumns();
+
+ // Save view preference
+ saveViewScopePreference('personal');
+
isDashboardInitialized = false; // Reset to allow refresh with new view
await initDashboard();
}
@@ -237,6 +322,10 @@
updateViewButtons();
updateDashboardTitle();
updateTableColumns();
+
+ // Save view preference
+ saveViewScopePreference('global');
+
isDashboardInitialized = false; // Reset to allow refresh with new view
await initDashboard();
} else {
@@ -1017,7 +1106,7 @@
if (typeof window.openEditModal === 'function') {
window.currentEditingWarrantyIdStatusPage = warrantyId; // For observer
- window.openEditModal(finalWarrantyForModal);
+ await window.openEditModal(finalWarrantyForModal);
} else {
showToast('Edit modal functionality is not available.', 'error');
console.error("window.openEditModal is not a function. Ensure script.js is loaded and exposes it.");
diff --git a/frontend/style.css b/frontend/style.css
index 60fc514..c154745 100644
--- a/frontend/style.css
+++ b/frontend/style.css
@@ -2717,6 +2717,13 @@ input.invalid {
z-index: 1;
}
+/* Currency symbol on the right side of input */
+.price-input-wrapper.currency-right .currency-symbol {
+ left: auto;
+ right: 12px;
+ pointer-events: none; /* Prevent interference with input */
+}
+
/* Default style for currency symbols (e.g., on cards) */
.currency-symbol {
display: inline; /* Ensure it stays inline */
@@ -2724,10 +2731,22 @@ input.invalid {
/* Remove absolute positioning properties if they were here */
}
+/* Currency symbol on the right side of numbers */
+.currency-symbol.currency-right {
+ margin-right: 0;
+ margin-left: 0.2em; /* Add space before the symbol when on the right */
+}
+
.price-input-wrapper .form-control {
padding-left: 25px;
}
+/* Adjust padding for right-positioned currency symbol */
+.price-input-wrapper.currency-right .form-control {
+ padding-left: 12px;
+ padding-right: 25px;
+}
+
/* Product name header at the top of cards */
.product-name-header {
width: 100%;
@@ -3939,20 +3958,20 @@ html.dark-mode .warracker-footer a:hover {
/* Grid view photo positioning */
.grid-view .product-photo-thumbnail img {
- width: 60px;
- height: 60px;
+ width: 80px;
+ height: 80px;
}
/* List view photo positioning */
.list-view .product-photo-thumbnail img {
- width: 50px;
- height: 50px;
+ width: 70px;
+ height: 70px;
}
/* Table view photo positioning */
.table-view .product-photo-thumbnail img {
- width: 40px;
- height: 40px;
+ width: 55px;
+ height: 55px;
}
/* Dark mode adjustments */
@@ -3969,13 +3988,13 @@ html.dark-mode .warracker-footer a:hover {
@media (max-width: 768px) {
.grid-view .product-photo-thumbnail img,
.list-view .product-photo-thumbnail img {
- width: 45px;
- height: 45px;
+ width: 60px;
+ height: 60px;
}
.table-view .product-photo-thumbnail img {
- width: 35px;
- height: 35px;
+ width: 50px;
+ height: 50px;
}
.product-photo-thumbnail {
diff --git a/frontend/version-checker.js b/frontend/version-checker.js
index 7927931..d42feff 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.10.1.0'; // Current version of the application
+ const currentVersion = '0.10.1.1'; // Current version of the application
const updateStatus = document.getElementById('updateStatus');
const updateLink = document.getElementById('updateLink');