Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Add warranty expiration change history (#209)

sassanix0031a9e3dce9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 008ffc3..f3ec16a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## 1.0.8 - Unreleased
+- **Warranty expiration change history (#209):** editing a warranty's expiration date, duration, or lifetime status now records the transition (previous value, new value, timestamp, editor, and an optional reason up to 255 characters) in a new `warranty_expiry_history` table without automatically mutating dates from claims. Warranties with recorded changes show a subtle clickable history badge next to the expiration date across the dashboard and Status page, opening an Expiry History modal; the Status page detail row and the Edit Warranty modal also display the change history, and the Edit Warranty modal dynamically reveals the optional reason field only when expiration inputs are modified.
+ - _Files: `backend/migrations/056_create_warranty_expiry_history.sql`, `backend/warranties_routes.py`, `backend/statistics_routes.py`, `frontend/js/components/expiryHistory.js`, `frontend/js/components/editModal.js`, `frontend/js/components/warrantyRenderer.js`, `frontend/js/components/ui.js`, `frontend/js/controllers/warrantyListController.js`, `frontend/js/index.js`, `frontend/index.html`, `frontend/status.html`, `frontend/script.js`, `frontend/status.js`, `frontend/style.css`, `frontend/sw.js`, `locales/*/translation.json`, `tests/test_warranty_expiry_history.py`_
- **Security and Python dependency updates (#295):** Apprise moves from 2.2.0 to 2.3.0, carrying upstream security fix GHSA-rmjg-h4cf-m74j along with OAuth token redaction in debug logs, slow-attachment timeout protection, and new notification services. Authlib moves from 1.9.5 to 1.9.10 (five patch releases for the OIDC client stack), and `email-validator` moves from 2.3.0 to 2.4.0 (enforcing IDNA Bidi rules, rejecting overlong IDN domains before encoding, and fixing quoted local-part normalization).
- _Files: `backend/requirements.txt`_
- **Docker base image and BuildKit syntax refreshed (#290, #296):** the pinned `python:3.15-slim-trixie` base image digest was refreshed in both Dockerfile stages to pick up upstream Python and Debian Trixie security updates, and the BuildKit Dockerfile syntax moves from 1.28.0 to 1.29.0.
diff --git a/backend/migrations/056_create_warranty_expiry_history.sql b/backend/migrations/056_create_warranty_expiry_history.sql
new file mode 100644
index 0000000..49cbeb0
--- /dev/null
+++ b/backend/migrations/056_create_warranty_expiry_history.sql
@@ -0,0 +1,15 @@
+-- Track warranty expiration date and lifetime changes on edit (issue #209)
+CREATE TABLE IF NOT EXISTS warranty_expiry_history (
+ id SERIAL PRIMARY KEY,
+ warranty_id INTEGER NOT NULL REFERENCES warranties(id) ON DELETE CASCADE,
+ previous_expiration_date DATE,
+ new_expiration_date DATE,
+ previous_is_lifetime BOOLEAN NOT NULL DEFAULT FALSE,
+ new_is_lifetime BOOLEAN NOT NULL DEFAULT FALSE,
+ reason VARCHAR(255),
+ changed_by_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
+ changed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE INDEX IF NOT EXISTS idx_warranty_expiry_history_warranty
+ ON warranty_expiry_history (warranty_id, changed_at DESC, id DESC);
diff --git a/backend/statistics_routes.py b/backend/statistics_routes.py
index a05d4d1..4ffd71d 100644
--- a/backend/statistics_routes.py
+++ b/backend/statistics_routes.py
@@ -226,7 +226,8 @@ def get_statistics():
expiration_date, invoice_path, manual_path, other_document_path, product_url, purchase_price, is_lifetime,
model_number, notes, currency, vendor, warranty_type,
(archived_at IS NOT NULL) AS is_archived,
- (voided_at IS NOT NULL) AS is_voided
+ (voided_at IS NOT NULL) AS is_voided,
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
{from_clause}
{where_clause}
ORDER BY expiration_date DESC
@@ -457,7 +458,8 @@ def get_global_statistics():
u.username, u.email, u.first_name, u.last_name,
w.model_number, w.notes, w.currency, w.vendor, w.warranty_type,
(w.archived_at IS NOT NULL) AS is_archived,
- (w.voided_at IS NOT NULL) AS is_voided
+ (w.voided_at IS NOT NULL) AS is_voided,
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
FROM warranties w
JOIN users u ON w.user_id = u.id
ORDER BY w.expiration_date DESC
diff --git a/backend/warranties_routes.py b/backend/warranties_routes.py
index 1784d5a..336b003 100644
--- a/backend/warranties_routes.py
+++ b/backend/warranties_routes.py
@@ -402,7 +402,8 @@ def get_warranties():
WHEN COUNT(c.id) = 0 THEN 'NO_CLAIMS'
WHEN BOOL_OR(c.status IN ('Submitted', 'In Progress')) THEN 'OPEN'
ELSE 'FINISHED'
- END AS claim_status_summary
+ END AS claim_status_summary,
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
FROM warranties w
LEFT JOIN warranty_claims c ON w.id = c.warranty_id
WHERE w.user_id = %s AND w.archived_at IS NULL
@@ -471,7 +472,8 @@ def get_archived_warranties():
WHEN COUNT(c.id) = 0 THEN 'NO_CLAIMS'
WHEN BOOL_OR(c.status IN ('Submitted', 'In Progress')) THEN 'OPEN'
ELSE 'FINISHED'
- END AS claim_status_summary
+ END AS claim_status_summary,
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
FROM warranties w
LEFT JOIN warranty_claims c ON w.id = c.warranty_id
WHERE w.user_id = %s AND w.archived_at IS NOT NULL
@@ -1067,13 +1069,15 @@ def update_warranty(warranty_id):
with conn.cursor() as cur:
# Check if warranty exists and belongs to the user
if is_admin:
- cur.execute('SELECT id, currency FROM warranties WHERE id = %s', (warranty_id,))
+ cur.execute('SELECT id, currency, expiration_date, is_lifetime FROM warranties WHERE id = %s', (warranty_id,))
else:
- cur.execute('SELECT id, currency FROM warranties WHERE id = %s AND user_id = %s', (warranty_id, user_id))
+ cur.execute('SELECT id, currency, expiration_date, is_lifetime FROM warranties WHERE id = %s AND user_id = %s', (warranty_id, user_id))
warranty = cur.fetchone()
if not warranty:
return jsonify({"error": "Warranty not found or you don't have permission to update it"}), 404
existing_currency = warranty[1] if len(warranty) > 1 else None
+ existing_expiration_date = warranty[2] if len(warranty) > 2 else None
+ existing_is_lifetime = bool(warranty[3]) if len(warranty) > 3 else False
# --- PATCH: Support JSON-only notes update ---
if request.is_json and 'notes' in request.json and len(request.json) == 1:
@@ -1093,6 +1097,11 @@ def update_warranty(warranty_id):
if len(serial_number) > 255:
return jsonify({"error": "Serial number must be 255 characters or less",
"code": "serial_number_too_long"}), 400
+ raw_expiry_reason = request.form.get('expiry_change_reason')
+ expiry_change_reason = raw_expiry_reason.strip() if raw_expiry_reason else None
+ if expiry_change_reason and len(expiry_change_reason) > 255:
+ return jsonify({"error": "Expiry change reason must be 255 characters or less",
+ "code": "expiry_change_reason_too_long"}), 400
if not request.form.get('purchase_date'):
return jsonify({"error": "Purchase date is required"}), 400
logger.info(f"Received update request for warranty {warranty_id}")
@@ -1493,6 +1502,29 @@ def update_warranty(warranty_id):
cur.execute(update_sql, sql_values)
logger.info(f"Updated warranty with SQL: {update_sql}")
logger.info(f"Parameters: {sql_values}")
+
+ # Record expiration date or lifetime transitions (issue #209)
+ if existing_expiration_date != expiration_date or existing_is_lifetime != bool(is_lifetime):
+ cur.execute('''
+ INSERT INTO warranty_expiry_history (
+ warranty_id,
+ previous_expiration_date,
+ new_expiration_date,
+ previous_is_lifetime,
+ new_is_lifetime,
+ reason,
+ changed_by_user_id
+ )
+ VALUES (%s, %s, %s, %s, %s, %s, %s)
+ ''', (
+ warranty_id,
+ existing_expiration_date,
+ expiration_date,
+ existing_is_lifetime,
+ bool(is_lifetime),
+ expiry_change_reason,
+ user_id,
+ ))
# Update serial numbers
cur.execute('DELETE FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))
@@ -2023,7 +2055,8 @@ def get_all_warranties():
WHEN COUNT(c.id) = 0 THEN 'NO_CLAIMS'
WHEN BOOL_OR(c.status IN ('Submitted', 'In Progress')) THEN 'OPEN'
ELSE 'FINISHED'
- END AS claim_status_summary
+ END AS claim_status_summary,
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
FROM warranties w
JOIN users u ON w.user_id = u.id
LEFT JOIN warranty_claims c ON w.id = c.warranty_id
@@ -2137,7 +2170,8 @@ def get_global_warranties():
WHERE c.warranty_id = w.id
) THEN 'FINISHED'
ELSE 'NO_CLAIMS'
- END AS claim_status_summary
+ END AS claim_status_summary,
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
FROM warranties w
JOIN users u ON w.user_id = u.id
WHERE w.archived_at IS NULL
@@ -2250,7 +2284,8 @@ def get_global_warranties_archived():
WHERE c.warranty_id = w.id
) THEN 'FINISHED'
ELSE 'NO_CLAIMS'
- END AS claim_status_summary
+ END AS claim_status_summary,
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
FROM warranties w
JOIN users u ON w.user_id = u.id
WHERE w.archived_at IS NOT NULL
@@ -2448,7 +2483,8 @@ def get_warranty_debug(warranty_id):
w.product_url, w.notes, w.purchase_price, w.user_id, w.created_at, w.updated_at, w.is_lifetime,
w.vendor, w.warranty_type, w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days,
w.product_photo_path, w.currency, w.paperless_invoice_id, w.paperless_manual_id, w.paperless_photo_id, w.paperless_other_id,
- u.username, u.email, u.first_name, u.last_name
+ u.username, u.email, u.first_name, u.last_name,
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
FROM warranties w
JOIN users u ON w.user_id = u.id
WHERE w.id = %s
@@ -2459,7 +2495,8 @@ def get_warranty_debug(warranty_id):
w.product_url, w.notes, w.purchase_price, w.user_id, w.created_at, w.updated_at, w.is_lifetime,
w.vendor, w.warranty_type, w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days,
w.product_photo_path, w.currency, w.paperless_invoice_id, w.paperless_manual_id, w.paperless_photo_id, w.paperless_other_id,
- u.username, u.email, u.first_name, u.last_name
+ u.username, u.email, u.first_name, u.last_name,
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
FROM warranties w
JOIN users u ON w.user_id = u.id
WHERE w.id = %s AND w.user_id = %s
@@ -2522,6 +2559,93 @@ def get_warranty_debug(warranty_id):
if conn:
release_db_connection(conn)
+
+@warranties_bp.route('/warranties/<int:warranty_id>/expiry-history', methods=['GET'])
+@token_required
+def get_warranty_expiry_history(warranty_id):
+ """Get recorded expiration date / lifetime changes for a warranty (issue #209)."""
+ conn = None
+ try:
+ user_id = request.user['id']
+ is_admin = request.user.get('is_admin', False)
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Match get_warranty_debug access rules: owner, admin, or any
+ # authenticated user when global view is enabled and not admin-only.
+ can_view_all = is_admin
+ if not is_admin:
+ cur.execute(
+ "SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')"
+ )
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+ global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'
+ admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'
+ can_view_all = global_view_enabled and not admin_only
+
+ if can_view_all:
+ cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
+ else:
+ cur.execute(
+ 'SELECT id FROM warranties WHERE id = %s AND user_id = %s',
+ (warranty_id, user_id),
+ )
+ if not cur.fetchone():
+ return jsonify({"error": "Warranty not found or access denied"}), 404
+
+ cur.execute('''
+ SELECT
+ h.id,
+ h.warranty_id,
+ h.previous_expiration_date,
+ h.new_expiration_date,
+ h.previous_is_lifetime,
+ h.new_is_lifetime,
+ h.reason,
+ h.changed_at,
+ u.first_name,
+ u.last_name,
+ u.username
+ FROM warranty_expiry_history h
+ LEFT JOIN users u ON h.changed_by_user_id = u.id
+ WHERE h.warranty_id = %s
+ ORDER BY h.changed_at DESC, h.id DESC
+ ''', (warranty_id,))
+
+ history = []
+ for row in cur.fetchall():
+ first_name = row[8].strip() if row[8] else ''
+ last_name = row[9].strip() if row[9] else ''
+ username = row[10].strip() if row[10] else ''
+ if first_name and last_name:
+ changed_by = f"{first_name} {last_name}"
+ elif first_name:
+ changed_by = first_name
+ elif username:
+ changed_by = username
+ else:
+ changed_by = None
+
+ history.append({
+ 'id': row[0],
+ 'warranty_id': row[1],
+ 'previous_expiration_date': row[2].isoformat() if row[2] else None,
+ 'new_expiration_date': row[3].isoformat() if row[3] else None,
+ 'previous_is_lifetime': bool(row[4]),
+ 'new_is_lifetime': bool(row[5]),
+ 'reason': row[6],
+ 'changed_at': row[7].isoformat() if row[7] else None,
+ 'changed_by': changed_by,
+ })
+
+ return jsonify(history), 200
+ except Exception as e:
+ logger.error(f"Error retrieving expiry history for warranty {warranty_id}: {e}")
+ return jsonify({"error": "Failed to retrieve expiry history"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
@warranties_bp.route('/timezones', methods=['GET'])
@token_required
def get_timezones():
diff --git a/frontend/index.html b/frontend/index.html
index 97af4e0..08f863e 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -896,6 +896,18 @@
<input type="date" id="editExactExpirationDate" name="exact_expiration_date" class="form-control">
</div>
</div>
+
+ <div class="form-group expiry-reason-group" id="editExpiryChangeReasonGroup" style="display: none;">
+ <label for="editExpiryChangeReason" data-i18n="warranties.expiry_change_reason_label">Reason for Expiry Change (Optional)</label>
+ <input type="text" id="editExpiryChangeReason" name="expiry_change_reason" class="form-control" maxlength="255" data-i18n-placeholder="warranties.expiry_change_reason_placeholder" placeholder="e.g. Extended after repair claim, manufacturer goodwill...">
+ </div>
+
+ <div class="form-group expiry-history-section" id="editExpiryHistorySection" style="display: none;">
+ <details class="expiry-history-details" id="editExpiryHistoryDetails">
+ <summary id="editExpiryHistorySummary" data-i18n="warranties.expiry_history_title">Expiry History</summary>
+ <div id="editExpiryHistoryContent" class="expiry-history-content"></div>
+ </details>
+ </div>
<div class="form-group">
<label for="editWarrantyType" data-i18n="warranties.warranty_type_optional">Warranty Type (Optional)</label>
diff --git a/frontend/js/components/editModal.js b/frontend/js/components/editModal.js
index e5350ef..d4e81e0 100644
--- a/frontend/js/components/editModal.js
+++ b/frontend/js/components/editModal.js
@@ -6,6 +6,7 @@ import { loadWarranties, applyFilters } from '../controllers/warrantyListControl
import { getCurrentWarrantyId, setCurrentWarrantyId, getEditSelectedTags, setEditSelectedTags } from '../store.js';
import { renderEditTagsList, renderEditSelectedTags, loadTags, openTagManagementModal } from './tagManager.js';
import { loadCurrencies } from '../lib/currency.js';
+import { initEditExpiryTracking, getEditExpiryChangeReason } from './expiryHistory.js';
function createElement(tag, className, text) {
const el = document.createElement(tag);
@@ -483,6 +484,7 @@ function fillWarrantyFields(warranty) {
}
applyLifetimeState();
applyWarrantyMethodState();
+ initEditExpiryTracking(warranty);
const typeSelect = document.getElementById('editWarrantyType');
const customInput = document.getElementById('editWarrantyTypeCustom');
if (typeSelect) {
@@ -689,6 +691,10 @@ export async function saveWarranty() {
formData.append('warranty_duration_months', 0);
formData.append('warranty_duration_days', 0);
}
+ const expiryChangeReason = getEditExpiryChangeReason();
+ if (expiryChangeReason) {
+ formData.append('expiry_change_reason', expiryChangeReason);
+ }
// Notes and misc fields
const notes = (document.getElementById('editNotes') || {}).value || '';
diff --git a/frontend/js/components/expiryHistory.js b/frontend/js/components/expiryHistory.js
new file mode 100644
index 0000000..ae079d6
--- /dev/null
+++ b/frontend/js/components/expiryHistory.js
@@ -0,0 +1,416 @@
+// Expiry history modal, list renderer, and edit-modal helper (issue #209)
+// Builds all user-controlled content via DOM nodes and textContent (XSS-safe).
+import { formatDate } from '../lib/dates.js';
+
+function t(key, fallback, options) {
+ try {
+ if (window.i18next && typeof window.i18next.t === 'function') {
+ const translated = window.i18next.t(key, options);
+ if (translated && translated !== key) {
+ return translated;
+ }
+ }
+ } catch (error) {
+ console.warn('[expiryHistory] failed to translate', key, error);
+ }
+ if (options && typeof fallback === 'string') {
+ return fallback.replace(/\{\{(\w+)\}\}/g, (_, k) => (options[k] !== undefined ? String(options[k]) : ''));
+ }
+ return fallback;
+}
+
+function getToken() {
+ if (window.auth && typeof window.auth.getToken === 'function') {
+ return window.auth.getToken();
+ }
+ return localStorage.getItem('auth_token');
+}
+
+function formatExpiryValue(dateStr, isLifetime) {
+ if (isLifetime) {
+ return t('warranties.lifetime', 'Lifetime');
+ }
+ if (!dateStr) {
+ return t('warranties.na', 'N/A');
+ }
+ return formatDate(dateStr);
+}
+
+function clearElement(el) {
+ if (!el) return;
+ while (el.firstChild) {
+ el.removeChild(el.firstChild);
+ }
+}
+
+export async function fetchExpiryHistory(warrantyId) {
+ const token = getToken();
+ const headers = {};
+ if (token) {
+ headers.Authorization = `Bearer ${token}`;
+ }
+ const response = await fetch(`/api/warranties/${encodeURIComponent(warrantyId)}/expiry-history`, {
+ headers,
+ });
+ if (!response.ok) {
+ let message = t('warranties.expiry_history_load_error', 'Failed to load expiry history.');
+ try {
+ const data = await response.json();
+ if (data && data.error) message = data.error;
+ } catch {
+ // ignore JSON parse failure
+ }
+ throw new Error(message);
+ }
+ return response.json();
+}
+
+export function renderExpiryHistoryList(container, entries) {
+ if (!container) return;
+ clearElement(container);
+
+ if (!Array.isArray(entries) || entries.length === 0) {
+ const empty = document.createElement('p');
+ empty.className = 'expiry-history-empty';
+ empty.textContent = t('warranties.expiry_history_empty', 'No expiration date changes recorded.');
+ container.appendChild(empty);
+ return;
+ }
+
+ const list = document.createElement('ul');
+ list.className = 'expiry-history-list';
+
+ entries.forEach((entry) => {
+ const item = document.createElement('li');
+ item.className = 'expiry-history-item';
+
+ const transition = document.createElement('div');
+ transition.className = 'expiry-history-transition';
+
+ const prevSpan = document.createElement('span');
+ prevSpan.className = 'expiry-history-date expiry-history-prev';
+ prevSpan.textContent = formatExpiryValue(entry.previous_expiration_date, entry.previous_is_lifetime);
+
+ const arrowSpan = document.createElement('span');
+ arrowSpan.className = 'expiry-history-arrow';
+ arrowSpan.setAttribute('aria-hidden', 'true');
+ arrowSpan.textContent = '→';
+
+ const nextSpan = document.createElement('span');
+ nextSpan.className = 'expiry-history-date expiry-history-new';
+ nextSpan.textContent = formatExpiryValue(entry.new_expiration_date, entry.new_is_lifetime);
+
+ transition.appendChild(prevSpan);
+ transition.appendChild(arrowSpan);
+ transition.appendChild(nextSpan);
+ item.appendChild(transition);
+
+ if (entry.reason && String(entry.reason).trim() !== '') {
+ const reasonEl = document.createElement('div');
+ reasonEl.className = 'expiry-history-reason';
+ reasonEl.textContent = String(entry.reason);
+ item.appendChild(reasonEl);
+ }
+
+ const metaEl = document.createElement('div');
+ metaEl.className = 'expiry-history-meta';
+ const changedDate = entry.changed_at ? formatDate(entry.changed_at) : t('warranties.na', 'N/A');
+ if (entry.changed_by) {
+ metaEl.textContent = t(
+ 'warranties.expiry_history_changed_on_by',
+ 'Changed on {{date}} by {{user}}',
+ { date: changedDate, user: entry.changed_by },
+ );
+ } else {
+ metaEl.textContent = t(
+ 'warranties.expiry_history_changed_on',
+ 'Changed on {{date}}',
+ { date: changedDate },
+ );
+ }
+ item.appendChild(metaEl);
+
+ list.appendChild(item);
+ });
+
+ container.appendChild(list);
+}
+
+let modalDom = null;
+let modalRequestToken = 0;
+
+function ensureModal() {
+ let modal = document.getElementById('expiryHistoryModal');
+ if (!modal) {
+ modal = document.createElement('div');
+ modal.id = 'expiryHistoryModal';
+ modal.className = 'modal-backdrop';
+
+ const dialog = document.createElement('div');
+ dialog.className = 'modal expiry-history-modal';
+
+ const header = document.createElement('div');
+ header.className = 'modal-header';
+
+ const titleWrap = document.createElement('div');
+ titleWrap.className = 'expiry-history-header-titles';
+
+ const title = document.createElement('h3');
+ title.className = 'modal-title';
+ title.id = 'expiryHistoryModalTitle';
+
+ const subtitle = document.createElement('div');
+ subtitle.className = 'expiry-history-modal-subtitle';
+ subtitle.id = 'expiryHistoryModalSubtitle';
+
+ titleWrap.appendChild(title);
+ titleWrap.appendChild(subtitle);
+
+ const closeBtn = document.createElement('button');
+ closeBtn.type = 'button';
+ closeBtn.className = 'close-btn';
+ closeBtn.id = 'closeExpiryHistoryModal';
+ closeBtn.setAttribute('aria-label', t('actions.close', 'Close'));
+ closeBtn.textContent = '×';
+
+ header.appendChild(titleWrap);
+ header.appendChild(closeBtn);
+
+ const body = document.createElement('div');
+ body.className = 'modal-body';
+ body.id = 'expiryHistoryModalBody';
+
+ const footer = document.createElement('div');
+ footer.className = 'modal-footer';
+
+ const closeFooterBtn = document.createElement('button');
+ closeFooterBtn.type = 'button';
+ closeFooterBtn.className = 'btn btn-secondary';
+ closeFooterBtn.id = 'closeExpiryHistoryFooterBtn';
+ closeFooterBtn.textContent = t('actions.close', 'Close');
+
+ footer.appendChild(closeFooterBtn);
+
+ dialog.appendChild(header);
+ dialog.appendChild(body);
+ dialog.appendChild(footer);
+ modal.appendChild(dialog);
+ document.body.appendChild(modal);
+ }
+
+ modalDom = {
+ modal,
+ title: document.getElementById('expiryHistoryModalTitle'),
+ subtitle: document.getElementById('expiryHistoryModalSubtitle'),
+ body: document.getElementById('expiryHistoryModalBody'),
+ closeBtn: document.getElementById('closeExpiryHistoryModal'),
+ closeFooterBtn: document.getElementById('closeExpiryHistoryFooterBtn'),
+ };
+
+ if (!modal._expiryHistoryBound) {
+ modalDom.closeBtn?.addEventListener('click', closeExpiryHistoryModal);
+ modalDom.closeFooterBtn?.addEventListener('click', closeExpiryHistoryModal);
+ modal.addEventListener('click', (event) => {
+ if (event.target === modal) closeExpiryHistoryModal();
+ });
+ document.addEventListener('keydown', (event) => {
+ if (event.key === 'Escape' && modal.classList.contains('active')) {
+ closeExpiryHistoryModal();
+ }
+ });
+ modal._expiryHistoryBound = true;
+ }
+
+ return modalDom;
+}
+
+export function closeExpiryHistoryModal() {
+ if (modalDom && modalDom.modal) {
+ modalDom.modal.classList.remove('active');
+ }
+}
+
+export async function openExpiryHistoryModal(warrantyOrId) {
+ const dom = ensureModal();
+ const warranty = warrantyOrId && typeof warrantyOrId === 'object' ? warrantyOrId : null;
+ const warrantyId = warranty ? warranty.id : parseInt(warrantyOrId, 10);
+ if (!Number.isFinite(warrantyId)) return;
+
+ if (dom.title) {
+ dom.title.textContent = t('warranties.expiry_history_title', 'Expiry History');
+ }
+ if (dom.subtitle) {
+ dom.subtitle.textContent = warranty && warranty.product_name ? String(warranty.product_name) : '';
+ dom.subtitle.style.display = dom.subtitle.textContent ? '' : 'none';
+ }
+ if (dom.closeFooterBtn) {
+ dom.closeFooterBtn.textContent = t('actions.close', 'Close');
+ }
+
+ clearElement(dom.body);
+ const loadingEl = document.createElement('p');
+ loadingEl.className = 'expiry-history-loading';
+ loadingEl.textContent = t('warranties.expiry_history_loading', 'Loading expiry history...');
+ dom.body.appendChild(loadingEl);
+ dom.modal.classList.add('active');
+
+ const currentToken = ++modalRequestToken;
+ try {
+ const entries = await fetchExpiryHistory(warrantyId);
+ if (currentToken !== modalRequestToken) return;
+ renderExpiryHistoryList(dom.body, entries);
+ } catch (error) {
+ if (currentToken !== modalRequestToken) return;
+ clearElement(dom.body);
+ const errorEl = document.createElement('p');
+ errorEl.className = 'expiry-history-error';
+ errorEl.textContent = error && error.message
+ ? error.message
+ : t('warranties.expiry_history_load_error', 'Failed to load expiry history.');
+ dom.body.appendChild(errorEl);
+ }
+}
+
+// --- Edit Modal helpers (shared by editModal.js and legacy script.js) ---
+
+let editExpiryBaseline = null;
+let editHistoryRequestToken = 0;
+
+function readCurrentEditExpiryState() {
+ const purchaseDate = (document.getElementById('editPurchaseDate') || {}).value || '';
+ const isLifetime = !!(document.getElementById('editIsLifetime') || {}).checked;
+ const exactRadio = document.getElementById('editExactDateMethod');
+ const useExact = !isLifetime && !!(exactRadio && exactRadio.checked);
+ const years = parseInt((document.getElementById('editWarrantyDurationYears') || {}).value || '0', 10) || 0;
+ const months = parseInt((document.getElementById('editWarrantyDurationMonths') || {}).value || '0', 10) || 0;
+ const days = parseInt((document.getElementById('editWarrantyDurationDays') || {}).value || '0', 10) || 0;
+ const exactDate = (document.getElementById('editExactExpirationDate') || {}).value || '';
+ return { purchaseDate, isLifetime, useExact, years, months, days, exactDate };
+}
+
+export function hasEditExpiryChanged() {
+ if (!editExpiryBaseline) return false;
+ const current = readCurrentEditExpiryState();
+ if (editExpiryBaseline.isLifetime && current.isLifetime) {
+ return false;
+ }
+ if (editExpiryBaseline.isLifetime !== current.isLifetime) {
+ return true;
+ }
+ if (editExpiryBaseline.useExact !== current.useExact) {
+ return true;
+ }
+ if (current.useExact) {
+ return current.exactDate !== editExpiryBaseline.exactDate;
+ }
+ return (
+ current.purchaseDate !== editExpiryBaseline.purchaseDate ||
+ current.years !== editExpiryBaseline.years ||
+ current.months !== editExpiryBaseline.months ||
+ current.days !== editExpiryBaseline.days
+ );
+}
+
+export function updateEditExpiryReasonVisibility() {
+ const group = document.getElementById('editExpiryChangeReasonGroup');
+ if (!group) return;
+ group.style.display = hasEditExpiryChanged() ? 'block' : 'none';
+}
+
+export function bindEditExpiryReasonInputs() {
+ const ids = [
+ 'editPurchaseDate',
+ 'editIsLifetime',
+ 'editDurationMethod',
+ 'editExactDateMethod',
+ 'editWarrantyDurationYears',
+ 'editWarrantyDurationMonths',
+ 'editWarrantyDurationDays',
+ 'editExactExpirationDate',
+ ];
+ ids.forEach((id) => {
+ const el = document.getElementById(id);
+ if (!el || el._expiryReasonBound) return;
+ el.addEventListener('change', updateEditExpiryReasonVisibility);
+ el.addEventListener('input', updateEditExpiryReasonVisibility);
+ el._expiryReasonBound = true;
+ });
+}
+
+export function initEditExpiryTracking(warranty) {
+ bindEditExpiryReasonInputs();
+ editExpiryBaseline = readCurrentEditExpiryState();
+ const reasonInput = document.getElementById('editExpiryChangeReason');
+ if (reasonInput) reasonInput.value = '';
+ updateEditExpiryReasonVisibility();
+ loadEditModalExpiryHistory(warranty);
+}
+
+export function getEditExpiryChangeReason() {
+ if (!hasEditExpiryChanged()) return '';
+ const input = document.getElementById('editExpiryChangeReason');
+ return input ? (input.value || '').trim() : '';
+}
+
+export async function loadEditModalExpiryHistory(warranty) {
+ const section = document.getElementById('editExpiryHistorySection');
+ const details = document.getElementById('editExpiryHistoryDetails');
+ const summary = document.getElementById('editExpiryHistorySummary');
+ const content = document.getElementById('editExpiryHistoryContent');
+ if (!section || !content) return;
+
+ const count = Number(warranty && warranty.expiry_change_count) || 0;
+ const currentToken = ++editHistoryRequestToken;
+
+ if (!warranty || !warranty.id || count <= 0) {
+ section.style.display = 'none';
+ if (details) details.open = false;
+ clearElement(content);
+ return;
+ }
+
+ section.style.display = 'block';
+ if (details) details.open = false;
+ if (summary) {
+ summary.textContent = t(
+ 'warranties.expiry_history_count_title',
+ 'Expiry History ({{count}})',
+ { count },
+ );
+ }
+ clearElement(content);
+ const loading = document.createElement('p');
+ loading.className = 'expiry-history-loading';
+ loading.textContent = t('warranties.expiry_history_loading', 'Loading expiry history...');
+ content.appendChild(loading);
+
+ try {
+ const entries = await fetchExpiryHistory(warranty.id);
+ if (currentToken !== editHistoryRequestToken) return;
+ renderExpiryHistoryList(content, entries);
+ } catch (error) {
+ if (currentToken !== editHistoryRequestToken) return;
+ clearElement(content);
+ const errorEl = document.createElement('p');
+ errorEl.className = 'expiry-history-error';
+ errorEl.textContent = error && error.message
+ ? error.message
+ : t('warranties.expiry_history_load_error', 'Failed to load expiry history.');
+ content.appendChild(errorEl);
+ }
+}
+
+export function init() {
+ if (typeof window !== 'undefined') {
+ window.openExpiryHistoryModal = openExpiryHistoryModal;
+ window.closeExpiryHistoryModal = closeExpiryHistoryModal;
+ window.fetchExpiryHistory = fetchExpiryHistory;
+ window.renderExpiryHistoryList = renderExpiryHistoryList;
+ window.initEditExpiryTracking = initEditExpiryTracking;
+ window.getEditExpiryChangeReason = getEditExpiryChangeReason;
+ window.updateEditExpiryReasonVisibility = updateEditExpiryReasonVisibility;
+ }
+}
+
+// Auto-expose on window when loaded directly as a module (e.g. status.html)
+init();
diff --git a/frontend/js/components/ui.js b/frontend/js/components/ui.js
index 6fecd8b..4d8443c 100644
--- a/frontend/js/components/ui.js
+++ b/frontend/js/components/ui.js
@@ -49,6 +49,7 @@ export function hideLoadingSpinner() {
// backend gains them; unknown codes fall back to the English message.
const API_ERROR_KEYS = {
product_name_too_long: 'messages.product_name_too_long',
+ expiry_change_reason_too_long: 'messages.expiry_change_reason_too_long',
// Reuses the existing client-side key (same meaning, already translated)
expiration_before_purchase: 'messages.expiration_date_after_purchase_date',
invalid_claim_status: 'messages.invalid_claim_status',
diff --git a/frontend/js/components/warrantyRenderer.js b/frontend/js/components/warrantyRenderer.js
index 3c8fbaa..0ba0c60 100644
--- a/frontend/js/components/warrantyRenderer.js
+++ b/frontend/js/components/warrantyRenderer.js
@@ -478,12 +478,24 @@ function buildPhotoHtml(warranty, view) {
`;
}
+function buildExpiryHistoryBadge(warranty) {
+ const count = Number(warranty && warranty.expiry_change_count) || 0;
+ if (count <= 0) return '';
+ const tooltip = t(
+ 'warranties.expiry_history_tooltip',
+ 'Expiry changed {{count}} time(s) — click to view history',
+ { count },
+ );
+ return ` <button type="button" class="expiry-history-badge" data-id="${warranty.id}" title="${escapeHtml(tooltip)}" aria-label="${escapeHtml(tooltip)}"><i class="fas fa-history" aria-hidden="true"></i><span>${count}</span></button>`;
+}
+
function buildInfoBlock(warranty, { userInfoHtml, productAge, warrantyDurationText, expirationDateText, priceHtml, serialsHtml }) {
+ const expiryHistoryBadge = buildExpiryHistoryBadge(warranty);
const pieces = [
userInfoHtml,
`<div><i class="fas fa-calendar"></i> ${t('warranties.age', 'Age')}: <span>${productAge}</span></div>`,
`<div><i class="fas fa-file-alt"></i> ${t('warranties.warranty', 'Warranty')}: <span>${warrantyDurationText}</span></div>`,
- `<div><i class="fas fa-wrench"></i> ${t('warranties.warranty_ends', 'Warranty Ends')}: <span>${expirationDateText}</span></div>`,
+ `<div class="warranty-ends-row"><i class="fas fa-wrench"></i> ${t('warranties.warranty_ends', 'Warranty Ends')}: <span>${expirationDateText}</span>${expiryHistoryBadge}</div>`,
priceHtml,
serialsHtml,
warranty.model_number ? `<div><i class="fas fa-tag"></i> ${t('warranties.model_number', 'Model Number')}: <span>${escapeHtml(warranty.model_number)}</span></div>` : '',
diff --git a/frontend/js/controllers/warrantyListController.js b/frontend/js/controllers/warrantyListController.js
index 22d20f9..9ef8e50 100644
--- a/frontend/js/controllers/warrantyListController.js
+++ b/frontend/js/controllers/warrantyListController.js
@@ -808,6 +808,15 @@ export function initEventListeners() {
if (typeof window.openClaimsModal === 'function' && id) window.openClaimsModal(id);
return;
}
+ if (e.target.closest('.expiry-history-badge')) {
+ e.preventDefault();
+ const id = parseInt(e.target.closest('.expiry-history-badge')?.dataset?.id, 10);
+ const warranty = storeGetWarranties().find(w => w.id === id);
+ if (typeof window.openExpiryHistoryModal === 'function' && id) {
+ window.openExpiryHistoryModal(warranty || id);
+ }
+ return;
+ }
if (e.target.closest('.edit-btn')) {
e.preventDefault();
const el = e.target.closest('.edit-btn');
diff --git a/frontend/js/index.js b/frontend/js/index.js
index 2d9f1da..68c56fc 100644
--- a/frontend/js/index.js
+++ b/frontend/js/index.js
@@ -12,6 +12,7 @@ import { init as initAddForm } from './components/addWarrantyForm.js';
import { init as initEditModal } from './components/editModal.js';
import { init as initNotes } from './components/notes.js';
import { init as initClaims } from './components/claims.js';
+import { init as initExpiryHistory } from './components/expiryHistory.js';
import { initFormTabs } from './components/formTabs.js';
import { addSerialNumberInput } from './components/serialNumbers.js';
@@ -22,6 +23,7 @@ function bootstrapModules() {
initEditModal();
initNotes();
initClaims();
+ initExpiryHistory();
initViewControls();
loadFilterAndSortPreferences();
loadViewPreference();
diff --git a/frontend/script.js b/frontend/script.js
index 1ba6ca2..9a5e5fd 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -2939,6 +2939,10 @@ async function openEditModal(warranty) {
handleEditWarrantyMethodChange();
}
+ if (typeof window.initEditExpiryTracking === 'function') {
+ window.initEditExpiryTracking(warranty);
+ }
+
// Set notes
const notesInput = document.getElementById('editNotes');
if (notesInput) {
@@ -5655,6 +5659,12 @@ function saveWarranty() {
formData.append('warranty_duration_months', 0);
formData.append('warranty_duration_days', 0);
}
+ const expiryChangeReason = typeof window.getEditExpiryChangeReason === 'function'
+ ? window.getEditExpiryChangeReason()
+ : '';
+ if (expiryChangeReason) {
+ formData.append('expiry_change_reason', expiryChangeReason);
+ }
// Add notes
const notes = document.getElementById('editNotes').value;
if (notes && notes.trim() !== '') {
diff --git a/frontend/status.html b/frontend/status.html
index 09ab3fb..f5db41d 100644
--- a/frontend/status.html
+++ b/frontend/status.html
@@ -47,6 +47,7 @@
on window itself. Without it the Edit button throws
ReferenceError and the modal never opens. -->
<script type="module" src="js/components/serialNumbers.js?v=20261119001"></script>
+ <script type="module" src="js/components/expiryHistory.js?v=20261123001"></script>
<style>
.user-menu {
position: relative;
@@ -660,6 +661,18 @@
<input type="date" id="editExactExpirationDate" name="exact_expiration_date" class="form-control">
</div>
</div>
+
+ <div class="form-group expiry-reason-group" id="editExpiryChangeReasonGroup" style="display: none;">
+ <label for="editExpiryChangeReason" data-i18n="warranties.expiry_change_reason_label">Reason for Expiry Change (Optional)</label>
+ <input type="text" id="editExpiryChangeReason" name="expiry_change_reason" class="form-control" maxlength="255" data-i18n-placeholder="warranties.expiry_change_reason_placeholder" placeholder="e.g. Extended after repair claim, manufacturer goodwill...">
+ </div>
+
+ <div class="form-group expiry-history-section" id="editExpiryHistorySection" style="display: none;">
+ <details class="expiry-history-details" id="editExpiryHistoryDetails">
+ <summary id="editExpiryHistorySummary" data-i18n="warranties.expiry_history_title">Expiry History</summary>
+ <div id="editExpiryHistoryContent" class="expiry-history-content"></div>
+ </details>
+ </div>
<div class="form-group">
<label for="editWarrantyType" data-i18n="warranties.warranty_type_optional">Warranty Type (Optional)</label>
diff --git a/frontend/status.js b/frontend/status.js
index bdc34bd..621c221 100644
--- a/frontend/status.js
+++ b/frontend/status.js
@@ -766,10 +766,18 @@
// Build row HTML based on current view mode
const lifetimeText = i18next.t('warranties.lifetime');
const naText = i18next.t('warranties.na', 'N/A');
+ const expiryCount = Number(warranty.expiry_change_count) || 0;
+ const expiryTooltip = i18next.t('warranties.expiry_history_tooltip', {
+ count: expiryCount,
+ defaultValue: `Expiry changed ${expiryCount} time(s) — click to view history`
+ });
+ const expiryBadgeHtml = expiryCount > 0
+ ? ` <button type="button" class="expiry-history-badge" data-id="${warranty.id}" title="${escapeHTML(expiryTooltip)}" aria-label="${escapeHTML(expiryTooltip)}"><i class="fas fa-history" aria-hidden="true"></i><span>${expiryCount}</span></button>`
+ : '';
let rowHTML = `
<td title="${escapeHTML(warranty.product_name)}">${escapeHTML(warranty.product_name)}</td>
<td>${warranty.purchase_date ? formatDateYYYYMMDD(new Date(warranty.purchase_date)) : naText}</td>
- <td>${warranty.is_lifetime ? lifetimeText : (warranty.expiration_date ? formatDateYYYYMMDD(new Date(warranty.expiration_date)) : naText)}</td>
+ <td>${warranty.is_lifetime ? lifetimeText : (warranty.expiration_date ? formatDateYYYYMMDD(new Date(warranty.expiration_date)) : naText)}${expiryBadgeHtml}</td>
<td><span class="${statusClass}">${statusText}</span></td>
`;
@@ -780,6 +788,15 @@
}
row.innerHTML = rowHTML; // Make sure escapeHTML is used on all string data from warranty
+ const badgeBtn = row.querySelector('.expiry-history-badge');
+ if (badgeBtn) {
+ badgeBtn.addEventListener('click', (event) => {
+ event.stopPropagation();
+ if (typeof window.openExpiryHistoryModal === 'function') {
+ window.openExpiryHistoryModal(warranty);
+ }
+ });
+ }
row.addEventListener('click', () => toggleWarrantyDetails(warranty.id, row));
});
}
@@ -1016,6 +1033,15 @@
dHtml += '<div style="flex: 1 1 100%; margin-top: 10px;"><h4>Notes</h4>';
dHtml += `<pre style="white-space: pre-wrap; word-wrap: break-word; background-color: var(--notes-bg, #efefef); padding: 10px; border-radius: 4px;">${escapeHTML(warrantyDetails.notes)}</pre></div>`;
}
+ const detailExpiryCount = Number(warrantyDetails.expiry_change_count) || 0;
+ if (detailExpiryCount > 0) {
+ const historyHeading = escapeHTML(i18next.t('warranties.expiry_history_count_title', {
+ count: detailExpiryCount,
+ defaultValue: `Expiry History (${detailExpiryCount})`
+ }));
+ const loadingText = escapeHTML(i18next.t('warranties.expiry_history_loading', 'Loading expiry history...'));
+ dHtml += `<div class="status-expiry-history-section" style="flex: 1 1 100%; margin-top: 10px;"><h4>${historyHeading}</h4><div class="status-expiry-history-list"><p class="expiry-history-loading">${loadingText}</p></div></div>`;
+ }
dHtml += '</div>'; // end warranty-details-content
dHtml += '<div class="warranty-details-actions" style="margin-top: 15px; text-align: right;">';
const canEdit = canEditWarranty(warrantyDetails.user_id);
@@ -1026,6 +1052,27 @@
detailsCell.innerHTML = dHtml;
detailsRow.appendChild(detailsCell);
clickedRow.parentNode.insertBefore(detailsRow, clickedRow.nextSibling);
+
+ if (detailExpiryCount > 0 && typeof window.fetchExpiryHistory === 'function' && typeof window.renderExpiryHistoryList === 'function') {
+ const historyContainer = detailsCell.querySelector('.status-expiry-history-list');
+ if (historyContainer) {
+ window.fetchExpiryHistory(warrantyDetails.id)
+ .then(entries => {
+ if (detailsRow.isConnected) {
+ window.renderExpiryHistoryList(historyContainer, entries);
+ }
+ })
+ .catch(err => {
+ if (detailsRow.isConnected) {
+ while (historyContainer.firstChild) historyContainer.removeChild(historyContainer.firstChild);
+ const errP = document.createElement('p');
+ errP.className = 'expiry-history-error';
+ errP.textContent = (err && err.message) || i18next.t('warranties.expiry_history_load_error', 'Failed to load expiry history.');
+ historyContainer.appendChild(errP);
+ }
+ });
+ }
+ }
} catch (error) {
console.error('Error in toggleWarrantyDetails (status.js IIFE):', error);
showToast(`Error: ${error.message}`, 'error');
diff --git a/frontend/style.css b/frontend/style.css
index 0ace3af..1619531 100644
--- a/frontend/style.css
+++ b/frontend/style.css
@@ -6251,3 +6251,157 @@ html.dark-mode .warracker-footer a:hover {
color: var(--text-color);
}
}
+
+/* ============================
+ Expiry Change History (issue #209)
+ ============================ */
+.expiry-history-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ margin-left: 6px;
+ padding: 1px 6px;
+ font-size: 0.75rem;
+ font-weight: 600;
+ line-height: 1.3;
+ color: var(--primary-color);
+ background-color: rgba(var(--primary-rgb, 52, 152, 219), 0.12);
+ border: 1px solid rgba(var(--primary-rgb, 52, 152, 219), 0.35);
+ border-radius: 999px;
+ cursor: pointer;
+ vertical-align: middle;
+ transition: background-color 0.2s ease, border-color 0.2s ease, color 0.2s ease;
+}
+
+.expiry-history-badge:hover,
+.expiry-history-badge:focus-visible {
+ background-color: rgba(var(--primary-rgb, 52, 152, 219), 0.22);
+ border-color: var(--primary-color);
+ outline: none;
+}
+
+.expiry-history-badge i {
+ font-size: 0.7rem;
+ margin: 0 !important;
+ width: auto !important;
+ color: inherit !important;
+}
+
+.expiry-history-modal {
+ max-width: 520px;
+}
+
+.expiry-history-header-titles {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+}
+
+.expiry-history-modal-subtitle {
+ font-size: 0.85rem;
+ color: var(--dark-gray);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.expiry-history-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.expiry-history-item {
+ padding: 10px 12px;
+ border-radius: 6px;
+ background-color: var(--details-bg, #f8f9fa);
+ border: 1px solid var(--border-color);
+}
+
+.expiry-history-transition {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px;
+ font-size: 0.92rem;
+ font-weight: 600;
+ color: var(--text-color);
+}
+
+.expiry-history-prev {
+ color: var(--dark-gray);
+ text-decoration: line-through;
+ font-weight: 500;
+}
+
+.expiry-history-arrow {
+ color: var(--primary-color);
+ font-weight: 700;
+}
+
+.expiry-history-new {
+ color: var(--text-color);
+}
+
+.expiry-history-reason {
+ margin-top: 6px;
+ font-size: 0.88rem;
+ color: var(--text-color);
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+.expiry-history-meta {
+ margin-top: 4px;
+ font-size: 0.78rem;
+ color: var(--dark-gray);
+}
+
+.expiry-history-empty,
+.expiry-history-loading {
+ font-size: 0.88rem;
+ color: var(--dark-gray);
+ margin: 4px 0;
+}
+
+.expiry-history-error {
+ font-size: 0.88rem;
+ color: var(--danger-color);
+ margin: 4px 0;
+}
+
+.expiry-reason-group {
+ padding: 10px 12px;
+ border-radius: 6px;
+ background-color: rgba(var(--primary-rgb, 52, 152, 219), 0.08);
+ border: 1px solid rgba(var(--primary-rgb, 52, 152, 219), 0.25);
+}
+
+.expiry-history-details {
+ border: 1px solid var(--border-color);
+ border-radius: 6px;
+ padding: 8px 12px;
+ background-color: var(--details-bg, #f8f9fa);
+}
+
+.expiry-history-details > summary {
+ cursor: pointer;
+ font-weight: 600;
+ font-size: 0.9rem;
+ color: var(--primary-color);
+ user-select: none;
+}
+
+.expiry-history-details[open] > summary {
+ margin-bottom: 10px;
+}
+
+.expiry-history-content {
+ max-height: 220px;
+ overflow-y: auto;
+}
+
diff --git a/frontend/sw.js b/frontend/sw.js
index 9aea316..d6ef79c 100644
--- a/frontend/sw.js
+++ b/frontend/sw.js
@@ -1,4 +1,4 @@
-const CACHE_NAME = 'warracker-cache-v20261121001';
+const CACHE_NAME = 'warracker-cache-v20261123001';
const urlsToCache = [
// HTML pages
'./',
diff --git a/locales/ar/translation.json b/locales/ar/translation.json
index c4b1c54..4c46f6c 100644
--- a/locales/ar/translation.json
+++ b/locales/ar/translation.json
@@ -191,7 +191,6 @@
"choose_file": "اختر ملف",
"browse_paperless": "تصفح مستندات Paperless-ngx",
"product_manual_optional": "دليل المنتج (اختياري)",
- "files_optional": "ملفات (اختياري)",
"search_or_add_tag": "ابحث أو أضف علامة جديدة...",
"product_information": "معلومات المنتج",
"product_url": "رابط المنتج",
@@ -243,7 +242,17 @@
"unnamed_product": "منتج غير مسمى",
"unvoid_warranty": "ضمان غير مبطل",
"void": "باطل",
- "void_warranty": "ضمان باطل"
+ "void_warranty": "ضمان باطل",
+ "expiry_history_title": "سجل تغييرات تاريخ الانتهاء",
+ "expiry_history_count_title": "سجل تغييرات تاريخ الانتهاء ({{count}})",
+ "expiry_history_tooltip": "تم تغيير تاريخ الانتهاء {{count}} مرة — انقر لعرض السجل",
+ "expiry_history_empty": "لم يتم تسجيل أي تغييرات في تاريخ الانتهاء.",
+ "expiry_history_loading": "جارٍ تحميل سجل تاريخ الانتهاء...",
+ "expiry_history_load_error": "فشل تحميل سجل تاريخ الانتهاء.",
+ "expiry_history_changed_on": "تم التغيير في {{date}}",
+ "expiry_history_changed_on_by": "تم التغيير في {{date}} بواسطة {{user}}",
+ "expiry_change_reason_label": "سبب تغيير تاريخ الانتهاء (اختياري)",
+ "expiry_change_reason_placeholder": "مثل: تمديد بعد مطالبة إصلاح، تمديد من الشركة المصنعة..."
},
"settings": {
"title": "الإعدادات",
@@ -664,7 +673,8 @@
"confirm_void_warranty": "هل يبطل هذا الضمان؟ سيتم وضع علامة عليه كغير نشط واستبعاده من الإجماليات والإشعارات. ويمكنك استعادته لاحقًا.",
"error_updating_void_status": "فشل تحديث حالة الفراغ",
"unvoided_success": "تم استعادة الضمان من الفراغ",
- "voided_success": "الضمان باطلة"
+ "voided_success": "الضمان باطلة",
+ "expiry_change_reason_too_long": "يجب ألا يتجاوز سبب تغيير تاريخ الانتهاء 255 حرفاً"
},
"languages": {
"en": "English",
diff --git a/locales/cs/translation.json b/locales/cs/translation.json
index cfc86a8..6751438 100644
--- a/locales/cs/translation.json
+++ b/locales/cs/translation.json
@@ -221,7 +221,6 @@
"current_other_document": "Aktuální jiný dokument",
"no_other_document_uploaded": "Žádný jiný dokument nebyl nahrán",
"other_document_will_be_deleted": "Jiný dokument bude při uložení smazán",
- "files_optional": "Soubory (volitelné)",
"invoice_receipt_short": "Faktura",
"product_manual_short": "Návod",
"files_short": "Soubory",
@@ -240,7 +239,17 @@
"unnamed_product": "Nejmenovaný produkt",
"unvoid_warranty": "Zrušení záruky",
"void": "Neplatné",
- "void_warranty": "Zrušení záruky"
+ "void_warranty": "Zrušení záruky",
+ "expiry_history_title": "Historie změn expirace",
+ "expiry_history_count_title": "Historie změn expirace ({{count}})",
+ "expiry_history_tooltip": "Datum expirace změněno {{count}}× — klikněte pro zobrazení historie",
+ "expiry_history_empty": "Nebyly zaznamenány žádné změny data expirace.",
+ "expiry_history_loading": "Načítání historie expirace...",
+ "expiry_history_load_error": "Nepodařilo se načíst historii expirace.",
+ "expiry_history_changed_on": "Změněno {{date}}",
+ "expiry_history_changed_on_by": "Změněno {{date}} uživatelem {{user}}",
+ "expiry_change_reason_label": "Důvod změny expirace (volitelné)",
+ "expiry_change_reason_placeholder": "např. Prodlouženo po reklamaci, vstřícnost výrobce..."
},
"settings": {
"title": "Nastavení",
@@ -661,7 +670,8 @@
"confirm_void_warranty": "Zrušit tuto záruku? Bude označena jako neaktivní a vyloučena z celkových součtů a oznámení. Můžete jej obnovit později.",
"error_updating_void_status": "Aktualizace stavu neplatnosti se nezdařila",
"unvoided_success": "Záruka obnovena z neplatnosti",
- "voided_success": "Záruka zrušena"
+ "voided_success": "Záruka zrušena",
+ "expiry_change_reason_too_long": "Důvod změny expirace může mít maximálně 255 znaků"
},
"languages": {
"en": "Angličtina",
diff --git a/locales/de/translation.json b/locales/de/translation.json
index 8c409c6..a4af651 100644
--- a/locales/de/translation.json
+++ b/locales/de/translation.json
@@ -214,7 +214,6 @@
"current_other_document": "Aktuelles anderes Dokument",
"no_other_document_uploaded": "Kein anderes Dokument hochgeladen",
"other_document_will_be_deleted": "Anderes Dokument wird beim Speichern gelöscht",
- "files_optional": "Dateien (optional)",
"invoice_receipt_short": "Rechnung",
"product_manual_short": "Handbuch",
"files_short": "Dateien",
@@ -233,7 +232,17 @@
"unnamed_product": "Unbenanntes Produkt",
"unvoid_warranty": "Ungültige Garantie",
"void": "Ungültig",
- "void_warranty": "Garantie erlischt"
+ "void_warranty": "Garantie erlischt",
+ "expiry_history_title": "Ablaufverlauf",
+ "expiry_history_count_title": "Ablaufverlauf ({{count}})",
+ "expiry_history_tooltip": "Ablaufdatum {{count}}-mal geändert — klicken für Verlauf",
+ "expiry_history_empty": "Keine Änderungen am Ablaufdatum aufgezeichnet.",
+ "expiry_history_loading": "Ablaufverlauf wird geladen...",
+ "expiry_history_load_error": "Ablaufverlauf konnte nicht geladen werden.",
+ "expiry_history_changed_on": "Geändert am {{date}}",
+ "expiry_history_changed_on_by": "Geändert am {{date}} von {{user}}",
+ "expiry_change_reason_label": "Grund für die Ablaufänderung (Optional)",
+ "expiry_change_reason_placeholder": "z. B. Verlängert nach Reparatur, Herstellerkulanz..."
},
"settings": {
"title": "Einstellungen",
@@ -654,7 +663,8 @@
"confirm_void_warranty": "Diese Garantie ungültig machen? Es wird als inaktiv markiert und von Gesamtsummen und Benachrichtigungen ausgeschlossen. Sie können es später wiederherstellen.",
"error_updating_void_status": "Der Ungültigkeitsstatus konnte nicht aktualisiert werden",
"unvoided_success": "Die Garantie wurde nach Ablauf der Gültigkeit wiederhergestellt",
- "voided_success": "Garantie erlischt"
+ "voided_success": "Garantie erlischt",
+ "expiry_change_reason_too_long": "Der Grund für die Ablaufänderung darf höchstens 255 Zeichen lang sein"
},
"languages": {
"en": "Englisch",
diff --git a/locales/en/translation.json b/locales/en/translation.json
index 6883b72..e7ca121 100644
--- a/locales/en/translation.json
+++ b/locales/en/translation.json
@@ -209,7 +209,6 @@
"current_other_document": "Current other document",
"no_other_document_uploaded": "No other document uploaded",
"other_document_will_be_deleted": "Other document will be deleted on save",
- "files_optional": "Files (Optional)",
"invoice_receipt_short": "Invoice",
"product_manual_short": "Manual",
"files_short": "Files",
@@ -233,7 +232,17 @@
"unnamed_product": "Unnamed Product",
"void": "Void",
"void_warranty": "Void warranty",
- "unvoid_warranty": "Unvoid warranty"
+ "unvoid_warranty": "Unvoid warranty",
+ "expiry_history_title": "Expiry History",
+ "expiry_history_count_title": "Expiry History ({{count}})",
+ "expiry_history_tooltip": "Expiry changed {{count}} time(s) — click to view history",
+ "expiry_history_empty": "No expiration date changes recorded.",
+ "expiry_history_loading": "Loading expiry history...",
+ "expiry_history_load_error": "Failed to load expiry history.",
+ "expiry_history_changed_on": "Changed on {{date}}",
+ "expiry_history_changed_on_by": "Changed on {{date}} by {{user}}",
+ "expiry_change_reason_label": "Reason for Expiry Change (Optional)",
+ "expiry_change_reason_placeholder": "e.g. Extended after repair claim, manufacturer goodwill..."
},
"settings": {
"title": "Warracker - Settings",
@@ -654,7 +663,8 @@
"voided_success": "Warranty voided",
"unvoided_success": "Warranty restored from void",
"error_updating_void_status": "Failed to update void status",
- "confirm_void_warranty": "Void this warranty? It will be marked inactive and excluded from totals and notifications. You can restore it later."
+ "confirm_void_warranty": "Void this warranty? It will be marked inactive and excluded from totals and notifications. You can restore it later.",
+ "expiry_change_reason_too_long": "Expiry change reason must be 255 characters or less"
},
"languages": {
"en": "English",
diff --git a/locales/es/translation.json b/locales/es/translation.json
index e7205e3..67667f1 100644
--- a/locales/es/translation.json
+++ b/locales/es/translation.json
@@ -157,7 +157,7 @@
"choose_file": "Elegir archivo",
"browse_paperless": "Explorar documentos de Paperless-ngx",
"product_manual_optional": "Manual del producto (opcional)",
- "files_optional": "Archivos (opcional)",
+ "files_optional": "Archivos (Opcional)",
"search_or_add_new_tag": "Buscar o añadir nueva etiqueta...",
"product_information": "Información del producto",
"product_url": "URL del producto",
@@ -210,7 +210,6 @@
"current_other_document": "Documento actual",
"no_other_document_uploaded": "No se ha subido ningún otro documento",
"other_document_will_be_deleted": "El otro documento se eliminará al guardar",
- "files_optional": "Archivos (Opcional)",
"invoice_receipt_short": "Factura",
"product_manual_short": "Manual",
"files_short": "Archivos",
@@ -233,7 +232,17 @@
"unnamed_product": "Producto sin nombre",
"unvoid_warranty": "Garantía no nula",
"void": "Nula",
- "void_warranty": "Garantía nula"
+ "void_warranty": "Garantía nula",
+ "expiry_history_title": "Historial de vencimiento",
+ "expiry_history_count_title": "Historial de vencimiento ({{count}})",
+ "expiry_history_tooltip": "Vencimiento cambiado {{count}} vez/veces — clic para ver historial",
+ "expiry_history_empty": "No se han registrado cambios en la fecha de vencimiento.",
+ "expiry_history_loading": "Cargando historial de vencimiento...",
+ "expiry_history_load_error": "No se pudo cargar el historial de vencimiento.",
+ "expiry_history_changed_on": "Cambiado el {{date}}",
+ "expiry_history_changed_on_by": "Cambiado el {{date}} por {{user}}",
+ "expiry_change_reason_label": "Motivo del cambio de vencimiento (Opcional)",
+ "expiry_change_reason_placeholder": "ej. Extendida tras reparación, cortesía del fabricante..."
},
"settings": {
"title": "Configuración",
@@ -654,7 +663,8 @@
"confirm_void_warranty": "¿Anular esta garantía? Se marcará como inactivo y se excluirá de totales y notificaciones. Puedes restaurarlo más tarde.",
"error_updating_void_status": "No se pudo actualizar el estado de anulación",
"unvoided_success": "Garantía restaurada desde nula",
- "voided_success": "Garantía anulada"
+ "voided_success": "Garantía anulada",
+ "expiry_change_reason_too_long": "El motivo del cambio de vencimiento debe tener 255 caracteres o menos"
},
"languages": {
"en": "English",
diff --git a/locales/fa/translation.json b/locales/fa/translation.json
index 848aa41..05fa86c 100644
--- a/locales/fa/translation.json
+++ b/locales/fa/translation.json
@@ -214,7 +214,6 @@
"current_other_document": "سند دیگر فعلی",
"no_other_document_uploaded": "هیچ سند دیگری آپلود نشده است",
"other_document_will_be_deleted": "سند دیگر هنگام ذخیره حذف خواهد شد",
- "files_optional": "فایل‌ها (اختیاری)",
"invoice_receipt_short": "فاکتور",
"product_manual_short": "دفترچه راهنما",
"files_short": "فایل‌ها",
@@ -233,7 +232,17 @@
"unnamed_product": "محصول بدون نام",
"unvoid_warranty": "گارانتی بی اعتبار",
"void": "باطل",
- "void_warranty": "گارانتی باطل"
+ "void_warranty": "گارانتی باطل",
+ "expiry_history_title": "تاریخچه تغییرات انقضا",
+ "expiry_history_count_title": "تاریخچه تغییرات انقضا ({{count}})",
+ "expiry_history_tooltip": "تاریخ انقضا {{count}} بار تغییر کرده — برای مشاهده تاریخچه کلیک کنید",
+ "expiry_history_empty": "هیچ تغییری در تاریخ انقضا ثبت نشده است.",
+ "expiry_history_loading": "در حال بارگذاری تاریخچه انقضا...",
+ "expiry_history_load_error": "بارگذاری تاریخچه انقضا ناموفق بود.",
+ "expiry_history_changed_on": "تغییر یافته در {{date}}",
+ "expiry_history_changed_on_by": "تغییر یافته در {{date}} توسط {{user}}",
+ "expiry_change_reason_label": "دلیل تغییر تاریخ انقضا (اختیاری)",
+ "expiry_change_reason_placeholder": "مثلاً تمدید پس از تعمیر، تمدید توسط سازنده..."
},
"settings": {
"title": "تنظیمات",
@@ -654,7 +663,8 @@
"confirm_void_warranty": "این گارانتی باطل می شود؟ غیرفعال علامت‌گذاری می‌شود و از جمع کل و اعلان‌ها حذف می‌شود. بعدا می توانید آن را بازیابی کنید.",
"error_updating_void_status": "وضعیت خالی به‌روزرسانی نشد",
"unvoided_success": "گارانتی از باطل بازگردانده شد",
- "voided_success": "گارانتی باطل شد"
+ "voided_success": "گارانتی باطل شد",
+ "expiry_change_reason_too_long": "دلیل تغییر تاریخ انقضا باید حداکثر ۲۵۵ نویسه باشد"
},
"languages": {
"en": "انگلیسی",
diff --git a/locales/fr/translation.json b/locales/fr/translation.json
index 4689bdf..44509cb 100644
--- a/locales/fr/translation.json
+++ b/locales/fr/translation.json
@@ -161,7 +161,7 @@
"choose_file": "Choisir un fichier",
"browse_paperless": "Parcourir les documents Paperless-ngx",
"product_manual_optional": "Manuel du produit (facultatif)",
- "files_optional": "Fichiers (facultatif)",
+ "files_optional": "Fichiers (Optionnel)",
"search_or_add_new_tag": "Rechercher ou ajouter une nouvelle étiquette...",
"product_information": "Informations sur le produit",
"product_url": "URL du produit",
@@ -214,7 +214,6 @@
"current_other_document": "Document actuel",
"no_other_document_uploaded": "Aucun autre document téléchargé",
"other_document_will_be_deleted": "L'autre document sera supprimé lors de la sauvegarde",
- "files_optional": "Fichiers (Optionnel)",
"invoice_receipt_short": "Facture",
"product_manual_short": "Manuel",
"files_short": "Fichiers",
@@ -233,7 +232,17 @@
"unnamed_product": "Produit sans nom",
"unvoid_warranty": "Annuler la garantie",
"void": "Annulée",
- "void_warranty": "Annuler la garantie"
+ "void_warranty": "Annuler la garantie",
+ "expiry_history_title": "Historique d'expiration",
+ "expiry_history_count_title": "Historique d'expiration ({{count}})",
+ "expiry_history_tooltip": "Expiration modifiée {{count}} fois — cliquer pour voir l'historique",
+ "expiry_history_empty": "Aucune modification de la date d'expiration enregistrée.",
+ "expiry_history_loading": "Chargement de l'historique d'expiration...",
+ "expiry_history_load_error": "Échec du chargement de l'historique d'expiration.",
+ "expiry_history_changed_on": "Modifié le {{date}}",
+ "expiry_history_changed_on_by": "Modifié le {{date}} par {{user}}",
+ "expiry_change_reason_label": "Raison de la modification d'expiration (Optionnel)",
+ "expiry_change_reason_placeholder": "ex. Prolongée après réparation, geste commercial..."
},
"settings": {
"title": "Paramètres",
@@ -654,7 +663,8 @@
"confirm_void_warranty": "Annuler cette garantie ? Il sera marqué comme inactif et exclu des totaux et des notifications. Vous pourrez le restaurer plus tard.",
"error_updating_void_status": "Échec de la mise à jour du statut d'annulation",
"unvoided_success": "Garantie restaurée après annulation",
- "voided_success": "Garantie annulée"
+ "voided_success": "Garantie annulée",
+ "expiry_change_reason_too_long": "La raison de la modification d'expiration doit comporter 255 caractères maximum"
},
"languages": {
"en": "English",
diff --git a/locales/he/translation.json b/locales/he/translation.json
index 5c863f7..07f7480 100644
--- a/locales/he/translation.json
+++ b/locales/he/translation.json
@@ -193,7 +193,6 @@
"choose_file": "בחר קובץ",
"browse_paperless": "עיין במסמכי Paperless-ngx",
"product_manual_optional": "מדריך מוצר (אופציונלי)",
- "files_optional": "קבצים (אופציונלי)",
"search_or_add_tag": "חפש או הוסף תגית חדשה...",
"search_or_add_new_tag": "חפש או הוסף תגית חדשה...",
"product_information": "מידע על המוצר",
@@ -243,7 +242,17 @@
"unnamed_product": "ללא שם מוצר",
"unvoid_warranty": "אחריות ללא ביטול",
"void": "בָּטֵל",
- "void_warranty": "אחריות בטלה"
+ "void_warranty": "אחריות בטלה",
+ "expiry_history_title": "היסטוריית תוקף",
+ "expiry_history_count_title": "היסטוריית תוקף ({{count}})",
+ "expiry_history_tooltip": "תאריך התוקף שונה {{count}} פעמים — לחץ לצפייה בהיסטוריה",
+ "expiry_history_empty": "לא נרשמו שינויים בתאריך התפוגה.",
+ "expiry_history_loading": "טוען היסטוריית תוקף...",
+ "expiry_history_load_error": "טעינת היסטוריית התוקף נכשלה.",
+ "expiry_history_changed_on": "שונה בתאריך {{date}}",
+ "expiry_history_changed_on_by": "שונה בתאריך {{date}} על ידי {{user}}",
+ "expiry_change_reason_label": "סיבת שינוי תאריך התפוגה (אופציונלי)",
+ "expiry_change_reason_placeholder": "לדוגמה: הוארך לאחר תיקון, מחוות יצרן..."
},
"settings": {
"title": "הגדרות",
@@ -664,7 +673,8 @@
"confirm_void_warranty": "לבטל את האחריות הזו? הוא יסומן כלא פעיל ולא ייכלל בסיכומים ובהודעות. אתה יכול לשחזר אותו מאוחר יותר.",
"error_updating_void_status": "עדכון סטטוס הריק נכשל",
"unvoided_success": "האחריות שוחזרה מבטלה",
- "voided_success": "האחריות בוטלה"
+ "voided_success": "האחריות בוטלה",
+ "expiry_change_reason_too_long": "סיבת שינוי התוקף חייבת להיות עד 255 תווים"
},
"languages": {
"en": "אנגלית",
diff --git a/locales/hi/translation.json b/locales/hi/translation.json
index 39382df..e585478 100644
--- a/locales/hi/translation.json
+++ b/locales/hi/translation.json
@@ -214,7 +214,6 @@
"current_other_document": "वर्तमान अन्य दस्तावेज़",
"no_other_document_uploaded": "कोई अन्य दस्तावेज़ अपलोड नहीं किया गया",
"other_document_will_be_deleted": "अन्य दस्तावेज़ सेव करने पर हटा दिया जाएगा",
- "files_optional": "फाइलें (वैकल्पिक)",
"invoice_receipt_short": "चालान",
"product_manual_short": "मैनुअल",
"files_short": "फाइलें",
@@ -233,7 +232,17 @@
"unnamed_product": "अनाम उत्पाद",
"unvoid_warranty": "निरर्थक वारंटी",
"void": "रद्द",
- "void_warranty": "शून्य वारंटी"
+ "void_warranty": "शून्य वारंटी",
+ "expiry_history_title": "समाप्ति इतिहास",
+ "expiry_history_count_title": "समाप्ति इतिहास ({{count}})",
+ "expiry_history_tooltip": "समाप्ति तिथि {{count}} बार बदली गई — इतिहास देखने के लिए क्लिक करें",
+ "expiry_history_empty": "समाप्ति तिथि में कोई बदलाव दर्ज नहीं किया गया है।",
+ "expiry_history_loading": "समाप्ति इतिहास लोड हो रहा है...",
+ "expiry_history_load_error": "समाप्ति इतिहास लोड करने में विफल।",
+ "expiry_history_changed_on": "{{date}} को बदला गया",
+ "expiry_history_changed_on_by": "{{user}} द्वारा {{date}} को बदला गया",
+ "expiry_change_reason_label": "समाप्ति बदलने का कारण (वैकल्पिक)",
+ "expiry_change_reason_placeholder": "जैसे: मरम्मत दावे के बाद बढ़ाया गया, निर्माता विस्तार..."
},
"settings": {
"title": "सेटिंग्स",
@@ -654,7 +663,8 @@
"confirm_void_warranty": "यह वारंटी रद्द करें? इसे निष्क्रिय के रूप में चिह्नित किया जाएगा और कुल और सूचनाओं से बाहर रखा जाएगा। आप इसे बाद में पुनर्स्थापित कर सकते हैं.",
"error_updating_void_status": "शून्य स्थिति अद्यतन करने में विफल",
"unvoided_success": "वारंटी शून्य से बहाल",
- "voided_success": "वारंटी रद्द कर दी गई"
+ "voided_success": "वारंटी रद्द कर दी गई",
+ "expiry_change_reason_too_long": "समाप्ति बदलने का कारण 255 अक्षरों या उससे कम होना चाहिए"
},
"languages": {
"en": "अंग्रेज़ी",
diff --git a/locales/it/translation.json b/locales/it/translation.json
index c2b3dab..29b02c1 100644
--- a/locales/it/translation.json
+++ b/locales/it/translation.json
@@ -446,7 +446,6 @@
"choose_file": "Scegli File",
"browse_paperless": "Sfoglia Documenti Paperless-ngx",
"product_manual_optional": "Manuale Prodotto (Opzionale)",
- "files_optional": "File (Opzionale)",
"search_or_add_tag": "Cerca o aggiungi nuovo tag...",
"product_information": "Informazioni Prodotto",
"product_url": "URL Prodotto",
@@ -498,7 +497,17 @@
"unnamed_product": "Prodotto senza nome",
"unvoid_warranty": "Garanzia non valida",
"void": "Nulla",
- "void_warranty": "Garanzia nulla"
+ "void_warranty": "Garanzia nulla",
+ "expiry_history_title": "Cronologia scadenza",
+ "expiry_history_count_title": "Cronologia scadenza ({{count}})",
+ "expiry_history_tooltip": "Scadenza modificata {{count}} volta/e — clicca per vedere la cronologia",
+ "expiry_history_empty": "Nessuna modifica alla data di scadenza registrata.",
+ "expiry_history_loading": "Caricamento cronologia scadenza...",
+ "expiry_history_load_error": "Impossibile caricare la cronologia scadenza.",
+ "expiry_history_changed_on": "Modificato il {{date}}",
+ "expiry_history_changed_on_by": "Modificato il {{date}} da {{user}}",
+ "expiry_change_reason_label": "Motivo della modifica scadenza (Opzionale)",
+ "expiry_change_reason_placeholder": "es. Estesa dopo riparazione, cortesia del produttore..."
},
"actions": {
"save": "Salva",
@@ -747,7 +756,8 @@
"confirm_void_warranty": "Annullare questa garanzia? Verrà contrassegnato come inattivo ed escluso dai totali e dalle notifiche. Puoi ripristinarlo in seguito.",
"error_updating_void_status": "Impossibile aggiornare lo stato di annullamento",
"unvoided_success": "Garanzia ripristinata da nulla",
- "voided_success": "Garanzia annullata"
+ "voided_success": "Garanzia annullata",
+ "expiry_change_reason_too_long": "Il motivo della modifica scadenza deve contenere al massimo 255 caratteri"
},
"claims": {
"claims": "Reclami",
diff --git a/locales/ja/translation.json b/locales/ja/translation.json
index 60a8ed9..a78bbd3 100644
--- a/locales/ja/translation.json
+++ b/locales/ja/translation.json
@@ -214,7 +214,6 @@
"current_other_document": "現在のその他のドキュメント",
"no_other_document_uploaded": "その他のドキュメントがアップロードされていません",
"other_document_will_be_deleted": "保存時にその他のドキュメントは削除されます",
- "files_optional": "ファイル(オプション)",
"invoice_receipt_short": "請求書",
"product_manual_short": "マニュアル",
"files_short": "ファイル",
@@ -233,7 +232,17 @@
"unnamed_product": "名前のない製品",
"unvoid_warranty": "無効でない保証",
"void": "無効",
- "void_warranty": "無効な保証"
+ "void_warranty": "無効な保証",
+ "expiry_history_title": "有効期限の変更履歴",
+ "expiry_history_count_title": "有効期限の変更履歴 ({{count}})",
+ "expiry_history_tooltip": "有効期限が{{count}}回変更されました — クリックして履歴を表示",
+ "expiry_history_empty": "有効期限の変更履歴はありません。",
+ "expiry_history_loading": "変更履歴を読み込み中...",
+ "expiry_history_load_error": "有効期限の変更履歴の読み込みに失敗しました。",
+ "expiry_history_changed_on": "{{date}} に変更",
+ "expiry_history_changed_on_by": "{{date}} に {{user}} が変更",
+ "expiry_change_reason_label": "有効期限変更の理由(任意)",
+ "expiry_change_reason_placeholder": "例:修理請求後の延長、メーカー延長対応..."
},
"settings": {
"title": "設定",
@@ -654,7 +663,8 @@
"confirm_void_warranty": "この保証は無効になりますか?これは非アクティブとしてマークされ、合計と通知から除外されます。後で復元できます。",
"error_updating_void_status": "無効ステータスの更新に失敗しました",
"unvoided_success": "無効な保証が回復されました",
- "voided_success": "保証が無効になる"
+ "voided_success": "保証が無効になる",
+ "expiry_change_reason_too_long": "有効期限変更の理由は255文字以内で入力してください"
},
"languages": {
"en": "English",
diff --git a/locales/ko/translation.json b/locales/ko/translation.json
index cd6a086..5981378 100644
--- a/locales/ko/translation.json
+++ b/locales/ko/translation.json
@@ -214,7 +214,6 @@
"current_other_document": "현재 기타 문서",
"no_other_document_uploaded": "업로드된 기타 문서 없음",
"other_document_will_be_deleted": "저장 시 기타 문서가 삭제됩니다",
- "files_optional": "파일 (선택 사항)",
"invoice_receipt_short": "송장",
"product_manual_short": "설명서",
"files_short": "파일",
@@ -233,7 +232,17 @@
"unnamed_product": "이름이 없는 제품",
"unvoid_warranty": "무효 보증",
"void": "무효의",
- "void_warranty": "보증 무효"
+ "void_warranty": "보증 무효",
+ "expiry_history_title": "만료일 변경 이력",
+ "expiry_history_count_title": "만료일 변경 이력 ({{count}})",
+ "expiry_history_tooltip": "만료일이 {{count}}회 변경됨 — 클릭하여 이력 보기",
+ "expiry_history_empty": "기록된 만료일 변경 내역이 없습니다.",
+ "expiry_history_loading": "만료일 변경 이력을 불러오는 중...",
+ "expiry_history_load_error": "만료일 변경 이력을 불러오지 못했습니다.",
+ "expiry_history_changed_on": "{{date}}에 변경됨",
+ "expiry_history_changed_on_by": "{{date}}에 {{user}}님이 변경함",
+ "expiry_change_reason_label": "만료일 변경 사유 (선택 사항)",
+ "expiry_change_reason_placeholder": "예: 수리 청구 후 연장, 제조사 연장 지원..."
},
"settings": {
"title": "설정",
@@ -654,7 +663,8 @@
"confirm_void_warranty": "이 보증을 무효화하시겠습니까? 비활성으로 표시되고 총계 및 알림에서 제외됩니다. 나중에 복원할 수 있습니다.",
"error_updating_void_status": "무효 상태를 업데이트하지 못했습니다.",
"unvoided_success": "무효로 인한 보증 복원",
- "voided_success": "보증이 무효화됨"
+ "voided_success": "보증이 무효화됨",
+ "expiry_change_reason_too_long": "만료일 변경 사유는 255자 이하여야 합니다"
},
"languages": {
"en": "English",
diff --git a/locales/nl/translation.json b/locales/nl/translation.json
index effb747..b7e1af4 100644
--- a/locales/nl/translation.json
+++ b/locales/nl/translation.json
@@ -214,7 +214,6 @@
"current_other_document": "Huidig ander document",
"no_other_document_uploaded": "Geen ander document geüpload",
"other_document_will_be_deleted": "Ander document wordt bij opslaan verwijderd",
- "files_optional": "Bestanden (optioneel)",
"invoice_receipt_short": "Factuur",
"product_manual_short": "Handleiding",
"files_short": "Bestanden",
@@ -233,7 +232,17 @@
"unnamed_product": "Naamloos product",
"unvoid_warranty": "Ongeldige garantie",
"void": "Ongeldig",
- "void_warranty": "Garantie ongeldig"
+ "void_warranty": "Garantie ongeldig",
+ "expiry_history_title": "Verloopgeschiedenis",
+ "expiry_history_count_title": "Verloopgeschiedenis ({{count}})",
+ "expiry_history_tooltip": "Vervaldatum {{count}} keer gewijzigd — klik om geschiedenis te bekijken",
+ "expiry_history_empty": "Geen wijzigingen in de vervaldatum geregistreerd.",
+ "expiry_history_loading": "Verloopgeschiedenis laden...",
+ "expiry_history_load_error": "Laden van verloopgeschiedenis mislukt.",
+ "expiry_history_changed_on": "Gewijzigd op {{date}}",
+ "expiry_history_changed_on_by": "Gewijzigd op {{date}} door {{user}}",
+ "expiry_change_reason_label": "Reden voor wijziging vervaldatum (Optioneel)",
+ "expiry_change_reason_placeholder": "bijv. Verlengd na reparatieclaim, coulance fabrikant..."
},
"settings": {
"title": "Instellingen",
@@ -654,7 +663,8 @@
"confirm_void_warranty": "Deze garantie ongeldig maken? Het wordt gemarkeerd als inactief en uitgesloten van totalen en meldingen. Je kunt het later herstellen.",
"error_updating_void_status": "Kan de ongeldigheidsstatus niet bijwerken",
"unvoided_success": "Garantie hersteld van ongeldig",
- "voided_success": "Garantie ongeldig"
+ "voided_success": "Garantie ongeldig",
+ "expiry_change_reason_too_long": "De reden voor wijziging van de vervaldatum mag maximaal 255 tekens bevatten"
},
"languages": {
"en": "Engels",
diff --git a/locales/pl/translation.json b/locales/pl/translation.json
index d0972b8..8c27457 100644
--- a/locales/pl/translation.json
+++ b/locales/pl/translation.json
@@ -210,7 +210,6 @@
"current_other_document": "Obecny inny dokument",
"no_other_document_uploaded": "Brak przesłanego innego dokumentu",
"other_document_will_be_deleted": "Inny dokument zostanie usunięty po zapisaniu",
- "files_optional": "Pliki (opcjonalnie)",
"invoice_receipt_short": "Faktura",
"product_manual_short": "Instrukcja",
"files_short": "Pliki",
@@ -233,7 +232,17 @@
"unnamed_product": "Nienazwany produkt",
"unvoid_warranty": "Nieunieważniona gwarancja",
"void": "Nieważna",
- "void_warranty": "Nieważna gwarancja"
+ "void_warranty": "Nieważna gwarancja",
+ "expiry_history_title": "Historia zmian wygaśnięcia",
+ "expiry_history_count_title": "Historia zmian wygaśnięcia ({{count}})",
+ "expiry_history_tooltip": "Data wygaśnięcia zmieniona {{count}} raz(y) — kliknij, aby zobaczyć historię",
+ "expiry_history_empty": "Brak zarejestrowanych zmian daty wygaśnięcia.",
+ "expiry_history_loading": "Ładowanie historii wygaśnięcia...",
+ "expiry_history_load_error": "Nie udało się załadować historii wygaśnięcia.",
+ "expiry_history_changed_on": "Zmieniono {{date}}",
+ "expiry_history_changed_on_by": "Zmieniono {{date}} przez {{user}}",
+ "expiry_change_reason_label": "Powód zmiany daty wygaśnięcia (Opcjonalnie)",
+ "expiry_change_reason_placeholder": "np. Przedłużono po naprawie, gest producenta..."
},
"settings": {
"title": "Warracker - Ustawienia",
@@ -654,7 +663,8 @@
"confirm_void_warranty": "Unieważnić tę gwarancję? Zostanie oznaczony jako nieaktywny i wykluczony z sum i powiadomień. Możesz go przywrócić później.",
"error_updating_void_status": "Nie udało się zaktualizować statusu nieważnego",
"unvoided_success": "Gwarancja przywrócona po utracie ważności",
- "voided_success": "Gwarancja unieważniona"
+ "voided_success": "Gwarancja unieważniona",
+ "expiry_change_reason_too_long": "Powód zmiany daty wygaśnięcia może mieć maksymalnie 255 znaków"
},
"languages": {
"en": "English",
diff --git a/locales/pt/translation.json b/locales/pt/translation.json
index 20f74fb..a877fee 100644
--- a/locales/pt/translation.json
+++ b/locales/pt/translation.json
@@ -214,7 +214,6 @@
"current_other_document": "Outro documento atual",
"no_other_document_uploaded": "Nenhum outro documento carregado",
"other_document_will_be_deleted": "O outro documento será excluído ao salvar",
- "files_optional": "Arquivos (Opcional)",
"invoice_receipt_short": "Fatura",
"product_manual_short": "Manual",
"files_short": "Arquivos",
@@ -233,7 +232,17 @@
"unnamed_product": "Produto sem nome",
"unvoid_warranty": "Garantia não anulada",
"void": "Anulada",
- "void_warranty": "Anular garantia"
+ "void_warranty": "Anular garantia",
+ "expiry_history_title": "Histórico de validade",
+ "expiry_history_count_title": "Histórico de validade ({{count}})",
+ "expiry_history_tooltip": "Validade alterada {{count}} vez(es) — clique para ver o histórico",
+ "expiry_history_empty": "Nenhuma alteração na data de validade registrada.",
+ "expiry_history_loading": "Carregando histórico de validade...",
+ "expiry_history_load_error": "Falha ao carregar o histórico de validade.",
+ "expiry_history_changed_on": "Alterado em {{date}}",
+ "expiry_history_changed_on_by": "Alterado em {{date}} por {{user}}",
+ "expiry_change_reason_label": "Motivo da alteração de validade (Opcional)",
+ "expiry_change_reason_placeholder": "ex. Estendida após reparo, cortesia do fabricante..."
},
"claims": {
"claims": "Reclamações",
@@ -709,7 +718,8 @@
"confirm_void_warranty": "Anular esta garantia? Será marcado como inativo e excluído dos totais e notificações. Você pode restaurá-lo mais tarde.",
"error_updating_void_status": "Falha ao atualizar o status nulo",
"unvoided_success": "Garantia restaurada do nulo",
- "voided_success": "Garantia anulada"
+ "voided_success": "Garantia anulada",
+ "expiry_change_reason_too_long": "O motivo da alteração de validade deve ter 255 caracteres ou menos"
},
"languages": {
"en": "English",
diff --git a/locales/ru/translation.json b/locales/ru/translation.json
index e480667..b39219b 100644
--- a/locales/ru/translation.json
+++ b/locales/ru/translation.json
@@ -220,7 +220,6 @@
"current_other_document": "Текущий другой документ",
"no_other_document_uploaded": "Другой документ не загружен",
"other_document_will_be_deleted": "Другой документ будет удален при сохранении",
- "files_optional": "Файлы (необязательно)",
"invoice_receipt_short": "Счет",
"product_manual_short": "Руководство",
"files_short": "Файлы",
@@ -239,7 +238,17 @@
"unnamed_product": "Безымянный продукт",
"unvoid_warranty": "Отменить гарантию",
"void": "Аннулирована",
- "void_warranty": "Аннулирование гарантии"
+ "void_warranty": "Аннулирование гарантии",
+ "expiry_history_title": "История изменений срока",
+ "expiry_history_count_title": "История изменений срока ({{count}})",
+ "expiry_history_tooltip": "Срок окончания изменён {{count}} раз(а) — нажмите для просмотра истории",
+ "expiry_history_empty": "Изменений даты окончания не зафиксировано.",
+ "expiry_history_loading": "Загрузка истории изменений срока...",
+ "expiry_history_load_error": "Не удалось загрузить историю изменений срока.",
+ "expiry_history_changed_on": "Изменено {{date}}",
+ "expiry_history_changed_on_by": "Изменено {{date}} пользователем {{user}}",
+ "expiry_change_reason_label": "Причина изменения срока (необязательно)",
+ "expiry_change_reason_placeholder": "напр. Продлено после ремонта, продление производителем..."
},
"claims": {
"claims": "Обращения",
@@ -715,7 +724,8 @@
"confirm_void_warranty": "Аннулировать эту гарантию? Он будет помечен как неактивный и исключен из итогов и уведомлений. Вы сможете восстановить его позже.",
"error_updating_void_status": "Не удалось обновить статус аннулирования.",
"unvoided_success": "Гарантия восстановлена ​​из недействительной",
- "voided_success": "Гарантия аннулирована"
+ "voided_success": "Гарантия аннулирована",
+ "expiry_change_reason_too_long": "Причина изменения срока не должна превышать 255 символов"
},
"languages": {
"en": "English",
diff --git a/locales/tr/translation.json b/locales/tr/translation.json
index f7acd79..2a8ebc6 100644
--- a/locales/tr/translation.json
+++ b/locales/tr/translation.json
@@ -209,7 +209,8 @@
"confirm_void_warranty": "Bu garanti geçersiz mi? Etkin değil olarak işaretlenecek ve toplamlardan ve bildirimlerden hariç tutulacaktır. Daha sonra geri yükleyebilirsiniz.",
"error_updating_void_status": "Geçersiz durumu güncellenemedi",
"unvoided_success": "Garanti geçersiz durumdan geri getirildi",
- "voided_success": "Garanti geçersiz"
+ "voided_success": "Garanti geçersiz",
+ "expiry_change_reason_too_long": "Bitiş tarihi değişiklik nedeni 255 karakter veya daha kısa olmalıdır"
},
"settings": {
"title": "Ayarlar",
@@ -608,7 +609,6 @@
"current_other_document": "Mevcut diğer belge",
"no_other_document_uploaded": "Başka belge yüklenmedi",
"other_document_will_be_deleted": "Diğer belge kaydetmede silinecek",
- "files_optional": "Dosyalar (İsteğe Bağlı)",
"invoice_receipt_short": "Fatura",
"product_manual_short": "Kılavuz",
"files_short": "Dosyalar",
@@ -631,7 +631,17 @@
"unnamed_product": "Adsız Ürün",
"unvoid_warranty": "Garantiyi geçersiz kılma",
"void": "Geçersiz",
- "void_warranty": "Garantiyi geçersiz kılma"
+ "void_warranty": "Garantiyi geçersiz kılma",
+ "expiry_history_title": "Bitiş Tarihi Geçmişi",
+ "expiry_history_count_title": "Bitiş Tarihi Geçmişi ({{count}})",
+ "expiry_history_tooltip": "Bitiş tarihi {{count}} kez değiştirildi — geçmişi görmek için tıklayın",
+ "expiry_history_empty": "Kaydedilmiş bitiş tarihi değişikliği yok.",
+ "expiry_history_loading": "Bitiş tarihi geçmişi yükleniyor...",
+ "expiry_history_load_error": "Bitiş tarihi geçmişi yüklenemedi.",
+ "expiry_history_changed_on": "{{date}} tarihinde değiştirildi",
+ "expiry_history_changed_on_by": "{{date}} tarihinde {{user}} tarafından değiştirildi",
+ "expiry_change_reason_label": "Bitiş Tarihi Değişiklik Nedeni (İsteğe bağlı)",
+ "expiry_change_reason_placeholder": "örn. Onarım talebi sonrası uzatıldı, üretici jesti..."
},
"actions": {
"save": "Kaydet",
diff --git a/locales/uk/translation.json b/locales/uk/translation.json
index edb7a45..8721a71 100644
--- a/locales/uk/translation.json
+++ b/locales/uk/translation.json
@@ -220,7 +220,6 @@
"current_other_document": "Поточний інший документ",
"no_other_document_uploaded": "Інший документ не завантажено",
"other_document_will_be_deleted": "Інший документ буде видалено при збереженні",
- "files_optional": "Файли (необов'язково)",
"invoice_receipt_short": "Рахунок",
"product_manual_short": "Посібник",
"files_short": "Файли",
@@ -239,7 +238,17 @@
"unnamed_product": "Продукт без назви",
"unvoid_warranty": "Недійсна гарантія",
"void": "Недійсна",
- "void_warranty": "Недійсна гарантія"
+ "void_warranty": "Недійсна гарантія",
+ "expiry_history_title": "Історія змін терміну дії",
+ "expiry_history_count_title": "Історія змін терміну дії ({{count}})",
+ "expiry_history_tooltip": "Термін дії змінено {{count}} раз(и) — натисніть для перегляду історії",
+ "expiry_history_empty": "Змін дати закінчення не зафіксовано.",
+ "expiry_history_loading": "Завантаження історії змін терміну дії...",
+ "expiry_history_load_error": "Не вдалося завантажити історію змін терміну дії.",
+ "expiry_history_changed_on": "Змінено {{date}}",
+ "expiry_history_changed_on_by": "Змінено {{date}} користувачем {{user}}",
+ "expiry_change_reason_label": "Причина зміни терміну дії (необов'язково)",
+ "expiry_change_reason_placeholder": "напр. Продовжено після ремонту, продовження виробником..."
},
"settings": {
"title": "Налаштування",
@@ -660,7 +669,8 @@
"confirm_void_warranty": "Скасувати цю гарантію? Його буде позначено як неактивний і виключено з підсумків і повідомлень. Ви можете відновити його пізніше.",
"error_updating_void_status": "Не вдалося оновити статус анулювання",
"unvoided_success": "Гарантія відновлена",
- "voided_success": "Гарантія анульована"
+ "voided_success": "Гарантія анульована",
+ "expiry_change_reason_too_long": "Причина зміни терміну дії не повинна перевищувати 255 символів"
},
"languages": {
"en": "English",
diff --git a/locales/zh_CN/translation.json b/locales/zh_CN/translation.json
index 77780e4..2eb36b2 100644
--- a/locales/zh_CN/translation.json
+++ b/locales/zh_CN/translation.json
@@ -214,7 +214,6 @@
"current_other_document": "当前其他文档",
"no_other_document_uploaded": "未上传其他文档",
"other_document_will_be_deleted": "保存后将删除其他文档",
- "files_optional": "附件(可选)",
"invoice_receipt_short": "发票",
"product_manual_short": "手册",
"files_short": "附件",
@@ -233,7 +232,17 @@
"unnamed_product": "未命名产品",
"unvoid_warranty": "保修无效",
"void": "无效",
- "void_warranty": "保修无效"
+ "void_warranty": "保修无效",
+ "expiry_history_title": "到期变更历史",
+ "expiry_history_count_title": "到期变更历史 ({{count}})",
+ "expiry_history_tooltip": "到期日期已变更 {{count}} 次 — 点击查看历史",
+ "expiry_history_empty": "暂无到期日期变更记录。",
+ "expiry_history_loading": "正在加载到期变更历史...",
+ "expiry_history_load_error": "加载到期变更历史失败。",
+ "expiry_history_changed_on": "变更于 {{date}}",
+ "expiry_history_changed_on_by": "由 {{user}} 于 {{date}} 变更",
+ "expiry_change_reason_label": "到期变更原因(可选)",
+ "expiry_change_reason_placeholder": "例如:维修索赔后延长、厂商延保..."
},
"settings": {
"title": "Warracker - 设置",
@@ -654,7 +663,8 @@
"confirm_void_warranty": "使本保修失效?它将被标记为非活动状态并从总数和通知中排除。您可以稍后恢复它。",
"error_updating_void_status": "无法更新无效状态",
"unvoided_success": "保修从无效状态恢复",
- "voided_success": "保修失效"
+ "voided_success": "保修失效",
+ "expiry_change_reason_too_long": "到期变更原因不能超过 255 个字符"
},
"languages": {
"en": "English",
diff --git a/locales/zh_HK/translation.json b/locales/zh_HK/translation.json
index 9d2e06d..d605ab3 100644
--- a/locales/zh_HK/translation.json
+++ b/locales/zh_HK/translation.json
@@ -214,7 +214,6 @@
"current_other_document": "目前其他文件",
"no_other_document_uploaded": "未上傳其他文件",
"other_document_will_be_deleted": "其他文件將在儲存時刪除",
- "files_optional": "檔案(可選)",
"invoice_receipt_short": "發票",
"product_manual_short": "手冊",
"files_short": "檔案",
@@ -233,7 +232,17 @@
"unnamed_product": "未命名產品",
"unvoid_warranty": "保固無效",
"void": "無效",
- "void_warranty": "保固無效"
+ "void_warranty": "保固無效",
+ "expiry_history_title": "到期變更記錄",
+ "expiry_history_count_title": "到期變更記錄 ({{count}})",
+ "expiry_history_tooltip": "到期日期已變更 {{count}} 次 — 點擊查看記錄",
+ "expiry_history_empty": "尚無到期日期變更記錄。",
+ "expiry_history_loading": "正在載入到期變更記錄...",
+ "expiry_history_load_error": "載入到期變更記錄失敗。",
+ "expiry_history_changed_on": "變更於 {{date}}",
+ "expiry_history_changed_on_by": "由 {{user}} 於 {{date}} 變更",
+ "expiry_change_reason_label": "到期變更原因(可選)",
+ "expiry_change_reason_placeholder": "例如:維修索償後延長、廠商延保..."
},
"settings": {
"title": "設定",
@@ -654,7 +663,8 @@
"confirm_void_warranty": "使本保固失效?它將被標記為非活動狀態並從總數和通知中排除。您可以稍後恢復它。",
"error_updating_void_status": "無法更新無效狀態",
"unvoided_success": "保固從無效狀態恢復",
- "voided_success": "保固失效"
+ "voided_success": "保固失效",
+ "expiry_change_reason_too_long": "到期變更原因不能超過 255 個字元"
},
"languages": {
"en": "English",
diff --git a/tests/README.md b/tests/README.md
index 393223f..e79f96a 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -53,6 +53,11 @@ CI runs the same suite on every pull request
void/unvoid, cross-user ownership boundaries (stranger vs admin),
global view visibility modes (`global`, `global/archived`,
`global-view-status`), `admin/warranties`, `timezones`, and `locales`.
+- `test_warranty_expiry_history.py` — expiration date and lifetime
+ change history (#209): recording transitions on edit with optional
+ reason, length validation, `expiry_change_count` across list/debug/
+ statistics endpoints, global-view access control, cascade/nullability,
+ and XSS-safe DOM rendering.
- `test_claims_crud_and_access.py` — full claim CRUD lifecycle,
`claim_status_summary` transitions, claim document upload/delete disk
cleanup, and cross-user claim/document privacy under global view.
diff --git a/tests/test_warranty_expiry_history.py b/tests/test_warranty_expiry_history.py
new file mode 100644
index 0000000..52d006e
--- /dev/null
+++ b/tests/test_warranty_expiry_history.py
@@ -0,0 +1,385 @@
+"""Tests for warranty expiration date / lifetime change history (issue #209)."""
+import os
+import pytest
+
+REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+
+def _create_warranty(client, headers, **overrides):
+ data = {
+ "product_name": "Test Laptop",
+ "purchase_date": "2025-01-01",
+ "exact_expiration_date": "2027-01-01",
+ }
+ data.update(overrides)
+ r = client.post("/api/warranties", data=data, headers=headers)
+ assert r.status_code in (200, 201), r.get_data(as_text=True)
+ return r.get_json()["id"]
+
+
+def _set_global_view(client, admin_headers, enabled, admin_only):
+ r = client.put(
+ "/api/admin/settings",
+ json={
+ "global_view_enabled": "true" if enabled else "false",
+ "global_view_admin_only": "true" if admin_only else "false",
+ },
+ headers=admin_headers,
+ )
+ assert r.status_code == 200, r.get_data(as_text=True)
+
+
+def test_unchanged_edits_do_not_record_expiry_history(client, user_factory):
+ user = user_factory()
+ wid = _create_warranty(
+ client,
+ user["headers"],
+ product_name="Unchanged Widget",
+ purchase_date="2025-01-01",
+ exact_expiration_date="2027-01-01",
+ )
+
+ # 1. Edit metadata while keeping the same exact expiration date
+ r = client.put(
+ f"/api/warranties/{wid}",
+ data={
+ "product_name": "Unchanged Widget Renamed",
+ "purchase_date": "2025-01-01",
+ "exact_expiration_date": "2027-01-01",
+ "vendor": "Acme Store",
+ "notes": "Updated notes only",
+ "expiry_change_reason": "Should not be logged because date did not change",
+ },
+ headers=user["headers"],
+ )
+ assert r.status_code == 200, r.get_data(as_text=True)
+
+ # 2. Switch from exact date to equivalent 2-year duration (still 2027-01-01)
+ r = client.put(
+ f"/api/warranties/{wid}",
+ data={
+ "product_name": "Unchanged Widget Renamed",
+ "purchase_date": "2025-01-01",
+ "warranty_duration_years": "2",
+ "warranty_duration_months": "0",
+ "warranty_duration_days": "0",
+ },
+ headers=user["headers"],
+ )
+ assert r.status_code == 200, r.get_data(as_text=True)
+
+ # 3. JSON-only notes update shortcut
+ r = client.put(
+ f"/api/warranties/{wid}",
+ json={"notes": "Quick notes update"},
+ headers=user["headers"],
+ )
+ assert r.status_code == 200, r.get_data(as_text=True)
+
+ hist = client.get(f"/api/warranties/{wid}/expiry-history", headers=user["headers"])
+ assert hist.status_code == 200
+ assert hist.get_json() == []
+
+ warranties = client.get("/api/warranties", headers=user["headers"]).get_json()
+ match = next(w for w in warranties if w["id"] == wid)
+ assert match["expiry_change_count"] == 0
+
+
+def test_expiry_history_records_date_duration_and_lifetime_transitions(client, user_factory):
+ user = user_factory()
+ wid = _create_warranty(
+ client,
+ user["headers"],
+ product_name="Repairable Camera",
+ purchase_date="2025-01-01",
+ exact_expiration_date="2026-01-01",
+ )
+
+ # 1. Exact date extension with optional reason (whitespace trimmed)
+ r = client.put(
+ f"/api/warranties/{wid}",
+ data={
+ "product_name": "Repairable Camera",
+ "purchase_date": "2025-01-01",
+ "exact_expiration_date": "2026-07-01",
+ "expiry_change_reason": " Extended 6 months after repair claim ",
+ },
+ headers=user["headers"],
+ )
+ assert r.status_code == 200, r.get_data(as_text=True)
+
+ # 2. Duration-based update (3 years from 2025-01-01 -> 2028-01-01), no reason
+ r = client.put(
+ f"/api/warranties/{wid}",
+ data={
+ "product_name": "Repairable Camera",
+ "purchase_date": "2025-01-01",
+ "warranty_duration_years": "3",
+ "warranty_duration_months": "0",
+ "warranty_duration_days": "0",
+ },
+ headers=user["headers"],
+ )
+ assert r.status_code == 200, r.get_data(as_text=True)
+
+ # 3. Switch to lifetime warranty
+ r = client.put(
+ f"/api/warranties/{wid}",
+ data={
+ "product_name": "Repairable Camera",
+ "purchase_date": "2025-01-01",
+ "is_lifetime": "true",
+ "expiry_change_reason": "Upgraded to lifetime coverage",
+ },
+ headers=user["headers"],
+ )
+ assert r.status_code == 200, r.get_data(as_text=True)
+
+ # 4. Re-saving lifetime with no expiry change should NOT add a row
+ r = client.put(
+ f"/api/warranties/{wid}",
+ data={
+ "product_name": "Repairable Camera Pro",
+ "purchase_date": "2025-01-01",
+ "is_lifetime": "true",
+ },
+ headers=user["headers"],
+ )
+ assert r.status_code == 200, r.get_data(as_text=True)
+
+ # 5. Switch from lifetime back to an exact date
+ r = client.put(
+ f"/api/warranties/{wid}",
+ data={
+ "product_name": "Repairable Camera Pro",
+ "purchase_date": "2025-01-01",
+ "is_lifetime": "false",
+ "exact_expiration_date": "2030-01-01",
+ "expiry_change_reason": "Corrected from lifetime to 5-year limit",
+ },
+ headers=user["headers"],
+ )
+ assert r.status_code == 200, r.get_data(as_text=True)
+
+ resp = client.get(f"/api/warranties/{wid}/expiry-history", headers=user["headers"])
+ assert resp.status_code == 200
+ entries = resp.get_json()
+ assert len(entries) == 4
+
+ # Ordered newest-first
+ assert entries[0]["previous_is_lifetime"] is True
+ assert entries[0]["previous_expiration_date"] is None
+ assert entries[0]["new_is_lifetime"] is False
+ assert entries[0]["new_expiration_date"] == "2030-01-01"
+ assert entries[0]["reason"] == "Corrected from lifetime to 5-year limit"
+ assert entries[0]["changed_by"] == "Test User"
+ assert entries[0]["changed_at"]
+
+ assert entries[1]["previous_is_lifetime"] is False
+ assert entries[1]["previous_expiration_date"] == "2028-01-01"
+ assert entries[1]["new_is_lifetime"] is True
+ assert entries[1]["new_expiration_date"] is None
+ assert entries[1]["reason"] == "Upgraded to lifetime coverage"
+
+ assert entries[2]["previous_expiration_date"] == "2026-07-01"
+ assert entries[2]["new_expiration_date"] == "2028-01-01"
+ assert entries[2]["reason"] is None
+
+ assert entries[3]["previous_expiration_date"] == "2026-01-01"
+ assert entries[3]["new_expiration_date"] == "2026-07-01"
+ assert entries[3]["reason"] == "Extended 6 months after repair claim"
+
+
+def test_expiry_change_reason_length_limit_rejected(client, user_factory):
+ user = user_factory()
+ wid = _create_warranty(client, user["headers"], exact_expiration_date="2027-01-01")
+
+ r = client.put(
+ f"/api/warranties/{wid}",
+ data={
+ "product_name": "Test Laptop",
+ "purchase_date": "2025-01-01",
+ "exact_expiration_date": "2028-01-01",
+ "expiry_change_reason": "x" * 256,
+ },
+ headers=user["headers"],
+ )
+ assert r.status_code == 400
+ payload = r.get_json()
+ assert payload["code"] == "expiry_change_reason_too_long"
+
+ # Warranty date and history must be untouched
+ hist = client.get(f"/api/warranties/{wid}/expiry-history", headers=user["headers"]).get_json()
+ assert hist == []
+
+
+def test_expiry_change_count_exposed_across_list_debug_and_stats_endpoints(
+ client, admin_user, user_factory
+):
+ user = user_factory()
+ wid = _create_warranty(
+ client,
+ user["headers"],
+ product_name="Counted Device",
+ exact_expiration_date="2026-06-01",
+ )
+
+ for new_date in ("2027-06-01", "2028-06-01"):
+ r = client.put(
+ f"/api/warranties/{wid}",
+ data={
+ "product_name": "Counted Device",
+ "purchase_date": "2025-01-01",
+ "exact_expiration_date": new_date,
+ },
+ headers=user["headers"],
+ )
+ assert r.status_code == 200
+
+ _set_global_view(client, admin_user["headers"], enabled=True, admin_only=False)
+ try:
+ # Personal list
+ personal = client.get("/api/warranties", headers=user["headers"]).get_json()
+ assert next(w for w in personal if w["id"] == wid)["expiry_change_count"] == 2
+
+ # Admin list
+ admin_list = client.get("/api/admin/warranties", headers=admin_user["headers"]).get_json()
+ assert next(w for w in admin_list if w["id"] == wid)["expiry_change_count"] == 2
+
+ # Global list
+ global_list = client.get("/api/warranties/global", headers=user["headers"]).get_json()
+ assert next(w for w in global_list if w["id"] == wid)["expiry_change_count"] == 2
+
+ # Debug endpoint
+ debug_w = client.get(f"/api/debug/warranty/{wid}", headers=user["headers"]).get_json()
+ assert debug_w["expiry_change_count"] == 2
+
+ # Personal statistics all_warranties
+ stats = client.get("/api/statistics", headers=user["headers"]).get_json()
+ assert next(w for w in stats["all_warranties"] if w["id"] == wid)["expiry_change_count"] == 2
+
+ # Global statistics all_warranties
+ gstats = client.get("/api/statistics/global", headers=user["headers"]).get_json()
+ assert next(w for w in gstats["all_warranties"] if w["id"] == wid)["expiry_change_count"] == 2
+
+ # Archive and verify archived + global/archived lists
+ arch = client.patch(
+ f"/api/warranties/{wid}/archive",
+ json={"archived": True},
+ headers=user["headers"],
+ )
+ assert arch.status_code == 200
+
+ archived = client.get("/api/warranties/archived", headers=user["headers"]).get_json()
+ assert next(w for w in archived if w["id"] == wid)["expiry_change_count"] == 2
+
+ g_archived = client.get("/api/warranties/global/archived", headers=user["headers"]).get_json()
+ assert next(w for w in g_archived if w["id"] == wid)["expiry_change_count"] == 2
+ finally:
+ _set_global_view(client, admin_user["headers"], enabled=True, admin_only=False)
+
+
+def test_expiry_history_access_control_matrix(client, admin_user, user_factory):
+ owner = user_factory()
+ stranger = user_factory()
+ wid = _create_warranty(client, owner["headers"], exact_expiration_date="2026-01-01")
+ r = client.put(
+ f"/api/warranties/{wid}",
+ data={
+ "product_name": "Test Laptop",
+ "purchase_date": "2025-01-01",
+ "exact_expiration_date": "2027-01-01",
+ "expiry_change_reason": "Warranty extension",
+ },
+ headers=owner["headers"],
+ )
+ assert r.status_code == 200
+
+ try:
+ # 1. Global view enabled for all -> owner, admin, stranger all see history
+ _set_global_view(client, admin_user["headers"], enabled=True, admin_only=False)
+ assert client.get(f"/api/warranties/{wid}/expiry-history", headers=owner["headers"]).status_code == 200
+ assert client.get(f"/api/warranties/{wid}/expiry-history", headers=admin_user["headers"]).status_code == 200
+ stranger_resp = client.get(f"/api/warranties/{wid}/expiry-history", headers=stranger["headers"])
+ assert stranger_resp.status_code == 200
+ assert len(stranger_resp.get_json()) == 1
+
+ # 2. Global view admin-only -> stranger gets 404, owner & admin get 200
+ _set_global_view(client, admin_user["headers"], enabled=True, admin_only=True)
+ assert client.get(f"/api/warranties/{wid}/expiry-history", headers=owner["headers"]).status_code == 200
+ assert client.get(f"/api/warranties/{wid}/expiry-history", headers=admin_user["headers"]).status_code == 200
+ assert client.get(f"/api/warranties/{wid}/expiry-history", headers=stranger["headers"]).status_code == 404
+
+ # 3. Global view disabled -> stranger gets 404, owner & admin still get 200
+ _set_global_view(client, admin_user["headers"], enabled=False, admin_only=False)
+ assert client.get(f"/api/warranties/{wid}/expiry-history", headers=owner["headers"]).status_code == 200
+ assert client.get(f"/api/warranties/{wid}/expiry-history", headers=admin_user["headers"]).status_code == 200
+ assert client.get(f"/api/warranties/{wid}/expiry-history", headers=stranger["headers"]).status_code == 404
+
+ # 4. Non-existent warranty returns 404 even for admin
+ assert client.get("/api/warranties/99999999/expiry-history", headers=admin_user["headers"]).status_code == 404
+ finally:
+ _set_global_view(client, admin_user["headers"], enabled=True, admin_only=False)
+
+
+def test_expiry_history_cascade_and_deleted_editor_nullability(
+ client, admin_user, user_factory, db_connection
+):
+ owner = user_factory()
+ editor = user_factory()
+ wid = _create_warranty(client, owner["headers"], exact_expiration_date="2026-01-01")
+
+ # Promote editor to admin so they can edit owner's warranty, then delete editor
+ with db_connection.cursor() as cur:
+ cur.execute("SELECT id FROM users WHERE username = %s", (editor["username"],))
+ editor_id = cur.fetchone()[0]
+ cur.execute("UPDATE users SET is_admin = TRUE WHERE id = %s", (editor_id,))
+ db_connection.commit()
+
+ # Re-login editor so token carries is_admin=True
+ login_r = client.post(
+ "/api/auth/login",
+ json={"username": editor["username"], "password": "TestPass123!"},
+ )
+ assert login_r.status_code == 200
+ editor_admin_headers = {"Authorization": f"Bearer {login_r.get_json()['token']}"}
+
+ r = client.put(
+ f"/api/warranties/{wid}",
+ data={
+ "product_name": "Test Laptop",
+ "purchase_date": "2025-01-01",
+ "exact_expiration_date": "2028-01-01",
+ "expiry_change_reason": "Adjusted by support admin",
+ },
+ headers=editor_admin_headers,
+ )
+ assert r.status_code == 200
+
+ # Delete editor account; ON DELETE SET NULL keeps history intact with changed_by=None
+ del_u = client.delete(f"/api/admin/users/{editor_id}", headers=admin_user["headers"])
+ assert del_u.status_code == 200, del_u.get_data(as_text=True)
+
+ hist = client.get(f"/api/warranties/{wid}/expiry-history", headers=owner["headers"])
+ assert hist.status_code == 200
+ entries = hist.get_json()
+ assert len(entries) == 1
+ assert entries[0]["changed_by"] is None
+ assert entries[0]["reason"] == "Adjusted by support admin"
+
+ # Delete warranty; ON DELETE CASCADE removes all expiry history rows
+ del_w = client.delete(f"/api/warranties/{wid}", headers=owner["headers"])
+ assert del_w.status_code == 200
+
+ with db_connection.cursor() as cur:
+ cur.execute("SELECT COUNT(*) FROM warranty_expiry_history WHERE warranty_id = %s", (wid,))
+ assert cur.fetchone()[0] == 0
+
+
+def test_expiry_history_frontend_uses_dom_textcontent_not_innerhtml():
+ src_path = os.path.join(REPO_ROOT, "frontend", "js", "components", "expiryHistory.js")
+ with open(src_path, encoding="utf-8") as fh:
+ src = fh.read()
+ assert "innerHTML" not in src
+ assert "reasonEl.textContent" in src
+ assert "metaEl.textContent" in src