Skip to content

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.

refactor: picking list (#916)

Brad Barbin362e97fdbf37
diff --git a/apps/erp/app/components/ItemThumbnail.tsx b/apps/erp/app/components/ItemThumbnail.tsx
index 77b74d734c..6a00cabe33 100644
--- a/apps/erp/app/components/ItemThumbnail.tsx
+++ b/apps/erp/app/components/ItemThumbnail.tsx
@@ -8,7 +8,7 @@ import { MethodItemTypeIcon } from "./Icons";
interface ItemThumbnailProps {
thumbnailPath?: string | null;
type?: MethodItemType;
- size?: "sm" | "md" | "lg";
+ size?: "sm" | "md" | "lg" | "xl";
}
const itemVariants = cva(
@@ -18,7 +18,8 @@ const itemVariants = cva(
size: {
sm: "w-8 h-8",
md: "w-10 h-10",
- lg: "w-11 h-11 bg-gradient-to-bl from-muted to-muted/40"
+ lg: "w-11 h-11 bg-gradient-to-bl from-muted to-muted/40",
+ xl: "w-16 h-16 bg-gradient-to-bl from-muted to-muted/40"
},
withPadding: {
true: "",
@@ -40,6 +41,11 @@ const itemVariants = cva(
withPadding: true,
size: "lg",
class: "p-2"
+ },
+ {
+ withPadding: true,
+ size: "xl",
+ class: "p-2.5"
}
],
defaultVariants: {
@@ -54,7 +60,8 @@ const iconVariants = cva("text-[#AAAAAA] dark:text-[#444]", {
size: {
sm: "w-4 h-4",
md: "w-5 h-5",
- lg: "w-6 h-6"
+ lg: "w-6 h-6",
+ xl: "w-11 h-11"
}
},
defaultVariants: {
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 12d3b1ef77..fd96f57e3b 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -2318,6 +2318,86 @@ export async function getPickingListAvailability(
return map;
}
+export type PickingListRecommendation = {
+ trackedEntityId: string;
+ readableId: string | null;
+};
+
+/**
+ * The recommended tracked entities (serial/batch lots) for each tracked picking
+ * line, in pick order — surfaced as at-a-glance subtext before the picker opens.
+ * One batched RPC fetches every available lot for every item on the list; we then
+ * greedily assign distinct lots to lines in pick order so the same serial is never
+ * recommended to two lines, and a batch lot is split across lines by remaining qty.
+ * Returns a map of pickingListLineId → recommended lots (empty/partial if short).
+ */
+export async function getPickingListRecommendations(
+ client: SupabaseClient<Database>,
+ pickingListId: string
+): Promise<Record<string, PickingListRecommendation[]>> {
+ const [linesResult, availableResult] = await Promise.all([
+ client
+ .from("pickingListLine")
+ .select(
+ "id, itemId, quantityToPick, quantityPicked, status, item(itemTrackingType)"
+ )
+ .eq("pickingListId", pickingListId)
+ .order("jobOperationId")
+ .order("itemId"),
+ client.rpc("get_picking_list_tracked_available", {
+ p_picking_list_id: pickingListId
+ })
+ ]);
+
+ const recommendations: Record<string, PickingListRecommendation[]> = {};
+ if (linesResult.error || availableResult.error) return recommendations;
+
+ // Ordered, mutable pool of available lots per item (the RPC already orders each
+ // item's rows by its configured pick method).
+ const poolByItem = new Map<
+ string,
+ Array<{ trackedEntityId: string; readableId: string | null; qty: number }>
+ >();
+ for (const row of availableResult.data ?? []) {
+ const list = poolByItem.get(row.itemId) ?? [];
+ list.push({
+ trackedEntityId: row.trackedEntityId,
+ readableId: row.readableId,
+ qty: Number(row.availableQuantity ?? 0)
+ });
+ poolByItem.set(row.itemId, list);
+ }
+
+ for (const line of linesResult.data ?? []) {
+ const trackingType = (line.item as { itemTrackingType?: string } | null)
+ ?.itemTrackingType;
+ if (trackingType !== "Serial" && trackingType !== "Batch") continue;
+
+ let remaining =
+ Number(line.quantityToPick ?? 0) - Number(line.quantityPicked ?? 0);
+ if (remaining <= 0) continue;
+
+ const pool = poolByItem.get(line.itemId);
+ if (!pool?.length) continue;
+
+ const picks: PickingListRecommendation[] = [];
+ while (remaining > 0 && pool.length > 0) {
+ const lot = pool[0];
+ picks.push({
+ trackedEntityId: lot.trackedEntityId,
+ readableId: lot.readableId
+ });
+ const take = Math.min(lot.qty, remaining);
+ remaining -= take;
+ lot.qty -= take;
+ if (lot.qty <= 0) pool.shift();
+ }
+ recommendations[line.id] = picks;
+ }
+
+ return recommendations;
+}
+
export async function getPickingListLine(
client: SupabaseClient<Database>,
lineId: string
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
index 77871755de..ea281845ac 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
@@ -38,8 +38,10 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
+import { formatDate } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
import { nanoid } from "nanoid";
import { useMemo, useState } from "react";
import {
@@ -88,6 +90,7 @@ const InventoryStorageUnits = ({
}: InventoryStorageUnitsProps) => {
const permissions = usePermissions();
const { t } = useLingui();
+ const { locale } = useLocale();
const adjustmentModal = useDisclosure();
const ruleViolations = useStorageRuleViolations({
action: path.to.inventoryItemAdjustment(pickMethod.itemId),
@@ -104,6 +107,20 @@ const InventoryStorageUnits = ({
const isSerial = itemTrackingType === "Serial";
const isBatch = itemTrackingType === "Batch";
+ const visibleStorageUnitQuantities = useMemo(
+ () => itemStorageUnitQuantities.filter((item) => item.quantity !== 0),
+ [itemStorageUnitQuantities]
+ );
+
+ const showExpirationColumn = useMemo(
+ () =>
+ visibleStorageUnitQuantities.some(
+ (item) =>
+ item.trackedEntityId && trackedEntityExpirations[item.trackedEntityId]
+ ),
+ [visibleStorageUnitQuantities, trackedEntityExpirations]
+ );
+
const [quantity, setQuantity] = useState(1);
const [selectedStorageUnitId, setSelectedStorageUnitId] = useState<
string | null
@@ -239,72 +256,89 @@ const InventoryStorageUnits = ({
<Th>
<Trans>Tracking ID</Trans>
</Th>
+ {showExpirationColumn && (
+ <Th>
+ <Trans>Expiration Date</Trans>
+ </Th>
+ )}
<Th className="flex flex-shrink-0 justify-end" />
</Tr>
</Thead>
<Tbody>
- {itemStorageUnitQuantities
- .filter((item) => item.quantity !== 0)
- .map((item, index) => (
- <Tr key={index}>
- <Td>
- {storageUnits.find((s) => s.value === item.storageUnitId)
- ?.label || item.storageUnitId}
- </Td>
+ {visibleStorageUnitQuantities.map((item, index) => (
+ <Tr key={index}>
+ <Td>
+ {storageUnits.find((s) => s.value === item.storageUnitId)
+ ?.label || item.storageUnitId}
+ </Td>
+ <Td>
+ <span>{item.quantity}</span>
+ </Td>
+ <Td>
+ {item.trackedEntityId && (
+ <HStack>
+ {item.readableId && <span>{item.readableId}</span>}
+ <Copy
+ icon={<LuQrCode />}
+ text={item.trackedEntityId}
+ withTextInTooltip
+ />
+ </HStack>
+ )}
+ </Td>
+ {showExpirationColumn && (
<Td>
- <span>{item.quantity}</span>
- </Td>
- <Td>
- {item.trackedEntityId && (
- <HStack>
- {item.readableId && <span>{item.readableId}</span>}
- <Copy
- icon={<LuQrCode />}
- text={item.trackedEntityId}
- withTextInTooltip
- />
- </HStack>
- )}
+ {item.trackedEntityId &&
+ trackedEntityExpirations[item.trackedEntityId] && (
+ <span>
+ {formatDate(
+ trackedEntityExpirations[item.trackedEntityId],
+ undefined,
+ locale
+ )}
+ </span>
+ )}
</Td>
- <Td className="flex flex-shrink-0 justify-end items-center">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label={t`Actions`}
- variant="ghost"
- icon={<LuEllipsisVertical />}
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent className="w-56">
+ )}
+ <Td className="flex flex-shrink-0 justify-end items-center">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label={t`Actions`}
+ variant="ghost"
+ icon={<LuEllipsisVertical />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="w-56">
+ <DropdownMenuItem
+ onClick={() =>
+ openAdjustmentModal(
+ item.storageUnitId,
+ item.trackedEntityId,
+ item.readableId,
+ item.quantity
+ )
+ }
+ >
+ <DropdownMenuIcon icon={<LuPencil />} />
+ <Trans>Update Quantity</Trans>
+ </DropdownMenuItem>
+ {item.trackedEntityId && (
<DropdownMenuItem
onClick={() =>
- openAdjustmentModal(
- item.storageUnitId,
- item.trackedEntityId,
- item.readableId,
- item.quantity
- )
+ handlePrintLabel(item.trackedEntityId!)
}
>
- <DropdownMenuIcon icon={<LuPencil />} />
- <Trans>Update Quantity</Trans>
+ <DropdownMenuIcon icon={<LuPrinter />} />
+ <Trans>Print Label</Trans>
</DropdownMenuItem>
- {item.trackedEntityId && (
- <DropdownMenuItem
- onClick={() =>
- handlePrintLabel(item.trackedEntityId!)
- }
- >
- <DropdownMenuIcon icon={<LuPrinter />} />
- <Trans>Print Label</Trans>
- </DropdownMenuItem>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- </Td>
- </Tr>
- ))}
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </Td>
+ </Tr>
+ ))}
</Tbody>
</Table>
</CardContent>
diff --git a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListHeader.tsx b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListHeader.tsx
index c300157f39..9adfd8c3dd 100644
--- a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListHeader.tsx
@@ -152,7 +152,7 @@ const PickingListHeader = () => {
<Button
type="button"
leftIcon={<LuCircleCheck />}
- variant={status === "In Progress" ? "primary" : "secondary"}
+ variant="secondary"
isDisabled={
status !== "In Progress" ||
statusFetcher.state !== "idle" ||
@@ -164,7 +164,7 @@ const PickingListHeader = () => {
}
onClick={() => submitStatus("Completed")}
>
- <Trans>Complete</Trans>
+ <Trans>Finish</Trans>
</Button>
<Button
type="button"
diff --git a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx
index 6e4408f1f2..a7942264d7 100644
--- a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx
@@ -20,6 +20,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
HStack,
+ Skeleton,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -28,7 +29,7 @@ import {
VStack
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
-import { useEffect, useMemo, useState } from "react";
+import { Suspense, useEffect, useMemo, useState } from "react";
import {
LuChevronDown,
LuCirclePlus,
@@ -36,7 +37,7 @@ import {
LuTriangleAlert,
LuUndo2
} from "react-icons/lu";
-import { useFetcher } from "react-router";
+import { Await, useFetcher } from "react-router";
import { Empty, ItemThumbnail } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { usePermissions } from "~/hooks";
@@ -45,7 +46,8 @@ import { path } from "~/utils/path";
import { isPickingListLocked } from "../../inventory.models";
import type {
getPickingList,
- getPickingListLines
+ getPickingListLines,
+ PickingListRecommendation
} from "../../inventory.service";
import { ShortPickModal } from "./ShortPickModal";
@@ -57,10 +59,15 @@ type PickingListLineData = NonNullable<
Awaited<ReturnType<typeof getPickingListLines>>["data"]
>;
+type RecommendationsPromise = Promise<
+ Record<string, PickingListRecommendation[]>
+>;
+
type PickingListLinesProps = {
pickingListLines: PickingListLineData;
pickingListId: string;
pickingList: PickingListData;
+ recommendations: RecommendationsPromise;
};
// A "kit" is the box a kitter fills for one job operation. Parts must not be
@@ -77,7 +84,8 @@ type Kit = {
const PickingListLines = ({
pickingListLines,
pickingListId,
- pickingList
+ pickingList,
+ recommendations
}: PickingListLinesProps) => {
const isLocked = isPickingListLocked(pickingList?.status);
const kits = useMemo(() => {
@@ -127,6 +135,7 @@ const PickingListLines = ({
kit={kit}
pickingListId={pickingListId}
isLocked={isLocked}
+ recommendations={recommendations}
/>
))}
</VStack>
@@ -136,11 +145,13 @@ const PickingListLines = ({
function PickingKitCard({
kit,
pickingListId,
- isLocked
+ isLocked,
+ recommendations
}: {
kit: Kit;
pickingListId: string;
isLocked: boolean;
+ recommendations: RecommendationsPromise;
}) {
const totalToPick = kit.lines.reduce(
(sum, l) => sum + Number(l.quantityToPick ?? 0),
@@ -177,6 +188,7 @@ function PickingKitCard({
pickingListId={pickingListId}
isLast={index === kit.lines.length - 1}
isLocked={isLocked}
+ recommendations={recommendations}
/>
))}
</div>
@@ -189,12 +201,14 @@ function PickingListLineItem({
line,
pickingListId,
isLast,
- isLocked
+ isLocked,
+ recommendations
}: {
line: PickingListLineData[number];
pickingListId: string;
isLast: boolean;
isLocked: boolean;
+ recommendations: RecommendationsPromise;
}) {
const permissions = usePermissions();
const { t } = useLingui();
@@ -304,15 +318,20 @@ function PickingListLineItem({
)}
>
<ItemThumbnail
- size="md"
+ size="xl"
thumbnailPath={null}
type={(item?.type as "Part") ?? "Part"}
/>
<VStack spacing={0} className="min-w-0">
- <p className="text-sm font-medium truncate">{itemName}</p>
- <p className="text-xs text-muted-foreground truncate">
+ <p className="truncate text-base font-medium sm:text-sm">
+ {itemName}
+ </p>
+ <p className="truncate font-mono text-sm text-muted-foreground sm:text-xs">
{item?.readableIdWithRevision ?? line.item?.readableId}
</p>
+ {isTracked && !isPicked && (
+ <RecommendedLots resolve={recommendations} lineId={line.id} />
+ )}
</VStack>
</HStack>
@@ -476,4 +495,42 @@ function PickingListLineItem({
);
}
+/**
+ * At-a-glance recommended serial/batch numbers for a tracked line, streamed in
+ * from the deferred list-wide recommendations so the row paints immediately.
+ * Rendered as readable monospace chips, no label — the chips speak for themselves.
+ */
+function RecommendedLots({
+ resolve,
+ lineId
+}: {
+ resolve: RecommendationsPromise;
+ lineId: string;
+}) {
+ return (
+ <Suspense
+ fallback={<Skeleton className="mt-2 h-6 w-36 rounded-md sm:h-5" />}
+ >
+ <Await resolve={resolve} errorElement={null}>
+ {(byLine) => {
+ const lots = byLine?.[lineId] ?? [];
+ if (lots.length === 0) return null;
+ return (
+ <div className="mt-2 flex min-w-0 flex-wrap items-center gap-1.5 text-base sm:text-sm">
+ {lots.map((lot) => (
+ <span
+ key={lot.trackedEntityId}
+ className="max-w-full truncate rounded-md border border-border bg-muted px-2 py-0.5 font-mono tabular-nums text-foreground"
+ >
+ {lot.readableId ?? lot.trackedEntityId}
+ </span>
+ ))}
+ </div>
+ );
+ }}
+ </Await>
+ </Suspense>
+ );
+}
+
export default PickingListLines;
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
index 6b55be2bc8..fa88765b96 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -663,6 +663,8 @@ function MaterialForm({
quantity: number;
kit: boolean;
storageUnitIds: Record<string, string>;
+ requiresBatchTracking: boolean;
+ requiresSerialTracking: boolean;
itemReplenishmentSystem: string;
}>({
itemId: item.data.itemId ?? "",
@@ -674,6 +676,8 @@ function MaterialForm({
quantity: item.data.quantity ?? 1,
kit: item.data.kit ?? false,
storageUnitIds: item.data.storageUnitIds ?? {},
+ requiresBatchTracking: item.data.item?.itemTrackingType === "Batch",
+ requiresSerialTracking: item.data.item?.itemTrackingType === "Serial",
itemReplenishmentSystem:
item.data.item?.replenishmentSystem ?? replenishmentSystem ?? "Buy"
});
@@ -692,6 +696,8 @@ function MaterialForm({
kit: false,
storageUnitIds: {},
methodOperationId: undefined,
+ requiresBatchTracking: false,
+ requiresSerialTracking: false,
itemReplenishmentSystem: replenishmentSystem ?? "Buy"
});
};
@@ -706,7 +712,7 @@ function MaterialForm({
const item = await carbon
.from("item")
.select(
- "name, readableIdWithRevision, type, unitOfMeasureCode, defaultMethodType, sourcingType, replenishmentSystem"
+ "name, readableIdWithRevision, type, unitOfMeasureCode, defaultMethodType, sourcingType, replenishmentSystem, itemTrackingType"
)
.eq("id", itemId)
.eq("companyId", company.id)
@@ -727,6 +733,8 @@ function MaterialForm({
methodType: item.data?.defaultMethodType ?? "Pull from Inventory",
sourcingType: item.data?.sourcingType ?? "Specified",
kit: false,
+ requiresBatchTracking: item.data?.itemTrackingType === "Batch",
+ requiresSerialTracking: item.data?.itemTrackingType === "Serial",
itemReplenishmentSystem: item.data?.replenishmentSystem ?? "Buy"
}));
if (item.data?.type) {
@@ -736,6 +744,9 @@ function MaterialForm({
const key = (field: string) => getFieldKey(field, item.id);
+ const isTracked =
+ itemData.requiresBatchTracking || itemData.requiresSerialTracking;
+
return (
<ValidatedForm
action={
@@ -1026,7 +1037,7 @@ function MaterialForm({
>
<HStack>
<LuGitPullRequestCreateArrow />
- <Label>Backflush</Label>
+ <Label>{isTracked ? t`Operation` : t`Backflush`}</Label>
</HStack>
<HStack>
<Badge
@@ -1045,8 +1056,8 @@ function MaterialForm({
icon={<LuChevronRight />}
aria-label={
backflushDisclosure.isOpen
- ? "Collapse Backflush"
- : "Expand Backflush"
+ ? "Collapse Operation"
+ : "Expand Operation"
}
variant="ghost"
size="md"
diff --git a/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx b/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx
index af1467738c..b2f7773c69 100644
--- a/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/PickMethodForm.tsx
@@ -197,7 +197,6 @@ const PickMethodForm = ({
<Select
name="sortMethod"
label={t`Pick Order`}
- helperText={t`Default order when picking serial or batch lots of this item. Pickers can still override it.`}
options={pickOrderOptions}
/>
)}
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 83e895a224..8961470758 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -699,7 +699,7 @@ export const jobMaterialValidator = baseMaterialValidator
export const jobMaterialValidatorForReleasedJob = baseMaterialValidator
.extend({
- jobOperationId: zfd.text(z.string().optional())
+ jobOperationId: z.string().min(1, { message: "Operation is required" })
})
.refine(
(data) => {
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
index e11ee7ab4c..9542c311f0 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -800,6 +800,9 @@ function MaterialForm({
const locationId = routeData?.job?.locationId ?? undefined;
const storageUnits = useStorageUnits(locationId);
+ const isTracked =
+ itemData.requiresBatchTracking || itemData.requiresSerialTracking;
+
return (
<ValidatedForm
action={
@@ -982,73 +985,68 @@ function MaterialForm({
</div>
</div>
- {(itemData.requiresBatchTracking || itemData.requiresSerialTracking) && (
- <Hidden name="jobOperationId" value={itemData.jobOperationId} />
- )}
- {!itemData.requiresBatchTracking && !itemData.requiresSerialTracking && (
- <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4 w-full">
- <HStack
- className="w-full justify-between cursor-pointer"
- onClick={backflushDisclosure.onToggle}
- >
- <HStack>
- <LuGitPullRequestCreateArrow />
- <Label>
- <Trans>Backflush</Trans>
- </Label>
- </HStack>
- <HStack>
- <Badge
- variant={jobOperations.length > 0 ? "secondary" : "destructive"}
- >
- <LuCog className="size-3 mr-1" />
- {itemData.jobOperationId
- ? jobOperations.find((o) => o.id === itemData.jobOperationId)
- ?.description || t`Selected Operation`
- : t`First Operation`}
- </Badge>
- <IconButton
- icon={<LuChevronRight />}
- aria-label={
- backflushDisclosure.isOpen
- ? "Collapse Backflush"
- : "Expand Backflush"
- }
- variant="ghost"
- size="md"
- onClick={(e) => {
- e.stopPropagation();
- backflushDisclosure.onToggle();
- }}
- className={`transition-transform ${
- backflushDisclosure.isOpen ? "rotate-90" : ""
- }`}
- />
- </HStack>
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4 w-full">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={backflushDisclosure.onToggle}
+ >
+ <HStack>
+ <LuGitPullRequestCreateArrow />
+ <Label>
+ {isTracked ? <Trans>Operation</Trans> : <Trans>Backflush</Trans>}
+ </Label>
</HStack>
- <div
- className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
- backflushDisclosure.isOpen ? "" : "hidden"
- }`}
- >
- <Select
- name="jobOperationId"
- label={t`Operation`}
- isClearable
- options={jobOperations.map((o) => ({
- value: o.id!,
- label: o.description
- }))}
- onChange={(newValue) => {
- setItemData((d) => ({
- ...d,
- jobOperationId: newValue?.value as string
- }));
+ <HStack>
+ <Badge
+ variant={jobOperations.length > 0 ? "secondary" : "destructive"}
+ >
+ <LuCog className="size-3 mr-1" />
+ {itemData.jobOperationId
+ ? jobOperations.find((o) => o.id === itemData.jobOperationId)
+ ?.description || t`Selected Operation`
+ : t`First Operation`}
+ </Badge>
+ <IconButton
+ icon={<LuChevronRight />}
+ aria-label={
+ backflushDisclosure.isOpen
+ ? "Collapse Operation"
+ : "Expand Operation"
+ }
+ variant="ghost"
+ size="md"
+ onClick={(e) => {
+ e.stopPropagation();
+ backflushDisclosure.onToggle();
}}
+ className={`transition-transform ${
+ backflushDisclosure.isOpen ? "rotate-90" : ""
+ }`}
/>
- </div>
+ </HStack>
+ </HStack>
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
+ backflushDisclosure.isOpen ? "" : "hidden"
+ }`}
+ >
+ <Select
+ name="jobOperationId"
+ label={t`Operation`}
+ isClearable
+ options={jobOperations.map((o) => ({
+ value: o.id!,
+ label: o.description
+ }))}
+ onChange={(newValue) => {
+ setItemData((d) => ({
+ ...d,
+ jobOperationId: newValue?.value as string
+ }));
+ }}
+ />
</div>
- )}
+ </div>
<motion.div
className="flex flex-1 items-center justify-end w-full pt-2"
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index ad34ebd4fe..b0c15d4b56 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -695,6 +695,8 @@ function MaterialForm({
kit: boolean;
storageUnitId?: string;
quoteOperationId?: string;
+ requiresBatchTracking: boolean;
+ requiresSerialTracking: boolean;
itemReplenishmentSystem: string;
}>({
itemId: item.data.itemId ?? "",
@@ -706,6 +708,8 @@ function MaterialForm({
kit: item.data.kit ?? false,
storageUnitId: item.data.storageUnitId,
quoteOperationId: item.data.quoteOperationId,
+ requiresBatchTracking: item.data.item?.itemTrackingType === "Batch",
+ requiresSerialTracking: item.data.item?.itemTrackingType === "Serial",
itemReplenishmentSystem: item.data.item?.replenishmentSystem ?? "Buy"
});
@@ -720,6 +724,8 @@ function MaterialForm({
description: "",
unitOfMeasureCode: "EA",
kit: false,
+ requiresBatchTracking: false,
+ requiresSerialTracking: false,
itemReplenishmentSystem: "Buy"
});
};
@@ -815,6 +821,9 @@ function MaterialForm({
const locationId = routeData?.quote?.locationId ?? undefined;
const storageUnits = useStorageUnits(locationId);
+ const isTracked =
+ itemData.requiresBatchTracking || itemData.requiresSerialTracking;
+
return (
<ValidatedForm
action={
@@ -989,7 +998,7 @@ function MaterialForm({
<HStack>
<LuGitPullRequestCreateArrow />
<Label>
- <Trans>Backflush</Trans>
+ {isTracked ? <Trans>Operation</Trans> : <Trans>Backflush</Trans>}
</Label>
</HStack>
<HStack>
@@ -1007,8 +1016,8 @@ function MaterialForm({
icon={<LuChevronRight />}
aria-label={
backflushDisclosure.isOpen
- ? "Collapse Backflush"
- : "Expand Backflush"
+ ? "Collapse Operation"
+ : "Expand Operation"
}
variant="ghost"
size="md"
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index cf28ef8d78..51fbaa6f34 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,6 +1,6 @@
{
- "generated": "2026-06-16T19:30:33.494Z",
- "totalTools": 1207,
+ "generated": "2026-06-20T00:13:41.606Z",
+ "totalTools": 1208,
"modules": 15,
"tools": [
{
@@ -6205,6 +6205,31 @@
]
}
},
+ {
+ "name": "inventory_getPickingListRecommendations",
+ "module": "inventory",
+ "classification": "READ",
+ "description": "get picking list recommendations",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "pickingListId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "pickingListId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "pickingListId"
+ ]
+ }
+ },
{
"name": "inventory_getPickingListLine",
"module": "inventory",
diff --git a/apps/erp/app/routes/x+/picking-list+/$pickingListId.details.tsx b/apps/erp/app/routes/x+/picking-list+/$pickingListId.details.tsx
index 88c7c6d95a..471b4646ff 100644
--- a/apps/erp/app/routes/x+/picking-list+/$pickingListId.details.tsx
+++ b/apps/erp/app/routes/x+/picking-list+/$pickingListId.details.tsx
@@ -1,7 +1,11 @@
import type { JSONContent } from "@carbon/react";
import { useParams } from "react-router";
import { useRouteData } from "~/hooks";
-import type { getPickingList, getPickingListLines } from "~/modules/inventory";
+import type {
+ getPickingList,
+ getPickingListLines,
+ PickingListRecommendation
+} from "~/modules/inventory";
import {
PickingListLines,
PickingListNotes
@@ -23,6 +27,7 @@ export default function PickingListDetailsRoute() {
const routeData = useRouteData<{
pickingList: PickingListData;
pickingListLines: PickingListLineData;
+ recommendations: Promise<Record<string, PickingListRecommendation[]>>;
}>(path.to.pickingList(pickingListId));
if (!routeData?.pickingList)
@@ -34,6 +39,7 @@ export default function PickingListDetailsRoute() {
pickingListLines={routeData.pickingListLines}
pickingListId={pickingListId}
pickingList={routeData.pickingList}
+ recommendations={routeData.recommendations}
/>
<PickingListNotes
id={pickingListId}
diff --git a/apps/erp/app/routes/x+/picking-list+/$pickingListId.tsx b/apps/erp/app/routes/x+/picking-list+/$pickingListId.tsx
index 1684f3dc3e..02b289f972 100644
--- a/apps/erp/app/routes/x+/picking-list+/$pickingListId.tsx
+++ b/apps/erp/app/routes/x+/picking-list+/$pickingListId.tsx
@@ -7,7 +7,8 @@ import { Outlet, redirect, useParams } from "react-router";
import {
getPickingList,
getPickingListAvailability,
- getPickingListLines
+ getPickingListLines,
+ getPickingListRecommendations
} from "~/modules/inventory";
import { PickingListHeader } from "~/modules/inventory/ui/PickingLists";
import type { Handle } from "~/utils/handle";
@@ -57,7 +58,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
pickingListLines: (pickingListLines.data ?? []).map((line) => ({
...line,
availableQuantity: availability.get(line.id) ?? 0
- }))
+ })),
+ // Deferred (not awaited): recommended serial/batch lots per line, streamed in
+ // after the list paints so the at-a-glance subtext never blocks first render.
+ recommendations: getPickingListRecommendations(client, pickingListId)
};
}
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index eb999ed99a..2a577854e3 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -77,6 +77,7 @@ import {
LuGitPullRequest,
LuHammer,
LuHardHat,
+ LuPackageCheck,
LuQrCode,
LuSquareUser,
LuTimer,
@@ -177,6 +178,34 @@ type JobOperationProps = {
>;
};
+/**
+ * Additive overlay badge showing how much of a material has been picked (staged at
+ * lineside). Picking is optional, so this renders nothing unless something has actually
+ * been picked — orange while partial, green once the full requirement is staged.
+ */
+function PickedBadge({
+ quantityPicked,
+ quantityToPick
+}: {
+ quantityPicked?: number | null;
+ quantityToPick?: number | null;
+}) {
+ const picked = Number(quantityPicked ?? 0);
+ if (picked <= 0) return null;
+ const toPick = Number(quantityToPick ?? 0);
+ const isFullyPicked = toPick > 0 && picked >= toPick;
+ return (
+ <Badge
+ variant={isFullyPicked ? "green" : "orange"}
+ className="gap-1 shrink-0"
+ title="Quantity picked to lineside"
+ >
+ <LuPackageCheck className="size-3" />
+ {isFullyPicked ? <Trans>Picked</Trans> : `${picked}/${toPick}`}
+ </Badge>
+ );
+}
+
export const JobOperation = ({
events,
expiredEntityPolicy = "Block",
@@ -1084,6 +1113,26 @@ export const JobOperation = ({
<Trans>Consumed expired</Trans>
</Badge>
)}
+ <PickedBadge
+ quantityPicked={
+ (
+ material as {
+ quantityPicked?:
+ | number
+ | null;
+ }
+ ).quantityPicked
+ }
+ quantityToPick={
+ (
+ material as {
+ quantityToPick?:
+ | number
+ | null;
+ }
+ ).quantityToPick
+ }
+ />
</HStack>
</Td>
<Td className="hidden lg:table-cell">
@@ -1248,6 +1297,26 @@ export const JobOperation = ({
/>
</Badge>
) : null}
+ <PickedBadge
+ quantityPicked={
+ (
+ kittedChild as {
+ quantityPicked?:
+ | number
+ | null;
+ }
+ ).quantityPicked
+ }
+ quantityToPick={
+ (
+ kittedChild as {
+ quantityToPick?:
+ | number
+ | null;
+ }
+ ).quantityToPick
+ }
+ />
</HStack>
</Td>
<Td className="lg:table-cell hidden">
diff --git a/apps/mes/app/routes/x+/picking.$pickingListId.tsx b/apps/mes/app/routes/x+/picking.$pickingListId.tsx
index 4116e5ba50..21f1c9c9ca 100644
--- a/apps/mes/app/routes/x+/picking.$pickingListId.tsx
+++ b/apps/mes/app/routes/x+/picking.$pickingListId.tsx
@@ -23,6 +23,7 @@ import {
Heading,
HStack,
SidebarTrigger,
+ Skeleton,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -31,7 +32,7 @@ import {
VStack
} from "@carbon/react";
import { Trans } from "@lingui/react/macro";
-import { useEffect, useMemo, useState } from "react";
+import { Suspense, useEffect, useMemo, useState } from "react";
import {
LuCheck,
LuChevronDown,
@@ -42,11 +43,13 @@ import {
LuUndo2
} from "react-icons/lu";
import type { LoaderFunctionArgs } from "react-router";
-import { useFetcher, useLoaderData } from "react-router";
+import { Await, useFetcher, useLoaderData } from "react-router";
import { Enumerable } from "~/components/Enumerable";
import ItemThumbnail from "~/components/ItemThumbnail";
import { PickingListStatus } from "~/components/PickingListStatus";
import { ShortPickModal } from "~/components/ShortPickModal";
+import type { PickingListRecommendation } from "~/services/inventory.service";
+import { getPickingListRecommendations } from "~/services/inventory.service";
import { isPickingListLocked } from "~/services/models";
import { getPickingListForExecution } from "~/services/picking.service";
import { useItems } from "~/stores";
@@ -63,7 +66,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
return {
- pickingList: result.data
+ pickingList: result.data,
+ // Deferred (not awaited): recommended serial/batch lots per line, streamed in
+ // after the list paints so the at-a-glance subtext never blocks first render.
+ recommendations: getPickingListRecommendations(client, pickingListId)
};
}
@@ -82,8 +88,12 @@ interface Kit {
lines: Line[];
}
+type RecommendationsPromise = Promise<
+ Record<string, PickingListRecommendation[]>
+>;
+
export default function PickingExecutionRoute() {
- const { pickingList } = useLoaderData<typeof loader>();
+ const { pickingList, recommendations } = useLoaderData<typeof loader>();
const lines = pickingList.lines ?? [];
const isLocked = isPickingListLocked(pickingList.status);
@@ -144,6 +154,7 @@ export default function PickingExecutionRoute() {
kit={kit}
pickingListId={pickingList.id}
isLocked={isLocked}
+ recommendations={recommendations}
/>
))}
</VStack>
@@ -184,7 +195,7 @@ function PickingListControls({
<HStack spacing={2}>
{status === "Draft" && (
<Button
- size="lg"
+ size="md"
leftIcon={<LuPlay />}
isLoading={isSubmitting}
isDisabled={isSubmitting}
@@ -196,12 +207,13 @@ function PickingListControls({
{status === "In Progress" && (
<Button
size="md"
+ variant="secondary"
leftIcon={<LuCheck />}
isLoading={isSubmitting}
isDisabled={isSubmitting}
onClick={() => setStatus("Completed")}
>
- <Trans>Complete</Trans>
+ <Trans>Finish</Trans>
</Button>
)}
</HStack>
@@ -219,11 +231,13 @@ function isLineResolved(line: Line) {
function PickingKitCard({
kit,
pickingListId,
- isLocked
+ isLocked,
+ recommendations
}: {
kit: Kit;
pickingListId: string;
isLocked: boolean;
+ recommendations: RecommendationsPromise;
}) {
const totalToPick = kit.lines.reduce(
(sum, l) => sum + Number(l.quantityToPick ?? 0),
@@ -260,6 +274,7 @@ function PickingKitCard({
pickingListId={pickingListId}
isLast={index === kit.lines.length - 1}
isLocked={isLocked}
+ recommendations={recommendations}
/>
))}
</div>
@@ -272,12 +287,14 @@ function PickLineItem({
line,
pickingListId,
isLast,
- isLocked
+ isLocked,
+ recommendations
}: {
line: Line;
pickingListId: string;
isLast: boolean;
isLocked: boolean;
+ recommendations: RecommendationsPromise;
}) {
const [items] = useItems();
const fetcher = useFetcher<{ success: boolean; message?: string }>();
@@ -365,34 +382,65 @@ function PickLineItem({
});
};
+ const quantityBadge = isTracked ? (
+ <Badge
+ className={cn(
+ "text-white text-base tabular-nums",
+ isFullyPicked
+ ? "bg-emerald-600"
+ : quantityPicked > 0
+ ? "bg-orange-500"
+ : "bg-red-600"
+ )}
+ >
+ {quantityPicked}/{quantityToPick}
+ </Badge>
+ ) : (
+ <Count
+ count={isShort ? quantityPicked : quantityToPick}
+ className={cn(
+ "text-white text-base tabular-nums",
+ isFullyPicked
+ ? "bg-emerald-600"
+ : isShort
+ ? "bg-orange-500"
+ : "bg-red-600"
+ )}
+ />
+ );
+
return (
<div
className={cn(
- "group flex items-center justify-between gap-6 p-4 border-b",
- isLast && "border-none"
+ "flex flex-col gap-4 p-4 border-b transition-opacity duration-150",
+ "sm:flex-row sm:items-center sm:justify-between sm:gap-6",
+ isLast && "border-none",
+ isResolved && "opacity-60 hover:opacity-100"
)}
>
- <HStack
- spacing={4}
- className={cn(
- "min-w-0 flex-1 transition-opacity duration-150",
- isResolved && "opacity-50 group-hover:opacity-100"
- )}
- >
- <ItemThumbnail
- size="lg"
- thumbnailPath={null}
- type={(item?.type as "Part") ?? "Part"}
- />
- <VStack spacing={0} className="min-w-0">
- <p className="text-sm font-medium truncate">{itemName}</p>
- <p className="text-xs text-muted-foreground truncate">
- {item?.readableIdWithRevision ?? lineItem?.readableId}
- </p>
- </VStack>
- </HStack>
-
- <HStack spacing={6} className="shrink-0">
+ {/* Identity — item, part number, suggested lots, and (mobile) the count */}
+ <div className="flex items-start justify-between gap-4 min-w-0 sm:flex-1">
+ <HStack spacing={4} className="min-w-0">
+ <ItemThumbnail
+ size="xl"
+ thumbnailPath={null}
+ type={(item?.type as "Part") ?? "Part"}
+ />
+ <VStack spacing={1} className="min-w-0">
+ <p className="truncate text-base font-medium">{itemName}</p>
+ <p className="truncate font-mono text-sm text-muted-foreground">
+ {item?.readableIdWithRevision ?? lineItem?.readableId}
+ </p>
+ {isTracked && !isFullyPicked && (
+ <RecommendedLots resolve={recommendations} lineId={line.id} />
+ )}
+ </VStack>
+ </HStack>
+ <div className="shrink-0 sm:hidden">{quantityBadge}</div>
+ </div>
+
+ {/* Controls — source, count (desktop), and pick actions */}
+ <div className="flex items-center justify-end gap-3 sm:gap-6 sm:shrink-0">
{source ? (
<div className="text-base font-medium whitespace-nowrap">
{source}
@@ -417,22 +465,7 @@ function PickLineItem({
</TooltipContent>
</Tooltip>
) : null}
- {isTracked ? (
- <Badge
- variant={
- isFullyPicked ? "green" : quantityPicked > 0 ? "orange" : "red"
- }
- className="text-base tabular-nums"
- >
- {quantityPicked}/{quantityToPick}
- </Badge>
- ) : (
- <Count
- count={isShort ? quantityPicked : quantityToPick}
- variant={isFullyPicked ? "green" : isShort ? "orange" : "red"}
- className="text-base tabular-nums"
- />
- )}
+ <div className="hidden sm:block">{quantityBadge}</div>
{isLocked ? (
isCancelled ? (
<Badge variant="red">
@@ -444,7 +477,7 @@ function PickLineItem({
<Trans>Cancelled</Trans>
</Badge>
) : isTracked ? (
- <HStack spacing={1}>
+ <HStack spacing={1} className="flex-1 justify-end sm:flex-none">
{pickedLots.length === 1 ? (
<Button
size="lg"
@@ -452,6 +485,7 @@ function PickLineItem({
leftIcon={<LuUndo2 />}
onClick={() => unpickTracked(pickedLots[0].trackedEntityId)}
isDisabled={isSubmitting}
+ className="flex-1 sm:flex-none"
>
{pickedLots[0].trackedEntity?.readableId ? (
<Trans>Unpick {pickedLots[0].trackedEntity.readableId}</Trans>
@@ -468,6 +502,7 @@ function PickLineItem({
leftIcon={<LuUndo2 />}
rightIcon={<LuChevronDown />}
isDisabled={isSubmitting}
+ className="flex-1 sm:flex-none"
>
<Trans>Unpick</Trans>
</Button>
@@ -492,6 +527,7 @@ function PickLineItem({
leftIcon={<LuQrCode />}
onClick={openPicker}
isDisabled={isSubmitting}
+ className="flex-1 sm:flex-none"
>
<Trans>Scan</Trans>
</Button>
@@ -505,16 +541,18 @@ function PickLineItem({
onClick={() => pick(0)}
isLoading={isSubmitting}
isDisabled={isSubmitting}
+ className="flex-1 sm:flex-none"
>
<Trans>Unpick</Trans>
</Button>
) : (
- <HStack spacing={1}>
+ <HStack spacing={1} className="flex-1 justify-end sm:flex-none">
<Button
size="lg"
variant="secondary"
onClick={() => setShortOpen(true)}
isDisabled={isSubmitting}
+ className="flex-1 sm:flex-none"
>
<Trans>Short</Trans>
</Button>
@@ -524,12 +562,13 @@ function PickLineItem({
onClick={() => pick(quantityToPick)}
isLoading={isSubmitting}
isDisabled={isSubmitting}
+ className="flex-1 sm:flex-none"
>
<Trans>Pick</Trans>
</Button>
</HStack>
)}
- </HStack>
+ </div>
{shortOpen && (
<ShortPickModal
@@ -566,3 +605,40 @@ function PickLineItem({
</div>
);
}
+
+/**
+ * At-a-glance recommended serial/batch numbers for a tracked line, streamed in
+ * from the deferred list-wide recommendations so the row paints immediately.
+ * Rendered as large, touch-readable monospace chips, no label — the chips
+ * speak for themselves.
+ */
+function RecommendedLots({
+ resolve,
+ lineId
+}: {
+ resolve: RecommendationsPromise;
+ lineId: string;
+}) {
+ return (
+ <Suspense fallback={<Skeleton className="mt-2 h-8 w-44 rounded-md" />}>
+ <Await resolve={resolve} errorElement={null}>
+ {(byLine) => {
+ const lots = byLine?.[lineId] ?? [];
+ if (lots.length === 0) return null;
+ return (
+ <div className="mt-2 flex min-w-0 flex-wrap items-center gap-2 text-base">
+ {lots.map((lot) => (
+ <span
+ key={lot.trackedEntityId}
+ className="max-w-full truncate rounded-md border border-border bg-background px-3 py-1 font-mono tabular-nums text-foreground shadow-sm"
+ >
+ {lot.readableId ?? lot.trackedEntityId}
+ </span>
+ ))}
+ </div>
+ );
+ }}
+ </Await>
+ </Suspense>
+ );
+}
diff --git a/apps/mes/app/services/inventory.service.ts b/apps/mes/app/services/inventory.service.ts
index eecaaa8a90..8ddcdfa954 100644
--- a/apps/mes/app/services/inventory.service.ts
+++ b/apps/mes/app/services/inventory.service.ts
@@ -196,6 +196,131 @@ export async function getPickOrder(
return data?.sortMethod ?? "Default";
}
+export type PickingListRecommendation = {
+ trackedEntityId: string;
+ readableId: string | null;
+};
+
+/**
+ * The recommended tracked entities (serial/batch lots) for each tracked picking
+ * line, in pick order — surfaced as at-a-glance subtext before the picker opens.
+ * One batched RPC fetches every available lot for every item on the list; we then
+ * greedily assign distinct lots to lines in pick order so the same serial is never
+ * recommended to two lines, and a batch lot is split across lines by remaining qty.
+ * Returns a map of pickingListLineId → recommended lots (empty/partial if short).
+ */
+export async function getPickingListRecommendations(
+ client: SupabaseClient<Database>,
+ pickingListId: string
+): Promise<Record<string, PickingListRecommendation[]>> {
+ const [linesResult, availableResult] = await Promise.all([
+ client
+ .from("pickingListLine")
+ .select(
+ "id, itemId, quantityToPick, quantityPicked, status, item(itemTrackingType)"
+ )
+ .eq("pickingListId", pickingListId)
+ .order("jobOperationId")
+ .order("itemId"),
+ client.rpc("get_picking_list_tracked_available", {
+ p_picking_list_id: pickingListId
+ })
+ ]);
+
+ const recommendations: Record<string, PickingListRecommendation[]> = {};
+ if (linesResult.error || availableResult.error) return recommendations;
+
+ // Ordered, mutable pool of available lots per item (the RPC already orders each
+ // item's rows by its configured pick method).
+ const poolByItem = new Map<
+ string,
+ Array<{ trackedEntityId: string; readableId: string | null; qty: number }>
+ >();
+ for (const row of availableResult.data ?? []) {
+ const list = poolByItem.get(row.itemId) ?? [];
+ list.push({
+ trackedEntityId: row.trackedEntityId,
+ readableId: row.readableId,
+ qty: Number(row.availableQuantity ?? 0)
+ });
+ poolByItem.set(row.itemId, list);
+ }
+
+ for (const line of linesResult.data ?? []) {
+ const trackingType = (line.item as { itemTrackingType?: string } | null)
+ ?.itemTrackingType;
+ if (trackingType !== "Serial" && trackingType !== "Batch") continue;
+
+ let remaining =
+ Number(line.quantityToPick ?? 0) - Number(line.quantityPicked ?? 0);
+ if (remaining <= 0) continue;
+
+ const pool = poolByItem.get(line.itemId);
+ if (!pool?.length) continue;
+
+ const picks: PickingListRecommendation[] = [];
+ while (remaining > 0 && pool.length > 0) {
+ const lot = pool[0];
+ picks.push({
+ trackedEntityId: lot.trackedEntityId,
+ readableId: lot.readableId
+ });
+ const take = Math.min(lot.qty, remaining);
+ remaining -= take;
+ lot.qty -= take;
+ if (lot.qty <= 0) pool.shift();
+ }
+ recommendations[line.id] = picks;
+ }
+
+ return recommendations;
+}
+
+export type JobMaterialPickedQuantity = {
+ quantityPicked: number;
+ quantityToPick: number;
+};
+
+/**
+ * How much of each job material has been picked, summed across every live picking-list
+ * line that references it. A job material can legitimately span several picking lists,
+ * so we sum per `jobMaterialId`. We only count lines whose parent list is actually being
+ * worked ("In Progress"/"Completed"): cancelling or drafting a list does NOT cascade a
+ * status down to its lines, so a Cancelled/Draft list would otherwise inflate the
+ * to-pick total with stale lines. Picking is optional — materials with no picking
+ * activity simply have no entry in the returned map. Never throws (returns {}).
+ */
+export async function getPickedQuantitiesByJobMaterial(
+ client: SupabaseClient<Database>,
+ jobMaterialIds: string[]
+): Promise<Record<string, JobMaterialPickedQuantity>> {
+ const picked: Record<string, JobMaterialPickedQuantity> = {};
+ if (jobMaterialIds.length === 0) return picked;
+
+ const { data, error } = await client
+ .from("pickingListLine")
+ .select(
+ "jobMaterialId, quantityToPick, quantityPicked, pickingList!inner(status)"
+ )
+ .in("jobMaterialId", jobMaterialIds)
+ .neq("status", "Cancelled")
+ .in("pickingList.status", ["In Progress", "Completed"]);
+
+ if (error || !data) return picked;
+
+ for (const line of data) {
+ if (!line.jobMaterialId) continue;
+ const entry = (picked[line.jobMaterialId] ??= {
+ quantityPicked: 0,
+ quantityToPick: 0
+ });
+ entry.quantityPicked += Number(line.quantityPicked ?? 0);
+ entry.quantityToPick += Number(line.quantityToPick ?? 0);
+ }
+
+ return picked;
+}
+
export async function insertManualInventoryAdjustment(
client: SupabaseClient<Database>,
inventoryAdjustment: z.infer<typeof inventoryAdjustmentValidator> & {
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index 00b72cf03b..329528eceb 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -11,6 +11,7 @@ import type { SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import type { z } from "zod";
import { sanitize } from "~/utils/supabase";
+import { getPickedQuantitiesByJobMaterial } from "./inventory.service";
import type {
documentTypes,
nonScrapQuantityValidator,
@@ -499,16 +500,35 @@ export async function getJobMaterialsByOperationId(
] === materialId && expiredConsumedIds.has(input.id)
);
+ // How much of each material has already been picked (staged at lineside) across any
+ // non-cancelled picking-list line. Picking is optional, so this is additive overlay
+ // data — materials with no picking activity have no entry and render unchanged.
+ const materialIds = Array.from(
+ new Set(
+ (materials.data ?? []).map((m) => m.id).filter((id): id is string => !!id)
+ )
+ );
+ const pickedByMaterial = await getPickedQuantitiesByJobMaterial(
+ client,
+ materialIds
+ );
+ const pickedFor = (materialId: string | null) =>
+ (materialId ? pickedByMaterial[materialId] : undefined) ?? {
+ quantityPicked: 0,
+ quantityToPick: 0
+ };
+
if (requiresSerialTracking) {
return {
materials:
materials.data?.map((material) => {
const hasExpiredConsumed = consumedExpiredFor(material.id);
+ const picked = pickedFor(material.id);
if (
!material.requiresSerialTracking &&
!material.requiresBatchTracking
)
- return { ...material, hasExpiredConsumed };
+ return { ...material, hasExpiredConsumed, ...picked };
const issuedForTrackedParent =
trackedInputs.data
?.filter(
@@ -524,7 +544,8 @@ export async function getJobMaterialsByOperationId(
return {
...material,
quantityIssued: issuedForTrackedParent,
- hasExpiredConsumed
+ hasExpiredConsumed,
+ ...picked
};
}) ?? [],
trackedInputs: trackedInputs.data ?? []
@@ -533,7 +554,8 @@ export async function getJobMaterialsByOperationId(
return {
materials: (materials.data ?? []).map((material) => ({
...material,
- hasExpiredConsumed: consumedExpiredFor(material.id)
+ hasExpiredConsumed: consumedExpiredFor(material.id),
+ ...pickedFor(material.id)
})),
trackedInputs: trackedInputs.data ?? []
};
diff --git a/llm/tasks/lessons.md b/llm/tasks/lessons.md
index 8c665f1139..83c465431a 100644
--- a/llm/tasks/lessons.md
+++ b/llm/tasks/lessons.md
@@ -2,6 +2,24 @@
Patterns learned from corrections. Review at the start of each session.
+## Cancelling a pickingList does NOT cascade `Cancelled` to its lines
+- Symptom: a "picked X/Y" rollup over `pickingListLine` summed too high — a
+ Cancelled picking list's lines were still `status = 'Pending'` and got counted.
+- Root cause: cancelling the LIST leaves each `pickingListLine.status` unchanged.
+- Rule: when aggregating `pickingListLine` (picked qty, allocations, availability),
+ filter by the PARENT `pickingList.status` (count only `In Progress`/`Completed`),
+ not just the line's own status. A line-level `status <> 'Cancelled'` check is
+ NOT sufficient. Likely also relevant to `getAvailableTrackedEntities`
+ (excludeAllocated) and the `get_picking_list_*` RPCs.
+
+## Verify data-scope bugs against the real DB before guessing
+- The local dev DB for `*.picking-list.dev` is Postgres on the port in
+ `.env.local` `SUPABASE_DB_URL` (e.g. 56332). `PGPASSWORD=postgres psql -h
+ localhost -p <port> -U postgres -d postgres` to inspect rows directly — far
+ faster than the browser for confirming a counting/scope discrepancy.
+- Inbucket (dev email catcher) web/API is a docker port-mapped 9000 → find with
+ `docker ps | grep inbucket` (e.g. localhost:56335). Use it for magic-link login.
+
## `*.picking-list.dev` is the LOCAL dev server (crbn + portless)
- The domains `erp.picking-list.dev`, `mes.picking-list.dev`, `api.picking-list.dev`, and `mail.picking-list.dev` (Inbucket) are **not** a remote/preview deployment. They are the **local** dev server that the `crbn` dev CLI spins up for the branch and exposes via **portless** (which maps the branch's local dev processes to those domains).
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 64b77b39d1..3a3bd1da77 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -65520,6 +65520,19 @@ export type Database = {
pickingListLineId: string
}[]
}
+ get_picking_list_tracked_available: {
+ Args: { p_picking_list_id: string }
+ Returns: {
+ availableQuantity: number
+ createdAt: string
+ expirationDate: string
+ itemId: string
+ readableId: string
+ storageUnitId: string
+ storageUnitName: string
+ trackedEntityId: string
+ }[]
+ }
get_picking_schedule: {
Args: { p_company_id: string; p_location_id: string; p_search?: string }
Returns: {
diff --git a/packages/database/supabase/migrations/20260617142853_picking-list-tracked-available.sql b/packages/database/supabase/migrations/20260617142853_picking-list-tracked-available.sql
new file mode 100644
index 0000000000..aa5ddf7931
--- /dev/null
+++ b/packages/database/supabase/migrations/20260617142853_picking-list-tracked-available.sql
@@ -0,0 +1,113 @@
+-- ============================================================================
+-- Function: get_picking_list_tracked_available
+-- Available (status 'Available') tracked entities for EVERY distinct item on a
+-- picking list, at the list's location/company — one row per entity, with the
+-- representative bin (most on-hand within scope) and the order keys for smart
+-- pick guidance. The batched analogue of get_available_tracked_entities, used to
+-- precompute the "recommended" serial/batch numbers shown on each picking line
+-- before the TrackedEntityPicker is opened.
+--
+-- Always nets out ALL non-cancelled allocations (a lot already allocated to any
+-- line is not free) and always drops lineside (work-center) bins — picking
+-- always sources from the warehouse. Rows are grouped + ordered per item by that
+-- item's configured pickMethod.sortMethod so the caller can greedily assign
+-- entities to lines in pick order:
+-- Default/FEFO -> expiringDate ASC (nulls last), then createdAt ASC
+-- FIFO -> createdAt ASC
+-- LIFO -> createdAt DESC
+-- ============================================================================
+
+CREATE OR REPLACE FUNCTION get_picking_list_tracked_available(p_picking_list_id TEXT)
+RETURNS TABLE (
+ "itemId" TEXT,
+ "trackedEntityId" TEXT,
+ "readableId" TEXT,
+ "storageUnitId" TEXT,
+ "storageUnitName" TEXT,
+ "availableQuantity" NUMERIC,
+ "createdAt" TIMESTAMPTZ,
+ "expirationDate" DATE
+)
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+AS $$
+ WITH pl AS (
+ SELECT "id", "companyId", "locationId"
+ FROM "pickingList"
+ WHERE "id" = p_picking_list_id
+ ),
+ list_items AS (
+ SELECT DISTINCT pll."itemId"
+ FROM "pickingListLine" pll
+ WHERE pll."pickingListId" = p_picking_list_id
+ AND pll."status" <> 'Cancelled'
+ ),
+ bin_onhand AS (
+ SELECT
+ il."itemId",
+ il."trackedEntityId",
+ il."storageUnitId",
+ s."name" AS storage_unit_name,
+ SUM(il."quantity") AS on_hand
+ FROM "itemLedger" il
+ JOIN pl ON il."companyId" = pl."companyId" AND il."locationId" = pl."locationId"
+ JOIN list_items li ON li."itemId" = il."itemId"
+ LEFT JOIN "storageUnit" s ON s."id" = il."storageUnitId"
+ WHERE il."trackedEntityId" IS NOT NULL
+ AND get_effective_work_center_id(il."storageUnitId") IS NULL
+ GROUP BY il."itemId", il."trackedEntityId", il."storageUnitId", s."name"
+ HAVING SUM(il."quantity") > 0
+ ),
+ entity_total AS (
+ SELECT "itemId", "trackedEntityId", SUM(on_hand) AS total_on_hand
+ FROM bin_onhand
+ GROUP BY "itemId", "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" pl2 ON pl2."id" = pll."pickingListId"
+ WHERE pl2."status" <> 'Cancelled'
+ AND pll."status" <> 'Cancelled'
+ GROUP BY pllte."trackedEntityId"
+ )
+ SELECT
+ et."itemId",
+ et."trackedEntityId",
+ te."readableId",
+ pb."storageUnitId",
+ pb.storage_unit_name AS "storageUnitName",
+ et.total_on_hand - COALESCE(a.allocated_qty, 0) AS "availableQuantity",
+ te."createdAt",
+ te."expirationDate"
+ FROM entity_total et
+ JOIN "trackedEntity" te ON te."id" = et."trackedEntityId"
+ JOIN primary_bin pb ON pb."trackedEntityId" = et."trackedEntityId"
+ CROSS JOIN pl
+ LEFT JOIN "pickMethod" pm
+ ON pm."itemId" = et."itemId"
+ AND pm."locationId" = pl."locationId"
+ AND pm."companyId" = pl."companyId"
+ LEFT JOIN allocated a ON a."trackedEntityId" = et."trackedEntityId"
+ WHERE te."status" = 'Available'
+ AND (et.total_on_hand - COALESCE(a.allocated_qty, 0)) > 0
+ ORDER BY
+ et."itemId",
+ CASE
+ WHEN COALESCE(pm."sortMethod", 'Default') IN ('Default', 'FEFO')
+ THEN te."expirationDate"
+ END ASC NULLS LAST,
+ CASE
+ WHEN COALESCE(pm."sortMethod", 'Default') = 'LIFO'
+ THEN te."createdAt"
+ END DESC,
+ te."createdAt" ASC;
+$$;
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 528fed3bb5..84f0343b49 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -71,7 +71,7 @@ msgid "+{0} more"
msgstr "+{0} weitere"
msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."
-msgstr ""
+msgstr "<0>Fügen Sie einen Lieferantenteil hinzu</0>, um für diesen Artikel einen bevorzugten Lieferanten festzulegen."
msgid "<0>delete</0> lets you delete rows. <1>delete</1> will match all rows by default, so remember to specify your filters!"
msgstr "<0>delete</0> ermöglicht es dir, Zeilen zu löschen. <1>delete</1> stimmt standardmäßig mit allen Zeilen überein, also denke daran, deine Filter anzugeben!"
@@ -2257,9 +2257,6 @@ msgstr "Standardmethode"
msgid "Default Method Type"
msgstr "Standardmethodentyp"
-msgid "Default order when picking serial or batch lots of this item. Pickers can still override it."
-msgstr "Standardreihenfolge beim Kommissionieren von Serien- oder Chargenlosen dieses Artikels. Kommissionierer können diese noch überschreiben."
-
msgid "Default Permissions"
msgstr "Standardberechtigungen"
@@ -5421,7 +5418,7 @@ msgid "No stock"
msgstr "Kein Bestand"
msgid "No suppliers yet"
-msgstr ""
+msgstr "Noch keine Lieferanten"
msgid "No time entries for this week"
msgstr "Keine Zeiteinträge für diese Woche"
@@ -7260,7 +7257,7 @@ msgid "Share"
msgstr "Teilen"
msgid "Share a branded portal link so customers can track their orders and documents."
-msgstr ""
+msgstr "Teilen Sie einen Portallink mit Ihrem Branding, damit Kunden ihre Bestellungen und Dokumente verfolgen können."
msgid "Share Link"
msgstr "Link teilen"
diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.po
index 15e91fc18d..8fd7de3580 100644
--- a/packages/locale/locales/de/mes.po
+++ b/packages/locale/locales/de/mes.po
@@ -722,6 +722,9 @@ msgstr "Kommissionieren"
msgid "Pick tracked item"
msgstr "Verfolgtes Element auswählen"
+msgid "Picked"
+msgstr "Gepickt"
+
msgid "Picked quantity"
msgstr "Gepickte Menge"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 69482dc3a3..72e5caba67 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -2257,9 +2257,6 @@ msgstr "Default Method"
msgid "Default Method Type"
msgstr "Default Method Type"
-msgid "Default order when picking serial or batch lots of this item. Pickers can still override it."
-msgstr "Default order when picking serial or batch lots of this item. Pickers can still override it."
-
msgid "Default Permissions"
msgstr "Default Permissions"
diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.po
index 2340ad9afe..cf9b0e058a 100644
--- a/packages/locale/locales/en/mes.po
+++ b/packages/locale/locales/en/mes.po
@@ -722,6 +722,9 @@ msgstr "Pick"
msgid "Pick tracked item"
msgstr "Pick tracked item"
+msgid "Picked"
+msgstr "Picked"
+
msgid "Picked quantity"
msgstr "Picked quantity"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 1e2ccd01ad..1162ac4d83 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -71,7 +71,7 @@ msgid "+{0} more"
msgstr "+{0} más"
msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."
-msgstr ""
+msgstr "<0>Agregar una parte de proveedor</0> para este artículo para establecer un proveedor preferido."
msgid "<0>delete</0> lets you delete rows. <1>delete</1> will match all rows by default, so remember to specify your filters!"
msgstr "<0>delete</0> te permite eliminar filas. <1>delete</1> coincidirá con todas las filas de forma predeterminada, ¡así que recuerda especificar tus filtros!"
@@ -2257,9 +2257,6 @@ msgstr "Método Predeterminado"
msgid "Default Method Type"
msgstr "Tipo de Método Predeterminado"
-msgid "Default order when picking serial or batch lots of this item. Pickers can still override it."
-msgstr "Orden predeterminada al seleccionar lotes seriales o por lotes de este artículo. Los recolectores aún pueden anularla."
-
msgid "Default Permissions"
msgstr "Permisos Predeterminados"
@@ -5421,7 +5418,7 @@ msgid "No stock"
msgstr "Sin stock"
msgid "No suppliers yet"
-msgstr ""
+msgstr "Sin proveedores aún"
msgid "No time entries for this week"
msgstr "No hay entradas de tiempo para esta semana"
@@ -7260,7 +7257,7 @@ msgid "Share"
msgstr "Compartir"
msgid "Share a branded portal link so customers can track their orders and documents."
-msgstr ""
+msgstr "Comparte un enlace de portal personalizado para que los clientes puedan rastrear sus pedidos y documentos."
msgid "Share Link"
msgstr "Enlace compartido"
diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.po
index 0e2f025bea..59376f5bd1 100644
--- a/packages/locale/locales/es/mes.po
+++ b/packages/locale/locales/es/mes.po
@@ -722,6 +722,9 @@ msgstr "Recoger"
msgid "Pick tracked item"
msgstr "Seleccionar artículo rastreado"
+msgid "Picked"
+msgstr "Recogido"
+
msgid "Picked quantity"
msgstr "Cantidad recogida"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 0fe745022d..187456f300 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -71,7 +71,7 @@ msgid "+{0} more"
msgstr "+{0} de plus"
msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."
-msgstr ""
+msgstr "<0>Ajouter une pièce fournisseur</0> pour cet article afin de définir un fournisseur préféré."
msgid "<0>delete</0> lets you delete rows. <1>delete</1> will match all rows by default, so remember to specify your filters!"
msgstr "<0>delete</0> vous permet de supprimer des lignes. <1>delete</1> correspondra à toutes les lignes par défaut, alors n'oubliez pas de spécifier vos filtres !"
@@ -2257,9 +2257,6 @@ msgstr "Méthode par défaut"
msgid "Default Method Type"
msgstr "Type de méthode par défaut"
-msgid "Default order when picking serial or batch lots of this item. Pickers can still override it."
-msgstr "Ordre par défaut lors du prélèvement de lots en série ou par lot de cet article. Les préleveurs peuvent toujours le modifier."
-
msgid "Default Permissions"
msgstr "Permissions par défaut"
@@ -5421,7 +5418,7 @@ msgid "No stock"
msgstr "Aucun stock"
msgid "No suppliers yet"
-msgstr ""
+msgstr "Aucun fournisseur pour le moment"
msgid "No time entries for this week"
msgstr "Aucune entrée de temps pour cette semaine"
@@ -7260,7 +7257,7 @@ msgid "Share"
msgstr "Partager"
msgid "Share a branded portal link so customers can track their orders and documents."
-msgstr ""
+msgstr "Partagez un lien de portail personnalisé pour que les clients puissent suivre leurs commandes et documents."
msgid "Share Link"
msgstr "Lien de partage"
diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.po
index 1789dc9f6a..7536f80a10 100644
--- a/packages/locale/locales/fr/mes.po
+++ b/packages/locale/locales/fr/mes.po
@@ -722,6 +722,9 @@ msgstr "Prélever"
msgid "Pick tracked item"
msgstr "Sélectionner un article suivi"
+msgid "Picked"
+msgstr "Prélevé"
+
msgid "Picked quantity"
msgstr "Quantité prélevée"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 12e99c101d..ee62b9cd61 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -71,7 +71,7 @@ msgid "+{0} more"
msgstr "+{0} और"
msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."
-msgstr ""
+msgstr "<0>एक आपूर्तिकर्ता भाग जोड़ें</0> इस आइटम के लिए एक पसंदीदा आपूर्तिकर्ता सेट करने के लिए।"
msgid "<0>delete</0> lets you delete rows. <1>delete</1> will match all rows by default, so remember to specify your filters!"
msgstr "<0>delete</0> आपको पंक्तियों को हटाने देता है। <1>delete</1> डिफ़ॉल्ट रूप से सभी पंक्तियों से मेल खाएगा, इसलिए अपने फ़िल्टर निर्दिष्ट करना याद रखें!"
@@ -2257,9 +2257,6 @@ msgstr "डिफ़ॉल्ट विधि"
msgid "Default Method Type"
msgstr "डिफ़ॉल्ट विधि प्रकार"
-msgid "Default order when picking serial or batch lots of this item. Pickers can still override it."
-msgstr "इस आइटम के सीरियल या बैच लॉट्स को चुनते समय डिफ़ॉल्ट ऑर्डर। पिकर्स इसे अभी भी ओवरराइड कर सकते हैं।"
-
msgid "Default Permissions"
msgstr "डिफ़ॉल्ट अनुमतियाँ"
@@ -5421,7 +5418,7 @@ msgid "No stock"
msgstr "स्टॉक नहीं"
msgid "No suppliers yet"
-msgstr ""
+msgstr "अभी तक कोई आपूर्तिकर्ता नहीं"
msgid "No time entries for this week"
msgstr "इस सप्ताह के लिए कोई समय प्रविष्टि नहीं"
@@ -7260,7 +7257,7 @@ msgid "Share"
msgstr "साझा करें"
msgid "Share a branded portal link so customers can track their orders and documents."
-msgstr ""
+msgstr "एक ब्रांडेड पोर्टल लिंक साझा करें ताकि ग्राहक अपने ऑर्डर और दस्तावेज़ों को ट्रैक कर सकें।"
msgid "Share Link"
msgstr "लिंक साझा करें"
diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.po
index 64a45768b9..3a39583ae5 100644
--- a/packages/locale/locales/hi/mes.po
+++ b/packages/locale/locales/hi/mes.po
@@ -722,6 +722,9 @@ msgstr "चुनें"
msgid "Pick tracked item"
msgstr "ट्रैक किए गए आइटम को चुनें"
+msgid "Picked"
+msgstr "उठाया गया"
+
msgid "Picked quantity"
msgstr "चुना गया मात्रा"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index deb6e6f5a4..d4438cefd5 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -71,7 +71,7 @@ msgid "+{0} more"
msgstr "+{0} altri"
msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."
-msgstr ""
+msgstr "<0>Aggiungi una parte fornitore</0> per questo articolo per impostare un fornitore preferito."
msgid "<0>delete</0> lets you delete rows. <1>delete</1> will match all rows by default, so remember to specify your filters!"
msgstr "<0>delete</0> ti permette di eliminare righe. <1>delete</1> corrisponderà a tutte le righe per impostazione predefinita, quindi ricordati di specificare i tuoi filtri!"
@@ -2257,9 +2257,6 @@ msgstr "Metodo Predefinito"
msgid "Default Method Type"
msgstr "Tipo di Metodo Predefinito"
-msgid "Default order when picking serial or batch lots of this item. Pickers can still override it."
-msgstr "Ordine predefinito quando si selezionano lotti seriali o batch di questo articolo. I picker possono comunque ignorarlo."
-
msgid "Default Permissions"
msgstr "Autorizzazioni Predefinite"
@@ -5421,7 +5418,7 @@ msgid "No stock"
msgstr "Nessun stock"
msgid "No suppliers yet"
-msgstr ""
+msgstr "Nessun fornitore ancora"
msgid "No time entries for this week"
msgstr "Nessuna registrazione oraria per questa settimana"
@@ -7260,7 +7257,7 @@ msgid "Share"
msgstr "Condividi"
msgid "Share a branded portal link so customers can track their orders and documents."
-msgstr ""
+msgstr "Condividi un link del portale personalizzato in modo che i clienti possano tracciare i loro ordini e documenti."
msgid "Share Link"
msgstr "Condividi Link"
diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.po
index e12c12c735..46d8658f56 100644
--- a/packages/locale/locales/it/mes.po
+++ b/packages/locale/locales/it/mes.po
@@ -722,6 +722,9 @@ msgstr "Preleva"
msgid "Pick tracked item"
msgstr "Seleziona articolo tracciato"
+msgid "Picked"
+msgstr "Prelevato"
+
msgid "Picked quantity"
msgstr "Quantità prelevata"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 472057abe2..53afc6c798 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -71,7 +71,7 @@ msgid "+{0} more"
msgstr "+{0} 件以上"
msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."
-msgstr ""
+msgstr "<0>サプライヤー部品を追加</0>このアイテムの優先サプライヤーを設定します。"
msgid "<0>delete</0> lets you delete rows. <1>delete</1> will match all rows by default, so remember to specify your filters!"
msgstr "<0>delete</0>を使用すると行を削除できます。<1>delete</1>はデフォルトではすべての行にマッチするため、フィルターを指定することを忘れないでください。"
@@ -2257,9 +2257,6 @@ msgstr "デフォルト方法"
msgid "Default Method Type"
msgstr "デフォルトメソッドタイプ"
-msgid "Default order when picking serial or batch lots of this item. Pickers can still override it."
-msgstr "このアイテムのシリアルまたはバッチロットをピッキングする際のデフォルト順序。ピッカーはそれでも上書きできます。"
-
msgid "Default Permissions"
msgstr "デフォルト権限"
@@ -5421,7 +5418,7 @@ msgid "No stock"
msgstr "在庫なし"
msgid "No suppliers yet"
-msgstr ""
+msgstr "まだサプライヤーがありません"
msgid "No time entries for this week"
msgstr "今週のタイムエントリがありません"
@@ -7260,7 +7257,7 @@ msgid "Share"
msgstr "共有"
msgid "Share a branded portal link so customers can track their orders and documents."
-msgstr ""
+msgstr "ブランド化されたポータルリンクを共有して、顧客が注文と書類を追跡できるようにします。"
msgid "Share Link"
msgstr "リンクを共有"
diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.po
index 35328bedcd..5a8c9c7278 100644
--- a/packages/locale/locales/ja/mes.po
+++ b/packages/locale/locales/ja/mes.po
@@ -722,6 +722,9 @@ msgstr "ピック"
msgid "Pick tracked item"
msgstr "追跡品目をピック"
+msgid "Picked"
+msgstr "ピック済み"
+
msgid "Picked quantity"
msgstr "ピック数量"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index b133b9f5a5..02792805e4 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -71,7 +71,7 @@ msgid "+{0} more"
msgstr "+{0} więcej"
msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."
-msgstr ""
+msgstr "<0>Dodaj część dostawcy</0> dla tego artykułu, aby ustawić preferowanego dostawcę."
msgid "<0>delete</0> lets you delete rows. <1>delete</1> will match all rows by default, so remember to specify your filters!"
msgstr "<0>delete</0> pozwala usuwać wiersze. <1>delete</1> domyślnie będzie pasować do wszystkich wierszy, więc pamiętaj, aby określić swoje filtry!"
@@ -2257,9 +2257,6 @@ msgstr "Metoda domyślna"
msgid "Default Method Type"
msgstr "Domyślny typ metody"
-msgid "Default order when picking serial or batch lots of this item. Pickers can still override it."
-msgstr "Domyślna kolejność podczas wybierania partii seryjnych lub zbiorczych tego artykułu. Pracownicy mogą ją nadal zmienić."
-
msgid "Default Permissions"
msgstr "Uprawnienia domyślne"
@@ -5421,7 +5418,7 @@ msgid "No stock"
msgstr "Brak zapasu"
msgid "No suppliers yet"
-msgstr ""
+msgstr "Brak dostawców"
msgid "No time entries for this week"
msgstr "Brak wpisów czasu pracy w tym tygodniu"
@@ -7260,7 +7257,7 @@ msgid "Share"
msgstr "Udostępnij"
msgid "Share a branded portal link so customers can track their orders and documents."
-msgstr ""
+msgstr "Udostępnij link do portalu ze swoją marką, aby klienci mogli śledzić swoje zamówienia i dokumenty."
msgid "Share Link"
msgstr "Udostępnij Link"
diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.po
index c2c91138cd..b4e8d502f8 100644
--- a/packages/locale/locales/pl/mes.po
+++ b/packages/locale/locales/pl/mes.po
@@ -722,6 +722,9 @@ msgstr "Pobierz"
msgid "Pick tracked item"
msgstr "Wybierz śledzony element"
+msgid "Picked"
+msgstr "Pobrane"
+
msgid "Picked quantity"
msgstr "Pobrana ilość"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index e06afa0455..8047ac684c 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -71,7 +71,7 @@ msgid "+{0} more"
msgstr "+{0} mais"
msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."
-msgstr ""
+msgstr "<0>Adicionar uma peça de fornecedor</0> para este item para definir um fornecedor preferido."
msgid "<0>delete</0> lets you delete rows. <1>delete</1> will match all rows by default, so remember to specify your filters!"
msgstr "<0>delete</0> permite que você delete linhas. <1>delete</1> corresponderá a todas as linhas por padrão, então lembre-se de especificar seus filtros!"
@@ -2257,9 +2257,6 @@ msgstr "Método Padrão"
msgid "Default Method Type"
msgstr "Tipo de Método Padrão"
-msgid "Default order when picking serial or batch lots of this item. Pickers can still override it."
-msgstr "Ordem padrão ao selecionar lotes seriais ou em lote deste item. Os operadores ainda podem substituí-la."
-
msgid "Default Permissions"
msgstr "Permissões Padrão"
@@ -5421,7 +5418,7 @@ msgid "No stock"
msgstr "Sem stock"
msgid "No suppliers yet"
-msgstr ""
+msgstr "Nenhum fornecedor ainda"
msgid "No time entries for this week"
msgstr "Sem registros de tempo para esta semana"
@@ -7260,7 +7257,7 @@ msgid "Share"
msgstr "Partilhar"
msgid "Share a branded portal link so customers can track their orders and documents."
-msgstr ""
+msgstr "Compartilhe um link de portal personalizado para que os clientes possam rastrear seus pedidos e documentos."
msgid "Share Link"
msgstr "Compartilhar Link"
diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.po
index e9eed229f5..6c123b7f62 100644
--- a/packages/locale/locales/pt/mes.po
+++ b/packages/locale/locales/pt/mes.po
@@ -722,6 +722,9 @@ msgstr "Apanhar"
msgid "Pick tracked item"
msgstr "Selecionar item rastreado"
+msgid "Picked"
+msgstr "Apanhado"
+
msgid "Picked quantity"
msgstr "Quantidade colhida"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 86023b4a44..6d373d8b87 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -71,7 +71,7 @@ msgid "+{0} more"
msgstr "+{0} ещё"
msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."
-msgstr ""
+msgstr "<0>Добавить поставщика</0> для этого товара, чтобы установить предпочтительного поставщика."
msgid "<0>delete</0> lets you delete rows. <1>delete</1> will match all rows by default, so remember to specify your filters!"
msgstr "<0>delete</0> позволяет удалять строки. <1>delete</1> по умолчанию совпадает со всеми строками, поэтому не забудьте указать фильтры!"
@@ -2257,9 +2257,6 @@ msgstr "Метод по умолчанию"
msgid "Default Method Type"
msgstr "Тип метода по умолчанию"
-msgid "Default order when picking serial or batch lots of this item. Pickers can still override it."
-msgstr "Порядок по умолчанию при выборе серийных или партионных лотов этого товара. Комплектовщики могут переопределить его."
-
msgid "Default Permissions"
msgstr "Разрешения по умолчанию"
@@ -5421,7 +5418,7 @@ msgid "No stock"
msgstr "Нет запасов"
msgid "No suppliers yet"
-msgstr ""
+msgstr "Поставщиков еще нет"
msgid "No time entries for this week"
msgstr "Нет записей о времени на эту неделю"
@@ -7260,7 +7257,7 @@ msgid "Share"
msgstr "Поделиться"
msgid "Share a branded portal link so customers can track their orders and documents."
-msgstr ""
+msgstr "Поделитесь ссылкой на фирменный портал, чтобы клиенты могли отслеживать свои заказы и документы."
msgid "Share Link"
msgstr "Поделиться ссылкой"
diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.po
index c37c99c600..2dbb734330 100644
--- a/packages/locale/locales/ru/mes.po
+++ b/packages/locale/locales/ru/mes.po
@@ -722,6 +722,9 @@ msgstr "Выбрать"
msgid "Pick tracked item"
msgstr "Выбрать отслеживаемый товар"
+msgid "Picked"
+msgstr "Подобрано"
+
msgid "Picked quantity"
msgstr "Выбранное количество"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 45c2d7f5db..adda232d5d 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -71,7 +71,7 @@ msgid "+{0} more"
msgstr "+{0} 更多"
msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."
-msgstr ""
+msgstr "<0>为此项目添加供应商零件</0>以设置首选供应商。"
msgid "<0>delete</0> lets you delete rows. <1>delete</1> will match all rows by default, so remember to specify your filters!"
msgstr "<0>delete</0> 让您删除行。<1>delete</1> 默认会匹配所有行,所以请记住指定您的过滤条件!"
@@ -2257,9 +2257,6 @@ msgstr "默认方法"
msgid "Default Method Type"
msgstr "默认方法类型"
-msgid "Default order when picking serial or batch lots of this item. Pickers can still override it."
-msgstr "拣选此物品的序列号或批次时的默认顺序。拣选员仍可以覆盖它。"
-
msgid "Default Permissions"
msgstr "默认权限"
@@ -5421,7 +5418,7 @@ msgid "No stock"
msgstr "无库存"
msgid "No suppliers yet"
-msgstr ""
+msgstr "还没有供应商"
msgid "No time entries for this week"
msgstr "本周没有时间条目"
@@ -7260,7 +7257,7 @@ msgid "Share"
msgstr "分享"
msgid "Share a branded portal link so customers can track their orders and documents."
-msgstr ""
+msgstr "分享品牌门户链接,让客户可以跟踪他们的订单和文档。"
msgid "Share Link"
msgstr "分享链接"
diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.po
index 3fafd86f13..793d4b41a8 100644
--- a/packages/locale/locales/zh/mes.po
+++ b/packages/locale/locales/zh/mes.po
@@ -722,6 +722,9 @@ msgstr "拣选"
msgid "Pick tracked item"
msgstr "拣选追踪项目"
+msgid "Picked"
+msgstr "已拣选"
+
msgid "Picked quantity"
msgstr "已拣选数量"
diff --git a/packages/react/src/TrackedEntityPicker.tsx b/packages/react/src/TrackedEntityPicker.tsx
index 0363660d69..1a8f436baf 100644
--- a/packages/react/src/TrackedEntityPicker.tsx
+++ b/packages/react/src/TrackedEntityPicker.tsx
@@ -160,6 +160,17 @@ export function TrackedEntityPicker({
const [order, setOrder] = useState<TrackedEntityPickOrder>(defaultOrder);
const [scan, setScan] = useState("");
+ // Hosts open the picker and fetch its data in parallel, so `defaultOrder`
+ // arrives a render after mount (undefined -> the item's configured order).
+ // Re-sync the selection when it changes so the stored pick order wins over
+ // the "Default" fallback. A subsequent user override sticks because
+ // `defaultOrder` is then stable.
+ const [appliedDefaultOrder, setAppliedDefaultOrder] = useState(defaultOrder);
+ if (defaultOrder !== appliedDefaultOrder) {
+ setAppliedDefaultOrder(defaultOrder);
+ setOrder(defaultOrder);
+ }
+
const orderOptions = usePickOrderOptions();
const ordered = useMemo(