🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Add photo by URL (#207), Duplicate warranty, Purchase Price tooltip (#223); fix 'undefined' labels during translation load
Omega (QA)947cdba17647
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ec3fe1c..84217d5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,15 @@## 1.0.5 - Unreleased+- **Product photo by URL (#207):** the add and edit forms now accept a photo URL next to the upload and camera options. The server downloads the image once, checks that it really is an image (PNG, JPG, WebP or GIF), and stores it like an uploaded photo, so cards and thumbnails work exactly as with an upload. Fetches are guarded: public http(s) addresses only, a size cap, a timeout, and a redirect limit. An uploaded file still wins when both are given.+ - _Files: `backend/warranties_routes.py`, `frontend/index.html`, `frontend/status.html`, `frontend/js/components/addWarrantyForm.js`, `frontend/js/components/editModal.js`, `frontend/style.css`, `locales/en/translation.json`, `tests/test_photo_url.py`_+- **Duplicate warranty action:** every warranty card gains a Duplicate button that opens the Add Warranty form prefilled with the original's details (name, purchase date or duration, price, vendor, model, serial numbers, warranty type, notes and tags), ready to adjust and save as a new warranty. It covers the common case behind the overlapping-warranties requests: a manufacturer warranty and an extended warranty on the same product no longer need everything retyped. Photos, documents and claims are not copied.+ - _Files: `frontend/js/components/warrantyRenderer.js`, `frontend/js/components/addWarrantyForm.js`, `frontend/js/controllers/warrantyListController.js`, `locales/en/translation.json`_+- **Purchase Price tooltip (#223):** the Purchase Price label in the add and edit forms now carries a help icon explaining that the field is the price paid for the product, not the cost of the warranty, and that a warranty included with a product simply takes the product's price. Translated in all 20 locales.+ - _Files: `frontend/index.html`, `frontend/status.html`, `frontend/style.css`, `locales/en/translation.json`_+- **Form labels no longer show "undefined" while translations load:** labels built in the first moments after page load could render the literal text "undefined" (most visibly the serial number placeholder and its add button, when the Add Warranty form was opened immediately). Every translation lookup in the frontend now falls back to the English string when the translation is not ready yet, across the form, list and component scripts.+ - _Files: `frontend/script.js`, `frontend/js/components/addWarrantyForm.js`, `frontend/js/components/serialNumbers.js`, `frontend/js/components/warrantyActions.js`, `frontend/js/components/editModal.js`, `frontend/js/components/formTabs.js`, `frontend/js/components/importExport.js`, `frontend/js/components/notes.js`, `frontend/js/controllers/warrantyListController.js`_+- **Dependency and runtime updates:** gunicorn 24.1.1 → 26.2.0 and gevent 24.11.1 → 26.9.0 (the new gevent ships Python 3.15 wheels, ending the from-source compile that slowed multi-arch Docker builds), python-dateutil 2.9.0 → 3.0.0, setuptools 84.0.0 → 84.2.1, and the Python 3.15 slim base image digest refreshed.- _Files: `Dockerfile`, `backend/requirements.txt`, `.github/workflows/renovate.yml`_diff --git a/backend/warranties_routes.py b/backend/warranties_routes.pyindex a8c6d91..f9bd95b 100644--- a/backend/warranties_routes.py+++ b/backend/warranties_routes.py@@ -12,6 +12,10 @@ from dateutil.parser import parse as date_parseimport mimetypesfrom flask import Responseimport uuid+import socket+import ipaddress+import urllib.parse+import requestsfrom werkzeug.exceptions import RequestEntityTooLarge# Add pytz import for timezone functionality@@ -48,6 +52,84 @@ def unique_upload_filename(original_name, infix=""):stamp = datetime.now().strftime('%Y%m%d%H%M%S')return f"{stamp}_{uuid.uuid4().hex[:8]}_{infix}{safe}"+def _photo_url_host_is_public(hostname):+ """SSRF guard for photo-by-URL: every address the host resolves to must+ be a public (global) IP. Skipped only when the deployment explicitly sets+ ALLOW_PRIVATE_PHOTO_URLS (used by the test suite with a local server)."""+ if current_app.config.get('ALLOW_PRIVATE_PHOTO_URLS'):+ return True+ try:+ infos = socket.getaddrinfo(hostname, None)+ except Exception:+ return False+ if not infos:+ return False+ for info in infos:+ try:+ addr = ipaddress.ip_address(info[4][0])+ except ValueError:+ return False+ if not addr.is_global:+ return False+ return True++def _detect_image_extension(data):+ """Magic-byte image sniffing (the upload path checks extensions only;+ a fetched file has no trustworthy name, so check the content)."""+ if data[:8] == b'\x89PNG\r\n\x1a\n':+ return '.png'+ if data[:3] == b'\xff\xd8\xff':+ return '.jpg'+ if data[:6] in (b'GIF87a', b'GIF89a'):+ return '.gif'+ if len(data) >= 12 and data[:4] == b'RIFF' and data[8:12] == b'WEBP':+ return '.webp'+ return None++def download_product_photo(url):+ """Fetch an image from a user-supplied URL for use as a product photo.+ Returns (bytes, extension). Raises ValueError with a user-facing message."""+ current = (url or '').strip()+ if not current:+ raise ValueError("Photo URL is empty.")+ max_bytes = current_app.config.get('MAX_CONTENT_LENGTH') or 32 * 1024 * 1024+ for _ in range(4):+ parsed = urllib.parse.urlparse(current)+ if parsed.scheme not in ('http', 'https') or not parsed.hostname:+ raise ValueError("Photo URL must be a valid http(s) URL.")+ if not _photo_url_host_is_public(parsed.hostname):+ raise ValueError("Photo URL must point to a public address.")+ try:+ resp = requests.get(current, timeout=10, stream=True, allow_redirects=False,+ headers={'User-Agent': 'Warracker photo fetch'})+ except requests.RequestException:+ raise ValueError("Could not fetch the photo URL.")+ if resp.status_code in (301, 302, 303, 307, 308):+ location = resp.headers.get('Location')+ resp.close()+ if not location:+ raise ValueError("Could not fetch the photo URL.")+ current = urllib.parse.urljoin(current, location)+ continue+ if resp.status_code != 200:+ resp.close()+ raise ValueError("Could not fetch the photo URL.")+ chunks, total = [], 0+ try:+ for chunk in resp.iter_content(chunk_size=65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError("Photo URL file is too large.")+ chunks.append(chunk)+ finally:+ resp.close()+ data = b''.join(chunks)+ ext = _detect_image_extension(data)+ if not ext:+ raise ValueError("Product photo must be an image file (PNG, JPG, JPEG, WEBP, GIF)")+ return data, ext+ raise ValueError("Too many redirects fetching the photo URL.")+# Map of currency symbols to ISO codes (mirrors frontend js/lib/currency.js).# Used to resolve a user's preferred currency symbol to a code for new warranties.SYMBOL_TO_CURRENCY_CODE = {@@ -497,6 +579,26 @@ def add_warranty():elif paperless_photo_id:logger.info(f"Product photo stored in Paperless-ngx with ID: {paperless_photo_id}")+ # Product photo by URL (#207): only when no file was uploaded and the+ # photo is not coming from Paperless. The image is downloaded once and+ # stored like an upload, so every later view uses the normal path.+ product_photo_url = (request.form.get('product_photo_url') or '').strip()+ if not db_product_photo_path and not paperless_photo_id and product_photo_url:+ try:+ photo_bytes, photo_ext = download_product_photo(product_photo_url)+ except ValueError as e:+ return jsonify({"error": str(e)}), 400+ filename = unique_upload_filename(f"downloaded{photo_ext}", "photo_")+ product_photo_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)+ try:+ with open(product_photo_path_on_disk, 'wb') as fh:+ fh.write(photo_bytes)+ db_product_photo_path = os.path.join('uploads', filename)+ logger.info(f"Successfully saved product_photo from URL: {db_product_photo_path}")+ except Exception as e:+ logger.error(f"Error saving product_photo from URL {filename}: {e}")+ return jsonify({"error": f"Failed to save product_photo: {str(e)}"}), 500+# Save to database@@ -1157,6 +1259,36 @@ def update_warranty(warranty_id):logger.error(f"Error deleting product_photo (delete request): {e}")db_product_photo_path = None # Set to None to clear in DB+ # Product photo by URL (#207): replace the photo with a downloaded+ # image when no file was uploaded and no delete was requested.+ product_photo_url = (request.form.get('product_photo_url') or '').strip()+ if (not db_product_photo_path and not paperless_photo_id and product_photo_url+ and request.form.get('delete_product_photo', 'false').lower() != 'true'):+ try:+ photo_bytes, photo_ext = download_product_photo(product_photo_url)+ except ValueError as e:+ return jsonify({"error": str(e)}), 400+ cur.execute('SELECT product_photo_path FROM warranties WHERE id = %s', (warranty_id,))+ old_product_photo_path = cur.fetchone()[0]+ if old_product_photo_path:+ full_path = os.path.join('/data', old_product_photo_path)+ if os.path.exists(full_path):+ try:+ os.remove(full_path)+ logger.info(f"Deleted old product_photo: {full_path}")+ except Exception as e:+ logger.error(f"Error deleting old product_photo: {e}")+ filename = unique_upload_filename(f"downloaded{photo_ext}", "photo_")+ product_photo_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)+ try:+ with open(product_photo_path_on_disk, 'wb') as fh:+ fh.write(photo_bytes)+ db_product_photo_path = os.path.join('uploads', filename)+ logger.info(f"Successfully saved updated product_photo from URL: {db_product_photo_path}")+ except Exception as e:+ logger.error(f"Error saving updated product_photo from URL {filename}: {e}")+ return jsonify({"error": f"Failed to save product_photo: {str(e)}"}), 500+# Prepare update parametersupdate_params = {'product_name': product_name,diff --git a/frontend/about.html b/frontend/about.htmlindex 6adfac6..6b9b0b3 100644--- a/frontend/about.html+++ b/frontend/about.html@@ -14,7 +14,7 @@<link rel="manifest" href="manifest.json"><!-- Stylesheets -->- <link rel="stylesheet" href="style.css?v=20261101001"> <!-- Main stylesheet -->+ <link rel="stylesheet" href="style.css?v=20261101002"> <!-- Main stylesheet --><link rel="stylesheet" href="style.css?v=20250119001"> <!-- Additional styles --><link rel="stylesheet" href="vendor/fontawesome/css/all.min.css?v=20261001001"> <!-- Font Awesome --><link rel="stylesheet" href="header-fix.css?v=20250119001"> <!-- Header specific styles -->diff --git a/frontend/auth-redirect.html b/frontend/auth-redirect.htmlindex 8ce40a2..cf603f4 100644--- a/frontend/auth-redirect.html+++ b/frontend/auth-redirect.html@@ -4,7 +4,7 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Authenticating...</title>- <link rel="stylesheet" href="style.css?v=20261101001">+ <link rel="stylesheet" href="style.css?v=20261101002"><script src="theme-loader.js?v=20250119001"></script><style>body {diff --git a/frontend/index.html b/frontend/index.htmlindex 36b583c..97af4e0 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -22,7 +22,7 @@<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2"><link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png"><link rel="manifest" href="manifest.json">- <link rel="stylesheet" href="style.css?v=20261101001">+ <link rel="stylesheet" href="style.css?v=20261101002"><script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early --><!-- Font Awesome for icons -->@@ -416,6 +416,7 @@<div id="productPhotoPreview" class="photo-preview" style="display: none;"><img id="productPhotoImg" src="" alt="Product Photo Preview" style="max-width: 200px; max-height: 200px; border-radius: 8px; margin-top: 10px;"></div>+ <input type="url" id="productPhotoUrl" name="product_photo_url" class="form-control photo-url-input" data-i18n-placeholder="warranties.photo_url_placeholder" placeholder="Or paste a photo URL"></div><div class="form-group">@@ -530,7 +531,7 @@</select></div><div class="form-group">- <label for="purchasePrice" data-i18n="warranties.purchase_price_optional">Purchase Price (Optional)</label>+ <label for="purchasePrice" class="label-with-help"><span data-i18n="warranties.purchase_price_optional">Purchase Price (Optional)</span> <i class="fas fa-info-circle field-help-icon" data-i18n-title="warranties.purchase_price_tooltip" title="The price you paid for the product itself, not the cost of the warranty. If the warranty was included with the product, enter the product's price."></i></label><div class="price-input-wrapper" id="addPriceInputWrapper"><span class="currency-symbol" id="addCurrencySymbol">$</span><input type="number" id="purchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">@@ -924,7 +925,7 @@</select></div><div class="form-group">- <label for="editPurchasePrice" data-i18n="warranties.purchase_price_optional">Purchase Price (Optional)</label>+ <label for="editPurchasePrice" class="label-with-help"><span data-i18n="warranties.purchase_price_optional">Purchase Price (Optional)</span> <i class="fas fa-info-circle field-help-icon" data-i18n-title="warranties.purchase_price_tooltip" title="The price you paid for the product itself, not the cost of the warranty. If the warranty was included with the product, enter the product's price."></i></label><div class="price-input-wrapper" id="editPriceInputWrapper"><span class="currency-symbol" id="editCurrencySymbol">$</span><input type="number" id="editPurchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">@@ -954,6 +955,7 @@<div id="editProductPhotoPreview" class="photo-preview" style="display: none;"><img id="editProductPhotoImg" src="" alt="Product Photo Preview" style="max-width: 200px; max-height: 200px; border-radius: 8px; margin-top: 10px;"></div>+ <input type="url" id="editProductPhotoUrl" name="product_photo_url" class="form-control photo-url-input" data-i18n-placeholder="warranties.photo_url_placeholder" placeholder="Or paste a photo URL"><div id="currentProductPhoto" class="mt-10"></div><button type="button" id="deleteProductPhotoBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> <span data-i18n="warranties.delete_photo">Delete Photo</span></button>@@ -1334,9 +1336,9 @@<div class="loading-spinner"></div></div>- <script type="module" src="js/index.js?v=20260518004"></script>+ <script type="module" src="js/index.js?v=20261101001"></script><script src="auth.js?v=20250119001"></script>- <script src="script.js?v=20261101002"></script>+ <script src="script.js?v=20261101003"></script><script>// Lightweight UI logic for Filter/Sort popovers (no change to core logic)document.addEventListener('DOMContentLoaded', function () {diff --git a/frontend/js/components/addWarrantyForm.js b/frontend/js/components/addWarrantyForm.jsindex 2555937..79cefe7 100644--- a/frontend/js/components/addWarrantyForm.js+++ b/frontend/js/components/addWarrantyForm.js@@ -46,8 +46,8 @@ const state = {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');+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;@@ -268,10 +268,10 @@ export function validateTab(index) {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.');+ 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.'));+ markInvalid(control, control.validationMessage || ((window.i18next && window.i18next.t('messages.field_is_invalid') || 'This field is invalid.')));}});return isValid;@@ -282,7 +282,7 @@ export function showValidationErrors(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);+ showToast((window.i18next && window.i18next.t('messages.correct_errors_in_tab') || 'Please correct the errors on this tab.'), 'error', 4000);}function handleFormInput(event) {@@ -393,7 +393,7 @@ export function updateSummary() {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';+ state.summary.serialNumbers.textContent = (window.i18next && window.i18next.t('warranties.none') || 'None');}}@@ -403,7 +403,7 @@ export function updateSummary() {const isLifetime = state.isLifetimeCheckbox?.checked;if (state.summary.warrantyDuration) {if (isLifetime) {- setTextContent(state.summary.warrantyDuration, window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime');+ 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;@@ -422,7 +422,7 @@ export function updateSummary() {const warrantyTypeSelect = document.getElementById('warrantyType');const warrantyTypeCustom = document.getElementById('warrantyTypeCustom');- let warrantyTypeText = window.i18next ? window.i18next.t('warranties.not_specified') : 'Not specified';+ 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) {@@ -439,7 +439,7 @@ export function updateSummary() {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';+ state.summary.purchasePrice.textContent = (window.i18next && window.i18next.t('warranties.not_specified') || 'Not specified');}}@@ -458,9 +458,7 @@ function renderSummaryTags() {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';+ state.summary.tags.textContent = (window.i18next && window.i18next.t('tags.no_selected', { defaultValue: 'No tags selected' }) || 'No tags selected');return;}tags.forEach((tag) => {@@ -519,7 +517,7 @@ export async function handleFormSubmit(event) {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');+ 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...');@@ -533,7 +531,7 @@ export async function handleFormSubmit(event) {} catch (error) {hideLoadingSpinner();console.error('[addWarrantyForm] Failed to save warranty', error);- showToast(apiErrorMessage(error, window.i18next ? window.i18next.t('messages.failed_to_add_warranty') : 'Failed to add warranty'), 'error');+ showToast(apiErrorMessage(error, (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');@@ -592,6 +590,85 @@ function closeModal() {resetAddWarrantyWizard();}+export function openDuplicateForm(warranty) {+ if (!warranty) return;+ resetAddWarrantyWizard();+ updateCurrencyDefaults();+ const setValue = (id, value) => {+ const el = document.getElementById(id);+ if (el) el.value = value ?? '';+ };+ setValue('productName', warranty.product_name || '');+ setValue('productUrl', warranty.product_url || '');+ setValue('modelNumber', warranty.model_number || '');+ setValue('vendor', warranty.vendor || '');+ setValue('purchasePrice', warranty.purchase_price || '');+ if (warranty.currency) setValue('currency', warranty.currency);+ setValue('purchaseDate', warranty.purchase_date ? String(warranty.purchase_date).split('T')[0] : '');+ const serials = Array.isArray(warranty.serial_numbers)+ ? warranty.serial_numbers+ .map((sn) => {+ if (!sn) return '';+ if (typeof sn === 'object' && sn.serial_number) return sn.serial_number;+ return String(sn);+ })+ .filter((value) => value && value.trim())+ : [];+ if (state.serialContainer && serials.length) {+ state.serialContainer.innerHTML = '';+ serials.forEach((serial) => addSerialNumberInput(serial));+ }+ const typeSelect = document.getElementById('warrantyType');+ const customInput = document.getElementById('warrantyTypeCustom');+ 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 || '';+ }+ }+ }+ if (state.isLifetimeCheckbox) state.isLifetimeCheckbox.checked = Boolean(warranty.is_lifetime);+ const years = warranty.warranty_duration_years || 0;+ const months = warranty.warranty_duration_months || 0;+ const days = warranty.warranty_duration_days || 0;+ const useExact = !warranty.is_lifetime && (warranty.original_input_method === 'exact_date'+ || (years === 0 && months === 0 && days === 0 && Boolean(warranty.expiration_date)));+ if (state.durationMethodRadio) state.durationMethodRadio.checked = !useExact;+ if (state.exactDateMethodRadio) state.exactDateMethodRadio.checked = useExact;+ if (useExact) {+ if (state.exactDateInput) state.exactDateInput.value = warranty.expiration_date ? String(warranty.expiration_date).split('T')[0] : '';+ } else {+ setValue('warrantyDurationYears', years || '');+ setValue('warrantyDurationMonths', months || '');+ setValue('warrantyDurationDays', days || '');+ }+ handleLifetimeChange();+ handleWarrantyMethodChange();+ setValue('notes', warranty.notes || '');+ const tags = Array.isArray(warranty.tags)+ ? warranty.tags.map((tag) => ({ id: tag.id, name: tag.name, color: tag.color }))+ : [];+ setSelectedTags(tags);+ if (Array.isArray(window.selectedTags)) window.selectedTags = tags;+ renderSelectedTags();+ updateSummary();+ state.modal?.classList.add('active');+ showToast((window.i18next && window.i18next.t('messages.details_copied') || 'Details copied. Adjust anything that differs, then save.'), 'success');+}++if (typeof window !== 'undefined') {+ window.openDuplicateForm = openDuplicateForm;+}+function updateCurrencyDefaults() {const currencySelect = document.getElementById('currency');const preferred = getCurrencyCode();@@ -607,8 +684,8 @@ 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');+ 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');@@ -665,6 +742,7 @@ function appendFiles(formData, storageOptions = {}) {}};appendFile(state.fileInputs.productPhoto, 'product_photo');+ formData.append('product_photo_url', document.getElementById('productPhotoUrl')?.value || '');if (storageOptions.invoiceStorage !== 'paperless') {appendFile(state.fileInputs.invoice, 'invoice');}@@ -704,7 +782,7 @@ function appendWarrantyMethod(formData) {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');+ 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);@@ -714,14 +792,14 @@ function appendWarrantyMethod(formData) {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');+ 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');+ throw new Error((window.i18next && window.i18next.t('messages.exact_expiration_date_required') || 'Exact expiration date is required'));}}@@ -734,7 +812,7 @@ function validateWarrantySelection() {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');+ 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;@@ -745,14 +823,14 @@ function validateWarrantySelection() {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');+ 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');+ showToast((window.i18next && window.i18next.t('messages.exact_expiration_date_required') || 'Exact expiration date is required'), 'error');switchToTab(1);return false;}@@ -860,7 +938,7 @@ function updateFileSummary(summaryElement, entry, urlValue = '', paperlessInputIif (urlValue) {summaryElement.textContent = `URL: ${urlValue}`;} else if (!entry?.input?.files?.[0]) {- summaryElement.textContent = window.i18next ? window.i18next.t('warranties.not_specified') : 'Not specified';+ summaryElement.textContent = (window.i18next && window.i18next.t('warranties.not_specified') || 'Not specified');}}diff --git a/frontend/js/components/editModal.js b/frontend/js/components/editModal.jsindex a9f94b1..e5350ef 100644--- a/frontend/js/components/editModal.js+++ b/frontend/js/components/editModal.js@@ -532,10 +532,12 @@ function populateDocuments(warranty) {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');+ 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'));+ const photoUrlInput = document.getElementById('editProductPhotoUrl');+ if (photoUrlInput) photoUrlInput.value = '';clearPaperlessSelection('edit_invoice');clearPaperlessSelection('edit_manual');clearPaperlessSelection('edit_productPhoto');@@ -550,7 +552,7 @@ export async function saveWarranty() {setCurrentWarrantyId(currentId);}if (!currentId) {- showToast(window.i18next ? window.i18next.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;}@@ -646,6 +648,8 @@ export async function saveWarranty() {if (manualFile) formData.append('manual', manualFile);if (otherDocumentFile) formData.append('other_document', otherDocumentFile);if (productPhotoFile) formData.append('product_photo', productPhotoFile);+ const productPhotoUrl = (document.getElementById('editProductPhotoUrl') || {}).value || '';+ if (productPhotoUrl) formData.append('product_photo_url', productPhotoUrl);// Paperless browse selections (linked existing documents)const paperlessFields = [@@ -722,7 +726,7 @@ export async function saveWarranty() {await updateWarranty(currentId, formData);hideLoadingSpinner();- showToast(window.i18next ? window.i18next.t('messages.warranty_updated_successfully') : 'Warranty updated successfully', 'success');+ showToast((window.i18next && window.i18next.t('messages.warranty_updated_successfully') || 'Warranty updated successfully'), 'success');setCurrentWarrantyId(null);if (typeof window !== 'undefined') {window.currentWarrantyId = null;@@ -751,7 +755,7 @@ export async function saveWarranty() {} catch (error) {hideLoadingSpinner();console.error('Error updating warranty:', error);- showToast(apiErrorMessage(error, window.i18next ? window.i18next.t('messages.failed_to_update_warranty') : 'Failed to update warranty'), 'error');+ showToast(apiErrorMessage(error, (window.i18next && window.i18next.t('messages.failed_to_update_warranty') || 'Failed to update warranty')), 'error');}}diff --git a/frontend/js/components/formTabs.js b/frontend/js/components/formTabs.jsindex dca78f4..25eeef7 100644--- a/frontend/js/components/formTabs.js+++ b/frontend/js/components/formTabs.js@@ -208,9 +208,9 @@ function showValidationErrors(tabIndex) {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.';+ 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.');+ validationMessageElement.textContent = control.validationMessage || ((window.i18next && window.i18next.t('messages.field_is_invalid') || 'This field is invalid.'));}} else {control.classList.remove('invalid');@@ -292,7 +292,7 @@ function updateSummary() {if (summaryWarrantyDuration) {if (isLifetime) {- summaryWarrantyDuration.textContent = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';+ summaryWarrantyDuration.textContent = (window.i18next && window.i18next.t('warranties.lifetime') || 'Lifetime');} else {const years = parseInt(warrantyDurationYearsInput?.value || 0);const months = parseInt(warrantyDurationMonthsInput?.value || 0);@@ -300,15 +300,15 @@ function updateSummary() {let durationParts = [];if (years > 0) {- const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;+ 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' : ''}`;+ 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' : ''}`;+ const dayText = (window.i18next && window.i18next.t('warranties.day', {count: days}) || `day${days !== 1 ? 's' : ''}`);durationParts.push(`${days} ${dayText}`);}diff --git a/frontend/js/components/importExport.js b/frontend/js/components/importExport.jsindex d5476aa..f634a96 100644--- a/frontend/js/components/importExport.js+++ b/frontend/js/components/importExport.js@@ -7,7 +7,7 @@ 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');+ showToast((window.i18next && window.i18next.t('messages.no_warranties_to_export') || 'No warranties to export'), 'info');return;}const filters = getFilters();@@ -38,7 +38,7 @@ export async function exportWarranties() {}if (!filtered.length) {- showToast(window.i18next ? window.i18next.t('messages.no_warranties_to_export') : 'No warranties to export', 'info');+ showToast((window.i18next && window.i18next.t('messages.no_warranties_to_export') || 'No warranties to export'), 'info');return;}@@ -103,20 +103,18 @@ export async function exportWarranties() {document.body.removeChild(link);URL.revokeObjectURL(url);showToast(- window.i18next- ? window.i18next.t('messages.exported_warranties_successfully', { count: filtered.length })- : `Exported ${filtered.length} warranties`,+ (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');+ 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');+ showToast((window.i18next && window.i18next.t('messages.invalid_file_type') || 'Invalid file type'), 'error');return;}showLoadingSpinner();@@ -133,14 +131,12 @@ export async function handleImport(file) {const result = await response.json();hideLoadingSpinner();if (!response.ok) {- showToast(result.error || (window.i18next ? window.i18next.t('messages.import_failed') : 'Import failed'), 'error');+ 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.`,+ (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);@@ -150,7 +146,7 @@ export async function handleImport(file) {} catch (error) {hideLoadingSpinner();console.error('[importExport] Import error', error);- showToast(window.i18next ? window.i18next.t('messages.import_failed') : 'Import failed', 'error');+ showToast((window.i18next && window.i18next.t('messages.import_failed') || 'Import failed'), 'error');} finally {const input = document.getElementById('csvFileInput');if (input) input.value = '';diff --git a/frontend/js/components/notes.js b/frontend/js/components/notes.jsindex e7ceea7..35a051b 100644--- a/frontend/js/components/notes.js+++ b/frontend/js/components/notes.js@@ -4,7 +4,7 @@ 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>+ <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">@@ -12,10 +12,10 @@ const DEFAULT_MODAL_HTML = `<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>+ <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>`;@@ -84,7 +84,7 @@ function handleEditWarranty() {warranty = resolveWarranty(state.warrantyId);}if (!warranty) {- showToast(window.i18next ? window.i18next.t('messages.warranty_not_found_refresh') : 'Warranty not found', 'error');+ showToast((window.i18next && window.i18next.t('messages.warranty_not_found_refresh') || 'Warranty not found'), 'error');return;}callIfExists(window.openEditModal, warranty);@@ -215,15 +215,13 @@ function updateStoreNotes(noteValue) {async function saveNotes() {if (!dom || !state.warrantyId || !state.warranty) {- showToast(window.i18next ? window.i18next.t('messages.warranty_not_found_refresh') : 'Warranty not found', 'error');+ 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.',+ (window.i18next && window.i18next.t('messages.invalid_warranty_duration_before_notes') || 'Cannot save notes until warranty duration is valid.'),'error',7000,);@@ -231,7 +229,7 @@ async function saveNotes() {}const token = getToken();if (!token) {- showToast(window.i18next ? window.i18next.t('messages.authentication_required') : 'Authentication required', 'error');+ showToast((window.i18next && window.i18next.t('messages.authentication_required') || 'Authentication required'), 'error');return;}try {@@ -247,7 +245,7 @@ async function saveNotes() {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');+ showToast((window.i18next && window.i18next.t('messages.note_updated_successfully') || 'Note updated'), 'success');updateStoreNotes(noteValue);if (!noteValue) {hideModal();@@ -259,7 +257,7 @@ async function saveNotes() {} 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');+ showToast(error.message || ((window.i18next && window.i18next.t('messages.failed_to_update_note') || 'Failed to update note')), 'error');}}diff --git a/frontend/js/components/serialNumbers.js b/frontend/js/components/serialNumbers.jsindex e5e02b1..273e763 100644--- a/frontend/js/components/serialNumbers.js+++ b/frontend/js/components/serialNumbers.js@@ -23,7 +23,7 @@ function addSerialNumberInput(container) {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';+ input.placeholder = (window.i18next && window.i18next.t('warranties.enter_serial_number') || 'Enter serial number');// Check if this is the first serial number inputconst isFirstInput = container.querySelectorAll('.serial-number-input').length === 0;@@ -59,7 +59,7 @@ function addSerialNumberInput(container) {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.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);diff --git a/frontend/js/components/warrantyActions.js b/frontend/js/components/warrantyActions.jsindex 7902521..bcba8fc 100644--- a/frontend/js/components/warrantyActions.js+++ b/frontend/js/components/warrantyActions.js@@ -5,7 +5,7 @@ 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');+ showToast((window.i18next && window.i18next.t('messages.no_warranty_selected') || 'No warranty selected'), 'error');return;}try {@@ -18,8 +18,8 @@ async function toggleArchiveStatus(warrantyId, shouldArchive) {hideLoadingSpinner();showToast(shouldArchive- ? window.i18next ? window.i18next.t('messages.archived_success') : 'Warranty archived'- : window.i18next ? window.i18next.t('messages.unarchived_success') : 'Warranty unarchived',+ ? (window.i18next && window.i18next.t('messages.archived_success') || 'Warranty archived')+ : (window.i18next && window.i18next.t('messages.unarchived_success') || 'Warranty unarchived'),'success',);await loadWarranties(true);@@ -28,7 +28,7 @@ async function toggleArchiveStatus(warrantyId, shouldArchive) {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',+ (window.i18next && window.i18next.t('messages.error_updating_archive_status') || 'Failed to update archive status'),'error',);}@@ -36,7 +36,7 @@ async function toggleArchiveStatus(warrantyId, shouldArchive) {async function toggleVoidStatus(warrantyId, shouldVoid) {if (!warrantyId) {- showToast(window.i18next ? window.i18next.t('messages.no_warranty_selected') : 'No warranty selected', 'error');+ showToast((window.i18next && window.i18next.t('messages.no_warranty_selected') || 'No warranty selected'), 'error');return;}try {@@ -49,8 +49,8 @@ async function toggleVoidStatus(warrantyId, shouldVoid) {hideLoadingSpinner();showToast(shouldVoid- ? window.i18next ? window.i18next.t('messages.voided_success') : 'Warranty voided'- : window.i18next ? window.i18next.t('messages.unvoided_success') : 'Warranty restored from void',+ ? (window.i18next && window.i18next.t('messages.voided_success') || 'Warranty voided')+ : (window.i18next && window.i18next.t('messages.unvoided_success') || 'Warranty restored from void'),'success',);await loadWarranties(true);@@ -59,7 +59,7 @@ async function toggleVoidStatus(warrantyId, shouldVoid) {hideLoadingSpinner();console.error('[warrantyActions] Failed to toggle void', error);showToast(- window.i18next ? window.i18next.t('messages.error_updating_void_status') : 'Failed to update void status',+ (window.i18next && window.i18next.t('messages.error_updating_void_status') || 'Failed to update void status'),'error',);}@@ -72,14 +72,14 @@ async function deleteWarranty() {warrantyId = window.currentWarrantyId;}if (!warrantyId) {- showToast(window.i18next ? window.i18next.t('messages.no_warranty_selected_for_deletion') : 'No warranty selected', 'error');+ 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');+ showToast((window.i18next && window.i18next.t('messages.deleted_successfully') || 'Warranty deleted'), 'success');closeModals();setCurrentWarrantyId(null);// Also clear global variable for script.js compatibility@@ -91,7 +91,7 @@ async function deleteWarranty() {} 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');+ showToast((window.i18next && window.i18next.t('messages.failed_to_delete_warranty') || 'Failed to delete warranty'), 'error');}}@@ -102,7 +102,7 @@ async function confirmArchive() {warrantyId = window.currentWarrantyId;}if (!warrantyId) {- showToast(window.i18next ? window.i18next.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;}await toggleArchiveStatus(warrantyId, true);diff --git a/frontend/js/components/warrantyRenderer.js b/frontend/js/components/warrantyRenderer.jsindex e84d9dd..16fc1c6 100644--- a/frontend/js/components/warrantyRenderer.js+++ b/frontend/js/components/warrantyRenderer.js@@ -385,6 +385,9 @@ function buildActionButtons(warranty, { canEdit, isArchivedView, claimsMeta }) {</button>`}`}+ <button class="action-btn duplicate-btn" title="${t('warranties.duplicate_warranty', 'Duplicate warranty')}" data-id="${warranty.id}">+ <i class="fas fa-copy"></i>+ </button><button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}"><i class="fas fa-trash"></i></button>diff --git a/frontend/js/controllers/warrantyListController.js b/frontend/js/controllers/warrantyListController.jsindex 206476a..3c24be8 100644--- a/frontend/js/controllers/warrantyListController.js+++ b/frontend/js/controllers/warrantyListController.js@@ -150,7 +150,7 @@ export async function loadWarranties(isAuthenticatedOverride) {if (!isAuthenticated) {renderEmptyState(getWarrantiesListElement(),- window.i18next ? window.i18next.t('messages.login_to_view_warranties') : 'Please log in to view warranties.',+ (window.i18next && window.i18next.t('messages.login_to_view_warranties') || 'Please log in to view warranties.'),);setWarranties([], { warrantiesLoaded: false, lastLoadedArchived: false, lastLoadedIncludesArchived: false });return;@@ -188,9 +188,7 @@ export async function loadWarranties(isAuthenticatedOverride) {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.',+ (window.i18next && window.i18next.t('messages.no_warranties_found_add_first') || 'No warranties yet. Add your first warranty to get started.'),);return;}@@ -203,13 +201,11 @@ export async function loadWarranties(isAuthenticatedOverride) {console.error('[controller.loadWarranties] Error:', error);renderEmptyState(getWarrantiesListElement(),- window.i18next- ? window.i18next.t('messages.error_loading_warranties_try_again')- : 'Error loading warranties. Please try again.',+ (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'),+ ((window.i18next && window.i18next.t('messages.error_loading_warranties_try_again') || 'Failed to load warranties')),'error',);} finally {@@ -797,6 +793,14 @@ export function initEventListeners() {}return;}+ if (e.target.closest('.duplicate-btn')) {+ e.preventDefault();+ const el = e.target.closest('.duplicate-btn');+ const id = parseInt(el?.dataset?.id);+ const warranty = storeGetWarranties().find(w => w.id === id);+ if (warranty && typeof window.openDuplicateForm === 'function') window.openDuplicateForm(warranty);+ return;+ }if (e.target.closest('.delete-btn')) {e.preventDefault();const el = e.target.closest('.delete-btn');@@ -834,9 +838,7 @@ export function initEventListeners() {if (e.target.closest('.void-btn')) {e.preventDefault();const id = parseInt(e.target.closest('.void-btn')?.dataset?.id);- const confirmMessage = window.i18next- ? window.i18next.t('messages.confirm_void_warranty')- : 'Void this warranty? It will be marked inactive and excluded from totals and notifications. You can restore it later.';+ const confirmMessage = (window.i18next && window.i18next.t('messages.confirm_void_warranty') || 'Void this warranty? It will be marked inactive and excluded from totals and notifications. You can restore it later.');if (Number.isFinite(id) && window.confirm(confirmMessage)) toggleVoid(id, true);return;}diff --git a/frontend/login.html b/frontend/login.htmlindex e539a88..072a2a1 100644--- a/frontend/login.html+++ b/frontend/login.html@@ -10,7 +10,7 @@<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2"><link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png"><link rel="manifest" href="manifest.json">- <link rel="stylesheet" href="style.css?v=20261101001">+ <link rel="stylesheet" href="style.css?v=20261101002"><script src="theme-loader.js?v=20250119001"></script><script>// If user is authenticated and has a theme in user_info (from previous sessions), reflect it earlydiff --git a/frontend/register.html b/frontend/register.htmlindex 1fddd45..13ad310 100644--- a/frontend/register.html+++ b/frontend/register.html@@ -13,7 +13,7 @@<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2"><link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png"><link rel="manifest" href="manifest.json">- <link rel="stylesheet" href="style.css?v=20261101001">+ <link rel="stylesheet" href="style.css?v=20261101002"><script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early --><!-- Font Awesome for icons --><link rel="stylesheet" href="vendor/fontawesome/css/all.min.css?v=20261001001">diff --git a/frontend/reset-password-request.html b/frontend/reset-password-request.htmlindex 9beac81..da697f7 100644--- a/frontend/reset-password-request.html+++ b/frontend/reset-password-request.html@@ -10,7 +10,7 @@<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2"><link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png"><link rel="manifest" href="manifest.json">- <link rel="stylesheet" href="style.css?v=20261101001">+ <link rel="stylesheet" href="style.css?v=20261101002"><script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early --><!-- Font Awesome for icons --><link rel="stylesheet" href="vendor/fontawesome/css/all.min.css?v=20261001001">diff --git a/frontend/reset-password.html b/frontend/reset-password.htmlindex 6bea659..32abb6a 100644--- a/frontend/reset-password.html+++ b/frontend/reset-password.html@@ -10,7 +10,7 @@<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2"><link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png"><link rel="manifest" href="manifest.json">- <link rel="stylesheet" href="style.css?v=20261101001">+ <link rel="stylesheet" href="style.css?v=20261101002"><script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early --><!-- Font Awesome for icons --><link rel="stylesheet" href="vendor/fontawesome/css/all.min.css?v=20261001001">diff --git a/frontend/script.js b/frontend/script.jsindex 4f1bb9b..a656706 100644--- a/frontend/script.js+++ b/frontend/script.js@@ -1277,7 +1277,7 @@ function processWarrantyData(warranty) {// --- Lifetime Handling ---if (processedWarranty.is_lifetime) {processedWarranty.status = 'active';- processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';+ processedWarranty.statusText = (window.i18next && window.i18next.t('warranties.lifetime') || 'Lifetime');processedWarranty.daysRemaining = Infinity;// Ensure duration components are 0 for lifetimeprocessedWarranty.warranty_duration_years = 0;@@ -1294,23 +1294,15 @@ function processWarrantyData(warranty) {if (daysRemaining < 0) {processedWarranty.status = 'expired';- processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.expired') : 'Expired';+ processedWarranty.statusText = (window.i18next && window.i18next.t('warranties.expired') || 'Expired');} else if (daysRemaining < expiringSoonDays) {processedWarranty.status = 'expiring';- const dayText = window.i18next ?- window.i18next.t('warranties.day', {count: daysRemaining}) :- `day${daysRemaining !== 1 ? 's' : ''}`;- processedWarranty.statusText = window.i18next ?- window.i18next.t('warranties.days_remaining', {days: daysRemaining, dayText: dayText}) :- `${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining`;+ const dayText = (window.i18next && window.i18next.t('warranties.day', {count: daysRemaining}) || `day${daysRemaining !== 1 ? 's' : ''}`);+ processedWarranty.statusText = (window.i18next && window.i18next.t('warranties.days_remaining', {days: daysRemaining, dayText: dayText}) || `${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining`);} else {processedWarranty.status = 'active';- const dayText = window.i18next ?- window.i18next.t('warranties.day', {count: daysRemaining}) :- `day${daysRemaining !== 1 ? 's' : ''}`;- processedWarranty.statusText = window.i18next ?- window.i18next.t('warranties.days_remaining', {days: daysRemaining, dayText: dayText}) :- `${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining`;+ const dayText = (window.i18next && window.i18next.t('warranties.day', {count: daysRemaining}) || `day${daysRemaining !== 1 ? 's' : ''}`);+ processedWarranty.statusText = (window.i18next && window.i18next.t('warranties.days_remaining', {days: daysRemaining, dayText: dayText}) || `${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining`);}// Preserve original duration values to detect input method@@ -1351,14 +1343,14 @@ function processWarrantyData(warranty) {}} else {processedWarranty.status = 'unknown';- processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.unknown_status') : 'Unknown Status';+ processedWarranty.statusText = (window.i18next && window.i18next.t('warranties.unknown_status') || 'Unknown Status');processedWarranty.daysRemaining = null;}// Void (issue #250) takes precedence over the date-derived statusif (processedWarranty.is_voided) {processedWarranty.status = 'void';- processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.void') : 'Void';+ processedWarranty.statusText = (window.i18next && window.i18next.t('warranties.void') || 'Void');}console.log('Processed warranty data result:', processedWarranty);@@ -1695,15 +1687,15 @@ async function renderWarranties(warrantiesToRender) {let statusText = warranty.statusText || 'Unknown Status';// If showing archived-only view or item itself is archived within All viewif (isArchivedView || warranty.is_archived) {- const archivedTextRaw = window.i18next ? window.i18next.t('warranties.archived') : 'Archived';+ const archivedTextRaw = (window.i18next && window.i18next.t('warranties.archived') || 'Archived');const archivedLabel = archivedTextRaw && archivedTextRaw !== 'warranties.archived' ? archivedTextRaw : 'Archived';statusClass = 'archived';statusText = archivedLabel;}// Format warranty duration text- let warrantyDurationText = window.i18next ? window.i18next.t('warranties.na') : 'N/A';+ let warrantyDurationText = (window.i18next && window.i18next.t('warranties.na') || 'N/A');if (isLifetime) {- warrantyDurationText = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';+ warrantyDurationText = (window.i18next && window.i18next.t('warranties.lifetime') || 'Lifetime');} else {// Use display_duration values if available, otherwise fall back to warranty_duration valuesconst years = warranty.display_duration_years !== undefined ? warranty.display_duration_years : (warranty.warranty_duration_years || 0);@@ -1716,15 +1708,15 @@ async function renderWarranties(warrantiesToRender) {if (calculatedDuration) {let parts = [];if (calculatedDuration.years > 0) {- const yearText = window.i18next ? window.i18next.t('warranties.year', {count: calculatedDuration.years}) : `year${calculatedDuration.years !== 1 ? 's' : ''}`;+ const yearText = (window.i18next && window.i18next.t('warranties.year', {count: calculatedDuration.years}) || `year${calculatedDuration.years !== 1 ? 's' : ''}`);parts.push(`${calculatedDuration.years} ${yearText}`);}if (calculatedDuration.months > 0) {- const monthText = window.i18next ? window.i18next.t('warranties.month', {count: calculatedDuration.months}) : `month${calculatedDuration.months !== 1 ? 's' : ''}`;+ const monthText = (window.i18next && window.i18next.t('warranties.month', {count: calculatedDuration.months}) || `month${calculatedDuration.months !== 1 ? 's' : ''}`);parts.push(`${calculatedDuration.months} ${monthText}`);}if (calculatedDuration.days > 0) {- const dayText = window.i18next ? window.i18next.t('warranties.day', {count: calculatedDuration.days}) : `day${calculatedDuration.days !== 1 ? 's' : ''}`;+ const dayText = (window.i18next && window.i18next.t('warranties.day', {count: calculatedDuration.days}) || `day${calculatedDuration.days !== 1 ? 's' : ''}`);parts.push(`${calculatedDuration.days} ${dayText}`);}if (parts.length > 0) {@@ -1735,15 +1727,15 @@ async function renderWarranties(warrantiesToRender) {// Use the stored/calculated duration fieldslet parts = [];if (years > 0) {- const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;+ 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' : ''}`;+ const monthText = (window.i18next && window.i18next.t('warranties.month', {count: months}) || `month${months !== 1 ? 's' : ''}`);parts.push(`${months} ${monthText}`);}if (days > 0) {- const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;+ const dayText = (window.i18next && window.i18next.t('warranties.day', {count: days}) || `day${days !== 1 ? 's' : ''}`);parts.push(`${days} ${dayText}`);}if (parts.length > 0) {@@ -1751,7 +1743,7 @@ async function renderWarranties(warrantiesToRender) {}}}- const expirationDateText = isLifetime ? (window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime') : formatDate(expirationDate);+ const expirationDateText = isLifetime ? ((window.i18next && window.i18next.t('warranties.lifetime') || 'Lifetime')) : formatDate(expirationDate);// Calculate product ageconst productAge = calculateProductAge(warranty.purchase_date);@@ -1763,7 +1755,7 @@ async function renderWarranties(warrantiesToRender) {// Prepare user info HTML for global viewlet userInfoHtml = '';if (isGlobalView && warranty.user_display_name) {- const ownerLabel = window.i18next ? window.i18next.t('warranties.owner') : 'Owner';+ const ownerLabel = (window.i18next && window.i18next.t('warranties.owner') || 'Owner');userInfoHtml = `<div><strong>${ownerLabel}:</strong> <span>${warranty.user_display_name}</span></div>`;}@@ -1783,7 +1775,7 @@ async function renderWarranties(warrantiesToRender) {// Remove the button, and instead prepare a notes link for document-links-rowlet notesLinkHtml = '';if (hasNotes) {- const notesLabel = window.i18next ? window.i18next.t('warranties.notes') : 'Notes';+ const notesLabel = (window.i18next && window.i18next.t('warranties.notes') || 'Notes');notesLinkHtml = `<a href="#" class="notes-link" data-id="${warranty.id}" title="View Notes"><i class='fas fa-sticky-note'></i> ${notesLabel}</a>`;}@@ -1886,12 +1878,12 @@ async function renderWarranties(warrantiesToRender) {${photoThumbnailHtml}<div class="warranty-info">${userInfoHtml}- <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>- <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>- <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>- ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}+ <div><i class="fas fa-calendar"></i> ${(window.i18next && window.i18next.t('warranties.age') || 'Age')}: <span>${productAge}</span></div>+ <div><i class="fas fa-file-alt"></i> ${(window.i18next && window.i18next.t('warranties.warranty') || 'Warranty')}: <span>${warrantyDurationText}</span></div>+ <div><i class="fas fa-wrench"></i> ${(window.i18next && window.i18next.t('warranties.warranty_ends') || 'Warranty Ends')}: <span>${expirationDateText}</span></div>+ ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${(window.i18next && window.i18next.t('warranties.price') || 'Price')}: <span>${formatCurrencyHTML(warranty.purchase_price, getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}${validSerialNumbers.length > 0 ? `- <div><i class="fas fa-barcode"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>+ <div><i class="fas fa-barcode"></i> ${(window.i18next && window.i18next.t('warranties.serial_number') || 'Serial Number')}: <span>${validSerialNumbers[0]}</span></div>${validSerialNumbers.length > 1 ? `<div style="margin-left: 28px;"><ul style="margin-top: 5px;">@@ -1900,9 +1892,9 @@ async function renderWarranties(warrantiesToRender) {</div>` : ''}` : ''}- ${warranty.model_number ? `<div><i class="fas fa-tag"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}- ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}- ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}+ ${warranty.model_number ? `<div><i class="fas fa-tag"></i> ${(window.i18next && window.i18next.t('warranties.model_number') || 'Model Number')}: <span>${warranty.model_number}</span></div>` : ''}+ ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${(window.i18next && window.i18next.t('warranties.vendor') || 'Vendor')}: <span>${warranty.vendor}</span></div>` : ''}+ ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${(window.i18next && window.i18next.t('warranties.type') || 'Type')}: <span>${warranty.warranty_type}</span></div>` : ''}</div></div>${hasDocuments ? `@@ -1910,7 +1902,7 @@ async function renderWarranties(warrantiesToRender) {<div class="document-links-inner-container">${warranty.product_url ? `<a href="${warranty.product_url}" class="product-link" target="_blank">- <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}+ <i class="fas fa-globe"></i> ${(window.i18next && window.i18next.t('warranties.product_website') || 'Product Website')}</a>` : ''}${generateDocumentLink(warranty, 'invoice')}@@ -1949,12 +1941,12 @@ async function renderWarranties(warrantiesToRender) {${photoThumbnailHtml}<div class="warranty-info">${userInfoHtml}- <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>- <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>- <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>- ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}+ <div><i class="fas fa-calendar"></i> ${(window.i18next && window.i18next.t('warranties.age') || 'Age')}: <span>${productAge}</span></div>+ <div><i class="fas fa-file-alt"></i> ${(window.i18next && window.i18next.t('warranties.warranty') || 'Warranty')}: <span>${warrantyDurationText}</span></div>+ <div><i class="fas fa-wrench"></i> ${(window.i18next && window.i18next.t('warranties.warranty_ends') || 'Warranty Ends')}: <span>${expirationDateText}</span></div>+ ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${(window.i18next && window.i18next.t('warranties.price') || 'Price')}: <span>${formatCurrencyHTML(warranty.purchase_price, getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}${validSerialNumbers.length > 0 ? `- <div><i class="fas fa-barcode"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>+ <div><i class="fas fa-barcode"></i> ${(window.i18next && window.i18next.t('warranties.serial_number') || 'Serial Number')}: <span>${validSerialNumbers[0]}</span></div>${validSerialNumbers.length > 1 ? `<div style="margin-left: 28px;"><ul style="margin-top: 5px;">@@ -1963,9 +1955,9 @@ async function renderWarranties(warrantiesToRender) {</div>` : ''}` : ''}- ${warranty.model_number ? `<div><i class=\"fas fa-tag\"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}- ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}- ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}+ ${warranty.model_number ? `<div><i class=\"fas fa-tag\"></i> ${(window.i18next && window.i18next.t('warranties.model_number') || 'Model Number')}: <span>${warranty.model_number}</span></div>` : ''}+ ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${(window.i18next && window.i18next.t('warranties.vendor') || 'Vendor')}: <span>${warranty.vendor}</span></div>` : ''}+ ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${(window.i18next && window.i18next.t('warranties.type') || 'Type')}: <span>${warranty.warranty_type}</span></div>` : ''}</div></div>${hasDocuments ? `@@ -1973,7 +1965,7 @@ async function renderWarranties(warrantiesToRender) {<div class="document-links-inner-container">${warranty.product_url ? `<a href="${warranty.product_url}" class="product-link" target="_blank">- <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}+ <i class="fas fa-globe"></i> ${(window.i18next && window.i18next.t('warranties.product_website') || 'Product Website')}</a>` : ''}${generateDocumentLink(warranty, 'invoice')}@@ -2012,12 +2004,12 @@ async function renderWarranties(warrantiesToRender) {${photoThumbnailHtml}<div class="warranty-info">${userInfoHtml}- <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>- <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>- <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>- ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}+ <div><i class="fas fa-calendar"></i> ${(window.i18next && window.i18next.t('warranties.age') || 'Age')}: <span>${productAge}</span></div>+ <div><i class="fas fa-file-alt"></i> ${(window.i18next && window.i18next.t('warranties.warranty') || 'Warranty')}: <span>${warrantyDurationText}</span></div>+ <div><i class="fas fa-wrench"></i> ${(window.i18next && window.i18next.t('warranties.warranty_ends') || 'Warranty Ends')}: <span>${expirationDateText}</span></div>+ ${warranty.purchase_price ? `<div><i class="fas fa-coins"></i> ${(window.i18next && window.i18next.t('warranties.price') || 'Price')}: <span>${formatCurrencyHTML(warranty.purchase_price, getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}${validSerialNumbers.length > 0 ? `- <div><i class="fas fa-barcode"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>+ <div><i class="fas fa-barcode"></i> ${(window.i18next && window.i18next.t('warranties.serial_number') || 'Serial Number')}: <span>${validSerialNumbers[0]}</span></div>${validSerialNumbers.length > 1 ? `<div style="margin-left: 28px;"><ul style="margin-top: 5px;">@@ -2026,9 +2018,9 @@ async function renderWarranties(warrantiesToRender) {</div>` : ''}` : ''}- ${warranty.model_number ? `<div><i class=\"fas fa-tag\"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}- ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}- ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}+ ${warranty.model_number ? `<div><i class=\"fas fa-tag\"></i> ${(window.i18next && window.i18next.t('warranties.model_number') || 'Model Number')}: <span>${warranty.model_number}</span></div>` : ''}+ ${warranty.vendor ? `<div><i class="fas fa-store"></i> ${(window.i18next && window.i18next.t('warranties.vendor') || 'Vendor')}: <span>${warranty.vendor}</span></div>` : ''}+ ${warranty.warranty_type ? `<div><i class="fas fa-shield-alt"></i> ${(window.i18next && window.i18next.t('warranties.type') || 'Type')}: <span>${warranty.warranty_type}</span></div>` : ''}</div></div><div class="warranty-status-row status-${statusClass}">@@ -2039,7 +2031,7 @@ async function renderWarranties(warrantiesToRender) {<div class="document-links-inner-container">${warranty.product_url ? `<a href="${warranty.product_url}" class="product-link" target="_blank">- <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}+ <i class="fas fa-globe"></i> ${(window.i18next && window.i18next.t('warranties.product_website') || 'Product Website')}</a>` : ''}${generateDocumentLink(warranty, 'invoice')}@@ -3514,7 +3506,7 @@ async function openClaimsModal(warrantyId) {// Find warranty infoconst warranty = warranties.find(w => w.id === warrantyId);if (!warranty) {- showToast(window.i18next ? window.i18next.t('claims.warranty_not_found') : 'Warranty not found', 'error');+ showToast((window.i18next && window.i18next.t('claims.warranty_not_found') || 'Warranty not found'), 'error');return;}@@ -3620,13 +3612,13 @@ function renderClaims() {if (currentClaims.length === 0) {const noClaimsMessage = currentClaimsCanEdit- ? (window.i18next ? window.i18next.t('claims.no_claims_message') : 'Click "Add New Claim" to get started')+ ? ((window.i18next && window.i18next.t('claims.no_claims_message') || 'Click "Add New Claim" to get started')): 'No claims have been filed for this warranty';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 style="color: var(--text-color); margin-bottom: 0.5rem;">${window.i18next ? window.i18next.t('claims.no_claims_yet') : 'No Claims Yet'}</h4>+ <h4 style="color: var(--text-color); margin-bottom: 0.5rem;">${(window.i18next && window.i18next.t('claims.no_claims_yet') || 'No Claims Yet')}</h4><p style="color: var(--dark-gray); margin-bottom: 0;">${noClaimsMessage}</p></div>`;@@ -3686,7 +3678,7 @@ function renderClaims() {if (e.target.closest('.delete-claim-btn')) {const claimId = parseInt(e.target.closest('.delete-claim-btn').dataset.claimId);- if (confirm(window.i18next ? window.i18next.t('claims.confirm_delete_claim') : 'Are you sure you want to delete this claim?')) {+ if (confirm((window.i18next && window.i18next.t('claims.confirm_delete_claim') || 'Are you sure you want to delete this claim?'))) {deleteClaim(claimId);}}@@ -3705,7 +3697,7 @@ function openClaimFormModal(claim = null) {// Update titleif (claimFormTitle) {- claimFormTitle.textContent = claim ? (window.i18next ? window.i18next.t('claims.edit_claim') : 'Edit Claim') : (window.i18next ? window.i18next.t('claims.add_new_claim') : 'Add New Claim');+ claimFormTitle.textContent = claim ? ((window.i18next && window.i18next.t('claims.edit_claim') || 'Edit Claim')) : ((window.i18next && window.i18next.t('claims.add_new_claim') || 'Add New Claim'));}// Reset form@@ -3782,7 +3774,7 @@ async function handleClaimFormSubmit(event) {throw new Error(error.error || 'Failed to save claim');}- showToast(isEdit ? (window.i18next ? window.i18next.t('claims.claim_updated_successfully') : 'Claim updated successfully') : (window.i18next ? window.i18next.t('claims.claim_created_successfully') : 'Claim created successfully'), 'success');+ showToast(isEdit ? ((window.i18next && window.i18next.t('claims.claim_updated_successfully') || 'Claim updated successfully')) : ((window.i18next && window.i18next.t('claims.claim_created_successfully') || 'Claim created successfully')), 'success');closeClaimFormModal();// Reload claims@@ -3815,7 +3807,7 @@ async function deleteClaim(claimId) {throw new Error(error.error || 'Failed to delete claim');}- showToast(window.i18next ? window.i18next.t('claims.claim_deleted_successfully') : 'Claim deleted successfully', 'success');+ showToast((window.i18next && window.i18next.t('claims.claim_deleted_successfully') || 'Claim deleted successfully'), 'success');// Reload claimsawait loadClaims(currentClaimsWarrantyId);@@ -4069,7 +4061,7 @@ function generateDocumentLink(warranty, docType) {paperlessId: warranty.paperless_invoice_id,url: warranty.invoice_url,icon: 'fas fa-file-invoice',- label: window.i18next ? window.i18next.t('warranties.invoice_receipt_short', 'Invoice') : 'Invoice',+ label: (window.i18next && window.i18next.t('warranties.invoice_receipt_short', 'Invoice') || 'Invoice'),className: 'invoice-link'},manual: {@@ -4077,7 +4069,7 @@ function generateDocumentLink(warranty, docType) {paperlessId: warranty.paperless_manual_id,url: warranty.manual_url,icon: 'fas fa-book',- label: window.i18next ? window.i18next.t('warranties.product_manual', 'Manual') : 'Manual',+ label: (window.i18next && window.i18next.t('warranties.product_manual', 'Manual') || 'Manual'),className: 'manual-link'},other: {@@ -4085,7 +4077,7 @@ function generateDocumentLink(warranty, docType) {paperlessId: warranty.paperless_other_id,url: warranty.other_document_url,icon: 'fas fa-file-alt',- label: window.i18next ? window.i18next.t('warranties.files', 'Files') : 'Files',+ label: (window.i18next && window.i18next.t('warranties.files', 'Files') || 'Files'),className: 'other-document-link'},photo: {@@ -4093,7 +4085,7 @@ function generateDocumentLink(warranty, docType) {paperlessId: warranty.paperless_photo_id,url: null,icon: 'fas fa-image',- label: window.i18next ? window.i18next.t('warranties.product_photo', 'Photo') : 'Photo',+ label: (window.i18next && window.i18next.t('warranties.product_photo', 'Photo') || 'Photo'),className: 'photo-link'}};diff --git a/frontend/settings-new.html b/frontend/settings-new.htmlindex 92a5d11..cf63dc4 100644--- a/frontend/settings-new.html+++ b/frontend/settings-new.html@@ -17,7 +17,7 @@<link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png"><link rel="manifest" href="manifest.json"><!-- Load the main site styles first -->- <link rel="stylesheet" href="style.css?v=20261101001">+ <link rel="stylesheet" href="style.css?v=20261101002"><!-- Font Awesome for icons --><link rel="stylesheet" href="vendor/fontawesome/css/all.min.css?v=20261001001"><!-- Then load settings-specific styles -->diff --git a/frontend/status.html b/frontend/status.htmlindex ce7433c..9e0a0d4 100644--- a/frontend/status.html+++ b/frontend/status.html@@ -19,7 +19,7 @@<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png?v=2"><link rel="apple-touch-icon" sizes="180x180" href="img/favicon-512x512.png"><link rel="manifest" href="manifest.json">- <link rel="stylesheet" href="style.css?v=20261101001">+ <link rel="stylesheet" href="style.css?v=20261101002"><script src="theme-loader.js?v=20250119001"></script> <!-- Apply theme early --><!-- Font Awesome for icons --><link rel="stylesheet" href="vendor/fontawesome/css/all.min.css?v=20261001001">@@ -38,7 +38,7 @@<script src="mobile-menu.js?v=20250119002" defer></script><!-- Load fix for auth buttons --><script src="fix-auth-buttons-loader.js?v=20250119001"></script>- <script src="script.js?v=20261101002" defer></script> <!-- Added script.js -->+ <script src="script.js?v=20261101003" defer></script> <!-- Added script.js --><style>.user-menu {position: relative;@@ -681,7 +681,7 @@</select></div><div class="form-group">- <label for="editPurchasePrice" data-i18n="warranties.purchase_price_optional">Purchase Price (Optional)</label>+ <label for="editPurchasePrice" class="label-with-help"><span data-i18n="warranties.purchase_price_optional">Purchase Price (Optional)</span> <i class="fas fa-info-circle field-help-icon" data-i18n-title="warranties.purchase_price_tooltip" title="The price you paid for the product itself, not the cost of the warranty. If the warranty was included with the product, enter the product's price."></i></label><div class="price-input-wrapper" id="editPriceInputWrapper"><span class="currency-symbol" id="editCurrencySymbol">$</span><input type="number" id="editPurchasePrice" name="purchase_price" class="form-control" min="0" step="0.01" placeholder="0.00">@@ -711,6 +711,7 @@<div id="editProductPhotoPreview" class="photo-preview" style="display: none;"><img id="editProductPhotoImg" src="" alt="Product Photo Preview" style="max-width: 200px; max-height: 200px; border-radius: 8px; margin-top: 10px;"></div>+ <input type="url" id="editProductPhotoUrl" name="product_photo_url" class="form-control photo-url-input" data-i18n-placeholder="warranties.photo_url_placeholder" placeholder="Or paste a photo URL"><div id="currentProductPhoto" class="mt-10"></div><button type="button" id="deleteProductPhotoBtn" class="btn btn-danger btn-sm mt-2" style="display:none;"><i class="fas fa-trash"></i> <span data-i18n="warranties.delete_photo">Delete Photo</span></button></div>diff --git a/frontend/style.css b/frontend/style.cssindex 5608c92..27083c9 100644--- a/frontend/style.css+++ b/frontend/style.css@@ -477,6 +477,22 @@ input.invalid {color: var(--text-color);}+.form-group label.label-with-help {+ display: inline-flex;+ align-items: center;+ gap: 6px;+}++.field-help-icon {+ color: var(--text-muted);+ cursor: help;+ font-size: 0.92em;+}++.photo-url-input {+ margin-top: 10px;+}+.form-control {width: 100%;padding: 12px;diff --git a/locales/ar/translation.json b/locales/ar/translation.jsonindex 12f0884..c9488a7 100644--- a/locales/ar/translation.json+++ b/locales/ar/translation.json@@ -174,6 +174,9 @@"other_custom": "أخرى (مخصص)","enter_custom_warranty_type": "أدخل نوع ضمان مخصص","purchase_price_optional": "سعر الشراء (اختياري)",+ "purchase_price_tooltip": "السعر الذي دفعته مقابل المنتج نفسه، وليس تكلفة الضمان. إذا كان الضمان مشمولاً مع المنتج، فأدخل سعر المنتج.",+ "duplicate_warranty": "تكرار الضمان",+ "photo_url_placeholder": "أو الصق رابط صورة","notes_optional": "ملاحظات (اختياري)","add_any_notes": "أضف أي ملاحظات حول هذا الضمان...","product_photo_optional": "صورة المنتج (اختياري)",@@ -514,6 +517,7 @@"correct_errors_in_tab": "يرجى تصحيح الأخطاء في التبويب المظلل قبل المتابعة.","please_fill_out_this_field": "يرجى ملء هذا الحقل.","warranty_added_successfully": "تم إضافة الضمان بنجاح",+ "details_copied": "تم نسخ التفاصيل. عدّل ما يختلف ثم احفظ.","tag_name_required": "اسم العلامة مطلوب","tag_creation_function_not_found": "وظيفة إنشاء العلامة غير موجودة","tag_created_successfully": "تم إنشاء العلامة بنجاح",diff --git a/locales/cs/translation.json b/locales/cs/translation.jsonindex fffad71..46e4a06 100644--- a/locales/cs/translation.json+++ b/locales/cs/translation.json@@ -151,6 +151,9 @@"other_custom": "Jiné (vlastní)","enter_custom_warranty_type": "Zadejte vlastní typ záruky","purchase_price_optional": "Nákupní cena (volitelné)",+ "purchase_price_tooltip": "Cena, kterou jste zaplatili za samotný výrobek, nikoli náklady na záruku. Pokud byla záruka součástí výrobku, zadejte cenu výrobku.",+ "duplicate_warranty": "Duplikovat záruku",+ "photo_url_placeholder": "Nebo vložte URL fotografie","notes_optional": "Poznámky (volitelné)","add_any_notes": "Přidejte jakékoli poznámky k této záruce...","product_photo_optional": "Fotografie produktu (volitelné)",@@ -511,6 +514,7 @@"correct_errors_in_tab": "Před pokračováním opravte chyby v zvýrazněné záložce.","please_fill_out_this_field": "Prosím vyplňte toto pole.","warranty_added_successfully": "Záruka byla úspěšně přidána",+ "details_copied": "Údaje zkopírovány. Upravte, co se liší, a poté uložte.","tag_name_required": "Název tagu je vyžadován","tag_creation_function_not_found": "Funkce pro vytvoření tagu nebyla nalezena","tag_created_successfully": "Tag byl úspěšně vytvořen",diff --git a/locales/de/translation.json b/locales/de/translation.jsonindex 28bd495..0341c49 100644--- a/locales/de/translation.json+++ b/locales/de/translation.json@@ -144,6 +144,9 @@"other_custom": "Andere (benutzerdefiniert)","enter_custom_warranty_type": "Benutzerdefinierten Garantietyp eingeben","purchase_price_optional": "Kaufpreis (optional)",+ "purchase_price_tooltip": "Der Preis, den Sie für das Produkt selbst bezahlt haben, nicht die Kosten der Garantie. Wenn die Garantie im Produkt enthalten war, geben Sie den Produktpreis ein.",+ "duplicate_warranty": "Garantie duplizieren",+ "photo_url_placeholder": "Oder eine Foto-URL einfügen","notes_optional": "Notizen (optional)","add_any_notes": "Fügen Sie Notizen zu dieser Garantie hinzu...","product_photo_optional": "Produktfoto (optional)",@@ -504,6 +507,7 @@"correct_errors_in_tab": "Bitte korrigieren Sie die Fehler im hervorgehobenen Tab, bevor Sie fortfahren.","please_fill_out_this_field": "Bitte füllen Sie dieses Feld aus.","warranty_added_successfully": "Garantie erfolgreich hinzugefügt",+ "details_copied": "Details kopiert. Passen Sie alles an, was sich unterscheidet, und speichern Sie dann.","tag_name_required": "Tag-Name ist erforderlich","tag_creation_function_not_found": "Tag-Erstellungsfunktion nicht gefunden","tag_created_successfully": "Tag erfolgreich erstellt",diff --git a/locales/en/translation.json b/locales/en/translation.jsonindex 90ee0c3..8b1d547 100644--- a/locales/en/translation.json+++ b/locales/en/translation.json@@ -139,6 +139,9 @@"other_custom": "Other (Custom)","enter_custom_warranty_type": "Enter custom warranty type","purchase_price_optional": "Purchase Price (Optional)",+ "purchase_price_tooltip": "The price you paid for the product itself, not the cost of the warranty. If the warranty was included with the product, enter the product's price.",+ "duplicate_warranty": "Duplicate warranty",+ "photo_url_placeholder": "Or paste a photo URL","notes_optional": "Notes (Optional)","add_any_notes": "Add any notes about this warranty...","product_photo_optional": "Product Photo (Optional)",@@ -504,6 +507,7 @@"correct_errors_in_tab": "Please correct the errors in the highlighted tab before continuing.","please_fill_out_this_field": "Please fill out this field.","warranty_added_successfully": "Warranty added successfully",+ "details_copied": "Details copied. Adjust anything that differs, then save.","tag_name_required": "Tag name is required","tag_creation_function_not_found": "Tag creation function not found","tag_created_successfully": "Tag created successfully",diff --git a/locales/es/translation.json b/locales/es/translation.jsonindex 81f08c3..7cca354 100644--- a/locales/es/translation.json+++ b/locales/es/translation.json@@ -140,6 +140,9 @@"other_custom": "Otro (personalizado)","enter_custom_warranty_type": "Introduzca un tipo de garantía personalizado","purchase_price_optional": "Precio de compra (opcional)",+ "purchase_price_tooltip": "El precio que pagó por el producto en sí, no el costo de la garantía. Si la garantía estaba incluida con el producto, ingrese el precio del producto.",+ "duplicate_warranty": "Duplicar garantía",+ "photo_url_placeholder": "O pegue la URL de una foto","notes_optional": "Notas (opcional)","add_any_notes": "Añada cualquier nota sobre esta garantía...","product_photo_optional": "Foto del producto (opcional)",@@ -504,6 +507,7 @@"correct_errors_in_tab": "Por favor, corrija los errores en la pestaña resaltada antes de continuar.","please_fill_out_this_field": "Por favor, complete este campo.","warranty_added_successfully": "Garantía agregada con éxito",+ "details_copied": "Datos copiados. Ajuste lo que sea diferente y luego guarde.","tag_name_required": "El nombre de la etiqueta es requerido","tag_creation_function_not_found": "Función de creación de etiquetas no encontrada","tag_created_successfully": "Etiqueta creada con éxito",diff --git a/locales/fa/translation.json b/locales/fa/translation.jsonindex ab425fd..f85f091 100644--- a/locales/fa/translation.json+++ b/locales/fa/translation.json@@ -144,6 +144,9 @@"other_custom": "سایر (سفارشی)","enter_custom_warranty_type": "نوع گارانتی سفارشی را وارد کنید","purchase_price_optional": "قیمت خرید (اختیاری)",+ "purchase_price_tooltip": "قیمتی که برای خود محصول پرداخت کردهاید، نه هزینه گارانتی. اگر گارانتی همراه محصول بوده است، قیمت محصول را وارد کنید.",+ "duplicate_warranty": "تکثیر گارانتی",+ "photo_url_placeholder": "یا نشانی اینترنتی عکس را بچسبانید","notes_optional": "یادداشتها (اختیاری)","add_any_notes": "هرگونه یادداشتی در مورد این گارانتی اضافه کنید...","product_photo_optional": "عکس محصول (اختیاری)",@@ -504,6 +507,7 @@"correct_errors_in_tab": "لطفاً خطاهای موجود در تب برجسته شده را قبل از ادامه تصحیح کنید.","please_fill_out_this_field": "لطفاً این فیلد را پر کنید.","warranty_added_successfully": "گارانتی با موفقیت اضافه شد",+ "details_copied": "جزئیات کپی شد. موارد متفاوت را تنظیم کنید و سپس ذخیره کنید。","tag_name_required": "نام برچسب الزامی است","tag_creation_function_not_found": "تابع ایجاد برچسب پیدا نشد","tag_created_successfully": "برچسب با موفقیت ایجاد شد",diff --git a/locales/fr/translation.json b/locales/fr/translation.jsonindex 180faa5..ed0668d 100644--- a/locales/fr/translation.json+++ b/locales/fr/translation.json@@ -144,6 +144,9 @@"other_custom": "Autre (personnalisé)","enter_custom_warranty_type": "Entrez un type de garantie personnalisé","purchase_price_optional": "Prix d'achat (facultatif)",+ "purchase_price_tooltip": "Le prix que vous avez payé pour le produit lui-même, et non le coût de la garantie. Si la garantie était incluse avec le produit, saisissez le prix du produit.",+ "duplicate_warranty": "Dupliquer la garantie",+ "photo_url_placeholder": "Ou collez l'URL d'une photo","notes_optional": "Notes (facultatif)","add_any_notes": "Ajoutez des notes sur cette garantie...","product_photo_optional": "Photo du produit (facultatif)",@@ -504,6 +507,7 @@"correct_errors_in_tab": "Veuillez corriger les erreurs dans l'onglet mis en évidence avant de continuer.","please_fill_out_this_field": "Veuillez remplir ce champ.","warranty_added_successfully": "Garantie ajoutée avec succès",+ "details_copied": "Détails copiés. Modifiez ce qui diffère, puis enregistrez.","tag_name_required": "Le nom du tag est requis","tag_creation_function_not_found": "Fonction de création de tag non trouvée","tag_created_successfully": "Tag créé avec succès",diff --git a/locales/he/translation.json b/locales/he/translation.jsonindex 657db7e..f2ef5e5 100644--- a/locales/he/translation.json+++ b/locales/he/translation.json@@ -176,6 +176,9 @@"other_custom": "אחר (מותאם)","enter_custom_warranty_type": "הזן סוג אחריות מותאם","purchase_price_optional": "מחיר רכישה (אופציונלי)",+ "purchase_price_tooltip": "המחיר ששילמתם עבור המוצר עצמו, לא עלות האחריות. אם האחריות נכללה עם המוצר, הזינו את מחיר המוצר.",+ "duplicate_warranty": "שכפול אחריות",+ "photo_url_placeholder": "או הדביקו כתובת URL של תמונה","notes_optional": "הערות (אופציונלי)","add_any_notes": "הוסף הערות לגבי אחריות זו...","product_photo_optional": "תמונת מוצר (אופציונלי)",@@ -514,6 +517,7 @@"correct_errors_in_tab": "אנא תקן את השגיאות בלשונית המסומנת לפני ההמשך.","please_fill_out_this_field": "אנא מלא שדה זה.","warranty_added_successfully": "האחריות נוספה בהצלחה",+ "details_copied": "הפרטים הועתקו. התאימו את מה ששונה, ואז שמרו.","tag_name_required": "נדרש שם תגית","tag_creation_function_not_found": "פונקציית יצירת תגית לא נמצאה","tag_created_successfully": "תגית נוצרה בהצלחה",diff --git a/locales/hi/translation.json b/locales/hi/translation.jsonindex 6e64946..ab17411 100644--- a/locales/hi/translation.json+++ b/locales/hi/translation.json@@ -144,6 +144,9 @@"other_custom": "अन्य (कस्टम)","enter_custom_warranty_type": "कस्टम वारंटी प्रकार दर्ज करें","purchase_price_optional": "खरीद मूल्य (वैकल्पिक)",+ "purchase_price_tooltip": "वह कीमत जो आपने उत्पाद के लिए चुकाई है, वारंटी की लागत नहीं। यदि वारंटी उत्पाद के साथ शामिल थी, तो उत्पाद की कीमत दर्ज करें।",+ "duplicate_warranty": "वारंटी डुप्लिकेट करें",+ "photo_url_placeholder": "या फ़ोटो का URL चिपकाएँ","notes_optional": "नोट्स (वैकल्पिक)","add_any_notes": "इस वारंटी के बारे में कोई नोट्स जोड़ें...","product_photo_optional": "उत्पाद फोटो (वैकल्पिक)",@@ -504,6 +507,7 @@"correct_errors_in_tab": "कृपया जारी रखने से पहले हाइलाइट किए गए टैब में त्रुटियों को सुधारें।","please_fill_out_this_field": "कृपया इस फ़ील्ड को भरें।","warranty_added_successfully": "वारंटी सफलतापूर्वक जोड़ी गई",+ "details_copied": "विवरण कॉपी हो गया। जो अलग है उसे समायोजित करें, फिर सहेजें।","tag_name_required": "टैग नाम आवश्यक है","tag_creation_function_not_found": "टैग निर्माण फ़ंक्शन नहीं मिला","tag_created_successfully": "टैग सफलतापूर्वक बनाया गया",diff --git a/locales/it/translation.json b/locales/it/translation.jsonindex 2b0ec4c..525a777 100644--- a/locales/it/translation.json+++ b/locales/it/translation.json@@ -429,6 +429,9 @@"other_custom": "Altro (Personalizzato)","enter_custom_warranty_type": "Inserisci tipo di garanzia personalizzato","purchase_price_optional": "Prezzo di Acquisto (Opzionale)",+ "purchase_price_tooltip": "Il prezzo pagato per il prodotto stesso, non il costo della garanzia. Se la garanzia era inclusa con il prodotto, inserisci il prezzo del prodotto.",+ "duplicate_warranty": "Duplica garanzia",+ "photo_url_placeholder": "Oppure incolla l'URL di una foto","notes_optional": "Note (Opzionali)","add_any_notes": "Aggiungi note su questa garanzia...","product_photo_optional": "Foto Prodotto (Opzionale)",@@ -597,6 +600,7 @@"correct_errors_in_tab": "Si prega di correggere gli errori nella scheda evidenziata prima di continuare.","please_fill_out_this_field": "Si prega di compilare questo campo.","warranty_added_successfully": "Garanzia aggiunta con successo",+ "details_copied": "Dettagli copiati. Modifica ciò che è diverso, quindi salva.","tag_name_required": "Il nome del tag è richiesto","tag_creation_function_not_found": "Funzione di creazione tag non trovata","tag_created_successfully": "Tag creato con successo",diff --git a/locales/ja/translation.json b/locales/ja/translation.jsonindex 8a6ba38..569cfba 100644--- a/locales/ja/translation.json+++ b/locales/ja/translation.json@@ -144,6 +144,9 @@"other_custom": "その他(カスタム)","enter_custom_warranty_type": "カスタム保証タイプを入力","purchase_price_optional": "購入価格(オプション)",+ "purchase_price_tooltip": "保証の費用ではなく、製品自体に支払った価格です。保証が製品に含まれていた場合は、製品の価格を入力してください。",+ "duplicate_warranty": "保証を複製",+ "photo_url_placeholder": "または写真のURLを貼り付け","notes_optional": "メモ(オプション)","add_any_notes": "この保証に関するメモを追加...","product_photo_optional": "製品写真(オプション)",@@ -504,6 +507,7 @@"correct_errors_in_tab": "続行する前に、ハイライトされたタブのエラーを修正してください。","please_fill_out_this_field": "このフィールドを入力してください。","warranty_added_successfully": "保証が正常に追加されました",+ "details_copied": "詳細をコピーしました。異なる点を調整して保存してください。","tag_name_required": "タグ名は必須です","tag_creation_function_not_found": "タグ作成機能が見つかりません","tag_created_successfully": "タグが正常に作成されました",diff --git a/locales/ko/translation.json b/locales/ko/translation.jsonindex 85e519d..78a9e53 100644--- a/locales/ko/translation.json+++ b/locales/ko/translation.json@@ -144,6 +144,9 @@"other_custom": "기타 (사용자 지정)","enter_custom_warranty_type": "사용자 지정 보증 유형 입력","purchase_price_optional": "구매 가격 (선택 사항)",+ "purchase_price_tooltip": "보증 비용이 아니라 제품 자체에 지불한 가격입니다. 보증이 제품에 포함되어 있었다면 제품 가격을 입력하세요.",+ "duplicate_warranty": "보증 복제",+ "photo_url_placeholder": "또는 사진 URL 붙여넣기","notes_optional": "메모 (선택 사항)","add_any_notes": "이 보증에 대한 메모 추가...","product_photo_optional": "제품 사진 (선택 사항)",@@ -504,6 +507,7 @@"correct_errors_in_tab": "계속하기 전에 강조 표시된 탭의 오류를 수정해 주세요.","please_fill_out_this_field": "이 필드를 채워주세요.","warranty_added_successfully": "보증이 성공적으로 추가되었습니다",+ "details_copied": "세부 정보가 복사되었습니다. 다른 부분을 조정한 뒤 저장하세요.","tag_name_required": "태그 이름이 필요합니다","tag_creation_function_not_found": "태그 생성 기능을 찾을 수 없습니다","tag_created_successfully": "태그가 성공적으로 생성되었습니다",diff --git a/locales/nl/translation.json b/locales/nl/translation.jsonindex efb4078..fe0f6e4 100644--- a/locales/nl/translation.json+++ b/locales/nl/translation.json@@ -144,6 +144,9 @@"other_custom": "Anders (aangepast)","enter_custom_warranty_type": "Voer aangepast garantietype in","purchase_price_optional": "Aankoopprijs (optioneel)",+ "purchase_price_tooltip": "De prijs die u voor het product zelf hebt betaald, niet de kosten van de garantie. Als de garantie bij het product was inbegrepen, voer dan de productprijs in.",+ "duplicate_warranty": "Garantie dupliceren",+ "photo_url_placeholder": "Of plak een foto-URL","notes_optional": "Notities (optioneel)","add_any_notes": "Voeg notities over deze garantie toe...","product_photo_optional": "Productfoto (optioneel)",@@ -504,6 +507,7 @@"correct_errors_in_tab": "Corrigeer de fouten in het gemarkeerde tabblad voordat u doorgaat.","please_fill_out_this_field": "Vul dit veld in.","warranty_added_successfully": "Garantie succesvol toegevoegd",+ "details_copied": "Gegevens gekopieerd. Pas aan wat verschilt en sla vervolgens op.","tag_name_required": "Tag naam is vereist","tag_creation_function_not_found": "Tag aanmaak functie niet gevonden","tag_created_successfully": "Tag succesvol aangemaakt",diff --git a/locales/pl/translation.json b/locales/pl/translation.jsonindex f028545..dce10ed 100644--- a/locales/pl/translation.json+++ b/locales/pl/translation.json@@ -140,6 +140,9 @@"other_custom": "Inne (własne)","enter_custom_warranty_type": "Wpisz własny typ gwarancji","purchase_price_optional": "Cena zakupu (opcjonalnie)",+ "purchase_price_tooltip": "Cena, którą zapłaciłeś za sam produkt, a nie koszt gwarancji. Jeśli gwarancja była dołączona do produktu, wpisz cenę produktu.",+ "duplicate_warranty": "Duplikuj gwarancję",+ "photo_url_placeholder": "Lub wklej adres URL zdjęcia","notes_optional": "Notatki (opcjonalnie)","add_any_notes": "Dodaj notatki dotyczące tej gwarancji...","product_photo_optional": "Zdjęcie produktu (opcjonalnie)",@@ -504,6 +507,7 @@"correct_errors_in_tab": "Proszę poprawić błędy w wyróżnionej zakładce przed kontynuacją.","please_fill_out_this_field": "Proszę wypełnić to pole.","warranty_added_successfully": "Gwarancja dodana pomyślnie",+ "details_copied": "Dane skopiowane. Dostosuj to, co się różni, a następnie zapisz.","tag_name_required": "Nazwa tagu jest wymagana","tag_creation_function_not_found": "Funkcja tworzenia tagu nie znaleziona","tag_created_successfully": "Tag utworzony pomyślnie",diff --git a/locales/pt/translation.json b/locales/pt/translation.jsonindex a6312f5..56c59e2 100644--- a/locales/pt/translation.json+++ b/locales/pt/translation.json@@ -144,6 +144,9 @@"other_custom": "Outro (Personalizado)","enter_custom_warranty_type": "Digite o tipo de garantia personalizado","purchase_price_optional": "Preço de Compra (Opcional)",+ "purchase_price_tooltip": "O preço que você pagou pelo produto em si, não o custo da garantia. Se a garantia estava incluída com o produto, insira o preço do produto.",+ "duplicate_warranty": "Duplicar garantia",+ "photo_url_placeholder": "Ou cole o URL de uma foto","notes_optional": "Notas (Opcional)","add_any_notes": "Adicione qualquer nota sobre esta garantia...","product_photo_optional": "Foto do Produto (Opcional)",@@ -559,6 +562,7 @@"correct_errors_in_tab": "Por favor, corrija os erros na aba destacada antes de continuar.","please_fill_out_this_field": "Por favor, preencha este campo.","warranty_added_successfully": "Garantia adicionada com sucesso",+ "details_copied": "Dados copiados. Ajuste o que for diferente e salve.","tag_name_required": "Nome da tag é obrigatório","tag_creation_function_not_found": "Função de criação de tag não encontrada","tag_created_successfully": "Tag criada com sucesso",diff --git a/locales/ru/translation.json b/locales/ru/translation.jsonindex 08c95a7..b206425 100644--- a/locales/ru/translation.json+++ b/locales/ru/translation.json@@ -150,6 +150,9 @@"other_custom": "Другой (пользовательский)","enter_custom_warranty_type": "Введите пользовательский тип гарантии","purchase_price_optional": "Цена покупки (необязательно)",+ "purchase_price_tooltip": "Цена, которую вы заплатили за сам товар, а не стоимость гарантии. Если гарантия входила в комплект товара, укажите цену товара.",+ "duplicate_warranty": "Дублировать гарантию",+ "photo_url_placeholder": "Или вставьте URL фотографии","notes_optional": "Заметки (необязательно)","add_any_notes": "Добавьте любые заметки об этой гарантии...","product_photo_optional": "Фото продукта (необязательно)",@@ -565,6 +568,7 @@"correct_errors_in_tab": "Пожалуйста, исправьте ошибки в выделенной вкладке перед продолжением.","please_fill_out_this_field": "Пожалуйста, заполните это поле.","warranty_added_successfully": "Гарантия успешно добавлена",+ "details_copied": "Данные скопированы. Измените то, что отличается, и сохраните.","tag_name_required": "Имя тега обязательно","tag_creation_function_not_found": "Функция создания тега не найдена","tag_created_successfully": "Тег успешно создан",diff --git a/locales/tr/translation.json b/locales/tr/translation.jsonindex 621b757..33d8f66 100644--- a/locales/tr/translation.json+++ b/locales/tr/translation.json@@ -163,6 +163,7 @@"correct_errors_in_tab": "Lütfen devam etmeden önce vurgulanan sekmedeki hataları düzeltin.","please_fill_out_this_field": "Lütfen bu alanı doldurun.","warranty_added_successfully": "Garanti başarıyla eklendi",+ "details_copied": "Ayrıntılar kopyalandı. Farklı olanları düzenleyip kaydedin.","tag_name_required": "Etiket adı gerekli","tag_creation_function_not_found": "Etiket oluşturma işlevi bulunamadı","tag_created_successfully": "Etiket başarıyla oluşturuldu",@@ -537,6 +538,9 @@"other_custom": "Diğer (Özel)","enter_custom_warranty_type": "Özel garanti türünü girin","purchase_price_optional": "Satın Alma Fiyatı (İsteğe Bağlı)",+ "purchase_price_tooltip": "Garanti maliyeti değil, ürünün kendisi için ödediğiniz fiyattır. Garanti ürünle birlikte verildiyse ürün fiyatını girin.",+ "duplicate_warranty": "Garantiyi kopyala",+ "photo_url_placeholder": "Veya bir fotoğraf URL'si yapıştırın","notes_optional": "Notlar (İsteğe Bağlı)","add_any_notes": "Bu garanti hakkında herhangi bir not ekleyin...","product_photo_optional": "Ürün Fotoğrafı (İsteğe Bağlı)",diff --git a/locales/uk/translation.json b/locales/uk/translation.jsonindex d9e92f5..31c375e 100644--- a/locales/uk/translation.json+++ b/locales/uk/translation.json@@ -150,6 +150,9 @@"other_custom": "Інший (користувацький)","enter_custom_warranty_type": "Введіть користувацький тип гарантії","purchase_price_optional": "Ціна покупки (необов'язково)",+ "purchase_price_tooltip": "Ціна, яку ви заплатили за сам товар, а не вартість гарантії. Якщо гарантія входила до комплекту товару, вкажіть ціну товару.",+ "duplicate_warranty": "Дублювати гарантію",+ "photo_url_placeholder": "Або вставте URL фотографії","notes_optional": "Нотатки (необов'язково)","add_any_notes": "Додайте будь-які нотатки про цю гарантію...","product_photo_optional": "Фото продукту (необов'язково)",@@ -510,6 +513,7 @@"correct_errors_in_tab": "Будь ласка, виправте помилки у виділеній вкладці перед продовженням.","please_fill_out_this_field": "Будь ласка, заповніть це поле.","warranty_added_successfully": "Гарантія успішно додана",+ "details_copied": "Дані скопійовано. Змініть те, що відрізняється, і збережіть.","tag_name_required": "Назва тегу обов'язкова","tag_creation_function_not_found": "Функція створення тегу не знайдена","tag_created_successfully": "Тег успішно створено",diff --git a/locales/zh_CN/translation.json b/locales/zh_CN/translation.jsonindex 543a632..eadb59c 100644--- a/locales/zh_CN/translation.json+++ b/locales/zh_CN/translation.json@@ -144,6 +144,9 @@"other_custom": "其他(自定义)","enter_custom_warranty_type": "输入自定义保修类型","purchase_price_optional": "购买金额(可选)",+ "purchase_price_tooltip": "您为产品本身支付的价格,而不是保修的费用。如果保修随产品附带,请输入产品的价格。",+ "duplicate_warranty": "复制保修",+ "photo_url_placeholder": "或粘贴照片链接","notes_optional": "备注(可选)","add_any_notes": "填写这条保修记录的备注...","product_photo_optional": "产品照片(可选)",@@ -504,6 +507,7 @@"correct_errors_in_tab": "请先修正高亮标签页中的错误,再继续操作。","please_fill_out_this_field": "请填写此字段。","warranty_added_successfully": "保修记录已添加",+ "details_copied": "已复制详细信息。调整不同之处,然后保存。","tag_name_required": "请输入标签名称","tag_creation_function_not_found": "未找到标签创建功能","tag_created_successfully": "标签已创建",diff --git a/locales/zh_HK/translation.json b/locales/zh_HK/translation.jsonindex 43633e7..fbe8afe 100644--- a/locales/zh_HK/translation.json+++ b/locales/zh_HK/translation.json@@ -144,6 +144,9 @@"other_custom": "其他(自訂)","enter_custom_warranty_type": "輸入自訂保養類型","purchase_price_optional": "購買價格(可選)",+ "purchase_price_tooltip": "您為產品本身支付的價格,而不是保養的費用。如果保養隨產品附帶,請輸入產品的價格。",+ "duplicate_warranty": "複製保養",+ "photo_url_placeholder": "或貼上相片連結","notes_optional": "備註(可選)","add_any_notes": "新增關於此保養的任何備註...","product_photo_optional": "產品照片(可選)",@@ -504,6 +507,7 @@"correct_errors_in_tab": "請在繼續之前更正突出顯示的分頁中的錯誤。","please_fill_out_this_field": "請填寫此欄位。","warranty_added_successfully": "保修已成功新增",+ "details_copied": "已複製詳細資訊。調整不同之處,然後儲存。","tag_name_required": "標籤名稱是必需的","tag_creation_function_not_found": "未找到標籤創建功能","tag_created_successfully": "標籤創建成功",diff --git a/tests/README.md b/tests/README.mdindex b6fe0a3..10919f3 100644--- a/tests/README.md+++ b/tests/README.md@@ -44,6 +44,10 @@ CI runs the same suite on every pull requestother users get the global-view-shared types (photo, invoice,manual) but never "other documents" or claim documents; missingfiles return a JSON 404.+- `test_photo_url.py` — product photo by URL (#207): the server+ downloads the image once and stores it like an upload; redirects are+ followed, non-images are rejected, an uploaded file wins over a URL,+ and the SSRF guard rejects non-public hosts.- `test_statistics.py` — void status drops a warranty out of TotalValue and the active counts and into the voided count (#250);Total Value counts no-currency and NULL-currency rows as thediff --git a/tests/test_photo_url.py b/tests/test_photo_url.pynew file mode 100644index 0000000..4a1c254--- /dev/null+++ b/tests/test_photo_url.py@@ -0,0 +1,135 @@+"""Product photo by URL (#207).++The server downloads the image once and stores it like an upload. The+SSRF guard rejects non-public hosts; the suite sets+ALLOW_PRIVATE_PHOTO_URLS so it can use a local throwaway server, and+one test turns the guard back on to prove it bites.+"""+import base64+import os+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import pytest++PNG_BYTES = base64.b64decode(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="+)+++class _Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ if self.path == "/photo.png":+ body, ctype = PNG_BYTES, "image/png"+ elif self.path == "/redirect":+ self.send_response(302)+ self.send_header("Location", "/photo.png")+ self.end_headers()+ return+ else:+ body, ctype = b"<html>not an image</html>", "text/html"+ self.send_response(200)+ self.send_header("Content-Type", ctype)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *args):+ pass++[email protected](scope="module")+def image_server():+ server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ yield f"http://127.0.0.1:{server.server_address[1]}"+ server.shutdown()+++def private_urls_allowed(app):+ app.config["ALLOW_PRIVATE_PHOTO_URLS"] = True+ yield+ app.config["ALLOW_PRIVATE_PHOTO_URLS"] = False+++def _photo_path(client, headers, wid):+ r = client.get("/api/warranties", headers=headers)+ items = r.get_json()+ if isinstance(items, dict):+ items = items.get("warranties", [])+ for w in items:+ if w["id"] == wid:+ return w.get("product_photo_path")+ return None+++def test_create_with_photo_url(client, user_factory, warranty_factory,+ image_server, private_urls_allowed):+ user = user_factory()+ r = warranty_factory(user["headers"],+ product_photo_url=f"{image_server}/photo.png")+ assert r.status_code == 201, r.get_data(as_text=True)+ path = _photo_path(client, user["headers"], r.get_json()["id"])+ assert path and path.endswith(".png"), path+ on_disk = os.path.join(os.environ["UPLOAD_FOLDER"], os.path.basename(path))+ assert os.path.exists(on_disk)+++def test_photo_url_follows_redirect(client, user_factory, warranty_factory,+ image_server, private_urls_allowed):+ user = user_factory()+ r = warranty_factory(user["headers"],+ product_photo_url=f"{image_server}/redirect")+ assert r.status_code == 201, r.get_data(as_text=True)+ assert _photo_path(client, user["headers"], r.get_json()["id"])+++def test_photo_url_rejects_non_image(client, user_factory, warranty_factory,+ image_server, private_urls_allowed):+ user = user_factory()+ r = warranty_factory(user["headers"],+ product_photo_url=f"{image_server}/page.html")+ assert r.status_code == 400+ assert "image" in r.get_json()["error"].lower()+++def test_photo_url_blocks_private_hosts(client, user_factory,+ warranty_factory, image_server, app):+ app.config["ALLOW_PRIVATE_PHOTO_URLS"] = False+ user = user_factory()+ r = warranty_factory(user["headers"],+ product_photo_url=f"{image_server}/photo.png")+ assert r.status_code == 400+ assert "public" in r.get_json()["error"].lower()+++def test_uploaded_file_wins_over_url(client, user_factory, warranty_factory,+ image_server, private_urls_allowed):+ import io+ user = user_factory()+ r = warranty_factory(+ user["headers"],+ product_photo_url=f"{image_server}/page.html",+ product_photo=(io.BytesIO(PNG_BYTES), "shot.png"),+ )+ assert r.status_code == 201, r.get_data(as_text=True)+ assert _photo_path(client, user["headers"], r.get_json()["id"])+++def test_update_with_photo_url(client, user_factory, warranty_factory,+ image_server, private_urls_allowed):+ user = user_factory()+ h = user["headers"]+ r = warranty_factory(h)+ assert r.status_code == 201+ wid = r.get_json()["id"]+ r = client.put(f"/api/warranties/{wid}", headers=h, data={+ "product_name": "Widget",+ "purchase_date": "2025-01-01",+ "exact_expiration_date": "2027-01-01",+ "product_photo_url": f"{image_server}/photo.png",+ })+ assert r.status_code == 200, r.get_data(as_text=True)+ assert _photo_path(client, h, wid)