phase-6: alerts engine, scheduler, notifications, calibration popup, and dashboard
This commit is contained in:
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user