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(core): stop stamping unhandled product-change actions as applied (#1463)
Viktor Holike3c70c893aa4
diff --git a/integration-tests/http/product-edit/modules/apply-product-change-actions.spec.ts b/integration-tests/http/product-edit/modules/apply-product-change-actions.spec.tsnew file mode 100644index 000000000..4f9897a95--- /dev/null+++ b/integration-tests/http/product-edit/modules/apply-product-change-actions.spec.ts@@ -0,0 +1,186 @@+import { MedusaContainer } from "@medusajs/framework/types"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import {+ MercurModules,+ ProductChangeActionType,+ ProductChangeStatus,+} from "@mercurjs/types"++import { applyProductChangeActionsWorkflow } from "@mercurjs/core/workflows"++import {+ adminHeaders,+ createAdminUser,+} from "../../../helpers/create-admin-user"+import { createSellerUser } from "../../../helpers/create-seller-user"++jest.setTimeout(60_000)++medusaIntegrationTestRunner({+ testSuite: ({ getContainer, dbConnection, api }) => {+ describe("applyProductChangeActionsWorkflow", () => {+ let container: MedusaContainer+ let sellerHeaders: { headers: Record<string, string> }++ beforeAll(async () => {+ container = getContainer()+ })++ beforeEach(async () => {+ await createAdminUser(dbConnection, adminHeaders, container)+ const seller = await createSellerUser(container, {+ email: "[email protected]",+ name: "Apply Actions Seller",+ })+ sellerHeaders = seller.headers+ })++ type ProductChangeRow = { id: string }+ type ProductEditService = {+ createProductChanges(+ data: Array<Record<string, unknown>>,+ ): Promise<ProductChangeRow[]>+ createProductChangeActions(+ data: Array<Record<string, unknown>>,+ ): Promise<ProductChangeRow[]>+ }++ const service = () =>+ container.resolve<ProductEditService>(MercurModules.PRODUCT_EDIT)++ const stageChange = async (+ productId: string,+ actions: Array<Record<string, unknown>>,+ ) => {+ const [change] = await service().createProductChanges([+ { product_id: productId, status: ProductChangeStatus.PENDING },+ ])+ const created = await service().createProductChangeActions(+ actions.map((action) => ({+ product_id: productId,+ product_change_id: change.id,+ applied: false,+ ...action,+ })),+ )+ return { change, actions: created }+ }++ const readActions = async (changeId: string) => {+ const query = container.resolve(ContainerRegistrationKeys.QUERY)+ const { data } = await query.graph({+ entity: "product_change_action",+ fields: ["id", "action", "applied", "reference", "reference_id"],+ filters: { product_change_id: changeId },+ })+ return data as Array<{+ id: string+ action: string+ applied: boolean+ reference: string | null+ reference_id: string | null+ }>+ }++ const createProduct = async (title: string): Promise<string> => {+ const res = await api.post("/vendor/products", { title }, sellerHeaders)+ return res.data.product.id+ }++ it("applies and stamps a handled action", async () => {+ const productId = await createProduct("Handled Only")+ const { change } = await stageChange(productId, [+ {+ action: ProductChangeActionType.UPDATE,+ details: { field: "subtitle", value: "applied subtitle" },+ },+ ])++ await applyProductChangeActionsWorkflow(container).run({+ input: { change_ids: [change.id] },+ })++ const actions = await readActions(change.id)+ expect(actions).toHaveLength(1)+ expect(actions[0].applied).toBe(true)++ const product = await api.get(+ `/admin/products/${productId}`,+ adminHeaders,+ )+ expect(product.data.product.subtitle).toBe("applied subtitle")+ })++ it("leaves an action type it does not handle untouched and unstamped", async () => {+ const productId = await createProduct("Unknown Action")+ const { change } = await stageChange(productId, [+ { action: "THIRD_PARTY_ACTION", details: { anything: true } },+ { action: ProductChangeActionType.CHANGE_REQUESTED, details: {} },+ ])++ await applyProductChangeActionsWorkflow(container).run({+ input: { change_ids: [change.id] },+ })++ const actions = await readActions(change.id)+ expect(actions).toHaveLength(2)+ expect(actions.every((a) => a.applied === false)).toBe(true)+ })++ it("stamps only the handled action when a change mixes handled and unknown types", async () => {+ const productId = await createProduct("Mixed Actions")+ const { change } = await stageChange(productId, [+ {+ action: ProductChangeActionType.UPDATE,+ details: { field: "subtitle", value: "mixed subtitle" },+ },+ { action: "THIRD_PARTY_ACTION", details: {} },+ ])++ await applyProductChangeActionsWorkflow(container).run({+ input: { change_ids: [change.id] },+ })++ const actions = await readActions(change.id)+ const applied = actions.filter((a) => a.applied)+ expect(applied).toHaveLength(1)+ expect(applied[0].action).toBe(ProductChangeActionType.UPDATE)+ })++ it("persists reference / reference_id and makes them filterable", async () => {+ const productId = await createProduct("Referenced Action")+ const { change } = await stageChange(productId, [+ {+ action: ProductChangeActionType.UPDATE,+ details: { field: "subtitle", value: "referenced" },+ reference: "product_variant",+ reference_id: "variant_ref_1",+ },+ {+ action: ProductChangeActionType.UPDATE,+ details: { field: "handle", value: "referenced-handle" },+ },+ ])++ const all = await readActions(change.id)+ const unreferenced = all.find((a) => a.reference === null)+ expect(unreferenced).toBeDefined()+ expect(unreferenced!.reference_id).toBeNull()++ const query = container.resolve(ContainerRegistrationKeys.QUERY)+ const { data } = await query.graph({+ entity: "product_change_action",+ fields: ["id", "reference", "reference_id"],+ filters: {+ reference: "product_variant",+ reference_id: "variant_ref_1",+ },+ })++ expect(data).toHaveLength(1)+ expect(data[0].reference).toBe("product_variant")+ })+ })+ },+})diff --git a/packages/core/src/modules/product-edit/migrations/Migration20260901120000.ts b/packages/core/src/modules/product-edit/migrations/Migration20260901120000.tsnew file mode 100644index 000000000..ee151f055--- /dev/null+++ b/packages/core/src/modules/product-edit/migrations/Migration20260901120000.ts@@ -0,0 +1,27 @@+import { Migration } from "@medusajs/framework/mikro-orm/migrations"++export class Migration20260901120000 extends Migration {+ override async up(): Promise<void> {+ this.addSql(`+ ALTER TABLE "product_change_action"+ ADD COLUMN IF NOT EXISTS "reference" text NULL,+ ADD COLUMN IF NOT EXISTS "reference_id" text NULL;+ `)+ this.addSql(`+ CREATE INDEX IF NOT EXISTS "IDX_prodchact_reference_reference_id"+ ON "product_change_action" ("reference", "reference_id")+ WHERE "deleted_at" IS NULL;+ `)+ }++ override async down(): Promise<void> {+ this.addSql(`+ DROP INDEX IF EXISTS "IDX_prodchact_reference_reference_id";+ `)+ this.addSql(`+ ALTER TABLE "product_change_action"+ DROP COLUMN IF EXISTS "reference",+ DROP COLUMN IF EXISTS "reference_id";+ `)+ }+}diff --git a/packages/core/src/modules/product-edit/models/product-change-action.ts b/packages/core/src/modules/product-edit/models/product-change-action.tsindex 1c056510f..bbfe1ada4 100644--- a/packages/core/src/modules/product-edit/models/product-change-action.ts+++ b/packages/core/src/modules/product-edit/models/product-change-action.ts@@ -9,6 +9,8 @@ const ProductChangeAction = modelordering: model.autoincrement(),action: model.text(),details: model.json().default({}),+ reference: model.text().nullable(),+ reference_id: model.text().nullable(),internal_note: model.text().nullable(),applied: model.boolean().default(false),product_change: model@@ -28,6 +30,12 @@ const ProductChangeAction = modelunique: false,where: "deleted_at IS NULL",},+ {+ name: "IDX_prodchact_reference_reference_id",+ on: ["reference", "reference_id"],+ unique: false,+ where: "deleted_at IS NULL",+ },{name: "IDX_prodchact_ordering",on: ["ordering"],diff --git a/packages/core/src/workflows/product-edit/workflows/apply-product-change-actions.ts b/packages/core/src/workflows/product-edit/workflows/apply-product-change-actions.tsindex 5d3ba85a4..836f4f380 100644--- a/packages/core/src/workflows/product-edit/workflows/apply-product-change-actions.ts+++ b/packages/core/src/workflows/product-edit/workflows/apply-product-change-actions.ts@@ -46,6 +46,18 @@ type BucketedActions = {pendingActionIds: string[]}+const HANDLED_ACTION_TYPES = new Set<string>([+ ProductChangeActionType.STATUS_CHANGE,+ ProductChangeActionType.UPDATE,+ ProductChangeActionType.VARIANT_ADD,+ ProductChangeActionType.VARIANT_UPDATE,+ ProductChangeActionType.VARIANT_REMOVE,+ ProductChangeActionType.ATTRIBUTE_ADD,+ ProductChangeActionType.ATTRIBUTE_REMOVE,+ ProductChangeActionType.ATTRIBUTE_UPDATE,+ ProductChangeActionType.PRODUCT_DELETE,+])+export const applyProductChangeActionsWorkflowId ="apply-product-change-actions"@@ -91,6 +103,9 @@ export const applyProductChangeActionsWorkflow: ReturnWorkflow<for (const action of actions ?? []) {if (!action || action.applied) continue+ // Types this workflow cannot act on keep `applied: false` — stamping+ // them would assert an application that never happened.+ if (!HANDLED_ACTION_TYPES.has(action.action as string)) continuependingActionIds.push(action.id as string)const productId = action.product_id as stringdiff --git a/packages/core/src/workflows/product-edit/workflows/product-edit-update-attributes.ts b/packages/core/src/workflows/product-edit/workflows/product-edit-update-attributes.tsindex be000430d..bf5197dc8 100644--- a/packages/core/src/workflows/product-edit/workflows/product-edit-update-attributes.ts+++ b/packages/core/src/workflows/product-edit/workflows/product-edit-update-attributes.ts@@ -1,10 +1,12 @@import { AdditionalData } from "@medusajs/framework/types"import { deepEqualObj } from "@medusajs/framework/utils"import {+ createHook,createWorkflow,+ type Hook,+ type ReturnWorkflow,transform,WorkflowResponse,- type ReturnWorkflow,} from "@medusajs/framework/workflows-sdk"import { useQueryGraphStep } from "@medusajs/medusa/core-flows"import {@@ -28,6 +30,17 @@ export type ProductEditUpdateAttributesWorkflowInput = {update?: ProductAttributeBatchUpdate[]} & AdditionalData+export type ProductEditUpdateAttributesWorkflowHooks = [+ Hook<+ "productChangeCreated",+ {+ product_change: ProductChangeDTO+ additional_data: Record<string, unknown> | undefined+ },+ unknown+ >,+]+export const productEditUpdateAttributesWorkflowId ="product-edit-update-attributes"@@ -63,7 +76,7 @@ const readScalar = (export const productEditUpdateAttributesWorkflow: ReturnWorkflow<ProductEditUpdateAttributesWorkflowInput,ProductChangeDTO,- []+ ProductEditUpdateAttributesWorkflowHooks> = createWorkflow(productEditUpdateAttributesWorkflowId,function (input: ProductEditUpdateAttributesWorkflowInput) {@@ -207,6 +220,13 @@ export const productEditUpdateAttributesWorkflow: ReturnWorkflow<})),})- return new WorkflowResponse(change)+ const productChangeCreated = createHook("productChangeCreated", {+ product_change: change,+ additional_data: input.additional_data,+ })++ return new WorkflowResponse(change, {+ hooks: [productChangeCreated],+ })},)diff --git a/packages/types/src/product/common.ts b/packages/types/src/product/common.tsindex 75012e520..d2c6048a4 100644--- a/packages/types/src/product/common.ts+++ b/packages/types/src/product/common.ts@@ -152,6 +152,8 @@ export interface ProductChangeActionDTO {ordering: numberaction: stringdetails: Record<string, unknown>+ reference: string | null+ reference_id: string | nullinternal_note: string | nullapplied: booleanproduct_change?: ProductChangeDTOdiff --git a/packages/types/src/product/mutations.ts b/packages/types/src/product/mutations.tsindex e41fbe9fb..ede07d289 100644--- a/packages/types/src/product/mutations.ts+++ b/packages/types/src/product/mutations.ts@@ -231,6 +231,8 @@ export interface CreateProductChangeActionDTO {product_id: stringaction: stringdetails?: Record<string, unknown>+ reference?: string | null+ reference_id?: string | nullinternal_note?: stringapplied?: boolean}