// 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 { rateToString } from '@oweme/core'; import { api } from './api.ts'; import { kvGet, kvSet } from './idb.ts'; import { today } from './format.ts'; export interface RatesDay { date: string; rates: Record; } const memory = new Map>(); /** Rates for a date (the latest published on or before it). */ export function ratesOn(date: string): Promise { let p = memory.get(date); if (!p) { p = (async () => { const key = `rates:${date}`; const cached = await kvGet(key); // A past date's rates never change; today's might still be published. if (cached && date < today()) return cached; try { const r = await api.rates(date); const day = { date: r.date, rates: r.rates }; await kvSet(key, day); await kvSet('rates:latest', day); return day; } catch { memory.delete(date); return cached ?? (await kvGet('rates:latest')) ?? null; } })(); memory.set(date, p); } return p; } /** Suggested rate string for 1 `from` = x `to`, or null if unknown. */ export async function suggestRate(from: string, to: string, date: string): Promise<{ rate: string; source: string } | null> { if (from === to) return { rate: '1', source: 'same' }; const day = await ratesOn(date); 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}` }; } /** Float conversion for display only (never stored). */ export async function displayRate(from: string, to: string): Promise { if (from === to) return 1; const day = await ratesOn(today()); const f = Number(day?.rates[from]); const tt = Number(day?.rates[to]); 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[] }> { 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)) }; }