Redesigned dash

This commit is contained in:
2026-09-29 12:24:04 +02:00
parent 8643b2625b
commit 8d069c2da0
3 changed files with 77 additions and 321 deletions
@@ -1,321 +1,5 @@
import React, { useEffect, useState, useMemo } from 'react';
import { useAuth } from '../../auth/AuthProvider';
import { api, extractApiErrors } from '../../services/api';
import { Project, Award, Milestone, Activity, Evidence } from '../../services/api/models';
import { encodeHashIdSync } from '../../services/toolsService';
import { ProjectCard } from './ProjectCard';
import {
Building2,
FolderKanban,
Award as AwardIcon,
RefreshCw,
LogOut,
Search,
Filter,
AlertTriangle,
Sparkles,
Layers,
CheckCircle2,
Clock,
HelpCircle
} from 'lucide-react';
import React from 'react';
export const DashboardPage: React.FC = () => {
const { user, logout } = useAuth();
const [isLoading, setIsLoading] = useState(true);
const [isRefreshing, setIsRefreshing] = useState(false);
const [errorMessages, setErrorMessages] = useState<string[]>([]);
// Raw fetched data
const [awards, setAwards] = useState<Award[]>([]);
const [projects, setProjects] = useState<Project[]>([]);
const [milestonesByProject, setMilestonesByProject] = useState<Record<string, Milestone[]>>({});
const [activitiesByProject, setActivitiesByProject] = useState<Record<string, Activity[]>>({});
const [evidenceByProject, setEvidenceByProject] = useState<Record<string, Evidence[]>>({});
// Filter & Search states
const [searchQuery, setSearchQuery] = useState('');
const [statusFilter, setStatusFilter] = useState<string>('all');
const hashedTenantId = user?.tenant_id !== undefined && user?.tenant_id !== null
? encodeHashIdSync(user.tenant_id)
: '';
// Main data loader function
const loadDashboardData = async (isBackgroundRefresh = false) => {
if (!isBackgroundRefresh) setIsLoading(true);
else setIsRefreshing(true);
setErrorMessages([]);
try {
// 1. Access the endpoint that returns applicant awards
const [awardsRes, projectsRes] = await Promise.all([
api.grants.getAwards({ page: 1, pageSize: 100 }).catch((err) => {
console.warn('Awards fetch warning:', err);
return { data: [] as Award[] };
}),
api.projects.getProjects({ page: 1, pageSize: 100 }).catch((err) => {
console.warn('Projects fetch warning:', err);
return { data: [] as Project[] };
}),
]);
const rawAwards: Award[] = Array.isArray(awardsRes?.data) ? awardsRes.data : [];
let rawProjects: Project[] = Array.isArray(projectsRes?.data) ? projectsRes.data : [];
// Extract unique linked project IDs from awards
const linkedProjectIdsFromAwards = Array.from(
new Set(rawAwards.map((a) => a.projectId).filter((id): id is string | number => id !== undefined && id !== null && id !== ''))
);
// If awards reference project IDs not in rawProjects, fetch them individually
const existingProjectIds = new Set(rawProjects.map((p) => String(p.id)));
const missingProjectIds = linkedProjectIdsFromAwards.filter((id) => !existingProjectIds.has(String(id)));
if (missingProjectIds.length > 0) {
const fetchedMissing = await Promise.all(
missingProjectIds.map(async (pId) => {
try {
const res = await api.projects.getProject(pId);
return res?.data;
} catch {
// Return a placeholder project linked to the award
return {
id: pId,
name: `Project #${encodeHashIdSync(pId)}`,
status: 'Active',
} as Project;
}
})
);
rawProjects = [...rawProjects, ...fetchedMissing.filter((p): p is Project => !!p)];
}
// If no projects exist but awards exist, create synthetic project containers for them
if (rawProjects.length === 0 && rawAwards.length > 0) {
rawProjects = rawAwards.map((award, idx) => ({
id: award.projectId || award.id || idx + 1,
name: `Grantee Portfolio #${encodeHashIdSync(award.projectId || award.id || idx + 1)}`,
status: 'Active',
budget: award.amount,
createdAt: award.createdAt,
}));
}
setAwards(rawAwards);
setProjects(rawProjects);
// 2. Fetch milestones, activities, and evidence for each project
const milestonesMap: Record<string, Milestone[]> = {};
const activitiesMap: Record<string, Activity[]> = {};
const evidenceMap: Record<string, Evidence[]> = {};
await Promise.all(
rawProjects.map(async (proj) => {
const pKey = String(proj.id);
try {
const [mRes, aRes, eRes] = await Promise.all([
api.projects.getProjectMilestones(proj.id!).catch(() => ({ data: [] as Milestone[] })),
api.projects.getProjectActivities(proj.id!).catch(() => ({ data: [] as Activity[] })),
api.evidence.getProjectEvidence(proj.id!).catch(() => ({ data: [] as Evidence[] })),
]);
milestonesMap[pKey] = Array.isArray(mRes?.data) ? mRes.data : [];
activitiesMap[pKey] = Array.isArray(aRes?.data) ? aRes.data : [];
evidenceMap[pKey] = Array.isArray(eRes?.data) ? eRes.data : [];
} catch (e) {
milestonesMap[pKey] = [];
activitiesMap[pKey] = [];
evidenceMap[pKey] = [];
}
})
);
setMilestonesByProject(milestonesMap);
setActivitiesByProject(activitiesMap);
setEvidenceByProject(evidenceMap);
} catch (err: any) {
console.error('[Dashboard Load Error]:', err);
const errors = extractApiErrors(err);
setErrorMessages(errors);
} finally {
setIsLoading(false);
setIsRefreshing(false);
}
};
useEffect(() => {
loadDashboardData();
}, []);
// Filter projects by search and status
const filteredProjects = useMemo(() => {
return projects.filter((p) => {
const pKey = String(p.id);
const projAwards = awards.filter((a) => String(a.projectId) === pKey);
const matchSearch =
!searchQuery.trim() ||
(p.name && p.name.toLowerCase().includes(searchQuery.toLowerCase())) ||
(p.code && p.code.toLowerCase().includes(searchQuery.toLowerCase())) ||
encodeHashIdSync(p.id).toLowerCase().includes(searchQuery.toLowerCase()) ||
projAwards.some((a) => encodeHashIdSync(a.id).toLowerCase().includes(searchQuery.toLowerCase()));
const matchStatus =
statusFilter === 'all' ||
String(p.status || '').toLowerCase().includes(statusFilter.toLowerCase());
return matchSearch && matchStatus;
});
}, [projects, awards, searchQuery, statusFilter]);
return (
<div className="space-y-8 pb-16">
{/* Uncluttered Top Bar-Free Grantee Context Header */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-6 pb-6 border-b border-white/10">
<div className="space-y-1.5">
<div className="flex items-center gap-2.5">
<span className="text-xs font-bold uppercase tracking-widest bg-gradient-to-r from-emerald-400 via-teal-300 to-cyan-300 bg-clip-text text-transparent">
PFM Grantee Portal
</span>
{hashedTenantId && (
<span className="font-mono text-[11px] font-bold text-emerald-300 bg-emerald-950/80 border border-emerald-500/30 px-2 py-0.5 rounded-lg shadow-sm">
#{hashedTenantId}
</span>
)}
</div>
<h1 className="text-2xl sm:text-3xl font-extrabold tracking-tight text-white">
{user?.tenant || 'Grantee Portfolio Overview'}
</h1>
<p className="text-xs sm:text-sm text-slate-300 max-w-2xl leading-relaxed">
Welcome, <span className="font-semibold text-slate-100">{user?.name || 'Grantee Partner'}</span> ({user?.email || 'Authorized Grantee'}). Access historic awards, track deliverable milestones, and submit activity evidence dossiers.
</p>
</div>
{/* Minimalist Top Actions (Refresh & Sign Out) */}
<div className="flex items-center gap-3 shrink-0">
<button
onClick={() => loadDashboardData(true)}
disabled={isRefreshing || isLoading}
className="flex items-center gap-2 px-3.5 py-2 rounded-2xl bg-white/[0.04] hover:bg-white/[0.08] border border-white/10 text-xs font-semibold text-slate-200 hover:text-white transition-all cursor-pointer shadow-sm active:scale-95"
title="Refresh latest awards and project milestones"
>
<RefreshCw className={`w-3.5 h-3.5 text-emerald-400 ${isRefreshing ? 'animate-spin' : ''}`} />
<span>{isRefreshing ? 'Refreshing...' : 'Sync Data'}</span>
</button>
<button
onClick={logout}
className="flex items-center gap-2 px-3.5 py-2 rounded-2xl bg-white/[0.04] hover:bg-rose-500/10 border border-white/10 hover:border-rose-500/30 text-xs font-semibold text-slate-300 hover:text-rose-200 transition-all cursor-pointer shadow-sm active:scale-95"
title="Sign out of partner portal"
>
<LogOut className="w-3.5 h-3.5 text-slate-400" />
<span>Sign Out</span>
</button>
</div>
</div>
{/* Global Error Banner (Comma-delimited error display) */}
{errorMessages.length > 0 && (
<div className="p-4 rounded-3xl bg-rose-950/70 border border-rose-500/40 text-rose-200 text-xs space-y-2 backdrop-blur-xl shadow-2xl animate-in fade-in">
<div className="flex items-center gap-2 font-bold text-rose-300">
<AlertTriangle className="w-4 h-4 text-rose-400 shrink-0" />
<span>Notice: API server returned validation issues:</span>
</div>
<ul className="list-disc pl-6 space-y-1 text-[11px] font-mono text-rose-200/90">
{errorMessages.map((msg, idx) => (
<li key={idx}>{msg}</li>
))}
</ul>
</div>
)}
{/* Search & Filter Controls */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div className="flex items-center gap-3 flex-1 max-w-md">
<div className="relative w-full">
<Search className="w-4 h-4 absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type="text"
placeholder="Search projects by name, code or #hash..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-9 pr-4 py-2 rounded-2xl bg-slate-900/60 border border-white/10 text-xs text-slate-200 placeholder:text-slate-500 focus:outline-none focus:border-emerald-500/50 backdrop-blur-md"
/>
</div>
</div>
<div className="flex items-center gap-3">
<div className="relative">
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
aria-label="Filter projects by status"
className="pl-3.5 pr-8 py-2 rounded-2xl bg-slate-900/60 border border-white/10 text-xs text-slate-200 focus:outline-none focus:border-emerald-500/50 appearance-none backdrop-blur-md cursor-pointer"
>
<option value="all">All Project Statuses</option>
<option value="active">Active</option>
<option value="approved">Approved</option>
<option value="pending">Pending</option>
<option value="completed">Completed</option>
</select>
<Filter className="w-3.5 h-3.5 absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
</div>
</div>
</div>
{/* Main Content Area */}
{isLoading ? (
<div className="py-24 flex flex-col items-center justify-center gap-4 text-slate-400">
<div className="h-8 w-8 animate-spin rounded-full border-2 border-emerald-500 border-t-transparent shadow-[0_0_15px_rgba(16,185,129,0.3)]" />
<span className="text-xs font-mono">Retrieving applicant awards and project deliverables...</span>
</div>
) : filteredProjects.length === 0 ? (
<div className="p-12 rounded-3xl border border-white/10 bg-slate-900/40 text-center space-y-3 backdrop-blur-xl">
<div className="inline-flex p-3 rounded-2xl bg-white/5 border border-white/10 text-slate-400">
<FolderKanban className="w-6 h-6" />
</div>
<h3 className="text-base font-bold text-white">No Projects or Awards Found</h3>
<p className="text-xs text-slate-400 max-w-md mx-auto">
{searchQuery
? 'No project records matched your search query. Try clearing the filter.'
: 'There are currently no active or historical awards linked to this grantee account.'}
</p>
{searchQuery && (
<button
onClick={() => {
setSearchQuery('');
setStatusFilter('all');
}}
className="mt-2 text-xs text-emerald-400 hover:text-emerald-300 font-semibold underline cursor-pointer"
>
Clear filters
</button>
)}
</div>
) : (
<div className="space-y-6">
{filteredProjects.map((project) => {
const pKey = String(project.id);
const projectAwards = awards.filter((a) => String(a.projectId) === pKey);
const projectMilestones = milestonesByProject[pKey] || [];
const projectActivities = activitiesByProject[pKey] || [];
const projectEvidence = evidenceByProject[pKey] || [];
return (
<ProjectCard
key={project.id}
project={project}
awards={projectAwards}
milestones={projectMilestones}
activities={projectActivities}
evidenceList={projectEvidence}
onEvidenceUploaded={() => loadDashboardData(true)}
/>
);
})}
</div>
)}
</div>
);
return null;
};