phase-8: polish, global search, audit log, packaging, and demo docs
This commit is contained in:
@@ -21,6 +21,7 @@ import { DashboardPage } from "@/pages/DashboardPage";
|
||||
import { NotificationsPage } from "@/pages/NotificationsPage";
|
||||
import { ReportsPage } from "@/pages/ReportsPage";
|
||||
import { ReportDetailPage } from "@/pages/ReportDetailPage";
|
||||
import { AuditLogsPage } from "@/pages/AuditLogsPage";
|
||||
import { ToastProvider } from "@/components/ToastProvider";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can, type Capability } from "@/lib/permissions";
|
||||
@@ -110,6 +111,14 @@ function AppRoutes() {
|
||||
</RoleGuard>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/audit-logs"
|
||||
element={
|
||||
<RoleGuard capability="manage_admin">
|
||||
<AuditLogsPage />
|
||||
</RoleGuard>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/settings"
|
||||
element={
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export interface AuditLogItem {
|
||||
id: number;
|
||||
entity_type: string;
|
||||
entity_id: number;
|
||||
action: string;
|
||||
changes_json: string | null;
|
||||
by_user_id: number | null;
|
||||
by_user_name: string | null;
|
||||
at: string;
|
||||
}
|
||||
|
||||
export interface AuditLogsResponse {
|
||||
items: AuditLogItem[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface AuditLogFilters {
|
||||
entity_type?: string;
|
||||
by_user_id?: number;
|
||||
action?: string;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
q?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export const auditApi = {
|
||||
list: (filters: AuditLogFilters = {}) => {
|
||||
const params = new URLSearchParams();
|
||||
if (filters.entity_type) params.set("entity_type", filters.entity_type);
|
||||
if (filters.by_user_id != null) {
|
||||
params.set("by_user_id", String(filters.by_user_id));
|
||||
}
|
||||
if (filters.action) params.set("action", filters.action);
|
||||
if (filters.date_from) params.set("date_from", filters.date_from);
|
||||
if (filters.date_to) params.set("date_to", filters.date_to);
|
||||
if (filters.q) params.set("q", filters.q);
|
||||
if (filters.page != null) params.set("page", String(filters.page));
|
||||
params.set("page_size", String(filters.page_size ?? 200));
|
||||
return api.get<AuditLogsResponse>(`/audit-logs?${params.toString()}`);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export interface SearchAssetItem {
|
||||
id: number;
|
||||
asset_code: string;
|
||||
name: string;
|
||||
serial_no: string | null;
|
||||
department_name: string | null;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface SearchComplaintItem {
|
||||
id: number;
|
||||
complaint_no: string;
|
||||
asset_code: string | null;
|
||||
asset_name: string | null;
|
||||
department_name: string | null;
|
||||
call_status: string;
|
||||
priority: string;
|
||||
}
|
||||
|
||||
export interface GlobalSearchResponse {
|
||||
assets: SearchAssetItem[];
|
||||
complaints: SearchComplaintItem[];
|
||||
}
|
||||
|
||||
export const searchApi = {
|
||||
query: (q: string) => {
|
||||
const params = new URLSearchParams({ q });
|
||||
return api.get<GlobalSearchResponse>(`/search?${params.toString()}`);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
import { AlertTriangle } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export interface ConfirmDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel?: string;
|
||||
cancelLabel?: string;
|
||||
variant?: "danger" | "default";
|
||||
loading?: boolean;
|
||||
onConfirm: () => void | Promise<void>;
|
||||
}
|
||||
|
||||
export function ConfirmDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
message,
|
||||
confirmLabel = "Confirm",
|
||||
cancelLabel = "Cancel",
|
||||
variant = "danger",
|
||||
loading = false,
|
||||
onConfirm,
|
||||
}: ConfirmDialogProps) {
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!loading) onOpenChange(next);
|
||||
}}
|
||||
title={title}
|
||||
description={message}
|
||||
className="max-w-md"
|
||||
>
|
||||
<div className="space-y-5">
|
||||
{variant === "danger" && (
|
||||
<div className="flex items-start gap-3 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800">
|
||||
<AlertTriangle className="h-4 w-4 shrink-0 text-red-600 mt-0.5" />
|
||||
<span>This action cannot be undone.</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-end gap-2 pt-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
{cancelLabel}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={variant === "danger" ? "danger" : "default"}
|
||||
size="sm"
|
||||
loading={loading}
|
||||
onClick={() => void onConfirm()}
|
||||
>
|
||||
{confirmLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,20 @@
|
||||
import { useState } from "react";
|
||||
import { Outlet } from "react-router-dom";
|
||||
import { Sidebar } from "./Sidebar";
|
||||
import { TopBar } from "./TopBar";
|
||||
import { CalibrationReminderModal } from "@/components/CalibrationReminderModal";
|
||||
|
||||
export function AppShell() {
|
||||
const [mobileNavOpen, setMobileNavOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen bg-gray-50">
|
||||
<Sidebar />
|
||||
<Sidebar
|
||||
mobileOpen={mobileNavOpen}
|
||||
onClose={() => setMobileNavOpen(false)}
|
||||
/>
|
||||
<div className="flex-1 flex flex-col min-w-0">
|
||||
<TopBar />
|
||||
<TopBar onMenuClick={() => setMobileNavOpen(true)} />
|
||||
<main className="flex-1 p-6 overflow-auto">
|
||||
<Outlet />
|
||||
</main>
|
||||
|
||||
@@ -12,8 +12,10 @@ import {
|
||||
BarChart3,
|
||||
Bell,
|
||||
Database,
|
||||
History,
|
||||
Settings,
|
||||
ChevronRight,
|
||||
X,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -71,10 +73,16 @@ const NAV_ITEMS: NavItem[] = [
|
||||
},
|
||||
{ to: "/notifications", label: "Notifications", icon: Bell },
|
||||
{ to: "/masters", label: "Masters", icon: Database, capability: "manage_admin" },
|
||||
{ to: "/audit-logs", label: "Audit Log", icon: History, capability: "manage_admin" },
|
||||
{ to: "/settings", label: "Settings", icon: Settings, capability: "manage_admin" },
|
||||
];
|
||||
|
||||
export function Sidebar() {
|
||||
interface SidebarProps {
|
||||
mobileOpen?: boolean;
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
export function Sidebar({ mobileOpen, onClose }: SidebarProps = {}) {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const role = user?.role;
|
||||
|
||||
@@ -84,10 +92,23 @@ export function Sidebar() {
|
||||
return true;
|
||||
});
|
||||
|
||||
return (
|
||||
<aside className="w-56 lg:w-64 shrink-0 min-h-screen bg-[#1e3a8a] text-white flex flex-col">
|
||||
const asideContent = (
|
||||
<aside
|
||||
aria-label="Primary Navigation"
|
||||
className="w-56 lg:w-64 shrink-0 min-h-screen bg-[#1e3a8a] text-white flex flex-col"
|
||||
>
|
||||
{/* Logo */}
|
||||
<div className="px-4 py-4 border-b border-blue-700 space-y-2">
|
||||
<div className="px-4 py-4 border-b border-blue-700 space-y-2 relative">
|
||||
{onClose && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Close navigation menu"
|
||||
className="md:hidden absolute right-2 top-2 p-1 rounded text-blue-200 hover:text-white hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
<div className="bg-white rounded-lg p-2">
|
||||
<img
|
||||
src="/logo.jpg"
|
||||
@@ -107,9 +128,10 @@ export function Sidebar() {
|
||||
key={to}
|
||||
to={to}
|
||||
end={to === "/"}
|
||||
onClick={() => onClose?.()}
|
||||
className={({ isActive }) =>
|
||||
cn(
|
||||
"flex items-center gap-3 px-3 py-2.5 rounded-md text-sm transition-colors group",
|
||||
"flex items-center gap-3 px-3 py-2.5 rounded-md text-sm transition-colors group focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white",
|
||||
isActive
|
||||
? "bg-blue-700 text-white"
|
||||
: "text-blue-100 hover:bg-blue-700/50 hover:text-white"
|
||||
@@ -125,8 +147,29 @@ export function Sidebar() {
|
||||
|
||||
{/* Footer */}
|
||||
<div className="px-4 py-3 border-t border-blue-700 text-xs text-blue-300">
|
||||
Phase 1 — Foundation
|
||||
Poona Hospital AMS • v1.0
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
|
||||
// When controlled by AppShell, hide desktop rail on small screens and render slide-over drawer when open
|
||||
if (mobileOpen === undefined) {
|
||||
return asideContent;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="hidden md:flex shrink-0">{asideContent}</div>
|
||||
{mobileOpen && (
|
||||
<div className="fixed inset-0 z-40 flex md:hidden">
|
||||
<div
|
||||
className="fixed inset-0 bg-black/40"
|
||||
onClick={onClose}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div className="relative z-50 flex">{asideContent}</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,10 @@ import {
|
||||
AlertTriangle,
|
||||
Info,
|
||||
Clock,
|
||||
Menu,
|
||||
X,
|
||||
Package,
|
||||
AlertCircle,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatDate, formatRelative } from "@/lib/format";
|
||||
@@ -21,14 +25,17 @@ import { ROLE_LABELS } from "@/lib/permissions";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { settingsApi } from "@/api/settings";
|
||||
import { notificationsApi, type NotificationItem } from "@/api/notifications";
|
||||
import { searchApi } from "@/api/search";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { AssetStatusBadge, CallStatusBadge } from "@/components/StatusBadge";
|
||||
import { toast } from "@/components/ToastProvider";
|
||||
|
||||
interface TopBarProps {
|
||||
title?: string;
|
||||
onMenuClick?: () => void;
|
||||
}
|
||||
|
||||
export function TopBar({ title }: TopBarProps) {
|
||||
export function TopBar({ title, onMenuClick }: TopBarProps) {
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
|
||||
@@ -39,26 +46,72 @@ export function TopBar({ title }: TopBarProps) {
|
||||
const [savingDate, setSavingDate] = useState(false);
|
||||
const [runningAlerts, setRunningAlerts] = useState(false);
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
const [debouncedQuery, setDebouncedQuery] = useState("");
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
|
||||
const bellContainerRef = useRef<HTMLDivElement>(null);
|
||||
const searchContainerRef = useRef<HTMLDivElement>(null);
|
||||
const userMenuRef = useRef<HTMLDivElement>(null);
|
||||
const seenIdsRef = useRef<Set<number> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setDateInput(demoAsOfDate ?? "");
|
||||
}, [demoAsOfDate]);
|
||||
|
||||
useEffect(() => {
|
||||
const trimmed = searchInput.trim();
|
||||
if (trimmed.length < 2) {
|
||||
setDebouncedQuery("");
|
||||
return;
|
||||
}
|
||||
const timer = window.setTimeout(() => {
|
||||
setDebouncedQuery(trimmed);
|
||||
}, 200);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [searchInput]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleOutside(e: MouseEvent) {
|
||||
const target = e.target as Node;
|
||||
if (
|
||||
bellContainerRef.current &&
|
||||
!bellContainerRef.current.contains(e.target as Node)
|
||||
!bellContainerRef.current.contains(target)
|
||||
) {
|
||||
setBellOpen(false);
|
||||
}
|
||||
if (
|
||||
searchContainerRef.current &&
|
||||
!searchContainerRef.current.contains(target)
|
||||
) {
|
||||
setSearchOpen(false);
|
||||
}
|
||||
if (userMenuRef.current && !userMenuRef.current.contains(target)) {
|
||||
setMenuOpen(false);
|
||||
}
|
||||
}
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") {
|
||||
setSearchOpen(false);
|
||||
setBellOpen(false);
|
||||
setMenuOpen(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", handleOutside);
|
||||
return () => document.removeEventListener("mousedown", handleOutside);
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", handleOutside);
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const searchQuery = useQuery({
|
||||
queryKey: ["global-search", debouncedQuery, user?.id],
|
||||
queryFn: () => searchApi.query(debouncedQuery),
|
||||
enabled: Boolean(user) && debouncedQuery.length >= 2,
|
||||
staleTime: 10_000,
|
||||
});
|
||||
|
||||
const isAdmin = user?.role === "system_admin";
|
||||
|
||||
const bellQuery = useQuery({
|
||||
@@ -178,6 +231,18 @@ 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">
|
||||
{/* Mobile nav toggle */}
|
||||
{onMenuClick && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onMenuClick}
|
||||
aria-label="Open navigation menu"
|
||||
className="md:hidden p-1.5 rounded-md text-gray-600 hover:bg-gray-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
>
|
||||
<Menu className="h-5 w-5" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Page title */}
|
||||
{title && (
|
||||
<h1 className="font-semibold text-gray-800 text-sm truncate mr-auto">
|
||||
@@ -185,14 +250,151 @@ export function TopBar({ title }: TopBarProps) {
|
||||
</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" />
|
||||
{/* Live Global Quick Search */}
|
||||
<div
|
||||
ref={searchContainerRef}
|
||||
className={cn("relative", title ? "w-64 sm:w-80" : "flex-1 max-w-xs sm:max-w-md")}
|
||||
>
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
|
||||
<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"
|
||||
aria-label="Search assets and complaints"
|
||||
value={searchInput}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
setSearchInput(val);
|
||||
setSearchOpen(val.trim().length >= 2);
|
||||
}}
|
||||
onFocus={() => {
|
||||
if (searchInput.trim().length >= 2) {
|
||||
setSearchOpen(true);
|
||||
}
|
||||
}}
|
||||
placeholder="Search assets, complaints..."
|
||||
className="w-full pl-9 pr-8 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"
|
||||
/>
|
||||
{searchInput && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Clear search"
|
||||
onClick={() => {
|
||||
setSearchInput("");
|
||||
setDebouncedQuery("");
|
||||
setSearchOpen(false);
|
||||
}}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 p-0.5 rounded text-gray-400 hover:text-gray-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{searchOpen && searchInput.trim().length >= 2 && (
|
||||
<div
|
||||
role="listbox"
|
||||
aria-label="Global search results"
|
||||
className="absolute left-0 right-0 mt-1.5 bg-white border border-gray-200 rounded-lg shadow-xl z-30 max-h-96 overflow-y-auto divide-y divide-gray-100"
|
||||
>
|
||||
{searchQuery.isFetching && !searchQuery.data ? (
|
||||
<div className="px-4 py-6 text-center text-xs text-gray-500">
|
||||
Searching assets & complaints...
|
||||
</div>
|
||||
) : searchQuery.isError ? (
|
||||
<div className="px-4 py-5 text-center text-xs text-red-600">
|
||||
Unable to load search results.
|
||||
</div>
|
||||
) : (
|
||||
(() => {
|
||||
const assets = searchQuery.data?.assets ?? [];
|
||||
const complaints = searchQuery.data?.complaints ?? [];
|
||||
if (assets.length === 0 && complaints.length === 0) {
|
||||
return (
|
||||
<div className="px-4 py-6 text-center text-xs text-gray-500">
|
||||
No matching assets or complaints found.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{assets.length > 0 && (
|
||||
<div className="py-1.5">
|
||||
<div className="px-3 py-1 text-[11px] font-semibold uppercase tracking-wide text-gray-500 flex items-center gap-1.5">
|
||||
<Package className="h-3.5 w-3.5 text-[#1e3a8a]" />
|
||||
Assets ({assets.length})
|
||||
</div>
|
||||
{assets.map((asset) => (
|
||||
<button
|
||||
key={`asset-${asset.id}`}
|
||||
type="button"
|
||||
role="option"
|
||||
onClick={() => {
|
||||
setSearchOpen(false);
|
||||
navigate(`/assets/${asset.id}`);
|
||||
}}
|
||||
className="w-full text-left px-3 py-2 hover:bg-blue-50/70 focus-visible:outline-none focus-visible:bg-blue-50 flex items-center justify-between gap-2 transition-colors"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-xs font-semibold text-[#1e3a8a]">
|
||||
{asset.asset_code}
|
||||
</span>
|
||||
<span className="text-xs font-medium text-gray-900 truncate">
|
||||
{asset.name}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-[11px] text-gray-500 truncate mt-0.5">
|
||||
{asset.department_name ?? "No Dept"}
|
||||
{asset.serial_no ? ` • SN: ${asset.serial_no}` : ""}
|
||||
</div>
|
||||
</div>
|
||||
<AssetStatusBadge status={asset.status} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{complaints.length > 0 && (
|
||||
<div className="py-1.5">
|
||||
<div className="px-3 py-1 text-[11px] font-semibold uppercase tracking-wide text-gray-500 flex items-center gap-1.5">
|
||||
<AlertCircle className="h-3.5 w-3.5 text-red-600" />
|
||||
Complaints ({complaints.length})
|
||||
</div>
|
||||
{complaints.map((c) => (
|
||||
<button
|
||||
key={`complaint-${c.id}`}
|
||||
type="button"
|
||||
role="option"
|
||||
onClick={() => {
|
||||
setSearchOpen(false);
|
||||
navigate(`/complaints/${c.id}`);
|
||||
}}
|
||||
className="w-full text-left px-3 py-2 hover:bg-blue-50/70 focus-visible:outline-none focus-visible:bg-blue-50 flex items-center justify-between gap-2 transition-colors"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-xs font-semibold text-gray-900">
|
||||
{c.complaint_no}
|
||||
</span>
|
||||
<span className="text-xs text-gray-700 truncate">
|
||||
{c.asset_code
|
||||
? `${c.asset_code}${c.asset_name ? ` — ${c.asset_name}` : ""}`
|
||||
: c.asset_name ?? "Equipment"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-[11px] text-gray-500 truncate mt-0.5">
|
||||
{c.department_name ?? "—"} • Priority: {c.priority}
|
||||
</div>
|
||||
</div>
|
||||
<CallStatusBadge status={c.call_status} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
})()
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Active Demo Date Pill */}
|
||||
@@ -254,8 +456,9 @@ export function TopBar({ title }: TopBarProps) {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBellOpen((o) => !o)}
|
||||
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-600"
|
||||
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
aria-label="Notifications"
|
||||
aria-expanded={bellOpen}
|
||||
>
|
||||
<Bell className="h-5 w-5" />
|
||||
{unreadCount > 0 && (
|
||||
@@ -348,11 +551,13 @@ export function TopBar({ title }: TopBarProps) {
|
||||
</div>
|
||||
|
||||
{/* User menu */}
|
||||
<div className="relative">
|
||||
<div ref={userMenuRef} 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"
|
||||
aria-label="User menu"
|
||||
aria-expanded={menuOpen}
|
||||
className="flex items-center gap-2 px-2.5 py-1.5 rounded-md hover:bg-gray-100 text-sm text-gray-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
>
|
||||
<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" />
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { History, Search, RotateCcw, Eye } from "lucide-react";
|
||||
import { auditApi, type AuditLogItem } from "@/api/audit";
|
||||
import { usersApi } from "@/api/masters";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
|
||||
const ENTITY_TYPES = [
|
||||
{ value: "", label: "All Entity Types" },
|
||||
{ value: "asset", label: "Asset" },
|
||||
{ value: "complaint", label: "Complaint" },
|
||||
{ value: "pm_schedule", label: "PM Schedule" },
|
||||
{ value: "pm_record", label: "PM Record" },
|
||||
{ value: "calibration_plan", label: "Calibration Plan" },
|
||||
{ value: "calibration_record", label: "Calibration Record" },
|
||||
{ value: "contract", label: "Contract" },
|
||||
{ value: "warranty", label: "Warranty" },
|
||||
{ value: "insurance_policy", label: "Insurance Policy" },
|
||||
{ value: "demo_equipment", label: "Demo Equipment" },
|
||||
{ value: "department_visit", label: "Department Visit" },
|
||||
{ value: "attachment", label: "Attachment" },
|
||||
{ value: "setting", label: "Setting" },
|
||||
{ value: "user", label: "User" },
|
||||
{ value: "department", label: "Department" },
|
||||
{ value: "location", label: "Location" },
|
||||
{ value: "category", label: "Category" },
|
||||
{ value: "vendor", label: "Vendor" },
|
||||
];
|
||||
|
||||
const ACTIONS = [
|
||||
{ value: "", label: "All Actions" },
|
||||
{ value: "create", label: "Create" },
|
||||
{ value: "update", label: "Update" },
|
||||
{ value: "delete", label: "Delete" },
|
||||
{ value: "status_change", label: "Status Change" },
|
||||
{ value: "complete", label: "Complete" },
|
||||
{ value: "reschedule", label: "Reschedule" },
|
||||
{ value: "renew", label: "Renew" },
|
||||
{ value: "return", label: "Return" },
|
||||
{ value: "login", label: "Login" },
|
||||
];
|
||||
|
||||
function ActionBadge({ action }: { action: string }) {
|
||||
const lower = action.toLowerCase();
|
||||
let cls = "bg-slate-100 text-slate-700 border-slate-200";
|
||||
if (lower.includes("create") || lower.includes("upload")) {
|
||||
cls = "bg-green-100 text-green-800 border-green-200";
|
||||
} else if (lower.includes("delete") || lower.includes("deactivate") || lower.includes("remove")) {
|
||||
cls = "bg-red-100 text-red-800 border-red-200";
|
||||
} else if (
|
||||
lower.includes("update") ||
|
||||
lower.includes("status") ||
|
||||
lower.includes("reschedule")
|
||||
) {
|
||||
cls = "bg-blue-100 text-blue-800 border-blue-200";
|
||||
} else if (
|
||||
lower.includes("complete") ||
|
||||
lower.includes("renew") ||
|
||||
lower.includes("return") ||
|
||||
lower.includes("approve")
|
||||
) {
|
||||
cls = "bg-emerald-100 text-emerald-800 border-emerald-200";
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border whitespace-nowrap capitalize",
|
||||
cls
|
||||
)}
|
||||
>
|
||||
{action.replace(/_/g, " ")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function summarizeChanges(changesJson: string | null): string {
|
||||
if (!changesJson) return "—";
|
||||
try {
|
||||
const parsed = JSON.parse(changesJson);
|
||||
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
||||
const keys = Object.keys(parsed);
|
||||
if (keys.length === 0) return "—";
|
||||
const preview = keys
|
||||
.slice(0, 3)
|
||||
.map((k) => {
|
||||
const val = (parsed as Record<string, unknown>)[k];
|
||||
if (val && typeof val === "object" && "old" in val && "new" in val) {
|
||||
const pair = val as { old: unknown; new: unknown };
|
||||
return `${k}: ${String(pair.old ?? "∅")} → ${String(pair.new ?? "∅")}`;
|
||||
}
|
||||
const str = typeof val === "string" ? val : JSON.stringify(val);
|
||||
return `${k}: ${str}`;
|
||||
})
|
||||
.join(", ");
|
||||
return keys.length > 3 ? `${preview} (+${keys.length - 3} more)` : preview;
|
||||
}
|
||||
return String(parsed);
|
||||
} catch {
|
||||
return changesJson.length > 90 ? `${changesJson.slice(0, 90)}…` : changesJson;
|
||||
}
|
||||
}
|
||||
|
||||
function formatJsonPretty(changesJson: string | null): string {
|
||||
if (!changesJson) return "No payload recorded.";
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(changesJson), null, 2);
|
||||
} catch {
|
||||
return changesJson;
|
||||
}
|
||||
}
|
||||
|
||||
export function AuditLogsPage() {
|
||||
const [entityType, setEntityType] = useState("");
|
||||
const [byUserId, setByUserId] = useState("");
|
||||
const [action, setAction] = useState("");
|
||||
const [dateFrom, setDateFrom] = useState("");
|
||||
const [dateTo, setDateTo] = useState("");
|
||||
const [q, setQ] = useState("");
|
||||
const [selectedEntry, setSelectedEntry] = useState<AuditLogItem | null>(null);
|
||||
|
||||
const usersQuery = useQuery({
|
||||
queryKey: ["users", "audit-filter"],
|
||||
queryFn: () => usersApi.list(true),
|
||||
});
|
||||
|
||||
const logsQuery = useQuery({
|
||||
queryKey: [
|
||||
"audit-logs",
|
||||
entityType,
|
||||
byUserId,
|
||||
action,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
q,
|
||||
],
|
||||
queryFn: () =>
|
||||
auditApi.list({
|
||||
entity_type: entityType || undefined,
|
||||
by_user_id: byUserId ? Number(byUserId) : undefined,
|
||||
action: action || undefined,
|
||||
date_from: dateFrom || undefined,
|
||||
date_to: dateTo || undefined,
|
||||
q: q.trim() || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const hasFilters = Boolean(
|
||||
entityType || byUserId || action || dateFrom || dateTo || q.trim()
|
||||
);
|
||||
|
||||
function handleReset() {
|
||||
setEntityType("");
|
||||
setByUserId("");
|
||||
setAction("");
|
||||
setDateFrom("");
|
||||
setDateTo("");
|
||||
setQ("");
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<AuditLogItem, unknown>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: "at",
|
||||
header: "Timestamp",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap text-xs text-gray-700">
|
||||
{formatDateTime(getValue() as string)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "user",
|
||||
accessorFn: (r) => r.by_user_name ?? `User #${r.by_user_id ?? "System"}`,
|
||||
header: "User",
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm font-medium text-gray-900">
|
||||
{row.original.by_user_name ||
|
||||
(row.original.by_user_id != null
|
||||
? `User #${row.original.by_user_id}`
|
||||
: "System")}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "entity_type",
|
||||
header: "Entity Type",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded bg-gray-100 text-gray-700 font-mono text-xs">
|
||||
{String(getValue() ?? "")}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "entity_id",
|
||||
header: "Entity ID",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="font-mono text-xs text-gray-700">
|
||||
#{String(getValue() ?? "")}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "action",
|
||||
header: "Action",
|
||||
cell: ({ getValue }) => <ActionBadge action={String(getValue() ?? "")} />,
|
||||
},
|
||||
{
|
||||
id: "changes",
|
||||
accessorFn: (r) => r.changes_json ?? "",
|
||||
header: "Changes",
|
||||
cell: ({ row }) => {
|
||||
const summary = summarizeChanges(row.original.changes_json);
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-2 max-w-md">
|
||||
<span className="text-xs text-gray-600 truncate" title={summary}>
|
||||
{summary}
|
||||
</span>
|
||||
{row.original.changes_json && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setSelectedEntry(row.original);
|
||||
}}
|
||||
aria-label={`View JSON changes for audit entry ${row.original.id}`}
|
||||
className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium text-[#1e3a8a] hover:bg-blue-50 border border-blue-200 shrink-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
>
|
||||
<Eye className="h-3 w-3" />
|
||||
JSON
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
[]
|
||||
);
|
||||
|
||||
const items = logsQuery.data?.items ?? [];
|
||||
const total = logsQuery.data?.total ?? items.length;
|
||||
const users = usersQuery.data?.items ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* Header */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<History className="h-6 w-6 text-[#1e3a8a]" />
|
||||
<h1 className="text-2xl font-bold text-gray-900">Audit Log</h1>
|
||||
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-[#1e3a8a] border border-blue-200">
|
||||
{total} {total === 1 ? "entry" : "entries"}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Track system-wide creations, updates, status transitions, and deletions.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filter Bar */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 shadow-sm">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-2.5 items-end">
|
||||
<div className="lg:col-span-2">
|
||||
<label
|
||||
htmlFor="audit-search"
|
||||
className="block text-xs font-medium text-gray-600 mb-1"
|
||||
>
|
||||
Search
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Search className="h-3.5 w-3.5 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
id="audit-search"
|
||||
type="text"
|
||||
aria-label="Search audit logs"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Search entity ID, action, changes..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="audit-entity-type"
|
||||
className="block text-xs font-medium text-gray-600 mb-1"
|
||||
>
|
||||
Entity Type
|
||||
</label>
|
||||
<select
|
||||
id="audit-entity-type"
|
||||
aria-label="Filter by Entity Type"
|
||||
value={entityType}
|
||||
onChange={(e) => setEntityType(e.target.value)}
|
||||
className="w-full px-2.5 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
{ENTITY_TYPES.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="audit-user"
|
||||
className="block text-xs font-medium text-gray-600 mb-1"
|
||||
>
|
||||
User
|
||||
</label>
|
||||
<select
|
||||
id="audit-user"
|
||||
aria-label="Filter by User"
|
||||
value={byUserId}
|
||||
onChange={(e) => setByUserId(e.target.value)}
|
||||
className="w-full px-2.5 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<option value="">All Users</option>
|
||||
{users.map((u) => (
|
||||
<option key={u.id} value={String(u.id)}>
|
||||
{u.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="audit-action"
|
||||
className="block text-xs font-medium text-gray-600 mb-1"
|
||||
>
|
||||
Action
|
||||
</label>
|
||||
<select
|
||||
id="audit-action"
|
||||
aria-label="Filter by Action"
|
||||
value={action}
|
||||
onChange={(e) => setAction(e.target.value)}
|
||||
className="w-full px-2.5 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
{ACTIONS.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-end gap-1.5">
|
||||
<div className="flex-1 min-w-0">
|
||||
<label
|
||||
htmlFor="audit-date-from"
|
||||
className="block text-xs font-medium text-gray-600 mb-1"
|
||||
>
|
||||
From
|
||||
</label>
|
||||
<input
|
||||
id="audit-date-from"
|
||||
type="date"
|
||||
aria-label="Date from"
|
||||
value={dateFrom}
|
||||
onChange={(e) => setDateFrom(e.target.value)}
|
||||
className="w-full px-2 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<label
|
||||
htmlFor="audit-date-to"
|
||||
className="block text-xs font-medium text-gray-600 mb-1"
|
||||
>
|
||||
To
|
||||
</label>
|
||||
<input
|
||||
id="audit-date-to"
|
||||
type="date"
|
||||
aria-label="Date to"
|
||||
value={dateTo}
|
||||
onChange={(e) => setDateTo(e.target.value)}
|
||||
className="w-full px-2 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasFilters && (
|
||||
<div className="mt-2.5 flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleReset}
|
||||
className="text-xs h-7 px-2.5"
|
||||
>
|
||||
<RotateCcw className="h-3.5 w-3.5 mr-1" />
|
||||
Reset filters
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<DataTable
|
||||
data={items}
|
||||
columns={columns}
|
||||
loading={logsQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter loaded audit entries..."
|
||||
exportFilename="audit-logs"
|
||||
emptyMessage="No audit log entries match your selected filters."
|
||||
/>
|
||||
|
||||
{/* JSON Diff Modal */}
|
||||
<Modal
|
||||
open={Boolean(selectedEntry)}
|
||||
onOpenChange={(o) => !o && setSelectedEntry(null)}
|
||||
title={
|
||||
selectedEntry
|
||||
? `Audit Entry #${selectedEntry.id} — ${selectedEntry.entity_type} #${selectedEntry.entity_id}`
|
||||
: "Audit Entry Details"
|
||||
}
|
||||
description={
|
||||
selectedEntry
|
||||
? `${selectedEntry.action.replace(/_/g, " ")} by ${
|
||||
selectedEntry.by_user_name || "System"
|
||||
} at ${formatDateTime(selectedEntry.at)}`
|
||||
: undefined
|
||||
}
|
||||
className="max-w-2xl"
|
||||
>
|
||||
{selectedEntry && (
|
||||
<div className="space-y-3">
|
||||
<pre className="rounded-md bg-gray-900 text-gray-100 p-4 text-xs overflow-x-auto max-h-96 font-mono leading-relaxed">
|
||||
{formatJsonPretty(selectedEntry.changes_json)}
|
||||
</pre>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSelectedEntry(null)}
|
||||
>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -31,6 +31,8 @@ import { Modal } from "@/components/ui/dialog";
|
||||
import { ExpiryChip } from "@/components/StatusBadge";
|
||||
import { AssetPicker } from "@/components/AssetPicker";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { toast } from "@/components/ToastProvider";
|
||||
|
||||
type TabKey = "contracts" | "warranties";
|
||||
|
||||
@@ -101,6 +103,13 @@ export function ContractsPage() {
|
||||
title: string;
|
||||
} | null>(null);
|
||||
|
||||
// Confirm delete dialog
|
||||
const [deleteTarget, setDeleteTarget] = useState<{
|
||||
kind: "contract" | "warranty";
|
||||
id: number;
|
||||
label: string;
|
||||
} | null>(null);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
@@ -150,16 +159,26 @@ export function ContractsPage() {
|
||||
const deleteContractMutation = useMutation({
|
||||
mutationFn: (id: number) => contractsApi.remove(id),
|
||||
onSuccess: () => {
|
||||
setDeleteTarget(null);
|
||||
qc.invalidateQueries({ queryKey: ["contracts"] });
|
||||
qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
toast.success("Contract deleted");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.detail : "Failed to delete contract");
|
||||
},
|
||||
});
|
||||
|
||||
const deleteWarrantyMutation = useMutation({
|
||||
mutationFn: (id: number) => warrantiesApi.remove(id),
|
||||
onSuccess: () => {
|
||||
setDeleteTarget(null);
|
||||
qc.invalidateQueries({ queryKey: ["warranties"] });
|
||||
qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
toast.success("Warranty deleted");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.detail : "Failed to delete warranty");
|
||||
},
|
||||
});
|
||||
|
||||
@@ -303,11 +322,13 @@ export function ContractsPage() {
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-red-600 hover:text-red-700"
|
||||
onClick={() => {
|
||||
if (window.confirm("Delete this contract?")) {
|
||||
deleteContractMutation.mutate(row.original.id);
|
||||
}
|
||||
}}
|
||||
onClick={() =>
|
||||
setDeleteTarget({
|
||||
kind: "contract",
|
||||
id: row.original.id,
|
||||
label: `${row.original.asset_code} (${row.original.contract_type})`,
|
||||
})
|
||||
}
|
||||
aria-label={`Delete contract ${row.original.id}`}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
@@ -412,6 +433,7 @@ export function ContractsPage() {
|
||||
setEditingWarranty(row.original);
|
||||
setWarrantyFormOpen(true);
|
||||
}}
|
||||
aria-label={`Edit warranty ${row.original.id}`}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
@@ -419,11 +441,14 @@ export function ContractsPage() {
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-red-600 hover:text-red-700"
|
||||
onClick={() => {
|
||||
if (window.confirm("Delete this warranty?")) {
|
||||
deleteWarrantyMutation.mutate(row.original.id);
|
||||
}
|
||||
}}
|
||||
onClick={() =>
|
||||
setDeleteTarget({
|
||||
kind: "warranty",
|
||||
id: row.original.id,
|
||||
label: `${row.original.asset_code} warranty`,
|
||||
})
|
||||
}
|
||||
aria-label={`Delete warranty ${row.original.id}`}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
@@ -652,6 +677,28 @@ export function ContractsPage() {
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
open={Boolean(deleteTarget)}
|
||||
onOpenChange={(o) => !o && setDeleteTarget(null)}
|
||||
title={
|
||||
deleteTarget?.kind === "warranty" ? "Delete Warranty" : "Delete Contract"
|
||||
}
|
||||
message={`Are you sure you want to delete ${deleteTarget?.label ?? "this record"}?`}
|
||||
confirmLabel="Delete"
|
||||
variant="danger"
|
||||
loading={
|
||||
deleteContractMutation.isPending || deleteWarrantyMutation.isPending
|
||||
}
|
||||
onConfirm={() => {
|
||||
if (!deleteTarget) return;
|
||||
if (deleteTarget.kind === "warranty") {
|
||||
deleteWarrantyMutation.mutate(deleteTarget.id);
|
||||
} else {
|
||||
deleteContractMutation.mutate(deleteTarget.id);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,6 +21,8 @@ import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { DemoStatusBadge } from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { toast } from "@/components/ToastProvider";
|
||||
|
||||
type ViewTab = "active" | "returned" | "all";
|
||||
|
||||
@@ -45,6 +47,7 @@ export function DemoEquipmentPage() {
|
||||
const [editing, setEditing] = useState<DemoEquipmentItem | null>(null);
|
||||
const [returnTarget, setReturnTarget] = useState<DemoEquipmentItem | null>(null);
|
||||
const [attachTarget, setAttachTarget] = useState<DemoEquipmentItem | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<DemoEquipmentItem | null>(null);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
@@ -86,7 +89,14 @@ export function DemoEquipmentPage() {
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => demoEquipmentApi.remove(id),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["demo-equipment"] }),
|
||||
onSuccess: () => {
|
||||
setDeleteTarget(null);
|
||||
qc.invalidateQueries({ queryKey: ["demo-equipment"] });
|
||||
toast.success("Demo equipment entry deleted");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.detail : "Failed to delete demo entry");
|
||||
},
|
||||
});
|
||||
|
||||
const items = useMemo(() => {
|
||||
@@ -227,11 +237,7 @@ export function DemoEquipmentPage() {
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-red-600 hover:text-red-700"
|
||||
onClick={() => {
|
||||
if (window.confirm(`Delete demo entry "${row.original.name}"?`)) {
|
||||
deleteMutation.mutate(row.original.id);
|
||||
}
|
||||
}}
|
||||
onClick={() => setDeleteTarget(row.original)}
|
||||
aria-label={`Delete demo equipment ${row.original.name}`}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
@@ -387,6 +393,19 @@ export function DemoEquipmentPage() {
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
open={Boolean(deleteTarget)}
|
||||
onOpenChange={(o) => !o && setDeleteTarget(null)}
|
||||
title="Delete Demo Equipment Entry"
|
||||
message={`Are you sure you want to delete "${deleteTarget?.name ?? "this demo entry"}"?`}
|
||||
confirmLabel="Delete"
|
||||
variant="danger"
|
||||
loading={deleteMutation.isPending}
|
||||
onConfirm={() => {
|
||||
if (deleteTarget) deleteMutation.mutate(deleteTarget.id);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ import { ExpiryChip } from "@/components/StatusBadge";
|
||||
import { AssetPicker } from "@/components/AssetPicker";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { toast } from "@/components/ToastProvider";
|
||||
|
||||
const inputCls =
|
||||
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
||||
@@ -55,6 +57,7 @@ export function InsurancePage() {
|
||||
label: string;
|
||||
} | null>(null);
|
||||
const [attachPolicy, setAttachPolicy] = useState<InsuranceItem | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<InsuranceItem | null>(null);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
@@ -82,8 +85,13 @@ export function InsurancePage() {
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => insuranceApi.remove(id),
|
||||
onSuccess: () => {
|
||||
setDeleteTarget(null);
|
||||
qc.invalidateQueries({ queryKey: ["insurance"] });
|
||||
qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
toast.success("Insurance policy deleted");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.detail : "Failed to delete insurance policy");
|
||||
},
|
||||
});
|
||||
|
||||
@@ -208,11 +216,7 @@ export function InsurancePage() {
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-red-600 hover:text-red-700"
|
||||
onClick={() => {
|
||||
if (window.confirm(`Delete policy ${row.original.policy_no}?`)) {
|
||||
deleteMutation.mutate(row.original.id);
|
||||
}
|
||||
}}
|
||||
onClick={() => setDeleteTarget(row.original)}
|
||||
aria-label={`Delete policy ${row.original.policy_no}`}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
@@ -347,6 +351,19 @@ export function InsurancePage() {
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
open={Boolean(deleteTarget)}
|
||||
onOpenChange={(o) => !o && setDeleteTarget(null)}
|
||||
title="Delete Insurance Policy"
|
||||
message={`Are you sure you want to delete policy ${deleteTarget?.policy_no ?? ""}?`}
|
||||
confirmLabel="Delete"
|
||||
variant="danger"
|
||||
loading={deleteMutation.isPending}
|
||||
onConfirm={() => {
|
||||
if (deleteTarget) deleteMutation.mutate(deleteTarget.id);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { MemoryRouter, Routes, Route, useLocation } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { TopBar } from "@/components/layout/TopBar";
|
||||
import { AuditLogsPage } from "@/pages/AuditLogsPage";
|
||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { ToastProvider } from "@/components/ToastProvider";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import * as searchModule from "@/api/search";
|
||||
import * as auditModule from "@/api/audit";
|
||||
import * as mastersModule from "@/api/masters";
|
||||
import * as notificationsModule from "@/api/notifications";
|
||||
|
||||
function LocationEcho() {
|
||||
const loc = useLocation();
|
||||
return <div data-testid="current-location">{loc.pathname}</div>;
|
||||
}
|
||||
|
||||
function renderWithProviders(ui: React.ReactNode, initialEntries = ["/"]) {
|
||||
const qc = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<ToastProvider>
|
||||
<MemoryRouter initialEntries={initialEntries}>{ui}</MemoryRouter>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("Phase 8 Frontend Polish", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 1,
|
||||
name: "System Admin",
|
||||
email: "admin@poona.demo",
|
||||
role: "system_admin",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "test-token",
|
||||
demoAsOfDate: null,
|
||||
hydrating: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("TopBar global quick search displays grouped Assets and Complaints and navigates on click", async () => {
|
||||
vi.spyOn(notificationsModule.notificationsApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
unread_count: 0,
|
||||
unread_calibration_count: 0,
|
||||
});
|
||||
const searchSpy = vi
|
||||
.spyOn(searchModule.searchApi, "query")
|
||||
.mockResolvedValue({
|
||||
assets: [
|
||||
{
|
||||
id: 42,
|
||||
asset_code: "PHRC-ICU-0042",
|
||||
name: "Drager Ventilator",
|
||||
serial_no: "SN-9901",
|
||||
department_name: "ICU",
|
||||
status: "in_service",
|
||||
},
|
||||
],
|
||||
complaints: [
|
||||
{
|
||||
id: 17,
|
||||
complaint_no: "CMP-2026-0017",
|
||||
asset_code: "PHRC-ICU-0042",
|
||||
asset_name: "Drager Ventilator",
|
||||
department_name: "ICU",
|
||||
call_status: "open",
|
||||
priority: "high",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
renderWithProviders(
|
||||
<>
|
||||
<TopBar />
|
||||
<LocationEcho />
|
||||
<Routes>
|
||||
<Route path="/" element={<div />} />
|
||||
<Route path="/assets/:id" element={<div>Asset Detail View</div>} />
|
||||
<Route
|
||||
path="/complaints/:id"
|
||||
element={<div>Complaint Detail View</div>}
|
||||
/>
|
||||
</Routes>
|
||||
</>
|
||||
);
|
||||
|
||||
const searchInput = screen.getByLabelText("Search assets and complaints");
|
||||
fireEvent.change(searchInput, { target: { value: "Ventilator" } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(searchSpy).toHaveBeenCalledWith("Ventilator");
|
||||
expect(screen.getByText("Assets (1)")).toBeInTheDocument();
|
||||
expect(screen.getByText("Complaints (1)")).toBeInTheDocument();
|
||||
expect(screen.getByText("Drager Ventilator")).toBeInTheDocument();
|
||||
expect(screen.getByText("CMP-2026-0017")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText("Drager Ventilator"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("current-location")).toHaveTextContent(
|
||||
"/assets/42"
|
||||
);
|
||||
expect(screen.getByText("Asset Detail View")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("AuditLogsPage renders filter controls, audit log rows, and opens JSON changes modal", async () => {
|
||||
vi.spyOn(mastersModule.usersApi, "list").mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
name: "System Admin",
|
||||
email: "admin@poona.demo",
|
||||
role: "system_admin",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
vi.spyOn(auditModule.auditApi, "list").mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 101,
|
||||
entity_type: "asset",
|
||||
entity_id: 55,
|
||||
action: "update",
|
||||
changes_json: JSON.stringify({
|
||||
status: { old: "in_service", new: "under_repair" },
|
||||
}),
|
||||
by_user_id: 1,
|
||||
by_user_name: "System Admin",
|
||||
at: "2026-11-12T08:30:00Z",
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
renderWithProviders(<AuditLogsPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Audit Log" })
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Filter by Entity Type")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Filter by User")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Filter by Action")).toBeInTheDocument();
|
||||
expect(screen.getByText("#55")).toBeInTheDocument();
|
||||
expect(screen.getByText("asset")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const jsonBtn = screen.getByLabelText("View JSON changes for audit entry 101");
|
||||
fireEvent.click(jsonBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/Audit Entry #101 — asset #55/i)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText(/"under_repair"/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("ConfirmDialog renders danger warning and invokes onConfirm", () => {
|
||||
const onConfirm = vi.fn();
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
render(
|
||||
<ConfirmDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
title="Delete Contract"
|
||||
message="Are you sure you want to delete PHRC-ICU-0001 (AMC)?"
|
||||
confirmLabel="Delete"
|
||||
variant="danger"
|
||||
onConfirm={onConfirm}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("Delete Contract")).toBeInTheDocument();
|
||||
expect(screen.getByText("This action cannot be undone.")).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
|
||||
expect(onConfirm).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -49,11 +49,13 @@ describe("Phase 1 Frontend Smoke Tests", () => {
|
||||
"Reports",
|
||||
"Notifications",
|
||||
"Masters",
|
||||
"Audit Log",
|
||||
"Settings",
|
||||
];
|
||||
for (const label of labels) {
|
||||
expect(screen.getByText(label)).toBeInTheDocument();
|
||||
}
|
||||
expect(screen.getByText("Poona Hospital AMS • v1.0")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hides Masters, Settings, and Department Visits for department_user and coordinator", () => {
|
||||
@@ -74,6 +76,7 @@ describe("Phase 1 Frontend Smoke Tests", () => {
|
||||
</MemoryRouter>
|
||||
);
|
||||
expect(screen.queryByText("Masters")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Audit Log")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Settings")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Department Visits")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Assets")).toBeInTheDocument();
|
||||
@@ -95,6 +98,7 @@ describe("Phase 1 Frontend Smoke Tests", () => {
|
||||
</MemoryRouter>
|
||||
);
|
||||
expect(screen.queryByText("Masters")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Audit Log")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Settings")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Department Visits")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Contracts & Warranty")).toBeInTheDocument();
|
||||
|
||||
Reference in New Issue
Block a user