Fixed API calls on governance page

Enforced multitenancy
This commit is contained in:
2026-09-26 10:28:43 +02:00
parent b2688867f3
commit f3a8f78144
16 changed files with 3552 additions and 503 deletions
@@ -0,0 +1,696 @@
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 {
FileText,
Plus,
Search,
Filter,
RefreshCw,
Edit2,
Eye,
Layers,
Calendar,
User as UserIcon,
Tag,
CheckCircle2,
AlertCircle,
} from 'lucide-react';
import { Modal } from '../ui/Modal';
import { HelpTooltip } from '../ui/HelpTooltip';
import { useToast } from '../ui/Toast';
import {
Instruction,
Programme,
ActivityStatus,
} from '../../types';
import {
getAllInstructions,
createInstruction,
updateInstruction,
} from '../../services/api';
import {
getActivityStatusBadge,
formatDate,
getUserEmail,
ACTIVITY_STATUS_OPTIONS,
} from '../../lib/formatters';
const instructionSchema = z.object({
programmeId: z.coerce.number().min(1, 'Please select an associated programme'),
name: z.string().min(3, 'Instruction title must be at least 3 characters'),
code: z.string().optional(),
description: z.string().min(5, 'Description is required (minimum 5 characters)'),
status: z.coerce.number().default(ActivityStatus.Active),
});
type InstructionFormValues = z.infer<typeof instructionSchema>;
interface InstructionsSectionProps {
programmes: Programme[];
currentUserId: string;
preselectedProgrammeId?: string | number | null;
onClearPreselectedProgramme?: () => void;
isCreateModalOpenExternal?: boolean;
onCloseCreateModalExternal?: () => void;
}
export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
programmes,
currentUserId,
preselectedProgrammeId,
onClearPreselectedProgramme,
isCreateModalOpenExternal,
onCloseCreateModalExternal,
}) => {
const queryClient = useQueryClient();
const { success, error: toastError } = useToast();
const [searchTerm, setSearchTerm] = useState('');
const [selectedProgrammeFilter, setSelectedProgrammeFilter] = useState<string>(
preselectedProgrammeId ? String(preselectedProgrammeId) : 'all'
);
const [statusFilter, setStatusFilter] = useState<string>('all');
// Modals
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingInstruction, setEditingInstruction] = useState<Instruction | null>(null);
const [inspectingInstruction, setInspectingInstruction] = useState<Instruction | null>(null);
// Sync external create modal trigger if provided
React.useEffect(() => {
if (isCreateModalOpenExternal) {
setEditingInstruction(null);
instructionForm.reset({
programmeId: preselectedProgrammeId ? Number(preselectedProgrammeId) : (programmes[0]?.id ? Number(programmes[0].id) : 0),
name: '',
code: '',
description: '',
status: ActivityStatus.Active,
});
setIsModalOpen(true);
}
}, [isCreateModalOpenExternal, preselectedProgrammeId, programmes]);
// Form setup
const instructionForm = useForm<InstructionFormValues>({
resolver: zodResolver(instructionSchema),
defaultValues: {
programmeId: programmes[0]?.id ? Number(programmes[0].id) : 0,
name: '',
code: '',
description: '',
status: ActivityStatus.Active,
},
});
// Query: Get all instructions
const {
data: instructions = [],
isLoading,
isFetching,
refetch,
} = useQuery({
queryKey: ['all-instructions', programmes],
queryFn: () => getAllInstructions(programmes),
});
// Programme lookup helper
const programmeMap = useMemo(() => {
const map = new Map<string, Programme>();
programmes.forEach((p) => map.set(String(p.id), p));
return map;
}, [programmes]);
// Mutation: Create or Update Instruction
const mutation = useMutation({
mutationFn: async (data: InstructionFormValues) => {
if (editingInstruction) {
await updateInstruction({
instructionId: editingInstruction.id,
programmeId: data.programmeId,
code: data.code,
name: data.name,
description: data.description,
status: data.status !== undefined ? Number(data.status) : ActivityStatus.Active,
userId: currentUserId,
});
} else {
await createInstruction({
programmeId: data.programmeId,
code: data.code,
name: data.name,
description: data.description,
status: data.status !== undefined ? Number(data.status) : ActivityStatus.Active,
userId: currentUserId,
});
}
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['all-instructions'] });
queryClient.invalidateQueries({ queryKey: ['instruments'] });
success(
editingInstruction ? 'Instruction Updated' : 'Instruction Created',
editingInstruction
? 'Funding instruction record updated successfully.'
: 'New funding instruction attached to programme successfully.'
);
setIsModalOpen(false);
setEditingInstruction(null);
if (onCloseCreateModalExternal) onCloseCreateModalExternal();
},
onError: (err: any) => {
toastError('Save Failed', err?.message || 'Failed to save instruction');
},
});
// Handlers
const openCreateModal = (programmeId?: number | string) => {
setEditingInstruction(null);
instructionForm.reset({
programmeId: programmeId
? Number(programmeId)
: selectedProgrammeFilter !== 'all'
? Number(selectedProgrammeFilter)
: programmes[0]?.id
? Number(programmes[0].id)
: 0,
name: '',
code: '',
description: '',
status: ActivityStatus.Active,
});
setIsModalOpen(true);
};
const openEditModal = (inst: Instruction) => {
setEditingInstruction(inst);
instructionForm.reset({
programmeId: Number(inst.programmeId),
name: inst.name || '',
code: inst.code || '',
description: inst.description || '',
status: Number(inst.status),
});
setIsModalOpen(true);
};
const handleCloseModal = () => {
setIsModalOpen(false);
setEditingInstruction(null);
if (onCloseCreateModalExternal) onCloseCreateModalExternal();
};
// Filter instructions
const filteredInstructions = useMemo(() => {
return instructions.filter((inst) => {
// Programme filter
if (selectedProgrammeFilter !== 'all' && String(inst.programmeId) !== String(selectedProgrammeFilter)) {
return false;
}
// Status filter
if (statusFilter !== 'all' && String(inst.status) !== String(statusFilter)) {
return false;
}
// Search term
if (searchTerm.trim()) {
const query = searchTerm.toLowerCase();
const pName = programmeMap.get(String(inst.programmeId))?.name?.toLowerCase() || '';
const matchTitle = (inst.name || '').toLowerCase().includes(query);
const matchCode = (inst.code || '').toLowerCase().includes(query);
const matchDesc = (inst.description || '').toLowerCase().includes(query);
const matchProg = pName.includes(query);
if (!matchTitle && !matchCode && !matchDesc && !matchProg) {
return false;
}
}
return true;
});
}, [instructions, selectedProgrammeFilter, statusFilter, searchTerm, programmeMap]);
return (
<div className="space-y-4">
{/* Top Filter and Actions Bar */}
<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">
{/* Search Input */}
<div className="relative flex-1 max-w-md">
<Search className="w-4 h-4 text-slate-500 absolute left-3 top-3" />
<input
type="text"
placeholder="Search instructions by title, code, description, or programme..."
value={searchTerm}
onChange={(e) => setSearchTerm(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>
{/* Programme Filter Dropdown */}
<div className="flex items-center gap-2">
<label className="text-xs text-slate-400 whitespace-nowrap flex items-center gap-1 font-medium">
<Layers className="w-3.5 h-3.5 text-slate-400" />
Programme:
</label>
<select
value={selectedProgrammeFilter}
onChange={(e) => {
setSelectedProgrammeFilter(e.target.value);
if (onClearPreselectedProgramme && e.target.value === 'all') {
onClearPreselectedProgramme();
}
}}
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 max-w-[200px]"
>
<option value="all">All Programmes ({programmes.length})</option>
{programmes.map((p) => (
<option key={p.id} value={String(p.id)}>
{p.name}
</option>
))}
</select>
</div>
{/* Status Filter Dropdown */}
<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={statusFilter}
onChange={(e) => setStatusFilter(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 value="all">All Statuses</option>
<option value={String(ActivityStatus.Active)}>Active</option>
<option value={String(ActivityStatus.Inactive)}>Inactive</option>
</select>
</div>
</div>
{/* Action Buttons */}
<div className="flex items-center gap-2 self-end lg:self-center">
<button
type="button"
onClick={() => refetch()}
disabled={isFetching}
className="inline-flex items-center gap-1.5 px-3 py-2 text-xs font-semibold text-slate-300 bg-slate-800/80 hover:bg-slate-700 rounded-xl border border-slate-700 transition cursor-pointer"
title="Refresh Instructions"
>
<RefreshCw className={`w-3.5 h-3.5 ${isFetching ? 'animate-spin' : ''}`} />
Refresh
</button>
<button
type="button"
onClick={() => openCreateModal()}
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 Instruction
</button>
</div>
</div>
{/* Instructions Table & Cards */}
<div className="rounded-2xl border border-slate-800/80 bg-[#0d121f]/90 overflow-hidden shadow-xl">
<div className="p-4 border-b border-slate-800/80 flex items-center justify-between">
<div className="flex items-center gap-2">
<FileText className="w-4 h-4 text-blue-400" />
<h3 className="text-xs font-bold text-slate-200 uppercase tracking-wider">
Funding Instructions & Instrument Guidelines ({filteredInstructions.length})
</h3>
<HelpTooltip
title="Funding Instructions"
content="Binding operational instructions and instrument guidelines tied to strategic funding programmes. Defines implementation directives and compliance standards."
placement="right"
size="sm"
/>
</div>
<span className="text-[11px] text-slate-400 font-mono">
{filteredInstructions.length} of {instructions.length} recorded
</span>
</div>
{isLoading ? (
<div className="p-12 text-center text-xs text-slate-400 flex flex-col items-center justify-center gap-2">
<RefreshCw className="w-5 h-5 animate-spin text-blue-400" />
<span>Loading instructions directory...</span>
</div>
) : filteredInstructions.length === 0 ? (
<div className="p-12 text-center text-xs text-slate-400 space-y-3">
<div className="text-slate-500">
{searchTerm || selectedProgrammeFilter !== 'all' || statusFilter !== 'all'
? 'No funding instructions match the active filters.'
: 'No funding instructions registered yet. Link instructions to programmes using the button below.'}
</div>
<button
type="button"
onClick={() => openCreateModal()}
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-500 rounded-xl transition cursor-pointer"
>
<Plus className="w-4 h-4" />
Add First Instruction
</button>
</div>
) : (
<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">
<th className="py-3 px-4">Code / Ref</th>
<th className="py-3 px-4">Instruction Title</th>
<th className="py-3 px-4">Associated Programme</th>
<th className="py-3 px-4">Status</th>
<th className="py-3 px-4">Created Info</th>
<th className="py-3 px-4 text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-800/60 text-xs text-slate-300">
{filteredInstructions.map((inst) => {
const statusBadge = getActivityStatusBadge(inst.status);
const parentProg = programmeMap.get(String(inst.programmeId));
return (
<tr key={inst.id} className="hover:bg-slate-800/30 transition-colors">
<td className="py-3.5 px-4 font-mono font-bold text-blue-400">
<span className="bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20 text-[11px]">
{inst.code || `INST-${inst.id}`}
</span>
</td>
<td className="py-3.5 px-4">
<div className="font-semibold text-white max-w-sm">{inst.name}</div>
{inst.description && (
<div className="text-[11px] text-slate-400 line-clamp-1 mt-0.5 max-w-md">
{inst.description}
</div>
)}
</td>
<td className="py-3.5 px-4">
{parentProg ? (
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs bg-slate-800/80 text-slate-200 border border-slate-700 font-medium">
<Layers className="w-3 h-3 text-blue-400" />
{parentProg.name}
</span>
) : (
<span className="text-slate-500 font-mono text-xs">
Programme #{inst.programmeId}
</span>
)}
</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 ${statusBadge.className}`}
>
{statusBadge.label}
</span>
</td>
<td className="py-3.5 px-4 text-[11px] text-slate-400 font-mono">
<div>{formatDate(inst.createdAt)}</div>
{inst.createdBy && (
<div className="text-[10px] text-slate-500">{getUserEmail(inst.createdBy)}</div>
)}
</td>
<td className="py-3.5 px-4 text-right">
<div className="flex items-center justify-end gap-1.5">
<button
type="button"
onClick={() => setInspectingInstruction(inst)}
className="inline-flex items-center gap-1 text-xs font-semibold text-cyan-400 hover:text-white bg-cyan-500/10 hover:bg-cyan-500/20 border border-cyan-500/30 px-2.5 py-1 rounded-lg transition shadow-xs cursor-pointer"
title="Inspect Instruction"
>
<Eye className="w-3 h-3" />
Inspect
</button>
<button
type="button"
onClick={() => openEditModal(inst)}
className="inline-flex items-center gap-1 text-xs font-semibold text-slate-200 hover:text-white bg-slate-900/80 hover:bg-slate-800 border border-slate-700/80 px-2.5 py-1 rounded-lg transition shadow-xs cursor-pointer"
title="Edit / Mutate Instruction"
>
<Edit2 className="w-3 h-3" />
Edit
</button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
{/* Modal: Create / Edit Instruction */}
<Modal
isOpen={isModalOpen}
onClose={handleCloseModal}
title={editingInstruction ? 'Edit Funding Instruction' : 'Add New Funding Instruction'}
subtitle={
editingInstruction
? `Mutating Instruction ${editingInstruction.code || `#${editingInstruction.id}`}`
: 'Authoritative operational instruction attached to a strategic programme'
}
helpText="Instructions operationalize funding programmes into concrete binding directives. Choose an existing programme from the dropdown to link data."
>
<form
onSubmit={instructionForm.handleSubmit((data) => mutation.mutate(data))}
className="space-y-4"
>
{/* Associated Programme Dropdown */}
<div>
<div className="flex items-center gap-1 mb-1">
<label className="block text-xs font-semibold text-slate-300">
Associated Programme *
</label>
<HelpTooltip
title="Associated Programme"
content="Select the strategic funding programme under which this operational instruction is established."
size="sm"
/>
</div>
<select
{...instructionForm.register('programmeId')}
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
>
<option value="">Select an associated programme...</option>
{programmes.map((p) => (
<option key={p.id} value={Number(p.id)}>
{p.name}
</option>
))}
</select>
{instructionForm.formState.errors.programmeId && (
<p className="text-red-400 text-[11px] mt-1">
{instructionForm.formState.errors.programmeId.message}
</p>
)}
</div>
{/* Title */}
<div>
<div className="flex items-center gap-1 mb-1">
<label className="block text-xs font-semibold text-slate-300">
Instruction Title *
</label>
<HelpTooltip
title="Instruction Title"
content="Formal title of the funding instruction or instrument (e.g., SME Technology Transfer Subsidy Guideline)."
size="sm"
/>
</div>
<input
type="text"
placeholder="e.g. Clean Energy Grant Directive 2026"
{...instructionForm.register('name')}
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
/>
{instructionForm.formState.errors.name && (
<p className="text-red-400 text-[11px] mt-1">
{instructionForm.formState.errors.name.message}
</p>
)}
</div>
{/* Code */}
<div>
<div className="flex items-center gap-1 mb-1">
<label className="block text-xs font-semibold text-slate-300">
Instruction Code (Optional)
</label>
<HelpTooltip
title="Instruction Code"
content="Unique operational reference code (e.g., INST-CE-001). If left blank, one is generated automatically."
size="sm"
/>
</div>
<input
type="text"
placeholder="e.g. INST-CE-001"
{...instructionForm.register('code')}
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500 font-mono"
/>
</div>
{/* Description */}
<div>
<div className="flex items-center gap-1 mb-1">
<label className="block text-xs font-semibold text-slate-300">
Description & Implementation Directives *
</label>
<HelpTooltip
title="Instruction Description"
content="Comprehensive directives, statutory mandate, eligibility scope, and operational guidelines."
size="sm"
/>
</div>
<textarea
rows={4}
placeholder="Detail the operational mandate, eligibility scope, disbursement triggers, and statutory compliance requirements..."
{...instructionForm.register('description')}
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
/>
{instructionForm.formState.errors.description && (
<p className="text-red-400 text-[11px] mt-1">
{instructionForm.formState.errors.description.message}
</p>
)}
</div>
{/* Status */}
<div>
<div className="flex items-center gap-1 mb-1">
<label className="block text-xs font-semibold text-slate-300">Status</label>
<HelpTooltip
title="Instruction Lifecycle Status"
content="Indicates whether this instruction is actively enforceable or archived/inactive."
size="sm"
/>
</div>
<select
{...instructionForm.register('status')}
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
>
{ACTIVITY_STATUS_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
{/* Footer Actions */}
<div className="pt-3 border-t border-slate-800 flex justify-end gap-2">
<button
type="button"
onClick={handleCloseModal}
className="px-4 py-2 text-xs font-semibold text-slate-300 bg-slate-800 hover:bg-slate-700 rounded-xl transition cursor-pointer"
>
Cancel
</button>
<button
type="submit"
disabled={mutation.isPending}
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-500 rounded-xl shadow-md transition disabled:opacity-50 cursor-pointer"
>
{mutation.isPending && <RefreshCw className="w-3.5 h-3.5 animate-spin" />}
{editingInstruction ? 'Save Instruction Changes' : 'Create Instruction'}
</button>
</div>
</form>
</Modal>
{/* Modal: Inspect Instruction Detail */}
{inspectingInstruction && (
<Modal
isOpen={!!inspectingInstruction}
onClose={() => setInspectingInstruction(null)}
title={`Instruction: ${inspectingInstruction.name || ''}`}
subtitle={`Reference: ${inspectingInstruction.code || `INST-${inspectingInstruction.id}`}`}
maxWidth="lg"
>
<div className="space-y-4 text-xs">
<div className="p-4 rounded-xl border border-slate-800 bg-[#0d121f] space-y-3">
<div className="flex items-center justify-between">
<span className="font-mono text-xs font-bold text-blue-400 bg-blue-500/10 px-2.5 py-1 rounded border border-blue-500/20">
{inspectingInstruction.code || `INST-${inspectingInstruction.id}`}
</span>
{(() => {
const badge = getActivityStatusBadge(inspectingInstruction.status);
return (
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border ${badge.className}`}
>
{badge.label}
</span>
);
})()}
</div>
<div>
<h4 className="text-sm font-bold text-white mb-1">{inspectingInstruction.name}</h4>
<p className="text-slate-300 whitespace-pre-wrap leading-relaxed">
{inspectingInstruction.description || 'No detailed description provided.'}
</p>
</div>
<div className="pt-3 border-t border-slate-800/80 grid grid-cols-2 gap-3 text-[11px]">
<div>
<span className="text-slate-500 block">Associated Programme</span>
<span className="text-slate-200 font-semibold">
{programmeMap.get(String(inspectingInstruction.programmeId))?.name ||
`Programme #${inspectingInstruction.programmeId}`}
</span>
</div>
<div>
<span className="text-slate-500 block">Created On</span>
<span className="text-slate-200 font-mono">
{formatDate(inspectingInstruction.createdAt)}
</span>
</div>
<div>
<span className="text-slate-500 block">Created By</span>
<span className="text-slate-200 font-mono">
{inspectingInstruction.createdBy ? getUserEmail(inspectingInstruction.createdBy) : '—'}
</span>
</div>
{inspectingInstruction.updatedAt && (
<div>
<span className="text-slate-500 block">Last Mutated</span>
<span className="text-slate-200 font-mono">
{formatDate(inspectingInstruction.updatedAt)}
</span>
</div>
)}
</div>
</div>
<div className="pt-2 border-t border-slate-800 flex justify-between items-center">
<button
type="button"
onClick={() => {
const inst = inspectingInstruction;
setInspectingInstruction(null);
openEditModal(inst);
}}
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-slate-200 bg-slate-800 hover:bg-slate-700 rounded-xl border border-slate-700 cursor-pointer"
>
<Edit2 className="w-3.5 h-3.5" />
Edit Instruction
</button>
<button
type="button"
onClick={() => setInspectingInstruction(null)}
className="px-4 py-2 text-xs font-semibold text-slate-300 bg-slate-800 hover:bg-slate-700 rounded-xl cursor-pointer"
>
Close
</button>
</div>
</div>
</Modal>
)}
</div>
);
};