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: crud for warehouse transfer lines

Brad Barbin6a1d6a1f93dd
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 85b9be217e..4a120c95d9 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -906,6 +906,21 @@ export async function getWarehouseTransfer(
.single();
}
+export async function getWarehouseTransferLine(
+ client: SupabaseClient<Database>,
+ transferId: string,
+ lineId: string
+) {
+ return client
+ .from("warehouseTransferLine")
+ .select(
+ "*, warehouseTransfer(*, fromLocation:location!fromLocationId(name), toLocation:location!toLocationId(name))"
+ )
+ .eq("id", lineId)
+ .eq("transferId", transferId)
+ .single();
+}
+
export async function getWarehouseTransferLines(
client: SupabaseClient<Database>,
transferId: string
@@ -991,7 +1006,6 @@ export async function upsertWarehouseTransferLine(
})
) {
if ("id" in line && line.id) {
- // Update existing line
const { id, ...updateData } = line;
return client
.from("warehouseTransferLine")
@@ -1003,7 +1017,6 @@ export async function upsertWarehouseTransferLine(
.select()
.single();
} else {
- // Insert new line
return client
.from("warehouseTransferLine")
.insert({
diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx
index 0484fe9397..d2f1d5b1cf 100644
--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx
@@ -17,6 +17,7 @@ import {
Submit,
TextArea,
} from "~/components/Form";
+import { usePermissions } from "~/hooks";
import { warehouseTransferValidator } from "../../inventory.models";
type WarehouseTransferFormProps = {
@@ -26,7 +27,12 @@ type WarehouseTransferFormProps = {
const WarehouseTransferForm = ({
initialValues,
}: WarehouseTransferFormProps) => {
+ const permissions = usePermissions();
const isEditing = !!initialValues.id;
+ const canEdit =
+ permissions.can("update", "inventory") &&
+ ["Draft"].includes(initialValues.status ?? "");
+
return (
<ValidatedForm
validator={warehouseTransferValidator}
@@ -78,7 +84,7 @@ const WarehouseTransferForm = ({
<TextArea name="notes" label="Notes" />
- <Submit>Save Transfer</Submit>
+ <Submit disabled={!canEdit}>Save Transfer</Submit>
</VStack>
</CardContent>
</Card>
diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx
index 175ac677e2..173db43a3e 100644
--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx
@@ -23,7 +23,6 @@ import {
Shelf,
Submit,
TextArea,
- UnitOfMeasure,
} from "~/components/Form";
import { usePermissions } from "~/hooks";
import type { MethodItemType } from "~/modules/shared/types";
@@ -42,13 +41,13 @@ const warehouseTransferLineFormValidator = z.discriminatedUnion("type", [
quantity: zfd.numeric(z.number().min(0.0001)),
fromShelfId: zfd.text(z.string().optional()),
toShelfId: zfd.text(z.string().optional()),
- unitOfMeasureCode: zfd.text(z.string().optional()),
notes: zfd.text(z.string().optional()),
}),
z.object({
type: z.literal("update"),
id: z.string().min(1),
transferId: z.string().min(1),
+ itemId: z.string().min(1),
fromLocationId: z.string().min(1),
toLocationId: z.string().min(1),
quantity: zfd.numeric(z.number().min(0.0001)),
@@ -76,10 +75,9 @@ const WarehouseTransferLineForm = ({
throw new Error("transferId is required");
}
- const [itemData, setItemData] = useState<{
- itemId: string;
- unitOfMeasureCode: string;
- }>();
+ const [itemId, setItemId] = useState<string>(
+ initialValues.type === "update" ? initialValues.itemId : ""
+ );
const [items] = useItems();
const [itemType, setItemType] = useState<MethodItemType>(
@@ -92,17 +90,17 @@ const WarehouseTransferLineForm = ({
? !permissions.can("update", "inventory")
: !permissions.can("create", "inventory");
- const action = path.to.warehouseTransferLines(transferId);
+ const action = initialValues.id
+ ? path.to.warehouseTransferLine(transferId, initialValues.id)
+ : path.to.newWarehouseTransferLine(transferId);
const fetcher = useFetcher<{ success: boolean; message: string }>();
useEffect(() => {
- if (fetcher.data?.success) {
- onClose();
- } else if (fetcher.data?.message) {
+ if (fetcher.data?.success === false) {
toast.error(fetcher.data.message);
}
- }, [fetcher.data?.success, fetcher.data?.message, onClose]);
+ }, [fetcher.data?.success, fetcher.data?.message]);
return (
<Drawer
@@ -138,14 +136,9 @@ const WarehouseTransferLineForm = ({
label="Item"
type={itemType}
onTypeChange={(t) => setItemType(t as MethodItemType)}
- value={itemData?.itemId}
+ value={itemId}
onChange={(value) => {
- setItemData({
- itemId: value?.value as string,
- unitOfMeasureCode:
- items.find((item) => item.id === value?.value)
- ?.unitOfMeasureCode ?? "",
- });
+ setItemId(value?.value as string);
}}
/>
<Number
@@ -154,12 +147,6 @@ const WarehouseTransferLineForm = ({
minValue={0.0001}
step={0.0001}
/>
- <UnitOfMeasure
- name="unitOfMeasureCode"
- label="Unit of Measure"
- value={itemData?.unitOfMeasureCode}
- disabled
- />
<Shelf
name="fromShelfId"
label="From Shelf"
diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx
index a75a9d89d5..d3364ce122 100644
--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx
@@ -1,17 +1,38 @@
-import { Card, CardContent, CardHeader, CardTitle, cn } from "@carbon/react";
-import { Outlet, useNavigate } from "@remix-run/react";
-import type { ColumnDef } from "@tanstack/react-table";
-import { useMemo } from "react";
-import { ItemThumbnail } from "~/components";
import {
- EditableList,
- EditableNumber,
-} from "~/components/Editable";
-import { useShelves } from "~/components/Form/Shelf";
-import Grid from "~/components/Grid";
-import type { WarehouseTransfer, WarehouseTransferLine } from "../../types";
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Count,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ VStack,
+ cn,
+ useDisclosure,
+} from "@carbon/react";
+import { formatRelativeTime } from "@carbon/utils";
+import { Link, Outlet, useFetcher, useNavigate } from "@remix-run/react";
+import { useEffect, useRef } from "react";
+import { LuArrowRight, LuCirclePlus, LuEllipsisVertical } from "react-icons/lu";
+import { EmployeeAvatar, Empty, ItemThumbnail } from "~/components";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
+import { getItemById, getItemReadableId } from "~/utils/items";
+import { path } from "~/utils/path";
+import type { WarehouseTransfer, WarehouseTransferLine } from "../../types";
import useWarehouseTransferLines from "./useWarehouseTransferLines";
type WarehouseTransferLinesProps = {
@@ -21,123 +42,70 @@ type WarehouseTransferLinesProps = {
compact?: boolean;
};
-type TransferLine = Pick<
- WarehouseTransferLine,
- | "id"
- | "itemId"
- | "quantity"
- | "fromShelfId"
- | "toShelfId"
- | "unitOfMeasureCode"
- | "notes"
- | "customFields"
-> & {
- itemReadableId: string;
- fromShelf?: { id: string; name: string } | null;
- toShelf?: { id: string; name: string } | null;
-};
-
const WarehouseTransferLines = ({
warehouseTransferLines,
transferId,
warehouseTransfer,
compact = false,
}: WarehouseTransferLinesProps) => {
- const navigate = useNavigate();
const [items] = useItems();
- const { canEdit, onCellEdit } = useWarehouseTransferLines(warehouseTransfer);
-
- const { options: fromShelfOptions } = useShelves(warehouseTransfer.fromLocationId);
- const { options: toShelfOptions } = useShelves(warehouseTransfer.toLocationId);
-
- const linesWithReadableIds: TransferLine[] = warehouseTransferLines
- .map((line) => ({
- id: line.id,
- itemId: line.itemId,
- quantity: line.quantity,
- fromShelfId: line.fromShelfId,
- toShelfId: line.toShelfId,
- unitOfMeasureCode: line.unitOfMeasureCode,
- notes: line.notes,
- customFields: line.customFields,
- itemReadableId: getItemReadableId(items, line.itemId) ?? "",
- fromShelf: line.fromShelf,
- toShelf: line.toShelf,
- }))
- .sort((a, b) => a.itemReadableId.localeCompare(b.itemReadableId));
-
- const columns = useMemo<ColumnDef<TransferLine>[]>(() => {
- const defaultColumns: ColumnDef<TransferLine>[] = [
- {
- accessorKey: "itemId",
- header: "Item",
- cell: ({ row }) => {
- const item = items.find((p) => p.id === row.original.itemId);
- return (
- <div className="flex items-center space-x-3">
- <ItemThumbnail
- size="sm"
- thumbnailPath={item?.thumbnailPath}
- type={(item?.type as "Part") ?? "Part"}
- />
- <div className="max-w-[280px]">
- <div className="font-medium truncate">{item?.name}</div>
- <div className="text-xs text-muted-foreground truncate">
- {item?.readableIdWithRevision}
- </div>
- </div>
- </div>
- );
- },
- },
- {
- accessorKey: "quantity",
- header: "Quantity",
- cell: (item) => Number(item.getValue<number>()).toLocaleString(),
- },
- {
- accessorKey: "fromShelfId",
- header: "From Shelf",
- cell: ({ row }) => row.original.fromShelf?.name || "N/A",
- },
- {
- accessorKey: "toShelfId",
- header: "To Shelf",
- cell: ({ row }) => row.original.toShelf?.name || "N/A",
- },
- {
- accessorKey: "unitOfMeasureCode",
- header: "UoM",
- cell: (item) => item.getValue(),
- },
- ];
- return defaultColumns;
- }, [items]);
+ const { canEdit } = useWarehouseTransferLines(warehouseTransfer);
- const editableComponents = useMemo(
- () => ({
- quantity: EditableNumber(onCellEdit),
- fromShelfId: EditableList(onCellEdit, fromShelfOptions),
- toShelfId: EditableList(onCellEdit, toShelfOptions),
- }),
- [onCellEdit, fromShelfOptions, toShelfOptions]
- );
+ const sortedLines = warehouseTransferLines.sort((a, b) => {
+ const aReadableId = getItemReadableId(items, a.itemId) ?? "";
+ const bReadableId = getItemReadableId(items, b.itemId) ?? "";
+ return aReadableId.localeCompare(bReadableId);
+ });
return (
<>
<Card className={cn(compact && "border-none p-0 dark:shadow-none")}>
- <CardHeader className={cn(compact && "px-0")}>
- <CardTitle>Transfer Lines</CardTitle>
- </CardHeader>
+ <HStack className="justify-between">
+ <CardHeader className={cn(compact && "px-0")}>
+ <CardTitle className="flex flex-row items-center gap-2">
+ Transfer Lines
+ {sortedLines.length > 0 && <Count count={sortedLines.length} />}
+ </CardTitle>
+ </CardHeader>
+ {canEdit && (
+ <CardAction>
+ <Button
+ variant="secondary"
+ leftIcon={<LuCirclePlus />}
+ asChild
+ disabled={!canEdit}
+ >
+ <Link to={path.to.newWarehouseTransferLine(transferId)}>
+ Add Line
+ </Link>
+ </Button>
+ </CardAction>
+ )}
+ </HStack>
<CardContent className={cn(compact && "px-0")}>
- <Grid<TransferLine>
- contained={false}
- data={linesWithReadableIds}
- columns={columns}
- canEdit={canEdit}
- editableComponents={editableComponents}
- onNewRow={canEdit ? () => navigate("new") : undefined}
- />
+ <div className="flex flex-col gap-6">
+ {sortedLines.length > 0 && (
+ <div className="border rounded-lg">
+ {sortedLines.map((line, index) => (
+ <WarehouseTransferLineListItem
+ key={line.id}
+ line={line}
+ warehouseTransfer={warehouseTransfer}
+ isDisabled={!canEdit}
+ className={
+ index === sortedLines.length - 1 ? "border-none" : ""
+ }
+ />
+ ))}
+ </div>
+ )}
+
+ {sortedLines.length === 0 && (
+ <div className="flex flex-1 py-24 justify-center items-center w-full">
+ <Empty />
+ </div>
+ )}
+ </div>
</CardContent>
</Card>
<Outlet />
@@ -145,5 +113,186 @@ const WarehouseTransferLines = ({
);
};
+function WarehouseTransferLineListItem({
+ line,
+ warehouseTransfer,
+ isDisabled,
+ className,
+}: {
+ line: WarehouseTransferLine;
+ warehouseTransfer: WarehouseTransfer;
+ isDisabled: boolean;
+ className?: string;
+}) {
+ const deleteModalDisclosure = useDisclosure();
+
+ const [items] = useItems();
+ const navigate = useNavigate();
+
+ const item = getItemById(items, line.itemId);
+ if (!item || !line.id) return null;
+
+ const isUpdated = line.updatedBy !== null;
+ const person = isUpdated ? line.updatedBy : line.createdBy;
+ const date = line.updatedAt ?? line.createdAt;
+
+ return (
+ <div className={cn("border-b p-6", className)}>
+ <div className="flex flex-1 justify-between items-center w-full">
+ <HStack spacing={4} className="w-1/2">
+ <HStack spacing={4} className="flex-1">
+ <div className="flex items-center space-x-3">
+ <ItemThumbnail
+ size="sm"
+ thumbnailPath={line.item?.thumbnailPath}
+ type={(item.type as "Part") ?? "Part"}
+ />
+ <VStack spacing={0}>
+ <span className="text-sm font-medium truncate">
+ {item.name}
+ </span>
+ <span className="text-xs text-muted-foreground truncate">
+ {item.readableIdWithRevision}
+ </span>
+ </VStack>
+ </div>
+ <div className="flex items-center gap-2">
+ <Badge variant="secondary">
+ {Number(line.quantity).toLocaleString()}
+ </Badge>
+ {line.fromShelf && (
+ <Badge variant="outline">{line.fromShelf.name}</Badge>
+ )}
+ <LuArrowRight className="size-4" />
+ {line.toShelf && (
+ <Badge variant="outline">{line.toShelf.name}</Badge>
+ )}
+ </div>
+ </HStack>
+ </HStack>
+ <div className="flex items-center justify-end gap-2">
+ <HStack spacing={2}>
+ <span className="text-xs text-muted-foreground">
+ {isUpdated ? "Updated" : "Created"} {formatRelativeTime(date)}
+ </span>
+ <EmployeeAvatar employeeId={person} withName={false} />
+ </HStack>
+ {!isDisabled && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Open menu"
+ icon={<LuEllipsisVertical />}
+ variant="ghost"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ disabled={isDisabled}
+ onClick={() =>
+ navigate(
+ path.to.warehouseTransferLine(
+ warehouseTransfer.id,
+ line.id
+ )
+ )
+ }
+ >
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={isDisabled}
+ destructive
+ onClick={deleteModalDisclosure.onOpen}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ </div>
+
+ {deleteModalDisclosure.isOpen && (
+ <DeleteWarehouseTransferLine
+ lineId={line.id}
+ warehouseTransferId={warehouseTransfer.id}
+ itemName={item.readableIdWithRevision}
+ onCancel={() => {
+ deleteModalDisclosure.onClose();
+ }}
+ onSubmit={() => {
+ deleteModalDisclosure.onClose();
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+function DeleteWarehouseTransferLine({
+ lineId,
+ warehouseTransferId,
+ itemName,
+ onCancel,
+ onSubmit,
+}: {
+ lineId: string;
+ warehouseTransferId: string;
+ itemName: string;
+ onCancel: () => void;
+ onSubmit: () => void;
+}) {
+ const fetcher = useFetcher<{ success: boolean }>();
+ const submitted = useRef(false);
+
+ useEffect(() => {
+ if (submitted.current && fetcher.state === "idle") {
+ onSubmit();
+ submitted.current = false;
+ }
+ }, [fetcher.state, onSubmit]);
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onCancel();
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Delete Transfer Line</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ Are you sure you want to delete this transfer line for {itemName}?
+ This cannot be undone.
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onCancel}>
+ Cancel
+ </Button>
+ <fetcher.Form
+ method="post"
+ action={path.to.warehouseTransferLine(warehouseTransferId, lineId)}
+ onSubmit={() => (submitted.current = true)}
+ >
+ <input type="hidden" name="type" value="delete" />
+ <input type="hidden" name="id" value={lineId} />
+ <Button
+ variant="destructive"
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={fetcher.state !== "idle"}
+ type="submit"
+ >
+ Delete
+ </Button>
+ </fetcher.Form>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+}
-export default WarehouseTransferLines;
\ No newline at end of file
+export default WarehouseTransferLines;
diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/useWarehouseTransferLines.ts b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/useWarehouseTransferLines.ts
index 7c1df2d0fc..ccc5ae4a63 100644
--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/useWarehouseTransferLines.ts
+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/useWarehouseTransferLines.ts
@@ -1,18 +1,16 @@
import { useFetcher } from "@remix-run/react";
import { useCallback } from "react";
-import type { WarehouseTransfer } from "~/modules/inventory";
import { usePermissions } from "~/hooks";
+import type { WarehouseTransfer } from "~/modules/inventory";
import { path } from "~/utils/path";
export default function useWarehouseTransferLines(
warehouseTransfer: WarehouseTransfer
) {
- const fetcher = useFetcher();
+ const fetcher = useFetcher<{ success: boolean; message: string }>();
const permissions = usePermissions();
- const isEditable = ["Draft", "To Ship and Receive", "To Ship"].includes(
- warehouseTransfer.status
- );
+ const isEditable = ["Draft"].includes(warehouseTransfer.status);
const canEdit = isEditable && permissions.can("update", "inventory");
const onCellEdit = useCallback(
@@ -26,7 +24,7 @@ export default function useWarehouseTransferLines(
fetcher.submit(formData, {
method: "post",
- action: path.to.warehouseTransferLines(warehouseTransfer.id),
+ action: path.to.warehouseTransferLine(warehouseTransfer.id, id),
});
},
[canEdit, fetcher, warehouseTransfer.id]
@@ -36,4 +34,4 @@ export default function useWarehouseTransferLines(
canEdit,
onCellEdit,
};
-}
\ No newline at end of file
+}
diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.$id.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.$id.tsx
new file mode 100644
index 0000000000..50a37a2b4c
--- /dev/null
+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.$id.tsx
@@ -0,0 +1,182 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+import {
+ deleteWarehouseTransferLine,
+ getWarehouseTransferLine,
+ upsertWarehouseTransferLine,
+ WarehouseTransferLineForm,
+} from "~/modules/inventory";
+import { path } from "~/utils/path";
+
+const warehouseTransferLineActionValidator = z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("create"),
+ transferId: z.string().min(1),
+ itemId: z.string().min(1),
+ quantity: zfd.numeric(z.number().min(0.0001)),
+ fromShelfId: zfd.text(z.string().optional()),
+ toShelfId: zfd.text(z.string().optional()),
+ notes: zfd.text(z.string().optional()),
+ }),
+ z.object({
+ type: z.literal("update"),
+ id: z.string().min(1),
+ quantity: zfd.numeric(z.number().min(0.0001)),
+ fromShelfId: zfd.text(z.string().optional()),
+ toShelfId: zfd.text(z.string().optional()),
+ notes: zfd.text(z.string().optional()),
+ }),
+ z.object({
+ type: z.literal("delete"),
+ id: z.string().min(1),
+ }),
+]);
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ update: "inventory",
+ });
+
+ const { transferId, id } = params;
+ if (!transferId) throw new Error("transferId not found");
+ if (!id) throw new Error("id not found");
+
+ const warehouseTransferLine = await getWarehouseTransferLine(
+ client,
+ transferId,
+ id
+ );
+ if (warehouseTransferLine.error) {
+ throw redirect(
+ path.to.warehouseTransferDetails(transferId),
+ await flash(
+ request,
+ error(
+ warehouseTransferLine.error,
+ "Failed to load warehouse transfer line"
+ )
+ )
+ );
+ }
+
+ return json({ warehouseTransferLine: warehouseTransferLine.data });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "inventory",
+ });
+
+ const { transferId, id } = params;
+ if (!transferId) throw new Error("transferId not found");
+ if (!id) throw new Error("id not found");
+
+ const formData = await request.formData();
+ const validation = await validator(
+ warehouseTransferLineActionValidator
+ ).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { type, ...data } = validation.data;
+
+ switch (type) {
+ case "update": {
+ const result = await upsertWarehouseTransferLine(client, {
+ id,
+ ...data,
+ transferId,
+ companyId,
+ updatedBy: userId,
+ });
+
+ if (result.error) {
+ return json(
+ { error: result.error },
+ await flash(
+ request,
+ error(result.error, "Failed to update warehouse transfer line")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.warehouseTransferDetails(transferId),
+ await flash(request, success("Updated warehouse transfer line"))
+ );
+ }
+
+ case "delete": {
+ const result = await deleteWarehouseTransferLine(client, id);
+
+ if (result.error) {
+ return json(
+ { error: result.error },
+ await flash(
+ request,
+ error(result.error, "Failed to delete warehouse transfer line")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.warehouseTransferDetails(transferId),
+ await flash(request, success("Deleted warehouse transfer line"))
+ );
+ }
+
+ default:
+ throw redirect(
+ path.to.warehouseTransferDetails(transferId),
+ await flash(
+ request,
+ error("Invalid action type", "Invalid action type")
+ )
+ );
+ }
+}
+
+export default function WarehouseTransferLineDetailsRoute() {
+ const params = useParams();
+ const { transferId, id } = params;
+ if (!transferId) throw new Error("transferId not found");
+ if (!id) throw new Error("id not found");
+
+ const { warehouseTransferLine } = useLoaderData<typeof loader>();
+ const initialValues = {
+ type: "update" as const,
+ id,
+ transferId,
+ itemId: warehouseTransferLine.itemId ?? "",
+ fromLocationId:
+ warehouseTransferLine.warehouseTransfer?.fromLocationId ?? "",
+ toLocationId: warehouseTransferLine.warehouseTransfer?.toLocationId ?? "",
+ quantity: warehouseTransferLine.quantity ?? 1,
+ fromShelfId: warehouseTransferLine.fromShelfId ?? "",
+ toShelfId: warehouseTransferLine.toShelfId ?? "",
+ notes: warehouseTransferLine.notes ?? "",
+ };
+
+ const navigate = useNavigate();
+
+ return (
+ <div className="flex flex-col gap-2 pb-16 w-full">
+ <WarehouseTransferLineForm
+ key={initialValues.id}
+ initialValues={initialValues}
+ warehouseTransfer={warehouseTransferLine.warehouseTransfer!}
+ onClose={() => navigate(-1)}
+ />
+ </div>
+ );
+}
diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.new.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.new.tsx
index 1974941c2a..8ed69c5de1 100644
--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.new.tsx
+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.new.tsx
@@ -1,4 +1,7 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
import { useNavigate, useParams } from "@remix-run/react";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
import { useRouteData } from "~/hooks";
import type {
WarehouseTransfer,
@@ -7,6 +10,56 @@ import type {
import { WarehouseTransferLineForm } from "~/modules/inventory/ui/WarehouseTransfers";
import { path } from "~/utils/path";
+import {
+ upsertWarehouseTransferLine,
+ warehouseTransferLineValidator,
+} from "~/modules/inventory";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ console.log("DEBUG: new action called");
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "inventory",
+ });
+
+ const { transferId } = params;
+ if (!transferId) {
+ throw new Error("transferId not found");
+ }
+
+ const formData = await request.formData();
+ const validation = warehouseTransferLineValidator.safeParse(
+ Object.fromEntries(formData)
+ );
+
+ if (!validation.success) {
+ return json({
+ success: false,
+ message: "Invalid form data",
+ });
+ }
+
+ const { id, ...data } = validation.data;
+
+ const createWarehouseTransferLine = await upsertWarehouseTransferLine(
+ client,
+ {
+ ...data,
+
+ companyId: companyId,
+ createdBy: userId,
+ }
+ );
+
+ if (createWarehouseTransferLine.error) {
+ return json({
+ success: false,
+ message: "Failed to create warehouse transfer line",
+ });
+ }
+
+ return redirect(path.to.warehouseTransfer(transferId));
+}
+
export default function NewWarehouseTransferLineRoute() {
const navigate = useNavigate();
const { transferId } = useParams();
diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.tsx
index 2a9a7ce0d1..7f178b0fd5 100644
--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.tsx
+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.tsx
@@ -6,9 +6,11 @@ import { useParams } from "@remix-run/react";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { useRouteData } from "~/hooks";
-import type { WarehouseTransfer, WarehouseTransferLine } from "~/modules/inventory";
+import type {
+ WarehouseTransfer,
+ WarehouseTransferLine,
+} from "~/modules/inventory";
import {
- getWarehouseTransfer,
upsertWarehouseTransfer,
warehouseTransferValidator,
} from "~/modules/inventory";
@@ -26,17 +28,21 @@ export async function action({ request }: ActionFunctionArgs) {
});
const formData = await request.formData();
- const validation = await validator(warehouseTransferValidator).validate(formData);
+ const validation = await validator(warehouseTransferValidator).validate(
+ formData
+ );
if (validation.error) {
return validationError(validation.error);
}
- const { id, ...data } = validation.data;
+ const { id, transferId, ...data } = validation.data;
if (!id) throw new Error("id not found");
+ if (!transferId) throw new Error("transferId not found");
const updateTransfer = await upsertWarehouseTransfer(client, {
id,
+ transferId,
...data,
updatedBy: userId,
customFields: setCustomFields(formData),
@@ -72,6 +78,9 @@ export default function WarehouseTransferDetailsRoute() {
const initialValues = {
...routeData.warehouseTransfer,
+ expectedReceiptDate:
+ routeData.warehouseTransfer.expectedReceiptDate ?? undefined,
+ transferDate: routeData.warehouseTransfer.transferDate ?? undefined,
transferId: routeData.warehouseTransfer.transferId ?? undefined,
reference: routeData.warehouseTransfer.reference ?? undefined,
notes: routeData.warehouseTransfer.notes ?? undefined,
@@ -80,16 +89,16 @@ export default function WarehouseTransferDetailsRoute() {
return (
<div className="flex flex-col gap-2 pb-16 w-full">
- <WarehouseTransferForm
+ <WarehouseTransferForm
key={initialValues.id}
initialValues={initialValues}
/>
-
- <WarehouseTransferLines
+
+ <WarehouseTransferLines
warehouseTransferLines={routeData.warehouseTransferLines}
transferId={transferId}
warehouseTransfer={routeData.warehouseTransfer}
/>
</div>
);
-}
\ No newline at end of file
+}
diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.lines.new.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.lines.new.tsx
deleted file mode 100644
index c858684996..0000000000
--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.lines.new.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { useNavigate, useParams } from "@remix-run/react";
-import { useRouteData } from "~/hooks";
-import type { WarehouseTransfer, WarehouseTransferLine } from "~/modules/inventory";
-import { WarehouseTransferLineForm } from "~/modules/inventory/ui/WarehouseTransfers";
-import { path } from "~/utils/path";
-
-export default function NewWarehouseTransferLineRoute() {
- const navigate = useNavigate();
- const { transferId } = useParams();
-
- if (!transferId) throw new Error("Could not find transferId");
-
- const routeData = useRouteData<{
- warehouseTransfer: WarehouseTransfer;
- warehouseTransferLines: WarehouseTransferLine[];
- }>(path.to.warehouseTransfer(transferId));
-
- if (!routeData?.warehouseTransfer) {
- throw new Error("Could not find warehouse transfer in routeData");
- }
-
- const initialValues = {
- type: "create" as const,
- transferId,
- fromLocationId: routeData.warehouseTransfer.fromLocationId,
- toLocationId: routeData.warehouseTransfer.toLocationId,
- itemId: "",
- quantity: 1,
- fromShelfId: "",
- toShelfId: "",
- unitOfMeasureCode: "",
- notes: "",
- };
-
- return (
- <WarehouseTransferLineForm
- initialValues={initialValues}
- warehouseTransfer={routeData.warehouseTransfer}
- onClose={() => navigate(path.to.warehouseTransferDetails(transferId))}
- />
- );
-}
\ No newline at end of file
diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.lines.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.lines.tsx
deleted file mode 100644
index 376fc65208..0000000000
--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.lines.tsx
+++ /dev/null
@@ -1,129 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { validationError, validator } from "@carbon/form";
-import { HStack } from "@carbon/react";
-import type { ActionFunctionArgs } from "@vercel/remix";
-import { json } from "@vercel/remix";
-import { z } from "zod";
-import { zfd } from "zod-form-data";
-import { upsertWarehouseTransferLine, deleteWarehouseTransferLine } from "~/modules/inventory";
-import { path } from "~/utils/path";
-
-const warehouseTransferLineActionValidator = z.discriminatedUnion("type", [
- z.object({
- type: z.literal("create"),
- transferId: z.string().min(1),
- itemId: z.string().min(1),
- quantity: zfd.numeric(z.number().min(0.0001)),
- fromShelfId: zfd.text(z.string().optional()),
- toShelfId: zfd.text(z.string().optional()),
- unitOfMeasureCode: zfd.text(z.string().optional()),
- notes: zfd.text(z.string().optional()),
- }),
- z.object({
- type: z.literal("update"),
- id: z.string().min(1),
- quantity: zfd.numeric(z.number().min(0.0001)),
- fromShelfId: zfd.text(z.string().optional()),
- toShelfId: zfd.text(z.string().optional()),
- notes: zfd.text(z.string().optional()),
- }),
- z.object({
- type: z.literal("delete"),
- id: z.string().min(1),
- }),
-]);
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
- update: "inventory",
- });
-
- const { transferId } = params;
- if (!transferId) throw new Error("transferId not found");
-
- const formData = await request.formData();
- const validation = await validator(warehouseTransferLineActionValidator).validate(
- formData
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { type, ...data } = validation.data;
-
- switch (type) {
- case "create": {
- const result = await upsertWarehouseTransferLine(client, {
- ...data,
- transferId,
- fromLocationId: formData.get("fromLocationId") as string,
- toLocationId: formData.get("toLocationId") as string,
- createdBy: userId,
- });
-
- if (result.error) {
- return json(
- { error: result.error },
- await flash(
- request,
- error(result.error, "Failed to create warehouse transfer line")
- )
- );
- }
-
- return json(
- { success: true },
- await flash(request, success("Added warehouse transfer line"))
- );
- }
-
- case "update": {
- const result = await upsertWarehouseTransferLine(client, {
- ...data,
- transferId,
- updatedBy: userId,
- });
-
- if (result.error) {
- return json(
- { error: result.error },
- await flash(
- request,
- error(result.error, "Failed to update warehouse transfer line")
- )
- );
- }
-
- return json(
- { success: true },
- await flash(request, success("Updated warehouse transfer line"))
- );
- }
-
- case "delete": {
- const result = await deleteWarehouseTransferLine(client, data.id);
-
- if (result.error) {
- return json(
- { error: result.error },
- await flash(
- request,
- error(result.error, "Failed to delete warehouse transfer line")
- )
- );
- }
-
- return json(
- { success: true },
- await flash(request, success("Deleted warehouse transfer line"))
- );
- }
-
- default:
- return json({ error: "Invalid action type" }, { status: 400 });
- }
-}
\ No newline at end of file
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 519fa648ff..095f2e91ad 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -942,6 +942,9 @@ export const path = {
newToolSupplier: (id: string) =>
generatePath(`${x}/tool/${id}/view/purchasing/new`),
newUom: `${x}/items/uom/new`,
+ newWarehouseTransfer: `${x}/warehouse-transfer/new`,
+ newWarehouseTransferLine: (transferId: string) =>
+ generatePath(`${x}/warehouse-transfer/${transferId}/details/new`),
newWorkCenter: `${x}/resources/work-centers/new`,
newWebhook: `${x}/settings/webhooks/new`,
@@ -1229,13 +1232,10 @@ export const path = {
generatePath(`${x}/warehouse-transfer/${id}/ship`),
warehouseTransferReceive: (id: string) =>
generatePath(`${x}/warehouse-transfer/${id}/receive`),
- warehouseTransferLines: (id: string) =>
- generatePath(`${x}/warehouse-transfer/${id}/lines`),
- newWarehouseTransfer: `${x}/warehouse-transfer/new`,
- newWarehouseTransferLine: (transferId: string) =>
- generatePath(`${x}/warehouse-transfer/${transferId}/lines/new`),
+ warehouseTransferLines: (transferId: string) =>
+ generatePath(`${x}/warehouse-transfer/${transferId}/lines`),
warehouseTransferLine: (transferId: string, lineId: string) =>
- generatePath(`${x}/warehouse-transfer/${transferId}/lines/${lineId}`),
+ generatePath(`${x}/warehouse-transfer/${transferId}/details/${lineId}`),
deleteWarehouseTransfer: (id: string) =>
generatePath(`${x}/warehouse-transfer/${id}/delete`),
shippingMethods: `${x}/inventory/shipping-methods`,
diff --git a/packages/database/supabase/functions/chat/index.ts b/packages/database/supabase/functions/chat/index.ts
index 0b5c423fe2..0b74c22646 100644
--- a/packages/database/supabase/functions/chat/index.ts
+++ b/packages/database/supabase/functions/chat/index.ts
@@ -1,7 +1,7 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { createAnthropic } from "npm:@ai-sdk/[email protected]";
import { APICallError, LanguageModelV1CallOptions } from "npm:[email protected]";
-import { z } from "npm:zod";
+import { z } from "npm:[email protected]";
import { corsHeaders } from "../lib/headers.ts";
import SupabaseClient from "https://esm.sh/v135/@supabase/[email protected]/dist/module/SupabaseClient.d.ts";