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.

feat(admin): sync Reservations panel with Figma (#1330)

Viktor Holik691a3543760f
diff --git a/integration-tests/http/reservation/admin/reservation.spec.ts b/integration-tests/http/reservation/admin/reservation.spec.ts
new file mode 100644
index 000000000..a1e253a47
--- /dev/null
+++ b/integration-tests/http/reservation/admin/reservation.spec.ts
@@ -0,0 +1,245 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import {
+ IRegionModuleService,
+ ISalesChannelModuleService,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { Modules } from "@medusajs/framework/utils"
+import { MercurModules, SellerStatus } from "@mercurjs/types"
+import { createSellerUser } from "../../../helpers/create-seller-user"
+import { createVendorProduct } from "../../../helpers/create-product"
+import {
+ adminHeaders,
+ createAdminUser,
+} from "../../../helpers/create-admin-user"
+
+jest.setTimeout(180000)
+
+/**
+ * Covers the Mercur admin `/admin/reservations` override
+ * (`packages/core/src/api/admin/reservations`): it extends the native route so
+ * the list exposes the owning store and the product behind each reservation's
+ * inventory item, and adds the `sku` + `seller_id` filters the Figma list uses.
+ *
+ * Data path under test:
+ * reservation -> inventory_item -> seller (inventory-item-seller-link)
+ * reservation -> inventory_item -> offers -> product (offer-product-link)
+ */
+
+const approveSeller = async (
+ container: MedusaContainer,
+ sellerId: string
+) => {
+ const sellerModule: any = container.resolve(MercurModules.SELLER)
+ await sellerModule.updateSellers({ id: sellerId, status: SellerStatus.OPEN })
+}
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api, dbConnection }) => {
+ describe("Admin - Reservations list (store/product joins + filters)", () => {
+ let appContainer: MedusaContainer
+ let salesChannel: any
+ let counter = 0
+
+ const seedSellerReservation = async (opts: {
+ email: string
+ name: string
+ stocked: number
+ }) => {
+ const { seller, headers } = await createSellerUser(appContainer, {
+ email: opts.email,
+ name: opts.name,
+ })
+ await approveSeller(appContainer, (seller as any).id)
+ const tag = `_${opts.name}_${Date.now()}_${++counter}`
+
+ const stockLocation = (
+ await api.post(
+ `/vendor/stock-locations`,
+ { name: `Warehouse${tag}` },
+ headers
+ )
+ ).data.stock_location
+
+ await api.post(
+ `/vendor/stock-locations/${stockLocation.id}/sales-channels`,
+ { add: [salesChannel.id] },
+ headers
+ )
+
+ const shippingProfile = (
+ await api.post(
+ `/vendor/shipping-profiles`,
+ { name: `SP${tag}`, type: "default" },
+ headers
+ )
+ ).data.shipping_profile
+
+ // The offer flow now titles the inventory item after the variant, so
+ // give the variant the unique tag to keep the lookup below stable.
+ const product = await createVendorProduct(api, headers, {
+ title: `Prod${tag}`,
+ sku: `V${tag}`,
+ variantTitle: `Inv${tag}`,
+ })
+
+ await api.post(
+ `/vendor/offers`,
+ {
+ sku: `OF${tag}`,
+ variant_id: product.variants[0].id,
+ shipping_profile_id: shippingProfile.id,
+ inventory_items: [
+ {
+ title: `Inv${tag}`,
+ sku: `SKU${tag}`,
+ required_quantity: 1,
+ stock_levels: [
+ {
+ location_id: stockLocation.id,
+ stocked_quantity: opts.stocked,
+ },
+ ],
+ },
+ ],
+ prices: [{ amount: 1000, currency_code: "usd" }],
+ },
+ headers
+ )
+
+ // Resolve the inventory item created for the offer + its sku.
+ const inventoryItem = (
+ await api.get(
+ `/admin/inventory-items?q=Inv${tag}`,
+ adminHeaders
+ )
+ ).data.inventory_items[0]
+
+ const reservation = (
+ await api.post(
+ `/admin/reservations`,
+ {
+ inventory_item_id: inventoryItem.id,
+ location_id: stockLocation.id,
+ quantity: 1,
+ },
+ adminHeaders
+ )
+ ).data.reservation
+
+ return {
+ sellerId: (seller as any).id,
+ product,
+ stockLocation,
+ inventoryItem,
+ reservation,
+ }
+ }
+
+ let sellerA: Awaited<ReturnType<typeof seedSellerReservation>>
+ let sellerB: Awaited<ReturnType<typeof seedSellerReservation>>
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ await createAdminUser(dbConnection, adminHeaders, appContainer)
+
+ const regionModule: IRegionModuleService = appContainer.resolve(
+ Modules.REGION
+ )
+ await regionModule.createRegions({
+ name: "US",
+ currency_code: "usd",
+ countries: ["us"],
+ })
+
+ const scModule: ISalesChannelModuleService = appContainer.resolve(
+ Modules.SALES_CHANNEL
+ )
+ salesChannel = await scModule.createSalesChannels({
+ name: `SC_${Date.now()}`,
+ })
+
+ sellerA = await seedSellerReservation({
+ email: "[email protected]",
+ name: "StoreA",
+ stocked: 100,
+ })
+ sellerB = await seedSellerReservation({
+ email: "[email protected]",
+ name: "StoreB",
+ stocked: 100,
+ })
+ })
+
+ it("returns the store (seller) and product joins for each reservation", async () => {
+ const response = await api.get(`/admin/reservations`, adminHeaders)
+ expect(response.status).toBe(200)
+
+ const row = response.data.reservations.find(
+ (r: any) => r.id === sellerA.reservation.id
+ )
+
+ expect(row).toBeTruthy()
+ expect(row.inventory_item).toBeTruthy()
+ expect(row.inventory_item.sku).toEqual(sellerA.inventoryItem.sku)
+ expect(row.inventory_item.seller?.id).toEqual(sellerA.sellerId)
+ expect(row.inventory_item.seller?.name).toEqual("StoreA")
+ expect(row.inventory_item.offers?.[0]?.product?.id).toEqual(
+ sellerA.product.id
+ )
+ })
+
+ it("filters by sku", async () => {
+ const sku = sellerA.inventoryItem.sku
+ const response = await api.get(
+ `/admin/reservations?sku=${encodeURIComponent(sku)}`,
+ adminHeaders
+ )
+
+ expect(response.status).toBe(200)
+ expect(response.data.reservations.length).toBeGreaterThan(0)
+ for (const r of response.data.reservations) {
+ expect(r.inventory_item.sku).toEqual(sku)
+ }
+ expect(
+ response.data.reservations.some(
+ (r: any) => r.id === sellerB.reservation.id
+ )
+ ).toBe(false)
+ })
+
+ it("filters by seller_id (store)", async () => {
+ const response = await api.get(
+ `/admin/reservations?seller_id=${sellerA.sellerId}`,
+ adminHeaders
+ )
+
+ expect(response.status).toBe(200)
+ expect(
+ response.data.reservations.some(
+ (r: any) => r.id === sellerA.reservation.id
+ )
+ ).toBe(true)
+ expect(
+ response.data.reservations.some(
+ (r: any) => r.id === sellerB.reservation.id
+ )
+ ).toBe(false)
+ })
+
+ it("sorts by created_at", async () => {
+ const response = await api.get(
+ `/admin/reservations?order=-created_at`,
+ adminHeaders
+ )
+
+ expect(response.status).toBe(200)
+ const dates = response.data.reservations.map((r: any) =>
+ new Date(r.created_at).getTime()
+ )
+ const sorted = [...dates].sort((a, b) => b - a)
+ expect(dates).toEqual(sorted)
+ })
+ })
+ },
+})
diff --git a/packages/admin/src/components/inputs/combobox/combobox.tsx b/packages/admin/src/components/inputs/combobox/combobox.tsx
index 1ecf52226..7f932329c 100644
--- a/packages/admin/src/components/inputs/combobox/combobox.tsx
+++ b/packages/admin/src/components/inputs/combobox/combobox.tsx
@@ -15,7 +15,7 @@ import {
TrianglesMini,
XMarkMini,
} from "@medusajs/icons"
-import { clx, Text } from "@medusajs/ui"
+import { Badge, clx, Text } from "@medusajs/ui"
import { matchSorter } from "match-sorter"
import {
ComponentPropsWithoutRef,
@@ -38,6 +38,8 @@ import { genericForwardRef } from "../../utilities/generic-forward-ref"
type ComboboxOption = {
value: string
label: string
+ /** Optional secondary text rendered as a trailing pill (e.g. a product name). */
+ secondaryLabel?: string
disabled?: boolean
}
@@ -356,7 +358,7 @@ const ComboboxImpl = <T extends Value = string>(
}}
aria-busy={isPending}
>
- {results.map(({ value, label, disabled }) => (
+ {results.map(({ value, label, secondaryLabel, disabled }) => (
<PrimitiveComboboxItem
key={value}
value={value}
@@ -374,9 +376,14 @@ const ComboboxImpl = <T extends Value = string>(
<PrimitiveComboboxItemCheck className="flex !size-5 items-center justify-center">
{isArrayValue ? <CheckMini /> : <EllipseMiniSolid />}
</PrimitiveComboboxItemCheck>
- <PrimitiveComboboxItemValue className="txt-compact-small">
+ <PrimitiveComboboxItemValue className="txt-compact-small flex-1 overflow-hidden text-ellipsis whitespace-nowrap">
{label}
</PrimitiveComboboxItemValue>
+ {secondaryLabel && (
+ <Badge size="2xsmall" className="ml-auto shrink-0">
+ {secondaryLabel}
+ </Badge>
+ )}
</PrimitiveComboboxItem>
))}
{!!fetchNextPage && <div ref={lastOptionRef} className="w-px" />}
diff --git a/packages/admin/src/extension-targets.d.ts b/packages/admin/src/extension-targets.d.ts
index 0e405b506..7003b6e0b 100644
--- a/packages/admin/src/extension-targets.d.ts
+++ b/packages/admin/src/extension-targets.d.ts
@@ -259,7 +259,7 @@ declare module "@mercurjs/dashboard-sdk" {
formZones: "edit"
formTabs: Record<string, string>
displayZones: "general"
- displayFieldIds: "available_quantity" | "description" | "header" | "line_item_id" | "location" | "reserved_quantity" | "stocked_quantity"
+ displayFieldIds: "available_quantity" | "description" | "header" | "item_id" | "location" | "reserved_quantity" | "stocked_quantity"
}
"seller": {
formZones: "create" | "edit"
diff --git a/packages/admin/src/i18n/translations/$schema.json b/packages/admin/src/i18n/translations/$schema.json
index 189aa5f9e..269777a0e 100644
--- a/packages/admin/src/i18n/translations/$schema.json
+++ b/packages/admin/src/i18n/translations/$schema.json
@@ -4562,6 +4562,9 @@
"lineItemId": {
"type": "string"
},
+ "itemId": {
+ "type": "string"
+ },
"orderID": {
"type": "string"
},
@@ -4571,6 +4574,9 @@
"location": {
"type": "string"
},
+ "goToInventoryItem": {
+ "type": "string"
+ },
"inStockAtLocation": {
"type": "string"
},
@@ -4583,12 +4589,27 @@
"reservedAmount": {
"type": "string"
},
+ "reserved": {
+ "type": "string"
+ },
+ "storeLocationWarningLabel": {
+ "type": "string"
+ },
+ "storeLocationWarning": {
+ "type": "string"
+ },
"create": {
"type": "string"
},
"itemToReserve": {
"type": "string"
},
+ "itemPlaceholder": {
+ "type": "string"
+ },
+ "locationPlaceholder": {
+ "type": "string"
+ },
"quantityPlaceholder": {
"type": "string"
},
@@ -4628,6 +4649,9 @@
"quantityOutOfRange": {
"type": "string"
},
+ "pleaseEnterQuantity": {
+ "type": "string"
+ },
"idRequired": {
"type": "string"
},
@@ -4641,6 +4665,7 @@
"required": [
"noAvaliableQuantity",
"quantityOutOfRange",
+ "pleaseEnterQuantity",
"idRequired",
"selectLocation",
"enterQuantity"
@@ -4652,15 +4677,22 @@
"header",
"editItemDetails",
"lineItemId",
+ "itemId",
"orderID",
"description",
"location",
+ "goToInventoryItem",
"inStockAtLocation",
"availableAtLocation",
"reservedAtLocation",
"reservedAmount",
+ "reserved",
+ "storeLocationWarningLabel",
+ "storeLocationWarning",
"create",
"itemToReserve",
+ "itemPlaceholder",
+ "locationPlaceholder",
"quantityPlaceholder",
"descriptionPlaceholder",
"successToast",
@@ -12633,12 +12665,92 @@
},
"deleteWarning": {
"type": "string"
+ },
+ "fields": {
+ "type": "object",
+ "properties": {
+ "date": {
+ "type": "string"
+ },
+ "product": {
+ "type": "string"
+ },
+ "store": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "date",
+ "product",
+ "store"
+ ],
+ "additionalProperties": false
+ },
+ "list": {
+ "type": "object",
+ "properties": {
+ "noRecordsTitle": {
+ "type": "string"
+ },
+ "noRecordsMessage": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "noRecordsTitle",
+ "noRecordsMessage"
+ ],
+ "additionalProperties": false
+ },
+ "delete": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "lockedTitle": {
+ "type": "string"
+ },
+ "lockedDescription": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "title",
+ "description",
+ "lockedTitle",
+ "lockedDescription"
+ ],
+ "additionalProperties": false
+ },
+ "edit": {
+ "type": "object",
+ "properties": {
+ "lockedTitle": {
+ "type": "string"
+ },
+ "lockedDescription": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "lockedTitle",
+ "lockedDescription"
+ ],
+ "additionalProperties": false
}
},
"required": [
"domain",
"subtitle",
- "deleteWarning"
+ "deleteWarning",
+ "fields",
+ "list",
+ "delete",
+ "edit"
],
"additionalProperties": false
},
diff --git a/packages/admin/src/i18n/translations/en.json b/packages/admin/src/i18n/translations/en.json
index 1709b84c3..49fef8ec9 100644
--- a/packages/admin/src/i18n/translations/en.json
+++ b/packages/admin/src/i18n/translations/en.json
@@ -1123,15 +1123,22 @@
"header": "Reservation of {{itemName}}",
"editItemDetails": "Edit reservation",
"lineItemId": "Line item ID",
+ "itemId": "Item ID",
"orderID": "Order ID",
"description": "Description",
"location": "Location",
+ "goToInventoryItem": "Go to inventory item",
"inStockAtLocation": "In stock at this location",
"availableAtLocation": "Available at this location",
"reservedAtLocation": "Reserved at this location",
"reservedAmount": "Reserve amount",
+ "reserved": "Reserved",
+ "storeLocationWarningLabel": "Warning",
+ "storeLocationWarning": "You're modifying a reservation at a Store Location. Please confirm it with the Vendor to avoid data inconsistencies.",
"create": "Create reservation",
"itemToReserve": "Item to reserve",
+ "itemPlaceholder": "Select item",
+ "locationPlaceholder": "Select location",
"quantityPlaceholder": "How much do you want to reserve?",
"descriptionPlaceholder": "What type of reservation is this?",
"successToast": "Reservation was successfully created.",
@@ -1141,10 +1148,10 @@
"deleteDescription": "You are about to delete a reservation. This may affect Store inventory records. Before proceeding, make sure the Vendor has confirmed this change to avoid inconsistencies.",
"deleteBlockedDescription": "This reservation cannot be deleted because it's linked to an unfulfilled order.",
"gotIt": "Got it",
- "storeLocationWarning": "You're creating a reservation at a Store location. Please confirm it with the Vendor to avoid data inconsistencies.",
"errors": {
"noAvaliableQuantity": "Stock location doesn't have available quantity",
"quantityOutOfRange": "Minimum quantity is 1 and maximum quantity is {{max}}",
+ "pleaseEnterQuantity": "Please enter quantity",
"idRequired": "Inventory item ID is required",
"selectLocation": "Please select a location",
"enterQuantity": "Please enter a quantity"
@@ -3171,7 +3178,26 @@
"reservations": {
"domain": "Reservations",
"subtitle": "Manage the reserved quantity of inventory items.",
- "deleteWarning": "You are about to delete a reservation. This action cannot be undone."
+ "deleteWarning": "You are about to delete a reservation. This action cannot be undone.",
+ "fields": {
+ "date": "Date",
+ "product": "Product",
+ "store": "Store"
+ },
+ "list": {
+ "noRecordsTitle": "No reservations yet",
+ "noRecordsMessage": "Create reservations to manage the reserved quantity of inventory items"
+ },
+ "delete": {
+ "title": "Delete reservation",
+ "description": "You are about to delete a reservation. This may affect your Store inventory records. Before proceeding, make sure the Vendor has confirmed this change to avoid inconsistencies.",
+ "lockedTitle": "Delete reservation",
+ "lockedDescription": "This reservation cannot be deleted because it's linked to an unfulfilled order."
+ },
+ "edit": {
+ "lockedTitle": "Edit reservation",
+ "lockedDescription": "This reservation cannot be edited because it's linked to an unfulfilled order."
+ }
},
"salesChannels": {
"domain": "Sales Channels",
diff --git a/packages/admin/src/pages/reservations/reservation-create/components/reservation-create-from/reservation-create-from.tsx b/packages/admin/src/pages/reservations/reservation-create/components/reservation-create-from/reservation-create-from.tsx
index 240e3bcba..bfb00e43d 100644
--- a/packages/admin/src/pages/reservations/reservation-create/components/reservation-create-from/reservation-create-from.tsx
+++ b/packages/admin/src/pages/reservations/reservation-create/components/reservation-create-from/reservation-create-from.tsx
@@ -8,6 +8,7 @@ import {
import { zodResolver } from "@hookform/resolvers/zod"
import { HttpTypes } from "@medusajs/types"
+import { OfferDTO } from "@mercurjs/types"
import React from "react"
import { useForm } from "react-hook-form"
import { useTranslation } from "react-i18next"
@@ -37,6 +38,13 @@ const AttributeGridRow = ({
)
}
+const getProductTitle = (
+ inventoryItem: HttpTypes.AdminInventoryItem
+): string | undefined => {
+ const item = inventoryItem as { offers?: OfferDTO[] | null }
+ return item.offers?.[0]?.product?.title ?? undefined
+}
+
const buildCreateReservationSchema = (t: (key: string) => string) =>
zod.object({
inventory_item_id: zod
@@ -72,6 +80,7 @@ export const ReservationCreateForm = (props: { inventoryItemId?: string }) => {
const { inventory_items: searchedItems } = useInventoryItems({
q: inventorySearch,
+ fields: "id,title,sku,+offers.product.title",
})
// The preselected item (from `?item_id=`) may not be in the search results,
@@ -190,10 +199,14 @@ export const ReservationCreateForm = (props: { inventoryItemId?: string }) => {
onChange(v)
}}
{...field}
+ placeholder={t(
+ "inventory.reservation.itemPlaceholder"
+ )}
disabled={!!props.inventoryItemId}
options={(inventory_items ?? []).map(
(inventoryItem) => ({
label: inventoryItem.title ?? inventoryItem.sku!,
+ secondaryLabel: getProductTitle(inventoryItem),
value: inventoryItem.id,
})
)}
@@ -219,6 +232,9 @@ export const ReservationCreateForm = (props: { inventoryItemId?: string }) => {
onChange(v)
}}
{...field}
+ placeholder={t(
+ "inventory.reservation.locationPlaceholder"
+ )}
disabled={!inventoryItemId}
options={(stock_locations ?? []).map(
(stockLocation) => ({
diff --git a/packages/admin/src/pages/reservations/reservation-detail/components/edit-reservation/components/edit-reservation-form.tsx b/packages/admin/src/pages/reservations/reservation-detail/components/edit-reservation/components/edit-reservation-form.tsx
index 762dc3229..f37222b36 100644
--- a/packages/admin/src/pages/reservations/reservation-detail/components/edit-reservation/components/edit-reservation-form.tsx
+++ b/packages/admin/src/pages/reservations/reservation-detail/components/edit-reservation/components/edit-reservation-form.tsx
@@ -1,5 +1,13 @@
import { HttpTypes } from "@medusajs/types"
-import { Button, Input, Select, Text, Textarea, toast } from "@medusajs/ui"
+import {
+ Button,
+ InlineTip,
+ Input,
+ Select,
+ Text,
+ Textarea,
+ toast,
+} from "@medusajs/ui"
import { RouteDrawer, useRouteModal } from "../../../../../../components/modals"
import { useTranslation } from "react-i18next"
@@ -8,21 +16,26 @@ import {
FormExtensionZone,
useExtendableForm,
} from "@mercurjs/dashboard-shared"
+import { SellerDTO } from "@mercurjs/types"
import { Form } from "../../../../../../components/common/form"
import { KeyboundForm } from "../../../../../../components/utilities/keybound-form"
import { useUpdateReservationItem } from "../../../../../../hooks/api/reservations"
import { useDocumentDirection } from "../../../../../../hooks/use-document-direction"
+type StockLocationWithSeller = HttpTypes.AdminStockLocation & {
+ seller?: SellerDTO | null
+}
+
type EditReservationFormProps = {
reservation: HttpTypes.AdminReservationResponse["reservation"]
- locations: HttpTypes.AdminStockLocation[]
+ locations: StockLocationWithSeller[]
item: HttpTypes.AdminInventoryItemResponse["inventory_item"]
}
const EditReservationSchema = z.object({
location_id: z.string(),
description: z.string().optional(),
- quantity: z.number().min(1),
+ quantity: z.number().nullable(),
})
const AttributeGridRow = ({
@@ -72,18 +85,6 @@ export const EditReservationForm = ({
const { mutateAsync } = useUpdateReservationItem(reservation.id)
- const handleSubmit = form.handleSubmit(async (values) => {
- mutateAsync(values, {
- onSuccess: () => {
- toast.success(t("inventory.reservation.updateSuccessToast"))
- handleSuccess()
- },
- onError: (e) => {
- toast.error(e.message)
- },
- })
- })
-
const reservedQuantity = form.watch("quantity")
const locationId = form.watch("location_id")
@@ -91,6 +92,61 @@ export const EditReservationForm = ({
(level: HttpTypes.AdminInventoryLevel) => level.location_id === locationId
)
+ const selectedLocation = (locations || []).find((l) => l.id === locationId)
+ const isStoreLocation = !!selectedLocation?.seller
+
+ // The reservation's own quantity is already counted in the level's reserved
+ // amount, so it is available to this edit — add it back to the ceiling.
+ const maxQuantity =
+ (level?.available_quantity ?? 0) + (reservation.quantity ?? 0)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ // A location with no available stock wins over the empty-field message,
+ // matching the Figma error states.
+ if (maxQuantity < 1) {
+ form.setError("quantity", {
+ type: "manual",
+ message: t("inventory.reservation.errors.noAvaliableQuantity"),
+ })
+ return
+ }
+
+ if (values.quantity === null || values.quantity === undefined) {
+ form.setError("quantity", {
+ type: "manual",
+ message: t("inventory.reservation.errors.pleaseEnterQuantity"),
+ })
+ return
+ }
+
+ if (values.quantity < 1 || values.quantity > maxQuantity) {
+ form.setError("quantity", {
+ type: "manual",
+ message: t("inventory.reservation.errors.quantityOutOfRange", {
+ max: maxQuantity,
+ }),
+ })
+ return
+ }
+
+ const { additional_data: _additionalData, ...payload } = values as z.infer<
+ typeof EditReservationSchema
+ > & { additional_data?: Record<string, unknown> }
+
+ mutateAsync(
+ { ...payload, quantity: values.quantity },
+ {
+ onSuccess: () => {
+ toast.success(t("inventory.reservation.updateSuccessToast"))
+ handleSuccess()
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
return (
<RouteDrawer.Form form={form}>
<KeyboundForm
@@ -146,7 +202,7 @@ export const EditReservationForm = ({
value={
level!.stocked_quantity -
(level!.reserved_quantity - reservation.quantity) -
- reservedQuantity
+ (reservedQuantity ?? 0)
}
/>
</div>
@@ -157,17 +213,14 @@ export const EditReservationForm = ({
return (
<Form.Item>
<Form.Label>
- {t("inventory.reservation.reservedAmount")}
+ {t("inventory.reservation.reserved")}
</Form.Label>
<Form.Control>
<Input
type="number"
min={0}
- max={
- (level!.available_quantity || 0) +
- (reservation.quantity || 0)
- }
- value={value || ""}
+ max={maxQuantity}
+ value={value ?? ""}
onChange={(e) => {
const value = e.target.value
@@ -200,6 +253,15 @@ export const EditReservationForm = ({
)
}}
/>
+ {isStoreLocation && (
+ <InlineTip
+ variant="warning"
+ label={t("inventory.reservation.storeLocationWarningLabel")}
+ data-testid="reservation-edit-store-location-warning"
+ >
+ {t("inventory.reservation.storeLocationWarning")}
+ </InlineTip>
+ )}
<FormExtensionZone
model="reservation"
zone="edit"
diff --git a/packages/admin/src/pages/reservations/reservation-detail/components/edit-reservation/edit-reservation-modal.tsx b/packages/admin/src/pages/reservations/reservation-detail/components/edit-reservation/edit-reservation-modal.tsx
index 100c28b89..b4fae208f 100644
--- a/packages/admin/src/pages/reservations/reservation-detail/components/edit-reservation/edit-reservation-modal.tsx
+++ b/packages/admin/src/pages/reservations/reservation-detail/components/edit-reservation/edit-reservation-modal.tsx
@@ -28,6 +28,7 @@ export const ReservationEdit = () => {
id: inventoryItem?.location_levels?.map(
(level) => level.location_id
),
+ fields: "+seller.id",
},
{
enabled: !!inventoryItem?.location_levels,
diff --git a/packages/admin/src/pages/reservations/reservation-detail/components/reservation-general-section/reservation-general-section.tsx b/packages/admin/src/pages/reservations/reservation-detail/components/reservation-general-section/reservation-general-section.tsx
index c6d8c0802..96d0114e0 100644
--- a/packages/admin/src/pages/reservations/reservation-detail/components/reservation-general-section/reservation-general-section.tsx
+++ b/packages/admin/src/pages/reservations/reservation-detail/components/reservation-general-section/reservation-general-section.tsx
@@ -70,12 +70,12 @@ export const ReservationGeneralSection = ({
<DisplayField
model="reservation"
zone="general"
- id="line_item_id"
+ id="item_id"
data={reservation}
>
<SectionRow
- title={t("inventory.reservation.lineItemId")}
- value={reservation.line_item_id} // TODO fetch order instead + add link
+ title={t("inventory.reservation.itemId")}
+ value={inventoryItem.sku ?? inventoryItem.id}
/>
</DisplayField>
<DisplayField
@@ -139,7 +139,7 @@ export const ReservationGeneralSection = ({
data={reservation}
builtInFieldIds={[
"header",
- "line_item_id",
+ "item_id",
"description",
"location",
"stocked_quantity",
diff --git a/packages/admin/src/pages/reservations/reservation-detail/components/reservation-inventory-section/index.ts b/packages/admin/src/pages/reservations/reservation-detail/components/reservation-inventory-section/index.ts
new file mode 100644
index 000000000..1722509a6
--- /dev/null
+++ b/packages/admin/src/pages/reservations/reservation-detail/components/reservation-inventory-section/index.ts
@@ -0,0 +1 @@
+export * from "./reservation-inventory-section"
diff --git a/packages/admin/src/pages/reservations/reservation-detail/components/reservation-inventory-section/reservation-inventory-section.tsx b/packages/admin/src/pages/reservations/reservation-detail/components/reservation-inventory-section/reservation-inventory-section.tsx
new file mode 100644
index 000000000..74377ff89
--- /dev/null
+++ b/packages/admin/src/pages/reservations/reservation-detail/components/reservation-inventory-section/reservation-inventory-section.tsx
@@ -0,0 +1,76 @@
+import { Container, Heading } from "@medusajs/ui"
+import { BuildingStorefront } from "@medusajs/icons"
+import { useTranslation } from "react-i18next"
+import type { ExtendedAdminInventoryItem } from "@custom-types/inventory"
+import { ActionMenu } from "../../../../../components/common/action-menu"
+import { SectionRow } from "../../../../../components/common/section"
+
+type ReservationInventorySectionProps = {
+ inventoryItem: ExtendedAdminInventoryItem
+}
+
+export const ReservationInventorySection = ({
+ inventoryItem,
+}: ReservationInventorySectionProps) => {
+ const { t } = useTranslation()
+
+ const getQuantityFormat = (quantity: number) => {
+ if (quantity !== undefined && !isNaN(quantity)) {
+ return t("inventory.quantityAcrossLocations", {
+ quantity,
+ locations: inventoryItem.location_levels?.length,
+ })
+ }
+
+ return "-"
+ }
+
+ return (
+ <Container
+ className="divide-y p-0"
+ data-testid="reservation-inventory-section"
+ >
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading data-testid="reservation-inventory-title">
+ {inventoryItem.title ?? inventoryItem.sku}
+ </Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <BuildingStorefront />,
+ label: t("inventory.reservation.goToInventoryItem"),
+ to: `/inventory/${inventoryItem.id}`,
+ },
+ ],
+ },
+ ]}
+ data-testid="reservation-inventory-action-menu"
+ />
+ </div>
+ <SectionRow
+ title={t("fields.sku")}
+ value={inventoryItem.sku ?? "-"}
+ data-testid="reservation-inventory-sku-row"
+ />
+ <SectionRow
+ title={t("fields.inStock")}
+ value={getQuantityFormat(inventoryItem.stocked_quantity)}
+ data-testid="reservation-inventory-in-stock-row"
+ />
+ <SectionRow
+ title={t("inventory.reserved")}
+ value={getQuantityFormat(inventoryItem.reserved_quantity)}
+ data-testid="reservation-inventory-reserved-row"
+ />
+ <SectionRow
+ title={t("inventory.available")}
+ value={getQuantityFormat(
+ inventoryItem.stocked_quantity - inventoryItem.reserved_quantity
+ )}
+ data-testid="reservation-inventory-available-row"
+ />
+ </Container>
+ )
+}
diff --git a/packages/admin/src/pages/reservations/reservation-detail/reservation-detail.tsx b/packages/admin/src/pages/reservations/reservation-detail/reservation-detail.tsx
index 5cd224142..3eb418f13 100644
--- a/packages/admin/src/pages/reservations/reservation-detail/reservation-detail.tsx
+++ b/packages/admin/src/pages/reservations/reservation-detail/reservation-detail.tsx
@@ -8,8 +8,8 @@ import { TwoColumnPage } from "../../../components/layout/pages";
import { useInventoryItem } from "../../../hooks/api";
import { useReservationItem } from "../../../hooks/api/reservations";
-import { InventoryItemGeneralSection } from "../../inventory/inventory-detail/components/inventory-item-general-section";
import { ReservationGeneralSection } from "./components/reservation-general-section";
+import { ReservationInventorySection } from "./components/reservation-inventory-section";
import { reservationItemLoader } from "./loader";
const Root = ({ children }: { children?: ReactNode }) => {
@@ -73,7 +73,7 @@ const Root = ({ children }: { children?: ReactNode }) => {
<TwoColumnPage.Sidebar>
<WidgetZone id="reservation.detail.side" data={reservation}>
{inventory_item && (
- <InventoryItemGeneralSection inventoryItem={inventory_item} />
+ <ReservationInventorySection inventoryItem={inventory_item} />
)}
</WidgetZone>
</TwoColumnPage.Sidebar>
@@ -85,5 +85,5 @@ export const ReservationDetailPage = Object.assign(Root, {
Main: TwoColumnPage.Main,
Sidebar: TwoColumnPage.Sidebar,
MainGeneralSection: ReservationGeneralSection,
- SidebarInventorySection: InventoryItemGeneralSection,
+ SidebarInventorySection: ReservationInventorySection,
});
diff --git a/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/reservation-actions.tsx b/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/reservation-actions.tsx
index 1691997fb..84f8623d5 100644
--- a/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/reservation-actions.tsx
+++ b/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/reservation-actions.tsx
@@ -3,6 +3,7 @@ import { PencilSquare, Trash } from "@medusajs/icons"
import { ActionMenu } from "../../../../../components/common/action-menu"
import { useDeleteReservationItem } from "../../../../../hooks/api/reservations"
import { usePrompt } from "@medusajs/ui"
+import { useNavigate } from "react-router-dom"
import { useTranslation } from "react-i18next"
import { ExtendedReservationItem } from "../../../../inventory/inventory-detail/components/reservations-table/use-reservation-list-table-columns"
import { toast } from "@medusajs/ui"
@@ -13,13 +14,47 @@ export const ReservationActions = ({
reservation: ExtendedReservationItem
}) => {
const { t } = useTranslation()
+ const navigate = useNavigate()
const prompt = usePrompt()
const { mutateAsync } = useDeleteReservationItem(reservation.id)
+ // Reservations linked to an unfulfilled order cannot be edited or deleted.
+ // A fulfilled order auto-removes its reservation, so a still-present
+ // line-item link means the order is unfulfilled.
+ const isLocked = !!reservation.line_item_id
+
+ const showLockedPrompt = (title: string, description: string) =>
+ prompt({
+ title,
+ description,
+ confirmText: t("general.gotIt"),
+ cancelText: t("actions.cancel"),
+ })
+
+ const handleEdit = async () => {
+ if (isLocked) {
+ await showLockedPrompt(
+ t("reservations.edit.lockedTitle"),
+ t("reservations.edit.lockedDescription")
+ )
+ return
+ }
+
+ navigate(`${reservation.id}/edit`)
+ }
+
const handleDelete = async () => {
+ if (isLocked) {
+ await showLockedPrompt(
+ t("reservations.delete.lockedTitle"),
+ t("reservations.delete.lockedDescription")
+ )
+ return
+ }
+
const res = await prompt({
- title: t("general.areYouSure"),
- description: t("reservations.deleteWarning"),
+ title: t("reservations.delete.title"),
+ description: t("reservations.delete.description"),
confirmText: t("actions.delete"),
cancelText: t("actions.cancel"),
})
@@ -45,7 +80,7 @@ export const ReservationActions = ({
actions: [
{
label: t("actions.edit"),
- to: `${reservation.id}/edit`,
+ onClick: handleEdit,
icon: <PencilSquare />,
},
],
diff --git a/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/reservation-list-table.tsx b/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/reservation-list-table.tsx
index c4fe7327b..bfcf5d55a 100644
--- a/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/reservation-list-table.tsx
+++ b/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/reservation-list-table.tsx
@@ -62,6 +62,7 @@ export const ReservationListHeader = ({ children }: { children?: ReactNode }) =>
}
export const ReservationListDataTable = () => {
+ const { t } = useTranslation()
const { searchParams, raw } = useReservationTableQuery({
pageSize: PAGE_SIZE,
})
@@ -101,8 +102,23 @@ export const ReservationListDataTable = () => {
filters={filters}
queryObject={raw}
pagination
+ search
+ orderBy={[
+ { key: "inventory_item.title", label: t("fields.title") },
+ { key: "inventory_item.sku", label: t("fields.sku") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ defaultOrder="inventory_item.title"
navigateTo={(row) => row.id}
- search={false}
+ noRecords={{
+ title: t("reservations.list.noRecordsTitle"),
+ message: t("reservations.list.noRecordsMessage"),
+ action: {
+ to: "create",
+ label: t("actions.create"),
+ },
+ }}
/>
)
}
diff --git a/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/use-reservation-table-columns.tsx b/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/use-reservation-table-columns.tsx
index 0156e51b5..ac3e86e24 100644
--- a/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/use-reservation-table-columns.tsx
+++ b/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/use-reservation-table-columns.tsx
@@ -1,6 +1,7 @@
import { createColumnHelper } from "@tanstack/react-table"
import { useMemo } from "react"
import { useTranslation } from "react-i18next"
+import { OfferDTO, SellerDTO } from "@mercurjs/types"
import { DateCell } from "../../../../../components/table/table-cells/common/date-cell"
import { PlaceholderCell } from "../../../../../components/table/table-cells/common/placeholder-cell"
import { ReservationActions } from "./reservation-actions"
@@ -8,89 +9,78 @@ import { ExtendedReservationItem } from "../../../../inventory/inventory-detail/
const columnHelper = createColumnHelper<ExtendedReservationItem>()
+const TruncatedTextCell = ({ value }: { value?: string | null }) => {
+ if (!value) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{value}</span>
+ </div>
+ )
+}
+
+// Product + Store come from links that may not be populated on every payload;
+// read them defensively and fall back to a placeholder. Inventory is
+// offer-scoped in Mercur, so the product is reached through the offer:
+// inventory_item -> offers -> product.
+const getProductTitle = (reservation: ExtendedReservationItem) => {
+ const item = reservation.inventory_item as
+ | { offers?: OfferDTO[] | null }
+ | undefined
+ return item?.offers?.[0]?.product?.title ?? undefined
+}
+
+const getStoreName = (reservation: ExtendedReservationItem) => {
+ const item = reservation.inventory_item as
+ | { seller?: SellerDTO | null }
+ | undefined
+ return item?.seller?.name ?? undefined
+}
+
export const useReservationTableColumns = () => {
const { t } = useTranslation()
return useMemo(
() => [
- columnHelper.accessor("inventory_item", {
+ columnHelper.accessor("inventory_item.title", {
+ header: t("fields.title"),
+ cell: ({ getValue }) => <TruncatedTextCell value={getValue()} />,
+ }),
+ columnHelper.accessor("inventory_item.sku", {
header: t("fields.sku"),
- cell: ({ getValue }) => {
- const inventoryItem = getValue()
-
- if (!inventoryItem || !inventoryItem.sku) {
- return <PlaceholderCell />
- }
-
- return (
- <div className="flex size-full items-center overflow-hidden">
- <span className="truncate">{inventoryItem.sku}</span>
- </div>
- )
- },
+ cell: ({ getValue }) => <TruncatedTextCell value={getValue()} />,
+ }),
+ columnHelper.display({
+ id: "product",
+ header: t("reservations.fields.product"),
+ cell: ({ row }) => (
+ <TruncatedTextCell value={getProductTitle(row.original)} />
+ ),
+ }),
+ columnHelper.display({
+ id: "store",
+ header: t("reservations.fields.store"),
+ cell: ({ row }) => (
+ <TruncatedTextCell value={getStoreName(row.original)} />
+ ),
}),
- /**
- * TEMP: hide this column until a link is added
- */
- // columnHelper.accessor("line_item", {
- // header: t("fields.order"),
- // cell: ({ getValue }) => {
- // const inventoryItem = getValue()
- //
- // if (!inventoryItem || !inventoryItem.order?.display_id) {
- // return <PlaceholderCell />
- // }
- //
- // return (
- // <div className="flex size-full items-center overflow-hidden">
- // <LinkButton to={`/orders/${inventoryItem.order.id}`}>
- // <span className="truncate">
- // #{inventoryItem.order.display_id}
- // </span>
- // </LinkButton>
- // </div>
- // )
- // },
- // }),
columnHelper.accessor("description", {
header: t("fields.description"),
- cell: ({ getValue }) => {
- const description = getValue()
-
- if (!description) {
- return <PlaceholderCell />
- }
-
- return (
- <div className="flex size-full items-center overflow-hidden">
- <span className="truncate">{description}</span>
- </div>
- )
- },
- }),
- columnHelper.accessor("created_at", {
- header: t("fields.created"),
- cell: ({ getValue }) => {
- const created = getValue()
-
- return <DateCell date={created} />
- },
+ cell: ({ getValue }) => <TruncatedTextCell value={getValue()} />,
}),
columnHelper.accessor("quantity", {
- header: () => (
- <div className="flex size-full items-center justify-end overflow-hidden text-right">
- <span className="truncate">{t("fields.quantity")}</span>
+ header: t("fields.quantity"),
+ cell: ({ getValue }) => (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{getValue()}</span>
</div>
),
- cell: ({ getValue }) => {
- const quantity = getValue()
-
- return (
- <div className="flex size-full items-center justify-end overflow-hidden text-right">
- <span className="truncate">{quantity}</span>
- </div>
- )
- },
+ }),
+ columnHelper.accessor("created_at", {
+ header: t("reservations.fields.date"),
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
}),
columnHelper.display({
id: "actions",
diff --git a/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/use-reservation-table-filters.tsx b/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/use-reservation-table-filters.tsx
index f8dc3769f..a67cb9130 100644
--- a/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/use-reservation-table-filters.tsx
+++ b/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/use-reservation-table-filters.tsx
@@ -1,4 +1,5 @@
import { Filter } from "../../../../../components/table/data-table"
+import { useSellers } from "../../../../../hooks/api/sellers"
import { useStockLocations } from "../../../../../hooks/api/stock-locations"
import { useTranslation } from "react-i18next"
@@ -7,9 +8,32 @@ export const useReservationTableFilters = () => {
const { stock_locations } = useStockLocations({
limit: 1000,
})
+ const { sellers } = useSellers({
+ limit: 1000,
+ fields: "id,name",
+ })
const filters: Filter[] = []
+ filters.push({
+ type: "string",
+ key: "sku",
+ label: t("fields.sku"),
+ })
+
+ if (sellers) {
+ filters.push({
+ type: "select",
+ options: sellers.map((s) => ({
+ label: s.name,
+ value: s.id,
+ })),
+ key: "seller_id",
+ searchable: true,
+ label: t("reservations.fields.store"),
+ })
+ }
+
if (stock_locations) {
const stockLocationFilter: Filter = {
type: "select",
diff --git a/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/use-reservation-table-query.tsx b/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/use-reservation-table-query.tsx
index b184dbfec..b398ed9cb 100644
--- a/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/use-reservation-table-query.tsx
+++ b/packages/admin/src/pages/reservations/reservation-list/components/reservation-list-table/use-reservation-table-query.tsx
@@ -9,7 +9,17 @@ export const useReservationTableQuery = ({
prefix?: string
}) => {
const raw = useQueryParams(
- ["location_id", "offset", "created_at", "quantity", "updated_at", "order"],
+ [
+ "q",
+ "sku",
+ "seller_id",
+ "location_id",
+ "offset",
+ "created_at",
+ "quantity",
+ "updated_at",
+ "order",
+ ],
prefix
)
@@ -21,7 +31,7 @@ export const useReservationTableQuery = ({
location_id: location_id,
created_at: created_at ? JSON.parse(created_at) : undefined,
updated_at: updated_at ? JSON.parse(updated_at) : undefined,
- order: order ?? "-created_at",
+ order: order ?? "inventory_item.title",
...rest,
}
diff --git a/packages/core/src/api/admin/middlewares.ts b/packages/core/src/api/admin/middlewares.ts
index 145ae68ce..e82411728 100644
--- a/packages/core/src/api/admin/middlewares.ts
+++ b/packages/core/src/api/admin/middlewares.ts
@@ -20,6 +20,7 @@ import { adminProductCategoriesMiddlewares } from "./product-categories/middlewa
import { adminProductAttributesMiddlewares } from "./product-attributes/middlewares"
import { adminProductChangesMiddlewares } from "./product-changes/middlewares"
import { adminStockLocationsMiddlewares } from "./stock-locations/middlewares"
+import { adminReservationsMiddlewares } from "./reservations/middlewares"
import { adminInventoryItemsMiddlewares } from "./inventory-items/middlewares"
import { adminShippingOptionsMiddlewares } from "./shipping-options/middlewares"
import { adminShippingProfilesMiddlewares } from "./shipping-profiles/middlewares"
@@ -52,6 +53,7 @@ export const adminMiddlewares: MiddlewareRoute[] = [
...adminProductAttributesMiddlewares,
...adminProductChangesMiddlewares,
...adminStockLocationsMiddlewares,
+ ...adminReservationsMiddlewares,
...adminInventoryItemsMiddlewares,
...adminShippingOptionsMiddlewares,
...adminShippingProfilesMiddlewares,
diff --git a/packages/core/src/api/admin/reservations/middlewares.ts b/packages/core/src/api/admin/reservations/middlewares.ts
new file mode 100644
index 000000000..68babed90
--- /dev/null
+++ b/packages/core/src/api/admin/reservations/middlewares.ts
@@ -0,0 +1,100 @@
+import {
+ AuthenticatedMedusaRequest,
+ maybeApplyLinkFilter,
+ MedusaNextFunction,
+ MedusaResponse,
+ MiddlewareRoute,
+} from "@medusajs/framework/http"
+import { validateAndTransformQuery } from "@medusajs/framework"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+import { ORIGINAL_MIDDLEWARES } from "../../../utils/disable-medusa-middlewares"
+import { listTransformQueryConfig } from "./query-config"
+import { AdminGetReservationsParams } from "./validators"
+
+const LIST_MATCHER = "/admin/reservations"
+
+const capturedBase = (ORIGINAL_MIDDLEWARES[
+ "dist/api/admin/reservations/middlewares.js"
+] ?? []) as MiddlewareRoute[]
+
+const baseWithoutListGet = capturedBase.filter((route) => {
+ if (route.matcher !== LIST_MATCHER) return true
+ const methods = Array.isArray(route.method)
+ ? route.method
+ : route.method
+ ? [route.method]
+ : []
+ return !methods.includes("GET")
+})
+
+// The list exposes a free-text SKU filter; SKU lives on the linked inventory
+// item, which the reservation query can't filter through a nested relation
+// path. Resolve the matching inventory item ids up front and narrow the
+// reservation query by `inventory_item_id` instead (dropping the flat `sku`
+// key, since the reservation entity has no `sku` column).
+const maybeApplyInventoryItemSkuFilter = async (
+ req: AuthenticatedMedusaRequest,
+ _res: MedusaResponse,
+ next: MedusaNextFunction
+) => {
+ const filterableFields = req.filterableFields
+ const sku = filterableFields?.sku as string | undefined
+
+ if (!sku) {
+ return next()
+ }
+
+ delete filterableFields.sku
+
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+ const { data: inventoryItems } = await query.graph({
+ entity: "inventory_item",
+ fields: ["id"],
+ filters: { sku },
+ })
+
+ const matchedIds = inventoryItems.map((item) => item.id as string)
+ const existing = filterableFields.inventory_item_id
+
+ if (existing) {
+ const existingIds = Array.isArray(existing) ? existing : [existing]
+ filterableFields.inventory_item_id = existingIds.filter((id) =>
+ matchedIds.includes(id as string)
+ )
+ } else {
+ filterableFields.inventory_item_id = matchedIds
+ }
+
+ // Reassign so the mutation sticks — `req.filterableFields` returns a fresh
+ // object per access, mirroring `maybeApplyLinkFilter`.
+ req.filterableFields = filterableFields
+
+ return next()
+}
+
+export const adminReservationsMiddlewares: MiddlewareRoute[] = [
+ ...baseWithoutListGet,
+ {
+ method: ["GET"],
+ matcher: LIST_MATCHER,
+ middlewares: [
+ validateAndTransformQuery(
+ AdminGetReservationsParams,
+ listTransformQueryConfig
+ ),
+ // Store filter: inventory_item -> seller (inventory-item-seller-link).
+ // Resolve matching inventory item ids from the link and filter
+ // reservations by inventory_item_id.
+ maybeApplyLinkFilter({
+ entryPoint: "inventory_item_seller",
+ resourceId: "inventory_item_id",
+ filterableField: "seller_id",
+ filterByField: "inventory_item_id",
+ }),
+ // Runs after the store filter so a combined sku + store query narrows
+ // the already-resolved inventory_item_id set instead of replacing it.
+ maybeApplyInventoryItemSkuFilter,
+ ],
+ },
+]
diff --git a/packages/core/src/api/admin/reservations/query-config.ts b/packages/core/src/api/admin/reservations/query-config.ts
new file mode 100644
index 000000000..9ad8619c5
--- /dev/null
+++ b/packages/core/src/api/admin/reservations/query-config.ts
@@ -0,0 +1,49 @@
+const defaultAdminReservationInventoryItemFields = [
+ "id",
+ "sku",
+ "title",
+ "description",
+ "thumbnail",
+ "requires_shipping",
+ "origin_country",
+ "hs_code",
+ "mid_code",
+ "material",
+ "weight",
+ "length",
+ "height",
+ "width",
+ "metadata",
+]
+
+export const defaultAdminReservationFields = [
+ "id",
+ "location_id",
+ "inventory_item_id",
+ "quantity",
+ "line_item_id",
+ "description",
+ "metadata",
+ "created_at",
+ "updated_at",
+ ...defaultAdminReservationInventoryItemFields.map(
+ (f) => `inventory_item.${f}`
+ ),
+ "inventory_item.seller.id",
+ "inventory_item.seller.name",
+ "inventory_item.offers.id",
+ "inventory_item.offers.product_variant.id",
+ "inventory_item.offers.product_variant.title",
+ "inventory_item.offers.product.id",
+ "inventory_item.offers.product.title",
+]
+
+export const retrieveTransformQueryConfig = {
+ defaults: defaultAdminReservationFields,
+ isList: false,
+}
+
+export const listTransformQueryConfig = {
+ ...retrieveTransformQueryConfig,
+ isList: true,
+}
diff --git a/packages/core/src/api/admin/reservations/validators.ts b/packages/core/src/api/admin/reservations/validators.ts
new file mode 100644
index 000000000..fd5d36937
--- /dev/null
+++ b/packages/core/src/api/admin/reservations/validators.ts
@@ -0,0 +1,16 @@
+import { z } from "zod"
+import { AdminGetReservationsParams as MedusaAdminGetReservationsParams } from "@medusajs/medusa/api/admin/reservations/validators"
+
+export type AdminGetReservationsParamsType = z.infer<
+ typeof AdminGetReservationsParams
+>
+
+// Extend the native reservation list params with the marketplace filters the
+// Figma list exposes: free-text SKU and a Store (seller) select.
+export const AdminGetReservationsParams =
+ MedusaAdminGetReservationsParams.merge(
+ z.object({
+ sku: z.string().optional(),
+ seller_id: z.union([z.string(), z.array(z.string())]).optional(),
+ })
+ )
diff --git a/packages/core/src/utils/disable-medusa-middlewares.ts b/packages/core/src/utils/disable-medusa-middlewares.ts
index 9fe5d263b..9cca6f817 100644
--- a/packages/core/src/utils/disable-medusa-middlewares.ts
+++ b/packages/core/src/utils/disable-medusa-middlewares.ts
@@ -35,6 +35,7 @@ const OVERRIDES: string[] = [
"dist/api/admin/shipping-options/middlewares.js",
"dist/api/admin/shipping-profiles/middlewares.js",
"dist/api/admin/stock-locations/middlewares.js",
+ "dist/api/admin/reservations/middlewares.js",
"dist/api/admin/inventory-items/middlewares.js",
"dist/api/store/products/middlewares.js",
"dist/api/store/product-categories/middlewares.js",
diff --git a/packages/core/src/workflows/offer/workflows/create-offers.ts b/packages/core/src/workflows/offer/workflows/create-offers.ts
index d6a91c598..9422a570c 100644
--- a/packages/core/src/workflows/offer/workflows/create-offers.ts
+++ b/packages/core/src/workflows/offer/workflows/create-offers.ts
@@ -55,37 +55,55 @@ export const createOffersWorkflow: ReturnWorkflow<
function (input: CreateOffersWorkflowInput) {
const validate = createHook("validate", { input })
- const inventoryItemsToCreate = transform({ input }, ({ input }) => {
- const items: Array<{
- sku?: string
- title: string
- location_levels: Array<{
- location_id: string
- stocked_quantity: number
- }>
- }> = []
- const offerSpans: Array<{ start: number; length: number }> = []
-
- input.offers.forEach((offer) => {
- if (!offer.inventory_items?.length) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- "Offer must have at least one inventory item",
- )
- }
- const start = items.length
- offer.inventory_items.forEach((item) => {
- items.push({
- sku: item.sku,
- title: item.title ?? item.sku ?? offer.sku,
- location_levels: item.stock_levels ?? [],
+ const variantIds = transform({ input }, ({ input }) =>
+ Array.from(new Set(input.offers.map((o) => o.variant_id))),
+ )
+
+ const { data: variants } = useQueryGraphStep({
+ entity: "product_variant",
+ fields: ["id", "title", "ean", "upc", "price_set.id", "product.id"],
+ filters: { id: variantIds },
+ }).config({ name: "get-variants" })
+
+ const inventoryItemsToCreate = transform(
+ { input, variants },
+ ({ input, variants }) => {
+ const variantTitleById = new Map(
+ variants.map((v) => [v.id, v.title as string | undefined]),
+ )
+
+ const items: Array<{
+ sku?: string
+ title: string
+ location_levels: Array<{
+ location_id: string
+ stocked_quantity: number
+ }>
+ }> = []
+ const offerSpans: Array<{ start: number; length: number }> = []
+
+ input.offers.forEach((offer) => {
+ if (!offer.inventory_items?.length) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ "Offer must have at least one inventory item",
+ )
+ }
+ const variantTitle = variantTitleById.get(offer.variant_id)
+ const start = items.length
+ offer.inventory_items.forEach((item) => {
+ items.push({
+ sku: item.sku,
+ title: variantTitle ?? item.title ?? item.sku ?? offer.sku,
+ location_levels: item.stock_levels ?? [],
+ })
})
+ offerSpans.push({ start, length: offer.inventory_items.length })
})
- offerSpans.push({ start, length: offer.inventory_items.length })
- })
- return { items, offerSpans }
- })
+ return { items, offerSpans }
+ },
+ )
const itemsForCreation = transform(
{ inventoryItemsToCreate },
@@ -111,16 +129,6 @@ export const createOffersWorkflow: ReturnWorkflow<
inventory_item_ids: createdInventoryItemIds,
})
- const variantIds = transform({ input }, ({ input }) =>
- Array.from(new Set(input.offers.map((o) => o.variant_id))),
- )
-
- const { data: variants } = useQueryGraphStep({
- entity: "product_variant",
- fields: ["id", "ean", "upc", "price_set.id", "product.id"],
- filters: { id: variantIds },
- }).config({ name: "get-variants" })
-
const stripped = transform(
{ input, variants, variantIds },
({ input, variants, variantIds }) => {