@crediblex.io/fineract-api-client
Version:
TypeScript client for Fineract APIs
870 lines • 44.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const index_1 = require("../index");
// Configuration for the Fineract SDK
const sdkConfig = {
// baseURL: "https://localhost:8443", // Your Fineract base URL
baseURL: "https://fineract-api.uat.crediblex.io",
tenantId: "default", // Your Fineract tenant ID
username: "haider", // Your Fineract username
password: "bex!BZQ3phw0zyf-caj", // Your Fineract password
timeout: 60000, // Optional: request timeout in milliseconds
};
// Create an instance of the Fineract SDK
const fineractSDK = (0, index_1.createFineractSDK)(sdkConfig);
async function createAndFetchSme() {
console.log("Attempting to create a new sme...");
const newSmeData = {
officeId: 1,
fullname: "Client created by API",
active: true,
activationDate: "2024-07-28",
dateFormat: "yyyy-MM-dd",
locale: "en",
legalFormId: 1,
externalId: "C1",
};
let createdSmeId;
let createdSmeExternalId;
try {
const createResponse = await fineractSDK.sme.create(newSmeData);
console.log("SME created successfully!");
console.log("Response:", JSON.stringify(createResponse, null, 2));
createdSmeId = createResponse.clientId;
createdSmeExternalId = createResponse.resourceExternalId;
if (!createdSmeId) {
console.error("Could not determine created sme ID from response:", createResponse);
return;
}
console.log(`Created sme ID: ${createdSmeId}`);
}
catch (error) {
const err = error;
console.error("Message:", err.message);
console.error("Details:", JSON.stringify(err.details, null, 2));
console.error("Status Code:", err.statusCode);
return; // Stop if sme creation fails
}
if (createdSmeId) {
console.log(`\nAttempting to fetch details for sme ID: ${createdSmeId}...`);
try {
const smeDetails1 = await fineractSDK.sme.getDetails(createdSmeId);
const smeDetails2 = await fineractSDK.sme.getDetailsByExternalId(createdSmeExternalId);
console.log("SME details retrieved successfully!");
console.log("Details 1:", JSON.stringify(smeDetails1, null, 2));
console.log("Details 2:", JSON.stringify(smeDetails2, null, 2));
}
catch (error) {
const err = error;
console.error(`Error fetching sme details for ID ${createdSmeId}:`, err.error);
console.error("Message:", err.message);
console.error("Details:", JSON.stringify(err.details, null, 2));
console.error("Status Code:", err.statusCode);
}
}
}
async function fetchDatatable() {
const datatable = await fineractSDK.datatable.getByName("m_client_extended");
const datatableEntries = await fineractSDK.datatable.getEntries("m_client_extended", 1);
console.log("Datatable:", JSON.stringify(datatable, null, 2));
console.log("Datatable entries:", JSON.stringify(datatableEntries, null, 2));
}
async function fetchLoanProducts() {
const loanProducts = await fineractSDK.loanproducts.getAll();
console.log("Loan products:", JSON.stringify(loanProducts, null, 2));
}
async function fetchSavingsProducts() {
const savingsProducts = await fineractSDK.savingsproducts.getAll();
console.log("Savings products:", JSON.stringify(savingsProducts, null, 2));
}
async function createSavingsAccount() {
const savingsProducts = await fineractSDK.savingsproducts.getAll();
// Create fallback savings account
const fallbackSavingsProduct = savingsProducts.find((product) => product.shortName === "FBSA");
console.log("Fallback savings product:", JSON.stringify(fallbackSavingsProduct, null, 2));
if (!fallbackSavingsProduct) {
console.error("Fallback savings product not found");
return;
}
const savingsAccount = await fineractSDK.savingsaccounts.create({
clientId: 430, // saved from a response of fineractSDK.sme.create(newSmeData);
productId: fallbackSavingsProduct.id,
submittedOnDate: "2024-07-28",
dateFormat: "yyyy-MM-dd",
locale: "en",
});
console.log("Savings account created:", JSON.stringify(savingsAccount, null, 2));
// Approve the savings account
const approvalResponse = await fineractSDK.savingsproducts.approve(savingsAccount.savingsId, {
approvedOnDate: "2024-06-19",
dateFormat: "yyyy-MM-dd",
locale: "en",
});
console.log("Savings account approved:", JSON.stringify(approvalResponse, null, 2));
// Activate the savings account
const activationResponse = await fineractSDK.savingsproducts.activate(savingsAccount.savingsId, {
activatedOnDate: "2024-06-19",
dateFormat: "yyyy-MM-dd",
locale: "en",
});
console.log("Savings account activated:", JSON.stringify(activationResponse, null, 2));
}
async function calculateLoanRepaymentSchedule() {
const loanRepaymentSchedule = await fineractSDK.loansaccounts.getRepaymentSchedule({
productId: 1,
// loanOfficerId: "",
// loanPurposeId: "",
// fundId: "",
submittedOnDate: "28 May 2025",
expectedDisbursementDate: "30 May 2025",
// externalId: "",
// linkAccountId: "",
// createStandingInstructionAtDisbursement: "",
loanTermFrequency: 3,
loanTermFrequencyType: 2,
numberOfRepayments: 3,
repaymentEvery: 1,
repaymentFrequencyType: 2,
// repaymentFrequencyNthDayType: "",
// repaymentFrequencyDayOfWeekType: "",
// repaymentsStartingFromDate: null,
// interestChargedFromDate: null,
interestType: 0,
// isEqualAmortization: false,
amortizationType: 1,
interestCalculationPeriodType: 1,
// loanIdToClose: "",
// isTopup: "",
transactionProcessingStrategyCode: "creocore-strategy",
// interestRateFrequencyType: 3,
interestRatePerPeriod: 1,
// charges: [],
// collateral: [],
dateFormat: "dd MMMM yyyy",
locale: "en",
clientId: 1,
loanType: "individual",
principal: 100000,
// allowPartialPeriodInterestCalcualtion: false,
});
console.log("Loan repayment schedule created:", JSON.stringify(loanRepaymentSchedule, null, 2));
}
// Run the example
// createAndFetchSme()
// .then(() => console.log("\nExample finished."))
// .catch((e) => console.error("Unhandled error in example script:", e));
// fetchDatatable()
// .then(() => console.log("\nExample finished."))
// .catch((e) => console.error("Unhandled error in example script:", e));
// fetchLoanProducts()
// .then(() => console.log("\nExample finished."))
// .catch((e) => console.error("Unhandled error in example script:", e));
// fetchSavingsProducts()
// .then(() => console.log("\nExample finished."))
// .catch((e) => console.error("Unhandled error in example script:", e));
// createSavingsAccount()
// .then(() => console.log("\nExample finished."))
// .catch((e) => console.error("Unhandled error in example script:", e));
// calculateLoanRepaymentSchedule()
// .then(() => console.log("\nExample finished."))
// .catch((e) => console.error("Unhandled error in example script:", e));
async function completeWorkflowExample() {
console.log("=== Starting Complete Workflow ===\n");
try {
console.log("Step 1: Creating SME Client...");
const smeResponse = await fineractSDK.sme.create({
officeId: 1, // Hardcoded to 1 because currently we only have head office
fullname: "haider 9 july 2025 test-api-client-5",
active: true, // Hardcoded to always true
activationDate: "2024-07-28",
dateFormat: "yyyy-MM-dd",
locale: "en",
legalFormId: 2, // Hardcoded to 2 meaning client in fineract language
externalId: "LOS-EXT-H5",
});
const clientId = smeResponse.clientId;
console.log("✓ SME Client Created with ID:", clientId);
// console.log("SME Response:", JSON.stringify(smeResponse, null, 2));
console.log();
console.log("Skipping virtual account number and remitter details for now");
// // Step 2: Add Virtual Account Number (Datatables API)
// console.log("Step 2: Adding Virtual Account Number...");
// await fineractSDK.datatable.createEntry("dt_client_virtual_account_number",
// client_id: clientId,
// virtualAccountNumber: 123456789,
// );
// console.log("✓ Virtual Account Number added successfully");
// console.log();
// // Step 2.1: Add Remitter Details (for RBF enabled SMEs)
// console.log("Step 2.1: Adding Remitter Details (RBF)...");
// await fineractSDK.datatable.addEntry("dt_client_remitter_names", {
// client_id: clientId,
// remitterName: "Example Remitter Name", // replace with actual remitter name
// });
// console.log("✓ Remitter Details added successfully");
// console.log();
// First get all savings products to find fallback product ID
const savingsProducts = await fineractSDK.savingsproducts.getAll();
const fallbackProduct = savingsProducts.find((product) => product.shortName === "FBSA");
const FALLBACK_PRODUCT_ID = fallbackProduct?.id || 1; // fallback to 1 if not found
console.log("Step 3: Creating Fallback Savings Account with product ID:", FALLBACK_PRODUCT_ID);
const fallbackAccount = await fineractSDK.savingsaccounts.create({
clientId: clientId,
productId: FALLBACK_PRODUCT_ID,
submittedOnDate: "2024-07-28",
dateFormat: "yyyy-MM-dd",
locale: "en",
});
const fallbackAccountId = fallbackAccount.resourceId;
console.log("✓ Fallback Savings Account Created with ID:", fallbackAccountId);
// Approve fallback account
await fineractSDK.savingsproducts.approve(fallbackAccountId, {
approvedOnDate: "2024-07-28",
dateFormat: "yyyy-MM-dd",
locale: "en",
});
console.log("✓ Fallback Savings Account Approved");
// Activate fallback account
await fineractSDK.savingsproducts.activate(fallbackAccountId, {
activatedOnDate: "2024-07-28",
dateFormat: "yyyy-MM-dd",
locale: "en",
});
console.log("✓ Fallback Account Activated");
console.log();
// Find cash margin product ID
const cashMarginProduct = savingsProducts.find((product) => product.shortName === "CMSA");
const CASH_MARGIN_PRODUCT_ID = cashMarginProduct?.id || 2; // fallback to 2 if not found
console.log("Step 4: Creating Cash Margin Account with product ID:", CASH_MARGIN_PRODUCT_ID);
// Create cash margin account
const cashMarginAccount = await fineractSDK.savingsaccounts.create({
clientId: clientId,
productId: CASH_MARGIN_PRODUCT_ID,
submittedOnDate: "2024-07-28",
dateFormat: "yyyy-MM-dd",
locale: "en",
});
const cashMarginAccountId = cashMarginAccount.resourceId;
console.log("✓ Cash Margin Account Created with ID:", cashMarginAccountId);
// Approve cash margin account
await fineractSDK.savingsproducts.approve(cashMarginAccountId, {
approvedOnDate: "2024-07-28",
dateFormat: "yyyy-MM-dd",
locale: "en",
});
console.log("✓ Cash Margin Account Approved");
// Activate cash margin account
await fineractSDK.savingsproducts.activate(cashMarginAccountId, {
activatedOnDate: "2024-07-28",
dateFormat: "yyyy-MM-dd",
locale: "en",
});
console.log("✓ Cash Margin Account Activated");
console.log();
// Find RBF collection product ID
const rbfProduct = savingsProducts.find((product) => product.shortName === "RBF");
const RBF_COLLECTION_PRODUCT_ID = rbfProduct?.id || 3; // fallback to 3 if not found
console.log("Step 5: Creating RBF Collection Account with product ID:", RBF_COLLECTION_PRODUCT_ID);
// Create RBF collection account
const rbfCollectionAccount = await fineractSDK.savingsaccounts.create({
clientId: clientId,
productId: RBF_COLLECTION_PRODUCT_ID,
submittedOnDate: "2024-07-28",
dateFormat: "yyyy-MM-dd",
locale: "en",
});
const rbfCollectionAccountId = rbfCollectionAccount.resourceId;
console.log("✓ RBF Collection Account Created with ID:", rbfCollectionAccountId);
// Approve RBF collection account
await fineractSDK.savingsproducts.approve(rbfCollectionAccountId, {
approvedOnDate: "2024-07-28",
dateFormat: "yyyy-MM-dd",
locale: "en",
});
console.log("✓ RBF Collection Account Approved");
// Activate RBF collection account
await fineractSDK.savingsproducts.activate(rbfCollectionAccountId, {
activatedOnDate: "2024-07-28",
dateFormat: "yyyy-MM-dd",
locale: "en",
});
console.log("✓ RBF Collection Account Activated");
console.log();
// Step 6: Create Loan Account
console.log("Step 6: Creating Loan Account...");
// Get all loan products to find RBF product
const loanProducts = await fineractSDK.loanproducts.getAll();
const rbfLoanProduct = loanProducts.find((product) => product.externalId === "REVENUE_BASED_FINANCING");
const RBF_LOAN_PRODUCT_ID = rbfLoanProduct?.id || 1; // fallback to 1 if not found
const newLoan = await fineractSDK.loansaccounts.create({
productId: RBF_LOAN_PRODUCT_ID,
linkAccountId: rbfCollectionAccountId.toString(), // Link to the collection account created above
submittedOnDate: "2025-07-09",
expectedDisbursementDate: "2025-07-10",
loanTermFrequency: 3,
loanTermFrequencyType: 2, // Months
numberOfRepayments: 3,
repaymentEvery: 1,
repaymentFrequencyType: 2, // Months
interestType: 0, // Flat
amortizationType: 1, // Equal installments
interestCalculationPeriodType: 1,
transactionProcessingStrategyCode: "mifos-standard-strategy",
interestRatePerPeriod: 1, // 10%
dateFormat: "yyyy-MM-dd",
locale: "en",
clientId: clientId,
loanType: "individual",
principal: 100000, // 100,000 principal amount
datatables: [
{
registeredTableName: "dt_loan_remitter_dp_info",
data: {
locale: "en",
remitter_name: "",
dp_name: "",
},
},
],
});
console.log("✓ Loan Account Created successfully!");
console.log("Loan Details:", JSON.stringify(newLoan, null, 2));
console.log();
console.log("=== Complete SME Workflow Finished Successfully! ===");
console.log(`Client ID: ${clientId}`);
console.log(`Fallback Account ID: ${fallbackAccountId}`);
console.log(`Cash Margin Account ID: ${cashMarginAccountId}`);
console.log(`RBF Collection Account ID: ${rbfCollectionAccountId}`);
console.log(`Loan Account ID: ${newLoan.loanId || newLoan.resourceId}`);
}
catch (error) {
console.error("❌ Error in complete workflow:", error);
// Log detailed error information including validation errors
if (error instanceof Error && "details" in error) {
const fineractError = error;
console.log("=== Detailed Error Information ===");
console.log("Error Message:", fineractError.message);
console.log("Status Code:", fineractError.statusCode);
if (fineractError.details?.errors &&
Array.isArray(fineractError.details.errors)) {
console.log("\n=== Validation Errors ===");
fineractError.details.errors.forEach((validationError, index) => {
console.log(`Error ${index + 1}:`);
console.log(` Field: ${validationError.parameterName || "Unknown"}`);
console.log(` Value: ${validationError.value !== undefined
? validationError.value
: "N/A"}`);
console.log(` Message: ${validationError.defaultUserMessage ||
validationError.userMessageGlobalisationCode ||
"No message"}`);
console.log(` Code: ${validationError.userMessageGlobalisationCode || "No code"}`);
if (validationError.supportedParameters) {
console.log(` Supported Parameters: ${JSON.stringify(validationError.supportedParameters)}`);
}
console.log("---");
});
}
if (fineractError.details?.developerMessage) {
console.log("\nDeveloper Message:", fineractError.details.developerMessage);
}
}
throw error;
}
}
// completeWorkflowExample()
// .then(() => console.log("\nComplete workflow example finished."))
// .catch((e) => console.error("Unhandled error in complete workflow:", e));
// Example function to demonstrate the new deposit transaction endpoint
async function depositTransactionExample() {
console.log("=== Deposit Transaction Example ===\n");
try {
const accountId = 3873; // Replace with actual account ID
const depositData = {
transactionDate: "11 August 2025",
transactionAmount: 1000,
paymentTypeId: 1,
note: "this is 1000 deposit",
dateFormat: "dd MMMM yyyy",
locale: "en",
};
console.log(`Creating deposit transaction for account ${accountId}...`);
const depositResponse = await fineractSDK.savingsaccounts.deposit(accountId, depositData);
console.log("✓ Deposit transaction created successfully!");
console.log("Response:", JSON.stringify(depositResponse, null, 2));
}
catch (error) {
console.error("❌ Error creating deposit transaction:", error);
const fineractError = error;
if (fineractError.details) {
console.log("Error Details:", JSON.stringify(fineractError.details, null, 2));
}
}
}
// Uncomment the line below to run the deposit transaction example
// depositTransactionExample()
// .then(() => console.log("\nDeposit transaction example finished."))
// .catch((e) => console.error("Unhandled error in deposit example:", e));
// Example function to demonstrate the new transaction template endpoint
async function transactionTemplateExample() {
console.log("=== Transaction Template Example ===\n");
try {
const accountId = 3; // Replace with actual account ID
console.log(`Getting transaction template for account ${accountId}...`);
const templateResponse = await fineractSDK.savingsaccounts.getTransactionTemplate(accountId);
console.log("✓ Transaction template retrieved successfully!");
console.log("Response:", JSON.stringify(templateResponse, null, 2));
// Display available payment types
console.log("\nAvailable Payment Types:");
templateResponse.paymentTypeOptions.forEach((paymentType) => {
console.log(`- ID: ${paymentType.id}, Name: ${paymentType.name}, Description: ${paymentType.description}`);
});
}
catch (error) {
console.error("❌ Error getting transaction template:", error);
const fineractError = error;
if (fineractError.details) {
console.log("Error Details:", JSON.stringify(fineractError.details, null, 2));
}
}
}
// Uncomment the line below to run the transaction template example
// transactionTemplateExample()
// .then(() => console.log("\nTransaction template example finished."))
// .catch((e) => console.error("Unhandled error in template example:", e));
// Example function to demonstrate the new holidays endpoint
async function holidaysExample() {
console.log("=== Holidays Example ===\n");
try {
console.log("Getting holidays for office ID 1...");
const officeHolidays = await fineractSDK.holidays.getHolidaysByOffice(1);
console.log("✓ Office holidays retrieved successfully!");
console.log(`Found ${officeHolidays.length} holidays for office 1`);
console.log("Response:", JSON.stringify(officeHolidays, null, 2));
// Display holiday summary
if (officeHolidays.length > 0) {
console.log("\nHoliday Summary:");
officeHolidays.forEach((holiday) => {
const fromDate = `${holiday.fromDate[0]}-${holiday.fromDate[1]
.toString()
.padStart(2, "0")}-${holiday.fromDate[2]
.toString()
.padStart(2, "0")}`;
const toDate = `${holiday.toDate[0]}-${holiday.toDate[1]
.toString()
.padStart(2, "0")}-${holiday.toDate[2].toString().padStart(2, "0")}`;
console.log(`- ${holiday.name}: ${fromDate} to ${toDate} (Status: ${holiday.status.value})`);
});
}
}
catch (error) {
console.error("❌ Error getting holidays:", error);
const fineractError = error;
if (fineractError.details) {
console.log("Error Details:", JSON.stringify(fineractError.details, null, 2));
}
}
}
// Uncomment the line below to run the holidays example
// holidaysExample()
// .then(() => console.log("\nHolidays example finished."))
// .catch((e) => console.error("Unhandled error in holidays example:", e));
// Example function to demonstrate the working days endpoint
async function workingDaysExample() {
console.log("=== Working Days Example ===\n");
try {
console.log("Getting working days configuration...");
const workingDays = await fineractSDK.workingdays.getWorkingDays();
console.log("✓ Working days retrieved successfully!");
console.log("Response:", JSON.stringify(workingDays, null, 2));
// Process working days information
console.log("\nWorking Days Analysis:");
const workingDayNames = Object.entries(workingDays)
.filter(([day, isWorking]) => isWorking)
.map(([day]) => day);
const nonWorkingDays = Object.entries(workingDays)
.filter(([day, isWorking]) => !isWorking)
.map(([day]) => day);
console.log(`Working days: ${workingDayNames.join(", ")}`);
console.log(`Non-working days: ${nonWorkingDays.join(", ")}`);
console.log(`Total working days per week: ${workingDayNames.length}`);
// Check specific days
if (workingDays.Saturday || workingDays.Sunday) {
console.log("Note: Weekend days are included as working days");
}
else {
console.log("Note: Standard Monday-Friday working week");
}
}
catch (error) {
console.error("❌ Error getting working days:", error);
const fineractError = error;
if (fineractError.details) {
console.log("Error Details:", JSON.stringify(fineractError.details, null, 2));
}
}
}
// Uncomment the line below to run the working days example
// workingDaysExample()
// .then(() => console.log("\nWorking days example finished."))
// .catch((e) => console.error("Unhandled error in working days example:", e));
// Example function to demonstrate the charges endpoint
async function chargesExample() {
console.log("=== Charges Example ===\n");
try {
console.log("Getting all available charges...");
const allCharges = await fineractSDK.creditlines.getCharges();
console.log("✓ All charges retrieved successfully!");
console.log(`Found ${allCharges.length} total charges`);
console.log();
console.log("Getting charges applicable to credit lines...");
const creditLineCharges = await fineractSDK.creditlines.getCreditLineCharges();
console.log("✓ Credit line charges retrieved successfully!");
console.log(`Found ${creditLineCharges.length} credit line applicable charges`);
console.log();
// Display first few charges as example
console.log("Sample Credit Line Charges:");
const sampleCharges = creditLineCharges.slice(0, 3);
for (let index = 0; index < sampleCharges.length; index++) {
const charge = sampleCharges[index];
console.log(`${index + 1}. ${charge.name} (ID: ${charge.id})`);
console.log(` Amount: ${charge.amount} ${charge.currency.code}`);
console.log(` Type: ${charge.chargeCalculationType.value}`);
console.log(` Active: ${charge.active ? "Yes" : "No"}`);
}
// Filter for specific charge types
const activationCharges = creditLineCharges.filter((charge) => charge.chargeTimeType.code === "chargeTimeType.lineOfCreditActivation");
console.log(`\nFound ${activationCharges.length} LOC activation charges`);
// Prepare charges for credit line creation
const selectedCharges = creditLineCharges
.filter((charge) => charge.chargeAppliesTo.code === "chargeAppliesTo.lineOfCredit")
.slice(0, 2)
.map((charge) => ({ ...charge, editableAmount: charge.amount }));
console.log(`\nSelected ${selectedCharges.length} charges for credit line creation`);
console.log("These charges can be used in CreateCreditLineRequest.charges array");
}
catch (error) {
console.error("❌ Error getting charges:", error);
const fineractError = error;
if (fineractError.details) {
console.log("Error Details:", JSON.stringify(fineractError.details, null, 2));
}
}
}
// Uncomment the line below to run the charges example
// chargesExample()
// .then(() => console.log("\nCharges example finished."))
// .catch((e) => console.error("Unhandled error in charges example:", e));
// Example function to demonstrate the credit lines endpoint
async function creditLinesExample() {
console.log("=== Credit Lines Example ===\n");
try {
const clientId = 4931; // Replace with actual client ID
// Step 1: Get template options to select deterministic values
console.log("Getting credit line template options...");
const cashMarginTypeOptions = await fineractSDK.creditlines.getCreditLineCashMarginTypeOptions(clientId);
const productTypeOptions = await fineractSDK.creditlines.getCreditLineProductTypeOptions(clientId);
const reviewPeriodOptions = await fineractSDK.creditlines.getCreditLineReviewPeriodOptions(clientId);
const interestChargeTimeOptions = await fineractSDK.creditlines.getCreditLineInterestChargeTimeOptions(clientId);
const loanOfficers = await fineractSDK.creditlines.getCreditLineLoanOfficers(clientId);
console.log("✓ Template options retrieved successfully!");
console.log(`Found ${cashMarginTypeOptions.length} cash margin type options`);
console.log(`Found ${productTypeOptions.length} product type options`);
console.log(`Found ${reviewPeriodOptions.length} review period options`);
console.log(`Found ${interestChargeTimeOptions.length} interest charge time options`);
console.log(`Found ${loanOfficers.length} loan officers`);
// Step 2: Get available charges for credit lines
console.log("\nGetting available charges for credit lines...");
const availableCharges = await fineractSDK.creditlines.getCreditLineCharges();
console.log("✓ Credit line charges retrieved successfully!");
console.log(`Found ${availableCharges.length} applicable charges`);
// Step 3: Filter and select template values based on business requirements
console.log("\nSelecting template values for credit line creation...");
// Select product type - looking for "RECEIVABLE" (ID: 1 in current data)
const selectedProductType = productTypeOptions.find((option) => option.code === "RECEIVABLE" || option.id === 1) || productTypeOptions[0]; // fallback to first option
// Select cash margin type - looking for "PERCENTAGE" (ID: 1 in current data)
const selectedCashMarginType = cashMarginTypeOptions.find((option) => option.code === "PERCENTAGE" || option.id === 1) || cashMarginTypeOptions[0];
// Select review period - looking for 6 months (ID: 6 in current data)
const selectedReviewPeriod = reviewPeriodOptions.find((option) => option.code === "locreviewperiod.6months" || option.id === 6) ||
reviewPeriodOptions.find((option) => option.id === 6) ||
reviewPeriodOptions[0];
// Select interest charge time - looking for "UPFRONT" (ID: 1 in current data)
const selectedInterestChargeTime = interestChargeTimeOptions.find((option) => option.code === "UPFRONT" || option.id === 1) || interestChargeTimeOptions[0];
// Select active loan officer (ID: 1 in current data)
const selectedLoanOfficer = loanOfficers.find((officer) => officer.isActive && officer.isLoanOfficer && officer.id === 1) ||
loanOfficers.find((officer) => officer.isActive && officer.isLoanOfficer) ||
loanOfficers[0];
// Select charges for the credit line (activation charges)
const selectedCharges = availableCharges
.filter((charge) => charge.active &&
charge.chargeTimeType.code === "chargeTimeType.lineOfCreditActivation")
.slice(0, 2) // Take first 2 activation charges
.map((charge) => ({
...charge,
editableAmount: charge.amount, // Use original amount as editable amount
}));
console.log("Selected template values:");
console.log(`- Product Type: ${selectedProductType?.value} (ID: ${selectedProductType?.id})`);
console.log(`- Cash Margin Type: ${selectedCashMarginType?.value} (ID: ${selectedCashMarginType?.id})`);
console.log(`- Review Period: ${selectedReviewPeriod?.value} (ID: ${selectedReviewPeriod?.id})`);
console.log(`- Interest Charge Time: ${selectedInterestChargeTime?.value} (ID: ${selectedInterestChargeTime?.id})`);
console.log(`- Loan Officer: ${selectedLoanOfficer?.displayName} (ID: ${selectedLoanOfficer?.id})`);
console.log(`- Selected ${selectedCharges.length} charges for credit line creation`);
if (selectedCharges.length > 0) {
console.log("Selected charges:");
for (const charge of selectedCharges) {
console.log(` - ${charge.name}: ${charge.amount} ${charge.currency.code}`);
}
}
// Step 4: Create credit line with template-derived values
const creditLineData = {
productType: selectedProductType?.id || 1,
currencyCode: "AED",
clientCompanyName: "Test Company Ltd",
clientContactPersonName: "John Doe",
clientContactPersonPhone: "0501234567",
clientContactPersonEmail: "john.doe@testcompany.com",
authorizedSignatoryName: "Jane Smith",
authorizedSignatoryPhone: "0507654321",
authorizedSignatoryEmail: "jane.smith@testcompany.com",
virtualAccount: "VA2000",
externalId: "CL-TEST-001",
specialConditions: "Test credit line with standard terms",
maxCreditLimit: "1000000",
reviewPeriod: selectedReviewPeriod?.id || 6,
interimReviewDate: "15 June 2026",
annualInterestRate: 120, // in percentage
tenorDays: 365,
advancePercentage: "85",
cashMarginType: selectedCashMarginType?.id || 1,
cashMarginValue: 15,
interestChargeTime: selectedInterestChargeTime?.id || 1,
loanOfficerId: selectedLoanOfficer?.id || 1,
distributionPartner: "Test Distribution Partner",
approvedBuyers: [
{ name: "Approved Buyer One" },
{ name: "Approved Buyer Two" },
],
settlementSavingsAccountId: null, // No settlement account
charges: selectedCharges, // Use template-derived charges
dateFormat: "dd MMMM yyyy",
locale: "en",
};
console.log(`\nCreating credit line for client ${clientId} with template-derived values...`);
const response = await fineractSDK.creditlines.createCreditLine(clientId, creditLineData);
console.log("✓ Credit line created successfully!");
console.log("Response:", JSON.stringify(response, null, 2));
// Display key information from response
console.log(`Credit Line Resource ID: ${response.resourceId}`);
}
catch (error) {
console.error("❌ Error creating credit line:", error);
const fineractError = error;
if (fineractError.details) {
console.log("Error Details:", JSON.stringify(fineractError.details, null, 2));
}
}
}
// Uncomment the line below to run the credit lines example
// creditLinesExample()
// .then(() => console.log("\nCredit lines example finished."))
// .catch((e) => console.error("Unhandled error in credit lines example:", e));
// Example function to demonstrate the credit line template endpoint
async function creditLineTemplateExample() {
console.log("=== Credit Line Template Example ===\n");
try {
const clientId = 6029; // Replace with actual client ID
console.log("Getting full credit line template...");
const template = await fineractSDK.creditlines.getCreditLineTemplate(clientId);
console.log("✓ Credit line template retrieved successfully!");
console.log("Template response:", JSON.stringify(template, null, 2));
console.log("\nGetting specific template options...");
// Get cash margin type options
const cashMarginTypeOptions = await fineractSDK.creditlines.getCreditLineCashMarginTypeOptions(clientId);
console.log("Cash Margin Type Options:");
for (const option of cashMarginTypeOptions) {
console.log(`- ID: ${option.id}, Code: ${option.code}, Value: ${option.value}`);
}
// Get product type options
const productTypeOptions = await fineractSDK.creditlines.getCreditLineProductTypeOptions(clientId);
console.log("\nProduct Type Options:");
for (const option of productTypeOptions) {
console.log(`- ID: ${option.id}, Code: ${option.code}, Value: ${option.value}`);
}
// Get review period options
const reviewPeriodOptions = await fineractSDK.creditlines.getCreditLineReviewPeriodOptions(clientId);
console.log("\nReview Period Options:");
for (const option of reviewPeriodOptions) {
console.log(`- ID: ${option.id}, Code: ${option.code}, Value: ${option.value}`);
}
// Get interest charge time options
const interestChargeTimeOptions = await fineractSDK.creditlines.getCreditLineInterestChargeTimeOptions(clientId);
console.log("\nInterest Charge Time Options:");
for (const option of interestChargeTimeOptions) {
console.log(`- ID: ${option.id}, Code: ${option.code}, Value: ${option.value}`);
}
// Get loan officers
const loanOfficers = await fineractSDK.creditlines.getCreditLineLoanOfficers(clientId);
console.log("\nLoan Officers:");
for (const officer of loanOfficers) {
console.log(`- ID: ${officer.id}, Name: ${officer.displayName}, Office: ${officer.officeName}`);
console.log(` Active: ${officer.isActive}, Loan Officer: ${officer.isLoanOfficer}`);
}
// Demonstrate deterministic value selection
console.log("\nUsing template options for deterministic credit line creation:");
const selectedCashMarginType = cashMarginTypeOptions.find((option) => option.code === "PERCENTAGE");
const selectedProductType = productTypeOptions.find((option) => option.code === "RECEIVABLE");
const selectedReviewPeriod = reviewPeriodOptions.find((option) => option.code === "locreviewperiod.6months");
console.log(`Selected Cash Margin Type: ${selectedCashMarginType?.value} (ID: ${selectedCashMarginType?.id})`);
console.log(`Selected Product Type: ${selectedProductType?.value} (ID: ${selectedProductType?.id})`);
console.log(`Selected Review Period: ${selectedReviewPeriod?.value} (ID: ${selectedReviewPeriod?.id})`);
console.log("\nThese IDs can now be used in CreateCreditLineRequest with confidence!");
}
catch (error) {
console.error("❌ Error getting credit line template:", error);
const fineractError = error;
if (fineractError.details) {
console.log("Error Details:", JSON.stringify(fineractError.details, null, 2));
}
}
}
// Uncomment the line below to run the credit line template example
// creditLineTemplateExample()
// .then(() => console.log("\nCredit line template example finished."))
// .catch((e) => console.error("Unhandled error in template example:", e));
// ===== Reports Example =====
async function getLoanPaymentsDue() {
console.log("Loan payments due ===\n");
const start = Date.now();
try {
// Only pass dynamic filters; officeId and loanOfficerId are auto-injected (1, -1)
const params = {
fromInstallment: 2,
toInstallment: 2,
};
console.log("[Loan payments due] Sending request...");
const report = await fineractSDK.reports.getLoanPaymentsDue(params);
console.log("✓ Loan payments due fetched successfully");
console.log("First 5 rows:", JSON.stringify(report.data.slice(0, 5), null, 2));
console.log(`[Loan payments due] Completed in ${Date.now() - start}ms`);
}
catch (error) {
console.error("❌ Error fetching Loan payments due:", error);
const fineractError = error;
if (fineractError.details) {
console.log("Error Details:", JSON.stringify(fineractError.details, null, 2));
}
console.log(`[Loan payments due] Failed after ${Date.now() - start}ms`);
}
}
// Uncomment to run the report example
// getLoanPaymentsDue()
// .then(() => console.log("\nLoan Payments Due example finished."))
// .catch((e) => console.error("Unhandled error in Loan Payments Due example:", e));
async function getLoanPaymentsDueOverdue() {
console.log("=== Loan payments due (Overdue Loans) ===\n");
const start = Date.now();
try {
// officeId and loanOfficerId auto-injected
const params = {
fromInstallment: 0,
toInstallment: 30,
overdueFromDays: 0,
overdueToDays: 90,
};
console.log("[Loan payments due (Overdue Loans)] Sending request...");
const report = await fineractSDK.reports.getLoanPaymentsDueOverdue(params);
console.log("✓ Loan payments due (Overdue Loans) fetched successfully");
console.log("First 5 overdue rows:", JSON.stringify(report.data.slice(0, 5), null, 2));
console.log(`[Loan payments due (Overdue Loans)] Completed in ${Date.now() - start}ms`);
}
catch (error) {
console.error("❌ Error fetching Loan payments due (Overdue Loans):", error);
const fineractError = error;
if (fineractError.details) {
console.log("Error Details:", JSON.stringify(fineractError.details, null, 2));
}
console.log(`[Loan payments due (Overdue Loans)] Failed after ${Date.now() - start}ms`);
}
}
// Uncomment to run the overdue report example
// getLoanPaymentsDueOverdue()
// .then(() => console.log("\nLoan payments due (Overdue Loans) example finished."))
// .catch((e) => console.error("Unhandled error in Loan payments due (Overdue Loans) example:", e));
async function getExpectedPaymentsByDateBasic() {
console.log("=== Expected Payments By Date - Basic ===\n");
const start = Date.now();
try {
// officeId and loanOfficerId auto-injected
const params = {
startDate: "2025-02-04",
endDate: "2025-10-23",
locale: "en",
dateFormat: "yyyy-MM-dd",
};
console.log("[Expected Payments By Date - Basic] Sending request...");
const report = await fineractSDK.reports.getExpectedPaymentsByDateBasic(params);
console.log("✓ Expected Payments By Date - Basic fetched successfully");
console.log("First 5 expected payment rows:", JSON.stringify(report.data.slice(0, 5), null, 2));
console.log(`[Expected Payments By Date - Basic ] Completed in ${Date.now() - start}ms`);
}
catch (error) {
console.error("❌ Error fetching Expected Payments By Date - Basic:", error);
const fineractError = error;
if (fineractError.details) {
console.log("Error Details:", JSON.stringify(fineractError.details, null, 2));
}
console.log(`[Expected Payments By Date - Basic] Failed after ${Date.now() - start}ms`);
}
}
/**
* Get all credit lines for a client
*/
async function getCreditLinesForClient() {
try {
console.log("\n--- Getting Credit Lines for Client ---");
const clientId = 6196; // Replace with actual client ID
console.log(`Fetching credit lines for client ${clientId}...`);
const creditLines = await fineractSDK.creditlines.getCreditLines(clientId);
if (creditLines.length === 0) {
console.log("No credit lines found for this client.");
return;
}
console.log(`Found ${creditLines.length} credit line(s):`);
for (const [index, creditLineWithLoans] of creditLines.entries()) {
const creditLine = creditLineWithLoans.lineOfCredit;
console.log(`\n${index + 1}. Credit Line ID: ${creditLine.id}`);
console.log(` Account Number: ${creditLine.accountNumber || "N/A"}`);
console.log(` Maximum Amount: ${creditLine.maximumAmount}`);
console.log(` Available Balance: ${creditLine.availableBalance}`);
console.log(` Status: ${creditLine.status?.value || "Unknown"}`);
if (creditLineWithLoans.loans && creditLineWithLoans.loans.length > 0) {
console.log(` Associated Loans (${creditLineWithLoans.loans.length}):`);
for (const [loanIndex, loan] of creditLineWithLoans.loans.entries()) {
console.log(` ${loanIndex + 1}. Loan #${loan.accountNo} - ${loan.productName || "Unknown Product"}`);
console.log(` Loan Balance: ${loan.loanBalance || 0}`);
console.log(` Status: ${loan.status?.value || "Unknown"}`);
console.log(` In Arrears: ${loan.inArrears ? "Yes" : "No"}`);
}
}
else {
console.log(" No associated loans.");
}
}
console.log("\nCredit lines retrieval completed successfully!");
}
catch (error) {
console.error("Error getting credit lines:", error);
throw error;
}
}
// Uncomment to run expected payments by date basic report
// getExpectedPaymentsByDateBasic()
// .then(() => console.log("\nExpected Payments By Date - Basic example finished."))
// .catch((e) => console.error("Unhandled error in Expected Payments By Date - Basic example:", e));
// Uncomment to run credit lines listing example
// getCreditLinesForClient()
// .then(() => console.log("\nCredit Lines listing example finished."))
// .catch((e) =>
// console.error("Unhandled error in Credit Lines listing example:", e)
// );
//# sourceMappingURL=run-examples.js.map