phase-6: alerts engine, scheduler, notifications, calibration popup, and dashboard
This commit is contained in:
@@ -58,11 +58,11 @@ cd backend
|
|||||||
| mgmt@poona.demo | Demo@123 | Management |
|
| mgmt@poona.demo | Demo@123 | Management |
|
||||||
| coord@poona.demo | Demo@123 | Coordinator |
|
| 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
|
- 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
|
- 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)
|
- 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
|
- 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)
|
- 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
|
- 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`
|
- 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
|
- 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`)
|
- 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
|
- 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)
|
- 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
|
- Idempotent deterministic seed script (`python -m app.seed.seed`) populating realistic hospital demo data
|
||||||
|
|||||||
@@ -40,6 +40,17 @@ def effective_today(db=None) -> date:
|
|||||||
return datetime.now(KOLKATA).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:
|
def to_kolkata(dt: datetime) -> datetime:
|
||||||
return dt.astimezone(KOLKATA)
|
return dt.astimezone(KOLKATA)
|
||||||
|
|
||||||
|
|||||||
+40
-2
@@ -1,10 +1,14 @@
|
|||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
import traceback
|
import traceback
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
|
from apscheduler.schedulers.background import BackgroundScheduler
|
||||||
|
from apscheduler.triggers.cron import CronTrigger
|
||||||
from fastapi import FastAPI, Request
|
from fastapi import FastAPI, Request
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import JSONResponse
|
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 .core.exceptions import CodedHTTPException, coded_http_exception_handler
|
||||||
from .models import Base
|
from .models import Base
|
||||||
from .routers import (
|
from .routers import (
|
||||||
@@ -14,16 +18,19 @@ from .routers import (
|
|||||||
calibration,
|
calibration,
|
||||||
complaints,
|
complaints,
|
||||||
contracts,
|
contracts,
|
||||||
|
dashboard,
|
||||||
demo_equipment,
|
demo_equipment,
|
||||||
health,
|
health,
|
||||||
insurance,
|
insurance,
|
||||||
masters,
|
masters,
|
||||||
|
notifications,
|
||||||
pm,
|
pm,
|
||||||
settings,
|
settings,
|
||||||
users,
|
users,
|
||||||
visits,
|
visits,
|
||||||
warranties,
|
warranties,
|
||||||
)
|
)
|
||||||
|
from .services.alerts import run_alert_check
|
||||||
from .services.settings_service import ensure_default_settings
|
from .services.settings_service import ensure_default_settings
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
@@ -33,6 +40,15 @@ logging.basicConfig(
|
|||||||
logger = logging.getLogger("poona_ams")
|
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
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
Base.metadata.create_all(bind=engine)
|
Base.metadata.create_all(bind=engine)
|
||||||
@@ -40,8 +56,28 @@ async def lifespan(app: FastAPI):
|
|||||||
ensure_default_settings(db)
|
ensure_default_settings(db)
|
||||||
db.commit()
|
db.commit()
|
||||||
logger.info("Database tables created/verified.")
|
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.")
|
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(
|
app = FastAPI(
|
||||||
@@ -86,3 +122,5 @@ app.include_router(warranties.router, prefix="/api")
|
|||||||
app.include_router(insurance.router, prefix="/api")
|
app.include_router(insurance.router, prefix="/api")
|
||||||
app.include_router(demo_equipment.router, prefix="/api")
|
app.include_router(demo_equipment.router, prefix="/api")
|
||||||
app.include_router(visits.router, prefix="/api")
|
app.include_router(visits.router, prefix="/api")
|
||||||
|
app.include_router(notifications.router, prefix="/api")
|
||||||
|
app.include_router(dashboard.router, prefix="/api")
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ from . import (
|
|||||||
calibration,
|
calibration,
|
||||||
complaints,
|
complaints,
|
||||||
contracts,
|
contracts,
|
||||||
|
dashboard,
|
||||||
demo_equipment,
|
demo_equipment,
|
||||||
health,
|
health,
|
||||||
insurance,
|
insurance,
|
||||||
masters,
|
masters,
|
||||||
|
notifications,
|
||||||
pm,
|
pm,
|
||||||
settings,
|
settings,
|
||||||
users,
|
users,
|
||||||
@@ -23,10 +25,12 @@ __all__ = [
|
|||||||
"calibration",
|
"calibration",
|
||||||
"complaints",
|
"complaints",
|
||||||
"contracts",
|
"contracts",
|
||||||
|
"dashboard",
|
||||||
"demo_equipment",
|
"demo_equipment",
|
||||||
"health",
|
"health",
|
||||||
"insurance",
|
"insurance",
|
||||||
"masters",
|
"masters",
|
||||||
|
"notifications",
|
||||||
"pm",
|
"pm",
|
||||||
"settings",
|
"settings",
|
||||||
"users",
|
"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)
|
||||||
@@ -45,6 +45,16 @@ from .contracts import (
|
|||||||
ContractRenewOut,
|
ContractRenewOut,
|
||||||
ContractUpdate,
|
ContractUpdate,
|
||||||
)
|
)
|
||||||
|
from .dashboard import (
|
||||||
|
ComplaintsByDepartmentItem,
|
||||||
|
ComplaintsByStatusItem,
|
||||||
|
DashboardKPIs,
|
||||||
|
DashboardSummaryOut,
|
||||||
|
MonthlyDowntimeItem,
|
||||||
|
MonthlyPMComparisonItem,
|
||||||
|
NeedsAttentionItem,
|
||||||
|
RecentComplaintItem,
|
||||||
|
)
|
||||||
from .demo_equipment import (
|
from .demo_equipment import (
|
||||||
DemoEquipmentCreate,
|
DemoEquipmentCreate,
|
||||||
DemoEquipmentListOut,
|
DemoEquipmentListOut,
|
||||||
@@ -72,6 +82,13 @@ from .masters import (
|
|||||||
VendorOut,
|
VendorOut,
|
||||||
VendorUpdate,
|
VendorUpdate,
|
||||||
)
|
)
|
||||||
|
from .notifications import (
|
||||||
|
AlertRunOut,
|
||||||
|
NotificationListOut,
|
||||||
|
NotificationOut,
|
||||||
|
NotificationReadAllOut,
|
||||||
|
NotificationReadOut,
|
||||||
|
)
|
||||||
from .pm import (
|
from .pm import (
|
||||||
PMRecordCompleteIn,
|
PMRecordCompleteIn,
|
||||||
PMRecordCompleteOut,
|
PMRecordCompleteOut,
|
||||||
|
|||||||
@@ -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]
|
||||||
@@ -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
|
||||||
@@ -31,6 +31,7 @@ from ..models import (
|
|||||||
Vendor,
|
Vendor,
|
||||||
Warranty,
|
Warranty,
|
||||||
)
|
)
|
||||||
|
from ..services.alerts import run_alert_check
|
||||||
from ..services.settings_service import ensure_default_settings
|
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])
|
visit.complaints.append(complaints[3])
|
||||||
db.add(visit)
|
db.add(visit)
|
||||||
|
|
||||||
|
db.flush()
|
||||||
|
alert_res = run_alert_check(db)
|
||||||
db.commit()
|
db.commit()
|
||||||
return {
|
return {
|
||||||
"departments": len(departments),
|
"departments": len(departments),
|
||||||
@@ -791,6 +794,7 @@ def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]
|
|||||||
"complaints": len(complaints),
|
"complaints": len(complaints),
|
||||||
"demo_equipment": len(demo_items),
|
"demo_equipment": len(demo_items),
|
||||||
"department_visits": 12,
|
"department_visits": 12,
|
||||||
|
"notifications": int(alert_res["created"]),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,375 @@
|
|||||||
|
from datetime import date, datetime, timezone
|
||||||
|
from sqlalchemy import or_
|
||||||
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
|
from ..core.time_utils import effective_now_utc, effective_today, format_date
|
||||||
|
from ..models import (
|
||||||
|
Asset,
|
||||||
|
CalibrationRecord,
|
||||||
|
Complaint,
|
||||||
|
Contract,
|
||||||
|
DemoEquipment,
|
||||||
|
InsurancePolicy,
|
||||||
|
Notification,
|
||||||
|
NotificationRead,
|
||||||
|
PMRecord,
|
||||||
|
PMSchedule,
|
||||||
|
User,
|
||||||
|
Warranty,
|
||||||
|
)
|
||||||
|
from .calculations import alert_state
|
||||||
|
from .permissions import Role
|
||||||
|
from .settings_service import get_setting_value
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_utc(dt: datetime) -> datetime:
|
||||||
|
if dt.tzinfo is None:
|
||||||
|
return dt.replace(tzinfo=timezone.utc)
|
||||||
|
return dt.astimezone(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def notification_link_url(entity_type: str, entity_id: int) -> str:
|
||||||
|
mapping = {
|
||||||
|
"contract": "/contracts",
|
||||||
|
"warranty": "/contracts?tab=warranties",
|
||||||
|
"calibration_record": "/calibration",
|
||||||
|
"pm_record": "/pm",
|
||||||
|
"insurance": "/insurance",
|
||||||
|
"demo_equipment": "/demo-equipment",
|
||||||
|
"complaint": f"/complaints/{entity_id}",
|
||||||
|
}
|
||||||
|
return mapping.get(entity_type, "/")
|
||||||
|
|
||||||
|
|
||||||
|
def _alert_settings(db: Session) -> dict[str, int]:
|
||||||
|
return {
|
||||||
|
"amc": int(
|
||||||
|
get_setting_value(
|
||||||
|
db,
|
||||||
|
"amc_cmc_lead_days",
|
||||||
|
get_setting_value(db, "contract_expiry_alert_days", 30),
|
||||||
|
)
|
||||||
|
),
|
||||||
|
"calibration": int(get_setting_value(db, "calibration_lead_days", 15)),
|
||||||
|
"pm_in_house": int(get_setting_value(db, "pm_inhouse_lead_days", 15)),
|
||||||
|
"pm_outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)),
|
||||||
|
"insurance": int(
|
||||||
|
get_setting_value(
|
||||||
|
db,
|
||||||
|
"insurance_lead_days",
|
||||||
|
get_setting_value(db, "insurance_expiry_alert_days", 30),
|
||||||
|
)
|
||||||
|
),
|
||||||
|
"warranty": int(
|
||||||
|
get_setting_value(
|
||||||
|
db,
|
||||||
|
"warranty_lead_days",
|
||||||
|
get_setting_value(db, "warranty_expiry_alert_days", 30),
|
||||||
|
)
|
||||||
|
),
|
||||||
|
"red": int(get_setting_value(db, "red_threshold_days", 7)),
|
||||||
|
"critical_hours": int(
|
||||||
|
get_setting_value(
|
||||||
|
db,
|
||||||
|
"critical_complaint_alert_hours",
|
||||||
|
get_setting_value(db, "escalation_open_complaint_hours", 24),
|
||||||
|
)
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _add_if_new(
|
||||||
|
db: Session,
|
||||||
|
existing_keys: set[str],
|
||||||
|
*,
|
||||||
|
dedupe_key: str,
|
||||||
|
alert_type: str,
|
||||||
|
severity: str,
|
||||||
|
title: str,
|
||||||
|
message: str,
|
||||||
|
entity_type: str,
|
||||||
|
entity_id: int,
|
||||||
|
due_date: date | None,
|
||||||
|
target_role: str,
|
||||||
|
created_at: datetime,
|
||||||
|
) -> int:
|
||||||
|
if dedupe_key in existing_keys:
|
||||||
|
return 0
|
||||||
|
existing_keys.add(dedupe_key)
|
||||||
|
db.add(
|
||||||
|
Notification(
|
||||||
|
type=alert_type,
|
||||||
|
severity=severity,
|
||||||
|
title=title,
|
||||||
|
message=message,
|
||||||
|
entity_type=entity_type,
|
||||||
|
entity_id=entity_id,
|
||||||
|
due_date=due_date,
|
||||||
|
target_role=target_role,
|
||||||
|
target_user_id=None,
|
||||||
|
dedupe_key=dedupe_key,
|
||||||
|
created_at=created_at,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
def run_alert_check(db: Session) -> dict[str, object]:
|
||||||
|
today = effective_today(db)
|
||||||
|
eff_now = effective_now_utc(db)
|
||||||
|
cfg = _alert_settings(db)
|
||||||
|
|
||||||
|
existing_keys = {row[0] for row in db.query(Notification.dedupe_key).all()}
|
||||||
|
created = 0
|
||||||
|
|
||||||
|
# 1. AMC / CMC / OTHER contracts expiring
|
||||||
|
contracts = (
|
||||||
|
db.query(Contract)
|
||||||
|
.options(joinedload(Contract.asset))
|
||||||
|
.filter(Contract.is_superseded.is_(False))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for c in contracts:
|
||||||
|
state = alert_state(c.end_date, today, cfg["amc"], cfg["red"])
|
||||||
|
if state in ("yellow", "red"):
|
||||||
|
created += _add_if_new(
|
||||||
|
db,
|
||||||
|
existing_keys,
|
||||||
|
dedupe_key=f"amc:{c.id}:{state}",
|
||||||
|
alert_type="amc_expiry",
|
||||||
|
severity=state,
|
||||||
|
title=f"{c.contract_type} Contract {'Critical' if state == 'red' else 'Expiring'}: {c.asset.asset_code}",
|
||||||
|
message=f"{c.contract_type} contract for {c.asset.name} ({c.asset.asset_code}) ends on {format_date(c.end_date)}.",
|
||||||
|
entity_type="contract",
|
||||||
|
entity_id=c.id,
|
||||||
|
due_date=c.end_date,
|
||||||
|
target_role="coordinator,management,biomedical,system_admin",
|
||||||
|
created_at=eff_now,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. Calibration due / overdue
|
||||||
|
cal_records = (
|
||||||
|
db.query(CalibrationRecord)
|
||||||
|
.options(joinedload(CalibrationRecord.asset))
|
||||||
|
.filter(or_(CalibrationRecord.status.is_(None), CalibrationRecord.status != "completed"))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for r in cal_records:
|
||||||
|
state = alert_state(r.due_date, today, cfg["calibration"], cfg["red"])
|
||||||
|
if state in ("yellow", "red"):
|
||||||
|
status_word = "Overdue" if r.due_date < today else "Due Soon"
|
||||||
|
created += _add_if_new(
|
||||||
|
db,
|
||||||
|
existing_keys,
|
||||||
|
dedupe_key=f"cal:{r.id}:{state}",
|
||||||
|
alert_type="calibration_due",
|
||||||
|
severity=state,
|
||||||
|
title=f"Calibration {status_word}: {r.asset.asset_code}",
|
||||||
|
message=f"Calibration for {r.asset.name} ({r.asset.asset_code}) is due on {format_date(r.due_date)}.",
|
||||||
|
entity_type="calibration_record",
|
||||||
|
entity_id=r.id,
|
||||||
|
due_date=r.due_date,
|
||||||
|
target_role="biomedical,coordinator,management,system_admin",
|
||||||
|
created_at=eff_now,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. PM due / overdue
|
||||||
|
pm_records = (
|
||||||
|
db.query(PMRecord)
|
||||||
|
.options(joinedload(PMRecord.asset), joinedload(PMRecord.schedule))
|
||||||
|
.filter(or_(PMRecord.status.is_(None), ~PMRecord.status.in_(["completed", "rescheduled"])))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for r in pm_records:
|
||||||
|
mode = r.schedule.service_mode if r.schedule else "in_house"
|
||||||
|
lead = cfg["pm_in_house"] if mode == "in_house" else cfg["pm_outsourced"]
|
||||||
|
state = alert_state(r.planned_date, today, lead, cfg["red"])
|
||||||
|
if state in ("yellow", "red"):
|
||||||
|
status_word = "Overdue" if r.planned_date < today else "Due Soon"
|
||||||
|
created += _add_if_new(
|
||||||
|
db,
|
||||||
|
existing_keys,
|
||||||
|
dedupe_key=f"pm:{r.id}:{state}",
|
||||||
|
alert_type="pm_due",
|
||||||
|
severity=state,
|
||||||
|
title=f"PM {status_word}: {r.asset.asset_code}",
|
||||||
|
message=f"Preventive maintenance ({mode.replace('_', '-')}) for {r.asset.name} ({r.asset.asset_code}) is planned for {format_date(r.planned_date)}.",
|
||||||
|
entity_type="pm_record",
|
||||||
|
entity_id=r.id,
|
||||||
|
due_date=r.planned_date,
|
||||||
|
target_role="biomedical,coordinator,management,system_admin",
|
||||||
|
created_at=eff_now,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. Insurance expiry
|
||||||
|
policies = db.query(InsurancePolicy).options(joinedload(InsurancePolicy.asset)).all()
|
||||||
|
for p in policies:
|
||||||
|
state = alert_state(p.end_date, today, cfg["insurance"], cfg["red"])
|
||||||
|
if state in ("yellow", "red"):
|
||||||
|
created += _add_if_new(
|
||||||
|
db,
|
||||||
|
existing_keys,
|
||||||
|
dedupe_key=f"ins:{p.id}:{state}",
|
||||||
|
alert_type="insurance_expiry",
|
||||||
|
severity=state,
|
||||||
|
title=f"Insurance {'Critical' if state == 'red' else 'Expiring'}: {p.asset.asset_code}",
|
||||||
|
message=f"Policy {p.policy_no} for {p.asset.name} ({p.asset.asset_code}) ends on {format_date(p.end_date)}.",
|
||||||
|
entity_type="insurance",
|
||||||
|
entity_id=p.id,
|
||||||
|
due_date=p.end_date,
|
||||||
|
target_role="coordinator,management,system_admin",
|
||||||
|
created_at=eff_now,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 5. Warranty expiry
|
||||||
|
warranties = db.query(Warranty).options(joinedload(Warranty.asset)).all()
|
||||||
|
for w in warranties:
|
||||||
|
state = alert_state(w.end_date, today, cfg["warranty"], cfg["red"])
|
||||||
|
if state in ("yellow", "red"):
|
||||||
|
created += _add_if_new(
|
||||||
|
db,
|
||||||
|
existing_keys,
|
||||||
|
dedupe_key=f"war:{w.id}:{state}",
|
||||||
|
alert_type="warranty_expiry",
|
||||||
|
severity=state,
|
||||||
|
title=f"Warranty {'Critical' if state == 'red' else 'Expiring'}: {w.asset.asset_code}",
|
||||||
|
message=f"Warranty for {w.asset.name} ({w.asset.asset_code}) ends on {format_date(w.end_date)}.",
|
||||||
|
entity_type="warranty",
|
||||||
|
entity_id=w.id,
|
||||||
|
due_date=w.end_date,
|
||||||
|
target_role="coordinator,biomedical,management,system_admin",
|
||||||
|
created_at=eff_now,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 6. Demo equipment overdue return
|
||||||
|
demos = (
|
||||||
|
db.query(DemoEquipment)
|
||||||
|
.filter(DemoEquipment.actual_return_date.is_(None), DemoEquipment.expected_return_date < today)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for d in demos:
|
||||||
|
created += _add_if_new(
|
||||||
|
db,
|
||||||
|
existing_keys,
|
||||||
|
dedupe_key=f"demo:{d.id}:overdue",
|
||||||
|
alert_type="demo_overdue",
|
||||||
|
severity="red",
|
||||||
|
title=f"Demo Return Overdue: {d.name}",
|
||||||
|
message=f"Demo equipment '{d.name}' expected back on {format_date(d.expected_return_date)} has not been returned.",
|
||||||
|
entity_type="demo_equipment",
|
||||||
|
entity_id=d.id,
|
||||||
|
due_date=d.expected_return_date,
|
||||||
|
target_role="biomedical,coordinator,management,system_admin",
|
||||||
|
created_at=eff_now,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 7. Critical complaints open >= critical_complaint_alert_hours
|
||||||
|
crit_complaints = (
|
||||||
|
db.query(Complaint)
|
||||||
|
.options(joinedload(Complaint.asset))
|
||||||
|
.filter(Complaint.call_status != "closed", Complaint.priority == "critical")
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
threshold_secs = cfg["critical_hours"] * 3600
|
||||||
|
for c in crit_complaints:
|
||||||
|
elapsed = (_ensure_utc(eff_now) - _ensure_utc(c.registered_at)).total_seconds()
|
||||||
|
if elapsed >= threshold_secs:
|
||||||
|
created += _add_if_new(
|
||||||
|
db,
|
||||||
|
existing_keys,
|
||||||
|
dedupe_key=f"cmp:{c.id}:critical_overdue",
|
||||||
|
alert_type="critical_complaint",
|
||||||
|
severity="red",
|
||||||
|
title=f"Critical Complaint Open > {cfg['critical_hours']}h: {c.complaint_no}",
|
||||||
|
message=f"Critical complaint {c.complaint_no} for {c.asset.name} ({c.asset.asset_code}) remains {c.call_status}.",
|
||||||
|
entity_type="complaint",
|
||||||
|
entity_id=c.id,
|
||||||
|
due_date=today,
|
||||||
|
target_role="biomedical,management,system_admin,department_user",
|
||||||
|
created_at=eff_now,
|
||||||
|
)
|
||||||
|
|
||||||
|
db.flush()
|
||||||
|
return {"created": created, "evaluated_today": today.isoformat()}
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_entity_departments(db: Session, notifications: list[Notification]) -> dict[tuple[str, int], int]:
|
||||||
|
by_type: dict[str, list[int]] = {}
|
||||||
|
for n in notifications:
|
||||||
|
by_type.setdefault(n.entity_type, []).append(n.entity_id)
|
||||||
|
|
||||||
|
dept_map: dict[tuple[str, int], int] = {}
|
||||||
|
|
||||||
|
asset_model_map = {
|
||||||
|
"contract": Contract,
|
||||||
|
"warranty": Warranty,
|
||||||
|
"insurance": InsurancePolicy,
|
||||||
|
"calibration_record": CalibrationRecord,
|
||||||
|
"pm_record": PMRecord,
|
||||||
|
"complaint": Complaint,
|
||||||
|
}
|
||||||
|
for etype, model in asset_model_map.items():
|
||||||
|
ids = list(set(by_type.get(etype, [])))
|
||||||
|
if ids:
|
||||||
|
rows = (
|
||||||
|
db.query(model.id, Asset.department_id)
|
||||||
|
.join(Asset, model.asset_id == Asset.id)
|
||||||
|
.filter(model.id.in_(ids))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for eid, dept_id in rows:
|
||||||
|
dept_map[(etype, eid)] = dept_id
|
||||||
|
|
||||||
|
demo_ids = list(set(by_type.get("demo_equipment", [])))
|
||||||
|
if demo_ids:
|
||||||
|
rows = (
|
||||||
|
db.query(DemoEquipment.id, DemoEquipment.department_id)
|
||||||
|
.filter(DemoEquipment.id.in_(demo_ids))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for eid, dept_id in rows:
|
||||||
|
dept_map[("demo_equipment", eid)] = dept_id
|
||||||
|
|
||||||
|
return dept_map
|
||||||
|
|
||||||
|
|
||||||
|
def get_visible_notifications_for_user(
|
||||||
|
db: Session,
|
||||||
|
user: User,
|
||||||
|
) -> tuple[list[Notification], dict[int, datetime]]:
|
||||||
|
"""Return (visible_notifications_ordered, read_at_by_notification_id) for the given user."""
|
||||||
|
all_rows = (
|
||||||
|
db.query(Notification)
|
||||||
|
.order_by(Notification.created_at.desc(), Notification.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
role_filtered: list[Notification] = []
|
||||||
|
for n in all_rows:
|
||||||
|
roles = {r.strip() for r in (n.target_role or "").split(",") if r.strip()}
|
||||||
|
if user.role in roles or n.target_user_id == user.id:
|
||||||
|
role_filtered.append(n)
|
||||||
|
|
||||||
|
if user.role == Role.department_user.value:
|
||||||
|
dept_map = _resolve_entity_departments(db, role_filtered)
|
||||||
|
visible = [
|
||||||
|
n
|
||||||
|
for n in role_filtered
|
||||||
|
if dept_map.get((n.entity_type, n.entity_id)) == user.department_id
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
visible = role_filtered
|
||||||
|
|
||||||
|
visible_ids = [n.id for n in visible]
|
||||||
|
read_map: dict[int, datetime] = {}
|
||||||
|
if visible_ids:
|
||||||
|
reads = (
|
||||||
|
db.query(NotificationRead)
|
||||||
|
.filter(
|
||||||
|
NotificationRead.user_id == user.id,
|
||||||
|
NotificationRead.notification_id.in_(visible_ids),
|
||||||
|
)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
read_map = {r.notification_id: r.read_at for r in reads}
|
||||||
|
|
||||||
|
return visible, read_map
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.core.time_utils import effective_today
|
||||||
|
from app.models import Asset, Complaint, Department, Notification
|
||||||
|
from app.seed.seed import seed_database
|
||||||
|
from app.services.alerts import run_alert_check
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module", autouse=True)
|
||||||
|
def seeded_phase6_db(db, tmp_path_factory):
|
||||||
|
upload_dir = tmp_path_factory.mktemp("phase6_test_uploads")
|
||||||
|
seed_database(db, upload_dir=upload_dir)
|
||||||
|
return upload_dir
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||||
|
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_alert_check_dedupe_and_seed_notifications(db):
|
||||||
|
# seed_database already ran run_alert_check -> notifications exist in DB
|
||||||
|
initial_count = db.query(Notification).count()
|
||||||
|
assert initial_count > 0
|
||||||
|
|
||||||
|
# Running run_alert_check again immediately creates 0 duplicates
|
||||||
|
res2 = run_alert_check(db)
|
||||||
|
db.commit()
|
||||||
|
assert res2["created"] == 0
|
||||||
|
assert db.query(Notification).count() == initial_count
|
||||||
|
|
||||||
|
|
||||||
|
def test_demo_clock_alert_run_and_admin_only_permission(client, db):
|
||||||
|
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||||
|
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||||
|
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||||
|
|
||||||
|
# Non-admins get 403 on POST /api/alerts/run
|
||||||
|
for h in (bio_headers, dept_headers, mgmt_headers, coord_headers):
|
||||||
|
assert client.post("/api/alerts/run", headers=h).status_code == 403
|
||||||
|
|
||||||
|
base_today = effective_today(db)
|
||||||
|
future_date = base_today + timedelta(days=20)
|
||||||
|
|
||||||
|
try:
|
||||||
|
set_res = client.post(
|
||||||
|
"/api/settings/demo-date",
|
||||||
|
headers=admin_headers,
|
||||||
|
json={"demo_as_of_date": str(future_date)},
|
||||||
|
)
|
||||||
|
assert set_res.status_code == 200
|
||||||
|
|
||||||
|
# First run at +20 days creates new notifications for newly-entered windows
|
||||||
|
run1 = client.post("/api/alerts/run", headers=admin_headers)
|
||||||
|
assert run1.status_code == 200, run1.text
|
||||||
|
data1 = run1.json()
|
||||||
|
assert data1["evaluated_today"] == str(future_date)
|
||||||
|
assert data1["created"] > 0
|
||||||
|
|
||||||
|
# Second run at same +20 days creates 0 (dedupe)
|
||||||
|
run2 = client.post("/api/alerts/run", headers=admin_headers)
|
||||||
|
assert run2.status_code == 200
|
||||||
|
assert run2.json()["created"] == 0
|
||||||
|
finally:
|
||||||
|
client.post(
|
||||||
|
"/api/settings/demo-date",
|
||||||
|
headers=admin_headers,
|
||||||
|
json={"demo_as_of_date": None},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_per_user_read_state_and_department_scoping(client, db):
|
||||||
|
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||||
|
|
||||||
|
admin_list_before = client.get("/api/notifications?limit=100", headers=admin_headers).json()
|
||||||
|
bio_list_before = client.get("/api/notifications?limit=100", headers=bio_headers).json()
|
||||||
|
assert admin_list_before["unread_count"] > 0
|
||||||
|
assert bio_list_before["unread_count"] > 0
|
||||||
|
|
||||||
|
# Pick a calibration_due notification visible to both admin and bio
|
||||||
|
cal_items = [n for n in admin_list_before["items"] if n["type"] == "calibration_due"]
|
||||||
|
assert len(cal_items) > 0
|
||||||
|
target_id = cal_items[0]["id"]
|
||||||
|
assert cal_items[0]["link_url"] == "/calibration"
|
||||||
|
|
||||||
|
# Admin marks single notification as read -> bio still sees it unread
|
||||||
|
mark_res = client.post(f"/api/notifications/{target_id}/read", headers=admin_headers)
|
||||||
|
assert mark_res.status_code == 200
|
||||||
|
assert mark_res.json()["is_read"] is True
|
||||||
|
|
||||||
|
admin_after_one = client.get("/api/notifications?limit=100", headers=admin_headers).json()
|
||||||
|
bio_after_one = client.get("/api/notifications?limit=100", headers=bio_headers).json()
|
||||||
|
assert admin_after_one["unread_count"] == admin_list_before["unread_count"] - 1
|
||||||
|
assert bio_after_one["unread_count"] == bio_list_before["unread_count"]
|
||||||
|
|
||||||
|
# Admin marks all calibration_due notifications read -> unread_calibration_count becomes 0 for admin, unchanged for bio
|
||||||
|
mark_cal = client.post("/api/notifications/read-all?type=calibration_due", headers=admin_headers)
|
||||||
|
assert mark_cal.status_code == 200
|
||||||
|
admin_after_cal = client.get("/api/notifications?limit=100", headers=admin_headers).json()
|
||||||
|
bio_after_cal = client.get("/api/notifications?limit=100", headers=bio_headers).json()
|
||||||
|
assert admin_after_cal["unread_calibration_count"] == 0
|
||||||
|
assert bio_after_cal["unread_calibration_count"] > 0
|
||||||
|
|
||||||
|
# department_user only sees critical_complaint alerts for their own department (ICU)
|
||||||
|
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||||
|
dept_notifs = client.get("/api/notifications?limit=100", headers=dept_headers).json()
|
||||||
|
for n in dept_notifs["items"]:
|
||||||
|
assert n["entity_type"] == "complaint"
|
||||||
|
assert n["link_url"] == f"/complaints/{n['entity_id']}"
|
||||||
|
comp = db.query(Complaint).filter(Complaint.id == n["entity_id"]).first()
|
||||||
|
assert comp.asset.department_id == icu.id
|
||||||
|
|
||||||
|
|
||||||
|
def test_dashboard_summary_role_scoping_and_charts(client, db):
|
||||||
|
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||||
|
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||||
|
|
||||||
|
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||||
|
icu_asset_count = db.query(Asset).filter(Asset.department_id == icu.id).count()
|
||||||
|
total_asset_count = db.query(Asset).count()
|
||||||
|
|
||||||
|
mgmt_res = client.get("/api/dashboard/summary", headers=mgmt_headers)
|
||||||
|
assert mgmt_res.status_code == 200, mgmt_res.text
|
||||||
|
mgmt = mgmt_res.json()
|
||||||
|
assert mgmt["department_scope"] is None
|
||||||
|
assert mgmt["kpis"]["total_assets"] == total_asset_count
|
||||||
|
assert len(mgmt["monthly_downtime_trend"]) == 6
|
||||||
|
assert len(mgmt["pm_planned_vs_completed"]) == 6
|
||||||
|
assert len(mgmt["complaints_by_status"]) == 3
|
||||||
|
assert len(mgmt["complaints_by_department"]) >= 2
|
||||||
|
assert len(mgmt["recent_complaints"]) <= 8
|
||||||
|
|
||||||
|
dept_res = client.get("/api/dashboard/summary", headers=dept_headers)
|
||||||
|
assert dept_res.status_code == 200, dept_res.text
|
||||||
|
dept = dept_res.json()
|
||||||
|
assert dept["department_scope"] == icu.name
|
||||||
|
assert dept["kpis"]["total_assets"] == icu_asset_count
|
||||||
|
assert dept["kpis"]["total_assets"] < mgmt["kpis"]["total_assets"]
|
||||||
|
assert len(dept["monthly_downtime_trend"]) == 6
|
||||||
|
assert len(dept["pm_planned_vs_completed"]) == 6
|
||||||
|
assert [d["department"] for d in dept["complaints_by_department"]] == [icu.name]
|
||||||
|
assert all(rc["department_name"] == icu.name for rc in dept["recent_complaints"])
|
||||||
@@ -17,11 +17,10 @@ import { ContractsPage } from "@/pages/ContractsPage";
|
|||||||
import { InsurancePage } from "@/pages/InsurancePage";
|
import { InsurancePage } from "@/pages/InsurancePage";
|
||||||
import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage";
|
import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage";
|
||||||
import { VisitsPage } from "@/pages/VisitsPage";
|
import { VisitsPage } from "@/pages/VisitsPage";
|
||||||
import {
|
import { DashboardPage } from "@/pages/DashboardPage";
|
||||||
DashboardPage,
|
import { NotificationsPage } from "@/pages/NotificationsPage";
|
||||||
ReportsPage,
|
import { ReportsPage } from "@/pages/stubs";
|
||||||
NotificationsPage,
|
import { ToastProvider } from "@/components/ToastProvider";
|
||||||
} from "@/pages/stubs";
|
|
||||||
import { useAuthStore } from "@/hooks/useAuth";
|
import { useAuthStore } from "@/hooks/useAuth";
|
||||||
import { can, type Capability } from "@/lib/permissions";
|
import { can, type Capability } from "@/lib/permissions";
|
||||||
|
|
||||||
@@ -127,9 +126,11 @@ function AppRoutes() {
|
|||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<BrowserRouter>
|
<ToastProvider>
|
||||||
<AppRoutes />
|
<BrowserRouter>
|
||||||
</BrowserRouter>
|
<AppRoutes />
|
||||||
|
</BrowserRouter>
|
||||||
|
</ToastProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<DashboardSummary>("/dashboard/summary"),
|
||||||
|
};
|
||||||
@@ -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<NotificationListResponse>(`/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"),
|
||||||
|
};
|
||||||
@@ -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<Set<string>>(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 (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onOpenChange={(o) => !o && setOpen(false)}
|
||||||
|
title={`Calibration Reminders (${items.length} Unread)`}
|
||||||
|
className="max-w-xl"
|
||||||
|
>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
The following equipment calibration schedules are due or overdue and require
|
||||||
|
attention:
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="max-h-72 overflow-y-auto divide-y divide-gray-100 border border-gray-200 rounded-lg">
|
||||||
|
{items.map((n) => {
|
||||||
|
const isRed = n.severity === "red";
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={n.id}
|
||||||
|
className="p-3 flex items-start gap-2.5 bg-white hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
{isRed ? (
|
||||||
|
<AlertTriangle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />
|
||||||
|
) : (
|
||||||
|
<Clock className="h-4 w-4 text-amber-600 shrink-0 mt-0.5" />
|
||||||
|
)}
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<span className="text-sm font-semibold text-gray-900 truncate">
|
||||||
|
{n.title}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={`text-[10px] font-semibold px-2 py-0.5 rounded-full uppercase ${
|
||||||
|
isRed
|
||||||
|
? "bg-red-100 text-red-800"
|
||||||
|
: "bg-amber-100 text-amber-800"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{n.severity}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-600 mt-0.5">{n.message}</p>
|
||||||
|
{n.due_date && (
|
||||||
|
<div className="text-[11px] text-gray-500 mt-1">
|
||||||
|
Due Date: <strong>{formatDate(n.due_date)}</strong>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2 pt-1">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
setOpen(false);
|
||||||
|
navigate("/calibration");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ExternalLink className="h-3.5 w-3.5 mr-1.5" />
|
||||||
|
Open Calibration Register
|
||||||
|
</Button>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
>
|
||||||
|
Remind Me Later
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
loading={acknowledgeMutation.isPending}
|
||||||
|
onClick={() => acknowledgeMutation.mutate()}
|
||||||
|
>
|
||||||
|
<CheckCircle2 className="h-4 w-4 mr-1.5" />
|
||||||
|
Acknowledge & Mark Read
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<ToastEntry, "id">) => void;
|
||||||
|
dismiss: (id: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useToastStore = create<ToastState>((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<ToastVariant, string> = {
|
||||||
|
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 <CheckCircle2 className="h-4 w-4 text-emerald-600 shrink-0 mt-0.5" />;
|
||||||
|
case "warning":
|
||||||
|
return <AlertTriangle className="h-4 w-4 text-amber-600 shrink-0 mt-0.5" />;
|
||||||
|
case "error":
|
||||||
|
return <AlertCircle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />;
|
||||||
|
default:
|
||||||
|
return <Info className="h-4 w-4 text-blue-600 shrink-0 mt-0.5" />;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ToastProvider({ children }: { children?: React.ReactNode }) {
|
||||||
|
const { toasts, dismiss } = useToastStore();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{children}
|
||||||
|
{toasts.length > 0 && (
|
||||||
|
<div
|
||||||
|
aria-live="polite"
|
||||||
|
className="fixed bottom-4 right-4 z-[60] flex flex-col gap-2 w-full max-w-sm pointer-events-none px-4 sm:px-0"
|
||||||
|
>
|
||||||
|
{toasts.map((t) => (
|
||||||
|
<div
|
||||||
|
key={t.id}
|
||||||
|
className={`pointer-events-auto flex items-start gap-2.5 rounded-lg border p-3.5 shadow-lg transition-all ${VARIANT_CLS[t.variant]}`}
|
||||||
|
>
|
||||||
|
<VariantIcon variant={t.variant} />
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="text-xs font-semibold">{t.title}</div>
|
||||||
|
{t.description && (
|
||||||
|
<div className="text-xs opacity-90 mt-0.5">{t.description}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => dismiss(t.id)}
|
||||||
|
aria-label="Dismiss notification"
|
||||||
|
className="p-0.5 rounded hover:bg-black/5 shrink-0"
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Outlet } from "react-router-dom";
|
import { Outlet } from "react-router-dom";
|
||||||
import { Sidebar } from "./Sidebar";
|
import { Sidebar } from "./Sidebar";
|
||||||
import { TopBar } from "./TopBar";
|
import { TopBar } from "./TopBar";
|
||||||
|
import { CalibrationReminderModal } from "@/components/CalibrationReminderModal";
|
||||||
|
|
||||||
export function AppShell() {
|
export function AppShell() {
|
||||||
return (
|
return (
|
||||||
@@ -12,6 +13,7 @@ export function AppShell() {
|
|||||||
<Outlet />
|
<Outlet />
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
<CalibrationReminderModal />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,28 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect, useRef } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useQueryClient } from "@tanstack/react-query";
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { Search, Bell, ChevronDown, User, LogOut, CalendarClock, RotateCcw } from "lucide-react";
|
import {
|
||||||
|
Search,
|
||||||
|
Bell,
|
||||||
|
ChevronDown,
|
||||||
|
User,
|
||||||
|
LogOut,
|
||||||
|
CalendarClock,
|
||||||
|
RotateCcw,
|
||||||
|
Play,
|
||||||
|
CheckCheck,
|
||||||
|
AlertTriangle,
|
||||||
|
Info,
|
||||||
|
Clock,
|
||||||
|
} from "lucide-react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { formatDate } from "@/lib/format";
|
import { formatDate, formatRelative } from "@/lib/format";
|
||||||
import { ROLE_LABELS } from "@/lib/permissions";
|
import { ROLE_LABELS } from "@/lib/permissions";
|
||||||
import { useAuthStore } from "@/hooks/useAuth";
|
import { useAuthStore } from "@/hooks/useAuth";
|
||||||
import { settingsApi } from "@/api/settings";
|
import { settingsApi } from "@/api/settings";
|
||||||
|
import { notificationsApi, type NotificationItem } from "@/api/notifications";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { toast } from "@/components/ToastProvider";
|
||||||
|
|
||||||
interface TopBarProps {
|
interface TopBarProps {
|
||||||
title?: string;
|
title?: string;
|
||||||
@@ -19,27 +34,142 @@ export function TopBar({ title }: TopBarProps) {
|
|||||||
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
|
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
|
||||||
|
|
||||||
const [menuOpen, setMenuOpen] = useState(false);
|
const [menuOpen, setMenuOpen] = useState(false);
|
||||||
|
const [bellOpen, setBellOpen] = useState(false);
|
||||||
const [dateInput, setDateInput] = useState(demoAsOfDate ?? "");
|
const [dateInput, setDateInput] = useState(demoAsOfDate ?? "");
|
||||||
const [savingDate, setSavingDate] = useState(false);
|
const [savingDate, setSavingDate] = useState(false);
|
||||||
|
const [runningAlerts, setRunningAlerts] = useState(false);
|
||||||
|
|
||||||
|
const bellContainerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const seenIdsRef = useRef<Set<number> | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setDateInput(demoAsOfDate ?? "");
|
setDateInput(demoAsOfDate ?? "");
|
||||||
}, [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 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) {
|
async function handleDemoDateUpdate(newDate: string | null) {
|
||||||
setSavingDate(true);
|
setSavingDate(true);
|
||||||
try {
|
try {
|
||||||
const res = await settingsApi.setDemoDate(newDate);
|
const res = await settingsApi.setDemoDate(newDate);
|
||||||
setDemoAsOfDate(res.demo_as_of_date ?? null);
|
setDemoAsOfDate(res.demo_as_of_date ?? null);
|
||||||
setDateInput(res.demo_as_of_date ?? "");
|
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 {
|
} finally {
|
||||||
setSavingDate(false);
|
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() {
|
function handleSignOut() {
|
||||||
setMenuOpen(false);
|
setMenuOpen(false);
|
||||||
logout();
|
logout();
|
||||||
@@ -49,7 +179,11 @@ export function TopBar({ title }: TopBarProps) {
|
|||||||
return (
|
return (
|
||||||
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-4 py-2 gap-3 sticky top-0 z-10">
|
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-4 py-2 gap-3 sticky top-0 z-10">
|
||||||
{/* Page title */}
|
{/* Page title */}
|
||||||
{title && <h1 className="font-semibold text-gray-800 text-sm truncate mr-auto">{title}</h1>}
|
{title && (
|
||||||
|
<h1 className="font-semibold text-gray-800 text-sm truncate mr-auto">
|
||||||
|
{title}
|
||||||
|
</h1>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Global search placeholder */}
|
{/* Global search placeholder */}
|
||||||
<div className={cn("relative", title ? "" : "flex-1 max-w-xs sm:max-w-sm")}>
|
<div className={cn("relative", title ? "" : "flex-1 max-w-xs sm:max-w-sm")}>
|
||||||
@@ -69,10 +203,12 @@ export function TopBar({ title }: TopBarProps) {
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Admin Demo Clock Picker */}
|
{/* Admin Demo Clock Picker + Run Alert Check */}
|
||||||
{isAdmin && (
|
{isAdmin && (
|
||||||
<div className="flex items-center gap-1.5 bg-gray-50 border border-gray-200 rounded-md px-2 py-1 text-xs">
|
<div className="flex items-center gap-1.5 bg-gray-50 border border-gray-200 rounded-md px-2 py-1 text-xs flex-wrap">
|
||||||
<span className="text-gray-500 font-medium hidden md:inline">As of Date:</span>
|
<span className="text-gray-500 font-medium hidden md:inline">
|
||||||
|
As of Date:
|
||||||
|
</span>
|
||||||
<input
|
<input
|
||||||
type="date"
|
type="date"
|
||||||
aria-label="As of Date"
|
aria-label="As of Date"
|
||||||
@@ -100,19 +236,116 @@ export function TopBar({ title }: TopBarProps) {
|
|||||||
<span className="hidden lg:inline">Reset</span>
|
<span className="hidden lg:inline">Reset</span>
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={runningAlerts}
|
||||||
|
onClick={handleRunAlertsNow}
|
||||||
|
className="inline-flex items-center gap-1 px-2 py-0.5 rounded border border-blue-300 bg-blue-50 text-[#1e3a8a] hover:bg-blue-100 disabled:opacity-40 font-medium"
|
||||||
|
title="Run alert engine immediately for current effective date"
|
||||||
|
>
|
||||||
|
<Play className="h-3 w-3" />
|
||||||
|
<span>{runningAlerts ? "Running..." : "Run alert check now"}</span>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Notification bell placeholder */}
|
{/* Live Notification Bell & Dropdown */}
|
||||||
<button
|
<div ref={bellContainerRef} className="relative ml-auto">
|
||||||
type="button"
|
<button
|
||||||
onClick={() => navigate("/notifications")}
|
type="button"
|
||||||
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-500 ml-auto"
|
onClick={() => setBellOpen((o) => !o)}
|
||||||
aria-label="Notifications"
|
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-600"
|
||||||
>
|
aria-label="Notifications"
|
||||||
<Bell className="h-5 w-5" />
|
>
|
||||||
<span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-red-500" />
|
<Bell className="h-5 w-5" />
|
||||||
</button>
|
{unreadCount > 0 && (
|
||||||
|
<span className="absolute -top-0.5 -right-0.5 min-w-[18px] h-[18px] px-1 rounded-full bg-red-600 text-white text-[10px] font-bold flex items-center justify-center leading-none">
|
||||||
|
{unreadCount > 99 ? "99+" : unreadCount}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{bellOpen && (
|
||||||
|
<div className="absolute right-0 mt-1.5 w-80 sm:w-96 bg-white border border-gray-200 rounded-lg shadow-xl z-30 overflow-hidden">
|
||||||
|
<div className="flex items-center justify-between px-3.5 py-2.5 border-b border-gray-100 bg-gray-50">
|
||||||
|
<div className="text-xs font-semibold text-gray-800">
|
||||||
|
Notifications{" "}
|
||||||
|
{unreadCount > 0 && (
|
||||||
|
<span className="ml-1 text-red-600">({unreadCount} unread)</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{unreadCount > 0 && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => markAllReadMutation.mutate()}
|
||||||
|
className="inline-flex items-center gap-1 text-[11px] font-medium text-[#1e3a8a] hover:underline"
|
||||||
|
>
|
||||||
|
<CheckCheck className="h-3.5 w-3.5" />
|
||||||
|
Mark all read
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="max-h-80 overflow-y-auto divide-y divide-gray-100">
|
||||||
|
{bellItems.length === 0 ? (
|
||||||
|
<div className="py-8 text-center text-xs text-gray-400">
|
||||||
|
No notifications yet.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
bellItems.map((n) => (
|
||||||
|
<button
|
||||||
|
key={n.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleNotificationClick(n)}
|
||||||
|
className={cn(
|
||||||
|
"w-full text-left px-3.5 py-2.5 hover:bg-gray-50 flex items-start gap-2.5 transition-colors",
|
||||||
|
!n.is_read && "bg-blue-50/40"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<SeverityIcon severity={n.severity} />
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"text-xs truncate",
|
||||||
|
!n.is_read
|
||||||
|
? "font-semibold text-gray-900"
|
||||||
|
: "font-medium text-gray-700"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{n.title}
|
||||||
|
</span>
|
||||||
|
{!n.is_read && (
|
||||||
|
<span className="h-2 w-2 rounded-full bg-blue-600 shrink-0" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-[11px] text-gray-600 line-clamp-2 mt-0.5">
|
||||||
|
{n.message}
|
||||||
|
</p>
|
||||||
|
<div className="text-[10px] text-gray-400 mt-1">
|
||||||
|
{formatRelative(n.created_at)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-3.5 py-2 border-t border-gray-100 bg-gray-50 text-center">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setBellOpen(false);
|
||||||
|
navigate("/notifications");
|
||||||
|
}}
|
||||||
|
className="text-xs font-medium text-[#1e3a8a] hover:underline"
|
||||||
|
>
|
||||||
|
View all notifications →
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* User menu */}
|
{/* User menu */}
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
@@ -125,7 +358,9 @@ export function TopBar({ title }: TopBarProps) {
|
|||||||
<User className="h-4 w-4" />
|
<User className="h-4 w-4" />
|
||||||
</div>
|
</div>
|
||||||
<div className="hidden sm:flex flex-col items-start leading-tight">
|
<div className="hidden sm:flex flex-col items-start leading-tight">
|
||||||
<span className="font-medium text-gray-800 text-xs">{user?.name ?? "User"}</span>
|
<span className="font-medium text-gray-800 text-xs">
|
||||||
|
{user?.name ?? "User"}
|
||||||
|
</span>
|
||||||
<span className="text-[10px] text-gray-500">
|
<span className="text-[10px] text-gray-500">
|
||||||
{user?.role ? ROLE_LABELS[user.role] : ""}
|
{user?.role ? ROLE_LABELS[user.role] : ""}
|
||||||
{user?.department_name ? ` • ${user.department_name}` : ""}
|
{user?.department_name ? ` • ${user.department_name}` : ""}
|
||||||
@@ -137,11 +372,17 @@ export function TopBar({ title }: TopBarProps) {
|
|||||||
{menuOpen && (
|
{menuOpen && (
|
||||||
<div className="absolute right-0 mt-1 w-60 bg-white border border-gray-200 rounded-md shadow-lg z-30 py-2">
|
<div className="absolute right-0 mt-1 w-60 bg-white border border-gray-200 rounded-md shadow-lg z-30 py-2">
|
||||||
<div className="px-3 py-2 border-b border-gray-100 space-y-1">
|
<div className="px-3 py-2 border-b border-gray-100 space-y-1">
|
||||||
<div className="text-sm font-medium text-gray-900 truncate">{user?.name}</div>
|
<div className="text-sm font-medium text-gray-900 truncate">
|
||||||
|
{user?.name}
|
||||||
|
</div>
|
||||||
<div className="text-xs text-gray-500 truncate">{user?.email}</div>
|
<div className="text-xs text-gray-500 truncate">{user?.email}</div>
|
||||||
<div className="flex items-center gap-1.5 flex-wrap pt-0.5">
|
<div className="flex items-center gap-1.5 flex-wrap pt-0.5">
|
||||||
{user?.role && <Badge variant="info">{ROLE_LABELS[user.role]}</Badge>}
|
{user?.role && (
|
||||||
{user?.department_name && <Badge variant="outline">{user.department_name}</Badge>}
|
<Badge variant="info">{ROLE_LABELS[user.role]}</Badge>
|
||||||
|
)}
|
||||||
|
{user?.department_name && (
|
||||||
|
<Badge variant="outline">{user.department_name}</Badge>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
@@ -158,3 +399,13 @@ export function TopBar({ title }: TopBarProps) {
|
|||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function SeverityIcon({ severity }: { severity: string }) {
|
||||||
|
if (severity === "red") {
|
||||||
|
return <AlertTriangle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />;
|
||||||
|
}
|
||||||
|
if (severity === "yellow") {
|
||||||
|
return <Clock className="h-4 w-4 text-amber-600 shrink-0 mt-0.5" />;
|
||||||
|
}
|
||||||
|
return <Info className="h-4 w-4 text-blue-600 shrink-0 mt-0.5" />;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,424 @@
|
|||||||
|
import { Link } from "react-router-dom";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
ResponsiveContainer,
|
||||||
|
PieChart,
|
||||||
|
Pie,
|
||||||
|
Cell,
|
||||||
|
BarChart,
|
||||||
|
Bar,
|
||||||
|
AreaChart,
|
||||||
|
Area,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
CartesianGrid,
|
||||||
|
Tooltip,
|
||||||
|
Legend,
|
||||||
|
} from "recharts";
|
||||||
|
import {
|
||||||
|
Package,
|
||||||
|
Wrench,
|
||||||
|
AlertCircle,
|
||||||
|
CalendarCheck,
|
||||||
|
Gauge,
|
||||||
|
FileText,
|
||||||
|
Truck,
|
||||||
|
AlertTriangle,
|
||||||
|
ArrowRight,
|
||||||
|
Building2,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { dashboardApi } from "@/api/dashboard";
|
||||||
|
import { formatDate, formatDuration } from "@/lib/format";
|
||||||
|
import { CallStatusBadge, CriticalityBadge } from "@/components/StatusBadge";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
|
||||||
|
const STATUS_COLORS: Record<string, { label: string; color: string }> = {
|
||||||
|
open: { label: "Open", color: "#ef4444" },
|
||||||
|
in_progress: { label: "In Progress", color: "#f59e0b" },
|
||||||
|
closed: { label: "Closed", color: "#22c55e" },
|
||||||
|
};
|
||||||
|
|
||||||
|
export function DashboardPage() {
|
||||||
|
const { data, isLoading, isError } = useQuery({
|
||||||
|
queryKey: ["dashboard", "summary"],
|
||||||
|
queryFn: () => dashboardApi.summary(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="h-8 w-56 bg-gray-200 rounded animate-pulse" />
|
||||||
|
<div className="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-7 gap-3">
|
||||||
|
{Array.from({ length: 7 }).map((_, i) => (
|
||||||
|
<div key={i} className="h-24 bg-white border border-gray-200 rounded-xl animate-pulse" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||||
|
<div className="h-72 bg-white border border-gray-200 rounded-xl animate-pulse" />
|
||||||
|
<div className="h-72 bg-white border border-gray-200 rounded-xl animate-pulse" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isError || !data) {
|
||||||
|
return (
|
||||||
|
<div className="bg-white border border-red-200 rounded-xl p-6 text-center text-sm text-red-700">
|
||||||
|
Unable to load dashboard summary. Please refresh and try again.
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const {
|
||||||
|
department_scope,
|
||||||
|
effective_today,
|
||||||
|
kpis,
|
||||||
|
complaints_by_status,
|
||||||
|
complaints_by_department,
|
||||||
|
monthly_downtime_trend,
|
||||||
|
pm_planned_vs_completed,
|
||||||
|
needs_attention,
|
||||||
|
recent_complaints,
|
||||||
|
} = data;
|
||||||
|
|
||||||
|
const kpiCards = [
|
||||||
|
{
|
||||||
|
label: "Total Assets",
|
||||||
|
value: kpis.total_assets,
|
||||||
|
to: "/assets",
|
||||||
|
icon: Package,
|
||||||
|
tone: "text-[#1e3a8a] bg-blue-50 border-blue-200",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Under Repair",
|
||||||
|
value: kpis.assets_under_repair,
|
||||||
|
to: "/assets?status=under_repair",
|
||||||
|
icon: Wrench,
|
||||||
|
tone: "text-amber-800 bg-amber-50 border-amber-200",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Open Complaints",
|
||||||
|
value: kpis.open_complaints,
|
||||||
|
to: "/complaints",
|
||||||
|
icon: AlertCircle,
|
||||||
|
tone: "text-red-800 bg-red-50 border-red-200",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "PM Due This Month",
|
||||||
|
value: kpis.pm_due_this_month,
|
||||||
|
to: "/pm",
|
||||||
|
icon: CalendarCheck,
|
||||||
|
tone: "text-indigo-800 bg-indigo-50 border-indigo-200",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Calibrations Due",
|
||||||
|
value: kpis.calibrations_due,
|
||||||
|
to: "/calibration",
|
||||||
|
icon: Gauge,
|
||||||
|
tone: "text-orange-800 bg-orange-50 border-orange-200",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Contracts Expiring",
|
||||||
|
value: kpis.contracts_expiring,
|
||||||
|
to: "/contracts",
|
||||||
|
icon: FileText,
|
||||||
|
tone: "text-purple-800 bg-purple-50 border-purple-200",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Equipment on Demo",
|
||||||
|
value: kpis.equipment_on_demo,
|
||||||
|
to: "/demo-equipment",
|
||||||
|
icon: Truck,
|
||||||
|
tone: "text-teal-800 bg-teal-50 border-teal-200",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const statusChartData = complaints_by_status.map((item) => ({
|
||||||
|
name: STATUS_COLORS[item.status]?.label ?? item.status,
|
||||||
|
value: item.count,
|
||||||
|
color: STATUS_COLORS[item.status]?.color ?? "#6b7280",
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-5">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">Hospital Operations Dashboard</h1>
|
||||||
|
<p className="text-sm text-gray-500 mt-0.5">
|
||||||
|
Live equipment health, breakdown downtime, PM compliance, and expiry alerts as of{" "}
|
||||||
|
<span className="font-medium text-gray-700">{formatDate(effective_today)}</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{department_scope && (
|
||||||
|
<div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-blue-50 border border-blue-200 text-xs font-semibold text-[#1e3a8a]">
|
||||||
|
<Building2 className="h-3.5 w-3.5" />
|
||||||
|
Viewing department scope: {department_scope}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 7 KPI Cards */}
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-7 gap-3">
|
||||||
|
{kpiCards.map((card) => {
|
||||||
|
const Icon = card.icon;
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
key={card.label}
|
||||||
|
to={card.to}
|
||||||
|
className={`rounded-xl border p-3.5 transition-shadow hover:shadow-md flex flex-col justify-between ${card.tone}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<span className="text-xs font-medium opacity-85">{card.label}</span>
|
||||||
|
<Icon className="h-4 w-4 shrink-0 opacity-80" />
|
||||||
|
</div>
|
||||||
|
<div className="text-2xl font-bold mt-2">{card.value}</div>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 4 Charts Grid */}
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||||
|
{/* Chart 1: Complaints by Status */}
|
||||||
|
<div className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
|
||||||
|
<h2 className="text-sm font-semibold text-gray-800 mb-3">
|
||||||
|
Complaints by Status
|
||||||
|
</h2>
|
||||||
|
<div className="h-60">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<PieChart>
|
||||||
|
<Pie
|
||||||
|
data={statusChartData}
|
||||||
|
dataKey="value"
|
||||||
|
nameKey="name"
|
||||||
|
cx="50%"
|
||||||
|
cy="50%"
|
||||||
|
innerRadius={52}
|
||||||
|
outerRadius={82}
|
||||||
|
paddingAngle={3}
|
||||||
|
>
|
||||||
|
{statusChartData.map((entry, idx) => (
|
||||||
|
<Cell key={idx} fill={entry.color} />
|
||||||
|
))}
|
||||||
|
</Pie>
|
||||||
|
<Tooltip />
|
||||||
|
<Legend />
|
||||||
|
</PieChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Chart 2: Complaints by Department */}
|
||||||
|
<div className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
|
||||||
|
<h2 className="text-sm font-semibold text-gray-800 mb-3">
|
||||||
|
Complaints by Department
|
||||||
|
</h2>
|
||||||
|
<div className="h-60">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<BarChart data={complaints_by_department}>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
|
||||||
|
<XAxis dataKey="department" tick={{ fontSize: 11 }} />
|
||||||
|
<YAxis allowDecimals={false} tick={{ fontSize: 11 }} />
|
||||||
|
<Tooltip />
|
||||||
|
<Legend />
|
||||||
|
<Bar
|
||||||
|
dataKey="critical"
|
||||||
|
name="Critical"
|
||||||
|
stackId="a"
|
||||||
|
fill="#ef4444"
|
||||||
|
radius={[0, 0, 0, 0]}
|
||||||
|
/>
|
||||||
|
<Bar
|
||||||
|
dataKey="non_critical"
|
||||||
|
name="Non-Critical"
|
||||||
|
stackId="a"
|
||||||
|
fill="#3b82f6"
|
||||||
|
radius={[4, 4, 0, 0]}
|
||||||
|
/>
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Chart 3: Monthly Downtime Trend */}
|
||||||
|
<div className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
|
||||||
|
<h2 className="text-sm font-semibold text-gray-800 mb-3">
|
||||||
|
Monthly Downtime Trend (Hours)
|
||||||
|
</h2>
|
||||||
|
<div className="h-60">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<AreaChart data={monthly_downtime_trend}>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
|
||||||
|
<XAxis dataKey="label" tick={{ fontSize: 11 }} />
|
||||||
|
<YAxis tick={{ fontSize: 11 }} />
|
||||||
|
<Tooltip />
|
||||||
|
<Area
|
||||||
|
type="monotone"
|
||||||
|
dataKey="downtime_hours"
|
||||||
|
name="Downtime (hrs)"
|
||||||
|
stroke="#ef4444"
|
||||||
|
fill="#fee2e2"
|
||||||
|
strokeWidth={2}
|
||||||
|
/>
|
||||||
|
</AreaChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Chart 4: PM Planned vs Completed */}
|
||||||
|
<div className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
|
||||||
|
<h2 className="text-sm font-semibold text-gray-800 mb-3">
|
||||||
|
PM Planned vs Completed (Last 6 Months)
|
||||||
|
</h2>
|
||||||
|
<div className="h-60">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<BarChart data={pm_planned_vs_completed}>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
|
||||||
|
<XAxis dataKey="label" tick={{ fontSize: 11 }} />
|
||||||
|
<YAxis allowDecimals={false} tick={{ fontSize: 11 }} />
|
||||||
|
<Tooltip />
|
||||||
|
<Legend />
|
||||||
|
<Bar dataKey="planned" name="Planned" fill="#1e3a8a" radius={[4, 4, 0, 0]} />
|
||||||
|
<Bar dataKey="completed" name="Completed" fill="#22c55e" radius={[4, 4, 0, 0]} />
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Bottom Panels: Needs Attention & Recent Complaints */}
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
|
||||||
|
{/* Needs Attention */}
|
||||||
|
<div className="lg:col-span-5 bg-white border border-gray-200 rounded-xl p-4 shadow-sm space-y-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h2 className="text-sm font-semibold text-gray-900 flex items-center gap-1.5">
|
||||||
|
<AlertTriangle className="h-4 w-4 text-red-600" />
|
||||||
|
Needs Attention
|
||||||
|
</h2>
|
||||||
|
<Link
|
||||||
|
to="/notifications"
|
||||||
|
className="text-xs font-medium text-[#1e3a8a] hover:underline"
|
||||||
|
>
|
||||||
|
View all →
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{needs_attention.length === 0 ? (
|
||||||
|
<div className="py-8 text-center text-xs text-gray-400">
|
||||||
|
No urgent red-severity alerts right now.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="divide-y divide-gray-100 max-h-80 overflow-y-auto">
|
||||||
|
{needs_attention.map((item) => (
|
||||||
|
<Link
|
||||||
|
key={item.id}
|
||||||
|
to={item.link_url}
|
||||||
|
className="flex items-start justify-between gap-2 py-2.5 px-2 -mx-2 rounded-md hover:bg-red-50/50 transition-colors"
|
||||||
|
>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="text-xs font-semibold text-gray-900 truncate">
|
||||||
|
{item.title}
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-gray-600 line-clamp-2 mt-0.5">
|
||||||
|
{item.message}
|
||||||
|
</div>
|
||||||
|
{item.due_date && (
|
||||||
|
<div className="text-[10px] text-red-700 font-medium mt-0.5">
|
||||||
|
Due: {formatDate(item.due_date)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ArrowRight className="h-3.5 w-3.5 text-gray-400 shrink-0 mt-1" />
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Recent Complaints */}
|
||||||
|
<div className="lg:col-span-7 bg-white border border-gray-200 rounded-xl p-4 shadow-sm space-y-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h2 className="text-sm font-semibold text-gray-900">
|
||||||
|
Recent Complaints
|
||||||
|
</h2>
|
||||||
|
<Link
|
||||||
|
to="/complaints"
|
||||||
|
className="text-xs font-medium text-[#1e3a8a] hover:underline"
|
||||||
|
>
|
||||||
|
All complaints →
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{recent_complaints.length === 0 ? (
|
||||||
|
<div className="py-8 text-center text-xs text-gray-400">
|
||||||
|
No complaints recorded yet.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full text-xs">
|
||||||
|
<thead className="bg-gray-50 border-b border-gray-200">
|
||||||
|
<tr>
|
||||||
|
<th className="text-left font-medium text-gray-600 px-3 py-2">
|
||||||
|
Complaint
|
||||||
|
</th>
|
||||||
|
<th className="text-left font-medium text-gray-600 px-3 py-2">
|
||||||
|
Asset
|
||||||
|
</th>
|
||||||
|
<th className="text-left font-medium text-gray-600 px-3 py-2">
|
||||||
|
Status
|
||||||
|
</th>
|
||||||
|
<th className="text-left font-medium text-gray-600 px-3 py-2">
|
||||||
|
Priority
|
||||||
|
</th>
|
||||||
|
<th className="text-left font-medium text-gray-600 px-3 py-2">
|
||||||
|
Downtime
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-100">
|
||||||
|
{recent_complaints.map((c) => (
|
||||||
|
<tr key={c.id} className="hover:bg-gray-50/70">
|
||||||
|
<td className="px-3 py-2 whitespace-nowrap">
|
||||||
|
<Link
|
||||||
|
to={`/complaints/${c.id}`}
|
||||||
|
className="font-mono font-semibold text-[#1e3a8a] hover:underline"
|
||||||
|
>
|
||||||
|
{c.complaint_no}
|
||||||
|
</Link>
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<div className="font-mono text-[11px] text-gray-700">
|
||||||
|
{c.asset_code}
|
||||||
|
</div>
|
||||||
|
<div className="text-gray-900 truncate max-w-[160px]">
|
||||||
|
{c.asset_name}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<CallStatusBadge status={c.call_status} />
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<CriticalityBadge criticality={c.priority} />
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2 whitespace-nowrap">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<span>{formatDuration(c.downtime_minutes)}</span>
|
||||||
|
{c.downtime_is_ongoing && (
|
||||||
|
<Badge variant="danger" className="text-[10px] px-1.5 py-0">
|
||||||
|
Ongoing
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
Bell,
|
||||||
|
CheckCheck,
|
||||||
|
AlertTriangle,
|
||||||
|
Clock,
|
||||||
|
Info,
|
||||||
|
ExternalLink,
|
||||||
|
Check,
|
||||||
|
} from "lucide-react";
|
||||||
|
import {
|
||||||
|
notificationsApi,
|
||||||
|
type NotificationItem,
|
||||||
|
type NotificationType,
|
||||||
|
} from "@/api/notifications";
|
||||||
|
import { formatDate, formatDateTime } from "@/lib/format";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { toast } from "@/components/ToastProvider";
|
||||||
|
|
||||||
|
const TYPE_OPTIONS: { value: NotificationType | ""; label: string }[] = [
|
||||||
|
{ value: "", label: "All Types" },
|
||||||
|
{ value: "amc_expiry", label: "AMC / CMC Expiry" },
|
||||||
|
{ value: "calibration_due", label: "Calibration Due" },
|
||||||
|
{ value: "pm_due", label: "PM Due" },
|
||||||
|
{ value: "insurance_expiry", label: "Insurance Expiry" },
|
||||||
|
{ value: "warranty_expiry", label: "Warranty Expiry" },
|
||||||
|
{ value: "demo_overdue", label: "Demo Overdue" },
|
||||||
|
{ value: "critical_complaint", label: "Critical Complaint" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const TYPE_LABELS: Record<string, string> = {
|
||||||
|
amc_expiry: "AMC / CMC Expiry",
|
||||||
|
calibration_due: "Calibration Due",
|
||||||
|
pm_due: "PM Due",
|
||||||
|
insurance_expiry: "Insurance Expiry",
|
||||||
|
warranty_expiry: "Warranty Expiry",
|
||||||
|
demo_overdue: "Demo Overdue",
|
||||||
|
critical_complaint: "Critical Complaint",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function NotificationsPage() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const qc = useQueryClient();
|
||||||
|
|
||||||
|
const [typeFilter, setTypeFilter] = useState("");
|
||||||
|
const [severityFilter, setSeverityFilter] = useState("");
|
||||||
|
const [unreadOnly, setUnreadOnly] = useState(false);
|
||||||
|
|
||||||
|
const notifsQuery = useQuery({
|
||||||
|
queryKey: ["notifications", "page", typeFilter, severityFilter, unreadOnly],
|
||||||
|
queryFn: () =>
|
||||||
|
notificationsApi.list({
|
||||||
|
type: typeFilter || undefined,
|
||||||
|
severity: severityFilter || undefined,
|
||||||
|
unread_only: unreadOnly,
|
||||||
|
page_size: 200,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const markReadMutation = useMutation({
|
||||||
|
mutationFn: (id: number) => notificationsApi.markRead(id),
|
||||||
|
onSuccess: () => {
|
||||||
|
qc.invalidateQueries({ queryKey: ["notifications"] });
|
||||||
|
qc.invalidateQueries({ queryKey: ["dashboard"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const markAllMutation = useMutation({
|
||||||
|
mutationFn: () => notificationsApi.markAllRead(typeFilter || undefined),
|
||||||
|
onSuccess: () => {
|
||||||
|
qc.invalidateQueries({ queryKey: ["notifications"] });
|
||||||
|
qc.invalidateQueries({ queryKey: ["dashboard"] });
|
||||||
|
toast.success("Notifications marked as read");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const items = notifsQuery.data?.items ?? [];
|
||||||
|
const unreadCount = notifsQuery.data?.unread_count ?? 0;
|
||||||
|
|
||||||
|
function handleOpen(n: NotificationItem) {
|
||||||
|
if (!n.is_read) {
|
||||||
|
markReadMutation.mutate(n.id);
|
||||||
|
}
|
||||||
|
if (n.link_url) {
|
||||||
|
navigate(n.link_url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">Notifications Centre</h1>
|
||||||
|
<p className="text-sm text-gray-500 mt-0.5">
|
||||||
|
Hospital-wide and department-scoped alerts for PM, calibration, expiry, demo returns, and critical breakdowns
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
disabled={unreadCount === 0}
|
||||||
|
loading={markAllMutation.isPending}
|
||||||
|
onClick={() => markAllMutation.mutate()}
|
||||||
|
>
|
||||||
|
<CheckCheck className="h-4 w-4 mr-1.5" />
|
||||||
|
Mark all read{unreadCount > 0 ? ` (${unreadCount})` : ""}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filter Bar */}
|
||||||
|
<div className="bg-white border border-gray-200 rounded-lg p-3.5 flex flex-wrap items-center gap-3">
|
||||||
|
<select
|
||||||
|
aria-label="Filter by Type"
|
||||||
|
value={typeFilter}
|
||||||
|
onChange={(e) => setTypeFilter(e.target.value)}
|
||||||
|
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||||
|
>
|
||||||
|
{TYPE_OPTIONS.map((o) => (
|
||||||
|
<option key={o.value} value={o.value}>
|
||||||
|
{o.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select
|
||||||
|
aria-label="Filter by Severity"
|
||||||
|
value={severityFilter}
|
||||||
|
onChange={(e) => setSeverityFilter(e.target.value)}
|
||||||
|
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||||
|
>
|
||||||
|
<option value="">All Severities</option>
|
||||||
|
<option value="red">Red (Urgent / Overdue)</option>
|
||||||
|
<option value="yellow">Yellow (Expiring / Due Soon)</option>
|
||||||
|
<option value="info">Info</option>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<label className="inline-flex items-center gap-2 text-xs text-gray-700 cursor-pointer ml-auto">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={unreadOnly}
|
||||||
|
onChange={(e) => setUnreadOnly(e.target.checked)}
|
||||||
|
className="h-3.5 w-3.5 rounded border-gray-300 text-[#1e3a8a]"
|
||||||
|
/>
|
||||||
|
Unread Only
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Notifications List */}
|
||||||
|
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||||
|
{notifsQuery.isLoading ? (
|
||||||
|
<div className="p-8 text-center text-sm text-gray-500">
|
||||||
|
Loading notifications...
|
||||||
|
</div>
|
||||||
|
) : items.length === 0 ? (
|
||||||
|
<div className="p-12 text-center space-y-2">
|
||||||
|
<Bell className="h-8 w-8 text-gray-300 mx-auto" />
|
||||||
|
<p className="text-sm font-medium text-gray-600">
|
||||||
|
No notifications match your filters.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="divide-y divide-gray-100">
|
||||||
|
{items.map((n) => (
|
||||||
|
<div
|
||||||
|
key={n.id}
|
||||||
|
className={`p-4 flex flex-wrap items-start justify-between gap-3 transition-colors ${
|
||||||
|
n.is_read ? "bg-white" : "bg-blue-50/40"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-start gap-3 flex-1 min-w-0">
|
||||||
|
<SeverityBadge severity={n.severity} />
|
||||||
|
<div className="min-w-0 flex-1 space-y-1">
|
||||||
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
|
<span
|
||||||
|
className={`text-sm ${
|
||||||
|
n.is_read
|
||||||
|
? "font-medium text-gray-800"
|
||||||
|
: "font-semibold text-gray-900"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{n.title}
|
||||||
|
</span>
|
||||||
|
<Badge variant="outline" className="text-[10px]">
|
||||||
|
{TYPE_LABELS[n.type] ?? n.type}
|
||||||
|
</Badge>
|
||||||
|
{!n.is_read && <Badge variant="info">Unread</Badge>}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-600">{n.message}</p>
|
||||||
|
<div className="flex flex-wrap items-center gap-4 text-[11px] text-gray-500 pt-0.5">
|
||||||
|
<span>Due: {formatDate(n.due_date)}</span>
|
||||||
|
<span>Created: {formatDateTime(n.created_at)}</span>
|
||||||
|
{n.is_read && n.read_at && (
|
||||||
|
<span>Read: {formatDateTime(n.read_at)}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 shrink-0">
|
||||||
|
{!n.is_read && (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => markReadMutation.mutate(n.id)}
|
||||||
|
title="Mark as read"
|
||||||
|
>
|
||||||
|
<Check className="h-3.5 w-3.5 mr-1" />
|
||||||
|
Mark Read
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => handleOpen(n)}
|
||||||
|
>
|
||||||
|
<ExternalLink className="h-3.5 w-3.5 mr-1" />
|
||||||
|
Open
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SeverityBadge({ severity }: { severity: string }) {
|
||||||
|
if (severity === "red") {
|
||||||
|
return (
|
||||||
|
<span className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-red-100 text-red-800 border border-red-200 text-[11px] font-semibold uppercase shrink-0">
|
||||||
|
<AlertTriangle className="h-3.5 w-3.5" />
|
||||||
|
Red
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (severity === "yellow") {
|
||||||
|
return (
|
||||||
|
<span className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-amber-100 text-amber-800 border border-amber-200 text-[11px] font-semibold uppercase shrink-0">
|
||||||
|
<Clock className="h-3.5 w-3.5" />
|
||||||
|
Yellow
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<span className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-blue-100 text-blue-800 border border-blue-200 text-[11px] font-semibold uppercase shrink-0">
|
||||||
|
<Info className="h-3.5 w-3.5" />
|
||||||
|
Info
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
// Stub pages — replaced phase by phase
|
// Stub pages — replaced phase by phase
|
||||||
import { Link } from "react-router-dom";
|
|
||||||
|
|
||||||
interface StubProps {
|
interface StubProps {
|
||||||
title: string;
|
title: string;
|
||||||
@@ -24,21 +23,6 @@ function StubPage({ title, phase, description, children }: StubProps) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const DashboardPage = () => (
|
|
||||||
<StubPage title="Dashboard" phase={6} description="KPI cards, charts, and needs-attention panel.">
|
|
||||||
<div className="mt-6">
|
|
||||||
<Link
|
|
||||||
to="/demo"
|
|
||||||
className="inline-flex items-center gap-1 text-sm font-medium text-[#1e3a8a] hover:underline"
|
|
||||||
>
|
|
||||||
Open Phase 0 DataTable Demo →
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
</StubPage>
|
|
||||||
);
|
|
||||||
export const ReportsPage = () => (
|
export const ReportsPage = () => (
|
||||||
<StubPage title="Reports & Exports" phase={7} description="8 reports with Excel export." />
|
<StubPage title="Reports & Exports" phase={7} description="8 reports with Excel export." />
|
||||||
);
|
);
|
||||||
export const NotificationsPage = () => (
|
|
||||||
<StubPage title="Notifications" phase={6} description="In-app alerts and notification centre." />
|
|
||||||
);
|
|
||||||
|
|||||||
@@ -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<typeof import("recharts")>("recharts");
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
|
ResponsiveContainer: ({ children }: { children: React.ReactNode }) => (
|
||||||
|
<div style={{ width: 600, height: 240 }}>{children}</div>
|
||||||
|
),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
function renderWithProviders(ui: React.ReactNode) {
|
||||||
|
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||||
|
return render(
|
||||||
|
<QueryClientProvider client={qc}>
|
||||||
|
<MemoryRouter>{ui}</MemoryRouter>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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(<DashboardPage />);
|
||||||
|
|
||||||
|
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(<NotificationsPage />);
|
||||||
|
|
||||||
|
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(<CalibrationReminderModal />);
|
||||||
|
|
||||||
|
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");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach } from "vitest";
|
|||||||
import { render, screen } from "@testing-library/react";
|
import { render, screen } from "@testing-library/react";
|
||||||
import { MemoryRouter } from "react-router-dom";
|
import { MemoryRouter } from "react-router-dom";
|
||||||
import { Sidebar } from "@/components/layout/Sidebar";
|
import { Sidebar } from "@/components/layout/Sidebar";
|
||||||
import { DashboardPage } from "@/pages/stubs";
|
import { ReportsPage } from "@/pages/stubs";
|
||||||
import { DataTableDemoPage } from "@/pages/DataTableDemoPage";
|
import { DataTableDemoPage } from "@/pages/DataTableDemoPage";
|
||||||
import { useAuthStore } from "@/hooks/useAuth";
|
import { useAuthStore } from "@/hooks/useAuth";
|
||||||
|
|
||||||
@@ -100,15 +100,14 @@ describe("Phase 1 Frontend Smoke Tests", () => {
|
|||||||
expect(screen.getByText("Contracts & Warranty")).toBeInTheDocument();
|
expect(screen.getByText("Contracts & Warranty")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("renders DashboardPage with clickable link to /demo", () => {
|
it("renders ReportsPage stub coming in Phase 7", () => {
|
||||||
render(
|
render(
|
||||||
<MemoryRouter>
|
<MemoryRouter>
|
||||||
<DashboardPage />
|
<ReportsPage />
|
||||||
</MemoryRouter>
|
</MemoryRouter>
|
||||||
);
|
);
|
||||||
const link = screen.getByRole("link", { name: /Open Phase 0 DataTable Demo/i });
|
expect(screen.getByText("Reports & Exports")).toBeInTheDocument();
|
||||||
expect(link).toBeInTheDocument();
|
expect(screen.getByText(/Coming in Phase 7/i)).toBeInTheDocument();
|
||||||
expect(link).toHaveAttribute("href", "/demo");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("renders DataTableDemoPage with mock rows", () => {
|
it("renders DataTableDemoPage with mock rows", () => {
|
||||||
|
|||||||
@@ -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"}
|
{"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"}
|
||||||
Reference in New Issue
Block a user