phase-6: alerts engine, scheduler, notifications, calibration popup, and dashboard
This commit is contained in:
@@ -17,11 +17,10 @@ import { ContractsPage } from "@/pages/ContractsPage";
|
||||
import { InsurancePage } from "@/pages/InsurancePage";
|
||||
import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage";
|
||||
import { VisitsPage } from "@/pages/VisitsPage";
|
||||
import {
|
||||
DashboardPage,
|
||||
ReportsPage,
|
||||
NotificationsPage,
|
||||
} from "@/pages/stubs";
|
||||
import { DashboardPage } from "@/pages/DashboardPage";
|
||||
import { NotificationsPage } from "@/pages/NotificationsPage";
|
||||
import { ReportsPage } from "@/pages/stubs";
|
||||
import { ToastProvider } from "@/components/ToastProvider";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can, type Capability } from "@/lib/permissions";
|
||||
|
||||
@@ -127,9 +126,11 @@ function AppRoutes() {
|
||||
export default function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<AppRoutes />
|
||||
</BrowserRouter>
|
||||
<ToastProvider>
|
||||
<BrowserRouter>
|
||||
<AppRoutes />
|
||||
</BrowserRouter>
|
||||
</ToastProvider>
|
||||
</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 { Sidebar } from "./Sidebar";
|
||||
import { TopBar } from "./TopBar";
|
||||
import { CalibrationReminderModal } from "@/components/CalibrationReminderModal";
|
||||
|
||||
export function AppShell() {
|
||||
return (
|
||||
@@ -12,6 +13,7 @@ export function AppShell() {
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
<CalibrationReminderModal />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,28 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { Search, Bell, ChevronDown, User, LogOut, CalendarClock, RotateCcw } from "lucide-react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Search,
|
||||
Bell,
|
||||
ChevronDown,
|
||||
User,
|
||||
LogOut,
|
||||
CalendarClock,
|
||||
RotateCcw,
|
||||
Play,
|
||||
CheckCheck,
|
||||
AlertTriangle,
|
||||
Info,
|
||||
Clock,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { formatDate, formatRelative } from "@/lib/format";
|
||||
import { ROLE_LABELS } from "@/lib/permissions";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { settingsApi } from "@/api/settings";
|
||||
import { notificationsApi, type NotificationItem } from "@/api/notifications";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { toast } from "@/components/ToastProvider";
|
||||
|
||||
interface TopBarProps {
|
||||
title?: string;
|
||||
@@ -19,27 +34,142 @@ export function TopBar({ title }: TopBarProps) {
|
||||
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
|
||||
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [bellOpen, setBellOpen] = useState(false);
|
||||
const [dateInput, setDateInput] = useState(demoAsOfDate ?? "");
|
||||
const [savingDate, setSavingDate] = useState(false);
|
||||
const [runningAlerts, setRunningAlerts] = useState(false);
|
||||
|
||||
const bellContainerRef = useRef<HTMLDivElement>(null);
|
||||
const seenIdsRef = useRef<Set<number> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setDateInput(demoAsOfDate ?? "");
|
||||
}, [demoAsOfDate]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleOutside(e: MouseEvent) {
|
||||
if (
|
||||
bellContainerRef.current &&
|
||||
!bellContainerRef.current.contains(e.target as Node)
|
||||
) {
|
||||
setBellOpen(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", handleOutside);
|
||||
return () => document.removeEventListener("mousedown", handleOutside);
|
||||
}, []);
|
||||
|
||||
const isAdmin = user?.role === "system_admin";
|
||||
|
||||
const bellQuery = useQuery({
|
||||
queryKey: ["notifications", "bell", user?.id],
|
||||
queryFn: () => notificationsApi.list({ limit: 10 }),
|
||||
enabled: Boolean(user),
|
||||
refetchInterval: 60_000,
|
||||
});
|
||||
|
||||
const bellItems = bellQuery.data?.items ?? [];
|
||||
const unreadCount = bellQuery.data?.unread_count ?? 0;
|
||||
|
||||
// Detect newly arrived unread notifications while app is open
|
||||
useEffect(() => {
|
||||
if (!bellQuery.data) return;
|
||||
const currentIds = new Set(bellItems.map((n) => n.id));
|
||||
if (seenIdsRef.current === null) {
|
||||
seenIdsRef.current = currentIds;
|
||||
return;
|
||||
}
|
||||
const newlyArrived = bellItems.filter(
|
||||
(n) => !n.is_read && !seenIdsRef.current!.has(n.id)
|
||||
);
|
||||
for (const n of newlyArrived.slice(0, 2)) {
|
||||
if (n.severity === "red") {
|
||||
toast.error(n.title, n.message);
|
||||
} else if (n.severity === "yellow") {
|
||||
toast.warning(n.title, n.message);
|
||||
} else {
|
||||
toast.info(n.title, n.message);
|
||||
}
|
||||
}
|
||||
seenIdsRef.current = currentIds;
|
||||
}, [bellQuery.data, bellItems]);
|
||||
|
||||
const markReadMutation = useMutation({
|
||||
mutationFn: (id: number) => notificationsApi.markRead(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["notifications"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
|
||||
},
|
||||
});
|
||||
|
||||
const markAllReadMutation = useMutation({
|
||||
mutationFn: () => notificationsApi.markAllRead(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["notifications"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
|
||||
toast.success("All notifications marked as read");
|
||||
},
|
||||
});
|
||||
|
||||
async function invalidateDateSensitiveQueries() {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ["notifications"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["dashboard"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["pm-records"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["calibration-records"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["contracts"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["warranties"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["insurance"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["demo-equipment"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["assets"] }),
|
||||
queryClient.invalidateQueries(),
|
||||
]);
|
||||
}
|
||||
|
||||
async function handleDemoDateUpdate(newDate: string | null) {
|
||||
setSavingDate(true);
|
||||
try {
|
||||
const res = await settingsApi.setDemoDate(newDate);
|
||||
setDemoAsOfDate(res.demo_as_of_date ?? null);
|
||||
setDateInput(res.demo_as_of_date ?? "");
|
||||
await queryClient.invalidateQueries();
|
||||
await invalidateDateSensitiveQueries();
|
||||
toast.info(
|
||||
res.demo_as_of_date
|
||||
? `Demo clock set to ${formatDate(res.demo_as_of_date)}`
|
||||
: "Demo clock reset to today"
|
||||
);
|
||||
} finally {
|
||||
setSavingDate(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRunAlertsNow() {
|
||||
setRunningAlerts(true);
|
||||
try {
|
||||
const res = await notificationsApi.runAlertsNow();
|
||||
await queryClient.invalidateQueries({ queryKey: ["notifications"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["dashboard"] });
|
||||
toast.success(
|
||||
`Alert check completed (${formatDate(res.evaluated_today)})`,
|
||||
`${res.created} new alert${res.created === 1 ? "" : "s"} created.`
|
||||
);
|
||||
} catch {
|
||||
toast.error("Failed to run alert check");
|
||||
} finally {
|
||||
setRunningAlerts(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleNotificationClick(n: NotificationItem) {
|
||||
setBellOpen(false);
|
||||
if (!n.is_read) {
|
||||
markReadMutation.mutate(n.id);
|
||||
}
|
||||
if (n.link_url) {
|
||||
navigate(n.link_url);
|
||||
}
|
||||
}
|
||||
|
||||
function handleSignOut() {
|
||||
setMenuOpen(false);
|
||||
logout();
|
||||
@@ -49,7 +179,11 @@ export function TopBar({ title }: TopBarProps) {
|
||||
return (
|
||||
<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 */}
|
||||
{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 */}
|
||||
<div className={cn("relative", title ? "" : "flex-1 max-w-xs sm:max-w-sm")}>
|
||||
@@ -69,10 +203,12 @@ export function TopBar({ title }: TopBarProps) {
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* Admin Demo Clock Picker */}
|
||||
{/* Admin Demo Clock Picker + Run Alert Check */}
|
||||
{isAdmin && (
|
||||
<div className="flex items-center gap-1.5 bg-gray-50 border border-gray-200 rounded-md px-2 py-1 text-xs">
|
||||
<span className="text-gray-500 font-medium hidden md:inline">As of Date:</span>
|
||||
<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>
|
||||
<input
|
||||
type="date"
|
||||
aria-label="As of Date"
|
||||
@@ -100,19 +236,116 @@ export function TopBar({ title }: TopBarProps) {
|
||||
<span className="hidden lg:inline">Reset</span>
|
||||
</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>
|
||||
)}
|
||||
|
||||
{/* Notification bell placeholder */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate("/notifications")}
|
||||
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-500 ml-auto"
|
||||
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" />
|
||||
</button>
|
||||
{/* Live Notification Bell & Dropdown */}
|
||||
<div ref={bellContainerRef} className="relative ml-auto">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBellOpen((o) => !o)}
|
||||
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-600"
|
||||
aria-label="Notifications"
|
||||
>
|
||||
<Bell className="h-5 w-5" />
|
||||
{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 */}
|
||||
<div className="relative">
|
||||
@@ -125,7 +358,9 @@ export function TopBar({ title }: TopBarProps) {
|
||||
<User className="h-4 w-4" />
|
||||
</div>
|
||||
<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">
|
||||
{user?.role ? ROLE_LABELS[user.role] : ""}
|
||||
{user?.department_name ? ` • ${user.department_name}` : ""}
|
||||
@@ -137,11 +372,17 @@ export function TopBar({ title }: TopBarProps) {
|
||||
{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="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="flex items-center gap-1.5 flex-wrap pt-0.5">
|
||||
{user?.role && <Badge variant="info">{ROLE_LABELS[user.role]}</Badge>}
|
||||
{user?.department_name && <Badge variant="outline">{user.department_name}</Badge>}
|
||||
{user?.role && (
|
||||
<Badge variant="info">{ROLE_LABELS[user.role]}</Badge>
|
||||
)}
|
||||
{user?.department_name && (
|
||||
<Badge variant="outline">{user.department_name}</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
@@ -158,3 +399,13 @@ export function TopBar({ title }: TopBarProps) {
|
||||
</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
|
||||
import { Link } from "react-router-dom";
|
||||
|
||||
interface StubProps {
|
||||
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 = () => (
|
||||
<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 { MemoryRouter } from "react-router-dom";
|
||||
import { Sidebar } from "@/components/layout/Sidebar";
|
||||
import { DashboardPage } from "@/pages/stubs";
|
||||
import { ReportsPage } from "@/pages/stubs";
|
||||
import { DataTableDemoPage } from "@/pages/DataTableDemoPage";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
@@ -100,15 +100,14 @@ describe("Phase 1 Frontend Smoke Tests", () => {
|
||||
expect(screen.getByText("Contracts & Warranty")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders DashboardPage with clickable link to /demo", () => {
|
||||
it("renders ReportsPage stub coming in Phase 7", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<DashboardPage />
|
||||
<ReportsPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
const link = screen.getByRole("link", { name: /Open Phase 0 DataTable Demo/i });
|
||||
expect(link).toBeInTheDocument();
|
||||
expect(link).toHaveAttribute("href", "/demo");
|
||||
expect(screen.getByText("Reports & Exports")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Coming in Phase 7/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders DataTableDemoPage with mock rows", () => {
|
||||
|
||||
@@ -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