diff --git a/README.md b/README.md index b0038dd..6a770a6 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,8 @@ Settle Up clone that runs in any browser and installs as an app. - Groups you open via a link; the key travels in the `#fragment` and never reaches the server - Equal, shares, exact-amount and percent splits; several payers; any member can be left out -- Multiple currencies with ECB daily rates (stored per expense, editable) +- Multiple currencies with daily rates — ECB, plus ExchangeRate-API for the + rest (stored per expense, editable) - One receipt photo per expense (resized, location data stripped, encrypted) - Who-pays-whom settle-up suggestions, with "record payment" - Full history: restore any version, or rewind the whole group (and undo that) diff --git a/SPEC.md b/SPEC.md index 499517b..e476394 100644 --- a/SPEC.md +++ b/SPEC.md @@ -156,7 +156,7 @@ entity fully defines it. Conflicts resolve **last-writer-wins by server "currency": "EUR", "amount": 12050, // 120.50 EUR "rate": "25.214", // decimal string: 1 EUR = 25.214 base; "1" if same currency - "rateSource": "ecb:2026-10-08", // or "manual" + "rateSource": "ecb:2026-10-08", // or "xr:", "manual" (see 8.2) "payers": [ { "member": "m1", "amount": 12050 } ], // sums to amount "split": { "mode": "equal", // equal | shares | exact | percent @@ -370,9 +370,27 @@ which group ids exist. ECB's own XML feed) every 6 hours and caches them in SQLite. The first run loads the full history (back to 1999) for back-dated expenses; later runs fetch the last 90 days. +- For currencies the ECB doesn't publish (e.g. ALL), the server also fetches + a **supplementary EUR-based feed** on the same schedule: ExchangeRate-API's + free endpoint (`RATES_EXTRA_URL`, default + `https://open.er-api.com/v6/latest/EUR`; empty turns it off). It has no + history, so its daily snapshots accumulate from when the server starts + fetching them; one older than a week before the requested date is not + used. It is stored apart from the ECB rates, and **the ECB rate always wins** + for a currency both publish. `GET /api/rates` merges the two and returns + `sources: { CODE: "xr:" }` for every supplementary rate. +- An expense's `rateSource` is `ecb:`, or `xr:` when either side + of the conversion came from the supplementary feed. The editor labels `xr:` + rates with a link to exchangerate-api.com (the free tier's attribution + requirement). - Clients fetch from our server only, so third parties don't learn users' IPs or currency usage. Clients cache rates offline. -- Currencies outside the ECB set can be used with a manually entered rate. +- The currency picker offers only **ISO 4217 currencies in circulation** + (`ACTIVE_CURRENCIES` in `packages/core/src/currencies.ts`, hand-maintained; + browsers' `Intl.supportedValuesOf('currency')` includes long-gone codes). + Those with a daily rate come first; the rest can be used with a manually + entered rate. A group or recent currency that has since been withdrawn + stays selectable. - Behind an interface so a paid intraday provider can be swapped in later. ### 8.3 Storage and limits diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index 8d673a0..67e156b 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -292,7 +292,7 @@ export function createApp(cfg: Config, store: Store) { function rates(res: ServerResponse, url: URL) { const date = url.searchParams.get('date') ?? new Date().toISOString().slice(0, 10); - if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new HttpError(400, 'bad date'); + if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || Number.isNaN(Date.parse(date))) throw new HttpError(400, 'bad date'); const r = store.ratesOn(date); if (!r) throw new HttpError(404, 'no rates'); // Past dates never change; today's may still be published later. diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index c9f0f9c..3d3b04b 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -26,6 +26,8 @@ export interface Config { pushEnabled: boolean; ratesEnabled: boolean; ratesBaseUrl: string; + /** supplementary EUR-based rates for currencies the ECB doesn't publish; empty = off */ + ratesExtraUrl: string; } export function loadConfig(env = process.env): Config { @@ -45,5 +47,7 @@ export function loadConfig(env = process.env): Config { pushEnabled: env.PUSH_DISABLED !== '1', ratesEnabled: env.RATES_DISABLED !== '1', ratesBaseUrl: env.RATES_BASE_URL || 'https://www.ecb.europa.eu/stats/eurofxref', + // `??`, not `||`: an explicitly empty value turns the extra source off. + ratesExtraUrl: env.RATES_EXTRA_URL ?? 'https://open.er-api.com/v6/latest/EUR', }; } diff --git a/apps/server/src/db.ts b/apps/server/src/db.ts index c550794..c23b618 100644 --- a/apps/server/src/db.ts +++ b/apps/server/src/db.ts @@ -19,6 +19,12 @@ export interface PushSub { deviceId: string; } +export interface RatesDay { + date: string; + rates: Record; + sources: Record; +} + export class Store { readonly db: DatabaseSync; @@ -65,6 +71,13 @@ export class Store { date TEXT PRIMARY KEY, json TEXT NOT NULL ); + -- Supplementary rates (see rates.ts), kept apart so ECB refreshes never + -- overwrite them and ECB always wins for currencies both publish. + CREATE TABLE IF NOT EXISTS rates_extra ( + date TEXT PRIMARY KEY, + source TEXT NOT NULL, + json TEXT NOT NULL + ); `); } @@ -160,12 +173,37 @@ export class Store { this.db.prepare('INSERT OR REPLACE INTO rates (date, json) VALUES (?, ?)').run(date, JSON.stringify(rates)); } - /** Rates for the latest published date on or before `date`. */ - ratesOn(date: string): { date: string; rates: Record } | undefined { + saveExtraRates(date: string, source: string, rates: Record): void { + this.db + .prepare('INSERT OR REPLACE INTO rates_extra (date, source, json) VALUES (?, ?, ?)') + .run(date, source, JSON.stringify(rates)); + } + + /** + * ECB rates for the latest published date on or before `date`, plus + * supplementary rates for currencies the ECB doesn't publish. `sources` + * names the origin of each supplementary rate (":"). + * Supplementary rates older than a week before `date` are not used. + */ + ratesOn(date: string): RatesDay | undefined { const r = this.db.prepare('SELECT date, json FROM rates WHERE date <= ? ORDER BY date DESC LIMIT 1').get(date) as | { date: string; json: string } | undefined; - return r && { date: r.date, rates: JSON.parse(r.json) }; + if (!r) return undefined; + const rates: Record = JSON.parse(r.json); + const sources: Record = {}; + const weekBefore = new Date(Date.parse(date) - 7 * 86400_000).toISOString().slice(0, 10); + const x = this.db + .prepare('SELECT date, source, json FROM rates_extra WHERE date <= ? AND date >= ? ORDER BY date DESC LIMIT 1') + .get(date, weekBefore) as { date: string; source: string; json: string } | undefined; + if (x) { + for (const [code, rate] of Object.entries(JSON.parse(x.json) as Record)) { + if (code in rates) continue; + rates[code] = rate; + sources[code] = `${x.source}:${x.date}`; + } + } + return { date: r.date, rates, sources }; } latestRatesDate(): string | undefined { diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 3a43c48..e2fdbe1 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -11,7 +11,7 @@ const server = createServer(createApp(cfg, store)); server.requestTimeout = 0; server.headersTimeout = 30_000; -const rates = new RatesService(store, cfg.ratesBaseUrl); +const rates = new RatesService(store, cfg.ratesBaseUrl, cfg.ratesExtraUrl); if (cfg.ratesEnabled) rates.start(); server.listen(cfg.port, cfg.host, () => { diff --git a/apps/server/src/rates.ts b/apps/server/src/rates.ts index e0bc450..792ead0 100644 --- a/apps/server/src/rates.ts +++ b/apps/server/src/rates.ts @@ -1,7 +1,35 @@ -// ECB daily reference rates (EUR-based). Fetched by the server so that -// clients never contact a third party (SPEC.md §8.2). +// Exchange rates, fetched by the server so that clients never contact a +// third party (SPEC.md §8.2): +// - ECB daily reference rates (EUR-based, ~30 currencies, history to 1999); +// - a supplementary EUR-based feed for everything else (e.g. ALL), in the +// format of ExchangeRate-API's free endpoint. It has no history, so its +// daily snapshots accumulate from the day the server starts fetching. import type { Store } from './db.ts'; +/** Short name stored with supplementary rates; the client labels it. */ +export const EXTRA_SOURCE = 'xr'; + +const DECIMAL_RE = /^\d{1,12}(?:\.\d{1,12})?$/; + +/** + * Parse an ExchangeRate-API style response + * (`{ result, base_code, time_last_update_unix, rates: { CODE: number } }`) + * into its UTC date and decimal-string rates. + */ +export function parseExtraRates(json: unknown): { date: string; rates: Record } { + const d = json as { result?: unknown; base_code?: unknown; time_last_update_unix?: unknown; rates?: unknown }; + if (d?.result !== 'success' || d.base_code !== 'EUR') throw new Error('not a successful EUR-based response'); + if (typeof d.time_last_update_unix !== 'number' || typeof d.rates !== 'object' || !d.rates) throw new Error('malformed response'); + const rates: Record = {}; + for (const [code, value] of Object.entries(d.rates as Record)) { + if (!/^[A-Z]{3}$/.test(code) || typeof value !== 'number' || !(value > 0)) continue; + const str = String(value); // e.g. 1e-7 would not be a valid rate string; skip it + if (DECIMAL_RE.test(str)) rates[code] = str; + } + if (Object.keys(rates).length === 0) throw new Error('no rates parsed'); + return { date: new Date(d.time_last_update_unix * 1000).toISOString().slice(0, 10), rates }; +} + /** Parse the ECB eurofxref XML into date → { currency: rate }. EUR = "1". */ export function parseEcbXml(xml: string): Map> { const out = new Map>(); @@ -19,10 +47,12 @@ export class RatesService { private timer: NodeJS.Timeout | undefined; private readonly store: Store; private readonly baseUrl: string; + private readonly extraUrl: string; - constructor(store: Store, baseUrl: string) { + constructor(store: Store, baseUrl: string, extraUrl = '') { this.store = store; this.baseUrl = baseUrl; + this.extraUrl = extraUrl; } async refresh(): Promise { @@ -38,9 +68,20 @@ export class RatesService { console.log(`rates: stored ${days.size} days from ${file}, latest ${this.store.latestRatesDate()}`); } + async refreshExtra(): Promise { + const res = await fetch(this.extraUrl, { signal: AbortSignal.timeout(60_000) }); + if (!res.ok) throw new Error(`extra rates: HTTP ${res.status}`); + const { date, rates } = parseExtraRates(await res.json()); + this.store.saveExtraRates(date, EXTRA_SOURCE, rates); + console.log(`rates: stored ${Object.keys(rates).length} extra rates for ${date}`); + } + /** Refresh now and then every 6 hours (ECB publishes once a day ~16:00 CET). */ start(): void { - const run = () => this.refresh().catch((e) => console.error(`rates: ${e.message}`)); + const run = () => { + this.refresh().catch((e) => console.error(`rates: ${e.message}`)); + if (this.extraUrl) this.refreshExtra().catch((e) => console.error(`rates: ${e.message}`)); + }; void run(); this.timer = setInterval(run, 6 * 3600_000); this.timer.unref(); diff --git a/apps/server/test/server.test.ts b/apps/server/test/server.test.ts index 5728658..5f27381 100644 --- a/apps/server/test/server.test.ts +++ b/apps/server/test/server.test.ts @@ -9,7 +9,7 @@ import { createApp } from '../src/app.ts'; import { loadConfig } from '../src/config.ts'; import { Store } from '../src/db.ts'; import { encryptPayload, isAllowedEndpoint, loadVapidKeys } from '../src/push.ts'; -import { parseEcbXml } from '../src/rates.ts'; +import { parseEcbXml, parseExtraRates } from '../src/rates.ts'; const b64u = (b: Buffer) => b.toString('base64url'); const newGroup = () => { @@ -35,6 +35,7 @@ before(async () => { }); store = new Store(cfg.dataDir); store.saveRates('2026-10-08', { EUR: '1', CZK: '24.4', USD: '1.12' }); + store.saveExtraRates('2026-10-09', 'xr', { EUR: '1', CZK: '24.9', ALL: '98.38' }); server = createServer(createApp(cfg, store)); await new Promise((r) => server.listen(0, '127.0.0.1', r)); const addr = server.address() as { port: number }; @@ -142,6 +143,27 @@ describe('rates and static', () => { assert.equal((await api('GET', '/api/rates?date=2020-01-01')).status, 404); }); + it('fills in currencies the ECB lacks from the extra source, ECB first', async () => { + const r = await api('GET', '/api/rates?date=2026-10-11'); + assert.equal(r.data.rates.ALL, '98.38'); + assert.equal(r.data.rates.CZK, '24.4'); + assert.deepEqual(r.data.sources, { ALL: 'xr:2026-10-09' }); + // A snapshot more than a week old is not used; ECB rates still are. + const late = await api('GET', '/api/rates?date=2026-10-20'); + assert.equal(late.data.rates.ALL, undefined); + assert.equal(late.data.rates.CZK, '24.4'); + assert.equal((await api('GET', '/api/rates?date=2026-02-30x')).status, 400); + assert.equal((await api('GET', '/api/rates?date=2026-13-45')).status, 400); + }); + + it('parses the extra rates feed', () => { + const t = Date.UTC(2026, 10, 6, 0, 2) / 1000; + const p = parseExtraRates({ result: 'success', base_code: 'EUR', time_last_update_unix: t, rates: { EUR: 1, ALL: 98.38, BAD: -1, XYZ: 1e-9, lower: 2 } }); + assert.deepEqual(p, { date: '2026-11-06', rates: { EUR: '1', ALL: '98.38' } }); + assert.throws(() => parseExtraRates({ result: 'error' })); + assert.throws(() => parseExtraRates({ result: 'success', base_code: 'USD', time_last_update_unix: t, rates: { EUR: 1 } })); + }); + it('parses ECB XML', () => { const xml = ''; assert.deepEqual(parseEcbXml(xml).get('2026-10-09'), { EUR: '1', USD: '1.1206', CZK: '24.369' }); diff --git a/apps/web/src/components/CurrencySelect.svelte b/apps/web/src/components/CurrencySelect.svelte index e289571..a50aef7 100644 --- a/apps/web/src/components/CurrencySelect.svelte +++ b/apps/web/src/components/CurrencySelect.svelte @@ -1,9 +1,10 @@ @@ -26,11 +27,11 @@ {#each recent as c}{/each} {/if} - - {#each ecb as c}{/each} + + {#each rated as c}{/each} {#if lists.other.length} - + {#each lists.other as c}{/each} {/if} diff --git a/apps/web/src/components/ExpenseEditor.svelte b/apps/web/src/components/ExpenseEditor.svelte index e434d20..73abe1f 100644 --- a/apps/web/src/components/ExpenseEditor.svelte +++ b/apps/web/src/components/ExpenseEditor.svelte @@ -138,7 +138,7 @@ return owedOriginal(e); }); - // Prefill the exchange rate from ECB rates. A rate typed by hand is kept + // Prefill the exchange rate from the server's daily rates. A rate typed by hand is kept // when the date changes, but not when the currency does. An existing // expense keeps its stored rate until one of them changes. let lastCurrency = untrack(() => currency); @@ -274,9 +274,11 @@ oninput={() => (rateSource = 'manual')} /> {base} +

{#if rateMissing && rateSource !== 'manual'}{t('rate_unavailable')} {:else if rateSource.startsWith('ecb:')}{t('rate_source_ecb', { date: fmtDate(rateSource.slice(4)) })} + {:else if rateSource.startsWith('xr:')}{t('rate_source_xr', { date: fmtDate(rateSource.slice(3)) })} {:else}{t('rate_source_manual')}{/if} {#if amount && isValidRate(rateText.trim().replace(',', '.'))} · ≈ {money(Math.round(amount * Number(rateText.replace(',', '.')) * 10 ** (exponent(base) - exp)), base)}{/if}

diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 1c4c8e3..9397dc5 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -62,7 +62,7 @@ export const api = { pushSubscribe: (id: string, token: string, sub: PushSubscriptionJSON, deviceId: string) => req('POST', `/api/groups/${id}/push`, { token, json: { ...sub, deviceId } }), pushUnsubscribe: (id: string, token: string, endpoint: string) => req('DELETE', `/api/groups/${id}/push`, { token, json: { endpoint } }), - rates: (date: string) => req<{ base: string; date: string; rates: Record }>('GET', `/api/rates?date=${date}`), + rates: (date: string) => req<{ base: string; date: string; rates: Record; sources?: Record }>('GET', `/api/rates?date=${date}`), }; /** diff --git a/apps/web/src/lib/locales/cs.ts b/apps/web/src/lib/locales/cs.ts index af00839..367e4b2 100644 --- a/apps/web/src/lib/locales/cs.ts +++ b/apps/web/src/lib/locales/cs.ts @@ -101,6 +101,9 @@ const cs: Messages = { rate: 'Směnný kurz', rate_source_ecb: 'Kurz ECB ze dne {date}', rate_source_manual: 'Zadáno ručně', + rate_source_xr: 'Kurz od Exchange Rate API ze dne {date}', + currencies_rated: 'Denní kurz', + currencies_manual: 'Kurz zadáte ručně', rate_unavailable: 'Pro tuto měnu není kurz k dispozici, zadejte ho prosím.', paid_by_label: 'Platil(a)', multiple_payers: 'Platilo více lidí', diff --git a/apps/web/src/lib/locales/en.ts b/apps/web/src/lib/locales/en.ts index c60c641..7db3eb5 100644 --- a/apps/web/src/lib/locales/en.ts +++ b/apps/web/src/lib/locales/en.ts @@ -109,6 +109,9 @@ const en = { rate: 'Exchange rate', rate_source_ecb: 'ECB rate from {date}', rate_source_manual: 'Entered manually', + rate_source_xr: 'Rates By Exchange Rate API, {date}', + currencies_rated: 'Daily rate', + currencies_manual: 'Enter rate manually', rate_unavailable: 'No rate available for this currency, please enter it.', paid_by_label: 'Paid by', multiple_payers: 'Several people paid', diff --git a/apps/web/src/lib/rates.ts b/apps/web/src/lib/rates.ts index 7a7aed4..f31b1a4 100644 --- a/apps/web/src/lib/rates.ts +++ b/apps/web/src/lib/rates.ts @@ -1,6 +1,7 @@ -// Exchange rates from our own server (ECB daily, EUR-based). Cached in +// Exchange rates from our own server (EUR-based: ECB daily, plus a +// supplementary source for currencies the ECB doesn't publish). Cached in // IndexedDB so prefilling still works offline (SPEC.md §5.2, §8.2). -import { rateToString } from '@oweme/core'; +import { ACTIVE_CURRENCIES, isActiveCurrency, rateToString } from '@oweme/core'; import { api } from './api.ts'; import { kvGet, kvSet } from './idb.ts'; import { today } from './format.ts'; @@ -8,6 +9,8 @@ import { today } from './format.ts'; export interface RatesDay { date: string; rates: Record; + /** ":" for rates not from the ECB (absent in older caches) */ + sources?: Record; } const memory = new Map>(); @@ -23,7 +26,7 @@ export function ratesOn(date: string): Promise { if (cached && date < today()) return cached; try { const r = await api.rates(date); - const day = { date: r.date, rates: r.rates }; + const day: RatesDay = { date: r.date, rates: r.rates, sources: r.sources ?? {} }; await kvSet(key, day); await kvSet('rates:latest', day); return day; @@ -44,7 +47,9 @@ export async function suggestRate(from: string, to: string, date: string): Promi const f = Number(day?.rates[from]); const tt = Number(day?.rates[to]); if (!day || !(f > 0) || !(tt > 0)) return null; - return { rate: rateToString(tt / f), source: `ecb:${day.date}` }; + // A cross rate is only as good as its weaker leg, so name that leg's source. + const source = day.sources?.[from] ?? day.sources?.[to] ?? `ecb:${day.date}`; + return { rate: rateToString(tt / f), source }; } /** Float conversion for display only (never stored). */ @@ -56,13 +61,9 @@ export async function displayRate(from: string, to: string): Promise 0 && tt > 0 ? tt / f : null; } -/** Currencies with ECB rates first, then every other ISO currency. */ -export async function currencyList(): Promise<{ ecb: string[]; other: string[] }> { +/** Active currencies with a known rate first, then the rest (manual rate). */ +export async function currencyList(): Promise<{ rated: string[]; other: string[] }> { const day = await ratesOn(today()); - const ecb = Object.keys(day?.rates ?? { EUR: '1', CZK: '1', USD: '1' }).sort(); - let all: string[] = []; - try { - all = Intl.supportedValuesOf('currency'); - } catch { /* old browser */ } - return { ecb, other: all.filter((c) => !ecb.includes(c)) }; + const rated = Object.keys(day?.rates ?? { EUR: '1', CZK: '1', USD: '1' }).filter(isActiveCurrency).sort(); + return { rated, other: ACTIVE_CURRENCIES.filter((c) => !rated.includes(c)) }; } diff --git a/packages/core/src/currencies.ts b/packages/core/src/currencies.ts new file mode 100644 index 0000000..d7cc409 --- /dev/null +++ b/packages/core/src/currencies.ts @@ -0,0 +1,32 @@ +// Currencies offered in the picker. Hardcoded rather than read from +// Intl.supportedValuesOf('currency'), which in browsers also returns +// historical codes (ATS, DEM, YUM, …) that nobody can spend any more. + +/** + * ISO 4217 currencies in circulation today. Excludes fund codes (CLF, USN, …), + * precious metals and other non-cash units (XAU, XDR, XSU), and codes that + * have been replaced: ANG → XCG (2025), BGN → EUR (2026), CUC (2021), + * HRK → EUR (2023), SLL → SLE (2024), ZWL → ZWG (2024). + * Update this list when ISO 4217 changes. + */ +export const ACTIVE_CURRENCIES: readonly string[] = [ + 'AED', 'AFN', 'ALL', 'AMD', 'AOA', 'ARS', 'AUD', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT', + 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BRL', 'BSD', 'BTN', 'BWP', 'BYN', 'BZD', 'CAD', + 'CDF', 'CHF', 'CLP', 'CNY', 'COP', 'CRC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', + 'DZD', 'EGP', 'ERN', 'ETB', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GHS', 'GIP', 'GMD', + 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HTG', 'HUF', 'IDR', 'ILS', 'INR', 'IQD', 'IRR', + 'ISK', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', + 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LYD', 'MAD', 'MDL', 'MGA', 'MKD', 'MMK', + 'MNT', 'MOP', 'MRU', 'MUR', 'MVR', 'MWK', 'MXN', 'MYR', 'MZN', 'NAD', 'NGN', 'NIO', + 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', + 'RON', 'RSD', 'RUB', 'RWF', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLE', + 'SOS', 'SRD', 'SSP', 'STN', 'SVC', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', + 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'UYU', 'UZS', 'VES', 'VND', 'VUV', + 'WST', 'XAF', 'XCD', 'XCG', 'XOF', 'XPF', 'YER', 'ZAR', 'ZMW', 'ZWG', +]; + +const ACTIVE = new Set(ACTIVE_CURRENCIES); + +export function isActiveCurrency(code: string): boolean { + return ACTIVE.has(code); +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 77e1e1b..8b1ce45 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -6,3 +6,4 @@ export * from './settle.ts'; export * from './recurring.ts'; export * from './stats.ts'; export * from './csv.ts'; +export * from './currencies.ts'; diff --git a/packages/core/test/core.test.ts b/packages/core/test/core.test.ts index dc56547..8d8e003 100644 --- a/packages/core/test/core.test.ts +++ b/packages/core/test/core.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest'; +import { ACTIVE_CURRENCIES, isActiveCurrency } from '../src/index.ts'; import { allocate, balances, convert, dueOccurrences, expensesCsv, inBase, logOrder, nthOccurrence, occurrenceId, parseAmount, rateToString, replay, settleUp, toDecimalString, computeStats, @@ -230,3 +231,13 @@ describe('stats and csv', () => { expect(expensesCsv(state)).toContain(`"'=HYPERLINK(""x"")"`); }); }); + +describe('ACTIVE_CURRENCIES', () => { + it('is sorted, unique ISO codes without replaced currencies', () => { + expect([...ACTIVE_CURRENCIES].sort()).toEqual(ACTIVE_CURRENCIES); + expect(new Set(ACTIVE_CURRENCIES).size).toBe(ACTIVE_CURRENCIES.length); + expect(ACTIVE_CURRENCIES.every((c) => /^[A-Z]{3}$/.test(c))).toBe(true); + for (const gone of ['ANG', 'BGN', 'CUC', 'HRK', 'SLL', 'ZWL', 'DEM', 'XDR']) expect(isActiveCurrency(gone)).toBe(false); + for (const c of ['ALL', 'CZK', 'EUR', 'XCG', 'ZWG']) expect(isActiveCurrency(c)).toBe(true); + }); +});