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(cart): confirm offer stock against the cart's total demand per inventory item (#1668)

Ricardo Satc447b17811ef
diff --git a/integration-tests/http/offer/cart/manage-inventory.spec.ts b/integration-tests/http/offer/cart/manage-inventory.spec.ts
index f37c2406a..b5b8e5680 100644
--- a/integration-tests/http/offer/cart/manage-inventory.spec.ts
+++ b/integration-tests/http/offer/cart/manage-inventory.spec.ts
@@ -5,6 +5,7 @@ import {
MedusaContainer,
} from "@medusajs/framework/types"
import { Modules } from "@medusajs/framework/utils"
+import { addToCartWorkflow } from "@medusajs/medusa/core-flows"
import { createSellerUser } from "../../../helpers/create-seller-user"
import { createShippingProfile } from "../../../helpers/create-shipping-profile"
import {
@@ -100,7 +101,62 @@ medusaIntegrationTestRunner({
)
).data.offer
- return { headers, sellerId: seller.id, offer, product }
+ return {
+ headers,
+ sellerId: seller.id,
+ offer,
+ product,
+ shippingProfile,
+ stockLocation,
+ }
+ }
+
+ const seedSharedItemOffers = async (name: string) => {
+ const base = await seedSellerOffer({
+ email: `${name.toLowerCase()}@test.com`,
+ name,
+ offerPrice: 100,
+ inventory_items: [{ stocked: 100, required_quantity: 1 }],
+ })
+ const sharedItemId = base.offer.inventory_items[0].id
+
+ const pack = (
+ await api.post(
+ `/vendor/offers`,
+ {
+ sku: `${name}-PACK-${Date.now()}`,
+ variant_id: base.product.variants[0].id,
+ shipping_profile_id: base.shippingProfile.id,
+ inventory_items: [
+ {
+ title: `${name} pack placeholder`,
+ required_quantity: 1,
+ stock_levels: [
+ {
+ location_id: base.stockLocation.id,
+ stocked_quantity: 0,
+ },
+ ],
+ },
+ ],
+ prices: [{ amount: 1200, currency_code: "usd" }],
+ },
+ base.headers
+ )
+ ).data.offer
+
+ await api.post(
+ `/vendor/offers/${pack.id}/inventory-items/batch`,
+ {
+ create: [
+ { inventory_item_id: sharedItemId, required_quantity: 12 },
+ ],
+ delete: [pack.inventory_items[0].id],
+ },
+ base.headers
+ )
+
+ return { unit: base.offer, pack }
}
const createCart = async () => {
@@ -256,6 +312,90 @@ medusaIntegrationTestRunner({
expect(res.status).toEqual(200)
})
+ it("rejects an add that pushes the merged line past stock", async () => {
+ const { offer } = await seedSellerOffer({
+ email: "[email protected]",
+ name: "Merged",
+ offerPrice: 1200,
+ inventory_items: [{ stocked: 100, required_quantity: 12 }],
+ })
+
+ const cart = await createCart()
+ const first = await addLine(cart.id, offer.id, 2)
+ expect(first.status).toEqual(200)
+
+ const second = await addLine(cart.id, offer.id, 7)
+ expect(second.status).toBeGreaterThanOrEqual(400)
+ expect(second.status).toBeLessThan(500)
+
+ const fits = await addLine(cart.id, offer.id, 6)
+ expect(fits.status).toEqual(200)
+ expect(fits.data.cart.items[0].quantity).toEqual(8)
+ })
+
+ it("counts other offers drawing on the same inventory item when adding", async () => {
+ const { unit, pack } = await seedSharedItemOffers("SharedAdd")
+
+ const cart = await createCart()
+ expect((await addLine(cart.id, unit.id, 90)).status).toEqual(200)
+
+ const res = await addLine(cart.id, pack.id, 1)
+ expect(res.status).toBeGreaterThanOrEqual(400)
+ expect(res.status).toBeLessThan(500)
+ })
+
+ it("sums items sharing an inventory item within a single add", async () => {
+ const { unit, pack } = await seedSharedItemOffers("SharedBatch")
+
+ const cart = await createCart()
+ const { errors } = await addToCartWorkflow(appContainer).run({
+ input: {
+ cart_id: cart.id,
+ items: [
+ {
+ variant_id: unit.variant_id,
+ quantity: 60,
+ offer_id: unit.id,
+ metadata: { offer_id: unit.id },
+ },
+ {
+ variant_id: pack.variant_id,
+ quantity: 4,
+ offer_id: pack.id,
+ metadata: { offer_id: pack.id },
+ },
+ ],
+ },
+ throwOnError: false,
+ })
+
+ expect(errors.length).toBeGreaterThan(0)
+ })
+
+ it("counts other offers drawing on the same inventory item when updating", async () => {
+ const { unit, pack } = await seedSharedItemOffers("SharedUpdate")
+
+ const cart = await createCart()
+ expect((await addLine(cart.id, unit.id, 80)).status).toEqual(200)
+ const added = await addLine(cart.id, pack.id, 1)
+ expect(added.status).toEqual(200)
+
+ const packLine = added.data.cart.items.find(
+ (i: { metadata?: { offer_id?: string } }) =>
+ i.metadata?.offer_id === pack.id
+ )
+ const res = await api
+ .post(
+ `/store/carts/${cart.id}/line-items/${packLine.id}`,
+ { quantity: 2 },
+ storeHeaders
+ )
+ .catch((e) => e.response)
+
+ expect(res.status).toBeGreaterThanOrEqual(400)
+ expect(res.status).toBeLessThan(500)
+ })
+
it("persists and returns the offer inventory flags", async () => {
const { offer, headers } = await seedSellerOffer({
diff --git a/packages/core/src/workflows/cart/hooks/validate.ts b/packages/core/src/workflows/cart/hooks/validate.ts
index 343ca990a..d0d912520 100644
--- a/packages/core/src/workflows/cart/hooks/validate.ts
+++ b/packages/core/src/workflows/cart/hooks/validate.ts
@@ -1,3 +1,4 @@
+import { BigNumberInput, MedusaContainer } from "@medusajs/framework/types"
import {
ContainerRegistrationKeys,
MathBN,
@@ -10,31 +11,60 @@ import {
updateLineItemInCartWorkflow,
} from "@medusajs/medusa/core-flows"
import {
+ OfferInventoryShape,
prepareOfferInventoryInput,
requiredOfferFieldsForInventoryConfirmation,
} from "../../offer/utils"
-addToCartWorkflow.hooks.validate(async ({ input, cart }, { container }) => {
- const items = input.items ?? []
- if (!items.length) {
- return
- }
+type OfferDemandLine = {
+ id: string
+ quantity: BigNumberInput
+ offer_id: string
+}
+const resolveCartOfferLines = async (
+ container: MedusaContainer,
+ cartId: string,
+): Promise<OfferDemandLine[]> => {
const query = container.resolve(ContainerRegistrationKeys.QUERY)
- const inventoryService = container.resolve(Modules.INVENTORY)
+ const { data } = await query.graph({
+ entity: "cart",
+ fields: ["items.id", "items.quantity", "items.offer.id"],
+ filters: { id: cartId },
+ })
- const offerIds = Array.from(
- new Set(
- items
- .map((i) => i.offer_id)
- .filter((v): v is string => typeof v === "string" && v.length > 0),
- ),
- )
+ const items = (data[0]?.items ?? []) as Array<{
+ id: string
+ quantity: BigNumberInput
+ offer?: { id?: string } | null
+ } | null>
- if (!offerIds.length) {
- return
- }
+ return items.flatMap((item) =>
+ item?.offer?.id
+ ? [{ id: item.id, quantity: item.quantity, offer_id: item.offer.id }]
+ : [],
+ )
+}
+
+// Several lines can draw on one inventory item: the same offer added again
+// before Medusa merges it, or different offers sharing an item through
+// inventory kits. Stock is confirmed against the cart's total demand per item,
+// not line by line.
+const hasCartOfferInventoryCoverage = async ({
+ container,
+ salesChannelId,
+ lines,
+ checkedLineIds,
+}: {
+ container: MedusaContainer
+ salesChannelId?: string
+ lines: OfferDemandLine[]
+ checkedLineIds: Set<string>
+}): Promise<boolean> => {
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const inventoryService = container.resolve(Modules.INVENTORY)
+ const offerIds = Array.from(new Set(lines.map((l) => l.offer_id)))
const { data: offers } = await query.graph({
entity: "offer",
fields: requiredOfferFieldsForInventoryConfirmation,
@@ -42,39 +72,99 @@ addToCartWorkflow.hooks.validate(async ({ input, cart }, { container }) => {
})
const foundIds = new Set(offers.map((o: { id: string }) => o.id))
- const missing = offerIds.find((id) => !foundIds.has(id))
+ const missing = lines.find(
+ (l) => checkedLineIds.has(l.id) && !foundIds.has(l.offer_id),
+ )
if (missing) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
- `Offer ${missing} not found`,
+ `Offer ${missing.offer_id} not found`,
)
}
- const { items: confirmInputs } = prepareOfferInventoryInput({
+ const { items: entries } = prepareOfferInventoryInput({
input: {
- sales_channel_id: cart.sales_channel_id ?? undefined,
- items: items.map((i) => ({
- id: undefined,
- quantity: i.quantity,
- offer: { id: i.offer_id },
- })),
- offers: offers as never,
+ sales_channel_id: salesChannelId,
+ items: lines
+ .filter((l) => foundIds.has(l.offer_id))
+ .map((l) => ({
+ id: l.id,
+ quantity: l.quantity,
+ offer: { id: l.offer_id },
+ })),
+ offers: offers as OfferInventoryShape[],
},
})
+ const demandByItem = new Map<
+ string,
+ { units: BigNumberInput; locationIds: Set<string>; checked: boolean }
+ >()
+
+ for (const entry of entries) {
+ if (!entry.manage_inventory) {
+ continue
+ }
+
+ const demand = demandByItem.get(entry.inventory_item_id) ?? {
+ units: 0,
+ locationIds: new Set<string>(),
+ checked: false,
+ }
+ demand.units = MathBN.add(
+ demand.units,
+ MathBN.mult(entry.required_quantity, entry.quantity),
+ )
+ if (
+ entry.id &&
+ checkedLineIds.has(entry.id) &&
+ !entry.allow_backorder
+ ) {
+ demand.checked = true
+ entry.location_ids.forEach((id) => demand.locationIds.add(id))
+ }
+ demandByItem.set(entry.inventory_item_id, demand)
+ }
+
const coverage = await promiseAll(
- confirmInputs
- .filter((entry) => entry.manage_inventory && !entry.allow_backorder)
- .map((entry) =>
+ Array.from(demandByItem.entries())
+ .filter(([, demand]) => demand.checked)
+ .map(([inventoryItemId, demand]) =>
inventoryService.confirmInventory(
- entry.inventory_item_id,
- entry.location_ids,
- MathBN.mult(entry.required_quantity, entry.quantity),
+ inventoryItemId,
+ Array.from(demand.locationIds),
+ demand.units,
),
),
)
- if (coverage.some((hasCoverage) => !hasCoverage)) {
+ return coverage.every(Boolean)
+}
+
+addToCartWorkflow.hooks.validate(async ({ input, cart }, { container }) => {
+ const incoming = (input.items ?? []).filter(
+ (i): i is typeof i & { offer_id: string } =>
+ typeof i.offer_id === "string" && i.offer_id.length > 0,
+ )
+ if (!incoming.length) {
+ return
+ }
+
+ const incomingLines = incoming.map((i, index) => ({
+ id: `incoming_${index}`,
+ quantity: i.quantity,
+ offer_id: i.offer_id,
+ }))
+ const existingLines = await resolveCartOfferLines(container, cart.id)
+
+ const covered = await hasCartOfferInventoryCoverage({
+ container,
+ salesChannelId: cart.sales_channel_id ?? undefined,
+ lines: [...existingLines, ...incomingLines],
+ checkedLineIds: new Set(incomingLines.map((l) => l.id)),
+ })
+
+ if (!covered) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Some inventory item linked to an offer does not have sufficient stock",
@@ -93,60 +183,23 @@ updateLineItemInCartWorkflow.hooks.validate(
return
}
- const line = (cart.items ?? []).find(
- (i: { id: string }) => i.id === input.item_id,
+ const lines = (
+ await resolveCartOfferLines(container, cart.id)
+ ).map((l) =>
+ l.id === input.item_id ? { ...l, quantity: newQuantity } : l,
)
- if (!line) {
+ if (!lines.some((l) => l.id === input.item_id)) {
return
}
- const query = container.resolve(ContainerRegistrationKeys.QUERY)
- const inventoryService = container.resolve(Modules.INVENTORY)
-
- const { data: cartLines } = await query.graph({
- entity: "line_item",
- fields: ["id", "offer.id"],
- filters: { id: [input.item_id] },
+ const covered = await hasCartOfferInventoryCoverage({
+ container,
+ salesChannelId: cart.sales_channel_id ?? undefined,
+ lines,
+ checkedLineIds: new Set([input.item_id]),
})
- const offerId = (cartLines[0] as { offer?: { id?: string } } | undefined)
- ?.offer?.id
- if (!offerId) {
- return
- }
-
- const { data: offers } = await query.graph({
- entity: "offer",
- fields: requiredOfferFieldsForInventoryConfirmation,
- filters: { id: [offerId] },
- })
-
- const { items: confirmInputs } = prepareOfferInventoryInput({
- input: {
- sales_channel_id: cart.sales_channel_id ?? undefined,
- items: [
- {
- id: input.item_id,
- quantity: newQuantity,
- offer: { id: offerId },
- },
- ],
- offers: offers as never,
- },
- })
-
- const coverage = await promiseAll(
- confirmInputs
- .filter((entry) => entry.manage_inventory && !entry.allow_backorder)
- .map((entry) =>
- inventoryService.confirmInventory(
- entry.inventory_item_id,
- entry.location_ids,
- MathBN.mult(entry.required_quantity, entry.quantity),
- ),
- ),
- )
- if (coverage.some((hasCoverage) => !hasCoverage)) {
+ if (!covered) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Cannot increase quantity: an inventory item linked to the offer is out of stock",