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: backflush the children of serial parts
Brad Barbin349f0a81ce0c
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.tsindex b291d8fd44..d312895da7 100644--- a/packages/database/supabase/functions/issue/index.ts+++ b/packages/database/supabase/functions/issue/index.ts@@ -1,4 +1,5 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";+import { Transaction } from "kysely";import { z } from "npm:zod@^3.24.1";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";@@ -13,6 +14,204 @@ import { getSupabaseServiceRole } from "../lib/supabase.ts";import { Database } from "../lib/types.ts";import { TrackedEntityAttributes } from "../lib/utils.ts";+async function issueJobOperationMaterials(+ trx: Transaction<DB>,+ {+ jobOperationId,+ quantity,+ companyId,+ userId,+ }: {+ jobOperationId: string;+ quantity: number;+ companyId: string;+ userId: string;+ }+) {+ const materialsToIssue = await trx+ .selectFrom("jobMaterial")+ .where("jobOperationId", "=", jobOperationId)+ .where("quantityToIssue", ">", 0)+ .where("itemType", "in", ["Material", "Part", "Consumable"])+ .where("methodType", "!=", "Make to Order")+ .where("estimatedQuantity", ">", 0)+ .where("requiresBatchTracking", "=", false)+ .where("requiresSerialTracking", "=", false)+ .selectAll()+ .execute();++ const kittedChildren = await trx+ .selectFrom("jobMaterialWithMakeMethodId")+ .where("jobOperationId", "=", jobOperationId)+ .where("itemType", "in", ["Material", "Part", "Consumable"])+ .where("methodType", "=", "Make to Order")+ .where("kit", "=", true)+ .selectAll()+ .execute();++ const jobMakeMethodIdsOfKittedChildren = kittedChildren.map(+ (kittedChild) => kittedChild.jobMaterialMakeMethodId+ );++ if (jobMakeMethodIdsOfKittedChildren.length > 0) {+ const materialsToIssueFromKittedChildren = await trx+ .selectFrom("jobMaterial")+ .where("jobMakeMethodId", "in", jobMakeMethodIdsOfKittedChildren)+ .where("quantityToIssue", ">", 0)+ .where("itemType", "in", ["Material", "Part", "Consumable"])+ .where("methodType", "!=", "Make to Order")+ .where("estimatedQuantity", ">", 0)+ .where("requiresBatchTracking", "=", false)+ .where("requiresSerialTracking", "=", false)+ .selectAll()+ .execute();++ materialsToIssue.push(...materialsToIssueFromKittedChildren);+ }++ if (materialsToIssue.length === 0) return;++ const jobId = materialsToIssue[0].jobId;++ const [job, items] = await Promise.all([+ trx+ .selectFrom("job")+ .where("id", "=", jobId)+ .select("locationId")+ .executeTakeFirst(),+ trx+ .selectFrom("item")+ .where(+ "id",+ "in",+ materialsToIssue.map((material) => material.itemId)+ )+ .select(["id", "item.itemTrackingType"])+ .execute(),+ ]);++ if (!job?.locationId) {+ throw new Error("Job location is required");+ }++ const itemIdIsTracked = new Map(+ items.map((item) => [item.id, item.itemTrackingType === "Inventory"])+ );++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ for await (const material of materialsToIssue) {+ if (!material.quantityToIssue) continue;++ const quantityToIssue = Number(material.quantity) * quantity;++ let proposedShelfId = material.shelfId;++ if (!proposedShelfId) {+ if (material.defaultShelf) {+ const pickMethod = await trx+ .selectFrom("pickMethod")+ .where("itemId", "=", material.itemId)+ .where("locationId", "=", job.locationId!)+ .where("companyId", "=", companyId)+ .select("defaultShelfId")+ .executeTakeFirst();++ proposedShelfId = pickMethod?.defaultShelfId;++ if (!proposedShelfId) {+ proposedShelfId = await getShelfWithHighestQuantity(+ trx,+ material.itemId,+ job.locationId!+ );+ }+ } else {+ proposedShelfId = await getShelfWithHighestQuantity(+ trx,+ material.itemId,+ job.locationId!+ );+ }+ }++ const currentShelfQuantity = await trx+ .selectFrom("itemLedger")+ .select((eb) => eb.fn.sum("quantity").as("quantity"))+ .where("itemId", "=", material.itemId)+ .where("locationId", "=", job.locationId!)+ .where("shelfId", "=", proposedShelfId ?? "")+ .executeTakeFirst();++ const allShelfQuantities = await trx+ .selectFrom("itemLedger")+ .select([+ "shelfId",+ (eb) => eb.fn.sum("quantity").as("quantity"),+ ])+ .where("itemId", "=", material.itemId)+ .where("locationId", "=", job.locationId!)+ .groupBy("shelfId")+ .having((eb) => eb.fn.sum("quantity"), ">", 0)+ .execute();++ let finalShelfId = proposedShelfId;+ const currentQuantity = Number(currentShelfQuantity?.quantity ?? 0);++ if (+ currentQuantity < quantityToIssue &&+ allShelfQuantities.length > 0+ ) {+ const bestShelf = allShelfQuantities.reduce((best, current) =>+ Number(current.quantity) > Number(best.quantity) ? current : best+ );+ finalShelfId = bestShelf.shelfId ?? null;+ }++ const isTracked = itemIdIsTracked.get(material.itemId);++ if (isTracked) {+ itemLedgerInserts.push({+ entryType: "Consumption",+ documentType: "Job Consumption",+ documentId: jobId,+ documentLineId: jobOperationId,+ companyId,+ itemId: material.itemId,+ quantity: -quantityToIssue,+ locationId: job.locationId,+ shelfId: finalShelfId,+ createdBy: userId,+ });+ }++ await trx+ .updateTable("jobMaterial")+ .set({+ quantityIssued:+ (Number(material.quantityIssued) ?? 0) + quantityToIssue,+ })+ .where("id", "=", material.id)+ .execute();+ }++ if (itemLedgerInserts.length > 0) {+ await trx.insertInto("itemLedger").values(itemLedgerInserts).execute();++ for (const ledger of itemLedgerInserts) {+ await updatePickMethodDefaultShelfIfNeeded(+ trx,+ ledger.itemId,+ ledger.locationId,+ ledger.shelfId,+ companyId,+ userId+ );+ }+ }+}+const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);@@ -336,204 +535,12 @@ serve(async (req: Request) => {case "jobOperation": {const { id, companyId, quantity, userId } = validatedPayload;await db.transaction().execute(async (trx) => {- const materialsToIssue = await trx- .selectFrom("jobMaterial")- .where("jobOperationId", "=", id)- .where("quantityToIssue", ">", 0)- .where("itemType", "in", ["Material", "Part", "Consumable"])- .where("methodType", "!=", "Make to Order")- .where("estimatedQuantity", ">", 0)- .where("requiresBatchTracking", "=", false)- .where("requiresSerialTracking", "=", false)- .selectAll()- .execute();-- const kittedChildren = await trx- .selectFrom("jobMaterialWithMakeMethodId")- .where("jobOperationId", "=", id)- .where("itemType", "in", ["Material", "Part", "Consumable"])- .where("methodType", "=", "Make to Order")- .where("kit", "=", true)- .selectAll()- .execute();-- const jobMakeMethodIdsOfKittedChildren = kittedChildren.map(- (kittedChild) => kittedChild.jobMaterialMakeMethodId- );-- if (jobMakeMethodIdsOfKittedChildren.length > 0) {- const materialsToIssueFromKittedChildren = await trx- .selectFrom("jobMaterial")- .where("jobMakeMethodId", "in", jobMakeMethodIdsOfKittedChildren)- .where("quantityToIssue", ">", 0)- .where("itemType", "in", ["Material", "Part", "Consumable"])- .where("methodType", "!=", "Make to Order")- .where("estimatedQuantity", ">", 0)- .where("requiresBatchTracking", "=", false)- .where("requiresSerialTracking", "=", false)- .selectAll()- .execute();-- materialsToIssue.push(...materialsToIssueFromKittedChildren);- }-- if (materialsToIssue.length > 0) {- const jobId = materialsToIssue[0].jobId;-- const [job, items] = await Promise.all([- trx- .selectFrom("job")- .where("id", "=", jobId)- .select("locationId")- .executeTakeFirst(),- trx- .selectFrom("item")- .where(- "id",- "in",- materialsToIssue.map((material) => material.itemId)- )- .select(["id", "item.itemTrackingType"])- .execute(),- ]);-- if (!job?.locationId) {- throw new Error("Job location is required");- }-- const itemIdIsTracked = new Map(- items.map((item) => [- item.id,- item.itemTrackingType === "Inventory",- ])- );-- for await (const material of materialsToIssue) {- if (material.quantityToIssue) {- // Calculate the quantity to issue based on payload quantity multiplied by the material quantity- const quantityToIssue = Number(material.quantity) * quantity;-- // Determine shelf to use - prioritize material.shelfId, then fetch if needed- let proposedShelfId = material.shelfId;-- if (!proposedShelfId) {- if (material.defaultShelf) {- // Fetch pick method default shelf- const pickMethod = await trx- .selectFrom("pickMethod")- .where("itemId", "=", material.itemId)- .where("locationId", "=", job?.locationId!)- .where("companyId", "=", companyId)- .select("defaultShelfId")- .executeTakeFirst();-- proposedShelfId = pickMethod?.defaultShelfId;-- // If defaultShelfId is null, get shelf with highest quantity- if (!proposedShelfId) {- proposedShelfId = await getShelfWithHighestQuantity(- trx,- material.itemId,- job?.locationId!- );- }- } else {- // Get shelf with highest quantity- proposedShelfId = await getShelfWithHighestQuantity(- trx,- material.itemId,- job?.locationId!- );- }- }-- // Get current quantity on this shelf for diagnostics- const currentShelfQuantity = await trx- .selectFrom("itemLedger")- .select((eb) => eb.fn.sum("quantity").as("quantity"))- .where("itemId", "=", material.itemId)- .where("locationId", "=", job.locationId!)- .where("shelfId", "=", proposedShelfId ?? "")- .executeTakeFirst();-- // Get all shelf quantities for this item for diagnostics- const allShelfQuantities = await trx- .selectFrom("itemLedger")- .select([- "shelfId",- (eb) => eb.fn.sum("quantity").as("quantity"),- ])- .where("itemId", "=", material.itemId)- .where("locationId", "=", job.locationId!)- .groupBy("shelfId")- .having((eb) => eb.fn.sum("quantity"), ">", 0)- .execute();-- // Use shelf with highest quantity if proposed shelf has insufficient quantity- let finalShelfId = proposedShelfId;- const currentQuantity = Number(- currentShelfQuantity?.quantity ?? 0- );-- if (- currentQuantity < quantityToIssue &&- allShelfQuantities.length > 0- ) {- const bestShelf = allShelfQuantities.reduce((best, current) =>- Number(current.quantity) > Number(best.quantity)- ? current- : best- );- finalShelfId = bestShelf.shelfId ?? null;- }-- const isTracked = itemIdIsTracked.get(material.itemId);-- if (isTracked) {- itemLedgerInserts.push({- entryType: "Consumption",- documentType: "Job Consumption",- documentId: jobId,- documentLineId: id,- companyId,- itemId: material.itemId,- quantity: -quantityToIssue,- locationId: job?.locationId,- shelfId: finalShelfId,- createdBy: userId,- });- }-- await trx- .updateTable("jobMaterial")- .set({- quantityIssued:- (Number(material.quantityIssued) ?? 0) + quantityToIssue,- })- .where("id", "=", material.id)- .execute();- }- }-- if (itemLedgerInserts.length > 0) {- await trx- .insertInto("itemLedger")- .values(itemLedgerInserts)- .execute();-- // Update pickMethod defaultShelfId if needed for each inserted ledger- for (const ledger of itemLedgerInserts) {- await updatePickMethodDefaultShelfIfNeeded(- trx,- ledger.itemId,- ledger.locationId,- ledger.shelfId,- companyId,- userId- );- }- }- }+ await issueJobOperationMaterials(trx, {+ jobOperationId: id,+ quantity,+ companyId,+ userId,+ });});break;@@ -630,6 +637,13 @@ serve(async (req: Request) => {.where("id", "=", trackedEntityId).execute();}++ await issueJobOperationMaterials(trx, {+ jobOperationId: row.jobOperationId,+ quantity: row.quantity,+ companyId,+ userId,+ });});return new Response(@@ -764,6 +778,13 @@ serve(async (req: Request) => {newEntityId = newTrackedEntityResult?.id;}++ await issueJobOperationMaterials(trx, {+ jobOperationId: row.jobOperationId,+ quantity: row.quantity,+ companyId,+ userId,+ });});return new Response(diff --git a/packages/database/supabase/migrations/20260416120000_backfill-missed-material-issue-on-tracked-parent-completion.sql b/packages/database/supabase/migrations/20260416120000_backfill-missed-material-issue-on-tracked-parent-completion.sqlnew file mode 100644index 0000000000..d029174406--- /dev/null+++ b/packages/database/supabase/migrations/20260416120000_backfill-missed-material-issue-on-tracked-parent-completion.sql@@ -0,0 +1,262 @@+-- Backfill missed material auto-issue for operations whose parent output is Serial/Batch tracked.+--+-- Before 20260416, the jobOperationBatchComplete and jobOperationSerialComplete handlers in+-- functions/issue/index.ts skipped the jobMaterial backflush logic that the plain jobOperation+-- handler ran. Completing a serial or batch parent therefore left child materials with+-- quantityIssued = 0 and no itemLedger consumption entries.+--+-- This migration is idempotent and recovers regardless of current DB state by driving+-- each target independently toward its expected value:+-- itemLedger total consumption for (jobId, jobOperationId, itemId)+-- should equal -(SUM over materials of material.quantity × completedQuantity)+-- jobMaterial.quantityIssued for each material+-- should equal material.quantity × completedQuantity+-- Each statement only fills the shortfall, so re-running is a no-op.+-- Kitted (kit = true) Make to Order children's materials are included, matching the runtime helper.++-- =========================================================================================+-- Statement 1: Insert missing itemLedger Consumption rows for Inventory-tracked materials.+-- =========================================================================================++WITH+ affected_operations AS (+ SELECT+ jo.id AS "jobOperationId",+ jo."jobId",+ j."locationId",+ j."companyId",+ SUM(pq.quantity) AS "completedQuantity"+ FROM "jobOperation" jo+ JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"+ JOIN "item" parent ON parent.id = jmm."itemId"+ JOIN "job" j ON j.id = jo."jobId"+ JOIN "productionQuantity" pq+ ON pq."jobOperationId" = jo.id+ AND pq.type = 'Production'+ WHERE parent."itemTrackingType" IN ('Serial', 'Batch')+ AND j."locationId" IS NOT NULL+ GROUP BY jo.id, jo."jobId", j."locationId", j."companyId"+ HAVING SUM(pq.quantity) > 0+ ),++ direct_materials AS (+ SELECT+ jm.id,+ jm."itemId",+ jm."jobId",+ ao."jobOperationId",+ jm.quantity,+ jm."quantityIssued",+ jm."shelfId" AS "materialShelfId",+ jm."defaultShelf",+ ao."completedQuantity",+ ao."locationId",+ ao."companyId"+ FROM "jobMaterial" jm+ JOIN affected_operations ao ON ao."jobOperationId" = jm."jobOperationId"+ WHERE jm."itemType" IN ('Material', 'Part', 'Consumable')+ AND jm."methodType" != 'Make to Order'+ AND jm."estimatedQuantity" > 0+ AND jm."requiresBatchTracking" = false+ AND jm."requiresSerialTracking" = false+ ),++ kitted_child_methods AS (+ SELECT+ jmm.id AS "childMakeMethodId",+ ao."jobOperationId",+ ao."completedQuantity",+ ao."locationId",+ ao."companyId"+ FROM "jobMaterial" jm+ JOIN affected_operations ao ON ao."jobOperationId" = jm."jobOperationId"+ JOIN "jobMakeMethod" jmm ON jmm."parentMaterialId" = jm.id+ WHERE jm."itemType" IN ('Material', 'Part', 'Consumable')+ AND jm."methodType" = 'Make to Order'+ AND jm.kit = true+ ),++ kitted_materials AS (+ SELECT+ jm.id,+ jm."itemId",+ jm."jobId",+ kcm."jobOperationId",+ jm.quantity,+ jm."quantityIssued",+ jm."shelfId" AS "materialShelfId",+ jm."defaultShelf",+ kcm."completedQuantity",+ kcm."locationId",+ kcm."companyId"+ FROM "jobMaterial" jm+ JOIN kitted_child_methods kcm ON kcm."childMakeMethodId" = jm."jobMakeMethodId"+ WHERE jm."itemType" IN ('Material', 'Part', 'Consumable')+ AND jm."methodType" != 'Make to Order'+ AND jm."estimatedQuantity" > 0+ AND jm."requiresBatchTracking" = false+ AND jm."requiresSerialTracking" = false+ ),++ all_materials AS (+ SELECT * FROM direct_materials+ UNION ALL+ SELECT * FROM kitted_materials+ ),++ -- itemLedger has no per-material key, so collapse to (jobId, jobOperationId, itemId).+ aggregated AS (+ SELECT+ m."jobId",+ m."jobOperationId",+ m."itemId",+ m."locationId",+ m."companyId",+ SUM(m.quantity * m."completedQuantity") AS "expectedIssued",+ MIN(m."materialShelfId") FILTER (WHERE m."materialShelfId" IS NOT NULL)+ AS "materialShelfId",+ BOOL_OR(m."defaultShelf") AS "defaultShelf"+ FROM all_materials m+ GROUP BY m."jobId", m."jobOperationId", m."itemId", m."locationId", m."companyId"+ ),++ ledger_shortfalls AS (+ SELECT+ a.*,+ i."itemTrackingType",+ COALESCE((+ SELECT SUM(il.quantity)+ FROM "itemLedger" il+ WHERE il."itemId" = a."itemId"+ AND il."entryType" = 'Consumption'+ AND il."documentType" = 'Job Consumption'+ AND il."documentId" = a."jobId"+ AND il."documentLineId" = a."jobOperationId"+ ), 0) AS "existingLedgerQty"+ FROM aggregated a+ JOIN "item" i ON i.id = a."itemId"+ ),++ needs_ledger AS (+ SELECT+ s.*,+ (-s."expectedIssued" - s."existingLedgerQty") AS "missingQty"+ FROM ledger_shortfalls s+ WHERE s."itemTrackingType" = 'Inventory'+ AND (-s."expectedIssued" - s."existingLedgerQty") < 0+ ),++ ledger_resolved AS (+ SELECT+ n.*,+ COALESCE(+ n."materialShelfId",+ pm."defaultShelfId",+ (+ SELECT il."shelfId"+ FROM "itemLedger" il+ WHERE il."itemId" = n."itemId"+ AND il."locationId" = n."locationId"+ AND il."shelfId" IS NOT NULL+ GROUP BY il."shelfId"+ HAVING SUM(il.quantity) > 0+ ORDER BY SUM(il.quantity) DESC+ LIMIT 1+ )+ ) AS "resolvedShelfId"+ FROM needs_ledger n+ LEFT JOIN "pickMethod" pm+ ON pm."itemId" = n."itemId"+ AND pm."locationId" = n."locationId"+ AND pm."companyId" = n."companyId"+ )++INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "documentLineId",+ "companyId", "itemId", quantity, "locationId", "shelfId", "createdBy"+)+SELECT+ 'Consumption',+ 'Job Consumption',+ r."jobId",+ r."jobOperationId",+ r."companyId",+ r."itemId",+ r."missingQty",+ r."locationId",+ r."resolvedShelfId",+ 'system'+FROM ledger_resolved r;++-- =========================================================================================+-- Statement 2: Close jobMaterial.quantityIssued deficit to match expected issuance.+-- =========================================================================================++WITH+ affected_operations AS (+ SELECT+ jo.id AS "jobOperationId",+ SUM(pq.quantity) AS "completedQuantity"+ FROM "jobOperation" jo+ JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"+ JOIN "item" parent ON parent.id = jmm."itemId"+ JOIN "job" j ON j.id = jo."jobId"+ JOIN "productionQuantity" pq+ ON pq."jobOperationId" = jo.id+ AND pq.type = 'Production'+ WHERE parent."itemTrackingType" IN ('Serial', 'Batch')+ AND j."locationId" IS NOT NULL+ GROUP BY jo.id+ HAVING SUM(pq.quantity) > 0+ ),++ direct_deficits AS (+ SELECT+ jm.id,+ (jm.quantity * ao."completedQuantity" - jm."quantityIssued") AS deficit+ FROM "jobMaterial" jm+ JOIN affected_operations ao ON ao."jobOperationId" = jm."jobOperationId"+ WHERE jm."itemType" IN ('Material', 'Part', 'Consumable')+ AND jm."methodType" != 'Make to Order'+ AND jm."estimatedQuantity" > 0+ AND jm."requiresBatchTracking" = false+ AND jm."requiresSerialTracking" = false+ AND (jm.quantity * ao."completedQuantity" - jm."quantityIssued") > 0+ ),++ kitted_child_methods AS (+ SELECT+ jmm.id AS "childMakeMethodId",+ ao."completedQuantity"+ FROM "jobMaterial" jm+ JOIN affected_operations ao ON ao."jobOperationId" = jm."jobOperationId"+ JOIN "jobMakeMethod" jmm ON jmm."parentMaterialId" = jm.id+ WHERE jm."itemType" IN ('Material', 'Part', 'Consumable')+ AND jm."methodType" = 'Make to Order'+ AND jm.kit = true+ ),++ kitted_deficits AS (+ SELECT+ jm.id,+ (jm.quantity * kcm."completedQuantity" - jm."quantityIssued") AS deficit+ FROM "jobMaterial" jm+ JOIN kitted_child_methods kcm ON kcm."childMakeMethodId" = jm."jobMakeMethodId"+ WHERE jm."itemType" IN ('Material', 'Part', 'Consumable')+ AND jm."methodType" != 'Make to Order'+ AND jm."estimatedQuantity" > 0+ AND jm."requiresBatchTracking" = false+ AND jm."requiresSerialTracking" = false+ AND (jm.quantity * kcm."completedQuantity" - jm."quantityIssued") > 0+ ),++ all_deficits AS (+ SELECT * FROM direct_deficits+ UNION ALL+ SELECT * FROM kitted_deficits+ )++UPDATE "jobMaterial" jm+SET "quantityIssued" = jm."quantityIssued" + d.deficit+FROM all_deficits d+WHERE jm.id = d.id;diff --git a/packages/database/supabase/migrations/20260416130000_production-quantity-to-numeric.sql b/packages/database/supabase/migrations/20260416130000_production-quantity-to-numeric.sqlnew file mode 100644index 0000000000..8946980098--- /dev/null+++ b/packages/database/supabase/migrations/20260416130000_production-quantity-to-numeric.sql@@ -0,0 +1,6 @@+-- Widen productionQuantity.quantity from INTEGER to NUMERIC so it can hold fractional+-- production for weight/length UoMs. Downstream consumers (jobOperation.quantityComplete,+-- itemLedger.quantity, jobMaterial.quantity*) are already NUMERIC.++ALTER TABLE "productionQuantity"+ ALTER COLUMN "quantity" TYPE NUMERIC USING "quantity"::NUMERIC;