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 component for editing line item in stock transfer

Brad Barbina52801fa308b
diff --git a/apps/erp/app/components/Form/Shelf.tsx b/apps/erp/app/components/Form/Shelf.tsx
index 48c96cdf9f..fdfdc55052 100644
--- a/apps/erp/app/components/Form/Shelf.tsx
+++ b/apps/erp/app/components/Form/Shelf.tsx
@@ -13,6 +13,7 @@ type ShelfSelectProps = Omit<
"options" | "onChange" | "inline"
> & {
locationId?: string;
+ itemId?: string;
inline?: boolean;
onChange?: (shelf: ListItem | null) => void;
};
@@ -31,7 +32,7 @@ const Shelf = (props: ShelfSelectProps) => {
const [created, setCreated] = useState<string>("");
const triggerRef = useRef<HTMLButtonElement>(null);
- const { options, data } = useShelves(props.locationId);
+ const { options, data } = useShelves(props.locationId, props.itemId);
const onChange = (newValue: { label: string; value: string } | null) => {
const shelf =
@@ -71,22 +72,32 @@ const Shelf = (props: ShelfSelectProps) => {
export default Shelf;
-export function useShelves(locationId?: string) {
+export function useShelves(locationId?: string, itemId?: string) {
const shelvesFetcher =
useFetcher<Awaited<ReturnType<typeof getShelvesList>>>();
useEffect(() => {
if (locationId) {
- shelvesFetcher.load(path.to.api.shelves(locationId));
+ if (itemId) {
+ // Use the new API route for shelves with quantities
+ shelvesFetcher.load(
+ path.to.api.shelvesWithQuantities(locationId, itemId)
+ );
+ } else {
+ // Use the existing API route for all shelves
+ shelvesFetcher.load(path.to.api.shelves(locationId));
+ }
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [locationId]);
+ }, [locationId, itemId]);
const options = useMemo(
() =>
shelvesFetcher.data?.data?.map((c) => ({
value: c.id,
label: c.name,
+ // Add quantity as helper text if available
+ ...(c.quantity !== undefined && { helper: `Qty: ${c.quantity}` }),
})) ?? [],
[shelvesFetcher.data]
);
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.ts
index 02e07a3f5e..4a05845f42 100644
--- a/apps/erp/app/modules/inventory/inventory.models.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.ts
@@ -305,8 +305,6 @@ export const stockTransferValidator = z.object({
export const stockTransferLineValidator = z.object({
id: zfd.text(z.string().optional()),
stockTransferId: z.string().min(1, { message: "Pick list is required" }),
- jobId: zfd.text(z.string().optional()),
- jobMaterialId: zfd.text(z.string().optional()),
itemId: z.string().min(1, { message: "Item is required" }),
fromShelfId: zfd.text(z.string().optional()),
toShelfId: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 6b3a78d3cd..5788c773b8 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -17,6 +17,7 @@ import type {
shelfValidator,
shipmentValidator,
shippingMethodValidator,
+ stockTransferValidator,
warehouseTransferValidator,
} from "./inventory.models";
@@ -27,20 +28,6 @@ export async function deleteBatchProperty(
return client.from("batchProperty").delete().eq("id", id);
}
-export async function deleteWarehouseTransfer(
- client: SupabaseClient<Database>,
- transferId: string
-) {
- return client.from("warehouseTransfer").delete().eq("id", transferId);
-}
-
-export async function deleteWarehouseTransferLine(
- client: SupabaseClient<Database>,
- transferLineId: string
-) {
- return client.from("warehouseTransferLine").delete().eq("id", transferLineId);
-}
-
export async function deleteKanban(
client: SupabaseClient<Database>,
kanbanId: string
@@ -93,6 +80,37 @@ export async function deleteShippingMethod(
.eq("id", shippingMethodId);
}
+export async function deleteStockTransfer(
+ client: SupabaseClient<Database>,
+ stockTransferId: string
+) {
+ return client.from("stockTransfer").delete().eq("id", stockTransferId);
+}
+
+export async function deleteStockTransferLine(
+ client: SupabaseClient<Database>,
+ stockTransferLineId: string
+) {
+ return client
+ .from("stockTransferLine")
+ .delete()
+ .eq("id", stockTransferLineId);
+}
+
+export async function deleteWarehouseTransfer(
+ client: SupabaseClient<Database>,
+ transferId: string
+) {
+ return client.from("warehouseTransfer").delete().eq("id", transferId);
+}
+
+export async function deleteWarehouseTransferLine(
+ client: SupabaseClient<Database>,
+ transferLineId: string
+) {
+ return client.from("warehouseTransferLine").delete().eq("id", transferLineId);
+}
+
export async function getItemLedgerPage(
client: SupabaseClient<Database>,
itemId: string,
@@ -235,6 +253,39 @@ export async function getKanban(
return client.from("kanbans").select("*").eq("id", kanbanId).single();
}
+export async function getStockTransfer(
+ client: SupabaseClient<Database>,
+ stockTransferId: string
+) {
+ return client
+ .from("stockTransfer")
+ .select("*")
+ .eq("id", stockTransferId)
+ .single();
+}
+
+export async function getStockTransferLines(
+ client: SupabaseClient<Database>,
+ stockTransferId: string
+) {
+ return client
+ .from("stockTransferLines")
+ .select("*")
+ .eq("stockTransferId", stockTransferId);
+}
+
+export async function getStockTransferTracking(
+ client: SupabaseClient<Database>,
+ stockTransferId: string,
+ companyId: string
+) {
+ return client
+ .from("trackedEntity")
+ .select("*")
+ .eq("attributes ->> Stock Transfer", stockTransferId)
+ .eq("companyId", companyId);
+}
+
export async function getStockTransfers(
client: SupabaseClient<Database>,
companyId: string,
@@ -264,6 +315,41 @@ export async function getStockTransfers(
return query;
}
+export async function getDefaultShelfOrShelfWithHighestQuantity(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ locationId: string,
+ companyId: string
+) {
+ const pickMethod = await client
+ .from("pickMethod")
+ .select("defaultShelfId")
+ .eq("itemId", itemId)
+ .eq("locationId", locationId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (pickMethod.data?.defaultShelfId) return pickMethod.data.defaultShelfId;
+
+ const shelves = await getItemShelfQuantities(
+ client,
+ itemId,
+ companyId,
+ locationId
+ );
+
+ const shelfWithHighestQuantity = shelves.data?.reduce(
+ (acc, curr) => {
+ return acc.quantity > curr.quantity
+ ? acc
+ : { ...curr, quantity: acc.quantity, shelfId: acc.shelfId };
+ },
+ { quantity: 0, shelfId: null }
+ );
+
+ return shelfWithHighestQuantity?.shelfId ?? null;
+}
+
export async function getReceipts(
client: SupabaseClient<Database>,
companyId: string,
@@ -913,6 +999,28 @@ export async function updateBatchPropertyOrder(
return client.from("batchProperty").update(sanitize(data)).eq("id", data.id);
}
+export async function updateStockTransferStatus(
+ client: SupabaseClient<Database>,
+ args: {
+ id: string;
+ status: Database["public"]["Enums"]["stockTransferStatus"];
+ assignee?: string | null;
+ completedAt: string | null;
+ updatedBy: string;
+ }
+) {
+ const { id, status, assignee, completedAt, updatedBy } = args;
+ return client
+ .from("stockTransfer")
+ .update({
+ status,
+ assignee,
+ completedAt,
+ updatedBy,
+ })
+ .eq("id", id);
+}
+
export async function upsertBatchProperty(
client: SupabaseClient<Database>,
batchProperty: z.infer<typeof batchPropertyValidator> & {
@@ -940,6 +1048,40 @@ export async function upsertBatchProperty(
});
}
+export async function upsertKanban(
+ client: SupabaseClient<Database>,
+ kanban:
+ | (Omit<z.infer<typeof kanbanValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof kanbanValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in kanban) {
+ return client
+ .from("kanban")
+ .insert({
+ ...kanban,
+ })
+ .select("id")
+ .single();
+ }
+ return client
+ .from("kanban")
+ .update({
+ ...sanitize(kanban),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("id", kanban.id)
+ .select("id")
+ .single();
+}
+
export async function upsertReceipt(
client: SupabaseClient<Database>,
receipt:
@@ -1064,39 +1206,60 @@ export async function upsertShipment(
.single();
}
-export async function upsertKanban(
+export async function upsertStockTransfer(
client: SupabaseClient<Database>,
- kanban:
- | (Omit<z.infer<typeof kanbanValidator>, "id"> & {
+ stockTransfer:
+ | {
+ locationId: string;
+ stockTransferId: string;
companyId: string;
createdBy: string;
customFields?: Json;
- })
- | (Omit<z.infer<typeof kanbanValidator>, "id"> & {
+ }
+ | {
id: string;
+ locationId: string;
+ stockTransferId: string;
+ companyId: string;
updatedBy: string;
customFields?: Json;
- })
+ }
) {
- if ("createdBy" in kanban) {
+ if ("createdBy" in stockTransfer) {
return client
- .from("kanban")
- .insert({
- ...kanban,
- })
+ .from("stockTransfer")
+ .insert(stockTransfer)
.select("id")
.single();
}
return client
- .from("kanban")
- .update({
- ...sanitize(kanban),
- updatedAt: today(getLocalTimeZone()).toString(),
- })
- .eq("id", kanban.id)
+ .from("stockTransfer")
+ .update(sanitize(stockTransfer))
+ .eq("id", stockTransfer.id)
.select("id")
.single();
}
+
+export async function upsertStockTransferLines(
+ client: SupabaseClient<Database>,
+ args: {
+ lines: z.infer<typeof stockTransferValidator>["lines"];
+ stockTransferId: string;
+ companyId: string;
+ createdBy: string;
+ }
+) {
+ const { lines, stockTransferId, companyId, createdBy } = args;
+ return client.from("stockTransferLine").insert(
+ lines.map((line) => ({
+ ...line,
+ stockTransferId,
+ companyId,
+ createdBy,
+ }))
+ );
+}
+
export async function upsertWarehouseTransfer(
client: SupabaseClient<Database>,
transfer:
diff --git a/apps/erp/app/modules/inventory/types.ts b/apps/erp/app/modules/inventory/types.ts
index 113218fae3..bbd3965716 100644
--- a/apps/erp/app/modules/inventory/types.ts
+++ b/apps/erp/app/modules/inventory/types.ts
@@ -11,6 +11,7 @@ import type {
getShipmentTracking,
getShipments,
getShippingMethods,
+ getStockTransferLines,
getStockTransfers,
getTrackedEntities,
getWarehouseTransferLines,
@@ -33,16 +34,12 @@ export type ItemTracking = NonNullable<
Awaited<ReturnType<typeof getReceiptTracking>>["data"]
>[number];
-export type Receipt = NonNullable<
- Awaited<ReturnType<typeof getReceipts>>["data"]
->[number];
-
export type Kanban = NonNullable<
Awaited<ReturnType<typeof getKanbans>>["data"]
>[number];
-export type StockTransfer = NonNullable<
- Awaited<ReturnType<typeof getStockTransfers>>["data"]
+export type Receipt = NonNullable<
+ Awaited<ReturnType<typeof getReceipts>>["data"]
>[number];
export type ReceiptLine = NonNullable<
@@ -78,6 +75,14 @@ export type ShippingMethod = NonNullable<
export type ShipmentSourceDocument =
Database["public"]["Enums"]["shipmentSourceDocument"];
+export type StockTransfer = NonNullable<
+ Awaited<ReturnType<typeof getStockTransfers>>["data"]
+>[number];
+
+export type StockTransferLine = NonNullable<
+ Awaited<ReturnType<typeof getStockTransferLines>>["data"]
+>[number];
+
export type TrackedEntity = NonNullable<
Awaited<ReturnType<typeof getTrackedEntities>>["data"]
>[number];
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
index d56bcd1f1b..dec8595d8d 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
@@ -497,6 +497,7 @@ function ShipmentLineItem({
<Shelf
locationId={line.locationId}
shelfId={line.shelfId}
+ itemId={line.itemId}
isReadOnly={isReadOnly}
onChange={(shelf) => {
onUpdate({
@@ -1127,34 +1128,38 @@ function SplitShipmentLineModal({
function Shelf({
locationId,
shelfId,
+ itemId,
isReadOnly,
onChange,
}: {
locationId: string | null;
shelfId: string | null;
+ itemId: string | null;
isReadOnly: boolean;
onChange: (shelf: string) => void;
}) {
- const { options } = useShelves(locationId ?? undefined);
+ const { options } = useShelves(locationId ?? undefined, itemId ?? undefined);
if (!locationId) return null;
return (
- <div className="flex flex-col items-start gap-1 min-w-[140px] text-sm">
+ <VStack spacing={1} className="min-w-[140px] text-sm">
<label className="text-xs text-muted-foreground">Shelf</label>
- <Combobox
- value={shelfId ?? undefined}
- onChange={(newValue) => {
- onChange(newValue);
- }}
- options={options}
- isReadOnly={isReadOnly}
- inline={(value, options) => {
- const option = options.find((o) => o.value === value);
- return option?.label ?? "";
- }}
- />
- </div>
+ <div className="py-1">
+ <Combobox
+ value={shelfId ?? undefined}
+ onChange={(newValue) => {
+ onChange(newValue);
+ }}
+ options={options}
+ isReadOnly={isReadOnly}
+ inline={(value, options) => {
+ const option = options.find((o) => o.value === value);
+ return option?.label ?? "";
+ }}
+ />
+ </div>
+ </VStack>
);
}
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferCompleteModal.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferCompleteModal.tsx
new file mode 100644
index 0000000000..c9aa78e800
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferCompleteModal.tsx
@@ -0,0 +1,216 @@
+import { useCarbon } from "@carbon/auth";
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+ Button,
+ HStack,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ toast,
+ useMount,
+} from "@carbon/react";
+import { useRouteData } from "@carbon/remix";
+import type { TrackedEntityAttributes } from "@carbon/utils";
+import { getItemReadableId } from "@carbon/utils";
+import { useFetcher, useNavigation, useParams } from "@remix-run/react";
+import { useEffect, useRef, useState } from "react";
+import { LuTriangleAlert } from "react-icons/lu";
+import { useUser } from "~/hooks";
+import { useItems } from "~/stores";
+import { path } from "~/utils/path";
+import { getStockTransferTracking } from "../../inventory.service";
+import type { StockTransferLine } from "../../types";
+
+const StockTransferPostModal = ({ onClose }: { onClose: () => void }) => {
+ const { id } = useParams();
+ if (!id) throw new Error("id not found");
+
+ const [items] = useItems();
+ const routeData = useRouteData<{
+ stockTransferLines: StockTransferLine[];
+ }>(path.to.stockTransfer(id));
+
+ const navigation = useNavigation();
+
+ const [validated, setValidated] = useState(false);
+ const [validationErrors, setValidationErrors] = useState<
+ {
+ itemReadableId: string | null;
+ pickedQuantity: number;
+ pickedQuantityError: string;
+ }[]
+ >([]);
+
+ const { carbon } = useCarbon();
+ const {
+ company: { id: companyId },
+ } = useUser();
+
+ const validateStockTransferTracking = async () => {
+ const errors: {
+ itemReadableId: string | null;
+ pickedQuantity: number;
+ pickedQuantityError: string;
+ }[] = [];
+
+ if (!carbon) {
+ toast.error("Carbon client is not available");
+ return;
+ }
+
+ const stockTransferLineTracking = await getStockTransferTracking(
+ carbon,
+ id,
+ companyId
+ );
+
+ if (
+ routeData?.stockTransferLines.length === 0 ||
+ routeData?.stockTransferLines.every((line) => line.pickedQuantity === 0)
+ ) {
+ setValidationErrors([
+ {
+ itemReadableId: null,
+ pickedQuantity: 0,
+ pickedQuantityError: "Stock transfer is empty",
+ },
+ ]);
+ }
+
+ routeData?.stockTransferLines.forEach((line: StockTransferLine) => {
+ if (line.requiresBatchTracking) {
+ const trackedEntity = stockTransferLineTracking.data?.find(
+ (tracking) => {
+ const attributes = tracking.attributes as TrackedEntityAttributes;
+ return attributes["Stock Transfer Line"] === line.id;
+ }
+ );
+
+ if (trackedEntity?.status !== "Available") {
+ errors.push({
+ itemReadableId: getItemReadableId(items, line.itemId) ?? null,
+ pickedQuantity: line.pickedQuantity ?? 0,
+ pickedQuantityError: "Tracked entity is not available",
+ });
+ }
+ }
+
+ if (line.requiresSerialTracking) {
+ const trackedEntities = stockTransferLineTracking.data?.filter(
+ (tracking) => {
+ const attributes = tracking.attributes as TrackedEntityAttributes;
+ return attributes["Stock Transfer Line"] === line.id;
+ }
+ );
+
+ const quantityAvailable = trackedEntities?.reduce((acc, tracking) => {
+ const trackingQuantity = Number(tracking.quantity);
+
+ return acc + (tracking.status === "Available" ? trackingQuantity : 0);
+ }, 0);
+
+ if (quantityAvailable !== line.pickedQuantity) {
+ errors.push({
+ itemReadableId: getItemReadableId(items, line.itemId) ?? null,
+ pickedQuantity: line.pickedQuantity ?? 0,
+ pickedQuantityError: "Serial numbers are missing or unavailable",
+ });
+ }
+ }
+ });
+
+ setValidationErrors(errors);
+ setValidated(true);
+ };
+
+ useMount(() => {
+ validateStockTransferTracking();
+ });
+
+ const fetcher = useFetcher<{}>();
+ const submitted = useRef(false);
+ useEffect(() => {
+ if (fetcher.state === "idle" && submitted.current) {
+ onClose();
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fetcher.state]);
+
+ return (
+ <Modal
+ open={true}
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Complete Stock Transfer</ModalTitle>
+ <ModalDescription>
+ Are you sure you want to complete this stock transfer?
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ {validationErrors.length > 0 && (
+ <Alert variant="destructive">
+ <LuTriangleAlert className="h-4 w-4" />
+ <AlertTitle>Missing Information</AlertTitle>
+ <AlertDescription>
+ <ul className="list-disc pl-4 mt-2 space-y-1">
+ {validationErrors.map((error, index) => (
+ <li key={index} className="text-sm font-medium">
+ <span className="font-mono">{error.itemReadableId}</span>
+ <span className="text-muted-foreground ml-2">
+ {error.pickedQuantity}
+ </span>
+ <span className="block mt-0.5 text-red-500 font-normal">
+ {error.pickedQuantityError}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </AlertDescription>
+ </Alert>
+ )}
+ </ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Button variant="solid" onClick={onClose}>
+ Cancel
+ </Button>
+ <fetcher.Form
+ action={path.to.stockTransferComplete(id)}
+ method="post"
+ onSubmit={() => {
+ submitted.current = true;
+ }}
+ >
+ <Button
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={
+ fetcher.state !== "idle" ||
+ navigation.state !== "idle" ||
+ !validated ||
+ validationErrors.length > 0
+ }
+ type="submit"
+ >
+ Complete
+ </Button>
+ </fetcher.Form>
+ </HStack>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+};
+
+export default StockTransferPostModal;
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx
new file mode 100644
index 0000000000..171c47c852
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx
@@ -0,0 +1,204 @@
+import {
+ Button,
+ Copy,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ Heading,
+ IconButton,
+ useDisclosure,
+} from "@carbon/react";
+import { useFetcher, useParams } from "@remix-run/react";
+import {
+ LuBarcode,
+ LuCircleCheck,
+ LuCirclePlay,
+ LuEllipsisVertical,
+ LuLoaderCircle,
+ LuTrash,
+} from "react-icons/lu";
+import ConfirmDelete from "~/components/Modals/ConfirmDelete";
+import { usePermissions, useRouteData } from "~/hooks";
+import type {
+ ItemTracking,
+ StockTransfer,
+ StockTransferLine,
+} from "~/modules/inventory";
+
+import type { Result } from "@carbon/auth";
+import Assignee, { useOptimisticAssignment } from "~/components/Assignee";
+import { path } from "~/utils/path";
+import StockTransferCompleteModal from "./StockTransferCompleteModal";
+import StockTransferStatus from "./StockTransferStatus";
+
+const StockTransferHeader = () => {
+ const { id } = useParams();
+ if (!id) throw new Error("id not found");
+
+ const routeData = useRouteData<{
+ stockTransfer: StockTransfer;
+ stockTransferLines: StockTransferLine[];
+ stockTransferLineTracking: ItemTracking[];
+ }>(path.to.stockTransfer(id));
+
+ if (!routeData?.stockTransfer)
+ throw new Error("Failed to load stockTransfer");
+ const status = routeData.stockTransfer.status;
+
+ const permissions = usePermissions();
+ const postModal = useDisclosure();
+ const deleteModal = useDisclosure();
+ const statusFetcher = useFetcher<Result>();
+
+ const canComplete =
+ routeData.stockTransferLines.length > 0 &&
+ routeData.stockTransferLines.some(
+ (line) => (line.pickedQuantity ?? 0) !== 0
+ );
+
+ const isCompleted = status === "Completed";
+
+ const optimisticAssignment = useOptimisticAssignment({
+ id,
+ table: "stockTransfer",
+ });
+ const assignee =
+ optimisticAssignment !== undefined
+ ? optimisticAssignment
+ : routeData?.stockTransfer?.assignee;
+
+ 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)]">
+ <HStack className="w-full justify-between">
+ <HStack>
+ <Heading size="h4" className="flex items-center gap-2">
+ <span>{routeData?.stockTransfer?.stockTransferId}</span>
+ </Heading>
+
+ <Copy text={routeData?.stockTransfer?.stockTransferId ?? ""} />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More options"
+ icon={<LuEllipsisVertical />}
+ variant="secondary"
+ size="sm"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ disabled={
+ !permissions.can("delete", "inventory") ||
+ !permissions.is("employee")
+ }
+ destructive
+ onClick={deleteModal.onOpen}
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete Stock Transfer
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <StockTransferStatus status={routeData?.stockTransfer?.status} />
+ </HStack>
+ <HStack>
+ <Assignee
+ size="md"
+ id={id}
+ value={assignee ?? ""}
+ table="stockTransfer"
+ isReadOnly={!permissions.can("update", "inventory")}
+ />
+ <Button variant="secondary" leftIcon={<LuBarcode />} asChild>
+ <a
+ target="_blank"
+ href={path.to.file.stockTransfer(id)}
+ rel="noreferrer"
+ >
+ Pick List
+ </a>
+ </Button>
+ <statusFetcher.Form
+ method="post"
+ action={path.to.stockTransferStatus(id)}
+ >
+ <input type="hidden" name="status" value="Released" />
+ <Button
+ type="submit"
+ leftIcon={<LuCirclePlay />}
+ variant={status === "Draft" ? "primary" : "secondary"}
+ isDisabled={
+ status !== "Draft" ||
+ statusFetcher.state !== "idle" ||
+ !permissions.can("update", "inventory")
+ }
+ isLoading={
+ statusFetcher.state !== "idle" &&
+ statusFetcher.formData?.get("status") === "Released"
+ }
+ >
+ Release
+ </Button>
+ </statusFetcher.Form>
+ <Button
+ variant={canComplete && !isCompleted ? "primary" : "secondary"}
+ onClick={postModal.onOpen}
+ isDisabled={
+ !canComplete || isCompleted || !permissions.is("employee")
+ }
+ leftIcon={<LuCircleCheck />}
+ >
+ Complete
+ </Button>
+ <statusFetcher.Form
+ method="post"
+ action={path.to.stockTransferStatus(id)}
+ >
+ <input type="hidden" name="status" value="Draft" />
+ <Button
+ type="submit"
+ variant="secondary"
+ leftIcon={<LuLoaderCircle />}
+ isDisabled={
+ ["Draft"].includes(routeData?.stockTransfer?.status ?? "") ||
+ statusFetcher.state !== "idle" ||
+ !permissions.can("update", "purchasing")
+ }
+ isLoading={
+ statusFetcher.state !== "idle" &&
+ statusFetcher.formData?.get("status") === "Draft"
+ }
+ >
+ Reopen
+ </Button>
+ </statusFetcher.Form>
+ </HStack>
+ </HStack>
+ </div>
+
+ {postModal.isOpen && (
+ <StockTransferCompleteModal onClose={postModal.onClose} />
+ )}
+ {deleteModal.isOpen && (
+ <ConfirmDelete
+ action={path.to.deleteStockTransfer(id)}
+ isOpen={deleteModal.isOpen}
+ name={routeData?.stockTransfer?.id ?? "stockTransfer"}
+ text={`Are you sure you want to delete ${routeData?.stockTransfer?.id}? This cannot be undone.`}
+ onCancel={() => {
+ deleteModal.onClose();
+ }}
+ onSubmit={() => {
+ deleteModal.onClose();
+ }}
+ />
+ )}
+ </>
+ );
+};
+
+export default StockTransferHeader;
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLineForm.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLineForm.tsx
new file mode 100644
index 0000000000..d70abe6ff6
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLineForm.tsx
@@ -0,0 +1,159 @@
+import { ValidatedForm } from "@carbon/form";
+import {
+ HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ VStack,
+ toast,
+} from "@carbon/react";
+import { useFetcher, useParams } from "@remix-run/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import { useEffect, useState } from "react";
+import type { z } from "zod";
+import { Hidden, Item, Number, Shelf, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { stockTransferLineValidator } from "~/modules/inventory";
+import type { MethodItemType } from "~/modules/shared/types";
+import { useItems } from "~/stores/items";
+import { path } from "~/utils/path";
+
+type StockTransferLineFormProps = {
+ initialValues: z.infer<typeof stockTransferLineValidator>;
+ locationId: string;
+ type?: "modal" | "drawer";
+ open?: boolean;
+ onClose: (data?: { id: string; name: string }) => void;
+};
+
+const StockTransferLineForm = ({
+ initialValues,
+ locationId,
+ open = true,
+ type = "drawer",
+ onClose,
+}: StockTransferLineFormProps) => {
+ const { id } = useParams();
+ if (!id) throw new Error("id not found");
+
+ const permissions = usePermissions();
+ const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
+ const [items] = useItems();
+ const [itemId, setItemId] = useState<string | null>(
+ initialValues.itemId ?? null
+ );
+
+ const [itemType, setItemType] = useState<MethodItemType | "Item">(() => {
+ if (initialValues.itemId) {
+ return (
+ (items.find((item) => item.id === initialValues.itemId)
+ ?.type as MethodItemType) ?? "Item"
+ );
+ }
+ return "Item";
+ });
+
+ const onTypeChange = (t: MethodItemType | "Item") => {
+ setItemType(t);
+ setItemId(null);
+ };
+
+ const onItemChange = (itemId: string) => {
+ setItemId(itemId);
+ const itemType =
+ (items.find((item) => item.id === itemId)?.type as MethodItemType) ??
+ "Item";
+ setItemType(itemType);
+ };
+
+ useEffect(() => {
+ if (type !== "modal") return;
+
+ if (fetcher.state === "loading" && fetcher.data?.data) {
+ onClose?.();
+ toast.success(`Created stock transfer line`);
+ } else if (fetcher.state === "idle" && fetcher.data?.error) {
+ toast.error(
+ `Failed to create stock transfer line: ${fetcher.data.error.message}`
+ );
+ }
+ }, [fetcher.data, fetcher.state, onClose, type]);
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "inventory")
+ : !permissions.can("create", "inventory");
+
+ return (
+ <ModalDrawerProvider type={type}>
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={stockTransferLineValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.stockTransferLine(id, initialValues.id!)
+ : path.to.newStockTransferLine(id)
+ }
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>
+ {isEditing ? "Edit" : "New"} Line
+ </ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="id" />
+ <Hidden name="stockTransferId" />
+ <VStack spacing={4}>
+ <Item
+ name="itemId"
+ label={itemType}
+ // @ts-ignore
+ type={itemType}
+ onChange={(value) => {
+ onItemChange(value?.value as string);
+ }}
+ onTypeChange={onTypeChange}
+ value={itemId ?? undefined}
+ />
+ <Number name="quantity" label="Quantity" />
+ <Shelf
+ name="fromShelfId"
+ label="From Shelf"
+ locationId={locationId}
+ itemId={itemId ?? undefined}
+ />
+ <Shelf
+ name="toShelfId"
+ label="To Shelf"
+ locationId={locationId}
+ itemId={itemId ?? undefined}
+ />
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ );
+};
+
+export default StockTransferLineForm;
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx
new file mode 100644
index 0000000000..36d2165608
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx
@@ -0,0 +1,211 @@
+import {
+ Button,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ VStack,
+ cn,
+} from "@carbon/react";
+import { getItemReadableId } from "@carbon/utils";
+import { useParams } from "@remix-run/react";
+import { useMemo } from "react";
+import {
+ LuCircleCheck,
+ LuEllipsisVertical,
+ LuPencilLine,
+ LuTrash,
+} from "react-icons/lu";
+import { Empty, ItemThumbnail } from "~/components";
+import { Enumerable } from "~/components/Enumerable";
+import { useLocations } from "~/components/Form/Location";
+import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
+import { useRouteData } from "~/hooks";
+import type { StockTransfer, StockTransferLine } from "~/modules/inventory";
+import { useItems } from "~/stores";
+import { path } from "~/utils/path";
+
+export default function StockTransferLines() {
+ const params = useParams();
+ const { id } = params;
+ if (!id) throw new Error("stock transfer id not found");
+
+ const [items] = useItems();
+ const unitsOfMeasure = useUnitOfMeasure();
+ const locations = useLocations();
+
+ const routeData = useRouteData<{
+ stockTransfer: StockTransfer;
+ stockTransferLines: StockTransferLine[];
+ }>(path.to.stockTransfer(id));
+
+ const isPickable = ["Released", "In Progress"].includes(
+ routeData?.stockTransfer?.status ?? ""
+ );
+
+ const isEditable = ["Draft", "Released", "In Progress"].includes(
+ routeData?.stockTransfer?.status ?? ""
+ );
+
+ // read-only shelves; no update handler
+
+ const lines = useMemo(() => {
+ const list = routeData?.stockTransferLines ?? [];
+ return list
+ .map((line) => ({
+ ...line,
+ itemReadableId: getItemReadableId(items, line.itemId) ?? "",
+ }))
+ .sort((a, b) => a.itemReadableId.localeCompare(b.itemReadableId));
+ }, [routeData?.stockTransferLines, items]);
+
+ return (
+ <Card>
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>Stock Transfer Lines</CardTitle>
+ <CardDescription>
+ <Enumerable
+ value={
+ locations?.find(
+ (l) => l.value === routeData?.stockTransfer?.locationId
+ )?.label ?? null
+ }
+ />
+ </CardDescription>
+ </CardHeader>
+ </HStack>
+
+ <CardContent>
+ <div className="border rounded-lg">
+ {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">
+ {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}>
+ <Button
+ isDisabled={!isPickable}
+ leftIcon={<LuCircleCheck />}
+ >
+ Pick
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="secondary"
+ isDisabled={!isEditable}
+ icon={<LuEllipsisVertical />}
+ aria-label="Line options"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem>
+ <DropdownMenuIcon icon={<LuPencilLine />} />
+ Edit Line
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={!isEditable}
+ destructive
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete Line
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </HStack>
+ </div>
+ </div>
+ </div>
+ );
+ })
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
+
+// removed editable Shelf component
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferNotes.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferNotes.tsx
new file mode 100644
index 0000000000..0c28214f41
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferNotes.tsx
@@ -0,0 +1,97 @@
+import { useCarbon } from "@carbon/auth";
+import type { JSONContent } from "@carbon/react";
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ toast,
+ useDebounce,
+} from "@carbon/react";
+import { Editor, generateHTML } from "@carbon/react/Editor";
+import { getLocalTimeZone, today } from "@internationalized/date";
+import { nanoid } from "nanoid";
+import { useState } from "react";
+import { usePermissions, useUser } from "~/hooks";
+import { getPrivateUrl } from "~/utils/path";
+
+const ShipmentNotes = ({
+ id,
+ notes: initialNotes,
+}: {
+ id: string | null;
+ notes?: JSONContent;
+}) => {
+ const {
+ id: userId,
+ company: { id: companyId },
+ } = useUser();
+ const { carbon } = useCarbon();
+ const permissions = usePermissions();
+ const [notes, setNotes] = useState(initialNotes ?? {});
+
+ const onUploadImage = async (file: File) => {
+ const fileType = file.name.split(".").pop();
+ const fileName = `${companyId}/inventory/${id}/${nanoid()}.${fileType}`;
+
+ const result = await carbon?.storage.from("private").upload(fileName, file);
+
+ if (result?.error) {
+ toast.error("Failed to upload image");
+ throw new Error(result.error.message);
+ }
+
+ if (!result?.data) {
+ throw new Error("Failed to upload image");
+ }
+
+ return getPrivateUrl(result.data.path);
+ };
+
+ const onUpdateNotes = useDebounce(
+ async (content: JSONContent) => {
+ await carbon
+ ?.from("stockTransfer")
+ .update({
+ notes: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", id!);
+ },
+ 2500,
+ true
+ );
+ if (!id) return null;
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>Stock Transfer Notes</CardTitle>
+ </CardHeader>
+ <CardContent>
+ {permissions.can("update", "inventory") ? (
+ <Editor
+ initialValue={(notes ?? {}) as JSONContent}
+ onUpload={onUploadImage}
+ onChange={(value) => {
+ setNotes(value);
+ onUpdateNotes(value);
+ }}
+ />
+ ) : (
+ <div
+ className="prose dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(notes as JSONContent),
+ }}
+ />
+ )}
+ </CardContent>
+ </Card>
+ </>
+ );
+};
+
+export default ShipmentNotes;
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferStatus.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferStatus.tsx
index 44f28ff793..11fb013591 100644
--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferStatus.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferStatus.tsx
@@ -3,15 +3,9 @@ import type { stockTransferStatusType } from "~/modules/inventory";
type StockTransferStatusProps = {
status?: (typeof stockTransferStatusType)[number] | null;
- invoiced?: boolean | null;
- voided?: boolean | null;
};
-const StockTransferStatus = ({
- status,
- invoiced,
- voided,
-}: StockTransferStatusProps) => {
+const StockTransferStatus = ({ status }: StockTransferStatusProps) => {
switch (status) {
case "Draft":
return <Status color="gray">{status}</Status>;
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx
index 933bf0c575..e47ba8fff0 100644
--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx
@@ -130,7 +130,7 @@ const StockTransfersTable = memo(
accessorKey: "stockTransferId",
header: "Stock Transfer ID",
cell: ({ row }) => (
- <Hyperlink to={path.to.stockTransferDetails(row.original.id!)}>
+ <Hyperlink to={path.to.stockTransfer(row.original.id!)}>
{row.original.stockTransferId}
</Hyperlink>
),
@@ -310,8 +310,6 @@ const StockTransfersTable = memo(
left: ["shipmentId"],
}}
defaultColumnVisibility={{
- createdAt: false,
- createdBy: false,
updatedAt: false,
updatedBy: false,
}}
@@ -1066,7 +1064,7 @@ function TransferGrid({ locationId }: { locationId: string }) {
{
accessorKey: "quantityRequired",
cell: ({ row }) => formatter.format(row.original.quantityRequired),
- header: "Allocated",
+ header: "Required",
},
];
}, [formatter, allTransferToData, wizard.selectedToShelfIds, wizard.lines]);
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
index 24ad2eb89c..f50dd83cf6 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -878,7 +878,12 @@ function MaterialForm({
value={itemData.methodType}
replenishmentSystem="Buy and Make"
/>
- <Shelf name="shelfId" label="Shelf" locationId={locationId} />
+ <Shelf
+ name="shelfId"
+ label="Shelf"
+ locationId={locationId}
+ itemId={itemData.itemId}
+ />
</div>
</div>
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index 5dfaee4b7e..76325ba301 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -842,7 +842,12 @@ function MaterialForm({
value={itemData.methodType}
replenishmentSystem="Buy and Make"
/>
- <Shelf name="shelfId" label="Shelf" locationId={locationId} />
+ <Shelf
+ name="shelfId"
+ label="Shelf"
+ locationId={locationId}
+ itemId={itemData.itemId}
+ />
</div>
</div>
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
index c1e0aca906..103e69ea11 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
@@ -52,6 +52,7 @@ import {
import { useCarbon } from "@carbon/auth";
import { getItemReadableId } from "@carbon/utils";
+import { getDefaultShelfForJob } from "~/modules/inventory/inventory.service";
import { methodType } from "~/modules/shared";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
@@ -133,7 +134,7 @@ const SalesOrderLineForm = ({
const onChange = async (itemId: string) => {
if (!itemId) return;
if (!carbon || !company.id) return;
- const [item, shelf, price] = await Promise.all([
+ const [item, price] = await Promise.all([
carbon
.from("item")
.select(
@@ -142,13 +143,6 @@ const SalesOrderLineForm = ({
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- carbon
- .from("pickMethod")
- .select("defaultShelfId")
- .eq("itemId", itemId)
- .eq("companyId", company.id)
- .eq("locationId", locationId)
- .maybeSingle(),
carbon
.from("itemUnitSalePrice")
.select("unitSalePrice")
@@ -157,13 +151,18 @@ const SalesOrderLineForm = ({
.maybeSingle(),
]);
+ // Get default shelf or shelf with highest quantity
+ const defaultShelfId = locationId
+ ? await getDefaultShelfForJob(carbon, itemId, locationId, company.id)
+ : null;
+
setItemData({
itemId,
description: item.data?.name ?? "",
methodType: item.data?.defaultMethodType ?? "",
unitPrice: price.data?.unitSalePrice ?? 0,
uom: item.data?.unitOfMeasureCode ?? "EA",
- shelfId: shelf.data?.defaultShelfId ?? "",
+ shelfId: defaultShelfId ?? "",
modelUploadId: item.data?.modelUploadId ?? null,
});
};
@@ -175,17 +174,18 @@ const SalesOrderLineForm = ({
setLocationId(newLocation.value);
if (!itemData.itemId) return;
- const shelf = await carbon
- .from("pickMethod")
- .select("defaultShelfId")
- .eq("itemId", itemData.itemId)
- .eq("companyId", company.id)
- .eq("locationId", newLocation.value)
- .maybeSingle();
+
+ // Get default shelf or shelf with highest quantity for the new location
+ const defaultShelfId = await getDefaultShelfForJob(
+ carbon,
+ itemData.itemId,
+ newLocation.value,
+ company.id
+ );
setItemData((d) => ({
...d,
- shelfId: shelf?.data?.defaultShelfId ?? "",
+ shelfId: defaultShelfId ?? "",
}));
};
@@ -428,6 +428,7 @@ const SalesOrderLineForm = ({
name="shelfId"
label="Shelf"
locationId={locationId}
+ itemId={itemData.itemId}
value={itemData.shelfId ?? undefined}
onChange={(newValue) => {
if (newValue) {
diff --git a/apps/erp/app/routes/api+/inventory.shelves-with-quantities.ts b/apps/erp/app/routes/api+/inventory.shelves-with-quantities.ts
new file mode 100644
index 0000000000..96051f829e
--- /dev/null
+++ b/apps/erp/app/routes/api+/inventory.shelves-with-quantities.ts
@@ -0,0 +1,95 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ClientLoaderFunctionArgs } from "@remix-run/react";
+import type { LoaderFunctionArgs, SerializeFrom } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { getShelvesListForLocation } from "~/modules/inventory";
+import { getItemShelfQuantities } from "~/modules/items/items.service";
+import { getCompanyId, shelvesQuery } from "~/utils/react-query";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const url = new URL(request.url);
+ const locationId = url.searchParams.get("locationId");
+ const itemId = url.searchParams.get("itemId");
+
+ if (!locationId) {
+ return json({
+ data: [],
+ error: null,
+ });
+ }
+
+ // If itemId is provided, get shelves with quantities
+ if (itemId) {
+ const [shelvesResult, quantitiesResult] = await Promise.all([
+ getShelvesListForLocation(client, companyId, locationId),
+ getItemShelfQuantities(client, itemId, companyId, locationId),
+ ]);
+
+ if (shelvesResult.error || quantitiesResult.error) {
+ return json({
+ data: [],
+ error: shelvesResult.error || quantitiesResult.error,
+ });
+ }
+
+ // Filter shelves to only include those with quantities > 0
+ const quantitiesMap = new Map(
+ quantitiesResult.data?.map((q) => [q.shelfId, q.quantity]) ?? []
+ );
+
+ const shelvesWithQuantities =
+ shelvesResult.data?.filter((shelf) => {
+ const quantity = quantitiesMap.get(shelf.id);
+ return quantity && quantity > 0;
+ }) ?? [];
+
+ // Add quantity information to each shelf
+ const shelvesWithQuantityData = shelvesWithQuantities.map((shelf) => ({
+ ...shelf,
+ quantity: quantitiesMap.get(shelf.id) ?? 0,
+ }));
+
+ return json({
+ data: shelvesWithQuantityData,
+ error: null,
+ });
+ }
+
+ // If no itemId, return all shelves for the location
+ return json(await getShelvesListForLocation(client, companyId, locationId));
+}
+
+export async function clientLoader({
+ request,
+ serverLoader,
+}: ClientLoaderFunctionArgs) {
+ const companyId = getCompanyId();
+
+ if (!companyId) {
+ return await serverLoader<typeof loader>();
+ }
+
+ const url = new URL(request.url);
+ const locationId = url.searchParams.get("locationId");
+ const itemId = url.searchParams.get("itemId");
+
+ const queryKey = shelvesQuery(
+ companyId,
+ locationId ?? null,
+ itemId ?? null
+ ).queryKey;
+ const data =
+ window?.clientCache?.getQueryData<SerializeFrom<typeof loader>>(queryKey);
+
+ if (!data) {
+ const serverData = await serverLoader<typeof loader>();
+ window?.clientCache?.setQueryData(queryKey, serverData);
+ return serverData;
+ }
+
+ return data;
+}
diff --git a/apps/erp/app/routes/x+/issue+/$id.status.tsx b/apps/erp/app/routes/x+/issue+/$id.status.tsx
index 625bd1d88f..d79463eda5 100644
--- a/apps/erp/app/routes/x+/issue+/$id.status.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.status.tsx
@@ -24,7 +24,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!status || !nonConformanceStatus.includes(status)) {
throw redirect(
- path.to.quote(id),
+ requestReferrer(request) ?? path.to.issueDetails(id),
await flash(request, error(null, "Invalid status"))
);
}
@@ -40,7 +40,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
]);
if (update.error) {
throw redirect(
- requestReferrer(request) ?? path.to.quote(id),
+ requestReferrer(request) ?? path.to.issueDetails(id),
await flash(request, error(update.error, "Failed to update issue status"))
);
}
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx
index df04a6a1c6..e91e0de5b6 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx
@@ -24,7 +24,6 @@ export const handle: Handle = {
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "inventory",
- bypassRls: true,
});
const { shipmentId } = params;
diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx
new file mode 100644
index 0000000000..7d76f75ef5
--- /dev/null
+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.status.tsx
@@ -0,0 +1,55 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import {
+ stockTransferStatusType,
+ updateStockTransferStatus,
+} from "~/modules/inventory";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "inventory",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const formData = await request.formData();
+ const status = formData.get(
+ "status"
+ ) as (typeof stockTransferStatusType)[number];
+
+ if (!status || !stockTransferStatusType.includes(status)) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.stockTransfer(id),
+ await flash(request, error(null, "Invalid status"))
+ );
+ }
+
+ const [update] = await Promise.all([
+ updateStockTransferStatus(client, {
+ id,
+ status,
+ assignee: ["Completed"].includes(status) ? null : undefined,
+ completedAt: ["Completed"].includes(status)
+ ? new Date().toISOString()
+ : null,
+ updatedBy: userId,
+ }),
+ ]);
+ if (update.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.stockTransfer(id),
+ await flash(request, error(update.error, "Failed to update issue status"))
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.stockTransfer(id),
+ await flash(request, success("Updated issue status"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.tsx
new file mode 100644
index 0000000000..bc4d387277
--- /dev/null
+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.tsx
@@ -0,0 +1,85 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { JSONContent } from "@carbon/react";
+import { VStack } from "@carbon/react";
+import { useLoaderData, useParams } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { PanelProvider } from "~/components/Layout";
+import {
+ getStockTransfer,
+ getStockTransferLines,
+ getStockTransferTracking,
+} from "~/modules/inventory";
+import StockTransferHeader from "~/modules/inventory/ui/StockTransfers/StockTransferHeader";
+import StockTransferLines from "~/modules/inventory/ui/StockTransfers/StockTransferLines";
+import StockTransferNotes from "~/modules/inventory/ui/StockTransfers/StockTransferNotes";
+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 loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "inventory",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const [stockTransfer, stockTransferLines, stockTransferLineTracking] =
+ await Promise.all([
+ getStockTransfer(client, id),
+ getStockTransferLines(client, id),
+ getStockTransferTracking(client, id, companyId),
+ ]);
+
+ if (stockTransfer.error) {
+ throw redirect(
+ path.to.stockTransfers,
+ await flash(
+ request,
+ error(stockTransfer.error, "Failed to load stockTransfer")
+ )
+ );
+ }
+
+ if (stockTransfer.data.companyId !== companyId) {
+ throw redirect(path.to.stockTransfers);
+ }
+
+ return json({
+ stockTransfer: stockTransfer.data,
+ stockTransferLines: stockTransferLines.data ?? [],
+ stockTransferLineTracking: stockTransferLineTracking.data ?? [],
+ });
+}
+
+export default function StockTransferRoute() {
+ const params = useParams();
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const { stockTransfer } = useLoaderData<typeof loader>();
+
+ return (
+ <PanelProvider>
+ <div className="flex flex-col h-[calc(100dvh-49px)] overflow-hidden w-full">
+ <StockTransferHeader />
+ <div className="flex h-[calc(100dvh-99px)] overflow-y-auto scrollbar-hide w-full">
+ <VStack spacing={4} className="h-full p-4 w-full max-w-5xl mx-auto">
+ <StockTransferLines />
+ <StockTransferNotes
+ id={id}
+ notes={(stockTransfer?.notes ?? {}) as JSONContent}
+ />
+ </VStack>
+ </div>
+ </div>
+ </PanelProvider>
+ );
+}
diff --git a/apps/erp/app/routes/x+/stock-transfer+/delete.$id.tsx b/apps/erp/app/routes/x+/stock-transfer+/delete.$id.tsx
new file mode 100644
index 0000000000..abe45cca61
--- /dev/null
+++ b/apps/erp/app/routes/x+/stock-transfer+/delete.$id.tsx
@@ -0,0 +1,35 @@
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { deleteStockTransfer } from "~/modules/inventory";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "inventory",
+ });
+
+ const { id } = params;
+
+ if (!id) throw new Error("id is not found");
+
+ const mutation = await deleteStockTransfer(client, id);
+ if (mutation.error) {
+ return json(
+ {
+ success: false,
+ },
+ await flash(
+ request,
+ error(mutation.error, "Failed to delete stock transfer")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.stockTransfers,
+ await flash(request, success("Successfully deleted stock transfer"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsx b/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsx
new file mode 100644
index 0000000000..dbb4fa205d
--- /dev/null
+++ b/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsx
@@ -0,0 +1,41 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "inventory",
+ });
+
+ const formData = await request.formData();
+ const ids = formData.getAll("ids");
+ const field = formData.get("field");
+ const value = formData.get("value");
+
+ if (
+ typeof field !== "string" ||
+ (typeof value !== "string" && value !== null)
+ ) {
+ return json({ error: { message: "Invalid form data" }, data: null });
+ }
+
+ switch (field) {
+ case "fromShelfId":
+ case "toShelfId":
+ const update = await client
+ .from("stockTransferLine")
+ .update({
+ [field]: value ? value : null,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .in("id", ids as string[])
+ .eq("companyId", companyId);
+
+ return json(update);
+ default:
+ return json({
+ error: { message: `Invalid field: ${field}` },
+ data: null,
+ });
+ }
+}
diff --git a/apps/erp/app/routes/x+/stock-transfer+/new.tsx b/apps/erp/app/routes/x+/stock-transfer+/new.tsx
index a447ebf63a..04e7e74200 100644
--- a/apps/erp/app/routes/x+/stock-transfer+/new.tsx
+++ b/apps/erp/app/routes/x+/stock-transfer+/new.tsx
@@ -1,11 +1,17 @@
-import { error, getCarbonServiceRole } from "@carbon/auth";
+import { error } 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 {
+ deleteStockTransfer,
+ stockTransferValidator,
+ upsertStockTransfer,
+ upsertStockTransferLines,
+} from "~/modules/inventory";
import { getNextSequence } from "~/modules/settings";
+import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -19,8 +25,6 @@ export async function action({ request }: ActionFunctionArgs) {
create: "inventory",
});
- const serviceRole = await getCarbonServiceRole();
-
const formData = await request.formData();
const validation = await validator(stockTransferValidator).validate(formData);
@@ -29,7 +33,7 @@ export async function action({ request }: ActionFunctionArgs) {
}
const nextSequence = await getNextSequence(
- serviceRole,
+ client,
"stockTransfer",
companyId
);
@@ -43,28 +47,46 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- console.log(validation.data);
+ const { locationId, lines } = validation.data;
+
+ const createStockTransfer = await upsertStockTransfer(client, {
+ stockTransferId: nextSequence.data,
+ locationId,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
- // const createIssue = await upsertIssue(serviceRole, {
- // ...nonConformance,
- // nonConformanceId: nextSequence.data,
- // companyId,
- // createdBy: userId,
- // customFields: setCustomFields(formData),
- // });
+ if (createStockTransfer.error) {
+ throw redirect(
+ path.to.stockTransfers,
+ await flash(
+ request,
+ error(createStockTransfer.error, "Failed to create stock transfer")
+ )
+ );
+ }
- // if (createIssue.error || !createIssue.data) {
- // throw redirect(
- // path.to.issues,
- // await flash(request, error(createIssue.error, "Failed to insert issue"))
- // );
- // }
+ const createStockTransferLines = await upsertStockTransferLines(client, {
+ lines,
+ stockTransferId: createStockTransfer.data.id,
+ companyId,
+ createdBy: userId,
+ });
+
+ if (createStockTransferLines.error) {
+ await deleteStockTransfer(client, createStockTransfer.data.id);
+ throw redirect(
+ path.to.stockTransfers,
+ await flash(
+ request,
+ error(
+ createStockTransferLines.error,
+ "Failed to create stock transfer lines"
+ )
+ )
+ );
+ }
- // const ncrId = createIssue.data?.id;
- // if (!ncrId) {
- // throw redirect(
- // path.to.issues,
- // await flash(request, error("Failed to insert issue"))
- // );
- // }
+ throw redirect(path.to.stockTransfer(createStockTransfer.data.id));
}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 61bfd5bbb6..bdbfb13a8e 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -140,6 +140,12 @@ export const path = {
generatePath(`${api}/people/shifts?location=${id}`),
shelves: (id: string) =>
generatePath(`${api}/inventory/shelves?locationId=${id}`),
+ shelvesWithQuantities: (locationId: string, itemId?: string) =>
+ generatePath(
+ `${api}/inventory/shelves-with-quantities?locationId=${locationId}${
+ itemId ? `&itemId=${itemId}` : ""
+ }`
+ ),
supplierContacts: (id: string) =>
generatePath(`${api}/purchasing/supplier-contacts/${id}`),
supplierLocations: (id: string) =>
@@ -289,7 +295,8 @@ export const path = {
return generatePath(url);
},
-
+ stockTransfer: (id: string) =>
+ generatePath(`${file}/stock-transfer/${id}.pdf`),
quote: (id: string) => generatePath(`${file}/quote/${id}.pdf`),
},
legal: {
@@ -365,6 +372,7 @@ export const path = {
bulkUpdateSalesOrder: `${x}/sales-order/update`,
bulkUpdateSalesRfq: `${x}/sales-rfq/update`,
bulkUpdateShipmentLine: `${x}/shipment/lines/update`,
+ bulkUpdateStockTransferLine: `${x}/stock-transfer/lines/update`,
bulkUpdateSupplierQuote: `${x}/supplier-quote/update`,
calibrations: `${x}/quality/calibrations`,
chartOfAccount: (id: string) =>
@@ -583,7 +591,7 @@ export const path = {
deletePaymentTerm: (id: string) =>
generatePath(`${x}/accounting/payment-terms/delete/${id}`),
deleteStockTransfer: (id: string) =>
- generatePath(`${x}/stock-transfer/${id}/delete`),
+ generatePath(`${x}/stock-transfer/delete/${id}`),
deleteProcedure: (id: string) =>
generatePath(`${x}/procedure/delete/${id}`),
deleteProcedureStep: (id: string, stepId: string) =>
@@ -935,6 +943,8 @@ export const path = {
newPartSupplier: (id: string) =>
generatePath(`${x}/part/${id}/view/purchasing/new`),
newStockTransfer: `${x}/stock-transfer/new`,
+ newStockTransferLine: (id: string) =>
+ generatePath(`${x}/stock-transfer/${id}/line/new`),
newProcedure: `${x}/production/procedures/new`,
newProcedureStep: (id: string) =>
generatePath(`${x}/procedure/${id}/steps/new`),
@@ -1057,12 +1067,14 @@ export const path = {
person: (id: string) => generatePath(`${x}/person/${id}`),
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}/stock-transfer/${id}`),
- stockTransferDetails: (id: string) =>
- generatePath(`${x}/stock-transfer/${id}/details`),
+ stockTransferComplete: (id: string) =>
+ generatePath(`${x}/stock-transfer/${id}/complete`),
+ stockTransferLine: (id: string, lineId: string) =>
+ generatePath(`${x}/stock-transfer/${id}/line/${lineId}`),
stockTransferStatus: (id: string) =>
generatePath(`${x}/stock-transfer/${id}/status`),
+ stockTransfers: `${x}/inventory/stock-transfers`,
procedure: (id: string) => generatePath(`${x}/procedure/${id}`),
procedureStep: (id: string, attributeId: string) =>
generatePath(`${x}/procedure/${id}/steps/${attributeId}`),
diff --git a/apps/erp/app/utils/react-query.ts b/apps/erp/app/utils/react-query.ts
index 75147a7924..88185cee2b 100644
--- a/apps/erp/app/utils/react-query.ts
+++ b/apps/erp/app/utils/react-query.ts
@@ -70,9 +70,15 @@ export const proceduresQuery = (companyId: string | null) => ({
export const shelvesQuery = (
companyId: string | null,
- locationId: string | null
+ locationId: string | null,
+ itemId?: string | null
) => ({
- queryKey: ["shelves", companyId ?? "null", locationId ?? "null"],
+ queryKey: [
+ "shelves",
+ companyId ?? "null",
+ locationId ?? "null",
+ itemId ?? "null",
+ ],
staleTime: RefreshRate.Low,
});
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 8291597d88..54992b609b 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -30823,6 +30823,7 @@ export type Database = {
customFields: Json | null
id: string
locationId: string
+ notes: Json | null
status: Database["public"]["Enums"]["stockTransferStatus"]
stockTransferId: string
tags: string[] | null
@@ -30838,6 +30839,7 @@ export type Database = {
customFields?: Json | null
id?: string
locationId: string
+ notes?: Json | null
status?: Database["public"]["Enums"]["stockTransferStatus"]
stockTransferId: string
tags?: string[] | null
@@ -30853,6 +30855,7 @@ export type Database = {
customFields?: Json | null
id?: string
locationId?: string
+ notes?: Json | null
status?: Database["public"]["Enums"]["stockTransferStatus"]
stockTransferId?: string
tags?: string[] | null
@@ -31012,8 +31015,11 @@ export type Database = {
itemId: string
jobId: string | null
jobMaterialId: string | null
+ outstandingQuantity: number | null
pickedQuantity: number
quantity: number
+ requiresBatchTracking: boolean
+ requiresSerialTracking: boolean
stockTransferId: string
toShelfId: string | null
updatedAt: string | null
@@ -31028,8 +31034,11 @@ export type Database = {
itemId: string
jobId?: string | null
jobMaterialId?: string | null
+ outstandingQuantity?: number | null
pickedQuantity?: number
quantity?: number
+ requiresBatchTracking?: boolean
+ requiresSerialTracking?: boolean
stockTransferId: string
toShelfId?: string | null
updatedAt?: string | null
@@ -31044,8 +31053,11 @@ export type Database = {
itemId?: string
jobId?: string | null
jobMaterialId?: string | null
+ outstandingQuantity?: number | null
pickedQuantity?: number
quantity?: number
+ requiresBatchTracking?: boolean
+ requiresSerialTracking?: boolean
stockTransferId?: string
toShelfId?: string | null
updatedAt?: string | null
@@ -47030,6 +47042,229 @@ export type Database = {
},
]
}
+ stockTransferLines: {
+ Row: {
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ fromShelfId: string | null
+ fromShelfName: string | null
+ id: string | null
+ itemId: string | null
+ jobId: string | null
+ jobMaterialId: string | null
+ outstandingQuantity: number | null
+ pickedQuantity: number | null
+ quantity: number | null
+ requiresBatchTracking: boolean | null
+ requiresSerialTracking: boolean | null
+ stockTransferId: string | null
+ thumbnailPath: string | null
+ toShelfId: string | null
+ toShelfName: string | null
+ unitOfMeasure: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "stockTransferLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_fromShelfId_fkey"
+ columns: ["fromShelfId"]
+ isOneToOne: false
+ referencedRelation: "shelf"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "openProductionOrders"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "openJobMaterialLines"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_stockTransferId_fkey"
+ columns: ["stockTransferId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "stockTransfer"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_toShelfId_fkey"
+ columns: ["toShelfId"]
+ isOneToOne: false
+ referencedRelation: "shelf"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
supplierProcesses: {
Row: {
companyId: string | null
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 8291597d88..54992b609b 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -30823,6 +30823,7 @@ export type Database = {
customFields: Json | null
id: string
locationId: string
+ notes: Json | null
status: Database["public"]["Enums"]["stockTransferStatus"]
stockTransferId: string
tags: string[] | null
@@ -30838,6 +30839,7 @@ export type Database = {
customFields?: Json | null
id?: string
locationId: string
+ notes?: Json | null
status?: Database["public"]["Enums"]["stockTransferStatus"]
stockTransferId: string
tags?: string[] | null
@@ -30853,6 +30855,7 @@ export type Database = {
customFields?: Json | null
id?: string
locationId?: string
+ notes?: Json | null
status?: Database["public"]["Enums"]["stockTransferStatus"]
stockTransferId?: string
tags?: string[] | null
@@ -31012,8 +31015,11 @@ export type Database = {
itemId: string
jobId: string | null
jobMaterialId: string | null
+ outstandingQuantity: number | null
pickedQuantity: number
quantity: number
+ requiresBatchTracking: boolean
+ requiresSerialTracking: boolean
stockTransferId: string
toShelfId: string | null
updatedAt: string | null
@@ -31028,8 +31034,11 @@ export type Database = {
itemId: string
jobId?: string | null
jobMaterialId?: string | null
+ outstandingQuantity?: number | null
pickedQuantity?: number
quantity?: number
+ requiresBatchTracking?: boolean
+ requiresSerialTracking?: boolean
stockTransferId: string
toShelfId?: string | null
updatedAt?: string | null
@@ -31044,8 +31053,11 @@ export type Database = {
itemId?: string
jobId?: string | null
jobMaterialId?: string | null
+ outstandingQuantity?: number | null
pickedQuantity?: number
quantity?: number
+ requiresBatchTracking?: boolean
+ requiresSerialTracking?: boolean
stockTransferId?: string
toShelfId?: string | null
updatedAt?: string | null
@@ -47030,6 +47042,229 @@ export type Database = {
},
]
}
+ stockTransferLines: {
+ Row: {
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ fromShelfId: string | null
+ fromShelfName: string | null
+ id: string | null
+ itemId: string | null
+ jobId: string | null
+ jobMaterialId: string | null
+ outstandingQuantity: number | null
+ pickedQuantity: number | null
+ quantity: number | null
+ requiresBatchTracking: boolean | null
+ requiresSerialTracking: boolean | null
+ stockTransferId: string | null
+ thumbnailPath: string | null
+ toShelfId: string | null
+ toShelfName: string | null
+ unitOfMeasure: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "stockTransferLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_fromShelfId_fkey"
+ columns: ["fromShelfId"]
+ isOneToOne: false
+ referencedRelation: "shelf"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "openProductionOrders"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "openJobMaterialLines"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_stockTransferId_fkey"
+ columns: ["stockTransferId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "stockTransfer"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_toShelfId_fkey"
+ columns: ["toShelfId"]
+ isOneToOne: false
+ referencedRelation: "shelf"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "stockTransferLine_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
supplierProcesses: {
Row: {
companyId: string | null
diff --git a/packages/database/supabase/migrations/20251007014240_stock-transfers.sql b/packages/database/supabase/migrations/20251007014240_stock-transfers.sql
index 761784d0d4..0a3626a3c8 100644
--- a/packages/database/supabase/migrations/20251007014240_stock-transfers.sql
+++ b/packages/database/supabase/migrations/20251007014240_stock-transfers.sql
@@ -150,8 +150,12 @@ CREATE TABLE "stockTransferLine" (
"itemId" TEXT NOT NULL,
"fromShelfId" TEXT,
"toShelfId" TEXT,
- "quantity" NUMERIC(10, 4) NOT NULL DEFAULT 0,
- "pickedQuantity" NUMERIC(10, 4) NOT NULL DEFAULT 0,
+ "quantity" NUMERIC NOT NULL DEFAULT 0,
+ "pickedQuantity" NUMERIC NOT NULL DEFAULT 0,
+ "outstandingQuantity" NUMERIC GENERATED ALWAYS AS (CASE WHEN "quantity" >= "pickedQuantity" THEN "quantity" - "pickedQuantity" ELSE 0 END) STORED,
+ "requiresBatchTracking" BOOLEAN NOT NULL DEFAULT false,
+ "requiresSerialTracking" BOOLEAN NOT NULL DEFAULT false,
+ "notes" JSON DEFAULT '{}'::json,
"companyId" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"createdBy" TEXT NOT NULL,
@@ -227,4 +231,22 @@ SELECT
6,
1,
"id"
-FROM "company";
\ No newline at end of file
+FROM "company";
+
+CREATE VIEW "stockTransferLines" AS
+SELECT
+ stl.*,
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ uom."name" AS "unitOfMeasure",
+ sf."name" AS "fromShelfName",
+ st."name" AS "toShelfName"
+FROM "stockTransferLine" stl
+LEFT JOIN "item" i ON i."id" = stl."itemId"
+LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"
+LEFT JOIN "unitOfMeasure" uom ON uom."code" = i."unitOfMeasureCode" AND uom."companyId" = i."companyId"
+LEFT JOIN "shelf" sf ON sf."id" = stl."fromShelfId"
+LEFT JOIN "shelf" st ON st."id" = stl."toShelfId";
+
diff --git a/packages/utils/src/types.ts b/packages/utils/src/types.ts
index 6d582bb773..8a16903c2f 100644
--- a/packages/utils/src/types.ts
+++ b/packages/utils/src/types.ts
@@ -40,6 +40,8 @@ export interface TrackedEntityAttributes {
"Shipment Line"?: string;
Shipment?: string;
"Split Entity ID"?: string;
+ "Stock Transfer Line"?: string;
+ "Stock Transfer"?: string;
}
export interface TrackedActivityAttributes {