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.

fix: configured BOMs in MRP and in jobs and quotes (#1968)

Brad Barbinf9d7efd2788b
diff --git a/.claude/rules/mrp-system.md b/.claude/rules/mrp-system.md
index 470cd1553b..46e7c8485c 100644
--- a/.claude/rules/mrp-system.md
+++ b/.claude/rules/mrp-system.md
@@ -208,7 +208,10 @@ Phase-7 write) and throws on failure.
`packages/database/src/mrp-engine.test.ts`.
- **BOM explosion**: for `Make` items, explodes the active make method to
derive child demand with low-level-code ordering, per-period inventory
- netting, and lead-time offsetting.
+ netting, and lead-time offsetting. A line with quantity 0 is left out
+ (`bomChildren`, `packages/planning/src/mrp/bom-children.ts`), never
+ defaulted to 1: a configured item carries every configuration's lines at 0
+ except the default's, and `|| 1` exploded all of them per parent.
- **Outputs (DB writes)**: deletes prior MRP forecast rows — including EVERY
`supplyForecast` row at the company's locations (MRP never inserts
`supplyForecast`; the planning.update routes do) — then batch-inserts
diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.md
index c3325c5221..801779e4a6 100644
--- a/apps/erp/app/modules/items/AGENTS.md
+++ b/apps/erp/app/modules/items/AGENTS.md
@@ -75,6 +75,7 @@ pnpm --filter erp test
- `getSupplierPartsBySupplier` — every active supplier part naming one supplier, with its item embedded, paged past the 1000-row cap (`fetchAllRecords`); backs the supplier's **Parts** tab (`x+/supplier+/$supplierId.parts.tsx`, `purchasing/ui/Supplier/SupplierParts.tsx`, client-side search). Its New / edit drawers post to the picked item's own purchasing routes (`SupplierPartForm` with `selectItem`), so every item-type create and edit route returns the `createSupplierPart` / `updateSupplierPart` result instead of redirecting
- `upsertPickMethodWithShelfLife` — pick method with shelf life configuration
- `getConfigurationParameters` / `getConfigurationRules` — product configurator
+ - A rule on `itemId:<methodMaterialId>` returns an item **id** (not a readable id). On a Make to Order line the job or quote explodes the configured item's active make method, not the BOM item's (`configuredMadeChild` in `production.service.ts`, all four `getMethod` paths); a configured item with no make method leaves the line with no sub-assembly.
- `createItemDocumentUploadUrl` — MCP file upload (step 1): presigned URL for an item document (`parts/{itemId}` folder); pair with `documents_insertUploadedDocument`. See `.claude/rules/mcp-tools-reference.md` → "File uploads"
- `createModelUploadUrl` / `insertModelUpload` — the API/MCP CAD model upload, and the one path the browser's `api+/model.upload.ts` shares: step 1 signs an upload into `temp-staging` (2.5 GB, where the dropzone stages raw CAD) at `${companyId}/models/${modelId}.${ext}`; step 2 records the `modelUpload` row, links it to any of `itemId` / `jobId` / `salesRfqLineId` / `quoteLineId` / `salesOrderLineId` (each checked first, all scoped by `companyId`), and starts `assembly-convert` for a STEP file with `convert`. The insert itself starts `model-optimize`: the `queue_model_pipeline` statement handler on `modelUpload` sends it for every new row, whoever inserts it, so no caller sends it. No transaction spans the row and the links: a failed link returns an error, the model row stands and is still processed
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index de2a63c775..052642b0d7 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -14512,10 +14512,20 @@ export async function getMethod(
// material at the successor and explode the SUCCESSOR's method
// (not the old part's). A Make -> Buy successor is a structural
// flip we leave on the old part (handled/flagged elsewhere).
- const madeSwapHandled = await swapMadeSubAssembly({
+ // A configuration rule may have moved this line onto another
+ // made item; the sub-assembly under it is then that item's.
+ const made = await configuredMadeChild(
trx,
companyId,
child,
+ material?.itemId
+ );
+ if (!made) continue;
+
+ const madeSwapHandled = await swapMadeSubAssembly({
+ trx,
+ companyId,
+ child: made,
material,
materialId,
locationId: job.locationId ?? "",
@@ -14525,9 +14535,9 @@ export async function getMethod(
});
// prevent an infinite loop
- if (!madeSwapHandled && child!.data.itemId !== itemId) {
+ if (!madeSwapHandled && made.data.itemId !== itemId) {
await traverseMethod(
- child,
+ made,
newMakeMethodId,
childTotalForCascade || 1
);
@@ -15268,10 +15278,20 @@ export async function getMethod(
// if a made component has an effective successor that is itself
// made, point the job material at the successor and explode the
// SUCCESSOR's method instead of the old part's.
- const madeSwapHandled = await swapMadeSubAssembly({
+ // A configuration rule may have moved this line onto another
+ // made item; the sub-assembly under it is then that item's.
+ const made = await configuredMadeChild(
trx,
companyId,
child,
+ material?.itemId
+ );
+ if (!made) continue;
+
+ const madeSwapHandled = await swapMadeSubAssembly({
+ trx,
+ companyId,
+ child: made,
material,
materialId,
locationId: job.data?.locationId ?? "",
@@ -15281,9 +15301,9 @@ export async function getMethod(
});
// prevent an infinite loop
- if (!madeSwapHandled && child.data.itemId !== itemId) {
+ if (!madeSwapHandled && made.data.itemId !== itemId) {
await traverseMethod(
- child,
+ made,
newMakeMethodId,
childTotalForCascade || 1
);
@@ -16103,9 +16123,26 @@ export async function getMethod(
}
);
+ // A configuration rule may have moved this line onto another
+ // made item; the sub-assembly under it is then that item's.
+ const made = await configuredMadeChild(
+ trx,
+ companyId,
+ child!,
+ madeMaterialsWithIds[index]!.itemId
+ );
+ if (!made) continue;
+ if (made !== child) {
+ for (const [id, ops] of await readOperationsForTree(
+ trx,
+ made
+ ))
+ treeOperations.set(id, ops);
+ }
+
// prevent an infinite loop
- if (child!.data.itemId !== itemId) {
- await traverseMethod(child, newMakeMethodId);
+ if (made.data.itemId !== itemId) {
+ await traverseMethod(made, newMakeMethodId);
}
}
}
@@ -16518,9 +16555,26 @@ export async function getMethod(
for (const [index, child] of madeChildren.entries()) {
const newMakeMethodId = newMakeMethodIds[index]!;
+ // A configuration rule may have moved this line onto another
+ // made item; the sub-assembly under it is then that item's.
+ const made = await configuredMadeChild(
+ trx,
+ companyId,
+ child,
+ madeMaterialsWithIds[index]!.itemId
+ );
+ if (!made) continue;
+ if (made !== child) {
+ for (const [id, ops] of await readOperationsForTree(
+ trx,
+ made
+ ))
+ treeOperations.set(id, ops);
+ }
+
// prevent an infinite loop
- if (child.data.itemId !== itemId) {
- await traverseMethod(child, newMakeMethodId);
+ if (made.data.itemId !== itemId) {
+ await traverseMethod(made, newMakeMethodId);
}
}
}
@@ -20744,6 +20798,50 @@ async function itemDerivedJobMaterialFields(opts: {
// scaling the cascade by the conversion factor. A Make -> Buy successor is a
// structural flip we leave on the old part (handled elsewhere). Returns true when
// the swap was applied, so the caller can skip the default traversal.
+/**
+ * The tree a made line explodes into. A configuration rule can move a Make to
+ * Order line onto another item (a 14 ft body where the BOM names the 12 ft
+ * one); the line is then that item's, and so is the sub-assembly under it.
+ * Exploding `child` as it stood built the BOM item's sub-assembly under the
+ * configured item. The line's own fields (quantity, operation, order, the
+ * row's ids) stay the BOM line's; the item and its method become the
+ * configured item's. Undefined when the configured item has no make method:
+ * there is nothing of its own to explode, and the BOM item's would be wrong.
+ */
+async function configuredMadeChild(
+ trx: Transaction<KyselyDatabase>,
+ companyId: string,
+ child: MethodTreeItem,
+ itemId: string | null | undefined
+): Promise<MethodTreeItem | undefined> {
+ if (!itemId || itemId === child.data.itemId) return child;
+ const method = await trx
+ .selectFrom("activeMakeMethods")
+ .select(["id"])
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!method?.id) return undefined;
+ const root = (await getMethodTree(trx, method.id)).data?.[0];
+ if (!root) return undefined;
+ return {
+ id: child.id,
+ data: {
+ ...child.data,
+ itemId: root.data.itemId,
+ itemReadableId: root.data.itemReadableId,
+ itemTrackingType: root.data.itemTrackingType,
+ itemType: root.data.itemType,
+ materialMakeMethodId: root.data.materialMakeMethodId,
+ replenishmentSystem: root.data.replenishmentSystem,
+ revision: root.data.revision,
+ unitCost: root.data.unitCost,
+ version: root.data.version
+ },
+ children: root.children
+ };
+}
+
async function swapMadeSubAssembly(opts: {
trx: Transaction<KyselyDatabase>;
companyId: string;
diff --git a/packages/planning/src/mrp/bom-children.test.ts b/packages/planning/src/mrp/bom-children.test.ts
new file mode 100644
index 0000000000..abc49b01e1
--- /dev/null
+++ b/packages/planning/src/mrp/bom-children.test.ts
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import { bomChildren } from "./bom-children.ts";
+
+describe("bomChildren", () => {
+ it("keeps each line's quantity", () => {
+ expect(
+ bomChildren([
+ { itemId: "ring", quantity: 4, methodType: "Pull from Inventory" },
+ { itemId: "steel", quantity: "12.5", methodType: "Pull from Inventory" }
+ ])
+ ).toEqual([
+ { itemId: "ring", quantity: 4, methodType: "Pull from Inventory" },
+ { itemId: "steel", quantity: 12.5, methodType: "Pull from Inventory" }
+ ]);
+ });
+
+ it("leaves out lines with no quantity instead of counting them as one", () => {
+ // A configured trailer: the default body at 1, the other configurations at 0.
+ expect(
+ bomChildren([
+ { itemId: "body-12ft", quantity: 1, methodType: "Make to Order" },
+ { itemId: "body-14ft", quantity: 0, methodType: "Make to Order" },
+ { itemId: "body-16ft", quantity: "0", methodType: "Make to Order" },
+ { itemId: "unset", quantity: null, methodType: "Pull from Inventory" }
+ ])
+ ).toEqual([
+ { itemId: "body-12ft", quantity: 1, methodType: "Make to Order" }
+ ]);
+ });
+});
diff --git a/packages/planning/src/mrp/bom-children.ts b/packages/planning/src/mrp/bom-children.ts
new file mode 100644
index 0000000000..0c329f737b
--- /dev/null
+++ b/packages/planning/src/mrp/bom-children.ts
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { BomChild, MethodType } from "@carbon/database/mrp-engine";
+
+export type MethodMaterialRow = {
+ itemId: string;
+ quantity: number | string | null;
+ methodType: MethodType | string;
+};
+
+// A make method's lines as BOM children for explosion. A line whose quantity
+// is zero (or missing) consumes nothing and is left out — it must not default
+// to one. A configured item holds every configuration's lines at quantity 0
+// except the default's; defaulting them to 1 exploded every configuration at
+// once (24 dump bodies per trailer).
+export function bomChildren(materials: MethodMaterialRow[]): BomChild[] {
+ const children: BomChild[] = [];
+ for (const mat of materials) {
+ const quantity = Number(mat.quantity);
+ if (!(quantity > 0)) continue;
+ children.push({
+ itemId: mat.itemId,
+ quantity,
+ methodType: mat.methodType as MethodType
+ });
+ }
+ return children;
+}
diff --git a/packages/planning/src/mrp/mrp.ts b/packages/planning/src/mrp/mrp.ts
index a735756614..961f2aa393 100644
--- a/packages/planning/src/mrp/mrp.ts
+++ b/packages/planning/src/mrp/mrp.ts
@@ -34,6 +34,7 @@ import type { SupabaseClient } from "@supabase/supabase-js";
import { type Kysely, sql } from "kysely";
import { z } from "zod";
import { toIsoDate } from "../scheduling/date-utils.ts";
+import { bomChildren } from "./bom-children.ts";
import {
actualConsumesForecast,
consumeForecast
@@ -378,15 +379,7 @@ export async function runMrp(
// Build itemId -> direct BOM children (one level only)
const bomByItem = new Map<string, BomChild[]>();
for (const [itemId, methodId] of methodIdByItem) {
- const materials = materialsByMethodId.get(methodId) ?? [];
- const children: BomChild[] = [];
- for (const mat of materials) {
- children.push({
- itemId: mat.itemId,
- quantity: Number(mat.quantity) || 1,
- methodType: mat.methodType as MethodType
- });
- }
+ const children = bomChildren(materialsByMethodId.get(methodId) ?? []);
if (children.length > 0) {
bomByItem.set(itemId, children);
}