🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Fixed tag, added lifetime, enhanced darkmode
sassanix11477b5c9bd3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 47649d3..1434c97 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,33 @@- Selected tags display in the add/edit warranty forms update correctly after a tag is deleted (`renderSelectedTags`, `renderEditSelectedTags`).- Added loading spinners and improved toast notifications/error messages for tag creation and deletion.++### Added+- **Lifetime Warranty Support**+ - Added lifetime warranty option for both new and existing warranties+ - Implemented database migration to add `is_lifetime` column to warranties table+ - Added lifetime warranty checkbox in add/edit warranty forms+ - Modified warranty display to show "Lifetime" instead of expiration date for lifetime warranties+ - Enhanced warranty status handling to properly manage lifetime warranties+ - Updated statistics and expiring notifications to exclude lifetime warranties+ - Added dynamic form behavior to hide warranty years input when lifetime is selected++### Changed+- **Backend API**+ - Modified warranty-related endpoints to handle lifetime warranty flag+ - Updated warranty validation to make warranty years optional for lifetime warranties+ - Enhanced warranty processing to handle lifetime warranties differently in statistics+ - Modified expiring warranty notifications to exclude lifetime warranties+ - Updated warranty retrieval to properly sort and display lifetime warranties++### UI/UX Improvements+- Added visual indicators for lifetime warranty status in all view modes (grid, list, table)+- Enhanced form validation to handle lifetime warranty scenarios+- Updated warranty summary view to clearly display lifetime warranty status+- Improved warranty filtering to properly handle lifetime warranties+- Corrected an issue where elements in Dark Mode had sharp corners instead of rounded ones like in Light Mode. Added the missing `--border-radius: 8px;` CSS variable to the `:root[data-theme="dark"]` definition in `frontend/style.css`.++## [0.9.8.9] - 2025-04-03### Addeddiff --git a/backend/app.py b/backend/app.pyindex 0a45be8..f6fc05f 100644--- a/backend/app.py+++ b/backend/app.py@@ -738,16 +738,16 @@ def reset_password():def get_warranties():conn = Nonetry:- conn = get_db_connection()user_id = request.user['id']is_admin = request.user['is_admin']+ conn = get_db_connection()with conn.cursor() as cur:# If admin, can see all warranties, otherwise only user's warrantiesif is_admin:- cur.execute('SELECT * FROM warranties ORDER BY expiration_date')+ cur.execute('SELECT * FROM warranties ORDER BY CASE WHEN is_lifetime THEN 1 ELSE 0 END, expiration_date NULLS LAST, product_name')else:- cur.execute('SELECT * FROM warranties WHERE user_id = %s ORDER BY expiration_date', (user_id,))+ cur.execute('SELECT * FROM warranties WHERE user_id = %s ORDER BY CASE WHEN is_lifetime THEN 1 ELSE 0 END, expiration_date NULLS LAST, product_name', (user_id,))warranties = cur.fetchall()columns = [desc[0] for desc in cur.description]@@ -801,18 +801,26 @@ def add_warranty():if not request.form.get('purchase_date'):return jsonify({"error": "Purchase date is required"}), 400-- try:- warranty_years = int(request.form.get('warranty_years', '0'))- if warranty_years <= 0 or warranty_years > 100: # Set reasonable limits- return jsonify({"error": "Warranty years must be between 1 and 100"}), 400- except ValueError:- return jsonify({"error": "Warranty years must be a valid number"}), 400++ # Handle lifetime warranty+ is_lifetime = request.form.get('is_lifetime', 'false').lower() == 'true'+ warranty_years = None+ expiration_date = None++ if not is_lifetime:+ if not request.form.get('warranty_years'):+ return jsonify({"error": "Warranty period (years) is required unless it's a lifetime warranty"}), 400+ try:+ warranty_years = int(request.form.get('warranty_years'))+ if warranty_years <= 0 or warranty_years > 100:+ return jsonify({"error": "Warranty years must be between 1 and 100"}), 400+ except ValueError:+ return jsonify({"error": "Warranty years must be a valid number"}), 400# Process the dataproduct_name = request.form['product_name']purchase_date_str = request.form['purchase_date']- serial_numbers = request.form.getlist('serial_numbers')+ serial_numbers = request.form.getlist('serial_numbers[]')product_url = request.form.get('product_url', '')user_id = request.user['id']@@ -837,11 +845,17 @@ def add_warranty():return jsonify({"error": "Purchase price must be a valid number"}), 400try:- purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d')+ purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d').date()except ValueError:return jsonify({"error": "Invalid date format. Use YYYY-MM-DD"}), 400- expiration_date = purchase_date + timedelta(days=warranty_years * 365)+ # Calculate expiration date only if not lifetime+ if not is_lifetime and warranty_years is not None:+ try:+ from dateutil.relativedelta import relativedelta+ expiration_date = purchase_date + relativedelta(years=warranty_years)+ except ImportError:+ expiration_date = purchase_date + timedelta(days=warranty_years * 365) # Approximate# Handle invoice file uploaddb_invoice_path = None@@ -880,10 +894,16 @@ def add_warranty():with conn.cursor() as cur:# Insert warrantycur.execute('''- INSERT INTO warranties (product_name, purchase_date, warranty_years, expiration_date, invoice_path, manual_path, product_url, purchase_price, user_id)- VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)+ INSERT INTO warranties (+ product_name, purchase_date, warranty_years, expiration_date,+ invoice_path, manual_path, product_url, purchase_price, user_id, is_lifetime+ )+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)RETURNING id- ''', (product_name, purchase_date, warranty_years, expiration_date, db_invoice_path, db_manual_path, product_url, purchase_price, user_id))+ ''', (+ product_name, purchase_date, warranty_years, expiration_date,+ db_invoice_path, db_manual_path, product_url, purchase_price, user_id, is_lifetime+ ))warranty_id = cur.fetchone()[0]# Insert serial numbers@@ -1197,56 +1217,36 @@ def get_statistics():try:conn = get_db_connection()-- # Get the user's expiring_soon_days preference- expiring_soon_days = 30 # Default value-- try:- # Check if user_preferences table exists before trying to query it- with conn.cursor() as check_cur:- check_cur.execute("""- SELECT EXISTS (- SELECT FROM information_schema.tables- WHERE table_name = 'user_preferences'- )- """)-- table_exists = check_cur.fetchone()[0]-- if table_exists:- with conn.cursor() as pref_cur:- pref_cur.execute(- """- SELECT expiring_soon_days FROM user_preferences- WHERE user_id = %s- """,- (user_id,)- )-- preference = pref_cur.fetchone()- if preference:- expiring_soon_days = preference[0]- except Exception as e:- logger.error(f"Error getting user preferences: {e}")- # Continue with default value-- # Current datetoday = date.today()- thirty_days_later = today + timedelta(days=expiring_soon_days)- ninety_days_later = today + timedelta(days=90)-- # Build the SQL query based on user role- from_clause = "FROM warranties"++ # Fetch user preference for expiring soon days+ expiring_soon_days = 30 # Default value+ try:+ with conn.cursor() as cur:+ cur.execute("SELECT expiring_soon_days FROM user_preferences WHERE user_id = %s", (user_id,))+ result = cur.fetchone()+ if result and result[0] is not None:+ expiring_soon_days = result[0]+ logger.info(f"Using custom expiring soon days: {expiring_soon_days} for user {user_id}")+ else:+ logger.info(f"Using default expiring soon days: {expiring_soon_days} for user {user_id}")+ except Exception as pref_err:+ # Log error fetching preference but continue with default+ logger.error(f"Error fetching expiring_soon_days preference for user {user_id}: {pref_err}. Using default 30 days.")++ expiring_soon_date = today + timedelta(days=expiring_soon_days)+ ninety_days_later = today + timedelta(days=90) # Keep timeline fixed or make configurable? For now, keep at 90.++ # Build base query based on role+ from_clause = "FROM warranties w"where_clause = ""- active_where = "AND"params = []-- # For non-admin users, filter by user_id+ active_where = "AND"+if not request.user.get('is_admin', False):- # For non-admin users, add join to warranty_users table- from_clause = "FROM warranties w JOIN warranty_users wu ON w.id = wu.warranty_id"- where_clause = "WHERE wu.user_id = %s"+ where_clause = "WHERE w.user_id = %s"params = [user_id]+ active_where = "AND"with conn.cursor() as cur:# Get total count@@ -1254,30 +1254,32 @@ def get_statistics():total_count = cur.fetchone()[0]logger.info(f"Total warranties: {total_count}")- # Get active count- cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} expiration_date > %s", params + [today])+ # Get active count (includes lifetime)+ cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} (w.is_lifetime = TRUE OR w.expiration_date > %s)", params + [today])active_count = cur.fetchone()[0]logger.info(f"Active warranties: {active_count}")- # Get expired count- cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} expiration_date <= %s", params + [today])+ # Get expired count (excludes lifetime)+ cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} w.is_lifetime = FALSE AND w.expiration_date <= %s", params + [today])expired_count = cur.fetchone()[0]logger.info(f"Expired warranties: {expired_count}")- # Get expiring soon count (using user preference)- cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} expiration_date > %s AND expiration_date <= %s",- params + [today, thirty_days_later])+ # Get expiring soon count (excludes lifetime) using user preference+ cur.execute(f"""SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'}+ w.is_lifetime = FALSE AND w.expiration_date > %s AND w.expiration_date <= %s""",+ params + [today, expiring_soon_date])expiring_soon_count = cur.fetchone()[0]- logger.info(f"Expiring soon warranties: {expiring_soon_count}")+ logger.info(f"Expiring soon ({expiring_soon_days} days) warranties: {expiring_soon_count}")- # Get expiration timeline (next 90 days, grouped by month)+ # Get expiration timeline (next 90 days, excluding lifetime)cur.execute(f"""SELECTEXTRACT(YEAR FROM expiration_date) as year,EXTRACT(MONTH FROM expiration_date) as month,COUNT(*) as count{from_clause}- {where_clause} {active_where if where_clause else 'WHERE'} expiration_date > %s AND expiration_date <= %s+ {where_clause} {active_where if where_clause else 'WHERE'}+ w.is_lifetime = FALSE AND w.expiration_date > %s AND w.expiration_date <= %sGROUP BY EXTRACT(YEAR FROM expiration_date), EXTRACT(MONTH FROM expiration_date)ORDER BY year, month""", params + [today, ninety_days_later])@@ -1293,17 +1295,21 @@ def get_statistics():"count": count})- # Get recent expiring warranties (30 days before and after today)- thirty_days_ago = today - timedelta(days=30)+ # Get recent expiring warranties (using user preference +/- 30 days for range, excluding lifetime)+ # We'll keep the window around today somewhat fixed for 'recent', maybe +/- 30 days is still reasonable? Or should this also use expiring_soon_days?+ # Let's adjust the recent window based on the preference for now: N days ago to N days later+ days_ago_for_recent = today - timedelta(days=expiring_soon_days)+ days_later_for_recent = expiring_soon_date # Same as the expiring soon cutoffcur.execute(f"""- SELECT- id, product_name, purchase_date, warranty_years,- expiration_date, invoice_path, manual_path, product_url, purchase_price- {from_clause}- {where_clause} {active_where if where_clause else 'WHERE'} expiration_date >= %s AND expiration_date <= %s+ SELECT+ id, product_name, purchase_date, warranty_years,+ expiration_date, invoice_path, manual_path, product_url, purchase_price, is_lifetime+ {from_clause}+ {where_clause} {active_where if where_clause else 'WHERE'}+ w.is_lifetime = FALSE AND w.expiration_date >= %s AND w.expiration_date <= %sORDER BY expiration_dateLIMIT 10- """, params + [thirty_days_ago, thirty_days_later])+ """, params + [days_ago_for_recent, days_later_for_recent])columns = [desc[0] for desc in cur.description]recent_warranties = []@@ -2236,17 +2242,13 @@ def secure_file_access(filename):return jsonify({"message": "Error accessing file"}), 500def get_expiring_warranties():- """- Query the database to find warranties that are expiring soon based on user preferences.- Returns a list of dictionaries containing the necessary information for email notifications.- """+ """Get warranties that are expiring soon for notification purposes"""conn = Nonetry:conn = get_db_connection()- with conn.cursor() as cur:- # Get today's date- today = date.today()+ today = date.today()+ with conn.cursor() as cur:cur.execute("""SELECTu.email,@@ -2261,8 +2263,9 @@ def get_expiring_warranties():LEFT JOINuser_preferences up ON u.id = up.user_idWHERE- w.expiration_date > %s- AND w.expiration_date <= %s + (COALESCE(up.expiring_soon_days, 30) || ' days')::interval+ w.is_lifetime = FALSE+ AND w.expiration_date > %s+ AND w.expiration_date <= (%s::date + (COALESCE(up.expiring_soon_days, 30) || ' days')::interval)::dateAND u.is_active = TRUEAND COALESCE(up.email_notifications, TRUE) = TRUE;""", (today, today))diff --git a/backend/migrations/011_add_lifetime_warranty.sql b/backend/migrations/011_add_lifetime_warranty.sqlnew file mode 100644index 0000000..2227fb0--- /dev/null+++ b/backend/migrations/011_add_lifetime_warranty.sql@@ -0,0 +1,15 @@+-- backend/migrations/011_add_lifetime_warranty.sql++-- Add is_lifetime column to warranties table if it doesn't exist+ALTER TABLE warranties ADD COLUMN IF NOT EXISTS is_lifetime BOOLEAN NOT NULL DEFAULT FALSE;++-- Make warranty_years nullable if it's not already+ALTER TABLE warranties ALTER COLUMN warranty_years DROP NOT NULL;++-- Make expiration_date nullable if it's not already+-- Note: expiration_date might already be nullable depending on previous migrations+-- We can ensure it is nullable like this:+ALTER TABLE warranties ALTER COLUMN expiration_date DROP NOT NULL;++-- Add an index for the new column+CREATE INDEX IF NOT EXISTS idx_is_lifetime ON warranties(is_lifetime);\ No newline at end of filediff --git a/frontend/index.html b/frontend/index.htmlindex 6142781..e190a0d 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -318,7 +318,16 @@<input type="date" id="purchaseDate" name="purchase_date" class="form-control" required></div>+ <!-- Add Lifetime Checkbox --><div class="form-group">+ <label class="lifetime-label">+ <input type="checkbox" id="isLifetime" name="is_lifetime" value="true">+ Lifetime Warranty+ </label>+ </div>+ <!-- End Lifetime Checkbox -->++ <div class="form-group" id="warrantyYearsGroup"><label for="warrantyYears">Warranty Period (Years)</label><input type="number" id="warrantyYears" name="warranty_years" class="form-control" min="1" max="100" required></div>@@ -602,7 +611,16 @@<input type="date" id="editPurchaseDate" name="purchase_date" class="form-control" required></div>+ <!-- Add Lifetime Checkbox --><div class="form-group">+ <label class="lifetime-label">+ <input type="checkbox" id="editIsLifetime" name="is_lifetime" value="true">+ Lifetime Warranty+ </label>+ </div>+ <!-- End Lifetime Checkbox -->++ <div class="form-group" id="editWarrantyYearsGroup"><label for="editWarrantyYears">Warranty Period (Years)</label><input type="number" id="editWarrantyYears" name="warranty_years" class="form-control" min="1" max="100" required></div>diff --git a/frontend/script.js b/frontend/script.jsindex ee6ac02..af9038c 100644--- a/frontend/script.js+++ b/frontend/script.js@@ -55,6 +55,14 @@ const tagManagementModal = document.getElementById('tagManagementModal');const newTagForm = document.getElementById('newTagForm');const existingTagsContainer = document.getElementById('existingTags');+// --- Add near other DOM Element declarations ---+const isLifetimeCheckbox = document.getElementById('isLifetime');+const warrantyYearsGroup = document.getElementById('warrantyYearsGroup');+const warrantyYearsInput = document.getElementById('warrantyYears');+const editIsLifetimeCheckbox = document.getElementById('editIsLifetime');+const editWarrantyYearsGroup = document.getElementById('editWarrantyYearsGroup');+const editWarrantyYearsInput = document.getElementById('editWarrantyYears');+/*** Get current user type (admin or user)* @returns {string} 'admin' or 'user'@@ -363,11 +371,19 @@ function updateSummary() {new Date(purchaseDate).toLocaleDateString() : '-';}- const warrantyYears = document.getElementById('warrantyYears')?.value;+ // --- Handle Lifetime in Summary ---+ const isLifetime = isLifetimeCheckbox ? isLifetimeCheckbox.checked : false;+ const warrantyYears = warrantyYearsInput ? warrantyYearsInput.value : null;const summaryWarrantyYears = document.getElementById('summary-warranty-years');+if (summaryWarrantyYears) {- summaryWarrantyYears.textContent = warrantyYears ?- `${warrantyYears} ${warrantyYears > 1 ? 'years' : 'year'}` : '-';+ if (isLifetime) {+ summaryWarrantyYears.textContent = 'Lifetime';+ } else if (warrantyYears) {+ summaryWarrantyYears.textContent = `${warrantyYears} ${parseInt(warrantyYears) === 1 ? 'year' : 'years'}`;+ } else {+ summaryWarrantyYears.textContent = '-';+ }}// Calculate and display expiration date@@ -759,57 +775,41 @@ function processWarrantyData(warranty) {}const today = new Date();-- // Handle purchase date- let purchaseDate = null;- if (processedWarranty.purchase_date) {- purchaseDate = new Date(processedWarranty.purchase_date);- // Check if date is valid- if (isNaN(purchaseDate.getTime())) {- purchaseDate = null;- }- }- processedWarranty.purchaseDate = purchaseDate;-- // Handle expiration date- let expirationDate = null;- if (processedWarranty.expiration_date) {- expirationDate = new Date(processedWarranty.expiration_date);- // Check if date is valid- if (isNaN(expirationDate.getTime())) {- expirationDate = null;+ today.setHours(0, 0, 0, 0); // Normalize today to midnight for accurate date comparisons++ processedWarranty.purchaseDate = processedWarranty.purchase_date ? new Date(processedWarranty.purchase_date) : null;+ processedWarranty.expirationDate = processedWarranty.expiration_date ? new Date(processedWarranty.expiration_date) : null;++ // --- Lifetime Handling ---+ if (processedWarranty.is_lifetime) {+ processedWarranty.status = 'active';+ processedWarranty.statusText = 'Lifetime';+ processedWarranty.daysRemaining = Infinity;+ } else if (processedWarranty.expirationDate && !isNaN(processedWarranty.expirationDate.getTime())) {+ // Existing logic for dated warranties+ const expirationDateOnly = new Date(processedWarranty.expirationDate);+ expirationDateOnly.setHours(0,0,0,0);++ const timeDiff = expirationDateOnly - today;+ const daysRemaining = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));+ processedWarranty.daysRemaining = daysRemaining;++ if (daysRemaining < 0) {+ processedWarranty.status = 'expired';+ processedWarranty.statusText = 'Expired';+ } else if (daysRemaining < expiringSoonDays) {+ processedWarranty.status = 'expiring';+ processedWarranty.statusText = `Expiring Soon (${daysRemaining} day${daysRemaining !== 1 ? 's' : ''})`;+ } else {+ processedWarranty.status = 'active';+ processedWarranty.statusText = `${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining`;}- }- processedWarranty.expirationDate = expirationDate;-- // Calculate days remaining only if expiration date is valid- let daysRemaining = null;- if (expirationDate && !isNaN(expirationDate.getTime())) {- daysRemaining = Math.floor((expirationDate - today) / (1000 * 60 * 60 * 24));- }-- let statusClass = 'active';- let statusText = 'Active';-- if (daysRemaining === null) {- statusClass = 'unknown';- statusText = 'Unknown status';- } else if (daysRemaining < 0) {- statusClass = 'expired';- statusText = 'Expired';- } else if (daysRemaining < expiringSoonDays) {- console.log(`Using expiringSoonDays: ${expiringSoonDays} for warranty: ${processedWarranty.product_name}`);- statusClass = 'expiring';- statusText = `Expiring Soon (${daysRemaining} days)`;} else {- statusText = `${daysRemaining} days remaining`;+ processedWarranty.status = 'unknown';+ processedWarranty.statusText = 'Unknown Status';+ processedWarranty.daysRemaining = null;}-- // Add status to warranty object- processedWarranty.status = statusClass;- processedWarranty.daysRemaining = daysRemaining;- processedWarranty.statusText = statusText;-+console.log('Processed warranty data result:', processedWarranty);return processedWarranty;}@@ -1003,13 +1003,14 @@ async function renderWarranties(warrantiesToRender) {}sortedWarranties.forEach(warranty => {- // Use the pre-processed dates from the warranty object+ // --- Use processed data ---const purchaseDate = warranty.purchaseDate;const expirationDate = warranty.expirationDate;-- // Use the pre-calculated status and days remaining from the warranty object+ const isLifetime = warranty.is_lifetime;const statusClass = warranty.status || 'unknown';- const statusText = warranty.statusText || 'Unknown status';+ const statusText = warranty.statusText || 'Unknown Status';+ const warrantyYearsText = isLifetime ? 'Lifetime' : (warranty.warranty_years !== undefined ? `${warranty.warranty_years} ${warranty.warranty_years === 1 ? 'year' : 'years'}` : 'N/A');+ const expirationDateText = isLifetime ? 'Lifetime' : formatDate(expirationDate);// Debug file pathsconsole.log(`Warranty ID ${warranty.id} - Product: ${warranty.product_name}`);@@ -1052,8 +1053,8 @@ async function renderWarranties(warrantiesToRender) {<div class="warranty-content"><div class="warranty-info"><div>Purchased: <span>${formatDate(purchaseDate)}</span></div>- <div>Warranty: <span>${warranty.warranty_years !== undefined ? `${warranty.warranty_years} ${warranty.warranty_years === 1 ? 'year' : 'years'}` : 'N/A'}</span></div>- <div>Expires: <span>${formatDate(expirationDate)}</span></div>+ <div>Warranty: <span>${warrantyYearsText}</span></div>+ <div>Expires: <span>${expirationDateText}</span></div>${warranty.purchase_price ? `<div>Price: <span>$${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}${validSerialNumbers.length > 0 ? `<div class="serial-numbers">@@ -1102,8 +1103,8 @@ async function renderWarranties(warrantiesToRender) {<div class="warranty-content"><div class="warranty-info"><div>Purchased: <span>${formatDate(purchaseDate)}</span></div>- <div>Warranty: <span>${warranty.warranty_years !== undefined ? `${warranty.warranty_years} ${warranty.warranty_years === 1 ? 'year' : 'years'}` : 'N/A'}</span></div>- <div>Expires: <span>${formatDate(expirationDate)}</span></div>+ <div>Warranty: <span>${warrantyYearsText}</span></div>+ <div>Expires: <span>${expirationDateText}</span></div>${warranty.purchase_price ? `<div>Price: <span>$${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}${validSerialNumbers.length > 0 ? `<div class="serial-numbers">@@ -1152,7 +1153,7 @@ async function renderWarranties(warrantiesToRender) {<div class="warranty-content"><div class="warranty-info"><div>Purchased: <span>${formatDate(purchaseDate)}</span></div>- <div>Expires: <span>${formatDate(expirationDate)}</span></div>+ <div>Expires: <span>${expirationDateText}</span></div></div></div><div class="warranty-status-row status-${statusClass}">@@ -1469,6 +1470,22 @@ function openEditModal(warranty) {}});});++ // --- Set Lifetime Checkbox and Toggle Years Input ---+ if (editIsLifetimeCheckbox && editWarrantyYearsGroup && editWarrantyYearsInput) {+ editIsLifetimeCheckbox.checked = warranty.is_lifetime || false;+ handleEditLifetimeChange(); // Call handler to set initial state++ // Remove previous listener if exists+ editIsLifetimeCheckbox.removeEventListener('change', handleEditLifetimeChange);+ // Add new listener+ editIsLifetimeCheckbox.addEventListener('change', handleEditLifetimeChange);++ // Set years value only if NOT lifetime+ editWarrantyYearsInput.value = warranty.is_lifetime ? '' : (warranty.warranty_years || '');+ } else {+ console.error("Lifetime warranty elements not found in edit form");+ }}function openDeleteModal(warrantyId, productName) {@@ -1526,6 +1543,15 @@ function validateFileSize(formData, maxSizeMB = 32) {function submitForm(event) {event.preventDefault();+ // --- Add Lifetime Check ---+ if (!isLifetimeCheckbox.checked && !warrantyYearsInput.value) {+ showToast('Warranty period (years) is required unless it\'s a lifetime warranty', 'error');+ switchToTab(1); // Switch to warranty details tab+ warrantyYearsInput.focus();+ warrantyYearsInput.classList.add('invalid');+ return;+ }+// Validate all tabsfor (let i = 0; i < tabContents.length; i++) {if (!validateTab(i)) {@@ -1552,6 +1578,11 @@ function submitForm(event) {formData.append('tag_ids', JSON.stringify(tagIds));}+ // --- Ensure is_lifetime is correctly added ---+ if (!isLifetimeCheckbox.checked) {+ formData.append('is_lifetime', 'false');+ }+// Show loading spinnershowLoadingSpinner();@@ -1739,6 +1770,14 @@ function initWarrantyForm() {if (warrantyForm) {warrantyForm.addEventListener('submit', submitForm);}++ // Initialize lifetime checkbox listener+ if (isLifetimeCheckbox && warrantyYearsGroup && warrantyYearsInput) {+ isLifetimeCheckbox.addEventListener('change', handleLifetimeChange);+ handleLifetimeChange(); // Initial check+ } else {+ console.error("Lifetime warranty elements not found in add form");+ }}// Initialize tag functionality@@ -2492,6 +2531,24 @@ function saveWarranty() {formData.append('manual', manualFile);}+ // --- Add Lifetime Check ---+ if (!editIsLifetimeCheckbox.checked && !editWarrantyYearsInput.value) {+ showToast('Warranty period (years) is required unless it\'s a lifetime warranty', 'error');+ // Switch to the warranty details tab in the edit modal+ const warrantyTabBtn = document.querySelector('.edit-tab-btn[data-tab="edit-warranty-details"]');+ if (warrantyTabBtn) warrantyTabBtn.click();+ editWarrantyYearsInput.focus();+ editWarrantyYearsInput.classList.add('invalid');+ return;+ }++ // --- Append is_lifetime and warranty_years ---+ const isLifetime = editIsLifetimeCheckbox.checked;+ formData.append('is_lifetime', isLifetime.toString());+ if (!isLifetime) {+ formData.append('warranty_years', editWarrantyYearsInput.value);+ }+// Get auth tokenconst token = localStorage.getItem('auth_token');if (!token) {@@ -2750,4 +2807,40 @@ function createNewTag() {.finally(() => {hideLoadingSpinner(); // Hide loading indicator});+}++// --- Add New Function ---+function handleLifetimeChange(event) {+ const checkbox = event ? event.target : isLifetimeCheckbox;+ const group = warrantyYearsGroup;+ const input = warrantyYearsInput;++ if (!checkbox || !group || !input) return;++ if (checkbox.checked) {+ group.style.display = 'none';+ input.required = false;+ input.value = '';+ } else {+ group.style.display = 'block';+ input.required = true;+ }+}++// --- Add New Function ---+function handleEditLifetimeChange(event) {+ const checkbox = event ? event.target : editIsLifetimeCheckbox;+ const group = editWarrantyYearsGroup;+ const input = editWarrantyYearsInput;++ if (!checkbox || !group || !input) return;++ if (checkbox.checked) {+ group.style.display = 'none';+ input.required = false;+ input.value = '';+ } else {+ group.style.display = 'block';+ input.required = true;+ }}\ No newline at end of filediff --git a/frontend/style.css b/frontend/style.cssindex 58593fe..045537a 100644--- a/frontend/style.css+++ b/frontend/style.css@@ -51,6 +51,7 @@--modal-background: #2d2d2d;--text-muted: #909090;--input-background: #1a1a1a;+ --border-radius: 8px; /* Added missing border radius for dark theme */}body {@@ -2937,4 +2938,35 @@ input.invalid {padding: 12px 15px;width: 20%;border-top: none;+}++/* Add near other form styles */+.lifetime-label {+ display: flex;+ align-items: center;+ gap: 8px;+ cursor: pointer;+ font-weight: 500;+ margin-bottom: 10px;+}++.lifetime-label input[type="checkbox"] {+ width: 18px;+ height: 18px;+ cursor: pointer;+ margin-right: 5px;+ accent-color: var(--primary-color);+}++/* Style for the warranty years group when hidden */+#warrantyYearsGroup[style*="display: none"],+#editWarrantyYearsGroup[style*="display: none"] {+ opacity: 0.5;+ transition: opacity 0.3s ease;+}++/* Add CSS for the tags cell in table view */+.table-view .tags-row-cell {+ display: table-cell;+ vertical-align: middle;}\ No newline at end of file