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
feat(offer): extend offer workflow hooks (#1654)
Viktor Holik1cff7de5b85c
diff --git a/apps/docs/platform/offer/reference/workflows.mdx b/apps/docs/platform/offer/reference/workflows.mdxindex 8418a0ab4..b0bbdf81a 100644--- a/apps/docs/platform/offer/reference/workflows.mdx+++ b/apps/docs/platform/offer/reference/workflows.mdx@@ -12,7 +12,7 @@ This reference lists the workflows for the Offer domain. Import them from| Workflow | Input | Purpose || --- | --- | --- || `createOffersWorkflow` | `{ offers[], additional_data? }` | Create offers with prices, inventory, and links |-| `updateOffersWorkflow` | `{ offers[], additional_data? }` | Update offer rows and rewrite their price ladders |+| `updateOffersWorkflow` | `{ offers[], updated_by?, additional_data? }` | Update offer rows and rewrite their price ladders || `deleteOffersWorkflow` | `{ ids[], additional_data? }` | Delete offers || `batchOfferInventoryItemsWorkflow` | `{ offer_id, create?, update?, delete?, additional_data? }` | Add, update, and detach an offer's inventory-item links |@@ -24,9 +24,37 @@ Each workflow exposes hooks so you can extend it without forking:| --- | --- || `createOffersWorkflow` | `validate`, `offersCreated` || `updateOffersWorkflow` | `validate`, `offersUpdated` |+| `upsertOfferPricesWorkflow` | `offerPricesUpserted` || `deleteOffersWorkflow` | `offersDeleted` || `batchOfferInventoryItemsWorkflow` | `validate`, `offerInventoryItemsBatched` |+### Hook payloads++| Hook | Payload |+| --- | --- |+| `offersCreated` | `{ offers: OfferDTO[], additional_data? }` — each offer carries `created_by` and its `prices` |+| `offersUpdated` | `{ offers: OfferDTO[], previous_offers: OfferDTO[], updated_by?, additional_data? }` — `previous_offers` is the row state before the write |+| `offerPricesUpserted` | `{ offers: Array<{ offer_id, previous_prices: OfferPriceDTO[], prices: OfferPriceDTO[], created: string[], updated: string[], deleted: string[] }>, updated_by: string \| null }` |+| `offersDeleted` | `{ ids: string[], offers: OfferDTO[], additional_data? }` — `offers` is a snapshot taken before deletion, including `prices` |++`updated_by` is the authenticated actor id. Vendor routes fill it from the session; pass it yourself when running `updateOffersWorkflow` or `upsertOfferPricesWorkflow` directly.++In `offerPricesUpserted`, `previous_prices` and `prices` are the offer's ladder before and after the write (`amount`, `currency_code`, `min_quantity`, `max_quantity`, `price_rules`). `created` and `deleted` hold the price ids added and removed; `updated` holds the ids rewritten in place whose amount, quantity bounds, or rules actually changed — an unchanged row resent with its id is not listed. The hook also fires when `updateOffersWorkflow` runs the price upsert for you, so a single handler on `upsertOfferPricesWorkflow` covers both entry points. Prices are hard-deleted and Medusa's pricing events carry ids only, so these payloads (and the `offersDeleted` snapshot) are the only place the previous values can be read.++```ts+import { upsertOfferPricesWorkflow } from "@mercurjs/core/workflows"+import { StepResponse } from "@medusajs/framework/workflows-sdk"++upsertOfferPricesWorkflow.hooks.offerPricesUpserted(+ async ({ offers, updated_by }, { container }) => {+ for (const { offer_id, previous_prices, prices, updated } of offers) {+ // record a price-history entry for every id in `updated`+ }+ return new StepResponse(undefined)+ }+)+```+## Behavior notes- **Prices** are written on the master variant's shared price set, each row scoped by an `offer_id` `PriceRule`. On update, supplying `prices` replaces the ladder with the given rows; omitting it leaves prices untouched.diff --git a/integration-tests/http/offer/vendor/offer-change-hooks.spec.ts b/integration-tests/http/offer/vendor/offer-change-hooks.spec.tsnew file mode 100644index 000000000..af3fb6bab--- /dev/null+++ b/integration-tests/http/offer/vendor/offer-change-hooks.spec.ts@@ -0,0 +1,280 @@+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import { MedusaContainer } from "@medusajs/framework/types"+import { StepResponse } from "@medusajs/framework/workflows-sdk"+import {+ createOffersWorkflow,+ deleteOffersWorkflow,+ updateOffersWorkflow,+ upsertOfferPricesWorkflow,+} from "@mercurjs/core/workflows"+import { OfferDTO, OfferPriceDTO } from "@mercurjs/types"+import { createSellerUser } from "../../../helpers/create-seller-user"+import { createShippingProfile } from "../../../helpers/create-shipping-profile"+import { createVendorProduct } from "../../../helpers/create-product"++jest.setTimeout(120000)++type PriceChange = {+ offer_id: string+ previous_prices: OfferPriceDTO[]+ prices: OfferPriceDTO[]+ created: string[]+ updated: string[]+ deleted: string[]+}++let createdPayload: { offers: OfferDTO[] } | null = null+let updatedPayload: {+ offers: OfferDTO[]+ previous_offers: OfferDTO[]+ updated_by: string | undefined+} | null = null+let pricesPayload: {+ offers: PriceChange[]+ updated_by: string | null+} | null = null+let deletedPayload: { ids: string[]; offers: OfferDTO[] } | null = null++createOffersWorkflow.hooks.offersCreated(({ offers }) => {+ createdPayload = { offers }+ return new StepResponse(undefined)+})++updateOffersWorkflow.hooks.offersUpdated(+ ({ offers, previous_offers, updated_by }) => {+ updatedPayload = { offers, previous_offers, updated_by }+ return new StepResponse(undefined)+ }+)++upsertOfferPricesWorkflow.hooks.offerPricesUpserted(+ ({ offers, updated_by }) => {+ pricesPayload = { offers, updated_by }+ return new StepResponse(undefined)+ }+)++deleteOffersWorkflow.hooks.offersDeleted(({ ids, offers }) => {+ deletedPayload = { ids, offers }+ return new StepResponse(undefined)+})++const byAmount = (prices: OfferPriceDTO[]) =>+ [...prices].sort((a, b) => Number(a.amount) - Number(b.amount))++medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api }) => {+ describe("Vendor - offer change hooks", () => {+ let appContainer: MedusaContainer+ let headers: { headers: Record<string, string> }+ let memberId: string+ let variantId: string+ let shippingProfileId: string++ beforeAll(() => {+ appContainer = getContainer()+ })++ beforeEach(async () => {+ createdPayload = null+ updatedPayload = null+ pricesPayload = null+ deletedPayload = null++ const seller = await createSellerUser(appContainer, {+ email: "[email protected]",+ name: "Hooks Seller",+ })+ headers = seller.headers+ memberId = seller.member.id++ const product = await createVendorProduct(api, headers, {+ title: "Hooked Product",+ variants: [{ title: "Default" }],+ })+ variantId = product.variants[0].id++ const profile = await createShippingProfile(appContainer, {+ name: "Hooks Profile",+ })+ shippingProfileId = profile.id+ })++ const createOffer = async () => {+ const response = await api.post(+ `/vendor/offers`,+ {+ sku: "HOOKED-SKU",+ variant_id: variantId,+ shipping_profile_id: shippingProfileId,+ inventory_items: [{ required_quantity: 1 }],+ prices: [+ {+ amount: 1000,+ currency_code: "usd",+ min_quantity: 1,+ max_quantity: 9,+ },+ { amount: 800, currency_code: "usd", min_quantity: 10 },+ { amount: 900, currency_code: "eur" },+ ],+ },+ headers+ )+ expect(response.status).toEqual(201)+ return response.data.offer as OfferDTO & {+ prices: OfferPriceDTO[]+ }+ }++ it("passes the created prices and created_by to offersCreated", async () => {+ const offer = await createOffer()++ expect(createdPayload?.offers).toHaveLength(1)+ const [created] = createdPayload!.offers+ expect(created.id).toEqual(offer.id)+ expect(created.created_by).toEqual(memberId)+ expect(byAmount(created.prices!).map((p) => p.amount)).toEqual([+ 800, 900, 1000,+ ])+ expect(created.prices!.map((p) => p.id).sort()).toEqual(+ offer.prices.map((p) => p.id).sort()+ )+ })++ it("reports the price ladder diff, the previous row and the actor on update", async () => {+ const offer = await createOffer()+ const usdTier1 = offer.prices.find((p) => p.amount === 1000)!+ const usdTier2 = offer.prices.find((p) => p.amount === 800)!+ const eur = offer.prices.find((p) => p.amount === 900)!++ const response = await api.post(+ `/vendor/offers/${offer.id}`,+ {+ sku: "HOOKED-SKU-2",+ prices: [+ {+ id: usdTier1.id,+ amount: 1200,+ currency_code: "usd",+ min_quantity: 1,+ max_quantity: 9,+ },+ { id: eur.id, amount: 900, currency_code: "eur" },+ { amount: 700, currency_code: "usd", min_quantity: 20 },+ ],+ },+ headers+ )+ expect(response.status).toEqual(200)++ expect(pricesPayload).not.toBeNull()+ expect(pricesPayload!.updated_by).toEqual(memberId)+ expect(pricesPayload!.offers).toHaveLength(1)++ const change = pricesPayload!.offers[0]+ expect(change.offer_id).toEqual(offer.id)+ expect(byAmount(change.previous_prices)).toEqual([+ expect.objectContaining({+ id: usdTier2.id,+ amount: 800,+ currency_code: "usd",+ min_quantity: 10,+ }),+ expect.objectContaining({+ id: eur.id,+ amount: 900,+ currency_code: "eur",+ }),+ expect.objectContaining({+ id: usdTier1.id,+ amount: 1000,+ currency_code: "usd",+ min_quantity: 1,+ max_quantity: 9,+ }),+ ])+ expect(change.updated).toEqual([usdTier1.id])+ expect(change.deleted).toEqual([usdTier2.id])+ expect(change.created).toHaveLength(1)++ const [createdId] = change.created+ expect(byAmount(change.prices)).toEqual([+ expect.objectContaining({+ id: createdId,+ amount: 700,+ currency_code: "usd",+ min_quantity: 20,+ }),+ expect.objectContaining({ id: eur.id, amount: 900 }),+ expect.objectContaining({+ id: usdTier1.id,+ amount: 1200,+ min_quantity: 1,+ max_quantity: 9,+ }),+ ])+ expect(+ change.prices.find((p) => p.id === usdTier1.id)?.price_rules+ ).toEqual([+ expect.objectContaining({+ attribute: "offer_id",+ value: offer.id,+ }),+ ])++ expect(updatedPayload).not.toBeNull()+ expect(updatedPayload!.updated_by).toEqual(memberId)+ expect(updatedPayload!.previous_offers).toEqual([+ expect.objectContaining({ id: offer.id, sku: "HOOKED-SKU" }),+ ])+ expect(updatedPayload!.offers).toEqual([+ expect.objectContaining({ id: offer.id, sku: "HOOKED-SKU-2" }),+ ])+ })++ it("does not run the price hook when prices are not part of the update", async () => {+ const offer = await createOffer()++ const response = await api.post(+ `/vendor/offers/${offer.id}`,+ { sku: "HOOKED-SKU-3" },+ headers+ )+ expect(response.status).toEqual(200)+ expect(pricesPayload).toBeNull()+ expect(updatedPayload?.updated_by).toEqual(memberId)+ })++ it("snapshots the offer with its prices before deletion", async () => {+ const offer = await createOffer()++ const response = await api.delete(+ `/vendor/offers/${offer.id}`,+ headers+ )+ expect(response.status).toEqual(200)++ expect(deletedPayload).not.toBeNull()+ expect(deletedPayload!.ids).toEqual([offer.id])+ expect(deletedPayload!.offers).toHaveLength(1)++ const [snapshot] = deletedPayload!.offers+ expect(snapshot).toEqual(+ expect.objectContaining({+ id: offer.id,+ sku: "HOOKED-SKU",+ seller_id: offer.seller_id,+ created_by: memberId,+ })+ )+ expect(byAmount(snapshot.prices!).map((p) => p.amount)).toEqual([+ 800, 900, 1000,+ ])+ expect(snapshot.prices!.map((p) => p.id).sort()).toEqual(+ offer.prices.map((p) => p.id).sort()+ )+ })+ })+ },+})diff --git a/packages/core/src/api/vendor/offers/[id]/route.ts b/packages/core/src/api/vendor/offers/[id]/route.tsindex 3290126a4..26049f6be 100644--- a/packages/core/src/api/vendor/offers/[id]/route.ts+++ b/packages/core/src/api/vendor/offers/[id]/route.ts@@ -43,6 +43,7 @@ export const POST = async (await updateOffersWorkflow(req.scope).run({input: {offers: [{ id, ...update }],+ updated_by: req.auth_context.actor_id,additional_data,},})diff --git a/packages/core/src/workflows/offer/workflows/create-offers.ts b/packages/core/src/workflows/offer/workflows/create-offers.tsindex 1d60ddca8..c03318944 100644--- a/packages/core/src/workflows/offer/workflows/create-offers.ts+++ b/packages/core/src/workflows/offer/workflows/create-offers.ts@@ -29,6 +29,7 @@ import {} from "../steps"import { linkSellerInventoryItemStep } from "../../inventory-item/steps"import { OfferWorkflowEvents } from "../../events"+import { OFFER_PRICE_FIELDS, pickOfferPrices } from "./upsert-offer-prices"export type CreateOffersWorkflowInput = {offers: CreateOfferDTO[]@@ -362,8 +363,31 @@ export const createOffersWorkflow: ReturnWorkflow<data: eventData,})+ const createdOfferIds = transform({ offers }, ({ offers }) =>+ offers.map((o) => o.id),+ )++ const { data: offersWithPrices } = useQueryGraphStep({+ entity: "offer",+ fields: ["*", ...OFFER_PRICE_FIELDS],+ filters: { id: createdOfferIds },+ }).config({ name: "get-created-offers" })++ const createdOffers = transform(+ { offers, offersWithPrices },+ ({ offers, offersWithPrices }) => {+ const byId = new Map(+ (offersWithPrices as unknown as OfferDTO[]).map((o) => [o.id, o]),+ )+ return offers.map((o): OfferDTO => {+ const loaded = byId.get(o.id)+ return { ...o, prices: loaded ? pickOfferPrices(loaded) : [] }+ })+ },+ )+const offersCreated = createHook("offersCreated", {- offers,+ offers: createdOffers,additional_data: input.additional_data,})diff --git a/packages/core/src/workflows/offer/workflows/delete-offers.ts b/packages/core/src/workflows/offer/workflows/delete-offers.tsindex 73c854759..1679b13c3 100644--- a/packages/core/src/workflows/offer/workflows/delete-offers.ts+++ b/packages/core/src/workflows/offer/workflows/delete-offers.ts@@ -3,23 +3,43 @@ import {createWorkflow,transform,WorkflowResponse,+ type Hook,+ type ReturnWorkflow,} from "@medusajs/framework/workflows-sdk"import { AdditionalData } from "@medusajs/framework/types"import { emitEventStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"+import { OfferDTO } from "@mercurjs/types"import { deleteOffersStep } from "../steps"import { OfferWorkflowEvents } from "../../events"+import { OFFER_PRICE_FIELDS, pickOfferPrices } from "./upsert-offer-prices"export type DeleteOffersWorkflowInput = { ids: string[] } & AdditionalData+export type DeleteOffersWorkflowHooks = [+ Hook<+ "offersDeleted",+ {+ ids: string[]+ offers: OfferDTO[]+ additional_data: Record<string, unknown> | undefined+ },+ unknown+ >,+]+export const deleteOffersWorkflowId = "delete-offers"-export const deleteOffersWorkflow = createWorkflow(+export const deleteOffersWorkflow: ReturnWorkflow<+ DeleteOffersWorkflowInput,+ void,+ DeleteOffersWorkflowHooks+> = createWorkflow(deleteOffersWorkflowId,function (input: DeleteOffersWorkflowInput) {const { data: offers } = useQueryGraphStep({entity: "offer",- fields: ["id", "product_id"],+ fields: ["*", ...OFFER_PRICE_FIELDS],filters: { id: input.ids },})@@ -34,8 +54,16 @@ export const deleteOffersWorkflow = createWorkflow(data: eventData,})+ const deletedOffers = transform({ offers }, ({ offers }) =>+ (offers as unknown as OfferDTO[]).map((o) => ({+ ...o,+ prices: pickOfferPrices(o),+ })),+ )+const offersDeleted = createHook("offersDeleted", {ids: input.ids,+ offers: deletedOffers,additional_data: input.additional_data,})diff --git a/packages/core/src/workflows/offer/workflows/update-offers.ts b/packages/core/src/workflows/offer/workflows/update-offers.tsindex c2615f236..0149c7605 100644--- a/packages/core/src/workflows/offer/workflows/update-offers.ts+++ b/packages/core/src/workflows/offer/workflows/update-offers.ts@@ -8,7 +8,7 @@ import {type ReturnWorkflow,} from "@medusajs/framework/workflows-sdk"import { AdditionalData } from "@medusajs/framework/types"-import { emitEventStep } from "@medusajs/medusa/core-flows"+import { emitEventStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"import { UpdateOfferDTO, OfferDTO } from "@mercurjs/types"import { updateOffersStep, validateOfferConditionsStep } from "../steps"@@ -17,6 +17,7 @@ import { OfferWorkflowEvents } from "../../events"export type UpdateOffersWorkflowInput = {offers: UpdateOfferDTO[]+ updated_by?: string} & AdditionalDataexport type UpdateOffersWorkflowHooks = [@@ -25,6 +26,8 @@ export type UpdateOffersWorkflowHooks = ["offersUpdated",{offers: OfferDTO[]+ previous_offers: OfferDTO[]+ updated_by: string | undefinedadditional_data: Record<string, unknown> | undefined},unknown@@ -50,6 +53,14 @@ export const updateOffersWorkflow: ReturnWorkflow<validateOfferConditionsStep({ condition_ids: conditionIds })+ const offerIds = transform(input, ({ offers }) => offers.map((o) => o.id))++ const { data: previousOffers } = useQueryGraphStep({+ entity: "offer",+ fields: ["*"],+ filters: { id: offerIds },+ }).config({ name: "get-offers-before-update" })+const rowUpdates = transform(input, ({ offers }) =>offers.map((o) => ({id: o.id,@@ -69,6 +80,7 @@ export const updateOffersWorkflow: ReturnWorkflow<offers: input.offers.filter((o) => Array.isArray(o.prices)).map((o) => ({ id: o.id, prices: o.prices ?? [] })),+ updated_by: input.updated_by,}))when({ offerPrices }, ({ offerPrices }) => offerPrices.offers.length > 0).then(@@ -88,6 +100,8 @@ export const updateOffersWorkflow: ReturnWorkflow<const offersUpdated = createHook("offersUpdated", {offers,+ previous_offers: previousOffers as unknown as OfferDTO[],+ updated_by: input.updated_by,additional_data: input.additional_data,})diff --git a/packages/core/src/workflows/offer/workflows/upsert-offer-prices.ts b/packages/core/src/workflows/offer/workflows/upsert-offer-prices.tsindex 6aeba4868..6cd50edb2 100644--- a/packages/core/src/workflows/offer/workflows/upsert-offer-prices.ts+++ b/packages/core/src/workflows/offer/workflows/upsert-offer-prices.ts@@ -1,8 +1,11 @@import {+ createHook,createWorkflow,transform,WorkflowData,WorkflowResponse,+ type Hook,+ type ReturnWorkflow,} from "@medusajs/framework/workflows-sdk"import { LinkDefinition, PricingTypes } from "@medusajs/framework/types"import {@@ -11,12 +14,17 @@ import {useQueryGraphStep,} from "@medusajs/medusa/core-flows"import { MedusaError, Modules } from "@medusajs/framework/utils"-import { MercurModules, UpsertOfferPriceDTO } from "@mercurjs/types"+import {+ MercurModules,+ OfferPriceDTO,+ UpsertOfferPriceDTO,+} from "@mercurjs/types"import {addOfferPricesStep,removeOfferPricesStep,type AddOfferPricesStepInput,+ type AddOfferPricesStepOutput,} from "../steps"import { assertOfferPriceOwnership } from "../utils"@@ -25,8 +33,66 @@ export type UpsertOfferPricesWorkflowInput = {id: stringprices: UpsertOfferPriceDTO[]}[]+ updated_by?: string+}++export type OfferPricesUpsertedHookOffer = {+ offer_id: string+ previous_prices: OfferPriceDTO[]+ prices: OfferPriceDTO[]+ created: string[]+ updated: string[]+ deleted: string[]}+export type UpsertOfferPricesWorkflowHooks = [+ Hook<+ "offerPricesUpserted",+ {+ offers: OfferPricesUpsertedHookOffer[]+ updated_by: string | null+ },+ unknown+ >,+]++export const OFFER_PRICE_FIELDS = [+ "prices.id",+ "prices.amount",+ "prices.currency_code",+ "prices.min_quantity",+ "prices.max_quantity",+ "prices.price_rules.attribute",+ "prices.price_rules.value",+] as const++type LoadedOfferPrices = {+ id: string+ prices?: Array<OfferPriceDTO | null> | null+}++export const pickOfferPrices = (offer: LoadedOfferPrices): OfferPriceDTO[] =>+ (offer.prices ?? []).filter((p): p is OfferPriceDTO => !!p?.id)++const serializeRules = (rules: Array<{ attribute: string; value: string }>) =>+ rules+ .map((r) => `${r.attribute}=${r.value}`)+ .sort()+ .join(",")++const serializePrice = (+ amount: unknown,+ min_quantity: unknown,+ max_quantity: unknown,+ rules: Array<{ attribute: string; value: string }>,+) =>+ JSON.stringify({+ amount: Number(amount),+ min_quantity: min_quantity ?? null,+ max_quantity: max_quantity ?? null,+ rules: serializeRules(rules),+ })+export const upsertOfferPricesWorkflowId = "upsert-offer-prices"/**@@ -34,7 +100,11 @@ export const upsertOfferPricesWorkflowId = "upsert-offer-prices"* 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(+export const upsertOfferPricesWorkflow: ReturnWorkflow<+ UpsertOfferPricesWorkflowInput,+ AddOfferPricesStepOutput,+ UpsertOfferPricesWorkflowHooks+> = createWorkflow(upsertOfferPricesWorkflowId,function (input: WorkflowData<UpsertOfferPricesWorkflowInput>) {const offerIds = transform({ input }, ({ input }) =>@@ -47,13 +117,7 @@ export const upsertOfferPricesWorkflow = createWorkflow("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",+ ...OFFER_PRICE_FIELDS,],filters: { id: offerIds },}).config({ name: "get-offer-prices" })@@ -68,13 +132,19 @@ export const upsertOfferPricesWorkflow = createWorkflow(product_variant?: {price_set?: { id?: string } | null} | null- prices?: Array<{ id: string } | null> | null+ prices?: Array<OfferPriceDTO | null> | null}>).map((o) => [o.id, o]),)const addPricesPayload: AddOfferPricesStepInput = []const toRemoveIds: string[] = []const removedLinks: LinkDefinition[] = []+ const changes: Array<{+ offer_id: string+ previous_prices: OfferPriceDTO[]+ updated: string[]+ deleted: string[]+ }> = []for (const offer of input.offers) {const loaded = offerById.get(offer.id)@@ -95,11 +165,9 @@ export const upsertOfferPricesWorkflow = createWorkflow(// `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 previousPrices = pickOfferPrices(loaded)+ const ownedById = new Map(previousPrices.map((p) => [p.id, p]))+ const ownedIds = new Set(ownedById.keys())const incomingIds = offer.prices.map((p) => p.id).filter((id): id is string => !!id)@@ -110,10 +178,12 @@ export const upsertOfferPricesWorkflow = createWorkflow(owned_price_ids: ownedIds,})+ const deleted: string[] = []const keepIds = new Set(incomingIds)for (const ownedId of ownedIds) {if (!keepIds.has(ownedId)) {toRemoveIds.push(ownedId)+ deleted.push(ownedId)removedLinks.push({[MercurModules.OFFER]: { offer_id: offer.id },[Modules.PRICING]: { price_id: ownedId },@@ -121,13 +191,31 @@ export const upsertOfferPricesWorkflow = createWorkflow(}}+ const updated: string[] = []const upsertPrices: Array<PricingTypes.CreatePricesDTO & { id?: string }> = offer.prices.map((p) => {+ const rules = { ...(p.rules ?? {}), offer_id: offer.id }+ const ruleRows = Object.entries(rules).map(+ ([attribute, value]) => ({ attribute, value }),+ )+ const existing = p.id ? ownedById.get(p.id) : undefined+ const rulesUnchanged =+ !!existing &&+ serializeRules(existing.price_rules ?? []) ===+ serializeRules(ruleRows)+const base: PricingTypes.CreatePricesDTO & { id?: string } = {amount: p.amount,currency_code: p.currency_code,- rules: { ...(p.rules ?? {}), offer_id: offer.id },+ }+ // Medusa matches an incoming row to an existing price by a hash of+ // its bounds and rules and, on a match, feeds the serialized+ // existing rule rows back into its upsert, which never completes.+ // Leaving `rules` out of an unchanged-rules update skips that+ // match and keeps the stored rule rows as they are.+ if (!rulesUnchanged) {+ base.rules = rules}if (p.id) {base.id = p.id@@ -138,6 +226,24 @@ export const upsertOfferPricesWorkflow = createWorkflow(if (p.max_quantity !== undefined && p.max_quantity !== null) {base.max_quantity = p.max_quantity}++ if (existing) {+ const before = serializePrice(+ existing.amount,+ existing.min_quantity,+ existing.max_quantity,+ existing.price_rules ?? [],+ )+ const after = serializePrice(+ p.amount,+ p.min_quantity,+ p.max_quantity,+ ruleRows,+ )+ if (before !== after || existing.currency_code !== p.currency_code) {+ updated.push(existing.id)+ }+ }return base})@@ -147,12 +253,20 @@ export const upsertOfferPricesWorkflow = createWorkflow(prices: upsertPrices,})}++ changes.push({+ offer_id: offer.id,+ previous_prices: previousPrices,+ updated,+ deleted,+ })}return {addPricesPayload,toRemoveIds,removedLinks,+ changes,}},)@@ -202,6 +316,46 @@ export const upsertOfferPricesWorkflow = createWorkflow(name: "create-new-offer-price-links",})- return new WorkflowResponse(addedPrices)+ const { data: updatedOfferRows } = useQueryGraphStep({+ entity: "offer",+ fields: ["id", ...OFFER_PRICE_FIELDS],+ filters: { id: offerIds },+ }).config({ name: "get-offer-prices-after-upsert" })++ const hookOffers = transform(+ { pricingDiff, addedPrices, updatedOfferRows },+ ({ pricingDiff, addedPrices, updatedOfferRows }) => {+ const createdByOffer = new Map(+ addedPrices.map((entry) => [entry.offer_id, entry.price_ids]),+ )+ const afterById = new Map(+ (updatedOfferRows as LoadedOfferPrices[]).map((o) => [o.id, o]),+ )+ return pricingDiff.changes.map(+ (change): OfferPricesUpsertedHookOffer => {+ const after = afterById.get(change.offer_id)+ return {+ ...change,+ prices: after ? pickOfferPrices(after) : [],+ created: createdByOffer.get(change.offer_id) ?? [],+ }+ },+ )+ },+ )++ const updatedBy = transform(+ { input },+ ({ input }) => input.updated_by ?? null,+ )++ const offerPricesUpserted = createHook("offerPricesUpserted", {+ offers: hookOffers,+ updated_by: updatedBy,+ })++ return new WorkflowResponse(addedPrices, {+ hooks: [offerPricesUpserted],+ })},)