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(core): close the gaps the Magento connector hit in the store, admin and offer APIs (#1697)

Viktor Holik8271e66a14bd
diff --git a/claude-progress.md b/claude-progress.md
index 3324ca9aa..f19170d79 100644
--- a/claude-progress.md
+++ b/claude-progress.md
@@ -14,6 +14,19 @@ session detail aggressively. The per-spec source of truth lives in
`bun run test:integration:http -- <pattern>`
- **Current blocker**: none
+## Session — Magento integration gaps in core (2026-10-23), branch `fix/magento-integration-gaps`
+
+Running the Magento connector against a live API (see the connector PRs #2–#5) exposed core behaviour the
+integration had to work around. Fixed here: `POST /store/carts` now ignores an empty `currency_code` instead of
+storing it and failing every later price calculation; the cart completion response lists the order group's child
+`orders` with `display_id`, `status` and `seller`; an admin product created or updated as `published` emits
+`product.published` (previously only `/confirm` did, so webhook subscribers never saw admin-published products);
+`createOffersWorkflow` refuses offers on products restricted to other sellers or rejected
+(`validateOfferProductsStep`); `GET /admin/products?sku=` filters variants instead of 500ing on `Product.sku`;
+the plugin's event list drops `order.shipment_created`, which nothing emits. Tests: new
+`product/admin/product-publish-and-sku.spec.ts`, three cases in `offer/vendor/offer.spec.ts`, one each in
+`offer/cart/cart.spec.ts` and `offer/order/order.spec.ts`. `bun run build` green (13/13).
+
## Session — Magento connector hardening sweep (2026-10-22), branches `feat/magento-external-payment-capture` (this repo) + `feat/checkout-orders-indexer-platform` (magento2-connector)
Audited `mercurjs/magento2-connector` v0.2.0 for checkout, order, indexing and platform gaps and
diff --git a/integration-tests/http/offer/cart/cart.spec.ts b/integration-tests/http/offer/cart/cart.spec.ts
index 9772bac94..4bdb3b42d 100644
--- a/integration-tests/http/offer/cart/cart.spec.ts
+++ b/integration-tests/http/offer/cart/cart.spec.ts
@@ -165,7 +165,24 @@ medusaIntegrationTestRunner({
})
describe("POST /store/carts/:id/line-items", () => {
- it("should reject add-to-cart when offer_id is missing", async () => {
+ it("creates the cart in the region currency when currency_code is empty", async () => {
+ const response = await api.post(
+ `/store/carts`,
+ {
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: "",
+ },
+ storeHeaders
+ )
+
+ expect(response.status).toEqual(200)
+ expect(response.data.cart.currency_code).toEqual(
+ region.currency_code
+ )
+ })
+
+ it("should reject add-to-cart when offer_id is missing", async () => {
await seedSellerOffer({
name: "Missing Offer",
diff --git a/integration-tests/http/offer/order/order.spec.ts b/integration-tests/http/offer/order/order.spec.ts
index 436501c00..4eb787213 100644
--- a/integration-tests/http/offer/order/order.spec.ts
+++ b/integration-tests/http/offer/order/order.spec.ts
@@ -339,6 +339,18 @@ medusaIntegrationTestRunner({
)
expect(completeResp.status).toEqual(200)
expect(completeResp.data.type).toEqual("order_group")
+ expect(completeResp.data.order_group.orders).toHaveLength(1)
+ expect(completeResp.data.order_group.orders[0]).toEqual(
+ expect.objectContaining({
+ id: expect.any(String),
+ display_id: expect.any(Number),
+ status: expect.any(String),
+ seller: expect.objectContaining({
+ id: expect.any(String),
+ name: expect.any(String),
+ }),
+ })
+ )
const query = appContainer.resolve(
ContainerRegistrationKeys.QUERY
diff --git a/integration-tests/http/offer/vendor/offer.spec.ts b/integration-tests/http/offer/vendor/offer.spec.ts
index 2faa9f34c..8913dffbc 100644
--- a/integration-tests/http/offer/vendor/offer.spec.ts
+++ b/integration-tests/http/offer/vendor/offer.spec.ts
@@ -3,7 +3,11 @@ import { MedusaContainer } from "@medusajs/framework/types"
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
import { createSellerUser } from "../../../helpers/create-seller-user"
import { createShippingProfile } from "../../../helpers/create-shipping-profile"
-import { createVendorProduct } from "../../../helpers/create-product"
+import {
+ assignProductsToSeller,
+ createVendorProduct,
+} from "../../../helpers/create-product"
+import { Modules } from "@medusajs/framework/utils"
import { linkSellerCurrencyRegions } from "../../../helpers/link-seller-regions"
jest.setTimeout(50000)
@@ -14,6 +18,8 @@ medusaIntegrationTestRunner({
let appContainer: MedusaContainer
let seller1Headers: any
let seller2Headers: any
+ let seller1Id: string
+ let seller2Id: string
let seedCounter = 0
const seedSellerOfferDeps = async (headers: any) => {
@@ -52,6 +58,7 @@ medusaIntegrationTestRunner({
name: "Seller One",
})
seller1Headers = result1.headers
+ seller1Id = result1.seller.id
await linkSellerCurrencyRegions(appContainer, result1.seller.id, [
"eur",
"gbp",
@@ -62,6 +69,7 @@ medusaIntegrationTestRunner({
name: "Seller Two",
})
seller2Headers = result2.headers
+ seller2Id = result2.seller.id
})
describe("POST /vendor/offers", () => {
@@ -104,6 +112,71 @@ medusaIntegrationTestRunner({
).toBeDefined()
})
+ it("should reject an offer on a product restricted to other sellers", async () => {
+ const deps = await seedSellerOfferDeps(seller1Headers)
+ await assignProductsToSeller(appContainer, seller2Id, [deps.product_id])
+
+ const response = await api
+ .post(
+ `/vendor/offers`,
+ {
+ sku: "SELLER1-RESTRICTED",
+ variant_id: deps.variant_id,
+ shipping_profile_id: deps.shipping_profile_id,
+ inventory_items: [{ required_quantity: 1 }],
+ prices: [{ amount: 2000, currency_code: "usd" }],
+ },
+ seller1Headers
+ )
+ .catch((e: any) => e.response)
+
+ expect(response.status).toEqual(400)
+ expect(response.data.message).toContain("restricted to other sellers")
+ })
+
+ it("should allow an offer on a product restricted to the offering seller", async () => {
+ const deps = await seedSellerOfferDeps(seller1Headers)
+ await assignProductsToSeller(appContainer, seller1Id, [deps.product_id])
+
+ const response = await api.post(
+ `/vendor/offers`,
+ {
+ sku: "SELLER1-ALLOWED",
+ variant_id: deps.variant_id,
+ shipping_profile_id: deps.shipping_profile_id,
+ inventory_items: [{ required_quantity: 1 }],
+ prices: [{ amount: 2000, currency_code: "usd" }],
+ },
+ seller1Headers
+ )
+
+ expect(response.status).toEqual(201)
+ })
+
+ it("should reject an offer on a rejected product", async () => {
+ const deps = await seedSellerOfferDeps(seller1Headers)
+ await appContainer
+ .resolve(Modules.PRODUCT)
+ .updateProducts(deps.product_id, { status: "rejected" })
+
+ const response = await api
+ .post(
+ `/vendor/offers`,
+ {
+ sku: "SELLER1-REJECTED",
+ variant_id: deps.variant_id,
+ shipping_profile_id: deps.shipping_profile_id,
+ inventory_items: [{ required_quantity: 1 }],
+ prices: [{ amount: 2000, currency_code: "usd" }],
+ },
+ seller1Headers
+ )
+ .catch((e: any) => e.response)
+
+ expect(response.status).toEqual(400)
+ expect(response.data.message).toContain("rejected")
+ })
+
it("should reject create when variant does not exist", async () => {
const deps = await seedSellerOfferDeps(seller1Headers)
diff --git a/integration-tests/http/product/admin/product-publish-and-sku.spec.ts b/integration-tests/http/product/admin/product-publish-and-sku.spec.ts
new file mode 100644
index 000000000..35df08d56
--- /dev/null
+++ b/integration-tests/http/product/admin/product-publish-and-sku.spec.ts
@@ -0,0 +1,104 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import { MedusaContainer } from "@medusajs/framework/types"
+import { Modules } from "@medusajs/framework/utils"
+
+import {
+ adminHeaders,
+ createAdminUser,
+} from "../../../helpers/create-admin-user"
+
+jest.setTimeout(60000)
+
+const waitFor = async (predicate: () => boolean, timeoutMs = 5000) => {
+ const started = Date.now()
+ while (!predicate()) {
+ if (Date.now() - started > timeoutMs) {
+ return
+ }
+ await new Promise((resolve) => setTimeout(resolve, 50))
+ }
+}
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api, dbConnection }) => {
+ describe("Admin - product publishing and SKU filter", () => {
+ let appContainer: MedusaContainer
+ let published: { id: string }[]
+
+ beforeAll(() => {
+ appContainer = getContainer()
+ // The container outlives the tests, so one subscription serves them all.
+ const eventBus = appContainer.resolve(Modules.EVENT_BUS)
+ eventBus.subscribe("product.published", async (event: { data: unknown }) => {
+ const data = Array.isArray(event.data) ? event.data : [event.data]
+ published.push(...(data as { id: string }[]))
+ })
+ })
+
+ beforeEach(async () => {
+ await createAdminUser(dbConnection, adminHeaders, appContainer)
+ published = []
+ })
+
+ const createProduct = async (status: string, sku: string) => {
+ const response = await api.post(
+ `/admin/products`,
+ {
+ title: `Product ${sku}`,
+ status,
+ variants: [{ title: "Default", sku }],
+ },
+ adminHeaders
+ )
+ expect(response.status).toEqual(200)
+
+ return response.data.product
+ }
+
+ it("emits product.published for a product created as published", async () => {
+ const product = await createProduct("published", `PUB-${Date.now()}`)
+
+ await waitFor(() => published.some((p) => p.id === product.id))
+
+ expect(published).toEqual(
+ expect.arrayContaining([expect.objectContaining({ id: product.id })])
+ )
+ })
+
+ it("emits product.published once when a draft is published, not on later edits", async () => {
+ const product = await createProduct("draft", `DRAFT-${Date.now()}`)
+ expect(published).toEqual([])
+
+ const publish = await api.post(
+ `/admin/products/${product.id}`,
+ { status: "published" },
+ adminHeaders
+ )
+ expect(publish.status).toEqual(200)
+ await waitFor(() => published.some((p) => p.id === product.id))
+ expect(published.filter((p) => p.id === product.id)).toHaveLength(1)
+
+ const rename = await api.post(
+ `/admin/products/${product.id}`,
+ { title: "Renamed", status: "published" },
+ adminHeaders
+ )
+ expect(rename.status).toEqual(200)
+ await new Promise((resolve) => setTimeout(resolve, 300))
+ expect(published.filter((p) => p.id === product.id)).toHaveLength(1)
+ })
+
+ it("filters the product list by variant SKU", async () => {
+ const sku = `SKU-${Date.now()}`
+ const product = await createProduct("published", sku)
+ await createProduct("published", `OTHER-${Date.now()}`)
+
+ const response = await api.get(`/admin/products?sku=${sku}`, adminHeaders)
+
+ expect(response.status).toEqual(200)
+ expect(response.data.products).toHaveLength(1)
+ expect(response.data.products[0].id).toEqual(product.id)
+ })
+ })
+ },
+})
diff --git a/packages/core/src/api/admin/products/[id]/route.ts b/packages/core/src/api/admin/products/[id]/route.ts
index 89118c561..9463208ec 100644
--- a/packages/core/src/api/admin/products/[id]/route.ts
+++ b/packages/core/src/api/admin/products/[id]/route.ts
@@ -5,6 +5,8 @@ import {
import {
ContainerRegistrationKeys,
MedusaError,
+ Modules,
+ ProductStatus,
} from "@medusajs/framework/utils"
import { AdditionalData } from "@medusajs/framework/types"
@@ -16,6 +18,7 @@ import {
wrapProductVariantsWithOffers,
} from "../../../utils"
import { productEditDeleteProductWorkflow } from "../../../../workflows/product-edit/workflows/product-edit-delete-product"
+import { ProductWorkflowEvents } from "../../../../workflows/product/events"
import { AdminUpdateProductType } from "../validators"
export const GET = async (
@@ -69,6 +72,15 @@ export const POST = async (
const { additional_data, ...update } = req.validatedBody
+ const publishing = update.status === ProductStatus.PUBLISHED
+ const wasPublished = publishing
+ ? (await query.graph({
+ entity: "product",
+ fields: ["status"],
+ filters: { id: req.params.id },
+ })).data[0]?.status === ProductStatus.PUBLISHED
+ : false
+
await updateProductsWorkflow(req.scope).run({
input: {
selector: { id: req.params.id },
@@ -77,6 +89,14 @@ export const POST = async (
},
})
+ if (publishing && !wasPublished) {
+ const eventBus = req.scope.resolve(Modules.EVENT_BUS)
+ await eventBus.emit({
+ name: ProductWorkflowEvents.PUBLISHED,
+ data: [{ id: req.params.id }],
+ })
+ }
+
const {
data: [product],
} = await query.graph({
diff --git a/packages/core/src/api/admin/products/route.ts b/packages/core/src/api/admin/products/route.ts
index e8a9c07f3..8aba13cdc 100644
--- a/packages/core/src/api/admin/products/route.ts
+++ b/packages/core/src/api/admin/products/route.ts
@@ -28,10 +28,17 @@ export const GET = async (
)
}
+ // `sku` lives on the variant; as a product filter it would hit a column that does not exist.
+ const { sku, ...filters } = req.filterableFields as Record<string, unknown> & { sku?: string }
+ if (sku) {
+ const and = (filters.$and as object[] | undefined) ?? []
+ filters.$and = [...and, { variants: { sku } }]
+ }
+
const { data: products, metadata } = await query.graph({
entity: "product",
fields: req.queryConfig.fields,
- filters: req.filterableFields,
+ filters,
pagination: req.queryConfig.pagination,
})
diff --git a/packages/core/src/api/store/carts/[id]/complete/query-config.ts b/packages/core/src/api/store/carts/[id]/complete/query-config.ts
index ff73d4776..cc0a17bda 100644
--- a/packages/core/src/api/store/carts/[id]/complete/query-config.ts
+++ b/packages/core/src/api/store/carts/[id]/complete/query-config.ts
@@ -6,9 +6,17 @@ export const defaultStoreRetrieveOrderGroupFields = [
"total",
"created_at",
"updated_at",
+ "orders.id",
+ "orders.display_id",
+ "orders.status",
+ "orders.seller.id",
+ "orders.seller.name",
]
+// Store requests strip the `orders` relation unless the route allows it explicitly; the
+// curated list is allowed as is, so the seller's private details stay out of reach.
export const storeCompleteCartQueryConfig = {
defaults: defaultStoreRetrieveOrderGroupFields,
+ allowed: defaultStoreRetrieveOrderGroupFields,
isList: false,
}
diff --git a/packages/core/src/api/store/carts/middlewares.ts b/packages/core/src/api/store/carts/middlewares.ts
index a7c8fed4c..e317509f8 100644
--- a/packages/core/src/api/store/carts/middlewares.ts
+++ b/packages/core/src/api/store/carts/middlewares.ts
@@ -3,6 +3,7 @@ import {
validateAndTransformQuery,
} from "@medusajs/framework/http"
import { MiddlewareRoute } from "@medusajs/medusa"
+import { MedusaNextFunction, MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { ORIGINAL_MIDDLEWARES } from "../../../utils/disable-medusa-middlewares"
import { storeCompleteCartQueryConfig } from "./[id]/complete/query-config"
@@ -33,7 +34,25 @@ const baseCartsMiddlewares = capturedBase.filter((route) => {
)
})
+// An empty currency_code passes Medusa's validator and is stored as is, which
+// later fails every price calculation; the region's currency has to win.
+const dropEmptyCurrencyCode = (
+ req: MedusaRequest<{ currency_code?: unknown }>,
+ _res: MedusaResponse,
+ next: MedusaNextFunction
+) => {
+ if (req.body && typeof req.body === "object" && req.body.currency_code === "") {
+ delete req.body.currency_code
+ }
+ next()
+}
+
export const storeCartsMiddlewares: MiddlewareRoute[] = [
+ {
+ method: ["POST"],
+ matcher: "/store/carts",
+ middlewares: [dropEmptyCurrencyCode],
+ },
...baseCartsMiddlewares,
{
method: ["POST"],
diff --git a/packages/core/src/workflows/offer/steps/index.ts b/packages/core/src/workflows/offer/steps/index.ts
index e0aeead72..bed7dd1aa 100644
--- a/packages/core/src/workflows/offer/steps/index.ts
+++ b/packages/core/src/workflows/offer/steps/index.ts
@@ -9,3 +9,4 @@ export * from "./update-offer-conditions"
export * from "./delete-offer-conditions"
export * from "./validate-offer-conditions"
export * from "./validate-offer-conditions-deletable"
+export * from "./validate-offer-products"
diff --git a/packages/core/src/workflows/offer/steps/validate-offer-products.ts b/packages/core/src/workflows/offer/steps/validate-offer-products.ts
new file mode 100644
index 000000000..4f488e77c
--- /dev/null
+++ b/packages/core/src/workflows/offer/steps/validate-offer-products.ts
@@ -0,0 +1,79 @@
+import { createStep } from "@medusajs/framework/workflows-sdk"
+import {
+ ContainerRegistrationKeys,
+ MedusaError,
+ ProductStatus,
+} from "@medusajs/framework/utils"
+
+export const validateOfferProductsStepId = "validate-offer-products"
+
+export type ValidateOfferProductsStepInput = {
+ offers: { seller_id: string; variant_id: string }[]
+ variants: {
+ id: string
+ product?: { id: string; status?: string } | null
+ }[]
+}
+
+/**
+ * The product–seller link is an allowlist: once a product has any link, only
+ * the linked sellers may sell it. Vendor read routes already honour that; the
+ * offer itself did not, so a seller who knew a variant id could list a product
+ * restricted to others, or one the operator had rejected.
+ */
+export const validateOfferProductsStep = createStep(
+ validateOfferProductsStepId,
+ async ({ offers, variants }: ValidateOfferProductsStepInput, { container }) => {
+ const productByVariant = new Map(
+ variants.map((variant) => [variant.id, variant.product ?? null])
+ )
+ const productIds = Array.from(
+ new Set(
+ offers
+ .map((offer) => productByVariant.get(offer.variant_id)?.id)
+ .filter((id): id is string => !!id)
+ )
+ )
+ if (!productIds.length) {
+ return
+ }
+
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const { data: links } = await query.graph({
+ entity: "product_seller",
+ fields: ["product_id", "seller_id"],
+ filters: { product_id: productIds },
+ })
+
+ const sellersByProduct = new Map<string, Set<string>>()
+ for (const link of links as { product_id: string | null; seller_id: string | null }[]) {
+ if (!link.product_id || !link.seller_id) {
+ continue
+ }
+ if (!sellersByProduct.has(link.product_id)) {
+ sellersByProduct.set(link.product_id, new Set())
+ }
+ sellersByProduct.get(link.product_id)!.add(link.seller_id)
+ }
+
+ for (const offer of offers) {
+ const product = productByVariant.get(offer.variant_id)
+ if (!product) {
+ continue
+ }
+ if (product.status === ProductStatus.REJECTED) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Product ${product.id} was rejected and cannot be offered`
+ )
+ }
+ const allowed = sellersByProduct.get(product.id)
+ if (allowed && !allowed.has(offer.seller_id)) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_ALLOWED,
+ `Product ${product.id} is restricted to other sellers`
+ )
+ }
+ }
+ }
+)
diff --git a/packages/core/src/workflows/offer/workflows/create-offers.ts b/packages/core/src/workflows/offer/workflows/create-offers.ts
index c03318944..2c5ce7857 100644
--- a/packages/core/src/workflows/offer/workflows/create-offers.ts
+++ b/packages/core/src/workflows/offer/workflows/create-offers.ts
@@ -26,6 +26,7 @@ import {
createOffersStep,
ensureVariantPriceSetsStep,
validateOfferConditionsStep,
+ validateOfferProductsStep,
} from "../steps"
import { linkSellerInventoryItemStep } from "../../inventory-item/steps"
import { OfferWorkflowEvents } from "../../events"
@@ -90,11 +91,19 @@ export const createOffersWorkflow: ReturnWorkflow<
"upc",
"price_set.id",
"product.id",
+ "product.status",
...VARIANT_INVENTORY_ATTRIBUTES,
],
filters: { id: variantIds },
}).config({ name: "get-variants" })
+ validateOfferProductsStep({
+ offers: transform({ input }, ({ input }) =>
+ input.offers.map((o) => ({ seller_id: o.seller_id, variant_id: o.variant_id })),
+ ),
+ variants,
+ })
+
const inventoryItemsToCreate = transform(
{ input, variants },
({ input, variants }) => {
diff --git a/packages/core/src/workflows/product/workflows/create-products.ts b/packages/core/src/workflows/product/workflows/create-products.ts
index 235497949..e60a6047f 100644
--- a/packages/core/src/workflows/product/workflows/create-products.ts
+++ b/packages/core/src/workflows/product/workflows/create-products.ts
@@ -17,6 +17,7 @@ import {
removeProductOptionsFromProductStep,
useQueryGraphStep,
} from "@medusajs/medusa/core-flows"
+import { ProductStatus } from "@medusajs/framework/utils"
import {
AttributeType,
CreateProductDTO,
@@ -285,6 +286,20 @@ export const createProductsWorkflow: ReturnWorkflow<
),
})
+ // Only the review flow emitted this, so a product an admin creates as published never reached
+ // the subscribers that mirror published products elsewhere.
+ const publishedIds = transform({ createdProducts }, ({ createdProducts }) =>
+ createdProducts
+ .filter((p) => p.status === ProductStatus.PUBLISHED)
+ .map((p) => ({ id: p.id })),
+ )
+ when(publishedIds, (ids) => ids.length > 0).then(() => {
+ emitEventStep({
+ eventName: ProductWorkflowEvents.PUBLISHED,
+ data: publishedIds,
+ }).config({ name: "emit-created-products-published" })
+ })
+
return new WorkflowResponse(createdProducts, {
hooks: [validate, productsCreated] as const,
})
diff --git a/packages/plugins/magento2-connector/README.md b/packages/plugins/magento2-connector/README.md
index e3de7995b..e4a87ec62 100644
--- a/packages/plugins/magento2-connector/README.md
+++ b/packages/plugins/magento2-connector/README.md
@@ -52,7 +52,8 @@ Run `medusa db:migrate` afterwards.
`{ provider_id: "pp_external_external", data: { reference, channel } }`.
The session is authorized, not captured. Pass `captured_at` only when the
storefront already settled the payment.
-6. `POST /store/carts/:id/complete`.
+6. `POST /store/carts/:id/complete`. The `order_group` in the response lists its child `orders`
+ with each one's `seller`, so the storefront can map its lines to seller orders without further calls.
7. When the storefront invoices the order,
`POST /admin/magento/order-groups/:id/payments/capture` (optional
`{ reference }`). Mercur captures the cart payment once, splits it between
diff --git a/packages/plugins/magento2-connector/src/types/common.ts b/packages/plugins/magento2-connector/src/types/common.ts
index 3b222cad7..4c742ea55 100644
--- a/packages/plugins/magento2-connector/src/types/common.ts
+++ b/packages/plugins/magento2-connector/src/types/common.ts
@@ -21,7 +21,6 @@ export const MAGENTO_WEBHOOK_EVENTS = [
"order.canceled",
"order.fulfillment_created",
"order.fulfillment_canceled",
- "order.shipment_created",
"shipment.created",
"delivery.created",
"order.return_requested",