Add a supplementary rate feed for currencies the ECB lacks (e.g. ALL)
The server also fetches ExchangeRate-API's free EUR-based endpoint (RATES_EXTRA_URL, empty = off), stored apart from ECB rates; ECB always wins for a currency both publish. /api/rates returns sources for supplementary rates, expenses record them as xr:<date>, and the editor shows the required attribution link. Snapshots older than a week before the requested date are not used. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HA82gVKYyo9BHLHPW4qr4x
This commit is contained in:
parent
6b0c80bb50
commit
62c19192a7
13 changed files with 160 additions and 27 deletions
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,6 +19,12 @@ export interface PushSub {
|
|||
deviceId: string;
|
||||
}
|
||||
|
||||
export interface RatesDay {
|
||||
date: string;
|
||||
rates: Record<string, string>;
|
||||
sources: Record<string, string>;
|
||||
}
|
||||
|
||||
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<string, string> } | undefined {
|
||||
saveExtraRates(date: string, source: string, rates: Record<string, string>): 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 ("<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
|
||||
| { date: string; json: string }
|
||||
| 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 {
|
||||
|
|
|
|||
|
|
@ -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, () => {
|
||||
|
|
|
|||
|
|
@ -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<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". */
|
||||
export function parseEcbXml(xml: string): 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 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<void> {
|
||||
|
|
@ -38,9 +68,20 @@ export class RatesService {
|
|||
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). */
|
||||
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();
|
||||
|
|
|
|||
|
|
@ -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<void>((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 = '<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' });
|
||||
|
|
|
|||
|
|
@ -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')} />
|
||||
<span class="muted">{base}</span>
|
||||
</div>
|
||||
<!-- xr: rates come from ExchangeRate-API's free tier, which requires the attribution link. -->
|
||||
<p class="small muted" style:text-align="center">
|
||||
{#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:')}<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}
|
||||
{#if amount && isValidRate(rateText.trim().replace(',', '.'))} · ≈ {money(Math.round(amount * Number(rateText.replace(',', '.')) * 10 ** (exponent(base) - exp)), base)}{/if}
|
||||
</p>
|
||||
|
|
|
|||
|
|
@ -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<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}`),
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -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í',
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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<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>>();
|
||||
|
|
@ -23,7 +26,7 @@ export function ratesOn(date: string): Promise<RatesDay | null> {
|
|||
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<number | nu
|
|||
return f > 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)) };
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue