Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions apps/desktop-tauri/src-tauri/src/commands/currency.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::{collections::HashMap, path::PathBuf};

use codexbar::currency::{
SUPPORTED_CURRENCY_CODES, convert_amount, fallback_rates, fetch_exchange_rates,
normalize_preferred_currency,
CURRENCIES, convert_amount, fallback_rates, fetch_exchange_rates, normalize_preferred_currency,
};
use serde::{Deserialize, Serialize};
use tauri::State;
Expand Down Expand Up @@ -102,12 +101,12 @@ fn cache_path() -> Option<PathBuf> {

fn clean_rates(rates: HashMap<String, f64>) -> HashMap<String, f64> {
let mut clean = HashMap::new();
for code in SUPPORTED_CURRENCY_CODES {
if let Some(rate) = rates.get(*code).copied()
for currency in CURRENCIES {
if let Some(rate) = rates.get(currency.code).copied()
&& rate.is_finite()
&& rate > 0.0
{
clean.insert((*code).to_string(), rate);
clean.insert(currency.code.to_string(), rate);
}
}
if clean
Expand Down Expand Up @@ -154,16 +153,15 @@ fn persist_rates(cached: &PersistedRates) {
#[cfg(test)]
mod tests {
use super::*;
use codexbar::currency::FALLBACK_RATES;

#[test]
fn fallback_table_covers_every_preferred_currency() {
let rates = fallback_rates();
assert_eq!(rates.len(), FALLBACK_RATES.len());
for code in SUPPORTED_CURRENCY_CODES {
assert_eq!(rates.len(), CURRENCIES.len());
for currency in CURRENCIES {
assert!(
rates
.get(*code)
.get(currency.code)
.is_some_and(|rate| rate.is_finite() && *rate > 0.0)
);
}
Expand Down
34 changes: 34 additions & 0 deletions apps/desktop-tauri/src/lib/currency.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import {
CURRENCY_PICKER_OPTIONS,
FALLBACK_CURRENCY_RATES,
SUPPORTED_CURRENCIES,
convertCurrencyAmount,
formatDisplayCurrency,
mergeValidCurrencyRates,
Expand All @@ -23,6 +25,38 @@ describe("preferred currency display", () => {
expect(display).toMatch(/485/);
});

it("lists the twelve added currencies after TRY with upstream fallback rates", () => {
const added = ["NZD", "SEK", "NOK", "DKK", "PLN", "BRL", "MXN", "ZAR", "THB", "IDR", "VND", "UAH"];
const tryIndex = SUPPORTED_CURRENCIES.indexOf("TRY");
expect(SUPPORTED_CURRENCIES.slice(tryIndex + 1)).toEqual(added);
expect(CURRENCY_PICKER_OPTIONS.slice(tryIndex + 1).map((option) => option.label)).toEqual([
"NZD ($)", "SEK (kr)", "NOK (kr)", "DKK (kr)", "PLN (zł)", "BRL (R$)",
"MXN ($)", "ZAR (R)", "THB (฿)", "IDR (Rp)", "VND (₫)", "UAH (₴)",
]);
expect(FALLBACK_CURRENCY_RATES).toMatchObject({
NZD: 1.761, SEK: 9.908, NOK: 9.48, DKK: 6.554, PLN: 3.838, BRL: 5.117,
MXN: 17.47, ZAR: 16.36, THB: 33.37, IDR: 17836, VND: 25962, UAH: 44.86,
});
expect(Object.keys(FALLBACK_CURRENCY_RATES)).toEqual([...SUPPORTED_CURRENCIES]);
for (const code of added) expect(normalizePreferredCurrency(code.toLowerCase())).toBe(code);
});

it("converts each added currency through the USD pivot", () => {
for (const code of ["NZD", "SEK", "NOK", "DKK", "PLN", "BRL", "MXN", "ZAR", "THB", "IDR", "VND", "UAH"]) {
const rate = FALLBACK_CURRENCY_RATES[code];
expect(convertCurrencyAmount(10, "USD", code, FALLBACK_CURRENCY_RATES)).toBeCloseTo(10 * rate, 8);
expect(convertCurrencyAmount(10 * rate, code, "USD", FALLBACK_CURRENCY_RATES)).toBeCloseTo(10, 8);
}
expect(convertCurrencyAmount(10, "EUR", "SEK", FALLBACK_CURRENCY_RATES)).toBeCloseTo((10 / 0.92) * 9.908, 8);
});

it("formats zero-decimal currencies without fractional units", () => {
const vnd = formatDisplayCurrency(0.01, "USD", "VND", FALLBACK_CURRENCY_RATES);
expect(vnd).toMatch(/260/);
expect(vnd).not.toMatch(/[.,]\d{1,2}\D*$/);
expect(formatDisplayCurrency(1, "USD", "JPY", FALLBACK_CURRENCY_RATES)).toMatch(/154(?![.,]\d)/);
});

it("keeps AUTO, credits, unknown units, and missing-rate values in source units", () => {
expect(formatDisplayCurrency(4.25, "USD", "AUTO", FALLBACK_CURRENCY_RATES)).toMatch(/4\.25/);
expect(formatDisplayCurrency(4.25, "Credits", "TRY", FALLBACK_CURRENCY_RATES)).toBe("4.25 Credits");
Expand Down
40 changes: 12 additions & 28 deletions apps/desktop-tauri/src/lib/currency.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,18 @@
export const SUPPORTED_CURRENCIES = [
"USD", "GBP", "EUR", "CZK", "CNY", "JPY", "KRW", "CAD", "AUD", "HKD", "TWD", "SGD",
"INR", "CHF", "AED", "TRY",
] as const;
import { CURRENCY_CATALOG } from "./currencyCatalog.generated";

export const FALLBACK_CURRENCY_RATES: Record<string, number> = {
USD: 1,
GBP: 0.79,
EUR: 0.92,
CZK: 21,
CNY: 7.27,
JPY: 154,
KRW: 1428.9,
CAD: 1.38,
AUD: 1.55,
HKD: 7.8,
TWD: 32.3,
SGD: 1.34,
INR: 84.5,
CHF: 0.8,
AED: 3.6725,
TRY: 48.5,
};
// The catalog (order, symbols, offline rates) is generated from rust/src/currency.rs.
export const SUPPORTED_CURRENCIES: readonly string[] = CURRENCY_CATALOG.map((entry) => entry.code);

export const FALLBACK_CURRENCY_RATES: Record<string, number> = Object.fromEntries(
CURRENCY_CATALOG.map((entry) => [entry.code, entry.fallbackRate]),
);

export const CURRENCY_PICKER_OPTIONS: ReadonlyArray<{ value: string; label: string }> =
CURRENCY_CATALOG.map((entry) => ({ value: entry.code, label: `${entry.code} (${entry.symbol})` }));

export function normalizePreferredCurrency(value: string | null | undefined): string {
const code = value?.trim().toUpperCase() || "AUTO";
return code === "AUTO" || SUPPORTED_CURRENCIES.includes(code as (typeof SUPPORTED_CURRENCIES)[number])
? code
: "AUTO";
return code === "AUTO" || SUPPORTED_CURRENCIES.includes(code) ? code : "AUTO";
}

export function convertCurrencyAmount(
Expand All @@ -38,8 +24,7 @@ export function convertCurrencyAmount(
if (!Number.isFinite(amount)) return null;
const source = sourceCode.trim().toUpperCase();
const target = targetCode.trim().toUpperCase();
if (!SUPPORTED_CURRENCIES.includes(source as (typeof SUPPORTED_CURRENCIES)[number]) ||
!SUPPORTED_CURRENCIES.includes(target as (typeof SUPPORTED_CURRENCIES)[number])) return null;
if (!SUPPORTED_CURRENCIES.includes(source) || !SUPPORTED_CURRENCIES.includes(target)) return null;
if (source === target) return amount;
const sourceRate = source === "USD" ? 1 : rates[source];
const targetRate = target === "USD" ? 1 : rates[target];
Expand Down Expand Up @@ -77,7 +62,6 @@ export function formatDisplayCurrency(
return new Intl.NumberFormat(undefined, {
style: "currency",
currency: preferred,
maximumFractionDigits: 2,
}).format(converted);
} catch {
return `${converted.toFixed(2)} ${preferred}`;
Expand Down
32 changes: 32 additions & 0 deletions apps/desktop-tauri/src/lib/currencyCatalog.generated.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Generated from rust/src/currency.rs (CURRENCIES). Do not edit by hand.
// Regenerate: UPDATE_CURRENCY_CATALOG=1 cargo test -p codexbar currency_catalog
export const CURRENCY_CATALOG = [
{ code: "USD", symbol: "$", fallbackRate: 1 },
{ code: "GBP", symbol: "£", fallbackRate: 0.79 },
{ code: "EUR", symbol: "€", fallbackRate: 0.92 },
{ code: "CZK", symbol: "Kč", fallbackRate: 21 },
{ code: "CNY", symbol: "¥", fallbackRate: 7.27 },
{ code: "JPY", symbol: "¥", fallbackRate: 154 },
{ code: "KRW", symbol: "₩", fallbackRate: 1428.9 },
{ code: "CAD", symbol: "$", fallbackRate: 1.38 },
{ code: "AUD", symbol: "$", fallbackRate: 1.55 },
{ code: "HKD", symbol: "$", fallbackRate: 7.8 },
{ code: "TWD", symbol: "NT$", fallbackRate: 32.3 },
{ code: "SGD", symbol: "$", fallbackRate: 1.34 },
{ code: "INR", symbol: "₹", fallbackRate: 84.5 },
{ code: "CHF", symbol: "Fr.", fallbackRate: 0.8 },
{ code: "AED", symbol: "د.إ", fallbackRate: 3.6725 },
{ code: "TRY", symbol: "₺", fallbackRate: 48.5 },
{ code: "NZD", symbol: "$", fallbackRate: 1.761 },
{ code: "SEK", symbol: "kr", fallbackRate: 9.908 },
{ code: "NOK", symbol: "kr", fallbackRate: 9.48 },
{ code: "DKK", symbol: "kr", fallbackRate: 6.554 },
{ code: "PLN", symbol: "zł", fallbackRate: 3.838 },
{ code: "BRL", symbol: "R$", fallbackRate: 5.117 },
{ code: "MXN", symbol: "$", fallbackRate: 17.47 },
{ code: "ZAR", symbol: "R", fallbackRate: 16.36 },
{ code: "THB", symbol: "฿", fallbackRate: 33.37 },
{ code: "IDR", symbol: "Rp", fallbackRate: 17836 },
{ code: "VND", symbol: "₫", fallbackRate: 25962 },
{ code: "UAH", symbol: "₴", fallbackRate: 44.86 },
] as const;
Original file line number Diff line number Diff line change
Expand Up @@ -309,11 +309,16 @@ describe("GeneralTab language picker", () => {
});

describe("GeneralTab preferred currency picker", () => {
it("offers AUTO and every supported currency with the TRY symbol", () => {
it("offers AUTO then every catalog currency as CODE (symbol) in catalog order", () => {
render(<GeneralTab settings={settings} set={vi.fn()} saving={false} />);
const select = screen.getByLabelText("PreferredCurrencyLabel");
const options = Array.from(select.querySelectorAll("option"), (option) => option.textContent);
expect(options).toEqual(["AUTO", "USD", "GBP", "EUR", "CZK", "CNY", "JPY", "KRW", "CAD", "AUD", "HKD", "TWD", "SGD", "INR", "CHF", "AED", "TRY (₺)"]);
expect(options).toEqual([
"AUTO", "USD ($)", "GBP (£)", "EUR (€)", "CZK (Kč)", "CNY (¥)", "JPY (¥)", "KRW (₩)",
"CAD ($)", "AUD ($)", "HKD ($)", "TWD (NT$)", "SGD ($)", "INR (₹)", "CHF (Fr.)",
"AED (د.إ)", "TRY (₺)", "NZD ($)", "SEK (kr)", "NOK (kr)", "DKK (kr)", "PLN (zł)",
"BRL (R$)", "MXN ($)", "ZAR (R)", "THB (฿)", "IDR (Rp)", "VND (₫)", "UAH (₴)",
]);
});

it("persists an explicitly selected preferred currency", () => {
Expand Down
7 changes: 2 additions & 5 deletions apps/desktop-tauri/src/surfaces/settings/tabs/GeneralTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import type {
UsageThresholdOverride,
} from "../../../types/bridge";
import type { LocaleKey } from "../../../i18n/keys";
import { SUPPORTED_CURRENCIES } from "../../../lib/currency";
import { CURRENCY_PICKER_OPTIONS } from "../../../lib/currency";
import type { TabProps } from "../settingsTabs";

const FALLBACK_LANGUAGE_OPTIONS: LanguageOption[] = [
Expand Down Expand Up @@ -274,10 +274,7 @@ export default function GeneralTab({
ariaLabel={t("PreferredCurrencyLabel")}
options={[
{ value: "AUTO", label: "AUTO" },
...SUPPORTED_CURRENCIES.map((code) => ({
value: code,
label: code === "TRY" ? "TRY (₺)" : code,
})),
...CURRENCY_PICKER_OPTIONS,
]}
onChange={(value) => set({ preferredCurrencyCode: value })}
/>
Expand Down
Loading