phase-6: alerts engine, scheduler, notifications, calibration popup, and dashboard
This commit is contained in:
@@ -0,0 +1,375 @@
|
||||
from datetime import date, datetime, timezone
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.time_utils import effective_now_utc, effective_today, format_date
|
||||
from ..models import (
|
||||
Asset,
|
||||
CalibrationRecord,
|
||||
Complaint,
|
||||
Contract,
|
||||
DemoEquipment,
|
||||
InsurancePolicy,
|
||||
Notification,
|
||||
NotificationRead,
|
||||
PMRecord,
|
||||
PMSchedule,
|
||||
User,
|
||||
Warranty,
|
||||
)
|
||||
from .calculations import alert_state
|
||||
from .permissions import Role
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
|
||||
def _ensure_utc(dt: datetime) -> datetime:
|
||||
if dt.tzinfo is None:
|
||||
return dt.replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def notification_link_url(entity_type: str, entity_id: int) -> str:
|
||||
mapping = {
|
||||
"contract": "/contracts",
|
||||
"warranty": "/contracts?tab=warranties",
|
||||
"calibration_record": "/calibration",
|
||||
"pm_record": "/pm",
|
||||
"insurance": "/insurance",
|
||||
"demo_equipment": "/demo-equipment",
|
||||
"complaint": f"/complaints/{entity_id}",
|
||||
}
|
||||
return mapping.get(entity_type, "/")
|
||||
|
||||
|
||||
def _alert_settings(db: Session) -> dict[str, int]:
|
||||
return {
|
||||
"amc": int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"amc_cmc_lead_days",
|
||||
get_setting_value(db, "contract_expiry_alert_days", 30),
|
||||
)
|
||||
),
|
||||
"calibration": int(get_setting_value(db, "calibration_lead_days", 15)),
|
||||
"pm_in_house": int(get_setting_value(db, "pm_inhouse_lead_days", 15)),
|
||||
"pm_outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)),
|
||||
"insurance": int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"insurance_lead_days",
|
||||
get_setting_value(db, "insurance_expiry_alert_days", 30),
|
||||
)
|
||||
),
|
||||
"warranty": int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"warranty_lead_days",
|
||||
get_setting_value(db, "warranty_expiry_alert_days", 30),
|
||||
)
|
||||
),
|
||||
"red": int(get_setting_value(db, "red_threshold_days", 7)),
|
||||
"critical_hours": int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"critical_complaint_alert_hours",
|
||||
get_setting_value(db, "escalation_open_complaint_hours", 24),
|
||||
)
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _add_if_new(
|
||||
db: Session,
|
||||
existing_keys: set[str],
|
||||
*,
|
||||
dedupe_key: str,
|
||||
alert_type: str,
|
||||
severity: str,
|
||||
title: str,
|
||||
message: str,
|
||||
entity_type: str,
|
||||
entity_id: int,
|
||||
due_date: date | None,
|
||||
target_role: str,
|
||||
created_at: datetime,
|
||||
) -> int:
|
||||
if dedupe_key in existing_keys:
|
||||
return 0
|
||||
existing_keys.add(dedupe_key)
|
||||
db.add(
|
||||
Notification(
|
||||
type=alert_type,
|
||||
severity=severity,
|
||||
title=title,
|
||||
message=message,
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
due_date=due_date,
|
||||
target_role=target_role,
|
||||
target_user_id=None,
|
||||
dedupe_key=dedupe_key,
|
||||
created_at=created_at,
|
||||
)
|
||||
)
|
||||
return 1
|
||||
|
||||
|
||||
def run_alert_check(db: Session) -> dict[str, object]:
|
||||
today = effective_today(db)
|
||||
eff_now = effective_now_utc(db)
|
||||
cfg = _alert_settings(db)
|
||||
|
||||
existing_keys = {row[0] for row in db.query(Notification.dedupe_key).all()}
|
||||
created = 0
|
||||
|
||||
# 1. AMC / CMC / OTHER contracts expiring
|
||||
contracts = (
|
||||
db.query(Contract)
|
||||
.options(joinedload(Contract.asset))
|
||||
.filter(Contract.is_superseded.is_(False))
|
||||
.all()
|
||||
)
|
||||
for c in contracts:
|
||||
state = alert_state(c.end_date, today, cfg["amc"], cfg["red"])
|
||||
if state in ("yellow", "red"):
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"amc:{c.id}:{state}",
|
||||
alert_type="amc_expiry",
|
||||
severity=state,
|
||||
title=f"{c.contract_type} Contract {'Critical' if state == 'red' else 'Expiring'}: {c.asset.asset_code}",
|
||||
message=f"{c.contract_type} contract for {c.asset.name} ({c.asset.asset_code}) ends on {format_date(c.end_date)}.",
|
||||
entity_type="contract",
|
||||
entity_id=c.id,
|
||||
due_date=c.end_date,
|
||||
target_role="coordinator,management,biomedical,system_admin",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 2. Calibration due / overdue
|
||||
cal_records = (
|
||||
db.query(CalibrationRecord)
|
||||
.options(joinedload(CalibrationRecord.asset))
|
||||
.filter(or_(CalibrationRecord.status.is_(None), CalibrationRecord.status != "completed"))
|
||||
.all()
|
||||
)
|
||||
for r in cal_records:
|
||||
state = alert_state(r.due_date, today, cfg["calibration"], cfg["red"])
|
||||
if state in ("yellow", "red"):
|
||||
status_word = "Overdue" if r.due_date < today else "Due Soon"
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"cal:{r.id}:{state}",
|
||||
alert_type="calibration_due",
|
||||
severity=state,
|
||||
title=f"Calibration {status_word}: {r.asset.asset_code}",
|
||||
message=f"Calibration for {r.asset.name} ({r.asset.asset_code}) is due on {format_date(r.due_date)}.",
|
||||
entity_type="calibration_record",
|
||||
entity_id=r.id,
|
||||
due_date=r.due_date,
|
||||
target_role="biomedical,coordinator,management,system_admin",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 3. PM due / overdue
|
||||
pm_records = (
|
||||
db.query(PMRecord)
|
||||
.options(joinedload(PMRecord.asset), joinedload(PMRecord.schedule))
|
||||
.filter(or_(PMRecord.status.is_(None), ~PMRecord.status.in_(["completed", "rescheduled"])))
|
||||
.all()
|
||||
)
|
||||
for r in pm_records:
|
||||
mode = r.schedule.service_mode if r.schedule else "in_house"
|
||||
lead = cfg["pm_in_house"] if mode == "in_house" else cfg["pm_outsourced"]
|
||||
state = alert_state(r.planned_date, today, lead, cfg["red"])
|
||||
if state in ("yellow", "red"):
|
||||
status_word = "Overdue" if r.planned_date < today else "Due Soon"
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"pm:{r.id}:{state}",
|
||||
alert_type="pm_due",
|
||||
severity=state,
|
||||
title=f"PM {status_word}: {r.asset.asset_code}",
|
||||
message=f"Preventive maintenance ({mode.replace('_', '-')}) for {r.asset.name} ({r.asset.asset_code}) is planned for {format_date(r.planned_date)}.",
|
||||
entity_type="pm_record",
|
||||
entity_id=r.id,
|
||||
due_date=r.planned_date,
|
||||
target_role="biomedical,coordinator,management,system_admin",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 4. Insurance expiry
|
||||
policies = db.query(InsurancePolicy).options(joinedload(InsurancePolicy.asset)).all()
|
||||
for p in policies:
|
||||
state = alert_state(p.end_date, today, cfg["insurance"], cfg["red"])
|
||||
if state in ("yellow", "red"):
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"ins:{p.id}:{state}",
|
||||
alert_type="insurance_expiry",
|
||||
severity=state,
|
||||
title=f"Insurance {'Critical' if state == 'red' else 'Expiring'}: {p.asset.asset_code}",
|
||||
message=f"Policy {p.policy_no} for {p.asset.name} ({p.asset.asset_code}) ends on {format_date(p.end_date)}.",
|
||||
entity_type="insurance",
|
||||
entity_id=p.id,
|
||||
due_date=p.end_date,
|
||||
target_role="coordinator,management,system_admin",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 5. Warranty expiry
|
||||
warranties = db.query(Warranty).options(joinedload(Warranty.asset)).all()
|
||||
for w in warranties:
|
||||
state = alert_state(w.end_date, today, cfg["warranty"], cfg["red"])
|
||||
if state in ("yellow", "red"):
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"war:{w.id}:{state}",
|
||||
alert_type="warranty_expiry",
|
||||
severity=state,
|
||||
title=f"Warranty {'Critical' if state == 'red' else 'Expiring'}: {w.asset.asset_code}",
|
||||
message=f"Warranty for {w.asset.name} ({w.asset.asset_code}) ends on {format_date(w.end_date)}.",
|
||||
entity_type="warranty",
|
||||
entity_id=w.id,
|
||||
due_date=w.end_date,
|
||||
target_role="coordinator,biomedical,management,system_admin",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 6. Demo equipment overdue return
|
||||
demos = (
|
||||
db.query(DemoEquipment)
|
||||
.filter(DemoEquipment.actual_return_date.is_(None), DemoEquipment.expected_return_date < today)
|
||||
.all()
|
||||
)
|
||||
for d in demos:
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"demo:{d.id}:overdue",
|
||||
alert_type="demo_overdue",
|
||||
severity="red",
|
||||
title=f"Demo Return Overdue: {d.name}",
|
||||
message=f"Demo equipment '{d.name}' expected back on {format_date(d.expected_return_date)} has not been returned.",
|
||||
entity_type="demo_equipment",
|
||||
entity_id=d.id,
|
||||
due_date=d.expected_return_date,
|
||||
target_role="biomedical,coordinator,management,system_admin",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 7. Critical complaints open >= critical_complaint_alert_hours
|
||||
crit_complaints = (
|
||||
db.query(Complaint)
|
||||
.options(joinedload(Complaint.asset))
|
||||
.filter(Complaint.call_status != "closed", Complaint.priority == "critical")
|
||||
.all()
|
||||
)
|
||||
threshold_secs = cfg["critical_hours"] * 3600
|
||||
for c in crit_complaints:
|
||||
elapsed = (_ensure_utc(eff_now) - _ensure_utc(c.registered_at)).total_seconds()
|
||||
if elapsed >= threshold_secs:
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"cmp:{c.id}:critical_overdue",
|
||||
alert_type="critical_complaint",
|
||||
severity="red",
|
||||
title=f"Critical Complaint Open > {cfg['critical_hours']}h: {c.complaint_no}",
|
||||
message=f"Critical complaint {c.complaint_no} for {c.asset.name} ({c.asset.asset_code}) remains {c.call_status}.",
|
||||
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()}
|
||||
|
||||
|
||||
def _resolve_entity_departments(db: Session, notifications: list[Notification]) -> dict[tuple[str, int], int]:
|
||||
by_type: dict[str, list[int]] = {}
|
||||
for n in notifications:
|
||||
by_type.setdefault(n.entity_type, []).append(n.entity_id)
|
||||
|
||||
dept_map: dict[tuple[str, int], int] = {}
|
||||
|
||||
asset_model_map = {
|
||||
"contract": Contract,
|
||||
"warranty": Warranty,
|
||||
"insurance": InsurancePolicy,
|
||||
"calibration_record": CalibrationRecord,
|
||||
"pm_record": PMRecord,
|
||||
"complaint": Complaint,
|
||||
}
|
||||
for etype, model in asset_model_map.items():
|
||||
ids = list(set(by_type.get(etype, [])))
|
||||
if ids:
|
||||
rows = (
|
||||
db.query(model.id, Asset.department_id)
|
||||
.join(Asset, model.asset_id == Asset.id)
|
||||
.filter(model.id.in_(ids))
|
||||
.all()
|
||||
)
|
||||
for eid, dept_id in rows:
|
||||
dept_map[(etype, eid)] = dept_id
|
||||
|
||||
demo_ids = list(set(by_type.get("demo_equipment", [])))
|
||||
if demo_ids:
|
||||
rows = (
|
||||
db.query(DemoEquipment.id, DemoEquipment.department_id)
|
||||
.filter(DemoEquipment.id.in_(demo_ids))
|
||||
.all()
|
||||
)
|
||||
for eid, dept_id in rows:
|
||||
dept_map[("demo_equipment", eid)] = dept_id
|
||||
|
||||
return dept_map
|
||||
|
||||
|
||||
def get_visible_notifications_for_user(
|
||||
db: Session,
|
||||
user: User,
|
||||
) -> tuple[list[Notification], dict[int, datetime]]:
|
||||
"""Return (visible_notifications_ordered, read_at_by_notification_id) for the given user."""
|
||||
all_rows = (
|
||||
db.query(Notification)
|
||||
.order_by(Notification.created_at.desc(), Notification.id.desc())
|
||||
.all()
|
||||
)
|
||||
role_filtered: list[Notification] = []
|
||||
for n in all_rows:
|
||||
roles = {r.strip() for r in (n.target_role or "").split(",") if r.strip()}
|
||||
if user.role in roles or n.target_user_id == user.id:
|
||||
role_filtered.append(n)
|
||||
|
||||
if user.role == Role.department_user.value:
|
||||
dept_map = _resolve_entity_departments(db, role_filtered)
|
||||
visible = [
|
||||
n
|
||||
for n in role_filtered
|
||||
if dept_map.get((n.entity_type, n.entity_id)) == user.department_id
|
||||
]
|
||||
else:
|
||||
visible = role_filtered
|
||||
|
||||
visible_ids = [n.id for n in visible]
|
||||
read_map: dict[int, datetime] = {}
|
||||
if visible_ids:
|
||||
reads = (
|
||||
db.query(NotificationRead)
|
||||
.filter(
|
||||
NotificationRead.user_id == user.id,
|
||||
NotificationRead.notification_id.in_(visible_ids),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
read_map = {r.notification_id: r.read_at for r in reads}
|
||||
|
||||
return visible, read_map
|
||||
Reference in New Issue
Block a user