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.

feat: slack endpoints

Brad Barbin888fd6c2e2ad
diff --git a/apps/academy/vite.config.ts b/apps/academy/vite.config.ts
index b07571e146..93a7d61821 100644
--- a/apps/academy/vite.config.ts
+++ b/apps/academy/vite.config.ts
@@ -23,6 +23,7 @@ export default defineConfig({
},
ssr: {
noExternal: [
+ "@slack/bolt",
"react-tweet",
"react-dropzone",
"react-icons",
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 8d36ff57d6..17a31bfa7b 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -474,7 +474,7 @@ export async function upsertIntegration(
updatedBy: string;
}
) {
- return client.from("companyIntegration").upsert([update]);
+ return client.from("companyIntegration").upsert([update]).select().single();
}
export async function updateDigitalQuoteSetting(
diff --git a/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.e.$eid.bom.ts b/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.e.$eid.bom.ts
index dd7e343113..bbfbecc38a 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.e.$eid.bom.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.e.$eid.bom.ts
@@ -1,8 +1,9 @@
import { requirePermissions } from "@carbon/auth/auth.server";
+import { Onshape as OnshapeConfig } from "@carbon/integrations";
+import { OnshapeClient } from "@carbon/integrations/onshape";
import type { ShouldRevalidateFunction } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
-import { Onshape as OnshapeConfig, OnshapeClient } from "@carbon/integrations";
import { getIntegration } from "~/modules/settings/settings.service";
import { getReadableIdWithRevision } from "~/utils/string";
diff --git a/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.elements.ts b/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.elements.ts
index f2ab747174..0891899cae 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.elements.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.elements.ts
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { OnshapeClient, Onshape as OnshapeConfig } from "@carbon/integrations";
+import { Onshape as OnshapeConfig } from "@carbon/integrations";
+import { OnshapeClient } from "@carbon/integrations/onshape";
import type { ShouldRevalidateFunction } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
diff --git a/apps/erp/app/routes/api+/integrations.onshape.d.$did.versions.ts b/apps/erp/app/routes/api+/integrations.onshape.d.$did.versions.ts
index 2216b2d13d..534fb13ae0 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.d.$did.versions.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.d.$did.versions.ts
@@ -1,8 +1,9 @@
import { requirePermissions } from "@carbon/auth/auth.server";
+import { Onshape as OnshapeConfig } from "@carbon/integrations";
+import { OnshapeClient } from "@carbon/integrations/onshape";
import type { ShouldRevalidateFunction } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
-import { Onshape as OnshapeConfig, OnshapeClient } from "@carbon/integrations";
import { getIntegration } from "~/modules/settings/settings.service";
export const shouldRevalidate: ShouldRevalidateFunction = () => {
diff --git a/apps/erp/app/routes/api+/integrations.onshape.documents.ts b/apps/erp/app/routes/api+/integrations.onshape.documents.ts
index 132f00b7de..d7fda1e4e2 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.documents.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.documents.ts
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { OnshapeClient, Onshape as OnshapeConfig } from "@carbon/integrations";
+import { Onshape as OnshapeConfig } from "@carbon/integrations";
+import { OnshapeClient } from "@carbon/integrations/onshape";
import type { ShouldRevalidateFunction } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
diff --git a/apps/erp/app/routes/api+/integrations.onshape.sync.ts b/apps/erp/app/routes/api+/integrations.onshape.sync.ts
index 3e0ec5aca6..da5b4c9d78 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.sync.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.sync.ts
@@ -1,6 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { onShapeDataValidator } from "@carbon/integrations";
+import { onShapeDataValidator } from "@carbon/integrations/onshape";
import { FunctionRegion } from "@supabase/supabase-js";
import { json, type ActionFunctionArgs } from "@vercel/remix";
diff --git a/apps/erp/app/routes/api+/integrations.slack.install.ts b/apps/erp/app/routes/api+/integrations.slack.install.ts
index e69de29bb2..0dae926486 100644
--- a/apps/erp/app/routes/api+/integrations.slack.install.ts
+++ b/apps/erp/app/routes/api+/integrations.slack.install.ts
@@ -0,0 +1,14 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getSlackInstallUrl } from "@carbon/integrations/slack";
+import { json, type LoaderFunctionArgs } from "@vercel/remix";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { userId, companyId } = await requirePermissions(request, {});
+
+ const url = await getSlackInstallUrl({
+ companyId,
+ userId,
+ });
+
+ return json({ url });
+}
diff --git a/apps/erp/app/routes/api+/integrations.slack.oauth.ts b/apps/erp/app/routes/api+/integrations.slack.oauth.ts
index e69de29bb2..e1e655a743 100644
--- a/apps/erp/app/routes/api+/integrations.slack.oauth.ts
+++ b/apps/erp/app/routes/api+/integrations.slack.oauth.ts
@@ -0,0 +1,142 @@
+import {
+ SLACK_CLIENT_ID,
+ SLACK_CLIENT_SECRET,
+ SLACK_OAUTH_REDIRECT_URL,
+} from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { Slack } from "@carbon/integrations";
+import {
+ createSlackApp,
+ getSlackInstaller,
+ slackAuthResponseSchema,
+} from "@carbon/integrations/slack";
+import { json, redirect, type LoaderFunctionArgs } from "@vercel/remix";
+import z from "zod";
+import { upsertIntegration } from "~/modules/settings/settings.service";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, userId, companyId } = await requirePermissions(request, {
+ update: "settings",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = Object.fromEntries(url.searchParams.entries());
+
+ const slackAuthResponse = slackAuthResponseSchema.safeParse(searchParams);
+
+ if (!slackAuthResponse.success) {
+ return json({ error: "Invalid Slack auth response" }, { status: 400 });
+ }
+
+ const { data } = slackAuthResponse;
+
+ const veryfiedState = await getSlackInstaller().stateStore?.verifyStateParam(
+ new Date(),
+ data.state
+ );
+ const parsedMetadata = z
+ .object({
+ companyId: z.string(),
+ userId: z.string(),
+ })
+ .safeParse(JSON.parse(veryfiedState?.metadata ?? "{}"));
+
+ if (!parsedMetadata.success) {
+ console.error("Invalid metadata", parsedMetadata.error.errors);
+ return json({ error: "Invalid metadata" }, { status: 400 });
+ }
+
+ if (parsedMetadata.data.companyId !== companyId) {
+ return json({ error: "Invalid company" }, { status: 400 });
+ }
+
+ if (parsedMetadata.data.userId !== userId) {
+ return json({ error: "Invalid user" }, { status: 400 });
+ }
+
+ try {
+ const slackOauthAccessUrl = [
+ "https://slack.com/api/oauth.v2.access",
+ `?client_id=${SLACK_CLIENT_ID}`,
+ `&client_secret=${SLACK_CLIENT_SECRET}`,
+ `&code=${data.code}`,
+ `&redirect_uri=${SLACK_OAUTH_REDIRECT_URL}`,
+ ].join("");
+
+ const response = await fetch(slackOauthAccessUrl);
+ const json = await response.json();
+
+ const parsedJson = slackAuthResponseSchema.safeParse(json);
+
+ if (!parsedJson.success) {
+ console.error(
+ "Invalid JSON response from slack",
+ parsedJson.error.errors
+ );
+ return json(
+ { error: "Failed to exchange code for token" },
+ { status: 500 }
+ );
+ }
+
+ const createdSlackIntegration = await upsertIntegration(client, {
+ id: Slack.id,
+ active: true,
+ metadata: {
+ access_token: data.access_token,
+ team_id: data.team.id,
+ team_name: data.team.name,
+ channel: data.incoming_webhook.channel,
+ channel_id: data.incoming_webhook.channel_id,
+ slack_configuration_url: data.incoming_webhook.configuration_url,
+ url: data.incoming_webhook.url,
+ bot_user_id: data.bot_user_id,
+ },
+ updatedBy: userId,
+ companyId: companyId,
+ });
+
+ if (createdSlackIntegration?.data?.metadata) {
+ const slackApp = createSlackApp({
+ token: data.access_token,
+ botId: data.bot_user_id,
+ });
+
+ try {
+ await slackApp.client.chat.postMessage({
+ channel: data.incoming_webhook.channel_id,
+ unfurl_links: false,
+ unfurl_media: false,
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "Ahoy maties! 🦜🏴‍☠️ Here be your new Cargh-bon bot. Use `/carbon` to get started.",
+ },
+ },
+ ],
+ });
+ } catch (err) {
+ console.error(err);
+ }
+
+ const requestUrl = new URL(request.url);
+
+ if (process.env.NODE_ENV === "development") {
+ requestUrl.protocol = "http";
+ }
+
+ return redirect(
+ `${requestUrl.origin}/all-done?event=app_oauth_completed`
+ );
+ }
+ } catch (err) {
+ return json(
+ { error: "Failed to exchange code for token" },
+ { status: 500 }
+ );
+ }
+
+ return json({ error: "Failed to exchange code for token" }, { status: 500 });
+}
diff --git a/apps/erp/vite.config.ts b/apps/erp/vite.config.ts
index c6724ca001..d5ac63a4d7 100644
--- a/apps/erp/vite.config.ts
+++ b/apps/erp/vite.config.ts
@@ -24,6 +24,7 @@ export default defineConfig({
},
ssr: {
noExternal: [
+ "@slack/bolt",
"react-tweet",
"react-dropzone",
"react-icons",
diff --git a/apps/mes/vite.config.ts b/apps/mes/vite.config.ts
index ad371e1985..6691980677 100644
--- a/apps/mes/vite.config.ts
+++ b/apps/mes/vite.config.ts
@@ -23,6 +23,7 @@ export default defineConfig({
},
ssr: {
noExternal: [
+ "@slack/bolt",
"react-tweet",
"react-dropzone",
"react-icons",
diff --git a/apps/starter/vite.config.ts b/apps/starter/vite.config.ts
index 2249021af4..ead86ab811 100644
--- a/apps/starter/vite.config.ts
+++ b/apps/starter/vite.config.ts
@@ -23,6 +23,7 @@ export default defineConfig({
},
ssr: {
noExternal: [
+ "@slack/bolt",
"react-tweet",
"react-dropzone",
"react-icons",
diff --git a/package-lock.json b/package-lock.json
index 0c1175947e..f521118505 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -36501,6 +36501,12 @@
"packages/integrations": {
"name": "@carbon/integrations",
"version": "*",
+ "dependencies": {
+ "@slack/bolt": "~4.4.0",
+ "@slack/oauth": "~3.0.3",
+ "@slack/web-api": "~7.6.0",
+ "zod": "^3.24.1"
+ },
"devDependencies": {
"@carbon/tsconfig": "*",
"typescript": "^5.2.2"
@@ -36566,12 +36572,10 @@
"@carbon/auth": "*",
"@carbon/database": "*",
"@carbon/kv": "*",
- "@slack/bolt": "~4.4.0",
- "@slack/oauth": "~3.0.3",
- "@slack/web-api": "~7.6.0",
"@supabase/supabase-js": "^2.40.0",
"@trigger.dev/sdk": "3.3.12",
- "resend": "^3.1.0"
+ "resend": "^3.1.0",
+ "zod": "^3.24.1"
},
"devDependencies": {
"@carbon/logger": "*",
diff --git a/packages/integrations/package.json b/packages/integrations/package.json
index 338234e87c..ac091683f6 100644
--- a/packages/integrations/package.json
+++ b/packages/integrations/package.json
@@ -3,7 +3,9 @@
"version": "*",
"exports": {
".": "./src/index.ts",
- "./exchange-rates/exchange-rates.server": "./src/exchange-rates/exchange-rates.server.ts"
+ "./exchange-rates/exchange-rates.server": "./src/exchange-rates/exchange-rates.server.ts",
+ "./slack": "./src/slack/lib/index.ts",
+ "./onshape": "./src/onshape/lib/index.ts"
},
"jest": {
"preset": "@carbon/jest/node"
@@ -15,7 +17,12 @@
"lint": "TIMING=1 eslint \"src/**/*.ts*\"",
"test": "jest"
},
- "dependencies": {},
+ "dependencies": {
+ "@slack/bolt": "~4.4.0",
+ "@slack/oauth": "~3.0.3",
+ "@slack/web-api": "~7.6.0",
+ "zod": "^3.24.1"
+ },
"devDependencies": {
"@carbon/tsconfig": "*",
"typescript": "^5.2.2"
diff --git a/packages/integrations/src/index.ts b/packages/integrations/src/index.ts
index b30c4c6275..1440c6b267 100644
--- a/packages/integrations/src/index.ts
+++ b/packages/integrations/src/index.ts
@@ -16,12 +16,14 @@ export const integrations = [
PaperlessParts,
Onshape,
Slack,
+ Sage,
QuickBooks,
Xero,
Zapier,
];
export { Onshape, Logo as OnshapeLogo } from "./onshape/config";
-export * from "./onshape/lib";
+export { Slack } from "./slack/config";
+// TODO: export as @carbon/integrations/paperless
export { PaperlessPartsClient } from "./paperless-parts/lib/client";
diff --git a/packages/integrations/src/slack/config.tsx b/packages/integrations/src/slack/config.tsx
index 351f131aa7..cb34c62251 100644
--- a/packages/integrations/src/slack/config.tsx
+++ b/packages/integrations/src/slack/config.tsx
@@ -5,16 +5,47 @@ export const Slack: IntegrationConfig = {
name: "Slack",
id: "slack",
category: "Assistant",
- active: false,
+ active: true,
logo: Logo,
- shortDescription:
- "Integrating with Carbon enables you to use Carbon Assistant within your Slack workspace.",
+ shortDescription: "Use the Carbon Assistant in your Slack workspace.",
description:
- "Integrating Carbon with Slack brings powerful capabilities directly into your team's communication hub. With this integration, you can seamlessly interact with Carbon without leaving your Slack workspace, enabling quick access to insights and actions.",
+ "Integrating Carbon with Slack allows you to use the Carbon Assistant to complete tasks from your Slack workspace.",
images: [],
settings: [],
schema: z.object({}),
- onInitialize: () => {},
+ onInitialize: async () => {
+ const response = await fetch("/api/integrations/slack/install").then(
+ (res) => res.json()
+ );
+
+ const { url } = response;
+
+ const width = 600;
+ const height = 800;
+ const left = window.screenX + (window.outerWidth - width) / 2;
+ const top = window.screenY + (window.outerHeight - height) / 2.5;
+
+ const popup = window.open(
+ url,
+ "",
+ `toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${width}, height=${height}, top=${top}, left=${left}`
+ );
+
+ if (!popup) {
+ window.location.href = url;
+ return;
+ }
+
+ const listener = (e: MessageEvent) => {
+ if (e.data === "app_oauth_completed") {
+ window.location.reload();
+ window.removeEventListener("message", listener);
+ popup.close();
+ }
+ };
+
+ window.addEventListener("message", listener);
+ },
onUninstall: () => {},
};
diff --git a/packages/integrations/src/slack/lib/client.ts b/packages/integrations/src/slack/lib/client.ts
index a386b9a01a..86be1b8781 100644
--- a/packages/integrations/src/slack/lib/client.ts
+++ b/packages/integrations/src/slack/lib/client.ts
@@ -1,6 +1,7 @@
import { LogLevel, App as SlackApp } from "@slack/bolt";
import { InstallProvider } from "@slack/oauth";
import { WebClient } from "@slack/web-api";
+import { z } from "zod";
import {
SLACK_CLIENT_ID,
@@ -10,6 +11,30 @@ import {
SLACK_STATE_SECRET,
} from "@carbon/auth";
+export const slackAuthResponseSchema = z.object({
+ ok: z.literal(true),
+ app_id: z.string(),
+ authed_user: z.object({
+ id: z.string(),
+ }),
+ code: z.string(),
+ scope: z.string(),
+ token_type: z.literal("bot"),
+ access_token: z.string(),
+ bot_user_id: z.string(),
+ team: z.object({
+ id: z.string(),
+ name: z.string(),
+ }),
+ incoming_webhook: z.object({
+ channel: z.string(),
+ channel_id: z.string(),
+ configuration_url: z.string().url(),
+ url: z.string().url(),
+ }),
+ state: z.any(),
+});
+
let slackInstaller: InstallProvider | null = null;
export const createSlackApp = ({
@@ -47,11 +72,11 @@ export const createSlackWebClient = ({ token }: { token: string }) => {
return new WebClient(token);
};
-export const getInstallUrl = ({
- teamId,
+export const getSlackInstallUrl = ({
+ companyId,
userId,
}: {
- teamId: string;
+ companyId: string;
userId: string;
}) => {
return getSlackInstaller().generateInstallUrl({
@@ -66,6 +91,6 @@ export const getInstallUrl = ({
"files:read",
],
redirectUri: SLACK_OAUTH_REDIRECT_URL,
- metadata: JSON.stringify({ teamId, userId }),
+ metadata: JSON.stringify({ companyId, userId }),
});
};
diff --git a/packages/integrations/src/slack/lib/index.ts b/packages/integrations/src/slack/lib/index.ts
new file mode 100644
index 0000000000..5ec76921e1
--- /dev/null
+++ b/packages/integrations/src/slack/lib/index.ts
@@ -0,0 +1 @@
+export * from "./client";
diff --git a/packages/integrations/src/slack/lib/init.ts b/packages/integrations/src/slack/lib/init.ts
deleted file mode 100644
index 286eb9608e..0000000000
--- a/packages/integrations/src/slack/lib/init.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-export const onInitialize = async () => {
- const response = await fetch("/api/integrations/slack/install").then((res) =>
- res.json()
- );
-
- const { url } = response;
-
- const width = 600;
- const height = 800;
- const left = window.screenX + (window.outerWidth - width) / 2;
- const top = window.screenY + (window.outerHeight - height) / 2.5;
-
- const popup = window.open(
- url,
- "",
- `toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${width}, height=${height}, top=${top}, left=${left}`
- );
-
- if (!popup) {
- window.location.href = url;
- return;
- }
-
- const listener = (e: MessageEvent) => {
- if (e.data === "app_oauth_completed") {
- window.location.reload();
- window.removeEventListener("message", listener);
- popup.close();
- }
- };
-
- window.addEventListener("message", listener);
-};
diff --git a/packages/lib/package.json b/packages/lib/package.json
index 6cf6653811..9ae3e1f0be 100644
--- a/packages/lib/package.json
+++ b/packages/lib/package.json
@@ -1,16 +1,13 @@
{
"name": "@carbon/lib",
- "type": "module",
"dependencies": {
"@carbon/auth": "*",
"@carbon/database": "*",
"@carbon/kv": "*",
- "@slack/bolt": "~4.4.0",
- "@slack/oauth": "~3.0.3",
- "@slack/web-api": "~7.6.0",
"@supabase/supabase-js": "^2.40.0",
"@trigger.dev/sdk": "3.3.12",
- "resend": "^3.1.0"
+ "resend": "^3.1.0",
+ "zod": "^3.24.1"
},
"devDependencies": {
"@carbon/logger": "*",