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.

perf(core): push vendor list seller scoping into SQL and fix order count on cross-module filters (#1678)

Viktor Holike00ec0439d8f
diff --git a/CLAUDE.md b/CLAUDE.md
index 7e89bda58..19b47fd2c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -46,6 +46,7 @@ bun run test:integration:tests # Run integration tests
- ALWAYS use `bun` (never npm, yarn, or pnpm)
- NEVER run `bun run test:integration:http` (runs all packages). Use `bun run test:integration:http -- <pattern>`
+- Run locally only the integration specs for the endpoints you touched. For a repo-wide check, open the PR and read the integration-test jobs there instead of running broad patterns locally: the full suite takes far too long on a laptop, and CI is the source of truth
## Testing a Worktree
diff --git a/bun.lock b/bun.lock
index 567b31449..4e8339616 100644
--- a/bun.lock
+++ b/bun.lock
@@ -352,7 +352,7 @@
"@antfu/ni": "^30.3.0",
"@medusajs/admin-bundler": "2.21.2",
"@medusajs/framework": "2.21.2",
- "@mercurjs/dashboard-sdk": "2.3.6",
+ "@mercurjs/dashboard-sdk": "2.3.8-canary.3",
"@vitejs/plugin-react": "^6.0.3",
"commander": "^15.0.0",
"cosmiconfig": "^9.0.0",
@@ -411,11 +411,12 @@
"@medusajs/framework": "2.21.2",
"@medusajs/icons": "2.21.2",
"@medusajs/medusa": "2.21.2",
+ "@medusajs/order": "2.21.2",
"@medusajs/test-utils": "2.21.2",
"@medusajs/types": "2.21.2",
"@medusajs/ui": "4.2.3",
- "@mercurjs/cli": "2.3.6",
- "@mercurjs/types": "2.3.6",
+ "@mercurjs/cli": "2.3.8-canary.3",
+ "@mercurjs/types": "2.3.8-canary.3",
"@swc/core": "^1.7.28",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
diff --git a/integration-tests/http/order/vendor/order-claim.spec.ts b/integration-tests/http/order/vendor/order-claim.spec.ts
index 98739b22a..c72631bc9 100644
--- a/integration-tests/http/order/vendor/order-claim.spec.ts
+++ b/integration-tests/http/order/vendor/order-claim.spec.ts
@@ -357,6 +357,49 @@ medusaIntegrationTestRunner({
})
})
+ describe("GET /vendor/claims", () => {
+ it("lists only the caller's own claims", async () => {
+ const order1 = await completeCartCheckout(seller1Seed.offer.id)
+ const order2 = await completeCartCheckout(seller2Seed.offer.id)
+
+ const claim1 = (
+ await api.post(
+ `/vendor/claims`,
+ { type: "refund", order_id: order1.id },
+ seller1Seed.headers
+ )
+ ).data.claim
+ const claim2 = (
+ await api.post(
+ `/vendor/claims`,
+ { type: "refund", order_id: order2.id },
+ seller2Seed.headers
+ )
+ ).data.claim
+
+ const asSeller1 = await api.get(`/vendor/claims`, seller1Seed.headers)
+ const ids1 = asSeller1.data.claims.map((c: any) => c.id)
+ expect(ids1).toContain(claim1.id)
+ expect(ids1).not.toContain(claim2.id)
+ expect(asSeller1.data.count).toEqual(1)
+
+ const asSeller2 = await api.get(`/vendor/claims`, seller2Seed.headers)
+ const ids2 = asSeller2.data.claims.map((c: any) => c.id)
+ expect(ids2).toContain(claim2.id)
+ expect(ids2).not.toContain(claim1.id)
+ })
+
+ it("rejects an order_id filter pointing at another seller's order", async () => {
+ const order1 = await completeCartCheckout(seller1Seed.offer.id)
+
+ const response = await api
+ .get(`/vendor/claims?order_id=${order1.id}`, seller2Seed.headers)
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(404)
+ })
+ })
+
describe("/:id sub-routes (seller-scope)", () => {
it("rejects claim-items add from non-owning seller", async () => {
const order = await completeCartCheckout(seller1Seed.offer.id)
diff --git a/integration-tests/http/order/vendor/order-exchange.spec.ts b/integration-tests/http/order/vendor/order-exchange.spec.ts
index 3bdcbb802..759f06f30 100644
--- a/integration-tests/http/order/vendor/order-exchange.spec.ts
+++ b/integration-tests/http/order/vendor/order-exchange.spec.ts
@@ -353,6 +353,49 @@ medusaIntegrationTestRunner({
})
})
+ describe("GET /vendor/exchanges", () => {
+ it("lists only the caller's own exchanges", async () => {
+ const order1 = await completeCartCheckout(seller1Seed.offer.id)
+ const order2 = await completeCartCheckout(seller2Seed.offer.id)
+
+ const exchange1 = (
+ await api.post(
+ `/vendor/exchanges`,
+ { order_id: order1.id },
+ seller1Seed.headers
+ )
+ ).data.exchange
+ const exchange2 = (
+ await api.post(
+ `/vendor/exchanges`,
+ { order_id: order2.id },
+ seller2Seed.headers
+ )
+ ).data.exchange
+
+ const asSeller1 = await api.get(`/vendor/exchanges`, seller1Seed.headers)
+ const ids1 = asSeller1.data.exchanges.map((e: any) => e.id)
+ expect(ids1).toContain(exchange1.id)
+ expect(ids1).not.toContain(exchange2.id)
+ expect(asSeller1.data.count).toEqual(1)
+
+ const asSeller2 = await api.get(`/vendor/exchanges`, seller2Seed.headers)
+ const ids2 = asSeller2.data.exchanges.map((e: any) => e.id)
+ expect(ids2).toContain(exchange2.id)
+ expect(ids2).not.toContain(exchange1.id)
+ })
+
+ it("rejects an order_id filter pointing at another seller's order", async () => {
+ const order1 = await completeCartCheckout(seller1Seed.offer.id)
+
+ const response = await api
+ .get(`/vendor/exchanges?order_id=${order1.id}`, seller2Seed.headers)
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(404)
+ })
+ })
+
describe("/:id sub-routes (seller-scope)", () => {
it("rejects inbound items from non-owning seller", async () => {
const order = await completeCartCheckout(seller1Seed.offer.id)
diff --git a/integration-tests/http/payment/split-order-payments.spec.ts b/integration-tests/http/payment/split-order-payments.spec.ts
index 167abecde..7ebd91a93 100644
--- a/integration-tests/http/payment/split-order-payments.spec.ts
+++ b/integration-tests/http/payment/split-order-payments.spec.ts
@@ -223,6 +223,28 @@ medusaIntegrationTestRunner({
})
}
+ describe("vendor list", () => {
+ it("lists only the payments of the caller's own orders", async () => {
+ const { orderA, orderB } = await checkoutBothSellers()
+ await captureEverything(orderA, orderB)
+
+ const paymentA = await orderPayment(orderA)
+ const paymentB = await orderPayment(orderB)
+
+ const asA = await api.get(`/vendor/payments`, sellerA.headers)
+ expect(asA.status).toEqual(200)
+ const idsA = asA.data.payments.map((p: any) => p.id)
+ expect(idsA).toContain(paymentA.id)
+ expect(idsA).not.toContain(paymentB.id)
+ expect(asA.data.count).toEqual(1)
+
+ const asB = await api.get(`/vendor/payments`, sellerB.headers)
+ const idsB = asB.data.payments.map((p: any) => p.id)
+ expect(idsB).toContain(paymentB.id)
+ expect(idsB).not.toContain(paymentA.id)
+ })
+ })
+
describe("vendor capture", () => {
it("does not let a seller capture the shared payment of a multi-seller cart", async () => {
const { orderA, orderB } = await checkoutBothSellers()
diff --git a/integration-tests/http/payouts/vendor/payouts.spec.ts b/integration-tests/http/payouts/vendor/payouts.spec.ts
index c73d4eec0..4b7a19610 100644
--- a/integration-tests/http/payouts/vendor/payouts.spec.ts
+++ b/integration-tests/http/payouts/vendor/payouts.spec.ts
@@ -378,6 +378,29 @@ medusaIntegrationTestRunner({
expect(listed.currency_code).toEqual("usd")
})
+ it("should not expose a payout to another seller", async () => {
+ const order = await placeOrder(1)
+ const payout = (
+ await createPayoutWorkflow(appContainer).run({
+ input: { order_id: order.id },
+ })
+ ).result
+
+ const other = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Other Payout Seller",
+ })
+
+ const asOther = await api.get(`/vendor/payouts`, other.headers)
+ expect(asOther.status).toEqual(200)
+ expect(asOther.data.payouts.map((p: any) => p.id)).not.toContain(payout.id)
+ expect(asOther.data.count).toEqual(0)
+
+ const asOwner = await api.get(`/vendor/payouts`, sellerHeaders)
+ expect(asOwner.data.payouts.map((p: any) => p.id)).toContain(payout.id)
+ expect(asOwner.data.count).toEqual(1)
+ })
+
it("should reject creating a payout for a non-existent order", async () => {
const { errors } = await createPayoutWorkflow(appContainer).run({
input: { order_id: "order_does_not_exist" },
diff --git a/integration-tests/http/price-lists/vendor/price-lists.spec.ts b/integration-tests/http/price-lists/vendor/price-lists.spec.ts
index b46a9b77b..f5cfdcaf8 100644
--- a/integration-tests/http/price-lists/vendor/price-lists.spec.ts
+++ b/integration-tests/http/price-lists/vendor/price-lists.spec.ts
@@ -107,6 +107,31 @@ medusaIntegrationTestRunner({
expect(response.data.price_lists.length).toBeGreaterThanOrEqual(2)
})
+ it("should not list another seller's price lists", async () => {
+ const own = (
+ await api.post(
+ `/vendor/price-lists`,
+ { title: "Seller One List", description: "Mine" },
+ seller1Headers
+ )
+ ).data.price_list
+ const foreign = (
+ await api.post(
+ `/vendor/price-lists`,
+ { title: "Seller Two List", description: "Theirs" },
+ seller2Headers
+ )
+ ).data.price_list
+
+ const response = await api.get(`/vendor/price-lists`, seller1Headers)
+
+ expect(response.status).toEqual(200)
+ const ids = response.data.price_lists.map((pl: any) => pl.id)
+ expect(ids).toContain(own.id)
+ expect(ids).not.toContain(foreign.id)
+ expect(response.data.count).toEqual(1)
+ })
+
it("should search price lists with q parameter", async () => {
await api.post(
`/vendor/price-lists`,
diff --git a/integration-tests/http/product/vendor/product-variants.spec.ts b/integration-tests/http/product/vendor/product-variants.spec.ts
new file mode 100644
index 000000000..93ec9b9c5
--- /dev/null
+++ b/integration-tests/http/product/vendor/product-variants.spec.ts
@@ -0,0 +1,84 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import { MedusaContainer } from "@medusajs/framework/types"
+
+import { createSellerUser } from "../../../helpers/create-seller-user"
+import {
+ assignProductsToSeller,
+ createVendorProduct,
+} from "../../../helpers/create-product"
+
+jest.setTimeout(60000)
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api }) => {
+ describe("Vendor - product variant list scoping", () => {
+ let appContainer: MedusaContainer
+ let sellerB: any
+ let headersA: any
+ let headersB: any
+
+ beforeAll(() => {
+ appContainer = getContainer()
+ })
+
+ beforeEach(async () => {
+ const a = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Variants A Store",
+ })
+ headersA = a.headers
+ const b = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Variants B Store",
+ })
+ sellerB = b.seller
+ headersB = b.headers
+ })
+
+ const variantIds = async (headers: any) => {
+ const response = await api.get(
+ "/vendor/product-variants?limit=100",
+ headers
+ )
+ expect(response.status).toEqual(200)
+ return response.data.variants.map((v: { id: string }) => v.id)
+ }
+
+ it("lists the seller's own proposed variants plus published ones", async () => {
+ const proposedByA = await createVendorProduct(api, headersA, {
+ title: "A Proposed",
+ status: "proposed",
+ sku: "A-PROPOSED",
+ })
+ const published = await createVendorProduct(api, headersB, {
+ title: "B Published",
+ status: "published",
+ sku: "B-PUBLISHED",
+ })
+
+ const idsA = await variantIds(headersA)
+ expect(idsA).toContain(proposedByA.variants[0].id)
+ expect(idsA).toContain(published.variants[0].id)
+
+ const idsB = await variantIds(headersB)
+ expect(idsB).toContain(published.variants[0].id)
+ expect(idsB).not.toContain(proposedByA.variants[0].id)
+ })
+
+ it("hides variants of a published product restricted to other sellers", async () => {
+ const restrictedToB = await createVendorProduct(api, headersA, {
+ title: "Restricted To B",
+ status: "published",
+ sku: "RESTRICTED-B",
+ })
+ await assignProductsToSeller(appContainer, sellerB.id, [restrictedToB.id])
+
+ const idsA = await variantIds(headersA)
+ expect(idsA).not.toContain(restrictedToB.variants[0].id)
+
+ const idsB = await variantIds(headersB)
+ expect(idsB).toContain(restrictedToB.variants[0].id)
+ })
+ })
+ },
+})
diff --git a/integration-tests/jest.config.js b/integration-tests/jest.config.js
index 8f30db200..3e4e2935c 100644
--- a/integration-tests/jest.config.js
+++ b/integration-tests/jest.config.js
@@ -5,10 +5,11 @@ loadEnv("test", process.cwd())
module.exports = {
transform: {
- // Mercur patches shipped core-flows cart, order and payment files. Jest never
+ // Mercur patches shipped core-flows cart, order and payment files and the
+ // order module's repository utils. Jest never
// consults Node's module hooks, so without this the patches are inert under
// test and the suite silently exercises unpatched code.
- "node_modules[\\\\/].*core-flows[\\\\/]dist[\\\\/](cart|order|payment)[\\\\/].*\\.js$":
+ "node_modules[\\\\/].*(core-flows[\\\\/]dist[\\\\/](cart|order|payment)|order[\\\\/]dist[\\\\/]utils)[\\\\/].*\\.js$":
"@mercurjs/core/patches/jest-transformer",
"^.+\\.[jt]s$": [
"@swc/jest",
@@ -25,7 +26,7 @@ module.exports = {
// order and payment files the patches target, and the ESM-only htmlparser2
// chain that sanitize-html require()s (Jest can't load ESM through require).
transformIgnorePatterns: [
- "/node_modules/(?!.*core-flows[\\\\/]dist[\\\\/](cart|order|payment)[\\\\/]|(?:.*[\\\\/])?(htmlparser2|domhandler|domutils|domelementtype|dom-serializer|entities)[\\\\/]dist[\\\\/])",
+ "/node_modules/(?!.*(core-flows[\\\\/]dist[\\\\/](cart|order|payment)|order[\\\\/]dist[\\\\/]utils)[\\\\/]|(?:.*[\\\\/])?(htmlparser2|domhandler|domutils|domelementtype|dom-serializer|entities)[\\\\/]dist[\\\\/])",
],
moduleFileExtensions: ["js", "ts", "json"],
modulePathIgnorePatterns: ["dist/"],
diff --git a/packages/core/package.json b/packages/core/package.json
index 8505a6464..a0664c5ed 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -55,6 +55,7 @@
"devDependencies": {
"cors": "^2.8.5",
"@medusajs/core-flows": "2.21.2",
+ "@medusajs/order": "2.21.2",
"@medusajs/cli": "2.21.2",
"@medusajs/framework": "2.21.2",
"@medusajs/icons": "2.21.2",
diff --git a/packages/core/src/api/utils/filter-by-seller-id.ts b/packages/core/src/api/utils/filter-by-seller-id.ts
index 3a96bbae3..3bce6ac83 100644
--- a/packages/core/src/api/utils/filter-by-seller-id.ts
+++ b/packages/core/src/api/utils/filter-by-seller-id.ts
@@ -1,12 +1,48 @@
import {
+ AuthenticatedMedusaRequest,
MedusaNextFunction,
- MedusaRequest,
MedusaResponse,
-} from "@medusajs/framework"
+} from "@medusajs/framework/http"
+
+/**
+ * Scopes a list query to the authenticated seller by nesting the seller id
+ * under the given relation path, e.g. `["seller"]` becomes
+ * `filters.seller.id`, `["order", "seller"]` becomes `filters.order.seller.id`.
+ *
+ * Medusa compiles a nested filter on a link relation into a correlated
+ * `EXISTS` subquery on the root entity, so the whole scope stays in SQL and
+ * no link rows are materialised. That only happens when the path sits at the
+ * top level of `filters` (never under `$and` / `$or`) and every hop is a link
+ * or module-internal relation — keep it that way when extending a path.
+ */
+export const applySellerLinkFilter =
+ (path: string[] = ["seller"]) =>
+ (
+ req: AuthenticatedMedusaRequest,
+ _res: MedusaResponse,
+ next: MedusaNextFunction
+ ) => {
+ req.filterableFields ??= {}
+
+ let cursor = req.filterableFields as Record<string, unknown>
+ for (const segment of path) {
+ const existing = cursor[segment]
+ const nested: Record<string, unknown> =
+ existing && typeof existing === "object" && !Array.isArray(existing)
+ ? (existing as Record<string, unknown>)
+ : {}
+ cursor[segment] = nested
+ cursor = nested
+ }
+
+ cursor.id = req.seller_context!.seller_id
+
+ return next()
+ }
export function filterBySellerId() {
return (
- req: MedusaRequest,
+ req: AuthenticatedMedusaRequest,
_res: MedusaResponse,
next: MedusaNextFunction
) => {
diff --git a/packages/core/src/api/vendor/campaigns/middlewares.ts b/packages/core/src/api/vendor/campaigns/middlewares.ts
index 333e030f1..621f8f70d 100644
--- a/packages/core/src/api/vendor/campaigns/middlewares.ts
+++ b/packages/core/src/api/vendor/campaigns/middlewares.ts
@@ -1,9 +1,5 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import {
@@ -21,19 +17,7 @@ import {
VendorUpdateCampaign,
} from "./validators"
-const applySellerCampaignLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "campaign_seller",
- resourceId: "campaign_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+const applySellerCampaignLinkFilter = applySellerLinkFilter()
export const vendorCampaignsMiddlewares: MiddlewareRoute[] = [
{
diff --git a/packages/core/src/api/vendor/customer-groups/middlewares.ts b/packages/core/src/api/vendor/customer-groups/middlewares.ts
index a5a8b5438..c01f91bae 100644
--- a/packages/core/src/api/vendor/customer-groups/middlewares.ts
+++ b/packages/core/src/api/vendor/customer-groups/middlewares.ts
@@ -1,9 +1,5 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import {
@@ -20,19 +16,7 @@ import {
VendorUpdateCustomerGroup,
} from "./validators"
-const applySellerCustomerGroupLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "customer_group_seller",
- resourceId: "customer_group_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+const applySellerCustomerGroupLinkFilter = applySellerLinkFilter()
export const vendorCustomerGroupsMiddlewares: MiddlewareRoute[] = [
{
diff --git a/packages/core/src/api/vendor/customers/middlewares.ts b/packages/core/src/api/vendor/customers/middlewares.ts
index e4d457fc2..7b8e797eb 100644
--- a/packages/core/src/api/vendor/customers/middlewares.ts
+++ b/packages/core/src/api/vendor/customers/middlewares.ts
@@ -1,9 +1,5 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import {
@@ -18,19 +14,7 @@ import {
VendorManageCustomerCustomerGroups,
} from "./validators"
-const applySellerCustomerLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "seller_customer",
- resourceId: "customer_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+const applySellerCustomerLinkFilter = applySellerLinkFilter(["sellers"])
export const vendorCustomersMiddlewares: MiddlewareRoute[] = [
{
diff --git a/packages/core/src/api/vendor/inventory-items/middlewares.ts b/packages/core/src/api/vendor/inventory-items/middlewares.ts
index 3ebb3833c..201a10f9c 100644
--- a/packages/core/src/api/vendor/inventory-items/middlewares.ts
+++ b/packages/core/src/api/vendor/inventory-items/middlewares.ts
@@ -1,9 +1,5 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import {
@@ -25,19 +21,7 @@ import {
VendorUpdateInventoryLocationLevel,
} from "./validators"
-const applySellerInventoryItemLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "inventory_item_seller",
- resourceId: "inventory_item_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+const applySellerInventoryItemLinkFilter = applySellerLinkFilter()
export const vendorInventoryItemsMiddlewares: MiddlewareRoute[] = [
{
diff --git a/packages/core/src/api/vendor/orders/middlewares.ts b/packages/core/src/api/vendor/orders/middlewares.ts
index 86f468e60..0d57e90f5 100644
--- a/packages/core/src/api/vendor/orders/middlewares.ts
+++ b/packages/core/src/api/vendor/orders/middlewares.ts
@@ -1,9 +1,5 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import {
@@ -24,19 +20,7 @@ import {
VendorGetOrdersParams,
} from "./validators"
-const applySellerLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "order_seller",
- resourceId: "order_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+const applySellerOrderLinkFilter = applySellerLinkFilter()
export const vendorOrdersMiddlewares: MiddlewareRoute[] = [
{
@@ -53,7 +37,7 @@ export const vendorOrdersMiddlewares: MiddlewareRoute[] = [
VendorGetOrdersParams,
vendorOrderQueryConfig.list
),
- applySellerLinkFilter,
+ applySellerOrderLinkFilter,
],
},
{
diff --git a/packages/core/src/api/vendor/payments/middlewares.ts b/packages/core/src/api/vendor/payments/middlewares.ts
index cfdf95abc..f26961897 100644
--- a/packages/core/src/api/vendor/payments/middlewares.ts
+++ b/packages/core/src/api/vendor/payments/middlewares.ts
@@ -1,9 +1,5 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import {
@@ -23,19 +19,13 @@ import {
VendorGetPaymentsParams,
} from "./validators"
-const applySellerPaymentLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "seller_payment",
- resourceId: "payment_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+// Order payments hang off the order's payment collection; cart-stage
+// payments are only reachable through the cart and are not listed here.
+const applySellerPaymentLinkFilter = applySellerLinkFilter([
+ "payment_collection",
+ "order",
+ "seller",
+])
export const vendorPaymentsMiddlewares: MiddlewareRoute[] = [
{
diff --git a/packages/core/src/api/vendor/payout-accounts/middlewares.ts b/packages/core/src/api/vendor/payout-accounts/middlewares.ts
index b10d9a98a..f22dbbea9 100644
--- a/packages/core/src/api/vendor/payout-accounts/middlewares.ts
+++ b/packages/core/src/api/vendor/payout-accounts/middlewares.ts
@@ -1,9 +1,5 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import {
@@ -22,19 +18,7 @@ import {
VendorGetPayoutAccountsParams,
} from "./validators"
-const applySellerPayoutAccountLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "seller_payout_account",
- resourceId: "payout_account_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+const applySellerPayoutAccountLinkFilter = applySellerLinkFilter()
export const vendorPayoutAccountsMiddlewares: MiddlewareRoute[] = [
{
diff --git a/packages/core/src/api/vendor/payouts/middlewares.ts b/packages/core/src/api/vendor/payouts/middlewares.ts
index dc745c958..0e911a132 100644
--- a/packages/core/src/api/vendor/payouts/middlewares.ts
+++ b/packages/core/src/api/vendor/payouts/middlewares.ts
@@ -1,9 +1,5 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import { validateAndTransformQuery } from "@medusajs/framework"
@@ -11,19 +7,7 @@ import { validateAndTransformQuery } from "@medusajs/framework"
import { vendorPayoutQueryConfig } from "./query-config"
import { VendorGetPayoutParams, VendorGetPayoutsParams } from "./validators"
-const applySellerPayoutLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "payout_seller",
- resourceId: "payout_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+const applySellerPayoutLinkFilter = applySellerLinkFilter()
export const vendorPayoutsMiddlewares: MiddlewareRoute[] = [
{
diff --git a/packages/core/src/api/vendor/price-lists/middlewares.ts b/packages/core/src/api/vendor/price-lists/middlewares.ts
index fc7d52034..1cc03f4ac 100644
--- a/packages/core/src/api/vendor/price-lists/middlewares.ts
+++ b/packages/core/src/api/vendor/price-lists/middlewares.ts
@@ -1,9 +1,5 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import {
@@ -23,19 +19,7 @@ import {
VendorUpdatePriceListPrice,
} from "./validators"
-const applySellerPriceListLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "price_list_seller",
- resourceId: "price_list_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+const applySellerPriceListLinkFilter = applySellerLinkFilter()
export const vendorPriceListsMiddlewares: MiddlewareRoute[] = [
{
diff --git a/packages/core/src/api/vendor/products/helpers.ts b/packages/core/src/api/vendor/products/helpers.ts
index d7f90c06b..0a04b4a20 100644
--- a/packages/core/src/api/vendor/products/helpers.ts
+++ b/packages/core/src/api/vendor/products/helpers.ts
@@ -1,6 +1,7 @@
import {
ContainerRegistrationKeys,
MedusaError,
+ promiseAll,
} from "@medusajs/framework/utils"
import type { MedusaContainer } from "@medusajs/framework/types"
import { ProductChangeActionType } from "@mercurjs/types"
@@ -26,15 +27,14 @@ export const getSellerOwnedProductIds = async (
},
})
- return actions
- .map(action => action.product_id)
+ return actions.map((action) => action.product_id)
}
/**
* Product ids that are restricted (have at least one `product_seller` row) but
* NOT assigned to this seller — i.e. restricted to other sellers, so they must
* be hidden from this seller's product list. Pass `productIds` to scope the
- * check to a known set instead of scanning every link.
+ * check to a known set; without it only the rows of other sellers are read.
*/
export const getProductIdsRestrictedFromSeller = async (
scope: MedusaContainer,
@@ -46,29 +46,32 @@ export const getProductIdsRestrictedFromSeller = async (
}
const query = scope.resolve(ContainerRegistrationKeys.QUERY)
-
- const { data: links } = await query.graph({
- entity: "product_seller",
- fields: ["product_id", "seller_id"],
- ...(productIds ? { filters: { product_id: productIds } } : {}),
- })
-
- const assigned = new Set<string>()
+ const productScope = productIds ? { product_id: productIds } : {}
+
+ const [{ data: otherSellerLinks }, { data: ownLinks }] = await promiseAll([
+ query.graph({
+ entity: "product_seller",
+ fields: ["product_id"],
+ filters: { seller_id: { $ne: sellerId }, ...productScope },
+ }),
+ query.graph({
+ entity: "product_seller",
+ fields: ["product_id"],
+ filters: { seller_id: sellerId, ...productScope },
+ }),
+ ])
+
+ const assigned = new Set(
+ (ownLinks as { product_id: string | null }[]).map((link) => link.product_id)
+ )
const restricted = new Set<string>()
- for (const link of links as {
- product_id: string | null
- seller_id: string | null
- }[]) {
- if (!link.product_id) {
- continue
- }
- restricted.add(link.product_id)
- if (link.seller_id === sellerId) {
- assigned.add(link.product_id)
+ for (const link of otherSellerLinks as { product_id: string | null }[]) {
+ if (link.product_id && !assigned.has(link.product_id)) {
+ restricted.add(link.product_id)
}
}
- return Array.from(restricted).filter((id) => !assigned.has(id))
+ return Array.from(restricted)
}
export const getProductStatus = async (
diff --git a/packages/core/src/api/vendor/promotions/middlewares.ts b/packages/core/src/api/vendor/promotions/middlewares.ts
index d7dced973..e74150462 100644
--- a/packages/core/src/api/vendor/promotions/middlewares.ts
+++ b/packages/core/src/api/vendor/promotions/middlewares.ts
@@ -1,9 +1,5 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import {
@@ -25,19 +21,7 @@ import {
} from "./validators"
import { createBatchBody } from "@medusajs/medusa/api/utils/validators"
-const applySellerPromotionLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "promotion_seller",
- resourceId: "promotion_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+const applySellerPromotionLinkFilter = applySellerLinkFilter()
export const vendorPromotionsMiddlewares: MiddlewareRoute[] = [
{
diff --git a/packages/core/src/api/vendor/returns/middlewares.ts b/packages/core/src/api/vendor/returns/middlewares.ts
index b23a336a7..2ef6eb195 100644
--- a/packages/core/src/api/vendor/returns/middlewares.ts
+++ b/packages/core/src/api/vendor/returns/middlewares.ts
@@ -1,7 +1,6 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
MedusaNextFunction,
MedusaResponse,
MiddlewareRoute,
@@ -40,17 +39,9 @@ const applySellerOrderLinkFilter = async (
req.seller_context!.seller_id,
req.filterableFields.order_id as string | string[]
)
- return next()
}
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "order_seller",
- resourceId: "order_id",
- filterableField: "seller_id",
- filterByField: "order_id",
- })(req, res, next)
+ return applySellerLinkFilter(["order", "seller"])(req, res, next)
}
export const vendorReturnsMiddlewares: MiddlewareRoute[] = [
diff --git a/packages/core/src/api/vendor/reviews/middlewares.ts b/packages/core/src/api/vendor/reviews/middlewares.ts
index 2e3462d31..6a5acfe0e 100644
--- a/packages/core/src/api/vendor/reviews/middlewares.ts
+++ b/packages/core/src/api/vendor/reviews/middlewares.ts
@@ -1,9 +1,5 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import {
@@ -11,23 +7,10 @@ import {
validateAndTransformQuery,
} from "@medusajs/framework"
-import sellerReview from "../../../links/seller-review"
import { vendorReviewQueryConfig } from "./query-config"
import { VendorGetReviewsParams, VendorRespondReview } from "./validators"
-const applySellerReviewLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: sellerReview.entryPoint,
- resourceId: "review_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+const applySellerReviewLinkFilter = applySellerLinkFilter()
export const vendorReviewsMiddlewares: MiddlewareRoute[] = [
{
diff --git a/packages/core/src/api/vendor/shipping-options/middlewares.ts b/packages/core/src/api/vendor/shipping-options/middlewares.ts
index 61fce2899..7caa2c200 100644
--- a/packages/core/src/api/vendor/shipping-options/middlewares.ts
+++ b/packages/core/src/api/vendor/shipping-options/middlewares.ts
@@ -1,9 +1,6 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import {
@@ -26,19 +23,7 @@ import {
VendorUpdateShippingOptionRule,
} from "./validators"
-const applySellerShippingOptionLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "shipping_option_seller",
- resourceId: "shipping_option_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+const applySellerShippingOptionLinkFilter = applySellerLinkFilter()
export const vendorShippingOptionsMiddlewares: MiddlewareRoute[] = [
{
diff --git a/packages/core/src/api/vendor/stock-locations/middlewares.ts b/packages/core/src/api/vendor/stock-locations/middlewares.ts
index 1924560ae..ea5e1769e 100644
--- a/packages/core/src/api/vendor/stock-locations/middlewares.ts
+++ b/packages/core/src/api/vendor/stock-locations/middlewares.ts
@@ -1,9 +1,5 @@
-import { requirePermission } from "../../utils"
+import { applySellerLinkFilter, requirePermission } from "../../utils"
import {
- AuthenticatedMedusaRequest,
- maybeApplyLinkFilter,
- MedusaNextFunction,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import {
@@ -21,19 +17,7 @@ import {
VendorUpdateStockLocation,
} from "./validators"
-const applySellerStockLocationLinkFilter = (
- req: AuthenticatedMedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- req.filterableFields.seller_id = req.seller_context!.seller_id
-
- return maybeApplyLinkFilter({
- entryPoint: "stock_location_seller",
- resourceId: "stock_location_id",
- filterableField: "seller_id",
- })(req, res, next)
-}
+const applySellerStockLocationLinkFilter = applySellerLinkFilter()
export const vendorStockLocationsMiddlewares: MiddlewareRoute[] = [
{
diff --git a/packages/core/src/patches/README.md b/packages/core/src/patches/README.md
index 7d72eccd8..1e126a33a 100644
--- a/packages/core/src/patches/README.md
+++ b/packages/core/src/patches/README.md
@@ -51,11 +51,11 @@ through `transformIgnorePatterns` (see `integration-tests/jest.config.js`):
```js
transform: {
- "node_modules[\\/].*core-flows[\\/]dist[\\/](cart|order|payment)[\\/].*\\.js$":
+ "node_modules[\\/].*(core-flows[\\/]dist[\\/](cart|order|payment)|order[\\/]dist[\\/]utils)[\\/].*\\.js$":
"@mercurjs/core/patches/jest-transformer",
"^.+\\.[jt]s$": ["@swc/jest", { /* ... */ }],
},
-transformIgnorePatterns: ["/node_modules/(?!.*core-flows[\\/]dist[\\/](cart|order|payment)[\\/])"],
+transformIgnorePatterns: ["/node_modules/(?!.*(core-flows[\\/]dist[\\/](cart|order|payment)|order[\\/]dist[\\/]utils)[\\/])"],
```
Both paths funnel through `patchSourceForPath`, so a patch means the same thing
diff --git a/packages/core/src/patches/jest-transformer.ts b/packages/core/src/patches/jest-transformer.ts
index 9b1f2ca7c..c6b41e3db 100644
--- a/packages/core/src/patches/jest-transformer.ts
+++ b/packages/core/src/patches/jest-transformer.ts
@@ -15,11 +15,11 @@ import { PATCHES } from "./manifest"
// through `transformIgnorePatterns`:
//
// transform: {
-// "node_modules[\\\\/].*core-flows[\\\\/]dist[\\\\/](cart|order|payment)[\\\\/].*\\.js$":
+// "node_modules[\\\\/].*(core-flows[\\\\/]dist[\\\\/](cart|order|payment)|order[\\\\/]dist[\\\\/]utils)[\\\\/].*\\.js$":
// "@mercurjs/core/patches/jest-transformer",
// "^.+\\.[jt]s$": ["@swc/jest", { ... }],
// },
-// transformIgnorePatterns: ["/node_modules/(?!.*core-flows[\\\\/]dist[\\\\/](cart|order|payment)[\\\\/])"],
+// transformIgnorePatterns: ["/node_modules/(?!.*(core-flows[\\\\/]dist[\\\\/](cart|order|payment)|order[\\\\/]dist[\\\\/]utils)[\\\\/])"],
type TransformOutput = { code: string }
diff --git a/packages/core/src/patches/manifest.ts b/packages/core/src/patches/manifest.ts
index 695556b37..9cb130689 100644
--- a/packages/core/src/patches/manifest.ts
+++ b/packages/core/src/patches/manifest.ts
@@ -59,4 +59,16 @@ export const PATCHES: PatchEntry[] = [
"payable, and that release must run in the delivery's own transaction, with " +
"compensation, so it needs fulfillmentDelivered.",
},
+ {
+ file: "@[email protected]",
+ package: "@medusajs/order",
+ compatible: { from: "2.21.0", to: "2.22.0" },
+ reason:
+ "The order module's findAndCount runs find and count as two queries over " +
+ "the same where clause. A cross-module filter (filters.seller.id on orders, " +
+ "returns, claims, exchanges) is a MikroORM raw EXISTS fragment that the " +
+ "registry drops after its first use, so the count query renders the dead " +
+ "key as a column and every paginated vendor list 500s. The patch gives the " +
+ "count its own copy of each fragment.",
+ },
]
diff --git a/packages/core/src/patches/patches/@[email protected] b/packages/core/src/patches/patches/@[email protected]
new file mode 100644
index 000000000..71970ab33
--- /dev/null
+++ b/packages/core/src/patches/patches/@[email protected]
@@ -0,0 +1,46 @@
+diff --git a/dist/utils/base-repository-find.js b/dist/utils/base-repository-find.js
+index 1003e55..9d8c693 100644
+--- a/dist/utils/base-repository-find.js
++++ b/dist/utils/base-repository-find.js
+@@ -28,6 +28,25 @@ function applyCrossModuleJoins(repository, findOptions, manager) {
+ }
+ return augmented;
+ }
++function cloneWhereWithFreshRawFragments(where) {
++ if (Array.isArray(where)) {
++ return where.map(cloneWhereWithFreshRawFragments);
++ }
++ if (where === null ||
++ typeof where !== "object" ||
++ Object.getPrototypeOf(where) !== Object.prototype) {
++ return where;
++ }
++ const cloned = {};
++ for (const key of Object.keys(where)) {
++ const fragment = core_1.RawQueryFragment.getKnownFragment(key, false);
++ const nextKey = fragment
++ ? (0, core_1.raw)(fragment.sql, fragment.params)
++ : key;
++ cloned[nextKey] = cloneWhereWithFreshRawFragments(where[key]);
++ }
++ return cloned;
++}
+ function ensureOrderItemFieldsSelection(config, isRelatedEntity) {
+ const populate = config.options?.populate ?? [];
+ const fields = config.options?.fields ?? [];
+@@ -272,9 +291,14 @@ function setFindMethods(klass, entity) {
+ // control which items to load (not which root entities to count), we run
+ // find and count separately with different populateWhere options.
+ const countOptions = { ...config.options, populateWhere: undefined };
++ // `find` and `count` each consume the raw fragments in the where clause
++ // (the cross-module EXISTS filters). MikroORM drops a fragment from its
++ // registry on first use, so the second query would meet a dead key and
++ // render it as a column name. Hand the count its own copy of each one.
++ const countWhere = cloneWhereWithFreshRawFragments(config.where);
+ const [result, count] = await Promise.all([
+ manager.find(this.entity, config.where, config.options),
+- manager.count(this.entity, config.where, countOptions),
++ manager.count(this.entity, countWhere, countOptions),
+ ]);
+ if (loadAdjustments || shouldLoadShippingAdjustments) {
+ const orders = !isRelatedEntity