🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Add team note entries on warranties (1.0.8)
Omega (QA)6d9b5b3db0e0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 008ffc3..6fa7b8a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,8 @@- _Files: `Dockerfile`_- **CI workflow pinning and Renovate action update (#279, #282):** pinned `actions/checkout`, `actions/setup-python`, the CI `postgres:15` service image, and Python version in the test and Docker workflows by commit SHA/digest for supply-chain safety, and updated `renovatebot/github-action` from v46.3.10 to v46.3.14.- _Files: `.github/workflows/tests.yml`, `.github/workflows/docker-build.yml`, `.github/workflows/renovate.yml`_+- **Team notes on warranties:** anyone who can view a warranty can now add a note to it, and each entry shows the username of the person who added it and the time it was added. Entries live in a new table, so the warranty's own notes field is untouched and stays editable only by the owner or an admin. An entry can be deleted by its author, the warranty owner, or an admin. With global view off, or restricted to admins, non-owners can neither view nor add entries.+ - _Files: `backend/migrations/056_create_warranty_note_entries.sql`, `backend/warranties_routes.py`, `frontend/js/components/notes.js`, `frontend/script.js`, `tests/test_warranty_note_entries.py`, `tests/test_status_edit_and_notes.py`_## 1.0.7 - 2026-11-23diff --git a/backend/migrations/056_create_warranty_note_entries.sql b/backend/migrations/056_create_warranty_note_entries.sqlnew file mode 100644index 0000000..d48458b--- /dev/null+++ b/backend/migrations/056_create_warranty_note_entries.sql@@ -0,0 +1,14 @@+-- Migration 056: team note entries on warranties (next release)+-- A warranty's single notes field stays owner-edited. Team members who+-- can view a warranty may add entries here instead, each attributed to+-- its author with a timestamp, and an entry can be deleted by its+-- author, the warranty owner, or an admin.+CREATE TABLE IF NOT EXISTS warranty_note_entries (+ id SERIAL PRIMARY KEY,+ warranty_id INTEGER NOT NULL REFERENCES warranties(id) ON DELETE CASCADE,+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ note_text TEXT NOT NULL,+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP+);+CREATE INDEX IF NOT EXISTS idx_warranty_note_entries_warranty ON warranty_note_entries(warranty_id);+CREATE INDEX IF NOT EXISTS idx_warranty_note_entries_user ON warranty_note_entries(user_id);diff --git a/backend/warranties_routes.py b/backend/warranties_routes.pyindex 1784d5a..09a2396 100644--- a/backend/warranties_routes.py+++ b/backend/warranties_routes.py@@ -2876,6 +2876,167 @@ def get_claims(warranty_id):if conn:release_db_connection(conn)++def _warranty_viewable_by(cur, warranty_id, user_id, is_admin):+ """Return the warranty's (id, user_id) row if the caller may view it.++ Admins and owners always may. Other users may only when global view+ is enabled and not restricted to admins, matching get_warranty_debug+ and get_claims. Returns None both when the warranty does not exist+ and when the caller may not view it, so callers answer 404 in either+ case without revealing which one it is.+ """+ cur.execute("SELECT id, user_id FROM warranties WHERE id = %s", (warranty_id,))+ row = cur.fetchone()+ if not row:+ return None+ if is_admin or row[1] == user_id:+ return row+ cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")+ settings = {r[0]: r[1] for r 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'+ if global_view_enabled and not admin_only:+ return row+ return None+++def _note_entry_dict(row):+ return {+ 'id': row[0],+ 'warranty_id': row[1],+ 'user_id': row[2],+ 'username': row[3],+ 'text': row[4],+ 'created_at': row[5].isoformat() if row[5] else None,+ }+++@warranties_bp.route('/warranties/<int:warranty_id>/notes', methods=['GET'])+@token_required+def get_warranty_note_entries(warranty_id):+ """List the team note entries on a warranty, oldest first.++ Viewable by anyone who may view the warranty: the owner, an admin,+ or any authenticated user when global view allows it.+ """+ conn = None+ cur = None+ try:+ user_id = request.user['id']+ is_admin = request.user.get('is_admin', False)+ conn = get_db_connection()+ cur = conn.cursor()+ if not _warranty_viewable_by(cur, warranty_id, user_id, is_admin):+ return jsonify({'error': 'Warranty not found'}), 404+ cur.execute("""+ SELECT e.id, e.warranty_id, e.user_id, u.username, e.note_text, e.created_at+ FROM warranty_note_entries e+ JOIN users u ON e.user_id = u.id+ WHERE e.warranty_id = %s+ ORDER BY e.created_at ASC, e.id ASC+ """, (warranty_id,))+ return jsonify([_note_entry_dict(row) for row in cur.fetchall()]), 200+ except Exception as e:+ logger.error(f"Error getting note entries: {e}")+ return jsonify({'error': 'Internal server error'}), 500+ finally:+ if cur:+ cur.close()+ if conn:+ release_db_connection(conn)+++@warranties_bp.route('/warranties/<int:warranty_id>/notes', methods=['POST'])+@token_required+def create_warranty_note_entry(warranty_id):+ """Add a team note entry to a warranty.++ Allowed for anyone who may view the warranty. The entry is attributed+ to the caller with the current time; the warranty's own notes field+ is untouched.+ """+ conn = None+ cur = None+ try:+ user_id = request.user['id']+ is_admin = request.user.get('is_admin', False)+ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400+ text = data.get('text')+ if not isinstance(text, str) or not text.strip():+ return jsonify({'error': 'Note text is required'}), 400+ text = text.strip()+ if len(text) > 5000:+ return jsonify({'error': 'Note text must be 5000 characters or fewer'}), 400+ conn = get_db_connection()+ cur = conn.cursor()+ if not _warranty_viewable_by(cur, warranty_id, user_id, is_admin):+ return jsonify({'error': 'Warranty not found'}), 404+ cur.execute("""+ INSERT INTO warranty_note_entries (warranty_id, user_id, note_text)+ VALUES (%s, %s, %s)+ RETURNING id, created_at+ """, (warranty_id, user_id, text))+ entry_id, created_at = cur.fetchone()+ conn.commit()+ return jsonify({+ 'id': entry_id,+ 'warranty_id': warranty_id,+ 'user_id': user_id,+ 'username': request.user.get('username'),+ 'text': text,+ 'created_at': created_at.isoformat() if created_at else None,+ }), 201+ except Exception as e:+ logger.error(f"Error creating note entry: {e}")+ return jsonify({'error': 'Internal server error'}), 500+ finally:+ if cur:+ cur.close()+ if conn:+ release_db_connection(conn)+++@warranties_bp.route('/warranties/<int:warranty_id>/notes/<int:entry_id>', methods=['DELETE'])+@token_required+def delete_warranty_note_entry(warranty_id, entry_id):+ """Delete a team note entry.++ Allowed for the entry's author, the warranty owner, or an admin.+ """+ conn = None+ cur = None+ try:+ user_id = request.user['id']+ is_admin = request.user.get('is_admin', False)+ conn = get_db_connection()+ cur = conn.cursor()+ warranty = _warranty_viewable_by(cur, warranty_id, user_id, is_admin)+ if not warranty:+ return jsonify({'error': 'Warranty not found'}), 404+ cur.execute("""+ SELECT id, user_id FROM warranty_note_entries+ WHERE id = %s AND warranty_id = %s+ """, (entry_id, warranty_id))+ entry = cur.fetchone()+ if not entry:+ return jsonify({'error': 'Note entry not found'}), 404+ if not (is_admin or entry[1] == user_id or warranty[1] == user_id):+ return jsonify({'error': 'Only the entry author, the warranty owner, or an admin may delete this note'}), 403+ cur.execute("DELETE FROM warranty_note_entries WHERE id = %s", (entry_id,))+ conn.commit()+ return jsonify({'success': True}), 200+ except Exception as e:+ logger.error(f"Error deleting note entry: {e}")+ return jsonify({'error': 'Internal server error'}), 500+ finally:+ if cur:+ cur.close()+ if conn:+ release_db_connection(conn)+@warranties_bp.route('/warranties/<int:warranty_id>/claims/<int:claim_id>', methods=['PUT'])@token_requireddef update_claim(warranty_id, claim_id):diff --git a/frontend/js/components/notes.js b/frontend/js/components/notes.jsindex 8b89098..d131d38 100644--- a/frontend/js/components/notes.js+++ b/frontend/js/components/notes.js@@ -10,6 +10,11 @@ const DEFAULT_MODAL_HTML = `<div class="modal-body"><div id="notesModalContent" style="white-space: pre-line;"></div><textarea id="notesModalTextarea" style="display:none;width:100%;min-height:100px;"></textarea>+ <div id="notesThread" style="margin-top: 12px;"></div>+ <div id="notesAddBox" style="margin-top: 12px;">+ <textarea id="notesAddTextarea" placeholder="Add a note for the team..." style="width:100%;min-height:60px;"></textarea>+ <button class="btn btn-primary" id="addNoteEntryBtn" style="margin-top: 6px;">Add Note</button>+ </div></div><div class="modal-footer" id="notesModalFooter"><button class="btn btn-secondary" id="editNotesBtn">${(window.i18next && window.i18next.t('actions.edit_notes') || 'Edit Notes')}</button>@@ -68,6 +73,9 @@ function refreshDomRefs() {modal: document.getElementById('notesModal'),content: document.getElementById('notesModalContent'),textarea: document.getElementById('notesModalTextarea'),+ thread: document.getElementById('notesThread'),+ addTextarea: document.getElementById('notesAddTextarea'),+ addBtn: document.getElementById('addNoteEntryBtn'),editBtn: document.getElementById('editNotesBtn'),saveBtn: document.getElementById('saveNotesBtn'),cancelBtn: document.getElementById('cancelEditNotesBtn'),@@ -83,6 +91,7 @@ function bindEvents() {dom.saveBtn?.addEventListener('click', saveNotes);dom.cancelBtn?.addEventListener('click', exitEditMode);dom.editWarrantyBtn?.addEventListener('click', handleEditWarranty);+ dom.addBtn?.addEventListener('click', addNoteEntry);dom.modal._notesBound = true;}@@ -272,6 +281,112 @@ async function saveNotes() {}}+// 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+// are set with textContent, never interpolated into HTML.+function canDeleteNoteEntry(entry) {+ const currentUser = callIfExists(window.auth?.getCurrentUser) || null;+ if (!currentUser) return false;+ if (Boolean(currentUser.is_admin)) return true;+ if (Number(entry.user_id) === Number(currentUser.id)) return true;+ if (state.warranty && Number(state.warranty.user_id) === Number(currentUser.id)) return true;+ return false;+}++function renderNoteEntries(entries) {+ if (!dom || !dom.thread) return;+ dom.thread.innerHTML = '';+ if (!entries || entries.length === 0) return;+ for (const entry of entries) {+ const row = document.createElement('div');+ row.className = 'note-entry';+ row.style.cssText = 'border-top: 1px solid var(--border-color, #ddd); padding: 8px 0;';+ const meta = document.createElement('div');+ meta.className = 'note-entry-meta';+ meta.style.cssText = 'font-size: 0.85em; color: var(--text-muted, #666);';+ const when = entry.created_at ? new Date(entry.created_at).toLocaleString() : '';+ meta.textContent = entry.username + ' - ' + when;+ const text = document.createElement('div');+ text.className = 'note-entry-text';+ text.style.whiteSpace = 'pre-line';+ text.textContent = entry.text;+ row.appendChild(meta);+ row.appendChild(text);+ if (canDeleteNoteEntry(entry)) {+ const del = document.createElement('button');+ del.type = 'button';+ del.className = 'btn btn-sm btn-danger note-entry-delete';+ del.textContent = 'Delete';+ del.addEventListener('click', () => deleteNoteEntry(entry.id));+ row.appendChild(del);+ }+ dom.thread.appendChild(row);+ }+}++async function loadNoteEntries() {+ if (!dom || !state.warrantyId) return;+ const token = getToken();+ if (!token) return;+ try {+ const response = await fetch(`/api/warranties/${state.warrantyId}/notes`, {+ headers: { Authorization: `Bearer ${token}` },+ });+ if (!response.ok) return;+ renderNoteEntries(await response.json());+ } catch (error) {+ console.error('[notes] Failed to load note entries', error);+ }+}++async function addNoteEntry() {+ if (!dom || !state.warrantyId) return;+ const text = dom.addTextarea.value.trim();+ if (!text) return;+ const token = getToken();+ if (!token) {+ showToast((window.i18next && window.i18next.t('messages.authentication_required') || 'Authentication required'), 'error');+ return;+ }+ try {+ const response = await fetch(`/api/warranties/${state.warrantyId}/notes`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },+ body: JSON.stringify({ text }),+ });+ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.error || `Failed to add note (Status: ${response.status})`);+ }+ dom.addTextarea.value = '';+ await loadNoteEntries();+ } catch (error) {+ console.error('[notes] Failed to add note entry', error);+ showToast(error.message || 'Failed to add note', 'error');+ }+}++async function deleteNoteEntry(entryId) {+ if (!dom || !state.warrantyId) return;+ const token = getToken();+ if (!token) return;+ try {+ const response = await fetch(`/api/warranties/${state.warrantyId}/notes/${entryId}`, {+ method: 'DELETE',+ headers: { Authorization: `Bearer ${token}` },+ });+ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.error || `Failed to delete note (Status: ${response.status})`);+ }+ await loadNoteEntries();+ } catch (error) {+ console.error('[notes] Failed to delete note entry', error);+ showToast(error.message || 'Failed to delete note', 'error');+ }+}+export function showNotesModal(notes, warrantyOrId = null) {const refs = ensureModal();// If warrantyOrId is already a warranty object, use it directly@@ -308,7 +423,9 @@ export function showNotesModal(notes, warrantyOrId = null) {refs.editBtn.title = 'View only - not your warranty';}}+ if (refs.addTextarea) refs.addTextarea.value = '';exitEditMode();+ loadNoteEntries();refs.modal.classList.add('active');}diff --git a/frontend/script.js b/frontend/script.jsindex 1ba6ca2..a21e6aa 100644--- a/frontend/script.js+++ b/frontend/script.js@@ -6316,6 +6316,11 @@ if (!document.getElementById('notesModal')) {<div class="modal-body"><div id="notesModalContent" style="white-space: pre-line;"></div><textarea id="notesModalTextarea" style="display:none;width:100%;min-height:100px;"></textarea>+ <div id="notesThread" style="margin-top: 12px;"></div>+ <div id="notesAddBox" style="margin-top: 12px;">+ <textarea id="notesAddTextarea" placeholder="Add a note for the team..." style="width:100%;min-height:60px;"></textarea>+ <button class="btn btn-primary" id="addNoteEntryBtn" style="margin-top: 6px;">Add Note</button>+ </div></div><div class="modal-footer" id="notesModalFooter"><button class="btn btn-secondary" id="editNotesBtn">Edit Notes</button>diff --git a/tests/test_status_edit_and_notes.py b/tests/test_status_edit_and_notes.pyindex 57da8ee..60283a1 100644--- a/tests/test_status_edit_and_notes.py+++ b/tests/test_status_edit_and_notes.py@@ -66,3 +66,33 @@ def test_warranty_list_stops_after_logout_before_second_fetch():archived_fetch = controller.index("listWarranties({ scope, archived: true })")between = controller[first_fetch:archived_fetch]assert "if (!authService.isAuthenticated())" in between+++def test_notes_modal_renders_team_entry_thread():+ """Team note entries (next release): the notes modal must carry the+ thread container and add box, fetch entries when it opens, and+ render each entry's author and time with textContent, never+ interpolated into HTML."""+ notes = (REPO / "frontend" / "js" / "components" / "notes.js").read_text()+ assert 'id="notesThread"' in notes+ assert 'id="notesAddTextarea"' in notes+ assert 'id="addNoteEntryBtn"' in notes+ assert "fetch(`/api/warranties/${state.warrantyId}/notes`" in notes+ assert "new Date(entry.created_at).toLocaleString()" in notes+ assert "meta.textContent = entry.username + ' - ' + when" in notes+ assert "text.textContent = entry.text" in notes+ assert "refs.editBtn.disabled = !canEdit" in notes+ # The live modal markup is the legacy one script.js injects at load+ # time; the module reuses it when it exists. It must carry the same+ # thread and add-box elements, or the modal opens without them.+ legacy = (REPO / "frontend" / "script.js").read_text()+ assert 'id="notesThread"' in legacy+ assert 'id="notesAddTextarea"' in legacy+ assert 'id="addNoteEntryBtn"' in legacy+++def test_note_entry_endpoints_exist():+ routes = (REPO / "backend" / "warranties_routes.py").read_text()+ 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 routesdiff --git a/tests/test_warranty_note_entries.py b/tests/test_warranty_note_entries.pynew file mode 100644index 0000000..e17e3e3--- /dev/null+++ b/tests/test_warranty_note_entries.py@@ -0,0 +1,238 @@+"""Team note entries on warranties (next release).++Any authenticated user who may view a warranty may add a note entry to+it, and each entry carries its author and timestamp. The warranty's own+notes field is untouched. Deleting is for the entry author, the+warranty owner, or an admin. With global view off, or restricted to+admins, non-owners may neither view nor add.+"""+from types import SimpleNamespace++import pytest+++def _global_view(db_connection):+ """Set the two global view settings, restoring prior values after."""+ conn = db_connection+ with conn.cursor() as cur:+ cur.execute(+ "SELECT key, value FROM site_settings "+ "WHERE key IN ('global_view_enabled', 'global_view_admin_only')"+ )+ saved = dict(cur.fetchall())++ def _set(enabled, admin_only):+ with conn.cursor() as cur:+ for key, value in (+ ("global_view_enabled", enabled),+ ("global_view_admin_only", admin_only),+ ):+ cur.execute(+ "INSERT INTO site_settings (key, value) VALUES (%s, %s) "+ "ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value",+ (key, value),+ )+ conn.commit()++ yield _set++ with conn.cursor() as cur:+ for key in ("global_view_enabled", "global_view_admin_only"):+ if key in saved:+ cur.execute(+ "UPDATE site_settings SET value = %s WHERE key = %s",+ (saved[key], key),+ )+ else:+ cur.execute("DELETE FROM site_settings WHERE key = %s", (key,))+ conn.commit()++[email protected](scope="module")+def scenario(client, user_factory, warranty_factory):+ owner = user_factory()+ viewer = user_factory()+ other_viewer = user_factory()+ admin = user_factory()+ r = warranty_factory(owner["headers"], product_name="TeamNotesWidget")+ assert r.status_code == 201, r.get_data(as_text=True)+ return SimpleNamespace(+ owner=owner,+ viewer=viewer,+ other_viewer=other_viewer,+ admin=admin,+ wid=r.get_json()["id"],+ )+++def _promoted_admin(scenario, db_connection):+ """Promote the scenario admin via the DB. The admin_user fixture is+ only an admin when registered first in the session, so tests that+ need an admin depend on this instead."""+ with db_connection.cursor() as cur:+ cur.execute("SELECT id FROM users WHERE username = %s", (scenario.admin["username"],))+ admin_id = cur.fetchone()[0]+ cur.execute("UPDATE users SET is_admin = TRUE WHERE id = %s", (admin_id,))+ db_connection.commit()+++def _add(client, scenario, headers, text):+ return client.post(+ f"/api/warranties/{scenario.wid}/notes",+ json={"text": text},+ headers=headers,+ )+++def _list(client, scenario, headers):+ return client.get(f"/api/warranties/{scenario.wid}/notes", headers=headers)+++def test_owner_adds_entry(client, scenario, _global_view):+ _global_view("false", "false")+ r = _add(client, scenario, scenario.owner["headers"], "owner entry")+ assert r.status_code == 201, r.get_data(as_text=True)+ body = r.get_json()+ assert body["username"] == scenario.owner["username"]+ assert body["text"] == "owner entry"+ assert body["created_at"]+ assert body["warranty_id"] == scenario.wid+++def test_viewer_adds_entry_global_view_on(client, scenario, _global_view):+ _global_view("true", "false")+ r = _add(client, scenario, scenario.viewer["headers"], "viewer entry")+ assert r.status_code == 201, r.get_data(as_text=True)+ assert r.get_json()["username"] == scenario.viewer["username"]+++def test_admin_adds_entry(client, scenario, _global_view, _promoted_admin):+ _global_view("false", "false")+ r = _add(client, scenario, scenario.admin["headers"], "admin entry")+ assert r.status_code == 201, r.get_data(as_text=True)+++def test_viewer_add_forbidden_global_view_off(client, scenario, _global_view):+ _global_view("false", "false")+ r = _add(client, scenario, scenario.viewer["headers"], "should not land")+ assert r.status_code == 404+++def test_viewer_add_forbidden_admin_only(client, scenario, _global_view):+ _global_view("true", "true")+ r = _add(client, scenario, scenario.viewer["headers"], "should not land")+ assert r.status_code == 404+++def test_list_entries_oldest_first(client, scenario, _global_view):+ _global_view("true", "false")+ first = _add(client, scenario, scenario.owner["headers"], "list first").get_json()+ second = _add(client, scenario, scenario.viewer["headers"], "list second").get_json()+ r = _list(client, scenario, scenario.owner["headers"])+ assert r.status_code == 200, r.get_data(as_text=True)+ entries = r.get_json()+ ids = [e["id"] for e in entries]+ assert ids.index(first["id"]) < ids.index(second["id"])+ by_id = {e["id"]: e for e in entries}+ assert by_id[first["id"]]["username"] == scenario.owner["username"]+ assert by_id[second["id"]]["text"] == "list second"+ assert by_id[second["id"]]["created_at"]+++def test_list_forbidden_global_view_off(client, scenario, _global_view):+ _global_view("false", "false")+ r = _list(client, scenario, scenario.viewer["headers"])+ assert r.status_code == 404+++def test_validation_empty_and_missing_text(client, scenario):+ r = _add(client, scenario, scenario.owner["headers"], " ")+ assert r.status_code == 400+ r = client.post(+ f"/api/warranties/{scenario.wid}/notes",+ json={},+ headers=scenario.owner["headers"],+ )+ assert r.status_code == 400+++def test_validation_too_long(client, scenario):+ r = _add(client, scenario, scenario.owner["headers"], "x" * 5001)+ assert r.status_code == 400+ r = _add(client, scenario, scenario.owner["headers"], "x" * 5000)+ assert r.status_code == 201, r.get_data(as_text=True)+++def test_delete_by_author(client, scenario, _global_view):+ _global_view("true", "false")+ entry = _add(client, scenario, scenario.viewer["headers"], "author deletes").get_json()+ r = client.delete(+ f"/api/warranties/{scenario.wid}/notes/{entry['id']}",+ headers=scenario.viewer["headers"],+ )+ assert r.status_code == 200, r.get_data(as_text=True)+ ids = [e["id"] for e in _list(client, scenario, scenario.owner["headers"]).get_json()]+ assert entry["id"] not in ids+++def test_delete_by_owner(client, scenario, _global_view):+ _global_view("true", "false")+ entry = _add(client, scenario, scenario.viewer["headers"], "owner deletes").get_json()+ r = client.delete(+ f"/api/warranties/{scenario.wid}/notes/{entry['id']}",+ headers=scenario.owner["headers"],+ )+ assert r.status_code == 200, r.get_data(as_text=True)+++def test_delete_by_admin(client, scenario, _global_view, _promoted_admin):+ _global_view("true", "false")+ entry = _add(client, scenario, scenario.viewer["headers"], "admin deletes").get_json()+ r = client.delete(+ f"/api/warranties/{scenario.wid}/notes/{entry['id']}",+ headers=scenario.admin["headers"],+ )+ assert r.status_code == 200, r.get_data(as_text=True)+++def test_delete_forbidden_other_viewer(client, scenario, _global_view):+ _global_view("true", "false")+ entry = _add(client, scenario, scenario.viewer["headers"], "not yours").get_json()+ r = client.delete(+ f"/api/warranties/{scenario.wid}/notes/{entry['id']}",+ headers=scenario.other_viewer["headers"],+ )+ assert r.status_code == 403, r.get_data(as_text=True)+ ids = [e["id"] for e in _list(client, scenario, scenario.owner["headers"]).get_json()]+ assert entry["id"] in ids+++def test_delete_missing_entry(client, scenario):+ r = client.delete(+ f"/api/warranties/{scenario.wid}/notes/999999",+ headers=scenario.owner["headers"],+ )+ assert r.status_code == 404+++def test_missing_warranty(client, scenario):+ r = client.get("/api/warranties/999999/notes", headers=scenario.owner["headers"])+ assert r.status_code == 404+ r = client.post(+ "/api/warranties/999999/notes",+ json={"text": "nope"},+ headers=scenario.owner["headers"],+ )+ assert r.status_code == 404+ r = client.delete(+ "/api/warranties/999999/notes/1",+ headers=scenario.owner["headers"],+ )+ assert r.status_code == 404+++def test_unauthenticated(client, scenario):+ r = client.get(f"/api/warranties/{scenario.wid}/notes")+ assert r.status_code == 401