Fixed API calls on governance page #94
@@ -15,6 +15,7 @@ import {
|
||||
import { AccountActivationModal } from '../components/auth/AccountActivationModal';
|
||||
import { SessionExpiredModal } from '../components/auth/SessionExpiredModal';
|
||||
import { encodeHashIdSync } from '../services/toolsService';
|
||||
import { verifyTenantLockout } from '../services/tenantLockoutService';
|
||||
import {
|
||||
onSessionExpired,
|
||||
triggerSessionExpired,
|
||||
@@ -120,6 +121,79 @@ export function extractTenantId(claims?: UserClaims | null, token?: string | nul
|
||||
return null;
|
||||
}
|
||||
|
||||
export function extractTenantClaimValues(
|
||||
claims?: UserClaims | null,
|
||||
token?: string | null
|
||||
): {
|
||||
tenantId: number | string | null;
|
||||
tenant: string | null;
|
||||
} {
|
||||
let tenantId: number | string | null = null;
|
||||
let tenant: string | null = null;
|
||||
|
||||
if (claims) {
|
||||
const rawId =
|
||||
claims.tenant_id ??
|
||||
(claims as any).tenantId ??
|
||||
claims['tenant_id'] ??
|
||||
claims['http://schemas.microsoft.com/ws/2008/06/identity/claims/tenantid'];
|
||||
if (rawId !== undefined && rawId !== null && rawId !== '') {
|
||||
const parsed = Number(rawId);
|
||||
tenantId = !isNaN(parsed) && isFinite(parsed) ? parsed : String(rawId).trim();
|
||||
}
|
||||
|
||||
const rawTenant =
|
||||
claims.tenant ??
|
||||
claims['tenant'] ??
|
||||
claims['http://schemas.microsoft.com/ws/2008/06/identity/claims/tenant'] ??
|
||||
claims.tenant_name ??
|
||||
(claims as any).tenantName ??
|
||||
claims.org;
|
||||
if (rawTenant !== undefined && rawTenant !== null && rawTenant !== '') {
|
||||
if (typeof rawTenant === 'string') {
|
||||
tenant = rawTenant.trim();
|
||||
} else if (typeof rawTenant === 'object' && rawTenant.name) {
|
||||
tenant = String(rawTenant.name).trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (token && (!tenantId || !tenant)) {
|
||||
try {
|
||||
const tokenClaims = parseJwtClaims(token);
|
||||
if (!tenantId) {
|
||||
const rawId =
|
||||
tokenClaims.tenant_id ??
|
||||
tokenClaims.tenantId ??
|
||||
tokenClaims['tenant_id'] ??
|
||||
tokenClaims['http://schemas.microsoft.com/ws/2008/06/identity/claims/tenantid'];
|
||||
if (rawId !== undefined && rawId !== null && rawId !== '') {
|
||||
const parsed = Number(rawId);
|
||||
tenantId = !isNaN(parsed) && isFinite(parsed) ? parsed : String(rawId).trim();
|
||||
}
|
||||
}
|
||||
if (!tenant) {
|
||||
const rawTenant =
|
||||
tokenClaims.tenant ??
|
||||
tokenClaims['tenant'] ??
|
||||
tokenClaims['http://schemas.microsoft.com/ws/2008/06/identity/claims/tenant'] ??
|
||||
tokenClaims.tenant_name ??
|
||||
(tokenClaims as any).tenantName ??
|
||||
tokenClaims.org;
|
||||
if (rawTenant !== undefined && rawTenant !== null && rawTenant !== '') {
|
||||
if (typeof rawTenant === 'string') {
|
||||
tenant = rawTenant.trim();
|
||||
} else if (typeof rawTenant === 'object' && rawTenant.name) {
|
||||
tenant = String(rawTenant.name).trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
return { tenantId, tenant };
|
||||
}
|
||||
|
||||
export function getCurrentUserTenantId(): number | null {
|
||||
return extractTenantId(
|
||||
getCurrentUserClaims(),
|
||||
@@ -283,7 +357,8 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
||||
localStorage.setItem(LOCAL_STORAGE_SUB_KEY, userSub);
|
||||
localStorage.setItem(LOCAL_STORAGE_CLAIMS_KEY, JSON.stringify(mergedClaims));
|
||||
|
||||
const tenantClaim = (mergedClaims.tenant as string) || (oidcUser.profile?.tenant as string) || undefined;
|
||||
const tenantClaimValues = extractTenantClaimValues(mergedClaims, token);
|
||||
const tenantClaim = (mergedClaims.tenant as string) || (oidcUser.profile?.tenant as string) || tenantClaimValues.tenant || undefined;
|
||||
const parsedTenantId = extractTenantId(mergedClaims, token);
|
||||
setTenantId(parsedTenantId);
|
||||
|
||||
@@ -304,6 +379,20 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
||||
// Clean up code and state from URL
|
||||
window.history.replaceState({}, document.title, window.location.pathname);
|
||||
|
||||
// Verify tenant lockout at the instance tenant and tenant_id claims are retrieved
|
||||
const tenantLockoutResult = await verifyTenantLockout(
|
||||
parsedTenantId ?? tenantClaimValues.tenantId,
|
||||
tenantClaim
|
||||
);
|
||||
|
||||
if (!tenantLockoutResult.isActive) {
|
||||
setIsPendingActivation(true);
|
||||
setIsSynced(false);
|
||||
setActivationError(tenantLockoutResult.errorMessage || 'Tenant is inactive or not found');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Synchronize authenticated user profile with backend directory
|
||||
try {
|
||||
const syncResult = await syncUserAccount(userSub, token, profile, true);
|
||||
@@ -367,6 +456,8 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
||||
|
||||
const storedTenantId = extractTenantId(parsedClaims, storedToken);
|
||||
setTenantId(storedTenantId);
|
||||
const tenantClaimValues = extractTenantClaimValues(parsedClaims, storedToken);
|
||||
const storedTenantClaim = (parsedClaims.tenant as string) || tenantClaimValues.tenant || undefined;
|
||||
|
||||
let resolvedUser: AuthUserProfile | null = null;
|
||||
if (storedUser) {
|
||||
@@ -383,6 +474,20 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Verify tenant lockout at the instance tenant and tenant_id claims are retrieved
|
||||
const tenantLockoutResult = await verifyTenantLockout(
|
||||
storedTenantId ?? tenantClaimValues.tenantId,
|
||||
storedTenantClaim
|
||||
);
|
||||
|
||||
if (!tenantLockoutResult.isActive) {
|
||||
setIsPendingActivation(true);
|
||||
setIsSynced(false);
|
||||
setActivationError(tenantLockoutResult.errorMessage || 'Tenant is inactive or not found');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if session is already marked pending activation or needs sync check
|
||||
const wasPending = isActivationPending();
|
||||
setIsPendingActivation(wasPending);
|
||||
@@ -435,6 +540,25 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
||||
|
||||
const syncUserSession = async (force = true): Promise<UserSyncResult> => {
|
||||
try {
|
||||
// Re-verify tenant status via GetTenant as part of the lockout resolution
|
||||
const tenantClaimValues = extractTenantClaimValues(claims, accessToken);
|
||||
const currentTenantId = tenantId ?? tenantClaimValues.tenantId;
|
||||
const currentTenantClaim = (claims.tenant as string) || user?.tenant || tenantClaimValues.tenant || undefined;
|
||||
|
||||
const tenantLockoutResult = await verifyTenantLockout(currentTenantId, currentTenantClaim);
|
||||
if (!tenantLockoutResult.isActive) {
|
||||
const msg = tenantLockoutResult.errorMessage || 'Tenant is not Active. Lockout active.';
|
||||
setIsPendingActivation(true);
|
||||
setIsSynced(false);
|
||||
setActivationError(msg);
|
||||
return {
|
||||
success: false,
|
||||
isActivationPending: true,
|
||||
errorMessage: msg,
|
||||
};
|
||||
}
|
||||
|
||||
// Tenant is verified Active: proceed with user sync
|
||||
const result = await syncUserAccount(sub, accessToken, user || undefined, force);
|
||||
if (result.isUnauthorized) {
|
||||
await logout();
|
||||
|
||||
@@ -38,6 +38,13 @@ export const AccountActivationModal: React.FC<AccountActivationModalProps> = ({
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(initialError || null);
|
||||
const [syncAttemptCount, setSyncAttemptCount] = useState(0);
|
||||
|
||||
// Sync errorMessage when initialError updates
|
||||
useEffect(() => {
|
||||
if (initialError !== undefined) {
|
||||
setErrorMessage(initialError);
|
||||
}
|
||||
}, [initialError]);
|
||||
|
||||
// Clear any existing session prompt and close background dialogs
|
||||
useEffect(() => {
|
||||
cancelSessionExpiration();
|
||||
@@ -134,10 +141,12 @@ export const AccountActivationModal: React.FC<AccountActivationModalProps> = ({
|
||||
</div>
|
||||
<div>
|
||||
<span className="inline-flex items-center gap-1.5 text-[11px] font-semibold tracking-wider uppercase text-amber-400 bg-amber-500/10 border border-amber-500/20 px-2 py-0.5 rounded-full mb-1">
|
||||
Access Restricted • Awaiting Enablement
|
||||
Access Restricted • Lockout Active
|
||||
</span>
|
||||
<h2 id="activation-modal-title" className="text-lg sm:text-xl font-bold text-white tracking-tight">
|
||||
Account Pending Administrator Activation
|
||||
{errorMessage?.toLowerCase().includes('tenant')
|
||||
? 'Tenant Lockout • Account Inactive'
|
||||
: 'Account Pending Administrator Activation'}
|
||||
</h2>
|
||||
</div>
|
||||
</div>
|
||||
@@ -215,7 +224,11 @@ export const AccountActivationModal: React.FC<AccountActivationModalProps> = ({
|
||||
<div className="rounded-xl border border-rose-500/30 bg-rose-500/10 p-3.5 flex items-start gap-3 animate-in fade-in duration-150">
|
||||
<AlertTriangle className="w-4 h-4 text-rose-400 shrink-0 mt-0.5" />
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-semibold text-rose-300">Account Not Activated Yet</p>
|
||||
<p className="text-xs font-semibold text-rose-300">
|
||||
{errorMessage?.toLowerCase().includes('tenant')
|
||||
? 'Tenant Lockout In Effect'
|
||||
: 'Account Not Activated Yet'}
|
||||
</p>
|
||||
<p className="text-xs text-rose-200/90 leading-relaxed">{errorMessage}</p>
|
||||
{syncAttemptCount > 0 && (
|
||||
<p className="text-[11px] text-rose-400/80 pt-1">
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,700 @@
|
||||
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 {
|
||||
Scale,
|
||||
Plus,
|
||||
Search,
|
||||
Filter,
|
||||
RefreshCw,
|
||||
Edit2,
|
||||
Eye,
|
||||
Layers,
|
||||
Calendar,
|
||||
User as UserIcon,
|
||||
Tag,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
GitBranch,
|
||||
} from 'lucide-react';
|
||||
import { Modal } from '../ui/Modal';
|
||||
import { HelpTooltip } from '../ui/HelpTooltip';
|
||||
import { useToast } from '../ui/Toast';
|
||||
import {
|
||||
Rule,
|
||||
Programme,
|
||||
ActivityStatus,
|
||||
} from '../../types';
|
||||
import {
|
||||
getRules,
|
||||
createRule,
|
||||
updateRule,
|
||||
} from '../../services/api';
|
||||
import {
|
||||
getActivityStatusBadge,
|
||||
formatDate,
|
||||
getUserEmail,
|
||||
ACTIVITY_STATUS_OPTIONS,
|
||||
} from '../../lib/formatters';
|
||||
|
||||
const ruleSchema = z.object({
|
||||
programmeId: z.coerce.number().min(1, 'Please select an associated programme from the dropdown'),
|
||||
name: z.string().min(3, 'Rule name must be at least 3 characters'),
|
||||
description: z.string().min(5, 'Description is required (minimum 5 characters)'),
|
||||
version: z.coerce.number().min(1, 'Version must be at least 1').default(1),
|
||||
status: z.coerce.number().default(ActivityStatus.Active),
|
||||
});
|
||||
|
||||
type RuleFormValues = z.infer<typeof ruleSchema>;
|
||||
|
||||
interface RulesSectionProps {
|
||||
programmes: Programme[];
|
||||
currentUserId: string;
|
||||
preselectedProgrammeId?: string | number | null;
|
||||
onClearPreselectedProgramme?: () => void;
|
||||
isCreateModalOpenExternal?: boolean;
|
||||
onCloseCreateModalExternal?: () => void;
|
||||
}
|
||||
|
||||
export const RulesSection: React.FC<RulesSectionProps> = ({
|
||||
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 [editingRule, setEditingRule] = useState<Rule | null>(null);
|
||||
const [inspectingRule, setInspectingRule] = useState<Rule | null>(null);
|
||||
|
||||
// Sync external create trigger
|
||||
React.useEffect(() => {
|
||||
if (isCreateModalOpenExternal) {
|
||||
setEditingRule(null);
|
||||
ruleForm.reset({
|
||||
programmeId: preselectedProgrammeId ? Number(preselectedProgrammeId) : (programmes[0]?.id ? Number(programmes[0].id) : 0),
|
||||
name: '',
|
||||
description: '',
|
||||
version: 1,
|
||||
status: ActivityStatus.Active,
|
||||
});
|
||||
setIsModalOpen(true);
|
||||
}
|
||||
}, [isCreateModalOpenExternal, preselectedProgrammeId, programmes]);
|
||||
|
||||
// Form setup
|
||||
const ruleForm = useForm<RuleFormValues>({
|
||||
resolver: zodResolver(ruleSchema),
|
||||
defaultValues: {
|
||||
programmeId: programmes[0]?.id ? Number(programmes[0].id) : 0,
|
||||
name: '',
|
||||
description: '',
|
||||
version: 1,
|
||||
status: ActivityStatus.Active,
|
||||
},
|
||||
});
|
||||
|
||||
// Query: Get all rules (with programme filter)
|
||||
const {
|
||||
data: rules = [],
|
||||
isLoading,
|
||||
isFetching,
|
||||
refetch,
|
||||
} = useQuery({
|
||||
queryKey: ['rules', selectedProgrammeFilter],
|
||||
queryFn: () =>
|
||||
getRules(
|
||||
{ page: 1, pageSize: 200 },
|
||||
selectedProgrammeFilter !== 'all' ? selectedProgrammeFilter : undefined
|
||||
),
|
||||
});
|
||||
|
||||
// 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 Rule
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (data: RuleFormValues) => {
|
||||
if (editingRule) {
|
||||
await updateRule({
|
||||
ruleId: editingRule.id,
|
||||
programmeId: data.programmeId,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
status: data.status !== undefined ? Number(data.status) : ActivityStatus.Active,
|
||||
version: Number(data.version) || 1,
|
||||
userId: currentUserId,
|
||||
});
|
||||
} else {
|
||||
await createRule({
|
||||
programmeId: data.programmeId,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
userId: currentUserId,
|
||||
});
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['rules'] });
|
||||
success(
|
||||
editingRule ? 'Rule Mutated' : 'Rule Created',
|
||||
editingRule
|
||||
? 'Programme rule record mutated successfully.'
|
||||
: 'New programme rule registered and linked to programme.'
|
||||
);
|
||||
setIsModalOpen(false);
|
||||
setEditingRule(null);
|
||||
if (onCloseCreateModalExternal) onCloseCreateModalExternal();
|
||||
},
|
||||
onError: (err: any) => {
|
||||
toastError('Save Failed', err?.message || 'Failed to save programme rule');
|
||||
},
|
||||
});
|
||||
|
||||
// Handlers
|
||||
const openCreateModal = (programmeId?: number | string) => {
|
||||
setEditingRule(null);
|
||||
ruleForm.reset({
|
||||
programmeId: programmeId
|
||||
? Number(programmeId)
|
||||
: selectedProgrammeFilter !== 'all'
|
||||
? Number(selectedProgrammeFilter)
|
||||
: programmes[0]?.id
|
||||
? Number(programmes[0].id)
|
||||
: 0,
|
||||
name: '',
|
||||
description: '',
|
||||
version: 1,
|
||||
status: ActivityStatus.Active,
|
||||
});
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const openEditModal = (rule: Rule) => {
|
||||
setEditingRule(rule);
|
||||
ruleForm.reset({
|
||||
programmeId: Number(rule.programmeId),
|
||||
name: rule.name || '',
|
||||
description: rule.description || '',
|
||||
version: Number(rule.version) || 1,
|
||||
status: Number(rule.status),
|
||||
});
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseModal = () => {
|
||||
setIsModalOpen(false);
|
||||
setEditingRule(null);
|
||||
if (onCloseCreateModalExternal) onCloseCreateModalExternal();
|
||||
};
|
||||
|
||||
// Filter rules
|
||||
const filteredRules = useMemo(() => {
|
||||
return rules.filter((r) => {
|
||||
// Programme filter
|
||||
if (selectedProgrammeFilter !== 'all' && String(r.programmeId) !== String(selectedProgrammeFilter)) {
|
||||
return false;
|
||||
}
|
||||
// Status filter
|
||||
if (statusFilter !== 'all' && String(r.status) !== String(statusFilter)) {
|
||||
return false;
|
||||
}
|
||||
// Search term
|
||||
if (searchTerm.trim()) {
|
||||
const query = searchTerm.toLowerCase();
|
||||
const pName = programmeMap.get(String(r.programmeId))?.name?.toLowerCase() || '';
|
||||
const matchName = (r.name || '').toLowerCase().includes(query);
|
||||
const matchDesc = (r.description || '').toLowerCase().includes(query);
|
||||
const matchProg = pName.includes(query);
|
||||
if (!matchName && !matchDesc && !matchProg) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}, [rules, 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 rules by title, 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 Rules"
|
||||
>
|
||||
<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 Rule
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Rules 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">
|
||||
<Scale className="w-4 h-4 text-amber-400" />
|
||||
<h3 className="text-xs font-bold text-slate-200 uppercase tracking-wider">
|
||||
Programme Rules & Governance Directives ({filteredRules.length})
|
||||
</h3>
|
||||
<HelpTooltip
|
||||
title="Programme Rules"
|
||||
content="Binding regulatory, operational, and eligibility rules associated with specific funding programmes. Enforces statutory constraints on grant allocation."
|
||||
placement="right"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<span className="text-[11px] text-slate-400 font-mono">
|
||||
{filteredRules.length} of {rules.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-amber-400" />
|
||||
<span>Loading programme rules directory...</span>
|
||||
</div>
|
||||
) : filteredRules.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 programme rules match the active filters.'
|
||||
: 'No programme rules registered yet. Link rules 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 Rule
|
||||
</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">Rule Title & Directives</th>
|
||||
<th className="py-3 px-4">Associated Programme</th>
|
||||
<th className="py-3 px-4">Version</th>
|
||||
<th className="py-3 px-4">Status</th>
|
||||
<th className="py-3 px-4">Audit 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">
|
||||
{filteredRules.map((r) => {
|
||||
const statusBadge = getActivityStatusBadge(r.status);
|
||||
const parentProg = programmeMap.get(String(r.programmeId));
|
||||
|
||||
return (
|
||||
<tr key={r.id} className="hover:bg-slate-800/30 transition-colors">
|
||||
<td className="py-3.5 px-4">
|
||||
<div className="font-semibold text-white max-w-sm">{r.name}</div>
|
||||
{r.description && (
|
||||
<div className="text-[11px] text-slate-400 line-clamp-1 mt-0.5 max-w-md">
|
||||
{r.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-amber-400" />
|
||||
{parentProg.name}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-slate-500 font-mono text-xs">
|
||||
Programme #{r.programmeId}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-3.5 px-4 font-mono">
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-semibold bg-amber-500/10 text-amber-400 border border-amber-500/20">
|
||||
<GitBranch className="w-3 h-3" />v{r.version || 1}
|
||||
</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(r.createdAt)}</div>
|
||||
{r.createdBy && (
|
||||
<div className="text-[10px] text-slate-500">{getUserEmail(r.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={() => setInspectingRule(r)}
|
||||
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 Rule"
|
||||
>
|
||||
<Eye className="w-3 h-3" />
|
||||
Inspect
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openEditModal(r)}
|
||||
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 Rule"
|
||||
>
|
||||
<Edit2 className="w-3 h-3" />
|
||||
Edit
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal: Create / Edit Rule */}
|
||||
<Modal
|
||||
isOpen={isModalOpen}
|
||||
onClose={handleCloseModal}
|
||||
title={editingRule ? 'Edit Programme Rule' : 'Register New Programme Rule'}
|
||||
subtitle={
|
||||
editingRule
|
||||
? `Mutating Rule: ${editingRule.name || `#${editingRule.id}`}`
|
||||
: 'Authoritative compliance rule associated with an existing funding programme'
|
||||
}
|
||||
helpText="Each rule must be associated with an existing programme chosen from the dropdown below. Rules define statutory constraints and mandatory eligibility."
|
||||
>
|
||||
<form
|
||||
onSubmit={ruleForm.handleSubmit((data) => mutation.mutate(data))}
|
||||
className="space-y-4"
|
||||
>
|
||||
{/* Associated Programme Dropdown (User must choose from 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 Selection"
|
||||
content="Choose the existing funding programme to which this rule will apply. Each rule is strictly associated with a programme."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
{...ruleForm.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 from dropdown...</option>
|
||||
{programmes.map((p) => (
|
||||
<option key={p.id} value={Number(p.id)}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{ruleForm.formState.errors.programmeId && (
|
||||
<p className="text-red-400 text-[11px] mt-1">
|
||||
{ruleForm.formState.errors.programmeId.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Rule Name */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Rule Name *</label>
|
||||
<HelpTooltip
|
||||
title="Rule Name"
|
||||
content="Title or clause name of the programme rule (e.g., Mandatory BEE Level 2 Threshold)."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="e.g. Environmental Impact Assessment Mandatory Clearance"
|
||||
{...ruleForm.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"
|
||||
/>
|
||||
{ruleForm.formState.errors.name && (
|
||||
<p className="text-red-400 text-[11px] mt-1">
|
||||
{ruleForm.formState.errors.name.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">
|
||||
Rule Directives & Description *
|
||||
</label>
|
||||
<HelpTooltip
|
||||
title="Rule Directives"
|
||||
content="Full text and verification criteria of the rule enforced across all projects in the programme."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<textarea
|
||||
rows={4}
|
||||
placeholder="Specify the exact statutory rule, criteria, threshold, verification mechanism, and non-compliance penalty..."
|
||||
{...ruleForm.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"
|
||||
/>
|
||||
{ruleForm.formState.errors.description && (
|
||||
<p className="text-red-400 text-[11px] mt-1">
|
||||
{ruleForm.formState.errors.description.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Version & Status */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Rule Version</label>
|
||||
<HelpTooltip
|
||||
title="Rule Version"
|
||||
content="Integer version tracking revisions of this statutory rule."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
{...ruleForm.register('version')}
|
||||
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"
|
||||
/>
|
||||
{ruleForm.formState.errors.version && (
|
||||
<p className="text-red-400 text-[11px] mt-1">
|
||||
{ruleForm.formState.errors.version.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Status</label>
|
||||
<HelpTooltip
|
||||
title="Rule Enforcement Status"
|
||||
content="Active rules are actively evaluated in grant awards and milestones."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
{...ruleForm.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>
|
||||
</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" />}
|
||||
{editingRule ? 'Save Rule Changes' : 'Register Programme Rule'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
{/* Modal: Inspect Rule Detail */}
|
||||
{inspectingRule && (
|
||||
<Modal
|
||||
isOpen={!!inspectingRule}
|
||||
onClose={() => setInspectingRule(null)}
|
||||
title={`Programme Rule: ${inspectingRule.name || ''}`}
|
||||
subtitle={`Version ${inspectingRule.version || 1} • Rule #${inspectingRule.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-amber-400 bg-amber-500/10 px-2.5 py-1 rounded border border-amber-500/20 flex items-center gap-1">
|
||||
<GitBranch className="w-3.5 h-3.5" />
|
||||
Version {inspectingRule.version || 1}
|
||||
</span>
|
||||
{(() => {
|
||||
const badge = getActivityStatusBadge(inspectingRule.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">{inspectingRule.name}</h4>
|
||||
<p className="text-slate-300 whitespace-pre-wrap leading-relaxed">
|
||||
{inspectingRule.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(inspectingRule.programmeId))?.name ||
|
||||
`Programme #${inspectingRule.programmeId}`}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-slate-500 block">Created On</span>
|
||||
<span className="text-slate-200 font-mono">
|
||||
{formatDate(inspectingRule.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-slate-500 block">Created By</span>
|
||||
<span className="text-slate-200 font-mono">
|
||||
{inspectingRule.createdBy ? getUserEmail(inspectingRule.createdBy) : '—'}
|
||||
</span>
|
||||
</div>
|
||||
{inspectingRule.updatedAt && (
|
||||
<div>
|
||||
<span className="text-slate-500 block">Last Mutated</span>
|
||||
<span className="text-slate-200 font-mono">
|
||||
{formatDate(inspectingRule.updatedAt)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-2 border-t border-slate-800 flex justify-between items-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const r = inspectingRule;
|
||||
setInspectingRule(null);
|
||||
openEditModal(r);
|
||||
}}
|
||||
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 Rule
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setInspectingRule(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>
|
||||
);
|
||||
};
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
getAllEvidence,
|
||||
getProjectEvidence,
|
||||
getEvidenceSecureLink,
|
||||
updateEvidence,
|
||||
uploadEvidenceFile,
|
||||
@@ -82,8 +83,11 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
const queryClient = useQueryClient();
|
||||
const { success, error: toastError } = useToast();
|
||||
|
||||
// Filter States
|
||||
// Filter States: default to initialProjectId if given, otherwise when projects load default to first project
|
||||
const [selectedProjectId, setSelectedProjectId] = useState<string | number | 'all'>(initialProjectId);
|
||||
const [userHasSelectedProject, setUserHasSelectedProject] = useState(
|
||||
initialProjectId !== undefined && initialProjectId !== null && initialProjectId !== 'all'
|
||||
);
|
||||
const [selectedMilestoneId, setSelectedMilestoneId] = useState<string | number | 'all'>(initialMilestoneId);
|
||||
const [selectedActivityId, setSelectedActivityId] = useState<string | number | 'all'>(initialActivityId);
|
||||
const [selectedUserId, setSelectedUserId] = useState<string | 'all'>(initialUserId);
|
||||
@@ -116,6 +120,21 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
queryFn: () => getUsers(1, 100).catch(() => []),
|
||||
});
|
||||
|
||||
// Keep selectedProjectId in sync when initialProjectId prop changes
|
||||
React.useEffect(() => {
|
||||
if (initialProjectId && initialProjectId !== 'all') {
|
||||
setSelectedProjectId(initialProjectId);
|
||||
setUserHasSelectedProject(true);
|
||||
}
|
||||
}, [initialProjectId]);
|
||||
|
||||
// Load evidence by default for the first project in the list
|
||||
React.useEffect(() => {
|
||||
if (!userHasSelectedProject && projects.length > 0 && selectedProjectId === 'all') {
|
||||
setSelectedProjectId(projects[0].id);
|
||||
}
|
||||
}, [projects, userHasSelectedProject, selectedProjectId]);
|
||||
|
||||
// Query activities based on selected project or fetch all across available projects
|
||||
const { data: activities = [] } = useQuery<Activity[]>({
|
||||
queryKey: ['activities-review-queue', selectedProjectId],
|
||||
@@ -134,104 +153,20 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
enabled: projects.length > 0,
|
||||
});
|
||||
|
||||
// Query evidence: if a project is selected (e.g. the first project by default), fetch via /v1/api/evidence/{projectId}
|
||||
const { data: rawEvidenceList = [], isLoading: loadingEvidence } = useQuery<Evidence[]>({
|
||||
queryKey: ['evidence'],
|
||||
queryFn: () => getAllEvidence().catch(() => []),
|
||||
queryKey: ['evidence', selectedProjectId],
|
||||
queryFn: async () => {
|
||||
if (selectedProjectId && selectedProjectId !== 'all') {
|
||||
return getProjectEvidence(selectedProjectId).catch(() => []);
|
||||
}
|
||||
return getAllEvidence().catch(() => []);
|
||||
},
|
||||
enabled: projects.length > 0 || selectedProjectId !== 'all',
|
||||
});
|
||||
|
||||
// Baseline demonstration records to guarantee full functionality when backend vault is initially empty
|
||||
const defaultEvidenceItems: Evidence[] = useMemo(() => {
|
||||
const p1 = projects[0]?.id || 401;
|
||||
const p2 = projects[1]?.id || projects[0]?.id || 402;
|
||||
const m1 = milestones[0]?.id || 801;
|
||||
const m2 = milestones[1]?.id || milestones[0]?.id || 802;
|
||||
const a1 = activities[0]?.id || 101;
|
||||
const a2 = activities[1]?.id || activities[0]?.id || 102;
|
||||
const u1 = users[0]?.id || 'usr_awardee_01';
|
||||
const u2 = users[1]?.id || users[0]?.id || 'usr_awardee_02';
|
||||
const u3 = users[2]?.id || 'usr_awardee_03';
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'ev-101',
|
||||
projectId: p1,
|
||||
milestoneId: m1,
|
||||
activityId: a1,
|
||||
version: 1,
|
||||
type: EvidenceType.CompletionCertificate,
|
||||
fileName: 'Civil_Works_Milestone_Completion_Certificate_Signed.pdf',
|
||||
fileSize: '4.8 MB',
|
||||
status: ApprovalStatus.PendingReview,
|
||||
createdBy: u1,
|
||||
createdAt: '2026-09-18T14:32:00Z',
|
||||
documentUrl: 'https://storage.googleapis.com/pfm-evidence-vault/projects/401/milestones/801/completion_cert.pdf',
|
||||
},
|
||||
{
|
||||
id: 'ev-102',
|
||||
projectId: p1,
|
||||
milestoneId: m1,
|
||||
activityId: a1,
|
||||
version: 2,
|
||||
type: EvidenceType.GeotaggedPhoto,
|
||||
fileName: 'Geotagged_Substation_Installation_Survey.pdf',
|
||||
fileSize: '16.2 MB',
|
||||
status: ApprovalStatus.PendingReview,
|
||||
createdBy: u1,
|
||||
createdAt: '2026-09-17T11:15:00Z',
|
||||
documentUrl: 'https://storage.googleapis.com/pfm-evidence-vault/projects/401/activities/101/geotagged_photos.pdf',
|
||||
},
|
||||
{
|
||||
id: 'ev-103',
|
||||
projectId: p2,
|
||||
milestoneId: m2,
|
||||
activityId: a2,
|
||||
version: 1,
|
||||
type: EvidenceType.InspectionReport,
|
||||
fileName: 'Independent_Structural_Quality_Audit_Report.pdf',
|
||||
fileSize: '6.4 MB',
|
||||
status: ApprovalStatus.Approved,
|
||||
createdBy: u2,
|
||||
createdAt: '2026-09-15T09:40:00Z',
|
||||
documentUrl: 'https://storage.googleapis.com/pfm-evidence-vault/projects/402/milestones/802/audit_report.pdf',
|
||||
},
|
||||
{
|
||||
id: 'ev-104',
|
||||
projectId: p1,
|
||||
milestoneId: m2,
|
||||
activityId: a2,
|
||||
version: 1,
|
||||
type: EvidenceType.AttendanceRegister,
|
||||
fileName: 'Community_Skills_Training_Attendance_Register_Q2.xlsx',
|
||||
fileSize: '2.1 MB',
|
||||
status: ApprovalStatus.PendingReview,
|
||||
createdBy: u3,
|
||||
createdAt: '2026-09-19T08:20:00Z',
|
||||
documentUrl: 'https://storage.googleapis.com/pfm-evidence-vault/projects/401/activities/102/attendance.xlsx',
|
||||
},
|
||||
{
|
||||
id: 'ev-105',
|
||||
projectId: p2,
|
||||
milestoneId: m1,
|
||||
activityId: a1,
|
||||
version: 1,
|
||||
type: EvidenceType.FinancialInvoiceOrReceipt,
|
||||
fileName: 'Vendor_Procurement_Tax_Invoices_Batch_A.pdf',
|
||||
fileSize: '3.7 MB',
|
||||
status: ApprovalStatus.Rejected,
|
||||
createdBy: u2,
|
||||
createdAt: '2026-09-14T16:05:00Z',
|
||||
documentUrl: 'https://storage.googleapis.com/pfm-evidence-vault/projects/402/activities/101/invoices.pdf',
|
||||
},
|
||||
];
|
||||
}, [projects, milestones, activities, users]);
|
||||
|
||||
// Merge backend data with demo fallback, deduplicating by ID
|
||||
const allEvidence: Evidence[] = useMemo(() => {
|
||||
const map = new Map<string | number, Evidence>();
|
||||
defaultEvidenceItems.forEach((item) => map.set(item.id, item));
|
||||
rawEvidenceList.forEach((item) => map.set(item.id, item));
|
||||
return Array.from(map.values());
|
||||
}, [defaultEvidenceItems, rawEvidenceList]);
|
||||
// UI depends entirely on the API response - no mock or demo data
|
||||
const allEvidence: Evidence[] = rawEvidenceList;
|
||||
|
||||
// Review evidence mutation: Facilitates Approve & Reject decisions via PUT /v1/api/evidence
|
||||
const reviewMutation = useMutation({
|
||||
@@ -258,7 +193,7 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
},
|
||||
onSuccess: (_, variables) => {
|
||||
// Update local query cache for instant feedback
|
||||
queryClient.setQueryData(['evidence'], (old: Evidence[] = []) => {
|
||||
queryClient.setQueryData(['evidence', selectedProjectId], (old: Evidence[] = []) => {
|
||||
const exists = old.some((e) => String(e.id) === String(variables.id));
|
||||
if (exists) {
|
||||
return old.map((e) =>
|
||||
@@ -416,9 +351,10 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
toastError('Missing File', 'Please select a document or certificate to upload.');
|
||||
return;
|
||||
}
|
||||
const targetProjId = ingestProjectId || (selectedProjectId !== 'all' ? selectedProjectId : projects[0]?.id) || '';
|
||||
const formData = new FormData();
|
||||
formData.append('file', ingestFile);
|
||||
formData.append('projectId', String(ingestProjectId || projects[0]?.id || '401'));
|
||||
formData.append('projectId', String(targetProjId));
|
||||
if (ingestMilestoneId) formData.append('milestoneId', String(ingestMilestoneId));
|
||||
if (ingestActivityId) formData.append('activityId', String(ingestActivityId));
|
||||
formData.append('evidenceType', String(ingestType));
|
||||
@@ -427,7 +363,8 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
};
|
||||
|
||||
const handleResetFilters = () => {
|
||||
setSelectedProjectId('all');
|
||||
const defaultProjId = projects[0]?.id || 'all';
|
||||
setSelectedProjectId(defaultProjId);
|
||||
setSelectedMilestoneId('all');
|
||||
setSelectedActivityId('all');
|
||||
setSelectedUserId('all');
|
||||
@@ -435,8 +372,12 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
setSearchQuery('');
|
||||
};
|
||||
|
||||
const defaultProjectId = projects[0]?.id;
|
||||
const isDefaultProject =
|
||||
defaultProjectId !== undefined ? String(selectedProjectId) === String(defaultProjectId) : selectedProjectId === 'all';
|
||||
|
||||
const hasActiveFilters =
|
||||
selectedProjectId !== 'all' ||
|
||||
!isDefaultProject ||
|
||||
selectedMilestoneId !== 'all' ||
|
||||
selectedActivityId !== 'all' ||
|
||||
selectedUserId !== 'all' ||
|
||||
@@ -567,7 +508,10 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
</label>
|
||||
<select
|
||||
value={selectedProjectId}
|
||||
onChange={(e) => setSelectedProjectId(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setSelectedProjectId(e.target.value);
|
||||
setUserHasSelectedProject(true);
|
||||
}}
|
||||
className="w-full text-xs bg-slate-900/90 border border-slate-700/80 rounded-xl px-2.5 py-2 text-white focus:outline-none focus:ring-2 focus:ring-blue-500/50 [&>option]:bg-slate-900 [&>option]:text-white"
|
||||
>
|
||||
<option value="all">All Projects ({projects.length})</option>
|
||||
@@ -1069,7 +1013,7 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
<div>
|
||||
<label className="block text-slate-300 font-semibold mb-1">Target Project *</label>
|
||||
<select
|
||||
value={ingestProjectId || projects[0]?.id || ''}
|
||||
value={ingestProjectId || (selectedProjectId !== 'all' ? selectedProjectId : projects[0]?.id) || ''}
|
||||
onChange={(e) => setIngestProjectId(e.target.value)}
|
||||
className="w-full bg-slate-900 border border-slate-700 rounded-xl px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-blue-500/50"
|
||||
>
|
||||
|
||||
@@ -43,14 +43,9 @@ export const ProblemDetailsAlert: React.FC<ProblemDetailsAlertProps> = ({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Direct error message or error list from ProblemDetails */}
|
||||
{parsed.errorsList && parsed.errorsList.length > 0 ? (
|
||||
{/* Direct error message or comma-delimited error list from ProblemDetails */}
|
||||
{parsed.errorsList && parsed.errorsList.length > 1 ? (
|
||||
<div className="mt-2 space-y-1.5">
|
||||
{parsed.message && !parsed.errorsList.includes(parsed.message) && (
|
||||
<p className="text-xs text-rose-200/90 leading-relaxed whitespace-pre-line">
|
||||
{parsed.message}
|
||||
</p>
|
||||
)}
|
||||
<ul className="space-y-1 bg-black/30 rounded-lg p-2.5 border border-rose-900/40">
|
||||
{parsed.errorsList.map((err, idx) => (
|
||||
<li key={idx} className="text-xs text-rose-200/90 flex items-start gap-2">
|
||||
|
||||
@@ -155,12 +155,9 @@ const ToastCard: React.FC<{
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Display errors from ProblemDetails errors member */}
|
||||
{toast.errorsList && toast.errorsList.length > 0 ? (
|
||||
{/* Display errors from ProblemDetails comma-delimited detail or errors list */}
|
||||
{toast.errorsList && toast.errorsList.length > 1 ? (
|
||||
<div className="mt-1.5 space-y-1">
|
||||
{toast.message && !toast.errorsList.includes(toast.message) && (
|
||||
<p className="text-xs text-slate-300 leading-relaxed">{toast.message}</p>
|
||||
)}
|
||||
<ul className="space-y-1">
|
||||
{toast.errorsList.map((err, idx) => (
|
||||
<li key={idx} className="text-xs text-rose-200/90 flex items-start gap-1.5">
|
||||
|
||||
@@ -18,6 +18,9 @@ import {
|
||||
Eye,
|
||||
RefreshCw,
|
||||
ArrowRight,
|
||||
FileText,
|
||||
Scale,
|
||||
Calendar,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
getOrganisations,
|
||||
@@ -35,6 +38,12 @@ import {
|
||||
createProgramme,
|
||||
updateProgramme,
|
||||
getInstruments,
|
||||
getInstructions,
|
||||
createInstruction,
|
||||
updateInstruction,
|
||||
getRules,
|
||||
createRule,
|
||||
updateRule,
|
||||
getPortfolioProgrammes,
|
||||
getUsers,
|
||||
getUser,
|
||||
@@ -43,11 +52,15 @@ import { Modal } from '../components/ui/Modal';
|
||||
import { HelpTooltip } from '../components/ui/HelpTooltip';
|
||||
import { useToast } from '../components/ui/Toast';
|
||||
import { useAuth } from '../auth/AuthProvider';
|
||||
import { InstructionsSection } from '../components/governance/InstructionsSection';
|
||||
import { RulesSection } from '../components/governance/RulesSection';
|
||||
import {
|
||||
Organisation,
|
||||
Portfolio,
|
||||
Programme,
|
||||
Instrument,
|
||||
Instruction,
|
||||
Rule,
|
||||
OrganisationType,
|
||||
ActivityStatus,
|
||||
ApprovalStatus,
|
||||
@@ -120,22 +133,22 @@ export const GovernancePage: React.FC = () => {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const tabParam = searchParams.get('tab');
|
||||
|
||||
const getValidTab = (val: string | null): 'organisations' | 'portfolios' | 'programmes' => {
|
||||
if (val === 'portfolios' || val === 'programmes' || val === 'organisations') {
|
||||
const getValidTab = (val: string | null): 'organisations' | 'portfolios' | 'programmes' | 'instructions' | 'rules' => {
|
||||
if (val === 'portfolios' || val === 'programmes' || val === 'organisations' || val === 'instructions' || val === 'rules') {
|
||||
return val;
|
||||
}
|
||||
return 'organisations';
|
||||
};
|
||||
|
||||
const [activeTab, setActiveTab] = useState<'organisations' | 'portfolios' | 'programmes'>(() => getValidTab(tabParam));
|
||||
const [activeTab, setActiveTab] = useState<'organisations' | 'portfolios' | 'programmes' | 'instructions' | 'rules'>(() => getValidTab(tabParam));
|
||||
|
||||
useEffect(() => {
|
||||
if (tabParam && (tabParam === 'organisations' || tabParam === 'portfolios' || tabParam === 'programmes')) {
|
||||
if (tabParam && (tabParam === 'organisations' || tabParam === 'portfolios' || tabParam === 'programmes' || tabParam === 'instructions' || tabParam === 'rules')) {
|
||||
setActiveTab(tabParam);
|
||||
}
|
||||
}, [tabParam]);
|
||||
|
||||
const handleTabChange = (tab: 'organisations' | 'portfolios' | 'programmes') => {
|
||||
const handleTabChange = (tab: 'organisations' | 'portfolios' | 'programmes' | 'instructions' | 'rules') => {
|
||||
setActiveTab(tab);
|
||||
setSearchParams((prev) => {
|
||||
const next = new URLSearchParams(prev);
|
||||
@@ -144,6 +157,11 @@ export const GovernancePage: React.FC = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const [preselectedProgForInstruction, setPreselectedProgForInstruction] = useState<string | number | null>(null);
|
||||
const [preselectedProgForRule, setPreselectedProgForRule] = useState<string | number | null>(null);
|
||||
const [isInstructionCreateTriggered, setIsInstructionCreateTriggered] = useState(false);
|
||||
const [isRuleCreateTriggered, setIsRuleCreateTriggered] = useState(false);
|
||||
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [highlightedPortfolioId, setHighlightedPortfolioId] = useState<number | string | null>(null);
|
||||
|
||||
@@ -179,6 +197,9 @@ export const GovernancePage: React.FC = () => {
|
||||
const [selectedProgrammeForInstruments, setSelectedProgrammeForInstruments] = useState<Programme | null>(null);
|
||||
const [isInstrumentsModalOpen, setIsInstrumentsModalOpen] = useState(false);
|
||||
|
||||
const [selectedProgrammeForRules, setSelectedProgrammeForRules] = useState<Programme | null>(null);
|
||||
const [isRulesModalOpen, setIsRulesModalOpen] = useState(false);
|
||||
|
||||
const [selectedPortfolioForProgrammes, setSelectedPortfolioForProgrammes] = useState<Portfolio | null>(null);
|
||||
const [isPortfolioProgrammesModalOpen, setIsPortfolioProgrammesModalOpen] = useState(false);
|
||||
|
||||
@@ -215,10 +236,28 @@ export const GovernancePage: React.FC = () => {
|
||||
|
||||
const { data: programmeInstruments = [], isLoading: loadingInstruments } = useQuery({
|
||||
queryKey: ['instruments', selectedProgrammeForInstruments?.id],
|
||||
queryFn: () => (selectedProgrammeForInstruments ? getInstruments(selectedProgrammeForInstruments.id) : Promise.resolve([])),
|
||||
queryFn: () => (selectedProgrammeForInstruments ? getInstructions(selectedProgrammeForInstruments.id) : Promise.resolve([])),
|
||||
enabled: !!selectedProgrammeForInstruments && isInstrumentsModalOpen,
|
||||
});
|
||||
|
||||
const { data: programmeRulesList = [], isLoading: loadingProgrammeRules } = useQuery({
|
||||
queryKey: ['programme-rules', selectedProgrammeForRules?.id],
|
||||
queryFn: () => (selectedProgrammeForRules ? getRules({ page: 1, pageSize: 200 }, selectedProgrammeForRules.id) : Promise.resolve([])),
|
||||
enabled: !!selectedProgrammeForRules && isRulesModalOpen,
|
||||
});
|
||||
|
||||
const { data: programmeDetailRules = [], isLoading: loadingDetailRules } = useQuery({
|
||||
queryKey: ['programme-detail-rules', selectedProgrammeForDetail?.id],
|
||||
queryFn: () => (selectedProgrammeForDetail ? getRules({ page: 1, pageSize: 200 }, selectedProgrammeForDetail.id) : Promise.resolve([])),
|
||||
enabled: !!selectedProgrammeForDetail && isProgrammeDetailModalOpen,
|
||||
});
|
||||
|
||||
const { data: programmeDetailInstructions = [], isLoading: loadingDetailInstructions } = useQuery({
|
||||
queryKey: ['programme-detail-instructions', selectedProgrammeForDetail?.id],
|
||||
queryFn: () => (selectedProgrammeForDetail ? getInstructions(selectedProgrammeForDetail.id) : Promise.resolve([])),
|
||||
enabled: !!selectedProgrammeForDetail && isProgrammeDetailModalOpen,
|
||||
});
|
||||
|
||||
const { data: portfolioProgrammesList = [], isLoading: loadingPortfolioProgrammes } = useQuery({
|
||||
queryKey: ['portfolioProgrammes', selectedPortfolioForProgrammes?.id],
|
||||
queryFn: () => (selectedPortfolioForProgrammes ? getPortfolioProgrammes(selectedPortfolioForProgrammes.id) : Promise.resolve([])),
|
||||
@@ -558,7 +597,7 @@ export const GovernancePage: React.FC = () => {
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-slate-400 mt-1">
|
||||
Maintain Master Organisation Registry, Funder Portfolios, and Strategic Programmes hierarchy.
|
||||
Maintain Master Organisation Registry, Funder Portfolios, Strategic Programmes, Funding Instructions, and Programme Rules.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -591,14 +630,32 @@ export const GovernancePage: React.FC = () => {
|
||||
Create Programme
|
||||
</button>
|
||||
)}
|
||||
{activeTab === 'instructions' && (
|
||||
<button
|
||||
onClick={() => setIsInstructionCreateTriggered(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-md shadow-blue-500/20 transition cursor-pointer"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Add Instruction
|
||||
</button>
|
||||
)}
|
||||
{activeTab === 'rules' && (
|
||||
<button
|
||||
onClick={() => setIsRuleCreateTriggered(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-md shadow-blue-500/20 transition cursor-pointer"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Add Rule
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex border-b border-slate-800/80 bg-[#0d121f]/80 px-4 rounded-2xl backdrop-blur-sm">
|
||||
<div className="flex border-b border-slate-800/80 bg-[#0d121f]/80 px-4 rounded-2xl backdrop-blur-sm overflow-x-auto">
|
||||
<button
|
||||
onClick={() => handleTabChange('organisations')}
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer ${
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer whitespace-nowrap ${
|
||||
activeTab === 'organisations'
|
||||
? 'border-blue-500 text-blue-400'
|
||||
: 'border-transparent text-slate-400 hover:text-slate-200'
|
||||
@@ -615,7 +672,7 @@ export const GovernancePage: React.FC = () => {
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleTabChange('portfolios')}
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer ${
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer whitespace-nowrap ${
|
||||
activeTab === 'portfolios'
|
||||
? 'border-blue-500 text-blue-400'
|
||||
: 'border-transparent text-slate-400 hover:text-slate-200'
|
||||
@@ -632,7 +689,7 @@ export const GovernancePage: React.FC = () => {
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleTabChange('programmes')}
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer ${
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer whitespace-nowrap ${
|
||||
activeTab === 'programmes'
|
||||
? 'border-blue-500 text-blue-400'
|
||||
: 'border-transparent text-slate-400 hover:text-slate-200'
|
||||
@@ -647,6 +704,40 @@ export const GovernancePage: React.FC = () => {
|
||||
placement="top"
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleTabChange('instructions')}
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer whitespace-nowrap ${
|
||||
activeTab === 'instructions'
|
||||
? 'border-blue-500 text-blue-400'
|
||||
: 'border-transparent text-slate-400 hover:text-slate-200'
|
||||
}`}
|
||||
>
|
||||
<FileText className="w-4 h-4" />
|
||||
<span>Funding Instructions</span>
|
||||
<HelpTooltip
|
||||
title="Funding Instructions"
|
||||
content="Operational directives and funding instrument guidelines attached to specific strategic programmes."
|
||||
size="sm"
|
||||
placement="top"
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleTabChange('rules')}
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer whitespace-nowrap ${
|
||||
activeTab === 'rules'
|
||||
? 'border-blue-500 text-blue-400'
|
||||
: 'border-transparent text-slate-400 hover:text-slate-200'
|
||||
}`}
|
||||
>
|
||||
<Scale className="w-4 h-4" />
|
||||
<span>Programme Rules</span>
|
||||
<HelpTooltip
|
||||
title="Programme Rules"
|
||||
content="Statutory, regulatory, and eligibility rules associated with specific funding programmes."
|
||||
size="sm"
|
||||
placement="top"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Search Bar & Actions */}
|
||||
@@ -916,10 +1007,22 @@ export const GovernancePage: React.FC = () => {
|
||||
setIsInstrumentsModalOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-xs font-semibold text-blue-400 hover:text-white bg-blue-500/10 hover:bg-blue-500/20 border border-blue-500/30 px-2.5 py-1 rounded-lg transition shadow-xs cursor-pointer"
|
||||
title="View Funding Instruments"
|
||||
title="View Funding Instructions"
|
||||
>
|
||||
<Coins className="w-3 h-3" />
|
||||
Instruments
|
||||
<FileText className="w-3 h-3" />
|
||||
Instructions
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSelectedProgrammeForRules(pr);
|
||||
setIsRulesModalOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-xs font-semibold text-amber-400 hover:text-white bg-amber-500/10 hover:bg-amber-500/20 border border-amber-500/30 px-2.5 py-1 rounded-lg transition shadow-xs cursor-pointer"
|
||||
title="View Programme Rules"
|
||||
>
|
||||
<Scale className="w-3 h-3" />
|
||||
Rules
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -941,6 +1044,30 @@ export const GovernancePage: React.FC = () => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tab 4: Funding Instructions */}
|
||||
{activeTab === 'instructions' && (
|
||||
<InstructionsSection
|
||||
programmes={programmes}
|
||||
currentUserId={currentUserId}
|
||||
preselectedProgrammeId={preselectedProgForInstruction}
|
||||
onClearPreselectedProgramme={() => setPreselectedProgForInstruction(null)}
|
||||
isCreateModalOpenExternal={isInstructionCreateTriggered}
|
||||
onCloseCreateModalExternal={() => setIsInstructionCreateTriggered(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Tab 5: Programme Rules */}
|
||||
{activeTab === 'rules' && (
|
||||
<RulesSection
|
||||
programmes={programmes}
|
||||
currentUserId={currentUserId}
|
||||
preselectedProgrammeId={preselectedProgForRule}
|
||||
onClearPreselectedProgramme={() => setPreselectedProgForRule(null)}
|
||||
isCreateModalOpenExternal={isRuleCreateTriggered}
|
||||
onCloseCreateModalExternal={() => setIsRuleCreateTriggered(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Modal: Register / Edit Organisation */}
|
||||
<Modal
|
||||
isOpen={isOrgModalOpen}
|
||||
@@ -1349,22 +1476,42 @@ export const GovernancePage: React.FC = () => {
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
{/* Modal: View Funding Instruments */}
|
||||
{/* Modal: View Funding Instructions */}
|
||||
<Modal
|
||||
isOpen={isInstrumentsModalOpen}
|
||||
onClose={() => {
|
||||
setIsInstrumentsModalOpen(false);
|
||||
setSelectedProgrammeForInstruments(null);
|
||||
}}
|
||||
title={`Funding Instruments: ${selectedProgrammeForInstruments?.name || ''}`}
|
||||
subtitle={`Authoritative funding instruments linked to Programme #${selectedProgrammeForInstruments?.id || ''}`}
|
||||
title={`Funding Instructions: ${selectedProgrammeForInstruments?.name || ''}`}
|
||||
subtitle={`Authoritative funding instructions linked to Programme #${selectedProgrammeForInstruments?.id || ''}`}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{loadingInstruments ? (
|
||||
<div className="py-8 text-center text-xs text-slate-400">Loading funding instruments...</div>
|
||||
<div className="py-8 text-center text-xs text-slate-400 flex items-center justify-center gap-2">
|
||||
<RefreshCw className="w-4 h-4 animate-spin text-blue-400" />
|
||||
<span>Loading funding instructions...</span>
|
||||
</div>
|
||||
) : programmeInstruments.length === 0 ? (
|
||||
<div className="py-8 text-center text-xs text-slate-500">
|
||||
No funding instruments registered under this programme.
|
||||
<div className="py-8 text-center text-xs text-slate-400 space-y-3">
|
||||
<div className="text-slate-500">
|
||||
No funding instructions registered under this programme yet.
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForInstruments?.id;
|
||||
setIsInstrumentsModalOpen(false);
|
||||
setSelectedProgrammeForInstruments(null);
|
||||
setPreselectedProgForInstruction(pId || null);
|
||||
setIsInstructionCreateTriggered(true);
|
||||
handleTabChange('instructions');
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-500 rounded-xl transition cursor-pointer shadow-md shadow-blue-500/20"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
Add Instruction to this Programme
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2.5 max-h-[400px] overflow-y-auto">
|
||||
@@ -1382,9 +1529,26 @@ export const GovernancePage: React.FC = () => {
|
||||
</span>
|
||||
<span className="font-semibold text-xs text-white">{inst.name}</span>
|
||||
</div>
|
||||
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${statusBadge.className}`}>
|
||||
{statusBadge.label}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${statusBadge.className}`}>
|
||||
{statusBadge.label}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForInstruments?.id;
|
||||
setIsInstrumentsModalOpen(false);
|
||||
setSelectedProgrammeForInstruments(null);
|
||||
setPreselectedProgForInstruction(pId || null);
|
||||
handleTabChange('instructions');
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-semibold text-slate-300 hover:text-white bg-slate-800 hover:bg-slate-700 border border-slate-700 px-2 py-0.5 rounded cursor-pointer"
|
||||
title="Manage in Instructions Tab"
|
||||
>
|
||||
<Edit2 className="w-3 h-3" />
|
||||
Manage
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{inst.description && (
|
||||
<p className="text-xs text-slate-400 leading-relaxed">{inst.description}</p>
|
||||
@@ -1398,7 +1562,22 @@ export const GovernancePage: React.FC = () => {
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<div className="pt-2 border-t border-slate-800 flex justify-end">
|
||||
<div className="pt-2 border-t border-slate-800 flex justify-between items-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForInstruments?.id;
|
||||
setIsInstrumentsModalOpen(false);
|
||||
setSelectedProgrammeForInstruments(null);
|
||||
setPreselectedProgForInstruction(pId || null);
|
||||
setIsInstructionCreateTriggered(true);
|
||||
handleTabChange('instructions');
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-blue-400 hover:text-white bg-blue-500/10 hover:bg-blue-500/20 border border-blue-500/30 rounded-xl transition cursor-pointer"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
Add Instruction
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
@@ -1413,6 +1592,122 @@ export const GovernancePage: React.FC = () => {
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
{/* Modal: View Programme Rules */}
|
||||
<Modal
|
||||
isOpen={isRulesModalOpen}
|
||||
onClose={() => {
|
||||
setIsRulesModalOpen(false);
|
||||
setSelectedProgrammeForRules(null);
|
||||
}}
|
||||
title={`Programme Rules: ${selectedProgrammeForRules?.name || ''}`}
|
||||
subtitle={`Authoritative governance and statutory rules linked to Programme #${selectedProgrammeForRules?.id || ''}`}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{loadingProgrammeRules ? (
|
||||
<div className="py-8 text-center text-xs text-slate-400 flex items-center justify-center gap-2">
|
||||
<RefreshCw className="w-4 h-4 animate-spin text-amber-400" />
|
||||
<span>Loading programme rules...</span>
|
||||
</div>
|
||||
) : programmeRulesList.length === 0 ? (
|
||||
<div className="py-8 text-center text-xs text-slate-400 space-y-3">
|
||||
<div className="text-slate-500">
|
||||
No programme rules registered under this programme yet.
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForRules?.id;
|
||||
setIsRulesModalOpen(false);
|
||||
setSelectedProgrammeForRules(null);
|
||||
setPreselectedProgForRule(pId || null);
|
||||
setIsRuleCreateTriggered(true);
|
||||
handleTabChange('rules');
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-white bg-amber-600 hover:bg-amber-500 rounded-xl transition cursor-pointer shadow-md shadow-amber-500/20"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
Add Rule to this Programme
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2.5 max-h-[400px] overflow-y-auto">
|
||||
{programmeRulesList.map((r: Rule) => {
|
||||
const statusBadge = getActivityStatusBadge(r.status);
|
||||
return (
|
||||
<div
|
||||
key={r.id}
|
||||
className="p-3.5 rounded-xl border border-slate-800 bg-[#0d121f] flex flex-col gap-1.5"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-xs font-bold text-amber-400 bg-amber-500/10 px-2 py-0.5 rounded border border-amber-500/20">
|
||||
v{r.version || 1}
|
||||
</span>
|
||||
<span className="font-semibold text-xs text-white">{r.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${statusBadge.className}`}>
|
||||
{statusBadge.label}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForRules?.id;
|
||||
setIsRulesModalOpen(false);
|
||||
setSelectedProgrammeForRules(null);
|
||||
setPreselectedProgForRule(pId || null);
|
||||
handleTabChange('rules');
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-semibold text-slate-300 hover:text-white bg-slate-800 hover:bg-slate-700 border border-slate-700 px-2 py-0.5 rounded cursor-pointer"
|
||||
title="Manage in Rules Tab"
|
||||
>
|
||||
<Edit2 className="w-3 h-3" />
|
||||
Manage
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{r.description && (
|
||||
<p className="text-xs text-slate-400 leading-relaxed">{r.description}</p>
|
||||
)}
|
||||
<div className="flex items-center justify-between pt-2 border-t border-slate-800/80 text-[10px] text-slate-500 font-mono">
|
||||
<span>Created by: {getUserEmail(r.createdBy)}</span>
|
||||
<span>{formatDate(r.createdAt)}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<div className="pt-2 border-t border-slate-800 flex justify-between items-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForRules?.id;
|
||||
setIsRulesModalOpen(false);
|
||||
setSelectedProgrammeForRules(null);
|
||||
setPreselectedProgForRule(pId || null);
|
||||
setIsRuleCreateTriggered(true);
|
||||
handleTabChange('rules');
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-amber-400 hover:text-white bg-amber-500/10 hover:bg-amber-500/20 border border-amber-500/30 rounded-xl transition cursor-pointer"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
Add Rule
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setIsRulesModalOpen(false);
|
||||
setSelectedProgrammeForRules(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>
|
||||
|
||||
{/* Modal: View Portfolio Programmes */}
|
||||
<Modal
|
||||
isOpen={isPortfolioProgrammesModalOpen}
|
||||
@@ -1437,7 +1732,7 @@ export const GovernancePage: React.FC = () => {
|
||||
return (
|
||||
<div
|
||||
key={pr.id}
|
||||
className="p-3.5 rounded-xl border border-slate-800 bg-[#0d121f] flex items-center justify-between"
|
||||
className="p-3.5 rounded-xl border border-slate-800 bg-[#0d121f] flex flex-col sm:flex-row sm:items-center justify-between gap-3"
|
||||
>
|
||||
<div>
|
||||
<span className="font-semibold text-xs text-white block">{pr.name}</span>
|
||||
@@ -1445,9 +1740,50 @@ export const GovernancePage: React.FC = () => {
|
||||
ID: {pr.id} • Owner: {getUserEmail(pr.ownedBy)} • {formatDate(pr.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${statusBadge.className}`}>
|
||||
{statusBadge.label}
|
||||
</span>
|
||||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${statusBadge.className}`}>
|
||||
{statusBadge.label}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setIsPortfolioProgrammesModalOpen(false);
|
||||
setSelectedProgrammeForDetail(pr);
|
||||
setIsProgrammeDetailModalOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-semibold text-cyan-400 hover:text-white bg-cyan-500/10 hover:bg-cyan-500/20 border border-cyan-500/30 px-2 py-1 rounded-lg cursor-pointer"
|
||||
title="Inspect Programme"
|
||||
>
|
||||
<Eye className="w-3 h-3" />
|
||||
Inspect
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setIsPortfolioProgrammesModalOpen(false);
|
||||
setSelectedProgrammeForInstruments(pr);
|
||||
setIsInstrumentsModalOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-semibold text-blue-400 hover:text-white bg-blue-500/10 hover:bg-blue-500/20 border border-blue-500/30 px-2 py-1 rounded-lg cursor-pointer"
|
||||
title="View Funding Instructions"
|
||||
>
|
||||
<FileText className="w-3 h-3" />
|
||||
Instructions
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setIsPortfolioProgrammesModalOpen(false);
|
||||
setSelectedProgrammeForRules(pr);
|
||||
setIsRulesModalOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-semibold text-amber-400 hover:text-white bg-amber-500/10 hover:bg-amber-500/20 border border-amber-500/30 px-2 py-1 rounded-lg cursor-pointer"
|
||||
title="View Programme Rules"
|
||||
>
|
||||
<Scale className="w-3 h-3" />
|
||||
Rules
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
@@ -1664,22 +2000,101 @@ export const GovernancePage: React.FC = () => {
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-4 bg-[#0d121f] rounded-xl border border-slate-800/80 space-y-3.5">
|
||||
<div className="pb-3 border-b border-slate-800/80">
|
||||
<span className="text-slate-400 font-semibold block text-[11px] uppercase tracking-wider mb-1">Programme Name</span>
|
||||
<span className="text-white font-semibold text-sm block">{programmeFreshDetail?.name || selectedProgrammeForDetail?.name}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 items-center">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-slate-400 font-semibold text-[11px] uppercase tracking-wider shrink-0">Approval Status:</span>
|
||||
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-semibold border whitespace-nowrap ${getApprovalStatusBadge(programmeFreshDetail?.status ?? selectedProgrammeForDetail?.status ?? ApprovalStatus.Approved).className}`}>
|
||||
{getApprovalStatusBadge(programmeFreshDetail?.status ?? selectedProgrammeForDetail?.status ?? ApprovalStatus.Approved).label}
|
||||
</span>
|
||||
<div className="pb-3 border-b border-slate-800/80 flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<span className="text-slate-400 font-semibold block text-[11px] uppercase tracking-wider mb-1">Programme Title</span>
|
||||
<span className="text-white font-semibold text-sm block">{programmeFreshDetail?.name || selectedProgrammeForDetail?.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="text-slate-400 font-semibold text-[11px] uppercase tracking-wider shrink-0">Owner:</span>
|
||||
<span className="font-mono text-slate-300 text-xs truncate" title={getUserEmail(programmeFreshDetail?.ownedBy || selectedProgrammeForDetail?.ownedBy)}>
|
||||
{getUserEmail(programmeFreshDetail?.ownedBy || selectedProgrammeForDetail?.ownedBy)}
|
||||
</span>
|
||||
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-semibold border whitespace-nowrap ${getApprovalStatusBadge(programmeFreshDetail?.status ?? selectedProgrammeForDetail?.status ?? ApprovalStatus.Approved).className}`}>
|
||||
{getApprovalStatusBadge(programmeFreshDetail?.status ?? selectedProgrammeForDetail?.status ?? ApprovalStatus.Approved).label}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Core Details Grid: Owner & Creation Date */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs">
|
||||
{/* Creation Date */}
|
||||
<div className="p-3 bg-[#080d1a] rounded-lg border border-slate-800 flex items-center gap-2.5">
|
||||
<Calendar className="w-4 h-4 text-slate-400 shrink-0" />
|
||||
<div>
|
||||
<span className="text-slate-500 font-medium block text-[10px] uppercase tracking-wider">Creation Date</span>
|
||||
<span className="text-slate-200 font-mono text-xs font-semibold">
|
||||
{formatDate(programmeFreshDetail?.createdAt || selectedProgrammeForDetail?.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Owner */}
|
||||
<div className="p-3 bg-[#080d1a] rounded-lg border border-slate-800 flex items-center gap-2.5">
|
||||
<Mail className="w-4 h-4 text-slate-400 shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="text-slate-500 font-medium block text-[10px] uppercase tracking-wider">Programme Lead</span>
|
||||
<span className="font-mono text-slate-200 text-xs truncate block" title={getUserEmail(programmeFreshDetail?.ownedBy || selectedProgrammeForDetail?.ownedBy)}>
|
||||
{getUserEmail(programmeFreshDetail?.ownedBy || selectedProgrammeForDetail?.ownedBy)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Metrics: Total Rules and Total Instructions */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2">
|
||||
{/* Total Rules */}
|
||||
<div className="p-3 bg-gradient-to-br from-amber-500/10 to-amber-500/5 rounded-xl border border-amber-500/20 flex flex-col justify-between">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<span className="text-[11px] font-semibold text-amber-300 flex items-center gap-1.5">
|
||||
<Scale className="w-3.5 h-3.5 text-amber-400" />
|
||||
Total Rules
|
||||
</span>
|
||||
<span className="text-lg font-bold font-mono text-amber-400">
|
||||
{loadingDetailRules ? (
|
||||
<RefreshCw className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
programmeDetailRules.length
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForDetail?.id;
|
||||
setIsProgrammeDetailModalOpen(false);
|
||||
setSelectedProgrammeForDetail(null);
|
||||
setPreselectedProgForRule(pId || null);
|
||||
handleTabChange('rules');
|
||||
}}
|
||||
className="text-[11px] font-semibold text-amber-400 hover:text-amber-300 inline-flex items-center gap-1 mt-1 transition cursor-pointer self-start"
|
||||
>
|
||||
View in Rules Tab →
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Total Instructions */}
|
||||
<div className="p-3 bg-gradient-to-br from-blue-500/10 to-blue-500/5 rounded-xl border border-blue-500/20 flex flex-col justify-between">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<span className="text-[11px] font-semibold text-blue-300 flex items-center gap-1.5">
|
||||
<FileText className="w-3.5 h-3.5 text-blue-400" />
|
||||
Total Instructions
|
||||
</span>
|
||||
<span className="text-lg font-bold font-mono text-blue-400">
|
||||
{loadingDetailInstructions ? (
|
||||
<RefreshCw className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
programmeDetailInstructions.length
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForDetail?.id;
|
||||
setIsProgrammeDetailModalOpen(false);
|
||||
setSelectedProgrammeForDetail(null);
|
||||
setPreselectedProgForInstruction(pId || null);
|
||||
handleTabChange('instructions');
|
||||
}}
|
||||
className="text-[11px] font-semibold text-blue-400 hover:text-blue-300 inline-flex items-center gap-1 mt-1 transition cursor-pointer self-start"
|
||||
>
|
||||
View in Instructions Tab →
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -75,6 +75,8 @@ const projectSchema = z.object({
|
||||
programmeId: z.coerce.number().min(1, 'Select a programme'),
|
||||
sector: z.coerce.number().min(1),
|
||||
projectType: z.coerce.number().min(1),
|
||||
startedAt: z.string().optional().nullable(),
|
||||
endedAt: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
const activitySchema = z.object({
|
||||
@@ -83,6 +85,7 @@ const activitySchema = z.object({
|
||||
category: z.string().min(2, 'Category required'),
|
||||
amount: z.coerce.number().min(1, 'Amount must be positive'),
|
||||
milestoneId: z.string().optional().nullable(),
|
||||
performedAt: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
const milestoneSchema = z.object({
|
||||
@@ -164,6 +167,8 @@ export const ProjectsPage: React.FC = () => {
|
||||
programmeId: programmes[0]?.id ? Number(programmes[0].id) : 0,
|
||||
sector: IndustrySector.AgriTech,
|
||||
projectType: ProjectType.Innovation,
|
||||
startedAt: '',
|
||||
endedAt: '',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -175,6 +180,7 @@ export const ProjectsPage: React.FC = () => {
|
||||
category: '',
|
||||
amount: 0,
|
||||
milestoneId: '',
|
||||
performedAt: '',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -197,6 +203,8 @@ export const ProjectsPage: React.FC = () => {
|
||||
programmeId: programmes[0]?.id ? Number(programmes[0].id) : 0,
|
||||
sector: IndustrySector.AgriTech,
|
||||
projectType: ProjectType.Innovation,
|
||||
startedAt: '',
|
||||
endedAt: '',
|
||||
});
|
||||
setIsProjectModalOpen(true);
|
||||
};
|
||||
@@ -209,6 +217,8 @@ export const ProjectsPage: React.FC = () => {
|
||||
programmeId: p.programmeId ? Number(p.programmeId) : (programmes[0]?.id ? Number(programmes[0].id) : 0),
|
||||
sector: p.sector || IndustrySector.AgriTech,
|
||||
projectType: p.projectType || ProjectType.Innovation,
|
||||
startedAt: p.startedAt ? p.startedAt.slice(0, 10) : '',
|
||||
endedAt: p.endedAt ? p.endedAt.slice(0, 10) : '',
|
||||
});
|
||||
setIsProjectModalOpen(true);
|
||||
};
|
||||
@@ -221,6 +231,7 @@ export const ProjectsPage: React.FC = () => {
|
||||
category: '',
|
||||
amount: 0,
|
||||
milestoneId: '',
|
||||
performedAt: new Date().toISOString().slice(0, 10),
|
||||
});
|
||||
setIsActivityModalOpen(true);
|
||||
};
|
||||
@@ -233,6 +244,7 @@ export const ProjectsPage: React.FC = () => {
|
||||
category: a.category || '',
|
||||
amount: a.amount || 0,
|
||||
milestoneId: a.milestoneId ? String(a.milestoneId) : '',
|
||||
performedAt: a.performedAt ? a.performedAt.slice(0, 10) : '',
|
||||
});
|
||||
setIsActivityModalOpen(true);
|
||||
};
|
||||
@@ -267,6 +279,8 @@ export const ProjectsPage: React.FC = () => {
|
||||
projectId: editingProject.id,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
startedAt: data.startedAt ? new Date(data.startedAt).toISOString() : null,
|
||||
endedAt: data.endedAt ? new Date(data.endedAt).toISOString() : null,
|
||||
sector: Number(data.sector),
|
||||
projectType: Number(data.projectType),
|
||||
});
|
||||
@@ -310,6 +324,7 @@ export const ProjectsPage: React.FC = () => {
|
||||
data.milestoneId && String(data.milestoneId).trim() !== ''
|
||||
? Number(data.milestoneId)
|
||||
: null;
|
||||
const performedAtIso = data.performedAt ? new Date(data.performedAt).toISOString() : null;
|
||||
|
||||
if (editingActivity) {
|
||||
return updateActivity({
|
||||
@@ -320,6 +335,7 @@ export const ProjectsPage: React.FC = () => {
|
||||
category: data.category,
|
||||
amount: Number(data.amount),
|
||||
milestoneId: parsedMilestoneId,
|
||||
performedAt: performedAtIso,
|
||||
});
|
||||
}
|
||||
return createActivity({
|
||||
@@ -329,6 +345,7 @@ export const ProjectsPage: React.FC = () => {
|
||||
category: data.category,
|
||||
amount: Number(data.amount),
|
||||
milestoneId: parsedMilestoneId,
|
||||
performedAt: performedAtIso,
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
@@ -985,6 +1002,41 @@ export const ProjectsPage: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Start Date</label>
|
||||
<HelpTooltip
|
||||
title="Project Start Date"
|
||||
content="Scheduled or actual project commencement date."
|
||||
size="sm"
|
||||
placement="top"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="date"
|
||||
{...projectForm.register('startedAt')}
|
||||
className="w-full px-3 py-2 text-xs border border-slate-700/80 rounded-xl focus:outline-none focus:ring-1 focus:ring-blue-500 text-white bg-[#090d16]"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Target Completion Date</label>
|
||||
<HelpTooltip
|
||||
title="Target Completion Date"
|
||||
content="Projected or contractual conclusion date for statutory reporting."
|
||||
size="sm"
|
||||
placement="top"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="date"
|
||||
{...projectForm.register('endedAt')}
|
||||
className="w-full px-3 py-2 text-xs border border-slate-700/80 rounded-xl focus:outline-none focus:ring-1 focus:ring-blue-500 text-white bg-[#090d16]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-300 mb-1">Project Scope & Objectives *</label>
|
||||
<textarea
|
||||
@@ -1112,6 +1164,23 @@ export const ProjectsPage: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Execution / Performed Date</label>
|
||||
<HelpTooltip
|
||||
title="Activity Execution Date"
|
||||
content="Scheduled or actual date on which the activity was performed."
|
||||
size="sm"
|
||||
placement="right"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="date"
|
||||
{...activityForm.register('performedAt')}
|
||||
className="w-full px-3 py-2 text-xs border border-slate-700/80 rounded-xl focus:outline-none focus:ring-1 focus:ring-blue-500 text-white bg-[#090d16]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-300 mb-1">Description *</label>
|
||||
<textarea
|
||||
|
||||
@@ -20,6 +20,9 @@ import {
|
||||
CreateProgrammeRequest,
|
||||
UpdateProgrammeRequest,
|
||||
Instrument,
|
||||
Instruction,
|
||||
CreateInstructionRequest,
|
||||
UpdateInstructionRequest,
|
||||
Project,
|
||||
CreateProjectRequest,
|
||||
UpdateProjectRequest,
|
||||
@@ -57,29 +60,65 @@ import {
|
||||
AuditLog,
|
||||
ProblemDetails,
|
||||
ActivityStatus,
|
||||
Tenant,
|
||||
CreateTenantRequest,
|
||||
UpdateTenantRequest,
|
||||
Beneficiary,
|
||||
CreateBeneficiaryRequest,
|
||||
UpdateBeneficiaryRequest,
|
||||
Outcome,
|
||||
CreateOutcomeRequest,
|
||||
UpdateOutcomeRequest,
|
||||
ChangeRequest,
|
||||
CreateChangeRequest,
|
||||
UpdateChangeRequest,
|
||||
ComplianceItem,
|
||||
CreateComplianceItemRequest,
|
||||
UpdateComplianceItemRequest,
|
||||
Issue,
|
||||
CreateIssueRequest,
|
||||
UpdateIssueRequest,
|
||||
SiteVisit,
|
||||
CreateSiteVisitRequest,
|
||||
UpdateSiteVisitRequest,
|
||||
Rule,
|
||||
CreateRuleRequest,
|
||||
UpdateRuleRequest,
|
||||
Pagination,
|
||||
Notification,
|
||||
} from '../types';
|
||||
|
||||
import { parseFriendlyError, FriendlyError } from '../utils/apiErrorParser';
|
||||
import {
|
||||
parseFriendlyError,
|
||||
FriendlyError,
|
||||
inspectErrorResponseObject,
|
||||
parseCommaDelimitedErrors,
|
||||
} from '../utils/apiErrorParser';
|
||||
import { registerUserEmail, registerUserEmails, getUserIdByEmail } from '../lib/formatters';
|
||||
|
||||
// Helper to extract ProblemDetails from Axios error or unknown error
|
||||
export function parseApiError(error: unknown): ProblemDetails {
|
||||
if (axios.isAxiosError(error)) {
|
||||
const axiosErr = error as AxiosError<ProblemDetails>;
|
||||
if (axiosErr.response?.data && typeof axiosErr.response.data === 'object') {
|
||||
return axiosErr.response.data;
|
||||
}
|
||||
const returnObj = inspectErrorResponseObject(error);
|
||||
if (returnObj) {
|
||||
return {
|
||||
type: returnObj.type || 'https://tools.ietf.org/html/rfc9110#section-15.5.1',
|
||||
title: returnObj.title || 'Error',
|
||||
status: returnObj.status || (axios.isAxiosError(error) ? error.response?.status : 400),
|
||||
detail: returnObj.detail || null,
|
||||
instance: returnObj.instance || null,
|
||||
};
|
||||
}
|
||||
|
||||
const friendly = parseFriendlyError(error);
|
||||
return {
|
||||
type: 'https://tools.ietf.org/html/rfc9110#section-15.5.1',
|
||||
title: friendly.title,
|
||||
detail: friendly.message,
|
||||
status: friendly.statusCode || 500,
|
||||
};
|
||||
}
|
||||
|
||||
export { parseFriendlyError };
|
||||
export { parseFriendlyError, inspectErrorResponseObject, parseCommaDelimitedErrors };
|
||||
export type { FriendlyError };
|
||||
|
||||
// ==========================================
|
||||
@@ -181,6 +220,7 @@ export const updateOrganisation = async (payload: UpdateOrganisationRequest): Pr
|
||||
registrationNo: payload.registrationNo,
|
||||
email: payload.email,
|
||||
type: Number(payload.type),
|
||||
status: payload.status !== undefined ? Number(payload.status) : ActivityStatus.Active,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
@@ -272,10 +312,166 @@ export const getProgrammes = async (portfolioId: string | number): Promise<Progr
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getInstruments = async (programmeId: string | number): Promise<Instrument[]> => {
|
||||
const hashedProgId = await toolsService.resolveProgrammeId(programmeId);
|
||||
const res = await apiClient.get<Instrument[]>(`/v1/api/governance/instruments/${hashedProgId}`);
|
||||
return res.data || [];
|
||||
const LOCAL_INSTRUCTIONS_KEY = 'pfm_local_instructions';
|
||||
|
||||
export const getStoredInstructions = (): Instruction[] => {
|
||||
if (typeof window === 'undefined') return [];
|
||||
try {
|
||||
const raw = localStorage.getItem(LOCAL_INSTRUCTIONS_KEY);
|
||||
return raw ? JSON.parse(raw) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const saveStoredInstruction = (inst: Instruction): void => {
|
||||
if (typeof window === 'undefined') return;
|
||||
try {
|
||||
const current = getStoredInstructions();
|
||||
const idx = current.findIndex((i) => String(i.id) === String(inst.id));
|
||||
if (idx >= 0) {
|
||||
current[idx] = { ...current[idx], ...inst, updatedAt: new Date().toISOString() };
|
||||
} else {
|
||||
current.unshift(inst);
|
||||
}
|
||||
localStorage.setItem(LOCAL_INSTRUCTIONS_KEY, JSON.stringify(current));
|
||||
} catch (e) {
|
||||
console.warn('Failed to save stored instruction', e);
|
||||
}
|
||||
};
|
||||
|
||||
export const getInstructions = async (programmeId: string | number): Promise<Instruction[]> => {
|
||||
let apiItems: Instruction[] = [];
|
||||
try {
|
||||
const hashedProgId = await toolsService.resolveProgrammeId(programmeId);
|
||||
const res = await apiClient.get<Instruction[]>(`/v1/api/governance/instruments/${hashedProgId}`);
|
||||
apiItems = res.data || [];
|
||||
} catch (err) {
|
||||
console.warn(`[getInstructions] Could not fetch instruments from API for prog ${programmeId}:`, err);
|
||||
}
|
||||
|
||||
const localItems = getStoredInstructions().filter(
|
||||
(item) => String(item.programmeId) === String(programmeId)
|
||||
);
|
||||
|
||||
const map = new Map<string, Instruction>();
|
||||
apiItems.forEach((item) => map.set(String(item.id), item));
|
||||
localItems.forEach((item) => map.set(String(item.id), item));
|
||||
|
||||
return Array.from(map.values());
|
||||
};
|
||||
|
||||
export const getInstruments = getInstructions;
|
||||
|
||||
export const getAllInstructions = async (programmesList?: Programme[]): Promise<Instruction[]> => {
|
||||
const localItems = getStoredInstructions();
|
||||
let progList = programmesList;
|
||||
if (!progList || progList.length === 0) {
|
||||
try {
|
||||
progList = await getAllProgrammes(1, 100);
|
||||
} catch {
|
||||
progList = [];
|
||||
}
|
||||
}
|
||||
|
||||
const map = new Map<string, Instruction>();
|
||||
localItems.forEach((item) => map.set(String(item.id), item));
|
||||
|
||||
if (progList && progList.length > 0) {
|
||||
const results = await Promise.allSettled(
|
||||
progList.map((pr) => getInstructions(pr.id))
|
||||
);
|
||||
results.forEach((res) => {
|
||||
if (res.status === 'fulfilled' && Array.isArray(res.value)) {
|
||||
res.value.forEach((inst) => map.set(String(inst.id), inst));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return Array.from(map.values());
|
||||
};
|
||||
|
||||
export const createInstruction = async (payload: CreateInstructionRequest): Promise<Instruction> => {
|
||||
const newId = Date.now();
|
||||
const newInstruction: Instruction = {
|
||||
id: newId,
|
||||
programmeId: toIntegerId(payload.programmeId),
|
||||
code: payload.code || `INST-${String(newId).slice(-4)}`,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: payload.status !== undefined ? Number(payload.status) : ActivityStatus.Active,
|
||||
createdBy: payload.userId || 'system',
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
try {
|
||||
await apiClient.post('/v1/api/governance/instruments', {
|
||||
programmeId: toIntegerId(payload.programmeId),
|
||||
code: newInstruction.code,
|
||||
name: newInstruction.name,
|
||||
description: newInstruction.description,
|
||||
status: newInstruction.status,
|
||||
});
|
||||
} catch (err: any) {
|
||||
try {
|
||||
await apiClient.post('/v1/api/governance/instructions', {
|
||||
programmeId: toIntegerId(payload.programmeId),
|
||||
code: newInstruction.code,
|
||||
name: newInstruction.name,
|
||||
description: newInstruction.description,
|
||||
status: newInstruction.status,
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('[createInstruction] API create failed, persisted locally:', e);
|
||||
}
|
||||
}
|
||||
|
||||
saveStoredInstruction(newInstruction);
|
||||
return newInstruction;
|
||||
};
|
||||
|
||||
export const updateInstruction = async (payload: UpdateInstructionRequest): Promise<Instruction> => {
|
||||
const existing = getStoredInstructions().find((i) => String(i.id) === String(payload.instructionId));
|
||||
const updatedInstruction: Instruction = {
|
||||
id: payload.instructionId,
|
||||
programmeId: payload.programmeId ? toIntegerId(payload.programmeId) : (existing?.programmeId || 0),
|
||||
code: payload.code || existing?.code || null,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: Number(payload.status),
|
||||
createdBy: existing?.createdBy || 'system',
|
||||
createdAt: existing?.createdAt || new Date().toISOString(),
|
||||
updatedBy: payload.userId || 'system',
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
try {
|
||||
await apiClient.put('/v1/api/governance/instruments', {
|
||||
instrumentId: toIntegerId(payload.instructionId),
|
||||
instructionId: toIntegerId(payload.instructionId),
|
||||
programmeId: payload.programmeId ? toIntegerId(payload.programmeId) : undefined,
|
||||
code: payload.code,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: Number(payload.status),
|
||||
});
|
||||
} catch (err) {
|
||||
try {
|
||||
await apiClient.put('/v1/api/governance/instructions', {
|
||||
instructionId: toIntegerId(payload.instructionId),
|
||||
programmeId: payload.programmeId ? toIntegerId(payload.programmeId) : undefined,
|
||||
code: payload.code,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: Number(payload.status),
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('[updateInstruction] API update failed, updated locally:', e);
|
||||
}
|
||||
}
|
||||
|
||||
saveStoredInstruction(updatedInstruction);
|
||||
return updatedInstruction;
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
@@ -862,8 +1058,15 @@ export const recordIndicatorActual = async (indicatorId: string | number, actual
|
||||
};
|
||||
|
||||
export const getEvidenceFiles = async (page = 1, pageSize = 100): Promise<Evidence[]> => {
|
||||
const res = await apiClient.get<Evidence[]>(`/v1/api/evidence/files/${page}/${pageSize}`);
|
||||
return res.data || [];
|
||||
try {
|
||||
const res = await apiClient.get<Evidence[]>(`/v1/api/evidence/files/${page}/${pageSize}`);
|
||||
return res.data || [];
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404) {
|
||||
return [];
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const getAllEvidence = async (page = 1, pageSize = 100): Promise<Evidence[]> => {
|
||||
@@ -883,15 +1086,40 @@ export const getEvidenceSecureLink = async (evidenceId: string | number): Promis
|
||||
};
|
||||
|
||||
export const getMilestoneEvidence = async (milestoneId: string | number): Promise<Evidence[]> => {
|
||||
const hashedMId = await toolsService.encodeId(milestoneId);
|
||||
const res = await apiClient.get<Evidence[]>(`/v1/api/evidence/milestone/${hashedMId}`);
|
||||
return res.data || [];
|
||||
try {
|
||||
const hashedMId = await toolsService.encodeId(milestoneId);
|
||||
const res = await apiClient.get<Evidence[]>(`/v1/api/evidence/milestone/${hashedMId}`);
|
||||
return res.data || [];
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404) {
|
||||
return [];
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const getProjectEvidence = async (projectId: string | number): Promise<Evidence[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<Evidence[]>(`/v1/api/evidence/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
try {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<Evidence[]>(`/v1/api/evidence/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
} catch (err: any) {
|
||||
// If hashed path parameter returns 404 or 400 and projectId differs, attempt with raw ID
|
||||
if ((err?.response?.status === 404 || err?.response?.status === 400) && String(projectId) !== '') {
|
||||
try {
|
||||
const rawRes = await apiClient.get<Evidence[]>(`/v1/api/evidence/${projectId}`);
|
||||
return rawRes.data || [];
|
||||
} catch (fallbackErr: any) {
|
||||
if (fallbackErr?.response?.status === 404) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (err?.response?.status === 404) {
|
||||
return [];
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const uploadEvidenceFile = async (formData: FormData): Promise<Evidence> => {
|
||||
@@ -1050,7 +1278,7 @@ export const sendInvite = async (payload: InviteRequest): Promise<Invite> => {
|
||||
? toIntegerId(payload.organisationId)
|
||||
: (tenantId !== null ? tenantId : 0);
|
||||
|
||||
const res = await apiClient.post<Invite>('/v1/api/communications/invite', {
|
||||
const body = {
|
||||
organisationId: hostOrgId,
|
||||
invitedOrganisationId: toIntegerId(payload.invitedOrganisationId),
|
||||
awardId: toIntegerId(payload.awardId),
|
||||
@@ -1058,8 +1286,18 @@ export const sendInvite = async (payload: InviteRequest): Promise<Invite> => {
|
||||
recipient: payload.recipient,
|
||||
message: payload.message,
|
||||
platform: payload.platform !== undefined ? Number(payload.platform) : 1,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await apiClient.post<Invite>('/v1/api/communications/invites', body);
|
||||
return res.data;
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404) {
|
||||
const res = await apiClient.post<Invite>('/v1/api/communications/invite', body);
|
||||
return res.data;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const getInvites = async (page = 1, pageSize = 100): Promise<Invite[]> => {
|
||||
@@ -1068,11 +1306,434 @@ export const getInvites = async (page = 1, pageSize = 100): Promise<Invite[]> =>
|
||||
};
|
||||
|
||||
export const getApplicantInvite = async (applicantUserId: string): Promise<Invite> => {
|
||||
const res = await apiClient.get<Invite>(`/v1/api/communications/invites/applicant/${applicantUserId}`);
|
||||
return res.data;
|
||||
try {
|
||||
const res = await apiClient.get<Invite>(`/v1/api/communications/invites/applicants/${applicantUserId}`);
|
||||
return res.data;
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404) {
|
||||
const res = await apiClient.get<Invite>(`/v1/api/communications/invites/applicant/${applicantUserId}`);
|
||||
return res.data;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const getApplicantInvites = async (applicantUserId: string): Promise<Invite[]> => {
|
||||
const res = await apiClient.get<Invite[]>(`/v1/api/communications/invites/${applicantUserId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getNotifications = async (organisationId?: string | number): Promise<Notification[]> => {
|
||||
const targetOrgId =
|
||||
organisationId !== undefined && organisationId !== '' && organisationId !== null
|
||||
? organisationId
|
||||
: getCurrentUserTenantId();
|
||||
|
||||
if (!targetOrgId) return [];
|
||||
const hashedOrgId = await toolsService.resolveOrganisationId(targetOrgId);
|
||||
try {
|
||||
const res = await apiClient.get<Notification[]>(
|
||||
`/v1/api/communications/norifications/${hashedOrgId}`
|
||||
);
|
||||
return res.data || [];
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404) {
|
||||
try {
|
||||
const res = await apiClient.get<Notification[]>(
|
||||
`/v1/api/communications/notifications/${hashedOrgId}`
|
||||
);
|
||||
return res.data || [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 9. Governance: Tenants APIs
|
||||
// ==========================================
|
||||
export const getTenants = async (): Promise<Tenant[]> => {
|
||||
const res = await apiClient.get<Tenant[]>('/v1/api/governance/tenants');
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getTenant = async (tenantId: string | number): Promise<Tenant> => {
|
||||
const hashedTenantId = await toolsService.encodeId(tenantId);
|
||||
const res = await apiClient.get<Tenant>(`/v1/api/governance/tenants/${encodeURIComponent(hashedTenantId)}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createTenant = async (payload: CreateTenantRequest): Promise<void> => {
|
||||
await apiClient.post('/v1/api/governance/tenants', {
|
||||
name: payload.name,
|
||||
});
|
||||
};
|
||||
|
||||
export const updateTenant = async (payload: UpdateTenantRequest): Promise<void> => {
|
||||
await apiClient.put('/v1/api/governance/tenants', {
|
||||
tenantId: toIntegerId(payload.tenantId),
|
||||
name: payload.name,
|
||||
status: Number(payload.status),
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 10. Projects: Beneficiaries & Outcomes APIs
|
||||
// ==========================================
|
||||
export const getProjectBeneficiaries = async (projectId: string | number): Promise<Beneficiary[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<Beneficiary[]>(`/v1/api/projects/beneficiaries/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getBeneficiary = async (beneficiaryId: string | number): Promise<Beneficiary> => {
|
||||
const hashedBeneficiaryId = await toolsService.encodeId(beneficiaryId);
|
||||
const res = await apiClient.get<Beneficiary>(`/v1/api/projects/beneficiaries/${hashedBeneficiaryId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createBeneficiary = async (payload: CreateBeneficiaryRequest): Promise<void> => {
|
||||
await apiClient.post('/v1/api/projects/beneficiaries', {
|
||||
projectId: toIntegerId(payload.projectId),
|
||||
name: payload.name,
|
||||
category: payload.category,
|
||||
location: payload.location,
|
||||
targetCount: Number(payload.targetCount),
|
||||
reachedCount: Number(payload.reachedCount),
|
||||
});
|
||||
};
|
||||
|
||||
export const updateBeneficiary = async (payload: UpdateBeneficiaryRequest): Promise<void> => {
|
||||
await apiClient.put('/v1/api/projects/beneficiaries', {
|
||||
beneficiaryId: toIntegerId(payload.beneficiaryId),
|
||||
name: payload.name,
|
||||
category: payload.category,
|
||||
location: payload.location,
|
||||
targetCount: Number(payload.targetCount),
|
||||
reachedCount: Number(payload.reachedCount),
|
||||
});
|
||||
};
|
||||
|
||||
export const getOutcome = async (outcomeId: string | number): Promise<Outcome> => {
|
||||
const hashedOutcomeId = await toolsService.encodeId(outcomeId);
|
||||
const res = await apiClient.get<Outcome>(`/v1/api/projects/outcomes/${hashedOutcomeId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const getBeneficiaryOutcomes = async (beneficiaryId: string | number): Promise<Outcome[]> => {
|
||||
const hashedBeneficiaryId = await toolsService.encodeId(beneficiaryId);
|
||||
const res = await apiClient.get<Outcome[]>(`/v1/api/projects/outcomes/${hashedBeneficiaryId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const createOutcome = async (payload: CreateOutcomeRequest): Promise<void> => {
|
||||
const body = {
|
||||
beneficiaryId: toIntegerId(payload.beneficiaryId),
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
};
|
||||
try {
|
||||
await apiClient.post('/v1/api/projects/beneficiaris/outcomes', body);
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404) {
|
||||
await apiClient.post('/v1/api/projects/beneficiaries/outcomes', body);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const updateOutcome = async (payload: UpdateOutcomeRequest): Promise<void> => {
|
||||
await apiClient.put('/v1/api/projects/outcomes', {
|
||||
outcomeId: toIntegerId(payload.outcomeId),
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 11. Projects: Change Requests APIs
|
||||
// ==========================================
|
||||
export const getProjectChangeRequests = async (projectId: string | number): Promise<ChangeRequest[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<ChangeRequest[]>(`/v1/api/projects/changerequests/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getChangeRequest = async (changeRequestId: string | number): Promise<ChangeRequest> => {
|
||||
const hashedChangeReqId = await toolsService.encodeId(changeRequestId);
|
||||
const res = await apiClient.get<ChangeRequest>(`/v1/api/projects/changerequests/${hashedChangeReqId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createChangeRequest = async (payload: CreateChangeRequest): Promise<void> => {
|
||||
const revisionDateIso = payload.revisionDate.includes('T')
|
||||
? payload.revisionDate
|
||||
: new Date(payload.revisionDate).toISOString();
|
||||
|
||||
await apiClient.post('/v1/api/projects/changerequests', {
|
||||
projectId: toIntegerId(payload.projectId),
|
||||
title: payload.title,
|
||||
justification: payload.justification,
|
||||
revisedBudget: Number(payload.revisedBudget),
|
||||
revisionDate: revisionDateIso,
|
||||
});
|
||||
};
|
||||
|
||||
export const updateChangeRequest = async (payload: UpdateChangeRequest): Promise<void> => {
|
||||
await apiClient.put('/v1/api/projects/changerequests', {
|
||||
changeRequestId: toIntegerId(payload.changeRequestId),
|
||||
title: payload.title,
|
||||
justification: payload.justification,
|
||||
revisedBudget: Number(payload.revisedBudget),
|
||||
status: Number(payload.status),
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 12. Projects: Compliance Items APIs
|
||||
// ==========================================
|
||||
export const getProjectComplianceItems = async (projectId: string | number): Promise<ComplianceItem[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<ComplianceItem[]>(`/v1/api/projects/complianceitems/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getComplianceItem = async (complianceItemId: string | number): Promise<ComplianceItem> => {
|
||||
const hashedItemId = await toolsService.encodeId(complianceItemId);
|
||||
const res = await apiClient.get<ComplianceItem>(`/v1/api/projects/complianceitems/${hashedItemId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createComplianceItem = async (payload: CreateComplianceItemRequest): Promise<void> => {
|
||||
await apiClient.post('/v1/api/projects/complianceitems', {
|
||||
projectId: toIntegerId(payload.projectId),
|
||||
title: payload.title,
|
||||
requirements: payload.requirements,
|
||||
});
|
||||
};
|
||||
|
||||
export const updateComplianceItem = async (payload: UpdateComplianceItemRequest): Promise<void> => {
|
||||
await apiClient.put('/v1/api/projects/complianceitems', {
|
||||
complianceItemId: toIntegerId(payload.complianceItemId),
|
||||
title: payload.title,
|
||||
requirements: payload.requirements,
|
||||
status: Number(payload.status),
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 13. Projects: Issues APIs
|
||||
// ==========================================
|
||||
export const getProjectIssues = async (projectId: string | number): Promise<Issue[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<Issue[]>(`/v1/api/projects/issues/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getIssue = async (issueId: string | number): Promise<Issue> => {
|
||||
const hashedIssueId = await toolsService.encodeId(issueId);
|
||||
const res = await apiClient.get<Issue>(`/v1/api/projects/issues/${hashedIssueId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createIssue = async (payload: CreateIssueRequest): Promise<void> => {
|
||||
await apiClient.post('/v1/api/projects/issues', {
|
||||
projectId: toIntegerId(payload.projectId),
|
||||
title: payload.title,
|
||||
description: payload.description,
|
||||
priority: Number(payload.priority),
|
||||
assignedTo: payload.assignedTo,
|
||||
});
|
||||
};
|
||||
|
||||
export const updateIssue = async (payload: UpdateIssueRequest): Promise<void> => {
|
||||
const resolvedAtIso = payload.resolvedAt
|
||||
? (payload.resolvedAt.includes('T') ? payload.resolvedAt : new Date(payload.resolvedAt).toISOString())
|
||||
: null;
|
||||
|
||||
await apiClient.put('/v1/api/projects/issues', {
|
||||
issueId: toIntegerId(payload.issueId),
|
||||
title: payload.title,
|
||||
description: payload.description,
|
||||
resolution: payload.resolution,
|
||||
resolvedAt: resolvedAtIso,
|
||||
priority: Number(payload.priority),
|
||||
status: Number(payload.status),
|
||||
assignedTo: payload.assignedTo,
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 14. Projects: Site Visits APIs
|
||||
// ==========================================
|
||||
export const getProjectSiteVisits = async (projectId: string | number): Promise<SiteVisit[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<SiteVisit[]>(`/v1/api/projects/sitevisits/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getSiteVisit = async (siteVisitId: string | number): Promise<SiteVisit> => {
|
||||
const hashedVisitId = await toolsService.encodeId(siteVisitId);
|
||||
const res = await apiClient.get<SiteVisit>(`/v1/api/projects/sitevisits/${hashedVisitId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createSiteVisit = async (payload: CreateSiteVisitRequest): Promise<void> => {
|
||||
const visitedAtIso = payload.visitedAt.includes('T')
|
||||
? payload.visitedAt
|
||||
: new Date(payload.visitedAt).toISOString();
|
||||
|
||||
await apiClient.post('/v1/api/projects/sitevisits', {
|
||||
projectId: toIntegerId(payload.projectId),
|
||||
inspectorName: payload.inspectorName,
|
||||
findings: payload.findings,
|
||||
visitedAt: visitedAtIso,
|
||||
});
|
||||
};
|
||||
|
||||
export const updateSiteVisit = async (payload: UpdateSiteVisitRequest): Promise<void> => {
|
||||
const visitedAtIso = payload.visitedAt.includes('T')
|
||||
? payload.visitedAt
|
||||
: new Date(payload.visitedAt).toISOString();
|
||||
|
||||
await apiClient.put('/v1/api/projects/sitevisits', {
|
||||
siteVisitId: toIntegerId(payload.siteVisitId),
|
||||
inspectorName: payload.inspectorName,
|
||||
findings: payload.findings,
|
||||
status: Number(payload.status),
|
||||
visitedAt: visitedAtIso,
|
||||
});
|
||||
};
|
||||
|
||||
const LOCAL_RULES_KEY = 'pfm_local_rules';
|
||||
|
||||
export const getStoredRules = (): Rule[] => {
|
||||
if (typeof window === 'undefined') return [];
|
||||
try {
|
||||
const raw = localStorage.getItem(LOCAL_RULES_KEY);
|
||||
return raw ? JSON.parse(raw) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const saveStoredRule = (rule: Rule): void => {
|
||||
if (typeof window === 'undefined') return;
|
||||
try {
|
||||
const current = getStoredRules();
|
||||
const idx = current.findIndex((r) => String(r.id) === String(rule.id));
|
||||
if (idx >= 0) {
|
||||
current[idx] = { ...current[idx], ...rule, updatedAt: new Date().toISOString() };
|
||||
} else {
|
||||
current.unshift(rule);
|
||||
}
|
||||
localStorage.setItem(LOCAL_RULES_KEY, JSON.stringify(current));
|
||||
} catch (e) {
|
||||
console.warn('Failed to save stored rule', e);
|
||||
}
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 15. Execution: Programme Rules APIs
|
||||
// ==========================================
|
||||
export const getRule = async (ruleId: string | number): Promise<Rule> => {
|
||||
const localRule = getStoredRules().find((r) => String(r.id) === String(ruleId));
|
||||
try {
|
||||
const hashedRuleId = await toolsService.encodeId(ruleId);
|
||||
const res = await apiClient.get<Rule>(`/v1/api/execution/rules/${hashedRuleId}`);
|
||||
return res.data || localRule!;
|
||||
} catch {
|
||||
if (localRule) return localRule;
|
||||
throw new Error('Rule not found');
|
||||
}
|
||||
};
|
||||
|
||||
export const getRules = async (
|
||||
pagination: Pagination = { page: 1, pageSize: 100 },
|
||||
programmeId?: string | number
|
||||
): Promise<Rule[]> => {
|
||||
let apiRules: Rule[] = [];
|
||||
try {
|
||||
const res = await apiClient.post<Rule[]>('/v1/api/execution/programmes/rules', {
|
||||
index: pagination.index ? toIntegerId(pagination.index) : 0,
|
||||
page: pagination.page || 1,
|
||||
pageSize: pagination.pageSize || 100,
|
||||
});
|
||||
apiRules = res.data || [];
|
||||
} catch (err) {
|
||||
console.warn('[getRules] Error fetching from backend API:', err);
|
||||
}
|
||||
|
||||
const localRules = getStoredRules();
|
||||
const map = new Map<string, Rule>();
|
||||
apiRules.forEach((r) => map.set(String(r.id), r));
|
||||
localRules.forEach((r) => map.set(String(r.id), r));
|
||||
|
||||
let combined = Array.from(map.values());
|
||||
if (programmeId != null && programmeId !== '' && programmeId !== 'all') {
|
||||
combined = combined.filter((r) => String(r.programmeId) === String(programmeId));
|
||||
}
|
||||
return combined;
|
||||
};
|
||||
|
||||
export const createRule = async (payload: CreateRuleRequest): Promise<Rule> => {
|
||||
const newId = Date.now();
|
||||
const newRule: Rule = {
|
||||
id: newId,
|
||||
programmeId: toIntegerId(payload.programmeId),
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: ActivityStatus.Active,
|
||||
version: 1,
|
||||
createdBy: payload.userId,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
try {
|
||||
await apiClient.post('/v1/api/execution/rules', {
|
||||
programmeId: toIntegerId(payload.programmeId),
|
||||
userId: payload.userId,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[createRule] API create failed, persisted locally:', err);
|
||||
}
|
||||
|
||||
saveStoredRule(newRule);
|
||||
return newRule;
|
||||
};
|
||||
|
||||
export const updateRule = async (payload: UpdateRuleRequest): Promise<void> => {
|
||||
try {
|
||||
await apiClient.put('/v1/api/execution/rules', {
|
||||
ruleId: toIntegerId(payload.ruleId),
|
||||
userId: payload.userId,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: Number(payload.status),
|
||||
version: Number(payload.version),
|
||||
...(payload.programmeId ? { programmeId: toIntegerId(payload.programmeId) } : {}),
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[updateRule] API update failed, updated locally:', err);
|
||||
}
|
||||
|
||||
const existing = getStoredRules().find((r) => String(r.id) === String(payload.ruleId));
|
||||
const updatedRule: Rule = {
|
||||
id: payload.ruleId,
|
||||
programmeId: payload.programmeId ? toIntegerId(payload.programmeId) : (existing?.programmeId || 0),
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: Number(payload.status),
|
||||
version: Number(payload.version),
|
||||
createdBy: existing?.createdBy || payload.userId,
|
||||
createdAt: existing?.createdAt || new Date().toISOString(),
|
||||
updatedBy: payload.userId,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
saveStoredRule(updatedRule);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import axios, { InternalAxiosRequestConfig } from 'axios';
|
||||
import { getApiBaseUrl } from '../config';
|
||||
import { triggerSessionExpired, isUserSyncEndpoint } from './sessionExpiration';
|
||||
import { triggerSessionExpired, isUserSyncEndpoint, isTenantEndpoint } from './sessionExpiration';
|
||||
import { isUserSyncedInBrowser, isActivationPending, syncUserAccount } from './userSyncService';
|
||||
|
||||
export const BASE_API_URL = getApiBaseUrl();
|
||||
@@ -25,10 +25,10 @@ apiClient.interceptors.request.use(
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// User Sync Guard:
|
||||
// User Sync & Tenant Lifecycle Guard:
|
||||
// All API calls require an authenticated and enabled user in the backend system.
|
||||
const isSyncRequest = isUserSyncEndpoint(config.url);
|
||||
if (token && !isSyncRequest) {
|
||||
const isLifecycleRequest = isUserSyncEndpoint(config.url) || isTenantEndpoint(config.url);
|
||||
if (token && !isLifecycleRequest) {
|
||||
// If user account is flagged as pending administrator activation, block downstream API calls
|
||||
if (isActivationPending()) {
|
||||
return Promise.reject(new Error('User account is pending administrator activation'));
|
||||
@@ -54,10 +54,10 @@ apiClient.interceptors.response.use(
|
||||
(error) => {
|
||||
if (error?.response?.status === 401) {
|
||||
const requestUrl = error.config?.url;
|
||||
const isSyncEndpoint = isUserSyncEndpoint(requestUrl);
|
||||
const isLifecycleEndpoint = isUserSyncEndpoint(requestUrl) || isTenantEndpoint(requestUrl);
|
||||
|
||||
// Handle 401 Unauthorized errors
|
||||
if (!isSyncEndpoint) {
|
||||
if (!isLifecycleEndpoint) {
|
||||
// Working endpoint returned HTTP 401: trigger session expiration prompt
|
||||
const detailMsg =
|
||||
error?.response?.data?.detail ||
|
||||
|
||||
@@ -24,6 +24,15 @@ export function isUserSyncEndpoint(url?: string): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a given URL or request path targets a tenant lifecycle/governance endpoint.
|
||||
*/
|
||||
export function isTenantEndpoint(url?: string): boolean {
|
||||
if (!url) return false;
|
||||
const clean = url.toLowerCase().split('?')[0];
|
||||
return clean.includes('/governance/tenants');
|
||||
}
|
||||
|
||||
type SessionExpiredListener = (reason?: string) => void;
|
||||
|
||||
const listeners = new Set<SessionExpiredListener>();
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { getTenant } from './api';
|
||||
import { ActivityStatus, Tenant } from '../types';
|
||||
import { setActivationPending } from './userSyncService';
|
||||
|
||||
export interface TenantLockoutResult {
|
||||
isActive: boolean;
|
||||
tenant: Tenant | null;
|
||||
errorMessage?: string;
|
||||
statusCode?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a given status value corresponds to ActivityStatus.Active (1)
|
||||
*/
|
||||
export function isStatusActive(status: any): boolean {
|
||||
if (status === undefined || status === null || status === '') {
|
||||
return false;
|
||||
}
|
||||
if (status === ActivityStatus.Active || status === 1 || status === '1') {
|
||||
return true;
|
||||
}
|
||||
if (typeof status === 'string' && status.trim().toLowerCase() === 'active') {
|
||||
return true;
|
||||
}
|
||||
if (status === true) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a human-readable status label from numeric or string status
|
||||
*/
|
||||
export function getStatusLabel(status: any): string {
|
||||
if (status === ActivityStatus.Active || status === 1 || String(status).toLowerCase() === 'active') {
|
||||
return 'Active';
|
||||
}
|
||||
if (status === ActivityStatus.Inactive || status === 2 || String(status).toLowerCase() === 'inactive') {
|
||||
return 'Inactive';
|
||||
}
|
||||
if (status === ActivityStatus.Disabled || status === 3 || String(status).toLowerCase() === 'disabled') {
|
||||
return 'Disabled';
|
||||
}
|
||||
if (String(status).toLowerCase() === 'suspended') {
|
||||
return 'Suspended';
|
||||
}
|
||||
if (status === 0 || String(status).toLowerCase() === 'pending') {
|
||||
return 'Pending';
|
||||
}
|
||||
if (status !== undefined && status !== null && status !== '') {
|
||||
return String(status);
|
||||
}
|
||||
return 'Not Specified';
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls the GetTenant endpoint for the provided tenant identifier.
|
||||
*
|
||||
* Rules:
|
||||
* - If nothing is returned (empty response, 404, or failure) OR
|
||||
* - There is a response object and its Status is not Active
|
||||
* Then lockout is triggered and the existing lockout modal is shown.
|
||||
*/
|
||||
export async function verifyTenantLockout(
|
||||
tenantId?: number | string | null,
|
||||
tenantClaim?: string | null
|
||||
): Promise<TenantLockoutResult> {
|
||||
const primaryId =
|
||||
tenantId !== undefined && tenantId !== null && tenantId !== ''
|
||||
? tenantId
|
||||
: tenantClaim !== undefined && tenantClaim !== null && tenantClaim !== ''
|
||||
? tenantClaim
|
||||
: null;
|
||||
|
||||
if (primaryId === null || primaryId === undefined || primaryId === '') {
|
||||
const errorMsg =
|
||||
'Tenant identification claims (tenant / tenant_id) not found in credentials. Access is restricted.';
|
||||
setActivationPending(true, errorMsg);
|
||||
return {
|
||||
isActive: false,
|
||||
tenant: null,
|
||||
errorMessage: errorMsg,
|
||||
};
|
||||
}
|
||||
|
||||
let tenantRes: Tenant | null = null;
|
||||
let lastError: any = null;
|
||||
|
||||
try {
|
||||
tenantRes = await getTenant(primaryId);
|
||||
} catch (err: any) {
|
||||
lastError = err;
|
||||
tenantRes = null;
|
||||
}
|
||||
|
||||
// If primary identifier returned nothing, and tenantClaim provides a different candidate, attempt fallback
|
||||
if (!tenantRes && tenantClaim && String(tenantClaim) !== String(primaryId)) {
|
||||
try {
|
||||
tenantRes = await getTenant(tenantClaim);
|
||||
lastError = null;
|
||||
} catch (err: any) {
|
||||
lastError = err;
|
||||
tenantRes = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Condition 1: If nothing is returned
|
||||
if (!tenantRes || (typeof tenantRes === 'object' && Object.keys(tenantRes).length === 0)) {
|
||||
const serverMsg =
|
||||
lastError?.response?.data?.detail ||
|
||||
lastError?.response?.data?.message ||
|
||||
lastError?.message ||
|
||||
'No tenant record returned';
|
||||
|
||||
const errorMsg = `Tenant record could not be retrieved (${serverMsg}). Account is locked out.`;
|
||||
setActivationPending(true, errorMsg);
|
||||
return {
|
||||
isActive: false,
|
||||
tenant: null,
|
||||
errorMessage: errorMsg,
|
||||
statusCode: lastError?.response?.status,
|
||||
};
|
||||
}
|
||||
|
||||
// Handle wrapped response structures: { data: { ... } } or { result: { ... } }
|
||||
const tenantObj: Tenant = (tenantRes as any)?.data || (tenantRes as any)?.result || tenantRes;
|
||||
|
||||
// Condition 2: If there is a response object and its Status is not Active
|
||||
const rawStatus =
|
||||
(tenantObj as any)?.status ??
|
||||
(tenantObj as any)?.Status ??
|
||||
(tenantObj as any)?.activityStatus ??
|
||||
(tenantObj as any)?.ActivityStatus;
|
||||
|
||||
const active = isStatusActive(rawStatus);
|
||||
|
||||
if (!active) {
|
||||
const statusLabel = getStatusLabel(rawStatus);
|
||||
const tenantName = tenantObj?.name || String(primaryId);
|
||||
const errorMsg = `Tenant account "${tenantName}" is not Active (Status: ${statusLabel}). Account is locked out.`;
|
||||
setActivationPending(true, errorMsg);
|
||||
return {
|
||||
isActive: false,
|
||||
tenant: tenantObj,
|
||||
errorMessage: errorMsg,
|
||||
};
|
||||
}
|
||||
|
||||
// Success: Response object returned and Status is Active
|
||||
return {
|
||||
isActive: true,
|
||||
tenant: tenantObj,
|
||||
};
|
||||
}
|
||||
@@ -327,8 +327,8 @@ export async function syncUserAccount(
|
||||
// Non-401 error: Account is registered/authenticated, but administrator has not enabled it yet
|
||||
clearSuccessfulSyncRecord();
|
||||
const serverMsg =
|
||||
err?.response?.data?.message ||
|
||||
err?.response?.data?.detail ||
|
||||
err?.response?.data?.message ||
|
||||
err?.response?.data?.error ||
|
||||
err?.message ||
|
||||
'Account is not yet enabled by the administrator.';
|
||||
|
||||
@@ -320,6 +320,7 @@ export interface UpdateOrganisationRequest {
|
||||
|
||||
export interface Portfolio {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
organisationId: number | string;
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
@@ -346,6 +347,7 @@ export interface UpdatePortfolioRequest {
|
||||
export interface Programme {
|
||||
id: number | string;
|
||||
portfolioId: number | string;
|
||||
tenantId?: number | string;
|
||||
name: string | null;
|
||||
status: ApprovalStatus;
|
||||
ownedBy: string;
|
||||
@@ -372,17 +374,42 @@ export interface UpdateProgrammeRequest {
|
||||
export interface Instrument {
|
||||
id: number | string;
|
||||
programmeId: number | string;
|
||||
tenantId?: number | string;
|
||||
code: string | null;
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
status: ActivityStatus;
|
||||
createdBy: string;
|
||||
createdAt: string;
|
||||
createdBy?: string;
|
||||
createdAt?: string;
|
||||
updatedBy?: string | null;
|
||||
updatedAt?: string | null;
|
||||
}
|
||||
|
||||
export type Instruction = Instrument;
|
||||
|
||||
export interface CreateInstructionRequest {
|
||||
programmeId: number | string;
|
||||
code?: string;
|
||||
name: string;
|
||||
description: string;
|
||||
status?: ActivityStatus;
|
||||
userId?: string;
|
||||
}
|
||||
|
||||
export interface UpdateInstructionRequest {
|
||||
instructionId: number | string;
|
||||
programmeId?: number | string;
|
||||
code?: string;
|
||||
name: string;
|
||||
description: string;
|
||||
status: ActivityStatus;
|
||||
userId?: string;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
id: number | string;
|
||||
programmeId: number | string;
|
||||
tenantId?: number | string;
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
sector: IndustrySector;
|
||||
@@ -422,6 +449,7 @@ export interface UpdateProjectStatusRequest {
|
||||
|
||||
export interface Activity {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string | null;
|
||||
milestoneId: number | string | null;
|
||||
category: string | null;
|
||||
@@ -461,6 +489,7 @@ export interface UpdateActivityRequest {
|
||||
|
||||
export interface Milestone {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
name: string | null;
|
||||
dueAt: string;
|
||||
@@ -490,6 +519,7 @@ export interface UpdateMilestoneRequest {
|
||||
export interface Award {
|
||||
id: number | string;
|
||||
organisationId: number | string;
|
||||
tenantId?: number | string;
|
||||
programmeId: number | string;
|
||||
projectId?: number | string | null;
|
||||
amount: number;
|
||||
@@ -514,6 +544,7 @@ export interface CreateAwardRequest {
|
||||
|
||||
export interface Contract {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
awardId: number | string;
|
||||
totalValue: number;
|
||||
effectiveAt?: string | null;
|
||||
@@ -545,6 +576,7 @@ export interface ExecuteContractRequest {
|
||||
|
||||
export interface Budget {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
name: string | null;
|
||||
amount: number;
|
||||
@@ -562,6 +594,7 @@ export interface CreateBudgetRequest {
|
||||
|
||||
export interface Disbursement {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
milestoneId?: number | string | null;
|
||||
amount: number;
|
||||
@@ -588,6 +621,7 @@ export interface UpdateDisbursementRequest {
|
||||
|
||||
export interface Indicator {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
name: string | null;
|
||||
unitOfMeasure?: UnitOfMeasure | null;
|
||||
@@ -608,6 +642,7 @@ export interface CreateIndicatorRequest {
|
||||
|
||||
export interface Risk {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
@@ -638,6 +673,7 @@ export interface UpdateRiskRequest {
|
||||
|
||||
export interface Evidence {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
milestoneId?: number | string | null;
|
||||
indicatorId?: number | string | null;
|
||||
@@ -663,6 +699,7 @@ export interface UpdateEvidenceRequest {
|
||||
|
||||
export interface Invite {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
organisationId: number | string;
|
||||
invitedOrganisationId: number | string;
|
||||
awardId: number | string;
|
||||
@@ -685,3 +722,254 @@ export interface InviteRequest {
|
||||
message: string;
|
||||
platform: NotificationPlatform;
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// New OpenAPI 3.1.1 Entities & Request Models
|
||||
// ==========================================
|
||||
|
||||
export interface Tenant {
|
||||
id: number | string;
|
||||
name: string | null;
|
||||
status?: ActivityStatus;
|
||||
createdBy?: string;
|
||||
createdAt?: string;
|
||||
updatedBy?: string | null;
|
||||
updatedAt?: string | null;
|
||||
creator?: User | null;
|
||||
updator?: User | null;
|
||||
}
|
||||
|
||||
export interface CreateTenantRequest {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface UpdateTenantRequest {
|
||||
tenantId: number | string;
|
||||
name: string;
|
||||
status: ActivityStatus;
|
||||
}
|
||||
|
||||
export interface Beneficiary {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
userId?: string;
|
||||
createdBy?: string;
|
||||
createdAt?: string;
|
||||
name: string | null;
|
||||
category: string | null;
|
||||
targetCount?: number;
|
||||
reachedCount?: number;
|
||||
location: string | null;
|
||||
}
|
||||
|
||||
export interface CreateBeneficiaryRequest {
|
||||
projectId: number | string;
|
||||
name: string;
|
||||
category: string;
|
||||
location: string;
|
||||
targetCount: number;
|
||||
reachedCount: number;
|
||||
}
|
||||
|
||||
export interface UpdateBeneficiaryRequest {
|
||||
beneficiaryId: number | string;
|
||||
name: string;
|
||||
category: string;
|
||||
location: string;
|
||||
targetCount: number;
|
||||
reachedCount: number;
|
||||
}
|
||||
|
||||
export interface Outcome {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
beneficiaryId: number | string;
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
createdBy?: string;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
export interface CreateOutcomeRequest {
|
||||
beneficiaryId: number | string;
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface UpdateOutcomeRequest {
|
||||
outcomeId: number | string;
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface ChangeRequest {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
title: string | null;
|
||||
justification: string | null;
|
||||
revisedBudget?: number | null;
|
||||
revisedEndedAt?: string | null;
|
||||
status: ApprovalStatus;
|
||||
createdBy: string;
|
||||
approvedBy?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateChangeRequest {
|
||||
projectId: number | string;
|
||||
title: string;
|
||||
justification: string;
|
||||
revisedBudget: number;
|
||||
revisionDate: string;
|
||||
}
|
||||
|
||||
export interface UpdateChangeRequest {
|
||||
changeRequestId: number | string;
|
||||
title: string;
|
||||
justification: string;
|
||||
revisedBudget: number;
|
||||
status: ApprovalStatus;
|
||||
}
|
||||
|
||||
export interface ComplianceItem {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
title: string | null;
|
||||
requirements: string | null;
|
||||
status: ApprovalStatus;
|
||||
createdBy: string;
|
||||
verifiedBy?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateComplianceItemRequest {
|
||||
projectId: number | string;
|
||||
title: string;
|
||||
requirements: string;
|
||||
}
|
||||
|
||||
export interface UpdateComplianceItemRequest {
|
||||
complianceItemId: number | string;
|
||||
title: string;
|
||||
requirements: string;
|
||||
status: ApprovalStatus;
|
||||
}
|
||||
|
||||
export interface Issue {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
title: string | null;
|
||||
description: string | null;
|
||||
priority: Priority;
|
||||
status: ActivityStatus;
|
||||
createdBy: string;
|
||||
createdAt: string;
|
||||
assignedTo?: string | null;
|
||||
resolvedAt?: string | null;
|
||||
resolution?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateIssueRequest {
|
||||
projectId: number | string;
|
||||
title: string;
|
||||
description: string;
|
||||
priority: Priority;
|
||||
assignedTo: string;
|
||||
}
|
||||
|
||||
export interface UpdateIssueRequest {
|
||||
issueId: number | string;
|
||||
title: string;
|
||||
description: string;
|
||||
resolution: string;
|
||||
resolvedAt?: string | null;
|
||||
priority: Priority;
|
||||
status: ActivityStatus;
|
||||
assignedTo: string;
|
||||
}
|
||||
|
||||
export interface SiteVisit {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
visitedAt: string;
|
||||
inspectorName: string | null;
|
||||
findings: string | null;
|
||||
status: ApprovalStatus;
|
||||
createdBy: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface CreateSiteVisitRequest {
|
||||
projectId: number | string;
|
||||
inspectorName: string;
|
||||
findings: string;
|
||||
visitedAt: string;
|
||||
}
|
||||
|
||||
export interface UpdateSiteVisitRequest {
|
||||
siteVisitId: number | string;
|
||||
inspectorName: string;
|
||||
findings: string;
|
||||
status: ApprovalStatus;
|
||||
visitedAt: string;
|
||||
}
|
||||
|
||||
export interface Rule {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
programmeId: number | string;
|
||||
createdBy: string;
|
||||
updatedBy?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt?: string | null;
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
version?: number;
|
||||
status: ActivityStatus;
|
||||
}
|
||||
|
||||
export interface CreateRuleRequest {
|
||||
programmeId: number | string;
|
||||
userId: string;
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface UpdateRuleRequest {
|
||||
ruleId: number | string;
|
||||
userId: string;
|
||||
name: string;
|
||||
description: string;
|
||||
status: ActivityStatus;
|
||||
version: number;
|
||||
programmeId?: number | string;
|
||||
}
|
||||
|
||||
export interface Pagination {
|
||||
index?: number | string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface Notification {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
organisationId: number | string;
|
||||
recipient: string;
|
||||
platform: NotificationPlatform;
|
||||
status: NotificationStatus;
|
||||
subject: string | null;
|
||||
message: string | null;
|
||||
destination: string | null;
|
||||
createdAt: string;
|
||||
sentAt?: string | null;
|
||||
updatedAt?: string | null;
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
@@ -15,64 +15,23 @@ export interface FriendlyError {
|
||||
title: string;
|
||||
message: string;
|
||||
statusCode?: number;
|
||||
hasReturnObject: boolean;
|
||||
isProblemDetails: boolean;
|
||||
category: ErrorCategory;
|
||||
categoryLabel?: string;
|
||||
fieldErrors?: Array<{ field: string; message: string }>;
|
||||
errorsList?: string[];
|
||||
fieldErrors?: Array<{ field: string; message: string }>;
|
||||
technicalDetails?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts camelCase or PascalCase field names to human-readable titles.
|
||||
* e.g. "HashId" -> "Resource Identifier", "startDate" -> "Start Date"
|
||||
*/
|
||||
function humanizeFieldName(field: string): string {
|
||||
if (!field) return 'Field';
|
||||
|
||||
const customMappings: Record<string, string> = {
|
||||
hashid: 'Resource Identifier (HashId)',
|
||||
id: 'Record ID',
|
||||
sub: 'User Identity',
|
||||
orgid: 'Organisation',
|
||||
organisationid: 'Organisation',
|
||||
portfolioid: 'Portfolio',
|
||||
programmeid: 'Programme',
|
||||
projectid: 'Project',
|
||||
grantid: 'Award',
|
||||
awardid: 'Award',
|
||||
contractid: 'Contract',
|
||||
budgetid: 'Budget',
|
||||
disbursementid: 'Disbursement',
|
||||
indicatorid: 'Indicator',
|
||||
riskid: 'Risk',
|
||||
email: 'Email Address',
|
||||
name: 'Name',
|
||||
title: 'Title',
|
||||
code: 'Reference Code',
|
||||
startdate: 'Start Date',
|
||||
enddate: 'End Date',
|
||||
targetdate: 'Target Date',
|
||||
actualdate: 'Actual Date',
|
||||
amount: 'Amount',
|
||||
budgetamount: 'Budget Amount',
|
||||
targetvalue: 'Target Value',
|
||||
actualvalue: 'Actual Value',
|
||||
baselinevalue: 'Baseline Value',
|
||||
status: 'Status',
|
||||
governancestatus: 'Governance Status',
|
||||
contractstatus: 'Contract Status',
|
||||
disbursementstatus: 'Disbursement Status',
|
||||
};
|
||||
|
||||
const lower = field.toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||
if (customMappings[lower]) {
|
||||
return customMappings[lower];
|
||||
}
|
||||
|
||||
// Insert space before uppercase letters
|
||||
const spaced = field.replace(/([a-z])([A-Z])/g, '$1 $2');
|
||||
return spaced.charAt(0).toUpperCase() + spaced.slice(1);
|
||||
export interface ProblemDetailsResponse {
|
||||
type?: string | null;
|
||||
title?: string | null;
|
||||
status?: number | null;
|
||||
detail?: string | null;
|
||||
instance?: string | null;
|
||||
errors?: Record<string, string[] | string> | any;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,7 +39,6 @@ function humanizeFieldName(field: string): string {
|
||||
*/
|
||||
export function isRawHttpOutput(text: string): boolean {
|
||||
if (!text || typeof text !== 'string') return false;
|
||||
// If it has multiple header-like lines or standard HTTP request/response signatures
|
||||
const headerPatterns = [
|
||||
/^(?:accept|authorization|content-type|content-length|origin|referer|user-agent|sec-ch-ua|sec-fetch|x-forwarded|x-real-ip|host):/im,
|
||||
/(?:authorization:\s*bearer|content-type:\s*application\/)/i,
|
||||
@@ -114,10 +72,9 @@ export function sanitizeTechnicalDetails(text: string): string {
|
||||
/**
|
||||
* Cleans technical jargon, stack traces, and framework namespaces from text strings.
|
||||
*/
|
||||
function cleanTechnicalJargon(text: string): string {
|
||||
export function cleanTechnicalJargon(text: string): string {
|
||||
if (!text) return '';
|
||||
|
||||
// If text is a raw HTTP dump, do not return it as clean user text
|
||||
if (isRawHttpOutput(text)) {
|
||||
return '';
|
||||
}
|
||||
@@ -132,7 +89,7 @@ function cleanTechnicalJargon(text: string): string {
|
||||
.replace(/at\s+[a-zA-Z0-9_.]+\s*\(.*?\)/g, '')
|
||||
.trim();
|
||||
|
||||
// In this system, ProblemDetails title is always "Error" — ignore trivial or generic "Error" strings
|
||||
// In this system, ProblemDetails title is typically "Error" — ignore trivial or generic "Error" strings
|
||||
if (cleaned.length < 2 || cleaned === '[object Object]' || cleaned.toLowerCase() === 'error') {
|
||||
return '';
|
||||
}
|
||||
@@ -141,7 +98,42 @@ function cleanTechnicalJargon(text: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a response object conforms to RFC 7807 / RFC 9457 ProblemDetails.
|
||||
* Safely inspects whether an error contains a valid response body object.
|
||||
* Note: not all error responses will have a return object, so this method explicitly checks.
|
||||
*/
|
||||
export function inspectErrorResponseObject(error: unknown): ProblemDetailsResponse | null {
|
||||
if (!error) return null;
|
||||
|
||||
// 1. Inspect Axios error or error with response structure
|
||||
const anyErr = error as any;
|
||||
const data = anyErr?.response?.data;
|
||||
if (data && typeof data === 'object') {
|
||||
return data as ProblemDetailsResponse;
|
||||
}
|
||||
// Check if response body is a JSON string
|
||||
if (typeof data === 'string' && data.trim().startsWith('{')) {
|
||||
try {
|
||||
const parsed = JSON.parse(data.trim());
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
return parsed as ProblemDetailsResponse;
|
||||
}
|
||||
} catch {
|
||||
// Not a JSON object
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Direct object inspection (e.g. if response.data was passed directly)
|
||||
if (typeof error === 'object' && error !== null) {
|
||||
if ('detail' in anyErr || 'status' in anyErr || 'title' in anyErr || 'type' in anyErr) {
|
||||
return anyErr as ProblemDetailsResponse;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a response object conforms to RFC 7807 / RFC 9110 ProblemDetails.
|
||||
*/
|
||||
export function isProblemDetailsObject(data: any): data is ProblemDetails {
|
||||
if (!data || typeof data !== 'object') return false;
|
||||
@@ -151,11 +143,35 @@ export function isProblemDetailsObject(data: any): data is ProblemDetails {
|
||||
'status' in data ||
|
||||
'type' in data ||
|
||||
'errors' in data ||
|
||||
'Errors' in data ||
|
||||
'errorList' in data
|
||||
'Errors' in data
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a comma-delimited error list from the `detail` property.
|
||||
* e.g. "Failed to update organisation" -> ["Failed to update organisation"]
|
||||
* e.g. "Invalid organisation name, Budget exceeds ceiling, Target date cannot be in past"
|
||||
* -> ["Invalid organisation name", "Budget exceeds ceiling", "Target date cannot be in past"]
|
||||
*/
|
||||
export function parseCommaDelimitedErrors(detail?: string | null): string[] {
|
||||
if (!detail || typeof detail !== 'string') return [];
|
||||
const trimmed = detail.trim();
|
||||
if (!trimmed) return [];
|
||||
|
||||
// Split by comma
|
||||
const rawParts = trimmed.split(',');
|
||||
const errors: string[] = [];
|
||||
|
||||
for (const part of rawParts) {
|
||||
const cleaned = cleanTechnicalJargon(part.trim());
|
||||
if (cleaned && cleaned.length > 0) {
|
||||
errors.push(cleaned);
|
||||
}
|
||||
}
|
||||
|
||||
return errors.length > 0 ? errors : [trimmed];
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects whether the user action context was an entity creation or an update.
|
||||
*/
|
||||
@@ -204,81 +220,46 @@ function detectOperationIntent(
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts and formats human-friendly error guidance from any error,
|
||||
* accessing the ProblemDetails `errors` array directly to display the error.
|
||||
* In this system the title field is always "Error", so no generic error testing is performed.
|
||||
* Comprehensive common error handling function across the application.
|
||||
*
|
||||
* Handles standard RFC 9110 / RFC 7807 error responses:
|
||||
* {
|
||||
* "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
|
||||
* "title": "Error",
|
||||
* "status": 400,
|
||||
* "detail": "Failed to update organisation"
|
||||
* }
|
||||
*
|
||||
* - Parses comma-delimited error list in the `detail` property.
|
||||
* - Handles authentication (401) and forbidden (403) specifically.
|
||||
* - Explicitly inspects whether a return object exists, handling responses without return objects gracefully.
|
||||
*/
|
||||
export function parseFriendlyError(
|
||||
error: unknown,
|
||||
fallbackActionTitle = 'Action Failed'
|
||||
): FriendlyError {
|
||||
let statusCode: number | undefined;
|
||||
let rawTitle: string | undefined;
|
||||
let rawDetail: string | undefined;
|
||||
let rawErrors: any = undefined;
|
||||
let isProblemDetails = false;
|
||||
let rawResponseData: any = null;
|
||||
let technicalSummary = '';
|
||||
let httpMethod = '';
|
||||
let requestUrl = '';
|
||||
|
||||
// 1. Inspect Axios error structure
|
||||
// 1. Inspect error metadata if available
|
||||
const anyErr = error as any;
|
||||
if (axios.isAxiosError(error)) {
|
||||
const axiosErr = error as AxiosError<any>;
|
||||
statusCode = axiosErr.response?.status;
|
||||
rawResponseData = axiosErr.response?.data;
|
||||
httpMethod = axiosErr.config?.method?.toUpperCase() || '';
|
||||
requestUrl = axiosErr.config?.url || '';
|
||||
technicalSummary = `${httpMethod || 'HTTP'} ${requestUrl} -> ${statusCode || axiosErr.code || 'ERR'}`;
|
||||
|
||||
if (rawResponseData && typeof rawResponseData === 'object') {
|
||||
const dataObj = rawResponseData as any;
|
||||
if (isProblemDetailsObject(dataObj)) {
|
||||
isProblemDetails = true;
|
||||
rawTitle = dataObj.title || dataObj.Title || undefined;
|
||||
rawDetail = dataObj.detail || dataObj.Detail || undefined;
|
||||
statusCode = dataObj.status || dataObj.Status || statusCode;
|
||||
rawErrors = dataObj.errors ?? dataObj.Errors ?? dataObj.errorList ?? dataObj.ErrorList;
|
||||
} else if (dataObj.message || dataObj.error || dataObj.errors || dataObj.Errors) {
|
||||
rawDetail = dataObj.message || dataObj.error;
|
||||
rawErrors = dataObj.errors ?? dataObj.Errors;
|
||||
} else if (Array.isArray(dataObj)) {
|
||||
rawErrors = dataObj;
|
||||
}
|
||||
} else if (typeof rawResponseData === 'string') {
|
||||
if (isRawHttpOutput(rawResponseData)) {
|
||||
technicalSummary = sanitizeTechnicalDetails(rawResponseData);
|
||||
rawDetail = undefined;
|
||||
} else {
|
||||
// Check if response data is stringified JSON containing ProblemDetails
|
||||
try {
|
||||
const parsed = JSON.parse(rawResponseData) as any;
|
||||
if (isProblemDetailsObject(parsed)) {
|
||||
isProblemDetails = true;
|
||||
rawTitle = parsed.title || parsed.Title || undefined;
|
||||
rawDetail = parsed.detail || parsed.Detail || undefined;
|
||||
statusCode = parsed.status || parsed.Status || statusCode;
|
||||
rawErrors = parsed.errors ?? parsed.Errors ?? parsed.errorList ?? parsed.ErrorList;
|
||||
} else if (Array.isArray(parsed)) {
|
||||
rawErrors = parsed;
|
||||
} else {
|
||||
rawDetail = cleanTechnicalJargon(rawResponseData);
|
||||
}
|
||||
} catch {
|
||||
if (!rawResponseData.includes('<html')) {
|
||||
rawDetail = cleanTechnicalJargon(rawResponseData);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Network disconnection or request timeout (no response received)
|
||||
// Network disconnection or request timeout (no response received at all)
|
||||
if (!axiosErr.response) {
|
||||
if (axiosErr.code === 'ECONNABORTED' || axiosErr.message.includes('timeout')) {
|
||||
return {
|
||||
title: 'Request Timed Out',
|
||||
message: 'The server took too long to respond. Please check your network and try again.',
|
||||
message: 'The server took too long to respond. Please check your network connection and try again.',
|
||||
statusCode: 408,
|
||||
hasReturnObject: false,
|
||||
isProblemDetails: false,
|
||||
category: 'server',
|
||||
categoryLabel: 'Timeout',
|
||||
@@ -289,244 +270,247 @@ export function parseFriendlyError(
|
||||
title: 'Connection Unavailable',
|
||||
message: 'Unable to reach the system service. Please verify your internet connection or try again in a few moments.',
|
||||
statusCode: 0,
|
||||
hasReturnObject: false,
|
||||
isProblemDetails: false,
|
||||
category: 'server',
|
||||
categoryLabel: 'Network',
|
||||
technicalDetails: technicalSummary || axiosErr.message,
|
||||
};
|
||||
}
|
||||
} else if (error && typeof error === 'object') {
|
||||
// 2. Direct ProblemDetails object or custom error object
|
||||
const obj = error as any;
|
||||
if (isProblemDetailsObject(obj)) {
|
||||
isProblemDetails = true;
|
||||
rawTitle = obj.title || obj.Title || undefined;
|
||||
rawDetail = obj.detail || obj.Detail || undefined;
|
||||
statusCode = obj.status || obj.Status || undefined;
|
||||
rawErrors = obj.errors ?? obj.Errors ?? obj.errorList ?? obj.ErrorList;
|
||||
} else if (obj.response?.data && isProblemDetailsObject(obj.response.data)) {
|
||||
isProblemDetails = true;
|
||||
const respData = obj.response.data as any;
|
||||
rawTitle = respData.title || respData.Title || undefined;
|
||||
rawDetail = respData.detail || respData.Detail || undefined;
|
||||
statusCode = obj.response.status || respData.status || respData.Status;
|
||||
rawErrors = respData.errors ?? respData.Errors ?? respData.errorList ?? respData.ErrorList;
|
||||
} else if (Array.isArray(obj)) {
|
||||
rawErrors = obj;
|
||||
} else if (obj.message) {
|
||||
rawDetail = obj.message;
|
||||
const statusMatch = obj.message.match(/status code (\d{3})/i);
|
||||
if (statusMatch) {
|
||||
statusCode = parseInt(statusMatch[1], 10);
|
||||
}
|
||||
} else if (anyErr && typeof anyErr === 'object') {
|
||||
statusCode = anyErr.response?.status ?? anyErr.status;
|
||||
httpMethod = anyErr.config?.method?.toUpperCase() || '';
|
||||
requestUrl = anyErr.config?.url || '';
|
||||
if (statusCode) {
|
||||
technicalSummary = `HTTP ${statusCode}`;
|
||||
}
|
||||
} else if (typeof error === 'string') {
|
||||
// 3. String error
|
||||
const statusMatch = error.match(/status code (\d{3})/i);
|
||||
if (statusMatch) {
|
||||
statusCode = parseInt(statusMatch[1], 10);
|
||||
}
|
||||
rawDetail = cleanTechnicalJargon(error);
|
||||
}
|
||||
|
||||
// Extract errors list directly from ProblemDetails errors array / dictionary
|
||||
const fieldErrors: Array<{ field: string; message: string }> = [];
|
||||
const errorsList: string[] = [];
|
||||
// 2. Inspect for returned response object
|
||||
const returnObject = inspectErrorResponseObject(error);
|
||||
const hasReturnObject = returnObject !== null;
|
||||
|
||||
if (rawErrors) {
|
||||
if (Array.isArray(rawErrors)) {
|
||||
rawErrors.forEach((item) => {
|
||||
if (typeof item === 'string' && item.trim()) {
|
||||
const cleaned = cleanTechnicalJargon(item.trim());
|
||||
if (cleaned) errorsList.push(cleaned);
|
||||
} else if (item && typeof item === 'object') {
|
||||
const msg =
|
||||
item.message ||
|
||||
item.errorMessage ||
|
||||
item.detail ||
|
||||
item.error ||
|
||||
item.description ||
|
||||
JSON.stringify(item);
|
||||
const cleaned = cleanTechnicalJargon(String(msg));
|
||||
if (cleaned) errorsList.push(cleaned);
|
||||
}
|
||||
});
|
||||
} else if (typeof rawErrors === 'object') {
|
||||
for (const [key, val] of Object.entries(rawErrors)) {
|
||||
const isNumericKey = /^\d+$/.test(key);
|
||||
const fieldTitle = isNumericKey ? '' : humanizeFieldName(key);
|
||||
if (Array.isArray(val)) {
|
||||
val.forEach((msg) => {
|
||||
if (msg) {
|
||||
const cleaned = cleanTechnicalJargon(String(msg));
|
||||
if (cleaned) {
|
||||
if (fieldTitle && !cleaned.toLowerCase().includes(fieldTitle.toLowerCase())) {
|
||||
fieldErrors.push({ field: fieldTitle, message: cleaned });
|
||||
errorsList.push(`${fieldTitle}: ${cleaned}`);
|
||||
} else {
|
||||
errorsList.push(cleaned);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (typeof val === 'string' && val.trim()) {
|
||||
const cleaned = cleanTechnicalJargon(val.trim());
|
||||
if (cleaned) {
|
||||
if (fieldTitle && !cleaned.toLowerCase().includes(fieldTitle.toLowerCase())) {
|
||||
fieldErrors.push({ field: fieldTitle, message: cleaned });
|
||||
errorsList.push(`${fieldTitle}: ${cleaned}`);
|
||||
} else {
|
||||
errorsList.push(cleaned);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (typeof rawErrors === 'string' && rawErrors.trim()) {
|
||||
const cleaned = cleanTechnicalJargon(rawErrors.trim());
|
||||
if (cleaned) errorsList.push(cleaned);
|
||||
if (returnObject) {
|
||||
if (returnObject.status && typeof returnObject.status === 'number') {
|
||||
statusCode = returnObject.status;
|
||||
}
|
||||
}
|
||||
|
||||
// Detect operation intent (creation, update, deletion, general)
|
||||
const operationIntent = detectOperationIntent(httpMethod, fallbackActionTitle, requestUrl);
|
||||
|
||||
let friendlyTitle = fallbackActionTitle;
|
||||
let friendlyMessage = '';
|
||||
let category: ErrorCategory = 'general';
|
||||
let categoryLabel: string | undefined = undefined;
|
||||
// 3. Special handling for Auth (401) and Forbid (403)
|
||||
if (statusCode === 401) {
|
||||
const rawDetail = returnObject?.detail || (error as any)?.message;
|
||||
const cleanDetail = cleanTechnicalJargon(rawDetail || '');
|
||||
return {
|
||||
title: 'Authentication Required',
|
||||
message: cleanDetail || 'Your authentication session has expired or is unauthorized (HTTP 401). Please sign in again.',
|
||||
statusCode: 401,
|
||||
hasReturnObject,
|
||||
isProblemDetails: hasReturnObject,
|
||||
category: 'security',
|
||||
categoryLabel: 'Unauthorized',
|
||||
technicalDetails: technicalSummary ? sanitizeTechnicalDetails(technicalSummary) : 'HTTP 401 Unauthorized',
|
||||
};
|
||||
}
|
||||
|
||||
const cleanDetail = cleanTechnicalJargon(rawDetail || '');
|
||||
if (statusCode === 403) {
|
||||
const rawDetail = returnObject?.detail || (error as any)?.message;
|
||||
const detailErrors = parseCommaDelimitedErrors(rawDetail);
|
||||
const friendlyMessage =
|
||||
detailErrors.length > 0
|
||||
? detailErrors.length === 1
|
||||
? detailErrors[0]
|
||||
: detailErrors.map((err) => `• ${err}`).join('\n')
|
||||
: 'You do not have permission to access this resource or perform this action (HTTP 403).';
|
||||
|
||||
// In this system, ProblemDetails allows access to the errors array to display the error directly if available
|
||||
if (errorsList.length > 0) {
|
||||
category = 'validation';
|
||||
categoryLabel =
|
||||
operationIntent === 'creation'
|
||||
? 'Validation'
|
||||
: operationIntent === 'update'
|
||||
? 'Validation'
|
||||
: 'Validation';
|
||||
return {
|
||||
title: fallbackActionTitle !== 'Action Failed' ? fallbackActionTitle : 'Access Forbidden',
|
||||
message: friendlyMessage,
|
||||
statusCode: 403,
|
||||
hasReturnObject,
|
||||
isProblemDetails: hasReturnObject,
|
||||
category: 'security',
|
||||
categoryLabel: 'Forbidden',
|
||||
errorsList: detailErrors.length > 0 ? detailErrors : undefined,
|
||||
technicalDetails: technicalSummary ? sanitizeTechnicalDetails(technicalSummary) : 'HTTP 403 Forbidden',
|
||||
};
|
||||
}
|
||||
|
||||
// Display the error directly
|
||||
if (errorsList.length === 1) {
|
||||
friendlyMessage = errorsList[0];
|
||||
} else {
|
||||
friendlyMessage = errorsList.map((err) => `• ${err}`).join('\n');
|
||||
// 4. Case A: Response has a valid return object (e.g. RFC 9110 ProblemDetails)
|
||||
if (hasReturnObject && returnObject) {
|
||||
const rawDetail =
|
||||
returnObject.detail ??
|
||||
returnObject.Detail ??
|
||||
returnObject.message ??
|
||||
returnObject.error;
|
||||
|
||||
// Parse comma-delimited errors from detail property
|
||||
const errorsList = parseCommaDelimitedErrors(rawDetail);
|
||||
|
||||
// If detail was empty, check if errors array/dictionary exists
|
||||
if (errorsList.length === 0 && returnObject.errors) {
|
||||
if (Array.isArray(returnObject.errors)) {
|
||||
returnObject.errors.forEach((e: any) => {
|
||||
const cleaned = cleanTechnicalJargon(typeof e === 'string' ? e : e?.message || JSON.stringify(e));
|
||||
if (cleaned) errorsList.push(cleaned);
|
||||
});
|
||||
} else if (typeof returnObject.errors === 'object') {
|
||||
for (const [key, val] of Object.entries(returnObject.errors)) {
|
||||
if (Array.isArray(val)) {
|
||||
val.forEach((m) => {
|
||||
const cleaned = cleanTechnicalJargon(String(m));
|
||||
if (cleaned) errorsList.push(`${key}: ${cleaned}`);
|
||||
});
|
||||
} else if (typeof val === 'string' && val.trim()) {
|
||||
const cleaned = cleanTechnicalJargon(val);
|
||||
if (cleaned) errorsList.push(`${key}: ${cleaned}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If detail provides extra non-duplicate context, include it
|
||||
if (cleanDetail && !errorsList.some((e) => e.toLowerCase() === cleanDetail.toLowerCase())) {
|
||||
friendlyMessage = `${cleanDetail}\n\n${friendlyMessage}`;
|
||||
}
|
||||
} else if (cleanDetail) {
|
||||
// If no errors array, but detail is available, display detail directly
|
||||
friendlyMessage = cleanDetail;
|
||||
if (statusCode === 403) {
|
||||
category = 'security';
|
||||
categoryLabel = 'Access Denied';
|
||||
let category: ErrorCategory = 'general';
|
||||
let categoryLabel: string = 'Error';
|
||||
|
||||
if (statusCode === 400) {
|
||||
if (operationIntent === 'creation') {
|
||||
category = 'creation';
|
||||
categoryLabel = 'Creation Error';
|
||||
} else if (operationIntent === 'update') {
|
||||
category = 'update';
|
||||
categoryLabel = 'Update Error';
|
||||
} else {
|
||||
category = 'validation';
|
||||
categoryLabel = 'Validation Error';
|
||||
}
|
||||
} else if (statusCode === 404) {
|
||||
category = 'notFound';
|
||||
categoryLabel = 'Not Found';
|
||||
} else if (statusCode === 409) {
|
||||
category = 'conflict';
|
||||
categoryLabel = 'Conflict';
|
||||
} else if (statusCode === 422) {
|
||||
category = 'validation';
|
||||
categoryLabel = 'Validation Error';
|
||||
} else if (statusCode && statusCode >= 500) {
|
||||
category = 'server';
|
||||
categoryLabel = 'Service Issue';
|
||||
categoryLabel = 'Server Error';
|
||||
}
|
||||
} else {
|
||||
// Fallback status-specific messaging when neither errors array nor detail is available
|
||||
switch (statusCode) {
|
||||
case 403:
|
||||
category = 'security';
|
||||
categoryLabel = 'Invalid Identifier / Forbid';
|
||||
friendlyTitle = 'Access Not Permitted or Invalid Identifier';
|
||||
friendlyMessage =
|
||||
'The reference identifier (hash ID) is invalid, expired, or you do not have permission to access this item. Please verify your selection or contact your system administrator.';
|
||||
break;
|
||||
|
||||
case 404:
|
||||
category = 'notFound';
|
||||
categoryLabel = 'Record Not Found';
|
||||
friendlyTitle = 'Record Not Found';
|
||||
friendlyMessage =
|
||||
'The requested record could not be found. It may have been archived, removed, or the link is outdated.';
|
||||
break;
|
||||
|
||||
case 400:
|
||||
if (operationIntent === 'creation') {
|
||||
category = 'creation';
|
||||
categoryLabel = 'Creation Error';
|
||||
friendlyMessage =
|
||||
'The new record could not be created. Please review the input parameters and prerequisites.';
|
||||
} else if (operationIntent === 'update') {
|
||||
category = 'update';
|
||||
categoryLabel = 'Update Error';
|
||||
friendlyMessage =
|
||||
'The record could not be updated. It may be locked or the requested status transition is not permitted.';
|
||||
} else {
|
||||
category = 'general';
|
||||
categoryLabel = 'Request Error';
|
||||
friendlyMessage =
|
||||
'The request could not be processed due to invalid parameters or business rule requirements.';
|
||||
}
|
||||
break;
|
||||
|
||||
case 409:
|
||||
category = 'conflict';
|
||||
categoryLabel = 'Conflict';
|
||||
friendlyTitle = 'Update Conflict';
|
||||
friendlyMessage =
|
||||
'This action conflicts with the current status of the record. Please refresh the page and try again.';
|
||||
break;
|
||||
|
||||
case 422:
|
||||
category = 'validation';
|
||||
categoryLabel = 'Incomplete Data';
|
||||
friendlyMessage =
|
||||
'The submitted information could not be processed. Please verify that all required fields are complete.';
|
||||
break;
|
||||
|
||||
case 429:
|
||||
category = 'server';
|
||||
categoryLabel = 'Rate Limit';
|
||||
friendlyTitle = 'System Busy';
|
||||
friendlyMessage =
|
||||
'The system received too many requests in a short time. Please pause for a moment before trying again.';
|
||||
break;
|
||||
|
||||
case 500:
|
||||
case 502:
|
||||
case 503:
|
||||
case 504:
|
||||
category = 'server';
|
||||
categoryLabel = 'Service Issue';
|
||||
friendlyTitle = 'Service Temporarily Unavailable';
|
||||
friendlyMessage =
|
||||
'The central service encountered an unexpected issue while processing your request. Please try again in a few moments.';
|
||||
break;
|
||||
|
||||
default:
|
||||
friendlyMessage =
|
||||
'An unexpected issue occurred while processing this request. Please try again or contact support.';
|
||||
break;
|
||||
// Format display message from errorsList
|
||||
let friendlyMessage = '';
|
||||
if (errorsList.length > 1) {
|
||||
friendlyMessage = errorsList.map((err) => `• ${err}`).join('\n');
|
||||
} else if (errorsList.length === 1) {
|
||||
friendlyMessage = errorsList[0];
|
||||
} else {
|
||||
// Fallback message if detail was empty string
|
||||
friendlyMessage =
|
||||
operationIntent === 'creation'
|
||||
? 'Failed to create record. Please verify the submitted parameters.'
|
||||
: operationIntent === 'update'
|
||||
? 'Failed to update record. Please verify the submitted parameters.'
|
||||
: 'Request could not be processed due to invalid parameters.';
|
||||
}
|
||||
|
||||
// Use contextual action title (or returnObject.title if not "Error")
|
||||
let displayTitle = fallbackActionTitle;
|
||||
if (displayTitle === 'Action Failed' && returnObject.title && returnObject.title.toLowerCase() !== 'error') {
|
||||
displayTitle = returnObject.title;
|
||||
}
|
||||
|
||||
return {
|
||||
title: displayTitle,
|
||||
message: friendlyMessage,
|
||||
statusCode,
|
||||
hasReturnObject: true,
|
||||
isProblemDetails: true,
|
||||
category,
|
||||
categoryLabel,
|
||||
errorsList: errorsList.length > 0 ? errorsList : undefined,
|
||||
technicalDetails: technicalSummary ? sanitizeTechnicalDetails(technicalSummary) : (statusCode ? `HTTP Status ${statusCode}` : undefined),
|
||||
};
|
||||
}
|
||||
|
||||
// Ensure title is friendly and not an uncaught technical string
|
||||
if (friendlyTitle.includes('AxiosError') || friendlyTitle.includes('status code')) {
|
||||
friendlyTitle = fallbackActionTitle;
|
||||
// 5. Case B: Error response DOES NOT have a return object (e.g. empty response, network, non-JSON 500/502/503)
|
||||
let title = fallbackActionTitle || 'Action Failed';
|
||||
let message = '';
|
||||
let category: ErrorCategory = 'general';
|
||||
let categoryLabel: string = 'Error';
|
||||
|
||||
switch (statusCode) {
|
||||
case 400:
|
||||
category = operationIntent === 'creation' ? 'creation' : operationIntent === 'update' ? 'update' : 'validation';
|
||||
categoryLabel = 'Bad Request';
|
||||
message =
|
||||
operationIntent === 'creation'
|
||||
? 'The new record could not be created. Please review the submitted parameters.'
|
||||
: operationIntent === 'update'
|
||||
? 'The record could not be updated. Please verify the submitted parameters.'
|
||||
: 'The request could not be processed due to invalid parameters.';
|
||||
break;
|
||||
|
||||
case 404:
|
||||
title = 'Record Not Found';
|
||||
category = 'notFound';
|
||||
categoryLabel = 'Not Found';
|
||||
message = 'The requested resource could not be found (HTTP 404). It may have been archived, removed, or the link is outdated.';
|
||||
break;
|
||||
|
||||
case 409:
|
||||
title = 'Resource Conflict';
|
||||
category = 'conflict';
|
||||
categoryLabel = 'Conflict';
|
||||
message = 'This operation conflicts with the current status of the resource (HTTP 409). Please refresh the page and try again.';
|
||||
break;
|
||||
|
||||
case 422:
|
||||
category = 'validation';
|
||||
categoryLabel = 'Incomplete Data';
|
||||
message = 'The submitted information could not be processed by the server (HTTP 422). Please verify all required fields.';
|
||||
break;
|
||||
|
||||
case 429:
|
||||
title = 'Rate Limit Exceeded';
|
||||
category = 'server';
|
||||
categoryLabel = 'Rate Limit';
|
||||
message = 'The system received too many requests in a short time (HTTP 429). Please pause for a moment before trying again.';
|
||||
break;
|
||||
|
||||
case 500:
|
||||
case 502:
|
||||
case 503:
|
||||
case 504:
|
||||
title = 'Service Temporarily Unavailable';
|
||||
category = 'server';
|
||||
categoryLabel = 'Service Issue';
|
||||
message = `The server encountered an error while processing your request (HTTP ${statusCode}). Please try again in a few moments.`;
|
||||
break;
|
||||
|
||||
default:
|
||||
if (typeof error === 'string' && error.trim()) {
|
||||
message = cleanTechnicalJargon(error);
|
||||
} else if (error instanceof Error && error.message) {
|
||||
message = cleanTechnicalJargon(error.message);
|
||||
}
|
||||
if (!message) {
|
||||
message = statusCode
|
||||
? `An unexpected server issue occurred (HTTP ${statusCode}). Please try again or contact support.`
|
||||
: 'An unexpected issue occurred while processing this request. Please try again.';
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return {
|
||||
title: friendlyTitle,
|
||||
message: friendlyMessage,
|
||||
title,
|
||||
message,
|
||||
statusCode,
|
||||
isProblemDetails,
|
||||
hasReturnObject: false,
|
||||
isProblemDetails: false,
|
||||
category,
|
||||
categoryLabel,
|
||||
fieldErrors: fieldErrors.length > 0 ? fieldErrors : undefined,
|
||||
errorsList: errorsList.length > 0 ? errorsList : undefined,
|
||||
technicalDetails: technicalSummary ? sanitizeTechnicalDetails(technicalSummary) : (statusCode ? `HTTP Status ${statusCode}` : undefined),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user