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): actor-scope the pending product-change guard (#1443)
Viktor Holik15686f6966e6
diff --git a/integration-tests/http/product-edit/vendor/product-edit.spec.ts b/integration-tests/http/product-edit/vendor/product-edit.spec.tsindex be7ea65dd..5c4834e67 100644--- a/integration-tests/http/product-edit/vendor/product-edit.spec.ts+++ b/integration-tests/http/product-edit/vendor/product-edit.spec.ts@@ -26,6 +26,8 @@ medusaIntegrationTestRunner({let container: MedusaContainerlet sellerHeaders: { headers: Record<string, string> }let otherSellerHeaders: { headers: Record<string, string> }+ let sellerId: string+ let otherSellerId: stringbeforeAll(async () => {container = getContainer()@@ -37,11 +39,13 @@ medusaIntegrationTestRunner({name: "Edit Seller",})sellerHeaders = a.headers+ sellerId = sellerHeaders.headers["x-seller-id"]const b = await createSellerUser(container, {email: "[email protected]",name: "Other Seller",})otherSellerHeaders = b.headers+ otherSellerId = otherSellerHeaders.headers["x-seller-id"]})const createVendorProduct = async (@@ -171,7 +175,7 @@ medusaIntegrationTestRunner({it("rejects a second pending edit while one is already open", async () => {const productId = await createVendorProduct("Title")- await seedPendingChange(productId, "seller-x", [+ await seedPendingChange(productId, sellerId, [{action: ProductChangeActionType.UPDATE,details: { field: "title", value: "Pending" },@@ -191,6 +195,34 @@ medusaIntegrationTestRunner({"There is already an active update request for this product. Only one request can be active at a time.",)})++ it("allows an edit while another seller holds a pending change on the same product", async () => {+ const productId = await createVendorProduct("Shared Title")+ await seedPendingChange(productId, otherSellerId, [+ {+ action: ProductChangeActionType.UPDATE,+ details: { field: "title", value: "Other Seller Pending" },+ },+ ])++ const res = await api.post(+ `/vendor/products/${productId}`,+ { title: "My Edit" },+ sellerHeaders,+ )++ expect(res.status).toBe(202)+ expect(res.data.product_change.created_by).toBe(sellerId)++ // The other seller's pending change is untouched by this edit.+ const changes = await listChanges(productId)+ const otherPending = changes.filter(+ (c) =>+ c.status === ProductChangeStatus.PENDING &&+ c.created_by === otherSellerId,+ )+ expect(otherPending).toHaveLength(1)+ })})describe("DELETE /vendor/products/:id (staging)", () => {@@ -229,7 +261,6 @@ medusaIntegrationTestRunner({// Seed a pending change owned by the *first* seller. The route// resolves the change by `(product_id, created_by, status: pending)`,// so the seed must carry the seller's id, not a fake one.- const sellerId = sellerHeaders.headers["x-seller-id"]const changeId = await seedPendingChange(productId, sellerId, [{action: ProductChangeActionType.UPDATE,@@ -270,7 +301,6 @@ medusaIntegrationTestRunner({expect(res.status).toBe(200)expect(res.data.product_change).toBeNull()- const sellerId = sellerHeaders.headers["x-seller-id"]await seedPendingChange(productId, sellerId, [{action: ProductChangeActionType.UPDATE,@@ -287,7 +317,6 @@ medusaIntegrationTestRunner({it("does not leak another seller's pending change", async () => {const productId = await createVendorProduct("Owned", sellerHeaders)- const otherSellerId = otherSellerHeaders.headers["x-seller-id"]await seedPendingChange(productId, otherSellerId, [{action: ProductChangeActionType.UPDATE,diff --git a/packages/core/src/modules/product-edit/migrations/Migration20260828120000.ts b/packages/core/src/modules/product-edit/migrations/Migration20260828120000.tsnew file mode 100644index 000000000..12bfe34da--- /dev/null+++ b/packages/core/src/modules/product-edit/migrations/Migration20260828120000.ts@@ -0,0 +1,17 @@+import { Migration } from "@medusajs/framework/mikro-orm/migrations"++export class Migration20260828120000 extends Migration {+ override async up(): Promise<void> {+ this.addSql(`+ CREATE INDEX IF NOT EXISTS "IDX_product_change_product_id_status"+ ON "product_change" ("product_id", "status")+ WHERE "deleted_at" IS NULL;+ `)+ }++ override async down(): Promise<void> {+ this.addSql(`+ DROP INDEX IF EXISTS "IDX_product_change_product_id_status";+ `)+ }+}diff --git a/packages/core/src/modules/product-edit/models/product-change.ts b/packages/core/src/modules/product-edit/models/product-change.tsindex 57db121bf..49f2c452d 100644--- a/packages/core/src/modules/product-edit/models/product-change.ts+++ b/packages/core/src/modules/product-edit/models/product-change.ts@@ -45,6 +45,12 @@ const ProductChange = modelunique: false,where: "deleted_at IS NULL",},+ {+ name: "IDX_product_change_product_id_status",+ on: ["product_id", "status"],+ unique: false,+ where: "deleted_at IS NULL",+ },])export default ProductChangediff --git a/packages/core/src/workflows/product-edit/steps/validate-no-pending-product-change.ts b/packages/core/src/workflows/product-edit/steps/validate-no-pending-product-change.tsindex 14860528c..9b2556ed3 100644--- a/packages/core/src/workflows/product-edit/steps/validate-no-pending-product-change.ts+++ b/packages/core/src/workflows/product-edit/steps/validate-no-pending-product-change.ts@@ -1,5 +1,6 @@import {ContainerRegistrationKeys,+ isDefined,MedusaError,} from "@medusajs/framework/utils"import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"@@ -10,12 +11,17 @@ export const validateNoPendingProductChangeStepId =type ValidateNoPendingProductChangeStepInput = {product_ids: string[]+ /**+ * When set, only changes created by this actor conflict. Omitting it keeps+ * the product-wide behaviour for external callers.+ */+ created_by?: string | null}export const validateNoPendingProductChangeStep = createStep(validateNoPendingProductChangeStepId,async (- { product_ids }: ValidateNoPendingProductChangeStepInput,+ { product_ids, created_by }: ValidateNoPendingProductChangeStepInput,{ container },) => {if (!product_ids.length) {@@ -26,24 +32,19 @@ export const validateNoPendingProductChangeStep = createStep(const { data: changes } = await query.graph({entity: "product_change",- fields: ["id", "product_id", "status"],- filters: {},+ fields: ["id", "product_id", "created_by"],+ filters: {+ product_id: product_ids,+ status: ProductChangeStatus.PENDING,+ ...(isDefined(created_by) ? { created_by } : {}),+ },})- const conflicts = new Set<string>()- for (const change of changes as Array<{- id: string- product_id?: string- status?: string- }>) {- if (- change.status === ProductChangeStatus.PENDING &&- change.product_id &&- product_ids.includes(change.product_id)- ) {- conflicts.add(change.product_id)- }- }+ const conflicts = new Set(+ (changes as Array<{ product_id?: string }>)+ .map((change) => change.product_id)+ .filter(Boolean) as string[],+ )if (conflicts.size) {throw new MedusaError(diff --git a/packages/core/src/workflows/product-edit/workflows/create-product-change.ts b/packages/core/src/workflows/product-edit/workflows/create-product-change.tsindex af07d08f5..f3ba1f9e7 100644--- a/packages/core/src/workflows/product-edit/workflows/create-product-change.ts+++ b/packages/core/src/workflows/product-edit/workflows/create-product-change.ts@@ -43,11 +43,17 @@ export const createProductChangeWorkflow: ReturnWorkflow<function (input: CreateProductChangeWorkflowInput) {const validate = createHook("validate", { input })- const productIds = transform({ input }, ({ input }) =>- Array.from(new Set(input.changes.map((c) => c.product_id))),- )+ const guardInput = transform({ input }, ({ input }) => {+ const actors = new Set(input.changes.map((c) => c.created_by))- validateNoPendingProductChangeStep({ product_ids: productIds })+ return {+ product_ids: Array.from(new Set(input.changes.map((c) => c.product_id))),+ // A batch spanning several actors falls back to product-wide scoping.+ created_by: actors.size === 1 ? input.changes[0].created_by : undefined,+ }+ })++ validateNoPendingProductChangeStep(guardInput)const changes = createProductChangesStep(input.changes)diff --git a/packages/core/src/workflows/product-edit/workflows/product-edit-delete-product.ts b/packages/core/src/workflows/product-edit/workflows/product-edit-delete-product.tsindex 3f0900ba0..ba510f76f 100644--- a/packages/core/src/workflows/product-edit/workflows/product-edit-delete-product.ts+++ b/packages/core/src/workflows/product-edit/workflows/product-edit-delete-product.ts@@ -33,6 +33,7 @@ export const productEditDeleteProductWorkflow: ReturnWorkflow<validateNoPendingProductChangeStep(transform({ input }, ({ input }) => ({product_ids: [input.product_id],+ created_by: input.created_by,})),)diff --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 798c08912..be000430d 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@@ -70,6 +70,7 @@ export const productEditUpdateAttributesWorkflow: ReturnWorkflow<validateNoPendingProductChangeStep(transform({ input }, ({ input }) => ({product_ids: [input.product_id],+ created_by: input.created_by,})),)diff --git a/packages/core/src/workflows/product-edit/workflows/product-edit-update-product.ts b/packages/core/src/workflows/product-edit/workflows/product-edit-update-product.tsindex 3f71538c2..b7e044df6 100644--- a/packages/core/src/workflows/product-edit/workflows/product-edit-update-product.ts+++ b/packages/core/src/workflows/product-edit/workflows/product-edit-update-product.ts@@ -72,6 +72,7 @@ export const productEditUpdateProductWorkflow: ReturnWorkflow<validateNoPendingProductChangeStep(transform({ input }, ({ input }) => ({product_ids: [input.product_id],+ created_by: input.created_by,})),)diff --git a/packages/core/src/workflows/product-edit/workflows/product-edit-update-variants.ts b/packages/core/src/workflows/product-edit/workflows/product-edit-update-variants.tsindex 5c2d3105a..792558dcd 100644--- a/packages/core/src/workflows/product-edit/workflows/product-edit-update-variants.ts+++ b/packages/core/src/workflows/product-edit/workflows/product-edit-update-variants.ts@@ -57,6 +57,7 @@ export const productEditUpdateVariantsWorkflow: ReturnWorkflow<validateNoPendingProductChangeStep(transform({ input }, ({ input }) => ({product_ids: [input.product_id],+ created_by: input.created_by,})),)