Added, beneficiaries, site visits and change management

This commit is contained in:
2026-09-27 11:40:28 +02:00
parent fb27cc8c92
commit 36e5d3d7c8
16 changed files with 3132 additions and 212 deletions
@@ -0,0 +1,502 @@
import React, { useState, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import {
MapPin,
Calendar,
User,
Plus,
CheckCircle2,
AlertCircle,
RefreshCw,
Search,
MessageSquare,
Edit2,
FolderKanban,
FileText,
ShieldCheck,
Building,
Send,
} from 'lucide-react';
import {
getProjects,
getProjectSiteVisits,
createSiteVisit,
updateSiteVisit,
} from '../services/api';
import { Modal } from '../components/ui/Modal';
import { useToast } from '../components/ui/Toast';
import { ExportButton } from '../components/ui/ExportButton';
import { ExportColumn } from '../utils/exportUtils';
import { useTableSort, SortableTh } from '../utils/tableSort';
import { SiteVisit, ApprovalStatus } from '../types';
import {
getApprovalStatusBadge,
formatDate,
APPROVAL_STATUS_OPTIONS,
} from '../lib/formatters';
const siteVisitSchema = z.object({
inspectorName: z.string().min(2, 'Inspector name required'),
visitedAt: z.string().min(4, 'Visit date is required'),
findings: z.string().min(5, 'Field findings and observations required'),
status: z.coerce.number().optional(),
});
type SiteVisitFormValues = z.infer<typeof siteVisitSchema>;
export const SiteVisitsPage: React.FC = () => {
const queryClient = useQueryClient();
const { success, error: toastError } = useToast();
const [selectedProjectId, setSelectedProjectId] = useState<string>('all');
const [searchTerm, setSearchTerm] = useState('');
// Modals
const [isVisitModalOpen, setIsVisitModalOpen] = useState(false);
const [editingVisit, setEditingVisit] = useState<SiteVisit | null>(null);
const [selectedVisitForDetail, setSelectedVisitForDetail] = useState<SiteVisit | null>(null);
const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
// Queries
const { data: projects = [], isLoading: loadingProjects } = useQuery({
queryKey: ['projects'],
queryFn: () => getProjects(),
});
const effectiveProjectId = selectedProjectId !== 'all' ? selectedProjectId : projects[0]?.id;
const {
data: siteVisits = [],
isLoading: loadingVisits,
refetch: refetchVisits,
isFetching: fetchingVisits,
} = useQuery({
queryKey: ['siteVisits', effectiveProjectId],
queryFn: () => (effectiveProjectId ? getProjectSiteVisits(effectiveProjectId) : Promise.resolve([])),
enabled: !!effectiveProjectId,
});
// Forms
const visitForm = useForm<SiteVisitFormValues>({
resolver: zodResolver(siteVisitSchema),
defaultValues: {
inspectorName: '',
visitedAt: new Date().toISOString().split('T')[0],
findings: '',
status: ApprovalStatus.Pending,
},
});
// Mutations
const createVisitMutation = useMutation({
mutationFn: (vals: SiteVisitFormValues) => {
if (!effectiveProjectId) throw new Error('No project selected');
return createSiteVisit({
projectId: effectiveProjectId,
inspectorName: vals.inspectorName,
findings: vals.findings,
visitedAt: vals.visitedAt,
});
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['siteVisits'] });
setIsVisitModalOpen(false);
visitForm.reset();
success('Site Visit Logged', 'Field inspection recorded with inspector findings.');
},
onError: (err: any) => toastError('Logging Failed', err.message || 'Unable to save site visit.'),
});
const updateVisitMutation = useMutation({
mutationFn: (vals: SiteVisitFormValues) => {
if (!editingVisit) throw new Error('No visit selected');
return updateSiteVisit({
siteVisitId: editingVisit.id,
inspectorName: vals.inspectorName,
findings: vals.findings,
status: vals.status ?? ApprovalStatus.Pending,
visitedAt: vals.visitedAt,
});
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['siteVisits'] });
setIsVisitModalOpen(false);
setEditingVisit(null);
visitForm.reset();
success('Site Visit Updated', 'Inspection report and verification status updated.');
},
onError: (err: any) => toastError('Update Failed', err.message || 'Unable to update site visit.'),
});
// Filtered & Sorted Visits
const filteredVisits = useMemo(() => {
return siteVisits.filter((v) => {
return (
!searchTerm.trim() ||
(v.inspectorName && v.inspectorName.toLowerCase().includes(searchTerm.toLowerCase())) ||
(v.findings && v.findings.toLowerCase().includes(searchTerm.toLowerCase()))
);
});
}, [siteVisits, searchTerm]);
const { sortedData: sortedVisits, sortColumn: visitSortCol, sortDirection: visitSortDir, handleSort: handleVisitSort } =
useTableSort(filteredVisits);
// Exports
const visitExportCols: ExportColumn<SiteVisit>[] = [
{ header: 'Inspector Name', key: 'inspectorName' },
{ header: 'Visit Date', accessor: (v) => formatDate(v.visitedAt) },
{ header: 'Findings', key: 'findings' },
{ header: 'Status', accessor: (v) => (v.status === ApprovalStatus.Approved ? 'Approved' : 'Pending') },
];
const handleOpenEdit = (v: SiteVisit) => {
setEditingVisit(v);
visitForm.reset({
inspectorName: v.inspectorName || '',
visitedAt: v.visitedAt ? v.visitedAt.split('T')[0] : new Date().toISOString().split('T')[0],
findings: v.findings || '',
status: v.status ?? ApprovalStatus.Pending,
});
setIsVisitModalOpen(true);
};
return (
<div className="space-y-8 pb-16">
{/* Header Banner */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-gradient-to-r from-[#0d1322] via-[#0f172a] to-[#0d1322] p-6 sm:p-8 rounded-3xl border border-slate-800/80 shadow-2xl relative overflow-hidden">
<div className="absolute -right-10 -bottom-10 w-60 h-60 bg-emerald-600/10 rounded-full blur-3xl pointer-events-none" />
<div className="space-y-2 relative z-10">
<div className="flex items-center gap-3">
<div className="h-12 w-12 rounded-2xl bg-emerald-600/20 border border-emerald-500/30 flex items-center justify-center text-emerald-400 shadow-lg shadow-emerald-500/10">
<MapPin className="w-6 h-6" />
</div>
<div>
<h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-white flex items-center gap-2.5">
Site Visits & Field Verification
</h1>
<p className="text-xs sm:text-sm text-slate-400">
Log physical inspection reports, record field findings, and capture project feedback.
</p>
</div>
</div>
</div>
<div className="flex items-center gap-2.5 flex-wrap relative z-10">
<button
onClick={() => refetchVisits()}
disabled={fetchingVisits}
className="flex items-center gap-2 px-3.5 py-2.5 rounded-xl text-xs font-semibold bg-slate-900/90 text-slate-300 hover:text-white border border-slate-800 hover:bg-slate-800/80 transition cursor-pointer"
>
<RefreshCw className={`w-3.5 h-3.5 ${fetchingVisits ? 'animate-spin text-emerald-400' : ''}`} />
<span>Refresh</span>
</button>
<ExportButton data={sortedVisits} columns={visitExportCols} filename="site_visits" title="Site Visits Log" />
<button
onClick={() => {
setEditingVisit(null);
visitForm.reset({
inspectorName: '',
visitedAt: new Date().toISOString().split('T')[0],
findings: '',
status: ApprovalStatus.Pending,
});
setIsVisitModalOpen(true);
}}
className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-semibold bg-gradient-to-r from-emerald-600 to-teal-600 text-white hover:from-emerald-500 hover:to-teal-500 shadow-lg shadow-emerald-600/25 transition cursor-pointer"
>
<Plus className="w-4 h-4" />
<span>Log Site Visit</span>
</button>
</div>
</div>
{/* KPI Cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<div className="bg-[#0f1523]/80 backdrop-blur-md p-5 rounded-2xl border border-slate-800/80 shadow-xl space-y-2">
<div className="flex items-center justify-between text-slate-400">
<span className="text-xs font-semibold uppercase tracking-wider">Total Site Visits</span>
<MapPin className="w-4 h-4 text-emerald-400" />
</div>
<p className="text-2xl font-bold text-white">{siteVisits.length}</p>
<p className="text-[11px] text-slate-400">Field inspections logged</p>
</div>
<div className="bg-[#0f1523]/80 backdrop-blur-md p-5 rounded-2xl border border-slate-800/80 shadow-xl space-y-2">
<div className="flex items-center justify-between text-slate-400">
<span className="text-xs font-semibold uppercase tracking-wider">Approved Reports</span>
<CheckCircle2 className="w-4 h-4 text-teal-400" />
</div>
<p className="text-2xl font-bold text-teal-400">
{siteVisits.filter((v) => v.status === ApprovalStatus.Approved).length}
</p>
<p className="text-[11px] text-slate-400">Verified by project governance</p>
</div>
<div className="bg-[#0f1523]/80 backdrop-blur-md p-5 rounded-2xl border border-slate-800/80 shadow-xl space-y-2">
<div className="flex items-center justify-between text-slate-400">
<span className="text-xs font-semibold uppercase tracking-wider">Under Review</span>
<FileText className="w-4 h-4 text-amber-400" />
</div>
<p className="text-2xl font-bold text-amber-400">
{siteVisits.filter((v) => v.status === ApprovalStatus.Pending || v.status === ApprovalStatus.Review).length}
</p>
<p className="text-[11px] text-slate-400">Awaiting sign-off</p>
</div>
<div className="bg-[#0f1523]/80 backdrop-blur-md p-5 rounded-2xl border border-slate-800/80 shadow-xl space-y-2">
<div className="flex items-center justify-between text-slate-400">
<span className="text-xs font-semibold uppercase tracking-wider">Audited Projects</span>
<Building className="w-4 h-4 text-blue-400" />
</div>
<p className="text-2xl font-bold text-blue-400">{projects.length}</p>
<p className="text-[11px] text-slate-400">Under physical monitoring</p>
</div>
</div>
{/* Toolbar */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-800 pb-3">
<div className="flex items-center gap-3 flex-wrap">
<div className="flex items-center gap-2 text-xs text-slate-400">
<FolderKanban className="w-3.5 h-3.5 text-emerald-400" />
<span>Project:</span>
<select
value={selectedProjectId}
onChange={(e) => setSelectedProjectId(e.target.value)}
className="bg-slate-900 border border-slate-800 rounded-xl px-3 py-1.5 text-xs text-white focus:outline-none focus:border-emerald-500"
>
{projects.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
</div>
<div className="relative">
<Search className="w-3.5 h-3.5 absolute left-3 top-2.5 text-slate-400" />
<input
type="text"
placeholder="Search inspector / findings..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="bg-slate-900 border border-slate-800 rounded-xl pl-8 pr-3 py-1.5 text-xs text-white focus:outline-none focus:border-emerald-500 w-48 sm:w-64"
/>
</div>
</div>
</div>
{/* Table */}
<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 border-collapse">
<thead>
<tr className="border-b border-slate-800/80 bg-slate-900/50 text-[11px] font-semibold text-slate-400 uppercase tracking-wider">
<SortableTh column="inspectorName" currentColumn={visitSortCol} direction={visitSortDir} onSort={handleVisitSort}>
Inspector Name
</SortableTh>
<SortableTh column="visitedAt" currentColumn={visitSortCol} direction={visitSortDir} onSort={handleVisitSort}>
Inspection Date
</SortableTh>
<SortableTh column="findings" currentColumn={visitSortCol} direction={visitSortDir} onSort={handleVisitSort}>
Field Observations & Findings
</SortableTh>
<SortableTh column="status" currentColumn={visitSortCol} direction={visitSortDir} onSort={handleVisitSort}>
Verification Status
</SortableTh>
<th className="py-3 px-4 text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-800/60 text-xs">
{loadingVisits ? (
<tr>
<td colSpan={5} className="py-12 text-center text-slate-400">
<div className="flex flex-col items-center gap-2">
<div className="w-6 h-6 border-2 border-emerald-500 border-t-transparent rounded-full animate-spin" />
<span>Loading site visit logs...</span>
</div>
</td>
</tr>
) : sortedVisits.length === 0 ? (
<tr>
<td colSpan={5} className="py-12 text-center text-slate-400">
No site visits recorded for this project yet.
</td>
</tr>
) : (
sortedVisits.map((v) => (
<tr key={v.id} className="hover:bg-slate-800/30 transition">
<td className="py-3.5 px-4 font-semibold text-white">
<div className="flex items-center gap-2">
<User className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
<span>{v.inspectorName || 'Field Officer'}</span>
</div>
</td>
<td className="py-3.5 px-4 text-slate-300 font-medium">
<div className="flex items-center gap-1.5 text-slate-300">
<Calendar className="w-3 h-3 text-slate-500" />
<span>{formatDate(v.visitedAt)}</span>
</div>
</td>
<td className="py-3.5 px-4 text-slate-300 max-w-sm truncate" title={v.findings || ''}>
{v.findings || 'No findings recorded.'}
</td>
<td className="py-3.5 px-4">{getApprovalStatusBadge(v.status)}</td>
<td className="py-3.5 px-4 text-right space-x-2">
<button
onClick={() => {
setSelectedVisitForDetail(v);
setIsDetailModalOpen(true);
}}
className="px-2.5 py-1 text-xs font-medium text-emerald-400 hover:text-emerald-300 bg-emerald-950/40 hover:bg-emerald-900/40 rounded-lg border border-emerald-800/40 transition cursor-pointer"
>
View & Feedback
</button>
<button
onClick={() => handleOpenEdit(v)}
className="p-1 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg transition cursor-pointer"
title="Edit site visit"
>
<Edit2 className="w-3.5 h-3.5" />
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
{/* Modal: Create/Edit Site Visit */}
<Modal
isOpen={isVisitModalOpen}
onClose={() => setIsVisitModalOpen(false)}
title={editingVisit ? 'Edit Site Visit Report' : 'Log Project Site Visit'}
size="md"
>
<form
onSubmit={visitForm.handleSubmit((d) => (editingVisit ? updateVisitMutation.mutate(d) : createVisitMutation.mutate(d)))}
className="space-y-4"
>
<div>
<label className="block text-xs font-semibold text-slate-300 mb-1">Inspector / Officer Name *</label>
<input
{...visitForm.register('inspectorName')}
className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-emerald-500"
placeholder="e.g. Dr. K. Mokoena (Lead M&E Auditor)"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-300 mb-1">Inspection Date *</label>
<input
type="date"
{...visitForm.register('visitedAt')}
className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-emerald-500"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-300 mb-1">Field Findings & Observations *</label>
<textarea
rows={4}
{...visitForm.register('findings')}
className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-emerald-500"
placeholder="Detail on-site verification, physical progress, equipment installed, and beneficiary feedback..."
/>
</div>
{editingVisit && (
<div>
<label className="block text-xs font-semibold text-slate-300 mb-1">Verification Status</label>
<select
{...visitForm.register('status')}
className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-emerald-500"
>
{APPROVAL_STATUS_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
)}
<div className="flex justify-end gap-3 pt-4 border-t border-slate-800">
<button
type="button"
onClick={() => setIsVisitModalOpen(false)}
className="px-4 py-2 rounded-xl text-xs font-semibold text-slate-400 hover:text-white hover:bg-slate-800 transition"
>
Cancel
</button>
<button
type="submit"
disabled={createVisitMutation.isPending || updateVisitMutation.isPending}
className="px-4 py-2 rounded-xl text-xs font-semibold bg-emerald-600 hover:bg-emerald-500 text-white transition shadow-md shadow-emerald-600/30"
>
{editingVisit ? 'Update Report' : 'Save Site Visit'}
</button>
</div>
</form>
</Modal>
{/* Modal: Detail & Feedback */}
{selectedVisitForDetail && (
<Modal
isOpen={isDetailModalOpen}
onClose={() => setIsDetailModalOpen(false)}
title={`Site Visit: ${selectedVisitForDetail.inspectorName || 'Field Inspection'}`}
size="lg"
>
<div className="space-y-6">
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 bg-slate-900/60 p-4 rounded-xl border border-slate-800">
<div>
<span className="text-[10px] uppercase font-semibold text-slate-400 block">Inspection Date</span>
<span className="text-xs font-bold text-white">{formatDate(selectedVisitForDetail.visitedAt)}</span>
</div>
<div>
<span className="text-[10px] uppercase font-semibold text-slate-400 block">Status</span>
<div className="mt-0.5">{getApprovalStatusBadge(selectedVisitForDetail.status)}</div>
</div>
<div>
<span className="text-[10px] uppercase font-semibold text-slate-400 block">Inspector</span>
<span className="text-xs font-bold text-emerald-400">{selectedVisitForDetail.inspectorName}</span>
</div>
</div>
<div>
<h4 className="text-xs font-bold text-white uppercase tracking-wider mb-2 flex items-center gap-2">
<FileText className="w-4 h-4 text-emerald-400" />
<span>Field Findings & Observations</span>
</h4>
<div className="p-4 bg-slate-900/60 rounded-xl border border-slate-800 text-xs text-slate-200 whitespace-pre-wrap leading-relaxed">
{selectedVisitForDetail.findings || 'No detailed findings recorded.'}
</div>
</div>
{/* Feedback & Governance Notes Section */}
<div className="space-y-3 pt-4 border-t border-slate-800">
<h4 className="text-xs font-bold text-white uppercase tracking-wider flex items-center gap-2">
<MessageSquare className="w-4 h-4 text-blue-400" />
<span>Governance & Remediation Feedback</span>
</h4>
<div className="p-3 bg-blue-950/20 border border-blue-800/40 rounded-xl text-xs text-blue-300">
Site visit report is documented in the central monitoring audit ledger. You can update findings or sign off this
field evaluation using the edit report action.
</div>
</div>
</div>
</Modal>
)}
</div>
);
};