All files / src/helpers currency.ts

93.18% Statements 82/88
86.36% Branches 19/22
87.5% Functions 7/8
93.18% Lines 82/88

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 2781x 1x 1x 1x 1x 1x       1x   1x                                         1x 1x 1x 1x 4x 4x 3x 3x   2x 2x 2x 1x   1x                                     1x 1x 9x 9x 6x 6x   1x                                                 1x 1x 70x 70x   70x 70x 66x 66x 66x 66x   4x 8x   1x 1x   1x 1x 1x   1x 1x   1x 1x 1x 1x 1x 1x   1x                                                 1x 1x 4x 4x 4x 1x 1x   1x 4x   1x                                           1x 1x 8x 8x   1x                                 1x 1x 1x 1x   1x                                                     1x 1x 2x 2x 2x   1x                                         1x 1x                
//import type { ExchangeRateResponse, ParsedPrice } from "types";
import { CURRENCY_CODE_MAP } from '@/constants/currency';
import { findCountryByIso2 } from '@/helpers/country';
import { LRUCache } from 'lru-cache';
import priceParser from 'price-parser';
/**
 * @group Helpers
 * @groupDescription Currency conversion and price parsing utilities for handling different currencies and formats.
 * @source
 */
 
/**
 * LRU (Least Recently Used) cache for storing currency exchange rates.
 * Implements caching to minimize API calls to the exchange rate service.
 *
 * Configuration:
 * - Maximum size: 5 entries
 * - Automatic fetching of missing rates
 * - Fetches from Hexarate API (https://hexarate.paikama.co)
 *
 * Cache key format: "FROM:TO" (e.g., "USD:EUR")
 * Cache value: Exchange rate as a number
 *
 * @example
 * ```typescript
 * // Cache usage is automatic through getCurrencyRate():
 * const rate1 = await getCurrencyRate('USD', 'EUR'); // Fetches from API
 * const rate2 = await getCurrencyRate('USD', 'EUR'); // Uses cached value
 *
 * // After 5 different currency pairs, least recently used pair is evicted
 * ```
 * @source
 */
const lruCurrencyRate = new LRUCache({
  max: 5,
  fetchMethod: async (key: string) => {
    const [from, to] = key.split(':');
    if (from === to) return 1;
    const response = await fetch(
      `https://hexarate.paikama.co/api/rates/latest/${from}?target=${to}`,
    );
    const result = await response.json();
    return result.data.mid;
  },
});
 
/**
 * Extracts the currency symbol from a price string.
 * Uses Unicode property escapes to match currency symbols.
 * Supports a wide range of international currency symbols.
 *
 * @category Helpers
 * @param price - The price string to extract the currency symbol from
 * @returns The currency symbol if found, undefined otherwise
 *
 * @example
 * ```typescript
 * getCurrencySymbol('$1000') // Returns '$'
 * getCurrencySymbol('1000€') // Returns '€'
 * getCurrencySymbol('£99.99') // Returns '£'
 * getCurrencySymbol('¥10000') // Returns '¥'
 * getCurrencySymbol('₹1500') // Returns '₹'
 * getCurrencySymbol('1000') // Returns undefined (no symbol)
 * ```
 * @source
 */
export function getCurrencySymbol(price: string): CurrencySymbol {
  const match = price.match(/\p{Sc}/u);
  if (!match) return;
  return match[0] satisfies CurrencySymbol;
}
 
/**
 * Parses a price string into a structured object containing currency information.
 * Handles various price formats and number representations:
 * - Different currency symbol positions (prefix/suffix)
 * - International number formats (e.g., 1.234,56 or 1,234.56)
 * - Various currency symbols (€, $, £, ¥, etc.)
 *
 * @category Helpers
 * @param price - The price string to parse (e.g., "$1,234.56" or "1.234,56€")
 * @returns Object with currency code, symbol, and numeric price, or undefined if invalid
 *
 * @example
 * ```typescript
 * parsePrice('$1,234.56')
 * // Returns { currencyCode: 'USD', price: 1234.56, currencySymbol: '$' }
 *
 * parsePrice('1.234,56€')
 * // Returns { currencyCode: 'EUR', price: 1234.56, currencySymbol: '€' }
 *
 * parsePrice('£99.99')
 * // Returns { currencyCode: 'GBP', price: 99.99, currencySymbol: '£' }
 *
 * parsePrice('invalid') // Returns undefined
 * ```
 * @source
 */
export function parsePrice(price: string): ParsedPrice | void {
  if (typeof price !== 'string') return;
  const parsed = priceParser.parseFirst(price);
 
  if (parsed)
    return {
      currencyCode: parsed.currencyCode.toUpperCase(),
      currencySymbol: parsed.symbol,
      price: parsed.floatValue,
    } satisfies ParsedPrice;
 
  const currencySymbol = getCurrencySymbol(price);
  if (!currencySymbol) return;
 
  const currencyCode = getCurrencyCodeFromSymbol(currencySymbol);
  let bareAmount = price.replace(currencySymbol, '').trim();
 
  // Handle foreign number formats where commas and decimals are swapped
  if (bareAmount.match(/^(\d+\.\d+,\d{1,2}|\d{1,3},\d{1,2}|\d{1,3},\d{1,2})$/))
    bareAmount = bareAmount.replaceAll('.', 'xx').replaceAll(',', '.').replaceAll('xx', ',');
 
  // Remove all commas from the amount to make it castable to a number
  bareAmount = bareAmount.replace(/,/g, '');
 
  return {
    currencyCode,
    currencySymbol,
    price: Number(bareAmount),
  } satisfies ParsedPrice;
}
 
/**
 * Fetches the current exchange rate between two currencies.
 * Uses the Hexarate API to get real-time exchange rates.
 * Implements caching using LRU cache to minimize API calls.
 *
 * @category Helpers
 * @param from - The source currency code (e.g., 'USD', 'EUR')
 * @param to - The target currency code
 * @returns The exchange rate as a number
 * @throws Error if the API request fails or rate cannot be fetched
 *
 * @example
 * ```typescript
 * // Get EUR to USD rate
 * const rate = await getCurrencyRate('EUR', 'USD')
 * // Returns something like 1.18 (meaning 1 EUR = 1.18 USD)
 *
 * // Convert amount using rate
 * const amount = 100;
 * const converted = amount * rate; // 118 USD
 *
 * // Rates are cached for subsequent calls
 * await getCurrencyRate('EUR', 'USD') // Uses cached value
 * ```
 * @source
 */
export async function getCurrencyRate(from: CurrencyCode, to: CurrencyCode): Promise<number> {
  try {
    return await lruCurrencyRate.fetch(`${from}:${to}`);
  } catch (error) {
    throw new Error(
      `Failed to get currency rate for ${from} to ${to} - ${error instanceof Error ? error.message : String(error)}`,
    );
  }
}
 
/**
 * Maps a currency symbol to its corresponding ISO currency code.
 * Uses a predefined mapping from the CURRENCY_CODE_MAP constant.
 * Supports major international currency symbols.
 *
 * @category Helpers
 * @param symbol - The currency symbol to look up (e.g., '$', '€', '£')
 * @returns The corresponding ISO currency code (e.g., 'USD', 'EUR', 'GBP')
 *
 * @example
 * ```typescript
 * getCurrencyCodeFromSymbol('$') // Returns 'USD'
 * getCurrencyCodeFromSymbol('€') // Returns 'EUR'
 * getCurrencyCodeFromSymbol('£') // Returns 'GBP'
 * getCurrencyCodeFromSymbol('¥') // Returns 'JPY'
 * getCurrencyCodeFromSymbol('₹') // Returns 'INR'
 *
 * // Useful in combination with getCurrencySymbol
 * const symbol = getCurrencySymbol('$100');
 * const code = getCurrencyCodeFromSymbol(symbol); // 'USD'
 * ```
 * @source
 */
export function getCurrencyCodeFromSymbol(symbol: CurrencySymbol): CurrencyCode {
  return CURRENCY_CODE_MAP[String(symbol)];
}
 
/**
 * Maps a location to its corresponding currency code.
 * Looks the country up in `country-list-js` by its two-letter code and reads
 * the associated currency. Falls back to 'USD' for unknown locations (e.g. the
 * synthetic 'OTHER' option).
 *
 * @category Helpers
 * @param location - The location to look up (e.g., 'US', 'GB')
 * @returns The corresponding currency code (e.g., 'USD', 'GBP')
 *
 * @example
 * ```typescript
 * getCurrencyCodeFromLocation('US') // Returns 'USD'
 * getCurrencyCodeFromLocation('GB') // Returns 'GBP'
 * getCurrencyCodeFromLocation('OTHER') // Returns 'USD'
 * ```
 * @source
 */
export function getCurrencyCodeFromLocation(location: CountryCode): CurrencyCode {
  return findCountryByIso2(String(location))?.currency?.code ?? 'USD';
}
 
/**
 * Converts a given amount from any supported currency to USD.
 * Uses real-time exchange rates from the Hexarate API.
 * Results are rounded to 2 decimal places for standard currency format.
 *
 * @category Helpers
 * @param amount - The amount to convert
 * @param fromCurrencyCode - The source currency code (e.g., 'EUR', 'GBP')
 * @returns The converted amount in USD, formatted to 2 decimal places
 *
 * @example
 * ```typescript
 * // Convert 100 EUR to USD
 * await toUSD(100, 'EUR')
 * // Returns 118.45 (if rate is 1.1845)
 *
 * // Convert 1000 JPY to USD
 * await toUSD(1000, 'JPY')
 * // Returns 9.12 (if rate is 0.00912)
 *
 * // Chain conversions
 * const price = parsePrice('€50.00');
 * if (price) {
 *   const usdAmount = await toUSD(price.price, price.currencyCode);
 * }
 * ```
 * @source
 */
export async function toUSD(amount: number, fromCurrencyCode: CurrencyCode): Promise<number> {
  const rate = await getCurrencyRate(fromCurrencyCode, 'USD');
  return Number(Number(amount * rate).toFixed(2));
}
 
/**
 * Converts a given amount from USD to any supported currency.
 * Uses real-time exchange rates from the Hexarate API.
 * Results are rounded to 2 decimal places for standard currency format.
 *
 * @category Helpers
 * @param amount - The amount to convert
 * @param toCurrencyCode - The target currency code (e.g., 'EUR', 'GBP')
 * @returns The converted amount in the target currency, formatted to 2 decimal places
 *
 * @example
 * ```typescript
 * // Convert 100 USD to EUR
 * await USDto(100, 'EUR')
 * // Returns 85.32 (if rate is 0.8532)
 *
 * // Convert 500 USD to GBP
 * await USDto(500, 'GBP')
 * // Returns 387.50 (if rate is 0.775)
 * ```
 * @source
 */
export async function USDto(amount: number, toCurrencyCode: CurrencyCode): Promise<number> {
  const currencyData = priceParser.currencies.find(
    (c: { code: string }) => c.code === toCurrencyCode.toLowerCase(),
  );
  if (!currencyData) return 0;
  const rate = await getCurrencyRate('USD', toCurrencyCode);
  return Number(Number(amount * rate).toFixed(currencyData.exponent));
}