362 lines
11 KiB
TypeScript
362 lines
11 KiB
TypeScript
import { useState, useEffect, useCallback } from 'react';
|
|
import { useApiRequest } from './useApi';
|
|
import { getUserDataCache } from '../utils/userCache';
|
|
import api from '../api';
|
|
import { usePermissions, type UserPermissions } from './usePermissions';
|
|
import {
|
|
fetchContracts as fetchContractsApi,
|
|
fetchContractById as fetchContractByIdApi,
|
|
createContract as createContractApi,
|
|
updateContract as updateContractApi,
|
|
deleteContract as deleteContractApi,
|
|
type TrusteeContract,
|
|
type AttributeDefinition,
|
|
type PaginationParams
|
|
} from '../api/trusteeApi';
|
|
|
|
// Re-export types
|
|
export type { TrusteeContract, AttributeDefinition, PaginationParams };
|
|
|
|
// Contracts list hook
|
|
export function useTrusteeContracts() {
|
|
const [contracts, setContracts] = useState<TrusteeContract[]>([]);
|
|
const [attributes, setAttributes] = useState<AttributeDefinition[]>([]);
|
|
const [permissions, setPermissions] = useState<UserPermissions | null>(null);
|
|
const [pagination, setPagination] = useState<{
|
|
currentPage: number;
|
|
pageSize: number;
|
|
totalItems: number;
|
|
totalPages: number;
|
|
} | null>(null);
|
|
const { request, isLoading: loading, error } = useApiRequest<null, TrusteeContract[]>();
|
|
const { checkPermission } = usePermissions();
|
|
|
|
// Fetch attributes from backend
|
|
const fetchAttributes = useCallback(async () => {
|
|
try {
|
|
const response = await api.get('/api/attributes/TrusteeContract');
|
|
|
|
let attrs: AttributeDefinition[] = [];
|
|
if (response.data?.attributes && Array.isArray(response.data.attributes)) {
|
|
attrs = response.data.attributes;
|
|
} else if (Array.isArray(response.data)) {
|
|
attrs = response.data;
|
|
} else if (response.data && typeof response.data === 'object') {
|
|
const keys = Object.keys(response.data);
|
|
for (const key of keys) {
|
|
if (Array.isArray(response.data[key])) {
|
|
attrs = response.data[key];
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
setAttributes(attrs);
|
|
return attrs;
|
|
} catch (error: any) {
|
|
console.error('Error fetching attributes:', error);
|
|
setAttributes([]);
|
|
return [];
|
|
}
|
|
}, []);
|
|
|
|
// Fetch permissions from backend
|
|
const fetchPermissions = useCallback(async () => {
|
|
try {
|
|
const perms = await checkPermission('DATA', 'trustee.contract');
|
|
setPermissions(perms);
|
|
return perms;
|
|
} catch (error: any) {
|
|
console.error('Error fetching permissions:', error);
|
|
const defaultPerms: UserPermissions = {
|
|
view: false,
|
|
read: 'n',
|
|
create: 'n',
|
|
update: 'n',
|
|
delete: 'n',
|
|
};
|
|
setPermissions(defaultPerms);
|
|
return defaultPerms;
|
|
}
|
|
}, [checkPermission]);
|
|
|
|
const fetchContracts = useCallback(async (params?: PaginationParams) => {
|
|
try {
|
|
const data = await fetchContractsApi(request, params);
|
|
|
|
if (data && typeof data === 'object' && 'items' in data) {
|
|
const items = Array.isArray(data.items) ? data.items : [];
|
|
setContracts(items);
|
|
if (data.pagination) {
|
|
setPagination(data.pagination);
|
|
}
|
|
} else {
|
|
const items = Array.isArray(data) ? data : [];
|
|
setContracts(items);
|
|
setPagination(null);
|
|
}
|
|
} catch (error: any) {
|
|
setContracts([]);
|
|
setPagination(null);
|
|
}
|
|
}, [request]);
|
|
|
|
// Optimistically remove a contract
|
|
const removeOptimistically = (contractId: string) => {
|
|
setContracts(prevContracts => prevContracts.filter(contract => contract.id !== contractId));
|
|
};
|
|
|
|
// Optimistically update a contract
|
|
const updateOptimistically = (contractId: string, updateData: Partial<TrusteeContract>) => {
|
|
setContracts(prevContracts =>
|
|
prevContracts.map(contract =>
|
|
contract.id === contractId
|
|
? { ...contract, ...updateData }
|
|
: contract
|
|
)
|
|
);
|
|
};
|
|
|
|
// Fetch a single contract by ID
|
|
const fetchContractById = useCallback(async (contractId: string): Promise<TrusteeContract | null> => {
|
|
return await fetchContractByIdApi(request, contractId);
|
|
}, [request]);
|
|
|
|
// Generate edit fields from attributes dynamically
|
|
const generateEditFieldsFromAttributes = useCallback((): Array<{
|
|
key: string;
|
|
label: string;
|
|
type: 'string' | 'boolean' | 'email' | 'textarea' | 'date' | 'enum' | 'multiselect' | 'readonly';
|
|
editable?: boolean;
|
|
required?: boolean;
|
|
validator?: (value: any) => string | null;
|
|
options?: Array<{ value: string | number; label: string }>;
|
|
optionsReference?: string;
|
|
readonlyCondition?: (formData: any) => boolean;
|
|
}> => {
|
|
if (!attributes || attributes.length === 0) {
|
|
return [];
|
|
}
|
|
|
|
const editableFields = attributes
|
|
.filter(attr => {
|
|
if (attr.readonly === true || attr.editable === false) {
|
|
return false;
|
|
}
|
|
const nonEditableFields = ['id', 'mandate', '_createdBy', '_modifiedBy', '_createdAt', '_modifiedAt'];
|
|
return !nonEditableFields.includes(attr.name);
|
|
})
|
|
.map(attr => {
|
|
let fieldType: 'string' | 'boolean' | 'email' | 'textarea' | 'date' | 'enum' | 'multiselect' | 'readonly' = 'string';
|
|
let options: Array<{ value: string | number; label: string }> | undefined = undefined;
|
|
let optionsReference: string | undefined = undefined;
|
|
let readonlyCondition: ((formData: any) => boolean) | undefined = undefined;
|
|
|
|
if (attr.type === 'checkbox') {
|
|
fieldType = 'boolean';
|
|
} else if (attr.type === 'email') {
|
|
fieldType = 'email';
|
|
} else if (attr.type === 'date') {
|
|
fieldType = 'date';
|
|
} else if (attr.type === 'select') {
|
|
fieldType = 'enum';
|
|
if (Array.isArray(attr.options)) {
|
|
options = attr.options.map(opt => {
|
|
const labelValue = typeof opt.label === 'string'
|
|
? opt.label
|
|
: opt.label?.en || opt.label?.[Object.keys(opt.label)[0]] || String(opt.value);
|
|
return {
|
|
value: opt.value,
|
|
label: labelValue
|
|
};
|
|
});
|
|
} else if (typeof attr.options === 'string') {
|
|
optionsReference = attr.options;
|
|
}
|
|
} else if (attr.type === 'textarea') {
|
|
fieldType = 'textarea';
|
|
}
|
|
|
|
// IMPORTANT: organisationId is immutable after creation
|
|
// It's readonly when id is present (non-blank)
|
|
if (attr.name === 'organisationId') {
|
|
readonlyCondition = (formData: any) => {
|
|
return formData && formData.id && formData.id !== '';
|
|
};
|
|
}
|
|
|
|
let required = attr.required === true;
|
|
let validator: ((value: any) => string | null) | undefined = undefined;
|
|
|
|
if (attr.name === 'organisationId') {
|
|
required = true;
|
|
validator = (value: any) => {
|
|
if (!value || (typeof value === 'string' && value.trim() === '')) {
|
|
return 'Organisation is required';
|
|
}
|
|
return null;
|
|
};
|
|
} else if (attr.name === 'label') {
|
|
required = true;
|
|
validator = (value: string) => {
|
|
if (!value || value.trim() === '') {
|
|
return 'Label cannot be empty';
|
|
}
|
|
return null;
|
|
};
|
|
}
|
|
|
|
return {
|
|
key: attr.name,
|
|
label: attr.label || attr.name,
|
|
type: fieldType,
|
|
editable: attr.editable !== false && attr.readonly !== true,
|
|
required,
|
|
validator,
|
|
options,
|
|
optionsReference,
|
|
readonlyCondition
|
|
};
|
|
});
|
|
|
|
return editableFields;
|
|
}, [attributes]);
|
|
|
|
// Ensure attributes are loaded
|
|
const ensureAttributesLoaded = useCallback(async () => {
|
|
if (attributes && attributes.length > 0) {
|
|
return attributes;
|
|
}
|
|
const fetchedAttributes = await fetchAttributes();
|
|
return fetchedAttributes;
|
|
}, [attributes, fetchAttributes]);
|
|
|
|
// Fetch attributes and permissions on mount
|
|
useEffect(() => {
|
|
fetchAttributes();
|
|
fetchPermissions();
|
|
}, [fetchAttributes, fetchPermissions]);
|
|
|
|
// Initial fetch
|
|
useEffect(() => {
|
|
fetchContracts();
|
|
}, [fetchContracts]);
|
|
|
|
return {
|
|
contracts,
|
|
loading,
|
|
error,
|
|
refetch: fetchContracts,
|
|
removeOptimistically,
|
|
updateOptimistically,
|
|
attributes,
|
|
permissions,
|
|
pagination,
|
|
fetchContractById,
|
|
generateEditFieldsFromAttributes,
|
|
ensureAttributesLoaded
|
|
};
|
|
}
|
|
|
|
// Contract operations hook
|
|
export function useTrusteeContractOperations() {
|
|
const [deletingContracts, setDeletingContracts] = useState<Set<string>>(new Set());
|
|
const [creatingContract, setCreatingContract] = useState(false);
|
|
const { request, isLoading } = useApiRequest();
|
|
const [deleteError, setDeleteError] = useState<string | null>(null);
|
|
const [createError, setCreateError] = useState<string | null>(null);
|
|
const [updateError, setUpdateError] = useState<string | null>(null);
|
|
|
|
const handleContractDelete = async (contractId: string) => {
|
|
setDeleteError(null);
|
|
setDeletingContracts(prev => new Set(prev).add(contractId));
|
|
|
|
try {
|
|
await deleteContractApi(request, contractId);
|
|
await new Promise(resolve => setTimeout(resolve, 300));
|
|
return true;
|
|
} catch (error: any) {
|
|
setDeleteError(error.message);
|
|
return false;
|
|
} finally {
|
|
setDeletingContracts(prev => {
|
|
const newSet = new Set(prev);
|
|
newSet.delete(contractId);
|
|
return newSet;
|
|
});
|
|
}
|
|
};
|
|
|
|
const handleContractCreate = async (contractData: Partial<TrusteeContract>) => {
|
|
setCreateError(null);
|
|
setCreatingContract(true);
|
|
|
|
try {
|
|
const currentUserData = getUserDataCache();
|
|
const mandateId = currentUserData?.mandateId || '';
|
|
|
|
const requestBody = {
|
|
...contractData,
|
|
mandate: mandateId
|
|
};
|
|
|
|
const newContract = await createContractApi(request, requestBody);
|
|
|
|
return { success: true, contractData: newContract };
|
|
} catch (error: any) {
|
|
setCreateError(error.message);
|
|
return { success: false, error: error.message };
|
|
} finally {
|
|
setCreatingContract(false);
|
|
}
|
|
};
|
|
|
|
const handleContractUpdate = async (
|
|
contractId: string,
|
|
updateData: Partial<TrusteeContract>,
|
|
_originalData?: any
|
|
) => {
|
|
setUpdateError(null);
|
|
|
|
try {
|
|
const currentUserData = getUserDataCache();
|
|
const mandateId = currentUserData?.mandateId || '';
|
|
|
|
// Note: organisationId should NOT be included in update if immutable
|
|
// Backend will reject if organisationId is changed
|
|
const requestBody = {
|
|
...updateData,
|
|
mandate: mandateId
|
|
};
|
|
|
|
const updatedContract = await updateContractApi(request, contractId, requestBody);
|
|
|
|
return { success: true, contractData: updatedContract };
|
|
} catch (error: any) {
|
|
const errorMessage = error.response?.data?.message || error.message || 'Failed to update contract';
|
|
const statusCode = error.response?.status;
|
|
|
|
setUpdateError(errorMessage);
|
|
|
|
return {
|
|
success: false,
|
|
error: errorMessage,
|
|
statusCode,
|
|
isPermissionError: statusCode === 403,
|
|
isValidationError: statusCode === 400
|
|
};
|
|
}
|
|
};
|
|
|
|
return {
|
|
deletingContracts,
|
|
creatingContract,
|
|
deleteError,
|
|
createError,
|
|
updateError,
|
|
handleContractDelete,
|
|
handleContractCreate,
|
|
handleContractUpdate,
|
|
isLoading
|
|
};
|
|
}
|