Files
poona-ams/frontend/src/components/layout/TopBar.tsx
T

412 lines
15 KiB
TypeScript

import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
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, 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;
}
export function TopBar({ title }: TopBarProps) {
const navigate = useNavigate();
const queryClient = useQueryClient();
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 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();
navigate("/login", { replace: true });
}
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>
)}
{/* Global search placeholder */}
<div className={cn("relative", title ? "" : "flex-1 max-w-xs sm:max-w-sm")}>
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
<input
type="text"
placeholder="Search assets, complaints... (Phase 8)"
className="w-full pl-9 pr-4 py-1.5 text-sm border border-gray-200 rounded-md bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:bg-white"
/>
</div>
{/* Active Demo Date Pill */}
{demoAsOfDate && (
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-amber-100 text-amber-800 border border-amber-300">
<CalendarClock className="h-3.5 w-3.5" />
Demo Date: {formatDate(demoAsOfDate)}
</span>
)}
{/* 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 flex-wrap">
<span className="text-gray-500 font-medium hidden md:inline">
As of Date:
</span>
<input
type="date"
aria-label="As of Date"
value={dateInput}
onChange={(e) => setDateInput(e.target.value)}
className="border border-gray-200 rounded px-1.5 py-0.5 text-xs bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
/>
<button
type="button"
disabled={savingDate || !dateInput}
onClick={() => handleDemoDateUpdate(dateInput || null)}
className="px-2 py-0.5 rounded bg-[#1e3a8a] text-white hover:bg-[#1e3480] disabled:opacity-40"
>
Apply
</button>
{demoAsOfDate && (
<button
type="button"
disabled={savingDate}
onClick={() => handleDemoDateUpdate(null)}
title="Reset to Today"
className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded border border-gray-300 bg-white text-gray-600 hover:bg-gray-100 disabled:opacity-40"
>
<RotateCcw className="h-3 w-3" />
<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>
)}
{/* 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">
<button
type="button"
onClick={() => setMenuOpen((o) => !o)}
className="flex items-center gap-2 px-2.5 py-1.5 rounded-md hover:bg-gray-100 text-sm text-gray-700"
>
<div className="h-7 w-7 rounded-full bg-[#1e3a8a] flex items-center justify-center text-white text-xs font-bold shrink-0">
<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="text-[10px] text-gray-500">
{user?.role ? ROLE_LABELS[user.role] : ""}
{user?.department_name ? ` • ${user.department_name}` : ""}
</span>
</div>
<ChevronDown className="h-4 w-4 text-gray-400" />
</button>
{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-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>
)}
</div>
</div>
<button
type="button"
onClick={handleSignOut}
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-red-600 hover:bg-red-50 text-left"
>
<LogOut className="h-4 w-4" />
Sign Out
</button>
</div>
)}
</div>
</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" />;
}