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.scoping import resolve_department_scope 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) scope = resolve_department_scope(current_user) if scope.is_empty: cur_month_start = date(today.year, today.month, 1) months_seq = [add_months(cur_month_start, offset) for offset in range(-5, 1)] return DashboardSummaryOut( department_scope="Unassigned Department", effective_today=today, kpis=DashboardKPIs( total_assets=0, assets_under_repair=0, open_complaints=0, pm_due_this_month=0, calibrations_due=0, contracts_expiring=0, equipment_on_demo=0, ), complaints_by_status=[ ComplaintsByStatusItem(status="open", count=0), ComplaintsByStatusItem(status="in_progress", count=0), ComplaintsByStatusItem(status="closed", count=0), ], complaints_by_department=[], monthly_downtime_trend=[ MonthlyDowntimeItem( month=f"{m.year:04d}-{m.month:02d}", label=m.strftime("%b %Y"), downtime_minutes=0, downtime_hours=0.0, ) for m in months_seq ], pm_planned_vs_completed=[ MonthlyPMComparisonItem( month=f"{m.year:04d}-{m.month:02d}", label=m.strftime("%b %Y"), planned=0, completed=0, ) for m in months_seq ], needs_attention=[], recent_complaints=[], ) scoped_dept_id: int | None = scope.department_id dept_scope_name: str | None = None if scoped_dept_id is not None: 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_due_window_days", 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, )