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.

fix(orders): reserve order-edit offer items at a stocked location (MER-211) (#1200)

Viktor Holikead01cf9ddb5
diff --git a/integration-tests/http/order/vendor/order-edit-reservation-multiplier.spec.ts b/integration-tests/http/order/vendor/order-edit-reservation-multiplier.spec.ts
index 3d657b305..dede1d08f 100644
--- a/integration-tests/http/order/vendor/order-edit-reservation-multiplier.spec.ts
+++ b/integration-tests/http/order/vendor/order-edit-reservation-multiplier.spec.ts
@@ -63,6 +63,10 @@ medusaIntegrationTestRunner({
stocked: number
offerPrice: number
requiredQuantity?: number
+ // Adds a SECOND stock level at another location. The primary
+ // location (`stocked`) stays first, so it remains the
+ // inventory item's `location_levels[0]`.
+ secondaryStocked?: number
}) => {
const requiredQuantity = opts.requiredQuantity ?? 1
@@ -159,6 +163,38 @@ medusaIntegrationTestRunner({
headers
)
+ // Linked to the same sales channel so checkout can reserve there.
+ let secondaryLocation: any = undefined
+ if (opts.secondaryStocked != null) {
+ secondaryLocation = (
+ await api.post(
+ `/vendor/stock-locations`,
+ { name: `Warehouse2${tag}` },
+ headers
+ )
+ ).data.stock_location
+ await api.post(
+ `/vendor/stock-locations/${secondaryLocation.id}/sales-channels`,
+ { add: [salesChannel.id] },
+ headers
+ )
+ }
+
+ const stockLevels = [
+ {
+ location_id: stockLocation.id,
+ stocked_quantity: opts.stocked,
+ },
+ ...(secondaryLocation
+ ? [
+ {
+ location_id: secondaryLocation.id,
+ stocked_quantity: opts.secondaryStocked!,
+ },
+ ]
+ : []),
+ ]
+
const offer = (
await api.post(
`/vendor/offers`,
@@ -170,12 +206,7 @@ medusaIntegrationTestRunner({
{
title: `Inv${tag}`,
required_quantity: requiredQuantity,
- stock_levels: [
- {
- location_id: stockLocation.id,
- stocked_quantity: opts.stocked,
- },
- ],
+ stock_levels: stockLevels,
},
],
prices: [
@@ -196,10 +227,68 @@ medusaIntegrationTestRunner({
variant: product.variants[0],
offer,
stockLocation,
+ secondaryLocation,
shippingProfile,
}
}
+ // Second product + offer under an existing seller, reusing its
+ // stock location and shipping profile.
+ const addOfferToSeller = async (opts: {
+ headers: any
+ stockLocationId: string
+ shippingProfileId: string
+ stocked: number
+ offerPrice: number
+ requiredQuantity?: number
+ }) => {
+ const requiredQuantity = opts.requiredQuantity ?? 1
+ const tag = `_extra_${Date.now()}_${++prerequisiteCounter}`
+
+ const product = await createVendorProduct(api, opts.headers, {
+ title: `Prod${tag}`,
+ sku: `V${tag}`,
+ })
+
+ await api.post(
+ `/vendor/sales-channels/${salesChannel.id}/products`,
+ { add: [product.id] },
+ opts.headers
+ )
+
+ const offer = (
+ await api.post(
+ `/vendor/offers`,
+ {
+ sku: `OF${tag}`,
+ variant_id: product.variants[0].id,
+ shipping_profile_id: opts.shippingProfileId,
+ inventory_items: [
+ {
+ title: `Inv${tag}`,
+ required_quantity: requiredQuantity,
+ stock_levels: [
+ {
+ location_id: opts.stockLocationId,
+ stocked_quantity: opts.stocked,
+ },
+ ],
+ },
+ ],
+ prices: [
+ {
+ amount: opts.offerPrice,
+ currency_code: "usd",
+ },
+ ],
+ },
+ opts.headers
+ )
+ ).data.offer
+
+ return { product, variant: product.variants[0], offer }
+ }
+
const completeCartCheckout = async (offerId: string) => {
const cart = (
await api.post(
@@ -416,6 +505,121 @@ medusaIntegrationTestRunner({
// new ordered_quantity (2) × required_quantity (3) = 6
expect(Number(reservations[0].quantity)).toEqual(6)
})
+
+ it("adds a new offer item via order edit and confirms with a correct reservation", async () => {
+ const seed = await seedSellerOfferWithShipping({
+ email: "[email protected]",
+ name: "EditAddS1",
+ stocked: 100,
+ offerPrice: 2500,
+ requiredQuantity: 1,
+ })
+
+ const order = await completeCartCheckout(seed.offer.id)
+ expect(order.items.length).toEqual(1)
+
+ const extra = await addOfferToSeller({
+ headers: seed.headers,
+ stockLocationId: seed.stockLocation.id,
+ shippingProfileId: seed.shippingProfile.id,
+ stocked: 100,
+ offerPrice: 2500,
+ requiredQuantity: 1,
+ })
+
+ await api.post(
+ `/vendor/order-edits`,
+ { order_id: order.id },
+ seed.headers
+ )
+
+ await api.post(
+ `/vendor/order-edits/${order.id}/items`,
+ { items: [{ offer_id: extra.offer.id, quantity: 1 }] },
+ seed.headers
+ )
+
+ await api.post(
+ `/vendor/order-edits/${order.id}/request`,
+ {},
+ seed.headers
+ )
+
+ const confirmResp = await api.post(
+ `/vendor/order-edits/${order.id}/confirm`,
+ {},
+ seed.headers
+ )
+ expect(confirmResp.status).toEqual(200)
+
+ const query = appContainer.resolve(
+ ContainerRegistrationKeys.QUERY
+ )
+ const { data: refreshed } = await query.graph({
+ entity: "order",
+ fields: ["id", "items.id", "items.variant_id"],
+ filters: { id: order.id },
+ })
+ expect((refreshed[0] as any).items.length).toEqual(2)
+ })
+
+ it("confirms a qty bump when the first stock level is short but another location has stock", async () => {
+ const seed = await seedSellerOfferWithShipping({
+ email: "[email protected]",
+ name: "EditLocS1",
+ // location_levels[0] holds 1 unit: enough for qty 1, short
+ // for a later bump to 3. Secondary location holds plenty.
+ stocked: 1,
+ secondaryStocked: 100,
+ offerPrice: 2500,
+ requiredQuantity: 1,
+ })
+ expect(seed.secondaryLocation).toBeTruthy()
+
+ const order = await completeCartCheckout(seed.offer.id)
+ const lineItemId = order.items[0].id
+
+ const inventoryService = appContainer.resolve(Modules.INVENTORY)
+ let reservations =
+ await inventoryService.listReservationItems({
+ line_item_id: lineItemId,
+ })
+ expect(reservations.length).toEqual(1)
+ expect(Number(reservations[0].quantity)).toEqual(1)
+
+ // Bump to 3: exceeds the primary location's stock (1).
+ await api.post(
+ `/vendor/order-edits`,
+ { order_id: order.id },
+ seed.headers
+ )
+ await api.post(
+ `/vendor/order-edits/${order.id}/items/item/${lineItemId}`,
+ { quantity: 3 },
+ seed.headers
+ )
+ await api.post(
+ `/vendor/order-edits/${order.id}/request`,
+ {},
+ seed.headers
+ )
+
+ const confirmResp = await api.post(
+ `/vendor/order-edits/${order.id}/confirm`,
+ {},
+ seed.headers
+ )
+ expect(confirmResp.status).toEqual(200)
+
+ reservations = await inventoryService.listReservationItems({
+ line_item_id: lineItemId,
+ })
+ expect(reservations.length).toEqual(1)
+ expect(Number(reservations[0].quantity)).toEqual(3)
+ expect(reservations[0].location_id).toEqual(
+ seed.secondaryLocation.id
+ )
+ })
})
},
})
diff --git a/packages/core/src/workflows/order/workflows/confirm-order-edit-request.ts b/packages/core/src/workflows/order/workflows/confirm-order-edit-request.ts
index 313bd0749..cfad70763 100644
--- a/packages/core/src/workflows/order/workflows/confirm-order-edit-request.ts
+++ b/packages/core/src/workflows/order/workflows/confirm-order-edit-request.ts
@@ -12,15 +12,42 @@ import {
} from "@medusajs/framework/workflows-sdk"
import { confirmOrderEditRequestWorkflow as baseConfirmOrderEditRequestWorkflow } from "@medusajs/medusa/core-flows"
+/**
+ * Mercur pins `variant.manage_inventory = false` on every variant, so
+ * Medusa's `reserveInventoryStep` is a no-op inside its confirm: added
+ * items get no reservation and bumped items keep the stale one Medusa
+ * just deleted. This wrapper re-syncs the per-line reservation set from
+ * the offer side after Medusa's confirm runs, placing each reservation
+ * at a location that actually has availability (not blindly the
+ * inventory item's first stock level).
+ */
+
+type OfferLevelRow = {
+ location_id?: string | null
+ stocked_quantity?: number | null
+ reserved_quantity?: number | null
+ raw_stocked_quantity?: { value?: string } | null
+ raw_reserved_quantity?: { value?: string } | null
+}
+
type OfferLinkRow = {
required_quantity?: number | null
inventory_item_id?: string | null
inventory_item?: {
id?: string | null
- location_levels?: Array<{ location_id?: string | null }> | null
+ location_levels?: OfferLevelRow[] | null
} | null
}
+// Prefer the raw BigNumber values so precision survives large quantities.
+const levelAvailable = (lvl: OfferLevelRow): number =>
+ Number(
+ MathBN.sub(
+ lvl.raw_stocked_quantity?.value ?? lvl.stocked_quantity ?? 0,
+ lvl.raw_reserved_quantity?.value ?? lvl.reserved_quantity ?? 0
+ ).toString()
+ )
+
type CompensationDeleteCreated = {
type: "delete-created"
id: string
@@ -94,8 +121,10 @@ const adjustOrderEditReservationsForOffersStep = createStep(
inventory_item_id:
link.inventory_item?.id ?? link.inventory_item_id ?? null,
required_quantity: Number(link.required_quantity ?? 1),
- location_id:
- link.inventory_item?.location_levels?.[0]?.location_id ?? null,
+ levels: (link.inventory_item?.location_levels ?? []).filter(
+ (lvl): lvl is OfferLevelRow & { location_id: string } =>
+ !!lvl.location_id
+ ),
}))
.filter(
(
@@ -103,7 +132,7 @@ const adjustOrderEditReservationsForOffersStep = createStep(
): l is {
inventory_item_id: string
required_quantity: number
- location_id: string | null
+ levels: Array<OfferLevelRow & { location_id: string }>
} => !!l.inventory_item_id
)
@@ -111,27 +140,38 @@ const adjustOrderEditReservationsForOffersStep = createStep(
continue
}
- const inventoryItemIdsMissingLocation = normalizedLinks
- .filter((l) => !l.location_id)
+ // Fall back to the inventory module when the nested location_levels
+ // relation didn't come back expanded on the offer link.
+ const inventoryItemIdsMissingLevels = normalizedLinks
+ .filter((l) => l.levels.length === 0)
.map((l) => l.inventory_item_id)
- if (inventoryItemIdsMissingLocation.length) {
+ if (inventoryItemIdsMissingLevels.length) {
const levels = await inventoryService.listInventoryLevels({
- inventory_item_id: inventoryItemIdsMissingLocation,
+ inventory_item_id: inventoryItemIdsMissingLevels,
})
- const firstLocationByItem = new Map<string, string>()
+ const levelsByItem = new Map<
+ string,
+ Array<OfferLevelRow & { location_id: string }>
+ >()
for (const lvl of levels) {
const itemId = (lvl as { inventory_item_id: string }).inventory_item_id
- if (!firstLocationByItem.has(itemId)) {
- firstLocationByItem.set(
- itemId,
- (lvl as { location_id: string }).location_id
- )
+ const locId = (lvl as { location_id?: string }).location_id
+ if (!locId) {
+ continue
}
+ const arr = levelsByItem.get(itemId) ?? []
+ arr.push({
+ location_id: locId,
+ stocked_quantity: (lvl as { stocked_quantity?: number })
+ .stocked_quantity,
+ reserved_quantity: (lvl as { reserved_quantity?: number })
+ .reserved_quantity,
+ })
+ levelsByItem.set(itemId, arr)
}
for (const link of normalizedLinks) {
- if (!link.location_id) {
- link.location_id =
- firstLocationByItem.get(link.inventory_item_id) ?? null
+ if (link.levels.length === 0) {
+ link.levels = levelsByItem.get(link.inventory_item_id) ?? []
}
}
}
@@ -141,27 +181,58 @@ const adjustOrderEditReservationsForOffersStep = createStep(
line_item_id: lineItemId,
})
+ const existingByInventoryItem = new Map<string, any>()
+ for (const r of existingReservations) {
+ existingByInventoryItem.set(
+ (r as { inventory_item_id: string }).inventory_item_id,
+ r
+ )
+ }
+
+ // This line's existing reservation is deleted below, freeing its units
+ // back, so credit them when scoring its current location.
+ const pickLocation = (
+ link: { inventory_item_id: string; levels: OfferLevelRow[] },
+ desired: number
+ ): string | null => {
+ const existing = existingByInventoryItem.get(link.inventory_item_id) as
+ | { location_id?: string; quantity?: number }
+ | undefined
+ const existingLoc = existing?.location_id ?? null
+ const existingQty = Number(existing?.quantity ?? 0)
+
+ const adjustedAvailable = (locId: string): number => {
+ const lvl = link.levels.find((l) => l.location_id === locId)
+ const base = lvl ? levelAvailable(lvl) : 0
+ return base + (existingLoc === locId ? existingQty : 0)
+ }
+
+ if (existingLoc && adjustedAvailable(existingLoc) >= desired) {
+ return existingLoc
+ }
+ const fit = link.levels.find(
+ (l) => !!l.location_id && adjustedAvailable(l.location_id) >= desired
+ )
+ if (fit?.location_id) {
+ return fit.location_id
+ }
+ return existingLoc ?? link.levels[0]?.location_id ?? null
+ }
+
const desiredByInventoryItem = new Map<
string,
{ quantity: number; location_id: string | null }
>()
for (const link of normalizedLinks) {
+ const quantity = Number(
+ MathBN.mult(reservationQuantity, link.required_quantity).toString()
+ )
desiredByInventoryItem.set(link.inventory_item_id, {
- quantity: Number(
- MathBN.mult(reservationQuantity, link.required_quantity).toString()
- ),
- location_id: link.location_id,
+ quantity,
+ location_id: pickLocation(link, quantity),
})
}
- const existingByInventoryItem = new Map<string, any>()
- for (const r of existingReservations) {
- existingByInventoryItem.set(
- (r as { inventory_item_id: string }).inventory_item_id,
- r
- )
- }
-
const allMatch =
existingReservations.length === desiredByInventoryItem.size &&
normalizedLinks.every((link) => {
@@ -183,7 +254,7 @@ const adjustOrderEditReservationsForOffersStep = createStep(
.map((link) => {
const desired = desiredByInventoryItem.get(link.inventory_item_id)!
const locationId =
- link.location_id ?? inheritedLocation?.location_id ?? null
+ desired.location_id ?? inheritedLocation?.location_id ?? null
return {
line_item_id: lineItemId,
inventory_item_id: link.inventory_item_id,