Removed settings page mock data and replaced with api calls

This commit is contained in:
2026-09-27 10:58:08 +02:00
parent 6ab01830f3
commit fb27cc8c92
10 changed files with 1067 additions and 557 deletions
@@ -2164,7 +2164,7 @@ export const GovernancePage: React.FC = () => {
</div>
</div>
<span className="text-[10px] font-mono font-semibold px-2 py-0.5 rounded-full bg-blue-500/20 text-blue-300 border border-blue-500/30">
Live API Total
Total Value
</span>
</div>
@@ -2266,7 +2266,7 @@ export const GovernancePage: React.FC = () => {
</div>
</div>
<span className="text-[10px] font-mono font-semibold px-2 py-0.5 rounded-full bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">
Live API Total
Total Value
</span>
</div>
@@ -22,6 +22,9 @@ import {
Link as LinkIcon,
Edit2,
ChevronRight,
RefreshCw,
Search,
RotateCcw,
} from 'lucide-react';
import {
getAllIndicators,
@@ -36,6 +39,8 @@ import {
import { Modal } from '../components/ui/Modal';
import { HelpTooltip } from '../components/ui/HelpTooltip';
import { useToast } from '../components/ui/Toast';
import { ExportButton } from '../components/ui/ExportButton';
import { ExportColumn } from '../utils/exportUtils';
import { ContractsManagement } from '../components/monitoring/ContractsManagement';
import { EvidenceReviewQueue } from '../components/monitoring/EvidenceReviewQueue';
import { RiskHeatmapMatrix } from '../components/ui/RiskHeatmapMatrix';
@@ -124,13 +129,34 @@ export const MonitoringPage: React.FC = () => {
const [selectedIndicatorForActual, setSelectedIndicatorForActual] = useState<Indicator | null>(null);
const [actualInput, setActualInput] = useState<number>(0);
// Indicator Filter States
const [indicatorSearchTerm, setIndicatorSearchTerm] = useState('');
const [indicatorProjectFilter, setIndicatorProjectFilter] = useState<string | number | 'all'>('all');
const [indicatorUnitFilter, setIndicatorUnitFilter] = useState<string | number | 'all'>('all');
const [indicatorStatusFilter, setIndicatorStatusFilter] = useState<string>('all');
// Risk Filter States
const [riskSearchTerm, setRiskSearchTerm] = useState('');
const [riskProjectFilter, setRiskProjectFilter] = useState<string | number | 'all'>('all');
const [riskSeverityFilter, setRiskSeverityFilter] = useState<string>('all');
// Queries
const { data: indicators = [], isLoading: loadingIndicators } = useQuery({
const {
data: indicators = [],
isLoading: loadingIndicators,
refetch: refetchIndicators,
isFetching: isFetchingIndicators,
} = useQuery({
queryKey: ['indicators'],
queryFn: () => getAllIndicators(),
});
const { data: risks = [], isLoading: loadingRisks } = useQuery({
const {
data: risks = [],
isLoading: loadingRisks,
refetch: refetchRisks,
isFetching: isFetchingRisks,
} = useQuery({
queryKey: ['risks'],
queryFn: () => getAllRisks(),
});
@@ -264,21 +290,106 @@ export const MonitoringPage: React.FC = () => {
return { label: '<70%', badge: 'bg-rose-500/10 text-rose-400 border-rose-500/20' };
};
const indicatorExportColumns: ExportColumn<Indicator>[] = [
{ header: 'Indicator ID', key: 'id' },
{ header: 'Indicator Statement', key: 'name' },
{ header: 'Project ID', key: 'projectId', format: (val) => `Project #${val}` },
{ header: 'Unit of Measure', key: 'unitOfMeasure', format: (val) => getUnitOfMeasureLabel(val) },
{ header: 'Baseline Value', key: 'baselineAmount' },
{ header: 'Target Value', key: 'targetAmount' },
{ header: 'Actual Recorded', key: 'actualAmount' },
{
header: 'Achievement %',
key: 'actualAmount',
format: (val, item) => (item.targetAmount ? `${Math.round((Number(val) / Number(item.targetAmount)) * 100)}%` : '—'),
},
{
header: 'Status',
key: 'actualAmount',
format: (val, item) => getIndicatorStatus(Number(val), Number(item.targetAmount)).label,
},
];
const filteredIndicators = indicators.filter((ind) => {
if (indicatorProjectFilter !== 'all' && String(ind.projectId) !== String(indicatorProjectFilter)) {
return false;
}
if (indicatorUnitFilter !== 'all' && String(ind.unitOfMeasure) !== String(indicatorUnitFilter)) {
return false;
}
if (indicatorStatusFilter !== 'all') {
const statusObj = getIndicatorStatus(ind.actualAmount, ind.targetAmount);
if (indicatorStatusFilter === 'green' && statusObj.label !== '≥90%') return false;
if (indicatorStatusFilter === 'amber' && statusObj.label !== '70–89%') return false;
if (indicatorStatusFilter === 'red' && statusObj.label !== '<70%') return false;
if (indicatorStatusFilter === 'pending' && statusObj.label !== 'Pending') return false;
}
if (!indicatorSearchTerm.trim()) return true;
const q = indicatorSearchTerm.toLowerCase();
const name = (ind.name || '').toLowerCase();
const projId = String(ind.projectId || '').toLowerCase();
const unit = getUnitOfMeasureLabel(ind.unitOfMeasure).toLowerCase();
return name.includes(q) || projId.includes(q) || unit.includes(q);
});
const riskExportColumns: ExportColumn<Risk>[] = [
{ header: 'Risk ID', key: 'id' },
{ header: 'Risk Title', key: 'name' },
{ header: 'Risk Description', key: 'description' },
{ header: 'Project ID', key: 'projectId', format: (val) => `Project #${val}` },
{ header: 'Likelihood (1–5)', key: 'likelihood' },
{ header: 'Impact (1–5)', key: 'impact' },
{
header: 'Residual Score',
key: 'likelihood',
format: (_, item) => `${item.likelihood * item.impact} / 25`,
},
{
header: 'Severity Level',
key: 'likelihood',
format: (_, item) => getRiskScoreColor(item.likelihood, item.impact).level,
},
{ header: 'Risk Owner', key: 'owner', format: (val) => getUserEmail(val) },
{ header: 'Mitigation Action / Controls', key: 'mitigationAction', format: (val) => val || '—' },
];
const filteredRisks = risks.filter((rk) => {
if (riskProjectFilter !== 'all' && String(rk.projectId) !== String(riskProjectFilter)) {
return false;
}
if (riskSeverityFilter !== 'all') {
const color = getRiskScoreColor(rk.likelihood, rk.impact);
if (riskSeverityFilter.toLowerCase() !== color.level.toLowerCase()) {
return false;
}
}
if (!riskSearchTerm.trim()) return true;
const q = riskSearchTerm.toLowerCase();
const name = (rk.name || '').toLowerCase();
const desc = (rk.description || '').toLowerCase();
const projId = String(rk.projectId || '').toLowerCase();
const owner = getUserEmail(rk.owner).toLowerCase();
const mitig = (rk.mitigationAction || '').toLowerCase();
return name.includes(q) || desc.includes(q) || projId.includes(q) || owner.includes(q) || mitig.includes(q);
});
return (
<div className="space-y-6 max-w-7xl mx-auto">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 bg-[#0f1523]/80 backdrop-blur-md p-6 rounded-2xl border border-slate-800/80 shadow-xl">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 bg-[#0d121f]/90 p-5 rounded-2xl border border-slate-800/80 backdrop-blur-md shadow-xl">
<div>
<h2 className="text-2xl font-bold text-white tracking-tight flex items-center gap-2">
<span>M&E, Evidence & Risk Management</span>
<div className="flex items-center gap-2">
<h2 className="text-xl font-bold text-white tracking-tight">
M&amp;E, Evidence &amp; Risk Management
</h2>
<HelpTooltip
title="Monitoring & Evaluation Hub"
content="Track performance indicators, verify tangible deliverable evidence against statutory milestones, and maintain proactive risk mitigation plans."
placement="right"
/>
</h2>
</div>
<p className="text-xs text-slate-400 mt-1">
Verification workflow: Evidence Upload & Review Queue, Indicator Actuals Recording, and Risk Register.
Verification workflow: Evidence Upload &amp; Review Queue, Indicator Actuals Recording, and Risk Register.
</p>
</div>
@@ -286,16 +397,16 @@ export const MonitoringPage: React.FC = () => {
{activeTab === 'contracts' && (
<button
onClick={() => setIsCreateContractModalOpen(true)}
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 rounded-xl shadow-lg shadow-blue-500/20 transition cursor-pointer"
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 rounded-xl shadow-md shadow-blue-500/20 transition cursor-pointer"
>
<Plus className="w-4 h-4" />
Create Contract & Upload PDF
Create Contract &amp; Upload PDF
</button>
)}
{activeTab === 'indicators' && (
<button
onClick={() => setIsIndicatorModalOpen(true)}
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 rounded-xl shadow-lg shadow-blue-500/20 transition cursor-pointer"
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 rounded-xl shadow-md shadow-blue-500/20 transition cursor-pointer"
>
<Plus className="w-4 h-4" />
Define Indicator
@@ -304,7 +415,7 @@ export const MonitoringPage: React.FC = () => {
{activeTab === 'risks' && (
<button
onClick={openCreateRisk}
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 rounded-xl shadow-lg shadow-blue-500/20 transition cursor-pointer"
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 rounded-xl shadow-md shadow-blue-500/20 transition cursor-pointer"
>
<Plus className="w-4 h-4" />
Add Risk to Register
@@ -405,63 +516,196 @@ export const MonitoringPage: React.FC = () => {
{/* Tab 2: Indicators Table (M08) */}
{activeTab === 'indicators' && (
<div className="bg-[#0f1523]/80 backdrop-blur-md rounded-2xl border border-slate-800/80 shadow-xl overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-left text-xs border-collapse">
<thead>
<tr className="bg-slate-900/60 border-b border-slate-800/80 text-slate-400 uppercase tracking-wider font-semibold">
<th className="py-3.5 px-5">Indicator Name</th>
<th className="py-3.5 px-4">Project ID</th>
<th className="py-3.5 px-4">Unit of Measure</th>
<th className="py-3.5 px-4 text-right">Baseline</th>
<th className="py-3.5 px-4 text-right">Target</th>
<th className="py-3.5 px-4 text-right">Actual Recorded</th>
<th className="py-3.5 px-4">Status</th>
<th className="py-3.5 px-5 text-right">Action</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-800/50">
{loadingIndicators ? (
<tr>
<td colSpan={8} className="py-8 text-center text-slate-500">
Loading indicators...
</td>
<div className="space-y-4">
{/* Indicators Search and Filter Toolbar */}
<div className="flex flex-col lg:flex-row lg:items-center justify-between gap-3 bg-[#0d121f]/90 p-4 rounded-2xl border border-slate-800/80 backdrop-blur-sm">
<div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 flex-1 flex-wrap">
{/* Search */}
<div className="relative flex-1 min-w-[200px] max-w-md">
<Search className="w-4 h-4 text-slate-500 absolute left-3 top-3" />
<input
type="text"
placeholder="Search indicators, statement, project ID..."
value={indicatorSearchTerm}
onChange={(e) => setIndicatorSearchTerm(e.target.value)}
className="w-full pl-9 pr-4 py-2.5 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl focus:outline-none focus:ring-1 focus:ring-blue-500 text-slate-200 placeholder:text-slate-500 transition shadow-xs"
/>
</div>
{/* Project Filter */}
<div className="flex items-center gap-2">
<label className="text-xs text-slate-400 whitespace-nowrap font-medium">Project:</label>
<select
value={indicatorProjectFilter}
onChange={(e) => setIndicatorProjectFilter(e.target.value === 'all' ? 'all' : Number(e.target.value))}
className="px-3 py-2 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500 [&>option]:bg-slate-900"
>
<option value="all">All Projects ({projects.length})</option>
{projects.map((p) => (
<option key={p.id} value={p.id}>
{p.name} (#{p.id})
</option>
))}
</select>
</div>
{/* Status Filter */}
<div className="flex items-center gap-2">
<label className="text-xs text-slate-400 whitespace-nowrap flex items-center gap-1 font-medium">
<Filter className="w-3.5 h-3.5 text-slate-400" />
Status:
</label>
<select
value={indicatorStatusFilter}
onChange={(e) => setIndicatorStatusFilter(e.target.value)}
className="px-3 py-2 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500 [&>option]:bg-slate-900"
>
<option value="all">All Statuses</option>
<option value="green">≥90% Target Achieved</option>
<option value="amber">70–89% On Track</option>
<option value="red">&lt;70% Underperforming</option>
<option value="pending">Pending Actuals</option>
</select>
</div>
{/* Unit Filter */}
<div className="flex items-center gap-2">
<label className="text-xs text-slate-400 whitespace-nowrap font-medium">Unit:</label>
<select
value={indicatorUnitFilter}
onChange={(e) => setIndicatorUnitFilter(e.target.value === 'all' ? 'all' : Number(e.target.value))}
className="px-3 py-2 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500 [&>option]:bg-slate-900"
>
<option value="all">All Units</option>
{UNIT_OF_MEASURE_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
{(indicatorSearchTerm || indicatorProjectFilter !== 'all' || indicatorStatusFilter !== 'all' || indicatorUnitFilter !== 'all') && (
<button
type="button"
onClick={() => {
setIndicatorSearchTerm('');
setIndicatorProjectFilter('all');
setIndicatorStatusFilter('all');
setIndicatorUnitFilter('all');
}}
className="inline-flex items-center gap-1 text-[11px] font-semibold text-slate-400 hover:text-white px-2.5 py-2 bg-slate-800 hover:bg-slate-700 rounded-xl transition cursor-pointer"
>
<RotateCcw className="w-3 h-3" />
<span>Reset</span>
</button>
)}
</div>
{/* Action Buttons: Refresh & Export */}
<div className="flex items-center gap-2 self-end lg:self-center">
<button
type="button"
onClick={() => {
refetchIndicators();
success('Refreshed', 'Latest performance metrics loaded from API.');
}}
disabled={isFetchingIndicators}
className="inline-flex items-center justify-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-slate-300 bg-[#0d121f] hover:bg-slate-800 border border-slate-700/80 rounded-xl transition cursor-pointer shadow-xs disabled:opacity-50"
title="Refresh indicators from API"
>
<RefreshCw className={`w-3.5 h-3.5 text-blue-400 ${isFetchingIndicators ? 'animate-spin' : ''}`} />
<span>Refresh</span>
</button>
<ExportButton
title="M&E Performance Indicators"
subtitle="Baseline and target metrics tracking for monitoring and evaluation"
filename={`pfm-indicators-${new Date().toISOString().split('T')[0]}`}
columns={indicatorExportColumns}
data={filteredIndicators}
/>
</div>
</div>
{/* Indicators Table Card */}
<div className="bg-[#0f1523]/80 backdrop-blur-md rounded-2xl border border-slate-800/80 shadow-xl overflow-hidden">
<div className="p-4 border-b border-slate-800/80 flex items-center justify-between">
<h3 className="text-sm font-semibold text-white flex items-center gap-2">
<TrendingUp className="w-4 h-4 text-blue-400" />
Performance Indicators &amp; Actuals Ledger
</h3>
<span className="text-xs text-slate-400 font-mono">
Showing {filteredIndicators.length} of {indicators.length} indicators
</span>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left text-xs border-collapse">
<thead>
<tr className="bg-slate-900/60 border-b border-slate-800/80 text-slate-400 uppercase tracking-wider font-semibold">
<th className="py-3.5 px-5">Indicator Name</th>
<th className="py-3.5 px-4">Project ID</th>
<th className="py-3.5 px-4">Unit of Measure</th>
<th className="py-3.5 px-4 text-right">Baseline</th>
<th className="py-3.5 px-4 text-right">Target</th>
<th className="py-3.5 px-4 text-right">Actual Recorded</th>
<th className="py-3.5 px-4">Status</th>
<th className="py-3.5 px-5 text-right">Action</th>
</tr>
) : (
indicators.map((ind) => {
const statusObj = getIndicatorStatus(ind.actualAmount, ind.targetAmount);
return (
<tr key={ind.id} className="hover:bg-slate-800/40 transition-colors">
<td className="py-3.5 px-5 font-semibold text-white">{ind.name}</td>
<td className="py-3.5 px-4 text-slate-400 font-mono">Project #{ind.projectId}</td>
<td className="py-3.5 px-4 text-slate-300">{getUnitOfMeasureLabel(ind.unitOfMeasure)}</td>
<td className="py-3.5 px-4 text-right font-mono text-slate-400">{ind.baselineAmount}</td>
<td className="py-3.5 px-4 text-right font-mono font-bold text-white">{ind.targetAmount}</td>
<td className="py-3.5 px-4 text-right font-mono font-bold text-emerald-400 text-xs">
{ind.actualAmount}
</td>
<td className="py-3.5 px-4">
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${statusObj.badge}`}>
{statusObj.label}
</span>
</td>
<td className="py-3.5 px-5 text-right">
<button
onClick={() => {
setSelectedIndicatorForActual(ind);
setActualInput(ind.actualAmount);
}}
className="inline-flex items-center gap-1 text-xs font-semibold text-slate-300 hover:text-white bg-slate-800/80 hover:bg-slate-700 px-3 py-1.5 rounded-lg border border-slate-700/60 transition"
>
Record Actual
</button>
</td>
</tr>
);
})
)}
</tbody>
</table>
</thead>
<tbody className="divide-y divide-slate-800/50">
{loadingIndicators ? (
<tr>
<td colSpan={8} className="py-12 text-center text-slate-500">
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-blue-400" />
Loading project indicators from API...
</td>
</tr>
) : filteredIndicators.length === 0 ? (
<tr>
<td colSpan={8} className="py-12 text-center text-slate-500">
<TrendingUp className="w-8 h-8 text-slate-600 mx-auto mb-2" />
{indicatorSearchTerm || indicatorProjectFilter !== 'all' || indicatorStatusFilter !== 'all' || indicatorUnitFilter !== 'all'
? 'No indicators match your filter criteria.'
: 'No performance indicators defined yet. Click "Define Indicator" to begin.'}
</td>
</tr>
) : (
filteredIndicators.map((ind) => {
const statusObj = getIndicatorStatus(ind.actualAmount, ind.targetAmount);
return (
<tr key={ind.id} className="hover:bg-slate-800/40 transition-colors">
<td className="py-3.5 px-5 font-semibold text-white">{ind.name}</td>
<td className="py-3.5 px-4 text-slate-400 font-mono">Project #{ind.projectId}</td>
<td className="py-3.5 px-4 text-slate-300">{getUnitOfMeasureLabel(ind.unitOfMeasure)}</td>
<td className="py-3.5 px-4 text-right font-mono text-slate-400">{ind.baselineAmount}</td>
<td className="py-3.5 px-4 text-right font-mono font-bold text-white">{ind.targetAmount}</td>
<td className="py-3.5 px-4 text-right font-mono font-bold text-emerald-400 text-xs">
{ind.actualAmount}
</td>
<td className="py-3.5 px-4">
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${statusObj.badge}`}>
{statusObj.label}
</span>
</td>
<td className="py-3.5 px-5 text-right">
<button
onClick={() => {
setSelectedIndicatorForActual(ind);
setActualInput(ind.actualAmount);
}}
className="inline-flex items-center gap-1 text-xs font-semibold text-slate-300 hover:text-white bg-slate-800/80 hover:bg-slate-700 px-3 py-1.5 rounded-lg border border-slate-700/60 transition cursor-pointer"
>
Record Actual
</button>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
</div>
</div>
)}
@@ -478,20 +722,112 @@ export const MonitoringPage: React.FC = () => {
subtitle="ISO 31000 standard matrix — click on any cell to filter and inspect risks or edit mitigation controls"
/>
{/* Risk Register Table */}
{/* Risk Search & Filter Toolbar */}
<div className="flex flex-col lg:flex-row lg:items-center justify-between gap-3 bg-[#0d121f]/90 p-4 rounded-2xl border border-slate-800/80 backdrop-blur-sm">
<div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 flex-1 flex-wrap">
{/* Search */}
<div className="relative flex-1 min-w-[200px] max-w-md">
<Search className="w-4 h-4 text-slate-500 absolute left-3 top-3" />
<input
type="text"
placeholder="Search risks by title, description, owner, mitigations..."
value={riskSearchTerm}
onChange={(e) => setRiskSearchTerm(e.target.value)}
className="w-full pl-9 pr-4 py-2.5 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl focus:outline-none focus:ring-1 focus:ring-blue-500 text-slate-200 placeholder:text-slate-500 transition shadow-xs"
/>
</div>
{/* Project Filter */}
<div className="flex items-center gap-2">
<label className="text-xs text-slate-400 whitespace-nowrap font-medium">Project:</label>
<select
value={riskProjectFilter}
onChange={(e) => setRiskProjectFilter(e.target.value === 'all' ? 'all' : Number(e.target.value))}
className="px-3 py-2 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500 [&>option]:bg-slate-900"
>
<option value="all">All Projects ({projects.length})</option>
{projects.map((p) => (
<option key={p.id} value={p.id}>
{p.name} (#{p.id})
</option>
))}
</select>
</div>
{/* Severity Filter */}
<div className="flex items-center gap-2">
<label className="text-xs text-slate-400 whitespace-nowrap flex items-center gap-1 font-medium">
<Filter className="w-3.5 h-3.5 text-slate-400" />
Severity:
</label>
<select
value={riskSeverityFilter}
onChange={(e) => setRiskSeverityFilter(e.target.value)}
className="px-3 py-2 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500 [&>option]:bg-slate-900"
>
<option value="all">All Severities</option>
<option value="critical">Critical (16–25)</option>
<option value="high">High (12–15)</option>
<option value="medium">Medium (6–10)</option>
<option value="low">Low (1–5)</option>
</select>
</div>
{(riskSearchTerm || riskProjectFilter !== 'all' || riskSeverityFilter !== 'all') && (
<button
type="button"
onClick={() => {
setRiskSearchTerm('');
setRiskProjectFilter('all');
setRiskSeverityFilter('all');
}}
className="inline-flex items-center gap-1 text-[11px] font-semibold text-slate-400 hover:text-white px-2.5 py-2 bg-slate-800 hover:bg-slate-700 rounded-xl transition cursor-pointer"
>
<RotateCcw className="w-3 h-3" />
<span>Reset</span>
</button>
)}
</div>
{/* Action Buttons: Refresh & Export */}
<div className="flex items-center gap-2 self-end lg:self-center">
<button
type="button"
onClick={() => {
refetchRisks();
success('Refreshed', 'Latest risk evaluations and residual scores loaded.');
}}
disabled={isFetchingRisks}
className="inline-flex items-center justify-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-slate-300 bg-[#0d121f] hover:bg-slate-800 border border-slate-700/80 rounded-xl transition cursor-pointer shadow-xs disabled:opacity-50"
title="Refresh risks from API"
>
<RefreshCw className={`w-3.5 h-3.5 text-blue-400 ${isFetchingRisks ? 'animate-spin' : ''}`} />
<span>Refresh</span>
</button>
<ExportButton
title="Project Risk Register & Heatmap"
subtitle="Itemized audit log of identified risks and mitigation controls"
filename={`pfm-risks-${new Date().toISOString().split('T')[0]}`}
columns={riskExportColumns}
data={filteredRisks}
/>
</div>
</div>
{/* Risk Register Table Card */}
<div className="bg-[#0f1523]/80 backdrop-blur-md rounded-2xl border border-slate-800/80 shadow-xl overflow-hidden">
<div className="p-4 border-b border-slate-800/80 flex items-center justify-between bg-slate-900/60">
<div className="p-4 border-b border-slate-800/80 flex items-center justify-between">
<div>
<h4 className="text-sm font-bold text-white">Project Risk Register</h4>
<h4 className="text-sm font-bold text-white flex items-center gap-2">
<ShieldAlert className="w-4 h-4 text-blue-400" />
Project Risk Register
</h4>
<p className="text-[11px] text-slate-400">Complete itemized audit log of identified risks and residual scores</p>
</div>
<button
onClick={openCreateRisk}
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-500 rounded-xl transition shadow-md shadow-blue-500/20"
>
<Plus className="w-3.5 h-3.5" />
Add Risk
</button>
<span className="text-xs text-slate-400 font-mono">
Showing {filteredRisks.length} of {risks.length} risks
</span>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left text-xs border-collapse">
@@ -510,18 +846,22 @@ export const MonitoringPage: React.FC = () => {
<tbody className="divide-y divide-slate-800/50">
{loadingRisks ? (
<tr>
<td colSpan={8} className="py-8 text-center text-slate-500">
Loading risk register...
<td colSpan={8} className="py-12 text-center text-slate-500">
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-blue-400" />
Loading risk register from API...
</td>
</tr>
) : risks.length === 0 ? (
) : filteredRisks.length === 0 ? (
<tr>
<td colSpan={8} className="py-8 text-center text-slate-500">
No risks recorded in the register. Click &quot;Add Risk&quot; to log your first risk item.
<td colSpan={8} className="py-12 text-center text-slate-500">
<ShieldAlert className="w-8 h-8 text-slate-600 mx-auto mb-2" />
{riskSearchTerm || riskProjectFilter !== 'all' || riskSeverityFilter !== 'all'
? 'No risks match your filter criteria.'
: 'No risks recorded in the register. Click "Add Risk" to log your first risk item.'}
</td>
</tr>
) : (
risks.map((rk) => {
filteredRisks.map((rk) => {
const score = rk.likelihood * rk.impact;
const color = getRiskScoreColor(rk.likelihood, rk.impact);
return (
@@ -545,7 +885,7 @@ export const MonitoringPage: React.FC = () => {
<td className="py-3.5 px-4 text-right">
<button
onClick={() => openEditRisk(rk)}
className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-700/60 rounded-lg transition"
className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-700/60 rounded-lg transition cursor-pointer"
title="Edit Risk"
>
<Edit2 className="w-3.5 h-3.5" />
@@ -33,6 +33,9 @@ import {
Server,
Database,
Hash,
ChevronDown,
ChevronRight,
User as UserIcon,
} from 'lucide-react';
import {
getUsers,
@@ -77,6 +80,7 @@ import {
getNotificationStatusBadge,
getNotificationPlatformLabel,
getUserEmail,
registerUserEmails,
getActivityStatusBadge,
EMAIL_STATUSES_OPTIONS,
NOTIFICATION_STATUS_OPTIONS,
@@ -103,11 +107,29 @@ export const SettingsPage: React.FC = () => {
status: userStatusFilter !== 'all' ? userStatusFilter : undefined,
};
const { data: usersDirectory = [] } = useQuery({
queryKey: ['users-directory'],
queryFn: () => getUsers(1, 200),
staleTime: 5 * 60 * 1000,
});
const { data: usersList = [], isLoading: loadingUsers, refetch: refetchUsers } = useQuery({
queryKey: ['users', userStatusFilter, userEmailSearch],
queryFn: () => getUsers(1, 100, userFilter),
});
React.useEffect(() => {
if (usersDirectory && usersDirectory.length > 0) {
registerUserEmails(usersDirectory);
}
}, [usersDirectory]);
React.useEffect(() => {
if (usersList && usersList.length > 0) {
registerUserEmails(usersList);
}
}, [usersList]);
const { data: userFreshDetail, isLoading: loadingUserFreshDetail } = useQuery({
queryKey: ['user-canonical', selectedUserForDetail?.id],
queryFn: () => (selectedUserForDetail?.id ? getUser(selectedUserForDetail.id) : null),
@@ -238,21 +260,25 @@ export const SettingsPage: React.FC = () => {
// ==========================================
const [emailGatewayStatus, setEmailGatewayStatus] = useState<EmailStatuses>(EmailStatuses.Connected);
const [notificationSearchTerm, setNotificationSearchTerm] = useState('');
const [notificationOrgFilter, setNotificationOrgFilter] = useState<string>('all');
const [notificationOrgFilter, setNotificationOrgFilter] = useState<string>('');
const [notificationPlatformFilter, setNotificationPlatformFilter] = useState<string>('all');
const [notificationStatusFilter, setNotificationStatusFilter] = useState<string>('all');
const [selectedNotificationForDetail, setSelectedNotificationForDetail] = useState<Notification | null>(null);
const [isNotificationDetailModalOpen, setIsNotificationDetailModalOpen] = useState(false);
const [copiedNotificationPayload, setCopiedNotificationPayload] = useState(false);
const effectiveNotificationOrgId =
notificationOrgFilter || (organisations[0]?.id ? String(organisations[0].id) : '1');
const {
data: fetchedNotifications = [],
isLoading: loadingNotifications,
refetch: refetchNotifications,
isFetching: isFetchingNotifications,
} = useQuery({
queryKey: ['notifications', notificationOrgFilter],
queryFn: () => getNotifications(notificationOrgFilter === 'all' ? undefined : notificationOrgFilter),
queryKey: ['notifications', effectiveNotificationOrgId],
queryFn: () => getNotifications(effectiveNotificationOrgId),
enabled: !!effectiveNotificationOrgId,
});
const notificationExportColumns: ExportColumn<Notification>[] = [
@@ -270,9 +296,6 @@ export const SettingsPage: React.FC = () => {
];
const filteredNotifications = fetchedNotifications.filter((item) => {
if (notificationOrgFilter !== 'all' && String(item.organisationId) !== String(notificationOrgFilter)) {
return false;
}
if (notificationPlatformFilter !== 'all' && String(item.platform) !== String(notificationPlatformFilter)) {
return false;
}
@@ -305,6 +328,28 @@ export const SettingsPage: React.FC = () => {
const [auditActionFilter, setAuditActionFilter] = useState<string>('all');
const [selectedAuditLog, setSelectedAuditLog] = useState<AuditLog | null>(null);
const [isAuditDetailModalOpen, setIsAuditDetailModalOpen] = useState(false);
const [copiedAuditPayload, setCopiedAuditPayload] = useState(false);
const [expandedAuditLogIds, setExpandedAuditLogIds] = useState<Record<string | number, boolean>>({});
const [copiedUserId, setCopiedUserId] = useState<string | number | null>(null);
const toggleExpandAuditLog = (id: string | number) => {
setExpandedAuditLogIds((prev) => ({
...prev,
[id]: !prev[id],
}));
};
const handleCopyUserId = (userId: string | number, e?: React.MouseEvent) => {
if (e) e.stopPropagation();
if (!userId) return;
const strId = String(userId);
navigator.clipboard.writeText(strId);
setCopiedUserId(userId);
success('User ID Copied', `Copied ${strId} to clipboard.`);
setTimeout(() => {
setCopiedUserId((curr) => (curr === userId ? null : curr));
}, 2000);
};
const {
data: auditLogs = [],
@@ -313,62 +358,83 @@ export const SettingsPage: React.FC = () => {
isFetching: isFetchingAuditLogs,
} = useQuery({
queryKey: ['audit-logs'],
queryFn: () => getAuditLogs(1, 200),
queryFn: () => getAuditLogs(1, 100),
});
const auditExportColumns: ExportColumn<AuditLog>[] = [
{ header: 'Audit Event ID', key: 'id' },
{ header: 'Timestamp', key: 'createdAt', format: (val) => formatDate(val) },
{ header: 'Action Type', key: 'action' },
{ header: 'Entity Type', key: 'entityType' },
{ header: 'Entity Identifier', key: 'entityId' },
{ header: 'Actor User / System', key: 'userEmail', format: (val) => getUserEmail(val) },
{ header: 'Audit Details & Payload', key: 'details', format: (val) => val || '—' },
{ header: 'Event ID', key: 'id' },
{ header: 'Timestamp', key: 'timestamp', format: (val) => formatDate(val) },
{ header: 'Action', key: 'action', format: (val) => val || '—' },
{ header: 'Entity Name', key: 'entityName', format: (val) => val || '—' },
{ header: 'Entity ID', key: 'entityId', format: (val) => val || '—' },
{
header: 'Performed By (Email)',
key: 'performedBy',
format: (val) => {
const email = getUserEmail(val);
return email && email !== '—' ? `${email} (${val})` : String(val || 'System');
},
},
{ header: 'Tenant ID', key: 'tenantId', format: (val) => (val ? `Tenant #${val}` : '—') },
{
header: 'Changes',
key: 'changes',
format: (val) => (Array.isArray(val) ? val.join('; ') : val || '—'),
},
];
const uniqueAuditEntities = Array.from(
new Set(auditLogs.map((l) => l.entityName).filter((e): e is string => Boolean(e)))
);
const uniqueAuditActions = Array.from(
new Set(auditLogs.map((l) => l.action).filter((a): a is string => Boolean(a)))
);
const filteredAuditLogs = auditLogs.filter((log) => {
if (auditEntityFilter !== 'all' && log.entityType.toLowerCase() !== auditEntityFilter.toLowerCase()) {
if (auditEntityFilter !== 'all' && (log.entityName || '').toLowerCase() !== auditEntityFilter.toLowerCase()) {
return false;
}
if (auditActionFilter !== 'all' && log.action.toLowerCase() !== auditActionFilter.toLowerCase()) {
if (auditActionFilter !== 'all' && (log.action || '').toLowerCase() !== auditActionFilter.toLowerCase()) {
return false;
}
if (!auditSearchTerm.trim()) return true;
const q = auditSearchTerm.toLowerCase();
const id = (log.id || '').toLowerCase();
const id = String(log.id || '').toLowerCase();
const action = (log.action || '').toLowerCase();
const entityType = (log.entityType || '').toLowerCase();
const entityName = (log.entityName || '').toLowerCase();
const entityId = String(log.entityId || '').toLowerCase();
const email = (log.userEmail || '').toLowerCase();
const details = (log.details || '').toLowerCase();
const performedBy = (log.performedBy || '').toLowerCase();
const tenant = String(log.tenantId || '').toLowerCase();
const changes = Array.isArray(log.changes) ? log.changes.join(' ').toLowerCase() : '';
return (
id.includes(q) ||
action.includes(q) ||
entityType.includes(q) ||
entityName.includes(q) ||
entityId.includes(q) ||
email.includes(q) ||
details.includes(q)
performedBy.includes(q) ||
tenant.includes(q) ||
changes.includes(q)
);
});
const getActionBadge = (action: string) => {
const act = (action || '').toUpperCase();
const getActionBadge = (action?: string | null) => {
const act = (action || 'GENERAL_EVENT').toUpperCase();
if (act.includes('APPROV') || act.includes('RELEASE') || act.includes('AUTH') || act.includes('VERIF')) {
return { label: action, className: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30' };
return { label: action || 'APPROVED', className: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30' };
}
if (act.includes('CREATE') || act.includes('REGISTER') || act.includes('ADD') || act.includes('SCHEDULE')) {
return { label: action, className: 'bg-blue-500/10 text-blue-400 border-blue-500/30' };
if (act.includes('CREATE') || act.includes('REGISTER') || act.includes('ADD') || act.includes('POST') || act.includes('INSERT')) {
return { label: action || 'CREATED', className: 'bg-blue-500/10 text-blue-400 border-blue-500/30' };
}
if (act.includes('UPDATE') || act.includes('SYNC') || act.includes('EDIT')) {
return { label: action, className: 'bg-indigo-500/10 text-indigo-400 border-indigo-500/30' };
if (act.includes('UPDATE') || act.includes('SYNC') || act.includes('EDIT') || act.includes('PUT') || act.includes('PATCH')) {
return { label: action || 'UPDATED', className: 'bg-indigo-500/10 text-indigo-400 border-indigo-500/30' };
}
if (act.includes('DISPATCH') || act.includes('INVIT') || act.includes('SEND') || act.includes('NOTIF')) {
return { label: action, className: 'bg-purple-500/10 text-purple-400 border-purple-500/30' };
return { label: action || 'DISPATCHED', className: 'bg-purple-500/10 text-purple-400 border-purple-500/30' };
}
if (act.includes('DELETE') || act.includes('SUSPEND') || act.includes('REJECT') || act.includes('LOCK')) {
return { label: action, className: 'bg-rose-500/10 text-rose-400 border-rose-500/30' };
return { label: action || 'REJECTED', className: 'bg-rose-500/10 text-rose-400 border-rose-500/30' };
}
return { label: action, className: 'bg-slate-800 text-slate-300 border-slate-700' };
return { label: action || 'AUDIT_EVENT', className: 'bg-slate-800 text-slate-300 border-slate-700' };
};
return (
@@ -914,18 +980,21 @@ export const SettingsPage: React.FC = () => {
<div className="flex flex-wrap items-center gap-2">
<div className="flex items-center gap-1.5">
<Building2 className="w-3.5 h-3.5 text-slate-400" />
<span className="text-xs font-semibold text-slate-400 whitespace-nowrap">Target Org:</span>
<Building2 className="w-3.5 h-3.5 text-blue-400" />
<select
value={notificationOrgFilter}
onChange={(e) => setNotificationOrgFilter(e.target.value)}
className="text-xs bg-[#090d16] border border-slate-700/80 rounded-xl px-2.5 py-2 text-slate-300 focus:outline-none focus:ring-1 focus:ring-blue-500 [&>option]:bg-slate-900 [&>option]:text-white"
className="text-xs bg-[#090d16] border border-blue-500/40 rounded-xl px-2.5 py-2 text-white font-medium focus:outline-none focus:ring-1 focus:ring-blue-500 [&>option]:bg-slate-900 [&>option]:text-white"
>
<option value="all">All Organisations</option>
{organisations.map((org) => (
<option key={org.id} value={org.id}>
{org.name} (#{org.id})
{org.name || `Organisation #${org.id}`} (#{org.id})
</option>
))}
{organisations.length === 0 && (
<option value="1">Default Organisation (Org #1)</option>
)}
</select>
</div>
@@ -962,13 +1031,11 @@ export const SettingsPage: React.FC = () => {
</div>
{(notificationSearchTerm ||
notificationOrgFilter !== 'all' ||
notificationPlatformFilter !== 'all' ||
notificationStatusFilter !== 'all') && (
<button
onClick={() => {
setNotificationSearchTerm('');
setNotificationOrgFilter('all');
setNotificationPlatformFilter('all');
setNotificationStatusFilter('all');
}}
@@ -978,6 +1045,28 @@ export const SettingsPage: React.FC = () => {
Reset
</button>
)}
<button
type="button"
onClick={() => {
refetchNotifications();
success('Refreshed', `Transmissions updated for Organisation #${effectiveNotificationOrgId}.`);
}}
disabled={isFetchingNotifications}
className="inline-flex items-center justify-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-slate-300 bg-[#0d121f] hover:bg-slate-800 border border-slate-700/80 rounded-xl transition cursor-pointer shadow-xs disabled:opacity-50"
title="Force refresh notifications from API"
>
<RefreshCw className={`w-3.5 h-3.5 text-blue-400 ${isFetchingNotifications ? 'animate-spin' : ''}`} />
<span>Refresh</span>
</button>
<ExportButton
title="Communications &amp; Notifications Ledger"
subtitle={`Transmission telemetry report for Organisation #${effectiveNotificationOrgId}`}
filename={`pfm-notifications-org-${effectiveNotificationOrgId}-${new Date().toISOString().split('T')[0]}`}
columns={notificationExportColumns}
data={filteredNotifications}
/>
</div>
</div>
@@ -997,7 +1086,7 @@ export const SettingsPage: React.FC = () => {
/>
</div>
<span className="text-[11px] text-slate-400 font-mono">
GET /v1/api/communications/norifications/{notificationOrgFilter === 'all' ? '{organisationId}' : notificationOrgFilter}
GET /v1/api/communications/norifications/{effectiveNotificationOrgId}
</span>
</div>
@@ -1020,14 +1109,14 @@ export const SettingsPage: React.FC = () => {
<tr>
<td colSpan={8} className="py-12 text-center text-slate-500">
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-blue-400" />
Querying communication microservice endpoints...
Querying communication microservice endpoints for Organisation #{effectiveNotificationOrgId}...
</td>
</tr>
) : filteredNotifications.length === 0 ? (
<tr>
<td colSpan={8} className="py-12 text-center text-slate-500">
<Bell className="w-8 h-8 text-slate-600 mx-auto mb-2" />
No notification records returned matching filter criteria.
No notification records returned for Organisation #{effectiveNotificationOrgId}.
</td>
</tr>
) : (
@@ -1106,37 +1195,37 @@ export const SettingsPage: React.FC = () => {
Total Audit Events
</span>
<div className="text-xl font-bold font-mono text-white">{auditLogs.length}</div>
<span className="text-[10px] text-slate-500">Immutable ledger records</span>
<span className="text-[10px] text-slate-500">Live API ledger records</span>
</div>
<div className="bg-[#0f1523]/80 backdrop-blur-md p-4 rounded-2xl border border-slate-800/80 shadow-xl space-y-1">
<span className="text-[11px] font-semibold text-emerald-400 block uppercase tracking-wider">
Financial Operations
Audited Entities
</span>
<div className="text-xl font-bold font-mono text-emerald-300">
{auditLogs.filter((l) => ['Award', 'Budget', 'Disbursement'].includes(l.entityType)).length}
{uniqueAuditEntities.length}
</div>
<span className="text-[10px] text-slate-500">Awards, budgets &amp; disbursements</span>
<span className="text-[10px] text-slate-500">Distinct system resources</span>
</div>
<div className="bg-[#0f1523]/80 backdrop-blur-md p-4 rounded-2xl border border-slate-800/80 shadow-xl space-y-1">
<span className="text-[11px] font-semibold text-blue-400 block uppercase tracking-wider">
Security &amp; Auth
Active Actors
</span>
<div className="text-xl font-bold font-mono text-blue-300">
{auditLogs.filter((l) => ['User', 'Security', 'Invite'].includes(l.entityType)).length}
{new Set(auditLogs.map((l) => l.performedBy).filter(Boolean)).size}
</div>
<span className="text-[10px] text-slate-500">Logins, roles &amp; access syncs</span>
<span className="text-[10px] text-slate-500">Distinct caller UUIDs</span>
</div>
<div className="bg-[#0f1523]/80 backdrop-blur-md p-4 rounded-2xl border border-slate-800/80 shadow-xl space-y-1">
<span className="text-[11px] font-semibold text-purple-400 block uppercase tracking-wider">
Audited Actors
Action Categories
</span>
<div className="text-xl font-bold font-mono text-purple-300">
{new Set(auditLogs.map((l) => l.userEmail)).size}
{uniqueAuditActions.length}
</div>
<span className="text-[10px] text-slate-500">Unique authorized principals</span>
<span className="text-[10px] text-slate-500">Registered action types</span>
</div>
</div>
@@ -1148,7 +1237,7 @@ export const SettingsPage: React.FC = () => {
type="text"
value={auditSearchTerm}
onChange={(e) => setAuditSearchTerm(e.target.value)}
placeholder="Search audit trail by action, email, entity ID, or details..."
placeholder="Search audit trail by action, entity name, ID, performed by UUID..."
className="w-full pl-9 pr-3 py-2 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl text-white placeholder-slate-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
/>
</div>
@@ -1162,14 +1251,20 @@ export const SettingsPage: React.FC = () => {
className="text-xs bg-[#090d16] border border-slate-700/80 rounded-xl px-2.5 py-1.5 text-white focus:outline-none focus:ring-1 focus:ring-blue-500 [&>option]:bg-slate-900 [&>option]:text-white cursor-pointer"
>
<option value="all">All Entities</option>
<option value="User">User</option>
<option value="Award">Award</option>
<option value="Budget">Budget</option>
<option value="Disbursement">Disbursement</option>
<option value="Risk">Risk</option>
<option value="Evidence">Evidence</option>
<option value="Invite">Invite</option>
<option value="Security">Security</option>
{uniqueAuditEntities.map((ent) => (
<option key={ent} value={ent}>
{ent}
</option>
))}
{uniqueAuditEntities.length === 0 && (
<>
<option value="User">User</option>
<option value="Award">Award</option>
<option value="Budget">Budget</option>
<option value="Disbursement">Disbursement</option>
<option value="Risk">Risk</option>
</>
)}
</select>
</div>
@@ -1181,15 +1276,11 @@ export const SettingsPage: React.FC = () => {
className="text-xs bg-[#090d16] border border-slate-700/80 rounded-xl px-2.5 py-1.5 text-white focus:outline-none focus:ring-1 focus:ring-blue-500 [&>option]:bg-slate-900 [&>option]:text-white cursor-pointer"
>
<option value="all">All Actions</option>
<option value="USER_AUTHENTICATED">USER_AUTHENTICATED</option>
<option value="DISBURSEMENT_APPROVED">DISBURSEMENT_APPROVED</option>
<option value="DISBURSEMENT_SCHEDULED">DISBURSEMENT_SCHEDULED</option>
<option value="BUDGET_LINE_CREATED">BUDGET_LINE_CREATED</option>
<option value="AWARD_REGISTERED">AWARD_REGISTERED</option>
<option value="RISK_EVALUATED">RISK_EVALUATED</option>
<option value="EVIDENCE_VERIFIED">EVIDENCE_VERIFIED</option>
<option value="INVITATION_DISPATCHED">INVITATION_DISPATCHED</option>
<option value="DIRECTORY_SYNCED">DIRECTORY_SYNCED</option>
{uniqueAuditActions.map((act) => (
<option key={act} value={act}>
{act}
</option>
))}
</select>
</div>
@@ -1211,19 +1302,19 @@ export const SettingsPage: React.FC = () => {
type="button"
onClick={() => {
refetchAuditLogs();
success('Audit Ledger Refreshed', 'Latest audit log entries loaded.');
success('Refreshed', 'Latest audit log entries loaded from API.');
}}
disabled={isFetchingAuditLogs}
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-slate-300 bg-[#0d121f] hover:bg-slate-800 border border-slate-700/80 rounded-xl transition cursor-pointer shadow-xs disabled:opacity-50"
title="Refresh audit trail"
className="inline-flex items-center justify-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-slate-300 bg-[#0d121f] hover:bg-slate-800 border border-slate-700/80 rounded-xl transition cursor-pointer shadow-xs disabled:opacity-50"
title="Refresh audit trail from API"
>
<RefreshCw className={`w-3.5 h-3.5 text-blue-400 ${isFetchingAuditLogs ? 'animate-spin' : ''}`} />
<span className="hidden sm:inline">Refresh</span>
<span>Refresh</span>
</button>
<ExportButton
title="System Audit & Security Log"
subtitle="Complete audit trail of user access, statutory approvals, and financial transactions"
title="System Audit &amp; Security Log"
subtitle="Complete audit trail retrieved directly from /v1/api/governance/auditlog"
filename={`pfm-audit-trail-${new Date().toISOString().split('T')[0]}`}
columns={auditExportColumns}
data={filteredAuditLogs}
@@ -1233,74 +1324,235 @@ export const SettingsPage: React.FC = () => {
{/* Audit Logs Table */}
<div className="bg-[#0f1523]/80 backdrop-blur-md rounded-2xl border border-slate-800/80 shadow-xl overflow-hidden">
<div className="p-4 border-b border-slate-800/80 flex items-center justify-between">
<div className="flex items-center gap-2">
<History className="w-4 h-4 text-blue-400" />
<h3 className="text-sm font-semibold text-white">
Audit Log Ledger ({filteredAuditLogs.length} of {auditLogs.length})
</h3>
<HelpTooltip
title="Audit Trail"
content="Authoritative record of state changes retrieved via POST /v1/api/governance/auditlog."
size="sm"
placement="right"
/>
</div>
<span className="text-[11px] text-slate-400 font-mono">
POST /v1/api/governance/auditlog
</span>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left text-xs border-collapse">
<thead>
<tr className="bg-slate-900/60 border-b border-slate-800/80 text-slate-400 uppercase tracking-wider font-semibold">
<th className="py-3.5 px-5">Timestamp</th>
<th className="py-3.5 px-3 w-10 text-center"></th>
<th className="py-3.5 px-4">Timestamp</th>
<th className="py-3.5 px-4">Event ID</th>
<th className="py-3.5 px-4">Action</th>
<th className="py-3.5 px-4">Entity</th>
<th className="py-3.5 px-4">Actor</th>
<th className="py-3.5 px-4">Details &amp; Telemetry</th>
<th className="py-3.5 px-4">Performed By</th>
<th className="py-3.5 px-4">Changes</th>
<th className="py-3.5 px-5 text-right">Inspect</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-800/50">
{loadingAuditLogs ? (
<tr>
<td colSpan={7} className="py-8 text-center text-slate-500">
Loading system audit ledger...
<td colSpan={8} className="py-12 text-center text-slate-500">
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-blue-400" />
Querying governance audit log endpoints...
</td>
</tr>
) : filteredAuditLogs.length === 0 ? (
<tr>
<td colSpan={7} className="py-8 text-center text-slate-500">
<td colSpan={8} className="py-12 text-center text-slate-500">
<History className="w-8 h-8 text-slate-600 mx-auto mb-2" />
{auditSearchTerm || auditEntityFilter !== 'all' || auditActionFilter !== 'all'
? 'No audit log entries match your filter criteria.'
: 'No audit records logged yet.'}
: 'No audit records returned from endpoint.'}
</td>
</tr>
) : (
filteredAuditLogs.map((log) => {
const badge = getActionBadge(log.action);
const isExpanded = !!expandedAuditLogIds[log.id];
const changesCount = Array.isArray(log.changes) ? log.changes.length : 0;
const performerEmail = getUserEmail(log.performedBy);
const hasResolvedEmail = performerEmail && performerEmail !== '—' && !performerEmail.includes('—');
const displayEmail = hasResolvedEmail ? performerEmail : (log.performedBy || 'System');
return (
<tr key={log.id} className="hover:bg-slate-800/40 transition-colors">
<td className="py-3.5 px-5 font-mono text-slate-400 whitespace-nowrap text-[11px]">
{formatDate(log.createdAt)}
</td>
<td className="py-3.5 px-4 font-mono font-bold text-white whitespace-nowrap">
{log.id}
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${badge.className}`}>
{badge.label}
</span>
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
<span className="font-semibold text-slate-200 block">{log.entityType}</span>
<span className="text-[10px] text-slate-500 font-mono">#{log.entityId}</span>
</td>
<td className="py-3.5 px-4 text-slate-300 font-mono text-[11px]">
{getUserEmail(log.userEmail)}
</td>
<td className="py-3.5 px-4 text-slate-400 max-w-md truncate" title={log.details}>
{log.details || '—'}
</td>
<td className="py-3.5 px-5 text-right whitespace-nowrap">
<button
type="button"
onClick={() => {
setSelectedAuditLog(log);
setIsAuditDetailModalOpen(true);
}}
className="inline-flex items-center gap-1 px-2.5 py-1 text-[11px] font-semibold text-slate-300 bg-slate-800 hover:bg-slate-700 border border-slate-700 rounded-lg transition cursor-pointer"
<React.Fragment key={log.id}>
<tr
onClick={() => toggleExpandAuditLog(log.id)}
className={`hover:bg-slate-800/40 transition-colors cursor-pointer ${
isExpanded ? 'bg-slate-800/30' : ''
}`}
>
<td className="py-3.5 px-3 text-center">
<button
type="button"
onClick={(e) => {
e.stopPropagation();
toggleExpandAuditLog(log.id);
}}
className="p-1 rounded-md hover:bg-slate-700/80 text-slate-400 hover:text-white transition cursor-pointer"
title={isExpanded ? 'Collapse changes shelf' : 'Expand changes shelf'}
>
<ChevronRight
className={`w-3.5 h-3.5 transition-transform duration-200 ${
isExpanded ? 'rotate-90 text-blue-400' : 'text-slate-500'
}`}
/>
</button>
</td>
<td className="py-3.5 px-4 font-mono text-slate-400 whitespace-nowrap text-[11px]">
{formatDate(log.timestamp)}
</td>
<td className="py-3.5 px-4 font-mono font-bold text-white whitespace-nowrap">
#{log.id}
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${badge.className}`}>
{badge.label}
</span>
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
<span className="font-semibold text-slate-200 block">{log.entityName || 'General'}</span>
{log.entityId && (
<span className="text-[10px] text-slate-500 font-mono">#{log.entityId}</span>
)}
</td>
<td
className="py-3.5 px-4"
onClick={(e) => e.stopPropagation()}
>
<Eye className="w-3 h-3 text-blue-400" />
Inspect
</button>
</td>
</tr>
<div className="flex items-center gap-1.5 min-w-0 max-w-[220px]">
<span
className="text-slate-200 font-mono text-[11px] truncate block"
title={`${displayEmail}${log.performedBy ? ` (User ID: ${log.performedBy})` : ''}`}
>
{displayEmail}
</span>
{log.performedBy && (
<button
type="button"
onClick={(e) => handleCopyUserId(log.performedBy, e)}
className="p-1 rounded-md hover:bg-slate-700/80 text-slate-400 hover:text-white transition cursor-pointer shrink-0"
title={`Click to copy User ID (${log.performedBy})`}
>
{copiedUserId === log.performedBy ? (
<Check className="w-3.5 h-3.5 text-emerald-400" />
) : (
<Copy className="w-3.5 h-3.5 hover:text-blue-400" />
)}
</button>
)}
</div>
</td>
<td className="py-3.5 px-4">
<button
type="button"
onClick={(e) => {
e.stopPropagation();
toggleExpandAuditLog(log.id);
}}
className="inline-flex items-center gap-1.5 px-2 py-1 rounded-lg bg-slate-800/90 hover:bg-slate-700 border border-slate-700/80 text-[11px] text-slate-300 hover:text-white transition cursor-pointer"
title="Click to toggle changes shelf"
>
<Layers className="w-3 h-3 text-blue-400" />
<span>{changesCount} {changesCount === 1 ? 'change' : 'changes'}</span>
<ChevronDown
className={`w-3 h-3 text-slate-400 transition-transform duration-200 ${
isExpanded ? 'rotate-180 text-blue-400' : ''
}`}
/>
</button>
</td>
<td className="py-3.5 px-5 text-right whitespace-nowrap">
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setSelectedAuditLog(log);
setIsAuditDetailModalOpen(true);
}}
className="inline-flex items-center gap-1 px-2.5 py-1 text-[11px] font-semibold text-slate-300 bg-slate-800 hover:bg-slate-700 border border-slate-700 rounded-lg transition cursor-pointer"
>
<Eye className="w-3 h-3 text-blue-400" />
Inspect
</button>
</td>
</tr>
{/* Expanding Shelf for Changes Content */}
{isExpanded && (
<tr className="bg-[#080c14] border-b border-slate-800/80">
<td colSpan={8} className="p-4 sm:p-5 bg-gradient-to-r from-[#0d121f] via-[#090d16] to-[#0d121f]">
<div className="rounded-xl border border-slate-800/90 bg-[#070a12]/90 p-4 space-y-3 shadow-inner">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-slate-800/80 pb-3">
<div className="flex items-center gap-2">
<Layers className="w-4 h-4 text-blue-400" />
<h4 className="text-xs font-bold text-white uppercase tracking-wider">
Recorded Changes Content (Event #{log.id})
</h4>
<span className="text-[10px] font-mono px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-400 border border-blue-500/20 font-semibold">
{changesCount} {changesCount === 1 ? 'Entry' : 'Entries'}
</span>
</div>
<div className="flex items-center gap-3 text-xs text-slate-400">
<span>
Entity: <strong className="text-white">{log.entityName || 'General'}</strong> {log.entityId ? `(#${log.entityId})` : ''}
</span>
<span>•</span>
<span className="flex items-center gap-1">
Performer: <strong className="text-slate-200 font-mono text-[11px]">{displayEmail}</strong>
{log.performedBy && (
<button
type="button"
onClick={(e) => handleCopyUserId(log.performedBy, e)}
className="p-1 rounded hover:bg-slate-800 text-slate-400 hover:text-white transition cursor-pointer"
title={`Copy User ID: ${log.performedBy}`}
>
{copiedUserId === log.performedBy ? (
<Check className="w-3 h-3 text-emerald-400" />
) : (
<Copy className="w-3 h-3 text-slate-400 hover:text-blue-400" />
)}
</button>
)}
</span>
</div>
</div>
{/* Changes List */}
{Array.isArray(log.changes) && log.changes.length > 0 ? (
<div className="space-y-2">
{log.changes.map((changeItem, idx) => (
<div
key={idx}
className="flex items-start gap-3 p-3 bg-slate-900/90 rounded-xl border border-slate-800/80 text-xs font-mono shadow-xs hover:border-slate-700 transition"
>
<span className="px-2 py-0.5 rounded-md bg-blue-500/10 text-blue-400 border border-blue-500/20 text-[10px] font-bold shrink-0 mt-0.5">
#{idx + 1}
</span>
<div className="flex-1 text-emerald-400 leading-relaxed break-all">
{changeItem}
</div>
</div>
))}
</div>
) : (
<div className="p-4 rounded-xl bg-slate-900/50 border border-slate-800/80 text-center text-slate-400 text-xs font-mono">
No itemized field changes content recorded for this event.
</div>
)}
</div>
</td>
</tr>
)}
</React.Fragment>
);
})
)}
@@ -1319,9 +1571,10 @@ export const SettingsPage: React.FC = () => {
onClose={() => {
setIsAuditDetailModalOpen(false);
setSelectedAuditLog(null);
setCopiedAuditPayload(false);
}}
title={`Audit Event: ${selectedAuditLog?.id || ''}`}
subtitle="Cryptographic verification and authoritative event metadata"
title={`Audit Event: #${selectedAuditLog?.id || ''}`}
subtitle="Authoritative event payload from /v1/api/governance/auditlog"
>
{selectedAuditLog && (
<div className="space-y-4 text-xs">
@@ -1329,37 +1582,112 @@ export const SettingsPage: React.FC = () => {
<div className="flex justify-between items-center border-b border-slate-800/80 pb-2">
<span className="text-slate-400 font-semibold uppercase text-[11px]">Action Type:</span>
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border ${getActionBadge(selectedAuditLog.action).className}`}>
{selectedAuditLog.action}
{selectedAuditLog.action || 'EVENT'}
</span>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<span className="text-slate-400 font-semibold block text-[11px] uppercase">Entity Type:</span>
<span className="text-white font-semibold">{selectedAuditLog.entityType}</span>
<span className="text-slate-400 font-semibold block text-[11px] uppercase">Entity Name:</span>
<span className="text-white font-semibold">{selectedAuditLog.entityName || '—'}</span>
</div>
<div>
<span className="text-slate-400 font-semibold block text-[11px] uppercase">Entity ID:</span>
<span className="font-mono text-slate-300">{selectedAuditLog.entityId}</span>
<span className="font-mono text-slate-300">{selectedAuditLog.entityId || '—'}</span>
</div>
</div>
<div className="grid grid-cols-2 gap-3 border-t border-slate-800/80 pt-2">
<div>
<span className="text-slate-400 font-semibold block text-[11px] uppercase">Actor / Principal:</span>
<span className="font-mono text-slate-200 break-all">{selectedAuditLog.userEmail}</span>
<span className="text-slate-400 font-semibold block text-[11px] uppercase">Performed By:</span>
<div className="flex items-center gap-1.5 mt-0.5">
<span className="font-mono text-slate-200 text-[11px] truncate">
{getUserEmail(selectedAuditLog.performedBy) !== '—'
? getUserEmail(selectedAuditLog.performedBy)
: (selectedAuditLog.performedBy || 'System')}
</span>
{selectedAuditLog.performedBy && (
<button
type="button"
onClick={(e) => handleCopyUserId(selectedAuditLog.performedBy, e)}
className="p-1 rounded hover:bg-slate-700/80 text-slate-400 hover:text-white transition cursor-pointer shrink-0"
title={`Copy User ID: ${selectedAuditLog.performedBy}`}
>
{copiedUserId === selectedAuditLog.performedBy ? (
<Check className="w-3.5 h-3.5 text-emerald-400" />
) : (
<Copy className="w-3.5 h-3.5 hover:text-blue-400" />
)}
</button>
)}
</div>
{selectedAuditLog.performedBy && (
<span className="text-[10px] text-slate-500 font-mono block mt-0.5 truncate">
ID: {selectedAuditLog.performedBy}
</span>
)}
</div>
<div>
<span className="text-slate-400 font-semibold block text-[11px] uppercase">Logged Timestamp:</span>
<span className="font-mono text-slate-300">{formatDate(selectedAuditLog.createdAt)}</span>
<span className="font-mono text-slate-300 block mt-0.5">{formatDate(selectedAuditLog.timestamp)}</span>
</div>
</div>
<div className="border-t border-slate-800/80 pt-2">
<span className="text-slate-400 font-semibold block text-[11px] uppercase mb-1">Details &amp; Audit Trail:</span>
<p className="p-3 rounded-lg bg-slate-900 border border-slate-800 text-slate-300 leading-relaxed font-mono text-[11px]">
{selectedAuditLog.details || 'No additional payload notes recorded for this transaction.'}
</p>
{selectedAuditLog.tenantId && (
<div className="border-t border-slate-800/80 pt-2">
<span className="text-slate-400 font-semibold block text-[11px] uppercase">Tenant Scope:</span>
<span className="font-mono text-slate-300">Tenant #{selectedAuditLog.tenantId}</span>
</div>
)}
<div className="border-t border-slate-800/80 pt-2 space-y-1">
<span className="text-slate-400 font-semibold block text-[11px] uppercase mb-1">State Changes / Delta:</span>
{Array.isArray(selectedAuditLog.changes) && selectedAuditLog.changes.length > 0 ? (
<ul className="space-y-1 p-2 rounded-lg bg-slate-900 border border-slate-800">
{selectedAuditLog.changes.map((ch, idx) => (
<li key={idx} className="font-mono text-emerald-400/90 text-[11px] flex items-center gap-1.5">
<span className="w-1.5 h-1.5 rounded-full bg-emerald-400" />
{ch}
</li>
))}
</ul>
) : (
<p className="p-3 rounded-lg bg-slate-900 border border-slate-800 text-slate-400 leading-relaxed font-mono text-[11px]">
No granular delta changes specified in audit payload.
</p>
)}
</div>
{/* Raw JSON Data Viewer */}
<div className="border-t border-slate-800/80 pt-2.5 space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-slate-400 font-semibold text-[11px] uppercase">
Raw Audit Record (JSON):
</span>
<button
onClick={() => {
navigator.clipboard.writeText(JSON.stringify(selectedAuditLog, null, 2));
setCopiedAuditPayload(true);
setTimeout(() => setCopiedAuditPayload(false), 2000);
}}
className="inline-flex items-center gap-1 text-[10px] font-medium text-slate-400 hover:text-white bg-slate-800 px-2 py-1 rounded transition cursor-pointer"
>
{copiedAuditPayload ? (
<>
<Check className="w-3 h-3 text-emerald-400" />
<span className="text-emerald-400">Copied</span>
</>
) : (
<>
<Copy className="w-3 h-3" />
<span>Copy JSON</span>
</>
)}
</button>
</div>
<pre className="p-3 rounded-lg bg-[#070a12] border border-slate-800/80 text-emerald-300/90 font-mono text-[10.5px] overflow-x-auto max-h-48">
{JSON.stringify(selectedAuditLog, null, 2)}
</pre>
</div>
</div>
@@ -1369,6 +1697,7 @@ export const SettingsPage: React.FC = () => {
onClick={() => {
setIsAuditDetailModalOpen(false);
setSelectedAuditLog(null);
setCopiedAuditPayload(false);
}}
className="px-4 py-2 text-xs font-semibold text-white bg-slate-800 hover:bg-slate-700 rounded-xl transition cursor-pointer"
>