π‘οΈ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Fix CSV export/import data loss and comma-tag corruption
Omega (QA)85d75e7c9e9a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 469a21b..cee6f09 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,10 @@- _Files: `backend/statistics_routes.py`, `backend/notifications.py`_- **CSV tag/serial round-trip fixed:** the frontend export joined tags and serial numbers with spaces while the import splits on commas, so re-importing an export merged multi-tag warranties into a single tag. Export now joins with `", "` to match the import.- _Files: `frontend/js/components/importExport.js`_+- **CSV export/import now round-trips all fields:** the export only wrote 13 columns, silently dropping **Notes, Currency, ModelNumber, and WarrantyType** β re-importing an export lost notes and reset currency to the user's default. Both exports (main page and status dashboard) now write 17 columns including those fields, and the importer accepts them: `Notes`, `ModelNumber`, and `WarrantyType` are stored as-is, `Currency` is validated against the supported code list (unknown codes fall back to the user's preferred currency, as before). Unknown-column files are still accepted via the optional-header mechanism.+ - _Files: `frontend/js/components/importExport.js`, `frontend/status.js`, `backend/warranties_routes.py`, `backend/statistics_routes.py`_+- **Tags/serial numbers containing commas now survive CSV round-trip:** export joined multi-value fields with `", "` and the import split naively on commas, so a tag like `sweepC,comma-tag` came back as two tags. Tags and SerialNumber cells are now JSON-encoded on export (`["a","b,c"]`); the importer parses JSON first and falls back to comma-splitting for legacy or hand-written files.+ - _Files: `frontend/js/components/importExport.js`, `frontend/status.js`, `backend/warranties_routes.py`_- **Missing English i18n keys added and all 19 non-English locales fully translated:** Static analysis of every `t('β¦')` call and `data-i18n` attribute found 66 keys (toast messages, validation errors, claims labels, tag-manager strings, the registration-disabled notice, `actions.view`, the `tags.no_selected` placeholder, and 16 `paperless.*` keys) missing from `locales/en/translation.json`. i18next renders undefined keys as raw key text, so users saw strings like `messages.deleted_successfully` in toasts. All values were taken from the inline English fallbacks already present at the call sites (with `defaultValue` fallbacks added at the call sites for graceful degradation), so default-language UX is unchanged; other languages now fall back to English instead of showing raw keys. Every key in `locales/en/translation.json` (767 keys) was then machine-translated from English (Google Translate) into all 19 non-English locales β 2,015 missing keys in total (ru 173, it 150, most others ~95β98) plus 1,194 strings that existed only as untranslated English β with `{{placeholder}}` integrity verified on every string (22 cases where the engine translated placeholder names like `{{name}}` β `{{nombre}}` were repaired; one Hindi string that dropped `{{count}}` was fixed by hand; a pre-existing Hebrew translation that dropped `{{username}}` was fixed). Short brand/technical terms (Warracker, Paperless-ngx, CSV, OIDC, URLs) were deliberately left as-is. These are machine translations β native-speaker review is recommended before relying on them for customer-facing polish.- _Files: `locales/*/translation.json`, `frontend/js/components/editModal.js`, `frontend/js/components/addWarrantyForm.js`, `frontend/js/components/tagManager.js`_- **Theme init crash on every page loading the classic script:** `script.js` called `initializeTheme()` unguarded on `DOMContentLoaded`, but `js/lib/theme.js` (the only file defining it) is never included as a classic script β it is an ES module loaded only via `js/index.js`. The call threw `initializeTheme is not defined` on about, status, register, and both reset-password pages (and index), which also silently skipped the rest of that init handler (`setupUIEventListeners()`, `setupModalTriggers()`, form wiring). The call is now guarded with `typeof initializeTheme === 'function'`; the visual theme was and is applied by `theme-loader.js` on all pages.diff --git a/backend/statistics_routes.py b/backend/statistics_routes.pyindex 38a2591..0ce6a68 100644--- a/backend/statistics_routes.py+++ b/backend/statistics_routes.py@@ -178,7 +178,7 @@ def get_statistics():id, product_name, purchase_date,warranty_duration_years, warranty_duration_months, warranty_duration_days,expiration_date, invoice_path, manual_path, other_document_path, product_url, purchase_price, is_lifetime,- model_number,+ model_number, notes, currency, vendor, warranty_type,(archived_at IS NOT NULL) AS is_archived{from_clause}{where_clause}@@ -200,6 +200,19 @@ def get_statistics():# Convert Decimal objects to float for JSON serializationif warranty.get('purchase_price') and isinstance(warranty['purchase_price'], Decimal):warranty['purchase_price'] = float(warranty['purchase_price'])++ # Serial numbers and tags (needed for the status-page CSV export)+ wid = warranty['id']+ cur.execute('SELECT serial_number FROM serial_numbers WHERE warranty_id = %s', (wid,))+ warranty['serial_numbers'] = [r[0] for r in cur.fetchall()]+ cur.execute('''+ SELECT t.id, t.name, t.color+ FROM tags t+ JOIN warranty_tags wt ON t.id = wt.tag_id+ WHERE wt.warranty_id = %s+ ORDER BY t.name+ ''', (wid,))+ warranty['tags'] = [{'id': t[0], 'name': t[1], 'color': t[2]} for t in cur.fetchall()]all_warranties_list.append(warranty)logger.info(f"Fetched {len(all_warranties_list)} total warranties.")@@ -385,7 +398,7 @@ def get_global_statistics():w.expiration_date, w.invoice_path, w.manual_path, w.other_document_path,w.product_url, w.purchase_price, w.is_lifetime,u.username, u.email, u.first_name, u.last_name,- w.model_number,+ w.model_number, w.notes, w.currency, w.vendor, w.warranty_type,(w.archived_at IS NOT NULL) AS is_archivedFROM warranties wJOIN users u ON w.user_id = u.id@@ -407,6 +420,19 @@ def get_global_statistics():# Convert Decimal objects to float for JSON serializationif warranty.get('purchase_price') and isinstance(warranty['purchase_price'], Decimal):warranty['purchase_price'] = float(warranty['purchase_price'])++ # Serial numbers and tags (needed for the status-page CSV export)+ wid = warranty['id']+ cur.execute('SELECT serial_number FROM serial_numbers WHERE warranty_id = %s', (wid,))+ warranty['serial_numbers'] = [r[0] for r in cur.fetchall()]+ cur.execute('''+ SELECT t.id, t.name, t.color+ FROM tags t+ JOIN warranty_tags wt ON t.id = wt.tag_id+ WHERE wt.warranty_id = %s+ ORDER BY t.name+ ''', (wid,))+ warranty['tags'] = [{'id': t[0], 'name': t[1], 'color': t[2]} for t in cur.fetchall()]# Add user display name for better UIfirst_name = warranty.get('first_name', '').strip() if warranty.get('first_name') else ''diff --git a/backend/warranties_routes.py b/backend/warranties_routes.pyindex e1cd6bb..e08517f 100644--- a/backend/warranties_routes.py+++ b/backend/warranties_routes.py@@ -1184,9 +1184,25 @@ def import_warranties():REQUIRED_CSV_HEADERS = ['ProductName', 'PurchaseDate']OPTIONAL_CSV_HEADERS = ['ExpirationDate', 'IsLifetime', 'PurchasePrice', 'SerialNumber', 'ProductURL', 'Tags', 'Vendor', 'WarrantyType',- 'WarrantyDurationYears', 'WarrantyDurationMonths', 'WarrantyDurationDays'+ 'WarrantyDurationYears', 'WarrantyDurationMonths', 'WarrantyDurationDays',+ 'Notes', 'Currency', 'ModelNumber',]+ def _parse_list_field(raw):+ """Parse a Tags/SerialNumber cell. New exports JSON-encode the list+ (so values containing commas round-trip); fall back to comma-split+ for hand-written or legacy files."""+ raw = (raw or '').strip()+ if not raw:+ return []+ try:+ parsed = json.loads(raw)+ if isinstance(parsed, list):+ return [str(x).strip() for x in parsed if str(x).strip()]+ except (ValueError, TypeError):+ pass+ return [x.strip() for x in raw.split(',') if x.strip()]+try:# Read the file content. utf-8-sig strips a BOM, which Excel and# other tools commonly prepend (issue #236: the first header then@@ -1243,6 +1259,9 @@ def import_warranties():vendor = row.get('Vendor', '').strip() # Extract Vendorwarranty_type = row.get('WarrantyType', '').strip() # Extract Warranty Typeexpiration_date_str = row.get('ExpirationDate', '').strip()+ notes = row.get('Notes', '').strip() or None # Extract Notes+ model_number = row.get('ModelNumber', '').strip() or None # Extract Model Number+ currency_str = row.get('Currency', '').strip().upper() # Extract Currencyif not product_name:errors.append("ProductName is required.")@@ -1328,13 +1347,13 @@ def import_warranties():else:errors.append("Either duration (Years, Months, Days) or an ExpirationDate is required unless IsLifetime is TRUE.")- # Split serial numbers- serial_numbers = [sn.strip() for sn in serial_numbers_str.split(',') if sn.strip()] if serial_numbers_str else []+ # Split serial numbers (JSON list from new exports, comma-separated legacy)+ serial_numbers = _parse_list_field(serial_numbers_str)# --- Process Tags ---tag_ids_to_link = []if tags_str:- tag_names = [name.strip() for name in tags_str.split(',') if name.strip()]+ tag_names = _parse_list_field(tags_str)if tag_names:# Find existing tag IDs (case-insensitive) for THIS USERplaceholders = ', '.join(['%s'] * len(tag_names))@@ -1443,19 +1462,40 @@ def import_warranties():except Exception as currency_err:logger.error(f"[Import] Error getting user currency preference: {currency_err}, defaulting to USD")+ # --- Resolve row currency: explicit Currency column wins when valid ---+ row_currency = user_currency_code+ if currency_str:+ # Validate against the CHECK constraint's code list+ if currency_str in (+ 'USD','EUR','GBP','JPY','CNY','INR','KRW','CHF','CAD','AUD',+ 'SEK','NOK','DKK','PLN','CZK','HUF','BGN','RON','HRK','RUB',+ 'BRL','MXN','ARS','CLP','COP','PEN','VES','ZAR','EGP','NGN',+ 'KES','GHS','MAD','TND','AED','SAR','QAR','KWD','BHD','OMR',+ 'JOD','LBP','ILS','TRY','IRR','PKR','BDT','LKR','NPR','BTN',+ 'MMK','THB','VND','LAK','KHR','MYR','SGD','IDR','PHP','TWD',+ 'HKD','MOP','KPW','MNT','KZT','UZS','KGS','TMT','AFN','AMD',+ 'AZN','GEL','MDL','UAH','BYN','RSD','MKD','ALL','BAM','ISK',+ 'FJD','PGK','SBD','TOP','VUV','WST','XPF','NZD'+ ):+ row_currency = currency_str+ else:+ logger.warning(f"[Import] Row {row_number}: unknown currency '{currency_str}', using {user_currency_code}")+# --- Insert into Database ---cur.execute("""INSERT INTO warranties (product_name, purchase_date, expiration_date,product_url, purchase_price, user_id, is_lifetime, vendor, warranty_type,- warranty_duration_years, warranty_duration_months, warranty_duration_days, currency+ warranty_duration_years, warranty_duration_months, warranty_duration_days, currency,+ notes, model_number)- VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)RETURNING id""", (product_name, purchase_date, expiration_date,product_url, purchase_price, user_id, is_lifetime, vendor, warranty_type,- warranty_duration_years, warranty_duration_months, warranty_duration_days, user_currency_code+ warranty_duration_years, warranty_duration_months, warranty_duration_days, row_currency,+ notes, model_number))warranty_id = cur.fetchone()[0]diff --git a/frontend/js/components/importExport.js b/frontend/js/components/importExport.jsindex 1a1ad0d..d5476aa 100644--- a/frontend/js/components/importExport.js+++ b/frontend/js/components/importExport.js@@ -56,15 +56,21 @@ export async function exportWarranties() {'ProductURL','Tags','Vendor',+ 'Notes',+ 'Currency',+ 'ModelNumber',+ 'WarrantyType',];let csv = `${headers.join(',')}\n`;filtered.forEach((warranty) => {+ // Tags/serials are JSON-encoded so values containing commas round-trip+ // intact; the importer falls back to comma-splitting for legacy files.const serials = Array.isArray(warranty.serial_numbers)- ? warranty.serial_numbers.filter(Boolean).join(', ')- : '';+ ? JSON.stringify(warranty.serial_numbers.filter(Boolean))+ : '[]';const tags = Array.isArray(warranty.tags)- ? warranty.tags.map((tag) => tag.name).join(', ')- : '';+ ? JSON.stringify(warranty.tags.map((tag) => tag.name))+ : '[]';const row = [warranty.product_name || '',warranty.purchase_date ? formatDateYYYYMMDD(new Date(warranty.purchase_date)) : '',@@ -79,6 +85,10 @@ export async function exportWarranties() {warranty.product_url || '',tags,warranty.vendor || '',+ warranty.notes || '',+ warranty.currency || '',+ warranty.model_number || '',+ warranty.warranty_type || '',];csv += `${row.map((field) => `"${String(field).replace(/"/g, '""')}"`).join(',')}\n`;});diff --git a/frontend/status.js b/frontend/status.jsindex 869a036..162f1d2 100644--- a/frontend/status.js+++ b/frontend/status.js@@ -574,6 +574,9 @@vendor: warranty.vendor,model_number: warranty.model_number, // include model number for searchingserial_numbers: warranty.serial_numbers || [],+ tags: warranty.tags || [],+ currency: warranty.currency || '',+ warranty_type: warranty.warranty_type || '',notes: warranty.notes,manual_path: warranty.manual_path || null,other_document_path: warranty.other_document_path || null,@@ -764,13 +767,21 @@'ProductURL','Tags','Vendor',+ 'Notes',+ 'Currency',+ 'ModelNumber',+ 'WarrantyType',];const escapeField = (field) => `"${String(field).replace(/"/g, '""')}"`;let csv = headers.join(',') + '\n';displayWarranties.forEach((warranty) => {+ // JSON-encoded so values containing commas round-trip intactconst serials = Array.isArray(warranty.serial_numbers)- ? warranty.serial_numbers.map(sn => (sn && sn.serial_number) || sn).filter(Boolean).join(', ')- : '';+ ? JSON.stringify(warranty.serial_numbers.map(sn => (sn && sn.serial_number) || sn).filter(Boolean))+ : '[]';+ const tags = Array.isArray(warranty.tags)+ ? JSON.stringify(warranty.tags.map(t => (t && t.name) || t).filter(Boolean))+ : '[]';const statusText = getWarrantyStatusInfo(warranty).text;const row = [warranty.product_name || '',@@ -784,8 +795,12 @@(warranty.purchase_price !== null && warranty.purchase_price !== undefined && warranty.purchase_price !== '') ? warranty.purchase_price : '',serials,warranty.product_url || '',- '', // Tags are not included in the statistics payload+ tags,warranty.vendor || '',+ warranty.notes || '',+ warranty.currency || '',+ warranty.model_number || '',+ warranty.warranty_type || '',];csv += row.map(escapeField).join(',') + '\n';});