Files
Medasset_ai/backend/tests/test_notifications_and_dashboard.py
T

149 lines
6.6 KiB
Python

from datetime import timedelta
import pytest
from app.core.time_utils import effective_today
from app.models import Asset, Complaint, Department, Notification
from app.seed.seed import seed_database
from app.services.alerts import run_alert_check
@pytest.fixture(scope="module", autouse=True)
def seeded_phase6_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("phase6_test_uploads")
seed_database(db, upload_dir=upload_dir)
return upload_dir
def _auth_headers(client, email: str) -> dict[str, str]:
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
assert res.status_code == 200, res.text
return {"Authorization": f"Bearer {res.json()['access_token']}"}
def test_alert_check_dedupe_and_seed_notifications(db):
# seed_database already ran run_alert_check -> notifications exist in DB
initial_count = db.query(Notification).count()
assert initial_count > 0
# Running run_alert_check again immediately creates 0 duplicates
res2 = run_alert_check(db)
db.commit()
assert res2["created"] == 0
assert db.query(Notification).count() == initial_count
def test_demo_clock_alert_run_and_admin_only_permission(client, db):
admin_headers = _auth_headers(client, "admin@xyz.demo")
bio_headers = _auth_headers(client, "bio@xyz.demo")
dept_headers = _auth_headers(client, "dept@xyz.demo")
mgmt_headers = _auth_headers(client, "mgmt@xyz.demo")
coord_headers = _auth_headers(client, "coord@xyz.demo")
# Non-admins get 403 on POST /api/alerts/run
for h in (bio_headers, dept_headers, mgmt_headers, coord_headers):
assert client.post("/api/alerts/run", headers=h).status_code == 403
base_today = effective_today(db)
future_date = base_today + timedelta(days=20)
try:
set_res = client.post(
"/api/settings/demo-date",
headers=admin_headers,
json={"demo_as_of_date": str(future_date)},
)
assert set_res.status_code == 200
# First run at +20 days creates new notifications for newly-entered windows
run1 = client.post("/api/alerts/run", headers=admin_headers)
assert run1.status_code == 200, run1.text
data1 = run1.json()
assert data1["evaluated_today"] == str(future_date)
assert data1["created"] > 0
# Second run at same +20 days creates 0 (dedupe)
run2 = client.post("/api/alerts/run", headers=admin_headers)
assert run2.status_code == 200
assert run2.json()["created"] == 0
finally:
client.post(
"/api/settings/demo-date",
headers=admin_headers,
json={"demo_as_of_date": None},
)
def test_per_user_read_state_and_department_scoping(client, db):
admin_headers = _auth_headers(client, "admin@xyz.demo")
bio_headers = _auth_headers(client, "bio@xyz.demo")
dept_headers = _auth_headers(client, "dept@xyz.demo")
admin_list_before = client.get("/api/notifications?limit=100", headers=admin_headers).json()
bio_list_before = client.get("/api/notifications?limit=100", headers=bio_headers).json()
assert admin_list_before["unread_count"] > 0
assert bio_list_before["unread_count"] > 0
# Pick a calibration_due notification visible to both admin and bio
cal_items = [n for n in admin_list_before["items"] if n["type"] == "calibration_due"]
assert len(cal_items) > 0
target_id = cal_items[0]["id"]
assert cal_items[0]["link_url"] == "/calibration"
# Admin marks single notification as read -> bio still sees it unread
mark_res = client.post(f"/api/notifications/{target_id}/read", headers=admin_headers)
assert mark_res.status_code == 200
assert mark_res.json()["is_read"] is True
admin_after_one = client.get("/api/notifications?limit=100", headers=admin_headers).json()
bio_after_one = client.get("/api/notifications?limit=100", headers=bio_headers).json()
assert admin_after_one["unread_count"] == admin_list_before["unread_count"] - 1
assert bio_after_one["unread_count"] == bio_list_before["unread_count"]
# Admin marks all calibration_due notifications read -> unread_calibration_count becomes 0 for admin, unchanged for bio
mark_cal = client.post("/api/notifications/read-all?type=calibration_due", headers=admin_headers)
assert mark_cal.status_code == 200
admin_after_cal = client.get("/api/notifications?limit=100", headers=admin_headers).json()
bio_after_cal = client.get("/api/notifications?limit=100", headers=bio_headers).json()
assert admin_after_cal["unread_calibration_count"] == 0
assert bio_after_cal["unread_calibration_count"] > 0
# department_user only sees critical_complaint alerts for their own department (ICU)
icu = db.query(Department).filter(Department.code == "ICU").first()
dept_notifs = client.get("/api/notifications?limit=100", headers=dept_headers).json()
for n in dept_notifs["items"]:
assert n["entity_type"] == "complaint"
assert n["link_url"] == f"/complaints/{n['entity_id']}"
comp = db.query(Complaint).filter(Complaint.id == n["entity_id"]).first()
assert comp.asset.department_id == icu.id
def test_dashboard_summary_role_scoping_and_charts(client, db):
mgmt_headers = _auth_headers(client, "mgmt@xyz.demo")
dept_headers = _auth_headers(client, "dept@xyz.demo")
icu = db.query(Department).filter(Department.code == "ICU").first()
icu_asset_count = db.query(Asset).filter(Asset.department_id == icu.id).count()
total_asset_count = db.query(Asset).count()
mgmt_res = client.get("/api/dashboard/summary", headers=mgmt_headers)
assert mgmt_res.status_code == 200, mgmt_res.text
mgmt = mgmt_res.json()
assert mgmt["department_scope"] is None
assert mgmt["kpis"]["total_assets"] == total_asset_count
assert len(mgmt["monthly_downtime_trend"]) == 6
assert len(mgmt["pm_planned_vs_completed"]) == 6
assert len(mgmt["complaints_by_status"]) == 3
assert len(mgmt["complaints_by_department"]) >= 2
assert len(mgmt["recent_complaints"]) <= 8
dept_res = client.get("/api/dashboard/summary", headers=dept_headers)
assert dept_res.status_code == 200, dept_res.text
dept = dept_res.json()
assert dept["department_scope"] == icu.name
assert dept["kpis"]["total_assets"] == icu_asset_count
assert dept["kpis"]["total_assets"] < mgmt["kpis"]["total_assets"]
assert len(dept["monthly_downtime_trend"]) == 6
assert len(dept["pm_planned_vs_completed"]) == 6
assert [d["department"] for d in dept["complaints_by_department"]] == [icu.name]
assert all(rc["department_name"] == icu.name for rc in dept["recent_complaints"])