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(offers): preserve existing variant prices and prevent dangling reference (#1550)

Ashish Bansalc84975835b9e
diff --git a/integration-tests/http/offer/vendor/update-offers-dangling-price-link.spec.ts b/integration-tests/http/offer/vendor/update-offers-dangling-price-link.spec.ts
index 19970dc13..ec040448d 100644
--- a/integration-tests/http/offer/vendor/update-offers-dangling-price-link.spec.ts
+++ b/integration-tests/http/offer/vendor/update-offers-dangling-price-link.spec.ts
@@ -80,6 +80,59 @@ medusaIntegrationTestRunner({
return result[0]
}
+ const seedOfferForVariant = async (
+ tag: string,
+ variantId: string,
+ prices: Array<{ amount: number; currency_code: string }>
+ ) => {
+ const { seller, member, headers } = await createSellerUser(
+ appContainer,
+ { email: `shared-${tag}@test.com`, name: `Seller ${tag}` }
+ )
+
+ const stockLocation = (
+ await api.post(
+ `/vendor/stock-locations`,
+ { name: `WH ${tag}` },
+ headers
+ )
+ ).data.stock_location
+
+ const shippingProfile = await createShippingProfile(appContainer, {
+ name: `Profile ${tag}`,
+ })
+
+ const { result } = await createOffersWorkflow(
+ appContainer
+ ).run({
+ input: {
+ offers: [
+ {
+ seller_id: seller.id,
+ created_by: member.id,
+ variant_id: variantId,
+ shipping_profile_id: shippingProfile.id,
+ sku: `SKU-${tag}`,
+ inventory_items: [
+ {
+ sku: `SKU-${tag}`,
+ stock_levels: [
+ {
+ location_id: stockLocation.id,
+ stocked_quantity: 100,
+ },
+ ],
+ },
+ ],
+ prices,
+ },
+ ],
+ },
+ })
+
+ return result[0]
+ }
+
const listPrices = async (offerId: string) => {
const query = appContainer.resolve(
ContainerRegistrationKeys.QUERY
@@ -206,6 +259,68 @@ medusaIntegrationTestRunner({
after.map((p) => p.amount).sort((a, b) => a - b)
).toEqual([900, 1100])
})
+
+ it("preserves another seller's prices on the same variant when seller 1 updates their offer prices", async () => {
+ const tag = `shared${Date.now()}`
+ const offer1 = await seedOffer(`${tag}-1`, [
+ { amount: 1000, currency_code: "usd" },
+ ])
+
+ const query = appContainer.resolve(
+ ContainerRegistrationKeys.QUERY
+ )
+ const { data } = await query.graph({
+ entity: "offer",
+ fields: ["variant_id"],
+ filters: { id: offer1.id },
+ })
+ const variantId = data[0].variant_id
+
+ const offer2 = await seedOfferForVariant(
+ `${tag}-2`,
+ variantId,
+ [
+ { amount: 2000, currency_code: "usd" },
+ { amount: 1800, currency_code: "eur" },
+ ]
+ )
+
+ // Verify both offers have their prices initially
+ const prices1Before = await listPrices(offer1.id)
+ const prices2Before = await listPrices(offer2.id)
+ expect(prices1Before).toHaveLength(1)
+ expect(prices1Before[0].amount).toBe(1000)
+ expect(prices2Before).toHaveLength(2)
+
+ // Seller 1 updates their offer price
+ await updateOffersWorkflow(appContainer).run({
+ input: {
+ offers: [
+ {
+ id: offer1.id,
+ prices: [
+ {
+ amount: 1500,
+ currency_code: "usd",
+ },
+ ],
+ },
+ ],
+ },
+ })
+
+ // Verify Seller 1's price is updated
+ const prices1After = await listPrices(offer1.id)
+ expect(prices1After).toHaveLength(1)
+ expect(prices1After[0].amount).toBe(1500)
+
+ // CRITICAL: Verify Seller 2's prices on the same variant were NOT wiped
+ const prices2After = await listPrices(offer2.id)
+ expect(prices2After).toHaveLength(2)
+ expect(
+ prices2After.map((p) => p.amount).sort((a, b) => a - b)
+ ).toEqual([1800, 2000])
+ })
})
},
})
diff --git a/packages/admin/src/pages/offers/[id]/_components/offer-pricing-section.tsx b/packages/admin/src/pages/offers/[id]/_components/offer-pricing-section.tsx
index fe350ab88..528634ada 100644
--- a/packages/admin/src/pages/offers/[id]/_components/offer-pricing-section.tsx
+++ b/packages/admin/src/pages/offers/[id]/_components/offer-pricing-section.tsx
@@ -11,6 +11,7 @@ type Props = { offer: OfferDetail }
const PAGE_STEP = 3
const isBaseRow = (price: OfferPrice) => {
+ if (!price) return false
const rules = price.price_rules ?? []
const extraRules = rules.filter((r) => r.attribute !== "offer_id")
return extraRules.length === 0
@@ -20,7 +21,7 @@ export const OfferPricingSection = ({ offer }: Props) => {
const { t } = useTranslation()
const prices = (offer.prices ?? [])
- .filter(isBaseRow)
+ .filter((p): p is OfferPrice => Boolean(p) && isBaseRow(p))
.sort((a, b) =>
(a.currency_code ?? "").localeCompare(b.currency_code ?? ""),
)
diff --git a/packages/core/src/workflows/offer/workflows/index.ts b/packages/core/src/workflows/offer/workflows/index.ts
index d7c25fc82..30079f739 100644
--- a/packages/core/src/workflows/offer/workflows/index.ts
+++ b/packages/core/src/workflows/offer/workflows/index.ts
@@ -1,4 +1,5 @@
export * from "./create-offers"
export * from "./update-offers"
+export * from "./upsert-offer-prices"
export * from "./delete-offers"
export * from "./batch-offer-inventory-items"
diff --git a/packages/core/src/workflows/offer/workflows/update-offers.ts b/packages/core/src/workflows/offer/workflows/update-offers.ts
index 9bf9e4af2..526522c0b 100644
--- a/packages/core/src/workflows/offer/workflows/update-offers.ts
+++ b/packages/core/src/workflows/offer/workflows/update-offers.ts
@@ -2,27 +2,17 @@ import {
createHook,
createWorkflow,
transform,
+ when,
WorkflowResponse,
type Hook,
type ReturnWorkflow,
} from "@medusajs/framework/workflows-sdk"
-import {
- AdditionalData,
- LinkDefinition,
- PricingTypes,
-} from "@medusajs/framework/types"
-import {
- createRemoteLinkStep,
- dismissRemoteLinkStep,
- emitEventStep,
- updatePriceSetsStep,
- useQueryGraphStep,
-} from "@medusajs/medusa/core-flows"
-import { MedusaError, Modules } from "@medusajs/framework/utils"
-import { UpdateOfferDTO, MercurModules, OfferDTO } from "@mercurjs/types"
+import { AdditionalData } from "@medusajs/framework/types"
+import { emitEventStep } from "@medusajs/medusa/core-flows"
+import { UpdateOfferDTO, OfferDTO } from "@mercurjs/types"
-import { removeOfferPricesStep, updateOffersStep } from "../steps"
-import { assertOfferPriceOwnership } from "../utils"
+import { updateOffersStep } from "../steps"
+import { upsertOfferPricesWorkflow } from "./upsert-offer-prices"
import { OfferWorkflowEvents } from "../../events"
export type UpdateOffersWorkflowInput = {
@@ -66,209 +56,18 @@ export const updateOffersWorkflow: ReturnWorkflow<
const offers = updateOffersStep(rowUpdates)
- const offersWithPriceUpdates = transform({ input }, ({ input }) =>
- input.offers
+ const offerPrices = transform({ input }, ({ input }) => ({
+ offers: input.offers
.filter((o) => Array.isArray(o.prices))
- .map((o) => o.id),
- )
-
- const { data: offerRows } = useQueryGraphStep({
- entity: "offer",
- fields: [
- "id",
- "variant_id",
- "product_variant.price_set.id",
- "prices.id",
- "prices.amount",
- "prices.currency_code",
- "prices.min_quantity",
- "prices.max_quantity",
- "prices.price_rules.attribute",
- "prices.price_rules.value",
- ],
- filters: { id: offersWithPriceUpdates },
- }).config({ name: "get-offer-prices" })
-
- const pricingDiff = transform(
- { input, offerRows },
- ({ input, offerRows }) => {
- const offerById = new Map(
- (offerRows as Array<{
- id: string
- variant_id: string
- product_variant?: {
- price_set?: { id?: string } | null
- } | null
- prices?: Array<{ id: string } | null> | null
- }>).map((o) => [o.id, o]),
- )
-
- const priceSetUpserts: PricingTypes.UpsertPriceSetDTO[] = []
- const toRemoveIds: string[] = []
- const newPriceOwners: Array<{
- offer_id: string
- priceSetId: string
- newRowCount: number
- }> = []
- const removedLinks: LinkDefinition[] = []
-
- for (const offer of input.offers) {
- if (!Array.isArray(offer.prices)) {
- continue
- }
- const loaded = offerById.get(offer.id)
- if (!loaded) {
- throw new MedusaError(
- MedusaError.Types.NOT_FOUND,
- `Offer ${offer.id} was not found`,
- )
- }
- const priceSetId = loaded.product_variant?.price_set?.id
- if (!priceSetId) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- `Variant ${loaded.variant_id} has no PriceSet`,
- )
- }
-
- // `prices` comes through the offer <-> price link, so a link row
- // whose price no longer resolves yields a null element. Such a
- // dangling link takes no part in the diff.
- const ownedIds = new Set(
- (loaded.prices ?? [])
- .filter((p): p is { id: string } => !!p?.id)
- .map((p) => p.id),
- )
- const incomingIds = offer.prices
- .map((p) => p.id)
- .filter((id): id is string => !!id)
-
- assertOfferPriceOwnership({
- offer_id: offer.id,
- price_ids: incomingIds,
- owned_price_ids: ownedIds,
- })
-
- const keepIds = new Set(incomingIds)
- for (const ownedId of ownedIds) {
- if (!keepIds.has(ownedId)) {
- toRemoveIds.push(ownedId)
- removedLinks.push({
- [MercurModules.OFFER]: { offer_id: offer.id },
- [Modules.PRICING]: { price_id: ownedId },
- })
- }
- }
-
- const upsertPrices: Array<
- PricingTypes.CreatePricesDTO & { id?: string }
- > = offer.prices.map((p) => {
- const base: PricingTypes.CreatePricesDTO & { id?: string } = {
- amount: p.amount,
- currency_code: p.currency_code,
- rules: { ...(p.rules ?? {}), offer_id: offer.id },
- }
- if (p.id) {
- base.id = p.id
- }
- if (p.min_quantity !== undefined && p.min_quantity !== null) {
- base.min_quantity = p.min_quantity
- }
- if (p.max_quantity !== undefined && p.max_quantity !== null) {
- base.max_quantity = p.max_quantity
- }
- return base
- })
-
- const newRowCount = offer.prices.filter((p) => !p.id).length
-
- priceSetUpserts.push({
- id: priceSetId,
- prices: upsertPrices,
- })
-
- if (newRowCount > 0) {
- newPriceOwners.push({
- offer_id: offer.id,
- priceSetId,
- newRowCount,
- })
- }
- }
-
- return {
- price_sets: priceSetUpserts,
- toRemoveIds,
- newPriceOwners,
- removedLinks,
- }
- },
- )
-
- const priceSetsPayload = transform(
- { pricingDiff },
- ({ pricingDiff }) => ({ price_sets: pricingDiff.price_sets }),
- )
+ .map((o) => ({ id: o.id, prices: o.prices ?? [] })),
+ }))
- const upsertedPriceSets = updatePriceSetsStep(priceSetsPayload)
-
- const toRemoveIds = transform(
- { pricingDiff },
- ({ pricingDiff }) => pricingDiff.toRemoveIds,
- )
-
- const removedLinks = transform(
- { pricingDiff },
- ({ pricingDiff }) => pricingDiff.removedLinks,
- )
- // Dismiss the links before deleting the prices: a failure between the two
- // then leaves an orphaned price rather than a dangling link, which would
- // make the offer permanently unupdatable.
- dismissRemoteLinkStep(removedLinks).config({
- name: "dismiss-removed-offer-price-links",
- })
-
- removeOfferPricesStep(toRemoveIds)
-
- const newLinks = transform(
- { pricingDiff, upsertedPriceSets },
- ({ pricingDiff, upsertedPriceSets }) => {
- if (!pricingDiff.newPriceOwners.length) {
- return [] as LinkDefinition[]
- }
- const priceSetById = new Map(
- (upsertedPriceSets ?? []).map((ps) => [ps.id, ps]),
- )
- const links: LinkDefinition[] = []
-
- for (const owner of pricingDiff.newPriceOwners) {
- const set = priceSetById.get(owner.priceSetId)
- if (!set) continue
- const matchingPrices = (set.prices ?? []).filter((price) => {
- const rules = (price as { price_rules?: Array<{
- attribute: string
- value: string
- }> }).price_rules ?? []
- return rules.some(
- (r) => r.attribute === "offer_id" && r.value === owner.offer_id,
- )
- })
-
- for (const price of matchingPrices) {
- links.push({
- [MercurModules.OFFER]: { offer_id: owner.offer_id },
- [Modules.PRICING]: { price_id: price.id },
- })
- }
- }
- return links
+ when({ offerPrices }, ({ offerPrices }) => offerPrices.offers.length > 0).then(
+ () => {
+ upsertOfferPricesWorkflow.runAsStep({ input: offerPrices })
},
)
- createRemoteLinkStep(newLinks).config({
- name: "create-new-offer-price-links",
- })
-
const eventData = transform({ offers }, ({ offers }) =>
offers.map((o) => ({ id: o.id, product_id: o.product_id })),
)
diff --git a/packages/core/src/workflows/offer/workflows/upsert-offer-prices.ts b/packages/core/src/workflows/offer/workflows/upsert-offer-prices.ts
new file mode 100644
index 000000000..6aeba4868
--- /dev/null
+++ b/packages/core/src/workflows/offer/workflows/upsert-offer-prices.ts
@@ -0,0 +1,207 @@
+import {
+ createWorkflow,
+ transform,
+ WorkflowData,
+ WorkflowResponse,
+} from "@medusajs/framework/workflows-sdk"
+import { LinkDefinition, PricingTypes } from "@medusajs/framework/types"
+import {
+ createRemoteLinkStep,
+ dismissRemoteLinkStep,
+ useQueryGraphStep,
+} from "@medusajs/medusa/core-flows"
+import { MedusaError, Modules } from "@medusajs/framework/utils"
+import { MercurModules, UpsertOfferPriceDTO } from "@mercurjs/types"
+
+import {
+ addOfferPricesStep,
+ removeOfferPricesStep,
+ type AddOfferPricesStepInput,
+} from "../steps"
+import { assertOfferPriceOwnership } from "../utils"
+
+export type UpsertOfferPricesWorkflowInput = {
+ offers: {
+ id: string
+ prices: UpsertOfferPriceDTO[]
+ }[]
+}
+
+export const upsertOfferPricesWorkflowId = "upsert-offer-prices"
+
+/**
+ * Replaces each offer's own prices. Offers on the same variant share its
+ * PriceSet, so prices are upserted by id instead of rewriting the set, which
+ * would drop the prices of every other offer on the variant.
+ */
+export const upsertOfferPricesWorkflow = createWorkflow(
+ upsertOfferPricesWorkflowId,
+ function (input: WorkflowData<UpsertOfferPricesWorkflowInput>) {
+ const offerIds = transform({ input }, ({ input }) =>
+ input.offers.map((o) => o.id),
+ )
+
+ const { data: offerRows } = useQueryGraphStep({
+ entity: "offer",
+ fields: [
+ "id",
+ "variant_id",
+ "product_variant.price_set.id",
+ "prices.id",
+ "prices.amount",
+ "prices.currency_code",
+ "prices.min_quantity",
+ "prices.max_quantity",
+ "prices.price_rules.attribute",
+ "prices.price_rules.value",
+ ],
+ filters: { id: offerIds },
+ }).config({ name: "get-offer-prices" })
+
+ const pricingDiff = transform(
+ { input, offerRows },
+ ({ input, offerRows }) => {
+ const offerById = new Map(
+ (offerRows as Array<{
+ id: string
+ variant_id: string
+ product_variant?: {
+ price_set?: { id?: string } | null
+ } | null
+ prices?: Array<{ id: string } | null> | null
+ }>).map((o) => [o.id, o]),
+ )
+
+ const addPricesPayload: AddOfferPricesStepInput = []
+ const toRemoveIds: string[] = []
+ const removedLinks: LinkDefinition[] = []
+
+ for (const offer of input.offers) {
+ const loaded = offerById.get(offer.id)
+ if (!loaded) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ `Offer ${offer.id} was not found`,
+ )
+ }
+ const priceSetId = loaded.product_variant?.price_set?.id
+ if (!priceSetId) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Variant ${loaded.variant_id} has no PriceSet`,
+ )
+ }
+
+ // `prices` comes through the offer <-> price link, so a link row
+ // whose price no longer resolves yields a null element. Such a
+ // dangling link takes no part in the diff.
+ const ownedIds = new Set(
+ (loaded.prices ?? [])
+ .filter((p): p is { id: string } => !!p?.id)
+ .map((p) => p.id),
+ )
+ const incomingIds = offer.prices
+ .map((p) => p.id)
+ .filter((id): id is string => !!id)
+
+ assertOfferPriceOwnership({
+ offer_id: offer.id,
+ price_ids: incomingIds,
+ owned_price_ids: ownedIds,
+ })
+
+ const keepIds = new Set(incomingIds)
+ for (const ownedId of ownedIds) {
+ if (!keepIds.has(ownedId)) {
+ toRemoveIds.push(ownedId)
+ removedLinks.push({
+ [MercurModules.OFFER]: { offer_id: offer.id },
+ [Modules.PRICING]: { price_id: ownedId },
+ })
+ }
+ }
+
+ const upsertPrices: Array<
+ PricingTypes.CreatePricesDTO & { id?: string }
+ > = offer.prices.map((p) => {
+ const base: PricingTypes.CreatePricesDTO & { id?: string } = {
+ amount: p.amount,
+ currency_code: p.currency_code,
+ rules: { ...(p.rules ?? {}), offer_id: offer.id },
+ }
+ if (p.id) {
+ base.id = p.id
+ }
+ if (p.min_quantity !== undefined && p.min_quantity !== null) {
+ base.min_quantity = p.min_quantity
+ }
+ if (p.max_quantity !== undefined && p.max_quantity !== null) {
+ base.max_quantity = p.max_quantity
+ }
+ return base
+ })
+
+ if (upsertPrices.length) {
+ addPricesPayload.push({
+ priceSetId,
+ prices: upsertPrices,
+ })
+ }
+ }
+
+ return {
+ addPricesPayload,
+ toRemoveIds,
+ removedLinks,
+ }
+ },
+ )
+
+ const toRemoveIds = transform(
+ { pricingDiff },
+ ({ pricingDiff }) => pricingDiff.toRemoveIds,
+ )
+
+ const removedLinks = transform(
+ { pricingDiff },
+ ({ pricingDiff }) => pricingDiff.removedLinks,
+ )
+ // Dismiss the links before deleting the prices: a failure between the two
+ // then leaves an orphaned price rather than a dangling link, which would
+ // make the offer permanently unupdatable.
+ dismissRemoteLinkStep(removedLinks).config({
+ name: "dismiss-removed-offer-price-links",
+ })
+
+ removeOfferPricesStep(toRemoveIds)
+
+ const addPricesPayload = transform(
+ { pricingDiff },
+ ({ pricingDiff }) => pricingDiff.addPricesPayload,
+ )
+
+ const addedPrices = addOfferPricesStep(addPricesPayload)
+
+ const newLinks = transform(
+ { addedPrices },
+ ({ addedPrices }) => {
+ const links: LinkDefinition[] = []
+ for (const entry of addedPrices) {
+ for (const priceId of entry.price_ids) {
+ links.push({
+ [MercurModules.OFFER]: { offer_id: entry.offer_id },
+ [Modules.PRICING]: { price_id: priceId },
+ })
+ }
+ }
+ return links
+ },
+ )
+
+ createRemoteLinkStep(newLinks).config({
+ name: "create-new-offer-price-links",
+ })
+
+ return new WorkflowResponse(addedPrices)
+ },
+)
diff --git a/packages/types/src/offer/mutations.ts b/packages/types/src/offer/mutations.ts
index ae4e85f8a..4022fe11d 100644
--- a/packages/types/src/offer/mutations.ts
+++ b/packages/types/src/offer/mutations.ts
@@ -96,8 +96,8 @@ export interface CreateOfferRowDTO {
/**
* Input to `updateOffersWorkflow`. Each entry is keyed by `id`; setting the
- * `prices` field rewrites the offer's `PriceSet` with replace semantics,
- * omitting it leaves the price ladder untouched. Offer-row fields
+ * `prices` field replaces the offer's own prices (prices of other offers on
+ * the same variant are left alone); omitting it leaves them untouched. Offer-row fields
* (`sku`, `shipping_profile_id`, `metadata`) are partial.
*/
export interface UpdateOfferDTO {
diff --git a/packages/vendor/src/pages/offers/[id]/_components/offer-pricing-section.tsx b/packages/vendor/src/pages/offers/[id]/_components/offer-pricing-section.tsx
index 7036656a1..6004bc906 100644
--- a/packages/vendor/src/pages/offers/[id]/_components/offer-pricing-section.tsx
+++ b/packages/vendor/src/pages/offers/[id]/_components/offer-pricing-section.tsx
@@ -15,6 +15,7 @@ type Props = { offer: OfferDetail }
const PAGE_STEP = 3
const isBaseRow = (price: OfferPrice) => {
+ if (!price) return false
const rules = price.price_rules ?? []
const extraRules = rules.filter((r) => r.attribute !== "offer_id")
return extraRules.length === 0
@@ -24,7 +25,7 @@ export const OfferPricingSection = ({ offer }: Props) => {
const { t } = useTranslation()
const prices = (offer.prices ?? [])
- .filter(isBaseRow)
+ .filter((p): p is OfferPrice => Boolean(p) && isBaseRow(p))
.sort((a, b) => (a.currency_code ?? "").localeCompare(b.currency_code ?? ""))
const hasPrices = prices.length > 0
diff --git a/packages/vendor/src/pages/offers/[id]/pricing/pricing-form/pricing-form.tsx b/packages/vendor/src/pages/offers/[id]/pricing/pricing-form/pricing-form.tsx
index 7e1ead77e..374138efd 100644
--- a/packages/vendor/src/pages/offers/[id]/pricing/pricing-form/pricing-form.tsx
+++ b/packages/vendor/src/pages/offers/[id]/pricing/pricing-form/pricing-form.tsx
@@ -31,6 +31,7 @@ type Props = {
}
const isBaseRow = (price: OfferPrice) => {
+ if (!price) return false
const rules = price.price_rules ?? []
const extraRules = rules.filter((r) => r.attribute !== "offer_id")
return extraRules.length === 0
@@ -45,7 +46,7 @@ const buildDefaults = (
currency_prices: currencies.reduce<Record<string, number | "">>(
(acc, code) => {
const existing = offer.prices?.find(
- (p) => isBaseRow(p) && p.currency_code === code,
+ (p) => Boolean(p) && isBaseRow(p) && p.currency_code === code,
)
acc[code] = existing?.amount ?? ""
return acc
@@ -106,14 +107,21 @@ const PricingFormInner = ({
const handleSubmit = form.handleSubmit(async (values) => {
const row = values.prices[0]
- const submitted: { amount: number; currency_code: string }[] = []
+ const submitted: { id?: string; amount: number; currency_code: string }[] = []
for (const [currency_code, amount] of Object.entries(
row.currency_prices ?? {},
)) {
if (amount === "" || amount === undefined || amount === null) continue
const num = castNumber(amount)
if (!Number.isFinite(num)) continue
- submitted.push({ amount: num, currency_code })
+ const existing = offer.prices?.find(
+ (p) => Boolean(p) && isBaseRow(p) && p.currency_code === currency_code,
+ )
+ submitted.push({
+ ...(existing?.id ? { id: existing.id } : {}),
+ amount: num,
+ currency_code,
+ })
}
await mutateAsync(