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.

fix: realtime subscriptions

Brad Barbin35b549e87f56
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index 569d8a47eb..45ed8dc9a0 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -42,10 +42,17 @@ import {
Tr,
useDisclosure,
useInterval,
+ useMount,
VStack,
type JSONContent,
} from "@carbon/react";
-import { Await, useFetcher, useNavigate, useParams } from "@remix-run/react";
+import {
+ Await,
+ useFetcher,
+ useNavigate,
+ useParams,
+ useRevalidator,
+} from "@remix-run/react";
import type { ComponentProps, ReactNode } from "react";
import {
Suspense,
@@ -61,7 +68,7 @@ import {
FilePreview,
OperationStatusIcon,
} from "~/components";
-import { useMode, useRealtime, useUser } from "~/hooks";
+import { useMode, useUser } from "~/hooks";
import type { productionEventType } from "~/services/models";
import {
finishValidator,
@@ -146,22 +153,30 @@ export const JobOperation = ({
workCenter,
}: JobOperationProps) => {
const navigate = useNavigate();
- useRealtime("job", `id=eq.${job.id}`);
+
+ const { downloadFile, getFilePath } = useFiles(job);
+
const {
+ active,
activeTab,
+ completeModal,
eventType,
+ finishModal,
+ hasActiveEvents,
isOverdue,
- operation,
issueModal,
- finishModal,
- scrapModal,
+ laborProductionEvent,
+ machineProductionEvent,
+ operation,
+ progress,
reworkModal,
- completeModal,
+ scrapModal,
selectedMaterial,
- setSelectedMaterial,
setActiveTab,
setEventType,
- } = useOperationState(originalOperation, job);
+ setSelectedMaterial,
+ setupProductionEvent,
+ } = useOperation(originalOperation, events);
const controlsHeight = useMemo(() => {
let operations = 1;
@@ -175,17 +190,6 @@ export const JobOperation = ({
operation.setupDuration,
]);
- const { downloadFile, getFilePath } = useFiles(job);
-
- const {
- active,
- hasActiveEvents,
- setupProductionEvent,
- laborProductionEvent,
- machineProductionEvent,
- progress,
- } = useActiveEvents(originalOperation, events);
-
const mode = useMode();
const { operationId } = useParams();
@@ -885,21 +889,38 @@ export const JobOperation = ({
);
};
-function useActiveEvents(
+function useOperation(
operation: OperationWithDetails,
events: ProductionEvent[]
-): {
- active: { setup: boolean; labor: boolean; machine: boolean };
- hasActiveEvents: boolean;
- setupProductionEvent: ProductionEvent | undefined;
- laborProductionEvent: ProductionEvent | undefined;
- machineProductionEvent: ProductionEvent | undefined;
- progress: { setup: number; labor: number; machine: number };
-} {
+) {
const { carbon, accessToken } = useCarbon();
const user = useUser();
+ const revalidator = useRevalidator();
const channelRef = useRef<RealtimeChannel | null>(null);
+ const scrapModal = useDisclosure();
+ const reworkModal = useDisclosure();
+ const completeModal = useDisclosure();
+ const finishModal = useDisclosure();
+ const issueModal = useDisclosure();
+
+ const [selectedMaterial, setSelectedMaterial] = useState<JobMaterial | null>(
+ null
+ );
+
+ const [activeTab, setActiveTab] = useState("details");
+ const [eventType, setEventType] = useState(() => {
+ if (operation.setupDuration > 0) {
+ return "Setup";
+ }
+ if (operation.laborDuration > 0) {
+ return "Labor";
+ }
+ return "Machine";
+ });
+
+ const [operationState, setOperationState] = useState(operation);
+
const [eventState, setEventState] = useState<ProductionEvent[]>(events);
useEffect(() => {
@@ -907,12 +928,28 @@ function useActiveEvents(
}, [events]);
useEffect(() => {
- if (!carbon || !accessToken) return;
- carbon.realtime.setAuth(accessToken);
+ setOperationState(operation);
+ }, [operation]);
- if (!channelRef.current) {
+ useMount(() => {
+ if (!channelRef.current && carbon && accessToken) {
+ carbon.realtime.setAuth(accessToken);
channelRef.current = carbon
- .channel("realtime:core")
+ .channel(`job-operations:${operation.id}`)
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "job",
+ filter: `id=eq.${operation.jobId}`,
+ },
+ (payload) => {
+ if (payload.eventType === "UPDATE") {
+ revalidator.revalidate();
+ }
+ }
+ )
.on(
"postgres_changes",
{
@@ -932,10 +969,14 @@ function useActiveEvents(
break;
case "UPDATE":
const { new: updated } = payload;
+
setEventState((prevEvents) =>
prevEvents.map((event) =>
event.id === updated.id
- ? (updated as ProductionEvent)
+ ? ({
+ ...event,
+ ...updated,
+ } as ProductionEvent)
: event
)
);
@@ -951,15 +992,45 @@ function useActiveEvents(
}
}
)
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "jobOperation",
+ filter: `id=eq.${operation.id}`,
+ },
+ (payload) => {
+ if (payload.eventType === "UPDATE") {
+ const updated = payload.new;
+ setOperationState((prev) => ({
+ ...prev,
+ ...updated,
+ operationStatus: updated.status ?? prev.operationStatus,
+ }));
+ } else if (payload.eventType === "DELETE") {
+ toast.error("This operation has been deleted");
+ window.location.href = path.to.operations;
+ }
+ }
+ )
.subscribe();
}
return () => {
- if (channelRef.current) carbon?.removeChannel(channelRef.current);
+ if (channelRef.current) {
+ channelRef.current.unsubscribe();
+ carbon?.removeChannel(channelRef.current);
+ channelRef.current = null;
+ }
};
+ });
+ useEffect(() => {
+ if (carbon && accessToken && channelRef.current)
+ carbon.realtime.setAuth(accessToken);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [accessToken, operation.id]);
+ }, [accessToken]);
const getProgress = useCallback(() => {
const timeNow = now(getLocalTimeZone());
@@ -1029,6 +1100,21 @@ function useActiveEvents(
progress.setup > 0 || progress.labor > 0 || progress.machine > 0,
...activeEvents,
progress,
+ operation: operationState,
+ activeTab,
+ eventType,
+ scrapModal,
+ reworkModal,
+ completeModal,
+ finishModal,
+ issueModal,
+ isOverdue: operation.jobDueDate
+ ? new Date(operation.jobDueDate) < new Date()
+ : false,
+ selectedMaterial,
+ setSelectedMaterial,
+ setActiveTab,
+ setEventType,
};
}
@@ -1086,102 +1172,6 @@ function useFiles(job: Job) {
};
}
-function useOperationState(operation: OperationWithDetails, job: Job) {
- const scrapModal = useDisclosure();
- const reworkModal = useDisclosure();
- const completeModal = useDisclosure();
- const finishModal = useDisclosure();
- const issueModal = useDisclosure();
-
- const [selectedMaterial, setSelectedMaterial] = useState<JobMaterial | null>(
- null
- );
-
- const [activeTab, setActiveTab] = useState("details");
- const [eventType, setEventType] = useState(() => {
- if (operation.setupDuration > 0) {
- return "Setup";
- }
- if (operation.laborDuration > 0) {
- return "Labor";
- }
- return "Machine";
- });
-
- const { carbon, accessToken } = useCarbon();
- const [operationState, setOperationState] = useState(operation);
- const channelRef = useRef<RealtimeChannel | null>(null);
-
- useEffect(() => {
- setOperationState(operation);
- }, [operation]);
-
- useEffect(() => {
- if (!carbon || !accessToken) return;
-
- carbon.realtime.setAuth(accessToken);
-
- if (!channelRef.current) {
- channelRef.current = carbon
- .channel("realtime:core")
- .on(
- "postgres_changes",
- {
- event: "*",
- schema: "public",
- table: "jobOperation",
- filter: `id=eq.${operation.id}`,
- },
- (payload) => {
- if (payload.eventType === "UPDATE") {
- const { new: updated } = payload;
- if (updated.id === operation.id) {
- setOperationState((prevState) => ({
- ...prevState,
- quantityComplete: updated.quantityComplete,
- quantityScrapped: updated.quantityScrapped,
- quantityReworked: updated.quantityReworked,
- }));
- }
- } else if (payload.eventType === "DELETE") {
- if (payload.old.id === operation.id) {
- alert("This operation has been deleted.");
- window.location.href = path.to.operations;
- }
- }
- }
- )
- .subscribe();
- }
-
- return () => {
- if (channelRef.current) {
- carbon?.removeChannel(channelRef.current);
- channelRef.current = null;
- }
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [accessToken, operation.id]);
-
- return {
- operation: operationState,
- activeTab,
- eventType,
- scrapModal,
- reworkModal,
- completeModal,
- finishModal,
- issueModal,
- isOverdue: operation.jobDueDate
- ? new Date(operation.jobDueDate) < new Date()
- : false,
- selectedMaterial,
- setSelectedMaterial,
- setActiveTab,
- setEventType,
- };
-}
-
function TableSkeleton() {
return (
<Table>
diff --git a/apps/mes/app/routes/x+/operation.$operationId.tsx b/apps/mes/app/routes/x+/operation.$operationId.tsx
index 9604437fce..86541ad96e 100644
--- a/apps/mes/app/routes/x+/operation.$operationId.tsx
+++ b/apps/mes/app/routes/x+/operation.$operationId.tsx
@@ -105,7 +105,6 @@ export default function OperationRoute() {
return (
<JobOperation
- key={operationId}
events={events}
files={files}
materials={materials}
diff --git a/apps/mes/app/services/location.server.ts b/apps/mes/app/services/location.server.ts
index 8e2da126b9..db473cae9f 100644
--- a/apps/mes/app/services/location.server.ts
+++ b/apps/mes/app/services/location.server.ts
@@ -6,7 +6,8 @@ import * as cookie from "cookie";
export function getCompanySettings(request: Request, companyId: string) {
const cookieHeader = request.headers.get("cookie");
const parsed = cookieHeader ? cookie.parse(cookieHeader)[companyId] : null;
- if (parsed) {
+ if (parsed && !parsed.includes(":")) {
+ // temporary check for backwards compatibility
return { location: parsed };
}
return {