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(mcp): job materials created over the connector get their requirements recalc
Sidwebworks20c42b16851b
diff --git a/apps/erp/app/modules/production/production.mcp.server.ts b/apps/erp/app/modules/production/production.mcp.server.tsindex 32f03fc2ff..db9dea650b 100644--- a/apps/erp/app/modules/production/production.mcp.server.ts+++ b/apps/erp/app/modules/production/production.mcp.server.ts@@ -1,13 +1,20 @@import { hasPermission } from "@carbon/auth";import { getUserClaims } from "@carbon/auth/users.server";-import type { Database } from "@carbon/database";+import type { Database, Json } from "@carbon/database";import {evaluateLinesForSurface,isBlocked} from "@carbon/ee/storage-rules.server";import type { SupabaseClient } from "@supabase/supabase-js";+import type { z } from "zod";import { getDatabaseClient } from "~/services/database.server";-import { recalculateJobOperationDependencies } from "./production.service";+import type { jobMaterialValidator } from "./production.models";+import {+ pullJobMaterialMakeMethod,+ recalculateJobMakeMethodRequirements,+ recalculateJobOperationDependencies,+ upsertJobMaterial as upsertJobMaterialRow+} from "./production.service";// MCP-exposed production writes that depend on server-only modules// (`@carbon/auth/users.server`, `@carbon/ee/storage-rules.server`). These CANNOT@@ -175,3 +182,128 @@ export async function scheduleJob(userId});}++/**+ * Upsert a job material WITH the route-level orchestration the bare service+ * function lacks. Shadows `production.service.ts`'s `upsertJobMaterial` in the+ * MCP/API registry (the mcp.server spread wins), so the published tool name is+ * unchanged; the ERP routes keep calling the service directly and run this+ * orchestration themselves.+ *+ * Without this, a connector-created material sat at `estimatedQuantity = 0`+ * (the column default — the requirements recalc that fills it lives in the+ * ROUTES, not the service), and since `quantityToIssue` is GENERATED as+ * `estimatedQuantity - quantityIssued`, issue/picking pulled nothing.+ *+ * Mirrors `x+/job+/methods+/$jobId.material.new.tsx` and `.material.$id.tsx`:+ * - Make-to-Order pulls the subassembly's method — on create, and on the+ * TRANSITION into Make to Order only (a re-pull wipes existing edits).+ * - Create recalcs requirements + operation dependencies when the job is+ * already released (release itself recalcs the whole job, so Draft/Planned+ * creates match the UI: estimates fill at release).+ * - Update recalcs requirements ALWAYS; dependencies when the material is+ * Make to Order and tied to an operation.+ */+export async function upsertJobMaterial(+ client: SupabaseClient<Database>,+ jobMaterial:+ | (z.infer<typeof jobMaterialValidator> & {+ jobId: string;+ jobOperationId?: string;+ companyId: string;+ createdBy: string;+ customFields?: Json;+ })+ | (z.infer<typeof jobMaterialValidator> & {+ jobId: string;+ jobOperationId?: string;+ companyId: string;+ updatedBy: string;+ customFields?: Json;+ })+) {+ const isUpdate = "updatedBy" in jobMaterial;+ const userId = isUpdate ? jobMaterial.updatedBy : jobMaterial.createdBy;+ const { companyId, jobId } = jobMaterial;++ // The dependency recalc reaches the scheduling engine over Kysely (no RLS),+ // so the routes' production gate is re-applied here, like scheduleJob.+ const action = isUpdate ? ("update" as const) : ("create" as const);+ const claims = await getUserClaims(userId, companyId);+ if (!hasPermission(claims?.permissions, "production", action, companyId)) {+ throw new Error(+ `You do not have permission to ${action} job materials (production ${action}).`+ );+ }++ // Capture the previous methodType BEFORE the write — the make-method pull+ // runs only on the transition INTO "Make to Order".+ let wasMakeToOrder = false;+ if (isUpdate) {+ const existing = await client+ .from("jobMaterial")+ .select("methodType")+ .eq("id", jobMaterial.id)+ .eq("companyId", companyId)+ .single();+ if (existing.error) return existing;+ wasMakeToOrder = existing.data?.methodType === "Make to Order";+ }++ const upserted = await upsertJobMaterialRow(client, jobMaterial);+ if (upserted.error || !upserted.data) return upserted;+ const jobMaterialId = upserted.data.id;++ if (jobMaterial.methodType === "Make to Order" && !wasMakeToOrder) {+ const makeMethod = await pullJobMaterialMakeMethod(client, {+ jobMaterialId,+ itemId: jobMaterial.itemId,+ companyId,+ userId+ });+ if (makeMethod.error) {+ return { data: upserted.data, error: makeMethod.error };+ }+ }++ let recalcRequirements: boolean;+ let recalcDependencies: boolean;+ if (isUpdate) {+ recalcRequirements = true;+ recalcDependencies =+ jobMaterial.methodType === "Make to Order" &&+ Boolean(jobMaterial.jobOperationId);+ } else {+ const job = await client+ .from("job")+ .select("status")+ .eq("id", jobId)+ .single();+ const isReleased = !["Draft", "Planned"].includes(job.data?.status ?? "");+ recalcRequirements = isReleased;+ recalcDependencies = isReleased;+ }++ if (recalcRequirements) {+ const requirements = await recalculateJobMakeMethodRequirements(client, {+ id: jobMaterial.jobMakeMethodId,+ companyId,+ userId+ });+ if (requirements.error) {+ return { data: upserted.data, error: requirements.error };+ }+ }+ if (recalcDependencies) {+ const dependencies = await recalculateJobOperationDependencies(+ client,+ getDatabaseClient(),+ { jobId, companyId, userId }+ );+ if (dependencies?.error) {+ return { data: upserted.data, error: dependencies.error };+ }+ }++ return upserted;+}diff --git a/apps/erp/test/mcp-upsert-job-material.test.ts b/apps/erp/test/mcp-upsert-job-material.test.tsnew file mode 100644index 0000000000..d37dbc7c0b--- /dev/null+++ b/apps/erp/test/mcp-upsert-job-material.test.ts@@ -0,0 +1,172 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++// Pin the ORCHESTRATION the MCP wrapper adds over the bare service upsert —+// the routes run this themselves, so a connector call must reproduce it or+// imported materials sit at estimatedQuantity 0 (and the generated+// quantityToIssue 0 means issue/picking pulls nothing).++const upsertJobMaterialRow = vi.fn();+const pullJobMaterialMakeMethod = vi.fn();+const recalculateJobMakeMethodRequirements = vi.fn();+const recalculateJobOperationDependencies = vi.fn();++vi.mock("~/modules/production/production.service", () => ({+ upsertJobMaterial: (...args: unknown[]) => upsertJobMaterialRow(...args),+ pullJobMaterialMakeMethod: (...args: unknown[]) =>+ pullJobMaterialMakeMethod(...args),+ recalculateJobMakeMethodRequirements: (...args: unknown[]) =>+ recalculateJobMakeMethodRequirements(...args),+ recalculateJobOperationDependencies: (...args: unknown[]) =>+ recalculateJobOperationDependencies(...args)+}));+vi.mock("~/services/database.server", () => ({+ getDatabaseClient: () => ({}) as never+}));+vi.mock("@carbon/auth/users.server", () => ({+ getUserClaims: vi.fn(async () => ({+ permissions: {+ production_create: ["c1"],+ production_update: ["c1"]+ },+ role: "employee"+ }))+}));+vi.mock("@carbon/auth", () => ({+ hasPermission: (+ permissions: Record<string, string[]> | undefined,+ module: string,+ action: string,+ companyId: string+ ) => Boolean(permissions?.[`${module}_${action}`]?.includes(companyId))+}));+vi.mock("@carbon/ee/storage-rules.server", () => ({+ evaluateLinesForSurface: vi.fn(),+ isBlocked: vi.fn()+}));++import { upsertJobMaterial } from "~/modules/production/production.mcp.server";++/** A supabase client stub answering the wrapper's two reads. */+function makeClient(opts: {+ jobStatus?: string;+ existingMethodType?: string | null;+}) {+ return {+ from: (table: string) => ({+ select: () => ({+ eq: () => ({+ eq: () => ({+ single: async () => ({+ data: { methodType: opts.existingMethodType ?? null },+ error: null+ })+ }),+ single: async () => ({+ data: { status: opts.jobStatus ?? "Draft" },+ error: null+ })+ })+ })+ })+ } as never;+}++const base = {+ id: "jm1",+ description: "Bracket",+ jobMakeMethodId: "jmm1",+ itemType: "Part" as const,+ methodType: "Pull from Inventory" as const,+ itemId: "item1",+ kit: false,+ order: 1,+ quantity: 2,+ requiresBatchTracking: false,+ requiresSerialTracking: false,+ unitCost: 0,+ unitOfMeasureCode: "EA",+ jobId: "job1",+ companyId: "c1"+};++beforeEach(() => {+ vi.clearAllMocks();+ upsertJobMaterialRow.mockResolvedValue({+ data: { id: "jm1", methodType: "Pull from Inventory" },+ error: null+ });+ pullJobMaterialMakeMethod.mockResolvedValue({ data: {}, error: null });+ recalculateJobMakeMethodRequirements.mockResolvedValue({+ data: {},+ error: null+ });+ recalculateJobOperationDependencies.mockResolvedValue({+ data: {},+ error: null+ });+});++describe("MCP upsertJobMaterial orchestration", () => {+ it("create on a Draft job inserts without recalc (release fills estimates, like the UI)", async () => {+ const result = await upsertJobMaterial(makeClient({ jobStatus: "Draft" }), {+ ...base,+ createdBy: "u1"+ });+ expect(result.error).toBeNull();+ expect(upsertJobMaterialRow).toHaveBeenCalledOnce();+ expect(recalculateJobMakeMethodRequirements).not.toHaveBeenCalled();+ expect(recalculateJobOperationDependencies).not.toHaveBeenCalled();+ });++ it("create on a released job recalcs requirements and dependencies", async () => {+ await upsertJobMaterial(makeClient({ jobStatus: "Ready" }), {+ ...base,+ createdBy: "u1"+ });+ expect(recalculateJobMakeMethodRequirements).toHaveBeenCalledWith(+ expect.anything(),+ { id: "jmm1", companyId: "c1", userId: "u1" }+ );+ expect(recalculateJobOperationDependencies).toHaveBeenCalledOnce();+ });++ it("update always recalcs requirements; dependencies only for op-linked Make to Order", async () => {+ await upsertJobMaterial(+ makeClient({ existingMethodType: "Pull from Inventory" }),+ { ...base, updatedBy: "u1" }+ );+ expect(recalculateJobMakeMethodRequirements).toHaveBeenCalledOnce();+ expect(recalculateJobOperationDependencies).not.toHaveBeenCalled();+ });++ it("pulls the subassembly method only on the transition INTO Make to Order", async () => {+ await upsertJobMaterial(+ makeClient({ existingMethodType: "Make to Order" }),+ { ...base, methodType: "Make to Order", updatedBy: "u1" }+ );+ expect(pullJobMaterialMakeMethod).not.toHaveBeenCalled();++ await upsertJobMaterial(+ makeClient({ existingMethodType: "Pull from Inventory" }),+ {+ ...base,+ methodType: "Make to Order",+ jobOperationId: "op1",+ updatedBy: "u1"+ }+ );+ expect(pullJobMaterialMakeMethod).toHaveBeenCalledOnce();+ expect(recalculateJobOperationDependencies).toHaveBeenCalledOnce();+ });++ it("refuses a user without the production permission", async () => {+ await expect(+ upsertJobMaterial(makeClient({}), {+ ...base,+ companyId: "other-company",+ createdBy: "u1"+ })+ ).rejects.toThrow(/permission/);+ expect(upsertJobMaterialRow).not.toHaveBeenCalled();+ });+});