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
fix: path for parts files, and assigned view for MES
Brad Barbin5af5ace4d3db
diff --git a/apps/mes/app/components/AppSidebar.tsx b/apps/mes/app/components/AppSidebar.tsxindex da5c18180e..f342dedf64 100644--- a/apps/mes/app/components/AppSidebar.tsx+++ b/apps/mes/app/components/AppSidebar.tsx@@ -6,6 +6,7 @@ import {LuCalendarDays,LuChevronDown,LuChevronsUpDown,+ LuClipboardList,LuClock,LuLogOut,LuMapPin,@@ -163,6 +164,11 @@ export function OperationsNav({ activeEvents }: { activeEvents: number }) {icon: LuCalendarDays,to: path.to.operations,},+ {+ title: "Assigned",+ icon: LuClipboardList,+ to: path.to.assigned,+ },{title: "Active",icon: LuActivity,@@ -183,7 +189,9 @@ export function OperationsNav({ activeEvents }: { activeEvents: number }) {<SidebarGroupLabel>Operations</SidebarGroupLabel><SidebarMenu>{links.map((item) => {- const isActive = pathname.includes(item.to);+ const isActive =+ pathname.includes(item.to) ||+ (pathname.includes("operations") && item.title === "Schedule");return (<SidebarMenuItem key={item.title}><SidebarMenuButtondiff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsxindex 5704866598..04d1d91226 100644--- a/apps/mes/app/components/JobOperation.tsx+++ b/apps/mes/app/components/JobOperation.tsx@@ -1332,7 +1332,7 @@ function useOperation(}));} else if (payload.eventType === "DELETE") {toast.error("This operation has been deleted");- window.location.href = path.to.operations;+ window.location.href = path.to.assigned;}})@@ -1452,12 +1452,23 @@ function useFiles(job: Job) {(file: StorageItem) => {const companyId = user.company.id;const { bucket } = file;- const folder =- bucket === "job" ? job.id : job.salesOrderLineId ?? job.quoteLineId;- const path = `${companyId}/${bucket}/${folder}/${file.name}`;- return path;+ let id: string | null = "";++ switch (bucket) {+ case "job":+ id = job.id;+ break;+ case "opportunity-line":+ id = job.salesOrderLineId ?? job.quoteLineId;+ break;+ case "parts":+ id = job.itemId;+ break;+ }++ return `${companyId}/${bucket}/${id}/${file.name}`;},- [job.id, job.quoteLineId, job.salesOrderLineId, user.company.id]+ [job.id, job.itemId, job.quoteLineId, job.salesOrderLineId, user.company.id]);const downloadFile = useCallback(diff --git a/apps/mes/app/routes/x+/_index.tsx b/apps/mes/app/routes/x+/_index.tsxindex 959e525c1d..b71df4cad3 100644--- a/apps/mes/app/routes/x+/_index.tsx+++ b/apps/mes/app/routes/x+/_index.tsx@@ -3,5 +3,5 @@ import { redirect } from "@vercel/remix";import { path } from "~/utils/path";export const loader: LoaderFunction = async ({ request }) => {- return redirect(path.to.operations);+ return redirect(path.to.assigned);};diff --git a/apps/mes/app/routes/x+/active.tsx b/apps/mes/app/routes/x+/active.tsxindex d8d7a8180b..feedb5f3b4 100644--- a/apps/mes/app/routes/x+/active.tsx+++ b/apps/mes/app/routes/x+/active.tsx@@ -54,7 +54,8 @@ export default function ActiveRoute() {(operation) =>operation.description?.toLowerCase().includes(lowercasedTerm) ||operation.jobReadableId?.toLowerCase().includes(lowercasedTerm) ||- operation.itemReadableId?.toLowerCase().includes(lowercasedTerm)+ operation.itemReadableId?.toLowerCase().includes(lowercasedTerm) ||+ operation.itemDescription?.toLowerCase().includes(lowercasedTerm));}, [operations, searchTerm]);diff --git a/apps/mes/app/routes/x+/assigned.tsx b/apps/mes/app/routes/x+/assigned.tsxnew file mode 100644index 0000000000..abc15953a8--- /dev/null+++ b/apps/mes/app/routes/x+/assigned.tsx@@ -0,0 +1,151 @@+import { getCarbonServiceRole } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import {+ Button,+ Heading,+ Input,+ SidebarTrigger,+ useIsMobile,+} from "@carbon/react";+import { json, useLoaderData, useParams } from "@remix-run/react";+import type { LoaderFunctionArgs } from "@vercel/remix";+import { useEffect, useMemo, useRef, useState } from "react";+import { LuSearch, LuTriangleAlert } from "react-icons/lu";+import type { ImperativePanelHandle } from "react-resizable-panels";+import { OperationsList } from "~/components";+import { getLocation } from "~/services/location.server";+import {+ getJobOperationsAssignedToEmployee,+ getWorkCentersByLocation,+} from "~/services/operations.service";+import type { Operation } from "~/services/types";+import { makeDurations } from "~/utils/durations";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId, userId } = await requirePermissions(request, {});++ const serviceRole = await getCarbonServiceRole();++ const { location } = await getLocation(request, serviceRole, {+ companyId,+ userId,+ });++ const [operations, workCenters] = await Promise.all([+ getJobOperationsAssignedToEmployee(serviceRole, userId, companyId),+ getWorkCentersByLocation(serviceRole, location),+ ]);++ return json({+ operations: operations?.data?.map(makeDurations) ?? [],+ workCenters: workCenters?.data ?? [],+ });+}++export default function AssignedRoute() {+ const { operations, workCenters } = useLoaderData<typeof loader>();+ const [searchTerm, setSearchTerm] = useState("");++ const panelRef = useRef<ImperativePanelHandle>(null);+ const isMobile = useIsMobile();+ const { operationId } = useParams();++ useEffect(() => {+ if (isMobile && !!operationId) {+ panelRef.current?.collapse();+ } else {+ panelRef.current?.expand();+ }+ }, [isMobile, operationId]);++ const filteredOperations = useMemo(() => {+ if (!searchTerm) return operations;+ const lowercasedTerm = searchTerm.toLowerCase();+ return operations.filter(+ (operation) =>+ operation.description?.toLowerCase().includes(lowercasedTerm) ||+ operation.jobReadableId?.toLowerCase().includes(lowercasedTerm) ||+ operation.itemReadableId?.toLowerCase().includes(lowercasedTerm) ||+ operation.itemDescription?.toLowerCase().includes(lowercasedTerm)+ );+ }, [operations, searchTerm]);++ const filteredOperationsByWorkCenter = useMemo(() => {+ return filteredOperations.reduce<Record<string, Operation[]>>(+ (acc, operation) => {+ const workCenter = operation.workCenterId;+ if (!workCenter) return acc;+ acc[workCenter] = [...(acc[workCenter] || []), operation];+ return acc;+ },+ {}+ );+ }, [filteredOperations]);++ return (+ <div className="flex flex-col flex-1">+ <header className="sticky top-0 z-10 flex h-[var(--header-height)] overflow-y-scroll scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent shrink-0 items-center gap-2 transition-[width,height] ease-linear group-has-[[data-collapsible=icon]]/sidebar-wrapper:h-12 border-b bg-background">+ <div className="flex items-center gap-2 px-2">+ <SidebarTrigger />+ <Heading size="h4">Assigned to Me</Heading>+ </div>+ </header>++ <main className="h-[calc(100dvh-var(--header-height))] w-full overflow-y-auto scrollbar-thin scrollbar-thumb-accent scrollbar-track-transparent">+ <div className="w-full p-4 h-[var(--header-height)]">+ <div className="relative">+ <div className="flex justify-between gap-4">+ <div className="flex flex-grow">+ <LuSearch className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />+ <Input+ value={searchTerm}+ onChange={(e) => setSearchTerm(e.target.value)}+ placeholder="Search"+ className="pl-8"+ />+ </div>+ </div>+ </div>+ </div>++ {Object.keys(filteredOperationsByWorkCenter).length > 0 ? (+ <div className="flex flex-col flex-1 mt-4">+ {Object.entries(filteredOperationsByWorkCenter).map(+ ([workCenterId, operations]) => (+ <div key={workCenterId} className="flex flex-col">+ <div className="bg-muted px-4 py-2 border-y">+ <h3 className="font-medium">+ {workCenters.find((wc) => wc.id === workCenterId)?.name}+ </h3>+ </div>+ <div className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,330px),1fr))] p-4 gap-4">+ <OperationsList operations={operations} />+ </div>+ </div>+ )+ )}+ </div>+ ) : searchTerm ? (+ <div className="flex flex-col flex-1 w-full h-[calc(100%-var(--header-height)*2)] items-center justify-center gap-4">+ <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">+ <LuTriangleAlert className="h-6 w-6" />+ </div>+ <span className="text-xs font-mono font-light text-foreground uppercase">+ No results exist+ </span>+ <Button onClick={() => setSearchTerm("")}>Clear Search</Button>+ </div>+ ) : (+ <div className="flex flex-col flex-1 w-full h-[calc(100%-var(--header-height)*2)] items-center justify-center gap-4">+ <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">+ <LuTriangleAlert className="h-6 w-6" />+ </div>+ <span className="text-xs font-mono font-light text-foreground uppercase">+ No assigned operations+ </span>+ </div>+ )}+ </main>+ </div>+ );+}diff --git a/apps/mes/app/routes/x+/finish.tsx b/apps/mes/app/routes/x+/finish.tsxindex b38fcdb8ca..8ae30f79c3 100644--- a/apps/mes/app/routes/x+/finish.tsx+++ b/apps/mes/app/routes/x+/finish.tsx@@ -41,7 +41,7 @@ export async function action({ request }: ActionFunctionArgs) {}throw redirect(- path.to.operations,+ path.to.assigned,await flash(request, success("Operation finished successfully")));}diff --git a/apps/mes/app/routes/x+/recent.tsx b/apps/mes/app/routes/x+/recent.tsxindex c6474eda65..11d57bd634 100644--- a/apps/mes/app/routes/x+/recent.tsx+++ b/apps/mes/app/routes/x+/recent.tsx@@ -53,7 +53,8 @@ export default function ActiveRoute() {(operation) =>operation.description?.toLowerCase().includes(lowercasedTerm) ||operation.jobReadableId?.toLowerCase().includes(lowercasedTerm) ||- operation.itemReadableId?.toLowerCase().includes(lowercasedTerm)+ operation.itemReadableId?.toLowerCase().includes(lowercasedTerm) ||+ operation.itemDescription?.toLowerCase().includes(lowercasedTerm));}, [operations, searchTerm]);diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex d730819c1e..698cb914ab 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -150,7 +150,7 @@ export async function getJobFiles(return [...(jobFiles.data?.map((f) => ({ ...f, bucket: "job" })) || []),- ...(itemFiles.data?.map((f) => ({ ...f, bucket: "item" })) || []),+ ...(itemFiles.data?.map((f) => ({ ...f, bucket: "parts" })) || []),];}}@@ -174,14 +174,10 @@ export async function getJobOperationsAssignedToEmployee(employeeId: string,companyId: string) {- return client- .from("jobOperation")- .select(- "id, operationStatus:status, description, workCenterId, ...job(jobId:id, jobStatus:status, jobReadableId:jobId)"- )- .in("jobStatus", ["In Progress", "Ready", "Paused"])- .eq("assignee", employeeId)- .eq("companyId", companyId);+ return client.rpc("get_assigned_job_operations", {+ user_id: employeeId,+ company_id: companyId,+ });}export async function getJobOperationById(diff --git a/apps/mes/app/styles/tailwind.css b/apps/mes/app/styles/tailwind.cssindex 4cc78dfbf5..0084b3d756 100644--- a/apps/mes/app/styles/tailwind.css+++ b/apps/mes/app/styles/tailwind.css@@ -21,7 +21,7 @@--header-height: 50px;--filters-height: 38px;--controls-width: 240px;-+ --sidebar-width: 240px;--base-shadow-color: rgb(0 0 0 / 0.16);--button-drop-shadow: rgb(0 0 0 / 0.4);diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.tsindex e3704f2ce4..facf2a7dec 100644--- a/apps/mes/app/utils/path.ts+++ b/apps/mes/app/utils/path.ts@@ -19,6 +19,7 @@ export const path = {},accountSettings: `${ERP_URL}/x/account`,active: `${x}/active`,+ assigned: `${x}/assigned`,authenticatedRoot: x,callback: "/callback",complete: `${x}/complete`,diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 354fd40a3e..f7f12cbd74 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -32469,6 +32469,45 @@ export type Database = {thumbnailPath: string}[]}+ get_assigned_job_operations: {+ Args: {+ user_id: string+ company_id: string+ }+ Returns: {+ id: string+ jobId: string+ operationOrder: number+ processId: string+ workCenterId: string+ description: string+ setupTime: number+ setupUnit: Database["public"]["Enums"]["factor"]+ laborTime: number+ laborUnit: Database["public"]["Enums"]["factor"]+ machineTime: number+ machineUnit: Database["public"]["Enums"]["factor"]+ operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]+ jobReadableId: string+ jobStatus: Database["public"]["Enums"]["jobStatus"]+ jobDueDate: string+ jobDeadlineType: Database["public"]["Enums"]["deadlineType"]+ jobCustomerId: string+ salesOrderReadableId: string+ salesOrderId: string+ salesOrderLineId: string+ parentMaterialId: string+ itemReadableId: string+ itemDescription: string+ operationStatus: Database["public"]["Enums"]["jobOperationStatus"]+ operationQuantity: number+ quantityComplete: number+ quantityScrapped: number+ thumbnailPath: string+ assignee: string+ tags: string[]+ }[]+ }get_claims: {Args: {uid: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 354fd40a3e..f7f12cbd74 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -32469,6 +32469,45 @@ export type Database = {thumbnailPath: string}[]}+ get_assigned_job_operations: {+ Args: {+ user_id: string+ company_id: string+ }+ Returns: {+ id: string+ jobId: string+ operationOrder: number+ processId: string+ workCenterId: string+ description: string+ setupTime: number+ setupUnit: Database["public"]["Enums"]["factor"]+ laborTime: number+ laborUnit: Database["public"]["Enums"]["factor"]+ machineTime: number+ machineUnit: Database["public"]["Enums"]["factor"]+ operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]+ jobReadableId: string+ jobStatus: Database["public"]["Enums"]["jobStatus"]+ jobDueDate: string+ jobDeadlineType: Database["public"]["Enums"]["deadlineType"]+ jobCustomerId: string+ salesOrderReadableId: string+ salesOrderId: string+ salesOrderLineId: string+ parentMaterialId: string+ itemReadableId: string+ itemDescription: string+ operationStatus: Database["public"]["Enums"]["jobOperationStatus"]+ operationQuantity: number+ quantityComplete: number+ quantityScrapped: number+ thumbnailPath: string+ assignee: string+ tags: string[]+ }[]+ }get_claims: {Args: {uid: stringdiff --git a/packages/database/supabase/migrations/20250123212102_mes-assignments.sql b/packages/database/supabase/migrations/20250123212102_mes-assignments.sqlnew file mode 100644index 0000000000..f2b26d2467--- /dev/null+++ b/packages/database/supabase/migrations/20250123212102_mes-assignments.sql@@ -0,0 +1,95 @@+DROP FUNCTION IF EXISTS get_assigned_job_operations;+CREATE OR REPLACE FUNCTION get_assigned_job_operations(+ user_id TEXT,+ company_id TEXT+)+RETURNS TABLE (+ "id" TEXT,+ "jobId" TEXT,+ "operationOrder" DOUBLE PRECISION,+ "processId" TEXT,+ "workCenterId" TEXT,+ "description" TEXT,+ "setupTime" NUMERIC(10,2),+ "setupUnit" factor,+ "laborTime" NUMERIC(10,2),+ "laborUnit" factor,+ "machineTime" NUMERIC(10,2),+ "machineUnit" factor,+ "operationOrderType" "methodOperationOrder",+ "jobReadableId" TEXT,+ "jobStatus" "jobStatus",+ "jobDueDate" DATE,+ "jobDeadlineType" "deadlineType",+ "jobCustomerId" TEXT,+ "salesOrderReadableId" TEXT,+ "salesOrderId" TEXT,+ "salesOrderLineId" TEXT,+ "parentMaterialId" TEXT,+ "itemReadableId" TEXT,+ "itemDescription" TEXT,+ "operationStatus" "jobOperationStatus",+ "operationQuantity" NUMERIC(10,2),+ "quantityComplete" NUMERIC(10,2),+ "quantityScrapped" NUMERIC(10,2),+ "thumbnailPath" TEXT,+ "assignee" TEXT,+ "tags" TEXT[]+)+SECURITY INVOKER+AS $$+BEGIN+ RETURN QUERY+ SELECT+ jo."id",+ jo."jobId",+ jo."order" AS "operationOrder",+ jo."processId",+ jo."workCenterId",+ jo."description",+ jo."setupTime",+ jo."setupUnit",+ jo."laborTime",+ jo."laborUnit",+ jo."machineTime",+ jo."machineUnit",+ jo."operationOrder" AS "operationOrderType",+ j."jobId" AS "jobReadableId",+ j."status" AS "jobStatus",+ j."dueDate" AS "jobDueDate",+ j."deadlineType" AS "jobDeadlineType",+ j."customerId" AS "jobCustomerId",+ so."salesOrderId" AS "salesOrderReadableId",+ so."id" AS "salesOrderId",+ j."salesOrderLineId",+ jmm."parentMaterialId",+ i."readableId" as "itemReadableId",+ i."name" as "itemDescription",+ CASE+ WHEN j."status" = 'Paused' THEN 'Paused'+ ELSE jo."status"+ END AS "operationStatus",+ jo."operationQuantity",+ jo."quantityComplete",+ jo."quantityScrapped",+ CASE+ WHEN jmm."parentMaterialId" IS NULL THEN COALESCE(j_mu."thumbnailPath", i_mu."thumbnailPath")+ ELSE COALESCE(i."thumbnailPath", i_mu."thumbnailPath")+ END as "thumbnailPath",+ jo."assignee",+ jo."tags"+ FROM "jobOperation" jo+ JOIN "job" j ON j.id = jo."jobId"+ LEFT JOIN "salesOrderLine" sol ON sol."id" = j."salesOrderLineId"+ LEFT JOIN "salesOrder" so ON so."id" = sol."salesOrderId"+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id+ LEFT JOIN "item" i ON jmm."itemId" = i.id+ LEFT JOIN "modelUpload" j_mu ON j_mu.id = j."modelUploadId"+ LEFT JOIN "modelUpload" i_mu ON i_mu.id = i."modelUploadId"+ WHERE jo."assignee" = user_id+ AND jo."status" IN ('Todo', 'Ready', 'Waiting', 'In Progress', 'Paused')+ AND j."status" IN ('Ready', 'In Progress', 'Paused')+ AND j."companyId" = company_id+ ORDER BY jo."priority";+END;+$$ LANGUAGE plpgsql;