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.

feat: add pagination and cart to stock transfer wizard

Brad Barbin6805175c5bbe
diff --git a/CLAUDE.md b/CLAUDE.md
index f1b575aa3e..0fe4662765 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -24,3 +24,4 @@ Rules for updating/writing to the FAQ:
- ALWAYS update the FAQ if you learn something about the codebase that was not in the FAQ and is not from a current change you're making (i.e. is committed).
- ALWAYS update the FAQ after a commit.
- NEVER update the FAQ about staged/uncommitted code.
+- NEVER rebuild the database to test changes. Wait for the user to do that.
diff --git a/apps/erp/app/components/Table/components/Pagination/Pagination.tsx b/apps/erp/app/components/Table/components/Pagination/Pagination.tsx
index 24077f6ba1..e01914efcd 100644
--- a/apps/erp/app/components/Table/components/Pagination/Pagination.tsx
+++ b/apps/erp/app/components/Table/components/Pagination/Pagination.tsx
@@ -1,6 +1,5 @@
import {
Button,
- cn,
DropdownMenu,
DropdownMenuContent,
DropdownMenuLabel,
@@ -47,10 +46,7 @@ const Pagination = (props: PaginationProps) => {
<>
<hr className="m-0 h-px w-full border-none bg-gradient-to-r from-zinc-200/0 via-zinc-500/30 to-zinc-200/0" />
<HStack
- className={cn(
- "text-center bg-card justify-between py-4 w-full z-[1]",
- compact ? "px-4" : "px-4 md:px-0"
- )}
+ className="text-center bg-card justify-between py-4 w-full z-[1] px-4"
spacing={6}
>
<DropdownMenu>
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.ts
index acad751776..02e07a3f5e 100644
--- a/apps/erp/app/modules/inventory/inventory.models.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.ts
@@ -278,9 +278,28 @@ export const stockTransferStatusType = [
export const stockTransferValidator = z.object({
id: zfd.text(z.string().optional()),
locationId: z.string().min(1, { message: "Location is required" }),
- status: z.enum(stockTransferStatusType).optional(),
- createdDate: zfd.text(z.string().optional()),
- completedDate: zfd.text(z.string().optional()),
+ lines: z.string().transform((val, ctx) => {
+ try {
+ const parsed = JSON.parse(val);
+ return z
+ .array(
+ z.object({
+ itemId: z.string().min(1, { message: "Item is required" }),
+ fromShelfId: z.string().optional(),
+ toShelfId: z.string().optional(),
+ quantity: z.number().min(0).optional(),
+ })
+ )
+ .min(1, { message: "At least one line is required" })
+ .parse(parsed);
+ } catch (e) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Invalid JSON format for lines",
+ });
+ return z.NEVER;
+ }
+ }),
});
export const stockTransferLineValidator = z.object({
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 30ca0bf546..6b3a78d3cd 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -240,6 +240,7 @@ export async function getStockTransfers(
companyId: string,
args: GenericQueryFilters & {
search: string | null;
+ locationId: string | null;
}
) {
let query = client
@@ -253,6 +254,10 @@ export async function getStockTransfers(
query = query.ilike("stockTransferId", `%${args.search}%`);
}
+ if (args.locationId) {
+ query = query.eq("locationId", args.locationId);
+ }
+
query = setGenericQueryFilters(query, args, [
{ column: "stockTransferId", ascending: false },
]);
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx
index d6fd367f4a..933bf0c575 100644
--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx
@@ -1,24 +1,104 @@
-import { MenuIcon, MenuItem, useDisclosure } from "@carbon/react";
-import { formatDate } from "@carbon/utils";
-import { useNavigate } from "@remix-run/react";
-import type { ColumnDef } from "@tanstack/react-table";
-import { memo, useCallback, useMemo, useState } from "react";
+import type { Result } from "@carbon/auth";
+import { useCarbon } from "@carbon/auth";
import {
+ Badge,
+ Button,
+ cn,
+ Combobox,
+ Count,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerHeader,
+ DrawerTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ Heading,
+ HStack,
+ IconButton,
+ Input,
+ InputGroup,
+ InputLeftElement,
+ MenuIcon,
+ MenuItem,
+ NumberField,
+ NumberInput,
+ NumberInputGroup,
+ PulsingDot,
+ ScrollArea,
+ Spinner,
+ Table as TableBase,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ toast,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ Tr,
+ useDisclosure,
+ useMount,
+ VStack,
+} from "@carbon/react";
+import { formatDate, prettifyKeyboardShortcut } from "@carbon/utils";
+import { useNumberFormatter } from "@react-aria/i18n";
+import { useFetcher, useNavigate } from "@remix-run/react";
+import {
+ flexRender,
+ getCoreRowModel,
+ useReactTable,
+ type ColumnDef,
+} from "@tanstack/react-table";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { BsChevronLeft, BsChevronRight } from "react-icons/bs";
+import {
+ LuArrowLeft,
+ LuArrowRight,
LuBookMarked,
LuCalendar,
+ LuCheckCheck,
+ LuCirclePlus,
LuClock,
+ LuFlag,
LuMapPin,
+ LuMaximize2,
+ LuMinus,
LuPencil,
+ LuSearch,
LuTrash,
+ LuTrash2,
+ LuTriangleAlert,
+ LuTruck,
LuUser,
+ LuX,
} from "react-icons/lu";
-import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
+import { EmployeeAvatar, Hyperlink, ItemThumbnail, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { ConfirmDelete } from "~/components/Modals";
-import { usePermissions, useRealtime, useUrlParams } from "~/hooks";
+import { getAccessorKey } from "~/components/Table/utils";
+import { usePermissions, useUrlParams, useUser } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
-import { usePeople } from "~/stores";
+import {
+ addTransferLine,
+ clearSelectedToShelves,
+ clearStockTransferWizard,
+ hasTransferLine,
+ hasTransferLinesToShelf,
+ isToShelfSelected,
+ removeTransferLine,
+ toggleToShelfSelection,
+ updateTransferLineQuantity,
+ usePeople,
+ useStockTransferWizard,
+ useStockTransferWizardLinesCount,
+} from "~/stores";
import { path } from "~/utils/path";
import { stockTransferStatusType } from "../../inventory.models";
import type { StockTransfer } from "../../types";
@@ -27,11 +107,12 @@ import StockTransferStatus from "./StockTransferStatus";
type StockTransfersTableProps = {
data: StockTransfer[];
count: number;
+ locationId: string;
};
const StockTransfersTable = memo(
- ({ data, count }: StockTransfersTableProps) => {
- useRealtime("shipment", `id=in.(${data.map((d) => d.id).join(",")})`);
+ ({ data, count, locationId }: StockTransfersTableProps) => {
+ const wizardDisclosure = useDisclosure();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -116,26 +197,9 @@ const StockTransfersTable = memo(
icon: <LuUser />,
},
},
- {
- accessorKey: "assignee",
- header: "Assignee",
- cell: ({ row }) => (
- <EmployeeAvatar employeeId={row.original.assignee} />
- ),
- meta: {
- filter: {
- type: "static",
- options: people.map((employee) => ({
- value: employee.id,
- label: employee.name,
- })),
- },
- icon: <LuUser />,
- },
- },
{
accessorKey: "completedAt",
- header: "Created At",
+ header: "Completed At",
cell: (item) => formatDate(item.getValue<string>()),
meta: {
icon: <LuCalendar />,
@@ -252,9 +316,26 @@ const StockTransfersTable = memo(
updatedBy: false,
}}
primaryAction={
- permissions.can("create", "inventory") && (
- <New label="Stock Transfer" to={path.to.newStockTransfer} />
- )
+ <div className="flex items-center gap-2">
+ <Combobox
+ asButton
+ size="sm"
+ value={locationId}
+ options={locations}
+ onChange={(selected) => {
+ // hard refresh because initialValues update has no effect otherwise
+ window.location.href = getLocationPath(selected);
+ }}
+ />
+ {permissions.can("create", "inventory") && (
+ <Button
+ onClick={wizardDisclosure.onOpen}
+ leftIcon={<LuCirclePlus />}
+ >
+ Add Stock Transfer
+ </Button>
+ )}
+ </div>
}
renderContextMenu={renderContextMenu}
title="Stock Transfers"
@@ -277,6 +358,12 @@ const StockTransfersTable = memo(
}}
/>
)}
+ {wizardDisclosure.isOpen && (
+ <StockTransferWizard
+ locationId={locationId}
+ onClose={wizardDisclosure.onClose}
+ />
+ )}
</>
);
}
@@ -284,3 +371,1281 @@ const StockTransfersTable = memo(
StockTransfersTable.displayName = "StockTransfersTable";
export default StockTransfersTable;
+
+function getLocationPath(locationId: string) {
+ return `${path.to.stockTransfers}?location=${locationId}`;
+}
+
+function StockTransferWizard({
+ locationId,
+ onClose,
+}: {
+ locationId: string;
+ onClose: () => void;
+}) {
+ return (
+ <Drawer
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DrawerContent size="full">
+ <DrawerHeader className="px-4">
+ <DrawerTitle>Stock Transfer Wizard</DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody className="w-full h-full p-0">
+ <TransferGrid locationId={locationId} />
+ </DrawerBody>
+ </DrawerContent>
+ </Drawer>
+ );
+}
+
+type TransferTableRow = {
+ itemId: string;
+ itemReadableId: string;
+ description: string;
+ thumbnailPath: string;
+ quantityOnHand: number;
+ quantityRequired: number;
+ quantityAvailable: number;
+ shelfId: string | null;
+ shelfName: string | null;
+};
+
+function TransferGrid({ locationId }: { locationId: string }) {
+ const [pageSize, setPageSize] = useState(100);
+ const formatter = useNumberFormatter();
+
+ const { carbon } = useCarbon();
+ const {
+ company: { id: companyId },
+ } = useUser();
+
+ const [wizard] = useStockTransferWizard();
+
+ const [transferTo, setTransferTo] = useState<TransferTableRow[]>([]);
+ const [allTransferToData, setAllTransferToData] = useState<
+ TransferTableRow[]
+ >([]);
+ const [transferToSearch, setTransferToSearch] = useState("");
+ const [transferToOffset, setTransferToOffset] = useState(0);
+ const [transferToIsLoading, setTransferToIsLoading] = useState(false);
+
+ const [transferFrom, setTransferFrom] = useState<TransferTableRow[]>([]);
+ const [allTransferFromData, setAllTransferFromData] = useState<
+ TransferTableRow[]
+ >([]);
+ const [transferFromSearch, setTransferFromSearch] = useState("");
+ const [transferFromOffset, setTransferFromOffset] = useState(0);
+ const [transferFromIsLoading, setTransferFromIsLoading] = useState(false);
+
+ const transferToQuery = useCallback(async () => {
+ if (!carbon) return;
+ setTransferToIsLoading(true);
+ const { data, error } = await carbon.rpc(
+ "get_item_shelf_requirements_by_location",
+ {
+ company_id: companyId,
+ location_id: locationId,
+ }
+ );
+
+ if (error) {
+ toast.error(error.message);
+ setAllTransferToData([]);
+ } else {
+ const mappedData =
+ data?.map((item) => ({
+ itemId: item.itemId,
+ itemReadableId: item.itemReadableId,
+ description: item.description,
+ thumbnailPath: item.thumbnailPath,
+ quantityOnHand: item.quantityOnHandInShelf,
+ quantityRequired: item.quantityRequiredByShelf,
+ quantityAvailable:
+ item.quantityOnHandInShelf - item.quantityRequiredByShelf,
+ shelfId: item.shelfId,
+ shelfName: item.shelfName,
+ })) ?? [];
+ setAllTransferToData(mappedData);
+ }
+
+ setTransferToIsLoading(false);
+ }, [carbon, companyId, locationId]);
+
+ const transferFromQuery = useCallback(async () => {
+ if (!carbon || wizard.selectedToShelfIds.size === 0) {
+ setAllTransferFromData([]);
+ return;
+ }
+
+ setTransferFromIsLoading(true);
+
+ // Get the selected "to" items to extract their itemIds
+ const selectedToItems = allTransferToData.filter((item) =>
+ wizard.selectedToShelfIds.has(item.shelfId!)
+ );
+
+ // Fetch data for each selected item
+ const fromDataPromises = selectedToItems.map(async (toItem) => {
+ const { data, error } = await carbon.rpc(
+ "get_item_shelf_requirements_by_location_and_item",
+ {
+ company_id: companyId,
+ location_id: locationId,
+ item_id: toItem.itemId,
+ }
+ );
+
+ if (error) {
+ console.error(error);
+ return [];
+ }
+
+ // Filter out the selected "to" shelf
+ return (
+ data
+ ?.filter((item) => item.shelfId !== toItem.shelfId)
+ .map((item) => ({
+ itemId: item.itemId,
+ itemReadableId: item.itemReadableId,
+ description: item.description,
+ thumbnailPath: item.thumbnailPath,
+ quantityOnHand: item.quantityOnHandInShelf,
+ quantityRequired: item.quantityRequiredByShelf,
+ quantityAvailable:
+ item.quantityOnHandInShelf - item.quantityRequiredByShelf,
+ shelfId: item.shelfId,
+ shelfName: item.shelfName,
+ })) ?? []
+ );
+ });
+
+ const fromDataArrays = await Promise.all(fromDataPromises);
+ const flattenedFromData = fromDataArrays.flat();
+
+ setAllTransferFromData(flattenedFromData);
+ setTransferFromIsLoading(false);
+ }, [
+ carbon,
+ companyId,
+ locationId,
+ wizard.selectedToShelfIds,
+ allTransferToData,
+ ]);
+
+ useMount(() => {
+ transferToQuery();
+ });
+
+ // Refresh "from" data when selected "to" items change
+ useEffect(() => {
+ transferFromQuery();
+ }, [transferFromQuery]);
+
+ // Reset offsets when page size changes
+ useEffect(() => {
+ setTransferToOffset(0);
+ setTransferFromOffset(0);
+ }, [pageSize]);
+
+ // Deselect active item/shelf when "to" table page changes
+ useEffect(() => {
+ clearSelectedToShelves();
+ }, [transferToOffset]);
+
+ // Client-side filtering and pagination for "to" table
+ useEffect(() => {
+ let filtered = allTransferToData;
+
+ if (transferToSearch) {
+ filtered = filtered.filter((item) =>
+ item.itemReadableId
+ .toLowerCase()
+ .includes(transferToSearch.toLowerCase())
+ );
+ }
+
+ setTransferTo(filtered);
+ setTransferToOffset(0); // Reset to first page when data changes
+ }, [allTransferToData, transferToSearch]);
+
+ // Client-side filtering and pagination for "from" table
+ useEffect(() => {
+ let filtered = allTransferFromData;
+
+ if (transferFromSearch) {
+ filtered = filtered.filter((item) =>
+ item.itemReadableId
+ .toLowerCase()
+ .includes(transferFromSearch.toLowerCase())
+ );
+ }
+
+ setTransferFrom(filtered);
+ setTransferFromOffset(0); // Reset to first page when data changes
+ }, [allTransferFromData, transferFromSearch]);
+
+ // Pagination logic for "to" table
+ const paginatedTransferTo = useMemo(
+ () => transferTo.slice(transferToOffset, transferToOffset + pageSize),
+ [transferTo, transferToOffset, pageSize]
+ );
+
+ const canPreviousPageTo = transferToOffset > 0;
+ const canNextPageTo = transferToOffset + pageSize < transferTo.length;
+
+ const handlePreviousPageTo = useCallback(() => {
+ setTransferToOffset((prev) => Math.max(0, prev - pageSize));
+ }, [pageSize]);
+
+ const handleNextPageTo = useCallback(() => {
+ setTransferToOffset((prev) => {
+ const newOffset = prev + pageSize;
+ return newOffset < transferTo.length ? newOffset : prev;
+ });
+ }, [pageSize, transferTo.length]);
+
+ // Pagination logic for "from" table
+ const paginatedTransferFrom = useMemo(
+ () => transferFrom.slice(transferFromOffset, transferFromOffset + pageSize),
+ [transferFrom, transferFromOffset, pageSize]
+ );
+
+ const canPreviousPageFrom = transferFromOffset > 0;
+ const canNextPageFrom = transferFromOffset + pageSize < transferFrom.length;
+
+ const handlePreviousPageFrom = useCallback(() => {
+ setTransferFromOffset((prev) => Math.max(0, prev - pageSize));
+ }, [pageSize]);
+
+ const handleNextPageFrom = useCallback(() => {
+ setTransferFromOffset((prev) => {
+ const newOffset = prev + pageSize;
+ return newOffset < transferFrom.length ? newOffset : prev;
+ });
+ }, [pageSize, transferFrom.length]);
+
+ const columnsTo = useMemo<ColumnDef<TransferTableRow>[]>(() => {
+ return [
+ {
+ accessorKey: "itemReadableId",
+ cell: ({ row }) => (
+ <HStack spacing={2}>
+ <ItemThumbnail
+ thumbnailPath={row.original.thumbnailPath}
+ type="Part"
+ />
+ <VStack spacing={0} className="max-w-[200px] truncate">
+ <div className="text-sm font-medium text-wrap">
+ {row.original.itemReadableId}
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {row.original.description}
+ </div>
+ </VStack>
+ </HStack>
+ ),
+ header: "Item ID",
+ },
+ {
+ accessorKey: "shelfName",
+ cell: ({ row }) => row.original.shelfName,
+ header: "Shelf",
+ },
+ {
+ accessorKey: "quantityOnHand",
+ cell: ({ row }) => {
+ // Calculate total quantity being transferred to this shelf
+ const transferLinesToThisShelf = wizard.lines.filter(
+ (line) => line.toShelfId === row.original.shelfId
+ );
+ const totalTransferQuantity = transferLinesToThisShelf.reduce(
+ (sum, line) => sum + (line.quantity ?? 0),
+ 0
+ );
+
+ const adjustedQuantity =
+ row.original.quantityOnHand + totalTransferQuantity;
+
+ return (
+ <div className="flex flex-col">
+ <span
+ className={
+ totalTransferQuantity > 0
+ ? "text-muted-foreground line-through text-xs"
+ : ""
+ }
+ >
+ {formatter.format(row.original.quantityOnHand)}
+ </span>
+ {totalTransferQuantity > 0 && (
+ <span className="font-medium">
+ {formatter.format(adjustedQuantity)}
+ </span>
+ )}
+ </div>
+ );
+ },
+ header: "On Hand",
+ },
+ {
+ accessorKey: "quantityRequired",
+ cell: ({ row }) => formatter.format(row.original.quantityRequired),
+ header: "Required",
+ },
+ {
+ accessorKey: "quantityAvailable",
+ cell: ({ row }) => {
+ // Calculate total quantity being transferred to this shelf
+ const transferLinesToThisShelf = wizard.lines.filter(
+ (line) => line.toShelfId === row.original.shelfId
+ );
+ const totalTransferQuantity = transferLinesToThisShelf.reduce(
+ (sum, line) => sum + (line.quantity ?? 0),
+ 0
+ );
+
+ const adjustedAvailable =
+ row.original.quantityAvailable + totalTransferQuantity;
+
+ return (
+ <div className="flex flex-col">
+ <span
+ className={
+ totalTransferQuantity > 0
+ ? "text-muted-foreground line-through text-xs"
+ : ""
+ }
+ >
+ {row.original.quantityAvailable < 0 ? (
+ <HStack>
+ <span className="text-red-500">
+ {formatter.format(row.original.quantityAvailable)}
+ </span>
+ <LuFlag className="text-red-500" />
+ </HStack>
+ ) : (
+ <span>
+ {formatter.format(row.original.quantityAvailable)}
+ </span>
+ )}
+ </span>
+ {totalTransferQuantity > 0 && (
+ <span
+ className={`font-medium ${
+ adjustedAvailable < 0 ? "text-red-500" : ""
+ }`}
+ >
+ {adjustedAvailable < 0 ? (
+ <HStack>
+ <span>{formatter.format(adjustedAvailable)}</span>
+ <LuFlag className="text-red-500" />
+ </HStack>
+ ) : (
+ formatter.format(adjustedAvailable)
+ )}
+ </span>
+ )}
+ </div>
+ );
+ },
+ header: "Available",
+ },
+
+ {
+ id: "actions",
+ cell: ({ row }) => {
+ const isSelected = isToShelfSelected(row.original.shelfId!);
+ const hasTransfers = hasTransferLinesToShelf(row.original.shelfId!);
+ return (
+ <div className="flex justify-end">
+ <Button
+ variant={isSelected ? "primary" : "secondary"}
+ onClick={() => {
+ if (isSelected) {
+ // If already selected, deselect it
+ toggleToShelfSelection(row.original.shelfId!);
+ } else {
+ // If not selected, clear selection and select only this one
+ clearSelectedToShelves();
+ toggleToShelfSelection(row.original.shelfId!);
+ }
+ }}
+ >
+ {hasTransfers ? (
+ <HStack>
+ <PulsingDot />
+ <span>Transfer</span>
+ </HStack>
+ ) : (
+ "Transfer"
+ )}
+ </Button>
+ </div>
+ );
+ },
+ header: "",
+ },
+ ];
+ }, [formatter, wizard.lines]);
+
+ const columnsFrom = useMemo<ColumnDef<TransferTableRow>[]>(() => {
+ return [
+ {
+ id: "actions",
+ cell: ({ row }) => {
+ // Find the corresponding "to" item
+ const toItem = allTransferToData.find(
+ (item) =>
+ item.itemId === row.original.itemId &&
+ wizard.selectedToShelfIds.has(item.shelfId!)
+ );
+
+ if (!toItem) return null;
+
+ const isLineAdded = hasTransferLine(
+ row.original.itemId,
+ row.original.shelfId!,
+ toItem.shelfId!
+ );
+
+ return (
+ <div className="flex justify-end">
+ <Button
+ leftIcon={<LuArrowLeft />}
+ variant={isLineAdded ? "primary" : "secondary"}
+ onClick={() => {
+ if (isLineAdded) {
+ removeTransferLine(
+ row.original.itemId,
+ row.original.shelfId!,
+ toItem.shelfId!
+ );
+ } else {
+ // Calculate default quantity:
+ // Amount needed to bring "to" bin to 0 available (fulfill requirements)
+ // Capped by what's available in "from" bin
+ const quantityNeeded = Math.max(
+ 0,
+ toItem.quantityRequired - toItem.quantityOnHand
+ );
+ const defaultQuantity = Math.min(
+ quantityNeeded,
+ row.original.quantityAvailable
+ );
+
+ addTransferLine({
+ itemId: row.original.itemId,
+ itemReadableId: row.original.itemReadableId,
+ description: row.original.description,
+ thumbnailPath: row.original.thumbnailPath,
+ fromShelfId: row.original.shelfId!,
+ fromShelfName: row.original.shelfName!,
+ toShelfId: toItem.shelfId!,
+ toShelfName: toItem.shelfName!,
+ quantityAvailable: row.original.quantityAvailable,
+ quantity: defaultQuantity,
+ });
+ }
+ }}
+ >
+ Transfer
+ </Button>
+ </div>
+ );
+ },
+ header: "",
+ },
+ {
+ id: "quantity",
+ cell: ({ row }) => {
+ // Find the corresponding "to" item
+ const toItem = allTransferToData.find(
+ (item) =>
+ item.itemId === row.original.itemId &&
+ wizard.selectedToShelfIds.has(item.shelfId!)
+ );
+
+ if (!toItem) return null;
+
+ const isLineAdded = hasTransferLine(
+ row.original.itemId,
+ row.original.shelfId!,
+ toItem.shelfId!
+ );
+
+ if (!isLineAdded) return null;
+
+ // Find the line to get the current quantity
+ const line = wizard.lines.find(
+ (l) =>
+ l.itemId === row.original.itemId &&
+ l.fromShelfId === row.original.shelfId! &&
+ l.toShelfId === toItem.shelfId!
+ );
+
+ return (
+ <NumberField
+ value={Math.max(0, line?.quantity ?? 0)}
+ minValue={0}
+ onChange={(value: number) => {
+ if (value !== null && !isNaN(value)) {
+ const clampedValue = Math.min(
+ Math.max(0, value),
+ row.original.quantityAvailable
+ );
+ updateTransferLineQuantity(
+ row.original.itemId,
+ row.original.shelfId!,
+ toItem.shelfId!,
+ clampedValue
+ );
+ }
+ }}
+ className="w-24"
+ >
+ <NumberInputGroup>
+ <NumberInput size="sm" />
+ </NumberInputGroup>
+ </NumberField>
+ );
+ },
+ header: "Quantity",
+ },
+ {
+ accessorKey: "itemReadableId",
+ cell: ({ row }) => (
+ <HStack spacing={2}>
+ <ItemThumbnail
+ thumbnailPath={row.original.thumbnailPath}
+ type="Part"
+ />
+ <VStack spacing={0} className="max-w-[200px] truncate">
+ <div className="text-sm font-medium text-wrap">
+ {row.original.itemReadableId}
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {row.original.description}
+ </div>
+ </VStack>
+ </HStack>
+ ),
+ header: "Item ID",
+ },
+ {
+ accessorKey: "shelfName",
+ cell: ({ row }) => row.original.shelfName,
+ header: "Shelf",
+ },
+ {
+ accessorKey: "quantityOnHand",
+ cell: ({ row }) => {
+ // Find the corresponding "to" item
+ const toItem = allTransferToData.find(
+ (item) =>
+ item.itemId === row.original.itemId &&
+ wizard.selectedToShelfIds.has(item.shelfId!)
+ );
+
+ if (!toItem) return formatter.format(row.original.quantityOnHand);
+
+ // Find the transfer line to get the quantity being transferred
+ const transferLine = wizard.lines.find(
+ (l) =>
+ l.itemId === row.original.itemId &&
+ l.fromShelfId === row.original.shelfId! &&
+ l.toShelfId === toItem.shelfId!
+ );
+
+ const transferQuantity = transferLine?.quantity ?? 0;
+ const adjustedQuantity =
+ row.original.quantityOnHand - transferQuantity;
+
+ return (
+ <div className="flex flex-col">
+ <span
+ className={
+ transferQuantity > 0
+ ? "text-muted-foreground line-through text-xs"
+ : ""
+ }
+ >
+ {formatter.format(row.original.quantityOnHand)}
+ </span>
+ {transferQuantity > 0 && (
+ <span className="font-medium">
+ {formatter.format(adjustedQuantity)}
+ </span>
+ )}
+ </div>
+ );
+ },
+ header: "On Hand",
+ },
+ {
+ accessorKey: "quantityAvailable",
+ cell: ({ row }) => {
+ // Find the corresponding "to" item
+ const toItem = allTransferToData.find(
+ (item) =>
+ item.itemId === row.original.itemId &&
+ wizard.selectedToShelfIds.has(item.shelfId!)
+ );
+
+ if (!toItem) {
+ return row.original.quantityAvailable < 0 ? (
+ <HStack>
+ <span className="text-red-500">
+ {formatter.format(row.original.quantityAvailable)}
+ </span>
+ <LuFlag className="text-red-500" />
+ </HStack>
+ ) : (
+ <span>{formatter.format(row.original.quantityAvailable)}</span>
+ );
+ }
+
+ // Find the transfer line to get the quantity being transferred
+ const transferLine = wizard.lines.find(
+ (l) =>
+ l.itemId === row.original.itemId &&
+ l.fromShelfId === row.original.shelfId! &&
+ l.toShelfId === toItem.shelfId!
+ );
+
+ const transferQuantity = transferLine?.quantity ?? 0;
+ const adjustedAvailable =
+ row.original.quantityAvailable - transferQuantity;
+
+ return (
+ <div className="flex flex-col">
+ <span
+ className={
+ transferQuantity > 0
+ ? "text-muted-foreground line-through text-xs"
+ : ""
+ }
+ >
+ {row.original.quantityAvailable < 0 ? (
+ <HStack>
+ <span className="text-red-500">
+ {formatter.format(row.original.quantityAvailable)}
+ </span>
+ <LuFlag className="text-red-500" />
+ </HStack>
+ ) : (
+ <span>
+ {formatter.format(row.original.quantityAvailable)}
+ </span>
+ )}
+ </span>
+ {transferQuantity > 0 && (
+ <span
+ className={`font-medium ${
+ adjustedAvailable < 0 ? "text-red-500" : ""
+ }`}
+ >
+ {adjustedAvailable < 0 ? (
+ <HStack>
+ <span>{formatter.format(adjustedAvailable)}</span>
+ <LuFlag className="text-red-500" />
+ </HStack>
+ ) : (
+ formatter.format(adjustedAvailable)
+ )}
+ </span>
+ )}
+ </div>
+ );
+ },
+ header: "Available",
+ },
+ {
+ accessorKey: "quantityRequired",
+ cell: ({ row }) => formatter.format(row.original.quantityRequired),
+ header: "Allocated",
+ },
+ ];
+ }, [formatter, allTransferToData, wizard.selectedToShelfIds, wizard.lines]);
+
+ return (
+ <>
+ <div className="grid grid-cols-2 gap-0 h-full w-full">
+ <div className="flex flex-col">
+ <div className="flex-1 border-r">
+ <TransferTable
+ title="Transfer To"
+ data={paginatedTransferTo}
+ isLoading={transferToIsLoading}
+ columns={columnsTo}
+ count={transferTo.length}
+ offset={transferToOffset}
+ canPreviousPage={canPreviousPageTo}
+ canNextPage={canNextPageTo}
+ handlePreviousPage={handlePreviousPageTo}
+ handleNextPage={handleNextPageTo}
+ pageSize={pageSize}
+ setPageSize={setPageSize}
+ search={transferToSearch}
+ onSearchChange={setTransferToSearch}
+ isRowSelected={(row) => isToShelfSelected(row.shelfId!)}
+ />
+ </div>
+ </div>
+ <div className="flex flex-col">
+ <div className="flex-1">
+ <TransferTable
+ title="Transfer From"
+ data={paginatedTransferFrom}
+ isLoading={transferFromIsLoading}
+ columns={columnsFrom}
+ count={transferFrom.length}
+ offset={transferFromOffset}
+ canPreviousPage={canPreviousPageFrom}
+ canNextPage={canNextPageFrom}
+ handlePreviousPage={handlePreviousPageFrom}
+ handleNextPage={handleNextPageFrom}
+ pageSize={pageSize}
+ setPageSize={setPageSize}
+ search={transferFromSearch}
+ onSearchChange={setTransferFromSearch}
+ isRowSelected={(row) => {
+ const toItem = allTransferToData.find(
+ (item) =>
+ item.itemId === row.itemId &&
+ wizard.selectedToShelfIds.has(item.shelfId!)
+ );
+ return toItem
+ ? hasTransferLine(row.itemId, row.shelfId!, toItem.shelfId!)
+ : false;
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ <StockTransferWizardWidget locationId={locationId} />
+ </>
+ );
+}
+
+function TransferTable({
+ title,
+ data,
+ columns,
+ count,
+ isLoading,
+ offset,
+ pageSize,
+ setPageSize,
+ canPreviousPage,
+ canNextPage,
+ handlePreviousPage,
+ handleNextPage,
+ search,
+ onSearchChange,
+ isRowSelected,
+}: {
+ title: string;
+ data: TransferTableRow[];
+ isLoading: boolean;
+ columns: ColumnDef<TransferTableRow>[];
+ count: number;
+ offset: number;
+ pageSize: number;
+ setPageSize: (size: number) => void;
+ canPreviousPage: boolean;
+ canNextPage: boolean;
+ handlePreviousPage: () => void;
+ handleNextPage: () => void;
+ search: string;
+ onSearchChange: (value: string) => void;
+ isRowSelected?: (row: TransferTableRow) => boolean;
+}) {
+ const pageSizes = [20, 100, 500, 1000];
+ if (!pageSizes.includes(pageSize)) {
+ pageSizes.push(pageSize);
+ pageSizes.sort();
+ }
+
+ const table = useReactTable({
+ data: data,
+ columns: columns,
+ getCoreRowModel: getCoreRowModel(),
+ });
+
+ const rows = table.getRowModel().rows;
+ const tableRef = useRef<HTMLTableElement>(null);
+
+ return (
+ <VStack spacing={0} className="h-full bg-card flex flex-col w-full px-0">
+ <HStack className="px-4 py-2 justify-between bg-card border-b w-full">
+ <HStack spacing={4} className="w-full justify-between">
+ <Heading size="h4" className="flex-shrink-0">
+ {title}
+ </Heading>
+ <div>
+ <InputGroup size="sm">
+ <InputLeftElement>
+ <LuSearch className="text-muted-foreground w-3.5 h-3.5 mt-[-2px]" />
+ </InputLeftElement>
+ <Input
+ value={search}
+ onChange={(e) => {
+ onSearchChange(e.target.value);
+ }}
+ placeholder="Search"
+ className="w-[100px] sm:w-[200px] text-sm"
+ />
+ </InputGroup>
+ </div>
+ </HStack>
+ </HStack>
+ <div
+ id="table-container"
+ className="w-full h-full overflow-x-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
+ style={{ contain: "strict" }}
+ >
+ <div className="flex max-w-full h-full">
+ {isLoading ? (
+ <div className="flex h-full w-full items-center justify-center">
+ <Spinner className="size-8" />
+ </div>
+ ) : rows.length === 0 ? (
+ <div className="flex flex-col w-full h-full items-center justify-center gap-4">
+ <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background -mt-[10dvh]">
+ <LuTriangleAlert className="h-6 w-6 flex-shrink-0" />
+ </div>
+ <span className="text-xs font-mono font-light text-foreground uppercase">
+ No bins exist
+ </span>
+ </div>
+ ) : (
+ <TableBase
+ ref={tableRef}
+ full
+ className="relative border-collapse border-spacing-0"
+ >
+ <Thead className="sticky top-0 z-10">
+ {table.getHeaderGroups().map((headerGroup) => (
+ <Tr key={headerGroup.id} className="h-10">
+ {headerGroup.headers.map((header) => {
+ const accessorKey = getAccessorKey(
+ header.column.columnDef
+ );
+
+ const sortable =
+ accessorKey &&
+ !accessorKey.endsWith(".id") &&
+ header.column.columnDef.enableSorting !== false;
+
+ return (
+ <Th
+ key={header.id}
+ colSpan={header.colSpan}
+ id={`header-${header.id}`}
+ className={cn(
+ "px-4 py-3 whitespace-nowrap",
+ sortable && "cursor-pointer"
+ )}
+ style={{
+ width: header.getSize(),
+ }}
+ >
+ {!header.isPlaceholder && (
+ <div className="flex justify-start items-center gap-2">
+ {header.column.columnDef.meta?.icon}
+ {flexRender(
+ header.column.columnDef.header,
+ header.getContext()
+ )}
+ </div>
+ )}
+ </Th>
+ );
+ })}
+ </Tr>
+ ))}
+ </Thead>
+ <Tbody>
+ {rows.map((row) => {
+ const selected = isRowSelected?.(row.original) ?? false;
+ return (
+ <Tr
+ key={row.id}
+ className={cn(
+ "border-b border-border transition-colors",
+ selected && "bg-primary/10 hover:bg-primary/15"
+ )}
+ >
+ {row.getVisibleCells().map((cell, columnIndex) => {
+ return (
+ <Td
+ key={cell.id}
+ className="relative px-4 py-2 whitespace-nowrap text-sm outline-none"
+ >
+ <div>
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext()
+ )}
+ </div>
+ </Td>
+ );
+ })}
+ </Tr>
+ );
+ })}
+ </Tbody>
+ </TableBase>
+ )}
+ </div>
+ </div>
+ <hr className="m-0 h-px w-full border-none bg-gradient-to-r from-zinc-200/0 via-zinc-500/30 to-zinc-200/0" />
+ <HStack
+ className="text-center bg-card justify-between py-4 w-full z-[1] px-4"
+ spacing={6}
+ >
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="secondary">{pageSize} rows</Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-48">
+ <DropdownMenuLabel>Results per page</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuRadioGroup value={`${pageSize}`}>
+ {pageSizes.map((size) => (
+ <DropdownMenuRadioItem
+ key={`${size}`}
+ value={`${size}`}
+ onClick={() => {
+ setPageSize(size);
+ }}
+ >
+ {size}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <HStack>
+ <PaginationButtons
+ count={count}
+ offset={offset}
+ pageSize={pageSize}
+ canPreviousPage={canPreviousPage}
+ canNextPage={canNextPage}
+ handlePreviousPage={handlePreviousPage}
+ handleNextPage={handleNextPage}
+ />
+ </HStack>
+ </HStack>
+ </VStack>
+ );
+}
+
+function PaginationButtons({
+ count,
+ offset,
+ pageSize,
+ canPreviousPage,
+ canNextPage,
+ handlePreviousPage,
+ handleNextPage,
+}: {
+ count: number;
+ offset: number;
+ pageSize: number;
+ canPreviousPage: boolean;
+ canNextPage: boolean;
+ handlePreviousPage: () => void;
+ handleNextPage: () => void;
+}) {
+ return (
+ <>
+ <div className="text-foreground text-sm font-medium align-center hidden lg:flex">
+ {count > 0 ? offset + 1 : 0} - {Math.min(offset + pageSize, count)} of{" "}
+ {count}
+ </div>
+ <Tooltip>
+ <TooltipTrigger>
+ <Button
+ variant="secondary"
+ isDisabled={!canPreviousPage}
+ onClick={handlePreviousPage}
+ leftIcon={<BsChevronLeft />}
+ >
+ Previous
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>{prettifyKeyboardShortcut("ArrowLeft")}</HStack>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger>
+ <Button
+ variant="secondary"
+ isDisabled={!canNextPage}
+ onClick={handleNextPage}
+ rightIcon={<BsChevronRight />}
+ >
+ Next
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>{prettifyKeyboardShortcut("ArrowRight")}</HStack>
+ </TooltipContent>
+ </Tooltip>
+ </>
+ );
+}
+
+const StockTransferWizardWidget = ({ locationId }: { locationId: string }) => {
+ const fetcher = useFetcher<Result>();
+ const [wizard] = useStockTransferWizard();
+ const linesCount = useStockTransferWizardLinesCount();
+
+ const [isExpanded, setIsExpanded] = useState(false);
+ const [isMinimized, setIsMinimized] = useState(false);
+
+ // Filter out lines with quantity 0
+ const activeLines = wizard.lines.filter((line) => (line.quantity ?? 0) > 0);
+
+ const onRemoveItem = (
+ itemId: string,
+ fromShelfId: string,
+ toShelfId: string
+ ) => {
+ removeTransferLine(itemId, fromShelfId, toShelfId);
+ };
+
+ const onClearAll = () => {
+ clearStockTransferWizard();
+ };
+
+ if (linesCount === 0) {
+ return null;
+ }
+
+ if (isMinimized) {
+ return (
+ <div className="fixed bottom-6 right-6 z-50">
+ <button
+ onClick={() => setIsMinimized(false)}
+ className="relative flex items-center justify-center w-16 h-16 bg-card border-2 border-border rounded-full shadow-2xl hover:scale-105 transition-transform duration-200"
+ >
+ <LuTruck className="w-6 h-6 text-foreground" />
+ {activeLines.length > 0 && (
+ <Badge className="absolute -top-2 -right-2 h-7 w-7 flex items-center justify-center p-0 border-2 border-background">
+ {activeLines.length}
+ </Badge>
+ )}
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="fixed bottom-6 right-6 z-[9999]">
+ <div
+ className={`bg-card border-2 border-border rounded-2xl shadow-2xl transition-all duration-300 ease-in-out ${
+ isExpanded ? "w-96 h-[32rem]" : "w-80 h-auto"
+ }`}
+ >
+ {/* Header */}
+ <div className="flex items-center justify-between p-4 border-b-2 border-border">
+ <div className="flex items-center gap-3">
+ <div className="flex items-center justify-center w-10 h-10 bg-primary rounded-lg">
+ <LuCheckCheck className="w-5 h-5 text-primary-foreground" />
+ </div>
+ <div>
+ <h3 className="font-semibold text-card-foreground text-base">
+ Transfer Lines
+ </h3>
+ <p className="text-xs text-muted-foreground">
+ {activeLines.length}{" "}
+ {activeLines.length === 1 ? "item" : "items"}
+ </p>
+ </div>
+ </div>
+ <div className="flex items-center gap-1">
+ <IconButton
+ variant="ghost"
+ aria-label={isExpanded ? "Minimize" : "Expand"}
+ icon={
+ isExpanded ? (
+ <LuMinus className="size-4" />
+ ) : (
+ <LuMaximize2 className="size-4" />
+ )
+ }
+ onClick={() => setIsExpanded(!isExpanded)}
+ />
+ <IconButton
+ variant="ghost"
+ aria-label="Close"
+ icon={<LuX className="size-4" />}
+ onClick={() => setIsMinimized(true)}
+ />
+ </div>
+ </div>
+
+ {/* Content */}
+ {isExpanded ? (
+ <div className="flex flex-col h-[calc(32rem-5rem)]">
+ <ScrollArea className="flex-1 p-4">
+ {activeLines.length === 0 ? (
+ <div className="flex flex-col items-center justify-center h-full text-center py-12">
+ <div className="w-16 h-16 bg-muted rounded-full flex items-center justify-center mb-4">
+ <LuTruck className="w-8 h-8 text-muted-foreground" />
+ </div>
+ <p className="text-sm text-muted-foreground">
+ No transfer lines yet
+ </p>
+ <p className="text-xs text-muted-foreground mt-1">
+ Start adding items to transfer
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-3">
+ {activeLines.map((line) => (
+ <div
+ key={`${line.itemId}-${line.fromShelfId}-${line.toShelfId}`}
+ className="group bg-secondary/50 border border-border rounded-lg p-3 hover:bg-secondary transition-colors"
+ >
+ <div className="flex items-start justify-between gap-3 mb-2">
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-1">
+ <ItemThumbnail
+ thumbnailPath={line.thumbnailPath}
+ type="Part"
+ size="sm"
+ />
+ <div className="flex-1">
+ <span className="font-mono text-xs font-semibold block">
+ {line.itemReadableId}
+ </span>
+ <p className="text-xs text-muted-foreground truncate">
+ {line.description}
+ </p>
+ </div>
+ </div>
+ </div>
+ <IconButton
+ variant="secondary"
+ aria-label="Remove item"
+ icon={<LuTrash2 />}
+ size="sm"
+ onClick={() =>
+ onRemoveItem(
+ line.itemId,
+ line.fromShelfId,
+ line.toShelfId
+ )
+ }
+ />
+ </div>
+ <div className="space-y-1 text-xs">
+ <HStack
+ className="items-center justify-start"
+ spacing={1}
+ >
+ <Badge variant="outline">{line.fromShelfName}</Badge>
+ <LuArrowRight className="size-4" />
+ <Count count={line.quantity ?? 0} />
+ <LuArrowRight className="size-4" />
+ <Badge variant="outline">{line.toShelfName}</Badge>
+ </HStack>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </ScrollArea>
+
+ {/* Footer */}
+ {activeLines.length > 0 && (
+ <div className="p-4 border-t-2 border-border space-y-2">
+ <fetcher.Form method="post" action={path.to.newStockTransfer}>
+ <input type="hidden" name="locationId" value={locationId} />
+ <input
+ type="hidden"
+ name="lines"
+ value={JSON.stringify(activeLines)}
+ />
+ <Button
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={fetcher.state !== "idle"}
+ size="lg"
+ className="w-full"
+ type="submit"
+ >
+ Create Transfer
+ </Button>
+ </fetcher.Form>
+ <Button variant="ghost" className="w-full" onClick={onClearAll}>
+ Clear All
+ </Button>
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="p-4 space-y-4">
+ {activeLines.length === 0 ? (
+ <p className="text-sm text-muted-foreground text-center py-2">
+ No transfer lines yet
+ </p>
+ ) : (
+ <div className="space-y-2">
+ {activeLines.slice(0, 3).map((line) => (
+ <div
+ key={`${line.itemId}-${line.fromShelfId}-${line.toShelfId}`}
+ className="flex items-center justify-between text-sm"
+ >
+ <span className="font-mono text-xs truncate flex-1">
+ {line.itemReadableId}
+ </span>
+ <HStack spacing={1}>
+ <Count count={line.quantity ?? 0} />
+ <LuArrowRight className="size-4" />
+ <Badge variant="outline" className="ml-2">
+ {line.toShelfName}
+ </Badge>
+ </HStack>
+ </div>
+ ))}
+ {activeLines.length > 3 && (
+ <p className="text-xs text-muted-foreground text-center pt-1">
+ +{activeLines.length - 3} more
+ </p>
+ )}
+ </div>
+ )}
+ {activeLines.length > 0 && (
+ <fetcher.Form method="post" action={path.to.newStockTransfer}>
+ <input type="hidden" name="locationId" value={locationId} />
+ <input
+ type="hidden"
+ name="lines"
+ value={JSON.stringify(activeLines)}
+ />
+ <Button
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={fetcher.state !== "idle"}
+ size="lg"
+ className="w-full"
+ type="submit"
+ >
+ Create Transfer
+ </Button>
+ </fetcher.Form>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
index 5610801e0b..f8e8303fbc 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
@@ -61,7 +61,7 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
if (!jobId) throw new Error("Job ID is required");
const routeData = useRouteData<{ job: Job }>(path.to.job(jobId));
- const isAllocated = ["Planned", "Ready", "In Progress", "Paused"].includes(
+ const isRequired = ["Planned", "Ready", "In Progress", "Paused"].includes(
routeData?.job?.status ?? ""
);
@@ -92,7 +92,7 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
return;
}
- const quantityRequiredByShelf = isAllocated
+ const quantityRequiredByShelf = isRequired
? material.quantityFromProductionOrderInShelf
: material.quantityFromProductionOrderInShelf +
material.estimatedQuantity;
@@ -119,13 +119,13 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
const incoming =
material.quantityOnPurchaseOrder + material.quantityOnProductionOrder;
- const allocated =
+ const required =
material.quantityFromProductionOrderInShelf +
material.quantityFromProductionOrderNotInShelf +
material.quantityOnSalesOrder;
const hasTotalQuantityFlag =
- quantityOnHand + incoming - allocated <
+ quantityOnHand + incoming - required <
(material.estimatedQuantity ?? 0);
if (hasTotalQuantityFlag) {
@@ -136,7 +136,7 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
action: "order",
quantity:
(material.estimatedQuantity ?? 0) -
- (quantityOnHand + incoming - allocated),
+ (quantityOnHand + incoming - required),
});
}
});
@@ -234,7 +234,7 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
</Badge>
);
- const quantityRequiredByShelf = isAllocated
+ const quantityRequiredByShelf = isRequired
? row.original.quantityFromProductionOrderInShelf
: row.original.quantityFromProductionOrderInShelf +
row.original.estimatedQuantity;
@@ -251,11 +251,13 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
<HStack>
{hasShelfQuantityFlag ? (
<>
- <span className="text-red-500">{quantityOnHandInShelf}</span>
+ <span className="text-red-500">
+ {formatter.format(quantityOnHandInShelf)}
+ </span>
<LuFlag className="text-red-500" />
</>
) : (
- <span>{quantityOnHandInShelf}</span>
+ <span>{formatter.format(quantityOnHandInShelf)}</span>
)}
</HStack>
);
@@ -282,24 +284,26 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
row.original.quantityOnPurchaseOrder +
row.original.quantityOnProductionOrder;
- const allocated =
+ const required =
row.original.quantityFromProductionOrderInShelf +
row.original.quantityFromProductionOrderNotInShelf +
row.original.quantityOnSalesOrder;
const hasTotalQuantityFlag =
- quantityOnHand + incoming - allocated <
+ quantityOnHand + incoming - required <
(row.original.estimatedQuantity ?? 0);
return (
<HStack>
{hasTotalQuantityFlag ? (
<>
- <span className="text-red-500">{quantityOnHand}</span>
+ <span className="text-red-500">
+ {formatter.format(quantityOnHand)}
+ </span>
<LuFlag className="text-red-500" />
</>
) : (
- <span>{quantityOnHand}</span>
+ <span>{formatter.format(quantityOnHand)}</span>
)}
</HStack>
);
@@ -309,13 +313,14 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
},
},
{
- id: "allocated",
- header: "Allocated",
+ id: "required",
+ header: "Required",
cell: ({ row }) =>
- row.original.quantityFromProductionOrderInShelf +
- row.original.quantityFromProductionOrderNotInShelf +
- row.original.quantityOnSalesOrder,
-
+ formatter.format(
+ row.original.quantityFromProductionOrderInShelf +
+ row.original.quantityFromProductionOrderNotInShelf +
+ row.original.quantityOnSalesOrder
+ ),
meta: {
icon: <LuArrowDown className="text-red-600" />,
},
@@ -324,8 +329,10 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
id: "incoming",
header: "Incoming",
cell: ({ row }) =>
- row.original.quantityOnPurchaseOrder +
- row.original.quantityOnProductionOrder,
+ formatter.format(
+ row.original.quantityOnPurchaseOrder +
+ row.original.quantityOnProductionOrder
+ ),
meta: {
icon: <LuArrowUp className="text-emerald-600" />,
},
@@ -336,7 +343,7 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
items,
jobId,
setSelectedMaterialId,
- isAllocated,
+ isRequired,
formatter,
sessionItemsCount,
]);
@@ -353,7 +360,7 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
return null;
}
- const quantityRequiredByShelf = isAllocated
+ const quantityRequiredByShelf = isRequired
? row.quantityFromProductionOrderInShelf
: row.quantityFromProductionOrderInShelf + row.estimatedQuantity;
@@ -363,7 +370,7 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
row.quantityOnHandInShelf + row.quantityOnHandNotInShelf;
const incoming =
row.quantityOnPurchaseOrder + row.quantityOnProductionOrder;
- const allocated =
+ const required =
row.quantityFromProductionOrderInShelf +
row.quantityFromProductionOrderNotInShelf +
row.quantityOnSalesOrder;
@@ -410,7 +417,7 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
action: "order",
quantity:
(row.estimatedQuantity ?? 0) -
- (quantityOnHand + incoming - allocated),
+ (quantityOnHand + incoming - required),
});
}
}}
@@ -421,7 +428,7 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
</>
);
};
- }, [isAllocated, session.items]);
+ }, [isRequired, session.items]);
const permissions = usePermissions();
@@ -527,26 +534,26 @@ const StockTransferSessionWidget = () => {
</div>
</div>
<div className="flex items-center gap-1">
- <Button
+ <IconButton
variant="ghost"
size="sm"
- className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
+ aria-label={isExpanded ? "Minimize" : "Expand"}
+ icon={
+ isExpanded ? (
+ <LuMinus className="size-4" />
+ ) : (
+ <LuMaximize2 className="size-4" />
+ )
+ }
onClick={() => setIsExpanded(!isExpanded)}
- >
- {isExpanded ? (
- <LuMinus className="size-4" />
- ) : (
- <LuMaximize2 className="size-4" />
- )}
- </Button>
- <Button
+ />
+ <IconButton
variant="ghost"
size="sm"
- className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
+ aria-label="Close"
+ icon={<LuX className="size-4" />}
onClick={() => setIsMinimized(true)}
- >
- <LuX className="size-4" />
- </Button>
+ />
</div>
</div>
@@ -656,24 +663,17 @@ const StockTransferSessionWidget = () => {
{/* Footer */}
{allItems.length > 0 && (
<div className="p-4 border-t-2 border-border space-y-2">
- <Button
- className="w-full bg-accent hover:bg-accent/90 text-accent-foreground font-semibold"
- size="lg"
- >
- Submit
+ <Button size="lg" className="w-full">
+ Create
</Button>
- <Button
- variant="secondary"
- className="w-full bg-transparent"
- onClick={onClearAll}
- >
+ <Button variant="ghost" className="w-full" onClick={onClearAll}>
Clear All
</Button>
</div>
)}
</div>
) : (
- <div className="p-4">
+ <div className="p-4 space-y-4">
{allItems.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-2">
No parts added yet
@@ -698,6 +698,7 @@ const StockTransferSessionWidget = () => {
)}
</div>
)}
+ {allItems.length > 0 && <Button size="lg">Create</Button>}
</div>
)}
</div>
diff --git a/apps/erp/app/routes/x+/inventory+/stock-transfers.tsx b/apps/erp/app/routes/x+/inventory+/stock-transfers.tsx
index 1e30a09522..1d0ac68e12 100644
--- a/apps/erp/app/routes/x+/inventory+/stock-transfers.tsx
+++ b/apps/erp/app/routes/x+/inventory+/stock-transfers.tsx
@@ -7,6 +7,8 @@ import type { LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { getStockTransfers } from "~/modules/inventory";
import StockTransfersTable from "~/modules/inventory/ui/StockTransfers/StockTransfersTable";
+import { getLocationsList } from "~/modules/resources";
+import { getUserDefaults } from "~/modules/users/users.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
@@ -17,7 +19,7 @@ export const handle: Handle = {
};
export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
view: "inventory",
});
@@ -27,8 +29,40 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
+ let locationId = searchParams.get("location");
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId, companyId);
+ if (userDefaults.error) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client, companyId);
+ if (locations.error || !locations.data?.length) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
const [stockTransfers] = await Promise.all([
getStockTransfers(client, companyId, {
+ locationId,
search,
limit,
offset,
@@ -48,15 +82,20 @@ export async function loader({ request }: LoaderFunctionArgs) {
return json({
stockTransfers: stockTransfers.data ?? [],
count: stockTransfers.count ?? 0,
+ locationId,
});
}
export default function StockTransfersRoute() {
- const { stockTransfers, count } = useLoaderData<typeof loader>();
+ const { stockTransfers, count, locationId } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <StockTransfersTable data={stockTransfers} count={count ?? 0} />
+ <StockTransfersTable
+ data={stockTransfers}
+ count={count ?? 0}
+ locationId={locationId}
+ />
<Outlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/stock-transfer+/_layout.tsx b/apps/erp/app/routes/x+/stock-transfer+/_layout.tsx
new file mode 100644
index 0000000000..6dba389657
--- /dev/null
+++ b/apps/erp/app/routes/x+/stock-transfer+/_layout.tsx
@@ -0,0 +1,22 @@
+import { Outlet } from "@remix-run/react";
+import type { MetaFunction } from "@vercel/remix";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Stock Transfer" }];
+};
+
+export const config = {
+ runtime: "nodejs",
+};
+
+export const handle: Handle = {
+ breadcrumb: "Inventory",
+ to: path.to.inventory,
+ module: "inventory",
+};
+
+export default function StockTransferRoute() {
+ return <Outlet />;
+}
diff --git a/apps/erp/app/routes/x+/stock-transfer+/new.tsx b/apps/erp/app/routes/x+/stock-transfer+/new.tsx
new file mode 100644
index 0000000000..a447ebf63a
--- /dev/null
+++ b/apps/erp/app/routes/x+/stock-transfer+/new.tsx
@@ -0,0 +1,70 @@
+import { error, getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import { stockTransferValidator } from "~/modules/inventory";
+import { getNextSequence } from "~/modules/settings";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Stock Transfers",
+ to: path.to.stockTransfers,
+};
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "inventory",
+ });
+
+ const serviceRole = await getCarbonServiceRole();
+
+ const formData = await request.formData();
+ const validation = await validator(stockTransferValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const nextSequence = await getNextSequence(
+ serviceRole,
+ "stockTransfer",
+ companyId
+ );
+ if (nextSequence.error) {
+ throw redirect(
+ path.to.stockTransfers,
+ await flash(
+ request,
+ error(nextSequence.error, "Failed to get next sequence")
+ )
+ );
+ }
+
+ console.log(validation.data);
+
+ // const createIssue = await upsertIssue(serviceRole, {
+ // ...nonConformance,
+ // nonConformanceId: nextSequence.data,
+ // companyId,
+ // createdBy: userId,
+ // customFields: setCustomFields(formData),
+ // });
+
+ // if (createIssue.error || !createIssue.data) {
+ // throw redirect(
+ // path.to.issues,
+ // await flash(request, error(createIssue.error, "Failed to insert issue"))
+ // );
+ // }
+
+ // const ncrId = createIssue.data?.id;
+ // if (!ncrId) {
+ // throw redirect(
+ // path.to.issues,
+ // await flash(request, error("Failed to insert issue"))
+ // );
+ // }
+}
diff --git a/apps/erp/app/stores/stock-transfer.ts b/apps/erp/app/stores/stock-transfer.ts
index 76d19f1a87..648708d41d 100644
--- a/apps/erp/app/stores/stock-transfer.ts
+++ b/apps/erp/app/stores/stock-transfer.ts
@@ -86,3 +86,171 @@ export const isInStockTransferSession = (
(item) => item.id === itemId && item.action === action
);
};
+
+// Stock Transfer Wizard Store
+export type StockTransferWizardLine = {
+ itemId: string;
+ itemReadableId: string;
+ description: string;
+ thumbnailPath: string;
+ fromShelfId: string;
+ fromShelfName: string;
+ toShelfId: string;
+ toShelfName: string;
+ quantityAvailable: number;
+ quantity?: number;
+};
+
+export type StockTransferWizardState = {
+ selectedToShelfIds: Set<string>; // Set of shelfIds selected in the "to" table
+ lines: StockTransferWizardLine[];
+};
+
+const $wizardStore = atom<StockTransferWizardState>({
+ selectedToShelfIds: new Set(),
+ lines: [],
+});
+
+const $wizardLinesCount = computed(
+ $wizardStore,
+ (wizard) => wizard.lines.filter((line) => (line.quantity ?? 0) > 0).length
+);
+
+export const useStockTransferWizard = () =>
+ useNanoStore<StockTransferWizardState>($wizardStore, "wizard");
+export const useStockTransferWizardLinesCount = () =>
+ useValue($wizardLinesCount);
+
+// Stock Transfer Wizard actions
+export const toggleToShelfSelection = (shelfId: string) => {
+ const currentWizard = $wizardStore.get();
+ const newSelectedToShelfIds = new Set(currentWizard.selectedToShelfIds);
+
+ if (newSelectedToShelfIds.has(shelfId)) {
+ newSelectedToShelfIds.delete(shelfId);
+ // Remove all lines that have this toShelfId
+ const updatedLines = currentWizard.lines.filter(
+ (line) => line.toShelfId !== shelfId
+ );
+ $wizardStore.set({
+ selectedToShelfIds: newSelectedToShelfIds,
+ lines: updatedLines,
+ });
+ } else {
+ newSelectedToShelfIds.add(shelfId);
+ $wizardStore.set({
+ ...currentWizard,
+ selectedToShelfIds: newSelectedToShelfIds,
+ });
+ }
+};
+
+export const isToShelfSelected = (shelfId: string) => {
+ const currentWizard = $wizardStore.get();
+ return currentWizard.selectedToShelfIds.has(shelfId);
+};
+
+export const addTransferLine = (line: StockTransferWizardLine) => {
+ const currentWizard = $wizardStore.get();
+
+ // Check if a line with same itemId, fromShelfId and toShelfId already exists
+ const existingLineIndex = currentWizard.lines.findIndex(
+ (l) =>
+ l.itemId === line.itemId &&
+ l.fromShelfId === line.fromShelfId &&
+ l.toShelfId === line.toShelfId
+ );
+
+ if (existingLineIndex >= 0) {
+ // Update existing line
+ const updatedLines = [...currentWizard.lines];
+ updatedLines[existingLineIndex] = {
+ ...updatedLines[existingLineIndex],
+ ...line,
+ };
+ $wizardStore.set({ ...currentWizard, lines: updatedLines });
+ } else {
+ // Add new line
+ $wizardStore.set({
+ ...currentWizard,
+ lines: [...currentWizard.lines, line],
+ });
+ }
+};
+
+export const removeTransferLine = (
+ itemId: string,
+ fromShelfId: string,
+ toShelfId: string
+) => {
+ const currentWizard = $wizardStore.get();
+ const updatedLines = currentWizard.lines.filter(
+ (line) =>
+ !(
+ line.itemId === itemId &&
+ line.fromShelfId === fromShelfId &&
+ line.toShelfId === toShelfId
+ )
+ );
+ $wizardStore.set({ ...currentWizard, lines: updatedLines });
+};
+
+export const hasTransferLine = (
+ itemId: string,
+ fromShelfId: string,
+ toShelfId: string
+) => {
+ const currentWizard = $wizardStore.get();
+ return currentWizard.lines.some(
+ (line) =>
+ line.itemId === itemId &&
+ line.fromShelfId === fromShelfId &&
+ line.toShelfId === toShelfId
+ );
+};
+
+export const hasTransferLinesToShelf = (shelfId: string) => {
+ const currentWizard = $wizardStore.get();
+ return currentWizard.lines.some(
+ (line) => line.toShelfId === shelfId && (line.quantity ?? 0) > 0
+ );
+};
+
+export const updateTransferLineQuantity = (
+ itemId: string,
+ fromShelfId: string,
+ toShelfId: string,
+ quantity: number
+) => {
+ const currentWizard = $wizardStore.get();
+ const lineIndex = currentWizard.lines.findIndex(
+ (line) =>
+ line.itemId === itemId &&
+ line.fromShelfId === fromShelfId &&
+ line.toShelfId === toShelfId
+ );
+
+ if (lineIndex >= 0) {
+ const updatedLines = [...currentWizard.lines];
+ updatedLines[lineIndex] = {
+ ...updatedLines[lineIndex],
+ quantity,
+ };
+ $wizardStore.set({ ...currentWizard, lines: updatedLines });
+ }
+};
+
+export const clearStockTransferWizard = () => {
+ $wizardStore.set({
+ selectedToShelfIds: new Set(),
+ lines: [],
+ });
+};
+
+export const clearSelectedToShelves = () => {
+ const currentWizard = $wizardStore.get();
+ $wizardStore.set({
+ ...currentWizard,
+ selectedToShelfIds: new Set(),
+ });
+};
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 3d9f5fc16b..61bfd5bbb6 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -583,7 +583,7 @@ export const path = {
deletePaymentTerm: (id: string) =>
generatePath(`${x}/accounting/payment-terms/delete/${id}`),
deleteStockTransfer: (id: string) =>
- generatePath(`${x}/inventory/stock-transfers/${id}/delete`),
+ generatePath(`${x}/stock-transfer/${id}/delete`),
deleteProcedure: (id: string) =>
generatePath(`${x}/procedure/delete/${id}`),
deleteProcedureStep: (id: string, stepId: string) =>
@@ -934,7 +934,7 @@ export const path = {
newPart: `${x}/part/new`,
newPartSupplier: (id: string) =>
generatePath(`${x}/part/${id}/view/purchasing/new`),
- newStockTransfer: `${x}/inventory/stock-transfers/new`,
+ newStockTransfer: `${x}/stock-transfer/new`,
newProcedure: `${x}/production/procedures/new`,
newProcedureStep: (id: string) =>
generatePath(`${x}/procedure/${id}/steps/new`),
@@ -1058,12 +1058,11 @@ export const path = {
personDetails: (id: string) => generatePath(`${x}/person/${id}/details`),
personJob: (id: string) => generatePath(`${x}/person/${id}/job`),
stockTransfers: `${x}/inventory/stock-transfers`,
- stockTransfer: (id: string) =>
- generatePath(`${x}/inventory/stock-transfers/${id}`),
+ stockTransfer: (id: string) => generatePath(`${x}/stock-transfer/${id}`),
stockTransferDetails: (id: string) =>
- generatePath(`${x}/inventory/stock-transfers/${id}/details`),
+ generatePath(`${x}/stock-transfer/${id}/details`),
stockTransferStatus: (id: string) =>
- generatePath(`${x}/inventory/stock-transfers/${id}/status`),
+ generatePath(`${x}/stock-transfer/${id}/status`),
procedure: (id: string) => generatePath(`${x}/procedure/${id}`),
procedureStep: (id: string, attributeId: string) =>
generatePath(`${x}/procedure/${id}/steps/${attributeId}`),
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 9ac91e9cd1..90b46f56bf 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -58046,6 +58046,74 @@ export default {
tags: ["(rpc) xid_time"],
},
},
+ "/rpc/get_item_shelf_requirements_by_location": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "company_id",
+ required: true,
+ type: "string",
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "location_id",
+ required: true,
+ type: "string",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_item_shelf_requirements_by_location"],
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ company_id: {
+ format: "text",
+ type: "string",
+ },
+ location_id: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["company_id", "location_id"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_item_shelf_requirements_by_location"],
+ },
+ },
"/rpc/get_sales_order_lines_by_customer_id": {
get: {
parameters: [
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 32c47683a0..8291597d88 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -41523,14 +41523,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -45413,14 +45413,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -48588,6 +48588,49 @@ export type Database = {
quantity: number
}[]
}
+ get_item_shelf_requirements_by_location: {
+ Args: {
+ company_id: string
+ location_id: string
+ }
+ Returns: {
+ itemId: string
+ itemReadableId: string
+ name: string
+ description: string
+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
+ type: Database["public"]["Enums"]["itemType"]
+ thumbnailPath: string
+ unitOfMeasureCode: string
+ quantityOnHandInShelf: number
+ quantityRequiredByShelf: number
+ shelfId: string
+ shelfName: string
+ isDefaultShelf: boolean
+ }[]
+ }
+ get_item_shelf_requirements_by_location_and_item: {
+ Args: {
+ company_id: string
+ location_id: string
+ item_id?: string
+ }
+ Returns: {
+ itemId: string
+ itemReadableId: string
+ name: string
+ description: string
+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
+ type: Database["public"]["Enums"]["itemType"]
+ thumbnailPath: string
+ unitOfMeasureCode: string
+ quantityOnHandInShelf: number
+ quantityRequiredByShelf: number
+ shelfId: string
+ shelfName: string
+ isDefaultShelf: boolean
+ }[]
+ }
get_job_method: {
Args: {
jid: string
diff --git a/packages/database/supabase/functions/lib/seed.ts b/packages/database/supabase/functions/lib/seed.ts
index 52881c6801..73b3dd7640 100644
--- a/packages/database/supabase/functions/lib/seed.ts
+++ b/packages/database/supabase/functions/lib/seed.ts
@@ -1888,6 +1888,15 @@ export const sequences = [
size: 6,
step: 1,
},
+ {
+ table: "stockTransfer",
+ name: "Stock Transfer",
+ prefix: "ST",
+ suffix: null,
+ next: 0,
+ size: 6,
+ step: 1,
+ },
{
table: "quote",
name: "Quote",
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 32c47683a0..8291597d88 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -41523,14 +41523,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -45413,14 +45413,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -48588,6 +48588,49 @@ export type Database = {
quantity: number
}[]
}
+ get_item_shelf_requirements_by_location: {
+ Args: {
+ company_id: string
+ location_id: string
+ }
+ Returns: {
+ itemId: string
+ itemReadableId: string
+ name: string
+ description: string
+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
+ type: Database["public"]["Enums"]["itemType"]
+ thumbnailPath: string
+ unitOfMeasureCode: string
+ quantityOnHandInShelf: number
+ quantityRequiredByShelf: number
+ shelfId: string
+ shelfName: string
+ isDefaultShelf: boolean
+ }[]
+ }
+ get_item_shelf_requirements_by_location_and_item: {
+ Args: {
+ company_id: string
+ location_id: string
+ item_id?: string
+ }
+ Returns: {
+ itemId: string
+ itemReadableId: string
+ name: string
+ description: string
+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
+ type: Database["public"]["Enums"]["itemType"]
+ thumbnailPath: string
+ unitOfMeasureCode: string
+ quantityOnHandInShelf: number
+ quantityRequiredByShelf: number
+ shelfId: string
+ shelfName: string
+ isDefaultShelf: boolean
+ }[]
+ }
get_job_method: {
Args: {
jid: string
diff --git a/packages/database/supabase/migrations/20251007014240_stock-transfers.sql b/packages/database/supabase/migrations/20251007014240_stock-transfers.sql
index d9a070c4f8..761784d0d4 100644
--- a/packages/database/supabase/migrations/20251007014240_stock-transfers.sql
+++ b/packages/database/supabase/migrations/20251007014240_stock-transfers.sql
@@ -217,3 +217,14 @@ FOR DELETE USING (
)
);
+INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step", "companyId")
+SELECT
+ 'stockTransfer',
+ 'Stock Transfer',
+ 'ST',
+ NULL,
+ 0,
+ 6,
+ 1,
+ "id"
+FROM "company";
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20251013212930_stock-transfer-wizard-view.sql b/packages/database/supabase/migrations/20251013212930_stock-transfer-wizard-view.sql
new file mode 100644
index 0000000000..7d38d74202
--- /dev/null
+++ b/packages/database/supabase/migrations/20251013212930_stock-transfer-wizard-view.sql
@@ -0,0 +1,205 @@
+DROP FUNCTION IF EXISTS get_item_shelf_requirements_by_location;
+CREATE OR REPLACE FUNCTION get_item_shelf_requirements_by_location(company_id TEXT, location_id TEXT)
+ RETURNS TABLE (
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "name" TEXT,
+ "description" TEXT,
+ "itemTrackingType" "itemTrackingType",
+ "type" "itemType",
+ "thumbnailPath" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "quantityOnHandInShelf" NUMERIC,
+ "quantityRequiredByShelf" NUMERIC,
+ "shelfId" TEXT,
+ "shelfName" TEXT,
+ "isDefaultShelf" BOOLEAN
+ ) AS $$
+ BEGIN
+ RETURN QUERY
+
+WITH
+ item_shelves AS (
+ SELECT DISTINCT
+ il."itemId",
+ il."shelfId"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ ),
+ open_job_requirements_in_shelf AS (
+ SELECT
+ jm."itemId",
+ jm."shelfId",
+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemandInShelf"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make'
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ GROUP BY jm."itemId", jm."shelfId"
+ ),
+ item_ledgers_in_shelf AS (
+ SELECT
+ il."itemId" AS "ledgerItemId",
+ il."shelfId",
+ SUM(il."quantity") AS "quantityOnHandInShelf"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ GROUP BY il."itemId", il."shelfId"
+ ),
+ items_with_activity AS (
+ SELECT DISTINCT active_items."itemId", active_items."shelfId"
+ FROM (
+ SELECT ils."ledgerItemId" AS "itemId", ils."shelfId"
+ FROM item_ledgers_in_shelf ils
+ WHERE ils."quantityOnHandInShelf" > 0
+
+ UNION
+
+ SELECT ojis."itemId", ojis."shelfId"
+ FROM open_job_requirements_in_shelf ojis
+ WHERE ojis."quantityOnProductionDemandInShelf" > 0
+ ) active_items
+ )
+
+SELECT
+ ish."itemId",
+ i."readableId" AS "itemReadableId",
+ i."name",
+ i."name" AS "description",
+ i."itemTrackingType",
+ i."type",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ COALESCE(ils."quantityOnHandInShelf", 0) AS "quantityOnHandInShelf",
+ COALESCE(ojis."quantityOnProductionDemandInShelf", 0) AS "quantityRequiredByShelf",
+ ish."shelfId",
+ s."name" AS "shelfName",
+ COALESCE(pm."defaultShelfId" = ish."shelfId", false) AS "isDefaultShelf"
+FROM
+ items_with_activity ish
+ INNER JOIN "item" i ON i."id" = ish."itemId"
+ LEFT JOIN "shelf" s ON s."id" = ish."shelfId"
+ LEFT JOIN item_ledgers_in_shelf ils ON i."id" = ils."ledgerItemId" AND ish."shelfId" IS NOT DISTINCT FROM ils."shelfId"
+ LEFT JOIN open_job_requirements_in_shelf ojis ON i."id" = ojis."itemId" AND ish."shelfId" IS NOT DISTINCT FROM ojis."shelfId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "pickMethod" pm ON pm."itemId" = i."id" AND pm."locationId" = location_id
+ORDER BY (COALESCE(ils."quantityOnHandInShelf", 0) - COALESCE(ojis."quantityOnProductionDemandInShelf", 0)) ASC;
+ END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+
+DROP FUNCTION IF EXISTS get_item_shelf_requirements_by_location_and_item;
+CREATE OR REPLACE FUNCTION get_item_shelf_requirements_by_location_and_item(company_id TEXT, location_id TEXT, item_id TEXT DEFAULT NULL)
+ RETURNS TABLE (
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "name" TEXT,
+ "description" TEXT,
+ "itemTrackingType" "itemTrackingType",
+ "type" "itemType",
+ "thumbnailPath" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "quantityOnHandInShelf" NUMERIC,
+ "quantityRequiredByShelf" NUMERIC,
+ "shelfId" TEXT,
+ "shelfName" TEXT,
+ "isDefaultShelf" BOOLEAN
+ ) AS $$
+ BEGIN
+ RETURN QUERY
+
+WITH
+ item_shelves AS (
+ SELECT DISTINCT
+ il."itemId",
+ il."shelfId"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ ),
+ open_job_requirements_in_shelf AS (
+ SELECT
+ jm."itemId",
+ jm."shelfId",
+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemandInShelf"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make'
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ AND (item_id IS NULL OR jm."itemId" = item_id)
+ GROUP BY jm."itemId", jm."shelfId"
+ ),
+ item_ledgers_in_shelf AS (
+ SELECT
+ il."itemId" AS "ledgerItemId",
+ il."shelfId",
+ SUM(il."quantity") AS "quantityOnHandInShelf"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ GROUP BY il."itemId", il."shelfId"
+ ),
+ items_with_activity AS (
+ SELECT DISTINCT active_items."itemId", active_items."shelfId"
+ FROM (
+ SELECT ils."ledgerItemId" AS "itemId", ils."shelfId"
+ FROM item_ledgers_in_shelf ils
+ WHERE ils."quantityOnHandInShelf" > 0
+
+ UNION
+
+ SELECT ojis."itemId", ojis."shelfId"
+ FROM open_job_requirements_in_shelf ojis
+ WHERE ojis."quantityOnProductionDemandInShelf" > 0
+ ) active_items
+ )
+
+SELECT
+ ish."itemId",
+ i."readableId" AS "itemReadableId",
+ i."name",
+ i."name" AS "description",
+ i."itemTrackingType",
+ i."type",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ COALESCE(ils."quantityOnHandInShelf", 0) AS "quantityOnHandInShelf",
+ COALESCE(ojis."quantityOnProductionDemandInShelf", 0) AS "quantityRequiredByShelf",
+ ish."shelfId",
+ s."name" AS "shelfName",
+ COALESCE(pm."defaultShelfId" = ish."shelfId", false) AS "isDefaultShelf"
+FROM
+ items_with_activity ish
+ INNER JOIN "item" i ON i."id" = ish."itemId"
+ LEFT JOIN "shelf" s ON s."id" = ish."shelfId"
+ LEFT JOIN item_ledgers_in_shelf ils ON i."id" = ils."ledgerItemId" AND ish."shelfId" IS NOT DISTINCT FROM ils."shelfId"
+ LEFT JOIN open_job_requirements_in_shelf ojis ON i."id" = ojis."itemId" AND ish."shelfId" IS NOT DISTINCT FROM ojis."shelfId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "pickMethod" pm ON pm."itemId" = i."id" AND pm."locationId" = location_id
+ORDER BY (COALESCE(ils."quantityOnHandInShelf", 0) - COALESCE(ojis."quantityOnProductionDemandInShelf", 0)) DESC;
+ END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;