Refactored UI and compose file

This commit is contained in:
2026-09-17 07:07:05 +02:00
parent 2d74f7f1bd
commit 831d57a8a0
47 changed files with 9718 additions and 10088 deletions
File diff suppressed because it is too large Load Diff
@@ -5,24 +5,24 @@ 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,
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)
(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)
);
@@ -1,196 +1,210 @@
import Hashids from 'hashids';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from './httpClient';
import { queryClient } from '../lib/queryClient';
const env = (typeof import.meta !== 'undefined' && import.meta.env
? import.meta.env
: {}) as Record<string, string | undefined>;
/**
* Deterministic fallback encoder for offline/preview sessions
* Generates an obfuscated, unique HashID string with salt
* Deterministic Hashids configuration matching pfm-api HasherSettings.
* Ensures 100% interoperability with the C# Hashids.net NuGet package on the backend.
*/
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
export const HASHER_SETTINGS = {
minHashLength: Number(env.VITE_HASHER_MIN_LENGTH) || 11,
salt:
(env.VITE_HASHER_SALT as string) ||
'TGlnaHQgQ2hhcm1zLCBNaWRyYW5kQm9va3MgbWFrZSBsb3RzIG9mIG1vbmV5IGFuZCBhcmUgYSBzdWNjZXNzZnVsIHZpcmFsIHN0b3J5IGluIFNvdXRoIEFmcmljYQ==',
};
// Singleton Hashids instance initialized with salt & minHashLength
let hasher = new Hashids(HASHER_SETTINGS.salt, HASHER_SETTINGS.minHashLength);
/**
* Dynamically reconfigures the deterministic Hashids instance from runtime configuration.
*/
export function updateHasherSettings(salt?: string, minLength?: number | string): void {
let updated = false;
if (salt && typeof salt === 'string' && salt.trim() !== '') {
HASHER_SETTINGS.salt = salt.trim();
updated = true;
}
if (minLength !== undefined && minLength !== null && minLength !== '') {
const parsed = Number(minLength);
if (!isNaN(parsed) && parsed > 0) {
HASHER_SETTINGS.minHashLength = parsed;
updated = true;
}
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')}`;
}
if (updated) {
hasher = new Hashids(HASHER_SETTINGS.salt, HASHER_SETTINGS.minHashLength);
}
}
/**
* Invokes the backend tools encoding endpoint to retrieve the designated HashID string
* Checks whether an incoming string is already a valid Hashid matching the configured salt and min length.
* Prevents double-encoding already-hashed route parameters or IDs.
*/
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);
function isAlreadyHashId(candidate: string): boolean {
if (typeof candidate !== 'string' || candidate.length < HASHER_SETTINGS.minHashLength) {
return false;
}
try {
const decoded = hasher.decode(candidate);
return Array.isArray(decoded) && decoded.length > 0;
} catch {
return false;
}
}
/**
* Invokes the backend tools decoding endpoint
* Deterministically encodes a numeric ID or numeric string into a HashID string.
* Synchronous and does not perform HTTP network round trips.
*/
async function fetchDecodedIdFromEndpoint(hashId: string, context = 'general'): Promise<number | string> {
if (!hashId) return '';
export function encodeHashIdSync(id: number | string | null | undefined): string {
if (id === undefined || id === null || id === '') {
return '';
}
// If already a number
if (typeof id === 'number') {
if (isNaN(id) || !isFinite(id) || id < 0) return '';
return hasher.encode(id);
}
const str = String(id).trim();
if (!str) return '';
// Check if string is already a valid HashID
if (isAlreadyHashId(str)) {
return str;
}
// Check if string is pure digits (e.g. "123")
if (/^\d+$/.test(str)) {
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;
}
const num = parseInt(str, 10);
if (!isNaN(num) && num >= 0) {
return hasher.encode(num);
}
} catch {
// Passthrough or fallback
// Fall through
}
return hashId;
}
// Non-numeric identifiers (UUIDs, codes) returned as-is
return str;
}
/**
* Deterministically decodes a HashID string back to original numeric ID or string.
* Synchronous and does not perform HTTP network round trips.
*/
export function decodeHashIdSync(hashId: string | null | undefined): number | string {
if (!hashId) return '';
const str = String(hashId).trim();
if (!str) return '';
try {
const decoded = hasher.decode(str);
if (Array.isArray(decoded) && decoded.length > 0) {
return Number(decoded[0]);
}
} catch {
// If decoding fails, return raw string
}
return str;
}
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 '';
/**
* Synchronous encoding
*/
encodeIdSync(id: number | string | null | undefined): string {
return encodeHashIdSync(id);
},
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
});
},
/**
* Synchronous decoding
*/
decodeIdSync(hashId: string | null | undefined): number | string {
return decodeHashIdSync(hashId);
},
/**
* Decodes a HashID string back to original identifier
*/
async decodeId(hashId: string, context = 'general'): Promise<number | string> {
if (!hashId) return '';
/**
* Encodes a raw ID to a HashID (returns Promise for backward compatibility with existing callers)
*/
async encodeId(id: number | string | null | undefined, _context = 'general'): Promise<string> {
return encodeHashIdSync(id);
},
return queryClient.fetchQuery({
queryKey: ['decodeHashId', context, hashId],
queryFn: () => fetchDecodedIdFromEndpoint(hashId, context),
staleTime: Infinity,
gcTime: 1000 * 60 * 60 * 24,
});
},
/**
* Decodes a HashID string back to original identifier
*/
async decodeId(hashId: string | null | undefined, _context = 'general'): Promise<number | string> {
return decodeHashIdSync(hashId);
},
/**
* Specific convenience resolvers for domain entities
*/
async resolveProjectId(projectId: number | string): Promise<string> {
return this.encodeId(projectId, 'project');
},
/**
* Domain-specific convenience resolvers for entities
*/
async resolveProjectId(projectId: number | string): Promise<string> {
return encodeHashIdSync(projectId);
},
async resolveOrganisationId(organisationId: number | string): Promise<string> {
return this.encodeId(organisationId, 'organisation');
},
async resolveOrganisationId(organisationId: number | string): Promise<string> {
return encodeHashIdSync(organisationId);
},
async resolveProgrammeId(programmeId: number | string): Promise<string> {
return this.encodeId(programmeId, 'programme');
},
async resolveProgrammeId(programmeId: number | string): Promise<string> {
return encodeHashIdSync(programmeId);
},
async resolvePortfolioId(portfolioId: number | string): Promise<string> {
return this.encodeId(portfolioId, 'portfolio');
},
async resolvePortfolioId(portfolioId: number | string): Promise<string> {
return encodeHashIdSync(portfolioId);
},
async resolveAwardId(awardId: number | string): Promise<string> {
return this.encodeId(awardId, 'award');
},
async resolveAwardId(awardId: number | string): Promise<string> {
return encodeHashIdSync(awardId);
},
async resolveContractId(contractId: number | string): Promise<string> {
return this.encodeId(contractId, 'contract');
},
async resolveContractId(contractId: number | string): Promise<string> {
return encodeHashIdSync(contractId);
},
/**
* 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;
},
/**
* 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) {
resolved[key] = encodeHashIdSync(val);
}
}
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)));
},
/**
* Compatibility cache primer (now a no-op as Hashids calculation is instantaneous client-side)
*/
async primeCache(_items: { id: number | string; context: string }[]): Promise<void> {
// No-op - instant deterministic computation
},
};
/**
* 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,
});
return useQuery({
queryKey: ['hashId', context, id !== undefined && id !== null ? String(id) : ''],
queryFn: () => Promise.resolve(encodeHashIdSync(id)),
enabled: id !== undefined && id !== null && id !== '',
staleTime: Infinity,
});
}