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
feat(mes): suggest batch on issue + return unused picks at job complete
Sidwebworks5b4d020d75ae
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 5d30248362..46c22912b6 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -105,3 +105,23 @@ Format: `Context → Problem → Rule → Applies to`**Rule:** In SQL functions: (1) any UPDATE issued by a trigger/interceptor that other interceptors may react to must stamp `"updatedBy"` (from the payload's `createdBy`/`updatedBy`) and `"updatedAt"`; (2) never write a payload user field into a NOT NULL column without a fallback — `COALESCE(p_new->>'updatedBy', p_new->>'createdBy')` (`createdBy` is NOT NULL on source tables); (3) functions taking `p_user_id` that write audit columns must not default it to NULL, or must guard right after `BEGIN` with a fallback to the entity's `createdBy` (see `20260706182830_fix-null-user-audit-columns.sql`). When forking a large function to add such a guard, extract the newest body verbatim (sed) and diff-verify instead of retyping.**Applies to:** `packages/database/supabase/migrations/` — all `sync_*` interceptors and any PL/pgSQL function writing `createdBy`/`updatedBy`/`postedBy`; reviews of new event-system interceptors.++## A LANGUAGE sql set-returning function's internal ORDER BY is not guaranteed through PostgREST++**Context:** `get_available_tracked_entities` (a `LANGUAGE sql STABLE` set-returning function) was extended with a `p_sort_method` param and a CASE-based `ORDER BY` (FEFO/FIFO/LIFO) to power an on-the-fly picking suggestion. FEFO worked, but calling the RPC for FIFO returned rows in the wrong order — its only effective sort key was the trailing `te."createdAt" ASC`, which came back unordered. Adding an explicit outer `ORDER BY "createdAt"` at the call site fixed it, proving the function's internal order was being dropped.++**Problem:** The Postgres planner **inlines** simple `LANGUAGE sql` functions into the calling query; when the caller (here, PostgREST via `client.rpc(...)`) supplies no outer `ORDER BY`, the inlined subquery's `ORDER BY` can be optimized away. Ordering that leads with a real indexed/leading column (expiration for FEFO) may survive by luck; ordering whose only key is a trailing column silently does not. Unit tests and typecheck can't catch this — only real-data querying does.++**Rule:** Do not rely on a `LANGUAGE sql` set-returning function's internal `ORDER BY` to reach the app. Either (a) sort authoritatively in the app after the RPC returns (return the sort columns and order in TS — see `apps/mes/app/services/allocation.ts` `sortLotsByPickMethod`, applied in `getSuggestedAllocationForMaterial`), or (b) if ordering must live in SQL, use `LANGUAGE plpgsql` with `RETURN QUERY ... ORDER BY` (plpgsql is never inlined). Always verify RPC ordering against seeded real data, not just unit tests.++**Applies to:** `packages/database/supabase/migrations/` set-returning `LANGUAGE sql` functions consumed via `client.rpc(...)`; any app code that greedy-fills / picks "the first row" from an RPC result.++## Tracked consumption/split must book against the entity's ACTUAL bin, not an arbitrary ledger row++**Context:** Building "return unused picks at job complete" surfaced a pre-existing bug in the `issue` edge function (`trackedEntitiesToOperation`). Consuming a batch that had been picked to a lineside shelf booked the Consumption + split `itemLedger` rows against `itemLedgers.find(il => il.trackedEntityId === id)?.storageUnitId` — the FIRST row for the entity in a `createdBy`-ordered list, i.e. an arbitrary bin. A picked entity has ledger rows in BOTH its warehouse source and its lineside bin, so consumption landed on the warehouse bin, leaving the entity at −N on-hand in one bin / +N in another: a per-bin-negative, internally inconsistent ledger, and the un-consumed remainder (a split entity) stranded on the wrong bin.++**Problem:** For a tracked entity that has moved between bins (pick/transfer), "which bin holds the stock" is NOT the first ledger row — it's the bin whose net on-hand is positive. Picking any row's `storageUnitId` silently misplaces consumption and breaks any downstream feature that reasons about physical location (e.g. returning lineside remainder to source).++**Rule:** When booking a consumption/split/movement ledger row for a tracked entity, resolve the storage unit from **net on-hand per bin** (the bin with the highest positive net), never `.find(...)?.storageUnitId` over an unordered/`createdBy`-ordered list. See `resolveTrackedEntityBin` (`packages/database/supabase/functions/issue/resolve-tracked-entity-bin.ts`, pure + `deno test`-covered). Scope such a fix to the path you can verify — the same `.find` pattern exists in other cases (e.g. `unconsumeTrackedEntities`); don't blanket-replace untested paths.++**Applies to:** `packages/database/supabase/functions/issue/index.ts` and any edge function inserting `itemLedger` rows for a tracked entity that may hold stock in multiple bins.diff --git a/.ai/rules/mes-job-operation-ui.md b/.ai/rules/mes-job-operation-ui.mdindex d4c1df3e76..9cb4a832c4 100644--- a/.ai/rules/mes-job-operation-ui.md+++ b/.ai/rules/mes-job-operation-ui.md@@ -27,6 +27,14 @@ steps/parameters, files, serials, and scrap/rework/finish actions.`path.to.endOperation(id)` (`/x/end/:operationId`); rework targets at`path.to.reworkTargets(id)`. Start/end routes write `productionEvent` /`productionQuantity` (end calls `finishJobOperation`).+- **`finishJobOperation`** (`operations.service.ts`) flips the op to `Done` (firing+ the `sync_finish_job_operation` trigger that completes the job to inventory when+ it's the last op). It then runs `returnAllocatedRemaindersAtJobComplete`: once+ `job.status='Completed'`, it sweeps the job's tracked (batch/serial) picking-list+ allocations and invokes the `post-picking` `returnPickedRemainder` case (via the+ service-role client) to return each un-consumed lineside remainder to its+ warehouse source. The SQL trigger can't call edge functions, so this is+ orchestrated in TS.## Componentsdiff --git a/.ai/rules/traceability-model.md b/.ai/rules/traceability-model.mdindex 7879e6ecf7..98d90ad066 100644--- a/.ai/rules/traceability-model.md+++ b/.ai/rules/traceability-model.md@@ -104,7 +104,20 @@ entities for picking. These return **`storageUnitId` / `storageUnitName`** (`stotable) — the modern naming after the `shelf` → `storageUnit` rename. They net out`pickingListLineTrackedEntity` allocations, drop lineside (work-center) bins, and order byFEFO (`expirationDate ASC NULLS LAST`) then FIFO (`createdAt ASC`). Powers the shared-`packages/react/src/TrackedEntityPicker.tsx`.+`packages/react/src/TrackedEntityPicker.tsx`. `get_available_tracked_entities` also+takes `p_sort_method` (`Default|FEFO|FIFO|LIFO`) — but its internal `ORDER BY` is not+guaranteed through PostgREST (SQL-function inlining), so callers that need a specific+order sort in the app (MES `sortLotsByPickMethod` in `apps/mes/app/services/allocation.ts`).++**Pick → consume → return lifecycle (batch/serial):** a **pick** (`post-picking`) is an+`itemLedger` Transfer warehouse→lineside; **consumption** (`issue` `trackedEntitiesToOperation`)+posts a negative Consumption row and, on partial use, **splits** the entity — the un-consumed+remainder becomes a NEW `trackedEntity` (a Split descendant), NOT the originally-picked one, and+`pickingListLineTrackedEntity` is not updated. Consumption/split rows are booked against the+entity's actual on-hand bin (`resolveTrackedEntityBin`), not an arbitrary ledger row. At job+complete, `post-picking` `returnPickedRemainder` walks the picked entity's split lineage and+transfers each lineage entity's remaining lineside on-hand back to source (decrementing+`pickingListLineTrackedEntity`/`pickingListLine.quantityPicked`).**Gotcha:** the older `get_item_quantities_by_tracking_id` (`20260101163400`) still emitslegacy `shelfId` / `shelfName` and joins the `shelf` table — both column sets exist; checkdiff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 93c13f667f..02f5ca7980 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,5 +1,5 @@{- "generated": "2026-07-07T02:25:35.624Z",+ "generated": "2026-07-09T15:17:16.810Z","totalTools": 1263,"modules": 15,"tools": [diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsxindex 3008a62387..c392ce7e92 100644--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx@@ -65,7 +65,8 @@ import { useFetcher } from "react-router";import { PrintButton } from "~/components";import type {getBatchNumbersForItem,- getSerialNumbersForItem+ getSerialNumbersForItem,+ SuggestedAllocationLot} from "~/services/inventory.service";import { convertEntityValidator, issueValidator } from "~/services/models";import type { JobMaterial, TrackedInput } from "~/services/types";@@ -306,6 +307,66 @@ export function IssueMaterialModal({// Tab stateconst [activeTab, setActiveTab] = useState("scan");+ // When no picking list has allocated this tracked material, suggest the same+ // lots a picking list would (netting + the item's pickMethod sort) and pre-fill+ // the selection. The suggestion is a default only — fully editable below.+ const pickedOverlay = material as+ | { quantityToPick?: number | null; quantityPicked?: number | null }+ | undefined;+ const hasPickingAllocation =+ Number(pickedOverlay?.quantityToPick ?? 0) > 0 ||+ Number(pickedOverlay?.quantityPicked ?? 0) > 0;+ const shouldSuggestAllocation =+ !!material &&+ !!selectedItemId &&+ !!locationId &&+ !hasPickingAllocation &&+ (trackingType === "Batch" || trackingType === "Serial");+ const { data: suggestedAllocation } = useSuggestedAllocation(+ shouldSuggestAllocation+ ? {+ itemId: selectedItemId,+ locationId: locationId as string,+ quantity: initialQuantity+ }+ : undefined+ );+ const hasSeededSuggestionRef = useRef(false);+ useEffect(() => {+ if (hasSeededSuggestionRef.current) return;+ if (!suggestedAllocation.length) return;+ if (trackingType === "Batch") {+ // Don't clobber a selection the operator already started if the (async)+ // suggestion arrives after they picked.+ if (selectedBatchNumbers.some((b) => b.id)) return;+ setSelectedBatchNumbers(+ suggestedAllocation.map((lot, index) => ({+ index,+ id: lot.trackedEntityId,+ quantity: lot.quantity+ }))+ );+ setActiveTab("select");+ hasSeededSuggestionRef.current = true;+ } else if (trackingType === "Serial") {+ if (selectedSerialNumbers.some((s) => s.id)) return;+ setSelectedSerialNumbers((prev) =>+ prev.map((row, i) =>+ suggestedAllocation[i]+ ? { ...row, id: suggestedAllocation[i].trackedEntityId }+ : row+ )+ );+ setActiveTab("select");+ hasSeededSuggestionRef.current = true;+ }+ }, [+ suggestedAllocation,+ trackingType,+ selectedBatchNumbers,+ selectedSerialNumbers+ ]);+// Expiry override state. Surfaced when a selected serial/batch is expired.// Server enforces the actual company policy (Warn / Block / BlockWithOverride);// this UI lets the operator type a reason that the server records when the@@ -1898,3 +1959,32 @@ function useBatchNumbers(itemId?: string) {return { data: batchNumbersFetcher.data };}++// Hook for the on-the-fly picking-list-style allocation suggestion.+// Loads only when args are provided (tracked item, no picking allocation).+function useSuggestedAllocation(args?: {+ itemId: string;+ locationId: string;+ quantity: number;+}) {+ const fetcher = useFetcher<{ data: SuggestedAllocationLot[]; error: null }>();+ const key =+ args && args.itemId && args.locationId && args.quantity > 0+ ? `${args.itemId}:${args.locationId}:${args.quantity}`+ : undefined;++ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed on args identity+ useEffect(() => {+ if (args && key) {+ fetcher.load(+ path.to.api.suggestedAllocation(+ args.itemId,+ args.locationId,+ args.quantity+ )+ );+ }+ }, [key]);++ return { data: fetcher.data?.data ?? [] };+}diff --git a/apps/mes/app/routes/api+/suggested-allocation.ts b/apps/mes/app/routes/api+/suggested-allocation.tsnew file mode 100644index 0000000000..6da3e3e1fd--- /dev/null+++ b/apps/mes/app/routes/api+/suggested-allocation.ts@@ -0,0 +1,30 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type { LoaderFunctionArgs } from "react-router";+import { getSuggestedAllocationForMaterial } from "~/services/inventory.service";++/**+ * On-the-fly batch/lot suggestion for issuing a tracked material with no picking+ * list linked — the same allocation the picking list would compute, per material.+ * `companyId` is derived from the session, never trusted from the client.+ */+export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {});++ const url = new URL(request.url);+ const itemId = url.searchParams.get("itemId");+ const locationId = url.searchParams.get("locationId");+ const quantity = Number(url.searchParams.get("quantity") ?? "0");++ if (!itemId || !locationId || !Number.isFinite(quantity) || quantity <= 0) {+ return { data: [], error: null };+ }++ const data = await getSuggestedAllocationForMaterial(client, {+ itemId,+ companyId,+ locationId,+ quantity+ });++ return { data, error: null };+}diff --git a/apps/mes/app/services/allocation.ts b/apps/mes/app/services/allocation.tsnew file mode 100644index 0000000000..e320993183--- /dev/null+++ b/apps/mes/app/services/allocation.ts@@ -0,0 +1,101 @@+/**+ * Pure allocation helpers, kept free of the `@carbon/auth` import chain so they+ * can be unit-tested without booting env validation. Re-exported from+ * `inventory.service.ts` for call sites.+ */++export type SuggestedAllocationLot = {+ trackedEntityId: string;+ readableId: string | null;+ quantity: number;+ expirationDate: string | null;+ storageUnitId: string | null;+ storageUnitName: string | null;+};++export type PickMethodSortMethod = "Default" | "FEFO" | "FIFO" | "LIFO";++type SortableLot = {+ createdAt?: string | null;+ expirationDate?: string | null;+};++// String date compare treating null/empty as "largest" (sorts last on ASC).+function cmpNullable(+ a: string | null | undefined,+ b: string | null | undefined+) {+ const av = a ?? "";+ const bv = b ?? "";+ if (av === bv) return 0;+ if (av === "") return 1;+ if (bv === "") return -1;+ return av < bv ? -1 : 1;+}++/**+ * Order lots by the item's pick method — the authoritative ordering for the+ * on-the-fly suggestion. We sort here in TS rather than trusting the RPC's+ * internal ORDER BY because a `LANGUAGE sql` set-returning function is inlined by+ * the planner and its ordering is NOT guaranteed to survive through PostgREST+ * (verified: FIFO's `createdAt`-only order was dropped). Stable + pure.+ * Default/FEFO → expiration asc (nulls last), then createdAt asc+ * FIFO → createdAt asc+ * LIFO → createdAt desc+ */+export function sortLotsByPickMethod<T extends SortableLot>(+ lots: T[],+ sortMethod: PickMethodSortMethod | string+): T[] {+ const sorted = [...lots];+ if (sortMethod === "FIFO") {+ sorted.sort((a, b) => cmpNullable(a.createdAt, b.createdAt));+ } else if (sortMethod === "LIFO") {+ sorted.sort((a, b) => -cmpNullable(a.createdAt, b.createdAt));+ } else {+ // Default / FEFO+ sorted.sort(+ (a, b) =>+ cmpNullable(a.expirationDate, b.expirationDate) ||+ cmpNullable(a.createdAt, b.createdAt)+ );+ }+ return sorted;+}++/**+ * Greedily fill `quantity` from an ordered pool of available lots (the pool must+ * already be in pick order — FEFO/FIFO/LIFO). Takes `min(lot on-hand, remaining)`+ * from each lot, spilling to the next when one is exhausted, and stops once the+ * quantity is covered. Never suggests more than a lot's on-hand. Pure + total.+ */+export function greedyFillAllocation(+ pool: Array<{+ trackedEntityId: string;+ readableId: string | null;+ availableQuantity: number;+ expirationDate?: string | null;+ storageUnitId?: string | null;+ storageUnitName?: string | null;+ }>,+ quantity: number+): SuggestedAllocationLot[] {+ const picks: SuggestedAllocationLot[] = [];+ let remaining = quantity;+ for (const lot of pool) {+ if (remaining <= 0) break;+ const available = Number(lot.availableQuantity ?? 0);+ if (available <= 0) continue;+ const take = Math.min(available, remaining);+ picks.push({+ trackedEntityId: lot.trackedEntityId,+ readableId: lot.readableId,+ quantity: take,+ expirationDate: lot.expirationDate ?? null,+ storageUnitId: lot.storageUnitId ?? null,+ storageUnitName: lot.storageUnitName ?? null+ });+ remaining -= take;+ }+ return picks;+}diff --git a/apps/mes/app/services/inventory.greedy.test.ts b/apps/mes/app/services/inventory.greedy.test.tsnew file mode 100644index 0000000000..dc1bf47112--- /dev/null+++ b/apps/mes/app/services/inventory.greedy.test.ts@@ -0,0 +1,112 @@+import { describe, expect, it } from "vitest";+import { greedyFillAllocation, sortLotsByPickMethod } from "./allocation";++const lot = (id: string, availableQuantity: number) => ({+ trackedEntityId: id,+ readableId: id,+ availableQuantity+});++describe("greedyFillAllocation", () => {+ it("spills across lots to cover the quantity", () => {+ const picks = greedyFillAllocation([lot("A", 3), lot("B", 5)], 4);+ expect(picks).toEqual([+ {+ trackedEntityId: "A",+ readableId: "A",+ quantity: 3,+ expirationDate: null,+ storageUnitId: null,+ storageUnitName: null+ },+ {+ trackedEntityId: "B",+ readableId: "B",+ quantity: 1,+ expirationDate: null,+ storageUnitId: null,+ storageUnitName: null+ }+ ]);+ });++ it("stops at a single lot when it covers the quantity", () => {+ const picks = greedyFillAllocation([lot("A", 3), lot("B", 5)], 2);+ expect(picks).toEqual([+ {+ trackedEntityId: "A",+ readableId: "A",+ quantity: 2,+ expirationDate: null,+ storageUnitId: null,+ storageUnitName: null+ }+ ]);+ });++ it("never suggests more than the total on-hand", () => {+ const picks = greedyFillAllocation([lot("A", 3), lot("B", 5)], 100);+ expect(picks.map((p) => p.quantity)).toEqual([3, 5]);+ });++ it("returns nothing for zero or negative quantity", () => {+ expect(greedyFillAllocation([lot("A", 3)], 0)).toEqual([]);+ expect(greedyFillAllocation([lot("A", 3)], -1)).toEqual([]);+ });++ it("skips lots with no on-hand", () => {+ const picks = greedyFillAllocation([lot("A", 0), lot("B", 2)], 2);+ expect(picks).toEqual([+ {+ trackedEntityId: "B",+ readableId: "B",+ quantity: 2,+ expirationDate: null,+ storageUnitId: null,+ storageUnitName: null+ }+ ]);+ });++ it("preserves lot pick order (does not reorder the pool)", () => {+ const picks = greedyFillAllocation([lot("B", 1), lot("A", 1)], 2);+ expect(picks.map((p) => p.trackedEntityId)).toEqual(["B", "A"]);+ });+});++describe("sortLotsByPickMethod", () => {+ // Two lots whose expiry order is the opposite of their creation order.+ const A = { id: "A", createdAt: "2026-01-01", expirationDate: "2026-12-01" };+ const B = { id: "B", createdAt: "2026-06-01", expirationDate: "2026-08-01" };+ const lots = [A, B];++ const ids = (sorted: Array<{ id: string }>) => sorted.map((l) => l.id);++ it("FEFO / Default: earliest expiry first", () => {+ expect(ids(sortLotsByPickMethod(lots, "FEFO"))).toEqual(["B", "A"]);+ expect(ids(sortLotsByPickMethod(lots, "Default"))).toEqual(["B", "A"]);+ });++ it("FIFO: oldest createdAt first", () => {+ expect(ids(sortLotsByPickMethod(lots, "FIFO"))).toEqual(["A", "B"]);+ });++ it("LIFO: newest createdAt first", () => {+ expect(ids(sortLotsByPickMethod(lots, "LIFO"))).toEqual(["B", "A"]);+ });++ it("FEFO: null expiry sorts last", () => {+ const noExp = { id: "C", createdAt: "2025-01-01", expirationDate: null };+ expect(ids(sortLotsByPickMethod([noExp, A, B], "FEFO"))).toEqual([+ "B",+ "A",+ "C"+ ]);+ });++ it("does not mutate the input array", () => {+ const input = [A, B];+ sortLotsByPickMethod(input, "FIFO");+ expect(input).toEqual([A, B]);+ });+});diff --git a/apps/mes/app/services/inventory.service.ts b/apps/mes/app/services/inventory.service.tsindex 8ddcdfa954..7dac14b935 100644--- a/apps/mes/app/services/inventory.service.ts+++ b/apps/mes/app/services/inventory.service.ts@@ -8,6 +8,11 @@ import { toDocumentTemplate } from "@carbon/documents/template";import type { SupabaseClient } from "@supabase/supabase-js";import { z } from "zod";import { zfd } from "zod-form-data";+import type { SuggestedAllocationLot } from "./allocation";+import { greedyFillAllocation, sortLotsByPickMethod } from "./allocation";++export type { SuggestedAllocationLot };+export { greedyFillAllocation, sortLotsByPickMethod };/*** Load a stored document template as a `DocumentTemplate | null` to pass to a@@ -166,6 +171,7 @@ export async function getAvailableTrackedEntities(excludeLineside?: boolean;excludeAllocated?: boolean;excludeLineId?: string | null;+ sortMethod?: Database["public"]["Enums"]["pickMethodSortMethod"];}) {return client.rpc("get_available_tracked_entities", {@@ -174,7 +180,8 @@ 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_sort_method: args.sortMethod ?? undefined});}@@ -276,6 +283,59 @@ export async function getPickingListRecommendations(return recommendations;}+/**+ * On-the-fly batch/lot suggestion for issuing a single tracked material when no+ * picking list has allocated it — the same allocation the picking list would make,+ * computed per material. Sources the ordered, allocation-netted, warehouse-only+ * pool from `get_available_tracked_entities` honoring the item's `pickMethod`+ * sort, then greedily fills `quantity` across lots. Returns [] for non-tracked+ * items, zero/negative quantity, or when nothing is available.+ */+export async function getSuggestedAllocationForMaterial(+ client: SupabaseClient<Database>,+ args: {+ itemId: string;+ companyId: string;+ locationId: string;+ quantity: number;+ }+): Promise<SuggestedAllocationLot[]> {+ if (args.quantity <= 0) return [];++ const sortMethod = await getPickOrder(client, {+ itemId: args.itemId,+ locationId: args.locationId,+ companyId: args.companyId+ });++ const { data, error } = await getAvailableTrackedEntities(client, {+ itemId: args.itemId,+ companyId: args.companyId,+ locationId: args.locationId,+ excludeLineside: true,+ excludeAllocated: true,+ sortMethod+ });+ if (error || !data) return [];++ // Sort in the app: the RPC's internal ORDER BY is not guaranteed through+ // PostgREST (SQL-function inlining), so ordering is authoritative here.+ const ordered = sortLotsByPickMethod(+ data.map((row) => ({+ trackedEntityId: row.trackedEntityId,+ readableId: row.readableId,+ availableQuantity: Number(row.availableQuantity ?? 0),+ expirationDate: row.expirationDate,+ createdAt: row.createdAt,+ storageUnitId: row.storageUnitId,+ storageUnitName: row.storageUnitName+ })),+ sortMethod+ );++ return greedyFillAllocation(ordered, args.quantity);+}+export type JobMaterialPickedQuantity = {quantityPicked: number;quantityToPick: number;diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 329528eceb..00870574b8 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -1,3 +1,4 @@+import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";import type { JSONContent } from "@carbon/react";import {@@ -183,11 +184,83 @@ export async function finishJobOperation();}});++ // The status='Done' write fires the sync_finish_job_operation trigger, which+ // completes the job to inventory (job.status → 'Completed') when this was the+ // last operation. At that point, return any picking-list-allocated batch/serial+ // stock that was staged to lineside but not consumed back to its warehouse+ // source — the SQL trigger can't call edge functions, so we orchestrate it here.+ await returnAllocatedRemaindersAtJobComplete(args);}return result;}+/**+ * When a job has just completed, sweep its tracked (batch/serial) picking-list+ * allocations and return the un-consumed remainder of each from the lineside+ * shelf back to the warehouse source (so it's re-allocatable, and inventory+ * reflects only what was actually consumed). No-op unless the job is 'Completed'.+ * Idempotent: `returnPickedRemainder` returns nothing once lineside on-hand is 0.+ *+ * Runs with the service-role client: reads the picking allocations (an inventory+ * table the finishing operator may not have RLS access to) and invokes the+ * privileged return — otherwise the returns would be silently skipped for+ * production-only roles.+ */+async function returnAllocatedRemaindersAtJobComplete(args: {+ jobOperationId: string;+ userId: string;+ companyId: string;+}) {+ const serviceRole = getCarbonServiceRole();++ const op = await serviceRole+ .from("jobOperation")+ .select("jobId")+ .eq("id", args.jobOperationId)+ .maybeSingle();+ const jobId = op.data?.jobId;+ if (!jobId) return;++ const job = await serviceRole+ .from("job")+ .select("status, locationId")+ .eq("id", jobId)+ .maybeSingle();+ const locationId = job.data?.locationId;+ if (job.data?.status !== "Completed" || !locationId) return;++ const { data: lines } = await serviceRole+ .from("pickingListLine")+ .select("id, pickingListId, pickingListLineTrackedEntity(trackedEntityId)")+ .eq("jobId", jobId)+ .neq("status", "Cancelled");+ if (!lines?.length) return;++ const returns = lines.flatMap((line) => {+ const allocations =+ (line.pickingListLineTrackedEntity as Array<{+ trackedEntityId: string;+ }> | null) ?? [];+ return allocations.map((allocation) =>+ serviceRole.functions.invoke("post-picking", {+ body: {+ type: "returnPickedRemainder",+ pickingListId: line.pickingListId,+ pickingListLineId: line.id,+ trackedEntityId: allocation.trackedEntityId,+ locationId,+ userId: args.userId,+ companyId: args.companyId+ }+ })+ );+ });++ await Promise.all(returns);+}+export async function getActiveJobOperationsByEmployee(client: SupabaseClient<Database>,args: {diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.tsindex 29a58b188a..2de5b8d87c 100644--- a/apps/mes/app/utils/path.ts+++ b/apps/mes/app/utils/path.ts@@ -16,7 +16,15 @@ export const path = {failureModes: `${api}/failure-modes`,qualityIssueTypes: `${api}/quality-issue-types`,serialNumbers: (itemId: string) =>- generatePath(`${api}/serial-numbers?itemId=${itemId}`)+ generatePath(`${api}/serial-numbers?itemId=${itemId}`),+ suggestedAllocation: (+ itemId: string,+ locationId: string,+ quantity: number+ ) =>+ generatePath(+ `${api}/suggested-allocation?itemId=${itemId}&locationId=${locationId}&quantity=${quantity}`+ )},file: {jobTraveler: (id: string) => `${getAppUrl()}${file}/traveler/${id}.pdf`,diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.tsindex adf209b37d..35c57070e6 100644--- a/packages/database/supabase/functions/issue/index.ts+++ b/packages/database/supabase/functions/issue/index.ts@@ -19,6 +19,7 @@ import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";import { getNextSequence } from "../shared/get-next-sequence.ts";import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";import { calculateCOGS } from "../shared/calculate-cogs.ts";+import { resolveTrackedEntityBin } from "./resolve-tracked-entity-bin.ts";type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";@@ -2210,10 +2211,7 @@ serve(async (req: Request) => {itemId: trackedEntity.sourceDocumentId,quantity: -Number(trackedEntity.quantity),locationId: job?.locationId,- storageUnitId: itemLedgers.find(- (itemLedger) =>- itemLedger.trackedEntityId === trackedEntityId- )?.storageUnitId,+ storageUnitId: resolveTrackedEntityBin(itemLedgers, trackedEntityId),trackedEntityId: trackedEntity.id!,createdBy: userId,},@@ -2225,10 +2223,7 @@ serve(async (req: Request) => {itemId: trackedEntity.sourceDocumentId,quantity: quantity,locationId: job?.locationId,- storageUnitId: itemLedgers.find(- (itemLedger) =>- itemLedger.trackedEntityId === trackedEntityId- )?.storageUnitId,+ storageUnitId: resolveTrackedEntityBin(itemLedgers, trackedEntityId),trackedEntityId: trackedEntity.id!,createdBy: userId,},@@ -2240,10 +2235,7 @@ serve(async (req: Request) => {itemId: trackedEntity.sourceDocumentId,quantity: remainingQuantity,locationId: job?.locationId,- storageUnitId: itemLedgers.find(- (itemLedger) =>- itemLedger.trackedEntityId === trackedEntityId- )?.storageUnitId,+ storageUnitId: resolveTrackedEntityBin(itemLedgers, trackedEntityId),trackedEntityId: newTrackedEntityId,createdBy: userId,}@@ -2277,9 +2269,7 @@ serve(async (req: Request) => {itemId: trackedEntity.sourceDocumentId,quantity: -quantity,locationId: job?.locationId,- storageUnitId: itemLedgers.find(- (itemLedger) => itemLedger.trackedEntityId === trackedEntityId- )?.storageUnitId,+ storageUnitId: resolveTrackedEntityBin(itemLedgers, trackedEntityId),trackedEntityId,createdBy: userId,});@@ -2568,6 +2558,9 @@ serve(async (req: Request) => {itemId: trackedEntity.sourceDocumentId,quantity: quantity,locationId: job?.locationId,+ // NOTE: unconsume path left on its original bin-selection until+ // it can be verified; the resolveTrackedEntityBin fix is scoped+ // to the consumption path (trackedEntitiesToOperation).storageUnitId: itemLedgers.find((itemLedger) => itemLedger.trackedEntityId === trackedEntityId)?.storageUnitId,diff --git a/packages/database/supabase/functions/issue/resolve-tracked-entity-bin.test.ts b/packages/database/supabase/functions/issue/resolve-tracked-entity-bin.test.tsnew file mode 100644index 0000000000..7f1e66615b--- /dev/null+++ b/packages/database/supabase/functions/issue/resolve-tracked-entity-bin.test.ts@@ -0,0 +1,42 @@+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";+import { resolveTrackedEntityBin } from "./resolve-tracked-entity-bin.ts";++const row = (+ trackedEntityId: string | null,+ storageUnitId: string | null,+ quantity: number+) => ({ trackedEntityId, storageUnitId, quantity });++Deno.test("returns the bin with the highest positive net on-hand", () => {+ // te has 3 at lineside (net), 0 at source (picked and moved).+ const ledgers = [+ row("te", "source", 5),+ row("te", "source", -5),+ row("te", "lineside", 3)+ ];+ assertEquals(resolveTrackedEntityBin(ledgers, "te"), "lineside");+});++Deno.test("ignores other entities' rows", () => {+ const ledgers = [row("other", "binX", 10), row("te", "binY", 2)];+ assertEquals(resolveTrackedEntityBin(ledgers, "te"), "binY");+});++Deno.test("nets multiple rows per bin before choosing", () => {+ const ledgers = [+ row("te", "a", 4),+ row("te", "a", -3), // a nets to 1+ row("te", "b", 2) // b nets to 2 → wins+ ];+ assertEquals(resolveTrackedEntityBin(ledgers, "te"), "b");+});++Deno.test("falls back to first bin seen when nothing nets positive", () => {+ const ledgers = [row("te", "a", 5), row("te", "a", -5)];+ assertEquals(resolveTrackedEntityBin(ledgers, "te"), "a");+});++Deno.test("returns null when the entity has no bins", () => {+ assertEquals(resolveTrackedEntityBin([row("other", "a", 1)], "te"), null);+ assertEquals(resolveTrackedEntityBin([row("te", null, 1)], "te"), null);+});diff --git a/packages/database/supabase/functions/issue/resolve-tracked-entity-bin.ts b/packages/database/supabase/functions/issue/resolve-tracked-entity-bin.tsnew file mode 100644index 0000000000..bac5be25e0--- /dev/null+++ b/packages/database/supabase/functions/issue/resolve-tracked-entity-bin.ts@@ -0,0 +1,45 @@+// The storage unit where a tracked entity currently holds stock, derived from+// its item-ledger rows by net on-hand per bin. Pure — no DB, no I/O — so it is+// unit-testable with `deno test`.+//+// A picked entity has ledger rows in BOTH its source and lineside bins;+// consumption/split entries must be booked against the bin that actually holds+// the stock (the lineside bin after a pick), NOT an arbitrary row. Selecting+// `.find(...)?.storageUnitId` off a `createdBy`-ordered list grabs a wrong bin+// and produces a per-bin-negative ledger. Returns the bin with the highest+// positive net; falls back to any bin the entity appears in when nothing nets+// positive.++export type BinLedgerRow = {+ trackedEntityId: string | null;+ storageUnitId: string | null;+ quantity: number | string | null;+};++export function resolveTrackedEntityBin(+ ledgers: BinLedgerRow[],+ trackedEntityId: string+): string | null {+ const netByBin = new Map<string, number>();+ for (const l of ledgers) {+ if (l.trackedEntityId !== trackedEntityId || !l.storageUnitId) continue;+ netByBin.set(+ l.storageUnitId,+ (netByBin.get(l.storageUnitId) ?? 0) + Number(l.quantity ?? 0)+ );+ }+ let bestBin: string | null = null;+ let bestQty = 0;+ for (const [bin, qty] of netByBin) {+ if (qty > bestQty) {+ bestQty = qty;+ bestBin = bin;+ }+ }+ if (bestBin) return bestBin;+ return (+ ledgers.find(+ (l) => l.trackedEntityId === trackedEntityId && l.storageUnitId+ )?.storageUnitId ?? null+ );+}diff --git a/packages/database/supabase/functions/post-picking/index.ts b/packages/database/supabase/functions/post-picking/index.tsindex 3e7ee98a66..5658ab292a 100644--- a/packages/database/supabase/functions/post-picking/index.ts+++ b/packages/database/supabase/functions/post-picking/index.ts@@ -73,6 +73,21 @@ const payloadValidator = z.discriminatedUnion("type", [locationId: z.string(),userId: z.string(),companyId: z.string()+ }),+ // Return the un-consumed remainder of a tracked (batch/serial) allocation from+ // the lineside shelf back to the warehouse source at job complete. Unlike+ // unpickBatch (all-or-nothing, keyed to the original picked entity), this walks+ // the picked entity's split lineage and moves whatever is still physically on+ // hand at the lineside bin — because a partial consume splits the remainder+ // into a NEW entity the picking line never references.+ z.object({+ type: z.literal("returnPickedRemainder"),+ pickingListId: z.string(),+ pickingListLineId: z.string(),+ trackedEntityId: z.string(),+ locationId: z.string(),+ userId: z.string(),+ companyId: z.string()})]);@@ -709,6 +724,151 @@ serve(async (req: Request) => {});break;}++ case "returnPickedRemainder": {+ const {+ pickingListId,+ pickingListLineId,+ trackedEntityId,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ const line = await trx+ .selectFrom("pickingListLine")+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ const lineside = line.toStorageUnitId;+ const source = line.storageUnitId;+ // No lineside stage or no source to return to → nothing to do.+ if (!lineside || !source) return;++ // Walk the picked entity's split lineage (picked entity + every split+ // descendant). A partial consume splits the un-consumed remainder into+ // a new entity, so the leftover stock at lineside sits under a+ // descendant, not the originally-picked entity.+ const lineage = new Set<string>([trackedEntityId]);+ let frontier: string[] = [trackedEntityId];+ while (frontier.length > 0) {+ const rows = await trx+ .selectFrom("trackedActivityInput as tai")+ .innerJoin(+ "trackedActivityOutput as tao",+ "tao.trackedActivityId",+ "tai.trackedActivityId"+ )+ .where("tai.trackedEntityId", "in", frontier)+ .where("tai.companyId", "=", companyId)+ .whereRef("tao.trackedEntityId", "<>", "tai.trackedEntityId")+ .select("tao.trackedEntityId as id")+ .distinct()+ .execute();+ const next: string[] = [];+ for (const r of rows) {+ if (r.id && !lineage.has(r.id)) {+ lineage.add(r.id);+ next.push(r.id);+ }+ }+ frontier = next;+ }++ // Transfer each lineage entity's remaining lineside on-hand back to+ // the warehouse source bin.+ const inserts: ItemLedgerInsert[] = [];+ let totalReturned = 0;+ for (const entityId of lineage) {+ const onHandRow = await trx+ .selectFrom("itemLedger")+ .where("trackedEntityId", "=", entityId)+ .where("storageUnitId", "=", lineside)+ .where("itemId", "=", line.itemId)+ .where("companyId", "=", companyId)+ .select((eb) => eb.fn.sum<number>("quantity").as("qty"))+ .executeTakeFirst();+ const onHand = Number(onHandRow?.qty ?? 0);+ if (onHand <= 0) continue;+ inserts.push(+ ...transferPair({+ today,+ itemId: line.itemId,+ quantity: onHand,+ locationId,+ fromStorageUnitId: lineside,+ toStorageUnitId: source,+ documentId: pickingListId,+ trackedEntityId: entityId,+ userId,+ companyId+ })+ );+ totalReturned += onHand;+ }++ if (totalReturned <= 0) return;++ await trx.insertInto("itemLedger").values(inserts).execute();++ // Decrement the recorded picked qty by what was returned so the lot is+ // re-allocatable and the picked/to-pick display reflects reality.+ const allocation = await trx+ .selectFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", pickingListLineId)+ .where("trackedEntityId", "=", trackedEntityId)+ .selectAll()+ .executeTakeFirst();+ if (allocation) {+ const nextQuantity = Math.max(+ 0,+ Number(allocation.quantity ?? 0) - totalReturned+ );+ const nextPicked = Math.max(+ 0,+ Number(allocation.quantityPicked ?? 0) - totalReturned+ );+ if (nextPicked <= 0) {+ await trx+ .deleteFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", pickingListLineId)+ .where("trackedEntityId", "=", trackedEntityId)+ .execute();+ } else {+ await trx+ .updateTable("pickingListLineTrackedEntity")+ .set({ quantity: nextQuantity, quantityPicked: nextPicked })+ .where("pickingListLineId", "=", pickingListLineId)+ .where("trackedEntityId", "=", trackedEntityId)+ .execute();+ }+ }++ const nextLinePicked = Math.max(+ 0,+ Number(line.quantityPicked ?? 0) - totalReturned+ );+ await trx+ .updateTable("pickingListLine")+ .set({+ quantityPicked: nextLinePicked,+ // Fully returned → the line is no longer picked; mirror unpick's+ // reset so status doesn't linger on 'Picked' with 0 picked qty.+ ...(nextLinePicked <= 0 ? { status: "Pending" as const } : {}),+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .execute();++ await restoreJobMaterialSource(trx, line, userId);+ });+ break;+ }}return new Response(@@ -730,6 +890,37 @@ serve(async (req: Request) => {}});+// A balanced Transfer ledger pair moving `quantity` of a tracked entity from one+// storage unit to another (a pick, unpick, or return is all the same shape).+function transferPair(args: {+ today: string;+ itemId: string;+ quantity: number;+ locationId: string;+ fromStorageUnitId: string;+ toStorageUnitId: string;+ documentId: string;+ trackedEntityId: string;+ userId: string;+ companyId: string;+}): ItemLedgerInsert[] {+ const base = {+ postingDate: args.today,+ itemId: args.itemId,+ locationId: args.locationId,+ entryType: "Transfer" as const,+ documentType: "Direct Transfer" as const,+ documentId: args.documentId,+ trackedEntityId: args.trackedEntityId,+ createdBy: args.userId,+ companyId: args.companyId+ };+ return [+ { ...base, quantity: -args.quantity, storageUnitId: args.fromStorageUnitId },+ { ...base, quantity: args.quantity, storageUnitId: args.toStorageUnitId }+ ];+}+// Point the job material at the lineside shelf so production (backflush/issue)// consumes from where the pick just moved the stock.async function pointJobMaterialAtLineside(diff --git a/packages/database/supabase/migrations/20260709125411_available-tracked-entities-sort-method.sql b/packages/database/supabase/migrations/20260709125411_available-tracked-entities-sort-method.sqlnew file mode 100644index 0000000000..83718c6a7c--- /dev/null+++ b/packages/database/supabase/migrations/20260709125411_available-tracked-entities-sort-method.sql@@ -0,0 +1,115 @@+-- ============================================================================+-- Function: get_available_tracked_entities (sort-method aware)+-- Adds p_sort_method so the single-item availability picker can honor the+-- item's configured pickMethod.sortMethod, matching what a real picking list+-- would allocate. Previously the ordering was fixed FEFO→FIFO.+--+-- p_sort_method — 'Default' | 'FEFO' | 'FIFO' | 'LIFO' (pickMethodSortMethod).+-- Default/FEFO → expirationDate ASC NULLS LAST, then createdAt ASC+-- FIFO → createdAt ASC+-- LIFO → createdAt DESC+-- Mirrors the ORDER BY in get_picking_list_tracked_available (20260617142853).+--+-- All other behavior (bin on-hand, lineside exclusion, allocation netting,+-- one row per entity at its highest-on-hand bin) is unchanged from+-- 20260614171204_available-tracked-entities.sql.+--+-- Drop the old 6-arg signature first: adding a defaulted 7th param would+-- otherwise register a distinct overload and leave the old function callable+-- (ambiguous). We want a clean single definition.+-- ============================================================================++DROP FUNCTION IF EXISTS get_available_tracked_entities(+ TEXT, TEXT, TEXT, BOOLEAN, BOOLEAN, 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'+)+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+ )+ 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;+$$;