diff --git a/README.md b/README.md index 8c9b539..0758e69 100644 --- a/README.md +++ b/README.md @@ -58,11 +58,11 @@ cd backend | mgmt@poona.demo | Demo@123 | Management | | coord@poona.demo | Demo@123 | Coordinator | -## What exists now (Phase 5) +## What exists now (Phase 6) - Complete SQLAlchemy 19-table data model across masters, assets, maintenance, complaints, operations, and system modules - JWT authentication (`/api/auth/login`, `/api/auth/me`), RBAC permission matrix for 5 roles, and Quick Demo Login - Admin Master Lists CRUD (`/masters`: Departments, Locations, Categories, Vendors, Users) -- Typed System Settings (`/settings`) and TopBar "As of Date" Demo Clock (`POST /api/settings/demo-date`) +- Typed System Settings (`/settings`) and TopBar "As of Date" Demo Clock (`POST /api/settings/demo-date`) + Admin `"Run alert check now"` (`POST /api/alerts/run`) - Asset Register (`/assets` & `/assets/:id`): full CRUD with duplicate asset code check (`409`), department scoping, coordinator field-level edit restrictions, 8-tab Asset Detail Overview, and audit logging - Breakdown & Complaint Register (`/complaints` & `/complaints/:id`): sequential complaint numbering, `AssetPicker` raise modal with multi-file attachments, response time & ongoing/milestone downtime calculations, assign/attend/restore/close/reopen workflow with asset status sync, event timeline, admin timestamp correction, and role-enforced technical/CE/spares section (`FORBIDDEN_TECHNICAL_FIELDS` 403 + read-only lock banner) - Preventive Maintenance (`/pm`): in-house & outsourced PM schedules (`/api/pm/schedules`), dynamic read-time `upcoming`/`due`/`overdue`/`completed`/`rescheduled` status & severity evaluation against `effective_today()`, KPI summary strip, Table View & 7-column Mon–Sun Month Calendar View, Complete (auto-advancing next cycle via `add_months`) and Reschedule workflows, plus Asset Detail PM tab actions @@ -71,6 +71,8 @@ cd backend - Asset Insurance (`/insurance`) & Slide-Over `InsuranceDrawer`: insurance policy register with INR coverage display, expiry alerts, policy attachments (`insurance`), and `"View Insurance"` drawer accessible from `AssetDetailPage`, `AssetPicker`, and `ComplaintDetailPage` - Demo Equipment (`/demo-equipment`): trial equipment register with dynamic `on_demo`/`overdue_return`/`returned` status relative to `effective_today()`, return logging (`POST /api/demo-equipment/:id/return`), and `demo_equipment` attachments - Department Visits (`/visits`): biomedical/admin round logs with management read access (403 for `department_user` and `coordinator`), department-filtered multi-asset checklist, observations, and complaint creation/linking (`POST /api/visits/:id/link-complaint`) +- Alert Engine, Scheduler & Notifications (`/notifications` + TopBar Bell & Calibration Login Pop-up): APScheduler `06:00 Asia/Kolkata` daily job using short-lived `get_scheduler_db()`, deduplicated 7-type alerts (`amc_expiry`, `calibration_due`, `pm_due`, `insurance_expiry`, `warranty_expiry`, `demo_overdue`, `critical_complaint`) evaluated against `effective_today()`/`effective_now_utc()`, per-user `NotificationRead` state with `department_user` entity-department filtering, 60s bell polling with live toast alerts, and once-per-login `CalibrationReminderModal` +- Hospital Operations Dashboard (`/`): role-aware `department_scope` banner, 7 clickable KPI cards, 4 Recharts visualizations (Complaints by Status, Complaints by Department, 6-month `clip_downtime_to_month` Downtime Trend, PM Planned vs Completed), `"Needs Attention"` red alerts panel, and `"Recent Complaints"` table - Reusable `AssetPicker` (`/api/assets/lookup`) with warranty/condemned status badges - Secure Document Attachments (`/api/attachments`: JPG/PNG/PDF validation with magic-byte check, 10 MB limit, authenticated preview/download, role-based upload/delete) - Idempotent deterministic seed script (`python -m app.seed.seed`) populating realistic hospital demo data diff --git a/backend/app/core/time_utils.py b/backend/app/core/time_utils.py index 88655cb..e739442 100644 --- a/backend/app/core/time_utils.py +++ b/backend/app/core/time_utils.py @@ -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) diff --git a/backend/app/main.py b/backend/app/main.py index a8c5591..740a7e2 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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") diff --git a/backend/app/routers/__init__.py b/backend/app/routers/__init__.py index 965d05f..efcb2ca 100644 --- a/backend/app/routers/__init__.py +++ b/backend/app/routers/__init__.py @@ -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", diff --git a/backend/app/routers/dashboard.py b/backend/app/routers/dashboard.py new file mode 100644 index 0000000..acf0339 --- /dev/null +++ b/backend/app/routers/dashboard.py @@ -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, + ) diff --git a/backend/app/routers/notifications.py b/backend/app/routers/notifications.py new file mode 100644 index 0000000..0867e68 --- /dev/null +++ b/backend/app/routers/notifications.py @@ -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) diff --git a/backend/app/schemas/__init__.py b/backend/app/schemas/__init__.py index d3a094f..9993c7b 100644 --- a/backend/app/schemas/__init__.py +++ b/backend/app/schemas/__init__.py @@ -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, diff --git a/backend/app/schemas/dashboard.py b/backend/app/schemas/dashboard.py new file mode 100644 index 0000000..1e4a344 --- /dev/null +++ b/backend/app/schemas/dashboard.py @@ -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] diff --git a/backend/app/schemas/notifications.py b/backend/app/schemas/notifications.py new file mode 100644 index 0000000..789a7d7 --- /dev/null +++ b/backend/app/schemas/notifications.py @@ -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 diff --git a/backend/app/seed/seed.py b/backend/app/seed/seed.py index 3cb6000..9ebef2d 100644 --- a/backend/app/seed/seed.py +++ b/backend/app/seed/seed.py @@ -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"]), } diff --git a/backend/app/services/alerts.py b/backend/app/services/alerts.py new file mode 100644 index 0000000..b775e7e --- /dev/null +++ b/backend/app/services/alerts.py @@ -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 diff --git a/backend/tests/test_notifications_and_dashboard.py b/backend/tests/test_notifications_and_dashboard.py new file mode 100644 index 0000000..a6b8261 --- /dev/null +++ b/backend/tests/test_notifications_and_dashboard.py @@ -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"]) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 13693f7..146f4f7 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -17,11 +17,10 @@ import { ContractsPage } from "@/pages/ContractsPage"; import { InsurancePage } from "@/pages/InsurancePage"; import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage"; import { VisitsPage } from "@/pages/VisitsPage"; -import { - DashboardPage, - ReportsPage, - NotificationsPage, -} from "@/pages/stubs"; +import { DashboardPage } from "@/pages/DashboardPage"; +import { NotificationsPage } from "@/pages/NotificationsPage"; +import { ReportsPage } from "@/pages/stubs"; +import { ToastProvider } from "@/components/ToastProvider"; import { useAuthStore } from "@/hooks/useAuth"; import { can, type Capability } from "@/lib/permissions"; @@ -127,9 +126,11 @@ function AppRoutes() { export default function App() { return ( - - - + + + + + ); } diff --git a/frontend/src/api/dashboard.ts b/frontend/src/api/dashboard.ts new file mode 100644 index 0000000..4311804 --- /dev/null +++ b/frontend/src/api/dashboard.ts @@ -0,0 +1,77 @@ +import { api } from "./client"; + +export interface DashboardKPIs { + total_assets: number; + assets_under_repair: number; + open_complaints: number; + pm_due_this_month: number; + calibrations_due: number; + contracts_expiring: number; + equipment_on_demo: number; +} + +export interface StatusCountItem { + status: string; + count: number; +} + +export interface DeptComplaintCountItem { + department: string; + critical: number; + non_critical: number; +} + +export interface MonthlyDowntimePoint { + month: string; + label: string; + downtime_minutes: number; + downtime_hours: number; +} + +export interface MonthlyPMPoint { + month: string; + label: string; + planned: number; + completed: number; +} + +export interface NeedsAttentionItem { + id: number; + type: string; + severity: string; + title: string; + message: string; + entity_type: string | null; + entity_id: number | null; + due_date: string | null; + link_url: string; +} + +export interface RecentComplaintItem { + id: number; + complaint_no: string; + asset_code: string; + asset_name: string; + department_name: string | null; + priority: string; + call_status: string; + registered_at: string; + downtime_minutes: number; + downtime_is_ongoing: boolean; +} + +export interface DashboardSummary { + department_scope: string | null; + effective_today: string; + kpis: DashboardKPIs; + complaints_by_status: StatusCountItem[]; + complaints_by_department: DeptComplaintCountItem[]; + monthly_downtime_trend: MonthlyDowntimePoint[]; + pm_planned_vs_completed: MonthlyPMPoint[]; + needs_attention: NeedsAttentionItem[]; + recent_complaints: RecentComplaintItem[]; +} + +export const dashboardApi = { + summary: () => api.get("/dashboard/summary"), +}; diff --git a/frontend/src/api/notifications.ts b/frontend/src/api/notifications.ts new file mode 100644 index 0000000..7abec44 --- /dev/null +++ b/frontend/src/api/notifications.ts @@ -0,0 +1,67 @@ +import { api } from "./client"; + +export type NotificationSeverity = "info" | "yellow" | "red"; + +export type NotificationType = + | "amc_expiry" + | "calibration_due" + | "pm_due" + | "insurance_expiry" + | "warranty_expiry" + | "demo_overdue" + | "critical_complaint"; + +export interface NotificationItem { + id: number; + type: NotificationType | string; + severity: NotificationSeverity | string; + title: string; + message: string; + entity_type: string | null; + entity_id: number | null; + due_date: string | null; + created_at: string; + is_read: boolean; + read_at: string | null; + link_url: string; +} + +export interface NotificationListResponse { + items: NotificationItem[]; + total: number; + unread_count: number; + unread_calibration_count: number; +} + +export interface NotificationListParams { + type?: string; + severity?: string; + unread_only?: boolean; + limit?: number; + page?: number; + page_size?: number; +} + +export const notificationsApi = { + list: (params: NotificationListParams = {}) => { + const sp = new URLSearchParams(); + if (params.type) sp.set("type", params.type); + if (params.severity) sp.set("severity", params.severity); + if (params.unread_only) sp.set("unread_only", "true"); + if (params.limit != null) sp.set("limit", String(params.limit)); + if (params.page != null) sp.set("page", String(params.page)); + if (params.page_size != null) sp.set("page_size", String(params.page_size)); + const qs = sp.toString(); + return api.get(`/notifications${qs ? `?${qs}` : ""}`); + }, + markRead: (id: number) => + api.post<{ status: string; id: number }>(`/notifications/${id}/read`), + markAllRead: (type?: string) => { + const qs = type ? `?type=${encodeURIComponent(type)}` : ""; + return api.post<{ status: string; marked_count?: number }>( + `/notifications/read-all${qs}` + ); + }, + runAlertsNow: () => + api.post<{ created: number; evaluated_today: string }>("/alerts/run"), +}; diff --git a/frontend/src/components/CalibrationReminderModal.tsx b/frontend/src/components/CalibrationReminderModal.tsx new file mode 100644 index 0000000..7808f58 --- /dev/null +++ b/frontend/src/components/CalibrationReminderModal.tsx @@ -0,0 +1,159 @@ +import { useState, useEffect, useRef } from "react"; +import { useNavigate } from "react-router-dom"; +import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; +import { AlertTriangle, Clock, CheckCircle2, ExternalLink } from "lucide-react"; +import { notificationsApi } from "@/api/notifications"; +import { useAuthStore } from "@/hooks/useAuth"; +import { formatDate } from "@/lib/format"; +import { Modal } from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { toast } from "@/components/ToastProvider"; + +export function CalibrationReminderModal() { + const navigate = useNavigate(); + const qc = useQueryClient(); + const { user, token } = useAuthStore(); + const [open, setOpen] = useState(false); + const promptedTokensRef = useRef>(new Set()); + + const sessionKey = token ? `cal_popup_shown:${token.slice(-16)}` : null; + + const calNotifsQuery = useQuery({ + queryKey: ["notifications", "calibration-login-popup", user?.id], + queryFn: () => + notificationsApi.list({ + type: "calibration_due", + unread_only: true, + limit: 25, + }), + enabled: Boolean(user && token), + }); + + const items = calNotifsQuery.data?.items ?? []; + + useEffect(() => { + if (!token || !user || items.length === 0) return; + const alreadyShownInRef = promptedTokensRef.current.has(token); + let alreadyShownInSession = false; + try { + alreadyShownInSession = Boolean( + sessionKey && sessionStorage.getItem(sessionKey) + ); + } catch { + alreadyShownInSession = false; + } + + if (!alreadyShownInRef && !alreadyShownInSession) { + promptedTokensRef.current.add(token); + try { + if (sessionKey) sessionStorage.setItem(sessionKey, "1"); + } catch { + // ignore storage errors + } + setOpen(true); + } + }, [token, user, items.length, sessionKey]); + + const acknowledgeMutation = useMutation({ + mutationFn: () => notificationsApi.markAllRead("calibration_due"), + onSuccess: async () => { + await qc.invalidateQueries({ queryKey: ["notifications"] }); + await qc.invalidateQueries({ queryKey: ["dashboard"] }); + toast.success("Calibration reminders acknowledged"); + setOpen(false); + }, + onError: () => { + toast.error("Failed to acknowledge calibration reminders"); + }, + }); + + if (!open || items.length === 0) return null; + + return ( + !o && setOpen(false)} + title={`Calibration Reminders (${items.length} Unread)`} + className="max-w-xl" + > +
+

+ The following equipment calibration schedules are due or overdue and require + attention: +

+ +
+ {items.map((n) => { + const isRed = n.severity === "red"; + return ( +
+ {isRed ? ( + + ) : ( + + )} +
+
+ + {n.title} + + + {n.severity} + +
+

{n.message}

+ {n.due_date && ( +
+ Due Date: {formatDate(n.due_date)} +
+ )} +
+
+ ); + })} +
+ +
+ +
+ + +
+
+
+
+ ); +} diff --git a/frontend/src/components/ToastProvider.tsx b/frontend/src/components/ToastProvider.tsx new file mode 100644 index 0000000..b65dc39 --- /dev/null +++ b/frontend/src/components/ToastProvider.tsx @@ -0,0 +1,100 @@ +import { create } from "zustand"; +import { CheckCircle2, Info, AlertTriangle, AlertCircle, X } from "lucide-react"; + +export type ToastVariant = "success" | "info" | "warning" | "error"; + +export interface ToastEntry { + id: string; + title: string; + description?: string; + variant: ToastVariant; +} + +interface ToastState { + toasts: ToastEntry[]; + push: (t: Omit) => void; + dismiss: (id: string) => void; +} + +export const useToastStore = create((set) => ({ + toasts: [], + push: (entry) => { + const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + set((s) => ({ toasts: [...s.toasts.slice(-4), { ...entry, id }] })); + setTimeout(() => { + set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) })); + }, 5000); + }, + dismiss: (id) => + set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) })), +})); + +export const toast = { + success: (title: string, description?: string) => + useToastStore.getState().push({ title, description, variant: "success" }), + info: (title: string, description?: string) => + useToastStore.getState().push({ title, description, variant: "info" }), + warning: (title: string, description?: string) => + useToastStore.getState().push({ title, description, variant: "warning" }), + error: (title: string, description?: string) => + useToastStore.getState().push({ title, description, variant: "error" }), +}; + +const VARIANT_CLS: Record = { + success: "bg-emerald-50 border-emerald-300 text-emerald-900", + info: "bg-blue-50 border-blue-300 text-blue-900", + warning: "bg-amber-50 border-amber-300 text-amber-900", + error: "bg-red-50 border-red-300 text-red-900", +}; + +function VariantIcon({ variant }: { variant: ToastVariant }) { + switch (variant) { + case "success": + return ; + case "warning": + return ; + case "error": + return ; + default: + return ; + } +} + +export function ToastProvider({ children }: { children?: React.ReactNode }) { + const { toasts, dismiss } = useToastStore(); + + return ( + <> + {children} + {toasts.length > 0 && ( +
+ {toasts.map((t) => ( +
+ +
+
{t.title}
+ {t.description && ( +
{t.description}
+ )} +
+ +
+ ))} +
+ )} + + ); +} diff --git a/frontend/src/components/layout/AppShell.tsx b/frontend/src/components/layout/AppShell.tsx index a1338a1..5614ea8 100644 --- a/frontend/src/components/layout/AppShell.tsx +++ b/frontend/src/components/layout/AppShell.tsx @@ -1,6 +1,7 @@ import { Outlet } from "react-router-dom"; import { Sidebar } from "./Sidebar"; import { TopBar } from "./TopBar"; +import { CalibrationReminderModal } from "@/components/CalibrationReminderModal"; export function AppShell() { return ( @@ -12,6 +13,7 @@ export function AppShell() { + ); } diff --git a/frontend/src/components/layout/TopBar.tsx b/frontend/src/components/layout/TopBar.tsx index c1eb175..9a16eec 100644 --- a/frontend/src/components/layout/TopBar.tsx +++ b/frontend/src/components/layout/TopBar.tsx @@ -1,13 +1,28 @@ -import { useState, useEffect } from "react"; +import { useState, useEffect, useRef } from "react"; import { useNavigate } from "react-router-dom"; -import { useQueryClient } from "@tanstack/react-query"; -import { Search, Bell, ChevronDown, User, LogOut, CalendarClock, RotateCcw } from "lucide-react"; +import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; +import { + Search, + Bell, + ChevronDown, + User, + LogOut, + CalendarClock, + RotateCcw, + Play, + CheckCheck, + AlertTriangle, + Info, + Clock, +} from "lucide-react"; import { cn } from "@/lib/utils"; -import { formatDate } from "@/lib/format"; +import { formatDate, formatRelative } from "@/lib/format"; import { ROLE_LABELS } from "@/lib/permissions"; import { useAuthStore } from "@/hooks/useAuth"; import { settingsApi } from "@/api/settings"; +import { notificationsApi, type NotificationItem } from "@/api/notifications"; import { Badge } from "@/components/ui/badge"; +import { toast } from "@/components/ToastProvider"; interface TopBarProps { title?: string; @@ -19,27 +34,142 @@ export function TopBar({ title }: TopBarProps) { const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore(); const [menuOpen, setMenuOpen] = useState(false); + const [bellOpen, setBellOpen] = useState(false); const [dateInput, setDateInput] = useState(demoAsOfDate ?? ""); const [savingDate, setSavingDate] = useState(false); + const [runningAlerts, setRunningAlerts] = useState(false); + + const bellContainerRef = useRef(null); + const seenIdsRef = useRef | null>(null); useEffect(() => { setDateInput(demoAsOfDate ?? ""); }, [demoAsOfDate]); + useEffect(() => { + function handleOutside(e: MouseEvent) { + if ( + bellContainerRef.current && + !bellContainerRef.current.contains(e.target as Node) + ) { + setBellOpen(false); + } + } + document.addEventListener("mousedown", handleOutside); + return () => document.removeEventListener("mousedown", handleOutside); + }, []); + const isAdmin = user?.role === "system_admin"; + const bellQuery = useQuery({ + queryKey: ["notifications", "bell", user?.id], + queryFn: () => notificationsApi.list({ limit: 10 }), + enabled: Boolean(user), + refetchInterval: 60_000, + }); + + const bellItems = bellQuery.data?.items ?? []; + const unreadCount = bellQuery.data?.unread_count ?? 0; + + // Detect newly arrived unread notifications while app is open + useEffect(() => { + if (!bellQuery.data) return; + const currentIds = new Set(bellItems.map((n) => n.id)); + if (seenIdsRef.current === null) { + seenIdsRef.current = currentIds; + return; + } + const newlyArrived = bellItems.filter( + (n) => !n.is_read && !seenIdsRef.current!.has(n.id) + ); + for (const n of newlyArrived.slice(0, 2)) { + if (n.severity === "red") { + toast.error(n.title, n.message); + } else if (n.severity === "yellow") { + toast.warning(n.title, n.message); + } else { + toast.info(n.title, n.message); + } + } + seenIdsRef.current = currentIds; + }, [bellQuery.data, bellItems]); + + const markReadMutation = useMutation({ + mutationFn: (id: number) => notificationsApi.markRead(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ["notifications"] }); + queryClient.invalidateQueries({ queryKey: ["dashboard"] }); + }, + }); + + const markAllReadMutation = useMutation({ + mutationFn: () => notificationsApi.markAllRead(), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ["notifications"] }); + queryClient.invalidateQueries({ queryKey: ["dashboard"] }); + toast.success("All notifications marked as read"); + }, + }); + + async function invalidateDateSensitiveQueries() { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ["notifications"] }), + queryClient.invalidateQueries({ queryKey: ["dashboard"] }), + queryClient.invalidateQueries({ queryKey: ["pm-records"] }), + queryClient.invalidateQueries({ queryKey: ["calibration-records"] }), + queryClient.invalidateQueries({ queryKey: ["contracts"] }), + queryClient.invalidateQueries({ queryKey: ["warranties"] }), + queryClient.invalidateQueries({ queryKey: ["insurance"] }), + queryClient.invalidateQueries({ queryKey: ["demo-equipment"] }), + queryClient.invalidateQueries({ queryKey: ["assets"] }), + queryClient.invalidateQueries(), + ]); + } + async function handleDemoDateUpdate(newDate: string | null) { setSavingDate(true); try { const res = await settingsApi.setDemoDate(newDate); setDemoAsOfDate(res.demo_as_of_date ?? null); setDateInput(res.demo_as_of_date ?? ""); - await queryClient.invalidateQueries(); + await invalidateDateSensitiveQueries(); + toast.info( + res.demo_as_of_date + ? `Demo clock set to ${formatDate(res.demo_as_of_date)}` + : "Demo clock reset to today" + ); } finally { setSavingDate(false); } } + async function handleRunAlertsNow() { + setRunningAlerts(true); + try { + const res = await notificationsApi.runAlertsNow(); + await queryClient.invalidateQueries({ queryKey: ["notifications"] }); + await queryClient.invalidateQueries({ queryKey: ["dashboard"] }); + toast.success( + `Alert check completed (${formatDate(res.evaluated_today)})`, + `${res.created} new alert${res.created === 1 ? "" : "s"} created.` + ); + } catch { + toast.error("Failed to run alert check"); + } finally { + setRunningAlerts(false); + } + } + + function handleNotificationClick(n: NotificationItem) { + setBellOpen(false); + if (!n.is_read) { + markReadMutation.mutate(n.id); + } + if (n.link_url) { + navigate(n.link_url); + } + } + function handleSignOut() { setMenuOpen(false); logout(); @@ -49,7 +179,11 @@ export function TopBar({ title }: TopBarProps) { return (
{/* Page title */} - {title &&

{title}

} + {title && ( +

+ {title} +

+ )} {/* Global search placeholder */}
@@ -69,10 +203,12 @@ export function TopBar({ title }: TopBarProps) { )} - {/* Admin Demo Clock Picker */} + {/* Admin Demo Clock Picker + Run Alert Check */} {isAdmin && ( -
- As of Date: +
+ + As of Date: + Reset )} +
)} - {/* Notification bell placeholder */} - + {/* Live Notification Bell & Dropdown */} +
+ + + {bellOpen && ( +
+
+
+ Notifications{" "} + {unreadCount > 0 && ( + ({unreadCount} unread) + )} +
+ {unreadCount > 0 && ( + + )} +
+ +
+ {bellItems.length === 0 ? ( +
+ No notifications yet. +
+ ) : ( + bellItems.map((n) => ( + + )) + )} +
+ +
+ +
+
+ )} +
{/* User menu */}
@@ -125,7 +358,9 @@ export function TopBar({ title }: TopBarProps) {
- {user?.name ?? "User"} + + {user?.name ?? "User"} + {user?.role ? ROLE_LABELS[user.role] : ""} {user?.department_name ? ` • ${user.department_name}` : ""} @@ -137,11 +372,17 @@ export function TopBar({ title }: TopBarProps) { {menuOpen && (
-
{user?.name}
+
+ {user?.name} +
{user?.email}
- {user?.role && {ROLE_LABELS[user.role]}} - {user?.department_name && {user.department_name}} + {user?.role && ( + {ROLE_LABELS[user.role]} + )} + {user?.department_name && ( + {user.department_name} + )}
+
+ + {/* Filter Bar */} +
+ + + + + +
+ + {/* Notifications List */} +
+ {notifsQuery.isLoading ? ( +
+ Loading notifications... +
+ ) : items.length === 0 ? ( +
+ +

+ No notifications match your filters. +

+
+ ) : ( +
+ {items.map((n) => ( +
+
+ +
+
+ + {n.title} + + + {TYPE_LABELS[n.type] ?? n.type} + + {!n.is_read && Unread} +
+

{n.message}

+
+ Due: {formatDate(n.due_date)} + Created: {formatDateTime(n.created_at)} + {n.is_read && n.read_at && ( + Read: {formatDateTime(n.read_at)} + )} +
+
+
+ +
+ {!n.is_read && ( + + )} + +
+
+ ))} +
+ )} +
+
+ ); +} + +function SeverityBadge({ severity }: { severity: string }) { + if (severity === "red") { + return ( + + + Red + + ); + } + if (severity === "yellow") { + return ( + + + Yellow + + ); + } + return ( + + + Info + + ); +} diff --git a/frontend/src/pages/stubs.tsx b/frontend/src/pages/stubs.tsx index d68a6a5..3ef852f 100644 --- a/frontend/src/pages/stubs.tsx +++ b/frontend/src/pages/stubs.tsx @@ -1,5 +1,4 @@ // Stub pages — replaced phase by phase -import { Link } from "react-router-dom"; interface StubProps { title: string; @@ -24,21 +23,6 @@ function StubPage({ title, phase, description, children }: StubProps) { ); } -export const DashboardPage = () => ( - -
- - Open Phase 0 DataTable Demo → - -
-
-); export const ReportsPage = () => ( ); -export const NotificationsPage = () => ( - -); diff --git a/frontend/src/test/phase6-modules.test.tsx b/frontend/src/test/phase6-modules.test.tsx new file mode 100644 index 0000000..be3e0d4 --- /dev/null +++ b/frontend/src/test/phase6-modules.test.tsx @@ -0,0 +1,215 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { render, screen, waitFor, fireEvent } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { DashboardPage } from "@/pages/DashboardPage"; +import { NotificationsPage } from "@/pages/NotificationsPage"; +import { CalibrationReminderModal } from "@/components/CalibrationReminderModal"; +import { dashboardApi, type DashboardSummary } from "@/api/dashboard"; +import { + notificationsApi, + type NotificationItem, +} from "@/api/notifications"; +import { useAuthStore } from "@/hooks/useAuth"; + +vi.mock("recharts", async () => { + const actual = await vi.importActual("recharts"); + return { + ...actual, + ResponsiveContainer: ({ children }: { children: React.ReactNode }) => ( +
{children}
+ ), + }; +}); + +function renderWithProviders(ui: React.ReactNode) { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + {ui} + + ); +} + +const MOCK_SUMMARY: DashboardSummary = { + department_scope: "ICU", + effective_today: "2026-11-12", + kpis: { + total_assets: 18, + assets_under_repair: 2, + open_complaints: 4, + pm_due_this_month: 5, + calibrations_due: 3, + contracts_expiring: 6, + equipment_on_demo: 1, + }, + complaints_by_status: [ + { status: "open", count: 2 }, + { status: "in_progress", count: 2 }, + { status: "closed", count: 8 }, + ], + complaints_by_department: [ + { department: "ICU", critical: 3, non_critical: 9 }, + ], + monthly_downtime_trend: [ + { month: "2026-06", label: "Jun 2026", downtime_minutes: 120, downtime_hours: 2 }, + { month: "2026-07", label: "Jul 2026", downtime_minutes: 60, downtime_hours: 1 }, + { month: "2026-08", label: "Aug 2026", downtime_minutes: 0, downtime_hours: 0 }, + { month: "2026-09", label: "Sep 2026", downtime_minutes: 180, downtime_hours: 3 }, + { month: "2026-10", label: "Oct 2026", downtime_minutes: 90, downtime_hours: 1.5 }, + { month: "2026-11", label: "Nov 2026", downtime_minutes: 240, downtime_hours: 4 }, + ], + pm_planned_vs_completed: [ + { month: "2026-06", label: "Jun 2026", planned: 4, completed: 4 }, + { month: "2026-07", label: "Jul 2026", planned: 3, completed: 3 }, + { month: "2026-08", label: "Aug 2026", planned: 5, completed: 4 }, + { month: "2026-09", label: "Sep 2026", planned: 2, completed: 2 }, + { month: "2026-10", label: "Oct 2026", planned: 4, completed: 3 }, + { month: "2026-11", label: "Nov 2026", planned: 6, completed: 1 }, + ], + needs_attention: [ + { + id: 901, + type: "calibration_due", + severity: "red", + title: "Calibration Overdue: PHRC-ICU-0001", + message: "ICU Ventilator calibration overdue by 3 days", + entity_type: "calibration_record", + entity_id: 12, + due_date: "2026-11-09", + link_url: "/calibration", + }, + ], + recent_complaints: [ + { + id: 42, + complaint_no: "CMP-2026-0042", + asset_code: "PHRC-ICU-0001", + asset_name: "ICU Ventilator", + department_name: "ICU", + priority: "critical", + call_status: "open", + registered_at: "2026-11-11T08:00:00Z", + downtime_minutes: 150, + downtime_is_ongoing: true, + }, + ], +}; + +const MOCK_CAL_NOTIF: NotificationItem = { + id: 501, + type: "calibration_due", + severity: "red", + title: "Calibration Overdue: PHRC-ICU-0001", + message: "Ventilator calibration due on 09-Nov-2026", + entity_type: "calibration_record", + entity_id: 12, + due_date: "2026-11-09", + created_at: "2026-11-12T06:00:00Z", + is_read: false, + read_at: null, + link_url: "/calibration", +}; + +describe("Phase 6 Modules", () => { + beforeEach(() => { + vi.restoreAllMocks(); + sessionStorage.clear(); + useAuthStore.setState({ + user: { + id: 2, + email: "bio@poona.org", + name: "Biomed Engineer", + role: "biomedical", + department_id: null, + department_name: null, + is_active: true, + }, + token: "token-phase6-test", + }); + }); + + it("DashboardPage renders KPI cards, department scope banner, and Needs Attention panel", async () => { + vi.spyOn(dashboardApi, "summary").mockResolvedValue(MOCK_SUMMARY); + + renderWithProviders(); + + await waitFor(() => { + expect(screen.getByText("Viewing department scope: ICU")).toBeInTheDocument(); + expect(screen.getByText("Total Assets")).toBeInTheDocument(); + expect(screen.getByText("18")).toBeInTheDocument(); + expect(screen.getByText("PM Due This Month")).toBeInTheDocument(); + expect(screen.getByText("Needs Attention")).toBeInTheDocument(); + expect( + screen.getByText("Calibration Overdue: PHRC-ICU-0001") + ).toBeInTheDocument(); + expect(screen.getByText("CMP-2026-0042")).toBeInTheDocument(); + expect(screen.getByText("Ongoing")).toBeInTheDocument(); + }); + }); + + it("NotificationsPage renders notifications and marks single & all read", async () => { + vi.spyOn(notificationsApi, "list").mockResolvedValue({ + items: [MOCK_CAL_NOTIF], + total: 1, + unread_count: 1, + unread_calibration_count: 1, + }); + const markReadSpy = vi + .spyOn(notificationsApi, "markRead") + .mockResolvedValue({ status: "ok", id: 501 }); + const markAllSpy = vi + .spyOn(notificationsApi, "markAllRead") + .mockResolvedValue({ status: "ok", marked_count: 1 }); + + renderWithProviders(); + + await waitFor(() => { + expect( + screen.getByText("Calibration Overdue: PHRC-ICU-0001") + ).toBeInTheDocument(); + expect(screen.getByText("Unread")).toBeInTheDocument(); + }); + + fireEvent.click(screen.getByRole("button", { name: /^Mark Read$/i })); + await waitFor(() => { + expect(markReadSpy).toHaveBeenCalledWith(501); + }); + + fireEvent.click(screen.getByRole("button", { name: /Mark all read/i })); + await waitFor(() => { + expect(markAllSpy).toHaveBeenCalled(); + }); + }); + + it("CalibrationReminderModal pops up when unread calibration notifications exist and marks read on acknowledge", async () => { + vi.spyOn(notificationsApi, "list").mockResolvedValue({ + items: [MOCK_CAL_NOTIF], + total: 1, + unread_count: 1, + unread_calibration_count: 1, + }); + const markAllSpy = vi + .spyOn(notificationsApi, "markAllRead") + .mockResolvedValue({ status: "ok", marked_count: 1 }); + + renderWithProviders(); + + await waitFor(() => { + expect( + screen.getByText(/Calibration Reminders \(1 Unread\)/i) + ).toBeInTheDocument(); + expect( + screen.getByText("Calibration Overdue: PHRC-ICU-0001") + ).toBeInTheDocument(); + }); + + fireEvent.click( + screen.getByRole("button", { name: /Acknowledge & Mark Read/i }) + ); + + await waitFor(() => { + expect(markAllSpy).toHaveBeenCalledWith("calibration_due"); + }); + }); +}); diff --git a/frontend/src/test/smoke.test.tsx b/frontend/src/test/smoke.test.tsx index 29e0f05..c53c71b 100644 --- a/frontend/src/test/smoke.test.tsx +++ b/frontend/src/test/smoke.test.tsx @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach } from "vitest"; import { render, screen } from "@testing-library/react"; import { MemoryRouter } from "react-router-dom"; import { Sidebar } from "@/components/layout/Sidebar"; -import { DashboardPage } from "@/pages/stubs"; +import { ReportsPage } from "@/pages/stubs"; import { DataTableDemoPage } from "@/pages/DataTableDemoPage"; import { useAuthStore } from "@/hooks/useAuth"; @@ -100,15 +100,14 @@ describe("Phase 1 Frontend Smoke Tests", () => { expect(screen.getByText("Contracts & Warranty")).toBeInTheDocument(); }); - it("renders DashboardPage with clickable link to /demo", () => { + it("renders ReportsPage stub coming in Phase 7", () => { render( - + ); - const link = screen.getByRole("link", { name: /Open Phase 0 DataTable Demo/i }); - expect(link).toBeInTheDocument(); - expect(link).toHaveAttribute("href", "/demo"); + expect(screen.getByText("Reports & Exports")).toBeInTheDocument(); + expect(screen.getByText(/Coming in Phase 7/i)).toBeInTheDocument(); }); it("renders DataTableDemoPage with mock rows", () => { diff --git a/frontend/tsconfig.tsbuildinfo b/frontend/tsconfig.tsbuildinfo index 0afee99..75cbeea 100644 --- a/frontend/tsconfig.tsbuildinfo +++ b/frontend/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/phase5.ts","./src/api/pm.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/calibrationmodals.tsx","./src/components/insurancedrawer.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/contractspage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/demoequipmentpage.tsx","./src/pages/insurancepage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/pmpage.tsx","./src/pages/settingspage.tsx","./src/pages/visitspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/phase5-modules.test.tsx","./src/test/pm-page.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"} \ No newline at end of file +{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/dashboard.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/notifications.ts","./src/api/phase5.ts","./src/api/pm.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/calibrationmodals.tsx","./src/components/calibrationremindermodal.tsx","./src/components/insurancedrawer.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/toastprovider.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/contractspage.tsx","./src/pages/dashboardpage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/demoequipmentpage.tsx","./src/pages/insurancepage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/notificationspage.tsx","./src/pages/pmpage.tsx","./src/pages/settingspage.tsx","./src/pages/visitspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/phase5-modules.test.tsx","./src/test/phase6-modules.test.tsx","./src/test/pm-page.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"} \ No newline at end of file