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
Realtime Refactor
Brad Barbin31c28ac77700
diff --git a/apps/carbon/app/components/Form/Customer.tsx b/apps/carbon/app/components/Form/Customer.tsxindex 99ddd8a1ed..0f8319efad 100644--- a/apps/carbon/app/components/Form/Customer.tsx+++ b/apps/carbon/app/components/Form/Customer.tsx@@ -7,7 +7,7 @@ import {} from "@chakra-ui/react";import { useEffect, useMemo } from "react";import { useControlField, useField } from "remix-validated-form";-import { useCustomers } from "~/stores/data";+import { useCustomers } from "~/stores";import type { SelectProps } from "./Select";type CustomerSelectProps = Omit<SelectProps, "options">;diff --git a/apps/carbon/app/components/Form/Part.tsx b/apps/carbon/app/components/Form/Part.tsxindex 73802d4d2a..97f06914a8 100644--- a/apps/carbon/app/components/Form/Part.tsx+++ b/apps/carbon/app/components/Form/Part.tsx@@ -8,7 +8,7 @@ import {import { useMemo } from "react";import { useControlField, useField } from "remix-validated-form";import type { PartReplenishmentSystem } from "~/modules/parts";-import { useParts } from "~/stores/data";+import { useParts } from "~/stores";import type { SelectProps } from "./Select";type PartSelectProps = Omit<SelectProps, "options"> & {diff --git a/apps/carbon/app/components/Form/Supplier.tsx b/apps/carbon/app/components/Form/Supplier.tsxindex aa30d0c9af..e019c6611a 100644--- a/apps/carbon/app/components/Form/Supplier.tsx+++ b/apps/carbon/app/components/Form/Supplier.tsx@@ -7,7 +7,7 @@ import {} from "@chakra-ui/react";import { useEffect, useMemo } from "react";import { useControlField, useField } from "remix-validated-form";-import { useSuppliers } from "~/stores/data";+import { useSuppliers } from "~/stores";import type { SelectProps } from "./Select";type SupplierSelectProps = Omit<SelectProps, "options">;diff --git a/apps/carbon/app/hooks/index.ts b/apps/carbon/app/hooks/index.tsindex ee084b09b2..9b3b97ab4c 100644--- a/apps/carbon/app/hooks/index.ts+++ b/apps/carbon/app/hooks/index.ts@@ -1,4 +1,5 @@import { useMovingCellRef } from "./useMovingCellRef";+import { useNanoStore } from "./useNanoStore";import { usePermissions } from "./usePermissions";import { useRealtime } from "./useRealtime";import { useRouteData } from "./useRouteData";@@ -7,6 +8,7 @@ import { useUser } from "./useUser";export {useMovingCellRef,+ useNanoStore,usePermissions,useRealtime,useRouteData,diff --git a/apps/carbon/app/stores/nanostore.ts b/apps/carbon/app/hooks/useNanoStore.tssimilarity index 88%rename from apps/carbon/app/stores/nanostore.tsrename to apps/carbon/app/hooks/useNanoStore.tsindex 5d07f75cc3..2931968bb3 100644--- a/apps/carbon/app/stores/nanostore.ts+++ b/apps/carbon/app/hooks/useNanoStore.ts@@ -2,7 +2,7 @@ import { useStore } from "@nanostores/react";import { type WritableAtom } from "nanostores";import { useCallback } from "react";-export const useValue = <T>(atom: WritableAtom<T>) => {+export function useNanoStore<T>(atom: WritableAtom<T>) {const value = useStore(atom);const set = useCallback(@@ -17,4 +17,4 @@ export const useValue = <T>(atom: WritableAtom<T>) => {);return [value, set] as const;-};+}diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsxindex 1dbff16e8a..b78fa5e578 100644--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx@@ -58,7 +58,10 @@ export default function useReceiptForm({);const onClose = async () => {- if (!sourceDocumentId || !locationId || internalReceiptLines.length === 0) {+ if (+ internalReceiptLines.length === 0 ||+ internalReceiptLines.every((line) => line.receivedQuantity === 0)+ ) {await deleteReceipt();}diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsxindex 6490d311dc..661525b3b2 100644--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx@@ -5,7 +5,7 @@ import { usePermissions } from "~/hooks";import { useSupabase } from "~/lib/supabase";import type { getAccountsList } from "~/modules/accounting";import type { PurchaseOrderLine } from "~/modules/purchasing";-import { usePurchasedParts } from "~/stores/data";+import { usePurchasedParts } from "~/stores/parts";export default function usePurchaseOrderLines() {const { supabase } = useSupabase();diff --git a/apps/carbon/app/modules/shared/ui/Notes/Notes.tsx b/apps/carbon/app/modules/shared/ui/Notes/Notes.tsxindex 4c51549a4a..29e33c6c67 100644--- a/apps/carbon/app/modules/shared/ui/Notes/Notes.tsx+++ b/apps/carbon/app/modules/shared/ui/Notes/Notes.tsx@@ -49,14 +49,17 @@ const Notes = ({ documentId, notes }: NotesProps) => {throw new Error("Invalid user");return (<Fragment key={note.id}>+ {/* @ts-ignore */}<Avatar path={note.user.avatarUrl} /><VStack spacing={1} w="full" alignItems="start">- <Text fontWeight="bold">{note.user?.fullName}</Text>+ {/* @ts-ignore */}+ <Text fontWeight="bold">{note.user?.fullName!}</Text><HTML text={note.note} /><HStack spacing={4}><Text color="gray.500">{formatTimeAgo(note.createdAt)}</Text>+ {/* @ts-ignore */}{user.id === note.user.id && (<Formmethod="post"diff --git a/apps/carbon/app/modules/shared/ui/Realtime/RealtimeDataProvider.tsx b/apps/carbon/app/modules/shared/ui/Realtime/RealtimeDataProvider.tsxnew file mode 100644index 0000000000..5b6e2fa668--- /dev/null+++ b/apps/carbon/app/modules/shared/ui/Realtime/RealtimeDataProvider.tsx@@ -0,0 +1,218 @@+import { Image, Text, useColorModeValue, VStack } from "@chakra-ui/react";+import { useEffect, useState } from "react";+import { Background } from "~/components/Layout";+import { useSupabase } from "~/lib/supabase";+import { useCustomers, useParts, useSuppliers } from "~/stores";++const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {+ const [loading, setLoading] = useState(true);+ const { supabase, accessToken } = useSupabase();++ const [, setParts] = useParts();+ const [, setSuppliers] = useSuppliers();+ const [, setCustomers] = useCustomers();++ const fetchData = async () => {+ if (!supabase || !accessToken) return;++ const [parts, suppliers, customers] = await Promise.all([+ supabase+ .from("part")+ .select("id, name, replenishmentSystem")+ .eq("active", true),+ supabase.from("supplier").select("id, name"),+ supabase.from("customer").select("id, name"),+ ]);++ if (parts.error || suppliers.error || customers.error) {+ throw new Error("Failed to fetch core data");+ }++ setParts(parts.data ?? []);+ setSuppliers(suppliers.data ?? []);+ setCustomers(customers.data ?? []);++ setLoading(false);+ };++ useEffect(() => {+ if (!supabase || !accessToken) return;+ fetchData();++ supabase.realtime.setAuth(accessToken);+ const channel = supabase+ .channel("realtime:core")+ .on(+ "postgres_changes",+ {+ event: "*",+ schema: "public",+ table: "part",+ },+ (payload) => {+ switch (payload.eventType) {+ case "INSERT":+ const { new: inserted } = payload;+ setParts((parts) => [+ ...parts,+ {+ id: inserted.id,+ name: inserted.name,+ replenishmentSystem: inserted.replenishmentSystem,+ },+ ]);+ break;+ case "UPDATE":+ const { new: updated } = payload;+ setParts((parts) =>+ parts.map((p) => {+ if (p.id === updated.id) {+ return {+ ...p,+ name: updated.name,+ replenishmentSystem: updated.replenishmentSystem,+ };+ }+ return p;+ })+ );+ break;+ case "DELETE":+ const { old: deleted } = payload;+ setParts((parts) => parts.filter((p) => p.id !== deleted.id));+ break;+ default:+ break;+ }+ }+ )+ .on(+ "postgres_changes",+ {+ event: "*",+ schema: "public",+ table: "customer",+ },+ (payload) => {+ switch (payload.eventType) {+ case "INSERT":+ const { new: inserted } = payload;+ setCustomers((customers) => [+ ...customers,+ {+ id: inserted.id,+ name: inserted.name,+ },+ ]);+ break;+ case "UPDATE":+ const { new: updated } = payload;+ setCustomers((customers) =>+ customers.map((p) => {+ if (p.id === updated.id) {+ return {+ ...p,+ name: updated.name,+ };+ }+ return p;+ })+ );+ break;+ case "DELETE":+ const { old: deleted } = payload;+ setCustomers((customers) =>+ customers.filter((p) => p.id !== deleted.id)+ );+ break;+ default:+ break;+ }+ }+ )+ .on(+ "postgres_changes",+ {+ event: "*",+ schema: "public",+ table: "supplier",+ },+ (payload) => {+ switch (payload.eventType) {+ case "INSERT":+ const { new: inserted } = payload;+ setSuppliers((suppliers) => [+ ...suppliers,+ {+ id: inserted.id,+ name: inserted.name,+ },+ ]);+ break;+ case "UPDATE":+ const { new: updated } = payload;+ setSuppliers((suppliers) =>+ suppliers.map((p) => {+ if (p.id === updated.id) {+ return {+ ...p,+ name: updated.name,+ };+ }+ return p;+ })+ );+ break;+ case "DELETE":+ const { old: deleted } = payload;+ setSuppliers((suppliers) =>+ suppliers.filter((p) => p.id !== deleted.id)+ );+ break;+ default:+ break;+ }+ }+ )+ .subscribe();++ return () => {+ if (channel) supabase?.removeChannel(channel);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [supabase, accessToken]);++ if (loading) {+ return <Loading />;+ }++ return <>{children}</>;+};++function Loading() {+ return (+ <VStack+ h="100vh"+ w="100vw"+ alignItems="center"+ justifyContent="center"+ spacing={4}+ >+ <Image+ src={useColorModeValue(+ "/carbon-logo-dark.png",+ "/carbon-logo-light.png"+ )}+ alt="Carbon Logo"+ maxW={100}+ marginBottom={3}+ />+ <Text letterSpacing={-1} textTransform="uppercase" fontWeight={700}>+ Loading...+ </Text>+ <Background />+ </VStack>+ );+}++export default RealtimeDataProvider;diff --git a/apps/carbon/app/modules/shared/ui/Realtime/index.ts b/apps/carbon/app/modules/shared/ui/Realtime/index.tsnew file mode 100644index 0000000000..4ea9c8fd4a--- /dev/null+++ b/apps/carbon/app/modules/shared/ui/Realtime/index.ts@@ -0,0 +1,3 @@+import RealtimeDataProvider from "./RealtimeDataProvider";++export default RealtimeDataProvider;diff --git a/apps/carbon/app/modules/shared/ui/index.ts b/apps/carbon/app/modules/shared/ui/index.tsindex 6fa98be72e..ed7f793a53 100644--- a/apps/carbon/app/modules/shared/ui/index.ts+++ b/apps/carbon/app/modules/shared/ui/index.ts@@ -1,3 +1,4 @@import Notes from "./Notes";+import RealtimeDataProvider from "./Realtime";-export { Notes };+export { RealtimeDataProvider, Notes };diff --git a/apps/carbon/app/root.tsx b/apps/carbon/app/root.tsxindex fe177a9fd7..5ce9738fa2 100644--- a/apps/carbon/app/root.tsx+++ b/apps/carbon/app/root.tsx@@ -58,9 +58,6 @@ function Document({children: React.ReactNode;title?: string;}) {- const loaderData = useLoaderData<typeof loader>();- const env = loaderData?.env ?? {};-return (<html lang="en"><head>@@ -71,11 +68,7 @@ function Document({<body>{children}<ScrollRestoration />- <script- dangerouslySetInnerHTML={{- __html: `window.env = ${JSON.stringify(env)}`,- }}- />+<Scripts />{process.env.NODE_ENV === "development" && <LiveReload />}</body>@@ -84,12 +77,20 @@ function Document({}export default function App() {+ const loaderData = useLoaderData<typeof loader>();+ const env = loaderData?.env ?? {};+return (<Document><ThemeProvider><SkipNavLink zIndex={7}>Skip to content</SkipNavLink><Outlet /></ThemeProvider>+ <script+ dangerouslySetInnerHTML={{+ __html: `window.env = ${JSON.stringify(env)}`,+ }}+ /></Document>);}diff --git a/apps/carbon/app/routes/x+/_layout.tsx b/apps/carbon/app/routes/x+/_layout.tsxindex 5702f9159c..f266e044a3 100644--- a/apps/carbon/app/routes/x+/_layout.tsx+++ b/apps/carbon/app/routes/x+/_layout.tsx@@ -8,6 +8,7 @@ import NProgress from "nprogress";import { useEffect } from "react";import { IconSidebar, Topbar } from "~/components/Layout";import { getSupabase, SupabaseProvider } from "~/lib/supabase";+import { RealtimeDataProvider } from "~/modules/shared";import {getUser,getUserClaims,@@ -19,7 +20,6 @@ import {getSessionFlash,requireAuthSession,} from "~/services/session";-import { RealtimeDataProvider } from "~/stores/data";export async function loader({ request }: LoaderFunctionArgs) {const { accessToken, expiresAt, expiresIn, userId } =diff --git a/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx b/apps/carbon/app/routes/x+/inventory+/receipts.new.tsxindex a4879d014f..63bf165199 100644--- a/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx+++ b/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx@@ -1,7 +1,11 @@import type { LoaderFunctionArgs } from "@remix-run/node";import { redirect } from "@remix-run/node";+import { getSupabaseServiceRole } from "~/lib/supabase";+import type { ReceiptSourceDocument } from "~/modules/inventory";import { upsertReceipt } from "~/modules/inventory";+import { getPurchaseOrder } from "~/modules/purchasing";import { getNextSequence, rollbackNextSequence } from "~/modules/settings";+import { getUserDefaults } from "~/modules/users";import { requirePermissions } from "~/services/auth";import { flash } from "~/services/session";import { error } from "~/utils/result";@@ -11,7 +15,16 @@ export async function loader({ request }: LoaderFunctionArgs) {create: "inventory",});- const nextSequence = await getNextSequence(client, "receipt", userId);+ const url = new URL(request.url);+ const sourceDocument =+ (url.searchParams.get("sourceDocument") as ReceiptSourceDocument) ??+ undefined;+ const sourceDocumentId = url.searchParams.get("sourceDocumentId") ?? "";++ const [nextSequence, defaults] = await Promise.all([+ getNextSequence(client, "receipt", userId),+ getUserDefaults(client, userId),+ ]);if (nextSequence.error) {return redirect(request.headers.get("Referer") ?? "/x/inventory/receipts",@@ -22,9 +35,32 @@ export async function loader({ request }: LoaderFunctionArgs) {);}+ let sourceDocumentReadableId: string | undefined;+ if (sourceDocument) {+ const serviceRole = getSupabaseServiceRole();+ switch (sourceDocument) {+ case "Purchase Order":+ const purchaseOrder = await getPurchaseOrder(+ serviceRole,+ sourceDocumentId+ );+ if (purchaseOrder.data) {+ sourceDocumentReadableId =+ purchaseOrder.data.purchaseOrderId ?? undefined;+ }+ break;+ default:+ break;+ }+ }+const insertReceipt = await upsertReceipt(client, {receiptId: nextSequence.data,- sourceDocumentId: "",+ // @ts-expect-error+ sourceDocument,+ sourceDocumentId,+ sourceDocumentReadableId,+ locationId: defaults.data?.locationId ?? undefined,createdBy: userId,});if (insertReceipt.error) {diff --git a/apps/carbon/app/stores/customers.ts b/apps/carbon/app/stores/customers.tsnew file mode 100644index 0000000000..44eb0a75a6--- /dev/null+++ b/apps/carbon/app/stores/customers.ts@@ -0,0 +1,6 @@+import { atom } from "nanostores";+import { useNanoStore } from "~/hooks";+import type { ListItem } from "~/types";++const $customersStore = atom<ListItem[]>([]);+export const useCustomers = () => useNanoStore($customersStore);diff --git a/apps/carbon/app/stores/data.tsx b/apps/carbon/app/stores/data.tsxdeleted file mode 100644index ca9c46b6bd..0000000000--- a/apps/carbon/app/stores/data.tsx+++ /dev/null@@ -1,207 +0,0 @@-import { Image, Text, useColorModeValue, VStack } from "@chakra-ui/react";-import { useStore } from "@nanostores/react";-import { atom, computed } from "nanostores";-import { useEffect, useState } from "react";-import { Background } from "~/components/Layout";-import { useSupabase } from "~/lib/supabase";-import type { ListItem } from "~/types";-import { useValue } from "./nanostore";--const partsStore = atom<- (ListItem & { replenishmentSystem: "Buy" | "Make" | "Buy and Make" })[]->([]);-export const useParts = () => useValue(partsStore);--const purchasedPartsStore = computed(partsStore, (part) =>- part.filter((i) => i.replenishmentSystem === "Buy")-);-export const usePurchasedParts = () => useStore(purchasedPartsStore);--const manufacturedPartsStore = computed(partsStore, (part) =>- part.filter((i) => i.replenishmentSystem === "Make")-);-export const useManufacturedParts = () => useStore(manufacturedPartsStore);--const suppliersStore = atom<ListItem[]>([]);-export const useSuppliers = () => useValue(suppliersStore);--const customersStore = atom<ListItem[]>([]);-export const useCustomers = () => useValue(customersStore);--export const RealtimeDataProvider = ({- children,-}: {- children: React.ReactNode;-}) => {- const [loading, setLoading] = useState(true);- const { supabase, accessToken } = useSupabase();-- const [, setParts] = useParts();- const [, setSuppliers] = useSuppliers();- const [, setCustomers] = useCustomers();-- const fetchData = async () => {- if (!supabase || !accessToken) return;-- const [parts, suppliers, customers] = await Promise.all([- supabase- .from("part")- .select("id, name, replenishmentSystem")- .eq("active", true),- supabase.from("supplier").select("id, name"),- supabase.from("customer").select("id, name"),- ]);-- if (parts.error || suppliers.error || customers.error) {- throw new Error("Failed to fetch core data");- }-- setParts(parts.data ?? []);- setSuppliers(suppliers.data ?? []);- setCustomers(customers.data ?? []);-- setLoading(false);- };-- useEffect(() => {- if (!supabase || !accessToken) return;- fetchData();-- supabase.realtime.setAuth(accessToken);- const channel = supabase- .channel("realtime:core")- .on(- "postgres_changes",- {- event: "INSERT",- schema: "public",- table: "part",- },- (payload) => {- const { new: inserted } = payload;- setParts((parts) => [- ...parts,- {- id: inserted.id,- name: inserted.name,- replenishmentSystem: inserted.replenishmentSystem,- },- ]);- }- )- .on(- "postgres_changes",- {- event: "DELETE",- schema: "public",- table: "part",- },- (payload) => {- const { old: deleted } = payload;- setParts((parts) => parts.filter((p) => p.id !== deleted.id));- }- )- .on(- "postgres_changes",- {- event: "INSERT",- schema: "public",- table: "customer",- },- (payload) => {- const { new: inserted } = payload;- setCustomers((customers) => [- ...customers,- {- id: inserted.id,- name: inserted.name,- },- ]);- }- )- .on(- "postgres_changes",- {- event: "DELETE",- schema: "public",- table: "part",- },- (payload) => {- const { old: deleted } = payload;- setCustomers((customers) =>- customers.filter((c) => c.id !== deleted.id)- );- }- )- .on(- "postgres_changes",- {- event: "INSERT",- schema: "public",- table: "supplier",- },- (payload) => {- const { new: inserted } = payload;- setSuppliers((suppliers) => [- ...suppliers,- {- id: inserted.id,- name: inserted.name,- },- ]);- }- )- .on(- "postgres_changes",- {- event: "DELETE",- schema: "public",- table: "part",- },- (payload) => {- const { old: deleted } = payload;- setSuppliers((suppliers) =>- suppliers.filter((c) => c.id !== deleted.id)- );- }- )- .subscribe();-- return () => {- if (channel) supabase?.removeChannel(channel);- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [supabase, accessToken]);-- if (loading) {- return <Loading />;- }-- return <>{children}</>;-};--function Loading() {- return (- <VStack- h="100vh"- w="100vw"- alignItems="center"- justifyContent="center"- spacing={4}- >- <Image- src={useColorModeValue(- "/carbon-logo-dark.png",- "/carbon-logo-light.png"- )}- alt="Carbon Logo"- maxW={100}- marginBottom={3}- />- <Text letterSpacing={-1} textTransform="uppercase" fontWeight={700}>- Loading...- </Text>- <Background />- </VStack>- );-}diff --git a/apps/carbon/app/stores/index.ts b/apps/carbon/app/stores/index.tsnew file mode 100644index 0000000000..3e6542ec72--- /dev/null+++ b/apps/carbon/app/stores/index.ts@@ -0,0 +1,3 @@+export * from "./customers";+export * from "./parts";+export * from "./suppliers";diff --git a/apps/carbon/app/stores/parts.ts b/apps/carbon/app/stores/parts.tsnew file mode 100644index 0000000000..248b5ccf35--- /dev/null+++ b/apps/carbon/app/stores/parts.ts@@ -0,0 +1,20 @@+import { useStore as useValue } from "@nanostores/react";+import { atom, computed } from "nanostores";+import { useNanoStore } from "~/hooks";+import type { ListItem } from "~/types";++type Part = ListItem & { replenishmentSystem: "Buy" | "Make" | "Buy and Make" };++const $partsStore = atom<Part[]>([]);++const $purchasedPartsStore = computed($partsStore, (part) =>+ part.filter((i) => i.replenishmentSystem === "Buy")+);++const $manufacturedPartsStore = computed($partsStore, (part) =>+ part.filter((i) => i.replenishmentSystem === "Make")+);++export const useParts = () => useNanoStore<Part[]>($partsStore);+export const usePurchasedParts = () => useValue($purchasedPartsStore);+export const useManufacturedParts = () => useValue($manufacturedPartsStore);diff --git a/apps/carbon/app/stores/suppliers.ts b/apps/carbon/app/stores/suppliers.tsnew file mode 100644index 0000000000..da7f34a8a5--- /dev/null+++ b/apps/carbon/app/stores/suppliers.ts@@ -0,0 +1,6 @@+import { atom } from "nanostores";+import { useNanoStore } from "~/hooks";+import type { ListItem } from "~/types";++const $suppliersStore = atom<ListItem[]>([]);+export const useSuppliers = () => useNanoStore($suppliersStore);