The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
fix(offer): attribute created offer prices to offers by rule, not position (#1397)
Viktor Holik8758c2e5f188
diff --git a/integration-tests/http/offer/vendor/create-offers-price-links.spec.ts b/integration-tests/http/offer/vendor/create-offers-price-links.spec.tsnew file mode 100644index 000000000..185028f3e--- /dev/null+++ b/integration-tests/http/offer/vendor/create-offers-price-links.spec.ts@@ -0,0 +1,128 @@+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import { MedusaContainer } from "@medusajs/framework/types"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"+import { createOffersWorkflow } from "@mercurjs/core/workflows"+import { createSellerUser } from "../../../helpers/create-seller-user"+import { createVendorProduct } from "../../../helpers/create-product"++jest.setTimeout(120000)++medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api }) => {+ describe("createOffersWorkflow - offer price links", () => {+ let appContainer: MedusaContainer++ beforeAll(() => {+ appContainer = getContainer()+ })++ // Regression: with many offers in a single call, several offers+ // land prices in the same variant price set. The offer↔price links+ // must be attributed by the `offer_id` price rule, not by the order+ // prices come back from the pricing module.+ it("links every price to the offer that owns it", async () => {+ const tag = `t${Date.now()}`+ const { seller, member, headers } = await createSellerUser(+ appContainer,+ { email: `links-${tag}@test.com`, name: "Links Seller" }+ )++ const stockLocation = (+ await api.post(+ `/vendor/stock-locations`,+ { name: `WH ${tag}` },+ headers+ )+ ).data.stock_location++ const shippingProfile = (+ await api.post(+ `/vendor/shipping-profiles`,+ { name: `Profile ${tag}`, type: "default" },+ headers+ )+ ).data.shipping_profile++ const VARIANT_COUNT = 10+ const OFFERS_PER_VARIANT = 3++ const product = await createVendorProduct(api, headers, {+ title: `Links Product ${tag}`,+ variants: Array.from(+ { length: VARIANT_COUNT },+ (_, v) => ({ title: `V${v} ${tag}` })+ ),+ })++ const offersInput = product.variants.flatMap((variant, v) =>+ Array.from({ length: OFFERS_PER_VARIANT }, (_, o) => ({+ seller_id: seller.id,+ created_by: member.id,+ variant_id: variant.id,+ shipping_profile_id: shippingProfile.id,+ sku: `S-${v}-${o}-${tag}`,+ inventory_items: [+ {+ sku: `S-${v}-${o}-${tag}`,+ stock_levels: [+ {+ location_id: stockLocation.id,+ stocked_quantity: 100,+ },+ ],+ },+ ],+ prices: [+ {+ amount: (v + 1) * 100 + o,+ currency_code: "usd",+ },+ ],+ }))+ )++ const { result: created } = await createOffersWorkflow(+ appContainer+ ).run({ input: { offers: offersInput } })++ expect(created).toHaveLength(VARIANT_COUNT * OFFERS_PER_VARIANT)++ const query = appContainer.resolve(+ ContainerRegistrationKeys.QUERY+ )++ const { data: offers } = await query.graph({+ entity: "offer",+ fields: [+ "id",+ "prices.id",+ "prices.price_rules.attribute",+ "prices.price_rules.value",+ ],+ filters: { id: created.map((o) => o.id) },+ })++ for (const offer of offers) {+ const prices = (offer.prices ?? []) as Array<{+ id: string+ price_rules?: Array<{+ attribute: string+ value: string+ }>+ }>++ // Each offer must own exactly its own price, and that+ // price's offer_id rule must point back at the offer.+ expect(prices).toHaveLength(1)++ for (const price of prices) {+ const offerRule = (price.price_rules ?? []).find(+ (r) => r.attribute === "offer_id"+ )+ expect(offerRule?.value).toBe(offer.id)+ }+ }+ })+ })+ },+})diff --git a/packages/core/src/workflows/offer/steps/add-offer-prices.ts b/packages/core/src/workflows/offer/steps/add-offer-prices.tsindex a74cf8830..20a047256 100644--- a/packages/core/src/workflows/offer/steps/add-offer-prices.ts+++ b/packages/core/src/workflows/offer/steps/add-offer-prices.ts@@ -5,8 +5,8 @@ import type { AddPricesDTO } from "@medusajs/framework/types"export type AddOfferPricesStepInput = AddPricesDTO[]export type AddOfferPricesStepOutput = Array<{- priceSetId: string- prices: Array<{ id: string }>+ offer_id: string+ price_ids: string[]}>export const addOfferPricesStepId = "add-offer-prices"@@ -20,9 +20,7 @@ export const addOfferPricesStep = createStep(const pricingModule = container.resolve(Modules.PRICING)- const uniquePriceSetIds = Array.from(- new Set(data.map((d) => d.priceSetId)),- )+ const uniquePriceSetIds = Array.from(new Set(data.map((d) => d.priceSetId)))const existingSets = await pricingModule.listPriceSets({ id: uniquePriceSetIds },@@ -37,35 +35,49 @@ export const addOfferPricesStep = createStep(const updatedSets = await pricingModule.addPrices(data)- const newPricesBySet = new Map<string, string[]>()+ const newPriceIds: string[] = []for (const updated of updatedSets) {const before = existingIdsBySet.get(updated.id) ?? new Set<string>()- const newPrices = (updated.prices ?? [])- .map((p) => p.id)- .filter((id) => !before.has(id))- newPricesBySet.set(updated.id, newPrices)+ for (const price of updated.prices ?? []) {+ if (!before.has(price.id)) {+ newPriceIds.push(price.id)+ }+ }}- const queueBySet = new Map<string, string[]>()- for (const [setId, ids] of newPricesBySet) {- queueBySet.set(setId, [...ids])- }+ // Attribute each new price to its offer through the `offer_id` price rule+ // written in the payload, not by position: a single price set can receive+ // prices from several offers in one call, and the order `addPrices` returns+ // them in is not guaranteed to match the input order.+ const createdPrices = newPriceIds.length+ ? await pricingModule.listPrices(+ { id: newPriceIds },+ { relations: ["price_rules"] },+ )+ : []- const output: AddOfferPricesStepOutput = data.map((entry) => {- const queue = queueBySet.get(entry.priceSetId) ?? []- const consumed = queue.splice(0, entry.prices.length)- queueBySet.set(entry.priceSetId, queue)- return {- priceSetId: entry.priceSetId,- prices: consumed.map((id) => ({ id })),+ const priceIdsByOffer = new Map<string, string[]>()+ for (const price of createdPrices) {+ const rules =+ (+ price as {+ price_rules?: Array<{ attribute: string; value: string }>+ }+ ).price_rules ?? []+ const offerId = rules.find((r) => r.attribute === "offer_id")?.value+ if (!offerId) {+ continue}- })+ const bucket = priceIdsByOffer.get(offerId) ?? []+ bucket.push(price.id)+ priceIdsByOffer.set(offerId, bucket)+ }- const createdPriceIds = output.flatMap((entry) =>- entry.prices.map((p) => p.id),- )+ const output: AddOfferPricesStepOutput = Array.from(+ priceIdsByOffer.entries(),+ ).map(([offer_id, price_ids]) => ({ offer_id, price_ids }))- return new StepResponse(output, createdPriceIds)+ return new StepResponse(output, newPriceIds)},async (createdPriceIds, { container }) => {if (!createdPriceIds?.length) {diff --git a/packages/core/src/workflows/offer/workflows/create-offers.ts b/packages/core/src/workflows/offer/workflows/create-offers.tsindex af436aaa2..dbb8a7afb 100644--- a/packages/core/src/workflows/offer/workflows/create-offers.ts+++ b/packages/core/src/workflows/offer/workflows/create-offers.ts@@ -296,25 +296,17 @@ export const createOffersWorkflow: ReturnWorkflow<const addedPrices = addOfferPricesStep(addPricesInput)const offerPriceLinks = transform(- { input, offers, addedPrices },- ({ input, offers, addedPrices }) => {+ { addedPrices },+ ({ addedPrices }) => {const links: LinkDefinition[] = []- let cursor = 0- input.offers.forEach((offer, idx) => {- if (!offer.prices?.length) {- return- }- const entry = addedPrices[cursor++]- if (!entry) {- return- }- for (const price of entry.prices) {+ for (const entry of addedPrices) {+ for (const priceId of entry.price_ids) {links.push({- [MercurModules.OFFER]: { offer_id: offers[idx].id },- [Modules.PRICING]: { price_id: price.id },+ [MercurModules.OFFER]: { offer_id: entry.offer_id },+ [Modules.PRICING]: { price_id: priceId },})}- })+ }return links},)