phase-6: alerts engine, scheduler, notifications, calibration popup, and dashboard

This commit is contained in:
Atharv1705
2026-11-12 14:39:22 +05:30
parent ba4777b182
commit aec1b6ad41
25 changed files with 2743 additions and 58 deletions
+11
View File
@@ -40,6 +40,17 @@ def effective_today(db=None) -> date:
return datetime.now(KOLKATA).date()
def effective_now_utc(db=None) -> datetime:
"""Returns current UTC datetime anchored to effective_today(db) in Asia/Kolkata when demo date is set."""
now_kol = datetime.now(KOLKATA)
today = effective_today(db)
if today == now_kol.date():
return now_kol.astimezone(timezone.utc)
return KOLKATA.localize(datetime.combine(today, now_kol.timetz().replace(tzinfo=None))).astimezone(
timezone.utc
)
def to_kolkata(dt: datetime) -> datetime:
return dt.astimezone(KOLKATA)
+40 -2
View File
@@ -1,10 +1,14 @@
import logging
import os
import sys
import traceback
from contextlib import asynccontextmanager
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from .core.db import SessionLocal, engine
from .core.db import SessionLocal, engine, get_scheduler_db
from .core.exceptions import CodedHTTPException, coded_http_exception_handler
from .models import Base
from .routers import (
@@ -14,16 +18,19 @@ from .routers import (
calibration,
complaints,
contracts,
dashboard,
demo_equipment,
health,
insurance,
masters,
notifications,
pm,
settings,
users,
visits,
warranties,
)
from .services.alerts import run_alert_check
from .services.settings_service import ensure_default_settings
logging.basicConfig(
@@ -33,6 +40,15 @@ logging.basicConfig(
logger = logging.getLogger("poona_ams")
def _scheduled_alert_job() -> None:
try:
with get_scheduler_db() as db:
res = run_alert_check(db)
logger.info("Scheduled alert check finished: %s", res)
except Exception:
logger.exception("Scheduled alert check failed.")
@asynccontextmanager
async def lifespan(app: FastAPI):
Base.metadata.create_all(bind=engine)
@@ -40,8 +56,28 @@ async def lifespan(app: FastAPI):
ensure_default_settings(db)
db.commit()
logger.info("Database tables created/verified.")
scheduler: BackgroundScheduler | None = None
is_testing = bool(os.environ.get("PYTEST_CURRENT_TEST") or "pytest" in sys.modules)
if not is_testing:
_scheduled_alert_job()
scheduler = BackgroundScheduler(timezone="Asia/Kolkata")
scheduler.add_job(
_scheduled_alert_job,
trigger=CronTrigger(hour=6, minute=0, timezone="Asia/Kolkata"),
id="daily_alert_check",
replace_existing=True,
)
scheduler.start()
logger.info("APScheduler daily alert check started (06:00 Asia/Kolkata).")
logger.info("Poona Hospital AMS started.")
yield
try:
yield
finally:
if scheduler is not None:
scheduler.shutdown(wait=False)
logger.info("APScheduler stopped.")
app = FastAPI(
@@ -86,3 +122,5 @@ app.include_router(warranties.router, prefix="/api")
app.include_router(insurance.router, prefix="/api")
app.include_router(demo_equipment.router, prefix="/api")
app.include_router(visits.router, prefix="/api")
app.include_router(notifications.router, prefix="/api")
app.include_router(dashboard.router, prefix="/api")
+4
View File
@@ -5,10 +5,12 @@ from . import (
calibration,
complaints,
contracts,
dashboard,
demo_equipment,
health,
insurance,
masters,
notifications,
pm,
settings,
users,
@@ -23,10 +25,12 @@ __all__ = [
"calibration",
"complaints",
"contracts",
"dashboard",
"demo_equipment",
"health",
"insurance",
"masters",
"notifications",
"pm",
"settings",
"users",
+286
View File
@@ -0,0 +1,286 @@
from datetime import date
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user
from ..core.time_utils import add_months, effective_now_utc, effective_today
from ..models import (
Asset,
CalibrationRecord,
Complaint,
Contract,
DemoEquipment,
Department,
PMRecord,
User,
)
from ..schemas.dashboard import (
ComplaintsByDepartmentItem,
ComplaintsByStatusItem,
DashboardKPIs,
DashboardSummaryOut,
MonthlyDowntimeItem,
MonthlyPMComparisonItem,
NeedsAttentionItem,
RecentComplaintItem,
)
from ..services.alerts import get_visible_notifications_for_user, notification_link_url
from ..services.calculations import (
clip_downtime_to_month,
compute_downtime_minutes,
compute_schedule_status,
coverage_status,
)
from ..services.permissions import Role
from ..services.settings_service import get_setting_value
router = APIRouter(prefix="/dashboard", tags=["dashboard"])
@router.get("/summary", response_model=DashboardSummaryOut)
def get_dashboard_summary(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
today = effective_today(db)
eff_now = effective_now_utc(db)
scoped_dept_id: int | None = None
dept_scope_name: str | None = None
if current_user.role == Role.department_user.value:
scoped_dept_id = current_user.department_id
dept_obj = db.query(Department).filter(Department.id == scoped_dept_id).first()
dept_scope_name = dept_obj.name if dept_obj else None
# Settings for dynamic calculations
cal_lead = int(get_setting_value(db, "calibration_lead_days", 15))
amc_lead = int(
get_setting_value(
db,
"amc_cmc_lead_days",
get_setting_value(db, "contract_expiry_alert_days", 30),
)
)
red_days = int(get_setting_value(db, "red_threshold_days", 7))
downtime_milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
# 1. Assets KPIs
asset_q = db.query(Asset)
if scoped_dept_id is not None:
asset_q = asset_q.filter(Asset.department_id == scoped_dept_id)
total_assets = asset_q.count()
assets_under_repair = asset_q.filter(Asset.status == "under_repair").count()
# 2. Complaints queries (used for KPIs, status chart, dept chart, downtime trend, recent list)
cmp_q = (
db.query(Complaint)
.join(Asset, Complaint.asset_id == Asset.id)
.options(joinedload(Complaint.asset).joinedload(Asset.department))
)
if scoped_dept_id is not None:
cmp_q = cmp_q.filter(Asset.department_id == scoped_dept_id)
complaints = cmp_q.order_by(Complaint.registered_at.desc(), Complaint.id.desc()).all()
open_cnt = sum(1 for c in complaints if c.call_status == "open")
in_prog_cnt = sum(1 for c in complaints if c.call_status == "in_progress")
closed_cnt = sum(1 for c in complaints if c.call_status == "closed")
open_complaints_kpi = open_cnt + in_prog_cnt
complaints_by_status = [
ComplaintsByStatusItem(status="open", count=open_cnt),
ComplaintsByStatusItem(status="in_progress", count=in_prog_cnt),
ComplaintsByStatusItem(status="closed", count=closed_cnt),
]
dept_q = db.query(Department).filter(Department.is_active.is_(True))
if scoped_dept_id is not None:
dept_q = dept_q.filter(Department.id == scoped_dept_id)
departments = dept_q.order_by(Department.name.asc()).all()
dept_crit_counts: dict[str, dict[str, int]] = {
d.name: {"critical": 0, "non_critical": 0} for d in departments
}
for c in complaints:
dname = c.asset.department.name if (c.asset and c.asset.department) else "Unknown"
if dname not in dept_crit_counts:
dept_crit_counts[dname] = {"critical": 0, "non_critical": 0}
if c.priority == "critical":
dept_crit_counts[dname]["critical"] += 1
else:
dept_crit_counts[dname]["non_critical"] += 1
complaints_by_department = [
ComplaintsByDepartmentItem(
department=dname,
critical=vals["critical"],
non_critical=vals["non_critical"],
)
for dname, vals in dept_crit_counts.items()
]
# 3. PM records (KPI + 6-month chart)
pm_q = db.query(PMRecord).join(Asset, PMRecord.asset_id == Asset.id)
if scoped_dept_id is not None:
pm_q = pm_q.filter(Asset.department_id == scoped_dept_id)
pm_records = pm_q.all()
pm_due_this_month = 0
for r in pm_records:
if r.status in ("completed", "rescheduled"):
continue
if r.planned_date < today or (
r.planned_date.year == today.year and r.planned_date.month == today.month
):
pm_due_this_month += 1
# 4. Calibrations due KPI
cal_q = db.query(CalibrationRecord).join(Asset, CalibrationRecord.asset_id == Asset.id)
if scoped_dept_id is not None:
cal_q = cal_q.filter(Asset.department_id == scoped_dept_id)
cal_records = cal_q.all()
calibrations_due = 0
for r in cal_records:
st, _ = compute_schedule_status(r.due_date, r.status, today, cal_lead, red_days)
if st in ("due", "overdue"):
calibrations_due += 1
# 5. Contracts expiring KPI
con_q = (
db.query(Contract)
.join(Asset, Contract.asset_id == Asset.id)
.filter(Contract.is_superseded.is_(False))
)
if scoped_dept_id is not None:
con_q = con_q.filter(Asset.department_id == scoped_dept_id)
contracts = con_q.all()
contracts_expiring = 0
for c in contracts:
st, _ = coverage_status(c.start_date, c.end_date, today, amc_lead, red_days)
if st in ("expiring", "expired"):
contracts_expiring += 1
# 6. Equipment on demo KPI
demo_q = db.query(DemoEquipment).filter(DemoEquipment.actual_return_date.is_(None))
if scoped_dept_id is not None:
demo_q = demo_q.filter(DemoEquipment.department_id == scoped_dept_id)
equipment_on_demo = demo_q.count()
# 7. Last 6 calendar months (oldest -> current month)
cur_month_start = date(today.year, today.month, 1)
months_seq = [add_months(cur_month_start, offset) for offset in range(-5, 1)]
monthly_downtime_trend: list[MonthlyDowntimeItem] = []
pm_planned_vs_completed: list[MonthlyPMComparisonItem] = []
for m_start in months_seq:
y, m = m_start.year, m_start.month
m_key = f"{y:04d}-{m:02d}"
m_label = m_start.strftime("%b %Y")
total_mins = 0
for c in complaints:
end_map = {
"attended_at": c.attended_at,
"restored_at": c.restored_at,
"closed_at": c.closed_at,
}
end_dt = end_map.get(downtime_milestone) or eff_now
mins, _ = clip_downtime_to_month(c.registered_at, end_dt, y, m)
total_mins += mins
monthly_downtime_trend.append(
MonthlyDowntimeItem(
month=m_key,
label=m_label,
downtime_minutes=total_mins,
downtime_hours=round(total_mins / 60.0, 2),
)
)
planned_cnt = sum(
1 for r in pm_records if r.planned_date.year == y and r.planned_date.month == m
)
completed_cnt = sum(
1
for r in pm_records
if r.status == "completed"
and (r.completed_date or r.planned_date).year == y
and (r.completed_date or r.planned_date).month == m
)
pm_planned_vs_completed.append(
MonthlyPMComparisonItem(
month=m_key,
label=m_label,
planned=planned_cnt,
completed=completed_cnt,
)
)
# 8. Needs attention (top 15 unread red notifications visible to user)
visible_notifs, read_map = get_visible_notifications_for_user(db, current_user)
red_unread = [
n for n in visible_notifs if n.severity == "red" and n.id not in read_map
]
red_unread.sort(key=lambda n: (n.due_date or today, -n.id))
needs_attention = [
NeedsAttentionItem(
id=n.id,
type=n.type,
severity=n.severity,
title=n.title,
message=n.message,
entity_type=n.entity_type,
entity_id=n.entity_id,
due_date=n.due_date,
link_url=notification_link_url(n.entity_type, n.entity_id),
)
for n in red_unread[:15]
]
# 9. Recent complaints (latest 8)
recent_complaints: list[RecentComplaintItem] = []
for c in complaints[:8]:
dt_mins, is_ongoing = compute_downtime_minutes(
c.registered_at,
c.attended_at,
c.restored_at,
c.closed_at,
milestone=downtime_milestone,
now_utc=eff_now,
)
recent_complaints.append(
RecentComplaintItem(
id=c.id,
complaint_no=c.complaint_no,
asset_code=c.asset.asset_code,
asset_name=c.asset.name,
department_name=c.asset.department.name if c.asset.department else None,
priority=c.priority,
call_status=c.call_status,
registered_at=c.registered_at,
downtime_minutes=dt_mins,
downtime_is_ongoing=is_ongoing,
)
)
return DashboardSummaryOut(
department_scope=dept_scope_name,
effective_today=today,
kpis=DashboardKPIs(
total_assets=total_assets,
assets_under_repair=assets_under_repair,
open_complaints=open_complaints_kpi,
pm_due_this_month=pm_due_this_month,
calibrations_due=calibrations_due,
contracts_expiring=contracts_expiring,
equipment_on_demo=equipment_on_demo,
),
complaints_by_status=complaints_by_status,
complaints_by_department=complaints_by_department,
monthly_downtime_trend=monthly_downtime_trend,
pm_planned_vs_completed=pm_planned_vs_completed,
needs_attention=needs_attention,
recent_complaints=recent_complaints,
)
+150
View File
@@ -0,0 +1,150 @@
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from ..core.db import get_db
from ..core.deps import get_current_user, require_roles
from ..core.time_utils import utc_now
from ..models import Notification, NotificationRead, User
from ..schemas.notifications import (
AlertRunOut,
NotificationListOut,
NotificationOut,
NotificationReadAllOut,
NotificationReadOut,
)
from ..services.alerts import (
get_visible_notifications_for_user,
notification_link_url,
run_alert_check,
)
from ..services.permissions import Role
router = APIRouter(tags=["notifications"])
@router.post("/alerts/run", response_model=AlertRunOut)
def trigger_alert_run(
db: Session = Depends(get_db),
_: User = Depends(require_roles(Role.system_admin)),
):
result = run_alert_check(db)
db.commit()
return AlertRunOut(**result)
@router.get("/notifications", response_model=NotificationListOut)
def list_notifications(
notif_type: Optional[str] = Query(None, alias="type"),
severity: Optional[str] = None,
unread_only: bool = False,
limit: Optional[int] = Query(None, ge=1, le=200),
page: int = Query(1, ge=1),
page_size: int = Query(50, ge=1, le=200),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
visible, read_map = get_visible_notifications_for_user(db, current_user)
unread_count = sum(1 for n in visible if n.id not in read_map)
unread_calibration_count = sum(
1 for n in visible if n.id not in read_map and n.type == "calibration_due"
)
filtered: list[Notification] = []
for n in visible:
is_read = n.id in read_map
if notif_type and n.type != notif_type:
continue
if severity and n.severity != severity:
continue
if unread_only and is_read:
continue
filtered.append(n)
total = len(filtered)
eff_size = limit if limit is not None else page_size
start = (page - 1) * eff_size
page_items = filtered[start : start + eff_size]
items_out = [
NotificationOut(
id=n.id,
type=n.type,
severity=n.severity,
title=n.title,
message=n.message,
entity_type=n.entity_type,
entity_id=n.entity_id,
due_date=n.due_date,
link_url=notification_link_url(n.entity_type, n.entity_id),
is_read=n.id in read_map,
read_at=read_map.get(n.id),
created_at=n.created_at,
)
for n in page_items
]
return NotificationListOut(
items=items_out,
total=total,
unread_count=unread_count,
unread_calibration_count=unread_calibration_count,
)
@router.post("/notifications/read-all", response_model=NotificationReadAllOut)
def mark_all_notifications_read(
notif_type: Optional[str] = Query(None, alias="type"),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
visible, read_map = get_visible_notifications_for_user(db, current_user)
now = utc_now()
marked = 0
for n in visible:
if n.id in read_map:
continue
if notif_type and n.type != notif_type:
continue
db.add(
NotificationRead(
notification_id=n.id,
user_id=current_user.id,
read_at=now,
)
)
marked += 1
if marked:
db.commit()
return NotificationReadAllOut(marked_read=marked)
@router.post("/notifications/{notification_id}/read", response_model=NotificationReadOut)
def mark_notification_read(
notification_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
notif = db.query(Notification).filter(Notification.id == notification_id).first()
if notif is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Notification not found.")
visible, read_map = get_visible_notifications_for_user(db, current_user)
if all(n.id != notification_id for n in visible):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access denied for this notification.",
)
if notification_id not in read_map:
db.add(
NotificationRead(
notification_id=notification_id,
user_id=current_user.id,
read_at=utc_now(),
)
)
db.commit()
return NotificationReadOut(notification_id=notification_id, is_read=True)
+17
View File
@@ -45,6 +45,16 @@ from .contracts import (
ContractRenewOut,
ContractUpdate,
)
from .dashboard import (
ComplaintsByDepartmentItem,
ComplaintsByStatusItem,
DashboardKPIs,
DashboardSummaryOut,
MonthlyDowntimeItem,
MonthlyPMComparisonItem,
NeedsAttentionItem,
RecentComplaintItem,
)
from .demo_equipment import (
DemoEquipmentCreate,
DemoEquipmentListOut,
@@ -72,6 +82,13 @@ from .masters import (
VendorOut,
VendorUpdate,
)
from .notifications import (
AlertRunOut,
NotificationListOut,
NotificationOut,
NotificationReadAllOut,
NotificationReadOut,
)
from .pm import (
PMRecordCompleteIn,
PMRecordCompleteOut,
+75
View File
@@ -0,0 +1,75 @@
from datetime import date, datetime
from typing import Optional
from pydantic import BaseModel
class DashboardKPIs(BaseModel):
total_assets: int
assets_under_repair: int
open_complaints: int
pm_due_this_month: int
calibrations_due: int
contracts_expiring: int
equipment_on_demo: int
class ComplaintsByStatusItem(BaseModel):
status: str
count: int
class ComplaintsByDepartmentItem(BaseModel):
department: str
critical: int
non_critical: int
class MonthlyDowntimeItem(BaseModel):
month: str
label: str
downtime_minutes: int
downtime_hours: float
class MonthlyPMComparisonItem(BaseModel):
month: str
label: str
planned: int
completed: int
class NeedsAttentionItem(BaseModel):
id: int
type: str
severity: str
title: str
message: str
entity_type: str
entity_id: int
due_date: Optional[date] = None
link_url: str
class RecentComplaintItem(BaseModel):
id: int
complaint_no: str
asset_code: str
asset_name: str
department_name: Optional[str] = None
priority: str
call_status: str
registered_at: datetime
downtime_minutes: int
downtime_is_ongoing: bool
class DashboardSummaryOut(BaseModel):
department_scope: Optional[str] = None
effective_today: date
kpis: DashboardKPIs
complaints_by_status: list[ComplaintsByStatusItem]
complaints_by_department: list[ComplaintsByDepartmentItem]
monthly_downtime_trend: list[MonthlyDowntimeItem]
pm_planned_vs_completed: list[MonthlyPMComparisonItem]
needs_attention: list[NeedsAttentionItem]
recent_complaints: list[RecentComplaintItem]
+42
View File
@@ -0,0 +1,42 @@
from datetime import date, datetime
from typing import Optional
from pydantic import BaseModel, ConfigDict
class AlertRunOut(BaseModel):
created: int
evaluated_today: str
class NotificationOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
type: str
severity: str
title: str
message: str
entity_type: str
entity_id: int
due_date: Optional[date] = None
link_url: str
is_read: bool
read_at: Optional[datetime] = None
created_at: datetime
class NotificationListOut(BaseModel):
items: list[NotificationOut]
total: int
unread_count: int
unread_calibration_count: int
class NotificationReadOut(BaseModel):
status: str = "ok"
notification_id: int
is_read: bool = True
class NotificationReadAllOut(BaseModel):
marked_read: int
+4
View File
@@ -31,6 +31,7 @@ from ..models import (
Vendor,
Warranty,
)
from ..services.alerts import run_alert_check
from ..services.settings_service import ensure_default_settings
@@ -775,6 +776,8 @@ def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]
visit.complaints.append(complaints[3])
db.add(visit)
db.flush()
alert_res = run_alert_check(db)
db.commit()
return {
"departments": len(departments),
@@ -791,6 +794,7 @@ def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]
"complaints": len(complaints),
"demo_equipment": len(demo_items),
"department_visits": 12,
"notifications": int(alert_res["created"]),
}
+375
View File
@@ -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
@@ -0,0 +1,148 @@
from datetime import timedelta
import pytest
from app.core.time_utils import effective_today
from app.models import Asset, Complaint, Department, Notification
from app.seed.seed import seed_database
from app.services.alerts import run_alert_check
@pytest.fixture(scope="module", autouse=True)
def seeded_phase6_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("phase6_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_alert_check_dedupe_and_seed_notifications(db):
# seed_database already ran run_alert_check -> notifications exist in DB
initial_count = db.query(Notification).count()
assert initial_count > 0
# Running run_alert_check again immediately creates 0 duplicates
res2 = run_alert_check(db)
db.commit()
assert res2["created"] == 0
assert db.query(Notification).count() == initial_count
def test_demo_clock_alert_run_and_admin_only_permission(client, db):
admin_headers = _auth_headers(client, "admin@poona.demo")
bio_headers = _auth_headers(client, "bio@poona.demo")
dept_headers = _auth_headers(client, "dept@poona.demo")
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
coord_headers = _auth_headers(client, "coord@poona.demo")
# Non-admins get 403 on POST /api/alerts/run
for h in (bio_headers, dept_headers, mgmt_headers, coord_headers):
assert client.post("/api/alerts/run", headers=h).status_code == 403
base_today = effective_today(db)
future_date = base_today + timedelta(days=20)
try:
set_res = client.post(
"/api/settings/demo-date",
headers=admin_headers,
json={"demo_as_of_date": str(future_date)},
)
assert set_res.status_code == 200
# First run at +20 days creates new notifications for newly-entered windows
run1 = client.post("/api/alerts/run", headers=admin_headers)
assert run1.status_code == 200, run1.text
data1 = run1.json()
assert data1["evaluated_today"] == str(future_date)
assert data1["created"] > 0
# Second run at same +20 days creates 0 (dedupe)
run2 = client.post("/api/alerts/run", headers=admin_headers)
assert run2.status_code == 200
assert run2.json()["created"] == 0
finally:
client.post(
"/api/settings/demo-date",
headers=admin_headers,
json={"demo_as_of_date": None},
)
def test_per_user_read_state_and_department_scoping(client, db):
admin_headers = _auth_headers(client, "admin@poona.demo")
bio_headers = _auth_headers(client, "bio@poona.demo")
dept_headers = _auth_headers(client, "dept@poona.demo")
admin_list_before = client.get("/api/notifications?limit=100", headers=admin_headers).json()
bio_list_before = client.get("/api/notifications?limit=100", headers=bio_headers).json()
assert admin_list_before["unread_count"] > 0
assert bio_list_before["unread_count"] > 0
# Pick a calibration_due notification visible to both admin and bio
cal_items = [n for n in admin_list_before["items"] if n["type"] == "calibration_due"]
assert len(cal_items) > 0
target_id = cal_items[0]["id"]
assert cal_items[0]["link_url"] == "/calibration"
# Admin marks single notification as read -> bio still sees it unread
mark_res = client.post(f"/api/notifications/{target_id}/read", headers=admin_headers)
assert mark_res.status_code == 200
assert mark_res.json()["is_read"] is True
admin_after_one = client.get("/api/notifications?limit=100", headers=admin_headers).json()
bio_after_one = client.get("/api/notifications?limit=100", headers=bio_headers).json()
assert admin_after_one["unread_count"] == admin_list_before["unread_count"] - 1
assert bio_after_one["unread_count"] == bio_list_before["unread_count"]
# Admin marks all calibration_due notifications read -> unread_calibration_count becomes 0 for admin, unchanged for bio
mark_cal = client.post("/api/notifications/read-all?type=calibration_due", headers=admin_headers)
assert mark_cal.status_code == 200
admin_after_cal = client.get("/api/notifications?limit=100", headers=admin_headers).json()
bio_after_cal = client.get("/api/notifications?limit=100", headers=bio_headers).json()
assert admin_after_cal["unread_calibration_count"] == 0
assert bio_after_cal["unread_calibration_count"] > 0
# department_user only sees critical_complaint alerts for their own department (ICU)
icu = db.query(Department).filter(Department.code == "ICU").first()
dept_notifs = client.get("/api/notifications?limit=100", headers=dept_headers).json()
for n in dept_notifs["items"]:
assert n["entity_type"] == "complaint"
assert n["link_url"] == f"/complaints/{n['entity_id']}"
comp = db.query(Complaint).filter(Complaint.id == n["entity_id"]).first()
assert comp.asset.department_id == icu.id
def test_dashboard_summary_role_scoping_and_charts(client, db):
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
dept_headers = _auth_headers(client, "dept@poona.demo")
icu = db.query(Department).filter(Department.code == "ICU").first()
icu_asset_count = db.query(Asset).filter(Asset.department_id == icu.id).count()
total_asset_count = db.query(Asset).count()
mgmt_res = client.get("/api/dashboard/summary", headers=mgmt_headers)
assert mgmt_res.status_code == 200, mgmt_res.text
mgmt = mgmt_res.json()
assert mgmt["department_scope"] is None
assert mgmt["kpis"]["total_assets"] == total_asset_count
assert len(mgmt["monthly_downtime_trend"]) == 6
assert len(mgmt["pm_planned_vs_completed"]) == 6
assert len(mgmt["complaints_by_status"]) == 3
assert len(mgmt["complaints_by_department"]) >= 2
assert len(mgmt["recent_complaints"]) <= 8
dept_res = client.get("/api/dashboard/summary", headers=dept_headers)
assert dept_res.status_code == 200, dept_res.text
dept = dept_res.json()
assert dept["department_scope"] == icu.name
assert dept["kpis"]["total_assets"] == icu_asset_count
assert dept["kpis"]["total_assets"] < mgmt["kpis"]["total_assets"]
assert len(dept["monthly_downtime_trend"]) == 6
assert len(dept["pm_planned_vs_completed"]) == 6
assert [d["department"] for d in dept["complaints_by_department"]] == [icu.name]
assert all(rc["department_name"] == icu.name for rc in dept["recent_complaints"])