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 core CRUD, access-control, frontend, and locale test suites

sassanixb2019ac27af8
diff --git a/backend/warranties_routes.py b/backend/warranties_routes.py
index 4cd683b..1784d5a 100644
--- a/backend/warranties_routes.py
+++ b/backend/warranties_routes.py
@@ -2617,7 +2617,8 @@ def get_locales():
'pt': 'Português',
'ko': '한국어',
'tr': 'Türkçe',
- 'pl': 'Polski'
+ 'pl': 'Polski',
+ 'he': 'עברית'
}
locales = []
diff --git a/tests/README.md b/tests/README.md
index 6fd3303..927af45 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -44,10 +44,27 @@ CI runs the same suite on every pull request
other users get the global-view-shared types (photo, invoice,
manual) but never "other documents" or claim documents; missing
files return a JSON 404.
-- `test_config_deprecation.py` — the softened #221 behavior: the
- built-in DB credential defaults still work in 1.0.5, production
- init does not refuse to start, and the startup deprecation warning
- names exactly the unset variables (all four gone in 1.0.6).
+- `test_db_credentials_required.py` — required `DB_USER`/`DB_PASSWORD`
+ (or `DATABASE_URL` with credentials) with zero built-in defaults (#221),
+ optional paired `DB_ADMIN_USER`/`DB_ADMIN_PASSWORD`, and end-to-end
+ `apply_migrations.py`, `fix_permissions.py`, and `Docker/entrypoint.sh`
+ checks.
+- `test_warranty_lifecycle_and_global_view.py` — archive/unarchive,
+ 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_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.
+- `test_tags_crud.py` — tag create/update/delete validation, per-user
+ uniqueness, non-owner 403 enforcement, and warranty-tag routes.
+- `test_user_account_and_preferences.py` — user preferences validation
+ and persistence, language preference, registration gate, self account
+ deletion, admin user deletion protections, and audit trail.
+- `test_frontend_and_locales.py` — `node --check` syntax checks across
+ all frontend JS files and inline HTML scripts, pure JS date/currency
+ helper tests, locale JSON completeness vs `SUPPORTED_LANGUAGES`, and
+ frontend version-string lockstep.
- `test_notifications.py` — notification selection: the expiring-soon
query includes in-window warranties and excludes expired, lifetime,
archived and voided ones, and honors each user's own
diff --git a/tests/test_claims_crud_and_access.py b/tests/test_claims_crud_and_access.py
new file mode 100644
index 0000000..f7b43e8
--- /dev/null
+++ b/tests/test_claims_crud_and_access.py
@@ -0,0 +1,273 @@
+"""Warranty claims & claim documents CRUD, file cleanup, and access control.
+
+Covers:
+- Full claim CRUD lifecycle (POST, GET, PUT, DELETE) and claim_status_summary
+ transitions on GET /api/warranties (NO_CLAIMS -> OPEN -> FINISHED -> NO_CLAIMS)
+- Claim document upload, listing, individual deletion (with disk cleanup),
+ and cascade file cleanup when deleting a claim or parent warranty
+- Cross-user authorization: non-owners cannot create/update/delete claims or
+ documents, cannot read /claims/<id>/documents even under global view, and
+ receive empty documents[] when reading claims under global view
+"""
+import io
+import os
+
+import pytest
+
+
+def _promote(db_connection, username):
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "UPDATE users SET is_admin = TRUE WHERE username = %s",
+ (username,),
+ )
+
+
+def _global_view_setting(db_connection):
+ 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()
+
+
+def _warranty_summary(client, headers, wid):
+ rows = client.get("/api/warranties", headers=headers).get_json()
+ return next(w for w in rows if w["id"] == wid)["claim_status_summary"]
+
+
+def test_claim_crud_and_warranty_status_summary_transitions(
+ client, user_factory, warranty_factory):
+ user = user_factory()
+ h = user["headers"]
+ wid = warranty_factory(h, product_name="Claimable Laptop").get_json()["id"]
+
+ assert _warranty_summary(client, h, wid) == "NO_CLAIMS"
+
+ # Missing claim_date rejected.
+ r_bad = client.post(
+ f"/api/warranties/{wid}/claims", headers=h, json={"status": "Submitted"}
+ )
+ assert r_bad.status_code == 400
+
+ # Create open claim -> summary becomes OPEN.
+ r_create = client.post(
+ f"/api/warranties/{wid}/claims",
+ headers=h,
+ json={
+ "claim_date": "2025-06-10",
+ "status": "Submitted",
+ "claim_number": " CLM-100 ",
+ "description": "Screen flicker",
+ },
+ )
+ assert r_create.status_code == 201, r_create.get_data(as_text=True)
+ claim = r_create.get_json()
+ cid = claim["id"]
+ assert claim["claim_number"] == "CLM-100"
+ assert claim["documents"] == []
+ assert _warranty_summary(client, h, wid) == "OPEN"
+
+ # GET returns the created claim.
+ r_list = client.get(f"/api/warranties/{wid}/claims", headers=h)
+ assert r_list.status_code == 200
+ assert [c["id"] for c in r_list.get_json()] == [cid]
+
+ # Update claim to Resolved -> summary becomes FINISHED.
+ r_upd = client.put(
+ f"/api/warranties/{wid}/claims/{cid}",
+ headers=h,
+ json={
+ "status": "Resolved",
+ "resolution": "Replaced panel",
+ "resolution_date": "2025-06-20",
+ },
+ )
+ assert r_upd.status_code == 200, r_upd.get_data(as_text=True)
+ updated = r_upd.get_json()
+ assert updated["status"] == "Resolved"
+ assert updated["resolution"] == "Replaced panel"
+ assert updated["resolution_date"] == "2025-06-20"
+ assert _warranty_summary(client, h, wid) == "FINISHED"
+
+ # Delete claim -> summary returns to NO_CLAIMS.
+ r_del = client.delete(f"/api/warranties/{wid}/claims/{cid}", headers=h)
+ assert r_del.status_code == 200, r_del.get_data(as_text=True)
+ assert client.get(f"/api/warranties/{wid}/claims", headers=h).get_json() == []
+ assert _warranty_summary(client, h, wid) == "NO_CLAIMS"
+
+
+def test_claim_documents_lifecycle_and_disk_cleanup(
+ app, client, user_factory, warranty_factory):
+ user = user_factory()
+ h = user["headers"]
+ wid = warranty_factory(h, product_name="Claim Docs Phone").get_json()["id"]
+ cid = client.post(
+ f"/api/warranties/{wid}/claims",
+ headers=h,
+ json={"claim_date": "2025-07-01", "status": "Submitted"},
+ ).get_json()["id"]
+
+ # Missing file and paperless_document_id rejected.
+ r_empty = client.post(
+ f"/api/warranties/{wid}/claims/{cid}/documents",
+ headers=h,
+ data={},
+ content_type="multipart/form-data",
+ )
+ assert r_empty.status_code == 400
+
+ # Upload two local PDF documents to the claim.
+ def _upload(name):
+ r = client.post(
+ f"/api/warranties/{wid}/claims/{cid}/documents",
+ headers=h,
+ data={"file": (io.BytesIO(b"%PDF-1.4\ntest"), name)},
+ content_type="multipart/form-data",
+ )
+ assert r.status_code == 201, r.get_data(as_text=True)
+ return r.get_json()
+
+ doc1 = _upload("rma_label.pdf")
+ doc2 = _upload("repair_report.pdf")
+ upload_dir = app.config["UPLOAD_FOLDER"]
+ path1 = os.path.join(upload_dir, os.path.basename(doc1["file_path"]))
+ path2 = os.path.join(upload_dir, os.path.basename(doc2["file_path"]))
+ assert os.path.isfile(path1)
+ assert os.path.isfile(path2)
+
+ # Listing documents returns both in order.
+ r_docs = client.get(f"/api/warranties/{wid}/claims/{cid}/documents", headers=h)
+ assert r_docs.status_code == 200
+ assert [d["id"] for d in r_docs.get_json()] == [doc1["id"], doc2["id"]]
+
+ # Deleting doc1 removes its DB row and unlinks its file from disk.
+ r_del_doc = client.delete(
+ f"/api/warranties/{wid}/claims/{cid}/documents/{doc1['id']}", headers=h
+ )
+ assert r_del_doc.status_code == 200
+ assert not os.path.exists(path1)
+ assert os.path.isfile(path2)
+ assert [
+ d["id"]
+ for d in client.get(
+ f"/api/warranties/{wid}/claims/{cid}/documents", headers=h
+ ).get_json()
+ ] == [doc2["id"]]
+
+ # Deleting the claim cascades and unlinks doc2 from disk too.
+ r_del_claim = client.delete(f"/api/warranties/{wid}/claims/{cid}", headers=h)
+ assert r_del_claim.status_code == 200
+ assert not os.path.exists(path2)
+
+
+def test_claim_and_document_cross_user_privacy_and_access(
+ client, admin_user, user_factory, warranty_factory,
+ db_connection, _global_view_setting):
+ _promote(db_connection, admin_user["username"])
+ owner = user_factory()
+ stranger = user_factory()
+ wid = warranty_factory(owner["headers"], product_name="Private Claim Gear").get_json()["id"]
+
+ cid = client.post(
+ f"/api/warranties/{wid}/claims",
+ headers=owner["headers"],
+ json={"claim_date": "2025-08-01", "status": "In Progress"},
+ ).get_json()["id"]
+ doc = client.post(
+ f"/api/warranties/{wid}/claims/{cid}/documents",
+ headers=owner["headers"],
+ data={"file": (io.BytesIO(b"%PDF-1.4\nsecret"), "private_receipt.pdf")},
+ content_type="multipart/form-data",
+ ).get_json()
+
+ # Stranger cannot create, update, or delete owner's claims or documents.
+ assert client.post(
+ f"/api/warranties/{wid}/claims",
+ headers=stranger["headers"],
+ json={"claim_date": "2025-08-02"},
+ ).status_code == 404
+ assert client.put(
+ f"/api/warranties/{wid}/claims/{cid}",
+ headers=stranger["headers"],
+ json={"status": "Cancelled"},
+ ).status_code == 404
+ assert client.delete(
+ f"/api/warranties/{wid}/claims/{cid}",
+ headers=stranger["headers"],
+ ).status_code == 404
+ assert client.post(
+ f"/api/warranties/{wid}/claims/{cid}/documents",
+ headers=stranger["headers"],
+ data={"file": (io.BytesIO(b"%PDF-1.4\nx"), "x.pdf")},
+ content_type="multipart/form-data",
+ ).status_code == 404
+ assert client.delete(
+ f"/api/warranties/{wid}/claims/{cid}/documents/{doc['id']}",
+ headers=stranger["headers"],
+ ).status_code == 404
+
+ # Under global view enabled: stranger can read claim summary, but
+ # embedded documents are stripped and /documents endpoint returns 404.
+ _global_view_setting("true", "false")
+ r_claims_stranger = client.get(
+ f"/api/warranties/{wid}/claims", headers=stranger["headers"]
+ )
+ assert r_claims_stranger.status_code == 200
+ stranger_claims = r_claims_stranger.get_json()
+ assert len(stranger_claims) == 1
+ assert stranger_claims[0]["documents"] == []
+
+ assert client.get(
+ f"/api/warranties/{wid}/claims/{cid}/documents",
+ headers=stranger["headers"],
+ ).status_code == 404
+
+ # Owner and admin DO see claim documents.
+ r_docs_admin = client.get(
+ f"/api/warranties/{wid}/claims/{cid}/documents",
+ headers=admin_user["headers"],
+ )
+ assert r_docs_admin.status_code == 200
+ assert [d["id"] for d in r_docs_admin.get_json()] == [doc["id"]]
+
+ r_claims_admin = client.get(
+ f"/api/warranties/{wid}/claims", headers=admin_user["headers"]
+ )
+ assert r_claims_admin.status_code == 200
+ assert [d["id"] for d in r_claims_admin.get_json()[0]["documents"]] == [doc["id"]]
+
+ # Under global view disabled: stranger gets 404 on GET /claims too.
+ _global_view_setting("false", "false")
+ assert client.get(
+ f"/api/warranties/{wid}/claims", headers=stranger["headers"]
+ ).status_code == 404
diff --git a/tests/test_frontend_and_locales.py b/tests/test_frontend_and_locales.py
new file mode 100644
index 0000000..8a97eee
--- /dev/null
+++ b/tests/test_frontend_and_locales.py
@@ -0,0 +1,207 @@
+"""Frontend JS syntax, pure utility behavior, locale integrity, and version pins.
+
+Fast static and Node.js checks that protect day-to-day frontend and i18n work:
+- Every JS file under frontend/ (excluding vendored libs) and every inline
+ <script> block in frontend/*.html must parse cleanly with `node --check`.
+- Pure frontend date and currency helpers behave consistently (formatting,
+ duration calculation across year/month boundaries, currency positioning and
+ thousands grouping).
+- All locale translation.json files are valid UTF-8 JSON, contain every key
+ present in English (locales/en/translation.json), and stay in sync with
+ backend/localization.py SUPPORTED_LANGUAGES.
+- Hardcoded frontend version strings in about.html and version-checker.js stay
+ in lockstep.
+"""
+import json
+import os
+import re
+import shutil
+import subprocess
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from backend.localization import SUPPORTED_LANGUAGES
+
+REPO = Path(__file__).resolve().parent.parent
+FRONTEND = REPO / "frontend"
+LOCALES = REPO / "locales"
+
+
+def _flatten_keys(obj, prefix=""):
+ keys = set()
+ for key, value in obj.items():
+ full = f"{prefix}.{key}" if prefix else key
+ if isinstance(value, dict):
+ keys |= _flatten_keys(value, full)
+ else:
+ keys.add(full)
+ return keys
+
+
+def test_all_frontend_js_files_parse_cleanly():
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node is not installed")
+
+ js_files = sorted(
+ p for p in FRONTEND.rglob("*.js")
+ if "vendor" not in p.parts
+ )
+ assert js_files, "no frontend JS files found"
+
+ failures = []
+ for js_file in js_files:
+ r = subprocess.run(
+ [node, "--check", str(js_file)],
+ capture_output=True, text=True,
+ )
+ if r.returncode != 0:
+ failures.append(f"{js_file.relative_to(REPO)}: {r.stderr.strip()}")
+ assert not failures, "\n".join(failures)
+
+
+def test_all_inline_html_scripts_parse_cleanly():
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node is not installed")
+
+ html_files = sorted(FRONTEND.glob("*.html"))
+ assert html_files, "no frontend HTML files found"
+
+ failures = []
+ for html_file in html_files:
+ src = html_file.read_text(encoding="utf-8")
+ for idx, match in enumerate(
+ re.finditer(r"<script\b([^>]*)>(.*?)</script>", src, re.S | re.I)
+ ):
+ attrs, body = match.group(1), match.group(2)
+ if re.search(r"\bsrc\s*=", attrs, re.I) or not body.strip():
+ continue
+ is_module = bool(re.search(r'type\s*=\s*["\']module["\']', attrs, re.I))
+ suffix = ".mjs" if is_module else ".js"
+ with tempfile.NamedTemporaryFile(
+ "w", suffix=suffix, delete=False, encoding="utf-8"
+ ) as tf:
+ tf.write(body)
+ tmp_path = tf.name
+ try:
+ r = subprocess.run(
+ [node, "--check", tmp_path],
+ capture_output=True, text=True,
+ )
+ if r.returncode != 0:
+ failures.append(
+ f"{html_file.relative_to(REPO)} inline script #{idx}: {r.stderr.strip()}"
+ )
+ finally:
+ os.unlink(tmp_path)
+
+ assert not failures, "\n".join(failures)
+
+
+def test_frontend_dates_and_currency_helpers_behavior():
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node is not installed")
+
+ dates_url = (FRONTEND / "js" / "lib" / "dates.js").as_uri()
+ currency_url = (FRONTEND / "js" / "lib" / "currency.js").as_uri()
+
+ script = f"""
+ globalThis.window = {{ location: {{ origin: 'http://localhost', pathname: '/' }} }};
+ globalThis.document = {{ addEventListener: () => {{}} }};
+ globalThis.localStorage = {{ getItem: () => null, setItem: () => {{}}, removeItem: () => {{}} }};
+ const dates = await import({json.dumps(dates_url)});
+ const currency = await import({json.dumps(currency_url)});
+
+ function eq(actual, expected, label) {{
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) {{
+ throw new Error(`${{label}}: expected ${{JSON.stringify(expected)}}, got ${{JSON.stringify(actual)}}`);
+ }}
+ }}
+
+ // dates.js
+ eq(dates.formatDate('2025-03-15T00:00:00Z'), 'Mar 15, 2025', 'formatDate ISO');
+ eq(dates.formatDate(''), 'Unknown', 'formatDate empty');
+ eq(dates.formatDate('not-a-date'), 'Unknown', 'formatDate invalid');
+ eq(dates.formatDateYYYYMMDD(new Date(Date.UTC(2025, 0, 5))), '2025-01-05', 'formatDateYYYYMMDD');
+ eq(dates.formatDateYYYYMMDD(null), 'N/A', 'formatDateYYYYMMDD null');
+ eq(
+ dates.calculateDurationFromDates('2024-01-15', '2026-03-20'),
+ {{ years: 2, months: 2, days: 5 }},
+ 'calculateDurationFromDates simple'
+ );
+ eq(
+ dates.calculateDurationFromDates('2024-03-31', '2025-02-28'),
+ {{ years: 0, months: 10, days: 28 }},
+ 'calculateDurationFromDates borrow across year'
+ );
+
+ // currency.js
+ const expectedLeft = (1234.5).toLocaleString(undefined, {{
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }});
+ const expectedRight = (182591).toLocaleString(undefined, {{
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }});
+ eq(
+ currency.formatCurrencyHTML(1234.5, '$', 'left'),
+ `<span class="currency-symbol">$</span><span>${{expectedLeft}}</span>`,
+ 'formatCurrencyHTML left'
+ );
+ eq(
+ currency.formatCurrencyHTML(182591, 'дин', 'right'),
+ `<span>${{expectedRight}}</span><span class="currency-symbol currency-right">дин</span>`,
+ 'formatCurrencyHTML right'
+ );
+ eq(currency.getCurrencySymbolByCode('USD'), '$', 'USD symbol');
+ eq(currency.getCurrencySymbolByCode('EUR'), '€', 'EUR symbol');
+ eq(currency.getCurrencySymbolByCode('RSD'), 'дин', 'RSD symbol');
+ """
+ r = subprocess.run(
+ [node, "--input-type=module", "-e", script],
+ capture_output=True, text=True,
+ )
+ assert r.returncode == 0, r.stderr
+
+
+def test_locales_are_valid_json_complete_and_match_supported_languages():
+ en_path = LOCALES / "en" / "translation.json"
+ en_data = json.loads(en_path.read_text(encoding="utf-8"))
+ en_keys = _flatten_keys(en_data)
+ assert en_keys, "English translation file has no keys"
+
+ locale_dirs = sorted(
+ p.name for p in LOCALES.iterdir()
+ if p.is_dir() and (p / "translation.json").is_file()
+ )
+ assert set(locale_dirs) == set(SUPPORTED_LANGUAGES), (
+ f"locales/ dirs {sorted(locale_dirs)} != SUPPORTED_LANGUAGES {sorted(SUPPORTED_LANGUAGES)}"
+ )
+
+ missing_by_locale = {}
+ for lang in locale_dirs:
+ data = json.loads((LOCALES / lang / "translation.json").read_text(encoding="utf-8"))
+ keys = _flatten_keys(data)
+ missing = sorted(en_keys - keys)
+ if missing:
+ missing_by_locale[lang] = missing[:10]
+ assert not missing_by_locale, f"Missing translation keys: {missing_by_locale}"
+
+
+def test_frontend_version_strings_stay_in_sync():
+ about = (FRONTEND / "about.html").read_text(encoding="utf-8")
+ checker = (FRONTEND / "version-checker.js").read_text(encoding="utf-8")
+
+ m_badge = re.search(r'id="versionDisplay"[^>]*>Version v([0-9]+\.[0-9]+\.[0-9]+)<', about)
+ m_about_js = re.search(r"const currentVersion = '([0-9]+\.[0-9]+\.[0-9]+)';", about)
+ m_checker = re.search(r"const currentVersion = '([0-9]+\.[0-9]+\.[0-9]+)';", checker)
+
+ assert m_badge, "could not find About page version badge"
+ assert m_about_js, "could not find About page currentVersion constant"
+ assert m_checker, "could not find version-checker.js currentVersion constant"
+ assert m_badge.group(1) == m_about_js.group(1) == m_checker.group(1)
diff --git a/tests/test_tags_crud.py b/tests/test_tags_crud.py
new file mode 100644
index 0000000..93c0d74
--- /dev/null
+++ b/tests/test_tags_crud.py
@@ -0,0 +1,190 @@
+"""Direct tag CRUD and warranty-tag association routes.
+
+Complements tests/test_tag_ownership.py (which pins warranty create/update
+against foreign tag IDs) by covering:
+- POST /api/tags validation, per-user uniqueness, and cross-user isolation
+- GET /api/tags per-user scoping
+- PUT /api/tags/<id> rename/recolor, validation, conflict, and 403 for non-owners
+- DELETE /api/tags/<id> 403 for non-owners and cleanup of warranty_tags links
+- GET & POST /api/warranties/<id>/tags ownership, replacement, and admin read
+"""
+
+
+def _promote(db_connection, username):
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "UPDATE users SET is_admin = TRUE WHERE username = %s",
+ (username,),
+ )
+
+
+def test_tag_create_validation_and_per_user_uniqueness(client, user_factory):
+ alice = user_factory()
+ bob = user_factory()
+
+ # Empty name, missing name, invalid hex color rejected.
+ assert client.post("/api/tags", headers=alice["headers"], json={}).status_code == 400
+ assert client.post(
+ "/api/tags", headers=alice["headers"], json={"name": " "}
+ ).status_code == 400
+ assert client.post(
+ "/api/tags",
+ headers=alice["headers"],
+ json={"name": "Home", "color": "not-a-hex"},
+ ).status_code == 400
+
+ # Valid creation succeeds.
+ r1 = client.post(
+ "/api/tags",
+ headers=alice["headers"],
+ json={"name": "Electronics", "color": "#112233"},
+ )
+ assert r1.status_code == 201, r1.get_data(as_text=True)
+ tag_id = r1.get_json()["id"]
+
+ # Duplicate for the same user returns 409.
+ r_dup = client.post(
+ "/api/tags",
+ headers=alice["headers"],
+ json={"name": "Electronics", "color": "#445566"},
+ )
+ assert r_dup.status_code == 409
+
+ # Another user CAN create a tag with the same name; GET /api/tags is scoped.
+ r_bob = client.post(
+ "/api/tags",
+ headers=bob["headers"],
+ json={"name": "Electronics", "color": "#778899"},
+ )
+ assert r_bob.status_code == 201
+ alice_tags = client.get("/api/tags", headers=alice["headers"]).get_json()
+ bob_tags = client.get("/api/tags", headers=bob["headers"]).get_json()
+ assert [t["id"] for t in alice_tags] == [tag_id]
+ assert [t["id"] for t in bob_tags] == [r_bob.get_json()["id"]]
+
+
+def test_tag_update_validation_conflicts_and_ownership(client, user_factory):
+ alice = user_factory()
+ bob = user_factory()
+
+ t1 = client.post(
+ "/api/tags", headers=alice["headers"], json={"name": "Kitchen", "color": "#AA0000"}
+ ).get_json()["id"]
+ t2 = client.post(
+ "/api/tags", headers=alice["headers"], json={"name": "Garage", "color": "#00AA00"}
+ ).get_json()["id"]
+
+ # Validation checks on PUT.
+ assert client.put(
+ f"/api/tags/{t1}", headers=alice["headers"], json={"name": "", "color": "#0000AA"}
+ ).status_code == 400
+ assert client.put(
+ f"/api/tags/{t1}", headers=alice["headers"], json={"name": "x" * 51, "color": "#0000AA"}
+ ).status_code == 400
+ assert client.put(
+ f"/api/tags/{t1}", headers=alice["headers"], json={"name": "Kitchen", "color": "blue"}
+ ).status_code == 400
+
+ # Conflict with another tag of the same user returns 409.
+ assert client.put(
+ f"/api/tags/{t1}", headers=alice["headers"], json={"name": "Garage", "color": "#0000AA"}
+ ).status_code == 409
+
+ # Nonexistent tag returns 404.
+ assert client.put(
+ "/api/tags/99999999", headers=alice["headers"], json={"name": "Ghost", "color": "#0000AA"}
+ ).status_code == 404
+
+ # Another user gets 403 trying to update Alice's tag.
+ assert client.put(
+ f"/api/tags/{t1}", headers=bob["headers"], json={"name": "Stolen", "color": "#0000AA"}
+ ).status_code == 403
+
+ # Owner update succeeds.
+ r_ok = client.put(
+ f"/api/tags/{t1}",
+ headers=alice["headers"],
+ json={"name": "Appliances", "color": "#123456"},
+ )
+ assert r_ok.status_code == 200, r_ok.get_data(as_text=True)
+ assert r_ok.get_json() == {"id": t1, "name": "Appliances", "color": "#123456"}
+ assert t2 != t1
+
+
+def test_tag_delete_ownership_and_warranty_tag_routes(
+ client, admin_user, user_factory, warranty_factory, db_connection):
+ _promote(db_connection, admin_user["username"])
+ alice = user_factory()
+ bob = user_factory()
+
+ t1 = client.post(
+ "/api/tags", headers=alice["headers"], json={"name": "Office", "color": "#336699"}
+ ).get_json()["id"]
+ t2 = client.post(
+ "/api/tags", headers=alice["headers"], json={"name": "Travel", "color": "#996633"}
+ ).get_json()["id"]
+ bob_tag = client.post(
+ "/api/tags", headers=bob["headers"], json={"name": "BobTag", "color": "#111111"}
+ ).get_json()["id"]
+
+ wid = warranty_factory(alice["headers"], product_name="Tagged Monitor").get_json()["id"]
+
+ # Bad payloads on POST /warranties/<id>/tags return 400.
+ assert client.post(
+ f"/api/warranties/{wid}/tags", headers=alice["headers"], json={}
+ ).status_code == 400
+ assert client.post(
+ f"/api/warranties/{wid}/tags", headers=alice["headers"], json={"tag_ids": "not-a-list"}
+ ).status_code == 400
+
+ # Linking another user's tag via POST /warranties/<id>/tags is rejected (404).
+ assert client.post(
+ f"/api/warranties/{wid}/tags",
+ headers=alice["headers"],
+ json={"tag_ids": [bob_tag]},
+ ).status_code == 404
+
+ # Non-owner cannot read or modify Alice's warranty tags.
+ assert client.get(
+ f"/api/warranties/{wid}/tags", headers=bob["headers"]
+ ).status_code == 404
+ assert client.post(
+ f"/api/warranties/{wid}/tags",
+ headers=bob["headers"],
+ json={"tag_ids": [bob_tag]},
+ ).status_code == 404
+
+ # Owner links t1 and t2, then reads them back.
+ r_link = client.post(
+ f"/api/warranties/{wid}/tags",
+ headers=alice["headers"],
+ json={"tag_ids": [t1, t2]},
+ )
+ assert r_link.status_code == 200, r_link.get_data(as_text=True)
+
+ r_get = client.get(f"/api/warranties/{wid}/tags", headers=alice["headers"])
+ assert r_get.status_code == 200
+ assert [t["id"] for t in r_get.get_json()] == [t1, t2]
+
+ # Admin can inspect tags on Alice's warranty.
+ r_admin = client.get(f"/api/warranties/{wid}/tags", headers=admin_user["headers"])
+ assert r_admin.status_code == 200
+ assert [t["id"] for t in r_admin.get_json()] == [t1, t2]
+
+ # Bob gets 403 trying to delete Alice's tag; nonexistent tag returns 404.
+ assert client.delete(f"/api/tags/{t1}", headers=bob["headers"]).status_code == 403
+ assert client.delete("/api/tags/99999999", headers=alice["headers"]).status_code == 404
+
+ # Deleting t1 cleans up its warranty_tags association too.
+ r_del = client.delete(f"/api/tags/{t1}", headers=alice["headers"])
+ assert r_del.status_code == 200
+ remaining = client.get(f"/api/warranties/{wid}/tags", headers=alice["headers"]).get_json()
+ assert [t["id"] for t in remaining] == [t2]
+
+ # Empty tag_ids clears remaining tags cleanly.
+ assert client.post(
+ f"/api/warranties/{wid}/tags",
+ headers=alice["headers"],
+ json={"tag_ids": []},
+ ).status_code == 200
+ assert client.get(f"/api/warranties/{wid}/tags", headers=alice["headers"]).get_json() == []
diff --git a/tests/test_user_account_and_preferences.py b/tests/test_user_account_and_preferences.py
new file mode 100644
index 0000000..47e96d0
--- /dev/null
+++ b/tests/test_user_account_and_preferences.py
@@ -0,0 +1,284 @@
+"""User preferences, language settings, registration gate, account deletion,
+admin user deletion, and audit trail endpoints.
+
+Covers previously untested account & admin lifecycle flows:
+- GET & PUT /api/auth/preferences (defaults, persistence, saved_filters, 400 checks)
+- PUT /api/auth/user/language-preference
+- GET /api/auth/registration-status and POST /api/auth/register enforcement
+- DELETE /api/auth/account (cleanup + immediate token revocation; owner protection)
+- DELETE /api/admin/users/<id> (self/owner protection, cleanup, audit log)
+- GET /api/admin/audit-trail (admin-only enforcement + recorded actions)
+"""
+import pytest
+
+
+def _promote(db_connection, username):
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "UPDATE users SET is_admin = TRUE WHERE username = %s",
+ (username,),
+ )
+
+
+def _user_id(client, headers):
+ me = client.get("/api/auth/user", headers=headers).get_json()
+ return me["user"]["id"] if "user" in me else me["id"]
+
+
+def test_user_preferences_get_put_and_validation(client, user_factory):
+ user = user_factory()
+ h = user["headers"]
+
+ # Default preferences for a new user.
+ r_get = client.get("/api/auth/preferences", headers=h)
+ assert r_get.status_code == 200, r_get.get_data(as_text=True)
+ defaults = r_get.get_json()
+ assert defaults["default_view"] == "grid"
+ assert defaults["theme"] == "light"
+ assert defaults["expiring_soon_days"] == 30
+ assert defaults["currency_position"] == "left"
+ assert defaults["preferred_language"] == "en"
+
+ # Invalid values are rejected with 400.
+ bad_payloads = [
+ {"default_view": "kanban"},
+ {"theme": "neon"},
+ {"expiring_soon_days": 0},
+ {"expiring_soon_days": 366},
+ {"expiring_soon_days": "not-a-number"},
+ {"currency_symbol": "123456789"},
+ {"currency_position": "center"},
+ {"date_format": "BAD_FMT"},
+ {"notification_channel": "carrier_pigeon"},
+ {"paperless_view_in_app": "yes"},
+ {"preferred_language": "xx_INVALID"},
+ ]
+ for payload in bad_payloads:
+ r_bad = client.put("/api/auth/preferences", headers=h, json=payload)
+ assert r_bad.status_code == 400, f"expected 400 for {payload}, got {r_bad.status_code}"
+
+ # First PUT (creates row if absent) + second PUT (updates row + saved_filters).
+ r_put1 = client.put(
+ "/api/auth/preferences",
+ headers=h,
+ json={
+ "default_view": "table",
+ "theme": "dark",
+ "expiring_soon_days": 14,
+ "currency_symbol": "€",
+ "currency_position": "right",
+ "date_format": "DMY",
+ "notification_channel": "both",
+ "timezone": "Europe/Berlin",
+ "paperless_view_in_app": True,
+ "preferred_language": "de",
+ },
+ )
+ assert r_put1.status_code == 200, r_put1.get_data(as_text=True)
+ saved = r_put1.get_json()
+ assert saved["default_view"] == "table"
+ assert saved["theme"] == "dark"
+ assert saved["expiring_soon_days"] == 14
+ assert saved["currency_symbol"] == "€"
+ assert saved["currency_position"] == "right"
+ assert saved["date_format"] == "DMY"
+ assert saved["notification_channel"] == "both"
+ assert saved["timezone"] == "Europe/Berlin"
+ assert saved["paperless_view_in_app"] is True
+ assert saved["preferred_language"] == "de"
+
+ r_put2 = client.put(
+ "/api/auth/preferences",
+ headers=h,
+ json={"saved_filters": {"status": "active", "sort": "expiration"}},
+ )
+ assert r_put2.status_code == 200, r_put2.get_data(as_text=True)
+ assert r_put2.get_json()["saved_filters"] == {
+ "status": "active",
+ "sort": "expiration",
+ }
+
+ # GET reflects persisted updates.
+ r_after = client.get("/api/auth/preferences", headers=h)
+ assert r_after.status_code == 200
+ after = r_after.get_json()
+ assert after["theme"] == "dark"
+ assert after["preferred_language"] == "de"
+ assert after["saved_filters"] == {"status": "active", "sort": "expiration"}
+
+
+def test_language_preference_endpoint(client, user_factory):
+ user = user_factory()
+ h = user["headers"]
+
+ assert client.put(
+ "/api/auth/user/language-preference", headers=h, json={}
+ ).status_code == 400
+ assert client.put(
+ "/api/auth/user/language-preference",
+ headers=h,
+ json={"preferred_language": "klingon"},
+ ).status_code == 400
+
+ r_ok = client.put(
+ "/api/auth/user/language-preference",
+ headers=h,
+ json={"preferred_language": "he"},
+ )
+ assert r_ok.status_code == 200, r_ok.get_data(as_text=True)
+
+ prefs = client.get("/api/auth/preferences", headers=h).get_json()
+ assert prefs["preferred_language"] == "he"
+
+
+def test_registration_status_and_disabled_registration(client, db_connection):
+ with db_connection.cursor() as cur:
+ cur.execute(
+ "SELECT value FROM site_settings WHERE key = 'registration_enabled'"
+ )
+ row = cur.fetchone()
+ prev = row[0] if row else None
+
+ try:
+ # Disable registration.
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "INSERT INTO site_settings (key, value) VALUES ('registration_enabled', 'false') "
+ "ON CONFLICT (key) DO UPDATE SET value = 'false'"
+ )
+
+ r_status = client.get("/api/auth/registration-status")
+ assert r_status.status_code == 200
+ assert r_status.get_json()["enabled"] is False
+
+ r_reg = client.post(
+ "/api/auth/register",
+ json={
+ "username": "blocked_reg_user",
+ "email": "[email protected]",
+ "password": "TestPass123!",
+ },
+ )
+ assert r_reg.status_code == 403
+
+ # Re-enable registration.
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "UPDATE site_settings SET value = 'true' WHERE key = 'registration_enabled'"
+ )
+ assert client.get("/api/auth/registration-status").get_json()["enabled"] is True
+ finally:
+ with db_connection, db_connection.cursor() as cur:
+ if prev is None:
+ cur.execute(
+ "DELETE FROM site_settings WHERE key = 'registration_enabled'"
+ )
+ else:
+ cur.execute(
+ "UPDATE site_settings SET value = %s WHERE key = 'registration_enabled'",
+ (prev,),
+ )
+
+
+def test_self_account_deletion_cleans_data_and_blocks_owner(
+ client, admin_user, user_factory, warranty_factory, db_connection):
+ # Ensure at least one owner exists (first registered user / admin_user).
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute("SELECT id, username FROM users WHERE is_owner = TRUE LIMIT 1")
+ owner_row = cur.fetchone()
+ if not owner_row:
+ cur.execute(
+ "UPDATE users SET is_owner = TRUE, is_admin = TRUE WHERE username = %s",
+ (admin_user["username"],),
+ )
+
+ # Regular user creates warranty, tag, and preference, then deletes account.
+ victim = user_factory()
+ h = victim["headers"]
+ uid = _user_id(client, h)
+ wid = warranty_factory(h, product_name="Doomed Item").get_json()["id"]
+ tid = client.post(
+ "/api/tags", headers=h, json={"name": "DoomedTag", "color": "#222222"}
+ ).get_json()["id"]
+ assert client.put(
+ "/api/auth/preferences", headers=h, json={"theme": "dark"}
+ ).status_code == 200
+
+ r_del = client.delete("/api/auth/account", headers=h)
+ assert r_del.status_code == 200, r_del.get_data(as_text=True)
+
+ # Old token is immediately rejected, and DB rows are gone.
+ assert client.get("/api/warranties", headers=h).status_code == 401
+ with db_connection.cursor() as cur:
+ cur.execute("SELECT 1 FROM users WHERE id = %s", (uid,))
+ assert cur.fetchone() is None
+ cur.execute("SELECT 1 FROM warranties WHERE id = %s", (wid,))
+ assert cur.fetchone() is None
+ cur.execute("SELECT 1 FROM tags WHERE id = %s", (tid,))
+ assert cur.fetchone() is None
+
+ # Owner cannot delete their own account.
+ if owner_row is None or owner_row[1] == admin_user["username"]:
+ r_owner_del = client.delete("/api/auth/account", headers=admin_user["headers"])
+ assert r_owner_del.status_code == 403
+
+
+def test_admin_delete_user_protections_and_audit_trail(
+ client, admin_user, user_factory, warranty_factory, db_connection):
+ _promote(db_connection, admin_user["username"])
+ admin_id = _user_id(client, admin_user["headers"])
+
+ # Make sure an owner exists in the DB (mark admin_user if none).
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute("SELECT id FROM users WHERE is_owner = TRUE LIMIT 1")
+ row = cur.fetchone()
+ if row:
+ owner_id = row[0]
+ else:
+ cur.execute("UPDATE users SET is_owner = TRUE WHERE id = %s", (admin_id,))
+ owner_id = admin_id
+
+ regular = user_factory()
+ reg_id = _user_id(client, regular["headers"])
+ wid = warranty_factory(regular["headers"], product_name="Admin Deleted Item").get_json()["id"]
+
+ # Non-admin blocked from audit trail and user deletion.
+ assert client.get("/api/admin/audit-trail", headers=regular["headers"]).status_code == 403
+ assert client.delete(
+ f"/api/admin/users/{admin_id}", headers=regular["headers"]
+ ).status_code == 403
+
+ # Admin cannot delete self (403), cannot delete nonexistent user (404),
+ # and cannot delete owner (403) even from a second admin account.
+ assert client.delete(
+ f"/api/admin/users/{admin_id}", headers=admin_user["headers"]
+ ).status_code == 403
+ assert client.delete(
+ "/api/admin/users/99999999", headers=admin_user["headers"]
+ ).status_code == 404
+
+ second_admin = user_factory()
+ _promote(db_connection, second_admin["username"])
+ assert client.delete(
+ f"/api/admin/users/{owner_id}", headers=second_admin["headers"]
+ ).status_code == 403
+
+ # Deleting a regular user succeeds, cleans up their data, and logs to audit trail.
+ r_del = client.delete(
+ f"/api/admin/users/{reg_id}", headers=admin_user["headers"]
+ )
+ assert r_del.status_code == 200, r_del.get_data(as_text=True)
+
+ with db_connection.cursor() as cur:
+ cur.execute("SELECT 1 FROM users WHERE id = %s", (reg_id,))
+ assert cur.fetchone() is None
+ cur.execute("SELECT 1 FROM warranties WHERE id = %s", (wid,))
+ assert cur.fetchone() is None
+
+ r_audit = client.get("/api/admin/audit-trail?limit=20", headers=admin_user["headers"])
+ assert r_audit.status_code == 200, r_audit.get_data(as_text=True)
+ entries = r_audit.get_json()
+ assert any(
+ e["action"] == "DELETE_USER" and e["target_id"] == str(reg_id)
+ for e in entries
+ )
diff --git a/tests/test_warranty_lifecycle_and_global_view.py b/tests/test_warranty_lifecycle_and_global_view.py
new file mode 100644
index 0000000..40ac79a
--- /dev/null
+++ b/tests/test_warranty_lifecycle_and_global_view.py
@@ -0,0 +1,288 @@
+"""Warranty lifecycle, cross-user ownership, global view, and metadata routes.
+
+Covers core application endpoints that previously had no regression tests:
+- PATCH /api/warranties/<id>/archive and GET /api/warranties/archived
+- PATCH /api/warranties/<id>/void (void and restore)
+- Cross-user authorization on PUT, DELETE, archive, and void (non-owner vs admin)
+- GET /api/warranties/global, /api/warranties/global/archived, and
+ GET /api/settings/global-view-status across all three visibility modes
+- GET /api/admin/warranties (admin-only enforcement and active-only filtering)
+- GET /api/timezones and GET /api/locales
+"""
+import pytest
+
+from backend.localization import SUPPORTED_LANGUAGES
+
+
+def _promote(db_connection, username):
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "UPDATE users SET is_admin = TRUE WHERE username = %s",
+ (username,),
+ )
+
+
+def _global_view_setting(db_connection):
+ """Set global_view_enabled / global_view_admin_only and restore afterward."""
+ 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()
+
+
+def test_archive_and_unarchive_warranty_lifecycle(
+ client, user_factory, warranty_factory):
+ user = user_factory()
+ h = user["headers"]
+ wid = warranty_factory(h, product_name="Archive Desk").get_json()["id"]
+
+ # Initially active, not archived.
+ active_ids = [w["id"] for w in client.get("/api/warranties", headers=h).get_json()]
+ archived_ids = [w["id"] for w in client.get("/api/warranties/archived", headers=h).get_json()]
+ assert wid in active_ids
+ assert wid not in archived_ids
+
+ # Missing boolean rejected with 400.
+ r_bad = client.patch(f"/api/warranties/{wid}/archive", headers=h, json={})
+ assert r_bad.status_code == 400
+
+ # Archive moves warranty out of active list and into archived list.
+ r_arch = client.patch(
+ f"/api/warranties/{wid}/archive", headers=h, json={"archived": True}
+ )
+ assert r_arch.status_code == 200, r_arch.get_data(as_text=True)
+ assert r_arch.get_json()["archived"] is True
+
+ active_ids = [w["id"] for w in client.get("/api/warranties", headers=h).get_json()]
+ archived_ids = [w["id"] for w in client.get("/api/warranties/archived", headers=h).get_json()]
+ assert wid not in active_ids
+ assert wid in archived_ids
+
+ # Unarchive restores warranty to active list.
+ r_unarch = client.patch(
+ f"/api/warranties/{wid}/archive", headers=h, json={"archived": False}
+ )
+ assert r_unarch.status_code == 200, r_unarch.get_data(as_text=True)
+ assert r_unarch.get_json()["archived"] is False
+
+ active_ids = [w["id"] for w in client.get("/api/warranties", headers=h).get_json()]
+ archived_ids = [w["id"] for w in client.get("/api/warranties/archived", headers=h).get_json()]
+ assert wid in active_ids
+ assert wid not in archived_ids
+
+
+def test_void_and_unvoid_warranty_lifecycle(
+ client, user_factory, warranty_factory):
+ user = user_factory()
+ h = user["headers"]
+ wid = warranty_factory(h, product_name="Voidable Mixer").get_json()["id"]
+
+ r_bad = client.patch(f"/api/warranties/{wid}/void", headers=h, json={})
+ assert r_bad.status_code == 400
+
+ r_void = client.patch(
+ f"/api/warranties/{wid}/void", headers=h, json={"voided": True}
+ )
+ assert r_void.status_code == 200, r_void.get_data(as_text=True)
+ assert r_void.get_json()["voided"] is True
+
+ w_row = next(
+ w for w in client.get("/api/warranties", headers=h).get_json()
+ if w["id"] == wid
+ )
+ assert w_row["voided_at"] is not None
+
+ r_restore = client.patch(
+ f"/api/warranties/{wid}/void", headers=h, json={"voided": False}
+ )
+ assert r_restore.status_code == 200, r_restore.get_data(as_text=True)
+ assert r_restore.get_json()["voided"] is False
+
+ w_row = next(
+ w for w in client.get("/api/warranties", headers=h).get_json()
+ if w["id"] == wid
+ )
+ assert w_row["voided_at"] is None
+
+
+def test_cross_user_warranty_mutation_blocked_for_stranger_allowed_for_admin(
+ client, admin_user, user_factory, warranty_factory, db_connection):
+ _promote(db_connection, admin_user["username"])
+ owner = user_factory()
+ stranger = user_factory()
+ wid = warranty_factory(owner["headers"], product_name="Owner Watch").get_json()["id"]
+
+ # Another regular user cannot archive, void, edit, or delete owner's warranty.
+ assert client.patch(
+ f"/api/warranties/{wid}/archive",
+ headers=stranger["headers"],
+ json={"archived": True},
+ ).status_code == 404
+ assert client.patch(
+ f"/api/warranties/{wid}/void",
+ headers=stranger["headers"],
+ json={"voided": True},
+ ).status_code == 404
+ assert client.put(
+ f"/api/warranties/{wid}",
+ headers=stranger["headers"],
+ data={"product_name": "Hijacked"},
+ ).status_code in (403, 404)
+ assert client.delete(
+ f"/api/warranties/{wid}",
+ headers=stranger["headers"],
+ ).status_code == 404
+
+ # An admin can archive, void, restore, edit, and delete any user's warranty.
+ assert client.patch(
+ f"/api/warranties/{wid}/archive",
+ headers=admin_user["headers"],
+ json={"archived": True},
+ ).status_code == 200
+ assert client.patch(
+ f"/api/warranties/{wid}/archive",
+ headers=admin_user["headers"],
+ json={"archived": False},
+ ).status_code == 200
+ assert client.patch(
+ f"/api/warranties/{wid}/void",
+ headers=admin_user["headers"],
+ json={"voided": True},
+ ).status_code == 200
+ assert client.delete(
+ f"/api/warranties/{wid}",
+ headers=admin_user["headers"],
+ ).status_code == 200
+
+
+def test_global_warranties_and_status_respect_visibility_settings(
+ client, admin_user, user_factory, warranty_factory,
+ db_connection, _global_view_setting):
+ _promote(db_connection, admin_user["username"])
+ alice = user_factory()
+ bob = user_factory()
+
+ w_active = warranty_factory(
+ alice["headers"], product_name="Global Active Item"
+ ).get_json()["id"]
+ w_archived = warranty_factory(
+ bob["headers"], product_name="Global Archived Item"
+ ).get_json()["id"]
+ assert client.patch(
+ f"/api/warranties/{w_archived}/archive",
+ headers=bob["headers"],
+ json={"archived": True},
+ ).status_code == 200
+
+ # 1. Global view enabled for everyone.
+ _global_view_setting("true", "false")
+ r_status = client.get("/api/settings/global-view-status", headers=alice["headers"])
+ assert r_status.status_code == 200
+ assert r_status.get_json()["enabled"] is True
+
+ r_global = client.get("/api/warranties/global", headers=bob["headers"])
+ assert r_global.status_code == 200, r_global.get_data(as_text=True)
+ global_ids = {w["id"] for w in r_global.get_json()}
+ assert w_active in global_ids
+ assert w_archived not in global_ids
+
+ r_global_arch = client.get("/api/warranties/global/archived", headers=alice["headers"])
+ assert r_global_arch.status_code == 200, r_global_arch.get_data(as_text=True)
+ global_arch_ids = {w["id"] for w in r_global_arch.get_json()}
+ assert w_archived in global_arch_ids
+ assert w_active not in global_arch_ids
+
+ # 2. Global view restricted to admins only.
+ _global_view_setting("true", "true")
+ assert client.get(
+ "/api/settings/global-view-status", headers=alice["headers"]
+ ).get_json()["enabled"] is False
+ assert client.get(
+ "/api/settings/global-view-status", headers=admin_user["headers"]
+ ).get_json()["enabled"] is True
+
+ assert client.get("/api/warranties/global", headers=alice["headers"]).status_code == 403
+ assert client.get("/api/warranties/global/archived", headers=alice["headers"]).status_code == 403
+ assert client.get("/api/warranties/global", headers=admin_user["headers"]).status_code == 200
+ assert client.get("/api/warranties/global/archived", headers=admin_user["headers"]).status_code == 200
+
+ # 3. Global view disabled completely.
+ _global_view_setting("false", "false")
+ assert client.get(
+ "/api/settings/global-view-status", headers=admin_user["headers"]
+ ).get_json()["enabled"] is False
+ assert client.get("/api/warranties/global", headers=admin_user["headers"]).status_code == 403
+ assert client.get("/api/warranties/global/archived", headers=admin_user["headers"]).status_code == 403
+
+
+def test_admin_warranties_endpoint_requires_admin_and_excludes_archived(
+ client, admin_user, user_factory, warranty_factory, db_connection):
+ _promote(db_connection, admin_user["username"])
+ user = user_factory()
+ w_active = warranty_factory(user["headers"], product_name="Admin List Active").get_json()["id"]
+ w_arch = warranty_factory(user["headers"], product_name="Admin List Archived").get_json()["id"]
+ assert client.patch(
+ f"/api/warranties/{w_arch}/archive",
+ headers=user["headers"],
+ json={"archived": True},
+ ).status_code == 200
+
+ assert client.get("/api/admin/warranties", headers=user["headers"]).status_code == 403
+
+ r_admin = client.get("/api/admin/warranties", headers=admin_user["headers"])
+ assert r_admin.status_code == 200, r_admin.get_data(as_text=True)
+ ids = {w["id"] for w in r_admin.get_json()}
+ assert w_active in ids
+ assert w_arch not in ids
+
+
+def test_timezones_and_locales_metadata_endpoints(client, user_factory):
+ user = user_factory()
+
+ # /api/timezones requires auth and returns region-grouped IANA zones.
+ assert client.get("/api/timezones").status_code == 401
+ r_tz = client.get("/api/timezones", headers=user["headers"])
+ assert r_tz.status_code == 200
+ regions = {group["region"]: group["timezones"] for group in r_tz.get_json()}
+ assert "America" in regions and "Europe" in regions
+ assert any(z["value"] == "America/New_York" for z in regions["America"])
+
+ # /api/locales is public and returns every SUPPORTED_LANGUAGES entry
+ # with a human-readable native name (never falling back to raw code).
+ r_loc = client.get("/api/locales")
+ assert r_loc.status_code == 200
+ locales = r_loc.get_json()
+ by_code = {entry["code"]: entry for entry in locales}
+ assert set(by_code.keys()) == set(SUPPORTED_LANGUAGES)
+ for code, entry in by_code.items():
+ assert entry["native_name"] != code, f"missing display name for locale {code}"