Skip to content

Releases: medusajs/medusa

v2.8.6: Strengthened workflow engine and improved account holder management

30 Jun 14:23
Compare
Choose a tag to compare

Highlights

Strengthen the workflow engine

This release improves the workflow engine's data flow. When resuming workflows, we now compile workflow data (i.e. input and outputs of previous steps) from Redis and Postgres to ensure the most recent workflow execution and associated data are used.

Improve payment account holder flows

This release improves how payment account holders are managed when creating payment sessions in the createPaymentSessionWorkflow. In this workflow, we create a new payment account holder for the customer on the cart if it doesn't already exist. When the workflow fails in a later step, the compensation flow is triggered, and we now ensure we are only deleting the account holder if it was created as part of the invoke, i.e. it didn't exist before running the workflow.

Bugs

  • fix: do not apply prefix when getting file contents as buffer or stream by @thetutlage in #12831
  • fix(core-flows,workflows-sdk): compensate account holders only when its created by @riqwan in #12825
  • fix(): test utils events + workflow storage by @adrien2p in #12834
  • fix: fix onScroll in Select.Content by @peterlgh7 in #12855

Documentation

Chores

Other Changes

New Contributors

Full Changelog: v2.8.5...v2.8.6

v2.8.5: Tax-inclusive Promotions, Improved Product Imports, and Faster Application Startup

25 Jun 09:58
Compare
Choose a tag to compare

Highlights

Improved Product Imports

This release overhauls the bulk import process to make it more performant and include strict validations to catch formatting issues or typos during the pre-processing phase.

Import phases

A CSV file with products to import goes through the following two phases.

  • Pre-processing: In the pre-processing phase, we validate the contents of the entire file, check for typos, unknown columns, invalid data types, or missing values, and report errors as soon as you upload the file.
  • Importing: Products are imported in the background (as it could be time-consuming with large product catalogs). Since the validations have already been performed during the pre-processing phase, the chances of failure during the import phase are rare. However, certain database constraints around duplicate data might result in a failure.

Changes to import template

Earlier, the import template (downloaded from the admin dashboard) was out of sync with our documentation and supported many columns that were part of Medusa V1.

However, now the import template strictly allows the columns mentioned in the documentation, and an error will be raised if an unknown column is specified in the CSV file.

Performance improvements

The following changes have been made to the internals to improve the import performance and memory consumption.

  • Use S3 direct uploads instead of self-importing and storing huge CSV files on a Medusa server. For this, you must configure the S3 file provider in production.
  • Read the CSV contents as a stream of chunks and process/validate 1000 rows at a time. As a result, we never read or process the entire CSV file in memory. From our tests, this led to a memory drop from 4GB to 500MB when processing a file with 62000 rows.

Tax-inclusive Promotions

This release introduces an option to specify if fixed promotions take effect before or after taxes. Up until now, fixed promotions would always be applied before taxes, which could lead to unexpected total calculations in scenarios where pricing was otherwise tax-inclusive.

For example, consider a fixed promotion with a value of $10 applied to a tax-inclusive cart of $100 in a tax region with a 25% tax rate.

Before promotion is applied:

  • Cart total (tax-inclusive) -> $100 ($80 ex. 25% VAT)

After promotion is applied:

  • Cart total (tax-inclusive) -> $87.5 ($70 ex. 25% VAT)

As you can see, the cart is reduced by $12.5 even though the promotion value was $10. The calculation we used to perform to find the promotion adjustment was:

const adjustmentTotal = (cartWithoutTax - promotion.value) * (1 + tax_rate)

In our example, this would be:

const adjustmentTotal = (80 - 10) * (1.25) = 87.5

In this release, we updated this calculation to ensure the correct adjustment total. It looks as follows:

const adjustmentTotal = (cartWithoutTax - (promotion.value / 1 + tax_rate)) * (1 + tax_rate)

In our example, this would be:

const adjustmentTotal = (80 - 8) * (1.25) = 90

The tax-inclusivity option on a promotion is part of the promotion creation flow in the admin dashboard.

Improved application startup time

This release reduces application startup time by around ~75%. For example, on Medusa Cloud, the startup time for a relatively simple Medusa application has gone from 20 seconds to around 4 seconds. This improvement comes from parallelizing the bootstrapping of modules. Modules are strictly independent from each other, so this should have no side effects.

Querying deleted records

This release fixes issues with querying for deleted database records.

Up until now, filtering data by providing any value to the deleted_at filter would be treated as if you wanted to fetch deleted records.

For example:

const { data } = await query.graph({
  entity: "product",
  filters: { deleted_at: { $eq: null } }
}) 

In this query request, we are asking for all non-deleted records; however, we mistakenly assumed that any deleted_at filter would always be filtering for deleted records, so in this case, the result set would contain deleted records.

In this release, we remove the autodetection mechanism in favor of an explicit flag withDeleted.

To query deleted records, you now need to pass the flag to the request:

const { data } = await query.graph({
  entity: "product",
  filters: { deleted_at: { "<some timestamp>" } }
  withDeleted: true
}) 

Features

  • feat: wire up direct uploads with local file provider by @thetutlage in #12643
  • feat(promotion, dashboard, core-flows, cart, types, utils, medusa): tax inclusive promotions by @fPolic in #12412
  • feat(dashboard,types): add credit lines + loyalty changes by @riqwan in #11885
  • feat: Improve startup time by parallelizing module and link loading by @sradevski in #12731
  • feat: Normalize payment method data and options when passed to Stripe by @sradevski in #12757
  • fix(dashboard, types): loyalty UI changes by @fPolic in #12764
  • feat(): Add support for jwt asymetric keys by @adrien2p in #12813
  • feat: add cookie options by @riqwan in #12720

Bugs

  • fix(workflow-sdk): Async/nested runAsStep propagation by @adrien2p in #12675
  • fix: update product import template by @thetutlage in #12697
  • fix(create-medusa-app): remove "Created admin user" message by @shahednasser in #12707
  • fix(promotion, types): non discountable items check by @fPolic in #12644
  • fix: remote query types by @thetutlage in #12712
  • fix(core-flows): cart complete order address creation by @fPolic in #12493
  • fix(utils): medusa internal service returned data should match typings by @adrien2p in #12715
  • fix(utils): Typecasting non-text fields in FTS by @olivermrbl in #12729
  • fix: Disable ensure database checks when establishing DB connection by @sradevski in #12734
  • fix(create-medusa-app): ensure the same package manager is used consistently by @shahednasser in #12714
  • fix(payment): add account holder methods to the manual provider by @fPolic in #12751
  • fix(core, medusa-test-utils): Fix medusa test runner plugin modules loading by @adrien2p in #12753
  • fix: Add missing partially funded event handler for Stripe by @sradevski in #12763
  • fix: initiate request container before other express middleware by @thetutlage in #12761
  • fix(dashboard): fix subtitle for tax inclusive fields in promotions by @shahednasser in #12776
  • fix(workflow-engine-redis): Ensure PK is set without errors by @olivermrbl in #12775
  • fix: add operators to RemoteQueryFilters by @peterlgh7 in #12735
  • fix: Return and set the correct status when a session is created with… by @sradevski in #12769
  • fix: Allow setting the status of a payment session when updating by @sradevski in #12809
  • fix(workflow-engine-*): Cleanup expired executions and reduce redis storage usage by @adrien2p in #12795
  • fix(medusa): Query Config update Order By filter by @juanzgc in #12781
  • fix(payment): round currency precision by @carlos-r-l-rodrigues in #12803
  • fix(dashboard): fix currency input locale formatting by @fPolic in #12812
  • fix(utils): build query withDeleted remove auto detection by @adrien2p in #12788
  • fix: Add missing migration for payment statuses by @sradevski in #12821

Documentation

Read more

v2.8.4: Strengthening of cart-completion flows

05 Jun 18:43
Compare
Choose a tag to compare

Highlights

Eliminate race condition in cart-completion flow

This release strengthens the cart-completion flow by eliminating a potential race condition that, in rare cases, could result in an incorrectly refunded payment.

The race condition occurs when cart completion is triggered from two sources: 1) the regular HTTP request to POST /store/carts/:id/complete, and 2) a webhook event from the payment provider signaling successful payment authorization.

To reduce the risk of a conflict, we have, up until now, delayed webhook processing by 5 seconds. However, this mitigation proved insufficient in some cases.

Now, whenever the completeCartWorkflow is executed whether via the API route or the webhook handler, we now hold a lock on the cart ID for the duration of the workflow. This lock ensures that multiple completion attempts for the same cart are processed sequentially. Once a cart is successfully completed (typically on the first attempt), subsequent attempts will detect the completed cart and exit early, returning the associated order.

Features

Bugs

Documentation

Chores

  • chore(modules-sdk): Log full error when a loader fail to run by @adrien2p in #12584
  • chore(core-flows): ignore hooks in complete cart workflow by @shahednasser in #12600

Other Changes

New Contributors

Full Changelog: v2.8.3...v2.8.4

v2.8.3

22 May 12:10
Compare
Choose a tag to compare

Highlights

New Analytics module and Posthog provider

This release introduces a new Analytics module, allowing you to easily set up server-side tracking of events and users.

The module comes with two methods:

 /**
   * This method tracks an event in the analytics provider.
   *
   * @param {TrackAnalyticsEventDTO} data - The event's details.
   * @returns {Promise<void>} Resolves when the event is tracked successfully.
   *
   * @example
   * await analyticsModuleService.track({
   *   event: "order_placed",
   *   properties: {
   *     order_id: "order_123",
   *     customer_id: "customer_456",
   *     total: 100,
   *   }
   * })
   */
track(data: TrackAnalyticsEventDTO): Promise<void>

 /**
   * This method identifies an actor or group in the analytics provider.
   *
   * @param {IdentifyAnalyticsEventDTO} data - The details of the actor or group.
   * @returns {Promise<void>} Resolves when the actor or group is identified successfully.
   *
   * @example
   * await analyticsModuleService.identify({
   *   actor_id: "123",
   *   properties: {
   *     name: "John Doe"
   *   }
   * })
   */
identify(data: IdentifyAnalyticsEventDTO): Promise<void>

To configure the Analytics module, register it in the modules of your medusa-config.ts:

  ...
  modules: [
    ...,
    {
      resolve: "@medusajs/medusa/analytics",
      options: {
        providers: [{ ... }],
      },
    },
  ],
  ...

The Analytics module does not do much as is. You need to configure a provider responsible for handling the tracking. This release comes with two moduNopeles, @medusajs/analytics-local and @medusajs/analytics-posthog. The former will log the events and can be used for local development. The latter is an official integration with Posthog.

The provider is installed like so:

  ...
  modules: [
    ...,
    {
      resolve: "@medusajs/medusa/analytics",
      options: {
        providers: [ 
          {
            resolve: "@medusajs/analytics-posthog",
            options: {
              posthogEventsKey: "<your-api-key>",
              posthogHost: "<your host>",
            }
          }
      }],
    },
  ],
  ...

Read more about the new module and providers in our documentation.

Features

  • feat(index): Only run the synchronisation in worker/shared mode by @adrien2p in #12530
  • chore(product, modules-sdk): Add missing index for select-in strategy + allow to pass top level strategy to force the behaviour by @adrien2p in #12508
  • feat: Add an analytics module and local and posthog providers by @sradevski in #12505
  • feat: process import from pre-processed chunks by @thetutlage in #12527
  • feat: add presignedUrl method to upload sdk by @christiananese in #12569

Bugs

Documentation

Chores

Other Changes

New Contributors

Full Changelog: v2.8.2...v2.8.3

v2.8.2

16 May 09:36
Compare
Choose a tag to compare

Highlights

Fixes regression related to updating weight, height, length, and width on products

Features

Bugs

  • fix(types): change update signature of IAuthProvider by @shahednasser in #12496
  • fix: fix weight/length/height/width types in updates by @peterlgh7 in #12500
  • fix(core-flows): fulfilment cancelation with shared inventory kit item by @fPolic in #12503

Documentation

Chores

Full Changelog: v2.8.1...v2.8.2

v2.8.1

15 May 07:53
Compare
Choose a tag to compare

Highlights

Fixes a regression introduced in v2.8.0

In v2.8.0, we unintentionally introduced a regression that affected ordering products returned from the product module service. This broke workflows (e.g. updateProductsWorkflow) that rely on consistent ordering for subsequent operations such as applying price updates. This release brings back the correct ordering behavior and resolves the issue.

We strongly recommend upgrading to v2.8.1 as soon as possible to avoid incorrect data.

Features

Bugs

Documentation

Chores

Full Changelog: v2.8.0...v2.8.1

v2.8.0: Fix regression with product updates

13 May 11:10
Compare
Choose a tag to compare

Highlights

Important: This release introduced a regression with product updates

We unintentionally introduced a regression that affected the ordering of products returned from the product module service. This broke workflows (e.g. updateProductsWorkflow) that rely on consistent ordering for subsequent operations such as applying price updates.

Upgrade to v2.8.1 as soon as possible to avoid any issues related to this change.

Cart-completion robustness

Warning

Breaking changes

This release introduces important changes to the completeCartWorkflow aimed at improving robustness and making it easier to recover from failures.

Changes to idempotency

Until now, the workflow has had the following configuration:

{
  name: completeCartWorkflowId
  store: true,
  idempotent: true,
  retentionTime: THREE_DAYS,
}

Here's a brief description of what these properties do, excluding name:

  • store: Store the workflow execution. If no retention time is specified, the workflow is only stored for the duration of its execution
  • idempotent: Store the result of the first workflow execution and return it on subsequent runs
  • retentionTime: Store the result in the configured data store for "x" amount of time–here, three days

In this release, we change the idempotent flag from true to false. Initially, the idea of having an idempotent cart-completion stemmed from wanting to ensure that multiple requests to complete the same cart would lead to the same outcome. This is, in of itself, still reasonable to ensure there is only ever one attempt to complete the same cart. However, in case of failures, the idempotent mechanism makes it challenging to recover, since a new cart with the same details is required to re-attempt the completion. This is because the result of the failing workflow is stored and returned on all subsequent runs, regardless of whether the cart is updated to satisfy the constraints for completion.

With idempotent set to false, it will be possible to retry failed executions, making it simpler to bring the cart to a satisfying state and eventually create the order.

It is worth mentioning that concurrency continues to be appropriately managed by passing the cart ID as the transactionId when running the workflow. The transaction ID ensures that only one workflow execution can run at a time.

Changes to the structure

The workflow has been slightly restructured to minimize the risk of payment sessions getting stuck in a state that is difficult to recover from. More specifically, the payment authorization step has been moved to the very end of the workflow, so that all first-party checks are performed before we authorize the payment.

To understand why this is important, we need to cover the compensateIfNeeded step of the workflow briefly. This step compensates active payment sessions in the case of failure to avoid orphaned third-party payments and recreates the Medusa payment session so that new payment details can be attached.

For example, suppose the payment authorization is performed off-band (e.g., in a webhook), and the cart-completion workflow fails to execute. In that case, the step will void the third-party payment and bring the cart to a correct state, all while ensuring consistency between the two systems.

Moving the payment authorization step to the end of the workflow ensures that we only create an authorized payment if all other cart constraints are satisfied.

Changes to the webhook handler

The webhook handler ensures consistency between Medusa and the third-party payment provider. More specifically, it will handle the following scenarios:

  • Payment authorization: when we receive a payment authorization event, we will attempt to authorize and create a payment in Medusa
  • Payment capture: when we receive a payment capture event, we will attempt to capture the associated payment in Medusa
  • Cart-completion: when we receive a payment authorization event, we will attempt to complete the cart
  • Payment authorization and capture: when we receive a payment capture event and there is no existing payment in Medusa, we will attempt to authorize, create, and capture a payment in Medusa

We have only handled the first three scenarios until now. This release introduces functionality for the fourth, a more unusual scenario involving auto-captures in the third-party payment provider.

Line item generation

Warning

Breaking changes

This release changes the source of line item titles and subtitles. The title has changed from the variant title to the product title, and the subtitle has changed from the product title to the variant title.

Cross-module filters (experimental)

This release introduces experimental support for cross-module filters via a new module, @medusajs/index.

Please remember that this module is experimental and in development, so please use it cautiously. It is subject to change as we finalize the design to enable cross-module filtering.

We will keep the description brief since the module is still in development. Here's what you need to know:

  • Medusa's architecture is divided into a range of modules, each being isolated (at the data model level) from one another. By default, the modules share the same database, but the architecture is built to support external data sources, in case your module needs a different type of database, or you want to use a third-party service in place of Medusa's core module
  • Consequently, queries to retrieve data are performed per module, and the data is aggregated in the end to create the result set
  • Our new index module allows you to ingest data into a central, relational-like structure
  • The structure enables efficient filtering over data coming from different data sources (provided it is ingested)

The index module can be enabled by installing the module:

yarn add @medusajs/index

Adding it to your Medusa config:

{
  // ...rest of config
  modules: [{ resolve: "@medusajs/index", options: {} }]
}

And finally, adding a feature flag to enable it:

// .env
MEDUSA_FF_INDEX_ENGINE=true

Then, apply the migrations to create the related tables:

npx medusa db:migrate

The next time you start your server, we will ingest data into the index engine.

In this first iteration, we only ingest the following core entities:

  • Products
  • Product Variants
  • Prices
  • Sales Channels

The data in the index is queried through a new API with semantics identical to the existing query graph:

  const { data: products = [], metadata } = await query.index({
    entity: "product",
    fields: ["id", "name"],
  });

In addition to ingesting a few select resources from the core, we have added support for ingesting data from custom modules through link definitions. For example, say you want to introduce a Brand on Products and filter your Products by it.

Assuming you have added a Brand module, you create a link as follows:

import { defineLink } from "@medusajs/framework/utils";
import ProductModule from "@medusajs/medusa/product";
import BrandModule from "../modules/brand";

export default defineLink(
  {
    linkable: ProductModule.linkable.product,
    isList: true,
  },
  {
    linkable: BrandModule.linkable.brand,
  }
);

This link will associate the two data models and allow you to query them from both sides of the link.

Furthermore, to ingest the Brand into the index and make the data filterable, you need to add the new filterable property to the link:

import { defineLink } from "@medusajs/framework/utils";
import ProductModule from "@medusajs/medusa/product";
import BrandModule from "../modules/brand";

export default defineLink(
  {
    linkable: ProductModule.linkable.product,
    isList: true,
  },
  {
    linkable: BrandModule.linkable.brand,
    filterable: ["id", "name"]
  }
);

The link above specifies that Brands should be ingested into the index and made filterable via the properties id and title.

As a result, you can now filter Products by Brands ID or title like so:

  const { data: products = [], metadata } = await query.index({
    entity: "product",
    fields: ["id", "title", "brand.*"],
    filters: {
      brand: {
        name: "Hermes"
      }
    },
  });

An important trade-off in the index module is the need to avoid the performance cost of COUNT(*) queries, which can be an incredibly high cost for very large data sets. Instead, we use Postgres’ internal query planner to compute an estimated count of the result set. For very small data sets, this estimate can be very inaccurate, but for larger ones it should provide a reasonable estimate. The trade-off allows us to achieve very fast response times making it ideal for user-facing search and browsing experiences. As noted earlier, the tool is still experimental, and we plan to continue iterating and improving it over time.

Custom Tax Providers

This release introduces full support for custom Tax Providers by making these key changes:

  • Load custom Tax Providers in the Tax Module
  • Manage (create, update) provider per Tax Region in the admin dashboard
  • Migrate all Tax Regions to use a tax provider

The migration script will run the first time you start the server after upgrading. It will assign the default system provider to the Tax Region, if the region did not have a custom provider specified already.

Feat...

Read more

v2.7.1: Strengthened workflow engine, expanded data for fulfillments, and more robust event handling

23 Apr 07:37
Compare
Choose a tag to compare

Highlights

Expanded fulfillment data

This release extends fulfillment capabilities by exposing more core order data to fulfillment providers–that is, data passed upon creating fulfillments in Medusa.

The additional data included on orders passed to providers are:

  • display_id
  • region
  • customer_id
  • customer
  • sales_channel_id
  • sales_channel
  • items.variant.upc
  • items.variant.sku
  • items.variant.barcode
  • items.variant.hs_code
  • items.variant.origin_country
  • items.variant.product.origin_country
  • items.variant.product.hs_code
  • items.variant.product.mid_code
  • items.variant.product.material
  • items.tax_lines.rate
  • subtotal
  • discount_total
  • tax_total
  • item_total
  • shipping_total
  • total
  • created_at

Strengthened workflow engine

We have improved the core internals of our workflow engine, including fixing an issue with events grouping not working correctly for async workflows.

Read more in the PRs below:

Features

  • feat(core-flows, js-sdk, medusa): draft order shipping removal by @fPolic in #12124
  • feat: Add support for dynamoDB for storing sessions and some types cleanup by @thetutlage in #12140
  • feat(orchestration): skip on permanent failure by @carlos-r-l-rodrigues in #12027
  • feat: Add support for uploading a file directly to the file provider from the client by @sradevski in #12224

Bugs

  • fix(dashboard): display null sku by @fPolic in #12155
  • fix(types): fix type of application_method_type filter by @shahednasser in #12160
  • fix(core-flows): draft order reservations by @fPolic in #12115
  • fix(index): Default schema typings by @adrien2p in #12183
  • fix(): Event group id propagation and event managements by @adrien2p in #12157
  • fix(payment): properly delete refund by @fPolic in #12193
  • fix: apply additional data validator using a global middleware by @thetutlage in #12194
  • fix(dashboard): properly register settings custom routes by @fPolic in #12198
  • fix(): Properly handle workflow as step now that events are fixed entirely by @adrien2p in #12196
  • fix(core-flows): export registerOrderDeliveryStep by @shahednasser in #12221
  • fix: expose beforeRefreshingPaymentCollection hook by @thetutlage in #12232
  • fix(medusa): sales_channel_id middleware manipulation leading to lost of the sc by @adrien2p in #12234
  • fix: steps to return undefined and still chain the config method by @thetutlage in #12255
  • fix(core-flows, link-modules): return fulfillment creation by @fPolic in #12227
  • fix: oas CLI to convert Windows paths to unix by @thetutlage in #12254

Documentation

Chores

Other Changes

New Contributors

Read more

v2.7.0: Save payment methods, improved links, and performance improvements

11 Apr 08:53
Compare
Choose a tag to compare

Highlights

Support multiple payment account holders for customers

Warning

Breaking changes

This release adds support for a customer to have multiple account holders, therefore supporting multiple payment providers at the same time.

If you were using customer.account_holder in your implementation, you must change it to customer.account_holders and choose the relevant one for the provider_id you want to use.

If you haven't done anything custom with payments and account holders, there are no breaking changes.

Enforce integrity constraints on module links

This release enforces integrity constraints on module links in the application layer.

The constraints are enforced as exemplified below:

One-to-one

export default defineLink(
  ProductModule.linkable.product,
  CustomModule.linkable.customModel
)

// This succeeds
await link.create({
  [Modules.PRODUCT]: {
    product_id: "prod_123",
  },
  "customModule": {
    custom_id: "cus_123",
  },
})

// This throws
await link.create({
  [Modules.PRODUCT]: {
    product_id: "prod_123",
  },
  "customModule": {
    custom_id: "cus_321",
  },
})

// This throws
await link.create({
  [Modules.PRODUCT]: {
    product_id: "prod_321",
  },
  "customModule": {
    custom_id: "cus_123",
  },
})

One-to-many / Many-to-one

export default defineLink(
  ProductModule.linkable.product,
  {
    linkable: CustomModule.linkable.customModel,
    isList: true,
  }
)

// export default defineLink(
//   { 
//     linkable: ProductModule.linkable.product,
//     isList: true,
//   },
//   CustomModule.linkable.customModel
// )

// This succeeds
await link.create({
  [Modules.PRODUCT]: {
    product_id: "prod_123",
  },
  "customModule": {
    custom_id: "cus_123",
  },
})

// This succeeds
await link.create({
  [Modules.PRODUCT]: {
    product_id: "prod_123",
  },
  "customModule": {
    custom_id: "cus_321",
  },
})

// This throws
await link.create({
  [Modules.PRODUCT]: {
    product_id: "prod_456",
  },
  "customModule": {
    custom_id: "cus_123",
  },
})

Many-to-many

export default defineLink(
  {
    linkable: ProductModule.linkable.product,
    isList: true
  },
  {
    linkable: CustomModule.linkable.customModel,
    isList: true,
  }
)

// This succeeds
await link.create({
  [Modules.PRODUCT]: {
    product_id: "prod_123",
  },
  "customModule": {
    custom_id: "cus_123",
  },
})

// This succeeds
await link.create({
  [Modules.PRODUCT]: {
    product_id: "prod_123",
  },
  "customModule": {
    custom_id: "cus_321",
  },
})

// This succeeds
await link.create({
  [Modules.PRODUCT]: {
    product_id: "prod_456",
  },
  "customModule": {
    custom_id: "cus_123",
  },
})

Introduce dynamic pricing workflow hooks

This release introduces workflow hooks to override the default pricing context passed to the pricing module when calculating prices for variants and shipping options.

Prices with custom rules need a different context than what is passed by default. For example, say you have a custom rule that ties prices with a specific location location_id: loc_1234. To account for this rule in the price calculation logic, the pricing context needs to be populated with a location_id.

The pricing hooks are used as follows:

// src/workflows/hooks/pricing-hooks.ts
import { addToCartWorkflow } from "@medusajs/medusa/core-flows";
import { StepResponse } from "@medusajs/workflows-sdk";

addToCartWorkflow.hooks.setPricingContext(() => {
  return new StepResponse({
    location_id: "loca_1234", // Special price for in-store purchases
  });
});

Assuming you have a custom pricing rule { attribute: "location_id", operator: "eq", value: "loca_1234" }, this would be part of the pricing result set when retrieving the associated product variant or adding the same to the cart.

The hooks have been introduced to the following workflows:

  • addToCartWorkflow
  • createCartsWorkflow
  • listShippingOptionsForCartWorkflow
  • refreshCartItemsWorkflow
  • updateLineItemInCartWorkflow
  • addLineItemsToOrderWorkflow
  • updateClaimShippingMethodWorkflow
  • createOrderWorkflow
  • updateExchangeShippingMethodWorkflow
  • createOrderEditShippingMethodWorkflow
  • updateOrderEditShippingMethodWorkflow
  • createCompleteReturnWorkflow
  • updateReturnShippingMethodWorkflow

Please don't hesitate to submit a Github issue, if you want us to consider adding the hook to more workflows.

Resolve issues with broken plugin dependencies in development server

This release reworks how admin extensions are loaded from plugins and how extensions are managed internally in the dashboard project.

Previously we loaded extensions from plugins the same way we do for extensions found in a user's application. This being scanning the source code for possible extensions in .medusa/server/src/admin, and including any extensions that were discovered in the final virtual modules.

This was causing issues with how Vite optimizes dependencies and would lead to CJS/ESM issues.

To circumvent the above issue, we have changed the strategy for loading extensions from plugins. We now build plugins slightly different–if a plugin has admin extensions, we build those to .medusa/server/src/admin/index.mjs and .medusa/server/src/admin/index.js for a ESM and CJS build.

When determining how to load extensions from a source, we follow these rules:

  • If the source has a medusa-plugin-options.json or is the root application, we determine that it is a local extension source and load extensions as previously through a virtual module.
  • If it has neither of the above, but has a ./admin export in its package.json, then we determine that it is a package extension, and we update the entry point for the dashboard to import the package and pass its extensions along to the dashboard manager.

Changes required by plugin authors

The change has no breaking changes, but requires plugin authors to update the package.json of their plugins to also include a ./admin export. It should look like this:

{
  "name": "@medusajs/plugin",
  "version": "0.0.1",
  "description": "A starter for Medusa plugins.",
  "author": "Medusa (https://medusajs.com)",
  "license": "MIT",
  "files": [
    ".medusa/server"
  ],
  "exports": {
    "./package.json": "./package.json",
    "./workflows": "./.medusa/server/src/workflows/index.js",
    "./.medusa/server/src/modules/*": "./.medusa/server/src/modules/*/index.js",
    "./modules/*": "./.medusa/server/src/modules/*/index.js",
    "./providers/*": "./.medusa/server/src/providers/*/index.js",
    "./*": "./.medusa/server/src/*.js",
    "./admin": {
      "import": "./.medusa/server/src/admin/index.mjs",
      "require": "./.medusa/server/src/admin/index.js",
      "default": "./.medusa/server/src/admin/index.js"
    }
  },
}

Improve performance of price-selection

This release comes with significant optimizations of the pricing retrieval query to improve performance, especially on large datasets.

We have:

  • Removed costly subqueries and excessive joins
  • Leveraged targeted subqueries and indexed filters for rule checks
  • Optimized queries without rule contexts to bypass unnecessary logic

The improvements have been tested on a dataset with ~1,200,000 prices and ~1,200,000 price rules. The impact of the changes are as follows:

  • Before: ~718ms execution time
  • After: ~17ms execution time

We are dedicated to continuously improve performance, so you can expect further improvements going forward.

Improve the robustness of payment workflows

This release improves the robustness of payment workflows by squashing a range of minor bugs.

These fixes can be found in the following PRs:

Features

  • fix(medusa,utils,test-utils,types,framework,dashboard,admin-vite-plugin,admin-bundler): Fix broken plugin dependencies in development server by @kasperkristensen in #11720
  • refactor: use module name as the snapshot name by @thetutlage in #11802
  • feat: Change customer to account_holder to be one-to-many by @sradevski in #11803
  • feat: add check for uniqueness when creating links with isList=false by @thetutlage in #11767
  • fix(types,order,medusa): Create credit lines + hooks by @riqwan in #11569
  • feat(dashboard,js-sdk,admin-shared): add customer addresses + layout change by @riqwan in #11871
  • feat(core-flows,types,utils): make payment optional when cart balance is 0 by @riqwan in #11872
  • feat(medusa,types): add enabled plugins route by @riqwan in #11876
  • feat: Add support for generating a production-ready config out of the… by @sradevski in #11850
  • feat: add support for accessing step results via context by @thetutlage in https://github.com/medusajs/medusa/p...
Read more

v2.6.1: Improved Scheduled Jobs

10 Mar 15:47
Compare
Choose a tag to compare

Highlights

Scheduled Jobs execution

Ensure Scheduled Jobs are only executed by server instances running in worker or shared mode. Our workflow engine powers scheduled jobs, and we create a workflow for every job. Scheduled Jobs (i.e. workflows) are not registered in servers that run in server mode. Consequently, if a server instance tries to pick up a Scheduled Job, it will fail, as it cannot find the underlying workflow. This change ensures that only worker and shared server instances execute Scheduled Jobs.

Features

  • feat(workflows-sdk): Allow when then in parallelize by @adrien2p in #11756

Bugs

Documentation

Chores

Full Changelog: v2.6.0...v2.6.1