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 form for adding warehouse transfer line
Brad Barbin4b7a35cc7ecd
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex d88454df91..85b9be217e 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -966,64 +966,51 @@ export async function upsertWarehouseTransfer(.single();}-export async function shipWarehouseTransfer(+export async function updateWarehouseTransferStatus(client: SupabaseClient<Database>,transferId: string,- quantity: number,+ status: Database["public"]["Tables"]["warehouseTransfer"]["Row"]["status"],updatedBy: string) {- // Update all transfer lines to mark quantities as shipped- const linesUpdate = await client- .from("warehouseTransferLine")- .update({- shippedQuantity: quantity,- updatedBy,- updatedAt: new Date().toISOString(),- })- .eq("transferId", transferId);-- if (linesUpdate.error) {- return linesUpdate;- }-- // Update transfer status to In Transitreturn client.from("warehouseTransfer").update({- status: "In Transit",+ status,updatedBy,updatedAt: new Date().toISOString(),}).eq("id", transferId);}-export async function receiveWarehouseTransfer(+export async function upsertWarehouseTransferLine(client: SupabaseClient<Database>,- transferId: string,- quantity: number,- updatedBy: string+ line:+ | Database["public"]["Tables"]["warehouseTransferLine"]["Insert"]+ | (Database["public"]["Tables"]["warehouseTransferLine"]["Update"] & {+ id: string;+ })) {- // Update all transfer lines to mark quantities as received- const linesUpdate = await client- .from("warehouseTransferLine")- .update({- receivedQuantity: quantity,- updatedBy,- updatedAt: new Date().toISOString(),- })- .eq("transferId", transferId);-- if (linesUpdate.error) {- return linesUpdate;+ if ("id" in line && line.id) {+ // Update existing line+ const { id, ...updateData } = line;+ return client+ .from("warehouseTransferLine")+ .update({+ ...updateData,+ updatedAt: new Date().toISOString(),+ })+ .eq("id", id)+ .select()+ .single();+ } else {+ // Insert new line+ return client+ .from("warehouseTransferLine")+ .insert({+ ...line,+ createdAt: new Date().toISOString(),+ } as Database["public"]["Tables"]["warehouseTransferLine"]["Insert"])+ .select()+ .single();}-- // Update transfer status to Received- return client- .from("warehouseTransfer")- .update({- status: "Received",- updatedBy,- updatedAt: new Date().toISOString(),- })- .eq("id", transferId);}diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader.tsxindex 87e4cd1acd..fa0a551690 100644--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader.tsx+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferHeader.tsx@@ -11,7 +11,7 @@ import {HStack,toast,} from "@carbon/react";-import { Link } from "@remix-run/react";+import { Link, useFetcher } from "@remix-run/react";import { useCallback, useEffect, useState } from "react";import {LuCheckCheck,@@ -19,9 +19,11 @@ import {LuCirclePlus,LuCircleStop,LuHandCoins,+ LuLoaderCircle,LuTruck,} from "react-icons/lu";import { usePermissions } from "~/hooks";+import type { action as statusAction } from "~/routes/x+/warehouse-transfer+/$transferId.status";import { path } from "~/utils/path";import type { Receipt, Shipment, WarehouseTransfer } from "../../types";import { ReceiptStatus } from "../Receipts";@@ -36,6 +38,7 @@ const WarehouseTransferHeader = ({warehouseTransfer,}: WarehouseTransferHeaderProps) => {const permissions = usePermissions();+ const statusFetcher = useFetcher<typeof statusAction>();const { receipts, shipments, ship, receive } =useWarehouseTransferRelatedDocuments(warehouseTransfer.id);@@ -52,37 +55,53 @@ const WarehouseTransferHeader = ({<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")- }+ <statusFetcher.Form+ method="post"+ action={path.to.warehouseTransferStatus(warehouseTransfer.id)}>- Confirm- </Button>+ <input type="hidden" name="status" value="To Ship and Receive" />+ <Button+ type="submit"+ leftIcon={<LuCheckCheck />}+ variant={+ warehouseTransfer.status === "Draft" ? "primary" : "secondary"+ }+ isDisabled={+ !["Draft"].includes(warehouseTransfer.status) ||+ statusFetcher.state !== "idle" ||+ !permissions.can("update", "inventory")+ }+ isLoading={+ statusFetcher.state !== "idle" &&+ statusFetcher.formData?.get("status") === "To Ship and Receive"+ }+ >+ Confirm+ </Button>+ </statusFetcher.Form>- <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")- }+ <statusFetcher.Form+ method="post"+ action={path.to.warehouseTransferStatus(warehouseTransfer.id)}>- Cancel- </Button>+ <input type="hidden" name="status" value="Cancelled" />+ <Button+ type="submit"+ variant="secondary"+ leftIcon={<LuCircleStop />}+ isDisabled={+ ["Cancelled", "Completed"].includes(warehouseTransfer.status) ||+ statusFetcher.state !== "idle" ||+ !permissions.can("update", "inventory")+ }+ isLoading={+ statusFetcher.state !== "idle" &&+ statusFetcher.formData?.get("status") === "Cancelled"+ }+ >+ Cancel+ </Button>+ </statusFetcher.Form>{shipments.length > 0 ? (<DropdownMenu>@@ -212,6 +231,28 @@ const WarehouseTransferHeader = ({Receive</Button>)}+ <statusFetcher.Form+ method="post"+ action={path.to.warehouseTransferStatus(warehouseTransfer.id)}+ >+ <input type="hidden" name="status" value="Draft" />+ <Button+ type="submit"+ variant="secondary"+ leftIcon={<LuLoaderCircle />}+ isDisabled={+ ["Draft"].includes(warehouseTransfer.status ?? "") ||+ statusFetcher.state !== "idle" ||+ !permissions.can("update", "inventory")+ }+ isLoading={+ statusFetcher.state !== "idle" &&+ statusFetcher.formData?.get("status") === "Draft"+ }+ >+ Reopen+ </Button>+ </statusFetcher.Form></HStack></HStack></div>diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsxnew file mode 100644index 0000000000..175ac677e2--- /dev/null+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx@@ -0,0 +1,197 @@+import { ValidatedForm } from "@carbon/form";+import {+ Button,+ Drawer,+ DrawerBody,+ DrawerContent,+ DrawerFooter,+ DrawerHeader,+ DrawerTitle,+ HStack,+ toast,+ VStack,+} from "@carbon/react";+import { useFetcher, useParams } from "@remix-run/react";+import { useEffect, useState } from "react";+import { z } from "zod";+import { zfd } from "zod-form-data";+import {+ CustomFormFields,+ Hidden,+ Item,+ Number,+ Shelf,+ Submit,+ TextArea,+ UnitOfMeasure,+} from "~/components/Form";+import { usePermissions } from "~/hooks";+import type { MethodItemType } from "~/modules/shared/types";+import { useItems } from "~/stores/items";+import { path } from "~/utils/path";+import type { WarehouseTransfer } from "../../types";++const warehouseTransferLineFormValidator = z.discriminatedUnion("type", [+ z.object({+ id: zfd.text(z.string().optional()),+ type: z.literal("create"),+ transferId: z.string().min(1),+ fromLocationId: z.string().min(1),+ toLocationId: 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),+ transferId: z.string().min(1),+ fromLocationId: z.string().min(1),+ toLocationId: 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()),+ }),+]);++type WarehouseTransferLineFormProps = {+ initialValues: z.infer<typeof warehouseTransferLineFormValidator>;+ warehouseTransfer: WarehouseTransfer;+ onClose: () => void;+};++const WarehouseTransferLineForm = ({+ initialValues,+ warehouseTransfer,+ onClose,+}: WarehouseTransferLineFormProps) => {+ const permissions = usePermissions();+ const { transferId } = useParams();++ if (!transferId) {+ throw new Error("transferId is required");+ }++ const [itemData, setItemData] = useState<{+ itemId: string;+ unitOfMeasureCode: string;+ }>();++ const [items] = useItems();+ const [itemType, setItemType] = useState<MethodItemType>(+ // @ts-expect-error - Service+ items.find((item) => item.id === initialValues.itemId)?.type ?? "Item"+ );++ const isEditing = initialValues.id !== undefined;+ const isDisabled = isEditing+ ? !permissions.can("update", "inventory")+ : !permissions.can("create", "inventory");++ const action = path.to.warehouseTransferLines(transferId);++ const fetcher = useFetcher<{ success: boolean; message: string }>();++ useEffect(() => {+ if (fetcher.data?.success) {+ onClose();+ } else if (fetcher.data?.message) {+ toast.error(fetcher.data.message);+ }+ }, [fetcher.data?.success, fetcher.data?.message, onClose]);++ return (+ <Drawer+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <DrawerContent>+ <ValidatedForm+ defaultValues={initialValues}+ validator={warehouseTransferLineFormValidator}+ method="post"+ action={action}+ className="flex flex-col h-full"+ fetcher={fetcher}+ >+ <DrawerHeader>+ <DrawerTitle>+ {isEditing ? "Edit" : "New"} Transfer Line+ </DrawerTitle>+ </DrawerHeader>+ <DrawerBody>+ <Hidden name="id" />+ <Hidden name="transferId" />+ <Hidden name="fromLocationId" />+ <Hidden name="toLocationId" />+ <Hidden name="type" value={isEditing ? "update" : "create"} />++ <VStack spacing={4}>+ <Item+ name="itemId"+ label="Item"+ type={itemType}+ onTypeChange={(t) => setItemType(t as MethodItemType)}+ value={itemData?.itemId}+ onChange={(value) => {+ setItemData({+ itemId: value?.value as string,+ unitOfMeasureCode:+ items.find((item) => item.id === value?.value)+ ?.unitOfMeasureCode ?? "",+ });+ }}+ />+ <Number+ name="quantity"+ label="Quantity"+ minValue={0.0001}+ step={0.0001}+ />+ <UnitOfMeasure+ name="unitOfMeasureCode"+ label="Unit of Measure"+ value={itemData?.unitOfMeasureCode}+ disabled+ />+ <Shelf+ name="fromShelfId"+ label="From Shelf"+ locationId={warehouseTransfer.fromLocationId}+ />+ <Shelf+ name="toShelfId"+ label="To Shelf"+ locationId={warehouseTransfer.toLocationId}+ />+ <TextArea name="notes" label="Notes" rows={3} />+ <CustomFormFields table="warehouseTransferLine" />+ </VStack>+ </DrawerBody>+ <DrawerFooter>+ <HStack>+ <Submit+ isDisabled={isDisabled || fetcher.state !== "idle"}+ isLoading={fetcher.state !== "idle"}+ withBlocker={false}+ >+ Save+ </Submit>+ <Button size="md" variant="solid" onClick={onClose}>+ Cancel+ </Button>+ </HStack>+ </DrawerFooter>+ </ValidatedForm>+ </DrawerContent>+ </Drawer>+ );+};++export default WarehouseTransferLineForm;diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsxindex b499314a00..a75a9d89d5 100644--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx@@ -1,113 +1,149 @@-import { VStack } from "@carbon/react";+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 { LuHash, LuPackage, LuMapPin } from "react-icons/lu";-import { Table } from "~/components";-import type { WarehouseTransferLine } from "../../types";+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";+import { useItems } from "~/stores";+import { getItemReadableId } from "~/utils/items";+import useWarehouseTransferLines from "./useWarehouseTransferLines";type WarehouseTransferLinesProps = {warehouseTransferLines: WarehouseTransferLine[];transferId: string;+ warehouseTransfer: WarehouseTransfer;+ compact?: boolean;};-const WarehouseTransferLines = ({ warehouseTransferLines }: WarehouseTransferLinesProps) => {- const columns = useMemo<ColumnDef<WarehouseTransferLine>[]>(() => [- {- accessorKey: "itemReadableId",- header: "Item",- cell: ({ row }) => row.original.item?.readableIdWithRevision || row.original.itemReadableId || "N/A",- meta: {- icon: <LuPackage />,- },- },- {- id: "itemName",- header: "Item Name",- cell: ({ row }) => row.original.item?.name || "N/A",- meta: {- icon: <LuHash />,- },- },- {- accessorKey: "quantity",- header: "Quantity",- cell: ({ row }) => {- const quantity = Number(row.original.quantity);- return quantity.toLocaleString();- },- meta: {- icon: <LuHash />,- },- },- {- accessorKey: "shippedQuantity",- header: "Shipped",- cell: ({ row }) => {- const quantity = Number(row.original.shippedQuantity || 0);- return quantity.toLocaleString();- },- meta: {- icon: <LuHash />,- },- },- {- accessorKey: "receivedQuantity",- header: "Received",- cell: ({ row }) => {- const quantity = Number(row.original.receivedQuantity || 0);- return quantity.toLocaleString();- },- meta: {- icon: <LuHash />,+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>+ );+ },},- },- {- id: "fromShelf",- header: "From Shelf",- cell: ({ row }) => row.original.fromShelf?.name || "N/A",- meta: {- icon: <LuMapPin />,+ {+ accessorKey: "quantity",+ header: "Quantity",+ cell: (item) => Number(item.getValue<number>()).toLocaleString(),},- },- {- id: "toShelf",- header: "To Shelf",- cell: ({ row }) => row.original.toShelf?.name || "N/A",- meta: {- icon: <LuMapPin />,+ {+ accessorKey: "fromShelfId",+ header: "From Shelf",+ cell: ({ row }) => row.original.fromShelf?.name || "N/A",},- },- {- accessorKey: "unitOfMeasureCode",- header: "UoM",- cell: ({ row }) => row.original.unitOfMeasureCode || "N/A",- meta: {- icon: <LuHash />,+ {+ accessorKey: "toShelfId",+ header: "To Shelf",+ cell: ({ row }) => row.original.toShelf?.name || "N/A",},- },- {- accessorKey: "notes",- header: "Notes",- cell: ({ row }) => row.original.notes || "",- meta: {- icon: <LuHash />,+ {+ accessorKey: "unitOfMeasureCode",+ header: "UoM",+ cell: (item) => item.getValue(),},- },- ], []);+ ];+ return defaultColumns;+ }, [items]);++ const editableComponents = useMemo(+ () => ({+ quantity: EditableNumber(onCellEdit),+ fromShelfId: EditableList(onCellEdit, fromShelfOptions),+ toShelfId: EditableList(onCellEdit, toShelfOptions),+ }),+ [onCellEdit, fromShelfOptions, toShelfOptions]+ );return (- <VStack spacing={4} className="w-full">- <Table<WarehouseTransferLine>- data={warehouseTransferLines}- columns={columns}- count={warehouseTransferLines.length}- title="Transfer Lines"- defaultColumnVisibility={{- notes: false,- }}- />- </VStack>+ <>+ <Card className={cn(compact && "border-none p-0 dark:shadow-none")}>+ <CardHeader className={cn(compact && "px-0")}>+ <CardTitle>Transfer Lines</CardTitle>+ </CardHeader>+ <CardContent className={cn(compact && "px-0")}>+ <Grid<TransferLine>+ contained={false}+ data={linesWithReadableIds}+ columns={columns}+ canEdit={canEdit}+ editableComponents={editableComponents}+ onNewRow={canEdit ? () => navigate("new") : undefined}+ />+ </CardContent>+ </Card>+ <Outlet />+ </>);};+export default WarehouseTransferLines;\ No newline at end of filediff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/index.ts b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/index.tsindex 8f7f9cda3f..ae572db686 100644--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/index.ts+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/index.ts@@ -1,5 +1,6 @@export { default as WarehouseTransfersTable } from "./WarehouseTransfersTable";export { default as WarehouseTransferHeader } from "./WarehouseTransferHeader";export { default as WarehouseTransferLines } from "./WarehouseTransferLines";+export { default as WarehouseTransferLineForm } from "./WarehouseTransferLineForm";export { default as WarehouseTransferStatus } from "./WarehouseTransferStatus";export { default as WarehouseTransferForm } from "./WarehouseTransferForm";\ No newline at end of filediff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/useWarehouseTransferLines.ts b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/useWarehouseTransferLines.tsnew file mode 100644index 0000000000..7c1df2d0fc--- /dev/null+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/useWarehouseTransferLines.ts@@ -0,0 +1,39 @@+import { useFetcher } from "@remix-run/react";+import { useCallback } from "react";+import type { WarehouseTransfer } from "~/modules/inventory";+import { usePermissions } from "~/hooks";+import { path } from "~/utils/path";++export default function useWarehouseTransferLines(+ warehouseTransfer: WarehouseTransfer+) {+ const fetcher = useFetcher();+ const permissions = usePermissions();++ const isEditable = ["Draft", "To Ship and Receive", "To Ship"].includes(+ warehouseTransfer.status+ );+ const canEdit = isEditable && permissions.can("update", "inventory");++ const onCellEdit = useCallback(+ (id: string, value: any, field: string) => {+ if (!canEdit) return;++ const formData = new FormData();+ formData.append("type", "update");+ formData.append("id", id);+ formData.append(field, value?.toString() ?? "");++ fetcher.submit(formData, {+ method: "post",+ action: path.to.warehouseTransferLines(warehouseTransfer.id),+ });+ },+ [canEdit, fetcher, warehouseTransfer.id]+ );++ return {+ canEdit,+ onCellEdit,+ };+}\ No newline at end of filediff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId._index.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId._index.tsxnew file mode 100644index 0000000000..dbb96dbeb7--- /dev/null+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId._index.tsx@@ -0,0 +1,9 @@+import type { LoaderFunctionArgs } from "@vercel/remix";+import { redirect } from "@vercel/remix";+import { path } from "~/utils/path";++export async function loader({ params }: LoaderFunctionArgs) {+ const { transferId } = params;+ if (!transferId) throw new Error("Could not find transferId");+ throw redirect(path.to.warehouseTransferDetails(transferId));+}\ No newline at end of filediff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.new.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.new.tsxnew file mode 100644index 0000000000..1974941c2a--- /dev/null+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.new.tsx@@ -0,0 +1,45 @@+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.warehouseTransfer(transferId))}+ />+ );+}diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.tsxnew file mode 100644index 0000000000..2a9a7ce0d1--- /dev/null+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.details.tsx@@ -0,0 +1,95 @@+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 { 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 {+ getWarehouseTransfer,+ upsertWarehouseTransfer,+ warehouseTransferValidator,+} from "~/modules/inventory";+import {+ WarehouseTransferForm,+ WarehouseTransferLines,+} from "~/modules/inventory/ui/WarehouseTransfers";+import { getCustomFields, setCustomFields } from "~/utils/form";+import { path } from "~/utils/path";++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "inventory",+ });++ const formData = await request.formData();+ const validation = await validator(warehouseTransferValidator).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;+ if (!id) throw new Error("id not found");++ const updateTransfer = await upsertWarehouseTransfer(client, {+ id,+ ...data,+ updatedBy: userId,+ customFields: setCustomFields(formData),+ });++ if (updateTransfer.error) {+ return json(+ {},+ await flash(+ request,+ error(updateTransfer.error, "Failed to update warehouse transfer")+ )+ );+ }++ throw redirect(+ path.to.warehouseTransfer(id),+ await flash(request, success("Updated warehouse transfer"))+ );+}++export default function WarehouseTransferDetailsRoute() {+ 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 = {+ ...routeData.warehouseTransfer,+ transferId: routeData.warehouseTransfer.transferId ?? undefined,+ reference: routeData.warehouseTransfer.reference ?? undefined,+ notes: routeData.warehouseTransfer.notes ?? undefined,+ ...getCustomFields(routeData.warehouseTransfer.customFields),+ };++ return (+ <div className="flex flex-col gap-2 pb-16 w-full">+ <WarehouseTransferForm+ key={initialValues.id}+ initialValues={initialValues}+ />++ <WarehouseTransferLines+ warehouseTransferLines={routeData.warehouseTransferLines}+ transferId={transferId}+ warehouseTransfer={routeData.warehouseTransfer}+ />+ </div>+ );+}\ No newline at end of filediff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.lines.new.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.lines.new.tsxnew file mode 100644index 0000000000..c858684996--- /dev/null+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.lines.new.tsx@@ -0,0 +1,42 @@+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 filediff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.lines.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.lines.tsxnew file mode 100644index 0000000000..376fc65208--- /dev/null+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.lines.tsx@@ -0,0 +1,129 @@+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 filediff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.receive.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.receive.tsxdeleted file mode 100644index 20f869f04f..0000000000--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.receive.tsx+++ /dev/null@@ -1,33 +0,0 @@-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 { redirect } from "@vercel/remix";-import { receiveWarehouseTransfer } from "~/modules/inventory";-import { path } from "~/utils/path";--export async function action({ request, params }: ActionFunctionArgs) {- const { client, userId } = await requirePermissions(request, {- update: "inventory",- });-- const { transferId } = params;- if (!transferId) throw new Response("Not found", { status: 404 });-- const result = await receiveWarehouseTransfer(client, transferId, 0, userId);-- if (result.error) {- throw redirect(- path.to.warehouseTransferDetails(transferId),- await flash(- request,- error(result.error, "Failed to receive warehouse transfer")- )- );- }-- throw redirect(- path.to.warehouseTransferDetails(transferId),- await flash(request, success("Warehouse transfer received successfully"))- );-}diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.ship.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.ship.tsxdeleted file mode 100644index 495baee373..0000000000--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.ship.tsx+++ /dev/null@@ -1,33 +0,0 @@-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 { redirect } from "@vercel/remix";-import { shipWarehouseTransfer } from "~/modules/inventory";-import { path } from "~/utils/path";--export async function action({ request, params }: ActionFunctionArgs) {- const { client, userId } = await requirePermissions(request, {- update: "inventory",- });-- const { transferId } = params;- if (!transferId) throw new Response("Not found", { status: 404 });-- const result = await shipWarehouseTransfer(client, transferId, userId);-- if (result.error) {- throw redirect(- path.to.warehouseTransferDetails(transferId),- await flash(- request,- error(result.error, "Failed to ship warehouse transfer")- )- );- }-- throw redirect(- path.to.warehouseTransferDetails(transferId),- await flash(request, success("Warehouse transfer shipped successfully"))- );-}\ No newline at end of filediff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsxnew file mode 100644index 0000000000..709751d9c1--- /dev/null+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.status.tsx@@ -0,0 +1,45 @@+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 { warehouseTransferStatusType, updateWarehouseTransferStatus } from "~/modules/inventory";+import { path } from "~/utils/path";++export const config = {+ runtime: "nodejs",+};++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "inventory",+ });++ const { transferId: id } = params;+ if (!id) throw new Error("Could not find id");++ const formData = await request.formData();+ const status = formData.get("status") as (typeof warehouseTransferStatusType)[number];++ if (!status || !warehouseTransferStatusType.includes(status)) {+ throw redirect(+ path.to.warehouseTransfer(id),+ await flash(request, error(null, "Invalid status"))+ );+ }++ const update = await updateWarehouseTransferStatus(client, id, status, userId);++ if (update.error) {+ throw redirect(+ path.to.warehouseTransfer(id),+ await flash(request, error(update.error, "Failed to update warehouse transfer status"))+ );+ }++ throw redirect(+ path.to.warehouseTransfer(id),+ await flash(request, success("Updated warehouse transfer status"))+ );+}\ No newline at end of filediff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.update.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.update.tsxnew file mode 100644index 0000000000..a47b036d01--- /dev/null+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.update.tsx@@ -0,0 +1,52 @@+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 type { ActionFunctionArgs } from "@vercel/remix";+import { json } from "@vercel/remix";+import { z } from "zod";+import { updateWarehouseTransferStatus } from "~/modules/inventory";+import { warehouseTransferStatusType } from "~/modules/inventory/inventory.models";++const updateStatusValidator = z.object({+ status: z.enum(warehouseTransferStatusType),+});++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(updateStatusValidator).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const result = await updateWarehouseTransferStatus(+ client,+ transferId,+ validation.data.status,+ userId+ );++ if (result.error) {+ return json(+ { error: result.error },+ await flash(+ request,+ error(result.error, "Failed to update warehouse transfer status")+ )+ );+ }++ return json(+ { success: true },+ await flash(request, success("Updated warehouse transfer status"))+ );+}\ No newline at end of filediff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 1504b84809..519fa648ff 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -1222,12 +1222,20 @@ export const path = {warehouseTransfer: (id: string) =>generatePath(`${x}/warehouse-transfer/${id}`),warehouseTransferDetails: (id: string) =>- generatePath(`${x}/warehouse-transfer/${id}`),+ generatePath(`${x}/warehouse-transfer/${id}/details`),+ warehouseTransferStatus: (id: string) =>+ generatePath(`${x}/warehouse-transfer/${id}/status`),warehouseTransferShip: (id: string) =>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`),+ warehouseTransferLine: (transferId: string, lineId: string) =>+ generatePath(`${x}/warehouse-transfer/${transferId}/lines/${lineId}`),deleteWarehouseTransfer: (id: string) =>generatePath(`${x}/warehouse-transfer/${id}/delete`),shippingMethods: `${x}/inventory/shipping-methods`,diff --git a/llm/cache/shipments-receipts-ui-patterns.md b/llm/cache/shipments-receipts-ui-patterns.mdnew file mode 100644index 0000000000..c31771279a--- /dev/null+++ b/llm/cache/shipments-receipts-ui-patterns.md@@ -0,0 +1,205 @@+# Shipments, Receipts, and Warehouse Transfers UI Patterns++## Overview++Shipments, receipts, and warehouse transfers in Carbon follow a consistent pattern with a header-detail structure, where the main document has associated line items. All three use similar UI patterns for forms, line item management, and status workflows.++## Route Structure++### Shipments+- List view: `/routes/x+/inventory+/shipments.tsx`+- Detail routes: `/routes/x+/shipment+/`+ - `$shipmentId.tsx` - Main layout with header+ - `$shipmentId._index.tsx` - Redirects to details+ - `$shipmentId.details.tsx` - Form and lines view+ - `$shipmentId.post.tsx` - Posting action+ - `$shipmentId.delete.tsx` - Delete action+ - `lines.update.tsx` - Update line items+ - `lines.tracking.tsx` - Tracking management+ - `lines.split.tsx` - Split line items+ - `new.tsx` - Create new shipment++### Receipts+- List view: `/routes/x+/inventory+/receipts.tsx`+- Detail routes: `/routes/x+/receipt+/`+ - `$receiptId.tsx` - Main layout with header+ - `$receiptId._index.tsx` - Redirects to details+ - `$receiptId.details.tsx` - Form and lines view+ - `$receiptId.post.tsx` - Posting action+ - `$receiptId.delete.tsx` - Delete action+ - `lines.update.tsx` - Update line items+ - `lines.tracking.tsx` - Tracking management+ - `lines.split.tsx` - Split line items+ - `new.tsx` - Create new receipt++### Warehouse Transfers+- List view: `/routes/x+/inventory+/warehouse-transfers.tsx`+- Detail routes: `/routes/x+/warehouse-transfer+/`+ - `$transferId.tsx` - Main layout with header (current implementation)+ - `$transferId._index.tsx` - Redirects to details (new)+ - `$transferId.details.tsx` - Form and lines view (new)+ - `$transferId.lines.tsx` - Lines management (new)+ - `$transferId.status.tsx` - Status updates (new)+ - `$transferId.update.tsx` - Update transfer (new)+ - `new.tsx` - Create new transfer++## UI Components Structure++### Common Pattern+Both shipments and receipts follow this component structure:++1. **Header Component** (`ShipmentHeader`/`ReceiptHeader`)+ - Displays status badge+ - Shows key information (ID, dates, etc.)+ - Contains action buttons (Post, Delete, etc.)++2. **Form Component** (`ShipmentForm`/`ReceiptForm`)+ - Card-based layout+ - Grid layout for fields (2 columns on desktop)+ - Source document selection with dependent ID field+ - Location selection+ - Custom fields support+ - Delete functionality in dropdown menu (when not posted)++3. **Lines Component** (`ShipmentLines`/`ReceiptLines`)+ - Card with list of line items+ - Each line item shows:+ - Item thumbnail and details+ - Quantities (ordered/shipped/received/outstanding)+ - Shelf selection (context-dependent)+ - Action menu (split, delete)+ - Inline editing of quantities+ - Tracking support (batch/serial)+ - Real-time updates using fetchers++4. **Notes Component**+ - Rich text editor for internal/external notes+ - Shipments have both internal and external notes+ - Receipts only have internal notes++## Key Features++### Line Item Management+- **Inline Editing**: Quantities and shelves can be edited directly+- **Split Functionality**: Lines can be split into multiple lines+- **Tracking**: Support for batch and serial number tracking+- **Validation**: Real-time validation of quantities and tracking numbers+- **Shelf Assignment**: Automatic or manual shelf assignment++### Status Management+- Documents have status workflows (Draft → Posted)+- Posted documents become read-only+- Status affects available actions++### Source Document Integration+- Links to source documents (Sales Orders, Purchase Orders)+- Automatically populates line items from source+- Validates against source document quantities++## Refactoring Warehouse Transfers to Match++To refactor warehouse transfers to match this pattern:++1. **Route Structure**: Create similar route structure under `/routes/x+/warehouse-transfer+/`+ - Add `$transferId._index.tsx` to redirect to details+ - Add `$transferId.details.tsx` for main form/lines view+ - Add line management routes (update, split, etc.)++2. **Update Layout**: The current `$transferId.tsx` should follow the panel provider pattern++3. **Refactor Form**: `WarehouseTransferForm` should:+ - Use consistent Card layout+ - Add dropdown menu for actions+ - Support custom fields++4. **Transform Lines Component**: Replace table view with inline editable cards:+ - Show item details with thumbnails+ - Add quantity editing (transferred/shipped/received)+ - Add shelf selection for both from/to locations+ - Add split/delete functionality+ - Support tracking numbers++5. **Add Notes Component**: Include internal notes support++6. **Status Workflow**: Implement proper status management (Draft → Shipped → Received)++## Warehouse Transfer Data Models++### WarehouseTransfer Fields+**Main Transfer Document:**+- `id` - Unique identifier (auto-generated)+- `transferId` - User-friendly ID (e.g., "WT000001")+- `fromLocationId` - Source location (required)+- `toLocationId` - Destination location (required)+- `status` - Transfer status (see status types below)+- `transferDate` - Date of transfer initiation+- `expectedReceiptDate` - Expected arrival date+- `notes` - Internal notes+- `reference` - External reference number+- `customFields` - JSONB for custom data+- `tags` - Text array for categorization+- Audit fields: `companyId`, `createdBy`, `createdAt`, `updatedBy`, `updatedAt`++**Status Types:**+- `Draft` - Editable, not yet processed+- `To Ship and Receive` - Ready for both shipping and receiving+- `To Ship` - Needs to be shipped+- `To Receive` - Shipped, awaiting receipt+- `Completed` - Fully processed+- `Cancelled` - Cancelled transfer++### WarehouseTransferLine Fields+**Transfer Line Items:**+- `id` - Unique line identifier+- `transferId` - Parent transfer reference+- `itemId` - Item being transferred (required)+- `quantity` - Total quantity to transfer (required, > 0)+- `shippedQuantity` - Amount shipped (default 0)+- `receivedQuantity` - Amount received (default 0)+- `fromLocationId` - Source location (required)+- `fromShelfId` - Source shelf (optional)+- `toLocationId` - Destination location (required)+- `toShelfId` - Destination shelf (optional)+- `unitOfMeasureCode` - Unit of measure+- `notes` - Line-specific notes+- `customFields` - JSONB for custom line data+- Audit fields: `companyId`, `createdBy`, `createdAt`, `updatedBy`, `updatedAt`++### Editability Rules by Status+**Draft Status:**+- All fields editable+- Can add/remove lines+- Can change locations and shelves+- Can modify quantities++**To Ship and Receive / To Ship:**+- Transfer details (dates, reference, notes) editable+- Line quantities may be restricted+- Location changes typically not allowed+- Shelf assignments may be editable++**To Receive:**+- Most fields read-only+- Receiving quantities editable+- Destination shelf assignment editable++**Completed / Cancelled:**+- All fields read-only+- No modifications allowed++## Data Flow Patterns++### Optimistic Updates+- Uses Remix fetchers for optimistic UI updates+- Pending changes merged with server data+- Real-time feedback without full page reloads++### Validation+- Form-level validation using Zod schemas+- Inline validation for quantities and tracking+- Server-side validation on submission++### Error Handling+- Flash messages for server errors+- Inline error display for field validation+- Graceful handling of concurrent updates\ No newline at end of filediff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.tsindex f49ea3eaf3..585c0db7c0 100644--- a/packages/database/supabase/functions/convert/index.ts+++ b/packages/database/supabase/functions/convert/index.ts@@ -89,6 +89,18 @@ const payloadValidator = z.discriminatedUnion("type", [})),}),+ z.object({+ type: z.literal("warehouseTransferToShipment"),+ id: z.string(),+ companyId: z.string(),+ userId: z.string(),+ }),+ z.object({+ type: z.literal("warehouseTransferToReceipt"),+ id: z.string(),+ companyId: z.string(),+ userId: z.string(),+ }),]);serve(async (req: Request) => {@@ -737,10 +749,12 @@ serve(async (req: Request) => {return acc;}, []);- await trx- .insertInto("salesInvoiceLine")- .values(salesInvoiceLines)- .execute();+ if (salesInvoiceLines.length > 0) {+ await trx+ .insertInto("salesInvoiceLine")+ .values(salesInvoiceLines)+ .execute();+ }});return new Response(@@ -1533,6 +1547,150 @@ serve(async (req: Request) => {break;}+ case "warehouseTransferToShipment": {+ const warehouseTransferId = id;+ const [warehouseTransfer, warehouseTransferLines] = await Promise.all([+ client+ .from("warehouseTransfer")+ .select("*")+ .eq("id", warehouseTransferId)+ .single(),+ client+ .from("warehouseTransferLine")+ .select("*")+ .eq("transferId", warehouseTransferId),+ ]);++ if (warehouseTransfer.error)+ throw new Error(warehouseTransfer.error.message);+ if (warehouseTransferLines.error)+ throw new Error(warehouseTransferLines.error.message);++ let shipmentId = "";++ await db.transaction().execute(async (trx) => {+ // Create shipment for outbound transfer+ shipmentId = await getNextSequence(trx, "shipment", companyId);++ const shipment = await trx+ .insertInto("shipment")+ .values({+ shipmentId,+ status: "Draft",+ sourceDocument: "Outbound Transfer",+ sourceDocumentId: warehouseTransferId,+ sourceDocumentReadableId: warehouseTransfer.data.transferId,+ locationId: warehouseTransfer.data.fromLocationId,+ createdBy: userId,+ companyId,+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!shipment.id) throw new Error("Failed to create shipment");+ shipmentId = shipment.id;++ // Create shipment lines+ const shipmentLineInserts = warehouseTransferLines.data.map(+ (line) => ({+ shipmentId,+ lineId: line.id,+ itemId: line.itemId,+ locationId: line.fromLocationId,+ shelfId: line.fromShelfId,+ orderQuantity: line.quantity,+ shippedQuantity: 0,+ unitOfMeasure: line.unitOfMeasureCode || "EA",+ unitPrice: 0,+ companyId,+ createdBy: userId,+ })+ );++ if (shipmentLineInserts.length > 0) {+ await trx+ .insertInto("shipmentLine")+ .values(shipmentLineInserts)+ .execute();+ }+ });++ convertedId = shipmentId;+ break;+ }++ case "warehouseTransferToReceipt": {+ const warehouseTransferId = id;+ const [warehouseTransfer, warehouseTransferLines] = await Promise.all([+ client+ .from("warehouseTransfer")+ .select("*")+ .eq("id", warehouseTransferId)+ .single(),+ client+ .from("warehouseTransferLine")+ .select("*")+ .eq("transferId", warehouseTransferId),+ ]);++ if (warehouseTransfer.error)+ throw new Error(warehouseTransfer.error.message);+ if (warehouseTransferLines.error)+ throw new Error(warehouseTransferLines.error.message);++ let receiptId = "";++ await db.transaction().execute(async (trx) => {+ // Create receipt for inbound transfer+ receiptId = await getNextSequence(trx, "receipt", companyId);++ const receipt = await trx+ .insertInto("receipt")+ .values({+ receiptId,+ status: "Draft",+ sourceDocument: "Inbound Transfer",+ sourceDocumentId: warehouseTransferId,+ sourceDocumentReadableId: warehouseTransfer.data.transferId,+ locationId: warehouseTransfer.data.toLocationId,+ createdBy: userId,+ companyId,+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!receipt.id) throw new Error("Failed to create receipt");+ receiptId = receipt.id;++ // Create receipt lines+ const receiptLineInserts = warehouseTransferLines.data.map(+ (line) => ({+ receiptId,+ lineId: line.id,+ itemId: line.itemId,+ locationId: line.toLocationId,+ shelfId: line.toShelfId,+ orderQuantity: line.quantity,+ receivedQuantity: 0,+ unitOfMeasure: line.unitOfMeasureCode || "EA",+ unitPrice: 0,+ companyId,+ createdBy: userId,+ })+ );++ if (receiptLineInserts.length > 0) {+ await trx+ .insertInto("receiptLine")+ .values(receiptLineInserts)+ .execute();+ }+ });++ convertedId = receiptId;+ break;+ }+default:throw new Error(`Invalid type ${type}`);}diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.tsindex 127f2e3e13..d2d2285ca6 100644--- a/packages/database/supabase/functions/post-receipt/index.ts+++ b/packages/database/supabase/functions/post-receipt/index.ts@@ -999,6 +999,280 @@ serve(async (req: Request) => {});break;}+ case "Inbound Transfer": {+ if (!receipt.data.sourceDocumentId)+ throw new Error("Receipt has no sourceDocumentId");++ const [warehouseTransfer, warehouseTransferLines] = await Promise.all([+ client+ .from("warehouseTransfer")+ .select("*")+ .eq("id", receipt.data.sourceDocumentId)+ .single(),+ client+ .from("warehouseTransferLine")+ .select("*")+ .eq("transferId", receipt.data.sourceDocumentId),+ ]);++ if (warehouseTransfer.error)+ throw new Error("Failed to fetch warehouse transfer");+ if (warehouseTransferLines.error)+ throw new Error("Failed to fetch warehouse transfer lines");++ // Get item costs for valuation+ const transferItemIds = warehouseTransferLines.data+ .map((line) => line.itemId)+ .filter(Boolean) as string[];+ const itemCosts = await client+ .from("itemCost")+ .select("itemId, itemPostingGroupId, unitCost")+ .in("itemId", transferItemIds);++ if (itemCosts.error) {+ throw new Error("Failed to fetch item costs");+ }++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const journalLineInserts: Omit<+ Database["public"]["Tables"]["journalLine"]["Insert"],+ "journalId"+ >[] = [];+ const warehouseTransferLineUpdates: Record<+ string,+ Database["public"]["Tables"]["warehouseTransferLine"]["Update"]+ > = {};++ // Cache for inventory posting groups to avoid repeated queries+ const inventoryPostingGroups: Record<+ string,+ Database["public"]["Tables"]["postingGroupInventory"]["Row"] | null+ > = {};++ // Process each receipt line+ for await (const receiptLine of receiptLines.data) {+ const warehouseTransferLine = warehouseTransferLines.data.find(+ (line) => line.id === receiptLine.lineId+ );++ if (!warehouseTransferLine) continue;++ const receivedQuantity = receiptLine.receivedQuantity ?? 0;+ if (receivedQuantity === 0) continue;++ // Update warehouse transfer line received quantity+ const newReceivedQuantity =+ (warehouseTransferLine.receivedQuantity ?? 0) + receivedQuantity;++ warehouseTransferLineUpdates[warehouseTransferLine.id] = {+ receivedQuantity: newReceivedQuantity,+ };++ // Get item cost for this item+ const itemCost = itemCosts.data?.find(+ (cost) => cost.itemId === receiptLine.itemId+ );+ const unitCost = itemCost?.unitCost ?? 0;+ const totalValue = Math.abs(receivedQuantity) * unitCost;++ // Create item ledger entry for positive adjustment at destination+ itemLedgerInserts.push({+ postingDate: today,+ itemId: receiptLine.itemId,+ quantity: receivedQuantity,+ locationId: receiptLine.locationId,+ shelfId: receiptLine.shelfId,+ entryType: "Transfer",+ documentType: "Transfer Receipt",+ documentId: warehouseTransfer.data?.transferId,+ externalDocumentId: receipt.data?.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId,+ });++ // Create journal entries for inventory movement if there's value+ if (totalValue > 0 && itemCost?.itemPostingGroupId) {+ const fromLocationId = warehouseTransferLine.fromLocationId;+ const toLocationId = receiptLine.locationId;++ // Get inventory posting groups for both locations+ const fromGroupKey = `${itemCost.itemPostingGroupId}-${fromLocationId}`;+ const toGroupKey = `${itemCost.itemPostingGroupId}-${toLocationId}`;++ // Fetch from location posting group if not cached+ if (!(fromGroupKey in inventoryPostingGroups)) {+ const fromPostingGroup = await getInventoryPostingGroup(+ client,+ companyId,+ {+ itemPostingGroupId: itemCost.itemPostingGroupId,+ locationId: fromLocationId,+ }+ );+ inventoryPostingGroups[fromGroupKey] =+ fromPostingGroup.data ?? null;+ }++ // Fetch to location posting group if not cached+ if (!(toGroupKey in inventoryPostingGroups)) {+ const toPostingGroup = await getInventoryPostingGroup(+ client,+ companyId,+ {+ itemPostingGroupId: itemCost.itemPostingGroupId,+ locationId: toLocationId,+ }+ );+ inventoryPostingGroups[toGroupKey] = toPostingGroup.data ?? null;+ }++ const fromPostingGroup = inventoryPostingGroups[fromGroupKey];+ const toPostingGroup = inventoryPostingGroups[toGroupKey];++ if (fromPostingGroup && toPostingGroup) {+ const journalLineReference = nanoid();++ // Credit (subtract) inventory from source location+ journalLineInserts.push({+ accountNumber: fromPostingGroup.inventoryAccount,+ description: `Transfer Out - ${warehouseTransfer.data?.transferId}`,+ amount: credit("asset", totalValue),+ quantity: Math.abs(receivedQuantity),+ documentType: "Receipt",+ documentId: receipt.data?.id,+ externalDocumentId: warehouseTransfer.data?.transferId,+ documentLineReference: `transfer-receipt:${receiptLine.lineId}`,+ journalLineReference,+ companyId,+ });++ // Debit (add) inventory to destination location+ journalLineInserts.push({+ accountNumber: toPostingGroup.inventoryAccount,+ description: `Transfer In - ${warehouseTransfer.data?.transferId}`,+ amount: debit("asset", totalValue),+ quantity: Math.abs(receivedQuantity),+ documentType: "Receipt",+ documentId: receipt.data?.id,+ externalDocumentId: warehouseTransfer.data?.transferId,+ documentLineReference: `transfer-receipt:${receiptLine.lineId}`,+ journalLineReference,+ companyId,+ });+ }+ }+ }++ // Check if all lines are fully received+ const allLinesFullyReceived = warehouseTransferLines.data.every(+ (line) => {+ const updates = warehouseTransferLineUpdates[line.id];+ const receivedQty =+ updates?.receivedQuantity ?? line.receivedQuantity ?? 0;+ return receivedQty >= (line.quantity ?? 0);+ }+ );++ // Check if all lines are fully shipped+ const allLinesFullyShipped = warehouseTransferLines.data.every(+ (line) => {+ const shippedQty = line.shippedQuantity ?? 0;+ return shippedQty >= (line.quantity ?? 0);+ }+ );++ // Determine new warehouse transfer status+ let newStatus: Database["public"]["Tables"]["warehouseTransfer"]["Row"]["status"] =+ warehouseTransfer.data.status;++ if (allLinesFullyReceived && allLinesFullyShipped) {+ newStatus = "Completed";+ } else if (allLinesFullyReceived && !allLinesFullyShipped) {+ newStatus = "To Ship";+ } else if (!allLinesFullyReceived && allLinesFullyShipped) {+ newStatus = "To Receive";+ }++ const accountingPeriodId = await getCurrentAccountingPeriod(+ client,+ companyId,+ db+ );++ await db.transaction().execute(async (trx) => {+ // Update warehouse transfer lines+ for await (const [lineId, update] of Object.entries(+ warehouseTransferLineUpdates+ )) {+ await trx+ .updateTable("warehouseTransferLine")+ .set(update)+ .where("id", "=", lineId)+ .execute();+ }++ // Update warehouse transfer status+ await trx+ .updateTable("warehouseTransfer")+ .set({+ status: newStatus,+ updatedBy: userId,+ })+ .where("id", "=", warehouseTransfer.data.id)+ .execute();++ // Create journal entries if there are any+ if (journalLineInserts.length > 0) {+ const journal = await trx+ .insertInto("journal")+ .values({+ accountingPeriodId,+ description: `Transfer Receipt ${receipt.data.receiptId}`,+ postingDate: today,+ companyId,+ })+ .returning(["id"])+ .execute();++ const journalId = journal[0].id;+ if (!journalId) throw new Error("Failed to insert journal");++ await trx+ .insertInto("journalLine")+ .values(+ journalLineInserts.map((journalLine) => ({+ ...journalLine,+ journalId,+ }))+ )+ .returning(["id"])+ .execute();+ }++ // Create item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }++ // Update receipt status+ await trx+ .updateTable("receipt")+ .set({+ status: "Posted",+ postingDate: today,+ postedBy: userId,+ })+ .where("id", "=", receiptId)+ .execute();+ });++ break;+ }default: {break;}diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.tsindex c4edf07a77..98892a0185 100644--- a/packages/database/supabase/functions/post-shipment/index.ts+++ b/packages/database/supabase/functions/post-shipment/index.ts@@ -1142,6 +1142,138 @@ serve(async (req: Request) => {});break;}+ case "Outbound Transfer": {+ if (!shipment.data.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [warehouseTransfer, warehouseTransferLines] = await Promise.all([+ client+ .from("warehouseTransfer")+ .select("*")+ .eq("id", shipment.data.sourceDocumentId)+ .single(),+ client+ .from("warehouseTransferLine")+ .select("*")+ .eq("transferId", shipment.data.sourceDocumentId),+ ]);++ if (warehouseTransfer.error)+ throw new Error("Failed to fetch warehouse transfer");+ if (warehouseTransferLines.error)+ throw new Error("Failed to fetch warehouse transfer lines");++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] = [];+ const warehouseTransferLineUpdates: Record<+ string,+ Database["public"]["Tables"]["warehouseTransferLine"]["Update"]+ > = {};++ // Process each shipment line+ for await (const shipmentLine of shipmentLines.data) {+ const warehouseTransferLine = warehouseTransferLines.data.find(+ (line) => line.id === shipmentLine.lineId+ );++ if (!warehouseTransferLine) continue;++ const shippedQuantity = shipmentLine.shippedQuantity ?? 0;++ // Update warehouse transfer line shipped quantity+ const newShippedQuantity =+ (warehouseTransferLine.shippedQuantity ?? 0) + shippedQuantity;++ warehouseTransferLineUpdates[warehouseTransferLine.id] = {+ shippedQuantity: newShippedQuantity,+ };++ // Create item ledger entry for negative adjustment at source+ if (shippedQuantity !== 0) {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: -shippedQuantity, // Negative for outbound transfer+ locationId: shipmentLine.locationId,+ shelfId: shipmentLine.shelfId,+ entryType: "Transfer",+ documentType: "Transfer Shipment",+ documentId: warehouseTransfer.data?.transferId,+ externalDocumentId: shipment.data?.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId,+ });+ }+ }++ // Check if all lines are fully shipped+ const allLinesFullyShipped = warehouseTransferLines.data.every((line) => {+ const updates = warehouseTransferLineUpdates[line.id];+ const shippedQty = updates?.shippedQuantity ?? line.shippedQuantity ?? 0;+ return shippedQty >= (line.quantity ?? 0);+ });++ // Check if all lines are fully received+ const allLinesFullyReceived = warehouseTransferLines.data.every((line) => {+ const receivedQty = line.receivedQuantity ?? 0;+ return receivedQty >= (line.quantity ?? 0);+ });++ // Determine new warehouse transfer status+ let newStatus: Database["public"]["Tables"]["warehouseTransfer"]["Row"]["status"] =+ warehouseTransfer.data.status;++ if (allLinesFullyShipped && allLinesFullyReceived) {+ newStatus = "Completed";+ } else if (allLinesFullyShipped && !allLinesFullyReceived) {+ newStatus = "To Receive";+ } else if (!allLinesFullyShipped && allLinesFullyReceived) {+ newStatus = "To Ship";+ }++ await db.transaction().execute(async (trx) => {+ // Update warehouse transfer lines+ for await (const [lineId, update] of Object.entries(+ warehouseTransferLineUpdates+ )) {+ await trx+ .updateTable("warehouseTransferLine")+ .set(update)+ .where("id", "=", lineId)+ .execute();+ }++ // Update warehouse transfer status+ await trx+ .updateTable("warehouseTransfer")+ .set({+ status: newStatus,+ updatedBy: userId,+ })+ .where("id", "=", warehouseTransfer.data.id)+ .execute();++ // Create item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }++ // Update shipment status+ await trx+ .updateTable("shipment")+ .set({+ status: "Posted",+ postedBy: userId,+ })+ .where("id", "=", shipmentId)+ .execute();+ });++ break;+ }default: {throw new Error(`Invalid source document type: ${shipment.data.sourceDocument}`