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