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(suggestions): extract postSuggestionToCarbonSlack helper

naveenkashc6f4cb4cc7c3
diff --git a/apps/erp/app/routes/x+/resources+/suggestions.new.tsx b/apps/erp/app/routes/x+/resources+/suggestions.new.tsx
index f57d73bbcf..204791d26c 100644
--- a/apps/erp/app/routes/x+/resources+/suggestions.new.tsx
+++ b/apps/erp/app/routes/x+/resources+/suggestions.new.tsx
@@ -2,7 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
-import { getSlackClient } from "@carbon/lib/slack.server";
+import { postSuggestionToCarbonSlack } from "@carbon/lib/slack.server";
import { getLogger } from "@carbon/logger";
import { NotificationEvent } from "@carbon/notifications";
import type { ActionFunctionArgs } from "react-router";
@@ -59,65 +59,15 @@ export async function action({ request }: ActionFunctionArgs) {
const company = await getCompany(serviceRole, companyId);
if (sendToCarbon) {
- try {
- const [user, attachmentUrl] = await Promise.all([
- formUserId
- ? serviceRole
- .from("user")
- .select("firstName, lastName, email")
- .eq("id", formUserId)
- .single()
- : Promise.resolve(null),
- attachmentPath
- ? serviceRole.storage
- .from("private")
- .createSignedUrl(attachmentPath, 60 * 60 * 24 * 7)
- .then((result) => result.data?.signedUrl ?? null)
- : Promise.resolve(null)
- ]);
-
- const submittedBy = user?.data
- ? `${user.data.firstName ?? ""} ${user.data.lastName ?? ""} <${
- user.data.email ?? ""
- }>`
- : "Anonymous";
-
- const slackClient = getSlackClient();
- await slackClient.sendMessage({
- channel: "#feedback",
- text: `New suggestion from ${company.data?.name ?? companyId}`,
- blocks: [
- {
- type: "section",
- text: {
- type: "mrkdwn",
- text: `${emoji} New suggestion from *${
- company.data?.name ?? companyId
- }*`
- }
- },
- {
- type: "section",
- text: { type: "mrkdwn", text: suggestion }
- },
- {
- type: "section",
- fields: [
- { type: "mrkdwn", text: `*Submitted by:*\n${submittedBy}` },
- { type: "mrkdwn", text: `*Page:*\n${path}` },
- {
- type: "mrkdwn",
- text: `*Attachment:*\n${
- attachmentUrl ? `<${attachmentUrl}|View image>` : "None"
- }`
- }
- ]
- }
- ]
- });
- } catch (err) {
- logger.error("Failed to send suggestion to Slack", { error: err });
- }
+ await postSuggestionToCarbonSlack(serviceRole, {
+ companyId,
+ companyName: company.data?.name,
+ suggestion,
+ emoji,
+ path,
+ userId: formUserId,
+ attachmentPath
+ });
}
if (!company.error && company.data?.suggestionNotificationGroup?.length) {
diff --git a/apps/mes/app/routes/x+/suggestion.tsx b/apps/mes/app/routes/x+/suggestion.tsx
index bde5e6a736..7262cf658d 100644
--- a/apps/mes/app/routes/x+/suggestion.tsx
+++ b/apps/mes/app/routes/x+/suggestion.tsx
@@ -2,7 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
-import { getSlackClient } from "@carbon/lib/slack.server";
+import { postSuggestionToCarbonSlack } from "@carbon/lib/slack.server";
import { getLogger } from "@carbon/logger";
import { NotificationEvent } from "@carbon/notifications";
import type { ActionFunctionArgs } from "react-router";
@@ -62,65 +62,15 @@ export async function action({ request }: ActionFunctionArgs) {
.single();
if (sendToCarbon) {
- try {
- const [user, attachmentUrl] = await Promise.all([
- formUserId
- ? serviceRole
- .from("user")
- .select("firstName, lastName, email")
- .eq("id", formUserId)
- .single()
- : Promise.resolve(null),
- attachmentPath
- ? serviceRole.storage
- .from("private")
- .createSignedUrl(attachmentPath, 60 * 60 * 24 * 7)
- .then((result) => result.data?.signedUrl ?? null)
- : Promise.resolve(null)
- ]);
-
- const submittedBy = user?.data
- ? `${user.data.firstName ?? ""} ${user.data.lastName ?? ""} <${
- user.data.email ?? ""
- }>`
- : "Anonymous";
-
- const slackClient = getSlackClient();
- await slackClient.sendMessage({
- channel: "#feedback",
- text: `New suggestion from ${company.data?.name ?? companyId}`,
- blocks: [
- {
- type: "section",
- text: {
- type: "mrkdwn",
- text: `${emoji} New suggestion from *${
- company.data?.name ?? companyId
- }*`
- }
- },
- {
- type: "section",
- text: { type: "mrkdwn", text: suggestion }
- },
- {
- type: "section",
- fields: [
- { type: "mrkdwn", text: `*Submitted by:*\n${submittedBy}` },
- { type: "mrkdwn", text: `*Page:*\n${path}` },
- {
- type: "mrkdwn",
- text: `*Attachment:*\n${
- attachmentUrl ? `<${attachmentUrl}|View image>` : "None"
- }`
- }
- ]
- }
- ]
- });
- } catch (err) {
- log.error("Failed to send suggestion to Slack", { error: err });
- }
+ await postSuggestionToCarbonSlack(serviceRole, {
+ companyId,
+ companyName: company.data?.name,
+ suggestion,
+ emoji,
+ path,
+ userId: formUserId,
+ attachmentPath
+ });
}
if (!company.error && company.data?.suggestionNotificationGroup?.length) {
diff --git a/packages/lib/src/slack.server.ts b/packages/lib/src/slack.server.ts
index 67e907435a..543e5579e7 100644
--- a/packages/lib/src/slack.server.ts
+++ b/packages/lib/src/slack.server.ts
@@ -1,6 +1,8 @@
+import type { Database } from "@carbon/database";
import { getAppUrl, SLACK_BOT_TOKEN } from "@carbon/env";
import { getLogger } from "@carbon/logger";
import { WebClient } from "@slack/web-api";
+import type { SupabaseClient } from "@supabase/supabase-js";
const log = getLogger("lib", "slack");
@@ -39,3 +41,121 @@ export function getSlackClient(token?: string): SlackClient {
token ?? process.env.SLACK_BOT_TOKEN ?? SLACK_BOT_TOKEN ?? ""
);
}
+
+const SUGGESTION_CHANNEL = "#feedback";
+// Slack rejects section blocks over 3000 chars; stay under it and split long
+// text across blocks instead of truncating (50-block message ceiling).
+const SECTION_CHAR_LIMIT = 2900;
+const MAX_TEXT_BLOCKS = 12;
+
+function escapeSlackText(text: string): string {
+ return text
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;");
+}
+
+function splitForSections(text: string): string[] {
+ const chunks: string[] = [];
+ let start = 0;
+ while (start < text.length) {
+ let end = Math.min(start + SECTION_CHAR_LIMIT, text.length);
+ if (end < text.length) {
+ const newline = text.lastIndexOf("\n", end);
+ const space = text.lastIndexOf(" ", end);
+ const breakAt = Math.max(newline, space);
+ if (breakAt > start) end = breakAt;
+ }
+ chunks.push(text.slice(start, end));
+ start = end;
+ }
+ return chunks;
+}
+
+/**
+ * Posts a customer suggestion to Carbon's own Slack workspace (env
+ * SLACK_BOT_TOKEN), NOT the customer's linked workspace. Never throws — Slack
+ * being down must not fail the user's submission.
+ */
+export async function postSuggestionToCarbonSlack(
+ client: SupabaseClient<Database>,
+ input: {
+ companyId: string;
+ companyName?: string | null;
+ suggestion: string;
+ emoji: string;
+ path: string;
+ userId?: string | null;
+ attachmentPath?: string | null;
+ }
+): Promise<void> {
+ try {
+ const [user, attachmentUrl] = await Promise.all([
+ input.userId
+ ? client
+ .from("user")
+ .select("firstName, lastName, email")
+ .eq("id", input.userId)
+ .single()
+ : Promise.resolve(null),
+ input.attachmentPath
+ ? client.storage
+ .from("private")
+ .createSignedUrl(input.attachmentPath, 60 * 60 * 24 * 7)
+ .then((result) => result.data?.signedUrl ?? null)
+ : Promise.resolve(null)
+ ]);
+
+ const companyName = escapeSlackText(input.companyName ?? input.companyId);
+ const submittedBy = user?.data
+ ? `${escapeSlackText(
+ `${user.data.firstName ?? ""} ${user.data.lastName ?? ""}`.trim()
+ )} <${user.data.email ?? ""}>`
+ : "Anonymous";
+
+ const chunks = splitForSections(escapeSlackText(input.suggestion));
+ const textBlocks = chunks.slice(0, MAX_TEXT_BLOCKS).map((chunk) => ({
+ type: "section",
+ text: { type: "mrkdwn", text: chunk }
+ }));
+ if (chunks.length > MAX_TEXT_BLOCKS) {
+ textBlocks.push({
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "_… suggestion too long for Slack — read the full text in Carbon._"
+ }
+ });
+ }
+
+ await getSlackClient().sendMessage({
+ channel: SUGGESTION_CHANNEL,
+ text: `New suggestion from ${companyName}`,
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `${input.emoji} New suggestion from *${companyName}*`
+ }
+ },
+ ...textBlocks,
+ {
+ type: "section",
+ fields: [
+ { type: "mrkdwn", text: `*Submitted by:*\n${submittedBy}` },
+ { type: "mrkdwn", text: `*Page:*\n${escapeSlackText(input.path)}` },
+ {
+ type: "mrkdwn",
+ text: `*Attachment:*\n${
+ attachmentUrl ? `<${attachmentUrl}|View image>` : "None"
+ }`
+ }
+ ]
+ }
+ ]
+ });
+ } catch (error) {
+ log.error("Failed to post suggestion to Carbon Slack", { error });
+ }
+}