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: realtime sync of progress across multiple operators/work stations

Brad Barbin3edff22e361b
diff --git a/apps/carbon/app/components/ItemThumbnail.tsx b/apps/carbon/app/components/ItemThumbnail.tsx
index b96e4bea37..c2e7ffe08e 100644
--- a/apps/carbon/app/components/ItemThumbnail.tsx
+++ b/apps/carbon/app/components/ItemThumbnail.tsx
@@ -1,5 +1,5 @@
import { Spinner } from "@carbon/react";
-import { LuHexagon } from "react-icons/lu";
+import { LuSquareStack } from "react-icons/lu";
import type { MethodItemType } from "~/modules/shared";
import { MethodItemTypeIcon } from "./Icons";
@@ -32,7 +32,7 @@ const ItemThumbnail = ({
type={type}
/>
) : (
- <LuHexagon className="w-5 h-5 text-muted-foreground" />
+ <LuSquareStack className="w-5 h-5 text-muted-foreground" />
)}
</div>
);
diff --git a/apps/carbon/app/components/Layout/Navigation/ContentSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/ContentSidebar.tsx
index 5de97403e7..da04b92252 100644
--- a/apps/carbon/app/components/Layout/Navigation/ContentSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/ContentSidebar.tsx
@@ -13,7 +13,7 @@ const ContentSidebar = ({ links }: { links: Route[] }) => {
<CollapsibleSidebar>
<div className="overflow-y-auto h-full w-full pb-8">
<VStack>
- <VStack spacing={0} className="p-2">
+ <VStack spacing={1} className="p-2">
{links.map((route) => {
const isActive =
location.pathname.includes(route.to) && route.q === filter;
diff --git a/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
index 88d00f8080..a039db7d72 100644
--- a/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
@@ -23,7 +23,7 @@ const GroupedContentSidebar = ({
<VStack
key={group.name}
className="border-b border-border p-2"
- spacing={0}
+ spacing={1}
>
<h4 className="text-xs text-muted-foreground font-mono pl-4 py-1 uppercase">
{group.name}
diff --git a/apps/carbon/app/components/Layout/Navigation/useModules.tsx b/apps/carbon/app/components/Layout/Navigation/useModules.tsx
index 07b688dbb0..b9c496b484 100644
--- a/apps/carbon/app/components/Layout/Navigation/useModules.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/useModules.tsx
@@ -4,10 +4,10 @@ import {
LuCrown,
LuFactory,
LuFiles,
- LuHexagon,
LuSettings,
LuShield,
LuShoppingCart,
+ LuSquareStack,
LuUsers,
LuWrench,
} from "react-icons/lu";
@@ -35,7 +35,7 @@ export function useModules() {
permission: "parts",
name: "Items",
to: path.to.parts,
- icon: LuHexagon,
+ icon: LuSquareStack,
},
{
permission: "inventory",
diff --git a/apps/carbon/app/components/Layout/Topbar/CreateMenu.tsx b/apps/carbon/app/components/Layout/Topbar/CreateMenu.tsx
index 137a83b0ea..da43fac363 100644
--- a/apps/carbon/app/components/Layout/Topbar/CreateMenu.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/CreateMenu.tsx
@@ -11,9 +11,9 @@ import { Link } from "@remix-run/react";
import {
LuContainer,
LuHardHat,
- LuHexagon,
LuPlus,
LuShoppingCart,
+ LuSquareStack,
LuUserSquare,
LuUsers,
} from "react-icons/lu";
@@ -38,7 +38,7 @@ function useCreate(): Route[] {
links.push({
name: "Part",
to: path.to.newPart,
- icon: <LuHexagon />,
+ icon: <LuSquareStack />,
});
}
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx
index c24bb31426..13a6f43996 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx
@@ -30,7 +30,7 @@ import {
LuAlertTriangle,
LuDownload,
LuHardHat,
- LuHexagon,
+ LuSquareStack,
LuUpload,
} from "react-icons/lu";
import { RiProgress4Line } from "react-icons/ri";
@@ -154,7 +154,7 @@ const JobBreadcrumbs = () => {
{isJobMethod && (
<TabsList className="grid w-full grid-cols-2 my-4">
<TabsTrigger value="item">
- <LuHexagon className="mr-2" /> Item
+ <LuSquareStack className="mr-2" /> Item
</TabsTrigger>
<TabsTrigger value="quote">
<RiProgress4Line className="mr-2" />
diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.ts
index 7ef007e52c..bf2d1d7b46 100644
--- a/apps/carbon/app/modules/users/users.server.ts
+++ b/apps/carbon/app/modules/users/users.server.ts
@@ -9,7 +9,6 @@ import type { Database, Json } from "@carbon/database";
import { redis } from "@carbon/kv";
import type { SupabaseClient } from "@supabase/supabase-js";
import { redirect } from "@vercel/remix";
-import crypto from "crypto";
import { getSupplierContact } from "~/modules/purchasing";
import { getCustomerContact } from "~/modules/sales";
import type {
@@ -358,21 +357,58 @@ async function createUser(
export async function deactivateUser(
client: SupabaseClient<Database>,
- userId: string
+ userId: string,
+ companyId: string
): Promise<Result> {
- const updateActiveStatus = await client
- .from("user")
- .update({ active: false, firstName: "Deactivate", lastName: "User" })
- .eq("id", userId);
- if (updateActiveStatus.error) {
- return error(updateActiveStatus.error, "Failed to deactivate user");
+ const serviceRole = getCarbonServiceRole();
+ const currentPermissions = await serviceRole
+ .from("userPermission")
+ .select("*")
+ .eq("id", userId)
+ .single();
+
+ if (currentPermissions.error) {
+ return error(currentPermissions.error, "Failed to get user permissions");
}
- const randomPassword = crypto.randomBytes(20).toString("hex");
- const updatePassword = await resetPassword(userId, randomPassword);
+ const permissions = Object.entries(
+ currentPermissions.data?.permissions as Record<string, string[]>
+ ).reduce<Record<string, string[]>>((acc, [key, value]) => {
+ acc[key] = value.filter((id) => id !== companyId);
+ return acc;
+ }, {});
+
+ const [updatePermissions, userToCompanyDelete, employeeDelete] =
+ await Promise.all([
+ serviceRole
+ .from("userPermission")
+ .update({ permissions })
+ .eq("id", userId),
+ serviceRole
+ .from("userToCompany")
+ .delete()
+ .eq("userId", userId)
+ .eq("companyId", companyId),
+ serviceRole
+ .from("employee")
+ .delete()
+ .eq("id", userId)
+ .eq("companyId", companyId),
+ ]);
+
+ if (updatePermissions.error) {
+ return error(updatePermissions.error, "Failed to update user permissions");
+ }
+
+ if (userToCompanyDelete.error) {
+ return error(
+ userToCompanyDelete.error,
+ "Failed to remove user from company"
+ );
+ }
- if (updatePassword.error) {
- return error(updatePassword.error, "Failed to deactivate user");
+ if (employeeDelete.error) {
+ return error(employeeDelete.error, "Failed to remove employee");
}
return success("Sucessfully deactivated user");
diff --git a/apps/carbon/app/routes/x+/users+/deactivate.tsx b/apps/carbon/app/routes/x+/users+/deactivate.tsx
index f826f7fb20..8333896a13 100644
--- a/apps/carbon/app/routes/x+/users+/deactivate.tsx
+++ b/apps/carbon/app/routes/x+/users+/deactivate.tsx
@@ -12,7 +12,7 @@ import type { userAdminTask } from "~/trigger/user-admin";
// export const config = { runtime: "nodejs" };
export async function action({ request }: ActionFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
delete: "users",
});
@@ -28,7 +28,7 @@ export async function action({ request }: ActionFunctionArgs) {
if (users.length === 1) {
const [userId] = users;
- const result = await deactivateUser(client, userId);
+ const result = await deactivateUser(client, userId, companyId);
throw redirect(safeRedirect(redirectTo), await flash(request, result));
} else {
@@ -36,6 +36,7 @@ export async function action({ request }: ActionFunctionArgs) {
payload: {
id,
type: "deactivate" as const,
+ companyId,
},
}));
diff --git a/apps/carbon/app/routes/x+/users+/resend-invite.tsx b/apps/carbon/app/routes/x+/users+/resend-invite.tsx
index eab70bead1..8d071d121a 100644
--- a/apps/carbon/app/routes/x+/users+/resend-invite.tsx
+++ b/apps/carbon/app/routes/x+/users+/resend-invite.tsx
@@ -12,7 +12,7 @@ import { userAdminTask } from "~/trigger/user-admin";
// export const config = { runtime: "nodejs" };
export async function action({ request }: ActionFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
delete: "users",
});
@@ -39,6 +39,7 @@ export async function action({ request }: ActionFunctionArgs) {
payload: {
id,
type: "resend",
+ companyId,
},
}))
);
diff --git a/apps/carbon/app/trigger/user-admin.ts b/apps/carbon/app/trigger/user-admin.ts
index b7db0b1b50..ba6a6647da 100644
--- a/apps/carbon/app/trigger/user-admin.ts
+++ b/apps/carbon/app/trigger/user-admin.ts
@@ -9,6 +9,7 @@ const serviceRole = getCarbonServiceRole();
export const userAdminSchema = z.object({
id: z.string(),
type: z.enum(["resend", "deactivate"]),
+ companyId: z.string(),
});
export const userAdminTask = task({
@@ -25,7 +26,11 @@ export const userAdminTask = task({
break;
case "deactivate":
console.log(`🚭 Deactivating ${payload.id}`);
- result = await deactivateUser(serviceRole, payload.id);
+ result = await deactivateUser(
+ serviceRole,
+ payload.id,
+ payload.companyId
+ );
break;
default:
result = {
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index 9d6e09ad63..7ebfec8a71 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -42,7 +42,7 @@ import {
} from "@carbon/react";
import { Await, Link, useFetcher } from "@remix-run/react";
import type { ComponentProps, ReactNode } from "react";
-import { Suspense, useCallback, useMemo, useState } from "react";
+import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import {
DeadlineIcon,
DocumentIcon,
@@ -120,21 +120,24 @@ export const JobOperation = ({
operation,
}: JobOperationProps) => {
const {
- active,
activeTab,
eventType,
fullscreen,
- laborProductionEvent,
- machineProductionEvent,
isOverdue,
- progress,
scrapModal,
- setupProductionEvent,
downloadDocument,
getDocumentPath,
setActiveTab,
setEventType,
- } = useOperation(operation, events, job);
+ } = useOperation(operation, job);
+
+ const {
+ active,
+ setupProductionEvent,
+ laborProductionEvent,
+ machineProductionEvent,
+ progress,
+ } = useActiveEvents(operation, events);
return (
<OptionallyFullscreen
@@ -598,18 +601,76 @@ export const JobOperation = ({
);
};
-function useActiveEvents(events: ProductionEvent[]): {
+function useActiveEvents(
+ operation: OperationWithDetails,
+ events: ProductionEvent[]
+): {
active: { setup: boolean; labor: boolean; machine: 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 [eventState, setEventState] = useState<ProductionEvent[]>(events);
+
+ useEffect(() => {
+ setEventState(events);
+ }, [events]);
+
+ useEffect(() => {
+ if (!carbon || !accessToken) return;
+ carbon.realtime.setAuth(accessToken);
+ const channel = carbon
+ .channel("realtime:core")
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "productionEvent",
+ filter: `jobOperationId=eq.${operation.id}`,
+ },
+ (payload) => {
+ switch (payload.eventType) {
+ case "INSERT":
+ const { new: inserted } = payload;
+ setEventState((prevEvents) => [
+ ...prevEvents,
+ inserted as ProductionEvent,
+ ]);
+ break;
+ case "UPDATE":
+ const { new: updated } = payload;
+ setEventState((prevEvents) =>
+ prevEvents.map((event) =>
+ event.id === updated.id ? (updated as ProductionEvent) : event
+ )
+ );
+ break;
+ case "DELETE":
+ const { old: deleted } = payload;
+ setEventState((prevEvents) =>
+ prevEvents.filter((event) => event.id !== deleted.id)
+ );
+ break;
+ default:
+ break;
+ }
+ }
+ )
+ .subscribe();
+
+ return () => {
+ if (channel) carbon?.removeChannel(channel);
+ };
+ }, [accessToken, carbon, operation.id]);
+
const getProgress = useCallback(() => {
const timeNow = now(getLocalTimeZone());
- return events.reduce(
+ return eventState.reduce(
(acc, event) => {
if (event.endTime && event.type) {
acc[event.type.toLowerCase() as keyof typeof acc] +=
@@ -634,7 +695,7 @@ function useActiveEvents(events: ProductionEvent[]): {
machine: 0,
}
);
- }, [events]);
+ }, [eventState]);
const [progress, setProgress] = useState<{
setup: number;
labor: number;
@@ -651,11 +712,11 @@ function useActiveEvents(events: ProductionEvent[]): {
(e) =>
e.type === "Labor" && e.endTime === null && e.employeeId === user.id
),
- machineProductionEvent: events.find(
+ machineProductionEvent: eventState.find(
(e) => e.type === "Machine" && e.endTime === null
),
};
- }, [events, user.id]);
+ }, [eventState, events, user.id]);
const active = useMemo(() => {
return {
@@ -676,11 +737,7 @@ function useActiveEvents(events: ProductionEvent[]): {
};
}
-function useOperation(
- operation: OperationWithDetails,
- events: ProductionEvent[],
- job: Job
-) {
+function useOperation(operation: OperationWithDetails, job: Job) {
const user = useUser();
const { carbon } = useCarbon();
const fullscreen = useDisclosure();
@@ -696,14 +753,6 @@ function useOperation(
return "Setup";
});
- const {
- active,
- setupProductionEvent,
- laborProductionEvent,
- machineProductionEvent,
- progress,
- } = useActiveEvents(events);
-
const getDocumentPath = useCallback(
(file: StorageItem) => {
const companyId = user.company.id;
@@ -751,15 +800,10 @@ function useOperation(
);
return {
- active,
activeTab,
eventType,
fullscreen,
- laborProductionEvent,
- machineProductionEvent,
- progress,
scrapModal,
- setupProductionEvent,
isOverdue: operation.jobDueDate
? new Date(operation.jobDueDate) < new Date()
: false,
diff --git a/apps/mes/app/routes/_public+/_layout.tsx b/apps/mes/app/routes/_public+/_layout.tsx
index ffee026244..07042a5ee7 100644
--- a/apps/mes/app/routes/_public+/_layout.tsx
+++ b/apps/mes/app/routes/_public+/_layout.tsx
@@ -6,9 +6,12 @@ import { Heading } from "@carbon/react";
export default function PublicRoute() {
return (
<div className="container relative h-full flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0">
- <div className="relative hidden h-full flex-col bg-muted p-10 text-white lg:flex dark:border-r">
+ <div className="relative hidden h-full flex-col bg-muted p-10 lg:flex dark:border-r">
<div className="absolute inset-0 bg-zinc-900" />
- <Heading size="h1" className="relative z-20 flex items-center">
+ <Heading
+ size="h1"
+ className="relative z-20 flex items-center text-white"
+ >
<BsHexagonFill className="w-6 h-6 mr-2" />
CarbonOS
</Heading>
diff --git a/packages/database/supabase/migrations/20241002012019_production-quantities.sql b/packages/database/supabase/migrations/20241002012019_production-quantities.sql
index 88630aad14..bf635a1a09 100644
--- a/packages/database/supabase/migrations/20241002012019_production-quantities.sql
+++ b/packages/database/supabase/migrations/20241002012019_production-quantities.sql
@@ -68,4 +68,11 @@ CREATE POLICY "Employees can delete production quantities" ON "productionQuantit
AND "companyId" = ANY(
SELECT "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
- );
\ No newline at end of file
+ );
+
+
+ALTER TABLE "productionQuantity" REPLICA IDENTITY FULL;
+ALTER PUBLICATION supabase_realtime ADD TABLE "productionQuantity";
+
+ALTER TABLE "jobOperation" REPLICA IDENTITY FULL;
+ALTER PUBLICATION supabase_realtime ADD TABLE "jobOperation";