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
Bug fixes (#1196)
Anshul sharma224b8dcdd7c9
diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsxindex 5d9c2bd7b8..3e48d434f1 100644--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx@@ -25,6 +25,7 @@ import {LuCirclePlay,LuClipboardCheck,LuDollarSign,+ LuGitPullRequestArrow,LuGraduationCap,LuHammer,LuInbox,@@ -208,6 +209,16 @@ function GenericNotification({{...props}/>);+ case NotificationEvent.ChangeOrderStarted:+ case NotificationEvent.ChangeOrderImplementation:+ case NotificationEvent.ChangeOrderDone:+ return (+ <Notification+ icon={<LuGitPullRequestArrow />}+ to={path.to.changeOrderDetails(id)}+ {...props}+ />+ );case NotificationEvent.DigitalQuoteResponse:return (<Notificationdiff --git a/apps/erp/app/modules/items/items.server.ts b/apps/erp/app/modules/items/items.server.tsindex e54ae462cb..0e7619c03f 100644--- a/apps/erp/app/modules/items/items.server.ts+++ b/apps/erp/app/modules/items/items.server.ts@@ -194,23 +194,41 @@ export const changeOrderStageEvent: Record<string, NotificationEvent> = {Done: NotificationEvent.ChangeOrderDone};-// notifyChangeOrderTransition — broadcasts a stage transition to the whole-// company team (PRD §3.1 "Broadcast to team"). The recipient is the company-// employee group; the `notify` job expands it via the users_for_groups RPC.-// Best-effort: never throws into the caller's redirect path.+// Broadcasts a CO stage to the whole team (best-effort). Recipient is the seeded+// "All Employees" group — NOT companyGroupId, which is the currency/subsidiary+// grouping and has no user members.export async function notifyChangeOrderTransition(args: {+ client: SupabaseClient<Database>;event: NotificationEvent;changeOrderId: string;companyId: string;- companyGroupId: string;userId: string;}): Promise<void> {try {+ const employeeGroup = await args.client+ .from("group")+ .select("id")+ .eq("companyId", args.companyId)+ .eq("isEmployeeTypeGroup", true)+ .eq("name", "All Employees")+ .single();++ if (employeeGroup.error || !employeeGroup.data) {+ logger.error(+ "Failed to resolve All Employees group for CO notification",+ {+ error: employeeGroup.error,+ companyId: args.companyId+ }+ );+ return;+ }+await trigger("notify", {event: args.event,companyId: args.companyId,documentId: args.changeOrderId,- recipient: { type: "group", groupIds: [args.companyGroupId] },+ recipient: { type: "group", groupIds: [employeeGroup.data.id] },from: args.userId});} catch (e) {diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsxindex 85f41945f3..75bfbb8a06 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx@@ -719,6 +719,18 @@ function MaterialForm({item.data.item?.replenishmentSystem ?? replenishmentSystem ?? "Buy"});+ // methodType/sourcingType are read-only mirrors of the component item+ // (see method-material-sourcing rule). Re-sync them when the loader row+ // changes — e.g. after the properties panel updates the default method type —+ // since the useState initializer above only runs at mount.+ useEffect(() => {+ setItemData((d) => ({+ ...d,+ methodType: item.data.methodType ?? "Pull from Inventory",+ sourcingType: item.data.sourcingType ?? "Specified"+ }));+ }, [item.data.methodType, item.data.sourcingType]);+const onTypeChange = (value: MethodItemType | "Item") => {if (value === itemType) return;setItemType(value as MethodItemType);diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex c76008a4a0..61bd150cf5 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -3218,6 +3218,48 @@ export async function upsertJobMaterialMakeMethod(return { data: null, error: null };}+/**+ * Resolve a job material's child make-method id and pull its source item's+ * method (BOM + operations) into it. Shared by the job-material create and edit+ * routes: both flip a material to "Make to Order" and must populate the newly+ * created child make method.+ */+export async function pullJobMaterialMakeMethod(+ client: SupabaseClient<Database>,+ args: {+ jobMaterialId: string;+ itemId: string;+ companyId: string;+ userId: string;+ }+) {+ const materialMakeMethod = await client+ .from("jobMaterialWithMakeMethodId")+ .select("jobMaterialMakeMethodId")+ .eq("id", args.jobMaterialId)+ .eq("companyId", args.companyId)+ .single();++ if (+ materialMakeMethod.error ||+ !materialMakeMethod.data?.jobMaterialMakeMethodId+ ) {+ return {+ data: null,+ error: (materialMakeMethod.error ?? {+ message: "Failed to resolve job material make method"+ }) as PostgrestError+ };+ }++ return upsertJobMaterialMakeMethod(client, {+ sourceId: args.itemId,+ targetId: materialMakeMethod.data.jobMaterialMakeMethodId,+ companyId: args.companyId,+ userId: args.userId+ });+}+export async function upsertMakeMethodFromJob(client: SupabaseClient<Database>,jobMethod: {diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionForm.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionForm.tsxindex 86e7536d08..ae308f5152 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionForm.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionForm.tsx@@ -18,6 +18,7 @@ import { LuCircleCheck, LuInfo, LuTriangleAlert } from "react-icons/lu";import type { z } from "zod";import { Hidden, Item, Submit } from "~/components/Form";import { usePermissions } from "~/hooks";+import type { MethodItemType } from "~/modules/shared";import { path } from "~/utils/path";import {assemblyInstructionFromItemValidator,@@ -51,6 +52,8 @@ const AssemblyInstructionForm = ({state: "idle"});+ const [itemType, setItemType] = useState<MethodItemType | "Item">("Item");+// Mirrors getModelForItem on the server: conversion is lazy, so any STEP// model is usable — the state just tells the user what will happen on saveconst checkModel = useCallback(@@ -174,7 +177,8 @@ const AssemblyInstructionForm = ({<Itemname="itemId"label="Item"- type="Item"+ type={itemType}+ onTypeChange={setItemType}replenishmentSystem="Make"onChange={(selected) => {checkModel(selected?.value ?? "");diff --git a/apps/erp/app/routes/api+/link.ts b/apps/erp/app/routes/api+/link.tsindex 1c34db3ec3..1270aa49ff 100644--- a/apps/erp/app/routes/api+/link.ts+++ b/apps/erp/app/routes/api+/link.ts@@ -63,10 +63,9 @@ function resolve(return path.to.gauge(documentId);case NotificationEvent.NonConformanceAssignment:return path.to.issue(documentId);- case NotificationEvent.ChangeOrderApproved:- case NotificationEvent.ChangeOrderRejected:- case NotificationEvent.ChangeOrderReleased:- case NotificationEvent.ChangeOrderSubmittedForReview:+ case NotificationEvent.ChangeOrderStarted:+ case NotificationEvent.ChangeOrderImplementation:+ case NotificationEvent.ChangeOrderDone:return path.to.changeOrderDetails(documentId);case NotificationEvent.RiskAssignment:return path.to.risk(documentId);diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex a0bf4d5b26..5dd93a33d6 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,6 +1,6 @@{- "generated": "2026-07-22T10:02:02.348Z",- "totalTools": 1374,+ "generated": "2026-07-22T10:57:38.910Z",+ "totalTools": 1375,"modules": 15,"tools": [{@@ -20864,6 +20864,35 @@]}},+ {+ "name": "production_pullJobMaterialMakeMethod",+ "module": "production",+ "classification": "WRITE",+ "description": "pull job material make method",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "jobMaterialId": {+ "type": "string"+ },+ "itemId": {+ "type": "string"+ }+ },+ "required": [+ "jobMaterialId",+ "itemId"+ ]+ }+ },{"name": "production_upsertMakeMethodFromJob","module": "production",diff --git a/apps/erp/app/routes/x+/items+/change-order+/$id.status.tsx b/apps/erp/app/routes/x+/items+/change-order+/$id.status.tsxindex 56503ecfb9..24fed3fac2 100644--- a/apps/erp/app/routes/x+/items+/change-order+/$id.status.tsx+++ b/apps/erp/app/routes/x+/items+/change-order+/$id.status.tsx@@ -19,10 +19,9 @@ import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId, companyId, companyGroupId } =- await requirePermissions(request, {- update: "parts"- });+ const { client, userId, companyId } = await requirePermissions(request, {+ update: "parts"+ });const { id } = params;if (!id) throw new Error("Could not find id");@@ -81,10 +80,10 @@ export async function action({ request, params }: ActionFunctionArgs) {// (Start / Implementation / Done). Best-effort; never blocks the redirect.if (changeOrderBroadcastStages.includes(toStatus)) {await notifyChangeOrderTransition({+ client,event: changeOrderStageEvent[toStatus],changeOrderId: id,companyId,- companyGroupId,userId});}diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsxindex 18256bd5f4..887c232b36 100644--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx@@ -6,6 +6,7 @@ import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import {jobMaterialValidator,+ pullJobMaterialMakeMethod,recalculateJobMakeMethodRequirements,recalculateJobOperationDependencies,upsertJobMaterial@@ -35,6 +36,26 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}+ // Capture the previous methodType so we only pull the subassembly's method on+ // the transition INTO "Make to Order" (not on every save of a material that is+ // already Make to Order — that would re-pull and wipe existing edits).+ const existingMaterial = await client+ .from("jobMaterial")+ .select("methodType")+ .eq("id", id)+ .eq("companyId", companyId)+ .single();+ if (existingMaterial.error) {+ return data(+ { id: null },+ await flash(+ request,+ error(existingMaterial.error, "Failed to load job material")+ )+ );+ }+ const wasMakeToOrder = existingMaterial.data?.methodType === "Make to Order";+const updateJobMaterial = await upsertJobMaterial(client, {jobId,...validation.data,@@ -68,6 +89,28 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // On transition Pull/Purchase → Make to Order, pull the subassembly's method+ // (BOM + operations) into the newly-created child make method, mirroring the+ // create route. Without this the material flips to Make to Order but stays empty.+ // `client` here is already service-role (requirePermissions bypassRls).+ if (validation.data.methodType === "Make to Order" && !wasMakeToOrder) {+ const makeMethod = await pullJobMaterialMakeMethod(client, {+ jobMaterialId,+ itemId: validation.data.itemId,+ companyId,+ userId+ });+ if (makeMethod.error) {+ return data(+ { id: jobMaterialId },+ await flash(+ request,+ error(makeMethod.error, "Failed to insert job material make method")+ )+ );+ }+ }+if (validation.data.methodType === "Make to Order") {const promises = [recalculateJobMakeMethodRequirements(client, {diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsxindex 8cbeb98156..1a2ef8da40 100644--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx@@ -7,10 +7,10 @@ import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import {jobMaterialValidator,+ pullJobMaterialMakeMethod,recalculateJobMakeMethodRequirements,recalculateJobOperationDependencies,- upsertJobMaterial,- upsertJobMaterialMakeMethod+ upsertJobMaterial} from "~/modules/production";import { setCustomFields } from "~/utils/form";@@ -74,25 +74,9 @@ export async function action({ request, params }: ActionFunctionArgs) {const isReleased = !["Draft", "Planned"].includes(job.data?.status ?? "");if (validation.data.methodType === "Make to Order") {- const materialMakeMethod = await serviceRole- .from("jobMaterialWithMakeMethodId")- .select("*")- .eq("id", jobMaterialId)- .single();- if (materialMakeMethod.error) {- return data(- {- id: null- },- await flash(- request,- error(materialMakeMethod.error, "Failed to get material make method")- )- );- }- const makeMethod = await upsertJobMaterialMakeMethod(serviceRole, {- sourceId: validation.data.itemId,- targetId: materialMakeMethod.data?.jobMaterialMakeMethodId!,+ const makeMethod = await pullJobMaterialMakeMethod(serviceRole, {+ jobMaterialId,+ itemId: validation.data.itemId,companyId,userId});diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.tsindex d659a8a825..ce3cb1b3e1 100644--- a/packages/database/supabase/functions/get-method/index.ts+++ b/packages/database/supabase/functions/get-method/index.ts@@ -1472,7 +1472,7 @@ serve(async (req: Request) => {requiresSerialTracking:child.data.itemTrackingType === "Serial",unitOfMeasureCode: child.data.unitOfMeasureCode,- unitCost: child.data.unitCost,+ unitCost: child.data.unitCost ?? 0,itemScrapPercentage,storageUnitId: await getStorageUnitId(trx,@@ -4796,7 +4796,7 @@ serve(async (req: Request) => {quantity: child.data.quantity,storageUnitId: child.data.storageUnitId,unitOfMeasureCode: child.data.unitOfMeasureCode,- unitCost: child.data.unitCost, // TODO: get unit cost+ unitCost: child.data.unitCost ?? 0, // TODO: get real unit costcompanyId,createdBy: userId,customFields: {},@@ -5283,7 +5283,7 @@ serve(async (req: Request) => {],quantity: child.data.quantity,storageUnitId: child.data.storageUnitId,- unitCost: child.data.unitCost, // TODO: get unit cost+ unitCost: child.data.unitCost ?? 0, // TODO: get real unit costunitOfMeasureCode: child.data.unitOfMeasureCode,companyId,createdBy: userId,diff --git a/packages/jobs/src/inngest/functions/notifications/content.ts b/packages/jobs/src/inngest/functions/notifications/content.tsindex f5f14de507..6624949c5a 100644--- a/packages/jobs/src/inngest/functions/notifications/content.ts+++ b/packages/jobs/src/inngest/functions/notifications/content.ts@@ -110,6 +110,20 @@ type EventContentOptions = {userId?: string;};+function changeOrderStageDescription(+ type: NotificationEvent,+ readableId: string+): string {+ switch (type) {+ case NotificationEvent.ChangeOrderStarted:+ return `Change order ${readableId} has started`;+ case NotificationEvent.ChangeOrderImplementation:+ return `Change order ${readableId} has moved to implementation`;+ default:+ return `Change order ${readableId} is complete`;+ }+}+async function buildEventContent(client: ReturnType<typeof getCarbonServiceRole>,type: NotificationEvent,@@ -1032,7 +1046,9 @@ async function buildEventContent(}return {- description: `Quality document "${qd.data.name ?? "Untitled"}" ${docPhrase}`,+ description: `Quality document "${+ qd.data.name ?? "Untitled"+ }" ${docPhrase}`,details: buildDetails([{label: "Version",@@ -1052,36 +1068,56 @@ async function buildEventContent(};}- case NotificationEvent.ChangeOrderSubmittedForReview:- case NotificationEvent.ChangeOrderApproved:- case NotificationEvent.ChangeOrderRejected:- case NotificationEvent.ChangeOrderReleased: {- const changeOrder = await client+ case NotificationEvent.ChangeOrderStarted:+ case NotificationEvent.ChangeOrderImplementation:+ case NotificationEvent.ChangeOrderDone: {+ // Company-scope both lookups: readable ids (ECO-…) repeat across tenants.+ const companyId = opts?.companyId;+ if (!companyId) {+ throw new Error(+ `companyId is required to resolve change order ${documentId}`+ );+ }++ // documentId may be the row id (co_…) or the readable id (ECO-…) — try both.+ const rowLookup = await client.from("changeOrder").select("changeOrderId, status").eq("id", documentId)- .single();+ .eq("companyId", companyId)+ .maybeSingle();+ if (rowLookup.error) {+ console.error("Failed to get changeOrder", rowLookup.error);+ throw rowLookup.error;+ }++ let changeOrderData = rowLookup.data;+ if (!changeOrderData) {+ const readableIdLookup = await client+ .from("changeOrder")+ .select("changeOrderId, status")+ .eq("changeOrderId", documentId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (readableIdLookup.error) {+ console.error("Failed to get changeOrder", readableIdLookup.error);+ throw readableIdLookup.error;+ }+ changeOrderData = readableIdLookup.data;+ }- if (changeOrder.error || !changeOrder.data) {- console.error("Failed to get changeOrder", changeOrder.error);- throw changeOrder.error;+ if (!changeOrderData) {+ throw new Error(`Change order not found for documentId ${documentId}`);}- const readableId = changeOrder.data.changeOrderId;- const description =- type === NotificationEvent.ChangeOrderSubmittedForReview- ? `Change order ${readableId} is ready for your review`- : type === NotificationEvent.ChangeOrderApproved- ? `Change order ${readableId} was approved`- : type === NotificationEvent.ChangeOrderRejected- ? `Change order ${readableId} was rejected`- : `Change order ${readableId} was released`;+ const readableId = changeOrderData.changeOrderId;+ const description = changeOrderStageDescription(type, readableId);return {description,reference: readableId ?? undefined,details: buildDetails([- { label: "Status", value: changeOrder.data?.status }+ { label: "Status", value: changeOrderData?.status }])};}diff --git a/packages/jobs/src/inngest/functions/notifications/notify.ts b/packages/jobs/src/inngest/functions/notifications/notify.tsindex a9b859a66b..c670e5cc76 100644--- a/packages/jobs/src/inngest/functions/notifications/notify.ts+++ b/packages/jobs/src/inngest/functions/notifications/notify.ts@@ -62,19 +62,15 @@ const defaultDestinations: Partial<NotificationDestination.Email,NotificationDestination.Slack],- [NotificationEvent.ChangeOrderApproved]: [+ [NotificationEvent.ChangeOrderStarted]: [NotificationDestination.Email,NotificationDestination.Slack],- [NotificationEvent.ChangeOrderRejected]: [+ [NotificationEvent.ChangeOrderImplementation]: [NotificationDestination.Email,NotificationDestination.Slack],- [NotificationEvent.ChangeOrderReleased]: [- NotificationDestination.Email,- NotificationDestination.Slack- ],- [NotificationEvent.ChangeOrderSubmittedForReview]: [+ [NotificationEvent.ChangeOrderDone]: [NotificationDestination.Email,NotificationDestination.Slack],diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.tsindex 861c34d4bb..e8c2f46fb7 100644--- a/packages/notifications/src/index.ts+++ b/packages/notifications/src/index.ts@@ -8,12 +8,7 @@ export enum NotificationEvent {ApprovalApproved = "approval-approved",ApprovalRejected = "approval-rejected",ApprovalRequested = "approval-requested",- ChangeOrderApproved = "change-order-approved",- ChangeOrderRejected = "change-order-rejected",- ChangeOrderReleased = "change-order-released",- ChangeOrderSubmittedForReview = "change-order-submitted-for-review",- // Stage-broadcast events (V1 standalone Change Orders module) — fired to the- // company team on entry to Start / Implementation / Done.+ // Change-order stage broadcasts (the only CO events; no approval flow in v1).ChangeOrderStarted = "change-order-started",ChangeOrderImplementation = "change-order-implementation",ChangeOrderDone = "change-order-done",@@ -54,6 +49,7 @@ export enum NotificationTopic {Approval = "approval",General = "general",Inventory = "inventory",+ Items = "items",Job = "job",Maintenance = "maintenance",Purchasing = "purchasing",@@ -140,14 +136,11 @@ export function getNotificationTopic(case NotificationEvent.ApprovalApproved:case NotificationEvent.ApprovalRejected:case NotificationEvent.ApprovalRequested:- case NotificationEvent.ChangeOrderApproved:- case NotificationEvent.ChangeOrderRejected:- case NotificationEvent.ChangeOrderReleased:- case NotificationEvent.ChangeOrderSubmittedForReview:+ return NotificationTopic.Approval;case NotificationEvent.ChangeOrderStarted:case NotificationEvent.ChangeOrderImplementation:case NotificationEvent.ChangeOrderDone:- return NotificationTopic.Approval;+ return NotificationTopic.Items;default:return NotificationTopic.General;}@@ -217,14 +210,6 @@ export function getNotificationEmailHeading(event: NotificationEvent): string {return "Your request was approved";case NotificationEvent.ApprovalRejected:return "Your request was rejected";- case NotificationEvent.ChangeOrderSubmittedForReview:- return "Change order ready for review";- case NotificationEvent.ChangeOrderApproved:- return "Change order approved";- case NotificationEvent.ChangeOrderRejected:- return "Change order rejected";- case NotificationEvent.ChangeOrderReleased:- return "Change order released";case NotificationEvent.ChangeOrderStarted:return "Change order started";case NotificationEvent.ChangeOrderImplementation:@@ -245,11 +230,6 @@ export function getNotificationEmailCtaLabel(event: NotificationEvent): string {case NotificationEvent.ApprovalApproved:case NotificationEvent.ApprovalRejected:return "View decision";- case NotificationEvent.ChangeOrderSubmittedForReview:- return "Review change order";- case NotificationEvent.ChangeOrderApproved:- case NotificationEvent.ChangeOrderRejected:- case NotificationEvent.ChangeOrderReleased:case NotificationEvent.ChangeOrderStarted:case NotificationEvent.ChangeOrderImplementation:case NotificationEvent.ChangeOrderDone:@@ -294,6 +274,8 @@ export function getNotificationTopicPhrase(return `${count} training ${plural}`;case NotificationTopic.Inventory:return `${count} inventory ${plural}`;+ case NotificationTopic.Items:+ return `${count} item ${plural}`;case NotificationTopic.Suggestion:return `${count} suggestion ${plural}`;case NotificationTopic.Approval: