oweme/apps/web/src/lib/rates.ts
agent 8fbbb4933e Add Svelte web client and service worker
Mobile-first PWA: groups via key-in-fragment links, encrypted outbox and
sync over SSE, all split modes, currencies with ECB rate prefill, photos,
comments, history and rewind, stats, recurring expenses, CSV and backup,
EN/CS, dark/light theme, Web Push decrypted in the service worker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
2026-10-09 19:59:16 +00:00

68 lines
2.4 KiB
TypeScript

// 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<string, string>;
}
const memory = new Map<string, Promise<RatesDay | null>>();
/** Rates for a date (the latest published on or before it). */
export function ratesOn(date: string): Promise<RatesDay | null> {
let p = memory.get(date);
if (!p) {
p = (async () => {
const key = `rates:${date}`;
const cached = await kvGet<RatesDay>(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<RatesDay>('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<number | null> {
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)) };
}