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
refactor: fix post message to slack when issue is created
Brad Barbin4cba94cbe354
diff --git a/apps/erp/app/components/Form/WorkCenter.tsx b/apps/erp/app/components/Form/WorkCenter.tsxindex 32272ef12f..d3f7c3b5d0 100644--- a/apps/erp/app/components/Form/WorkCenter.tsx+++ b/apps/erp/app/components/Form/WorkCenter.tsx@@ -85,8 +85,6 @@ export const useWorkCenters = (args: {workCenterFetcher.load(path.to.api.workCenters);});- console.log({ args, data: workCenterFetcher.data });-const options = useMemo(() =>workCenterFetcher.data?.datadiff --git a/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx b/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsxindex 10e7ba8f01..31dd7a01d1 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx@@ -414,7 +414,9 @@ const JobDocuments = ({): "--"}</Td>- <Td>Job</Td>+ <Td>+ <Enumerable value="Job" />+ </Td><Td><div className="flex justify-end w-full"><DropdownMenu>diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.tsindex 740d7e44b3..e909df2967 100644--- a/apps/erp/app/modules/quality/quality.service.ts+++ b/apps/erp/app/modules/quality/quality.service.ts@@ -310,7 +310,7 @@ export async function getIssues(if (args) {query = setGenericQueryFilters(query, args, [- { column: "name", ascending: false },+ { column: "nonConformanceId", ascending: false },]);}@@ -993,7 +993,6 @@ export async function upsertIssue(customFields?: Json;})) {- console.log({ nonConformance });if ("createdBy" in nonConformance) {const result = await client.from("nonConformance")diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsxindex bfd2e26f58..bf8c8070cc 100644--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx@@ -477,7 +477,9 @@ const OpportunityLineDocuments = ({): "--"}</Td>- <Td>Opportunity Line</Td>+ <Td>+ <Enumerable value="Opportunity Line" />+ </Td><Td><div className="flex justify-end w-full"><DropdownMenu>diff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.tsindex 7316bb1070..be0ed8c564 100644--- a/apps/erp/app/modules/settings/settings.server.ts+++ b/apps/erp/app/modules/settings/settings.server.ts@@ -24,12 +24,34 @@ export async function clearCompanyIntegrationCache(const cacheKey = `integrations:${companyId}`;try {- await redis.del(cacheKey);+ // Clear both old and new key formats+ await redis.del(cacheKey, `json:${cacheKey}`);} catch (error) {console.error("Redis cache invalidation error:", error);}}+export async function clearAllIntegrationCaches(): Promise<void> {+ try {+ // Clear both old and new key patterns+ const oldPattern = "integrations:*";+ const newPattern = "json:integrations:*";++ const [oldKeys, newKeys] = await Promise.all([+ redis.keys(oldPattern),+ redis.keys(newPattern),+ ]);++ const allKeys = [...oldKeys, ...newKeys];+ if (allKeys.length > 0) {+ console.log(`Clearing ${allKeys.length} integration cache entries`);+ await redis.del(...allKeys);+ }+ } catch (error) {+ console.error("Error clearing all integration caches:", error);+ }+}+export async function deactivateIntegration(client: SupabaseClient<Database>,args: {@@ -85,12 +107,67 @@ export async function getCompanyIntegrations(const cacheKey = `integrations:${companyId}`;try {- const cached = await redis.get(cacheKey);- if (cached) {- return JSON.parse(cached as string);+ // Try the new prefixed key first+ let cached = await redis.get(`json:${cacheKey}`);+ if (cached && typeof cached === "string") {+ try {+ return JSON.parse(cached);+ } catch (parseError) {+ console.error(+ `JSON parse error for prefixed cache key json:${cacheKey}:`,+ parseError+ );+ await redis.del(`json:${cacheKey}`);+ }+ }++ // Fallback to old key format for backwards compatibility+ cached = await redis.get(cacheKey);+ if (cached !== null && cached !== undefined) {+ // Log the type and content for debugging+ console.log(`Cache hit for ${cacheKey}:`, {+ type: typeof cached,+ isArray: Array.isArray(cached),+ value: cached,+ constructor: cached?.constructor?.name,+ });++ // Handle different response types from Upstash+ if (Array.isArray(cached)) {+ // Direct array return from Upstash+ return cached as CompanyIntegration[];+ } else if (typeof cached === "object" && cached !== null) {+ // Object return from Upstash - could be a parsed JSON already+ return cached as CompanyIntegration[];+ } else if (typeof cached === "string") {+ // String return - needs JSON parsing+ try {+ return JSON.parse(cached);+ } catch (parseError) {+ console.error(+ `JSON parse error for cache key ${cacheKey}:`,+ parseError+ );+ console.error("Cached value that failed to parse:", cached);+ await redis.del(cacheKey);+ }+ } else {+ console.warn(+ `Unexpected cache format for key ${cacheKey}:`,+ typeof cached,+ cached+ );+ await redis.del(cacheKey);+ }}} catch (error) {console.error("Redis cache read error:", error);+ // Clear the corrupted cache entry+ try {+ await redis.del(cacheKey);+ } catch (deleteError) {+ console.error("Failed to delete corrupted cache entry:", deleteError);+ }}const { data, error } = await client@@ -105,11 +182,18 @@ export async function getCompanyIntegrations(const integrations = data || [];try {- await redis.setex(- cacheKey,- INTEGRATION_CACHE_TTL,- JSON.stringify(integrations)- );+ // Force string storage to avoid Upstash automatic deserialization issues+ const serializedData = JSON.stringify(integrations);+ if (typeof serializedData === "string" && serializedData.length > 0) {+ // Use a prefixed key to ensure we know this is a JSON string+ await redis.setex(+ `json:${cacheKey}`,+ INTEGRATION_CACHE_TTL,+ serializedData+ );+ } else {+ console.error("Failed to serialize integrations data for cache");+ }} catch (error) {console.error("Redis cache write error:", error);}diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsxindex f3cd361ce2..b021243d8a 100644--- a/apps/erp/app/routes/_public+/login.tsx+++ b/apps/erp/app/routes/_public+/login.tsx@@ -59,7 +59,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const ratelimit = new Ratelimit({redis,- limiter: Ratelimit.slidingWindow(5, "1 h"),+ limiter: Ratelimit.slidingWindow(15, "1 h"),analytics: true,});diff --git a/apps/erp/app/routes/_public+/verify.tsx b/apps/erp/app/routes/_public+/verify.tsxindex acc392715e..e52c6bb0d0 100644--- a/apps/erp/app/routes/_public+/verify.tsx+++ b/apps/erp/app/routes/_public+/verify.tsx@@ -59,7 +59,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const ratelimit = new Ratelimit({redis,- limiter: Ratelimit.slidingWindow(5, "1 h"), // 5 submissions per hour+ limiter: Ratelimit.slidingWindow(15, "1 h"), // 5 submissions per houranalytics: true,});diff --git a/apps/erp/app/routes/api+/integrations.slack.interactive.ts b/apps/erp/app/routes/api+/integrations.slack.interactive.tsindex 59a1aa5c7e..13d6c60d41 100644--- a/apps/erp/app/routes/api+/integrations.slack.interactive.ts+++ b/apps/erp/app/routes/api+/integrations.slack.interactive.ts@@ -1,6 +1,13 @@import { getCarbonServiceRole, VERCEL_URL } from "@carbon/auth";-import { createSlackWebClient } from "@carbon/integrations/slack.server";-import { tasks } from "@trigger.dev/sdk/v3";+import type { Database } from "@carbon/database";+import {+ createIssueSlackThread,+ createSlackWebClient,+ getCarbonEmployeeFromSlackId,+ getSlackIntegrationByTeamId,+} from "@carbon/integrations/slack.server";+import type { SupabaseClient } from "@supabase/supabase-js";+import { FunctionRegion } from "@supabase/supabase-js";import { json, type ActionFunctionArgs } from "@vercel/remix";import { z } from "zod";import {@@ -8,10 +15,8 @@ import {getIssueWorkflowsList,upsertIssue,} from "~/modules/quality/quality.service";-import {- getIntegration,- getNextSequence,-} from "~/modules/settings/settings.service";++import { getNextSequence } from "~/modules/settings/settings.service";import { path } from "~/utils/path";export const config = {@@ -20,22 +25,34 @@ export const config = {const slackInteractivePayloadSchema = z.object({type: z.string(),- team: z.object({- id: z.string(),- domain: z.string(),- }),+ team: z+ .object({+ id: z.string(),+ domain: z.string(),+ })+ .optional(),user: z.object({id: z.string(),- name: z.string(),- }),- channel: z.object({- id: z.string(),- name: z.string(),+ name: z.string().optional(),+ username: z.string().optional(),}),+ channel: z+ .object({+ id: z.string(),+ name: z.string(),+ })+ .optional(),trigger_id: z.string().optional(),response_url: z.string().optional(),actions: z.array(z.any()).optional(),view: z.any().optional(),+ api_app_id: z.string().optional(),+ token: z.string().optional(),+ container: z.any().optional(),+ enterprise: z.any().optional(),+ message: z.any().optional(),+ // Shortcut specific fields+ callback_id: z.string().optional(),});export async function action({ request }: ActionFunctionArgs) {@@ -47,19 +64,39 @@ export async function action({ request }: ActionFunctionArgs) {return json({ error: "Missing payload" }, { status: 400 });}- const payload = slackInteractivePayloadSchema.parse(+ let payload = slackInteractivePayloadSchema.safeParse(JSON.parse(payloadString));+ if (!payload.success) {+ console.error(+ "Slack payload validation error:",+ JSON.stringify(payload.error)+ );+ return json(+ {+ response_type: "ephemeral",+ text: "Invalid payload format received.",+ },+ { status: 400 }+ );+ }+const serviceRole = await getCarbonServiceRole();- const integration = await getIntegration(+ if (!payload.data.team?.id) {+ return json({+ response_type: "ephemeral",+ text: "Invalid payload: missing team information.",+ });+ }++ const integration = await getSlackIntegrationByTeamId(serviceRole,- "slack",- payload.team.id+ payload.data.team.id);- if (!integration.data) {+ if (!integration.data || integration.error) {return json({response_type: "ephemeral",text: "Slack integration not found for this workspace.",@@ -76,16 +113,20 @@ export async function action({ request }: ActionFunctionArgs) {});}- switch (payload.type) {+ switch (payload.data.type) {+ case "shortcut":+ return handleShortcut(payload.data, companyId, slackToken, serviceRole);+case "block_actions":- return handleBlockActions(payload, companyId, slackToken);+ return handleBlockActions(payload.data, companyId, slackToken);case "view_submission":return handleViewSubmission(- payload,+ payload.data,companyId,slackToken,- serviceRole+ serviceRole,+ integration.data);case "view_closed":@@ -94,7 +135,7 @@ export async function action({ request }: ActionFunctionArgs) {default:return json({response_type: "ephemeral",- text: `Unknown interaction type: ${payload.type}`,+ text: `Unknown interaction type: ${payload.data.type}`,});}} catch (error) {@@ -110,7 +151,7 @@ export async function action({ request }: ActionFunctionArgs) {}async function handleBlockActions(- payload: any,+ payload: z.infer<typeof slackInteractivePayloadSchema>,companyId: string,slackToken: string) {@@ -120,166 +161,221 @@ async function handleBlockActions(return json({ ok: true });}- const slackClient = createSlackWebClient({ token: slackToken });+ // Handle other block actions here as needed+ // Issue creation is now handled via shortcutsswitch (action.action_id) {- case "ncr":- const serviceRole = await getCarbonServiceRole();- const [types, workflows] = await Promise.all([- getIssueTypesList(serviceRole, companyId),- getIssueWorkflowsList(serviceRole, companyId),- ]);-- 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",- },- },+ case "view_in_carbon":+ // This action just opens a URL, so we don't need to handle it+ return json({ ok: true });++ default:+ return json({ ok: true });+ }+}++async function handleShortcut(+ payload: z.infer<typeof slackInteractivePayloadSchema>,+ companyId: string,+ slackToken: string,+ serviceRole: SupabaseClient<Database>+) {+ // Handle different shortcut types based on callback_id+ const callbackId = payload.callback_id;++ switch (callbackId) {+ case "create_ncr_modal":+ return handleCreateNcrShortcut(+ payload,+ companyId,+ slackToken,+ serviceRole+ );++ default:+ return json({ ok: true });+ }+}++async function handleCreateNcrShortcut(+ payload: z.infer<typeof slackInteractivePayloadSchema>,+ companyId: string,+ slackToken: string,+ serviceRole: any+) {+ if (!payload.trigger_id) {+ return json({+ response_type: "ephemeral",+ text: "Missing trigger ID for modal interaction.",+ });+ }++ try {+ const [types, workflows] = await Promise.all([+ getIssueTypesList(serviceRole, companyId),+ getIssueWorkflowsList(serviceRole, companyId),+ ]);++ const slackClient = createSlackWebClient({ token: slackToken });++ await slackClient.views.open({+ trigger_id: payload.trigger_id,+ view: {+ type: "modal",+ callback_id: "create_ncr_modal",+ title: {+ type: "plain_text",+ text: "Create Issue",+ },+ 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",},- {- type: "input",- block_id: "description_block",- label: {+ element: {+ type: "plain_text_input",+ action_id: "title",+ placeholder: {type: "plain_text",- text: "Description",+ text: "Brief description of the non-conformance",},- 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: "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: "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,- })) || [],+ text: "Detailed description of the issue",},},- {- type: "input",- block_id: "workflow_block",- label: {+ 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: "Workflow",+ text: "Select issue type",},- 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,+ options:+ types.data?.map((type) => ({+ text: {+ type: "plain_text",+ text: type.name,+ },+ value: type.id,+ })) || [],+ },+ },+ // Only include workflow block if workflows are available+ ...(workflows.data && workflows.data.length > 0+ ? [+ {+ type: "input" as const,+ block_id: "workflow_block",+ label: {+ type: "plain_text" as const,+ text: "Workflow",+ },+ element: {+ type: "static_select" as const,+ action_id: "workflow",+ placeholder: {+ type: "plain_text" as const,+ text: "Select workflow",},- value: workflow.id,- })) || [],- },- optional: true,+ options: workflows.data.map((workflow) => ({+ text: {+ type: "plain_text" as const,+ text: workflow.name,+ },+ value: workflow.id,+ })),+ },+ optional: true,+ },+ ]+ : []),+ {+ type: "input",+ block_id: "severity_block",+ label: {+ type: "plain_text",+ text: "Severity",},- {- type: "input",- block_id: "severity_block",- label: {+ element: {+ type: "static_select",+ action_id: "severity",+ placeholder: {type: "plain_text",- text: "Severity",+ text: "Select 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",},- 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,+ { text: { type: "plain_text", text: "High" }, value: "High" },+ {+ text: { type: "plain_text", text: "Critical" },+ value: "Critical",+ },+ ],},- ],- private_metadata: JSON.stringify({- channel_id: payload.channel.id,- user_id: payload.user.id,- }),- },- });-- return json({ ok: true });+ optional: true,+ },+ ],+ private_metadata: JSON.stringify({+ channel_id: payload.channel?.id || "",+ user_id: payload.user.id,+ }),+ },+ });- default:- return json({ ok: true });+ return json({ ok: true });+ } catch (error) {+ console.error("Error opening Issue modal:", error);+ return json({+ response_type: "ephemeral",+ text: "Failed to open Issue form. Please try again.",+ });}}async function handleViewSubmission(- payload: any,+ payload: z.infer<typeof slackInteractivePayloadSchema>,companyId: string,slackToken: string,- serviceRole: any+ serviceRole: SupabaseClient<Database>,+ integration: any) {const view = payload.view;@@ -296,27 +392,39 @@ async function handleViewSubmission(const severity =values.severity_block?.severity?.selected_option?.value || "Medium";- const metadata = JSON.parse(view.private_metadata);- const { channel_id, user_id } = metadata;+ const modalMetadata = JSON.parse(view.private_metadata);+ const { user_id } = modalMetadata;- const nextSequence = await getNextSequence(- serviceRole,- "nonConformance",- companyId- );+ // Use the configured channel from integration metadata, not the trigger channel+ const integrationMetadata = integration.metadata as any;+ const configuredChannelId = integrationMetadata?.channel_id;++ if (!configuredChannelId) {+ throw new Error("No channel configured for Slack integration");+ }++ const [nextSequence, employee] = await Promise.all([+ getNextSequence(serviceRole, "nonConformance", companyId),+ getCarbonEmployeeFromSlackId(serviceRole, slackToken, user_id, companyId),+ ]);if (nextSequence.error || !nextSequence.data) {throw new Error("Failed to get next sequence number");}+ if (employee.error || !employee.data) {+ console.error(employee.error);+ throw new Error("Failed to get employee");+ }+const createResult = await upsertIssue(serviceRole, {nonConformanceId: nextSequence.data,approvalRequirements: [],companyId,- createdBy: "system",+ createdBy: employee.data?.id,description,investigationTypeIds: [],- locationId: "",+ locationId: employee.data?.locationId || "",name: title,nonConformanceTypeId: typeId,nonConformanceWorkflowId: workflowId,@@ -327,98 +435,62 @@ async function handleViewSubmission(});if (createResult.error || !createResult.data) {- throw new Error("Failed to create non-conformance");+ console.error(createResult.error);+ throw new Error("Failed to create issue");}const ncrId = createResult.data.id;- const slackClient = createSlackWebClient({ token: slackToken });- 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}`,- },- ],- },+ const [threadResult, tasksResult] = await Promise.all([+ createIssueSlackThread(+ serviceRole,{- type: "context",- elements: [- {- type: "mrkdwn",- text: `Created by <@${user_id}>`,- },- ],+ carbonUrl: `${VERCEL_URL || "http://localhost:3000"}${path.to.issue(+ ncrId+ )}`,+ companyId,+ description,+ id: ncrId,+ nonConformanceId: nextSequence.data,+ severity,+ title,+ userId: employee.data?.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",- },- ],+ slackToken,+ slackUserId: user_id,+ channelId: configuredChannelId,+ }+ ),+ serviceRole.functions.invoke("create", {+ body: {+ type: "nonConformanceTasks",+ id: ncrId,+ companyId,+ userId: employee.data?.id ?? "system",},- ],- });+ region: FunctionRegion.UsEast1,+ }),+ ]);- if (threadMessage.ts) {- await serviceRole.from("slackDocumentThread").insert({- documentType: "nonConformance",- documentId: ncrId,- companyId,- channelId: channel_id,- threadTs: threadMessage.ts,- createdBy: user_id,- });+ if (tasksResult.error) {+ console.error("Error creating tasks:", tasksResult.error);+ }- await tasks.trigger("slack-document-created", {- documentType: "nonConformance",- documentId: ncrId,- companyId,- channelId: channel_id,- threadTs: threadMessage.ts,- });+ if (threadResult.error) {+ console.error("Error creating thread:", threadResult.error);}return json({response_action: "clear",});} catch (error) {- console.error("Error creating NCR:", error);+ console.error("Error creating Issue:", error);return json({response_action: "errors",errors: {- title_block: "Failed to create NCR. Please try again.",+ title_block: "Failed to create Issue. Please try again.",},});}diff --git a/apps/erp/app/routes/x+/issue+/$id.status.tsx b/apps/erp/app/routes/x+/issue+/$id.status.tsxindex cf12c61a46..5dd4c953ea 100644--- a/apps/erp/app/routes/x+/issue+/$id.status.tsx+++ b/apps/erp/app/routes/x+/issue+/$id.status.tsx@@ -55,6 +55,7 @@ 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,@@ -62,7 +63,6 @@ export async function action({ request, params }: ActionFunctionArgs) {previousStatus,newStatus: status,updatedBy: userId,- reason: formData.get("reason") as string | undefined,});}} catch (error) {diff --git a/apps/erp/app/routes/x+/issue+/new.tsx b/apps/erp/app/routes/x+/issue+/new.tsxindex e434c9eda7..4d5e9cde29 100644--- a/apps/erp/app/routes/x+/issue+/new.tsx+++ b/apps/erp/app/routes/x+/issue+/new.tsx@@ -1,7 +1,13 @@-import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";+import {+ assertIsPost,+ error,+ getCarbonServiceRole,+ VERCEL_URL,+} from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";+import { createIssueSlackThread } from "@carbon/integrations/slack.service";import { getLocalTimeZone, today } from "@internationalized/date";import { useLoaderData } from "@remix-run/react";import { FunctionRegion } from "@supabase/supabase-js";@@ -19,7 +25,6 @@ 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";@@ -128,10 +133,17 @@ export async function action({ request }: ActionFunctionArgs) {try {const hasSlack = await hasSlackIntegration(client, companyId);if (hasSlack) {- await createIssueSlackThreadWithMessage(serviceRole, {- nonConformanceId: ncrId,+ await createIssueSlackThread(serviceRole, {+ carbonUrl: `${VERCEL_URL || "http://localhost:3000"}${path.to.issue(+ ncrId+ )}`,companyId,- createdBy: userId,+ description: validation.data.description,+ id: ncrId,+ nonConformanceId: nextSequence.data,+ severity: validation.data.priority,+ title: validation.data.name,+ userId: userId,});}} catch (error) {diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 8663c04ff9..31defb8900 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -80850,7 +80850,7 @@ export default {],properties: {id: {- default: "public.id('dst'::text)",+ default: "public.id('slack'::text)",description: "Note:\nThis is a Primary Key.<pk/>",format: "text",type: "string",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 3d35da2c5a..8a15ef3646 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -39679,14 +39679,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -43511,14 +43511,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -44054,14 +44054,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -47578,15 +47578,6 @@ 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"@@ -47605,6 +47596,15 @@ export type Database = {| "Tool"| "Fixture"| "Consumable"+ documentthreadtype:+ | "nonConformance"+ | "quote"+ | "salesOrder"+ | "job"+ | "purchaseOrder"+ | "invoice"+ | "receipt"+ | "shipment"documentTransactionType:| "Download"| "Edit"diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 3d35da2c5a..8a15ef3646 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -39679,14 +39679,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -43511,14 +43511,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -44054,14 +44054,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -47578,15 +47578,6 @@ 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"@@ -47605,6 +47596,15 @@ export type Database = {| "Tool"| "Fixture"| "Consumable"+ documentthreadtype:+ | "nonConformance"+ | "quote"+ | "salesOrder"+ | "job"+ | "purchaseOrder"+ | "invoice"+ | "receipt"+ | "shipment"documentTransactionType:| "Download"| "Edit"diff --git a/packages/database/supabase/functions/slack-document-sync/index.ts b/packages/database/supabase/functions/slack-document-sync/index.tsindex b6af07281f..035835bb70 100644--- a/packages/database/supabase/functions/slack-document-sync/index.ts+++ b/packages/database/supabase/functions/slack-document-sync/index.ts@@ -1,6 +1,12 @@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 {+ slackDocumentAssignmentUpdate,+ slackDocumentCreated,+ slackDocumentStatusUpdate,+ slackDocumentTaskUpdate,+} from "../../../../jobs/trigger/slack-document-sync.ts";import { corsHeaders } from "../lib/headers.ts";import { getSupabaseServiceRole } from "../lib/supabase.ts";@@ -19,9 +25,9 @@ type DocumentType = z.infer<typeof documentTypeSchema>;const metadataSchema = z.record(z.unknown()).optional();-const payloadValidator = z.discriminatedUnion("updateType", [+const payloadValidator = z.discriminatedUnion("type", [z.object({- updateType: z.literal("created"),+ type: z.literal("created"),documentType: documentTypeSchema,documentId: z.string(),companyId: z.string(),@@ -34,7 +40,7 @@ const payloadValidator = z.discriminatedUnion("updateType", [.optional(),}),z.object({- updateType: z.literal("status-update"),+ type: z.literal("status-update"),documentType: documentTypeSchema,documentId: z.string(),companyId: z.string(),@@ -42,12 +48,11 @@ const payloadValidator = z.discriminatedUnion("updateType", [previousStatus: z.string(),newStatus: z.string(),updatedBy: z.string(),- reason: z.string().optional(),metadata: metadataSchema,}),}),z.object({- updateType: z.literal("task-update"),+ type: z.literal("task-update"),documentType: documentTypeSchema,documentId: z.string(),companyId: z.string(),@@ -63,7 +68,7 @@ const payloadValidator = z.discriminatedUnion("updateType", [}),}),z.object({- updateType: z.literal("assignment-update"),+ type: z.literal("assignment-update"),documentType: documentTypeSchema,documentId: z.string(),companyId: z.string(),@@ -75,7 +80,7 @@ const payloadValidator = z.discriminatedUnion("updateType", [}),}),z.object({- updateType: z.literal("custom"),+ type: z.literal("custom"),documentType: documentTypeSchema,documentId: z.string(),companyId: z.string(),@@ -101,18 +106,12 @@ serve(async (req: Request) => {try {const body = await req.json();const validatedPayload = payloadValidator.parse(body);- const {- updateType,- documentType,- documentId,- companyId,- payload,- ...otherData- } = validatedPayload;+ const { type, documentType, documentId, companyId, payload, ...otherData } =+ validatedPayload;console.log({function: "slack-document-sync",- updateType,+ type,documentType,documentId,companyId,@@ -124,6 +123,7 @@ serve(async (req: Request) => {req.headers.get("carbon-key") ?? "",companyId);+const { data: integration } = await serviceRole.from("companyIntegration").select("metadata")@@ -167,47 +167,59 @@ serve(async (req: Request) => {}// Trigger the appropriate Trigger.dev job- switch (updateType) {+ switch (type) {case "created": {const createdData = otherData as Extract<ValidatedPayload,- { updateType: "created" }+ { type: "created" }>;- await tasks.trigger("slack-document-created", {- documentType,- documentId,- companyId,- channelId: createdData.channelId,- threadTs: createdData.threadTs,- });+ await tasks.trigger<typeof slackDocumentCreated>(+ "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,- });+ await tasks.trigger<typeof slackDocumentStatusUpdate>(+ "slack-document-status-update",+ {+ documentType,+ documentId,+ companyId,+ ...payload,+ }+ );break;case "task-update":- await tasks.trigger("slack-document-task-update", {- documentType,- documentId,- companyId,- ...payload,- });+ await tasks.trigger<typeof slackDocumentTaskUpdate>(+ "slack-document-task-update",+ {+ documentType,+ documentId,+ companyId,+ ...payload,+ }+ );break;case "assignment-update":- await tasks.trigger("slack-document-assignment-update", {- documentType,- documentId,- companyId,- ...payload,- });+ await tasks.trigger<typeof slackDocumentAssignmentUpdate>(+ "slack-document-assignment-update",+ {+ documentType,+ documentId,+ companyId,+ ...payload,+ }+ );break;case "custom":@@ -216,7 +228,7 @@ serve(async (req: Request) => {break;default:- throw new Error(`Invalid updateType ${updateType}`);+ throw new Error(`Invalid type ${type}`);}return new Response(diff --git a/packages/database/supabase/migrations/20250810203046_slack-nonconformance-integration.sql b/packages/database/supabase/migrations/20250810203046_slack-nonconformance-integration.sqlindex 8755922e49..5b17ec5427 100644--- a/packages/database/supabase/migrations/20250810203046_slack-nonconformance-integration.sql+++ b/packages/database/supabase/migrations/20250810203046_slack-nonconformance-integration.sql@@ -1,62 +1,3 @@--- 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 settingsUPDATE "integration"SET "jsonschema" = jsonb_build_object('type', 'object',diff --git a/packages/database/supabase/migrations/20250810204801_slack-document-threads-refactor.sql b/packages/database/supabase/migrations/20250810204801_slack-document-threads.sqlsimilarity index 67%rename from packages/database/supabase/migrations/20250810204801_slack-document-threads-refactor.sqlrename to packages/database/supabase/migrations/20250810204801_slack-document-threads.sqlindex bf6f416c00..766f2ec79f 100644--- a/packages/database/supabase/migrations/20250810204801_slack-document-threads-refactor.sql+++ b/packages/database/supabase/migrations/20250810204801_slack-document-threads.sql@@ -3,7 +3,7 @@ DROP TABLE IF EXISTS "nonConformanceSlackThread";-- Create generic document thread mapping tableCREATE TABLE "slackDocumentThread" (- "id" TEXT NOT NULL DEFAULT id('dst'),+ "id" TEXT NOT NULL DEFAULT id('slack'),"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@@ -29,37 +29,9 @@ CREATE INDEX "slackDocumentThread_channelId_threadTs_idx" ON "slackDocumentThrea-- Enable Row Level SecurityALTER 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 (+CREATE TYPE documentThreadType AS ENUM ('nonConformance','quote','salesOrder',@@ -73,4 +45,4 @@ CREATE TYPE document_thread_type AS ENUM (-- Add check constraint to ensure documentType uses valid valuesALTER TABLE "slackDocumentThread"ADD CONSTRAINT "slackDocumentThread_documentType_check"-CHECK ("documentType"::document_thread_type IS NOT NULL);\ No newline at end of file+CHECK ("documentType"::documentThreadType IS NOT NULL);\ No newline at end of filediff --git a/packages/integrations/src/slack/lib/client.ts b/packages/integrations/src/slack/lib/client.tsindex c03bdbea7b..17f03bf235 100644--- a/packages/integrations/src/slack/lib/client.ts+++ b/packages/integrations/src/slack/lib/client.ts@@ -71,6 +71,10 @@ export const createSlackApp = ({});};+export const createSlackWebClient = ({ token }: { token: string }) => {+ return new WebClient(token);+};+export const getSlackInstaller = (): InstallProvider => {if (!slackInstaller) {if (!SLACK_CLIENT_ID || !SLACK_CLIENT_SECRET) {@@ -90,10 +94,6 @@ export const getSlackInstaller = (): InstallProvider => {return slackInstaller;};-export const createSlackWebClient = ({ token }: { token: string }) => {- return new WebClient(token);-};-export const getSlackInstallUrl = ({companyId,userId,@@ -103,14 +103,16 @@ export const getSlackInstallUrl = ({}) => {return getSlackInstaller().generateInstallUrl({scopes: [- "incoming-webhook",- "chat:write",- "chat:write.public",- "team:read","assistant:write",- "im:history",+ "chat:write.public",+ "chat:write","commands","files:read",+ "im:history",+ "incoming-webhook",+ "team:read",+ "users:read",+ "users:read.email",],redirectUri: SLACK_OAUTH_REDIRECT_URL,metadata: JSON.stringify({ companyId, userId }),diff --git a/packages/integrations/src/slack/lib/service.ts b/packages/integrations/src/slack/lib/service.tsindex cc601b4dbe..fbda072e92 100644--- a/packages/integrations/src/slack/lib/service.ts+++ b/packages/integrations/src/slack/lib/service.ts@@ -1,17 +1,15 @@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";+import { createSlackWebClient } from "./client";++export type DocumentType = "nonConformance";++export interface SlackAuth {+ slackToken: string;+ slackUserId?: string;+ channelId: string;+}export interface SlackDocumentThread {id: string;@@ -26,67 +24,122 @@ export interface SlackDocumentThread {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(+export async function createIssueSlackThread(client: SupabaseClient<Database>,data: {- documentType: DocumentType;- documentId: string;+ carbonUrl: string;companyId: string;- channelId: string;- threadTs: string;- createdBy: string;- }+ description?: string;+ id: string;+ nonConformanceId: string;+ severity: string;+ title: string;+ userId: string;+ },+ slackAuth?: SlackAuth) {- return client.from("slackDocumentThread").insert(data).select("*").single();-}+ try {+ const auth =+ slackAuth ?? (await getSlackAuth(client, data.companyId, data.userId));+ if (!auth) {+ throw new Error("Slack auth not found");+ }-/**- * Update Slack thread mapping- */-export async function updateSlackDocumentThread(- client: SupabaseClient<Database>,- id: string,- updates: {- channelId?: string;- threadTs?: string;- updatedBy: string;+ const slackClient = createSlackWebClient({ token: auth?.slackToken });++ const threadMessage = await slackClient.chat.postMessage({+ channel: auth.channelId,+ unfurl_links: false,+ unfurl_media: false,+ blocks: [+ {+ type: "header",+ text: {+ type: "plain_text",+ text: `Issue ${data.nonConformanceId}`,+ },+ },+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*${data.title}*\n${+ data.description || "_No description provided_"+ }`,+ },+ fields: [+ {+ type: "mrkdwn",+ text: `*Status:*\nRegistered`,+ },+ {+ type: "mrkdwn",+ text: `*Severity:*\n${data.severity}`,+ },+ ],+ },+ {+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `Created by <@${auth.slackUserId}>`,+ },+ ],+ },+ {+ type: "actions",+ elements: [+ {+ type: "button",+ text: {+ type: "plain_text",+ text: "View in Carbon",+ },+ url: data.carbonUrl,+ action_id: "view_in_carbon",+ },+ ],+ },+ ],+ });++ if (threadMessage.ts) {+ const threadRecord = await client+ .from("slackDocumentThread")+ .insert({+ documentType: "nonConformance",+ documentId: data.id,+ companyId: data.companyId,+ channelId: auth.channelId,+ threadTs: threadMessage.ts,+ createdBy: data.userId,+ })+ .select("*")+ .single();++ if (threadRecord.error) {+ console.error("Error creating thread record:", threadRecord.error);+ }++ return threadRecord;+ }++ return {+ data: null,+ error: { message: "Failed to post message to Slack" },+ };+ } catch (error) {+ console.error("Error creating Issue Slack thread:", error);+ return {+ data: null,+ error: {+ message: error instanceof Error ? error.message : "Unknown error",+ },+ };}-) {- 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,@@ -101,9 +154,6 @@ export async function deleteSlackDocumentThread(.eq("companyId", companyId);}-/**- * Get all Slack threads for a company (optionally filtered by document type)- */export async function getCompanySlackThreads(client: SupabaseClient<Database>,companyId: string,@@ -121,16 +171,159 @@ export async function getCompanySlackThreads(return query.order("createdAt", { ascending: false });}-/**- * Generic function to sync document updates to Slack- */+export async function getIssueSlackThread(+ client: SupabaseClient<Database>,+ nonConformanceId: string,+ companyId: string+) {+ return getSlackDocumentThread(+ client,+ "nonConformance",+ nonConformanceId,+ companyId+ );+}++export async function getSlackAuth(+ client: SupabaseClient<Database>,+ companyId: string,+ userId: string+): Promise<SlackAuth | null> {+ const companyIntegration = await client+ .from("companyIntegration")+ .select("*")+ .eq("companyId", companyId)+ .eq("id", "slack")+ .maybeSingle();+ if (companyIntegration.error) {+ return null;+ }++ const metadata = companyIntegration.data?.metadata as {+ access_token: string;+ channel_id: string;+ };++ if (!metadata) {+ return null;+ }++ const user = await client+ .from("user")+ .select("email")+ .eq("id", userId)+ .single();++ if (user.error || !user.data?.email) {+ return {+ slackToken: metadata.access_token,+ channelId: metadata.channel_id,+ };+ }++ try {+ const slackClient = createSlackWebClient({ token: metadata.access_token });+ const slackUser = await slackClient.users.lookupByEmail({+ email: user.data.email,+ });++ if (slackUser.ok && slackUser.user?.id) {+ return {+ slackToken: metadata.access_token,+ slackUserId: slackUser.user.id,+ channelId: metadata.channel_id,+ };+ }+ } catch (error) {+ console.error("Failed to lookup Slack user by email:", error);+ }++ return {+ slackToken: metadata.access_token,+ channelId: metadata.channel_id,+ };+}++export async function getSlackDocumentThread(+ client: SupabaseClient<Database>,+ documentType: DocumentType,+ documentId: string,+ companyId: string+) {+ console.log({ documentType, documentId, companyId });+ return client+ .from("slackDocumentThread")+ .select("*")+ .eq("documentType", documentType)+ .eq("documentId", documentId)+ .eq("companyId", companyId)+ .single();+}++export async function getSlackIntegrationByTeamId(+ client: SupabaseClient<Database>,+ teamId: string+) {+ return await client+ .from("companyIntegration")+ .select("*")+ .eq("metadata->>team_id", teamId)+ .eq("id", "slack")+ .maybeSingle();+}++export async function getCarbonEmployeeFromSlackId(+ client: SupabaseClient<Database>,+ accessToken: string,+ slackUserId: string,+ carbonCompanyId: string+) {+ try {+ const slackClient = createSlackWebClient({ token: accessToken });++ // Get user info from Slack+ const userInfo = await slackClient.users.info({+ user: slackUserId,+ });++ console.log({ userInfo: userInfo.user?.profile });++ if (!userInfo.ok || !userInfo.user?.profile?.email) {+ return { data: null, error: "Could not retrieve user email from Slack" };+ }++ const email = userInfo.user.profile.email;++ const user = await client+ .from("user")+ .select("id")+ .eq("email", email)+ .single();+ if (user.error) {+ throw new Error("User not found");+ }+ return client+ .from("employeeJob")+ .select("*")+ .eq("id", user.data.id)+ .eq("companyId", carbonCompanyId)+ .single();+ } catch (error) {+ console.error("Error getting Carbon employee from Slack ID:", error);+ return {+ data: null,+ error: error instanceof Error ? error.message : "Unknown error",+ };+ }+}+export async function syncDocumentToSlack(client: SupabaseClient<Database>,data: {documentType: DocumentType;documentId: string;companyId: string;- updateType:+ type:| "created"| "status-update"| "task-update"@@ -139,22 +332,21 @@ export async function syncDocumentToSlack(payload: Record<string, any>;}) {- // Check if Slack thread exists+ const serviceRole = getCarbonServiceRole();const thread = await getSlackDocumentThread(- client,+ serviceRole,data.documentType,data.documentId,data.companyId);if (thread.data) {- // Invoke the edge function to trigger Slack sync- return getCarbonServiceRole().functions.invoke("slack-document-sync", {+ return serviceRole.functions.invoke("slack-document-sync", {body: {documentType: data.documentType,documentId: data.documentId,companyId: data.companyId,- updateType: data.updateType,+ type: data.type,channelId: thread.data.channelId,threadTs: thread.data.threadTs,payload: data.payload,@@ -165,9 +357,6 @@ export async function syncDocumentToSlack(return { data: null, error: null };}-/**- * Sync document creation to Slack (creates initial thread message)- */export async function syncDocumentCreatedToSlack(client: SupabaseClient<Database>,data: {@@ -183,7 +372,7 @@ export async function syncDocumentCreatedToSlack(documentType: data.documentType,documentId: data.documentId,companyId: data.companyId,- updateType: "created",+ type: "created",payload: {channelId: data.channelId,threadTs: data.threadTs,@@ -192,9 +381,6 @@ export async function syncDocumentCreatedToSlack(});}-/**- * Sync document status update to Slack- */export async function syncDocumentStatusToSlack(client: SupabaseClient<Database>,data: {@@ -212,20 +398,16 @@ export async function syncDocumentStatusToSlack(documentType: data.documentType,documentId: data.documentId,companyId: data.companyId,- updateType: "status-update",+ type: "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: {@@ -242,7 +424,7 @@ export async function syncDocumentAssignmentToSlack(documentType: data.documentType,documentId: data.documentId,companyId: data.companyId,- updateType: "assignment-update",+ type: "assignment-update",payload: {previousAssignee: data.previousAssignee,newAssignee: data.newAssignee,@@ -252,9 +434,6 @@ export async function syncDocumentAssignmentToSlack(});}-/**- * Sync custom document update to Slack- */export async function syncDocumentCustomToSlack(client: SupabaseClient<Database>,data: {@@ -269,7 +448,7 @@ export async function syncDocumentCustomToSlack(documentType: data.documentType,documentId: data.documentId,companyId: data.companyId,- updateType: "custom",+ type: "custom",payload: {customType: data.customType,...data.payload,@@ -277,50 +456,6 @@ export async function syncDocumentCustomToSlack(});}-// 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: {@@ -339,13 +474,9 @@ export async function syncIssueStatusToSlack(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: {@@ -377,9 +508,6 @@ export async function syncIssueTaskToSlack(});}-/**- * Sync assignment update to Slack- */export async function syncIssueAssignmentToSlack(client: SupabaseClient<Database>,data: {@@ -400,141 +528,22 @@ export async function syncIssueAssignmentToSlack(});}-/**- * 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(+export async function updateSlackDocumentThread(client: SupabaseClient<Database>,- data: {- nonConformanceId: string;- companyId: string;- createdBy: string;+ id: string,+ updates: {+ channelId?: string;+ threadTs?: string;+ updatedBy: 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;+ return client+ .from("slackDocumentThread")+ .update({+ ...updates,+ updatedAt: new Date().toISOString(),+ })+ .eq("id", id)+ .select("*")+ .single();}