427 lines
16 KiB
Python
427 lines
16 KiB
Python
from datetime import date
|
|
import pytest
|
|
|
|
from app.core.time_utils import add_months
|
|
from app.models import (
|
|
Asset,
|
|
CalibrationPlan,
|
|
CalibrationRecord,
|
|
Category,
|
|
Contract,
|
|
Department,
|
|
Location,
|
|
PMRecord,
|
|
PMSchedule,
|
|
Vendor,
|
|
)
|
|
from app.seed.seed import seed_database
|
|
|
|
|
|
@pytest.fixture(scope="module", autouse=True)
|
|
def seeded_pm_cal_db(db, tmp_path_factory):
|
|
upload_dir = tmp_path_factory.mktemp("pm_cal_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 _create_test_asset(client, headers, db, code_suffix: str, req_cal: bool = False) -> int:
|
|
icu = db.query(Department).filter(Department.code == "ICU").first()
|
|
loc = db.query(Location).filter(Location.department_id == icu.id).first()
|
|
cat = db.query(Category).first()
|
|
res = client.post(
|
|
"/api/assets",
|
|
headers=headers,
|
|
json={
|
|
"asset_code": f"PHRC-PMCAL-{code_suffix}",
|
|
"serial_no": f"SN-PMCAL-{code_suffix}",
|
|
"name": f"PM Cal Test Unit {code_suffix}",
|
|
"category_id": cat.id,
|
|
"department_id": icu.id,
|
|
"location_id": loc.id,
|
|
"status": "in_service",
|
|
"criticality": "critical",
|
|
"requires_calibration": req_cal,
|
|
"insurance_applicable": False,
|
|
},
|
|
)
|
|
assert res.status_code == 201, res.text
|
|
return res.json()["id"]
|
|
|
|
|
|
def test_add_months_clamping_and_db_note_n2(db):
|
|
assert add_months(date(2026, 1, 31), 1) == date(2026, 2, 28)
|
|
assert add_months(date(2024, 1, 31), 1) == date(2024, 2, 29)
|
|
assert add_months(date(2026, 3, 31), 3) == date(2026, 6, 30)
|
|
assert add_months(date(2026, 10, 15), 4) == date(2027, 2, 15)
|
|
|
|
# Note N2: seeded DB never persists 'upcoming', 'due', or 'overdue'
|
|
bad_cal = (
|
|
db.query(CalibrationRecord)
|
|
.filter(CalibrationRecord.status.in_(["upcoming", "due", "overdue"]))
|
|
.count()
|
|
)
|
|
bad_pm = (
|
|
db.query(PMRecord)
|
|
.filter(PMRecord.status.in_(["upcoming", "due", "overdue"]))
|
|
.count()
|
|
)
|
|
assert bad_cal == 0
|
|
assert bad_pm == 0
|
|
|
|
|
|
def test_outsourced_pm_lifecycle_complete_and_reschedule(client, db):
|
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
|
dept_headers = _auth_headers(client, "dept@poona.demo")
|
|
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
|
|
|
provider = db.query(Vendor).filter(Vendor.vendor_type == "service_provider").first()
|
|
contract = db.query(Contract).filter(Contract.is_superseded.is_(False)).first()
|
|
asset_id = contract.asset_id
|
|
|
|
# Forbidden for department_user and management
|
|
forbid_res = client.post(
|
|
"/api/pm/schedules",
|
|
headers=dept_headers,
|
|
json={
|
|
"asset_id": asset_id,
|
|
"service_mode": "in_house",
|
|
"frequency_months": 3,
|
|
"responsible_team": "ICU Bio",
|
|
"next_planned_date": "2026-06-10",
|
|
},
|
|
)
|
|
assert forbid_res.status_code == 403
|
|
assert (
|
|
client.post(
|
|
"/api/pm/schedules",
|
|
headers=mgmt_headers,
|
|
json={
|
|
"asset_id": asset_id,
|
|
"service_mode": "in_house",
|
|
"frequency_months": 3,
|
|
"responsible_team": "Bio Team",
|
|
"next_planned_date": "2026-06-10",
|
|
},
|
|
).status_code
|
|
== 403
|
|
)
|
|
|
|
# Outsourced PM schedule without provider_id/contract_id auto-fills from active AMC/CMC
|
|
auto_out = client.post(
|
|
"/api/pm/schedules",
|
|
headers=bio_headers,
|
|
json={
|
|
"asset_id": asset_id,
|
|
"service_mode": "outsourced",
|
|
"frequency_months": 3,
|
|
"next_planned_date": "2026-06-10",
|
|
},
|
|
)
|
|
assert auto_out.status_code == 201, auto_out.text
|
|
assert auto_out.json()["contract_id"] == contract.id
|
|
assert auto_out.json()["provider_id"] == contract.provider_id
|
|
|
|
# Create outsourced PM schedule with provider + contract
|
|
sched_res = client.post(
|
|
"/api/pm/schedules",
|
|
headers=bio_headers,
|
|
json={
|
|
"asset_id": asset_id,
|
|
"service_mode": "outsourced",
|
|
"frequency_months": 3,
|
|
"provider_id": contract.provider_id or provider.id,
|
|
"contract_id": contract.id,
|
|
"next_planned_date": "2026-06-10",
|
|
},
|
|
)
|
|
assert sched_res.status_code == 201, sched_res.text
|
|
sched = sched_res.json()
|
|
assert sched["service_mode"] == "outsourced"
|
|
assert sched["contract_id"] == contract.id
|
|
assert sched["contract_summary"] is not None
|
|
|
|
# Initial PMRecord was created with planned_date=2026-06-10 and DB status=None
|
|
recs_res = client.get(f"/api/pm/records?schedule_id={sched['id']}", headers=bio_headers)
|
|
assert recs_res.status_code == 200
|
|
items = recs_res.json()["items"]
|
|
assert len(items) == 1
|
|
first_rec_id = items[0]["id"]
|
|
assert items[0]["planned_date"] == "2026-06-10"
|
|
db.expire_all()
|
|
assert db.query(PMRecord).filter(PMRecord.id == first_rec_id).first().status is None
|
|
|
|
# Complete the initial PMRecord on 2026-06-12 -> next planned 2026-09-12
|
|
comp_res = client.post(
|
|
f"/api/pm/records/{first_rec_id}/complete",
|
|
headers=bio_headers,
|
|
json={
|
|
"completed_date": "2026-06-12",
|
|
"service_details": "Replaced flow sensor filter and verified pressure calibration.",
|
|
"remarks": "Vendor engineer visit completed.",
|
|
},
|
|
)
|
|
assert comp_res.status_code == 200, comp_res.text
|
|
comp_data = comp_res.json()
|
|
assert comp_data["completed_record"]["status"] == "completed"
|
|
assert comp_data["completed_record"]["completed_date"] == "2026-06-12"
|
|
assert comp_data["next_record"]["planned_date"] == "2026-09-12"
|
|
|
|
# Re-completing same record -> 400
|
|
recomp = client.post(
|
|
f"/api/pm/records/{first_rec_id}/complete",
|
|
headers=bio_headers,
|
|
json={"completed_date": "2026-06-13", "service_details": "Duplicate"},
|
|
)
|
|
assert recomp.status_code == 400
|
|
|
|
# Reschedule the generated next record from 2026-09-12 to 2026-09-25
|
|
second_rec_id = comp_data["next_record"]["id"]
|
|
resched_res = client.post(
|
|
f"/api/pm/records/{second_rec_id}/reschedule",
|
|
headers=bio_headers,
|
|
json={"rescheduled_to": "2026-09-25", "remarks": "OT occupied on 12 Sep."},
|
|
)
|
|
assert resched_res.status_code == 200, resched_res.text
|
|
resched_data = resched_res.json()
|
|
assert resched_data["rescheduled_record"]["status"] == "rescheduled"
|
|
assert resched_data["rescheduled_record"]["rescheduled_to"] == "2026-09-25"
|
|
assert resched_data["next_record"]["planned_date"] == "2026-09-25"
|
|
|
|
# Verify schedule next_planned_date updated and deactivate schedule works
|
|
del_res = client.delete(f"/api/pm/schedules/{sched['id']}", headers=bio_headers)
|
|
assert del_res.status_code == 200
|
|
assert del_res.json()["is_active"] is False
|
|
|
|
|
|
def test_calibration_plan_approval_permissions_and_completion(client, db):
|
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
|
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
|
dept_headers = _auth_headers(client, "dept@poona.demo")
|
|
|
|
a1 = _create_test_asset(client, bio_headers, db, "001", req_cal=False)
|
|
a2 = _create_test_asset(client, bio_headers, db, "002", req_cal=False)
|
|
a3 = _create_test_asset(client, bio_headers, db, "003", req_cal=True)
|
|
agency = db.query(Vendor).filter(Vendor.vendor_type == "calibration_agency").first()
|
|
|
|
# Biomedical cannot create with approve=True
|
|
forbid_create_app = client.post(
|
|
f"/api/calibration/plans/from-asset/{a1}",
|
|
headers=bio_headers,
|
|
json={
|
|
"frequency_months": 6,
|
|
"agency_id": agency.id,
|
|
"next_due_date": "2026-08-01",
|
|
"approve": True,
|
|
},
|
|
)
|
|
assert forbid_create_app.status_code == 403
|
|
assert forbid_create_app.json()["code"] == "FORBIDDEN_CALIBRATION_APPROVAL"
|
|
|
|
# Biomedical creates unapproved plan from asset -> sets requires_calibration=True
|
|
c1 = client.post(
|
|
f"/api/calibration/plans/from-asset/{a1}",
|
|
headers=bio_headers,
|
|
json={
|
|
"frequency_months": 6,
|
|
"agency_id": agency.id,
|
|
"next_due_date": "2026-08-01",
|
|
"approve": False,
|
|
},
|
|
)
|
|
assert c1.status_code == 201, c1.text
|
|
plan1 = c1.json()
|
|
assert plan1["calibrations_per_year"] == 2
|
|
assert plan1["approved_by_id"] is None
|
|
db.expire_all()
|
|
assert db.query(Asset).filter(Asset.id == a1).first().requires_calibration is True
|
|
|
|
# Duplicate from-asset -> 409 DUPLICATE_CALIBRATION_PLAN
|
|
dup = client.post(
|
|
f"/api/calibration/plans/from-asset/{a1}",
|
|
headers=bio_headers,
|
|
json={"frequency_months": 6, "next_due_date": "2026-08-01"},
|
|
)
|
|
assert dup.status_code == 409
|
|
assert dup.json()["code"] == "DUPLICATE_CALIBRATION_PLAN"
|
|
|
|
# Bulk add with a1 (already has plan) + a2 + a3
|
|
bulk_res = client.post(
|
|
"/api/calibration/plans/bulk-from-assets",
|
|
headers=bio_headers,
|
|
json={
|
|
"asset_ids": [a1, a2, a3],
|
|
"frequency_months": 12,
|
|
"agency_id": agency.id,
|
|
"next_due_date": "2026-10-15",
|
|
"approve": False,
|
|
},
|
|
)
|
|
assert bulk_res.status_code == 200, bulk_res.text
|
|
bulk_json = bulk_res.json()
|
|
assert [p["asset_id"] for p in bulk_json["created"]] == [a2, a3]
|
|
assert bulk_json["skipped_asset_ids"] == [a1]
|
|
|
|
# Biomedical gets 403 trying to modify frequency or approve; management succeeds (200)
|
|
bio_freq = client.put(
|
|
f"/api/calibration/plans/{plan1['id']}",
|
|
headers=bio_headers,
|
|
json={"frequency_months": 12},
|
|
)
|
|
assert bio_freq.status_code == 403
|
|
assert bio_freq.json()["code"] == "FORBIDDEN_CALIBRATION_APPROVAL"
|
|
|
|
bio_app = client.post(f"/api/calibration/plans/{plan1['id']}/approve", headers=bio_headers)
|
|
assert bio_app.status_code == 403
|
|
|
|
assert client.post(f"/api/calibration/plans/{plan1['id']}/approve", headers=dept_headers).status_code == 403
|
|
|
|
mgmt_freq = client.put(
|
|
f"/api/calibration/plans/{plan1['id']}",
|
|
headers=mgmt_headers,
|
|
json={"frequency_months": 4},
|
|
)
|
|
assert mgmt_freq.status_code == 200
|
|
assert mgmt_freq.json()["frequency_months"] == 4
|
|
assert mgmt_freq.json()["calibrations_per_year"] == 3
|
|
|
|
mgmt_app = client.post(
|
|
f"/api/calibration/plans/{plan1['id']}/approve",
|
|
headers=mgmt_headers,
|
|
json={"frequency_months": 6},
|
|
)
|
|
assert mgmt_app.status_code == 200, mgmt_app.text
|
|
assert mgmt_app.json()["frequency_months"] == 6
|
|
assert mgmt_app.json()["approved_by_name"] is not None
|
|
assert mgmt_app.json()["approved_on"] is not None
|
|
|
|
# Complete calibration record -> creates next record at completed_date + frequency_months and preserves history
|
|
cal_recs = client.get(f"/api/calibration/records?asset_id={a1}", headers=bio_headers).json()["items"]
|
|
assert len(cal_recs) == 1
|
|
rec1_id = cal_recs[0]["id"]
|
|
|
|
comp = client.post(
|
|
f"/api/calibration/records/{rec1_id}/complete",
|
|
headers=bio_headers,
|
|
json={
|
|
"completed_date": "2026-08-05",
|
|
"certificate_no": "NABL-2026-9901",
|
|
"agency_id": agency.id,
|
|
"remarks": "All channels within +/-1% tolerance.",
|
|
},
|
|
)
|
|
assert comp.status_code == 200, comp.text
|
|
comp_json = comp.json()
|
|
assert comp_json["completed_record"]["status"] == "completed"
|
|
assert comp_json["completed_record"]["certificate_no"] == "NABL-2026-9901"
|
|
assert comp_json["next_record"]["due_date"] == "2027-02-05"
|
|
|
|
# Both historical and next records exist for asset
|
|
history = client.get(f"/api/calibration/records?asset_id={a1}", headers=bio_headers).json()
|
|
assert history["total"] == 2
|
|
assert history["summary"]["completed"] == 1
|
|
|
|
|
|
def test_demo_clock_transitions_statuses_dynamically_on_read(client, db):
|
|
admin_headers = _auth_headers(client, "admin@poona.demo")
|
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
|
|
|
asset_id = _create_test_asset(client, bio_headers, db, "CLK", req_cal=True)
|
|
agency = db.query(Vendor).filter(Vendor.vendor_type == "calibration_agency").first()
|
|
|
|
# Calibration due 2028-06-20; PM planned 2028-06-20 (far future, no interference)
|
|
cal_plan = client.post(
|
|
f"/api/calibration/plans/from-asset/{asset_id}",
|
|
headers=admin_headers,
|
|
json={
|
|
"frequency_months": 12,
|
|
"agency_id": agency.id,
|
|
"next_due_date": "2028-06-20",
|
|
"approve": True,
|
|
},
|
|
)
|
|
assert cal_plan.status_code == 201
|
|
|
|
pm_sched = client.post(
|
|
"/api/pm/schedules",
|
|
headers=bio_headers,
|
|
json={
|
|
"asset_id": asset_id,
|
|
"service_mode": "in_house",
|
|
"frequency_months": 6,
|
|
"responsible_team": "Bio Team A",
|
|
"next_planned_date": "2028-06-20",
|
|
},
|
|
)
|
|
assert pm_sched.status_code == 201
|
|
|
|
try:
|
|
# 1) 2028-05-01 -> 50 days before due -> both 'upcoming' (ok)
|
|
client.post(
|
|
"/api/settings/demo-date",
|
|
headers=admin_headers,
|
|
json={"demo_as_of_date": "2028-05-01"},
|
|
)
|
|
cal1 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
|
pm1 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
|
ov1 = client.get(f"/api/assets/{asset_id}/overview", headers=bio_headers).json()
|
|
assert cal1["status"] == "upcoming" and cal1["severity"] == "ok"
|
|
assert pm1["status"] == "upcoming" and pm1["severity"] == "ok"
|
|
assert ov1["calibration_records"][0]["status"] == "upcoming"
|
|
assert ov1["pm_records"][0]["status"] == "upcoming"
|
|
|
|
# 2) 2028-06-10 -> 10 days before due (<= 15 lead, > 7 red) -> both 'due' (yellow)
|
|
client.post(
|
|
"/api/settings/demo-date",
|
|
headers=admin_headers,
|
|
json={"demo_as_of_date": "2028-06-10"},
|
|
)
|
|
cal2 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
|
pm2 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
|
ov2 = client.get(f"/api/assets/{asset_id}/overview", headers=bio_headers).json()
|
|
assert cal2["status"] == "due" and cal2["severity"] == "yellow"
|
|
assert pm2["status"] == "due" and pm2["severity"] == "yellow"
|
|
assert ov2["calibration_records"][0]["status"] == "due"
|
|
assert ov2["pm_records"][0]["status"] == "due"
|
|
|
|
# 3) 2028-06-15 -> 5 days before due (<= 7 red) -> 'due' (red)
|
|
client.post(
|
|
"/api/settings/demo-date",
|
|
headers=admin_headers,
|
|
json={"demo_as_of_date": "2028-06-15"},
|
|
)
|
|
cal3 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
|
pm3 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
|
assert cal3["status"] == "due" and cal3["severity"] == "red"
|
|
assert pm3["status"] == "due" and pm3["severity"] == "red"
|
|
|
|
# 4) 2028-06-25 -> 5 days past due -> 'overdue' (red)
|
|
client.post(
|
|
"/api/settings/demo-date",
|
|
headers=admin_headers,
|
|
json={"demo_as_of_date": "2028-06-25"},
|
|
)
|
|
cal4 = client.get(f"/api/calibration/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
|
pm4 = client.get(f"/api/pm/records?asset_id={asset_id}", headers=bio_headers).json()["items"][0]
|
|
ov4 = client.get(f"/api/assets/{asset_id}/overview", headers=bio_headers).json()
|
|
assert cal4["status"] == "overdue" and cal4["severity"] == "red"
|
|
assert pm4["status"] == "overdue" and pm4["severity"] == "red"
|
|
assert ov4["calibration_records"][0]["status"] == "overdue"
|
|
assert ov4["pm_records"][0]["status"] == "overdue"
|
|
|
|
# Confirm DB status columns stayed NULL throughout!
|
|
db.expire_all()
|
|
assert db.query(CalibrationRecord).filter(CalibrationRecord.asset_id == asset_id).first().status is None
|
|
assert db.query(PMRecord).filter(PMRecord.asset_id == asset_id).first().status is None
|
|
finally:
|
|
client.post(
|
|
"/api/settings/demo-date",
|
|
headers=admin_headers,
|
|
json={"demo_as_of_date": None},
|
|
)
|