Rates for currencies the ECB lacks (ALL); only list currencies in circulation #5

Merged
reudy merged 2 commits from fix/currency-rates into main 2026-11-06 19:39:19 +01:00
17 changed files with 212 additions and 34 deletions

View file

@ -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 - 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 - 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) - One receipt photo per expense (resized, location data stripped, encrypted)
- Who-pays-whom settle-up suggestions, with "record payment" - Who-pays-whom settle-up suggestions, with "record payment"
- Full history: restore any version, or rewind the whole group (and undo that) - Full history: restore any version, or rewind the whole group (and undo that)

22
SPEC.md
View file

@ -156,7 +156,7 @@ entity fully defines it. Conflicts resolve **last-writer-wins by server
"currency": "EUR", "currency": "EUR",
"amount": 12050, // 120.50 EUR "amount": 12050, // 120.50 EUR
"rate": "25.214", // decimal string: 1 EUR = 25.214 base; "1" if same currency "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:<date>", "manual" (see 8.2)
"payers": [ { "member": "m1", "amount": 12050 } ], // sums to amount "payers": [ { "member": "m1", "amount": 12050 } ], // sums to amount
"split": { "split": {
"mode": "equal", // equal | shares | exact | percent "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 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 loads the full history (back to 1999) for back-dated expenses; later runs
fetch the last 90 days. 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:<date>" }` for every supplementary rate.
- An expense's `rateSource` is `ecb:<date>`, or `xr:<date>` 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 - Clients fetch from our server only, so third parties don't learn users' IPs
or currency usage. Clients cache rates offline. 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. - Behind an interface so a paid intraday provider can be swapped in later.
### 8.3 Storage and limits ### 8.3 Storage and limits

View file

@ -292,7 +292,7 @@ export function createApp(cfg: Config, store: Store) {
function rates(res: ServerResponse, url: URL) { function rates(res: ServerResponse, url: URL) {
const date = url.searchParams.get('date') ?? new Date().toISOString().slice(0, 10); 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); const r = store.ratesOn(date);
if (!r) throw new HttpError(404, 'no rates'); if (!r) throw new HttpError(404, 'no rates');
// Past dates never change; today's may still be published later. // Past dates never change; today's may still be published later.

View file

@ -26,6 +26,8 @@ export interface Config {
pushEnabled: boolean; pushEnabled: boolean;
ratesEnabled: boolean; ratesEnabled: boolean;
ratesBaseUrl: string; ratesBaseUrl: string;
/** supplementary EUR-based rates for currencies the ECB doesn't publish; empty = off */
ratesExtraUrl: string;
} }
export function loadConfig(env = process.env): Config { export function loadConfig(env = process.env): Config {
@ -45,5 +47,7 @@ export function loadConfig(env = process.env): Config {
pushEnabled: env.PUSH_DISABLED !== '1', pushEnabled: env.PUSH_DISABLED !== '1',
ratesEnabled: env.RATES_DISABLED !== '1', ratesEnabled: env.RATES_DISABLED !== '1',
ratesBaseUrl: env.RATES_BASE_URL || 'https://www.ecb.europa.eu/stats/eurofxref', 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',
}; };
} }

View file

@ -19,6 +19,12 @@ export interface PushSub {
deviceId: string; deviceId: string;
} }
export interface RatesDay {
date: string;
rates: Record<string, string>;
sources: Record<string, string>;
}
export class Store { export class Store {
readonly db: DatabaseSync; readonly db: DatabaseSync;
@ -65,6 +71,13 @@ export class Store {
date TEXT PRIMARY KEY, date TEXT PRIMARY KEY,
json TEXT NOT NULL 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)); 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`. */ saveExtraRates(date: string, source: string, rates: Record<string, string>): void {
ratesOn(date: string): { date: string; rates: Record<string, string> } | undefined { 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 ("<source>:<date>").
* 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 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 } | { date: string; json: string }
| undefined; | undefined;
return r && { date: r.date, rates: JSON.parse(r.json) }; if (!r) return undefined;
const rates: Record<string, string> = JSON.parse(r.json);
const sources: Record<string, string> = {};
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<string, string>)) {
if (code in rates) continue;
rates[code] = rate;
sources[code] = `${x.source}:${x.date}`;
}
}
return { date: r.date, rates, sources };
} }
latestRatesDate(): string | undefined { latestRatesDate(): string | undefined {

View file

@ -11,7 +11,7 @@ const server = createServer(createApp(cfg, store));
server.requestTimeout = 0; server.requestTimeout = 0;
server.headersTimeout = 30_000; 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(); if (cfg.ratesEnabled) rates.start();
server.listen(cfg.port, cfg.host, () => { server.listen(cfg.port, cfg.host, () => {

View file

@ -1,7 +1,35 @@
// ECB daily reference rates (EUR-based). Fetched by the server so that // Exchange rates, fetched by the server so that clients never contact a
// clients never contact a third party (SPEC.md §8.2). // 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'; 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<string, string> } {
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<string, string> = {};
for (const [code, value] of Object.entries(d.rates as Record<string, unknown>)) {
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". */ /** Parse the ECB eurofxref XML into date → { currency: rate }. EUR = "1". */
export function parseEcbXml(xml: string): Map<string, Record<string, string>> { export function parseEcbXml(xml: string): Map<string, Record<string, string>> {
const out = new Map<string, Record<string, string>>(); const out = new Map<string, Record<string, string>>();
@ -19,10 +47,12 @@ export class RatesService {
private timer: NodeJS.Timeout | undefined; private timer: NodeJS.Timeout | undefined;
private readonly store: Store; private readonly store: Store;
private readonly baseUrl: string; private readonly baseUrl: string;
private readonly extraUrl: string;
constructor(store: Store, baseUrl: string) { constructor(store: Store, baseUrl: string, extraUrl = '') {
this.store = store; this.store = store;
this.baseUrl = baseUrl; this.baseUrl = baseUrl;
this.extraUrl = extraUrl;
} }
async refresh(): Promise<void> { async refresh(): Promise<void> {
@ -38,9 +68,20 @@ export class RatesService {
console.log(`rates: stored ${days.size} days from ${file}, latest ${this.store.latestRatesDate()}`); console.log(`rates: stored ${days.size} days from ${file}, latest ${this.store.latestRatesDate()}`);
} }
async refreshExtra(): Promise<void> {
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). */ /** Refresh now and then every 6 hours (ECB publishes once a day ~16:00 CET). */
start(): void { 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(); void run();
this.timer = setInterval(run, 6 * 3600_000); this.timer = setInterval(run, 6 * 3600_000);
this.timer.unref(); this.timer.unref();

View file

@ -9,7 +9,7 @@ import { createApp } from '../src/app.ts';
import { loadConfig } from '../src/config.ts'; import { loadConfig } from '../src/config.ts';
import { Store } from '../src/db.ts'; import { Store } from '../src/db.ts';
import { encryptPayload, isAllowedEndpoint, loadVapidKeys } from '../src/push.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 b64u = (b: Buffer) => b.toString('base64url');
const newGroup = () => { const newGroup = () => {
@ -35,6 +35,7 @@ before(async () => {
}); });
store = new Store(cfg.dataDir); store = new Store(cfg.dataDir);
store.saveRates('2026-10-08', { EUR: '1', CZK: '24.4', USD: '1.12' }); 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)); server = createServer(createApp(cfg, store));
await new Promise<void>((r) => server.listen(0, '127.0.0.1', r)); await new Promise<void>((r) => server.listen(0, '127.0.0.1', r));
const addr = server.address() as { port: number }; 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); 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', () => { it('parses ECB XML', () => {
const xml = '<Cube><Cube time="2026-10-09"><Cube currency="USD" rate="1.1206"/><Cube currency="CZK" rate="24.369"/></Cube></Cube>'; const xml = '<Cube><Cube time="2026-10-09"><Cube currency="USD" rate="1.1206"/><Cube currency="CZK" rate="24.369"/></Cube></Cube>';
assert.deepEqual(parseEcbXml(xml).get('2026-10-09'), { EUR: '1', USD: '1.1206', CZK: '24.369' }); assert.deepEqual(parseEcbXml(xml).get('2026-10-09'), { EUR: '1', USD: '1.1206', CZK: '24.369' });

View file

@ -1,9 +1,10 @@
<script lang="ts"> <script lang="ts">
import { currencyList } from '../lib/rates.ts'; import { currencyList } from '../lib/rates.ts';
import { currencyName } from '../lib/format.ts'; import { currencyName } from '../lib/format.ts';
import { t } from '../lib/settings.svelte.ts';
let { value = $bindable(), disabled = false, id }: { value: string; disabled?: boolean; id?: string } = $props(); let { value = $bindable(), disabled = false, id }: { value: string; disabled?: boolean; id?: string } = $props();
let lists = $state<{ ecb: string[]; other: string[] }>({ ecb: [], other: [] }); let lists = $state<{ rated: string[]; other: string[] }>({ rated: [], other: [] });
currencyList().then((l) => (lists = l)); currencyList().then((l) => (lists = l));
const recent = (() => { const recent = (() => {
@ -14,9 +15,9 @@
} }
})(); })();
// Keep the current value selectable even before the lists load, or if // Keep the current value selectable even before the lists load, or if
// it's a code this browser doesn't know. // it's a code that is no longer in circulation (e.g. an old group in BGN).
const ecb = $derived( const rated = $derived(
[...lists.ecb, ...lists.other, ...recent].includes(value) ? lists.ecb : [value, ...lists.ecb], [...lists.rated, ...lists.other, ...recent].includes(value) ? lists.rated : [value, ...lists.rated],
); );
</script> </script>
@ -26,11 +27,11 @@
{#each recent as c}<option value={c}>{c} · {currencyName(c)}</option>{/each} {#each recent as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
</optgroup> </optgroup>
{/if} {/if}
<optgroup label="ECB"> <optgroup label={t('currencies_rated')}>
{#each ecb as c}<option value={c}>{c} · {currencyName(c)}</option>{/each} {#each rated as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
</optgroup> </optgroup>
{#if lists.other.length} {#if lists.other.length}
<optgroup label="…"> <optgroup label={t('currencies_manual')}>
{#each lists.other as c}<option value={c}>{c} · {currencyName(c)}</option>{/each} {#each lists.other as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
</optgroup> </optgroup>
{/if} {/if}

View file

@ -138,7 +138,7 @@
return owedOriginal(e); 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 // when the date changes, but not when the currency does. An existing
// expense keeps its stored rate until one of them changes. // expense keeps its stored rate until one of them changes.
let lastCurrency = untrack(() => currency); let lastCurrency = untrack(() => currency);
@ -274,9 +274,11 @@
oninput={() => (rateSource = 'manual')} /> oninput={() => (rateSource = 'manual')} />
<span class="muted">{base}</span> <span class="muted">{base}</span>
</div> </div>
<!-- xr: rates come from ExchangeRate-API's free tier, which requires the attribution link. -->
<p class="small muted" style:text-align="center"> <p class="small muted" style:text-align="center">
{#if rateMissing && rateSource !== 'manual'}{t('rate_unavailable')} {#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('ecb:')}{t('rate_source_ecb', { date: fmtDate(rateSource.slice(4)) })}
{:else if rateSource.startsWith('xr:')}<a href="https://www.exchangerate-api.com" target="_blank" rel="noopener noreferrer">{t('rate_source_xr', { date: fmtDate(rateSource.slice(3)) })}</a>
{:else}{t('rate_source_manual')}{/if} {: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} {#if amount && isValidRate(rateText.trim().replace(',', '.'))} · ≈ {money(Math.round(amount * Number(rateText.replace(',', '.')) * 10 ** (exponent(base) - exp)), base)}{/if}
</p> </p>

View file

@ -62,7 +62,7 @@ export const api = {
pushSubscribe: (id: string, token: string, sub: PushSubscriptionJSON, deviceId: string) => pushSubscribe: (id: string, token: string, sub: PushSubscriptionJSON, deviceId: string) =>
req('POST', `/api/groups/${id}/push`, { token, json: { ...sub, deviceId } }), 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 } }), 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<string, string> }>('GET', `/api/rates?date=${date}`), rates: (date: string) => req<{ base: string; date: string; rates: Record<string, string>; sources?: Record<string, string> }>('GET', `/api/rates?date=${date}`),
}; };
/** /**

View file

@ -101,6 +101,9 @@ const cs: Messages = {
rate: 'Směnný kurz', rate: 'Směnný kurz',
rate_source_ecb: 'Kurz ECB ze dne {date}', rate_source_ecb: 'Kurz ECB ze dne {date}',
rate_source_manual: 'Zadáno ručně', 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.', rate_unavailable: 'Pro tuto měnu není kurz k dispozici, zadejte ho prosím.',
paid_by_label: 'Platil(a)', paid_by_label: 'Platil(a)',
multiple_payers: 'Platilo více lidí', multiple_payers: 'Platilo více lidí',

View file

@ -109,6 +109,9 @@ const en = {
rate: 'Exchange rate', rate: 'Exchange rate',
rate_source_ecb: 'ECB rate from {date}', rate_source_ecb: 'ECB rate from {date}',
rate_source_manual: 'Entered manually', 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.', rate_unavailable: 'No rate available for this currency, please enter it.',
paid_by_label: 'Paid by', paid_by_label: 'Paid by',
multiple_payers: 'Several people paid', multiple_payers: 'Several people paid',

View file

@ -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). // 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 { api } from './api.ts';
import { kvGet, kvSet } from './idb.ts'; import { kvGet, kvSet } from './idb.ts';
import { today } from './format.ts'; import { today } from './format.ts';
@ -8,6 +9,8 @@ import { today } from './format.ts';
export interface RatesDay { export interface RatesDay {
date: string; date: string;
rates: Record<string, string>; rates: Record<string, string>;
/** "<source>:<date>" for rates not from the ECB (absent in older caches) */
sources?: Record<string, string>;
} }
const memory = new Map<string, Promise<RatesDay | null>>(); const memory = new Map<string, Promise<RatesDay | null>>();
@ -23,7 +26,7 @@ export function ratesOn(date: string): Promise<RatesDay | null> {
if (cached && date < today()) return cached; if (cached && date < today()) return cached;
try { try {
const r = await api.rates(date); 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(key, day);
await kvSet('rates:latest', day); await kvSet('rates:latest', day);
return 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 f = Number(day?.rates[from]);
const tt = Number(day?.rates[to]); const tt = Number(day?.rates[to]);
if (!day || !(f > 0) || !(tt > 0)) return null; 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). */ /** Float conversion for display only (never stored). */
@ -56,13 +61,9 @@ export async function displayRate(from: string, to: string): Promise<number | nu
return f > 0 && tt > 0 ? tt / f : null; return f > 0 && tt > 0 ? tt / f : null;
} }
/** Currencies with ECB rates first, then every other ISO currency. */ /** Active currencies with a known rate first, then the rest (manual rate). */
export async function currencyList(): Promise<{ ecb: string[]; other: string[] }> { export async function currencyList(): Promise<{ rated: string[]; other: string[] }> {
const day = await ratesOn(today()); const day = await ratesOn(today());
const ecb = Object.keys(day?.rates ?? { EUR: '1', CZK: '1', USD: '1' }).sort(); const rated = Object.keys(day?.rates ?? { EUR: '1', CZK: '1', USD: '1' }).filter(isActiveCurrency).sort();
let all: string[] = []; return { rated, other: ACTIVE_CURRENCIES.filter((c) => !rated.includes(c)) };
try {
all = Intl.supportedValuesOf('currency');
} catch { /* old browser */ }
return { ecb, other: all.filter((c) => !ecb.includes(c)) };
} }

View file

@ -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);
}

View file

@ -6,3 +6,4 @@ export * from './settle.ts';
export * from './recurring.ts'; export * from './recurring.ts';
export * from './stats.ts'; export * from './stats.ts';
export * from './csv.ts'; export * from './csv.ts';
export * from './currencies.ts';

View file

@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { ACTIVE_CURRENCIES, isActiveCurrency } from '../src/index.ts';
import { import {
allocate, balances, convert, dueOccurrences, expensesCsv, inBase, logOrder, nthOccurrence, allocate, balances, convert, dueOccurrences, expensesCsv, inBase, logOrder, nthOccurrence,
occurrenceId, parseAmount, rateToString, replay, settleUp, toDecimalString, computeStats, occurrenceId, parseAmount, rateToString, replay, settleUp, toDecimalString, computeStats,
@ -230,3 +231,13 @@ describe('stats and csv', () => {
expect(expensesCsv(state)).toContain(`"'=HYPERLINK(""x"")"`); 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);
});
});