🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
feat(frontend): modularize architecture, add state management, improve image loading, and fix critical bugs
sassanix0e46c8132cc3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1823f54..cc1644f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,6 +1,69 @@# Changelog-## 1.0.3 - 2025-10-31+## 1.0.3 - 2026-03-29+### Enhanced+- **Frontend Architecture Refactoring:** Migrated frontend JavaScript from monolithic `script.js` to modular ES modules for improved maintainability and code organization.+ - **New Modular Components:** Created dedicated modules for `addWarrantyForm`, `editModal`, `tagManager`, `notes`, `claims`, `importExport`, `warrantyActions`, `modals`, `ui`, and `paperless`.+ - **Centralized State Management:** Implemented `store.js` module for centralized application state and event-driven UI updates.+ - **Controller Pattern:** Added `warrantyListController.js` to orchestrate warranty display, filtering, and actions.+ - **Bootstrap Module:** Created `bootstrap.js` for centralized initialization of core services (auth, theme, currencies, Paperless).+ - **Backward Compatibility:** Legacy `script.js` remains functional during migration with sync mechanisms to ensure data consistency.+ - _Files: `frontend/js/bootstrap.js`, `frontend/js/index.js`, `frontend/js/store.js`, `frontend/js/controllers/warrantyListController.js`, `frontend/js/components/*.js`_++- **Frontend Architecture Refactoring - Phase 2:** Continued modularization effort, reducing `script.js` by 841 lines (9% reduction).+ - **Form Tabs Module:** Extracted complete form tab navigation system to `formTabs.js` with validation, summary generation, and form reset functionality.+ - **Serial Numbers Module:** Created `serialNumbers.js` for dynamic serial number input management with add/remove/get/set operations.+ - **Code Consolidation:** Removed duplicate mobile menu code (157 lines), theme functions, and date utilities by delegating to existing modules (`mobile-menu.js`, `lib/theme.js`, `lib/dates.js`).+ - **Claims Documentation:** Documented delegation pattern for claims functionality already extracted to `components/claims.js`.+ - **Module Integration:** Added new modules to `js/index.js` with proper ES6 imports while maintaining backward compatibility via `window` exports.+ - _Files: `frontend/js/components/formTabs.js`, `frontend/js/components/serialNumbers.js`, `frontend/script.js`, `frontend/js/index.js`_+ - _Documentation: `memory_bank/frontend-refactoring-phase2.md`_++- **Secure Image Loading Optimization:** Improved product photo loading performance with parallel fetching and caching.+ - **Parallel Image Loading:** Images now load simultaneously using `Promise.all` instead of sequentially.+ - **Image Preloading:** Warranty images are preloaded in the background after warranties load, enabling instant display when rendered.+ - **Memory Caching:** Blob URLs are cached in memory to prevent re-fetching previously loaded images.+ - **Loading Animation:** Added CSS shimmer skeleton animation during image loading with smooth fade-in on completion.+ - _Files: `frontend/js/components/paperless.js`, `frontend/script.js`, `frontend/style.css`_++### Fixed+- **Paperless-ngx File Upload:** Fixed critical bug where files selected for Paperless-ngx storage were incorrectly uploaded locally instead.+ - **Root Cause:** The `getStorageOption()` function was generating incorrect radio button names for the add warranty form (`InvoiceStorage` instead of `invoiceStorage`), causing the storage selection to default to 'local'.+ - **Solution:** Corrected the function to use lowercase names for add form (`invoiceStorage`, `manualStorage`) and camelCase for edit form (`editInvoiceStorage`, `editManualStorage`).+ - _Files: `frontend/js/components/paperless.js`, `frontend/script.js`_++- **Authentication Compatibility:** Fixed `TypeError: window.auth.checkAuthState is not a function` error on protected pages.+ - **Root Cause:** The `authService.js` module was overwriting `window.auth` without including the `checkAuthState` method.+ - **Solution:** Added `checkAuthState` to the `window.auth` compatibility object.+ - _Files: `frontend/js/services/authService.js`_++- **Tag Management in Warranty Forms:** Fixed tags not being added or removed correctly when saving warranties.+ - **Root Cause:** The modular `addWarrantyForm.js` and `editModal.js` were reading from stale global `window.selectedTags` arrays instead of the centralized store.+ - **Solution:** Updated both modules to exclusively use `getSelectedTags()` and `getEditSelectedTags()` from the store.+ - _Files: `frontend/js/components/addWarrantyForm.js`, `frontend/js/components/editModal.js`_++- **Expiring Soon Status Display:** Fixed "Expiring Soon" status not showing correctly based on user preferences.+ - **Root Cause:** The `expiringSoonDays` value from user preferences was not being synced to the store after loading from the API.+ - **Solution:** Added explicit store update in `loadAndApplyUserPreferences()` and a storage event listener to keep the store in sync.+ - _Files: `frontend/script.js`_++- **Notes Modal Edit Warranty:** Fixed "Edit Warranty" button in notes modal not working with `messages.warranty_not_found_refresh` error.+ - **Root Cause:** Duplicate global exposure in `notes.js` was overwriting the correct `showNotesModal` function, preventing the warranty object from being stored properly.+ - **Solution:** Removed duplicate code and ensured `handleEditWarranty` uses the already-stored warranty object.+ - _Files: `frontend/js/components/notes.js`_++- **Warranty Delete/Archive Actions:** Fixed warranty deletion and archiving not working from the modular components.+ - **Root Cause:** The `warrantyActions.js` module was reading from an empty store while `script.js` was setting global variables.+ - **Solution:** Added fallback to `window.currentWarrantyId` and sync to store in `openDeleteModal`/`openArchiveModal`.+ - _Files: `frontend/js/components/warrantyActions.js`, `frontend/script.js`_++- **No Tags Selected Placeholder:** Fixed raw i18n key `tags.no_selected` displaying instead of translated text when no tags are selected.+ - **Solution:** Added `defaultValue` option to `window.t()` calls to ensure a human-readable fallback is always displayed.+ - _Files: `frontend/js/components/addWarrantyForm.js`, `frontend/js/components/tagManager.js`_++- **Missing Translations:** Added missing translation keys to resolve console warnings.+ - Added keys: `filters.filter`, `filters.filter_by`, `filters.clear`, `filters.apply`, `filters.sort`, `warranties.archived`, `actions.data`, `warranties.or_link_to_invoice_url`, `warranties.or_link_to_manual_url`, `warranties.or_link_to_files_url`, `warranties.enter_serial_number`, `warranties.add_serial_number`.+ - _Files: `locales/en/translation.json`_## 1.0.2 - 2025-10-30@@ -2006,4 +2069,4 @@ _Files: `docker-compose.yml`_- **Layout:** Updated `.panel-header` CSS to use Flexbox for aligning the title (`h2`) to the left and action buttons (`.panel-header-actions` containing Add Warranty and Refresh buttons) to the right (`frontend/style.css`).- **Layout:** Removed the `border-bottom` style from the `.panel-header` / `.warranties-panel h2` for a cleaner look (`frontend/style.css`).- **Branding:** Updated the website `<title>` to include "Warracker" (`frontend/index.html`).-- **UI:** Added an "Add New Warranty" button (`#showAddWarrantyBtn`) to trigger the new modal (`frontend/index.html`\ No newline at end of file+- **UI:** Added an "Add New Warranty" button (`#showAddWarrantyBtn`) to trigger the new modal (`frontend/index.html`diff --git a/Dockerfile b/Dockerfileindex cbf5f0f..17df14a 100644--- a/Dockerfile+++ b/Dockerfile@@ -112,7 +112,7 @@ COPY --chown=warracker:warracker backend/migrations/ ./migrations/COPY --chown=warracker:warracker locales/ ./locales/COPY --chown=warracker:warracker locales/ /var/www/html/locales/-# 4. Frontend (bundled in one instruction)+# 4. Frontend (static files, no build step)COPY --chown=warracker:warracker frontend/ /var/www/html/# 5. Backend (bundled in one instruction)diff --git a/frontend/about.html b/frontend/about.htmlindex a7c52a8..f3be9ef 100644--- a/frontend/about.html+++ b/frontend/about.html@@ -333,7 +333,7 @@<!-- Hero Section --><div class="about-hero"><h1><i class="fas fa-shield-alt"></i> Warracker</h1>- <div class="version" id="versionDisplay" data-i18n="about.version">Version v1.0.2</div>+ <div class="version" id="versionDisplay" data-i18n="about.version">Version v1.0.3</div><p class="description" data-i18n="about.description">A comprehensive warranty management system designed to help you track, organize, and manage all your product warranties in one secure, user-friendly platform.</p>@@ -434,7 +434,7 @@// Update version display dynamicallyconst versionDisplay = document.getElementById('versionDisplay');if (versionDisplay && window.i18next) {- const currentVersion = '1.0.2'; // This should match version-checker.js+ const currentVersion = '1.0.3'; // This should match version-checker.jsversionDisplay.textContent = window.i18next.t('about.version') + ' v' + currentVersion;}diff --git a/frontend/index.html b/frontend/index.htmlindex 1d70404..f67e0b3 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -1325,6 +1325,7 @@<div class="loading-spinner"></div></div>+ <script type="module" src="js/index.js?v=20250119001"></script><script src="auth.js?v=20250119001"></script><script src="script.js?v=20250119002"></script><script>diff --git a/frontend/js/bootstrap.js b/frontend/js/bootstrap.jsnew file mode 100644index 0000000..76d0bb5--- /dev/null+++ b/frontend/js/bootstrap.js@@ -0,0 +1,54 @@+import authService from './services/authService.js';+import { initializeTheme, bindThemeToggle } from './lib/theme.js';+import { loadCurrencies } from './lib/currency.js';+import { initPaperlessIntegration } from './components/paperless.js';++let paperlessInitialized = false;+let currenciesLoaded = false;+let bootstrapInitialized = false;++function registerServiceWorker() {+ if (!('serviceWorker' in navigator)) return;+ window.addEventListener('load', () => {+ navigator.serviceWorker+ .register('./sw.js')+ .then((registration) => {+ console.log('[bootstrap] Service worker registered:', registration.scope);+ })+ .catch((error) => {+ console.error('[bootstrap] Service worker registration failed:', error);+ });+ });+}++function handleAuthState(event) {+ const isAuthenticated = !!(event.detail && event.detail.isAuthenticated);+ if (isAuthenticated) {+ if (!currenciesLoaded) {+ currenciesLoaded = true;+ loadCurrencies().catch((error) => console.error('[bootstrap] Failed to load currencies', error));+ }+ if (!paperlessInitialized) {+ paperlessInitialized = true;+ initPaperlessIntegration().catch((error) => console.error('[bootstrap] Failed to init paperless', error));+ }+ }+}++export function initBootstrap() {+ if (bootstrapInitialized) return;+ bootstrapInitialized = true;+ authService.initAuth();+ document.addEventListener('DOMContentLoaded', () => {+ initializeTheme();+ bindThemeToggle();+ registerServiceWorker();+ });+ window.addEventListener('authStateReady', handleAuthState);+}++export default {+ initBootstrap,+};++diff --git a/frontend/js/components/addWarrantyForm.js b/frontend/js/components/addWarrantyForm.jsindex 7dc831a..eab4333 100644--- a/frontend/js/components/addWarrantyForm.js+++ b/frontend/js/components/addWarrantyForm.js@@ -1,72 +1,864 @@-// Add Warranty Form Wizard (compat layer)-// Delegates to existing global implementations to preserve identical behavior.+import { showToast, showLoadingSpinner, hideLoadingSpinner } from './ui.js';+import { createWarranty } from '../services/apiService.js';+import { loadWarranties, applyFilters } from '../controllers/warrantyListController.js';+import {+ processPaperlessUploads,+ clearPaperlessSelection,+ getStorageOption,+ autoLinkRecentDocuments,+} from './paperless.js';+import {+ getCurrencySymbol,+ getCurrencySymbolByCode,+ getCurrencyCode,+ getCurrencyPosition,+ formatCurrencyHTML,+ updateFormCurrencyPosition,+} from '../lib/currency.js';+import {+ getSelectedTags,+ setSelectedTags,+ StoreEvents,+} from '../store.js';+import {+ renderSelectedTags,+} from './tagManager.js';-function callIfExists(fn, ...args) {- if (typeof fn === 'function') {- return fn(...args);+const state = {+ modal: null,+ form: null,+ tabs: [],+ tabContents: [],+ currentTabIndex: 0,+ nextBtn: null,+ prevBtn: null,+ submitBtn: null,+ serialContainer: null,+ isLifetimeCheckbox: null,+ durationMethodRadio: null,+ exactDateMethodRadio: null,+ durationFields: null,+ exactDateField: null,+ exactDateInput: null,+ fileInputs: {},+ summary: {},+ initialised: false,+ tagListenerBound: false,+};++const SERIAL_PLACEHOLDER = () => (window.i18next ? window.i18next.t('warranties.enter_serial_number') : 'Enter serial number');+const ADD_SERIAL_LABEL = () => (window.i18next ? window.i18next.t('warranties.add_serial_number') : 'Add Serial Number');++export function init() {+ if (state.initialised) return;+ cacheDom();+ if (!state.form) return;+ bindEvents();+ refreshTabs();+ resetAddWarrantyWizard();+ updateSummary();+ state.initialised = true;+}++function cacheDom() {+ state.modal = document.getElementById('addWarrantyModal');+ state.form = document.getElementById('warrantyForm');+ state.serialContainer = document.getElementById('serialNumbersContainer');+ state.isLifetimeCheckbox = document.getElementById('isLifetime');+ state.durationMethodRadio = document.getElementById('durationMethod');+ state.exactDateMethodRadio = document.getElementById('exactDateMethod');+ state.durationFields = document.getElementById('warrantyDurationFields');+ state.exactDateField = document.getElementById('exactExpirationField');+ state.exactDateInput = document.getElementById('exactExpirationDate');+ state.nextBtn = document.getElementById('nextTabBtn');+ state.prevBtn = document.getElementById('prevTabBtn');+ state.submitBtn = document.getElementById('submitWarrantyBtn');+ state.fileInputs = {+ productPhoto: {+ input: document.getElementById('productPhoto'),+ label: document.getElementById('productPhotoFileName'),+ previewWrapper: document.getElementById('productPhotoPreview'),+ previewImage: document.getElementById('productPhotoImg'),+ },+ invoice: {+ input: document.getElementById('invoice'),+ label: document.getElementById('fileName'),+ },+ manual: {+ input: document.getElementById('manual'),+ label: document.getElementById('manualFileName'),+ },+ other: {+ input: document.getElementById('otherDocument'),+ label: document.getElementById('otherDocumentFileName'),+ },+ };+ state.summary = {+ productName: document.getElementById('summary-product-name'),+ productUrl: document.getElementById('summary-product-url'),+ serialNumbers: document.getElementById('summary-serial-numbers'),+ purchaseDate: document.getElementById('summary-purchase-date'),+ warrantyDuration: document.getElementById('summary-warranty-duration'),+ warrantyType: document.getElementById('summary-warranty-type'),+ purchasePrice: document.getElementById('summary-purchase-price'),+ productPhoto: document.getElementById('summary-product-photo'),+ invoice: document.getElementById('summary-invoice'),+ manual: document.getElementById('summary-manual'),+ otherDocument: document.getElementById('summary-other-document'),+ tags: document.getElementById('summary-tags'),+ vendor: document.getElementById('summary-vendor'),+ };+}++function bindEvents() {+ if (!state.form) return;++ // Guard against multiple submit listener attachments+ if (!state.form._awfSubmitBound) {+ state.form.addEventListener('submit', handleFormSubmit);+ state.form._awfSubmitBound = true;+ }++ if (!state.form._awfInputBound) {+ state.form.addEventListener('input', handleFormInput, true);+ state.form.addEventListener('change', handleFormInput, true);+ state.form._awfInputBound = true;+ }++ if (state.serialContainer && !state.serialContainer._awfBound) {+ state.serialContainer.addEventListener('click', handleSerialContainerClick);+ state.serialContainer._awfBound = true;+ }++ if (state.isLifetimeCheckbox && !state.isLifetimeCheckbox._awfBound) {+ state.isLifetimeCheckbox.addEventListener('change', handleLifetimeChange);+ state.isLifetimeCheckbox._awfBound = true;+ }+ if (state.durationMethodRadio && !state.durationMethodRadio._awfBound) {+ state.durationMethodRadio.addEventListener('change', handleWarrantyMethodChange);+ state.durationMethodRadio._awfBound = true;+ }+ if (state.exactDateMethodRadio && !state.exactDateMethodRadio._awfBound) {+ state.exactDateMethodRadio.addEventListener('change', handleWarrantyMethodChange);+ state.exactDateMethodRadio._awfBound = true;+ }++ const showModalBtn = document.getElementById('showAddWarrantyBtn');+ if (showModalBtn && !showModalBtn._awfBound) {+ showModalBtn.addEventListener('click', (event) => {+ event.preventDefault();+ openModal();+ });+ showModalBtn._awfBound = true;+ }++ const closeBtn = state.modal ? state.modal.querySelector('[data-dismiss="modal"]') : null;+ if (closeBtn && !closeBtn._awfBound) {+ closeBtn.addEventListener('click', () => {+ closeModal();+ });+ closeBtn._awfBound = true;+ }++ if (state.nextBtn && !state.nextBtn._awfBound) {+ state.nextBtn.addEventListener('click', handleNextTab);+ state.nextBtn._awfBound = true;+ }+ if (state.prevBtn && !state.prevBtn._awfBound) {+ state.prevBtn.addEventListener('click', handlePrevTab);+ state.prevBtn._awfBound = true;+ }++ if (!state.tagListenerBound) {+ window.addEventListener(StoreEvents.SELECTED_TAGS_CHANGED, updateSummary);+ state.tagListenerBound = true;+ }++ Object.values(state.fileInputs).forEach((entry) => {+ if (entry.input && !entry.input._awfBound) {+ entry.input.addEventListener('change', () => updateFileDisplay(entry));+ entry.input._awfBound = true;+ }+ });+}++function refreshTabs() {+ if (!state.modal) return;+ state.tabs = Array.from(state.modal.querySelectorAll('.form-tab'));+ state.tabContents = Array.from(state.modal.querySelectorAll('.tab-content'));+ state.tabs.forEach((tab, index) => {+ if (tab._awfBound) return;+ tab.addEventListener('click', () => handleTabClick(index));+ tab._awfBound = true;+ });+ updateCompletedTabs();+ updateNavigationButtons();+}++function handleTabClick(targetIndex) {+ if (targetIndex === state.currentTabIndex) return;+ if (targetIndex < state.currentTabIndex) {+ switchToTab(targetIndex);+ return;+ }+ if (validateTab(state.currentTabIndex)) {+ markTabCompleted(state.currentTabIndex);+ switchToTab(targetIndex);+ } else {+ showValidationErrors(state.currentTabIndex);+ }+}++function handleNextTab() {+ if (validateTab(state.currentTabIndex)) {+ markTabCompleted(state.currentTabIndex);+ switchToTab(state.currentTabIndex + 1);+ } else {+ showValidationErrors(state.currentTabIndex);}}-export function initFormTabs() {- return callIfExists(window.initFormTabs);+function handlePrevTab() {+ switchToTab(state.currentTabIndex - 1);}export function switchToTab(index) {- return callIfExists(window.switchToTab, index);+ if (!state.tabs.length) return;+ if (index < 0 || index >= state.tabs.length) return;+ state.tabs.forEach((tab, idx) => tab.classList.toggle('active', idx === index));+ state.tabContents.forEach((content, idx) => content.classList.toggle('active', idx === index));+ state.currentTabIndex = index;+ const container = state.modal?.querySelector('.form-tabs');+ if (container) container.setAttribute('data-step', String(index));+ updateCompletedTabs();+ updateNavigationButtons();+ if (index === state.tabs.length - 1) {+ updateSummary();+ }}export function updateNavigationButtons() {- return callIfExists(window.updateNavigationButtons);+ if (!state.nextBtn || !state.prevBtn || !state.submitBtn) return;+ state.prevBtn.style.display = state.currentTabIndex === 0 ? 'none' : 'block';+ const isLast = state.currentTabIndex === state.tabs.length - 1;+ state.nextBtn.style.display = isLast ? 'none' : 'block';+ state.submitBtn.style.display = isLast ? 'block' : 'none';}export function updateCompletedTabs() {- return callIfExists(window.updateCompletedTabs);+ state.tabs.forEach((tab, idx) => {+ tab.classList.toggle('completed', idx < state.currentTabIndex);+ });+}++function markTabCompleted(index) {+ const tab = state.tabs[index];+ if (tab) tab.classList.add('completed');+}++export function validateTab(index) {+ const content = state.tabContents[index];+ if (!content) return true;+ let isValid = true;+ const controls = content.querySelectorAll('input, textarea, select');+ controls.forEach((control) => {+ removeValidationMessage(control);+ control.classList.remove('invalid');+ if (control.disabled || control.type === 'hidden') return;+ const value = control.value || '';+ if (control.hasAttribute('required') && !value.trim()) {+ isValid = false;+ markInvalid(control, window.i18next ? window.i18next.t('messages.please_fill_out_this_field') : 'Please fill out this field.');+ } else if (!control.checkValidity()) {+ isValid = false;+ markInvalid(control, control.validationMessage || (window.i18next ? window.i18next.t('messages.field_is_invalid') : 'This field is invalid.'));+ }+ });+ return isValid;+}++export function showValidationErrors(index) {+ const content = state.tabContents[index];+ if (!content) return;+ const firstInvalid = content.querySelector('.invalid');+ if (firstInvalid) firstInvalid.focus();+ showToast(window.i18next ? window.i18next.t('messages.correct_errors_in_tab') : 'Please correct the errors on this tab.', 'error', 4000);+}++function handleFormInput(event) {+ const target = event.target;+ if (!target || !state.form.contains(target)) return;+ if (target.classList.contains('invalid') && target.value.trim()) {+ target.classList.remove('invalid');+ removeValidationMessage(target);+ }+ if (!state.tabs.length || state.currentTabIndex === state.tabs.length - 1) {+ updateSummary();+ }}-export function validateTab(tabIndex) {- return callIfExists(window.validateTab, tabIndex);+function handleSerialContainerClick(event) {+ const addButton = event.target.closest('.add-serial-number');+ if (addButton) {+ event.preventDefault();+ addSerialNumberInput('');+ return;+ }+ const removeButton = event.target.closest('.remove-serial');+ if (removeButton) {+ event.preventDefault();+ const row = removeButton.closest('.serial-number-input');+ if (row && state.serialContainer && state.serialContainer.children.length > 1) {+ row.remove();+ }+ }}-export function showValidationErrors(tabIndex) {- return callIfExists(window.showValidationErrors, tabIndex);+function addSerialNumberInput(value = '') {+ if (!state.serialContainer) return;+ const isFirst = state.serialContainer.querySelectorAll('.serial-number-input').length === 0;+ const row = document.createElement('div');+ row.className = 'serial-number-input d-flex mb-2';+ const input = document.createElement('input');+ input.type = 'text';+ input.className = 'form-control';+ input.name = 'serial_numbers[]';+ input.placeholder = SERIAL_PLACEHOLDER();+ input.value = value || '';+ row.appendChild(input);+ const button = document.createElement('button');+ button.type = 'button';+ if (isFirst) {+ button.className = 'btn btn-sm btn-primary add-serial-number';+ button.innerHTML = `<i class="fas fa-plus"></i> ${ADD_SERIAL_LABEL()}`;+ } else {+ button.className = 'btn btn-sm btn-danger remove-serial';+ button.innerHTML = '<i class="fas fa-times"></i>';+ }+ row.appendChild(button);+ if (isFirst) {+ state.serialContainer.appendChild(row);+ } else {+ state.serialContainer.appendChild(row);+ }+}++export function handleLifetimeChange() {+ if (!state.isLifetimeCheckbox || !state.durationFields) return;+ const isLifetime = state.isLifetimeCheckbox.checked;+ const methodWrapper = document.getElementById('warrantyEntryMethod');+ if (isLifetime) {+ if (methodWrapper) methodWrapper.style.display = 'none';+ state.durationFields.style.display = 'none';+ if (state.exactDateField) state.exactDateField.style.display = 'none';+ clearDurationFields();+ if (state.exactDateInput) state.exactDateInput.value = '';+ } else {+ if (methodWrapper) methodWrapper.style.display = 'block';+ handleWarrantyMethodChange();+ }+ updateSummary();+}++export function handleWarrantyMethodChange() {+ const isLifetime = state.isLifetimeCheckbox?.checked;+ const useDuration = state.durationMethodRadio?.checked;+ if (isLifetime) {+ if (state.durationFields) state.durationFields.style.display = 'none';+ if (state.exactDateField) state.exactDateField.style.display = 'none';+ return;+ }+ if (useDuration) {+ if (state.durationFields) state.durationFields.style.display = 'block';+ if (state.exactDateField) state.exactDateField.style.display = 'none';+ if (state.exactDateInput) state.exactDateInput.value = '';+ } else {+ if (state.durationFields) state.durationFields.style.display = 'none';+ clearDurationFields();+ if (state.exactDateField) state.exactDateField.style.display = 'block';+ }+ updateSummary();}export function updateSummary() {- return callIfExists(window.updateSummary);+ if (!state.summary) return;+ const getValue = (id) => (document.getElementById(id)?.value || '').trim();+ setTextContent(state.summary.productName, getValue('productName') || '-');+ setTextContent(state.summary.productUrl, getValue('productUrl') || '-');++ const serialValues = Array.from(state.serialContainer?.querySelectorAll('input[name="serial_numbers[]"]') || [])+ .map((input) => input.value.trim())+ .filter(Boolean);+ if (state.summary.serialNumbers) {+ if (serialValues.length) {+ state.summary.serialNumbers.innerHTML = `<ul>${serialValues.map((sn) => `<li>${sn}</li>`).join('')}</ul>`;+ } else {+ state.summary.serialNumbers.textContent = window.i18next ? window.i18next.t('warranties.none') : 'None';+ }+ }++ const purchaseDate = getValue('purchaseDate');+ setTextContent(state.summary.purchaseDate, formatDisplayDate(purchaseDate));++ const isLifetime = state.isLifetimeCheckbox?.checked;+ if (state.summary.warrantyDuration) {+ if (isLifetime) {+ setTextContent(state.summary.warrantyDuration, window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime');+ } else if (state.durationMethodRadio?.checked) {+ const years = Number.parseInt(getValue('warrantyDurationYears'), 10) || 0;+ const months = Number.parseInt(getValue('warrantyDurationMonths'), 10) || 0;+ const days = Number.parseInt(getValue('warrantyDurationDays'), 10) || 0;+ const parts = [];+ if (years) parts.push(`${years} ${pluralize('warranties.year', 'year', years)}`);+ if (months) parts.push(`${months} ${pluralize('warranties.month', 'month', months)}`);+ if (days) parts.push(`${days} ${pluralize('warranties.day', 'day', days)}`);+ setTextContent(state.summary.warrantyDuration, parts.length ? parts.join(', ') : '-');+ } else if (state.exactDateInput?.value) {+ setTextContent(state.summary.warrantyDuration, formatDisplayDate(state.exactDateInput.value));+ } else {+ setTextContent(state.summary.warrantyDuration, '-');+ }+ }++ const warrantyTypeSelect = document.getElementById('warrantyType');+ const warrantyTypeCustom = document.getElementById('warrantyTypeCustom');+ let warrantyTypeText = window.i18next ? window.i18next.t('warranties.not_specified') : 'Not specified';+ if (warrantyTypeSelect?.value === 'other' && warrantyTypeCustom?.value.trim()) {+ warrantyTypeText = warrantyTypeCustom.value.trim();+ } else if (warrantyTypeSelect?.value) {+ warrantyTypeText = warrantyTypeSelect.value;+ }+ setTextContent(state.summary.warrantyType, warrantyTypeText);++ const currencySelect = document.getElementById('currency');+ const purchasePrice = getValue('purchasePrice');+ if (state.summary.purchasePrice) {+ if (purchasePrice) {+ const code = currencySelect?.value || getCurrencyCode();+ const symbol = code ? getCurrencySymbolByCode(code) : getCurrencySymbol();+ const position = getCurrencyPosition();+ state.summary.purchasePrice.innerHTML = formatCurrencyHTML(purchasePrice, symbol, position);+ } else {+ state.summary.purchasePrice.textContent = window.i18next ? window.i18next.t('warranties.not_specified') : 'Not specified';+ }+ }++ updateFileSummary(state.summary.productPhoto, state.fileInputs.productPhoto);+ updateFileSummary(state.summary.invoice, state.fileInputs.invoice, getValue('invoiceUrl'));+ updateFileSummary(state.summary.manual, state.fileInputs.manual, getValue('manualUrl'));+ updateFileSummary(state.summary.otherDocument, state.fileInputs.other, getValue('otherDocumentUrl'));++ renderSummaryTags();++ setTextContent(state.summary.vendor, getValue('vendor') || '-');}-export function handleFormSubmit(event) {- return callIfExists(window.handleFormSubmit, event);+function renderSummaryTags() {+ if (!state.summary.tags) return;+ const tags = getSelectedTags();+ state.summary.tags.innerHTML = '';+ if (!tags.length) {+ state.summary.tags.textContent = window.i18next+ ? window.i18next.t('tags.no_selected', { defaultValue: 'No tags selected' })+ : 'No tags selected';+ return;+ }+ tags.forEach((tag) => {+ const span = document.createElement('span');+ span.className = 'tag';+ span.style.backgroundColor = tag.color;+ span.textContent = tag.name;+ state.summary.tags.appendChild(span);+ });+}++let isSubmitting = false;++export async function handleFormSubmit(event) {+ event.preventDefault();++ // Prevent double submission+ if (isSubmitting) {+ console.log('[addWarrantyForm] Submission already in progress, ignoring duplicate submit');+ return;+ }++ if (!state.form) return;++ for (let i = 0; i < state.tabContents.length; i += 1) {+ if (!validateTab(i)) {+ switchToTab(i);+ showValidationErrors(i);+ return;+ }+ }+ if (!validateWarrantySelection()) return;++ isSubmitting = true;++ const invoiceStorage = getStorageOption('invoice');+ const manualStorage = getStorageOption('manual');+ const formData = new FormData();+ appendBasicFields(formData);+ appendSerialNumbers(formData);+ appendTagIds(formData);+ appendDocumentUrls(formData);+ appendFiles(formData, { invoiceStorage, manualStorage });+ appendPaperlessSelections(formData, { invoiceStorage, manualStorage });+ appendWarrantyMethod(formData);+ const invoiceFileInput = state.fileInputs.invoice.input;+ const manualFileInput = state.fileInputs.manual.input;+ const invoiceFile = invoiceFileInput?.files?.[0] || null;+ const manualFile = manualFileInput?.files?.[0] || null;++ try {+ showLoadingSpinner();+ const uploads = await processPaperlessUploads(formData);+ Object.entries(uploads || {}).forEach(([key, value]) => formData.append(key, value));+ console.log('[addWarrantyForm] Creating warranty with tags:', getSelectedTags());+ const created = await createWarranty(formData);+ console.log('[addWarrantyForm] Warranty created:', created);+ hideLoadingSpinner();+ showToast(window.i18next ? window.i18next.t('messages.warranty_added_successfully') : 'Warranty added successfully', 'success');+ state.modal?.classList.remove('active');+ resetAddWarrantyWizard();+ console.log('[addWarrantyForm] Loading warranties after creation...');+ await loadWarranties(true);+ console.log('[addWarrantyForm] Applying filters...');+ applyFilters();+ handleAutoLink(created?.id, {+ invoice: invoiceStorage === 'paperless' ? invoiceFile : null,+ manual: manualStorage === 'paperless' ? manualFile : null,+ });+ } catch (error) {+ hideLoadingSpinner();+ console.error('[addWarrantyForm] Failed to save warranty', error);+ showToast(error?.message || (window.i18next ? window.i18next.t('messages.failed_to_add_warranty') : 'Failed to add warranty'), 'error');+ } finally {+ isSubmitting = false;+ console.log('[addWarrantyForm] Submission complete, flag reset');+ }}export function resetAddWarrantyWizard() {- return callIfExists(window.resetAddWarrantyWizard);+ if (!state.form) return;+ console.log('[addWarrantyForm] Resetting wizard, tags before reset:', getSelectedTags());+ state.form.reset();+ setSelectedTags([]);+ if (Array.isArray(window.selectedTags)) {+ window.selectedTags = [];+ }+ console.log('[addWarrantyForm] Tags after reset:', getSelectedTags());+ renderSelectedTags();+ if (state.serialContainer) {+ state.serialContainer.innerHTML = '';+ addSerialNumberInput('');+ }+ Object.values(state.fileInputs).forEach((entry) => {+ if (entry.label) entry.label.textContent = '';+ if (entry.previewWrapper) entry.previewWrapper.style.display = 'none';+ });+ clearPaperlessSelection('invoice');+ clearPaperlessSelection('manual');+ clearPaperlessSelection('productPhoto');+ clearPaperlessSelection('otherDocument');+ const invoiceLocal = document.querySelector('input[name="invoiceStorage"][value="local"]');+ const manualLocal = document.querySelector('input[name="manualStorage"][value="local"]');+ if (invoiceLocal) invoiceLocal.checked = true;+ if (manualLocal) manualLocal.checked = true;+ if (state.isLifetimeCheckbox) state.isLifetimeCheckbox.checked = false;+ if (state.durationMethodRadio) state.durationMethodRadio.checked = true;+ if (state.exactDateMethodRadio) state.exactDateMethodRadio.checked = false;+ clearDurationFields();+ if (state.exactDateInput) state.exactDateInput.value = '';+ clearValidationState();+ state.currentTabIndex = 0;+ refreshTabs();+ switchToTab(0);+ updateCurrencyDefaults();+ updateSummary();}-export function handleLifetimeChange(event) {- return callIfExists(window.handleLifetimeChange, event);+function openModal() {+ resetAddWarrantyWizard();+ updateCurrencyDefaults();+ state.modal?.classList.add('active');}-export function handleWarrantyMethodChange() {- return callIfExists(window.handleWarrantyMethodChange);+function closeModal() {+ state.modal?.classList.remove('active');+ resetAddWarrantyWizard();}-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;+function updateCurrencyDefaults() {+ const currencySelect = document.getElementById('currency');+ const preferred = getCurrencyCode();+ if (currencySelect && preferred) {+ currencySelect.value = preferred;+ }+ const symbol = getCurrencySymbol();+ const position = getCurrencyPosition();+ updateFormCurrencyPosition(symbol, position);+}++function appendBasicFields(formData) {+ const getValue = (id) => (document.getElementById(id)?.value || '').trim();+ const productName = getValue('productName');+ const purchaseDate = getValue('purchaseDate');+ if (!productName) throw new Error(window.i18next ? window.i18next.t('messages.product_name_required') : 'Product name is required');+ if (!purchaseDate) throw new Error(window.i18next ? window.i18next.t('messages.purchase_date_required') : 'Purchase date is required');+ formData.append('product_name', productName);+ formData.append('purchase_date', purchaseDate);+ let productUrl = getValue('productUrl');+ if (productUrl && !productUrl.startsWith('http://') && !productUrl.startsWith('https://')) {+ productUrl = `https://${productUrl}`;+ }+ formData.append('product_url', productUrl || '');+ formData.append('model_number', getValue('modelNumber'));+ formData.append('vendor', getValue('vendor'));++ const warrantyTypeSelect = document.getElementById('warrantyType');+ const warrantyTypeCustom = document.getElementById('warrantyTypeCustom');+ let warrantyTypeValue = '';+ if (warrantyTypeSelect) {+ if (warrantyTypeSelect.value === 'other' && warrantyTypeCustom?.value.trim()) {+ warrantyTypeValue = warrantyTypeCustom.value.trim();+ } else {+ warrantyTypeValue = warrantyTypeSelect.value || '';+ }}+ formData.append('warranty_type', warrantyTypeValue);+ formData.append('currency', document.getElementById('currency')?.value || '');+ formData.append('purchase_price', getValue('purchasePrice'));+ formData.append('notes', (document.getElementById('notes')?.value || '').trim());}-// Backward compatibility on window if needed+function appendSerialNumbers(formData) {+ const serialValues = Array.from(state.serialContainer?.querySelectorAll('input[name="serial_numbers[]"]') || [])+ .map((input) => input.value.trim())+ .filter(Boolean);+ formData.delete('serial_numbers[]');+ if (!serialValues.length) return;+ serialValues.forEach((value) => formData.append('serial_numbers[]', value));+}++function appendTagIds(formData) {+ const tags = getSelectedTags() || [];+ console.log('[addWarrantyForm] Selected tags:', tags);+ const ids = tags.map((tag) => tag.id);+ console.log('[addWarrantyForm] Tag IDs being sent:', ids);+ formData.append('tag_ids', JSON.stringify(ids));+}++function appendDocumentUrls(formData) {+ formData.append('invoice_url', document.getElementById('invoiceUrl')?.value || '');+ formData.append('manual_url', document.getElementById('manualUrl')?.value || '');+ formData.append('other_document_url', document.getElementById('otherDocumentUrl')?.value || '');+}++function appendFiles(formData, storageOptions = {}) {+ const appendFile = (entry, key) => {+ if (entry?.input?.files?.[0]) {+ formData.append(key, entry.input.files[0]);+ }+ };+ appendFile(state.fileInputs.productPhoto, 'product_photo');+ if (storageOptions.invoiceStorage !== 'paperless') {+ appendFile(state.fileInputs.invoice, 'invoice');+ }+ if (storageOptions.manualStorage !== 'paperless') {+ appendFile(state.fileInputs.manual, 'manual');+ }+ appendFile(state.fileInputs.other, 'other_document');+}++function appendPaperlessSelections(formData, storageOptions = {}) {+ const appendHidden = (id, key) => {+ const hidden = document.getElementById(id);+ if (hidden && hidden.value) formData.append(key, hidden.value);+ };+ appendHidden('selectedPaperlessInvoice', 'paperless_invoice_id');+ appendHidden('selectedPaperlessManual', 'paperless_manual_id');+ appendHidden('selectedPaperlessProductPhoto', 'paperless_photo_id');+ appendHidden('selectedPaperlessOtherDocument', 'paperless_other_id');+ const invoiceStorage = storageOptions.invoiceStorage || 'local';+ const manualStorage = storageOptions.manualStorage || 'local';+ formData.set('invoiceStorage', invoiceStorage);+ formData.set('manualStorage', manualStorage);+}++function appendWarrantyMethod(formData) {+ const isLifetime = state.isLifetimeCheckbox?.checked;+ formData.append('is_lifetime', String(Boolean(isLifetime)));+ if (isLifetime) {+ formData.append('warranty_duration_years', 0);+ formData.append('warranty_duration_months', 0);+ formData.append('warranty_duration_days', 0);+ return;+ }+ const useDuration = state.durationMethodRadio?.checked;+ if (useDuration) {+ const years = Number.parseInt(document.getElementById('warrantyDurationYears')?.value || '0', 10) || 0;+ const months = Number.parseInt(document.getElementById('warrantyDurationMonths')?.value || '0', 10) || 0;+ const days = Number.parseInt(document.getElementById('warrantyDurationDays')?.value || '0', 10) || 0;+ if (years === 0 && months === 0 && days === 0) {+ throw new Error(window.i18next ? window.i18next.t('messages.warranty_duration_required') : 'Warranty duration is required');+ }+ formData.append('warranty_duration_years', years);+ formData.append('warranty_duration_months', months);+ formData.append('warranty_duration_days', days);+ formData.delete('exact_expiration_date');+ } else if (state.exactDateInput?.value) {+ const expiration = state.exactDateInput.value;+ const purchase = document.getElementById('purchaseDate')?.value;+ if (purchase && expiration <= purchase) {+ throw new Error(window.i18next ? window.i18next.t('messages.expiration_date_after_purchase_date') : 'Expiration date must be after purchase date');+ }+ formData.append('exact_expiration_date', expiration);+ formData.append('warranty_duration_years', 0);+ formData.append('warranty_duration_months', 0);+ formData.append('warranty_duration_days', 0);+ } else {+ throw new Error(window.i18next ? window.i18next.t('messages.exact_expiration_date_required') : 'Exact expiration date is required');+ }+}++function validateWarrantySelection() {+ const isLifetime = state.isLifetimeCheckbox?.checked;+ if (isLifetime) return true;+ const useDuration = state.durationMethodRadio?.checked;+ if (useDuration) {+ const years = Number.parseInt(document.getElementById('warrantyDurationYears')?.value || '0', 10) || 0;+ const months = Number.parseInt(document.getElementById('warrantyDurationMonths')?.value || '0', 10) || 0;+ const days = Number.parseInt(document.getElementById('warrantyDurationDays')?.value || '0', 10) || 0;+ if (years === 0 && months === 0 && days === 0) {+ showToast(window.i18next ? window.i18next.t('messages.warranty_duration_required') : 'Warranty duration is required', 'error');+ state.durationFields?.classList.add('invalid-duration');+ switchToTab(1);+ return false;+ }+ state.durationFields?.classList.remove('invalid-duration');+ return true;+ }+ if (state.exactDateInput?.value) {+ const purchase = document.getElementById('purchaseDate')?.value;+ if (purchase && state.exactDateInput.value <= purchase) {+ showToast(window.i18next ? window.i18next.t('messages.expiration_date_after_purchase_date') : 'Expiration date must be after purchase date', 'error');+ switchToTab(1);+ state.exactDateInput.focus();+ return false;+ }+ return true;+ }+ showToast(window.i18next ? window.i18next.t('messages.exact_expiration_date_required') : 'Exact expiration date is required', 'error');+ switchToTab(1);+ return false;+}++function handleAutoLink(warrantyId, files = {}) {+ if (!warrantyId) return;+ const documentTypes = [];+ const fileInfo = {};+ if (files.invoice) {+ documentTypes.push('invoice');+ fileInfo.invoice = files.invoice.name;+ }+ if (files.manual) {+ documentTypes.push('manual');+ fileInfo.manual = files.manual.name;+ }+ if (!documentTypes.length) return;+ autoLinkRecentDocuments(warrantyId, documentTypes, 10, 10000, fileInfo);+}++function updateFileDisplay(entry) {+ if (!entry || !entry.input) return;+ const file = entry.input.files?.[0];+ if (entry.label) entry.label.textContent = file ? file.name : '';+ if (entry.previewWrapper && entry.previewImage) {+ if (file && file.type.startsWith('image/')) {+ const reader = new FileReader();+ reader.onload = (e) => {+ entry.previewImage.src = e.target.result;+ entry.previewWrapper.style.display = 'block';+ };+ reader.readAsDataURL(file);+ } else {+ entry.previewWrapper.style.display = 'none';+ }+ }+ updateSummary();+}++function markInvalid(control, message) {+ control.classList.add('invalid');+ let messageElement = control.nextElementSibling;+ if (!messageElement || !messageElement.classList.contains('validation-message')) {+ messageElement = document.createElement('div');+ messageElement.className = 'validation-message';+ control.parentNode.insertBefore(messageElement, control.nextSibling);+ }+ messageElement.textContent = message;+}++function removeValidationMessage(control) {+ if (!control) return;+ const messageElement = control.nextElementSibling;+ if (messageElement && messageElement.classList.contains('validation-message')) {+ messageElement.remove();+ }+}++function clearDurationFields() {+ const years = document.getElementById('warrantyDurationYears');+ const months = document.getElementById('warrantyDurationMonths');+ const days = document.getElementById('warrantyDurationDays');+ if (years) years.value = '';+ if (months) months.value = '';+ if (days) days.value = '';+}++function clearValidationState() {+ state.form.querySelectorAll('.invalid').forEach((el) => el.classList.remove('invalid'));+ state.form.querySelectorAll('.validation-message').forEach((el) => el.remove());+ state.durationFields?.classList.remove('invalid-duration');+}++function setTextContent(element, text) {+ if (element) element.textContent = text ?? '';+}++function formatDisplayDate(value) {+ if (!value) return '-';+ const [year, month, day] = value.split('-').map((part) => Number.parseInt(part, 10));+ if (Number.isNaN(year) || Number.isNaN(month) || Number.isNaN(day)) return value;+ const date = new Date(Date.UTC(year, month - 1, day));+ const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];+ return `${monthNames[date.getUTCMonth()]} ${day}, ${year}`;+}++function pluralize(key, fallback, count) {+ if (window.i18next) {+ return window.i18next.t(key, { count });+ }+ return `${fallback}${count !== 1 ? 's' : ''}`;+}++function updateFileSummary(summaryElement, entry, urlValue = '') {+ if (!summaryElement) return;+ if (entry?.input?.files?.[0]) {+ summaryElement.textContent = entry.input.files[0].name;+ } else if (urlValue) {+ summaryElement.textContent = `URL: ${urlValue}`;+ } else {+ summaryElement.textContent = window.i18next ? window.i18next.t('warranties.not_specified') : 'Not specified';+ }+}++// Backward compatibility during transitionif (typeof window !== 'undefined') {window.addWarrantyForm = {init,- initFormTabs,switchToTab,updateNavigationButtons,updateCompletedTabs,@@ -76,8 +868,6 @@ if (typeof window !== 'undefined') {handleFormSubmit,resetAddWarrantyWizard,handleLifetimeChange,- handleWarrantyMethodChange+ handleWarrantyMethodChange,};}--diff --git a/frontend/js/components/claims.js b/frontend/js/components/claims.jsindex 22b2d46..6dd119e 100644--- a/frontend/js/components/claims.js+++ b/frontend/js/components/claims.js@@ -1,3 +1,399 @@+import authService from '../services/authService.js';+import { getWarranties, getIsGlobalView } from '../store.js';+import { showToast } from './ui.js';+import { formatDate } from '../lib/dates.js';++const state = {+ currentWarrantyId: null,+ claims: [],+ canEdit: false,+};++const dom = {+ claimsModal: null,+ claimFormModal: null,+ claimsListBody: null,+ addClaimBtn: null,+ claimForm: null,+ warrantyClaimInfo: null,+ editClaimId: null,+ claimFormTitle: null,+};++const t = (key, fallback) => {+ try {+ if (window.i18next?.t) return window.i18next.t(key);+ } catch (error) {+ console.warn('[claims] translation failed', key, error);+ }+ return fallback;+};++const formatDateSafe = (value) => {+ const date = value instanceof Date ? value : value ? new Date(value) : null;+ if (!date || Number.isNaN(date.getTime())) return 'N/A';+ return formatDate(date);+};++const escapeHtml = (text = '') => {+ if (typeof text !== 'string') return '';+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+};++function queryDom() {+ dom.claimsModal = document.getElementById('claimsModal');+ dom.claimFormModal = document.getElementById('claimFormModal');+ dom.claimsListBody = document.getElementById('claimsListBody');+ dom.addClaimBtn = document.getElementById('addClaimBtn');+ dom.claimForm = document.getElementById('claimForm');+ dom.warrantyClaimInfo = document.getElementById('warrantyClaimInfo');+ dom.editClaimId = document.getElementById('editClaimId');+ dom.claimFormTitle = document.getElementById('claimFormTitle');+}++function getToken() {+ return authService.getToken?.() || window.auth?.getToken?.() || localStorage.getItem('auth_token');+}++function bindCloseButtons(modal, handler) {+ if (!modal || modal._claimsCloseBound) return;+ modal.querySelectorAll('[data-dismiss="modal"]').forEach((btn) => {+ btn.addEventListener('click', handler);+ });+ modal._claimsCloseBound = true;+}++function bindClaimsListDelegation() {+ const list = document.getElementById('warrantiesList');+ if (!list || list._claimsLinkDelegated) return;+ if (list._wlcDelegated) return;+ list.addEventListener('click', (event) => {+ const claimsLink = event.target.closest('.claims-link');+ if (claimsLink) {+ event.preventDefault();+ const id = parseInt(claimsLink.dataset.id, 10);+ if (Number.isFinite(id)) openClaimsModal(id);+ }+ });+ list._claimsLinkDelegated = true;+}++function bindClaimsListBodyActions() {+ if (!dom.claimsListBody || dom.claimsListBody._claimsActionsBound) return;+ dom.claimsListBody.addEventListener('click', (event) => {+ if (!state.canEdit) return;+ const editBtn = event.target.closest('.edit-claim-btn');+ if (editBtn) {+ const claimId = parseInt(editBtn.dataset.claimId, 10);+ const claim = state.claims.find((c) => c.id === claimId);+ if (claim) openClaimFormModal(claim);+ return;+ }+ const deleteBtn = event.target.closest('.delete-claim-btn');+ if (deleteBtn) {+ const claimId = parseInt(deleteBtn.dataset.claimId, 10);+ const confirmMessage =+ t('claims.confirm_delete_claim', 'Are you sure you want to delete this claim?');+ if (window.confirm(confirmMessage)) {+ deleteClaim(claimId);+ }+ }+ });+ dom.claimsListBody._claimsActionsBound = true;+}++function updateAddClaimVisibility() {+ if (dom.addClaimBtn) {+ dom.addClaimBtn.style.display = state.canEdit ? 'inline-block' : 'none';+ }+}++function updateWarrantyInfo(warranty) {+ if (!dom.warrantyClaimInfo) return;+ if (!warranty) {+ dom.warrantyClaimInfo.textContent = '';+ return;+ }+ const vendorLabel = warranty.vendor || t('claims.unknown_vendor', 'Unknown Vendor');+ const expiresLabel = `${t('claims.expires_label', 'Expires')}: ${formatDateSafe(warranty.expiration_date)}`;+ const statusClass = warranty.status || 'unknown';+ const statusText = warranty.statusText || t('warranties.unknown_status', 'Unknown Status');+ dom.warrantyClaimInfo.innerHTML = `+ <div class="warranty-info-card">+ <h4>${warranty.product_name || t('warranties.unnamed_product', 'Unnamed Product')}</h4>+ <div class="warranty-details">+ <span><i class="fas fa-building"></i> ${vendorLabel}</span>+ <span><i class="fas fa-calendar"></i> ${expiresLabel}</span>+ <span class="warranty-status status-${statusClass}">+ ${statusText}+ </span>+ </div>+ </div>+ `;+}++function ensureFormSubmissionHandler() {+ if (!dom.claimForm || dom.claimForm._claimsSubmitBound) return;+ dom.claimForm.addEventListener('submit', handleClaimFormSubmit);+ dom.claimForm._claimsSubmitBound = true;+}++function ensureAddClaimHandler() {+ if (!dom.addClaimBtn || dom.addClaimBtn._claimsAddBound) return;+ dom.addClaimBtn.addEventListener('click', () => openClaimFormModal());+ dom.addClaimBtn._claimsAddBound = true;+}++function renderClaims() {+ if (!dom.claimsListBody) return;+ if (!state.claims.length) {+ const message = state.canEdit+ ? t('claims.no_claims_message', 'Click "Add New Claim" to get started')+ : t('claims.no_claims_view_only', 'No claims have been filed for this warranty');+ dom.claimsListBody.innerHTML = `+ <div class="no-claims-message" style="text-align: center; padding: 40px;">+ <i class="fas fa-clipboard-list" style="font-size: 3rem; color: var(--medium-gray); margin-bottom: 1rem;"></i>+ <h4>${t('claims.no_claims_yet', 'No Claims Yet')}</h4>+ <p>${message}</p>+ </div>+ `;+ return;+}+ const claimsHtml = state.claims+ .map((claim) => {+ const statusClass = claim.status ? claim.status.toLowerCase().replace(/\s+/g, '-') : 'unknown';+ const resolutionDateHtml =+ claim.resolution_date && claim.resolution_date.trim()+ ? `<span style="margin-left: 10px;"><i class="fas fa-check-circle"></i> ${t('claims.resolved_label', 'Resolved')}: ${formatDateSafe(claim.resolution_date)}</span>`+ : '';+ const actionsHtml = state.canEdit+ ? `+ <button class="btn btn-sm btn-secondary edit-claim-btn" data-claim-id="${claim.id}">+ <i class="fas fa-edit"></i> ${t('actions.edit', 'Edit')}+ </button>+ <button class="btn btn-sm btn-danger delete-claim-btn" data-claim-id="${claim.id}">+ <i class="fas fa-trash"></i> ${t('actions.delete', 'Delete')}+ </button>+ `+ : `+ <span class="claim-readonly-indicator" style="color: var(--medium-gray); font-size: 0.9em;">+ <i class="fas fa-eye"></i> ${t('claims.view_only', 'View Only')}+ </span>+ `;+ return `+ <div class="claim-item" data-claim-id="${claim.id}">+ <div class="claim-header">+ <div class="claim-info">+ <div class="claim-title">+ ${claim.claim_number ? `<strong>${escapeHtml(claim.claim_number)}</strong>` : `<strong>${t('claims.claim_number_label', 'Claim #')}${claim.id}</strong>`}+ <span class="claim-status-badge claim-status-${statusClass}">+ ${escapeHtml(claim.status || t('claims.status_unknown', 'Unknown'))}+ </span>+ </div>+ <div class="claim-date">+ <i class="fas fa-calendar"></i> ${formatDateSafe(claim.claim_date)}+ ${resolutionDateHtml}+ </div>+ </div>+ <div class="claim-actions">+ ${actionsHtml}+ </div>+ </div>+ ${claim.description ? `<div class="claim-description">${escapeHtml(claim.description)}</div>` : ''}+ ${claim.resolution ? `<div class="claim-resolution"><strong>${t('claims.resolution_label', 'Resolution')}:</strong> ${escapeHtml(claim.resolution)}</div>` : ''}+ </div>+ `;+ })+ .join('');+ dom.claimsListBody.innerHTML = claimsHtml;+}++async function loadClaims(warrantyId) {+ if (!dom.claimsListBody) return;+ dom.claimsListBody.innerHTML = `+ <div class="loading-message" style="text-align: center; padding: 20px;">+ <i class="fas fa-spinner fa-spin"></i> ${t('claims.loading', 'Loading claims...')}+ </div>+ `;+ try {+ const token = getToken();+ if (!token) throw new Error(t('messages.authentication_required', 'Authentication required'));+ const response = await fetch(`/api/warranties/${warrantyId}/claims`, {+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json',+ },+ });+ if (!response.ok) throw new Error(t('claims.failed_to_load', 'Failed to load claims'));+ state.claims = await response.json();+ renderClaims();+ } catch (error) {+ console.error('[claims] loadClaims failed', error);+ dom.claimsListBody.innerHTML = `+ <div class="error-message" style="text-align: center; padding: 20px; color: var(--danger-color);">+ <i class="fas fa-exclamation-triangle"></i> ${t('claims.failed_to_load', 'Failed to load claims')}+ </div>+ `;+ }+}++function openClaimFormModal(claim = null) {+ if (!dom.claimFormModal) return;+ if (dom.claimFormTitle) {+ dom.claimFormTitle.textContent = claim+ ? t('claims.edit_claim', 'Edit Claim')+ : t('claims.add_new_claim', 'Add New Claim');+ }+ if (dom.claimForm) dom.claimForm.reset();+ if (dom.editClaimId) dom.editClaimId.value = claim ? claim.id : '';++ const fields = {+ claimDate: claim?.claim_date || new Date().toISOString().split('T')[0],+ claimStatus: claim?.status || 'Submitted',+ claimNumber: claim?.claim_number || '',+ claimDescription: claim?.description || '',+ claimResolution: claim?.resolution || '',+ resolutionDate: claim?.resolution_date || '',+ };+ Object.entries(fields).forEach(([id, value]) => {+ const input = document.getElementById(id);+ if (input) input.value = value || '';+ });+ dom.claimFormModal.classList.add('active');+}++async function handleClaimFormSubmit(event) {+ if (event) event.preventDefault();+ if (!dom.claimForm || !state.currentWarrantyId) return;+ try {+ const token = getToken();+ if (!token) throw new Error(t('messages.authentication_required', 'Authentication required'));+ const formData = new FormData(dom.claimForm);+ const claimId = dom.editClaimId?.value;+ const payload = {+ claim_date: formData.get('claim_date') || null,+ status: formData.get('status') || null,+ claim_number: formData.get('claim_number') || null,+ description: formData.get('description') || null,+ resolution: formData.get('resolution') || null,+ resolution_date: formData.get('resolution_date') || null,+ };+ const isEdit = Boolean(claimId);+ const url = isEdit+ ? `/api/warranties/${state.currentWarrantyId}/claims/${claimId}`+ : `/api/warranties/${state.currentWarrantyId}/claims`;+ const response = await fetch(url, {+ method: isEdit ? 'PUT' : 'POST',+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(payload),+ });+ if (!response.ok) {+ const error = await response.json().catch(() => ({}));+ throw new Error(error.error || t('claims.failed_to_save', 'Failed to save claim'));+ }+ showToast(+ isEdit ? t('claims.claim_updated_successfully', 'Claim updated successfully') : t('claims.claim_created_successfully', 'Claim created successfully'),+ 'success',+ );+ closeClaimFormModal();+ await loadClaims(state.currentWarrantyId);+ } catch (error) {+ console.error('[claims] save failed', error);+ showToast(error.message || t('claims.failed_to_save', 'Failed to save claim'), 'error');+ }+}++async function deleteClaim(claimId) {+ if (!state.currentWarrantyId) return;+ try {+ const token = getToken();+ if (!token) throw new Error(t('messages.authentication_required', 'Authentication required'));+ const response = await fetch(`/api/warranties/${state.currentWarrantyId}/claims/${claimId}`, {+ method: 'DELETE',+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json',+ },+ });+ if (!response.ok) {+ const error = await response.json().catch(() => ({}));+ throw new Error(error.error || t('claims.failed_to_delete', 'Failed to delete claim'));+ }+ showToast(t('claims.claim_deleted_successfully', 'Claim deleted successfully'), 'success');+ await loadClaims(state.currentWarrantyId);+ } catch (error) {+ console.error('[claims] delete failed', error);+ showToast(error.message || t('claims.failed_to_delete', 'Failed to delete claim'), 'error');+ }+}++export function closeClaimsModal() {+ if (dom.claimsModal) dom.claimsModal.classList.remove('active');+ state.currentWarrantyId = null;+ state.claims = [];+ state.canEdit = false;+ if (dom.claimsListBody) dom.claimsListBody.innerHTML = '';+}++export function closeClaimFormModal() {+ if (dom.claimFormModal) dom.claimFormModal.classList.remove('active');+ if (dom.claimForm) dom.claimForm.reset();+ if (dom.editClaimId) dom.editClaimId.value = '';+}++export async function openClaimsModal(warrantyId) {+ queryDom();+ if (!dom.claimsModal) {+ console.warn('[claims] claims modal not found');+ return;+ }+ const warranty = getWarranties().find((w) => w.id === warrantyId);+ if (!warranty) {+ showToast(t('claims.warranty_not_found', 'Warranty not found'), 'error');+ return;+ }+ state.currentWarrantyId = warrantyId;+ const currentUser = authService.getCurrentUser?.() || null;+ const isAdmin = Boolean(currentUser?.is_admin);+ const globalView = getIsGlobalView();+ if (typeof warranty.permissions?.canEdit === 'boolean') {+ state.canEdit = warranty.permissions.canEdit;+ } else {+ state.canEdit = !globalView || warranty.user_id === currentUser?.id || isAdmin;+ }+ updateAddClaimVisibility();+ updateWarrantyInfo(warranty);+ dom.claimsModal.classList.add('active');+ await loadClaims(warrantyId);+}++export function init() {+ queryDom();+ ensureAddClaimHandler();+ ensureFormSubmissionHandler();+ bindCloseButtons(dom.claimsModal, closeClaimsModal);+ bindCloseButtons(dom.claimFormModal, closeClaimFormModal);+ bindClaimsListDelegation();+ bindClaimsListBodyActions();+}++if (typeof window !== 'undefined') {+ window.components = window.components || {};+ window.components.claims = {+ init,+ openClaimsModal,+ closeClaimsModal,+ closeClaimFormModal,+ };+ window.openClaimsModal = openClaimsModal;+ window.closeClaimsModal = closeClaimsModal;+ window.closeClaimFormModal = closeClaimFormModal;+}function el(tag, className, text) {const e = document.createElement(tag);if (className) e.className = className;diff --git a/frontend/js/components/editModal.js b/frontend/js/components/editModal.jsindex ea4b70c..17ec25b 100644--- a/frontend/js/components/editModal.js+++ b/frontend/js/components/editModal.js@@ -1,5 +1,11 @@// Edit modal helper components (DOM-based, no innerHTML templates)import { updateWarranty } from '../services/apiService.js';+import { showToast, showLoadingSpinner, hideLoadingSpinner } from './ui.js';+import { autoLinkRecentDocuments, processEditPaperlessUploads, loadSecureImages, clearPaperlessSelection } from './paperless.js';+import { loadWarranties, applyFilters } from '../controllers/warrantyListController.js';+import { getCurrentWarrantyId, setCurrentWarrantyId, getEditSelectedTags, setEditSelectedTags } from '../store.js';+import { renderEditTagsList, renderEditSelectedTags, loadTags, openTagManagementModal } from './tagManager.js';+import { loadCurrencies } from '../lib/currency.js';function createElement(tag, className, text) {const el = document.createElement(tag);@@ -237,25 +243,314 @@ export function renderCurrentOther(element, deleteBtn, warranty, i18n = window.i}}-// Expose globally-if (typeof window !== 'undefined') {- window.components = window.components || {};- window.components.editModal = {- renderSerialNumbers,- renderCurrentInvoice,- renderCurrentManual,- renderCurrentPhoto,- renderCurrentOther,- saveWarranty,- };+const editState = {+ initialized: false,+ modal: null,+ form: null,+ tabs: [],+ contents: [],+ tagSearch: null,+ tagList: null,+};++function ensureInitialized() {+ if (editState.initialized) return;+ editState.modal = document.getElementById('editModal');+ editState.form = document.getElementById('editWarrantyForm');+ if (!editState.modal || !editState.form) return;+ editState.tabs = Array.from(editState.modal.querySelectorAll('.edit-tab-btn'));+ editState.contents = Array.from(editState.modal.querySelectorAll('.edit-tab-content'));+ editState.tabs.forEach((btn) => {+ if (btn._editBound) return;+ btn.addEventListener('click', () => activateTab(btn.dataset.tab));+ btn._editBound = true;+ });+ editState.tagSearch = document.getElementById('editTagSearch');+ editState.tagList = document.getElementById('editTagsList');+ if (editState.tagSearch && !editState.tagSearch._editBound) {+ editState.tagSearch.addEventListener('focus', () => renderEditTagsList(editState.tagSearch.value));+ editState.tagSearch.addEventListener('input', () => renderEditTagsList(editState.tagSearch.value));+ document.addEventListener('click', (event) => {+ if (!editState.tagSearch.contains(event.target) && !editState.tagList?.contains(event.target)) {+ if (editState.tagList) editState.tagList.classList.remove('show');+ }+ });+ editState.tagSearch._editBound = true;+ }+ const manageBtn = document.getElementById('editManageTagsBtn');+ if (manageBtn && !manageBtn._editBound) {+ manageBtn.addEventListener('click', (event) => {+ event.preventDefault();+ openTagManagementModal();+ });+ manageBtn._editBound = true;+ }+ bindFileInput('editProductPhoto', 'editProductPhotoFileName', 'editProductPhotoPreview', 'editProductPhotoImg');+ bindFileInput('editInvoice', 'editFileName');+ bindFileInput('editManual', 'editManualFileName');+ bindFileInput('editOtherDocument', 'editOtherDocumentFileName');+ const lifetimeToggle = document.getElementById('editIsLifetime');+ if (lifetimeToggle && !lifetimeToggle._editBound) {+ lifetimeToggle.addEventListener('change', applyLifetimeState);+ lifetimeToggle._editBound = true;+ }+ ['editDurationMethod', 'editExactDateMethod'].forEach((id) => {+ const radio = document.getElementById(id);+ if (radio && !radio._editBound) {+ radio.addEventListener('change', applyWarrantyMethodState);+ radio._editBound = true;+ }+ });+ const closeButtons = editState.modal.querySelectorAll('[data-dismiss="modal"], .close-btn');+ closeButtons.forEach((btn) => {+ if (btn._editBound) return;+ btn.addEventListener('click', (event) => {+ event.preventDefault();+ closeEditModal();+ });+ btn._editBound = true;+ });+ editState.initialized = true;+}++function activateTab(tabId) {+ if (!tabId) return;+ editState.tabs.forEach((btn) => btn.classList.toggle('active', btn.dataset.tab === tabId));+ editState.contents.forEach((content) => content.classList.toggle('active', content.id === tabId));+}++function bindFileInput(inputId, labelId, previewWrapperId, previewImgId) {+ const input = document.getElementById(inputId);+ if (!input || input._editBound) return;+ const label = labelId ? document.getElementById(labelId) : null;+ const previewWrapper = previewWrapperId ? document.getElementById(previewWrapperId) : null;+ const previewImg = previewImgId ? document.getElementById(previewImgId) : null;+ input.addEventListener('change', () => {+ const file = input.files?.[0];+ if (label) label.textContent = file ? file.name : '';+ if (previewWrapper && previewImg) {+ if (file && file.type.startsWith('image/')) {+ const reader = new FileReader();+ reader.onload = (e) => {+ previewImg.src = e.target.result;+ previewWrapper.style.display = 'block';+ };+ reader.readAsDataURL(file);+ } else {+ previewWrapper.style.display = 'none';+ }+ }+ });+ input._editBound = true;+}++function applyLifetimeState() {+ const checkbox = document.getElementById('editIsLifetime');+ const methodWrapper = document.getElementById('editWarrantyEntryMethod');+ const durationFields = document.getElementById('editWarrantyDurationFields');+ const exactField = document.getElementById('editExactExpirationField');+ if (!checkbox) return;+ if (checkbox.checked) {+ if (methodWrapper) methodWrapper.style.display = 'none';+ if (durationFields) durationFields.style.display = 'none';+ if (exactField) exactField.style.display = 'none';+ } else {+ if (methodWrapper) methodWrapper.style.display = 'block';+ applyWarrantyMethodState();+ }+}++function applyWarrantyMethodState() {+ const durationFields = document.getElementById('editWarrantyDurationFields');+ const exactField = document.getElementById('editExactExpirationField');+ const useDuration = document.getElementById('editDurationMethod')?.checked;+ if (useDuration) {+ if (durationFields) durationFields.style.display = 'block';+ if (exactField) exactField.style.display = 'none';+ } else {+ if (durationFields) durationFields.style.display = 'none';+ if (exactField) exactField.style.display = 'block';+ }+}++function setDeleteHandler(buttonId, targetElement, message) {+ const button = document.getElementById(buttonId);+ if (!button || button._editBound) return;+ button.addEventListener('click', (event) => {+ event.preventDefault();+ button.dataset.delete = 'true';+ if (targetElement) {+ targetElement.innerHTML = `<span class="text-danger">${message}</span>`;+ }+ button.style.display = 'none';+ });+ button._editBound = true;+}++function resetFileInputs(ids) {+ ids.forEach((id) => {+ const input = document.getElementById(id);+ if (input) input.value = '';+ });+ const labels = ['editProductPhotoFileName', 'editFileName', 'editManualFileName', 'editOtherDocumentFileName'];+ labels.forEach((labelId) => {+ const label = document.getElementById(labelId);+ if (label) label.textContent = '';+ });+ const preview = document.getElementById('editProductPhotoPreview');+ if (preview) preview.style.display = 'none';+}++function setStorageSelection(name, isPaperless) {+ const radios = document.getElementsByName(name);+ if (!radios || !radios.length) return;+ radios.forEach((radio) => {+ radio.checked = isPaperless ? radio.value === 'paperless' : radio.value === 'local';+ });+}++function normalizeSerials(serials) {+ if (!Array.isArray(serials)) return [];+ return serials+ .map((sn) => {+ if (!sn) return '';+ if (typeof sn === 'object' && sn.serial_number) return sn.serial_number;+ return String(sn);+ })+ .filter((value) => value && value.trim());+}++function formatDateInput(value) {+ if (!value) return '';+ if (value.includes('T')) return value.split('T')[0];+ return value;}+function isExactMethodByDuration(warranty) {+ const years = warranty.warranty_duration_years || 0;+ const months = warranty.warranty_duration_months || 0;+ const days = warranty.warranty_duration_days || 0;+ return years === 0 && months === 0 && days === 0 && warranty.expiration_date;+}++function setValue(id, value) {+ const el = document.getElementById(id);+ if (el) el.value = value ?? '';+}++export async function openEditModal(warranty) {+ if (!warranty) return;+ ensureInitialized();+ await Promise.all([loadTags().catch(() => {}), loadCurrencies().catch(() => {})]);+ setCurrentWarrantyId(warranty.id);+ if (typeof window !== 'undefined') {+ window.currentWarrantyId = warranty.id;+ }+ fillWarrantyFields(warranty);+ populateDocuments(warranty);+ activateTab('edit-product-info');+ if (editState.modal) editState.modal.classList.add('active');+ setTimeout(() => loadSecureImages(), 100);+}++function fillWarrantyFields(warranty) {+ const serialContainer = document.getElementById('editSerialNumbersContainer');+ renderSerialNumbers(serialContainer, normalizeSerials(warranty.serial_numbers), window.i18next);+ setValue('editProductName', warranty.product_name || '');+ setValue('editProductUrl', warranty.product_url || '');+ setValue('editModelNumber', warranty.model_number || '');+ setValue('editVendor', warranty.vendor || '');+ setValue('editPurchasePrice', warranty.purchase_price || '');+ setValue('editCurrency', warranty.currency || '');+ setValue('editPurchaseDate', formatDateInput(warranty.purchase_date));+ const expirationDate = formatDateInput(warranty.expiration_date);+ const lifetimeCheckbox = document.getElementById('editIsLifetime');+ if (lifetimeCheckbox) lifetimeCheckbox.checked = Boolean(warranty.is_lifetime);+ const useExact = !warranty.is_lifetime && (warranty.original_input_method === 'exact_date' || isExactMethodByDuration(warranty));+ const durationRadio = document.getElementById('editDurationMethod');+ const exactRadio = document.getElementById('editExactDateMethod');+ if (durationRadio) durationRadio.checked = !useExact;+ if (exactRadio) exactRadio.checked = useExact;+ setValue('editExactExpirationDate', useExact ? expirationDate : '');+ if (!useExact) {+ setValue('editWarrantyDurationYears', warranty.warranty_duration_years || 0);+ setValue('editWarrantyDurationMonths', warranty.warranty_duration_months || 0);+ setValue('editWarrantyDurationDays', warranty.warranty_duration_days || 0);+ } else {+ setValue('editWarrantyDurationYears', '');+ setValue('editWarrantyDurationMonths', '');+ setValue('editWarrantyDurationDays', '');+ }+ applyLifetimeState();+ applyWarrantyMethodState();+ const typeSelect = document.getElementById('editWarrantyType');+ const customInput = document.getElementById('editWarrantyTypeCustom');+ if (typeSelect) {+ const optionExists = Array.from(typeSelect.options).some((option) => option.value === (warranty.warranty_type || ''));+ if (optionExists) {+ typeSelect.value = warranty.warranty_type || '';+ if (customInput) {+ customInput.style.display = 'none';+ customInput.value = '';+ }+ } else {+ typeSelect.value = 'other';+ if (customInput) {+ customInput.style.display = 'block';+ customInput.value = warranty.warranty_type || '';+ }+ }+ }+ setValue('editNotes', warranty.notes || '');+ const tags = Array.isArray(warranty.tags)+ ? warranty.tags.map((tag) => ({ id: tag.id, name: tag.name, color: tag.color }))+ : [];+ setEditSelectedTags(tags);+ if (typeof window !== 'undefined') {+ window.editSelectedTags = tags;+ }+ renderEditSelectedTags();+ renderEditTagsList();+}++function populateDocuments(warranty) {+ setStorageSelection('editInvoiceStorage', Boolean(warranty.paperless_invoice_id));+ setStorageSelection('editManualStorage', Boolean(warranty.paperless_manual_id));+ const invoiceContainer = document.getElementById('currentInvoice');+ const manualContainer = document.getElementById('currentManual');+ const photoContainer = document.getElementById('currentProductPhoto');+ const otherContainer = document.getElementById('currentOtherDocument');+ const deleteInvoiceBtn = document.getElementById('deleteInvoiceBtn');+ const deleteManualBtn = document.getElementById('deleteManualBtn');+ const deletePhotoBtn = document.getElementById('deleteProductPhotoBtn');+ const deleteOtherBtn = document.getElementById('deleteOtherDocumentBtn');+ if (deleteInvoiceBtn) deleteInvoiceBtn.dataset.delete = 'false';+ if (deleteManualBtn) deleteManualBtn.dataset.delete = 'false';+ if (deletePhotoBtn) deletePhotoBtn.dataset.delete = 'false';+ if (deleteOtherBtn) deleteOtherBtn.dataset.delete = 'false';+ renderCurrentInvoice(invoiceContainer, deleteInvoiceBtn, warranty, window.i18next);+ renderCurrentManual(manualContainer, deleteManualBtn, warranty, window.i18next);+ renderCurrentPhoto(photoContainer, deletePhotoBtn, warranty, window.i18next);+ renderCurrentOther(otherContainer, deleteOtherBtn, warranty, window.i18next);+ setDeleteHandler('deleteInvoiceBtn', invoiceContainer, window.i18next ? window.i18next.t('warranties.invoice_will_be_deleted') : 'Invoice will be deleted');+ setDeleteHandler('deleteManualBtn', manualContainer, window.i18next ? window.i18next.t('warranties.manual_will_be_deleted') : 'Manual will be deleted');+ setDeleteHandler('deleteProductPhotoBtn', photoContainer, window.i18next ? window.i18next.t('warranties.photo_will_be_deleted') : 'Photo will be deleted');+ setDeleteHandler('deleteOtherDocumentBtn', otherContainer, window.i18next ? window.i18next.t('warranties.other_document_will_be_deleted') : 'Files will be deleted');+ clearPaperlessSelection('edit_invoice');+ clearPaperlessSelection('edit_manual');+ clearPaperlessSelection('edit_productPhoto');+ clearPaperlessSelection('edit_otherDocument');+ resetFileInputs(['editProductPhoto', 'editInvoice', 'editManual', 'editOtherDocument']);+}-// Submit handler for the Edit Warranty modalexport async function saveWarranty() {- const currentId = typeof window !== 'undefined' ? window.currentWarrantyId : null;+ let currentId = getCurrentWarrantyId();+ if (!currentId && typeof window !== 'undefined' && window.currentWarrantyId) {+ currentId = window.currentWarrantyId;+ setCurrentWarrantyId(currentId);+ }if (!currentId) {- if (window && window.showToast) window.showToast(window.t ? window.t('messages.no_warranty_selected_for_update') : 'No warranty selected', 'error');+ showToast(window.i18next ? window.i18next.t('messages.no_warranty_selected_for_update') : 'No warranty selected', 'error');return;}@@ -334,8 +629,8 @@ export async function saveWarranty() {});// Tags- const editSelectedTags = (typeof window !== 'undefined' && window.editSelectedTags) ? window.editSelectedTags : [];- formData.append('tag_ids', JSON.stringify(Array.isArray(editSelectedTags) ? editSelectedTags.map(t => t.id) : []));+ const tags = getEditSelectedTags() || [];+ formData.append('tag_ids', JSON.stringify(tags.map((t) => t.id)));// Document URLsformData.append('invoice_url', (document.getElementById('editInvoiceUrl') || {}).value || '');@@ -407,53 +702,73 @@ export async function saveWarranty() {console.log(`[DEBUG saveWarranty] FormData: ${key} = ${value}`);}- if (window && window.showLoadingSpinner) window.showLoadingSpinner();+ showLoadingSpinner();try {// Paperless uploads pipeline (delegated to legacy/global)- const uploads = (window && typeof window.processEditPaperlessNgxUploads === 'function')- ? await window.processEditPaperlessNgxUploads(formData)- : {};+ const uploads = await processEditPaperlessUploads(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) window.currentWarrantyId = null; // Clear the warranty ID after successful save- if (window && typeof window.closeModals === 'function') window.closeModals();+ hideLoadingSpinner();+ showToast(window.i18next ? window.i18next.t('messages.warranty_updated_successfully') : 'Warranty updated successfully', 'success');+ setCurrentWarrantyId(null);+ if (typeof window !== 'undefined') {+ window.currentWarrantyId = null;+ }+ closeEditModal();// 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();+ try {+ await loadWarranties(true);+ applyFilters();+ setTimeout(() => loadSecureImages(), 200);+ const notesModal = document.getElementById('notesModal');+ if (notesModal && notesModal.style.display === 'block') notesModal.style.display = 'none';+ if ((invoiceFile || manualFile || otherDocumentFile) && currentId) {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);+ const fileInfo = {};+ if (invoiceFile) fileInfo.invoice = invoiceFile.name;+ if (manualFile) fileInfo.manual = manualFile.name;+ if (otherDocumentFile) fileInfo.other = otherDocumentFile.name;+ 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();+ hideLoadingSpinner();console.error('Error updating warranty:', error);- if (window && window.showToast) window.showToast(error?.message || 'Failed to update warranty', 'error');+ showToast(error?.message || (window.i18next ? window.i18next.t('messages.failed_to_update_warranty') : 'Failed to update warranty'), 'error');}}++export function closeEditModal() {+ const modal = document.getElementById('editModal');+ if (modal) modal.classList.remove('active');+}++export function init() {+ ensureInitialized();+}++if (typeof window !== 'undefined') {+ window.components = window.components || {};+ window.components.editModal = {+ renderSerialNumbers,+ renderCurrentInvoice,+ renderCurrentManual,+ renderCurrentPhoto,+ renderCurrentOther,+ openEditModal,+ saveWarranty,+ closeEditModal,+ init,+ };+ window.openEditModal = openEditModal;+ window.saveWarranty = saveWarranty;+ window.closeEditModal = closeEditModal;+ window.editSelectedTags = window.editSelectedTags || [];+}diff --git a/frontend/js/components/formTabs.js b/frontend/js/components/formTabs.jsnew file mode 100644index 0000000..dca78f4--- /dev/null+++ b/frontend/js/components/formTabs.js@@ -0,0 +1,528 @@+import { getSelectedTags } from '../store.js';++// Module-scoped variables (previously global)+let formTabs = [];+let tabContents = [];+let currentTabIndex = 0;++// References to form elements+let warrantyForm = null;+let serialNumbersContainer = null;+let isLifetimeCheckbox = null;+let warrantyDurationYearsInput = null;+let warrantyDurationMonthsInput = null;+let warrantyDurationDaysInput = null;++function initFormTabs() {+ console.log('Initializing form tabs...');+ // Use the modal context if available, otherwise query document+ const modalContext = document.getElementById('addWarrantyModal');+ const context = modalContext && modalContext.classList.contains('active') ? modalContext : document;++ const tabsContainer = context.querySelector('.form-tabs');+ const contentsElements = context.querySelectorAll('.tab-content');+ tabContents = contentsElements ? Array.from(contentsElements) : [];++ const tabsElements = tabsContainer ? tabsContainer.querySelectorAll('.form-tab') : [];+ formTabs = tabsElements ? Array.from(tabsElements) : [];++ const nextButton = context.querySelector('#nextTabBtn');+ const prevButton = context.querySelector('#prevTabBtn');+ const submitButton = context.querySelector('#submitWarrantyBtn');++ if (!tabsContainer || !tabContents.length || !formTabs.length || !nextButton || !prevButton || !submitButton) {+ console.warn('Form tab elements not found in the expected context. Skipping tab initialization.');+ return;+ }++ // Get form element references+ warrantyForm = document.getElementById('warrantyForm');+ serialNumbersContainer = document.getElementById('serialNumbersContainer');+ isLifetimeCheckbox = document.getElementById('isLifetime');+ warrantyDurationYearsInput = document.getElementById('warrantyDurationYears');+ warrantyDurationMonthsInput = document.getElementById('warrantyDurationMonths');+ warrantyDurationDaysInput = document.getElementById('warrantyDurationDays');++ // Clone and replace nav buttons to remove old listeners+ let nextButtonCloned = nextButton;+ let prevButtonCloned = prevButton;+ if (nextButton && prevButton) {+ nextButtonCloned = nextButton.cloneNode(true);+ prevButtonCloned = prevButton.cloneNode(true);+ nextButton.parentNode.replaceChild(nextButtonCloned, nextButton);+ prevButton.parentNode.replaceChild(prevButtonCloned, prevButton);+ } else {+ console.warn("Next/Prev buttons not found for cloning listeners.");+ }++ // Setup tab click listeners+ formTabs.forEach((tab, index) => {+ if (tab) {+ tab.addEventListener('click', () => {+ if (index < currentTabIndex) {+ let canSwitch = true;+ for (let i = 0; i < index; i++) {+ if (!validateTab(i)) {+ canSwitch = false;+ break;+ }+ }+ if (canSwitch) switchToTab(index);+ } else if (index === currentTabIndex) {+ // Clicking current tab does nothing+ } else {+ if (validateTab(currentTabIndex)) {+ if (formTabs[currentTabIndex]) formTabs[currentTabIndex].classList.add('completed');+ switchToTab(index);+ } else {+ showValidationErrors(currentTabIndex);+ }+ }+ });+ }+ });++ if (nextButtonCloned) {+ nextButtonCloned.addEventListener('click', () => {+ if (validateTab(currentTabIndex)) {+ if (formTabs[currentTabIndex]) formTabs[currentTabIndex].classList.add('completed');+ if (currentTabIndex < formTabs.length - 1) {+ switchToTab(currentTabIndex + 1);+ }+ } else {+ showValidationErrors(currentTabIndex);+ }+ });+ } else {+ console.warn("Cloned Next button not found, listener not added.");+ }++ if (prevButtonCloned) {+ prevButtonCloned.addEventListener('click', () => {+ if (currentTabIndex > 0) {+ switchToTab(currentTabIndex - 1);+ }+ });+ }++ // Initialize the first tab+ switchToTab(0);+}++function switchToTab(index) {+ console.log(`Switching to tab ${index} from tab ${currentTabIndex}`);++ if (index < 0 || index >= formTabs.length) {+ console.log(`Invalid tab index: ${index}, not switching`);+ return;+ }++ // Update summary FIRST if switching TO the summary tab+ if (index === formTabs.length - 1) {+ updateSummary();+ }++ // Update active tab+ formTabs.forEach(tab => tab.classList.remove('active'));+ tabContents.forEach(content => content.classList.remove('active'));++ formTabs[index].classList.add('active');+ tabContents[index].classList.add('active');++ currentTabIndex = index;++ // Update progress indicator+ const formTabsContainer = document.querySelector('.form-tabs');+ if (formTabsContainer) {+ formTabsContainer.setAttribute('data-step', currentTabIndex);+ }++ updateCompletedTabs();+ updateNavigationButtons();+}++function updateNavigationButtons() {+ const prevButton = document.querySelector('.prev-tab');+ const nextButton = document.querySelector('.next-tab');+ const submitButton = document.querySelector('button[type="submit"]');++ if (prevButton) {+ prevButton.style.display = currentTabIndex === 0 ? 'none' : 'block';+ }++ if (currentTabIndex === formTabs.length - 1) {+ if (nextButton) nextButton.style.display = 'none';+ if (submitButton) submitButton.style.display = 'block';+ } else {+ if (nextButton) nextButton.style.display = 'block';+ if (submitButton) submitButton.style.display = 'none';+ }+}++function updateCompletedTabs() {+ formTabs.forEach((tab, index) => {+ if (index < currentTabIndex) {+ tab.classList.add('completed');+ } else {+ tab.classList.remove('completed');+ }+ });+}++function validateTab(tabIndex) {+ const tabContent = tabContents[tabIndex];+ const controls = tabContent.querySelectorAll('input, textarea, select');+ let isTabValid = true;++ controls.forEach(control => {+ control.classList.remove('invalid');+ let validationMessageElement = control.nextElementSibling;+ if (validationMessageElement && validationMessageElement.classList.contains('validation-message')) {+ validationMessageElement.remove();+ }++ if (control.hasAttribute('required') && control.value.trim() === '') {+ isTabValid = false;+ control.classList.add('invalid');+ } else if (!control.validity.valid) {+ isTabValid = false;+ control.classList.add('invalid');+ }+ });+ return isTabValid;+}++function showValidationErrors(tabIndex) {+ const tabContent = tabContents[tabIndex];+ const controls = tabContent.querySelectorAll('input, textarea, select');+ let validationToast = document.querySelector('.validation-toast');++ controls.forEach(control => {+ if (!control.validity.valid) {+ control.classList.add('invalid');++ let validationMessageElement = control.nextElementSibling;+ if (!validationMessageElement || !validationMessageElement.classList.contains('validation-message')) {+ validationMessageElement = document.createElement('div');+ validationMessageElement.className = 'validation-message';+ control.parentNode.insertBefore(validationMessageElement, control.nextSibling);+ }+ if (control.hasAttribute('required') && control.value.trim() === '') {+ validationMessageElement.textContent = window.i18next ? window.i18next.t('messages.please_fill_out_this_field') : 'Please fill out this field.';+ } else {+ validationMessageElement.textContent = control.validationMessage || (window.i18next ? window.i18next.t('messages.field_is_invalid') : 'This field is invalid.');+ }+ } else {+ control.classList.remove('invalid');+ let validationMessageElement = control.nextElementSibling;+ if (validationMessageElement && validationMessageElement.classList.contains('validation-message')) {+ validationMessageElement.remove();+ }+ }+ });++ if (!validationToast && window.showToast) {+ validationToast = window.showToast(window.t('messages.correct_errors_in_tab'), 'error', 0);+ if (validationToast) {+ validationToast.classList.add('validation-toast');+ }+ } else if (validationToast && validationToast.querySelector('span')) {+ validationToast.querySelector('span').textContent = window.t('messages.correct_errors_in_tab');+ }+}++function updateSummary() {+ // Product information+ const summaryProductName = document.getElementById('summary-product-name');+ if (summaryProductName) {+ summaryProductName.textContent = document.getElementById('productName')?.value || '-';+ }++ const summaryProductUrl = document.getElementById('summary-product-url');+ if (summaryProductUrl) {+ summaryProductUrl.textContent = document.getElementById('productUrl')?.value || '-';+ }++ // Serial numbers+ const serialNumbers = [];+ document.querySelectorAll('input[name="serial_numbers[]"]').forEach(input => {+ if (input && input.value && input.value.trim()) {+ serialNumbers.push(input.value.trim());+ }+ });++ const serialNumbersContainer = document.getElementById('summary-serial-numbers');+ if (serialNumbersContainer) {+ if (serialNumbers.length > 0) {+ serialNumbersContainer.innerHTML = '<ul>' ++ serialNumbers.map(sn => `<li>${sn}</li>`).join('') ++ '</ul>';+ } else {+ serialNumbersContainer.textContent = 'None';+ }+ }++ // Warranty details+ const purchaseDateStr = document.getElementById('purchaseDate')?.value;+ const summaryPurchaseDate = document.getElementById('summary-purchase-date');+ if (summaryPurchaseDate) {+ if (purchaseDateStr) {+ const parts = String(purchaseDateStr).split('-');+ let formattedDate = '-';+ if (parts.length === 3) {+ const year = parseInt(parts[0], 10);+ const month = parseInt(parts[1], 10) - 1;+ const day = parseInt(parts[2], 10);+ const dateObj = new Date(Date.UTC(year, month, day));+ if (!isNaN(dateObj.getTime())) {+ const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];+ formattedDate = `${monthNames[month]} ${day}, ${year}`;+ }+ }+ summaryPurchaseDate.textContent = formattedDate;+ } else {+ summaryPurchaseDate.textContent = '-';+ }+ }++ // Handle Lifetime in Summary+ const isLifetime = isLifetimeCheckbox ? isLifetimeCheckbox.checked : false;+ const summaryWarrantyDuration = document.getElementById('summary-warranty-duration');++ if (summaryWarrantyDuration) {+ if (isLifetime) {+ summaryWarrantyDuration.textContent = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';+ } else {+ const years = parseInt(warrantyDurationYearsInput?.value || 0);+ const months = parseInt(warrantyDurationMonthsInput?.value || 0);+ const days = parseInt(warrantyDurationDaysInput?.value || 0);++ let durationParts = [];+ if (years > 0) {+ const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;+ durationParts.push(`${years} ${yearText}`);+ }+ if (months > 0) {+ const monthText = window.i18next ? window.i18next.t('warranties.month', {count: months}) : `month${months !== 1 ? 's' : ''}`;+ durationParts.push(`${months} ${monthText}`);+ }+ if (days > 0) {+ const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;+ durationParts.push(`${days} ${dayText}`);+ }++ summaryWarrantyDuration.textContent = durationParts.length > 0 ? durationParts.join(', ') : '-';+ }+ }++ // Warranty type+ const warrantyTypeSelect = document.getElementById('warrantyType');+ const warrantyTypeCustom = document.getElementById('warrantyTypeCustom');+ const summaryWarrantyType = document.getElementById('summary-warranty-type');+ if (summaryWarrantyType) {+ let warrantyTypeText = 'Not specified';+ if (warrantyTypeSelect && warrantyTypeSelect.value) {+ if (warrantyTypeSelect.value === 'other' && warrantyTypeCustom && warrantyTypeCustom.value.trim()) {+ warrantyTypeText = warrantyTypeCustom.value.trim();+ } else if (warrantyTypeSelect.value !== 'other') {+ warrantyTypeText = warrantyTypeSelect.value;+ }+ }+ summaryWarrantyType.textContent = warrantyTypeText;+ }++ // Purchase price+ const purchasePrice = document.getElementById('purchasePrice')?.value;+ const summaryPurchasePrice = document.getElementById('summary-purchase-price');+ if (summaryPurchasePrice) {+ if (purchasePrice) {+ const symbol = window.getCurrencySymbol ? window.getCurrencySymbol() : '$';+ const position = window.getCurrencyPosition ? window.getCurrencyPosition() : 'before';+ const amount = parseFloat(purchasePrice).toFixed(2);+ if (window.formatCurrencyHTML) {+ summaryPurchasePrice.innerHTML = window.formatCurrencyHTML(amount, symbol, position);+ } else {+ summaryPurchasePrice.textContent = `${symbol}${amount}`;+ }+ } else {+ summaryPurchasePrice.textContent = 'Not specified';+ }+ }++ // Documents+ const productPhotoFile = document.getElementById('productPhoto')?.files[0];+ const summaryProductPhoto = document.getElementById('summary-product-photo');+ if (summaryProductPhoto) {+ summaryProductPhoto.textContent = productPhotoFile ? productPhotoFile.name : 'No photo selected';+ }++ const invoiceFile = document.getElementById('invoice')?.files[0];+ const invoiceUrlField = document.getElementById('invoiceUrl');+ const invoiceUrl = invoiceUrlField ? invoiceUrlField.value : '';+ const summaryInvoice = document.getElementById('summary-invoice');+ if (summaryInvoice) {+ if (invoiceFile) {+ summaryInvoice.textContent = invoiceFile.name;+ } else if (invoiceUrl) {+ summaryInvoice.textContent = 'URL: ' + invoiceUrl;+ } else {+ summaryInvoice.textContent = 'Not specified';+ }+ }++ const manualFile = document.getElementById('manual')?.files[0];+ const manualUrlField = document.getElementById('manualUrl');+ const manualUrl = manualUrlField ? manualUrlField.value : '';+ const summaryManual = document.getElementById('summary-manual');+ if (summaryManual) {+ if (manualFile) {+ summaryManual.textContent = manualFile.name;+ } else if (manualUrl) {+ summaryManual.textContent = 'URL: ' + manualUrl;+ } else {+ summaryManual.textContent = 'Not specified';+ }+ }++ const otherDocumentFile = document.getElementById('otherDocument')?.files[0];+ const otherDocumentUrlField = document.getElementById('otherDocumentUrl');+ const otherDocumentUrl = otherDocumentUrlField ? otherDocumentUrlField.value : '';+ const summaryOtherDocument = document.getElementById('summary-other-document');+ if (summaryOtherDocument) {+ if (otherDocumentFile) {+ summaryOtherDocument.textContent = otherDocumentFile.name;+ } else if (otherDocumentUrl) {+ summaryOtherDocument.textContent = 'URL: ' + otherDocumentUrl;+ } else {+ summaryOtherDocument.textContent = 'Not specified';+ }+ }++ // Tags+ const selectedTags = getSelectedTags();+ const summaryTags = document.getElementById('summary-tags');+ if (summaryTags) {+ if (selectedTags && selectedTags.length > 0) {+ summaryTags.innerHTML = '';++ selectedTags.forEach(tag => {+ const tagElement = document.createElement('span');+ tagElement.className = 'tag';+ tagElement.style.backgroundColor = tag.color;+ if (window.getContrastColor) {+ tagElement.style.color = window.getContrastColor(tag.color);+ }+ tagElement.textContent = tag.name;++ summaryTags.appendChild(tagElement);+ });+ } else {+ summaryTags.textContent = 'No tags selected';+ }+ }++ // Vendor/Retailer+ const vendor = document.getElementById('vendor');+ const summaryVendor = document.getElementById('summary-vendor');+ if (summaryVendor) {+ summaryVendor.textContent = vendor && vendor.value ? vendor.value : '-';+ }+}++function resetForm() {+ if (!warrantyForm) {+ warrantyForm = document.getElementById('warrantyForm');+ }++ if (warrantyForm) {+ warrantyForm.reset();+ }++ // Reset serial numbers container+ if (!serialNumbersContainer) {+ serialNumbersContainer = document.getElementById('serialNumbersContainer');+ }++ if (serialNumbersContainer) {+ serialNumbersContainer.innerHTML = '';+ }++ // Add the first serial number input+ if (window.addSerialNumberInput) {+ window.addSerialNumberInput();+ }++ // Reset form tabs+ currentTabIndex = 0;+ switchToTab(0);++ // Clear any file input displays+ const productPhotoFileName = document.getElementById('productPhotoFileName');+ if (productPhotoFileName) productPhotoFileName.textContent = '';++ const fileName = document.getElementById('fileName');+ if (fileName) fileName.textContent = '';++ const manualFileName = document.getElementById('manualFileName');+ if (manualFileName) manualFileName.textContent = '';++ const otherDocumentFileName = document.getElementById('otherDocumentFileName');+ if (otherDocumentFileName) otherDocumentFileName.textContent = '';++ // Reset photo preview+ const productPhotoPreview = document.getElementById('productPhotoPreview');+ if (productPhotoPreview) {+ productPhotoPreview.style.display = 'none';+ }+}++// Add input event listener to remove validation errors when user types+document.addEventListener('input', (e) => {+ if (e.target.hasAttribute('required') && e.target.classList.contains('invalid')) {+ if (e.target.value.trim()) {+ e.target.classList.remove('invalid');++ const validationMessage = e.target.nextElementSibling;+ if (validationMessage && validationMessage.classList.contains('validation-message')) {+ validationMessage.remove();+ }+ }+ }+});++// Export functions+export {+ initFormTabs,+ switchToTab,+ updateNavigationButtons,+ updateCompletedTabs,+ validateTab,+ showValidationErrors,+ updateSummary,+ resetForm+};++// Expose to window for backward compatibility+if (typeof window !== 'undefined') {+ window.formTabs = {+ init: initFormTabs,+ switchToTab,+ updateNavigationButtons,+ updateCompletedTabs,+ validateTab,+ showValidationErrors,+ updateSummary,+ reset: resetForm+ };++ // Also expose individual functions+ window.initFormTabs = initFormTabs;+ window.switchToTab = switchToTab;+ window.updateNavigationButtons = updateNavigationButtons;+ window.updateCompletedTabs = updateCompletedTabs;+ window.validateTab = validateTab;+ window.showValidationErrors = showValidationErrors;+ window.updateSummary = updateSummary;+ window.resetForm = resetForm;+}diff --git a/frontend/js/components/importExport.js b/frontend/js/components/importExport.jsnew file mode 100644index 0000000..d2bf021--- /dev/null+++ b/frontend/js/components/importExport.js@@ -0,0 +1,169 @@+import { getWarranties, getFilters } from '../store.js';+import { showToast, showLoadingSpinner, hideLoadingSpinner } from './ui.js';+import { loadWarranties, applyFilters } from '../controllers/warrantyListController.js';+import { loadTags } from './tagManager.js';+import { formatDateYYYYMMDD } from '../lib/dates.js';++export async function exportWarranties() {+ const warranties = getWarranties();+ if (!warranties.length) {+ showToast(window.i18next ? window.i18next.t('messages.no_warranties_to_export') : 'No warranties to export', 'info');+ return;+ }+ const filters = getFilters();+ let filtered = [...warranties];+ if (filters.search) {+ const term = filters.search.toLowerCase();+ filtered = filtered.filter((warranty) => {+ const nameMatch = (warranty.product_name || '').toLowerCase().includes(term);+ const vendorMatch = (warranty.vendor || '').toLowerCase().includes(term);+ const tagMatch = Array.isArray(warranty.tags)+ && warranty.tags.some((tag) => (tag.name || '').toLowerCase().includes(term));+ return nameMatch || vendorMatch || tagMatch;+ });+ }+ if (filters.status !== 'all') {+ filtered = filtered.filter((warranty) => warranty.status === filters.status);+ }+ if (filters.tag !== 'all') {+ const tagId = Number.parseInt(filters.tag, 10);+ filtered = filtered.filter((warranty) => Array.isArray(warranty.tags)+ && warranty.tags.some((tag) => tag.id === tagId));+ }+ if (filters.vendor !== 'all') {+ filtered = filtered.filter((warranty) => (warranty.vendor || '').toLowerCase() === (filters.vendor || '').toLowerCase());+ }+ if (filters.warranty_type !== 'all') {+ filtered = filtered.filter((warranty) => (warranty.warranty_type || '').toLowerCase() === (filters.warranty_type || '').toLowerCase());+ }++ if (!filtered.length) {+ showToast(window.i18next ? window.i18next.t('messages.no_warranties_to_export') : 'No warranties to export', 'info');+ return;+ }++ const headers = [+ 'ProductName',+ 'PurchaseDate',+ 'IsLifetime',+ 'WarrantyDurationYears',+ 'WarrantyDurationMonths',+ 'WarrantyDurationDays',+ 'ExpirationDate',+ 'Status',+ 'PurchasePrice',+ 'SerialNumber',+ 'ProductURL',+ 'Tags',+ 'Vendor',+ ];+ let csv = `${headers.join(',')}\n`;+ filtered.forEach((warranty) => {+ const serials = Array.isArray(warranty.serial_numbers)+ ? warranty.serial_numbers.filter(Boolean).join(' ')+ : '';+ const tags = Array.isArray(warranty.tags)+ ? warranty.tags.map((tag) => tag.name).join(' ')+ : '';+ const row = [+ warranty.product_name || '',+ warranty.purchase_date ? formatDateYYYYMMDD(new Date(warranty.purchase_date)) : '',+ warranty.is_lifetime ? 'TRUE' : 'FALSE',+ warranty.warranty_duration_years || 0,+ warranty.warranty_duration_months || 0,+ warranty.warranty_duration_days || 0,+ warranty.expiration_date ? formatDateYYYYMMDD(new Date(warranty.expiration_date)) : '',+ warranty.status || '',+ warranty.purchase_price || '',+ serials,+ warranty.product_url || '',+ tags,+ warranty.vendor || '',+ ];+ csv += `${row.map((field) => `"${String(field).replace(/"/g, '""')}"`).join(',')}\n`;+ });++ const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });+ const link = document.createElement('a');+ const url = URL.createObjectURL(blob);+ link.href = url;+ link.download = `warranties_export_${formatDateYYYYMMDD(new Date())}.csv`;+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ URL.revokeObjectURL(url);+ showToast(+ window.i18next+ ? window.i18next.t('messages.exported_warranties_successfully', { count: filtered.length })+ : `Exported ${filtered.length} warranties`,+ 'success',+ );+}++export async function handleImport(file) {+ if (!file) {+ showToast(window.i18next ? window.i18next.t('messages.no_file_selected') : 'No file selected', 'warning');+ return;+ }+ if (!file.name.toLowerCase().endsWith('.csv')) {+ showToast(window.i18next ? window.i18next.t('messages.invalid_file_type') : 'Invalid file type', 'error');+ return;+ }+ showLoadingSpinner();+ const formData = new FormData();+ formData.append('csv_file', file);+ try {+ const response = await fetch('/api/warranties/import', {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${authToken()}`,+ },+ body: formData,+ });+ const result = await response.json();+ hideLoadingSpinner();+ if (!response.ok) {+ showToast(result.error || (window.i18next ? window.i18next.t('messages.import_failed') : 'Import failed'), 'error');+ if (result.errors) console.warn('[importExport] detailed import errors', result.errors);+ return;+ }+ showToast(+ window.i18next+ ? window.i18next.t('messages.import_success', { success: result.success_count, failure: result.failure_count })+ : `${result.success_count} warranties imported. ${result.failure_count} failed.`,+ 'success',+ );+ await loadTags(true);+ await delay(500);+ await loadWarranties(true);+ applyFilters();+ } catch (error) {+ hideLoadingSpinner();+ console.error('[importExport] Import error', error);+ showToast(window.i18next ? window.i18next.t('messages.import_failed') : 'Import failed', 'error');+ } finally {+ const input = document.getElementById('csvFileInput');+ if (input) input.value = '';+ }+}++function authToken() {+ const token = localStorage.getItem('auth_token');+ if (!token) throw new Error('Authentication required');+ return token;+}++function delay(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++if (typeof window !== 'undefined') {+ window.exportWarranties = exportWarranties;+ window.handleImport = handleImport;+}++++++diff --git a/frontend/js/components/modals.js b/frontend/js/components/modals.jsindex ca315a5..689a076 100644--- a/frontend/js/components/modals.js+++ b/frontend/js/components/modals.js@@ -1,4 +1,4 @@-// Lightweight modal utilities and wrappers+import { setCurrentWarrantyId } from '../store.js';export function showModalById(modalId) {const modal = document.getElementById(modalId);@@ -19,17 +19,26 @@ export function setText(selector, text) {if (el) el.textContent = text || '';}-export function openDeleteModal(productName) {+export function openDeleteModal(warrantyId, productName) {+ if (Number.isFinite(warrantyId)) {+ setCurrentWarrantyId(warrantyId);+ }setText('#deleteProductName', productName || '');showModalById('deleteModal');}-export function openArchiveModal(productName) {+export function openArchiveModal(warrantyId, productName) {+ if (Number.isFinite(warrantyId)) {+ setCurrentWarrantyId(warrantyId);+ }setText('#archiveProductName', productName || '');showModalById('archiveModal');}-// Non-module exposure+export function closeModals() {+ document.querySelectorAll('.modal-backdrop').forEach((modal) => modal.classList.remove('active'));+}+if (typeof window !== 'undefined') {window.components = window.components || {};window.components.modals = {@@ -38,7 +47,9 @@ if (typeof window !== 'undefined') {setText,openDeleteModal,openArchiveModal,+ closeModals,};+ window.openDeleteModal = openDeleteModal;+ window.openArchiveModal = openArchiveModal;+ window.closeModals = closeModals;}--diff --git a/frontend/js/components/notes.js b/frontend/js/components/notes.jsindex 653d5ff..e7ceea7 100644--- a/frontend/js/components/notes.js+++ b/frontend/js/components/notes.js@@ -1,55 +1,296 @@-function el(tag, className, text) {- const e = document.createElement(tag);- if (className) e.className = className;- if (text !== undefined && text !== null) e.textContent = text;- return e;-}--export function ensureNotesModal() {- if (document.getElementById('notesModal')) return;- const backdrop = el('div', 'modal-backdrop');- backdrop.id = 'notesModal';-- const modal = el('div', 'modal');- modal.style.maxWidth = '500px';-- const header = el('div', 'modal-header');- const title = el('h3', 'modal-title', (window.i18next && window.i18next.t('warranties.notes')) || 'Warranty Notes');- const closeBtn = el('button', 'close-btn');- closeBtn.id = 'closeNotesModal';- closeBtn.textContent = '×';- header.appendChild(title);- header.appendChild(closeBtn);-- const body = el('div', 'modal-body');- const content = el('div'); content.id = 'notesModalContent'; content.style.whiteSpace = 'pre-line';- const textarea = el('textarea'); textarea.id = 'notesModalTextarea'; textarea.style.display = 'none'; textarea.style.width = '100%'; textarea.style.minHeight = '100px';- body.appendChild(content);- body.appendChild(textarea);-- const footer = el('div', 'modal-footer'); footer.id = 'notesModalFooter';- const editBtn = el('button', 'btn btn-secondary', (window.i18next && window.i18next.t('actions.edit')) || 'Edit Notes'); editBtn.id = 'editNotesBtn';- const editWarrantyBtn = el('button', 'btn btn-info', (window.i18next && window.i18next.t('warranties.edit_warranty')) || 'Edit Warranty'); editWarrantyBtn.id = 'editWarrantyBtn';- const saveBtn = el('button', 'btn btn-primary', (window.i18next && window.i18next.t('actions.save')) || 'Save'); saveBtn.id = 'saveNotesBtn'; saveBtn.style.display = 'none';- const cancelBtn = el('button', 'btn btn-danger', (window.i18next && window.i18next.t('actions.cancel')) || 'Cancel'); cancelBtn.id = 'cancelEditNotesBtn'; cancelBtn.style.display = 'none';- footer.appendChild(editBtn);- footer.appendChild(editWarrantyBtn);- footer.appendChild(saveBtn);- footer.appendChild(cancelBtn);-- modal.appendChild(header);- modal.appendChild(body);- modal.appendChild(footer);- backdrop.appendChild(modal);- document.body.appendChild(backdrop);-- closeBtn.addEventListener('click', () => backdrop.classList.remove('active'));-}--// Global exposure-if (typeof window !== 'undefined') {- window.components = window.components || {};- window.components.notes = { ensureNotesModal };+import { getWarranties, setWarranties } from '../store.js';+import { showLoadingSpinner, hideLoadingSpinner, showToast } from './ui.js';++const DEFAULT_MODAL_HTML = `+ <div class="modal" style="max-width: 500px;">+ <div class="modal-header">+ <h3 class="modal-title">${window.i18next ? window.i18next.t('warranties.notes_title') : 'Warranty Notes'}</h3>+ <button class="close-btn" id="closeNotesModal">×</button>+ </div>+ <div class="modal-body">+ <div id="notesModalContent" style="white-space: pre-line;"></div>+ <textarea id="notesModalTextarea" style="display:none;width:100%;min-height:100px;"></textarea>+ </div>+ <div class="modal-footer" id="notesModalFooter">+ <button class="btn btn-secondary" id="editNotesBtn">${window.i18next ? window.i18next.t('actions.edit_notes') : 'Edit Notes'}</button>+ <button class="btn btn-info" id="editWarrantyBtn">${window.i18next ? window.i18next.t('actions.edit_warranty') : 'Edit Warranty'}</button>+ <button class="btn btn-primary" id="saveNotesBtn" style="display:none;">${window.i18next ? window.i18next.t('actions.save') : 'Save'}</button>+ <button class="btn btn-danger" id="cancelEditNotesBtn" style="display:none;">${window.i18next ? window.i18next.t('actions.cancel') : 'Cancel'}</button>+ </div>+ </div>+`;++const state = {+ warrantyId: null,+ warranty: null,+};++let dom = null;++function callIfExists(fn, ...args) {+ if (typeof fn === 'function') {+ return fn(...args);+ }+ return undefined;+}++function getToken() {+ return callIfExists(window.auth?.getToken) || localStorage.getItem('auth_token');+}++function ensureModal() {+ let modal = document.getElementById('notesModal');+ if (!modal) {+ modal = document.createElement('div');+ modal.id = 'notesModal';+ modal.className = 'modal-backdrop';+ modal.innerHTML = DEFAULT_MODAL_HTML;+ document.body.appendChild(modal);+ }+ refreshDomRefs();+ bindEvents();+ return dom;+}++function refreshDomRefs() {+ dom = {+ modal: document.getElementById('notesModal'),+ content: document.getElementById('notesModalContent'),+ textarea: document.getElementById('notesModalTextarea'),+ editBtn: document.getElementById('editNotesBtn'),+ saveBtn: document.getElementById('saveNotesBtn'),+ cancelBtn: document.getElementById('cancelEditNotesBtn'),+ editWarrantyBtn: document.getElementById('editWarrantyBtn'),+ closeBtn: document.getElementById('closeNotesModal'),+ };+}++function bindEvents() {+ if (!dom || dom.modal?._notesBound) return;+ dom.closeBtn?.addEventListener('click', hideModal);+ dom.editBtn?.addEventListener('click', enterEditMode);+ dom.saveBtn?.addEventListener('click', saveNotes);+ dom.cancelBtn?.addEventListener('click', exitEditMode);+ dom.editWarrantyBtn?.addEventListener('click', handleEditWarranty);+ dom.modal._notesBound = true;+}++function handleEditWarranty() {+ if (!state.warrantyId) return;+ hideModal();+ // Use already-stored warranty first (set when modal was opened), then try to resolve by ID+ let warranty = state.warranty;+ if (!warranty) {+ warranty = resolveWarranty(state.warrantyId);+ }+ if (!warranty) {+ showToast(window.i18next ? window.i18next.t('messages.warranty_not_found_refresh') : 'Warranty not found', 'error');+ return;+ }+ callIfExists(window.openEditModal, warranty);+}++function hideModal() {+ if (dom?.modal) {+ dom.modal.classList.remove('active');+ }+ exitEditMode();+}++function enterEditMode() {+ if (!dom) return;+ dom.content.style.display = 'none';+ dom.textarea.style.display = '';+ dom.textarea.value = dom.content.textContent;+ dom.editBtn.style.display = 'none';+ dom.saveBtn.style.display = '';+ dom.cancelBtn.style.display = '';+ dom.textarea.focus();}+function exitEditMode() {+ if (!dom) return;+ dom.content.style.display = '';+ dom.textarea.style.display = 'none';+ dom.editBtn.style.display = '';+ dom.saveBtn.style.display = 'none';+ dom.cancelBtn.style.display = 'none';+}++function resolveWarranty(warrantyOrId) {+ if (warrantyOrId && typeof warrantyOrId === 'object') return warrantyOrId;+ const id = typeof warrantyOrId === 'number' ? warrantyOrId : parseInt(warrantyOrId, 10);+ if (!Number.isFinite(id)) return null;+ // Try store first+ let found = getWarranties().find((w) => w.id === id);+ // Fallback to global warranties array (script.js compatibility)+ if (!found && Array.isArray(window.warranties)) {+ found = window.warranties.find((w) => w.id === id);+ }+ return found || null;+}++function validateDuration(warranty) {+ if (!warranty) return false;+ if (warranty.is_lifetime) return true;+ const years = parseInt(warranty.warranty_duration_years, 10) || 0;+ const months = parseInt(warranty.warranty_duration_months, 10) || 0;+ const days = parseInt(warranty.warranty_duration_days, 10) || 0;+ return years > 0 || months > 0 || days > 0 || Boolean(warranty.expiration_date);+}+function buildFormData(warranty, noteValue) {+ const formData = new FormData();+ formData.append('product_name', warranty.product_name);+ formData.append('purchase_date', (warranty.purchase_date || '').split('T')[0]);+ formData.append('is_lifetime', warranty.is_lifetime ? 'true' : 'false');+ if (!warranty.is_lifetime) {+ formData.append('warranty_duration_years', warranty.warranty_duration_years || 0);+ formData.append('warranty_duration_months', warranty.warranty_duration_months || 0);+ formData.append('warranty_duration_days', warranty.warranty_duration_days || 0);+ const isExactDateWarranty =+ (parseInt(warranty.warranty_duration_years, 10) || 0) === 0 &&+ (parseInt(warranty.warranty_duration_months, 10) || 0) === 0 &&+ (parseInt(warranty.warranty_duration_days, 10) || 0) === 0 &&+ warranty.expiration_date;+ if (isExactDateWarranty) {+ formData.append('exact_expiration_date', warranty.expiration_date.split('T')[0]);+ }+ }+ if (warranty.product_url) formData.append('product_url', warranty.product_url);+ if (warranty.purchase_price !== null && warranty.purchase_price !== undefined) {+ formData.append('purchase_price', warranty.purchase_price);+ }+ const vendorInput = document.getElementById('editVendorOrRetailer');+ if (vendorInput) {+ formData.append('vendor', vendorInput.value.trim());+ } else if (warranty.vendor) {+ formData.append('vendor', warranty.vendor);+ }+ if (warranty.warranty_type) formData.append('warranty_type', warranty.warranty_type);+ const modelNumberInput = document.getElementById('editModelNumber');+ if (modelNumberInput && modelNumberInput.value.trim() !== '') {+ formData.append('model_number', modelNumberInput.value.trim());+ } else if (typeof warranty.model_number !== 'undefined' && warranty.model_number !== null) {+ formData.append('model_number', warranty.model_number);+ }+ if (Array.isArray(warranty.serial_numbers)) {+ warranty.serial_numbers.forEach((sn) => {+ if (sn && String(sn).trim() !== '') {+ formData.append('serial_numbers[]', String(sn).trim());+ }+ });+ }+ if (Array.isArray(warranty.tags)) {+ const tagIds = warranty.tags.map((tag) => tag.id);+ formData.append('tag_ids', JSON.stringify(tagIds));+ } else {+ formData.append('tag_ids', JSON.stringify([]));+ }+ formData.append('notes', noteValue);+ return formData;+}++async function refreshWarranties() {+ if (window.warrantyListController?.loadWarranties) {+ await window.warrantyListController.loadWarranties(true);+ callIfExists(window.warrantyListController.applyFilters);+ return;+ }+ if (typeof window.loadWarranties === 'function') {+ await window.loadWarranties(true);+ callIfExists(window.applyFilters);+ }+}++function updateStoreNotes(noteValue) {+ const warranties = getWarranties();+ const index = warranties.findIndex((w) => w.id === state.warrantyId);+ if (index === -1) return;+ const updated = [...warranties];+ updated[index] = { ...updated[index], notes: noteValue };+ setWarranties(updated);+ state.warranty = updated[index];+}++async function saveNotes() {+ if (!dom || !state.warrantyId || !state.warranty) {+ showToast(window.i18next ? window.i18next.t('messages.warranty_not_found_refresh') : 'Warranty not found', 'error');+ return;+ }+ const noteValue = dom.textarea.value.trim();+ if (!validateDuration(state.warranty)) {+ showToast(+ window.i18next+ ? window.i18next.t('messages.invalid_warranty_duration_before_notes')+ : 'Cannot save notes until warranty duration is valid.',+ 'error',+ 7000,+ );+ return;+ }+ const token = getToken();+ if (!token) {+ showToast(window.i18next ? window.i18next.t('messages.authentication_required') : 'Authentication required', 'error');+ return;+ }+ try {+ showLoadingSpinner();+ const formData = buildFormData(state.warranty, noteValue);+ const response = await fetch(`/api/warranties/${state.warrantyId}`, {+ method: 'PUT',+ headers: { Authorization: `Bearer ${token}` },+ body: formData,+ });+ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.error || `Failed to update note (Status: ${response.status})`);+ }+ hideLoadingSpinner();+ showToast(window.i18next ? window.i18next.t('messages.note_updated_successfully') : 'Note updated', 'success');+ updateStoreNotes(noteValue);+ if (!noteValue) {+ hideModal();+ } else if (dom) {+ dom.content.textContent = noteValue;+ exitEditMode();+ }+ await refreshWarranties();+ } catch (error) {+ hideLoadingSpinner();+ console.error('[notes] Failed to update note', error);+ showToast(error.message || (window.i18next ? window.i18next.t('messages.failed_to_update_note') : 'Failed to update note'), 'error');+ }+}++export function showNotesModal(notes, warrantyOrId = null) {+ const refs = ensureModal();+ // If warrantyOrId is already a warranty object, use it directly+ let warranty = null;+ if (warrantyOrId && typeof warrantyOrId === 'object' && warrantyOrId.id) {+ warranty = warrantyOrId;+ } else {+ warranty = resolveWarranty(warrantyOrId);+ }+ state.warrantyId = warranty?.id || (typeof warrantyOrId === 'number' ? warrantyOrId : null);+ state.warranty = warranty || null;+ const contentText = typeof notes === 'string' ? notes : warranty?.notes || '';+ if (!refs.modal) return;+ refs.content.textContent = contentText || '';+ refs.textarea.value = contentText || '';+ exitEditMode();+ refs.modal.classList.add('active');+}++export function init() {+ ensureModal();+}++// Global exposure - expose all public functions+if (typeof window !== 'undefined') {+ window.components = window.components || {};+ window.components.notes = {+ init,+ showNotesModal,+ };+}diff --git a/frontend/js/components/paperless.js b/frontend/js/components/paperless.jsindex 7272e65..7847b13 100644--- a/frontend/js/components/paperless.js+++ b/frontend/js/components/paperless.js@@ -1,3 +1,692 @@+import authService from '../services/authService.js';+import { showToast, showLoadingSpinner, hideLoadingSpinner } from './ui.js';+import { loadWarranties, applyFilters } from '../controllers/warrantyListController.js';+import { getIsGlobalView, getUserPreferencePrefix, setUserPreferencePrefix } from '../store.js';++let paperlessNgxEnabled = false;++const browserState = {+ isOpen: false,+ documentType: null,+ mode: 'add',+ currentPage: 1,+ totalPages: 1,+ searchQuery: '',+ documents: [],+};++function resolvePreferencePrefix() {+ let prefix = getUserPreferencePrefix();+ if (prefix) return prefix;+ const user = authService.getCurrentUser?.();+ prefix = user?.is_admin ? 'admin_' : 'user_';+ setUserPreferencePrefix(prefix);+ return prefix;+}++function getAuthToken() {+ return authService.getToken() || localStorage.getItem('auth_token');+}++function getSelectionInputId(documentType) {+ if (documentType.startsWith('edit_')) {+ const base = documentType.replace('edit_', '');+ return `selectedEditPaperless${capitalize(base)}`;+ }+ return `selectedPaperless${capitalize(documentType)}`;+}++function getSelectionDisplayId(documentType) {+ if (documentType.startsWith('edit_')) {+ return `selectedEdit${capitalize(documentType.replace('edit_', ''))}FromPaperless`;+ }+ return `selected${capitalize(documentType)}FromPaperless`;+}++function capitalize(value = '') {+ return value.charAt(0).toUpperCase() + value.slice(1);+}++export function showPaperlessUploadLoading(documentType) {+ let overlay = document.getElementById('paperless-upload-overlay');+ if (overlay) {+ overlay.style.display = 'flex';+ return;+ }+ overlay = document.createElement('div');+ overlay.id = 'paperless-upload-overlay';+ overlay.innerHTML = `+ <div class="paperless-upload-modal">+ <div class="paperless-upload-content">+ <div class="paperless-upload-spinner"></div>+ <h3>${window.t ? window.t('paperless.uploading_documents') : 'Uploading documents...'}</h3>+ <p id="paperless-upload-status">${window.t ? window.t('paperless.uploading', { documentType }) : `Uploading ${documentType}`} </p>+ <div class="paperless-upload-progress">+ <div class="paperless-upload-progress-bar" id="paperless-progress-bar"></div>+ </div>+ </div>+ </div>+ `;+ document.body.appendChild(overlay);+}++export function updatePaperlessUploadStatus(message, isProcessing = false) {+ const statusEl = document.getElementById('paperless-upload-status');+ const progressBar = document.getElementById('paperless-progress-bar');+ if (statusEl) statusEl.textContent = message;+ if (progressBar) {+ progressBar.classList.toggle('processing', isProcessing);+ }+}++export function hidePaperlessUploadLoading() {+ const overlay = document.getElementById('paperless-upload-overlay');+ if (!overlay) return;+ const progressBar = document.getElementById('paperless-progress-bar');+ if (progressBar) progressBar.classList.remove('processing');+ overlay.remove();+}++export async function checkPaperlessNgxStatus() {+ try {+ const token = getAuthToken();+ if (!token) return false;+ const response = await fetch('/api/admin/settings', {+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json',+ },+ });+ if (!response.ok) return false;+ const settings = await response.json();+ paperlessNgxEnabled = settings.paperless_enabled === 'true';+ window.paperlessNgxEnabled = paperlessNgxEnabled;+ return paperlessNgxEnabled;+ } catch (error) {+ console.error('[paperless] Failed to check status', error);+ return false;+ }+}++export async function initPaperlessIntegration() {+ const isEnabled = await checkPaperlessNgxStatus();+ const infoAlert = document.getElementById('paperlessInfoAlert');+ ['invoice', 'manual'].forEach((type) => {+ const addSelection = document.getElementById(`${type}StorageSelection`);+ const editSelection = document.getElementById(`edit${capitalize(type)}StorageSelection`);+ if (addSelection) addSelection.style.display = isEnabled ? 'block' : 'none';+ if (editSelection) editSelection.style.display = isEnabled ? 'block' : 'none';+ });+ if (infoAlert) infoAlert.style.display = isEnabled ? 'block' : 'none';+ togglePaperlessBrowseSections();+}++export function getStorageOption(documentType, isEdit = false) {+ const allowed = ['invoice', 'manual'];+ if (!allowed.includes(documentType)) return 'local';+ // For add form: invoiceStorage, manualStorage (lowercase)+ // For edit form: editInvoiceStorage, editManualStorage (capitalize after 'edit')+ const name = isEdit+ ? `edit${capitalize(documentType)}Storage`+ : `${documentType}Storage`;+ const radio = document.querySelector(`input[name="${name}"]:checked`);+ return radio ? radio.value : 'local';+}++async function uploadToPaperlessNgx(file, documentType) {+ try {+ const token = getAuthToken();+ if (!token) throw new Error('Authentication token not available');+ showPaperlessUploadLoading(documentType);++ const formData = new FormData();+ formData.append('file', file);+ formData.append('document_type', documentType);+ formData.append('title', `Warracker ${documentType} - ${file.name}`);+ formData.append('tags', ['warracker', documentType].join(','));++ updatePaperlessUploadStatus(window.t ? window.t('paperless.uploading_to_server') : 'Uploading file to Paperless-ngx...');+ const response = await fetch('/api/paperless/upload', {+ method: 'POST',+ headers: { Authorization: `Bearer ${token}` },+ body: formData,+ });+ if (!response.ok) {+ let errorMessage = window.t ? window.t('paperless.upload_failed') : 'Failed to upload to Paperless-ngx';+ try {+ const errorData = await response.json();+ errorMessage = errorData.error || errorMessage;+ } catch {+ errorMessage = `HTTP ${response.status}: ${response.statusText}`;+ }+ hidePaperlessUploadLoading();+ throw new Error(errorMessage);+ }+ const result = await response.json();+ if (result.document_id) {+ updatePaperlessUploadStatus(window.t ? window.t('paperless.upload_complete') : 'Document uploaded and ready!');+ } else {+ updatePaperlessUploadStatus(window.t ? window.t('paperless.upload_processing') : 'Document uploaded, processing...', true);+ }+ return {+ success: true,+ document_id: result.document_id,+ message: result.message,+ error: result.error,+ };+ } catch (error) {+ console.error('[paperless] Upload error', error);+ hidePaperlessUploadLoading();+ return { success: false, error: error.message };+ }+}++export async function processPaperlessUploads(formData) {+ if (!paperlessNgxEnabled) return {};+ const uploads = {};+ const documentTypes = ['invoice', 'manual'];+ for (const docType of documentTypes) {+ const storage = formData.get(`${docType}Storage`) || 'local';+ const input = document.getElementById(docType);+ const file = input?.files[0];+ if (storage === 'paperless' && file) {+ const uploadResult = await uploadToPaperlessNgx(file, docType);+ if (uploadResult.success || (uploadResult.error?.includes('duplicate') && uploadResult.document_id)) {+ const mapping = {+ productPhoto: 'paperless_photo_id',+ invoice: 'paperless_invoice_id',+ manual: 'paperless_manual_id',+ otherDocument: 'paperless_other_id',+ };+ const dbField = mapping[docType];+ if (dbField && uploadResult.document_id) {+ uploads[dbField] = uploadResult.document_id;+ hidePaperlessUploadLoading();+ if (uploadResult.error?.includes('duplicate')) {+ showToast(window.t ? window.t('paperless.duplicate_linked') : 'Duplicate document detected in Paperless-ngx. Linked to existing document.', 'info');+ }+ } else if (dbField && !uploadResult.document_id) {+ updatePaperlessUploadStatus(window.t ? window.t('paperless.processing_search') : 'Document processing, searching for link...', true);+ }+ if (formData.has(docType)) formData.delete(docType);+ } else {+ throw new Error(uploadResult.error || 'Failed to upload document to Paperless-ngx');+ }+ }+ }+ return uploads;+}++export async function processEditPaperlessUploads(formData) {+ if (!paperlessNgxEnabled) return {};+ const uploads = {};+ const documentTypes = ['invoice', 'manual'];+ for (const docType of documentTypes) {+ const storage = getStorageOption(docType, true);+ if (storage !== 'paperless') continue;+ const input = document.getElementById(`edit${capitalize(docType)}`);+ const file = input?.files[0];+ if (!file) continue;+ const uploadResult = await uploadToPaperlessNgx(file, docType);+ if (uploadResult.success || (uploadResult.error?.includes('duplicate') && uploadResult.document_id)) {+ const mapping = {+ productPhoto: 'paperless_photo_id',+ invoice: 'paperless_invoice_id',+ manual: 'paperless_manual_id',+ otherDocument: 'paperless_other_id',+ };+ const dbField = mapping[docType];+ if (dbField && uploadResult.document_id) {+ uploads[dbField] = uploadResult.document_id;+ hidePaperlessUploadLoading();+ if (uploadResult.error?.includes('duplicate')) {+ showToast(window.t ? window.t('paperless.duplicate_linked') : 'Duplicate document detected in Paperless-ngx. Linked to existing document.', 'info');+ }+ } else if (dbField && !uploadResult.document_id) {+ updatePaperlessUploadStatus(window.t ? window.t('paperless.processing_search') : 'Document processing, searching for link...', true);+ }+ if (formData.has(docType)) formData.delete(docType);+ } else {+ throw new Error(uploadResult.error || 'Failed to upload document to Paperless-ngx');+ }+ }+ return uploads;+}++async function debugPaperlessConfiguration() {+ try {+ const token = getAuthToken();+ if (!token) return null;+ const response = await fetch('/api/paperless/debug', {+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json',+ },+ });+ if (!response.ok) return null;+ return response.json();+ } catch (error) {+ console.error('[paperless] debug failed', error);+ return null;+ }+}++async function getUserPaperlessViewPreference(warrantyContext = null) {+ const prefix = resolvePreferencePrefix();+ const local = localStorage.getItem(`${prefix}paperlessViewInApp`);+ const globalView = getIsGlobalView();+ const currentUser = authService.getCurrentUser?.();+ if (warrantyContext && globalView && currentUser && warrantyContext.user_id && warrantyContext.user_id !== currentUser.id) {+ return true;+ }+ if (local !== null) return local === 'true';+ try {+ const token = getAuthToken();+ if (!token) return false;+ const response = await fetch('/api/auth/preferences', {+ headers: { Authorization: `Bearer ${token}` },+ });+ if (!response.ok) return false;+ const prefs = await response.json();+ return Boolean(prefs.paperless_view_in_app);+ } catch (error) {+ console.warn('[paperless] Failed to read user preference', error);+ return false;+ }+}++export async function openPaperlessDocument(paperlessId, warrantyContext = null) {+ try {+ const debugInfo = await debugPaperlessConfiguration();+ if (debugInfo && (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false')) {+ showToast(window.t ? window.t('paperless.disabled') : 'Paperless-ngx integration is not enabled', 'error');+ return;+ }+ const token = getAuthToken();+ if (!token) {+ showToast(window.t ? window.t('messages.authentication_required') : 'Authentication required', 'error');+ return;+ }+ const viewInApp = await getUserPaperlessViewPreference(warrantyContext);+ if (viewInApp) {+ const url = `/api/paperless-file/${paperlessId}?token=${encodeURIComponent(token)}`;+ const win = window.open(url, '_blank');+ if (!win) showToast(window.t ? window.t('paperless.popup_blocked') : 'Please allow popups to view documents', 'warning');+ return;+ }+ const response = await fetch('/api/paperless/url', {+ headers: { Authorization: `Bearer ${token}` },+ });+ if (!response.ok) throw new Error('Failed to get Paperless-ngx URL');+ const result = await response.json();+ if (!result.success) throw new Error(result.message || 'Failed to get Paperless-ngx URL');+ const baseUrl = result.url.replace(/\/$/, '');+ const docUrl = `${baseUrl}/documents/${paperlessId}/details`;+ const win = window.open(docUrl, '_blank');+ if (!win) showToast(window.t ? window.t('paperless.popup_blocked') : 'Please allow popups to view documents in Paperless-ngx', 'warning');+ } catch (error) {+ console.error('[paperless] openPaperlessDocument failed', error);+ showToast(error.message || 'Error opening document', 'error');+ }+}++export async function autoLinkRecentDocuments(warrantyId, documentTypes = ['invoice', 'manual'], maxRetries = 10, retryDelay = 10000, fileInfo = {}) {+ const token = getAuthToken();+ if (!token) return;+ let attempt = 0;+ const tryLinking = async () => {+ attempt += 1;+ try {+ const debugInfo = await debugPaperlessConfiguration();+ if (!debugInfo || !debugInfo.paperless_enabled) return;+ let linkedDocuments = [];+ for (const [docType, filename] of Object.entries(fileInfo)) {+ if (!documentTypes.includes(docType)) continue;+ const baseName = filename.replace(/\.[^/.]+$/, '');+ const queries = [filename, baseName, `"${filename}"`, `"${baseName}"`, `Warracker ${docType} - ${baseName}`];+ for (const query of queries) {+ const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(query)}`, {+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json',+ },+ });+ if (!response.ok) continue;+ const result = await response.json();+ const docs = result.results || [];+ const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);+ const recentDocs = docs.filter((doc) => {+ try {+ const docDate = new Date(doc.created);+ return docDate > oneDayAgo;+ } catch {+ return true;+ }+ });+ if (recentDocs.length > 0) {+ linkedDocuments = linkedDocuments.concat(recentDocs.map((doc) => ({ docType, document_id: doc.id })));+ break;+ }+ }+ }+ if (!linkedDocuments.length) {+ if (attempt < maxRetries) {+ setTimeout(tryLinking, retryDelay);+ } else {+ hidePaperlessUploadLoading();+ }+ return;+ }+ const linkPayload = {+ warranty_id: warrantyId,+ documents: linkedDocuments,+ };+ const response = await fetch('/api/paperless/link-documents', {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(linkPayload),+ });+ if (!response.ok) {+ throw new Error(await response.text());+ }+ hidePaperlessUploadLoading();+ showToast(window.t ? window.t('paperless.documents_linked') : 'Documents linked successfully', 'success');+ await loadWarranties(true);+ applyFilters();+ setTimeout(() => loadSecureImages(), 200);+ } catch (error) {+ console.error('[paperless] autoLink failed', error);+ if (attempt < maxRetries) {+ setTimeout(tryLinking, retryDelay);+ } else {+ hidePaperlessUploadLoading();+ }+ }+ };+ tryLinking();+}++export function openPaperlessBrowser(documentType) {+ browserState.documentType = documentType;+ browserState.mode = documentType.startsWith('edit_') ? 'edit' : 'add';+ browserState.currentPage = 1;+ browserState.searchQuery = '';+ const modal = document.getElementById('paperlessBrowserModal');+ if (modal) {+ modal.classList.add('active');+ fetchPaperlessDocuments();+ }+}++function closePaperlessBrowser() {+ const modal = document.getElementById('paperlessBrowserModal');+ if (modal) modal.classList.remove('active');+ browserState.documentType = null;+}++async function fetchPaperlessDocuments(page = 1, query = '') {+ try {+ const token = getAuthToken();+ if (!token) throw new Error('Authentication required');+ showPaperlessLoading();+ const params = new URLSearchParams({+ page: page.toString(),+ query,+ document_type: browserState.documentType.replace('edit_', ''),+ });+ const response = await fetch(`/api/paperless/documents?${params.toString()}`, {+ headers: { Authorization: `Bearer ${token}` },+ });+ if (!response.ok) throw new Error('Failed to fetch documents');+ const result = await response.json();+ browserState.currentPage = result.page || page;+ browserState.totalPages = result.total_pages || 1;+ browserState.documents = result.documents || [];+ renderPaperlessDocuments();+ updatePaperlessPagination();+ } catch (error) {+ console.error('[paperless] browse failed', error);+ showPaperlessError(error.message || 'Failed to load documents');+ }+}++function renderPaperlessDocuments() {+ const container = document.getElementById('paperlessDocumentsContainer');+ if (!container) return;+ container.textContent = '';+ if (!browserState.documents.length) {+ showPaperlessError(window.t ? window.t('paperless.no_documents_found') : 'No documents found');+ return;+ }+ browserState.documents.forEach((doc) => {+ const item = document.createElement('div');+ item.className = 'paperless-document-item';+ item.dataset.id = doc.id;+ item.innerHTML = `+ <div class="document-title">${doc.title || ''}</div>+ <div class="document-meta">+ <span><i class="fas fa-calendar"></i> ${doc.created ? new Date(doc.created).toLocaleDateString() : ''}</span>+ <span><i class="fas fa-file"></i> ${doc.mime_type || 'Unknown'}</span>+ ${doc.correspondent ? `<span><i class="fas fa-user"></i> ${doc.correspondent}</span>` : ''}+ </div>+ ${Array.isArray(doc.tags) && doc.tags.length ? `+ <div class="document-tags">+ ${doc.tags.map((tag) => `<span class="document-tag">${tag}</span>`).join('')}+ </div>` : ''}+ `;+ item.addEventListener('click', () => selectPaperlessDocument(doc.id));+ container.appendChild(item);+ });+}++function selectPaperlessDocument(documentId) {+ const doc = browserState.documents.find((d) => d.id === documentId);+ if (!doc) return;+ const type = browserState.documentType;+ const inputId = getSelectionInputId(type);+ const input = document.getElementById(inputId);+ if (input) input.value = documentId;+ updatePaperlessSelectionUI();+ closePaperlessBrowser();+}++function updatePaperlessSelectionUI() {+ const types = ['invoice', 'manual', 'productPhoto', 'otherDocument', 'edit_invoice', 'edit_manual', 'edit_productPhoto', 'edit_otherDocument'];+ types.forEach((type) => {+ const input = document.getElementById(getSelectionInputId(type));+ const display = document.getElementById(getSelectionDisplayId(type));+ if (!input || !display) return;+ if (input.value) {+ display.style.display = 'flex';+ display.querySelector('.selected-doc-name').textContent = `${window.t ? window.t('paperless.document_selected') : 'Document selected'} (#${input.value})`;+ } else {+ display.style.display = 'none';+ }+ });+}++export function clearPaperlessSelection(documentType) {+ const input = document.getElementById(getSelectionInputId(documentType));+ if (input) input.value = '';+ const display = document.getElementById(getSelectionDisplayId(documentType));+ if (display) display.style.display = 'none';+}++function changePage(direction) {+ const targetPage = browserState.currentPage + direction;+ if (targetPage < 1 || targetPage > browserState.totalPages) return;+ fetchPaperlessDocuments(targetPage, browserState.searchQuery);+}++function updatePaperlessPagination() {+ const current = document.getElementById('paperlessCurrentPage');+ const total = document.getElementById('paperlessTotalPages');+ if (current) current.textContent = browserState.currentPage;+ if (total) total.textContent = browserState.totalPages;+ const prev = document.getElementById('paperlessPrevBtn');+ const next = document.getElementById('paperlessNextBtn');+ if (prev) prev.disabled = browserState.currentPage <= 1;+ if (next) next.disabled = browserState.currentPage >= browserState.totalPages;+}++function showPaperlessLoading() {+ const container = document.getElementById('paperlessDocumentsContainer');+ if (!container) return;+ container.innerHTML = `<div class="loading-message">+ <i class="fas fa-spinner fa-spin"></i> ${window.t ? window.t('paperless.loading_documents') : 'Loading documents...'}+ </div>`;+}++function showPaperlessError(message) {+ const container = document.getElementById('paperlessDocumentsContainer');+ if (!container) return;+ container.innerHTML = `<div class="no-documents-message">+ <i class="fas fa-exclamation-triangle"></i>+ <h4>${window.t ? window.t('errors.error') : 'Error'}</h4>+ <p>${message}</p>+ </div>`;+}++export function togglePaperlessBrowseSections() {+ const browseSections = document.querySelectorAll('.paperless-browse-section');+ browseSections.forEach((section) => {+ section.style.display = paperlessNgxEnabled ? 'block' : 'none';+ });+}++// Image preload cache - stores blob URLs by secure path+const imageCache = new Map();++// Preload images from warranties data before rendering+export async function preloadWarrantyImages(warranties) {+ const token = getAuthToken();+ if (!token || !Array.isArray(warranties)) return;++ const imagePaths = warranties+ .filter(w => w.product_photo_path && w.product_photo_path !== 'null')+ .map(w => {+ const sanitizedPath = w.product_photo_path.replace('uploads/', '');+ return `/api/secure-file/${sanitizedPath}`;+ })+ .filter(path => !imageCache.has(path)); // Only load uncached images++ if (imagePaths.length === 0) return;++ // Preload all images in parallel+ const loadPromises = imagePaths.map(async (secureUrl) => {+ try {+ const response = await fetch(secureUrl, {+ headers: { Authorization: `Bearer ${token}` },+ });+ if (!response.ok) return;+ const blob = await response.blob();+ const blobUrl = URL.createObjectURL(blob);+ imageCache.set(secureUrl, blobUrl);+ } catch (error) {+ // Silently fail for preload - will retry on render+ }+ });++ await Promise.all(loadPromises);+}++export async function loadSecureImages() {+ const token = getAuthToken();+ if (!token) return;+ const secureImages = document.querySelectorAll('img.secure-image[data-secure-src]');++ // Load all images in parallel for better performance+ const loadPromises = Array.from(secureImages).map(async (img) => {+ try {+ const existingBlobUrl = img.getAttribute('data-blob-url');+ // Skip if already loaded and has valid blob URL+ if (img.classList.contains('loaded') && existingBlobUrl && img.src.startsWith('blob:')) {+ return;+ }+ // Clean up existing blob URL if present+ if (existingBlobUrl) {+ URL.revokeObjectURL(existingBlobUrl);+ img.removeAttribute('data-blob-url');+ img.classList.remove('loaded');+ }+ const secureUrl = img.getAttribute('data-secure-src');++ // Check cache first for instant loading+ if (imageCache.has(secureUrl)) {+ const cachedBlobUrl = imageCache.get(secureUrl);+ img.src = cachedBlobUrl;+ img.setAttribute('data-blob-url', cachedBlobUrl);+ img.classList.add('loaded');+ return;+ }++ // Fetch if not in cache+ const response = await fetch(secureUrl, {+ headers: { Authorization: `Bearer ${token}` },+ });+ if (!response.ok) {+ img.style.display = 'none';+ return;+ }+ const blob = await response.blob();+ const blobUrl = URL.createObjectURL(blob);+ img.src = blobUrl;+ img.setAttribute('data-blob-url', blobUrl);+ img.classList.add('loaded');+ // Also cache for future use+ imageCache.set(secureUrl, blobUrl);+ } catch (error) {+ console.error('[paperless] loadSecureImages failed for', img.getAttribute('data-secure-src'), error);+ img.style.display = 'none';+ }+ });++ await Promise.all(loadPromises);+}++// Clear cache (call when user logs out or warranties change significantly)+export function clearImageCache() {+ imageCache.forEach((blobUrl) => URL.revokeObjectURL(blobUrl));+ imageCache.clear();+}++if (typeof window !== 'undefined') {+ window.openPaperlessDocument = openPaperlessDocument;+ window.openPaperlessBrowser = openPaperlessBrowser;+ window.clearPaperlessSelection = clearPaperlessSelection;+ window.autoLinkRecentDocuments = autoLinkRecentDocuments;+ window.loadSecureImages = loadSecureImages;+ window.preloadWarrantyImages = preloadWarrantyImages;+ window.clearImageCache = clearImageCache;+ window.changePage = changePage;+ // Expose via components namespace for modular access+ window.components = window.components || {};+ window.components.paperless = {+ loadSecureImages,+ preloadWarrantyImages,+ clearImageCache,+ };+}++export default {+ initPaperlessIntegration,+ processPaperlessUploads,+ processEditPaperlessUploads,+ openPaperlessDocument,+ autoLinkRecentDocuments,+ openPaperlessBrowser,+ clearPaperlessSelection,+ togglePaperlessBrowseSections,+ showPaperlessUploadLoading,+ updatePaperlessUploadStatus,+ hidePaperlessUploadLoading,+ loadSecureImages,+ preloadWarrantyImages,+ clearImageCache,+};function el(tag, className, text) {const e = document.createElement(tag);if (className) e.className = className;diff --git a/frontend/js/components/serialNumbers.js b/frontend/js/components/serialNumbers.jsnew file mode 100644index 0000000..e5e02b1--- /dev/null+++ b/frontend/js/components/serialNumbers.js@@ -0,0 +1,162 @@+/**+ * Serial Numbers Management Component+ * Handles adding/removing serial number inputs in warranty forms+ */++function addSerialNumberInput(container) {+ // If no container provided, try to find it+ if (!container) {+ container = document.getElementById('serialNumbersContainer');+ }++ // Check if the container exists before proceeding+ if (!container) {+ console.warn('Serial numbers container not found, cannot add input.');+ return;+ }++ const div = document.createElement('div');+ div.className = 'serial-number-input d-flex mb-2';++ // Create an input element+ const input = document.createElement('input');+ input.type = 'text';+ input.className = 'form-control';+ input.name = 'serial_numbers[]';+ input.placeholder = window.i18next ? window.i18next.t('warranties.enter_serial_number') : 'Enter serial number';++ // Check if this is the first serial number input+ const isFirstInput = container.querySelectorAll('.serial-number-input').length === 0;++ // Append input to the input group+ div.appendChild(input);++ // Only add remove button if this is not the first input+ if (!isFirstInput) {+ // Create a remove button+ const removeButton = document.createElement('button');+ removeButton.type = 'button';+ removeButton.className = 'btn btn-sm btn-danger remove-serial';+ removeButton.innerHTML = '<i class="fas fa-times"></i>';++ // Add event listener to remove button+ removeButton.addEventListener('click', function() {+ container.removeChild(div);+ });++ // Append remove button to the input group+ div.appendChild(removeButton);+ }++ // Insert the new input group before the add button+ const addButton = container.querySelector('.add-serial');+ if (addButton) {+ container.insertBefore(div, addButton);+ } else {+ container.appendChild(div);++ // Create and append an add button if it doesn't exist+ const newAddButton = document.createElement('button');+ newAddButton.type = 'button';+ newAddButton.className = 'btn btn-sm btn-secondary add-serial';+ newAddButton.innerHTML = '<i class="fas fa-plus"></i> ' + (window.i18next ? window.i18next.t('warranties.add_serial_number') : 'Add Serial Number');++ newAddButton.addEventListener('click', function() {+ addSerialNumberInput(container);+ });++ container.appendChild(newAddButton);+ }+}++function removeSerialNumberInput(inputElement) {+ if (inputElement && inputElement.parentNode) {+ inputElement.parentNode.remove();+ }+}++function clearSerialNumbers(container) {+ if (!container) {+ container = document.getElementById('serialNumbersContainer');+ }++ if (container) {+ container.innerHTML = '';+ }+}++function getSerialNumbers(container) {+ if (!container) {+ container = document.getElementById('serialNumbersContainer');+ }++ if (!container) {+ return [];+ }++ const serialNumbers = [];+ const inputs = container.querySelectorAll('input[name="serial_numbers[]"]');+ inputs.forEach(input => {+ if (input.value && input.value.trim()) {+ serialNumbers.push(input.value.trim());+ }+ });++ return serialNumbers;+}++function setSerialNumbers(serialNumbers, container) {+ if (!container) {+ container = document.getElementById('serialNumbersContainer');+ }++ if (!container) {+ console.warn('Serial numbers container not found');+ return;+ }++ // Clear existing inputs+ clearSerialNumbers(container);++ // Add serial number inputs+ if (serialNumbers && serialNumbers.length > 0) {+ serialNumbers.forEach((serialNumber) => {+ addSerialNumberInput(container);+ const inputs = container.querySelectorAll('input[name="serial_numbers[]"]');+ const lastInput = inputs[inputs.length - 1];+ if (lastInput) {+ lastInput.value = serialNumber;+ }+ });+ } else {+ // Add at least one empty input+ addSerialNumberInput(container);+ }+}++// Export functions+export {+ addSerialNumberInput,+ removeSerialNumberInput,+ clearSerialNumbers,+ getSerialNumbers,+ setSerialNumbers+};++// Expose to window for backward compatibility+if (typeof window !== 'undefined') {+ window.serialNumbers = {+ add: addSerialNumberInput,+ remove: removeSerialNumberInput,+ clear: clearSerialNumbers,+ get: getSerialNumbers,+ set: setSerialNumbers+ };++ // Also expose individual functions+ window.addSerialNumberInput = addSerialNumberInput;+ window.removeSerialNumberInput = removeSerialNumberInput;+ window.clearSerialNumbers = clearSerialNumbers;+ window.getSerialNumbers = getSerialNumbers;+ window.setSerialNumbers = setSerialNumbers;+}diff --git a/frontend/js/components/tagManager.js b/frontend/js/components/tagManager.jsindex 0588aaa..06ee65c 100644--- a/frontend/js/components/tagManager.js+++ b/frontend/js/components/tagManager.js@@ -1,95 +1,564 @@-// Tag Manager (compat layer)-// Encapsulates tag management by delegating to existing global implementations to keep behavior identical.+import {+ getAllTags,+ setAllTags,+ getSelectedTags,+ setSelectedTags,+ getEditSelectedTags,+ setEditSelectedTags,+ getWarranties,+ setWarranties,+ areWarrantiesLoaded,+ wasLastLoadedArchived,+ didLastLoadIncludeArchived,+} from '../store.js';+import {+ getTags as fetchTags,+ createTagRequest,+ updateTagRequest,+ deleteTagRequest,+} from '../services/apiService.js';+import { showToast, showLoadingSpinner, hideLoadingSpinner } from './ui.js';+import { renderWarrantiesList } from './warrantyRenderer.js';-function callIfExists(fn, ...args) {- if (typeof fn === 'function') {- return fn(...args);- }+// Safe translation helper that works even if i18next isn't fully loaded+function t(key, options = {}) {+ // Try window.i18next first (the actual i18next library)+ if (window.i18next?.t) {+ return window.i18next.t(key, options);+ }+ // Try window.i18n.t (wrapper set by i18n.js)+ if (window.i18n?.t) {+ return window.i18n.t(key, options);+ }+ // Try window.t (global helper)+ if (window.t) {+ return window.t(key, options);+ }+ // Return defaultValue if provided, otherwise the key+ return options.defaultValue || key;}-export function loadTags(force = false) {- return callIfExists(window.loadTags, force);+const selectors = {+ main: {+ tagSearch: 'tagSearch',+ tagsList: 'tagsList',+ manageBtn: 'manageTagsBtn',+ selectedContainer: 'selectedTags',+ },+ edit: {+ tagsList: 'editTagsList',+ selectedContainer: 'editSelectedTags',+ },+ modal: {+ root: 'tagManagementModal',+ existingTags: 'existingTags',+ newTagForm: 'newTagForm',+ tagNameInput: 'newTagName',+ tagColorInput: 'newTagColor',+ },+};++const state = {+ listenersBound: false,+};++function getElement(id) {+ return document.getElementById(id);+}++function updateWarrantiesInStore(mapper) {+ const current = getWarranties();+ if (!Array.isArray(current) || current.length === 0) return;+ const updated = current.map((warranty) => {+ if (!Array.isArray(warranty.tags)) return warranty;+ const nextTags = mapper(warranty.tags);+ if (nextTags === warranty.tags) return warranty;+ return { ...warranty, tags: nextTags };+ });+ setWarranties(updated, {+ warrantiesLoaded: areWarrantiesLoaded(),+ lastLoadedArchived: wasLastLoadedArchived(),+ lastLoadedIncludesArchived: didLastLoadIncludeArchived(),+ });+ renderWarrantiesList(updated);+}++function dispatchTagsUpdatedEvent() {+ window.dispatchEvent(new CustomEvent('tags:updated', { detail: { tags: getAllTags() } }));+}++export async function loadTags(force = false) {+ if (!force && getAllTags().length) return;+ try {+ const tags = await fetchTags(force);+ setAllTags(Array.isArray(tags) ? tags : []);+ dispatchTagsUpdatedEvent();+ } catch (error) {+ console.error('[tagManager] Failed to load tags', error);+ setAllTags([]);+ }}-export function initTagFunctionality() {- return callIfExists(window.initTagFunctionality);+function ensureTagsLoaded() {+ if (!getAllTags().length) {+ loadTags().catch(() => {});+ }+}++function renderDropdownList(container, tags, selected, onSelect, searchTerm = '') {+ if (!container) return;+ container.innerHTML = '';+ const normalized = searchTerm.trim().toLowerCase();++ const filtered = tags.filter((tag) => !normalized || tag.name.toLowerCase().includes(normalized));+ if (normalized && !filtered.some((tag) => tag.name.toLowerCase() === normalized)) {+ const createOption = document.createElement('div');+ createOption.className = 'tag-option create-tag';+ // Use i18next directly with fallback+ const createText = window.i18next?.t('tags.create_with_name', { name: searchTerm, defaultValue: `Create "${searchTerm}"` }) || `Create "${searchTerm}"`;+ createOption.innerHTML = `<i class="fas fa-plus"></i> ${createText}`;+ createOption.addEventListener('click', async () => {+ try {+ const created = await createTag(searchTerm);+ setSelectedTags([...getSelectedTags(), created]);+ renderSelectedTags();+ if (typeof window.updateSummary === 'function') window.updateSummary();+ // Re-render the dropdown to show the new tag as selected+ renderDropdownList(container, [...getAllTags()], getSelectedTags(), onSelect, '');+ } finally {+ container.classList.remove('show');+ }+ });+ container.appendChild(createOption);+ }++ filtered.forEach((tag) => {+ const option = document.createElement('div');+ option.className = 'tag-option';+ const isSelected = selected.some((selectedTag) => selectedTag.id === tag.id);+ option.innerHTML = `+ <span class="tag-color" style="background-color: ${tag.color}"></span>+ ${tag.name}+ <span class="tag-status">${isSelected ? '<i class="fas fa-check"></i>' : ''}</span>+ `;+ option.addEventListener('click', () => onSelect(tag, isSelected));+ container.appendChild(option);+ });++ container.classList.add('show');}export function renderTagsList(searchTerm = '') {- return callIfExists(window.renderTagsList, searchTerm);+ const input = getElement(selectors.main.tagSearch);+ const list = getElement(selectors.main.tagsList);+ if (!input || !list) return;+ ensureTagsLoaded();+ renderDropdownList(+ list,+ getAllTags(),+ getSelectedTags(),+ (tag, isSelected) => {+ const current = getSelectedTags();+ const next = isSelected ? current.filter((t) => t.id !== tag.id) : [...current, tag];+ setSelectedTags(next);+ renderSelectedTags();+ if (typeof window.updateSummary === 'function') window.updateSummary();+ renderTagsList(searchTerm);+ },+ searchTerm || input.value,+ );}export function renderEditTagsList(searchTerm = '') {- return callIfExists(window.renderEditTagsList, searchTerm);+ const list = getElement(selectors.edit.tagsList);+ if (!list) return;+ ensureTagsLoaded();+ renderDropdownList(+ list,+ getAllTags(),+ getEditSelectedTags(),+ (tag, isSelected) => {+ const current = getEditSelectedTags();+ const next = isSelected ? current.filter((t) => t.id !== tag.id) : [...current, tag];+ setEditSelectedTags(next);+ renderEditSelectedTags();+ renderEditTagsList(searchTerm);+ },+ searchTerm,+ );}export function renderSelectedTags() {- return callIfExists(window.renderSelectedTags);+ const container = getElement(selectors.main.selectedContainer);+ if (!container) return;+ container.innerHTML = '';+ const tags = getSelectedTags();+ if (!tags.length) {+ const placeholder = document.createElement('span');+ placeholder.className = 'no-tags-selected';+ placeholder.textContent = t('tags.no_selected', { defaultValue: 'No tags selected' });+ container.appendChild(placeholder);+ return;+ }+ tags.forEach((tag) => {+ const tagElement = document.createElement('span');+ tagElement.className = 'tag';+ tagElement.style.backgroundColor = tag.color;+ tagElement.style.color = getContrastColor(tag.color);+ tagElement.innerHTML = `+ ${tag.name}+ <span class="remove-tag" data-id="${tag.id}">×</span>+ `;+ tagElement.querySelector('.remove-tag').addEventListener('click', (event) => {+ event.stopPropagation();+ setSelectedTags(getSelectedTags().filter((t) => t.id !== tag.id));+ renderSelectedTags();+ if (typeof window.updateSummary === 'function') window.updateSummary();+ });+ container.appendChild(tagElement);+ });}export function renderEditSelectedTags() {- return callIfExists(window.renderEditSelectedTags);+ const container = getElement(selectors.edit.selectedContainer);+ if (!container) return;+ container.innerHTML = '';+ const tags = getEditSelectedTags();+ if (!tags.length) {+ const placeholder = document.createElement('span');+ placeholder.className = 'no-tags-selected';+ placeholder.textContent = t('tags.no_selected', { defaultValue: 'No tags selected' });+ container.appendChild(placeholder);+ return;+ }+ tags.forEach((tag) => {+ const tagElement = document.createElement('span');+ tagElement.className = 'tag';+ tagElement.style.backgroundColor = tag.color;+ tagElement.style.color = getContrastColor(tag.color);+ tagElement.innerHTML = `+ ${tag.name}+ <span class="remove-tag" data-id="${tag.id}">×</span>+ `;+ tagElement.querySelector('.remove-tag').addEventListener('click', (event) => {+ event.preventDefault();+ setEditSelectedTags(getEditSelectedTags().filter((t) => t.id !== tag.id));+ renderEditSelectedTags();+ });+ container.appendChild(tagElement);+ });+}++function getContrastColor(hexColor) {+ if (!hexColor || !hexColor.startsWith('#') || hexColor.length < 7) return '#000000';+ const r = parseInt(hexColor.substr(1, 2), 16);+ const g = parseInt(hexColor.substr(3, 2), 16);+ const b = parseInt(hexColor.substr(5, 2), 16);+ const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;+ return yiq >= 128 ? '#000000' : '#ffffff';}-export function createTag(name) {- return callIfExists(window.createTag, name);+export async function createTag(name, color) {+ const trimmed = (name || '').trim();+ if (!trimmed) {+ showToast(t('messages.tag_name_required', { defaultValue: 'Tag name is required' }), 'error');+ throw new Error('Tag name required');+ }+ const chosenColor = color || `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')}`;+ const payload = { name: trimmed, color: chosenColor };+ try {+ const tag = await createTagRequest(payload);+ setAllTags([...getAllTags(), tag]);+ showToast(t('messages.tag_created_successfully', { defaultValue: 'Tag created' }), 'success');+ dispatchTagsUpdatedEvent();+ return tag;+ } catch (error) {+ showToast(error.message || t('messages.failed_to_create_tag', { defaultValue: 'Failed to create tag' }), 'error');+ throw error;+ }}-export function updateTag(id, name, color) {- return callIfExists(window.updateTag, id, name, color);+export async function updateTag(id, name, color) {+ try {+ const currentTag = getAllTags().find((tag) => tag.id === id);+ const resolvedColor = color || currentTag?.color || '#808080';+ const payload = { name, color: resolvedColor };+ const updated = await updateTagRequest(id, payload);+ await loadTags(true);+ syncSelectionsWithTag(updated);+ updateWarrantiesInStore((tags) => tags.map((tag) => (tag.id === updated.id ? { ...tag, name: updated.name, color: updated.color } : tag)));+ renderExistingTags();+ renderSelectedTags();+ renderEditSelectedTags();+ dispatchTagsUpdatedEvent();+ showToast(t('messages.tag_updated_successfully', { defaultValue: 'Tag updated' }), 'success');+ } catch (error) {+ showToast(error.message || t('messages.failed_to_update_tag', { defaultValue: 'Failed to update tag' }), 'error');+ }}-export function deleteTag(id) {- return callIfExists(window.deleteTag, id);+function syncSelectionsWithTag(tag) {+ const updateList = (list) => list.map((item) => (item.id === tag.id ? { ...item, name: tag.name, color: tag.color } : item));+ setSelectedTags(updateList(getSelectedTags()));+ setEditSelectedTags(updateList(getEditSelectedTags()));+}++export async function deleteTag(id) {+ if (!window.confirm(t('tags.confirm_delete', { defaultValue: 'Delete this tag?' }))) return;+ try {+ showLoadingSpinner();+ await deleteTagRequest(id);+ setAllTags(getAllTags().filter((tag) => tag.id !== id));+ setSelectedTags(getSelectedTags().filter((tag) => tag.id !== id));+ setEditSelectedTags(getEditSelectedTags().filter((tag) => tag.id !== id));+ updateWarrantiesInStore((tags) => tags.filter((tag) => tag.id !== id));+ renderExistingTags();+ renderSelectedTags();+ renderEditSelectedTags();+ dispatchTagsUpdatedEvent();+ showToast(t('messages.tag_deleted_successfully', { defaultValue: 'Tag deleted' }), 'success');+ } catch (error) {+ showToast(error.message || t('messages.failed_to_delete_tag', { defaultValue: 'Failed to delete tag' }), 'error');+ } finally {+ hideLoadingSpinner();+ }}export function openTagManagementModal() {- return callIfExists(window.openTagManagementModal);+ const modal = getElement(selectors.modal.root);+ if (!modal) return;+ ensureTagsLoaded();+ renderExistingTags();+ modal.classList.add('active');}export function renderExistingTags() {- return callIfExists(window.renderExistingTags);+ const container = getElement(selectors.modal.existingTags);+ if (!container) return;+ container.innerHTML = '';+ const tags = getAllTags();+ const wrapper = document.createElement('div');+ wrapper.className = 'table-responsive';+ const table = document.createElement('table');+ table.className = 'tag-management-table';+ const thead = document.createElement('thead');+ thead.innerHTML = `+ <tr>+ <th>${t('tags.color', { defaultValue: 'Color' })}</th>+ <th>${t('tags.name', { defaultValue: 'Name' })}</th>+ <th>${t('tags.actions', { defaultValue: 'Actions' })}</th>+ </tr>+ `;+ table.appendChild(thead);+ const tbody = document.createElement('tbody');+ if (!tags.length) {+ const row = document.createElement('tr');+ row.innerHTML = `<td colspan="3"><div class="no-tags">${t('messages.no_tags_created_yet', { defaultValue: 'No tags created yet' })}</div></td>`;+ tbody.appendChild(row);+ } else {+ tags.forEach((tag) => {+ const row = document.createElement('tr');+ row.className = 'existing-tag-row';+ row.dataset.id = String(tag.id);+ row.innerHTML = `+ <td>+ <div class="tag-color-swatch-container">+ <div class="tag-color-swatch" style="background-color: ${tag.color}" aria-label="${tag.name}"></div>+ <input type="color" class="tag-color-input-hidden" value="${tag.color}" aria-label="${t('tags.pick_color', { defaultValue: 'Pick color' })}" />+ </div>+ </td>+ <td>+ <span class="tag-name-display">${tag.name}</span>+ <input type="text" class="form-control tag-name-input" value="${tag.name}" />+ </td>+ <td class="tag-actions">+ <div class="view-actions">+ <button class="btn btn-sm btn-secondary edit-tag"><i class="fas fa-edit"></i></button>+ <button class="btn btn-sm btn-danger delete-tag"><i class="fas fa-trash"></i></button>+ </div>+ <div class="edit-actions">+ <button class="btn btn-sm btn-primary save-tag"><i class="fas fa-check"></i></button>+ <button class="btn btn-sm btn-secondary cancel-edit"><i class="fas fa-times"></i></button>+ </div>+ </td>+ `;+ tbody.appendChild(row);+ });+ }+ table.appendChild(tbody);+ wrapper.appendChild(table);+ container.appendChild(wrapper);+ bindTagManagementDelegates();+}++function bindTagManagementDelegates() {+ if (state.listenersBound) return;+ const container = getElement(selectors.modal.existingTags);+ if (!container) return;+ state.listenersBound = true;+ container.addEventListener('click', (event) => {+ const row = event.target.closest('tr.existing-tag-row');+ if (!row) return;+ const id = parseInt(row.dataset.id, 10);+ if (Number.isNaN(id)) return;+ if (event.target.closest('.edit-tag')) {+ enterEditMode(row);+ return;+ }+ if (event.target.closest('.cancel-edit')) {+ exitEditMode(row);+ return;+ }+ if (event.target.closest('.save-tag')) {+ const nameInput = row.querySelector('.tag-name-input');+ const colorInput = row.querySelector('.tag-color-input-hidden');+ const newName = nameInput ? nameInput.value.trim() : '';+ const newColor = colorInput ? colorInput.value : undefined;+ if (!newName) {+ showToast(t('messages.tag_name_required', { defaultValue: 'Tag name is required' }), 'error');+ return;+ }+ updateTag(id, newName, newColor);+ exitEditMode(row);+ return;+ }+ if (event.target.closest('.delete-tag')) {+ deleteTag(id);+ }+ });++ container.addEventListener('input', (event) => {+ if (!event.target.matches('.tag-color-input-hidden')) return;+ const row = event.target.closest('tr.existing-tag-row');+ const swatch = row ? row.querySelector('.tag-color-swatch') : null;+ if (swatch) swatch.style.backgroundColor = event.target.value;+ });++ container.addEventListener('change', (event) => {+ if (!event.target.matches('.tag-color-input-hidden')) return;+ const row = event.target.closest('tr.existing-tag-row');+ if (!row) return;+ const id = parseInt(row.dataset.id, 10);+ if (Number.isNaN(id)) return;+ const nameInput = row.querySelector('.tag-name-input');+ const nameDisplay = row.querySelector('.tag-name-display');+ const name = nameInput && nameInput.style.display !== 'none'+ ? nameInput.value.trim()+ : (nameDisplay ? nameDisplay.textContent.trim() : '');+ if (!name) {+ showToast(window.t ? window.t('messages.tag_name_required') : 'Tag name is required', 'error');+ return;+ }+ updateTag(id, name, event.target.value);+ });+}++function enterEditMode(row) {+ const nameDisplay = row.querySelector('.tag-name-display');+ const nameInput = row.querySelector('.tag-name-input');+ const viewActions = row.querySelector('.view-actions');+ const editActions = row.querySelector('.edit-actions');+ if (!nameDisplay || !nameInput || !viewActions || !editActions) return;+ nameDisplay.style.display = 'none';+ nameInput.style.display = 'block';+ viewActions.style.display = 'none';+ editActions.style.display = 'flex';+ row.classList.add('editing');+}++function exitEditMode(row) {+ const nameDisplay = row.querySelector('.tag-name-display');+ const nameInput = row.querySelector('.tag-name-input');+ const viewActions = row.querySelector('.view-actions');+ const editActions = row.querySelector('.edit-actions');+ if (nameDisplay) nameDisplay.style.display = '';+ if (nameInput) nameInput.style.display = 'none';+ if (viewActions) viewActions.style.display = '';+ if (editActions) editActions.style.display = 'none';+ row.classList.remove('editing');}export function addTagManagementEventListeners() {- return callIfExists(window.addTagManagementEventListeners);+ const modal = getElement(selectors.modal.root);+ if (!modal || modal.dataset.listenersBound === 'true') return;+ modal.dataset.listenersBound = 'true';+ const form = getElement(selectors.modal.newTagForm);+ if (form) {+ form.addEventListener('submit', async (event) => {+ event.preventDefault();+ const nameInput = getElement(selectors.modal.tagNameInput);+ const colorInput = getElement(selectors.modal.tagColorInput);+ const name = nameInput ? nameInput.value.trim() : '';+ const color = colorInput ? colorInput.value : '#808080';+ if (!name) {+ showToast(window.t ? window.t('messages.tag_name_required') : 'Tag name is required', 'error');+ return;+ }+ try {+ await createTag(name, color);+ renderExistingTags();+ renderSelectedTags();+ renderEditSelectedTags();+ if (nameInput) nameInput.value = '';+ if (colorInput) colorInput.value = '#808080';+ } catch (error) {+ showToast(error.message || t('messages.failed_to_create_tag', { defaultValue: 'Failed to create tag' }), 'error');+ }+ });+ }}-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- };+function bindMainFormEvents() {+ const searchInput = getElement(selectors.main.tagSearch);+ const list = getElement(selectors.main.tagsList);+ const manageBtn = getElement(selectors.main.manageBtn);+ if (!searchInput || !list || !manageBtn) return;+ searchInput.addEventListener('focus', () => renderTagsList(searchInput.value));+ searchInput.addEventListener('input', () => renderTagsList(searchInput.value));+ document.addEventListener('click', (event) => {+ if (!searchInput.contains(event.target) && !list.contains(event.target)) {+ list.classList.remove('show');+ }+ });+ manageBtn.addEventListener('click', (event) => {+ event.preventDefault();+ openTagManagementModal();+ });}+export function init() {+ ensureTagsLoaded();+ bindMainFormEvents();+ renderSelectedTags();+ addTagManagementEventListeners();+ const globalBtn = document.getElementById('globalManageTagsBtn');+ if (globalBtn && !globalBtn._tagBound) {+ globalBtn.addEventListener('click', async (event) => {+ event.preventDefault();+ await loadTags(true);+ openTagManagementModal();+ });+ globalBtn._tagBound = true;+ }+}+// Legacy exposure during transition+if (typeof window !== 'undefined') {+ window.components = window.components || {};+ window.components.tagManager = {+ init,+ loadTags,+ renderTagsList,+ renderEditTagsList,+ renderSelectedTags,+ renderEditSelectedTags,+ createTag,+ updateTag,+ deleteTag,+ openTagManagementModal,+ renderExistingTags,+ addTagManagementEventListeners,+ };+ // Also expose at root for backwards compatibility+ window.tagManager = window.components.tagManager;+}diff --git a/frontend/js/components/ui.js b/frontend/js/components/ui.jsindex 38f083c..ab2fd20 100644--- a/frontend/js/components/ui.js+++ b/frontend/js/components/ui.js@@ -5,6 +5,98 @@ function el(tag, className, text) {return e;}+const getLoadingContainer = () => window.loadingContainer || document.getElementById('loadingContainer');+const getToastContainer = () => document.getElementById('toastContainer');++export function showLoading() {+ const container = getLoadingContainer();+ if (container) {+ container.classList.add('active');+ window.loadingContainer = container;+ } else {+ console.error('showLoading: #loadingContainer not found');+ }+}++export function hideLoading() {+ const container = getLoadingContainer();+ if (container) {+ container.classList.remove('active');+ window.loadingContainer = container;+ } else {+ console.error('hideLoading: #loadingContainer not found');+ }+}++export function showLoadingSpinner() {+ const container = getLoadingContainer();+ if (container) {+ container.style.display = 'flex';+ window.loadingContainer = container;+ }+}++export function hideLoadingSpinner() {+ const container = getLoadingContainer();+ if (container) {+ container.style.display = 'none';+ window.loadingContainer = container;+ }+}++export function showToast(message, type = 'info', duration = 5000) {+ const toastContainer = getToastContainer();+ if (!toastContainer) return null;++ const existingToasts = toastContainer.querySelectorAll(`.toast.toast-${type}`);+ for (let i = 0; i < existingToasts.length; i += 1) {+ const span = existingToasts[i].querySelector('span');+ if (span && span.textContent === message) {+ return existingToasts[i];+ }+ }++ const toast = document.createElement('div');+ toast.className = `toast toast-${type}`;++ const icon = document.createElement('i');+ switch (type) {+ case 'success':+ icon.className = 'fas fa-check-circle';+ break;+ case 'error':+ icon.className = 'fas fa-exclamation-circle';+ break;+ case 'warning':+ icon.className = 'fas fa-exclamation-triangle';+ break;+ default:+ icon.className = 'fas fa-info-circle';+ }++ const messageSpan = document.createElement('span');+ messageSpan.textContent = message;++ toast.appendChild(icon);+ toast.appendChild(messageSpan);+ toastContainer.appendChild(toast);++ toast.remove = function removeToast() {+ toast.classList.add('toast-fade-out');+ setTimeout(() => {+ if (toast.parentNode) {+ toast.parentNode.removeChild(toast);+ }+ }, 300);+ };++ if (duration > 0) {+ setTimeout(() => toast.remove(), duration);+ }++ return toast;+}+export function renderEmptyState(container, message) {if (!container) return;container.textContent = '';@@ -21,7 +113,19 @@ export function renderEmptyState(container, message) {// Global exposeif (typeof window !== 'undefined') {window.components = window.components || {};- window.components.ui = { renderEmptyState };+ window.components.ui = {+ renderEmptyState,+ showLoading,+ hideLoading,+ showLoadingSpinner,+ hideLoadingSpinner,+ showToast,+ };+ window.showLoading = showLoading;+ window.hideLoading = hideLoading;+ window.showLoadingSpinner = showLoadingSpinner;+ window.hideLoadingSpinner = hideLoadingSpinner;+ window.showToast = showToast;}diff --git a/frontend/js/components/warrantyActions.js b/frontend/js/components/warrantyActions.jsnew file mode 100644index 0000000..a235458--- /dev/null+++ b/frontend/js/components/warrantyActions.js@@ -0,0 +1,103 @@+import { deleteWarranty as apiDeleteWarranty, request } from '../services/apiService.js';+import { showToast, showLoadingSpinner, hideLoadingSpinner } from './ui.js';+import { loadWarranties, applyFilters } from '../controllers/warrantyListController.js';+import { getCurrentWarrantyId, setCurrentWarrantyId } from '../store.js';++async function toggleArchiveStatus(warrantyId, shouldArchive) {+ if (!warrantyId) {+ showToast(window.i18next ? window.i18next.t('messages.no_warranty_selected') : 'No warranty selected', 'error');+ return;+ }+ try {+ showLoadingSpinner();+ await request(`/api/warranties/${warrantyId}/archive`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ archived: !!shouldArchive }),+ });+ hideLoadingSpinner();+ showToast(+ shouldArchive+ ? window.i18next ? window.i18next.t('messages.archived_success') : 'Warranty archived'+ : window.i18next ? window.i18next.t('messages.unarchived_success') : 'Warranty unarchived',+ 'success',+ );+ await loadWarranties(true);+ applyFilters();+ } catch (error) {+ hideLoadingSpinner();+ console.error('[warrantyActions] Failed to toggle archive', error);+ showToast(+ window.i18next ? window.i18next.t('messages.error_updating_archive_status') : 'Failed to update archive status',+ 'error',+ );+ }+}++async function deleteWarranty() {+ let warrantyId = getCurrentWarrantyId();+ // Fallback to global variable (script.js compatibility)+ if (!warrantyId && typeof window !== 'undefined' && window.currentWarrantyId) {+ warrantyId = window.currentWarrantyId;+ }+ if (!warrantyId) {+ showToast(window.i18next ? window.i18next.t('messages.no_warranty_selected_for_deletion') : 'No warranty selected', 'error');+ return;+ }+ try {+ showLoadingSpinner();+ await apiDeleteWarranty(warrantyId);+ hideLoadingSpinner();+ showToast(window.i18next ? window.i18next.t('messages.deleted_successfully') : 'Warranty deleted', 'success');+ closeModals();+ setCurrentWarrantyId(null);+ // Also clear global variable for script.js compatibility+ if (typeof window !== 'undefined') {+ window.currentWarrantyId = null;+ }+ await loadWarranties(true);+ applyFilters();+ } catch (error) {+ hideLoadingSpinner();+ console.error('[warrantyActions] Failed to delete warranty', error);+ showToast(window.i18next ? window.i18next.t('messages.failed_to_delete_warranty') : 'Failed to delete warranty', 'error');+ }+}++async function confirmArchive() {+ let warrantyId = getCurrentWarrantyId();+ // Fallback to global variable (script.js compatibility)+ if (!warrantyId && typeof window !== 'undefined' && window.currentWarrantyId) {+ warrantyId = window.currentWarrantyId;+ }+ if (!warrantyId) {+ showToast(window.i18next ? window.i18next.t('messages.no_warranty_selected_for_update') : 'No warranty selected', 'error');+ return;+ }+ await toggleArchiveStatus(warrantyId, true);+ closeModals();+ setCurrentWarrantyId(null);+ // Also clear global variable for script.js compatibility+ if (typeof window !== 'undefined') {+ window.currentWarrantyId = null;+ }+}++function closeModals() {+ document.querySelectorAll('.modal-backdrop').forEach((modal) => modal.classList.remove('active'));+}++export { toggleArchiveStatus, deleteWarranty, confirmArchive, closeModals };++if (typeof window !== 'undefined') {+ window.toggleArchiveStatus = toggleArchiveStatus;+ window.deleteWarranty = deleteWarranty;+ window.confirmArchive = confirmArchive;+ window.closeModals = closeModals;+}++++++diff --git a/frontend/js/components/warrantyRenderer.js b/frontend/js/components/warrantyRenderer.jsnew file mode 100644index 0000000..a83981e--- /dev/null+++ b/frontend/js/components/warrantyRenderer.js@@ -0,0 +1,558 @@+import { getCurrentView, getFilters, getIsGlobalView } from '../store.js';+import { renderEmptyState } from './ui.js';+import authService from '../services/authService.js';+import {+ formatDate,+ calculateProductAge,+ calculateDurationFromDates,+} from '../lib/dates.js';+import {+ getCurrencySymbol,+ getCurrencySymbolByCode,+ getCurrencyPosition,+ formatCurrencyHTML,+} from '../lib/currency.js';+import { loadSecureImages } from './paperless.js';++const VIEW_BUTTON_IDS = {+ grid: 'gridViewBtn',+ list: 'listViewBtn',+ table: 'tableViewBtn',+};++const PHOTO_CONFIG = {+ grid: { size: 80, radius: 8, border: '2px solid var(--border-color)' },+ list: { size: 180, radius: 6, border: '2px solid var(--border-color)' },+ table: { size: 55, radius: 4, border: '1px solid var(--border-color)' },+};++const t = (key, fallback, options) => {+ try {+ if (window.i18next?.t) {+ return window.i18next.t(key, options);+ }+ return fallback;+ } catch (error) {+ console.warn('[warrantyRenderer] failed to translate', key, error);+ return fallback;+ }+};++function getContrastColor(hexColor) {+ if (!hexColor) return '#ffffff';+ const hex = hexColor.replace('#', '');+ const bigint = parseInt(hex, 16);+ if (Number.isNaN(bigint)) return '#ffffff';+ const r = (bigint >> 16) & 255;+ const g = (bigint >> 8) & 255;+ const b = bigint & 255;+ const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;+ return luminance > 0.5 ? '#000000' : '#ffffff';+}++function getElements() {+ return {+ list: document.getElementById('warrantiesList'),+ tableHeader: document.querySelector('.table-view-header'),+ gridBtn: document.getElementById(VIEW_BUTTON_IDS.grid),+ listBtn: document.getElementById(VIEW_BUTTON_IDS.list),+ tableBtn: document.getElementById(VIEW_BUTTON_IDS.table),+ };+}++function updateViewUI(currentView, isArchivedView, elements) {+ if (elements.tableHeader) {+ elements.tableHeader.classList.toggle('visible', currentView === 'table');+ }+ ['grid', 'list', 'table'].forEach((view) => {+ const btn = elements[`${view}Btn`];+ if (btn) btn.classList.toggle('active', view === currentView);+ });+ if (elements.list) {+ elements.list.className = `warranties-list ${currentView}-view ${isArchivedView ? 'archived-view' : ''}`;+ }+}++function normalizeWarranties(warranties) {+ return Array.isArray(warranties) ? warranties.slice() : [];+}++function calculateProductAgeInDays(purchaseDate) {+ if (!purchaseDate) return 0;+ const purchase = new Date(purchaseDate);+ const now = new Date();+ if (Number.isNaN(purchase.getTime()) || purchase > now) return 0;+ const diffTime = now.getTime() - purchase.getTime();+ return Math.floor(diffTime / (1000 * 60 * 60 * 24));+}++function sortWarranties(warranties, filters) {+ const today = new Date();+ return warranties.sort((a, b) => {+ switch (filters.sortBy) {+ case 'name':+ return (a.product_name || '').toLowerCase().localeCompare((b.product_name || '').toLowerCase());+ case 'purchase':+ return new Date(b.purchase_date || 0) - new Date(a.purchase_date || 0);+ case 'age':+ return calculateProductAgeInDays(b.purchase_date) - calculateProductAgeInDays(a.purchase_date);+ case 'vendor':+ return (a.vendor || '').toLowerCase().localeCompare((b.vendor || '').toLowerCase());+ case 'warranty_type':+ return (a.warranty_type || '').toLowerCase().localeCompare((b.warranty_type || '').toLowerCase());+ case 'expiration':+ default: {+ const dateA = new Date(a.expiration_date || 0);+ const dateB = new Date(b.expiration_date || 0);+ const isExpiredA = dateA < today;+ const isExpiredB = dateB < today;+ if (isExpiredA && !isExpiredB) return 1;+ if (!isExpiredA && isExpiredB) return -1;+ return dateA - dateB;+ }+ }+ });+}++function buildWarrantyDurationText(warranty) {+ if (warranty.is_lifetime) {+ return t('warranties.lifetime', 'Lifetime');+ }+ const duration = {+ years: warranty.display_duration_years ?? warranty.warranty_duration_years ?? 0,+ months: warranty.display_duration_months ?? warranty.warranty_duration_months ?? 0,+ days: warranty.display_duration_days ?? warranty.warranty_duration_days ?? 0,+ };+ let parts = [];+ if (duration.years === 0 && duration.months === 0 && duration.days === 0 && warranty.expiration_date && warranty.purchase_date) {+ const calculated = calculateDurationFromDates(warranty.purchase_date, warranty.expiration_date);+ if (calculated) {+ duration.years = calculated.years || 0;+ duration.months = calculated.months || 0;+ duration.days = calculated.days || 0;+ }+ }+ if (duration.years > 0) {+ const fallback = `year${duration.years !== 1 ? 's' : ''}`;+ parts.push(`${duration.years} ${t('warranties.year', fallback, { count: duration.years })}`);+ }+ if (duration.months > 0) {+ const fallback = `month${duration.months !== 1 ? 's' : ''}`;+ parts.push(`${duration.months} ${t('warranties.month', fallback, { count: duration.months })}`);+ }+ if (duration.days > 0) {+ const fallback = `day${duration.days !== 1 ? 's' : ''}`;+ parts.push(`${duration.days} ${t('warranties.day', fallback, { count: duration.days })}`);+ }+ return parts.length ? parts.join(', ') : t('warranties.na', 'N/A');+}++function buildTagsHtml(tags = []) {+ if (!tags.length) return '';+ return `+ <div class="tags-row">+ ${tags.map((tag) => `+ <span class="tag" style="background-color: ${tag.color}; color: ${getContrastColor(tag.color)}">+ ${tag.name}+ </span>+ `).join('')}+ </div>+ `;+}++function buildNotesLink(warranty) {+ const notes = (warranty.notes || '').trim();+ if (!notes) return { hasNotes: false, html: '' };+ const label = t('warranties.notes', 'Notes');+ return {+ hasNotes: true,+ html: `<a href="#" class="notes-link" data-id="${warranty.id}" title="${label}"><i class='fas fa-sticky-note'></i> ${label}</a>`,+ };+}++function buildDocumentLinks(warranty, notesLinkHtml) {+ const links = [];+ if (warranty.product_url) {+ links.push(`+ <a href="${warranty.product_url}" class="product-link" target="_blank">+ <i class="fas fa-globe"></i> ${t('warranties.product_website', 'Product Website')}+ </a>+ `);+ }+ const invoiceLink = generateDocumentLink(warranty, 'invoice');+ const manualLink = generateDocumentLink(warranty, 'manual');+ const otherLink = generateDocumentLink(warranty, 'other');+ if (invoiceLink) links.push(invoiceLink);+ if (manualLink) links.push(manualLink);+ if (otherLink) links.push(otherLink);+ if (notesLinkHtml) links.push(notesLinkHtml);+ if (!links.length) return '';+ return `+ <div class="document-links-row">+ <div class="document-links-inner-container">+ ${links.join('')}+ </div>+ </div>+ `;+}++function generateDocumentLink(warranty, docType) {+ const config = {+ invoice: {+ localPath: warranty.invoice_path,+ paperlessId: warranty.paperless_invoice_id,+ url: warranty.invoice_url,+ icon: 'fas fa-file-invoice',+ label: t('warranties.invoice_receipt', 'Invoice'),+ className: 'invoice-link',+ },+ manual: {+ localPath: warranty.manual_path,+ paperlessId: warranty.paperless_manual_id,+ url: warranty.manual_url,+ icon: 'fas fa-book',+ label: t('warranties.product_manual', 'Manual'),+ className: 'manual-link',+ },+ other: {+ localPath: warranty.other_document_path,+ paperlessId: warranty.paperless_other_id,+ url: warranty.other_document_url,+ icon: 'fas fa-file-alt',+ label: t('warranties.files', 'Files'),+ className: 'other-document-link',+ },+ photo: {+ localPath: warranty.product_photo_path,+ paperlessId: warranty.paperless_photo_id,+ url: null,+ icon: 'fas fa-image',+ label: t('warranties.product_photo', 'Photo'),+ className: 'photo-link',+ },+ }[docType];++ if (!config) return '';++ const globalView = getIsGlobalView();+ const currentUser = authService.getCurrentUser?.() || null;+ const currentUserId = currentUser?.id;+ const isAdmin = Boolean(currentUser?.is_admin);++ if (docType === 'other' && globalView) {+ const canViewOtherDocs = warranty.user_id === currentUserId || isAdmin;+ if (!canViewOtherDocs) return '';+ }++ const hasLocal = config.localPath && config.localPath !== 'null';+ const hasPaperless = config.paperlessId && config.paperlessId !== null;+ const hasUrl = config.url && config.url.trim() !== '';++ let linksHtml = '';+ if (hasLocal) {+ linksHtml += `<a href="#" onclick="openSecureFile('${config.localPath}'); return false;" class="${config.className}">+ <i class="${config.icon}"></i> ${config.label}+ </a>`;+ } else if (hasPaperless) {+ const context = JSON.stringify({ user_id: warranty.user_id, id: warranty.id }).replace(/"/g, '"');+ linksHtml += `<a href="#" onclick="openPaperlessDocument(${config.paperlessId}, JSON.parse('${context}')); return false;" class="${config.className}">+ <i class="${config.icon}"></i> ${config.label}+ <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i>+ </a>`;+ }++ if (hasUrl) {+ if (linksHtml) linksHtml += ' ';+ linksHtml += `<a href="${config.url}" target="_blank" class="document-url-link ${config.className}">+ <i class="fas fa-link"></i> ${config.label} ${t('warranties.link', 'Link')}+ </a>`;+ }+ return linksHtml;+}++function getPriceHtml(warranty) {+ if (!warranty.purchase_price) return '';+ const symbol = warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol();+ const position = getCurrencyPosition();+ const formatted = formatCurrencyHTML(warranty.purchase_price, symbol, position);+ const label = t('warranties.price', 'Price');+ return `<div><i class="fas fa-coins"></i> ${label}: <span>${formatted}</span></div>`;+}++function buildSerialNumberHtml(serialNumbers = []) {+ if (!serialNumbers.length) return '';+ const label = t('warranties.serial_number', 'Serial Number');+ const [first, ...rest] = serialNumbers;+ const extra = rest.length+ ? `+ <div style="margin-left: 28px;">+ <ul style="margin-top: 5px;">+ ${rest.map((sn) => `<li>${sn}</li>`).join('')}+ </ul>+ </div>+ `+ : '';+ return `+ <div><i class="fas fa-barcode"></i> ${label}: <span>${first}</span></div>+ ${extra}+ `;+}++function buildUserInfo(warranty, isGlobalView) {+ if (!isGlobalView || !warranty.user_display_name) return '';+ const ownerLabel = t('warranties.owner', 'Owner');+ return `<div><strong>${ownerLabel}:</strong> <span>${warranty.user_display_name}</span></div>`;+}++function resolveCanEdit(warranty, isGlobalView) {+ if (!isGlobalView) return warranty.permissions?.canEdit !== false;+ if (typeof warranty.permissions?.canEdit === 'boolean') {+ return warranty.permissions.canEdit;+ }+ const currentUser = authService.getCurrentUser?.() || {};+ const isAdmin = Boolean(currentUser?.is_admin);+ return isAdmin || warranty.user_id === currentUser?.id;+}++function buildClaimsMeta(warranty) {+ if (warranty.claim_status_summary === 'OPEN') {+ return { className: 'action-btn claims-link claims-open', title: 'Claims (Open)' };+ }+ if (warranty.claim_status_summary === 'FINISHED') {+ return { className: 'action-btn claims-link claims-finished', title: 'Claims (Finished)' };+ }+ return { className: 'action-btn claims-link', title: 'Claims' };+}++function buildActionButtons(warranty, { canEdit, isArchivedView, claimsMeta }) {+ if (!canEdit) {+ return `+ <button class="${claimsMeta.className}" title="${claimsMeta.title}" 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>+ `;+ }+ return `+ <button class="${claimsMeta.className}" title="${claimsMeta.title}" 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>+ `;+}++function cardClassName(warranty, view, statusClass) {+ const isArchived = warranty.is_archived || warranty.viewFlags?.isArchivedView;+ if (isArchived) return 'warranty-card archived';+ if (view === 'table') return `warranty-card status-${statusClass}`;+ if (statusClass === 'expired') return 'warranty-card expired';+ if (statusClass === 'expiring') return 'warranty-card expiring-soon';+ return 'warranty-card active';+}++function buildPhotoHtml(warranty, view) {+ const config = PHOTO_CONFIG[view];+ if (!config || !warranty.product_photo_path || warranty.product_photo_path === 'null') return '';+ const sanitizedPath = warranty.product_photo_path.replace('uploads/', '');+ 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/${sanitizedPath}" alt="Product Photo"+ style="width: ${config.size}px; height: ${config.size}px; object-fit: cover; border-radius: ${config.radius}px; border: ${config.border}; cursor: pointer;"+ onerror="this.style.display='none'" class="secure-image">+ </a>+ </div>+ `;+}++function buildInfoBlock(warranty, { userInfoHtml, productAge, warrantyDurationText, expirationDateText, priceHtml, serialsHtml }) {+ const pieces = [+ userInfoHtml,+ `<div><i class="fas fa-calendar"></i> ${t('warranties.age', 'Age')}: <span>${productAge}</span></div>`,+ `<div><i class="fas fa-file-alt"></i> ${t('warranties.warranty', 'Warranty')}: <span>${warrantyDurationText}</span></div>`,+ `<div><i class="fas fa-wrench"></i> ${t('warranties.warranty_ends', 'Warranty Ends')}: <span>${expirationDateText}</span></div>`,+ priceHtml,+ serialsHtml,+ warranty.model_number ? `<div><i class="fas fa-tag"></i> ${t('warranties.model_number', 'Model Number')}: <span>${warranty.model_number}</span></div>` : '',+ warranty.vendor ? `<div><i class="fas fa-store"></i> ${t('warranties.vendor', 'Vendor')}: <span>${warranty.vendor}</span></div>` : '',+ warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${t('warranties.type', 'Type')}: <span>${warranty.warranty_type}</span></div>` : '',+ ];+ return pieces.filter(Boolean).join('');+}++function buildCardInnerHtml(view, warranty, derived) {+ const photoHtml = buildPhotoHtml(warranty, view);+ const infoHtml = buildInfoBlock(warranty, derived);+ const statusRow = `+ <div class="warranty-status-row status-${derived.statusClass}">+ <span>${derived.statusText}</span>+ </div>+ `;+ const base = `+ <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">+ ${derived.actionButtons}+ </div>+ </div>+ <div class="warranty-content">+ ${photoHtml}+ <div class="warranty-info">+ ${infoHtml}+ </div>+ </div>+ `;+ const docs = derived.documentLinks || '';+ const tags = derived.tagsHtml || '';++ if (view === 'table') {+ return `+ ${base}+ ${statusRow}+ ${docs}+ ${tags}+ `;+ }+ return `+ ${base}+ ${docs}+ ${tags}+ ${statusRow}+ `;+}++function alignGridHeights(list) {+ if (!list) return;+ const cards = list.querySelectorAll('.warranty-card');+ if (!cards.length) return;+ const images = list.querySelectorAll('.secure-image');+ let loaded = 0;+ const total = images.length;+ const align = () => {+ let maxHeight = 0;+ cards.forEach((card) => {+ card.style.minHeight = '';+ maxHeight = Math.max(maxHeight, card.getBoundingClientRect().height);+ });+ cards.forEach((card) => { card.style.minHeight = `${maxHeight}px`; });+ };+ if (!total) {+ align();+ return;+ }+ images.forEach((img) => {+ const onDone = () => {+ loaded += 1;+ if (loaded === total) align();+ };+ if (img.complete) {+ onDone();+ } else {+ img.addEventListener('load', onDone);+ img.addEventListener('error', onDone);+ }+ });+}++function postRender(currentView, list) {+ loadSecureImages();+ if (currentView === 'grid') {+ alignGridHeights(list);+ }+}++export function renderWarrantiesList(warranties, options = {}) {+ const elements = getElements();+ if (!elements.list) return;++ const normalized = normalizeWarranties(warranties);+ if (!normalized.length) {+ const message = options.emptyMessage || (options.meta?.isArchivedView+ ? t('messages.no_archived_warranties', 'No archived warranties.')+ : t('messages.no_warranties_found_add_first', 'No warranties yet. Add your first warranty to get started.'));+ renderEmptyState(elements.list, message);+ return;+ }++ const filters = getFilters();+ const currentView = options.meta?.currentView || getCurrentView() || 'grid';+ const isArchivedView = options.meta?.isArchivedView ?? filters.status === 'archived';+ const isGlobalView = getIsGlobalView();+ const sorted = sortWarranties(normalized, filters);++ updateViewUI(currentView, isArchivedView, elements);++ const fragment = document.createDocumentFragment();+ sorted.forEach((warranty) => {+ const statusText = (isArchivedView || warranty.is_archived)+ ? t('warranties.archived', 'Archived')+ : warranty.statusText || t('warranties.unknown_status', 'Unknown Status');+ const statusClass = (isArchivedView || warranty.is_archived) ? 'archived' : (warranty.status || 'unknown');+ const notesLink = buildNotesLink(warranty);+ const documentLinks = buildDocumentLinks(warranty, notesLink.html);+ const tagsHtml = buildTagsHtml(warranty.tags);+ const priceHtml = getPriceHtml(warranty);+ const serialNumbers = Array.isArray(warranty.serial_numbers)+ ? warranty.serial_numbers.filter((sn) => sn && typeof sn === 'string' && sn.trim() !== '')+ : [];+ const serialsHtml = serialNumbers.length ? buildSerialNumberHtml(serialNumbers) : '';+ const productAge = calculateProductAge(warranty.purchase_date);+ const expirationDateValue = warranty.expiration_date || warranty.expirationDate || null;+ const expirationDateText = warranty.is_lifetime+ ? t('warranties.lifetime', 'Lifetime')+ : (expirationDateValue ? formatDate(expirationDateValue) : t('warranties.na', 'N/A'));+ const userInfoHtml = buildUserInfo(warranty, isGlobalView);+ const canEdit = resolveCanEdit(warranty, isGlobalView);+ const claimsMeta = buildClaimsMeta(warranty);+ const actionButtons = buildActionButtons(warranty, { canEdit, isArchivedView, claimsMeta });++ const card = document.createElement('div');+ card.className = cardClassName(warranty, currentView, statusClass);+ card.dataset.id = warranty.id;+ card.innerHTML = buildCardInnerHtml(currentView, warranty, {+ statusClass,+ statusText,+ actionButtons,+ userInfoHtml,+ productAge,+ warrantyDurationText: buildWarrantyDurationText(warranty),+ expirationDateText,+ priceHtml,+ serialsHtml,+ documentLinks,+ tagsHtml,+ });+ fragment.appendChild(card);+ });++ elements.list.innerHTML = '';+ elements.list.appendChild(fragment);+ postRender(currentView, elements.list);+}++if (typeof window !== 'undefined') {+ window.components = window.components || {};+ window.components.warrantyRenderer = { renderWarrantiesList };+}+diff --git a/frontend/js/controllers/warrantyListController.js b/frontend/js/controllers/warrantyListController.jsindex b215d49..b3e1522 100644--- a/frontend/js/controllers/warrantyListController.js+++ b/frontend/js/controllers/warrantyListController.js@@ -1,3 +1,37 @@+import authService from '../services/authService.js';+import { listWarranties, saveUserPreferences, getGlobalViewStatus } from '../services/apiService.js';+import {+ getFilters,+ updateFilter,+ getWarranties as storeGetWarranties,+ setWarranties,+ getIsGlobalView,+ setIsGlobalView,+ getCurrentView,+ setCurrentView,+ getUserPreferencePrefix,+ setUserPreferencePrefix,+ getAllTags,+ wasLastLoadedArchived,+ didLastLoadIncludeArchived,+ StoreEvents,+} from '../store.js';+import {+ showLoading,+ hideLoading,+ showLoadingSpinner,+ hideLoadingSpinner,+ showToast,+ renderEmptyState,+} from '../components/ui.js';+import { loadTags as loadTagsModule, openTagManagementModal } from '../components/tagManager.js';+import { renderWarrantiesList } from '../components/warrantyRenderer.js';+import { processWarrantyData } from '../lib/warrantyProcessing.js';+import { exportWarranties, handleImport as importCsv } from '../components/importExport.js';+import { deleteWarranty as deleteWarrantyAction, toggleArchiveStatus as toggleArchive, confirmArchive as confirmArchiveAction } from '../components/warrantyActions.js';+import { openEditModal, saveWarranty as saveEditedWarranty } from '../components/editModal.js';+import { preloadWarrantyImages } from '../components/paperless.js';+// Warranty List Controller// Incremental extraction of main list responsibilities with strict backward compatibility.@@ -5,162 +39,217 @@ function callIfExists(fn, ...args) {if (typeof fn === 'function') return fn(...args);}+const DEFAULT_SCOPE = 'personal';+const VIEW_SCOPE_KEY = 'viewScope';++function getPreferenceKeyPrefix() {+ let prefix = getUserPreferencePrefix();+ if (prefix) return prefix;+ const user = authService.getCurrentUser();+ prefix = user && user.is_admin ? 'admin_' : 'user_';+ setUserPreferencePrefix(prefix);+ return prefix;+}++function saveViewScopePreference(scope) {+ localStorage.setItem(`${getPreferenceKeyPrefix()}${VIEW_SCOPE_KEY}`, scope);+}++function loadViewScopePreference() {+ return localStorage.getItem(`${getPreferenceKeyPrefix()}${VIEW_SCOPE_KEY}`) || DEFAULT_SCOPE;+}++function queryViewElements() {+ return {+ warrantiesList: document.getElementById('warrantiesList'),+ gridViewBtn: document.getElementById('gridViewBtn'),+ listViewBtn: document.getElementById('listViewBtn'),+ tableViewBtn: document.getElementById('tableViewBtn'),+ tableViewHeader: document.querySelector('.table-view-header'),+ currentViewIcon: document.getElementById('currentViewIcon'),+ };+}++function updateViewButtons(viewType, { gridViewBtn, listViewBtn, tableViewBtn }) {+ const buttons = [gridViewBtn, listViewBtn, tableViewBtn];+ if (!buttons.every(Boolean)) return;+ buttons.forEach((btn) => btn.classList.remove('active'));+ if (viewType === 'grid' && gridViewBtn) gridViewBtn.classList.add('active');+ if (viewType === 'list' && listViewBtn) listViewBtn.classList.add('active');+ if (viewType === 'table' && tableViewBtn) tableViewBtn.classList.add('active');+}++function updateViewIcon(viewType, icon) {+ if (!icon) return;+ icon.className = 'fas';+ if (viewType === 'list') {+ icon.classList.add('fa-list');+ icon.setAttribute('aria-label', 'List');+ } else if (viewType === 'table') {+ icon.classList.add('fa-table');+ icon.setAttribute('aria-label', 'Table');+ } else {+ icon.classList.add('fa-th-large');+ icon.setAttribute('aria-label', 'Grid');+ }+}++function updateWarrantiesPanelTitle(isGlobal = false) {+ const title = document.getElementById('warrantiesPanelTitle');+ if (!title) return;+ if (window.i18next && window.i18next.t) {+ title.textContent = isGlobal ? window.i18next.t('warranties.title_global') : window.i18next.t('warranties.title');+ } else {+ title.textContent = isGlobal ? "All Users' Warranties" : 'Your Warranties';+ }+}++function updateScopeIcon(scope) {+ const icon = document.getElementById('currentScopeIcon');+ if (!icon) return;+ icon.className = 'fas';+ if (scope === 'global') {+ icon.classList.add('fa-globe');+ icon.setAttribute('aria-label', 'Global');+ } else {+ icon.classList.add('fa-user');+ icon.setAttribute('aria-label', 'Personal');+ }+}++function updateScopeButtons(scope) {+ const personalViewBtn = document.getElementById('personalViewBtn');+ const globalViewBtn = document.getElementById('globalViewBtn');+ if (personalViewBtn) personalViewBtn.classList.toggle('active', scope === 'personal');+ if (globalViewBtn) globalViewBtn.classList.toggle('active', scope === 'global');+ const scopePersonalOption = document.getElementById('scopePersonalOption');+ const scopeGlobalOption = document.getElementById('scopeGlobalOption');+ if (scopePersonalOption) scopePersonalOption.classList.toggle('active', scope === 'personal');+ if (scopeGlobalOption) scopeGlobalOption.classList.toggle('active', scope === 'global');+}++function getWarrantiesListElement() {+ return document.getElementById('warrantiesList');+}++function processWarranty(warranty) {+ return processWarrantyData(warranty);+}+// 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);+export async function loadWarranties(isAuthenticatedOverride) {+ const isAuthenticated =+ typeof isAuthenticatedOverride === 'boolean' ? isAuthenticatedOverride : authService.isAuthenticated();+ showLoading();try {- // Ensure view preference is applied BEFORE first render so thumbnails use correct sizes- callIfExists(window.loadViewPreference);+ loadViewPreference();- const __filters = (window.store && window.store.getFilters && window.store.getFilters()) || {};+ const filters = 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.');- }+ renderEmptyState(+ getWarrantiesListElement(),+ window.i18next ? window.i18next.t('messages.login_to_view_warranties') : 'Please log in to view warranties.',+ );+ setWarranties([], { warrantiesLoaded: false, lastLoadedArchived: false, lastLoadedIncludesArchived: false });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;- }+ const scope = loadViewScopePreference();+ setIsGlobalView(scope === 'global');+ updateScopeButtons(scope);+ updateScopeIcon(scope);+ updateWarrantiesPanelTitle(scope === 'global');- // 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 = [];+ const primary = await listWarranties({ scope, archived: filters.status === 'archived' });+ let combined = Array.isArray(primary) ? primary : [];- // Keep isGlobalView in sync with loaded scope- try { if (typeof window.isGlobalView !== 'undefined') window.isGlobalView = shouldUseGlobalView; } catch {}+ let lastLoadedArchived = filters.status === 'archived';+ let lastLoadedIncludesArchived = false;- // 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 (filters.status === 'all') {+ const archived = await listWarranties({ scope, archived: true });+ const archivedMarked = Array.isArray(archived) ? archived.map((warranty) => ({ ...warranty, __isArchived: true })) : [];+ combined = combined.concat(archivedMarked);+ lastLoadedIncludesArchived = true;+ }- if (window.store && window.store.setWarranties) window.store.setWarranties(processed);+ const processed = combined.map(processWarranty);+ setWarranties(processed, {+ warrantiesLoaded: true,+ lastLoadedArchived,+ lastLoadedIncludesArchived,+ });- // Update archived-load flag- try { if (typeof window.lastLoadedArchived !== 'undefined') window.lastLoadedArchived = !!isArchivedView; } catch {}+ // Preload images immediately so they're ready when cards render+ preloadWarrantyImages(processed).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.');- }+ if (!processed.length) {+ renderEmptyState(+ getWarrantiesListElement(),+ window.i18next+ ? window.i18next.t('messages.no_warranties_found_add_first')+ : '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();+ populateTagFilter();+ populateVendorFilter();+ populateWarrantyTypeFilter();+ 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.');- }+ renderEmptyState(+ getWarrantiesListElement(),+ window.i18next+ ? window.i18next.t('messages.error_loading_warranties_try_again')+ : 'Error loading warranties. Please try again.',+ );+ showToast(+ error?.message ||+ (window.i18next ? window.i18next.t('messages.error_loading_warranties_try_again') : 'Failed to load warranties'),+ 'error',+ );} finally {- callIfExists(window.hideLoading) || callIfExists(window.hideLoadingSpinner);+ hideLoading();}}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);+ const filters = getFilters();+ const warranties = storeGetWarranties();++ const wasArchivedLoaded = wasLastLoadedArchived();+ const includesArchivedLoaded = didLastLoadIncludeArchived();++ if (+ (filters.status === 'archived' && !wasArchivedLoaded) ||+ (filters.status !== 'archived' && wasArchivedLoaded) ||+ (filters.status === 'all' && !includesArchivedLoaded)+ ) {+ loadWarranties();return;}- // Filter warranties based on current filters- const filtered = __warranties.filter(warranty => {+ 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;+ 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;+ if (filters.status !== 'all' && filters.status !== 'archived' && warranty.status !== filters.status) return false;// Tag filter- if (__filters.tag !== 'all') {- const tagId = parseInt(__filters.tag);+ if (filters.tag !== 'all') {+ const tagId = parseInt(filters.tag, 10);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;+ 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;+ 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();+ 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);@@ -172,8 +261,7 @@ export function applyFilters() {return true;});- // Preserve legacy behavior: just render (renderWarranties re-applies filters during render)- renderWarranties();+ renderWarrantiesList(filtered);}export function renderWarranties() { return callIfExists(window.renderWarranties); }export function filterWarranties() { return callIfExists(window.filterWarranties); }@@ -184,7 +272,7 @@ export function populateTagFilter() {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()) || []);+ const all = storeGetWarranties();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 })));@@ -204,7 +292,7 @@ export function populateVendorFilter() {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()) || []);+ const all = storeGetWarranties();all.forEach(warranty => {if (warranty.vendor && warranty.vendor.trim() !== '') uniqueVendors.add(warranty.vendor.trim().toLowerCase());});@@ -222,7 +310,7 @@ export function populateWarrantyTypeFilter() {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()) || []);+ const all = storeGetWarranties();all.forEach(warranty => {if (warranty.warranty_type && warranty.warranty_type.trim() !== '') uniqueTypes.add(warranty.warranty_type.trim().toLowerCase());});@@ -238,8 +326,8 @@ export function populateWarrantyTypeFilter() {// Extracted implementations: persist and restore filters/sortexport 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 prefix = getPreferenceKeyPrefix();+ const filters = getFilters();const filtersToSave = {status: filters.status || 'all',tag: filters.tag || 'all',@@ -250,21 +338,11 @@ export async function saveFilterPreferences(saveToApi = true) {};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);- }+ if (saveToApi && authService.isAuthenticated()) {+ try {+ await saveUserPreferences({ saved_filters: filtersToSave });+ } catch (e) {+ console.error('[Filters] Error saving filter preferences to API:', e);}}} catch (e) {@@ -272,23 +350,142 @@ export async function saveFilterPreferences(saveToApi = true) {}}+export async function switchView(viewType, saveToApi = true, reapplyFilters = true) {+ if (!viewType || viewType === getCurrentView()) {+ setCurrentView(viewType || getCurrentView() || 'grid');+ }+ setCurrentView(viewType);++ const prefix = getPreferenceKeyPrefix();+ const viewKey = `${prefix}defaultView`;+ const legacyKey = `${prefix}warrantyView`;+ if (localStorage.getItem(viewKey) !== viewType) {+ localStorage.setItem(viewKey, viewType);+ localStorage.setItem(legacyKey, viewType);+ localStorage.setItem('viewPreference', viewType);+ }++ if (saveToApi && authService.isAuthenticated()) {+ try {+ await saveUserPreferences({ default_view: viewType });+ } catch (error) {+ console.error('[switchView] Failed to save preference to API', error);+ }+ }++ const { warrantiesList, gridViewBtn, listViewBtn, tableViewBtn, tableViewHeader, currentViewIcon } = queryViewElements();+ if (warrantiesList) {+ warrantiesList.classList.remove('grid-view', 'list-view', 'table-view');+ warrantiesList.classList.add(`${viewType}-view`);+ }+ updateViewButtons(viewType, { gridViewBtn, listViewBtn, tableViewBtn });+ if (tableViewHeader) {+ tableViewHeader.classList.toggle('visible', viewType === 'table');+ }+ updateViewIcon(viewType, currentViewIcon);++ try {+ await saveFilterPreferences(false);+ } catch (error) {+ console.error('[switchView] Failed to persist filters locally', error);+ }++ if (reapplyFilters && storeGetWarranties().length > 0) {+ applyFilters();+ }+}++export function loadViewPreference() {+ const prefix = getPreferenceKeyPrefix();+ const savedView =+ localStorage.getItem(`${prefix}defaultView`) ||+ localStorage.getItem('viewPreference') ||+ localStorage.getItem(`${prefix}warrantyView`) ||+ 'grid';+ switchView(savedView, false, false);+}++async function ensureGlobalScopeEnabled() {+ try {+ const result = await getGlobalViewStatus();+ return !!result?.enabled;+ } catch (error) {+ console.error('[warrantyListController] Failed to check global view status', error);+ return true;+ }+}++async function switchScope(scope) {+ const isGlobal = scope === 'global';+ setIsGlobalView(isGlobal);+ saveViewScopePreference(scope);+ updateScopeButtons(scope);+ updateScopeIcon(scope);+ updateWarrantiesPanelTitle(isGlobal);+ try {+ await loadWarranties(authService.isAuthenticated());+ applyFilters();+ } catch (error) {+ console.error('[warrantyListController] Error switching scope', error);+ showToast(+ window.t+ ? window.t(isGlobal ? 'messages.error_loading_global_warranties' : 'messages.error_loading_personal_warranties')+ : 'Failed to load warranties',+ 'error',+ );+ }+}++export const switchToPersonalView = () => switchScope('personal');++export async function switchToGlobalView() {+ const enabled = await ensureGlobalScopeEnabled();+ if (!enabled) {+ showToast(window.t ? window.t('messages.global_view_disabled') : 'Global view is disabled', 'error');+ return;+ }+ switchScope('global');+}++export async function initViewControls() {+ const scopeDropdown = document.getElementById('scopeDropdown');+ const adminViewSwitcher = document.getElementById('adminViewSwitcher');+ try {+ const status = await getGlobalViewStatus();+ if (adminViewSwitcher) adminViewSwitcher.style.display = 'none';+ const enabled = !!status?.enabled;+ if (scopeDropdown) scopeDropdown.style.display = enabled ? 'block' : 'none';+ if (!enabled) {+ if (getIsGlobalView()) {+ await switchScope('personal');+ }+ } else {+ const savedScope = loadViewScopePreference();+ updateScopeButtons(savedScope);+ updateScopeIcon(savedScope);+ updateWarrantiesPanelTitle(savedScope === 'global');+ }+ } catch (error) {+ console.error('[warrantyListController] initViewControls failed', error);+ if (scopeDropdown) scopeDropdown.style.display = 'block';+ }+}+export function loadFilterAndSortPreferences() {try {- const prefix = (typeof window.getPreferenceKeyPrefix === 'function') ? window.getPreferenceKeyPrefix() : '';+ const prefix = 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 existing = getFilters();+ if (savedFilters.status !== undefined) updateFilter('status', savedFilters.status || existing.status);+ if (savedFilters.tag !== undefined) updateFilter('tag', savedFilters.tag || existing.tag);+ if (savedFilters.vendor !== undefined) updateFilter('vendor', savedFilters.vendor || existing.vendor);+ if (savedFilters.warranty_type !== undefined) updateFilter('warranty_type', savedFilters.warranty_type || existing.warranty_type);+ if (savedFilters.search !== undefined) updateFilter('search', savedFilters.search || '');+ if (savedFilters.sortBy !== undefined) updateFilter('sortBy', savedFilters.sortBy || existing.sortBy);const searchInput = document.getElementById('searchWarranties');const clearSearchBtn = document.getElementById('clearSearch');@@ -308,20 +505,20 @@ export function initEventListeners() {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);+ const tags = getAllTags();+ if (!tags || tags.length === 0) {+ showLoadingSpinner();try {- await callIfExists(window.loadTags);+ await loadTagsModule();} 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);+ showToast(window.t ? window.t('messages.could_not_load_tags') : 'Could not load tags', 'error');+ hideLoadingSpinner();return;}- callIfExists(window.hideLoadingSpinner);+ hideLoadingSpinner();}- callIfExists(window.openTagManagementModal);+ openTagManagementModal();});globalManageTagsBtn._wlcBound = true;}@@ -370,7 +567,7 @@ export function initEventListeners() {if (searchInput && !searchInput._wlcBound) {let searchDebounceTimeout;searchInput.addEventListener('input', () => {- if (window.store && window.store.updateFilter) window.store.updateFilter('search', searchInput.value.toLowerCase());+ updateFilter('search', searchInput.value.toLowerCase());if (clearSearchBtn) clearSearchBtn.style.display = searchInput.value ? 'flex' : 'none';if (searchInput.value) {searchInput.parentElement.classList.add('active-search');@@ -379,8 +576,8 @@ export function initEventListeners() {}if (searchDebounceTimeout) clearTimeout(searchDebounceTimeout);searchDebounceTimeout = setTimeout(() => {- callIfExists(window.applyFilters);- callIfExists(window.saveFilterPreferences);+ applyFilters();+ saveFilterPreferences();}, 300);});searchInput._wlcBound = true;@@ -390,12 +587,12 @@ export function initEventListeners() {clearSearchBtn.addEventListener('click', () => {if (searchInput) {searchInput.value = '';- if (window.store && window.store.updateFilter) window.store.updateFilter('search', '');+ updateFilter('search', '');clearSearchBtn.style.display = 'none';searchInput.parentElement.classList.remove('active-search');searchInput.focus();- callIfExists(window.applyFilters);- callIfExists(window.saveFilterPreferences);+ applyFilters();+ saveFilterPreferences();}});clearSearchBtn._wlcBound = true;@@ -403,45 +600,45 @@ export function initEventListeners() {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);+ updateFilter('status', statusFilter.value);+ applyFilters();+ 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);+ updateFilter('tag', tagFilter.value);+ applyFilters();+ 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);+ updateFilter('vendor', vendorFilter.value);+ applyFilters();+ 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);+ updateFilter('warranty_type', warrantyTypeFilter.value);+ applyFilters();+ 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);+ updateFilter('sortBy', sortBySelect.value);+ applyFilters();+ saveFilterPreferences();});sortBySelect._wlcBound = true;}@@ -450,20 +647,62 @@ export function initEventListeners() {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; }+ if (gridViewBtn && !gridViewBtn._wlcBound) { gridViewBtn.addEventListener('click', () => switchView('grid')); gridViewBtn._wlcBound = true; }+ if (listViewBtn && !listViewBtn._wlcBound) { listViewBtn.addEventListener('click', () => switchView('list')); listViewBtn._wlcBound = true; }+ if (tableViewBtn && !tableViewBtn._wlcBound) { tableViewBtn.addEventListener('click', () => switchView('table')); tableViewBtn._wlcBound = true; }++ const personalViewBtn = document.getElementById('personalViewBtn');+ if (personalViewBtn && !personalViewBtn._scopeBound) {+ personalViewBtn.addEventListener('click', () => switchToPersonalView());+ personalViewBtn._scopeBound = true;+ }+ const globalViewBtn = document.getElementById('globalViewBtn');+ if (globalViewBtn && !globalViewBtn._scopeBound) {+ globalViewBtn.addEventListener('click', () => switchToGlobalView());+ globalViewBtn._scopeBound = true;+ }+ const scopePersonalOption = document.getElementById('scopePersonalOption');+ if (scopePersonalOption && !scopePersonalOption._scopeBound) {+ scopePersonalOption.addEventListener('click', () => {+ switchToPersonalView();+ const scopeMenu = document.getElementById('scopeMenu');+ if (scopeMenu) scopeMenu.classList.remove('active');+ });+ scopePersonalOption._scopeBound = true;+ }+ const scopeGlobalOption = document.getElementById('scopeGlobalOption');+ if (scopeGlobalOption && !scopeGlobalOption._scopeBound) {+ scopeGlobalOption.addEventListener('click', () => {+ switchToGlobalView();+ const scopeMenu = document.getElementById('scopeMenu');+ if (scopeMenu) scopeMenu.classList.remove('active');+ });+ scopeGlobalOption._scopeBound = true;+ }++ if (!window._wlcStoreEventsBound) {+ const handleWarrantiesChanged = () => {+ populateTagFilter();+ populateVendorFilter();+ populateWarrantyTypeFilter();+ renderWarrantiesList(storeGetWarranties());+ };+ const handleFiltersChanged = () => applyFilters();+ window.addEventListener(StoreEvents.WARRANTIES_CHANGED, handleWarrantiesChanged);+ window.addEventListener(StoreEvents.FILTERS_CHANGED, handleFiltersChanged);+ window._wlcStoreEventsBound = true;+ }// Export / Importconst exportBtn = document.getElementById('exportBtn');- if (exportBtn && !exportBtn._wlcBound) { exportBtn.addEventListener('click', () => callIfExists(window.exportWarranties)); exportBtn._wlcBound = true; }+ if (exportBtn && !exportBtn._wlcBound) { exportBtn.addEventListener('click', 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]);+ importCsv(event.target.files[0]);}});importBtn._wlcBound = true;@@ -472,7 +711,7 @@ export function initEventListeners() {// Refreshconst refreshBtn = document.getElementById('refreshBtn');if (refreshBtn && !refreshBtn._wlcBound) {- refreshBtn.addEventListener('click', () => loadWarranties(true));+ refreshBtn.addEventListener('click', () => loadWarranties());refreshBtn._wlcBound = true;}@@ -512,30 +751,26 @@ export function initEventListeners() {// Save warranty changesconst 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);- }+ let handler = saveEditedWarranty;+ if (typeof window.setupSaveWarrantyObserver === 'function') {+ try {+ handler = window.setupSaveWarrantyObserver(saveEditedWarranty);+ window.saveWarrantyObserverAttachedByScriptJS = true;+ } catch (e) {+ console.error('[warrantyListController] Failed to wrap saveWarranty:', e);}- saveWarrantyBtn.addEventListener('click', () => {- if (typeof functionToAttachOnClick === 'function') functionToAttachOnClick();- });+ }+ saveWarrantyBtn.addEventListener('click', () => {+ if (typeof handler === 'function') handler();+ });saveWarrantyBtn._wlcBound = true;}// Confirm delete/archiveconst confirmDeleteBtn = document.getElementById('confirmDeleteBtn');- if (confirmDeleteBtn && !confirmDeleteBtn._wlcBound) { confirmDeleteBtn.addEventListener('click', () => callIfExists(window.deleteWarranty)); confirmDeleteBtn._wlcBound = true; }+ if (confirmDeleteBtn && !confirmDeleteBtn._wlcBound) { confirmDeleteBtn.addEventListener('click', deleteWarrantyAction); confirmDeleteBtn._wlcBound = true; }const confirmArchiveBtn = document.getElementById('confirmArchiveBtn');- if (confirmArchiveBtn && !confirmArchiveBtn._wlcBound) { confirmArchiveBtn.addEventListener('click', () => callIfExists(window.confirmArchive)); confirmArchiveBtn._wlcBound = true; }+ if (confirmArchiveBtn && !confirmArchiveBtn._wlcBound) { confirmArchiveBtn.addEventListener('click', confirmArchiveAction); confirmArchiveBtn._wlcBound = true; }// List delegated events (claims/edit/delete/notes/archive/unarchive) - controller owns this exclusivelyconst list = document.getElementById('warrantiesList');@@ -552,8 +787,14 @@ export function initEventListeners() {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);+ const warranty = storeGetWarranties().find(w => w.id === id);+ if (warranty) {+ if (typeof openEditModal === 'function') {+ openEditModal(warranty);+ } else if (typeof window.openEditModal === 'function') {+ window.openEditModal(warranty);+ }+ }return;}if (e.target.closest('.delete-btn')) {@@ -570,7 +811,7 @@ export function initEventListeners() {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);+ const warranty = storeGetWarranties().find(w => w.id === id);if (warranty && typeof window.showNotesModal === 'function') window.showNotesModal(warranty.notes, warranty);return;}@@ -587,7 +828,7 @@ export function initEventListeners() {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);+ if (Number.isFinite(id)) toggleArchive(id, false);return;}});@@ -607,6 +848,11 @@ if (typeof window !== 'undefined') {populateWarrantyTypeFilter,saveFilterPreferences,loadFilterAndSortPreferences,+ switchView,+ loadViewPreference,+ switchToPersonalView,+ switchToGlobalView,+ initViewControls,initEventListeners};// Legacy globals to avoid breaking existing references during staged extraction@@ -615,6 +861,13 @@ if (typeof window !== 'undefined') {window.populateWarrantyTypeFilter = populateWarrantyTypeFilter;window.saveFilterPreferences = saveFilterPreferences;window.loadFilterAndSortPreferences = loadFilterAndSortPreferences;+ window.switchView = switchView;+ window.loadViewPreference = loadViewPreference;+ window.switchToPersonalView = switchToPersonalView;+ window.switchToGlobalView = switchToGlobalView;+ window.initViewControls = initViewControls;+ window.saveViewScopePreference = saveViewScopePreference;+ window.loadViewScopePreference = loadViewScopePreference;}export const init = initEventListeners;diff --git a/frontend/js/index.js b/frontend/js/index.jsindex 3b3b763..2d9f1da 100644--- a/frontend/js/index.js+++ b/frontend/js/index.js@@ -1,25 +1,39 @@// Main Application Entry Point-import authService from './services/authService.js';-import { init as initListController, loadWarranties } from './controllers/warrantyListController.js';+import { initBootstrap } from './bootstrap.js';+import {+ init as initListController,+ loadWarranties,+ loadFilterAndSortPreferences,+ loadViewPreference,+ initViewControls,+} from './controllers/warrantyListController.js';import { init as initTagManager } from './components/tagManager.js';import { init as initAddForm } from './components/addWarrantyForm.js';+import { init as initEditModal } from './components/editModal.js';+import { init as initNotes } from './components/notes.js';+import { init as initClaims } from './components/claims.js';+import { initFormTabs } from './components/formTabs.js';+import { addSerialNumberInput } from './components/serialNumbers.js';++function bootstrapModules() {+ initListController();+ initTagManager();+ initAddForm();+ initEditModal();+ initNotes();+ initClaims();+ initViewControls();+ loadFilterAndSortPreferences();+ loadViewPreference();+}++initBootstrap();-// Initialize auth first (idempotent; authService also auto-inits on DOMContentLoaded)document.addEventListener('DOMContentLoaded', () => {- authService.initAuth();+ bootstrapModules();});-// Wait for authentication to be confirmed before loading protected data and initializing auth-dependent moduleswindow.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);- }+ const isAuthenticated = !!(event.detail && event.detail.isAuthenticated);+ loadWarranties(isAuthenticated);});--diff --git a/frontend/js/lib/currency.js b/frontend/js/lib/currency.jsnew file mode 100644index 0000000..105c3b8--- /dev/null+++ b/frontend/js/lib/currency.js@@ -0,0 +1,197 @@+import authService from '../services/authService.js';+import { getUserPreferencePrefix, setUserPreferencePrefix } from '../store.js';++function resolvePreferencePrefix() {+ let prefix = getUserPreferencePrefix();+ if (prefix) return prefix;+ const user = authService.getCurrentUser();+ prefix = user?.is_admin ? 'admin_' : 'user_';+ setUserPreferencePrefix(prefix);+ return prefix;+}++export function getCurrencySymbol() {+ const prefix = resolvePreferencePrefix();+ let symbol = '$';+ const explicit = localStorage.getItem(`${prefix}currencySymbol`);+ if (explicit) return explicit;+ try {+ const prefs = localStorage.getItem(`${prefix}preferences`);+ if (prefs) {+ const parsed = JSON.parse(prefs);+ if (parsed?.currency_symbol) symbol = parsed.currency_symbol;+ }+ } catch (error) {+ console.warn('[currency] Failed to parse preferences', error);+ }+ return symbol;+}++export function getCurrencyCode() {+ const prefix = resolvePreferencePrefix();+ const explicit = localStorage.getItem(`${prefix}currencyCode`);+ if (explicit) return explicit;+ const symbol = getCurrencySymbol();+ const map = {+ '$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'JPY', '₹': 'INR', '₩': 'KRW',+ 'CHF': 'CHF', 'C$': 'CAD', 'A$': 'AUD', 'kr': 'SEK', 'zł': 'PLN', 'Kč': 'CZK',+ 'Ft': 'HUF', '₽': 'RUB', 'R$': 'BRL', '₪': 'ILS', '₺': 'TRY', 'NZ$': 'NZD',+ };+ return map[symbol] || 'USD';+}++export function getCurrencySymbolByCode(code) {+ const map = {+ USD: '$', EUR: '€', GBP: '£', JPY: '¥', CNY: '¥', INR: '₹', KRW: '₩',+ CHF: 'CHF', CAD: 'C$', AUD: 'A$', SEK: 'kr', NOK: 'kr', DKK: 'kr',+ PLN: 'zł', CZK: 'Kč', HUF: 'Ft', BGN: 'лв', RON: 'lei', HRK: 'kn',+ RUB: '₽', BRL: 'R$', MXN: '$', ARS: '$', CLP: '$', COP: '$',+ PEN: 'S/', VES: 'Bs', ZAR: 'R', EGP: '£', NGN: '₦', KES: 'KSh',+ GHS: '₵', MAD: 'DH', TND: 'DT', AED: 'AED', SAR: 'SR', QAR: 'QR',+ KWD: 'KD', BHD: 'BD', OMR: 'OR', JOD: 'JD', LBP: 'LL', ILS: '₪',+ TRY: '₺', IRR: '﷼', PKR: '₨', BDT: '৳', LKR: 'Rs', NPR: 'Rs',+ BTN: 'Nu', MMK: 'K', THB: '฿', VND: '₫', LAK: '₭', KHR: '៛',+ MYR: 'RM', SGD: 'S$', IDR: 'Rp', PHP: '₱', TWD: 'NT$', HKD: 'HK$',+ MOP: 'MOP', KPW: '₩', MNT: '₮', KZT: '₸', UZS: 'soʻm', TJS: 'SM',+ KGS: 'с', TMT: 'T', AFN: '؋', AMD: '֏', AZN: '₼', GEL: '₾',+ MDL: 'L', UAH: '₴', BYN: 'Br', RSD: 'дин', MKD: 'ден', ALL: 'L',+ BAM: 'KM', ISK: 'kr', FJD: 'FJ$', PGK: 'K', SBD: 'SI$', TOP: 'T$',+ VUV: 'VT', WST: 'WS$', XPF: '₣', NZD: 'NZ$',+ };+ return map[code] || code;+}++export function getCurrencyPosition() {+ const prefix = resolvePreferencePrefix();+ return localStorage.getItem(`${prefix}currencyPosition`) || 'left';+}++export function formatCurrencyHTML(amount, symbol, position) {+ const formatted = Number.parseFloat(amount || 0).toFixed(2);+ if (position === 'right') {+ return `<span>${formatted}</span><span class="currency-symbol currency-right">${symbol}</span>`;+ }+ return `<span class="currency-symbol">${symbol}</span><span>${formatted}</span>`;+}++export function setupDynamicCurrencyPosition(input, currencySymbol) {+ if (!input || !currencySymbol) return;+ const updatePosition = () => {+ const wrapper = input.closest('.price-input-wrapper');+ if (!wrapper || !wrapper.classList.contains('currency-right')) return;++ if (wrapper.offsetWidth === 0) {+ setTimeout(updatePosition, 50);+ return;+ }++ const text = input.value || input.placeholder || '0.00';+ const tempSpan = document.createElement('span');+ tempSpan.style.visibility = 'hidden';+ tempSpan.style.position = 'absolute';+ tempSpan.style.font = window.getComputedStyle(input).font;+ tempSpan.textContent = text;+ document.body.appendChild(tempSpan);+ const textWidth = tempSpan.offsetWidth;+ document.body.removeChild(tempSpan);++ const paddingLeft = Number.parseInt(window.getComputedStyle(input).paddingLeft, 10) || 12;+ const gap = 4;+ const wrapperWidth = wrapper.offsetWidth;+ const right = Math.max(8, wrapperWidth - paddingLeft - textWidth - gap - 20);+ currencySymbol.style.right = `${right}px`;+ };++ input.addEventListener('input', updatePosition);+ input.addEventListener('focus', updatePosition);+ input.addEventListener('blur', updatePosition);+ requestAnimationFrame(() => {+ updatePosition();+ setTimeout(updatePosition, 100);+ setTimeout(updatePosition, 300);+ });+}++export function updateFormCurrencyPosition(symbol, position) {+ const apply = (wrapperId, symbolId, inputId) => {+ const wrapper = document.getElementById(wrapperId);+ const symbolEl = document.getElementById(symbolId);+ const input = document.getElementById(inputId);+ if (!wrapper || !symbolEl) return;+ symbolEl.textContent = symbol;+ if (position === 'right') {+ wrapper.classList.add('currency-right');+ if (input) setupDynamicCurrencyPosition(input, symbolEl);+ } else {+ wrapper.classList.remove('currency-right');+ symbolEl.style.right = '';+ }+ };+ apply('addPriceInputWrapper', 'addCurrencySymbol', 'purchasePrice');+ apply('editPriceInputWrapper', 'editCurrencySymbol', 'editPurchasePrice');+}++export function updateCurrencySymbols() {+ const symbol = getCurrencySymbol();+ const position = getCurrencyPosition();+ document.querySelectorAll('.currency-symbol').forEach((el) => {+ el.textContent = symbol;+ });+ updateFormCurrencyPosition(symbol, position);+}++export async function loadCurrencies() {+ try {+ const token = authService.getToken() || localStorage.getItem('auth_token');+ if (!token) throw new Error('Authentication required');+ const response = await fetch('/api/currencies', { headers: { Authorization: `Bearer ${token}` } });+ if (!response.ok) throw new Error('Failed to fetch currencies');+ const currencies = await response.json();+ const preferred = getCurrencyCode();++ const applyOptions = (select) => {+ if (!select) return;+ select.innerHTML = '';+ currencies.forEach((currency) => {+ const option = document.createElement('option');+ option.value = currency.code;+ option.textContent = `${currency.code} - ${currency.name} (${currency.symbol})`;+ select.appendChild(option);+ });+ };++ const addSelect = document.getElementById('currency');+ const editSelect = document.getElementById('editCurrency');+ applyOptions(addSelect);+ applyOptions(editSelect);++ if (addSelect && preferred) {+ setTimeout(() => {+ addSelect.value = preferred;+ addSelect.dispatchEvent(new Event('change', { bubbles: true }));+ }, 10);+ }+ } catch (error) {+ console.error('[currency] Failed to load currencies', error);+ const fallback = (select, label) => {+ if (select) {+ select.innerHTML = `<option value="USD">${label}</option>`;+ }+ };+ fallback(document.getElementById('currency'), 'USD - US Dollar ($)');+ fallback(document.getElementById('editCurrency'), 'USD - US Dollar ($)');+ }+}++export default {+ getCurrencySymbol,+ getCurrencyCode,+ getCurrencySymbolByCode,+ getCurrencyPosition,+ formatCurrencyHTML,+ updateCurrencySymbols,+ updateFormCurrencyPosition,+ setupDynamicCurrencyPosition,+ loadCurrencies,+};+diff --git a/frontend/js/lib/dates.js b/frontend/js/lib/dates.jsnew file mode 100644index 0000000..afa8dcd--- /dev/null+++ b/frontend/js/lib/dates.js@@ -0,0 +1,117 @@+const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];++function safeI18n(key, fallback, options) {+ try {+ if (window?.i18next?.t) {+ const result = window.i18next.t(key, options);+ if (result && result !== key) return result;+ }+ } catch (error) {+ console.warn('[dates] i18n failure', key, error);+ }+ return fallback;+}++export function formatDate(value) {+ if (!value) return safeI18n('dates.unknown', 'Unknown');+ const date = value instanceof Date ? value : new Date(value);+ if (Number.isNaN(date.getTime())) return safeI18n('dates.unknown', 'Unknown');+ const month = MONTH_NAMES[date.getUTCMonth()];+ const day = String(date.getUTCDate()).padStart(2, '0');+ const year = date.getUTCFullYear();+ return `${month} ${day}, ${year}`;+}++export function formatDateYYYYMMDD(date) {+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) return 'N/A';+ const year = date.getUTCFullYear();+ const month = String(date.getUTCMonth() + 1).padStart(2, '0');+ const day = String(date.getUTCDate()).padStart(2, '0');+ return `${year}-${month}-${day}`;+}++export function calculateProductAge(purchaseDate) {+ if (!purchaseDate) return safeI18n('warranties.unknown_age', 'Unknown');+ const purchase = new Date(purchaseDate);+ const now = new Date();+ if (Number.isNaN(purchase.getTime()) || purchase > now) return safeI18n('warranties.unknown_age', 'Unknown');++ let years = now.getFullYear() - purchase.getFullYear();+ let months = now.getMonth() - purchase.getMonth();+ let days = now.getDate() - purchase.getDate();++ if (days < 0) {+ months -= 1;+ const lastMonth = new Date(now.getFullYear(), now.getMonth(), 0);+ days += lastMonth.getDate();+ }++ if (months < 0) {+ years -= 1;+ months += 12;+ }++ const parts = [];+ if (years > 0) {+ const text = safeI18n('warranties.year', `year${years !== 1 ? 's' : ''}`, { count: years });+ parts.push(`${years} ${text}`);+ }+ if (months > 0) {+ const text = safeI18n('warranties.month', `month${months !== 1 ? 's' : ''}`, { count: months });+ parts.push(`${months} ${text}`);+ }+ if (days > 0 && years === 0) {+ const text = safeI18n('warranties.day', `day${days !== 1 ? 's' : ''}`, { count: days });+ parts.push(`${days} ${text}`);+ }++ if (!parts.length) return safeI18n('dates.today', 'Today');+ return parts.join(', ');+}++export function calculateProductAgeInDays(purchaseDate) {+ if (!purchaseDate) return 0;+ const purchase = new Date(purchaseDate);+ const now = new Date();+ if (Number.isNaN(purchase.getTime()) || purchase > now) return 0;+ const diff = now.getTime() - purchase.getTime();+ return Math.floor(diff / (1000 * 60 * 60 * 24));+}++export function calculateDurationFromDates(startDate, endDate) {+ try {+ if (!startDate || !endDate) return null;+ const start = new Date(startDate);+ const end = new Date(endDate);+ if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) return null;++ let years = end.getFullYear() - start.getFullYear();+ let months = end.getMonth() - start.getMonth();+ let days = end.getDate() - start.getDate();++ if (days < 0) {+ months -= 1;+ const prevMonth = new Date(end.getFullYear(), end.getMonth(), 0);+ days += prevMonth.getDate();+ }++ if (months < 0) {+ years -= 1;+ months += 12;+ }++ return { years, months, days };+ } catch (error) {+ console.error('[dates] Failed to calculate duration', error);+ return null;+ }+}++export default {+ formatDate,+ formatDateYYYYMMDD,+ calculateProductAge,+ calculateProductAgeInDays,+ calculateDurationFromDates,+};+diff --git a/frontend/js/lib/theme.js b/frontend/js/lib/theme.jsnew file mode 100644index 0000000..20678bc--- /dev/null+++ b/frontend/js/lib/theme.js@@ -0,0 +1,61 @@+import authService from '../services/authService.js';+import { saveUserPreferences } from '../services/apiService.js';++function setTheme(isDark) {+ const theme = isDark ? 'dark' : 'light';+ document.documentElement.setAttribute('data-theme', theme);+ localStorage.setItem('darkMode', String(isDark));+ const headerToggle = document.getElementById('darkModeToggle');+ if (headerToggle) {+ headerToggle.checked = isDark;+ }+}++async function saveThemePreference(isDark, saveToApi = true) {+ try {+ setTheme(isDark);+ if (!saveToApi || !authService.isAuthenticated()) return;+ await saveUserPreferences({ theme: isDark ? 'dark' : 'light' });+ } catch (error) {+ console.warn('[theme] Failed to save theme preference', error);+ }+}++function initializeTheme() {+ const stored = localStorage.getItem('darkMode');+ if (stored !== null) {+ setTheme(stored === 'true');+ return;+ }+ const prefersDark = window.matchMedia?.('(prefers-color-scheme: dark)').matches;+ setTheme(Boolean(prefersDark));+}++function bindThemeToggle() {+ const toggle = document.getElementById('darkModeToggle');+ if (!toggle || toggle._themeBound) return;+ toggle.addEventListener('change', (event) => {+ saveThemePreference(event.target.checked);+ });+ toggle._themeBound = true;+}++export { setTheme, saveThemePreference, initializeTheme, bindThemeToggle };++if (typeof window !== 'undefined') {+ window.theme = {+ setTheme,+ saveThemePreference,+ initializeTheme,+ bindThemeToggle,+ };+ window.setTheme = setTheme;+ window.saveThemePreference = saveThemePreference;+ window.initializeTheme = initializeTheme;+}++++++diff --git a/frontend/js/lib/warrantyProcessing.js b/frontend/js/lib/warrantyProcessing.jsnew file mode 100644index 0000000..abc28e4--- /dev/null+++ b/frontend/js/lib/warrantyProcessing.js@@ -0,0 +1,142 @@+import {+ getWarranties,+ setWarranties,+ wasLastLoadedArchived,+ didLastLoadIncludeArchived,+ areWarrantiesLoaded,+ getExpiringSoonDays,+} from '../store.js';+import { calculateDurationFromDates } from './dates.js';++export function processWarrantyData(warranty) {+ if (!warranty || typeof warranty !== 'object') return warranty;+ const processed = { ...warranty };+ processed.is_archived = Boolean(warranty.__isArchived || warranty.is_archived);+ processed.product_name = processed.product_name || 'Unnamed Product';++ const today = new Date();+ today.setHours(0, 0, 0, 0);++ processed.purchaseDate = parseDate(processed.purchase_date);+ processed.expirationDate = parseDate(processed.expiration_date);++ if (processed.is_lifetime) {+ processed.status = 'active';+ processed.statusText = translate('warranties.lifetime', 'Lifetime');+ processed.daysRemaining = Infinity;+ processed.warranty_duration_years = 0;+ processed.warranty_duration_months = 0;+ processed.warranty_duration_days = 0;+ processed.display_duration_years = 0;+ processed.display_duration_months = 0;+ processed.display_duration_days = 0;+ processed.original_input_method = 'duration';+ return processed;+ }++ if (processed.expirationDate && !Number.isNaN(processed.expirationDate.getTime())) {+ const expirationOnly = new Date(processed.expirationDate);+ expirationOnly.setHours(0, 0, 0, 0);+ const timeDiff = expirationOnly.getTime() - today.getTime();+ const daysRemaining = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));+ processed.daysRemaining = daysRemaining;+ const soonThreshold = getExpiringSoonDays();+ if (daysRemaining < 0) {+ processed.status = 'expired';+ processed.statusText = translate('warranties.expired', 'Expired');+ } else if (daysRemaining < soonThreshold) {+ processed.status = 'expiring';+ processed.statusText = translate(+ 'warranties.days_remaining',+ `${daysRemaining} days remaining`,+ { days: daysRemaining, dayText: translate('warranties.day', `day${daysRemaining !== 1 ? 's' : ''}`, { count: daysRemaining }) },+ );+ } else {+ processed.status = 'active';+ processed.statusText = translate(+ 'warranties.days_remaining',+ `${daysRemaining} days remaining`,+ { days: daysRemaining, dayText: translate('warranties.day', `day${daysRemaining !== 1 ? 's' : ''}`, { count: daysRemaining }) },+ );+ }++ const originalYears = processed.warranty_duration_years || 0;+ const originalMonths = processed.warranty_duration_months || 0;+ const originalDays = processed.warranty_duration_days || 0;+ const usedExactDate = originalYears === 0 && originalMonths === 0 && originalDays === 0;+ processed.original_input_method = usedExactDate ? 'exact_date' : 'duration';++ if (usedExactDate && processed.purchaseDate) {+ const calculated = calculateDurationFromDates(+ processed.purchaseDate.toISOString().split('T')[0],+ processed.expirationDate.toISOString().split('T')[0],+ );+ if (calculated) {+ processed.display_duration_years = calculated.years;+ processed.display_duration_months = calculated.months;+ processed.display_duration_days = calculated.days;+ processed.warranty_duration_years = 0;+ processed.warranty_duration_months = 0;+ processed.warranty_duration_days = 0;+ }+ } else {+ processed.display_duration_years = originalYears;+ processed.display_duration_months = originalMonths;+ processed.display_duration_days = originalDays;+ }+ } else {+ processed.status = 'unknown';+ processed.statusText = translate('warranties.unknown_status', 'Unknown Status');+ processed.daysRemaining = null;+ }++ return processed;+}++export function processAllWarranties() {+ const warranties = getWarranties();+ if (!Array.isArray(warranties) || !warranties.length) return;+ const processed = warranties.map((warranty) => processWarrantyData(warranty));+ setWarranties(processed, {+ warrantiesLoaded: areWarrantiesLoaded(),+ lastLoadedArchived: wasLastLoadedArchived(),+ lastLoadedIncludesArchived: didLastLoadIncludeArchived(),+ });+}++function parseDate(value) {+ if (!value) return null;+ const parts = String(value).split('-');+ if (parts.length === 3) {+ const year = Number.parseInt(parts[0], 10);+ const month = Number.parseInt(parts[1], 10) - 1;+ const day = Number.parseInt(parts[2], 10);+ const parsed = new Date(Date.UTC(year, month, day));+ if (!Number.isNaN(parsed.getTime())) return parsed;+ }+ const fallback = new Date(value);+ return Number.isNaN(fallback.getTime()) ? null : fallback;+}++function translate(key, fallback, options) {+ try {+ if (window.i18next?.t) {+ const result = window.i18next.t(key, options);+ if (result && result !== key) return result;+ }+ } catch (error) {+ console.warn('[warrantyProcessing] translation failed', key, error);+ }+ return fallback;+}++if (typeof window !== 'undefined') {+ window.processWarrantyData = processWarrantyData;+ window.processAllWarranties = processAllWarranties;+}++++++diff --git a/frontend/js/services/apiService.js b/frontend/js/services/apiService.jsindex 7c59f15..a142a9b 100644--- a/frontend/js/services/apiService.js+++ b/frontend/js/services/apiService.js@@ -33,6 +33,11 @@ export async function getWarranties(query = '') {return res.json();}+export async function createWarranty(formData) {+ const res = await baseRequest('/api/warranties', { method: 'POST', body: formData });+ return res.json();+}+export async function updateWarranty(id, formData) {const res = await baseRequest(`/api/warranties/${id}`, { method: 'PUT', body: formData });return res.json();@@ -48,6 +53,32 @@ export async function getStatistics() {return res.json();}+export async function listWarranties({ scope = 'personal', archived = false } = {}) {+ const base = scope === 'global' ? '/api/warranties/global' : '/api/warranties';+ const path = archived ? `${base}/archived` : base;+ const res = await baseRequest(path);+ return res.json();+}++export async function getGlobalViewStatus() {+ const res = await baseRequest('/api/settings/global-view-status');+ return res.json();+}++export async function getUserPreferences() {+ const res = await baseRequest('/api/auth/preferences');+ return res.json();+}++export async function saveUserPreferences(preferences) {+ const res = await baseRequest('/api/auth/preferences', {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(preferences),+ });+ return res.json();+}+// --- Settings & Admin endpoints ---export async function getUser() {const res = await baseRequest('/api/auth/user');@@ -97,6 +128,35 @@ export async function triggerNotifications() {return res.json();}+// Tags+export async function getTags(force = false) {+ const res = await baseRequest(force ? '/api/tags?force=1' : '/api/tags');+ return res.json();+}++export async function createTagRequest(payload) {+ const res = await baseRequest('/api/tags', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ });+ return res.json();+}++export async function updateTagRequest(id, payload) {+ const res = await baseRequest(`/api/tags/${id}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ });+ return res.json();+}++export async function deleteTagRequest(id) {+ await baseRequest(`/api/tags/${id}`, { method: 'DELETE' });+ return true;+}+// Generic request helper for arbitrary endpointsexport async function request(path, options = {}) {return baseRequest(path, options);@@ -151,9 +211,14 @@ if (typeof window !== 'undefined') {export default {getWarranties,+ createWarranty,updateWarranty,deleteWarranty,getStatistics,+ listWarranties,+ getGlobalViewStatus,+ getUserPreferences,+ saveUserPreferences,request,savePreferences,// settings & admin@@ -165,6 +230,10 @@ export default {deleteUser,getAuditTrail,triggerNotifications,+ getTags,+ createTagRequest,+ updateTagRequest,+ deleteTagRequest,};diff --git a/frontend/js/services/authService.js b/frontend/js/services/authService.jsindex 4aed282..6673fa8 100644--- a/frontend/js/services/authService.js+++ b/frontend/js/services/authService.js@@ -1,69 +1,77 @@-// Centralized Authentication Service-// Provides a single source of truth for auth state and UI updates.--const authService = (() => {- let cachedToken = null;- let cachedUser = null;- const logoutCallbacks = [];+// Centralized Authentication Service implemented as an AuthManager class.+class AuthManager {+ constructor() {+ this.cachedToken = null;+ this.cachedUser = null;+ this.logoutCallbacks = [];+ this.globalClickListenerAttached = false;+ this.storageListenerAttached = false;+ this.registrationObserver = null;+ this.initialized = false;+ }- function readStateFromStorage() {- cachedToken = localStorage.getItem('auth_token');+ readStateFromStorage() {+ this.cachedToken = localStorage.getItem('auth_token');const userInfoString = localStorage.getItem('user_info');- cachedUser = null;+ this.cachedUser = null;if (userInfoString) {try {- cachedUser = JSON.parse(userInfoString);+ this.cachedUser = JSON.parse(userInfoString);} catch {localStorage.removeItem('user_info');- cachedUser = null;+ this.cachedUser = null;}}}- function isAuthenticated() {- return !!(cachedToken && cachedUser && cachedUser.id);+ isAuthenticated() {+ return !!(this.cachedToken && this.cachedUser && this.cachedUser.id);}- function getToken() {- if (!cachedToken) cachedToken = localStorage.getItem('auth_token');- return cachedToken;+ getToken() {+ if (!this.cachedToken) this.cachedToken = localStorage.getItem('auth_token');+ return this.cachedToken;}- function getCurrentUser() {- if (!cachedUser) {+ getCurrentUser() {+ if (!this.cachedUser) {const userInfoString = localStorage.getItem('user_info');if (userInfoString) {try {- cachedUser = JSON.parse(userInfoString);+ this.cachedUser = JSON.parse(userInfoString);} catch {- cachedUser = null;+ this.cachedUser = null;}}}- return cachedUser;+ return this.cachedUser;}- function clearAuthData() {+ clearAuthData() {localStorage.removeItem('auth_token');localStorage.removeItem('user_info');- cachedToken = null;- cachedUser = null;- logoutCallbacks.forEach((cb) => {- try { cb(); } catch {}+ this.cachedToken = null;+ this.cachedUser = null;+ this.logoutCallbacks.forEach((cb) => {+ try {+ cb();+ } catch (error) {+ console.error('[authService] logout callback failed', error);+ }});}- function onLogout(callback) {- if (typeof callback === 'function') logoutCallbacks.push(callback);+ onLogout(callback) {+ if (typeof callback === 'function') this.logoutCallbacks.push(callback);}- function dispatchAuthStateEvent(isAuthed, user) {+ dispatchAuthStateEvent(isAuthed, user) {setTimeout(() => {window.dispatchEvent(new CustomEvent('authStateReady', { detail: { isAuthenticated: isAuthed, user } }));}, 0);}- function updateHeaderUI(isAuthed, user) {+ updateHeaderUI(isAuthed, user) {const authContainer = document.getElementById('authContainer');const userMenu = document.getElementById('userMenu');const userDisplayName = document.getElementById('userDisplayName');@@ -98,8 +106,7 @@ const authService = (() => {}}- function immediateCssToggle() {- // Fast, CSS-based hide/show to prevent flicker before scripts finish+ immediateCssToggle() {const styleId = 'auth-ui-style';let style = document.getElementById(styleId);if (!style) {@@ -113,39 +120,31 @@ const authService = (() => {: `#authContainer, .auth-buttons { display: flex !important; visibility: visible !important; } a[href="login.html"], a[href="/login.html"], a[href="register.html"], a[href="/register.html"], .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn { display: inline-block !important; visibility: visible !important; } #userMenu, .user-menu { display: none !important; visibility: hidden !important; }`;}- async function validateTokenAndLoadUser() {- if (!cachedToken) return;+ async validateTokenAndLoadUser() {+ if (!this.cachedToken) return;try {- const res = await fetch('/api/auth/validate-token', { headers: { Authorization: `Bearer ${cachedToken}` } });+ const res = await fetch('/api/auth/validate-token', { headers: { Authorization: `Bearer ${this.cachedToken}` } });if (!res.ok) throw new Error('Token validation failed');const data = await res.json();if (data && data.valid && data.user) {- cachedUser = data.user;- localStorage.setItem('user_info', JSON.stringify(cachedUser));+ this.cachedUser = data.user;+ localStorage.setItem('user_info', JSON.stringify(this.cachedUser));} else {- clearAuthData();+ this.clearAuthData();}} catch {- clearAuthData();+ this.clearAuthData();}}- async function initAuth() {- readStateFromStorage();- immediateCssToggle();- await validateTokenAndLoadUser();- updateHeaderUI(isAuthenticated(), cachedUser);- dispatchAuthStateEvent(isAuthenticated(), cachedUser);-- // Keep dropdown handlers consistent+ attachDropdownHandlers() {const logoutMenuItem = document.getElementById('logoutMenuItem');if (logoutMenuItem) {const clone = logoutMenuItem.cloneNode(true);logoutMenuItem.parentNode.replaceChild(clone, logoutMenuItem);- clone.addEventListener('click', () => logout());+ clone.addEventListener('click', () => this.logout());}- // User menu toggle (replicates legacy behavior from auth.js)const userMenuBtnOriginal = document.getElementById('userMenuBtn');const userMenuDropdown = document.getElementById('userMenuDropdown');if (userMenuBtnOriginal && userMenuDropdown) {@@ -157,7 +156,6 @@ const authService = (() => {});}- // Settings gear menu toggle if presentconst settingsBtnOriginal = document.getElementById('settingsBtn');const settingsMenu = document.getElementById('settingsMenu');if (settingsBtnOriginal && settingsMenu) {@@ -169,8 +167,7 @@ const authService = (() => {});}- // Global click to close any open dropdowns (add once)- if (!window._authServiceGlobalClickListenerAdded) {+ if (!this.globalClickListenerAttached) {document.addEventListener('click', (e) => {const dd = document.getElementById('userMenuDropdown');const btn = document.getElementById('userMenuBtn');@@ -183,67 +180,87 @@ const authService = (() => {sm.classList.remove('active');}});- window._authServiceGlobalClickListenerAdded = true;+ this.globalClickListenerAttached = true;}+ }- // Storage changes from other tabs+ attachStorageListener() {+ if (this.storageListenerAttached) return;window.addEventListener('storage', (e) => {if (e.key === 'auth_token' || e.key === 'user_info') {- readStateFromStorage();- updateHeaderUI(isAuthenticated(), cachedUser);- dispatchAuthStateEvent(isAuthenticated(), cachedUser);+ this.readStateFromStorage();+ this.updateHeaderUI(this.isAuthenticated(), this.cachedUser);+ this.dispatchAuthStateEvent(this.isAuthenticated(), this.cachedUser);}});+ this.storageListenerAttached = true;+ }- // Optionally hide registration links if registration disabled and user logged out- if (!getToken()) {- const hideRegistrationUI = () => {- const forceHide = (el) => {- if (!el) return;- // Strong hide to defeat CSS !important rules- el.style.setProperty('display', 'none', 'important');- el.style.setProperty('visibility', 'hidden', 'important');- el.setAttribute('hidden', 'true');- el.setAttribute('aria-hidden', 'true');- };+ async ensureRegistrationVisibility() {+ if (this.getToken()) return;+ const hideRegistrationUI = () => {+ const forceHide = (el) => {+ if (!el) return;+ el.style.setProperty('display', 'none', 'important');+ el.style.setProperty('visibility', 'hidden', 'important');+ el.setAttribute('hidden', 'true');+ el.setAttribute('aria-hidden', 'true');+ };- const selectors = [- '.register-btn', '.auth-btn.register-btn',- 'a[href="register.html"]', 'a[href="./register.html"]', 'a[href="/register.html"]',- 'a[data-i18n="auth.create_account"]'- ];- selectors.forEach((sel) => document.querySelectorAll(sel).forEach(forceHide));+ const selectors = [+ '.register-btn', '.auth-btn.register-btn',+ 'a[href="register.html"]', 'a[href="./register.html"]', 'a[href="/register.html"]',+ 'a[data-i18n="auth.create_account"]'+ ];+ selectors.forEach((sel) => document.querySelectorAll(sel).forEach(forceHide));- const authLinks = document.querySelector('.auth-links');- if (authLinks) {- authLinks.querySelectorAll('a').forEach((a) => {- const text = (a.textContent || '').trim().toLowerCase();- if (text === 'create account' || a.getAttribute('href')?.includes('register.html') || a.dataset?.i18n === 'auth.create_account') {- forceHide(a);- }- });- }- };+ const authLinks = document.querySelector('.auth-links');+ if (authLinks) {+ authLinks.querySelectorAll('a').forEach((a) => {+ const text = (a.textContent || '').trim().toLowerCase();+ if (text === 'create account' || a.getAttribute('href')?.includes('register.html') || a.dataset?.i18n === 'auth.create_account') {+ forceHide(a);+ }+ });+ }+ };- try {- const res = await fetch('/api/auth/registration-status');- if (res.ok) {- const data = await res.json();- if (!data.enabled) {- hideRegistrationUI();- // Keep it hidden even if i18n or other scripts mutate DOM later- if (!window._authServiceRegObserver) {- const observer = new MutationObserver(() => hideRegistrationUI());- observer.observe(document.body, { childList: true, subtree: true });- window._authServiceRegObserver = observer;- }+ try {+ const res = await fetch('/api/auth/registration-status');+ if (res.ok) {+ const data = await res.json();+ if (!data.enabled) {+ hideRegistrationUI();+ if (!this.registrationObserver) {+ this.registrationObserver = new MutationObserver(() => hideRegistrationUI());+ this.registrationObserver.observe(document.body, { childList: true, subtree: true });}}- } catch {}+ }+ } catch {+ // Ignore errors: failing to hide registration links is non-fatal}}- async function login(username, password) {+ async initAuth() {+ if (this.initialized) {+ this.readStateFromStorage();+ this.updateHeaderUI(this.isAuthenticated(), this.cachedUser);+ this.dispatchAuthStateEvent(this.isAuthenticated(), this.cachedUser);+ return;+ }+ this.initialized = true;+ this.readStateFromStorage();+ this.immediateCssToggle();+ await this.validateTokenAndLoadUser();+ this.updateHeaderUI(this.isAuthenticated(), this.cachedUser);+ this.dispatchAuthStateEvent(this.isAuthenticated(), this.cachedUser);+ this.attachDropdownHandlers();+ this.attachStorageListener();+ await this.ensureRegistrationVisibility();+ }++ async login(username, password) {const res = await fetch('/api/auth/login', {method: 'POST',headers: { 'Content-Type': 'application/json' },@@ -253,38 +270,31 @@ const authService = (() => {if (!res.ok) throw new Error(data?.message || 'Login failed');localStorage.setItem('auth_token', data.token);localStorage.setItem('user_info', JSON.stringify(data.user));- readStateFromStorage();- updateHeaderUI(true, data.user);- dispatchAuthStateEvent(true, data.user);+ this.readStateFromStorage();+ this.updateHeaderUI(true, data.user);+ this.dispatchAuthStateEvent(true, data.user);return data;}- async function logout() {- const tokenForApi = getToken();- clearAuthData();- updateHeaderUI(false, null);- dispatchAuthStateEvent(false, null);+ async logout() {+ const tokenForApi = this.getToken();+ this.clearAuthData();+ this.updateHeaderUI(false, null);+ this.dispatchAuthStateEvent(false, null);try {if (tokenForApi) {await fetch('/api/auth/logout', { method: 'POST', headers: { Authorization: `Bearer ${tokenForApi}` } });}- } catch {}+ } catch {+ // ignore network errors during logout+ }if (window.location.pathname !== '/login.html') {window.location.href = 'login.html';}}+}- return {- initAuth,- login,- logout,- getToken,- getCurrentUser,- isAuthenticated,- clearAuthData,- onLogout,- };-})();+const authService = new AuthManager();// Backwards compatibility for existing scriptswindow.auth = {@@ -294,6 +304,7 @@ window.auth = {login: (u, p) => authService.login(u, p),logout: () => authService.logout(),onLogout: (cb) => authService.onLogout(cb),+ checkAuthState: (isInitialLoad) => authService.initAuth(),};// Auto-init on DOM readydiff --git a/frontend/js/store.js b/frontend/js/store.jsindex 1df4db9..0f856a9 100644--- a/frontend/js/store.js+++ b/frontend/js/store.js@@ -1,47 +1,277 @@-// Private state object-let state = {+const initialFilters = {+ status: 'all',+ tag: 'all',+ search: '',+ sortBy: 'expiration',+ vendor: 'all',+ warranty_type: 'all',+};++const state = {warranties: [],- filters: { status: 'all', tag: 'all', search: '', sortBy: 'expiration', vendor: 'all', warranty_type: 'all' },+ warrantiesLoaded: false,+ lastLoadedArchived: false,+ lastLoadedIncludesArchived: false,+ filters: { ...initialFilters },+ allTags: [],+ selectedTags: [],+ editSelectedTags: [],+ isGlobalView: false,+ currentView: 'grid',+ expiringSoonDays: 30,+ userPreferencePrefix: null,+ currentWarrantyId: null,+ currentTabIndex: 0,+ tabContents: [],+ editMode: false,+ claims: {+ warrantyId: null,+ items: [],+ canEdit: false,+ },+ notes: {+ warrantyId: null,+ entity: null,+ },+ paperless: {+ enabled: false,+ documents: [],+ selectedDocument: null,+ currentPage: 1,+ totalPages: 1,+ currentDocumentType: '',+ searchQuery: '',+ },isLoading: false,- allTags: []};-// Simple event dispatcher-const dispatch = (eventName, detail) => window.dispatchEvent(new CustomEvent(eventName, { detail }));+export const StoreEvents = Object.freeze({+ WARRANTIES_CHANGED: 'state:warrantiesChanged',+ FILTERS_CHANGED: 'state:filtersChanged',+ TAGS_CHANGED: 'state:tagsChanged',+ SELECTED_TAGS_CHANGED: 'state:selectedTagsChanged',+ EDIT_SELECTED_TAGS_CHANGED: 'state:editSelectedTagsChanged',+ VIEW_CHANGED: 'state:viewChanged',+ GLOBAL_VIEW_CHANGED: 'state:globalViewChanged',+ LOADING_CHANGED: 'state:loadingChanged',+ CLAIMS_CHANGED: 'state:claimsChanged',+ NOTES_CHANGED: 'state:notesChanged',+ PAPERLESS_CHANGED: 'state:paperlessChanged',+});-// Exported functions to interact with the state-export const getWarranties = () => state.warranties;-export const setWarranties = (newWarranties) => {- state.warranties = Array.isArray(newWarranties) ? newWarranties : [];- dispatch('state:warrantiesChanged', { warranties: state.warranties });-};+const listeners = new Map();++export function subscribe(eventName, callback) {+ if (!listeners.has(eventName)) {+ listeners.set(eventName, new Set());+ }+ listeners.get(eventName).add(callback);+ return () => unsubscribe(eventName, callback);+}++export function unsubscribe(eventName, callback) {+ const set = listeners.get(eventName);+ if (!set) return;+ set.delete(callback);+ if (set.size === 0) listeners.delete(eventName);+}++export function dispatch(eventName, detail) {+ window.dispatchEvent(new CustomEvent(eventName, { detail }));+ const set = listeners.get(eventName);+ if (!set) return;+ set.forEach((callback) => {+ try {+ callback(detail);+ } catch (error) {+ console.error('[store] listener error', error);+ }+ });+}++export const getState = () => ({ ...state });-export const getFilters = () => state.filters;-export const updateFilter = (key, value) => {+// Warranties+export const getWarranties = () => state.warranties.slice();+export function setWarranties(newWarranties = [], metadata = {}) {+ state.warranties = Array.isArray(newWarranties) ? [...newWarranties] : [];+ if (typeof metadata.warrantiesLoaded === 'boolean') {+ state.warrantiesLoaded = metadata.warrantiesLoaded;+ }+ if (typeof metadata.lastLoadedArchived === 'boolean') {+ state.lastLoadedArchived = metadata.lastLoadedArchived;+ }+ if (typeof metadata.lastLoadedIncludesArchived === 'boolean') {+ state.lastLoadedIncludesArchived = metadata.lastLoadedIncludesArchived;+ }+ dispatch(StoreEvents.WARRANTIES_CHANGED, {+ warranties: getWarranties(),+ meta: {+ warrantiesLoaded: state.warrantiesLoaded,+ lastLoadedArchived: state.lastLoadedArchived,+ lastLoadedIncludesArchived: state.lastLoadedIncludesArchived,+ },+ });+}++export const areWarrantiesLoaded = () => state.warrantiesLoaded;+export const wasLastLoadedArchived = () => state.lastLoadedArchived;+export const didLastLoadIncludeArchived = () => state.lastLoadedIncludesArchived;++// Filters+export const getFilters = () => ({ ...state.filters });+export function updateFilter(key, value) {+ if (!(key in state.filters)) return;state.filters[key] = value;- dispatch('state:filtersChanged', { filters: state.filters });-};+ dispatch(StoreEvents.FILTERS_CHANGED, { filters: getFilters() });+}+export function setFilters(nextFilters = {}) {+ state.filters = { ...state.filters, ...nextFilters };+ dispatch(StoreEvents.FILTERS_CHANGED, { filters: getFilters() });+}+export function resetFilters() {+ state.filters = { ...initialFilters };+ dispatch(StoreEvents.FILTERS_CHANGED, { filters: getFilters() });+}-export const setLoading = (isLoading) => {+// Loading+export function setLoading(isLoading) {state.isLoading = !!isLoading;- dispatch('state:loadingChanged', { isLoading: state.isLoading });-};+ dispatch(StoreEvents.LOADING_CHANGED, { isLoading: state.isLoading });+}+export const getIsLoading = () => state.isLoading;-export const getAllTags = () => state.allTags;-export const setAllTags = (tags) => {- state.allTags = Array.isArray(tags) ? tags : [];- dispatch('state:tagsChanged', { allTags: state.allTags });-};+// Tags+export const getAllTags = () => state.allTags.slice();+export function setAllTags(tags = []) {+ state.allTags = Array.isArray(tags) ? [...tags] : [];+ // Sync with legacy global for script.js compatibility+ if (typeof window !== 'undefined') {+ window.allTags = state.allTags.slice();+ }+ dispatch(StoreEvents.TAGS_CHANGED, { allTags: getAllTags() });+}+export const getSelectedTags = () => state.selectedTags.slice();+export function setSelectedTags(tags = []) {+ state.selectedTags = Array.isArray(tags) ? [...tags] : [];+ // Sync with legacy global for script.js compatibility+ if (typeof window !== 'undefined') {+ window.selectedTags = state.selectedTags.slice();+ }+ dispatch(StoreEvents.SELECTED_TAGS_CHANGED, { selectedTags: getSelectedTags() });+}+export const getEditSelectedTags = () => state.editSelectedTags.slice();+export function setEditSelectedTags(tags = []) {+ state.editSelectedTags = Array.isArray(tags) ? [...tags] : [];+ dispatch(StoreEvents.EDIT_SELECTED_TAGS_CHANGED, { editSelectedTags: getEditSelectedTags() });+}++// View preferences+export const getCurrentView = () => state.currentView;+export function setCurrentView(view) {+ if (!view) return;+ state.currentView = view;+ dispatch(StoreEvents.VIEW_CHANGED, { currentView: state.currentView });+}+export const getExpiringSoonDays = () => state.expiringSoonDays;+export function setExpiringSoonDays(days) {+ if (Number.isFinite(days)) state.expiringSoonDays = days;+}+export const getIsGlobalView = () => state.isGlobalView;+export function setIsGlobalView(isGlobal = false) {+ state.isGlobalView = !!isGlobal;+ dispatch(StoreEvents.GLOBAL_VIEW_CHANGED, { isGlobalView: state.isGlobalView });+}+export const getUserPreferencePrefix = () => state.userPreferencePrefix;+export function setUserPreferencePrefix(prefix) {+ state.userPreferencePrefix = prefix;+}++// Selection / tab state+export const getCurrentWarrantyId = () => state.currentWarrantyId;+export function setCurrentWarrantyId(id) {+ state.currentWarrantyId = id;+}+export const getTabState = () => ({+ currentTabIndex: state.currentTabIndex,+ tabContents: [...state.tabContents],+ editMode: state.editMode,+});+export function setTabState({ currentTabIndex, tabContents, editMode }) {+ if (Number.isInteger(currentTabIndex)) state.currentTabIndex = currentTabIndex;+ if (Array.isArray(tabContents)) state.tabContents = [...tabContents];+ if (typeof editMode === 'boolean') state.editMode = editMode;+}++// Claims+export const getClaimsState = () => ({ ...state.claims, items: state.claims.items.slice() });+export function setClaimsState(partial = {}) {+ state.claims = {+ ...state.claims,+ ...partial,+ items: Array.isArray(partial.items) ? [...partial.items] : state.claims.items,+ };+ dispatch(StoreEvents.CLAIMS_CHANGED, { claims: getClaimsState() });+}++// Notes+export const getNotesState = () => ({ ...state.notes });+export function setNotesState(partial = {}) {+ state.notes = { ...state.notes, ...partial };+ dispatch(StoreEvents.NOTES_CHANGED, { notes: getNotesState() });+}++// Paperless+export const getPaperlessState = () => ({+ ...state.paperless,+ documents: state.paperless.documents.slice(),+});+export function setPaperlessState(partial = {}) {+ state.paperless = {+ ...state.paperless,+ ...partial,+ documents: Array.isArray(partial.documents) ? [...partial.documents] : state.paperless.documents,+ };+ dispatch(StoreEvents.PAPERLESS_CHANGED, { paperless: getPaperlessState() });+}-// Non-module compatibility for existing scripts+// Non-module compatibilityif (typeof window !== 'undefined') {window.store = {+ getState,+ subscribe,+ dispatch,getWarranties,setWarranties,getFilters,updateFilter,+ setFilters,+ resetFilters,setLoading,+ getIsLoading,getAllTags,setAllTags,+ getSelectedTags,+ setSelectedTags,+ getEditSelectedTags,+ setEditSelectedTags,+ getCurrentView,+ setCurrentView,+ getIsGlobalView,+ setIsGlobalView,+ getExpiringSoonDays,+ setExpiringSoonDays,+ getUserPreferencePrefix,+ setUserPreferencePrefix,+ getCurrentWarrantyId,+ setCurrentWarrantyId,+ getTabState,+ setTabState,+ getClaimsState,+ setClaimsState,+ getNotesState,+ setNotesState,+ getPaperlessState,+ setPaperlessState,};}diff --git a/frontend/script.js b/frontend/script.jsindex dc064ef..51327f8 100644--- a/frontend/script.js+++ b/frontend/script.js@@ -1,165 +1,6 @@-// ===== MOBILE HAMBURGER MENU (kept for other pages) =====-(function() {- function buildMobileMenuContent(panel, header) {- if (!panel || !header) return;- // Build only once- if (panel.getAttribute('data-built') === 'true') return;- panel.innerHTML = '';-- const createSection = (titleText) => {- const title = document.createElement('div');- title.className = 'section-title';- title.textContent = titleText;- panel.appendChild(title);- };-- const appendLinks = (links) => {- if (!links || links.length === 0) return;- const list = document.createElement('div');- list.className = 'menu-list';- links.forEach(a => {- try {- const cloned = a.cloneNode(true);- // Remove ids to avoid duplicates- if (cloned.id) cloned.id = '';- list.appendChild(cloned);- } catch (e) {- // Skip problematic nodes- }- });- panel.appendChild(list);- };-- // Resolve auth state and display name- const isAuthenticated = !!(function(){ try { return localStorage.getItem('auth_token'); } catch(_) { return null; } })();- let displayName = '';- const headerDisplayNameEl = header.querySelector('#userDisplayName');- if (headerDisplayNameEl && headerDisplayNameEl.textContent) {- displayName = headerDisplayNameEl.textContent.trim();- }- if (!displayName) {- try {- const userInfo = JSON.parse(localStorage.getItem('user_info') || 'null');- if (userInfo) displayName = userInfo.first_name || userInfo.username || 'Account';- } catch(_) {}- }- if (!displayName) displayName = 'Account';-- // Nav links- const navLinksContainer = header.querySelector('.nav-links');- const navAnchors = navLinksContainer ? Array.from(navLinksContainer.querySelectorAll('a')) : [];- if (navAnchors.length) {- createSection('Navigation');- appendLinks(navAnchors);- }-- // Auth buttons if present (only when NOT authenticated)- const authContainer = header.querySelector('#authContainer');- const authAnchors = (!isAuthenticated && authContainer) ? Array.from(authContainer.querySelectorAll('a')) : [];- if (!isAuthenticated && authAnchors.length) {- createSection('Account');- appendLinks(authAnchors);- }-- // User menu dropdown items if present- const userDropdown = header.querySelector('#userMenuDropdown');- const userMenuAnchors = userDropdown ? Array.from(userDropdown.querySelectorAll('a')) : [];- if (userMenuAnchors.length) {- // Use username as section title when available- createSection(displayName || 'Menu');- appendLinks(userMenuAnchors);-- // Add Logout if available- const logoutSource = header.querySelector('#logoutMenuItem');- if (logoutSource) {- const logoutLink = document.createElement('a');- logoutLink.href = '#';- logoutLink.id = 'mobileLogoutLink';- logoutLink.innerHTML = '<i class="fas fa-sign-out-alt"></i> <span>Logout</span>';- logoutLink.addEventListener('click', async function(e) {- e.preventDefault();- try {- if (window.auth && typeof window.auth.logout === 'function') {- await window.auth.logout();- } else {- localStorage.removeItem('auth_token');- localStorage.removeItem('user_info');- window.location.href = 'login.html';- }- } catch (_) {- localStorage.removeItem('auth_token');- localStorage.removeItem('user_info');- window.location.href = 'login.html';- }- });- const list = document.createElement('div');- list.className = 'menu-list';- list.appendChild(logoutLink);- panel.appendChild(list);- }- }-- panel.setAttribute('data-built', 'true');- }-- function initializeMobileMenu() {- const header = document.querySelector('header');- if (!header) return;- const toggleBtn = header.querySelector('.mobile-menu-toggle');- const panel = document.getElementById('mobileMenuPanel');- const overlay = document.getElementById('mobileMenuOverlay');- if (!toggleBtn || !panel || !overlay) return;-- // Prevent double-binding- if (toggleBtn.getAttribute('data-mm-bound') === '1') return;- toggleBtn.setAttribute('data-mm-bound', '1');-- const openMenu = () => {- buildMobileMenuContent(panel, header);- panel.classList.add('is-open');- overlay.classList.add('is-open');- document.body.classList.add('mobile-menu-active');- };-- const closeMenu = () => {- panel.classList.remove('is-open');- overlay.classList.remove('is-open');- document.body.classList.remove('mobile-menu-active');- };-- toggleBtn.addEventListener('click', function(e) {- e.preventDefault();- const isOpen = panel.classList.contains('is-open');- if (isOpen) closeMenu(); else openMenu();- });-- overlay.addEventListener('click', function() {- closeMenu();- });-- panel.addEventListener('click', function(e) {- const link = e.target.closest('a');- if (link && link.href) {- closeMenu();- }- });-- document.addEventListener('keydown', function(e) {- if (e.key === 'Escape' && panel.classList.contains('is-open')) {- closeMenu();- }- });- }-- // Expose and initialize- window.initializeMobileMenu = initializeMobileMenu;- document.addEventListener('DOMContentLoaded', initializeMobileMenu);-})();console.log('[SCRIPT VERSION] 20250529-005 - Added CSS cache busting for consistent styling across domains');console.log('[DEBUG] script.js loaded and running');-// alert('script.js loaded!'); // Remove alert after confirming script loads-// Global variableslet warranties = [];let warrantiesLoaded = false; // Track if warranties have been loaded from API@@ -310,6 +151,9 @@ function getUserType() {* Initialize view controls for all authenticated users*/async function initViewControls() {+ if (window.warrantyListController && typeof window.warrantyListController.initViewControls === 'function') {+ return window.warrantyListController.initViewControls();+ }// Check if global view is enabledtry {const response = await fetch('/api/settings/global-view-status', {@@ -365,6 +209,9 @@ async function initViewControls() {* Switch to personal view (user's own warranties)*/async function switchToPersonalView() {+ if (window.warrantyListController && typeof window.warrantyListController.switchToPersonalView === 'function') {+ return window.warrantyListController.switchToPersonalView();+ }if (!personalViewBtn || !globalViewBtn) return;isGlobalView = false;@@ -403,6 +250,9 @@ async function switchToPersonalView() {* Switch to global view (all users' warranties) - available to all users*/async function switchToGlobalView() {+ if (window.warrantyListController && typeof window.warrantyListController.switchToGlobalView === 'function') {+ return window.warrantyListController.switchToGlobalView();+ }if (!personalViewBtn || !globalViewBtn) return;// Check if global view is still enabled@@ -487,6 +337,9 @@ function getPreferenceKeyPrefix() {* @param {string} scope - 'personal' or 'global'*/function saveViewScopePreference(scope) {+ if (window.warrantyListController && typeof window.warrantyListController.saveViewScopePreference === 'function') {+ return window.warrantyListController.saveViewScopePreference(scope);+ }try {const prefix = getPreferenceKeyPrefix();localStorage.setItem(`${prefix}viewScope`, scope);@@ -501,6 +354,9 @@ function saveViewScopePreference(scope) {* @returns {string} The saved preference ('personal', 'global', or 'personal' as default)*/function loadViewScopePreference() {+ if (window.warrantyListController && typeof window.warrantyListController.loadViewScopePreference === 'function') {+ return window.warrantyListController.loadViewScopePreference();+ }try {const prefix = getPreferenceKeyPrefix();const savedScope = localStorage.getItem(`${prefix}viewScope`);@@ -513,54 +369,7 @@ function loadViewScopePreference() {}// Theme Management - Simplified-function setTheme(isDark) {- const theme = isDark ? 'dark' : 'light';- console.log('Setting theme to:', theme);-- // 1. Apply theme attribute to document root- document.documentElement.setAttribute('data-theme', theme);-- // 2. Save the single source of truth to localStorage- localStorage.setItem('darkMode', isDark);-- // Update toggle state if the toggle exists on this page (e.g., in the header)- const headerToggle = document.getElementById('darkModeToggle');- if (headerToggle) {- headerToggle.checked = isDark;- }-}--// Persist theme to API similar to view/filters-async function saveThemePreference(isDark, saveToApi = true) {- try {- // Always persist locally first- setTheme(isDark);-- if (saveToApi && window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {- const token = window.auth.getToken();- if (token) {- try {- console.log('[Theme] Saving theme preference to API:', isDark ? 'dark' : 'light');- const response = await fetch('/api/auth/preferences', {- method: 'PUT',- headers: {- 'Authorization': `Bearer ${token}`,- 'Content-Type': 'application/json'- },- body: JSON.stringify({ theme: isDark ? 'dark' : 'light' })- });- if (!response.ok) {- console.warn('[Theme] Failed to save theme to API:', response.status);- }- } catch (err) {- console.error('[Theme] Error saving theme to API:', err);- }- }- }- } catch (e) {- console.warn('Failed to save theme preference', e);- }-}+// Theme functions are now in js/lib/theme.js and exposed globally via window.setTheme and window.saveThemePreference// Initialization logic on DOMContentLoadeddocument.addEventListener('DOMContentLoaded', function() {@@ -668,14 +477,11 @@ document.addEventListener('DOMContentLoaded', function() {// --- END REFACTORED TAG MODAL AND MAIN FORM TAG UI SETUP ---- // Setup form submission (assuming addWarrantyForm exists - this is 'warrantyFormElement')- // const form = document.getElementById('addWarrantyForm'); // Old selector- if (warrantyFormElement) { // Use the variable defined above- warrantyFormElement.addEventListener('submit', handleFormSubmit);- // Initialize form tabs if the form exists- // initFormTabs(); // This should be called when the ADD MODAL is SHOWN, not globally here.- // It's correctly in setupModalTriggers for the addWarrantyModal.- }+ // Setup form submission - REMOVED: now handled by js/components/addWarrantyForm.js+ // The modular component handles form submission to prevent duplicate submissions+ // if (warrantyFormElement) {+ // warrantyFormElement.addEventListener('submit', handleFormSubmit);+ // }// Initialize theme toggle state *after* DOM is loaded@@ -818,16 +624,7 @@ document.addEventListener('DOMContentLoaded', function() {// updateCurrencySymbols(); // Call removed, rely on loadWarranties triggering render with correct symbol});-// Initialize theme based on user preference or system preference-function initializeTheme() {- // Only use the global darkMode key for theme persistence- const savedTheme = localStorage.getItem('darkMode');- if (savedTheme !== null) {- setTheme(savedTheme === 'true');- } else {- setTheme(window.matchMedia('(prefers-color-scheme: dark)').matches);- }-}+// initializeTheme is now in js/lib/theme.js and exposed globally via window.initializeTheme// Variableslet currentView = 'grid'; // Default view@@ -885,608 +682,115 @@ let formTabs = []; // Changed from const to let, initialized as empty// const prevButton = document.querySelector('.prev-tab'); // Keep these if needed globally, otherwise might remove// --- Add near other DOM Element declarations ---- // ... existing code ...- // Add save button handler for notes modal (if not already present)- const saveNotesBtn = document.getElementById('saveNotesBtn');- if (saveNotesBtn) {- saveNotesBtn.onclick = async function() {- // Get the warranty ID being edited- const warrantyId = notesModalWarrantyId;- const notesValue = document.getElementById('notesModalTextarea').value;- if (!warrantyId || !notesModalWarrantyObj) return;- // Get auth token- const token = localStorage.getItem('auth_token');- if (!token) {- showToast(window.t('messages.authentication_required'), 'error');- return;- }- showLoadingSpinner();- try {- // Use FormData and send all required fields, just like the edit modal- const formData = new FormData();- formData.append('product_name', notesModalWarrantyObj.product_name);- formData.append('purchase_date', (notesModalWarrantyObj.purchase_date || '').split('T')[0]);- formData.append('is_lifetime', notesModalWarrantyObj.is_lifetime ? 'true' : 'false');- if (!notesModalWarrantyObj.is_lifetime) {- // Append duration components instead of warranty_years- formData.append('warranty_duration_years', notesModalWarrantyObj.warranty_duration_years || 0);- formData.append('warranty_duration_months', notesModalWarrantyObj.warranty_duration_months || 0);- formData.append('warranty_duration_days', notesModalWarrantyObj.warranty_duration_days || 0);-- // If all duration fields are 0 but we have an expiration date, this was created with exact date method- const isExactDateWarranty = (notesModalWarrantyObj.warranty_duration_years || 0) === 0 &&- (notesModalWarrantyObj.warranty_duration_months || 0) === 0 &&- (notesModalWarrantyObj.warranty_duration_days || 0) === 0 &&- notesModalWarrantyObj.expiration_date;-- if (isExactDateWarranty) {- // For exact date warranties, send the expiration date as exact_expiration_date- formData.append('exact_expiration_date', notesModalWarrantyObj.expiration_date.split('T')[0]);- }- }- if (notesModalWarrantyObj.product_url) {- formData.append('product_url', notesModalWarrantyObj.product_url);- }- if (notesModalWarrantyObj.purchase_price !== null && notesModalWarrantyObj.purchase_price !== undefined) {- formData.append('purchase_price', notesModalWarrantyObj.purchase_price);- }- if (notesModalWarrantyObj.vendor) {- formData.append('vendor', notesModalWarrantyObj.vendor);- }- if (notesModalWarrantyObj.warranty_type) {- formData.append('warranty_type', notesModalWarrantyObj.warranty_type);- }- if (typeof notesModalWarrantyObj.model_number !== 'undefined' && notesModalWarrantyObj.model_number !== null) {- formData.append('model_number', notesModalWarrantyObj.model_number);- }- if (notesModalWarrantyObj.serial_numbers && Array.isArray(notesModalWarrantyObj.serial_numbers)) {- notesModalWarrantyObj.serial_numbers.forEach(sn => {- if (sn && sn.trim() !== '') {- formData.append('serial_numbers[]', sn); // Use [] for arrays- }- });- } else if (!formData.has('serial_numbers[]')) {- // Send empty array if none exist- // formData.append('serial_numbers[]', ''); // Sending empty string might not work as expected, better to not send if empty- }- if (notesModalWarrantyObj.tags && Array.isArray(notesModalWarrantyObj.tags)) {- const tagIds = notesModalWarrantyObj.tags.map(tag => tag.id);- formData.append('tag_ids', JSON.stringify(tagIds));- } else {- formData.append('tag_ids', JSON.stringify([]));- }- formData.append('notes', notesValue);- // Also include model number value from edit input if present on DOM- const editModelNumberInput = document.getElementById('editModelNumber');- if (editModelNumberInput && editModelNumberInput.value.trim() !== '') {- formData.set('model_number', editModelNumberInput.value.trim());- }- const response = await fetch(`/api/warranties/${warrantyId}`, {- method: 'PUT',- headers: {- 'Authorization': 'Bearer ' + token- },- body: formData- });- if (!response.ok) {- const data = await response.json();- throw new Error(data.error || 'Failed to update notes');- }- hideLoadingSpinner();- showToast(window.t('messages.notes_updated_successfully'), 'success');- // Close the modal- const notesModal = document.getElementById('notesModal');- if (notesModal) notesModal.style.display = 'none';- // Now reload warranties and re-render UI- await loadWarranties();- applyFilters();- } catch (error) {- hideLoadingSpinner();- console.error('Error updating notes:', error);- showToast(error.message || window.t('messages.failed_to_update_notes'), 'error');- }- };- }--// Initialize form tabs-function initFormTabs() {- console.log('Initializing form tabs...');- // Use the modal context if available, otherwise query document- const modalContext = document.getElementById('addWarrantyModal'); // Assuming this is the context- const context = modalContext && modalContext.classList.contains('active') ? modalContext : document;-- const tabsContainer = context.querySelector('.form-tabs');- // Re-query tabContents and formTabs within the correct context and update global variables- const contentsElements = context.querySelectorAll('.tab-content');- tabContents = contentsElements ? Array.from(contentsElements) : []; // Update global variable-- const tabsElements = tabsContainer ? tabsContainer.querySelectorAll('.form-tab') : [];- formTabs = tabsElements ? Array.from(tabsElements) : []; // Update global variable-- const nextButton = context.querySelector('#nextTabBtn'); // Use context- const prevButton = context.querySelector('#prevTabBtn'); // Use context- const submitButton = context.querySelector('#submitWarrantyBtn'); // Use context-- // Use the updated global variables length for checks- if (!tabsContainer || !tabContents.length || !formTabs.length || !nextButton || !prevButton || !submitButton) {- console.warn('Form tab elements not found in the expected context. Skipping tab initialization.');- return; // Don't proceed if elements aren't present- }-- // Remove the local 'tabs' and 'contents' variables, use global ones now- // let currentTabIndex = 0; // Already global- // const tabs = tabsContainer.querySelectorAll('.form-tab'); // Use global formTabs- // const contents = document.querySelectorAll('.tab-content'); // Use global tabContents-- // Remove the inner switchToTab and updateNavigationButtons functions as they are defined globally- /*- function switchToTab(index) {- // ... removed inner function ...- }-- function updateNavigationButtons() {- // ... removed inner function ...- }- */-- // --- CLONE AND REPLACE NAV BUTTONS TO REMOVE OLD LISTENERS ---- // Ensure buttons exist before cloning- let nextButtonCloned = nextButton;- let prevButtonCloned = prevButton;- if (nextButton && prevButton) {- nextButtonCloned = nextButton.cloneNode(true);- prevButtonCloned = prevButton.cloneNode(true);- nextButton.parentNode.replaceChild(nextButtonCloned, nextButton);- prevButton.parentNode.replaceChild(prevButtonCloned, prevButton);- } else {- console.warn("Next/Prev buttons not found for cloning listeners.");- }--- // ... (rest of initFormTabs, including event listeners, ensure element checks)- // Make sure event listeners use the correct global functions and variables- formTabs.forEach((tab, index) => { // Use global formTabs- if (tab) { // Check if tab exists- tab.addEventListener('click', () => {- // Allow clicking only on previous tabs if valid, or current- if (index < currentTabIndex) {- let canSwitch = true;- for (let i = 0; i < index; i++) {- // Ensure validateTab uses the correct global tabContents- if (!validateTab(i)) {- canSwitch = false;- break;- }- }- if (canSwitch) switchToTab(index); // Call global function- } else if (index === currentTabIndex) {- // Clicking current tab does nothing- } else {- // Try to navigate forward by clicking tab- // Ensure validateTab uses the correct global tabContents- if (validateTab(currentTabIndex)) {- // Mark current as completed- if(formTabs[currentTabIndex]) formTabs[currentTabIndex].classList.add('completed'); // Use global formTabs- switchToTab(index); // Call global function- } else {- // If current tab is invalid, show errors for it- showValidationErrors(currentTabIndex);- }- }- });+// ... existing code ...+// Add save button handler for notes modal (if not already present)+const saveNotesBtn = document.getElementById('saveNotesBtn');+if (saveNotesBtn) {+ saveNotesBtn.onclick = async function() {+ if (window.components?.notes?.showNotesModal) {+ return;}- });-- if (nextButtonCloned) { // Check button exists- nextButtonCloned.addEventListener('click', () => {- // Ensure validateTab uses the correct global tabContents- if (validateTab(currentTabIndex)) {- if (formTabs[currentTabIndex]) formTabs[currentTabIndex].classList.add('completed'); // Use global formTabs- // Use global formTabs length- if (currentTabIndex < formTabs.length - 1) { // <-- Ensure this uses formTabs.length- switchToTab(currentTabIndex + 1); // Call global function+ // Get the warranty ID being edited+ const warrantyId = notesModalWarrantyId;+ const notesValue = document.getElementById('notesModalTextarea').value;+ if (!warrantyId || !notesModalWarrantyObj) return;+ // Get auth token+ const token = localStorage.getItem('auth_token');+ if (!token) {+ showToast(window.t('messages.authentication_required'), 'error');+ return;+ }+ showLoadingSpinner();+ try {+ // Use FormData and send all required fields, just like the edit modal+ const formData = new FormData();+ formData.append('product_name', notesModalWarrantyObj.product_name);+ formData.append('purchase_date', (notesModalWarrantyObj.purchase_date || '').split('T')[0]);+ formData.append('is_lifetime', notesModalWarrantyObj.is_lifetime ? 'true' : 'false');+ if (!notesModalWarrantyObj.is_lifetime) {+ // Append duration components instead of warranty_years+ formData.append('warranty_duration_years', notesModalWarrantyObj.warranty_duration_years || 0);+ formData.append('warranty_duration_months', notesModalWarrantyObj.warranty_duration_months || 0);+ formData.append('warranty_duration_days', notesModalWarrantyObj.warranty_duration_days || 0);++ // If all duration fields are 0 but we have an expiration date, this was created with exact date method+ const isExactDateWarranty = (notesModalWarrantyObj.warranty_duration_years || 0) === 0 &&+ (notesModalWarrantyObj.warranty_duration_months || 0) === 0 &&+ (notesModalWarrantyObj.warranty_duration_days || 0) === 0 &&+ notesModalWarrantyObj.expiration_date;++ if (isExactDateWarranty) {+ // For exact date warranties, send the expiration date as exact_expiration_date+ formData.append('exact_expiration_date', notesModalWarrantyObj.expiration_date.split('T')[0]);}- } else {- // If current tab is invalid, show errors- showValidationErrors(currentTabIndex);}- });- } else {- console.warn("Cloned Next button not found, listener not added.");- }-- if (prevButtonCloned) { // Check button exists- prevButtonCloned.addEventListener('click', () => {- if (currentTabIndex > 0) {- switchToTab(currentTabIndex - 1);- }- });- }-- // Initialize the first tab- switchToTab(0);-}--// Switch to a specific tab-function switchToTab(index) {- console.log(`Switching to tab ${index} from tab ${currentTabIndex}`);-- // Ensure index is within bounds- if (index < 0 || index >= formTabs.length) {- console.log(`Invalid tab index: ${index}, not switching`);- return;- }-- // Update summary FIRST if switching TO the summary tab- if (index === formTabs.length - 1) {- updateSummary();- }-- // Update active tab- formTabs.forEach(tab => tab.classList.remove('active'));- tabContents.forEach(content => content.classList.remove('active'));-- formTabs[index].classList.add('active');- tabContents[index].classList.add('active');-- // Update current tab index- currentTabIndex = index;-- // Update progress indicator- document.querySelector('.form-tabs').setAttribute('data-step', currentTabIndex);-- // Update completed tabs- updateCompletedTabs();-- // Update navigation buttons- updateNavigationButtons();-}--// Update navigation buttons based on current tab-function updateNavigationButtons() {- const prevButton = document.querySelector('.prev-tab');- const nextButton = document.querySelector('.next-tab');- const submitButton = document.querySelector('button[type="submit"]');-- // Hide/show previous button- prevButton.style.display = currentTabIndex === 0 ? 'none' : 'block';-- // Hide/show next button and submit button- if (currentTabIndex === formTabs.length - 1) {- nextButton.style.display = 'none';- submitButton.style.display = 'block';- } else {- nextButton.style.display = 'block';- submitButton.style.display = 'none';- }-}--// Update completed tabs-function updateCompletedTabs() {- formTabs.forEach((tab, index) => {- if (index < currentTabIndex) {- tab.classList.add('completed');- } else {- tab.classList.remove('completed');- }- });-}--// Validate a specific tab-function validateTab(tabIndex) {- const tabContent = tabContents[tabIndex];- const controls = tabContent.querySelectorAll('input, textarea, select');- let isTabValid = true;-- controls.forEach(control => {- // Clear previous validation state- control.classList.remove('invalid');- let validationMessageElement = control.nextElementSibling;- if (validationMessageElement && validationMessageElement.classList.contains('validation-message')) {- validationMessageElement.remove();- }-- // Manual validation for required fields- if (control.hasAttribute('required') && control.value.trim() === '') {- isTabValid = false;- control.classList.add('invalid');- // Mark as invalid, message will be added by showValidationErrors- } else if (!control.validity.valid) { // For other HTML5 validation issues (e.g., type mismatch)- isTabValid = false;- control.classList.add('invalid');- }- });- return isTabValid;-}--// Show validation errors for a specific tab-function showValidationErrors(tabIndex) {- const tabContent = tabContents[tabIndex];- const controls = tabContent.querySelectorAll('input, textarea, select');- let firstInvalidControl = null;- let validationToast = document.querySelector('.validation-toast'); // Check for existing validation toast-- controls.forEach(control => {- if (!control.validity.valid) {- if (!firstInvalidControl) firstInvalidControl = control;- control.classList.add('invalid');-- // Add or update validation message- let validationMessageElement = control.nextElementSibling;- if (!validationMessageElement || !validationMessageElement.classList.contains('validation-message')) {- validationMessageElement = document.createElement('div');- validationMessageElement.className = 'validation-message';- control.parentNode.insertBefore(validationMessageElement, control.nextSibling);+ if (notesModalWarrantyObj.product_url) {+ formData.append('product_url', notesModalWarrantyObj.product_url);}- if (control.hasAttribute('required') && control.value.trim() === '') {- validationMessageElement.textContent = window.i18next ? window.i18next.t('messages.please_fill_out_this_field') : 'Please fill out this field.';- } else {- validationMessageElement.textContent = control.validationMessage || (window.i18next ? window.i18next.t('messages.field_is_invalid') : 'This field is invalid.');+ if (notesModalWarrantyObj.purchase_price !== null && notesModalWarrantyObj.purchase_price !== undefined) {+ formData.append('purchase_price', notesModalWarrantyObj.purchase_price);}- } else {- // Ensure invalid class is removed if somehow missed by validateTab (shouldn't happen)- control.classList.remove('invalid');- // Remove validation message if control is now valid- let validationMessageElement = control.nextElementSibling;- if (validationMessageElement && validationMessageElement.classList.contains('validation-message')) {- validationMessageElement.remove();+ if (notesModalWarrantyObj.vendor) {+ formData.append('vendor', notesModalWarrantyObj.vendor);}- }- });-- // The browser will attempt to focus the first invalid field when form submission is prevented.- // Switching to the tab containing the error (done by handleFormSubmit) is key.-- // Manage a single validation toast- if (!validationToast) {- validationToast = showToast(window.t('messages.correct_errors_in_tab'), 'error', 0); // 0 duration = persistent- validationToast.classList.add('validation-toast'); // Add a class to identify it- } else {- // Update existing toast message if needed (optional)- validationToast.querySelector('span').textContent = window.t('messages.correct_errors_in_tab');- }-}--// Update summary tab with current form values-function updateSummary() {- // Product information- const summaryProductName = document.getElementById('summary-product-name');- if (summaryProductName) {- summaryProductName.textContent =- document.getElementById('productName')?.value || '-';- }-- const summaryProductUrl = document.getElementById('summary-product-url');- if (summaryProductUrl) {- summaryProductUrl.textContent =- document.getElementById('productUrl')?.value || '-';- }-- // Serial numbers- const serialNumbers = [];- document.querySelectorAll('input[name="serial_numbers[]"]').forEach(input => {- if (input && input.value && input.value.trim()) {- serialNumbers.push(input.value.trim());- }- });-- const serialNumbersContainer = document.getElementById('summary-serial-numbers');- if (serialNumbersContainer) {- if (serialNumbers.length > 0) {- serialNumbersContainer.innerHTML = '<ul>' +- serialNumbers.map(sn => `<li>${sn}</li>`).join('') +- '</ul>';- } else {- serialNumbersContainer.textContent = 'None';- }- }-- // Warranty details- const purchaseDateStr = document.getElementById('purchaseDate')?.value;- const summaryPurchaseDate = document.getElementById('summary-purchase-date');- if (summaryPurchaseDate) {- if (purchaseDateStr) {- // Use the same logic as formatDate to handle YYYY-MM-DD- const parts = String(purchaseDateStr).split('-');- let formattedDate = '-'; // Default- if (parts.length === 3) {- const year = parseInt(parts[0], 10);- const month = parseInt(parts[1], 10) - 1; // JS months are 0-indexed- const day = parseInt(parts[2], 10);- const dateObj = new Date(Date.UTC(year, month, day));- if (!isNaN(dateObj.getTime())) {- // Format manually (example: Jan 1, 2023)- const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];- formattedDate = `${monthNames[month]} ${day}, ${year}`;- }+ if (notesModalWarrantyObj.warranty_type) {+ formData.append('warranty_type', notesModalWarrantyObj.warranty_type);}- summaryPurchaseDate.textContent = formattedDate;- } else {- summaryPurchaseDate.textContent = '-';- }- }-- // --- Handle Lifetime in Summary ---- const isLifetime = isLifetimeCheckbox ? isLifetimeCheckbox.checked : false;- const summaryWarrantyDuration = document.getElementById('summary-warranty-duration'); // Use new ID-- if (summaryWarrantyDuration) {- if (isLifetime) {- summaryWarrantyDuration.textContent = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';- } else {- const years = parseInt(warrantyDurationYearsInput?.value || 0);- const months = parseInt(warrantyDurationMonthsInput?.value || 0);- const days = parseInt(warrantyDurationDaysInput?.value || 0);-- let durationParts = [];- if (years > 0) {- const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;- durationParts.push(`${years} ${yearText}`);+ if (typeof notesModalWarrantyObj.model_number !== 'undefined' && notesModalWarrantyObj.model_number !== null) {+ formData.append('model_number', notesModalWarrantyObj.model_number);}- if (months > 0) {- const monthText = window.i18next ? window.i18next.t('warranties.month', {count: months}) : `month${months !== 1 ? 's' : ''}`;- durationParts.push(`${months} ${monthText}`);+ if (notesModalWarrantyObj.serial_numbers && Array.isArray(notesModalWarrantyObj.serial_numbers)) {+ notesModalWarrantyObj.serial_numbers.forEach(sn => {+ if (sn && sn.trim() !== '') {+ formData.append('serial_numbers[]', sn); // Use [] for arrays+ }+ });+ } else if (!formData.has('serial_numbers[]')) {+ // Send empty array if none exist+ // formData.append('serial_numbers[]', ''); // Sending empty string might not work as expected, better to not send if empty}- if (days > 0) {- const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;- durationParts.push(`${days} ${dayText}`);+ if (notesModalWarrantyObj.tags && Array.isArray(notesModalWarrantyObj.tags)) {+ const tagIds = notesModalWarrantyObj.tags.map(tag => tag.id);+ formData.append('tag_ids', JSON.stringify(tagIds));+ } else {+ formData.append('tag_ids', JSON.stringify([]));}-- summaryWarrantyDuration.textContent = durationParts.length > 0 ? durationParts.join(', ') : '-';- }- }-- // Warranty type - handle dropdown and custom input- const warrantyTypeSelect = document.getElementById('warrantyType');- const warrantyTypeCustom = document.getElementById('warrantyTypeCustom');- const summaryWarrantyType = document.getElementById('summary-warranty-type');- if (summaryWarrantyType) {- let warrantyTypeText = 'Not specified';- if (warrantyTypeSelect && warrantyTypeSelect.value) {- if (warrantyTypeSelect.value === 'other' && warrantyTypeCustom && warrantyTypeCustom.value.trim()) {- warrantyTypeText = warrantyTypeCustom.value.trim();- } else if (warrantyTypeSelect.value !== 'other') {- warrantyTypeText = warrantyTypeSelect.value;+ formData.append('notes', notesValue);+ // Also include model number value from edit input if present on DOM+ const editModelNumberInput = document.getElementById('editModelNumber');+ if (editModelNumberInput && editModelNumberInput.value.trim() !== '') {+ formData.set('model_number', editModelNumberInput.value.trim());}- }- summaryWarrantyType.textContent = warrantyTypeText;- }-- // Purchase price- const purchasePrice = document.getElementById('purchasePrice')?.value;- const currency = document.getElementById('currency')?.value;- const summaryPurchasePrice = document.getElementById('summary-purchase-price');- if (summaryPurchasePrice) {- if (purchasePrice) {- const symbol = getCurrencySymbol();- const position = getCurrencyPosition();- const amount = parseFloat(purchasePrice).toFixed(2);- summaryPurchasePrice.innerHTML = formatCurrencyHTML(amount, symbol, position);- } else {- summaryPurchasePrice.textContent = 'Not specified';- }- }-- // Documents- const productPhotoFile = document.getElementById('productPhoto')?.files[0];- const summaryProductPhoto = document.getElementById('summary-product-photo');- if (summaryProductPhoto) {- summaryProductPhoto.textContent = productPhotoFile ?- productPhotoFile.name : 'No photo selected';- }-- const invoiceFile = document.getElementById('invoice')?.files[0];- const invoiceUrlField = document.getElementById('invoiceUrl');- const invoiceUrl = invoiceUrlField ? invoiceUrlField.value : '';- const summaryInvoice = document.getElementById('summary-invoice');- if (summaryInvoice) {- if (invoiceFile) {- summaryInvoice.textContent = invoiceFile.name;- } else if (invoiceUrl) {- summaryInvoice.textContent = 'URL: ' + invoiceUrl;- } else {- summaryInvoice.textContent = 'Not specified';- }- }-- const manualFile = document.getElementById('manual')?.files[0];- const manualUrlField = document.getElementById('manualUrl');- const manualUrl = manualUrlField ? manualUrlField.value : '';- const summaryManual = document.getElementById('summary-manual');- if (summaryManual) {- if (manualFile) {- summaryManual.textContent = manualFile.name;- } else if (manualUrl) {- summaryManual.textContent = 'URL: ' + manualUrl;- } else {- summaryManual.textContent = 'Not specified';- }- }-- const otherDocumentFile = document.getElementById('otherDocument')?.files[0];- const otherDocumentUrlField = document.getElementById('otherDocumentUrl');- const otherDocumentUrl = otherDocumentUrlField ? otherDocumentUrlField.value : '';- const summaryOtherDocument = document.getElementById('summary-other-document');- if (summaryOtherDocument) {- if (otherDocumentFile) {- summaryOtherDocument.textContent = otherDocumentFile.name;- } else if (otherDocumentUrl) {- summaryOtherDocument.textContent = 'URL: ' + otherDocumentUrl;- } else {- summaryOtherDocument.textContent = 'Not specified';- }- }-- // Tags- const summaryTags = document.getElementById('summary-tags');- if (summaryTags) {- if (selectedTags && selectedTags.length > 0) {- summaryTags.innerHTML = '';-- selectedTags.forEach(tag => {- const tagElement = document.createElement('span');- tagElement.className = 'tag';- tagElement.style.backgroundColor = tag.color;- tagElement.style.color = getContrastColor(tag.color);- tagElement.textContent = tag.name;-- summaryTags.appendChild(tagElement);+ const response = await fetch(`/api/warranties/${warrantyId}`, {+ method: 'PUT',+ headers: {+ 'Authorization': 'Bearer ' + token+ },+ body: formData});- } else {- summaryTags.textContent = 'No tags selected';- }- }-- // Vendor/Retailer- const vendor = document.getElementById('vendor');- document.getElementById('summary-vendor').textContent = vendor && vendor.value ? vendor.value : '-';-}--// Add input event listeners to remove validation errors when user types-document.addEventListener('input', (e) => {- if (e.target.hasAttribute('required') && e.target.classList.contains('invalid')) {- if (e.target.value.trim()) {- e.target.classList.remove('invalid');-- // Remove validation message if exists- const validationMessage = e.target.nextElementSibling;- if (validationMessage && validationMessage.classList.contains('validation-message')) {- validationMessage.remove();+ if (!response.ok) {+ const data = await response.json();+ throw new Error(data.error || 'Failed to update notes');}+ hideLoadingSpinner();+ showToast(window.t('messages.notes_updated_successfully'), 'success');+ // Close the modal+ const notesModal = document.getElementById('notesModal');+ if (notesModal) notesModal.style.display = 'none';+ // Now reload warranties and re-render UI+ await loadWarranties();+ applyFilters();+ } catch (error) {+ hideLoadingSpinner();+ console.error('Error updating notes:', error);+ showToast(error.message || window.t('messages.failed_to_update_notes'), 'error');}- }-});--// Function to reset the form and initialize serial number inputs-function resetForm() {- // Reset the form- warrantyForm.reset();-- // Reset serial numbers container- serialNumbersContainer.innerHTML = '';-- // Add the first serial number input- addSerialNumberInput();-- // Reset form tabs- currentTabIndex = 0;- switchToTab(0);-- // Clear any file input displays- const productPhotoFileName = document.getElementById('productPhotoFileName');- if (productPhotoFileName) productPhotoFileName.textContent = '';- fileName.textContent = '';- manualFileName.textContent = '';- if (otherDocumentFileName) otherDocumentFileName.textContent = '';-- // Reset photo preview- const productPhotoPreview = document.getElementById('productPhotoPreview');- if (productPhotoPreview) {- productPhotoPreview.style.display = 'none';- }+ };}+// Initialize form tabs+// Form tabs functionality moved to js/components/formTabs.js+async function exportWarranties() {console.log('[EXPORT DEBUG] Starting export process');console.log('[EXPORT DEBUG] Total warranties in memory:', warranties.length);@@ -1615,6 +919,9 @@ async function exportWarranties() {// Switch view of warranties listasync function switchView(viewType, saveToApi = true) { // Added saveToApi parameter with default true+ if (window.warrantyListController && typeof window.warrantyListController.switchView === 'function') {+ return window.warrantyListController.switchView(viewType, saveToApi);+ }console.log(`Switching to view: ${viewType}`);currentView = viewType;@@ -1726,6 +1033,9 @@ async function switchView(viewType, saveToApi = true) { // Added saveToApi param// Load view preference from localStoragefunction loadViewPreference() {+ if (window.warrantyListController && typeof window.warrantyListController.loadViewPreference === 'function') {+ return window.warrantyListController.loadViewPreference();+ }// Get the appropriate key prefix based on user typeconst prefix = getPreferenceKeyPrefix();let savedView = null;@@ -1775,77 +1085,14 @@ if (serialNumbersContainer) {}// Add a serial number input field-function addSerialNumberInput(container = serialNumbersContainer) {- // Check if the container exists before proceeding- if (!container) {- console.warn('Serial numbers container not found, cannot add input.');- return;- }-- const div = document.createElement('div');- div.className = 'serial-number-input d-flex mb-2';-- // Create an input element- const input = document.createElement('input');- input.type = 'text';- input.className = 'form-control';- input.name = 'serial_numbers[]';- input.placeholder = window.i18next ? window.i18next.t('warranties.enter_serial_number') : 'Enter serial number';- console.log('i18next available for serial number placeholder:', !!window.i18next);- if (window.i18next) {- console.log('Translation for warranties.enter_serial_number:', window.i18next.t('warranties.enter_serial_number'));- }-- // Check if this is the first serial number input- const isFirstInput = container.querySelectorAll('.serial-number-input').length === 0;-- // Append input to the input group- div.appendChild(input);-- // Only add remove button if this is not the first input- if (!isFirstInput) {- // Create a remove button- const removeButton = document.createElement('button');- removeButton.type = 'button';- removeButton.className = 'btn btn-sm btn-danger remove-serial';- removeButton.innerHTML = '<i class="fas fa-times"></i>';-- // Add event listener to remove button- removeButton.addEventListener('click', function() {- container.removeChild(div);- });-- // Append remove button to the input group- div.appendChild(removeButton);- }-- // Insert the new input group before the add button- const addButton = container.querySelector('.add-serial');- if (addButton) {- container.insertBefore(div, addButton);- } else {- container.appendChild(div);-- // Create and append an add button if it doesn't exist- const addButton = document.createElement('button');- addButton.type = 'button';- addButton.className = 'btn btn-sm btn-secondary add-serial';- addButton.innerHTML = '<i class="fas fa-plus"></i> ' + (window.i18next ? window.i18next.t('warranties.add_serial_number') : 'Add Serial Number');- console.log('i18next available in addSerialNumberInput:', !!window.i18next);- if (window.i18next) {- console.log('Translation for warranties.add_serial_number:', window.i18next.t('warranties.add_serial_number'));- }-- addButton.addEventListener('click', function() {- addSerialNumberInput(container);- });-- container.appendChild(addButton);- }-}+// Serial numbers functionality moved to js/components/serialNumbers.js// Functionsfunction showLoading() {+ if (window.components?.ui?.showLoading) {+ window.components.ui.showLoading();+ return;+ }let localLoadingContainer = window.loadingContainer || document.getElementById('loadingContainer');if (localLoadingContainer) {localLoadingContainer.classList.add('active');@@ -1856,6 +1103,10 @@ function showLoading() {}function hideLoading() {+ if (window.components?.ui?.hideLoading) {+ window.components.ui.hideLoading();+ return;+ }let localLoadingContainer = window.loadingContainer || document.getElementById('loadingContainer');if (localLoadingContainer) {localLoadingContainer.classList.remove('active');@@ -1866,6 +1117,9 @@ function hideLoading() {}function showToast(message, type = 'info', duration = 5000) {+ if (window.components?.ui?.showToast) {+ return window.components.ui.showToast(message, type, duration);+ }// Check if a toast with the same message and type already existsconst existingToasts = document.querySelectorAll(`.toast.toast-${type}`);for (let i = 0; i < existingToasts.length; i++) {@@ -2107,6 +1361,9 @@ function processAllWarranties() {}async function loadWarranties(isAuthenticated) { // Added isAuthenticated parameter+ if (window.warrantyListController && typeof window.warrantyListController.loadWarranties === 'function') {+ return window.warrantyListController.loadWarranties(isAuthenticated);+ }// +++ REMOVED: Ensure Preferences are loaded FIRST (Now handled by authStateReady) +++// await loadAndApplyUserPreferences();// +++ Preferences Loaded +++@@ -2276,6 +1533,21 @@ async function loadWarranties(isAuthenticated) { // Added isAuthenticated parameconsole.log('[DEBUG] Total warranties loaded:', warranties.length);console.log('[DEBUG] Warranty IDs loaded:', warranties.map(w => w.id));+ // Sync with store for modular components (notes, claims, etc.)+ if (window.store?.setWarranties) {+ window.store.setWarranties(warranties, {+ warrantiesLoaded: true,+ lastLoadedArchived: isArchivedView,+ lastLoadedIncludesArchived: lastLoadedIncludesArchived+ });+ console.log('[DEBUG] Synced warranties to store:', warranties.length);+ }++ // Preload images immediately so they're ready when cards render+ if (typeof window.preloadWarrantyImages === 'function') {+ window.preloadWarrantyImages(warranties).catch(() => {});+ }+// Set flag to indicate warranties have been loaded from APIwarrantiesLoaded = true;@@ -2303,6 +1575,17 @@ async function loadWarranties(isAuthenticated) { // Added isAuthenticated parame}function renderEmptyState(message = 'No warranties yet. Add your first warranty to get started.') {+ if (window.components?.ui?.renderEmptyState) {+ const container = warrantiesList || document.getElementById('warrantiesList');+ if (container) {+ window.components.ui.renderEmptyState(container, message);+ return;+ }+ }+ if (!warrantiesList) {+ console.warn('renderEmptyState: warrantiesList element not found. Aborting render. This might be normal if not on the main warranties page.');+ return;+ }warrantiesList.innerHTML = `<div class="empty-state"><i class="fas fa-box-open"></i>@@ -2312,136 +1595,15 @@ function renderEmptyState(message = 'No warranties yet. Add your first warranty`;}-function formatDate(date) {- // Input 'date' should now be a Date object created by processWarrantyData (or null)- if (!date || !(date instanceof Date) || isNaN(date.getTime())) {- return 'N/A';- }-- // Get the user's preferred format from localStorage, default to MDY- const formatPreference = localStorage.getItem('dateFormat') || 'MDY';-- // Manually extract UTC components to avoid timezone discrepancies- const year = date.getUTCFullYear();- const monthIndex = date.getUTCMonth(); // 0-indexed for month names array- const day = date.getUTCDate();-- // Padded numeric values- const monthPadded = (monthIndex + 1).toString().padStart(2, '0');- const dayPadded = day.toString().padStart(2, '0');-- // Abbreviated month names- const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];- const monthAbbr = monthNames[monthIndex];-- switch (formatPreference) {- case 'DMY':- return `${dayPadded}/${monthPadded}/${year}`;- case 'YMD':- return `${year}-${monthPadded}-${dayPadded}`;- case 'MDY_WORDS': // Added- return `${monthAbbr} ${day}, ${year}`;- case 'DMY_WORDS': // Added- return `${day} ${monthAbbr} ${year}`;- case 'YMD_WORDS': // Added- return `${year} ${monthAbbr} ${day}`;- case 'MDY':- default:- return `${monthPadded}/${dayPadded}/${year}`;- }-}--function formatDateYYYYMMDD(date) {- if (!date || !(date instanceof Date) || isNaN(date.getTime())) {- return 'N/A';- }-- const year = date.getUTCFullYear();- const month = String(date.getUTCMonth() + 1).padStart(2, '0');- const day = String(date.getUTCDate()).padStart(2, '0');-- return `${year}-${month}-${day}`;-}--/**- * Calculate the age of a product from purchase date to now- * @param {string|Date} purchaseDate - The purchase date- * @returns {string} - Formatted age string (e.g., "2 years, 3 months", "6 months", "15 days")- */-function calculateProductAge(purchaseDate) {- if (!purchaseDate) return 'Unknown';-- const purchase = new Date(purchaseDate);- const now = new Date();-- if (isNaN(purchase.getTime()) || purchase > now) {- return 'Unknown';- }-- // Calculate the difference- let years = now.getFullYear() - purchase.getFullYear();- let months = now.getMonth() - purchase.getMonth();- let days = now.getDate() - purchase.getDate();-- // Adjust for negative days- if (days < 0) {- months--;- const lastMonth = new Date(now.getFullYear(), now.getMonth(), 0);- days += lastMonth.getDate();- }-- // Adjust for negative months- if (months < 0) {- years--;- months += 12;- }-- // Format the result- const parts = [];- if (years > 0) {- const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;- parts.push(`${years} ${yearText}`);- }- if (months > 0) {- const monthText = window.i18next ? window.i18next.t('warranties.month', {count: months}) : `month${months !== 1 ? 's' : ''}`;- parts.push(`${months} ${monthText}`);- }- if (days > 0 && years === 0) { // Only show days if less than a year old- const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;- parts.push(`${days} ${dayText}`);- }-- if (parts.length === 0) {- return 'Today'; // Purchased today- }-- return parts.join(', ');-}--/**- * Calculate the age of a product in days for sorting purposes- * @param {string|Date} purchaseDate - The purchase date- * @returns {number} - Age in days (0 if invalid date)- */-function calculateProductAgeInDays(purchaseDate) {- if (!purchaseDate) return 0;-- const purchase = new Date(purchaseDate);- const now = new Date();-- if (isNaN(purchase.getTime()) || purchase > now) {- return 0;- }-- // Calculate difference in milliseconds and convert to days- const diffTime = now.getTime() - purchase.getTime();- const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));-- return diffDays;-}+// Date utility functions moved to js/lib/dates.js+// Note: The script.js versions had date format preferences (DMY, MDY, etc.)+// Consider adding these features to lib/dates.js if neededasync function renderWarranties(warrantiesToRender) {+ if (window.components?.warrantyRenderer?.renderWarrantiesList) {+ window.components.warrantyRenderer.renderWarrantiesList(warrantiesToRender);+ return;+ }console.log('renderWarranties called with:', warrantiesToRender);// Guard clause: If the main warrantiesList element doesn't exist on the current page, exit.@@ -3053,6 +2215,9 @@ function filterWarranties() {}function applyFilters() {+ if (window.warrantyListController && typeof window.warrantyListController.applyFilters === 'function') {+ return window.warrantyListController.applyFilters();+ }console.log('[FILTER DEBUG] Applying filters with:', currentFilters);console.log('[FILTER DEBUG] Total warranties before filtering:', warranties.length);@@ -3138,6 +2303,9 @@ function applyFilters() {// --- Persist and restore filters/sort ---async function saveFilterPreferences(saveToApi = true) {+ if (window.warrantyListController && typeof window.warrantyListController.saveFilterPreferences === 'function') {+ return window.warrantyListController.saveFilterPreferences(saveToApi);+ }try {const prefix = getPreferenceKeyPrefix();const filtersToSave = {@@ -3183,6 +2351,9 @@ async function saveFilterPreferences(saveToApi = true) {// Deprecated: Sort preference is now saved as part of saveFilterPreferencesfunction loadFilterAndSortPreferences() {+ if (window.warrantyListController && typeof window.warrantyListController.loadFilterAndSortPreferences === 'function') {+ return window.warrantyListController.loadFilterAndSortPreferences();+ }try {const prefix = getPreferenceKeyPrefix();const savedFiltersRaw = localStorage.getItem(`${prefix}warrantyFilters`);@@ -3217,6 +2388,9 @@ function loadFilterAndSortPreferences() {}async function openEditModal(warranty) {+ if (window.components?.editModal?.openEditModal) {+ return window.components.editModal.openEditModal(warranty);+ }// Close any existing modals firstcloseModals();@@ -3775,6 +2949,10 @@ async function openEditModal(warranty) {function openDeleteModal(warrantyId, productName) {currentWarrantyId = warrantyId;+ // Sync with store for modular components+ if (window.store?.setCurrentWarrantyId) {+ window.store.setCurrentWarrantyId(warrantyId);+ }const deleteProductNameElement = document.getElementById('deleteProductName');if (deleteProductNameElement) {@@ -3790,6 +2968,10 @@ function openDeleteModal(warrantyId, productName) {// Open Archive confirmation modalfunction openArchiveModal(warrantyId, productName) {currentWarrantyId = warrantyId;+ // Sync with store for modular components+ if (window.store?.setCurrentWarrantyId) {+ window.store.setCurrentWarrantyId(warrantyId);+ }const archiveProductNameElement = document.getElementById('archiveProductName');if (archiveProductNameElement) {archiveProductNameElement.textContent = productName || '';@@ -4223,16 +3405,19 @@ document.addEventListener('DOMContentLoaded', function() {});// ====== WARRANTY CLAIMS FUNCTIONALITY ======+// Claims functionality moved to js/components/claims.js+// Legacy fallback functions below delegate to the modular version if available-// Global variables for claims+// Global variables for claims (kept for backward compatibility)let currentClaimsWarrantyId = null;let currentClaims = [];-let currentClaimsCanEdit = false; // Track if current user can edit the warranty being viewed+let currentClaimsCanEdit = false;-/**- * Initialize claims event listeners- */function initClaimsEventListeners() {+ if (window.components?.claims?.init) {+ window.components.claims.init();+ return;+ }// Event delegation for claims linksif (warrantiesList) {warrantiesList.addEventListener('click', (e) => {@@ -4301,6 +3486,9 @@ function initClaimsEventListeners() {* Open the claims modal for a specific warranty*/async function openClaimsModal(warrantyId) {+ if (window.components?.claims?.openClaimsModal) {+ return window.components.claims.openClaimsModal(warrantyId);+ }try {currentClaimsWarrantyId = warrantyId;@@ -4360,6 +3548,10 @@ async function openClaimsModal(warrantyId) {* Load claims for a warranty*/async function loadClaims(warrantyId) {+ if (window.components?.claims) {+ console.warn('loadClaims legacy function invoked while claims component is active.');+ return;+ }try {// Show loadingif (claimsListBody) {@@ -4402,6 +3594,9 @@ async function loadClaims(warrantyId) {* Render claims list*/function renderClaims() {+ if (window.components?.claims) {+ return;+ }if (!claimsListBody) return;if (currentClaims.length === 0) {@@ -4484,6 +3679,9 @@ function renderClaims() {* Open claim form modal for adding or editing*/function openClaimFormModal(claim = null) {+ if (window.components?.claims) {+ return;+ }if (!claimFormModal) return;// Update title@@ -4520,6 +3718,9 @@ function openClaimFormModal(claim = null) {* Handle claim form submission*/async function handleClaimFormSubmit(event) {+ if (window.components?.claims) {+ return;+ }event.preventDefault();try {@@ -4578,6 +3779,9 @@ async function handleClaimFormSubmit(event) {* Delete a claim*/async function deleteClaim(claimId) {+ if (window.components?.claims) {+ return;+ }try {const response = await fetch(`/api/warranties/${currentClaimsWarrantyId}/claims/${claimId}`, {method: 'DELETE',@@ -4607,6 +3811,9 @@ async function deleteClaim(claimId) {* Close claims modal*/function closeClaimsModal() {+ if (window.components?.claims) {+ return window.components.claims.closeClaimsModal();+ }if (claimsModal) {claimsModal.classList.remove('active');}@@ -4619,6 +3826,9 @@ function closeClaimsModal() {* Close claim form modal*/function closeClaimFormModal() {+ if (window.components?.claims) {+ return window.components.claims.closeClaimFormModal();+ }if (claimFormModal) {claimFormModal.classList.remove('active');}@@ -4960,10 +4170,8 @@ function initWarrantyForm() {// Initialize tag functionalityinitTagFunctionality();- // Form submission- if (warrantyForm) {- warrantyForm.addEventListener('submit', handleFormSubmit); // Use renamed handler- }+ // Form submission - REMOVED: now handled by js/components/addWarrantyForm.js+ // The modular component handles form submission to prevent duplicate submissions// Initialize lifetime checkbox listenerif (isLifetimeCheckbox && warrantyDurationFields) { // Check for new container@@ -5070,6 +4278,9 @@ async function loadTags(force = false) {// Render the tags dropdown listfunction renderTagsList(searchTerm = '') {+ if (window.components?.tagManager?.renderTagsList) {+ return window.components.tagManager.renderTagsList(searchTerm);+ }if (!tagsList) return;tagsList.innerHTML = '';@@ -5136,6 +4347,9 @@ function renderTagsList(searchTerm = '') {// Update renderEditTagsList to add new tag to editSelectedTags after creationfunction renderEditTagsList(searchTerm = '') {+ if (window.components?.tagManager?.renderEditTagsList) {+ return window.components.tagManager.renderEditTagsList(searchTerm);+ }const editTagsList = document.getElementById('editTagsList');if (!editTagsList) return;editTagsList.innerHTML = '';@@ -5201,6 +4415,9 @@ function renderEditTagsList(searchTerm = '') {// Render the selected tagsfunction renderSelectedTags() {+ if (window.components?.tagManager?.renderSelectedTags) {+ return window.components.tagManager.renderSelectedTags();+ }if (!selectedTagsContainer) return;selectedTagsContainer.innerHTML = '';@@ -5242,6 +4459,9 @@ function renderSelectedTags() {// Helper function to render the edit selected tagsfunction renderEditSelectedTags() {+ if (window.components?.tagManager?.renderEditSelectedTags) {+ return window.components.tagManager.renderEditSelectedTags();+ }const editSelectedTagsContainer = document.getElementById('editSelectedTags');if (!editSelectedTagsContainer) return;@@ -5288,7 +4508,7 @@ function renderEditSelectedTags() {}// Update createTag to return a Promise-function createTag(name) {+function createTag(name, color) {return new Promise((resolve, reject) => {// Enhanced auth manager availability checkif (!window.auth) {@@ -5313,8 +4533,9 @@ function createTag(name) {reject(new Error('No authentication token found. Please try logging in again.'));return;}- // Generate a random color for the tag- const color = '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');+ const chosenColor = color && typeof color === 'string' && color.startsWith('#')+ ? color+ : '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');fetch('/api/tags', {method: 'POST',headers: {@@ -5323,7 +4544,7 @@ function createTag(name) {},body: JSON.stringify({name: name,- color: color+ color: chosenColor})}).then(response => {@@ -5722,6 +4943,9 @@ function deleteTag(id) {// Set up event listeners for UI controlsfunction setupUIEventListeners() {+ if (window.warrantyListController && typeof window.warrantyListController.initEventListeners === 'function') {+ return window.warrantyListController.initEventListeners();+ }// --- Global Manage Tags Button ---const globalManageTagsBtn = document.getElementById('globalManageTagsBtn');if (globalManageTagsBtn) {@@ -5988,6 +5212,10 @@ function setupUIEventListeners() {// Function to show loading spinnerfunction showLoadingSpinner() {+ if (window.components?.ui?.showLoadingSpinner) {+ window.components.ui.showLoadingSpinner();+ return;+ }if (loadingContainer) {loadingContainer.style.display = 'flex';}@@ -5995,6 +5223,10 @@ function showLoadingSpinner() {// Function to hide loading spinnerfunction hideLoadingSpinner() {+ if (window.components?.ui?.hideLoadingSpinner) {+ window.components.ui.hideLoadingSpinner();+ return;+ }if (loadingContainer) {loadingContainer.style.display = 'none';}@@ -6207,6 +5439,9 @@ function deleteWarranty() {// Save warranty updatesfunction saveWarranty() {+ if (window.components?.editModal?.saveWarranty) {+ return window.components.editModal.saveWarranty();+ }console.log("[script.js] CORE saveWarranty (original from script.js) EXECUTING.");if (!currentWarrantyId) {showToast(window.t('messages.no_warranty_selected_for_update'), 'error');@@ -6535,6 +5770,9 @@ function saveWarranty() {// Function to populate tag filter dropdownfunction populateTagFilter() {+ if (window.warrantyListController && typeof window.warrantyListController.populateTagFilter === 'function') {+ return window.warrantyListController.populateTagFilter();+ }const tagFilter = document.getElementById('tagFilter');if (!tagFilter) return;@@ -6574,6 +5812,9 @@ function populateTagFilter() {// Function to populate vendor filter dropdownfunction populateVendorFilter() {+ if (window.warrantyListController && typeof window.warrantyListController.populateVendorFilter === 'function') {+ return window.warrantyListController.populateVendorFilter();+ }const vendorFilterElement = document.getElementById('vendorFilter');if (!vendorFilterElement) return;@@ -6609,6 +5850,9 @@ function populateVendorFilter() {// Function to populate warranty type filter dropdownfunction populateWarrantyTypeFilter() {+ if (window.warrantyListController && typeof window.warrantyListController.populateWarrantyTypeFilter === 'function') {+ return window.warrantyListController.populateWarrantyTypeFilter();+ }const warrantyTypeFilterElement = document.getElementById('warrantyTypeFilter');if (!warrantyTypeFilterElement) return;@@ -7052,6 +6296,9 @@ if (!document.getElementById('notesModal')) {// Add event listener for Edit Warranty buttondocument.getElementById('editWarrantyBtn').addEventListener('click', async () => {+ if (window.components?.notes?.showNotesModal) {+ return;+ }// Find the current warranty data from the global arrayconst currentWarranty = warranties.find(w => w.id === notesModalWarrantyId);if (currentWarranty) {@@ -7071,6 +6318,9 @@ let notesModalWarrantyId = null;let notesModalWarrantyObj = null;function showNotesModal(notes, warrantyOrId = null) {+ if (window.components?.notes?.showNotesModal) {+ return window.components.notes.showNotesModal(notes, warrantyOrId);+ }const notesModal = document.getElementById('notesModal');const notesModalContent = document.getElementById('notesModalContent');const notesModalTextarea = document.getElementById('notesModalTextarea');@@ -7599,6 +6849,12 @@ window.addEventListener('storage', function(e) {processAllWarranties();}}+ if (e.key === `${prefix}expiringSoonDays`) {+ const days = parseInt(e.newValue, 10);+ if (!Number.isNaN(days) && window.store?.setExpiringSoonDays) {+ window.store.setExpiringSoonDays(days);+ }+ }});// +++ NEW FUNCTION TO LOAD PREFS AND SAVE TO LOCALSTORAGE +++@@ -7614,6 +6870,11 @@ async function loadAndApplyUserPreferences(isAuthenticated) { // Added isAuthent}console.log(`[Prefs Loader] Attempting to load preferences using prefix: ${prefix}, isAuthenticated: ${isAuthenticated}`);+ const storedExpiring = parseInt(localStorage.getItem(`${prefix}expiringSoonDays`), 10);+ if (!Number.isNaN(storedExpiring) && window.store?.setExpiringSoonDays) {+ window.store.setExpiringSoonDays(storedExpiring);+ }+if (isAuthenticated && window.auth) { // Use passed isAuthenticated and check if window.auth existsconst token = window.auth.getToken(); // Still need token for the API callif (!token) {@@ -7658,13 +6919,16 @@ async function loadAndApplyUserPreferences(isAuthenticated) { // Added isAuthentlocalStorage.setItem(`${prefix}warrantyFilters`, JSON.stringify(apiPrefs.saved_filters));console.log(`[Prefs Loader] Saved ${prefix}warrantyFilters:`, apiPrefs.saved_filters);}- if (apiPrefs.expiring_soon_days !== undefined) {- localStorage.setItem(`${prefix}expiringSoonDays`, apiPrefs.expiring_soon_days);- // Also update the global variable used by processWarrantyData- expiringSoonDays = apiPrefs.expiring_soon_days;- console.log(`[Prefs Loader] Saved ${prefix}expiringSoonDays: ${apiPrefs.expiring_soon_days}`);- console.log(`[Prefs Loader] Updated global expiringSoonDays variable to: ${expiringSoonDays}`);- }+ if (apiPrefs.expiring_soon_days !== undefined) {+ localStorage.setItem(`${prefix}expiringSoonDays`, apiPrefs.expiring_soon_days);+ // Also update the global variable used by processWarrantyData+ expiringSoonDays = apiPrefs.expiring_soon_days;+ console.log(`[Prefs Loader] Saved ${prefix}expiringSoonDays: ${apiPrefs.expiring_soon_days}`);+ console.log(`[Prefs Loader] Updated global expiringSoonDays variable to: ${expiringSoonDays}`);+ if (window.store?.setExpiringSoonDays) {+ window.store.setExpiringSoonDays(expiringSoonDays);+ }+ }if (apiPrefs.date_format) {localStorage.setItem('dateFormat', apiPrefs.date_format);console.log(`[Prefs Loader] Saved dateFormat: ${apiPrefs.date_format}`);@@ -7824,9 +7088,15 @@ function calculateDurationFromDates(startDate, endDate) {}/**- * Load secure images with authentication+ * Load secure images with authentication (parallel loading for better performance)+ * Delegates to paperless.js module if available (which has caching support)*/async function loadSecureImages() {+ // Use the modular version with caching if available+ if (window.components?.paperless?.loadSecureImages) {+ return window.components.paperless.loadSecureImages();+ }+const token = localStorage.getItem('auth_token');if (!token) {console.log('[DEBUG] No auth token available for secure image loading');@@ -7837,18 +7107,23 @@ async function loadSecureImages() {const secureImages = document.querySelectorAll('img.secure-image[data-secure-src]');console.log(`[DEBUG] Found ${secureImages.length} secure images to load/refresh`);- for (const img of secureImages) {+ // Load all images in parallel for better performance+ const loadPromises = Array.from(secureImages).map(async (img) => {try {- const secureUrl = img.getAttribute('data-secure-src');- console.log(`[DEBUG] Loading secure image: ${secureUrl}`);-- // Clean up existing blob URL if presentconst existingBlobUrl = img.getAttribute('data-blob-url');+ // Skip if already loaded and has valid blob URL+ if (img.classList.contains('loaded') && existingBlobUrl && img.src.startsWith('blob:')) {+ return;+ }+ // Clean up existing blob URL if presentif (existingBlobUrl) {URL.revokeObjectURL(existingBlobUrl);img.removeAttribute('data-blob-url');+ img.classList.remove('loaded');}+ const secureUrl = img.getAttribute('data-secure-src');+const response = await fetch(secureUrl, {headers: {'Authorization': `Bearer ${token}`@@ -7860,13 +7135,10 @@ async function loadSecureImages() {const blobUrl = URL.createObjectURL(blob);img.src = blobUrl;- // Clean up blob URL when image is removed from DOM- img.addEventListener('load', () => {- console.log(`[DEBUG] Secure image loaded successfully: ${secureUrl}`);- }, { once: true });-// Store blob URL for cleanupimg.setAttribute('data-blob-url', blobUrl);+ // Mark as loaded to stop shimmer animation+ img.classList.add('loaded');} else {console.error(`[DEBUG] Failed to load secure image: ${secureUrl}, status: ${response.status}`);img.style.display = 'none';@@ -7875,7 +7147,9 @@ async function loadSecureImages() {console.error(`[DEBUG] Error loading secure image:`, error);img.style.display = 'none';}- }+ });++ await Promise.all(loadPromises);}// ============================================================================@@ -7982,9 +7256,12 @@ function getStorageOption(documentType, isEdit = false) {return 'local'; // Force local storage for productPhoto and otherDocument}- const prefix = isEdit ? 'edit' : '';+ // For add form: invoiceStorage, manualStorage (lowercase)+ // For edit form: editInvoiceStorage, editManualStorage (capitalize after 'edit')const capitalizedType = documentType.charAt(0).toUpperCase() + documentType.slice(1);- const name = `${prefix}${capitalizedType}Storage`;+ const name = isEdit+ ? `edit${capitalizedType}Storage`+ : `${documentType}Storage`;const radio = document.querySelector(`input[name="${name}"]:checked`);return radio ? radio.value : 'local';}diff --git a/frontend/style.css b/frontend/style.cssindex 4c14ae6..8984a6a 100644--- a/frontend/style.css+++ b/frontend/style.css@@ -4744,6 +4744,20 @@ html.dark-mode .warracker-footer a:hover {background-color: #f5f5f5;}+/* Secure image - hidden until loaded to prevent flicker */+.product-photo-thumbnail img.secure-image {+ opacity: 0;+ transition: opacity 0.15s ease-in;+}++.product-photo-thumbnail img.secure-image.loaded {+ opacity: 1;+}++:root[data-theme="dark"] .product-photo-thumbnail img {+ background-color: #3a3a3a;+}+.product-photo-thumbnail img:hover {transform: scale(1.05);box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);diff --git a/frontend/version-checker.js b/frontend/version-checker.jsindex 3be2504..b1e5b78 100644--- a/frontend/version-checker.js+++ b/frontend/version-checker.js@@ -1,6 +1,6 @@// Version checker for Warrackerdocument.addEventListener('DOMContentLoaded', () => {- const currentVersion = '1.0.2'; // Current version of the application+ const currentVersion = '1.0.3'; // Current version of the applicationconst updateStatus = document.getElementById('updateStatus');const updateLink = document.getElementById('updateLink');const versionDisplay = document.getElementById('versionDisplay');diff --git a/locales/en/translation.json b/locales/en/translation.jsonindex 7156a20..a100f8a 100644--- a/locales/en/translation.json+++ b/locales/en/translation.json@@ -214,7 +214,11 @@"add_any_notes_placeholder": "Add any notes about this warranty...","add_serial_number": "Add another serial number","model_number_optional": "Model Number (Optional)",- "model_number_placeholder": "e.g. SM-G991U1"+ "model_number_placeholder": "e.g. SM-G991U1",+ "archived": "Archived",+ "or_link_to_invoice_url": "Or link to invoice URL",+ "or_link_to_manual_url": "Or link to manual URL",+ "or_link_to_files_url": "Or link to files URL"},"settings": {"title": "Warracker - Settings",@@ -312,6 +316,8 @@"issuer_url_desc": "The base URL of your OIDC provider.","scope_desc": "Space-separated OIDC scopes.","oidc_restart_message": "Application restart is required for OIDC settings to take full effect.",+ "oidc_admin_group": "OIDC Admin Group",+ "oidc_admin_desc": "Group that is given admin privileges. Leave blank to disable.","api_token": "API Token","view_documents": "View Documents in Warracker","connection_testing": "Connection Testing",@@ -398,7 +404,8 @@"download": "Download","manage_tags": "Manage Tags","close": "Close",- "save_changes": "Save Changes"+ "save_changes": "Save Changes",+ "data": "Data"},"filters": {"all_status": "All Status",@@ -417,7 +424,12 @@"vendor": "Vendor","warranty_type": "Warranty Type","view": "View",- "scope": "Scope"+ "scope": "Scope",+ "filter": "Filter",+ "filter_by": "Filter By",+ "clear": "Clear",+ "apply": "Apply",+ "sort": "Sort"},"messages": {"success": "Success",