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
feat: warn for low quantities in bin
Brad Barbina6975d28b696
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsxindex 3ce5e5ad15..5ae8651540 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx@@ -225,6 +225,7 @@ const BillOfMaterial = ({if (isReadOnly) return;const materialId = nanoid();setSelectedItemId(materialId);+ setSelectedMaterialId(materialId);let newOrder = 1;if (materials.length) {diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsxindex 98b6e89382..15a51561bb 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx@@ -313,6 +313,7 @@ const JobBillOfMaterial = ({if (!permissions.can("update", "production") || isDisabled) return;const materialId = nanoid();setSelectedItemId(materialId);+ setSelectedMaterialId(materialId);let newOrder = 1;if (items.length) {@@ -687,7 +688,7 @@ function MaterialForm({return;}- const [item, itemCost] = await Promise.all([+ const [item, itemCost, pickMethod] = await Promise.all([carbon.from("item").select(@@ -697,6 +698,13 @@ function MaterialForm({.eq("companyId", company.id).single(),carbon.from("itemCost").select("unitCost").eq("itemId", itemId).single(),+ carbon+ .from("pickMethod")+ .select("defaultShelfId")+ .eq("itemId", itemId)+ .eq("companyId", company.id)+ .eq("locationId", locationId!)+ .maybeSingle(),]);if (item.error) {@@ -713,6 +721,7 @@ function MaterialForm({methodType: item.data?.defaultMethodType ?? "Buy",requiresBatchTracking: item.data?.itemTrackingType === "Batch",requiresSerialTracking: item.data?.itemTrackingType === "Serial",+ shelfId: pickMethod.data?.defaultShelfId ?? undefined,}));if (item.data?.type) {diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsxindex 76f56696bf..32d3bb2463 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx@@ -1,17 +1,19 @@-import { useCarbon } from "@carbon/auth";-import { Badge, Button, HStack, VStack } from "@carbon/react";+import { Badge, Button, cn, HStack, VStack } from "@carbon/react";+import { useNumberFormatter } from "@react-aria/i18n";import { useFetcher, useParams } from "@remix-run/react";import type { ColumnDef } from "@tanstack/react-table";-import { memo, useCallback, useMemo } from "react";+import { memo, useMemo } from "react";import {+ LuArrowDown,+ LuArrowLeft,+ LuArrowUp,LuBookMarked,LuCircleCheck,LuFlag,+ LuGitPullRequest,LuHash,LuRefreshCcwDot,- LuRuler,} from "react-icons/lu";-import { RxCodesandboxLogo } from "react-icons/rx";import {Hyperlink,ItemThumbnail,@@ -19,26 +21,26 @@ import {Table,TrackingTypeIcon,} from "~/components";-import { EditableNumber, EditableText } from "~/components/Editable";-import { Enumerable } from "~/components/Enumerable";-import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";-import { usePermissions, useUser } from "~/hooks";-import { methodType } from "~/modules/shared";+import { usePermissions, useRouteData } from "~/hooks";import { useBom, useItems } from "~/stores";import { path } from "~/utils/path";-import type { JobMaterial } from "../../types";+import type { Job, JobMaterial } from "../../types";type JobMaterialsTableProps = {data: JobMaterial[];count: number;};-const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {const { jobId } = useParams();if (!jobId) throw new Error("Job ID is required");+ const routeData = useRouteData<{ job: Job }>(path.to.job(jobId));+ const isAllocated = ["Planned", "Ready", "In Progress", "Paused"].includes(+ routeData?.job?.status ?? ""+ );+const fetcher = useFetcher<{}>();- const unitsOfMeasure = useUnitOfMeasure();+ const formatter = useNumberFormatter();const [items] = useItems();const [, setSelectedMaterialId] = useBom();@@ -84,69 +86,42 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {},},{- accessorKey: "methodType",- header: "Method Type",- cell: (item) => (- <Badge variant="secondary">- <MethodIcon type={item.getValue<string>()} className="mr-2" />- <span>{item.getValue<string>()}</span>- </Badge>- ),+ accessorKey: "estimatedQuantity",+ header: "Quantity",+ cell: ({ row }) => formatter.format(row.original.estimatedQuantity),meta: {- filter: {- type: "static",- options: methodType.map((value) => ({- value,- label: (- <Badge variant="secondary">- <MethodIcon type={value} className="mr-2" />- <span>{value}</span>- </Badge>- ),- })),- },- icon: <RxCodesandboxLogo />,+ icon: <LuHash />,},},-{- accessorKey: "unitOfMeasureCode",- header: "UoM",- cell: (item) => (- <Enumerable- value={- unitsOfMeasure.find((u) => u.value === item.getValue())?.label ??- null- }- />+ id: "method",+ header: "Method",+ cell: ({ row }) => (+ <HStack>+ <Badge variant="secondary">+ <MethodIcon+ type={row.original.methodType}+ className="size-3 mr-1"+ />+ {row.original.methodType}+ </Badge>+ <LuArrowLeft+ className={cn(+ row.original.methodType === "Make" ? "rotate-180" : ""+ )}+ />+ <Badge variant="secondary">+ <LuGitPullRequest className="size-3 mr-1" />+ {row.original.shelfName ??+ (row.original.methodType === "Make" ? "WIP" : "Default Shelf")}+ </Badge>+ </HStack>),- meta: {- icon: <LuRuler />,- },},{- accessorKey: "quantityPerParent",- header: "Qty. per Parent",- cell: (item) => item.getValue(),- meta: {- icon: <LuHash />,- },- },- {- accessorKey: "estimatedQuantity",- header: "Estimated",- cell: (item) => item.getValue(),- meta: {- icon: <LuHash />,- },- },- {- id: "quantityOnHand",- header: "On Hand",- meta: {- icon: <LuHash />,- },+ id: "quantityOnHandInShelf",+ header: "On Hand (Shelf)",cell: ({ row }) => {const isInventoried =row.original.itemTrackingType !== "Non-Inventory";@@ -158,75 +133,102 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {</Badge>);+ const quantityRequiredByShelf = isAllocated+ ? row.original.quantityFromProductionOrderInShelf+ : row.original.quantityFromProductionOrderInShelf ++ row.original.estimatedQuantity;+if (row.original.methodType === "Make") {return null;}- const quantityOnHand = row.original.quantityOnHand;+ const quantityOnHandInShelf = row.original.quantityOnHandInShelf;- if (quantityOnHand < (row.original.estimatedQuantity ?? 0))+ if (quantityOnHandInShelf < quantityRequiredByShelf)return (<Badge variant="destructive"><LuFlag className="mr-2" />- <span className="group-hover:hidden">Insufficient</span>- <span className="hidden group-hover:block">- {quantityOnHand}- </span>+ {quantityOnHandInShelf}</Badge>);return (<Badge variant="green"><LuCircleCheck className="mr-2" />- <span className="group-hover:hidden">In Stock</span>- <span className="hidden group-hover:block">{quantityOnHand}</span>+ {quantityOnHandInShelf}</Badge>);},+ meta: {+ icon: <LuHash />,+ },},{- id: "quantityOnPurchaseOrder",- header: "On PO",- cell: ({ row }) => row.original.quantityOnPurchaseOrder,+ id: "quantityOnHand",+ header: "On Hand (Total)",+ cell: ({ row }) => {+ if (+ row.original.itemTrackingType === "Non-Inventory" ||+ row.original.methodType === "Make"+ ) {+ return null;+ }+ const quantityOnHand =+ row.original.quantityOnHandInShelf ++ row.original.quantityOnHandNotInShelf;++ const incoming =+ row.original.quantityOnPurchaseOrder ++ row.original.quantityOnProductionOrder;++ const allocated =+ row.original.quantityFromProductionOrderInShelf ++ row.original.quantityFromProductionOrderNotInShelf ++ row.original.quantityOnSalesOrder;++ if (+ quantityOnHand + incoming - allocated <+ (row.original.estimatedQuantity ?? 0)+ ) {+ return (+ <Badge variant="destructive">+ <LuFlag className="mr-2" />+ {quantityOnHand}+ </Badge>+ );+ }+ return quantityOnHand;+ },meta: {icon: <LuHash />,},},{- id: "quantityOnProductionOrder",- header: "In Prod.",- cell: ({ row }) => row.original.quantityOnProductionOrder,+ id: "allocated",+ header: "Allocated",+ cell: ({ row }) =>+ row.original.quantityFromProductionOrderInShelf ++ row.original.quantityFromProductionOrderNotInShelf ++ row.original.quantityOnSalesOrder,++ meta: {+ icon: <LuArrowDown className="text-red-600" />,+ },+ },+ {+ id: "incoming",+ header: "Incoming",+ cell: ({ row }) =>+ row.original.quantityOnPurchaseOrder ++ row.original.quantityOnProductionOrder,meta: {- icon: <LuHash />,+ icon: <LuArrowUp className="text-emerald-600" />,},},];- }, [items, jobId, setSelectedMaterialId, unitsOfMeasure]);+ }, [items, jobId, setSelectedMaterialId]);const permissions = usePermissions();- const { carbon } = useCarbon();- const { id: userId } = useUser();- const onCellEdit = useCallback(- async (id: string, value: unknown, row: JobMaterial) => {- if (!carbon) throw new Error("Carbon client not found");- return await carbon- .from("jobMaterial")- .update({- [id]: value,- updatedBy: userId,- })- .eq("id", row.id!);- },- [carbon, userId]- );-- const editableComponents = useMemo(() => {- return {- description: EditableText(onCellEdit),- quantity: EditableNumber(onCellEdit),- estimatedQuantity: EditableNumber(onCellEdit),- };- }, [onCellEdit]);return (<Table<JobMaterial>@@ -249,9 +251,7 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {</fetcher.Form>) : undefined}- editableComponents={editableComponents}title="Materials"- withInlineEditing={permissions.can("update", "production")}/>);});diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsxindex a05911dc35..1083720887 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx@@ -320,6 +320,7 @@ const QuoteBillOfMaterial = ({if (!permissions.can("update", "sales") || isDisabled) return;const materialId = nanoid();setSelectedItemId(materialId);+ setSelectedMaterialId(materialId);let newOrder = 1;if (items.length) {diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 5f7b0e6b21..f925ae36fa 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -48629,12 +48629,16 @@ export type Database = {jobMaterialItemId: stringmethodType: Database["public"]["Enums"]["methodType"]name: string+ quantityFromProductionOrderInShelf: number+ quantityFromProductionOrderNotInShelf: numberquantityIssued: number- quantityOnHand: number+ quantityOnHandInShelf: number+ quantityOnHandNotInShelf: numberquantityOnProductionOrder: numberquantityOnPurchaseOrder: numberquantityOnSalesOrder: numberquantityPerParent: number+ shelfName: stringthumbnailPath: stringtype: Database["public"]["Enums"]["itemType"]unitOfMeasureCode: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 5f7b0e6b21..f925ae36fa 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -48629,12 +48629,16 @@ export type Database = {jobMaterialItemId: stringmethodType: Database["public"]["Enums"]["methodType"]name: string+ quantityFromProductionOrderInShelf: number+ quantityFromProductionOrderNotInShelf: numberquantityIssued: number- quantityOnHand: number+ quantityOnHandInShelf: number+ quantityOnHandNotInShelf: numberquantityOnProductionOrder: numberquantityOnPurchaseOrder: numberquantityOnSalesOrder: numberquantityPerParent: number+ shelfName: stringthumbnailPath: stringtype: Database["public"]["Enums"]["itemType"]unitOfMeasureCode: stringdiff --git a/packages/database/supabase/migrations/20251007014346_update-job-method-rpcs-with-shelf.sql b/packages/database/supabase/migrations/20251007014346_update-job-method-rpcs-with-shelf.sqlindex f7d1649186..bcc64f97a4 100644--- a/packages/database/supabase/migrations/20251007014346_update-job-method-rpcs-with-shelf.sql+++ b/packages/database/supabase/migrations/20251007014346_update-job-method-rpcs-with-shelf.sql@@ -587,3 +587,213 @@ INNER JOIN item ON material."itemId" = item.idWHERE material."quoteId" = qidORDER BY "order"$$ LANGUAGE sql STABLE;+++DROP FUNCTION IF EXISTS get_job_quantity_on_hand;+CREATE OR REPLACE FUNCTION get_job_quantity_on_hand(job_id TEXT, company_id TEXT, location_id TEXT)+ RETURNS TABLE (+ "id" TEXT,+ "jobMaterialItemId" TEXT,+ "jobMakeMethodId" TEXT,+ "itemReadableId" TEXT,+ "name" TEXT,+ "description" TEXT,+ "itemTrackingType" "itemTrackingType",+ "methodType" "methodType",+ "type" "itemType",+ "thumbnailPath" TEXT,+ "unitOfMeasureCode" TEXT,+ "quantityPerParent" NUMERIC,+ "estimatedQuantity" NUMERIC,+ "quantityIssued" NUMERIC,+ "quantityOnHandInShelf" NUMERIC,+ "quantityOnHandNotInShelf" NUMERIC,+ "quantityOnSalesOrder" NUMERIC,+ "quantityOnPurchaseOrder" NUMERIC,+ "quantityOnProductionOrder" NUMERIC,+ "quantityFromProductionOrderInShelf" NUMERIC,+ "quantityFromProductionOrderNotInShelf" NUMERIC,+ "shelfName" TEXT+ ) AS $$+ BEGIN+ RETURN QUERY++WITH+ job_materials AS (+ SELECT+ jm."id",+ jm."itemId",+ jm."jobMakeMethodId",+ jm."description",+ jm."methodType",+ jm."quantity",+ jm."estimatedQuantity",+ jm."quantityIssued",+ jm."shelfId"+ FROM+ "jobMaterial" jm+ WHERE+ jm."jobId" = job_id+ ),+ open_purchase_orders AS (+ SELECT+ pol."itemId" AS "purchaseOrderItemId",+ SUM(pol."quantityToReceive" * pol."conversionFactor") AS "quantityOnPurchaseOrder"+ FROM+ "purchaseOrder" po+ INNER JOIN "purchaseOrderLine" pol+ ON pol."purchaseOrderId" = po."id"+ INNER JOIN job_materials jm+ ON jm."itemId" = pol."itemId"+ WHERE+ po."status" IN (+ 'To Receive',+ 'To Receive and Invoice'+ )+ AND po."companyId" = company_id+ AND pol."locationId" = location_id+ GROUP BY pol."itemId"+ ),+ open_sales_orders AS (+ SELECT+ sol."itemId" AS "salesOrderItemId",+ SUM(sol."quantityToSend") AS "quantityOnSalesOrder"+ FROM+ "salesOrder" so+ INNER JOIN "salesOrderLine" sol+ ON sol."salesOrderId" = so."id"+ INNER JOIN job_materials jm+ ON jm."itemId" = sol."itemId"+ WHERE+ so."status" IN (+ 'Confirmed',+ 'To Ship and Invoice',+ 'To Ship',+ 'To Invoice',+ 'In Progress'+ )+ AND so."companyId" = company_id+ AND sol."locationId" = location_id+ GROUP BY sol."itemId"+ ),+ open_jobs AS (+ SELECT+ j."itemId" AS "jobItemId",+ SUM(j."productionQuantity" + j."scrapQuantity" - j."quantityReceivedToInventory" - j."quantityShipped") AS "quantityOnProductionOrder"+ FROM job j+ WHERE j."status" IN (+ 'Ready',+ 'In Progress',+ 'Paused'+ )+ GROUP BY j."itemId"+ ),+ open_job_requirements AS (+ SELECT+ jm."itemId",+ jm."shelfId",+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemand"+ FROM "jobMaterial" jm+ INNER JOIN "job" j ON jm."jobId" = j."id"+ INNER JOIN job_materials jmat+ ON jmat."itemId" = jm."itemId"+ WHERE j."status" IN (+ 'Planned',+ 'Ready',+ 'In Progress',+ 'Paused'+ )+ AND jm."methodType" != 'Make'+ AND j."companyId" = company_id+ AND j."locationId" = location_id+ GROUP BY jm."itemId", jm."shelfId"+ ),+ open_job_requirements_in_shelf AS (+ SELECT+ ojr."itemId",+ SUM(ojr."quantityOnProductionDemand") AS "quantityOnProductionDemandInShelf"+ FROM open_job_requirements ojr+ INNER JOIN job_materials jm+ ON jm."itemId" = ojr."itemId" AND jm."shelfId" = ojr."shelfId"+ GROUP BY ojr."itemId"+ ),+ open_job_requirements_not_in_shelf AS (+ SELECT+ ojr."itemId",+ SUM(ojr."quantityOnProductionDemand") AS "quantityOnProductionDemandNotInShelf"+ FROM open_job_requirements ojr+ INNER JOIN job_materials jm+ ON jm."itemId" = ojr."itemId" AND (jm."shelfId" IS NULL OR jm."shelfId" != ojr."shelfId")+ GROUP BY ojr."itemId"+ ),+ item_ledgers AS (+ SELECT+ il."itemId" AS "ledgerItemId",+ il."shelfId",+ SUM(il."quantity") AS "quantityOnHand"+ FROM "itemLedger" il+ INNER JOIN job_materials jm+ ON jm."itemId" = il."itemId"+ WHERE il."companyId" = company_id+ AND il."locationId" = location_id+ GROUP BY il."itemId", il."shelfId"+ ),+ item_ledgers_in_shelf AS (+ SELECT+ il."ledgerItemId",+ SUM(il."quantityOnHand") AS "quantityOnHandInShelf"+ FROM item_ledgers il+ INNER JOIN job_materials jm+ ON jm."itemId" = il."ledgerItemId" AND jm."shelfId" = il."shelfId"+ GROUP BY il."ledgerItemId"+ ),+ item_ledgers_not_in_shelf AS (+ SELECT+ il."ledgerItemId",+ SUM(il."quantityOnHand") AS "quantityOnHandNotInShelf"+ FROM item_ledgers il+ INNER JOIN job_materials jm+ ON jm."itemId" = il."ledgerItemId" AND (jm."shelfId" IS NULL OR jm."shelfId" != il."shelfId")+ GROUP BY il."ledgerItemId"+ )++SELECT+ jm."id",+ jm."itemId" AS "jobMaterialItemId",+ jm."jobMakeMethodId",+ i."readableId" AS "itemReadableId",+ i."name",+ jm."description",+ i."itemTrackingType",+ jm."methodType",+ i."type",+ CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END AS "thumbnailPath",+ i."unitOfMeasureCode",+ jm."quantity" as "quantityPerParent",+ jm."estimatedQuantity",+ jm."quantityIssued",+ COALESCE(ils."quantityOnHandInShelf", 0) AS "quantityOnHandInShelf",+ COALESCE(ilns."quantityOnHandNotInShelf", 0) AS "quantityOnHandNotInShelf",+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",+ COALESCE(oj."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",+ COALESCE(ojis."quantityOnProductionDemandInShelf", 0) AS "quantityFromProductionOrderInShelf",+ COALESCE(ojns."quantityOnProductionDemandNotInShelf", 0) AS "quantityFromProductionOrderNotInShelf",+ s."name" AS "shelfName"+FROM+ job_materials jm+ INNER JOIN "item" i ON i."id" = jm."itemId"+ LEFT JOIN "shelf" s ON s."id" = jm."shelfId"+ LEFT JOIN item_ledgers_in_shelf ils ON i."id" = ils."ledgerItemId"+ LEFT JOIN item_ledgers_not_in_shelf ilns ON i."id" = ilns."ledgerItemId"+ LEFT JOIN open_sales_orders so ON i."id" = so."salesOrderItemId"+ LEFT JOIN open_purchase_orders po ON i."id" = po."purchaseOrderItemId"+ LEFT JOIN open_jobs oj ON i."id" = oj."jobItemId"+ LEFT JOIN open_job_requirements_in_shelf ojis ON i."id" = ojis."itemId"+ LEFT JOIN open_job_requirements_not_in_shelf ojns ON i."id" = ojns."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId";+ END;+$$ LANGUAGE plpgsql SECURITY DEFINER;