37 lines
883 B
TypeScript
37 lines
883 B
TypeScript
export type NormalizePriceInput = {
|
|
amount: number;
|
|
currency: string;
|
|
exchangeRates?: Record<string, number>;
|
|
};
|
|
|
|
export type NormalizedPrice = {
|
|
currency: "USD";
|
|
amountUsd: number;
|
|
notes: string[];
|
|
};
|
|
|
|
export function normalizePriceToUsd(
|
|
input: NormalizePriceInput
|
|
): NormalizedPrice {
|
|
const currency = input.currency.trim().toUpperCase();
|
|
if (currency === "USD") {
|
|
return {
|
|
currency: "USD",
|
|
amountUsd: input.amount,
|
|
notes: ["Price already in USD."]
|
|
};
|
|
}
|
|
|
|
const rate = input.exchangeRates?.[currency];
|
|
if (typeof rate !== "number" || !Number.isFinite(rate) || rate <= 0) {
|
|
throw new Error(`Missing usable exchange rate for ${currency}.`);
|
|
}
|
|
|
|
const amountUsd = Math.round(input.amount * rate * 100) / 100;
|
|
return {
|
|
currency: "USD",
|
|
amountUsd,
|
|
notes: [`Converted ${currency} to USD using rate ${rate}.`]
|
|
};
|
|
}
|