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(mes): a recorded step backflushes only its own operation's loose parts
Raul69056e5a4679
diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsxindex 3100322594..29f25e2ab4 100644--- a/apps/mes/app/components/AssemblyView.tsx+++ b/apps/mes/app/components/AssemblyView.tsx@@ -105,6 +105,7 @@ import { MesAppBar } from "~/components/MesAppBar";import { useMesBottomBar } from "~/components/MesBottomBar";import { useRealtime, useUser } from "~/hooks";import { isSerialEntityIncompleteForOperation } from "~/services/operations.service";+import { ownsLooseMaterial } from "~/services/step-backflush";import type {JobMaterial,JobOperationStep,@@ -771,12 +772,18 @@ export function AssemblyView({// with NO step link are unassigned ("General") and show on the FIRST step only — loose// untracked parts are backflushed when the unit's first step is recorded, so that's// where the operator sees and handles them; repeating them on every step just buries- // the step-specific parts. Quantity and issuing live on the jobMaterial (the part), so- // a part on several assigned steps never multiplies the requirement.+ // the step-specific parts. A General part attached to another operation of the method+ // belongs to that operation's first step, where its backflush runs. Quantity and issuing+ // live on the jobMaterial (the part), so a part on several assigned steps never+ // multiplies the requirement.const stepNumberById = new Map(steps.map((s, i) => [s.id, i + 1] as const));const allMaterials: any[] = materials?.materials ?? [];const isGeneralMaterial = (m: any) =>- (m.jobOperationStepIds ?? []).length === 0;+ (m.jobOperationStepIds ?? []).length === 0 &&+ ownsLooseMaterial(+ { jobOperationId: m.jobOperationId ?? null },+ operationId+ );const isOnCurrentStep = (m: any) =>step?.id != null && (m.jobOperationStepIds ?? []).includes(step.id);// Visible here = parts assigned to the current step, plus (first step only) thediff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex a0186eb60e..4f4ad81d6f 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -39,6 +39,7 @@ import type {scrapQuantityValidator,stepRecordValidator} from "./models";+import { planStepBackflush } from "./step-backflush";import type { BaseOperationWithDetails, Job, StorageItem } from "./types";const log = getLogger("mes", "operations");@@ -1391,8 +1392,10 @@ export async function getJobMaterialsByOperationId(* still require a scan). Step ownership:* • A step-assigned part (jobMaterialStep) is owned by its assigned step(s) and* issues when any of those steps is recorded for a unit.- * • A loose part (no step assignment) is owned by the operation's FIRST step —- * that's where the operator sees it — matching the prior behavior.+ * • A loose part (no step assignment) is owned by its operation's FIRST step —+ * that's where the operator sees it. A loose part attached to another+ * operation of the same make method waits for that operation's first step,+ * as the completion backflush attributes it (`planStepBackflush`).* Idempotent by construction: per material the target is* (distinct units that recorded an owning step) × per-unit quantity, and only the* shortfall vs quantityIssued is issued — re-records, undo/redo, manual issues,@@ -1438,7 +1441,7 @@ export async function backflushUntrackedMaterialsOnStepRecord(const materials = await client.from("jobMaterial")- .select("id, itemId, quantity, quantityIssued, methodType")+ .select("id, itemId, quantity, quantityIssued, methodType, jobOperationId").eq("jobMakeMethodId", operation.data.jobMakeMethodId).eq("companyId", args.companyId).in("itemType", ["Material", "Part", "Consumable"])@@ -1469,18 +1472,6 @@ export async function backflushUntrackedMaterialsOnStepRecord()) as unknown as typeof stepLinks;}if (stepLinks.error) return { error: stepLinks.error };- const ownedSteps = new Map<string, Set<string>>();- const linkQuantities = new Map<string, Map<string, number | null>>();- for (const link of stepLinks.data ?? []) {- const set = ownedSteps.get(link.jobMaterialId) ?? new Set<string>();- set.add(link.jobOperationStepId);- ownedSteps.set(link.jobMaterialId, set);- const quantities =- linkQuantities.get(link.jobMaterialId) ??- new Map<string, number | null>();- quantities.set(link.jobOperationStepId, link.quantity);- linkQuantities.set(link.jobMaterialId, quantities);- }// Units (index) that have recorded each of the operation's steps, so we can// count distinct started units per material from its owning step(s).@@ -1489,72 +1480,34 @@ export async function backflushUntrackedMaterialsOnStepRecord(.select("jobOperationStepId, index").in("jobOperationStepId", stepIds);if (records.error) return { error: records.error };- const unitsByStep = new Map<string, Set<number>>();- for (const r of records.data ?? []) {- const set = unitsByStep.get(r.jobOperationStepId) ?? new Set<number>();- set.add(r.index);- unitsByStep.set(r.jobOperationStepId, set);- }++ const issues = planStepBackflush({+ operationId,+ stepIds,+ materials: materials.data,+ stepLinks: (stepLinks.data ?? []).map((link) => ({+ jobMaterialId: link.jobMaterialId,+ jobOperationStepId: link.jobOperationStepId,+ quantity: link.quantity ?? null+ })),+ records: records.data ?? []+ });const failures: string[] = [];- for (const material of materials.data) {- const perUnit = material.quantity ?? 0;- if (perUnit <= 0) continue;- // Owning steps: the material's assigned steps (scoped to this operation), or- // the first step when it's loose (unassigned).- const owning = ownedSteps.get(material.id);- const triggerStepIds =- owning && owning.size > 0- ? stepIds.filter((id) => owning.has(id))- : [firstStepId];- const quantities = linkQuantities.get(material.id);- const hasSplitQuantities = triggerStepIds.some(- (id) => (quantities?.get(id) ?? null) !== null- );- // Distinct units that recorded at least one owning step — the line-level- // requirement bound: a material can never owe more than units × per-unit.- const units = new Set<number>();- for (const id of triggerStepIds) {- for (const idx of unitsByStep.get(id) ?? []) units.add(idx);- }- let target: number;- if (hasSplitQuantities) {- // The line is SPLIT across steps (5 screws at step 1, 5 at step 2): each- // owning step consumes its own share as it is recorded, so the target is- // the per-step sum. A link left without an explicit quantity falls back- // to the full per-unit quantity for its step. The sum is capped at the- // line-level bound — the BOM line is the source of truth, so shares that- // over-allocate the line (2 + 10 on a 5-quantity line) must not issue- // more stock than the line requires.- target = Math.min(- triggerStepIds.reduce(- (sum, id) =>- sum +- (unitsByStep.get(id)?.size ?? 0) * (quantities?.get(id) ?? perUnit),- 0- ),- units.size * perUnit- );- } else {- // Unsplit: distinct units counted once, so the requirement never- // multiplies across a material's several owning steps.- target = units.size * perUnit;- }- const delta = target - (material.quantityIssued ?? 0);- if (delta <= 0) continue;+ for (const issue of issues) {const issued = await erpPosting("issue",{ client, companyId: args.companyId, userId: args.userId },{id: operationId,type: "partToOperation",- itemId: material.itemId,- materialId: material.id,- quantity: delta,+ itemId: issue.itemId,+ materialId: issue.materialId,+ quantity: issue.quantity,adjustmentType: "Negative Adjmt."});- if (issued.error) failures.push(issued.error.message || material.itemId);+ if (issued.error) failures.push(issued.error.message || issue.itemId);}return {diff --git a/apps/mes/app/services/step-backflush.test.ts b/apps/mes/app/services/step-backflush.test.tsnew file mode 100644index 0000000000..4627a45fe6--- /dev/null+++ b/apps/mes/app/services/step-backflush.test.ts@@ -0,0 +1,160 @@+// 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 {+ ownsLooseMaterial,+ planStepBackflush,+ type StepBackflushMaterial+} from "./step-backflush";++const material = (+ overrides: Partial<StepBackflushMaterial> & { id: string }+): StepBackflushMaterial => ({+ itemId: `item-${overrides.id}`,+ quantity: 1,+ quantityIssued: 0,+ jobOperationId: "op-1",+ ...overrides+});++describe("planStepBackflush", () => {+ it("issues a loose part when the operation's first step is recorded", () => {+ const issues = planStepBackflush({+ operationId: "op-1",+ stepIds: ["s1", "s2"],+ materials: [material({ id: "glue", quantity: 2 })],+ stepLinks: [],+ records: [{ jobOperationStepId: "s1", index: 0 }]+ });+ expect(issues).toEqual([+ { materialId: "glue", itemId: "item-glue", quantity: 2 }+ ]);+ });++ it("does not issue a loose part that belongs to another operation", () => {+ // A two-operation method: the resin is on operation 2. Recording operation+ // 1's first step must not consume it; operation 2 owns it.+ const issues = planStepBackflush({+ operationId: "op-1",+ stepIds: ["s1"],+ materials: [+ material({ id: "tape", jobOperationId: "op-1" }),+ material({ id: "resin", jobOperationId: "op-2" })+ ],+ stepLinks: [],+ records: [{ jobOperationStepId: "s1", index: 0 }]+ });+ expect(issues.map((i) => i.materialId)).toEqual(["tape"]);+ });++ it("issues the other operation's loose part when that operation records its first step", () => {+ const issues = planStepBackflush({+ operationId: "op-2",+ stepIds: ["s3", "s4"],+ materials: [+ material({ id: "tape", jobOperationId: "op-1" }),+ material({ id: "resin", jobOperationId: "op-2", quantity: 0.5 })+ ],+ stepLinks: [],+ records: [{ jobOperationStepId: "s3", index: 0 }]+ });+ expect(issues).toEqual([+ { materialId: "resin", itemId: "item-resin", quantity: 0.5 }+ ]);+ });++ it("keeps issuing a loose part with no operation on any operation's first step", () => {+ const issues = planStepBackflush({+ operationId: "op-2",+ stepIds: ["s3"],+ materials: [material({ id: "wipe", jobOperationId: null })],+ stepLinks: [],+ records: [{ jobOperationStepId: "s3", index: 0 }]+ });+ expect(issues.map((i) => i.materialId)).toEqual(["wipe"]);+ });++ it("issues a step-assigned part only when its own step is recorded", () => {+ const base = {+ operationId: "op-1",+ stepIds: ["s1", "s2"],+ materials: [material({ id: "screw", quantity: 4 })],+ stepLinks: [+ { jobMaterialId: "screw", jobOperationStepId: "s2", quantity: null }+ ]+ };+ expect(+ planStepBackflush({+ ...base,+ records: [{ jobOperationStepId: "s1", index: 0 }]+ })+ ).toEqual([]);+ expect(+ planStepBackflush({+ ...base,+ records: [+ { jobOperationStepId: "s1", index: 0 },+ { jobOperationStepId: "s2", index: 0 }+ ]+ })+ ).toEqual([{ materialId: "screw", itemId: "item-screw", quantity: 4 }]);+ });++ it("ignores a part assigned only to another operation's steps", () => {+ const issues = planStepBackflush({+ operationId: "op-1",+ stepIds: ["s1"],+ materials: [material({ id: "bolt", jobOperationId: "op-1" })],+ stepLinks: [+ { jobMaterialId: "bolt", jobOperationStepId: "s9", quantity: null }+ ],+ records: [{ jobOperationStepId: "s1", index: 0 }]+ });+ expect(issues).toEqual([]);+ });++ it("issues only the shortfall against what is already issued", () => {+ const issues = planStepBackflush({+ operationId: "op-1",+ stepIds: ["s1"],+ materials: [material({ id: "glue", quantity: 2, quantityIssued: 3 })],+ stepLinks: [],+ records: [+ { jobOperationStepId: "s1", index: 0 },+ { jobOperationStepId: "s1", index: 1 }+ ]+ });+ expect(issues).toEqual([+ { materialId: "glue", itemId: "item-glue", quantity: 1 }+ ]);+ });++ it("issues each step's share of a split line, capped at the line", () => {+ const issues = planStepBackflush({+ operationId: "op-1",+ stepIds: ["s1", "s2"],+ materials: [material({ id: "screw", quantity: 5 })],+ stepLinks: [+ { jobMaterialId: "screw", jobOperationStepId: "s1", quantity: 2 },+ { jobMaterialId: "screw", jobOperationStepId: "s2", quantity: 10 }+ ],+ records: [+ { jobOperationStepId: "s1", index: 0 },+ { jobOperationStepId: "s2", index: 0 }+ ]+ });+ expect(issues).toEqual([+ { materialId: "screw", itemId: "item-screw", quantity: 5 }+ ]);+ });+});++describe("ownsLooseMaterial", () => {+ it("owns its own and unassigned parts, never another operation's", () => {+ expect(ownsLooseMaterial({ jobOperationId: "op-1" }, "op-1")).toBe(true);+ expect(ownsLooseMaterial({ jobOperationId: null }, "op-1")).toBe(true);+ expect(ownsLooseMaterial({ jobOperationId: "op-2" }, "op-1")).toBe(false);+ });+});diff --git a/apps/mes/app/services/step-backflush.ts b/apps/mes/app/services/step-backflush.tsnew file mode 100644index 0000000000..7adc9636fd--- /dev/null+++ b/apps/mes/app/services/step-backflush.ts@@ -0,0 +1,141 @@+// 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.++/** An untracked job material the step-record backflush may issue. */+export type StepBackflushMaterial = {+ id: string;+ itemId: string;+ quantity: number | null;+ quantityIssued: number | null;+ jobOperationId: string | null;+};++export type StepBackflushLink = {+ jobMaterialId: string;+ jobOperationStepId: string;+ // NULL = the full BOM line quantity.+ quantity: number | null;+};++export type StepBackflushIssue = {+ materialId: string;+ itemId: string;+ quantity: number;+};++/**+ * Whether an operation owns a loose (step-unassigned) part: the part is on this+ * operation, or on no operation at all. A part attached to another operation of+ * the same make method is that operation's, the same attribution the completion+ * backflush (`issueJobOperationMaterials`, by `jobOperationId`) uses.+ */+export function ownsLooseMaterial(+ material: Pick<StepBackflushMaterial, "jobOperationId">,+ operationId: string+) {+ return (+ material.jobOperationId === null || material.jobOperationId === operationId+ );+}++/**+ * What recording one of an operation's steps issues. Step ownership:+ * • A step-assigned part (jobMaterialStep) is owned by its assigned step(s)+ * and issues when any of those steps is recorded for a unit.+ * • A loose part (no step assignment) is owned by its operation's FIRST step,+ * where the operator sees it. A loose part on another operation is skipped.+ * Per material the target is (distinct units that recorded an owning step) ×+ * per-unit quantity, and only the shortfall against `quantityIssued` is issued,+ * so re-records, undo/redo, manual issues and the completion backflush overlap+ * without double-issuing. A part assigned to several steps is counted once per+ * unit, so its requirement never multiplies. A line split across steps (per-link+ * quantities) issues each step's share, capped at the line.+ */+export function planStepBackflush(args: {+ operationId: string;+ // The operation's steps, in order.+ stepIds: string[];+ materials: StepBackflushMaterial[];+ stepLinks: StepBackflushLink[];+ records: { jobOperationStepId: string; index: number }[];+}): StepBackflushIssue[] {+ const firstStepId = args.stepIds[0];+ if (!firstStepId) return [];++ const ownedSteps = new Map<string, Set<string>>();+ const linkQuantities = new Map<string, Map<string, number | null>>();+ for (const link of args.stepLinks) {+ const set = ownedSteps.get(link.jobMaterialId) ?? new Set<string>();+ set.add(link.jobOperationStepId);+ ownedSteps.set(link.jobMaterialId, set);+ const quantities =+ linkQuantities.get(link.jobMaterialId) ??+ new Map<string, number | null>();+ quantities.set(link.jobOperationStepId, link.quantity);+ linkQuantities.set(link.jobMaterialId, quantities);+ }++ // Units (index) that have recorded each of the operation's steps.+ const unitsByStep = new Map<string, Set<number>>();+ for (const r of args.records) {+ const set = unitsByStep.get(r.jobOperationStepId) ?? new Set<number>();+ set.add(r.index);+ unitsByStep.set(r.jobOperationStepId, set);+ }++ const issues: StepBackflushIssue[] = [];+ for (const material of args.materials) {+ const perUnit = material.quantity ?? 0;+ if (perUnit <= 0) continue;+ // Owning steps: the material's assigned steps (scoped to this operation), or+ // the first step when it's loose and this operation owns it.+ const owning = ownedSteps.get(material.id);+ const isLoose = !owning || owning.size === 0;+ if (isLoose && !ownsLooseMaterial(material, args.operationId)) continue;+ const triggerStepIds = isLoose+ ? [firstStepId]+ : args.stepIds.filter((id) => owning.has(id));+ const quantities = linkQuantities.get(material.id);+ const hasSplitQuantities = triggerStepIds.some(+ (id) => (quantities?.get(id) ?? null) !== null+ );+ // Distinct units that recorded at least one owning step — the line-level+ // requirement bound: a material can never owe more than units × per-unit.+ const units = new Set<number>();+ for (const id of triggerStepIds) {+ for (const idx of unitsByStep.get(id) ?? []) units.add(idx);+ }+ let target: number;+ if (hasSplitQuantities) {+ // The line is SPLIT across steps (5 screws at step 1, 5 at step 2): each+ // owning step consumes its own share as it is recorded, so the target is+ // the per-step sum. A link left without an explicit quantity falls back+ // to the full per-unit quantity for its step. The sum is capped at the+ // line-level bound — the BOM line is the source of truth, so shares that+ // over-allocate the line (2 + 10 on a 5-quantity line) must not issue+ // more stock than the line requires.+ target = Math.min(+ triggerStepIds.reduce(+ (sum, id) =>+ sum ++ (unitsByStep.get(id)?.size ?? 0) * (quantities?.get(id) ?? perUnit),+ 0+ ),+ units.size * perUnit+ );+ } else {+ // Unsplit: distinct units counted once, so the requirement never+ // multiplies across a material's several owning steps.+ target = units.size * perUnit;+ }+ const delta = target - (material.quantityIssued ?? 0);+ if (delta <= 0) continue;+ issues.push({+ materialId: material.id,+ itemId: material.itemId,+ quantity: delta+ });+ }+ return issues;+}