🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Removed vite
sassanix23028fe6961f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ce508f1..08440fa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,55 +2,65 @@## 1.0.3 - 2025-11-07### Added-- **Vite build tool (multi-page app) for the frontend**- - Initialized npm in `frontend/` with `dev`, `build`, and `preview` scripts.- - Introduced `vite.config.js` with `root: 'src'`, `outDir: '../dist'`, `publicDir: 'public'`, a development `/api` proxy, and explicit multi-page HTML inputs.- - Restructured frontend: moved sources to `frontend/src/` and static/non-module assets to `frontend/public/`.- - _Files: `frontend/package.json`, `frontend/vite.config.js`, `frontend/src/**/*`, `frontend/public/**/*`_+- **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/src/js/services/authService.js`, `frontend/src/*.html` (module includes)_+ - _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/src/js/services/apiService.js`, `frontend/src/*.html` (module includes)_+ - _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/src/js/store.js`_+ - _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/src/js/components/*`_+ - _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/src/index.html`_+ - _Files: `frontend/index.html`_### Enhanced-- **Dockerfile: multi-stage frontend build + runtime serving**- - Added `frontend-build` stage using `node:20-alpine` to run `npm ci && npm run build`.- - Final stage copies `frontend/dist/` to `/var/www/html` and includes `frontend/public/` assets in the build.- - Unpinned Node digest to resolve `not found` errors on some hosts.+- **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 root-relative (e.g., `/script.js`).+ - 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.- - Moved non-module assets (e.g., `i18n.js`, `i18next*.js`, `script.js`, `theme-loader.js`, etc.) to `frontend/public/` so they are served verbatim in production.- - _Files: `frontend/src/*.html`, `frontend/public/**/*`_--- **Build stability**- - Moved `settings-styles.css` to `public/` to bypass a PostCSS parse error in production builds (no functional/visual changes).- - _Files: `frontend/public/settings-styles.css`_+ - 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.@@ -58,39 +68,113 @@- **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/src/script.js`, `frontend/src/js/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 serving them from Vite `public/`.+- 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/src/about.html` and removing it from the service worker pre-cache (`frontend/public/sw.js`).- - _Files: `frontend/src/about.html`, `frontend/public/sw.js`_+- 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/src/auth.js`, `frontend/src/auth-new.js`, `frontend/src/include-auth-new.js`, `frontend/src/fix-auth-buttons.js`, `frontend/src/fix-auth-buttons-loader.js`, `frontend/src/registration-status.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 in favor of `frontend/public` copies:- - `frontend/src/js/i18n.js`, `frontend/src/js/i18n-debug.js`, and `frontend/src/js/lib/*` (kept `frontend/public/js` versions)- - Root-level duplicates in `frontend/src/`: `chart.js`, `file-utils.js`, `footer-content.js`, `footer-fix.js`, `mobile-menu.js`, `script.js`, `settings-new.js`, `theme-loader.js`, `version-checker.js`, `auth-redirect.js`, `sw.js`- - Removed unused stylesheet: `frontend/src/styles.css`- - Removed debug files: `frontend/public/js/i18n-debug.js`, `frontend/src/temp-toast-debug.js`+- 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` (Docker builds frontend in-image)+- 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.2 - 2025-10-30diff --git a/Dockerfile b/Dockerfileindex ef8fa08..17df14a 100644--- a/Dockerfile+++ b/Dockerfile@@ -54,17 +54,6 @@ COPY backend/requirements.txt /tmp/requirements.txtRUN pip install --no-cache-dir -r /tmp/requirements.txt-FROM node:20-alpine AS frontend-build--WORKDIR /app/frontend-COPY frontend/package.json frontend/package-lock.json ./-COPY frontend/vite.config.js ./-COPY frontend/public ./public-COPY frontend/src ./src--RUN npm ci --no-audit --no-fund && npm run build--FROM python:3.13-slim-trixie@sha256:079601253d5d25ae095110937ea8cfd7403917b53b077870bccd8b026dc7c42f AS runtimeARG NGINX_VERSION@@ -123,8 +112,8 @@ COPY --chown=warracker:warracker backend/migrations/ ./migrations/COPY --chown=warracker:warracker locales/ ./locales/COPY --chown=warracker:warracker locales/ /var/www/html/locales/-# 4. Frontend (built with Vite)-COPY --chown=warracker:warracker --from=frontend-build /app/frontend/dist/ /var/www/html/+# 4. Frontend (static files, no build step)+COPY --chown=warracker:warracker frontend/ /var/www/html/# 5. Backend (bundled in one instruction)COPY --chown=warracker:warracker backend/ ./backend/diff --git a/frontend/src/about.html b/frontend/about.htmlsimilarity index 94%rename from frontend/src/about.htmlrename to frontend/about.htmlindex 8e0c738..bc4e990 100644--- a/frontend/src/about.html+++ b/frontend/about.html@@ -7,32 +7,33 @@<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="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="./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 src="./script.js?v=20250119001" defer></script>+ <script type="module" src="./js/index.js"></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 {@@ -414,13 +415,13 @@<!-- 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">diff --git a/frontend/src/auth-redirect.html b/frontend/auth-redirect.htmlsimilarity index 92%rename from frontend/src/auth-redirect.htmlrename to frontend/auth-redirect.htmlindex 61fc5bd..6451da3 100644--- a/frontend/src/auth-redirect.html+++ b/frontend/auth-redirect.html@@ -4,10 +4,10 @@<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>+ <script type="module" src="./js/services/authService.js"></script>+ <script type="module" src="./js/services/apiService.js"></script><style>body {display: flex;@@ -161,20 +161,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/public/auth-redirect.js b/frontend/auth-redirect.jssimilarity index 100%rename from frontend/public/auth-redirect.jsrename to frontend/auth-redirect.jsdiff --git a/frontend/public/chart.js b/frontend/chart.jssimilarity index 100%rename from frontend/public/chart.jsrename to frontend/chart.jsdiff --git a/frontend/src/debug-export.html b/frontend/debug-export.htmlsimilarity index 96%rename from frontend/src/debug-export.htmlrename to frontend/debug-export.htmlindex 985327a..ff5413a 100644--- a/frontend/src/debug-export.html+++ b/frontend/debug-export.html@@ -106,14 +106,14 @@</div><!-- i18next Local Scripts -->- <script type="module" src="/js/services/authService.js"></script>- <script type="module" src="/js/services/apiService.js"></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 type="module" src="./js/services/authService.js"></script>+ <script type="module" src="./js/services/apiService.js"></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>let warranties = [];diff --git a/frontend/src/favicon.ico b/frontend/favicon.icosimilarity index 100%rename from frontend/src/favicon.icorename to frontend/favicon.icodiff --git a/frontend/public/file-utils.js b/frontend/file-utils.jssimilarity index 100%rename from frontend/public/file-utils.jsrename to frontend/file-utils.jsdiff --git a/frontend/public/footer-content.js b/frontend/footer-content.jssimilarity index 100%rename from frontend/public/footer-content.jsrename to frontend/footer-content.jsdiff --git a/frontend/public/footer-fix.js b/frontend/footer-fix.jssimilarity index 100%rename from frontend/public/footer-fix.jsrename to frontend/footer-fix.jsdiff --git a/frontend/src/header-fix.css b/frontend/header-fix.csssimilarity index 100%rename from frontend/src/header-fix.cssrename to frontend/header-fix.cssdiff --git a/frontend/src/img/favicon-16x16.png b/frontend/img/favicon-16x16.pngsimilarity index 100%rename from frontend/src/img/favicon-16x16.pngrename to frontend/img/favicon-16x16.pngdiff --git a/frontend/src/img/favicon-32x32.png b/frontend/img/favicon-32x32.pngsimilarity index 100%rename from frontend/src/img/favicon-32x32.pngrename to frontend/img/favicon-32x32.pngdiff --git a/frontend/src/img/favicon-512x512.png b/frontend/img/favicon-512x512.pngsimilarity index 100%rename from frontend/src/img/favicon-512x512.pngrename to frontend/img/favicon-512x512.pngdiff --git a/frontend/src/index.html b/frontend/index.htmlsimilarity index 98%rename from frontend/src/index.htmlrename to frontend/index.htmlindex cf80354..0306769 100644--- a/frontend/src/index.html+++ b/frontend/index.html@@ -2,56 +2,56 @@<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 --><!-- 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 -->+ <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><!-- 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 --><!-- 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>@@ -1337,7 +1337,8 @@</div>- <script src="/script.js?v=20250119002" defer></script>+ <script src="./script.js?v=20250119002" defer></script>+ <script type="module" src="./js/index.js"></script><script>// Lightweight UI logic for Filter/Sort popovers (no change to core logic)document.addEventListener('DOMContentLoaded', function () {@@ -1646,10 +1647,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/js/components/addWarrantyForm.js b/frontend/js/components/addWarrantyForm.jsnew file mode 100644index 0000000..7dc831a--- /dev/null+++ b/frontend/js/components/addWarrantyForm.js@@ -0,0 +1,83 @@+// Add Warranty Form Wizard (compat layer)+// Delegates to existing global implementations to preserve identical behavior.++function callIfExists(fn, ...args) {+ if (typeof fn === 'function') {+ return fn(...args);+ }+}++export function initFormTabs() {+ return callIfExists(window.initFormTabs);+}++export function switchToTab(index) {+ return callIfExists(window.switchToTab, index);+}++export function updateNavigationButtons() {+ return callIfExists(window.updateNavigationButtons);+}++export function updateCompletedTabs() {+ return callIfExists(window.updateCompletedTabs);+}++export function validateTab(tabIndex) {+ return callIfExists(window.validateTab, tabIndex);+}++export function showValidationErrors(tabIndex) {+ return callIfExists(window.showValidationErrors, tabIndex);+}++export function updateSummary() {+ return callIfExists(window.updateSummary);+}++export function handleFormSubmit(event) {+ return callIfExists(window.handleFormSubmit, event);+}++export function resetAddWarrantyWizard() {+ return callIfExists(window.resetAddWarrantyWizard);+}++export function handleLifetimeChange(event) {+ return callIfExists(window.handleLifetimeChange, event);+}++export function handleWarrantyMethodChange() {+ return callIfExists(window.handleWarrantyMethodChange);+}++export function init() {+ // Ensure tab structure initialized if present+ initFormTabs();+ // Wire form submit if form exists+ const form = document.getElementById('addWarrantyForm');+ if (form && !form._awfBound) {+ form.addEventListener('submit', (e) => handleFormSubmit(e));+ form._awfBound = true;+ }+}++// Backward compatibility on window if needed+if (typeof window !== 'undefined') {+ window.addWarrantyForm = {+ init,+ initFormTabs,+ switchToTab,+ updateNavigationButtons,+ updateCompletedTabs,+ validateTab,+ showValidationErrors,+ updateSummary,+ handleFormSubmit,+ resetAddWarrantyWizard,+ handleLifetimeChange,+ handleWarrantyMethodChange+ };+}++diff --git a/frontend/src/js/components/claims.js b/frontend/js/components/claims.jssimilarity index 100%rename from frontend/src/js/components/claims.jsrename to frontend/js/components/claims.jsdiff --git a/frontend/src/js/components/editModal.js b/frontend/js/components/editModal.jssimilarity index 52%rename from frontend/src/js/components/editModal.jsrename to frontend/js/components/editModal.jsindex eff0d44..22e318b 100644--- a/frontend/src/js/components/editModal.js+++ b/frontend/js/components/editModal.js@@ -1,4 +1,5 @@// Edit modal helper components (DOM-based, no innerHTML templates)+import { updateWarranty } from '../services/apiService.js';function createElement(tag, className, text) {const el = document.createElement(tag);@@ -245,7 +246,213 @@ if (typeof window !== 'undefined') {renderCurrentManual,renderCurrentPhoto,renderCurrentOther,+ saveWarranty,};}+// Submit handler for the Edit Warranty modal+export async function saveWarranty() {+ const currentId = typeof window !== 'undefined' ? window.currentWarrantyId : null;+ if (!currentId) {+ if (window && window.showToast) window.showToast(window.t ? window.t('messages.no_warranty_selected_for_update') : 'No warranty selected', 'error');+ return;+ }++ // Gather inputs+ const productName = (document.getElementById('editProductName') || {}).value?.trim() || '';+ const purchaseDate = (document.getElementById('editPurchaseDate') || {}).value || '';+ const isLifetime = !!(document.getElementById('editIsLifetime') || {}).checked;+ const editDurationMethodRadioLocal = document.getElementById('editDurationMethod');+ const isDurationMethod = !!(editDurationMethodRadioLocal && editDurationMethodRadioLocal.checked);+ 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 editExactExpirationDateInputLocal = document.getElementById('editExactExpirationDate');+ const exactDate = editExactExpirationDateInputLocal ? editExactExpirationDateInputLocal.value : '';+ const editWarrantyDurationFieldsLocal = document.getElementById('editWarrantyDurationFields');++ // Basic validation+ if (!productName) {+ if (window && window.showToast) window.showToast(window.t ? window.t('messages.product_name_required') : 'Product name is required', 'error');+ return;+ }+ if (!purchaseDate) {+ if (window && window.showToast) window.showToast(window.t ? window.t('messages.purchase_date_required') : 'Purchase date is required', 'error');+ return;+ }++ // Validation for lifetime/duration/exact date+ if (!isLifetime) {+ if (isDurationMethod) {+ if (years === 0 && months === 0 && days === 0) {+ if (window && window.showToast) window.showToast(window.t ? window.t('messages.warranty_duration_required') : 'Warranty duration is required', 'error');+ const yearsInput = document.getElementById('editWarrantyDurationYears');+ if (yearsInput) {+ yearsInput.focus();+ if (editWarrantyDurationFieldsLocal) editWarrantyDurationFieldsLocal.classList.add('invalid-duration');+ }+ return;+ }+ } else {+ if (!exactDate) {+ if (window && window.showToast) window.showToast(window.t ? window.t('messages.exact_expiration_date_required') : 'Exact expiration date is required', 'error');+ if (editExactExpirationDateInputLocal) editExactExpirationDateInputLocal.focus();+ return;+ }+ if (purchaseDate && exactDate <= purchaseDate) {+ if (window && window.showToast) window.showToast(window.t ? window.t('messages.expiration_date_after_purchase_date') : 'Expiration date must be after purchase date', 'error');+ if (editExactExpirationDateInputLocal) editExactExpirationDateInputLocal.focus();+ return;+ }+ }+ }+ if (editWarrantyDurationFieldsLocal) editWarrantyDurationFieldsLocal.classList.remove('invalid-duration');++ // Build FormData+ const formData = new FormData();+ formData.append('product_name', productName);+ formData.append('purchase_date', purchaseDate);++ 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+ const serialInputs = document.querySelectorAll('#editSerialNumbersContainer input[name="serial_numbers[]"]');+ formData.delete('serial_numbers[]');+ serialInputs.forEach(input => {+ if (input.value && input.value.trim()) formData.append('serial_numbers[]', input.value.trim());+ });++ // Tags+ const editSelectedTags = (typeof window !== 'undefined' && window.editSelectedTags) ? window.editSelectedTags : [];+ formData.append('tag_ids', JSON.stringify(Array.isArray(editSelectedTags) ? editSelectedTags.map(t => t.id) : []));++ // Document URLs+ formData.append('invoice_url', (document.getElementById('editInvoiceUrl') || {}).value || '');+ formData.append('manual_url', (document.getElementById('editManualUrl') || {}).value || '');+ formData.append('other_document_url', (document.getElementById('editOtherDocumentUrl') || {}).value || '');++ // Files+ const invoiceFile = (document.getElementById('editInvoice') || {}).files ? document.getElementById('editInvoice').files[0] : null;+ const manualFile = (document.getElementById('editManual') || {}).files ? document.getElementById('editManual').files[0] : null;+ const otherDocumentFile = (document.getElementById('editOtherDocument') || {}).files ? document.getElementById('editOtherDocument').files[0] : null;+ const productPhotoFile = (document.getElementById('editProductPhoto') || {}).files ? document.getElementById('editProductPhoto').files[0] : null;+ if (invoiceFile) formData.append('invoice', invoiceFile);+ if (manualFile) formData.append('manual', manualFile);+ if (otherDocumentFile) formData.append('other_document', otherDocumentFile);+ if (productPhotoFile) formData.append('product_photo', productPhotoFile);++ // 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');++ // Lifetime/duration+ formData.append('is_lifetime', String(isLifetime));+ if (!isLifetime) {+ if (isDurationMethod) {+ formData.append('warranty_duration_years', years);+ formData.append('warranty_duration_months', months);+ formData.append('warranty_duration_days', days);+ } else {+ formData.append('exact_expiration_date', exactDate);+ formData.append('warranty_duration_years', 0);+ formData.append('warranty_duration_months', 0);+ formData.append('warranty_duration_days', 0);+ }+ } else {+ formData.append('warranty_duration_years', 0);+ formData.append('warranty_duration_months', 0);+ formData.append('warranty_duration_days', 0);+ }++ // Notes and misc fields+ const notes = (document.getElementById('editNotes') || {}).value || '';+ formData.append('notes', notes.trim() !== '' ? notes : '');+ const editModelNumber = document.getElementById('editModelNumber');+ formData.append('model_number', editModelNumber && editModelNumber.value.trim() ? editModelNumber.value.trim() : '');+ const editVendorInput = document.getElementById('editVendor');+ formData.append('vendor', editVendorInput ? (editVendorInput.value || '').trim() : '');+ const editWarrantyTypeInput = document.getElementById('editWarrantyType');+ const editWarrantyTypeCustomInput = document.getElementById('editWarrantyTypeCustom');+ let warrantyTypeValue = '';+ if (editWarrantyTypeInput) {+ warrantyTypeValue = (editWarrantyTypeInput.value === 'other' && editWarrantyTypeCustomInput && editWarrantyTypeCustomInput.value.trim())+ ? editWarrantyTypeCustomInput.value.trim()+ : editWarrantyTypeInput.value.trim();+ }+ formData.append('warranty_type', warrantyTypeValue);++ // Debug logs preserved+ 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);+ for (let [key, value] of formData.entries()) {+ console.log(`[DEBUG saveWarranty] FormData: ${key} = ${value}`);+ }++ if (window && window.showLoadingSpinner) window.showLoadingSpinner();+ try {+ // Paperless uploads pipeline (delegated to legacy/global)+ const uploads = (window && typeof window.processEditPaperlessNgxUploads === 'function')+ ? await window.processEditPaperlessNgxUploads(formData)+ : {};+ Object.keys(uploads || {}).forEach(k => formData.append(k, uploads[k]));++ // Submit update via API service (auto-injects Authorization header)+ await updateWarranty(currentId, formData);++ if (window && window.hideLoadingSpinner) window.hideLoadingSpinner();+ if (window && window.showToast) window.showToast('Warranty updated successfully', 'success');+ if (window && typeof window.closeModals === 'function') window.closeModals();++ // Reload warranties to pick up processed assets/paths+ if (window && window.warrantyListController && typeof window.warrantyListController.loadWarranties === 'function') {+ try {+ await window.warrantyListController.loadWarranties(true);+ if (window && typeof window.applyFilters === 'function') window.applyFilters();+ setTimeout(() => {+ if (window && typeof window.loadSecureImages === 'function') {+ window.loadSecureImages();+ }+ }, 200);+ const notesModal = document.getElementById('notesModal');+ if (notesModal && notesModal.style.display === 'block') notesModal.style.display = 'none';+ // Auto-link paperless docs post-update+ if ((invoiceFile || manualFile || otherDocumentFile) && currentId) {+ setTimeout(() => {+ if (typeof window.autoLinkRecentDocuments === 'function') {+ const fileInfo = {};+ if (invoiceFile) fileInfo.invoice = invoiceFile.name;+ if (manualFile) fileInfo.manual = manualFile.name;+ if (otherDocumentFile) fileInfo.other = otherDocumentFile.name;+ window.autoLinkRecentDocuments(currentId, ['invoice', 'manual', 'other'], 10, 10000, fileInfo);+ }+ }, 3000);+ }+ } catch (e) {+ console.error('Error reloading warranties after edit:', e);+ }+ }+ } catch (error) {+ if (window && window.hideLoadingSpinner) window.hideLoadingSpinner();+ console.error('Error updating warranty:', error);+ if (window && window.showToast) window.showToast(error?.message || 'Failed to update warranty', 'error');+ }+}diff --git a/frontend/src/js/components/modals.js b/frontend/js/components/modals.jssimilarity index 100%rename from frontend/src/js/components/modals.jsrename to frontend/js/components/modals.jsdiff --git a/frontend/src/js/components/notes.js b/frontend/js/components/notes.jssimilarity index 100%rename from frontend/src/js/components/notes.jsrename to frontend/js/components/notes.jsdiff --git a/frontend/src/js/components/paperless.js b/frontend/js/components/paperless.jssimilarity index 100%rename from frontend/src/js/components/paperless.jsrename to frontend/js/components/paperless.jsdiff --git a/frontend/src/js/components/tag.js b/frontend/js/components/tag.jssimilarity index 100%rename from frontend/src/js/components/tag.jsrename to frontend/js/components/tag.jsdiff --git a/frontend/js/components/tagManager.js b/frontend/js/components/tagManager.jsnew file mode 100644index 0000000..0588aaa--- /dev/null+++ b/frontend/js/components/tagManager.js@@ -0,0 +1,95 @@+// Tag Manager (compat layer)+// Encapsulates tag management by delegating to existing global implementations to keep behavior identical.++function callIfExists(fn, ...args) {+ if (typeof fn === 'function') {+ return fn(...args);+ }+}++export function loadTags(force = false) {+ return callIfExists(window.loadTags, force);+}++export function initTagFunctionality() {+ return callIfExists(window.initTagFunctionality);+}++export function renderTagsList(searchTerm = '') {+ return callIfExists(window.renderTagsList, searchTerm);+}++export function renderEditTagsList(searchTerm = '') {+ return callIfExists(window.renderEditTagsList, searchTerm);+}++export function renderSelectedTags() {+ return callIfExists(window.renderSelectedTags);+}++export function renderEditSelectedTags() {+ return callIfExists(window.renderEditSelectedTags);+}++export function createTag(name) {+ return callIfExists(window.createTag, name);+}++export function updateTag(id, name, color) {+ return callIfExists(window.updateTag, id, name, color);+}++export function deleteTag(id) {+ return callIfExists(window.deleteTag, id);+}++export function openTagManagementModal() {+ return callIfExists(window.openTagManagementModal);+}++export function renderExistingTags() {+ return callIfExists(window.renderExistingTags);+}++export function addTagManagementEventListeners() {+ return callIfExists(window.addTagManagementEventListeners);+}++export function init() {+ // Ensure tag functionality on main form if present+ initTagFunctionality();+ // Attach global Manage Tags button if present+ const btn = document.getElementById('globalManageTagsBtn');+ if (btn && !btn._tmBound) {+ btn.addEventListener('click', async (e) => {+ e.preventDefault();+ try {+ await loadTags();+ } finally {+ openTagManagementModal();+ }+ });+ btn._tmBound = true;+ }+}++// Backward compatibility on window+if (typeof window !== 'undefined') {+ window.tagManager = {+ init,+ loadTags,+ initTagFunctionality,+ renderTagsList,+ renderEditTagsList,+ renderSelectedTags,+ renderEditSelectedTags,+ createTag,+ updateTag,+ deleteTag,+ openTagManagementModal,+ renderExistingTags,+ addTagManagementEventListeners+ };+}++diff --git a/frontend/src/js/components/ui.js b/frontend/js/components/ui.jssimilarity index 100%rename from frontend/src/js/components/ui.jsrename to frontend/js/components/ui.jsdiff --git a/frontend/src/js/components/warrantyCard.js b/frontend/js/components/warrantyCard.jssimilarity index 100%rename from frontend/src/js/components/warrantyCard.jsrename to frontend/js/components/warrantyCard.jsdiff --git a/frontend/js/controllers/warrantyListController.js b/frontend/js/controllers/warrantyListController.jsnew file mode 100644index 0000000..b215d49--- /dev/null+++ b/frontend/js/controllers/warrantyListController.js@@ -0,0 +1,622 @@+// Warranty List Controller+// Incremental extraction of main list responsibilities with strict backward compatibility.++function callIfExists(fn, ...args) {+ if (typeof fn === 'function') return fn(...args);+}++// Public API (delegations kept for now until full extraction of implementations)+export async function loadWarranties(isAuthenticated) {+ // Show loading (tolerant to whichever loader exists)+ callIfExists(window.showLoading) || callIfExists(window.showLoadingSpinner);++ try {+ // Ensure view preference is applied BEFORE first render so thumbnails use correct sizes+ callIfExists(window.loadViewPreference);++ const __filters = (window.store && window.store.getFilters && window.store.getFilters()) || {};++ // Check auth state (match legacy behavior)+ if (!isAuthenticated) {+ if (typeof window.i18next !== 'undefined') {+ callIfExists(window.renderEmptyState, window.i18next.t('messages.login_to_view_warranties'));+ } else {+ callIfExists(window.renderEmptyState, 'Please log in to view warranties.');+ }+ return;+ }++ const token = window.auth && window.auth.getToken ? window.auth.getToken() : null;+ if (!token) {+ if (typeof window.i18next !== 'undefined') {+ callIfExists(window.renderEmptyState, window.i18next.t('messages.authentication_error_login_again'));+ } else {+ callIfExists(window.renderEmptyState, 'Authentication error. Please log in again.');+ }+ return;+ }++ // Determine scope and endpoint (mirrors legacy logic)+ const savedScope = callIfExists(window.loadViewScopePreference) || 'personal';+ const shouldUseGlobalView = savedScope === 'global';+ const baseUrl = window.location.origin;+ const isArchivedView = __filters && __filters.status === 'archived';+ const apiUrl = isArchivedView+ ? (shouldUseGlobalView ? `${baseUrl}/api/warranties/global/archived` : `${baseUrl}/api/warranties/archived`)+ : (shouldUseGlobalView ? `${baseUrl}/api/warranties/global` : `${baseUrl}/api/warranties`);++ // Fetch warranties+ const response = await fetch(apiUrl, {+ method: 'GET',+ headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }+ });+ if (!response.ok) {+ let msg = `HTTP ${response.status}`;+ try {+ const j = await response.json();+ if (j && j.message) msg = j.message;+ } catch {}+ throw new Error(msg);+ }+ let data = await response.json();+ if (!Array.isArray(data)) data = [];++ // Keep isGlobalView in sync with loaded scope+ try { if (typeof window.isGlobalView !== 'undefined') window.isGlobalView = shouldUseGlobalView; } catch {}++ // Merge archived when Status=All (mirrors legacy behavior for both scopes)+ let combinedData = Array.isArray(data) ? data : [];+ try {+ // Reset includesArchived flag+ try { if (typeof window.lastLoadedIncludesArchived !== 'undefined') window.lastLoadedIncludesArchived = false; } catch {}+ if (!isArchivedView && __filters && __filters.status === 'all') {+ const archivedUrl = shouldUseGlobalView ? `${baseUrl}/api/warranties/global/archived` : `${baseUrl}/api/warranties/archived`;+ const archivedResp = await fetch(archivedUrl, { headers: { 'Authorization': `Bearer ${token}` } });+ if (archivedResp.ok) {+ const archivedData = await archivedResp.json();+ const archivedMarked = Array.isArray(archivedData) ? archivedData.map(w => ({ ...w, __isArchived: true })) : [];+ combinedData = combinedData.concat(archivedMarked);+ try { if (typeof window.lastLoadedIncludesArchived !== 'undefined') window.lastLoadedIncludesArchived = true; } catch {}+ }+ }+ } catch {}++ // Process warranties using legacy processor if available+ const processed = Array.isArray(combinedData)+ ? combinedData.map(w => {+ const p = callIfExists(window.processWarrantyData, w);+ return p !== undefined ? p : w;+ })+ : [];++ if (window.store && window.store.setWarranties) window.store.setWarranties(processed);++ // Update archived-load flag+ try { if (typeof window.lastLoadedArchived !== 'undefined') window.lastLoadedArchived = !!isArchivedView; } catch {}++ const loaded = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];+ if (loaded.length === 0) {+ if (typeof window.i18next !== 'undefined') {+ callIfExists(window.renderEmptyState, window.i18next.t('messages.no_warranties_found_add_first'));+ } else {+ callIfExists(window.renderEmptyState, 'No warranties yet. Add your first warranty to get started.');+ }+ return;+ }++ // Populate filters and render+ try { populateTagFilter(); } catch {}+ try { populateVendorFilter(); } catch {}+ try { populateWarrantyTypeFilter(); } catch {}++ callIfExists(window.applyFilters) || applyFilters();+ } catch (error) {+ console.error('[controller.loadWarranties] Error:', error);+ if (typeof window.i18next !== 'undefined') {+ callIfExists(window.renderEmptyState, window.i18next.t('messages.error_loading_warranties_try_again'));+ } else {+ callIfExists(window.renderEmptyState, 'Error loading warranties. Please try again.');+ }+ } finally {+ callIfExists(window.hideLoading) || callIfExists(window.hideLoadingSpinner);+ }+}+export function applyFilters() {+ // Mirrors legacy script.js logic to preserve identical behavior+ const __filters = (window.store && window.store.getFilters && window.store.getFilters()) || {};+ const __warranties = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];++ // Ensure data source correctness around archived/all toggles+ const wasArchivedLoaded = !!(window.lastLoadedArchived);+ const includesArchivedLoaded = !!(window.lastLoadedIncludesArchived);+ if (__filters.status === 'archived') {+ if (!wasArchivedLoaded) {+ loadWarranties(true);+ return;+ }+ } else if (wasArchivedLoaded) {+ loadWarranties(true);+ return;+ } else if (__filters.status === 'all' && !includesArchivedLoaded) {+ loadWarranties(true);+ return;+ }++ // Filter warranties based on current filters+ const filtered = __warranties.filter(warranty => {+ // Exclude archived in 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;+ });++ // Preserve legacy behavior: just render (renderWarranties re-applies filters during render)+ renderWarranties();+}+export function renderWarranties() { return callIfExists(window.renderWarranties); }+export function filterWarranties() { return callIfExists(window.filterWarranties); }++// Extracted implementations: dropdown population+export function populateTagFilter() {+ const tagFilter = document.getElementById('tagFilter');+ if (!tagFilter) return;+ while (tagFilter.options.length > 1) tagFilter.remove(1);+ const uniqueTags = new Set();+ const all = ((window.store && window.store.getWarranties && window.store.getWarranties()) || []);+ all.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 })));+ }+ });+ const sortedTags = Array.from(uniqueTags).map(j => JSON.parse(j)).sort((a, b) => a.name.localeCompare(b.name));+ sortedTags.forEach(tag => {+ const option = document.createElement('option');+ option.value = tag.id;+ option.textContent = tag.name;+ tagFilter.appendChild(option);+ });+}++export function populateVendorFilter() {+ const vendorFilterElement = document.getElementById('vendorFilter');+ if (!vendorFilterElement) return;+ while (vendorFilterElement.options.length > 1) vendorFilterElement.remove(1);+ const uniqueVendors = new Set();+ const all = ((window.store && window.store.getWarranties && window.store.getWarranties()) || []);+ all.forEach(warranty => {+ if (warranty.vendor && warranty.vendor.trim() !== '') uniqueVendors.add(warranty.vendor.trim().toLowerCase());+ });+ const sortedVendors = Array.from(uniqueVendors).sort((a, b) => a.localeCompare(b));+ sortedVendors.forEach(vendor => {+ const option = document.createElement('option');+ option.value = vendor;+ option.textContent = vendor.charAt(0).toUpperCase() + vendor.slice(1);+ vendorFilterElement.appendChild(option);+ });+}++export function populateWarrantyTypeFilter() {+ const warrantyTypeFilterElement = document.getElementById('warrantyTypeFilter');+ if (!warrantyTypeFilterElement) return;+ while (warrantyTypeFilterElement.options.length > 1) warrantyTypeFilterElement.remove(1);+ const uniqueTypes = new Set();+ const all = ((window.store && window.store.getWarranties && window.store.getWarranties()) || []);+ all.forEach(warranty => {+ if (warranty.warranty_type && warranty.warranty_type.trim() !== '') uniqueTypes.add(warranty.warranty_type.trim().toLowerCase());+ });+ const sorted = Array.from(uniqueTypes).sort((a, b) => a.localeCompare(b));+ sorted.forEach(type => {+ const option = document.createElement('option');+ option.value = type;+ option.textContent = type.charAt(0).toUpperCase() + type.slice(1);+ warrantyTypeFilterElement.appendChild(option);+ });+}++// Extracted implementations: persist and restore filters/sort+export async function saveFilterPreferences(saveToApi = true) {+ try {+ const prefix = (typeof window.getPreferenceKeyPrefix === 'function') ? window.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'+ };+ localStorage.setItem(`${prefix}warrantyFilters`, JSON.stringify(filtersToSave));++ if (saveToApi && window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {+ const token = window.auth.getToken && window.auth.getToken();+ if (token) {+ try {+ await fetch('/api/auth/preferences', {+ method: 'PUT',+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({ saved_filters: filtersToSave })+ });+ } catch (e) {+ console.error('[Filters] Error saving filter preferences to API:', e);+ }+ }+ }+ } catch (e) {+ console.warn('Failed to save filter preferences', e);+ }+}++export function loadFilterAndSortPreferences() {+ try {+ const prefix = (typeof window.getPreferenceKeyPrefix === 'function') ? window.getPreferenceKeyPrefix() : '';+ const savedFiltersRaw = localStorage.getItem(`${prefix}warrantyFilters`);+ if (!savedFiltersRaw) return;+ const savedFilters = JSON.parse(savedFiltersRaw);+ if (!savedFilters || typeof savedFilters !== 'object') return;++ 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);+ }++ const searchInput = document.getElementById('searchWarranties');+ const clearSearchBtn = document.getElementById('clearSearch');+ if (searchInput && savedFilters.search) {+ searchInput.value = savedFilters.search;+ if (clearSearchBtn) clearSearchBtn.style.display = 'flex';+ if (searchInput.parentElement) searchInput.parentElement.classList.add('active-search');+ }+ } catch (e) {+ console.warn('Failed to load filter/sort preferences', e);+ }+}++// Extracted: setupUIEventListeners -> initEventListeners+export function initEventListeners() {+ // --- Global Manage Tags Button ---+ const globalManageTagsBtn = document.getElementById('globalManageTagsBtn');+ if (globalManageTagsBtn && !globalManageTagsBtn._wlcBound) {+ globalManageTagsBtn.addEventListener('click', async () => {+ const __tags = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];+ if (!__tags || __tags.length === 0) {+ callIfExists(window.showLoadingSpinner);+ try {+ await callIfExists(window.loadTags);+ } catch (error) {+ console.error('Failed to load tags before opening modal:', error);+ callIfExists(window.showToast, window.t ? window.t('messages.could_not_load_tags') : 'Could not load tags', 'error');+ callIfExists(window.hideLoadingSpinner);+ return;+ }+ callIfExists(window.hideLoadingSpinner);+ }+ callIfExists(window.openTagManagementModal);+ });+ globalManageTagsBtn._wlcBound = true;+ }++ // Initialize edit tabs if available+ callIfExists(window.initEditTabs);++ // Close modals on backdrop or dismiss buttons+ document.querySelectorAll('.modal-backdrop, [data-dismiss="modal"]').forEach(element => {+ if (element._wlcBound) return;+ element.addEventListener('click', (e) => {+ if (e.target === element || e.target.matches('[data-dismiss="modal"]')) {+ const modalToClose = e.target.closest('.modal-backdrop');+ if (modalToClose) {+ if ((modalToClose.id === 'addWarrantyModal' || modalToClose.id === 'editModal' || modalToClose.id === 'claimsModal' || modalToClose.id === 'claimFormModal') && e.target === modalToClose) {+ return;+ }+ modalToClose.classList.remove('active');+ if (modalToClose.id === 'editModal') {+ // optional reset area+ } else if (modalToClose.id === 'addWarrantyModal') {+ callIfExists(window.resetAddWarrantyWizard);+ }+ }+ }+ });+ element._wlcBound = true;+ });++ // Prevent modal content clicks from closing the modal+ document.querySelectorAll('.modal').forEach(modal => {+ if (modal._wlcBound) return;+ modal.addEventListener('click', (e) => e.stopPropagation());+ modal._wlcBound = true;+ });++ // Filter controls+ 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');+ const warrantyTypeFilter = document.getElementById('warrantyTypeFilter');++ if (searchInput && !searchInput._wlcBound) {+ let searchDebounceTimeout;+ searchInput.addEventListener('input', () => {+ if (window.store && window.store.updateFilter) window.store.updateFilter('search', searchInput.value.toLowerCase());+ if (clearSearchBtn) clearSearchBtn.style.display = searchInput.value ? 'flex' : 'none';+ if (searchInput.value) {+ searchInput.parentElement.classList.add('active-search');+ } else {+ searchInput.parentElement.classList.remove('active-search');+ }+ if (searchDebounceTimeout) clearTimeout(searchDebounceTimeout);+ searchDebounceTimeout = setTimeout(() => {+ callIfExists(window.applyFilters);+ callIfExists(window.saveFilterPreferences);+ }, 300);+ });+ searchInput._wlcBound = true;+ }++ if (clearSearchBtn && !clearSearchBtn._wlcBound) {+ clearSearchBtn.addEventListener('click', () => {+ if (searchInput) {+ searchInput.value = '';+ if (window.store && window.store.updateFilter) window.store.updateFilter('search', '');+ clearSearchBtn.style.display = 'none';+ searchInput.parentElement.classList.remove('active-search');+ searchInput.focus();+ callIfExists(window.applyFilters);+ callIfExists(window.saveFilterPreferences);+ }+ });+ clearSearchBtn._wlcBound = true;+ }++ if (statusFilter && !statusFilter._wlcBound) {+ statusFilter.addEventListener('change', () => {+ if (window.store && window.store.updateFilter) window.store.updateFilter('status', statusFilter.value);+ callIfExists(window.applyFilters);+ callIfExists(window.saveFilterPreferences);+ });+ statusFilter._wlcBound = true;+ }++ if (tagFilter && !tagFilter._wlcBound) {+ tagFilter.addEventListener('change', () => {+ if (window.store && window.store.updateFilter) window.store.updateFilter('tag', tagFilter.value);+ callIfExists(window.applyFilters);+ callIfExists(window.saveFilterPreferences);+ });+ tagFilter._wlcBound = true;+ }++ if (vendorFilter && !vendorFilter._wlcBound) {+ vendorFilter.addEventListener('change', () => {+ if (window.store && window.store.updateFilter) window.store.updateFilter('vendor', vendorFilter.value);+ callIfExists(window.applyFilters);+ callIfExists(window.saveFilterPreferences);+ });+ vendorFilter._wlcBound = true;+ }++ if (warrantyTypeFilter && !warrantyTypeFilter._wlcBound) {+ warrantyTypeFilter.addEventListener('change', () => {+ if (window.store && window.store.updateFilter) window.store.updateFilter('warranty_type', warrantyTypeFilter.value);+ callIfExists(window.applyFilters);+ callIfExists(window.saveFilterPreferences);+ });+ warrantyTypeFilter._wlcBound = true;+ }++ if (sortBySelect && !sortBySelect._wlcBound) {+ sortBySelect.addEventListener('change', () => {+ if (window.store && window.store.updateFilter) window.store.updateFilter('sortBy', sortBySelect.value);+ callIfExists(window.applyFilters);+ callIfExists(window.saveFilterPreferences);+ });+ sortBySelect._wlcBound = true;+ }++ // View switchers+ const gridViewBtn = document.getElementById('gridViewBtn');+ const listViewBtn = document.getElementById('listViewBtn');+ const tableViewBtn = document.getElementById('tableViewBtn');+ if (gridViewBtn && !gridViewBtn._wlcBound) { gridViewBtn.addEventListener('click', () => callIfExists(window.switchView, 'grid')); gridViewBtn._wlcBound = true; }+ if (listViewBtn && !listViewBtn._wlcBound) { listViewBtn.addEventListener('click', () => callIfExists(window.switchView, 'list')); listViewBtn._wlcBound = true; }+ if (tableViewBtn && !tableViewBtn._wlcBound) { tableViewBtn.addEventListener('click', () => callIfExists(window.switchView, 'table')); tableViewBtn._wlcBound = true; }++ // Export / Import+ const exportBtn = document.getElementById('exportBtn');+ if (exportBtn && !exportBtn._wlcBound) { exportBtn.addEventListener('click', () => callIfExists(window.exportWarranties)); exportBtn._wlcBound = true; }+ const importBtn = document.getElementById('importBtn');+ const csvFileInput = document.getElementById('csvFileInput');+ if (importBtn && csvFileInput && !importBtn._wlcBound) {+ importBtn.addEventListener('click', () => csvFileInput.click());+ csvFileInput.addEventListener('change', (event) => {+ if (event.target.files && event.target.files.length > 0) {+ callIfExists(window.handleImport, event.target.files[0]);+ }+ });+ importBtn._wlcBound = true;+ }++ // Refresh+ const refreshBtn = document.getElementById('refreshBtn');+ if (refreshBtn && !refreshBtn._wlcBound) {+ refreshBtn.addEventListener('click', () => loadWarranties(true));+ refreshBtn._wlcBound = true;+ }++ // Warranty Type custom input handling+ const warrantyTypeInput = document.getElementById('warrantyType');+ const warrantyTypeCustomInput = document.getElementById('warrantyTypeCustom');+ if (warrantyTypeInput && warrantyTypeCustomInput && !warrantyTypeInput._wlcBound) {+ warrantyTypeInput.addEventListener('change', () => {+ if (warrantyTypeInput.value === 'other') {+ warrantyTypeCustomInput.style.display = 'block';+ warrantyTypeCustomInput.focus();+ } else {+ warrantyTypeCustomInput.style.display = 'none';+ warrantyTypeCustomInput.value = '';+ }+ callIfExists(window.updateSummary);+ });+ warrantyTypeCustomInput.addEventListener('input', () => callIfExists(window.updateSummary));+ warrantyTypeInput._wlcBound = true;+ }++ const editWarrantyTypeInput = document.getElementById('editWarrantyType');+ const editWarrantyTypeCustomInput = document.getElementById('editWarrantyTypeCustom');+ if (editWarrantyTypeInput && editWarrantyTypeCustomInput && !editWarrantyTypeInput._wlcBound) {+ editWarrantyTypeInput.addEventListener('change', () => {+ if (editWarrantyTypeInput.value === 'other') {+ editWarrantyTypeCustomInput.style.display = 'block';+ editWarrantyTypeCustomInput.focus();+ } else {+ editWarrantyTypeCustomInput.style.display = 'none';+ editWarrantyTypeCustomInput.value = '';+ }+ });+ editWarrantyTypeInput._wlcBound = true;+ }++ // Save warranty changes+ const saveWarrantyBtn = document.getElementById('saveWarrantyBtn');+ if (saveWarrantyBtn && !saveWarrantyBtn._wlcBound) {+ let baseSave =+ (window.components && window.components.editModal && window.components.editModal.saveWarranty)+ ? window.components.editModal.saveWarranty+ : window.saveWarranty;+ let functionToAttachOnClick = baseSave;+ if (typeof window.setupSaveWarrantyObserver === 'function') {+ try {+ functionToAttachOnClick = window.setupSaveWarrantyObserver(baseSave);+ window.saveWarrantyObserverAttachedByScriptJS = true;+ } catch (e) {+ console.error('[warrantyListController] Failed to wrap saveWarranty:', e);+ }+ }+ saveWarrantyBtn.addEventListener('click', () => {+ if (typeof functionToAttachOnClick === 'function') functionToAttachOnClick();+ });+ saveWarrantyBtn._wlcBound = true;+ }++ // Confirm delete/archive+ const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');+ if (confirmDeleteBtn && !confirmDeleteBtn._wlcBound) { confirmDeleteBtn.addEventListener('click', () => callIfExists(window.deleteWarranty)); confirmDeleteBtn._wlcBound = true; }+ const confirmArchiveBtn = document.getElementById('confirmArchiveBtn');+ if (confirmArchiveBtn && !confirmArchiveBtn._wlcBound) { confirmArchiveBtn.addEventListener('click', () => callIfExists(window.confirmArchive)); confirmArchiveBtn._wlcBound = true; }++ // List delegated events (claims/edit/delete/notes/archive/unarchive) - controller owns this exclusively+ const list = document.getElementById('warrantiesList');+ if (list && !list._wlcDelegated) {+ list.addEventListener('click', (e) => {+ if (e.target.closest('.claims-link')) {+ e.preventDefault();+ const id = parseInt(e.target.closest('.claims-link')?.dataset?.id);+ if (typeof window.openClaimsModal === 'function' && id) window.openClaimsModal(id);+ return;+ }+ if (e.target.closest('.edit-btn')) {+ e.preventDefault();+ const el = e.target.closest('.edit-btn');+ if (el?.disabled) return;+ const id = parseInt(el?.dataset?.id);+ const warranty = ((window.store && window.store.getWarranties && window.store.getWarranties()) || []).find(w => w.id === id);+ if (warranty && typeof window.openEditModal === 'function') window.openEditModal(warranty);+ return;+ }+ if (e.target.closest('.delete-btn')) {+ e.preventDefault();+ const el = e.target.closest('.delete-btn');+ const id = 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() : '';+ if (typeof window.openDeleteModal === 'function') window.openDeleteModal(id, productName);+ return;+ }+ if (e.target.closest('.notes-link')) {+ e.preventDefault();+ const el = e.target.closest('.notes-link');+ const id = parseInt(el?.dataset?.id);+ const warranty = ((window.store && window.store.getWarranties && window.store.getWarranties()) || []).find(w => w.id === id);+ if (warranty && typeof window.showNotesModal === 'function') window.showNotesModal(warranty.notes, warranty);+ return;+ }+ if (e.target.closest('.archive-btn')) {+ e.preventDefault();+ const el = e.target.closest('.archive-btn');+ const id = 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() : '';+ if (typeof window.openArchiveModal === 'function') window.openArchiveModal(id, productName);+ return;+ }+ if (e.target.closest('.unarchive-btn')) {+ e.preventDefault();+ const id = parseInt(e.target.closest('.unarchive-btn')?.dataset?.id);+ if (typeof window.toggleArchiveStatus === 'function' && id) window.toggleArchiveStatus(id, false);+ return;+ }+ });+ list._wlcDelegated = true;+ }+}++// Backward compatibility for legacy callers+if (typeof window !== 'undefined') {+ window.warrantyListController = {+ loadWarranties,+ applyFilters,+ renderWarranties,+ filterWarranties,+ populateTagFilter,+ populateVendorFilter,+ populateWarrantyTypeFilter,+ saveFilterPreferences,+ loadFilterAndSortPreferences,+ initEventListeners+ };+ // Legacy globals to avoid breaking existing references during staged extraction+ window.populateTagFilter = populateTagFilter;+ window.populateVendorFilter = populateVendorFilter;+ window.populateWarrantyTypeFilter = populateWarrantyTypeFilter;+ window.saveFilterPreferences = saveFilterPreferences;+ window.loadFilterAndSortPreferences = loadFilterAndSortPreferences;+}++export const init = initEventListeners;++diff --git a/frontend/public/js/i18n.js b/frontend/js/i18n.jssimilarity index 100%rename from frontend/public/js/i18n.jsrename to frontend/js/i18n.jsdiff --git a/frontend/js/index.js b/frontend/js/index.jsnew file mode 100644index 0000000..3b3b763--- /dev/null+++ b/frontend/js/index.js@@ -0,0 +1,25 @@+// Main Application Entry Point+import authService from './services/authService.js';+import { init as initListController, loadWarranties } from './controllers/warrantyListController.js';+import { init as initTagManager } from './components/tagManager.js';+import { init as initAddForm } from './components/addWarrantyForm.js';++// Initialize auth first (idempotent; authService also auto-inits on DOMContentLoaded)+document.addEventListener('DOMContentLoaded', () => {+ authService.initAuth();+});++// Wait for authentication to be confirmed before loading protected data and initializing auth-dependent modules+window.addEventListener('authStateReady', (event) => {+ if (event.detail && event.detail.isAuthenticated) {+ // Initialize all feature modules+ initListController();+ initTagManager();+ initAddForm();++ // Trigger the initial data load for the application+ loadWarranties(true);+ }+});++diff --git a/frontend/public/js/lib/i18next.min.js b/frontend/js/lib/i18next.min.jssimilarity index 100%rename from frontend/public/js/lib/i18next.min.jsrename to frontend/js/lib/i18next.min.jsdiff --git a/frontend/public/js/lib/i18nextBrowserLanguageDetector.min.js b/frontend/js/lib/i18nextBrowserLanguageDetector.min.jssimilarity index 100%rename from frontend/public/js/lib/i18nextBrowserLanguageDetector.min.jsrename to frontend/js/lib/i18nextBrowserLanguageDetector.min.jsdiff --git a/frontend/public/js/lib/i18nextHttpBackend.min.js b/frontend/js/lib/i18nextHttpBackend.min.jssimilarity index 100%rename from frontend/public/js/lib/i18nextHttpBackend.min.jsrename to frontend/js/lib/i18nextHttpBackend.min.jsdiff --git a/frontend/src/js/services/apiService.js b/frontend/js/services/apiService.jssimilarity index 58%rename from frontend/src/js/services/apiService.jsrename to frontend/js/services/apiService.jsindex 178706f..7c59f15 100644--- a/frontend/src/js/services/apiService.js+++ b/frontend/js/services/apiService.js@@ -1,4 +1,4 @@-import authService from '/js/services/authService.js';+import authService from './authService.js';async function baseRequest(path, options = {}) {const headers = new Headers(options.headers || {});@@ -48,6 +48,60 @@ export async function getStatistics() {return res.json();}+// --- Settings & Admin endpoints ---+export async function getUser() {+ const res = await baseRequest('/api/auth/user');+ return res.json();+}++export async function getSiteSettings() {+ const res = await baseRequest('/api/admin/settings');+ return res.json();+}++export async function saveSiteSettings(settings) {+ const res = await baseRequest('/api/admin/settings', {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(settings),+ });+ return res.json();+}++export async function getUsers() {+ const res = await baseRequest('/api/admin/users');+ return res.json();+}++export async function updateUser(userId, data) {+ const res = await baseRequest(`/api/admin/users/${userId}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(data),+ });+ return res.json();+}++export async function deleteUser(userId) {+ await baseRequest(`/api/admin/users/${userId}`, { method: 'DELETE' });+ return true;+}++export async function getAuditTrail() {+ const res = await baseRequest('/api/admin/audit-trail');+ return res.json();+}++export async function triggerNotifications() {+ const res = await baseRequest('/api/admin/send-notifications', { method: 'POST' });+ return res.json();+}++// Generic request helper for arbitrary endpoints+export async function request(path, options = {}) {+ return baseRequest(path, options);+}+export async function savePreferences(prefs) {const res = await baseRequest('/api/auth/preferences', {method: 'POST',@@ -81,7 +135,17 @@ if (typeof window !== 'undefined') {updateWarranty,deleteWarranty,getStatistics,+ request,savePreferences,+ // settings & admin+ getUser,+ getSiteSettings,+ saveSiteSettings,+ getUsers,+ updateUser,+ deleteUser,+ getAuditTrail,+ triggerNotifications,};}@@ -90,7 +154,17 @@ export default {updateWarranty,deleteWarranty,getStatistics,+ request,savePreferences,+ // settings & admin+ getUser,+ getSiteSettings,+ saveSiteSettings,+ getUsers,+ updateUser,+ deleteUser,+ getAuditTrail,+ triggerNotifications,};diff --git a/frontend/src/js/services/authService.js b/frontend/js/services/authService.jssimilarity index 100%rename from frontend/src/js/services/authService.jsrename to frontend/js/services/authService.jsdiff --git a/frontend/js/services/i18nAdapter.js b/frontend/js/services/i18nAdapter.jsnew file mode 100644index 0000000..634195a--- /dev/null+++ b/frontend/js/services/i18nAdapter.js@@ -0,0 +1,20 @@+// Small adapter to provide a stable i18n interface for modules.+// It prefers a global `window.i18next` (loaded via non-module scripts),+// but keeps a safe fallback API so callers can import this module.+const i18nAdapter = {+ t: (...args) => {+ if (typeof window !== 'undefined' && window.i18next && typeof window.i18next.t === 'function') return window.i18next.t(...args);+ // fallback: return default or key+ return args[1] || args[0] || '';+ },+ changeLanguage: (lang) => {+ if (typeof window !== 'undefined' && window.i18next && typeof window.i18next.changeLanguage === 'function') return window.i18next.changeLanguage(lang);+ return Promise.resolve();+ },+ getCurrentLanguage: () => {+ if (typeof window !== 'undefined' && window.i18next && window.i18next.language) return window.i18next.language;+ return 'en';+ }+};++export default i18nAdapter;diff --git a/frontend/src/js/store.js b/frontend/js/store.jssimilarity index 100%rename from frontend/src/js/store.jsrename to frontend/js/store.jsdiff --git a/frontend/src/login.html b/frontend/login.htmlsimilarity index 93%rename from frontend/src/login.htmlrename to frontend/login.htmlindex 5750120..2c5c641 100644--- a/frontend/src/login.html+++ b/frontend/login.html@@ -1,19 +1,19 @@<!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 type="module" src="./js/services/authService.js"></script>+ <script type="module" src="./js/services/apiService.js"></script><script>// If user is authenticated and has a theme in user_info (from previous sessions), reflect it earlytry {@@ -24,10 +24,10 @@} 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></head>@@ -84,7 +84,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>diff --git a/frontend/src/manifest.json b/frontend/manifest.jsonsimilarity index 100%rename from frontend/src/manifest.jsonrename to frontend/manifest.jsondiff --git a/frontend/src/mobile-header.css b/frontend/mobile-header.csssimilarity index 100%rename from frontend/src/mobile-header.cssrename to frontend/mobile-header.cssdiff --git a/frontend/public/mobile-menu.js b/frontend/mobile-menu.jssimilarity index 100%rename from frontend/public/mobile-menu.jsrename to frontend/mobile-menu.jsdiff --git a/frontend/package-lock.json b/frontend/package-lock.jsondeleted file mode 100644index 4579c58..0000000--- a/frontend/package-lock.json+++ /dev/null@@ -1,1061 +0,0 @@-{- "name": "frontend",- "version": "1.0.0",- "lockfileVersion": 3,- "requires": true,- "packages": {- "": {- "name": "frontend",- "version": "1.0.0",- "license": "ISC",- "devDependencies": {- "vite": "^7.1.12"- }- },- "node_modules/@esbuild/aix-ppc64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.11.tgz",- "integrity": "sha512-Xt1dOL13m8u0WE8iplx9Ibbm+hFAO0GsU2P34UNoDGvZYkY8ifSiy6Zuc1lYxfG7svWE2fzqCUmFp5HCn51gJg==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "aix"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/android-arm": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.11.tgz",- "integrity": "sha512-uoa7dU+Dt3HYsethkJ1k6Z9YdcHjTrSb5NUy66ZfZaSV8hEYGD5ZHbEMXnqLFlbBflLsl89Zke7CAdDJ4JI+Gg==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/android-arm64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.11.tgz",- "integrity": "sha512-9slpyFBc4FPPz48+f6jyiXOx/Y4v34TUeDDXJpZqAWQn/08lKGeD8aDp9TMn9jDz2CiEuHwfhRmGBvpnd/PWIQ==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/android-x64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.11.tgz",- "integrity": "sha512-Sgiab4xBjPU1QoPEIqS3Xx+R2lezu0LKIEcYe6pftr56PqPygbB7+szVnzoShbx64MUupqoE0KyRlN7gezbl8g==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/darwin-arm64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.11.tgz",- "integrity": "sha512-VekY0PBCukppoQrycFxUqkCojnTQhdec0vevUL/EDOCnXd9LKWqD/bHwMPzigIJXPhC59Vd1WFIL57SKs2mg4w==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/darwin-x64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.11.tgz",- "integrity": "sha512-+hfp3yfBalNEpTGp9loYgbknjR695HkqtY3d3/JjSRUyPg/xd6q+mQqIb5qdywnDxRZykIHs3axEqU6l1+oWEQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/freebsd-arm64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.11.tgz",- "integrity": "sha512-CmKjrnayyTJF2eVuO//uSjl/K3KsMIeYeyN7FyDBjsR3lnSJHaXlVoAK8DZa7lXWChbuOk7NjAc7ygAwrnPBhA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/freebsd-x64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.11.tgz",- "integrity": "sha512-Dyq+5oscTJvMaYPvW3x3FLpi2+gSZTCE/1ffdwuM6G1ARang/mb3jvjxs0mw6n3Lsw84ocfo9CrNMqc5lTfGOw==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-arm": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.11.tgz",- "integrity": "sha512-TBMv6B4kCfrGJ8cUPo7vd6NECZH/8hPpBHHlYI3qzoYFvWu2AdTvZNuU/7hsbKWqu/COU7NIK12dHAAqBLLXgw==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-arm64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.11.tgz",- "integrity": "sha512-Qr8AzcplUhGvdyUF08A1kHU3Vr2O88xxP0Tm8GcdVOUm25XYcMPp2YqSVHbLuXzYQMf9Bh/iKx7YPqECs6ffLA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-ia32": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.11.tgz",- "integrity": "sha512-TmnJg8BMGPehs5JKrCLqyWTVAvielc615jbkOirATQvWWB1NMXY77oLMzsUjRLa0+ngecEmDGqt5jiDC6bfvOw==",- "cpu": [- "ia32"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-loong64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.11.tgz",- "integrity": "sha512-DIGXL2+gvDaXlaq8xruNXUJdT5tF+SBbJQKbWy/0J7OhU8gOHOzKmGIlfTTl6nHaCOoipxQbuJi7O++ldrxgMw==",- "cpu": [- "loong64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-mips64el": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.11.tgz",- "integrity": "sha512-Osx1nALUJu4pU43o9OyjSCXokFkFbyzjXb6VhGIJZQ5JZi8ylCQ9/LFagolPsHtgw6himDSyb5ETSfmp4rpiKQ==",- "cpu": [- "mips64el"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-ppc64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.11.tgz",- "integrity": "sha512-nbLFgsQQEsBa8XSgSTSlrnBSrpoWh7ioFDUmwo158gIm5NNP+17IYmNWzaIzWmgCxq56vfr34xGkOcZ7jX6CPw==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-riscv64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.11.tgz",- "integrity": "sha512-HfyAmqZi9uBAbgKYP1yGuI7tSREXwIb438q0nqvlpxAOs3XnZ8RsisRfmVsgV486NdjD7Mw2UrFSw51lzUk1ww==",- "cpu": [- "riscv64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-s390x": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.11.tgz",- "integrity": "sha512-HjLqVgSSYnVXRisyfmzsH6mXqyvj0SA7pG5g+9W7ESgwA70AXYNpfKBqh1KbTxmQVaYxpzA/SvlB9oclGPbApw==",- "cpu": [- "s390x"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/linux-x64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.11.tgz",- "integrity": "sha512-HSFAT4+WYjIhrHxKBwGmOOSpphjYkcswF449j6EjsjbinTZbp8PJtjsVK1XFJStdzXdy/jaddAep2FGY+wyFAQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/netbsd-arm64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.11.tgz",- "integrity": "sha512-hr9Oxj1Fa4r04dNpWr3P8QKVVsjQhqrMSUzZzf+LZcYjZNqhA3IAfPQdEh1FLVUJSiu6sgAwp3OmwBfbFgG2Xg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "netbsd"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/netbsd-x64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.11.tgz",- "integrity": "sha512-u7tKA+qbzBydyj0vgpu+5h5AeudxOAGncb8N6C9Kh1N4n7wU1Xw1JDApsRjpShRpXRQlJLb9wY28ELpwdPcZ7A==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "netbsd"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/openbsd-arm64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.11.tgz",- "integrity": "sha512-Qq6YHhayieor3DxFOoYM1q0q1uMFYb7cSpLD2qzDSvK1NAvqFi8Xgivv0cFC6J+hWVw2teCYltyy9/m/14ryHg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openbsd"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/openbsd-x64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.11.tgz",- "integrity": "sha512-CN+7c++kkbrckTOz5hrehxWN7uIhFFlmS/hqziSFVWpAzpWrQoAG4chH+nN3Be+Kzv/uuo7zhX716x3Sn2Jduw==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openbsd"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/openharmony-arm64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.11.tgz",- "integrity": "sha512-rOREuNIQgaiR+9QuNkbkxubbp8MSO9rONmwP5nKncnWJ9v5jQ4JxFnLu4zDSRPf3x4u+2VN4pM4RdyIzDty/wQ==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openharmony"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/sunos-x64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.11.tgz",- "integrity": "sha512-nq2xdYaWxyg9DcIyXkZhcYulC6pQ2FuCgem3LI92IwMgIZ69KHeY8T4Y88pcwoLIjbed8n36CyKoYRDygNSGhA==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "sunos"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/win32-arm64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.11.tgz",- "integrity": "sha512-3XxECOWJq1qMZ3MN8srCJ/QfoLpL+VaxD/WfNRm1O3B4+AZ/BnLVgFbUV3eiRYDMXetciH16dwPbbHqwe1uU0Q==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/win32-ia32": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.11.tgz",- "integrity": "sha512-3ukss6gb9XZ8TlRyJlgLn17ecsK4NSQTmdIXRASVsiS2sQ6zPPZklNJT5GR5tE/MUarymmy8kCEf5xPCNCqVOA==",- "cpu": [- "ia32"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@esbuild/win32-x64": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.11.tgz",- "integrity": "sha512-D7Hpz6A2L4hzsRpPaCYkQnGOotdUpDzSGRIv9I+1ITdHROSFUWW95ZPZWQmGka1Fg7W3zFJowyn9WGwMJ0+KPA==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@rollup/rollup-android-arm-eabi": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.52.5.tgz",- "integrity": "sha512-8c1vW4ocv3UOMp9K+gToY5zL2XiiVw3k7f1ksf4yO1FlDFQ1C2u72iACFnSOceJFsWskc2WZNqeRhFRPzv+wtQ==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ]- },- "node_modules/@rollup/rollup-android-arm64": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.52.5.tgz",- "integrity": "sha512-mQGfsIEFcu21mvqkEKKu2dYmtuSZOBMmAl5CFlPGLY94Vlcm+zWApK7F/eocsNzp8tKmbeBP8yXyAbx0XHsFNA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ]- },- "node_modules/@rollup/rollup-darwin-arm64": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.52.5.tgz",- "integrity": "sha512-takF3CR71mCAGA+v794QUZ0b6ZSrgJkArC+gUiG6LB6TQty9T0Mqh3m2ImRBOxS2IeYBo4lKWIieSvnEk2OQWA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ]- },- "node_modules/@rollup/rollup-darwin-x64": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.52.5.tgz",- "integrity": "sha512-W901Pla8Ya95WpxDn//VF9K9u2JbocwV/v75TE0YIHNTbhqUTv9w4VuQ9MaWlNOkkEfFwkdNhXgcLqPSmHy0fA==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ]- },- "node_modules/@rollup/rollup-freebsd-arm64": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.52.5.tgz",- "integrity": "sha512-QofO7i7JycsYOWxe0GFqhLmF6l1TqBswJMvICnRUjqCx8b47MTo46W8AoeQwiokAx3zVryVnxtBMcGcnX12LvA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ]- },- "node_modules/@rollup/rollup-freebsd-x64": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.52.5.tgz",- "integrity": "sha512-jr21b/99ew8ujZubPo9skbrItHEIE50WdV86cdSoRkKtmWa+DDr6fu2c/xyRT0F/WazZpam6kk7IHBerSL7LDQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ]- },- "node_modules/@rollup/rollup-linux-arm-gnueabihf": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.52.5.tgz",- "integrity": "sha512-PsNAbcyv9CcecAUagQefwX8fQn9LQ4nZkpDboBOttmyffnInRy8R8dSg6hxxl2Re5QhHBf6FYIDhIj5v982ATQ==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-arm-musleabihf": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.52.5.tgz",- "integrity": "sha512-Fw4tysRutyQc/wwkmcyoqFtJhh0u31K+Q6jYjeicsGJJ7bbEq8LwPWV/w0cnzOqR2m694/Af6hpFayLJZkG2VQ==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-arm64-gnu": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.52.5.tgz",- "integrity": "sha512-a+3wVnAYdQClOTlyapKmyI6BLPAFYs0JM8HRpgYZQO02rMR09ZcV9LbQB+NL6sljzG38869YqThrRnfPMCDtZg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-arm64-musl": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.52.5.tgz",- "integrity": "sha512-AvttBOMwO9Pcuuf7m9PkC1PUIKsfaAJ4AYhy944qeTJgQOqJYJ9oVl2nYgY7Rk0mkbsuOpCAYSs6wLYB2Xiw0Q==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-loong64-gnu": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.52.5.tgz",- "integrity": "sha512-DkDk8pmXQV2wVrF6oq5tONK6UHLz/XcEVow4JTTerdeV1uqPeHxwcg7aFsfnSm9L+OO8WJsWotKM2JJPMWrQtA==",- "cpu": [- "loong64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-ppc64-gnu": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.52.5.tgz",- "integrity": "sha512-W/b9ZN/U9+hPQVvlGwjzi+Wy4xdoH2I8EjaCkMvzpI7wJUs8sWJ03Rq96jRnHkSrcHTpQe8h5Tg3ZzUPGauvAw==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-riscv64-gnu": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.52.5.tgz",- "integrity": "sha512-sjQLr9BW7R/ZiXnQiWPkErNfLMkkWIoCz7YMn27HldKsADEKa5WYdobaa1hmN6slu9oWQbB6/jFpJ+P2IkVrmw==",- "cpu": [- "riscv64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-riscv64-musl": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.52.5.tgz",- "integrity": "sha512-hq3jU/kGyjXWTvAh2awn8oHroCbrPm8JqM7RUpKjalIRWWXE01CQOf/tUNWNHjmbMHg/hmNCwc/Pz3k1T/j/Lg==",- "cpu": [- "riscv64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-s390x-gnu": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.52.5.tgz",- "integrity": "sha512-gn8kHOrku8D4NGHMK1Y7NA7INQTRdVOntt1OCYypZPRt6skGbddska44K8iocdpxHTMMNui5oH4elPH4QOLrFQ==",- "cpu": [- "s390x"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-x64-gnu": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.52.5.tgz",- "integrity": "sha512-hXGLYpdhiNElzN770+H2nlx+jRog8TyynpTVzdlc6bndktjKWyZyiCsuDAlpd+j+W+WNqfcyAWz9HxxIGfZm1Q==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-x64-musl": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.52.5.tgz",- "integrity": "sha512-arCGIcuNKjBoKAXD+y7XomR9gY6Mw7HnFBv5Rw7wQRvwYLR7gBAgV7Mb2QTyjXfTveBNFAtPt46/36vV9STLNg==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-openharmony-arm64": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.52.5.tgz",- "integrity": "sha512-QoFqB6+/9Rly/RiPjaomPLmR/13cgkIGfA40LHly9zcH1S0bN2HVFYk3a1eAyHQyjs3ZJYlXvIGtcCs5tko9Cw==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openharmony"- ]- },- "node_modules/@rollup/rollup-win32-arm64-msvc": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.52.5.tgz",- "integrity": "sha512-w0cDWVR6MlTstla1cIfOGyl8+qb93FlAVutcor14Gf5Md5ap5ySfQ7R9S/NjNaMLSFdUnKGEasmVnu3lCMqB7w==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ]- },- "node_modules/@rollup/rollup-win32-ia32-msvc": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.52.5.tgz",- "integrity": "sha512-Aufdpzp7DpOTULJCuvzqcItSGDH73pF3ko/f+ckJhxQyHtp67rHw3HMNxoIdDMUITJESNE6a8uh4Lo4SLouOUg==",- "cpu": [- "ia32"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ]- },- "node_modules/@rollup/rollup-win32-x64-gnu": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.52.5.tgz",- "integrity": "sha512-UGBUGPFp1vkj6p8wCRraqNhqwX/4kNQPS57BCFc8wYh0g94iVIW33wJtQAx3G7vrjjNtRaxiMUylM0ktp/TRSQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ]- },- "node_modules/@rollup/rollup-win32-x64-msvc": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.52.5.tgz",- "integrity": "sha512-TAcgQh2sSkykPRWLrdyy2AiceMckNf5loITqXxFI5VuQjS5tSuw3WlwdN8qv8vzjLAUTvYaH/mVjSFpbkFbpTg==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ]- },- "node_modules/@types/estree": {- "version": "1.0.8",- "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",- "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",- "dev": true,- "license": "MIT"- },- "node_modules/esbuild": {- "version": "0.25.11",- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.11.tgz",- "integrity": "sha512-KohQwyzrKTQmhXDW1PjCv3Tyspn9n5GcY2RTDqeORIdIJY8yKIF7sTSopFmn/wpMPW4rdPXI0UE5LJLuq3bx0Q==",- "dev": true,- "hasInstallScript": true,- "license": "MIT",- "bin": {- "esbuild": "bin/esbuild"- },- "engines": {- "node": ">=18"- },- "optionalDependencies": {- "@esbuild/aix-ppc64": "0.25.11",- "@esbuild/android-arm": "0.25.11",- "@esbuild/android-arm64": "0.25.11",- "@esbuild/android-x64": "0.25.11",- "@esbuild/darwin-arm64": "0.25.11",- "@esbuild/darwin-x64": "0.25.11",- "@esbuild/freebsd-arm64": "0.25.11",- "@esbuild/freebsd-x64": "0.25.11",- "@esbuild/linux-arm": "0.25.11",- "@esbuild/linux-arm64": "0.25.11",- "@esbuild/linux-ia32": "0.25.11",- "@esbuild/linux-loong64": "0.25.11",- "@esbuild/linux-mips64el": "0.25.11",- "@esbuild/linux-ppc64": "0.25.11",- "@esbuild/linux-riscv64": "0.25.11",- "@esbuild/linux-s390x": "0.25.11",- "@esbuild/linux-x64": "0.25.11",- "@esbuild/netbsd-arm64": "0.25.11",- "@esbuild/netbsd-x64": "0.25.11",- "@esbuild/openbsd-arm64": "0.25.11",- "@esbuild/openbsd-x64": "0.25.11",- "@esbuild/openharmony-arm64": "0.25.11",- "@esbuild/sunos-x64": "0.25.11",- "@esbuild/win32-arm64": "0.25.11",- "@esbuild/win32-ia32": "0.25.11",- "@esbuild/win32-x64": "0.25.11"- }- },- "node_modules/fdir": {- "version": "6.5.0",- "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",- "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=12.0.0"- },- "peerDependencies": {- "picomatch": "^3 || ^4"- },- "peerDependenciesMeta": {- "picomatch": {- "optional": true- }- }- },- "node_modules/fsevents": {- "version": "2.3.3",- "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",- "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",- "dev": true,- "hasInstallScript": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": "^8.16.0 || ^10.6.0 || >=11.0.0"- }- },- "node_modules/nanoid": {- "version": "3.3.11",- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",- "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",- "dev": true,- "funding": [- {- "type": "github",- "url": "https://github.com/sponsors/ai"- }- ],- "license": "MIT",- "bin": {- "nanoid": "bin/nanoid.cjs"- },- "engines": {- "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"- }- },- "node_modules/picocolors": {- "version": "1.1.1",- "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",- "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",- "dev": true,- "license": "ISC"- },- "node_modules/picomatch": {- "version": "4.0.3",- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",- "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",- "dev": true,- "license": "MIT",- "peer": true,- "engines": {- "node": ">=12"- },- "funding": {- "url": "https://github.com/sponsors/jonschlinkert"- }- },- "node_modules/postcss": {- "version": "8.5.6",- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",- "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",- "dev": true,- "funding": [- {- "type": "opencollective",- "url": "https://opencollective.com/postcss/"- },- {- "type": "tidelift",- "url": "https://tidelift.com/funding/github/npm/postcss"- },- {- "type": "github",- "url": "https://github.com/sponsors/ai"- }- ],- "license": "MIT",- "dependencies": {- "nanoid": "^3.3.11",- "picocolors": "^1.1.1",- "source-map-js": "^1.2.1"- },- "engines": {- "node": "^10 || ^12 || >=14"- }- },- "node_modules/rollup": {- "version": "4.52.5",- "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.52.5.tgz",- "integrity": "sha512-3GuObel8h7Kqdjt0gxkEzaifHTqLVW56Y/bjN7PSQtkKr0w3V/QYSdt6QWYtd7A1xUtYQigtdUfgj1RvWVtorw==",- "dev": true,- "license": "MIT",- "dependencies": {- "@types/estree": "1.0.8"- },- "bin": {- "rollup": "dist/bin/rollup"- },- "engines": {- "node": ">=18.0.0",- "npm": ">=8.0.0"- },- "optionalDependencies": {- "@rollup/rollup-android-arm-eabi": "4.52.5",- "@rollup/rollup-android-arm64": "4.52.5",- "@rollup/rollup-darwin-arm64": "4.52.5",- "@rollup/rollup-darwin-x64": "4.52.5",- "@rollup/rollup-freebsd-arm64": "4.52.5",- "@rollup/rollup-freebsd-x64": "4.52.5",- "@rollup/rollup-linux-arm-gnueabihf": "4.52.5",- "@rollup/rollup-linux-arm-musleabihf": "4.52.5",- "@rollup/rollup-linux-arm64-gnu": "4.52.5",- "@rollup/rollup-linux-arm64-musl": "4.52.5",- "@rollup/rollup-linux-loong64-gnu": "4.52.5",- "@rollup/rollup-linux-ppc64-gnu": "4.52.5",- "@rollup/rollup-linux-riscv64-gnu": "4.52.5",- "@rollup/rollup-linux-riscv64-musl": "4.52.5",- "@rollup/rollup-linux-s390x-gnu": "4.52.5",- "@rollup/rollup-linux-x64-gnu": "4.52.5",- "@rollup/rollup-linux-x64-musl": "4.52.5",- "@rollup/rollup-openharmony-arm64": "4.52.5",- "@rollup/rollup-win32-arm64-msvc": "4.52.5",- "@rollup/rollup-win32-ia32-msvc": "4.52.5",- "@rollup/rollup-win32-x64-gnu": "4.52.5",- "@rollup/rollup-win32-x64-msvc": "4.52.5",- "fsevents": "~2.3.2"- }- },- "node_modules/source-map-js": {- "version": "1.2.1",- "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",- "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",- "dev": true,- "license": "BSD-3-Clause",- "engines": {- "node": ">=0.10.0"- }- },- "node_modules/tinyglobby": {- "version": "0.2.15",- "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",- "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",- "dev": true,- "license": "MIT",- "dependencies": {- "fdir": "^6.5.0",- "picomatch": "^4.0.3"- },- "engines": {- "node": ">=12.0.0"- },- "funding": {- "url": "https://github.com/sponsors/SuperchupuDev"- }- },- "node_modules/vite": {- "version": "7.1.12",- "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.12.tgz",- "integrity": "sha512-ZWyE8YXEXqJrrSLvYgrRP7p62OziLW7xI5HYGWFzOvupfAlrLvURSzv/FyGyy0eidogEM3ujU+kUG1zuHgb6Ug==",- "dev": true,- "license": "MIT",- "dependencies": {- "esbuild": "^0.25.0",- "fdir": "^6.5.0",- "picomatch": "^4.0.3",- "postcss": "^8.5.6",- "rollup": "^4.43.0",- "tinyglobby": "^0.2.15"- },- "bin": {- "vite": "bin/vite.js"- },- "engines": {- "node": "^20.19.0 || >=22.12.0"- },- "funding": {- "url": "https://github.com/vitejs/vite?sponsor=1"- },- "optionalDependencies": {- "fsevents": "~2.3.3"- },- "peerDependencies": {- "@types/node": "^20.19.0 || >=22.12.0",- "jiti": ">=1.21.0",- "less": "^4.0.0",- "lightningcss": "^1.21.0",- "sass": "^1.70.0",- "sass-embedded": "^1.70.0",- "stylus": ">=0.54.8",- "sugarss": "^5.0.0",- "terser": "^5.16.0",- "tsx": "^4.8.1",- "yaml": "^2.4.2"- },- "peerDependenciesMeta": {- "@types/node": {- "optional": true- },- "jiti": {- "optional": true- },- "less": {- "optional": true- },- "lightningcss": {- "optional": true- },- "sass": {- "optional": true- },- "sass-embedded": {- "optional": true- },- "stylus": {- "optional": true- },- "sugarss": {- "optional": true- },- "terser": {- "optional": true- },- "tsx": {- "optional": true- },- "yaml": {- "optional": true- }- }- }- }-}diff --git a/frontend/package.json b/frontend/package.jsondeleted file mode 100644index 498e3a6..0000000--- a/frontend/package.json+++ /dev/null@@ -1,19 +0,0 @@-{- "name": "frontend",- "version": "1.0.0",- "description": "",- "main": "auth-new.js",- "scripts": {- "dev": "vite",- "build": "vite build",- "preview": "vite preview",- "test": "echo \"Error: no test specified\" && exit 1"- },- "keywords": [],- "author": "",- "license": "ISC",- "type": "commonjs",- "devDependencies": {- "vite": "^7.1.12"- }-}diff --git a/frontend/src/register.html b/frontend/register.htmlsimilarity index 94%rename from frontend/src/register.htmlrename to frontend/register.htmlindex 2dc83a6..6fa1c9e 100644--- a/frontend/src/register.html+++ b/frontend/register.html@@ -2,36 +2,37 @@<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 -->+ <script type="module" src="./js/services/authService.js"></script>+ <script type="module" src="./js/services/apiService.js"></script><!-- 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 src="./script.js?v=20250119001" defer></script>+ <script type="module" src="./js/index.js"></script><style>.auth-container {max-width: 500px;@@ -621,10 +622,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/src/reset-password-request.html b/frontend/reset-password-request.htmlsimilarity index 89%rename from frontend/src/reset-password-request.htmlrename to frontend/reset-password-request.htmlindex 88879cc..d55d9ca 100644--- a/frontend/src/reset-password-request.html+++ b/frontend/reset-password-request.html@@ -5,30 +5,31 @@<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 -->+ <script type="module" src="./js/services/authService.js"></script>+ <script type="module" src="./js/services/apiService.js"></script><!-- 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 src="./script.js?v=20250119001" defer></script>+ <script type="module" src="./js/index.js"></script><style>.auth-container {max-width: 400px;@@ -264,10 +265,10 @@<!-- 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/src/reset-password.html b/frontend/reset-password.htmlsimilarity index 93%rename from frontend/src/reset-password.htmlrename to frontend/reset-password.htmlindex a4fc88c..45a2c0c 100644--- a/frontend/src/reset-password.html+++ b/frontend/reset-password.html@@ -5,30 +5,31 @@<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 -->+ <script type="module" src="./js/services/authService.js"></script>+ <script type="module" src="./js/services/apiService.js"></script><!-- 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 src="./script.js?v=20250119001" defer></script>+ <script type="module" src="./js/index.js"></script><style>.auth-container {max-width: 400px;@@ -431,10 +432,10 @@<!-- 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/public/script.js b/frontend/script.jssimilarity index 84%rename from frontend/public/script.jsrename to frontend/script.jsindex dc064ef..b057d13 100644--- a/frontend/public/script.js+++ b/frontend/script.js@@ -161,27 +161,23 @@ 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@@ -583,7 +579,7 @@ document.addEventListener('DOMContentLoaded', function() {if (searchBtn && searchInput) {searchBtn.addEventListener('click', function(e) {e.preventDefault();- currentFilters.search = searchInput.value.toLowerCase();+ if (window.store && window.store.updateFilter) window.store.updateFilter('search', searchInput.value.toLowerCase());applyFilters();});}@@ -592,7 +588,8 @@ document.addEventListener('DOMContentLoaded', function() {const globalManageTagsBtn = document.getElementById('globalManageTagsBtn');if (globalManageTagsBtn) {globalManageTagsBtn.addEventListener('click', async () => {- if (!allTags || allTags.length === 0) {+ const __tags = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];+ if (!__tags || __tags.length === 0) {showLoadingSpinner();try {await loadTags();@@ -756,7 +753,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:', warranties);+ console.log('[DEBUG] After loadWarranties, warranties array:', (window.store && window.store.getWarranties && window.store.getWarranties()) || []);// After warranties are loaded and filter dropdowns populated, load filter/sort prefs and applyloadFilterAndSortPreferences();// Reflect saved filters in UI selects if present@@ -765,11 +762,12 @@ document.addEventListener('DOMContentLoaded', function() {const vendorFilterEl = document.getElementById('vendorFilter');const warrantyTypeFilterEl = document.getElementById('warrantyTypeFilter');const sortByEl = document.getElementById('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;+ 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;// Update the filter indicator if availableif (typeof window.updateFilterIndicator === 'function') {window.updateFilterIndicator();@@ -832,6 +830,14 @@ 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';@@ -1489,16 +1495,18 @@ function resetForm() {async function exportWarranties() {console.log('[EXPORT DEBUG] Starting export process');- console.log('[EXPORT DEBUG] Total warranties in memory:', warranties.length);- console.log('[EXPORT DEBUG] Current filters:', currentFilters);+ 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);// Get filtered warranties- let warrantiesToExport = [...warranties];+ let warrantiesToExport = [...__warrantiesData];console.log('[EXPORT DEBUG] Initial warranties to export:', warrantiesToExport.length);// Apply current filters- if (currentFilters.search) {- const searchTerm = currentFilters.search.toLowerCase();+ if (__filters.search) {+ const searchTerm = __filters.search.toLowerCase();console.log('[EXPORT DEBUG] Applying search filter:', searchTerm);warrantiesToExport = warrantiesToExport.filter(warranty => {// Check if product name contains search term@@ -1517,17 +1525,17 @@ async function exportWarranties() {console.log('[EXPORT DEBUG] After search filter:', warrantiesToExport.length);}- if (currentFilters.status !== 'all') {- console.log('[EXPORT DEBUG] Applying status filter:', currentFilters.status);+ if (__filters.status !== 'all') {+ console.log('[EXPORT DEBUG] Applying status filter:', __filters.status);warrantiesToExport = warrantiesToExport.filter(warranty =>- warranty.status === currentFilters.status+ warranty.status === __filters.status);console.log('[EXPORT DEBUG] After status filter:', warrantiesToExport.length);}// Apply tag filter- if (currentFilters.tag !== 'all') {- const tagId = parseInt(currentFilters.tag);+ if (__filters.tag !== 'all') {+ const tagId = parseInt(__filters.tag);console.log('[EXPORT DEBUG] Applying tag filter:', tagId);warrantiesToExport = warrantiesToExport.filter(warranty =>warranty.tags && Array.isArray(warranty.tags) &&@@ -1537,19 +1545,19 @@ async function exportWarranties() {}// Apply vendor filter- if (currentFilters.vendor !== 'all') {- console.log('[EXPORT DEBUG] Applying vendor filter:', currentFilters.vendor);+ if (__filters.vendor !== 'all') {+ console.log('[EXPORT DEBUG] Applying vendor filter:', __filters.vendor);warrantiesToExport = warrantiesToExport.filter(warranty =>- (warranty.vendor || '').toLowerCase() === currentFilters.vendor.toLowerCase()+ (warranty.vendor || '').toLowerCase() === __filters.vendor.toLowerCase());console.log('[EXPORT DEBUG] After vendor filter:', warrantiesToExport.length);}// Apply warranty type filter- if (currentFilters.warranty_type !== 'all') {- console.log('[EXPORT DEBUG] Applying warranty type filter:', currentFilters.warranty_type);+ if (__filters.warranty_type !== 'all') {+ console.log('[EXPORT DEBUG] Applying warranty type filter:', __filters.warranty_type);warrantiesToExport = warrantiesToExport.filter(warranty =>- (warranty.warranty_type || '').toLowerCase() === currentFilters.warranty_type.toLowerCase()+ (warranty.warranty_type || '').toLowerCase() === __filters.warranty_type.toLowerCase());console.log('[EXPORT DEBUG] After warranty type filter:', warrantiesToExport.length);}@@ -2100,205 +2108,17 @@ function processWarrantyData(warranty) {// Function to process all warranties in the arrayfunction processAllWarranties() {console.log('Processing all warranties in array...');- if (warranties && warranties.length > 0) {- warranties = warranties.map(warranty => processWarrantyData(warranty));+ 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);}- console.log('Processed warranties:', warranties);+ console.log('Processed warranties:', (window.store && window.store.getWarranties && window.store.getWarranties()) || []);}-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();+async function loadWarranties(isAuthenticated) {+ if (window.warrantyListController && typeof window.warrantyListController.loadWarranties === 'function') {+ return window.warrantyListController.loadWarranties(isAuthenticated);}}@@ -2441,8 +2261,176 @@ function calculateProductAgeInDays(purchaseDate) {return diffDays;}-async function renderWarranties(warrantiesToRender) {- console.log('renderWarranties called with:', warrantiesToRender);+// 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');// 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@@ -2452,21 +2440,74 @@ async function renderWarranties(warrantiesToRender) {return;}- const isArchivedView = currentFilters && currentFilters.status === 'archived';+ 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;+ });if (!warrantiesToRender || warrantiesToRender.length === 0) {- renderEmptyState(isArchivedView ? (window.t ? window.t('messages.no_archived_warranties') : 'No archived warranties.') : undefined); // renderEmptyState should also check for warrantiesList or its specific container+ 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);+ }return;}const today = new Date();const globalSymbol = getCurrencySymbol(); // Get the global symbol as fallback- warrantiesList.innerHTML = '';+ // Efficiently clear container+ warrantiesList.textContent = '';// Apply sorting based on current sort selectionconst sortedWarranties = [...warrantiesToRender].sort((a, b) => {- switch (currentFilters.sortBy) {+ switch (__filters.sortBy) {case 'name':return (a.product_name || '').toLowerCase().localeCompare((b.product_name || '').toLowerCase());case 'purchase':@@ -2510,6 +2551,9 @@ async function renderWarranties(warrantiesToRender) {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;@@ -2579,38 +2623,19 @@ async function renderWarranties(warrantiesToRender) {// 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() !== ''): [];- // 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>`;- }-++ // Build user info HTML+ const userInfoHtml = buildUserInfoHtml(warranty);++ // Notes link+ const notesLinkHtml = buildNotesLinkHtml(warranty);++ // Has documents?const hasDocuments = Boolean(warranty.product_url ||warranty.invoice_path || warranty.invoice_url ||@@ -2618,10 +2643,9 @@ async function renderWarranties(warrantiesToRender) {warranty.other_document_path || warranty.other_document_url ||warranty.paperless_invoice_id || warranty.paperless_manual_id ||warranty.paperless_photo_id || warranty.paperless_other_id ||- hasNotes+ notesLinkHtml);--+// Get current user ID to check warranty ownershipconst currentUserId = (() => {try {@@ -2636,307 +2660,103 @@ async function renderWarranties(warrantiesToRender) {// 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)';- }-- // 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');+ // Build actions/content/status for the component+ const actionButtonsHtml = buildActionButtonsHtml(warranty, isArchivedView, canEdit);+ const contentHtml = buildWarrantyInfoHtml({+ warranty,+ userInfoHtml,+ productAge,+ warrantyDurationText,+ expirationDateText,+ validSerialNumbers+ });const isArchivedItem = isArchivedView || warranty.is_archived;- 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);- });+ 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);}+ }- // 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);+ // 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);});+ const docRow = cardElement.querySelector('.document-links-row');+ if (docRow) {+ docRow.insertAdjacentElement('afterend', tagsRow);+ } else {+ cardElement.appendChild(tagsRow);+ }}}- // 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');- }- });- }++ fragment.appendChild(cardElement);});+ warrantiesList.appendChild(fragment);+// Load secure images with authentication after renderingloadSecureImages();@@ -2999,12 +2819,12 @@ function filterWarranties() {}if (!searchTerm) {- return warranties; // Return the full list if no search term+ return ((window.store && window.store.getWarranties && window.store.getWarranties()) || []); // Return the full list if no search term// REMOVED: renderWarranties();// REMOVED: return;}- const filtered = warranties.filter(warranty => {+ const filtered = (((window.store && window.store.getWarranties && window.store.getWarranties()) || [])).filter(warranty => {// Check product nameif (warranty.product_name && warranty.product_name.toLowerCase().includes(searchTerm)) { // Add null checkreturn true;@@ -3053,100 +2873,23 @@ function filterWarranties() {}function 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;+ if (window.warrantyListController && typeof window.warrantyListController.applyFilters === 'function') {+ return window.warrantyListController.applyFilters();}-- // 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: currentFilters.status || 'all',- tag: currentFilters.tag || 'all',- vendor: currentFilters.vendor || 'all',- warranty_type: currentFilters.warranty_type || 'all',- search: currentFilters.search || '',- sortBy: currentFilters.sortBy || 'expiration'+ 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'};localStorage.setItem(`${prefix}warrantyFilters`, JSON.stringify(filtersToSave));@@ -3190,12 +2933,15 @@ function loadFilterAndSortPreferences() {const savedFilters = JSON.parse(savedFiltersRaw);if (savedFilters && typeof savedFilters === 'object') {console.log('[Filters] Loading saved filters from localStorage:', savedFilters);- 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;+ 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);+ }// Restore search input UI stateconst searchInput = document.getElementById('searchWarranties');@@ -3775,29 +3521,27 @@ async function openEditModal(warranty) {function openDeleteModal(warrantyId, productName) {currentWarrantyId = warrantyId;-- const deleteProductNameElement = document.getElementById('deleteProductName');- if (deleteProductNameElement) {- deleteProductNameElement.textContent = productName || '';+ 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 || '';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;- const archiveProductNameElement = document.getElementById('archiveProductName');- if (archiveProductNameElement) {- archiveProductNameElement.textContent = productName || '';+ 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 || '';const archiveModal = document.getElementById('archiveModal');- if (archiveModal) {- archiveModal.classList.add('active');- }+ if (archiveModal) archiveModal.classList.add('active');}// Confirm archive handler@@ -4169,7 +3913,9 @@ document.addEventListener('DOMContentLoaded', function() {initializeTheme();// Set up event listeners for other UI controls (should contain checks)- setupUIEventListeners();+ if (window.warrantyListController && typeof window.warrantyListController.initEventListeners === 'function') {+ window.warrantyListController.initEventListeners();+ }setupModalTriggers(); // Add the new modal listeners// Check if user is logged in and update UI@@ -4233,35 +3979,7 @@ let currentClaimsCanEdit = false; // Track if current user can edit the warranty* Initialize claims event listeners*/function initClaimsEventListeners() {- // 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;- }- });- }+ // Card action delegation is now handled by warrantyListController.initEventListeners()// Add claim buttonif (addClaimBtn) {@@ -4305,7 +4023,7 @@ async function openClaimsModal(warrantyId) {currentClaimsWarrantyId = warrantyId;// Find warranty info- const warranty = warranties.find(w => w.id === warrantyId);+ const warranty = (((window.store && window.store.getWarranties && window.store.getWarranties()) || []).find(w => w.id === warrantyId));if (!warranty) {showToast(window.i18next ? window.i18next.t('claims.warranty_not_found') : 'Warranty not found', 'error');return;@@ -4994,12 +4712,13 @@ 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)- if (allTags.length === 0) {+ const __tagsInit = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];+ if (__tagsInit.length === 0) {loadTags(); // loadTags is async}mainFormTagSearch.addEventListener('focus', () => {- renderTagsList(); // Renders suggestions into mainFormTagsList based on allTags+ renderTagsList(); // Renders suggestions into mainFormTagsList based on store tagsmainFormTagsList.classList.add('show');});@@ -5032,10 +4751,11 @@ 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- if (!force && allTags && allTags.length > 0) {- console.log('[script.js] Tags already loaded in allTags global. Skipping fetch. Count:', allTags.length);+ 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);// Optionally, re-dispatch the event if other components might need it on subsequent (though now less likely) calls- // document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: allTags }));+ // document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: __existingTags }));return;}@@ -5043,7 +4763,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.');- allTags = []; // Ensure allTags is empty if we can't load+ if (window.store && window.store.setAllTags) window.store.setAllTags([]); // Ensure tags are empty if we can't loadreturn;}const response = await fetch('/api/tags', {@@ -5052,19 +4772,20 @@ async function loadTags(force = false) {if (!response.ok) {const errorText = await response.text();console.error('[script.js] Failed to load tags:', response.status, errorText);- allTags = []; // Default to empty on error+ if (window.store && window.store.setAllTags) window.store.setAllTags([]); // Default to empty on errorreturn;}const fetchedTags = await response.json();// Assuming fetchedTags is an array of {id, name, color, ...} as expected by other functions- allTags = fetchedTags;- console.log('[script.js] All tags loaded into global allTags variable:', allTags.length, 'tags. Sample:', allTags.slice(0,2));+ 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));// Dispatch event for any components that might be waiting for tags (e.g., Tagify instances)- document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: allTags }));+ document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: __tagsAfterSet }));} catch (error) {console.error('[script.js] Error in loadTags():', error);- allTags = []; // Default to empty on critical error+ if (window.store && window.store.setAllTags) window.store.setAllTags([]); // Default to empty on critical error}}@@ -5075,7 +4796,8 @@ function renderTagsList(searchTerm = '') {tagsList.innerHTML = '';// Filter tags based on search term- const filteredTags = allTags.filter(tag =>+ const __allTagsForRender = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];+ const filteredTags = __allTagsForRender.filter(tag =>!searchTerm || tag.name.toLowerCase().includes(searchTerm.toLowerCase()));@@ -5140,7 +4862,8 @@ function renderEditTagsList(searchTerm = '') {if (!editTagsList) return;editTagsList.innerHTML = '';// Filter tags based on search term- const filteredTags = allTags.filter(tag =>+ const __allTagsForEdit = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];+ const filteredTags = __allTagsForEdit.filter(tag =>!searchTerm || tag.name.toLowerCase().includes(searchTerm.toLowerCase()));// Add option to create new tag if search term is provided and not in list@@ -5366,7 +5089,8 @@ function createTag(name) {name: data.name,color: data.color};- allTags.push(newTag);+ const __existing = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];+ if (window.store && window.store.setAllTags) window.store.setAllTags([...__existing, newTag]);renderExistingTags();populateTagFilter();showToast(window.t('messages.tag_created_successfully'), 'success');@@ -5430,12 +5154,13 @@ function renderExistingTags() {const tbody = document.createElement('tbody');- if (!allTags || allTags.length === 0) {+ const __storeTags = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];+ if (!__storeTags || __storeTags.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 {- allTags.forEach(tag => {+ __storeTags.forEach(tag => {const row = document.createElement('tr');row.className = 'existing-tag-row';row.dataset.id = String(tag.id);@@ -5534,18 +5259,17 @@ 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- 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;- }- });- }- });- }+ 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);+ }}} catch (e) {console.warn('[script.js] Non-fatal error while updating local tag state after update:', e);@@ -5555,7 +5279,7 @@ function updateTag(id, name, color) {renderSelectedTags();renderEditSelectedTags();populateTagFilter();- renderWarranties(warranties);+ renderWarranties();if (document.getElementById('summary-tags')) {updateSummary();}@@ -5688,25 +5412,30 @@ function deleteTag(id) {}).then(data => {// Remove tag from allTags array- allTags = allTags.filter(tag => tag.id !== id);+ 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);// 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- warranties.forEach(warranty => {+ const __warrantiesNow = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];+ const __updatedWarranties = __warrantiesNow.map(warranty => {if (warranty.tags && Array.isArray(warranty.tags)) {- warranty.tags = warranty.tags.filter(tag => tag.id !== id);+ return { ...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(warranties); // Update warranty cards to remove deleted tag+ renderWarranties(); // Update warranty cards to remove deleted tag// --- END FIX ---showToast(window.t('messages.tag_deleted_successfully'), 'success');@@ -5720,270 +5449,37 @@ function deleteTag(id) {});}-// 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');-- 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 ***-- // Otherwise, close the modal (handles other modals' backdrop clicks and all dismiss buttons)- modalToClose.classList.remove('active');+// Set up event listeners for UI controls (delegated to controller in index.js)- // 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 = '';- }- });+// 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);}-- // Save warranty changes- const saveWarrantyBtn = document.getElementById('saveWarrantyBtn');- if (saveWarrantyBtn) {- let functionToAttachOnClick = saveWarranty; // Default to the original saveWarranty from script.js+}- // Check if the observer setup function from status.js is available- if (typeof window.setupSaveWarrantyObserver === 'function') {- console.log('[script.js] window.setupSaveWarrantyObserver (from status.js) was FOUND. Attempting to wrap local saveWarranty function.');- try {- // Call the observer setup function, passing it the original saveWarranty from this script.- // The observer setup function is expected to return a new function that wraps the original.- functionToAttachOnClick = window.setupSaveWarrantyObserver(saveWarranty);-- // Optional: A flag to let status.js know that script.js has handled the wrapping.- // This can be useful if status.js has any fallback/polling logic to prevent double-wrapping.- window.saveWarrantyObserverAttachedByScriptJS = true;- console.log('[script.js] Local saveWarranty function has been successfully WRAPPED by the observer from status.js.');- } catch (e) {- console.error('[script.js] An error occurred while trying to wrap saveWarranty with the observer from status.js:', e);- // If an error occurs during wrapping, functionToAttachOnClick will remain the original saveWarranty.- }- } else {- console.log('[script.js] window.setupSaveWarrantyObserver (from status.js) was NOT FOUND. Using the original saveWarranty function for the button.');- }+function loadFilterAndSortPreferences() {+ if (window.warrantyListController && typeof window.warrantyListController.loadFilterAndSortPreferences === 'function') {+ return window.warrantyListController.loadFilterAndSortPreferences();+ }+}- // 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!');- }- });+function populateTagFilter() {+ if (window.warrantyListController && typeof window.warrantyListController.populateTagFilter === 'function') {+ return window.warrantyListController.populateTagFilter();+ }+}- } else {- console.warn('[script.js] saveWarrantyBtn DOM element not found. Cannot attach click listener.');+function populateVendorFilter() {+ if (window.warrantyListController && typeof window.warrantyListController.populateVendorFilter === 'function') {+ return window.warrantyListController.populateVendorFilter();}-- // 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 populateWarrantyTypeFilter() {+ if (window.warrantyListController && typeof window.warrantyListController.populateWarrantyTypeFilter === 'function') {+ return window.warrantyListController.populateWarrantyTypeFilter();+ }}// Function to show loading spinner@@ -6191,7 +5687,9 @@ function deleteWarranty() {// --- BEGIN FIX: Update UI immediately ---// Remove the deleted warranty from the global arrayconst deletedId = currentWarrantyId; // Store ID before resetting- warranties = warranties.filter(warranty => warranty.id !== deletedId);+ 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);currentWarrantyId = null; // Reset current ID// Re-render the list using the updated local array@@ -6205,333 +5703,7 @@ function deleteWarranty() {});}-// 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');- });-}+// Save warranty logic moved to window.components.editModal.saveWarranty// Function to populate tag filter dropdownfunction populateTagFilter() {@@ -6547,7 +5719,8 @@ function populateTagFilter() {const uniqueTags = new Set();// Collect all unique tags from warranties- warranties.forEach(warranty => {+ const __w = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];+ __w.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}));@@ -6586,7 +5759,8 @@ function populateVendorFilter() {const uniqueVendors = new Set();// Collect all unique, non-empty vendors from warranties- warranties.forEach(warranty => {+ const __w = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];+ __w.forEach(warranty => {if (warranty.vendor && warranty.vendor.trim() !== '') {uniqueVendors.add(warranty.vendor.trim().toLowerCase());}@@ -6621,7 +5795,8 @@ function populateWarrantyTypeFilter() {const uniqueWarrantyTypes = new Set();// Collect all unique, non-empty warranty types from warranties- warranties.forEach(warranty => {+ const __w = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];+ __w.forEach(warranty => {if (warranty.warranty_type && warranty.warranty_type.trim() !== '') {uniqueWarrantyTypes.add(warranty.warranty_type.trim().toLowerCase());}@@ -7053,7 +6228,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 = warranties.find(w => w.id === notesModalWarrantyId);+ const currentWarranty = (((window.store && window.store.getWarranties && window.store.getWarranties()) || []).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@@ -7085,7 +6260,7 @@ function showNotesModal(notes, warrantyOrId = null) {} else {notesModalWarrantyId = warrantyOrId;// Try to find the warranty object from global warranties array- notesModalWarrantyObj = warranties.find(w => w.id === notesModalWarrantyId) || null;+ notesModalWarrantyObj = ((((window.store && window.store.getWarranties && window.store.getWarranties()) || []).find(w => w.id === notesModalWarrantyId)) || null);}// Show note content, hide textarea and edit controlsdiff --git a/frontend/src/settings-new.html b/frontend/settings-new.htmlsimilarity index 94%rename from frontend/src/settings-new.htmlrename to frontend/settings-new.htmlindex 08b4b34..eca725a 100644--- a/frontend/src/settings-new.html+++ b/frontend/settings-new.html@@ -2,7 +2,7 @@<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 -->@@ -11,38 +11,38 @@<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>+ <script type="module" src="./js/services/authService.js"></script>+ <script type="module" src="./js/services/apiService.js"></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 --><!-- 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><!-- 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,52 +1076,17 @@<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" onclick="deleteUser()">Delete</button>+ <button type="button" id="confirmDeleteUserBtn" class="btn btn-danger">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;" 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><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><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"- 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>+ <button type="button" id="emergencyDeleteBtn" class="btn btn-sm btn-danger">Emergency Delete</button></div></div></form>@@ -1172,13 +1137,13 @@<!-- Scripts -->- <script src="/settings-new.js?v=20250119001"></script>+ <script type="module" src="./settings-new.js"></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/public/settings-new.js b/frontend/settings-new.jssimilarity index 100%rename from frontend/public/settings-new.jsrename to frontend/settings-new.jsdiff --git a/frontend/public/settings-styles.css b/frontend/settings-styles.csssimilarity index 100%rename from frontend/public/settings-styles.cssrename to frontend/settings-styles.cssdiff --git a/frontend/src/status.html b/frontend/status.htmlsimilarity index 96%rename from frontend/src/status.htmlrename to frontend/status.htmlindex 1c0863e..8077370 100644--- a/frontend/src/status.html+++ b/frontend/status.html@@ -2,46 +2,47 @@<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 --><!-- 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 -->+ <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><!-- 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="/status.js?v=20250119001"></script> <!-- Status page specific functionality -->+ <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 --><style>.user-menu {position: relative;@@ -826,13 +827,13 @@</div>- <script type="module" src="/status.js?v=20250119001"></script>+ <script type="module" src="./status.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/src/status.js b/frontend/status.jssimilarity index 97%rename from frontend/src/status.jsrename to frontend/status.jsindex 6ffa111..6191ddc 100644--- a/frontend/src/status.js+++ b/frontend/status.js@@ -1,3 +1,5 @@+import apiService from './js/services/apiService.js';+import authService from './js/services/authService.js';(function() {// DOM Elementsconst loadingIndicator = document.getElementById('loadingIndicator');@@ -101,17 +103,13 @@async function fetchStatistics() {try {console.log('Checking authentication status... (status.js IIFE)');- if (!window.auth || !window.auth.isAuthenticated()) {+ if (!authService || !authService.isAuthenticated()) {throw new Error('Authentication required.');}- const token = window.auth.getToken();+ const token = authService.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();@@ -121,17 +119,15 @@const apiUrl = shouldUseGlobalView ? GLOBAL_STATISTICS_API_URL : STATISTICS_API_URL;console.log('Fetching statistics from:', apiUrl, '(Global view preference:', savedScope, ')');- const response = await fetch(apiUrl, options);- if (!response.ok) {- const errorText = await response.text();- throw new Error(`Failed to fetch statistics: ${response.status} ${errorText}`);- }-+ const response = shouldUseGlobalView+ ? await apiService.request('/api/statistics/global')+ : await apiService.request('/api/statistics');+ const json = await response.json();// Update isGlobalView to match the loaded dataisGlobalView = shouldUseGlobalView;console.log(`[DEBUG] Set isGlobalView to: ${isGlobalView}`);- return await response.json();+ return json;} catch (error) {console.error('Error fetching statistics (status.js IIFE):', error);throw error;@@ -158,13 +154,10 @@try {// Check if global view is enabled for this user- const token = window.auth.getToken();+ const token = authService.getToken();if (!token) return;- const response = await fetch('/api/settings/global-view-status', {- method: 'GET',- headers: { 'Authorization': `Bearer ${token}` }- });+ const response = await apiService.request('/api/settings/global-view-status', { method: 'GET' });if (response.ok) {const result = await response.json();@@ -343,11 +336,8 @@try {// Check if global view is still available- const token = window.auth.getToken();- const response = await fetch('/api/settings/global-view-status', {- method: 'GET',- headers: { 'Authorization': `Bearer ${token}` }- });+ const token = authService.getToken();+ const response = await apiService.request('/api/settings/global-view-status', { method: 'GET' });if (response.ok) {const result = await response.json();@@ -944,14 +934,9 @@let allWarrantiesForTimeline = [];try {// Try to fetch all warranties for a complete timeline- const token = window.auth && window.auth.getToken ? window.auth.getToken() : null;+ const token = authService && authService.getToken ? authService.getToken() : null;if (token) {- const allWarrantiesResponse = await fetch('/api/warranties', {- headers: {- 'Authorization': `Bearer ${token}`,- 'Content-Type': 'application/json'- }- });+ const allWarrantiesResponse = await apiService.request('/api/warranties', { method: 'GET' });if (allWarrantiesResponse.ok) {allWarrantiesForTimeline = await allWarrantiesResponse.json();} else {@@ -1032,9 +1017,8 @@async function loadUserPreferences() {try {- if (!window.auth || !window.auth.getToken()) { console.warn('Auth or token not available for prefs in status.js'); return; }- const token = window.auth.getToken();- const response = await fetch('/api/auth/preferences', { headers: { 'Authorization': `Bearer ${token}` } });+ if (!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 (response.ok) {const prefs = await response.json();if (prefs && prefs.expiring_soon_days !== undefined) { // Check for undefined specifically@@ -1088,13 +1072,10 @@// ALWAYS fetch fresh details when editing from the status page to ensure modal has latest data.console.log(`[DEBUG status.js] Edit from status page for warranty ${warrantyId}. ALWAYS fetching fresh details from /api/debug/warranty/:id.`);showLoadingSpinner(); // Show spinner for this specific fetch- const token = localStorage.getItem('auth_token') || (window.auth && window.auth.getToken());+ const token = authService.getToken();if (!token) throw new Error('Authentication token not available for fetching fresh details.');- const response = await fetch(`/api/debug/warranty/${warrantyId}`, {- method: 'GET',- headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }- });+ const response = await apiService.request(`/api/debug/warranty/${warrantyId}`, { method: 'GET' });if (!response.ok) {const errorData = await response.json().catch(() => ({}));diff --git a/frontend/src/style.css b/frontend/style.csssimilarity index 99%rename from frontend/src/style.cssrename to frontend/style.cssindex 4c14ae6..b365df8 100644--- a/frontend/src/style.css+++ b/frontend/style.css@@ -4827,18 +4827,18 @@ html.dark-mode .warracker-footer a:hover {}}-@media (max-width: 768px) {+@media (max-width: 360px) {.grid-view .product-photo-thumbnail img {- width: 30px;- height: 30px;+ width: 30px;+ height: 30px;}.list-view .product-photo-thumbnail img {- width: 25px;- height: 25px;+ width: 60px;+ height: 60px;}.table-view .product-photo-thumbnail img {- width: 20px;- height: 20px;+ width: 20px;+ height: 20px;}.product-photo-thumbnail {margin-right: 5px;diff --git a/frontend/public/sw.js b/frontend/sw.jssimilarity index 100%rename from frontend/public/sw.jsrename to frontend/sw.jsdiff --git a/frontend/public/theme-loader.js b/frontend/theme-loader.jssimilarity index 100%rename from frontend/public/theme-loader.jsrename to frontend/theme-loader.jsdiff --git a/frontend/public/version-checker.js b/frontend/version-checker.jssimilarity index 100%rename from frontend/public/version-checker.jsrename to frontend/version-checker.jsdiff --git a/frontend/vite.config.js b/frontend/vite.config.jsdeleted file mode 100644index 539dc78..0000000--- a/frontend/vite.config.js+++ /dev/null@@ -1,35 +0,0 @@-import { defineConfig } from 'vite';-import { resolve } from 'node:path';--export default defineConfig({- root: 'src',- publicDir: resolve(__dirname, 'public'),- build: {- outDir: '../dist',- rollupOptions: {- input: {- index: resolve(__dirname, 'src/index.html'),- login: resolve(__dirname, 'src/login.html'),- register: resolve(__dirname, 'src/register.html'),- status: resolve(__dirname, 'src/status.html'),- settings: resolve(__dirname, 'src/settings-new.html'),- resetPassword: resolve(__dirname, 'src/reset-password.html'),- resetPasswordRequest: resolve(__dirname, 'src/reset-password-request.html'),- authRedirect: resolve(__dirname, 'src/auth-redirect.html'),- about: resolve(__dirname, 'src/about.html'),- debugExport: resolve(__dirname, 'src/debug-export.html'),- },- },- },- server: {- proxy: {- '/api': {- target: 'http://localhost:5000',- changeOrigin: true,- secure: false,- },- },- },-});--