phase-6: alerts engine, scheduler, notifications, calibration popup, and dashboard

This commit is contained in:
Atharv1705
2026-11-12 14:39:22 +05:30
parent ba4777b182
commit aec1b6ad41
25 changed files with 2743 additions and 58 deletions
@@ -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 &amp; Mark Read
</Button>
</div>
</div>
</div>
</Modal>
);
}
+100
View File
@@ -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>
);
}
+274 -23
View File
@@ -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" />;
}