Skip to content

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

Fix pre-1.0.8 regressions in photo pinning, team notes, scheduler, Paperless, and expiry history

sassanix7fb987a0efa1
diff --git a/backend/gunicorn_config.py b/backend/gunicorn_config.py
index 146927c..be3bf89 100644
--- a/backend/gunicorn_config.py
+++ b/backend/gunicorn_config.py
@@ -70,6 +70,13 @@ else:
worker_rlimit_as = 134217728 # 128MB per worker limit
print("Using OPTIMIZED memory mode - balanced RAM usage and performance")
+# Export worker_class and master PID before when_ready so the master's
+# scheduler selects GeventScheduler when gevent monkey-patching is active
+# (avoiding BackgroundScheduler threading._active KeyErrors in forked
+# workers) and workers can read the master's live scheduler status (#299).
+os.environ["GUNICORN_WORKER_CLASS"] = worker_class
+os.environ["WARRACKER_GUNICORN_MASTER_PID"] = str(os.getpid())
+
# Note: Gevent monkey patching was applied early at top of file for SSL compatibility
if worker_class == "gevent":
print(f"ℹ️ Using gevent workers with early monkey patching applied.")
diff --git a/backend/notifications.py b/backend/notifications.py
index db62aee..c3b75ce 100644
--- a/backend/notifications.py
+++ b/backend/notifications.py
@@ -917,6 +917,90 @@ def should_run_scheduler():
return True
+def _master_scheduler_status_path(master_pid=None):
+ """Path to the live scheduler status snapshot written by the gunicorn master."""
+ import tempfile
+ pid = master_pid or os.environ.get('WARRACKER_GUNICORN_MASTER_PID') or os.getpid()
+ return os.path.join(tempfile.gettempdir(), f'warracker_scheduler_status_{pid}.json')
+
+
+def _collect_local_scheduler_jobs():
+ """Return serializable job descriptors from the in-process scheduler."""
+ if not (scheduler and hasattr(scheduler, 'get_jobs')):
+ return False, []
+ try:
+ jobs = scheduler.get_jobs()
+ return bool(scheduler.running), [
+ {
+ 'id': job.id,
+ 'next_run_time': job.next_run_time.isoformat() if job.next_run_time else None,
+ 'trigger': str(job.trigger),
+ }
+ for job in jobs
+ ]
+ except Exception as e:
+ logger.error(f"Error getting scheduler jobs: {e}")
+ return False, []
+
+
+def _write_master_scheduler_status():
+ """Publish the master's live scheduler status so gunicorn workers can read it (#299)."""
+ if not os.environ.get('WARRACKER_GUNICORN_MASTER') or os.environ.get('GUNICORN_WORKER_ID') is not None:
+ return
+ try:
+ import json
+ running, jobs = _collect_local_scheduler_jobs()
+ payload = {
+ 'master_pid': os.getpid(),
+ 'scheduler_initialized': bool(scheduler_initialized),
+ 'scheduler_running': running,
+ 'scheduler_jobs': jobs,
+ 'updated_at': datetime.now(UTC).isoformat(),
+ }
+ path = _master_scheduler_status_path(os.getpid())
+ tmp_path = f"{path}.{os.getpid()}.tmp"
+ with open(tmp_path, 'w', encoding='utf-8') as fh:
+ json.dump(payload, fh)
+ os.replace(tmp_path, path)
+ except Exception as e:
+ logger.debug(f"Could not write master scheduler status snapshot: {e}")
+
+
+def _clear_master_scheduler_status():
+ """Remove the master scheduler status snapshot on master shutdown."""
+ if not os.environ.get('WARRACKER_GUNICORN_MASTER') or os.environ.get('GUNICORN_WORKER_ID') is not None:
+ return
+ try:
+ path = _master_scheduler_status_path(os.getpid())
+ if os.path.exists(path):
+ os.remove(path)
+ except Exception:
+ pass
+
+
+def _read_master_scheduler_status():
+ """Read the gunicorn master's scheduler snapshot from a worker process."""
+ master_pid_str = os.environ.get('WARRACKER_GUNICORN_MASTER_PID')
+ if not master_pid_str:
+ return None
+ try:
+ master_pid = int(master_pid_str)
+ # Verify the master process is alive before trusting the snapshot.
+ os.kill(master_pid, 0)
+ except (ValueError, OSError):
+ return None
+ try:
+ import json
+ path = _master_scheduler_status_path(master_pid)
+ with open(path, 'r', encoding='utf-8') as fh:
+ data = json.load(fh)
+ if data.get('master_pid') != master_pid:
+ return None
+ return data
+ except Exception:
+ return None
+
+
def discard_inherited_scheduler():
"""Drop a scheduler inherited across a fork, without closing it.
@@ -924,19 +1008,33 @@ def discard_inherited_scheduler():
before forking, so every worker inherits a running copy (#299).
That copy must never send. Shutting it down would join its thread,
which is a copy of the master's dead thread, so instead remove its
- only job and mark it stopped: the loop then exits on its next
- wakeup having sent nothing. The master keeps the real scheduler.
- Safe to call when no scheduler exists.
+ only job, mark it stopped, and wake/stop any inherited event or
+ greenlet so it exits immediately without sending anything. The
+ master keeps the real scheduler. Safe to call when no scheduler
+ exists.
"""
global scheduler, scheduler_initialized
if scheduler is None:
return
+ old_scheduler = scheduler
+ try:
+ old_scheduler.remove_job('notification_job')
+ except Exception:
+ pass
+ try:
+ old_scheduler.state = STATE_STOPPED
+ except Exception:
+ pass
try:
- scheduler.remove_job('notification_job')
+ ev = getattr(old_scheduler, '_event', None)
+ if ev is not None and hasattr(ev, 'set'):
+ ev.set()
except Exception:
pass
try:
- scheduler.state = STATE_STOPPED
+ greenlet = getattr(old_scheduler, '_greenlet', None)
+ if greenlet is not None and hasattr(greenlet, 'kill'):
+ greenlet.kill(block=False)
except Exception:
pass
scheduler = None
@@ -1010,12 +1108,15 @@ def init_scheduler(app, get_db_connection, release_db_connection, force=False):
# ---> FIX: Create a wrapper that pushes an app context <---
def notification_job_with_context():
- with app.app_context():
- send_expiration_notifications(
- manual_trigger=False,
- get_db_connection=get_db_connection,
- release_db_connection=release_db_connection
- )
+ try:
+ with app.app_context():
+ send_expiration_notifications(
+ manual_trigger=False,
+ get_db_connection=get_db_connection,
+ release_db_connection=release_db_connection
+ )
+ finally:
+ _write_master_scheduler_status()
# Only add the job once: a second init_scheduler call (from
# app.py after create_app, or from when_ready after create_app)
@@ -1030,12 +1131,16 @@ def init_scheduler(app, get_db_connection, release_db_connection, force=False):
# been discarded (set to None) by a forked worker, or
# already stopped by another hook; the hook is inherited
# across the fork too, so more than one may be registered.
- atexit.register(lambda: scheduler.shutdown()
- if scheduler is not None and scheduler.running
- else None)
+ def _shutdown_scheduler():
+ _clear_master_scheduler_status()
+ if scheduler is not None and scheduler.running:
+ scheduler.shutdown()
+
+ atexit.register(_shutdown_scheduler)
else:
logger.info("ℹ️ Notification scheduler already running; keeping the existing job")
scheduler_initialized = True
+ _write_master_scheduler_status()
return True
except Exception as e:
logger.error(f"❌ Failed to start scheduler: {e}")
@@ -1058,29 +1163,31 @@ def get_scheduler_status():
worker_name = os.environ.get('GUNICORN_WORKER_PROCESS_NAME', 'unknown')
worker_class = os.environ.get('GUNICORN_WORKER_CLASS', 'unknown')
- scheduler_jobs = []
- scheduler_running = False
-
- if scheduler and hasattr(scheduler, 'get_jobs'):
- try:
- jobs = scheduler.get_jobs()
- scheduler_running = scheduler.running
- scheduler_jobs = [
- {
- 'id': job.id,
- 'next_run_time': job.next_run_time.isoformat() if job.next_run_time else None,
- 'trigger': str(job.trigger)
- }
- for job in jobs
- ]
- except Exception as e:
- logger.error(f"Error getting scheduler jobs: {e}")
+ scheduler_running, scheduler_jobs = _collect_local_scheduler_jobs()
+ effective_initialized = scheduler_initialized
+ scheduler_owner = 'current-process'
+
+ # Under gunicorn, HTTP requests always hit a worker whose local copy
+ # was discarded in post_fork; read the live snapshot published by the
+ # gunicorn master so admin diagnostics reflect reality (#299).
+ if (
+ not scheduler_running
+ and os.environ.get('WARRACKER_GUNICORN_MASTER')
+ and os.environ.get('GUNICORN_WORKER_ID') is not None
+ ):
+ master_status = _read_master_scheduler_status()
+ if master_status is not None:
+ effective_initialized = bool(master_status.get('scheduler_initialized'))
+ scheduler_running = bool(master_status.get('scheduler_running'))
+ scheduler_jobs = master_status.get('scheduler_jobs', [])
+ scheduler_owner = 'gunicorn-master'
return {
- 'scheduler_initialized': scheduler_initialized,
+ 'scheduler_initialized': effective_initialized,
'scheduler_retry_attempted': scheduler_retry_attempted,
'scheduler_running': scheduler_running,
'scheduler_jobs': scheduler_jobs,
+ 'scheduler_owner': scheduler_owner,
'worker_info': {
'worker_id': worker_id,
'worker_name': worker_name,
diff --git a/backend/paperless_handler.py b/backend/paperless_handler.py
index 22fb8b7..3c35a94 100644
--- a/backend/paperless_handler.py
+++ b/backend/paperless_handler.py
@@ -701,20 +701,26 @@ class PaperlessHandler:
task_url_legacy_list = f"{self.paperless_url}/api/tasks/"
deadline = time.time() + timeout_secs
+ use_list_endpoint = False
while time.time() < deadline:
try:
- try:
- resp = self.get(task_url_primary, timeout=10)
- if resp.status_code == 404:
- # Fall back to legacy ?task_id=<uuid> filter
- resp = self.get(task_url_legacy_list, params={"task_id": task_id}, timeout=10)
- except requests.exceptions.HTTPError as http_err:
- if http_err.response.status_code == 404 and http_err.response.url.rstrip('/') == task_url_primary.rstrip('/'):
- # Primary endpoint not available, try legacy
- resp = self.get(task_url_legacy_list, params={"task_id": task_id}, timeout=10)
- else:
- raise
+ if use_list_endpoint:
+ resp = self.get(task_url_legacy_list, params={"task_id": task_id}, timeout=10)
+ else:
+ try:
+ resp = self.get(task_url_primary, timeout=10)
+ if resp.status_code == 404:
+ # Fall back to legacy ?task_id=<uuid> filter and keep using it
+ use_list_endpoint = True
+ resp = self.get(task_url_legacy_list, params={"task_id": task_id}, timeout=10)
+ except requests.exceptions.HTTPError as http_err:
+ if http_err.response.status_code == 404 and http_err.response.url.rstrip('/') == task_url_primary.rstrip('/'):
+ # Primary endpoint not available, try legacy and remember it
+ use_list_endpoint = True
+ resp = self.get(task_url_legacy_list, params={"task_id": task_id}, timeout=10)
+ else:
+ raise
resp.raise_for_status()
diff --git a/backend/warranties_routes.py b/backend/warranties_routes.py
index 717b426..6cc03bb 100644
--- a/backend/warranties_routes.py
+++ b/backend/warranties_routes.py
@@ -226,14 +226,23 @@ class _PinnedPhotoAdapter(requests.adapters.HTTPAdapter):
def _resolve_and_pin(self, hostname):
"""One resolve-validate-pin cycle for a hop hostname.
- Returns the IP string to connect to."""
+ Returns the IP string to connect to.
+
+ Every returned address is validated against the public-address
+ guard so a mixed public/private answer is always rejected. When
+ a dual-stack host returns both IPv6 and IPv4 addresses, prefer
+ IPv4 so standard IPv4-only Docker containers do not fail with
+ ENETUNREACH on an unreachable AAAA record, while IPv6-only hosts
+ still connect via their validated IPv6 address.
+ """
try:
infos = socket.getaddrinfo(hostname, None)
except Exception:
raise _PhotoHostRejectedError(hostname)
if not infos:
raise _PhotoHostRejectedError(hostname)
- pinned = None
+ first_any = None
+ first_ipv4 = None
for info in infos:
try:
addr = ipaddress.ip_address(info[4][0])
@@ -241,9 +250,11 @@ class _PinnedPhotoAdapter(requests.adapters.HTTPAdapter):
raise _PhotoHostRejectedError(hostname)
if not self._allow_private and not _ip_address_is_public(addr):
raise _PhotoHostRejectedError(hostname)
- if pinned is None:
- pinned = info[4][0]
- return pinned
+ if first_any is None:
+ first_any = info[4][0]
+ if first_ipv4 is None and addr.version == 4:
+ first_ipv4 = info[4][0]
+ return first_ipv4 or first_any
def build_connection_pool_key_attributes(self, request, verify,
cert=None):
@@ -479,7 +490,8 @@ def get_warranties():
WHEN BOOL_OR(c.status IN ('Submitted', 'In Progress')) THEN 'OPEN'
ELSE 'FINISHED'
END AS claim_status_summary,
- (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count,
+ (SELECT COUNT(*) FROM warranty_note_entries n WHERE n.warranty_id = w.id) AS note_entry_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
@@ -549,7 +561,8 @@ def get_archived_warranties():
WHEN BOOL_OR(c.status IN ('Submitted', 'In Progress')) THEN 'OPEN'
ELSE 'FINISHED'
END AS claim_status_summary,
- (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count,
+ (SELECT COUNT(*) FROM warranty_note_entries n WHERE n.warranty_id = w.id) AS note_entry_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
@@ -1580,7 +1593,12 @@ def update_warranty(warranty_id):
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):
+ new_is_lifetime = bool(is_lifetime)
+ expiry_changed = (
+ existing_is_lifetime != new_is_lifetime
+ or (not existing_is_lifetime and not new_is_lifetime and existing_expiration_date != expiration_date)
+ )
+ if expiry_changed:
cur.execute('''
INSERT INTO warranty_expiry_history (
warranty_id,
@@ -1597,7 +1615,7 @@ def update_warranty(warranty_id):
existing_expiration_date,
expiration_date,
existing_is_lifetime,
- bool(is_lifetime),
+ new_is_lifetime,
expiry_change_reason,
user_id,
))
@@ -2132,7 +2150,8 @@ def get_all_warranties():
WHEN BOOL_OR(c.status IN ('Submitted', 'In Progress')) THEN 'OPEN'
ELSE 'FINISHED'
END AS claim_status_summary,
- (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count,
+ (SELECT COUNT(*) FROM warranty_note_entries n WHERE n.warranty_id = w.id) AS note_entry_count
FROM warranties w
JOIN users u ON w.user_id = u.id
LEFT JOIN warranty_claims c ON w.id = c.warranty_id
@@ -2247,7 +2266,8 @@ def get_global_warranties():
) THEN 'FINISHED'
ELSE 'NO_CLAIMS'
END AS claim_status_summary,
- (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count,
+ (SELECT COUNT(*) FROM warranty_note_entries n WHERE n.warranty_id = w.id) AS note_entry_count
FROM warranties w
JOIN users u ON w.user_id = u.id
WHERE w.archived_at IS NULL
@@ -2361,7 +2381,8 @@ def get_global_warranties_archived():
) THEN 'FINISHED'
ELSE 'NO_CLAIMS'
END AS claim_status_summary,
- (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count,
+ (SELECT COUNT(*) FROM warranty_note_entries n WHERE n.warranty_id = w.id) AS note_entry_count
FROM warranties w
JOIN users u ON w.user_id = u.id
WHERE w.archived_at IS NOT NULL
@@ -2560,7 +2581,8 @@ def get_warranty_debug(warranty_id):
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,
- (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count,
+ (SELECT COUNT(*) FROM warranty_note_entries n WHERE n.warranty_id = w.id) AS note_entry_count
FROM warranties w
JOIN users u ON w.user_id = u.id
WHERE w.id = %s
@@ -2572,7 +2594,8 @@ def get_warranty_debug(warranty_id):
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,
- (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count
+ (SELECT COUNT(*) FROM warranty_expiry_history h WHERE h.warranty_id = w.id) AS expiry_change_count,
+ (SELECT COUNT(*) FROM warranty_note_entries n WHERE n.warranty_id = w.id) AS note_entry_count
FROM warranties w
JOIN users u ON w.user_id = u.id
WHERE w.id = %s AND w.user_id = %s
@@ -3161,8 +3184,8 @@ def create_warranty_note_entry(warranty_id):
try:
user_id = request.user['id']
is_admin = request.user.get('is_admin', False)
- data = request.get_json()
- if not data:
+ data = request.get_json(silent=True)
+ if not isinstance(data, dict):
return jsonify({'error': 'No data provided'}), 400
text = data.get('text')
if not isinstance(text, str) or not text.strip():
diff --git a/frontend/js/components/notes.js b/frontend/js/components/notes.js
index 322bad6..e78e4a8 100644
--- a/frontend/js/components/notes.js
+++ b/frontend/js/components/notes.js
@@ -267,7 +267,8 @@ async function saveNotes() {
hideLoadingSpinner();
showToast((window.i18next && window.i18next.t('messages.note_updated_successfully') || 'Note updated'), 'success');
updateStoreNotes(noteValue);
- if (!noteValue) {
+ const hasTeamNotes = Boolean(dom?.thread && dom.thread.children.length > 0);
+ if (!noteValue && !hasTeamNotes) {
hideModal();
} else if (dom) {
dom.content.textContent = noteValue;
@@ -281,6 +282,18 @@ async function saveNotes() {
}
}
+let noteEntriesRequestToken = 0;
+
+function updateStoreNoteEntryCount(count) {
+ const warranties = getWarranties();
+ const index = warranties.findIndex((w) => w.id === state.warrantyId);
+ if (index === -1) return;
+ const updated = [...warranties];
+ updated[index] = { ...updated[index], note_entry_count: count };
+ setWarranties(updated);
+ state.warranty = updated[index];
+}
+
// Team note entries: anyone who can view the warranty may add one,
// and each entry shows its author and time. Deleting is for the entry
// author, the warranty owner, or an admin. Entry text and usernames
@@ -335,12 +348,17 @@ async function loadNoteEntries() {
if (!dom || !state.warrantyId) return;
const token = getToken();
if (!token) return;
+ const requestToken = ++noteEntriesRequestToken;
+ const requestedWarrantyId = state.warrantyId;
try {
const response = await fetch(`/api/warranties/${state.warrantyId}/notes`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) return;
- renderNoteEntries(await response.json());
+ const entries = await response.json();
+ if (requestToken !== noteEntriesRequestToken || state.warrantyId !== requestedWarrantyId) return;
+ renderNoteEntries(entries);
+ updateStoreNoteEntryCount(Array.isArray(entries) ? entries.length : 0);
} catch (error) {
console.error('[notes] Failed to load note entries', error);
}
@@ -355,6 +373,8 @@ async function addNoteEntry() {
showToast((window.i18next && window.i18next.t('messages.authentication_required') || 'Authentication required'), 'error');
return;
}
+ if (dom.addBtn?.disabled) return;
+ if (dom.addBtn) dom.addBtn.disabled = true;
try {
const response = await fetch(`/api/warranties/${state.warrantyId}/notes`, {
method: 'POST',
@@ -367,9 +387,12 @@ async function addNoteEntry() {
}
dom.addTextarea.value = '';
await loadNoteEntries();
+ await refreshWarranties();
} catch (error) {
console.error('[notes] Failed to add note entry', error);
showToast(error.message || 'Failed to add note', 'error');
+ } finally {
+ if (dom?.addBtn) dom.addBtn.disabled = false;
}
}
@@ -387,6 +410,7 @@ async function deleteNoteEntry(entryId) {
throw new Error(errorData.error || `Failed to delete note (Status: ${response.status})`);
}
await loadNoteEntries();
+ await refreshWarranties();
} catch (error) {
console.error('[notes] Failed to delete note entry', error);
showToast(error.message || 'Failed to delete note', 'error');
@@ -408,6 +432,7 @@ export function showNotesModal(notes, warrantyOrId = null) {
if (!refs.modal) return;
refs.content.textContent = contentText || '';
refs.textarea.value = contentText || '';
+ if (refs.thread) refs.thread.innerHTML = '';
if (refs.editWarrantyBtn) {
const canEdit = canEditWarranty(warranty);
refs.editWarrantyBtn.disabled = !canEdit;
diff --git a/frontend/js/components/warrantyRenderer.js b/frontend/js/components/warrantyRenderer.js
index 0ba0c60..19aed03 100644
--- a/frontend/js/components/warrantyRenderer.js
+++ b/frontend/js/components/warrantyRenderer.js
@@ -178,11 +178,12 @@ function buildTagsHtml(tags = []) {
function buildNotesLink(warranty) {
const notes = (warranty.notes || '').trim();
- if (!notes) return { hasNotes: false, html: '' };
+ const entryCount = Number(warranty.note_entry_count) || 0;
const label = t('warranties.notes', 'Notes');
+ const countSuffix = entryCount > 0 ? ` (${entryCount})` : '';
return {
- hasNotes: true,
- html: `<a href="#" class="notes-link" data-id="${warranty.id}" title="${label}"><i class='fas fa-sticky-note'></i> ${label}</a>`,
+ hasNotes: Boolean(notes) || entryCount > 0,
+ html: `<a href="#" class="notes-link" data-id="${warranty.id}" title="${label}"><i class='fas fa-sticky-note'></i> ${label}${countSuffix}</a>`,
};
}
diff --git a/frontend/script.js b/frontend/script.js
index 64f237b..34f09e2 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -1769,15 +1769,14 @@ async function renderWarranties(warrantiesToRender) {
).join('')}
</div>`
: '';
- // Add notes display button if present
+ // Always show the Notes link so owners and viewers can open team notes
+ // even when the warranty's own notes field is blank.
let notesHtml = '';
- const hasNotes = warranty.notes && warranty.notes.trim() !== '';
- // Remove the button, and instead prepare a notes link for document-links-row
- let notesLinkHtml = '';
- if (hasNotes) {
- const notesLabel = (window.i18next && window.i18next.t('warranties.notes') || 'Notes');
- notesLinkHtml = `<a href="#" class="notes-link" data-id="${warranty.id}" title="View Notes"><i class='fas fa-sticky-note'></i> ${notesLabel}</a>`;
- }
+ const noteEntryCount = Number(warranty.note_entry_count) || 0;
+ const hasNotes = Boolean((warranty.notes && warranty.notes.trim() !== '') || noteEntryCount > 0);
+ const notesLabel = (window.i18next && window.i18next.t('warranties.notes') || 'Notes');
+ const notesCountSuffix = noteEntryCount > 0 ? ` (${noteEntryCount})` : '';
+ const notesLinkHtml = `<a href="#" class="notes-link" data-id="${warranty.id}" title="View Notes"><i class='fas fa-sticky-note'></i> ${notesLabel}${notesCountSuffix}</a>`;
const hasDocuments = Boolean(
warranty.product_url ||
@@ -1786,7 +1785,7 @@ async function renderWarranties(warrantiesToRender) {
warranty.other_document_path || warranty.other_document_url ||
warranty.paperless_invoice_id || warranty.paperless_manual_id ||
warranty.paperless_photo_id || warranty.paperless_other_id ||
- hasNotes
+ notesLinkHtml
);
diff --git a/tests/test_paperless_api_v10.py b/tests/test_paperless_api_v10.py
index bda9b6d..22f2243 100644
--- a/tests/test_paperless_api_v10.py
+++ b/tests/test_paperless_api_v10.py
@@ -149,11 +149,13 @@ def test_v10_running_then_success():
done = {"count": 1, "next": None, "previous": None,
"results": [{"id": 7, "task_id": TASK_ID,
"status": "success", "related_document_ids": [420]}]}
- _stub_get(handler,
- primary=(404, {"detail": "Not found"}),
- task_list=[running, done])
+ calls = _stub_get(handler,
+ primary=(404, {"detail": "Not found"}),
+ task_list=[running, done])
assert handler._get_document_id_from_task(
TASK_ID, timeout_secs=5, poll_interval=0.01) == 420
+ assert calls["primary"] == 1
+ assert calls["list"] == 2
def test_v9_detail_poll_still_works():
diff --git a/tests/test_photo_url.py b/tests/test_photo_url.py
index 24fd7f7..e3cbc43 100644
--- a/tests/test_photo_url.py
+++ b/tests/test_photo_url.py
@@ -549,3 +549,46 @@ def test_photo_fetch_timeout_env_var_enforced_end_to_end(monkeypatch):
assert time.monotonic() - start < 10
finally:
server.shutdown()
+
+
+def test_dual_stack_prefers_validated_ipv4_and_still_validates_ipv6(monkeypatch, app):
+ """Dual-stack hosts returning IPv6 before IPv4 pin the validated IPv4
+ address so IPv4-only Docker containers can connect, IPv6-only hosts
+ still pin IPv6, and any private IPv4 or IPv6 in the answer rejects
+ the host."""
+ import socket
+ from backend.warranties_routes import _PinnedPhotoAdapter, _PhotoHostRejectedError
+
+ real_getaddrinfo = socket.getaddrinfo
+
+ def fake(host, port, *args, **kwargs):
+ if host == "dual.example.invalid":
+ return [
+ (socket.AF_INET6, socket.SOCK_STREAM, 0, "", ("2606:2800:220:1:248:1893:25c8:1946", port or 80, 0, 0)),
+ (socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", port or 80)),
+ ]
+ if host == "v6only.example.invalid":
+ return [
+ (socket.AF_INET6, socket.SOCK_STREAM, 0, "", ("2606:2800:220:1:248:1893:25c8:1946", port or 80, 0, 0)),
+ ]
+ if host == "mixed-private-v6.example.invalid":
+ return [
+ (socket.AF_INET6, socket.SOCK_STREAM, 0, "", ("::1", port or 80, 0, 0)),
+ (socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", port or 80)),
+ ]
+ if host == "mixed-private-v4.example.invalid":
+ return [
+ (socket.AF_INET6, socket.SOCK_STREAM, 0, "", ("2606:2800:220:1:248:1893:25c8:1946", port or 80, 0, 0)),
+ (socket.AF_INET, socket.SOCK_STREAM, 0, "", ("10.0.0.1", port or 80)),
+ ]
+ return real_getaddrinfo(host, port, *args, **kwargs)
+
+ monkeypatch.setattr(socket, "getaddrinfo", fake)
+ adapter = _PinnedPhotoAdapter(allow_private=False)
+ assert adapter._resolve_and_pin("dual.example.invalid") == "93.184.216.34"
+ assert adapter._resolve_and_pin("v6only.example.invalid") == "2606:2800:220:1:248:1893:25c8:1946"
+ with pytest.raises(_PhotoHostRejectedError):
+ adapter._resolve_and_pin("mixed-private-v6.example.invalid")
+ with pytest.raises(_PhotoHostRejectedError):
+ adapter._resolve_and_pin("mixed-private-v4.example.invalid")
+
diff --git a/tests/test_scheduler_single_process.py b/tests/test_scheduler_single_process.py
index cc3be0a..f58e754 100644
--- a/tests/test_scheduler_single_process.py
+++ b/tests/test_scheduler_single_process.py
@@ -229,3 +229,61 @@ def test_forked_pool_is_discarded_and_recreated(db_connection):
# The discarded pool is gone for good; the fresh pool created
# above is the live one now. Nothing to restore.
pass
+
+
+def test_discard_wakes_event_and_kills_greenlet(monkeypatch):
+ events = []
+ fake = types.SimpleNamespace(
+ remove_job=lambda job_id: events.append(("remove", job_id)),
+ state=1,
+ _event=types.SimpleNamespace(set=lambda: events.append(("event_set",))),
+ _greenlet=types.SimpleNamespace(kill=lambda block=False: events.append(("kill", block))),
+ )
+ monkeypatch.setattr(notifications, "scheduler", fake)
+ monkeypatch.setattr(notifications, "scheduler_initialized", True)
+ discard_inherited_scheduler()
+ assert ("remove", "notification_job") in events
+ assert ("event_set",) in events
+ assert ("kill", False) in events
+ assert notifications.scheduler is None
+
+
+def test_worker_get_scheduler_status_reads_master_snapshot(monkeypatch):
+ """Under gunicorn, /api/admin/scheduler-status hits a worker whose local
+ scheduler was discarded; it must read the live snapshot published by the
+ gunicorn master instead of reporting the scheduler as stopped."""
+ from datetime import datetime, UTC
+
+ fake_job = types.SimpleNamespace(
+ id="notification_job",
+ next_run_time=datetime(2026, 11, 25, 12, 0, 0, tzinfo=UTC),
+ trigger="interval[0:02:00]",
+ )
+ fake_master_sched = types.SimpleNamespace(
+ running=True,
+ get_jobs=lambda: [fake_job],
+ )
+ monkeypatch.setattr(notifications, "scheduler", fake_master_sched)
+ monkeypatch.setattr(notifications, "scheduler_initialized", True)
+ monkeypatch.setenv("WARRACKER_GUNICORN_MASTER", "1")
+ monkeypatch.setenv("WARRACKER_GUNICORN_MASTER_PID", str(os.getpid()))
+ monkeypatch.delenv("GUNICORN_WORKER_ID", raising=False)
+
+ try:
+ notifications._write_master_scheduler_status()
+
+ # Simulate a gunicorn worker that discarded its inherited scheduler
+ monkeypatch.setattr(notifications, "scheduler", None)
+ monkeypatch.setattr(notifications, "scheduler_initialized", False)
+ monkeypatch.setenv("GUNICORN_WORKER_ID", "0")
+
+ status = notifications.get_scheduler_status()
+ assert status["scheduler_initialized"] is True
+ assert status["scheduler_running"] is True
+ assert status["scheduler_owner"] == "gunicorn-master"
+ assert len(status["scheduler_jobs"]) == 1
+ assert status["scheduler_jobs"][0]["id"] == "notification_job"
+ finally:
+ monkeypatch.delenv("GUNICORN_WORKER_ID", raising=False)
+ notifications._clear_master_scheduler_status()
+
diff --git a/tests/test_status_edit_and_notes.py b/tests/test_status_edit_and_notes.py
index 0d2c29d..d018756 100644
--- a/tests/test_status_edit_and_notes.py
+++ b/tests/test_status_edit_and_notes.py
@@ -106,3 +106,20 @@ def test_note_entry_endpoints_exist():
assert "'/warranties/<int:warranty_id>/notes', methods=['GET']" in routes
assert "'/warranties/<int:warranty_id>/notes', methods=['POST']" in routes
assert "'/warranties/<int:warranty_id>/notes/<int:entry_id>', methods=['DELETE']" in routes
+
+
+def test_notes_link_always_rendered_and_modal_guards_race_and_double_submit():
+ renderer = (
+ REPO / "frontend" / "js" / "components" / "warrantyRenderer.js"
+ ).read_text()
+ idx = renderer.index("function buildNotesLink(warranty)")
+ block = renderer[idx:renderer.index("\n}\n", idx) + 3]
+ assert "if (!notes) return" not in block
+ assert "note_entry_count" in block
+ assert 'class="notes-link"' in block
+
+ notes = (REPO / "frontend" / "js" / "components" / "notes.js").read_text()
+ assert "refs.thread.innerHTML = ''" in notes
+ assert "noteEntriesRequestToken" in notes
+ assert "dom.addBtn.disabled = true" in notes
+
diff --git a/tests/test_warranty_expiry_history.py b/tests/test_warranty_expiry_history.py
index 52d006e..b18850d 100644
--- a/tests/test_warranty_expiry_history.py
+++ b/tests/test_warranty_expiry_history.py
@@ -383,3 +383,39 @@ def test_expiry_history_frontend_uses_dom_textcontent_not_innerhtml():
assert "innerHTML" not in src
assert "reasonEl.textContent" in src
assert "metaEl.textContent" in src
+
+
+def test_legacy_lifetime_with_stale_date_does_not_log_lifetime_to_lifetime(
+ client, user_factory, db_connection
+):
+ user = user_factory()
+ wid = _create_warranty(
+ client,
+ user["headers"],
+ product_name="Legacy Lifetime",
+ purchase_date="2025-01-01",
+ is_lifetime="true",
+ )
+ # Simulate a legacy lifetime row that still carried a non-null expiration_date
+ with db_connection.cursor() as cur:
+ cur.execute(
+ "UPDATE warranties SET expiration_date = '2099-01-01' WHERE id = %s",
+ (wid,),
+ )
+ db_connection.commit()
+
+ r = client.put(
+ f"/api/warranties/{wid}",
+ data={
+ "product_name": "Legacy Lifetime Renamed",
+ "purchase_date": "2025-01-01",
+ "is_lifetime": "true",
+ },
+ 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() == []
+
diff --git a/tests/test_warranty_note_entries.py b/tests/test_warranty_note_entries.py
index e17e3e3..deb0e01 100644
--- a/tests/test_warranty_note_entries.py
+++ b/tests/test_warranty_note_entries.py
@@ -236,3 +236,59 @@ def test_missing_warranty(client, scenario):
def test_unauthenticated(client, scenario):
r = client.get(f"/api/warranties/{scenario.wid}/notes")
assert r.status_code == 401
+
+
+def test_malformed_json_returns_400(client, scenario):
+ r = client.post(
+ f"/api/warranties/{scenario.wid}/notes",
+ data="not json",
+ content_type="text/plain",
+ headers=scenario.owner["headers"],
+ )
+ assert r.status_code == 400
+ r = client.post(
+ f"/api/warranties/{scenario.wid}/notes",
+ json=["not", "a", "dict"],
+ headers=scenario.owner["headers"],
+ )
+ assert r.status_code == 400
+
+
+def test_note_entry_count_exposed_on_warranty_endpoints(
+ client, user_factory, warranty_factory, _global_view
+):
+ _global_view("true", "false")
+ owner = user_factory()
+ viewer = user_factory()
+ created = warranty_factory(owner["headers"], product_name="BlankNotesWidget")
+ assert created.status_code == 201, created.get_data(as_text=True)
+ wid = created.get_json()["id"]
+
+ # Initially 0 team notes
+ personal = client.get("/api/warranties", headers=owner["headers"]).get_json()
+ assert next(w for w in personal if w["id"] == wid)["note_entry_count"] == 0
+
+ # Add two team notes (owner + viewer)
+ e1 = client.post(
+ f"/api/warranties/{wid}/notes", json={"text": "first"}, headers=owner["headers"]
+ )
+ e2 = client.post(
+ f"/api/warranties/{wid}/notes", json={"text": "second"}, headers=viewer["headers"]
+ )
+ assert e1.status_code == 201 and e2.status_code == 201
+
+ personal = client.get("/api/warranties", headers=owner["headers"]).get_json()
+ assert next(w for w in personal if w["id"] == wid)["note_entry_count"] == 2
+ global_list = client.get("/api/warranties/global", headers=viewer["headers"]).get_json()
+ assert next(w for w in global_list if w["id"] == wid)["note_entry_count"] == 2
+ debug_w = client.get(f"/api/debug/warranty/{wid}", headers=viewer["headers"]).get_json()
+ assert debug_w["note_entry_count"] == 2
+
+ # Deleting one drops the count to 1
+ d = client.delete(
+ f"/api/warranties/{wid}/notes/{e2.get_json()['id']}", headers=viewer["headers"]
+ )
+ assert d.status_code == 200
+ personal = client.get("/api/warranties", headers=owner["headers"]).get_json()
+ assert next(w for w in personal if w["id"] == wid)["note_entry_count"] == 1
+