Skip to content

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

feat: add notifications to job operation notes

Brad Barbin5d30ae204590
diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
index ad3caf7a1a..c5f0264fa2 100644
--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx
@@ -23,6 +23,7 @@ import {
LuHammer,
LuInbox,
LuMailCheck,
+ LuMessageSquare,
LuShoppingCart,
} from "react-icons/lu";
import {
@@ -138,7 +139,19 @@ function GenericNotification({
{...props}
/>
);
+ case NotificationEvent.JobOperationMessage:
+ const [jobId, operationId, makeMethodId, materialId] = id.split(":");
+ const link = materialId
+ ? path.to.jobMakeMethod(jobId, makeMethodId, materialId)
+ : path.to.jobMethod(jobId, makeMethodId);
+ return (
+ <Notification
+ icon={<LuMessageSquare />}
+ to={`${link}?selectedOperation=${operationId}`}
+ {...props}
+ />
+ );
case NotificationEvent.QuoteExpired:
return (
<Notification
diff --git a/apps/erp/app/novu/workflows.ts b/apps/erp/app/novu/workflows.ts
index 0f316519df..2d460032ef 100644
--- a/apps/erp/app/novu/workflows.ts
+++ b/apps/erp/app/novu/workflows.ts
@@ -19,6 +19,7 @@ const payloadSchema = z.object({
NotificationEvent.SalesOrderAssignment,
NotificationEvent.SalesRfqAssignment,
NotificationEvent.SupplierQuoteAssignment,
+ NotificationEvent.JobOperationMessage,
]),
from: z.string().optional(),
});
@@ -59,3 +60,14 @@ export const expirationWorkflow = workflow(
},
{ payloadSchema }
);
+
+export const messageWorkflow = workflow(
+ NotificationWorkflow.Message,
+ async ({ payload, step }) => {
+ await step.inApp(NotificationType.MessageInApp, () => ({
+ body: "New Message",
+ payload,
+ }));
+ },
+ { payloadSchema }
+);
diff --git a/apps/erp/app/routes/api+/messaging.notify.ts b/apps/erp/app/routes/api+/messaging.notify.ts
new file mode 100644
index 0000000000..274e6aeaf3
--- /dev/null
+++ b/apps/erp/app/routes/api+/messaging.notify.ts
@@ -0,0 +1,92 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { NotificationEvent } from "@carbon/notifications";
+import { tasks } from "@trigger.dev/sdk/v3";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { z } from "zod";
+import type { notifyTask } from "~/trigger/notify";
+
+export const config = {
+ runtime: "nodejs",
+};
+
+export const messagingNotifySchema = z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("jobOperationNote"),
+ source: z.enum(["erp", "mes"]).optional(),
+ operationId: z.string(),
+ }),
+]);
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {});
+
+ const payload = messagingNotifySchema.safeParse(await request.json());
+
+ if (payload.success) {
+ switch (payload.data.type) {
+ case "jobOperationNote":
+ const { source, operationId } = payload.data;
+
+ if (source === "mes") {
+ const data = await client
+ .from("jobOperation")
+ .select("*, job(id, assignee), jobMakeMethod(id, parentMaterialId)")
+ .eq("id", operationId)
+ .single();
+ const assignee = data.data?.job?.assignee;
+ const jobId = data.data?.job?.id;
+ const makeMethodId = data.data?.jobMakeMethod?.id;
+ const materialId = data.data?.jobMakeMethod?.parentMaterialId;
+
+ console.log({
+ assignee,
+ jobId,
+ makeMethodId,
+ materialId,
+ });
+ if (assignee) {
+ const notificationEvent = getNotificationEvent("jobOperationNote");
+ if (notificationEvent) {
+ await tasks.trigger<typeof notifyTask>("notify", {
+ companyId,
+ documentId: `${jobId}:${operationId}:${makeMethodId}:${
+ materialId ?? ""
+ }`,
+ event: notificationEvent,
+ recipient: {
+ type: "user",
+ userId: assignee,
+ },
+ from: userId,
+ });
+ }
+ }
+ }
+
+ break;
+ default:
+ return json(
+ { success: false },
+ await flash(request, error(null, "Invalid payload"))
+ );
+ }
+
+ return json({ success: true });
+ } else {
+ return json(
+ { success: false },
+ await flash(request, error(null, "Failed to notify user"))
+ );
+ }
+}
+
+function getNotificationEvent(table: string): NotificationEvent | null {
+ switch (table) {
+ case "jobOperationNote":
+ return NotificationEvent.JobOperationMessage;
+ default:
+ return null;
+ }
+}
diff --git a/apps/erp/app/routes/api+/novu.ts b/apps/erp/app/routes/api+/novu.ts
index cd110f5e0d..78dd91ecab 100644
--- a/apps/erp/app/routes/api+/novu.ts
+++ b/apps/erp/app/routes/api+/novu.ts
@@ -3,6 +3,7 @@ import {
assignmentWorkflow,
digitalQuoteResponseWorkflow,
expirationWorkflow,
+ messageWorkflow,
} from "~/novu/workflows";
const handler = serve({
@@ -10,6 +11,7 @@ const handler = serve({
assignmentWorkflow,
digitalQuoteResponseWorkflow,
expirationWorkflow,
+ messageWorkflow,
],
});
diff --git a/apps/erp/app/trigger/notify.ts b/apps/erp/app/trigger/notify.ts
index 683459d4cb..2a969df5e6 100644
--- a/apps/erp/app/trigger/notify.ts
+++ b/apps/erp/app/trigger/notify.ts
@@ -53,6 +53,8 @@ export const notifyTask = task({
return NotificationWorkflow.Assignment;
case NotificationEvent.DigitalQuoteResponse:
return NotificationWorkflow.DigitalQuoteResponse;
+ case NotificationEvent.JobOperationMessage:
+ return NotificationWorkflow.Message;
default:
return null;
}
@@ -114,6 +116,21 @@ export const notifyTask = task({
return `Job ${job?.data?.jobId} assigned to you`;
+ case NotificationEvent.JobOperationMessage:
+ const [, operationId] = documentId.split(":");
+ const jobOperation = await client
+ .from("jobOperation")
+ .select("*, job(id, jobId)")
+ .eq("id", operationId)
+ .single();
+
+ if (jobOperation.error) {
+ console.error("Failed to get jobOperation", jobOperation.error);
+ throw jobOperation.error;
+ }
+
+ return `New message on ${jobOperation?.data?.job?.jobId} operation: ${jobOperation?.data?.description}`;
+
case NotificationEvent.DigitalQuoteResponse:
const digitalQuote = await client
.from("quote")
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index c4ecd72838..ece3a4beef 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -46,6 +46,7 @@ import {
TooltipProvider,
TooltipTrigger,
Tr,
+ useDebounce,
useDisclosure,
useInterval,
useMount,
@@ -1000,6 +1001,7 @@ function Notes({ operation }: { operation: OperationWithDetails }) {
const user = useUser();
const [employees] = usePeople();
const [notes, setNotes] = useState<Note[]>([]);
+
const [isLoading, setIsLoading] = useState(false);
const { carbon, accessToken } = useCarbon();
@@ -1080,6 +1082,32 @@ function Notes({ operation }: { operation: OperationWithDetails }) {
const [note, setNote] = useState("");
+ const notify = useDebounce(
+ async () => {
+ if (!carbon) return;
+
+ const response = await fetch(path.to.messagingNotify, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Cookie: document.cookie, // Include cookie header for cross-origin requests
+ },
+ body: JSON.stringify({
+ type: "jobOperationNote",
+ source: "mes",
+ operationId: operation.id,
+ }),
+ credentials: "include", // Keep credentials: include for cookies
+ });
+
+ if (!response.ok) {
+ console.error("Failed to notify user");
+ }
+ },
+ 5000,
+ true
+ );
+
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
@@ -1099,7 +1127,10 @@ function Notes({ operation }: { operation: OperationWithDetails }) {
setNote("");
});
- await carbon?.from("jobOperationNote").insert(newNote);
+ await Promise.all([
+ carbon?.from("jobOperationNote").insert(newNote),
+ notify(),
+ ]);
};
return (
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index 563c579f73..f13890da57 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -28,6 +28,7 @@ export const path = {
forgotPassword: `${ERP_URL}/forgot-password`,
healthcheck: "/healthcheck",
issue: `${x}/issue`,
+ messagingNotify: `${ERP_URL}/api/messaging/notify`,
operation: (id: string) => generatePath(`${x}/operation/${id}`),
operations: `${x}/operations?saved=1`,
location: `${x}/location`,
diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.ts
index d4df113db3..3b20f3ff58 100644
--- a/packages/notifications/src/index.ts
+++ b/packages/notifications/src/index.ts
@@ -6,11 +6,13 @@ export enum NotificationWorkflow {
Assignment = "assignment",
DigitalQuoteResponse = "digital-quote-response",
Expiration = "expiration",
+ Message = "message",
}
export enum NotificationEvent {
DigitalQuoteResponse = "digital-quote-response",
JobAssignment = "job-assignment",
+ JobOperationMessage = "job-operation-message",
PurchaseInvoiceAssignment = "purchase-invoice-assignment",
PurchaseOrderAssignment = "purchase-order-assignment",
QuoteAssignment = "quote-assignment",
@@ -24,6 +26,7 @@ export enum NotificationType {
AssignmentInApp = "assignment-in-app",
DigitalQuoteResponseInApp = "digital-quote-response-in-app",
ExpirationInApp = "expiration-in-app",
+ MessageInApp = "message-in-app",
}
export type TriggerUser = {