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.

fix: currency integration shouldn't require an API key

Brad Barbin9a6ef52480c1
diff --git a/apps/carbon/app/lib/exchange-rates.server.ts b/apps/carbon/app/lib/exchange-rates.server.ts
index f2ac896dd7..857abde1b4 100644
--- a/apps/carbon/app/lib/exchange-rates.server.ts
+++ b/apps/carbon/app/lib/exchange-rates.server.ts
@@ -2,7 +2,7 @@ import type { CurrencyCode } from "~/modules/accounting";
type ExchangeClientOptions = {
apiKey?: string;
- apiUrl?: string;
+ apiUrl: string;
baseCurrency: CurrencyCode;
};
@@ -34,7 +34,7 @@ export class ExchangeRatesClient {
constructor(options: ExchangeClientOptions) {
if (!options.apiKey) throw new Error("EXCHANGE_RATES_API_KEY not set");
- if (!options.apiUrl) throw new Error("EXCHANGE_RATES_API_URL not set");
+
this.#apiKey = options.apiKey;
this.#apiUrl = options.apiUrl;
this.#baseCurrency = options.baseCurrency ?? "USD";
@@ -48,7 +48,9 @@ export class ExchangeRatesClient {
}
async getExchangeRates(base?: CurrencyCode): Promise<Rates> {
- const response = await fetch(`${this.#apiUrl}?access_key=${this.#apiKey}`);
+ const url = `${this.#apiUrl}?access_key=${this.#apiKey}`;
+ console.log(url);
+ const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@@ -81,7 +83,7 @@ export class ExchangeRatesClient {
export const getExchangeRatesClient = (
apiKey?: string,
- apiUrl: string = "http://api.exchangeratesapi.io/v1/latest",
+ apiUrl: string = "https://api.exchangeratesapi.io/v1/latest",
baseCurrency: CurrencyCode = "USD"
) => {
return typeof apiKey === "string"
diff --git a/apps/carbon/app/modules/settings/integrations.models.ts b/apps/carbon/app/modules/settings/integrations.models.ts
index 71013e7f88..250f4a25b0 100644
--- a/apps/carbon/app/modules/settings/integrations.models.ts
+++ b/apps/carbon/app/modules/settings/integrations.models.ts
@@ -9,18 +9,7 @@ export const apiKey = z.object({
apiKey: z.string(),
});
-export const exchangeRatesFormValidator = integration.merge(apiKey).refine(
- (data) => {
- if (data.active) {
- return data.apiKey.length > 0;
- }
- return true;
- },
- {
- message: "API key is required when integration is active",
- path: ["apiKey"],
- }
-);
+export const exchangeRatesFormValidator = integration;
export const googlePlacesFormValidator = integration.merge(apiKey).refine(
(data) => {
diff --git a/apps/carbon/app/modules/settings/ui/Integrations/ExchangeRatesForm.tsx b/apps/carbon/app/modules/settings/ui/Integrations/ExchangeRatesForm.tsx
index 19467d4976..9bbd6295cc 100644
--- a/apps/carbon/app/modules/settings/ui/Integrations/ExchangeRatesForm.tsx
+++ b/apps/carbon/app/modules/settings/ui/Integrations/ExchangeRatesForm.tsx
@@ -12,7 +12,7 @@ import {
VStack,
} from "@carbon/react";
import type { z } from "zod";
-import { Boolean, Input, Submit } from "~/components/Form";
+import { Boolean, Submit } from "~/components/Form";
import { usePermissions } from "~/hooks";
import { exchangeRatesFormValidator } from "~/modules/settings";
import { path } from "~/utils/path";
@@ -54,7 +54,6 @@ const ExchangeRatesForm = ({
<DrawerBody>
<VStack spacing={4}>
<Boolean name="active" label="Active" />
- <Input name="apiKey" label="API Key" />
</VStack>
</DrawerBody>
<DrawerFooter>
diff --git a/apps/carbon/app/routes/x+/settings+/integrations.exchange-rates-v1.tsx b/apps/carbon/app/routes/x+/settings+/integrations.exchange-rates-v1.tsx
index bddc631154..e93f7ff1d7 100644
--- a/apps/carbon/app/routes/x+/settings+/integrations.exchange-rates-v1.tsx
+++ b/apps/carbon/app/routes/x+/settings+/integrations.exchange-rates-v1.tsx
@@ -15,7 +15,6 @@ import {
import { path } from "~/utils/path";
const defaultValue = {
- apiKey: "",
active: false,
};
@@ -65,14 +64,10 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const { active, ...data } = validation.data;
-
const update = await upsertIntegration(client, {
id: "exchange-rates-v1",
- active,
- metadata: {
- ...data,
- },
+ active: validation.data.active,
+ metadata: {},
companyId,
updatedBy: userId,
});
diff --git a/apps/carbon/app/trigger/update-exchange-rates.ts b/apps/carbon/app/trigger/update-exchange-rates.ts
index 3a384c0ce2..3fb869ae2d 100644
--- a/apps/carbon/app/trigger/update-exchange-rates.ts
+++ b/apps/carbon/app/trigger/update-exchange-rates.ts
@@ -1,64 +1,92 @@
-import { getCarbonServiceRole } from "@carbon/auth";
-import { schedules, wait } from "@trigger.dev/sdk/v3";
-import type { ExchangeRatesClient, Rates } from "~/lib/exchange-rates.server";
+import { EXCHANGE_RATES_API_KEY, getCarbonServiceRole } from "@carbon/auth";
+import { schedules } from "@trigger.dev/sdk/v3";
+import type { Rates } from "~/lib/exchange-rates.server";
import { getExchangeRatesClient } from "~/lib/exchange-rates.server";
import type { CurrencyCode } from "~/modules/accounting";
-import { exchangeRatesFormValidator } from "~/modules/settings";
const serviceRole = getCarbonServiceRole();
export const updateExchangeRates = schedules.task({
id: "update-exchange-rates",
- cron: "0 */8 * * *",
+ cron: "0 0 * * *",
run: async () => {
let rates: Rates;
- let hasRates = false;
- let exchangeRatesClient: ExchangeRatesClient | undefined;
+ console.log(`💵 Exchange Rates Task Started: ${new Date().toISOString()}`);
const integrations = await serviceRole
.from("companyIntegration")
- .select("active, metadata, companyId")
- .eq("id", "exchange-rates-v1");
+ .select("active, companyId")
+ .eq("id", "exchange-rates-v1")
+ .eq("active", true);
if (integrations.error) {
- console.error(JSON.stringify(integrations.error));
+ console.error(
+ `Error fetching integrations: ${JSON.stringify(integrations.error)}`
+ );
return;
}
- console.log(`💵 Exchange Rates Task: ${new Date().toISOString()}`);
- for (const integration of integrations.data) {
- const integrationMetadata = exchangeRatesFormValidator.safeParse(
- integration?.metadata
- );
+ if (integrations.data?.length === 0) {
+ console.log("No active exchange rate integrations found. Exiting task.");
+ return;
+ }
- if (!integrationMetadata.success || integration?.active !== true)
- continue;
+ console.log(`Found ${integrations.data.length} active integrations`);
- try {
- if (!hasRates) {
- exchangeRatesClient = getExchangeRatesClient(
- integrationMetadata.data.apiKey
- );
+ const exchangeRatesClient = getExchangeRatesClient(EXCHANGE_RATES_API_KEY);
+ if (!exchangeRatesClient) {
+ console.error(
+ "Exchange rates client is undefined. Check API key configuration."
+ );
+ return;
+ }
- if (!exchangeRatesClient) continue;
- console.log(JSON.stringify(exchangeRatesClient.getMetaData()));
- rates = await exchangeRatesClient.getExchangeRates();
- console.log(JSON.stringify(rates));
- hasRates = true;
- }
- // @ts-expect-error
- if (!rates) throw new Error("No rates found");
+ 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)
+ }`
+ );
+ return;
+ }
- const updatedAt = new Date().toISOString();
+ const updatedAt = new Date().toISOString();
- const { data } = await serviceRole
+ for (const integration of integrations.data) {
+ console.log(
+ `Processing integration for company ID: ${integration.companyId}`
+ );
+ try {
+ const { data, error } = await serviceRole
.from("currency")
.select("*")
.eq("companyId", integration.companyId);
- if (!data) continue;
+
+ if (error) {
+ console.error(
+ `Error fetching currencies for company ${
+ integration.companyId
+ }: ${JSON.stringify(error)}`
+ );
+ continue;
+ }
+
+ if (!data || data.length === 0) {
+ console.log(
+ `No currencies found for company ${integration.companyId}`
+ );
+ continue;
+ }
const updates = data
- // eslint-disable-next-line no-loop-func
.map((currency) => ({
...currency,
exchangeRate: Number(
@@ -70,21 +98,41 @@ export const updateExchangeRates = schedules.task({
}))
.filter((currency) => currency.exchangeRate);
- if (updates?.length === 0) continue;
-
- const { error } = await serviceRole.from("currency").upsert(updates);
- if (error) {
- console.error(JSON.stringify(error));
+ if (updates.length === 0) {
+ console.log(
+ `No currency updates needed for company ${integration.companyId}`
+ );
continue;
}
+
+ console.log(
+ `Updating ${updates.length} currencies for company ${integration.companyId}`
+ );
+ const { error: upsertError } = await serviceRole
+ .from("currency")
+ .upsert(updates);
+ if (upsertError) {
+ console.error(
+ `Error updating currencies for company ${
+ integration.companyId
+ }: ${JSON.stringify(upsertError)}`
+ );
+ } else {
+ console.log(
+ `Successfully updated currencies for company ${integration.companyId}`
+ );
+ }
} catch (err) {
- // TODO: notify someone
- console.error(JSON.stringify(err));
+ console.error(
+ `Unexpected error processing company ${integration.companyId}: ${
+ err instanceof Error ? err.message : String(err)
+ }`
+ );
}
}
- console.log("Success");
- // Wait for 8 hours before the next run
- await wait.for({ hours: 8 });
+ console.log(
+ `💵 Exchange Rates Task Completed: ${new Date().toISOString()}`
+ );
},
});
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index 66908b7745..01bea2daf5 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -76,10 +76,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
}),
]);
- if (storedLocations.updated) {
- console.log(`_layout.tsx`, storedLocations.location);
- }
-
return json(
{
session: {
diff --git a/apps/mes/app/routes/x+/location.tsx b/apps/mes/app/routes/x+/location.tsx
index 72d704f2b9..f7403a0bc6 100644
--- a/apps/mes/app/routes/x+/location.tsx
+++ b/apps/mes/app/routes/x+/location.tsx
@@ -19,7 +19,6 @@ export async function action({ request }: ActionFunctionArgs) {
const workCenters = await getWorkCentersByLocation(client, currentLocation);
const workCenter = workCenters?.data?.[0]?.id ?? "";
- console.log(`location.tsx: ${currentLocation}`);
throw redirect(path.to.authenticatedRoot, {
headers: {
"Set-Cookie": setLocationAndWorkCenter(currentLocation, workCenter),
diff --git a/packages/auth/src/config/env.ts b/packages/auth/src/config/env.ts
index 1f69c6851f..7684db3ef7 100644
--- a/packages/auth/src/config/env.ts
+++ b/packages/auth/src/config/env.ts
@@ -67,6 +67,10 @@ export const AUTODESK_CLIENT_SECRET = getEnv("AUTODESK_CLIENT_SECRET", {
isRequired: false,
});
export const DOMAIN = getEnv("DOMAIN", { isRequired: false }); // preview environments need no domain
+export const EXCHANGE_RATES_API_KEY = getEnv("EXCHANGE_RATES_API_KEY", {
+ isRequired: false,
+ isSecret: true,
+});
export const SUPABASE_SERVICE_ROLE = getEnv("SUPABASE_SERVICE_ROLE");
export const SESSION_SECRET = getEnv("SESSION_SECRET");
export const SESSION_KEY = "auth";
diff --git a/packages/database/supabase/migrations/20240930162032_exchange-rates-api-key.sql b/packages/database/supabase/migrations/20240930162032_exchange-rates-api-key.sql
new file mode 100644
index 0000000000..45c7d2433b
--- /dev/null
+++ b/packages/database/supabase/migrations/20240930162032_exchange-rates-api-key.sql
@@ -0,0 +1,3 @@
+UPDATE "integration"
+SET "jsonschema" = '{"type": "object", "properties": {}}'::json
+WHERE "id" = 'exchange-rates-v1';
\ No newline at end of file