Open MercatoDocsSearch docsAPI reference

Framework

Currencies and Exchange Rates

An order in euros and a report in dollars need an exchange rate from the right date. The Currencies module stores currency definitions and rates, can fetch updates from a provider and exposes a service for looking up the rate your operation needs.

Architecture Overview

┌─────────────────────────┐
│  ExchangeRateService    │  ← High-level, business-focused API
│  (Get rates with        │     - Database-first retrieval
│   automatic fetching)   │     - Automatic provider fallback
└───────────┬─────────────┘     - Daily fallback (up to 30 days)
            │
            ▼
┌─────────────────────────┐
│  RateFetchingService    │  ← Low-level, provider orchestration
│  (Fetch and store)      │     - Manages provider lifecycle
└───────────┬─────────────┘     - Batch processing
            │                    - Error tracking
            ▼
┌─────────────────────────┐
│   Rate Providers        │  ← External data sources
│   (NBP, Raiffeisen,     │     - Pluggable architecture
│    Custom providers)    │     - Standardized interface
└─────────────────────────┘

Database Schema

Currency Entity

Stores currency metadata with multi-tenant scoping:

@Entity()
export class Currency {
  @PrimaryKey()
  id: string

  @Property()
  code: string // ISO 4217 code (e.g., "USD")

  @Property()
  name: string

  @Property({ nullable: true })
  symbol?: string

  @Property({ default: 2 })
  decimalPlaces: number

  @Property({ nullable: true })
  thousandsSeparator?: string

  @Property({ nullable: true })
  decimalSeparator?: string

  @Property({ default: false })
  isBase: boolean // One base currency per organization

  @Property()
  tenantId: string

  @Property()
  organizationId: string

  @Property()
  isActive: boolean

  @Property()
  createdAt: Date

  @Property({ onUpdate: () => new Date() })
  updatedAt: Date
}

Key indexes:

ExchangeRate Entity

Stores directional exchange rates with source attribution:

import { ExactDecimalType } from '@open-mercato/shared/lib/db/exactDecimalType'

@Entity()
export class ExchangeRate {
  @PrimaryKey()
  id: string

  @Property()
  fromCurrencyCode: string

  @Property()
  toCurrencyCode: string

  @Property({ type: ExactDecimalType, columnType: 'numeric' })
  rate: string // Unconstrained decimal string, never rounded to a fixed scale

  @Property()
  date: Date

  @Property()
  source: string // Provider identifier (e.g., "NBP", "Raiffeisen", "manual")

  @Property({ nullable: true })
  type?: 'buy' | 'sell' // Bank's perspective

  @Property({ type: 'jsonb', nullable: true })
  metadata?: Record<string, unknown> | null // Free-form context, e.g. the NBP table number

  @Property()
  tenantId: string

  @Property()
  organizationId: string

  @Property()
  isActive: boolean

  @Property()
  createdAt: Date

  @Property({ onUpdate: () => new Date() })
  updatedAt: Date
}

Key indexes:

CurrencyFetchConfig Entity

Tracks provider configuration and sync status:

@Entity()
export class CurrencyFetchConfig {
  @PrimaryKey()
  id: string

  @Property()
  provider: string // Provider identifier

  @Property({ default: true })
  enabled: boolean

  @Property({ nullable: true })
  config?: Record<string, unknown> | null

  @Property({ nullable: true })
  lastSyncAt?: Date

  @Property({ nullable: true })
  lastSyncCount?: number

  @Property()
  tenantId: string

  @Property()
  organizationId: string

  @Property()
  createdAt: Date

  @Property({ onUpdate: () => new Date() })
  updatedAt: Date
}

Service Layer

ExchangeRateService

High-level API for retrieving exchange rates with automatic fetching and fallback.

Dependency Injection

import type { ExchangeRateService } from '@open-mercato/core/modules/currencies/services/exchangeRateService'

const exchangeRateService = container.resolve<ExchangeRateService>('exchangeRateService')

Single Rate Retrieval

import { decimalToString, multiplyDecimals } from '@open-mercato/shared/lib/decimal'

const result = await exchangeRateService.getRate({
  fromCurrencyCode: 'USD',
  toCurrencyCode: 'EUR',
  date: new Date('2024-01-15'),
  scope: {
    tenantId: 'tenant-123',
    organizationId: 'org-456',
  },
  options: {
    maxDaysBack: 30,      // Look back up to 30 days (default)
    autoFetch: true,      // Fetch from providers if not found (default)
  },
})

// Result structure
interface RateResult {
  rates: ExchangeRate[]
  fromCurrencyCode: string
  toCurrencyCode: string
  requestedDate: Date
  actualDate: Date | null
  error?: Error
}

if (result.rates.length > 0) {
  const convertedAmount = decimalToString(multiplyDecimals('100', result.rates[0].rate))
}

Batch Retrieval

const results = await exchangeRateService.getRates({
  pairs: [
    { fromCurrencyCode: 'USD', toCurrencyCode: 'EUR' },
    { fromCurrencyCode: 'GBP', toCurrencyCode: 'PLN' },
    { fromCurrencyCode: 'EUR', toCurrencyCode: 'JPY' },
  ],
  date: new Date(),
  scope: { tenantId, organizationId },
})

// Results is a Map<string, RateResult>
for (const [key, result] of results.entries()) {
  if (result.error) {
    console.error(`Failed to get ${key}: ${result.error.message}`)
  } else if (result.rates.length > 0) {
    console.log(`${key}: ${result.rates[0].rate}`)
  } else {
    console.log(`${key}: No rates found`)
  }
}

Daily Fallback

If a rate isn't found for the requested date, the service automatically:

  1. Checks the database
  2. Fetches from providers if autoFetch=true
  3. Recursively checks previous days (up to maxDaysBack)
  4. Returns actualDate to indicate which date was used

Date Validation

// ✅ Valid
await exchangeRateService.getRate({
  fromCurrencyCode: 'USD',
  toCurrencyCode: 'EUR',
  date: new Date(), // Today
  scope: { tenantId, organizationId },
})

// ❌ Throws error
const tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
await exchangeRateService.getRate({
  fromCurrencyCode: 'USD',
  toCurrencyCode: 'EUR',
  date: tomorrow,
  scope: { tenantId, organizationId },
})

RateFetchingService

Lower-level service for fetching and storing rates from providers.

Dependency Injection

import type { RateFetchingService } from '@open-mercato/core/modules/currencies/services/rateFetchingService'

const rateFetchingService = container.resolve<RateFetchingService>('rateFetchingService')

Fetch Rates

const result = await rateFetchingService.fetchRatesForDate(
  new Date('2024-01-15'),
  { tenantId: 'tenant-123', organizationId: 'org-456' }
)

// Result structure
interface FetchResult {
  totalFetched: number
  byProvider: Record<string, { count: number; errors?: string[] }>
  errors: string[]
}

console.log(`Fetched ${result.totalFetched} rates`)
console.log(`NBP: ${result.byProvider.NBP?.count ?? 0}`)
console.log(`Raiffeisen: ${result.byProvider['Raiffeisen Bank Polska']?.count ?? 0}`)

When to Use Each Service

Use CaseService
Business logic needing ratesExchangeRateService
Currency conversionsExchangeRateService
Scheduled/batch fetchingRateFetchingService
Admin operationsRateFetchingService
Automatic fallback neededExchangeRateService
Explicit control over fetchingRateFetchingService

Rate Providers

Built-in Providers

NBP (National Bank of Poland)

import { NBPProvider } from '@open-mercato/core/modules/currencies/services/providers/nbp'

const provider = new NBPProvider()

Raiffeisen Bank Polska

import { RaiffeisenPolandProvider } from '@open-mercato/core/modules/currencies/services/providers/raiffeisen'

const provider = new RaiffeisenPolandProvider()

Creating Custom Providers

Implement the RateProvider interface:

import type { RateProvider, RateProviderResult } from '@open-mercato/core/modules/currencies/services/providers/base'

export type ProviderRate = {
  from: string
  to: string
  value: string
  reference?: string
  type?: 'buy' | 'sell'
}

export class MyCustomProvider implements RateProvider {
  readonly name = 'MyProvider'
  readonly source = 'MyProvider'

  constructor(private readonly fetchFromApi: (
    date: Date,
    scope: { tenantId: string; organizationId: string },
  ) => Promise<ProviderRate[]>) {}

  isAvailable(): boolean {
    return true
  }

  async fetchRates(
    date: Date,
    scope: { tenantId: string; organizationId: string },
    availableCurrencies: Set<string>,
  ): Promise<RateProviderResult[]> {
    const rates = await this.fetchFromApi(date, scope)
    return rates
      .filter(rate => availableCurrencies.has(rate.from) && availableCurrencies.has(rate.to))
      .map(rate => ({
        fromCurrencyCode: rate.from,
        toCurrencyCode: rate.to,
        rate: rate.value,
        source: this.source,
        date,
        type: rate.type,
        metadata: { reference: rate.reference },
      }))
  }
}

Register Custom Provider

import { asFunction } from 'awilix'
import type { AppContainer } from '@open-mercato/shared/lib/di/container'
import type { RateFetchingService } from '@open-mercato/core/modules/currencies/services/rateFetchingService'
import { MyCustomProvider } from './providers/myCustomProvider'
import { fetchRatesFromApi } from './providers/myProviderApi'

export function register(container: AppContainer) {
  container.register({
    myCurrencyRateProvider: asFunction(() => new MyCustomProvider(fetchRatesFromApi)).singleton(),
  })
  container.resolve<RateFetchingService>('rateFetchingService')
    .registerProvider(container.resolve<MyCustomProvider>('myCurrencyRateProvider'))
}

REST API

Currencies

GET    /api/currencies/currencies              List currencies
POST   /api/currencies/currencies              Create currency
PUT    /api/currencies/currencies              Update currency (id in body)
DELETE /api/currencies/currencies?id=<uuid>    Delete currency

Query parameters for GET:

Exchange Rates

GET    /api/currencies/exchange-rates              List rates
POST   /api/currencies/exchange-rates              Create rate
PUT    /api/currencies/exchange-rates              Update rate (id in body)
DELETE /api/currencies/exchange-rates?id=<uuid>    Delete rate

Query parameters for GET:

Fetch Configuration

GET    /api/currencies/fetch-configs              List provider configs
POST   /api/currencies/fetch-configs              Enable provider
PUT    /api/currencies/fetch-configs              Update config (id in body)
DELETE /api/currencies/fetch-configs?id=<uuid>    Delete config

Trigger Manual Fetch

POST   /api/currencies/fetch-rates    Fetch rates for a date

Request body:

{
  "date": "2024-01-15",
  "providers": ["NBP"]
}

CLI Commands

Fetch Rates

# Fetch for today
yarn mercato currencies fetch-rates --tenant <tenantId> --org <organizationId>

# Fetch for specific date
yarn mercato currencies fetch-rates --tenant <tenantId> --org <organizationId> --date 2024-01-15

# Fetch for date range
yarn mercato currencies fetch-rates --tenant <tenantId> --org <organizationId> --from 2024-01-01 --to 2024-01-31

List Providers

yarn mercato currencies list-providers

Shows all registered providers, their status, and available currencies.

Seed Example Currencies

yarn mercato currencies seed --tenant <tenantId> --org <organizationId>

Creates example currencies (USD, EUR, PLN, GBP) for testing.

Access Control (ACL)

The module defines these features for RBAC:

export const features = [
  {
    id: 'currencies.view',
    label: 'View currencies',
    description: 'Can view currency list and details',
  },
  {
    id: 'currencies.manage',
    label: 'Manage currencies',
    description: 'Can create, update, and delete currencies',
  },
  {
    id: 'currencies.rates.view',
    label: 'View exchange rates',
    description: 'Can view exchange rates',
  },
  {
    id: 'currencies.rates.manage',
    label: 'Manage exchange rates',
    description: 'Can create, update, and delete exchange rates',
  },
  {
    id: 'currencies.fetch.view',
    label: 'View fetch configuration',
    description: 'Can view provider configuration',
  },
  {
    id: 'currencies.fetch.manage',
    label: 'Manage fetch configuration',
    description: 'Can configure rate providers',
  },
]

Use in API route metadata:

export const metadata = {
  GET: { requireAuth: true, requireFeatures: ['currencies.view'] },
  POST: { requireAuth: true, requireFeatures: ['currencies.manage'] },
}

CQRS Commands

The module uses command/query separation. Pass an authenticated, organization-scoped command context. The example assumes EUR already exists in that scope:

import type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'

async function createCurrencyAndRate(ctx: CommandRuntimeContext, scope: {
  tenantId: string
  organizationId: string
}) {
  const commandBus = ctx.container.resolve<CommandBus>('commandBus')
  await commandBus.execute('currencies.currencies.create', {
    input: {
      ...scope,
      code: 'USD',
      name: 'US Dollar',
      symbol: '$',
      decimalPlaces: 2,
      isBase: true,
    },
    ctx,
  })
  await commandBus.execute('currencies.exchange_rates.create', {
    input: {
      ...scope,
      fromCurrencyCode: 'USD',
      toCurrencyCode: 'EUR',
      rate: '0.92',
      date: new Date(),
      source: 'manual',
      type: 'buy',
    },
    ctx,
  })
}

Data Validation

All inputs are validated using Zod schemas:

import { currencyCreateSchema, exchangeRateCreateSchema } from '@open-mercato/core/modules/currencies/data/validators'

// Currency validation
const currencyData = currencyCreateSchema.parse({
  code: 'USD',
  name: 'US Dollar',
  symbol: '$',
  // ...
})

// Exchange rate validation
const rateData = exchangeRateCreateSchema.parse({
  fromCurrencyCode: 'USD',
  toCurrencyCode: 'EUR',
  rate: '0.92',
  // ...
})

Key validation rules:

Example: Currency Conversion Utility

import type { ExchangeRateService } from '@open-mercato/core/modules/currencies/services/exchangeRateService'
import { decimalToString, multiplyDecimals } from '@open-mercato/shared/lib/decimal'

export async function convertCurrency(
  exchangeRateService: ExchangeRateService,
  amount: string | number,
  fromCode: string,
  toCode: string,
  date: Date,
  scope: { tenantId: string; organizationId: string },
  options?: {
    preferredProvider?: string
    rateType?: 'buy' | 'sell'
  }
): Promise<string | null> {

  const result = await exchangeRateService.getRate({
    fromCurrencyCode: fromCode,
    toCurrencyCode: toCode,
    date,
    scope,
  })

  if (result.rates.length === 0) {
    return null // No rate available
  }

  // Filter by preferences
  let selectedRate = result.rates[0]

  if (options?.preferredProvider) {
    const providerRate = result.rates.find(r => r.source === options.preferredProvider)
    if (providerRate) selectedRate = providerRate
  }

  if (options?.rateType) {
    const typeRate = result.rates.find(r => r.type === options.rateType)
    if (typeRate) selectedRate = typeRate
  }

  return decimalToString(multiplyDecimals(amount, selectedRate.rate))
}

// Usage
const exchangeRateService = container.resolve<ExchangeRateService>('exchangeRateService')
const eurAmount = await convertCurrency(
  exchangeRateService,
  '100',
  'USD',
  'EUR',
  new Date(),
  { tenantId: 'tenant-123', organizationId: 'org-456' },
  { preferredProvider: 'NBP', rateType: 'sell' }
)

Module Configuration

Enable in apps/mercato/src/modules.ts:

export const modules: ModuleConfig[] = [
  // ... other modules
  { id: 'currencies', from: '@open-mercato/core' },
]

The module is fully self-contained:

Migration Generation

Generate migrations after schema changes:

yarn generate
yarn db:generate

Migrations are written to:

packages/core/src/modules/currencies/migrations/

Apply migrations:

yarn db:migrate

See Also

Previous: Core Modules · Next: Devices