from io import BytesIO from datetime import date, timedelta import pytest from app.core.time_utils import effective_today from app.models import Asset, Department, Location, PMRecord, PMSchedule, Vendor from app.seed.seed import seed_database @pytest.fixture(scope="module", autouse=True) def _seed(db, tmp_path_factory): upload_dir = tmp_path_factory.mktemp("uploads") seed_database(db, upload_dir=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 token = res.json()["access_token"] return {"Authorization": f"Bearer {token}"} def test_pm_record_attachment_upload_and_download(client, db): bio_headers = _auth_headers(client, "bio@poona.demo") pm_rec = db.query(PMRecord).first() assert pm_rec is not None # Valid PDF file upload against pm_record fake_pdf = b"%PDF-1.4 sample pm service report job sheet content" files = {"file": ("pm_service_report.pdf", BytesIO(fake_pdf), "application/pdf")} data = {"entity_type": "pm_record", "entity_id": str(pm_rec.id)} upload_res = client.post("/api/attachments", headers=bio_headers, data=data, files=files) assert upload_res.status_code == 201, upload_res.text att_data = upload_res.json() att_id = att_data["id"] assert att_data["entity_type"] == "pm_record" assert att_data["original_name"] == "pm_service_report.pdf" # List attachments for pm_record list_res = client.get( f"/api/attachments?entity_type=pm_record&entity_id={pm_rec.id}", headers=bio_headers, ) assert list_res.status_code == 200 assert any(item["id"] == att_id for item in list_res.json()["items"]) # Download attachment dl_res = client.get(f"/api/attachments/{att_id}/download", headers=bio_headers) assert dl_res.status_code == 200 assert dl_res.content == fake_pdf def test_complaint_assigned_team_and_location_filter(client, db): bio_headers = _auth_headers(client, "bio@poona.demo") asset = db.query(Asset).filter(Asset.location_id.isnot(None)).first() assert asset is not None # 1. Raise complaint with assigned_team res = client.post( "/api/complaints", headers=bio_headers, json={ "asset_id": asset.id, "description": "Ventilator screen flickering", "priority": "non_critical", "assigned_team": "Biomedical Clinical Support", }, ) assert res.status_code == 201, res.text c_data = res.json() cid = c_data["id"] assert c_data["assigned_team"] == "Biomedical Clinical Support" # 2. Assign team via /assign endpoint assign_res = client.post( f"/api/complaints/{cid}/assign", headers=bio_headers, json={"assigned_team": "External Vendor Tier 2 Team", "note": "Assigned to specialized vendor team"}, ) assert assign_res.status_code == 200, assign_res.text assert assign_res.json()["assigned_team"] == "External Vendor Tier 2 Team" # 3. Filter by location_id loc_res = client.get( f"/api/complaints?location_id={asset.location_id}", headers=bio_headers, ) assert loc_res.status_code == 200 items = loc_res.json()["items"] assert any(c["id"] == cid for c in items) def test_demo_equipment_serial_no(client, db): bio_headers = _auth_headers(client, "bio@poona.demo") dept = db.query(Department).first() vendor = db.query(Vendor).first() today = effective_today(db) # Create demo equipment with serial_no res = client.post( "/api/demo-equipment", headers=bio_headers, json={ "name": "Trial Dialysis Unit", "equipment_type": "Dialysis", "serial_no": "DEMO-SN-DIAL-901", "supplier_id": vendor.id, "department_id": dept.id, "start_date": str(today), "expected_return_date": str(today + timedelta(days=14)), "remarks": "Evaluation unit on 14-day trial", }, ) assert res.status_code == 201, res.text demo_data = res.json() demo_id = demo_data["id"] assert demo_data["serial_no"] == "DEMO-SN-DIAL-901" # List demo equipment list_res = client.get(f"/api/demo-equipment?department_id={dept.id}", headers=bio_headers) assert list_res.status_code == 200 found = next((item for item in list_res.json()["items"] if item["id"] == demo_id), None) assert found is not None assert found["serial_no"] == "DEMO-SN-DIAL-901" def test_department_visit_new_requirements_and_monthly_report(client, db): bio_headers = _auth_headers(client, "bio@poona.demo") mgmt_headers = _auth_headers(client, "mgmt@poona.demo") dept = db.query(Department).first() today = effective_today(db) # Create visit with new_requirements req_text = "Urgent: Requesting 2 additional Infusion Pumps for Bed 3 & 4" res = client.post( "/api/visits", headers=bio_headers, json={ "department_id": dept.id, "visit_date": str(today), "observations": "All ICU ventilators functioning normally; routine checks complete.", "new_requirements": req_text, }, ) assert res.status_code == 201, res.text v_data = res.json() assert v_data["new_requirements"] == req_text # Monthly Department Report reflects new requirements month_str = today.strftime("%Y-%m") rep_res = client.get( f"/api/reports/monthly-department?month={month_str}&department_id={dept.id}", headers=mgmt_headers, ) assert rep_res.status_code == 200, rep_res.text rows = rep_res.json()["rows"] dept_row = next((r for r in rows if r["department_id"] == dept.id), None) assert dept_row is not None assert req_text in dept_row["new_equipment_requirements"] def test_asset_calibration_and_insurance_filters(client, db): bio_headers = _auth_headers(client, "bio@poona.demo") # Filter calibration applicable res_cal_yes = client.get("/api/assets?requires_calibration=true", headers=bio_headers) assert res_cal_yes.status_code == 200 for a in res_cal_yes.json()["items"]: assert a["requires_calibration"] is True res_cal_no = client.get("/api/assets?requires_calibration=false", headers=bio_headers) assert res_cal_no.status_code == 200 for a in res_cal_no.json()["items"]: assert a["requires_calibration"] is False # Filter insurance applicable res_ins_yes = client.get("/api/assets?insurance_applicable=true", headers=bio_headers) assert res_ins_yes.status_code == 200 for a in res_ins_yes.json()["items"]: assert a["insurance_applicable"] is True def test_bulk_import_templates_endpoints(client): coord_headers = _auth_headers(client, "coord@poona.demo") # Contracts template r_c = client.get("/api/contracts/import-template", headers=coord_headers) assert r_c.status_code == 200 assert r_c.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" assert len(r_c.content) > 1000 # Calibration template r_cal = client.get("/api/calibration/import-template", headers=coord_headers) assert r_cal.status_code == 200 assert r_cal.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" assert len(r_cal.content) > 1000 # Insurance template r_ins = client.get("/api/insurance/import-template", headers=coord_headers) assert r_ins.status_code == 200 assert r_ins.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" assert len(r_ins.content) > 1000 def test_sqlite_auto_migration_reconciles_missing_columns(): from sqlalchemy import create_engine from app.core.migrations import run_sqlite_migrations test_eng = create_engine("sqlite:///:memory:") with test_eng.begin() as conn: # Create complaints table without assigned_team column conn.exec_driver_sql( "CREATE TABLE complaints (" "id INTEGER PRIMARY KEY, " "complaint_no VARCHAR(50), " "asset_id INTEGER, " "description TEXT, " "priority VARCHAR(50), " "registered_at DATETIME, " "registered_by_id INTEGER, " "received_by_id INTEGER, " "call_status VARCHAR(50)" ")" ) cols_before = {r[1] for r in conn.exec_driver_sql("PRAGMA table_info(complaints)").fetchall()} assert "assigned_team" not in cols_before # Run auto-migration run_sqlite_migrations(test_eng) with test_eng.begin() as conn: cols_after = {r[1] for r in conn.exec_driver_sql("PRAGMA table_info(complaints)").fetchall()} assert "assigned_team" in cols_after