Files
pfm/PostFundManagement.ConsoleUI/src/components/layout/AppLayout.tsx
T
2026-10-22 15:42:36 +02:00

621 lines
28 KiB
TypeScript

import React, { useState } from 'react';
import { NavLink, Outlet, useNavigate, Link } from 'react-router-dom';
import {
LayoutDashboard,
Building2,
FolderKanban,
Coins,
ShieldAlert,
Settings,
LogOut,
ChevronRight,
ChevronDown,
ShieldCheck,
Database,
Home,
User,
Users,
GitPullRequest,
MapPin,
PanelLeftClose,
PanelLeftOpen,
ChevronsLeft,
ChevronsRight,
} from 'lucide-react';
import { useAuth } from '../../auth/AuthProvider';
import { BrandLogo } from '../ui/BrandLogo';
import { HelpTooltip } from '../ui/HelpTooltip';
import { ErrorBoundary } from '../ui/ErrorBoundary';
import { useQuery } from '@tanstack/react-query';
import { getUsers, getTenant } from '../../services/api';
import { getUserEmail, registerUserEmail } from '../../lib/formatters';
import { useRbac, RoleClaim } from '../../auth/rbac';
interface SubNavItem {
name: string;
path: string;
icon: React.ElementType;
help?: string;
claim?: RoleClaim;
}
interface NavItem {
name: string;
path: string;
icon: React.ElementType;
help: string;
claim?: RoleClaim;
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.',
claim: 'dashboard',
},
{
name: 'Governance & Structure',
path: '/governance',
icon: Building2,
help: 'Master records for legal entities, holding structures, investment portfolios, and thematic programmes funded under statutory mandates.',
claim: 'governance',
},
{
name: 'Projects & Milestones',
path: '/projects',
icon: FolderKanban,
help: 'Project Work Breakdown Structure (WBS), contractual deliverables, scheduled milestones, evidence verification, and execution tracking.',
claim: 'projects_milestones',
subItems: [
{
name: 'Beneficiaries',
path: '/projects/beneficiaries',
icon: Users,
help: 'Manage target beneficiaries, demographics, and statutory compliance items satisfying beneficiaries.',
claim: 'beneficiaries',
},
{
name: 'Change Management',
path: '/projects/change-management',
icon: GitPullRequest,
help: 'Track project issues, contractual change requests, and resolve changes in-place.',
claim: 'change_management',
},
{
name: 'Site Visits',
path: '/projects/site-visits',
icon: MapPin,
help: 'Log physical site visits, field observations, inspector findings, and project feedback.',
claim: 'site_visits',
},
{
name: 'Compliance',
path: '/compliance',
icon: ShieldCheck,
help: 'Portfolio & programme compliance dashboard, statutory requirements, beneficiary outcome fulfillment, and risk monitoring.',
claim: 'compliance',
},
],
},
{
name: 'Grant & Financials',
path: '/grants',
icon: Coins,
help: 'Financial management including statutory awards, multi-year budget line allocations, tranches, and scheduled payment disbursements.',
claim: 'grant_financials',
},
{
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.',
claim: 'evidence_risks',
},
{
name: 'Tenant Management',
path: '/tenants',
icon: Database,
help: 'Multi-tenant partition directory, organizational onboarding, status lifecycle controls, and system-wide isolation boundaries.',
claim: 'tenant_management',
},
{
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, tenantName: authTenantName, canManageTenants, logout, roles } = useAuth();
const userRole = user?.role || (Array.isArray(roles) && roles.length > 0 ? roles[0] : (claims?.role as string) || 'User');
const { canView } = useRbac();
const [sidebarOpen, setSidebarOpen] = useState(true);
const [userMenuOpen, setUserMenuOpen] = useState(false);
const navigate = useNavigate();
const handleLogout = async () => {
await logout();
};
// Filter navigation shelf strictly according to RBAC Role Claims
const visibleNavItems = navItems
.filter((item) => {
if (item.path === '/tenants') {
return canManageTenants || canView('tenant_management') || canView('tenant_self_service');
}
if (item.path === '/settings') {
return (
canView('settings_users') ||
canView('settings_invites') ||
canView('settings_notifications') ||
canView('settings_auditlog') ||
canView('tenant_self_service')
);
}
if (item.claim) {
return canView(item.claim);
}
return true;
})
.map((item) => {
if (!item.subItems) return item;
return {
...item,
subItems: item.subItems.filter((subItem) => {
if (subItem.claim) {
return canView(subItem.claim);
}
return true;
}),
};
});
// 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,
});
// Query tenant endpoint to resolve tenant name if not provided in claims or profile
const { data: remoteTenant } = useQuery({
queryKey: ['active-tenant-header', tenantId],
queryFn: () => getTenant(tenantId!),
enabled: !!tenantId && !claims?.tenant && !user?.tenant && !authTenantName,
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 from user claim 'tenant', auth context, remote tenant endpoint, or organization name
const tenantName =
(claims?.tenant as string) ||
(claims?.['tenant'] as string) ||
authTenantName ||
user?.tenant ||
remoteTenant?.name ||
user?.organisationName ||
(claims?.organisation as string) ||
(tenantId ? `Tenant #${tenantId}` : '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-[72px]'
} shrink-0 bg-gradient-to-b from-[#0b101b] via-[#090d16] to-[#0b101b] text-slate-200 border-r border-slate-800/80 transition-all duration-300 ease-in-out flex flex-col z-30 shadow-2xl backdrop-blur-md relative`}
>
{/* Brand Header */}
<div className={`h-16 border-b border-slate-800/80 bg-[#0d121f]/90 flex items-center transition-all ${
sidebarOpen ? 'px-4 justify-between' : 'px-2 justify-center'
}`}>
{sidebarOpen ? (
<>
<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={32} showGlow animateOnHover />
<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(false)}
className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800/80 border border-transparent hover:border-slate-700/60 transition cursor-pointer shadow-xs"
title="Collapse sidebar shelf"
aria-label="Collapse sidebar shelf"
>
<PanelLeftClose className="w-4 h-4" />
</button>
</>
) : (
<div className="flex items-center justify-center">
<Link
to="/"
id="nav-brand-home-link-collapsed"
title="PFM Console • Go to Home page"
className="cursor-pointer transition transform hover:scale-105"
>
<BrandLogo size={32} showGlow animateOnHover />
</Link>
</div>
)}
</div>
{/* Collapsed Shelf Expand Button */}
{!sidebarOpen && (
<div className="pt-2 pb-1 px-2 flex justify-center border-b border-slate-800/40">
<button
onClick={() => setSidebarOpen(true)}
className="w-10 h-8 flex items-center justify-center rounded-lg text-slate-400 hover:text-blue-400 hover:bg-blue-600/10 border border-slate-800 hover:border-blue-500/30 transition cursor-pointer shadow-xs group relative"
title="Expand sidebar shelf"
aria-label="Expand sidebar shelf"
>
<PanelLeftOpen className="w-4 h-4 transition-transform group-hover:scale-110" />
<div className="absolute left-full ml-3 px-2.5 py-1 bg-slate-900 text-white text-xs font-semibold rounded-lg shadow-2xl border border-slate-700 whitespace-nowrap z-50 pointer-events-none opacity-0 group-hover:opacity-100 transition-all duration-150">
Expand Navigation Shelf
</div>
</button>
</div>
)}
{/* Navigation Items */}
<nav className={`flex-1 overflow-y-auto space-y-1.5 ${sidebarOpen ? 'px-3 py-4' : 'px-2 py-3'}`}>
{visibleNavItems.map((item) => {
const Icon = item.icon;
const hasSub = item.subItems && item.subItems.length > 0;
if (!sidebarOpen) {
return (
<div key={item.path} className="flex justify-center">
<NavLink
to={item.path}
end={hasSub}
className={({ isActive }) =>
`group relative flex items-center justify-center w-11 h-11 rounded-xl transition-all ${
isActive
? 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-lg shadow-blue-600/30 font-semibold ring-1 ring-blue-400/50'
: 'text-slate-400 hover:text-white hover:bg-slate-800/70 border border-transparent hover:border-slate-700/60'
}`
}
title={item.name}
>
<Icon className="w-5 h-5 shrink-0" />
{/* Hover Floating Tooltip Shelf */}
<div className="absolute left-full ml-3 px-3 py-2 bg-[#0d1322] text-slate-100 rounded-xl shadow-2xl border border-slate-700/90 whitespace-nowrap z-50 pointer-events-none opacity-0 group-hover:opacity-100 transition-all duration-150 translate-x-1 group-hover:translate-x-0 min-w-[160px]">
<div className="text-xs font-bold text-white flex items-center gap-1.5">
<Icon className="w-3.5 h-3.5 text-blue-400" />
<span>{item.name}</span>
</div>
<div className="text-[10px] text-slate-400 font-normal mt-0.5 max-w-[200px] line-clamp-2">
{item.help}
</div>
{hasSub && (
<div className="mt-1.5 pt-1.5 border-t border-slate-800 flex flex-col gap-1 text-[10px] text-blue-300">
{item.subItems?.map((s) => (
<span key={s.path} className="flex items-center gap-1 text-slate-300">
• {s.name}
</span>
))}
</div>
)}
</div>
</NavLink>
</div>
);
}
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.5 h-4.5 shrink-0" />
<span className="truncate flex-1">{item.name}</span>
</NavLink>
{/* Sub-items under parent item */}
{hasSub && (
<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={`border-t border-slate-800/80 bg-[#0d121f]/90 ${sidebarOpen ? 'p-3' : 'p-2'}`}>
{sidebarOpen ? (
<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 relative shadow-xs">
{tokenUserName ? tokenUserName.slice(0, 2).toUpperCase() : 'AU'}
<span className="absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full bg-emerald-500 border-2 border-[#0d121f]" title="Active Online Session" />
</div>
<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 className="mt-1 flex items-center gap-1.5">
<span className="text-[10px] font-semibold text-blue-400 bg-blue-500/10 border border-blue-500/25 px-1.5 py-0.5 rounded truncate" title={`Assigned Role: ${userRole}`}>
Role: {userRole}
</span>
</div>
</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 className="flex flex-col items-center gap-2">
<div
className="h-10 w-10 shrink-0 rounded-xl bg-blue-600/20 border border-blue-500/40 flex items-center justify-center font-bold text-xs text-blue-400 relative group cursor-pointer shadow-xs"
title={`${tokenUserName} (${tokenUserEmail}) • Role: ${userRole}`}
>
{tokenUserName ? tokenUserName.slice(0, 2).toUpperCase() : 'AU'}
<span className="absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full bg-emerald-500 border-2 border-[#0d121f]" />
<div className="absolute left-full ml-3 px-3 py-2 bg-[#0d1322] text-white text-xs font-medium rounded-xl shadow-2xl border border-slate-700 whitespace-nowrap z-50 pointer-events-none opacity-0 group-hover:opacity-100 transition-all duration-150">
<div className="font-semibold">{tokenUserName}</div>
<div className="text-[10px] text-slate-400 font-mono mt-0.5">{tokenUserEmail}</div>
<div className="text-[10px] text-blue-400 font-semibold mt-1">Role: {userRole}</div>
</div>
</div>
<button
onClick={handleLogout}
id="sidebar-logout-btn-collapsed"
className="w-10 h-9 rounded-xl flex items-center justify-center text-slate-400 hover:text-rose-400 hover:bg-rose-950/30 border border-transparent hover:border-rose-900/40 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>
{canManageTenants || canView('tenant_management') || canView('tenant_self_service') ? (
<Link
to="/tenants"
className="bg-slate-900/80 hover:bg-slate-800/90 text-slate-200 hover:text-white px-2.5 py-1 rounded-lg border border-slate-800 hover:border-slate-700 flex items-center gap-1.5 font-medium shadow-xs max-w-[320px] truncate transition group cursor-pointer"
title={`Manage Tenants • Current: ${tenantName}${hashedTenantId ? ` (Partition: ${hashedTenantId})` : ''}`}
>
<Database className="w-3.5 h-3.5 text-blue-400 shrink-0 group-hover:text-blue-300 transition" />
<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>
)}
</Link>
) : (
<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">
<div className="flex items-center justify-end gap-1.5">
<p className="text-xs font-semibold text-white truncate max-w-[150px]" title={tokenUserName}>
{tokenUserName}
</p>
<span className="text-[10px] font-semibold uppercase tracking-wider text-blue-400 bg-blue-500/10 border border-blue-500/25 px-1.5 py-0.5 rounded truncate" title={`Role: ${userRole}`}>
{userRole}
</span>
</div>
</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">
<div className="flex items-center justify-between gap-1.5">
<p className="text-xs font-semibold text-white truncate">{tokenUserName}</p>
<span className="text-[10px] font-semibold uppercase text-blue-400 bg-blue-500/10 border border-blue-500/25 px-1.5 py-0.5 rounded shrink-0">
{userRole}
</span>
</div>
<p className="text-[11px] text-slate-300 font-medium truncate mt-0.5">{tokenUserEmail || (sub ? getUserEmail(sub) : '')}</p>
<p className="text-[10px] text-slate-400 mt-1">Role: <strong className="text-blue-300">{userRole}</strong></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 min-w-0 p-4 sm:p-6 md:p-8 bg-[#090d16] relative text-slate-100">
{/* Ambient Glows & Dot Grid - Isolated inside overflow-hidden to prevent phantom page scrollbars */}
<div className="absolute inset-0 overflow-hidden pointer-events-none">
<div
className="absolute inset-0 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" />
<div className="absolute top-1/2 -right-24 w-80 h-80 bg-indigo-600/10 rounded-full blur-3xl" />
</div>
<div className="relative z-10 min-w-0 w-full">
<ErrorBoundary>
<Outlet />
</ErrorBoundary>
</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>
);
};