Compare commits
No commits in common. "62c19192a726bc42480d39ba2f4b45cc4c6e64e0" and "1c691cd54f9a3095e426467781b504ed7e25c632" have entirely different histories.
62c19192a7
...
1c691cd54f
17 changed files with 34 additions and 212 deletions
|
|
@ -5,8 +5,7 @@ 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 daily rates — ECB, plus ExchangeRate-API for the
|
||||
rest (stored per expense, editable)
|
||||
- Multiple currencies with ECB daily rates (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)
|
||||
|
|
|
|||
22
SPEC.md
22
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 "xr:<date>", "manual" (see 8.2)
|
||||
"rateSource": "ecb:2026-10-08", // or "manual"
|
||||
"payers": [ { "member": "m1", "amount": 12050 } ], // sums to amount
|
||||
"split": {
|
||||
"mode": "equal", // equal | shares | exact | percent
|
||||
|
|
@ -370,27 +370,9 @@ 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:<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
|
||||
or currency usage. Clients cache rates offline.
|
||||
- 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.
|
||||
- Currencies outside the ECB set can be used with a manually entered rate.
|
||||
- Behind an interface so a paid intraday provider can be swapped in later.
|
||||
|
||||
### 8.3 Storage and limits
|
||||
|
|
|
|||
|
|
@ -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) || Number.isNaN(Date.parse(date))) throw new HttpError(400, 'bad date');
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(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,8 +26,6 @@ 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 {
|
||||
|
|
@ -47,7 +45,5 @@ 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,12 +19,6 @@ export interface PushSub {
|
|||
deviceId: string;
|
||||
}
|
||||
|
||||
export interface RatesDay {
|
||||
date: string;
|
||||
rates: Record<string, string>;
|
||||
sources: Record<string, string>;
|
||||
}
|
||||
|
||||
export class Store {
|
||||
readonly db: DatabaseSync;
|
||||
|
||||
|
|
@ -71,13 +65,6 @@ 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
|
||||
);
|
||||
`);
|
||||
}
|
||||
|
||||
|
|
@ -173,37 +160,12 @@ export class Store {
|
|||
this.db.prepare('INSERT OR REPLACE INTO rates (date, json) VALUES (?, ?)').run(date, JSON.stringify(rates));
|
||||
}
|
||||
|
||||
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 {
|
||||
/** Rates for the latest published date on or before `date`. */
|
||||
ratesOn(date: string): { date: string; rates: Record<string, string> } | 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;
|
||||
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 };
|
||||
return r && { date: r.date, rates: JSON.parse(r.json) };
|
||||
}
|
||||
|
||||
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, cfg.ratesExtraUrl);
|
||||
const rates = new RatesService(store, cfg.ratesBaseUrl);
|
||||
if (cfg.ratesEnabled) rates.start();
|
||||
|
||||
server.listen(cfg.port, cfg.host, () => {
|
||||
|
|
|
|||
|
|
@ -1,35 +1,7 @@
|
|||
// 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.
|
||||
// ECB daily reference rates (EUR-based). Fetched by the server so that
|
||||
// clients never contact a third party (SPEC.md §8.2).
|
||||
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>>();
|
||||
|
|
@ -47,12 +19,10 @@ 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, extraUrl = '') {
|
||||
constructor(store: Store, baseUrl: string) {
|
||||
this.store = store;
|
||||
this.baseUrl = baseUrl;
|
||||
this.extraUrl = extraUrl;
|
||||
}
|
||||
|
||||
async refresh(): Promise<void> {
|
||||
|
|
@ -68,20 +38,9 @@ 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}`));
|
||||
if (this.extraUrl) this.refreshExtra().catch((e) => console.error(`rates: ${e.message}`));
|
||||
};
|
||||
const run = () => this.refresh().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, parseExtraRates } from '../src/rates.ts';
|
||||
import { parseEcbXml } from '../src/rates.ts';
|
||||
|
||||
const b64u = (b: Buffer) => b.toString('base64url');
|
||||
const newGroup = () => {
|
||||
|
|
@ -35,7 +35,6 @@ 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 };
|
||||
|
|
@ -143,27 +142,6 @@ 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' });
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
<script lang="ts">
|
||||
import { currencyList } from '../lib/rates.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 lists = $state<{ rated: string[]; other: string[] }>({ rated: [], other: [] });
|
||||
let lists = $state<{ ecb: string[]; other: string[] }>({ ecb: [], other: [] });
|
||||
currencyList().then((l) => (lists = l));
|
||||
|
||||
const recent = (() => {
|
||||
|
|
@ -15,9 +14,9 @@
|
|||
}
|
||||
})();
|
||||
// Keep the current value selectable even before the lists load, or if
|
||||
// it's a code that is no longer in circulation (e.g. an old group in BGN).
|
||||
const rated = $derived(
|
||||
[...lists.rated, ...lists.other, ...recent].includes(value) ? lists.rated : [value, ...lists.rated],
|
||||
// it's a code this browser doesn't know.
|
||||
const ecb = $derived(
|
||||
[...lists.ecb, ...lists.other, ...recent].includes(value) ? lists.ecb : [value, ...lists.ecb],
|
||||
);
|
||||
</script>
|
||||
|
||||
|
|
@ -27,11 +26,11 @@
|
|||
{#each recent as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
|
||||
</optgroup>
|
||||
{/if}
|
||||
<optgroup label={t('currencies_rated')}>
|
||||
{#each rated as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
|
||||
<optgroup label="ECB">
|
||||
{#each ecb as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
|
||||
</optgroup>
|
||||
{#if lists.other.length}
|
||||
<optgroup label={t('currencies_manual')}>
|
||||
<optgroup label="…">
|
||||
{#each lists.other as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
|
||||
</optgroup>
|
||||
{/if}
|
||||
|
|
|
|||
|
|
@ -138,7 +138,7 @@
|
|||
return owedOriginal(e);
|
||||
});
|
||||
|
||||
// Prefill the exchange rate from the server's daily rates. A rate typed by hand is kept
|
||||
// Prefill the exchange rate from ECB 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,11 +274,9 @@
|
|||
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>; sources?: Record<string, string> }>('GET', `/api/rates?date=${date}`),
|
||||
rates: (date: string) => req<{ base: string; date: string; rates: Record<string, string> }>('GET', `/api/rates?date=${date}`),
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -101,9 +101,6 @@ 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,9 +109,6 @@ 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,7 +1,6 @@
|
|||
// Exchange rates from our own server (EUR-based: ECB daily, plus a
|
||||
// supplementary source for currencies the ECB doesn't publish). Cached in
|
||||
// Exchange rates from our own server (ECB daily, EUR-based). Cached in
|
||||
// IndexedDB so prefilling still works offline (SPEC.md §5.2, §8.2).
|
||||
import { ACTIVE_CURRENCIES, isActiveCurrency, rateToString } from '@oweme/core';
|
||||
import { rateToString } from '@oweme/core';
|
||||
import { api } from './api.ts';
|
||||
import { kvGet, kvSet } from './idb.ts';
|
||||
import { today } from './format.ts';
|
||||
|
|
@ -9,8 +8,6 @@ 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>>();
|
||||
|
|
@ -26,7 +23,7 @@ export function ratesOn(date: string): Promise<RatesDay | null> {
|
|||
if (cached && date < today()) return cached;
|
||||
try {
|
||||
const r = await api.rates(date);
|
||||
const day: RatesDay = { date: r.date, rates: r.rates, sources: r.sources ?? {} };
|
||||
const day = { date: r.date, rates: r.rates };
|
||||
await kvSet(key, day);
|
||||
await kvSet('rates:latest', day);
|
||||
return day;
|
||||
|
|
@ -47,9 +44,7 @@ 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;
|
||||
// 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 };
|
||||
return { rate: rateToString(tt / f), source: `ecb:${day.date}` };
|
||||
}
|
||||
|
||||
/** Float conversion for display only (never stored). */
|
||||
|
|
@ -61,9 +56,13 @@ export async function displayRate(from: string, to: string): Promise<number | nu
|
|||
return f > 0 && tt > 0 ? tt / f : null;
|
||||
}
|
||||
|
||||
/** Active currencies with a known rate first, then the rest (manual rate). */
|
||||
export async function currencyList(): Promise<{ rated: string[]; other: string[] }> {
|
||||
/** Currencies with ECB rates first, then every other ISO currency. */
|
||||
export async function currencyList(): Promise<{ ecb: string[]; other: string[] }> {
|
||||
const day = await ratesOn(today());
|
||||
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)) };
|
||||
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)) };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,32 +0,0 @@
|
|||
// 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);
|
||||
}
|
||||
|
|
@ -6,4 +6,3 @@ export * from './settle.ts';
|
|||
export * from './recurring.ts';
|
||||
export * from './stats.ts';
|
||||
export * from './csv.ts';
|
||||
export * from './currencies.ts';
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
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,
|
||||
|
|
@ -231,13 +230,3 @@ 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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue