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: scan bar codes for serial/batch transfers
Brad Barbin14a23b5b1b29
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.tsindex 4a05845f42..8b78659648 100644--- a/apps/erp/app/modules/inventory/inventory.models.ts+++ b/apps/erp/app/modules/inventory/inventory.models.ts@@ -288,6 +288,8 @@ export const stockTransferValidator = z.object({fromShelfId: z.string().optional(),toShelfId: z.string().optional(),quantity: z.number().min(0).optional(),+ requiresSerialTracking: z.boolean().optional(),+ requiresBatchTracking: z.boolean().optional(),})).min(1, { message: "At least one line is required" })@@ -314,4 +316,20 @@ export const stockTransferLineValidator = z.object({.min(0, { message: "Quantity must be greater than or equal to 0" })),pickedQuantity: zfd.numeric(z.number().min(0).optional()),+ requiresBatchTracking: zfd.text(+ z.string().transform((val) => val === "true")+ ),+ requiresSerialTracking: zfd.text(+ z.string().transform((val) => val === "true")+ ),+});++export const stockTransferLineScanValidator = z.object({+ id: zfd.text(z.string().optional()),+ itemId: z.string().min(1, { message: "Item is required" }),+ locationId: z.string().min(1, { message: "Location is required" }),+ stockTransferId: z.string().min(1, { message: "Stock transfer is required" }),+ trackedEntityId: z+ .string()+ .min(1, { message: "Tracked entity ID is required" }),});diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 6c6843e637..cce4aa898d 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -270,7 +270,7 @@ export async function getStockTransferLine(stockTransferLineId: string) {return client- .from("stockTransferLine")+ .from("stockTransferLines").select("*").eq("id", stockTransferLineId).single();@@ -294,9 +294,10 @@ export async function getStockTransferTracking(companyId: string) {return client- .from("trackedEntity")- .select("*")- .eq("attributes ->> Stock Transfer", stockTransferId)+ .from("trackedActivity")+ .select("attributes, trackedActivityInput(trackedEntityId)")+ .eq("sourceDocument", "Stock Transfer")+ .eq("sourceDocumentId", stockTransferId).eq("companyId", companyId);}@@ -1242,7 +1243,10 @@ export async function upsertStockTransfer(if ("createdBy" in stockTransfer) {return client.from("stockTransfer")- .insert(stockTransfer)+ .insert({+ ...stockTransfer,+ status: "Released",+ }).select("id").single();}diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsxindex c25a680d02..37252f9361 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx@@ -228,7 +228,7 @@ const InventoryShelves = ({name="quantity"label="Quantity"minValue={0}- value={quantity}+ value={isSerial ? 1 : quantity}onChange={setQuantity}isReadOnly={isSerial}/>diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsxindex 257e39fa10..e95ffb01df 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx@@ -71,6 +71,10 @@ const StockTransferHeader = () => {? optimisticAssignment: routeData?.stockTransfer?.assignee;+ const hasPickedItems = routeData?.stockTransferLines.some(+ (line) => line.pickedQuantity && line.pickedQuantity > 0+ );+return (<><div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border h-[50px] overflow-x-auto scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1)]">@@ -94,7 +98,9 @@ const StockTransferHeader = () => {<DropdownMenuItemdisabled={!permissions.can("delete", "inventory") ||- !permissions.is("employee")+ !permissions.is("employee") ||+ !["Released", "Draft"].includes(status) ||+ hasPickedItems}destructiveonClick={deleteModal.onOpen}diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLineForm.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLineForm.tsxindex d70abe6ff6..88060673dd 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLineForm.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLineForm.tsx@@ -57,6 +57,18 @@ const StockTransferLineForm = ({return "Item";});+ const [itemTrackingType, setItemTrackingType] = useState<string | null>(+ () => {+ if (initialValues.itemId) {+ return (+ items.find((item) => item.id === initialValues.itemId)+ ?.itemTrackingType ?? null+ );+ }+ return null;+ }+ );+const onTypeChange = (t: MethodItemType | "Item") => {setItemType(t);setItemId(null);@@ -64,10 +76,11 @@ const StockTransferLineForm = ({const onItemChange = (itemId: string) => {setItemId(itemId);- const itemType =- (items.find((item) => item.id === itemId)?.type as MethodItemType) ??- "Item";+ const item = items.find((item) => item.id === itemId);+ const itemType = (item?.type as MethodItemType) ?? "Item";+ const trackingType = item?.itemTrackingType ?? null;setItemType(itemType);+ setItemTrackingType(trackingType);};useEffect(() => {@@ -117,6 +130,14 @@ const StockTransferLineForm = ({<ModalDrawerBody><Hidden name="id" /><Hidden name="stockTransferId" />+ <Hidden+ name="requiresSerialTracking"+ value={itemTrackingType === "Serial" ? "true" : "false"}+ />+ <Hidden+ name="requiresBatchTracking"+ value={itemTrackingType === "Batch" ? "true" : "false"}+ /><VStack spacing={4}><Itemname="itemId"@@ -129,7 +150,13 @@ const StockTransferLineForm = ({onTypeChange={onTypeChange}value={itemId ?? undefined}/>- <Number name="quantity" label="Quantity" />+ <Number+ name="quantity"+ label="Quantity"+ minValue={itemTrackingType === "Serial" ? 1 : 0}+ maxValue={itemTrackingType === "Serial" ? 1 : undefined}+ defaultValue={itemTrackingType === "Serial" ? 1 : undefined}+ /><Shelfname="fromShelfId"label="From Shelf"diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsxindex ae2446ece8..d716bd0bae 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx@@ -17,13 +17,19 @@ import {cn,useDisclosure,} from "@carbon/react";-import { Link, useFetchers, useParams, useSubmit } from "@remix-run/react";+import {+ Link,+ useFetchers,+ useNavigate,+ useParams,+ useSubmit,+} from "@remix-run/react";import { useState } from "react";import {- LuCircleCheck,LuCirclePlus,LuEllipsisVertical,LuPencilLine,+ LuQrCode,LuTrash,LuUndo2,} from "react-icons/lu";@@ -36,22 +42,206 @@ import { usePermissions, useRouteData } from "~/hooks";import type { StockTransfer, StockTransferLine } from "~/modules/inventory";import { useItems } from "~/stores";import { path } from "~/utils/path";+import type { TrackedEntityAttributes } from "../../../../../../../packages/utils/src/types";++interface StockTransferLineProps {+ line: StockTransferLine;+ index: number;+ totalLines: number;+ pickedQuantity: number;+ isPickable: boolean;+ isEditable: boolean;+ isPending: boolean;+ onPick: (line: StockTransferLine) => void;+ onUnpick: (line: StockTransferLine) => void;+ onDelete: (line: StockTransferLine) => void;+ permissions: ReturnType<typeof usePermissions>;+}++function StockTransferLineComponent({+ line,+ index,+ totalLines,+ pickedQuantity,+ isPickable,+ isEditable,+ isPending,+ onPick,+ onUnpick,+ onDelete,+ permissions,+}: StockTransferLineProps) {+ const navigate = useNavigate();+ const params = useParams();+ const { id } = params;+ if (!id) throw new Error("stock transfer id not found");+ const [items] = useItems();+ const unitsOfMeasure = useUnitOfMeasure();++ const item = items.find((p) => p.id === line.itemId);+ const isTracked = line.requiresSerialTracking || line.requiresBatchTracking;++ return (+ <div+ className={cn(+ "flex flex-col border-b p-6 gap-6",+ index === totalLines - 1 && "border-none"+ )}+ >+ <div className="flex justify-between items-center w-full">+ <HStack spacing={4} className="w-1/2 justify-between">+ <HStack spacing={4}>+ <ItemThumbnail+ size="md"+ thumbnailPath={line.thumbnailPath}+ type={(item?.type as "Part") ?? "Part"}+ />+ <VStack spacing={0} className="max-w-[380px] w-full">+ <div className="w-full overflow-hidden">+ <span className="text-sm font-medium truncate block w-full">+ {item?.name}+ </span>+ <span className="text-xs text-muted-foreground truncate block w-full">+ {item?.readableIdWithRevision}+ </span>+ </div>+ <div className="mt-2">+ <Enumerable+ value={+ unitsOfMeasure?.find((u) => u.value === line.unitOfMeasure)+ ?.label ?? null+ }+ />+ </div>+ </VStack>+ </HStack>+ <VStack spacing={1} className="text-end items-end">+ <label className="text-xs text-muted-foreground text-right">+ Quantity+ </label>+ <span className="text-sm py-1.5 text-right">+ {pickedQuantity}/{line.quantity ?? 0}+ </span>+ </VStack>+ </HStack>+ <div className="flex flex-grow items-center justify-between gap-4 pl-4 w-1/2">+ <HStack spacing={4} className="text-left items-center">+ {"fromShelfId" in line && (+ <VStack spacing={1} className="text-left items-start">+ <label className="text-xs text-muted-foreground">From</label>+ <span className="text-sm py-1.5 whitespace-nowrap">+ {line.fromShelfName ?? ""}+ </span>+ </VStack>+ )}+ {"toShelfId" in line && (+ <VStack spacing={1} className="text-center items-center">+ <label className="text-xs text-muted-foreground">To</label>+ <span className="text-sm py-1.5 whitespace-nowrap">+ {line.toShelfName ?? ""}+ </span>+ </VStack>+ )}+ </HStack>+ <HStack spacing={1}>+ {pickedQuantity === line.quantity ? (+ <Button+ variant="secondary"+ isDisabled={!isPickable || isPending}+ isLoading={isPending}+ leftIcon={<LuUndo2 />}+ onClick={() => onUnpick(line)}+ >+ Unpick+ </Button>+ ) : (+ <Button+ isDisabled={!isPickable || isPending}+ isLoading={isPending}+ leftIcon={isTracked ? <LuQrCode /> : <LuCirclePlus />}+ onClick={+ isTracked+ ? () => navigate(path.to.stockTransferScan(id, line.id!))+ : () => onPick(line)+ }+ >+ Pick+ </Button>+ )}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ variant="secondary"+ isDisabled={!isEditable}+ icon={<LuEllipsisVertical />}+ aria-label="Line options"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem+ disabled={+ !isEditable || !permissions.can("update", "inventory")+ }+ asChild+ >+ <Link+ to={path.to.stockTransferLine(+ line.stockTransferId!,+ line.id!+ )}+ >+ <DropdownMenuIcon icon={<LuPencilLine />} />+ Edit Line+ </Link>+ </DropdownMenuItem>+ <DropdownMenuItem+ disabled={+ !isEditable || !permissions.can("delete", "inventory")+ }+ destructive+ onClick={() => onDelete(line)}+ >+ <DropdownMenuIcon icon={<LuTrash />} />+ Delete Line+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </HStack>+ </div>+ </div>+ </div>+ );+}export default function StockTransferLines() {const params = useParams();const { id } = params;if (!id) throw new Error("stock transfer id not found");- const [items] = useItems();const permissions = usePermissions();- const unitsOfMeasure = useUnitOfMeasure();const locations = useLocations();const routeData = useRouteData<{stockTransfer: StockTransfer;stockTransferLines: StockTransferLine[];+ stockTransferLineTracking: {+ attributes: TrackedEntityAttributes;+ trackedActivityInput: { trackedEntityId: string }[];+ }[];}>(path.to.stockTransfer(id));+ const trackedEntitiesByLineId = new Map<string, string>();+ routeData?.stockTransferLineTracking.forEach((trackedEntity) => {+ const attributes = trackedEntity.attributes as TrackedEntityAttributes;+ const stockTransferLineId = attributes["Stock Transfer Line"];+ if (stockTransferLineId) {+ trackedEntitiesByLineId.set(+ stockTransferLineId,+ trackedEntity.trackedActivityInput.at(0)?.trackedEntityId ?? ""+ );+ }+ });+const isPickable = ["Released", "In Progress"].includes(routeData?.stockTransfer?.status ?? "");@@ -105,6 +295,11 @@ export default function StockTransferLines() {formData.append("quantity", line.quantity!.toString());formData.append("locationId", routeData?.stockTransfer?.locationId ?? "");+ const trackedEntityId = trackedEntitiesByLineId.get(line.id ?? "");+ if (trackedEntityId) {+ formData.append("trackedEntityId", trackedEntityId);+ }+submit(formData, {method: "post",action: path.to.stockTransferLineQuantity(id),@@ -118,6 +313,10 @@ export default function StockTransferLines() {formData.append("id", line.id!);formData.append("quantity", "0");formData.append("locationId", routeData?.stockTransfer?.locationId ?? "");+ const trackedEntityId = trackedEntitiesByLineId.get(line.id ?? "");+ if (trackedEntityId) {+ formData.append("trackedEntityId", trackedEntityId);+ }submit(formData, {method: "post",@@ -162,171 +361,27 @@ export default function StockTransferLines() {{lines.length === 0 ? (<Empty className="py-6" />) : (- lines.map((line, index) => {- const item = items.find((p) => p.id === line.itemId);- return (- <div- key={line.id}- className={cn(- "flex flex-col border-b p-6 gap-6",- index === lines.length - 1 && "border-none"- )}- >- <div className="flex justify-between items-center w-full">- <HStack spacing={4} className="w-1/2 justify-between">- <HStack spacing={4}>- <ItemThumbnail- size="md"- thumbnailPath={line.thumbnailPath}- type={(item?.type as "Part") ?? "Part"}- />- <VStack spacing={0} className="max-w-[380px] w-full">- <div className="w-full overflow-hidden">- <span className="text-sm font-medium truncate block w-full">- {item?.name}- </span>- <span className="text-xs text-muted-foreground truncate block w-full">- {item?.readableIdWithRevision}- </span>- </div>- <div className="mt-2">- <Enumerable- value={- unitsOfMeasure?.find(- (u) => u.value === line.unitOfMeasure- )?.label ?? null- }- />- </div>- </VStack>- </HStack>- <VStack- spacing={1}- className="text-center items-center"- >- <label className="text-xs text-muted-foreground">- Quantity- </label>- <span className="text-sm py-1.5">- {pickedQuantitiesById.get(line.id ?? "") ?? 0}/- {line.quantity ?? 0}- </span>- </VStack>- </HStack>- <div className="flex flex-grow items-center justify-between gap-8 pl-4 w-1/2">- <HStack- spacing={8}- className="text-center items-center"- >- {"fromShelfId" in line && (- <VStack- spacing={1}- className="text-center items-center"- >- <label className="text-xs text-muted-foreground">- From- </label>- <span className="text-sm py-1.5 whitespace-nowrap">- {line.fromShelfName ?? ""}- </span>- </VStack>- )}- {"toShelfId" in line && (- <VStack- spacing={1}- className="text-center items-center"- >- <label className="text-xs text-muted-foreground">- To- </label>- <span className="text-sm py-1.5 whitespace-nowrap">- {line.toShelfName ?? ""}- </span>- </VStack>- )}- </HStack>- <HStack spacing={1}>- {pickedQuantitiesById.get(line.id ?? "") ===- line.quantity ? (- <Button- variant="secondary"- isDisabled={- !isPickable ||- pendingQuantities?.some((q) => q.id === line.id)- }- isLoading={pendingQuantities?.some(- (q) => q.id === line.id- )}- leftIcon={<LuUndo2 />}- onClick={() => {- onUnpick(line);- }}- >- Unpick- </Button>- ) : (- <Button- isDisabled={- !isPickable ||- pendingQuantities?.some((q) => q.id === line.id)- }- isLoading={pendingQuantities?.some(- (q) => q.id === line.id- )}- leftIcon={<LuCircleCheck />}- onClick={() => {- onPick(line);- }}- >- Pick- </Button>- )}- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- variant="secondary"- isDisabled={!isEditable}- icon={<LuEllipsisVertical />}- aria-label="Line options"- />- </DropdownMenuTrigger>- <DropdownMenuContent>- <DropdownMenuItem- disabled={- !isEditable ||- !permissions.can("update", "inventory")- }- asChild- >- <Link- to={path.to.stockTransferLine(id, line.id!)}- >- <DropdownMenuIcon icon={<LuPencilLine />} />- Edit Line- </Link>- </DropdownMenuItem>- <DropdownMenuItem- disabled={- !isEditable ||- !permissions.can("delete", "inventory")- }- destructive- onClick={() => {- setSelectedLine(line);- deleteDisclosure.onOpen();- }}- >- <DropdownMenuIcon icon={<LuTrash />} />- Delete Line- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </HStack>- </div>- </div>- </div>- );- })+ lines.map((line, index) => (+ <StockTransferLineComponent+ key={line.id}+ line={line}+ index={index}+ totalLines={lines.length}+ pickedQuantity={pickedQuantitiesById.get(line.id ?? "") ?? 0}+ isPickable={isPickable}+ isEditable={isEditable}+ isPending={+ pendingQuantities?.some((q) => q.id === line.id) ?? false+ }+ onPick={onPick}+ onUnpick={onUnpick}+ onDelete={() => {+ setSelectedLine(line);+ deleteDisclosure.onOpen();+ }}+ permissions={permissions}+ />+ )))}</div></CardContent>diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsxindex e034d0bfd4..2c38ac65ec 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx@@ -95,6 +95,7 @@ import {removeTransferLine,toggleToItemShelfSelection,updateTransferLineQuantity,+ useItems,usePeople,useStockTransferWizard,useStockTransferWizardLinesCount,@@ -283,7 +284,7 @@ const StockTransfersTable = memo(disabled={!permissions.can("delete", "inventory") ||!!row.completedAt ||- row.status === "Completed"+ ["Completed", "In Progress"].includes(row.status)}destructiveonClick={() => {@@ -327,7 +328,10 @@ const StockTransfersTable = memo(/>{permissions.can("create", "inventory") && (<Button- onClick={wizardDisclosure.onOpen}+ onClick={() => {+ clearStockTransferWizard();+ wizardDisclosure.onOpen();+ }}leftIcon={<LuCirclePlus />}>Add Stock Transfer@@ -656,11 +660,13 @@ function TransferGrid({ locationId }: { locationId: string }) {{accessorKey: "quantityOnHand",cell: ({ row }) => {- // Calculate total quantity being transferred to this shelf- const transferLinesToThisShelf = wizard.lines.filter(- (line) => line.toShelfId === row.original.shelfId+ // Calculate total quantity being transferred to this specific item/shelf combination+ const transferLinesToThisItemShelf = wizard.lines.filter(+ (line) =>+ line.itemId === row.original.itemId &&+ line.toShelfId === row.original.shelfId);- const totalTransferQuantity = transferLinesToThisShelf.reduce(+ const totalTransferQuantity = transferLinesToThisItemShelf.reduce((sum, line) => sum + (line.quantity ?? 0),0);@@ -697,11 +703,13 @@ function TransferGrid({ locationId }: { locationId: string }) {{accessorKey: "quantityAvailable",cell: ({ row }) => {- // Calculate total quantity being transferred to this shelf- const transferLinesToThisShelf = wizard.lines.filter(- (line) => line.toShelfId === row.original.shelfId+ // Calculate total quantity being transferred to this specific item/shelf combination+ const transferLinesToThisItemShelf = wizard.lines.filter(+ (line) =>+ line.itemId === row.original.itemId &&+ line.toShelfId === row.original.shelfId);- const totalTransferQuantity = transferLinesToThisShelf.reduce(+ const totalTransferQuantity = transferLinesToThisItemShelf.reduce((sum, line) => sum + (line.quantity ?? 0),0);@@ -802,6 +810,8 @@ function TransferGrid({ locationId }: { locationId: string }) {];}, [formatter, wizard.lines]);+ const [items] = useItems();+const columnsFrom = useMemo<ColumnDef<TransferTableRow>[]>(() => {return [{@@ -849,6 +859,12 @@ function TransferGrid({ locationId }: { locationId: string }) {row.original.quantityAvailable);+ const item = items.find(+ (item) => item.id === row.original.itemId+ );++ const trackingType = item?.itemTrackingType ?? "Inventory";+addTransferLine({itemId: row.original.itemId,itemReadableId: row.original.itemReadableId,@@ -860,6 +876,8 @@ function TransferGrid({ locationId }: { locationId: string }) {toShelfName: toItem.shelfName!,quantityAvailable: row.original.quantityAvailable,quantity: defaultQuantity,+ requiresSerialTracking: trackingType === "Serial",+ requiresBatchTracking: trackingType === "Batch",});}}}@@ -911,6 +929,7 @@ function TransferGrid({ locationId }: { locationId: string }) {Math.max(0, value),row.original.quantityAvailable);+updateTransferLineQuantity(row.original.itemId,row.original.shelfId!,@@ -1088,10 +1107,11 @@ function TransferGrid({ locationId }: { locationId: string }) {},];}, [- formatter,allTransferToData,wizard.selectedToItemShelfIds,wizard.lines,+ items,+ formatter,]);return (@@ -1449,10 +1469,6 @@ const StockTransferWizardWidget = ({ locationId }: { locationId: string }) => {removeTransferLine(itemId, fromShelfId, toShelfId);};- const onClearAll = () => {- clearStockTransferWizard();- };-if (linesCount === 0) {return null;}@@ -1613,7 +1629,11 @@ const StockTransferWizardWidget = ({ locationId }: { locationId: string }) => {Create Transfer</Button></fetcher.Form>- <Button variant="ghost" className="w-full" onClick={onClearAll}>+ <Button+ variant="ghost"+ className="w-full"+ onClick={clearStockTransferWizard}+ >Clear All</Button></div>diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsxindex f50dd83cf6..7c8118b3d2 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx@@ -677,7 +677,7 @@ function MaterialForm({kit: false,requiresBatchTracking: false,requiresSerialTracking: false,- shelfId: undefined,+ shelfId: "",});};@@ -721,7 +721,7 @@ function MaterialForm({methodType: item.data?.defaultMethodType ?? "Buy",requiresBatchTracking: item.data?.itemTrackingType === "Batch",requiresSerialTracking: item.data?.itemTrackingType === "Serial",- shelfId: pickMethod.data?.defaultShelfId ?? undefined,+ shelfId: pickMethod.data?.defaultShelfId ?? "",}));if (item.data?.type) {@@ -881,6 +881,13 @@ function MaterialForm({<Shelfname="shelfId"label="Shelf"+ value={itemData.shelfId}+ onChange={(value) => {+ setItemData((d) => ({+ ...d,+ shelfId: value?.id ?? "",+ }));+ }}locationId={locationId}itemId={itemData.itemId}/>diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex f4bb32ba3c..820d1f64ba 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -375,7 +375,6 @@ export async function insertCompany(company: z.infer<typeof companyValidator>,ownerId?: string) {- console.log("inserting company", company);return client.from("company").insert({ ...company, ownerId })diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsxindex 525dad643f..44004f9286 100644--- a/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx@@ -1,13 +1,6 @@-import {- assertIsPost,- error,- getCarbonServiceRole,- notFound,- success,-} from "@carbon/auth";+import { assertIsPost, error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import type { Database } from "@carbon/database";import type { ActionFunctionArgs } from "@vercel/remix";import { json } from "@vercel/remix";@@ -25,6 +18,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const lineId = formData.get("id") as string;const pickedQuantity = parseInt(formData.get("quantity") as string, 10);const locationId = formData.get("locationId") as string;+ const trackedEntityId = formData.get("trackedEntityId") as string | undefined;if (!lineId || !Number.isFinite(pickedQuantity)) {return json(@@ -53,81 +47,62 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =- [];-- const today = new Date().toISOString().split("T")[0];- const transactionQuantity =- pickedQuantity === 0- ? -stockTransferLine.data.pickedQuantity- : pickedQuantity;-- itemLedgerInserts.push({- postingDate: today,- itemId: stockTransferLine.data.itemId,- quantity: transactionQuantity,- locationId: locationId,- shelfId: stockTransferLine.data.toShelfId,- entryType: "Transfer",- documentType: "Direct Transfer",- documentId: stockTransferLine.data.stockTransferId ?? undefined,- createdBy: userId,- companyId,- });-- itemLedgerInserts.push({- postingDate: today,- itemId: stockTransferLine.data.itemId,- quantity: -transactionQuantity,- locationId: locationId,- shelfId: stockTransferLine.data.fromShelfId,- entryType: "Transfer",- documentType: "Direct Transfer",- documentId: stockTransferLine.data.stockTransferId ?? undefined,- createdBy: userId,- companyId,- });-- const serviceRole = getCarbonServiceRole();-- const insertItemTransactions = await serviceRole- .from("itemLedger")- .insert(itemLedgerInserts)- .select("id");+ let type = "inventory";+ if (pickedQuantity === 0) {+ if (stockTransferLine.data.requiresSerialTracking) {+ type = "unpickSerial";+ } else if (stockTransferLine.data.requiresBatchTracking) {+ type = "unpickBatch";+ } else {+ type = "unpickInventory";+ }+ }- if (insertItemTransactions.error) {+ if (+ !trackedEntityId &&+ (stockTransferLine.data.requiresSerialTracking ||+ stockTransferLine.data.requiresBatchTracking)+ ) {return json({success: false,},await flash(request,- error(insertItemTransactions.error, "Failed to insert item ledger")+ error("Tracked entity not found", "Tracked entity not found")));}- const quantityUpdate = await client- .from("stockTransferLine")- .update({- pickedQuantity,- updatedBy: userId,- updatedAt: new Date().toISOString(),- })- .eq("id", lineId)- .eq("companyId", companyId);-- if (quantityUpdate.error) {- await serviceRole- .from("itemLedger")- .delete()- .in("id", insertItemTransactions.data?.map((item) => item.id) ?? []);+ // Call the post-stock-transfer function for inventory items+ const { error: functionError } = await client.functions.invoke(+ "post-stock-transfer",+ {+ body: JSON.stringify({+ type: type,+ stockTransferId: stockTransferLine.data.stockTransferId,+ stockTransferLineId: lineId,+ quantity: pickedQuantity,+ locationId: locationId,+ trackedEntityId: trackedEntityId,+ userId,+ companyId,+ }),+ }+ );+ if (functionError) {return json({success: false,},- await flash(request, error(quantityUpdate.error, "Failed to update line"))+ await flash(+ request,+ error(+ functionError.message || "Failed to pick line",+ "Failed to pick line"+ )+ ));}diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsxnew file mode 100644index 0000000000..a3da1168a9--- /dev/null+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx@@ -0,0 +1,349 @@+import type { Result } from "@carbon/auth";+import { error, success, useCarbon } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { Hidden, ValidatedForm } from "@carbon/form";+import {+ Alert,+ AlertTitle,+ Button,+ cn,+ Input,+ InputGroup,+ InputRightElement,+ Modal,+ ModalBody,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalTitle,+ toast,+} from "@carbon/react";+import { useFetcher, useLoaderData, useNavigate } from "@remix-run/react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";+import { useEffect, useState } from "react";+import {+ LuCheck,+ LuCircleCheck,+ LuQrCode,+ LuTriangleAlert,+ LuX,+} from "react-icons/lu";+import { useRouteData } from "~/hooks";+import type { StockTransfer } from "~/modules/inventory";+import {+ getStockTransferLine,+ stockTransferLineScanValidator,+} from "~/modules/inventory";+import { getItemShelfQuantities } from "~/modules/items";+import { path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "inventory",+ });+ const { id, lineId } = params;+ if (!id) throw new Error("id not found");+ if (!lineId) throw new Error("lineId not found");++ const stockTransferLine = await getStockTransferLine(client, lineId);+ if (stockTransferLine.error) {+ throw redirect(+ path.to.stockTransfer(id),+ await flash(+ request,+ error(stockTransferLine.error, "Failed to load stock transfer line")+ )+ );+ }++ return json({ stockTransferLine: stockTransferLine.data });+}++export async function action({ request }: ActionFunctionArgs) {+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "inventory",+ });++ const payload = await request.json();+ const validated = stockTransferLineScanValidator.safeParse(payload);+ if (!validated.success) {+ return json(+ { success: false, message: "Invalid form data" },+ await flash(request, error(validated.error.message, "Invalid form data"))+ );+ }++ const { id, stockTransferId, itemId, locationId, trackedEntityId } =+ validated.data;++ const [stockTransferLine, itemShelfQuantities] = await Promise.all([+ client.from("stockTransferLines").select("*").eq("id", id!).single(),+ getItemShelfQuantities(client, itemId, companyId, locationId),+ ]);++ if (stockTransferLine.error || itemShelfQuantities.error) {+ return json(+ {+ success: false,+ message: "Failed to load stock transfer line or item shelf quantities",+ },+ await flash(+ request,+ error(+ stockTransferLine.error || itemShelfQuantities.error,+ "Failed to load stock transfer line or item shelf quantities"+ )+ )+ );+ }++ const currentShelfId =+ itemShelfQuantities.data+ ?.sort((a, b) => b.quantity - a.quantity)+ .find((q) => q.trackedEntityId === trackedEntityId)?.shelfId ?? null;++ // Determine the type of transfer based on tracking requirements+ const transferType = stockTransferLine.data?.requiresBatchTracking+ ? "batch"+ : "serial";++ // Prepare the payload for the post-stock-transfer function+ const functionPayload: any = {+ type: transferType,+ stockTransferId,+ stockTransferLineId: id,+ trackedEntityId,+ quantity:+ transferType === "batch" ? stockTransferLine.data?.quantity ?? 1 : 1,+ fromShelfId: currentShelfId,+ locationId: locationId,+ userId,+ companyId,+ };++ const { error: functionError } = await client.functions.invoke(+ "post-stock-transfer",+ {+ body: JSON.stringify(functionPayload),+ }+ );++ if (functionError) {+ return json(+ { success: false, message: "Failed to pick line" },+ await flash(+ request,+ error(+ functionError.message || "Failed to pick line",+ "Failed to pick line"+ )+ )+ );+ }++ throw redirect(+ path.to.stockTransfer(stockTransferId),+ await flash(request, success("Tracked entity scanned and transferred"))+ );+}++export default function StockTransferScan() {+ const { stockTransferLine } = useLoaderData<typeof loader>();+ const navigate = useNavigate();+ const onClose = () =>+ navigate(path.to.stockTransfer(stockTransferLine.stockTransferId!));++ const { carbon } = useCarbon();+ const [isLoading, setIsLoading] = useState(false);+ const [validationError, setValidationError] = useState<string | null>(null);+ const [isValid, setIsValid] = useState<boolean | null>(null);+ const [serialNumber, setSerialNumber] = useState("");++ const fetcher = useFetcher<Result>();++ useEffect(() => {+ if (fetcher.data?.success === false) {+ toast.error(fetcher.data.message);+ }+ }, [fetcher.data?.message, fetcher.data?.success]);++ const locationId =+ useRouteData<{+ stockTransfer: StockTransfer;+ }>(path.to.stockTransfer(stockTransferLine.stockTransferId!))?.stockTransfer+ .locationId ?? "";++ const onPick = (trackedEntityId?: string) => {+ fetcher.submit(+ {+ id: stockTransferLine.id!,+ stockTransferId: stockTransferLine.stockTransferId!,+ trackedEntityId: trackedEntityId!,+ itemId: stockTransferLine.itemId!,+ locationId: locationId,+ },+ {+ method: "POST",+ encType: "application/json",+ }+ );+ };++ const validateTrackedEntity = async (trackedEntityId: string) => {+ if (!trackedEntityId.trim()) {+ setValidationError(null);+ setIsValid(null);+ return;+ }++ setIsLoading(true);+ setValidationError(null);+ setIsValid(null);++ try {+ const result = await carbon+ ?.from("trackedEntity")+ .select("*")+ .eq("id", trackedEntityId)+ .eq("companyId", stockTransferLine.companyId!)+ .single();++ if (result?.error || !result?.data) {+ setValidationError("Serial number not found");+ setIsValid(false);+ } else if (result.data.status !== "Available") {+ setValidationError(`Entity is ${result.data.status}`);+ setIsValid(false);+ } else if (result.data.sourceDocumentId !== stockTransferLine.itemId!) {+ setValidationError(+ `Item ${result.data.sourceDocumentReadableId} is not the same as the item ${stockTransferLine.itemReadableId}`+ );+ setIsValid(false);+ } else {+ setValidationError(null);+ setIsValid(true);+ onPick(trackedEntityId);+ }+ } catch (error) {+ setValidationError("Error validating serial number");+ setIsValid(false);+ } finally {+ setIsLoading(false);+ }+ };++ const handleSerialNumberChange = (value: string) => {+ setSerialNumber(value);+ // Clear validation state when user types+ if (validationError || isValid !== null) {+ setValidationError(null);+ setIsValid(null);+ }+ };++ const handleBlur = () => {+ validateTrackedEntity(serialNumber);+ };++ const handleKeyDown = (event: React.KeyboardEvent) => {+ if (event.key === "Enter") {+ event.preventDefault();+ validateTrackedEntity(serialNumber);+ }+ };++ return (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) {+ onClose();+ }+ }}+ >+ <ValidatedForm+ method="post"+ validator={stockTransferLineScanValidator}+ defaultValues={{+ id: stockTransferLine.id!,+ stockTransferId: stockTransferLine.stockTransferId!,+ itemId: stockTransferLine.itemId!,+ locationId: locationId,+ trackedEntityId: "",+ }}+ >+ <ModalContent>+ <ModalHeader>+ <ModalTitle>{stockTransferLine?.itemReadableId}</ModalTitle>+ <ModalDescription>+ Scan the tracking ID for this line+ </ModalDescription>+ </ModalHeader>+ <ModalBody>+ <Hidden name="id" />+ <Hidden name="stockTransferId" />+ <Hidden name="itemId" />+ <Hidden name="locationId" />++ <div className="space-y-4">+ {validationError && (+ <Alert variant="destructive">+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>{validationError}</AlertTitle>+ </Alert>+ )}+ <InputGroup>+ <Input+ name="trackedEntityId"+ value={serialNumber}+ isDisabled={fetcher.state !== "idle"}+ onChange={(e) => handleSerialNumberChange(e.target.value)}+ onBlur={handleBlur}+ onKeyDown={handleKeyDown}+ autoFocus+ placeholder="Enter or scan serial number"+ className={cn(+ validationError && "border-destructive",+ isValid && "border-emerald-500"+ )}+ disabled={isLoading}+ />+ <InputRightElement className="pl-2">+ {isLoading ? (+ <div className="animate-spin h-4 w-4 border-2 border-gray-300 border-t-gray-600 rounded-full" />+ ) : validationError ? (+ <LuX className="text-destructive" />+ ) : isValid ? (+ <LuCheck className="text-emerald-500" />+ ) : (+ <LuQrCode />+ )}+ </InputRightElement>+ </InputGroup>+ </div>+ </ModalBody>+ <ModalFooter>+ <Button+ variant="secondary"+ isDisabled={fetcher.state !== "idle"}+ onClick={() => onClose()}+ >+ Cancel+ </Button>+ <Button+ leftIcon={<LuCircleCheck />}+ isLoading={fetcher.state !== "idle"}+ isDisabled={fetcher.state !== "idle"}+ onClick={() => validateTrackedEntity(serialNumber)}+ >+ Pick+ </Button>+ </ModalFooter>+ </ModalContent>+ </ValidatedForm>+ </Modal>+ );+}diff --git a/apps/erp/app/routes/x+/stock-transfer+/new.tsx b/apps/erp/app/routes/x+/stock-transfer+/new.tsxindex 04e7e74200..989c9592d1 100644--- a/apps/erp/app/routes/x+/stock-transfer+/new.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/new.tsx@@ -49,6 +49,30 @@ export async function action({ request }: ActionFunctionArgs) {const { locationId, lines } = validation.data;+ const linesWithExpandedSerialTracking = lines.reduce<typeof lines>(+ (acc, line) => {+ // If quantity contains a decimal, ignore the line (as per requirements)+ if (line.quantity && !Number.isInteger(line.quantity)) {+ return acc;+ }++ // If item requires serial tracking and quantity is a whole number > 1+ if (line.requiresSerialTracking && line.quantity && line.quantity > 1) {+ // Break out into multiple lines with quantity 1+ acc.push(+ ...Array.from({ length: line.quantity }, () => ({+ ...line,+ quantity: 1,+ }))+ );+ } else {+ acc.push(line);+ }+ return acc;+ },+ []+ );+const createStockTransfer = await upsertStockTransfer(client, {stockTransferId: nextSequence.data,locationId,@@ -68,7 +92,7 @@ export async function action({ request }: ActionFunctionArgs) {}const createStockTransferLines = await upsertStockTransferLines(client, {- lines,+ lines: linesWithExpandedSerialTracking,stockTransferId: createStockTransfer.data.id,companyId,createdBy: userId,diff --git a/apps/erp/app/stores/stock-transfer.ts b/apps/erp/app/stores/stock-transfer.tsindex 79586d948b..a49cfe1158 100644--- a/apps/erp/app/stores/stock-transfer.ts+++ b/apps/erp/app/stores/stock-transfer.ts@@ -8,6 +8,8 @@ export type StockTransferSessionItem = {description: string;action: "order" | "transfer";quantity?: number;+ requiresSerialTracking: boolean;+ requiresBatchTracking: boolean;};export type StockTransferSessionState = {@@ -99,6 +101,8 @@ export type StockTransferWizardLine = {toShelfName: string;quantityAvailable: number;quantity?: number;+ requiresSerialTracking: boolean;+ requiresBatchTracking: boolean;};export type StockTransferWizardState = {diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex b496040d46..db678269d8 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -19,14 +19,7 @@ export const path = {assign: `${api}/assign`,batchNumbers: (itemId: string) =>generatePath(`${api}/inventory/batch-numbers?itemId=${itemId}`),- trackedEntitiesByShelf: (- itemId: string,- shelfId: string,- locationId: string- ) =>- generatePath(- `${api}/inventory/tracked-entities-by-shelf?itemId=${itemId}&shelfId=${shelfId}&locationId=${locationId}`- ),+billOfMaterials: (methodId: string, withOperations: boolean = false) =>generatePath(`${api}/items/methods/${methodId}/bom?withOperations=${withOperations}`@@ -1084,6 +1077,8 @@ export const path = {generatePath(`${x}/stock-transfer/${id}/line/${lineId}`),stockTransferLineQuantity: (id: string) =>generatePath(`${x}/stock-transfer/${id}/line/quantity`),+ stockTransferScan: (id: string, lineId: string) =>+ generatePath(`${x}/stock-transfer/${id}/scan/${lineId}`),stockTransferStatus: (id: string) =>generatePath(`${x}/stock-transfer/${id}/status`),stockTransfers: `${x}/inventory/stock-transfers`,diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 313b32a183..87efcd8708 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -23394,6 +23394,9 @@ export default {{$ref: "#/parameters/rowFilter.stockTransferLines.itemReadableId",},+ {+ $ref: "#/parameters/rowFilter.stockTransferLines.itemDescription",+ },{$ref: "#/parameters/rowFilter.stockTransferLines.unitOfMeasure",},@@ -72651,6 +72654,10 @@ export default {format: "text",type: "string",},+ itemDescription: {+ format: "text",+ type: "string",+ },unitOfMeasure: {format: "text",type: "string",@@ -100717,6 +100724,12 @@ export default {in: "query",type: "string",},+ "rowFilter.stockTransferLines.itemDescription": {+ name: "itemDescription",+ required: false,+ in: "query",+ type: "string",+ },"rowFilter.stockTransferLines.unitOfMeasure": {name: "unitOfMeasure",required: false,diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex c0e913c3df..e291a0d433 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -45425,14 +45425,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.tomlindex 99a5440a5a..c40640dac4 100644--- a/packages/database/supabase/config.toml+++ b/packages/database/supabase/config.toml@@ -155,3 +155,14 @@ entrypoint = "./functions/pick/index.ts"# Specifies static files to be bundled with the function. Supports glob patterns.# For example, if you want to serve static HTML pages in your function:# static_files = [ "./functions/pick/*.html" ]++[functions.post-stock-transfer]+enabled = true+verify_jwt = true+import_map = "./functions/post-stock-transfer/deno.json"+# Uncomment to specify a custom file path to the entrypoint.+# Supported file extensions are: .ts, .js, .mjs, .jsx, .tsx+entrypoint = "./functions/post-stock-transfer/index.ts"+# Specifies static files to be bundled with the function. Supports glob patterns.+# For example, if you want to serve static HTML pages in your function:+# static_files = [ "./functions/post-stock-transfer/*.html" ]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex c0e913c3df..e291a0d433 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -45425,14 +45425,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/post-stock-transfer/.npmrc b/packages/database/supabase/functions/post-stock-transfer/.npmrcnew file mode 100644index 0000000000..48c6388638--- /dev/null+++ b/packages/database/supabase/functions/post-stock-transfer/.npmrc@@ -0,0 +1,3 @@+# Configuration for private npm package dependencies+# For more information on using private registries with Edge Functions, see:+# https://supabase.com/docs/guides/functions/import-maps#importing-from-private-registriesdiff --git a/packages/database/supabase/functions/post-stock-transfer/deno.json b/packages/database/supabase/functions/post-stock-transfer/deno.jsonnew file mode 100644index 0000000000..f6ca8454c5--- /dev/null+++ b/packages/database/supabase/functions/post-stock-transfer/deno.json@@ -0,0 +1,3 @@+{+ "imports": {}+}diff --git a/packages/database/supabase/functions/post-stock-transfer/index.ts b/packages/database/supabase/functions/post-stock-transfer/index.tsnew file mode 100644index 0000000000..505271e086--- /dev/null+++ b/packages/database/supabase/functions/post-stock-transfer/index.ts@@ -0,0 +1,1003 @@+import { serve } from "https://deno.land/[email protected]/http/server.ts";+import { format } from "https://deno.land/[email protected]/datetime/mod.ts";+import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";+import { z } from "https://deno.land/x/[email protected]/mod.ts";+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { corsHeaders } from "../lib/headers.ts";+import type { Database } from "../lib/types.ts";++const pool = getConnectionPool(1);+const db = getDatabaseClient<DB>(pool);++const payloadValidator = z.discriminatedUnion("type", [+ z.object({+ type: z.literal("inventory"),+ stockTransferId: z.string(),+ stockTransferLineId: z.string(),+ quantity: z.number().positive(),+ locationId: z.string(),+ userId: z.string(),+ companyId: z.string(),+ }),+ z.object({+ type: z.literal("unpickInventory"),+ stockTransferId: z.string(),+ stockTransferLineId: z.string(),+ locationId: z.string(),+ userId: z.string(),+ companyId: z.string(),+ }),+ z.object({+ type: z.literal("serial"),+ stockTransferId: z.string(),+ stockTransferLineId: z.string(),+ trackedEntityId: z.string(),+ fromShelfId: z.string().nullable(),+ locationId: z.string(),+ userId: z.string(),+ companyId: z.string(),+ }),+ z.object({+ type: z.literal("batch"),+ stockTransferId: z.string(),+ stockTransferLineId: z.string(),+ trackedEntityId: z.string(),+ fromShelfId: z.string().nullable(),+ quantity: z.number().positive(),+ locationId: z.string(),+ userId: z.string(),+ companyId: z.string(),+ }),+ z.object({+ type: z.literal("unpickSerial"),+ stockTransferId: z.string(),+ stockTransferLineId: z.string(),+ trackedEntityId: z.string(),+ locationId: z.string(),+ userId: z.string(),+ companyId: z.string(),+ }),+ z.object({+ type: z.literal("unpickBatch"),+ stockTransferId: z.string(),+ stockTransferLineId: z.string(),+ trackedEntityId: z.string(),+ locationId: z.string(),+ userId: z.string(),+ companyId: z.string(),+ }),+]);++serve(async (req: Request) => {+ if (req.method === "OPTIONS") {+ return new Response("ok", { headers: corsHeaders });+ }++ const payload = await req.json();+ const today = format(new Date(), "yyyy-MM-dd");++ try {+ const validatedPayload = payloadValidator.parse(payload);++ console.log({+ function: "post-stock-transfer",+ ...validatedPayload,+ });++ switch (validatedPayload.type) {+ case "inventory": {+ const {+ stockTransferId,+ stockTransferLineId,+ quantity,+ locationId,+ userId,+ companyId,+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Get stock transfer line details+ const stockTransferLine = await trx+ .selectFrom("stockTransferLine")+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ // Create item ledger entries for inventory transfer+ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: -quantity,+ locationId: locationId,+ shelfId: stockTransferLine.fromShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ createdBy: userId,+ companyId,+ });++ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: quantity,+ locationId: locationId,+ shelfId: stockTransferLine.toShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ createdBy: userId,+ companyId,+ });++ // Insert item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ // Update stock transfer line with picked quantity+ await trx+ .updateTable("stockTransferLine")+ .set({+ pickedQuantity:+ (stockTransferLine.pickedQuantity ?? 0) + quantity,+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ })+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "unpickInventory": {+ const {+ stockTransferId,+ stockTransferLineId,+ locationId,+ userId,+ companyId,+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Get stock transfer line details+ const stockTransferLine = await trx+ .selectFrom("stockTransferLine")+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ const currentPickedQuantity = stockTransferLine.pickedQuantity ?? 0;++ if (currentPickedQuantity > 0) {+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ // Create reverse item ledger entries to undo the transfer+ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: currentPickedQuantity, // Positive to restore inventory at from shelf+ locationId: locationId,+ shelfId: stockTransferLine.fromShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ createdBy: userId,+ companyId,+ });++ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: -currentPickedQuantity, // Negative to remove inventory from to shelf+ locationId: locationId,+ shelfId: stockTransferLine.toShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ createdBy: userId,+ companyId,+ });++ // Insert reverse item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }+ }++ // Reset picked quantity to 0+ await trx+ .updateTable("stockTransferLine")+ .set({+ pickedQuantity: 0,+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ })+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "serial": {+ const {+ fromShelfId,+ stockTransferId,+ stockTransferLineId,+ trackedEntityId,+ locationId,+ userId,+ companyId,+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Get stock transfer line details+ const stockTransferLine = await trx+ .selectFrom("stockTransferLine")+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ // Create transfer activity+ const transferActivityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: transferActivityId,+ type: "Transfer",+ sourceDocument: "Stock Transfer",+ sourceDocumentId: stockTransferId,+ attributes: {+ "Stock Transfer": stockTransferId,+ "Stock Transfer Line": stockTransferLineId,+ "From Location": locationId,+ "To Location": locationId,+ "From Shelf": stockTransferLine.fromShelfId,+ "To Shelf": stockTransferLine.toShelfId,+ },+ companyId,+ createdBy: userId,+ })+ .execute();++ // Record tracked entity as input to transfer+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: transferActivityId,+ trackedEntityId: trackedEntityId,+ quantity: 1,+ companyId,+ createdBy: userId,+ })+ .execute();++ // Create item ledger entries for transfer+ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: -1,+ locationId: locationId,+ shelfId: fromShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId,+ });++ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: 1,+ locationId: locationId,+ shelfId: stockTransferLine.toShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId,+ });++ // Insert item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ // Update stock transfer line with picked quantity+ await trx+ .updateTable("stockTransferLine")+ .set({+ fromShelfId: fromShelfId,+ pickedQuantity: (stockTransferLine.pickedQuantity ?? 0) + 1,+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ })+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "batch": {+ const {+ fromShelfId,+ stockTransferId,+ stockTransferLineId,+ trackedEntityId,+ quantity,+ locationId,+ userId,+ companyId,+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Get stock transfer line details+ const stockTransferLine = await trx+ .selectFrom("stockTransferLine")+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ // Get tracked entity details+ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ const entityQuantity = Number(trackedEntity.quantity);+ const transferQuantity = quantity;+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ // Handle batch splitting if needed+ if (entityQuantity !== transferQuantity) {+ // Need to split the batch+ const remainingQuantity = entityQuantity - transferQuantity;+ const newTrackedEntityId = nanoid();++ // Create split activity+ const splitActivityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: splitActivityId,+ type: "Split",+ sourceDocument: "Stock Transfer",+ sourceDocumentId: stockTransferId,+ attributes: {+ "Original Quantity": entityQuantity,+ "Transfer Quantity": transferQuantity,+ "Remaining Quantity": remainingQuantity,+ "Split Entity ID": newTrackedEntityId,+ },+ companyId,+ createdBy: userId,+ })+ .execute();++ // Record original entity as input to split+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: splitActivityId,+ trackedEntityId: trackedEntityId,+ quantity: entityQuantity,+ companyId,+ createdBy: userId,+ })+ .execute();++ // Create new tracked entity for remaining quantity+ await trx+ .insertInto("trackedEntity")+ .values({+ id: newTrackedEntityId,+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId:+ trackedEntity.sourceDocumentReadableId,+ quantity: remainingQuantity,+ status: "Available",+ attributes: trackedEntity.attributes,+ companyId,+ createdBy: userId,+ })+ .execute();++ // Record outputs from split+ await trx+ .insertInto("trackedActivityOutput")+ .values([+ {+ trackedActivityId: splitActivityId,+ trackedEntityId: newTrackedEntityId,+ quantity: remainingQuantity,+ companyId,+ createdBy: userId,+ },+ {+ trackedActivityId: splitActivityId,+ trackedEntityId: trackedEntityId,+ quantity: transferQuantity,+ companyId,+ createdBy: userId,+ },+ ])+ .execute();++ // Update original entity with split reference and new quantity+ await trx+ .updateTable("trackedEntity")+ .set({+ quantity: transferQuantity,+ attributes: {+ ...(trackedEntity.attributes as Record<string, unknown>),+ "Split Entity ID": newTrackedEntityId,+ },+ })+ .where("id", "=", trackedEntityId)+ .execute();++ // Create item ledger entries for split+ itemLedgerInserts.push(+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: -entityQuantity,+ locationId: locationId,+ shelfId: fromShelfId,+ entryType: "Negative Adjmt.",+ documentType: "Batch Split",+ documentId: splitActivityId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId,+ },+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: transferQuantity,+ locationId: locationId,+ shelfId: fromShelfId,+ entryType: "Positive Adjmt.",+ documentType: "Batch Split",+ documentId: splitActivityId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId,+ },+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: remainingQuantity,+ locationId: locationId,+ shelfId: fromShelfId,+ entryType: "Positive Adjmt.",+ documentType: "Batch Split",+ documentId: splitActivityId,+ trackedEntityId: newTrackedEntityId,+ createdBy: userId,+ companyId,+ }+ );+ }++ // Create transfer activity+ const transferActivityId = nanoid();+ await trx+ .insertInto("trackedActivity")+ .values({+ id: transferActivityId,+ type: "Transfer",+ sourceDocument: "Stock Transfer",+ sourceDocumentId: stockTransferId,+ attributes: {+ "Stock Transfer": stockTransferId,+ "Stock Transfer Line": stockTransferLineId,+ "From Location": locationId,+ "To Location": locationId,+ "From Shelf": stockTransferLine.fromShelfId,+ "To Shelf": stockTransferLine.toShelfId,+ },+ companyId,+ createdBy: userId,+ })+ .execute();++ // Record tracked entity as input to transfer+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: transferActivityId,+ trackedEntityId: trackedEntityId,+ quantity: transferQuantity,+ companyId,+ createdBy: userId,+ })+ .execute();++ // Update tracked entity status to consumed+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Consumed",+ })+ .where("id", "=", trackedEntityId)+ .execute();++ // Create item ledger entries for transfer+ itemLedgerInserts.push(+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: -transferQuantity,+ locationId: locationId,+ shelfId: fromShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId,+ },+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: transferQuantity,+ locationId: locationId,+ shelfId: stockTransferLine.toShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId,+ }+ );++ // Insert item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ // Update stock transfer line with picked quantity+ await trx+ .updateTable("stockTransferLine")+ .set({+ fromShelfId: fromShelfId,+ pickedQuantity: transferQuantity,+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ })+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "unpickSerial": {+ const {+ stockTransferId,+ stockTransferLineId,+ trackedEntityId,+ locationId,+ userId,+ companyId,+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Get stock transfer line details+ const stockTransferLine = await trx+ .selectFrom("stockTransferLine")+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ // Get tracked entity details+ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ // Find the transfer activity for this tracked entity+ const transferActivity = await trx+ .selectFrom("trackedActivity")+ .innerJoin(+ "trackedActivityInput",+ "trackedActivity.id",+ "trackedActivityInput.trackedActivityId"+ )+ .where("trackedActivity.type", "=", "Transfer")+ .where("trackedActivity.sourceDocument", "=", "Stock Transfer")+ .where("trackedActivity.sourceDocumentId", "=", stockTransferId)+ .where("trackedActivityInput.trackedEntityId", "=", trackedEntityId)+ .where("trackedActivity.companyId", "=", companyId)+ .selectAll("trackedActivity")+ .executeTakeFirstOrThrow();++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ // Create reverse item ledger entries to undo the transfer+ // First, remove the entity from the destination shelf (toShelfId)+ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: -1, // Negative to remove inventory from to shelf+ locationId: locationId,+ shelfId: stockTransferLine.toShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId,+ });++ // Then, restore the entity to the source shelf (fromShelfId)+ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: 1, // Positive to restore inventory at from shelf+ locationId: locationId,+ shelfId: stockTransferLine.fromShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId,+ });++ // Insert reverse item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ // Delete the tracked activity and its related records+ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", transferActivity.id!)+ .execute();++ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", transferActivity.id!)+ .execute();++ // Update tracked entity status back to available and restore shelf location+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Available",+ attributes: {+ ...(trackedEntity.attributes as Record<string, unknown>),+ Shelf: stockTransferLine.fromShelfId,+ },+ })+ .where("id", "=", trackedEntityId)+ .execute();++ // Update stock transfer line with reduced picked quantity+ await trx+ .updateTable("stockTransferLine")+ .set({+ pickedQuantity: Math.max(+ 0,+ (stockTransferLine.pickedQuantity ?? 0) - 1+ ),+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ })+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }++ case "unpickBatch": {+ const {+ stockTransferId,+ stockTransferLineId,+ trackedEntityId,+ locationId,+ userId,+ companyId,+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ // Get stock transfer line details+ const stockTransferLine = await trx+ .selectFrom("stockTransferLine")+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ // Get tracked entity details+ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ // Find the transfer activity for this tracked entity+ const transferActivity = await trx+ .selectFrom("trackedActivity")+ .innerJoin(+ "trackedActivityInput",+ "trackedActivity.id",+ "trackedActivityInput.trackedActivityId"+ )+ .where("trackedActivity.type", "=", "Transfer")+ .where("trackedActivity.sourceDocument", "=", "Stock Transfer")+ .where("trackedActivity.sourceDocumentId", "=", stockTransferId)+ .where("trackedActivityInput.trackedEntityId", "=", trackedEntityId)+ .where("trackedActivity.companyId", "=", companyId)+ .selectAll("trackedActivity")+ .executeTakeFirstOrThrow();++ const transferQuantity = Number(trackedEntity.quantity);+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ // Check if this entity was created from a split operation+ const splitEntityId = (+ trackedEntity.attributes as Record<string, unknown>+ )?.["Split Entity ID"] as string | undefined;++ if (splitEntityId) {+ // This entity was created from a split, need to merge it back+ const originalEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", splitEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ const originalQuantity =+ Number(originalEntity.quantity) + transferQuantity;++ const remainingQuantity = (+ trackedEntity.attributes as Record<string, unknown>+ )?.["Remaining Quantity"] as number | undefined;++ // Find the split activity+ const splitActivity = await trx+ .selectFrom("trackedActivity")+ .where("type", "=", "Split")+ .where("sourceDocument", "=", "Stock Transfer")+ .where("sourceDocumentId", "=", stockTransferId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ // Update original entity with merged quantity and restore shelf location+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Consumed",+ quantity: 0,+ })+ .where("id", "=", splitEntityId)+ .execute();++ // Mark the split entity as consumed (don't delete it)+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Available",+ quantity: originalQuantity,+ })+ .where("id", "=", trackedEntityId)+ .execute();++ // Create item ledger entries for merge+ // Both entities are on the fromShelfId during the merge operation+ itemLedgerInserts.push(+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: originalQuantity, // zero out the split entity+ locationId: locationId,+ shelfId: stockTransferLine.fromShelfId,+ entryType: "Positive Adjmt.",+ documentType: "Direct Transfer",+ documentId: stockTransferId!,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId,+ },+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: -transferQuantity, // Positive to restore to original entity+ locationId: locationId,+ shelfId: stockTransferLine.toShelfId, // Both entities are on the source shelf+ entryType: "Negative Adjmt.",+ documentType: "Direct Transfer",+ documentId: stockTransferId!,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId,+ },+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: -(originalQuantity - transferQuantity), // Positive to restore to original entity+ locationId: locationId,+ shelfId: stockTransferLine.fromShelfId, // Both entities are on the source shelf+ entryType: "Negative Adjmt.",+ documentType: "Direct Transfer",+ documentId: stockTransferId!,+ trackedEntityId: splitEntityId,+ createdBy: userId,+ companyId,+ }+ );++ // Delete split activity records+ await trx+ .deleteFrom("trackedActivityOutput")+ .where("trackedActivityId", "=", splitActivity.id!)+ .execute();++ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", splitActivity.id!)+ .execute();++ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", splitActivity.id!)+ .execute();+ } else {+ // This was a direct transfer, just restore the entity and shelf location+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Available",+ attributes: {+ ...(trackedEntity.attributes as Record<string, unknown>),+ Shelf: stockTransferLine.fromShelfId,+ },+ })+ .where("id", "=", trackedEntityId)+ .execute();++ // Create reverse item ledger entries to undo the transfer+ // Use the correct trackedEntityId based on whether this was a split operation+ // For split operations, use the original entity (splitEntityId)+ // For direct operations, use the trackedEntityId+ const finalTrackedEntityId = splitEntityId || trackedEntityId;++ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: transferQuantity, // Positive to restore inventory at from shelf+ locationId: locationId,+ shelfId: stockTransferLine.fromShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: finalTrackedEntityId,+ createdBy: userId,+ companyId,+ });++ itemLedgerInserts.push({+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: -transferQuantity, // Negative to remove inventory from to shelf+ locationId: locationId,+ shelfId: stockTransferLine.toShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stockTransferId,+ trackedEntityId: finalTrackedEntityId,+ createdBy: userId,+ companyId,+ });+ }++ // Insert item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .execute();+ }++ // Delete the transfer activity and its related records+ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", transferActivity.id!)+ .execute();++ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", transferActivity.id!)+ .execute();++ // Update stock transfer line with reduced picked quantity+ await trx+ .updateTable("stockTransferLine")+ .set({+ pickedQuantity: Math.max(+ 0,+ (stockTransferLine.pickedQuantity ?? 0) - transferQuantity+ ),+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ })+ .where("id", "=", stockTransferLineId)+ .where("companyId", "=", companyId)+ .execute();+ });++ break;+ }+ }++ return new Response(+ JSON.stringify({+ success: true,+ }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 200,+ }+ );+ } catch (err) {+ console.error(err);+ return new Response(JSON.stringify(err), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 500,+ });+ }+});diff --git a/packages/react/src/Brackets.tsx b/packages/react/src/Brackets.tsxnew file mode 100644index 0000000000..d80415c587--- /dev/null+++ b/packages/react/src/Brackets.tsx@@ -0,0 +1,10 @@+export function Brackets() {+ return (+ <>+ <span className="absolute top-0 left-0 w-2 h-2 border-t-2 border-l-2 border-white pointer-events-none" />+ <span className="absolute top-0 right-0 w-2 h-2 border-t-2 border-r-2 border-white pointer-events-none" />+ <span className="absolute bottom-0 left-0 w-2 h-2 border-b-2 border-l-2 border-white pointer-events-none" />+ <span className="absolute bottom-0 right-0 w-2 h-2 border-b-2 border-r-2 border-white pointer-events-none" />+ </>+ );+}