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
|
|
@ -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