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: refuse a batch shipment when the batch's bin cannot cover the quantity
aashu4f666469efe8
diff --git a/packages/server-functions/src/lib/storage-units.ts b/packages/server-functions/src/lib/storage-units.tsindex 574da41cd6..4a9fd5cd41 100644--- a/packages/server-functions/src/lib/storage-units.ts+++ b/packages/server-functions/src/lib/storage-units.ts@@ -3,7 +3,11 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import type { KyselyDatabase as DB } from "@carbon/database/client";-import { datetime, resolveTrackedEntityBins } from "@carbon/utils";+import {+ datetime,+ resolveTrackedEntityBins,+ type TrackedEntityBin+} from "@carbon/utils";import type { Kysely, Transaction } from "kysely";export async function getStorageUnitId(@@ -30,7 +34,7 @@ export async function getStorageUnitId(}/**- * Where each tracked entity holds stock, per location (see+ * Where each tracked entity holds stock, and how much, per location (see* `resolveTrackedEntityBins`: `null` is the unassigned bin). The lookup returns* `undefined` for an entity with no positive bin at that location.*/@@ -38,7 +42,7 @@ export async function getTrackedEntityBins(db: Kysely<DB>,args: { trackedEntityIds: string[]; locationIds: string[]; companyId: string }): Promise<- (trackedEntityId: string, locationId: string) => string | null | undefined+ (trackedEntityId: string, locationId: string) => TrackedEntityBin | undefined> {if (args.trackedEntityIds.length === 0 || args.locationIds.length === 0) {return () => undefined;@@ -52,17 +56,15 @@ export async function getTrackedEntityBins(.select(["trackedEntityId", "locationId", "storageUnitId", "quantity"]).execute();- const binsByLocation = new Map<string, Map<string, string | null>>();+ const binsByLocation = new Map<string, Map<string, TrackedEntityBin>>();for (const locationId of args.locationIds) {binsByLocation.set(locationId,resolveTrackedEntityBins(rows.filter((r) => r.locationId === locationId)));}- return (trackedEntityId, locationId) => {- const bins = binsByLocation.get(locationId);- return bins?.has(trackedEntityId) ? bins.get(trackedEntityId) : undefined;- };+ return (trackedEntityId, locationId) =>+ binsByLocation.get(locationId)?.get(trackedEntityId);}/** A tracked entity's on-hand in one bin; `null` is the unassigned bin. */diff --git a/packages/server-functions/src/post-shipment/index.ts b/packages/server-functions/src/post-shipment/index.tsindex 8ccb6cd3ac..0028e282c4 100644--- a/packages/server-functions/src/post-shipment/index.ts+++ b/packages/server-functions/src/post-shipment/index.ts@@ -303,7 +303,8 @@ const postShipment = defineServerFn({const locationId = shipmentHeader.locationId;// A serial or batch leaves the bin it actually holds stock in; the- // line's bin is only a default. One with no stock is refused.+ // line's bin is only a default. A unit whose bin cannot cover the+ // quantity is refused rather than driving that bin negative.const trackedEntityBins = await getTrackedEntityBins(db, {trackedEntityIds: (shipmentLineTracking.data ?? []).map((tracking) => tracking.id@@ -319,21 +320,27 @@ const postShipment = defineServerFn({});const sourceBin = (trackedEntityId: string | undefined,- lineLocationId: string | null+ lineLocationId: string | null,+ quantity: number): string | null => {const bin =trackedEntityId && lineLocationId? trackedEntityBins(trackedEntityId, lineLocationId): undefined;- if (bin === undefined) {- const readableId = shipmentLineTracking.data?.find(- (tracking) => tracking.id === trackedEntityId- )?.readableId;+ if (!bin || round(bin.quantity) < round(quantity)) {+ const readableId =+ shipmentLineTracking.data?.find(+ (tracking) => tracking.id === trackedEntityId+ )?.readableId ??+ trackedEntityId ??+ "A tracked item";throw new Error(- `${readableId ?? trackedEntityId ?? "A tracked item"} has no stock to ship at this location`+ bin+ ? `${readableId} has only ${round(bin.quantity)} in one storage unit, ${round(quantity)} needed. Move it into one storage unit first`+ : `${readableId} has no stock to ship at this location`);}- return bin;+ return bin.storageUnitId;};for await (const shipmentLine of shipmentLines.data) {@@ -493,7 +500,8 @@ const postShipment = defineServerFn({locationId: shipmentLine.locationId ?? locationId,storageUnitId: sourceBin(batchId,- shipmentLine.locationId ?? locationId+ shipmentLine.locationId ?? locationId,+ shippedQuantity),entryType: "Negative Adjmt.",documentType: "Sales Shipment",@@ -523,7 +531,8 @@ const postShipment = defineServerFn({locationId: shipmentLine.locationId ?? locationId,storageUnitId: sourceBin(tracking.id,- shipmentLine.locationId ?? locationId+ shipmentLine.locationId ?? locationId,+ 1),entryType: "Negative Adjmt.",documentType: "Sales Shipment",@@ -982,7 +991,8 @@ const postShipment = defineServerFn({bin: {storageUnitId: sourceBin(splitInfo.originalEntityId,- shipmentLine?.locationId ?? locationId+ shipmentLine?.locationId ?? locationId,+ splitInfo.shippedQuantity),locationId},diff --git a/packages/server-functions/src/tracked-entity-source-bin.test.ts b/packages/server-functions/src/tracked-entity-source-bin.test.tsindex 6d7c6260da..83b4fc7d03 100644--- a/packages/server-functions/src/tracked-entity-source-bin.test.ts+++ b/packages/server-functions/src/tracked-entity-source-bin.test.ts@@ -276,6 +276,50 @@ describe.skipIf(!hasLocalDatabase)("tracked entity source bin", () => {});+ databaseTest(+ "a shipment refuses a batch whose bin cannot cover the quantity",+ async () => {+ const lot = { itemId: batchItemId, quantity: 6 };+ const batch = await stockIn("ship-batch-spread", aftersales, lot);+ // The same batch also holds 4 in another bin, so 10 in total.+ await seed(f, (trx) =>+ trx+ .insertInto("itemLedger")+ .values({+ itemId: batchItemId,+ trackedEntityId: batch,+ quantity: 4,+ locationId: f.locationId,+ storageUnitId: readyToSell,+ entryType: "Positive Adjmt.",+ companyId: f.companyId,+ createdBy: USER+ })+ .execute()+ );+ await seed(f, (trx) =>+ trx+ .updateTable("trackedEntity")+ .set({ quantity: 10 })+ .where("id", "=", batch)+ .execute()+ );+ const shipmentId = await shipmentFor("ship-batch-spread", batch, {+ itemId: batchItemId,+ quantity: 8+ });++ const result = await postShipment(f.ctx, { type: "post", shipmentId });+ expect(result.error?.message).toMatch(+ /SN-ship-batch-spread has only 6 in one storage unit, 8 needed/+ );+ expect(await onHand(batch)).toEqual({+ [aftersales]: 6,+ [readyToSell]: 4+ });+ }+ );+databaseTest("a shipment refuses a serial with no stock", async () => {const serial = await stockIn("ship-empty", "none");const shipmentId = await shipmentFor("ship-empty", serial);diff --git a/packages/utils/src/resolve-tracked-entity-bin.test.ts b/packages/utils/src/resolve-tracked-entity-bin.test.tsindex 8ef907374b..ae2ceffe45 100644--- a/packages/utils/src/resolve-tracked-entity-bin.test.ts+++ b/packages/utils/src/resolve-tracked-entity-bin.test.ts@@ -56,8 +56,7 @@ describe("resolveTrackedEntityBins", () => {row("te", "aftersales", -1),row("te", null, 1)]);- expect(bins.get("te")).toBeNull();- expect(bins.has("te")).toBe(true);+ expect(bins.get("te")).toEqual({ storageUnitId: null, quantity: 1 });});it("picks the positive bin when another bin is negative", () => {@@ -66,7 +65,7 @@ describe("resolveTrackedEntityBins", () => {row("te", null, 1),row("te", "ready-to-sell", -1)]);- expect(bins.get("te")).toBeNull();+ expect(bins.get("te")).toEqual({ storageUnitId: null, quantity: 1 });});it("leaves out an entity with no positive bin", () => {@@ -84,8 +83,8 @@ describe("resolveTrackedEntityBins", () => {row("serial", "binC", 1),row(null, "binD", 9)]);- expect(bins.get("batch")).toEqual("binB");- expect(bins.get("serial")).toEqual("binC");+ expect(bins.get("batch")).toEqual({ storageUnitId: "binB", quantity: 15 });+ expect(bins.get("serial")).toEqual({ storageUnitId: "binC", quantity: 1 });expect(bins.size).toBe(2);});});diff --git a/packages/utils/src/resolve-tracked-entity-bin.ts b/packages/utils/src/resolve-tracked-entity-bin.tsindex 0ca596e690..09ec2d091e 100644--- a/packages/utils/src/resolve-tracked-entity-bin.ts+++ b/packages/utils/src/resolve-tracked-entity-bin.ts@@ -47,13 +47,19 @@ export function resolveTrackedEntityBin();}-// The bin each tracked entity holds stock in. Unlike `resolveTrackedEntityBin`,-// the unassigned bin (`null`) counts: a unit moved into "no storage unit" must-// not resolve back to the named bin it left. An entity with no positive bin is-// absent, so the caller decides what "no stock anywhere" means.+export type TrackedEntityBin = {+ storageUnitId: string | null;+ quantity: number;+};++// The bin each tracked entity holds stock in, with its on-hand there. Unlike+// `resolveTrackedEntityBin`, the unassigned bin (`null`) counts: a unit moved+// into "no storage unit" must not resolve back to the named bin it left. An+// entity with no positive bin is absent, so the caller decides what "no stock+// anywhere" means.export function resolveTrackedEntityBins(ledgers: BinLedgerRow[]-): Map<string, string | null> {+): Map<string, TrackedEntityBin> {const netByEntityBin = new Map<string, Map<string | null, number>>();for (const l of ledgers) {if (!l.trackedEntityId) continue;@@ -65,13 +71,11 @@ export function resolveTrackedEntityBins(netByEntityBin.set(l.trackedEntityId, bins);}- const result = new Map<string, string | null>();+ const result = new Map<string, TrackedEntityBin>();for (const [trackedEntityId, bins] of netByEntityBin) {- let bestQty = 0;- for (const [bin, qty] of bins) {- if (qty > bestQty) {- bestQty = qty;- result.set(trackedEntityId, bin);+ for (const [storageUnitId, quantity] of bins) {+ if (quantity > (result.get(trackedEntityId)?.quantity ?? 0)) {+ result.set(trackedEntityId, { storageUnitId, quantity });}}}