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.

Realtime subscription bugs (#388)

Sid589e1f2b97a3
diff --git a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
index d030d8172e..655d130e27 100644
--- a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
+++ b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
@@ -1,7 +1,7 @@
import { VStack, cn, useDisclosure } from "@carbon/react";
import { Link, useMatches } from "@remix-run/react";
-import { forwardRef, type AnchorHTMLAttributes } from "react";
-import { z } from 'zod/v3';
+import { forwardRef, type AnchorHTMLAttributes, memo } from "react";
+import { z } from "zod/v3";
import { useModules, useOptimisticLocation } from "~/hooks";
import type { Authenticated, NavItem } from "~/types";
@@ -129,7 +129,7 @@ const NavigationIconLink = forwardRef<
});
NavigationIconLink.displayName = "NavigationIconLink";
-export default PrimaryNavigation;
+export default memo(PrimaryNavigation);
export function getModule(link: string) {
return link.split("/")?.[2];
diff --git a/apps/erp/app/components/Layout/Topbar/Search.tsx b/apps/erp/app/components/Layout/Topbar/Search.tsx
index 91a41c7688..40b6dabecf 100644
--- a/apps/erp/app/components/Layout/Topbar/Search.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Search.tsx
@@ -22,7 +22,7 @@ import {
import { useNavigate } from "@remix-run/react";
import idb from "localforage";
import { nanoid } from "nanoid";
-import { useCallback, useEffect, useState } from "react";
+import { memo, useCallback, useEffect, useState } from "react";
import {
LuFileCheck,
LuHardHat,
@@ -397,4 +397,4 @@ function useGroupedSubmodules() {
return shortcuts;
}
-export default SearchButton;
+export default memo(SearchButton);
diff --git a/apps/erp/app/components/RealtimeDataProvider.tsx b/apps/erp/app/components/RealtimeDataProvider.tsx
index c6981e23fe..73c3a91ef0 100644
--- a/apps/erp/app/components/RealtimeDataProvider.tsx
+++ b/apps/erp/app/components/RealtimeDataProvider.tsx
@@ -2,8 +2,8 @@
import { useCarbon } from "@carbon/auth";
import { fetchAllFromTable } from "@carbon/database";
-import type { RealtimeChannel } from "@supabase/supabase-js";
-import { useEffect, useRef } from "react";
+import { useRealtimeChannel } from "@carbon/react";
+import { useEffect } from "react";
import { useUser } from "~/hooks";
import { useCustomers, useItems, usePeople, useSuppliers } from "~/stores";
import type { Item } from "~/stores/items";
@@ -13,7 +13,7 @@ let hydratedFromIdb = false;
let hydratedFromServer = false;
const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
- const { carbon, accessToken, realtimeAuthSet } = useCarbon();
+ const { carbon, accessToken } = useCarbon();
const {
company: { id: companyId },
} = useUser();
@@ -121,20 +121,18 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
idb.setItem("people", people.data);
};
-
useEffect(() => {
if (!companyId) return;
hydrate();
-
-
+
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [companyId]);
- const channelRef = useRef<RealtimeChannel | null>(null);
-
- useEffect(() => {
- if (!channelRef.current && carbon && accessToken && realtimeAuthSet) {
- channelRef.current = carbon
- .channel("realtime:core")
+
+ useRealtimeChannel({
+ topic: `realtime:core`,
+ dependencies: [companyId],
+ setup(channel, carbon) {
+ return channel
.on(
"postgres_changes",
{
@@ -338,20 +336,9 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
setPeople(data);
}
}
- )
- .subscribe();
- }
-
- return () => {
- if (channelRef.current) {
- channelRef.current.unsubscribe();
- channelRef.current = null;
- }
- };
-// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [carbon, accessToken, companyId, realtimeAuthSet]);
-
-
+ );
+ },
+ });
return <>{children}</>;
};
diff --git a/apps/erp/app/hooks/index.ts b/apps/erp/app/hooks/index.ts
index bcd5887ba5..50259e985f 100644
--- a/apps/erp/app/hooks/index.ts
+++ b/apps/erp/app/hooks/index.ts
@@ -9,6 +9,7 @@ import { useCurrencyFormatter } from "./useCurrencyFormatter";
import { useModules } from "./useModules";
import { useMovingCellRef } from "./useMovingCellRef";
+import { useGooglePlaces } from "./useGooglePlaces";
import { useNextItemId } from "./useNextItemId";
import { useNotifications } from "./useNotifications";
import { useOnboarding } from "./useOnboarding";
@@ -17,10 +18,10 @@ import { usePermissions } from "./usePermissions";
import { useRealtime } from "./useRealtime";
import { useScrollPosition } from "./useScrollPosition";
import { useUser } from "./useUser";
-import { useGooglePlaces } from "./useGooglePlaces";
export {
useCurrencyFormatter,
+ useGooglePlaces,
useModules,
useMovingCellRef,
useNanoStore,
@@ -35,5 +36,4 @@ export {
useScrollPosition,
useUrlParams,
useUser,
- useGooglePlaces,
};
diff --git a/apps/erp/app/hooks/useRealtime.tsx b/apps/erp/app/hooks/useRealtime.tsx
index 67be77b82f..0142c75218 100644
--- a/apps/erp/app/hooks/useRealtime.tsx
+++ b/apps/erp/app/hooks/useRealtime.tsx
@@ -1,43 +1,27 @@
-import { useCarbon } from "@carbon/auth";
+import { useRealtimeChannel } from "@carbon/react";
import { useRevalidator } from "@remix-run/react";
-import { useEffect } from "react";
import { useUser } from "./useUser";
export function useRealtime(table: string, filter?: string) {
const { company } = useUser();
- const { accessToken, carbon } = useCarbon();
const revalidator = useRevalidator();
- useEffect(() => {
- if (!carbon || !accessToken || !table) return;
- carbon.realtime.setAuth(accessToken);
-
- const channel = carbon
- .channel(`postgres_changes:${table}}`)
- .on(
+ const channel = useRealtimeChannel({
+ topic: `postgres_changes:${table}}`,
+ dependencies: [company.id, filter],
+ setup(channel) {
+ return channel.on(
"postgres_changes",
- {
- event: "*",
- schema: "public",
- table: table,
- filter: filter,
- },
+ { event: "*", schema: "public", table: table, filter: filter },
(payload) => {
- if (
- "companyId" in payload.new &&
- payload.new.companyId !== company.id
- )
+ if ("companyId" in payload && payload.companyId !== company.id) {
return;
-
+ }
revalidator.revalidate();
}
- )
- .subscribe();
+ );
+ },
+ });
- return () => {
- if (channel) carbon?.removeChannel(channel);
- };
- // Don't put the revalidator in the deps array
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [carbon, table, filter, accessToken, company.id]);
+ return channel;
}
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index 00f788dde7..0a8ccece9f 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -44,6 +44,7 @@ import {
useDebounce,
useDisclosure,
useMount,
+ useRealtimeChannel,
VStack,
} from "@carbon/react";
import { Editor } from "@carbon/react/Editor";
@@ -54,7 +55,6 @@ import {
} from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import { Link, useFetcher, useFetchers, useParams } from "@remix-run/react";
-import type { RealtimeChannel } from "@supabase/supabase-js";
import { AnimatePresence, LayoutGroup, motion, Reorder } from "framer-motion";
import { nanoid } from "nanoid";
import type { Dispatch, SetStateAction } from "react";
@@ -603,77 +603,52 @@ const JobBillOfProcess = ({
const [page, setPage] = useState(0);
const [isLoading, setIsLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
- const channelRef = useRef<RealtimeChannel | null>(null);
const addOperationButtonRef = useRef<HTMLButtonElement>(null);
- useEffect(() => {
- if (
- !channelRef.current &&
- carbon &&
- accessToken &&
- selectedItemId &&
- !temporaryItems[selectedItemId]
- ) {
- carbon.realtime.setAuth(accessToken);
-
- channelRef.current = carbon
- .channel(`production-events:${selectedItemId}`)
- .on(
- "postgres_changes",
- {
- event: "*",
- schema: "public",
- table: "productionEvent",
- filter: `jobOperationId=eq.${selectedItemId}`,
- },
- (payload) => {
- switch (payload.eventType) {
- case "INSERT":
- const { new: inserted } = payload;
- setProductionEvents((prevEvents) => [
- ...prevEvents,
- inserted as Database["public"]["Tables"]["productionEvent"]["Row"],
- ]);
- break;
- case "UPDATE":
- const { new: updated } = payload;
- setProductionEvents((prevEvents) =>
- prevEvents.map((event) =>
- event.id === updated.id
- ? (updated as Database["public"]["Tables"]["productionEvent"]["Row"])
- : event
- )
- );
- break;
- case "DELETE":
- const { old: deleted } = payload;
- setProductionEvents((prevEvents) =>
- prevEvents.filter((event) => event.id !== deleted.id)
- );
- break;
- default:
- break;
- }
+ useRealtimeChannel({
+ topic: `production-events:${selectedItemId}`,
+ enabled: !!selectedItemId && !temporaryItems[selectedItemId],
+ setup(channel) {
+ return channel.on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "productionEvent",
+ filter: `jobOperationId=eq.${selectedItemId}`,
+ },
+ (payload) => {
+ switch (payload.eventType) {
+ case "INSERT":
+ const { new: inserted } = payload;
+ setProductionEvents((prevEvents) => [
+ ...prevEvents,
+ inserted as Database["public"]["Tables"]["productionEvent"]["Row"],
+ ]);
+ break;
+ case "UPDATE":
+ const { new: updated } = payload;
+ setProductionEvents((prevEvents) =>
+ prevEvents.map((event) =>
+ event.id === updated.id
+ ? (updated as Database["public"]["Tables"]["productionEvent"]["Row"])
+ : event
+ )
+ );
+ break;
+ case "DELETE":
+ const { old: deleted } = payload;
+ setProductionEvents((prevEvents) =>
+ prevEvents.filter((event) => event.id !== deleted.id)
+ );
+ break;
+ default:
+ break;
}
- )
- .subscribe();
- }
-
- return () => {
- if (channelRef.current) {
- channelRef.current.unsubscribe();
- carbon?.removeChannel(channelRef.current);
- channelRef.current = null;
- }
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [selectedItemId]);
-
- useEffect(() => {
- if (carbon && accessToken && channelRef.current)
- carbon.realtime.setAuth(accessToken);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [accessToken]);
+ }
+ );
+ },
+ });
const loadMoreProductionEvents = useCallback(async () => {
if (isLoading || !hasMore || !selectedItemId) return;
@@ -3167,48 +3142,29 @@ function OperationChat({ jobOperationId }: { jobOperationId: string }) {
fetchChat();
});
- const channelRef = useRef<RealtimeChannel | null>(null);
-
- useMount(() => {
- if (!channelRef.current && carbon && accessToken) {
- carbon.realtime.setAuth(accessToken);
- channelRef.current = carbon
- .channel(`job-operation-notes-${jobOperationId}`)
- .on(
- "postgres_changes",
- {
- event: "INSERT",
- schema: "public",
- table: "jobOperationNote",
- filter: `jobOperationId=eq.${jobOperationId}`,
- },
- (payload) => {
- setMessages((prev) => {
- if (prev.some((m) => m.id === payload.new.id)) {
- return prev;
- }
- return [...prev, payload.new as Message];
- });
- }
- )
- .subscribe();
- }
-
- return () => {
- if (channelRef.current) {
- channelRef.current.unsubscribe();
- carbon?.removeChannel(channelRef.current);
- channelRef.current = null;
- }
- };
+ useRealtimeChannel({
+ topic: `job-operation-notes-${jobOperationId}`,
+ setup(channel) {
+ return channel.on(
+ "postgres_changes",
+ {
+ event: "INSERT",
+ schema: "public",
+ table: "jobOperationNote",
+ filter: `jobOperationId=eq.${jobOperationId}`,
+ },
+ (payload) => {
+ setMessages((prev) => {
+ if (prev.some((m) => m.id === payload.new.id)) {
+ return prev;
+ }
+ return [...prev, payload.new as Message];
+ });
+ }
+ );
+ },
});
- useEffect(() => {
- if (carbon && accessToken && channelRef.current)
- carbon.realtime.setAuth(accessToken);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [accessToken]);
-
const messagesEndRef = useRef<HTMLDivElement>(null);
useEffect(() => {
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
index fa5db7610b..3fd200562b 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
@@ -105,7 +105,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (scheduler.error) {
throw redirect(
requestReferrer(request) ?? path.to.job(id),
- await flash(request, error(error, "Failed to schedule job"))
+ await flash(request, error(scheduler.error, "Failed to schedule job"))
);
}
diff --git a/apps/erp/app/routes/x+/production+/_index.tsx b/apps/erp/app/routes/x+/production+/_index.tsx
index be7b8ba9eb..c9f2a695fc 100644
--- a/apps/erp/app/routes/x+/production+/_index.tsx
+++ b/apps/erp/app/routes/x+/production+/_index.tsx
@@ -24,7 +24,7 @@ import {
Tooltip,
TooltipContent,
TooltipTrigger,
- useMount,
+ useRealtimeChannel,
} from "@carbon/react";
import {
ChartContainer,
@@ -48,7 +48,7 @@ import {
useFetcher,
useLoaderData,
} from "@remix-run/react";
-import { Suspense, useEffect, useMemo, useRef, useState } from "react";
+import { Suspense, useEffect, useMemo, useState } from "react";
import { CSVLink } from "react-csv";
import {
LuArrowUpRight,
@@ -78,7 +78,6 @@ import { capitalize } from "~/utils/string";
import { useCarbon } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import type { RealtimeChannel } from "@supabase/supabase-js";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { flushSync } from "react-dom";
import { RiProgress8Line } from "react-icons/ri";
@@ -761,66 +760,47 @@ function WorkCenterCards({
setEvents(initialEvents);
}, [initialEvents]);
- const channelRef = useRef<RealtimeChannel | null>(null);
-
- useMount(() => {
- if (!channelRef.current && carbon && accessToken) {
- carbon.realtime.setAuth(accessToken);
- channelRef.current = carbon
- .channel(`production-dashboard-work-centers:${companyId}`)
- .on(
- "postgres_changes",
- {
- event: "*",
- schema: "public",
- table: "productionEvent",
- filter: `companyId=eq.${companyId}`,
- },
- (payload) => {
- if (payload.eventType === "INSERT") {
- const { new: inserted } = payload;
- setEvents((prev) => [...prev, inserted as ActiveProductionEvent]);
- ensureMetaData({ jobOperationId: inserted.jobOperationId });
- } else if (payload.eventType === "UPDATE") {
- const { new: updated } = payload;
- setEvents((prev) => {
- if (updated.endTime) {
- return prev.filter((event) => event.id !== updated.id);
- }
- const exists = prev.some((event) => event.id === updated.id);
- if (exists) {
- return prev.map((event) =>
- event.id === updated.id ? { ...event, ...updated } : event
- );
- }
- return [...prev, updated as ActiveProductionEvent];
- });
- } else if (payload.eventType === "DELETE") {
- const { old: deleted } = payload;
- setEvents((prev) =>
- prev.filter((event) => event.id !== deleted.id)
- );
- }
+ useRealtimeChannel({
+ topic: `production-dashboard-work-centers:${companyId}`,
+ setup(channel) {
+ return channel.on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "productionEvent",
+ filter: `companyId=eq.${companyId}`,
+ },
+ (payload) => {
+ if (payload.eventType === "INSERT") {
+ const { new: inserted } = payload;
+ setEvents((prev) => [...prev, inserted as ActiveProductionEvent]);
+ ensureMetaData({ jobOperationId: inserted.jobOperationId });
+ } else if (payload.eventType === "UPDATE") {
+ const { new: updated } = payload;
+ setEvents((prev) => {
+ if (updated.endTime) {
+ return prev.filter((event) => event.id !== updated.id);
+ }
+ const exists = prev.some((event) => event.id === updated.id);
+ if (exists) {
+ return prev.map((event) =>
+ event.id === updated.id ? { ...event, ...updated } : event
+ );
+ }
+ return [...prev, updated as ActiveProductionEvent];
+ });
+ } else if (payload.eventType === "DELETE") {
+ const { old: deleted } = payload;
+ setEvents((prev) =>
+ prev.filter((event) => event.id !== deleted.id)
+ );
}
- )
- .subscribe();
- }
-
- return () => {
- if (channelRef.current) {
- channelRef.current.unsubscribe();
- carbon?.removeChannel(channelRef.current);
- channelRef.current = null;
- }
- };
+ }
+ );
+ },
});
- useEffect(() => {
- if (carbon && accessToken && channelRef.current) {
- carbon.realtime.setAuth(accessToken);
- }
- }, [accessToken, carbon]);
-
return (
<div className="w-full grid grid-cols-6 gap-4">
{workCenters.map((workCenter) => {
diff --git a/apps/erp/app/routes/x+/schedule+/operations.tsx b/apps/erp/app/routes/x+/schedule+/operations.tsx
index 699b4ee237..8d9230b21a 100644
--- a/apps/erp/app/routes/x+/schedule+/operations.tsx
+++ b/apps/erp/app/routes/x+/schedule+/operations.tsx
@@ -20,6 +20,7 @@ import {
useInterval,
useLocalStorage,
useMount,
+ useRealtimeChannel,
VStack,
} from "@carbon/react";
import {
@@ -29,9 +30,8 @@ import {
toZoned,
} from "@internationalized/date";
import { Link, useLoaderData } from "@remix-run/react";
-import type { RealtimeChannel } from "@supabase/supabase-js";
import { json, redirect, type LoaderFunctionArgs } from "@vercel/remix";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { LuCirclePlus, LuSettings2, LuTriangleAlert } from "react-icons/lu";
import { SearchFilter } from "~/components";
import { Enumerable } from "~/components/Enumerable";
@@ -559,7 +559,7 @@ function useProgressByOperation(
const {
company: { id: companyId },
} = useUser();
- const { carbon, accessToken } = useCarbon();
+ const { carbon } = useCarbon();
const [productionEventsByOperation, setProductionEventsByOperation] =
useState<Record<string, Event[]>>({});
@@ -666,12 +666,10 @@ function useProgressByOperation(
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [productionEventsByOperation]);
- const channelRef = useRef<RealtimeChannel | null>(null);
- useMount(() => {
- if (!channelRef.current && carbon && accessToken) {
- carbon.realtime.setAuth(accessToken);
- channelRef.current = carbon
- .channel(`kanban-schedule:${companyId}`)
+ useRealtimeChannel({
+ topic: `kanban-schedule:${companyId}`,
+ setup(channel) {
+ return channel
.on(
"postgres_changes",
{
@@ -756,25 +754,10 @@ function useProgressByOperation(
}
}
}
- )
- .subscribe();
- }
-
- return () => {
- 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]);
-
return { progressByOperation };
}
diff --git a/apps/mes/app/components/JobOperation/components/Chat.tsx b/apps/mes/app/components/JobOperation/components/Chat.tsx
index 586f52ad6b..ae555e8d08 100644
--- a/apps/mes/app/components/JobOperation/components/Chat.tsx
+++ b/apps/mes/app/components/JobOperation/components/Chat.tsx
@@ -7,6 +7,7 @@ import {
ScrollArea,
useDebounce,
useMount,
+ useRealtimeChannel,
} from "@carbon/react";
import { useEffect, useRef, useState } from "react";
import { useUser } from "~/hooks";
@@ -14,7 +15,6 @@ import type { OperationWithDetails } from "~/services/types";
import { path } from "~/utils/path";
import { useCarbon } from "@carbon/auth";
-import type { RealtimeChannel } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import { flushSync } from "react-dom";
import { LuSend } from "react-icons/lu";
@@ -63,48 +63,29 @@ export function OperationChat({
fetchChats();
});
- const channelRef = useRef<RealtimeChannel | null>(null);
-
- useMount(() => {
- if (!channelRef.current && carbon && accessToken) {
- carbon.realtime.setAuth(accessToken);
- channelRef.current = carbon
- .channel(`job-operation-notes-${operation.id}`)
- .on(
- "postgres_changes",
- {
- event: "INSERT",
- schema: "public",
- table: "jobOperationNote",
- filter: `jobOperationId=eq.${operation.id}`,
- },
- (payload) => {
- setMessages((prev) => {
- if (prev.some((note) => note.id === payload.new.id)) {
- return prev;
- }
- return [...prev, payload.new as Message];
- });
- }
- )
- .subscribe();
- }
-
- return () => {
- if (channelRef.current) {
- channelRef.current.unsubscribe();
- carbon?.removeChannel(channelRef.current);
- channelRef.current = null;
- }
- };
+ useRealtimeChannel({
+ topic: `job-operation-notes-${operation.id}`,
+ setup(channel) {
+ return channel.on(
+ "postgres_changes",
+ {
+ event: "INSERT",
+ schema: "public",
+ table: "jobOperationNote",
+ filter: `jobOperationId=eq.${operation.id}`,
+ },
+ (payload) => {
+ setMessages((prev) => {
+ if (prev.some((note) => note.id === payload.new.id)) {
+ return prev;
+ }
+ return [...prev, payload.new as Message];
+ });
+ }
+ );
+ },
});
- useEffect(() => {
- if (carbon && accessToken && channelRef.current)
- carbon.realtime.setAuth(accessToken);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [accessToken]);
-
const messagesEndRef = useRef<HTMLDivElement>(null);
useEffect(() => {
diff --git a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx b/apps/mes/app/components/JobOperation/hooks/useOperation.tsx
index f4ed24d5aa..1e7d43febe 100644
--- a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx
+++ b/apps/mes/app/components/JobOperation/hooks/useOperation.tsx
@@ -1,4 +1,9 @@
-import { toast, useDisclosure, useInterval, useMount } from "@carbon/react";
+import {
+ toast,
+ useDisclosure,
+ useInterval,
+ useRealtimeChannel,
+} from "@carbon/react";
import { useParams, useRevalidator } from "@remix-run/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useUrlParams, useUser } from "~/hooks";
@@ -89,11 +94,11 @@ export function useOperation({
setOperationState(operation);
}, [operation]);
- useMount(() => {
- if (!channelRef.current && carbon && accessToken) {
- carbon.realtime.setAuth(accessToken);
- channelRef.current = carbon
- .channel(`job-operations:${operation.id}`)
+ useRealtimeChannel({
+ topic: `job-operations:${operation.id}`,
+ dependencies: [operation.jobId],
+ setup(channel) {
+ return channel
.on(
"postgres_changes",
{
@@ -171,25 +176,10 @@ export function useOperation({
window.location.href = path.to.operations;
}
}
- )
- .subscribe();
- }
-
- return () => {
- 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]);
-
const getProgress = useCallback(() => {
const timeNow = now(getLocalTimeZone());
return eventState.reduce(
diff --git a/apps/mes/app/components/RealtimeDataProvider.tsx b/apps/mes/app/components/RealtimeDataProvider.tsx
index 0c6bfb63d1..de90e04600 100644
--- a/apps/mes/app/components/RealtimeDataProvider.tsx
+++ b/apps/mes/app/components/RealtimeDataProvider.tsx
@@ -2,6 +2,7 @@
import { useCarbon } from "@carbon/auth";
import { fetchAllFromTable } from "@carbon/database";
+import { useRealtimeChannel } from "@carbon/react";
import type { RealtimeChannel } from "@supabase/supabase-js";
import idb from "localforage";
import { useEffect, useRef } from "react";
@@ -13,7 +14,7 @@ let hydratedFromIdb = false;
let hydratedFromServer = false;
const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
- const { carbon, accessToken, realtimeAuthSet } = useCarbon();
+ const { carbon, accessToken, isRealtimeAuthSet } = useCarbon();
const {
company: { id: companyId },
} = useUser();
@@ -100,96 +101,83 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [companyId, accessToken]);
- useEffect(() => {
- if (!channelRef.current && carbon && accessToken && realtimeAuthSet) {
- channelRef.current = carbon
- .channel("realtime:core")
- .on(
- "postgres_changes",
- {
- event: "*",
- schema: "public",
- table: "item",
- filter: `companyId=eq.${companyId}`,
- },
- (payload) => {
- if (
- "companyId" in payload.new &&
- payload.new.companyId !== companyId
- )
- return;
- switch (payload.eventType) {
- case "INSERT":
- const { new: inserted } = payload;
-
- setItems((items) =>
- [
- ...items,
- {
- id: inserted.id,
- name: inserted.name,
- readableIdWithRevision: inserted.readableIdWithRevision,
- replenishmentSystem: inserted.replenishmentSystem,
- itemTrackingType: inserted.itemTrackingType,
- type: inserted.type,
- active: inserted.active,
- thumbnailPath: inserted.thumbnailPath,
- },
- ].sort((a, b) =>
+ useRealtimeChannel({
+ topic: "realtime:core",
+ dependencies: [companyId],
+ setup(channel) {
+ return channel.on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "item",
+ filter: `companyId=eq.${companyId}`,
+ },
+ (payload) => {
+ if ("companyId" in payload.new && payload.new.companyId !== companyId)
+ return;
+ switch (payload.eventType) {
+ case "INSERT":
+ const { new: inserted } = payload;
+
+ setItems((items) =>
+ [
+ ...items,
+ {
+ id: inserted.id,
+ name: inserted.name,
+ readableIdWithRevision: inserted.readableIdWithRevision,
+ replenishmentSystem: inserted.replenishmentSystem,
+ itemTrackingType: inserted.itemTrackingType,
+ type: inserted.type,
+ active: inserted.active,
+ thumbnailPath: inserted.thumbnailPath,
+ },
+ ].sort((a, b) =>
+ a.readableIdWithRevision.localeCompare(
+ b.readableIdWithRevision
+ )
+ )
+ );
+
+ break;
+ case "UPDATE":
+ const { new: updated } = payload;
+
+ setItems((items) =>
+ items
+ .map((i) => {
+ if (i.id === updated.id) {
+ return {
+ ...i,
+ readableIdWithRevision: updated.readableIdWithRevision,
+ name: updated.name,
+ replenishmentSystem: updated.replenishmentSystem,
+ type: updated.type,
+ active: updated.active,
+ thumbnailPath: updated.thumbnailPath,
+ };
+ }
+ return i;
+ })
+ .sort((a, b) =>
a.readableIdWithRevision.localeCompare(
b.readableIdWithRevision
)
)
- );
-
- break;
- case "UPDATE":
- const { new: updated } = payload;
-
- setItems((items) =>
- items
- .map((i) => {
- if (i.id === updated.id) {
- return {
- ...i,
- readableIdWithRevision:
- updated.readableIdWithRevision,
- name: updated.name,
- replenishmentSystem: updated.replenishmentSystem,
- type: updated.type,
- active: updated.active,
- thumbnailPath: updated.thumbnailPath,
- };
- }
- return i;
- })
- .sort((a, b) =>
- a.readableIdWithRevision.localeCompare(
- b.readableIdWithRevision
- )
- )
- );
- break;
- case "DELETE":
- const { old: deleted } = payload;
- setItems((items) => items.filter((p) => p.id !== deleted.id));
- break;
- default:
- break;
- }
+ );
+ break;
+ case "DELETE":
+ const { old: deleted } = payload;
+ setItems((items) => items.filter((p) => p.id !== deleted.id));
+ break;
+ default:
+ break;
}
- )
- .subscribe();
- }
-
- return () => {
- if (channelRef.current) {
- channelRef.current.unsubscribe();
- channelRef.current = null;
- }
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [carbon, accessToken, companyId, realtimeAuthSet]);
+ }
+ );
+ },
+ });
return <>{children}</>;
};
diff --git a/apps/mes/app/hooks/useRealtime.tsx b/apps/mes/app/hooks/useRealtime.tsx
index e7fa0b8299..72fbec3f0e 100644
--- a/apps/mes/app/hooks/useRealtime.tsx
+++ b/apps/mes/app/hooks/useRealtime.tsx
@@ -1,20 +1,16 @@
-import { useCarbon } from "@carbon/auth";
+import { useRealtimeChannel } from "@carbon/react";
import { useRevalidator } from "@remix-run/react";
-import { useEffect } from "react";
import { useUser } from "./useUser";
export function useRealtime(table: string, filter?: string) {
const { company } = useUser();
- const { accessToken, carbon } = useCarbon();
const revalidator = useRevalidator();
- useEffect(() => {
- if (!carbon || !accessToken || !table) return;
- carbon.realtime.setAuth(accessToken);
-
- const channel = carbon
- .channel(`postgres_changes:${table}}`)
- .on(
+ const channel = useRealtimeChannel({
+ topic: `postgres_changes:${table}}`,
+ dependencies: [company.id, filter],
+ setup(channel) {
+ return channel.on(
"postgres_changes",
{
event: "*",
@@ -22,16 +18,12 @@ export function useRealtime(table: string, filter?: string) {
table: table,
filter: filter ?? `companyId=eq.${company.id}`,
},
- (payload) => {
+ () => {
revalidator.revalidate();
}
- )
- .subscribe();
+ );
+ },
+ });
- return () => {
- if (channel) carbon?.removeChannel(channel);
- };
- // Don't put the revalidator in the deps array
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [carbon, table, filter, accessToken, company.id]);
+ return channel;
}
diff --git a/apps/mes/app/routes/x+/operations.tsx b/apps/mes/app/routes/x+/operations.tsx
index 03329f172f..4a533dbfd1 100644
--- a/apps/mes/app/routes/x+/operations.tsx
+++ b/apps/mes/app/routes/x+/operations.tsx
@@ -15,6 +15,7 @@ import {
useInterval,
useLocalStorage,
useMount,
+ useRealtimeChannel,
VStack,
} from "@carbon/react";
import {
@@ -24,9 +25,8 @@ import {
toZoned,
} from "@internationalized/date";
import { json, redirect, useLoaderData } from "@remix-run/react";
-import type { RealtimeChannel } from "@supabase/supabase-js";
import type { LoaderFunctionArgs } from "@vercel/remix";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { LuSettings2, LuTriangleAlert } from "react-icons/lu";
import type { ColumnFilter } from "~/components/Filter";
@@ -607,12 +607,11 @@ function useProgressByOperation(
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [productionEventsByOperation]);
- const channelRef = useRef<RealtimeChannel | null>(null);
- useMount(() => {
- if (!channelRef.current && carbon && accessToken) {
- carbon.realtime.setAuth(accessToken);
- channelRef.current = carbon
- .channel(`kanban-schedule:${companyId}`)
+ useRealtimeChannel({
+ topic: `kanban-schedule:${companyId}`,
+ dependencies: [items.length],
+ setup(channel) {
+ return channel
.on(
"postgres_changes",
{
@@ -685,18 +684,9 @@ function useProgressByOperation(
}
}
}
- )
- .subscribe();
- }
+ );
+ },
});
- useEffect(() => {
- return () => {
- if (channelRef.current) {
- carbon?.removeChannel(channelRef.current);
- }
- };
- }, [carbon]);
-
return { progressByOperation };
}
diff --git a/packages/auth/src/lib/supabase/provider.tsx b/packages/auth/src/lib/supabase/provider.tsx
index e282519205..d0bbbd0886 100644
--- a/packages/auth/src/lib/supabase/provider.tsx
+++ b/packages/auth/src/lib/supabase/provider.tsx
@@ -4,17 +4,21 @@ import { isBrowser } from "@carbon/utils";
import { useFetcher } from "@remix-run/react";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { PropsWithChildren } from "react";
-import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
-
+import { createContext, useContext, useEffect, useRef, useState } from "react";
+import type { StoreApi } from "zustand";
+import { createStore, useStore } from "zustand";
import type { AuthSession } from "../../types";
import { path } from "../../utils/path";
import { getCarbon } from "./client";
-const CarbonContext = createContext<{
- carbon: SupabaseClient<Database> | undefined;
- accessToken: string | undefined;
- realtimeAuthSet: boolean;
-}>({ carbon: undefined, accessToken: undefined, realtimeAuthSet: false });
+interface ICarbonStore {
+ carbon: SupabaseClient<Database>;
+ accessToken: string;
+ isRealtimeAuthSet: boolean;
+ setAuthToken: (accessToken: string, refreshToken: string) => Promise<void>;
+}
+
+const CarbonContext = createContext<StoreApi<ICarbonStore>>(null);
export const CarbonProvider = ({
children,
@@ -22,24 +26,34 @@ export const CarbonProvider = ({
}: PropsWithChildren<{
session: Partial<AuthSession>;
}>) => {
- const { accessToken, expiresAt } = session;
- const initialLoad = useRef(true);
+ const [store] = useState(() =>
+ createStore<ICarbonStore>((set, get) => ({
+ accessToken: session.accessToken || "",
+ isRealtimeAuthSet: false,
+ carbon: getCarbon(session.accessToken),
+ setAuthToken: async (accessToken, refreshToken) => {
+ const { carbon } = get();
+
+ await carbon.auth.setSession({
+ access_token: accessToken,
+ refresh_token: refreshToken,
+ });
+
+ await carbon.realtime.setAuth(accessToken);
+
+ set({ accessToken, isRealtimeAuthSet: true });
+ },
+ }))
+ );
- const carbon = useMemo(() => getCarbon(accessToken), [accessToken]);
- const [realtimeAuthSet, setRealtimeAuthSet] = useState(false);
+ const { carbon, setAuthToken } = useStore(store);
+
+ const initialLoad = useRef(true);
const refresh = useFetcher<{}>();
useEffect(() => {
- const updateRealtimeAuth = async () => {
- if (carbon && accessToken && !realtimeAuthSet) {
- await carbon.realtime.setAuth(accessToken);
- setRealtimeAuthSet(true);
- }
- };
- updateRealtimeAuth();
- }, [carbon, accessToken, realtimeAuthSet]);
-
-
+ setAuthToken(session.accessToken, session.refreshToken);
+ }, [carbon, session.refreshToken, setAuthToken, session.accessToken]);
useEffect(() => {
const handleVisibilityChange = () => {
@@ -67,8 +81,8 @@ export const CarbonProvider = ({
useInterval(() => {
// refresh ten minutes before expiry
- const shouldRefresh = expiresAt - 60 * 10 < Date.now() / 1000;
- const shouldReload = expiresAt < Date.now() / 1000;
+ const shouldRefresh = session.expiresAt - 60 * 10 < Date.now() / 1000;
+ const shouldReload = session.expiresAt < Date.now() / 1000;
if (shouldReload) {
window.location.reload();
@@ -84,19 +98,17 @@ export const CarbonProvider = ({
initialLoad.current = false;
}, 60000); // Check every minute
- const value = useMemo(() => ({ carbon, accessToken, realtimeAuthSet }), [carbon, accessToken, realtimeAuthSet]);
-
return (
- <CarbonContext.Provider value={value}>{children}</CarbonContext.Provider>
+ <CarbonContext.Provider value={store}>{children}</CarbonContext.Provider>
);
};
export const useCarbon = () => {
- const context = useContext(CarbonContext);
+ const store = useContext(CarbonContext);
- if (isBrowser && context === undefined) {
- throw new Error(`useCarbon must be used within a CarbonProvider.`);
+ if (!store) {
+ throw new Error("useCarbon must be used within a CarbonProvider");
}
- return context;
+ return useStore(store);
};
diff --git a/packages/database/supabase/migrations/20251209172004_purchase-order-realtime.sql b/packages/database/supabase/migrations/20251209172004_purchase-order-realtime.sql
new file mode 100644
index 0000000000..c8d96d956a
--- /dev/null
+++ b/packages/database/supabase/migrations/20251209172004_purchase-order-realtime.sql
@@ -0,0 +1 @@
+ALTER publication supabase_realtime ADD TABLE "purchaseOrder";
\ No newline at end of file
diff --git a/packages/react/src/Input.tsx b/packages/react/src/Input.tsx
index 0881ec2b8d..f5ce4db5b7 100644
--- a/packages/react/src/Input.tsx
+++ b/packages/react/src/Input.tsx
@@ -368,6 +368,7 @@ export interface InputElementProps
isFirstChild?: boolean;
isLastChild?: boolean;
isDisabled?: boolean;
+ isInvalid?: boolean;
}
const InputLeftElement = forwardRef<HTMLDivElement, InputElementProps>(
@@ -378,6 +379,7 @@ const InputLeftElement = forwardRef<HTMLDivElement, InputElementProps>(
isFirstChild,
isLastChild,
isDisabled = false,
+ isInvalid,
...props
},
ref
diff --git a/packages/react/src/hooks/index.ts b/packages/react/src/hooks/index.ts
index b958a83e80..12986854c4 100644
--- a/packages/react/src/hooks/index.ts
+++ b/packages/react/src/hooks/index.ts
@@ -9,6 +9,7 @@ import useKeyboardShortcuts from "./useKeyboardShortcuts";
import useLocalStorage from "./useLocalStorage";
import useMount from "./useMount";
import useOutsideClick from "./useOutsideClick";
+import { useRealtimeChannel } from "./useRealtimeChannel";
import type { Shortcut, ShortcutDefinition } from "./useShortcutKeys";
import { useShortcutKeys } from "./useShortcutKeys";
import useThrottle from "./useThrottle";
@@ -25,6 +26,7 @@ export {
useLocalStorage,
useMount,
useOutsideClick,
+ useRealtimeChannel,
useShortcutKeys,
useThrottle,
};
diff --git a/packages/react/src/hooks/useRealtimeChannel.ts b/packages/react/src/hooks/useRealtimeChannel.ts
new file mode 100644
index 0000000000..063717ea1d
--- /dev/null
+++ b/packages/react/src/hooks/useRealtimeChannel.ts
@@ -0,0 +1,107 @@
+import { useCarbon } from "@carbon/auth";
+import type { RealtimeChannel, SupabaseClient } from "@supabase/supabase-js";
+import { REALTIME_SUBSCRIBE_STATES } from "@supabase/supabase-js";
+import { useCallback, useEffect, useRef } from "react";
+import useMount from "./useMount";
+
+interface UseRealtimeChannelOptions<TDeps extends any[]> {
+ topic: string;
+ setup: (
+ channel: RealtimeChannel,
+ carbon: SupabaseClient,
+ deps: TDeps
+ ) => RealtimeChannel;
+ enabled?: boolean;
+ dependencies?: TDeps;
+}
+
+export const useRealtimeChannel = <TDeps extends any[]>(
+ options: UseRealtimeChannelOptions<TDeps>
+) => {
+ const { topic, setup, enabled = true, dependencies = [] } = options;
+ const channelRef = useRef<RealtimeChannel | null>(null);
+ const { carbon, isRealtimeAuthSet } = useCarbon();
+
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const memoSetup = useCallback(setup, [topic, ...dependencies]);
+
+ const teardown = useCallback(async () => {
+ const channel = channelRef.current;
+
+ if (!channel || !carbon) return;
+
+ try {
+ await carbon.removeChannel(channel); // prefer removeChannel always[web:14][web:37]
+ } catch (error) {
+ console.error(`❌ Error removing channel ${topic}:`, error);
+ } finally {
+ channelRef.current = null;
+ }
+ }, [carbon, topic]);
+
+ useEffect(() => {
+ if (!carbon) return;
+
+ if (!isRealtimeAuthSet || !enabled) {
+ // If disabled/auth lost, tear down any existing channel
+ void teardown();
+ return;
+ }
+
+ // Always create a fresh channel instance when deps change
+ (async () => {
+ // Ensure previous instance is gone before creating a new one
+ if (channelRef.current) {
+ await teardown();
+ }
+
+ try {
+ const channel = carbon.channel(topic);
+
+ const configuredChannel = memoSetup(
+ channel,
+ carbon,
+ dependencies as TDeps
+ );
+
+ channelRef.current = configuredChannel;
+
+ configuredChannel.subscribe(async (status, err) => {
+ if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {
+ return;
+ }
+
+ // Treat error/timeout/closed as dead; tear down so effect can recreate
+ if (
+ status === REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR ||
+ status === REALTIME_SUBSCRIBE_STATES.TIMED_OUT ||
+ status === REALTIME_SUBSCRIBE_STATES.CLOSED
+ ) {
+ await teardown();
+ }
+ });
+ } catch (error) {
+ console.error(
+ `Failed to subscribe to realtime channel ${topic}:`,
+ error
+ );
+ }
+ })();
+
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ carbon,
+ isRealtimeAuthSet,
+ enabled,
+ topic,
+ memoSetup,
+ teardown,
+ // dependencies are already in memoSetup, so not needed here
+ ]);
+
+ useMount(() => {
+ return () => void teardown();
+ });
+
+ return channelRef;
+};