Files
smom-dbis-138/services/settlement-middleware/src/adapters/fineract.ts
zaragoza444 5229c2d888
Some checks failed
CI/CD Pipeline / Solidity Contracts (push) Failing after 1m13s
CI/CD Pipeline / Lint and Format (push) Has been cancelled
CI/CD Pipeline / Security Scanning (push) Has been cancelled
CI/CD Pipeline / Terraform Validation (push) Has been cancelled
CI/CD Pipeline / Kubernetes Validation (push) Has been cancelled
Deploy ChainID 138 / Deploy ChainID 138 (push) Has been cancelled
HYBX OMNL TypeScript & anchor / token-aggregation build + reconcile artifact (push) Has been cancelled
Validation / validate-genesis (push) Has been cancelled
Validation / validate-terraform (push) Has been cancelled
Validation / validate-kubernetes (push) Has been cancelled
Validation / validate-smart-contracts (push) Has been cancelled
Validation / validate-security (push) Has been cancelled
Validation / validate-documentation (push) Has been cancelled
Verify Deployment / Verify Deployment (push) Has been cancelled
fix(omnl): production blockers for M0-M4 settlement stack
Exempt dashboard read APIs from anonymous rate limits, preserve nginx-injected auth, wire chain-mint and DB env through deploy/LXC scripts, resolve M3 token addresses from registry, and harden super-admin seeding.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-29 06:47:20 -07:00

219 lines
7.5 KiB
TypeScript

import axios from 'axios';
import { settlementStore } from '../store/settlement-store';
const GL_HINTS = ['1000', '1050', '1410', '2000', '2100', '2200', '2300'];
function fineractBase(): string {
return (process.env.OMNL_FINERACT_BASE_URL || '').replace(/\/$/, '');
}
function authHeaders(): Record<string, string> {
const tenant = process.env.OMNL_FINERACT_TENANT || 'omnl';
const user =
process.env.OMNL_FINERACT_USER?.trim() ||
process.env.OMNL_FINERACT_USERNAME?.trim() ||
'ali_hospitallers_tenant';
const pass = process.env.OMNL_FINERACT_PASSWORD || '';
if (!fineractBase() || !pass) throw new Error('Fineract credentials required');
const auth = Buffer.from(`${user}:${pass}`).toString('base64');
return {
Authorization: `Basic ${auth}`,
'Fineract-Platform-TenantId': tenant,
'Content-Type': 'application/json',
Accept: 'application/json',
};
}
export async function fineractOfficeReachable(officeId: number): Promise<boolean> {
try {
const { status } = await axios.get(`${fineractBase()}/offices/${officeId}`, {
headers: authHeaders(),
timeout: 20000,
});
return status === 200;
} catch {
return false;
}
}
async function fetchOfficeJournalLines(officeId: number) {
const headers = authHeaders();
const out: Array<{ glAccountId: number; amount: number; entryType: 'DEBIT' | 'CREDIT' }> = [];
let offset = 0;
const limit = 200;
for (;;) {
const { data } = await axios.get(`${fineractBase()}/journalentries`, {
headers,
timeout: 60000,
params: { officeId, limit, offset },
});
const batch = Array.isArray(data) ? data : (data as { pageItems?: unknown[] })?.pageItems ?? [];
if (!Array.isArray(batch) || batch.length === 0) break;
for (const je of batch) {
const row = je as {
glAccountId?: number;
amount?: number;
entryType?: string | { value?: string; code?: string };
debits?: Array<{ glAccountId?: number; amount?: number }>;
credits?: Array<{ glAccountId?: number; amount?: number }>;
};
const flat =
typeof row.entryType === 'string'
? row.entryType
: row.entryType?.value || row.entryType?.code || '';
if (row.glAccountId != null && row.amount != null && flat) {
const normalized = flat.toUpperCase();
out.push({
glAccountId: row.glAccountId,
amount: Number(row.amount || 0),
entryType: normalized.startsWith('DEB') ? 'DEBIT' : 'CREDIT',
});
continue;
}
for (const d of row.debits ?? []) {
if (d.glAccountId != null) {
out.push({ glAccountId: d.glAccountId, amount: Number(d.amount || 0), entryType: 'DEBIT' });
}
}
for (const c of row.credits ?? []) {
if (c.glAccountId != null) {
out.push({ glAccountId: c.glAccountId, amount: Number(c.amount || 0), entryType: 'CREDIT' });
}
}
}
if (batch.length < limit) break;
offset += limit;
}
return out;
}
async function fetchGlAccountMap(ids: Set<number>): Promise<Map<number, string>> {
const headers = authHeaders();
const map = new Map<number, string>();
for (const code of GL_HINTS) {
const { data } = await axios.get(`${fineractBase()}/glaccounts`, {
headers,
timeout: 30000,
params: { glCode: code },
});
const rows = Array.isArray(data) ? data : (data as { pageItems?: unknown[] })?.pageItems ?? [];
for (const row of rows as { id?: number; glCode?: string }[]) {
if (row.id != null && row.glCode) map.set(row.id, String(row.glCode));
}
}
if ([...ids].some((id) => !map.has(id))) {
let offset = 0;
const limit = 200;
for (;;) {
const { data } = await axios.get(`${fineractBase()}/glaccounts`, {
headers,
timeout: 30000,
params: { limit, offset },
});
const rows = Array.isArray(data) ? data : (data as { pageItems?: unknown[] })?.pageItems ?? [];
if (!rows.length) break;
for (const row of rows as { id?: number; glCode?: string }[]) {
if (row.id != null && row.glCode && ids.has(row.id)) map.set(row.id, String(row.glCode));
}
if (rows.length < limit) break;
offset += limit;
}
}
return map;
}
async function fetchGlBalancesFromJournals(officeId: number): Promise<Record<string, string>> {
const lines = await fetchOfficeJournalLines(officeId);
if (!lines.length) return {};
const ids = new Set(lines.map((l) => l.glAccountId));
const glById = await fetchGlAccountMap(ids);
const net = new Map<number, number>();
for (const line of lines) {
net.set(line.glAccountId, (net.get(line.glAccountId) ?? 0) + (line.entryType === 'DEBIT' ? line.amount : -line.amount));
}
const out: Record<string, string> = {};
for (const [id, val] of net.entries()) {
if (Math.abs(val) < 0.005) continue;
const code = glById.get(id) ?? String(id);
out[code] = Math.abs(val).toFixed(2);
}
return out;
}
export async function postJournalEntry(entry: {
officeId: number;
transactionDate: string;
referenceNumber: string;
comments: string;
debits: { glAccountId: number; amount: number }[];
credits: { glAccountId: number; amount: number }[];
}): Promise<{ resourceId: number }> {
const { data } = await axios.post(`${fineractBase()}/journalentries`, entry, {
headers: authHeaders(),
timeout: 60000,
});
return { resourceId: data.resourceId ?? data.entityId ?? 0 };
}
const glCodeCache = new Map<string, number>();
/** Resolve Fineract GL account id from chart code (e.g. 1410 → 24). */
export async function resolveGlAccountId(glCode: string): Promise<number> {
const code = String(glCode).trim();
const cached = glCodeCache.get(code);
if (cached != null) return cached;
const { data } = await axios.get(`${fineractBase()}/glaccounts`, {
headers: authHeaders(),
timeout: 30000,
params: { glCode: code },
});
const rows = Array.isArray(data) ? data : (data as { pageItems?: unknown[] })?.pageItems ?? [];
const match = (rows as { id?: number; glCode?: string }[]).find((r) => r.glCode === code);
if (!match?.id) {
throw new Error(`GL account not found for code ${code}`);
}
glCodeCache.set(code, match.id);
return match.id;
}
export async function fetchGlBalances(officeId: number): Promise<Record<string, string>> {
const base = fineractBase();
if (!base || !process.env.OMNL_FINERACT_PASSWORD) return {};
let out: Record<string, string> = {};
try {
const { data } = await axios.get(`${base}/runreports/General Ledger Report`, {
headers: authHeaders(),
params: { R_officeId: officeId, genericResultSet: false },
timeout: 60000,
});
const rows = Array.isArray(data) ? data : (data as { data?: unknown[] })?.data ?? [];
for (const row of rows as { glCode?: string; balance?: number }[]) {
if (row.glCode) out[row.glCode] = String(row.balance ?? 0);
}
if (Object.keys(out).length === 0) {
out = await fetchGlBalancesFromJournals(officeId);
}
} catch {
try {
out = await fetchGlBalancesFromJournals(officeId);
} catch {
out = {};
}
}
out.inFlightSwift = sumInFlightSwift().toFixed(2);
return out;
}
function sumInFlightSwift(): number {
const inFlightPhases = new Set(['HYBX_RAIL_DISPATCHED', 'ISO20022_ARCHIVED', 'CHAIN_MINT_REQUESTED']);
return settlementStore
.list(500)
.filter(
(r) =>
inFlightPhases.has(r.phase) &&
(r.request.rail === 'SWIFT' || r.request.rail === 'RTGS' || r.request.rail === 'SEPA'),
)
.reduce((sum, r) => sum + (parseFloat(r.request.amount ?? '0') || 0), 0);
}