Implemented data export

This commit is contained in:
2026-09-26 13:45:42 +02:00
parent 15a8d8f449
commit 2949d6218b
12 changed files with 10939 additions and 359 deletions
@@ -17,19 +17,23 @@ import {
Tag,
CheckCircle2,
AlertCircle,
Coins,
} from 'lucide-react';
import { Modal } from '../ui/Modal';
import { HelpTooltip } from '../ui/HelpTooltip';
import { useToast } from '../ui/Toast';
import { ExportButton } from '../ui/ExportButton';
import { ExportColumn } from '../../utils/exportUtils';
import {
Instrument,
Instruction,
Programme,
ActivityStatus,
} from '../../types';
import {
getAllInstructions,
createInstruction,
updateInstruction,
getAllInstruments,
createInstrument,
updateInstrument,
} from '../../services/api';
import {
getActivityStatusBadge,
@@ -38,17 +42,17 @@ import {
ACTIVITY_STATUS_OPTIONS,
} from '../../lib/formatters';
const instructionSchema = z.object({
const instrumentSchema = 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'),
name: z.string().min(3, 'Funding instrument 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>;
type InstrumentFormValues = z.infer<typeof instrumentSchema>;
interface InstructionsSectionProps {
interface FundingInstrumentsSectionProps {
programmes: Programme[];
currentUserId: string;
preselectedProgrammeId?: string | number | null;
@@ -57,7 +61,7 @@ interface InstructionsSectionProps {
onCloseCreateModalExternal?: () => void;
}
export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
export const FundingInstrumentsSection: React.FC<FundingInstrumentsSectionProps> = ({
programmes,
currentUserId,
preselectedProgrammeId,
@@ -76,27 +80,12 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
// 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]);
const [editingInstrument, setEditingInstrument] = useState<Instrument | null>(null);
const [inspectingInstrument, setInspectingInstrument] = useState<Instrument | null>(null);
// Form setup
const instructionForm = useForm<InstructionFormValues>({
resolver: zodResolver(instructionSchema),
const instrumentForm = useForm<InstrumentFormValues>({
resolver: zodResolver(instrumentSchema),
defaultValues: {
programmeId: programmes[0]?.id ? Number(programmes[0].id) : 0,
name: '',
@@ -106,15 +95,30 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
},
});
// Query: Get all instructions
// Sync external create modal trigger if provided
React.useEffect(() => {
if (isCreateModalOpenExternal) {
setEditingInstrument(null);
instrumentForm.reset({
programmeId: preselectedProgrammeId ? Number(preselectedProgrammeId) : (programmes[0]?.id ? Number(programmes[0].id) : 0),
name: '',
code: '',
description: '',
status: ActivityStatus.Active,
});
setIsModalOpen(true);
}
}, [isCreateModalOpenExternal, preselectedProgrammeId, programmes, instrumentForm]);
// Query: Get all funding instruments primarily from API
const {
data: instructions = [],
data: instruments = [],
isLoading,
isFetching,
refetch,
} = useQuery({
queryKey: ['all-instructions', programmes],
queryFn: () => getAllInstructions(programmes),
queryKey: ['all-instruments', programmes],
queryFn: () => getAllInstruments(programmes),
});
// Programme lookup helper
@@ -124,12 +128,14 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
return map;
}, [programmes]);
// Mutation: Create or Update Instruction
// Mutation: Create or Update Funding Instrument
const mutation = useMutation({
mutationFn: async (data: InstructionFormValues) => {
if (editingInstruction) {
await updateInstruction({
instructionId: editingInstruction.id,
mutationFn: async (data: InstrumentFormValues) => {
if (editingInstrument) {
await updateInstrument({
instructionId: editingInstrument.id,
instrumentId: editingInstrument.id,
id: editingInstrument.id,
programmeId: data.programmeId,
code: data.code,
name: data.name,
@@ -138,7 +144,7 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
userId: currentUserId,
});
} else {
await createInstruction({
await createInstrument({
programmeId: data.programmeId,
code: data.code,
name: data.name,
@@ -149,27 +155,28 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
}
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['all-instruments'] });
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.'
editingInstrument ? 'Funding Instrument Updated' : 'Funding Instrument Created',
editingInstrument
? 'Funding instrument record updated successfully via the API.'
: 'New funding instrument created and linked to strategic programme successfully.'
);
setIsModalOpen(false);
setEditingInstruction(null);
setEditingInstrument(null);
if (onCloseCreateModalExternal) onCloseCreateModalExternal();
},
onError: (err: any) => {
toastError('Save Failed', err?.message || 'Failed to save instruction');
toastError('Save Failed', err?.message || 'Failed to save funding instrument');
},
});
// Handlers
const openCreateModal = (programmeId?: number | string) => {
setEditingInstruction(null);
instructionForm.reset({
setEditingInstrument(null);
instrumentForm.reset({
programmeId: programmeId
? Number(programmeId)
: selectedProgrammeFilter !== 'all'
@@ -185,9 +192,9 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
setIsModalOpen(true);
};
const openEditModal = (inst: Instruction) => {
setEditingInstruction(inst);
instructionForm.reset({
const openEditModal = (inst: Instrument) => {
setEditingInstrument(inst);
instrumentForm.reset({
programmeId: Number(inst.programmeId),
name: inst.name || '',
code: inst.code || '',
@@ -199,13 +206,13 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
const handleCloseModal = () => {
setIsModalOpen(false);
setEditingInstruction(null);
setEditingInstrument(null);
if (onCloseCreateModalExternal) onCloseCreateModalExternal();
};
// Filter instructions
const filteredInstructions = useMemo(() => {
return instructions.filter((inst) => {
// Filter funding instruments
const filteredInstruments = useMemo(() => {
return instruments.filter((inst) => {
// Programme filter
if (selectedProgrammeFilter !== 'all' && String(inst.programmeId) !== String(selectedProgrammeFilter)) {
return false;
@@ -228,7 +235,29 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
}
return true;
});
}, [instructions, selectedProgrammeFilter, statusFilter, searchTerm, programmeMap]);
}, [instruments, selectedProgrammeFilter, statusFilter, searchTerm, programmeMap]);
// Export columns definition
const instrumentExportColumns: ExportColumn<Instrument>[] = useMemo(
() => [
{ header: 'Instrument ID', key: 'id' },
{ header: 'Instrument Code', key: 'code', format: (val) => val || '—' },
{ header: 'Title / Name', key: 'name', format: (val) => val || 'Untitled' },
{
header: 'Strategic Programme',
key: 'programmeId',
format: (val) => programmeMap.get(String(val))?.name || `Programme #${val}`,
},
{
header: 'Status',
key: 'status',
format: (val) => (Number(val) === ActivityStatus.Active ? 'Active' : 'Inactive'),
},
{ header: 'Description', key: 'description', format: (val) => val || '—' },
{ header: 'Created Date', key: 'createdAt', format: (val) => (val ? formatDate(val) : '—') },
],
[programmeMap]
);
return (
<div className="space-y-4">
@@ -240,7 +269,7 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
<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..."
placeholder="Search funding instruments 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"
@@ -290,60 +319,72 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
</div>
</div>
{/* Action Buttons */}
{/* Action Buttons: Refresh, Export & Add */}
<div className="flex items-center gap-2 self-end lg:self-center">
<button
type="button"
onClick={() => refetch()}
onClick={() => {
refetch();
success('Refreshed', 'Funding instruments updated from API.');
}}
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"
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 Funding Instruments from API"
>
<RefreshCw className={`w-3.5 h-3.5 ${isFetching ? 'animate-spin' : ''}`} />
Refresh
<RefreshCw className={`w-3.5 h-3.5 text-blue-400 ${isFetching ? 'animate-spin' : ''}`} />
<span>Refresh</span>
</button>
<ExportButton
title="Funding Instruments Registry"
subtitle="Authoritative funding instruments and financing directives attached to strategic programmes"
filename={`pfm-funding-instruments-${new Date().toISOString().split('T')[0]}`}
columns={instrumentExportColumns}
data={filteredInstruments}
/>
<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
<span>Add Instrument</span>
</button>
</div>
</div>
{/* Instructions Table & Cards */}
{/* Funding Instruments 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" />
<Coins 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})
Funding Instruments & Financing Directives ({filteredInstruments.length})
</h3>
<HelpTooltip
title="Funding Instructions"
content="Binding operational instructions and instrument guidelines tied to strategic funding programmes. Defines implementation directives and compliance standards."
title="Funding Instruments"
content="Binding funding instruments and financing directives tied to strategic funding programmes. Defines capital allocation mechanisms, rules, and statutory guidelines."
placement="right"
size="sm"
/>
</div>
<span className="text-[11px] text-slate-400 font-mono">
{filteredInstructions.length} of {instructions.length} recorded
{filteredInstruments.length} of {instruments.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>
<span>Loading funding instruments directory...</span>
</div>
) : filteredInstructions.length === 0 ? (
) : filteredInstruments.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.'}
? 'No funding instruments match the active filters.'
: 'No funding instruments registered yet. Link funding instruments to programmes using the button below.'}
</div>
<button
type="button"
@@ -351,7 +392,7 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
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
Add First Funding Instrument
</button>
</div>
) : (
@@ -360,7 +401,7 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
<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">Instrument 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>
@@ -368,7 +409,7 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
</tr>
</thead>
<tbody className="divide-y divide-slate-800/60 text-xs text-slate-300">
{filteredInstructions.map((inst) => {
{filteredInstruments.map((inst) => {
const statusBadge = getActivityStatusBadge(inst.status);
const parentProg = programmeMap.get(String(inst.programmeId));
@@ -416,9 +457,9 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
<div className="flex items-center justify-end gap-1.5">
<button
type="button"
onClick={() => setInspectingInstruction(inst)}
onClick={() => setInspectingInstrument(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"
title="Inspect Instrument"
>
<Eye className="w-3 h-3" />
Inspect
@@ -427,7 +468,7 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
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"
title="Edit / Update Instrument"
>
<Edit2 className="w-3 h-3" />
Edit
@@ -443,20 +484,20 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
)}
</div>
{/* Modal: Create / Edit Instruction */}
{/* Modal: Create / Edit Funding Instrument */}
<Modal
isOpen={isModalOpen}
onClose={handleCloseModal}
title={editingInstruction ? 'Edit Funding Instruction' : 'Add New Funding Instruction'}
title={editingInstrument ? 'Edit Funding Instrument' : 'Add New Funding Instrument'}
subtitle={
editingInstruction
? `Mutating Instruction ${editingInstruction.code || `#${editingInstruction.id}`}`
: 'Authoritative operational instruction attached to a strategic programme'
editingInstrument
? `Updating Instrument ${editingInstrument.code || `#${editingInstrument.id}`}`
: 'Authoritative funding instrument attached to a strategic programme'
}
helpText="Instructions operationalize funding programmes into concrete binding directives. Choose an existing programme from the dropdown to link data."
helpText="Funding instruments operationalize funding programmes into concrete financing mechanisms. Select a strategic programme from the dropdown."
>
<form
onSubmit={instructionForm.handleSubmit((data) => mutation.mutate(data))}
onSubmit={instrumentForm.handleSubmit((data) => mutation.mutate(data))}
className="space-y-4"
>
{/* Associated Programme Dropdown */}
@@ -467,12 +508,12 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
</label>
<HelpTooltip
title="Associated Programme"
content="Select the strategic funding programme under which this operational instruction is established."
content="Select the strategic funding programme under which this operational funding instrument is established."
size="sm"
/>
</div>
<select
{...instructionForm.register('programmeId')}
{...instrumentForm.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>
@@ -482,9 +523,9 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
</option>
))}
</select>
{instructionForm.formState.errors.programmeId && (
{instrumentForm.formState.errors.programmeId && (
<p className="text-red-400 text-[11px] mt-1">
{instructionForm.formState.errors.programmeId.message}
{instrumentForm.formState.errors.programmeId.message}
</p>
)}
</div>
@@ -493,23 +534,23 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
<div>
<div className="flex items-center gap-1 mb-1">
<label className="block text-xs font-semibold text-slate-300">
Instruction Title *
Instrument Title *
</label>
<HelpTooltip
title="Instruction Title"
content="Formal title of the funding instruction or instrument (e.g., SME Technology Transfer Subsidy Guideline)."
title="Instrument Title"
content="Formal title of the funding 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')}
{...instrumentForm.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 && (
{instrumentForm.formState.errors.name && (
<p className="text-red-400 text-[11px] mt-1">
{instructionForm.formState.errors.name.message}
{instrumentForm.formState.errors.name.message}
</p>
)}
</div>
@@ -518,10 +559,10 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
<div>
<div className="flex items-center gap-1 mb-1">
<label className="block text-xs font-semibold text-slate-300">
Instruction Code (Optional)
Instrument Code (Optional)
</label>
<HelpTooltip
title="Instruction Code"
title="Instrument Code"
content="Unique operational reference code (e.g., INST-CE-001). If left blank, one is generated automatically."
size="sm"
/>
@@ -529,7 +570,7 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
<input
type="text"
placeholder="e.g. INST-CE-001"
{...instructionForm.register('code')}
{...instrumentForm.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>
@@ -538,23 +579,23 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
<div>
<div className="flex items-center gap-1 mb-1">
<label className="block text-xs font-semibold text-slate-300">
Description & Implementation Directives *
Description & Financing Directives *
</label>
<HelpTooltip
title="Instruction Description"
content="Comprehensive directives, statutory mandate, eligibility scope, and operational guidelines."
title="Instrument Description"
content="Comprehensive directives, statutory mandate, eligibility scope, and financing guidelines."
size="sm"
/>
</div>
<textarea
rows={4}
placeholder="Detail the operational mandate, eligibility scope, disbursement triggers, and statutory compliance requirements..."
{...instructionForm.register('description')}
placeholder="Detail the financing mandate, eligibility scope, disbursement triggers, and statutory compliance requirements..."
{...instrumentForm.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 && (
{instrumentForm.formState.errors.description && (
<p className="text-red-400 text-[11px] mt-1">
{instructionForm.formState.errors.description.message}
{instrumentForm.formState.errors.description.message}
</p>
)}
</div>
@@ -564,13 +605,13 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
<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."
title="Instrument Lifecycle Status"
content="Indicates whether this funding instrument is actively enforceable or archived/inactive."
size="sm"
/>
</div>
<select
{...instructionForm.register('status')}
{...instrumentForm.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) => (
@@ -596,29 +637,29 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
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'}
{editingInstrument ? 'Save Instrument Changes' : 'Create Funding Instrument'}
</button>
</div>
</form>
</Modal>
{/* Modal: Inspect Instruction Detail */}
{inspectingInstruction && (
{/* Modal: Inspect Funding Instrument Detail */}
{inspectingInstrument && (
<Modal
isOpen={!!inspectingInstruction}
onClose={() => setInspectingInstruction(null)}
title={`Instruction: ${inspectingInstruction.name || ''}`}
subtitle={`Reference: ${inspectingInstruction.code || `INST-${inspectingInstruction.id}`}`}
isOpen={!!inspectingInstrument}
onClose={() => setInspectingInstrument(null)}
title={`Funding Instrument: ${inspectingInstrument.name || ''}`}
subtitle={`Reference: ${inspectingInstrument.code || `INST-${inspectingInstrument.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}`}
{inspectingInstrument.code || `INST-${inspectingInstrument.id}`}
</span>
{(() => {
const badge = getActivityStatusBadge(inspectingInstruction.status);
const badge = getActivityStatusBadge(inspectingInstrument.status);
return (
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border ${badge.className}`}
@@ -630,9 +671,9 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
</div>
<div>
<h4 className="text-sm font-bold text-white mb-1">{inspectingInstruction.name}</h4>
<h4 className="text-sm font-bold text-white mb-1">{inspectingInstrument.name}</h4>
<p className="text-slate-300 whitespace-pre-wrap leading-relaxed">
{inspectingInstruction.description || 'No detailed description provided.'}
{inspectingInstrument.description || 'No detailed description provided.'}
</p>
</div>
@@ -640,27 +681,27 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
<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}`}
{programmeMap.get(String(inspectingInstrument.programmeId))?.name ||
`Programme #${inspectingInstrument.programmeId}`}
</span>
</div>
<div>
<span className="text-slate-500 block">Created On</span>
<span className="text-slate-200 font-mono">
{formatDate(inspectingInstruction.createdAt)}
{formatDate(inspectingInstrument.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) : '—'}
{inspectingInstrument.createdBy ? getUserEmail(inspectingInstrument.createdBy) : '—'}
</span>
</div>
{inspectingInstruction.updatedAt && (
{inspectingInstrument.updatedAt && (
<div>
<span className="text-slate-500 block">Last Mutated</span>
<span className="text-slate-200 font-mono">
{formatDate(inspectingInstruction.updatedAt)}
{formatDate(inspectingInstrument.updatedAt)}
</span>
</div>
)}
@@ -671,18 +712,18 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
<button
type="button"
onClick={() => {
const inst = inspectingInstruction;
setInspectingInstruction(null);
const inst = inspectingInstrument;
setInspectingInstrument(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
Edit Funding Instrument
</button>
<button
type="button"
onClick={() => setInspectingInstruction(null)}
onClick={() => setInspectingInstrument(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
@@ -694,3 +735,6 @@ export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
</div>
);
};
export const InstructionsSection = FundingInstrumentsSection;
@@ -22,6 +22,8 @@ import {
import { Modal } from '../ui/Modal';
import { HelpTooltip } from '../ui/HelpTooltip';
import { useToast } from '../ui/Toast';
import { ExportButton } from '../ui/ExportButton';
import { ExportColumn } from '../../utils/exportUtils';
import {
Rule,
Programme,
@@ -231,6 +233,28 @@ export const RulesSection: React.FC<RulesSectionProps> = ({
});
}, [rules, selectedProgrammeFilter, statusFilter, searchTerm, programmeMap]);
// Export columns definition
const ruleExportColumns: ExportColumn<Rule>[] = useMemo(
() => [
{ header: 'Rule ID', key: 'id' },
{ header: 'Rule Name', key: 'name', format: (val) => val || 'Untitled Rule' },
{
header: 'Strategic Programme',
key: 'programmeId',
format: (val) => programmeMap.get(String(val))?.name || `Programme #${val}`,
},
{ header: 'Version', key: 'version', format: (val) => `v${val || 1}` },
{
header: 'Status',
key: 'status',
format: (val) => (Number(val) === ActivityStatus.Active ? 'Active' : 'Inactive'),
},
{ header: 'Rule Description', key: 'description', format: (val) => val || '—' },
{ header: 'Created Date', key: 'createdAt', format: (val) => (val ? formatDate(val) : '—') },
],
[programmeMap]
);
return (
<div className="space-y-4">
{/* Top Filter and Actions Bar */}
@@ -291,25 +315,37 @@ export const RulesSection: React.FC<RulesSectionProps> = ({
</div>
</div>
{/* Action Buttons */}
{/* Action Buttons: Refresh, Export & Add */}
<div className="flex items-center gap-2 self-end lg:self-center">
<button
type="button"
onClick={() => refetch()}
onClick={() => {
refetch();
success('Refreshed', 'Programme rules updated from API.');
}}
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 Rules"
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 Programme Rules from API"
>
<RefreshCw className={`w-3.5 h-3.5 ${isFetching ? 'animate-spin' : ''}`} />
Refresh
<RefreshCw className={`w-3.5 h-3.5 text-blue-400 ${isFetching ? 'animate-spin' : ''}`} />
<span>Refresh</span>
</button>
<ExportButton
title="Programme Rules Registry"
subtitle="Statutory, regulatory, and eligibility rules governing strategic funding programmes"
filename={`pfm-programme-rules-${new Date().toISOString().split('T')[0]}`}
columns={ruleExportColumns}
data={filteredRules}
/>
<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 Rule
<span>Add Rule</span>
</button>
</div>
</div>
@@ -0,0 +1,139 @@
import React, { useState, useRef, useEffect } from 'react';
import { Download, FileSpreadsheet, FileText, ChevronDown } from 'lucide-react';
import { ExportColumn, exportToSpreadsheet, exportToPdf } from '../../utils/exportUtils';
import { useAuth } from '../../auth/AuthProvider';
export interface ExportButtonProps<T = any> {
title: string;
subtitle?: string;
filename: string;
columns: ExportColumn<T>[];
data: T[];
label?: string;
size?: 'sm' | 'md';
className?: string;
}
export function ExportButton<T>({
title,
subtitle,
filename,
columns,
data,
label = 'Export',
size = 'md',
className = '',
}: ExportButtonProps<T>) {
const [isOpen, setIsOpen] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
const { user, claims, tenantId } = useAuth();
const isDisabled = !data || data.length === 0;
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
setIsOpen(false);
}
}
if (isOpen) {
document.addEventListener('mousedown', handleClickOutside);
}
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [isOpen]);
const handleExportSpreadsheet = () => {
if (isDisabled) return;
setIsOpen(false);
exportToSpreadsheet({
title,
subtitle,
filename,
columns,
data,
tenantName: (claims as any)?.tenant_name || (claims as any)?.tenant || `Tenant #${tenantId || 1}`,
userEmail: user?.profile?.email || (claims as any)?.email || '',
});
};
const handleExportPdf = () => {
if (isDisabled) return;
setIsOpen(false);
exportToPdf({
title,
subtitle,
filename,
columns,
data,
tenantName: (claims as any)?.tenant_name || (claims as any)?.tenant || `Tenant #${tenantId || 1}`,
userEmail: user?.profile?.email || (claims as any)?.email || '',
});
};
return (
<div className={`relative inline-block ${className}`} ref={dropdownRef}>
<button
type="button"
onClick={() => !isDisabled && setIsOpen(!isOpen)}
disabled={isDisabled}
title={
isDisabled
? 'No data available to export in current view'
: `Export ${data.length} records to Spreadsheet or PDF`
}
className={`inline-flex items-center justify-center gap-1.5 font-semibold rounded-xl border transition cursor-pointer shadow-xs ${
size === 'sm' ? 'px-3 py-1.5 text-xs' : 'px-3.5 py-2 text-xs'
} ${
isDisabled
? 'text-slate-600 bg-slate-900/40 border-slate-800/80 cursor-not-allowed opacity-60'
: 'text-slate-300 bg-[#0d121f] hover:bg-slate-800 border-slate-700/80 hover:text-white'
}`}
>
<Download className={`w-3.5 h-3.5 ${isDisabled ? 'text-slate-600' : 'text-emerald-400'}`} />
<span>{label}</span>
<ChevronDown className={`w-3 h-3 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
</button>
{isOpen && !isDisabled && (
<div className="absolute right-0 mt-1.5 w-52 bg-[#0d121f] border border-slate-700/90 rounded-xl shadow-2xl z-50 overflow-hidden backdrop-blur-md animate-in fade-in-50 zoom-in-95">
<div className="p-2 border-b border-slate-800/80">
<span className="text-[10px] font-semibold uppercase tracking-wider text-slate-400 px-2 block">
Export Format ({data.length} items)
</span>
</div>
<div className="p-1 space-y-0.5">
<button
type="button"
onClick={handleExportSpreadsheet}
className="w-full flex items-center gap-2.5 px-3 py-2 text-xs text-left text-slate-200 hover:text-white hover:bg-emerald-500/15 rounded-lg transition-colors cursor-pointer group"
>
<div className="w-6 h-6 rounded-md bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center shrink-0 group-hover:bg-emerald-500/20">
<FileSpreadsheet className="w-3.5 h-3.5 text-emerald-400" />
</div>
<div>
<span className="font-semibold block leading-tight">Spreadsheet (.xlsx)</span>
<span className="text-[10px] text-slate-400">Excel / Google Sheets</span>
</div>
</button>
<button
type="button"
onClick={handleExportPdf}
className="w-full flex items-center gap-2.5 px-3 py-2 text-xs text-left text-slate-200 hover:text-white hover:bg-blue-500/15 rounded-lg transition-colors cursor-pointer group"
>
<div className="w-6 h-6 rounded-md bg-blue-500/10 border border-blue-500/20 flex items-center justify-center shrink-0 group-hover:bg-blue-500/20">
<FileText className="w-3.5 h-3.5 text-blue-400" />
</div>
<div>
<span className="font-semibold block leading-tight">PDF Document (.pdf)</span>
<span className="text-[10px] text-slate-400">Landscape with PFM Logo</span>
</div>
</button>
</div>
</div>
)}
</div>
);
}