fix: close sets restored_at, SLA alert type, error shape, prefix label

This commit is contained in:
Atharv1705
2026-11-12 18:11:08 +05:30
parent e2a6fa601e
commit 1cf218ca00
6 changed files with 200 additions and 20 deletions
+6 -5
View File
@@ -690,17 +690,18 @@ def close_complaint(
payload.closure_remarks if payload.closure_remarks is not None else comp.closure_remarks
)
if require_remarks and (effective_remarks is None or not str(effective_remarks).strip()):
raise HTTPException(
# Use CodedHTTPException so 422 responses match {"detail": str, "code": str} across the API
raise CodedHTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail={
"code": "CLOSURE_REMARKS_REQUIRED",
"message": "Closure remarks are required.",
},
detail="Closure remarks are required.",
code="CLOSURE_REMARKS_REQUIRED",
)
now = utc_now()
prev_status = comp.call_status
comp.closed_by_id = current_user.id
comp.closed_at = now
if comp.restored_at is None:
comp.restored_at = comp.closed_at
if payload.closure_remarks is not None:
comp.closure_remarks = payload.closure_remarks
comp.call_status = "closed"
+35 -11
View File
@@ -278,7 +278,7 @@ def run_alert_check(db: Session) -> dict[str, object]:
created_at=eff_now,
)
# 7. Critical complaints open >= critical_complaint_alert_hours
# 7. Critical complaints open >= escalation_open_complaint_hours
crit_complaints = (
db.query(Complaint)
.options(joinedload(Complaint.asset))
@@ -288,16 +288,7 @@ def run_alert_check(db: Session) -> dict[str, object]:
threshold_secs = cfg["critical_hours"] * 3600
for c in crit_complaints:
elapsed = (_ensure_utc(eff_now) - _ensure_utc(c.registered_at)).total_seconds()
sla_breached, _target_h = compute_sla_status(
c.priority,
c.registered_at,
c.attended_at,
c.restored_at,
critical_sla_hours=cfg["critical_sla_hours"],
non_critical_sla_hours=cfg["non_critical_sla_hours"],
now_utc=eff_now,
)
if elapsed >= threshold_secs or sla_breached:
if elapsed >= threshold_secs:
created += _add_if_new(
db,
existing_keys,
@@ -313,6 +304,39 @@ def run_alert_check(db: Session) -> dict[str, object]:
created_at=eff_now,
)
# 8. Open unrestored complaints breaching configured SLA hours
open_unrestored = (
db.query(Complaint)
.options(joinedload(Complaint.asset))
.filter(Complaint.call_status != "closed", Complaint.restored_at.is_(None))
.all()
)
for c in open_unrestored:
sla_breached, sla_hours = compute_sla_status(
c.priority,
c.registered_at,
c.attended_at,
c.restored_at,
critical_sla_hours=cfg["critical_sla_hours"],
non_critical_sla_hours=cfg["non_critical_sla_hours"],
now_utc=eff_now,
)
if sla_breached:
created += _add_if_new(
db,
existing_keys,
dedupe_key=f"cmp:{c.id}:sla_breach",
alert_type="sla_breach",
severity="red",
title=f"SLA Breach: Open > {sla_hours}h: {c.complaint_no}",
message=f"Complaint {c.complaint_no} for {c.asset.name} ({c.asset.asset_code}) exceeded {sla_hours}h SLA without restoration.",
entity_type="complaint",
entity_id=c.id,
due_date=today,
target_role="biomedical,management,system_admin,department_user",
created_at=eff_now,
)
db.flush()
return {"created": created, "evaluated_today": today.isoformat()}
+2 -2
View File
@@ -131,8 +131,8 @@ SETTINGS_SCHEMA: list[dict[str, Any]] = [
"key": "asset_code_prefix",
"type": "str",
"default": "PHRC",
"label": "Asset Code Prefix",
"description": "Default prefix used when formatting hospital asset codes (e.g. PHRC-ICU-0001).",
"label": "Asset Code Prefix (used in bulk-import template sample row only)",
"description": "Sample code prefix shown in the bulk-import template sample row (e.g. PHRC-ICU-0001). Hand-typed asset codes are not restricted.",
"min": None,
"max": None,
"options": None,
+153 -1
View File
@@ -365,7 +365,8 @@ def test_require_closure_remarks_and_wired_settings(client, db):
json={"closure_remarks": " "},
)
assert fail_close.status_code == 422
assert fail_close.json()["detail"]["code"] == "CLOSURE_REMARKS_REQUIRED"
assert fail_close.json()["code"] == "CLOSURE_REMARKS_REQUIRED"
assert fail_close.json()["detail"] == "Closure remarks are required."
try:
# Disable require_closure_remarks -> blank remarks closes cleanly (200)
@@ -415,3 +416,154 @@ def test_require_closure_remarks_and_wired_settings(client, db):
)
assert target2 == 24 and not_breached is False
def test_close_without_restore_sets_restored_at_and_reopen_recloses(client, db):
bio_headers = _auth_headers(client, "bio@poona.demo")
asset = db.query(Asset).first()
assert asset is not None
create_res = client.post(
"/api/complaints",
headers=bio_headers,
json={
"asset_id": asset.id,
"priority": "non_critical",
"description": "Close without explicit restore check",
},
)
assert create_res.status_code == 201, create_res.text
cid = create_res.json()["id"]
# Close directly without /restore -> restored_at is backfilled to closed_at
close1 = client.post(
f"/api/complaints/{cid}/close",
headers=bio_headers,
json={"closure_remarks": "Resolved during inspection"},
)
assert close1.status_code == 200, close1.text
c1 = close1.json()
assert c1["call_status"] == "closed"
assert c1["closed_at"] is not None
assert c1["restored_at"] == c1["closed_at"]
assert c1["downtime_is_ongoing"] is False
# Reopen -> restored_at is cleared and downtime is ongoing again
reopen1 = client.post(
f"/api/complaints/{cid}/reopen",
headers=bio_headers,
json={"reason": "Issue recurred"},
)
assert reopen1.status_code == 200, reopen1.text
r1 = reopen1.json()
assert r1["call_status"] != "closed"
assert r1["restored_at"] is None
assert r1["closed_at"] is None
assert r1["downtime_is_ongoing"] is True
# Close again without /restore -> restored_at == closed_at again
close2 = client.post(
f"/api/complaints/{cid}/close",
headers=bio_headers,
json={"closure_remarks": "Replaced cable and verified"},
)
assert close2.status_code == 200, close2.text
c2 = close2.json()
assert c2["closed_at"] is not None
assert c2["restored_at"] == c2["closed_at"]
assert c2["downtime_is_ongoing"] is False
def test_sla_breach_alert_emitted_and_suppressed_when_restored(client, db):
from app.core.time_utils import effective_now_utc
from app.models import Notification
from app.services.alerts import run_alert_check
bio_headers = _auth_headers(client, "bio@poona.demo")
asset = db.query(Asset).first()
assert asset is not None
r_unrestored = client.post(
"/api/complaints",
headers=bio_headers,
json={
"asset_id": asset.id,
"priority": "critical",
"description": "SLA breach unrestored test",
},
)
r_restored = client.post(
"/api/complaints",
headers=bio_headers,
json={
"asset_id": asset.id,
"priority": "critical",
"description": "SLA breach already restored test",
},
)
assert r_unrestored.status_code == 201 and r_restored.status_code == 201
cid_unrestored = r_unrestored.json()["id"]
cid_restored = r_restored.json()["id"]
now = effective_now_utc(db)
past_5h = now - timedelta(hours=5)
try:
c_unrestored = db.query(Complaint).filter(Complaint.id == cid_unrestored).first()
c_restored = db.query(Complaint).filter(Complaint.id == cid_restored).first()
c_unrestored.registered_at = past_5h
c_unrestored.restored_at = None
c_restored.registered_at = past_5h
c_restored.restored_at = now - timedelta(hours=1)
db.commit()
run_alert_check(db)
db.commit()
sla_unrestored = (
db.query(Notification)
.filter(
Notification.type == "sla_breach",
Notification.entity_type == "complaint",
Notification.entity_id == cid_unrestored,
)
.all()
)
assert len(sla_unrestored) == 1
assert "SLA Breach: Open > 4h" in sla_unrestored[0].title
# Restored complaint past SLA should NOT emit sla_breach
sla_restored = (
db.query(Notification)
.filter(
Notification.type == "sla_breach",
Notification.entity_type == "complaint",
Notification.entity_id == cid_restored,
)
.all()
)
assert sla_restored == []
# 5h open is < default escalation_open_complaint_hours (24h), so critical_complaint stays silent
crit_unrestored = (
db.query(Notification)
.filter(
Notification.type == "critical_complaint",
Notification.entity_type == "complaint",
Notification.entity_id == cid_unrestored,
)
.all()
)
assert crit_unrestored == []
finally:
db.query(Notification).filter(
Notification.entity_type == "complaint",
Notification.entity_id.in_([cid_unrestored, cid_restored]),
).delete(synchronize_session=False)
db.commit()
for cid_cleanup in (cid_unrestored, cid_restored):
client.post(
f"/api/complaints/{cid_cleanup}/close",
headers=bio_headers,
json={"closure_remarks": "Cleanup after SLA alert test"},
)