Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

refactor(vendor): simplify manage locations form and use SDK for inventory levels

vholik0a686b8126c7
diff --git a/packages/vendor/src/hooks/api/inventory.tsx b/packages/vendor/src/hooks/api/inventory.tsx
index 8a932bbc7..7e8a9c34e 100644
--- a/packages/vendor/src/hooks/api/inventory.tsx
+++ b/packages/vendor/src/hooks/api/inventory.tsx
@@ -175,20 +175,13 @@ export const useInventoryItemLevels = (
>,
) => {
const { data, ...rest } = useQuery({
- queryFn: () => {
- if (!inventoryItemId) {
- throw new Error(
- "inventoryItemId is required for useInventoryItemLevels",
- );
- }
- return fetchQuery(
- `/vendor/inventory-items/${inventoryItemId}/location-levels`,
- {
- method: "GET",
- query: { ...query },
- },
- );
- },
+ queryFn: () =>
+ sdk.vendor.inventoryItems.$id.locationLevels.query({
+ $id: inventoryItemId,
+ limit: query?.limit ?? 100,
+ offset: query?.offset ?? 0,
+ ...query,
+ }),
queryKey: inventoryItemLevelsQueryKeys.list({
...(query || {}),
inventoryItemId,
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/adjust-inventory-drawer.tsx b/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/adjust-inventory-drawer.tsx
index d872a99c3..e181ae43b 100644
--- a/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/adjust-inventory-drawer.tsx
+++ b/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/adjust-inventory-drawer.tsx
@@ -1,46 +1,43 @@
-import { InventoryTypes } from "@medusajs/types"
-import { Heading } from "@medusajs/ui"
-import { useTranslation } from "react-i18next"
-import { useParams } from "react-router-dom"
-import { RouteDrawer } from "@components/modals"
-import {
- useInventoryItem,
- useInventoryItemLevels,
-} from "@hooks/api/inventory"
-import { useStockLocation } from "@hooks/api/stock-locations"
-import { AdjustInventoryForm } from "./components/adjust-inventory-form"
+import { InventoryTypes } from "@medusajs/types";
+import { Heading } from "@medusajs/ui";
+import { useTranslation } from "react-i18next";
+import { useParams } from "react-router-dom";
+import { RouteDrawer } from "@components/modals";
+import { useInventoryItem, useInventoryItemLevels } from "@hooks/api/inventory";
+import { useStockLocation } from "@hooks/api/stock-locations";
+import { AdjustInventoryForm } from "./components/adjust-inventory-form";
export const AdjustInventoryDrawer = () => {
- const { id, location_id } = useParams()
- const { t } = useTranslation()
+ const { id, location_id } = useParams();
+ const { t } = useTranslation();
const {
inventory_item: inventoryItem,
isPending: isLoading,
isError,
error,
- } = useInventoryItem(id!)
+ } = useInventoryItem(id!);
- const { location_levels } = useInventoryItemLevels(id!)
+ const { inventory_levels } = useInventoryItemLevels(id!);
- const inventoryLevel = location_levels?.find(
+ const inventoryLevel = inventory_levels?.find(
(level: InventoryTypes.InventoryLevelDTO) =>
- level.location_id === location_id
- )
+ level.location_id === location_id,
+ );
const { stock_location, isLoading: isLoadingLocation } = useStockLocation(
- location_id!
- )
+ location_id!,
+ );
const ready =
!isLoading &&
inventoryItem &&
inventoryLevel &&
!isLoadingLocation &&
- stock_location
+ stock_location;
if (isError) {
- throw error
+ throw error;
}
return (
@@ -56,5 +53,5 @@ export const AdjustInventoryDrawer = () => {
/>
)}
</RouteDrawer>
- )
-}
+ );
+};
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/location-list-table.tsx b/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/location-list-table.tsx
index ed932add3..b8f0f01f2 100644
--- a/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/location-list-table.tsx
+++ b/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/location-list-table.tsx
@@ -1,32 +1,35 @@
-import { _DataTable } from "@components/table/data-table"
-import { useInventoryItemLevels } from "@hooks/api/inventory"
-import { useDataTable } from "@hooks/use-data-table"
-import { useLocationListTableColumns } from "./use-location-list-table-columns"
-import { useLocationLevelTableQuery } from "./use-location-list-table-query"
+import { _DataTable } from "@components/table/data-table";
+import { useInventoryItemLevels } from "@hooks/api/inventory";
+import { useDataTable } from "@hooks/use-data-table";
+import { useLocationListTableColumns } from "./use-location-list-table-columns";
+import { useLocationLevelTableQuery } from "./use-location-list-table-query";
+import { StockLocationDTO } from "@medusajs/types";
-const PAGE_SIZE = 20
+const PAGE_SIZE = 20;
export const ItemLocationListTable = ({
inventory_item_id,
}: {
- inventory_item_id: string
+ inventory_item_id: string;
}) => {
const { searchParams, raw } = useLocationLevelTableQuery({
pageSize: PAGE_SIZE,
- })
+ });
- const { location_levels, count, isLoading } = useInventoryItemLevels(
+ const { inventory_levels, count, isLoading } = useInventoryItemLevels(
inventory_item_id,
{
...searchParams,
fields: "*stock_locations",
- }
- )
- const columns = useLocationListTableColumns()
+ },
+ );
+ const columns = useLocationListTableColumns();
- const filteredLocationLevels = location_levels?.filter(
- (level) => level.stock_locations?.length > 0
- )
+ const filteredLocationLevels = inventory_levels?.filter(
+ (level) =>
+ (level as unknown as { stock_locations: StockLocationDTO[] })
+ .stock_locations.length > 0,
+ );
const { table } = useDataTable({
data: filteredLocationLevels ?? [],
@@ -35,7 +38,7 @@ export const ItemLocationListTable = ({
enablePagination: true,
getRowId: (row) => row.id,
pageSize: PAGE_SIZE,
- })
+ });
return (
<_DataTable
@@ -47,5 +50,5 @@ export const ItemLocationListTable = ({
pagination
queryObject={raw}
/>
- )
-}
+ );
+};
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/components/manage-locations-form.tsx b/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/components/manage-locations-form.tsx
index 547bcaeed..96dc75172 100644
--- a/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/components/manage-locations-form.tsx
+++ b/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/components/manage-locations-form.tsx
@@ -1,45 +1,19 @@
-import * as zod from "zod"
-
-import { zodResolver } from "@hookform/resolvers/zod"
-import { AdminInventoryItem, AdminStockLocation } from "@medusajs/types"
-import { Button, Text, toast } from "@medusajs/ui"
-import { useFieldArray, useForm } from "react-hook-form"
-import { useTranslation } from "react-i18next"
-import { z } from "zod"
-import { RouteDrawer, useRouteModal } from "@components/modals"
-import { useBatchInventoryItemLocationLevels } from "@hooks/api/inventory"
-
-import { useMemo } from "react"
-import { KeyboundForm } from "@components/utilities/keybound-form"
-import { LocationItem } from "./location-item"
+import { AdminInventoryItem, AdminStockLocation } from "@medusajs/types";
+import { Button, Text, toast } from "@medusajs/ui";
+import { useTranslation } from "react-i18next";
+import {
+ RouteDrawer,
+ useRouteModal,
+} from "../../../../../../components/modals";
+import { useBatchInventoryItemLocationLevels } from "../../../../../../hooks/api/inventory";
+
+import { useMemo, useState } from "react";
+import { LocationItem } from "./location-item";
type EditInventoryItemAttributeFormProps = {
- item: AdminInventoryItem
- locations: AdminStockLocation[]
-}
-
-const EditInventoryItemAttributesSchema = z.object({
- locations: z.array(
- z.object({
- id: z.string(),
- location_id: z.string().optional(),
- selected: z.boolean(),
- })
- ),
-})
-
-const getDefaultValues = (
- allLocations: AdminStockLocation[],
- existingLevels: Set<string>
-) => {
- return {
- locations: allLocations.map((location) => ({
- ...location,
- location_id: location.id,
- selected: existingLevels.has(location.id),
- })),
- }
-}
+ item: AdminInventoryItem;
+ locations: AdminStockLocation[];
+};
export const ManageLocationsForm = ({
item,
@@ -47,149 +21,122 @@ export const ManageLocationsForm = ({
}: EditInventoryItemAttributeFormProps) => {
const existingLocationLevels = useMemo(
() => new Set(item.location_levels?.map((l) => l.location_id) ?? []),
- [item.location_levels]
- )
-
- const { t } = useTranslation()
- const { handleSuccess } = useRouteModal()
-
- const form = useForm<zod.infer<typeof EditInventoryItemAttributesSchema>>({
- defaultValues: getDefaultValues(locations, existingLocationLevels),
- resolver: zodResolver(EditInventoryItemAttributesSchema),
- })
-
- const { fields: locationFields, update: updateField } = useFieldArray({
- control: form.control,
- name: "locations",
- })
-
- const { mutateAsync } = useBatchInventoryItemLocationLevels(item.id)
-
- const handleSubmit = form.handleSubmit(async ({ locations }) => {
- // Changes in selected locations
+ [item.location_levels],
+ );
+
+ const { t } = useTranslation();
+ const { handleSuccess } = useRouteModal();
+ const [selectedLocationIds, setSelectedLocationIds] = useState<Set<string>>(
+ existingLocationLevels,
+ );
+
+ const handleLocationSelect = (locationId: string, selected: boolean) => {
+ setSelectedLocationIds((prev) => {
+ const newSet = new Set(prev);
+ if (selected) {
+ newSet.add(locationId);
+ } else {
+ newSet.delete(locationId);
+ }
+ return newSet;
+ });
+ };
- const [selectedLocations, unselectedLocations] = locations.reduce(
- (acc, location) => {
- if (!location.location_id) {
- return acc
- }
+ const { mutateAsync } = useBatchInventoryItemLocationLevels(item.id);
- // If the location is not changed do nothing
- if (
- (!location.selected &&
- !existingLocationLevels.has(location.location_id)) ||
- (location.selected &&
- existingLocationLevels.has(location.location_id))
- ) {
- return acc
- }
+ const handleSubmit = async () => {
+ const toCreate = Array.from(selectedLocationIds).filter(
+ (id) => !existingLocationLevels.has(id),
+ );
- if (location.selected) {
- acc[0].push(location.location_id)
- } else {
- acc[1].push(location.location_id)
- }
- return acc
- },
- [[], []] as [string[], string[]]
- )
+ const toDeleteLocations = Array.from(existingLocationLevels).filter(
+ (id) => !selectedLocationIds.has(id),
+ );
- if (selectedLocations.length === 0 && unselectedLocations.length === 0) {
- return handleSuccess()
- }
+ const toDelete = toDeleteLocations
+ .map((id) => item.location_levels?.find((l) => l.location_id === id)?.id)
+ .filter(Boolean) as unknown as string[];
await mutateAsync(
{
- create: selectedLocations.length
- ? selectedLocations.map((item) => ({ location_id: item }))
- : undefined,
- // update: [],
- delete: unselectedLocations,
+ create: toCreate.map((location_id) => ({
+ location_id,
+ })),
+ delete: toDelete,
},
{
onSuccess: () => {
- toast.success(t("inventory.toast.updateLocations"))
- handleSuccess()
+ toast.success(t("inventory.toast.updateLocations"));
+ handleSuccess();
},
onError: (e) => {
- toast.error(e.message)
+ toast.error(e.message);
},
- }
- )
- })
+ },
+ );
+ };
return (
- <RouteDrawer.Form form={form}>
- <KeyboundForm
- onSubmit={handleSubmit}
- className="flex flex-1 flex-col overflow-hidden"
- >
- <RouteDrawer.Body className="flex flex-1 flex-col gap-y-4 overflow-auto">
- <div className="text-ui-fg-subtle shadow-elevation-card-rest grid grid-rows-2 divide-y rounded-lg border">
- <div className="grid grid-cols-2 divide-x">
- <Text className="px-2 py-1.5" size="small" leading="compact">
- {t("fields.title")}
- </Text>
- <Text className="px-2 py-1.5" size="small" leading="compact">
- {item.title ?? "-"}
- </Text>
- </div>
- <div className="grid grid-cols-2 divide-x">
- <Text className="px-2 py-1.5" size="small" leading="compact">
- {t("fields.sku")}
- </Text>
- <Text className="px-2 py-1.5" size="small" leading="compact">
- {item.sku}
- </Text>
- </div>
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-4 overflow-auto">
+ <div className="text-ui-fg-subtle shadow-elevation-card-rest grid grid-rows-2 divide-y rounded-lg border">
+ <div className="grid grid-cols-2 divide-x">
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {t("fields.title")}
+ </Text>
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {item.title ?? "-"}
+ </Text>
</div>
- <div className="flex flex-col">
- <Text size="small" weight="plus" leading="compact">
- {t("locations.domain")}
+ <div className="grid grid-cols-2 divide-x">
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {t("fields.sku")}
+ </Text>
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {item.sku}
</Text>
- <div className="text-ui-fg-subtle flex w-full justify-between">
- <Text size="small" leading="compact">
- {t("locations.selectLocations")}
- </Text>
- <Text size="small" leading="compact">
- {"("}
- {t("general.countOfTotalSelected", {
- count: locationFields.filter((l) => l.selected).length,
- total: locations.length,
- })}
- {")"}
- </Text>
- </div>
</div>
- {locationFields.map((location, idx) => {
- return (
- <LocationItem
- selected={location.selected}
- location={location as any}
- onSelect={() =>
- updateField(idx, {
- ...location,
- selected: !location.selected,
- })
- }
- key={location.id}
- />
- )
- })}
- </RouteDrawer.Body>
- <RouteDrawer.Footer>
- <div className="flex items-center justify-end gap-x-2">
- <RouteDrawer.Close asChild>
- <Button variant="secondary" size="small">
- {t("actions.cancel")}
- </Button>
- </RouteDrawer.Close>
- <Button type="submit" size="small" isLoading={false}>
- {t("actions.save")}
- </Button>
+ </div>
+ <div className="flex flex-col">
+ <Text size="small" weight="plus" leading="compact">
+ {t("locations.domain")}
+ </Text>
+ <div className="text-ui-fg-subtle flex w-full justify-between">
+ <Text size="small" leading="compact">
+ {t("locations.selectLocations")}
+ </Text>
+ <Text size="small" leading="compact">
+ {"("}
+ {t("general.countOfTotalSelected", {
+ count: selectedLocationIds.size,
+ total: locations.length,
+ })}
+ {")"}
+ </Text>
</div>
- </RouteDrawer.Footer>
- </KeyboundForm>
- </RouteDrawer.Form>
- )
-}
+ </div>
+
+ {locations.map((location) => (
+ <LocationItem
+ key={location.id}
+ selected={selectedLocationIds.has(location.id)}
+ location={location}
+ onSelect={(selected) => handleLocationSelect(location.id, selected)}
+ />
+ ))}
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button onClick={handleSubmit} size="small" isLoading={false}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </div>
+ );
+};
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/manage-locations-drawer.tsx b/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/manage-locations-drawer.tsx
index c8180d804..273554ece 100644
--- a/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/manage-locations-drawer.tsx
+++ b/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/manage-locations-drawer.tsx
@@ -1,16 +1,16 @@
-import { Heading } from "@medusajs/ui"
-import { useTranslation } from "react-i18next"
+import { Heading } from "@medusajs/ui";
+import { useTranslation } from "react-i18next";
-import { useParams } from "react-router-dom"
-import { RouteDrawer } from "@components/modals"
-import { useInventoryItem } from "@hooks/api/inventory"
-import { useStockLocations } from "@hooks/api/stock-locations"
-import { ManageLocationsForm } from "./components/manage-locations-form"
-import { INVENTORY_DETAIL_FIELDS } from "../../constants"
+import { useParams } from "react-router-dom";
+import { RouteDrawer } from "@components/modals";
+import { useInventoryItem } from "@hooks/api/inventory";
+import { useStockLocations } from "@hooks/api/stock-locations";
+import { ManageLocationsForm } from "./components/manage-locations-form";
+import { INVENTORY_DETAIL_FIELDS } from "../../constants";
export const ManageLocationsDrawer = () => {
- const { id } = useParams()
- const { t } = useTranslation()
+ const { id } = useParams();
+ const { t } = useTranslation();
const {
inventory_item: inventoryItem,
@@ -19,15 +19,15 @@ export const ManageLocationsDrawer = () => {
error,
} = useInventoryItem(id!, {
fields: INVENTORY_DETAIL_FIELDS,
- })
+ });
- const { stock_locations, isLoading: loadingLocations } = useStockLocations()
+ const { stock_locations, isLoading: loadingLocations } = useStockLocations();
const ready =
- !isLoading && !loadingLocations && inventoryItem && stock_locations
+ !isLoading && !loadingLocations && inventoryItem && stock_locations;
if (isError) {
- throw error
+ throw error;
}
return (
@@ -39,5 +39,5 @@ export const ManageLocationsDrawer = () => {
<ManageLocationsForm item={inventoryItem} locations={stock_locations} />
)}
</RouteDrawer>
- )
-}
+ );
+};
diff --git a/packages/vendor/src/pages/inventory/[id]/index.tsx b/packages/vendor/src/pages/inventory/[id]/index.tsx
index d19898b1c..6d443ad72 100644
--- a/packages/vendor/src/pages/inventory/[id]/index.tsx
+++ b/packages/vendor/src/pages/inventory/[id]/index.tsx
@@ -18,7 +18,6 @@ import { queryClient } from "@lib/query-client";
import { InventoryItemAttributeSection } from "./_components/inventory-item-attributes/attributes-section";
import { InventoryItemGeneralSection } from "./_components/inventory-item-general-section";
import { InventoryItemLocationLevelsSection } from "./_components/inventory-item-location-levels";
-import { InventoryItemReservationsSection } from "./_components/inventory-item-reservations";
import { InventoryItemVariantsSection } from "./_components/inventory-item-variants/variants-section";
import { INVENTORY_DETAIL_FIELDS } from "./constants";
@@ -63,7 +62,6 @@ export const Component = () => {
{ fields: INVENTORY_DETAIL_FIELDS },
{ initialData },
);
- const { getWidgets } = useDashboardExtension();
if (isLoading || !inventory_item) {
return (
@@ -77,7 +75,7 @@ export const Component = () => {
}
return (
- <TwoColumnPage data={inventory_item} >
+ <TwoColumnPage data={inventory_item}>
<TwoColumnPage.Main>
<InventoryItemGeneralSection inventoryItem={inventory_item} />
<InventoryItemLocationLevelsSection inventoryItem={inventory_item} />