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: serials and batches leave the bin they are actually in on sales shipments and stock transfers
aashu522ab02b489d
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex cb2926539e..762f64ade6 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -289,6 +289,16 @@ Format: `Context → Problem → Rule → Applies to`**Applies to:** `packages/server-functions/src/issue/index.ts` and any server function inserting `itemLedger` rows for a tracked entity that may hold stock in multiple bins.+## A tracked entity's bin is where it IS, never the document line's bin — and "no storage unit" is a bin++**Context:** Sales order shipments booked every serial and batch against `shipmentLine.storageUnitId` (copied from the sales order line, which defaults to the item's default bin). A unit picked from any other bin drove the line's bin negative and left its real bin showing stock that had already shipped. The stock transfer picker had the matching gap: it listed every lot at the location, not the line's source bin, and an empty source (`fromStorageUnitId` null — the wizard's "No storage unit") meant "any bin".++**Problem:** A document line's bin is a default for untracked stock. For a serial or batch the ledger already knows the bin, and ignoring it corrupts two bins at once. `resolveTrackedEntityBin` skips the unassigned bin (`null`), so a unit moved into "no storage unit" resolves back to the named bin it left. And `NULL` as a filter value cannot also mean "no filter".++**Rule:** Book a tracked entity's outbound row against its actual bin: `resolveTrackedEntityBins` (`@carbon/utils`, null-aware) through `getTrackedEntityBins` (`server-functions/src/lib/storage-units.ts`). Refuse when it has no stock anywhere rather than falling back to the line's bin. A void reverses into the bin the posting used (read the posted `itemLedger` rows), not the line's. A bin filter that must express "no storage unit" takes an explicit switch (`p_filter_storage_unit` on `get_available_tracked_entities`) and compares with `IS NOT DISTINCT FROM`.++**Applies to:** `post-shipment` (Sales Order post/void, serial + batch), `post-stock-transfer` (`assertInSourceBin`), the stock transfer picker. Return and outbound-transfer shipments still use the line's bin.+## Biome does not apply 3rd-level nested configs — enforce Deno via an override**Context:** Bringing Supabase edge functions (`packages/database/supabase/functions/**`, Deno) into Biome's lint surface for the new `noConsole` rule. These files sit outside the linted globs (`apps/*/app/**`, `packages/*/src/**`) and were never Biome-formatted.diff --git a/.claude/rules/shipments-receipts-ui-patterns.md b/.claude/rules/shipments-receipts-ui-patterns.mdindex 3e3b736b9a..a3c4b26ca6 100644--- a/.claude/rules/shipments-receipts-ui-patterns.md+++ b/.claude/rules/shipments-receipts-ui-patterns.md@@ -148,7 +148,11 @@ the service-role client + Kysely `db.transaction()`, and branch on `sourceDocumequantity is less than the entity's — same `buildBatchSplitRecords` mechanism as SO). SO path: COGS`journalLine`s via `calculateCOGS` + `costLedger`, negative `itemLedger`, advances SO line`quantitySent`/`sentComplete` and SO `status`, updates `job.quantityShipped`/status for Job- fulfillment, and **splits** batch tracked entities when shipped qty < entity qty.+ fulfillment, and **splits** batch tracked entities when shipped qty < entity qty. A serial or+ batch is taken from the bin it actually holds stock in (`getTrackedEntityBins`, null = no+ storage unit), not `shipmentLine.storageUnitId`; the split is booked in that same bin, a unit+ with no stock anywhere refuses the post, and the void restores each unit to the bin its posting+ used.The shipment journal lines (SO pairs, fixed asset sale lines, return pairs) are builtby the pure `post-shipment/posting-lines.ts` from facts the posting gathers; theaccounting cutover's legacy backfill (`activate-accounting/legacy/shipment.ts`) callsdiff --git a/apps/erp/app/modules/inventory/inventory.models.test.ts b/apps/erp/app/modules/inventory/inventory.models.test.tsindex 8c1aadbb7b..0fa0c93ea1 100644--- a/apps/erp/app/modules/inventory/inventory.models.test.ts+++ b/apps/erp/app/modules/inventory/inventory.models.test.ts@@ -45,23 +45,17 @@ describe("storageUnitValidator", () => {describe("resolveStockTransferPickForward", () => {const base = {- storageUnitId: "bin-chosen" as string | null,- currentStorageUnitId: "bin-default" as string | null,lineQuantity: 10,pickedQuantity: 0};- it("forwards the picker quantity and chosen bin for a batch scan", () => {+ it("forwards the picker quantity for a batch scan", () => {const r = resolveStockTransferPickForward({...base,transferType: "batch",quantity: 3});- expect(r).toEqual({- ok: true,- quantity: 3,- fromStorageUnitId: "bin-chosen"- });+ expect(r).toEqual({ ok: true, quantity: 3 });});it("posts quantity 1 for a serial scan regardless of the picker quantity", () => {@@ -70,21 +64,7 @@ describe("resolveStockTransferPickForward", () => {transferType: "serial",quantity: 4});- expect(r).toEqual({- ok: true,- quantity: 1,- fromStorageUnitId: "bin-chosen"- });- });-- it("falls back to the highest-quantity bin when the picker sends none", () => {- const r = resolveStockTransferPickForward({- ...base,- transferType: "batch",- quantity: 3,- storageUnitId: null- });- expect(r.ok && r.fromStorageUnitId).toBe("bin-default");+ expect(r).toEqual({ ok: true, quantity: 1 });});it("refuses a pick on a fully-picked line", () => {diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.tsindex 4930d51b59..f4edb3ad38 100644--- a/apps/erp/app/modules/inventory/inventory.models.ts+++ b/apps/erp/app/modules/inventory/inventory.models.ts@@ -662,10 +662,9 @@ export const stockTransferLineScanValidator = z.object({trackedEntityId: z.string().min(1, { message: "Tracked entity ID is required" }),- // The picker sends the clamped pick quantity and the bin the user chose; the- // action forwards both to the server function (serial always posts 1).- quantity: z.number().positive({ message: "Quantity must be greater than 0" }),- storageUnitId: z.string().nullable().optional()+ // The picker sends the clamped pick quantity; the action forwards it to the+ // server function (serial always posts 1). The source bin is the line's own.+ quantity: z.number().positive({ message: "Quantity must be greater than 0" })});/**@@ -675,19 +674,14 @@ export const stockTransferLineScanValidator = z.object({* re-checks the same limits under a row lock (`resolvePick` in @carbon/utils).* - A serial scan always moves one unit; a batch scan moves the picker's* clamped quantity.- * - The bin the user chose wins; the highest-quantity bin is only a fallback.* - A line with no outstanding quantity (or a pick that exceeds it) is refused.*/export function resolveStockTransferPickForward(input: {transferType: "batch" | "serial";quantity: number;- storageUnitId: string | null | undefined;- currentStorageUnitId: string | null;lineQuantity: number;pickedQuantity: number;-}):- | { ok: true; quantity: number; fromStorageUnitId: string | null }- | { ok: false; message: string } {+}): { ok: true; quantity: number } | { ok: false; message: string } {// Round like the server function's resolvePick does, so the pre-check and the// post-lock re-check cannot disagree about a residue pick.const pickQuantity = round(@@ -713,11 +707,7 @@ export function resolveStockTransferPickForward(input: {message: `Only ${outstanding} left to pick on this line`};}- return {- ok: true,- quantity: pickQuantity,- fromStorageUnitId: input.storageUnitId ?? input.currentStorageUnitId- };+ return { ok: true, quantity: pickQuantity };}export const pickingListStatusType = [diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 31b7f2d6a1..104d6e4f18 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -948,6 +948,8 @@ export async function getAvailableTrackedEntities(excludeLineside?: boolean;excludeAllocated?: boolean;excludeLineId?: string | null;+ /** Only lots in this bin; `id: null` is the unassigned bin. */+ inStorageUnit?: { id: string | null };}) {return client.rpc("get_available_tracked_entities", {@@ -956,7 +958,9 @@ export async function getAvailableTrackedEntities(p_location_id: args.locationId,p_exclude_lineside: args.excludeLineside ?? false,p_exclude_allocated: args.excludeAllocated ?? false,- p_exclude_line_id: args.excludeLineId ?? undefined+ p_exclude_line_id: args.excludeLineId ?? undefined,+ p_filter_storage_unit: args.inStorageUnit !== undefined,+ p_storage_unit_id: args.inStorageUnit?.id ?? undefined});}diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 2b78e7aefe..d371b56d72 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -184,7 +184,7 @@{"name":"inventory_expandStorageUnitIdsWithDescendants","classification":"WRITE","paramCount":1,"schema":"f413382980a7","response":"681004346c78","injectAuth":"companyId","permission":"inventory:update","paginates":false},{"name":"inventory_generateInventoryCountLines","classification":"DESTRUCTIVE","paramCount":4,"schema":"7cf62698d5f8","response":"cddf8275afa1","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},{"name":"inventory_generatePickingList","classification":"DESTRUCTIVE","paramCount":4,"schema":"412bd8dbff31","response":"81802516b555","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},- {"name":"inventory_getAvailableTrackedEntities","classification":"READ","paramCount":5,"schema":"a254ee2edef1","response":"723554a256de","injectAuth":"companyId","permission":"inventory:view","paginates":false},+ {"name":"inventory_getAvailableTrackedEntities","classification":"READ","paramCount":6,"schema":"6a561d222e27","response":"723554a256de","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getBatchNumbersForItem","classification":"READ","paramCount":2,"schema":"786c6e7af03b","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getBatchProperties","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"9a2b986c906d","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getDefaultStorageUnitForJob","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"174e29b899b9","injectAuth":"companyId","permission":"inventory:view","paginates":false},diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsxindex 3cacb0e195..f57ad666ec 100644--- a/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx@@ -28,7 +28,6 @@ import {resolveStockTransferPickForward,stockTransferLineScanValidator} from "~/modules/inventory";-import { getItemStorageUnitQuantities } from "~/modules/items";import { getCompanySettings } from "~/modules/settings";import { getDatabaseClient } from "~/services/database.server";import { requireUnlocked } from "~/utils/lockedGuard.server";@@ -51,7 +50,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const line = await client.from("stockTransferLine").select(- "id, itemId, quantity, pickedQuantity, requiresSerialTracking, stockTransfer(locationId)"+ "id, itemId, quantity, pickedQuantity, requiresSerialTracking, fromStorageUnitId, stockTransfer(locationId)").eq("id", lineId).single();@@ -71,7 +70,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {locationId,// A stock transfer moves stock between bins in the warehouse, so// lineside (work-center) bins are not valid sources.- excludeLineside: true+ excludeLineside: true,+ // Only lots in the line's source bin can be picked for it; an+ // empty source is the unassigned bin, not "any bin".+ inStorageUnit: { id: line.data.fromStorageUnitId }}): { data: [] };@@ -126,41 +128,27 @@ export async function action({ request, params }: ActionFunctionArgs) {const {id: lineId,stockTransferId,- itemId,locationId,trackedEntityId,- quantity,- storageUnitId+ quantity} = validated.data;- const [stockTransferLine, itemStorageUnitQuantities] = await Promise.all([- client.from("stockTransferLines").select("*").eq("id", lineId!).single(),- getItemStorageUnitQuantities(client, itemId, companyId, locationId)- ]);+ const stockTransferLine = await client+ .from("stockTransferLines")+ .select("*")+ .eq("id", lineId!)+ .single();- if (stockTransferLine.error || itemStorageUnitQuantities.error) {+ if (stockTransferLine.error) {return data(- {- success: false,- message:- "Failed to load stock transfer line or item storage unit quantities"- },+ { success: false, message: "Failed to load stock transfer line" },await flash(request,- error(- stockTransferLine.error || itemStorageUnitQuantities.error,- "Failed to load stock transfer line or item storage unit quantities"- )+ error(stockTransferLine.error, "Failed to load stock transfer line")));}- const currentStorageUnitId =- itemStorageUnitQuantities.data- ?.sort((a, b) => b.quantity - a.quantity)- .find((q) => q.trackedEntityId === trackedEntityId)?.storageUnitId ??- null;-// Determine the type of transfer based on tracking requirementsconst transferType = stockTransferLine.data?.requiresBatchTracking? "batch"@@ -171,8 +159,6 @@ export async function action({ request, params }: ActionFunctionArgs) {const forward = resolveStockTransferPickForward({transferType,quantity,- storageUnitId,- currentStorageUnitId,lineQuantity: Number(stockTransferLine.data?.quantity ?? 0),pickedQuantity: Number(stockTransferLine.data?.pickedQuantity ?? 0)});@@ -190,7 +176,6 @@ export async function action({ request, params }: ActionFunctionArgs) {stockTransferLineId: lineId,trackedEntityId,quantity: forward.quantity,- fromStorageUnitId: forward.fromStorageUnitId,locationId: locationId,userId,companyId@@ -314,10 +299,8 @@ export default function StockTransferScan() {trackedEntityId: selection.trackedEntityId,itemId: stockTransferLine.itemId!,locationId,- // Forward the picker's clamped quantity and chosen bin — the host- // picking-list scanner does the same.- quantity: selection.quantity,- storageUnitId: selection.storageUnitId ?? null+ // Forward the picker's clamped quantity; the source bin is the line's.+ quantity: selection.quantity},{method: "POST",diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 8235c8cfd8..6e93f7f643 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -104017,6 +104017,13 @@ export default {name: "p_sort_method",required: false,type: "string"+ },+ {+ format: "text",+ in: "query",+ name: "p_storage_unit_id",+ required: false,+ type: "string"}],produces: [@@ -104066,6 +104073,10 @@ export default {p_sort_method: {format: "text",type: "string"+ },+ p_storage_unit_id: {+ format: "text",+ type: "string"}},required: ["p_item_id", "p_company_id", "p_location_id"],diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex dab2a35580..d68d582555 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -89800,9 +89800,11 @@ export type Database = {p_exclude_allocated?: booleanp_exclude_line_id?: stringp_exclude_lineside?: boolean+ p_filter_storage_unit?: booleanp_item_id: stringp_location_id: stringp_sort_method?: string+ p_storage_unit_id?: string}Returns: {availableQuantity: numberdiff --git a/packages/database/supabase/migrations/20261012153000_available-tracked-entities-storage-unit.sql b/packages/database/supabase/migrations/20261012153000_available-tracked-entities-storage-unit.sqlnew file mode 100644index 0000000000..4da2f6125d--- /dev/null+++ b/packages/database/supabase/migrations/20261012153000_available-tracked-entities-storage-unit.sql@@ -0,0 +1,120 @@+-- ============================================================================+-- Function: get_available_tracked_entities (storage-unit aware)+-- Adds a source-bin filter so a picker can offer only the lots that sit in one+-- bin. A stock transfer line names the bin it moves stock out of; the picker+-- listed every lot at the location instead, so lots from other bins were+-- offered and picking one moved stock the line never asked for.+--+-- p_filter_storage_unit — true restricts to p_storage_unit_id; false (default)+-- keeps the location-wide behavior.+-- p_storage_unit_id — the bin to restrict to. NULL is the unassigned bin+-- ("No storage unit"), a real source a line can name, which is why the+-- filter needs its own switch instead of treating NULL as "any bin".+--+-- All other behavior is unchanged from+-- 20260709125411_available-tracked-entities-sort-method.sql.+--+-- Drop the old 7-arg signature first so the defaulted new params do not+-- register a second, ambiguous overload.+-- ============================================================================++DROP FUNCTION IF EXISTS get_available_tracked_entities(+ TEXT, TEXT, TEXT, BOOLEAN, BOOLEAN, TEXT, TEXT+);++CREATE OR REPLACE FUNCTION get_available_tracked_entities(+ p_item_id TEXT,+ p_company_id TEXT,+ p_location_id TEXT,+ p_exclude_lineside BOOLEAN DEFAULT false,+ p_exclude_allocated BOOLEAN DEFAULT false,+ p_exclude_line_id TEXT DEFAULT NULL,+ p_sort_method TEXT DEFAULT 'Default',+ p_filter_storage_unit BOOLEAN DEFAULT false,+ p_storage_unit_id TEXT DEFAULT NULL+)+RETURNS TABLE (+ "trackedEntityId" TEXT,+ "readableId" TEXT,+ "storageUnitId" TEXT,+ "storageUnitName" TEXT,+ "availableQuantity" NUMERIC,+ "createdAt" TIMESTAMPTZ,+ "expirationDate" DATE,+ "status" TEXT+)+LANGUAGE sql+STABLE+SECURITY INVOKER+AS $$+ WITH bin_onhand AS (+ SELECT+ il."trackedEntityId",+ il."storageUnitId",+ s."name" AS storage_unit_name,+ SUM(il."quantity") AS on_hand+ FROM "itemLedger" il+ LEFT JOIN "storageUnit" s ON s."id" = il."storageUnitId"+ WHERE il."itemId" = p_item_id+ AND il."companyId" = p_company_id+ AND il."locationId" = p_location_id+ AND il."trackedEntityId" IS NOT NULL+ AND (+ NOT p_exclude_lineside+ OR get_effective_work_center_id(il."storageUnitId") IS NULL+ )+ AND (+ NOT p_filter_storage_unit+ OR il."storageUnitId" IS NOT DISTINCT FROM p_storage_unit_id+ )+ GROUP BY il."trackedEntityId", il."storageUnitId", s."name"+ HAVING SUM(il."quantity") > 0+ ),+ entity_total AS (+ SELECT "trackedEntityId", SUM(on_hand) AS total_on_hand+ FROM bin_onhand+ GROUP BY "trackedEntityId"+ ),+ primary_bin AS (+ SELECT DISTINCT ON ("trackedEntityId")+ "trackedEntityId", "storageUnitId", storage_unit_name+ FROM bin_onhand+ ORDER BY "trackedEntityId", on_hand DESC+ ),+ allocated AS (+ SELECT pllte."trackedEntityId", SUM(pllte."quantity") AS allocated_qty+ FROM "pickingListLineTrackedEntity" pllte+ JOIN "pickingListLine" pll ON pll."id" = pllte."pickingListLineId"+ JOIN "pickingList" pl ON pl."id" = pll."pickingListId"+ WHERE pl."status" <> 'Cancelled'+ AND pll."status" <> 'Cancelled'+ AND (p_exclude_line_id IS NULL OR pll."id" <> p_exclude_line_id)+ GROUP BY pllte."trackedEntityId"+ )+ SELECT+ et."trackedEntityId",+ te."readableId",+ pb."storageUnitId",+ pb.storage_unit_name AS "storageUnitName",+ et.total_on_hand+ - CASE WHEN p_exclude_allocated THEN COALESCE(a.allocated_qty, 0) ELSE 0 END+ AS "availableQuantity",+ te."createdAt",+ te."expirationDate",+ te."status"+ FROM entity_total et+ JOIN "trackedEntity" te ON te."id" = et."trackedEntityId"+ JOIN primary_bin pb ON pb."trackedEntityId" = et."trackedEntityId"+ LEFT JOIN allocated a ON a."trackedEntityId" = et."trackedEntityId"+ WHERE te."status" = 'Available'+ AND (+ et.total_on_hand+ - CASE WHEN p_exclude_allocated THEN COALESCE(a.allocated_qty, 0) ELSE 0 END+ ) > 0+ ORDER BY+ CASE WHEN COALESCE(p_sort_method, 'Default') IN ('Default', 'FEFO')+ THEN te."expirationDate" END ASC NULLS LAST,+ CASE WHEN COALESCE(p_sort_method, 'Default') = 'LIFO'+ THEN te."createdAt" END DESC,+ te."createdAt" ASC;+$$;diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex afbe36783f..757d5b6809 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20261012111443",+ "schemaVersion": "20261012153000","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-12T12:00:40.103Z",+ "exportedAt": "2026-10-12T17:09:04.683Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",diff --git a/packages/server-functions/src/lib/storage-units.ts b/packages/server-functions/src/lib/storage-units.tsindex 24ed804cf6..574da41cd6 100644--- a/packages/server-functions/src/lib/storage-units.ts+++ b/packages/server-functions/src/lib/storage-units.ts@@ -3,8 +3,8 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import type { KyselyDatabase as DB } from "@carbon/database/client";-import { datetime } from "@carbon/utils";-import type { Transaction } from "kysely";+import { datetime, resolveTrackedEntityBins } from "@carbon/utils";+import type { Kysely, Transaction } from "kysely";export async function getStorageUnitId(trx: Transaction<DB>,@@ -29,6 +29,63 @@ export async function getStorageUnitId(return storageUnitWithHighestQuantity ?? undefined;}+/**+ * Where each tracked entity holds stock, per location (see+ * `resolveTrackedEntityBins`: `null` is the unassigned bin). The lookup returns+ * `undefined` for an entity with no positive bin at that location.+ */+export async function getTrackedEntityBins(+ db: Kysely<DB>,+ args: { trackedEntityIds: string[]; locationIds: string[]; companyId: string }+): Promise<+ (trackedEntityId: string, locationId: string) => string | null | undefined+> {+ if (args.trackedEntityIds.length === 0 || args.locationIds.length === 0) {+ return () => undefined;+ }++ const rows = await db+ .selectFrom("itemLedger")+ .where("trackedEntityId", "in", args.trackedEntityIds)+ .where("locationId", "in", args.locationIds)+ .where("companyId", "=", args.companyId)+ .select(["trackedEntityId", "locationId", "storageUnitId", "quantity"])+ .execute();++ const binsByLocation = new Map<string, Map<string, string | null>>();+ 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;+ };+}++/** A tracked entity's on-hand in one bin; `null` is the unassigned bin. */+export async function getTrackedEntityOnHandInBin(+ trx: Transaction<DB>,+ args: {+ trackedEntityId: string;+ locationId: string;+ storageUnitId: string | null;+ companyId: string;+ }+): Promise<number> {+ const row = await trx+ .selectFrom("itemLedger")+ .where("trackedEntityId", "=", args.trackedEntityId)+ .where("locationId", "=", args.locationId)+ .where("storageUnitId", "is not distinct from", args.storageUnitId)+ .where("companyId", "=", args.companyId)+ .select((eb) => eb.fn.sum<number>("quantity").as("onHand"))+ .executeTakeFirst();+ return Number(row?.onHand ?? 0);+}+// Utility function to get the storage unit with the highest quantityexport async function getStorageUnitWithHighestQuantity(trx: Transaction<DB>,diff --git a/packages/server-functions/src/post-shipment/index.ts b/packages/server-functions/src/post-shipment/index.tsindex 341373beb6..8ccb6cd3ac 100644--- a/packages/server-functions/src/post-shipment/index.ts+++ b/packages/server-functions/src/post-shipment/index.ts@@ -52,6 +52,7 @@ import { getCurrentAccountingPeriod } from "../lib/get-accounting-period";import { getDefaultPostingGroup } from "../lib/get-posting-group";import { journalLineDimensionRows } from "../lib/journal-line-dimensions";import { assertPostable } from "../lib/postable";+import { getTrackedEntityBins } from "../lib/storage-units";import {buildReturnShipmentJournal,buildSalesShipmentJournal,@@ -300,6 +301,41 @@ const postShipment = defineServerFn({const serialNumbersConsumed: string[] = [];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.+ const trackedEntityBins = await getTrackedEntityBins(db, {+ trackedEntityIds: (shipmentLineTracking.data ?? []).map(+ (tracking) => tracking.id+ ),+ locationIds: [+ ...new Set(+ shipmentLines.data.flatMap(+ (line) => line.locationId ?? locationId ?? []+ )+ )+ ],+ companyId+ });+ const sourceBin = (+ trackedEntityId: string | undefined,+ lineLocationId: string | null+ ): string | null => {+ const bin =+ trackedEntityId && lineLocationId+ ? trackedEntityBins(trackedEntityId, lineLocationId)+ : undefined;+ if (bin === undefined) {+ const readableId = shipmentLineTracking.data?.find(+ (tracking) => tracking.id === trackedEntityId+ )?.readableId;+ throw new Error(+ `${readableId ?? trackedEntityId ?? "A tracked item"} has no stock to ship at this location`+ );+ }+ return bin;+ };+for await (const shipmentLine of shipmentLines.data) {if (shipmentLine.fulfillment?.type === "Job" &&@@ -442,23 +478,27 @@ const postShipment = defineServerFn({}if (shipmentLine.requiresBatchTracking) {+ const batchId = shipmentLineTracking.data?.find(+ (tracking) =>+ (+ tracking.attributes as+ | TrackedEntityAttributes+ | undefined+ )?.["Shipment Line"] === shipmentLine.id+ )?.id;itemLedgerInserts.push({postingDate: today,itemId: shipmentLine.itemId,quantity: round(-shippedQuantity),locationId: shipmentLine.locationId ?? locationId,- storageUnitId: shipmentLine.storageUnitId,+ storageUnitId: sourceBin(+ batchId,+ shipmentLine.locationId ?? locationId+ ),entryType: "Negative Adjmt.",documentType: "Sales Shipment",documentId: shipmentHeader.id ?? undefined,- trackedEntityId: shipmentLineTracking.data?.find(- (tracking) =>- (- tracking.attributes as- | TrackedEntityAttributes- | undefined- )?.["Shipment Line"] === shipmentLine.id- )?.id,+ trackedEntityId: batchId,externalDocumentId: undefined,createdBy: userId,companyId@@ -481,7 +521,10 @@ const postShipment = defineServerFn({itemId: shipmentLine.itemId,quantity: -1,locationId: shipmentLine.locationId ?? locationId,- storageUnitId: shipmentLine.storageUnitId,+ storageUnitId: sourceBin(+ tracking.id,+ shipmentLine.locationId ?? locationId+ ),entryType: "Negative Adjmt.",documentType: "Sales Shipment",documentId: shipmentHeader.id ?? undefined,@@ -935,8 +978,12 @@ const postShipment = defineServerFn({splitActivityId: nanoid(),activitySourceDocument: "Shipment",activitySourceDocumentId: shipmentId,+ // The same bin the shipment's own row draws from.bin: {- storageUnitId: shipmentLine?.storageUnitId ?? null,+ storageUnitId: sourceBin(+ splitInfo.originalEntityId,+ shipmentLine?.locationId ?? locationId+ ),locationId},itemLedgerItemId: shipmentLine?.itemId ?? null,@@ -2720,6 +2767,31 @@ const postShipment = defineServerFn({Database["public"]["Tables"]["job"]["Update"]> = {};+ // Put each serial or batch back in the bin its posting took it+ // from, which is not always the line's bin.+ const postedTrackedRows = await db+ .selectFrom("itemLedger")+ .where("documentId", "=", shipmentHeader.id)+ .where("documentType", "=", "Sales Shipment")+ .where("companyId", "=", companyId)+ .where("trackedEntityId", "is not", null)+ .where("quantity", "<", 0)+ .select(["trackedEntityId", "storageUnitId"])+ .execute();+ const postedTrackedBins = new Map<string, string | null>(+ postedTrackedRows.map((row) => [+ row.trackedEntityId as string,+ row.storageUnitId ?? null+ ])+ );+ const restoreBin = (+ trackedEntityId: string | undefined,+ lineStorageUnitId: string | null+ ) =>+ trackedEntityId && postedTrackedBins.has(trackedEntityId)+ ? (postedTrackedBins.get(trackedEntityId) ?? null)+ : lineStorageUnitId;+const locationId = shipmentHeader.locationId;for await (const shipmentLine of shipmentLines.data) {if (@@ -2820,23 +2892,27 @@ const postShipment = defineServerFn({}if (shipmentLine.requiresBatchTracking) {+ const batchId = shipmentLineTracking.data?.find(+ (tracking) =>+ (+ tracking.attributes as+ | TrackedEntityAttributes+ | undefined+ )?.["Shipment Line"] === shipmentLine.id+ )?.id;itemLedgerInserts.push({postingDate: today,itemId: shipmentLine.itemId,quantity: round(shippedQuantity), // Positive to restore inventorylocationId: shipmentLine.locationId ?? locationId,- storageUnitId: shipmentLine.storageUnitId,+ storageUnitId: restoreBin(+ batchId,+ shipmentLine.storageUnitId+ ),entryType: "Positive Adjmt.",documentType: "Sales Shipment",documentId: shipmentHeader.id ?? undefined,- trackedEntityId: shipmentLineTracking.data?.find(- (tracking) =>- (- tracking.attributes as- | TrackedEntityAttributes- | undefined- )?.["Shipment Line"] === shipmentLine.id- )?.id,+ trackedEntityId: batchId,externalDocumentId: undefined,createdBy: userId,companyId@@ -2859,7 +2935,10 @@ const postShipment = defineServerFn({itemId: shipmentLine.itemId,quantity: 1, // Positive to restore inventorylocationId: shipmentLine.locationId ?? locationId,- storageUnitId: shipmentLine.storageUnitId,+ storageUnitId: restoreBin(+ tracking.id,+ shipmentLine.storageUnitId+ ),entryType: "Positive Adjmt.",documentType: "Sales Shipment",documentId: shipmentHeader.id ?? undefined,diff --git a/packages/server-functions/src/post-stock-transfer/index.ts b/packages/server-functions/src/post-stock-transfer/index.tsindex 282f7e9212..f223912512 100644--- a/packages/server-functions/src/post-stock-transfer/index.ts+++ b/packages/server-functions/src/post-stock-transfer/index.ts@@ -15,12 +15,13 @@ import {round} from "@carbon/utils";import type { CalendarDate } from "@internationalized/date";-import type { Insertable } from "kysely";+import type { Insertable, Transaction } from "kysely";import { nanoid } from "nanoid";import { z } from "zod";import { assertCompanyRecords } from "../company-records";import { defineServerFn } from "../define-server-fn";import { NotFoundError } from "../errors";+import { getTrackedEntityOnHandInBin } from "../lib/storage-units";import {type ExpiredEntityPolicy,type ExpiryOverride,@@ -32,6 +33,31 @@ import { attributesContain } from "../tracked-entity-attributes";const logger = getLogger("server-functions", "post-stock-transfer");+/**+ * A line moves stock out of the bin it names, and only that bin (`null` is the+ * unassigned bin). Picking a unit held elsewhere would book its -1 against a+ * bin that does not hold it.+ */+async function assertInSourceBin(+ trx: Transaction<KyselyDatabase>,+ args: {+ trackedEntityId: string;+ readableId: string | null;+ quantity: number;+ locationId: string;+ storageUnitId: string | null;+ companyId: string;+ }+) {+ const onHand = await getTrackedEntityOnHandInBin(trx, args);+ if (round(onHand) < round(args.quantity)) {+ throw new PickGuardError(+ "over-pick",+ `${args.readableId ?? args.trackedEntityId} is not in this line's source storage unit`+ );+ }+}+/*** Applies the company's expired-entity policy to one entity about to be* transferred: a warning under `Warn`, a throw when blocked. An override with@@ -73,7 +99,6 @@ export const postStockTransferInput = z.discriminatedUnion("type", [stockTransferId: z.string(),stockTransferLineId: z.string(),trackedEntityId: z.string(),- fromStorageUnitId: z.string().nullable(),locationId: z.string()}),z.object({@@ -81,7 +106,6 @@ export const postStockTransferInput = z.discriminatedUnion("type", [stockTransferId: z.string(),stockTransferLineId: z.string(),trackedEntityId: z.string(),- fromStorageUnitId: z.string().nullable(),quantity: z.number().positive(),overrideExpired: z.boolean().optional(),overrideReason: z.string().optional(),@@ -119,9 +143,9 @@ const postStockTransfer = defineServerFn({// The permission check proves the caller may act in companyId, not that the// body's ids belong to it. Every case writes stockTransferId as the- // ledger/activity documentId and locationId / fromStorageUnitId onto this- // company's ledger rows, so they are re-read under companyId — and the line- // must be on the transfer the body names.+ // ledger/activity documentId and locationId onto this company's ledger+ // rows, so they are re-read under companyId — and the line must be on the+ // transfer the body names.{const { companyId, stockTransferId, stockTransferLineId, locationId } =validatedPayload;@@ -140,17 +164,6 @@ const postStockTransfer = defineServerFn({companyId,"Location");- await assertCompanyRecords(- db,- "storageUnit",- [- "fromStorageUnitId" in validatedPayload- ? validatedPayload.fromStorageUnitId- : null- ],- companyId,- "Storage unit"- );}const companyToday = datetime.today(@@ -319,7 +332,6 @@ const postStockTransfer = defineServerFn({case "serial": {const {- fromStorageUnitId,stockTransferId,stockTransferLineId,trackedEntityId,@@ -359,6 +371,16 @@ const postStockTransfer = defineServerFn({.forUpdate().executeTakeFirstOrThrow();+ const fromStorageUnitId = stockTransferLine.fromStorageUnitId;+ await assertInSourceBin(trx, {+ trackedEntityId,+ readableId: trackedEntity.readableId,+ quantity: 1,+ locationId,+ storageUnitId: fromStorageUnitId,+ companyId+ });+// Refuse a REPEAT scan of the same serial on this transfer. Each scan// posts a Transfer activity + a −1/+1 ledger pair, so a silent no-op// would let the ledger double; the guard is an explicit 400.@@ -400,8 +422,6 @@ const postStockTransfer = defineServerFn({"Stock Transfer Line": stockTransferLineId,"From Location": locationId,"To Location": locationId,- // The line's own column is overwritten with this same payload- // value later in the transaction — read the payload directly."From Shelf": fromStorageUnitId,"To Shelf": stockTransferLine.toStorageUnitId},@@ -464,7 +484,6 @@ const postStockTransfer = defineServerFn({.updateTable("stockTransferLine").set({trackedEntityId,- fromStorageUnitId: fromStorageUnitId,pickedQuantity: newPickedQuantity,updatedBy: userId,updatedAt: datetime.timestamp()@@ -479,7 +498,6 @@ const postStockTransfer = defineServerFn({case "batch": {const {- fromStorageUnitId,stockTransferId,stockTransferLineId,trackedEntityId,@@ -526,6 +544,15 @@ const postStockTransfer = defineServerFn({entityQuantity: Number(trackedEntity.quantity),transferQuantity: quantity});+ const fromStorageUnitId = stockTransferLine.fromStorageUnitId;+ await assertInSourceBin(trx, {+ trackedEntityId,+ readableId: trackedEntity.readableId,+ quantity,+ locationId,+ storageUnitId: fromStorageUnitId,+ companyId+ });// Expiry policy gate (throws on hard reject; returns warning for 'Warn').const expiredCheck = checkExpiredEntity(@@ -645,8 +672,6 @@ const postStockTransfer = defineServerFn({"Stock Transfer Line": stockTransferLineId,"From Location": locationId,"To Location": locationId,- // The line's own column is overwritten with this same payload- // value later in the transaction — read the payload directly."From Shelf": fromStorageUnitId,"To Shelf": stockTransferLine.toStorageUnitId},@@ -717,7 +742,6 @@ const postStockTransfer = defineServerFn({.updateTable("stockTransferLine").set({trackedEntityId: transferredEntityId,- fromStorageUnitId: fromStorageUnitId,pickedQuantity: newPickedQuantity,updatedBy: userId,updatedAt: datetime.timestamp()diff --git a/packages/server-functions/src/tracked-entity-source-bin.test.ts b/packages/server-functions/src/tracked-entity-source-bin.test.tsnew file mode 100644index 0000000000..6d7c6260da--- /dev/null+++ b/packages/server-functions/src/tracked-entity-source-bin.test.ts@@ -0,0 +1,397 @@+// 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.++// A serial leaves the bin it is actually in. A sales shipment booked it against+// the line's bin, and a stock transfer pick took it from wherever it sat, so a+// bin it was never in went negative while the real bin kept a unit that had+// already left.++import { sql } from "kysely";+import { afterAll, beforeAll, describe, expect } from "vitest";+import {+ alwaysPostFixture,+ type Fixture,+ seed,+ USER,+ unwrap+} from "./always-post-test-fixture";+import create from "./create";+import { databaseTest, hasLocalDatabase } from "./local-database-test-fixture";+import postShipment from "./post-shipment";+import postStockTransfer from "./post-stock-transfer";++describe.skipIf(!hasLocalDatabase)("tracked entity source bin", () => {+ let f: Fixture;+ let serialItemId: string;+ let batchItemId: string;+ let aftersales: string;+ let readyToSell: string;++ beforeAll(async () => {+ f = await alwaysPostFixture();+ serialItemId = `${f.prefix}-serial`;+ batchItemId = `${f.prefix}-batch`;+ aftersales = `${f.prefix}-aftersales`;+ readyToSell = `${f.prefix}-ready`;+ await seed(f, async (trx) => {+ await trx+ .insertInto("item")+ .values([+ {+ id: serialItemId,+ readableId: `${f.prefix}-VEH`,+ name: "Vehicle",+ type: "Part",+ itemTrackingType: "Serial",+ replenishmentSystem: "Buy",+ companyId: f.companyId,+ createdBy: USER+ },+ {+ id: batchItemId,+ readableId: `${f.prefix}-OIL`,+ name: "Oil",+ type: "Part",+ itemTrackingType: "Batch",+ replenishmentSystem: "Buy",+ companyId: f.companyId,+ createdBy: USER+ }+ ])+ .execute();+ await trx+ .updateTable("itemCost")+ .set({ costingMethod: "FIFO", unitCost: 10 })+ .where("itemId", "in", [serialItemId, batchItemId])+ .where("companyId", "=", f.companyId)+ .execute();+ await trx+ .insertInto("storageUnit")+ .values([+ {+ id: aftersales,+ name: "Aftersales",+ locationId: f.locationId,+ companyId: f.companyId,+ createdBy: USER+ },+ {+ id: readyToSell,+ name: "Ready to Sell",+ locationId: f.locationId,+ companyId: f.companyId,+ createdBy: USER+ }+ ])+ .execute();+ });+ });++ afterAll(async () => {+ await f?.cleanup();+ });++ /** A serial or batch on hand in `bin` (`null` = no storage unit), or with no stock. */+ async function stockIn(+ key: string,+ bin: string | null | "none",+ lot: { itemId: string; quantity: number } = {+ itemId: serialItemId,+ quantity: 1+ }+ ) {+ const id = `${f.prefix}-te-${key}`;+ await seed(f, async (trx) => {+ await trx+ .insertInto("trackedEntity")+ .values({+ id,+ readableId: `SN-${key}`,+ quantity: lot.quantity,+ status: "Available",+ sourceDocument: "Item",+ sourceDocumentId: lot.itemId,+ itemId: lot.itemId,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ if (bin === "none") return;+ await trx+ .insertInto("itemLedger")+ .values({+ itemId: lot.itemId,+ trackedEntityId: id,+ quantity: lot.quantity,+ locationId: f.locationId,+ storageUnitId: bin,+ entryType: "Positive Adjmt.",+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ });+ return id;+ }++ async function onHand(trackedEntityId: string) {+ const rows = await f.db+ .selectFrom("itemLedger")+ .where("trackedEntityId", "=", trackedEntityId)+ .where("companyId", "=", f.companyId)+ .groupBy("storageUnitId")+ .select(["storageUnitId", (eb) => eb.fn.sum<number>("quantity").as("q")])+ .execute();+ return Object.fromEntries(+ rows.map((r) => [r.storageUnitId ?? "none", Number(r.q)])+ );+ }++ /** A sales-order shipment whose line names Ready to Sell. */+ async function shipmentFor(+ key: string,+ trackedEntityId: string,+ line: { itemId: string; quantity: number } = {+ itemId: serialItemId,+ quantity: 1+ }+ ) {+ const salesOrderId = `${f.prefix}-so-${key}`;+ await seed(f, async (trx) => {+ await trx+ .insertInto("salesOrder")+ .values({+ id: salesOrderId,+ salesOrderId: `SO-${key}`,+ customerId: f.customerId,+ currencyCode: "USD",+ exchangeRate: 1,+ locationId: f.locationId,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ await trx+ .insertInto("salesOrderShipment")+ .values({ id: salesOrderId, companyId: f.companyId })+ .execute();+ await trx+ .insertInto("salesOrderLine")+ .values({+ salesOrderId,+ salesOrderLineType: "Part",+ itemId: line.itemId,+ saleQuantity: line.quantity,+ unitPrice: 25,+ methodType: "Pull from Inventory",+ unitOfMeasureCode: "EA",+ locationId: f.locationId,+ storageUnitId: readyToSell,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ });+ const shipment = unwrap(+ await create(f.ctx, {+ type: "shipmentFromSalesOrder",+ salesOrderId,+ locationId: f.locationId+ })+ );+ const shipmentLine = await f.db+ .selectFrom("shipmentLine")+ .where("shipmentId", "=", shipment.id)+ .select(["id", "storageUnitId"])+ .executeTakeFirstOrThrow();+ expect(shipmentLine.storageUnitId).toBe(readyToSell);+ await seed(f, (trx) =>+ trx+ .updateTable("trackedEntity")+ .set({+ attributes: JSON.stringify({+ Shipment: shipment.id,+ "Shipment Line": shipmentLine.id,+ "Shipment Line Index": 0+ })+ })+ .where("id", "=", trackedEntityId)+ .execute()+ );+ return shipment.id;+ }++ databaseTest(+ "a shipment takes the serial from the bin it is in, and a void puts it back there",+ async () => {+ const serial = await stockIn("ship", aftersales);+ const shipmentId = await shipmentFor("ship", serial);++ unwrap(await postShipment(f.ctx, { type: "post", shipmentId }));+ expect(await onHand(serial)).toEqual({ [aftersales]: 0 });++ unwrap(await postShipment(f.ctx, { type: "void", shipmentId }));+ expect(await onHand(serial)).toEqual({ [aftersales]: 1 });+ }+ );++ databaseTest(+ "a shipment takes a serial with no storage unit from no storage unit",+ async () => {+ const serial = await stockIn("ship-unassigned", null);+ const shipmentId = await shipmentFor("ship-unassigned", serial);++ unwrap(await postShipment(f.ctx, { type: "post", shipmentId }));+ expect(await onHand(serial)).toEqual({ none: 0 });+ }+ );++ databaseTest(+ "a partial batch shipment splits and ships from the batch's own bin",+ async () => {+ const lot = { itemId: batchItemId, quantity: 10 };+ const batch = await stockIn("ship-batch", aftersales, lot);+ const shipmentId = await shipmentFor("ship-batch", batch, {+ itemId: batchItemId,+ quantity: 4+ });++ unwrap(await postShipment(f.ctx, { type: "post", shipmentId }));++ const byBin = await f.db+ .selectFrom("itemLedger")+ .where("itemId", "=", batchItemId)+ .where("companyId", "=", f.companyId)+ .groupBy("storageUnitId")+ .select([+ "storageUnitId",+ (eb) => eb.fn.sum<number>("quantity").as("q")+ ])+ .execute();+ expect(+ Object.fromEntries(byBin.map((r) => [r.storageUnitId, Number(r.q)]))+ ).toEqual({ [aftersales]: 6 });+ expect(await onHand(batch)).toEqual({ [aftersales]: 6 });+ }+ );++ databaseTest("a shipment refuses a serial with no stock", async () => {+ const serial = await stockIn("ship-empty", "none");+ const shipmentId = await shipmentFor("ship-empty", serial);++ const result = await postShipment(f.ctx, { type: "post", shipmentId });+ expect(result.error?.message).toMatch(/SN-ship-empty has no stock/);+ expect(await onHand(serial)).toEqual({});+ });++ /** A transfer line moving one serial from `from` to the other bin. */+ async function transferLine(key: string, from: string | null) {+ const stockTransferId = `${f.prefix}-st-${key}`;+ const lineId = `${f.prefix}-stl-${key}`;+ await seed(f, async (trx) => {+ await trx+ .insertInto("stockTransfer")+ .values({+ id: stockTransferId,+ stockTransferId: `ST-${key}`,+ locationId: f.locationId,+ status: "In Progress",+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ await trx+ .insertInto("stockTransferLine")+ .values({+ id: lineId,+ stockTransferId,+ itemId: serialItemId,+ quantity: 1,+ requiresSerialTracking: true,+ fromStorageUnitId: from,+ toStorageUnitId: from === readyToSell ? aftersales : readyToSell,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ });+ return (trackedEntityId: string) =>+ postStockTransfer(f.ctx, {+ type: "serial",+ stockTransferId,+ stockTransferLineId: lineId,+ trackedEntityId,+ locationId: f.locationId+ });+ }++ databaseTest(+ "a transfer pick moves the serial out of the line's source bin",+ async () => {+ const serial = await stockIn("pick", aftersales);+ const pick = await transferLine("pick", aftersales);++ unwrap(await pick(serial));+ expect(await onHand(serial)).toEqual({+ [aftersales]: 0,+ [readyToSell]: 1+ });+ }+ );++ databaseTest(+ "a transfer pick refuses a serial held in another bin",+ async () => {+ const serial = await stockIn("pick-elsewhere", readyToSell);+ const pick = await transferLine("pick-elsewhere", aftersales);++ const result = await pick(serial);+ expect(result.error?.message).toMatch(+ /SN-pick-elsewhere is not in this line's source storage unit/+ );+ expect(await onHand(serial)).toEqual({ [readyToSell]: 1 });+ }+ );++ databaseTest(+ "the picker query lists only the source bin, and NULL is no storage unit",+ async () => {+ const unassigned = await stockIn("rpc-unassigned", null);+ const binned = await stockIn("rpc-binned", aftersales);+ const available = async (filter: boolean, bin: string | null) => {+ const { rows } = await sql<{ trackedEntityId: string }>`+ SELECT "trackedEntityId" FROM get_available_tracked_entities(+ p_item_id => ${serialItemId},+ p_company_id => ${f.companyId},+ p_location_id => ${f.locationId},+ p_filter_storage_unit => ${filter},+ p_storage_unit_id => ${bin}+ )`.execute(f.db);+ return rows.map((r) => r.trackedEntityId);+ };++ expect(await available(true, null)).toContain(unassigned);+ expect(await available(true, null)).not.toContain(binned);+ expect(await available(true, aftersales)).toContain(binned);+ expect(await available(true, aftersales)).not.toContain(unassigned);+ expect(await available(false, null)).toEqual(+ expect.arrayContaining([unassigned, binned])+ );+ }+ );++ databaseTest(+ "an empty source bin means no storage unit, not any bin",+ async () => {+ const unassigned = await stockIn("pick-unassigned", null);+ const binned = await stockIn("pick-binned", aftersales);++ unwrap(await (await transferLine("pick-unassigned", null))(unassigned));+ expect(await onHand(unassigned)).toEqual({ none: 0, [readyToSell]: 1 });++ const result = await (await transferLine("pick-binned", null))(binned);+ expect(result.error?.message).toMatch(/not in this line's source/);+ }+ );+});diff --git a/packages/utils/src/resolve-tracked-entity-bin.test.ts b/packages/utils/src/resolve-tracked-entity-bin.test.tsindex b04c2bd3ff..8ef907374b 100644--- a/packages/utils/src/resolve-tracked-entity-bin.test.ts+++ b/packages/utils/src/resolve-tracked-entity-bin.test.ts@@ -2,8 +2,11 @@// 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 { expect, it } from "vitest";-import { resolveTrackedEntityBin } from "./resolve-tracked-entity-bin";+import { describe, expect, it } from "vitest";+import {+ resolveTrackedEntityBin,+ resolveTrackedEntityBins+} from "./resolve-tracked-entity-bin";const row = (trackedEntityId: string | null,@@ -44,3 +47,45 @@ it("returns null when the entity has no bins", () => {expect(resolveTrackedEntityBin([row("other", "a", 1)], "te")).toEqual(null);expect(resolveTrackedEntityBin([row("te", null, 1)], "te")).toEqual(null);});++describe("resolveTrackedEntityBins", () => {+ it("counts the unassigned bin as a real bin", () => {+ // Moved from "aftersales" into no storage unit.+ const bins = resolveTrackedEntityBins([+ row("te", "aftersales", 1),+ row("te", "aftersales", -1),+ row("te", null, 1)+ ]);+ expect(bins.get("te")).toBeNull();+ expect(bins.has("te")).toBe(true);+ });++ it("picks the positive bin when another bin is negative", () => {+ // A shipment once booked this unit against a bin it was never in.+ const bins = resolveTrackedEntityBins([+ row("te", null, 1),+ row("te", "ready-to-sell", -1)+ ]);+ expect(bins.get("te")).toBeNull();+ });++ it("leaves out an entity with no positive bin", () => {+ const bins = resolveTrackedEntityBins([+ row("te", "binA", 1),+ row("te", "binA", -1)+ ]);+ expect(bins.has("te")).toBe(false);+ });++ it("resolves each entity independently, highest net wins", () => {+ const bins = resolveTrackedEntityBins([+ row("batch", "binA", 5),+ row("batch", "binB", 15),+ row("serial", "binC", 1),+ row(null, "binD", 9)+ ]);+ expect(bins.get("batch")).toEqual("binB");+ expect(bins.get("serial")).toEqual("binC");+ 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 8b8c58ddbe..0ca596e690 100644--- a/packages/utils/src/resolve-tracked-entity-bin.ts+++ b/packages/utils/src/resolve-tracked-entity-bin.ts@@ -46,3 +46,34 @@ export function resolveTrackedEntityBin()?.storageUnitId ?? null);}++// 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 function resolveTrackedEntityBins(+ ledgers: BinLedgerRow[]+): Map<string, string | null> {+ const netByEntityBin = new Map<string, Map<string | null, number>>();+ for (const l of ledgers) {+ if (!l.trackedEntityId) continue;+ const bins = netByEntityBin.get(l.trackedEntityId) ?? new Map();+ bins.set(+ l.storageUnitId,+ (bins.get(l.storageUnitId) ?? 0) + Number(l.quantity ?? 0)+ );+ netByEntityBin.set(l.trackedEntityId, bins);+ }++ const result = new Map<string, string | null>();+ for (const [trackedEntityId, bins] of netByEntityBin) {+ let bestQty = 0;+ for (const [bin, qty] of bins) {+ if (qty > bestQty) {+ bestQty = qty;+ result.set(trackedEntityId, bin);+ }+ }+ }+ return result;+}