Added PFM Console UI project
This commit is contained in:
@@ -0,0 +1,535 @@
|
||||
import axios, { AxiosError } from 'axios';
|
||||
import { apiClient } from './httpClient';
|
||||
import { toolsService } from './toolsService';
|
||||
import { getCurrentUserSub } from '../auth/AuthProvider';
|
||||
import {
|
||||
Dashboard,
|
||||
Organisation,
|
||||
CreateOrganisationRequest,
|
||||
UpdateOrganisationRequest,
|
||||
Portfolio,
|
||||
CreatePortfolioRequest,
|
||||
UpdatePortfolioRequest,
|
||||
Programme,
|
||||
CreateProgrammeRequest,
|
||||
UpdateProgrammeRequest,
|
||||
Project,
|
||||
CreateProjectRequest,
|
||||
UpdateProjectRequest,
|
||||
UpdateProjectStatusRequest,
|
||||
Activity,
|
||||
CreateActivityRequest,
|
||||
Milestone,
|
||||
CreateMilestoneRequest,
|
||||
UpdateMilestoneRequest,
|
||||
Award,
|
||||
CreateAwardRequest,
|
||||
Contract,
|
||||
CreateContractRequest,
|
||||
ExecuteContractRequest,
|
||||
Budget,
|
||||
CreateBudgetRequest,
|
||||
Disbursement,
|
||||
CreateDisbursementRequest,
|
||||
UpdateDisbursementRequest,
|
||||
Indicator,
|
||||
CreateIndicatorRequest,
|
||||
Evidence,
|
||||
UpdateEvidenceRequest,
|
||||
Risk,
|
||||
CreateRiskRequest,
|
||||
UpdateRiskRequest,
|
||||
User,
|
||||
UserFilterRequest,
|
||||
Invite,
|
||||
InviteRequest,
|
||||
InviteUserRequest,
|
||||
AuditLog,
|
||||
ProblemDetails,
|
||||
} from '../types';
|
||||
|
||||
// Helper to extract ProblemDetails from Axios error
|
||||
export function parseApiError(error: unknown): ProblemDetails {
|
||||
if (axios.isAxiosError(error)) {
|
||||
const axiosErr = error as AxiosError<ProblemDetails>;
|
||||
if (axiosErr.response?.data) {
|
||||
return axiosErr.response.data;
|
||||
}
|
||||
return {
|
||||
title: 'API Request Error',
|
||||
detail: axiosErr.message || 'Unable to communicate with the remote PFM service.',
|
||||
status: axiosErr.response?.status || 500,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: 'Unexpected Application Error',
|
||||
detail: String(error),
|
||||
status: 500,
|
||||
};
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 1. Executive Dashboard APIs
|
||||
// ==========================================
|
||||
export const getDashboard = async (): Promise<Dashboard> => {
|
||||
const res = await apiClient.get<Dashboard>('/v1/api/governance/dashboard');
|
||||
return res.data;
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 2. Governance & Structure APIs
|
||||
// ==========================================
|
||||
export const getOrganisations = async (page = 1, pageSize = 100): Promise<Organisation[]> => {
|
||||
const res = await apiClient.get<Organisation[]>('/v1/api/governance/organisations', {
|
||||
params: { page, pageSize },
|
||||
});
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getOrganisation = async (organisationId: string | number): Promise<Organisation> => {
|
||||
const hashedOrgId = await toolsService.resolveOrganisationId(organisationId);
|
||||
const res = await apiClient.get<Organisation>(`/v1/api/governance/organisations/${hashedOrgId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createOrganisation = async (payload: CreateOrganisationRequest): Promise<Organisation> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/governance/organisations', {
|
||||
...payload,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const updateOrganisation = async (payload: UpdateOrganisationRequest): Promise<Organisation> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.put('/v1/api/governance/organisations', {
|
||||
...payload,
|
||||
updatedBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const getPortfolios = async (organisationId: string | number): Promise<Portfolio[]> => {
|
||||
const hashedOrgId = await toolsService.resolveOrganisationId(organisationId);
|
||||
const res = await apiClient.get<Portfolio[]>(`/v1/api/governance/organisations/${hashedOrgId}/portfolio`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getAllPortfolios = async (): Promise<Portfolio[]> => {
|
||||
try {
|
||||
const res = await apiClient.get<Portfolio[]>('/v1/api/governance/organisations/portfolio');
|
||||
return res.data || [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const createPortfolio = async (payload: CreatePortfolioRequest): Promise<Portfolio> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/governance/organisations/portfolio', {
|
||||
...payload,
|
||||
ownerId: payload.ownerId || userSub || undefined,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const updatePortfolio = async (payload: UpdatePortfolioRequest): Promise<Portfolio> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.put('/v1/api/governance/organisations/portfolio', {
|
||||
...payload,
|
||||
ownerId: payload.ownerId || userSub || undefined,
|
||||
updatedBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const getProgrammes = async (portfolioId: string | number): Promise<Programme[]> => {
|
||||
const hashedPortId = await toolsService.resolvePortfolioId(portfolioId);
|
||||
const res = await apiClient.get<Programme[]>(`/v1/api/governance/programmes/${hashedPortId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getAllProgrammes = async (): Promise<Programme[]> => {
|
||||
try {
|
||||
const res = await apiClient.get<Programme[]>('/v1/api/projects/programmes');
|
||||
return res.data || [];
|
||||
} catch {
|
||||
try {
|
||||
const resFallback = await apiClient.get<Programme[]>('/v1/api/governance/programmes');
|
||||
return resFallback.data || [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const createProgramme = async (payload: CreateProgrammeRequest): Promise<Programme> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/projects/programme', {
|
||||
...payload,
|
||||
ownerId: payload.ownerId || userSub || undefined,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const updateProgramme = async (payload: UpdateProgrammeRequest): Promise<Programme> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.put('/v1/api/projects/programme', {
|
||||
...payload,
|
||||
ownerId: payload.ownerId || userSub || undefined,
|
||||
updatedBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 3. Project & Milestone Management APIs
|
||||
// ==========================================
|
||||
export const getProjects = async (page = 1, pageSize = 100): Promise<Project[]> => {
|
||||
const res = await apiClient.get<Project[]>('/v1/api/projects', {
|
||||
params: { page, pageSize },
|
||||
});
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getProject = async (projectId: string | number): Promise<Project> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<Project | Project[]>(`/v1/api/projects/${hashedProjectId}`);
|
||||
return Array.isArray(res.data) ? res.data[0] : res.data;
|
||||
};
|
||||
|
||||
export const createProject = async (payload: CreateProjectRequest): Promise<Project> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/projects', {
|
||||
...payload,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const updateProject = async (payload: UpdateProjectRequest): Promise<Project> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.put('/v1/api/projects', {
|
||||
...payload,
|
||||
updatedBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const updateProjectStatus = async (payload: UpdateProjectStatusRequest): Promise<void> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
await apiClient.put('/v1/api/projects/status', {
|
||||
...payload,
|
||||
updatedBy: userSub || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
export const getActivities = async (projectId: string | number): Promise<Activity[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<Activity[]>(`/v1/api/projects/${hashedProjectId}/activities`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const createActivity = async (payload: CreateActivityRequest): Promise<Activity> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/projects/activities', {
|
||||
...payload,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const getMilestones = async (projectId: string | number): Promise<Milestone[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<Milestone[]>(`/v1/api/projects/${hashedProjectId}/milestones`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getAllMilestones = async (page = 1, pageSize = 100): Promise<Milestone[]> => {
|
||||
const res = await apiClient.get<Milestone[]>(`/v1/api/projects/milestones/${page}/${pageSize}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const createMilestone = async (payload: CreateMilestoneRequest): Promise<Milestone> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/evidence/milestones', {
|
||||
...payload,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const updateMilestone = async (payload: UpdateMilestoneRequest): Promise<void> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
await apiClient.put('/v1/api/projects/milestone', {
|
||||
...payload,
|
||||
updatedBy: userSub || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 4. Grant & Financial Management APIs
|
||||
// ==========================================
|
||||
export const getAwards = async (page = 1, pageSize = 100): Promise<Award[]> => {
|
||||
const res = await apiClient.get<Award[]>('/v1/api/grants/awards', {
|
||||
params: { page, pageSize },
|
||||
});
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getAward = async (awardId: string | number): Promise<Award> => {
|
||||
const res = await apiClient.get<Award>(`/v1/api/grants/awards/${awardId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createAward = async (payload: CreateAwardRequest): Promise<Award> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/grants/awards', {
|
||||
...payload,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const getContracts = async (page = 1, pageSize = 100): Promise<Contract[]> => {
|
||||
const res = await apiClient.get<Contract[]>('/v1/api/grants/contracts', {
|
||||
params: { page, pageSize },
|
||||
});
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getContract = async (contractId: string | number): Promise<Contract> => {
|
||||
const res = await apiClient.get<Contract>(`/v1/api/grants/contracts/${contractId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createContract = async (payload: CreateContractRequest): Promise<Contract> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/grants/contracts', {
|
||||
...payload,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const executeContract = async (payload: ExecuteContractRequest): Promise<void> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
await apiClient.post('/v1/api/grants/contracts/execute', {
|
||||
...payload,
|
||||
executedBy: userSub || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
export const getBudgets = async (page = 1, pageSize = 100): Promise<Budget[]> => {
|
||||
const res = await apiClient.get<Budget[]>('/v1/api/grants/budgets', {
|
||||
params: { page, pageSize },
|
||||
});
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const createBudget = async (payload: CreateBudgetRequest): Promise<Budget> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/grants/budgets', {
|
||||
...payload,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const getDisbursements = async (page = 1, pageSize = 100): Promise<Disbursement[]> => {
|
||||
const res = await apiClient.get<Disbursement[]>('/v1/api/execution/disbursements', {
|
||||
params: { page, pageSize },
|
||||
});
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const createDisbursement = async (payload: CreateDisbursementRequest): Promise<Disbursement> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/execution/disbursements', {
|
||||
...payload,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const updateDisbursement = async (payload: UpdateDisbursementRequest): Promise<void> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
await apiClient.put('/v1/api/execution/disbursements', {
|
||||
...payload,
|
||||
updatedBy: userSub || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
export const approveDisbursement = async (disbursementId: string | number): Promise<void> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
await apiClient.post(`/v1/api/execution/disbursements/${disbursementId}/approve`, {
|
||||
approvedBy: userSub || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 5. M&E, Evidence & Risk Management APIs
|
||||
// ==========================================
|
||||
export const getProjectIndicators = async (projectId: string | number): Promise<Indicator[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<Indicator[]>(`/v1/api/projects/indicators/project/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getAllIndicators = async (page = 1, pageSize = 100): Promise<Indicator[]> => {
|
||||
const res = await apiClient.get<Indicator[]>(`/v1/api/evidence/indicators/${page}/${pageSize}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const createIndicator = async (payload: CreateIndicatorRequest): Promise<Indicator> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/evidence/indicators', {
|
||||
...payload,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const recordIndicatorActual = async (indicatorId: string | number, actualAmount: number): Promise<void> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
await apiClient.post(`/v1/api/evidence/indicators/${indicatorId}/actuals/${actualAmount}`, {
|
||||
recordedBy: userSub || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
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 || [];
|
||||
};
|
||||
|
||||
export const getAllEvidence = async (): Promise<Evidence[]> => {
|
||||
try {
|
||||
const res = await apiClient.get<Evidence[]>('/v1/api/evidence');
|
||||
return res.data || [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const uploadEvidenceFile = async (formData: FormData): Promise<Evidence> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
if (userSub && !formData.get('userId')) {
|
||||
formData.append('userId', userSub);
|
||||
}
|
||||
const res = await apiClient.put<Evidence>('/v1/api/evidence/file', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const updateEvidence = async (payload: UpdateEvidenceRequest): Promise<void> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
await apiClient.put('/v1/api/evidence', {
|
||||
...payload,
|
||||
updatedBy: userSub || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
export const getProjectRisks = async (projectId: string | number): Promise<Risk[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<Risk[]>(`/v1/api/projects/${hashedProjectId}/risks`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getAllRisks = async (page = 1, pageSize = 100): Promise<Risk[]> => {
|
||||
const res = await apiClient.get<Risk[]>('/v1/api/execution/risks', {
|
||||
params: { page, pageSize },
|
||||
});
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const createRisk = async (payload: CreateRiskRequest): Promise<Risk> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/execution/risks', {
|
||||
...payload,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const updateRisk = async (payload: UpdateRiskRequest): Promise<void> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
await apiClient.put('/v1/api/execution/risks', {
|
||||
...payload,
|
||||
updatedBy: userSub || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 6. User Directory & Communications APIs
|
||||
// ==========================================
|
||||
export const getUsers = async (
|
||||
page = 1,
|
||||
pageSize = 100,
|
||||
filter: UserFilterRequest = {}
|
||||
): Promise<User[]> => {
|
||||
const res = await apiClient.post<User[]>(`/v1/api/users/${page}/${pageSize}`, filter);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getUser = async (userId: string): Promise<User> => {
|
||||
const res = await apiClient.get<User>(`/v1/api/users/${userId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const getCurrentUser = async (): Promise<User> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
if (userSub) {
|
||||
return getUser(userSub);
|
||||
}
|
||||
const res = await apiClient.get<User>('/v1/api/users/current');
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const updateUserStatus = async (userId: string, status: number): Promise<void> => {
|
||||
await apiClient.get(`/v1/api/users/${userId}/status/${status}`);
|
||||
};
|
||||
|
||||
export const sendInvite = async (payload: InviteRequest): Promise<Invite> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/communications/invite', {
|
||||
...payload,
|
||||
createdBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const getInvites = async (): Promise<Invite[]> => {
|
||||
try {
|
||||
const res = await apiClient.get<Invite[]>('/v1/api/communications/invite');
|
||||
return res.data || [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const inviteUser = async (payload: InviteUserRequest): Promise<User> => {
|
||||
const userSub = getCurrentUserSub();
|
||||
const res = await apiClient.post('/v1/api/governance/users/invite', {
|
||||
...payload,
|
||||
invitedBy: userSub || undefined,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const revokeUser = async (userId: string): Promise<void> => {
|
||||
await apiClient.delete(`/v1/api/governance/users/${userId}`);
|
||||
};
|
||||
|
||||
export const getAuditLogs = async (): Promise<AuditLog[]> => {
|
||||
try {
|
||||
const res = await apiClient.get<AuditLog[]>('/v1/api/governance/audit');
|
||||
return res.data || [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
import axios, { InternalAxiosRequestConfig } from 'axios';
|
||||
import { getApiBaseUrl } from '../config';
|
||||
|
||||
export const BASE_API_URL = getApiBaseUrl();
|
||||
|
||||
// Create Axios Instance
|
||||
export const apiClient = axios.create({
|
||||
baseURL: BASE_API_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json; version=1',
|
||||
Accept: 'application/json; version=1',
|
||||
},
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
// Request Interceptor to dynamically set baseURL and attach Bearer Token
|
||||
apiClient.interceptors.request.use(
|
||||
(config: InternalAxiosRequestConfig) => {
|
||||
// Dynamically synchronize baseURL from runtime configuration
|
||||
config.baseURL = getApiBaseUrl();
|
||||
const token = localStorage.getItem('pfm_access_token');
|
||||
if (token && config.headers) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
@@ -0,0 +1,196 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { apiClient } from './httpClient';
|
||||
import { queryClient } from '../lib/queryClient';
|
||||
|
||||
/**
|
||||
* Deterministic fallback encoder for offline/preview sessions
|
||||
* Generates an obfuscated, unique HashID string with salt
|
||||
*/
|
||||
function generateDeterministicHashId(id: number | string, context: string): string {
|
||||
const str = `${context}:${id}:pfm-salt-2026`;
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
hash = ((hash << 5) + hash) + str.charCodeAt(i);
|
||||
hash = hash & hash; // Convert to 32bit integer
|
||||
}
|
||||
const positiveHash = Math.abs(hash);
|
||||
const base62Chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
let encoded = '';
|
||||
let num = positiveHash;
|
||||
while (num > 0) {
|
||||
encoded = base62Chars[num % 62] + encoded;
|
||||
num = Math.floor(num / 62);
|
||||
}
|
||||
const prefix = context ? context.slice(0, 3).toLowerCase() : 'id';
|
||||
return `${prefix}_${encoded.padStart(8, 'x')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the backend tools encoding endpoint to retrieve the designated HashID string
|
||||
*/
|
||||
async function fetchHashIdFromEndpoint(id: number | string, context = 'general'): Promise<string> {
|
||||
if (id === undefined || id === null || id === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
// Attempt standard tools encoding endpoint variations
|
||||
const response = await apiClient.get<string | { hashId?: string; encoded?: string; result?: string; value?: string }>(
|
||||
`/v1/api/tools/encode/${id}`,
|
||||
{
|
||||
params: { context, type: context },
|
||||
timeout: 4000,
|
||||
}
|
||||
);
|
||||
|
||||
if (typeof response.data === 'string' && response.data.trim()) {
|
||||
return response.data.trim();
|
||||
}
|
||||
if (response.data && typeof response.data === 'object') {
|
||||
const candidate = response.data.hashId || response.data.encoded || response.data.result || response.data.value;
|
||||
if (candidate) return candidate;
|
||||
}
|
||||
} catch {
|
||||
// Attempt query param variant
|
||||
try {
|
||||
const response = await apiClient.get<string | { hashId?: string; encoded?: string; result?: string; value?: string }>(
|
||||
'/v1/api/tools/encode',
|
||||
{
|
||||
params: { id, context, type: context },
|
||||
timeout: 4000,
|
||||
}
|
||||
);
|
||||
if (typeof response.data === 'string' && response.data.trim()) {
|
||||
return response.data.trim();
|
||||
}
|
||||
if (response.data && typeof response.data === 'object') {
|
||||
const candidate = response.data.hashId || response.data.encoded || response.data.result || response.data.value;
|
||||
if (candidate) return candidate;
|
||||
}
|
||||
} catch {
|
||||
// Fallback to deterministic HashID generator
|
||||
}
|
||||
}
|
||||
|
||||
// Graceful fallback guaranteeing valid HashID output during preview
|
||||
return generateDeterministicHashId(id, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the backend tools decoding endpoint
|
||||
*/
|
||||
async function fetchDecodedIdFromEndpoint(hashId: string, context = 'general'): Promise<number | string> {
|
||||
if (!hashId) return '';
|
||||
try {
|
||||
const response = await apiClient.get<{ id?: number | string; decoded?: number | string } | number | string>(
|
||||
`/v1/api/tools/decode/${encodeURIComponent(hashId)}`,
|
||||
{ params: { context }, timeout: 4000 }
|
||||
);
|
||||
if (typeof response.data === 'number' || typeof response.data === 'string') {
|
||||
return response.data;
|
||||
}
|
||||
if (response.data && typeof response.data === 'object') {
|
||||
if (response.data.id !== undefined) return response.data.id;
|
||||
if (response.data.decoded !== undefined) return response.data.decoded;
|
||||
}
|
||||
} catch {
|
||||
// Passthrough or fallback
|
||||
}
|
||||
return hashId;
|
||||
}
|
||||
|
||||
export const toolsService = {
|
||||
/**
|
||||
* Encodes a raw ID to a HashID, cached client-side in TanStack Query for the active session
|
||||
*/
|
||||
async encodeId(id: number | string, context = 'general'): Promise<string> {
|
||||
if (id === undefined || id === null || id === '') return '';
|
||||
|
||||
const idStr = String(id);
|
||||
return queryClient.fetchQuery({
|
||||
queryKey: ['hashId', context, idStr],
|
||||
queryFn: () => fetchHashIdFromEndpoint(id, context),
|
||||
staleTime: Infinity, // Caches client-side during the active session to eliminate redundant round trips
|
||||
gcTime: 1000 * 60 * 60 * 24, // Keep in memory
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Decodes a HashID string back to original identifier
|
||||
*/
|
||||
async decodeId(hashId: string, context = 'general'): Promise<number | string> {
|
||||
if (!hashId) return '';
|
||||
|
||||
return queryClient.fetchQuery({
|
||||
queryKey: ['decodeHashId', context, hashId],
|
||||
queryFn: () => fetchDecodedIdFromEndpoint(hashId, context),
|
||||
staleTime: Infinity,
|
||||
gcTime: 1000 * 60 * 60 * 24,
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Specific convenience resolvers for domain entities
|
||||
*/
|
||||
async resolveProjectId(projectId: number | string): Promise<string> {
|
||||
return this.encodeId(projectId, 'project');
|
||||
},
|
||||
|
||||
async resolveOrganisationId(organisationId: number | string): Promise<string> {
|
||||
return this.encodeId(organisationId, 'organisation');
|
||||
},
|
||||
|
||||
async resolveProgrammeId(programmeId: number | string): Promise<string> {
|
||||
return this.encodeId(programmeId, 'programme');
|
||||
},
|
||||
|
||||
async resolvePortfolioId(portfolioId: number | string): Promise<string> {
|
||||
return this.encodeId(portfolioId, 'portfolio');
|
||||
},
|
||||
|
||||
async resolveAwardId(awardId: number | string): Promise<string> {
|
||||
return this.encodeId(awardId, 'award');
|
||||
},
|
||||
|
||||
async resolveContractId(contractId: number | string): Promise<string> {
|
||||
return this.encodeId(contractId, 'contract');
|
||||
},
|
||||
|
||||
/**
|
||||
* Resolves query parameters or path variables encoded as HashIDs
|
||||
* before performing API calls
|
||||
*/
|
||||
async resolveHashedParams<T extends Record<string, any>>(
|
||||
params: T,
|
||||
keysToHash: (keyof T)[]
|
||||
): Promise<T> {
|
||||
const resolved: any = { ...params };
|
||||
for (const key of keysToHash) {
|
||||
const val = params[key];
|
||||
if (val !== undefined && val !== null) {
|
||||
const contextStr = String(key).replace(/Id$/i, '').toLowerCase();
|
||||
resolved[key] = await this.encodeId(val, contextStr);
|
||||
}
|
||||
}
|
||||
return resolved;
|
||||
},
|
||||
|
||||
/**
|
||||
* Pre-fetches and primes cache for a collection of IDs
|
||||
*/
|
||||
async primeCache(items: { id: number | string; context: string }[]): Promise<void> {
|
||||
await Promise.all(items.map((item) => this.encodeId(item.id, item.context)));
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* React Hook for consuming HashIDs with TanStack Query caching in components
|
||||
*/
|
||||
export function useHashId(id?: number | string | null, context = 'general') {
|
||||
return useQuery({
|
||||
queryKey: ['hashId', context, id !== undefined && id !== null ? String(id) : ''],
|
||||
queryFn: () => (id !== undefined && id !== null ? toolsService.encodeId(id, context) : Promise.resolve('')),
|
||||
enabled: id !== undefined && id !== null && id !== '',
|
||||
staleTime: Infinity,
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user