Hello from MCP server

List Files | Just Commands | Repo | Logs

← back |
/**
 * Currency conversion utilities
 *
 * Base currency is XAG (silver). All monetary values in the database
 * are stored in XAG and converted to the user's preferred currency for display.
 */

export interface ExchangeRate {
  baseCurrency: string;
  quoteCurrency: string;
  rate: number | string;
}

export interface Currency {
  id: string;
  refId?: string;
  symbol?: string;
  name?: string;
}

/**
 * Convert a value from base currency (XAG) to target currency
 */
export function convertCurrency(
  value: number,
  targetCurrency: string,
  rates: ExchangeRate[],
): number {
  const rate = rates.find(r => r.quoteCurrency === targetCurrency);
  const rateValue = rate ? Number(rate.rate) : 1;
  return Math.ceil(value * rateValue);
}

/**
 * Convert a value from target currency back to base currency (XAG)
 */
export function convertToBase(
  value: number,
  fromCurrency: string,
  rates: ExchangeRate[],
): number {
  const rate = rates.find(r => r.quoteCurrency === fromCurrency);
  const rateValue = rate ? Number(rate.rate) : 1;
  return rateValue > 0 ? value / rateValue : value;
}

/**
 * Format a currency value with symbol
 */
export function formatCurrency(
  value: number,
  targetCurrency: string,
  rates: ExchangeRate[],
  currencies: Currency[],
): string {
  const converted = convertCurrency(value, targetCurrency, rates);
  const currency = currencies.find(c => c.refId === targetCurrency);
  const symbol = currency?.symbol || "";
  return `${symbol}${converted.toLocaleString()}`;
}

/**
 * Get currency symbol
 */
export function getCurrencySymbol(
  currencyRefId: string,
  currencies: Currency[],
): string {
  const currency = currencies.find(c => c.refId === currencyRefId);
  return currency?.symbol || "";
}