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 crud for stock transfer lines
Brad Barbine5683fcae609
diff --git a/apps/erp/app/components/Form/Shelf.tsx b/apps/erp/app/components/Form/Shelf.tsxindex fdfdc55052..6a4d786e30 100644--- a/apps/erp/app/components/Form/Shelf.tsx+++ b/apps/erp/app/components/Form/Shelf.tsx@@ -54,6 +54,7 @@ const Shelf = (props: ShelfSelectProps) => {setCreated(option);}}/>+{newShelfModal.isOpen && (<ShelfFormlocationId={props.locationId!}@@ -75,32 +76,65 @@ export default Shelf;export function useShelves(locationId?: string, itemId?: string) {const shelvesFetcher =useFetcher<Awaited<ReturnType<typeof getShelvesList>>>();+ const shelvesWithQuantitiesFetcher =+ useFetcher<Awaited<ReturnType<typeof getShelvesList>>>();useEffect(() => {if (locationId) {if (itemId) {- // Use the new API route for shelves with quantities- shelvesFetcher.load(+ // Load both shelves with quantities and all shelves+ shelvesWithQuantitiesFetcher.load(path.to.api.shelvesWithQuantities(locationId, itemId));- } else {- // Use the existing API route for all shelves- shelvesFetcher.load(path.to.api.shelves(locationId));}+ shelvesFetcher.load(path.to.api.shelves(locationId));}// eslint-disable-next-line react-hooks/exhaustive-deps}, [locationId, itemId]);- const options = useMemo(- () =>+ const options = useMemo(() => {+ if (itemId && shelvesWithQuantitiesFetcher.data?.data) {+ // Create a map of shelves with quantities+ const shelvesWithQuantities = shelvesWithQuantitiesFetcher.data.data;+ const allShelves = shelvesFetcher.data?.data ?? [];++ // Create a set of shelf IDs that have quantities+ const shelfIdsWithQuantities = new Set(+ shelvesWithQuantities.map((s: any) => s.id)+ );++ // Filter out shelves that already have quantities from the all shelves list+ const shelvesWithoutQuantities = allShelves.filter(+ (shelf: any) => !shelfIdsWithQuantities.has(shelf.id)+ );++ // Combine the lists: shelves with quantities first, then others+ const combinedShelves = [+ ...shelvesWithQuantities.map((c: any) => ({+ value: c.id,+ label: c.name,+ helper: `Qty: ${c.quantity}`,+ })),+ ...shelvesWithoutQuantities.map((c: any) => ({+ value: c.id,+ label: c.name,+ })),+ ];++ return combinedShelves;+ }++ // Fallback to original behavior+ return (shelvesFetcher.data?.data?.map((c) => ({value: c.id,label: c.name,// Add quantity as helper text if available+ // @ts-ignore...(c.quantity !== undefined && { helper: `Qty: ${c.quantity}` }),- })) ?? [],- [shelvesFetcher.data]- );+ })) ?? []+ );+ }, [shelvesFetcher.data, shelvesWithQuantitiesFetcher.data, itemId]);return { options, data: shelvesFetcher.data };}diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 5788c773b8..9638c9d8ac 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -17,6 +17,7 @@ import type {shelfValidator,shipmentValidator,shippingMethodValidator,+ stockTransferLineValidator,stockTransferValidator,warehouseTransferValidator,} from "./inventory.models";@@ -264,6 +265,17 @@ export async function getStockTransfer(.single();}+export async function getStockTransferLine(+ client: SupabaseClient<Database>,+ stockTransferLineId: string+) {+ return client+ .from("stockTransferLine")+ .select("*")+ .eq("id", stockTransferLineId)+ .single();+}+export async function getStockTransferLines(client: SupabaseClient<Database>,stockTransferId: string@@ -1240,6 +1252,33 @@ export async function upsertStockTransfer(.single();}+export async function upsertStockTransferLine(+ client: SupabaseClient<Database>,+ stockTransferLine:+ | (Omit<z.infer<typeof stockTransferLineValidator>, "id"> & {+ companyId: string;+ createdBy: string;+ })+ | (Omit<z.infer<typeof stockTransferLineValidator>, "id"> & {+ id: string;+ updatedBy: string;+ })+) {+ if ("createdBy" in stockTransferLine) {+ return client+ .from("stockTransferLine")+ .insert(stockTransferLine)+ .select("id")+ .single();+ }+ return client+ .from("stockTransferLine")+ .update(sanitize(stockTransferLine))+ .eq("id", stockTransferLine.id)+ .select("id")+ .single();+}+export async function upsertStockTransferLines(client: SupabaseClient<Database>,args: {diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsxindex 36d2165608..a6818a86e6 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx@@ -1,6 +1,7 @@import {Button,Card,+ CardAction,CardContent,CardDescription,CardHeader,@@ -14,12 +15,14 @@ import {IconButton,VStack,cn,+ useDisclosure,} from "@carbon/react";import { getItemReadableId } from "@carbon/utils";-import { useParams } from "@remix-run/react";-import { useMemo } from "react";+import { Link, useParams } from "@remix-run/react";+import { useMemo, useState } from "react";import {LuCircleCheck,+ LuCirclePlus,LuEllipsisVertical,LuPencilLine,LuTrash,@@ -28,7 +31,8 @@ import { Empty, ItemThumbnail } from "~/components";import { Enumerable } from "~/components/Enumerable";import { useLocations } from "~/components/Form/Location";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";-import { useRouteData } from "~/hooks";+import { ConfirmDelete } from "~/components/Modals";+import { usePermissions, useRouteData } from "~/hooks";import type { StockTransfer, StockTransferLine } from "~/modules/inventory";import { useItems } from "~/stores";import { path } from "~/utils/path";@@ -39,6 +43,7 @@ export default function StockTransferLines() {if (!id) throw new Error("stock transfer id not found");const [items] = useItems();+ const permissions = usePermissions();const unitsOfMeasure = useUnitOfMeasure();const locations = useLocations();@@ -55,7 +60,10 @@ export default function StockTransferLines() {routeData?.stockTransfer?.status ?? "");- // read-only shelves; no update handler+ const [selectedLine, setSelectedLine] = useState<StockTransferLine | null>(+ null+ );+ const deleteDisclosure = useDisclosure();const lines = useMemo(() => {const list = routeData?.stockTransferLines ?? [];@@ -68,144 +76,188 @@ export default function StockTransferLines() {}, [routeData?.stockTransferLines, items]);return (- <Card>- <HStack className="justify-between items-start">- <CardHeader>- <CardTitle>Stock Transfer Lines</CardTitle>- <CardDescription>- <Enumerable- value={- locations?.find(- (l) => l.value === routeData?.stockTransfer?.locationId- )?.label ?? null- }- />- </CardDescription>- </CardHeader>- </HStack>+ <>+ <Card>+ <HStack className="justify-between items-start">+ <CardHeader>+ <CardTitle>Stock Transfer Lines</CardTitle>+ <CardDescription>+ <Enumerable+ value={+ locations?.find(+ (l) => l.value === routeData?.stockTransfer?.locationId+ )?.label ?? null+ }+ />+ </CardDescription>+ </CardHeader>+ <CardAction>+ {isEditable && permissions.can("create", "inventory") && (+ <Button+ variant="secondary"+ isDisabled={!isEditable}+ leftIcon={<LuCirclePlus />}+ asChild+ >+ <Link to={path.to.newStockTransferLine(id)}>Add Line</Link>+ </Button>+ )}+ </CardAction>+ </HStack>- <CardContent>- <div className="border rounded-lg">- {lines.length === 0 ? (- <Empty className="py-6" />- ) : (- lines.map((line, index) => {- const item = items.find((p) => p.id === line.itemId);- return (- <div- key={line.id}- className={cn(- "flex flex-col border-b p-6 gap-6",- index === lines.length - 1 && "border-none"- )}- >- <div className="flex justify-between items-center w-full">- <HStack spacing={4} className="w-1/2 justify-between">- <HStack spacing={4}>- <ItemThumbnail- size="md"- thumbnailPath={line.thumbnailPath}- type={(item?.type as "Part") ?? "Part"}- />- <VStack spacing={0} className="max-w-[380px] w-full">- <div className="w-full overflow-hidden">- <span className="text-sm font-medium truncate block w-full">- {item?.name}- </span>- <span className="text-xs text-muted-foreground truncate block w-full">- {item?.readableIdWithRevision}- </span>- </div>- <div className="mt-2">- <Enumerable- value={- unitsOfMeasure?.find(- (u) => u.value === line.unitOfMeasure- )?.label ?? null- }- />- </div>- </VStack>- </HStack>- <VStack spacing={1} className="text-center items-center">- <label className="text-xs text-muted-foreground">- Quantity- </label>- <span className="text-sm py-1.5">- {line.quantity ?? 0}- </span>- </VStack>- </HStack>- <div className="flex flex-grow items-center justify-between gap-8 pl-4 w-1/2">- <HStack spacing={8} className="text-center items-center">- {"fromShelfId" in line && (- <VStack- spacing={1}- className="text-center items-center"- >- <label className="text-xs text-muted-foreground">- From- </label>- <span className="text-sm py-1.5 whitespace-nowrap">- {line.fromShelfName ?? ""}- </span>- </VStack>- )}- {"toShelfId" in line && (- <VStack- spacing={1}- className="text-center items-center"- >- <label className="text-xs text-muted-foreground">- To- </label>- <span className="text-sm py-1.5 whitespace-nowrap">- {line.toShelfName ?? ""}- </span>+ <CardContent>+ <div className="border rounded-lg">+ {lines.length === 0 ? (+ <Empty className="py-6" />+ ) : (+ lines.map((line, index) => {+ const item = items.find((p) => p.id === line.itemId);+ return (+ <div+ key={line.id}+ className={cn(+ "flex flex-col border-b p-6 gap-6",+ index === lines.length - 1 && "border-none"+ )}+ >+ <div className="flex justify-between items-center w-full">+ <HStack spacing={4} className="w-1/2 justify-between">+ <HStack spacing={4}>+ <ItemThumbnail+ size="md"+ thumbnailPath={line.thumbnailPath}+ type={(item?.type as "Part") ?? "Part"}+ />+ <VStack spacing={0} className="max-w-[380px] w-full">+ <div className="w-full overflow-hidden">+ <span className="text-sm font-medium truncate block w-full">+ {item?.name}+ </span>+ <span className="text-xs text-muted-foreground truncate block w-full">+ {item?.readableIdWithRevision}+ </span>+ </div>+ <div className="mt-2">+ <Enumerable+ value={+ unitsOfMeasure?.find(+ (u) => u.value === line.unitOfMeasure+ )?.label ?? null+ }+ />+ </div></VStack>- )}+ </HStack>+ <VStack+ spacing={1}+ className="text-center items-center"+ >+ <label className="text-xs text-muted-foreground">+ Quantity+ </label>+ <span className="text-sm py-1.5">+ {line.quantity ?? 0}+ </span>+ </VStack></HStack>- <HStack spacing={1}>- <Button- isDisabled={!isPickable}- leftIcon={<LuCircleCheck />}+ <div className="flex flex-grow items-center justify-between gap-8 pl-4 w-1/2">+ <HStack+ spacing={8}+ className="text-center items-center">- Pick- </Button>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- variant="secondary"- isDisabled={!isEditable}- icon={<LuEllipsisVertical />}- aria-label="Line options"- />- </DropdownMenuTrigger>- <DropdownMenuContent>- <DropdownMenuItem>- <DropdownMenuIcon icon={<LuPencilLine />} />- Edit Line- </DropdownMenuItem>- <DropdownMenuItem- disabled={!isEditable}- destructive+ {"fromShelfId" in line && (+ <VStack+ spacing={1}+ className="text-center items-center">- <DropdownMenuIcon icon={<LuTrash />} />- Delete Line- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </HStack>+ <label className="text-xs text-muted-foreground">+ From+ </label>+ <span className="text-sm py-1.5 whitespace-nowrap">+ {line.fromShelfName ?? ""}+ </span>+ </VStack>+ )}+ {"toShelfId" in line && (+ <VStack+ spacing={1}+ className="text-center items-center"+ >+ <label className="text-xs text-muted-foreground">+ To+ </label>+ <span className="text-sm py-1.5 whitespace-nowrap">+ {line.toShelfName ?? ""}+ </span>+ </VStack>+ )}+ </HStack>+ <HStack spacing={1}>+ <Button+ isDisabled={!isPickable}+ leftIcon={<LuCircleCheck />}+ >+ Pick+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ variant="secondary"+ isDisabled={!isEditable}+ icon={<LuEllipsisVertical />}+ aria-label="Line options"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem+ disabled={+ !isEditable ||+ !permissions.can("update", "inventory")+ }+ asChild+ >+ <Link+ to={path.to.stockTransferLine(id, line.id!)}+ >+ <DropdownMenuIcon icon={<LuPencilLine />} />+ Edit Line+ </Link>+ </DropdownMenuItem>+ <DropdownMenuItem+ disabled={+ !isEditable ||+ !permissions.can("delete", "inventory")+ }+ destructive+ onClick={() => {+ setSelectedLine(line);+ deleteDisclosure.onOpen();+ }}+ >+ <DropdownMenuIcon icon={<LuTrash />} />+ Delete Line+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </HStack>+ </div></div></div>- </div>- );- })- )}- </div>- </CardContent>- </Card>+ );+ })+ )}+ </div>+ </CardContent>+ </Card>+ {deleteDisclosure.isOpen && (+ <ConfirmDelete+ name="Stock Transfer Line"+ text="Are you sure you want to delete this stock transfer line?"+ action={path.to.deleteStockTransferLine(id, selectedLine?.id!)}+ onCancel={deleteDisclosure.onClose}+ onSubmit={deleteDisclosure.onClose}+ />+ )}+ </>);}--// removed editable Shelf componentdiff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.line.$lineId.delete.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.line.$lineId.delete.tsxnew file mode 100644index 0000000000..f67df4d31c--- /dev/null+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.line.$lineId.delete.tsx@@ -0,0 +1,33 @@+import { error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";+import { deleteStockTransferLine } from "~/modules/inventory";+import { path } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ const { client } = await requirePermissions(request, {+ delete: "inventory",+ });++ const { id, lineId } = params;++ if (!id) throw new Error("id is not found");+ if (!lineId) throw new Error("lineId is not found");++ const mutation = await deleteStockTransferLine(client, lineId);+ if (mutation.error) {+ return json(+ {+ success: false,+ },+ await flash(request, error(mutation.error, "Failed to delete line"))+ );+ }++ throw redirect(+ path.to.stockTransfer(id),+ await flash(request, success("Successfully deleted line"))+ );+}diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.line.$lineId.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.line.$lineId.tsxnew file mode 100644index 0000000000..06eb514237--- /dev/null+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.line.$lineId.tsx@@ -0,0 +1,97 @@+import { assertIsPost, error, notFound, 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 { useRouteData } from "@carbon/remix";+import { useNavigate, useParams } from "@remix-run/react";+import type { ActionFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";+import {+ stockTransferLineValidator,+ upsertStockTransferLine,+} from "~/modules/inventory";+import type {+ StockTransfer,+ StockTransferLine,+} from "~/modules/inventory/types";+import StockTransferLineForm from "~/modules/inventory/ui/StockTransfers/StockTransferLineForm";++import { path } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ create: "inventory",+ });++ const { id, lineId } = params;+ if (!id) throw notFound("id not found");+ if (!lineId) throw notFound("lineId not found");++ const formData = await request.formData();++ const validation = await validator(stockTransferLineValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id: _id, ...data } = validation.data;++ const updateStockTransferLine = await upsertStockTransferLine(client, {+ id: lineId,+ ...data,+ updatedBy: userId,+ });+ if (updateStockTransferLine.error) {+ return json(+ {},+ await flash(+ request,+ error(updateStockTransferLine.error, "Failed to update line")+ )+ );+ }++ return redirect(+ path.to.stockTransfer(id),+ await flash(request, success("Line updated"))+ );+}++export default function NewStockTransferLinesRoute() {+ const { id, lineId } = useParams();+ if (!id) throw new Error("Could not find id");+ if (!lineId) throw new Error("Could not find lineId");+ const navigate = useNavigate();+ const routeData = useRouteData<{+ stockTransfer: StockTransfer;+ stockTransferLines: StockTransferLine[];+ }>(path.to.stockTransfer(id));++ if (!routeData?.stockTransfer?.locationId)+ throw new Error("No location found");++ const line = routeData?.stockTransferLines?.find(+ (line) => line.id === lineId+ );++ const initialValues = {+ id: lineId,+ stockTransferId: id,+ itemId: line?.itemId ?? "",+ quantity: line?.quantity ?? 1,+ fromShelfId: line?.fromShelfId ?? "",+ toShelfId: line?.toShelfId ?? "",+ };++ return (+ <StockTransferLineForm+ locationId={routeData?.stockTransfer.locationId}+ onClose={() => navigate(-1)}+ initialValues={initialValues}+ />+ );+}diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.line.new.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.line.new.tsxnew file mode 100644index 0000000000..017b92aff0--- /dev/null+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.line.new.tsx@@ -0,0 +1,94 @@+import { assertIsPost, error, notFound, 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 { useRouteData } from "@carbon/remix";+import { useNavigate, useParams } from "@remix-run/react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";+import {+ stockTransferLineValidator,+ upsertStockTransferLine,+} from "~/modules/inventory";+import type { StockTransfer } from "~/modules/inventory/types";+import StockTransferLineForm from "~/modules/inventory/ui/StockTransfers/StockTransferLineForm";++import { path } from "~/utils/path";++export async function loader({ request }: LoaderFunctionArgs) {+ await requirePermissions(request, {+ create: "inventory",+ });++ return null;+}++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "inventory",+ });++ const { id } = params;+ if (!id) throw notFound("id not found");++ const formData = await request.formData();++ const validation = await validator(stockTransferLineValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id: lineId, ...data } = validation.data;++ const insertStockTransferLine = await upsertStockTransferLine(client, {+ ...data,+ companyId,+ createdBy: userId,+ });+ if (insertStockTransferLine.error) {+ return json(+ {},+ await flash(+ request,+ error(insertStockTransferLine.error, "Failed to insert line")+ )+ );+ }++ return redirect(+ path.to.stockTransfer(id),+ await flash(request, success("Line created"))+ );+}++export default function NewStockTransferLinesRoute() {+ const { id } = useParams();+ if (!id) throw new Error("Could not find id");+ const navigate = useNavigate();+ const routeData = useRouteData<{+ stockTransfer: StockTransfer;+ }>(path.to.stockTransfer(id));++ if (!routeData?.stockTransfer?.locationId)+ throw new Error("No location found");++ const initialValues = {+ stockTransferId: id,+ itemId: "",+ quantity: 1,+ fromShelfId: "",+ toShelfId: "",+ };++ return (+ <StockTransferLineForm+ locationId={routeData?.stockTransfer.locationId}+ onClose={() => navigate(-1)}+ initialValues={initialValues}+ />+ );+}diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.tsxindex bc4d387277..a056fd3233 100644--- a/apps/erp/app/routes/x+/stock-transfer+/$id.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.tsx@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { JSONContent } from "@carbon/react";import { VStack } from "@carbon/react";-import { useLoaderData, useParams } from "@remix-run/react";+import { Outlet, useLoaderData, useParams } from "@remix-run/react";import type { LoaderFunctionArgs } from "@vercel/remix";import { json, redirect } from "@vercel/remix";import { PanelProvider } from "~/components/Layout";@@ -80,6 +80,7 @@ export default function StockTransferRoute() {</VStack></div></div>+ <Outlet /></PanelProvider>);}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex bdbfb13a8e..fed340ebfa 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -592,6 +592,8 @@ export const path = {generatePath(`${x}/accounting/payment-terms/delete/${id}`),deleteStockTransfer: (id: string) =>generatePath(`${x}/stock-transfer/delete/${id}`),+ deleteStockTransferLine: (id: string, lineId: string) =>+ generatePath(`${x}/stock-transfer/${id}/line/${lineId}/delete`),deleteProcedure: (id: string) =>generatePath(`${x}/procedure/delete/${id}`),deleteProcedureStep: (id: string, stepId: string) =>