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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add slack integration prototype
Brad Barbin1891fb58c981
diff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.tsindex ce9808f226..7316bb1070 100644--- a/apps/erp/app/modules/settings/settings.server.ts+++ b/apps/erp/app/modules/settings/settings.server.ts@@ -1,10 +1,12 @@-import type { Database } from "@carbon/database";+import type { Database, Json } from "@carbon/database";import { redis } from "@carbon/kv";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";import { sanitize } from "~/utils/supabase";import type { customFieldValidator } from "./settings.models";+const INTEGRATION_CACHE_TTL = 3600;+export async function clearCustomFieldsCache(companyId?: string) {const keys = companyId ? `customFields:${companyId}:*` : "customFields:*";redis.keys(keys).then(function (keys) {@@ -16,6 +18,47 @@ export async function clearCustomFieldsCache(companyId?: string) {});}+export async function clearCompanyIntegrationCache(+ companyId: string+): Promise<void> {+ const cacheKey = `integrations:${companyId}`;++ try {+ await redis.del(cacheKey);+ } catch (error) {+ console.error("Redis cache invalidation error:", error);+ }+}++export async function deactivateIntegration(+ client: SupabaseClient<Database>,+ args: {+ id: string;+ companyId: string;+ updatedBy: string;+ }+) {+ const { id, companyId, updatedBy } = args;++ const result = await client+ .from("companyIntegration")+ .update({+ active: false,+ updatedBy,+ updatedAt: new Date().toISOString(),+ })+ .eq("id", id)+ .eq("companyId", companyId);++ if (result.error) {+ return result;+ }++ await clearCompanyIntegrationCache(companyId);++ return result;+}+export async function deleteCustomField(client: SupabaseClient<Database>,id: string,@@ -28,6 +71,127 @@ export async function deleteCustomField(}}+interface CompanyIntegration {+ id: string;+ companyId: string;+ metadata: Record<string, any>;+ active: boolean;+}++export async function getCompanyIntegrations(+ client: SupabaseClient<Database>,+ companyId: string+): Promise<CompanyIntegration[]> {+ const cacheKey = `integrations:${companyId}`;++ try {+ const cached = await redis.get(cacheKey);+ if (cached) {+ return JSON.parse(cached as string);+ }+ } catch (error) {+ console.error("Redis cache read error:", error);+ }++ const { data, error } = await client+ .from("companyIntegration")+ .select("*")+ .eq("companyId", companyId);++ if (error) {+ throw error;+ }++ const integrations = data || [];++ try {+ await redis.setex(+ cacheKey,+ INTEGRATION_CACHE_TTL,+ JSON.stringify(integrations)+ );+ } catch (error) {+ console.error("Redis cache write error:", error);+ }++ return integrations as CompanyIntegration[];+}++export async function hasIntegration(+ client: SupabaseClient<Database>,+ companyId: string,+ integrationId: string+): Promise<boolean> {+ const integrations = await getCompanyIntegrations(client, companyId);+ return integrations.some((i) => i.id === integrationId && i.active === true);+}++export async function getCompanyIntegration(+ client: SupabaseClient<Database>,+ companyId: string,+ integrationId: string+): Promise<CompanyIntegration | null> {+ const integrations = await getCompanyIntegrations(client, companyId);+ return (+ integrations.find((i) => i.id === integrationId && i.active === true) ||+ null+ );+}++export async function getSlackIntegration(+ client: SupabaseClient<Database>,+ companyId: string+): Promise<{ token: string; channelId?: string } | null> {+ const integration = await getCompanyIntegration(client, companyId, "slack");++ if (!integration?.metadata) {+ return null;+ }++ const metadata = integration.metadata as any;++ if (!metadata.access_token) {+ return null;+ }++ return {+ token: metadata.access_token,+ channelId: metadata.channel_id || metadata.default_channel_id,+ };+}++export async function hasSlackIntegration(+ client: SupabaseClient<Database>,+ companyId: string+): Promise<boolean> {+ return hasIntegration(client, companyId, "slack");+}++export async function upsertCompanyIntegration(+ client: SupabaseClient<Database>,+ update: {+ id: string;+ active: boolean;+ metadata: Json;+ companyId: string;+ updatedBy: string;+ }+) {+ const result = await client+ .from("companyIntegration")+ .upsert([update])+ .select()+ .single();++ if (result.error) {+ return result;+ }++ await clearCompanyIntegrationCache(update.companyId);++ return result;+}+export async function upsertCustomField(client: SupabaseClient<Database>,customField:diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex 17a31bfa7b..5fec6316aa 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -1,6 +1,6 @@import { SUPABASE_URL } from "@carbon/auth";-import type { Database, Json } from "@carbon/database";+import type { Database } from "@carbon/database";import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";import type { z } from "zod";@@ -15,27 +15,6 @@ import type {webhookValidator,} from "./settings.models";-export async function deactivateIntegration(- client: SupabaseClient<Database>,- args: {- id: string;- companyId: string;- updatedBy: string;- }-) {- const { id, companyId, updatedBy } = args;-- return client- .from("companyIntegration")- .update({- active: false,- updatedBy,- updatedAt: new Date().toISOString(),- })- .eq("id", id)- .eq("companyId", companyId);-}-export async function deleteApiKey(client: SupabaseClient<Database>,id: string@@ -464,19 +443,6 @@ export async function upsertApiKey(return client.from("apiKey").update(sanitize(apiKey)).eq("id", apiKey.id);}-export async function upsertIntegration(- client: SupabaseClient<Database>,- update: {- id: string;- active: boolean;- metadata: Json;- companyId: string;- updatedBy: string;- }-) {- return client.from("companyIntegration").upsert([update]).select().single();-}-export async function updateDigitalQuoteSetting(client: SupabaseClient<Database>,companyId: string,diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsxindex 568c03a8bd..8a5953d786 100644--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx@@ -48,8 +48,9 @@ function IntegrationCard({const handleInstall = async () => {if (integration.settings.some((setting) => setting.required)) {navigate(path.to.integration(integration.id));+ } else if (integration.onInitialize) {+ await integration.onInitialize?.();} else {- integration.onInitialize?.();const formData = new FormData();fetcher.submit(formData, {method: "post",diff --git a/apps/erp/app/routes/api+/integrations.slack.interactive.ts b/apps/erp/app/routes/api+/integrations.slack.interactive.tsnew file mode 100644index 0000000000..54c30de65a--- /dev/null+++ b/apps/erp/app/routes/api+/integrations.slack.interactive.ts@@ -0,0 +1,442 @@+import { getCarbonServiceRole, VERCEL_URL } from "@carbon/auth";+import { createSlackWebClient } from "@carbon/integrations/slack.server";+import { tasks } from "@trigger.dev/sdk/v3";+import { json, type ActionFunctionArgs } from "@vercel/remix";+import { z } from "zod";+import {+ getIssueTypesList,+ getIssueWorkflowsList,+ upsertIssue,+} from "~/modules/quality/quality.service";+import {+ getIntegration,+ getNextSequence,+} from "~/modules/settings/settings.service";+import { path } from "~/utils/path";++export const config = {+ runtime: "nodejs",+};++// Slack interactive payload schema+const slackInteractivePayloadSchema = z.object({+ type: z.string(),+ team: z.object({+ id: z.string(),+ domain: z.string(),+ }),+ user: z.object({+ id: z.string(),+ name: z.string(),+ }),+ channel: z.object({+ id: z.string(),+ name: z.string(),+ }),+ trigger_id: z.string().optional(),+ response_url: z.string().optional(),+ actions: z.array(z.any()).optional(),+ view: z.any().optional(),+});++export async function action({ request }: ActionFunctionArgs) {+ try {+ // Verify the request is from Slack+ const formData = await request.formData();+ const payloadString = formData.get("payload") as string;++ if (!payloadString) {+ return json({ error: "Missing payload" }, { status: 400 });+ }++ const payload = slackInteractivePayloadSchema.parse(+ JSON.parse(payloadString)+ );++ // Get the service role client+ const serviceRole = await getCarbonServiceRole();++ // Get the Slack integration for this team+ const integration = await getIntegration(+ serviceRole,+ "slack",+ payload.team.id+ );++ if (!integration.data) {+ return json({+ response_type: "ephemeral",+ text: "Slack integration not found for this workspace.",+ });+ }++ const { companyId, metadata } = integration.data;+ const slackToken = (metadata as any)?.access_token as string;++ if (!slackToken) {+ return json({+ response_type: "ephemeral",+ text: "Slack token not found. Please reconfigure the integration.",+ });+ }++ // Handle different interaction types+ switch (payload.type) {+ case "block_actions":+ return handleBlockActions(payload, companyId, slackToken);++ case "view_submission":+ return handleViewSubmission(+ payload,+ companyId,+ slackToken,+ serviceRole+ );++ case "view_closed":+ // User closed the modal without submitting+ return json({ ok: true });++ default:+ return json({+ response_type: "ephemeral",+ text: `Unknown interaction type: ${payload.type}`,+ });+ }+ } catch (error) {+ console.error("Slack interactive error:", error);+ return json(+ {+ response_type: "ephemeral",+ text: "An error occurred processing your interaction. Please try again.",+ },+ { status: 500 }+ );+ }+}++async function handleBlockActions(+ payload: any,+ companyId: string,+ slackToken: string+) {+ const action = payload.actions?.[0];++ if (!action) {+ return json({ ok: true });+ }++ const slackClient = createSlackWebClient({ token: slackToken });++ switch (action.action_id) {+ case "open_ncr_modal":+ // Get lists for the modal+ const serviceRole = await getCarbonServiceRole();+ const [types, workflows] = await Promise.all([+ getIssueTypesList(serviceRole, companyId),+ getIssueWorkflowsList(serviceRole, companyId),+ ]);++ // Open the NCR creation modal+ await slackClient.views.open({+ trigger_id: payload.trigger_id,+ view: {+ type: "modal",+ callback_id: "create_ncr_modal",+ title: {+ type: "plain_text",+ text: "Create NCR",+ },+ submit: {+ type: "plain_text",+ text: "Create",+ },+ close: {+ type: "plain_text",+ text: "Cancel",+ },+ blocks: [+ {+ type: "input",+ block_id: "title_block",+ label: {+ type: "plain_text",+ text: "Title",+ },+ element: {+ type: "plain_text_input",+ action_id: "title",+ placeholder: {+ type: "plain_text",+ text: "Brief description of the non-conformance",+ },+ },+ },+ {+ type: "input",+ block_id: "description_block",+ label: {+ type: "plain_text",+ text: "Description",+ },+ element: {+ type: "plain_text_input",+ action_id: "description",+ multiline: true,+ placeholder: {+ type: "plain_text",+ text: "Detailed description of the issue",+ },+ },+ optional: true,+ },+ {+ type: "input",+ block_id: "type_block",+ label: {+ type: "plain_text",+ text: "Type",+ },+ element: {+ type: "static_select",+ action_id: "type",+ placeholder: {+ type: "plain_text",+ text: "Select issue type",+ },+ options:+ types.data?.map((type) => ({+ text: {+ type: "plain_text",+ text: type.name,+ },+ value: type.id,+ })) || [],+ },+ },+ {+ type: "input",+ block_id: "workflow_block",+ label: {+ type: "plain_text",+ text: "Workflow",+ },+ element: {+ type: "static_select",+ action_id: "workflow",+ placeholder: {+ type: "plain_text",+ text: "Select workflow",+ },+ options:+ workflows.data?.map((workflow) => ({+ text: {+ type: "plain_text",+ text: workflow.name,+ },+ value: workflow.id,+ })) || [],+ },+ optional: true,+ },+ {+ type: "input",+ block_id: "severity_block",+ label: {+ type: "plain_text",+ text: "Severity",+ },+ element: {+ type: "static_select",+ action_id: "severity",+ placeholder: {+ type: "plain_text",+ text: "Select severity",+ },+ options: [+ { text: { type: "plain_text", text: "Low" }, value: "Low" },+ {+ text: { type: "plain_text", text: "Medium" },+ value: "Medium",+ },+ { text: { type: "plain_text", text: "High" }, value: "High" },+ {+ text: { type: "plain_text", text: "Critical" },+ value: "Critical",+ },+ ],+ },+ optional: true,+ },+ ],+ private_metadata: JSON.stringify({+ channel_id: payload.channel.id,+ user_id: payload.user.id,+ }),+ },+ });++ return json({ ok: true });++ default:+ return json({ ok: true });+ }+}++async function handleViewSubmission(+ payload: any,+ companyId: string,+ slackToken: string,+ serviceRole: any+) {+ const view = payload.view;++ if (view.callback_id !== "create_ncr_modal") {+ return json({ ok: true });+ }++ try {+ // Extract form values+ const values = view.state.values;+ const title = values.title_block.title.value;+ const description = values.description_block?.description?.value || "";+ const typeId = values.type_block.type.selected_option?.value;+ const workflowId = values.workflow_block?.workflow?.selected_option?.value;+ const severity =+ values.severity_block?.severity?.selected_option?.value || "Medium";++ // Parse metadata+ const metadata = JSON.parse(view.private_metadata);+ const { channel_id, user_id } = metadata;++ // Get next sequence number+ const nextSequence = await getNextSequence(+ serviceRole,+ "nonConformance",+ companyId+ );++ if (nextSequence.error || !nextSequence.data) {+ throw new Error("Failed to get next sequence number");+ }++ // Create the non-conformance+ const createResult = await upsertIssue(serviceRole, {+ nonConformanceId: nextSequence.data,+ approvalRequirements: [],+ companyId,+ createdBy: "system", // TODO: Map Slack user to system user+ description,+ investigationTypeIds: [],+ locationId: "", // TODO+ name: title,+ nonConformanceTypeId: typeId,+ nonConformanceWorkflowId: workflowId,+ openDate: new Date().toISOString(),+ priority: severity,+ requiredActionIds: [],+ source: "Internal",+ });++ if (createResult.error || !createResult.data) {+ throw new Error("Failed to create non-conformance");+ }++ const ncrId = createResult.data.id;+ const slackClient = createSlackWebClient({ token: slackToken });++ // Post initial message to channel+ const threadMessage = await slackClient.chat.postMessage({+ channel: channel_id,+ unfurl_links: false,+ unfurl_media: false,+ blocks: [+ {+ type: "header",+ text: {+ type: "plain_text",+ text: `Issue #${nextSequence.data}`,+ },+ },+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*${title}*\n${description || "_No description provided_"}`,+ },+ fields: [+ {+ type: "mrkdwn",+ text: `*Status:*\nRegistered`,+ },+ {+ type: "mrkdwn",+ text: `*Severity:*\n${severity}`,+ },+ ],+ },+ {+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `Created by <@${user_id}>`,+ },+ ],+ },+ {+ type: "actions",+ elements: [+ {+ type: "button",+ text: {+ type: "plain_text",+ text: "View in Carbon",+ },+ url: `${VERCEL_URL || "http://localhost:3000"}${path.to.issue(+ ncrId+ )}`,+ action_id: "view_in_carbon",+ },+ ],+ },+ ],+ });++ // Store the thread mapping in the database+ if (threadMessage.ts) {+ await serviceRole.from("slackDocumentThread").insert({+ documentType: "nonConformance",+ documentId: ncrId,+ companyId,+ channelId: channel_id,+ threadTs: threadMessage.ts,+ createdBy: user_id,+ });++ // Trigger async job to sync additional details+ await tasks.trigger("slack-document-created", {+ documentType: "nonConformance",+ documentId: ncrId,+ companyId,+ channelId: channel_id,+ threadTs: threadMessage.ts,+ });+ }++ // Close the modal with success+ return json({+ response_action: "clear",+ });+ } catch (error) {+ console.error("Error creating NCR:", error);++ // Show error in modal+ return json({+ response_action: "errors",+ errors: {+ title_block: "Failed to create NCR. Please try again.",+ },+ });+ }+}diff --git a/apps/erp/app/routes/api+/integrations.slack.oauth.ts b/apps/erp/app/routes/api+/integrations.slack.oauth.tsindex 4e33786cc1..e61f758684 100644--- a/apps/erp/app/routes/api+/integrations.slack.oauth.ts+++ b/apps/erp/app/routes/api+/integrations.slack.oauth.ts@@ -9,11 +9,13 @@ import { Slack } from "@carbon/integrations";import {createSlackApp,getSlackInstaller,- slackAuthResponseSchema,+ slackOAuthCallbackSchema,+ slackOAuthTokenResponseSchema,} from "@carbon/integrations/slack.server";import { json, redirect, type LoaderFunctionArgs } from "@vercel/remix";import z from "zod";-import { upsertIntegration } from "~/modules/settings/settings.service";+import { upsertCompanyIntegration } from "~/modules/settings/settings.server";+import { path } from "~/utils/path";export const config = {runtime: "nodejs",@@ -27,7 +29,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = Object.fromEntries(url.searchParams.entries());- const slackAuthResponse = slackAuthResponseSchema.safeParse(searchParams);+ const slackAuthResponse = slackOAuthCallbackSchema.safeParse(searchParams);if (!slackAuthResponse.success) {return json({ error: "Invalid Slack auth response" }, { status: 400 });@@ -47,7 +49,6 @@ export async function loader({ request }: LoaderFunctionArgs) {.safeParse(JSON.parse(veryfiedState?.metadata ?? "{}"));if (!parsedMetadata.success) {- console.error("Invalid metadata", parsedMetadata.error.errors);return json({ error: "Invalid metadata" }, { status: 400 });}@@ -59,43 +60,79 @@ export async function loader({ request }: LoaderFunctionArgs) {return json({ error: "Invalid user" }, { status: 400 });}+ // Validate required environment variables+ if (!SLACK_CLIENT_ID || !SLACK_CLIENT_SECRET || !SLACK_OAUTH_REDIRECT_URL) {+ return json({ error: "Slack OAuth not configured" }, { status: 500 });+ }+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 body = new URLSearchParams({+ client_id: SLACK_CLIENT_ID,+ client_secret: SLACK_CLIENT_SECRET,+ code: data.code,+ redirect_uri: SLACK_OAUTH_REDIRECT_URL,+ });- const response = await fetch(slackOauthAccessUrl);- const json = await response.json();+ const response = await fetch("https://slack.com/api/oauth.v2.access", {+ method: "POST",+ headers: {+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body: body.toString(),+ });- const parsedJson = slackAuthResponseSchema.safeParse(json);+ if (!response.ok) {+ return json(+ { error: "Failed to exchange code for token - HTTP error" },+ { status: 500 }+ );+ }- if (!parsedJson.success) {- console.error(- "Invalid JSON response from slack",- parsedJson.error.errors+ const responseText = await response.text();++ let responseData;+ try {+ responseData = JSON.parse(responseText);+ } catch (parseError) {+ return json(+ { error: "Invalid JSON response from Slack" },+ { status: 500 });+ }++ // Check if Slack returned an error+ if (!responseData.ok) {return json(- { error: "Failed to exchange code for token" },+ { error: `Slack OAuth error: ${responseData.error}` },+ { status: 400 }+ );+ }++ const parsedJson = slackOAuthTokenResponseSchema.safeParse(responseData);++ if (!parsedJson.success) {+ return json(+ { error: "Failed to parse Slack OAuth response" },{ status: 500 });}- const createdSlackIntegration = await upsertIntegration(client, {+ const { data: tokenData } = parsedJson;++ const createdSlackIntegration = await upsertCompanyIntegration(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,+ access_token: tokenData.access_token,+ team_id: tokenData.team.id,+ team_name: tokenData.team.name,+ ...(tokenData.incoming_webhook && {+ channel: tokenData.incoming_webhook.channel,+ channel_id: tokenData.incoming_webhook.channel_id,+ slack_configuration_url: tokenData.incoming_webhook.configuration_url,+ url: tokenData.incoming_webhook.url,+ }),+ bot_user_id: tokenData.bot_user_id,},updatedBy: userId,companyId: companyId,@@ -103,27 +140,30 @@ export async function loader({ request }: LoaderFunctionArgs) {if (createdSlackIntegration?.data?.metadata) {const slackApp = createSlackApp({- token: data.access_token,- botId: data.bot_user_id,+ token: tokenData.access_token,+ botId: tokenData.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.",+ // Only try to post a message if we have webhook configuration+ if (tokenData.incoming_webhook?.channel_id) {+ try {+ await slackApp.client.chat.postMessage({+ channel: tokenData.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 `/` to get started.",+ },},- },- ],- });- } catch (err) {- console.error(err);+ ],+ });+ } catch (err) {+ // Silently fail if welcome message can't be posted+ }}const requestUrl = new URL(request.url);@@ -132,8 +172,13 @@ export async function loader({ request }: LoaderFunctionArgs) {requestUrl.protocol = "http";}- return redirect(- `${requestUrl.origin}/all-done?event=app_oauth_completed`+ const redirectUrl = `${requestUrl.origin}${path.to.integrations}`;++ return redirect(redirectUrl);+ } else {+ return json(+ { error: "Failed to save Slack integration" },+ { status: 500 });}} catch (err) {@@ -142,6 +187,4 @@ export async function loader({ request }: LoaderFunctionArgs) {{ status: 500 });}-- return json({ error: "Failed to exchange code for token" }, { status: 500 });}diff --git a/apps/erp/app/routes/x+/issue+/$id.status.tsx b/apps/erp/app/routes/x+/issue+/$id.status.tsxindex 752b5c8ff0..cf12c61a46 100644--- a/apps/erp/app/routes/x+/issue+/$id.status.tsx+++ b/apps/erp/app/routes/x+/issue+/$id.status.tsx@@ -1,14 +1,20 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { syncIssueStatusToSlack } from "@carbon/integrations/slack.server";import type { ActionFunctionArgs } from "@vercel/remix";import { redirect } from "@vercel/remix";-import { nonConformanceStatus, updateIssueStatus } from "~/modules/quality";+import {+ getIssue,+ nonConformanceStatus,+ updateIssueStatus,+} from "~/modules/quality";+import { hasSlackIntegration } from "~/modules/settings/settings.server";import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, userId, companyId } = await requirePermissions(request, {update: "quality",});@@ -27,6 +33,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ const currentIssue = await getIssue(client, id);+ const previousStatus = currentIssue.data?.status || "";+const [update] = await Promise.all([updateIssueStatus(client, {id,@@ -43,6 +52,24 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // Sync status update to Slack (non-blocking)+ try {+ const hasSlack = await hasSlackIntegration(client, companyId);+ if (hasSlack) {+ await syncIssueStatusToSlack(client, {+ nonConformanceId: id,+ companyId,+ previousStatus,+ newStatus: status,+ updatedBy: userId,+ reason: formData.get("reason") as string | undefined,+ });+ }+ } catch (error) {+ console.error("Failed to sync status to Slack:", error);+ // Continue without blocking the main operation+ }+throw redirect(requestReferrer(request) ?? path.to.issueDetails(id),await flash(request, success("Updated issue status"))diff --git a/apps/erp/app/routes/x+/issue+/new.tsx b/apps/erp/app/routes/x+/issue+/new.tsxindex af8edd0833..e434c9eda7 100644--- a/apps/erp/app/routes/x+/issue+/new.tsx+++ b/apps/erp/app/routes/x+/issue+/new.tsx@@ -19,7 +19,9 @@ import {} from "~/modules/quality";import IssueForm from "~/modules/quality/ui/Issue/IssueForm";+import { createIssueSlackThreadWithMessage } from "@carbon/integrations/slack.server";import { getNextSequence } from "~/modules/settings";+import { hasSlackIntegration } from "~/modules/settings/settings.server";import { setCustomFields } from "~/utils/form";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -52,7 +54,7 @@ export async function loader({ request }: LoaderFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { companyId, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {create: "quality",});@@ -122,6 +124,20 @@ export async function action({ request }: ActionFunctionArgs) {await flash(request, error("Failed to create tasks")));}++ try {+ const hasSlack = await hasSlackIntegration(client, companyId);+ if (hasSlack) {+ await createIssueSlackThreadWithMessage(serviceRole, {+ nonConformanceId: ncrId,+ companyId,+ createdBy: userId,+ });+ }+ } catch (error) {+ console.error("Failed to create Slack notification:", error);+ }+throw redirect(path.to.issue(ncrId!));}diff --git a/apps/erp/app/routes/x+/issue+/task.$id.status.tsx b/apps/erp/app/routes/x+/issue+/task.$id.status.tsxindex dc31b34ee6..4e6a5a892d 100644--- a/apps/erp/app/routes/x+/issue+/task.$id.status.tsx+++ b/apps/erp/app/routes/x+/issue+/task.$id.status.tsx@@ -3,12 +3,14 @@ import { json, type ActionFunctionArgs } from "@vercel/remix";import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { syncIssueTaskToSlack } from "@carbon/integrations/slack.server";import type { IssueInvestigationTask } from "~/modules/quality";import { updateIssueTaskStatus } from "~/modules/quality";+import { hasSlackIntegration } from "~/modules/settings/settings.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, userId, companyId } = await requirePermissions(request, {update: "quality",});@@ -27,6 +29,8 @@ export async function action({ request, params }: ActionFunctionArgs) {| "approval"| "review";const assignee = formData.get("assignee") as string;+ const nonConformanceId = formData.get("nonConformanceId") as string;+ const taskName = formData.get("taskName") as string;const update = await updateIssueTaskStatus(client, {id,@@ -42,5 +46,28 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // Sync task update to Slack if we have the required info (non-blocking)+ if (nonConformanceId && taskName && type !== "review") {+ try {+ const hasSlack = await hasSlackIntegration(client, companyId);+ if (hasSlack) {+ await syncIssueTaskToSlack(client, {+ nonConformanceId,+ companyId,+ taskType: type as "investigation" | "action" | "approval",+ taskName,+ status,+ assignedTo: assignee || undefined,+ completedBy: status === "Completed" ? userId : undefined,+ completedAt:+ status === "Completed" ? new Date().toISOString() : undefined,+ });+ }+ } catch (error) {+ console.error("Failed to sync task to Slack:", error);+ // Continue without blocking the main operation+ }+ }+return json({});}diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsxindex 4edeb4ef18..1807576351 100644--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx@@ -5,11 +5,8 @@ import { validationError, validator } from "@carbon/form";import { integrations as availableIntegrations } from "@carbon/integrations";import { redirect, useLoaderData, useNavigate } from "@remix-run/react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";-import {- IntegrationForm,- getIntegration,- upsertIntegration,-} from "~/modules/settings";+import { IntegrationForm, getIntegration } from "~/modules/settings";+import { upsertCompanyIntegration } from "~/modules/settings/settings.server";import { path } from "~/utils/path";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -65,7 +62,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const { active, ...data } = validation.data;- const update = await upsertIntegration(client, {+ const update = await upsertCompanyIntegration(client, {id: integrationId,active: true,metadata: {diff --git a/apps/erp/app/routes/x+/settings+/integrations.deactivate.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.deactivate.$id.tsxindex 66c22463c3..b19e3b29c5 100644--- a/apps/erp/app/routes/x+/settings+/integrations.deactivate.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.deactivate.$id.tsx@@ -4,7 +4,7 @@ import { flash } from "@carbon/auth/session.server";import { integrations as availableIntegrations } from "@carbon/integrations";import { redirect } from "@remix-run/react";import type { ActionFunctionArgs } from "@vercel/remix";-import { deactivateIntegration } from "~/modules/settings";+import { deactivateIntegration } from "~/modules/settings/settings.server";import { path } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 015912ec2d..8663c04ff9 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -45708,6 +45708,186 @@ export default {tags: ["purchaseInvoicePaymentRelation"],},},+ "/slackDocumentThread": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.id",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.documentType",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.documentId",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.channelId",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.threadTs",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.createdBy",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.updatedBy",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/order",+ },+ {+ $ref: "#/parameters/range",+ },+ {+ $ref: "#/parameters/rangeUnit",+ },+ {+ $ref: "#/parameters/offset",+ },+ {+ $ref: "#/parameters/limit",+ },+ {+ $ref: "#/parameters/preferCount",+ },+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/slackDocumentThread",+ },+ type: "array",+ },+ },+ "206": {+ description: "Partial Content",+ },+ },+ tags: ["slackDocumentThread"],+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.slackDocumentThread",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/preferPost",+ },+ ],+ responses: {+ "201": {+ description: "Created",+ },+ },+ tags: ["slackDocumentThread"],+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.id",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.documentType",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.documentId",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.channelId",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.threadTs",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.createdBy",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.updatedBy",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["slackDocumentThread"],+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.id",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.documentType",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.documentId",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.channelId",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.threadTs",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.createdBy",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.slackDocumentThread.updatedBy",+ },+ {+ $ref: "#/parameters/body.slackDocumentThread",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["slackDocumentThread"],+ },+ },"/purchaseOrderLines": {get: {parameters: [@@ -80657,6 +80837,70 @@ export default {},type: "object",},+ slackDocumentThread: {+ required: [+ "id",+ "companyId",+ "documentType",+ "documentId",+ "channelId",+ "threadTs",+ "createdAt",+ "createdBy",+ ],+ properties: {+ id: {+ default: "public.id('dst'::text)",+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string",+ },+ companyId: {+ description:+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string",+ },+ documentType: {+ format: "text",+ type: "string",+ },+ documentId: {+ format: "text",+ type: "string",+ },+ channelId: {+ format: "text",+ type: "string",+ },+ threadTs: {+ format: "text",+ type: "string",+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string",+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string",+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string",+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string",+ },+ },+ type: "object",+ },purchaseOrderLines: {properties: {id: {@@ -108879,6 +109123,75 @@ export default {in: "query",type: "string",},+ "body.slackDocumentThread": {+ name: "slackDocumentThread",+ description: "slackDocumentThread",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/slackDocumentThread",+ },+ },+ "rowFilter.slackDocumentThread.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.slackDocumentThread.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.slackDocumentThread.documentType": {+ name: "documentType",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.slackDocumentThread.documentId": {+ name: "documentId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.slackDocumentThread.channelId": {+ name: "channelId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.slackDocumentThread.threadTs": {+ name: "threadTs",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.slackDocumentThread.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.slackDocumentThread.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.slackDocumentThread.updatedAt": {+ name: "updatedAt",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.slackDocumentThread.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string",+ },"body.purchaseOrderLines": {name: "purchaseOrderLines",description: "purchaseOrderLines",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 6126e61062..3d35da2c5a 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -29751,6 +29751,144 @@ export type Database = {},]}+ slackDocumentThread: {+ Row: {+ channelId: string+ companyId: string+ createdAt: string+ createdBy: string+ documentId: string+ documentType: string+ id: string+ threadTs: string+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ channelId: string+ companyId: string+ createdAt?: string+ createdBy: string+ documentId: string+ documentType: string+ id?: string+ threadTs: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ channelId?: string+ companyId?: string+ createdAt?: string+ createdBy?: string+ documentId?: string+ documentType?: string+ id?: string+ threadTs?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "slackDocumentThread_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "slackDocumentThread_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "slackDocumentThread_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "slackDocumentThread_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }supplier: {Row: {accountManagerId: string | null@@ -47440,6 +47578,15 @@ export type Database = {| "Total"deadlineType: "No Deadline" | "ASAP" | "Soft Deadline" | "Hard Deadline"demandSourceType: "Sales Order" | "Job Material"+ document_thread_type:+ | "nonConformance"+ | "quote"+ | "salesOrder"+ | "job"+ | "purchaseOrder"+ | "invoice"+ | "receipt"+ | "shipment"documentSourceType:| "Job"| "Part"diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 6126e61062..3d35da2c5a 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -29751,6 +29751,144 @@ export type Database = {},]}+ slackDocumentThread: {+ Row: {+ channelId: string+ companyId: string+ createdAt: string+ createdBy: string+ documentId: string+ documentType: string+ id: string+ threadTs: string+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ channelId: string+ companyId: string+ createdAt?: string+ createdBy: string+ documentId: string+ documentType: string+ id?: string+ threadTs: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ channelId?: string+ companyId?: string+ createdAt?: string+ createdBy?: string+ documentId?: string+ documentType?: string+ id?: string+ threadTs?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "slackDocumentThread_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "slackDocumentThread_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "slackDocumentThread_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "slackDocumentThread_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "slackDocumentThread_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }supplier: {Row: {accountManagerId: string | null@@ -47440,6 +47578,15 @@ export type Database = {| "Total"deadlineType: "No Deadline" | "ASAP" | "Soft Deadline" | "Hard Deadline"demandSourceType: "Sales Order" | "Job Material"+ document_thread_type:+ | "nonConformance"+ | "quote"+ | "salesOrder"+ | "job"+ | "purchaseOrder"+ | "invoice"+ | "receipt"+ | "shipment"documentSourceType:| "Job"| "Part"diff --git a/packages/database/supabase/functions/slack-document-sync/index.ts b/packages/database/supabase/functions/slack-document-sync/index.tsnew file mode 100644index 0000000000..b6af07281f--- /dev/null+++ b/packages/database/supabase/functions/slack-document-sync/index.ts@@ -0,0 +1,238 @@+import { serve } from "https://deno.land/[email protected]/http/server.ts";+import { tasks } from "npm:@trigger.dev/[email protected]/v3";+import { z } from "npm:zod@^3.24.1";+import { corsHeaders } from "../lib/headers.ts";+import { getSupabaseServiceRole } from "../lib/supabase.ts";++const documentTypeSchema = z.enum([+ "nonConformance",+ "quote",+ "salesOrder",+ "job",+ "purchaseOrder",+ "invoice",+ "receipt",+ "shipment",+]);++type DocumentType = z.infer<typeof documentTypeSchema>;++const metadataSchema = z.record(z.unknown()).optional();++const payloadValidator = z.discriminatedUnion("updateType", [+ z.object({+ updateType: z.literal("created"),+ documentType: documentTypeSchema,+ documentId: z.string(),+ companyId: z.string(),+ channelId: z.string(),+ threadTs: z.string(),+ payload: z+ .object({+ metadata: metadataSchema,+ })+ .optional(),+ }),+ z.object({+ updateType: z.literal("status-update"),+ documentType: documentTypeSchema,+ documentId: z.string(),+ companyId: z.string(),+ payload: z.object({+ previousStatus: z.string(),+ newStatus: z.string(),+ updatedBy: z.string(),+ reason: z.string().optional(),+ metadata: metadataSchema,+ }),+ }),+ z.object({+ updateType: z.literal("task-update"),+ documentType: documentTypeSchema,+ documentId: z.string(),+ companyId: z.string(),+ payload: z.object({+ taskType: z.enum(["investigation", "action", "approval"]),+ taskName: z.string(),+ status: z.string(),+ assignedTo: z.string().optional(),+ completedBy: z.string().optional(),+ completedAt: z.string().optional(),+ notes: z.string().optional(),+ metadata: metadataSchema,+ }),+ }),+ z.object({+ updateType: z.literal("assignment-update"),+ documentType: documentTypeSchema,+ documentId: z.string(),+ companyId: z.string(),+ payload: z.object({+ previousAssignee: z.string().optional(),+ newAssignee: z.string(),+ updatedBy: z.string(),+ metadata: metadataSchema,+ }),+ }),+ z.object({+ updateType: z.literal("custom"),+ documentType: documentTypeSchema,+ documentId: z.string(),+ companyId: z.string(),+ payload: z.object({+ customType: z.string(),+ data: z.record(z.unknown()),+ }),+ }),+]);++type ValidatedPayload = z.infer<typeof payloadValidator>;++interface SlackIntegrationMetadata {+ access_token?: string;+ [key: string]: unknown;+}++serve(async (req: Request) => {+ if (req.method === "OPTIONS") {+ return new Response("ok", { headers: corsHeaders });+ }++ try {+ const body = await req.json();+ const validatedPayload = payloadValidator.parse(body);+ const {+ updateType,+ documentType,+ documentId,+ companyId,+ payload,+ ...otherData+ } = validatedPayload;++ console.log({+ function: "slack-document-sync",+ updateType,+ documentType,+ documentId,+ companyId,+ });++ // Check if Slack integration is enabled for this company+ const serviceRole = await getSupabaseServiceRole(+ req.headers.get("Authorization"),+ req.headers.get("carbon-key") ?? "",+ companyId+ );+ const { data: integration } = await serviceRole+ .from("companyIntegration")+ .select("metadata")+ .eq("companyId", companyId)+ .eq("active", true)+ .single();++ if (!integration?.metadata) {+ console.log("Slack integration not active for company", companyId);+ return new Response(+ JSON.stringify({+ success: true,+ message: "Slack integration not active",+ }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 200,+ }+ );+ }++ const metadata = integration.metadata as SlackIntegrationMetadata;++ // Check if notifications are enabled for this document type+ const notificationKey = `${documentType}_notifications_enabled`;+ if (metadata[notificationKey] === false) {+ console.log(+ `${documentType} notifications disabled for company`,+ companyId+ );+ return new Response(+ JSON.stringify({+ success: true,+ message: `${documentType} notifications disabled`,+ }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 200,+ }+ );+ }++ // Trigger the appropriate Trigger.dev job+ switch (updateType) {+ case "created": {+ const createdData = otherData as Extract<+ ValidatedPayload,+ { updateType: "created" }+ >;+ await tasks.trigger("slack-document-created", {+ documentType,+ documentId,+ companyId,+ channelId: createdData.channelId,+ threadTs: createdData.threadTs,+ });+ break;+ }++ case "status-update":+ await tasks.trigger("slack-document-status-update", {+ documentType,+ documentId,+ companyId,+ ...payload,+ });+ break;++ case "task-update":+ await tasks.trigger("slack-document-task-update", {+ documentType,+ documentId,+ companyId,+ ...payload,+ });+ break;++ case "assignment-update":+ await tasks.trigger("slack-document-assignment-update", {+ documentType,+ documentId,+ companyId,+ ...payload,+ });+ break;++ case "custom":+ // For now, just log custom updates+ console.log(`Custom update for ${documentType}:`, payload);+ break;++ default:+ throw new Error(`Invalid updateType ${updateType}`);+ }++ return new Response(+ JSON.stringify({+ success: true,+ }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 200,+ }+ );+ } catch (err) {+ console.error("slack-document-sync error:", err);+ return new Response(JSON.stringify(err), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 500,+ });+ }+});diff --git a/packages/database/supabase/migrations/20250810004621_slack-integration.sql b/packages/database/supabase/migrations/20250810004621_slack-integration.sqlindex de3f09f2ba..931451542f 100644--- a/packages/database/supabase/migrations/20250810004621_slack-integration.sql+++ b/packages/database/supabase/migrations/20250810004621_slack-integration.sql@@ -1,3 +1,3 @@INSERT INTO "integration" ("id", "jsonschema")VALUES- ('slack', '{"type": "object", "properties": {}'::json);\ No newline at end of file+ ('slack', '{"type": "object", "properties": {}}'::json);\ No newline at end of filediff --git a/packages/database/supabase/migrations/20250810203046_slack-nonconformance-integration.sql b/packages/database/supabase/migrations/20250810203046_slack-nonconformance-integration.sqlnew file mode 100644index 0000000000..8755922e49--- /dev/null+++ b/packages/database/supabase/migrations/20250810203046_slack-nonconformance-integration.sql@@ -0,0 +1,83 @@+-- Create table for mapping non-conformances to Slack threads+CREATE TABLE "nonConformanceSlackThread" (+ "id" TEXT NOT NULL DEFAULT id('ncslt'),+ "nonConformanceId" TEXT NOT NULL,+ "companyId" TEXT NOT NULL,+ "channelId" TEXT NOT NULL,+ "threadTs" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "nonConformanceSlackThread_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "nonConformanceSlackThread_nonConformanceId_fkey" FOREIGN KEY ("nonConformanceId") REFERENCES "nonConformance"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "nonConformanceSlackThread_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "nonConformanceSlackThread_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "nonConformanceSlackThread_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "nonConformanceSlackThread_unique" UNIQUE ("nonConformanceId", "companyId")+);++-- Create indexes for efficient lookups+CREATE INDEX "nonConformanceSlackThread_nonConformanceId_idx" ON "nonConformanceSlackThread" ("nonConformanceId");+CREATE INDEX "nonConformanceSlackThread_companyId_idx" ON "nonConformanceSlackThread" ("companyId");+CREATE INDEX "nonConformanceSlackThread_channelId_threadTs_idx" ON "nonConformanceSlackThread" ("channelId", "threadTs");++-- Enable Row Level Security+ALTER TABLE "nonConformanceSlackThread" ENABLE ROW LEVEL SECURITY;++-- RLS Policies using modern pattern+CREATE POLICY "SELECT" ON "public"."nonConformanceSlackThread"+FOR SELECT USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('quality_view'))::text[]+ )+);++CREATE POLICY "INSERT" ON "public"."nonConformanceSlackThread"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('quality_create'))::text[]+ )+);++CREATE POLICY "UPDATE" ON "public"."nonConformanceSlackThread"+FOR UPDATE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('quality_update'))::text[]+ )+);++CREATE POLICY "DELETE" ON "public"."nonConformanceSlackThread"+FOR DELETE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('quality_delete'))::text[]+ )+);++-- Add Slack configuration to integration metadata+-- Update the Slack integration jsonschema to include non-conformance settings+UPDATE "integration"+SET "jsonschema" = jsonb_build_object(+ 'type', 'object',+ 'properties', jsonb_build_object(+ 'access_token', jsonb_build_object('type', 'string'),+ 'team_id', jsonb_build_object('type', 'string'),+ 'team_name', jsonb_build_object('type', 'string'),+ 'channel', jsonb_build_object('type', 'string'),+ 'channel_id', jsonb_build_object('type', 'string'),+ 'slack_configuration_url', jsonb_build_object('type', 'string'),+ 'url', jsonb_build_object('type', 'string'),+ 'bot_user_id', jsonb_build_object('type', 'string'),+ 'nonconformance_channel_id', jsonb_build_object(+ 'type', 'string',+ 'description', 'Default Slack channel for non-conformance notifications'+ ),+ 'nonconformance_notifications_enabled', jsonb_build_object(+ 'type', 'boolean',+ 'default', true,+ 'description', 'Enable automatic Slack notifications for non-conformances'+ )+ )+)+WHERE "id" = 'slack';\ No newline at end of filediff --git a/packages/database/supabase/migrations/20250810204801_slack-document-threads-refactor.sql b/packages/database/supabase/migrations/20250810204801_slack-document-threads-refactor.sqlnew file mode 100644index 0000000000..bf6f416c00--- /dev/null+++ b/packages/database/supabase/migrations/20250810204801_slack-document-threads-refactor.sql@@ -0,0 +1,76 @@+-- Drop the specific non-conformance Slack thread table+DROP TABLE IF EXISTS "nonConformanceSlackThread";++-- Create generic document thread mapping table+CREATE TABLE "slackDocumentThread" (+ "id" TEXT NOT NULL DEFAULT id('dst'),+ "companyId" TEXT NOT NULL,+ "documentType" TEXT NOT NULL, -- e.g., 'nonConformance', 'quote', 'salesOrder', 'job'+ "documentId" TEXT NOT NULL, -- The ID of the document in its respective table+ "channelId" TEXT NOT NULL,+ "threadTs" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,+ "createdBy" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,++ CONSTRAINT "slackDocumentThread_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "slackDocumentThread_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "slackDocumentThread_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "slackDocumentThread_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "slackDocumentThread_unique" UNIQUE ("documentType", "documentId", "companyId")+);++-- Create indexes for efficient lookups+CREATE INDEX "slackDocumentThread_companyId_idx" ON "slackDocumentThread" ("companyId");+CREATE INDEX "slackDocumentThread_documentType_documentId_idx" ON "slackDocumentThread" ("documentType", "documentId");+CREATE INDEX "slackDocumentThread_channelId_threadTs_idx" ON "slackDocumentThread" ("channelId", "threadTs");++-- Enable Row Level Security+ALTER TABLE "slackDocumentThread" ENABLE ROW LEVEL SECURITY;++-- RLS Policies using modern pattern+CREATE POLICY "SELECT" ON "public"."slackDocumentThread"+FOR SELECT USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('integration_view'))::text[]+ )+);++CREATE POLICY "INSERT" ON "public"."slackDocumentThread"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('integration_create'))::text[]+ )+);++CREATE POLICY "UPDATE" ON "public"."slackDocumentThread"+FOR UPDATE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('integration_update'))::text[]+ )+);++CREATE POLICY "DELETE" ON "public"."slackDocumentThread"+FOR DELETE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('integration_delete'))::text[]+ )+);++-- Create an enum for document types to ensure consistency+CREATE TYPE document_thread_type AS ENUM (+ 'nonConformance',+ 'quote',+ 'salesOrder',+ 'job',+ 'purchaseOrder',+ 'invoice',+ 'receipt',+ 'shipment'+);++-- Add check constraint to ensure documentType uses valid values+ALTER TABLE "slackDocumentThread"+ADD CONSTRAINT "slackDocumentThread_documentType_check"+CHECK ("documentType"::document_thread_type IS NOT NULL);\ No newline at end of filediff --git a/packages/integrations/package.json b/packages/integrations/package.jsonindex 1dc77526b7..d6c644aca6 100644--- a/packages/integrations/package.json+++ b/packages/integrations/package.json@@ -5,8 +5,9 @@"exports": {".": "./src/index.ts","./exchange-rates/exchange-rates.server": "./src/exchange-rates/exchange-rates.server.ts",- "./slack.server": "./src/slack/lib/index.ts",- "./onshape": "./src/onshape/lib/index.ts"+ "./onshape": "./src/onshape/lib/index.ts",+ "./slack.server": "./src/slack.server.ts",+ "./slack.service": "./src/slack/lib/service.ts"},"jest": {"preset": "@carbon/jest/node"diff --git a/packages/integrations/src/exchange-rates/config.tsx b/packages/integrations/src/exchange-rates/config.tsxindex 2689e40064..478fa2e396 100644--- a/packages/integrations/src/exchange-rates/config.tsx+++ b/packages/integrations/src/exchange-rates/config.tsx@@ -15,8 +15,6 @@ export const ExchangeRates: IntegrationConfig = {"Automatically update the currency exchange rates for your company.",images: [],settings: [],- onInitialize: () => {},- onUninstall: () => {},schema: z.object({}),};diff --git a/packages/integrations/src/onshape/config.tsx b/packages/integrations/src/onshape/config.tsxindex eded583c3a..bc03f81e8f 100644--- a/packages/integrations/src/onshape/config.tsx+++ b/packages/integrations/src/onshape/config.tsx@@ -57,8 +57,6 @@ export const Onshape: IntegrationConfig = {secretKey: z.string().min(1, { message: "Secret Key is required" }),companyId: z.string().min(1, { message: "Company ID is required" }),}),- onInitialize: () => {},- onUninstall: () => {},};function SetupInstructions({ companyId }: { companyId: string }) {diff --git a/packages/integrations/src/paperless-parts/config.tsx b/packages/integrations/src/paperless-parts/config.tsxindex df4f4fa0d2..5212076046 100644--- a/packages/integrations/src/paperless-parts/config.tsx+++ b/packages/integrations/src/paperless-parts/config.tsx@@ -38,8 +38,6 @@ export const PaperlessParts: IntegrationConfig = {.string().min(1, { message: "Webhook Signing Secret is required" }),}),- onInitialize: () => {},- onUninstall: () => {},};function SetupInstructions({ companyId }: { companyId: string }) {diff --git a/packages/integrations/src/quickbooks/config.tsx b/packages/integrations/src/quickbooks/config.tsxindex 40de35ea6c..30be1ce92e 100644--- a/packages/integrations/src/quickbooks/config.tsx+++ b/packages/integrations/src/quickbooks/config.tsx@@ -13,8 +13,6 @@ export const QuickBooks: IntegrationConfig = {shortDescription:"Automatically post transactions from sales and purchase invoices.",images: [],- onInitialize: () => {},- onUninstall: () => {},settings: [],schema: z.object({}),};diff --git a/packages/integrations/src/resend/config.tsx b/packages/integrations/src/resend/config.tsxindex 3b617e034f..826b47dae4 100644--- a/packages/integrations/src/resend/config.tsx+++ b/packages/integrations/src/resend/config.tsx@@ -34,8 +34,6 @@ export const Resend: IntegrationConfig = {apiKey: z.string().min(1, { message: "API Key is required" }),fromEmail: z.string().email(),}),- onInitialize: () => {},- onUninstall: () => {},};function Logo(props: SVGProps<SVGSVGElement>) {diff --git a/packages/integrations/src/sage/config.tsx b/packages/integrations/src/sage/config.tsxnew file mode 100644index 0000000000..4b1add0056--- /dev/null+++ b/packages/integrations/src/sage/config.tsx@@ -0,0 +1,48 @@+import type { ComponentProps } from "react";+import { z } from "zod";+import type { IntegrationConfig } from "../types";++export const Sage: IntegrationConfig = {+ name: "Sage Intacct",+ id: "sage",+ active: false,+ category: "Accounting",+ logo: Logo,+ description:+ "Integrating Carbon with Sage Intacct enables you to post transactions into your existing accounting software, neatly organizing everything in your accounting software.",+ shortDescription:+ "Automatically post transactions from sales and purchase invoices.",+ images: [],+ settings: [],+ schema: z.object({}),+};++function Logo(props: ComponentProps<"svg">) {+ return (+ <svg+ {...props}+ xmlns="http://www.w3.org/2000/svg"+ width="250"+ height="141"+ viewBox="0 0 250 141"+ fill="none"+ >+ <path+ d="M27.6269 0C43.2682 0 55.9863 10.8171 56.2793 25.8724C56.4258 30.1107 53.3561 32.4512 49.9935 32.4512C46.7773 32.4512 44.0006 30.1139 43.8542 26.1654C43.7077 17.6855 36.5462 11.3997 27.4805 11.3997C19.0006 11.3997 12.5716 17.3926 12.5716 25.5794C12.5716 34.4954 18.5645 38.444 30.9896 42.9753C44.2904 47.7995 56.4258 53.4993 56.4258 70.4557C56.4258 85.2213 44.8763 97.0605 28.7988 97.0605C13.0111 97.0605 0 85.9505 0 70.8952C0 61.5397 4.53125 54.9609 8.91602 54.9609C12.7181 54.9609 15.0553 57.4447 15.0553 60.8073C15.0553 63.7305 12.5716 65.0456 12.5716 70.3092C12.5716 79.6647 20.1725 85.6576 28.7988 85.6576C37.8613 85.6576 43.8542 79.3717 43.8542 71.7708C43.8542 62.4154 37.8613 58.4701 25.4362 54.082C11.5495 49.1178 0 43.1217 0 26.6048C0 11.696 11.9857 0 27.6269 0Z"+ fill="currentColor"+ />+ <path+ d="M91.4225 97.0636C75.6348 97.0636 62.4805 84.3455 62.4805 68.2648C62.4805 51.6014 75.7813 39.1763 91.862 39.1763C109.111 39.1763 121.243 52.0409 121.243 69.5832V90.9243C121.243 94.5799 118.32 97.0636 114.958 97.0636C111.449 97.0636 108.525 94.5799 108.525 90.9243V70.0194C108.525 58.4699 101.947 50.576 91.569 50.576C82.36 50.576 75.0521 58.3234 75.0521 68.2648C75.0521 77.4738 82.2135 85.3677 91.2793 85.3677C94.6419 85.3677 96.1035 84.492 98.151 84.492C100.928 84.492 103.851 86.8293 103.851 90.1919C103.848 94.7231 98.4375 97.0636 91.4225 97.0636Z"+ fill="currentColor"+ />+ <path+ d="M157.262 140.625C140.889 140.625 127.295 128.929 127.295 113.727C127.295 108.61 130.218 106.273 133.581 106.273C136.943 106.273 139.72 108.467 139.867 112.705C140.013 122.207 147.614 129.222 157.116 129.222C167.204 129.222 173.779 122.79 173.779 114.456C173.779 104.954 166.471 101.009 154.046 97.0604C139.574 92.3826 127.295 85.9504 127.295 68.1183C127.295 51.7446 139.867 39.1763 156.237 39.1763C172.754 39.1763 186.351 51.1619 186.351 66.9497C186.351 76.5981 182.406 84.0526 176.995 84.0526C173.34 84.0526 170.856 81.4224 170.856 78.2062C170.856 74.8436 173.779 73.382 173.779 67.3892C173.779 57.3013 165.885 50.5793 156.383 50.5793C147.174 50.5793 139.867 57.5975 139.867 66.8065C139.867 77.1841 147.321 81.5721 159.6 85.6639C173.779 90.3416 186.351 96.188 186.351 113.291C186.351 128.639 174.219 140.625 157.262 140.625Z"+ fill="currentColor"+ />+ <path+ d="M222.227 97.0638C205.853 97.0638 192.406 84.1992 192.406 68.1218C192.406 52.041 205.417 39.1797 221.494 39.1797C237.722 39.1797 250 50.4362 250 64.7624C250 70.3158 246.055 73.6784 239.623 73.6784H222.813C219.45 73.6784 216.966 71.3411 216.966 68.2682C216.966 65.345 219.45 63.0046 222.813 63.0046H235.384C236.553 63.0046 237.432 62.4186 237.432 61.25C237.432 57.0117 232.022 50.4329 221.937 50.4329C212.582 50.4329 204.981 58.4733 204.981 68.1218C204.981 77.9167 212.728 85.6641 222.376 85.6641C233.487 85.6641 237.142 79.0853 241.673 79.0853C245.475 79.0853 247.52 81.569 247.52 84.349C247.52 86.9792 245.765 89.3197 241.38 92.0964C236.989 94.8698 230.414 97.0638 222.227 97.0638Z"+ fill="currentColor"+ />+ </svg>+ );+}diff --git a/packages/integrations/src/slack.server.ts b/packages/integrations/src/slack.server.tsnew file mode 100644index 0000000000..a0ede84dfc--- /dev/null+++ b/packages/integrations/src/slack.server.ts@@ -0,0 +1,7 @@+// Server-side exports for Slack integration+export * from "./slack/lib/client";+export * from "./slack/lib/service";+export * from "./slack/lib/messages";++// Re-export specific types to avoid conflicts+export type { DocumentType } from "./slack/lib/service";\ No newline at end of filediff --git a/packages/integrations/src/slack/lib/client.ts b/packages/integrations/src/slack/lib/client.tsindex 0c5d633c50..c03bdbea7b 100644--- a/packages/integrations/src/slack/lib/client.ts+++ b/packages/integrations/src/slack/lib/client.ts@@ -1,6 +1,7 @@-import * as Bolt from "@slack/bolt";+import Bolt from "@slack/bolt";import { InstallProvider } from "@slack/oauth";import { WebClient } from "@slack/web-api";+import { createHmac } from "node:crypto";import { z } from "zod";import {@@ -11,13 +12,19 @@ import {SLACK_STATE_SECRET,} from "@carbon/auth";-export const slackAuthResponseSchema = z.object({+const { App } = Bolt;++export const slackOAuthCallbackSchema = z.object({+ code: z.string(),+ state: z.string(),+});++export const slackOAuthTokenResponseSchema = 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(),@@ -26,15 +33,28 @@ export const slackAuthResponseSchema = 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(),+ // incoming_webhook is only present when the app has incoming-webhook scope+ incoming_webhook: z+ .object({+ channel: z.string(),+ channel_id: z.string(),+ configuration_url: z.string().url(),+ url: z.string().url(),+ })+ .optional(),+ // Enterprise field can be an object, null, or missing+ enterprise: z+ .object({+ name: z.string(),+ id: z.string(),+ })+ .nullable()+ .optional(),});+// Legacy export for backward compatibility - should be removed eventually+export const slackAuthResponseSchema = slackOAuthTokenResponseSchema;+let slackInstaller: InstallProvider | null = null;export const createSlackApp = ({@@ -44,7 +64,7 @@ export const createSlackApp = ({token: string;botId: string;}) => {- return new Bolt.App({+ return new App({signingSecret: SLACK_SIGNING_SECRET,token,botId,@@ -96,3 +116,140 @@ export const getSlackInstallUrl = ({metadata: JSON.stringify({ companyId, userId }),});};++export async function verifySlackWebhook(req: Request) {+ if (!SLACK_SIGNING_SECRET) {+ throw new Error("SLACK_SIGNING_SECRET is not set");+ }++ const fiveMinutesInSeconds = 5 * 60;+ const slackSignatureVersion = "v0";++ const body = await req.text();+ const timestamp = req.headers.get("x-slack-request-timestamp");+ const slackSignature = req.headers.get("x-slack-signature");++ if (!timestamp || !slackSignature) {+ throw new Error("Missing required Slack headers");+ }++ const currentTime = Math.floor(Date.now() / 1000);+ if (+ Math.abs(currentTime - Number.parseInt(timestamp)) > fiveMinutesInSeconds+ ) {+ throw new Error("Request is too old");+ }++ const sigBasestring = `${slackSignatureVersion}:${timestamp}:${body}`;+ const mySignature = createHmac("sha256", SLACK_SIGNING_SECRET)+ .update(sigBasestring)+ .digest("hex");++ if (`${slackSignatureVersion}=${mySignature}` !== slackSignature) {+ throw new Error("Invalid Slack signature");+ }++ return JSON.parse(body);+}++/**+ * Post a message to a Slack thread+ */+export async function postToSlackThread({+ token,+ channelId,+ threadTs,+ blocks,+ text,+}: {+ token: string;+ channelId: string;+ threadTs: string;+ blocks?: any[];+ text?: string;+}) {+ const client = createSlackWebClient({ token });++ return client.chat.postMessage({+ channel: channelId,+ thread_ts: threadTs,+ blocks,+ text: text || "Message from Carbon",+ unfurl_links: false,+ unfurl_media: false,+ });+}++/**+ * Create a new Slack thread+ */+export async function createSlackThread({+ token,+ channelId,+ blocks,+ text,+}: {+ token: string;+ channelId: string;+ blocks?: any[];+ text?: string;+}) {+ const client = createSlackWebClient({ token });++ return client.chat.postMessage({+ channel: channelId,+ blocks,+ text: text || "New thread from Carbon",+ unfurl_links: false,+ unfurl_media: false,+ });+}++/**+ * Update a Slack message+ */+export async function updateSlackMessage({+ token,+ channelId,+ ts,+ blocks,+ text,+}: {+ token: string;+ channelId: string;+ ts: string;+ blocks?: any[];+ text?: string;+}) {+ const client = createSlackWebClient({ token });++ return client.chat.update({+ channel: channelId,+ ts,+ blocks,+ text: text || "Updated message from Carbon",+ });+}++/**+ * Get thread replies from Slack+ */+export async function getSlackThreadReplies({+ token,+ channelId,+ threadTs,+ limit = 100,+}: {+ token: string;+ channelId: string;+ threadTs: string;+ limit?: number;+}) {+ const client = createSlackWebClient({ token });++ return client.conversations.replies({+ channel: channelId,+ ts: threadTs,+ limit,+ });+}diff --git a/packages/integrations/src/slack/lib/index.ts b/packages/integrations/src/slack/lib/index.tsindex 5ec76921e1..e43c84d7e9 100644--- a/packages/integrations/src/slack/lib/index.ts+++ b/packages/integrations/src/slack/lib/index.ts@@ -1 +1,2 @@export * from "./client";+export * from "./messages";diff --git a/packages/integrations/src/slack/lib/messages.ts b/packages/integrations/src/slack/lib/messages.tsnew file mode 100644index 0000000000..986a6ecc9c--- /dev/null+++ b/packages/integrations/src/slack/lib/messages.ts@@ -0,0 +1,588 @@+import type { KnownBlock } from "@slack/types";++export type DocumentType =+ | "nonConformance"+ | "quote"+ | "salesOrder"+ | "job"+ | "purchaseOrder"+ | "invoice"+ | "receipt"+ | "shipment";++export interface BaseDocumentData {+ id: string;+ documentType: DocumentType;+ title: string;+ description?: string;+ status: string;+ createdBy?: string;+ createdAt?: string;+ updatedAt?: string;+ assignedTo?: string;+ metadata?: Record<string, any>;+}++export interface NonConformanceData extends BaseDocumentData {+ documentType: "nonConformance";+ nonConformanceId: string;+ severity?: string;+ typeId?: string;+ typeName?: string;+ workflowName?: string;+ investigationTypes?: string[];+ requiredActions?: string[];+}++export interface QuoteData extends BaseDocumentData {+ documentType: "quote";+ quoteId: string;+ customerName?: string;+ expirationDate?: string;+}++export interface SalesOrderData extends BaseDocumentData {+ documentType: "salesOrder";+ salesOrderId: string;+ customerName?: string;+ deliveryDate?: string;+}++export interface JobData extends BaseDocumentData {+ documentType: "job";+ jobId: string;+ partNumber?: string;+ quantity?: number;+ dueDate?: string;+}++export type DocumentData =+ | NonConformanceData+ | QuoteData+ | SalesOrderData+ | JobData;++export interface TaskUpdate {+ taskType: "investigation" | "action" | "approval";+ taskName: string;+ status: string;+ assignedTo?: string;+ completedBy?: string;+ completedAt?: string;+ notes?: string;+}++export interface StatusUpdate {+ previousStatus: string;+ newStatus: string;+ updatedBy: string;+ reason?: string;+}++export interface AssignmentUpdate {+ previousAssignee?: string;+ newAssignee: string;+ updatedBy: string;+}++/**+ * Get document type display info+ */+function getDocumentTypeInfo(documentType: DocumentType): {+ emoji: string;+ name: string;+ urlPath: string;+} {+ const typeMap = {+ nonConformance: {+ emoji: "⚠️",+ name: "Issue",+ urlPath: "/x/issue",+ },+ quote: {+ emoji: "💰",+ name: "Quote",+ urlPath: "/x/quote",+ },+ salesOrder: {+ emoji: "📦",+ name: "Sales Order",+ urlPath: "/x/sales-order",+ },+ job: { emoji: "🔧", name: "Job", urlPath: "/x/job" },+ purchaseOrder: {+ emoji: "📋",+ name: "Purchase Order",+ urlPath: "/x/purchase-order",+ },+ invoice: {+ emoji: "🧾",+ name: "Invoice",+ urlPath: "/x/invoice",+ },+ receipt: {+ emoji: "📥",+ name: "Receipt",+ urlPath: "/x/receipt",+ },+ shipment: {+ emoji: "🚚",+ name: "Shipment",+ urlPath: "/x/shipment",+ },+ };++ return typeMap[documentType];+}++/**+ * Get document identifier for display+ */+function getDocumentIdentifier(data: DocumentData): string {+ switch (data.documentType) {+ case "nonConformance":+ return (data as NonConformanceData).nonConformanceId;+ case "quote":+ return (data as QuoteData).quoteId;+ case "salesOrder":+ return (data as SalesOrderData).salesOrderId;+ case "job":+ return (data as JobData).jobId;+ default:+ // @ts-expect-error - this is a fallback for unknown document types+ throw new Error(`Unknown document type: ${data.documentType}`);+ }+}++/**+ * Format the initial document creation message+ */+export function formatDocumentCreated(+ data: DocumentData,+ baseUrl: string+): KnownBlock[] {+ const typeInfo = getDocumentTypeInfo(data.documentType);+ const identifier = getDocumentIdentifier(data);++ const blocks: KnownBlock[] = [+ {+ type: "header",+ text: {+ type: "plain_text",+ text: `${typeInfo.emoji} #${identifier}`,+ },+ },+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*${data.title}*\n${+ data.description || "_No description provided_"+ }`,+ },+ fields: [+ {+ type: "mrkdwn",+ text: `*Status:*\n${data.status}`,+ },+ {+ type: "mrkdwn",+ text: `*Type:*\n${typeInfo.name}`,+ },+ ],+ },+ ];++ // Add document-specific fields+ const specificFields = getDocumentSpecificFields(data);+ if (specificFields.length > 0) {+ blocks.push({+ type: "section",+ fields: specificFields,+ });+ }++ // Add document-specific sections+ const specificSections = getDocumentSpecificSections(data);+ blocks.push(...specificSections);++ // Add context+ blocks.push({+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `Created ${data.createdBy ? `by <@${data.createdBy}>` : ""} ${+ data.createdAt+ ? `on <!date^${Math.floor(+ new Date(data.createdAt).getTime() / 1000+ )}^{date_short_pretty} at {time}|${data.createdAt}>`+ : ""+ }`.trim(),+ },+ ],+ });++ // Add action buttons+ blocks.push({+ type: "actions",+ elements: [+ {+ type: "button",+ text: {+ type: "plain_text",+ text: "View in Carbon",+ },+ url: `${baseUrl}${typeInfo.urlPath}/${data.id}`,+ action_id: "view_in_carbon",+ },+ {+ type: "button",+ text: {+ type: "plain_text",+ text: "Update Status",+ },+ value: data.id,+ action_id: `update_${data.documentType}_status`,+ },+ ],+ });++ return blocks;+}++/**+ * Get document-specific fields for the main section+ */+function getDocumentSpecificFields(data: DocumentData): any[] {+ const fields: any[] = [];++ switch (data.documentType) {+ case "nonConformance":+ const ncrData = data as NonConformanceData;+ if (ncrData.severity) {+ fields.push({+ type: "mrkdwn",+ text: `*Severity:*\n${ncrData.severity}`,+ });+ }+ if (ncrData.typeName) {+ fields.push({+ type: "mrkdwn",+ text: `*Issue Type:*\n${ncrData.typeName}`,+ });+ }+ break;++ case "quote":+ const quoteData = data as QuoteData;+ if (quoteData.customerName) {+ fields.push({+ type: "mrkdwn",+ text: `*Customer:*\n${quoteData.customerName}`,+ });+ }+ break;++ case "salesOrder":+ const soData = data as SalesOrderData;+ if (soData.customerName) {+ fields.push({+ type: "mrkdwn",+ text: `*Customer:*\n${soData.customerName}`,+ });+ }+ break;++ case "job":+ const jobData = data as JobData;+ if (jobData.partNumber) {+ fields.push({+ type: "mrkdwn",+ text: `*Part Number:*\n${jobData.partNumber}`,+ });+ }+ if (jobData.quantity) {+ fields.push({+ type: "mrkdwn",+ text: `*Quantity:*\n${jobData.quantity.toLocaleString()}`,+ });+ }+ break;+ }++ return fields;+}++/**+ * Get document-specific sections+ */+function getDocumentSpecificSections(data: DocumentData): KnownBlock[] {+ const sections: KnownBlock[] = [];++ switch (data.documentType) {+ case "nonConformance":+ const ncrData = data as NonConformanceData;+ if (+ ncrData.investigationTypes?.length ||+ ncrData.requiredActions?.length+ ) {+ let text = "";+ if (ncrData.investigationTypes?.length) {+ text += `*Investigations:*\n${ncrData.investigationTypes+ .map((t) => `• ${t}`)+ .join("\n")}\n\n`;+ }+ if (ncrData.requiredActions?.length) {+ text += `*Required Actions:*\n${ncrData.requiredActions+ .map((a) => `• ${a}`)+ .join("\n")}`;+ }++ sections.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: text.trim(),+ },+ });+ }+ break;++ case "quote":+ const quoteData = data as QuoteData;+ if (quoteData.expirationDate) {+ sections.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*Expires:* <!date^${Math.floor(+ new Date(quoteData.expirationDate).getTime() / 1000+ )}^{date_short_pretty}|${quoteData.expirationDate}>`,+ },+ });+ }+ break;++ case "job":+ const jobData = data as JobData;+ if (jobData.dueDate) {+ sections.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*Due Date:* <!date^${Math.floor(+ new Date(jobData.dueDate).getTime() / 1000+ )}^{date_short_pretty}|${jobData.dueDate}>`,+ },+ });+ }+ break;+ }++ return sections;+}++/**+ * Format a status update message+ */+export function formatStatusUpdate(+ documentType: DocumentType,+ documentIdentifier: string,+ update: StatusUpdate+): KnownBlock[] {+ const typeInfo = getDocumentTypeInfo(documentType);++ const blocks: KnownBlock[] = [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `${typeInfo.emoji} *Status Updated*\n\`${update.previousStatus}\` → \`${update.newStatus}\``,+ },+ },+ ];++ if (update.reason) {+ blocks.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*Reason:* ${update.reason}`,+ },+ });+ }++ blocks.push({+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `Updated by <@${update.updatedBy}> • #${documentIdentifier}`,+ },+ ],+ });++ return blocks;+}++/**+ * Format a task update message+ */+export function formatTaskUpdate(+ documentType: DocumentType,+ documentIdentifier: string,+ update: TaskUpdate+): KnownBlock[] {+ const taskTypeLabel = {+ investigation: "Investigation",+ action: "Action",+ approval: "Approval",+ }[update.taskType];++ const statusEmoji =+ {+ Pending: "⏳",+ "In Progress": "🔄",+ Completed: "✅",+ Skipped: "⏭️",+ }[update.status] || "📋";++ const blocks: KnownBlock[] = [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `${statusEmoji} *${taskTypeLabel} Task ${update.status}*\n_${update.taskName}_`,+ },+ },+ ];++ const fields: any[] = [];++ if (update.assignedTo) {+ fields.push({+ type: "mrkdwn",+ text: `*Assigned to:*\n<@${update.assignedTo}>`,+ });+ }++ if (update.completedBy) {+ fields.push({+ type: "mrkdwn",+ text: `*Completed by:*\n<@${update.completedBy}>`,+ });+ }++ if (fields.length > 0) {+ blocks.push({+ type: "section",+ fields,+ });+ }++ if (update.notes) {+ blocks.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*Notes:* ${update.notes}`,+ },+ });+ }++ blocks.push({+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `#${documentIdentifier} ${+ update.completedAt+ ? `• Completed <!date^${Math.floor(+ new Date(update.completedAt).getTime() / 1000+ )}^{date_short_pretty} at {time}|${update.completedAt}>`+ : ""+ }`.trim(),+ },+ ],+ });++ return blocks;+}++/**+ * Format an assignment update message+ */+export function formatAssignmentUpdate(+ documentType: DocumentType,+ documentIdentifier: string,+ update: AssignmentUpdate+): KnownBlock[] {+ const typeInfo = getDocumentTypeInfo(documentType);++ const blocks: KnownBlock[] = [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `${typeInfo.emoji} *Assignment Updated*\n${+ update.previousAssignee+ ? `<@${update.previousAssignee}> → <@${update.newAssignee}>`+ : `Assigned to <@${update.newAssignee}>`+ }`,+ },+ },+ {+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `Updated by <@${update.updatedBy}> • #${documentIdentifier}`,+ },+ ],+ },+ ];++ return blocks;+}++/**+ * Format a simple notification message+ */+export function formatSimpleNotification(+ title: string,+ message: string,+ context?: string+): KnownBlock[] {+ const blocks: KnownBlock[] = [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*${title}*\n${message}`,+ },+ },+ ];++ if (context) {+ blocks.push({+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: context,+ },+ ],+ });+ }++ return blocks;+}++// Backward compatibility exports for NCR-specific functions+export function formatNonConformanceCreated(+ data: NonConformanceData,+ baseUrl: string+): KnownBlock[] {+ return formatDocumentCreated(data, baseUrl);+}diff --git a/packages/integrations/src/slack/lib/service.ts b/packages/integrations/src/slack/lib/service.tsnew file mode 100644index 0000000000..cc601b4dbe--- /dev/null+++ b/packages/integrations/src/slack/lib/service.ts@@ -0,0 +1,540 @@+import { getCarbonServiceRole } from "@carbon/auth";+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";+import { tasks } from "@trigger.dev/sdk/v3";++export type DocumentType =+ | "nonConformance"+ | "quote"+ | "salesOrder"+ | "job"+ | "purchaseOrder"+ | "invoice"+ | "receipt"+ | "shipment";++export interface SlackDocumentThread {+ id: string;+ companyId: string;+ documentType: DocumentType;+ documentId: string;+ channelId: string;+ threadTs: string;+ createdAt: string;+ createdBy: string;+ updatedAt?: string;+ updatedBy?: string;+}++/**+ * Get Slack thread for any document type+ */+export async function getSlackDocumentThread(+ client: SupabaseClient<Database>,+ documentType: DocumentType,+ documentId: string,+ companyId: string+) {+ return client+ .from("slackDocumentThread")+ .select("*")+ .eq("documentType", documentType)+ .eq("documentId", documentId)+ .eq("companyId", companyId)+ .single();+}++/**+ * Create Slack thread mapping for any document type+ */+export async function createSlackDocumentThread(+ client: SupabaseClient<Database>,+ data: {+ documentType: DocumentType;+ documentId: string;+ companyId: string;+ channelId: string;+ threadTs: string;+ createdBy: string;+ }+) {+ return client.from("slackDocumentThread").insert(data).select("*").single();+}++/**+ * Update Slack thread mapping+ */+export async function updateSlackDocumentThread(+ client: SupabaseClient<Database>,+ id: string,+ updates: {+ channelId?: string;+ threadTs?: string;+ updatedBy: string;+ }+) {+ return client+ .from("slackDocumentThread")+ .update({+ ...updates,+ updatedAt: new Date().toISOString(),+ })+ .eq("id", id)+ .select("*")+ .single();+}++/**+ * Delete Slack thread mapping+ */+export async function deleteSlackDocumentThread(+ client: SupabaseClient<Database>,+ documentType: DocumentType,+ documentId: string,+ companyId: string+) {+ return client+ .from("slackDocumentThread")+ .delete()+ .eq("documentType", documentType)+ .eq("documentId", documentId)+ .eq("companyId", companyId);+}++/**+ * Get all Slack threads for a company (optionally filtered by document type)+ */+export async function getCompanySlackThreads(+ client: SupabaseClient<Database>,+ companyId: string,+ documentType?: DocumentType+) {+ let query = client+ .from("slackDocumentThread")+ .select("*")+ .eq("companyId", companyId);++ if (documentType) {+ query = query.eq("documentType", documentType);+ }++ return query.order("createdAt", { ascending: false });+}++/**+ * Generic function to sync document updates to Slack+ */+export async function syncDocumentToSlack(+ client: SupabaseClient<Database>,+ data: {+ documentType: DocumentType;+ documentId: string;+ companyId: string;+ updateType:+ | "created"+ | "status-update"+ | "task-update"+ | "assignment-update"+ | "custom";+ payload: Record<string, any>;+ }+) {+ // Check if Slack thread exists+ const thread = await getSlackDocumentThread(+ client,+ data.documentType,+ data.documentId,+ data.companyId+ );++ if (thread.data) {+ // Invoke the edge function to trigger Slack sync+ return getCarbonServiceRole().functions.invoke("slack-document-sync", {+ body: {+ documentType: data.documentType,+ documentId: data.documentId,+ companyId: data.companyId,+ updateType: data.updateType,+ channelId: thread.data.channelId,+ threadTs: thread.data.threadTs,+ payload: data.payload,+ },+ });+ }++ return { data: null, error: null };+}++/**+ * Sync document creation to Slack (creates initial thread message)+ */+export async function syncDocumentCreatedToSlack(+ client: SupabaseClient<Database>,+ data: {+ documentType: DocumentType;+ documentId: string;+ companyId: string;+ channelId: string;+ threadTs: string;+ metadata?: Record<string, any>;+ }+) {+ return syncDocumentToSlack(client, {+ documentType: data.documentType,+ documentId: data.documentId,+ companyId: data.companyId,+ updateType: "created",+ payload: {+ channelId: data.channelId,+ threadTs: data.threadTs,+ metadata: data.metadata,+ },+ });+}++/**+ * Sync document status update to Slack+ */+export async function syncDocumentStatusToSlack(+ client: SupabaseClient<Database>,+ data: {+ documentType: DocumentType;+ documentId: string;+ companyId: string;+ previousStatus: string;+ newStatus: string;+ updatedBy: string;+ reason?: string;+ metadata?: Record<string, any>;+ }+) {+ return syncDocumentToSlack(client, {+ documentType: data.documentType,+ documentId: data.documentId,+ companyId: data.companyId,+ updateType: "status-update",+ payload: {+ previousStatus: data.previousStatus,+ newStatus: data.newStatus,+ updatedBy: data.updatedBy,+ reason: data.reason,+ metadata: data.metadata,+ },+ });+}++/**+ * Sync document assignment update to Slack+ */+export async function syncDocumentAssignmentToSlack(+ client: SupabaseClient<Database>,+ data: {+ documentType: DocumentType;+ documentId: string;+ companyId: string;+ previousAssignee?: string;+ newAssignee: string;+ updatedBy: string;+ metadata?: Record<string, any>;+ }+) {+ return syncDocumentToSlack(client, {+ documentType: data.documentType,+ documentId: data.documentId,+ companyId: data.companyId,+ updateType: "assignment-update",+ payload: {+ previousAssignee: data.previousAssignee,+ newAssignee: data.newAssignee,+ updatedBy: data.updatedBy,+ metadata: data.metadata,+ },+ });+}++/**+ * Sync custom document update to Slack+ */+export async function syncDocumentCustomToSlack(+ client: SupabaseClient<Database>,+ data: {+ documentType: DocumentType;+ documentId: string;+ companyId: string;+ customType: string;+ payload: Record<string, any>;+ }+) {+ return syncDocumentToSlack(client, {+ documentType: data.documentType,+ documentId: data.documentId,+ companyId: data.companyId,+ updateType: "custom",+ payload: {+ customType: data.customType,+ ...data.payload,+ },+ });+}++// Non-conformance specific wrapper functions for backward compatibility++/**+ * Get Slack thread for a non-conformance+ */+export async function getIssueSlackThread(+ client: SupabaseClient<Database>,+ nonConformanceId: string,+ companyId: string+) {+ return getSlackDocumentThread(+ client,+ "nonConformance",+ nonConformanceId,+ companyId+ );+}++/**+ * Create Slack thread mapping for a non-conformance+ */+export async function createIssueSlackThread(+ client: SupabaseClient<Database>,+ data: {+ nonConformanceId: string;+ companyId: string;+ channelId: string;+ threadTs: string;+ createdBy: string;+ }+) {+ return createSlackDocumentThread(client, {+ documentType: "nonConformance",+ documentId: data.nonConformanceId,+ companyId: data.companyId,+ channelId: data.channelId,+ threadTs: data.threadTs,+ createdBy: data.createdBy,+ });+}++/**+ * Sync non-conformance status update to Slack+ */+export async function syncIssueStatusToSlack(+ client: SupabaseClient<Database>,+ data: {+ nonConformanceId: string;+ companyId: string;+ previousStatus: string;+ newStatus: string;+ updatedBy: string;+ reason?: string;+ }+) {+ return syncDocumentStatusToSlack(client, {+ documentType: "nonConformance",+ documentId: data.nonConformanceId,+ companyId: data.companyId,+ previousStatus: data.previousStatus,+ newStatus: data.newStatus,+ updatedBy: data.updatedBy,+ reason: data.reason,+ });+}++/**+ * Sync task update to Slack+ */+export async function syncIssueTaskToSlack(+ client: SupabaseClient<Database>,+ data: {+ nonConformanceId: string;+ companyId: string;+ taskType: "investigation" | "action" | "approval";+ taskName: string;+ status: string;+ assignedTo?: string;+ completedBy?: string;+ completedAt?: string;+ notes?: string;+ }+) {+ return syncDocumentCustomToSlack(client, {+ documentType: "nonConformance",+ documentId: data.nonConformanceId,+ companyId: data.companyId,+ customType: "task-update",+ payload: {+ taskType: data.taskType,+ taskName: data.taskName,+ status: data.status,+ assignedTo: data.assignedTo,+ completedBy: data.completedBy,+ completedAt: data.completedAt,+ notes: data.notes,+ },+ });+}++/**+ * Sync assignment update to Slack+ */+export async function syncIssueAssignmentToSlack(+ client: SupabaseClient<Database>,+ data: {+ nonConformanceId: string;+ companyId: string;+ previousAssignee?: string;+ newAssignee: string;+ updatedBy: string;+ }+) {+ return syncDocumentAssignmentToSlack(client, {+ documentType: "nonConformance",+ documentId: data.nonConformanceId,+ companyId: data.companyId,+ previousAssignee: data.previousAssignee,+ newAssignee: data.newAssignee,+ updatedBy: data.updatedBy,+ });+}++/**+ * Create Slack thread for any document type - posts initial message and stores thread mapping+ */+export async function createDocumentSlackThread(+ client: SupabaseClient<Database>,+ data: {+ documentType: DocumentType;+ documentId: string;+ companyId: string;+ createdBy: string;+ }+) {+ try {+ // Get the Slack integration for this company+ const { data: integration } = await client+ .from("companyIntegration")+ .select("metadata")+ .eq("id", "slack")+ .eq("companyId", data.companyId)+ .single();++ if (!integration?.metadata) {+ // No Slack integration found, skip silently+ return { data: null, error: null };+ }++ const slackMetadata = integration.metadata as any;+ const slackToken = slackMetadata.access_token as string;+ const channelId = slackMetadata.incoming_webhook?.channel_id as string;++ if (!slackToken || !channelId) {+ // Missing required Slack configuration, skip silently+ return { data: null, error: null };+ }++ // Import Slack client functions dynamically+ const { createSlackWebClient } = await import("./client");+ const slackClient = createSlackWebClient({ token: slackToken });++ // Post initial message to channel (simple format for now)+ const threadMessage = await slackClient.chat.postMessage({+ channel: channelId,+ unfurl_links: false,+ unfurl_media: false,+ blocks: [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `📄 New ${data.documentType} created`,+ },+ },+ {+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `Document ID: ${data.documentId} • Company: ${data.companyId}`,+ },+ ],+ },+ ],+ });++ // Store the thread mapping in the database+ if (threadMessage.ts) {+ const { data: threadRecord } = await client+ .from("slackDocumentThread")+ .insert({+ documentType: data.documentType,+ documentId: data.documentId,+ companyId: data.companyId,+ channelId,+ threadTs: threadMessage.ts,+ createdBy: data.createdBy,+ })+ .select("*")+ .single();++ // Trigger background job to sync detailed information+ try {+ const { tasks } = await import("@trigger.dev/sdk/v3");+ await tasks.trigger("slack-document-created", {+ documentType: data.documentType,+ documentId: data.documentId,+ companyId: data.companyId,+ channelId,+ threadTs: threadMessage.ts,+ });+ } catch (error) {+ console.warn("Failed to trigger background job:", error);+ // Don't fail the operation if background job fails+ }++ return { data: threadRecord, error: null };+ }++ return { data: null, error: "Failed to post message to Slack" };+ } catch (error) {+ console.error("Error creating Slack thread:", error);+ // Don't throw error - we don't want to fail document creation if Slack fails+ return {+ data: null,+ error: error instanceof Error ? error.message : "Unknown error",+ };+ }+}++/**+ * Create Slack thread for a non-conformance (issue)+ */+export async function createIssueSlackThreadWithMessage(+ client: SupabaseClient<Database>,+ data: {+ nonConformanceId: string;+ companyId: string;+ createdBy: string;+ }+) {+ const result = await createDocumentSlackThread(client, {+ documentType: "nonConformance",+ documentId: data.nonConformanceId,+ companyId: data.companyId,+ createdBy: data.createdBy,+ });++ if (result.error) {+ return result;+ }++ await tasks.trigger("slack-document-created", {+ documentType: "nonConformance",+ documentId: data.nonConformanceId,+ companyId: data.companyId,+ });++ return result;+}diff --git a/packages/integrations/src/types.ts b/packages/integrations/src/types.tsindex a5186a9a4b..ddc2f2e712 100644--- a/packages/integrations/src/types.ts+++ b/packages/integrations/src/types.ts@@ -18,6 +18,6 @@ export type IntegrationConfig = {value: unknown;}[];schema: ZodType;- onInitialize: () => void | Promise<void>;- onUninstall: () => void | Promise<void>;+ onInitialize?: () => void | Promise<void>;+ onUninstall?: () => void | Promise<void>;};diff --git a/packages/integrations/src/xero/config.tsx b/packages/integrations/src/xero/config.tsxindex f3d326808e..fa57aa64aa 100644--- a/packages/integrations/src/xero/config.tsx+++ b/packages/integrations/src/xero/config.tsx@@ -13,8 +13,6 @@ export const Xero: IntegrationConfig = {shortDescription:"Automatically post transactions from sales and purchase invoices.",images: [],- onInitialize: () => {},- onUninstall: () => {},settings: [],schema: z.object({}),};diff --git a/packages/integrations/src/zapier/config.tsx b/packages/integrations/src/zapier/config.tsxindex f66de1c2f3..6bb9cef181 100644--- a/packages/integrations/src/zapier/config.tsx+++ b/packages/integrations/src/zapier/config.tsx@@ -12,8 +12,6 @@ export const Zapier: IntegrationConfig = {"Integrating with Zapier enables you to automate tasks and workflows in your business by connecting Carbon to other apps.",shortDescription: "Automate tasks and workflows in your business.",images: [],- onInitialize: () => {},- onUninstall: () => {},settings: [],schema: z.object({}),};diff --git a/packages/jobs/trigger/slack-document-sync.ts b/packages/jobs/trigger/slack-document-sync.tsnew file mode 100644index 0000000000..f2a0e5481d--- /dev/null+++ b/packages/jobs/trigger/slack-document-sync.ts@@ -0,0 +1,853 @@+import { getCarbonServiceRole, VERCEL_URL } from "@carbon/auth";+import { WebClient } from "@slack/web-api";+import { task } from "@trigger.dev/sdk/v3";++// Type definitions+type DocumentType =+ | "nonConformance"+ | "quote"+ | "salesOrder"+ | "job"+ | "purchaseOrder"+ | "invoice"+ | "receipt"+ | "shipment";++interface DocumentData {+ documentType: DocumentType;+ id: string;+ title?: string;+ description?: string;+ status?: string;+ createdBy?: string;+ createdAt?: string;+}++interface NonConformanceData extends DocumentData {+ documentType: "nonConformance";+ nonConformanceId: string;+ severity?: string;+ typeId?: string;+ typeName?: string;+ workflowName?: string;+ investigationTypes?: string[];+ requiredActions?: string[];+}++interface StatusUpdate {+ previousStatus: string;+ newStatus: string;+ updatedBy: string;+ reason?: string;+}++interface TaskUpdate {+ taskType: "investigation" | "action" | "approval";+ taskName: string;+ status: string;+ assignedTo?: string;+ completedBy?: string;+ completedAt?: string;+ notes?: string;+}++interface AssignmentUpdate {+ previousAssignee?: string;+ newAssignee: string;+ updatedBy: string;+}++/**+ * Post initial document creation message to Slack+ */+export const slackDocumentCreated = task({+ id: "slack-document-created",+ run: async (payload: {+ documentType: DocumentType;+ documentId: string;+ companyId: string;+ channelId: string;+ threadTs: string;+ }) => {+ const { documentType, documentId, companyId, channelId, threadTs } =+ payload;++ try {+ const serviceRole = await getCarbonServiceRole();++ // Get the document details based on type+ const documentData = await getDocumentData(+ serviceRole,+ documentType,+ documentId,+ companyId+ );++ if (!documentData) {+ throw new Error(`${documentType} ${documentId} not found`);+ }++ // Get the Slack integration+ const { data: integration } = await serviceRole+ .from("companyIntegration")+ .select("metadata")+ .eq("id", "slack")+ .eq("companyId", companyId)+ .single();++ if (!integration?.metadata) {+ throw new Error("Slack integration not found");+ }++ const slackToken = (integration.metadata as any)?.access_token as string;+ const baseUrl = VERCEL_URL || "http://localhost:3000";++ // Post detailed information to the thread+ await postToSlackThread({+ token: slackToken,+ channelId,+ threadTs,+ blocks: formatDocumentCreated(documentData, baseUrl),+ });++ return { success: true };+ } catch (error) {+ console.error(`Error posting ${documentType} to Slack:`, error);+ throw error;+ }+ },+});++/**+ * Post status update to Slack thread+ */+export const slackDocumentStatusUpdate = task({+ id: "slack-document-status-update",+ run: async (payload: {+ documentType: DocumentType;+ documentId: string;+ companyId: string;+ previousStatus: string;+ newStatus: string;+ updatedBy: string;+ reason?: string;+ }) => {+ const {+ documentType,+ documentId,+ companyId,+ previousStatus,+ newStatus,+ updatedBy,+ reason,+ } = payload;++ try {+ const serviceRole = await getCarbonServiceRole();++ // Get the Slack thread for this document+ const { data: thread } = await serviceRole+ .from("slackDocumentThread")+ .select("channelId, threadTs")+ .eq("documentType", documentType)+ .eq("documentId", documentId)+ .eq("companyId", companyId)+ .single();++ if (!thread) {+ return { success: true, message: "No Slack thread found" };+ }++ // Get the Slack integration+ const { data: integration } = await serviceRole+ .from("companyIntegration")+ .select("metadata")+ .eq("id", "slack")+ .eq("companyId", companyId)+ .single();++ if (!integration?.metadata) {+ throw new Error("Slack integration not found");+ }++ const slackToken = (integration.metadata as any).access_token as string;++ // Get the document identifier for display+ const documentIdentifier = await getDocumentIdentifier(+ serviceRole,+ documentType,+ documentId,+ companyId+ );++ const statusUpdate: StatusUpdate = {+ previousStatus,+ newStatus,+ updatedBy,+ reason,+ };++ // Post status update to the thread+ await postToSlackThread({+ token: slackToken,+ channelId: thread.channelId,+ threadTs: thread.threadTs,+ blocks: formatStatusUpdate(+ documentType,+ documentIdentifier,+ statusUpdate+ ),+ });++ return { success: true };+ } catch (error) {+ console.error(+ `Error posting ${documentType} status update to Slack:`,+ error+ );+ throw error;+ }+ },+});++/**+ * Post task update to Slack thread (mainly for non-conformances)+ */+export const slackDocumentTaskUpdate = task({+ id: "slack-document-task-update",+ run: async (payload: {+ documentType: DocumentType;+ documentId: string;+ companyId: string;+ taskType: "investigation" | "action" | "approval";+ taskName: string;+ status: string;+ assignedTo?: string;+ completedBy?: string;+ completedAt?: string;+ notes?: string;+ }) => {+ const {+ documentType,+ documentId,+ companyId,+ taskType,+ taskName,+ status,+ assignedTo,+ completedBy,+ completedAt,+ notes,+ } = payload;++ try {+ const serviceRole = await getCarbonServiceRole();++ // Get the Slack thread for this document+ const { data: thread } = await serviceRole+ .from("slackDocumentThread")+ .select("channelId, threadTs")+ .eq("documentType", documentType)+ .eq("documentId", documentId)+ .eq("companyId", companyId)+ .single();++ if (!thread) {+ return { success: true, message: "No Slack thread found" };+ }++ // Get the Slack integration+ const { data: integration } = await serviceRole+ .from("companyIntegration")+ .select("metadata")+ .eq("id", "slack")+ .eq("companyId", companyId)+ .single();++ if (!integration?.metadata) {+ throw new Error("Slack integration not found");+ }++ const slackToken = (integration.metadata as any).access_token as string;++ // Get the document identifier for display+ const documentIdentifier = await getDocumentIdentifier(+ serviceRole,+ documentType,+ documentId,+ companyId+ );++ const taskUpdate: TaskUpdate = {+ taskType,+ taskName,+ status,+ assignedTo,+ completedBy,+ completedAt,+ notes,+ };++ // Post task update to the thread+ await postToSlackThread({+ token: slackToken,+ channelId: thread.channelId,+ threadTs: thread.threadTs,+ blocks: formatTaskUpdate(documentType, documentIdentifier, taskUpdate),+ });++ return { success: true };+ } catch (error) {+ console.error(+ `Error posting ${documentType} task update to Slack:`,+ error+ );+ throw error;+ }+ },+});++/**+ * Post assignment update to Slack thread+ */+export const slackDocumentAssignmentUpdate = task({+ id: "slack-document-assignment-update",+ run: async (payload: {+ documentType: DocumentType;+ documentId: string;+ companyId: string;+ previousAssignee?: string;+ newAssignee: string;+ updatedBy: string;+ }) => {+ const {+ documentType,+ documentId,+ companyId,+ previousAssignee,+ newAssignee,+ updatedBy,+ } = payload;++ try {+ const serviceRole = await getCarbonServiceRole();++ // Get the Slack thread for this document+ const { data: thread } = await serviceRole+ .from("slackDocumentThread")+ .select("channelId, threadTs")+ .eq("documentType", documentType)+ .eq("documentId", documentId)+ .eq("companyId", companyId)+ .single();++ if (!thread) {+ return { success: true, message: "No Slack thread found" };+ }++ // Get the Slack integration+ const { data: integration } = await serviceRole+ .from("companyIntegration")+ .select("metadata")+ .eq("id", "slack")+ .eq("companyId", companyId)+ .single();++ if (!integration?.metadata) {+ throw new Error("Slack integration not found");+ }++ const slackToken = (integration.metadata as any).access_token as string;++ // Get the document identifier for display+ const documentIdentifier = await getDocumentIdentifier(+ serviceRole,+ documentType,+ documentId,+ companyId+ );++ const assignmentUpdate: AssignmentUpdate = {+ previousAssignee,+ newAssignee,+ updatedBy,+ };++ // Post assignment update to the thread+ await postToSlackThread({+ token: slackToken,+ channelId: thread.channelId,+ threadTs: thread.threadTs,+ blocks: formatAssignmentUpdate(+ documentType,+ documentIdentifier,+ assignmentUpdate+ ),+ });++ return { success: true };+ } catch (error) {+ console.error(+ `Error posting ${documentType} assignment update to Slack:`,+ error+ );+ throw error;+ }+ },+});++/**+ * Helper function to get document data based on type+ */+async function getDocumentData(+ serviceRole: any,+ documentType: DocumentType,+ documentId: string,+ companyId: string+): Promise<DocumentData | null> {+ switch (documentType) {+ case "nonConformance": {+ const { data } = await serviceRole+ .from("nonConformance")+ .select(+ `+ *,+ type:typeId(name),+ workflow:workflowId(name)+ `+ )+ .eq("id", documentId)+ .eq("companyId", companyId)+ .single();++ if (!data) return null;++ // Get investigation and action tasks+ const [investigations, actions] = await Promise.all([+ serviceRole+ .from("nonConformanceInvestigationTask")+ .select("investigationType")+ .eq("nonConformanceId", documentId)+ .eq("companyId", companyId),+ serviceRole+ .from("nonConformanceActionTask")+ .select("actionType")+ .eq("nonConformanceId", documentId)+ .eq("companyId", companyId),+ ]);++ return {+ documentType: "nonConformance",+ id: data.id,+ nonConformanceId: data.nonConformanceId,+ title: data.title,+ description: data.description,+ status: data.status,+ severity: data.severity,+ typeId: data.typeId,+ typeName: data.type?.name,+ workflowName: data.workflow?.name,+ createdBy: data.createdBy,+ createdAt: data.createdAt,+ investigationTypes:+ investigations.data?.map((i) => i.investigationType) || [],+ requiredActions: actions.data?.map((a) => a.actionType) || [],+ } as NonConformanceData;+ }++ // Add other document types here in the future+ case "quote":+ case "salesOrder":+ case "job":+ default:+ console.warn(`Document type ${documentType} not yet implemented`);+ return null;+ }+}++/**+ * Helper function to get document identifier for display+ */+async function getDocumentIdentifier(+ serviceRole: any,+ documentType: DocumentType,+ documentId: string,+ companyId: string+): Promise<string> {+ switch (documentType) {+ case "nonConformance": {+ const { data } = await serviceRole+ .from("nonConformance")+ .select("nonConformanceId")+ .eq("id", documentId)+ .single();+ return data?.nonConformanceId || documentId;+ }++ // Add other document types here+ default:+ return documentId;+ }+}++/**+ * Helper function to post messages to a Slack thread+ */+async function postToSlackThread(params: {+ token: string;+ channelId: string;+ threadTs: string;+ blocks: any[];+ text?: string;+}) {+ const { token, channelId, threadTs, blocks, text } = params;++ const client = new WebClient(token);++ return await client.chat.postMessage({+ channel: channelId,+ thread_ts: threadTs,+ blocks,+ text: text || "Update from Carbon",+ });+}++/**+ * Format document creation message for Slack+ */+function formatDocumentCreated(+ data: DocumentData,+ baseUrl: string+): any[] {+ const blocks: any[] = [];++ if (data.documentType === "nonConformance") {+ const ncData = data as NonConformanceData;++ blocks.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*Non-Conformance Created: ${ncData.nonConformanceId}*\n${ncData.title || "No title"}`,+ },+ });++ if (ncData.description) {+ blocks.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*Description:*\n${ncData.description}`,+ },+ });+ }++ const fields: any[] = [];++ if (ncData.status) {+ fields.push({+ type: "mrkdwn",+ text: `*Status:*\n${ncData.status}`,+ });+ }++ if (ncData.severity) {+ fields.push({+ type: "mrkdwn",+ text: `*Severity:*\n${ncData.severity}`,+ });+ }++ if (ncData.typeName) {+ fields.push({+ type: "mrkdwn",+ text: `*Type:*\n${ncData.typeName}`,+ });+ }++ if (ncData.workflowName) {+ fields.push({+ type: "mrkdwn",+ text: `*Workflow:*\n${ncData.workflowName}`,+ });+ }++ if (fields.length > 0) {+ blocks.push({+ type: "section",+ fields,+ });+ }++ if (ncData.investigationTypes && ncData.investigationTypes.length > 0) {+ blocks.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*Investigation Types:*\n${ncData.investigationTypes.join(", ")}`,+ },+ });+ }++ if (ncData.requiredActions && ncData.requiredActions.length > 0) {+ blocks.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*Required Actions:*\n${ncData.requiredActions.join(", ")}`,+ },+ });+ }++ blocks.push({+ type: "actions",+ elements: [+ {+ type: "button",+ text: {+ type: "plain_text",+ text: "View in Carbon",+ },+ url: `${baseUrl}/x/issue/${ncData.id}`,+ action_id: "view_nonconformance",+ },+ ],+ });+ }++ blocks.push({+ type: "divider",+ });++ return blocks;+}++/**+ * Format status update message for Slack+ */+function formatStatusUpdate(+ documentType: DocumentType,+ documentIdentifier: string,+ update: StatusUpdate+): any[] {+ const blocks: any[] = [];++ const emoji = getStatusEmoji(update.newStatus);++ blocks.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `${emoji} *Status Updated*\n${documentIdentifier}`,+ },+ });++ blocks.push({+ type: "section",+ fields: [+ {+ type: "mrkdwn",+ text: `*From:*\n${update.previousStatus}`,+ },+ {+ type: "mrkdwn",+ text: `*To:*\n${update.newStatus}`,+ },+ ],+ });++ if (update.reason) {+ blocks.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*Reason:*\n${update.reason}`,+ },+ });+ }++ blocks.push({+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `Updated by ${update.updatedBy} at <!date^${Math.floor(Date.now() / 1000)}^{date_short_pretty} {time}|${new Date().toISOString()}>`,+ },+ ],+ });++ return blocks;+}++/**+ * Format task update message for Slack+ */+function formatTaskUpdate(+ documentType: DocumentType,+ documentIdentifier: string,+ update: TaskUpdate+): any[] {+ const blocks: any[] = [];++ const emoji = getTaskStatusEmoji(update.status);+ const taskTypeLabel =+ update.taskType === "investigation" ? "Investigation" :+ update.taskType === "action" ? "Action" :+ "Approval";++ blocks.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `${emoji} *${taskTypeLabel} Task Updated*\n${documentIdentifier}`,+ },+ });++ const fields: any[] = [+ {+ type: "mrkdwn",+ text: `*Task:*\n${update.taskName}`,+ },+ {+ type: "mrkdwn",+ text: `*Status:*\n${update.status}`,+ },+ ];++ if (update.assignedTo) {+ fields.push({+ type: "mrkdwn",+ text: `*Assigned To:*\n${update.assignedTo}`,+ });+ }++ if (update.completedBy) {+ fields.push({+ type: "mrkdwn",+ text: `*Completed By:*\n${update.completedBy}`,+ });+ }++ blocks.push({+ type: "section",+ fields,+ });++ if (update.notes) {+ blocks.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*Notes:*\n${update.notes}`,+ },+ });+ }++ if (update.completedAt) {+ blocks.push({+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `Completed at ${update.completedAt}`,+ },+ ],+ });+ }++ return blocks;+}++/**+ * Format assignment update message for Slack+ */+function formatAssignmentUpdate(+ documentType: DocumentType,+ documentIdentifier: string,+ update: AssignmentUpdate+): any[] {+ const blocks: any[] = [];++ blocks.push({+ type: "section",+ text: {+ type: "mrkdwn",+ text: `👤 *Assignment Updated*\n${documentIdentifier}`,+ },+ });++ const fields: any[] = [];++ if (update.previousAssignee) {+ fields.push({+ type: "mrkdwn",+ text: `*Previous Assignee:*\n${update.previousAssignee}`,+ });+ }++ fields.push({+ type: "mrkdwn",+ text: `*New Assignee:*\n${update.newAssignee}`,+ });++ blocks.push({+ type: "section",+ fields,+ });++ blocks.push({+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `Updated by ${update.updatedBy} at <!date^${Math.floor(Date.now() / 1000)}^{date_short_pretty} {time}|${new Date().toISOString()}>`,+ },+ ],+ });++ return blocks;+}++/**+ * Get emoji for status+ */+function getStatusEmoji(status: string): string {+ const statusLower = status.toLowerCase();++ if (statusLower.includes("closed") || statusLower.includes("complete")) {+ return "✅";+ } else if (statusLower.includes("progress") || statusLower.includes("review")) {+ return "🔄";+ } else if (statusLower.includes("pending") || statusLower.includes("open")) {+ return "📋";+ } else if (statusLower.includes("rejected") || statusLower.includes("cancelled")) {+ return "❌";+ }++ return "📌";+}++/**+ * Get emoji for task status+ */+function getTaskStatusEmoji(status: string): string {+ const statusLower = status.toLowerCase();++ if (statusLower.includes("completed")) {+ return "✅";+ } else if (statusLower.includes("progress")) {+ return "⏳";+ } else if (statusLower.includes("skipped")) {+ return "⏭️";+ } else if (statusLower.includes("pending")) {+ return "⏸️";+ }++ return "📝";+}++// Backward compatibility exports+export const slackNcrCreated = slackDocumentCreated;+export const slackNcrStatusUpdate = slackDocumentStatusUpdate;+export const slackNcrTaskUpdate = slackDocumentTaskUpdate;+export const slackNcrAssignmentUpdate = slackDocumentAssignmentUpdate;