phase-3: breakdown and complaint register with calculations and permissions
This commit is contained in:
@@ -0,0 +1,332 @@
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
import pytest
|
||||
|
||||
from app.core.time_utils import KOLKATA
|
||||
from app.models import Asset, Complaint, Department, User
|
||||
from app.seed.seed import seed_database
|
||||
from app.services.calculations import (
|
||||
clip_downtime_to_month,
|
||||
compute_ce_response_time_minutes,
|
||||
compute_downtime_minutes,
|
||||
compute_response_time_minutes,
|
||||
)
|
||||
from app.services.numbering import generate_complaint_no
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_complaints_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("complaint_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_generate_complaint_no_and_custom_prefix(db):
|
||||
dt = datetime(2026, 4, 15, 10, 0, tzinfo=timezone.utc)
|
||||
# Seed created CMP-2026-0001..0030 (when run in 2026) or current year; test custom prefix cleanly
|
||||
c1 = generate_complaint_no(db, "PHRC", dt)
|
||||
assert c1 == "PHRC-2026-0001"
|
||||
|
||||
# Existing CMP prefix in current KOLKATA year increments sequentially
|
||||
now_utc = datetime.now(timezone.utc)
|
||||
cur_year = now_utc.astimezone(KOLKATA).year
|
||||
next_cmp = generate_complaint_no(db, "CMP", now_utc)
|
||||
assert next_cmp == f"CMP-{cur_year}-0031"
|
||||
|
||||
|
||||
def test_response_time_and_downtime_calculations():
|
||||
reg = datetime(2026, 5, 10, 8, 0, tzinfo=timezone.utc)
|
||||
recv = datetime(2026, 5, 10, 8, 15, tzinfo=timezone.utc)
|
||||
att = datetime(2026, 5, 10, 9, 0, tzinfo=timezone.utc)
|
||||
rst = datetime(2026, 5, 10, 11, 30, tzinfo=timezone.utc)
|
||||
cls = datetime(2026, 5, 10, 12, 0, tzinfo=timezone.utc)
|
||||
ce_att = datetime(2026, 5, 10, 10, 0, tzinfo=timezone.utc)
|
||||
now = datetime(2026, 5, 10, 13, 0, tzinfo=timezone.utc)
|
||||
|
||||
# Response time
|
||||
assert compute_response_time_minutes(reg, recv, None, "registered_at") is None
|
||||
assert compute_response_time_minutes(reg, recv, att, "registered_at") == 60
|
||||
assert compute_response_time_minutes(reg, recv, att, "received_at") == 45
|
||||
|
||||
# CE response time
|
||||
assert compute_ce_response_time_minutes(reg, None) is None
|
||||
assert compute_ce_response_time_minutes(reg, ce_att) == 120
|
||||
|
||||
# Downtime milestones
|
||||
assert compute_downtime_minutes(reg, att, rst, cls, "attended_at", now) == (60, False)
|
||||
assert compute_downtime_minutes(reg, att, rst, cls, "restored_at", now) == (210, False)
|
||||
assert compute_downtime_minutes(reg, att, rst, cls, "closed_at", now) == (240, False)
|
||||
|
||||
# Ongoing downtime when chosen milestone is None
|
||||
assert compute_downtime_minutes(reg, att, None, None, "restored_at", now) == (300, True)
|
||||
|
||||
|
||||
def test_clip_downtime_to_month_across_boundary():
|
||||
# Jan 30 22:00 IST to Feb 02 04:00 IST
|
||||
start_utc = KOLKATA.localize(datetime(2026, 1, 30, 22, 0, 0)).astimezone(timezone.utc)
|
||||
end_utc = KOLKATA.localize(datetime(2026, 2, 2, 4, 0, 0)).astimezone(timezone.utc)
|
||||
|
||||
jan_mins, jan_days = clip_downtime_to_month(start_utc, end_utc, 2026, 1)
|
||||
assert jan_mins == 26 * 60 # 2h on Jan 30 + 24h on Jan 31 = 1560 mins
|
||||
assert jan_days == {date(2026, 1, 30), date(2026, 1, 31)}
|
||||
|
||||
feb_mins, feb_days = clip_downtime_to_month(start_utc, end_utc, 2026, 2)
|
||||
assert feb_mins == 28 * 60 # 24h on Feb 1 + 4h on Feb 2 = 1680 mins
|
||||
assert feb_days == {date(2026, 2, 1), date(2026, 2, 2)}
|
||||
|
||||
mar_mins, mar_days = clip_downtime_to_month(start_utc, end_utc, 2026, 3)
|
||||
assert mar_mins == 0
|
||||
assert mar_days == set()
|
||||
|
||||
|
||||
def test_complaint_field_level_permissions(client, db):
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
ot = db.query(Department).filter(Department.code == "OT").first()
|
||||
icu_cmp = (
|
||||
db.query(Complaint)
|
||||
.join(Asset, Complaint.asset_id == Asset.id)
|
||||
.filter(Asset.department_id == icu.id, Complaint.call_status != "closed")
|
||||
.first()
|
||||
)
|
||||
ot_cmp = (
|
||||
db.query(Complaint)
|
||||
.join(Asset, Complaint.asset_id == Asset.id)
|
||||
.filter(Asset.department_id == ot.id)
|
||||
.first()
|
||||
)
|
||||
if icu_cmp is None:
|
||||
icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first()
|
||||
r = client.post(
|
||||
"/api/complaints",
|
||||
headers=dept_headers,
|
||||
json={"asset_id": icu_asset.id, "description": "Permission test issue", "priority": "non_critical"},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
icu_cmp_id = r.json()["id"]
|
||||
else:
|
||||
icu_cmp_id = icu_cmp.id
|
||||
|
||||
# Department scoping on list and detail
|
||||
if ot_cmp is not None:
|
||||
assert client.get(f"/api/complaints/{ot_cmp.id}", headers=dept_headers).status_code == 403
|
||||
assert client.get(f"/api/complaints/{ot_cmp.id}/events", headers=dept_headers).status_code == 403
|
||||
list_res = client.get("/api/complaints?page_size=200", headers=dept_headers)
|
||||
assert list_res.status_code == 200
|
||||
assert all(item["department_id"] == icu.id for item in list_res.json()["items"])
|
||||
|
||||
# Restricted technical fields rejected with 403 for dept_user, management, coordinator
|
||||
for headers in (dept_headers, mgmt_headers, coord_headers):
|
||||
for payload in (
|
||||
{"action_taken": "Replaced PCB"},
|
||||
{"root_cause": "Short circuit"},
|
||||
{"spare_required": True, "spare_cost_estimate": 5000},
|
||||
):
|
||||
r = client.patch(f"/api/complaints/{icu_cmp_id}", headers=headers, json=payload)
|
||||
assert r.status_code == 403
|
||||
assert r.json()["code"] == "FORBIDDEN_TECHNICAL_FIELDS"
|
||||
|
||||
# Non-restricted edit by dept_user works on own non-closed complaint, fails for mgmt/coord
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/complaints/{icu_cmp_id}",
|
||||
headers=dept_headers,
|
||||
json={"notes": "Updated ward note"},
|
||||
).status_code
|
||||
== 200
|
||||
)
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/complaints/{icu_cmp_id}",
|
||||
headers=mgmt_headers,
|
||||
json={"notes": "Mgmt edit"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/complaints/{icu_cmp_id}",
|
||||
headers=coord_headers,
|
||||
json={"notes": "Coord edit"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# biomedical and system_admin succeed on technical fields
|
||||
bio_patch = client.patch(
|
||||
f"/api/complaints/{icu_cmp_id}",
|
||||
headers=bio_headers,
|
||||
json={"action_taken": "Cleaned connector", "root_cause": "Loose cable"},
|
||||
)
|
||||
assert bio_patch.status_code == 200
|
||||
assert bio_patch.json()["action_taken"] == "Cleaned connector"
|
||||
|
||||
admin_patch = client.patch(
|
||||
f"/api/complaints/{icu_cmp_id}",
|
||||
headers=admin_headers,
|
||||
json={"corrective_action": "Secured latch"},
|
||||
)
|
||||
assert admin_patch.status_code == 200
|
||||
assert admin_patch.json()["corrective_action"] == "Secured latch"
|
||||
|
||||
|
||||
def test_full_complaint_workflow_and_asset_status_sync(client, db):
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
asset = db.query(Asset).filter(Asset.department_id == icu.id, Asset.status == "in_service").first()
|
||||
assert asset is not None
|
||||
|
||||
bio1 = db.query(User).filter(User.email == "bio@poona.demo").first()
|
||||
bio2 = db.query(User).filter(User.email == "vikram.shinde@poona.demo").first()
|
||||
|
||||
# 1. Dept user raises critical complaint -> asset becomes under_repair
|
||||
create_res = client.post(
|
||||
"/api/complaints",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"asset_id": asset.id,
|
||||
"description": "Ventilator pressure drop alarm",
|
||||
"breakdown_details": "Alarm triggered during patient weaning",
|
||||
"priority": "critical",
|
||||
"notes": "Urgent ICU support needed",
|
||||
},
|
||||
)
|
||||
assert create_res.status_code == 201, create_res.text
|
||||
cmp_data = create_res.json()
|
||||
cid = cmp_data["id"]
|
||||
assert cmp_data["call_status"] == "open"
|
||||
assert cmp_data["asset_status"] == "under_repair"
|
||||
assert cmp_data["downtime_is_ongoing"] is True
|
||||
|
||||
# 2. Assign -> reassign (events logged)
|
||||
asg1 = client.post(
|
||||
f"/api/complaints/{cid}/assign",
|
||||
headers=bio_headers,
|
||||
json={"assigned_to_id": bio1.id, "note": "Initial assignment"},
|
||||
)
|
||||
assert asg1.status_code == 200
|
||||
assert asg1.json()["call_status"] == "in_progress"
|
||||
assert asg1.json()["assigned_to_id"] == bio1.id
|
||||
|
||||
asg2 = client.post(
|
||||
f"/api/complaints/{cid}/assign",
|
||||
headers=bio_headers,
|
||||
json={"assigned_to_id": bio2.id, "note": "Escalated to senior bio"},
|
||||
)
|
||||
assert asg2.status_code == 200
|
||||
assert asg2.json()["assigned_to_id"] == bio2.id
|
||||
|
||||
# 3. Attend -> response_time_minutes computed
|
||||
att_res = client.post(
|
||||
f"/api/complaints/{cid}/attend",
|
||||
headers=bio_headers,
|
||||
json={"attended_by_id": bio2.id, "note": "Reached ICU Bay"},
|
||||
)
|
||||
assert att_res.status_code == 200
|
||||
assert att_res.json()["attended_at"] is not None
|
||||
assert att_res.json()["response_time_minutes"] is not None
|
||||
|
||||
# 4. Edit technical / spare / CE fields
|
||||
ce_time = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
|
||||
tech_res = client.patch(
|
||||
f"/api/complaints/{cid}",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"action_taken": "Replaced inspiratory valve diaphragm",
|
||||
"root_cause": "Diaphragm tear",
|
||||
"corrective_action": "Replaced valve kit and ran leak test",
|
||||
"lessons_learned": "Inspect diaphragm at every 6m PM",
|
||||
"ce_name": "Mahesh Kulkarni (OEM)",
|
||||
"ce_attended_at": ce_time,
|
||||
"ce_action_taken": "Calibrated flow sensor post replacement",
|
||||
"spare_required": True,
|
||||
"spare_details": "Inspiratory valve diaphragm kit",
|
||||
"spare_cost_estimate": 12500.0,
|
||||
},
|
||||
)
|
||||
assert tech_res.status_code == 200
|
||||
assert tech_res.json()["spare_required"] is True
|
||||
assert tech_res.json()["ce_response_time_minutes"] is not None
|
||||
|
||||
# 5. Restore -> asset returns to in_service
|
||||
rst_res = client.post(
|
||||
f"/api/complaints/{cid}/restore",
|
||||
headers=bio_headers,
|
||||
json={"note": "Passed 30-min leak test"},
|
||||
)
|
||||
assert rst_res.status_code == 200
|
||||
assert rst_res.json()["restored_at"] is not None
|
||||
assert rst_res.json()["asset_status"] == "in_service"
|
||||
assert rst_res.json()["downtime_is_ongoing"] is False
|
||||
|
||||
# 6. Close -> call_status closed
|
||||
cls_res = client.post(
|
||||
f"/api/complaints/{cid}/close",
|
||||
headers=bio_headers,
|
||||
json={"closure_remarks": "Handed over to ICU charge nurse"},
|
||||
)
|
||||
assert cls_res.status_code == 200
|
||||
assert cls_res.json()["call_status"] == "closed"
|
||||
assert cls_res.json()["closed_at"] is not None
|
||||
assert cls_res.json()["asset_status"] == "in_service"
|
||||
|
||||
# 7. Reopen -> critical asset back to under_repair
|
||||
reopen_res = client.post(
|
||||
f"/api/complaints/{cid}/reopen",
|
||||
headers=bio_headers,
|
||||
json={"reason": "Alarm reappeared during shift change"},
|
||||
)
|
||||
assert reopen_res.status_code == 200
|
||||
assert reopen_res.json()["call_status"] == "in_progress"
|
||||
assert reopen_res.json()["closed_at"] is None
|
||||
assert reopen_res.json()["asset_status"] == "under_repair"
|
||||
|
||||
# 8. Correct timestamp: biomedical -> 403, system_admin -> 200
|
||||
new_reg = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
|
||||
bio_ts = client.post(
|
||||
f"/api/complaints/{cid}/correct-timestamp",
|
||||
headers=bio_headers,
|
||||
json={"field": "registered_at", "new_value": new_reg, "reason": "Late entry"},
|
||||
)
|
||||
assert bio_ts.status_code == 403
|
||||
|
||||
admin_ts = client.post(
|
||||
f"/api/complaints/{cid}/correct-timestamp",
|
||||
headers=admin_headers,
|
||||
json={"field": "registered_at", "new_value": new_reg, "reason": "Logged after phone call"},
|
||||
)
|
||||
assert admin_ts.status_code == 200
|
||||
assert admin_ts.json()["response_time_minutes"] >= 119
|
||||
|
||||
# 9. Verify events timeline
|
||||
ev_res = client.get(f"/api/complaints/{cid}/events", headers=bio_headers)
|
||||
assert ev_res.status_code == 200
|
||||
events = ev_res.json()["items"]
|
||||
event_types = [e["event_type"] for e in events]
|
||||
assert event_types == [
|
||||
"registered",
|
||||
"assigned",
|
||||
"reassigned",
|
||||
"attended",
|
||||
"field_edited",
|
||||
"restored",
|
||||
"closed",
|
||||
"reopened",
|
||||
"timestamp_corrected",
|
||||
]
|
||||
assert events[2]["from_value"] == bio1.name
|
||||
assert events[2]["to_value"] == bio2.name
|
||||
assert events[8]["note"] == "registered_at: Logged after phone call"
|
||||
Reference in New Issue
Block a user