# Mambu Toolkit Updated

A ready-to-use SDK for the **Mambu Banking API**.  
This toolkit lets you connect to Mambu's banking platform from any Node.js or NestJS project with just a few lines of code.
---

## What Can It Do?

This toolkit gives you access to **77 Mambu API resources** covering the entire Mambu Banking platform:

| Category                | Resources                                                                                                                                                                                                                                                                                                         |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Core Banking**        | Clients, Loans, Deposits, Branches, Centres, Groups, Users                                                                                                                                                                                                                                                        |
| **Products**            | Loan Products, Deposit Products                                                                                                                                                                                                                                                                                   |
| **Transactions**        | Loan Transactions, Deposit Transactions (sync & async)                                                                                                                                                                                                                                                            |
| **Documents**           | Client Documents, Loan Documents, Deposit Documents, General Documents                                                                                                                                                                                                                                            |
| **Scheduling**          | Loan Schedules, Loan Tranches, Installments, Planned Fees                                                                                                                                                                                                                                                         |
| **Cards & Auth**        | Cards, Authorization Holds                                                                                                                                                                                                                                                                                        |
| **Credit Arrangements** | Credit Arrangements (CRUD + search)                                                                                                                                                                                                                                                                               |
| **Accounting**          | GL Accounts, Journal Entries, Interest Accrual, Accounting Reports                                                                                                                                                                                                                                                |
| **Currencies**          | Currencies, Exchange Rates, Accounting Rates                                                                                                                                                                                                                                                                      |
| **Configuration (20+)** | Accounting Rules, Branches, Centres, Client Roles, Currencies, Custom Fields, Deposit Products, End-of-Day Processing, Group Roles, Holidays, ID Document Templates, Index Rates, Internal Controls, Labels, Loan Products, Loan Risk Levels, Organization, Transaction Channels, User Roles, Authorization Holds |
| **Organization**        | Holidays, General Holidays, Non-Working Days, ID Document Templates, Transaction Channels                                                                                                                                                                                                                         |
| **Custom Fields**       | Custom Fields, Custom Field Sets                                                                                                                                                                                                                                                                                  |
| **Operations**          | Crons (EOD & Early EOD), Background Process, Bulks, Database Backup                                                                                                                                                                                                                                               |
| **Integration**         | API Consumers, API Key Rotation, Subscriptions, Streaming, Webhooks, Extension Points                                                                                                                                                                                                                             |
| **Setup & Templates**   | General Setup, Organization Setup, Templates, Process Definitions                                                                                                                                                                                                                                                 |
| **Other**               | Comments, Tasks, Communications, Funding Sources, User Roles, Index Rate Sources                                                                                                                                                                                                                                  |

---

## � Features

- **Complete TypeScript SDK**: Full type safety with auto-generated types from Mambu OpenAPI specifications
- **Comprehensive API Coverage**: Support for all 77 Mambu API resources including loans, deposits, clients, and more
- **NestJS Native**: Built as a first-class NestJS module with dependency injection, global modules, and async configuration
- **Multi-Tenant Support**: Register multiple named Mambu instances with `forFeature()` for multi-tenant applications
- **Modular Architecture**: Each Mambu service is available as a separate accessor with clean interfaces
- **Zero Configuration Hassle**: Simple setup with domain and API key via `forRoot()` or `forRootAsync()`
- **Production Ready**: Optimized builds, comprehensive error handling, and auto-generated from official Mambu OpenAPI specs

---

## 📦 Installation

Install the package using npm, yarn, or pnpm:

```bash
npm install mambu-toolkit-updated
# or
yarn add mambu-toolkit-updated
# or
pnpm add mambu-toolkit-updated
```

---

## 🚀 Quick Start

```typescript
import { Module } from '@nestjs/common';
import { MambuModule } from 'mambu-toolkit-updated';

@Module({
  imports: [
    MambuModule.forRoot({
      domain: 'https://your-tenant.mambu.com/api',
      apiKey: 'YOUR_MAMBU_API_KEY',
    }),
  ],
})
export class AppModule {}
```

Then inject `MambuService` anywhere in your application:

```typescript
import { Injectable } from '@nestjs/common';
import { MambuService } from 'mambu-toolkit-updated';

@Injectable()
export class YourService {
  constructor(private readonly mambu: MambuService) {}

  async getLoanProduct(id: string) {
    return this.mambu.loanProducts.getById(id);
  }
}
```

---

## 📚 Usage Guide

### Configuration

#### Basic (Static)

```typescript
MambuModule.forRoot({
  domain: 'https://your-tenant.mambu.com/api',
  apiKey: 'YOUR_MAMBU_API_KEY',
});
```

#### Async Configuration

For dynamic environments (e.g., loading from ConfigService):

```typescript
import { ConfigModule, ConfigService } from '@nestjs/config';

MambuModule.forRootAsync({
  useFactory: (config: ConfigService) => ({
    domain: config.get<string>('MAMBU_DOMAIN'),
    apiKey: config.get<string>('MAMBU_API_KEY'),
  }),
  inject: [ConfigService],
});
```

#### Multi-Tenant Support

Register multiple named Mambu instances:

```typescript
@Module({
  imports: [
    MambuModule.forFeature('tenantA', {
      domain: 'https://tenant-a.mambu.com/api',
      apiKey: 'TENANT_A_KEY',
    }),
    MambuModule.forFeature('tenantB', {
      domain: 'https://tenant-b.mambu.com/api',
      apiKey: 'TENANT_B_KEY',
    }),
  ],
})
export class MultiTenantModule {}
```

Inject named instances with the `@InjectMambu` decorator:

```typescript
import { Injectable } from '@nestjs/common';
import { InjectMambu } from 'mambu-toolkit-updated';
import { MambuService } from 'mambu-toolkit-updated';

@Injectable()
export class TenantService {
  constructor(
    @InjectMambu('tenantA') private readonly mambuA: MambuService,
    @InjectMambu('tenantB') private readonly mambuB: MambuService,
  ) {}
}
```

---

### Available Services

All Mambu API services are available as properties on the `MambuService` instance:

#### Loan Management

```typescript
// Loan Products
const loanProduct = await this.mambu.loanProducts.getById('product-id');

// Loan Accounts
const loanAccount = await this.mambu.loans.getById('account-id');

// Loan Transactions
const repayment = await this.mambu.loanTransactions.makeRepayment('account-id', {
  amount: 500,
  notes: 'Monthly repayment',
});

// Loan Schedule
const schedule = await this.mambu.loanSchedule.getScheduleForLoanAccount('account-id');
```

#### Deposit Management

```typescript
// Deposit Accounts
const depositAccount = await this.mambu.deposits.getById('account-id');

// Deposit Transactions
const withdrawal = await this.mambu.depositTransactions.makeWithdrawal('account-id', {
  amount: 500,
  notes: 'Withdrawal transaction',
});

const transfer = await this.mambu.depositTransactions.makeTransfer('account-id', {
  amount: 1000,
  transferDetails: {
    linkedAccountKey: 'target-account-key',
  },
});

// Async Deposit Transactions
const asyncDeposit = await this.mambu.depositTransactionAsync.makeDepositAsync('account-id', {
  amount: 2000,
  notes: 'Async deposit',
});
```

#### Client Management

```typescript
// Clients
const client = await this.mambu.clients.getById('client-id');
const allClients = await this.mambu.clients.getAll();
const searchResults = await this.mambu.clients.search(searchCriteria);

// Client Documents
const documents = await this.mambu.clientDocuments.getDocumentsByClientId('client-id');
```

#### Credit Arrangements

```typescript
// Credit Arrangements
const arrangement = await this.mambu.creditArrangements.getById('arrangement-id');
const accounts = await this.mambu.creditArrangements.getAllAccounts('arrangement-id');

// Search
const results = await this.mambu.creditArrangementsSearch.search(criteria);
```

#### Configuration & Administration

```typescript
// Branches
const branches = await this.mambu.branches.getAll();

// Custom Fields
const customField = await this.mambu.customFields.getById('field-id');

// Users
const users = await this.mambu.users.getAll();

// Configuration APIs (20+ available)
const orgConfig = await this.mambu.configOrganization.get();
const loanProductConfig = await this.mambu.configLoanProducts.get();
```

#### Accounting & GL

```typescript
// GL Accounts
const glAccounts = await this.mambu.glAccounts.getAll();

// Journal Entries
const entries = await this.mambu.journalEntries.getAll();
await this.mambu.journalEntries.create(journalEntryData);

// Interest Accrual
const accruals = await this.mambu.accountingInterestAccrual.search(criteria);
```

#### Operations & Integration

```typescript
// Database Backup
await this.mambu.databaseBackup.triggerBackup();

// API Consumers
const consumers = await this.mambu.apiConsumers.getAll();

// Subscriptions (Event Streaming)
const subscription = await this.mambu.subscriptions.createOrGetSubscription(subData);

// End-of-Day Crons
await this.mambu.cronsEod.runHourlyAndEndOfDayCrons();
```

### Type Safety

Import models from their respective SDK modules for full type safety:

```typescript
import { MambuService } from 'mambu-toolkit-updated';

// Models are available from individual SDK imports
import { LoanAccount } from 'mambu-toolkit-updated/dist/mambu-sdk/loans/models';
import { DepositAccount } from 'mambu-toolkit-updated/dist/mambu-sdk/deposits/models';
import { Client } from 'mambu-toolkit-updated/dist/mambu-sdk/clients/models';
```

---

## �🔧 API Reference

### Core Services

| Service     | Description          | Key Methods                                                                                                                        |
| ----------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `clients`   | Client management    | `getAll`, `getById`, `create`, `update`, `patch`, `_delete`, `search`, `getRoleByClientId`, `getCreditArrangementsByClientIdOrKey` |
| `branches`  | Branch management    | `getAll`, `getById`, `create`                                                                                                      |
| `centres`   | Centre management    | `getAll`, `getById`                                                                                                                |
| `groups`    | Group management     | `getAll`, `getById`, `create`, `update`, `patch`, `_delete`, `search`, `getCreditArrangementsByGroupIdOrKey`                       |
| `users`     | User management      | `getAll`, `getById`, `create`, `update`, `patch`, `_delete`                                                                        |
| `userRoles` | User role management | `getAll`, `getById`, `create`, `update`, `patch`, `_delete`                                                                        |

### Loan Services

| Service               | Description                 | Key Methods                                                                                                                                                                                                                                                                                |
| --------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `loans`               | Loan account operations     | See [Detailed Loans API Reference](#loans-service-api-reference) below                                                                                                                                                                                                                     |
| `loansSearch`         | Loan account search         | `search`                                                                                                                                                                                                                                                                                   |
| `loanProducts`        | Loan product management     | `getAll`, `getById`, `create`, `update`, `patch`, `_delete`                                                                                                                                                                                                                                |
| `loanTransactions`    | Loan transaction processing | `getAll`, `getById`, `search`, `makeRepayment`, `makeDisbursement`, `applyFee`, `makeRefund`, `makePrincipalOverpayment`, `makeWithdrawal`, `makeRedrawRepayment`, `makeDepositOnCreditBalance`, `applyPaymentMade`, `applyLock`, `applyUnlock`, `adjust`, `getTransactionsForAllVersions` |
| `loanSchedule`        | Loan schedule management    | `getScheduleForLoanAccount`, `editSchedule`, `previewSchedule`, `previewProcessPMTTransactionally`, `previewTranchesOnSchedule`                                                                                                                                                            |
| `loanTranches`        | Loan tranche management     | `getTranches`, `editTranches`                                                                                                                                                                                                                                                              |
| `loanBalances`        | Loan balance operations     | `getBalancesByLoanAccountId`, `applyBalanceInterest`                                                                                                                                                                                                                                       |
| `loanDocuments`       | Loan document access        | `getLoanAccountDocument`, `getPdfDocument`                                                                                                                                                                                                                                                 |
| `loanFunding`         | Loan funding sources        | `createLoanAccountFundingSources`, `updateLoanAccountFundingSources`, `deleteFundingSources`, `deleteSingleFundingSource`, `patchFundingSource`                                                                                                                                            |
| `loanPlannedFees`     | Planned fee management      | `getAllPlannedFees`, `createPlannedFees`, `updatePlannedFees`, `deletePlannedFees`, `applyPlannedFees`                                                                                                                                                                                     |
| `loanSchedulePreview` | Schedule preview            | `getPreviewLoanAccountSchedule`                                                                                                                                                                                                                                                            |
| `collateralAssets`    | Collateral management       | `reevaluateCollateralAssets`                                                                                                                                                                                                                                                               |

### Deposit Services

| Service                       | Description                    | Key Methods                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| ----------------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `deposits`                    | Deposit account operations     | `getAll`, `getById`, `create`, `update`, `patch`, `_delete`, `search`, `changeState`, `changeInterestRate`, `changeWithholdingTax`, `applyInterest`, `reopen`, `startMaturity`, `undoMaturity`, `transferOwnership`, `bulkUpdateAccounts`, `createAuthorizationHold`, `reverseAuthorizationHold`, `getAllAuthorizationHolds`, `getAuthorizationHoldById`, `createBlockFund`, `patchBlockFund`, `unblockFund`, `getAllBlocks`, `createCard`, `deleteCard`, `getAllCards`, `getFundedLoans`, `getWithholdingTaxHistory` |
| `depositProducts`             | Deposit product management     | `getAll`, `getById`, `create`, `update`, `patch`, `_delete`, `batchUpdate`                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `depositTransactions`         | Deposit transaction processing | `getAll`, `getById`, `search`, `makeDeposit`, `makeWithdrawal`, `makeTransfer`, `makeBulkDeposits`, `makeSeizure`, `applyFee`, `adjust`, `editTransactionDetails`                                                                                                                                                                                                                                                                                                                                                     |
| `depositTransactionAsync`     | Async deposit transactions     | `makeDepositAsync`, `makeWithdrawalAsync`                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `depositTransactionDocuments` | Transaction documents          | `getDepositTransactionDocument`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `depositBalances`             | Deposit balance retrieval      | `getBalances`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `depositBalanceSummary`       | Balance summary & search       | `getAll`, `search`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `depositDocuments`            | Deposit document access        | `getDepositAccountDocument`, `getPdfDocument`                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `depositInterestAvailability` | Interest availability          | `getInterestAvailabilitiesList`, `getInterestAvailabilityById`, `createInterestAvailability`, `updateInterestAvailability`, `deleteInterestAvailability`, `makeBulkInterestAccountSettingsAvailabilities`                                                                                                                                                                                                                                                                                                             |
| `fundedLoanAccounts`          | Funded loan accounts           | `getScheduleForFundedAccount`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |

### Document Services

| Service           | Description                 | Key Methods                                                                                      |
| ----------------- | --------------------------- | ------------------------------------------------------------------------------------------------ |
| `clientDocuments` | Client document management  | `getDocumentsByClientId`, `getClientDocumentById`, `getClientDocumentFileById`, `createDocument` |
| `documents`       | General document management | `createDocument`, `downloadDocumentById`, `deleteDocumentById`, `getDocumentsByEntityId`         |

### Credit & Accounting Services

| Service                     | Description                   | Key Methods                                                                                                                                |
| --------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `creditArrangements`        | Credit arrangement management | `getAll`, `getById`, `create`, `update`, `patch`, `_delete`, `changeState`, `addAccount`, `removeAccount`, `getAllAccounts`, `getSchedule` |
| `creditArrangementsSearch`  | Credit arrangement search     | `search`                                                                                                                                   |
| `glAccounts`                | General ledger accounts       | `getAll`, `getById`, `create`, `patch`                                                                                                     |
| `journalEntries`            | GL journal entries            | `getAll`, `create`, `search`                                                                                                               |
| `accountingInterestAccrual` | Interest accrual search       | `search`                                                                                                                                   |
| `accountingReports`         | Accounting reports            | `create`, `get`                                                                                                                            |
| `accountingRates`           | Currency accounting rates     | `getAll`, `create`                                                                                                                         |

### Currency & Rate Services

| Service            | Description                  | Key Methods                                                                                          |
| ------------------ | ---------------------------- | ---------------------------------------------------------------------------------------------------- |
| `currencies`       | Currency management          | `getAll`, `get`, `create`, `update`, `_delete`                                                       |
| `exchangeRates`    | Exchange rate management     | `getAll`, `create`                                                                                   |
| `indexRateSources` | Index rate source management | `getAllIndexRateSources`, `getIndexRateSourceById`, `createIndexRateSource`, `deleteIndexRateSource` |
| `indexRates`       | Index rate management        | `getAllIndexRates`, `createIndexRate`, `deleteIndexRate`                                             |

### Cards & Authorization

| Service | Description                 | Key Methods                                                                                                                                                                                                                                                          |
| ------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cards` | Card transaction processing | `createCardTransaction`, `getCardTransaction`, `reverseCardTransaction`, `createAuthorizationHold`, `getAuthorizationHoldById`, `increaseAuthorizationHold`, `decreaseAuthorizationHold`, `reverseAuthorizationHold`, `patchAuthorizationHold`, `getAccountBalances` |

### Custom Fields

| Service           | Description                 | Key Methods               |
| ----------------- | --------------------------- | ------------------------- |
| `customFields`    | Custom field retrieval      | `getById`                 |
| `customFieldSets` | Custom field set management | `getAll`, `getAllBySetId` |

### Configuration Services (20+ APIs)

All configuration services follow the pattern: `get()` to retrieve current config, `update()` to modify.

| Service                     | Description                                  |
| --------------------------- | -------------------------------------------- |
| `configAccountingRules`     | Accounting rules configuration               |
| `configAuthorizationHolds`  | Authorization holds configuration            |
| `configBranches`            | Branch configuration                         |
| `configCentres`             | Centre configuration                         |
| `configClientRoles`         | Client role configuration                    |
| `configCurrencies`          | Currency configuration                       |
| `configCustomFields`        | Custom field configuration (+ `getTemplate`) |
| `configDepositProducts`     | Deposit product configuration                |
| `configEndOfDayProcessing`  | End-of-day processing configuration          |
| `configGroupRoleNames`      | Group role names configuration               |
| `configHolidays`            | Holiday configuration                        |
| `configIdDocumentTemplates` | ID document template configuration           |
| `configIndexRates`          | Index rate configuration                     |
| `configInternalControls`    | Internal controls configuration              |
| `configLabels`              | Object labels configuration                  |
| `configLoanProducts`        | Loan product configuration                   |
| `configLoanRiskLevels`      | Loan risk levels configuration               |
| `configOrganization`        | Organization configuration (+ `getTemplate`) |
| `configTransactionChannels` | Transaction channels configuration           |
| `configUserRoles`           | User roles configuration (+ `getTemplate`)   |

### Organization Services

| Service               | Description           | Key Methods                                        |
| --------------------- | --------------------- | -------------------------------------------------- |
| `holidays`            | Organization holidays | `get`, `update`                                    |
| `generalHolidays`     | General holidays CRUD | `getByIdentifier`, `create`, `_delete`             |
| `nonWorkingDays`      | Non-working days      | `getNonWorkingDays`, `updateNonWorkingDays`        |
| `idDocumentTemplates` | ID document templates | `getAll`                                           |
| `transactionChannels` | Transaction channels  | `getAll`, `getById`, `create`, `update`, `_delete` |
| `installments`        | Installment retrieval | `getAll`                                           |

### Operations & Integration Services

| Service                | Description                   | Key Methods                                                                                                                                                            |
| ---------------------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cronsEod`             | End-of-day crons              | `runHourlyAndEndOfDayCrons`                                                                                                                                            |
| `cronsEarlyEod`        | Early EOD crons               | `runEarlierHourlyAndEndOfDayCrons`                                                                                                                                     |
| `backgroundProcess`    | Background processes          | `getLatestByType`, `update`                                                                                                                                            |
| `bulks`                | Bulk operations               | `getBulkStatus`                                                                                                                                                        |
| `databaseBackup`       | Database backup               | `triggerBackup`, `downloadBackup`                                                                                                                                      |
| `apiConsumers`         | API consumer management       | `getAll`, `getById`, `create`, `update`, `patch`, `_delete`, `createApiKeyForConsumer`, `createSecretKeyForConsumer`, `deleteApiKeyForConsumer`, `getKeysByConsumerId` |
| `apiKeysRotation`      | API key rotation              | `rotateKey`                                                                                                                                                            |
| `subscriptions`        | Event subscriptions           | `createOrGetSubscription`, `deleteSubscription`, `getSubscriptionEvents`, `getSubscriptionStats`, `commitCursors`                                                      |
| `streamingPublisher`   | Streaming stats               | `getStats`                                                                                                                                                             |
| `notificationSettings` | Webhook notification settings | `getWebhookNotificationSettings`, `updateWebhookNotificationSettings`                                                                                                  |
| `extensionPoints`      | Extension points              | `getAll`, `getProcessDefinitions`, `storeProcessDefinitions`                                                                                                           |
| `processDefinitions`   | Process definitions           | `upload`                                                                                                                                                               |

### Other Services

| Service             | Description                   | Key Methods                                                                                |
| ------------------- | ----------------------------- | ------------------------------------------------------------------------------------------ |
| `comments`          | Comment management            | `getComments`, `createComment`                                                             |
| `tasks`             | Task management               | `getAll`, `getById`, `create`, `update`, `patch`, `_delete`                                |
| `communications`    | Communications/messaging      | `send`, `enqueueByDate`, `enqueueByKeys`, `getByEncodedKey`, `resend`, `search`, `search1` |
| `templates`         | Template management           | `getByTemplateId`, `createTemplate`, `updateTemplate`, `_delete`                           |
| `fundingSources`    | Funding sources               | `sell`                                                                                     |
| `archivedDeposits`  | Archived deposit transactions | `getById`, `search`                                                                        |
| `application`       | Application status            | `getApplicationStatus`                                                                     |
| `generalSetup`      | General setup                 | `getGeneralSetup`                                                                          |
| `organizationSetup` | Organization setup            | `getOrganizationSetup`, `updateOrganizationSetup`                                          |

---

## Loans Service API Reference

The `loans` service provides comprehensive loan account management capabilities. Below is the complete list of available methods:

### Account Management

| Method            | Parameters                                                                                                                                                       | Description                                       |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
| `getById`         | `loanAccountId: string, detailsLevel?: string`                                                                                                                   | Retrieves a loan account by its ID                |
| `getAll`          | `offset?, limit?, paginationDetails?, detailsLevel?, creditOfficerUsername?, branchId?, centreId?, accountState?, accountHolderType?, accountHolderId?, sortBy?` | Retrieves all loan accounts with optional filters |
| `create`          | `body: LoanAccount, idempotencyKey?: string`                                                                                                                     | Creates a new loan account                        |
| `update`          | `loanAccountId: string, body: LoanAccount`                                                                                                                       | Updates a loan account's information              |
| `patch`           | `loanAccountId: string, body: PatchOperation[]`                                                                                                                  | Partially updates a loan account using JSON Patch |
| `_delete`         | `loanAccountId: string`                                                                                                                                          | Deletes a loan account                            |
| `getVersionsById` | `loanAccountId: string, offset?, limit?, paginationDetails?`                                                                                                     | Retrieves all versions of a loan account          |
| `migrateExternal` | `loanAccountId: string, body: MigrateLoanAccount, idempotencyKey?`                                                                                               | Migrates an external loan account                 |

### State & Settings Management

| Method                   | Parameters                                                                  | Description                                                          |
| ------------------------ | --------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| `changeState`            | `loanAccountId: string, body: LoanAccountAction, idempotencyKey?`           | Changes the state of a loan account (approve, disburse, close, etc.) |
| `changeInterestRate`     | `loanAccountId: string, body: PatchOperation[], idempotencyKey?`            | Changes the interest rate on a loan                                  |
| `changePeriodicPayment`  | `loanAccountId: string, body: ChangePeriodicPaymentInput, idempotencyKey?`  | Changes the periodic payment amount for an active loan               |
| `changeRepaymentValue`   | `loanAccountId: string, body: ChangeRepaymentValueInput, idempotencyKey?`   | Changes the repayment value of a loan                                |
| `changeLoanTerm`         | `loanAccountId: string, body: ChangeLoanTermInput, idempotencyKey?`         | Changes the loan term                                                |
| `changeFeeRate`          | `loanAccountId: string, body: ChangeFeeRateInput, idempotencyKey?`          | Changes a fee rate on a loan                                         |
| `changeArrearsSettings`  | `loanAccountId: string, body: ChangeArrearsSettingsInput, idempotencyKey?`  | Changes arrears settings                                             |
| `changeDueDatesSettings` | `loanAccountId: string, body: ChangeDueDatesSettingsInput, idempotencyKey?` | Changes due dates settings                                           |
| `applyInterest`          | `loanAccountId: string, body: ApplyInterestInput, idempotencyKey?`          | Applies interest on a loan account                                   |

### Account Actions

| Method                 | Parameters                                                                | Description                                   |
| ---------------------- | ------------------------------------------------------------------------- | --------------------------------------------- |
| `payOff`               | `loanAccountId: string, body: LoanAccountPayOffInput, idempotencyKey?`    | Pays off a loan account                       |
| `writeOff`             | `loanAccountId: string, body: WriteOffInput, idempotencyKey?`             | Writes off a loan account                     |
| `undoWriteOff`         | `loanAccountId: string, body: UndoWriteOffInput, idempotencyKey?`         | Undoes a write-off for a loan account         |
| `refinance`            | `loanAccountId: string, body: RefinanceAction, idempotencyKey?`           | Refinances a loan account                     |
| `undoRefinance`        | `loanAccountId: string, body: UndoRefinanceAction, idempotencyKey?`       | Undoes a refinance                            |
| `reschedule`           | `loanAccountId: string, body: RescheduleAction, idempotencyKey?`          | Reschedules a loan account                    |
| `undoReschedule`       | `loanAccountId: string, body: UndoRescheduleAction, idempotencyKey?`      | Undoes a reschedule                           |
| `terminateLoanAccount` | `loanAccountId: string, body: TerminateLoanAccountInput, idempotencyKey?` | Terminates a loan account                     |
| `previewPayOffAmounts` | `loanAccountId: string, date?: string`                                    | Previews pay-off due amounts at a future date |

### Card Management

| Method                     | Parameters                                                            | Description                              |
| -------------------------- | --------------------------------------------------------------------- | ---------------------------------------- |
| `createCard`               | `loanAccountId: string, body: Card`                                   | Creates a card for a loan account        |
| `deleteCard`               | `loanAccountId: string, cardReferenceToken: string`                   | Deletes a card using its reference token |
| `getAllCards`              | `loanAccountId: string`                                               | Gets all cards for a loan account        |
| `getAllAuthorizationHolds` | `loanAccountId: string, offset?, limit?, paginationDetails?, status?` | Gets all authorization holds             |

### Schedule Management (via `loanSchedule`)

| Method                             | Parameters                                                          | Description                                          |
| ---------------------------------- | ------------------------------------------------------------------- | ---------------------------------------------------- |
| `getScheduleForLoanAccount`        | `loanAccountId: string, detailsLevel?`                              | Retrieves the loan schedule                          |
| `editSchedule`                     | `loanAccountId: string, body: LoanAccountSchedule, idempotencyKey?` | Updates a loan account schedule                      |
| `previewSchedule`                  | `body: PreviewLoanAccountSchedule`                                  | Previews a schedule for a non-existent loan account  |
| `previewProcessPMTTransactionally` | `loanAccountId: string`                                             | Previews schedule using transactional PMT processing |
| `previewTranchesOnSchedule`        | `loanAccountId: string, body: LoanTranche[]`                        | Previews schedule with tranches                      |

### Tranche Management (via `loanTranches`)

| Method         | Parameters                                   | Description                         |
| -------------- | -------------------------------------------- | ----------------------------------- |
| `getTranches`  | `loanAccountId: string`                      | Retrieves the loan account tranches |
| `editTranches` | `loanAccountId: string, body: LoanTranche[]` | Updates the loan account tranches   |

### Transaction Management (via `loanTransactions`)

| Method                          | Parameters                                                                                         | Description                                     |
| ------------------------------- | -------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| `getById`                       | `loanTransactionId: string, detailsLevel?`                                                         | Retrieves a loan transaction by ID              |
| `getAll`                        | `loanAccountId: string, offset?, limit?, paginationDetails?, detailsLevel?`                        | Gets all transactions for a loan account        |
| `search`                        | `body: LoanTransactionSearchCriteria, offset?, limit?, paginationDetails?, cursor?, detailsLevel?` | Searches loan transactions by criteria          |
| `getTransactionsForAllVersions` | `loanAccountId: string, offset?, limit?, paginationDetails?, detailsLevel?`                        | Gets transactions for all loan account versions |
| `adjust`                        | `loanTransactionId: string, body: AdjustmentDetails`                                               | Adjusts a loan transaction                      |

### Payment Operations (via `loanTransactions`)

| Method                       | Parameters                                                                  | Description                                 |
| ---------------------------- | --------------------------------------------------------------------------- | ------------------------------------------- |
| `makeRepayment`              | `loanAccountId: string, body: RepaymentInput, idempotencyKey?`              | Makes a repayment transaction               |
| `makeDisbursement`           | `loanAccountId: string, body: DisbursementInput, idempotencyKey?`           | Makes a disbursement on a loan              |
| `makePrincipalOverpayment`   | `loanAccountId: string, body: PrincipalOverpaymentInput, idempotencyKey?`   | Makes a non-scheduled principal overpayment |
| `makeRefund`                 | `loanAccountId: string, body: RefundInput, idempotencyKey?`                 | Makes a refund transaction                  |
| `makeWithdrawal`             | `loanAccountId: string, body: WithdrawalInput, idempotencyKey?`             | Makes a withdrawal from redraw balance      |
| `makeRedrawRepayment`        | `loanAccountId: string, body: RedrawRepaymentInput, idempotencyKey?`        | Makes a redraw repayment                    |
| `makeDepositOnCreditBalance` | `loanAccountId: string, body: DepositOnCreditBalanceInput, idempotencyKey?` | Deposits on credit balance                  |
| `applyPaymentMade`           | `loanAccountId: string, body: PaymentMadeInput, idempotencyKey?`            | Applies a payment in redraw balance         |
| `applyFee`                   | `loanAccountId: string, body: FeeInput, idempotencyKey?`                    | Applies a fee to a loan                     |
| `applyLock`                  | `loanAccountId: string, body: LockInput, idempotencyKey?`                   | Locks loan account income sources           |
| `applyUnlock`                | `loanAccountId: string, body: UnlockInput, idempotencyKey?`                 | Unlocks loan account income sources         |

### Balance & Funding (via `loanBalances`, `loanFunding`)

| Method                            | Parameters                                                                           | Description                                |
| --------------------------------- | ------------------------------------------------------------------------------------ | ------------------------------------------ |
| `getBalancesByLoanAccountId`      | `loanAccountId: string`                                                              | Retrieves loan account balances            |
| `applyBalanceInterest`            | `loanAccountId: string, loanAccountBalance: string, body: ApplyBalanceInterestInput` | Applies interest on a loan account balance |
| `createLoanAccountFundingSources` | `loanAccountId: string, body: InvestorFund[]`                                        | Creates funding sources                    |
| `updateLoanAccountFundingSources` | `loanAccountId: string, body: InvestorFund[]`                                        | Updates funding sources                    |
| `deleteFundingSources`            | `loanAccountId: string`                                                              | Deletes all funding sources                |
| `deleteSingleFundingSource`       | `loanAccountId: string, fundId: string`                                              | Deletes a single funding source            |
| `patchFundingSource`              | `loanAccountId: string, fundId: string, body: PatchOperation[]`                      | Patches a funding source                   |

---

## Available API Endpoints

When running the built-in server (`npm run start:mambu`), these REST endpoints are available:

| Method | Endpoint                               | Description                 | SDK Method                                 |
| ------ | -------------------------------------- | --------------------------- | ------------------------------------------ |
| GET    | `/mambu/clients`                       | List all clients            | `clients.getAll()`                         |
| GET    | `/mambu/clients/:clientId`             | Get client by ID            | `clients.getById()`                        |
| POST   | `/mambu/clients`                       | Create a new client         | `clients.create()`                         |
| POST   | `/mambu/clients:search`                | Search clients              | `clients.search()`                         |
| GET    | `/mambu/branches`                      | List all branches           | `branches.getAll()`                        |
| GET    | `/mambu/branches/:branchId`            | Get branch by ID            | `branches.getById()`                       |
| GET    | `/mambu/loans`                         | List all loan accounts      | `loans.getAll()`                           |
| GET    | `/mambu/loans/:loanId`                 | Get loan by ID              | `loans.getById()`                          |
| POST   | `/mambu/loans:search`                  | Search loans                | `loansSearch.search()`                     |
| GET    | `/mambu/deposits`                      | List all deposit accounts   | `deposits.getAll()`                        |
| GET    | `/mambu/deposits/:depositId`           | Get deposit by ID           | `deposits.getById()`                       |
| POST   | `/mambu/deposits:search`               | Search deposits             | `deposits.search()`                        |
| GET    | `/mambu/users`                         | List all users              | `users.getAll()`                           |
| GET    | `/mambu/groups`                        | List all groups             | `groups.getAll()`                          |
| POST   | `/mambu/groups:search`                 | Search groups               | `groups.search()`                          |
| GET    | `/mambu/loan-products`                 | List all loan products      | `loanProducts.getAll()`                    |
| GET    | `/mambu/deposit-products`              | List all deposit products   | `depositProducts.getAll()`                 |
| POST   | `/mambu/loan-transactions:search`      | Search loan transactions    | `loanTransactions.search()`                |
| POST   | `/mambu/deposit-transactions:search`   | Search deposit transactions | `depositTransactions.search()`             |
| GET    | `/mambu/clients/:clientId/documents`   | List client documents       | `clientDocuments.getDocumentsByClientId()` |
| GET    | `/mambu/clients/documents/:documentId` | Get client document         | `clientDocuments.getClientDocumentById()`  |
| DELETE | `/mambu/documents/:documentId`         | Delete a document           | `documents.deleteDocumentById()`           |

> **Note:** The built-in server exposes a subset of endpoints for testing. When using `MambuService` directly in your NestJS project, you have access to **all 90+ API classes** and their full method sets listed in the API Reference above.



## Multi-Tenant / Multi-App Support

If you have multiple apps or developers working on the same project, each can use their own Mambu credentials.

### Using Named Instances

## Project Structure (What Each File Does)

```
mambu-wrapper/
|
|-- mambu-specs/                  # Mambu API specification files (JSON)
|   |-- clients.json              # Describes all client-related API endpoints
|   |-- loans.json                # Describes all loan-related API endpoints
|   |-- deposits.json             # ... and so on for each resource
|   |-- branches.json
|   |-- users.json
|   |-- groups.json
|   |-- loanproducts.json
|   |-- depositproducts.json
|   |-- loans_transactions.json
|   |-- deposits_transactions.json
|   |-- (+ more specs available for future use)
|
|-- src/
|   |-- mambu-sdk/                # Auto-generated SDK code (DO NOT EDIT MANUALLY)
|   |   |-- clients/              # Generated client API code
|   |   |-- loans/                # Generated loans API code
|   |   |-- deposits/             # Generated deposits API code
|   |   |-- branches/             # Generated branches API code
|   |   |-- users/                # Generated users API code
|   |   |-- groups/               # Generated groups API code
|   |   |-- loan-products/        # Generated loan products API code
|   |   |-- deposit-products/     # Generated deposit products API code
|   |   |-- loans-transactions/   # Generated loan transactions API code
|   |   |-- deposits-transactions/# Generated deposit transactions API code
|   |
|   |-- mambu/                    # The NestJS wrapper (this is the main toolkit code)
|   |   |-- mambu.config.ts       # Configuration class and helper tokens
|   |   |-- mambu.module.ts       # NestJS module (forRoot, forFeature, forRootAsync)
|   |   |-- mambu.service.ts      # Main service that connects to all Mambu APIs
|   |   |-- mambu.controller.ts   # REST endpoints for testing the SDK
|   |   |-- index.ts              # Exports everything from the mambu folder
|   |
|   |-- app.module.ts             # Main application module
|   |-- main.ts                   # Application entry point
|
|-- start-mambu.mjs               # Interactive startup script (prompts for credentials)
|-- package.json                  # Project dependencies and scripts
|-- tsconfig.json                 # TypeScript configuration
|-- nest-cli.json                 # NestJS CLI configuration
```

### Key Files Explained

| File                  | What It Does                                                                                                                         |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `mambu.config.ts`     | Defines the configuration structure (tenant URL, apiKey) and helper functions for multi-instance support                             |
| `mambu.module.ts`     | The NestJS module that wires everything together. Provides `forRoot()` for single-instance and `forFeature()` for multi-instance use |
| `mambu.service.ts`    | The main service. Creates API clients for each Mambu resource (clients, loans, etc.) and exposes them as properties                  |
| `mambu.controller.ts` | Provides REST endpoints (`/mambu/clients`, `/mambu/loans`, etc.) for testing                                                         |
| `start-mambu.mjs`     | A script that prompts you for your Mambu credentials in the terminal, then starts the server                                         |

---

## Complete SDK Property Reference

When using `MambuService`, all **90+ API properties** are available. Here is the full list organized by category:

### Core Entities

| Property               | API Class           | Description                |
| ---------------------- | ------------------- | -------------------------- |
| `mambu.clients`        | `ClientsApi`        | Client/customer operations |
| `mambu.branches`       | `BranchesApi`       | Branch operations          |
| `mambu.centres`        | `CentresApi`        | Centre operations          |
| `mambu.groups`         | `GroupsApi`         | Group operations           |
| `mambu.users`          | `UsersApi`          | User/staff operations      |
| `mambu.userRoles`      | `UserRolesApi`      | User role operations       |
| `mambu.comments`       | `CommentsApi`       | Comment operations         |
| `mambu.tasks`          | `TasksApi`          | Task operations            |
| `mambu.communications` | `CommunicationsApi` | Messaging operations       |

### Loans

| Property                    | API Class                       | Description                 |
| --------------------------- | ------------------------------- | --------------------------- |
| `mambu.loans`               | `LoanAccountsApi`               | Loan account CRUD & actions |
| `mambu.loansSearch`         | `LoanAccountsSearchApi`         | Loan account search         |
| `mambu.loanProducts`        | `LoanProductsApi`               | Loan product management     |
| `mambu.loanTransactions`    | `LoanTransactionsApi`           | Loan transaction processing |
| `mambu.loanSchedule`        | `LoanAccountScheduleApi`        | Loan schedule management    |
| `mambu.loanTranches`        | `LoanAccountTranchesApi`        | Loan tranche management     |
| `mambu.loanBalances`        | `LoanAccountBalancesApi`        | Loan balance retrieval      |
| `mambu.loanDocuments`       | `LoanAccountDocumentsApi`       | Loan document access        |
| `mambu.loanFunding`         | `LoanAccountFundingApi`         | Loan funding sources        |
| `mambu.loanPlannedFees`     | `LoanAccountPlannedFeesApi`     | Planned fee management      |
| `mambu.loanSchedulePreview` | `LoanAccountSchedulePreviewApi` | Schedule preview            |
| `mambu.collateralAssets`    | `CollateralAssetsApi`           | Collateral management       |

### Deposits

| Property                            | API Class                               | Description                    |
| ----------------------------------- | --------------------------------------- | ------------------------------ |
| `mambu.deposits`                    | `DepositAccountsApi`                    | Deposit account CRUD & actions |
| `mambu.depositProducts`             | `DepositProductsApi`                    | Deposit product management     |
| `mambu.depositTransactions`         | `DepositTransactionsApi`                | Deposit transaction processing |
| `mambu.depositTransactionAsync`     | `DepositTransactionAsyncApi`            | Async deposit transactions     |
| `mambu.depositTransactionDocuments` | `DepositTransactionDocumentsApi`        | Transaction documents          |
| `mambu.depositBalances`             | `DepositAccountBalancesApi`             | Deposit balance retrieval      |
| `mambu.depositBalanceSummary`       | `DepositAccountBalanceSummaryApi`       | Balance summary & search       |
| `mambu.depositDocuments`            | `DepositAccountDocumentsApi`            | Deposit document access        |
| `mambu.depositInterestAvailability` | `DepositAccountInterestAvailabilityApi` | Interest availability          |
| `mambu.fundedLoanAccounts`          | `FundedLoanAccountsApi`                 | Funded loan accounts           |

### Documents

| Property                | API Class            | Description                 |
| ----------------------- | -------------------- | --------------------------- |
| `mambu.clientDocuments` | `ClientDocumentsApi` | Client document management  |
| `mambu.documents`       | `DocumentsApi`       | General document management |

### Credit & Accounting

| Property                          | API Class                      | Description               |
| --------------------------------- | ------------------------------ | ------------------------- |
| `mambu.creditArrangements`        | `CreditArrangementsApi`        | Credit arrangement CRUD   |
| `mambu.creditArrangementsSearch`  | `CreditArrangementsSearchApi`  | Credit arrangement search |
| `mambu.glAccounts`                | `GLAccountsApi`                | General ledger accounts   |
| `mambu.journalEntries`            | `JournalEntriesApi`            | GL journal entries        |
| `mambu.accountingInterestAccrual` | `AccountingInterestAccrualApi` | Interest accrual search   |
| `mambu.accountingReports`         | `AccountingReportsApi`         | Accounting reports        |
| `mambu.accountingRates`           | `AccountingRatesApi`           | Currency accounting rates |

### Currencies & Rates

| Property                 | API Class             | Description         |
| ------------------------ | --------------------- | ------------------- |
| `mambu.currencies`       | `CurrenciesApi`       | Currency management |
| `mambu.exchangeRates`    | `ExchangeRateApi`     | Exchange rates      |
| `mambu.indexRateSources` | `IndexRateSourcesApi` | Index rate sources  |
| `mambu.indexRates`       | `IndexRatesApi`       | Index rates         |

### Cards

| Property      | API Class  | Description                    |
| ------------- | ---------- | ------------------------------ |
| `mambu.cards` | `CardsApi` | Card transactions & auth holds |

### Custom Fields

| Property                | API Class            | Description            |
| ----------------------- | -------------------- | ---------------------- |
| `mambu.customFields`    | `CustomFieldsApi`    | Custom field retrieval |
| `mambu.customFieldSets` | `CustomFieldSetsApi` | Custom field sets      |

### Configuration (20 properties)

| Property                          | API Class                                         |
| --------------------------------- | ------------------------------------------------- |
| `mambu.configAccountingRules`     | `AccountingRulesConfigurationApi`                 |
| `mambu.configAuthorizationHolds`  | `AuthorizationHoldsConfigurationApi`              |
| `mambu.configBranches`            | `BranchesConfigurationApi`                        |
| `mambu.configCentres`             | `CentresConfigurationApi`                         |
| `mambu.configClientRoles`         | `ClientRolesConfigurationApi`                     |
| `mambu.configCurrencies`          | `CurrenciesConfigurationApi`                      |
| `mambu.configCustomFields`        | `CustomFieldsConfigurationApi`                    |
| `mambu.configDepositProducts`     | `DepositProductsConfigurationApi`                 |
| `mambu.configEndOfDayProcessing`  | `EndOfDayProcessingConfigurationApi`              |
| `mambu.configGroupRoleNames`      | `GroupRoleNamesConfigurationApi`                  |
| `mambu.configHolidays`            | `HolidaysConfigurationApi`                        |
| `mambu.configIdDocumentTemplates` | `IdentificationDocumentTemplatesConfigurationApi` |
| `mambu.configIndexRates`          | `IndexRatesConfigurationApi`                      |
| `mambu.configInternalControls`    | `InternalControlsConfigurationApi`                |
| `mambu.configLabels`              | `ObjectLabelsConfigurationApi`                    |
| `mambu.configLoanProducts`        | `LoanProductsConfigurationApi`                    |
| `mambu.configLoanRiskLevels`      | `LoanRiskLevelsConfigurationApi`                  |
| `mambu.configOrganization`        | `OrganizationConfigurationApi`                    |
| `mambu.configTransactionChannels` | `TransactionChannelsConfigurationApi`             |
| `mambu.configUserRoles`           | `UserRolesConfigurationApi`                       |

### Organization

| Property                    | API Class                            | Description           |
| --------------------------- | ------------------------------------ | --------------------- |
| `mambu.holidays`            | `HolidaysApi`                        | Organization holidays |
| `mambu.generalHolidays`     | `GeneralHolidaysApi`                 | General holidays      |
| `mambu.nonWorkingDays`      | `NonWorkingDaysApi`                  | Non-working days      |
| `mambu.idDocumentTemplates` | `IdentificationDocumentTemplatesApi` | ID document templates |
| `mambu.transactionChannels` | `TransactionChannelsApi`             | Transaction channels  |
| `mambu.installments`        | `InstallmentsApi`                    | Installments          |

### Operations & Integration

| Property                     | API Class                 | Description               |
| ---------------------------- | ------------------------- | ------------------------- |
| `mambu.cronsEod`             | `CronsApi`                | End-of-day crons          |
| `mambu.cronsEarlyEod`        | `CronsApi`                | Early EOD crons           |
| `mambu.backgroundProcess`    | `BackgroundProcessApi`    | Background processes      |
| `mambu.bulks`                | `BulksApi`                | Bulk operations           |
| `mambu.databaseBackup`       | `DatabaseBackupApi`       | Database backup           |
| `mambu.apiConsumers`         | `APIConsumersApi`         | API consumers             |
| `mambu.apiKeysRotation`      | `APIKeysRotationApi`      | API key rotation          |
| `mambu.subscriptions`        | `SubscriptionApi`         | Event subscriptions       |
| `mambu.streamingPublisher`   | `StreamingPublisherApi`   | Streaming publisher stats |
| `mambu.notificationSettings` | `NotificationSettingsApi` | Webhook settings          |
| `mambu.extensionPoints`      | `ExtensionPointsApi`      | Extension points          |
| `mambu.processDefinitions`   | `ProcessDefinitionsApi`   | Process definitions       |

### Other

| Property                  | API Class              | Description           |
| ------------------------- | ---------------------- | --------------------- |
| `mambu.templates`         | `TemplatesApi`         | Template management   |
| `mambu.fundingSources`    | `FundingSourcesApi`    | Funding sources       |
| `mambu.archivedDeposits`  | `ArchivedDepositsApi`  | Archived transactions |
| `mambu.application`       | `ApplicationApi`       | Application status    |
| `mambu.generalSetup`      | `GeneralSetupApi`      | General setup         |
| `mambu.organizationSetup` | `OrganizationSetupApi` | Organization setup    |

---

## License

MIS

## Author

MARTIN WAMBUGU
