Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: add crud for managing shelves by location

Brad Barbina7e8e1516605
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 4a120c95d9..5bde07a8cd 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -39,6 +39,13 @@ export async function deleteReceiptLine(
return client.from("receiptLine").delete().eq("id", receiptLineId);
}
+export async function deleteShelf(
+ client: SupabaseClient<Database>,
+ shelfId: string
+) {
+ return client.from("shelf").delete().eq("id", shelfId);
+}
+
export async function deleteShipment(
client: SupabaseClient<Database>,
shipmentId: string
@@ -334,6 +341,40 @@ export async function getShelvesListForLocation(
.order("name");
}
+export async function getShelves(
+ client: SupabaseClient<Database>,
+ locationId: string,
+ companyId: string,
+ args: GenericQueryFilters & {
+ search: string | null;
+ }
+) {
+ let query = client
+ .from("shelf")
+ .select("*", {
+ count: "exact",
+ })
+ .eq("companyId", companyId)
+ .eq("locationId", locationId);
+
+ if (args?.search) {
+ query = query.ilike("name", `%${args.search}%`);
+ }
+
+ query = setGenericQueryFilters(query, args, [
+ { column: "name", ascending: true },
+ ]);
+
+ return query;
+}
+
+export async function getShelf(
+ client: SupabaseClient<Database>,
+ shelfId: string
+) {
+ return client.from("shelf").select("*").eq("id", shelfId).single();
+}
+
export async function getShipments(
client: SupabaseClient<Database>,
companyId: string,
diff --git a/apps/erp/app/modules/inventory/ui/Shelves/ShelfForm.tsx b/apps/erp/app/modules/inventory/ui/Shelves/ShelfForm.tsx
index df7b113325..6c2881d810 100644
--- a/apps/erp/app/modules/inventory/ui/Shelves/ShelfForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shelves/ShelfForm.tsx
@@ -77,7 +77,11 @@ const ShelfForm = ({
<VStack spacing={4}>
<Input name="name" label="Name" />
- <Location name="locationId" label="Location" />
+ <Location
+ isReadOnly={isEditing}
+ name="locationId"
+ label="Location"
+ />
</VStack>
</ModalDrawerBody>
<ModalDrawerFooter>
diff --git a/apps/erp/app/modules/inventory/ui/Shelves/ShelvesTable.tsx b/apps/erp/app/modules/inventory/ui/Shelves/ShelvesTable.tsx
new file mode 100644
index 0000000000..74eebdcf93
--- /dev/null
+++ b/apps/erp/app/modules/inventory/ui/Shelves/ShelvesTable.tsx
@@ -0,0 +1,203 @@
+import {
+ Button,
+ Checkbox,
+ Combobox,
+ HStack,
+ MenuIcon,
+ MenuItem,
+ VStack,
+ useDisclosure,
+} from "@carbon/react";
+import { Link, useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo, useState } from "react";
+import {
+ LuBookMarked,
+ LuCheck,
+ LuMapPin,
+ LuPencil,
+ LuPlus,
+ LuTrash,
+} from "react-icons/lu";
+import { Hyperlink, Table } from "~/components";
+import { Enumerable } from "~/components/Enumerable";
+import { useLocations } from "~/components/Form/Location";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions, useUrlParams } from "~/hooks";
+import { path } from "~/utils/path";
+
+type Shelf = {
+ id: string;
+ name: string;
+ locationId: string | null;
+ active: boolean;
+ createdAt: string;
+ updatedAt: string | null;
+};
+
+type ShelvesTableProps = {
+ data: Shelf[];
+ count: number;
+ locationId: string;
+};
+
+const ShelvesTable = memo(({ data, count, locationId }: ShelvesTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const locations = useLocations();
+
+ const [selectedShelf, setSelectedShelf] = useState<Shelf | null>(null);
+ const deleteShelfModal = useDisclosure();
+
+ const columns = useMemo<ColumnDef<Shelf>[]>(() => {
+ return [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => (
+ <HStack className="py-1">
+ <Hyperlink to={`${path.to.shelf(row.original.id!)}?${params}`}>
+ <VStack spacing={0}>{row.original.name}</VStack>
+ </Hyperlink>
+ </HStack>
+ ),
+ meta: {
+ icon: <LuBookMarked />,
+ },
+ },
+ {
+ accessorKey: "locationId",
+ header: "Location",
+ cell: ({ row }) => {
+ const location = locations.find(
+ (l) => l.value === row.original.locationId
+ );
+ return (
+ <Enumerable value={location?.label ?? row.original.locationId} />
+ );
+ },
+ meta: {
+ icon: <LuMapPin />,
+ },
+ },
+ {
+ accessorKey: "active",
+ header: "Active",
+ cell: (item) => <Checkbox isChecked={item.getValue<boolean>()} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: [
+ { value: "true", label: "Active" },
+ { value: "false", label: "Inactive" },
+ ],
+ },
+ pluralHeader: "Active Statuses",
+ icon: <LuCheck />,
+ },
+ },
+ ];
+ }, [locations, params]);
+
+ const defaultColumnVisibility = {
+ active: false,
+ };
+
+ const defaultColumnPinning = {
+ left: ["name"],
+ };
+
+ const actions = useMemo(() => {
+ return (
+ <div className="flex items-center gap-2">
+ <Combobox
+ asButton
+ size="sm"
+ value={locationId}
+ options={locations}
+ onChange={(selected) => {
+ // hard refresh because initialValues update has no effect otherwise
+ window.location.href = getLocationPath(selected);
+ }}
+ />
+ <Button asChild leftIcon={<LuPlus />}>
+ <Link to={`${path.to.newShelf}?location=${locationId}`}>
+ New Shelf
+ </Link>
+ </Button>
+ </div>
+ );
+ }, [locationId, locations]);
+
+ const renderContextMenu = useCallback(
+ (row: Shelf) => {
+ return (
+ <>
+ <MenuItem
+ disabled={!permissions.can("update", "inventory")}
+ onClick={() => {
+ navigate(`${path.to.shelf(row.id)}?${params.toString()}`);
+ }}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Shelf
+ </MenuItem>
+ <MenuItem
+ disabled={!permissions.can("delete", "inventory")}
+ destructive
+ onClick={() => {
+ setSelectedShelf(row);
+ deleteShelfModal.onOpen();
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Shelf
+ </MenuItem>
+ </>
+ );
+ },
+ [deleteShelfModal, navigate, params, permissions]
+ );
+
+ return (
+ <>
+ <Table<Shelf>
+ count={count}
+ columns={columns}
+ data={data}
+ defaultColumnVisibility={defaultColumnVisibility}
+ defaultColumnPinning={defaultColumnPinning}
+ primaryAction={actions}
+ renderContextMenu={renderContextMenu}
+ title="Shelves"
+ table="shelf"
+ withSavedView
+ />
+ {selectedShelf && selectedShelf.id && (
+ <ConfirmDelete
+ action={path.to.deleteShelf(selectedShelf.id)}
+ isOpen={deleteShelfModal.isOpen}
+ name={selectedShelf.name!}
+ text={`Are you sure you want to delete ${selectedShelf.name!}? This cannot be undone.`}
+ onCancel={() => {
+ deleteShelfModal.onClose();
+ setSelectedShelf(null);
+ }}
+ onSubmit={() => {
+ deleteShelfModal.onClose();
+ setSelectedShelf(null);
+ }}
+ />
+ )}
+ </>
+ );
+});
+
+ShelvesTable.displayName = "ShelvesTable";
+
+export default ShelvesTable;
+
+function getLocationPath(locationId: string) {
+ return `${path.to.shelves}?location=${locationId}`;
+}
diff --git a/apps/erp/app/modules/inventory/ui/Shelves/index.ts b/apps/erp/app/modules/inventory/ui/Shelves/index.ts
index a538fd0250..d4a079d011 100644
--- a/apps/erp/app/modules/inventory/ui/Shelves/index.ts
+++ b/apps/erp/app/modules/inventory/ui/Shelves/index.ts
@@ -1,3 +1,4 @@
import ShelfForm from "./ShelfForm";
+import ShelvesTable from "./ShelvesTable";
-export { ShelfForm };
+export { ShelfForm, ShelvesTable };
diff --git a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
index d64f7c8876..e7821fa165 100644
--- a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
+++ b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
@@ -5,6 +5,7 @@ import {
LuQrCode,
LuTally5,
LuTruck,
+ LuWarehouse,
} from "react-icons/lu";
import { usePermissions } from "~/hooks";
import { useSavedViews } from "~/hooks/useSavedViews";
@@ -62,6 +63,13 @@ const inventoryRoutes: AuthenticatedRouteGroup[] = [
{
name: "Configure",
routes: [
+ {
+ name: "Shelves",
+ to: path.to.shelves,
+ role: "employee",
+ icon: <LuWarehouse />,
+ table: "shelf",
+ },
{
name: "Shipping Methods",
to: path.to.shippingMethods,
diff --git a/apps/erp/app/routes/x+/inventory+/shelves.$id.tsx b/apps/erp/app/routes/x+/inventory+/shelves.$id.tsx
deleted file mode 100644
index bec9c2de52..0000000000
--- a/apps/erp/app/routes/x+/inventory+/shelves.$id.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { validationError, validator } from "@carbon/form";
-import type { ClientActionFunctionArgs } from "@remix-run/react";
-import type { ActionFunctionArgs } from "@vercel/remix";
-import { json, redirect } from "@vercel/remix";
-import { shelfValidator, upsertShelf } from "~/modules/inventory";
-import { setCustomFields } from "~/utils/form";
-import { path } from "~/utils/path";
-import { getCompanyId, shelvesQuery } from "~/utils/react-query";
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
- create: "inventory",
- });
-
- const formData = await request.formData();
- const validation = await validator(shelfValidator).validate(formData);
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { id, ...data } = validation.data;
-
- if (!id) {
- throw redirect(
- path.to.inventory,
- await flash(request, error(null, "Failed to update shelf"))
- );
- }
-
- const update = await upsertShelf(client, {
- id,
- ...data,
- customFields: setCustomFields(formData),
- updatedBy: userId,
- });
- if (update.error) {
- throw redirect(
- path.to.inventory,
- await flash(request, error(update.error, "Failed to update shelf"))
- );
- }
-
- return json(null, await flash(request, success("Updated shelf")));
-}
-
-export async function clientAction({
- request,
- serverAction,
-}: ClientActionFunctionArgs) {
- const companyId = getCompanyId();
-
- const formData = await request.clone().formData(); // if we. don't clone it we can't access it in the action
- const validation = await validator(shelfValidator).validate(formData);
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- if (companyId && validation.data.locationId) {
- window.clientCache?.setQueryData(
- shelvesQuery(companyId, validation.data.locationId).queryKey,
- null
- );
- }
- return await serverAction();
-}
diff --git a/apps/erp/app/routes/x+/inventory+/shelves.$shelfId.tsx b/apps/erp/app/routes/x+/inventory+/shelves.$shelfId.tsx
new file mode 100644
index 0000000000..792715f33b
--- /dev/null
+++ b/apps/erp/app/routes/x+/inventory+/shelves.$shelfId.tsx
@@ -0,0 +1,112 @@
+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 type { ClientActionFunctionArgs } from "@remix-run/react";
+import { useLoaderData, useNavigate } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import {
+ ShelfForm,
+ getShelf,
+ shelfValidator,
+ upsertShelf,
+} from "~/modules/inventory";
+import { getCustomFields, setCustomFields } from "~/utils/form";
+import { getParams, path } from "~/utils/path";
+import { getCompanyId, shelvesQuery } from "~/utils/react-query";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "inventory",
+ role: "employee",
+ });
+
+ const { shelfId } = params;
+ if (!shelfId) throw notFound("shelfId not found");
+
+ const shelf = await getShelf(client, shelfId);
+
+ return json({
+ shelf: shelf?.data ?? null,
+ });
+}
+
+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(shelfValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+ if (!id) throw new Error("id not found");
+
+ const updateShelf = await upsertShelf(client, {
+ id,
+ ...data,
+ updatedBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (updateShelf.error) {
+ return json(
+ {},
+ await flash(request, error(updateShelf.error, "Failed to update shelf"))
+ );
+ }
+
+ throw redirect(
+ `${path.to.shelves}?${getParams(request)}`,
+ await flash(request, success("Updated shelf"))
+ );
+}
+
+export async function clientAction({
+ request,
+ serverAction,
+}: ClientActionFunctionArgs) {
+ const companyId = getCompanyId();
+
+ const formData = await request.clone().formData();
+ const validation = await validator(shelfValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ if (companyId && validation.data.locationId) {
+ window.clientCache?.setQueryData(
+ shelvesQuery(companyId, validation.data.locationId).queryKey,
+ null
+ );
+ }
+ return await serverAction();
+}
+
+export default function EditShelfRoute() {
+ const { shelf } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ const initialValues = {
+ id: shelf?.id ?? undefined,
+ name: shelf?.name ?? "",
+ locationId: shelf?.locationId ?? "",
+ ...getCustomFields(shelf?.customFields),
+ };
+
+ return (
+ <ShelfForm
+ key={initialValues.id}
+ initialValues={initialValues}
+ locationId={initialValues.locationId}
+ onClose={() => navigate(-1)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/inventory+/shelves.delete.$shelfId.tsx b/apps/erp/app/routes/x+/inventory+/shelves.delete.$shelfId.tsx
new file mode 100644
index 0000000000..bd14b6797a
--- /dev/null
+++ b/apps/erp/app/routes/x+/inventory+/shelves.delete.$shelfId.tsx
@@ -0,0 +1,90 @@
+import { error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ClientActionFunctionArgs } from "@remix-run/react";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { ConfirmDelete } from "~/components/Modals";
+import { deleteShelf, getShelf } from "~/modules/inventory";
+import { getParams, path } from "~/utils/path";
+import { getCompanyId } from "~/utils/react-query";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "inventory",
+ });
+ const { shelfId } = params;
+ if (!shelfId) throw notFound("shelfId not found");
+
+ const shelf = await getShelf(client, shelfId);
+ if (shelf.error) {
+ throw redirect(
+ path.to.shelves,
+ await flash(request, error(shelf.error, "Failed to get shelf"))
+ );
+ }
+
+ return json({ shelf: shelf.data });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "inventory",
+ });
+
+ const { shelfId } = params;
+ if (!shelfId) {
+ throw redirect(
+ path.to.shelves,
+ await flash(request, error(params, "Failed to get a shelf id"))
+ );
+ }
+
+ const { error: deleteShelfError } = await deleteShelf(client, shelfId);
+ if (deleteShelfError) {
+ throw redirect(
+ path.to.shelves,
+ await flash(request, error(deleteShelfError, "Failed to delete shelf"))
+ );
+ }
+
+ throw redirect(
+ `${path.to.shelves}?${getParams(request)}`,
+ await flash(request, success("Successfully deleted shelf"))
+ );
+}
+
+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
+ const companyId = getCompanyId();
+
+ window.clientCache?.invalidateQueries({
+ predicate: (query) => {
+ const queryKey = query.queryKey as string[];
+ return queryKey[0] === "shelves" && queryKey[1] === companyId;
+ },
+ });
+
+ return await serverAction();
+}
+
+export default function DeleteShelfRoute() {
+ const { shelfId } = useParams();
+ if (!shelfId) throw notFound("shelfId not found");
+
+ const { shelf } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!shelfId) return null;
+
+ const onCancel = () => navigate(path.to.shelves);
+
+ return (
+ <ConfirmDelete
+ action={path.to.deleteShelf(shelfId)}
+ name={shelf.name}
+ text={`Are you sure you want to delete the shelf: ${shelf.name}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/inventory+/shelves.new.tsx b/apps/erp/app/routes/x+/inventory+/shelves.new.tsx
index e71bc2cb34..51715ca457 100644
--- a/apps/erp/app/routes/x+/inventory+/shelves.new.tsx
+++ b/apps/erp/app/routes/x+/inventory+/shelves.new.tsx
@@ -1,20 +1,24 @@
-import { assertIsPost, error } from "@carbon/auth";
+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 { ClientActionFunctionArgs } from "@remix-run/react";
-import type { ActionFunctionArgs } from "@vercel/remix";
+import { useNavigate, useSearchParams } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { shelfValidator, upsertShelf } from "~/modules/inventory";
+import { useUser } from "~/hooks";
+import { ShelfForm, shelfValidator, upsertShelf } from "~/modules/inventory";
import { setCustomFields } from "~/utils/form";
-import { path } from "~/utils/path";
+import { getParams, path } from "~/utils/path";
import { getCompanyId, shelvesQuery } from "~/utils/react-query";
-// export const handle: Handle = {
-// breadcrumb: "Shelves",
-// to: path.to.shelves,
-// module: "inventory",
-// };
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ create: "inventory",
+ });
+
+ return null;
+}
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
@@ -40,26 +44,18 @@ export async function action({ request }: ActionFunctionArgs) {
createdBy: userId,
});
if (createShelf.error) {
- return modal
- ? json(
- createShelf,
- await flash(
- request,
- error(createShelf.error, "Failed to insert shelf")
- )
- )
- : redirect(
- path.to.inventory,
- await flash(
- request,
- error(createShelf.error, "Failed to insert shelf")
- )
- );
+ return json(
+ {},
+ await flash(request, error(createShelf.error, "Failed to insert shelf"))
+ );
}
- // const shelfId = createShelf.data?.id;
-
- return modal ? json(createShelf) : redirect(path.to.inventory);
+ return modal
+ ? json(createShelf, { status: 201 })
+ : redirect(
+ `${path.to.shelves}?${getParams(request)}`,
+ await flash(request, success("Shelf created"))
+ );
}
export async function clientAction({
@@ -68,7 +64,7 @@ export async function clientAction({
}: ClientActionFunctionArgs) {
const companyId = getCompanyId();
- const formData = await request.clone().formData(); // if we don't clone it we can't access it in the action
+ const formData = await request.clone().formData();
const validation = await validator(shelfValidator).validate(formData);
if (validation.error) {
@@ -83,3 +79,24 @@ export async function clientAction({
}
return await serverAction();
}
+
+export default function NewShelfRoute() {
+ const navigate = useNavigate();
+ const [searchParams] = useSearchParams();
+ const { defaults } = useUser();
+ const locationId =
+ (searchParams.get("location") || defaults.locationId) ?? "";
+
+ const initialValues = {
+ name: "",
+ locationId,
+ };
+
+ return (
+ <ShelfForm
+ initialValues={initialValues}
+ locationId={locationId}
+ onClose={() => navigate(-1)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/inventory+/shelves.tsx b/apps/erp/app/routes/x+/inventory+/shelves.tsx
new file mode 100644
index 0000000000..bacbfec1b1
--- /dev/null
+++ b/apps/erp/app/routes/x+/inventory+/shelves.tsx
@@ -0,0 +1,97 @@
+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 type { LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { getShelves } from "~/modules/inventory";
+import ShelvesTable from "~/modules/inventory/ui/Shelves/ShelvesTable";
+import { getLocationsList } from "~/modules/resources";
+import { getUserDefaults } from "~/modules/users/users.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: "Shelves",
+ to: path.to.shelves,
+ module: "inventory",
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "inventory",
+ bypassRls: true,
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ let locationId = searchParams.get("location");
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId, companyId);
+ if (userDefaults.error) {
+ throw redirect(
+ path.to.shelves,
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client, companyId);
+ if (locations.error || !locations.data?.length) {
+ throw redirect(
+ path.to.shelves,
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ const shelves = await getShelves(client, locationId, companyId, {
+ search,
+ limit,
+ offset,
+ sorts,
+ filters,
+ });
+
+ if (shelves.error) {
+ throw redirect(
+ path.to.authenticatedRoot,
+ await flash(request, error(shelves.error, "Failed to fetch shelves"))
+ );
+ }
+
+ return json({
+ count: shelves.count ?? 0,
+ shelves: shelves.data ?? [],
+ locationId,
+ });
+}
+
+export default function ShelvesRoute() {
+ const { count, shelves, locationId } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <ShelvesTable data={shelves} count={count} locationId={locationId} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 3a3ba4ed47..7b3b152986 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -608,6 +608,8 @@ export const path = {
deleteShift: (id: string) =>
generatePath(`${x}/people/shifts/delete/${id}`),
deleteShipment: (id: string) => generatePath(`${x}/shipment/${id}/delete`),
+ deleteShelf: (id: string) =>
+ generatePath(`${x}/inventory/shelves/delete/${id}`),
deleteShippingMethod: (id: string) =>
generatePath(`${x}/inventory/shipping-methods/delete/${id}`),
deleteSupplierContact: (supplierId: string, id: string) =>
@@ -697,9 +699,11 @@ export const path = {
issueReview: (id: string) => generatePath(`${x}/issue/${id}/review`),
issueWorkflow: (id: string) => generatePath(`${x}/issue-workflow/${id}`),
issueWorkflows: `${x}/quality/issue-workflows`,
- investigationType: (id: string) => generatePath(`${x}/quality/investigation-types/${id}`),
+ investigationType: (id: string) =>
+ generatePath(`${x}/quality/investigation-types/${id}`),
investigationTypes: `${x}/quality/investigation-types`,
- requiredAction: (id: string) => generatePath(`${x}/quality/required-actions/${id}`),
+ requiredAction: (id: string) =>
+ generatePath(`${x}/quality/required-actions/${id}`),
requiredActions: `${x}/quality/required-actions`,
issueType: (id: string) => generatePath(`${x}/quality/issue-types/${id}`),
issueTypes: `${x}/quality/issue-types`,
@@ -1217,6 +1221,7 @@ export const path = {
settings: `${x}/settings`,
sequences: `${x}/settings/sequences`,
shelf: (id: string) => generatePath(`${x}/inventory/shelves/${id}`),
+ shelves: `${x}/inventory/shelves`,
shift: (id: string) => generatePath(`${x}/people/shifts/${id}`),
shifts: `${x}/people/shifts`,
shipments: `${x}/inventory/shipments`,