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(production): planning scrap math, MRP double-netting, recalc scrap/rounding drift (#1312)
Siddharth Gaikwad542d353b9d72
diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsxindex b48de25969..1f943f590e 100644--- a/apps/erp/app/routes/x+/production+/planning.update.tsx+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx@@ -214,7 +214,7 @@ export async function action({ request }: ActionFunctionArgs) {manufacturing.data?.scrapPercentage ?? 0;const updateScrapQuantity =updateScrapPercentage > 0- ? Math.ceil(order.quantity * (updateScrapPercentage / 100))+ ? Math.ceil(order.quantity * updateScrapPercentage): 0;const updateJob = await clientdiff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.tsindex 958f6b8ade..ce693f7a02 100644--- a/packages/database/supabase/functions/get-method/index.ts+++ b/packages/database/supabase/functions/get-method/index.ts@@ -615,14 +615,16 @@ serve(async (req: Request) => {// - scrapQuantity = targetQuantity * scrapRate (the extra needed for scrap)// - totalForChildren = target + scrap (passed to children for cascade)const nodeScrapQuantity = targetQuantity * nodeScrapPercentage;- const totalWithScrap = Math.ceil(targetQuantity + nodeScrapQuantity);+ const totalWithScrap = targetQuantity + nodeScrapQuantity;// For Make: estimatedQuantity is the good quantity (without scrap)// For Buy/Pick: estimatedQuantity includes scrap since that's what we procureconst estimatedQuantity =node.data.methodType === "Make to Order" ? targetQuantity : totalWithScrap;// operationQuantity should be the total (including scrap) since that's what we need to make- const operationQuantity = totalWithScrap;+ // Operation/production counts stay whole even when material+ // quantities are fractional+ const operationQuantity = Math.ceil(totalWithScrap);// Pass total (including scrap) to children so cascade works correctlyconst totalQuantityForChildren = totalWithScrap;@@ -1092,9 +1094,8 @@ serve(async (req: Request) => {const childTargetQuantity = totalQuantityForChildren * quantity;// scrapQuantity = portion attributable to scrapconst childScrapQuantity = childTargetQuantity * itemScrapPercentage;- const childTotalWithScrap = Math.ceil(- childTargetQuantity + childScrapQuantity- );+ const childTotalWithScrap =+ childTargetQuantity + childScrapQuantity;// For Make: estimatedQuantity is the good quantity (without scrap)// For Buy/Pick: estimatedQuantity includes scrap since that's what we procureconst childEstimatedQuantity =@@ -1525,10 +1526,12 @@ serve(async (req: Request) => {// - For Make parts: estimatedQuantity = targetQuantity (good quantity, NOT including scrap)// - For Buy/Pick parts: estimatedQuantity = target + scrap (what we need to procure)const nodeScrapQuantity = targetQuantity * nodeScrapPercentage;- const totalWithScrap = Math.ceil(targetQuantity + nodeScrapQuantity);+ const totalWithScrap = targetQuantity + nodeScrapQuantity;const estimatedQuantity =node.data.methodType === "Make to Order" ? targetQuantity : totalWithScrap;- const operationQuantity = totalWithScrap;+ // Operation/production counts stay whole even when material+ // quantities are fractional+ const operationQuantity = Math.ceil(totalWithScrap);const totalQuantityForChildren = totalWithScrap;const relatedOperations = await client@@ -1780,9 +1783,8 @@ serve(async (req: Request) => {totalQuantityForChildren * (child.data.quantity ?? 1);const childScrapQuantity =childTargetQuantity * itemScrapPercentage;- const childTotalWithScrap = Math.ceil(- childTargetQuantity + childScrapQuantity- );+ const childTotalWithScrap =+ childTargetQuantity + childScrapQuantity;// For Make: estimatedQuantity is the good quantity (without scrap)// For Buy/Pick: estimatedQuantity includes scrap since that's what we procureconst childEstimatedQuantity =@@ -4836,7 +4838,11 @@ serve(async (req: Request) => {// Track estimated quantities for each make method to set on operationsconst quoteMakeMethodIdToQuantities: Record<string,- { targetQuantity: number; estimatedQuantity: number }+ {+ targetQuantity: number;+ estimatedQuantity: number;+ totalWithScrap: number;+ }> = {};await db.transaction().execute(async (trx) => {@@ -4890,15 +4896,11 @@ serve(async (req: Request) => {rootItemReplenishment?.scrapPercentage ?? 0);const rootTarget = job.data?.quantity ?? 1;- const rootScrapQuantity =- node.data.methodType === "Make to Order"- ? rootTarget * rootScrapPercentage- : 0;- const rootTotalWithScrap = Math.ceil(- rootTarget + rootScrapQuantity- );+ // Scrap applies to every method type (mirrors itemToJob)+ const rootScrapQuantity = rootTarget * rootScrapPercentage;+ const rootTotalWithScrap = rootTarget + rootScrapQuantity;// For Make: estimatedQuantity is good quantity (without scrap)- // For Buy/Pick: estimatedQuantity = total (but scrap is 0, so same as target)+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procureconst rootEstimatedQuantity =node.data.methodType === "Make to Order"? rootTarget@@ -4939,15 +4941,13 @@ serve(async (req: Request) => {// Target = parent's total (including scrap) * quantity per parentconst childTargetQuantity =nodeTotalForChildren * (child.data.quantity ?? 1);+ // Scrap applies to every method type (mirrors itemToJob)const childScrapQuantity =- child.data.methodType === "Make to Order"- ? childTargetQuantity * itemScrapPercentage- : 0;- const childTotalWithScrap = Math.ceil(- childTargetQuantity + childScrapQuantity- );+ childTargetQuantity * itemScrapPercentage;+ const childTotalWithScrap =+ childTargetQuantity + childScrapQuantity;// For Make: estimatedQuantity is good quantity (without scrap)- // For Buy/Pick: estimatedQuantity = total (but scrap is 0, so same as target)+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procureconst childEstimatedQuantity =child.data.methodType === "Make to Order"? childTargetQuantity@@ -5074,6 +5074,16 @@ serve(async (req: Request) => {// Get quantities for this operation's make methodconst opQuantities =quoteMakeMethodIdToQuantities[op.quoteMakeMethodId ?? ""];+ // The traversal stores quantities for every make method in the+ // tree, so a miss means the operation references an orphaned+ // make method. Fail the conversion (rolls back the transaction)+ // instead of silently inserting a zero-quantity operation with+ // a NULL jobMakeMethodId.+ if (!opQuantities) {+ throw new Error(+ `No quantities found for quote make method ${op.quoteMakeMethodId} referenced by operation ${op.id} — the quote method tree and its operations are out of sync`+ );+ }return {jobId,jobMakeMethodId:@@ -5103,8 +5113,10 @@ serve(async (req: Request) => {operationUnitCost: op.operationUnitCost ?? 0,tags: op.tags ?? [],workInstruction: parts.workInstructions ? op.workInstruction : {},- targetQuantity: opQuantities?.targetQuantity ?? 0,- operationQuantity: opQuantities?.totalWithScrap ?? 0,+ targetQuantity: opQuantities.targetQuantity,+ // Operation/production counts stay whole even when material+ // quantities are fractional+ operationQuantity: Math.ceil(opQuantities.totalWithScrap),companyId,createdBy: userId,customFields: {},diff --git a/packages/database/supabase/functions/lib/mrp-engine.ts b/packages/database/supabase/functions/lib/mrp-engine.tsindex fd8237b0a3..91f037324f 100644--- a/packages/database/supabase/functions/lib/mrp-engine.ts+++ b/packages/database/supabase/functions/lib/mrp-engine.ts@@ -1,6 +1,4 @@// Pure MRP engine functions shared across Supabase edge functions.-// The same algorithm is independently available (with unit tests) at-// packages/mrp/src/engine.ts.export type MethodType =| "Make to Order"diff --git a/packages/database/supabase/functions/mrp/index.ts b/packages/database/supabase/functions/mrp/index.tsindex 087f9b7082..f9ff5331a3 100644--- a/packages/database/supabase/functions/mrp/index.ts+++ b/packages/database/supabase/functions/mrp/index.ts@@ -352,14 +352,14 @@ serve(async (req: Request) => {type DemandForecastSourceInsert =Database["public"]["Tables"]["demandForecastSource"]["Insert"];- // Demand projections (netted against production supply)+ // Demand projections. Do NOT net firm job/PO supply here — supply is+ // credited exactly once by explodeBom's running balance (which receives+ // jobAndPoSupplyByLocationPeriodItem below). Netting here as well would+ // double-count supply and under-drive child demand.for (const projection of demandProjections.data) {if (!projection.itemId || !projection.forecastQuantity) continue;- let netDemand = projection.forecastQuantity;- const periodKey = `${projection.locationId ?? ""}-${projection.periodId}-${projection.itemId}`;- const plannedProduction = jobSupplyByLocationPeriodItem.get(periodKey) ?? 0;- netDemand = Math.max(0, projection.forecastQuantity - plannedProduction);+ const netDemand = projection.forecastQuantity;if (netDemand > 0) {const key = `${projection.locationId ?? ""}-${projection.periodId}-${projection.itemId}`;diff --git a/packages/database/supabase/functions/recalculate/index.ts b/packages/database/supabase/functions/recalculate/index.tsindex 916bfd0de9..0fe8cbb945 100644--- a/packages/database/supabase/functions/recalculate/index.ts+++ b/packages/database/supabase/functions/recalculate/index.ts@@ -95,7 +95,9 @@ serve(async (req: Request) => {if (job.error) {throw new Error(`Failed to get job: ${job.error.message}`);}- parentQuantity = job.data.productionQuantity ?? 1;+ // Use job.quantity as the root's target quantity (not productionQuantity)+ // The item's scrap percentage will be applied within updateJobQuantities+ parentQuantity = job.data.quantity ?? 1;}const jobMethodTrees = await getJobMethodTree(@@ -193,39 +195,37 @@ const updateJobQuantities = async (// Get scrap percentage from jobMaterial (stored at job creation time)// Fall back to itemReplenishment if not stored+ // Scrap applies to every method type (get-method stamps itemScrapPercentage+ // on every material row and applies scrap unconditionally at creation)let scrapPercentage = 0;- if (tree.data.methodType === "Make to Order") {- const jobMaterial = await trx- .selectFrom("jobMaterial")- .select("itemScrapPercentage")- .where("id", "=", tree.id)+ const jobMaterial = await trx+ .selectFrom("jobMaterial")+ .select("itemScrapPercentage")+ .where("id", "=", tree.id)+ .executeTakeFirst();++ // A stored 0 is intentional (locked at job creation) — only a NULL falls+ // back to the item's current replenishment scrap percentage.+ if (jobMaterial?.itemScrapPercentage != null) {+ scrapPercentage = Number(jobMaterial.itemScrapPercentage);+ } else {+ // Fall back to itemReplenishment+ const itemReplenishment = await trx+ .selectFrom("itemReplenishment")+ .select("scrapPercentage")+ .where("itemId", "=", tree.data.itemId).executeTakeFirst();-- if (- jobMaterial?.itemScrapPercentage != null &&- jobMaterial.itemScrapPercentage > 0- ) {- scrapPercentage = Number(jobMaterial.itemScrapPercentage);- } else {- // Fall back to itemReplenishment- const itemReplenishment = await trx- .selectFrom("itemReplenishment")- .select("scrapPercentage")- .where("itemId", "=", tree.data.itemId)- .executeTakeFirst();- scrapPercentage = Number(itemReplenishment?.scrapPercentage ?? 0);- }+ scrapPercentage = Number(itemReplenishment?.scrapPercentage ?? 0);}// Calculate scrap and estimated quantities- // scrapQuantity = portion attributable to scrap (only for Make parts)+ // scrapQuantity = portion attributable to scrap// totalWithScrap = target + scrap allowance (what we need to make/procure)// estimatedQuantity: For Make = good quantity (without scrap), For Buy/Pick = total- const scrapQuantity =- tree.data.methodType === "Make to Order" ? targetQuantity * scrapPercentage : 0;- const totalWithScrap = Math.ceil(targetQuantity + scrapQuantity);+ const scrapQuantity = targetQuantity * scrapPercentage;+ const totalWithScrap = targetQuantity + scrapQuantity;// For Make: estimatedQuantity is good quantity (without scrap)- // For Buy/Pick: estimatedQuantity = total (but scrap is 0, so same as target)+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procureconst estimatedQuantity =tree.data.methodType === "Make to Order" ? targetQuantity : totalWithScrap;@@ -255,7 +255,9 @@ const updateJobQuantities = async (.updateTable("jobOperation").set({targetQuantity: targetQuantity,- operationQuantity: totalWithScrap,+ // Operation/production counts stay whole even when material+ // quantities are fractional+ operationQuantity: Math.ceil(totalWithScrap),}).where("jobMakeMethodId", "=", tree.data.jobMaterialMakeMethodId).where("reworkId", "is", null)@@ -266,7 +268,9 @@ const updateJobQuantities = async (await trx.updateTable("trackedEntity").set({- quantity: jobMakeMethod.requiresSerialTracking ? 1 : totalWithScrap,+ quantity: jobMakeMethod.requiresSerialTracking+ ? 1+ : Math.ceil(totalWithScrap),}).where("id", "=", jobMakeMethod.trackedEntityId).execute();