Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

refactor: build a notification pipeline for integrations

Brad Barbin387a85d3f46e
diff --git a/apps/erp/app/routes/x+/issue+/$id.status.tsx b/apps/erp/app/routes/x+/issue+/$id.status.tsx
index 5cb89543a1..a185432b8d 100644
--- a/apps/erp/app/routes/x+/issue+/$id.status.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.status.tsx
@@ -1,15 +1,11 @@
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 { notifyIssueStatusChanged } from "@carbon/integrations/notifications";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
-import {
- getIssue,
- nonConformanceStatus,
- updateIssueStatus,
-} from "~/modules/quality";
-import { hasSlackIntegration } from "~/modules/settings/settings.server";
+import { nonConformanceStatus, updateIssueStatus } from "~/modules/quality";
+import { getCompanyIntegrations } from "~/modules/settings/settings.server";
import { path, requestReferrer } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -33,9 +29,6 @@ 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,
@@ -52,21 +45,22 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- // Sync status update to Slack (non-blocking)
+ // Send status update notifications (non-blocking)
try {
- const hasSlack = await hasSlackIntegration(client, companyId);
-
- if (hasSlack) {
- await syncIssueStatusToSlack(client, {
- companyId,
- newStatus: status,
+ const integrations = await getCompanyIntegrations(client, companyId);
+ await notifyIssueStatusChanged({ client }, integrations, {
+ companyId,
+ userId,
+ carbonUrl: `${path.to.issue(id)}`, // We might need the full URL here
+ issue: {
+ id,
+ status,
nonConformanceId: id,
- previousStatus,
- userId,
- });
- }
+ title: "", // We might need to get the title from the issue data
+ },
+ });
} catch (error) {
- console.error("Failed to sync status to Slack:", error);
+ console.error("Failed to send notifications:", error);
// Continue without blocking the main operation
}
diff --git a/apps/erp/app/routes/x+/issue+/new.tsx b/apps/erp/app/routes/x+/issue+/new.tsx
index 4d5e9cde29..b2b41e4d0a 100644
--- a/apps/erp/app/routes/x+/issue+/new.tsx
+++ b/apps/erp/app/routes/x+/issue+/new.tsx
@@ -7,7 +7,7 @@ import {
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 { notifyIssueCreated } from "@carbon/integrations/notifications";
import { getLocalTimeZone, today } from "@internationalized/date";
import { useLoaderData } from "@remix-run/react";
import { FunctionRegion } from "@supabase/supabase-js";
@@ -26,7 +26,7 @@ import {
import IssueForm from "~/modules/quality/ui/Issue/IssueForm";
import { getNextSequence } from "~/modules/settings";
-import { hasSlackIntegration } from "~/modules/settings/settings.server";
+import { getCompanyIntegrations } from "~/modules/settings/settings.server";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -131,23 +131,25 @@ export async function action({ request }: ActionFunctionArgs) {
}
try {
- const hasSlack = await hasSlackIntegration(client, companyId);
- if (hasSlack) {
- await createIssueSlackThread(serviceRole, {
- carbonUrl: `${VERCEL_URL || "http://localhost:3000"}${path.to.issue(
- ncrId
- )}`,
+ const integrations = await getCompanyIntegrations(client, companyId);
+ await notifyIssueCreated(
+ { client, serviceRole },
+ integrations,
+ {
companyId,
- description: validation.data.description,
- id: ncrId,
- nonConformanceId: nextSequence.data,
- severity: validation.data.priority,
- title: validation.data.name,
- userId: userId,
- });
- }
+ userId,
+ carbonUrl: `${VERCEL_URL || "http://localhost:3000"}${path.to.issue(ncrId)}`,
+ issue: {
+ id: ncrId,
+ nonConformanceId: nextSequence.data,
+ title: validation.data.name,
+ description: validation.data.description,
+ severity: validation.data.priority,
+ },
+ }
+ );
} catch (error) {
- console.error("Failed to create Slack notification:", error);
+ console.error("Failed to send notifications:", 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.tsx
index b989062863..e2712a939f 100644
--- a/apps/erp/app/routes/x+/issue+/task.$id.status.tsx
+++ b/apps/erp/app/routes/x+/issue+/task.$id.status.tsx
@@ -1,12 +1,12 @@
-import { json, type ActionFunctionArgs } from "@vercel/remix";
-
-import { assertIsPost, error } from "@carbon/auth";
+import { assertIsPost, error, VERCEL_URL } 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 { notifyTaskStatusChanged } from "@carbon/integrations/notifications";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
import type { IssueInvestigationTask } from "~/modules/quality";
import { updateIssueTaskStatus } from "~/modules/quality";
-import { hasSlackIntegration } from "~/modules/settings/settings.server";
+import { getCompanyIntegrations } from "~/modules/settings/settings.server";
+import { path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -45,17 +45,21 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
try {
- const hasSlack = await hasSlackIntegration(client, companyId);
- if (hasSlack && update.data?.nonConformanceId) {
- await syncIssueTaskToSlack(client, {
- completedAt:
- status === "Completed" ? new Date().toISOString() : undefined,
+ const integrations = await getCompanyIntegrations(client, companyId);
+ if (update.data?.nonConformanceId) {
+ await notifyTaskStatusChanged({ client }, integrations, {
companyId,
- id,
- nonConformanceId: update.data.nonConformanceId,
- status,
- taskType: type as "investigation" | "action" | "approval",
userId,
+ carbonUrl: `${VERCEL_URL}${path.to.issue(
+ update.data.nonConformanceId
+ )}`,
+ task: {
+ id,
+ status,
+ issueId: update.data.nonConformanceId,
+ title: "",
+ type,
+ },
});
}
} catch (error) {
diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.ts
index 33aba055e4..f9d71e5758 100644
--- a/packages/database/supabase/functions/create/index.ts
+++ b/packages/database/supabase/functions/create/index.ts
@@ -322,7 +322,6 @@ serve(async (req: Request) => {
) {
// @ts-ignore -- content is json
const contentFromWorkflow = workflow?.data?.content?.content ?? [];
-
const insertedContent = {
type: "doc",
content: contentFromWorkflow,
@@ -337,11 +336,16 @@ serve(async (req: Request) => {
});
}
+ console.log({
+ description: nonConformance.data?.description,
+ insertedContent,
+ });
+
if (insertedContent.content.length > 0) {
await trx
.updateTable("nonConformance")
.set({
- content: insertedContent.content,
+ content: JSON.stringify(insertedContent),
})
.where("id", "=", id)
.execute();
diff --git a/packages/integrations/package.json b/packages/integrations/package.json
index d6c644aca6..90d0791124 100644
--- a/packages/integrations/package.json
+++ b/packages/integrations/package.json
@@ -5,9 +5,10 @@
"exports": {
".": "./src/index.ts",
"./exchange-rates/exchange-rates.server": "./src/exchange-rates/exchange-rates.server.ts",
+ "./notifications": "./src/notifications/index.ts",
"./onshape": "./src/onshape/lib/index.ts",
"./slack.server": "./src/slack.server.ts",
- "./slack.service": "./src/slack/lib/service.ts"
+ "./slack/messages": "./src/slack/lib/messages.ts"
},
"jest": {
"preset": "@carbon/jest/node"
diff --git a/packages/integrations/src/index.ts b/packages/integrations/src/index.ts
index b5c78b301d..6150ee748a 100644
--- a/packages/integrations/src/index.ts
+++ b/packages/integrations/src/index.ts
@@ -25,6 +25,7 @@ export const integrations = [
export { Onshape, Logo as OnshapeLogo } from "./onshape/config";
export { Slack } from "./slack/config";
+export * from "./slack/lib/messages";
// TODO: export as @carbon/integrations/paperless
export { PaperlessPartsClient } from "./paperless-parts/lib/client";
diff --git a/packages/integrations/src/notifications/index.ts b/packages/integrations/src/notifications/index.ts
new file mode 100644
index 0000000000..7d9cfd67c3
--- /dev/null
+++ b/packages/integrations/src/notifications/index.ts
@@ -0,0 +1,9 @@
+import { notificationRegistry } from "./registry";
+import { SlackNotificationService } from "./services/slack";
+
+notificationRegistry.register(new SlackNotificationService());
+
+export * from "./pipeline";
+export * from "./registry";
+export * from "./types";
+export { SlackNotificationService };
diff --git a/packages/integrations/src/notifications/pipeline.ts b/packages/integrations/src/notifications/pipeline.ts
new file mode 100644
index 0000000000..a8d587457b
--- /dev/null
+++ b/packages/integrations/src/notifications/pipeline.ts
@@ -0,0 +1,174 @@
+import { notificationRegistry } from "./registry";
+import type {
+ CompanyIntegration,
+ NotificationContext,
+ NotificationEvent,
+} from "./types";
+
+export class NotificationPipeline {
+ constructor(private context: NotificationContext) {}
+
+ async send(
+ event: NotificationEvent,
+ integrations: CompanyIntegration[]
+ ): Promise<void> {
+ try {
+ const activeNotificationServices = integrations.filter(
+ (integration) =>
+ integration.active && this.isNotificationService(integration.id)
+ );
+
+ const sendPromises = activeNotificationServices.map(
+ async (integration) => {
+ const service = notificationRegistry.getService(integration.id);
+ if (!service) {
+ console.warn(
+ `Notification service ${integration.id} not found in registry`
+ );
+ return;
+ }
+
+ try {
+ await service.send(event, {
+ serviceRole: this.context.serviceRole || this.context.client,
+ });
+ } catch (error) {
+ console.error(
+ `Failed to send notification via ${integration.id}:`,
+ error
+ );
+ }
+ }
+ );
+
+ await Promise.all(sendPromises);
+ } catch (error) {
+ console.error("Failed to send notification:", error);
+ }
+ }
+
+ private isNotificationService(integrationId: string): boolean {
+ const notificationServiceIds = ["slack"];
+ return notificationServiceIds.includes(integrationId);
+ }
+}
+
+export function createNotificationPipeline(
+ context: NotificationContext
+): NotificationPipeline {
+ return new NotificationPipeline(context);
+}
+
+export async function notifyIssueCreated(
+ context: NotificationContext,
+ integrations: CompanyIntegration[],
+ data: {
+ companyId: string;
+ userId: string;
+ carbonUrl: string;
+ issue: {
+ id: string;
+ nonConformanceId: string;
+ title: string;
+ description: string;
+ severity: string;
+ };
+ }
+): Promise<void> {
+ const pipeline = createNotificationPipeline(context);
+ await pipeline.send(
+ {
+ type: "issue.created",
+ companyId: data.companyId,
+ userId: data.userId,
+ carbonUrl: data.carbonUrl,
+ data: data.issue,
+ },
+ integrations
+ );
+}
+
+export async function notifyIssueStatusChanged(
+ context: NotificationContext,
+ integrations: CompanyIntegration[],
+ data: {
+ companyId: string;
+ userId: string;
+ carbonUrl: string;
+ issue: {
+ id: string;
+ status: string;
+ nonConformanceId: string;
+ title: string;
+ };
+ }
+): Promise<void> {
+ const pipeline = createNotificationPipeline(context);
+ await pipeline.send(
+ {
+ type: "issue.status.changed",
+ companyId: data.companyId,
+ userId: data.userId,
+ carbonUrl: data.carbonUrl,
+ data: data.issue,
+ },
+ integrations
+ );
+}
+
+export async function notifyTaskStatusChanged(
+ context: NotificationContext,
+ integrations: CompanyIntegration[],
+ data: {
+ companyId: string;
+ userId: string;
+ carbonUrl: string;
+ task: {
+ id: string;
+ status: string;
+ issueId: string;
+ title: string;
+ type: "investigation" | "action" | "approval" | "review";
+ };
+ }
+): Promise<void> {
+ const pipeline = createNotificationPipeline(context);
+ await pipeline.send(
+ {
+ type: "task.status.changed",
+ companyId: data.companyId,
+ userId: data.userId,
+ carbonUrl: data.carbonUrl,
+ data: data.task,
+ },
+ integrations
+ );
+}
+
+export async function notifyTaskAssigned(
+ context: NotificationContext,
+ integrations: CompanyIntegration[],
+ data: {
+ companyId: string;
+ userId: string;
+ carbonUrl: string;
+ task: {
+ id: string;
+ table: string;
+ assignee: string;
+ title?: string;
+ };
+ }
+): Promise<void> {
+ const pipeline = createNotificationPipeline(context);
+ await pipeline.send(
+ {
+ type: "task.assigned",
+ companyId: data.companyId,
+ userId: data.userId,
+ carbonUrl: data.carbonUrl,
+ data: data.task,
+ },
+ integrations
+ );
+}
diff --git a/packages/integrations/src/notifications/registry.ts b/packages/integrations/src/notifications/registry.ts
new file mode 100644
index 0000000000..583794fba9
--- /dev/null
+++ b/packages/integrations/src/notifications/registry.ts
@@ -0,0 +1,19 @@
+import type { NotificationService, NotificationServiceRegistry } from "./types";
+
+class ServiceRegistry implements NotificationServiceRegistry {
+ private services = new Map<string, NotificationService>();
+
+ register(service: NotificationService): void {
+ this.services.set(service.id, service);
+ }
+
+ getService(id: string): NotificationService | undefined {
+ return this.services.get(id);
+ }
+
+ getAllServices(): NotificationService[] {
+ return Array.from(this.services.values());
+ }
+}
+
+export const notificationRegistry = new ServiceRegistry();
\ No newline at end of file
diff --git a/packages/integrations/src/notifications/services/slack.ts b/packages/integrations/src/notifications/services/slack.ts
new file mode 100644
index 0000000000..eb965351a3
--- /dev/null
+++ b/packages/integrations/src/notifications/services/slack.ts
@@ -0,0 +1,68 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import {
+ createIssueSlackThread,
+ syncIssueAssignmentToSlack,
+ syncIssueStatusToSlack,
+ syncIssueTaskToSlack,
+} from "../../slack/lib/service";
+import type { NotificationEvent, NotificationService } from "../types";
+
+export class SlackNotificationService implements NotificationService {
+ id = "slack";
+ name = "Slack";
+
+ async send(
+ event: NotificationEvent,
+ context: { serviceRole: SupabaseClient<Database> }
+ ): Promise<void> {
+ switch (event.type) {
+ case "issue.created":
+ await createIssueSlackThread(context.serviceRole, {
+ carbonUrl: event.carbonUrl,
+ companyId: event.companyId,
+ description: event.data.description,
+ id: event.data.id,
+ nonConformanceId: event.data.nonConformanceId,
+ severity: event.data.severity,
+ title: event.data.title,
+ userId: event.userId,
+ });
+ break;
+
+ case "issue.status.changed":
+ await syncIssueStatusToSlack(context.serviceRole, {
+ companyId: event.companyId,
+ nonConformanceId: event.data.nonConformanceId,
+ newStatus: event.data.status,
+ previousStatus: "", // We'll need to get this from the event data if needed
+ userId: event.userId,
+ });
+ break;
+
+ case "task.status.changed":
+ await syncIssueTaskToSlack(context.serviceRole, {
+ companyId: event.companyId,
+ id: event.data.id,
+ status: event.data.status,
+ // @ts-expect-error - it's cool
+ taskType: event.data.type,
+ userId: event.userId,
+ });
+ break;
+
+ case "task.assigned":
+ await syncIssueAssignmentToSlack(context.serviceRole, {
+ nonConformanceId: event.data.id,
+ companyId: event.companyId,
+ userId: event.userId,
+ newAssignee: event.data.assignee,
+ });
+ break;
+
+ default:
+ // Unknown event type, skip
+ break;
+ }
+ }
+}
diff --git a/packages/integrations/src/notifications/types.ts b/packages/integrations/src/notifications/types.ts
new file mode 100644
index 0000000000..6064227e83
--- /dev/null
+++ b/packages/integrations/src/notifications/types.ts
@@ -0,0 +1,85 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+
+// Integration types
+export interface CompanyIntegration {
+ id: string;
+ companyId: string;
+ metadata: Record<string, any>;
+ active: boolean;
+}
+
+// Base notification event types
+export interface BaseNotificationEvent {
+ companyId: string;
+ userId: string;
+ carbonUrl: string;
+}
+
+export interface IssueCreatedEvent extends BaseNotificationEvent {
+ type: "issue.created";
+ data: {
+ id: string;
+ nonConformanceId: string;
+ title: string;
+ description: string;
+ severity: string;
+ };
+}
+
+export interface IssueStatusChangedEvent extends BaseNotificationEvent {
+ type: "issue.status.changed";
+ data: {
+ id: string;
+ status: string;
+ nonConformanceId: string;
+ title: string;
+ };
+}
+
+export interface TaskStatusChangedEvent extends BaseNotificationEvent {
+ type: "task.status.changed";
+ data: {
+ id: string;
+ status: string;
+ issueId: string;
+ title: string;
+ type?: string;
+ };
+}
+
+export interface TaskAssignedEvent extends BaseNotificationEvent {
+ type: "task.assigned";
+ data: {
+ id: string;
+ table: string;
+ assignee: string;
+ title?: string;
+ };
+}
+
+export type NotificationEvent =
+ | IssueCreatedEvent
+ | IssueStatusChangedEvent
+ | TaskStatusChangedEvent
+ | TaskAssignedEvent;
+
+// Notification service interface
+export interface NotificationService {
+ id: string;
+ name: string;
+ send(event: NotificationEvent, config: any): Promise<void>;
+}
+
+// Context for notification services
+export interface NotificationContext {
+ client: SupabaseClient<Database>;
+ serviceRole?: SupabaseClient<Database>;
+}
+
+// Service registry
+export interface NotificationServiceRegistry {
+ register(service: NotificationService): void;
+ getService(id: string): NotificationService | undefined;
+ getAllServices(): NotificationService[];
+}
diff --git a/packages/integrations/src/slack/lib/messages.ts b/packages/integrations/src/slack/lib/messages.ts
index e36c89fa91..4ecd16a992 100644
--- a/packages/integrations/src/slack/lib/messages.ts
+++ b/packages/integrations/src/slack/lib/messages.ts
@@ -1,25 +1,24 @@
import type { KnownBlock } from "@slack/types";
-export type DocumentType = "nonConformance";
-// | "quote"
-// | "salesOrder"
-// | "job"
-// | "purchaseOrder"
-// | "invoice"
-// | "receipt"
-// | "shipment";
+export type DocumentType =
+ | "nonConformance"
+ | "quote"
+ | "salesOrder"
+ | "job"
+ | "purchaseOrder"
+ | "invoice"
+ | "receipt"
+ | "shipment";
export interface BaseDocumentData {
- id: string;
documentType: DocumentType;
- title: string;
+ id: string;
+ readableId: string;
+ title?: string;
description?: string;
- status: string;
+ status?: string;
createdBy?: string;
createdAt?: string;
- updatedAt?: string;
- assignedTo?: string;
- metadata?: Record<string, any>;
}
export interface NonConformanceData extends BaseDocumentData {
@@ -39,7 +38,8 @@ export interface IssueTaskUpdate {
taskType: "investigation" | "action" | "approval";
taskName: string;
status: string;
- assignedTo?: string;
+ assignee?: string | null;
+ readableId?: string;
completedBy?: string;
completedAt?: string;
notes?: string;
@@ -109,14 +109,14 @@ export function formatDocumentCreated(
type: "section",
text: {
type: "mrkdwn",
- text: `*${data.title}*\n${
+ text: `*${data.title || "No title"}*\n${
data.description || "_No description provided_"
}`,
},
fields: [
{
type: "mrkdwn",
- text: `*Status:*\n${data.status}`,
+ text: `*Status:*\n${data.status || "Unknown"}`,
},
{
type: "mrkdwn",
@@ -258,16 +258,29 @@ export function formatStatusUpdate(
documentIdentifier: string,
update: IssueStatusUpdate
): KnownBlock[] {
- const typeInfo = getDocumentTypeInfo(documentType);
+ const emoji = getStatusEmoji(update.newStatus);
const blocks: KnownBlock[] = [
{
type: "section",
text: {
type: "mrkdwn",
- text: `${typeInfo.emoji} *Status Updated*\n\`${update.previousStatus}\` → \`${update.newStatus}\``,
+ text: `${emoji} *Issue Status Updated*\n${documentIdentifier}`,
},
},
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*From:*\n${update.previousStatus}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*To:*\n${update.newStatus}`,
+ },
+ ],
+ },
];
if (update.reason) {
@@ -285,7 +298,9 @@ export function formatStatusUpdate(
elements: [
{
type: "mrkdwn",
- text: `Updated by <@${update.updatedBy}> • #${documentIdentifier}`,
+ text: `Updated by <@${update.updatedBy}> at <!date^${Math.floor(
+ Date.now() / 1000
+ )}^{date_short_pretty} {time}|${new Date().toISOString()}>`,
},
],
});
@@ -307,13 +322,7 @@ export function formatTaskUpdate(
approval: "Approval",
}[update.taskType];
- const statusEmoji =
- {
- Pending: "⏳",
- "In Progress": "🔄",
- Completed: "✅",
- Skipped: "⏭️",
- }[update.status] || "📋";
+ const statusEmoji = getTaskStatusEmoji(update.status);
const blocks: KnownBlock[] = [
{
@@ -327,10 +336,10 @@ export function formatTaskUpdate(
const fields: any[] = [];
- if (update.assignedTo) {
+ if (update.assignee) {
fields.push({
type: "mrkdwn",
- text: `*Assigned to:*\n<@${update.assignedTo}>`,
+ text: `*Assigned to:*\n<@${update.assignee}>`,
});
}
@@ -385,31 +394,47 @@ export function formatAssignmentUpdate(
documentIdentifier: string,
update: IssueAssignmentUpdate
): 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}>`
- }`,
+ text: `🎯 *Assignment Updated*\n${documentIdentifier}`,
},
},
- {
- type: "context",
- elements: [
- {
- type: "mrkdwn",
- text: `Updated by <@${update.updatedBy}> • #${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;
}
@@ -446,6 +471,50 @@ export function formatSimpleNotification(
return blocks;
}
+/**
+ * Get status emoji based on status string
+ */
+export 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 task status emoji based on status string
+ */
+export 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 for NCR-specific functions
export function formatNonConformanceCreated(
data: NonConformanceData,
diff --git a/packages/integrations/src/slack/lib/service.ts b/packages/integrations/src/slack/lib/service.ts
index 321aed0a81..c34f0684dd 100644
--- a/packages/integrations/src/slack/lib/service.ts
+++ b/packages/integrations/src/slack/lib/service.ts
@@ -466,14 +466,30 @@ export async function syncDocumentToSlack(
break;
case "assignment-update":
+ let previousAssignee: string | undefined;
+ let newAssignee: string | undefined;
+ if (data.payload.previousAssignee) {
+ previousAssignee = await getSlackUserIdByCarbonId(
+ client,
+ slackAuth.slackToken,
+ data.payload.previousAssignee || ""
+ );
+ }
+ if (data.payload.newAssignee) {
+ newAssignee = await getSlackUserIdByCarbonId(
+ client,
+ slackAuth.slackToken,
+ data.payload.newAssignee || ""
+ );
+ }
result = await tasks.trigger<typeof slackDocumentAssignmentUpdate>(
"slack-document-assignment-update",
{
documentType: data.documentType,
documentId: data.documentId,
companyId: data.companyId,
- previousAssignee: data.payload.previousAssignee,
- newAssignee: data.payload.newAssignee,
+ previousAssignee,
+ newAssignee,
updatedBy: slackAuth.slackUserId || data.payload.updatedBy,
}
);
@@ -635,15 +651,40 @@ export async function syncIssueTaskToSlack(
companyId: string;
completedAt?: string;
id: string;
- nonConformanceId: string;
status: string;
- taskType: "investigation" | "action" | "approval";
+ taskType: "investigation" | "action" | "review";
userId: string;
}
) {
+ let nonConformanceId = "";
+ if (data.taskType === "investigation") {
+ const nonConformance = await client
+ .from("nonConformanceInvestigationTask")
+ .select("nonConformanceId")
+ .eq("id", data.id)
+ .single();
+ nonConformanceId = nonConformance.data?.nonConformanceId || "";
+ }
+ if (data.taskType === "action") {
+ const nonConformance = await client
+ .from("nonConformanceActionTask")
+ .select("nonConformanceId")
+ .eq("id", data.id)
+ .single();
+ nonConformanceId = nonConformance.data?.nonConformanceId || "";
+ }
+ if (data.taskType === "review") {
+ const nonConformance = await client
+ .from("nonConformanceApprovalTask")
+ .select("nonConformanceId")
+ .eq("id", data.id)
+ .single();
+ nonConformanceId = nonConformance.data?.nonConformanceId || "";
+ }
+
return syncDocumentToSlack(client, {
documentType: "nonConformance",
- documentId: data.nonConformanceId,
+ documentId: nonConformanceId,
companyId: data.companyId,
userId: data.userId,
type: "task-update",
diff --git a/packages/jobs/package.json b/packages/jobs/package.json
index a756d07329..7753959d81 100644
--- a/packages/jobs/package.json
+++ b/packages/jobs/package.json
@@ -14,6 +14,7 @@
"@carbon/database": "*",
"@carbon/documents": "*",
"@carbon/lib": "*",
+ "@carbon/integrations": "*",
"@carbon/notifications": "*",
"@internationalized/date": "^3.5.2",
"@novu/node": "^2.0.1",
diff --git a/packages/jobs/trigger/notify.ts b/packages/jobs/trigger/notify.ts
index 4b1b6df072..51ea83e5bf 100644
--- a/packages/jobs/trigger/notify.ts
+++ b/packages/jobs/trigger/notify.ts
@@ -3,6 +3,8 @@ import {
NOVU_SECRET_KEY,
VERCEL_URL,
} from "@carbon/auth";
+
+import { notifyTaskAssigned } from "@carbon/integrations/notifications";
import {
getSubscriberId,
NotificationEvent,
@@ -17,6 +19,14 @@ import { task } from "@trigger.dev/sdk/v3";
const novu = new Novu(NOVU_SECRET_KEY!);
const isLocal = VERCEL_URL === undefined || VERCEL_URL.includes("localhost");
+// Helper function to get company integrations
+async function getCompanyIntegrations(client: any, companyId: string) {
+ return client
+ .from("companyIntegration")
+ .select("*")
+ .eq("companyId", companyId);
+}
+
export const notifyTask = task({
id: "notify",
run: async (payload: {
@@ -236,6 +246,50 @@ export const notifyTask = task({
);
}
+ // Send integration notifications for non-conformance assignment events (e.g., Slack)
+ if (
+ payload.event === NotificationEvent.NonConformanceAssignment &&
+ payload.recipient.type === "user"
+ ) {
+ console.log(
+ "Processing non-conformance assignment notification for integrations",
+ {
+ event: payload.event,
+ companyId: payload.companyId,
+ documentId: payload.documentId,
+ recipientUserId: payload.recipient.userId,
+ from: payload.from,
+ }
+ );
+
+ try {
+ const integrationsResult = await getCompanyIntegrations(
+ client,
+ payload.companyId
+ );
+
+ if (integrationsResult.data && integrationsResult.data.length > 0) {
+ await notifyTaskAssigned({ client }, integrationsResult.data, {
+ companyId: payload.companyId,
+ userId: payload.from || "system",
+ carbonUrl: `${VERCEL_URL}/x/issue/${payload.documentId}`,
+ task: {
+ id: payload.documentId,
+ table: "nonConformance",
+ assignee: payload.recipient.userId,
+ title: description,
+ },
+ });
+ }
+ } catch (error) {
+ console.error(
+ "Failed to send integration assignment notification:",
+ error
+ );
+ // Continue without blocking the main operation
+ }
+ }
+
if (payload.recipient.type === "user") {
try {
await trigger(novu, {
diff --git a/packages/jobs/trigger/slack-document-sync.ts b/packages/jobs/trigger/slack-document-sync.ts
index 6238231c11..e7db487ee9 100644
--- a/packages/jobs/trigger/slack-document-sync.ts
+++ b/packages/jobs/trigger/slack-document-sync.ts
@@ -1,64 +1,21 @@
import { getCarbonServiceRole, VERCEL_URL } from "@carbon/auth";
import type { Database } from "@carbon/database";
+import {
+ type DocumentData,
+ type DocumentType,
+ type IssueAssignmentUpdate,
+ type IssueStatusUpdate,
+ type IssueTaskUpdate,
+ type NonConformanceData,
+ formatAssignmentUpdate,
+ formatDocumentCreated,
+ formatStatusUpdate,
+ formatTaskUpdate,
+} from "@carbon/integrations/slack/messages";
import { WebClient } from "@slack/web-api";
import type { SupabaseClient } from "@supabase/supabase-js";
import { task } from "@trigger.dev/sdk/v3";
-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;
- assignee?: string | null;
- readableId?: string;
- completedBy?: string;
- completedAt?: string;
- notes?: string;
-}
-
-interface AssignmentUpdate {
- previousAssignee?: string;
- newAssignee: string;
- updatedBy: string;
-}
-
export const slackDocumentCreated = task({
id: "slack-document-created",
run: async (payload: {
@@ -163,14 +120,18 @@ export const slackDocumentStatusUpdate = task({
const slackToken = (integration.metadata as any).access_token as string;
- const documentIdentifier = await getDocumentReadableId(
+ const documentData = await getDocumentData(
serviceRole,
documentType,
documentId,
companyId
);
- const statusUpdate: StatusUpdate = {
+ if (!documentData) {
+ throw new Error(`${documentType} ${documentId} not found`);
+ }
+
+ const statusUpdate: IssueStatusUpdate = {
previousStatus,
newStatus,
updatedBy,
@@ -183,7 +144,7 @@ export const slackDocumentStatusUpdate = task({
threadTs: thread.threadTs,
blocks: formatStatusUpdate(
documentType,
- documentIdentifier,
+ documentData.readableId,
statusUpdate
),
});
@@ -250,14 +211,18 @@ export const slackDocumentTaskUpdate = task({
const slackToken = (integration.metadata as any).access_token as string;
- const documentIdentifier = await getDocumentReadableId(
+ const documentData = await getDocumentData(
serviceRole,
documentType,
documentId,
companyId
);
- const taskUpdate: TaskUpdate = {
+ if (!documentData) {
+ throw new Error(`${documentType} ${documentId} not found`);
+ }
+
+ const taskUpdate: IssueTaskUpdate = {
taskType,
taskName,
status,
@@ -269,7 +234,11 @@ export const slackDocumentTaskUpdate = task({
token: slackToken,
channelId: thread.channelId,
threadTs: thread.threadTs,
- blocks: formatTaskUpdate(documentType, documentIdentifier, taskUpdate),
+ blocks: formatTaskUpdate(
+ documentType,
+ documentData.readableId,
+ taskUpdate
+ ),
});
return { success: true };
@@ -330,14 +299,18 @@ export const slackDocumentAssignmentUpdate = task({
const slackToken = (integration.metadata as any).access_token as string;
- const documentIdentifier = await getDocumentReadableId(
+ const documentData = await getDocumentData(
serviceRole,
documentType,
documentId,
companyId
);
- const assignmentUpdate: AssignmentUpdate = {
+ if (!documentData) {
+ throw new Error(`${documentType} ${documentId} not found`);
+ }
+
+ const assignmentUpdate: IssueAssignmentUpdate = {
previousAssignee,
newAssignee,
updatedBy,
@@ -349,7 +322,7 @@ export const slackDocumentAssignmentUpdate = task({
threadTs: thread.threadTs,
blocks: formatAssignmentUpdate(
documentType,
- documentIdentifier,
+ documentData.readableId,
assignmentUpdate
),
});
@@ -385,6 +358,7 @@ async function getDocumentData(
return {
documentType: "nonConformance",
id: data.id,
+ readableId: data.nonConformanceId,
nonConformanceId: data.nonConformanceId,
title: data.name,
description: data.description,
@@ -403,27 +377,6 @@ async function getDocumentData(
}
}
-async function getDocumentReadableId(
- serviceRole: SupabaseClient<Database>,
- 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;
- }
-
- default:
- return documentId;
- }
-}
-
async function postToSlackThread(params: {
token: string;
channelId: string;
@@ -443,335 +396,6 @@ async function postToSlackThread(params: {
});
}
-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;
-}
-
-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} *Issue 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;
-}
-
-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.assignee) {
- fields.push({
- type: "mrkdwn",
- text: `*Assigned To:*\n<@${update.assignee}>`,
- });
- }
-
- 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;
-}
-
-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;
-}
-
-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 "📌";
-}
-
-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 "📝";
-}
-
export const slackNcrCreated = slackDocumentCreated;
export const slackNcrStatusUpdate = slackDocumentStatusUpdate;
export const slackNcrTaskUpdate = slackDocumentTaskUpdate;