Files
pfm/PostFundManagement.ConsoleUI/src/components/layout/AppLayout.tsx
T

414 lines
17 KiB
TypeScript

import React, { useState } from 'react';
import { NavLink, Outlet, useNavigate, Link } from 'react-router-dom';
import {
LayoutDashboard,
Building2,
FolderKanban,
Coins,
ShieldAlert,
Settings,
LogOut,
Menu,
X,
ChevronRight,
ChevronDown,
ShieldCheck,
Database,
Home,
User,
Users,
GitPullRequest,
MapPin,
} from 'lucide-react';
import { useAuth } from '../../auth/AuthProvider';
import { BrandLogo } from '../ui/BrandLogo';
import { HelpTooltip } from '../ui/HelpTooltip';
import { useQuery } from '@tanstack/react-query';
import { getUsers } from '../../services/api';
import { getUserEmail, registerUserEmail } from '../../lib/formatters';
interface SubNavItem {
name: string;
path: string;
icon: React.ElementType;
help?: string;
}
interface NavItem {
name: string;
path: string;
icon: React.ElementType;
help: string;
subItems?: SubNavItem[];
}
const navItems: NavItem[] = [
{
name: 'Executive Dashboard',
path: '/dashboard',
icon: LayoutDashboard,
help: 'Strategic macro metrics, portfolio value, disbursed funding, ISO 31000 risk heatmap, and projects requiring immediate intervention.',
},
{
name: 'Governance & Structure',
path: '/governance',
icon: Building2,
help: 'Master records for legal entities, holding structures, investment portfolios, and thematic programmes funded under statutory mandates.',
},
{
name: 'Projects & Milestones',
path: '/projects',
icon: FolderKanban,
help: 'Project Work Breakdown Structure (WBS), contractual deliverables, scheduled milestones, evidence verification, and execution tracking.',
subItems: [
{
name: 'Beneficiaries',
path: '/projects/beneficiaries',
icon: Users,
help: 'Manage target beneficiaries, demographics, and statutory compliance items satisfying beneficiaries.',
},
{
name: 'Change Management',
path: '/projects/change-management',
icon: GitPullRequest,
help: 'Track project issues, contractual change requests, and resolve changes in-place.',
},
],
},
{
name: 'Site Visits',
path: '/site-visits',
icon: MapPin,
help: 'Log physical site visits, field observations, inspector findings, and project feedback.',
},
{
name: 'Grant & Financials',
path: '/grants',
icon: Coins,
help: 'Financial management including statutory awards, multi-year budget line allocations, tranches, and scheduled payment disbursements.',
},
{
name: 'M&E, Evidence & Risks',
path: '/monitoring',
icon: ShieldAlert,
help: 'Monitoring & Evaluation (M&E) framework, indicator tracking, ISO 31000 risk registers, mitigation plans, and compliance audits.',
},
{
name: 'Settings & Communications',
path: '/settings',
icon: Settings,
help: 'User account provisioning, statutory sync, tenant environment parameters, and communication invite templates.',
},
];
export const AppLayout: React.FC = () => {
const { user, claims, sub, tenantId, hashedTenantId, logout } = useAuth();
const [sidebarOpen, setSidebarOpen] = useState(true);
const [userMenuOpen, setUserMenuOpen] = useState(false);
const navigate = useNavigate();
const handleLogout = async () => {
await logout();
};
// Pre-populate user directory cache so all components and modals resolve user emails instantly
useQuery({
queryKey: ['users-directory'],
queryFn: () => getUsers(1, 200),
staleTime: 5 * 60 * 1000,
});
// Ensure current logged-in user is registered in the email cache
const effectiveEmail = ((user?.email || claims?.email || claims?.['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'] || claims?.upn) as string);
if (sub && effectiveEmail) {
registerUserEmail(sub, effectiveEmail);
}
if (user?.id && effectiveEmail) {
registerUserEmail(user.id, effectiveEmail);
}
// Extract name and email directly from validated token claims
const tokenUserName =
user?.name ||
(claims.name as string) ||
(claims.preferred_username as string) ||
(claims.given_name ? `${claims.given_name} ${claims.family_name || ''}`.trim() : '') ||
'Authorized User';
const tokenUserEmail =
user?.email ||
(claims.email as string) ||
(claims['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'] as string) ||
(claims.upn as string) ||
(sub ? getUserEmail(sub) : '');
// Extract tenant name directly from the user claim named 'tenant'
const tenantName =
(claims?.tenant as string) ||
user?.tenant ||
(claims?.['tenant'] as string) ||
user?.organisationName ||
(claims?.organisation as string) ||
'Department of Science, Innovation & Technology (DSI)';
return (
<div className="flex h-screen w-full overflow-hidden bg-[#090d16] font-sans text-slate-100 selection:bg-blue-600 selection:text-white">
{/* Sidebar */}
<aside
className={`${
sidebarOpen ? 'w-64' : 'w-20'
} shrink-0 bg-[#0b101b]/95 text-slate-200 border-r border-slate-800/80 transition-all duration-300 flex flex-col z-30 shadow-2xl backdrop-blur-md`}
>
{/* Brand Header */}
<div className="h-16 px-4 flex items-center justify-between border-b border-slate-800/80 bg-[#0d121f]/90">
<Link
to="/"
id="nav-brand-home-link"
title="Go to Home page"
className="flex items-center gap-3 overflow-hidden group cursor-pointer"
>
<BrandLogo size={36} showGlow animateOnHover />
{sidebarOpen && (
<div className="flex flex-col min-w-0">
<span className="font-bold text-sm tracking-tight text-white truncate group-hover:text-blue-400 transition">
PFM Console
</span>
<span className="text-[11px] text-blue-400 font-medium tracking-tight">Enterprise Management</span>
</div>
)}
</Link>
<button
onClick={() => setSidebarOpen(!sidebarOpen)}
className="rounded-lg p-1.5 text-slate-400 hover:text-white hover:bg-slate-800/60 transition cursor-pointer"
title={sidebarOpen ? 'Collapse sidebar' : 'Expand sidebar'}
>
{sidebarOpen ? <X className="w-4 h-4" /> : <Menu className="w-4 h-4" />}
</button>
</div>
{/* Navigation Items */}
<nav className="flex-1 overflow-y-auto px-3 py-4 space-y-1.5">
{navItems.map((item) => {
const Icon = item.icon;
const hasSub = item.subItems && item.subItems.length > 0;
return (
<div key={item.path} className="space-y-1">
<NavLink
to={item.path}
end={hasSub}
className={({ isActive }) =>
`flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-medium transition-all min-w-0 ${
isActive
? 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-md shadow-blue-600/25 font-semibold'
: 'text-slate-400 hover:text-slate-100 hover:bg-slate-800/60'
}`
}
title={item.name}
>
<Icon className="w-4 h-4 shrink-0" />
{sidebarOpen && <span className="truncate flex-1">{item.name}</span>}
</NavLink>
{/* Sub-items under parent item */}
{hasSub && sidebarOpen && (
<div className="pl-6 pr-1 py-1 space-y-1 border-l border-slate-800/80 ml-5">
{item.subItems?.map((subItem) => {
const SubIcon = subItem.icon;
return (
<NavLink
key={subItem.path}
to={subItem.path}
className={({ isActive }) =>
`flex items-center gap-2.5 px-3 py-2 rounded-lg text-[11px] font-medium transition-all min-w-0 ${
isActive
? 'bg-blue-600/20 text-blue-300 font-semibold border border-blue-500/30'
: 'text-slate-400 hover:text-slate-200 hover:bg-slate-800/50'
}`
}
title={subItem.name}
>
<SubIcon className="w-3.5 h-3.5 shrink-0 text-slate-400" />
<span className="truncate">{subItem.name}</span>
</NavLink>
);
})}
</div>
)}
</div>
);
})}
</nav>
{/* User Card */}
<div className="p-3 border-t border-slate-800/80 bg-[#0d121f]/90">
<div className="flex items-center gap-3">
<div className="h-9 w-9 shrink-0 rounded-full bg-blue-600/20 border border-blue-500/40 flex items-center justify-center font-bold text-xs text-blue-400">
{tokenUserName ? tokenUserName.slice(0, 2).toUpperCase() : 'AU'}
</div>
{sidebarOpen && (
<div className="flex-1 min-w-0">
<p className="text-xs font-semibold text-white truncate" title={tokenUserName}>
{tokenUserName}
</p>
<p className="text-[11px] text-slate-400 truncate font-mono" title={tokenUserEmail}>
{tokenUserEmail || 'Authenticated User'}
</p>
</div>
)}
<button
onClick={handleLogout}
id="sidebar-logout-btn"
className="rounded-lg p-1.5 text-slate-400 hover:text-rose-400 hover:bg-rose-950/30 transition cursor-pointer"
title="Sign Out of Session"
>
<LogOut className="w-4 h-4" />
</button>
</div>
</div>
</aside>
{/* Main Content Area */}
<div className="flex-1 flex flex-col min-w-0 overflow-hidden relative">
{/* Top Header */}
<header className="h-16 bg-[#0d121f]/90 border-b border-slate-800/80 backdrop-blur-md px-4 sm:px-6 md:px-8 flex items-center justify-between shrink-0 z-20">
<div className="flex items-center gap-3">
{/* Home Navigation */}
<Link
to="/"
id="header-home-link"
className="flex items-center gap-1.5 text-xs font-semibold text-slate-300 hover:text-white bg-slate-900/80 hover:bg-slate-800 px-3 py-1.5 rounded-lg border border-slate-800 transition cursor-pointer shadow-xs"
title="Return to Auth-Aware Home page"
>
<Home className="w-3.5 h-3.5 text-blue-400" />
<span>Home</span>
</Link>
<ChevronRight className="w-4 h-4 text-slate-600" />
<div className="hidden sm:flex items-center gap-2 text-xs font-medium text-slate-300">
<span className="text-slate-400">Tenant:</span>
<span
className="bg-slate-900/80 text-slate-200 px-2.5 py-1 rounded-lg border border-slate-800 flex items-center gap-1.5 font-medium shadow-xs max-w-[320px] truncate"
title={`${tenantName}${hashedTenantId ? ` (Partition: ${hashedTenantId})` : ''}`}
>
<Database className="w-3.5 h-3.5 text-blue-400 shrink-0" />
<span className="truncate">{tenantName}</span>
{hashedTenantId && (
<span
className="text-[10px] font-mono text-blue-400 bg-blue-950/60 px-1.5 py-0.5 rounded border border-blue-800/60 shrink-0"
title={`Tenant Partition HashID: ${hashedTenantId}`}
>
{hashedTenantId}
</span>
)}
</span>
<HelpTooltip
title="Tenant Context"
content={`Identifies the multi-tenant organization partition and database boundary within the national PFM environment.${
hashedTenantId ? ` Tenant Partition (HashID): ${hashedTenantId}` : ''
}`}
size="sm"
placement="bottom"
/>
</div>
<ChevronRight className="w-4 h-4 text-slate-600 hidden sm:block" />
<div className="flex items-center gap-1.5">
<span className="text-xs font-medium text-emerald-400 bg-emerald-500/10 px-2.5 py-0.5 rounded-full border border-emerald-500/30 flex items-center gap-1.5 shadow-xs">
<ShieldCheck className="w-3.5 h-3.5 text-emerald-400" />
Authenticated Session
</span>
<HelpTooltip
title="Security Session Status"
content="Current session is verified against OIDC Identity Server with active cryptographic token and claims."
size="sm"
placement="bottom"
/>
</div>
</div>
{/* User Profile and Controls */}
<div className="relative flex items-center gap-3">
<div className="text-right hidden sm:block">
<p className="text-xs font-semibold text-white truncate max-w-[200px]" title={tokenUserName}>
{tokenUserName}
</p>
<p className="text-[11px] text-slate-400 font-mono truncate max-w-[200px]" title={tokenUserEmail}>
{tokenUserEmail}
</p>
</div>
<button
onClick={() => setUserMenuOpen(!userMenuOpen)}
id="header-user-menu-btn"
className="h-9 w-9 rounded-full bg-blue-600/20 border border-blue-500/40 hover:border-blue-400 flex items-center justify-center font-bold text-xs text-blue-400 transition cursor-pointer shadow-md shadow-blue-500/10"
title="User Account"
>
{tokenUserName ? tokenUserName.slice(0, 2).toUpperCase() : <User className="w-4 h-4" />}
</button>
{/* Dropdown Menu */}
{userMenuOpen && (
<div
className="absolute right-0 top-12 w-64 bg-[#0f1523] border border-slate-800 rounded-2xl shadow-2xl p-3 z-50 space-y-2 animate-in fade-in slide-in-from-top-2 backdrop-blur-md"
onMouseLeave={() => setUserMenuOpen(false)}
>
<div className="p-2.5 border-b border-slate-800">
<p className="text-xs font-semibold text-white">{tokenUserName}</p>
<p className="text-[11px] text-slate-300 font-medium truncate">{tokenUserEmail || (sub ? getUserEmail(sub) : '')}</p>
</div>
<Link
to="/"
onClick={() => setUserMenuOpen(false)}
className="flex items-center gap-2 px-3 py-2 text-xs text-slate-300 hover:text-white hover:bg-slate-800/60 rounded-xl transition"
>
<Home className="w-3.5 h-3.5 text-blue-400" />
<span>Go to Home Page</span>
</Link>
<button
onClick={handleLogout}
id="dropdown-logout-btn"
className="w-full flex items-center gap-2 px-3 py-2 text-xs text-rose-400 hover:bg-rose-950/30 rounded-xl transition cursor-pointer"
>
<LogOut className="w-3.5 h-3.5" />
<span>Sign Out of Session</span>
</button>
</div>
)}
</div>
</header>
{/* Main Content Area */}
<main className="flex-1 overflow-y-auto p-6 md:p-8 bg-[#090d16] relative text-slate-100">
<div
className="absolute inset-0 pointer-events-none opacity-15"
style={{
backgroundImage: 'radial-gradient(circle at 1px 1px, rgba(255,255,255,0.15) 1px, transparent 0)',
backgroundSize: '32px 32px',
}}
/>
<div className="absolute -top-24 -left-24 w-80 h-80 bg-blue-600/10 rounded-full blur-3xl pointer-events-none" />
<div className="absolute top-1/2 -right-24 w-80 h-80 bg-indigo-600/10 rounded-full blur-3xl pointer-events-none" />
<div className="relative z-10">
<Outlet />
</div>
</main>
{/* Bottom Status Footer */}
<footer className="h-10 px-6 md:px-8 border-t border-slate-800/80 bg-[#0d121f]/90 flex items-center justify-between text-[11px] text-slate-400 shrink-0">
<span>Project Financial Management (PFM) System</span>
<span className="text-slate-400 font-medium flex items-center gap-1.5">
<span className="h-1.5 w-1.5 rounded-full bg-emerald-400 inline-block"></span>
Enterprise Secure Session
</span>
</footer>
</div>
</div>
);
};