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): checkout lock units, batched commission rates, scoped vendor product checks, list indexes (#1677)

Viktor Holike79179d096a0
diff --git a/claude-progress.md b/claude-progress.md
index be3f73c9b..1ef31dd4d 100644
--- a/claude-progress.md
+++ b/claude-progress.md
@@ -14,6 +14,18 @@ session detail aggressively. The per-spec source of truth lives in
`bun run test:integration:http -- <pattern>`
- **Current blocker**: none
+## Session — Core hot-path performance (2026-10-21), branch `perf/core-hot-path-optimizations`, PR #1677
+
+Technique catalog from the Medusa source in `docs/PERFORMANCE.md` (section 4 lists what this branch
+applied, section 5 the remaining checklist). Fixed: checkout lock timeout/ttl/retention passed in ms
+instead of s; cart lock skipped on the webhook-driven completion path; commission rates loaded once per
+checkout via `getCommissionLinesBatch`; vendor single-product scoping no longer scans `product_seller`;
+cache opt-in on reference reads; order-group SQL soft-delete joins; composite partial indexes on
+order_group/offer/payout/review/commission_rule (+ migrations). Verified locally: core tsc, unit specs
+4/4, `commission-rates/admin/(commission-providers|commission-calculation)` 15/15; other suites on CI.
+Gotcha: the order module decorates totals only when a top-level total field (e.g. `subtotal`) is
+selected, and needs `items.*` to derive line totals. Follow-ups listed in the PR body.
+
## Session — Dashboard extensions, OS deltas D-001…D-005 (2026-10-20), branch `feat/dashboard-layout-composer`
Spec: `docs/specs/spec-dashboard-extensions/` (local; `docs/specs` is gitignored), `in_progress`. PR #1674.
diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md
new file mode 100644
index 000000000..50ca2f2ea
--- /dev/null
+++ b/docs/PERFORMANCE.md
@@ -0,0 +1,349 @@
+# Performance techniques from Medusa core, and how Mercur should apply them
+
+Catalog of the optimization techniques used inside Medusa 2.x (read from the
+`develop` branch, 2.21.0, which matches the pins in this repo). Every item names
+where the technique lives in the Medusa source, what it does, and the rule Mercur
+should follow. Paths are relative to the Medusa monorepo `packages/` directory.
+
+## 1. Workflows
+
+### 1.1 Keep hot-path workflows non-stored
+- `orchestration/src/transaction/distributed-transaction.ts:514`,
+ `transaction-orchestrator.ts:1514-1523`
+- A workflow writes a checkpoint to Redis/DB at every step boundary only if it
+ has `retentionTime`, `idempotent`, `timeout`, `retryInterval`, `store`, or an
+ `async` step. Medusa's cart workflows have none of these, so they run fully in
+ memory. `completeCartWorkflow` is the deliberate exception
+ (`store: true, retentionTime: 3 days`), and gets idempotency from the
+ `order_cart` link check plus a lock, not from `idempotent: true`.
+- **Mercur rule:** never add those options to cart, offer, pricing, or listing
+ workflows. Get completion idempotency from a domain check (does the link
+ exist?). Do not pass deterministic `transactionId`s on high-frequency routes
+ (Medusa removed them in commit `990691e78a`).
+
+### 1.2 `parallelize()` independent steps
+- 94 call sites in `core/core-flows`. `complete-cart.ts:648` runs link
+ creation, `completed_at`, inventory reservation, promotion usage, and the
+ `order.placed` event together. `create-carts.ts:204` runs sales channel,
+ region and customer lookups together.
+- **Mercur rule:** seller lookup, commission rule resolution, and payout reads
+ that do not depend on each other go in one `parallelize`.
+
+### 1.3 `when()` guards and "skip if unchanged"
+- `refresh-cart-items.ts:158,202,251`: full repricing only on `force_refresh`,
+ which `update-cart.ts:390` sets only when region, locale, or tax-relevant
+ address changed. Otherwise only the touched line items get tax lines.
+- `refresh-payment-collection.ts:124`: skips when amount and currency match.
+ `refresh-cart-shipping-methods.ts:64`: skips when the cart has no methods.
+- `complete-cart.ts:409`: the whole order branch is `when(!orderId)`.
+- **Mercur rule:** gate commission recompute, split-order creation, and seller
+ notifications on what actually changed. Every step returns early on empty
+ input (30+ examples in `cart/steps`).
+
+### 1.4 Nested locks are skipped
+- `locking/steps/acquire-lock.ts:69`: inside a sub-workflow the step returns
+ `StepResponse.skip()` unless `executeOnSubWorkflow` is set. Cart workflows use
+ `timeout: 2, ttl: 10`; `completeCart` uses `timeout: 30, ttl: 120`.
+- **Mercur rule:** use `acquireLockStep` on `cart_id` in split-order completion
+ with the same values. Lock inventory per inventory item
+ (`reserve-inventory.ts:88`), never per seller or globally.
+
+### 1.5 Pass loaded data into sub-workflows
+- Refresh sub-workflows accept `cart?` and fetch only `when(!input.cart)`.
+ Purpose-built field constants live in `cart/utils/fields.ts`
+ (`completeCartFields`, `cartFieldsForPricingContext`, ...).
+- `get-variants-and-items-with-prices.ts` indexes variants in a `Map` (commit
+ `5cc7fdef18`) so per-item lookup is O(1).
+- **Mercur rule:** define per-purpose field constants, accept a preloaded entity
+ in sub-workflows, use `Map` lookups in `transform`, and return several fields
+ from one `transform` since results are memoized per transaction.
+
+### 1.6 One bulk read, one bulk write
+- `get-line-item-actions.ts:61`: one `listLineItems` with an `id` array, split
+ into create/update sets. `update-line-items.ts:55`: one list (as the
+ compensation snapshot) and one `updateLineItems(items)`.
+- `get-variant-price-sets.ts:117`: prices grouped by context, one
+ `calculatePrices` per distinct context, not per item.
+- **Mercur rule:** pass `{ id, ...data }[]` to module update methods. Never
+ selector-per-row.
+
+### 1.7 Cheap compensation
+- `getSelectsAndRelationsFromObjectArray(data)` (51 files) snapshots only the
+ columns being changed. Deletes are soft in the forward step and restored by
+ ID in compensation. Read-only steps have no compensate function.
+- Payment is authorized last in `completeCart` (`complete-cart.ts:684`) so the
+ rollback window is small.
+
+### 1.8 Chunking and async steps for long work
+- Import: 1000 CSV rows per chunk (`normalize-products-to-chunks.ts:93`),
+ processed by an `async: true` step that frees memory between chunks.
+ Export: batch size 50. Translations: 100.
+- `async: true, backgroundExecution: true` on export, import, and reindex
+ workflows. The HTTP request returns at once.
+- **Mercur rule:** vendor CSV import/export, payout batches, and reindex use
+ async background steps with 50 to 1000 item chunks. Never on cart paths.
+
+### 1.9 Query cache inside workflows
+- `useQueryGraphStep` with `options.cache.enable: true` for reference data
+ (region, shipping options, promotion codes, customer). Variant queries use
+ `computeAutomaticTags: true` plus explicit link-table tags in
+ `cart/utils/fields.ts:212`.
+- **Mercur rule:** Mercur link tables (seller-product, seller-order, offer
+ links) need explicit `Link<Name>:list:*` tags or cached results go stale.
+
+## 2. Query and data layer
+
+### 2.1 How `query.graph` avoids N+1
+- `core/query/src/joiner/remote-joiner.ts`, `execute.ts:386-516`. The query is
+ compiled into stages by depth and service; IDs are unioned and deduplicated so
+ each relation level costs one `list({ [fk]: ids })` per module. Sibling stages
+ run in parallel. ID sets over 4000 are chunked with concurrency 10
+ (`module-data-fetcher.ts:14`).
+- Nested relations are fetched without a limit (`module-data-fetcher.ts:263`).
+- A count query runs only when `skip` or `cursor` is set; `take` alone does not.
+- **Mercur rule:** one `query.graph` with explicit `fields`, never a loop over
+ sellers calling services. Each link hop adds one sequential stage. Do not
+ expand unbounded one-to-many links (seller to products) in list views. Pass
+ only `take` for internal lookups to avoid the COUNT.
+
+### 2.2 Cross-module filters stay in SQL only under conditions
+- `core/query/src/joiner/cross-module-joins/index.ts`,
+ `utils/src/dal/mikro-orm/cross-module-query/augment-find-options.ts`.
+ Filters and sorts on linked entities are rewritten into `EXISTS` subqueries
+ if every hop is a link module or DML relation, all modules share the same
+ database connection, and the field is a persisted, non-computed DML column.
+ Otherwise the filter becomes "residual": the whole root set is loaded and
+ filtered in memory, and pagination is re-applied afterwards
+ (`execute.ts:61-149`).
+- **Mercur rule:** keep every Mercur module on the shared connection (no
+ `database.clientUrl`), use `model.define`, and filter only on persisted
+ columns. This is the biggest cliff: filtering products by a seller field with
+ pagination otherwise falls into memory.
+
+### 2.3 MikroORM settings
+- `mikro-orm-create-connection.ts:103`: `useBatchInserts`, `useBatchUpdates`,
+ `batchSize: 100`, `implicitTransactions: false`,
+ `autoJoinRefsForFilters: false`, metadata cache on.
+- Default load strategy is `BALANCED` with forced LEFT JOIN populates
+ (`mikro-orm-repository.ts:1535-1620`). Override per call with
+ `config.options.strategy: "select-in"` for wide one-to-many populates.
+- Each `@InjectManager` call forks the entity manager, so the identity map is
+ per call. Transactions are reused only when `sharedContext` is threaded.
+- `upsertWithReplace` does one SELECT, one bulk INSERT, then chunked
+ `nativeUpdateMany` in parallel (`mikro-orm-repository.ts:1294`).
+- Product repository splits deep populates into one `populate` call per
+ relation to dodge a MikroORM slow path (`product/src/repositories/product.ts:76`).
+- Inventory quantities are computed with raw knex sums
+ (`inventory/src/repositories/inventory-level.ts:13`).
+- **Mercur rule:** thread `@MedusaContext() sharedContext` through every nested
+ service call. Use bulk `create`/`update` arrays and `upsertWithReplace` for
+ vendor imports. Raw knex is acceptable for aggregates.
+
+### 2.4 Indexes
+- DML indexes are partial on `deleted_at IS NULL` by default
+ (`dml/helpers/entity-builder/build-indexes.ts:17`). Every `belongsTo` FK and
+ every `deleted_at` column is indexed automatically. Link tables get FK and
+ `deleted_at` indexes (`link-modules/src/utils/generate-entity.ts:104`), but
+ `extraColumns` are not indexed.
+- Composite example `pricing/src/models/price-rule.ts:15`:
+ `["price_id","attribute","operator"]` unique and `["attribute","value","price_id"]`.
+ GIN on jsonb: `price-list-rule.ts:22` (`type: "gin"`).
+- **Mercur rule:** declare composite indexes for every filter combination used
+ on list routes (`seller_id + status`, `seller_id + created_at`, offer
+ `seller_id + sku`). Any raw SQL must include `deleted_at IS NULL` or the
+ partial indexes are skipped. Add migrations for link `extraColumns` you
+ filter on.
+
+### 2.5 Pricing
+- `pricing/src/repositories/pricing.ts:66-315`: candidate prices come from one
+ knex query. Price-list rule matching uses a derived table with
+ `COUNT(*) FILTER (...) = rules_count` and jsonb `@>`; price rules use a
+ `LATERAL` subquery. Denormalized `rules_count` columns avoid counting at
+ query time. Contexts with more than 10 keys are pruned against a cached
+ distinct-attribute set.
+- **Mercur rule:** offer-scoped prices as `offer_id` price rules already use
+ this single-query path. Pass the pricing context through
+ `QueryContext(req.pricingContext)` on `variants.calculated_price`. Never call
+ `calculatePrices` per variant. Keep the context under 10 keys.
+
+### 2.6 Index engine
+- `modules/index`: denormalized `index_data` (jsonb, GIN `jsonb_path_ops`,
+ partitioned per entity) and `index_relation` tables. Synced by events in
+ batches of 100 IDs, with full resync by keyset cursor under a lock. Listing
+ runs `SELECT DISTINCT root.id` with jsonb containment filters, then hydrates
+ via `query.graph`. Count is `count_estimate()` from EXPLAIN, only when `skip`
+ is set. Sync and listeners run only in worker/shared mode.
+- **Mercur rule:** mark the seller-product link `filterable` so Seller is
+ ingested and seller filtering stays inside the index. Accept estimated
+ counts. Entity IDs must be ULIDs for keyset sync.
+
+### 2.7 Pool, transactions, replicas
+- One shared knex pool for all internal modules. `pool.min` defaults to 2,
+ `pool.max` has no Medusa default (knex uses 10). Config via
+ `databaseDriverOptions.pool`. Parallel joiner stages can use up to 10
+ connections per request.
+- No read replica support anywhere in core.
+- **Mercur rule:** set `pool: { min: 2, max: 20 }` per process and size
+ `(servers + workers) * max` within Postgres or PgBouncer limits.
+
+### 2.8 Events
+- Bulk service methods emit one message with `data.id` as an array
+ (`event-builder-factory.ts:28`). Workflows group events by `eventGroupId`
+ and release them only after commit (`workflow-export.ts:636`), staged in
+ Redis with a 600 s TTL. Only events with subscribers are enqueued, via one
+ `addBulk`.
+- **Mercur rule:** subscribers must handle `id: string[]`. Emit from workflows
+ with `emitEventStep` so events are dropped on rollback. Emit arrays in one
+ call.
+
+## 3. HTTP layer, caching, runtime
+
+### 3.1 There is no HTTP response cache
+Caching is at the data layer only: the `cache` option on `query.graph` and
+`query.index`, active only when `MEDUSA_FF_CACHING=true` and the Caching Module
+with a provider is registered. Medusa Cloud's published gains
+(`www/apps/cloud/app/cache/page.mdx`):
+
+| Endpoint | Before | After |
+|---|---|---|
+| GET /store/products | 354 ms | 83 ms |
+| GET /store/products/:id | 161 ms | 123 ms |
+| POST /store/carts/:id/line-items | 697 ms | 427 ms |
+| POST /store/carts/:id/complete | 1357 ms | 1018 ms |
+| GET /store/shipping-options | 272 ms | 173 ms |
+
+- Keys hash fields, filters, pagination, pricing context, and locale, so
+ entries split per region and customer group. Invalidation is tag-based and
+ driven by a `*` event subscriber that parses `<entity>.<op>` events into
+ `Entity:id` and `Entity:list:*` tags. In-flight identical gets are coalesced.
+ Redis provider gzips payloads over 2 KB and uses pipelines.
+- `useCache(cb, { key, tags, ttl })` and the `@Cached` decorator wrap any
+ computation, and are no-ops when caching is off.
+- **Mercur rule:** pass `{ cache: { enable: true }, locale }` on seller and
+ product listing routes, as the core store products route does. Emit Mercur
+ module events as `seller.updated`, `commission_rate.updated` with `{ id }`
+ so Seller entries invalidate. Always select `id` in cached queries. Wrap
+ commission rule resolution and seller shipping aggregation in `useCache`.
+ Never mutate cached results in place (memory provider uses `useClones:
+ false`). Use a separate `CACHE_REDIS_URL` so cache evictions do not touch
+ queues. Core gaps to fix in Mercur copies: `setTaxContext` refetches the
+ region without cache, and customer groups in `setPricingContext` are not
+ cached.
+
+### 3.2 Worker mode and clustering
+- `workerMode`: `shared` (default), `server`, `worker`. In `worker` mode there
+ is no Express app. Subscribers load everywhere so servers know which events
+ to enqueue, but only workers process them. Scheduled jobs, workflow engine
+ retries, index sync, and the cleaner run only in worker/shared.
+- `medusa start --cluster N --servers X --workers Y` forks processes and
+ re-forks crashed ones.
+- **Mercur rule:** production runs N `WORKER_MODE=server` replicas plus one or
+ more `worker`. Mercur subscribers and payout jobs then run off the request
+ path automatically. Never do heavy work in `onApplicationStart` without
+ checking `worker_mode !== "server"`.
+
+### 3.3 Query config and limits
+- Store routes get `storeRelationsLimit` 3 (default) or per-route override;
+ the products route uses 4. `fields` nested deeper than 2 levels are rejected.
+ Default list limit is 50, and there is no maximum `limit` in core.
+- **Mercur rule:** `/vendor/*` routes never get `req.storeRelationsLimit`, so
+ add a vendor middleware that sets it. Add `.max(100)` to Mercur find-params
+ `limit`. Use `allowFields(...)` instead of widening core allowlists. Request
+ `inventory_quantity` only when needed. Vendor product lists must use curated
+ fields, never the `*`-relation defaults.
+
+### 3.4 Express settings
+- Gzip is off by default (`http.compression.enabled`, threshold 1 KB). Enable
+ only without a CDN or nginx in front.
+- Body parsers are memoized per config; routes can set `bodyParser: false`
+ (multer uploads) or `preserveRawBody: true` (Stripe Connect webhooks only).
+- Sessions use Redis when `redisUrl` is set; without it every node has its own
+ in-memory store and horizontal scaling breaks. Session `resave: true` by
+ default; set `false` to cut Redis writes. Bearer JWT for the vendor panel
+ skips session lookups entirely.
+
+### 3.5 Redis modules
+- Event bus: `removeOnComplete: true`, `attempts: 1`, worker `concurrency: 1`
+ on Cloud. Set `workerOptions.concurrency: 5-10` on workers if Mercur
+ subscribers are I/O-bound and idempotent. Pass `attempts` and `backoff` per
+ emit for notification events.
+- Locking: default lease 60 s, auto-renewed every lease/3, wait timeout 5 s,
+ retry 20 ms with exponential backoff and jitter. Register `locking-redis` as
+ the default provider in multi-instance deployments.
+- Workflow engine: three queues (main, jobs, cleaner) with separate
+ `workerOptions.concurrency`. The Redis storage writes to Postgres only at
+ handover points (commit `bd206cb250`) and uses pipelines with `NX` for
+ "already started" detection. Keep `retentionTime` short or unset so
+ `workflow_execution` stays small.
+
+### 3.6 Store product listing path (reference for seller-scoped listing)
+Middleware chain in `medusa/src/api/store/products/middlewares.ts`:
+authenticate (optional) → validate query (limit 50, depth 4) → sales channel
+filter from publishable key → `applyMaybeLinkFilterIfNecessary` (skips the link
+pre-query when the index engine is on, or when only one sales channel exists)
+→ default filters → `normalizeDataForContext` (region from cart or cached store
+default) → `setPricingContext` (cached region, uncached customer groups) →
+`setTaxContext` → clear context keys. Handler uses `query.index` when the flag
+is on and no tag/category/option filters are present, otherwise `query.graph`,
+both with `cache: { enable: true }`. Tax prices are wrapped in one batched
+`getTaxLines` call after the query.
+
+**Mercur rule:** reuse `normalizeDataForContext`, `setPricingContext`, and
+`setTaxContext` from `@medusajs/medusa/api/utils/middlewares`. Copy the
+"skip the filter when only one exists" trick for seller filters.
+
+## 4. Applied on `perf/core-hot-path-optimizations`
+
+- Checkout: lock timeout/ttl and `retentionTime` were passed in milliseconds
+ (an 8 hour lock wait, 33 hour lock, 8 year retention); now seconds like core.
+ The cart lock is also taken when checkout runs nested under
+ `processPaymentWorkflow`, which releases its own lock first. Shipping
+ options, promotion sellers, seller-customer links and offer inventory are
+ read in one `parallelize`; link creation and offer-link mirroring join the
+ post-order fan-out.
+- Commission: `getCommissionLinesBatch` on the module service and system
+ provider loads the rate table once per checkout instead of once per seller
+ order. The order fetch is trimmed to the fields the context builder reads.
+ Providers may implement the optional batch method; the module falls back to
+ per-context calls otherwise.
+- Split payments: lock taken on the nested path, two reads parallelized.
+- Steps: early returns on empty input for offer create/update and every
+ `link-seller-*` step; offer updates pass `{ id, ...data }` so the module does
+ one lookup instead of one per selector.
+- Vendor product scoping: single-product visibility and ownership checks are
+ filtered by `product_id` instead of loading the whole `product_seller`
+ table and every product the seller ever created.
+- Cache opt-in on reference reads: visible sellers, sales-channel stock
+ locations, seller regions and currencies, store product list and detail
+ (with locale).
+- Order-group list SQL: soft-deleted orders, links and summaries excluded from
+ the aggregates and filters.
+- Indexes: `order_group` (cart_id, customer_id+created_at, created_at),
+ `offer` (seller_id+created_at, product_id+seller_id+created_at), `payout`
+ (account_id+created_at, status+created_at), `review`
+ (reference+status+created_at), `commission_rule` (reference+reference_id).
+ `commission_line` declares the indexes its migration already created.
+
+## 5. Priority checklist for Mercur before load testing
+
+1. Audit every Mercur workflow for `retentionTime`, `idempotent`, `timeout`,
+ `retryInterval`, and `async` on hot paths. Remove them.
+2. Audit every `query.graph` call for missing `fields`, `*`-relation defaults,
+ and expanded unbounded links.
+3. Find filters on computed or cross-connection fields that fall into residual
+ in-memory filtering, especially product-by-seller listing with pagination.
+4. Add composite partial indexes for the seller-scoped list filters on orders,
+ offers, product changes, and payouts.
+5. Thread `sharedContext` through every nested service call in Mercur modules.
+6. Mark the seller-product link `filterable` and move store listing to
+ `query.index`.
+7. Enable the caching flag plus Redis provider, add link-table tags to Mercur
+ cached queries, and emit `<entity>.<op>` events from Mercur modules.
+8. Cap `limit`, set the relations limit on `/vendor/*`, and set
+ `databaseDriverOptions.pool.max`.
+9. Run server/worker split with `locking-redis` registered.
+10. Move payout batches, imports, and exports to async background steps.
+
+Useful Medusa commits to read with `git show` in the Medusa checkout:
+`2fe68a975b`, `c54c5ed6de`, `990691e78a`, `d1efad9bf0`, `5cc7fdef18`,
+`bd206cb250`, `8e5c22a8e8`, `bd571aca82`.
diff --git a/integration-tests/http/commission-rates/admin/commission-context-hook.spec.ts b/integration-tests/http/commission-rates/admin/commission-context-hook.spec.ts
index 8d604178d..24578a7f1 100644
--- a/integration-tests/http/commission-rates/admin/commission-context-hook.spec.ts
+++ b/integration-tests/http/commission-rates/admin/commission-context-hook.spec.ts
@@ -55,14 +55,16 @@ medusaIntegrationTestRunner({
shipping_methods: [{ name: "Standard", amount: 50 }],
})
- const spy = jest.spyOn(commissionService, "getCommissionLines")
+ const spy = jest.spyOn(commissionService, "getCommissionLinesBatch")
await refreshOrderCommissionLinesWorkflow(appContainer).run({
input: { order_ids: [order.id] },
})
expect(spy).toHaveBeenCalledTimes(1)
- const [context] = spy.mock.calls[0] as [CommissionCalculationContext]
+ const [contexts] = spy.mock.calls[0] as [CommissionCalculationContext[]]
+ expect(contexts).toHaveLength(1)
+ const [context] = contexts
expect(context.order_id).toEqual(order.id)
expect(context.additional_context).toEqual({
diff --git a/integration-tests/http/commission-rates/admin/commission-providers.spec.ts b/integration-tests/http/commission-rates/admin/commission-providers.spec.ts
index a2c6ef657..4a1d84f31 100644
--- a/integration-tests/http/commission-rates/admin/commission-providers.spec.ts
+++ b/integration-tests/http/commission-rates/admin/commission-providers.spec.ts
@@ -39,6 +39,40 @@ class OtherCommissionProvider implements ICommissionProvider {
}
}
+class BatchCommissionProvider implements ICommissionProvider {
+ static identifier = "batch"
+ static singleCalls = 0
+ static batchCalls = 0
+
+ async getCommissionLines(
+ context: CommissionCalculationContext
+ ): Promise<CreateCommissionLineDTO[]> {
+ BatchCommissionProvider.singleCalls += 1
+ return (context.items ?? []).map((item) => ({
+ item_id: item.id,
+ shipping_method_id: null,
+ code: "SINGLE",
+ rate: 1,
+ amount: 1,
+ }))
+ }
+
+ async getCommissionLinesBatch(
+ contexts: CommissionCalculationContext[]
+ ): Promise<CreateCommissionLineDTO[][]> {
+ BatchCommissionProvider.batchCalls += 1
+ return contexts.map((context) =>
+ (context.items ?? []).map((item) => ({
+ item_id: item.id,
+ shipping_method_id: null,
+ code: "BATCH",
+ rate: 2,
+ amount: 2,
+ }))
+ )
+ }
+}
+
const context: CommissionCalculationContext = {
currency_code: "usd",
items: [{ id: "item_1", subtotal: 100 }],
@@ -91,6 +125,72 @@ moduleIntegrationTestRunner({
})
)
})
+
+ it("falls back to per-context calls when the provider has no batch method", async () => {
+ const batches = await service.getCommissionLinesBatch([
+ context,
+ { ...context, items: [{ id: "item_2", subtotal: 50 }] },
+ ])
+
+ expect(batches).toEqual([
+ [expect.objectContaining({ item_id: "item_1", provider_id: "fixed" })],
+ [expect.objectContaining({ item_id: "item_2", provider_id: "fixed" })],
+ ])
+ })
+ })
+ },
+})
+
+moduleIntegrationTestRunner({
+ moduleName: MercurModules.COMMISSION,
+ dbName: "medusa-commission-providers-batch",
+ resolve,
+ moduleOptions: {
+ providers: [
+ {
+ resolve: { services: [BatchCommissionProvider] },
+ id: "batch",
+ is_default: true,
+ },
+ ],
+ },
+ testSuite: ({ service }) => {
+ describe("Commission providers - batch-capable provider", () => {
+ beforeEach(() => {
+ BatchCommissionProvider.singleCalls = 0
+ BatchCommissionProvider.batchCalls = 0
+ })
+
+ it("resolves a batch through getCommissionLinesBatch once", async () => {
+ const batches = await service.getCommissionLinesBatch([
+ context,
+ { ...context, items: [{ id: "item_2", subtotal: 50 }] },
+ ])
+
+ expect(BatchCommissionProvider.batchCalls).toBe(1)
+ expect(BatchCommissionProvider.singleCalls).toBe(0)
+ expect(batches).toEqual([
+ [
+ expect.objectContaining({
+ item_id: "item_1",
+ code: "BATCH",
+ provider_id: "batch",
+ }),
+ ],
+ [
+ expect.objectContaining({
+ item_id: "item_2",
+ code: "BATCH",
+ provider_id: "batch",
+ }),
+ ],
+ ])
+ })
+
+ it("skips the provider for an empty batch", async () => {
+ await expect(service.getCommissionLinesBatch([])).resolves.toEqual([])
+ expect(BatchCommissionProvider.batchCalls).toBe(0)
+ })
})
},
})
diff --git a/packages/core/src/api/store/offers/helpers.ts b/packages/core/src/api/store/offers/helpers.ts
index ade595019..ddfbe412c 100644
--- a/packages/core/src/api/store/offers/helpers.ts
+++ b/packages/core/src/api/store/offers/helpers.ts
@@ -236,11 +236,14 @@ export const wrapOffersWithInventoryQuantityForSalesChannel = async (
}
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
- const { data: channels } = await query.graph({
- entity: "sales_channel",
- fields: ["stock_locations.id"],
- filters: { id: channelToUse },
- })
+ const { data: channels } = await query.graph(
+ {
+ entity: "sales_channel",
+ fields: ["stock_locations.id"],
+ filters: { id: channelToUse },
+ },
+ { cache: { enable: true } }
+ )
const channelLocationIds = new Set<string>(
(channels[0]?.stock_locations ?? [])
diff --git a/packages/core/src/api/store/products/[id]/route.ts b/packages/core/src/api/store/products/[id]/route.ts
index acd2bf136..c57165174 100644
--- a/packages/core/src/api/store/products/[id]/route.ts
+++ b/packages/core/src/api/store/products/[id]/route.ts
@@ -42,11 +42,14 @@ export const GET = async (req: MedusaStoreRequest, res: MedusaResponse) => {
const {
data: [product],
- } = await query.graph({
- entity: "product",
- fields: req.queryConfig.fields,
- filters: { ...productFilters, id: req.params.id },
- })
+ } = await query.graph(
+ {
+ entity: "product",
+ fields: req.queryConfig.fields,
+ filters: { ...productFilters, id: req.params.id },
+ },
+ { cache: { enable: true }, locale: req.locale }
+ )
if (!product) {
throw new MedusaError(
diff --git a/packages/core/src/api/store/products/route.ts b/packages/core/src/api/store/products/route.ts
index 8e4c27b3d..5bfd2a034 100644
--- a/packages/core/src/api/store/products/route.ts
+++ b/packages/core/src/api/store/products/route.ts
@@ -30,12 +30,15 @@ export const GET = async (req: MedusaStoreRequest, res: MedusaResponse) => {
...productFilters
} = (req.filterableFields ?? {}) as Record<string, unknown>
- const { data: products, metadata } = await query.graph({
- entity: "product",
- fields: req.queryConfig.fields,
- filters: productFilters,
- pagination: req.queryConfig.pagination,
- })
+ const { data: products, metadata } = await query.graph(
+ {
+ entity: "product",
+ fields: req.queryConfig.fields,
+ filters: productFilters,
+ pagination: req.queryConfig.pagination,
+ },
+ { cache: { enable: true }, locale: req.locale }
+ )
await enrichProductAttributes(req.scope, products as any[])
diff --git a/packages/core/src/api/utils/sellers.ts b/packages/core/src/api/utils/sellers.ts
index 34e0fd2c0..a7e997596 100644
--- a/packages/core/src/api/utils/sellers.ts
+++ b/packages/core/src/api/utils/sellers.ts
@@ -6,7 +6,9 @@ export const resolveVisibleSellerIds = async (
scope: MedusaContainer
): Promise<string[]> => {
const query = scope.resolve(ContainerRegistrationKeys.QUERY)
- const now = new Date()
+ // `now` is part of the cache key, so it is truncated to the minute to let
+ // requests within the same minute share one cached entry.
+ const now = new Date(Math.floor(Date.now() / 60_000) * 60_000)
const { data: visibleSellers } = await query.graph({
entity: "seller",
@@ -18,7 +20,7 @@ export const resolveVisibleSellerIds = async (
{ $or: [{ closed_to: null }, { closed_to: { $lt: now } }] },
],
},
- })
+ }, { cache: { enable: true } })
return visibleSellers.map((s: { id: string }) => s.id)
}
diff --git a/packages/core/src/api/vendor/products/helpers.ts b/packages/core/src/api/vendor/products/helpers.ts
index fbd72d464..d7f90c06b 100644
--- a/packages/core/src/api/vendor/products/helpers.ts
+++ b/packages/core/src/api/vendor/products/helpers.ts
@@ -7,8 +7,13 @@ import { ProductChangeActionType } from "@mercurjs/types"
export const getSellerOwnedProductIds = async (
scope: MedusaContainer,
- sellerId: string
+ sellerId: string,
+ productIds?: string[]
): Promise<string[]> => {
+ if (productIds && !productIds.length) {
+ return []
+ }
+
const query = scope.resolve(ContainerRegistrationKeys.QUERY)
const { data: actions } = await query.graph({
@@ -17,6 +22,7 @@ export const getSellerOwnedProductIds = async (
filters: {
action: ProductChangeActionType.PRODUCT_ADD,
product_change: { created_by: sellerId },
+ ...(productIds ? { product_id: productIds } : {}),
},
})
@@ -27,17 +33,24 @@ export const getSellerOwnedProductIds = async (
/**
* 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.
+ * be hidden from this seller's product list. Pass `productIds` to scope the
+ * check to a known set instead of scanning every link.
*/
export const getProductIdsRestrictedFromSeller = async (
scope: MedusaContainer,
- sellerId: string
+ sellerId: string,
+ productIds?: string[]
): Promise<string[]> => {
+ if (productIds && !productIds.length) {
+ return []
+ }
+
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>()
@@ -100,7 +113,7 @@ export const ensureSellerOwnsProduct = async (
const ownedProductIds = new Set<string | null>(
data.map(({ product_id }) => product_id)
)
- for (const id of await getSellerOwnedProductIds(scope, sellerId)) {
+ for (const id of await getSellerOwnedProductIds(scope, sellerId, productIds)) {
ownedProductIds.add(id)
}
const missingProductId = productIds.find((id) => !ownedProductIds.has(id))
diff --git a/packages/core/src/api/vendor/products/middlewares.ts b/packages/core/src/api/vendor/products/middlewares.ts
index 44ea9909d..fe9e4c9d9 100644
--- a/packages/core/src/api/vendor/products/middlewares.ts
+++ b/packages/core/src/api/vendor/products/middlewares.ts
@@ -81,8 +81,8 @@ const ensureProductVisibleToSeller = async (
const productId = req.params.id
const [ownProductIds, restrictedFromSellerIds, product] = await promiseAll([
- getSellerOwnedProductIds(req.scope, sellerId),
- getProductIdsRestrictedFromSeller(req.scope, sellerId),
+ getSellerOwnedProductIds(req.scope, sellerId, [productId]),
+ getProductIdsRestrictedFromSeller(req.scope, sellerId, [productId]),
getProductStatus(req.scope, productId),
])
diff --git a/packages/core/src/api/vendor/regions/helpers.ts b/packages/core/src/api/vendor/regions/helpers.ts
index c0242a16b..1b6fc3ca4 100644
--- a/packages/core/src/api/vendor/regions/helpers.ts
+++ b/packages/core/src/api/vendor/regions/helpers.ts
@@ -10,11 +10,14 @@ export const listSellerRegionIds = async (
): Promise<string[]> => {
const query = scope.resolve(ContainerRegistrationKeys.QUERY)
- const { data: links } = await query.graph({
- entity: "region_seller",
- filters: { seller_id: sellerId },
- fields: ["region_id"],
- })
+ const { data: links } = await query.graph(
+ {
+ entity: "region_seller",
+ filters: { seller_id: sellerId },
+ fields: ["region_id"],
+ },
+ { cache: { enable: true } }
+ )
return links.map((link) => (link as { region_id: string }).region_id)
}
@@ -29,11 +32,14 @@ export const listSellerCurrencyCodes = async (
}
const query = scope.resolve(ContainerRegistrationKeys.QUERY)
- const { data: regions } = await query.graph({
- entity: "region",
- filters: { id: regionIds },
- fields: ["currency_code"],
- })
+ const { data: regions } = await query.graph(
+ {
+ entity: "region",
+ filters: { id: regionIds },
+ fields: ["currency_code"],
+ },
+ { cache: { enable: true } }
+ )
return Array.from(
new Set(regions.map((r) => (r.currency_code as string).toLowerCase()))
diff --git a/packages/core/src/api/vendor/sales-channels/helpers.ts b/packages/core/src/api/vendor/sales-channels/helpers.ts
index 241ea00a9..3fefc6853 100644
--- a/packages/core/src/api/vendor/sales-channels/helpers.ts
+++ b/packages/core/src/api/vendor/sales-channels/helpers.ts
@@ -41,7 +41,7 @@ export const ensureSellerOwnsProducts = async (
const ownedProductIds = new Set<string | null>(
links.map((link: { product_id: string | null }) => link.product_id)
)
- for (const id of await getSellerOwnedProductIds(scope, sellerId)) {
+ for (const id of await getSellerOwnedProductIds(scope, sellerId, productIds)) {
ownedProductIds.add(id)
}
const unowned = productIds.filter((id) => !ownedProductIds.has(id))
diff --git a/packages/core/src/modules/commission/__tests__/system-provider.unit.spec.ts b/packages/core/src/modules/commission/__tests__/system-provider.unit.spec.ts
new file mode 100644
index 000000000..22a954655
--- /dev/null
+++ b/packages/core/src/modules/commission/__tests__/system-provider.unit.spec.ts
@@ -0,0 +1,105 @@
+import { CommissionCalculationContext } from "@mercurjs/types"
+
+import { SystemCommissionProvider } from "../providers/system"
+
+const rates = [
+ {
+ id: "rate_default",
+ code: "default",
+ type: "percentage",
+ value: 10,
+ is_enabled: true,
+ is_default: true,
+ include_tax: false,
+ include_shipping: true,
+ currency_code: null,
+ created_at: new Date("2026-01-01T00:00:00Z"),
+ rules: [],
+ values: [],
+ },
+ {
+ id: "rate_seller",
+ code: "seller-a",
+ type: "percentage",
+ value: 20,
+ is_enabled: true,
+ is_default: false,
+ include_tax: false,
+ include_shipping: false,
+ currency_code: null,
+ created_at: new Date("2026-01-02T00:00:00Z"),
+ rules: [{ reference: "seller", reference_id: "seller_a" }],
+ values: [],
+ },
+]
+
+const buildProvider = () => {
+ const list = jest.fn(async () => rates)
+ const provider = new SystemCommissionProvider({
+ commissionRateService: { list } as never,
+ })
+ return { provider, list }
+}
+
+const contexts: CommissionCalculationContext[] = [
+ {
+ order_id: "order_a",
+ currency_code: "usd",
+ items: [
+ {
+ id: "item_a",
+ subtotal: 100,
+ product: { id: "prod_a", seller: { id: "seller_a" } },
+ },
+ ],
+ shipping_methods: [{ id: "sm_a", subtotal: 10 }],
+ },
+ {
+ order_id: "order_b",
+ currency_code: "usd",
+ items: [
+ {
+ id: "item_b",
+ subtotal: 50,
+ product: { id: "prod_b", seller: { id: "seller_b" } },
+ },
+ ],
+ shipping_methods: [],
+ },
+]
+
+describe("SystemCommissionProvider.getCommissionLinesBatch", () => {
+ it("loads the rate table once for the whole batch", async () => {
+ const { provider, list } = buildProvider()
+
+ const batches = await provider.getCommissionLinesBatch(contexts)
+
+ expect(list).toHaveBeenCalledTimes(1)
+ expect(batches).toHaveLength(2)
+ expect(batches[0]).toEqual([
+ expect.objectContaining({ item_id: "item_a", code: "seller-a", amount: 20 }),
+ expect.objectContaining({ shipping_method_id: "sm_a", code: "default", amount: 1 }),
+ ])
+ expect(batches[1]).toEqual([
+ expect.objectContaining({ item_id: "item_b", code: "default", amount: 5 }),
+ ])
+ })
+
+ it("returns the same lines as the per-context method, in order", async () => {
+ const { provider } = buildProvider()
+
+ const batches = await provider.getCommissionLinesBatch(contexts)
+ const single = await Promise.all(
+ contexts.map((context) => provider.getCommissionLines(context))
+ )
+
+ expect(batches).toEqual(single)
+ })
+
+ it("skips the rate query for an empty batch", async () => {
+ const { provider, list } = buildProvider()
+
+ await expect(provider.getCommissionLinesBatch([])).resolves.toEqual([])
+ expect(list).not.toHaveBeenCalled()
+ })
+})
diff --git a/packages/core/src/modules/commission/migrations/Migration20261021000000.ts b/packages/core/src/modules/commission/migrations/Migration20261021000000.ts
new file mode 100644
index 000000000..9673f954e
--- /dev/null
+++ b/packages/core/src/modules/commission/migrations/Migration20261021000000.ts
@@ -0,0 +1,13 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations"
+
+export class Migration20261021000000 extends Migration {
+ override async up(): Promise<void> {
+ this.addSql(
+ `CREATE INDEX IF NOT EXISTS "IDX_commission_rule_reference_reference_id" ON "commission_rule" ("reference", "reference_id") WHERE deleted_at IS NULL;`
+ )
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`DROP INDEX IF EXISTS "IDX_commission_rule_reference_reference_id";`)
+ }
+}
diff --git a/packages/core/src/modules/commission/models/commission-line.ts b/packages/core/src/modules/commission/models/commission-line.ts
index 467518e05..89c12d408 100644
--- a/packages/core/src/modules/commission/models/commission-line.ts
+++ b/packages/core/src/modules/commission/models/commission-line.ts
@@ -1,16 +1,29 @@
import { model } from "@medusajs/framework/utils"
-const CommissionLine = model.define("commission_line", {
- id: model.id({ prefix: "comline" }).primaryKey(),
- item_id: model.text().nullable(),
- shipping_method_id: model.text().nullable(),
- commission_rate_id: model.text().nullable(),
- provider_id: model.text().default("system"),
- code: model.text(),
- rate: model.float(),
- amount: model.bigNumber(),
- description: model.text().nullable(),
- data: model.json().nullable(),
-})
+const CommissionLine = model
+ .define("commission_line", {
+ id: model.id({ prefix: "comline" }).primaryKey(),
+ item_id: model.text().nullable(),
+ shipping_method_id: model.text().nullable(),
+ commission_rate_id: model.text().nullable(),
+ provider_id: model.text().default("system"),
+ code: model.text(),
+ rate: model.float(),
+ amount: model.bigNumber(),
+ description: model.text().nullable(),
+ data: model.json().nullable(),
+ })
+ .indexes([
+ {
+ name: "IDX_commission_line_item_id",
+ on: ["item_id"],
+ where: "deleted_at IS NULL",
+ },
+ {
+ name: "IDX_commission_line_shipping_method_id",
+ on: ["shipping_method_id"],
+ where: "deleted_at IS NULL",
+ },
+ ])
export default CommissionLine
diff --git a/packages/core/src/modules/commission/models/commission-rule.ts b/packages/core/src/modules/commission/models/commission-rule.ts
index e1cbf9433..cb87609d3 100644
--- a/packages/core/src/modules/commission/models/commission-rule.ts
+++ b/packages/core/src/modules/commission/models/commission-rule.ts
@@ -2,13 +2,21 @@ import { model } from "@medusajs/framework/utils"
import CommissionRate from "./commission-rate"
-const CommissionRule = model.define("commission_rule", {
- id: model.id({ prefix: "comrule" }).primaryKey(),
- reference: model.text(),
- reference_id: model.text(),
- commission_rate: model.belongsTo(() => CommissionRate, {
- mappedBy: "rules",
- }),
-})
+const CommissionRule = model
+ .define("commission_rule", {
+ id: model.id({ prefix: "comrule" }).primaryKey(),
+ reference: model.text(),
+ reference_id: model.text(),
+ commission_rate: model.belongsTo(() => CommissionRate, {
+ mappedBy: "rules",
+ }),
+ })
+ .indexes([
+ {
+ name: "IDX_commission_rule_reference_reference_id",
+ on: ["reference", "reference_id"],
+ where: "deleted_at IS NULL",
+ },
+ ])
export default CommissionRule
diff --git a/packages/core/src/modules/commission/providers/system.ts b/packages/core/src/modules/commission/providers/system.ts
index 5324dd3de..24f6fc8a9 100644
--- a/packages/core/src/modules/commission/providers/system.ts
+++ b/packages/core/src/modules/commission/providers/system.ts
@@ -133,19 +133,43 @@ export class SystemCommissionProvider implements ICommissionProvider {
}
}
+ /**
+ * Enabled rates with their rules and per-currency values, oldest first so
+ * created_at is the deterministic tie-break.
+ */
+ private async loadEnabledRates(): Promise<CommissionRateEntity[]> {
+ return (await this.commissionRateService_.list(
+ { is_enabled: true },
+ { relations: ["rules", "values"], order: { created_at: "ASC" } }
+ )) as CommissionRateEntity[]
+ }
+
async getCommissionLines(
context: CommissionCalculationContext
): Promise<CreateCommissionLineDTO[]> {
+ const commissionRates = await this.loadEnabledRates()
+ return this.resolveCommissionLines(context, commissionRates)
+ }
+
+ async getCommissionLinesBatch(
+ contexts: CommissionCalculationContext[]
+ ): Promise<CreateCommissionLineDTO[][]> {
+ if (!contexts.length) {
+ return []
+ }
+ const commissionRates = await this.loadEnabledRates()
+ return contexts.map((context) =>
+ this.resolveCommissionLines(context, commissionRates)
+ )
+ }
+
+ private resolveCommissionLines(
+ context: CommissionCalculationContext,
+ commissionRates: CommissionRateEntity[]
+ ): CreateCommissionLineDTO[] {
const commissionLines: CreateCommissionLineDTO[] = []
const { items = [], shipping_methods = [], currency_code } = context
- // Load all enabled rates with their rules + per-currency values,
- // oldest first (created_at ASC) so it is the deterministic tie-break.
- const commissionRates = (await this.commissionRateService_.list(
- { is_enabled: true },
- { relations: ["rules", "values"], order: { created_at: "ASC" } }
- )) as CommissionRateEntity[]
-
// Legacy single-currency rates only apply to their currency; rates
// without a currency_code apply to any currency.
const applicableRates = commissionRates.filter(
diff --git a/packages/core/src/modules/commission/service.ts b/packages/core/src/modules/commission/service.ts
index 771584e33..c83d964e5 100644
--- a/packages/core/src/modules/commission/service.ts
+++ b/packages/core/src/modules/commission/service.ts
@@ -10,6 +10,7 @@ import {
InjectManager,
MedusaContext,
MedusaService,
+ promiseAll,
} from "@medusajs/framework/utils"
import { raw } from "@medusajs/framework/mikro-orm/postgresql"
@@ -84,6 +85,30 @@ class CommissionModuleService extends MedusaService({
}))
}
+ async getCommissionLinesBatch(
+ contexts: CommissionCalculationContext[]
+ ): Promise<CreateCommissionLineDTO[][]> {
+ if (!contexts.length) {
+ return []
+ }
+
+ const provider = this.commissionProviderService_.retrieveProvider(
+ this.defaultProviderId_
+ )
+ const batches = provider.getCommissionLinesBatch
+ ? await provider.getCommissionLinesBatch(contexts)
+ : await promiseAll(
+ contexts.map((context) => provider.getCommissionLines(context))
+ )
+
+ return batches.map((lines) =>
+ lines.map((line) => ({
+ ...line,
+ provider_id: line.provider_id ?? this.defaultProviderId_,
+ }))
+ )
+ }
+
/**
* Overrides the auto-generated upsert with idempotent **replace**
* semantics keyed on the line's anchor (item_id / shipping_method_id):
diff --git a/packages/core/src/modules/offer/migrations/Migration20261021000000.ts b/packages/core/src/modules/offer/migrations/Migration20261021000000.ts
new file mode 100644
index 000000000..05ff03b2b
--- /dev/null
+++ b/packages/core/src/modules/offer/migrations/Migration20261021000000.ts
@@ -0,0 +1,17 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations"
+
+export class Migration20261021000000 extends Migration {
+ override async up(): Promise<void> {
+ this.addSql(
+ `CREATE INDEX IF NOT EXISTS "IDX_offer_seller_id_created_at" ON "offer" ("seller_id", "created_at") WHERE deleted_at IS NULL;`
+ )
+ this.addSql(
+ `CREATE INDEX IF NOT EXISTS "IDX_offer_product_id_seller_id_created_at" ON "offer" ("product_id", "seller_id", "created_at") WHERE deleted_at IS NULL;`
+ )
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`DROP INDEX IF EXISTS "IDX_offer_seller_id_created_at";`)
+ this.addSql(`DROP INDEX IF EXISTS "IDX_offer_product_id_seller_id_created_at";`)
+ }
+}
diff --git a/packages/core/src/modules/offer/models/offer.ts b/packages/core/src/modules/offer/models/offer.ts
index e102dea92..096a2784f 100644
--- a/packages/core/src/modules/offer/models/offer.ts
+++ b/packages/core/src/modules/offer/models/offer.ts
@@ -64,6 +64,16 @@ const Offer = model
on: ["upc"],
where: "deleted_at IS NULL AND upc IS NOT NULL",
},
+ {
+ name: "IDX_offer_seller_id_created_at",
+ on: ["seller_id", "created_at"],
+ where: "deleted_at IS NULL",
+ },
+ {
+ name: "IDX_offer_product_id_seller_id_created_at",
+ on: ["product_id", "seller_id", "created_at"],
+ where: "deleted_at IS NULL",
+ },
])
export default Offer
diff --git a/packages/core/src/modules/payout/migrations/Migration20261021000000.ts b/packages/core/src/modules/payout/migrations/Migration20261021000000.ts
new file mode 100644
index 000000000..95a6acb19
--- /dev/null
+++ b/packages/core/src/modules/payout/migrations/Migration20261021000000.ts
@@ -0,0 +1,17 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations"
+
+export class Migration20261021000000 extends Migration {
+ override async up(): Promise<void> {
+ this.addSql(
+ `CREATE INDEX IF NOT EXISTS "IDX_payout_account_id_created_at" ON "payout" ("account_id", "created_at") WHERE deleted_at IS NULL;`
+ )
+ this.addSql(
+ `CREATE INDEX IF NOT EXISTS "IDX_payout_status_created_at" ON "payout" ("status", "created_at") WHERE deleted_at IS NULL;`
+ )
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`DROP INDEX IF EXISTS "IDX_payout_account_id_created_at";`)
+ this.addSql(`DROP INDEX IF EXISTS "IDX_payout_status_created_at";`)
+ }
+}
diff --git a/packages/core/src/modules/payout/models/payout.ts b/packages/core/src/modules/payout/models/payout.ts
index 5746b7762..427b5f373 100644
--- a/packages/core/src/modules/payout/models/payout.ts
+++ b/packages/core/src/modules/payout/models/payout.ts
@@ -3,14 +3,27 @@ import { model } from '@medusajs/framework/utils'
import { PayoutAccount } from './payout-account'
import { PayoutStatus } from '@mercurjs/types'
-export const Payout = model.define('payout', {
- id: model.id({ prefix: 'pout' }).primaryKey(),
- display_id: model.autoincrement(),
- currency_code: model.text(),
- amount: model.bigNumber(),
- data: model.json().nullable(),
- account: model.belongsTo(() => PayoutAccount, {
- mappedBy: 'payouts'
- }),
- status: model.enum(PayoutStatus).default(PayoutStatus.PENDING)
-})
+export const Payout = model
+ .define('payout', {
+ id: model.id({ prefix: 'pout' }).primaryKey(),
+ display_id: model.autoincrement(),
+ currency_code: model.text(),
+ amount: model.bigNumber(),
+ data: model.json().nullable(),
+ account: model.belongsTo(() => PayoutAccount, {
+ mappedBy: 'payouts'
+ }),
+ status: model.enum(PayoutStatus).default(PayoutStatus.PENDING)
+ })
+ .indexes([
+ {
+ name: 'IDX_payout_account_id_created_at',
+ on: ['account_id', 'created_at'],
+ where: 'deleted_at IS NULL'
+ },
+ {
+ name: 'IDX_payout_status_created_at',
+ on: ['status', 'created_at'],
+ where: 'deleted_at IS NULL'
+ }
+ ])
diff --git a/packages/core/src/modules/review/migrations/Migration20261021000000.ts b/packages/core/src/modules/review/migrations/Migration20261021000000.ts
new file mode 100644
index 000000000..8b8df4d38
--- /dev/null
+++ b/packages/core/src/modules/review/migrations/Migration20261021000000.ts
@@ -0,0 +1,13 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations"
+
+export class Migration20261021000000 extends Migration {
+ override async up(): Promise<void> {
+ this.addSql(
+ `CREATE INDEX IF NOT EXISTS "IDX_review_reference_status_created_at" ON "review" ("reference", "status", "created_at") WHERE deleted_at IS NULL;`
+ )
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`DROP INDEX IF EXISTS "IDX_review_reference_status_created_at";`)
+ }
+}
diff --git a/packages/core/src/modules/review/models/review.ts b/packages/core/src/modules/review/models/review.ts
index 443f69290..4c0d81702 100644
--- a/packages/core/src/modules/review/models/review.ts
+++ b/packages/core/src/modules/review/models/review.ts
@@ -1,13 +1,21 @@
import { model } from "@medusajs/framework/utils"
-const Review = model.define("review", {
- id: model.id({ prefix: "rev" }).primaryKey(),
- display_id: model.autoincrement(),
- reference: model.enum(["product", "seller"]),
- rating: model.number(),
- customer_note: model.text().searchable().nullable(),
- seller_note: model.text().searchable().nullable(),
- status: model.enum(["pending", "published", "rejected"]).default("pending"),
-})
+const Review = model
+ .define("review", {
+ id: model.id({ prefix: "rev" }).primaryKey(),
+ display_id: model.autoincrement(),
+ reference: model.enum(["product", "seller"]),
+ rating: model.number(),
+ customer_note: model.text().searchable().nullable(),
+ seller_note: model.text().searchable().nullable(),
+ status: model.enum(["pending", "published", "rejected"]).default("pending"),
+ })
+ .indexes([
+ {
+ name: "IDX_review_reference_status_created_at",
+ on: ["reference", "status", "created_at"],
+ where: "deleted_at IS NULL",
+ },
+ ])
export default Review
diff --git a/packages/core/src/modules/seller/migrations/Migration20261021000000.ts b/packages/core/src/modules/seller/migrations/Migration20261021000000.ts
new file mode 100644
index 000000000..dce596f6c
--- /dev/null
+++ b/packages/core/src/modules/seller/migrations/Migration20261021000000.ts
@@ -0,0 +1,21 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations"
+
+export class Migration20261021000000 extends Migration {
+ override async up(): Promise<void> {
+ this.addSql(
+ `CREATE INDEX IF NOT EXISTS "IDX_order_group_cart_id" ON "order_group" ("cart_id") WHERE deleted_at IS NULL;`
+ )
+ this.addSql(
+ `CREATE INDEX IF NOT EXISTS "IDX_order_group_customer_id_created_at" ON "order_group" ("customer_id", "created_at") WHERE deleted_at IS NULL;`
+ )
+ this.addSql(
+ `CREATE INDEX IF NOT EXISTS "IDX_order_group_created_at" ON "order_group" ("created_at") WHERE deleted_at IS NULL;`
+ )
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`DROP INDEX IF EXISTS "IDX_order_group_cart_id";`)
+ this.addSql(`DROP INDEX IF EXISTS "IDX_order_group_customer_id_created_at";`)
+ this.addSql(`DROP INDEX IF EXISTS "IDX_order_group_created_at";`)
+ }
+}
diff --git a/packages/core/src/modules/seller/models/order-group.ts b/packages/core/src/modules/seller/models/order-group.ts
index fc15faa0b..fc90b06b1 100644
--- a/packages/core/src/modules/seller/models/order-group.ts
+++ b/packages/core/src/modules/seller/models/order-group.ts
@@ -1,12 +1,30 @@
import { model } from "@medusajs/framework/utils"
-const OrderGroup = model.define("order_group", {
- id: model.id({ prefix: 'og' }).primaryKey(),
- display_id: model.autoincrement(),
- seller_count: model.number().computed(),
- customer_id: model.text().nullable(),
- total: model.bigNumber().computed(),
- cart_id: model.text(),
-})
+const OrderGroup = model
+ .define("order_group", {
+ id: model.id({ prefix: 'og' }).primaryKey(),
+ display_id: model.autoincrement(),
+ seller_count: model.number().computed(),
+ customer_id: model.text().nullable(),
+ total: model.bigNumber().computed(),
+ cart_id: model.text(),
+ })
+ .indexes([
+ {
+ name: "IDX_order_group_cart_id",
+ on: ["cart_id"],
+ where: "deleted_at IS NULL",
+ },
+ {
+ name: "IDX_order_group_customer_id_created_at",
+ on: ["customer_id", "created_at"],
+ where: "deleted_at IS NULL",
+ },
+ {
+ name: "IDX_order_group_created_at",
+ on: ["created_at"],
+ where: "deleted_at IS NULL",
+ },
+ ])
export default OrderGroup
diff --git a/packages/core/src/modules/seller/repositories/order-group.ts b/packages/core/src/modules/seller/repositories/order-group.ts
index 44d8485df..0fd0f81f7 100644
--- a/packages/core/src/modules/seller/repositories/order-group.ts
+++ b/packages/core/src/modules/seller/repositories/order-group.ts
@@ -257,8 +257,8 @@ export class OrderGroupRepository extends DALUtils.mikroOrmBaseRepositoryFactory
`EXISTS (
SELECT 1
FROM order_group_order qogo
- JOIN "order" qo ON qo.id = qogo.order_id
- WHERE qogo.order_group_id = og.id AND qo.display_id = ?
+ JOIN "order" qo ON qo.id = qogo.order_id AND qo.deleted_at IS NULL
+ WHERE qogo.order_group_id = og.id AND qogo.deleted_at IS NULL AND qo.display_id = ?
)`
)
params.push(displayId, displayId)
@@ -274,10 +274,10 @@ export class OrderGroupRepository extends DALUtils.mikroOrmBaseRepositoryFactory
whereClauses.push(`EXISTS (
SELECT 1
FROM order_group_order fogo
- JOIN "order" fo ON fo.id = fogo.order_id
- LEFT JOIN order_order_seller_seller fo_seller ON fo_seller.order_id = fo.id
+ JOIN "order" fo ON fo.id = fogo.order_id AND fo.deleted_at IS NULL
+ LEFT JOIN order_order_seller_seller fo_seller ON fo_seller.order_id = fo.id AND fo_seller.deleted_at IS NULL
${needsPaymentStatus ? ORDER_PAYMENT_STATUS_JOIN : ""}
- WHERE fogo.order_group_id = og.id AND ${orderClauses.join(" AND ")}
+ WHERE fogo.order_group_id = og.id AND fogo.deleted_at IS NULL AND ${orderClauses.join(" AND ")}
)`)
params.push(...orderParams)
}
@@ -307,10 +307,10 @@ export class OrderGroupRepository extends DALUtils.mikroOrmBaseRepositoryFactory
COUNT(DISTINCT oso.seller_id) as seller_count,
COALESCE(SUM((os.totals->>'current_order_total')::numeric), 0) as total
FROM order_group og
- LEFT JOIN order_group_order ogo ON ogo.order_group_id = og.id
- LEFT JOIN "order" o ON o.id = ogo.order_id
- LEFT JOIN order_summary os ON os.order_id = o.id AND os.version = o.version
- LEFT JOIN order_order_seller_seller oso ON oso.order_id = o.id
+ LEFT JOIN order_group_order ogo ON ogo.order_group_id = og.id AND ogo.deleted_at IS NULL
+ LEFT JOIN "order" o ON o.id = ogo.order_id AND o.deleted_at IS NULL
+ LEFT JOIN order_summary os ON os.order_id = o.id AND os.version = o.version AND os.deleted_at IS NULL
+ LEFT JOIN order_order_seller_seller oso ON oso.order_id = o.id AND oso.deleted_at IS NULL
WHERE ${whereClause}
GROUP BY og.id
ORDER BY ${orderByClauses.join(", ")}
diff --git a/packages/core/src/workflows/campaign/steps/link-seller-campaign.ts b/packages/core/src/workflows/campaign/steps/link-seller-campaign.ts
index 0b83f4ff7..ab97a947d 100644
--- a/packages/core/src/workflows/campaign/steps/link-seller-campaign.ts
+++ b/packages/core/src/workflows/campaign/steps/link-seller-campaign.ts
@@ -11,6 +11,10 @@ type LinkSellerCampaignStepInput = {
export const linkSellerCampaignStep = createStep(
"link-seller-campaign",
async (input: LinkSellerCampaignStepInput, { container }) => {
+ if (!input.campaign_ids.length) {
+ return new StepResponse(undefined, undefined)
+ }
+
const remoteLink: Link = container.resolve(ContainerRegistrationKeys.LINK)
const links = input.campaign_ids.map((campaignId) => ({
diff --git a/packages/core/src/workflows/cart/workflows/__tests__/complete-cart-lock-settings.unit.spec.ts b/packages/core/src/workflows/cart/workflows/__tests__/complete-cart-lock-settings.unit.spec.ts
new file mode 100644
index 000000000..aa17ff013
--- /dev/null
+++ b/packages/core/src/workflows/cart/workflows/__tests__/complete-cart-lock-settings.unit.spec.ts
@@ -0,0 +1,16 @@
+import {
+ THIRTY_SECONDS,
+ THREE_DAYS,
+ TWO_MINUTES,
+} from "../complete-cart-with-split-orders"
+
+// acquireLockStep timeout/ttl and the workflow retentionTime are seconds. A
+// millisecond value turns a 30 s lock wait into 8 hours and keeps every
+// checkout execution for years.
+describe("completeCartWithSplitOrdersWorkflow lock settings", () => {
+ it("expresses lock timeout, ttl and retention in seconds", () => {
+ expect(THIRTY_SECONDS).toBe(30)
+ expect(TWO_MINUTES).toBe(120)
+ expect(THREE_DAYS).toBe(259_200)
+ })
+})
diff --git a/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts b/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts
index f2ca2146c..d82dacada 100644
--- a/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts
+++ b/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts
@@ -70,9 +70,11 @@ export type SetOrderStatusHookResult =
}
| undefined
-export const THREE_DAYS = 3 * 24 * 60 * 60 * 1000
-export const THIRTY_SECONDS = 30 * 1000
-export const TWO_MINUTES = 2 * 60 * 1000
+// Lock timeout/ttl and retentionTime are seconds, the same units the native
+// completeCartWorkflow uses.
+export const THREE_DAYS = 3 * 24 * 60 * 60
+export const THIRTY_SECONDS = 30
+export const TWO_MINUTES = 2 * 60
export const completeCartWithSplitOrdersWorkflow = createWorkflow(
{
@@ -82,10 +84,13 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
retentionTime: THREE_DAYS,
},
(input: CompleteCartWithSplitOrdersWorkflowInput) => {
+ // processPaymentWorkflow releases its own cart lock before running this
+ // as a sub-workflow, so the lock must not be skipped on that path.
acquireLockStep({
key: input.cart_id,
timeout: THIRTY_SECONDS,
ttl: TWO_MINUTES,
+ executeOnSubWorkflow: true,
})
const [orderGroup, cartData] = parallelize(
@@ -135,18 +140,82 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
const cartOptionIds = transform({ cart: cartData.data }, ({ cart }) => {
return cart.shipping_methods?.map((sm) => sm.shipping_option_id)
})
- const shippingOptionsData = useQueryGraphStep({
- entity: "shipping_option",
- fields: ['id', "shipping_profile_id", 'seller.id'],
- filters: { id: cartOptionIds },
- options: {
- cache: {
- enable: true,
- },
- },
- }).config({
- name: "shipping-options-query",
+
+ const cartPromotionIds = transform({ cart: cartData.data }, ({ cart }) => {
+ const adjustments = [
+ ...(cart.items ?? []).flatMap((item) => item.adjustments ?? []),
+ ...(cart.shipping_methods ?? []).flatMap((sm) => sm.adjustments ?? []),
+ ]
+ return { promotion_ids: adjustments.map((adjustment) => adjustment.promotion_id) }
})
+
+ const sellerCustomerQueryFilters = transform(
+ { cart: cartData.data },
+ ({ cart }) => {
+ if (!cart.customer_id) {
+ return { seller_id: [], customer_id: "" }
+ }
+ const sellerIds = new Set<string>(
+ (cart.items ?? [])
+ .map((item: any) => item.offer?.seller_id)
+ .filter((id: unknown): id is string => typeof id === "string")
+ )
+ return {
+ seller_id: Array.from(sellerIds),
+ customer_id: cart.customer?.id,
+ }
+ }
+ )
+
+ const uniqueOffers = transform(
+ { cart: cartData.data },
+ ({ cart }) => {
+ const byId = new Map<string, unknown>()
+ for (const item of cart.items ?? []) {
+ const offer = (item as { offer?: unknown }).offer as
+ | { id: string }
+ | undefined
+ if (offer?.id && !byId.has(offer.id)) {
+ byId.set(offer.id, item)
+ }
+ }
+ return Array.from(byId.keys())
+ }
+ )
+
+ const [
+ shippingOptionsData,
+ promotionSellerIds,
+ existingSellerCustomerLinks,
+ offersWithInventoryData,
+ ] = parallelize(
+ useQueryGraphStep({
+ entity: "shipping_option",
+ fields: ['id', "shipping_profile_id", 'seller.id'],
+ filters: { id: cartOptionIds },
+ options: {
+ cache: {
+ enable: true,
+ },
+ },
+ }).config({
+ name: "shipping-options-query",
+ }),
+ getPromotionSellerIdsStep(cartPromotionIds),
+ useQueryGraphStep({
+ entity: "seller_customer",
+ fields: ["seller_id", "customer_id"],
+ filters: sellerCustomerQueryFilters,
+ }).config({
+ name: "existing-seller-customer-links-query",
+ }),
+ useQueryGraphStep({
+ entity: "offer",
+ fields: requiredOfferFieldsForInventoryConfirmation,
+ filters: { id: uniqueOffers },
+ }).config({ name: "fetch-offers-for-reservation" })
+ )
+
validateSellerCartItemsStep({
cart: cartData.data,
})
@@ -165,16 +234,6 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
const orderStatusResult = setOrderStatus.getResult()
- const cartPromotionIds = transform({ cart: cartData.data }, ({ cart }) => {
- const adjustments = [
- ...(cart.items ?? []).flatMap((item) => item.adjustments ?? []),
- ...(cart.shipping_methods ?? []).flatMap((sm) => sm.adjustments ?? []),
- ]
- return { promotion_ids: adjustments.map((adjustment) => adjustment.promotion_id) }
- })
-
- const promotionSellerIds = getPromotionSellerIdsStep(cartPromotionIds)
-
const { ordersToCreate, sellerOrdersMap, offerIdsByOrderId } = transform({ cart: cartData.data, shippingOptionsData: shippingOptionsData.data, orderStatusResult, promotionSellerIds }, ({ cart, shippingOptionsData, orderStatusResult, promotionSellerIds }) => {
const statusResult = orderStatusResult as SetOrderStatusHookResult
const sellerIdOfPromotion = (promotionId?: string | null) =>
@@ -348,27 +407,6 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
)
- const sellerCustomerQueryFilters = transform(
- { cart: cartData.data, sellerOrdersMap },
- ({ cart, sellerOrdersMap }) => {
- if (!cart.customer_id) {
- return { seller_id: [], customer_id: "" }
- }
- return {
- seller_id: Object.keys(sellerOrdersMap),
- customer_id: cart.customer?.id,
- }
- }
- )
-
- const existingSellerCustomerLinks = useQueryGraphStep({
- entity: "seller_customer",
- fields: ["seller_id", "customer_id"],
- filters: sellerCustomerQueryFilters,
- }).config({
- name: "existing-seller-customer-links-query",
- })
-
const [createdOrderGroup, createdOrders] = parallelize(
createOrderGroupStep(orderGroupData),
createOrdersStep(ordersToCreate)
@@ -398,10 +436,6 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
}
)
- mirrorLineItemOfferLinksToOrderStep({
- pairs: orderLineOfferPairs,
- })
-
const offerReservationItems = transform(
{ createdOrders, orderLineOfferPairs },
({ createdOrders, orderLineOfferPairs }) => {
@@ -430,34 +464,12 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
}
)
- const uniqueOffers = transform(
- { cart: cartData.data },
- ({ cart }) => {
- const byId = new Map<string, unknown>()
- for (const item of cart.items ?? []) {
- const offer = (item as { offer?: unknown }).offer as
- | { id: string }
- | undefined
- if (offer?.id && !byId.has(offer.id)) {
- byId.set(offer.id, item)
- }
- }
- return Array.from(byId.keys())
- }
- )
-
- const { data: offersWithInventory } = useQueryGraphStep({
- entity: "offer",
- fields: requiredOfferFieldsForInventoryConfirmation,
- filters: { id: uniqueOffers },
- }).config({ name: "fetch-offers-for-reservation" })
-
const formatedInventoryItems = transform(
{
input: {
sales_channel_id,
items: offerReservationItems,
- offers: offersWithInventory,
+ offers: offersWithInventoryData.data,
},
},
prepareOfferInventoryInput
@@ -585,9 +597,11 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
return createdOrders.map((order) => ({ id: order.id }))
})
- createRemoteLinkStep(linksToCreate)
-
parallelize(
+ createRemoteLinkStep(linksToCreate),
+ mirrorLineItemOfferLinksToOrderStep({
+ pairs: orderLineOfferPairs,
+ }),
updateCartsStep([updateCompletedAt]),
reserveInventoryStep(reservableInventoryItems),
registerUsageStep(promotionUsage),
@@ -644,6 +658,7 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
releaseLockStep({
key: input.cart_id,
+ executeOnSubWorkflow: true,
})
const result = transform({ createdOrderGroup, orderGroupId }, ({ createdOrderGroup, orderGroupId }) => {
diff --git a/packages/core/src/workflows/commission/steps/get-commission-lines.ts b/packages/core/src/workflows/commission/steps/get-commission-lines.ts
index 93e0f7dda..fe56cb108 100644
--- a/packages/core/src/workflows/commission/steps/get-commission-lines.ts
+++ b/packages/core/src/workflows/commission/steps/get-commission-lines.ts
@@ -6,7 +6,6 @@ import {
} from "@mercurjs/types"
import CommissionModuleService from "../../../modules/commission/service"
-import { promiseAll } from "@medusajs/framework/utils"
export const getCommissionLinesStepId = "get-commission-lines"
@@ -16,15 +15,14 @@ export const getCommissionLinesStep = createStep(
input: CommissionCalculationContext[],
{ container }
): Promise<StepResponse<CreateCommissionLineDTO[]>> => {
+ if (!input.length) {
+ return new StepResponse([])
+ }
+
const service =
container.resolve(MercurModules.COMMISSION) as CommissionModuleService
-
- const commissionLines = await promiseAll(
- input.map(async (context) => {
- return await service.getCommissionLines(context)
- })
- )
+ const commissionLines = await service.getCommissionLinesBatch(input)
return new StepResponse(commissionLines.flat())
}
diff --git a/packages/core/src/workflows/commission/steps/upsert-commission-lines.ts b/packages/core/src/workflows/commission/steps/upsert-commission-lines.ts
index 0ef82119a..6c837b106 100644
--- a/packages/core/src/workflows/commission/steps/upsert-commission-lines.ts
+++ b/packages/core/src/workflows/commission/steps/upsert-commission-lines.ts
@@ -19,6 +19,10 @@ export const upsertCommissionLinesStep = createStep(
input: UpsertCommissionLinesStepInput,
{ container }
): Promise<StepResponse<CommissionLineDTO[]>> => {
+ if (!input.commission_lines.length) {
+ return new StepResponse([])
+ }
+
const service = container.resolve<CommissionModuleService>(
MercurModules.COMMISSION
)
diff --git a/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.ts b/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.ts
index 7a023279a..056f9e4c7 100644
--- a/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.ts
+++ b/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.ts
@@ -15,24 +15,18 @@ import {
import { getCommissionLinesStep, upsertCommissionLinesStep } from "../steps"
+// The order module only decorates totals when a top-level total field such
+// as `subtotal` is selected, and derives line totals from the raw columns in
+// `items.*` / `shipping_methods.*`, so those stay in the list.
const orderFields = [
"id",
- "status",
- "version",
"currency_code",
- "email",
- "canceled_at",
- "sales_channel_id",
- "region_id",
- "customer_id",
- "customer.*",
- "customer.groups.*",
- "promotions.*",
"subtotal",
"items.*",
"items.subtotal",
"items.tax_total",
"items.total",
+ "items.adjustments.*",
"items.product.id",
"items.product.collection_id",
"items.product.categories.id",
@@ -40,14 +34,10 @@ const orderFields = [
"items.product.type_id",
"items.product.attribute_values.id",
"items.offer.seller_id",
- "items.adjustments.*",
"shipping_methods.*",
- "shipping_methods.total",
"shipping_methods.subtotal",
"shipping_methods.tax_total",
"shipping_methods.adjustments.*",
- "shipping_methods.shipping_option_id",
- "shipping_address.*",
]
export type RefreshOrderCommissionLinesWorkflowInput = {
diff --git a/packages/core/src/workflows/customer-group/steps/link-seller-customer-group.ts b/packages/core/src/workflows/customer-group/steps/link-seller-customer-group.ts
index b1ce8b934..842c46a31 100644
--- a/packages/core/src/workflows/customer-group/steps/link-seller-customer-group.ts
+++ b/packages/core/src/workflows/customer-group/steps/link-seller-customer-group.ts
@@ -11,6 +11,10 @@ type LinkSellerCustomerGroupStepInput = {
export const linkSellerCustomerGroupStep = createStep(
"link-seller-customer-group",
async (input: LinkSellerCustomerGroupStepInput, { container }) => {
+ if (!input.customer_group_ids.length) {
+ return new StepResponse(undefined, undefined)
+ }
+
const remoteLink: Link = container.resolve(ContainerRegistrationKeys.LINK)
// Module order must match the `defineLink` order in
diff --git a/packages/core/src/workflows/inventory-item/steps/link-seller-inventory-item.ts b/packages/core/src/workflows/inventory-item/steps/link-seller-inventory-item.ts
index 50c8d87b4..6f521a3af 100644
--- a/packages/core/src/workflows/inventory-item/steps/link-seller-inventory-item.ts
+++ b/packages/core/src/workflows/inventory-item/steps/link-seller-inventory-item.ts
@@ -11,6 +11,10 @@ type LinkSellerInventoryItemStepInput = {
export const linkSellerInventoryItemStep = createStep(
"link-seller-inventory-item",
async (input: LinkSellerInventoryItemStepInput, { container }) => {
+ if (!input.inventory_item_ids.length) {
+ return new StepResponse(undefined, undefined)
+ }
+
const remoteLink: Link = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = input.inventory_item_ids.map((inventoryItemId) => ({
diff --git a/packages/core/src/workflows/offer/steps/create-offers.ts b/packages/core/src/workflows/offer/steps/create-offers.ts
index f07e9dfbc..6fe3670e1 100644
--- a/packages/core/src/workflows/offer/steps/create-offers.ts
+++ b/packages/core/src/workflows/offer/steps/create-offers.ts
@@ -8,6 +8,10 @@ export type CreateOffersStepInput = CreateOfferRowDTO[]
export const createOffersStep = createStep(
"create-offers",
async (data: CreateOffersStepInput, { container }) => {
+ if (!data.length) {
+ return new StepResponse([], [])
+ }
+
const service = container.resolve<OfferModuleService>(MercurModules.OFFER)
const offers = await service.createOffers(data)
return new StepResponse(
diff --git a/packages/core/src/workflows/offer/steps/update-offer-conditions.ts b/packages/core/src/workflows/offer/steps/update-offer-conditions.ts
index aaa8e438e..692c24ea0 100644
--- a/packages/core/src/workflows/offer/steps/update-offer-conditions.ts
+++ b/packages/core/src/workflows/offer/steps/update-offer-conditions.ts
@@ -14,7 +14,7 @@ export const updateOfferConditionsStep = createStep(
const before = await service.listOfferConditions({ id: ids })
const conditions = await service.updateOfferConditions(
- input.map(({ id, ...data }) => ({ selector: { id }, data }))
+ input
)
const compensation = before.map((prev) => ({
@@ -34,7 +34,7 @@ export const updateOfferConditionsStep = createStep(
}
const service = container.resolve<OfferModuleService>(MercurModules.OFFER)
await service.updateOfferConditions(
- compensation.map(({ id, ...data }) => ({ selector: { id }, data }))
+ compensation
)
}
)
diff --git a/packages/core/src/workflows/offer/steps/update-offers.ts b/packages/core/src/workflows/offer/steps/update-offers.ts
index 846504639..14e0367fd 100644
--- a/packages/core/src/workflows/offer/steps/update-offers.ts
+++ b/packages/core/src/workflows/offer/steps/update-offers.ts
@@ -17,18 +17,17 @@ export type UpdateOffersStepInput = Array<{
export const updateOffersStep = createStep(
"update-offers",
async (data: UpdateOffersStepInput, { container }) => {
+ if (!data.length) {
+ return new StepResponse([], [])
+ }
+
const service = container.resolve<OfferModuleService>(MercurModules.OFFER)
const ids = data.map((d) => d.id)
const before = await service.listOffers({ id: ids })
const beforeById = new Map(before.map((o) => [o.id, o]))
- const offers = await service.updateOffers(
- data.map(({ id, ...update }) => ({
- selector: { id },
- data: update,
- }))
- )
+ const offers = await service.updateOffers(data)
const compensation = data.map(({ id }) => {
const prev = beforeById.get(id)
@@ -51,11 +50,6 @@ export const updateOffersStep = createStep(
return
}
const service = container.resolve<OfferModuleService>(MercurModules.OFFER)
- await service.updateOffers(
- compensation.map(({ id, ...data }) => ({
- selector: { id },
- data,
- }))
- )
+ await service.updateOffers(compensation)
}
)
diff --git a/packages/core/src/workflows/payment/workflows/split-order-payments.ts b/packages/core/src/workflows/payment/workflows/split-order-payments.ts
index 6c655abdf..fe98da0a1 100644
--- a/packages/core/src/workflows/payment/workflows/split-order-payments.ts
+++ b/packages/core/src/workflows/payment/workflows/split-order-payments.ts
@@ -1,6 +1,7 @@
import { PaymentCollectionStatus, PaymentEvents } from "@medusajs/framework/utils"
import {
createWorkflow,
+ parallelize,
transform,
when,
WorkflowResponse,
@@ -86,23 +87,27 @@ export const splitCapturedCartPaymentWorkflow = createWorkflow(
({ input }) => `split-order-payment:${input.cart_id}`
)
+ // Runs as a sub-workflow of checkout and races the `payment.captured`
+ // subscriber, so the lock must also be taken on the nested path.
acquireLockStep({
key: lockKey,
timeout: LOCK_TIMEOUT_SECONDS,
ttl: LOCK_TTL_SECONDS,
+ executeOnSubWorkflow: true,
})
- const cartPaymentQuery = useQueryGraphStep({
- entity: "cart_payment_collection",
- fields: cartPaymentCollectionFields,
- filters: { cart_id: input.cart_id },
- }).config({ name: "get-cart-payment-collection" })
-
- const cartOrdersQuery = useQueryGraphStep({
- entity: "order_cart",
- fields: cartOrderFields,
- filters: { cart_id: input.cart_id },
- }).config({ name: "get-cart-orders" })
+ const [cartPaymentQuery, cartOrdersQuery] = parallelize(
+ useQueryGraphStep({
+ entity: "cart_payment_collection",
+ fields: cartPaymentCollectionFields,
+ filters: { cart_id: input.cart_id },
+ }).config({ name: "get-cart-payment-collection" }),
+ useQueryGraphStep({
+ entity: "order_cart",
+ fields: cartOrderFields,
+ filters: { cart_id: input.cart_id },
+ }).config({ name: "get-cart-orders" })
+ )
const plan = transform(
{ cartPaymentQuery, cartOrdersQuery },
@@ -212,7 +217,7 @@ export const splitCapturedCartPaymentWorkflow = createWorkflow(
data: capturedEvents,
})
- releaseLockStep({ key: lockKey })
+ releaseLockStep({ key: lockKey, executeOnSubWorkflow: true })
return new WorkflowResponse(capturedPayments)
}
diff --git a/packages/core/src/workflows/price-list/steps/link-seller-price-list.ts b/packages/core/src/workflows/price-list/steps/link-seller-price-list.ts
index 306630cfd..cb817250e 100644
--- a/packages/core/src/workflows/price-list/steps/link-seller-price-list.ts
+++ b/packages/core/src/workflows/price-list/steps/link-seller-price-list.ts
@@ -11,6 +11,10 @@ type LinkSellerPriceListStepInput = {
export const linkSellerPriceListStep = createStep(
"link-seller-price-list",
async (input: LinkSellerPriceListStepInput, { container }) => {
+ if (!input.price_list_ids.length) {
+ return new StepResponse(undefined, undefined)
+ }
+
const remoteLink: Link = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = input.price_list_ids.map((priceListId) => ({
diff --git a/packages/core/src/workflows/promotion/steps/link-seller-promotion.ts b/packages/core/src/workflows/promotion/steps/link-seller-promotion.ts
index 2c535433c..ff699a8a2 100644
--- a/packages/core/src/workflows/promotion/steps/link-seller-promotion.ts
+++ b/packages/core/src/workflows/promotion/steps/link-seller-promotion.ts
@@ -11,6 +11,10 @@ type LinkSellerPromotionStepInput = {
export const linkSellerPromotionStep = createStep(
"link-seller-promotion",
async (input: LinkSellerPromotionStepInput, { container }) => {
+ if (!input.promotion_ids.length) {
+ return new StepResponse(undefined, undefined)
+ }
+
const remoteLink: Link = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = input.promotion_ids.map((promotionId) => ({
diff --git a/packages/core/src/workflows/shipping-option/steps/link-seller-shipping-option.ts b/packages/core/src/workflows/shipping-option/steps/link-seller-shipping-option.ts
index 535c1a670..a842ccf69 100644
--- a/packages/core/src/workflows/shipping-option/steps/link-seller-shipping-option.ts
+++ b/packages/core/src/workflows/shipping-option/steps/link-seller-shipping-option.ts
@@ -11,6 +11,10 @@ type LinkSellerShippingOptionStepInput = {
export const linkSellerShippingOptionStep = createStep(
"link-seller-shipping-option",
async (input: LinkSellerShippingOptionStepInput, { container }) => {
+ if (!input.shipping_option_ids.length) {
+ return new StepResponse(undefined, undefined)
+ }
+
const remoteLink: Link = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
const links = input.shipping_option_ids.map((shippingOptionId) => ({
diff --git a/packages/core/src/workflows/stock-location/steps/link-seller-stock-location.ts b/packages/core/src/workflows/stock-location/steps/link-seller-stock-location.ts
index 2194ec5ea..a7220493d 100644
--- a/packages/core/src/workflows/stock-location/steps/link-seller-stock-location.ts
+++ b/packages/core/src/workflows/stock-location/steps/link-seller-stock-location.ts
@@ -11,6 +11,10 @@ type LinkSellerStockLocationStepInput = {
export const linkSellerStockLocationStep = createStep(
"link-seller-stock-location",
async (input: LinkSellerStockLocationStepInput, { container }) => {
+ if (!input.stock_location_ids.length) {
+ return new StepResponse(undefined, undefined)
+ }
+
const remoteLink: Link = container.resolve(ContainerRegistrationKeys.LINK)
const links = input.stock_location_ids.map((stockLocationId) => ({
diff --git a/packages/types/src/commission/provider.ts b/packages/types/src/commission/provider.ts
index 072a8df97..e41a1ec5c 100644
--- a/packages/types/src/commission/provider.ts
+++ b/packages/types/src/commission/provider.ts
@@ -13,6 +13,15 @@ export interface ICommissionProvider {
getCommissionLines(
context: CommissionCalculationContext
): Promise<CreateCommissionLineDTO[]>
+
+ /**
+ * Compute lines for several contexts at once, one result per context in
+ * the same order. Lets a provider load its rate data a single time per
+ * batch. Falls back to `getCommissionLines` per context when not implemented.
+ */
+ getCommissionLinesBatch?(
+ contexts: CommissionCalculationContext[]
+ ): Promise<CreateCommissionLineDTO[][]>
}
export interface CommissionModuleOptions {