initial commit
This commit is contained in:
@@ -0,0 +1,275 @@
|
||||
import csv
|
||||
from datetime import datetime, timezone
|
||||
from io import BytesIO, StringIO
|
||||
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import KOLKATA
|
||||
from app.models import Asset, Category, Complaint, Department, Location, User
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
ALL_REPORT_KEYS = [
|
||||
"monthly-maintenance",
|
||||
"monthly-department",
|
||||
"daily-visit",
|
||||
"breakdown-complaints",
|
||||
"pm-compliance",
|
||||
"calibration-due",
|
||||
"contracts-warranty",
|
||||
"demo-equipment",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_phase7_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("phase7_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_all_eight_reports_accessible_for_management_and_admin(client):
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
for headers in (mgmt_headers, admin_headers):
|
||||
for key in ALL_REPORT_KEYS:
|
||||
res = client.get(f"/api/reports/{key}", headers=headers)
|
||||
assert res.status_code == 200, f"{key} failed: {res.text}"
|
||||
body = res.json()
|
||||
assert body["report_key"] == key
|
||||
assert body["title"]
|
||||
assert isinstance(body["filters_applied"], dict)
|
||||
assert isinstance(body["summary"], dict)
|
||||
assert isinstance(body["columns"], list) and len(body["columns"]) > 0
|
||||
assert isinstance(body["rows"], list)
|
||||
|
||||
missing = client.get("/api/reports/non-existent-report", headers=admin_headers)
|
||||
assert missing.status_code == 404
|
||||
|
||||
|
||||
def test_daily_visit_rbac_and_department_user_scoping(client, db):
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
# daily-visit is forbidden for department_user and coordinator (JSON + export)
|
||||
for headers in (dept_headers, coord_headers):
|
||||
assert client.get("/api/reports/daily-visit", headers=headers).status_code == 403
|
||||
assert client.get("/api/reports/daily-visit/export?format=xlsx", headers=headers).status_code == 403
|
||||
|
||||
# Allowed for biomedical engineer
|
||||
assert client.get("/api/reports/daily-visit", headers=bio_headers).status_code == 200
|
||||
|
||||
# Department user attempting to pass another department_id is still scoped to own department
|
||||
dept_user = db.query(User).filter(User.email == "dept@poona.demo").first()
|
||||
other_dept = db.query(Department).filter(Department.id != dept_user.department_id).first()
|
||||
assert dept_user is not None and dept_user.department_id is not None
|
||||
assert other_dept is not None
|
||||
|
||||
for key in [k for k in ALL_REPORT_KEYS if k != "daily-visit"]:
|
||||
res = client.get(
|
||||
f"/api/reports/{key}?department_id={other_dept.id}",
|
||||
headers=dept_headers,
|
||||
)
|
||||
assert res.status_code == 200, f"{key} failed for dept user: {res.text}"
|
||||
body = res.json()
|
||||
if "department_id" in body["filters_applied"]:
|
||||
assert body["filters_applied"]["department_id"] == dept_user.department_id
|
||||
|
||||
maint = client.get(
|
||||
f"/api/reports/monthly-maintenance?department_id={other_dept.id}",
|
||||
headers=dept_headers,
|
||||
).json()
|
||||
assert len(maint["rows"]) == 1
|
||||
assert maint["rows"][0]["department_id"] == dept_user.department_id
|
||||
|
||||
|
||||
def test_monthly_maintenance_three_complaint_reconciliation(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
admin_user = db.query(User).filter(User.email == "admin@poona.demo").first()
|
||||
category = db.query(Category).first()
|
||||
location = db.query(Location).first()
|
||||
assert admin_user is not None and category is not None and location is not None
|
||||
|
||||
# Create isolated department with 2 non-condemned assets so calculation is deterministic
|
||||
dept = Department(name="Reconciliation Test Unit", code="REC-TEST-01", is_active=True)
|
||||
db.add(dept)
|
||||
db.flush()
|
||||
|
||||
asset1 = Asset(
|
||||
asset_code="REC-AST-001",
|
||||
serial_no="REC-SN-001",
|
||||
name="Reconciliation Monitor 1",
|
||||
category_id=category.id,
|
||||
department_id=dept.id,
|
||||
location_id=location.id,
|
||||
status="in_service",
|
||||
criticality="critical",
|
||||
)
|
||||
asset2 = Asset(
|
||||
asset_code="REC-AST-002",
|
||||
serial_no="REC-SN-002",
|
||||
name="Reconciliation Monitor 2",
|
||||
category_id=category.id,
|
||||
department_id=dept.id,
|
||||
location_id=location.id,
|
||||
status="in_service",
|
||||
criticality="non_critical",
|
||||
)
|
||||
db.add_all([asset1, asset2])
|
||||
db.flush()
|
||||
|
||||
# 3 fixed complaints for March 2027 (31 days * 24h * 60m = 44640 mins/asset -> 89280 total):
|
||||
# 1) Crosses month boundary: Feb 28 22:00 IST -> Mar 01 04:00 IST => 240 mins in March, day Mar 01
|
||||
# 2) Mid-month: Mar 10 10:00 IST -> Mar 10 13:30 IST => 210 mins, day Mar 10
|
||||
# 3) Distinct day: Mar 20 09:00 IST -> Mar 20 10:15 IST => 75 mins, day Mar 20
|
||||
# Expected total downtime = 525 mins, downtime days = 3, uptime = 88755 mins
|
||||
complaints = [
|
||||
Complaint(
|
||||
complaint_no="REC-CMP-001",
|
||||
asset_id=asset1.id,
|
||||
description="Month boundary downtime test",
|
||||
priority="critical",
|
||||
registered_at=KOLKATA.localize(datetime(2027, 2, 28, 22, 0)).astimezone(timezone.utc),
|
||||
restored_at=KOLKATA.localize(datetime(2027, 3, 1, 4, 0)).astimezone(timezone.utc),
|
||||
registered_by_id=admin_user.id,
|
||||
received_by_id=admin_user.id,
|
||||
call_status="closed",
|
||||
),
|
||||
Complaint(
|
||||
complaint_no="REC-CMP-002",
|
||||
asset_id=asset1.id,
|
||||
description="Mid-month downtime test",
|
||||
priority="non_critical",
|
||||
registered_at=KOLKATA.localize(datetime(2027, 3, 10, 10, 0)).astimezone(timezone.utc),
|
||||
restored_at=KOLKATA.localize(datetime(2027, 3, 10, 13, 30)).astimezone(timezone.utc),
|
||||
registered_by_id=admin_user.id,
|
||||
received_by_id=admin_user.id,
|
||||
call_status="closed",
|
||||
),
|
||||
Complaint(
|
||||
complaint_no="REC-CMP-003",
|
||||
asset_id=asset2.id,
|
||||
description="Third distinct day downtime test",
|
||||
priority="non_critical",
|
||||
registered_at=KOLKATA.localize(datetime(2027, 3, 20, 9, 0)).astimezone(timezone.utc),
|
||||
restored_at=KOLKATA.localize(datetime(2027, 3, 20, 10, 15)).astimezone(timezone.utc),
|
||||
registered_by_id=admin_user.id,
|
||||
received_by_id=admin_user.id,
|
||||
call_status="closed",
|
||||
),
|
||||
]
|
||||
db.add_all(complaints)
|
||||
db.commit()
|
||||
|
||||
res = client.get(
|
||||
f"/api/reports/monthly-maintenance?month=2027-03&department_id={dept.id}",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
payload = res.json()
|
||||
|
||||
summary = payload["summary"]
|
||||
assert summary["total_assets"] == 2
|
||||
assert summary["total_complaints"] == 3
|
||||
assert summary["total_downtime_minutes"] == 525
|
||||
assert summary["downtime_days_count"] == 3
|
||||
assert summary["total_scheduled_minutes"] == 89280
|
||||
assert summary["total_uptime_minutes"] == 88755
|
||||
assert summary["downtime_pct"] == round(525 / 89280 * 100, 2)
|
||||
|
||||
assert len(payload["rows"]) == 1
|
||||
row = payload["rows"][0]
|
||||
assert row["department_name"] == "Reconciliation Test Unit"
|
||||
assert row["asset_count"] == 2
|
||||
assert row["complaint_count"] == 3
|
||||
assert row["total_downtime_minutes"] == 525
|
||||
assert row["downtime_days_count"] == 3
|
||||
assert row["scheduled_minutes"] == 89280
|
||||
assert row["total_uptime_minutes"] == 88755
|
||||
|
||||
|
||||
def test_report_exports_xlsx_and_csv(client):
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
|
||||
# Excel export
|
||||
xlsx_res = client.get(
|
||||
"/api/reports/monthly-maintenance/export?format=xlsx&month=2027-03",
|
||||
headers=mgmt_headers,
|
||||
)
|
||||
assert xlsx_res.status_code == 200
|
||||
assert "spreadsheetml.sheet" in xlsx_res.headers["content-type"]
|
||||
assert 'filename="monthly-maintenance.xlsx"' in xlsx_res.headers["content-disposition"]
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(xlsx_res.content))
|
||||
ws = wb.active
|
||||
assert "Poona Hospital" in str(ws["A1"].value)
|
||||
assert "Generated:" in str(ws["A2"].value)
|
||||
assert "Filters:" in str(ws["A2"].value)
|
||||
assert "Total Downtime Minutes: 525" in str(ws["A3"].value)
|
||||
assert ws.freeze_panes == "A6"
|
||||
assert ws.cell(row=5, column=1).value == "Department"
|
||||
assert "1E3A8A" in str(ws.cell(row=5, column=1).fill.start_color.rgb)
|
||||
assert ws.max_row >= 6
|
||||
|
||||
# CSV export
|
||||
csv_res = client.get(
|
||||
"/api/reports/breakdown-complaints/export?format=csv",
|
||||
headers=mgmt_headers,
|
||||
)
|
||||
assert csv_res.status_code == 200
|
||||
assert "text/csv" in csv_res.headers["content-type"]
|
||||
assert 'filename="breakdown-complaints.csv"' in csv_res.headers["content-disposition"]
|
||||
assert csv_res.content.startswith(b"\xef\xbb\xbf")
|
||||
|
||||
decoded = csv_res.content.decode("utf-8-sig")
|
||||
parsed = list(csv.reader(StringIO(decoded)))
|
||||
assert len(parsed) >= 5
|
||||
assert "Poona Hospital" in parsed[0][0]
|
||||
assert parsed[4][0] == "Complaint No"
|
||||
|
||||
# Unsupported export format rejected
|
||||
bad_fmt = client.get(
|
||||
"/api/reports/monthly-maintenance/export?format=pdf",
|
||||
headers=mgmt_headers,
|
||||
)
|
||||
assert bad_fmt.status_code == 422
|
||||
|
||||
|
||||
def test_all_eight_reports_export_xlsx_and_csv(client):
|
||||
"""Verify that all 8 reports export cleanly as both XLSX and CSV without title/slash errors."""
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
for key in ALL_REPORT_KEYS:
|
||||
# Test XLSX export
|
||||
xlsx_res = client.get(
|
||||
f"/api/reports/{key}/export?format=xlsx",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert xlsx_res.status_code == 200, f"XLSX export failed for {key}: {xlsx_res.text}"
|
||||
assert "spreadsheetml.sheet" in xlsx_res.headers["content-type"]
|
||||
assert f'filename="{key}.xlsx"' in xlsx_res.headers["content-disposition"]
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(xlsx_res.content))
|
||||
ws = wb.active
|
||||
assert ws is not None
|
||||
assert "/" not in ws.title and "\\" not in ws.title
|
||||
assert len(ws.title) <= 31
|
||||
|
||||
# Test CSV export
|
||||
csv_res = client.get(
|
||||
f"/api/reports/{key}/export?format=csv",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert csv_res.status_code == 200, f"CSV export failed for {key}: {csv_res.text}"
|
||||
assert "text/csv" in csv_res.headers["content-type"]
|
||||
assert f'filename="{key}.csv"' in csv_res.headers["content-disposition"]
|
||||
|
||||
Reference in New Issue
Block a user