🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Reverted
sassanix7ead2f7aa72a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 08440fa..1823f54 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,180 +1,5 @@# Changelog-## 1.0.3 - 2025-11-07--### Added-- **Modular Entry Orchestrator and Feature Modules**- - Added a lean ES module entry orchestrator `index.js` that initializes auth and feature modules after `authStateReady`.- - Created feature-specific modules to prepare deconstruction of the monolith while preserving identical behavior:- - `warrantyListController.js` (list loading/filtering/rendering controller surface)- - `tagManager.js` (tag management: load/render/create/update/delete)- - `addWarrantyForm.js` (multi-step add warranty wizard surface)- - Wired pages to load the new module entry with `<script type="module" src="./js/index.js"></script>` alongside legacy `script.js` for zero-regression rollout.- - _Files: `frontend/js/index.js`, `frontend/js/controllers/warrantyListController.js`, `frontend/js/components/tagManager.js`, `frontend/js/components/addWarrantyForm.js`, `frontend/index.html`, `frontend/about.html`, `frontend/status.html`, `frontend/register.html`, `frontend/reset-password.html`, `frontend/reset-password-request.html`_--- **Centralized Authentication Service**- - New module `authService.js` exposes `initAuth`, `login`, `logout`, `getToken`, `getCurrentUser`, `isAuthenticated`.- - Backwards compatibility: attaches a `window.auth` facade so existing code continues to work.- - Handles header UI state, user menu/settings dropdown toggling, and dispatches a unified `authStateReady` event.- - Robustly hides “Create Account” UI when registration is disabled (with a MutationObserver to keep it hidden after other scripts mutate the DOM).- - _Files: `frontend/js/services/authService.js`, `frontend/*.html` (module includes)_--- **Dedicated API Service**- - New `apiService.js` provides a `baseRequest` wrapper that injects the `Authorization` header and normalizes error handling.- - Exposes named helpers (e.g., `getWarranties`, `updateWarranty`, `deleteWarranty`, `getStatistics`, `savePreferences`) and a `window.api` shim for non-module scripts.- - Safe global `fetch` shim adds the Authorization header for `/api/...` calls when missing.- - _Files: `frontend/js/services/apiService.js`, `frontend/*.html` (module includes)_-- - **Central State Management Store**- - Introduced a `store.js` module to act as a single source of truth for application data (warranties, filters, loading states), eliminating scattered global variables.- - UI updates are now driven by custom events, creating a predictable data flow.- - _Files: `frontend/js/store.js`_--- **Component-Based UI Modules**- - Created a suite of new, reusable UI component modules to replace HTML string concatenation. Each is responsible for building a specific part of the UI via safe DOM manipulation.- - Modules include: `warrantyCard.js`, `tag.js`, `modals.js`, `editModal.js`, `claims.js`, `notes.js`, `paperless.js`, and `ui.js`.- - _Files: `frontend/js/components/*`_--- **HTML `<template>` for Warranty Cards**- - Added a `<template id="warranty-card-template">` to `index.html` to define the warranty card structure, separating markup from rendering logic for improved performance and maintainability.- - _Files: `frontend/index.html`_--### Enhanced-- **Dockerfile: simplified static file serving**- - Removed build stage; frontend files are now copied directly to `/var/www/html/` for static serving.- - No build step required; all frontend assets are served as-is.- - _Files: `Dockerfile`_--- **HTML and asset loading**- - Switched all page `<script>` and `<link>` paths to relative paths (e.g., `./script.js`) for static file serving.- - Ensured `script.js` is loaded with `defer` across pages to avoid early DOM access issues.- - All assets are served directly from the `frontend/` directory without a build step.- - _Files: `frontend/*.html`, `frontend/**/*`_--- **Frontend structure**- - Consolidated all frontend files into a single `frontend/` directory for simplified static serving.- - _Files: `frontend/settings-styles.css`_--- **Global State Management Refactor**- - Migrated `frontend/script.js` to read/write state exclusively via the centralized `window.store` API.- - Replaced direct usages of `warranties`, `currentFilters`, and `allTags` with `store.getWarranties/setWarranties`, `store.getFilters/updateFilter`, and `store.getAllTags/setAllTags`.- - Updated filter event listeners, export flow, tag management (create/update/delete), and the filtering/rendering pipeline (`applyFilters`, `renderWarranties`) to consume store-backed data.- - `loadTags()` now persists tags to the store and dispatches events to refresh dependent UIs.- - Replaced remaining direct reads of removed globals with store getters in `script.js` (e.g., card action handlers, `filterWarranties()`, `openClaimsModal()`, and notes modal handlers). App behavior unchanged; all reads/writes now flow through `window.store`.- - _Files: `frontend/script.js`_--- **Major UI Refactor for Maintainability & Security**- - Replaced nearly all `innerHTML` assignments with a robust, component-based rendering approach. This makes the UI easier to debug, maintain, and more secure against XSS vulnerabilities.- - **Warranty List:** The main warranty display for grid, list, and table views is now rendered using the `warrantyCard.js` component.- - **Edit Modal:** The complex dynamic sections (serial numbers, current document displays for invoices/manuals/photos, and tag selection) are now built with the `editModal.js` component.- - **Claims Modal:** The entire claims view, including the header, loading/error states, and claims list, is now rendered by the `claims.js` component.- - **Other Modals:** Refactored the rendering logic for the Tag Management, Notes, and Paperless-ngx document browser modals to use their respective new components.- - _Files: `frontend/script.js`, `frontend/js/components/*`_--- **Begin Extraction of UI Event Listeners**- - Moved the global UI event initialization (`setupUIEventListeners`) into `warrantyListController.initEventListeners()` as part of the modularization.- - Legacy `frontend/script.js` delegates to the controller to attach listeners, maintaining identical behavior during the staged rollout.- - _Files: `frontend/js/controllers/warrantyListController.js`, `frontend/script.js`_--- **Controller-based Filter Pipeline**- - Migrated `applyFilters` logic into `warrantyListController.js` to centralize filtering while preserving identical behavior.- - Legacy `applyFilters` in `frontend/script.js` now delegates to the controller to avoid duplication.- - _Files: `frontend/js/controllers/warrantyListController.js`, `frontend/script.js`_--- **Filter Dropdowns and Preference Persistence Extraction**- - Moved filter dropdown population functions (`populateTagFilter`, `populateVendorFilter`, `populateWarrantyTypeFilter`) and preference persistence (`saveFilterPreferences`, `loadFilterAndSortPreferences`) into `warrantyListController.js`.- - Legacy functions in `frontend/script.js` now delegate to the controller, ensuring a single source of truth.- - _Files: `frontend/js/controllers/warrantyListController.js`, `frontend/script.js`_--- **Read-only State Bridges for Module Access**- - Exposed read-only getters on `window` for `currentView`, `lastLoadedArchived`, and `lastLoadedIncludesArchived` to allow module code to read legacy flags safely without changing their source of truth.- - _Files: `frontend/script.js`_--- **Delegated List Actions Fallback in Controller**- - Added robust delegated handlers in `warrantyListController.initEventListeners()` for `#warrantiesList` (claims, edit, delete, notes, archive/unarchive) that activate only when the legacy initializer is not present, preventing double bindings.- - _Files: `frontend/js/controllers/warrantyListController.js`_--- **Controller-based Data Loader (`loadWarranties`)**- - Migrated the full `loadWarranties` flow into `warrantyListController.js` while preserving behavior: authentication check, scope selection (Personal/Global), Archived vs All handling with archived merge, processing via `processWarrantyData`, filter dropdown repopulation, and final render through `applyFilters()`.- - Legacy `frontend/script.js` now delegates `loadWarranties` to the controller.- - _Files: `frontend/js/controllers/warrantyListController.js`, `frontend/script.js`_--- **Warranty List Rendering (component-based refactor, public bundle)**- - Rewrote `renderWarranties` in `frontend/script.js` to stop concatenating HTML strings and instead delegate card creation to `window.components.createWarrantyCard(warranty, options)`.- - Builds `actionsHtml`, `contentHtml`, `statusText/statusClass`, and view-specific root class via helpers; appends tags using `window.components.appendTags`; preserves document links row placement per view.- - Uses `DocumentFragment` to batch DOM insertions for performance and `window.components.ui.renderEmptyState` for empty states.- - Centralized card action handling with a single delegated listener on `#warrantiesList` for edit, delete, archive/unarchive, claims, and notes.- - Updated all call sites to the no-arg `renderWarranties()`; visual output and behavior remain identical across Grid, List, and Table views.- - _Files: `frontend/script.js`_--- **Finalized Legacy Script Delegation**- - Completed migration of UI event listeners from `frontend/script.js` (`setupUIEventListeners`) into `warrantyListController.initEventListeners()`:- - Filters: `statusFilter`, `tagFilter`, `vendorFilter`, `warrantyTypeFilter`- - Sort: `sortBy`- - View switchers: `gridViewBtn`, `listViewBtn`, `tableViewBtn`- - Actions: `refreshBtn`, `exportBtn`, `importBtn`- - Replaced the legacy initializer call site and removed `setupUIEventListeners` from `script.js` (now delegates to the controller).- - Delegated modal openings to component layer: `openDeleteModal`/`openArchiveModal` now call `window.components.modals.openDeleteModal/openArchiveModal` which owns DOM updates and visibility.- - Moved Edit modal save flow out of legacy script: `saveWarranty` now lives in `frontend/js/components/editModal.js`, uses `apiService.updateWarranty`, and is exposed as `window.components.editModal.saveWarranty`.- - Updated Save button wiring: controller binds Save to `editModal.saveWarranty`, preserving `setupSaveWarrantyObserver` wrapping when present.- - Consolidated card action delegation: the single `#warrantiesList` delegated listener resides exclusively in the controller; removed the overlapping legacy delegation from `script.js`.- - `script.js` is now a thin delegator with identical external behavior.- - _Files: `frontend/script.js`, `frontend/js/controllers/warrantyListController.js`, `frontend/js/components/modals.js`, `frontend/js/components/editModal.js`_-- - **Page-Specific Script Modularization (`status.js`)**- - Converted `frontend/status.js` from a legacy script into a self-contained ES Module.- - Replaced all `fetch` calls with methods from the imported `apiService.js` and all authentication logic with `authService.js`, removing dependencies on the global scope.- - The module now initializes itself via a `DOMContentLoaded` listener, making it independent of the legacy `script.js`.- - Updated `frontend/status.html` to load `status.js` with `type="module"`, ensuring modern script handling.- - _Files: `frontend/status.js`, `frontend/status.html`_-- - **API Service Extension**- - Added a generic `apiService.request()` method to handle various API calls, which was utilized in the refactoring of `status.js`.- - _Files: `frontend/js/services/apiService.js`_---### Fixed-- 404s for non-module assets in production by ensuring all assets are properly referenced with relative paths.-- User menu not opening: restored click/close listeners within `authService.js`.-- Login page “Create Account” visible while registration disabled: force-hidden with strong CSS and observer.-- Status page edit actions blocked by early `document.body.appendChild(...)`: added `defer` to `script.js` includes.-- **Thumbnail sizing on initial load (Grid/List/Table)**- - Removed inline image sizing in the renderer so thumbnail sizes are now driven by CSS view classes, ensuring correct sizes apply immediately without hard reload or manual view switch.- - Applied view preference before first render during data load to guarantee correct view class on first paint.- - Tuned responsive CSS for very small screens (≤360px): List view 60×60, Table view 20×20; preserved existing ≤768px sizes.- - _Files: `frontend/script.js`, `frontend/style.css`, `frontend/js/controllers/warrantyListController.js`_-- **Security:** Mitigated potential cross-site scripting (XSS) vulnerabilities by removing reliance on building the UI with `innerHTML` from dynamic data.-- **Performance:** Improved rendering performance by using efficient DOM creation and appending (`<template>` clones, `document.createElement`) instead of causing the browser to re-parse large HTML strings on every update.-- **Code Quality:** Drastically reduced code complexity and repetition in `script.js` by delegating UI creation to specialized component modules.-- Eliminated 404s for removed stylesheet by deleting the `/styles.css` link in `frontend/about.html` and removing it from the service worker pre-cache (`frontend/sw.js`).- - _Files: `frontend/about.html`, `frontend/sw.js`_-- Resolved transient `ReferenceError` messages (e.g., `allTags`/`warranties`/`currentFilters` not defined) by completing the store-backed migration in `frontend/script.js`.--### Removed-- Legacy, scattered auth scripts now replaced by `authService.js`:- - `frontend/auth.js`, `frontend/auth-new.js`, `frontend/include-auth-new.js`, `frontend/fix-auth-buttons.js`, `frontend/fix-auth-buttons-loader.js`, `frontend/registration-status.js`.- - **Global State Variables**- - Eliminated global variables like `let warranties = []` and `let currentFilters = {}` from `script.js`, centralizing all state management within `store.js`.-- **Hardcoded HTML Strings**- - Removed large, multi-line HTML string templates from JavaScript files, which were fragile and difficult to maintain.--- Frontend duplicate/unused assets removed:- - Removed unused stylesheet: `frontend/styles.css`- - Removed debug files: `frontend/js/i18n-debug.js`, `frontend/temp-toast-debug.js`-- - Backend cleanup: removed unused `backend/fix_notification_columns.py`.--### House Cleaning-- Deleted generated artifacts not needed in repo: `frontend/dist`, `frontend/node_modules` (frontend is now served statically without build)-- Purged Python caches: `backend/**/__pycache__`, stray `.pyc`-- Removed old backup: `backend/fix_permissions.sql.bak`-- **Code Refinement in `settings-new.js`**- - **Settings page refactor — ES Module & event wiring**- - Converted `frontend/settings-new.js` into a self-contained ES Module and updated `settings-new.html` to load it with a `<script type="module" src="./settings-new.js"></script>` tag. The module imports `authService` and `apiService` rather than relying on global functions.- - Removed inline `onclick` handlers from the Settings HTML (notably the Delete User modal) and rewired UI interactions using `addEventListener` inside the module so handlers are module-scoped instead of being attached to `window`.- - Extended `frontend/js/services/apiService.js` with settings/admin endpoints consumed by the module (for example: `getUser`, `getUsers`, `updateUser`, `deleteUser`, `getSiteSettings`, `saveSiteSettings`, `getAuditTrail`, `triggerNotifications`) and preserved the `window.api` shim for backward compatibility.- - Fixed a porting-induced syntax/parsing issue (unbalanced brace) and removed a leftover global (`window.currentDeleteUserId`) in favor of a module-scoped `currentDeleteUserId` to avoid leaking state.- - The refactored module parses without syntax errors. Runtime smoke tests are planned/encouraged (see next steps) and final decommission of the legacy `script.js` will follow once runtime verification is complete.- - _Files: `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/js/services/apiService.js`_+## 1.0.3 - 2025-10-31## 1.0.2 - 2025-10-30diff --git a/Dockerfile b/Dockerfileindex 17df14a..cbf5f0f 100644--- a/Dockerfile+++ b/Dockerfile@@ -112,7 +112,7 @@ COPY --chown=warracker:warracker backend/migrations/ ./migrations/COPY --chown=warracker:warracker locales/ ./locales/COPY --chown=warracker:warracker locales/ /var/www/html/locales/-# 4. Frontend (static files, no build step)+# 4. Frontend (bundled in one instruction)COPY --chown=warracker:warracker frontend/ /var/www/html/# 5. Backend (bundled in one instruction)diff --git a/frontend/about.html b/frontend/about.htmlindex bc4e990..a7c52a8 100644--- a/frontend/about.html+++ b/frontend/about.html@@ -7,33 +7,31 @@<title data-i18n="about.title">About - Warracker</title><!-- Favicons -->- <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">- <link rel="icon" type="image/png" sizes="16x16" href="./img/favicon-16x16.png?v=2">- <link rel="icon" type="image/png" sizes="32x32" href="./img/favicon-32x32.png?v=2">- <link rel="apple-touch-icon" sizes="180x180" href="./img/favicon-512x512.png">- <link rel="manifest" href="./manifest.json">+ <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">+ <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">+ <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">+ <link rel="manifest" href="manifest.json"><!-- Stylesheets -->- <link rel="stylesheet" href="./style.css?v=20250119004"> <!-- Main stylesheet -->+ <link rel="stylesheet" href="style.css?v=20250119004"> <!-- Main stylesheet -->+ <link rel="stylesheet" href="styles.css?v=20250119001"> <!-- Additional styles --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css"> <!-- Font Awesome -->- <link rel="stylesheet" href="./header-fix.css?v=20250119001"> <!-- Header specific styles -->+ <link rel="stylesheet" href="header-fix.css?v=20250119001"> <!-- Header specific styles --><!-- Mobile Header specific styles -->- <link rel="stylesheet" href="./mobile-header.css?v=20250119002">+ <link rel="stylesheet" href="mobile-header.css?v=20250119002"><!-- Scripts loaded in head -->- <script src="./theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->- <script type="module" src="./js/services/authService.js"></script>- <script type="module" src="./js/services/apiService.js"></script>--- <script src="./script.js?v=20250119001" defer></script>- <script type="module" src="./js/index.js"></script>+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->+ <script src="include-auth-new.js?v=20250119001"></script> <!-- Handles auth state display -->+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script> <!-- Fixes auth button display timing -->+ <script src="script.js?v=20250119001" defer></script><!-- i18next Local Scripts -->- <script src="./js/lib/i18next.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>+ <script src="js/lib/i18next.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script><!-- i18n initialization script -->- <script src="./js/i18n.js?v=20250119001"></script>+ <script src="js/i18n.js?v=20250119001"></script><style>.about-hero {@@ -335,7 +333,7 @@<!-- Hero Section --><div class="about-hero"><h1><i class="fas fa-shield-alt"></i> Warracker</h1>- <div class="version" id="versionDisplay" data-i18n="about.version">Version v1.0.3</div>+ <div class="version" id="versionDisplay" data-i18n="about.version">Version v1.0.2</div><p class="description" data-i18n="about.description">A comprehensive warranty management system designed to help you track, organize, and manage all your product warranties in one secure, user-friendly platform.</p>@@ -412,16 +410,16 @@</div><!-- Scripts loaded at the end of body -->-+ <script src="auth.js?v=20250119001"></script><!-- Version Checker -->- <script src="./version-checker.js?v=20251030001" defer></script> <!-- Version checker script -->+ <script src="version-checker.js?v=20251030001" defer></script> <!-- Version checker script --><!-- Footer Width Fix -->- <script src="./footer-fix.js?v=20251024001"></script>+ <script src="footer-fix.js?v=20251024001"></script><!-- Footer Content Manager -->- <script src="./footer-content.js?v=20250119001"></script>+ <script src="footer-content.js?v=20250119001"></script><!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">@@ -436,7 +434,7 @@// Update version display dynamicallyconst versionDisplay = document.getElementById('versionDisplay');if (versionDisplay && window.i18next) {- const currentVersion = '1.0.3'; // This should match version-checker.js+ const currentVersion = '1.0.2'; // This should match version-checker.jsversionDisplay.textContent = window.i18next.t('about.version') + ' v' + currentVersion;}diff --git a/frontend/auth-new.js b/frontend/auth-new.jsnew file mode 100644index 0000000..15e414b--- /dev/null+++ b/frontend/auth-new.js@@ -0,0 +1,224 @@+/**+ * Authentication functionality for Warracker (New UI)+ * Handles user login, logout, and authentication state management for the new UI design+ */++// Authentication state+let currentUser = null;+let authToken = null;++// Initialize authentication+document.addEventListener('DOMContentLoaded', () => {+ console.log('Initializing auth-new.js for new UI');++ // Initial check of authentication state+ checkAuthState();++ // Set up periodic check of auth state (every 30 seconds)+ setInterval(checkAuthState, 30000);++ // Set up logout functionality+ setupLogout();+});++/**+ * Set up logout functionality+ */+function setupLogout() {+ // Look for logout button in the new UI+ const logoutButton = document.querySelector('.logout-btn');++ if (logoutButton) {+ console.log('Found logout button in new UI');++ // Add click event to logout+ logoutButton.addEventListener('click', (e) => {+ e.preventDefault();+ logout();+ });+ }+}++/**+ * Check if user is authenticated and update UI accordingly+ */+function checkAuthState() {+ console.log('Checking auth state for new UI');++ // Get auth token from localStorage+ authToken = localStorage.getItem('auth_token');+ const userInfo = localStorage.getItem('user_info');++ if (authToken && userInfo) {+ try {+ currentUser = JSON.parse(userInfo);+ updateUIForAuthenticatedUser();+ validateToken();+ } catch (error) {+ console.error('Error parsing user info:', error);+ clearAuthData();+ updateUIForUnauthenticatedUser();+ }+ } else {+ updateUIForUnauthenticatedUser();+ }+}++/**+ * Update UI elements for authenticated user in the new UI+ */+function updateUIForAuthenticatedUser() {+ console.log('Updating UI for authenticated user');++ // Find login/register buttons in the new UI based on the screenshot+ const loginButton = document.querySelector('a[href="login.html"], a.login');+ const registerButton = document.querySelector('a[href="register.html"], a.register');++ // Hide login/register buttons if they exist+ if (loginButton) {+ console.log('Hiding login button');+ loginButton.style.display = 'none';+ }++ if (registerButton) {+ console.log('Hiding register button');+ registerButton.style.display = 'none';+ }++ // Show user info if it exists+ const userDisplay = document.querySelector('.user-display');+ if (userDisplay && currentUser) {+ let displayName = currentUser.username || 'User';+ userDisplay.textContent = displayName;+ userDisplay.style.display = 'inline-block';+ }+}++/**+ * Update UI elements for unauthenticated user in the new UI+ */+function updateUIForUnauthenticatedUser() {+ console.log('Updating UI for unauthenticated user');++ // Find login/register buttons in the new UI based on the screenshot+ const loginButton = document.querySelector('a[href="login.html"], a.login');+ const registerButton = document.querySelector('a[href="register.html"], a.register');++ // Show login/register buttons if they exist+ if (loginButton) {+ console.log('Showing login button');+ loginButton.style.display = 'inline-block';+ }++ if (registerButton) {+ console.log('Showing register button');+ registerButton.style.display = 'inline-block';+ }++ // Hide user info if it exists+ const userDisplay = document.querySelector('.user-display');+ if (userDisplay) {+ userDisplay.style.display = 'none';+ }+}++/**+ * Logout user+ */+async function logout() {+ try {+ console.log('Logging out user');++ // Call logout API+ const response = await fetch('/api/auth/logout', {+ method: 'POST',+ headers: {+ 'Authorization': `Bearer ${authToken}`,+ 'Content-Type': 'application/json'+ }+ });++ // Clear auth data regardless of API response+ clearAuthData();+ updateUIForUnauthenticatedUser();++ // Show success message+ console.log('Logged out successfully');++ // Reload page to refresh UI+ window.location.reload();++ } catch (error) {+ console.error('Logout error:', error);++ // Still clear auth data even if API call fails+ clearAuthData();+ updateUIForUnauthenticatedUser();++ console.log('Logged out with errors');+ }+}++/**+ * Clear authentication data from localStorage+ */+function clearAuthData() {+ localStorage.removeItem('auth_token');+ localStorage.removeItem('user_info');+ authToken = null;+ currentUser = null;+}++/**+ * Validate token with the server+ */+async function validateToken() {+ if (!authToken) {+ clearAuthData();+ updateUIForUnauthenticatedUser();+ return;+ }++ try {+ // Use the full URL to avoid path issues+ const apiUrl = window.location.origin + '/api/auth/validate-token';++ const response = await fetch(apiUrl, {+ method: 'GET',+ headers: {+ 'Authorization': `Bearer ${authToken}`+ }+ });++ if (!response.ok) {+ const errorData = await response.json();+ console.error('Token validation failed:', errorData.message);+ throw new Error(errorData.message || 'Invalid token');+ }++ // Token is valid, update last active time+ const data = await response.json();+ if (data.user) {+ currentUser = data.user;+ localStorage.setItem('user_info', JSON.stringify(currentUser));+ updateUIForAuthenticatedUser();+ }++ return true;+ } catch (error) {+ console.error('Token validation error:', error);+ clearAuthData();+ updateUIForUnauthenticatedUser();++ return false;+ }+}++// Export authentication functions for use in other scripts+window.authNew = {+ isAuthenticated: () => !!authToken,+ getCurrentUser: () => currentUser,+ getToken: () => authToken,+ checkAuthState,+ logout+};\ No newline at end of filediff --git a/frontend/auth-redirect.html b/frontend/auth-redirect.htmlindex 6451da3..a52b3c8 100644--- a/frontend/auth-redirect.html+++ b/frontend/auth-redirect.html@@ -4,10 +4,8 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Authenticating...</title>- <link rel="stylesheet" href="./style.css?v=20250119004">- <script src="./theme-loader.js?v=20250119001"></script>- <script type="module" src="./js/services/authService.js"></script>- <script type="module" src="./js/services/apiService.js"></script>+ <link rel="stylesheet" href="style.css?v=20250119004">+ <script src="theme-loader.js?v=20250119001"></script><style>body {display: flex;@@ -161,20 +159,20 @@</script><!-- i18next Local Scripts -->- <script src="./js/lib/i18next.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>+ <script src="js/lib/i18next.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script><!-- i18n Configuration -->- <script src="./js/i18n.js?v=20250119001"></script>+ <script src="js/i18n.js?v=20250119001"></script>- <script src="./auth-redirect.js?v=20250119001"></script>+ <script src="auth-redirect.js?v=20250119001"></script><!-- Footer Width Fix -->- <script src="./footer-fix.js?v=20251024001"></script>+ <script src="footer-fix.js?v=20251024001"></script><!-- Footer Content Manager -->- <script src="./footer-content.js?v=20250119001"></script>+ <script src="footer-content.js?v=20250119001"></script><!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">diff --git a/frontend/auth.js b/frontend/auth.jsnew file mode 100644index 0000000..cd9ac8f--- /dev/null+++ b/frontend/auth.js@@ -0,0 +1,364 @@+/**+ * Authentication functionality for Warracker+ * Handles user login, logout, and authentication state management+ */++class AuthManager {+ constructor() {+ this.token = null;+ this.currentUser = null;+ this.onLogoutCallbacks = [];++ // Initial state load from localStorage+ this.token = localStorage.getItem('auth_token');+ const userInfoString = localStorage.getItem('user_info');+ if (userInfoString) {+ try {+ this.currentUser = JSON.parse(userInfoString);+ } catch (e) {+ console.error('Auth.js: Corrupt user_info in localStorage. Clearing.');+ this.currentUser = null;+ localStorage.removeItem('user_info');+ // Consider clearing token as well if user_info is corrupt+ // localStorage.removeItem('auth_token');+ // this.token = null;+ }+ }+ console.log('[Auth.js] Initial state:', { token: this.token ? 'present' : 'null', currentUser: this.currentUser });+ }++ isAuthenticated() {+ // User is authenticated if both token and currentUser (with an id) are present+ return !!(this.token && this.currentUser && this.currentUser.id);+ }++ getCurrentUser() {+ return this.currentUser;+ }++ getToken() {+ // Always return the current state of this.token, which should be synced with localStorage+ return this.token;+ }++ clearAuthData() {+ console.log('[Auth.js] Clearing auth data.');+ localStorage.removeItem('auth_token');+ localStorage.removeItem('user_info');+ this.token = null;+ this.currentUser = null;+ this.onLogoutCallbacks.forEach(cb => cb());+ }++ onLogout(callback) {+ if (typeof callback === 'function') {+ this.onLogoutCallbacks.push(callback);+ }+ }++ async checkAuthState(isInitialLoad = false) {+ console.log('[Auth.js] checkAuthState called. Initial load:', isInitialLoad);+ this.token = localStorage.getItem('auth_token'); // Re-read token, might have changed (e.g. by auth-redirect.js)+ const userInfoString = localStorage.getItem('user_info');++ this.currentUser = null; // Reset before check++ if (userInfoString) {+ try {+ this.currentUser = JSON.parse(userInfoString);+ } catch (e) {+ console.error('Auth.js: Failed to parse user_info from localStorage during checkAuthState. Clearing auth data.', e);+ this.clearAuthData(); // Clear potentially corrupt data+ this.updateUIBasedOnAuthState(); // Update UI to reflect logged-out state+ return; // Exit early+ }+ }++ if (this.token) {+ // If token exists, try to validate it and fetch/confirm user_info+ // This is crucial if user_info was missing or to refresh/validate existing user_info+ console.log('[Auth.js] Token found. Validating and fetching user info...');+ try {+ const response = await fetch('/api/auth/validate-token', {+ headers: { 'Authorization': `Bearer ${this.token}` }+ });++ if (response.ok) {+ const data = await response.json();+ if (data.valid && data.user && data.user.id) {+ this.currentUser = data.user;+ localStorage.setItem('user_info', JSON.stringify(this.currentUser)); // Ensure localStorage is up-to-date+ console.log('[Auth.js] Token validated, user_info updated/confirmed:', this.currentUser);+ } else {+ console.warn('[Auth.js] Token validation failed or user data invalid from API. Clearing auth data.');+ this.clearAuthData();+ }+ } else {+ console.warn(`[Auth.js] Token validation API call failed (status: ${response.status}). Clearing auth data.`);+ this.clearAuthData();+ }+ } catch (error) {+ console.error('[Auth.js] Error validating token / fetching user info:', error);+ this.clearAuthData();+ }+ } else {+ // No token, ensure everything is cleared+ if (this.currentUser) { // If there was user_info but no token, clear user_info+ console.log('[Auth.js] No token found, but user_info was present. Clearing user_info.');+ this.clearAuthData();+ }+ }++ this.updateUIBasedOnAuthState();+ }++ updateUIBasedOnAuthState() {+ const isAuthenticated = this.isAuthenticated();+ this._updateDOMForAuthState(isAuthenticated, this.currentUser);+ this.dispatchAuthStateEvent(isAuthenticated, this.currentUser);+ }++ _updateDOMForAuthState(isAuthenticated, user) {+ const authContainer = document.getElementById('authContainer');+ const userMenu = document.getElementById('userMenu');+ const userDisplayName = document.getElementById('userDisplayName');+ const userNameMenu = document.getElementById('userName');+ const userEmailMenu = document.getElementById('userEmail');+ const logoutMenuItem = document.getElementById('logoutMenuItem');++ // Select all potential login/register buttons more broadly+ const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn');+ const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn');+ const genericAuthButtonsContainers = document.querySelectorAll('.auth-buttons');+++ if (isAuthenticated && user) {+ console.log('Auth.js: Updating UI for AUTHENTICATED user:', user);+ if (authContainer) { authContainer.style.display = 'none'; authContainer.style.visibility = 'hidden'; }++ if (userMenu) {+ userMenu.style.display = 'block'; // Or 'flex' based on CSS+ userMenu.style.visibility = 'visible';+ const displayNameText = user.first_name || user.username || 'User';+ const fullNameText = `${user.first_name || ''} ${user.last_name || ''}`.trim() || user.username || 'User Name';+ if (userDisplayName) userDisplayName.textContent = displayNameText;+ if (userNameMenu) userNameMenu.textContent = fullNameText;+ if (userEmailMenu && user.email) userEmailMenu.textContent = user.email;+ }+ loginButtons.forEach(btn => { btn.style.display = 'none'; btn.style.visibility = 'hidden'; });+ registerButtons.forEach(btn => { btn.style.display = 'none'; btn.style.visibility = 'hidden'; });+ genericAuthButtonsContainers.forEach(container => {+ if (container.id !== 'authContainer') { // Avoid double-hiding if authContainer also has .auth-buttons+ container.style.display = 'none'; container.style.visibility = 'hidden';+ }+ });++ if (logoutMenuItem) {+ logoutMenuItem.style.display = 'flex'; // Assuming it's a flex item+ // Ensure logout listener is attached (can be done once in constructor or DOMContentLoaded)+ }+ } else {+ console.log('Auth.js: Updating UI for UNAUTHENTICATED user.');+ if (authContainer) { authContainer.style.display = 'flex'; authContainer.style.visibility = 'visible'; }++ if (userMenu) { userMenu.style.display = 'none'; userMenu.style.visibility = 'hidden'; }++ // Reset user display names if they exist+ if (userDisplayName) userDisplayName.textContent = 'User';+ if (userNameMenu) userNameMenu.textContent = 'User Name';+ if (userEmailMenu) userEmailMenu.textContent = '[email protected]';++ loginButtons.forEach(btn => { btn.style.display = 'inline-block'; btn.style.visibility = 'visible'; });+ registerButtons.forEach(btn => { btn.style.display = 'inline-block'; btn.style.visibility = 'visible'; });+ genericAuthButtonsContainers.forEach(container => {+ if (container.id !== 'authContainer') {+ container.style.display = 'flex'; // Or 'block'+ container.style.visibility = 'visible';+ }+ });+ if (logoutMenuItem) { logoutMenuItem.style.display = 'none'; }+ }+ }++ dispatchAuthStateEvent(isAuthenticated, user) {+ console.log('[Auth.js] Dispatching authStateReady event', { isAuthenticated, user });+ // Ensure this event is dispatched after the current call stack clears+ setTimeout(() => {+ window.dispatchEvent(new CustomEvent('authStateReady', {+ detail: { isAuthenticated, user }+ }));+ }, 0);+ }++ async login(username, password) {+ // Assuming showLoading/hideLoading are global or part of another module+ if (typeof showLoading === 'function') showLoading();+ try {+ const response = await fetch('/api/auth/login', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ username, password })+ });+ const data = await response.json();+ if (response.ok) {+ this.token = data.token;+ this.currentUser = data.user;+ localStorage.setItem('auth_token', this.token);+ localStorage.setItem('user_info', JSON.stringify(this.currentUser));+ this.updateUIBasedOnAuthState();+ return data; // Return data for login.js to handle redirect+ } else {+ throw new Error(data.message || 'Login failed');+ }+ } catch (error) {+ this.clearAuthData(); // Ensure state is cleared on login failure+ this.updateUIBasedOnAuthState();+ throw error; // Re-throw for login.js to handle+ } finally {+ if (typeof hideLoading === 'function') hideLoading();+ }+ }++ async logout() {+ if (typeof showLoading === 'function') showLoading();+ const currentTokenForApiCall = this.token; // Use current token for API call++ this.clearAuthData(); // Clear local state immediately+ this.updateUIBasedOnAuthState(); // Update UI to logged-out state++ try {+ if (currentTokenForApiCall) {+ await fetch('/api/auth/logout', {+ method: 'POST',+ headers: { 'Authorization': `Bearer ${currentTokenForApiCall}` }+ });+ console.log('[Auth.js] Logout API call successful.');+ }+ } catch (error) {+ console.error('[Auth.js] Logout API call failed, but user is logged out locally.', error);+ } finally {+ if (typeof hideLoading === 'function') hideLoading();+ // Redirect to login page after all operations+ if (window.location.pathname !== '/login.html') {+ window.location.href = 'login.html';+ }+ }+ }++ addAuthHeader(options = {}) {+ const token = this.getToken();+ if (!token) return options;++ const headers = options.headers || {};+ return { ...options, headers: { ...headers, 'Authorization': `Bearer ${token}`}};+ }+}++// Initialize and export+window.auth = new AuthManager();++// Initial check on DOMContentLoaded+document.addEventListener('DOMContentLoaded', async () => {+ console.log('[Auth.js] DOMContentLoaded - performing initial async auth state check.');+ await window.auth.checkAuthState(true); // Ensure auth state is processed first++ // Setup user menu toggle+ const userMenuBtn_original = document.getElementById('userMenuBtn');+ const userMenuDropdown = document.getElementById('userMenuDropdown');++ if (userMenuBtn_original && userMenuDropdown) {+ console.log('[Auth.js] Setting up user menu. Button:', userMenuBtn_original, 'Dropdown:', userMenuDropdown);++ // Robust listener attachment: clone the button to remove any prior listeners+ const userMenuBtn = userMenuBtn_original.cloneNode(true);+ userMenuBtn_original.parentNode.replaceChild(userMenuBtn, userMenuBtn_original);++ userMenuBtn.addEventListener('click', (e) => {+ e.stopPropagation(); // Prevent click from immediately closing due to document listener+ console.log('[Auth.js] userMenuBtn clicked - DEBUG INFO:', {+ userMenuDropdown: !!userMenuDropdown,+ dropdownClassList: userMenuDropdown ? Array.from(userMenuDropdown.classList) : 'not found',+ hasActiveClass: userMenuDropdown ? userMenuDropdown.classList.contains('active') : 'dropdown not found',+ buttonId: userMenuBtn.id,+ dropdownId: userMenuDropdown ? userMenuDropdown.id : 'not found'+ });++ userMenuDropdown.classList.toggle('active');++ const isNowActive = userMenuDropdown.classList.contains('active');+ console.log('[Auth.js] User menu toggled via userMenuBtn. Active:', isNowActive);++ // Add a temporary debug check to see if it gets closed immediately+ setTimeout(() => {+ const stillActive = userMenuDropdown.classList.contains('active');+ console.log('[Auth.js] User menu status after 100ms:', stillActive);+ if (isNowActive && !stillActive) {+ console.warn('[Auth.js] User menu was closed immediately! Possible global click interference.');+ }+ }, 100);+ });+ console.log('[Auth.js] User menu click listener attached to userMenuBtn.');+ } else {+ console.warn('[Auth.js] User menu button (userMenuBtn) or dropdown (userMenuDropdown) not found. Menu interactivity might be affected.');+ }++ // Setup settings gear menu toggle (if elements exist on the current page)+ const settingsBtn_original = document.getElementById('settingsBtn');+ const settingsMenu = document.getElementById('settingsMenu'); // The dropdown menu itself+ if (settingsBtn_original && settingsMenu) {+ const settingsBtn = settingsBtn_original.cloneNode(true);+ settingsBtn_original.parentNode.replaceChild(settingsBtn, settingsBtn_original);++ settingsBtn.addEventListener('click', function(e) {+ e.stopPropagation();+ settingsMenu.classList.toggle('active');+ console.log('[Auth.js] Settings menu toggled via settingsBtn.');+ });+ console.log('[Auth.js] Settings menu click listener attached to settingsBtn.');+ }++ // Global click listener to close dropdowns - ensure this is added only once+ if (!window._authJsGlobalClickListenerAdded) {+ document.addEventListener('click', (e) => {+ console.log('[Auth.js] Global click detected on:', e.target);++ // Re-fetch elements by ID inside the listener to ensure they are current+ const currentDropdown = document.getElementById('userMenuDropdown');+ const currentButton = document.getElementById('userMenuBtn'); // Use the standardized ID++ if (currentDropdown && currentButton && currentDropdown.classList.contains('active')) {+ console.log('[Auth.js] User menu is active, checking if click is outside...');+ const isOutsideDropdown = !currentDropdown.contains(e.target);+ const isOutsideButton = !currentButton.contains(e.target);+ console.log('[Auth.js] Click outside dropdown:', isOutsideDropdown, 'outside button:', isOutsideButton);++ if (isOutsideDropdown && isOutsideButton) {+ currentDropdown.classList.remove('active');+ console.log('[Auth.js] User menu closed by global click.');+ }+ }++ const currentSettingsMenu = document.getElementById('settingsMenu');+ const currentSettingsBtn = document.getElementById('settingsBtn');+ if (currentSettingsMenu && currentSettingsBtn && currentSettingsMenu.classList.contains('active') &&+ !currentSettingsMenu.contains(e.target) && !currentSettingsBtn.contains(e.target)) {+ currentSettingsMenu.classList.remove('active');+ console.log('[Auth.js] Settings menu closed by global click.');+ }+ });+ window._authJsGlobalClickListenerAdded = true;+ console.log('[Auth.js] Global click listener for dropdowns added.');+ }++ // Attach logout listener to logout menu item+ const logoutMenuItem_original = document.getElementById('logoutMenuItem');+ if (logoutMenuItem_original) {+ const logoutMenuItem = logoutMenuItem_original.cloneNode(true); // Ensures fresh listener+ logoutMenuItem_original.parentNode.replaceChild(logoutMenuItem, logoutMenuItem_original);+ logoutMenuItem.addEventListener('click', () => {+ console.log('[Auth.js] Logout menu item clicked.');+ window.auth.logout();+ });+ console.log('[Auth.js] Logout menu item listener attached.');+ }+});diff --git a/frontend/fix-auth-buttons-loader.js b/frontend/fix-auth-buttons-loader.jsnew file mode 100644index 0000000..1331153--- /dev/null+++ b/frontend/fix-auth-buttons-loader.js@@ -0,0 +1,48 @@+/**+ * Script to load the fix-auth-buttons.js script on all pages+ * This script should be included in the head of each HTML file+ */++// Log authentication status for debugging+console.log('fix-auth-buttons-loader.js is running');+console.log('Auth token exists:', !!localStorage.getItem('auth_token'));+console.log('User info exists:', !!localStorage.getItem('user_info'));++// Execute immediately to hide buttons as soon as possible+if (localStorage.getItem('auth_token')) {+ console.log('User is logged in, attempting to hide login/register buttons immediately');++ // Hide auth container if it exists+ const authContainer = document.getElementById('authContainer');+ if (authContainer) {+ console.log('Found authContainer, hiding it');+ authContainer.style.display = 'none';+ }++ // Hide individual buttons if they exist+ const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');+ const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');++ console.log('Found login buttons:', loginButtons.length);+ console.log('Found register buttons:', registerButtons.length);++ loginButtons.forEach(button => button.style.display = 'none');+ registerButtons.forEach(button => button.style.display = 'none');++ // Show user menu if it exists+ const userMenu = document.getElementById('userMenu');+ if (userMenu) {+ console.log('Found userMenu, showing it');+ userMenu.style.display = 'block';+ }+}++// Create a script element to load the actual fix script+const script = document.createElement('script');+script.src = 'fix-auth-buttons.js';+script.async = true;++// Add the script to the document+document.head.appendChild(script);++console.log('Added fix-auth-buttons.js script to the page');\ No newline at end of filediff --git a/frontend/fix-auth-buttons.js b/frontend/fix-auth-buttons.jsnew file mode 100644index 0000000..d6eead0--- /dev/null+++ b/frontend/fix-auth-buttons.js@@ -0,0 +1,76 @@+/**+ * Script to fix the login and register buttons in the new UI+ * This script specifically targets the buttons shown in the screenshot+ */++// Log execution+console.log('fix-auth-buttons.js loaded and executing');++// Function to check if user is authenticated+function isAuthenticated() {+ const token = localStorage.getItem('auth_token');+ // console.log('Auth token check:', !!token); // Keep console logs minimal here if auth.js is primary+ return !!token;+}++// Function to find elements by text content+function getElementsByText(selector, text) {+ const elements = document.querySelectorAll(selector);+ return Array.prototype.filter.call(elements, element => element.textContent.trim() === text);+}++// Function to hide login and register buttons if user is authenticated+function updateAuthButtons() {+ // console.log('fix-auth-buttons.js: updateAuthButtons executing...'); // Keep console logs minimal here+ if (isAuthenticated()) {+ // console.log('fix-auth-buttons.js: User is authenticated, hiding login/register buttons');+ const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');+ const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');+ const authContainer = document.getElementById('authContainer');+ const userMenu = document.getElementById('userMenu'); // Ensure this ID is consistent or use userMenuBtn's parent++ loginButtons.forEach(button => { button.style.display = 'none'; button.style.visibility = 'hidden'; });+ registerButtons.forEach(button => { button.style.display = 'none'; button.style.visibility = 'hidden'; });+ if (authContainer) { authContainer.style.display = 'none'; authContainer.style.visibility = 'hidden';}+ if (userMenu) { userMenu.style.display = 'block'; userMenu.style.visibility = 'visible'; }++ const userInfo = localStorage.getItem('user_info');+ if (userInfo) {+ try {+ const user = JSON.parse(userInfo);+ const displayName = user.first_name || user.username || 'User';+ const userDisplayName = document.getElementById('userDisplayName');+ if (userDisplayName) userDisplayName.textContent = displayName;++ const userNameMenu = document.getElementById('userName');+ if (userNameMenu) {+ userNameMenu.textContent = `${user.first_name || ''} ${user.last_name || ''}`.trim() || user.username || 'User Name';+ }+ const userEmailMenu = document.getElementById('userEmail');+ if (userEmailMenu && user.email) userEmailMenu.textContent = user.email;+ } catch (error) { /* console.error('fix-auth-buttons.js: Error parsing user info:', error); */ }+ }+ } else {+ // console.log('fix-auth-buttons.js: User is not authenticated, showing login/register buttons');+ const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');+ const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');+ const authContainer = document.getElementById('authContainer');+ const userMenu = document.getElementById('userMenu');++ loginButtons.forEach(button => { button.style.display = 'inline-block'; button.style.visibility = 'visible'; });+ registerButtons.forEach(button => { button.style.display = 'inline-block'; button.style.visibility = 'visible'; });+ if (authContainer) { authContainer.style.display = 'flex'; authContainer.style.visibility = 'visible'; }+ if (userMenu) { userMenu.style.display = 'none'; userMenu.style.visibility = 'hidden'; }+ }+}++// Run immediately+// console.log('Running updateAuthButtons immediately from fix-auth-buttons.js');+updateAuthButtons();++// Update auth buttons when page loads+document.addEventListener('DOMContentLoaded', () => {+ // console.log('DOMContentLoaded event triggered in fix-auth-buttons.js, updating auth buttons');+ updateAuthButtons();+ // REMOVE: setupUserMenuDropdown();+});\ No newline at end of filediff --git a/frontend/include-auth-new.js b/frontend/include-auth-new.jsnew file mode 100644index 0000000..56e55f2--- /dev/null+++ b/frontend/include-auth-new.js@@ -0,0 +1,128 @@+/**+ * Immediate Authentication State Handler+ *+ * This script runs as soon as possible to hide login/register buttons if a user is logged in+ * It should be included directly in the HTML before any other scripts+ */++console.log('include-auth-new.js: Running immediate auth check');++// Function to update UI based on auth state (extracted for reuse)+function updateAuthUI() {+ if (localStorage.getItem('auth_token')) {+ console.log('include-auth-new.js: Updating UI for authenticated user');+ // Inject CSS to hide auth buttons and show user menu+ const styleId = 'auth-ui-style';+ let style = document.getElementById(styleId);+ if (!style) {+ style = document.createElement('style');+ style.id = styleId;+ document.head.appendChild(style);+ }+ style.textContent = `+ #authContainer, .auth-buttons, a[href="login.html"], a[href="register.html"],+ .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn {+ display: none !important;+ visibility: hidden !important;+ }+ #userMenu, .user-menu {+ display: block !important;+ visibility: visible !important;+ }+ `;++ // Update user info display elements immediately+ try {+ var userInfoStr = localStorage.getItem('user_info');+ if (userInfoStr) {+ var userInfo = JSON.parse(userInfoStr);+ var displayName = userInfo.username || 'User';+ var userDisplayName = document.getElementById('userDisplayName');+ if (userDisplayName) userDisplayName.textContent = displayName;+ var userName = document.getElementById('userName');+ if (userName) {+ userName.textContent = (userInfo.first_name || '') + ' ' + (userInfo.last_name || '');+ if (!userName.textContent.trim()) userName.textContent = userInfo.username || 'User';+ }+ var userEmail = document.getElementById('userEmail');+ if (userEmail && userInfo.email) userEmail.textContent = userInfo.email;+ }+ } catch (e) {+ console.error('include-auth-new.js: Error updating user info display:', e);+ }++ } else {+ console.log('include-auth-new.js: Updating UI for logged-out user');+ // Inject CSS to show auth buttons and hide user menu+ const styleId = 'auth-ui-style';+ let style = document.getElementById(styleId);+ if (!style) {+ style = document.createElement('style');+ style.id = styleId;+ document.head.appendChild(style);+ }+ style.textContent = `+ #authContainer, .auth-buttons {+ display: flex !important; /* Use flex for container */+ visibility: visible !important;+ }+ a[href="login.html"], a[href="register.html"],+ .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn {+ display: inline-block !important; /* Use inline-block for buttons */+ visibility: visible !important;+ }+ #userMenu, .user-menu {+ display: none !important;+ visibility: hidden !important;+ }+ `;+ }+}++// Immediately check auth state and update UI+updateAuthUI();++// Listen for changes to localStorage and update UI without reloading+window.addEventListener('storage', function(event) {+ if (event.key === 'auth_token' || event.key === 'user_info') {+ console.log(`include-auth-new.js: Storage event detected for ${event.key}. Updating UI.`);+ updateAuthUI(); // Update UI instead of reloading+ // window.location.reload(); // <-- Keep commented out / Remove permanently+ }+});++/**+ * Script to include the new authentication script in existing HTML files+ * This script should be included at the end of the body in each HTML file+ */++// Function to load and execute the new authentication script+function loadAuthNewScript() {+ // Create a script element+ const script = document.createElement('script');+ script.src = 'auth-new.js';+ script.async = true;++ // Add the script to the document+ document.body.appendChild(script);++ console.log('Added auth-new.js script to the page');+}++// Function to check if we're using the new UI+function isNewUI() {+ // Check for elements that are specific to the new UI+ const loginButton = document.querySelector('a[href="login.html"].auth-btn, a.login');+ const registerButton = document.querySelector('a[href="register.html"].auth-btn, a.register');++ // If we find these elements, we're using the new UI+ return !!(loginButton || registerButton);+}++// Load the new authentication script if we're using the new UI+if (isNewUI()) {+ console.log('Detected new UI, loading auth-new.js');+ loadAuthNewScript();+} else {+ console.log('Using old UI, not loading auth-new.js');+}\ No newline at end of filediff --git a/frontend/index.html b/frontend/index.htmlindex 0306769..1d70404 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -2,56 +2,45 @@<html><head><!-- Authentication redirect script -->- <script src="./auth-redirect.js?v=20250119001" data-protected="true"></script>+ <script src="auth-redirect.js?v=20250119001" data-protected="true"></script><!-- Include authentication script first to handle login state immediately -->-+ <script src="include-auth-new.js?v=20250119001"></script><!-- File utilities script for secure file handling -->- <script src="./file-utils.js?v=20250119001"></script>+ <script src="file-utils.js?v=20250119001"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Warracker - Warranty Tracker</title><!-- Add standard favicon.ico link -->- <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">+ <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"><!-- Replace the old favicon link --><!-- <link rel="icon" type="image/png" href="img/favicon.png"> --><!-- Add new favicon links -->- <link rel="icon" type="image/png" sizes="16x16" href="./img/favicon-16x16.png?v=2">- <link rel="icon" type="image/png" sizes="32x32" href="./img/favicon-32x32.png?v=2">- <link rel="apple-touch-icon" sizes="180x180" href="./img/favicon-512x512.png">- <link rel="manifest" href="./manifest.json">- <link rel="stylesheet" href="./style.css?v=20250119004">- <script src="./theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->- <script type="module" src="./js/store.js"></script>- <script type="module" src="./js/services/authService.js"></script>- <script type="module" src="./js/services/apiService.js"></script>- <script type="module" src="./js/components/warrantyCard.js"></script>- <script type="module" src="./js/components/tag.js"></script>- <script type="module" src="./js/components/editModal.js"></script>- <script type="module" src="./js/components/modals.js"></script>- <script type="module" src="./js/components/claims.js"></script>- <script type="module" src="./js/components/notes.js"></script>- <script type="module" src="./js/components/paperless.js"></script>- <script type="module" src="./js/components/ui.js"></script>+ <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">+ <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">+ <link rel="manifest" href="manifest.json">+ <link rel="stylesheet" href="style.css?v=20250119004">+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early --><!-- Font Awesome for icons --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css"><!-- Load header fix styles to ensure consistent header styling -->- <link rel="stylesheet" href="./header-fix.css?v=20250119001">+ <link rel="stylesheet" href="header-fix.css?v=20250119001"><!-- Load fix for auth buttons -->-+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script><!-- Mobile Header specific styles -->- <link rel="stylesheet" href="./mobile-header.css?v=20250119002">+ <link rel="stylesheet" href="mobile-header.css?v=20250119002"><!-- i18next Local Scripts -->- <script src="./js/lib/i18next.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>+ <script src="js/lib/i18next.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script><!-- i18n Configuration -->- <script src="./js/i18n.js?v=20250119001"></script>+ <script src="js/i18n.js?v=20250119001"></script><!-- Immediate authentication check script --><script>@@ -106,7 +95,7 @@</script><!-- Registration status check script -->-+ <script src="registration-status.js?v=20250119001"></script></head><body><!-- Header -->@@ -1336,9 +1325,8 @@<div class="loading-spinner"></div></div>-- <script src="./script.js?v=20250119002" defer></script>- <script type="module" src="./js/index.js"></script>+ <script src="auth.js?v=20250119001"></script>+ <script src="script.js?v=20250119002"></script><script>// Lightweight UI logic for Filter/Sort popovers (no change to core logic)document.addEventListener('DOMContentLoaded', function () {@@ -1647,10 +1635,10 @@</script><!-- Footer Width Fix -->- <script src="./footer-fix.js?v=20251024001"></script>+ <script src="footer-fix.js?v=20251024001"></script><!-- Footer Content Manager -->- <script src="./footer-content.js?v=20250119001"></script>+ <script src="footer-content.js?v=20250119001"></script><!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">@@ -1696,23 +1684,5 @@});</script>-<!-- Templates (do not affect layout) -->-<template id="warranty-card-template">- <div class="warranty-card">- <div class="product-name-header">- <h3 class="warranty-title"></h3>- <div class="warranty-actions">- <button class="action-btn edit-btn" title="Edit"><i class="fas fa-edit"></i></button>- <button class="action-btn delete-btn" title="Delete"><i class="fas fa-trash"></i></button>- </div>- </div>- <div class="warranty-content">- <div class="warranty-info"></div>- </div>- <div class="warranty-status-row"><span></span></div>- </div>-</template></body></html>--</html>diff --git a/frontend/login.html b/frontend/login.htmlindex 2c5c641..ea704fd 100644--- a/frontend/login.html+++ b/frontend/login.html@@ -1,19 +1,17 @@<!DOCTYPE html><html><head>- <script src="./auth-redirect.js?v=20250119001" data-protected="false"></script>+ <script src="auth-redirect.js?v=20250119001" data-protected="false"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title data-i18n="auth.login_title">Login - Warracker</title>- <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">- <link rel="icon" type="image/png" sizes="16x16" href="./img/favicon-16x16.png?v=2">- <link rel="icon" type="image/png" sizes="32x32" href="./img/favicon-32x32.png?v=2">- <link rel="apple-touch-icon" sizes="180x180" href="./img/favicon-512x512.png">- <link rel="manifest" href="./manifest.json">- <link rel="stylesheet" href="./style.css?v=20250119004">- <script src="./theme-loader.js?v=20250119001"></script>- <script type="module" src="./js/services/authService.js"></script>- <script type="module" src="./js/services/apiService.js"></script>+ <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">+ <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">+ <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">+ <link rel="manifest" href="manifest.json">+ <link rel="stylesheet" href="style.css?v=20250119004">+ <script src="theme-loader.js?v=20250119001"></script><script>// If user is authenticated and has a theme in user_info (from previous sessions), reflect it earlytry {@@ -24,11 +22,11 @@} catch (_) {}</script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css">- <script src="./js/lib/i18next.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>- <script src="./js/i18n.js?v=20250119001"></script>-+ <script src="js/lib/i18next.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>+ <script src="js/i18n.js?v=20250119001"></script>+ <script src="registration-status.js?v=20250119001"></script></head><body class="login-page-body">@@ -84,7 +82,7 @@</form><div id="ssoSection" style="display: none;"><div class="separator"><span>OR</span></div>- <a href="./api/oidc/login" id="oidcLoginButton" class="btn btn-secondary btn-block btn-sso" style="text-decoration: none;">+ <a href="/api/oidc/login" id="oidcLoginButton" class="btn btn-secondary btn-block btn-sso" style="text-decoration: none;"><i class="fab fa-openid" style="margin-right: 8px;"></i> <span>Login with SSO Provider</span></a></div>@@ -96,7 +94,7 @@</div></div>-+ <script src="auth.js?v=20250119001"></script><script>document.addEventListener('DOMContentLoaded', function() {// Check for OIDC errors in URL parameters and display themdiff --git a/frontend/register.html b/frontend/register.htmlindex 6fa1c9e..b67b39a 100644--- a/frontend/register.html+++ b/frontend/register.html@@ -2,37 +2,34 @@<html><head><!-- Authentication redirect script -->- <script src="./auth-redirect.js?v=20250119001" data-protected="false"></script>+ <script src="auth-redirect.js?v=20250119001" data-protected="false"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title data-i18n="auth.register">Register - Warracker</title><!-- Favicons -->- <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">- <link rel="icon" type="image/png" sizes="16x16" href="./img/favicon-16x16.png?v=2">- <link rel="icon" type="image/png" sizes="32x32" href="./img/favicon-32x32.png?v=2">- <link rel="apple-touch-icon" sizes="180x180" href="./img/favicon-512x512.png">- <link rel="manifest" href="./manifest.json">- <link rel="stylesheet" href="./style.css?v=20250119004">- <script src="./theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->- <script type="module" src="./js/services/authService.js"></script>- <script type="module" src="./js/services/apiService.js"></script>+ <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">+ <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">+ <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">+ <link rel="manifest" href="manifest.json">+ <link rel="stylesheet" href="style.css?v=20250119004">+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early --><!-- Font Awesome for icons --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css"><!-- Load header fix styles to ensure consistent header styling -->- <link rel="stylesheet" href="./header-fix.css?v=20250119001">+ <link rel="stylesheet" href="header-fix.css?v=20250119001"><!-- Mobile Header specific styles -->- <link rel="stylesheet" href="./mobile-header.css?v=20250119002">+ <link rel="stylesheet" href="mobile-header.css?v=20250119002"><!-- i18next Local Scripts -->- <script src="./js/lib/i18next.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>+ <script src="js/lib/i18next.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script><!-- i18n initialization script -->- <script src="./js/i18n.js?v=20250119001"></script>+ <script src="js/i18n.js?v=20250119001"></script><!-- Load fix for auth buttons -->-- <script src="./script.js?v=20250119001" defer></script>- <script type="module" src="./js/index.js"></script>+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script>+ <script src="script.js?v=20250119001" defer></script><style>.auth-container {max-width: 500px;@@ -240,7 +237,7 @@</style><!-- Registration status check script -->-+ <script src="registration-status.js?v=20250119001"></script><script>// Additional handling for the register pagedocument.addEventListener('DOMContentLoaded', function() {@@ -380,7 +377,7 @@</div><!-- Script for authentication -->-+ <script src="auth.js?v=20250119001"></script><script>document.addEventListener('DOMContentLoaded', function() {const registerForm = document.getElementById('registerForm');@@ -622,10 +619,10 @@</script><!-- Footer Width Fix -->- <script src="./footer-fix.js?v=20251024001"></script>+ <script src="footer-fix.js?v=20251024001"></script><!-- Footer Content Manager -->- <script src="./footer-content.js?v=20250119001"></script>+ <script src="footer-content.js?v=20250119001"></script><!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">diff --git a/frontend/registration-status.js b/frontend/registration-status.jsnew file mode 100644index 0000000..388e94d--- /dev/null+++ b/frontend/registration-status.js@@ -0,0 +1,92 @@+/**+ * Registration Status Checker+ *+ * This script checks if registration is enabled on the site and hides registration buttons/links if disabled.+ * Include this script in all pages that have registration links or buttons.+ */++document.addEventListener('DOMContentLoaded', function() {+ // Only check if user is not logged in+ if (!localStorage.getItem('auth_token')) {+ checkRegistrationStatus();+ }+});++/**+ * Check if registration is enabled and hide registration elements if disabled+ */+function checkRegistrationStatus() {+ fetch('/api/auth/registration-status')+ .then(response => response.json())+ .then(data => {+ if (!data.enabled) {+ // Hide all registration links and buttons+ hideRegistrationElements();+ }+ })+ .catch(error => {+ console.error('Error checking registration status:', error);+ });+}++/**+ * Hide all registration-related elements on the page+ */+function hideRegistrationElements() {+ // Hide elements with specific classes+ const elements = [+ '.register-btn', // Main navigation register button+ 'a[href="register.html"]', // Links to register page+ 'a[href="./register.html"]', // Links to register page (relative)+ 'a[href="/register.html"]' // Links to register page (root relative)+ ];++ // Apply to all matching elements+ elements.forEach(selector => {+ document.querySelectorAll(selector).forEach(element => {+ element.style.display = 'none';+ });+ });++ // Special case for auth container in the header+ const authContainer = document.getElementById('authContainer');+ if (authContainer) {+ // Check if it has multiple children and at least one is hidden+ const children = authContainer.children;+ let visibleCount = 0;++ for (let i = 0; i < children.length; i++) {+ if (children[i].style.display !== 'none') {+ visibleCount++;+ }+ }++ // If there's only one visible child, adjust the container styling+ if (visibleCount === 1) {+ authContainer.style.justifyContent = 'flex-end';+ }+ }++ // Special case for auth links in login/register pages+ const authLinks = document.querySelector('.auth-links');+ if (authLinks) {+ const links = authLinks.querySelectorAll('a');+ links.forEach(link => {+ if (link.textContent === 'Create Account' ||+ link.href.includes('register.html')) {+ link.style.display = 'none';+ }+ });++ // Add a message about registration being disabled if we're on the login page+ if (window.location.pathname.includes('login.html')) {+ const infoMessage = document.createElement('div');+ infoMessage.className = 'registration-info';+ infoMessage.innerHTML = '<small>New account registration is currently disabled</small>';+ infoMessage.style.color = 'var(--text-muted)';+ infoMessage.style.fontSize = '0.8em';+ infoMessage.style.marginTop = '10px';+ authLinks.appendChild(infoMessage);+ }+ }+}\ No newline at end of filediff --git a/frontend/reset-password-request.html b/frontend/reset-password-request.htmlindex d55d9ca..7ef017b 100644--- a/frontend/reset-password-request.html+++ b/frontend/reset-password-request.html@@ -5,31 +5,28 @@<meta name="viewport" content="width=device-width, initial-scale=1.0"><title data-i18n="auth.reset_password_title">Warracker - Reset Password</title><!-- Favicons -->- <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">- <link rel="icon" type="image/png" sizes="16x16" href="./img/favicon-16x16.png?v=2">- <link rel="icon" type="image/png" sizes="32x32" href="./img/favicon-32x32.png?v=2">- <link rel="apple-touch-icon" sizes="180x180" href="./img/favicon-512x512.png">- <link rel="manifest" href="./manifest.json">- <link rel="stylesheet" href="./style.css?v=20250119004">- <script src="./theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->- <script type="module" src="./js/services/authService.js"></script>- <script type="module" src="./js/services/apiService.js"></script>+ <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">+ <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">+ <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">+ <link rel="manifest" href="manifest.json">+ <link rel="stylesheet" href="style.css?v=20250119004">+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early --><!-- Font Awesome for icons --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css"><!-- Load header fix styles to ensure consistent header styling -->- <link rel="stylesheet" href="./header-fix.css?v=20250119001">+ <link rel="stylesheet" href="header-fix.css?v=20250119001"><!-- Mobile Header specific styles -->- <link rel="stylesheet" href="./mobile-header.css?v=20250119002">+ <link rel="stylesheet" href="mobile-header.css?v=20250119002"><!-- i18next Local Scripts -->- <script src="./js/lib/i18next.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>+ <script src="js/lib/i18next.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script><!-- i18n initialization script -->- <script src="./js/i18n.js?v=20250119001"></script>+ <script src="js/i18n.js?v=20250119001"></script><!-- Load fix for auth buttons -->-- <script src="./script.js?v=20250119001" defer></script>- <script type="module" src="./js/index.js"></script>+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script>+ <script src="script.js?v=20250119001" defer></script><style>.auth-container {max-width: 400px;@@ -100,7 +97,7 @@</style><!-- Registration status check script -->-+ <script src="registration-status.js?v=20250119001"></script></head><body><!-- Header -->@@ -262,13 +259,13 @@document.addEventListener('DOMContentLoaded', initializeTheme);</script>-+ <script src="auth.js?v=20250119001"></script><!-- Footer Width Fix -->- <script src="./footer-fix.js?v=20251024001"></script>+ <script src="footer-fix.js?v=20251024001"></script><!-- Footer Content Manager -->- <script src="./footer-content.js?v=20250119001"></script>+ <script src="footer-content.js?v=20250119001"></script><!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">diff --git a/frontend/reset-password.html b/frontend/reset-password.htmlindex 45a2c0c..bd351c7 100644--- a/frontend/reset-password.html+++ b/frontend/reset-password.html@@ -5,31 +5,28 @@<meta name="viewport" content="width=device-width, initial-scale=1.0"><title data-i18n="auth.set_new_password_title">Warracker - Set New Password</title><!-- Favicons -->- <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">- <link rel="icon" type="image/png" sizes="16x16" href="./img/favicon-16x16.png?v=2">- <link rel="icon" type="image/png" sizes="32x32" href="./img/favicon-32x32.png?v=2">- <link rel="apple-touch-icon" sizes="180x180" href="./img/favicon-512x512.png">- <link rel="manifest" href="./manifest.json">- <link rel="stylesheet" href="./style.css?v=20250119004">- <script src="./theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->- <script type="module" src="./js/services/authService.js"></script>- <script type="module" src="./js/services/apiService.js"></script>+ <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">+ <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">+ <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">+ <link rel="manifest" href="manifest.json">+ <link rel="stylesheet" href="style.css?v=20250119004">+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early --><!-- Font Awesome for icons --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css"><!-- Load header fix styles to ensure consistent header styling -->- <link rel="stylesheet" href="./header-fix.css?v=20250119001">+ <link rel="stylesheet" href="header-fix.css?v=20250119001"><!-- Mobile Header specific styles -->- <link rel="stylesheet" href="./mobile-header.css?v=20250119002">+ <link rel="stylesheet" href="mobile-header.css?v=20250119002"><!-- i18next Local Scripts -->- <script src="./js/lib/i18next.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>+ <script src="js/lib/i18next.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script><!-- i18n initialization script -->- <script src="./js/i18n.js?v=20250119001"></script>+ <script src="js/i18n.js?v=20250119001"></script><!-- Load fix for auth buttons -->-- <script src="./script.js?v=20250119001" defer></script>- <script type="module" src="./js/index.js"></script>+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script>+ <script src="script.js?v=20250119001" defer></script><style>.auth-container {max-width: 400px;@@ -157,7 +154,7 @@</style><!-- Registration status check script -->-+ <script src="registration-status.js?v=20250119001"></script></head><body><!-- Header -->@@ -429,13 +426,13 @@</script><!-- Scripts -->-+ <script src="auth.js?v=20250119001"></script><!-- Footer Width Fix -->- <script src="./footer-fix.js?v=20251024001"></script>+ <script src="footer-fix.js?v=20251024001"></script><!-- Footer Content Manager -->- <script src="./footer-content.js?v=20250119001"></script>+ <script src="footer-content.js?v=20250119001"></script><!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">diff --git a/frontend/script.js b/frontend/script.jsindex 48469e4..dc064ef 100644--- a/frontend/script.js+++ b/frontend/script.js@@ -161,23 +161,27 @@ console.log('[DEBUG] script.js loaded and running');// alert('script.js loaded!'); // Remove alert after confirming script loads// Global variables+let warranties = [];let warrantiesLoaded = false; // Track if warranties have been loaded from APIlet lastLoadedArchived = false; // Track if the current warranties array came from archived endpointlet lastLoadedIncludesArchived = false; // Track if the current warranties list includes archived itemslet currentTabIndex = 0;let tabContents = []; // Initialize as empty array--// Read-only bridges for module access (keep internal state source of truth here)-try {- Object.defineProperty(window, 'lastLoadedArchived', { get: () => lastLoadedArchived, set: (v) => { lastLoadedArchived = !!v; } });- Object.defineProperty(window, 'lastLoadedIncludesArchived', { get: () => lastLoadedIncludesArchived, set: (v) => { lastLoadedIncludesArchived = !!v; } });-} catch (_) {}let editMode = false;let currentWarrantyId = null;let userPreferencePrefix = null; // <<< ADDED GLOBAL PREFIX VARIABLElet isGlobalView = false; // Track if admin is viewing all users' warranties+let currentFilters = {+ status: 'all',+ tag: 'all',+ search: '',+ sortBy: 'expiration',+ vendor: 'all', // Added vendor filter+ warranty_type: 'all' // Added warranty type filter+};// Tag related variables+let allTags = [];let selectedTags = []; // Will hold objects with id, name, color// Global variable for edit mode tags@@ -579,7 +583,7 @@ document.addEventListener('DOMContentLoaded', function() {if (searchBtn && searchInput) {searchBtn.addEventListener('click', function(e) {e.preventDefault();- if (window.store && window.store.updateFilter) window.store.updateFilter('search', searchInput.value.toLowerCase());+ currentFilters.search = searchInput.value.toLowerCase();applyFilters();});}@@ -588,8 +592,7 @@ document.addEventListener('DOMContentLoaded', function() {const globalManageTagsBtn = document.getElementById('globalManageTagsBtn');if (globalManageTagsBtn) {globalManageTagsBtn.addEventListener('click', async () => {- const __tags = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];- if (!__tags || __tags.length === 0) {+ if (!allTags || allTags.length === 0) {showLoadingSpinner();try {await loadTags();@@ -753,7 +756,7 @@ document.addEventListener('DOMContentLoaded', function() {if (document.getElementById('warrantiesList')) {console.log("[runAuthenticatedTasks] Loading warranty data...");await loadWarranties(true); // Pass true- console.log('[DEBUG] After loadWarranties, warranties array:', (window.store && window.store.getWarranties && window.store.getWarranties()) || []);+ console.log('[DEBUG] After loadWarranties, warranties array:', warranties);// After warranties are loaded and filter dropdowns populated, load filter/sort prefs and applyloadFilterAndSortPreferences();// Reflect saved filters in UI selects if present@@ -762,12 +765,11 @@ document.addEventListener('DOMContentLoaded', function() {const vendorFilterEl = document.getElementById('vendorFilter');const warrantyTypeFilterEl = document.getElementById('warrantyTypeFilter');const sortByEl = document.getElementById('sortBy');- const __filters = (window.store && window.store.getFilters && window.store.getFilters()) || {};- if (statusFilterEl && __filters.status) statusFilterEl.value = __filters.status;- if (tagFilterEl && __filters.tag) tagFilterEl.value = __filters.tag;- if (vendorFilterEl && __filters.vendor) vendorFilterEl.value = __filters.vendor;- if (warrantyTypeFilterEl && __filters.warranty_type) warrantyTypeFilterEl.value = __filters.warranty_type;- if (sortByEl && __filters.sortBy) sortByEl.value = __filters.sortBy;+ if (statusFilterEl && currentFilters.status) statusFilterEl.value = currentFilters.status;+ if (tagFilterEl && currentFilters.tag) tagFilterEl.value = currentFilters.tag;+ if (vendorFilterEl && currentFilters.vendor) vendorFilterEl.value = currentFilters.vendor;+ if (warrantyTypeFilterEl && currentFilters.warranty_type) warrantyTypeFilterEl.value = currentFilters.warranty_type;+ if (sortByEl && currentFilters.sortBy) sortByEl.value = currentFilters.sortBy;// Update the filter indicator if availableif (typeof window.updateFilterIndicator === 'function') {window.updateFilterIndicator();@@ -830,14 +832,6 @@ function initializeTheme() {// Variableslet currentView = 'grid'; // Default viewlet expiringSoonDays = 30; // Default value, will be updated from user preferences-try {- Object.defineProperty(window, 'currentView', { get: () => currentView });-} catch (_) {}--// Bridge for global view flag-try {- Object.defineProperty(window, 'isGlobalView', { get: () => isGlobalView, set: (v) => { isGlobalView = !!v; } });-} catch (_) {}// API URLconst API_URL = '/api/warranties';@@ -1495,18 +1489,16 @@ function resetForm() {async function exportWarranties() {console.log('[EXPORT DEBUG] Starting export process');- const __warrantiesData = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];- const __filters = (window.store && window.store.getFilters && window.store.getFilters()) || {};- console.log('[EXPORT DEBUG] Total warranties in memory:', __warrantiesData.length);- console.log('[EXPORT DEBUG] Current filters:', __filters);+ console.log('[EXPORT DEBUG] Total warranties in memory:', warranties.length);+ console.log('[EXPORT DEBUG] Current filters:', currentFilters);// Get filtered warranties- let warrantiesToExport = [...__warrantiesData];+ let warrantiesToExport = [...warranties];console.log('[EXPORT DEBUG] Initial warranties to export:', warrantiesToExport.length);// Apply current filters- if (__filters.search) {- const searchTerm = __filters.search.toLowerCase();+ 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@@ -1525,17 +1517,17 @@ async function exportWarranties() {console.log('[EXPORT DEBUG] After search filter:', warrantiesToExport.length);}- if (__filters.status !== 'all') {- console.log('[EXPORT DEBUG] Applying status filter:', __filters.status);+ if (currentFilters.status !== 'all') {+ console.log('[EXPORT DEBUG] Applying status filter:', currentFilters.status);warrantiesToExport = warrantiesToExport.filter(warranty =>- warranty.status === __filters.status+ warranty.status === currentFilters.status);console.log('[EXPORT DEBUG] After status filter:', warrantiesToExport.length);}// Apply tag filter- if (__filters.tag !== 'all') {- const tagId = parseInt(__filters.tag);+ 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) &&@@ -1545,19 +1537,19 @@ async function exportWarranties() {}// Apply vendor filter- if (__filters.vendor !== 'all') {- console.log('[EXPORT DEBUG] Applying vendor filter:', __filters.vendor);+ if (currentFilters.vendor !== 'all') {+ console.log('[EXPORT DEBUG] Applying vendor filter:', currentFilters.vendor);warrantiesToExport = warrantiesToExport.filter(warranty =>- (warranty.vendor || '').toLowerCase() === __filters.vendor.toLowerCase()+ (warranty.vendor || '').toLowerCase() === currentFilters.vendor.toLowerCase());console.log('[EXPORT DEBUG] After vendor filter:', warrantiesToExport.length);}// Apply warranty type filter- if (__filters.warranty_type !== 'all') {- console.log('[EXPORT DEBUG] Applying warranty type filter:', __filters.warranty_type);+ if (currentFilters.warranty_type !== 'all') {+ console.log('[EXPORT DEBUG] Applying warranty type filter:', currentFilters.warranty_type);warrantiesToExport = warrantiesToExport.filter(warranty =>- (warranty.warranty_type || '').toLowerCase() === __filters.warranty_type.toLowerCase()+ (warranty.warranty_type || '').toLowerCase() === currentFilters.warranty_type.toLowerCase());console.log('[EXPORT DEBUG] After warranty type filter:', warrantiesToExport.length);}@@ -2108,17 +2100,205 @@ function processWarrantyData(warranty) {// Function to process all warranties in the arrayfunction processAllWarranties() {console.log('Processing all warranties in array...');- const __w = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];- if (__w && __w.length > 0) {- const __processed = __w.map(warranty => processWarrantyData(warranty));- if (window.store && window.store.setWarranties) window.store.setWarranties(__processed);+ if (warranties && warranties.length > 0) {+ warranties = warranties.map(warranty => processWarrantyData(warranty));}- console.log('Processed warranties:', (window.store && window.store.getWarranties && window.store.getWarranties()) || []);+ console.log('Processed warranties:', warranties);}-async function loadWarranties(isAuthenticated) {- if (window.warrantyListController && typeof window.warrantyListController.loadWarranties === 'function') {- return window.warrantyListController.loadWarranties(isAuthenticated);+async function loadWarranties(isAuthenticated) { // Added isAuthenticated parameter+ // +++ REMOVED: Ensure Preferences are loaded FIRST (Now handled by authStateReady) ++++ // await loadAndApplyUserPreferences();+ // +++ Preferences Loaded +++++ try {+ console.log('[DEBUG] Entered loadWarranties, isAuthenticated:', isAuthenticated);++ // Reset the flag when starting to load warranties+ warrantiesLoaded = false;++ showLoading();++ // Fetch user preferences (including date format) before loading warranties+ // --- THIS INNER PREFERENCE FETCH IS NOW REDUNDANT, REMOVE/COMMENT OUT ---+ /*+ try {+ const token = window.auth.getToken(); // Ensure token is retrieved here+ if (!token) throw new Error("No auth token found"); // Added error handling++ const prefsResponse = await fetch('/api/auth/preferences', {+ headers: {+ 'Authorization': `Bearer ${token}`+ }+ });++ if (prefsResponse.ok) {+ const prefsData = await prefsResponse.json();+ console.log("Preferences fetched in loadWarranties:", prefsData);++ // Update expiringSoonDays+ if (prefsData && typeof prefsData.expiring_soon_days !== 'undefined') {+ const oldValue = expiringSoonDays;+ expiringSoonDays = prefsData.expiring_soon_days;+ console.log('Updated expiring soon days from preferences:', expiringSoonDays);+ // Reprocess logic moved below warranty fetch+ }++ // --- ADDED: Update dateFormat in localStorage ---+ if (prefsData && typeof prefsData.date_format !== 'undefined') {+ const oldDateFormat = localStorage.getItem('dateFormat');+ localStorage.setItem('dateFormat', prefsData.date_format);+ console.log(`Updated dateFormat in localStorage from API: ${prefsData.date_format}`);+ // Trigger re-render if format changed and warranties already exist (though unlikely at this stage)+ if (warranties && warranties.length > 0 && oldDateFormat !== prefsData.date_format) {+ console.log('Date format changed, triggering re-render via applyFilters');+ applyFilters(); // Re-render warranties with new format+ }+ } else {+ // If API doesn't return date_format, ensure localStorage has a default+ if (!localStorage.getItem('dateFormat')) {+ localStorage.setItem('dateFormat', 'MDY');+ console.log('API did not return date_format, setting localStorage default to MDY');+ }+ }+ // --- END ADDED SECTION ---++ } else {+ // Handle failed preference fetch+ console.warn('Failed to fetch preferences:', prefsResponse.status);+ // Ensure a default date format exists if fetch fails+ if (!localStorage.getItem('dateFormat')) {+ localStorage.setItem('dateFormat', 'MDY');+ console.log('Preferences fetch failed, setting localStorage default date format to MDY');+ }+ }+ } catch (error) {+ console.error('Error loading preferences:', error);+ // Ensure a default date format exists on error+ if (!localStorage.getItem('dateFormat')) {+ localStorage.setItem('dateFormat', 'MDY');+ console.log('Error fetching preferences, setting localStorage default date format to MDY');+ }+ // Continue loading warranties even if preferences fail+ }+ */+ // --- END REDUNDANT PREFERENCE FETCH ---++ // 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;+ // If status is 'archived', use archived endpoint (support global vs personal)+ const isArchivedView = currentFilters && currentFilters.status === 'archived';+ const apiUrl = isArchivedView+ ? (shouldUseGlobalView ? `${baseUrl}/api/warranties/global/archived` : `${baseUrl}/api/warranties/archived`)+ : (shouldUseGlobalView ? `${baseUrl}/api/warranties/global` : `${baseUrl}/api/warranties`);++ console.log(`[DEBUG] Using API endpoint based on saved preference '${savedScope}', archivedView=${isArchivedView}: ${apiUrl}`);++ // Check if auth is available and user is authenticated using the passed parameter+ if (!isAuthenticated) {+ console.log('[DEBUG] loadWarranties: Early return - User not authenticated based on passed parameter.');+ renderEmptyState(window.t('messages.login_to_view_warranties'));+ hideLoading();+ return;+ }+ // Get the auth token+ const token = window.auth.getToken();+ if (!token) {+ console.log('[DEBUG] Early return: No auth token available');+ renderEmptyState(window.t('messages.authentication_error_login_again'));+ hideLoading();+ return;+ }++ // Create request with auth header+ const options = {+ method: 'GET',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Content-Type': 'application/json'+ }+ };++ console.log('Fetching warranties with auth token');+ const response = await fetch(apiUrl, options);+ if (!response.ok) {+ const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));+ console.error('Error loading warranties:', response.status, errorData);+ throw new Error(`Error loading warranties: ${errorData.message || response.status}`);+ }+ const data = await response.json();+ console.log('[DEBUG] Received warranties from server:', data);+ 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}`);++ // Optionally merge archived items into the "All" view (only in personal scope)+ let combinedData = Array.isArray(data) ? data : [];+ lastLoadedIncludesArchived = false;+ if (!isArchivedView && currentFilters && currentFilters.status === 'all') {+ try {+ const archivedUrl = shouldUseGlobalView ? `${baseUrl}/api/warranties/global/archived` : `${baseUrl}/api/warranties/archived`;+ const archivedResp = await fetch(archivedUrl, options);+ if (archivedResp.ok) {+ const archivedData = await archivedResp.json();+ const archivedMarked = Array.isArray(archivedData)+ ? archivedData.map(w => ({ ...w, __isArchived: true }))+ : [];+ combinedData = combinedData.concat(archivedMarked);+ lastLoadedIncludesArchived = true;+ console.log(`[DEBUG] Merged ${archivedMarked.length} archived warranties into All view`);+ } else {+ // Log but do not block rendering of non-archived warranties+ let errInfo = '';+ try {+ const errJson = await archivedResp.json();+ errInfo = JSON.stringify(errJson);+ } catch (_) {}+ console.warn('[DEBUG] Failed to load archived warranties for All view:', archivedResp.status, errInfo);+ }+ } catch (mergeErr) {+ console.warn('[DEBUG] Error while merging archived into All:', mergeErr);+ }+ }++ // Process each warranty to calculate status and days remaining+ warranties = Array.isArray(combinedData) ? combinedData.map(warranty => processWarrantyData(warranty)) : [];+ lastLoadedArchived = isArchivedView;+ console.log('[DEBUG] Final warranties array:', warranties);+ console.log('[DEBUG] Total warranties loaded:', warranties.length);+ console.log('[DEBUG] Warranty IDs loaded:', warranties.map(w => w.id));++ // Set flag to indicate warranties have been loaded from API+ warrantiesLoaded = true;++ if (warranties.length === 0) {+ console.log('No warranties found, showing empty state');+ renderEmptyState(window.t('messages.no_warranties_found_add_first'));+ } else {+ console.log('Applying filters to display warranties');++ // Populate tag filter dropdown with tags from warranties+ populateTagFilter();+ populateVendorFilter(); // Added call to populate vendor filter+ populateWarrantyTypeFilter(); // Added call to populate warranty type filter++ // Ensure the UI reflects the freshly loaded data+ applyFilters();+ }+ } catch (error) {+ console.error('[DEBUG] Error loading warranties:', error);+ warrantiesLoaded = false; // Reset flag on error+ renderEmptyState(window.t('messages.error_loading_warranties_try_again'));+ } finally {+ hideLoading();}}@@ -2261,176 +2441,8 @@ function calculateProductAgeInDays(purchaseDate) {return diffDays;}-// Helper: map card root modifier class from status/archived-function getCardRootModifierClass(statusClass, isArchivedItem) {- if (isArchivedItem) return 'archived';- if (statusClass === 'expired') return 'expired';- if (statusClass === 'expiring') return 'expiring-soon';- return 'active';-}--// Helper: build user info HTML (Global View owner label)-function buildUserInfoHtml(warranty) {- if (isGlobalView && warranty.user_display_name) {- const ownerLabel = window.i18next ? window.i18next.t('warranties.owner') : 'Owner';- return `<div><strong>${ownerLabel}:</strong> <span>${warranty.user_display_name}</span></div>`;- }- return '';-}--// Helper: claims button state-function getClaimsButtonProps(warranty) {- let className = 'action-btn claims-link';- let title = 'Claims';- if (warranty.claim_status_summary === 'OPEN') {- className += ' claims-open';- title = 'Claims (Open)';- } else if (warranty.claim_status_summary === 'FINISHED') {- className += ' claims-finished';- title = 'Claims (Finished)';- }- return { className, title };-}--// Helper: action buttons HTML-function buildActionButtonsHtml(warranty, isArchivedView, canEdit) {- const { className: claimsButtonClass, title: claimsTitle } = getClaimsButtonProps(warranty);- if (canEdit) {- return `- <button class="${claimsButtonClass}" title="${claimsTitle}" data-id="${warranty.id}">- <i class="fas fa-clipboard-list"></i>- </button>- ${ (isArchivedView || warranty.is_archived) ? `- <button class="action-btn unarchive-btn" title="Unarchive" data-id="${warranty.id}">- <i class="fas fa-box-open"></i>- </button>- <button class="action-btn edit-btn" title="Edit (disabled in archived view)" data-id="${warranty.id}" disabled>- <i class="fas fa-edit"></i>- </button>- ` : `- <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">- <i class="fas fa-edit"></i>- </button>- <button class="action-btn archive-btn" title="Archive" data-id="${warranty.id}">- <i class="fas fa-archive"></i>- </button>- `}- <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">- <i class="fas fa-trash"></i>- </button>- `;- }- return `- <button class="${claimsButtonClass}" title="${claimsTitle}" data-id="${warranty.id}">- <i class="fas fa-clipboard-list"></i>- </button>- <span class="action-btn-placeholder" title="View only - not your warranty">- <i class="fas fa-eye" style="color: #666;"></i>- </span>- `;-}--// Helper: build photo thumbnail HTML by view-function buildPhotoThumbnailHtml(warranty) {- if (!(warranty.product_photo_path && warranty.product_photo_path !== 'null')) return '';- if (currentView === 'table') {- return `- <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="object-fit: cover; border-radius: 4px; border: 1px solid var(--border-color); cursor: pointer;"- onerror="this.style.display='none'" class="secure-image">- </a>- </div>- `;- }- if (currentView === 'list') {- return `- <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="object-fit: cover; border-radius: 6px; border: 2px solid var(--border-color); cursor: pointer;"- onerror="this.style.display='none'" class="secure-image">- </a>- </div>- `;- }- // grid- return `- <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="object-fit: cover; border-radius: 8px; border: 2px solid var(--border-color); cursor: pointer;"- onerror="this.style.display='none'" class="secure-image">- </a>- </div>- `;-}--// Helper: build warranty info block HTML (inside .warranty-info)-function buildWarrantyInfoHtml(params) {- const {- warranty,- userInfoHtml,- productAge,- warrantyDurationText,- expirationDateText,- validSerialNumbers- } = params;- return `- ${userInfoHtml}- <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>- <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>- <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>- ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}- ${validSerialNumbers.length > 0 ? `- <div><i class="fas fa-barcode"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>- ${validSerialNumbers.length > 1 ? `- <div style="margin-left: 28px;">- <ul style="margin-top: 5px;">- ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}- </ul>- </div>- ` : ''}- ` : ''}- ${warranty.model_number ? `<div><i class="fas fa-tag"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}- ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}- ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}- `;-}--// Helper: build notes link html (included in document links row if has notes)-function buildNotesLinkHtml(warranty) {- const hasNotes = warranty.notes && warranty.notes.trim() !== '';- if (!hasNotes) return '';- const notesLabel = window.i18next ? window.i18next.t('warranties.notes') : 'Notes';- return `<a href="#" class="notes-link" data-id="${warranty.id}" title="View Notes"><i class='fas fa-sticky-note'></i> ${notesLabel}</a>`;-}--// Helper: build full document links row HTML (wrapper + inner)-function buildDocumentLinksRowHtml(warranty, notesLinkHtml) {- const productLinkHtml = warranty.product_url ? `- <a href="${warranty.product_url}" class="product-link" target="_blank">- <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}- </a>` : '';- const inner = `- ${productLinkHtml}- ${generateDocumentLink(warranty, 'invoice')}- ${generateDocumentLink(warranty, 'manual')}- ${generateDocumentLink(warranty, 'other')}- ${notesLinkHtml}- `;- return `- <div class="document-links-row">- <div class="document-links-inner-container">- ${inner}- </div>- </div>- `;-}--async function renderWarranties() {- console.log('renderWarranties called');+async function renderWarranties(warrantiesToRender) {+ console.log('renderWarranties called with:', warrantiesToRender);// Guard clause: If the main warrantiesList element doesn't exist on the current page, exit.// This can happen if saveWarranty -> applyFilters -> renderWarranties is called from a page@@ -2440,74 +2452,21 @@ async function renderWarranties() {return;}- const __filters = (window.store && window.store.getFilters && window.store.getFilters()) || {};- const isArchivedView = __filters && __filters.status === 'archived';-- // Pull data from store and filter by current filters (mirror applyFilters logic)- const __all = ((window.store && window.store.getWarranties && window.store.getWarranties()) || []);- const warrantiesToRender = __all.filter(warranty => {- // Exclude archived items from specific status views (only show in 'all' or 'archived')- if (warranty.is_archived && __filters.status !== 'all' && __filters.status !== 'archived') {- return false;- }- // Status filter: allow archived items to pass in All view- if (__filters.status !== 'all' && __filters.status !== 'archived' && warranty.status !== __filters.status) {- return false;- }- // Tag filter- if (__filters.tag !== 'all') {- const tagId = parseInt(__filters.tag);- const hasTag = warranty.tags && Array.isArray(warranty.tags) &&- warranty.tags.some(tag => tag.id === tagId);- if (!hasTag) {- return false;- }- }- // Vendor filter- if (__filters.vendor !== 'all' && (warranty.vendor || '').toLowerCase() !== __filters.vendor.toLowerCase()) {- return false;- }- // Warranty type filter- if (__filters.warranty_type !== 'all' && (warranty.warranty_type || '').toLowerCase() !== __filters.warranty_type.toLowerCase()) {- return false;- }- // Search filter- if (__filters.search) {- const searchTerm = __filters.search.toLowerCase();- const productNameMatch = (warranty.product_name || '').toLowerCase().includes(searchTerm);- const tagMatch = warranty.tags && Array.isArray(warranty.tags) &&- warranty.tags.some(tag => (tag.name || '').toLowerCase().includes(searchTerm));- const notesMatch = (warranty.notes || '').toLowerCase().includes(searchTerm);- const vendorMatch = (warranty.vendor || '').toLowerCase().includes(searchTerm);- const modelNumberMatch = (warranty.model_number || '').toLowerCase().includes(searchTerm);- const serialNumberMatch = warranty.serial_numbers && Array.isArray(warranty.serial_numbers) &&- warranty.serial_numbers.some(sn => sn && String(sn).toLowerCase().includes(searchTerm));- if (!productNameMatch && !tagMatch && !notesMatch && !vendorMatch && !modelNumberMatch && !serialNumberMatch) {- return false;- }- }- return true;- });+ const isArchivedView = currentFilters && currentFilters.status === 'archived';if (!warrantiesToRender || warrantiesToRender.length === 0) {- if (window.components && window.components.ui && window.components.ui.renderEmptyState) {- window.components.ui.renderEmptyState(warrantiesList, isArchivedView ? (window.t ? window.t('messages.no_archived_warranties') : 'No archived warranties.') : undefined);- } else {- // Fallback to legacy if component not present- renderEmptyState(isArchivedView ? (window.t ? window.t('messages.no_archived_warranties') : 'No archived warranties.') : undefined);- }+ renderEmptyState(isArchivedView ? (window.t ? window.t('messages.no_archived_warranties') : 'No archived warranties.') : undefined); // renderEmptyState should also check for warrantiesList or its specific containerreturn;}const today = new Date();const globalSymbol = getCurrencySymbol(); // Get the global symbol as fallback- // Efficiently clear container- warrantiesList.textContent = '';+ warrantiesList.innerHTML = '';// Apply sorting based on current sort selectionconst sortedWarranties = [...warrantiesToRender].sort((a, b) => {- switch (__filters.sortBy) {+ switch (currentFilters.sortBy) {case 'name':return (a.product_name || '').toLowerCase().localeCompare((b.product_name || '').toLowerCase());case 'purchase':@@ -2551,9 +2510,6 @@ async function renderWarranties() {tableViewBtn.classList.toggle('active', currentView === 'table');}- // Use DocumentFragment to batch DOM insertions- const fragment = document.createDocumentFragment();-sortedWarranties.forEach(warranty => {// --- Use processed data ---const purchaseDate = warranty.purchaseDate;@@ -2623,19 +2579,38 @@ async function renderWarranties() {// Calculate product ageconst productAge = calculateProductAge(warranty.purchase_date);-+// Make sure serial numbers array exists and is validconst validSerialNumbers = Array.isArray(warranty.serial_numbers)? warranty.serial_numbers.filter(sn => sn && typeof sn === 'string' && sn.trim() !== ''): [];-- // Build user info HTML- const userInfoHtml = buildUserInfoHtml(warranty);-- // Notes link- const notesLinkHtml = buildNotesLinkHtml(warranty);-- // Has documents?+ // Prepare user info HTML for global view+ let userInfoHtml = '';+ if (isGlobalView && warranty.user_display_name) {+ const ownerLabel = window.i18next ? window.i18next.t('warranties.owner') : 'Owner';+ userInfoHtml = `<div><strong>${ownerLabel}:</strong> <span>${warranty.user_display_name}</span></div>`;+ }++ // Prepare tags HTML+ const tagsHtml = warranty.tags && warranty.tags.length > 0+ ? `<div class="tags-row">+ ${warranty.tags.map(tag =>+ `<span class="tag" style="background-color: ${tag.color}; color: ${getContrastColor(tag.color)}">+ ${tag.name}+ </span>`+ ).join('')}+ </div>`+ : '';+ // Add notes display button if present+ let notesHtml = '';+ const hasNotes = warranty.notes && warranty.notes.trim() !== '';+ // Remove the button, and instead prepare a notes link for document-links-row+ let notesLinkHtml = '';+ if (hasNotes) {+ const notesLabel = window.i18next ? window.i18next.t('warranties.notes') : 'Notes';+ notesLinkHtml = `<a href="#" class="notes-link" data-id="${warranty.id}" title="View Notes"><i class='fas fa-sticky-note'></i> ${notesLabel}</a>`;+ }+const hasDocuments = Boolean(warranty.product_url ||warranty.invoice_path || warranty.invoice_url ||@@ -2643,9 +2618,10 @@ async function renderWarranties() {warranty.other_document_path || warranty.other_document_url ||warranty.paperless_invoice_id || warranty.paperless_manual_id ||warranty.paperless_photo_id || warranty.paperless_other_id ||- notesLinkHtml+ hasNotes);-++// Get current user ID to check warranty ownershipconst currentUserId = (() => {try {@@ -2660,103 +2636,307 @@ async function renderWarranties() {// Allow if: not in global view, user owns the warranty, or user is adminconst isAdmin = getUserType() === 'admin';const canEdit = !isGlobalView || (warranty.user_id === currentUserId) || isAdmin;++ // Determine claims button class and title based on claim status+ let claimsButtonClass = 'action-btn claims-link';+ let claimsTitle = 'Claims';++ if (warranty.claim_status_summary === 'OPEN') {+ claimsButtonClass += ' claims-open';+ claimsTitle = 'Claims (Open)';+ } else if (warranty.claim_status_summary === 'FINISHED') {+ claimsButtonClass += ' claims-finished';+ claimsTitle = 'Claims (Finished)';+ }- // Build actions/content/status for the component- const actionButtonsHtml = buildActionButtonsHtml(warranty, isArchivedView, canEdit);- const contentHtml = buildWarrantyInfoHtml({- warranty,- userInfoHtml,- productAge,- warrantyDurationText,- expirationDateText,- validSerialNumbers- });+ // Generate action buttons HTML based on permissions+ const actionButtonsHtml = canEdit ? `+ <button class="${claimsButtonClass}" title="${claimsTitle}" data-id="${warranty.id}">+ <i class="fas fa-clipboard-list"></i>+ </button>+ ${ (isArchivedView || warranty.is_archived) ? `+ <button class="action-btn unarchive-btn" title="Unarchive" data-id="${warranty.id}">+ <i class="fas fa-box-open"></i>+ </button>+ <button class="action-btn edit-btn" title="Edit (disabled in archived view)" data-id="${warranty.id}" disabled>+ <i class="fas fa-edit"></i>+ </button>+ ` : `+ <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">+ <i class="fas fa-edit"></i>+ </button>+ <button class="action-btn archive-btn" title="Archive" data-id="${warranty.id}">+ <i class="fas fa-archive"></i>+ </button>+ `}+ <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">+ <i class="fas fa-trash"></i>+ </button>+ ` : `+ <button class="${claimsButtonClass}" title="${claimsTitle}" data-id="${warranty.id}">+ <i class="fas fa-clipboard-list"></i>+ </button>+ <span class="action-btn-placeholder" title="View only - not your warranty">+ <i class="fas fa-eye" style="color: #666;"></i>+ </span>+ `;++ const cardElement = document.createElement('div');const isArchivedItem = isArchivedView || warranty.is_archived;- const rootModifierClass = getCardRootModifierClass(statusClass, isArchivedItem);-- const cardElement = (window.components && window.components.createWarrantyCard)- ? window.components.createWarrantyCard(warranty, {- actionsHtml: actionButtonsHtml,- contentHtml: contentHtml,- statusText: statusText,- statusClass: statusClass,- rootModifierClass: rootModifierClass- })- : (() => {- // Fallback: minimal element if component missing- const fallback = document.createElement('div');- fallback.className = `warranty-card ${rootModifierClass}`;- fallback.innerHTML = `<div class="product-name-header"><h3 class="warranty-title">${warranty.product_name || 'Unnamed Product'}</h3></div>`;- return fallback;- })();-- // Insert photo thumbnail (before .warranty-info inside .warranty-content)- const photoThumbnailHtml = buildPhotoThumbnailHtml(warranty);- if (photoThumbnailHtml) {- const contentWrap = cardElement.querySelector('.warranty-content');- const infoEl = cardElement.querySelector('.warranty-info');- if (contentWrap && infoEl) {- const photoHolder = document.createElement('div');- photoHolder.innerHTML = photoThumbnailHtml;- contentWrap.insertBefore(photoHolder.firstElementChild, infoEl);- }- }-- // Insert document links row (around status row according to view)- if (hasDocuments) {- const docRowHtml = buildDocumentLinksRowHtml(warranty, notesLinkHtml);- const statusRow = cardElement.querySelector('.warranty-status-row');- if (statusRow) {- if (currentView === 'table') {- statusRow.insertAdjacentHTML('afterend', docRowHtml);- } else {- statusRow.insertAdjacentHTML('beforebegin', docRowHtml);- }- } else {- // Fallback append- cardElement.insertAdjacentHTML('beforeend', docRowHtml);- }+ cardElement.className = `warranty-card ${isArchivedItem ? 'archived' : (statusClass === 'expired' ? 'expired' : statusClass === 'expiring' ? 'expiring-soon' : 'active')}`;++ // Claims button styling will be handled in the action buttons HTML generation++ if (currentView === 'grid') {+ // Grid view HTML structure+ const photoThumbnailHtml = warranty.product_photo_path && warranty.product_photo_path !== 'null' ? `+ <div class="product-photo-thumbnail">+ <a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">+ <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"+ style="width: 80px; height: 80px; object-fit: cover; border-radius: 8px; border: 2px solid var(--border-color); cursor: pointer;"+ onerror="this.style.display='none'" class="secure-image">+ </a>+ </div>+ ` : '';++ cardElement.innerHTML = `+ <div class="product-name-header">+ <h3 class="warranty-title" title="${warranty.product_name || 'Unnamed Product'}">${warranty.product_name || 'Unnamed Product'}</h3>+ <div class="warranty-actions">+ ${actionButtonsHtml}+ </div>+ </div>+ <div class="warranty-content">+ ${photoThumbnailHtml}+ <div class="warranty-info">+ ${userInfoHtml}+ <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>+ <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>+ <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>+ ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}+ ${validSerialNumbers.length > 0 ? `+ <div><i class="fas fa-barcode"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>+ ${validSerialNumbers.length > 1 ? `+ <div style="margin-left: 28px;">+ <ul style="margin-top: 5px;">+ ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}+ </ul>+ </div>+ ` : ''}+ ` : ''}+ ${warranty.model_number ? `<div><i class="fas fa-tag"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}+ ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}+ ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}+ </div>+ </div>+ ${hasDocuments ? `+ <div class="document-links-row">+ <div class="document-links-inner-container">+ ${warranty.product_url ? `+ <a href="${warranty.product_url}" class="product-link" target="_blank">+ <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}+ </a>+ ` : ''}+ ${generateDocumentLink(warranty, 'invoice')}+ ${generateDocumentLink(warranty, 'manual')}+ ${generateDocumentLink(warranty, 'other')}+ ${notesLinkHtml}++ </div>+ </div>+ ` : ''}+ ${tagsHtml}+ <div class="warranty-status-row status-${statusClass}">+ <span>${statusText}</span>+ </div>+ `;+ } else if (currentView === 'list') {+ // List view HTML structure+ const photoThumbnailHtml = warranty.product_photo_path && warranty.product_photo_path !== 'null' ? `+ <div class="product-photo-thumbnail">+ <a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">+ <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"+ style="width: 180px; height: 180px; object-fit: cover; border-radius: 6px; border: 2px solid var(--border-color); cursor: pointer;"+ onerror="this.style.display='none'" class="secure-image">+ </a>+ </div>+ ` : '';++ cardElement.innerHTML = `+ <div class="product-name-header">+ <h3 class="warranty-title" title="${warranty.product_name || 'Unnamed Product'}">${warranty.product_name || 'Unnamed Product'}</h3>+ <div class="warranty-actions">+ ${actionButtonsHtml}+ </div>+ </div>+ <div class="warranty-content">+ ${photoThumbnailHtml}+ <div class="warranty-info">+ ${userInfoHtml}+ <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>+ <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>+ <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>+ ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}+ ${validSerialNumbers.length > 0 ? `+ <div><i class="fas fa-barcode"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>+ ${validSerialNumbers.length > 1 ? `+ <div style="margin-left: 28px;">+ <ul style="margin-top: 5px;">+ ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}+ </ul>+ </div>+ ` : ''}+ ` : ''}+ ${warranty.model_number ? `<div><i class=\"fas fa-tag\"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}+ ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}+ ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}+ </div>+ </div>+ ${hasDocuments ? `+ <div class="document-links-row">+ <div class="document-links-inner-container">+ ${warranty.product_url ? `+ <a href="${warranty.product_url}" class="product-link" target="_blank">+ <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}+ </a>+ ` : ''}+ ${generateDocumentLink(warranty, 'invoice')}+ ${generateDocumentLink(warranty, 'manual')}+ ${generateDocumentLink(warranty, 'other')}+ ${notesLinkHtml}++ </div>+ </div>+ ` : ''}+ ${tagsHtml}+ <div class="warranty-status-row status-${statusClass}">+ <span>${statusText}</span>+ </div>+ `;+ } else if (currentView === 'table') {+ // Table view HTML structure+ const photoThumbnailHtml = warranty.product_photo_path && warranty.product_photo_path !== 'null' ? `+ <div class="product-photo-thumbnail">+ <a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">+ <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"+ style="width: 55px; height: 55px; object-fit: cover; border-radius: 4px; border: 1px solid var(--border-color); cursor: pointer;"+ onerror="this.style.display='none'" class="secure-image">+ </a>+ </div>+ ` : '';++ cardElement.innerHTML = `+ <div class="product-name-header">+ <h3 class="warranty-title" title="${warranty.product_name || 'Unnamed Product'}">${warranty.product_name || 'Unnamed Product'}</h3>+ <div class="warranty-actions">+ ${actionButtonsHtml}+ </div>+ </div>+ <div class="warranty-content">+ ${photoThumbnailHtml}+ <div class="warranty-info">+ ${userInfoHtml}+ <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>+ <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>+ <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>+ ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}+ ${validSerialNumbers.length > 0 ? `+ <div><i class="fas fa-barcode"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>+ ${validSerialNumbers.length > 1 ? `+ <div style="margin-left: 28px;">+ <ul style="margin-top: 5px;">+ ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}+ </ul>+ </div>+ ` : ''}+ ` : ''}+ ${warranty.model_number ? `<div><i class=\"fas fa-tag\"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}+ ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}+ ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}+ </div>+ </div>+ <div class="warranty-status-row status-${statusClass}">+ <span>${statusText}</span>+ </div>+ ${hasDocuments ? `+ <div class="document-links-row">+ <div class="document-links-inner-container">+ ${warranty.product_url ? `+ <a href="${warranty.product_url}" class="product-link" target="_blank">+ <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}+ </a>+ ` : ''}+ ${generateDocumentLink(warranty, 'invoice')}+ ${generateDocumentLink(warranty, 'manual')}+ ${generateDocumentLink(warranty, 'other')}+ ${notesLinkHtml}++ </div>+ </div>+ ` : ''}+ ${tagsHtml}+ `;}++ // Add event listeners+ warrantiesList.appendChild(cardElement);++ // Add event listeners only if user can edit (buttons exist)+ if (canEdit) {+ // Edit button event listener+ const editBtn = cardElement.querySelector('.edit-btn');+ if (editBtn && !editBtn.disabled) {+ editBtn.addEventListener('click', async () => {+ console.log('[DEBUG] Edit button clicked for warranty ID:', warranty.id);+ // Find the current warranty data instead of using the potentially stale warranty object+ const currentWarranty = warranties.find(w => w.id === warranty.id);+ console.log('[DEBUG] Found current warranty:', currentWarranty ? 'Yes' : 'No', currentWarranty?.notes);+ if (currentWarranty) {+ await openEditModal(currentWarranty);+ } else {+ showToast(window.t('messages.warranty_not_found_refresh'), 'error');+ }+ });+ }++ // Delete button event listener+ const deleteBtn = cardElement.querySelector('.delete-btn');+ if (deleteBtn) {+ deleteBtn.addEventListener('click', () => {+ openDeleteModal(warranty.id, warranty.product_name);+ });+ }- // Append tags using component util if available, otherwise build manually- if (Array.isArray(warranty.tags) && warranty.tags.length > 0) {- if (window.components && window.components.appendTags) {- window.components.appendTags(cardElement, warranty.tags);- } else {- const tagsRow = document.createElement('div');- tagsRow.className = 'tags-row';- warranty.tags.forEach(tag => {- const tagEl = (window.components && window.components.createTag)- ? window.components.createTag(tag?.name, tag?.color)- : (() => {- const el = document.createElement('span');- el.className = 'tag';- if (tag?.color) {- el.style.backgroundColor = tag.color;- try {- const contrast = (window.getContrastColor ? window.getContrastColor(tag.color) : null);- if (contrast) el.style.color = contrast;- } catch (e) {}- }- el.textContent = tag?.name || '';- return el;- })();- tagsRow.appendChild(tagEl);+ // Archive/Unarchive button event listeners+ const archiveBtn = cardElement.querySelector('.archive-btn');+ if (archiveBtn) {+ archiveBtn.addEventListener('click', () => {+ openArchiveModal(warranty.id, warranty.product_name);+ });+ }+ const unarchiveBtn = cardElement.querySelector('.unarchive-btn');+ if (unarchiveBtn) {+ unarchiveBtn.addEventListener('click', async () => {+ await toggleArchiveStatus(warranty.id, false);});- const docRow = cardElement.querySelector('.document-links-row');- if (docRow) {- docRow.insertAdjacentElement('afterend', tagsRow);- } else {- cardElement.appendChild(tagsRow);- }}}-- fragment.appendChild(cardElement);+ // View notes button event listener+ const notesLink = cardElement.querySelector('.notes-link');+ if (notesLink) {+ notesLink.addEventListener('click', (e) => {+ e.preventDefault();+ // Find the current warranty data instead of using the potentially stale warranty object+ const currentWarranty = warranties.find(w => w.id === warranty.id);+ if (currentWarranty) {+ showNotesModal(currentWarranty.notes, currentWarranty);+ } else {+ showToast(window.t('messages.warranty_not_found_refresh'), 'error');+ }+ });+ }});- warrantiesList.appendChild(fragment);-// Load secure images with authentication after renderingloadSecureImages();@@ -2819,12 +2999,12 @@ function filterWarranties() {}if (!searchTerm) {- return ((window.store && window.store.getWarranties && window.store.getWarranties()) || []); // Return the full list if no search term+ return warranties; // Return the full list if no search term// REMOVED: renderWarranties();// REMOVED: return;}- const filtered = (((window.store && window.store.getWarranties && window.store.getWarranties()) || [])).filter(warranty => {+ const filtered = warranties.filter(warranty => {// Check product nameif (warranty.product_name && warranty.product_name.toLowerCase().includes(searchTerm)) { // Add null checkreturn true;@@ -2873,23 +3053,100 @@ function filterWarranties() {}function applyFilters() {- if (window.warrantyListController && typeof window.warrantyListController.applyFilters === 'function') {- return window.warrantyListController.applyFilters();+ console.log('[FILTER DEBUG] Applying filters with:', currentFilters);+ console.log('[FILTER DEBUG] Total warranties before filtering:', warranties.length);++ // If user selected archived status, reload data from archived endpoint and return+ if (currentFilters.status === 'archived') {+ if (!lastLoadedArchived) {+ loadWarranties(true);+ return;+ }+ } else if (lastLoadedArchived) {+ // If leaving archived view, reload normal source+ loadWarranties(true);+ return;+ } else if (currentFilters.status === 'all' && !lastLoadedIncludesArchived) {+ // Ensure All view re-merges archived items after switching away and back+ loadWarranties(true);+ return;}++ // Filter warranties based on currentFilters+ const filtered = warranties.filter(warranty => {+ // Exclude archived items from specific status views (only show in 'all' or 'archived')+ if (warranty.is_archived && currentFilters.status !== 'all' && currentFilters.status !== 'archived') {+ return false;+ }+ // Status filter: allow archived items to pass in All view+ if (currentFilters.status !== 'all' && currentFilters.status !== 'archived' && warranty.status !== currentFilters.status) {+ return false;+ }++ // Tag filter+ if (currentFilters.tag !== 'all') {+ const tagId = parseInt(currentFilters.tag);+ const hasTag = warranty.tags && Array.isArray(warranty.tags) &&+ warranty.tags.some(tag => tag.id === tagId);+ if (!hasTag) {+ return false;+ }+ }++ // Vendor filter+ if (currentFilters.vendor !== 'all' && (warranty.vendor || '').toLowerCase() !== currentFilters.vendor.toLowerCase()) {+ return false;+ }++ // Warranty type filter+ if (currentFilters.warranty_type !== 'all' && (warranty.warranty_type || '').toLowerCase() !== currentFilters.warranty_type.toLowerCase()) {+ return false;+ }++ // Search filter+ if (currentFilters.search) {+ const searchTerm = currentFilters.search.toLowerCase();+ // Check if product name contains search term+ const productNameMatch = warranty.product_name.toLowerCase().includes(searchTerm);+ // Check if any tag name contains search term+ const tagMatch = warranty.tags && Array.isArray(warranty.tags) &&+ warranty.tags.some(tag => tag.name.toLowerCase().includes(searchTerm));+ // Check if notes contains search term+ const notesMatch = warranty.notes && warranty.notes.toLowerCase().includes(searchTerm);+ // Check if vendor contains search term+ const vendorMatch = warranty.vendor && warranty.vendor.toLowerCase().includes(searchTerm);+ // Check if model number contains search term+ const modelNumberMatch = warranty.model_number && warranty.model_number.toLowerCase().includes(searchTerm);+ // Check if any serial number contains search term+ const serialNumberMatch = warranty.serial_numbers && Array.isArray(warranty.serial_numbers) &&+ warranty.serial_numbers.some(sn => sn && sn.toLowerCase().includes(searchTerm));+ // Return true if any match+ if (!productNameMatch && !tagMatch && !notesMatch && !vendorMatch && !modelNumberMatch && !serialNumberMatch) {+ return false;+ }+ }++ return true;+ });++ 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);}// --- Persist and restore filters/sort ---async function saveFilterPreferences(saveToApi = true) {try {const prefix = getPreferenceKeyPrefix();- const __filters = (window.store && window.store.getFilters && window.store.getFilters()) || {};const filtersToSave = {- status: __filters.status || 'all',- tag: __filters.tag || 'all',- vendor: __filters.vendor || 'all',- warranty_type: __filters.warranty_type || 'all',- search: __filters.search || '',- sortBy: __filters.sortBy || 'expiration'+ status: currentFilters.status || 'all',+ tag: currentFilters.tag || 'all',+ vendor: currentFilters.vendor || 'all',+ warranty_type: currentFilters.warranty_type || 'all',+ search: currentFilters.search || '',+ sortBy: currentFilters.sortBy || 'expiration'};localStorage.setItem(`${prefix}warrantyFilters`, JSON.stringify(filtersToSave));@@ -2933,15 +3190,12 @@ function loadFilterAndSortPreferences() {const savedFilters = JSON.parse(savedFiltersRaw);if (savedFilters && typeof savedFilters === 'object') {console.log('[Filters] Loading saved filters from localStorage:', savedFilters);- const __existing = (window.store && window.store.getFilters && window.store.getFilters()) || {};- if (window.store && window.store.updateFilter) {- if (savedFilters.status !== undefined) window.store.updateFilter('status', savedFilters.status || __existing.status);- if (savedFilters.tag !== undefined) window.store.updateFilter('tag', savedFilters.tag || __existing.tag);- if (savedFilters.vendor !== undefined) window.store.updateFilter('vendor', savedFilters.vendor || __existing.vendor);- if (savedFilters.warranty_type !== undefined) window.store.updateFilter('warranty_type', savedFilters.warranty_type || __existing.warranty_type);- if (savedFilters.search !== undefined) window.store.updateFilter('search', savedFilters.search || '');- if (savedFilters.sortBy !== undefined) window.store.updateFilter('sortBy', savedFilters.sortBy || __existing.sortBy);- }+ currentFilters.status = savedFilters.status || currentFilters.status;+ currentFilters.tag = savedFilters.tag || currentFilters.tag;+ currentFilters.vendor = savedFilters.vendor || currentFilters.vendor;+ currentFilters.warranty_type = savedFilters.warranty_type || currentFilters.warranty_type;+ currentFilters.search = savedFilters.search || '';+ currentFilters.sortBy = savedFilters.sortBy || currentFilters.sortBy;// Restore search input UI stateconst searchInput = document.getElementById('searchWarranties');@@ -2967,7 +3221,6 @@ async function openEditModal(warranty) {closeModals();currentWarrantyId = warranty.id;- window.currentWarrantyId = warranty.id; // Also set on window for editModal.js module// Load currencies for the dropdown and wait for it to completeawait loadCurrencies();@@ -3522,27 +3775,29 @@ async function openEditModal(warranty) {function openDeleteModal(warrantyId, productName) {currentWarrantyId = warrantyId;- if (window.components && window.components.modals && typeof window.components.modals.openDeleteModal === 'function') {- window.components.modals.openDeleteModal(productName);- return;- }+const deleteProductNameElement = document.getElementById('deleteProductName');- if (deleteProductNameElement) deleteProductNameElement.textContent = productName || '';+ if (deleteProductNameElement) {+ deleteProductNameElement.textContent = productName || '';+ }+const deleteModal = document.getElementById('deleteModal');- if (deleteModal) deleteModal.classList.add('active');+ if (deleteModal) {+ deleteModal.classList.add('active');+ }}// Open Archive confirmation modalfunction openArchiveModal(warrantyId, productName) {currentWarrantyId = warrantyId;- if (window.components && window.components.modals && typeof window.components.modals.openArchiveModal === 'function') {- window.components.modals.openArchiveModal(productName);- return;- }const archiveProductNameElement = document.getElementById('archiveProductName');- if (archiveProductNameElement) archiveProductNameElement.textContent = productName || '';+ if (archiveProductNameElement) {+ archiveProductNameElement.textContent = productName || '';+ }const archiveModal = document.getElementById('archiveModal');- if (archiveModal) archiveModal.classList.add('active');+ if (archiveModal) {+ archiveModal.classList.add('active');+ }}// Confirm archive handler@@ -3558,7 +3813,6 @@ async function confirmArchive() {const guidance = 'You can find archived warranties by selecting "Archived" in Filters.';showToast(guidance, 'info');currentWarrantyId = null;- window.currentWarrantyId = null; // Also clear window property} catch (e) {// toggleArchiveStatus already toasts on failureconsole.error('Archive failed', e);@@ -3915,9 +4169,7 @@ document.addEventListener('DOMContentLoaded', function() {initializeTheme();// Set up event listeners for other UI controls (should contain checks)- if (window.warrantyListController && typeof window.warrantyListController.initEventListeners === 'function') {- window.warrantyListController.initEventListeners();- }+ setupUIEventListeners();setupModalTriggers(); // Add the new modal listeners// Check if user is logged in and update UI@@ -3981,7 +4233,35 @@ let currentClaimsCanEdit = false; // Track if current user can edit the warranty* Initialize claims event listeners*/function initClaimsEventListeners() {- // Card action delegation is now handled by warrantyListController.initEventListeners()+ // Event delegation for claims links+ if (warrantiesList) {+ warrantiesList.addEventListener('click', (e) => {+ if (e.target.closest('.claims-link')) {+ e.preventDefault();+ const warrantyId = parseInt(e.target.closest('.claims-link').dataset.id);+ openClaimsModal(warrantyId);+ return;+ }+ // Archive button+ if (e.target.closest('.archive-btn')) {+ e.preventDefault();+ const el = e.target.closest('.archive-btn');+ const warrantyId = parseInt(el.dataset.id);+ const card = el.closest('.warranty-card');+ const titleEl = card ? card.querySelector('.product-name-header .warranty-title') : null;+ const productName = titleEl ? titleEl.textContent.trim() : '';+ openArchiveModal(warrantyId, productName);+ return;+ }+ // Unarchive button+ if (e.target.closest('.unarchive-btn')) {+ e.preventDefault();+ const warrantyId = parseInt(e.target.closest('.unarchive-btn').dataset.id);+ toggleArchiveStatus(warrantyId, false);+ return;+ }+ });+ }// Add claim buttonif (addClaimBtn) {@@ -4025,7 +4305,7 @@ async function openClaimsModal(warrantyId) {currentClaimsWarrantyId = warrantyId;// Find warranty info- const warranty = (((window.store && window.store.getWarranties && window.store.getWarranties()) || []).find(w => w.id === warrantyId));+ const warranty = warranties.find(w => w.id === warrantyId);if (!warranty) {showToast(window.i18next ? window.i18next.t('claims.warranty_not_found') : 'Warranty not found', 'error');return;@@ -4714,13 +4994,12 @@ function initTagFunctionality() {console.log('Initializing main form tag UI functionality (search, selection, manage button).');// Load allTags if not already loaded (needed for search suggestions in the main form)- const __tagsInit = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];- if (__tagsInit.length === 0) {+ if (allTags.length === 0) {loadTags(); // loadTags is async}mainFormTagSearch.addEventListener('focus', () => {- renderTagsList(); // Renders suggestions into mainFormTagsList based on store tags+ renderTagsList(); // Renders suggestions into mainFormTagsList based on allTagsmainFormTagsList.classList.add('show');});@@ -4753,11 +5032,10 @@ async function loadTags(force = false) {console.log('[script.js] loadTags() called. Current page:', window.location.pathname);// Check if tags are already loaded and reasonably populated- const __existingTags = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];- if (!force && __existingTags && __existingTags.length > 0) {- console.log('[script.js] Tags already loaded in store. Skipping fetch. Count:', __existingTags.length);+ if (!force && allTags && allTags.length > 0) {+ console.log('[script.js] Tags already loaded in allTags global. Skipping fetch. Count:', allTags.length);// Optionally, re-dispatch the event if other components might need it on subsequent (though now less likely) calls- // document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: __existingTags }));+ // document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: allTags }));return;}@@ -4765,7 +5043,7 @@ async function loadTags(force = false) {const token = auth.getToken();if (!token) {console.warn('[script.js] No token available for loadTags. User might not be authenticated yet.');- if (window.store && window.store.setAllTags) window.store.setAllTags([]); // Ensure tags are empty if we can't load+ allTags = []; // Ensure allTags is empty if we can't loadreturn;}const response = await fetch('/api/tags', {@@ -4774,20 +5052,19 @@ async function loadTags(force = false) {if (!response.ok) {const errorText = await response.text();console.error('[script.js] Failed to load tags:', response.status, errorText);- if (window.store && window.store.setAllTags) window.store.setAllTags([]); // Default to empty on error+ allTags = []; // Default to empty on errorreturn;}const fetchedTags = await response.json();// Assuming fetchedTags is an array of {id, name, color, ...} as expected by other functions- if (window.store && window.store.setAllTags) window.store.setAllTags(fetchedTags);- const __tagsAfterSet = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];- console.log('[script.js] All tags loaded into store:', __tagsAfterSet.length, 'tags. Sample:', __tagsAfterSet.slice(0,2));+ allTags = fetchedTags;+ console.log('[script.js] All tags loaded into global allTags variable:', allTags.length, 'tags. Sample:', allTags.slice(0,2));// Dispatch event for any components that might be waiting for tags (e.g., Tagify instances)- document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: __tagsAfterSet }));+ document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: allTags }));} catch (error) {console.error('[script.js] Error in loadTags():', error);- if (window.store && window.store.setAllTags) window.store.setAllTags([]); // Default to empty on critical error+ allTags = []; // Default to empty on critical error}}@@ -4798,8 +5075,7 @@ function renderTagsList(searchTerm = '') {tagsList.innerHTML = '';// Filter tags based on search term- const __allTagsForRender = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];- const filteredTags = __allTagsForRender.filter(tag =>+ const filteredTags = allTags.filter(tag =>!searchTerm || tag.name.toLowerCase().includes(searchTerm.toLowerCase()));@@ -4864,8 +5140,7 @@ function renderEditTagsList(searchTerm = '') {if (!editTagsList) return;editTagsList.innerHTML = '';// Filter tags based on search term- const __allTagsForEdit = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];- const filteredTags = __allTagsForEdit.filter(tag =>+ const filteredTags = allTags.filter(tag =>!searchTerm || tag.name.toLowerCase().includes(searchTerm.toLowerCase()));// Add option to create new tag if search term is provided and not in list@@ -5091,8 +5366,7 @@ function createTag(name) {name: data.name,color: data.color};- const __existing = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];- if (window.store && window.store.setAllTags) window.store.setAllTags([...__existing, newTag]);+ allTags.push(newTag);renderExistingTags();populateTagFilter();showToast(window.t('messages.tag_created_successfully'), 'success');@@ -5156,13 +5430,12 @@ function renderExistingTags() {const tbody = document.createElement('tbody');- const __storeTags = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];- if (!__storeTags || __storeTags.length === 0) {+ if (!allTags || allTags.length === 0) {const emptyRow = document.createElement('tr');emptyRow.innerHTML = `<td colspan="3"><div class="no-tags">${window.t ? window.t('messages.no_tags_created_yet') : 'No tags created yet'}</div></td>`;tbody.appendChild(emptyRow);} else {- __storeTags.forEach(tag => {+ allTags.forEach(tag => {const row = document.createElement('tr');row.className = 'existing-tag-row';row.dataset.id = String(tag.id);@@ -5261,17 +5534,18 @@ function updateTag(id, name, color) {editSelectedTags = editSelectedTags.map(t => t.id === data.id ? { id: data.id, name: data.name, color: data.color } : t);}// Update tags inside existing warranties so cards reflect changes- const __w = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];- if (Array.isArray(__w) && __w.length > 0) {- const __updated = __w.map(w => {- if (Array.isArray(w.tags)) {- const newTags = w.tags.map(tag => tag.id === data.id ? { ...tag, name: data.name, color: data.color } : tag);- return { ...w, tags: newTags };- }- return w;- });- if (window.store && window.store.setWarranties) window.store.setWarranties(__updated);- }+ if (Array.isArray(warranties) && warranties.length > 0) {+ warranties.forEach(w => {+ if (Array.isArray(w.tags)) {+ w.tags.forEach(tag => {+ if (tag.id === data.id) {+ tag.name = data.name;+ tag.color = data.color;+ }+ });+ }+ });+ }}} catch (e) {console.warn('[script.js] Non-fatal error while updating local tag state after update:', e);@@ -5281,7 +5555,7 @@ function updateTag(id, name, color) {renderSelectedTags();renderEditSelectedTags();populateTagFilter();- renderWarranties();+ renderWarranties(warranties);if (document.getElementById('summary-tags')) {updateSummary();}@@ -5414,30 +5688,25 @@ function deleteTag(id) {}).then(data => {// Remove tag from allTags array- const __tagsNow = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];- const __updatedTags = __tagsNow.filter(tag => tag.id !== id);- if (window.store && window.store.setAllTags) window.store.setAllTags(__updatedTags);+ allTags = allTags.filter(tag => tag.id !== id);// Remove tag from selectedTags if present (in both add and edit modes)selectedTags = selectedTags.filter(tag => tag.id !== id);editSelectedTags = editSelectedTags.filter(tag => tag.id !== id);// Remove tag from warranties array- const __warrantiesNow = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];- const __updatedWarranties = __warrantiesNow.map(warranty => {+ warranties.forEach(warranty => {if (warranty.tags && Array.isArray(warranty.tags)) {- return { ...warranty, tags: warranty.tags.filter(tag => tag.id !== id) };+ warranty.tags = warranty.tags.filter(tag => tag.id !== id);}- return warranty;});- if (window.store && window.store.setWarranties) window.store.setWarranties(__updatedWarranties);// --- FIX: Re-render UI elements ---renderExistingTags(); // Update the list in the modalrenderSelectedTags(); // Update selected tags in the add formrenderEditSelectedTags(); // Update selected tags in the edit formpopulateTagFilter(); // Update the filter dropdown on the main page- renderWarranties(); // Update warranty cards to remove deleted tag+ renderWarranties(warranties); // Update warranty cards to remove deleted tag// --- END FIX ---showToast(window.t('messages.tag_deleted_successfully'), 'success');@@ -5451,37 +5720,270 @@ function deleteTag(id) {});}-// Set up event listeners for UI controls (delegated to controller in index.js)--// Delegate extracted filter/persist functions to controller (backward-compatible)-function saveFilterPreferences(saveToApi = true) {- if (window.warrantyListController && typeof window.warrantyListController.saveFilterPreferences === 'function') {- return window.warrantyListController.saveFilterPreferences(saveToApi);+// Set up event listeners for UI controls+function setupUIEventListeners() {+ // --- Global Manage Tags Button ---+ const globalManageTagsBtn = document.getElementById('globalManageTagsBtn');+ if (globalManageTagsBtn) {+ globalManageTagsBtn.addEventListener('click', async () => {+ // Ensure allTags are loaded before opening the modal+ if (!allTags || allTags.length === 0) {+ showLoadingSpinner();+ try {+ await loadTags();+ } catch (error) {+ console.error("Failed to load tags before opening modal:", error);+ showToast(window.t('messages.could_not_load_tags'), "error");+ hideLoadingSpinner();+ return;+ }+ hideLoadingSpinner();+ }+ openTagManagementModal();+ });}-}+ // Initialize edit tabs+ initEditTabs();++ // Close modals when clicking outside or on close button+ document.querySelectorAll('.modal-backdrop, [data-dismiss="modal"]').forEach(element => {+ element.addEventListener('click', (e) => {+ // Check if the click is on the backdrop itself OR a dismiss button+ if (e.target === element || e.target.matches('[data-dismiss="modal"]')) {+ // Find the closest modal backdrop to the element clicked+ const modalToClose = e.target.closest('.modal-backdrop');-function loadFilterAndSortPreferences() {- if (window.warrantyListController && typeof window.warrantyListController.loadFilterAndSortPreferences === 'function') {- return window.warrantyListController.loadFilterAndSortPreferences();- }-}+ if (modalToClose) {+ // *** MODIFIED CHECK ***+ // If the click target is the backdrop itself (not a dismiss button)+ // AND the modal is one of the protected modals, then DO NOTHING.+ if ((modalToClose.id === 'addWarrantyModal' || modalToClose.id === 'editModal' ||+ modalToClose.id === 'claimsModal' || modalToClose.id === 'claimFormModal') && e.target === modalToClose) {+ return; // Ignore backdrop click for protected modals+ }+ // *** END MODIFIED CHECK ***-function populateTagFilter() {- if (window.warrantyListController && typeof window.warrantyListController.populateTagFilter === 'function') {- return window.warrantyListController.populateTagFilter();- }-}+ // Otherwise, close the modal (handles other modals' backdrop clicks and all dismiss buttons)+ modalToClose.classList.remove('active');-function populateVendorFilter() {- if (window.warrantyListController && typeof window.warrantyListController.populateVendorFilter === 'function') {- return window.warrantyListController.populateVendorFilter();+ // Reset forms only when closing the respective modal+ if (modalToClose.id === 'editModal') {+ // Optional: Add any edit form reset logic here if needed+ console.log('Edit modal closed, reset logic (if any) can go here.');+ } else if (modalToClose.id === 'addWarrantyModal') {+ // This reset will now only trigger if closed via dismiss button+ resetAddWarrantyWizard();+ }+ // Add similar reset logic for other modals like deleteModal if needed+ // else if (modalToClose.id === 'deleteModal') { ... }+ }+ }+ });+ });++ // Prevent modal content clicks from closing the modal+ document.querySelectorAll('.modal').forEach(modal => {+ modal.addEventListener('click', (e) => {+ e.stopPropagation();+ });+ });++ // Filter event listeners+ const searchInput = document.getElementById('searchWarranties');+ const clearSearchBtn = document.getElementById('clearSearch');+ const statusFilter = document.getElementById('statusFilter');+ const tagFilter = document.getElementById('tagFilter');+ const sortBySelect = document.getElementById('sortBy');+ const vendorFilter = document.getElementById('vendorFilter'); // Added vendor filter select+ const warrantyTypeFilter = document.getElementById('warrantyTypeFilter'); // Added warranty type filter select++ if (searchInput) {+ // Debounce logic: only apply filters after user stops typing for 300ms+ let searchDebounceTimeout;+ searchInput.addEventListener('input', () => {+ currentFilters.search = searchInput.value.toLowerCase();+ // Show/hide clear button based on search input+ if (clearSearchBtn) {+ clearSearchBtn.style.display = searchInput.value ? 'flex' : 'none';+ }+ // Add visual feedback class to search box when active+ if (searchInput.value) {+ searchInput.parentElement.classList.add('active-search');+ } else {+ searchInput.parentElement.classList.remove('active-search');+ }+ // Debounce applyFilters+ if (searchDebounceTimeout) clearTimeout(searchDebounceTimeout);+ searchDebounceTimeout = setTimeout(() => {+ applyFilters();+ saveFilterPreferences();+ }, 300);+ });}-}++ if (clearSearchBtn) {+ clearSearchBtn.addEventListener('click', () => {+ if (searchInput) {+ searchInput.value = '';+ currentFilters.search = '';+ clearSearchBtn.style.display = 'none';+ searchInput.parentElement.classList.remove('active-search');+ searchInput.focus();+ applyFilters();+ saveFilterPreferences();+ }+ });+ }++ if (statusFilter) {+ statusFilter.addEventListener('change', () => {+ currentFilters.status = statusFilter.value;+ applyFilters();+ saveFilterPreferences();+ });+ }++ if (tagFilter) {+ tagFilter.addEventListener('change', () => {+ currentFilters.tag = tagFilter.value;+ applyFilters();+ saveFilterPreferences();+ });+ }++ if (vendorFilter) { // Added event listener for vendor filter+ vendorFilter.addEventListener('change', () => {+ currentFilters.vendor = vendorFilter.value;+ applyFilters();+ saveFilterPreferences();+ });+ }++ if (warrantyTypeFilter) { // Added event listener for warranty type filter+ warrantyTypeFilter.addEventListener('change', () => {+ currentFilters.warranty_type = warrantyTypeFilter.value;+ applyFilters();+ saveFilterPreferences();+ });+ }++ if (sortBySelect) {+ sortBySelect.addEventListener('change', () => {+ currentFilters.sortBy = sortBySelect.value;+ applyFilters();+ saveFilterPreferences();+ });+ }++ // Note: Clear Filters button handler is in index.html inline script to close popover++ // View switcher event listeners+ const gridViewBtn = document.getElementById('gridViewBtn');+ const listViewBtn = document.getElementById('listViewBtn');+ const tableViewBtn = document.getElementById('tableViewBtn');++ if (gridViewBtn) gridViewBtn.addEventListener('click', () => switchView('grid'));+ if (listViewBtn) listViewBtn.addEventListener('click', () => switchView('list'));+ if (tableViewBtn) tableViewBtn.addEventListener('click', () => switchView('table'));++ // Export button event listener+ const exportBtn = document.getElementById('exportBtn');+ if (exportBtn) exportBtn.addEventListener('click', exportWarranties);++ // Import button event listener+ if (importBtn && csvFileInput) {+ importBtn.addEventListener('click', () => {+ csvFileInput.click(); // Trigger hidden file input+ });+ csvFileInput.addEventListener('change', (event) => {+ if (event.target.files && event.target.files.length > 0) {+ handleImport(event.target.files[0]);+ }+ });+ }++ // Refresh button+ const refreshBtn = document.getElementById('refreshBtn');+ if (refreshBtn) refreshBtn.addEventListener('click', loadWarranties);++ // Warranty Type dropdown handlers for custom option+ if (warrantyTypeInput && warrantyTypeCustomInput) {+ warrantyTypeInput.addEventListener('change', () => {+ if (warrantyTypeInput.value === 'other') {+ warrantyTypeCustomInput.style.display = 'block';+ warrantyTypeCustomInput.focus();+ } else {+ warrantyTypeCustomInput.style.display = 'none';+ warrantyTypeCustomInput.value = '';+ }+ updateSummary(); // Update summary when warranty type changes+ });++ // Also update summary when custom warranty type changes+ warrantyTypeCustomInput.addEventListener('input', updateSummary);+ }++ if (editWarrantyTypeInput && editWarrantyTypeCustomInput) {+ editWarrantyTypeInput.addEventListener('change', () => {+ if (editWarrantyTypeInput.value === 'other') {+ editWarrantyTypeCustomInput.style.display = 'block';+ editWarrantyTypeCustomInput.focus();+ } else {+ editWarrantyTypeCustomInput.style.display = 'none';+ editWarrantyTypeCustomInput.value = '';+ }+ });+ }++ // Save warranty changes+ const saveWarrantyBtn = document.getElementById('saveWarrantyBtn');+ if (saveWarrantyBtn) {+ let functionToAttachOnClick = saveWarranty; // Default to the original saveWarranty from script.js-function populateWarrantyTypeFilter() {- if (window.warrantyListController && typeof window.warrantyListController.populateWarrantyTypeFilter === 'function') {- return window.warrantyListController.populateWarrantyTypeFilter();+ // Check if the observer setup function from status.js is available+ if (typeof window.setupSaveWarrantyObserver === 'function') {+ console.log('[script.js] window.setupSaveWarrantyObserver (from status.js) was FOUND. Attempting to wrap local saveWarranty function.');+ try {+ // Call the observer setup function, passing it the original saveWarranty from this script.+ // The observer setup function is expected to return a new function that wraps the original.+ functionToAttachOnClick = window.setupSaveWarrantyObserver(saveWarranty);++ // Optional: A flag to let status.js know that script.js has handled the wrapping.+ // This can be useful if status.js has any fallback/polling logic to prevent double-wrapping.+ window.saveWarrantyObserverAttachedByScriptJS = true;+ console.log('[script.js] Local saveWarranty function has been successfully WRAPPED by the observer from status.js.');+ } catch (e) {+ console.error('[script.js] An error occurred while trying to wrap saveWarranty with the observer from status.js:', e);+ // If an error occurs during wrapping, functionToAttachOnClick will remain the original saveWarranty.+ }+ } else {+ console.log('[script.js] window.setupSaveWarrantyObserver (from status.js) was NOT FOUND. Using the original saveWarranty function for the button.');+ }++ // Add the event listener using the (potentially) wrapped function.+ saveWarrantyBtn.addEventListener('click', () => {+ console.log('[script.js] Save button (saveWarrantyBtn) clicked. Invoking the determined save function (functionToAttachOnClick).');+ if (typeof functionToAttachOnClick === 'function') {+ functionToAttachOnClick(); // Execute the determined save function+ } else {+ console.error('[script.js] CRITICAL: functionToAttachOnClick is not a function when save button was clicked!');+ }+ });++ } else {+ console.warn('[script.js] saveWarrantyBtn DOM element not found. Cannot attach click listener.');}++ // Confirm delete button+ const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');+ if (confirmDeleteBtn) confirmDeleteBtn.addEventListener('click', deleteWarranty);++ // Confirm archive button+ const confirmArchiveBtn = document.getElementById('confirmArchiveBtn');+ if (confirmArchiveBtn) confirmArchiveBtn.addEventListener('click', confirmArchive);++ // Load saved view preference+ // loadViewPreference(); // Disabled: now called after authStateReady}// Function to show loading spinner@@ -5689,11 +6191,8 @@ function deleteWarranty() {// --- BEGIN FIX: Update UI immediately ---// Remove the deleted warranty from the global arrayconst deletedId = currentWarrantyId; // Store ID before resetting- const __w = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];- const __updated = __w.filter(warranty => warranty.id !== deletedId);- if (window.store && window.store.setWarranties) window.store.setWarranties(__updated);+ warranties = warranties.filter(warranty => warranty.id !== deletedId);currentWarrantyId = null; // Reset current ID- window.currentWarrantyId = null; // Also clear window property// Re-render the list using the updated local arrayapplyFilters();@@ -5706,7 +6205,333 @@ function deleteWarranty() {});}-// Save warranty logic moved to window.components.editModal.saveWarranty+// Save warranty updates+function saveWarranty() {+ console.log("[script.js] CORE saveWarranty (original from script.js) EXECUTING.");+ if (!currentWarrantyId) {+ showToast(window.t('messages.no_warranty_selected_for_update'), 'error');+ return;+ }++ // --- Get form values ---+ const productName = document.getElementById('editProductName').value.trim();+ const purchaseDate = document.getElementById('editPurchaseDate').value;+ const isLifetime = document.getElementById('editIsLifetime').checked;+ const isDurationMethod = editDurationMethodRadio && editDurationMethodRadio.checked;+ // Get new duration values+ const years = parseInt(document.getElementById('editWarrantyDurationYears').value || 0);+ const months = parseInt(document.getElementById('editWarrantyDurationMonths').value || 0);+ const days = parseInt(document.getElementById('editWarrantyDurationDays').value || 0);+ const exactDate = editExactExpirationDateInput ? editExactExpirationDateInput.value : '';++ // Basic validation+ if (!productName) {+ showToast(window.t('messages.product_name_required'), 'error');+ return;+ }++ if (!purchaseDate) {+ showToast(window.t('messages.purchase_date_required'), 'error');+ return;+ }++ // --- Updated Validation ---+ if (!isLifetime) {+ if (isDurationMethod) {+ // Validate duration fields+ if (years === 0 && months === 0 && days === 0) {+ showToast(window.t('messages.warranty_duration_required'), 'error');+ // Optional: focus the years input again+ const yearsInput = document.getElementById('editWarrantyDurationYears');+ if (yearsInput) { // Check if element exists+ yearsInput.focus();+ // Add invalid class to container or inputs+ if (editWarrantyDurationFields) editWarrantyDurationFields.classList.add('invalid-duration');+ }+ return;+ }+ } else {+ // Validate exact expiration date+ if (!exactDate) {+ showToast(window.t('messages.exact_expiration_date_required'), 'error');+ if (editExactExpirationDateInput) editExactExpirationDateInput.focus();+ return;+ }++ // Validate that expiration date is in the future relative to purchase date+ if (purchaseDate && exactDate <= purchaseDate) {+ showToast(window.t('messages.expiration_date_after_purchase_date'), 'error');+ if (editExactExpirationDateInput) editExactExpirationDateInput.focus();+ return;+ }+ }+ }++ // Remove invalid duration class if validation passes+ if (editWarrantyDurationFields) editWarrantyDurationFields.classList.remove('invalid-duration');+ // --- End Updated Validation ---++ // Create form data+ const formData = new FormData();+ formData.append('product_name', productName);+ formData.append('purchase_date', purchaseDate);++ // Optional fields+ let productUrl = document.getElementById('editProductUrl').value.trim();+ if (productUrl) {+ if (!productUrl.startsWith('http://') && !productUrl.startsWith('https://')) {+ productUrl = 'https://' + productUrl;+ }+ formData.append('product_url', productUrl);+ }++ 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[]"]');+ // Clear existing before appending+ formData.delete('serial_numbers[]');+ serialInputs.forEach(input => {+ if (input.value.trim()) {+ formData.append('serial_numbers[]', input.value.trim()); // Use []+ }+ });++ // Tags - add tag IDs as JSON string+ if (editSelectedTags && editSelectedTags.length > 0) {+ const tagIds = editSelectedTags.map(tag => tag.id);+ formData.append('tag_ids', JSON.stringify(tagIds));+ } else {+ // Send empty array to clear tags+ formData.append('tag_ids', JSON.stringify([]));+ }++ // Add URL fields for documents (with null checks)+ const editInvoiceUrlField = document.getElementById('editInvoiceUrl');+ formData.append('invoice_url', editInvoiceUrlField ? editInvoiceUrlField.value || '' : '');++ const editManualUrlField = document.getElementById('editManualUrl');+ formData.append('manual_url', editManualUrlField ? editManualUrlField.value || '' : '');++ const editOtherDocumentUrlField = document.getElementById('editOtherDocumentUrl');+ formData.append('other_document_url', editOtherDocumentUrlField ? editOtherDocumentUrlField.value || '' : '');++ // Files+ const invoiceFile = document.getElementById('editInvoice').files[0];+ if (invoiceFile) {+ formData.append('invoice', invoiceFile);+ }++ const manualFile = document.getElementById('editManual').files[0];+ if (manualFile) {+ formData.append('manual', manualFile);+ }++ const otherDocumentFile = document.getElementById('editOtherDocument').files[0];+ if (otherDocumentFile) {+ formData.append('other_document', otherDocumentFile);+ }++ // Product photo+ const productPhotoFile = document.getElementById('editProductPhoto').files[0];+ if (productPhotoFile) {+ formData.append('product_photo', productPhotoFile);+ }++ // Document deletion flags+ const deleteInvoiceBtn = document.getElementById('deleteInvoiceBtn');+ if (deleteInvoiceBtn && deleteInvoiceBtn.dataset.delete === 'true') {+ formData.append('delete_invoice', 'true');+ }+ const deleteManualBtn = document.getElementById('deleteManualBtn');+ if (deleteManualBtn && deleteManualBtn.dataset.delete === 'true') {+ formData.append('delete_manual', 'true');+ }+ const deleteOtherDocumentBtn = document.getElementById('deleteOtherDocumentBtn');+ if (deleteOtherDocumentBtn && deleteOtherDocumentBtn.dataset.delete === 'true') {+ formData.append('delete_other_document', 'true');+ }+ const deleteProductPhotoBtn = document.getElementById('deleteProductPhotoBtn');+ if (deleteProductPhotoBtn && deleteProductPhotoBtn.dataset.delete === 'true') {+ formData.append('delete_product_photo', 'true');+ }++ // --- Append is_lifetime and duration components ---+ formData.append('is_lifetime', isLifetime.toString());+ if (!isLifetime) {+ if (isDurationMethod) {+ formData.append('warranty_duration_years', years);+ formData.append('warranty_duration_months', months);+ formData.append('warranty_duration_days', days);+ } else {+ // Using exact date method+ formData.append('exact_expiration_date', exactDate);+ // Ensure duration fields are 0 when using exact date+ formData.append('warranty_duration_years', 0);+ formData.append('warranty_duration_months', 0);+ formData.append('warranty_duration_days', 0);+ }+ } else {+ // Ensure duration is 0 if lifetime+ formData.append('warranty_duration_years', 0);+ formData.append('warranty_duration_months', 0);+ formData.append('warranty_duration_days', 0);+ }+ // Add notes+ const notes = document.getElementById('editNotes').value;+ if (notes && notes.trim() !== '') {+ formData.append('notes', notes);+ } else {+ // Explicitly clear notes if empty+ formData.append('notes', '');+ }++ // Add model number to form data (optional)+ const editModelNumber = document.getElementById('editModelNumber');+ if (editModelNumber && editModelNumber.value.trim() !== '') {+ formData.append('model_number', editModelNumber.value.trim());+ } else {+ // Explicitly clear if empty+ formData.append('model_number', '');+ }++ // Add vendor/retailer to form data+ const editVendorInput = document.getElementById('editVendor'); // Use the correct ID+ formData.append('vendor', editVendorInput ? editVendorInput.value.trim() : ''); // Use the correct variable++ // Add warranty type to form data - handle custom type+ const editWarrantyTypeInput = document.getElementById('editWarrantyType');+ const editWarrantyTypeCustomInput = document.getElementById('editWarrantyTypeCustom');+ let warrantyTypeValue = '';+ if (editWarrantyTypeInput) {+ if (editWarrantyTypeInput.value === 'other' && editWarrantyTypeCustomInput && editWarrantyTypeCustomInput.value.trim()) {+ warrantyTypeValue = editWarrantyTypeCustomInput.value.trim();+ } else {+ warrantyTypeValue = editWarrantyTypeInput.value.trim();+ }+ }+ formData.append('warranty_type', warrantyTypeValue);++ // Add selected Paperless documents for edit form+ const selectedEditPaperlessProductPhoto = document.getElementById('selectedEditPaperlessProductPhoto');+ const selectedEditPaperlessInvoice = document.getElementById('selectedEditPaperlessInvoice');+ const selectedEditPaperlessManual = document.getElementById('selectedEditPaperlessManual');+ const selectedEditPaperlessOtherDocument = document.getElementById('selectedEditPaperlessOtherDocument');++ if (selectedEditPaperlessProductPhoto && selectedEditPaperlessProductPhoto.value) {+ formData.append('paperless_photo_id', selectedEditPaperlessProductPhoto.value);+ }+ if (selectedEditPaperlessInvoice && selectedEditPaperlessInvoice.value) {+ formData.append('paperless_invoice_id', selectedEditPaperlessInvoice.value);+ }+ if (selectedEditPaperlessManual && selectedEditPaperlessManual.value) {+ formData.append('paperless_manual_id', selectedEditPaperlessManual.value);+ }+ if (selectedEditPaperlessOtherDocument && selectedEditPaperlessOtherDocument.value) {+ formData.append('paperless_other_id', selectedEditPaperlessOtherDocument.value);+ }++ // DEBUG: Log what we're sending to the backend+ console.log('[DEBUG saveWarranty] Form data being sent:');+ console.log('[DEBUG saveWarranty] isLifetime:', isLifetime);+ console.log('[DEBUG saveWarranty] isDurationMethod:', isDurationMethod);+ console.log('[DEBUG saveWarranty] exactDate:', exactDate);+ console.log('[DEBUG saveWarranty] years/months/days:', years, months, days);++ // Log all form data entries+ for (let [key, value] of formData.entries()) {+ console.log(`[DEBUG saveWarranty] FormData: ${key} = ${value}`);+ }++ // Get auth token+ const token = localStorage.getItem('auth_token');+ if (!token) {+ showToast('Authentication required', 'error');+ return;+ }++ showLoadingSpinner();++ // Process Paperless-ngx uploads if enabled+ processEditPaperlessNgxUploads(formData)+ .then(paperlessUploads => {+ // Add Paperless-ngx document IDs to form data+ Object.keys(paperlessUploads).forEach(key => {+ formData.append(key, paperlessUploads[key]);+ });++ // Send request+ return fetch(`/api/warranties/${currentWarrantyId}`, {+ method: 'PUT',+ headers: {+ 'Authorization': 'Bearer ' + token+ },+ body: formData+ });+ })+ .then(response => {+ if (!response.ok) {+ return response.json().then(data => {+ throw new Error(data.error || 'Failed to update warranty');+ });+ }+ return response.json();+ })+ .then(data => {+ hideLoadingSpinner();+ showToast('Warranty updated successfully', 'success');+ closeModals();++ // Always reload from server to ensure we get the latest data including product photo paths+ console.log('Reloading warranties after edit to ensure latest data including product photos');+ loadWarranties(true).then(() => {+ console.log('Warranties reloaded after editing warranty');+ applyFilters();+ // Load secure images for the updated cards - additional call to ensure they load+ setTimeout(() => {+ console.log('Loading secure images for updated warranty cards');+ loadSecureImages();+ }, 200); // Slightly longer delay to ensure everything is rendered++ // Always close the notes modal if open, to ensure UI is in sync+ const notesModal = document.getElementById('notesModal');+ if (notesModal && notesModal.style.display === 'block') {+ notesModal.style.display = 'none';+ }++ console.log('Warranty updated and reloaded from server');++ // Auto-link any documents that were uploaded to Paperless-ngx+ if ((invoiceFile || manualFile || otherDocumentFile) && currentWarrantyId) {+ console.log('[Auto-Link] Starting automatic document linking after warranty update');++ // Collect filename information for intelligent searching+ const fileInfo = {};+ if (invoiceFile) fileInfo.invoice = invoiceFile.name;+ if (manualFile) fileInfo.manual = manualFile.name;+ if (otherDocumentFile) fileInfo.other = otherDocumentFile.name;++ setTimeout(() => {+ autoLinkRecentDocuments(currentWarrantyId, ['invoice', 'manual', 'other'], 10, 10000, fileInfo);+ }, 3000); // Wait 3 seconds for Paperless-ngx to process the documents+ }+ }).catch(error => {+ console.error('Error reloading warranties after edit:', error);+ });+ })+ .catch(error => {+ hideLoadingSpinner();+ console.error('Error updating warranty:', error);+ showToast(error.message || 'Failed to update warranty', 'error');+ });+}// Function to populate tag filter dropdownfunction populateTagFilter() {@@ -5722,8 +6547,7 @@ function populateTagFilter() {const uniqueTags = new Set();// Collect all unique tags from warranties- const __w = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];- __w.forEach(warranty => {+ warranties.forEach(warranty => {if (warranty.tags && Array.isArray(warranty.tags)) {warranty.tags.forEach(tag => {uniqueTags.add(JSON.stringify({id: tag.id, name: tag.name, color: tag.color}));@@ -5762,8 +6586,7 @@ function populateVendorFilter() {const uniqueVendors = new Set();// Collect all unique, non-empty vendors from warranties- const __w = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];- __w.forEach(warranty => {+ warranties.forEach(warranty => {if (warranty.vendor && warranty.vendor.trim() !== '') {uniqueVendors.add(warranty.vendor.trim().toLowerCase());}@@ -5798,8 +6621,7 @@ function populateWarrantyTypeFilter() {const uniqueWarrantyTypes = new Set();// Collect all unique, non-empty warranty types from warranties- const __w = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];- __w.forEach(warranty => {+ warranties.forEach(warranty => {if (warranty.warranty_type && warranty.warranty_type.trim() !== '') {uniqueWarrantyTypes.add(warranty.warranty_type.trim().toLowerCase());}@@ -6231,7 +7053,7 @@ if (!document.getElementById('notesModal')) {// Add event listener for Edit Warranty buttondocument.getElementById('editWarrantyBtn').addEventListener('click', async () => {// Find the current warranty data from the global array- const currentWarranty = (((window.store && window.store.getWarranties && window.store.getWarranties()) || []).find(w => w.id === notesModalWarrantyId));+ const currentWarranty = warranties.find(w => w.id === notesModalWarrantyId);if (currentWarranty) {console.log('[DEBUG] Edit Warranty button clicked, opening edit modal with warranty:', currentWarranty.id, 'notes:', currentWarranty.notes);// Close the notes modal first@@ -6263,7 +7085,7 @@ function showNotesModal(notes, warrantyOrId = null) {} else {notesModalWarrantyId = warrantyOrId;// Try to find the warranty object from global warranties array- notesModalWarrantyObj = ((((window.store && window.store.getWarranties && window.store.getWarranties()) || []).find(w => w.id === notesModalWarrantyId)) || null);+ notesModalWarrantyObj = warranties.find(w => w.id === notesModalWarrantyId) || null;}// Show note content, hide textarea and edit controlsdiff --git a/frontend/settings-new.html b/frontend/settings-new.htmlindex eca725a..04a4f1a 100644--- a/frontend/settings-new.html+++ b/frontend/settings-new.html@@ -2,47 +2,48 @@<html><head><!-- Authentication redirect script -->- <script src="./auth-redirect.js?v=20250119001" data-protected="true"></script>+ <script src="auth-redirect.js?v=20250119001" data-protected="true"></script><!-- Include authentication script first to handle login state immediately -->-+ <script src="include-auth-new.js?v=20250119001"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Settings - Warracker</title><!-- Favicons -->- <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">- <link rel="icon" type="image/png" sizes="16x16" href="./img/favicon-16x16.png?v=2">- <link rel="icon" type="image/png" sizes="32x32" href="./img/favicon-32x32.png?v=2">- <link rel="apple-touch-icon" sizes="180x180" href="./img/favicon-512x512.png">- <link rel="manifest" href="./manifest.json">+ <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">+ <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">+ <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">+ <link rel="manifest" href="manifest.json"><!-- Load the main site styles first -->- <link rel="stylesheet" href="./style.css?v=20250119004">+ <link rel="stylesheet" href="style.css?v=20250119004"><!-- Font Awesome for icons --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css"><!-- Then load settings-specific styles -->- <link rel="stylesheet" href="./settings-styles.css?v=20250119001">+ <link rel="stylesheet" href="settings-styles.css?v=20250119001"><!-- Apply theme immediately -->- <script src="./theme-loader.js?v=20250119001"></script>- <script type="module" src="./js/services/authService.js"></script>- <script type="module" src="./js/services/apiService.js"></script>+ <script src="theme-loader.js?v=20250119001"></script><!-- Load header fix styles last to override any conflicting styles -->- <link rel="stylesheet" href="./header-fix.css?v=20250119001">+ <link rel="stylesheet" href="header-fix.css?v=20250119001"><!-- Mobile Header specific styles -->- <link rel="stylesheet" href="./mobile-header.css?v=20250119002">+ <link rel="stylesheet" href="mobile-header.css?v=20250119002"><!-- Load fix for auth buttons -->-+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script><!-- i18next Local Scripts -->- <script src="./js/lib/i18next.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>+ <script src="js/lib/i18next.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script><!-- i18n Configuration -->- <script src="./js/i18n.js?v=20250119001"></script>+ <script src="js/i18n.js?v=20250119001"></script>++ <!-- Temporary debug script -->+ <script src="js/i18n-debug.js?v=20250119001"></script><!-- Mobile menu logic isolated to avoid collisions on settings -->- <script src="./mobile-menu.js?v=20250119002" defer></script>+ <script src="mobile-menu.js?v=20250119002" defer></script><!-- Immediate authentication check script --><script>@@ -1076,17 +1077,52 @@<p style="font-size: 0.8em; color: #666;">User ID: <span id="displayUserId"></span></p><div class="modal-footer"><button type="button" class="btn btn-secondary close-modal">Cancel</button>- <button type="button" id="confirmDeleteUserBtn" class="btn btn-danger">Delete</button>+ <button type="button" id="confirmDeleteUserBtn" class="btn btn-danger" onclick="deleteUser()">Delete</button></div><div style="margin-top: 20px; border-top: 1px solid #ddd; padding-top: 10px;"><p><small>If the delete button doesn't work, try these alternatives:</small></p><ul style="font-size: 0.8em;">- <li><a href="#" id="directDeleteLink" style="color: #dc3545;">Alternative 1: Direct function call</a></li>- <li><a href="#" id="directAPILink" style="color: #dc3545;">Alternative 2: Direct API call</a></li>+ <li><a href="#" id="directDeleteLink" style="color: #dc3545;" onclick="deleteUser(); return false;">Alternative 1: Direct function call</a></li>+ <li><a href="#" id="directAPILink" style="color: #dc3545;" onclick="directDeleteUserAPI(document.getElementById('deleteUserId').value); return false;">Alternative 2: Direct API call</a></li><li><button type="submit" class="btn btn-sm btn-danger">Alternative 3: Form Submit</button></li></ul><div style="margin-top: 10px;">- <button type="button" id="emergencyDeleteBtn" class="btn btn-sm btn-danger">Emergency Delete</button>+ <button type="button" id="emergencyDeleteBtn" class="btn btn-sm btn-danger"+ onclick="(function() {+ const userId = document.getElementById('deleteUserId').value || document.getElementById('displayUserId').textContent;+ if (!userId) {+ alert('Error: User ID is missing');+ return;+ }+ const token = localStorage.getItem('auth_token');+ if (!token) {+ alert('Error: Authentication token is missing');+ return;+ }+ alert('Emergency delete for user ID: ' + userId);+ fetch('/api/admin/users/' + userId, {+ method: 'DELETE',+ headers: {+ 'Authorization': 'Bearer ' + token,+ 'Content-Type': 'application/json'+ }+ })+ .then(response => {+ alert('Response status: ' + response.status);+ if (response.status >= 200 && response.status < 300) {+ alert('User deleted successfully');+ document.querySelectorAll('.modal-backdrop').forEach(m => m.style.display = 'none');+ location.reload();+ } else {+ alert('Failed to delete user: ' + response.status);+ }+ })+ .catch(error => {+ alert('Error: ' + error.message);+ });+ })(); return false;">+ Emergency Delete (Inline JS)+ </button></div></div></form>@@ -1136,14 +1172,14 @@<div id="toastContainer" class="toast-container"></div><!-- Scripts -->-- <script type="module" src="./settings-new.js"></script>+ <script src="auth.js?v=20250119001"></script>+ <script src="settings-new.js?v=20250119001"></script><!-- Footer Width Fix -->- <script src="./footer-fix.js?v=20251024001"></script>+ <script src="footer-fix.js?v=20251024001"></script><!-- Footer Content Manager -->- <script src="./footer-content.js?v=20250119001"></script>+ <script src="footer-content.js?v=20250119001"></script><!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">diff --git a/frontend/status.html b/frontend/status.htmlindex 8077370..e909f48 100644--- a/frontend/status.html+++ b/frontend/status.html@@ -2,47 +2,43 @@<html><head><!-- Authentication redirect script -->- <script src="./auth-redirect.js?v=20250119001" data-protected="true"></script>+ <script src="auth-redirect.js?v=20250119001" data-protected="true"></script><!-- Include authentication script first to handle login state immediately -->-+ <script src="include-auth-new.js?v=20250119001"></script><!-- File utilities script for secure file handling -->- <script src="./file-utils.js?v=20250119001"></script>+ <script src="file-utils.js?v=20250119001"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title data-i18n="status.title">Status - Warracker</title><!-- Favicons -->- <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">- <link rel="icon" type="image/png" sizes="16x16" href="./img/favicon-16x16.png?v=2">- <link rel="icon" type="image/png" sizes="32x32" href="./img/favicon-32x32.png?v=2">- <link rel="apple-touch-icon" sizes="180x180" href="./img/favicon-512x512.png">- <link rel="manifest" href="./manifest.json">- <link rel="stylesheet" href="./style.css?v=20250119004">- <script src="./theme-loader.js?v=20250119001"></script> <!-- Apply theme early -->- <script type="module" src="./js/store.js"></script>- <script type="module" src="./js/services/authService.js"></script>- <script type="module" src="./js/services/apiService.js"></script>+ <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">+ <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png?v=2">+ <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2">+ <link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png">+ <link rel="manifest" href="manifest.json">+ <link rel="stylesheet" href="style.css?v=20250119004">+ <script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early --><!-- Font Awesome for icons --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css"><!-- Load header fix styles to ensure consistent header styling -->- <link rel="stylesheet" href="./header-fix.css?v=20250119001">+ <link rel="stylesheet" href="header-fix.css?v=20250119001"><!-- Mobile Header specific styles -->- <link rel="stylesheet" href="./mobile-header.css?v=20250119002">+ <link rel="stylesheet" href="mobile-header.css?v=20250119002"><!-- Chart.js for visualizations -->- <script src="./chart.js?v=20250119001"></script>+ <script src="chart.js?v=20250119001"></script><!-- i18next Local Scripts -->- <script src="./js/lib/i18next.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>- <script src="./js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script>+ <script src="js/lib/i18next.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextHttpBackend.min.js?v=20250119001"></script>+ <script src="js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001"></script><!-- i18n initialization script -->- <script src="./js/i18n.js?v=20250119001"></script>+ <script src="js/i18n.js?v=20250119001"></script><!-- Load fix for auth buttons -->-- <script src="./script.js?v=20250119002" defer></script> <!-- Added script.js -->- <script type="module" src="./js/index.js"></script>- <script type="module" src="./status.js?v=20250119001"></script> <!-- Status page specific functionality -->+ <script src="fix-auth-buttons-loader.js?v=20250119001"></script>+ <script src="script.js?v=20250119002" defer></script> <!-- Added script.js -->+ <script src="status.js?v=20250119001" defer></script> <!-- Status page specific functionality --><style>.user-menu {position: relative;@@ -826,14 +822,14 @@<div class="loading-spinner"></div></div>-- <script type="module" src="./status.js?v=20250119001"></script>+ <script src="auth.js?v=20250119001"></script>+ <script src="status.js?v=20250119001" defer></script><!-- Footer Width Fix -->- <script src="./footer-fix.js?v=20251024001"></script>+ <script src="footer-fix.js?v=20251024001"></script><!-- Footer Content Manager -->- <script src="./footer-content.js?v=20250119001"></script>+ <script src="footer-content.js?v=20250119001"></script><!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">diff --git a/frontend/status.js b/frontend/status.jsindex 6191ddc..6ffa111 100644--- a/frontend/status.js+++ b/frontend/status.js@@ -1,5 +1,3 @@-import apiService from './js/services/apiService.js';-import authService from './js/services/authService.js';(function() {// DOM Elementsconst loadingIndicator = document.getElementById('loadingIndicator');@@ -103,13 +101,17 @@ import authService from './js/services/authService.js';async function fetchStatistics() {try {console.log('Checking authentication status... (status.js IIFE)');- if (!authService || !authService.isAuthenticated()) {+ if (!window.auth || !window.auth.isAuthenticated()) {throw new Error('Authentication required.');}- const token = authService.getToken();+ const token = window.auth.getToken();if (!token) {throw new Error('Authentication token not available.');}+ const options = {+ method: 'GET',+ headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json'}+ };// Check saved view scope preference to determine which API endpoint to useconst savedScope = loadViewScopePreference();@@ -119,15 +121,17 @@ import authService from './js/services/authService.js';const apiUrl = shouldUseGlobalView ? GLOBAL_STATISTICS_API_URL : STATISTICS_API_URL;console.log('Fetching statistics from:', apiUrl, '(Global view preference:', savedScope, ')');- const response = shouldUseGlobalView- ? await apiService.request('/api/statistics/global')- : await apiService.request('/api/statistics');- const json = await response.json();+ 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 dataisGlobalView = shouldUseGlobalView;console.log(`[DEBUG] Set isGlobalView to: ${isGlobalView}`);- return json;+ return await response.json();} catch (error) {console.error('Error fetching statistics (status.js IIFE):', error);throw error;@@ -154,10 +158,13 @@ import authService from './js/services/authService.js';try {// Check if global view is enabled for this user- const token = authService.getToken();+ const token = window.auth.getToken();if (!token) return;- const response = await apiService.request('/api/settings/global-view-status', { method: 'GET' });+ const response = await fetch('/api/settings/global-view-status', {+ method: 'GET',+ headers: { 'Authorization': `Bearer ${token}` }+ });if (response.ok) {const result = await response.json();@@ -336,8 +343,11 @@ import authService from './js/services/authService.js';try {// Check if global view is still available- const token = authService.getToken();- const response = await apiService.request('/api/settings/global-view-status', { method: 'GET' });+ const token = window.auth.getToken();+ const response = await fetch('/api/settings/global-view-status', {+ method: 'GET',+ headers: { 'Authorization': `Bearer ${token}` }+ });if (response.ok) {const result = await response.json();@@ -934,9 +944,14 @@ import authService from './js/services/authService.js';let allWarrantiesForTimeline = [];try {// Try to fetch all warranties for a complete timeline- const token = authService && authService.getToken ? authService.getToken() : null;+ const token = window.auth && window.auth.getToken ? window.auth.getToken() : null;if (token) {- const allWarrantiesResponse = await apiService.request('/api/warranties', { method: 'GET' });+ const allWarrantiesResponse = await fetch('/api/warranties', {+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Content-Type': 'application/json'+ }+ });if (allWarrantiesResponse.ok) {allWarrantiesForTimeline = await allWarrantiesResponse.json();} else {@@ -1017,8 +1032,9 @@ import authService from './js/services/authService.js';async function loadUserPreferences() {try {- if (!authService || !authService.getToken()) { console.warn('Auth or token not available for prefs in status.js'); return; }- const response = await apiService.request('/api/auth/preferences', { method: 'GET' });+ if (!window.auth || !window.auth.getToken()) { console.warn('Auth or token not available for prefs in status.js'); return; }+ const token = window.auth.getToken();+ const response = await fetch('/api/auth/preferences', { headers: { 'Authorization': `Bearer ${token}` } });if (response.ok) {const prefs = await response.json();if (prefs && prefs.expiring_soon_days !== undefined) { // Check for undefined specifically@@ -1072,10 +1088,13 @@ import authService from './js/services/authService.js';// ALWAYS fetch fresh details when editing from the status page to ensure modal has latest data.console.log(`[DEBUG status.js] Edit from status page for warranty ${warrantyId}. ALWAYS fetching fresh details from /api/debug/warranty/:id.`);showLoadingSpinner(); // Show spinner for this specific fetch- const token = authService.getToken();+ const token = localStorage.getItem('auth_token') || (window.auth && window.auth.getToken());if (!token) throw new Error('Authentication token not available for fetching fresh details.');- const response = await apiService.request(`/api/debug/warranty/${warrantyId}`, { method: 'GET' });+ const response = await fetch(`/api/debug/warranty/${warrantyId}`, {+ method: 'GET',+ headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }+ });if (!response.ok) {const errorData = await response.json().catch(() => ({}));diff --git a/frontend/style.css b/frontend/style.cssindex b365df8..4c14ae6 100644--- a/frontend/style.css+++ b/frontend/style.css@@ -4827,18 +4827,18 @@ html.dark-mode .warracker-footer a:hover {}}-@media (max-width: 360px) {+@media (max-width: 768px) {.grid-view .product-photo-thumbnail img {- width: 30px;- height: 30px;+ width: 30px;+ height: 30px;}.list-view .product-photo-thumbnail img {- width: 60px;- height: 60px;+ width: 25px;+ height: 25px;}.table-view .product-photo-thumbnail img {- width: 20px;- height: 20px;+ width: 20px;+ height: 20px;}.product-photo-thumbnail {margin-right: 5px;diff --git a/frontend/sw.js b/frontend/sw.jsindex d01731d..97b932f 100644--- a/frontend/sw.js+++ b/frontend/sw.js@@ -15,6 +15,7 @@ const urlsToCache = [// Stylesheets (versioned)'./style.css?v=20250119004',+ './styles.css?v=20250119001','./settings-styles.css?v=20250119001','./header-fix.css?v=20250119001','./mobile-header.css?v=20250119002',diff --git a/frontend/version-checker.js b/frontend/version-checker.jsindex b1e5b78..3be2504 100644--- a/frontend/version-checker.js+++ b/frontend/version-checker.js@@ -1,6 +1,6 @@// Version checker for Warrackerdocument.addEventListener('DOMContentLoaded', () => {- const currentVersion = '1.0.3'; // Current version of the application+ const currentVersion = '1.0.2'; // Current version of the applicationconst updateStatus = document.getElementById('updateStatus');const updateLink = document.getElementById('updateLink');const versionDisplay = document.getElementById('versionDisplay');