Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add header for warehouse transfer
Brad Barbin9cfdbdae3dba
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.tsindex f670c44d49..dad9382186 100644--- a/apps/erp/app/modules/inventory/inventory.models.ts+++ b/apps/erp/app/modules/inventory/inventory.models.ts@@ -197,46 +197,46 @@ export const splitValidator = z.object({export const warehouseTransferStatusType = ["Draft",- "Confirmed",- "In Transit",- "Partially Received",- "Received",- "Cancelled"+ "To Ship and Receive",+ "To Ship",+ "To Receive",+ "Completed",+ "Cancelled",] as const;-export const warehouseTransferValidator = z.object({- id: z.string().min(1),- transferId: z.string().min(1, { message: "Transfer ID is required" }),- fromLocationId: z.string().min(1, { message: "From Location is required" }),- toLocationId: z.string().min(1, { message: "To Location is required" }),- status: z.enum(warehouseTransferStatusType).optional(),- transferDate: zfd.text(z.string().optional()),- expectedReceiptDate: zfd.text(z.string().optional()),- notes: zfd.text(z.string().optional()),- reference: zfd.text(z.string().optional()),-}).refine(- (data) => data.fromLocationId !== data.toLocationId,- {+export const warehouseTransferValidator = z+ .object({+ id: zfd.text(z.string().optional()),+ transferId: zfd.text(z.string().optional()),+ fromLocationId: z.string().min(1, { message: "From Location is required" }),+ toLocationId: z.string().min(1, { message: "To Location is required" }),+ status: z.enum(warehouseTransferStatusType).optional(),+ transferDate: zfd.text(z.string().optional()),+ expectedReceiptDate: zfd.text(z.string().optional()),+ notes: zfd.text(z.string().optional()),+ reference: zfd.text(z.string().optional()),+ })+ .refine((data) => data.fromLocationId !== data.toLocationId, {message: "From and To locations must be different",- path: ["toLocationId"]- }-);+ path: ["toLocationId"],+ });-export const warehouseTransferLineValidator = z.object({- id: z.string().min(1).optional(),- transferId: z.string().min(1, { message: "Transfer ID is required" }),- itemId: z.string().min(1, { message: "Item is required" }),- quantity: zfd.numeric(z.number().min(0.0001, { message: "Quantity must be greater than 0" })),- fromLocationId: z.string().min(1, { message: "From Location is required" }),- fromShelfId: zfd.text(z.string().optional()),- toLocationId: z.string().min(1, { message: "To Location is required" }),- toShelfId: zfd.text(z.string().optional()),- unitOfMeasureCode: zfd.text(z.string().optional()),- notes: zfd.text(z.string().optional()),-}).refine(- (data) => data.fromLocationId !== data.toLocationId,- {+export const warehouseTransferLineValidator = z+ .object({+ id: zfd.text(z.string().optional()),+ transferId: z.string().min(1, { message: "Transfer ID is required" }),+ itemId: z.string().min(1, { message: "Item is required" }),+ quantity: zfd.numeric(+ z.number().min(0.0001, { message: "Quantity must be greater than 0" })+ ),+ fromLocationId: z.string().min(1, { message: "From Location is required" }),+ fromShelfId: zfd.text(z.string().optional()),+ toLocationId: z.string().min(1, { message: "To Location is required" }),+ toShelfId: zfd.text(z.string().optional()),+ unitOfMeasureCode: zfd.text(z.string().optional()),+ notes: zfd.text(z.string().optional()),+ })+ .refine((data) => data.fromLocationId !== data.toLocationId, {message: "From and To locations must be different",- path: ["toLocationId"]- }-);+ path: ["toLocationId"],+ });diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsxindex ec89136e7e..0484fe9397 100644--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferForm.tsx@@ -1,7 +1,8 @@-import { ValidatedForm } from "@carbon/form";+import { InputControlled, ValidatedForm } from "@carbon/form";import {Card,CardContent,+ CardDescription,CardHeader,CardTitle,VStack,@@ -12,6 +13,7 @@ import {Hidden,Input,Location,+ SequenceOrCustomId,Submit,TextArea,} from "~/components/Form";@@ -21,7 +23,10 @@ type WarehouseTransferFormProps = {initialValues: z.infer<typeof warehouseTransferValidator>;};-const WarehouseTransferForm = ({ initialValues }: WarehouseTransferFormProps) => {+const WarehouseTransferForm = ({+ initialValues,+}: WarehouseTransferFormProps) => {+ const isEditing = !!initialValues.id;return (<ValidatedFormvalidator={warehouseTransferValidator}@@ -31,26 +36,48 @@ const WarehouseTransferForm = ({ initialValues }: WarehouseTransferFormProps) =>><Card className="w-full"><CardHeader>- <CardTitle>Transfer Details</CardTitle>+ <CardTitle>{isEditing ? "Edit" : "New"} Transfer</CardTitle>+ {!isEditing && (+ <CardDescription>+ A warehouse transfer is an inter-company movement of inventory+ between two locations+ </CardDescription>+ )}</CardHeader><CardContent>+ <Hidden name="id" /><VStack spacing={4}>- <Hidden name="id" />- <Input name="transferId" label="Transfer ID" />-- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full items-start">+ {isEditing ? (+ <InputControlled+ name="transferId"+ label="Transfer ID"+ isDisabled+ value={initialValues.transferId!}+ />+ ) : (+ <SequenceOrCustomId+ name="transferId"+ label="Transfer ID"+ table="warehouseTransfer"+ />+ )}+ <Input name="reference" label="Reference" /><Location name="fromLocationId" label="From Location" /><Location name="toLocationId" label="To Location" />+ {isEditing && (+ <>+ <DatePicker name="transferDate" label="Transfer Date" />+ <DatePicker+ name="expectedReceiptDate"+ label="Expected Receipt Date"+ />+ </>+ )}</div>-- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <DatePicker name="transferDate" label="Transfer Date" />- <DatePicker name="expectedReceiptDate" label="Expected Receipt Date" />- </div>-- <Input name="reference" label="Reference" />+<TextArea name="notes" label="Notes" />-+<Submit>Save Transfer</Submit></VStack></CardContent>@@ -59,4 +86,4 @@ const WarehouseTransferForm = ({ initialValues }: WarehouseTransferFormProps) =>);};-export default WarehouseTransferForm;\ No newline at end of file+export default WarehouseTransferForm;diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader.tsxindex 2453a363c7..87e4cd1acd 100644--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader.tsx+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader.tsx@@ -1,8 +1,31 @@-import { Heading, HStack } from "@carbon/react";+import { useCarbon } from "@carbon/auth";+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuIcon,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Heading,+ HStack,+ toast,+} from "@carbon/react";import { Link } from "@remix-run/react";+import { useCallback, useEffect, useState } from "react";+import {+ LuCheckCheck,+ LuChevronDown,+ LuCirclePlus,+ LuCircleStop,+ LuHandCoins,+ LuTruck,+} from "react-icons/lu";import { usePermissions } from "~/hooks";import { path } from "~/utils/path";-import type { WarehouseTransfer } from "../../types";+import type { Receipt, Shipment, WarehouseTransfer } from "../../types";+import { ReceiptStatus } from "../Receipts";+import { ShipmentStatus } from "../Shipments";import WarehouseTransferStatus from "./WarehouseTransferStatus";type WarehouseTransferHeaderProps = {@@ -14,13 +37,8 @@ const WarehouseTransferHeader = ({}: WarehouseTransferHeaderProps) => {const permissions = usePermissions();- const canShip =- warehouseTransfer.status === "Confirmed" &&- warehouseTransfer.shippedQuantity < warehouseTransfer.totalQuantity;-- const canReceive =- warehouseTransfer.status === "In Transit" ||- warehouseTransfer.status === "Partially Received";+ const { receipts, shipments, ship, receive } =+ useWarehouseTransferRelatedDocuments(warehouseTransfer.id);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),0px_0px_4px_rgba(0,_0,_0,_0.08)]">@@ -33,9 +51,234 @@ const WarehouseTransferHeader = ({</Link><WarehouseTransferStatus status={warehouseTransfer.status} /></HStack>+ <HStack>+ <Button+ leftIcon={<LuCheckCheck />}+ variant={+ warehouseTransfer.status === "Draft" ? "primary" : "secondary"+ }+ onClick={() => {+ // TODO: Implement confirm functionality+ toast.success("Confirmed warehouse transfer");+ }}+ isDisabled={+ !["Draft"].includes(warehouseTransfer.status) ||+ !permissions.can("update", "inventory")+ }+ >+ Confirm+ </Button>++ <Button+ variant="secondary"+ leftIcon={<LuCircleStop />}+ onClick={() => {+ // TODO: Implement cancel functionality+ toast.success("Cancelled warehouse transfer");+ }}+ isDisabled={+ ["Cancelled", "Completed"].includes(warehouseTransfer.status) ||+ !permissions.can("update", "inventory")+ }+ >+ Cancel+ </Button>++ {shipments.length > 0 ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ leftIcon={<LuTruck />}+ variant="secondary"+ rightIcon={<LuChevronDown />}+ >+ Shipments+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem+ disabled={+ !["To Ship", "To Ship and Receive"].includes(+ warehouseTransfer.status ?? ""+ )+ }+ onClick={() => {+ ship(warehouseTransfer);+ }}+ >+ <DropdownMenuIcon icon={<LuCirclePlus />} />+ New Shipment+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ {shipments.map((shipment) => (+ <DropdownMenuItem key={shipment.id} asChild>+ <Link to={path.to.shipment(shipment.id)}>+ <DropdownMenuIcon icon={<LuTruck />} />+ <HStack spacing={8}>+ <span>{shipment.shipmentId}</span>+ <ShipmentStatus status={shipment.status} />+ </HStack>+ </Link>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <Button+ leftIcon={<LuTruck />}+ isDisabled={+ !["To Ship", "To Ship and Receive"].includes(+ warehouseTransfer.status ?? ""+ )+ }+ variant={+ ["To Ship", "To Ship and Receive"].includes(+ warehouseTransfer.status ?? ""+ )+ ? "primary"+ : "secondary"+ }+ onClick={() => {+ ship(warehouseTransfer);+ }}+ >+ Ship+ </Button>+ )}+ {receipts.length > 0 ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ leftIcon={<LuHandCoins />}+ variant={+ ["To Receive", "To Ship and Receive"].includes(+ warehouseTransfer.status ?? ""+ )+ ? "primary"+ : "secondary"+ }+ rightIcon={<LuChevronDown />}+ >+ Receipts+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem+ disabled={+ !["To Receive", "To Ship and Receive"].includes(+ warehouseTransfer.status ?? ""+ )+ }+ onClick={() => {+ receive(warehouseTransfer);+ }}+ >+ <DropdownMenuIcon icon={<LuCirclePlus />} />+ New Receipt+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ {receipts.map((receipt) => (+ <DropdownMenuItem key={receipt.id} asChild>+ <Link to={path.to.receipt(receipt.id)}>+ <DropdownMenuIcon icon={<LuHandCoins />} />+ <HStack spacing={8}>+ <span>{receipt.receiptId}</span>+ <ReceiptStatus status={receipt.status} />+ </HStack>+ </Link>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <Button+ leftIcon={<LuHandCoins />}+ isDisabled={+ !["To Receive", "To Ship and Receive"].includes(+ warehouseTransfer.status ?? ""+ )+ }+ variant={+ ["To Receive", "To Ship and Receive"].includes(+ warehouseTransfer.status ?? ""+ )+ ? "primary"+ : "secondary"+ }+ onClick={() => {+ receive(warehouseTransfer);+ }}+ >+ Receive+ </Button>+ )}+ </HStack></HStack></div>);};export default WarehouseTransferHeader;++export const useWarehouseTransferRelatedDocuments = (+ warehouseTransferId: string+) => {+ const [receipts, setReceipts] = useState<+ Pick<Receipt, "id" | "receiptId" | "status">[]+ >([]);++ const [shipments, setShipments] = useState<+ Pick<Shipment, "id" | "shipmentId" | "status">[]+ >([]);++ const { carbon } = useCarbon();++ const ship = useCallback((warehouseTransfer: WarehouseTransfer) => {+ // Navigate to ship route+ window.location.href = path.to.warehouseTransferShip(warehouseTransfer.id);+ }, []);++ const receive = useCallback((warehouseTransfer: WarehouseTransfer) => {+ // Navigate to receive route+ window.location.href = path.to.warehouseTransferReceive(+ warehouseTransfer.id+ );+ }, []);++ const getRelatedDocuments = useCallback(+ async (warehouseTransferId: string) => {+ if (!carbon || !warehouseTransferId) return;+ const [receipts, shipments] = await Promise.all([+ carbon+ .from("receipt")+ .select("id, receiptId, status")+ .eq("sourceDocument", "Inbound Transfer")+ .eq("sourceDocumentId", warehouseTransferId),+ carbon+ .from("shipment")+ .select("id, shipmentId, status")+ .eq("sourceDocument", "Outbound Transfer")+ .eq("sourceDocumentId", warehouseTransferId),+ ]);++ if (receipts.error) {+ toast.error("Failed to load receipts");+ } else {+ setReceipts(receipts.data);+ }++ if (shipments.error) {+ toast.error("Failed to load shipments");+ } else {+ setShipments(shipments.data);+ }+ },+ [carbon]+ );++ useEffect(() => {+ getRelatedDocuments(warehouseTransferId);+ }, [getRelatedDocuments, warehouseTransferId]);++ return { receipts, shipments, ship, receive };+};diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferStatus.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferStatus.tsxindex 147dfe38eb..0feb1fb62f 100644--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferStatus.tsx+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferStatus.tsx@@ -9,14 +9,14 @@ const WarehouseTransferStatus = ({ status }: Props) => {switch (status) {case "Draft":return <Badge variant="secondary">Draft</Badge>;- case "Confirmed":- return <Badge variant="yellow">Confirmed</Badge>;- case "In Transit":- return <Badge variant="blue">In Transit</Badge>;- case "Partially Received":- return <Badge variant="yellow">Partially Received</Badge>;- case "Received":- return <Badge variant="green">Received</Badge>;+ case "To Ship and Receive":+ return <Badge variant="yellow">To Ship and Receive</Badge>;+ case "To Ship":+ return <Badge variant="blue">To Ship</Badge>;+ case "To Receive":+ return <Badge variant="blue">To Receive</Badge>;+ case "Completed":+ return <Badge variant="green">Completed</Badge>;case "Cancelled":return <Badge variant="destructive">Cancelled</Badge>;default:diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.tsxindex d114b4a0a1..9cd4b45150 100644--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.tsx+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.tsx@@ -2,17 +2,20 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { VStack } from "@carbon/react";-import { Outlet, useLoaderData } from "@remix-run/react";+import { Outlet, useLoaderData, useParams } from "@remix-run/react";import type { LoaderFunctionArgs } from "@vercel/remix";import { json, redirect } from "@vercel/remix";-import { getWarehouseTransfer, getWarehouseTransferLines } from "~/modules/inventory";+import { PanelProvider } from "~/components/Layout/Panels";+import {+ getWarehouseTransfer,+ getWarehouseTransferLines,+} from "~/modules/inventory";import WarehouseTransferHeader from "~/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader";-import WarehouseTransferLines from "~/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {- breadcrumb: "Warehouse Transfer Details",+ breadcrumb: "Warehouse Transfer",to: path.to.warehouseTransfers,};@@ -44,7 +47,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {path.to.warehouseTransfers,await flash(request,- error(warehouseTransferLines.error, "Failed to load warehouse transfer lines")+ error(+ warehouseTransferLines.error,+ "Failed to load warehouse transfer lines"+ )));}@@ -56,16 +62,24 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}export default function WarehouseTransferRoute() {- const { warehouseTransfer, warehouseTransferLines } = useLoaderData<typeof loader>();+ const { warehouseTransfer } = useLoaderData<typeof loader>();+ const params = useParams();+ const { transferId } = params;+ if (!transferId) throw new Error("Could not find transferId");return (- <VStack spacing={4} className="h-full p-4">- <WarehouseTransferHeader warehouseTransfer={warehouseTransfer} />- <WarehouseTransferLines- warehouseTransferLines={warehouseTransferLines}- transferId={warehouseTransfer.id}- />- <Outlet />- </VStack>+ <PanelProvider>+ <div className="flex flex-col h-[calc(100dvh-49px)] overflow-hidden w-full">+ <WarehouseTransferHeader warehouseTransfer={warehouseTransfer} />+ <div className="flex h-[calc(100dvh-99px)] overflow-y-auto scrollbar-hide w-full">+ <VStack+ spacing={4}+ className="h-full p-2 w-full max-w-5xl mx-auto pb-32"+ >+ <Outlet />+ </VStack>+ </div>+ </div>+ </PanelProvider>);-}\ No newline at end of file+}diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/_layout.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/_layout.tsxnew file mode 100644index 0000000000..20649e8d30--- /dev/null+++ b/apps/erp/app/routes/x+/warehouse-transfer+/_layout.tsx@@ -0,0 +1,22 @@+import { Outlet } from "@remix-run/react";+import type { MetaFunction } from "@vercel/remix";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | Warehouse Transfer" }];+};++export const config = {+ runtime: "nodejs",+};++export const handle: Handle = {+ breadcrumb: "Inventory",+ to: path.to.inventory,+ module: "inventory",+};++export default function WarehouseTransferRoute() {+ return <Outlet />;+}diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/new.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/new.tsxindex 289fd1abc0..43057398b7 100644--- a/apps/erp/app/routes/x+/warehouse-transfer+/new.tsx+++ b/apps/erp/app/routes/x+/warehouse-transfer+/new.tsx@@ -1,10 +1,17 @@-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect, type LoaderFunctionArgs } from "@vercel/remix";-import { nanoid } from "nanoid";-import { upsertWarehouseTransfer } from "~/modules/inventory";-import { getUserDefaults } from "~/modules/users/users.server";+import { validationError, validator } from "@carbon/form";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";+import { redirect } from "@vercel/remix";+import { useUser } from "~/hooks";+import {+ upsertWarehouseTransfer,+ warehouseTransferValidator,+} from "~/modules/inventory";+import { WarehouseTransferForm } from "~/modules/inventory/ui/WarehouseTransfers";+import { getNextSequence } from "~/modules/settings";+import { setCustomFields } from "~/utils/form";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -14,30 +21,91 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {+ await requirePermissions(request, {+ create: "inventory",+ });++ return null;+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {create: "inventory",});- const defaults = await getUserDefaults(client, userId, companyId);-- // Generate a new transfer ID- const transferId = `WT-${Date.now()}`;-- const newTransfer = await upsertWarehouseTransfer(client, {+ const formData = await request.formData();+ const validation = await validator(warehouseTransferValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ let transferId = validation.data.transferId;+ const useNextSequence = !transferId;++ if (useNextSequence) {+ const nextSequence = await getNextSequence(+ client,+ "warehouseTransfer",+ companyId+ );+ if (nextSequence.error) {+ throw redirect(+ path.to.newWarehouseTransfer,+ await flash(+ request,+ error(nextSequence.error, "Failed to get next sequence")+ )+ );+ }+ transferId = nextSequence.data;+ }++ if (!transferId) throw new Error("transferId is not defined");+ const { id, ...data } = validation.data;++ const createTransfer = await upsertWarehouseTransfer(client, {+ ...data,transferId,- fromLocationId: defaults.data?.locationId ?? "",- toLocationId: "",- status: "Draft",companyId,createdBy: userId,+ customFields: setCustomFields(formData),});- if (newTransfer.error || !newTransfer.data) {+ if (createTransfer.error || !createTransfer.data) {throw redirect(path.to.warehouseTransfers,- await flash(request, error(newTransfer.error, "Failed to create warehouse transfer"))+ await flash(+ request,+ error(createTransfer.error, "Failed to create warehouse transfer")+ ));}- throw redirect(path.to.warehouseTransferDetails(newTransfer.data.id));-}\ No newline at end of file+ throw redirect(path.to.warehouseTransferDetails(createTransfer.data.id));+}++export default function WarehouseTransferNewRoute() {+ const { defaults } = useUser();++ const initialValues = {+ id: undefined,+ transferId: "",+ fromLocationId: defaults?.locationId ?? "",+ toLocationId: "",+ status: "Draft" as const,+ transferDate: "",+ expectedReceiptDate: "",+ notes: "",+ reference: "",+ };++ return (+ <div className="max-w-4xl w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">+ <WarehouseTransferForm initialValues={initialValues} />+ </div>+ );+}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex c813c85a1d..1504b84809 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -1219,15 +1219,16 @@ export const path = {shippingMethod: (id: string) =>generatePath(`${x}/inventory/shipping-methods/${id}`),warehouseTransfers: `${x}/inventory/warehouse-transfers`,- warehouseTransfer: (id: string) => generatePath(`${x}/warehouse-transfer/${id}`),+ warehouseTransfer: (id: string) =>+ generatePath(`${x}/warehouse-transfer/${id}`),warehouseTransferDetails: (id: string) =>- generatePath(`${x}/warehouse-transfer/${id}/details`),- warehouseTransferShip: (id: string) =>+ generatePath(`${x}/warehouse-transfer/${id}`),+ warehouseTransferShip: (id: string) =>generatePath(`${x}/warehouse-transfer/${id}/ship`),- warehouseTransferReceive: (id: string) =>+ warehouseTransferReceive: (id: string) =>generatePath(`${x}/warehouse-transfer/${id}/receive`),newWarehouseTransfer: `${x}/warehouse-transfer/new`,- deleteWarehouseTransfer: (id: string) =>+ deleteWarehouseTransfer: (id: string) =>generatePath(`${x}/warehouse-transfer/${id}/delete`),shippingMethods: `${x}/inventory/shipping-methods`,supplier: (id: string) => generatePath(`${x}/supplier/${id}`),diff --git a/llm/workflows/database-migration.md b/llm/workflows/database-migration.mdindex dfa914d387..f883f4dc0b 100644--- a/llm/workflows/database-migration.md+++ b/llm/workflows/database-migration.md@@ -66,6 +66,9 @@ CREATE INDEX "tableName_companyId_idx" ON "tableName" ("companyId");"updatedAt" TIMESTAMP WITH TIME ZONE```+- NEVER include an itemReadableId field.+- NEVER include the number of decimal places in a NUMERIC field.+#### Complete Table Example```sqldiff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 159045e9e1..14ce9dfb9b 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -7827,9 +7827,6 @@ export default {{$ref: "#/parameters/rowFilter.warehouseTransferLine.itemId",},- {- $ref: "#/parameters/rowFilter.warehouseTransferLine.itemReadableId",- },{$ref: "#/parameters/rowFilter.warehouseTransferLine.quantity",},@@ -7943,9 +7940,6 @@ export default {{$ref: "#/parameters/rowFilter.warehouseTransferLine.itemId",},- {- $ref: "#/parameters/rowFilter.warehouseTransferLine.itemReadableId",- },{$ref: "#/parameters/rowFilter.warehouseTransferLine.quantity",},@@ -8013,9 +8007,6 @@ export default {{$ref: "#/parameters/rowFilter.warehouseTransferLine.itemId",},- {- $ref: "#/parameters/rowFilter.warehouseTransferLine.itemReadableId",- },{$ref: "#/parameters/rowFilter.warehouseTransferLine.quantity",},@@ -30972,15 +30963,6 @@ export default {{$ref: "#/parameters/rowFilter.warehouseTransfer.reference",},- {- $ref: "#/parameters/rowFilter.warehouseTransfer.totalQuantity",- },- {- $ref: "#/parameters/rowFilter.warehouseTransfer.shippedQuantity",- },- {- $ref: "#/parameters/rowFilter.warehouseTransfer.receivedQuantity",- },{$ref: "#/parameters/rowFilter.warehouseTransfer.companyId",},@@ -30999,6 +30981,9 @@ export default {{$ref: "#/parameters/rowFilter.warehouseTransfer.customFields",},+ {+ $ref: "#/parameters/rowFilter.warehouseTransfer.tags",+ },{$ref: "#/parameters/select",},@@ -31085,15 +31070,6 @@ export default {{$ref: "#/parameters/rowFilter.warehouseTransfer.reference",},- {- $ref: "#/parameters/rowFilter.warehouseTransfer.totalQuantity",- },- {- $ref: "#/parameters/rowFilter.warehouseTransfer.shippedQuantity",- },- {- $ref: "#/parameters/rowFilter.warehouseTransfer.receivedQuantity",- },{$ref: "#/parameters/rowFilter.warehouseTransfer.companyId",},@@ -31112,6 +31088,9 @@ export default {{$ref: "#/parameters/rowFilter.warehouseTransfer.customFields",},+ {+ $ref: "#/parameters/rowFilter.warehouseTransfer.tags",+ },{$ref: "#/parameters/preferReturn",},@@ -31152,15 +31131,6 @@ export default {{$ref: "#/parameters/rowFilter.warehouseTransfer.reference",},- {- $ref: "#/parameters/rowFilter.warehouseTransfer.totalQuantity",- },- {- $ref: "#/parameters/rowFilter.warehouseTransfer.shippedQuantity",- },- {- $ref: "#/parameters/rowFilter.warehouseTransfer.receivedQuantity",- },{$ref: "#/parameters/rowFilter.warehouseTransfer.companyId",},@@ -31179,6 +31149,9 @@ export default {{$ref: "#/parameters/rowFilter.warehouseTransfer.customFields",},+ {+ $ref: "#/parameters/rowFilter.warehouseTransfer.tags",+ },{$ref: "#/parameters/body.warehouseTransfer",},@@ -62562,10 +62535,6 @@ export default {format: "text",type: "string",},- itemReadableId: {- format: "text",- type: "string",- },quantity: {default: 0,format: "numeric",@@ -73381,9 +73350,6 @@ export default {"fromLocationId","toLocationId","status",- "totalQuantity",- "shippedQuantity",- "receivedQuantity","companyId","createdBy","createdAt",@@ -73415,10 +73381,10 @@ export default {default: "Draft",enum: ["Draft",- "Confirmed",- "In Transit",- "Partially Received",- "Received",+ "To Ship and Receive",+ "To Ship",+ "To Receive",+ "Completed","Cancelled",],format: 'public."warehouseTransferStatus"',@@ -73440,21 +73406,6 @@ export default {format: "text",type: "string",},- totalQuantity: {- default: 0,- format: "numeric",- type: "number",- },- shippedQuantity: {- default: 0,- format: "numeric",- type: "number",- },- receivedQuantity: {- default: 0,- format: "numeric",- type: "number",- },companyId: {description:"Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",@@ -73485,6 +73436,13 @@ export default {customFields: {format: "jsonb",},+ tags: {+ format: "text[]",+ items: {+ type: "string",+ },+ type: "array",+ },},type: "object",},@@ -88365,12 +88323,6 @@ export default {in: "query",type: "string",},- "rowFilter.warehouseTransferLine.itemReadableId": {- name: "itemReadableId",- required: false,- in: "query",- type: "string",- },"rowFilter.warehouseTransferLine.quantity": {name: "quantity",required: false,@@ -100701,24 +100653,6 @@ export default {in: "query",type: "string",},- "rowFilter.warehouseTransfer.totalQuantity": {- name: "totalQuantity",- required: false,- in: "query",- type: "string",- },- "rowFilter.warehouseTransfer.shippedQuantity": {- name: "shippedQuantity",- required: false,- in: "query",- type: "string",- },- "rowFilter.warehouseTransfer.receivedQuantity": {- name: "receivedQuantity",- required: false,- in: "query",- type: "string",- },"rowFilter.warehouseTransfer.companyId": {name: "companyId",required: false,@@ -100755,6 +100689,12 @@ export default {in: "query",type: "string",},+ "rowFilter.warehouseTransfer.tags": {+ name: "tags",+ required: false,+ in: "query",+ type: "string",+ },"body.companyIntegration": {name: "companyIntegration",description: "companyIntegration",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 48277c0715..486b22b0de 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -34345,12 +34345,10 @@ export type Database = {fromLocationId: stringid: stringnotes: string | null- receivedQuantity: numberreference: string | null- shippedQuantity: numberstatus: Database["public"]["Enums"]["warehouseTransferStatus"]+ tags: string[] | nulltoLocationId: string- totalQuantity: numbertransferDate: string | nulltransferId: stringupdatedAt: string | null@@ -34365,12 +34363,10 @@ export type Database = {fromLocationId: stringid?: stringnotes?: string | null- receivedQuantity?: numberreference?: string | null- shippedQuantity?: numberstatus?: Database["public"]["Enums"]["warehouseTransferStatus"]+ tags?: string[] | nulltoLocationId: string- totalQuantity?: numbertransferDate?: string | nulltransferId: stringupdatedAt?: string | null@@ -34385,12 +34381,10 @@ export type Database = {fromLocationId?: stringid?: stringnotes?: string | null- receivedQuantity?: numberreference?: string | null- shippedQuantity?: numberstatus?: Database["public"]["Enums"]["warehouseTransferStatus"]+ tags?: string[] | nulltoLocationId?: string- totalQuantity?: numbertransferDate?: string | nulltransferId?: stringupdatedAt?: string | null@@ -34521,7 +34515,6 @@ export type Database = {fromShelfId: string | nullid: stringitemId: string- itemReadableId: string | nullnotes: string | nullquantity: numberreceivedQuantity: number@@ -34542,7 +34535,6 @@ export type Database = {fromShelfId?: string | nullid?: stringitemId: string- itemReadableId?: string | nullnotes?: string | nullquantity?: numberreceivedQuantity?: number@@ -34563,7 +34555,6 @@ export type Database = {fromShelfId?: string | nullid?: stringitemId?: string- itemReadableId?: string | nullnotes?: string | nullquantity?: numberreceivedQuantity?: number@@ -47588,10 +47579,10 @@ export type Database = {trackingSource: "Purchased" | "Manufactured"warehouseTransferStatus:| "Draft"- | "Confirmed"- | "In Transit"- | "Partially Received"- | "Received"+ | "To Ship and Receive"+ | "To Ship"+ | "To Receive"+ | "Completed"| "Cancelled"}CompositeTypes: {diff --git a/packages/database/supabase/functions/lib/seed.ts b/packages/database/supabase/functions/lib/seed.tsindex 57266d9a16..c0bbb27361 100644--- a/packages/database/supabase/functions/lib/seed.ts+++ b/packages/database/supabase/functions/lib/seed.ts@@ -1855,6 +1855,15 @@ export const sequences = [size: 6,step: 1,},+ {+ table: "warehouseTransfer",+ name: "Warehouse Transfer",+ prefix: "WT",+ suffix: null,+ next: 0,+ size: 6,+ step: 1,+ },];export const supplierStauses = ["Active", "Inactive", "Pending", "Rejected"];diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 48277c0715..486b22b0de 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -34345,12 +34345,10 @@ export type Database = {fromLocationId: stringid: stringnotes: string | null- receivedQuantity: numberreference: string | null- shippedQuantity: numberstatus: Database["public"]["Enums"]["warehouseTransferStatus"]+ tags: string[] | nulltoLocationId: string- totalQuantity: numbertransferDate: string | nulltransferId: stringupdatedAt: string | null@@ -34365,12 +34363,10 @@ export type Database = {fromLocationId: stringid?: stringnotes?: string | null- receivedQuantity?: numberreference?: string | null- shippedQuantity?: numberstatus?: Database["public"]["Enums"]["warehouseTransferStatus"]+ tags?: string[] | nulltoLocationId: string- totalQuantity?: numbertransferDate?: string | nulltransferId: stringupdatedAt?: string | null@@ -34385,12 +34381,10 @@ export type Database = {fromLocationId?: stringid?: stringnotes?: string | null- receivedQuantity?: numberreference?: string | null- shippedQuantity?: numberstatus?: Database["public"]["Enums"]["warehouseTransferStatus"]+ tags?: string[] | nulltoLocationId?: string- totalQuantity?: numbertransferDate?: string | nulltransferId?: stringupdatedAt?: string | null@@ -34521,7 +34515,6 @@ export type Database = {fromShelfId: string | nullid: stringitemId: string- itemReadableId: string | nullnotes: string | nullquantity: numberreceivedQuantity: number@@ -34542,7 +34535,6 @@ export type Database = {fromShelfId?: string | nullid?: stringitemId: string- itemReadableId?: string | nullnotes?: string | nullquantity?: numberreceivedQuantity?: number@@ -34563,7 +34555,6 @@ export type Database = {fromShelfId?: string | nullid?: stringitemId?: string- itemReadableId?: string | nullnotes?: string | nullquantity?: numberreceivedQuantity?: number@@ -47588,10 +47579,10 @@ export type Database = {trackingSource: "Purchased" | "Manufactured"warehouseTransferStatus:| "Draft"- | "Confirmed"- | "In Transit"- | "Partially Received"- | "Received"+ | "To Ship and Receive"+ | "To Ship"+ | "To Receive"+ | "Completed"| "Cancelled"}CompositeTypes: {diff --git a/packages/database/supabase/migrations/20250726000000_warehouse-transfers.sql b/packages/database/supabase/migrations/20250726000000_warehouse-transfers.sqlindex 5df39fe504..cfb11ec804 100644--- a/packages/database/supabase/migrations/20250726000000_warehouse-transfers.sql+++ b/packages/database/supabase/migrations/20250726000000_warehouse-transfers.sql@@ -1,10 +1,10 @@-- Warehouse Transfer StatusCREATE TYPE "warehouseTransferStatus" AS ENUM ('Draft',- 'Confirmed',- 'In Transit',- 'Partially Received',- 'Received',+ 'To Ship and Receive',+ 'To Ship',+ 'To Receive',+ 'Completed','Cancelled');@@ -19,26 +19,34 @@ CREATE TABLE "warehouseTransfer" ("expectedReceiptDate" DATE,"notes" TEXT,"reference" TEXT,- "totalQuantity" NUMERIC(18, 4) NOT NULL DEFAULT 0,- "shippedQuantity" NUMERIC(18, 4) NOT NULL DEFAULT 0,- "receivedQuantity" NUMERIC(18, 4) NOT NULL DEFAULT 0,"companyId" TEXT NOT NULL,"createdBy" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"updatedBy" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,- "customFields" JSONB+ "customFields" JSONB,+ "tags" TEXT[],++ CONSTRAINT "warehouseTransfer_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "warehouseTransfer_transferId_key" UNIQUE ("transferId", "companyId"),+ CONSTRAINT "warehouseTransfer_fromLocationId_fkey" FOREIGN KEY ("fromLocationId") REFERENCES "location"("id") ON DELETE RESTRICT,+ CONSTRAINT "warehouseTransfer_toLocationId_fkey" FOREIGN KEY ("toLocationId") REFERENCES "location"("id") ON DELETE RESTRICT,+ CONSTRAINT "warehouseTransfer_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,+ CONSTRAINT "warehouseTransfer_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT,+ CONSTRAINT "warehouseTransfer_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT);+INSERT INTO "customFieldTable" ("table", "name", "module")+VALUES ('warehouseTransfer', 'Warehouse Transfer', 'Inventory');+-- Warehouse Transfer Line TableCREATE TABLE "warehouseTransferLine" ("id" TEXT NOT NULL DEFAULT xid(),"transferId" TEXT NOT NULL,"itemId" TEXT NOT NULL,- "itemReadableId" TEXT,- "quantity" NUMERIC(18, 4) NOT NULL DEFAULT 0,- "shippedQuantity" NUMERIC(18, 4) NOT NULL DEFAULT 0,- "receivedQuantity" NUMERIC(18, 4) NOT NULL DEFAULT 0,+ "quantity" NUMERIC NOT NULL DEFAULT 0,+ "shippedQuantity" NUMERIC NOT NULL DEFAULT 0,+ "receivedQuantity" NUMERIC NOT NULL DEFAULT 0,"fromLocationId" TEXT NOT NULL,"fromShelfId" TEXT,"toLocationId" TEXT NOT NULL,@@ -50,62 +58,35 @@ CREATE TABLE "warehouseTransferLine" ("createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"updatedBy" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,- "customFields" JSONB+ "customFields" JSONB,++ CONSTRAINT "warehouseTransferLine_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "warehouseTransferLine_transferId_fkey" FOREIGN KEY ("transferId") REFERENCES "warehouseTransfer"("id") ON DELETE CASCADE,+ CONSTRAINT "warehouseTransferLine_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE RESTRICT,+ CONSTRAINT "warehouseTransferLine_fromLocationId_fkey" FOREIGN KEY ("fromLocationId") REFERENCES "location"("id") ON DELETE RESTRICT,+ CONSTRAINT "warehouseTransferLine_toLocationId_fkey" FOREIGN KEY ("toLocationId") REFERENCES "location"("id") ON DELETE RESTRICT,+ CONSTRAINT "warehouseTransferLine_fromShelfId_fkey" FOREIGN KEY ("fromShelfId") REFERENCES "shelf"("id") ON DELETE SET NULL,+ CONSTRAINT "warehouseTransferLine_toShelfId_fkey" FOREIGN KEY ("toShelfId") REFERENCES "shelf"("id") ON DELETE SET NULL,+ CONSTRAINT "warehouseTransferLine_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON DELETE SET NULL,+ CONSTRAINT "warehouseTransferLine_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,+ CONSTRAINT "warehouseTransferLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT,+ CONSTRAINT "warehouseTransferLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT);--- Primary Keys-ALTER TABLE "warehouseTransfer" ADD CONSTRAINT "warehouseTransfer_pkey" PRIMARY KEY ("id");-ALTER TABLE "warehouseTransferLine" ADD CONSTRAINT "warehouseTransferLine_pkey" PRIMARY KEY ("id");---- Foreign Key Constraints-ALTER TABLE "warehouseTransfer" ADD CONSTRAINT "warehouseTransfer_fromLocationId_fkey"- FOREIGN KEY ("fromLocationId") REFERENCES "location"("id") ON DELETE RESTRICT;--ALTER TABLE "warehouseTransfer" ADD CONSTRAINT "warehouseTransfer_toLocationId_fkey"- FOREIGN KEY ("toLocationId") REFERENCES "location"("id") ON DELETE RESTRICT;--ALTER TABLE "warehouseTransfer" ADD CONSTRAINT "warehouseTransfer_companyId_fkey"- FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;--ALTER TABLE "warehouseTransfer" ADD CONSTRAINT "warehouseTransfer_createdBy_fkey"- FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT;--ALTER TABLE "warehouseTransfer" ADD CONSTRAINT "warehouseTransfer_updatedBy_fkey"- FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT;--ALTER TABLE "warehouseTransferLine" ADD CONSTRAINT "warehouseTransferLine_transferId_fkey"- FOREIGN KEY ("transferId") REFERENCES "warehouseTransfer"("id") ON DELETE CASCADE;--ALTER TABLE "warehouseTransferLine" ADD CONSTRAINT "warehouseTransferLine_itemId_fkey"- FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE RESTRICT;--ALTER TABLE "warehouseTransferLine" ADD CONSTRAINT "warehouseTransferLine_fromLocationId_fkey"- FOREIGN KEY ("fromLocationId") REFERENCES "location"("id") ON DELETE RESTRICT;--ALTER TABLE "warehouseTransferLine" ADD CONSTRAINT "warehouseTransferLine_toLocationId_fkey"- FOREIGN KEY ("toLocationId") REFERENCES "location"("id") ON DELETE RESTRICT;--ALTER TABLE "warehouseTransferLine" ADD CONSTRAINT "warehouseTransferLine_fromShelfId_fkey"- FOREIGN KEY ("fromShelfId") REFERENCES "shelf"("id") ON DELETE SET NULL;--ALTER TABLE "warehouseTransferLine" ADD CONSTRAINT "warehouseTransferLine_toShelfId_fkey"- FOREIGN KEY ("toShelfId") REFERENCES "shelf"("id") ON DELETE SET NULL;--ALTER TABLE "warehouseTransferLine" ADD CONSTRAINT "warehouseTransferLine_unitOfMeasureCode_fkey"- FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON DELETE SET NULL;--ALTER TABLE "warehouseTransferLine" ADD CONSTRAINT "warehouseTransferLine_companyId_fkey"- FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;--ALTER TABLE "warehouseTransferLine" ADD CONSTRAINT "warehouseTransferLine_createdBy_fkey"- FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT;--ALTER TABLE "warehouseTransferLine" ADD CONSTRAINT "warehouseTransferLine_updatedBy_fkey"- FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT;---- Unique Constraints-ALTER TABLE "warehouseTransfer" ADD CONSTRAINT "warehouseTransfer_transferId_companyId_key"- UNIQUE ("transferId", "companyId");+INSERT INTO "customFieldTable" ("table", "name", "module")+VALUES ('warehouseTransferLine', 'Warehouse Transfer Line', 'Inventory');++INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step", "companyId")+SELECT+ 'warehouseTransfer',+ 'Warehouse Transfer',+ 'WT',+ NULL,+ 0,+ 6,+ 1,+ "id"+FROM "company";-- IndexesCREATE INDEX "warehouseTransfer_companyId_idx" ON "warehouseTransfer"("companyId");