Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

refactor: refactor update-exchange-rates.ts to only make one API call per run

Rob Carringtonce89acfdc918
diff --git a/apps/carbon/app/integrations/exchange-rates/exchange-rates.server.ts b/apps/carbon/app/integrations/exchange-rates/exchange-rates.server.ts
index 83039e8afe..8033ea43ff 100644
--- a/apps/carbon/app/integrations/exchange-rates/exchange-rates.server.ts
+++ b/apps/carbon/app/integrations/exchange-rates/exchange-rates.server.ts
@@ -3,7 +3,6 @@ import type { CurrencyCode } from "~/modules/accounting";
type ExchangeClientOptions = {
apiKey?: string;
apiUrl: string;
- baseCurrency: CurrencyCode;
};
export type Rates = { [key in CurrencyCode]?: number };
@@ -30,24 +29,25 @@ type ExchangeRatesResponse =
export class ExchangeRatesClient {
#apiKey: string;
#apiUrl: string;
- #baseCurrency: CurrencyCode;
constructor(options: ExchangeClientOptions) {
if (!options.apiKey) throw new Error("EXCHANGE_RATES_API_KEY not set");
this.#apiKey = options.apiKey;
this.#apiUrl = options.apiUrl;
- this.#baseCurrency = options.baseCurrency ?? "USD";
}
getMetaData() {
return {
apiUrl: this.#apiUrl,
- baseCurrency: this.#baseCurrency,
};
}
- async getExchangeRates(base?: CurrencyCode): Promise<Rates> {
+ async getExchangeRates(): Promise<Rates> {
+ /**
+ * Fetches the latest exchange rates from the API. For the free tier of the API, we can only fetch
+ * the rates with a base currency of EUR.
+ */
const url = `${this.#apiUrl}?access_key=${this.#apiKey}`;
const response = await fetch(url);
@@ -59,38 +59,46 @@ export class ExchangeRatesClient {
const data: ExchangeRatesResponse = await response.json();
if ("success" in data && data.success === true) {
- const baseRate = data.rates[base ?? this.#baseCurrency];
- if (!baseRate) throw new Error("Base rate not found in response");
-
- const convertedRates = Object.entries(data.rates).reduce<Rates>(
- (acc, [currency, value]) => {
- return {
- ...acc,
- [currency]: value / baseRate,
- };
- },
- {
- [data.base]: 1,
- }
- );
-
- return convertedRates;
+ return data.rates;
}
throw new Error("Unrecognized response from exchange rates server");
}
+
+ async convertExchangeRates(
+ baseCurrencyCode: CurrencyCode,
+ rates: Rates
+ ): Promise<Rates> {
+ /**
+ * Convert the EUR-based exchange rates to a different base currency.
+ */
+ const baseRate = rates[baseCurrencyCode];
+ if (!baseRate) throw new Error("Base rate not found");
+
+ const convertedRates = Object.entries(rates).reduce<Rates>(
+ (acc, [currency, value]) => {
+ return {
+ ...acc,
+ [currency]: value / baseRate,
+ };
+ },
+ {
+ [baseCurrencyCode]: 1,
+ }
+ );
+
+ return convertedRates;
+ }
}
export const getExchangeRatesClient = (
apiKey?: string,
- apiUrl: string = "https://api.exchangeratesapi.io/v1/latest",
- baseCurrency: CurrencyCode = "USD"
+ apiUrl: string = "https://api.exchangeratesapi.io/v1/latest"
) => {
return typeof apiKey === "string"
? new ExchangeRatesClient({
apiKey,
apiUrl,
- baseCurrency,
})
: undefined;
};
diff --git a/apps/carbon/app/trigger/update-exchange-rates.ts b/apps/carbon/app/trigger/update-exchange-rates.ts
index 7b6f5a08bf..43097bed7f 100644
--- a/apps/carbon/app/trigger/update-exchange-rates.ts
+++ b/apps/carbon/app/trigger/update-exchange-rates.ts
@@ -31,6 +31,40 @@ export const updateExchangeRates = schedules.task({
console.log(`Found ${integrations.data.length} active integrations`);
+ // Fetch the exchange rates for the base currency of EUR
+ const exchangeRatesClient = getExchangeRatesClient(EXCHANGE_RATES_API_KEY);
+
+ if (!exchangeRatesClient) {
+ console.error(
+ "Exchange rates client is undefined. Check API key configuration."
+ );
+ return;
+ }
+
+ let ratesEUR: Rates;
+ try {
+ ratesEUR = await exchangeRatesClient.getExchangeRates();
+ if (!ratesEUR)
+ throw new Error("No rates returned from exchange rates API");
+ console.log(
+ `Successfully fetched exchange rates with base currency of EUR for ${
+ Object.keys(ratesEUR).length
+ } currencies`
+ );
+ } catch (error) {
+ console.error(
+ `Error fetching exchange rates: ${
+ error instanceof Error ? error.message : String(error)
+ }`
+ );
+ return;
+ }
+
+ // Cache the rates for each currency to avoid unnecessary computations
+ let cachedRates: { [key in CurrencyCode]?: Rates } = {
+ EUR: ratesEUR,
+ };
+
for (const integration of integrations.data) {
console.log(
`Processing integration for company ID: ${integration.companyId}`
@@ -51,36 +85,19 @@ export const updateExchangeRates = schedules.task({
continue;
}
- const exchangeRatesClient = getExchangeRatesClient(
- EXCHANGE_RATES_API_KEY,
- undefined,
- company.data.baseCurrencyCode as CurrencyCode
- );
-
- if (!exchangeRatesClient) {
- console.error(
- "Exchange rates client is undefined. Check API key configuration."
- );
- return;
- }
-
- let rates: Rates;
- try {
- rates = await exchangeRatesClient.getExchangeRates();
- if (!rates)
- throw new Error("No rates returned from exchange rates API");
- console.log(
- `Successfully fetched exchange rates for ${
- Object.keys(rates).length
- } currencies`
- );
- } catch (error) {
- console.error(
- `Error fetching exchange rates: ${
- error instanceof Error ? error.message : String(error)
- }`
+ const baseCurrencyCode = company.data.baseCurrencyCode as CurrencyCode;
+ let rates: Rates | undefined;
+ rates = cachedRates[baseCurrencyCode];
+ // Check if the rates for this base currency are cached, and if not compute them
+ if (rates) {
+ console.log(`Using cached rates for ${baseCurrencyCode}`);
+ } else {
+ console.log(`Computing rates for ${baseCurrencyCode}`);
+ rates = await exchangeRatesClient.convertExchangeRates(
+ baseCurrencyCode,
+ ratesEUR
);
- return;
+ cachedRates[baseCurrencyCode] = rates;
}
const updatedAt = new Date().toISOString();