Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: notify all users who have posted messages about new messages on an operation
Brad Barbina15dd0320ef5
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsxindex 3d4474cd47..f0a862a768 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx@@ -1878,6 +1878,30 @@ function Notes({ jobOperationId }: { jobOperationId: string }) {const [note, setNote] = useState("");+ const notify = useDebounce(+ async () => {+ if (!carbon) return;++ const response = await fetch(path.to.api.messagingNotify, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ type: "jobOperationNote",+ operationId: jobOperationId,+ }),+ credentials: "include", // This is sufficient for CORS with cookies+ });++ if (!response.ok) {+ console.error("Failed to notify user");+ }+ },+ 5000,+ true+ );+const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {e.preventDefault();@@ -1897,7 +1921,10 @@ function Notes({ jobOperationId }: { jobOperationId: string }) {setNote("");});- await carbon?.from("jobOperationNote").insert(newNote);+ await Promise.all([+ carbon?.from("jobOperationNote").insert(newNote),+ notify(),+ ]);};return (diff --git a/apps/erp/app/routes/api+/messaging.notify.ts b/apps/erp/app/routes/api+/messaging.notify.tsindex da63eefc4f..0f84645557 100644--- a/apps/erp/app/routes/api+/messaging.notify.ts+++ b/apps/erp/app/routes/api+/messaging.notify.ts@@ -14,7 +14,6 @@ export const config = {export const messagingNotifySchema = z.discriminatedUnion("type", [z.object({type: z.literal("jobOperationNote"),- source: z.enum(["erp", "mes"]).optional(),operationId: z.string(),}),]);@@ -27,35 +26,52 @@ export async function action({ request }: ActionFunctionArgs) {if (payload.success) {switch (payload.data.type) {case "jobOperationNote":- const { source, operationId } = payload.data;+ const { operationId } = payload.data;- if (source === "mes") {- const data = await client+ const [job, previousMessages] = await Promise.all([+ 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;+ .single(),+ client+ .from("jobOperationNote")+ .select("*")+ .eq("jobOperationId", operationId),+ ]);- 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,- });- }+ const assignee = job.data?.job?.assignee;+ const jobId = job.data?.job?.id;+ const makeMethodId = job.data?.jobMakeMethod?.id;+ const materialId = job.data?.jobMakeMethod?.parentMaterialId;++ const usersToNotify = [+ ...new Set([+ ...(previousMessages.data?.map((m) => m.createdBy) ?? []).filter(+ (id) => id !== userId+ ),+ ]),+ ];++ if (assignee && assignee !== userId) {+ usersToNotify.push(assignee);+ }++ if (usersToNotify.length > 0) {+ const notificationEvent = getNotificationEvent("jobOperationNote");+ if (notificationEvent) {+ await tasks.trigger<typeof notifyTask>("notify", {+ companyId,+ documentId: `${jobId}:${operationId}:${makeMethodId}:${+ materialId ?? ""+ }`,+ event: notificationEvent,+ recipient: {+ type: "users",+ userIds: usersToNotify,+ },+ from: userId,+ });}}diff --git a/apps/erp/app/trigger/notify.ts b/apps/erp/app/trigger/notify.tsindex 2a969df5e6..fa9b27b6f0 100644--- a/apps/erp/app/trigger/notify.ts+++ b/apps/erp/app/trigger/notify.ts@@ -31,6 +31,10 @@ export const notifyTask = task({| {type: "group";groupIds: string[];+ }+ | {+ type: "users";+ userIds: string[];};from?: string;}) => {@@ -194,13 +198,20 @@ export const notifyTask = task({console.error("Error triggering notifications");console.error(error);}- } else if (payload.recipient.type === "group") {+ } else if (["group", "users"].includes(payload.recipient.type)) {console.log(- `triggering notification for group ${payload.recipient.groupIds}`+ `triggering notification for group ${payload.recipient.type}`);- const userIds = await client.rpc("users_for_groups", {- groups: payload.recipient.groupIds,- });++ const userIds =+ payload.recipient.type === "group"+ ? await client.rpc("users_for_groups", {+ groups: payload.recipient.groupIds,+ })+ : {+ data: payload.recipient.userIds,+ error: null,+ };if (userIds.error) {console.error("Failed to get userIds", userIds.error);@@ -213,7 +224,7 @@ export const notifyTask = task({userIds.data.length === 0) {console.error(- `No userIds found for group ${payload.recipient.groupIds}`+ `No userIds found for payload ${JSON.stringify(payload.recipient)}`);return;}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 0b6945c160..58737c0efa 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -40,6 +40,7 @@ export const path = {itemPostingGroups: `${api}/items/groups`,materialForms: `${api}/items/forms`,materialSubstances: `${api}/items/substances`,+ messagingNotify: `${api}/messaging/notify`,modelUpload: `${api}/model/upload`,purchasingKpi: (key: string) =>generatePath(`${api}/purchasing/kpi/${key}`),diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsxindex 9013ca6629..f70493cf88 100644--- a/apps/mes/app/components/JobOperation.tsx+++ b/apps/mes/app/components/JobOperation.tsx@@ -1093,7 +1093,6 @@ function Notes({ operation }: { operation: OperationWithDetails }) {},body: JSON.stringify({type: "jobOperationNote",- source: "mes",operationId: operation.id,}),credentials: "include", // This is sufficient for CORS with cookies