diff --git a/www/apps/book/app/learn/fundamentals/framework/page.mdx b/www/apps/book/app/learn/fundamentals/framework/page.mdx
new file mode 100644
index 0000000000..fb3a7a7ac7
--- /dev/null
+++ b/www/apps/book/app/learn/fundamentals/framework/page.mdx
@@ -0,0 +1,1085 @@
+import { CardList, SplitSections, SplitSection, CodeTabs, CodeTab, SplitList } from "docs-ui"
+
+export const metadata = {
+ title: `${pageNumber} Framework Overview`,
+}
+
+# {metadata.title}
+
+In this chapter, you'll learn about the Medusa Framework and how it facilitates building customizations in your Medusa application.
+
+## What is the Medusa Framework?
+
+All commerce application require some degree of customization. So, it's important to choose a platform that facilitates building those customizations.
+
+When you build customizations with other ecommerce platforms, they require you to pull data through HTTP APIs, run custom logic that span across systems in a separate application, and manually ensure data consistency across systems. This adds significant overhead and slows down development as you spend time managing complex distributed systems.
+
+The Medusa Framework eliminates this overhead by providing powerful low-level APIs and tools that let you build any type of customization directly within your Medusa project. You can build custom features, orchestrate operations and query data seamlessy across systems, extend core functionality, and automate tasks in your Medusa application.
+
+With the Medusa Framework, you can focus your efforts on building meaningful business customizations and continuously delivering new features.
+
+Using the Medusa Framework, you can build customizations like:
+
+- Product Reviews
+- Deep integration with an ERP system.
+- CMS integration with seamless content retrieval.
+- Custom item pricing in the cart.
+- Automated restock notifications.
+- Re-usable payment provider integrations.
+
+### Framework Concepts and Tools
+
+
+
+---
+
+## Build Custom Features
+
+The Medusa Framework allows you to build custom features tailored to your business needs.
+
+To create a custom feature, you can create a [module](../modules/page.mdx) that contains your feature's data models and the logic to manage them. A module is integrated into your Medusa application without side effects.
+
+
+
+
+export const modelHighlights = [
+ ["3", "Post", "Create a data model with Medusa's Data Model Language (DML)."]
+]
+
+```ts highlights={modelHighlights}
+import { model } from "@medusajs/framework/utils"
+
+export const Post = model.define("post", {
+ id: model.id().primaryKey(),
+ title: model.text(),
+})
+```
+
+
+
+
+
+export const serviceHighlights = [
+ ["4", "MedusaService", "Save time by extending the `MedusaService` for basic CRUD operations."]
+]
+
+```ts highlights={serviceHighlights}
+import { MedusaService } from "@medusajs/framework/utils"
+import { Post } from "./post"
+
+export class BlogModuleService extends MedusaService({
+ Post,
+}){
+ // CRUD methods generated by MedusaService
+}
+```
+
+
+
+
+
+```ts
+import { Module } from "@medusajs/framework/utils"
+import { BlogModuleService } from "./service"
+
+export const BLOG_MODULE = "blog"
+
+export default Module(BLOG_MODULE, {
+ service: BlogModuleService,
+})
+```
+
+
+
+
+
+Then, you can build commerce features and flows in [workflows](../workflows/page.mdx) that use your module. By using workflows, you benefit from features like [rollback mechanism](../workflows/compensation-function/page.mdx) and [retry configuration](../workflows/retry-failed-steps/page.mdx).
+
+
+
+
+export const stepHighlights = [
+ ["19", "", "Define the rollback logic for any step."]
+]
+
+```ts highlights={stepHighlights}
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { BlogModuleService, BLOG_MODULE } from "../../modules/blog"
+
+type Input = {
+ title: string
+}
+
+const createPostStep = createStep(
+ "create-post",
+ async (input: Input, { container }) => {
+ const blogModuleService: BlogModuleService = container.resolve(
+ BLOG_MODULE
+ )
+
+ const post = await blogModuleService.createPosts(input.title)
+
+ return new StepResponse(post, post.id)
+ },
+ async (postId, { container }) => {
+ if (!postId) {
+ return
+ }
+
+ const blogModuleService: BlogModuleService = container.resolve(
+ BLOG_MODULE
+ )
+
+ await blogModuleService.deletePosts(postId)
+ }
+)
+```
+
+
+
+
+```ts
+import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
+import { createPostStep } from "./steps"
+
+type Input = {
+ title: string
+}
+
+export const createPostWorkflow = createWorkflow(
+ "create-post",
+ (input: Input) => {
+ const post = createPostStep(input)
+
+ return new WorkflowResponse(post)
+ }
+)
+```
+
+
+
+
+Finally, you can expose your custom feature with [API routes](../api-routes/page.mdx) that are built on top of your module and workflows.
+
+```ts title="API Route Example"
+import type {
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { createPostWorkflow } from "../../../workflows/create-post"
+
+type PostRequestBody = {
+ title: string
+}
+
+export const POST = async (
+ req: MedusaRequest,
+ res: MedusaResponse
+) => {
+ const { result } = await createPostWorkflow(req.scope)
+ .run({
+ input: result.validatedBody
+ })
+
+ return res.json(result)
+}
+```
+
+### Examples
+
+The following tutorials are step-by-step guides that show you how to build custom features using the Medusa Framework.
+
+
+
+### Start Learning
+
+To learn more about the different concepts useful for building custom features, check out the following chapters:
+
+
+
+---
+
+## Extend Existing Features
+
+The Medusa Framework is flexible and extensible, allowing you to extend and build on top of existing models and features.
+
+To associate new properties and relations with an existing model, you can create a [module](../modules/page.mdx) with data models that define these additions. Then, you can define a [module link](../module-links/page.mdx) that associates two data models from separate modules.
+
+
+
+
+export const defineLinkHighlights = [
+ ["5", "defineLink", "Define a link between products and brands."]
+]
+
+```ts highlights={defineLinkHighlights}
+import BrandModule from "../modules/brand"
+import ProductModule from "@medusajs/medusa/product"
+import { defineLink } from "@medusajs/framework/utils"
+
+export default defineLink(
+ {
+ linkable: ProductModule.linkable.product,
+ isList: true,
+ },
+ BrandModule.linkable.brand
+)
+```
+
+
+
+
+
+```ts
+import { model } from "@medusajs/framework/utils"
+
+export const Brand = model.define("brand", {
+ id: model.id().primaryKey(),
+ name: model.text(),
+})
+```
+
+
+
+
+
+```ts
+import { MedusaService } from "@medusajs/framework/utils"
+import { Brand } from "./models/brand"
+
+class BrandModuleService extends MedusaService({
+ Brand,
+}) {
+
+}
+
+export default BrandModuleService
+```
+
+
+
+
+
+```ts
+import { Module } from "@medusajs/framework/utils"
+import BrandModuleService from "./service"
+
+export const BRAND_MODULE = "brand"
+
+export default Module(BRAND_MODULE, {
+ service: BrandModuleService,
+})
+```
+
+
+
+
+Then, you can [hook into existing workflows](../workflows/workflow-hooks/page.mdx) to perform custom actions as part of existing features and flows. For example, you can create a brand when a product is created.
+
+export const hookHighlights = [
+ ["8", "productsCreated", "Perform a custom action within the product creation flow."],
+ ["9", "additional_data", "Custom data passed in the HTTP request body."]
+]
+
+```ts title="Workflow Hook Example" highlights={hookHighlights}
+import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
+import { StepResponse } from "@medusajs/framework/workflows-sdk"
+import { Modules } from "@medusajs/framework/utils"
+import { LinkDefinition } from "@medusajs/framework/types"
+import { BRAND_MODULE } from "../../modules/brand"
+import BrandModuleService from "../../modules/brand/service"
+
+createProductsWorkflow.hooks.productsCreated(
+ (async ({ products, additional_data }, { container }) => {
+ if (!additional_data?.brand_id) {
+ return new StepResponse([], [])
+ }
+
+ const brandModuleService: BrandModuleService = container.resolve(
+ BRAND_MODULE
+ )
+
+ const brand = await brandModuleService.createBrands({
+ name: additional_data.brand_name,
+ })
+ })
+)
+```
+
+You can also build custom workflows using your custom module and Medusa's modules, and use [existing workflows and steps](!resources!/medusa-workflows-reference) within your custom workflows.
+
+### Examples
+
+The following tutorials are step-by-step guides that show you how to extend existing features using the Medusa Framework.
+
+
+
+### Start Learning
+
+To learn more about the different concepts useful for extending features, check out the following chapters:
+
+
+
+---
+
+## Integrate Third-Party Services
+
+The Medusa Framework provides the tools and infrastructure to build a middleware solution for your commerce ecosystem. You can integrate third-party services, perform operations across systems, and query data from multiple sources.
+
+### Orchestrate Operations Across Systems
+
+The Medusa Framework solves one of the biggest hurdles for ecommerce platforms: orchestrating operations across systems. Medusa has a built-in durable execution engine to help complete tasks that span multiple systems.
+
+You can integrate a third-party service in a [module](../modules/page.mdx). This module provides an interface to perform operations with the third-party service.
+
+
+
+
+export const erpServiceHighlights = [
+ ["5", "ErpModuleService", "Create a service that connects to the ERP system."],
+]
+
+```ts highlights={erpServiceHighlights}
+type Options = {
+ apiKey: string
+}
+
+export default class ErpModuleService {
+ private options: Options
+ private client
+
+ constructor({}, options: Options) {
+ this.options = options
+ // TODO initialize client that connects to ERP
+ }
+
+ async getProducts() {
+ // assuming client has a method to fetch products
+ return this.client.getProducts()
+ }
+
+ // TODO add more methods
+}
+```
+
+
+
+
+
+```ts
+import { Module } from "@medusajs/framework/utils"
+import ErpModuleService from "./service"
+
+export const ERP_MODULE = "erp"
+
+export default Module(ERP_MODULE, {
+ service: ErpModuleService,
+})
+```
+
+
+
+
+Then, you can build [workflows](../workflows/page.mdx) that perform operations across systems. In the workflow, you can use your module to interact with the integrated third-party service.
+
+For example, you can create a workflow that syncs products from your ERP system to your Medusa application.
+
+
+
+
+
+export const erpWorkflowHighlights = [
+ ["11", "getProductsFromErpStep", "Get products from the ERP system."],
+ ["13", "transform", "Prepare the products to be created in Medusa."],
+ ["32", "createProductsWorkflow", "Create the ERP products in Medusa."],
+]
+
+```ts highlights={erpWorkflowHighlights}
+import {
+ createWorkflow,
+ WorkflowResponse,
+ transform,
+} from "@medusajs/framework/workflows-sdk"
+import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
+
+export const syncFromErpWorkflow = createWorkflow(
+ "sync-from-erp",
+ () => {
+ const erpProducts = getProductsFromErpStep()
+
+ const productsToCreate = transform({
+ erpProducts,
+ }, (data) => {
+ // TODO prepare ERP products to be created in Medusa
+ return data.erpProducts.map((erpProduct) => {
+ return {
+ title: erpProduct.title,
+ external_id: erpProduct.id,
+ variants: erpProduct.variants.map((variant) => ({
+ title: variant.title,
+ metadata: {
+ external_id: variant.id,
+ },
+ })),
+ // other data...
+ }
+ })
+ })
+
+ createProductsWorkflow.runAsStep({
+ input: {
+ products: productsToCreate,
+ },
+ })
+
+ return new WorkflowResponse({
+ erpProducts,
+ })
+ }
+)
+```
+
+
+
+
+```ts
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { ERP_MODULE } from "../../modules/erp"
+import { ErpModuleService } from "../../modules/erp/service"
+
+const getProductsFromErpStep = createStep(
+ "get-products-from-erp",
+ async (_, { container }) => {
+ const erpModuleService: ErpModuleService = container.resolve(
+ ERP_MODULE
+ )
+
+ const products = await erpModuleService.getProducts()
+
+ return new StepResponse(products)
+ }
+)
+```
+
+
+
+
+By using a workflow to manage operations across systems, you benefit from features like [rollback mechanism](../workflows/compensation-function/page.mdx), [background long-running execution](../workflows/long-running-workflow/page.mdx), [retry configuration](../workflows/retry-failed-steps/page.mdx), and more. This is essential for building a middleware solution that performs operations across systems, as you don't have to worry about data inconsistencies or failures.
+
+You can then execute this workflow at a specific interval using [scheduled jobs](../scheduled-jobs/page.mdx) or when an event occurs using [events and subscribers](../events-and-subscribers/page.mdx). You can also expose its features to client applications using an [API route](../api-routes/page.mdx).
+
+
+
+
+export const syncProductsJobHighlights = [
+ ["6", "syncProductsJob", "Sync products once a day."],
+]
+
+```ts highlights={syncProductsJobHighlights}
+import {
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { syncFromErpWorkflow } from "../workflows/sync-from-erp"
+
+export default async function syncProductsJob(container: MedusaContainer) {
+ await syncFromErpWorkflow(container).run({})
+}
+
+export const config = {
+ name: "daily-product-sync",
+ schedule: "0 0 * * *", // Every day at midnight
+}
+```
+
+
+
+
+
+export const productsCreatedHandlerHighlights = [
+ ["4", "productsCreatedHandler", "Sync products when they are created."],
+]
+
+```ts highlights={productsCreatedHandlerHighlights}
+import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
+import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"
+
+export default async function productsCreatedHandler({
+ event: { data },
+ container,
+}: SubscriberArgs<{ id: string }[]>) {
+ await syncFromErpWorkflow(container).run({})
+}
+
+export const config: SubscriberConfig = {
+ event: `product.created`,
+}
+```
+
+
+
+
+
+export const apiRouteHighlights = [
+ ["7", "POST", "Expose a REST API route to sync products."],
+]
+
+```ts highlights={apiRouteHighlights}
+import type {
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { syncFromErpWorkflow } from "../../../workflows/sync-from-erp"
+
+export const POST = async (
+ req: MedusaRequest,
+ res: MedusaResponse
+) => {
+ const { result } = await syncFromErpWorkflow(req.scope).run({})
+
+ return res.status(200).json(result)
+}
+```
+
+
+
+
+#### Examples
+
+The following tutorials are step-by-step guides that show you how to orchestrate operations across third-party services using the Medusa Framework.
+
+
+
+#### Start Learning
+
+To learn more about the different concepts useful for integrating third-party services, check out the following chapters:
+
+
+
+### Query Data Across Systems
+
+Another essential feature for integrating third-party services is querying data across those systems efficiently.
+
+The Framework allows you to build links not only between Medusa data models, but also virtual data models using [read-only module links](../module-links/read-only/page.mdx). You can build a [module](../modules/page.mdx) that provides the logic to query data from a third-party service, then create a read-only link between an existing data model and a virtual one from the third-party service.
+
+
+
+
+export const readOnlyLinkHighlights = [
+ ["5", "defineLink", "Define a read-only link between products and brands from a third-party service."],
+]
+
+```ts highlights={readOnlyLinkHighlights}
+import BrandModule from "../modules/brand"
+import ProductModule from "@medusajs/medusa/product"
+import { defineLink } from "@medusajs/framework/utils"
+
+export default defineLink(
+ {
+ linkable: ProductModule.linkable.product,
+ field: "id",
+ },
+ {
+ ...BrandModule.linkable.brand.id,
+ primaryKey: "product_id",
+ },
+ {
+ readOnly: true,
+ }
+)
+```
+
+
+
+
+
+export const brandModuleService = [
+ ["12", "list", "Provide a method in the service to retrieve\nthe data from the third-party service."],
+]
+
+```ts highlights={brandModuleService}
+type BrandModuleOptions = {
+ apiKey: string
+}
+
+export default class BrandModuleService {
+ private client
+
+ constructor({}, options: BrandModuleOptions) {
+ this.client = new Client(options)
+ }
+
+ async list(
+ filter: {
+ id: string | string[]
+ }
+ ) {
+ return this.client.getBrands(filter)
+ /**
+ * Example of returned data:
+ *
+ * [
+ * {
+ * "id": "brand_123",
+ * "name": "Brand 123",
+ * "product_id": "prod_321"
+ * },
+ * {
+ * "id": "post_456",
+ * "name": "Brand 456",
+ * "product_id": "prod_654"
+ * }
+ * ]
+ */
+ }
+}
+```
+
+
+
+
+
+```ts
+import { Module } from "@medusajs/framework/utils"
+import BrandModuleService from "./service"
+
+export const BRAND_MODULE = "brand"
+
+export default Module(BRAND_MODULE, {
+ service: BrandModuleService,
+})
+```
+
+
+
+
+Then, you can use [Query](../module-links/query/page.mdx) to retrieve a product and its brand from the third-party service in a single query.
+
+export const queryHighlights = [
+ ["1", "graph", "Query a product and its brand from the\nthird-party service in a single query."],
+]
+
+```ts title="Query Example" highlights={queryHighlights}
+const { result } = await query.graph({
+ entity: "product",
+ fields: ["id", "brand.*"],
+ filters: {
+ id: "prod_123",
+ },
+})
+
+// result = [{
+// id: "prod_123",
+// brand: {
+// id: "brand_123",
+// name: "Brand 123",
+// product_id: "prod_123"
+// }
+// ...
+// }]
+```
+
+Query simplifies the process of retrieving data across systems, as you can retrieve data from multiple sources in a single query.
+
+#### Examples
+
+The following tutorials are step-by-step guides that show you how to query data across systems using the Medusa Framework.
+
+
+
+#### Start Learning
+
+To learn more about the different concepts useful for querying data across systems, check out the following chapters:
+
+
+
+---
+
+## Automate Tasks
+
+The Medusa Framework provides the tools to automate tasks in your Medusa application. Automation is useful when you want to perform a task periodically, such as syncing data, or when an event occurs, such as sending a confirmation email when an order is placed.
+
+To build the task to be automated, you first create a [workflow](../workflows/page.mdx) that contains the task's logic, such as syncing data or sending an email.
+
+
+
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { CreateNotificationDTO } from "@medusajs/framework/types"
+
+export const sendNotificationStep = createStep(
+ "send-notification",
+ async (data: CreateNotificationDTO[], { container }) => {
+ const notificationModuleService = container.resolve(
+ Modules.NOTIFICATION
+ )
+ const notification = await notificationModuleService.createNotifications(
+ data
+ )
+ return new StepResponse(notification)
+ }
+)
+```
+
+
+
+
+```ts
+import {
+ createWorkflow,
+ WorkflowResponse,
+} from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { sendNotificationStep } from "./steps/send-notification"
+
+type WorkflowInput = {
+ id: string
+}
+
+export const sendOrderConfirmationWorkflow = createWorkflow(
+ "send-order-confirmation",
+ ({ id }: WorkflowInput) => {
+ // @ts-ignore
+ const { data: orders } = useQueryGraphStep({
+ entity: "order",
+ fields: [
+ "id",
+ "email",
+ "currency_code",
+ "total",
+ "items.*",
+ ],
+ filters: {
+ id,
+ },
+ })
+
+ const notification = sendNotificationStep([{
+ to: orders[0].email,
+ channel: "email",
+ template: "order-placed",
+ data: {
+ order: orders[0],
+ },
+ }])
+
+ return new WorkflowResponse(notification)
+ }
+)
+```
+
+
+
+Then, you can execute this workflow when an event occurs using a [subscriber](../events-and-subscribers/page.mdx), or at a specific interval using a [scheduled job](../scheduled-jobs/page.mdx).
+
+
+
+
+export const orderPlacedHandlerHighlights = [
+ ["7", "orderPlacedHandler", "Send an order confirmation email when an order is placed."],
+]
+
+```ts highlights={orderPlacedHandlerHighlights}
+import type {
+ SubscriberArgs,
+ SubscriberConfig,
+} from "@medusajs/framework"
+import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"
+
+export default async function orderPlacedHandler({
+ event: { data },
+ container,
+}: SubscriberArgs<{ id: string }>) {
+ await sendOrderConfirmationWorkflow(container)
+ .run({
+ input: {
+ id: data.id,
+ },
+ })
+}
+
+export const config: SubscriberConfig = {
+ event: "order.placed",
+}
+```
+
+
+
+
+
+export const orderConfirmationJobHighlights = [
+ ["6", "orderConfirmationJob", "Send an order confirmation email once a day."],
+]
+
+```ts highlights={orderConfirmationJobHighlights}
+import type {
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"
+
+export default async function orderConfirmationJob(
+ container: MedusaContainer
+) {
+ await sendOrderConfirmationWorkflow(container).run({
+ input: {
+ id: "order_123",
+ }
+ })
+}
+export const config = {
+ name: "order-confirmation-job",
+ schedule: "0 0 * * *", // Every day at midnight
+}
+```
+
+
+
+
+### Examples
+
+The following guides are step-by-step guides that show you how to automate tasks using the Medusa Framework.
+
+
+
+### Start Learning
+
+To learn more about the different concepts useful for automating tasks, check out the following chapters:
+
+
+
+---
+
+## Re-Use Customizations Across Applications
+
+If you have custom features that you want to re-use across multiple Medusa applications, or you want to publish your customizations for the community to use, you can build a [plugin](../plugins/page.mdx).
+
+A plugin encapsulates your customizations in a single package. The customizations include [modules](../modules/page.mdx), [workflows](../workflows/page.mdx), [API routes](../api-routes/page.mdx), and more.
+
+
+
+You can then publish that plugin to NPM and install it in any Medusa application. This allows you to re-use your customizations efficiently across multiple projects, or share them with the community.
+
+### Examples
+
+The following tutorials are step-by-step guides that show you how to build plugins using the Medusa Framework.
+
+
+
+### Start Learning
+
+To learn more about the different concepts useful for building plugins, check out the following chapters:
+
+
diff --git a/www/apps/book/generated/edit-dates.mjs b/www/apps/book/generated/edit-dates.mjs
index 7c74293fba..71fac5bd21 100644
--- a/www/apps/book/generated/edit-dates.mjs
+++ b/www/apps/book/generated/edit-dates.mjs
@@ -118,5 +118,6 @@ export const generatedEditDates = {
"app/learn/configurations/ts-aliases/page.mdx": "2025-02-11T16:57:46.683Z",
"app/learn/production/worker-mode/page.mdx": "2025-03-11T15:21:50.906Z",
"app/learn/fundamentals/module-links/read-only/page.mdx": "2025-03-21T09:14:54.944Z",
- "app/learn/fundamentals/data-models/properties/page.mdx": "2025-03-18T07:57:17.826Z"
+ "app/learn/fundamentals/data-models/properties/page.mdx": "2025-03-18T07:57:17.826Z",
+ "app/learn/fundamentals/framework/page.mdx": "2025-04-16T14:39:59.724Z"
}
\ No newline at end of file
diff --git a/www/apps/book/generated/sidebar.mjs b/www/apps/book/generated/sidebar.mjs
index 025eb8888f..fe6d7ba254 100644
--- a/www/apps/book/generated/sidebar.mjs
+++ b/www/apps/book/generated/sidebar.mjs
@@ -233,6 +233,16 @@ export const generatedSidebars = [
"type": "category",
"title": "3. Framework",
"children": [
+ {
+ "loaded": true,
+ "isPathHref": true,
+ "type": "link",
+ "path": "/learn/fundamentals/framework",
+ "title": "Overview",
+ "children": [],
+ "chapterTitle": "3.1. Overview",
+ "number": "3.1."
+ },
{
"loaded": true,
"isPathHref": true,
@@ -240,8 +250,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/medusa-container",
"title": "Medusa Container",
"children": [],
- "chapterTitle": "3.1. Medusa Container",
- "number": "3.1."
+ "chapterTitle": "3.2. Medusa Container",
+ "number": "3.2."
},
{
"loaded": true,
@@ -257,8 +267,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/modules/modules-directory-structure",
"title": "Directory Structure",
"children": [],
- "chapterTitle": "3.2.1. Directory Structure",
- "number": "3.2.1."
+ "chapterTitle": "3.3.1. Directory Structure",
+ "number": "3.3.1."
},
{
"loaded": true,
@@ -267,8 +277,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/modules/loaders",
"title": "Loaders",
"children": [],
- "chapterTitle": "3.2.2. Loaders",
- "number": "3.2.2."
+ "chapterTitle": "3.3.2. Loaders",
+ "number": "3.3.2."
},
{
"loaded": true,
@@ -277,8 +287,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/modules/isolation",
"title": "Module Isolation",
"children": [],
- "chapterTitle": "3.2.3. Module Isolation",
- "number": "3.2.3."
+ "chapterTitle": "3.3.3. Module Isolation",
+ "number": "3.3.3."
},
{
"loaded": true,
@@ -287,8 +297,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/modules/container",
"title": "Module Container",
"children": [],
- "chapterTitle": "3.2.4. Module Container",
- "number": "3.2.4."
+ "chapterTitle": "3.3.4. Module Container",
+ "number": "3.3.4."
},
{
"loaded": true,
@@ -297,8 +307,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/modules/options",
"title": "Module Options",
"children": [],
- "chapterTitle": "3.2.5. Module Options",
- "number": "3.2.5."
+ "chapterTitle": "3.3.5. Module Options",
+ "number": "3.3.5."
},
{
"loaded": true,
@@ -307,8 +317,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/modules/service-factory",
"title": "Service Factory",
"children": [],
- "chapterTitle": "3.2.6. Service Factory",
- "number": "3.2.6."
+ "chapterTitle": "3.3.6. Service Factory",
+ "number": "3.3.6."
},
{
"loaded": true,
@@ -317,8 +327,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/modules/service-constraints",
"title": "Service Constraints",
"children": [],
- "chapterTitle": "3.2.7. Service Constraints",
- "number": "3.2.7."
+ "chapterTitle": "3.3.7. Service Constraints",
+ "number": "3.3.7."
},
{
"loaded": true,
@@ -327,8 +337,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/modules/db-operations",
"title": "Database Operations",
"children": [],
- "chapterTitle": "3.2.8. Database Operations",
- "number": "3.2.8."
+ "chapterTitle": "3.3.8. Database Operations",
+ "number": "3.3.8."
},
{
"loaded": true,
@@ -337,8 +347,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/modules/multiple-services",
"title": "Multiple Services",
"children": [],
- "chapterTitle": "3.2.9. Multiple Services",
- "number": "3.2.9."
+ "chapterTitle": "3.3.9. Multiple Services",
+ "number": "3.3.9."
},
{
"loaded": true,
@@ -347,8 +357,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/modules/commerce-modules",
"title": "Commerce Modules",
"children": [],
- "chapterTitle": "3.2.10. Commerce Modules",
- "number": "3.2.10."
+ "chapterTitle": "3.3.10. Commerce Modules",
+ "number": "3.3.10."
},
{
"loaded": true,
@@ -357,12 +367,12 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/modules/architectural-modules",
"title": "Architectural Modules",
"children": [],
- "chapterTitle": "3.2.11. Architectural Modules",
- "number": "3.2.11."
+ "chapterTitle": "3.3.11. Architectural Modules",
+ "number": "3.3.11."
}
],
- "chapterTitle": "3.2. Modules",
- "number": "3.2."
+ "chapterTitle": "3.3. Modules",
+ "number": "3.3."
},
{
"loaded": true,
@@ -378,8 +388,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/module-links/directions",
"title": "Module Link Direction",
"children": [],
- "chapterTitle": "3.3.1. Module Link Direction",
- "number": "3.3.1."
+ "chapterTitle": "3.4.1. Module Link Direction",
+ "number": "3.4.1."
},
{
"loaded": true,
@@ -388,8 +398,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/module-links/link",
"title": "Link",
"children": [],
- "chapterTitle": "3.3.2. Link",
- "number": "3.3.2."
+ "chapterTitle": "3.4.2. Link",
+ "number": "3.4.2."
},
{
"loaded": true,
@@ -398,8 +408,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/module-links/query",
"title": "Query",
"children": [],
- "chapterTitle": "3.3.3. Query",
- "number": "3.3.3."
+ "chapterTitle": "3.4.3. Query",
+ "number": "3.4.3."
},
{
"loaded": true,
@@ -408,8 +418,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/module-links/custom-columns",
"title": "Add Custom Columns",
"children": [],
- "chapterTitle": "3.3.4. Add Custom Columns",
- "number": "3.3.4."
+ "chapterTitle": "3.4.4. Add Custom Columns",
+ "number": "3.4.4."
},
{
"loaded": true,
@@ -418,8 +428,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/module-links/read-only",
"title": "Read-Only Links",
"children": [],
- "chapterTitle": "3.3.5. Read-Only Links",
- "number": "3.3.5."
+ "chapterTitle": "3.4.5. Read-Only Links",
+ "number": "3.4.5."
},
{
"loaded": true,
@@ -428,12 +438,12 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/module-links/query-context",
"title": "Query Context",
"children": [],
- "chapterTitle": "3.3.6. Query Context",
- "number": "3.3.6."
+ "chapterTitle": "3.4.6. Query Context",
+ "number": "3.4.6."
}
],
- "chapterTitle": "3.3. Module Links",
- "number": "3.3."
+ "chapterTitle": "3.4. Module Links",
+ "number": "3.4."
},
{
"loaded": true,
@@ -449,8 +459,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/data-models/infer-type",
"title": "Infer Type",
"children": [],
- "chapterTitle": "3.4.1. Infer Type",
- "number": "3.4.1."
+ "chapterTitle": "3.5.1. Infer Type",
+ "number": "3.5.1."
},
{
"loaded": true,
@@ -459,8 +469,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/data-models/properties",
"title": "Properties",
"children": [],
- "chapterTitle": "3.4.2. Properties",
- "number": "3.4.2."
+ "chapterTitle": "3.5.2. Properties",
+ "number": "3.5.2."
},
{
"loaded": true,
@@ -469,8 +479,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/data-models/relationships",
"title": "Relationships",
"children": [],
- "chapterTitle": "3.4.3. Relationships",
- "number": "3.4.3."
+ "chapterTitle": "3.5.3. Relationships",
+ "number": "3.5.3."
},
{
"loaded": true,
@@ -479,8 +489,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/data-models/manage-relationships",
"title": "Manage Relationships",
"children": [],
- "chapterTitle": "3.4.4. Manage Relationships",
- "number": "3.4.4."
+ "chapterTitle": "3.5.4. Manage Relationships",
+ "number": "3.5.4."
},
{
"loaded": true,
@@ -489,8 +499,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/data-models/index",
"title": "Define Index",
"children": [],
- "chapterTitle": "3.4.5. Define Index",
- "number": "3.4.5."
+ "chapterTitle": "3.5.5. Define Index",
+ "number": "3.5.5."
},
{
"loaded": true,
@@ -499,8 +509,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/data-models/check-constraints",
"title": "Check Constraints",
"children": [],
- "chapterTitle": "3.4.6. Check Constraints",
- "number": "3.4.6."
+ "chapterTitle": "3.5.6. Check Constraints",
+ "number": "3.5.6."
},
{
"loaded": true,
@@ -509,12 +519,12 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/data-models/write-migration",
"title": "Migrations",
"children": [],
- "chapterTitle": "3.4.7. Migrations",
- "number": "3.4.7."
+ "chapterTitle": "3.5.7. Migrations",
+ "number": "3.5.7."
}
],
- "chapterTitle": "3.4. Data Models",
- "number": "3.4."
+ "chapterTitle": "3.5. Data Models",
+ "number": "3.5."
},
{
"loaded": true,
@@ -530,8 +540,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/api-routes/http-methods",
"title": "HTTP Methods",
"children": [],
- "chapterTitle": "3.5.1. HTTP Methods",
- "number": "3.5.1."
+ "chapterTitle": "3.6.1. HTTP Methods",
+ "number": "3.6.1."
},
{
"loaded": true,
@@ -540,8 +550,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/api-routes/parameters",
"title": "Parameters",
"children": [],
- "chapterTitle": "3.5.2. Parameters",
- "number": "3.5.2."
+ "chapterTitle": "3.6.2. Parameters",
+ "number": "3.6.2."
},
{
"loaded": true,
@@ -550,8 +560,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/api-routes/responses",
"title": "Response",
"children": [],
- "chapterTitle": "3.5.3. Response",
- "number": "3.5.3."
+ "chapterTitle": "3.6.3. Response",
+ "number": "3.6.3."
},
{
"loaded": true,
@@ -560,8 +570,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/api-routes/middlewares",
"title": "Middlewares",
"children": [],
- "chapterTitle": "3.5.4. Middlewares",
- "number": "3.5.4."
+ "chapterTitle": "3.6.4. Middlewares",
+ "number": "3.6.4."
},
{
"loaded": true,
@@ -570,8 +580,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/api-routes/parse-body",
"title": "Body Parsing",
"children": [],
- "chapterTitle": "3.5.5. Body Parsing",
- "number": "3.5.5."
+ "chapterTitle": "3.6.5. Body Parsing",
+ "number": "3.6.5."
},
{
"loaded": true,
@@ -580,8 +590,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/api-routes/validation",
"title": "Validation",
"children": [],
- "chapterTitle": "3.5.6. Validation",
- "number": "3.5.6."
+ "chapterTitle": "3.6.6. Validation",
+ "number": "3.6.6."
},
{
"loaded": true,
@@ -590,8 +600,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/api-routes/protected-routes",
"title": "Protected Routes",
"children": [],
- "chapterTitle": "3.5.7. Protected Routes",
- "number": "3.5.7."
+ "chapterTitle": "3.6.7. Protected Routes",
+ "number": "3.6.7."
},
{
"loaded": true,
@@ -600,8 +610,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/api-routes/errors",
"title": "Errors",
"children": [],
- "chapterTitle": "3.5.8. Errors",
- "number": "3.5.8."
+ "chapterTitle": "3.6.8. Errors",
+ "number": "3.6.8."
},
{
"loaded": true,
@@ -610,8 +620,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/api-routes/cors",
"title": "Handling CORS",
"children": [],
- "chapterTitle": "3.5.9. Handling CORS",
- "number": "3.5.9."
+ "chapterTitle": "3.6.9. Handling CORS",
+ "number": "3.6.9."
},
{
"loaded": true,
@@ -620,12 +630,12 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/api-routes/additional-data",
"title": "Additional Data",
"children": [],
- "chapterTitle": "3.5.10. Additional Data",
- "number": "3.5.10."
+ "chapterTitle": "3.6.10. Additional Data",
+ "number": "3.6.10."
}
],
- "chapterTitle": "3.5. API Routes",
- "number": "3.5."
+ "chapterTitle": "3.6. API Routes",
+ "number": "3.6."
},
{
"loaded": true,
@@ -641,8 +651,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/constructor-constraints",
"title": "Constructor Constraints",
"children": [],
- "chapterTitle": "3.6.1. Constructor Constraints",
- "number": "3.6.1."
+ "chapterTitle": "3.7.1. Constructor Constraints",
+ "number": "3.7.1."
},
{
"loaded": true,
@@ -651,8 +661,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/variable-manipulation",
"title": "Transform Variables",
"children": [],
- "chapterTitle": "3.6.2. Transform Variables",
- "number": "3.6.2."
+ "chapterTitle": "3.7.2. Transform Variables",
+ "number": "3.7.2."
},
{
"loaded": true,
@@ -661,8 +671,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/conditions",
"title": "When-Then Conditions",
"children": [],
- "chapterTitle": "3.6.3. When-Then Conditions",
- "number": "3.6.3."
+ "chapterTitle": "3.7.3. When-Then Conditions",
+ "number": "3.7.3."
},
{
"loaded": true,
@@ -671,8 +681,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/compensation-function",
"title": "Compensation Function",
"children": [],
- "chapterTitle": "3.6.4. Compensation Function",
- "number": "3.6.4."
+ "chapterTitle": "3.7.4. Compensation Function",
+ "number": "3.7.4."
},
{
"loaded": true,
@@ -681,8 +691,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/workflow-hooks",
"title": "Workflow Hooks",
"children": [],
- "chapterTitle": "3.6.5. Workflow Hooks",
- "number": "3.6.5."
+ "chapterTitle": "3.7.5. Workflow Hooks",
+ "number": "3.7.5."
},
{
"loaded": true,
@@ -691,8 +701,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/add-workflow-hook",
"title": "Expose a Hook",
"children": [],
- "chapterTitle": "3.6.6. Expose a Hook",
- "number": "3.6.6."
+ "chapterTitle": "3.7.6. Expose a Hook",
+ "number": "3.7.6."
},
{
"loaded": true,
@@ -701,8 +711,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/access-workflow-errors",
"title": "Access Workflow Errors",
"children": [],
- "chapterTitle": "3.6.7. Access Workflow Errors",
- "number": "3.6.7."
+ "chapterTitle": "3.7.7. Access Workflow Errors",
+ "number": "3.7.7."
},
{
"loaded": true,
@@ -711,8 +721,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/retry-failed-steps",
"title": "Retry Failed Steps",
"children": [],
- "chapterTitle": "3.6.8. Retry Failed Steps",
- "number": "3.6.8."
+ "chapterTitle": "3.7.8. Retry Failed Steps",
+ "number": "3.7.8."
},
{
"loaded": true,
@@ -721,8 +731,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/parallel-steps",
"title": "Run Steps in Parallel",
"children": [],
- "chapterTitle": "3.6.9. Run Steps in Parallel",
- "number": "3.6.9."
+ "chapterTitle": "3.7.9. Run Steps in Parallel",
+ "number": "3.7.9."
},
{
"loaded": true,
@@ -731,8 +741,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/workflow-timeout",
"title": "Workflow Timeout",
"children": [],
- "chapterTitle": "3.6.10. Workflow Timeout",
- "number": "3.6.10."
+ "chapterTitle": "3.7.10. Workflow Timeout",
+ "number": "3.7.10."
},
{
"loaded": true,
@@ -741,8 +751,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/store-executions",
"title": "Store Workflow Executions",
"children": [],
- "chapterTitle": "3.6.11. Store Workflow Executions",
- "number": "3.6.11."
+ "chapterTitle": "3.7.11. Store Workflow Executions",
+ "number": "3.7.11."
},
{
"loaded": true,
@@ -751,8 +761,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/long-running-workflow",
"title": "Long-Running Workflow",
"children": [],
- "chapterTitle": "3.6.12. Long-Running Workflow",
- "number": "3.6.12."
+ "chapterTitle": "3.7.12. Long-Running Workflow",
+ "number": "3.7.12."
},
{
"loaded": true,
@@ -761,8 +771,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/execute-another-workflow",
"title": "Execute Another Workflow",
"children": [],
- "chapterTitle": "3.6.13. Execute Another Workflow",
- "number": "3.6.13."
+ "chapterTitle": "3.7.13. Execute Another Workflow",
+ "number": "3.7.13."
},
{
"loaded": true,
@@ -771,12 +781,12 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/workflows/multiple-step-usage",
"title": "Multiple Step Usage",
"children": [],
- "chapterTitle": "3.6.14. Multiple Step Usage",
- "number": "3.6.14."
+ "chapterTitle": "3.7.14. Multiple Step Usage",
+ "number": "3.7.14."
}
],
- "chapterTitle": "3.6. Workflows",
- "number": "3.6."
+ "chapterTitle": "3.7. Workflows",
+ "number": "3.7."
},
{
"loaded": true,
@@ -792,8 +802,8 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/events-and-subscribers/data-payload",
"title": "Events Data Payload",
"children": [],
- "chapterTitle": "3.7.1. Events Data Payload",
- "number": "3.7.1."
+ "chapterTitle": "3.8.1. Events Data Payload",
+ "number": "3.8.1."
},
{
"loaded": true,
@@ -802,12 +812,12 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/events-and-subscribers/emit-event",
"title": "Emit Event",
"children": [],
- "chapterTitle": "3.7.2. Emit Event",
- "number": "3.7.2."
+ "chapterTitle": "3.8.2. Emit Event",
+ "number": "3.8.2."
}
],
- "chapterTitle": "3.7. Events and Subscribers",
- "number": "3.7."
+ "chapterTitle": "3.8. Events and Subscribers",
+ "number": "3.8."
},
{
"loaded": true,
@@ -823,12 +833,12 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/scheduled-jobs/execution-number",
"title": "Execution Number",
"children": [],
- "chapterTitle": "3.8.1. Execution Number",
- "number": "3.8.1."
+ "chapterTitle": "3.9.1. Execution Number",
+ "number": "3.9.1."
}
],
- "chapterTitle": "3.8. Scheduled Jobs",
- "number": "3.8."
+ "chapterTitle": "3.9. Scheduled Jobs",
+ "number": "3.9."
},
{
"loaded": true,
@@ -844,12 +854,12 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/plugins/create",
"title": "Create Plugin",
"children": [],
- "chapterTitle": "3.9.1. Create Plugin",
- "number": "3.9.1."
+ "chapterTitle": "3.10.1. Create Plugin",
+ "number": "3.10.1."
}
],
- "chapterTitle": "3.9. Plugins",
- "number": "3.9."
+ "chapterTitle": "3.10. Plugins",
+ "number": "3.10."
},
{
"loaded": true,
@@ -865,12 +875,12 @@ export const generatedSidebars = [
"path": "/learn/fundamentals/custom-cli-scripts/seed-data",
"title": "Seed Data",
"children": [],
- "chapterTitle": "3.10.1. Seed Data",
- "number": "3.10.1."
+ "chapterTitle": "3.11.1. Seed Data",
+ "number": "3.11.1."
}
],
- "chapterTitle": "3.10. Custom CLI Scripts",
- "number": "3.10."
+ "chapterTitle": "3.11. Custom CLI Scripts",
+ "number": "3.11."
}
],
"chapterTitle": "3. Framework",
diff --git a/www/apps/book/public/llms-full.txt b/www/apps/book/public/llms-full.txt
index e3a2b341e1..4366dd7482 100644
--- a/www/apps/book/public/llms-full.txt
+++ b/www/apps/book/public/llms-full.txt
@@ -330,6 +330,28 @@ Refer to [this documentation](https://docs.medusajs.com/learn/update/index.html.
In the next chapters, you'll learn about the architecture of your Medusa application, then learn how to customize your application to build custom features.
+# Storefront Development
+
+The Medusa application is made up of a Node.js server and an admin dashboard. Storefronts are installed, built, and hosted separately from the Medusa application, giving you the flexibility to choose the frontend tech stack that you and your team are proficient in, and implement unique design systems and user experience.
+
+You can build your storefront from scratch with your preferred tech stack, or start with our Next.js Starter storefront. The Next.js Starter storefront provides rich commerce features and a sleek design. Developers and businesses can use it as-is or build on top of it to tailor it for the business's unique use case, design, and customer experience.
+
+- [Install Next.js Starter Storefront](https://docs.medusajs.com/resources/nextjs-starter/index.html.md)
+- [Build Custom Storefront](https://docs.medusajs.com/resources/storefront-development/index.html.md)
+
+***
+
+## Passing a Publishable API Key in Storefront Requests
+
+When sending a request to an API route starting with `/store`, you must include a publishable API key in the header of your request.
+
+A publishable API key sets the scope of your request to one or more sales channels.
+
+Then, when you retrieve products, only products of those sales channels are retrieved. This also ensures you retrieve correct inventory data, and associate created orders with the scoped sales channel.
+
+Learn more about passing the publishable API key in [this storefront development guide](https://docs.medusajs.com/resources/storefront-development/publishable-api-keys/index.html.md).
+
+
# Updating Medusa
In this chapter, you'll learn about updating your Medusa application and packages.
@@ -436,28 +458,6 @@ npm install
```
-# Storefront Development
-
-The Medusa application is made up of a Node.js server and an admin dashboard. Storefronts are installed, built, and hosted separately from the Medusa application, giving you the flexibility to choose the frontend tech stack that you and your team are proficient in, and implement unique design systems and user experience.
-
-You can build your storefront from scratch with your preferred tech stack, or start with our Next.js Starter storefront. The Next.js Starter storefront provides rich commerce features and a sleek design. Developers and businesses can use it as-is or build on top of it to tailor it for the business's unique use case, design, and customer experience.
-
-- [Install Next.js Starter Storefront](https://docs.medusajs.com/resources/nextjs-starter/index.html.md)
-- [Build Custom Storefront](https://docs.medusajs.com/resources/storefront-development/index.html.md)
-
-***
-
-## Passing a Publishable API Key in Storefront Requests
-
-When sending a request to an API route starting with `/store`, you must include a publishable API key in the header of your request.
-
-A publishable API key sets the scope of your request to one or more sales channels.
-
-Then, when you retrieve products, only products of those sales channels are retrieved. This also ensures you retrieve correct inventory data, and associate created orders with the scoped sales channel.
-
-Learn more about passing the publishable API key in [this storefront development guide](https://docs.medusajs.com/resources/storefront-development/publishable-api-keys/index.html.md).
-
-
# Medusa Application Configuration
In this chapter, you'll learn available configurations in the Medusa application. You can change the application's configurations to customize the behavior of the application, its integrated modules and plugins, and more.
@@ -1405,6 +1405,208 @@ import { BrandModuleService } from "@/modules/brand/service"
```
+# Build Custom Features
+
+In the upcoming chapters, you'll follow step-by-step guides to build custom features in Medusa. These guides gradually introduce Medusa's concepts to help you understand what they are and how to use them.
+
+By following these guides, you'll add brands to the Medusa application that you can associate with products.
+
+To build a custom feature in Medusa, you need three main tools:
+
+- [Module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md): a package with commerce logic for a single domain. It defines new tables to add to the database, and a class of methods to manage these tables.
+- [Workflow](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md): a tool to perform an operation comprising multiple steps with built-in rollback and retry mechanisms.
+- [API route](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md): a REST endpoint that exposes commerce features to clients, such as the admin dashboard or a storefront. The API route executes a workflow that implements the commerce feature using modules.
+
+
+
+***
+
+## Next Chapters: Brand Module Example
+
+The next chapters will guide you to:
+
+1. Build a Brand Module that creates a `Brand` data model and provides data-management features.
+2. Add a workflow to create a brand.
+3. Expose an API route that allows admin users to create a brand using the workflow.
+
+
+# Extend Core Commerce Features
+
+In the upcoming chapters, you'll learn about the concepts and tools to extend Medusa's core commerce features.
+
+In other commerce platforms, you extend core features and models through hacky workarounds that can introduce unexpected issues and side effects across the platform. It also makes your application difficult to maintain and upgrade in the long run.
+
+Medusa's framework and orchestration tools mitigate these issues while supporting all your customization needs:
+
+- [Module Links](https://docs.medusajs.com/learn/fundamentals/module-links/index.html.md): Link data models of different modules without building direct dependencies, ensuring that the Medusa application integrates your modules without side effects.
+- [Workflow Hooks](https://docs.medusajs.com/learn/fundamentals/workflows/workflow-hooks/index.html.md): inject custom functionalities into a workflow at predefined points, called hooks. This allows you to perform custom actions as a part of a core workflow without hacky workarounds.
+- [Additional Data in API Routes](https://docs.medusajs.com/learn/fundamentals/api-routes/additional-data/index.html.md): Configure core API routes to accept request parameters relevant to your customizations. These parameters are passed to the underlying workflow's hooks, where you can manage your custom data as part of an existing flow.
+
+***
+
+## Next Chapters: Link Brands to Products Example
+
+The next chapters explain how to use the tools mentioned above with step-by-step guides. You'll continue with the [brands example from the previous chapters](https://docs.medusajs.com/learn/customization/custom-features/index.html.md) to:
+
+- Link brands from the custom [Brand Module](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md) to products from Medusa's [Product Module](https://docs.medusajs.com/resources/commerce-modules/product/index.html.md).
+- Extend the core product-creation workflow and the API route that uses it to allow setting the brand of a newly created product.
+- Retrieve a product's associated brand's details.
+
+
+# Customize Medusa Admin Dashboard
+
+In the previous chapters, you've customized your Medusa application to [add brands](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md), [expose an API route to create brands](https://docs.medusajs.com/learn/customization/custom-features/api-route/index.html.md), and [linked brands to products](https://docs.medusajs.com/learn/customization/extend-features/define-link/index.html.md).
+
+After customizing and extending your application with new features, you may need to provide an interface for admin users to utilize these features. The Medusa Admin dashboard is extendable, allowing you to:
+
+- Insert components, called [widgets](https://docs.medusajs.com/learn/fundamentals/admin/widgets/index.html.md), on existing pages.
+- Add new pages, called [UI Routes](https://docs.medusajs.com/learn/fundamentals/admin/ui-routes/index.html.md).
+
+From these customizations, you can send requests to custom API routes, allowing admin users to manage custom resources on the dashboard
+
+***
+
+## Next Chapters: View Brands in Dashboard
+
+In the next chapters, you'll continue with the brands example to:
+
+- Add a new section to the product details page that shows the product's brand.
+- Add a new page in the dashboard that shows all brands in the store.
+
+
+# Integrate Third-Party Systems
+
+Commerce applications often connect to third-party systems that provide additional or specialized features. For example, you may integrate a Content-Management System (CMS) for rich content features, a payment provider to process credit-card payments, and a notification service to send emails.
+
+Medusa's framework facilitates integrating these systems and orchestrating operations across them, saving you the effort of managing them yourself. You won't find those capabilities in other commerce platforms that in these scenarios become a bottleneck to building customizations and iterating quickly.
+
+In Medusa, you integrate a third-party system by:
+
+1. Creating a module whose service provides the methods to connect to and perform operations in the third-party system.
+2. Building workflows that complete tasks spanning across systems. You use the module that integrates a third-party system in the workflow's steps.
+3. Executing the workflows you built in an [API route](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md), at a scheduled time, or when an event is emitted.
+
+***
+
+## Next Chapters: Sync Brands Example
+
+In the previous chapters, you've [added brands](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md) to your Medusa application. In the next chapters, you will:
+
+1. Integrate a dummy third-party CMS in the Brand Module.
+2. Sync brands to the CMS when a brand is created.
+3. Sync brands from the CMS at a daily schedule.
+
+
+# Customizations Next Steps: Learn the Fundamentals
+
+The previous guides introduced Medusa's different concepts and how you can use them to customize Medusa for a realistic use case, You added brands to your application, linked them to products, customized the admin dashboard, and integrated a third-party CMS.
+
+The next chapters will cover each of these concepts in depth, with the different ways you can use them, their options or configurations, and more advanced features that weren't covered in the previous guides. While you can start building with Medusa, it's highly recommended to follow the next chapters for a better understanding of Medusa's fundamentals.
+
+## Useful Guides
+
+The following guides and references are useful for your development journey:
+
+3. [Commerce Modules](https://docs.medusajs.com/resources/commerce-modules/index.html.md): Browse the list of commerce modules in Medusa and their references to learn how to use them.
+4. [Service Factory Reference](https://docs.medusajs.com/resources/service-factory-reference/index.html.md): Learn about the methods generated by `MedusaService` with examples.
+5. [Workflows Reference](https://docs.medusajs.com/resources/medusa-workflows-reference/index.html.md): Browse the list of core workflows and their hooks that are useful for your customizations.
+6. [Admin Injection Zones](https://docs.medusajs.com/resources/admin-widget-injection-zones/index.html.md): Browse the injection zones in the Medusa Admin to learn where you can inject widgets.
+
+***
+
+## More Examples in Recipes
+
+In the [Recipes](https://docs.medusajs.com/resources/recipes/index.html.md) documentation, you'll also find step-by-step guides for different use cases, such as building a marketplace, digital products, and more.
+
+
+# Re-Use Customizations with Plugins
+
+In the previous chapters, you've learned important concepts related to creating modules, implementing commerce features in workflows, exposing those features in API routes, customizing the Medusa Admin dashboard with Admin Extensions, and integrating third-party systems.
+
+You've implemented the brands example within a single Medusa application. However, this approach is not scalable when you want to reuse your customizations across multiple projects.
+
+To reuse your customizations across multiple Medusa applications, such as implementing brands in different projects, you can create a plugin. A plugin is an NPM package that encapsulates your customizations and can be installed in any Medusa application. Plugins can include modules, workflows, API routes, Admin Extensions, and more.
+
+
+
+Medusa provides the tooling to create a plugin package, test it in a local Medusa application, and publish it to NPM.
+
+To learn more about plugins and how to create them, refer to [this chapter](https://docs.medusajs.com/learn/fundamentals/plugins/index.html.md).
+
+
+# Medusa's Architecture
+
+In this chapter, you'll learn about the architectural layers in Medusa.
+
+Find the full architectural diagram at the [end of this chapter](#full-diagram-of-medusas-architecture).
+
+## HTTP, Workflow, and Module Layers
+
+Medusa is a headless commerce platform. So, storefronts, admin dashboards, and other clients consume Medusa's functionalities through its API routes.
+
+In a common Medusa application, requests go through four layers in the stack. In order of entry, those are:
+
+1. API Routes (HTTP): Our API Routes are the typical entry point. The Medusa server is based on Express.js, which handles incoming requests. It can also connect to a Redis database that stores the server session data.
+2. Workflows: API Routes consume workflows that hold the opinionated business logic of your application.
+3. Modules: Workflows use domain-specific modules for resource management.
+4. Data store: Modules query the underlying datastore, which is a PostgreSQL database in common cases.
+
+These layers of stack can be implemented within [plugins](https://docs.medusajs.com/learn/fundamentals/plugins/index.html.md).
+
+
+
+***
+
+## Database Layer
+
+The Medusa application injects into each module, including your [custom modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md), a connection to the configured PostgreSQL database. Modules use that connection to read and write data to the database.
+
+Modules can be implemented within [plugins](https://docs.medusajs.com/learn/fundamentals/plugins/index.html.md).
+
+
+
+***
+
+## Third-Party Integrations Layer
+
+Third-party services and systems are integrated through Medusa's Commerce and Architectural modules. You also create custom third-party integrations through a [custom module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md).
+
+Modules can be implemented within [plugins](https://docs.medusajs.com/learn/fundamentals/plugins/index.html.md).
+
+### Commerce Modules
+
+[Commerce modules](https://docs.medusajs.com/resources/commerce-modules/index.html.md) integrate third-party services relevant for commerce or user-facing features. For example, you can integrate [Stripe](https://docs.medusajs.com/resources/commerce-modules/payment/payment-provider/stripe/index.html.md) through a Payment Module Provider, or [ShipStation](https://docs.medusajs.com/resources/integrations/guides/shipstation/index.html.md) through a Fulfillment Module Provider.
+
+You can also integrate third-party services for custom functionalities. For example, you can integrate [Sanity](https://docs.medusajs.com/resources/integrations/guides/sanity/index.html.md) for rich CMS capabilities, or [Odoo](https://docs.medusajs.com/resources/recipes/erp/odoo/index.html.md) to sync your Medusa application with your ERP system.
+
+You can replace any of the third-party services mentioned above to build your preferred commerce ecosystem.
+
+
+
+### Architectural Modules
+
+[Architectural modules](https://docs.medusajs.com/resources/architectural-modules/index.html.md) integrate third-party services and systems for architectural features. Medusa has the following Architectural modules:
+
+- [Cache Module](https://docs.medusajs.com/resources/architectural-modules/cache/index.html.md): Caches data that require heavy computation. You can integrate a custom module to handle the caching with services like Memcached, or use the existing [Redis Cache Module](https://docs.medusajs.com/resources/architectural-modules/cache/redis/index.html.md).
+- [Event Module](https://docs.medusajs.com/resources/architectural-modules/event/index.html.md): A pub/sub system that allows you to subscribe to events and trigger them. You can integrate [Redis](https://docs.medusajs.com/resources/architectural-modules/event/redis/index.html.md) as the pub/sub system.
+- [File Module](https://docs.medusajs.com/resources/architectural-modules/file/index.html.md): Manages file uploads and storage, such as upload of product images. You can integrate [AWS S3](https://docs.medusajs.com/resources/architectural-modules/file/s3/index.html.md) for file storage.
+- [Locking Module](https://docs.medusajs.com/resources/architectural-modules/locking/index.html.md): Manages access to shared resources by multiple processes or threads, preventing conflict between processes and ensuring data consistency. You can integrate [Redis](https://docs.medusajs.com/resources/architectural-modules/locking/redis/index.html.md) for locking.
+- [Notification Module](https://docs.medusajs.com/resources/architectural-modules/notification/index.html.md): Sends notifications to customers and users, such as for order updates or newsletters. You can integrate [SendGrid](https://docs.medusajs.com/resources/architectural-modules/notification/sendgrid/index.html.md) for sending emails.
+- [Workflow Engine Module](https://docs.medusajs.com/resources/architectural-modules/workflow-engine/index.html.md): Orchestrates workflows that hold the business logic of your application. You can integrate [Redis](https://docs.medusajs.com/resources/architectural-modules/workflow-engine/redis/index.html.md) to orchestrate workflows.
+
+All of the third-party services mentioned above can be replaced to help you build your preferred architecture and ecosystem.
+
+
+
+***
+
+## Full Diagram of Medusa's Architecture
+
+The following diagram illustrates Medusa's architecture including all its layers.
+
+
+
+
# General Medusa Application Deployment Guide
In this document, you'll learn the general steps to deploy your Medusa application. How you apply these steps depend on your chosen hosting provider or platform.
@@ -1963,112 +2165,6 @@ The `activity` method returns the ID of the started activity. This ID can then b
If you configured the `LOG_LEVEL` environment variable to a level higher than those associated with the above methods, their messages won’t be logged.
-# Build Custom Features
-
-In the upcoming chapters, you'll follow step-by-step guides to build custom features in Medusa. These guides gradually introduce Medusa's concepts to help you understand what they are and how to use them.
-
-By following these guides, you'll add brands to the Medusa application that you can associate with products.
-
-To build a custom feature in Medusa, you need three main tools:
-
-- [Module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md): a package with commerce logic for a single domain. It defines new tables to add to the database, and a class of methods to manage these tables.
-- [Workflow](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md): a tool to perform an operation comprising multiple steps with built-in rollback and retry mechanisms.
-- [API route](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md): a REST endpoint that exposes commerce features to clients, such as the admin dashboard or a storefront. The API route executes a workflow that implements the commerce feature using modules.
-
-
-
-***
-
-## Next Chapters: Brand Module Example
-
-The next chapters will guide you to:
-
-1. Build a Brand Module that creates a `Brand` data model and provides data-management features.
-2. Add a workflow to create a brand.
-3. Expose an API route that allows admin users to create a brand using the workflow.
-
-
-# Customize Medusa Admin Dashboard
-
-In the previous chapters, you've customized your Medusa application to [add brands](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md), [expose an API route to create brands](https://docs.medusajs.com/learn/customization/custom-features/api-route/index.html.md), and [linked brands to products](https://docs.medusajs.com/learn/customization/extend-features/define-link/index.html.md).
-
-After customizing and extending your application with new features, you may need to provide an interface for admin users to utilize these features. The Medusa Admin dashboard is extendable, allowing you to:
-
-- Insert components, called [widgets](https://docs.medusajs.com/learn/fundamentals/admin/widgets/index.html.md), on existing pages.
-- Add new pages, called [UI Routes](https://docs.medusajs.com/learn/fundamentals/admin/ui-routes/index.html.md).
-
-From these customizations, you can send requests to custom API routes, allowing admin users to manage custom resources on the dashboard
-
-***
-
-## Next Chapters: View Brands in Dashboard
-
-In the next chapters, you'll continue with the brands example to:
-
-- Add a new section to the product details page that shows the product's brand.
-- Add a new page in the dashboard that shows all brands in the store.
-
-
-# Extend Core Commerce Features
-
-In the upcoming chapters, you'll learn about the concepts and tools to extend Medusa's core commerce features.
-
-In other commerce platforms, you extend core features and models through hacky workarounds that can introduce unexpected issues and side effects across the platform. It also makes your application difficult to maintain and upgrade in the long run.
-
-Medusa's framework and orchestration tools mitigate these issues while supporting all your customization needs:
-
-- [Module Links](https://docs.medusajs.com/learn/fundamentals/module-links/index.html.md): Link data models of different modules without building direct dependencies, ensuring that the Medusa application integrates your modules without side effects.
-- [Workflow Hooks](https://docs.medusajs.com/learn/fundamentals/workflows/workflow-hooks/index.html.md): inject custom functionalities into a workflow at predefined points, called hooks. This allows you to perform custom actions as a part of a core workflow without hacky workarounds.
-- [Additional Data in API Routes](https://docs.medusajs.com/learn/fundamentals/api-routes/additional-data/index.html.md): Configure core API routes to accept request parameters relevant to your customizations. These parameters are passed to the underlying workflow's hooks, where you can manage your custom data as part of an existing flow.
-
-***
-
-## Next Chapters: Link Brands to Products Example
-
-The next chapters explain how to use the tools mentioned above with step-by-step guides. You'll continue with the [brands example from the previous chapters](https://docs.medusajs.com/learn/customization/custom-features/index.html.md) to:
-
-- Link brands from the custom [Brand Module](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md) to products from Medusa's [Product Module](https://docs.medusajs.com/resources/commerce-modules/product/index.html.md).
-- Extend the core product-creation workflow and the API route that uses it to allow setting the brand of a newly created product.
-- Retrieve a product's associated brand's details.
-
-
-# Customizations Next Steps: Learn the Fundamentals
-
-The previous guides introduced Medusa's different concepts and how you can use them to customize Medusa for a realistic use case, You added brands to your application, linked them to products, customized the admin dashboard, and integrated a third-party CMS.
-
-The next chapters will cover each of these concepts in depth, with the different ways you can use them, their options or configurations, and more advanced features that weren't covered in the previous guides. While you can start building with Medusa, it's highly recommended to follow the next chapters for a better understanding of Medusa's fundamentals.
-
-## Useful Guides
-
-The following guides and references are useful for your development journey:
-
-3. [Commerce Modules](https://docs.medusajs.com/resources/commerce-modules/index.html.md): Browse the list of commerce modules in Medusa and their references to learn how to use them.
-4. [Service Factory Reference](https://docs.medusajs.com/resources/service-factory-reference/index.html.md): Learn about the methods generated by `MedusaService` with examples.
-5. [Workflows Reference](https://docs.medusajs.com/resources/medusa-workflows-reference/index.html.md): Browse the list of core workflows and their hooks that are useful for your customizations.
-6. [Admin Injection Zones](https://docs.medusajs.com/resources/admin-widget-injection-zones/index.html.md): Browse the injection zones in the Medusa Admin to learn where you can inject widgets.
-
-***
-
-## More Examples in Recipes
-
-In the [Recipes](https://docs.medusajs.com/resources/recipes/index.html.md) documentation, you'll also find step-by-step guides for different use cases, such as building a marketplace, digital products, and more.
-
-
-# Re-Use Customizations with Plugins
-
-In the previous chapters, you've learned important concepts related to creating modules, implementing commerce features in workflows, exposing those features in API routes, customizing the Medusa Admin dashboard with Admin Extensions, and integrating third-party systems.
-
-You've implemented the brands example within a single Medusa application. However, this approach is not scalable when you want to reuse your customizations across multiple projects.
-
-To reuse your customizations across multiple Medusa applications, such as implementing brands in different projects, you can create a plugin. A plugin is an NPM package that encapsulates your customizations and can be installed in any Medusa application. Plugins can include modules, workflows, API routes, Admin Extensions, and more.
-
-
-
-Medusa provides the tooling to create a plugin package, test it in a local Medusa application, and publish it to NPM.
-
-To learn more about plugins and how to create them, refer to [this chapter](https://docs.medusajs.com/learn/fundamentals/plugins/index.html.md).
-
-
# Medusa Testing Tools
In this chapter, you'll learn about Medusa's testing tools and how to install and configure them.
@@ -2165,100 +2261,30 @@ Medusa's Testing Framework works for integration tests only. You can write unit
The next chapters explain how to use the testing tools provided by `@medusajs/test-utils` to write tests.
-# Integrate Third-Party Systems
+# Admin Development
-Commerce applications often connect to third-party systems that provide additional or specialized features. For example, you may integrate a Content-Management System (CMS) for rich content features, a payment provider to process credit-card payments, and a notification service to send emails.
+In the next chapters, you'll learn more about possible admin customizations.
-Medusa's framework facilitates integrating these systems and orchestrating operations across them, saving you the effort of managing them yourself. You won't find those capabilities in other commerce platforms that in these scenarios become a bottleneck to building customizations and iterating quickly.
+You can customize the admin dashboard by:
-In Medusa, you integrate a third-party system by:
+- Adding new sections to existing pages using Widgets.
+- Adding new pages using UI Routes.
-1. Creating a module whose service provides the methods to connect to and perform operations in the third-party system.
-2. Building workflows that complete tasks spanning across systems. You use the module that integrates a third-party system in the workflow's steps.
-3. Executing the workflows you built in an [API route](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md), at a scheduled time, or when an event is emitted.
+However, you can't customize the admin dashboard's layout, design, or the content of the existing pages (aside from injecting widgets).
***
-## Next Chapters: Sync Brands Example
+## Medusa UI Package
-In the previous chapters, you've [added brands](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md) to your Medusa application. In the next chapters, you will:
+Medusa provides a Medusa UI package to facilitate your admin development through ready-made components and ensure a consistent design between your customizations and the dashboard’s design.
-1. Integrate a dummy third-party CMS in the Brand Module.
-2. Sync brands to the CMS when a brand is created.
-3. Sync brands from the CMS at a daily schedule.
-
-
-# Medusa's Architecture
-
-In this chapter, you'll learn about the architectural layers in Medusa.
-
-Find the full architectural diagram at the [end of this chapter](#full-diagram-of-medusas-architecture).
-
-## HTTP, Workflow, and Module Layers
-
-Medusa is a headless commerce platform. So, storefronts, admin dashboards, and other clients consume Medusa's functionalities through its API routes.
-
-In a common Medusa application, requests go through four layers in the stack. In order of entry, those are:
-
-1. API Routes (HTTP): Our API Routes are the typical entry point. The Medusa server is based on Express.js, which handles incoming requests. It can also connect to a Redis database that stores the server session data.
-2. Workflows: API Routes consume workflows that hold the opinionated business logic of your application.
-3. Modules: Workflows use domain-specific modules for resource management.
-4. Data store: Modules query the underlying datastore, which is a PostgreSQL database in common cases.
-
-These layers of stack can be implemented within [plugins](https://docs.medusajs.com/learn/fundamentals/plugins/index.html.md).
-
-
+Refer to the [Medusa UI documentation](https://docs.medusajs.com/ui/index.html.md) to learn how to install it and use its components.
***
-## Database Layer
+## Admin Components List
-The Medusa application injects into each module, including your [custom modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md), a connection to the configured PostgreSQL database. Modules use that connection to read and write data to the database.
-
-Modules can be implemented within [plugins](https://docs.medusajs.com/learn/fundamentals/plugins/index.html.md).
-
-
-
-***
-
-## Third-Party Integrations Layer
-
-Third-party services and systems are integrated through Medusa's Commerce and Architectural modules. You also create custom third-party integrations through a [custom module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md).
-
-Modules can be implemented within [plugins](https://docs.medusajs.com/learn/fundamentals/plugins/index.html.md).
-
-### Commerce Modules
-
-[Commerce modules](https://docs.medusajs.com/resources/commerce-modules/index.html.md) integrate third-party services relevant for commerce or user-facing features. For example, you can integrate [Stripe](https://docs.medusajs.com/resources/commerce-modules/payment/payment-provider/stripe/index.html.md) through a Payment Module Provider, or [ShipStation](https://docs.medusajs.com/resources/integrations/guides/shipstation/index.html.md) through a Fulfillment Module Provider.
-
-You can also integrate third-party services for custom functionalities. For example, you can integrate [Sanity](https://docs.medusajs.com/resources/integrations/guides/sanity/index.html.md) for rich CMS capabilities, or [Odoo](https://docs.medusajs.com/resources/recipes/erp/odoo/index.html.md) to sync your Medusa application with your ERP system.
-
-You can replace any of the third-party services mentioned above to build your preferred commerce ecosystem.
-
-
-
-### Architectural Modules
-
-[Architectural modules](https://docs.medusajs.com/resources/architectural-modules/index.html.md) integrate third-party services and systems for architectural features. Medusa has the following Architectural modules:
-
-- [Cache Module](https://docs.medusajs.com/resources/architectural-modules/cache/index.html.md): Caches data that require heavy computation. You can integrate a custom module to handle the caching with services like Memcached, or use the existing [Redis Cache Module](https://docs.medusajs.com/resources/architectural-modules/cache/redis/index.html.md).
-- [Event Module](https://docs.medusajs.com/resources/architectural-modules/event/index.html.md): A pub/sub system that allows you to subscribe to events and trigger them. You can integrate [Redis](https://docs.medusajs.com/resources/architectural-modules/event/redis/index.html.md) as the pub/sub system.
-- [File Module](https://docs.medusajs.com/resources/architectural-modules/file/index.html.md): Manages file uploads and storage, such as upload of product images. You can integrate [AWS S3](https://docs.medusajs.com/resources/architectural-modules/file/s3/index.html.md) for file storage.
-- [Locking Module](https://docs.medusajs.com/resources/architectural-modules/locking/index.html.md): Manages access to shared resources by multiple processes or threads, preventing conflict between processes and ensuring data consistency. You can integrate [Redis](https://docs.medusajs.com/resources/architectural-modules/locking/redis/index.html.md) for locking.
-- [Notification Module](https://docs.medusajs.com/resources/architectural-modules/notification/index.html.md): Sends notifications to customers and users, such as for order updates or newsletters. You can integrate [SendGrid](https://docs.medusajs.com/resources/architectural-modules/notification/sendgrid/index.html.md) for sending emails.
-- [Workflow Engine Module](https://docs.medusajs.com/resources/architectural-modules/workflow-engine/index.html.md): Orchestrates workflows that hold the business logic of your application. You can integrate [Redis](https://docs.medusajs.com/resources/architectural-modules/workflow-engine/redis/index.html.md) to orchestrate workflows.
-
-All of the third-party services mentioned above can be replaced to help you build your preferred architecture and ecosystem.
-
-
-
-***
-
-## Full Diagram of Medusa's Architecture
-
-The following diagram illustrates Medusa's architecture including all its layers.
-
-
+To build admin customizations that match the Medusa Admin's designs and layouts, refer to [this guide](https://docs.medusajs.com/resources/admin-components/index.html.md) to find common components.
# Custom CLI Scripts
@@ -2331,30 +2357,63 @@ npx medusa exec ./src/scripts/my-script.ts arg1 arg2
```
-# Admin Development
+# API Routes
-In the next chapters, you'll learn more about possible admin customizations.
+In this chapter, you’ll learn what API Routes are and how to create them.
-You can customize the admin dashboard by:
+## What is an API Route?
-- Adding new sections to existing pages using Widgets.
-- Adding new pages using UI Routes.
+An API Route is an endpoint. It exposes commerce features to external applications, such as storefronts, the admin dashboard, or third-party systems.
-However, you can't customize the admin dashboard's layout, design, or the content of the existing pages (aside from injecting widgets).
+The Medusa core application provides a set of admin and store API routes out-of-the-box. You can also create custom API routes to expose your custom functionalities.
***
-## Medusa UI Package
+## How to Create an API Route?
-Medusa provides a Medusa UI package to facilitate your admin development through ready-made components and ensure a consistent design between your customizations and the dashboard’s design.
+An API Route is created in a TypeScript or JavaScript file under the `src/api` directory of your Medusa application. The file’s name must be `route.ts` or `route.js`.
-Refer to the [Medusa UI documentation](https://docs.medusajs.com/ui/index.html.md) to learn how to install it and use its components.
+
+
+Each file exports API Route handler functions for at least one HTTP method (`GET`, `POST`, `DELETE`, etc…).
+
+For example, to create a `GET` API Route at `/hello-world`, create the file `src/api/hello-world/route.ts` with the following content:
+
+```ts title="src/api/hello-world/route.ts"
+import type {
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+
+export const GET = (
+ req: MedusaRequest,
+ res: MedusaResponse
+) => {
+ res.json({
+ message: "[GET] Hello world!",
+ })
+}
+```
+
+### Test API Route
+
+To test the API route above, start the Medusa application:
+
+```bash npm2yarn
+npm run dev
+```
+
+Then, send a `GET` request to the `/hello-world` API Route:
+
+```bash
+curl http://localhost:9000/hello-world
+```
***
-## Admin Components List
+## When to Use API Routes
-To build admin customizations that match the Medusa Admin's designs and layouts, refer to [this guide](https://docs.medusajs.com/resources/admin-components/index.html.md) to find common components.
+You're exposing custom functionality to be used by a storefront, admin dashboard, or any external application.
# Data Models
@@ -2461,65 +2520,6 @@ For example, the Blog Module's service would have methods like `retrievePost` an
Refer to the [Service Factory](https://docs.medusajs.com/learn/fundamentals/modules/service-factory/index.html.md) chapter to learn more about how to extend the service factory and manage data models, and refer to the [Service Factory Reference](https://docs.medusajs.com/resources/service-factory-reference/index.html.md) for the full list of generated methods and how to use them.
-# API Routes
-
-In this chapter, you’ll learn what API Routes are and how to create them.
-
-## What is an API Route?
-
-An API Route is an endpoint. It exposes commerce features to external applications, such as storefronts, the admin dashboard, or third-party systems.
-
-The Medusa core application provides a set of admin and store API routes out-of-the-box. You can also create custom API routes to expose your custom functionalities.
-
-***
-
-## How to Create an API Route?
-
-An API Route is created in a TypeScript or JavaScript file under the `src/api` directory of your Medusa application. The file’s name must be `route.ts` or `route.js`.
-
-
-
-Each file exports API Route handler functions for at least one HTTP method (`GET`, `POST`, `DELETE`, etc…).
-
-For example, to create a `GET` API Route at `/hello-world`, create the file `src/api/hello-world/route.ts` with the following content:
-
-```ts title="src/api/hello-world/route.ts"
-import type {
- MedusaRequest,
- MedusaResponse,
-} from "@medusajs/framework/http"
-
-export const GET = (
- req: MedusaRequest,
- res: MedusaResponse
-) => {
- res.json({
- message: "[GET] Hello world!",
- })
-}
-```
-
-### Test API Route
-
-To test the API route above, start the Medusa application:
-
-```bash npm2yarn
-npm run dev
-```
-
-Then, send a `GET` request to the `/hello-world` API Route:
-
-```bash
-curl http://localhost:9000/hello-world
-```
-
-***
-
-## When to Use API Routes
-
-You're exposing custom functionality to be used by a storefront, admin dashboard, or any external application.
-
-
# Environment Variables
In this chapter, you'll learn how environment variables are loaded in Medusa.
@@ -2599,6 +2599,765 @@ You should opt for setting configurations in `medusa-config.ts` where possible.
||Whether to disable analytics data collection. Learn more in ||
+# Framework Overview
+
+In this chapter, you'll learn about the Medusa Framework and how it facilitates building customizations in your Medusa application.
+
+## What is the Medusa Framework?
+
+All commerce application require some degree of customization. So, it's important to choose a platform that facilitates building those customizations.
+
+When you build customizations with other ecommerce platforms, they require you to pull data through HTTP APIs, run custom logic that span across systems in a separate application, and manually ensure data consistency across systems. This adds significant overhead and slows down development as you spend time managing complex distributed systems.
+
+The Medusa Framework eliminates this overhead by providing powerful low-level APIs and tools that let you build any type of customization directly within your Medusa project. You can build custom features, orchestrate operations and query data seamlessy across systems, extend core functionality, and automate tasks in your Medusa application.
+
+With the Medusa Framework, you can focus your efforts on building meaningful business customizations and continuously delivering new features.
+
+Using the Medusa Framework, you can build customizations like:
+
+- Product Reviews
+- Deep integration with an ERP system.
+- CMS integration with seamless content retrieval.
+- Custom item pricing in the cart.
+- Automated restock notifications.
+- Re-usable payment provider integrations.
+
+### Framework Concepts and Tools
+
+***
+
+## Build Custom Features
+
+The Medusa Framework allows you to build custom features tailored to your business needs.
+
+To create a custom feature, you can create a [module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md) that contains your feature's data models and the logic to manage them. A module is integrated into your Medusa application without side effects.
+
+### Data Model
+
+```ts highlights={modelHighlights}
+import { model } from "@medusajs/framework/utils"
+
+export const Post = model.define("post", {
+ id: model.id().primaryKey(),
+ title: model.text(),
+})
+```
+
+### Service
+
+```ts highlights={serviceHighlights}
+import { MedusaService } from "@medusajs/framework/utils"
+import { Post } from "./post"
+
+export class BlogModuleService extends MedusaService({
+ Post,
+}){
+ // CRUD methods generated by MedusaService
+}
+```
+
+### Module Definition
+
+```ts
+import { Module } from "@medusajs/framework/utils"
+import { BlogModuleService } from "./service"
+
+export const BLOG_MODULE = "blog"
+
+export default Module(BLOG_MODULE, {
+ service: BlogModuleService,
+})
+```
+
+Then, you can build commerce features and flows in [workflows](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md) that use your module. By using workflows, you benefit from features like [rollback mechanism](https://docs.medusajs.com/learn/fundamentals/workflows/compensation-function/index.html.md) and [retry configuration](https://docs.medusajs.com/learn/fundamentals/workflows/retry-failed-steps/index.html.md).
+
+### Step
+
+```ts highlights={stepHighlights}
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { BlogModuleService, BLOG_MODULE } from "../../modules/blog"
+
+type Input = {
+ title: string
+}
+
+const createPostStep = createStep(
+ "create-post",
+ async (input: Input, { container }) => {
+ const blogModuleService: BlogModuleService = container.resolve(
+ BLOG_MODULE
+ )
+
+ const post = await blogModuleService.createPosts(input.title)
+
+ return new StepResponse(post, post.id)
+ },
+ async (postId, { container }) => {
+ if (!postId) {
+ return
+ }
+
+ const blogModuleService: BlogModuleService = container.resolve(
+ BLOG_MODULE
+ )
+
+ await blogModuleService.deletePosts(postId)
+ }
+)
+```
+
+### Workflow
+
+```ts
+import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
+import { createPostStep } from "./steps"
+
+type Input = {
+ title: string
+}
+
+export const createPostWorkflow = createWorkflow(
+ "create-post",
+ (input: Input) => {
+ const post = createPostStep(input)
+
+ return new WorkflowResponse(post)
+ }
+)
+```
+
+Finally, you can expose your custom feature with [API routes](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md) that are built on top of your module and workflows.
+
+```ts title="API Route Example"
+import type {
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { createPostWorkflow } from "../../../workflows/create-post"
+
+type PostRequestBody = {
+ title: string
+}
+
+export const POST = async (
+ req: MedusaRequest,
+ res: MedusaResponse
+) => {
+ const { result } = await createPostWorkflow(req.scope)
+ .run({
+ input: result.validatedBody
+ })
+
+ return res.json(result)
+}
+```
+
+### Examples
+
+The following tutorials are step-by-step guides that show you how to build custom features using the Medusa Framework.
+
+- [Product Reviews](https://docs.medusajs.com/resources/how-to-tutorials/tutorials/product-reviews/index.html.md): Build a product reviews feature in your Medusa application.
+- [Wishlist](https://docs.medusajs.com/resources/plugins/guides/wishlist/index.html.md): Build a wishlist feature in your Medusa application.
+
+### Start Learning
+
+To learn more about the different concepts useful for building custom features, check out the following chapters:
+
+- [Modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md)
+- [Workflows](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md)
+- [API Routes](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md)
+
+***
+
+## Extend Existing Features
+
+The Medusa Framework is flexible and extensible, allowing you to extend and build on top of existing models and features.
+
+To associate new properties and relations with an existing model, you can create a [module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md) with data models that define these additions. Then, you can define a [module link](https://docs.medusajs.com/learn/fundamentals/module-links/index.html.md) that associates two data models from separate modules.
+
+### Module Link
+
+```ts highlights={defineLinkHighlights}
+import BrandModule from "../modules/brand"
+import ProductModule from "@medusajs/medusa/product"
+import { defineLink } from "@medusajs/framework/utils"
+
+export default defineLink(
+ {
+ linkable: ProductModule.linkable.product,
+ isList: true,
+ },
+ BrandModule.linkable.brand
+)
+```
+
+### Data Model
+
+```ts
+import { model } from "@medusajs/framework/utils"
+
+export const Brand = model.define("brand", {
+ id: model.id().primaryKey(),
+ name: model.text(),
+})
+```
+
+### Service
+
+```ts
+import { MedusaService } from "@medusajs/framework/utils"
+import { Brand } from "./models/brand"
+
+class BrandModuleService extends MedusaService({
+ Brand,
+}) {
+
+}
+
+export default BrandModuleService
+```
+
+### Module Definition
+
+```ts
+import { Module } from "@medusajs/framework/utils"
+import BrandModuleService from "./service"
+
+export const BRAND_MODULE = "brand"
+
+export default Module(BRAND_MODULE, {
+ service: BrandModuleService,
+})
+```
+
+Then, you can [hook into existing workflows](https://docs.medusajs.com/learn/fundamentals/workflows/workflow-hooks/index.html.md) to perform custom actions as part of existing features and flows. For example, you can create a brand when a product is created.
+
+```ts title="Workflow Hook Example" highlights={hookHighlights}
+import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
+import { StepResponse } from "@medusajs/framework/workflows-sdk"
+import { Modules } from "@medusajs/framework/utils"
+import { LinkDefinition } from "@medusajs/framework/types"
+import { BRAND_MODULE } from "../../modules/brand"
+import BrandModuleService from "../../modules/brand/service"
+
+createProductsWorkflow.hooks.productsCreated(
+ (async ({ products, additional_data }, { container }) => {
+ if (!additional_data?.brand_id) {
+ return new StepResponse([], [])
+ }
+
+ const brandModuleService: BrandModuleService = container.resolve(
+ BRAND_MODULE
+ )
+
+ const brand = await brandModuleService.createBrands({
+ name: additional_data.brand_name,
+ })
+ })
+)
+```
+
+You can also build custom workflows using your custom module and Medusa's modules, and use [existing workflows and steps](https://docs.medusajs.com/resources/medusa-workflows-reference/index.html.md) within your custom workflows.
+
+### Examples
+
+The following tutorials are step-by-step guides that show you how to extend existing features using the Medusa Framework.
+
+- [Custom Item Pricing](https://docs.medusajs.com/resources/examples/guides/custom-item-price/index.html.md): Add products with custom items to the cart.
+- [Loyalty Points System](https://docs.medusajs.com/resources/how-to-tutorials/tutorials/loyalty-points/index.html.md): Reward and allow customers to redeem loyalty points.
+
+### Start Learning
+
+To learn more about the different concepts useful for extending features, check out the following chapters:
+
+- [Modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md)
+- [Module Links](https://docs.medusajs.com/learn/fundamentals/module-links/index.html.md)
+- [Workflow Hooks](https://docs.medusajs.com/learn/fundamentals/workflows/workflow-hooks/index.html.md)
+
+***
+
+## Integrate Third-Party Services
+
+The Medusa Framework provides the tools and infrastructure to build a middleware solution for your commerce ecosystem. You can integrate third-party services, perform operations across systems, and query data from multiple sources.
+
+### Orchestrate Operations Across Systems
+
+The Medusa Framework solves one of the biggest hurdles for ecommerce platforms: orchestrating operations across systems. Medusa has a built-in durable execution engine to help complete tasks that span multiple systems.
+
+You can integrate a third-party service in a [module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md). This module provides an interface to perform operations with the third-party service.
+
+### Service
+
+```ts highlights={erpServiceHighlights}
+type Options = {
+ apiKey: string
+}
+
+export default class ErpModuleService {
+ private options: Options
+ private client
+
+ constructor({}, options: Options) {
+ this.options = options
+ // TODO initialize client that connects to ERP
+ }
+
+ async getProducts() {
+ // assuming client has a method to fetch products
+ return this.client.getProducts()
+ }
+
+ // TODO add more methods
+}
+```
+
+### Module Definition
+
+```ts
+import { Module } from "@medusajs/framework/utils"
+import ErpModuleService from "./service"
+
+export const ERP_MODULE = "erp"
+
+export default Module(ERP_MODULE, {
+ service: ErpModuleService,
+})
+```
+
+Then, you can build [workflows](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md) that perform operations across systems. In the workflow, you can use your module to interact with the integrated third-party service.
+
+For example, you can create a workflow that syncs products from your ERP system to your Medusa application.
+
+### Workflow
+
+```ts highlights={erpWorkflowHighlights}
+import {
+ createWorkflow,
+ WorkflowResponse,
+ transform,
+} from "@medusajs/framework/workflows-sdk"
+import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
+
+export const syncFromErpWorkflow = createWorkflow(
+ "sync-from-erp",
+ () => {
+ const erpProducts = getProductsFromErpStep()
+
+ const productsToCreate = transform({
+ erpProducts,
+ }, (data) => {
+ // TODO prepare ERP products to be created in Medusa
+ return data.erpProducts.map((erpProduct) => {
+ return {
+ title: erpProduct.title,
+ external_id: erpProduct.id,
+ variants: erpProduct.variants.map((variant) => ({
+ title: variant.title,
+ metadata: {
+ external_id: variant.id,
+ },
+ })),
+ // other data...
+ }
+ })
+ })
+
+ createProductsWorkflow.runAsStep({
+ input: {
+ products: productsToCreate,
+ },
+ })
+
+ return new WorkflowResponse({
+ erpProducts,
+ })
+ }
+)
+```
+
+### Step
+
+```ts
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { ERP_MODULE } from "../../modules/erp"
+import { ErpModuleService } from "../../modules/erp/service"
+
+const getProductsFromErpStep = createStep(
+ "get-products-from-erp",
+ async (_, { container }) => {
+ const erpModuleService: ErpModuleService = container.resolve(
+ ERP_MODULE
+ )
+
+ const products = await erpModuleService.getProducts()
+
+ return new StepResponse(products)
+ }
+)
+```
+
+By using a workflow to manage operations across systems, you benefit from features like [rollback mechanism](https://docs.medusajs.com/learn/fundamentals/workflows/compensation-function/index.html.md), [background long-running execution](https://docs.medusajs.com/learn/fundamentals/workflows/long-running-workflow/index.html.md), [retry configuration](https://docs.medusajs.com/learn/fundamentals/workflows/retry-failed-steps/index.html.md), and more. This is essential for building a middleware solution that performs operations across systems, as you don't have to worry about data inconsistencies or failures.
+
+You can then execute this workflow at a specific interval using [scheduled jobs](https://docs.medusajs.com/learn/fundamentals/scheduled-jobs/index.html.md) or when an event occurs using [events and subscribers](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md). You can also expose its features to client applications using an [API route](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md).
+
+### Scheduled Job
+
+```ts highlights={syncProductsJobHighlights}
+import {
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { syncFromErpWorkflow } from "../workflows/sync-from-erp"
+
+export default async function syncProductsJob(container: MedusaContainer) {
+ await syncFromErpWorkflow(container).run({})
+}
+
+export const config = {
+ name: "daily-product-sync",
+ schedule: "0 0 * * *", // Every day at midnight
+}
+```
+
+### Event Subscriber
+
+```ts highlights={productsCreatedHandlerHighlights}
+import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
+import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"
+
+export default async function productsCreatedHandler({
+ event: { data },
+ container,
+}: SubscriberArgs<{ id: string }[]>) {
+ await syncFromErpWorkflow(container).run({})
+}
+
+export const config: SubscriberConfig = {
+ event: `product.created`,
+}
+```
+
+### API Route
+
+```ts highlights={apiRouteHighlights}
+import type {
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { syncFromErpWorkflow } from "../../../workflows/sync-from-erp"
+
+export const POST = async (
+ req: MedusaRequest,
+ res: MedusaResponse
+) => {
+ const { result } = await syncFromErpWorkflow(req.scope).run({})
+
+ return res.status(200).json(result)
+}
+```
+
+#### Examples
+
+The following tutorials are step-by-step guides that show you how to orchestrate operations across third-party services using the Medusa Framework.
+
+- [Migrate Data from Magento](https://docs.medusajs.com/resources/integrations/guides/magento/index.html.md): Migrate data from Magento to your Medusa application.
+- [Integrate Third-Party Services](https://docs.medusajs.com/resources/integrations/index.html.md): Integrate CMS, Fulfillment, Payment, and other third-party services.
+
+#### Start Learning
+
+To learn more about the different concepts useful for integrating third-party services, check out the following chapters:
+
+- [Modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md)
+- [Workflows](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md)
+- [API Routes](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md)
+- [Events and Subscribers](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md)
+- [Scheduled Jobs](https://docs.medusajs.com/learn/fundamentals/scheduled-jobs/index.html.md)
+
+### Query Data Across Systems
+
+Another essential feature for integrating third-party services is querying data across those systems efficiently.
+
+The Framework allows you to build links not only between Medusa data models, but also virtual data models using [read-only module links](https://docs.medusajs.com/learn/fundamentals/module-links/read-only/index.html.md). You can build a [module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md) that provides the logic to query data from a third-party service, then create a read-only link between an existing data model and a virtual one from the third-party service.
+
+### Read-Only Link
+
+```ts highlights={readOnlyLinkHighlights}
+import BrandModule from "../modules/brand"
+import ProductModule from "@medusajs/medusa/product"
+import { defineLink } from "@medusajs/framework/utils"
+
+export default defineLink(
+ {
+ linkable: ProductModule.linkable.product,
+ field: "id",
+ },
+ {
+ ...BrandModule.linkable.brand.id,
+ primaryKey: "product_id",
+ },
+ {
+ readOnly: true,
+ }
+)
+```
+
+### Module Service
+
+```ts highlights={brandModuleService}
+type BrandModuleOptions = {
+ apiKey: string
+}
+
+export default class BrandModuleService {
+ private client
+
+ constructor({}, options: BrandModuleOptions) {
+ this.client = new Client(options)
+ }
+
+ async list(
+ filter: {
+ id: string | string[]
+ }
+ ) {
+ return this.client.getBrands(filter)
+ /**
+ - Example of returned data:
+ -
+ - [
+ - {
+ - "id": "brand_123",
+ - "name": "Brand 123",
+ - "product_id": "prod_321"
+ - },
+ - {
+ - "id": "post_456",
+ - "name": "Brand 456",
+ - "product_id": "prod_654"
+ - }
+ - ]
+ */
+ }
+}
+```
+
+### Module Definition
+
+```ts
+import { Module } from "@medusajs/framework/utils"
+import BrandModuleService from "./service"
+
+export const BRAND_MODULE = "brand"
+
+export default Module(BRAND_MODULE, {
+ service: BrandModuleService,
+})
+```
+
+Then, you can use [Query](https://docs.medusajs.com/learn/fundamentals/module-links/query/index.html.md) to retrieve a product and its brand from the third-party service in a single query.
+
+```ts title="Query Example" highlights={queryHighlights}
+const { result } = await query.graph({
+ entity: "product",
+ fields: ["id", "brand.*"],
+ filters: {
+ id: "prod_123",
+ },
+})
+
+// result = [{
+// id: "prod_123",
+// brand: {
+// id: "brand_123",
+// name: "Brand 123",
+// product_id: "prod_123"
+// }
+// ...
+// }]
+```
+
+Query simplifies the process of retrieving data across systems, as you can retrieve data from multiple sources in a single query.
+
+#### Examples
+
+The following tutorials are step-by-step guides that show you how to query data across systems using the Medusa Framework.
+
+- [Integrate Sanity CMS](https://docs.medusajs.com/resources/integrations/guides/sanity/index.html.md): Query data from third-party services using read-only links.
+
+#### Start Learning
+
+To learn more about the different concepts useful for querying data across systems, check out the following chapters:
+
+- [Modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md)
+- [Read-Only Links](https://docs.medusajs.com/learn/fundamentals/module-links/read-only/index.html.md)
+- [Query](https://docs.medusajs.com/learn/fundamentals/module-links/query/index.html.md)
+
+***
+
+## Automate Tasks
+
+The Medusa Framework provides the tools to automate tasks in your Medusa application. Automation is useful when you want to perform a task periodically, such as syncing data, or when an event occurs, such as sending a confirmation email when an order is placed.
+
+To build the task to be automated, you first create a [workflow](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md) that contains the task's logic, such as syncing data or sending an email.
+
+### Step
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { CreateNotificationDTO } from "@medusajs/framework/types"
+
+export const sendNotificationStep = createStep(
+ "send-notification",
+ async (data: CreateNotificationDTO[], { container }) => {
+ const notificationModuleService = container.resolve(
+ Modules.NOTIFICATION
+ )
+ const notification = await notificationModuleService.createNotifications(
+ data
+ )
+ return new StepResponse(notification)
+ }
+)
+```
+
+### Workflow
+
+```ts
+import {
+ createWorkflow,
+ WorkflowResponse,
+} from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { sendNotificationStep } from "./steps/send-notification"
+
+type WorkflowInput = {
+ id: string
+}
+
+export const sendOrderConfirmationWorkflow = createWorkflow(
+ "send-order-confirmation",
+ ({ id }: WorkflowInput) => {
+ // @ts-ignore
+ const { data: orders } = useQueryGraphStep({
+ entity: "order",
+ fields: [
+ "id",
+ "email",
+ "currency_code",
+ "total",
+ "items.*",
+ ],
+ filters: {
+ id,
+ },
+ })
+
+ const notification = sendNotificationStep([{
+ to: orders[0].email,
+ channel: "email",
+ template: "order-placed",
+ data: {
+ order: orders[0],
+ },
+ }])
+
+ return new WorkflowResponse(notification)
+ }
+)
+```
+
+Then, you can execute this workflow when an event occurs using a [subscriber](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md), or at a specific interval using a [scheduled job](https://docs.medusajs.com/learn/fundamentals/scheduled-jobs/index.html.md).
+
+### Event Subscriber
+
+```ts highlights={orderPlacedHandlerHighlights}
+import type {
+ SubscriberArgs,
+ SubscriberConfig,
+} from "@medusajs/framework"
+import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"
+
+export default async function orderPlacedHandler({
+ event: { data },
+ container,
+}: SubscriberArgs<{ id: string }>) {
+ await sendOrderConfirmationWorkflow(container)
+ .run({
+ input: {
+ id: data.id,
+ },
+ })
+}
+
+export const config: SubscriberConfig = {
+ event: "order.placed",
+}
+```
+
+### Scheduled Job
+
+```ts highlights={orderConfirmationJobHighlights}
+import type {
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"
+
+export default async function orderConfirmationJob(
+ container: MedusaContainer
+) {
+ await sendOrderConfirmationWorkflow(container).run({
+ input: {
+ id: "order_123",
+ }
+ })
+}
+export const config = {
+ name: "order-confirmation-job",
+ schedule: "0 0 * * *", // Every day at midnight
+}
+```
+
+### Examples
+
+The following guides are step-by-step guides that show you how to automate tasks using the Medusa Framework.
+
+- [Restock Notifications](https://docs.medusajs.com/resources/recipes/commerce-automation/restock-notification/index.html.md): Send restock notifications to customers when a product is back in stock.
+- [Sync Data from and to ERP](https://docs.medusajs.com/resources/recipes/erp#sync-products-from-erp/index.html.md): Sync data between your Medusa application and an ERP system.
+
+### Start Learning
+
+To learn more about the different concepts useful for automating tasks, check out the following chapters:
+
+- [Workflows](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md)
+- [Events and Subscribers](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md)
+- [Scheduled Jobs](https://docs.medusajs.com/learn/fundamentals/scheduled-jobs/index.html.md)
+
+***
+
+## Re-Use Customizations Across Applications
+
+If you have custom features that you want to re-use across multiple Medusa applications, or you want to publish your customizations for the community to use, you can build a [plugin](https://docs.medusajs.com/learn/fundamentals/plugins/index.html.md).
+
+A plugin encapsulates your customizations in a single package. The customizations include [modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md), [workflows](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md), [API routes](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md), and more.
+
+
+
+You can then publish that plugin to NPM and install it in any Medusa application. This allows you to re-use your customizations efficiently across multiple projects, or share them with the community.
+
+### Examples
+
+The following tutorials are step-by-step guides that show you how to build plugins using the Medusa Framework.
+
+- [Wishlist Plugin](https://docs.medusajs.com/resources/plugins/guides/wishlist/index.html.md): Build a wishlist plugin for your Medusa application.
+- [Migrate Data from Magento Plugin](https://docs.medusajs.com/resources/integrations/guides/magento/index.html.md): Build a plugin that migrates data from Magento to your Medusa application.
+
+### Start Learning
+
+To learn more about the different concepts useful for building plugins, check out the following chapters:
+
+- [Plugins](https://docs.medusajs.com/learn/fundamentals/plugins/index.html.md)
+
+
# Events and Subscribers
In this chapter, you’ll learn about Medusa's event system, and how to handle events with subscribers.
@@ -2851,138 +3610,6 @@ A [module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md),
Learn more about the module's container in [this chapter](https://docs.medusajs.com/learn/fundamentals/modules/container/index.html.md).
-# Plugins
-
-In this chapter, you'll learn what a plugin is in Medusa.
-
-Plugins are available starting from [Medusa v2.3.0](https://github.com/medusajs/medusa/releases/tag/v2.3.0).
-
-## What is a Plugin?
-
-A plugin is a package of reusable Medusa customizations that you can install in any Medusa application. The supported customizations are [Modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md), [API Routes](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md), [Workflows](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md), [Workflow Hooks](https://docs.medusajs.com/learn/fundamentals/workflows/workflow-hooks/index.html.md), [Links](https://docs.medusajs.com/learn/fundamentals/module-links/index.html.md), [Subscribers](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md), [Scheduled Jobs](https://docs.medusajs.com/learn/fundamentals/scheduled-jobs/index.html.md), and [Admin Extensions](https://docs.medusajs.com/learn/fundamentals/admin/index.html.md).
-
-Plugins allow you to reuse your Medusa customizations across multiple projects or share them with the community. They can be published to npm and installed in any Medusa project.
-
-
-
-Learn how to create a wishlist plugin in [this guide](https://docs.medusajs.com/resources/plugins/guides/wishlist/index.html.md).
-
-***
-
-## Plugin vs Module
-
-A [module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md) is an isolated package related to a single domain or functionality, such as product reviews or integrating a Content Management System. A module can't access any resources in the Medusa application that are outside its codebase.
-
-A plugin, on the other hand, can contain multiple Medusa customizations, including modules. Your plugin can define a module, then build flows around it.
-
-For example, in a plugin, you can define a module that integrates a third-party service, then add a workflow that uses the module when a certain event occurs to sync data to that service.
-
-- You want to reuse your Medusa customizations across multiple projects.
-- You want to share your Medusa customizations with the community.
-
-- You want to build a custom feature related to a single domain or integrate a third-party service. Instead, use a [module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md). You can wrap that module in a plugin if it's used in other customizations, such as if it has a module link or it's used in a workflow.
-
-***
-
-## How to Create a Plugin?
-
-The next chapter explains how you can create and publish a plugin.
-
-
-# Scheduled Jobs
-
-In this chapter, you’ll learn about scheduled jobs and how to use them.
-
-## What is a Scheduled Job?
-
-When building your commerce application, you may need to automate tasks and run them repeatedly at a specific schedule. For example, you need to automatically sync products to a third-party service once a day.
-
-In other commerce platforms, this feature isn't natively supported. Instead, you have to setup a separate application to execute cron jobs, which adds complexity as to how you expose this task to be executed in a cron job, or how do you debug it when it's not running within the platform's tooling.
-
-Medusa removes this overhead by supporting this feature natively with scheduled jobs. A scheduled job is an asynchronous function that the Medusa application runs at the interval you specify during the Medusa application's runtime. Your efforts are only spent on implementing the functionality performed by the job, such as syncing products to an ERP.
-
-- You want the action to execute at a specified schedule while the Medusa application **isn't** running. Instead, use the operating system's equivalent of a cron job.
-- You want to execute the action once when the application loads. Use [loaders](https://docs.medusajs.com/learn/fundamentals/modules/loaders/index.html.md) instead.
-- You want to execute the action if an event occurs. Use [subscribers](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md) instead.
-
-***
-
-## How to Create a Scheduled Job?
-
-You create a scheduled job in a TypeScript or JavaScript file under the `src/jobs` directory. The file exports the asynchronous function to run, and the configurations indicating the schedule to run the function.
-
-For example, create the file `src/jobs/hello-world.ts` with the following content:
-
-
-
-```ts title="src/jobs/hello-world.ts" highlights={highlights}
-import { MedusaContainer } from "@medusajs/framework/types"
-
-export default async function greetingJob(container: MedusaContainer) {
- const logger = container.resolve("logger")
-
- logger.info("Greeting!")
-}
-
-export const config = {
- name: "greeting-every-minute",
- schedule: "* * * * *",
-}
-```
-
-You export an asynchronous function that receives the [Medusa container](https://docs.medusajs.com/learn/fundamentals/medusa-container/index.html.md) as a parameter. In the function, you resolve the [Logger utility](https://docs.medusajs.com/learn/debugging-and-testing/logging/index.html.md) from the Medusa container and log a message.
-
-You also export a `config` object that has the following properties:
-
-- `name`: A unique name for the job.
-- `schedule`: A string that holds a [cron expression](https://crontab.guru/) indicating the schedule to run the job.
-
-This scheduled job executes every minute and logs into the terminal `Greeting!`.
-
-### Test the Scheduled Job
-
-To test out your scheduled job, start the Medusa application:
-
-```bash npm2yarn
-npm run dev
-```
-
-After a minute, the following message will be logged to the terminal:
-
-```bash
-info: Greeting!
-```
-
-***
-
-## Example: Sync Products Once a Day
-
-In this section, you'll find a brief example of how you use a scheduled job to sync products to a third-party service.
-
-When implementing flows spanning across systems or [modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md), you use [workflows](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md). A workflow is a task made up of a series of steps, and you construct it like you would a regular function, but it's a special function that supports rollback mechanism in case of errors, background execution, and more.
-
-You can learn how to create a workflow in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md), but this example assumes you already have a `syncProductToErpWorkflow` implemented. To execute this workflow once a day, create a scheduled job at `src/jobs/sync-products.ts` with the following content:
-
-```ts title="src/jobs/sync-products.ts"
-import { MedusaContainer } from "@medusajs/framework/types"
-import { syncProductToErpWorkflow } from "../workflows/sync-products-to-erp"
-
-export default async function syncProductsJob(container: MedusaContainer) {
- await syncProductToErpWorkflow(container)
- .run()
-}
-
-export const config = {
- name: "sync-products-job",
- schedule: "0 0 * * *",
-}
-```
-
-In the scheduled job function, you execute the `syncProductToErpWorkflow` by invoking it and passing it the container, then invoking the `run` method. You also specify in the exported configurations the schedule `0 0 * * *` which indicates midnight time of every day.
-
-The next time you start the Medusa application, it will run this job every day at midnight.
-
-
# Define Module Link
In this chapter, you’ll learn what a module link is and how to define one.
@@ -3198,6 +3825,44 @@ npx medusa db:migrate
```
+# Plugins
+
+In this chapter, you'll learn what a plugin is in Medusa.
+
+Plugins are available starting from [Medusa v2.3.0](https://github.com/medusajs/medusa/releases/tag/v2.3.0).
+
+## What is a Plugin?
+
+A plugin is a package of reusable Medusa customizations that you can install in any Medusa application. The supported customizations are [Modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md), [API Routes](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md), [Workflows](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md), [Workflow Hooks](https://docs.medusajs.com/learn/fundamentals/workflows/workflow-hooks/index.html.md), [Links](https://docs.medusajs.com/learn/fundamentals/module-links/index.html.md), [Subscribers](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md), [Scheduled Jobs](https://docs.medusajs.com/learn/fundamentals/scheduled-jobs/index.html.md), and [Admin Extensions](https://docs.medusajs.com/learn/fundamentals/admin/index.html.md).
+
+Plugins allow you to reuse your Medusa customizations across multiple projects or share them with the community. They can be published to npm and installed in any Medusa project.
+
+
+
+Learn how to create a wishlist plugin in [this guide](https://docs.medusajs.com/resources/plugins/guides/wishlist/index.html.md).
+
+***
+
+## Plugin vs Module
+
+A [module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md) is an isolated package related to a single domain or functionality, such as product reviews or integrating a Content Management System. A module can't access any resources in the Medusa application that are outside its codebase.
+
+A plugin, on the other hand, can contain multiple Medusa customizations, including modules. Your plugin can define a module, then build flows around it.
+
+For example, in a plugin, you can define a module that integrates a third-party service, then add a workflow that uses the module when a certain event occurs to sync data to that service.
+
+- You want to reuse your Medusa customizations across multiple projects.
+- You want to share your Medusa customizations with the community.
+
+- You want to build a custom feature related to a single domain or integrate a third-party service. Instead, use a [module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md). You can wrap that module in a plugin if it's used in other customizations, such as if it has a module link or it's used in a workflow.
+
+***
+
+## How to Create a Plugin?
+
+The next chapter explains how you can create and publish a plugin.
+
+
# Modules
In this chapter, you’ll learn about modules and how to create them.
@@ -3498,6 +4163,100 @@ This will create a post and return it in the response:
You can also execute the workflow from a [subscriber](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md) when an event occurs, or from a [scheduled job](https://docs.medusajs.com/learn/fundamentals/scheduled-jobs/index.html.md) to run it at a specified interval.
+# Scheduled Jobs
+
+In this chapter, you’ll learn about scheduled jobs and how to use them.
+
+## What is a Scheduled Job?
+
+When building your commerce application, you may need to automate tasks and run them repeatedly at a specific schedule. For example, you need to automatically sync products to a third-party service once a day.
+
+In other commerce platforms, this feature isn't natively supported. Instead, you have to setup a separate application to execute cron jobs, which adds complexity as to how you expose this task to be executed in a cron job, or how do you debug it when it's not running within the platform's tooling.
+
+Medusa removes this overhead by supporting this feature natively with scheduled jobs. A scheduled job is an asynchronous function that the Medusa application runs at the interval you specify during the Medusa application's runtime. Your efforts are only spent on implementing the functionality performed by the job, such as syncing products to an ERP.
+
+- You want the action to execute at a specified schedule while the Medusa application **isn't** running. Instead, use the operating system's equivalent of a cron job.
+- You want to execute the action once when the application loads. Use [loaders](https://docs.medusajs.com/learn/fundamentals/modules/loaders/index.html.md) instead.
+- You want to execute the action if an event occurs. Use [subscribers](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md) instead.
+
+***
+
+## How to Create a Scheduled Job?
+
+You create a scheduled job in a TypeScript or JavaScript file under the `src/jobs` directory. The file exports the asynchronous function to run, and the configurations indicating the schedule to run the function.
+
+For example, create the file `src/jobs/hello-world.ts` with the following content:
+
+
+
+```ts title="src/jobs/hello-world.ts" highlights={highlights}
+import { MedusaContainer } from "@medusajs/framework/types"
+
+export default async function greetingJob(container: MedusaContainer) {
+ const logger = container.resolve("logger")
+
+ logger.info("Greeting!")
+}
+
+export const config = {
+ name: "greeting-every-minute",
+ schedule: "* * * * *",
+}
+```
+
+You export an asynchronous function that receives the [Medusa container](https://docs.medusajs.com/learn/fundamentals/medusa-container/index.html.md) as a parameter. In the function, you resolve the [Logger utility](https://docs.medusajs.com/learn/debugging-and-testing/logging/index.html.md) from the Medusa container and log a message.
+
+You also export a `config` object that has the following properties:
+
+- `name`: A unique name for the job.
+- `schedule`: A string that holds a [cron expression](https://crontab.guru/) indicating the schedule to run the job.
+
+This scheduled job executes every minute and logs into the terminal `Greeting!`.
+
+### Test the Scheduled Job
+
+To test out your scheduled job, start the Medusa application:
+
+```bash npm2yarn
+npm run dev
+```
+
+After a minute, the following message will be logged to the terminal:
+
+```bash
+info: Greeting!
+```
+
+***
+
+## Example: Sync Products Once a Day
+
+In this section, you'll find a brief example of how you use a scheduled job to sync products to a third-party service.
+
+When implementing flows spanning across systems or [modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md), you use [workflows](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md). A workflow is a task made up of a series of steps, and you construct it like you would a regular function, but it's a special function that supports rollback mechanism in case of errors, background execution, and more.
+
+You can learn how to create a workflow in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md), but this example assumes you already have a `syncProductToErpWorkflow` implemented. To execute this workflow once a day, create a scheduled job at `src/jobs/sync-products.ts` with the following content:
+
+```ts title="src/jobs/sync-products.ts"
+import { MedusaContainer } from "@medusajs/framework/types"
+import { syncProductToErpWorkflow } from "../workflows/sync-products-to-erp"
+
+export default async function syncProductsJob(container: MedusaContainer) {
+ await syncProductToErpWorkflow(container)
+ .run()
+}
+
+export const config = {
+ name: "sync-products-job",
+ schedule: "0 0 * * *",
+}
+```
+
+In the scheduled job function, you execute the `syncProductToErpWorkflow` by invoking it and passing it the container, then invoking the `run` method. You also specify in the exported configurations the schedule `0 0 * * *` which indicates midnight time of every day.
+
+The next time you start the Medusa application, it will run this job every day at midnight.
+
+
# Worker Mode of Medusa Instance
In this chapter, you'll learn about the different modes of running a Medusa instance and how to configure the mode.
@@ -3844,72 +4603,6 @@ You can now execute this workflow in a custom API route, scheduled job, or subsc
Find a full list of the registered resources in the Medusa container and their registration key in [this reference](https://docs.medusajs.com/resources/medusa-container-resources/index.html.md). You can use these resources in your custom workflows.
-# Next.js Starter Storefront
-
-The Medusa application is made up of a Node.js server and an admin dashboard. The storefront is installed and hosted separately from the Medusa application, giving you the flexibility to choose the frontend tech stack that you and your team are proficient in, and implement unique design systems and user experience.
-
-The Next.js Starter storefront provides rich commerce features and a sleek design. Developers and businesses can use it as-is or build on top of it to tailor it for the business's unique use case, design, and customer experience.
-
-In this chapter, you’ll learn how to install the Next.js Starter storefront separately from the Medusa application. You can also install it while installing the Medusa application as explained in [the installation chapter](https://docs.medusajs.com/learn/installation/index.html.md).
-
-## Install Next.js Starter
-
-### Prerequisites
-
-- [Node.js v20+](https://nodejs.org/en/download)
-- [Git CLI tool](https://git-scm.com/downloads)
-
-If you already have a Medusa application installed with at least one region, you can install the Next.js Starter storefront with the following steps:
-
-1. Clone the [Next.js Starter](https://github.com/medusajs/nextjs-starter-medusa):
-
-```bash
-git clone https://github.com/medusajs/nextjs-starter-medusa my-medusa-storefront
-```
-
-2. Change to the `my-medusa-storefront` directory, install the dependencies, and rename the template environment variable file:
-
-```bash npm2yarn
-cd my-medusa-storefront
-npm install
-mv .env.template .env.local
-```
-
-3. Set the Medusa application's publishable API key in the `NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY` environment variable. You can retrieve the publishable API key in on the Medusa Admin dashboard by going to Settings -> Publishable API Keys
-
-```bash
-NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=pk_123...
-```
-
-4. While the Medusa application is running, start the Next.js Starter storefront:
-
-```bash npm2yarn
-npm run dev
-```
-
-Your Next.js Starter storefront is now running at `http://localhost:8000`.
-
-***
-
-## Customize Storefront
-
-To customize the storefront, refer to the following directories:
-
-- `src/app`: The storefront’s pages.
-- `src/modules`: The storefront’s components.
-- `src/styles`: The storefront’s styles.
-
-You can learn more about development with Next.js through [their documentation](https://nextjs.org/docs/getting-started).
-
-***
-
-## Configurations and Integrations
-
-The Next.js Starter is compatible with some Medusa integrations out-of-the-box, such as the Stripe provider module. You can also change some of its configurations if necessary.
-
-Refer to the [Next.js Starter reference](https://docs.medusajs.com/resources/nextjs-starter/index.html.md) for more details.
-
-
# Usage Information
At Medusa, we strive to provide the best experience for developers using our platform. For that reason, Medusa collects anonymous and non-sensitive data that provides a global understanding of how users are using Medusa.
@@ -4000,160 +4693,70 @@ MEDUSA_FF_ANALYTICS=false
```
-# Guide: Implement Brand Module
+# Next.js Starter Storefront
-In this chapter, you'll build a Brand Module that adds a `brand` table to the database and provides data-management features for it.
+The Medusa application is made up of a Node.js server and an admin dashboard. The storefront is installed and hosted separately from the Medusa application, giving you the flexibility to choose the frontend tech stack that you and your team are proficient in, and implement unique design systems and user experience.
-A module is a reusable package of functionalities related to a single domain or integration. Medusa comes with multiple pre-built modules for core commerce needs, such as the [Cart Module](https://docs.medusajs.com/resources/commerce-modules/cart/index.html.md) that holds the data models and business logic for cart operations.
+The Next.js Starter storefront provides rich commerce features and a sleek design. Developers and businesses can use it as-is or build on top of it to tailor it for the business's unique use case, design, and customer experience.
-In a module, you create data models and business logic to manage them. In the next chapters, you'll see how you use the module to build commerce features.
+In this chapter, you’ll learn how to install the Next.js Starter storefront separately from the Medusa application. You can also install it while installing the Medusa application as explained in [the installation chapter](https://docs.medusajs.com/learn/installation/index.html.md).
-Learn more about modules in [this chapter](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md).
+## Install Next.js Starter
-## 1. Create Module Directory
+### Prerequisites
-Modules are created in a sub-directory of `src/modules`. So, start by creating the directory `src/modules/brand` that will hold the Brand Module's files.
+- [Node.js v20+](https://nodejs.org/en/download)
+- [Git CLI tool](https://git-scm.com/downloads)
-
+If you already have a Medusa application installed with at least one region, you can install the Next.js Starter storefront with the following steps:
-***
-
-## 2. Create Data Model
-
-A data model represents a table in the database. You create data models using Medusa's Data Model Language (DML). It simplifies defining a table's columns, relations, and indexes with straightforward methods and configurations.
-
-Learn more about data models in [this chapter](https://docs.medusajs.com/learn/fundamentals/modules#1-create-data-model/index.html.md).
-
-You create a data model in a TypeScript or JavaScript file under the `models` directory of a module. So, to create a data model that represents a new `brand` table in the database, create the file `src/modules/brand/models/brand.ts` with the following content:
-
-
-
-```ts title="src/modules/brand/models/brand.ts"
-import { model } from "@medusajs/framework/utils"
-
-export const Brand = model.define("brand", {
- id: model.id().primaryKey(),
- name: model.text(),
-})
-```
-
-You create a `Brand` data model which has an `id` primary key property, and a `name` text property.
-
-You define the data model using the `define` method of the DML. It accepts two parameters:
-
-1. The first one is the name of the data model's table in the database. Use snake-case names.
-2. The second is an object, which is the data model's schema.
-
-Learn about other property types in [this chapter](https://docs.medusajs.com/learn/fundamentals/data-models/properties/index.html.md).
-
-***
-
-## 3. Create Module Service
-
-You perform database operations on your data models in a service, which is a class exported by the module and acts like an interface to its functionalities.
-
-In this step, you'll create the Brand Module's service that provides methods to manage the `Brand` data model. In the next chapters, you'll use this service when exposing custom features that involve managing brands.
-
-Learn more about services in [this chapter](https://docs.medusajs.com/learn/fundamentals/modules#2-create-service/index.html.md).
-
-You define a service in a `service.ts` or `service.js` file at the root of your module's directory. So, create the file `src/modules/brand/service.ts` with the following content:
-
-
-
-```ts title="src/modules/brand/service.ts" highlights={serviceHighlights}
-import { MedusaService } from "@medusajs/framework/utils"
-import { Brand } from "./models/brand"
-
-class BrandModuleService extends MedusaService({
- Brand,
-}) {
-
-}
-
-export default BrandModuleService
-```
-
-The `BrandModuleService` extends a class returned by `MedusaService` from the Modules SDK. This function generates a class with data-management methods for your module's data models.
-
-The `MedusaService` function receives an object of the module's data models as a parameter, and generates methods to manage those data models. So, the `BrandModuleService` now has methods like `createBrands` and `retrieveBrand` to manage the `Brand` data model.
-
-You'll use these methods in the [next chapter](https://docs.medusajs.com/learn/customization/custom-features/workflow/index.html.md).
-
-Find a reference of all generated methods in [this guide](https://docs.medusajs.com/resources/service-factory-reference/index.html.md).
-
-***
-
-## 4. Export Module Definition
-
-A module must export a definition that tells Medusa the name of the module and its main service. This definition is exported in an `index.ts` file at the module's root directory.
-
-So, to export the Brand Module's definition, create the file `src/modules/brand/index.ts` with the following content:
-
-
-
-```ts title="src/modules/brand/index.ts"
-import { Module } from "@medusajs/framework/utils"
-import BrandModuleService from "./service"
-
-export const BRAND_MODULE = "brand"
-
-export default Module(BRAND_MODULE, {
- service: BrandModuleService,
-})
-```
-
-You use `Module` from the Modules SDK to create the module's definition. It accepts two parameters:
-
-1. The module's name (`brand`). You'll use this name when you use this module in other customizations.
-2. An object with a required property `service` indicating the module's main service.
-
-You export `BRAND_MODULE` to reference the module's name more reliably in other customizations.
-
-***
-
-## 5. Add Module to Medusa's Configurations
-
-To start using your module, you must add it to Medusa's configurations in `medusa-config.ts`.
-
-The object passed to `defineConfig` in `medusa-config.ts` accepts a `modules` property, whose value is an array of modules to add to the application. So, add the following in `medusa-config.ts`:
-
-```ts title="medusa-config.ts"
-module.exports = defineConfig({
- // ...
- modules: [
- {
- resolve: "./src/modules/brand",
- },
- ],
-})
-```
-
-The Brand Module is now added to your Medusa application. You'll start using it in the [next chapter](https://docs.medusajs.com/learn/customization/custom-features/workflow/index.html.md).
-
-***
-
-## 6. Generate and Run Migrations
-
-A migration is a TypeScript or JavaScript file that defines database changes made by a module. Migrations ensure that your module is re-usable and removes friction when working in a team, making it easy to reflect changes across team members' databases.
-
-Learn more about migrations in [this chapter](https://docs.medusajs.com/learn/fundamentals/modules#5-generate-migrations/index.html.md).
-
-[Medusa's CLI tool](https://docs.medusajs.com/resources/medusa-cli/index.html.md) allows you to generate migration files for your module, then run those migrations to reflect the changes in the database. So, run the following commands in your Medusa application's directory:
+1. Clone the [Next.js Starter](https://github.com/medusajs/nextjs-starter-medusa):
```bash
-npx medusa db:generate brand
-npx medusa db:migrate
+git clone https://github.com/medusajs/nextjs-starter-medusa my-medusa-storefront
```
-The `db:generate` command accepts as an argument the name of the module to generate the migrations for, and the `db:migrate` command runs all migrations that haven't been run yet in the Medusa application.
+2. Change to the `my-medusa-storefront` directory, install the dependencies, and rename the template environment variable file:
+
+```bash npm2yarn
+cd my-medusa-storefront
+npm install
+mv .env.template .env.local
+```
+
+3. Set the Medusa application's publishable API key in the `NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY` environment variable. You can retrieve the publishable API key in on the Medusa Admin dashboard by going to Settings -> Publishable API Keys
+
+```bash
+NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=pk_123...
+```
+
+4. While the Medusa application is running, start the Next.js Starter storefront:
+
+```bash npm2yarn
+npm run dev
+```
+
+Your Next.js Starter storefront is now running at `http://localhost:8000`.
***
-## Next Step: Create Brand Workflow
+## Customize Storefront
-The Brand Module now creates a `brand` table in the database and provides a class to manage its records.
+To customize the storefront, refer to the following directories:
-In the next chapter, you'll implement the functionality to create a brand in a workflow. You'll then use that workflow in a later chapter to expose an endpoint that allows admin users to create a brand.
+- `src/app`: The storefront’s pages.
+- `src/modules`: The storefront’s components.
+- `src/styles`: The storefront’s styles.
+
+You can learn more about development with Next.js through [their documentation](https://nextjs.org/docs/getting-started).
+
+***
+
+## Configurations and Integrations
+
+The Next.js Starter is compatible with some Medusa integrations out-of-the-box, such as the Stripe provider module. You can also change some of its configurations if necessary.
+
+Refer to the [Next.js Starter reference](https://docs.medusajs.com/resources/nextjs-starter/index.html.md) for more details.
# Guide: Create Brand API Route
@@ -4364,6 +4967,582 @@ Now that you have brands in your Medusa application, you want to associate a bra
In the next chapters, you'll learn how to build associations between data models defined in different modules.
+# Guide: Create Brand Workflow
+
+This chapter builds on the work from the [previous chapter](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md) where you created a Brand Module.
+
+After adding custom modules to your application, you build commerce features around them using workflows. A workflow is a series of queries and actions, called steps, that complete a task spanning across modules. You construct a workflow similar to a regular function, but it's a special function that allows you to define roll-back logic, retry configurations, and more advanced features.
+
+The workflow you'll create in this chapter will use the Brand Module's service to implement the feature of creating a brand. In the [next chapter](https://docs.medusajs.com/learn/customization/custom-features/api-route/index.html.md), you'll expose an API route that allows admin users to create a brand, and you'll use this workflow in the route's implementation.
+
+Learn more about workflows in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md).
+
+### Prerequisites
+
+- [Brand Module](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md)
+
+***
+
+## 1. Create createBrandStep
+
+A workflow consists of a series of steps, each step created in a TypeScript or JavaScript file under the `src/workflows` directory. A step is defined using `createStep` from the Workflows SDK
+
+The workflow you're creating in this guide has one step to create the brand. So, create the file `src/workflows/create-brand.ts` with the following content:
+
+
+
+```ts title="src/workflows/create-brand.ts"
+import {
+ createStep,
+ StepResponse,
+} from "@medusajs/framework/workflows-sdk"
+import { BRAND_MODULE } from "../modules/brand"
+import BrandModuleService from "../modules/brand/service"
+
+export type CreateBrandStepInput = {
+ name: string
+}
+
+export const createBrandStep = createStep(
+ "create-brand-step",
+ async (input: CreateBrandStepInput, { container }) => {
+ const brandModuleService: BrandModuleService = container.resolve(
+ BRAND_MODULE
+ )
+
+ const brand = await brandModuleService.createBrands(input)
+
+ return new StepResponse(brand, brand.id)
+ }
+)
+```
+
+You create a `createBrandStep` using the `createStep` function. It accepts the step's unique name as a first parameter, and the step's function as a second parameter.
+
+The step function receives two parameters: input passed to the step when it's invoked, and an object of general context and configurations. This object has a `container` property, which is the Medusa container.
+
+The [Medusa container](https://docs.medusajs.com/learn/fundamentals/medusa-container/index.html.md) is a registry of framework and commerce tools accessible in your customizations, such as a workflow's step. The Medusa application registers the services of core and custom modules in the container, allowing you to resolve and use them.
+
+So, In the step function, you use the Medusa container to resolve the Brand Module's service and use its generated `createBrands` method, which accepts an object of brands to create.
+
+Learn more about the generated `create` method's usage in [this reference](https://docs.medusajs.com/resources/service-factory-reference/methods/create/index.html.md).
+
+A step must return an instance of `StepResponse`. Its first parameter is the data returned by the step, and the second is the data passed to the compensation function, which you'll learn about next.
+
+### Add Compensation Function to Step
+
+You define for each step a compensation function that's executed when an error occurs in the workflow. The compensation function defines the logic to roll-back the changes made by the step. This ensures your data remains consistent if an error occurs, which is especially useful when you integrate third-party services.
+
+Learn more about the compensation function in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/compensation-function/index.html.md).
+
+To add a compensation function to the `createBrandStep`, pass it as a third parameter to `createStep`:
+
+```ts title="src/workflows/create-brand.ts"
+export const createBrandStep = createStep(
+ // ...
+ async (id: string, { container }) => {
+ const brandModuleService: BrandModuleService = container.resolve(
+ BRAND_MODULE
+ )
+
+ await brandModuleService.deleteBrands(id)
+ }
+)
+```
+
+The compensation function's first parameter is the brand's ID which you passed as a second parameter to the step function's returned `StepResponse`. It also accepts a context object with a `container` property as a second parameter, similar to the step function.
+
+In the compensation function, you resolve the Brand Module's service from the Medusa container, then use its generated `deleteBrands` method to delete the brand created by the step. This method accepts the ID of the brand to delete.
+
+Learn more about the generated `delete` method's usage in [this reference](https://docs.medusajs.com/resources/service-factory-reference/methods/delete/index.html.md).
+
+So, if an error occurs during the workflow's execution, the brand that was created by the step is deleted to maintain data consistency.
+
+***
+
+## 2. Create createBrandWorkflow
+
+You can now create the workflow that runs the `createBrandStep`. A workflow is created in a TypeScript or JavaScript file under the `src/workflows` directory. In the file, you use `createWorkflow` from the Workflows SDK to create the workflow.
+
+Add the following content in the same `src/workflows/create-brand.ts` file:
+
+```ts title="src/workflows/create-brand.ts"
+// other imports...
+import {
+ // ...
+ createWorkflow,
+ WorkflowResponse,
+} from "@medusajs/framework/workflows-sdk"
+
+// ...
+
+type CreateBrandWorkflowInput = {
+ name: string
+}
+
+export const createBrandWorkflow = createWorkflow(
+ "create-brand",
+ (input: CreateBrandWorkflowInput) => {
+ const brand = createBrandStep(input)
+
+ return new WorkflowResponse(brand)
+ }
+)
+```
+
+You create the `createBrandWorkflow` using the `createWorkflow` function. This function accepts two parameters: the workflow's unique name, and the workflow's constructor function holding the workflow's implementation.
+
+The constructor function accepts the workflow's input as a parameter. In the function, you invoke the `createBrandStep` you created in the previous step to create a brand.
+
+A workflow must return an instance of `WorkflowResponse`. It accepts as a parameter the data to return to the workflow's executor.
+
+***
+
+## Next Steps: Expose Create Brand API Route
+
+You now have a `createBrandWorkflow` that you can execute to create a brand.
+
+In the next chapter, you'll add an API route that allows admin users to create a brand. You'll learn how to create the API route, and execute in it the workflow you implemented in this chapter.
+
+
+# Guide: Implement Brand Module
+
+In this chapter, you'll build a Brand Module that adds a `brand` table to the database and provides data-management features for it.
+
+A module is a reusable package of functionalities related to a single domain or integration. Medusa comes with multiple pre-built modules for core commerce needs, such as the [Cart Module](https://docs.medusajs.com/resources/commerce-modules/cart/index.html.md) that holds the data models and business logic for cart operations.
+
+In a module, you create data models and business logic to manage them. In the next chapters, you'll see how you use the module to build commerce features.
+
+Learn more about modules in [this chapter](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md).
+
+## 1. Create Module Directory
+
+Modules are created in a sub-directory of `src/modules`. So, start by creating the directory `src/modules/brand` that will hold the Brand Module's files.
+
+
+
+***
+
+## 2. Create Data Model
+
+A data model represents a table in the database. You create data models using Medusa's Data Model Language (DML). It simplifies defining a table's columns, relations, and indexes with straightforward methods and configurations.
+
+Learn more about data models in [this chapter](https://docs.medusajs.com/learn/fundamentals/modules#1-create-data-model/index.html.md).
+
+You create a data model in a TypeScript or JavaScript file under the `models` directory of a module. So, to create a data model that represents a new `brand` table in the database, create the file `src/modules/brand/models/brand.ts` with the following content:
+
+
+
+```ts title="src/modules/brand/models/brand.ts"
+import { model } from "@medusajs/framework/utils"
+
+export const Brand = model.define("brand", {
+ id: model.id().primaryKey(),
+ name: model.text(),
+})
+```
+
+You create a `Brand` data model which has an `id` primary key property, and a `name` text property.
+
+You define the data model using the `define` method of the DML. It accepts two parameters:
+
+1. The first one is the name of the data model's table in the database. Use snake-case names.
+2. The second is an object, which is the data model's schema.
+
+Learn about other property types in [this chapter](https://docs.medusajs.com/learn/fundamentals/data-models/properties/index.html.md).
+
+***
+
+## 3. Create Module Service
+
+You perform database operations on your data models in a service, which is a class exported by the module and acts like an interface to its functionalities.
+
+In this step, you'll create the Brand Module's service that provides methods to manage the `Brand` data model. In the next chapters, you'll use this service when exposing custom features that involve managing brands.
+
+Learn more about services in [this chapter](https://docs.medusajs.com/learn/fundamentals/modules#2-create-service/index.html.md).
+
+You define a service in a `service.ts` or `service.js` file at the root of your module's directory. So, create the file `src/modules/brand/service.ts` with the following content:
+
+
+
+```ts title="src/modules/brand/service.ts" highlights={serviceHighlights}
+import { MedusaService } from "@medusajs/framework/utils"
+import { Brand } from "./models/brand"
+
+class BrandModuleService extends MedusaService({
+ Brand,
+}) {
+
+}
+
+export default BrandModuleService
+```
+
+The `BrandModuleService` extends a class returned by `MedusaService` from the Modules SDK. This function generates a class with data-management methods for your module's data models.
+
+The `MedusaService` function receives an object of the module's data models as a parameter, and generates methods to manage those data models. So, the `BrandModuleService` now has methods like `createBrands` and `retrieveBrand` to manage the `Brand` data model.
+
+You'll use these methods in the [next chapter](https://docs.medusajs.com/learn/customization/custom-features/workflow/index.html.md).
+
+Find a reference of all generated methods in [this guide](https://docs.medusajs.com/resources/service-factory-reference/index.html.md).
+
+***
+
+## 4. Export Module Definition
+
+A module must export a definition that tells Medusa the name of the module and its main service. This definition is exported in an `index.ts` file at the module's root directory.
+
+So, to export the Brand Module's definition, create the file `src/modules/brand/index.ts` with the following content:
+
+
+
+```ts title="src/modules/brand/index.ts"
+import { Module } from "@medusajs/framework/utils"
+import BrandModuleService from "./service"
+
+export const BRAND_MODULE = "brand"
+
+export default Module(BRAND_MODULE, {
+ service: BrandModuleService,
+})
+```
+
+You use `Module` from the Modules SDK to create the module's definition. It accepts two parameters:
+
+1. The module's name (`brand`). You'll use this name when you use this module in other customizations.
+2. An object with a required property `service` indicating the module's main service.
+
+You export `BRAND_MODULE` to reference the module's name more reliably in other customizations.
+
+***
+
+## 5. Add Module to Medusa's Configurations
+
+To start using your module, you must add it to Medusa's configurations in `medusa-config.ts`.
+
+The object passed to `defineConfig` in `medusa-config.ts` accepts a `modules` property, whose value is an array of modules to add to the application. So, add the following in `medusa-config.ts`:
+
+```ts title="medusa-config.ts"
+module.exports = defineConfig({
+ // ...
+ modules: [
+ {
+ resolve: "./src/modules/brand",
+ },
+ ],
+})
+```
+
+The Brand Module is now added to your Medusa application. You'll start using it in the [next chapter](https://docs.medusajs.com/learn/customization/custom-features/workflow/index.html.md).
+
+***
+
+## 6. Generate and Run Migrations
+
+A migration is a TypeScript or JavaScript file that defines database changes made by a module. Migrations ensure that your module is re-usable and removes friction when working in a team, making it easy to reflect changes across team members' databases.
+
+Learn more about migrations in [this chapter](https://docs.medusajs.com/learn/fundamentals/modules#5-generate-migrations/index.html.md).
+
+[Medusa's CLI tool](https://docs.medusajs.com/resources/medusa-cli/index.html.md) allows you to generate migration files for your module, then run those migrations to reflect the changes in the database. So, run the following commands in your Medusa application's directory:
+
+```bash
+npx medusa db:generate brand
+npx medusa db:migrate
+```
+
+The `db:generate` command accepts as an argument the name of the module to generate the migrations for, and the `db:migrate` command runs all migrations that haven't been run yet in the Medusa application.
+
+***
+
+## Next Step: Create Brand Workflow
+
+The Brand Module now creates a `brand` table in the database and provides a class to manage its records.
+
+In the next chapter, you'll implement the functionality to create a brand in a workflow. You'll then use that workflow in a later chapter to expose an endpoint that allows admin users to create a brand.
+
+
+# Guide: Define Module Link Between Brand and Product
+
+In this chapter, you'll learn how to define a module link between a brand defined in the [custom Brand Module](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md), and a product defined in the [Product Module](https://docs.medusajs.com/resources/commerce-modules/product/index.html.md) that's available in your Medusa application out-of-the-box.
+
+Modules are [isolated](https://docs.medusajs.com/learn/fundamentals/modules/isolation/index.html.md) from other resources, ensuring that they're integrated into the Medusa application without side effects. However, you may need to associate data models of different modules, or you're trying to extend data models from commerce modules with custom properties. To do that, you define module links.
+
+A module link forms an association between two data models of different modules while maintaining module isolation. You can then manage and query linked records of the data models using Medusa's Modules SDK.
+
+In this chapter, you'll define a module link between the `Brand` data model of the Brand Module, and the `Product` data model of the Product Module. In later chapters, you'll manage and retrieve linked product and brand records.
+
+Learn more about module links in [this chapters](https://docs.medusajs.com/learn/fundamentals/module-links/index.html.md).
+
+### Prerequisites
+
+- [Brand Module having a Brand data model](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md)
+
+## 1. Define Link
+
+Links are defined in a TypeScript or JavaScript file under the `src/links` directory. The file defines and exports the link using `defineLink` from the Modules SDK.
+
+So, to define a link between the `Product` and `Brand` models, create the file `src/links/product-brand.ts` with the following content:
+
+
+
+```ts title="src/links/product-brand.ts" highlights={highlights}
+import BrandModule from "../modules/brand"
+import ProductModule from "@medusajs/medusa/product"
+import { defineLink } from "@medusajs/framework/utils"
+
+export default defineLink(
+ {
+ linkable: ProductModule.linkable.product,
+ isList: true,
+ },
+ BrandModule.linkable.brand
+)
+```
+
+You import each module's definition object from the `index.ts` file of the module's directory. Each module object has a special `linkable` property that holds the data models' link configurations.
+
+The `defineLink` function accepts two parameters of the same type, which is either:
+
+- The data model's link configuration, which you access from the Module's `linkable` property;
+- Or an object that has two properties:
+ - `linkable`: the data model's link configuration, which you access from the Module's `linkable` property.
+ - `isList`: A boolean indicating whether many records of the data model can be linked to the other model.
+
+So, in the above code snippet, you define a link between the `Product` and `Brand` data models. Since a brand can be associated with multiple products, you enable `isList` in the `Product` model's object.
+
+***
+
+## 2. Sync the Link to the Database
+
+A module link is represented in the database as a table that stores the IDs of linked records. So, after defining the link, run the following command to create the module link's table in the database:
+
+```bash
+npx medusa db:migrate
+```
+
+This command reflects migrations on the database and syncs module links, which creates a table for the `product-brand` link.
+
+You can also run the `npx medusa db:sync-links` to just sync module links without running migrations.
+
+***
+
+## Next Steps: Extend Create Product Flow
+
+In the next chapter, you'll extend Medusa's workflow and API route that create a product to allow associating a brand with a product. You'll also learn how to link brand and product records.
+
+
+# Guide: Extend Create Product Flow
+
+After linking the [custom Brand data model](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md) and Medusa's [Product Module](https://docs.medusajs.com/resources/commerce-modules/product/index.html.md) in the [previous chapter](https://docs.medusajs.com/learn/customization/extend-features/define-link/index.html.md), you'll extend the create product workflow and API route to allow associating a brand with a product.
+
+Some API routes, including the [Create Product API route](https://docs.medusajs.com/api/admin#products_postproducts), accept an `additional_data` request body parameter. This parameter can hold custom data that's passed to the [hooks](https://docs.medusajs.com/learn/fundamentals/workflows/workflow-hooks/index.html.md) of the workflow executed in the API route, allowing you to consume those hooks and perform actions with the custom data.
+
+So, in this chapter, to extend the create product flow and associate a brand with a product, you will:
+
+- Consume the [productsCreated](https://docs.medusajs.com/resources/references/medusa-workflows/createProductsWorkflow#productsCreated/index.html.md) hook of the [createProductsWorkflow](https://docs.medusajs.com/resources/references/medusa-workflows/createProductsWorkflow/index.html.md), which is executed within the workflow after the product is created. You'll link the product with the brand passed in the `additional_data` parameter.
+- Extend the Create Product API route to allow passing a brand ID in `additional_data`.
+
+To learn more about the `additional_data` property and the API routes that accept additional data, refer to [this chapter](https://docs.medusajs.com/learn/fundamentals/api-routes/additional-data/index.html.md).
+
+### Prerequisites
+
+- [Brand Module](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md)
+- [Defined link between the Brand and Product data models.](https://docs.medusajs.com/learn/customization/extend-features/define-link/index.html.md)
+
+***
+
+## 1. Consume the productsCreated Hook
+
+A workflow hook is a point in a workflow where you can inject a step to perform a custom functionality. Consuming a workflow hook allows you to extend the features of a workflow and, consequently, the API route that uses it.
+
+Learn more about the workflow hooks in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/workflow-hooks/index.html.md).
+
+The [createProductsWorkflow](https://docs.medusajs.com/resources/references/medusa-workflows/createProductsWorkflow/index.html.md) used in the [Create Product API route](https://docs.medusajs.com/api/admin#products_postproducts) has a `productsCreated` hook that runs after the product is created. You'll consume this hook to link the created product with the brand specified in the request parameters.
+
+To consume the `productsCreated` hook, create the file `src/workflows/hooks/created-product.ts` with the following content:
+
+
+
+```ts title="src/workflows/hooks/created-product.ts" highlights={hook1Highlights}
+import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
+import { StepResponse } from "@medusajs/framework/workflows-sdk"
+import { Modules } from "@medusajs/framework/utils"
+import { LinkDefinition } from "@medusajs/framework/types"
+import { BRAND_MODULE } from "../../modules/brand"
+import BrandModuleService from "../../modules/brand/service"
+
+createProductsWorkflow.hooks.productsCreated(
+ (async ({ products, additional_data }, { container }) => {
+ if (!additional_data?.brand_id) {
+ return new StepResponse([], [])
+ }
+
+ const brandModuleService: BrandModuleService = container.resolve(
+ BRAND_MODULE
+ )
+ // if the brand doesn't exist, an error is thrown.
+ await brandModuleService.retrieveBrand(additional_data.brand_id as string)
+
+ // TODO link brand to product
+ })
+)
+```
+
+Workflows have a special `hooks` property to access its hooks and consume them. Each hook, such as `productsCreated`, accepts a step function as a parameter. The step function accepts the following parameters:
+
+1. An object having an `additional_data` property, which is the custom data passed in the request body under `additional_data`. The object will also have properties passed from the workflow to the hook, which in this case is the `products` property that holds an array of the created products.
+2. An object of properties related to the step's context. It has a `container` property whose value is the [Medusa container](https://docs.medusajs.com/learn/fundamentals/medusa-container/index.html.md) to resolve framework and commerce tools.
+
+In the step, if a brand ID is passed in `additional_data`, you resolve the Brand Module's service and use its generated `retrieveBrand` method to retrieve the brand by its ID. The `retrieveBrand` method will throw an error if the brand doesn't exist.
+
+### Link Brand to Product
+
+Next, you want to create a link between the created products and the brand. To do so, you use Link, which is a class from the Modules SDK that provides methods to manage linked records.
+
+Learn more about Link in [this chapter](https://docs.medusajs.com/learn/fundamentals/module-links/link/index.html.md).
+
+To use Link in the `productsCreated` hook, replace the `TODO` with the following:
+
+```ts title="src/workflows/hooks/created-product.ts" highlights={hook2Highlights}
+const link = container.resolve("link")
+const logger = container.resolve("logger")
+
+const links: LinkDefinition[] = []
+
+for (const product of products) {
+ links.push({
+ [Modules.PRODUCT]: {
+ product_id: product.id,
+ },
+ [BRAND_MODULE]: {
+ brand_id: additional_data.brand_id,
+ },
+ })
+}
+
+await link.create(links)
+
+logger.info("Linked brand to products")
+
+return new StepResponse(links, links)
+```
+
+You resolve Link from the container. Then you loop over the created products to assemble an array of links to be created. After that, you pass the array of links to Link's `create` method, which will link the product and brand records.
+
+Each property in the link object is the name of a module, and its value is an object having a `{model_name}_id` property, where `{model_name}` is the snake-case name of the module's data model. Its value is the ID of the record to be linked. The link object's properties must be set in the same order as the link configurations passed to `defineLink`.
+
+
+
+Finally, you return an instance of `StepResponse` returning the created links.
+
+### Dismiss Links in Compensation
+
+You can pass as a second parameter of the hook a compensation function that undoes what the step did. It receives as a first parameter the returned `StepResponse`'s second parameter, and the step context object as a second parameter.
+
+To undo creating the links in the hook, pass the following compensation function as a second parameter to `productsCreated`:
+
+```ts title="src/workflows/hooks/created-product.ts"
+createProductsWorkflow.hooks.productsCreated(
+ // ...
+ (async (links, { container }) => {
+ if (!links?.length) {
+ return
+ }
+
+ const link = container.resolve("link")
+
+ await link.dismiss(links)
+ })
+)
+```
+
+In the compensation function, if the `links` parameter isn't empty, you resolve Link from the container and use its `dismiss` method. This method removes a link between two records. It accepts the same parameter as the `create` method.
+
+***
+
+## 2. Configure Additional Data Validation
+
+Now that you've consumed the `productsCreated` hook, you want to configure the `/admin/products` API route that creates a new product to accept a brand ID in its `additional_data` parameter.
+
+You configure the properties accepted in `additional_data` in the `src/api/middlewares.ts` that exports middleware configurations. So, create the file (or, if already existing, add to the file) `src/api/middlewares.ts` the following content:
+
+
+
+```ts title="src/api/middlewares.ts"
+import { defineMiddlewares } from "@medusajs/framework/http"
+import { z } from "zod"
+
+// ...
+
+export default defineMiddlewares({
+ routes: [
+ // ...
+ {
+ matcher: "/admin/products",
+ method: ["POST"],
+ additionalDataValidator: {
+ brand_id: z.string().optional(),
+ },
+ },
+ ],
+})
+```
+
+Objects in `routes` accept an `additionalDataValidator` property that configures the validation rules for custom properties passed in the `additional_data` request parameter. It accepts an object whose keys are custom property names, and their values are validation rules created using [Zod](https://zod.dev/).
+
+So, `POST` requests sent to `/admin/products` can now pass the ID of a brand in the `brand_id` property of `additional_data`.
+
+***
+
+## Test it Out
+
+To test it out, first, retrieve the authentication token of your admin user by sending a `POST` request to `/auth/user/emailpass`:
+
+```bash
+curl -X POST 'http://localhost:9000/auth/user/emailpass' \
+-H 'Content-Type: application/json' \
+--data-raw '{
+ "email": "admin@medusa-test.com",
+ "password": "supersecret"
+}'
+```
+
+Make sure to replace the email and password in the request body with your user's credentials.
+
+Then, send a `POST` request to `/admin/products` to create a product, and pass in the `additional_data` parameter a brand's ID:
+
+```bash
+curl -X POST 'http://localhost:9000/admin/products' \
+-H 'Content-Type: application/json' \
+-H 'Authorization: Bearer {token}' \
+--data '{
+ "title": "Product 1",
+ "options": [
+ {
+ "title": "Default option",
+ "values": ["Default option value"]
+ }
+ ],
+ "shipping_profile_id": "{shipping_profile_id}",
+ "additional_data": {
+ "brand_id": "{brand_id}"
+ }
+}'
+```
+
+Make sure to replace `{token}` with the token you received from the previous request, `shipping_profile_id` with the ID of a shipping profile in your application, and `{brand_id}` with the ID of a brand in your application. You can retrieve the ID of a shipping profile either from the Medusa Admin, or the [List Shipping Profiles API route](https://docs.medusajs.com/api/admin#shipping-profiles_getshippingprofiles).
+
+The request creates a product and returns it.
+
+In the Medusa application's logs, you'll find the message `Linked brand to products`, indicating that the workflow hook handler ran and linked the brand to the products.
+
+***
+
+## Next Steps: Query Linked Brands and Products
+
+Now that you've extending the create-product flow to link a brand to it, you want to retrieve the brand details of a product. You'll learn how to do so in the next chapter.
+
+
# Create Brands UI Route in Admin
In this chapter, you'll add a UI route to the admin dashboard that shows all [brands](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md) in a new page. You'll retrieve the brands from the server and display them in a table with pagination.
@@ -4736,212 +5915,152 @@ Your customizations often span across systems, where you need to retrieve data o
In the next chapters, you'll learn about the concepts that facilitate integrating third-party systems in your application. You'll integrate a dummy third-party system and sync the brands between it and the Medusa application.
-# Guide: Create Brand Workflow
+# Guide: Query Product's Brands
-This chapter builds on the work from the [previous chapter](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md) where you created a Brand Module.
+In the previous chapters, you [defined a link](https://docs.medusajs.com/learn/customization/extend-features/define-link/index.html.md) between the [custom Brand Module](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md) and Medusa's [Product Module](https://docs.medusajs.com/resources/commerce-modules/product/index.html.md), then [extended the create-product flow](https://docs.medusajs.com/learn/customization/extend-features/extend-create-product/index.html.md) to link a product to a brand.
-After adding custom modules to your application, you build commerce features around them using workflows. A workflow is a series of queries and actions, called steps, that complete a task spanning across modules. You construct a workflow similar to a regular function, but it's a special function that allows you to define roll-back logic, retry configurations, and more advanced features.
-
-The workflow you'll create in this chapter will use the Brand Module's service to implement the feature of creating a brand. In the [next chapter](https://docs.medusajs.com/learn/customization/custom-features/api-route/index.html.md), you'll expose an API route that allows admin users to create a brand, and you'll use this workflow in the route's implementation.
-
-Learn more about workflows in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md).
+In this chapter, you'll learn how to retrieve a product's brand (and vice-versa) in two ways: Using Medusa's existing API route, or in customizations, such as a custom API route.
### Prerequisites
- [Brand Module](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md)
+- [Defined link between the Brand and Product data models.](https://docs.medusajs.com/learn/customization/extend-features/define-link/index.html.md)
***
-## 1. Create createBrandStep
+## Approach 1: Retrieve Brands in Existing API Routes
-A workflow consists of a series of steps, each step created in a TypeScript or JavaScript file under the `src/workflows` directory. A step is defined using `createStep` from the Workflows SDK
+Medusa's existing API routes accept a `fields` query parameter that allows you to specify the fields and relations of a model to retrieve. So, when you send a request to the [List Products](https://docs.medusajs.com/api/admin#products_getproducts), [Get Product](https://docs.medusajs.com/api/admin#products_getproductsid), or any product-related store or admin routes that accept a `fields` query parameter, you can specify in this parameter to return the product's brands.
-The workflow you're creating in this guide has one step to create the brand. So, create the file `src/workflows/create-brand.ts` with the following content:
+Learn more about selecting fields and relations in the [API Reference](https://docs.medusajs.com/api/admin#select-fields-and-relations).
-
-
-```ts title="src/workflows/create-brand.ts"
-import {
- createStep,
- StepResponse,
-} from "@medusajs/framework/workflows-sdk"
-import { BRAND_MODULE } from "../modules/brand"
-import BrandModuleService from "../modules/brand/service"
-
-export type CreateBrandStepInput = {
- name: string
-}
-
-export const createBrandStep = createStep(
- "create-brand-step",
- async (input: CreateBrandStepInput, { container }) => {
- const brandModuleService: BrandModuleService = container.resolve(
- BRAND_MODULE
- )
-
- const brand = await brandModuleService.createBrands(input)
-
- return new StepResponse(brand, brand.id)
- }
-)
-```
-
-You create a `createBrandStep` using the `createStep` function. It accepts the step's unique name as a first parameter, and the step's function as a second parameter.
-
-The step function receives two parameters: input passed to the step when it's invoked, and an object of general context and configurations. This object has a `container` property, which is the Medusa container.
-
-The [Medusa container](https://docs.medusajs.com/learn/fundamentals/medusa-container/index.html.md) is a registry of framework and commerce tools accessible in your customizations, such as a workflow's step. The Medusa application registers the services of core and custom modules in the container, allowing you to resolve and use them.
-
-So, In the step function, you use the Medusa container to resolve the Brand Module's service and use its generated `createBrands` method, which accepts an object of brands to create.
-
-Learn more about the generated `create` method's usage in [this reference](https://docs.medusajs.com/resources/service-factory-reference/methods/create/index.html.md).
-
-A step must return an instance of `StepResponse`. Its first parameter is the data returned by the step, and the second is the data passed to the compensation function, which you'll learn about next.
-
-### Add Compensation Function to Step
-
-You define for each step a compensation function that's executed when an error occurs in the workflow. The compensation function defines the logic to roll-back the changes made by the step. This ensures your data remains consistent if an error occurs, which is especially useful when you integrate third-party services.
-
-Learn more about the compensation function in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/compensation-function/index.html.md).
-
-To add a compensation function to the `createBrandStep`, pass it as a third parameter to `createStep`:
-
-```ts title="src/workflows/create-brand.ts"
-export const createBrandStep = createStep(
- // ...
- async (id: string, { container }) => {
- const brandModuleService: BrandModuleService = container.resolve(
- BRAND_MODULE
- )
-
- await brandModuleService.deleteBrands(id)
- }
-)
-```
-
-The compensation function's first parameter is the brand's ID which you passed as a second parameter to the step function's returned `StepResponse`. It also accepts a context object with a `container` property as a second parameter, similar to the step function.
-
-In the compensation function, you resolve the Brand Module's service from the Medusa container, then use its generated `deleteBrands` method to delete the brand created by the step. This method accepts the ID of the brand to delete.
-
-Learn more about the generated `delete` method's usage in [this reference](https://docs.medusajs.com/resources/service-factory-reference/methods/delete/index.html.md).
-
-So, if an error occurs during the workflow's execution, the brand that was created by the step is deleted to maintain data consistency.
-
-***
-
-## 2. Create createBrandWorkflow
-
-You can now create the workflow that runs the `createBrandStep`. A workflow is created in a TypeScript or JavaScript file under the `src/workflows` directory. In the file, you use `createWorkflow` from the Workflows SDK to create the workflow.
-
-Add the following content in the same `src/workflows/create-brand.ts` file:
-
-```ts title="src/workflows/create-brand.ts"
-// other imports...
-import {
- // ...
- createWorkflow,
- WorkflowResponse,
-} from "@medusajs/framework/workflows-sdk"
-
-// ...
-
-type CreateBrandWorkflowInput = {
- name: string
-}
-
-export const createBrandWorkflow = createWorkflow(
- "create-brand",
- (input: CreateBrandWorkflowInput) => {
- const brand = createBrandStep(input)
-
- return new WorkflowResponse(brand)
- }
-)
-```
-
-You create the `createBrandWorkflow` using the `createWorkflow` function. This function accepts two parameters: the workflow's unique name, and the workflow's constructor function holding the workflow's implementation.
-
-The constructor function accepts the workflow's input as a parameter. In the function, you invoke the `createBrandStep` you created in the previous step to create a brand.
-
-A workflow must return an instance of `WorkflowResponse`. It accepts as a parameter the data to return to the workflow's executor.
-
-***
-
-## Next Steps: Expose Create Brand API Route
-
-You now have a `createBrandWorkflow` that you can execute to create a brand.
-
-In the next chapter, you'll add an API route that allows admin users to create a brand. You'll learn how to create the API route, and execute in it the workflow you implemented in this chapter.
-
-
-# Guide: Define Module Link Between Brand and Product
-
-In this chapter, you'll learn how to define a module link between a brand defined in the [custom Brand Module](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md), and a product defined in the [Product Module](https://docs.medusajs.com/resources/commerce-modules/product/index.html.md) that's available in your Medusa application out-of-the-box.
-
-Modules are [isolated](https://docs.medusajs.com/learn/fundamentals/modules/isolation/index.html.md) from other resources, ensuring that they're integrated into the Medusa application without side effects. However, you may need to associate data models of different modules, or you're trying to extend data models from commerce modules with custom properties. To do that, you define module links.
-
-A module link forms an association between two data models of different modules while maintaining module isolation. You can then manage and query linked records of the data models using Medusa's Modules SDK.
-
-In this chapter, you'll define a module link between the `Brand` data model of the Brand Module, and the `Product` data model of the Product Module. In later chapters, you'll manage and retrieve linked product and brand records.
-
-Learn more about module links in [this chapters](https://docs.medusajs.com/learn/fundamentals/module-links/index.html.md).
-
-### Prerequisites
-
-- [Brand Module having a Brand data model](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md)
-
-## 1. Define Link
-
-Links are defined in a TypeScript or JavaScript file under the `src/links` directory. The file defines and exports the link using `defineLink` from the Modules SDK.
-
-So, to define a link between the `Product` and `Brand` models, create the file `src/links/product-brand.ts` with the following content:
-
-
-
-```ts title="src/links/product-brand.ts" highlights={highlights}
-import BrandModule from "../modules/brand"
-import ProductModule from "@medusajs/medusa/product"
-import { defineLink } from "@medusajs/framework/utils"
-
-export default defineLink(
- {
- linkable: ProductModule.linkable.product,
- isList: true,
- },
- BrandModule.linkable.brand
-)
-```
-
-You import each module's definition object from the `index.ts` file of the module's directory. Each module object has a special `linkable` property that holds the data models' link configurations.
-
-The `defineLink` function accepts two parameters of the same type, which is either:
-
-- The data model's link configuration, which you access from the Module's `linkable` property;
-- Or an object that has two properties:
- - `linkable`: the data model's link configuration, which you access from the Module's `linkable` property.
- - `isList`: A boolean indicating whether many records of the data model can be linked to the other model.
-
-So, in the above code snippet, you define a link between the `Product` and `Brand` data models. Since a brand can be associated with multiple products, you enable `isList` in the `Product` model's object.
-
-***
-
-## 2. Sync the Link to the Database
-
-A module link is represented in the database as a table that stores the IDs of linked records. So, after defining the link, run the following command to create the module link's table in the database:
+For example, send the following request to retrieve the list of products with their brands:
```bash
-npx medusa db:migrate
+curl 'http://localhost:9000/admin/products?fields=+brand.*' \
+--header 'Authorization: Bearer {token}'
```
-This command reflects migrations on the database and syncs module links, which creates a table for the `product-brand` link.
+Make sure to replace `{token}` with your admin user's authentication token. Learn how to retrieve it in the [API reference](https://docs.medusajs.com/api/store#authentication).
-You can also run the `npx medusa db:sync-links` to just sync module links without running migrations.
+Any product that is linked to a brand will have a `brand` property in its object:
+
+```json title="Example Product Object"
+{
+ "id": "prod_123",
+ // ...
+ "brand": {
+ "id": "01JEB44M61BRM3ARM2RRMK7GJF",
+ "name": "Acme",
+ "created_at": "2024-12-05T09:59:08.737Z",
+ "updated_at": "2024-12-05T09:59:08.737Z",
+ "deleted_at": null
+ }
+}
+```
+
+By using the `fields` query parameter, you don't have to re-create existing API routes to get custom data models that you linked to core data models.
+
+### Limitations: Filtering by Brands in Existing API Routes
+
+While you can retrieve linked records using the `fields` query parameter of an existing API route, you can't filter by linked records.
+
+Instead, you'll have to create a custom API route that uses Query to retrieve linked records with filters, as explained in the [Query documentation](https://docs.medusajs.com/learn/fundamentals/module-links/query#apply-filters-and-pagination-on-linked-records/index.html.md).
***
-## Next Steps: Extend Create Product Flow
+## Approach 2: Use Query to Retrieve Linked Records
-In the next chapter, you'll extend Medusa's workflow and API route that create a product to allow associating a brand with a product. You'll also learn how to link brand and product records.
+You can also retrieve linked records using Query. Query allows you to retrieve data across modules with filters, pagination, and more. You can resolve Query from the Medusa container and use it in your API route or workflow.
+
+Learn more about Query in [this chapter](https://docs.medusajs.com/learn/fundamentals/module-links/query/index.html.md).
+
+For example, you can create an API route that retrieves brands and their products. If you followed the [Create Brands API route chapter](https://docs.medusajs.com/learn/customization/custom-features/api-route/index.html.md), you'll have the file `src/api/admin/brands/route.ts` with a `POST` API route. Add a new `GET` function to the same file:
+
+```ts title="src/api/admin/brands/route.ts" highlights={highlights}
+// other imports...
+import {
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+
+export const GET = async (
+ req: MedusaRequest,
+ res: MedusaResponse
+) => {
+ const query = req.scope.resolve("query")
+
+ const { data: brands } = await query.graph({
+ entity: "brand",
+ fields: ["*", "products.*"],
+ })
+
+ res.json({ brands })
+}
+```
+
+This adds a `GET` API route at `/admin/brands`. In the API route, you resolve Query from the Medusa container. Query has a `graph` method that runs a query to retrieve data. It accepts an object having the following properties:
+
+- `entity`: The data model's name as specified in the first parameter of `model.define`.
+- `fields`: An array of properties and relations to retrieve. You can pass:
+ - A property's name, such as `id`, or `*` for all properties.
+ - A relation or linked model's name, such as `products` (use the plural name since brands are linked to list of products). You suffix the name with `.*` to retrieve all its properties.
+
+`graph` returns an object having a `data` property, which is the retrieved brands. You return the brands in the response.
+
+### Test it Out
+
+To test the API route out, send a `GET` request to `/admin/brands`:
+
+```bash
+curl 'http://localhost:9000/admin/brands' \
+-H 'Authorization: Bearer {token}'
+```
+
+Make sure to replace `{token}` with your admin user's authentication token. Learn how to retrieve it in the [API reference](https://docs.medusajs.com/api/store#authentication).
+
+This returns the brands in your store with their linked products. For example:
+
+```json title="Example Response"
+{
+ "brands": [
+ {
+ "id": "123",
+ // ...
+ "products": [
+ {
+ "id": "prod_123",
+ // ...
+ }
+ ]
+ }
+ ]
+}
+```
+
+### Limitations: Filtering by Brand in Query
+
+While you can use Query to retrieve linked records, you can't filter by linked records.
+
+For an alternative approach, refer to the [Query documentation](https://docs.medusajs.com/learn/fundamentals/module-links/query#apply-filters-and-pagination-on-linked-records/index.html.md).
+
+***
+
+## Summary
+
+By following the examples of the previous chapters, you:
+
+- Defined a link between the Brand and Product modules's data models, allowing you to associate a product with a brand.
+- Extended the create-product workflow and route to allow setting the product's brand while creating the product.
+- Queried a product's brand, and vice versa.
+
+***
+
+## Next Steps: Customize Medusa Admin
+
+Clients, such as the Medusa Admin dashboard, can now use brand-related features, such as creating a brand or setting the brand of a product.
+
+In the next chapters, you'll learn how to customize the Medusa Admin to show a product's brand on its details page, and to show a new page with the list of brands in your store.
# Guide: Add Product's Brand Widget in Admin
@@ -5098,567 +6217,6 @@ The [Admin Components guides](https://docs.medusajs.com/resources/admin-componen
In the next chapter, you'll add a UI route that displays the list of brands in your application and allows admin users.
-# Guide: Query Product's Brands
-
-In the previous chapters, you [defined a link](https://docs.medusajs.com/learn/customization/extend-features/define-link/index.html.md) between the [custom Brand Module](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md) and Medusa's [Product Module](https://docs.medusajs.com/resources/commerce-modules/product/index.html.md), then [extended the create-product flow](https://docs.medusajs.com/learn/customization/extend-features/extend-create-product/index.html.md) to link a product to a brand.
-
-In this chapter, you'll learn how to retrieve a product's brand (and vice-versa) in two ways: Using Medusa's existing API route, or in customizations, such as a custom API route.
-
-### Prerequisites
-
-- [Brand Module](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md)
-- [Defined link between the Brand and Product data models.](https://docs.medusajs.com/learn/customization/extend-features/define-link/index.html.md)
-
-***
-
-## Approach 1: Retrieve Brands in Existing API Routes
-
-Medusa's existing API routes accept a `fields` query parameter that allows you to specify the fields and relations of a model to retrieve. So, when you send a request to the [List Products](https://docs.medusajs.com/api/admin#products_getproducts), [Get Product](https://docs.medusajs.com/api/admin#products_getproductsid), or any product-related store or admin routes that accept a `fields` query parameter, you can specify in this parameter to return the product's brands.
-
-Learn more about selecting fields and relations in the [API Reference](https://docs.medusajs.com/api/admin#select-fields-and-relations).
-
-For example, send the following request to retrieve the list of products with their brands:
-
-```bash
-curl 'http://localhost:9000/admin/products?fields=+brand.*' \
---header 'Authorization: Bearer {token}'
-```
-
-Make sure to replace `{token}` with your admin user's authentication token. Learn how to retrieve it in the [API reference](https://docs.medusajs.com/api/store#authentication).
-
-Any product that is linked to a brand will have a `brand` property in its object:
-
-```json title="Example Product Object"
-{
- "id": "prod_123",
- // ...
- "brand": {
- "id": "01JEB44M61BRM3ARM2RRMK7GJF",
- "name": "Acme",
- "created_at": "2024-12-05T09:59:08.737Z",
- "updated_at": "2024-12-05T09:59:08.737Z",
- "deleted_at": null
- }
-}
-```
-
-By using the `fields` query parameter, you don't have to re-create existing API routes to get custom data models that you linked to core data models.
-
-### Limitations: Filtering by Brands in Existing API Routes
-
-While you can retrieve linked records using the `fields` query parameter of an existing API route, you can't filter by linked records.
-
-Instead, you'll have to create a custom API route that uses Query to retrieve linked records with filters, as explained in the [Query documentation](https://docs.medusajs.com/learn/fundamentals/module-links/query#apply-filters-and-pagination-on-linked-records/index.html.md).
-
-***
-
-## Approach 2: Use Query to Retrieve Linked Records
-
-You can also retrieve linked records using Query. Query allows you to retrieve data across modules with filters, pagination, and more. You can resolve Query from the Medusa container and use it in your API route or workflow.
-
-Learn more about Query in [this chapter](https://docs.medusajs.com/learn/fundamentals/module-links/query/index.html.md).
-
-For example, you can create an API route that retrieves brands and their products. If you followed the [Create Brands API route chapter](https://docs.medusajs.com/learn/customization/custom-features/api-route/index.html.md), you'll have the file `src/api/admin/brands/route.ts` with a `POST` API route. Add a new `GET` function to the same file:
-
-```ts title="src/api/admin/brands/route.ts" highlights={highlights}
-// other imports...
-import {
- MedusaRequest,
- MedusaResponse,
-} from "@medusajs/framework/http"
-
-export const GET = async (
- req: MedusaRequest,
- res: MedusaResponse
-) => {
- const query = req.scope.resolve("query")
-
- const { data: brands } = await query.graph({
- entity: "brand",
- fields: ["*", "products.*"],
- })
-
- res.json({ brands })
-}
-```
-
-This adds a `GET` API route at `/admin/brands`. In the API route, you resolve Query from the Medusa container. Query has a `graph` method that runs a query to retrieve data. It accepts an object having the following properties:
-
-- `entity`: The data model's name as specified in the first parameter of `model.define`.
-- `fields`: An array of properties and relations to retrieve. You can pass:
- - A property's name, such as `id`, or `*` for all properties.
- - A relation or linked model's name, such as `products` (use the plural name since brands are linked to list of products). You suffix the name with `.*` to retrieve all its properties.
-
-`graph` returns an object having a `data` property, which is the retrieved brands. You return the brands in the response.
-
-### Test it Out
-
-To test the API route out, send a `GET` request to `/admin/brands`:
-
-```bash
-curl 'http://localhost:9000/admin/brands' \
--H 'Authorization: Bearer {token}'
-```
-
-Make sure to replace `{token}` with your admin user's authentication token. Learn how to retrieve it in the [API reference](https://docs.medusajs.com/api/store#authentication).
-
-This returns the brands in your store with their linked products. For example:
-
-```json title="Example Response"
-{
- "brands": [
- {
- "id": "123",
- // ...
- "products": [
- {
- "id": "prod_123",
- // ...
- }
- ]
- }
- ]
-}
-```
-
-### Limitations: Filtering by Brand in Query
-
-While you can use Query to retrieve linked records, you can't filter by linked records.
-
-For an alternative approach, refer to the [Query documentation](https://docs.medusajs.com/learn/fundamentals/module-links/query#apply-filters-and-pagination-on-linked-records/index.html.md).
-
-***
-
-## Summary
-
-By following the examples of the previous chapters, you:
-
-- Defined a link between the Brand and Product modules's data models, allowing you to associate a product with a brand.
-- Extended the create-product workflow and route to allow setting the product's brand while creating the product.
-- Queried a product's brand, and vice versa.
-
-***
-
-## Next Steps: Customize Medusa Admin
-
-Clients, such as the Medusa Admin dashboard, can now use brand-related features, such as creating a brand or setting the brand of a product.
-
-In the next chapters, you'll learn how to customize the Medusa Admin to show a product's brand on its details page, and to show a new page with the list of brands in your store.
-
-
-# Guide: Extend Create Product Flow
-
-After linking the [custom Brand data model](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md) and Medusa's [Product Module](https://docs.medusajs.com/resources/commerce-modules/product/index.html.md) in the [previous chapter](https://docs.medusajs.com/learn/customization/extend-features/define-link/index.html.md), you'll extend the create product workflow and API route to allow associating a brand with a product.
-
-Some API routes, including the [Create Product API route](https://docs.medusajs.com/api/admin#products_postproducts), accept an `additional_data` request body parameter. This parameter can hold custom data that's passed to the [hooks](https://docs.medusajs.com/learn/fundamentals/workflows/workflow-hooks/index.html.md) of the workflow executed in the API route, allowing you to consume those hooks and perform actions with the custom data.
-
-So, in this chapter, to extend the create product flow and associate a brand with a product, you will:
-
-- Consume the [productsCreated](https://docs.medusajs.com/resources/references/medusa-workflows/createProductsWorkflow#productsCreated/index.html.md) hook of the [createProductsWorkflow](https://docs.medusajs.com/resources/references/medusa-workflows/createProductsWorkflow/index.html.md), which is executed within the workflow after the product is created. You'll link the product with the brand passed in the `additional_data` parameter.
-- Extend the Create Product API route to allow passing a brand ID in `additional_data`.
-
-To learn more about the `additional_data` property and the API routes that accept additional data, refer to [this chapter](https://docs.medusajs.com/learn/fundamentals/api-routes/additional-data/index.html.md).
-
-### Prerequisites
-
-- [Brand Module](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md)
-- [Defined link between the Brand and Product data models.](https://docs.medusajs.com/learn/customization/extend-features/define-link/index.html.md)
-
-***
-
-## 1. Consume the productsCreated Hook
-
-A workflow hook is a point in a workflow where you can inject a step to perform a custom functionality. Consuming a workflow hook allows you to extend the features of a workflow and, consequently, the API route that uses it.
-
-Learn more about the workflow hooks in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/workflow-hooks/index.html.md).
-
-The [createProductsWorkflow](https://docs.medusajs.com/resources/references/medusa-workflows/createProductsWorkflow/index.html.md) used in the [Create Product API route](https://docs.medusajs.com/api/admin#products_postproducts) has a `productsCreated` hook that runs after the product is created. You'll consume this hook to link the created product with the brand specified in the request parameters.
-
-To consume the `productsCreated` hook, create the file `src/workflows/hooks/created-product.ts` with the following content:
-
-
-
-```ts title="src/workflows/hooks/created-product.ts" highlights={hook1Highlights}
-import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
-import { StepResponse } from "@medusajs/framework/workflows-sdk"
-import { Modules } from "@medusajs/framework/utils"
-import { LinkDefinition } from "@medusajs/framework/types"
-import { BRAND_MODULE } from "../../modules/brand"
-import BrandModuleService from "../../modules/brand/service"
-
-createProductsWorkflow.hooks.productsCreated(
- (async ({ products, additional_data }, { container }) => {
- if (!additional_data?.brand_id) {
- return new StepResponse([], [])
- }
-
- const brandModuleService: BrandModuleService = container.resolve(
- BRAND_MODULE
- )
- // if the brand doesn't exist, an error is thrown.
- await brandModuleService.retrieveBrand(additional_data.brand_id as string)
-
- // TODO link brand to product
- })
-)
-```
-
-Workflows have a special `hooks` property to access its hooks and consume them. Each hook, such as `productsCreated`, accepts a step function as a parameter. The step function accepts the following parameters:
-
-1. An object having an `additional_data` property, which is the custom data passed in the request body under `additional_data`. The object will also have properties passed from the workflow to the hook, which in this case is the `products` property that holds an array of the created products.
-2. An object of properties related to the step's context. It has a `container` property whose value is the [Medusa container](https://docs.medusajs.com/learn/fundamentals/medusa-container/index.html.md) to resolve framework and commerce tools.
-
-In the step, if a brand ID is passed in `additional_data`, you resolve the Brand Module's service and use its generated `retrieveBrand` method to retrieve the brand by its ID. The `retrieveBrand` method will throw an error if the brand doesn't exist.
-
-### Link Brand to Product
-
-Next, you want to create a link between the created products and the brand. To do so, you use Link, which is a class from the Modules SDK that provides methods to manage linked records.
-
-Learn more about Link in [this chapter](https://docs.medusajs.com/learn/fundamentals/module-links/link/index.html.md).
-
-To use Link in the `productsCreated` hook, replace the `TODO` with the following:
-
-```ts title="src/workflows/hooks/created-product.ts" highlights={hook2Highlights}
-const link = container.resolve("link")
-const logger = container.resolve("logger")
-
-const links: LinkDefinition[] = []
-
-for (const product of products) {
- links.push({
- [Modules.PRODUCT]: {
- product_id: product.id,
- },
- [BRAND_MODULE]: {
- brand_id: additional_data.brand_id,
- },
- })
-}
-
-await link.create(links)
-
-logger.info("Linked brand to products")
-
-return new StepResponse(links, links)
-```
-
-You resolve Link from the container. Then you loop over the created products to assemble an array of links to be created. After that, you pass the array of links to Link's `create` method, which will link the product and brand records.
-
-Each property in the link object is the name of a module, and its value is an object having a `{model_name}_id` property, where `{model_name}` is the snake-case name of the module's data model. Its value is the ID of the record to be linked. The link object's properties must be set in the same order as the link configurations passed to `defineLink`.
-
-
-
-Finally, you return an instance of `StepResponse` returning the created links.
-
-### Dismiss Links in Compensation
-
-You can pass as a second parameter of the hook a compensation function that undoes what the step did. It receives as a first parameter the returned `StepResponse`'s second parameter, and the step context object as a second parameter.
-
-To undo creating the links in the hook, pass the following compensation function as a second parameter to `productsCreated`:
-
-```ts title="src/workflows/hooks/created-product.ts"
-createProductsWorkflow.hooks.productsCreated(
- // ...
- (async (links, { container }) => {
- if (!links?.length) {
- return
- }
-
- const link = container.resolve("link")
-
- await link.dismiss(links)
- })
-)
-```
-
-In the compensation function, if the `links` parameter isn't empty, you resolve Link from the container and use its `dismiss` method. This method removes a link between two records. It accepts the same parameter as the `create` method.
-
-***
-
-## 2. Configure Additional Data Validation
-
-Now that you've consumed the `productsCreated` hook, you want to configure the `/admin/products` API route that creates a new product to accept a brand ID in its `additional_data` parameter.
-
-You configure the properties accepted in `additional_data` in the `src/api/middlewares.ts` that exports middleware configurations. So, create the file (or, if already existing, add to the file) `src/api/middlewares.ts` the following content:
-
-
-
-```ts title="src/api/middlewares.ts"
-import { defineMiddlewares } from "@medusajs/framework/http"
-import { z } from "zod"
-
-// ...
-
-export default defineMiddlewares({
- routes: [
- // ...
- {
- matcher: "/admin/products",
- method: ["POST"],
- additionalDataValidator: {
- brand_id: z.string().optional(),
- },
- },
- ],
-})
-```
-
-Objects in `routes` accept an `additionalDataValidator` property that configures the validation rules for custom properties passed in the `additional_data` request parameter. It accepts an object whose keys are custom property names, and their values are validation rules created using [Zod](https://zod.dev/).
-
-So, `POST` requests sent to `/admin/products` can now pass the ID of a brand in the `brand_id` property of `additional_data`.
-
-***
-
-## Test it Out
-
-To test it out, first, retrieve the authentication token of your admin user by sending a `POST` request to `/auth/user/emailpass`:
-
-```bash
-curl -X POST 'http://localhost:9000/auth/user/emailpass' \
--H 'Content-Type: application/json' \
---data-raw '{
- "email": "admin@medusa-test.com",
- "password": "supersecret"
-}'
-```
-
-Make sure to replace the email and password in the request body with your user's credentials.
-
-Then, send a `POST` request to `/admin/products` to create a product, and pass in the `additional_data` parameter a brand's ID:
-
-```bash
-curl -X POST 'http://localhost:9000/admin/products' \
--H 'Content-Type: application/json' \
--H 'Authorization: Bearer {token}' \
---data '{
- "title": "Product 1",
- "options": [
- {
- "title": "Default option",
- "values": ["Default option value"]
- }
- ],
- "shipping_profile_id": "{shipping_profile_id}",
- "additional_data": {
- "brand_id": "{brand_id}"
- }
-}'
-```
-
-Make sure to replace `{token}` with the token you received from the previous request, `shipping_profile_id` with the ID of a shipping profile in your application, and `{brand_id}` with the ID of a brand in your application. You can retrieve the ID of a shipping profile either from the Medusa Admin, or the [List Shipping Profiles API route](https://docs.medusajs.com/api/admin#shipping-profiles_getshippingprofiles).
-
-The request creates a product and returns it.
-
-In the Medusa application's logs, you'll find the message `Linked brand to products`, indicating that the workflow hook handler ran and linked the brand to the products.
-
-***
-
-## Next Steps: Query Linked Brands and Products
-
-Now that you've extending the create-product flow to link a brand to it, you want to retrieve the brand details of a product. You'll learn how to do so in the next chapter.
-
-
-# Write Tests for Modules
-
-In this chapter, you'll learn about `moduleIntegrationTestRunner` from Medusa's Testing Framework and how to use it to write integration tests for a module's main service.
-
-### Prerequisites
-
-- [Testing Tools Setup](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools/index.html.md)
-
-## moduleIntegrationTestRunner Utility
-
-`moduleIntegrationTestRunner` creates integration tests for a module. The integration tests run on a test Medusa application with only the specified module enabled.
-
-For example, assuming you have a `blog` module, create a test file at `src/modules/blog/__tests__/service.spec.ts`:
-
-```ts title="src/modules/blog/__tests__/service.spec.ts"
-import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
-import { BLOG_MODULE } from ".."
-import BlogModuleService from "../service"
-import Post from "../models/post"
-
-moduleIntegrationTestRunner({
- moduleName: BLOG_MODULE,
- moduleModels: [Post],
- resolve: "./src/modules/blog",
- testSuite: ({ service }) => {
- // TODO write tests
- },
-})
-
-jest.setTimeout(60 * 1000)
-```
-
-The `moduleIntegrationTestRunner` function accepts as a parameter an object with the following properties:
-
-- `moduleName`: The name of the module.
-- `moduleModels`: An array of models in the module. Refer to [this section](#write-tests-for-modules-without-data-models) if your module doesn't have data models.
-- `resolve`: The path to the module's directory.
-- `testSuite`: A function that defines the tests to run.
-
-The `testSuite` function accepts as a parameter an object having the `service` property, which is an instance of the module's main service.
-
-The type argument provided to the `moduleIntegrationTestRunner` function is used as the type of the `service` property.
-
-The tests in the `testSuite` function are written using [Jest](https://jestjs.io/).
-
-***
-
-## Run Tests
-
-Run the following command to run your module integration tests:
-
-```bash npm2yarn
-npm run test:integration:modules
-```
-
-If you don't have a `test:integration:modules` script in `package.json`, refer to the [Medusa Testing Tools chapter](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools#add-test-commands/index.html.md).
-
-This runs your Medusa application and runs the tests available in any `__tests__` directory under the `src/modules` directory.
-
-***
-
-## Pass Module Options
-
-If your module accepts options, you can set them using the `moduleOptions` property of the `moduleIntegrationTestRunner`'s parameter.
-
-For example:
-
-```ts
-import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
-import BlogModuleService from "../service"
-
-moduleIntegrationTestRunner({
- moduleOptions: {
- apiKey: "123",
- },
- // ...
-})
-```
-
-***
-
-## Write Tests for Modules without Data Models
-
-If your module doesn't have a data model, pass a dummy model in the `moduleModels` property.
-
-For example:
-
-```ts
-import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
-import BlogModuleService from "../service"
-import { model } from "@medusajs/framework/utils"
-
-const DummyModel = model.define("dummy_model", {
- id: model.id().primaryKey(),
-})
-
-moduleIntegrationTestRunner({
- moduleModels: [DummyModel],
- // ...
-})
-
-jest.setTimeout(60 * 1000)
-```
-
-***
-
-### Other Options and Inputs
-
-Refer to [the Test Tooling Reference](https://docs.medusajs.com/resources/test-tools-reference/moduleIntegrationTestRunner/index.html.md) for other available parameter options and inputs of the `testSuite` function.
-
-***
-
-## Database Used in Tests
-
-The `moduleIntegrationTestRunner` function creates a database with a random name before running the tests. Then, it drops that database after all the tests end.
-
-To manage that database, such as changing its name or perform operations on it in your tests, refer to [the Test Tooling Reference](https://docs.medusajs.com/resources/test-tools-reference/moduleIntegrationTestRunner/index.html.md).
-
-
-# Write Integration Tests
-
-In this chapter, you'll learn about `medusaIntegrationTestRunner` from Medusa's Testing Framework and how to use it to write integration tests.
-
-### Prerequisites
-
-- [Testing Tools Setup](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools/index.html.md)
-
-## medusaIntegrationTestRunner Utility
-
-The `medusaIntegrationTestRunner` is from Medusa's Testing Framework and it's used to create integration tests in your Medusa project. It runs a full Medusa application, allowing you test API routes, workflows, or other customizations.
-
-For example:
-
-```ts title="integration-tests/http/test.spec.ts" highlights={highlights}
-import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
-
-medusaIntegrationTestRunner({
- testSuite: ({ api, getContainer }) => {
- // TODO write tests...
- },
-})
-
-jest.setTimeout(60 * 1000)
-```
-
-The `medusaIntegrationTestRunner` function accepts an object as a parameter. The object has a required property `testSuite`.
-
-`testSuite`'s value is a function that defines the tests to run. The function accepts as a parameter an object that has the following properties:
-
-- `api`: a set of utility methods used to send requests to the Medusa application. It has the following methods:
- - `get`: Send a `GET` request to an API route.
- - `post`: Send a `POST` request to an API route.
- - `delete`: Send a `DELETE` request to an API route.
-- `getContainer`: a function that retrieves the Medusa Container. Use the `getContainer().resolve` method to resolve resources from the Medusa Container.
-
-The tests in the `testSuite` function are written using [Jest](https://jestjs.io/).
-
-### Jest Timeout
-
-Since your tests connect to the database and perform actions that require more time than the typical tests, make sure to increase the timeout in your test:
-
-```ts title="integration-tests/http/test.spec.ts"
-// in your test's file
-jest.setTimeout(60 * 1000)
-```
-
-***
-
-### Run Tests
-
-Run the following command to run your tests:
-
-```bash npm2yarn
-npm run test:integration
-```
-
-If you don't have a `test:integration` script in `package.json`, refer to the [Medusa Testing Tools chapter](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools#add-test-commands/index.html.md).
-
-This runs your Medusa application and runs the tests available under the `src/integrations/http` directory.
-
-***
-
-## Other Options and Inputs
-
-Refer to [the Test Tooling Reference](https://docs.medusajs.com/resources/test-tools-reference/medusaIntegrationTestRunner/index.html.md) for other available parameter options and inputs of the `testSuite` function.
-
-***
-
-## Database Used in Tests
-
-The `medusaIntegrationTestRunner` function creates a database with a random name before running the tests. Then, it drops that database after all the tests end.
-
-To manage that database, such as changing its name or perform operations on it in your tests, refer to [the Test Tooling Reference](https://docs.medusajs.com/resources/test-tools-reference/medusaIntegrationTestRunner/index.html.md).
-
-***
-
-## Example Integration Tests
-
-The next chapters provide examples of writing integration tests for API routes and workflows.
-
-
# Guide: Sync Brands from Medusa to Third-Party
In the [previous chapter](https://docs.medusajs.com/learn/customization/integrate-systems/service/index.html.md), you created a CMS Module that integrates a dummy third-party system. You can now perform actions using that module within your custom flows.
@@ -6240,194 +6798,6 @@ By following the previous chapters, you utilized Medusa's framework and orchestr
With Medusa, you can integrate any service from your commerce ecosystem with ease. You don't have to set up separate applications to manage your different customizations, or worry about data inconsistency across systems. Your efforts only go into implementing the business logic that ties your systems together.
-# Seed Data with Custom CLI Script
-
-In this chapter, you'll learn how to seed data using a custom CLI script.
-
-## How to Seed Data
-
-To seed dummy data for development or demo purposes, use a custom CLI script.
-
-In the CLI script, use your custom workflows or Medusa's existing workflows, which you can browse in [this reference](https://docs.medusajs.com/resources/medusa-workflows-reference/index.html.md), to seed data.
-
-### Example: Seed Dummy Products
-
-In this section, you'll follow an example of creating a custom CLI script that seeds fifty dummy products.
-
-First, install the [Faker](https://fakerjs.dev/) library to generate random data in your script:
-
-```bash npm2yarn
-npm install --save-dev @faker-js/faker
-```
-
-Then, create the file `src/scripts/demo-products.ts` with the following content:
-
-```ts title="src/scripts/demo-products.ts" highlights={highlights} collapsibleLines="1-12" expandButtonLabel="Show Imports"
-import { ExecArgs } from "@medusajs/framework/types"
-import { faker } from "@faker-js/faker"
-import {
- ContainerRegistrationKeys,
- Modules,
- ProductStatus,
-} from "@medusajs/framework/utils"
-import {
- createInventoryLevelsWorkflow,
- createProductsWorkflow,
-} from "@medusajs/medusa/core-flows"
-
-export default async function seedDummyProducts({
- container,
-}: ExecArgs) {
- const salesChannelModuleService = container.resolve(
- Modules.SALES_CHANNEL
- )
- const logger = container.resolve(
- ContainerRegistrationKeys.LOGGER
- )
- const query = container.resolve(
- ContainerRegistrationKeys.QUERY
- )
-
- const defaultSalesChannel = await salesChannelModuleService
- .listSalesChannels({
- name: "Default Sales Channel",
- })
-
- const sizeOptions = ["S", "M", "L", "XL"]
- const colorOptions = ["Black", "White"]
- const currency_code = "eur"
- const productsNum = 50
-
- // TODO seed products
-}
-```
-
-So far, in the script, you:
-
-- Resolve the Sales Channel Module's main service to retrieve the application's default sales channel. This is the sales channel the dummy products will be available in.
-- Resolve the Logger to log messages in the terminal, and Query to later retrieve data useful for the seeded products.
-- Initialize some default data to use when seeding the products next.
-
-Next, replace the `TODO` with the following:
-
-```ts title="src/scripts/demo-products.ts"
-const productsData = new Array(productsNum).fill(0).map((_, index) => {
- const title = faker.commerce.product() + "_" + index
- return {
- title,
- is_giftcard: true,
- description: faker.commerce.productDescription(),
- status: ProductStatus.PUBLISHED,
- options: [
- {
- title: "Size",
- values: sizeOptions,
- },
- {
- title: "Color",
- values: colorOptions,
- },
- ],
- images: [
- {
- url: faker.image.urlPlaceholder({
- text: title,
- }),
- },
- {
- url: faker.image.urlPlaceholder({
- text: title,
- }),
- },
- ],
- variants: new Array(10).fill(0).map((_, variantIndex) => ({
- title: `${title} ${variantIndex}`,
- sku: `variant-${variantIndex}${index}`,
- prices: new Array(10).fill(0).map((_, priceIndex) => ({
- currency_code,
- amount: 10 * priceIndex,
- })),
- options: {
- Size: sizeOptions[Math.floor(Math.random() * 3)],
- },
- })),
- shipping_profile_id: "sp_123",
- sales_channels: [
- {
- id: defaultSalesChannel[0].id,
- },
- ],
- }
-})
-
-// TODO seed products
-```
-
-You generate fifty products using the sales channel and variables you initialized, and using Faker for random data, such as the product's title or images.
-
-Then, replace the new `TODO` with the following:
-
-```ts title="src/scripts/demo-products.ts"
-const { result: products } = await createProductsWorkflow(container).run({
- input: {
- products: productsData,
- },
-})
-
-logger.info(`Seeded ${products.length} products.`)
-
-// TODO add inventory levels
-```
-
-You create the generated products using the `createProductsWorkflow` imported previously from `@medusajs/medusa/core-flows`. It accepts the product data as input, and returns the created products.
-
-Only thing left is to create inventory levels for the products. So, replace the last `TODO` with the following:
-
-```ts title="src/scripts/demo-products.ts"
-logger.info("Seeding inventory levels.")
-
-const { data: stockLocations } = await query.graph({
- entity: "stock_location",
- fields: ["id"],
-})
-
-const { data: inventoryItems } = await query.graph({
- entity: "inventory_item",
- fields: ["id"],
-})
-
-const inventoryLevels = inventoryItems.map((inventoryItem) => ({
- location_id: stockLocations[0].id,
- stocked_quantity: 1000000,
- inventory_item_id: inventoryItem.id,
-}))
-
-await createInventoryLevelsWorkflow(container).run({
- input: {
- inventory_levels: inventoryLevels,
- },
-})
-
-logger.info("Finished seeding inventory levels data.")
-```
-
-You use Query to retrieve the stock location, to use the first location in the application, and the inventory items.
-
-Then, you generate inventory levels for each inventory item, associating it with the first stock location.
-
-Finally, you use the `createInventoryLevelsWorkflow` from Medusa's core workflows to create the inventory levels.
-
-### Test Script
-
-To test out the script, run the following command in your project's directory:
-
-```bash
-npx medusa exec ./src/scripts/demo-products.ts
-```
-
-This seeds the products to your database. If you run your Medusa application and view the products in the dashboard, you'll find fifty new products.
-
-
# Guide: Integrate Third-Party Brand System
In the previous chapters, you've created a [Brand Module](https://docs.medusajs.com/learn/customization/custom-features/module/index.html.md) that adds brands to your application. In this chapter, you'll integrate a dummy Content-Management System (CMS) in a new module. The module's service will provide methods to retrieve and manage brands in the CMS. You'll later use this service to sync data from and to the CMS.
@@ -6587,6 +6957,207 @@ You can now use the CMS Module's service to perform actions on the third-party C
In the next chapter, you'll learn how to emit an event when a brand is created, then handle that event to sync the brand from Medusa to the third-party service.
+# Write Tests for Modules
+
+In this chapter, you'll learn about `moduleIntegrationTestRunner` from Medusa's Testing Framework and how to use it to write integration tests for a module's main service.
+
+### Prerequisites
+
+- [Testing Tools Setup](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools/index.html.md)
+
+## moduleIntegrationTestRunner Utility
+
+`moduleIntegrationTestRunner` creates integration tests for a module. The integration tests run on a test Medusa application with only the specified module enabled.
+
+For example, assuming you have a `blog` module, create a test file at `src/modules/blog/__tests__/service.spec.ts`:
+
+```ts title="src/modules/blog/__tests__/service.spec.ts"
+import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
+import { BLOG_MODULE } from ".."
+import BlogModuleService from "../service"
+import Post from "../models/post"
+
+moduleIntegrationTestRunner({
+ moduleName: BLOG_MODULE,
+ moduleModels: [Post],
+ resolve: "./src/modules/blog",
+ testSuite: ({ service }) => {
+ // TODO write tests
+ },
+})
+
+jest.setTimeout(60 * 1000)
+```
+
+The `moduleIntegrationTestRunner` function accepts as a parameter an object with the following properties:
+
+- `moduleName`: The name of the module.
+- `moduleModels`: An array of models in the module. Refer to [this section](#write-tests-for-modules-without-data-models) if your module doesn't have data models.
+- `resolve`: The path to the module's directory.
+- `testSuite`: A function that defines the tests to run.
+
+The `testSuite` function accepts as a parameter an object having the `service` property, which is an instance of the module's main service.
+
+The type argument provided to the `moduleIntegrationTestRunner` function is used as the type of the `service` property.
+
+The tests in the `testSuite` function are written using [Jest](https://jestjs.io/).
+
+***
+
+## Run Tests
+
+Run the following command to run your module integration tests:
+
+```bash npm2yarn
+npm run test:integration:modules
+```
+
+If you don't have a `test:integration:modules` script in `package.json`, refer to the [Medusa Testing Tools chapter](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools#add-test-commands/index.html.md).
+
+This runs your Medusa application and runs the tests available in any `__tests__` directory under the `src/modules` directory.
+
+***
+
+## Pass Module Options
+
+If your module accepts options, you can set them using the `moduleOptions` property of the `moduleIntegrationTestRunner`'s parameter.
+
+For example:
+
+```ts
+import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
+import BlogModuleService from "../service"
+
+moduleIntegrationTestRunner({
+ moduleOptions: {
+ apiKey: "123",
+ },
+ // ...
+})
+```
+
+***
+
+## Write Tests for Modules without Data Models
+
+If your module doesn't have a data model, pass a dummy model in the `moduleModels` property.
+
+For example:
+
+```ts
+import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
+import BlogModuleService from "../service"
+import { model } from "@medusajs/framework/utils"
+
+const DummyModel = model.define("dummy_model", {
+ id: model.id().primaryKey(),
+})
+
+moduleIntegrationTestRunner({
+ moduleModels: [DummyModel],
+ // ...
+})
+
+jest.setTimeout(60 * 1000)
+```
+
+***
+
+### Other Options and Inputs
+
+Refer to [the Test Tooling Reference](https://docs.medusajs.com/resources/test-tools-reference/moduleIntegrationTestRunner/index.html.md) for other available parameter options and inputs of the `testSuite` function.
+
+***
+
+## Database Used in Tests
+
+The `moduleIntegrationTestRunner` function creates a database with a random name before running the tests. Then, it drops that database after all the tests end.
+
+To manage that database, such as changing its name or perform operations on it in your tests, refer to [the Test Tooling Reference](https://docs.medusajs.com/resources/test-tools-reference/moduleIntegrationTestRunner/index.html.md).
+
+
+# Write Integration Tests
+
+In this chapter, you'll learn about `medusaIntegrationTestRunner` from Medusa's Testing Framework and how to use it to write integration tests.
+
+### Prerequisites
+
+- [Testing Tools Setup](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools/index.html.md)
+
+## medusaIntegrationTestRunner Utility
+
+The `medusaIntegrationTestRunner` is from Medusa's Testing Framework and it's used to create integration tests in your Medusa project. It runs a full Medusa application, allowing you test API routes, workflows, or other customizations.
+
+For example:
+
+```ts title="integration-tests/http/test.spec.ts" highlights={highlights}
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+
+medusaIntegrationTestRunner({
+ testSuite: ({ api, getContainer }) => {
+ // TODO write tests...
+ },
+})
+
+jest.setTimeout(60 * 1000)
+```
+
+The `medusaIntegrationTestRunner` function accepts an object as a parameter. The object has a required property `testSuite`.
+
+`testSuite`'s value is a function that defines the tests to run. The function accepts as a parameter an object that has the following properties:
+
+- `api`: a set of utility methods used to send requests to the Medusa application. It has the following methods:
+ - `get`: Send a `GET` request to an API route.
+ - `post`: Send a `POST` request to an API route.
+ - `delete`: Send a `DELETE` request to an API route.
+- `getContainer`: a function that retrieves the Medusa Container. Use the `getContainer().resolve` method to resolve resources from the Medusa Container.
+
+The tests in the `testSuite` function are written using [Jest](https://jestjs.io/).
+
+### Jest Timeout
+
+Since your tests connect to the database and perform actions that require more time than the typical tests, make sure to increase the timeout in your test:
+
+```ts title="integration-tests/http/test.spec.ts"
+// in your test's file
+jest.setTimeout(60 * 1000)
+```
+
+***
+
+### Run Tests
+
+Run the following command to run your tests:
+
+```bash npm2yarn
+npm run test:integration
+```
+
+If you don't have a `test:integration` script in `package.json`, refer to the [Medusa Testing Tools chapter](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools#add-test-commands/index.html.md).
+
+This runs your Medusa application and runs the tests available under the `src/integrations/http` directory.
+
+***
+
+## Other Options and Inputs
+
+Refer to [the Test Tooling Reference](https://docs.medusajs.com/resources/test-tools-reference/medusaIntegrationTestRunner/index.html.md) for other available parameter options and inputs of the `testSuite` function.
+
+***
+
+## Database Used in Tests
+
+The `medusaIntegrationTestRunner` function creates a database with a random name before running the tests. Then, it drops that database after all the tests end.
+
+To manage that database, such as changing its name or perform operations on it in your tests, refer to [the Test Tooling Reference](https://docs.medusajs.com/resources/test-tools-reference/medusaIntegrationTestRunner/index.html.md).
+
+***
+
+## Example Integration Tests
+
+The next chapters provide examples of writing integration tests for API routes and workflows.
+
+
# Admin Development Constraints
This chapter lists some constraints of admin widgets and UI routes.
@@ -6993,125 +7564,6 @@ The Medusa Admin dashboard can be displayed in languages other than English, whi
Learn how to add a new language translation for the Medusa Admin in [this guide](https://docs.medusajs.com/learn/resources/contribution-guidelines/admin-translations/index.html.md).
-# Admin Widgets
-
-In this chapter, you’ll learn more about widgets and how to use them.
-
-## What is an Admin Widget?
-
-The Medusa Admin dashboard's pages are customizable to insert widgets of custom content in pre-defined injection zones. You create these widgets as React components that allow admin users to perform custom actions.
-
-For example, you can add a widget on the product details page that allow admin users to sync products to a third-party service.
-
-***
-
-## How to Create a Widget?
-
-### Prerequisites
-
-- [Medusa application installed](https://docs.medusajs.com/learn/installation/index.html.md)
-
-You create a widget in a `.tsx` file under the `src/admin/widgets` directory. The file’s default export must be the widget, which is the React component that renders the custom content. The file must also export the widget’s configurations indicating where to insert the widget.
-
-For example, create the file `src/admin/widgets/product-widget.tsx` with the following content:
-
-
-
-```tsx title="src/admin/widgets/product-widget.tsx" highlights={widgetHighlights}
-import { defineWidgetConfig } from "@medusajs/admin-sdk"
-import { Container, Heading } from "@medusajs/ui"
-
-// The widget
-const ProductWidget = () => {
- return (
-
-
- Product Widget
-
-
- )
-}
-
-// The widget's configurations
-export const config = defineWidgetConfig({
- zone: "product.details.before",
-})
-
-export default ProductWidget
-```
-
-You export the `ProductWidget` component, which shows the heading `Product Widget`. In the widget, you use [Medusa UI](https://docs.medusajs.com/ui/index.html.md), a package that Medusa maintains to allow you to customize the dashboard with the same components used to build it.
-
-To export the widget's configurations, you use `defineWidgetConfig` from the Admin Extension SDK. It accepts as a parameter an object with the `zone` property, whose value is a string or an array of strings, each being the name of the zone to inject the widget into.
-
-In the example above, the widget is injected at the top of a product’s details.
-
-The widget component must be created as an arrow function.
-
-### Test the Widget
-
-To test out the widget, start the Medusa application:
-
-```bash npm2yarn
-npm run dev
-```
-
-Then, open a product’s details page. You’ll find your custom widget at the top of the page.
-
-***
-
-## Props Passed in Detail Pages
-
-Widgets that are injected into a details page receive a `data` prop, which is the main data of the details page.
-
-For example, a widget injected into the `product.details.before` zone receives the product's details in the `data` prop:
-
-```tsx title="src/admin/widgets/product-widget.tsx" highlights={detailHighlights}
-import { defineWidgetConfig } from "@medusajs/admin-sdk"
-import { Container, Heading } from "@medusajs/ui"
-import {
- DetailWidgetProps,
- AdminProduct,
-} from "@medusajs/framework/types"
-
-// The widget
-const ProductWidget = ({
- data,
-}: DetailWidgetProps) => {
- return (
-
-
-
- Product Widget {data.title}
-
-
-
- )
-}
-
-// The widget's configurations
-export const config = defineWidgetConfig({
- zone: "product.details.before",
-})
-
-export default ProductWidget
-```
-
-The props type is `DetailWidgetProps`, and it accepts as a type argument the expected type of `data`. For the product details page, it's `AdminProduct`.
-
-***
-
-## Injection Zone
-
-Refer to [this reference](https://docs.medusajs.com/resources/admin-widget-injection-zones/index.html.md) for the full list of injection zones and their props.
-
-***
-
-## Admin Components List
-
-To build admin customizations that match the Medusa Admin's designs and layouts, refer to [this guide](https://docs.medusajs.com/resources/admin-components/index.html.md) to find common components.
-
-
# Admin UI Routes
In this chapter, you’ll learn how to create a UI route in the admin dashboard.
@@ -7348,1191 +7800,123 @@ To build admin customizations that match the Medusa Admin's designs and layouts,
For more customizations related to routes, refer to the [Routing Customizations chapter](https://docs.medusajs.com/learn/fundamentals/admin/routing/index.html.md).
-# Data Model Database Index
+# Admin Widgets
-In this chapter, you’ll learn how to define a database index on a data model.
+In this chapter, you’ll learn more about widgets and how to use them.
-You can also define an index on a property as explained in the [Properties chapter](https://docs.medusajs.com/learn/fundamentals/data-models/properties#define-database-index-on-property/index.html.md).
+## What is an Admin Widget?
-## Define Database Index on Data Model
+The Medusa Admin dashboard's pages are customizable to insert widgets of custom content in pre-defined injection zones. You create these widgets as React components that allow admin users to perform custom actions.
-A data model has an `indexes` method that defines database indices on its properties.
-
-The index can be on multiple columns (composite index). For example:
-
-```ts highlights={dataModelIndexHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const MyCustom = model.define("my_custom", {
- id: model.id().primaryKey(),
- name: model.text(),
- age: model.number(),
-}).indexes([
- {
- on: ["name", "age"],
- },
-])
-
-export default MyCustom
-```
-
-The `indexes` method receives an array of indices as a parameter. Each index is an object with a required `on` property indicating the properties to apply the index on.
-
-In the above example, you define a composite index on the `name` and `age` properties.
-
-### Index Conditions
-
-An index can have conditions. For example:
-
-```ts highlights={conditionHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const MyCustom = model.define("my_custom", {
- id: model.id().primaryKey(),
- name: model.text(),
- age: model.number(),
-}).indexes([
- {
- on: ["name", "age"],
- where: {
- age: 30,
- },
- },
-])
-
-export default MyCustom
-```
-
-The index object passed to `indexes` accepts a `where` property whose value is an object of conditions. The object's key is a property's name, and its value is the condition on that property.
-
-In the example above, the composite index is created on the `name` and `age` properties when the `age`'s value is `30`.
-
-A property's condition can be a negation. For example:
-
-```ts highlights={negationHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const MyCustom = model.define("my_custom", {
- id: model.id().primaryKey(),
- name: model.text(),
- age: model.number().nullable(),
-}).indexes([
- {
- on: ["name", "age"],
- where: {
- age: {
- $ne: null,
- },
- },
- },
-])
-
-export default MyCustom
-```
-
-A property's value in `where` can be an object having a `$ne` property. `$ne`'s value indicates what the specified property's value shouldn't be.
-
-In the example above, the composite index is created on the `name` and `age` properties when `age`'s value is not `null`.
-
-### Unique Database Index
-
-The object passed to `indexes` accepts a `unique` property indicating that the created index must be a unique index.
-
-For example:
-
-```ts highlights={uniqueHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const MyCustom = model.define("my_custom", {
- id: model.id().primaryKey(),
- name: model.text(),
- age: model.number(),
-}).indexes([
- {
- on: ["name", "age"],
- unique: true,
- },
-])
-
-export default MyCustom
-```
-
-This creates a unique composite index on the `name` and `age` properties.
-
-
-# Add Data Model Check Constraints
-
-In this chapter, you'll learn how to add check constraints to your data model.
-
-## What is a Check Constraint?
-
-A check constraint is a condition that must be satisfied by records inserted into a database table, otherwise an error is thrown.
-
-For example, if you have a data model with a `price` property, you want to only allow positive number values. So, you add a check constraint that fails when inserting a record with a negative price value.
+For example, you can add a widget on the product details page that allow admin users to sync products to a third-party service.
***
-## How to Set a Check Constraint?
+## How to Create a Widget?
-To set check constraints on a data model, use the `checks` method. This method accepts an array of check constraints to apply on the data model.
+### Prerequisites
-For example, to set a check constraint on a `price` property that ensures its value can only be a positive number:
+- [Medusa application installed](https://docs.medusajs.com/learn/installation/index.html.md)
-```ts highlights={checks1Highlights}
-import { model } from "@medusajs/framework/utils"
+You create a widget in a `.tsx` file under the `src/admin/widgets` directory. The file’s default export must be the widget, which is the React component that renders the custom content. The file must also export the widget’s configurations indicating where to insert the widget.
-const CustomProduct = model.define("custom_product", {
- // ...
- price: model.bigNumber(),
-})
-.checks([
- (columns) => `${columns.price} >= 0`,
-])
-```
+For example, create the file `src/admin/widgets/product-widget.tsx` with the following content:
-The item passed in the array parameter of `checks` can be a callback function that accepts as a parameter an object whose keys are the names of the properties in the data model schema, and values the respective column name in the database.
+
-The function returns a string indicating the [SQL check constraint expression](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-CHECK-CONSTRAINTS). In the expression, use the `columns` parameter to access a property's column name.
+```tsx title="src/admin/widgets/product-widget.tsx" highlights={widgetHighlights}
+import { defineWidgetConfig } from "@medusajs/admin-sdk"
+import { Container, Heading } from "@medusajs/ui"
-You can also pass an object to the `checks` method:
-
-```ts highlights={checks2Highlights}
-import { model } from "@medusajs/framework/utils"
-
-const CustomProduct = model.define("custom_product", {
- // ...
- price: model.bigNumber(),
-})
-.checks([
- {
- name: "custom_product_price_check",
- expression: (columns) => `${columns.price} >= 0`,
- },
-])
-```
-
-The object accepts the following properties:
-
-- `name`: The check constraint's name.
-- `expression`: A function similar to the one that can be passed to the array. It accepts an object of columns and returns an [SQL check constraint expression](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-CHECK-CONSTRAINTS).
-
-***
-
-## Apply in Migrations
-
-After adding the check constraint, make sure to generate and run migrations if you already have the table in the database. Otherwise, the check constraint won't be reflected.
-
-To generate a migration for the data model's module then reflect it on the database, run the following command:
-
-```bash
-npx medusa db:generate custom_module
-npx medusa db:migrate
-```
-
-The first command generates the migration under the `migrations` directory of your module's directory, and the second reflects it on the database.
-
-
-# Infer Type of Data Model
-
-In this chapter, you'll learn how to infer the type of a data model.
-
-## How to Infer Type of Data Model?
-
-Consider you have a `Post` data model. You can't reference this data model in a type, such as a workflow input or service method output types, since it's a variable.
-
-Instead, Medusa provides `InferTypeOf` that transforms your data model to a type.
-
-For example:
-
-```ts
-import { InferTypeOf } from "@medusajs/framework/types"
-import { Post } from "../modules/blog/models/post" // relative path to the model
-
-export type Post = InferTypeOf
-```
-
-`InferTypeOf` accepts as a type argument the type of the data model.
-
-Since the `Post` data model is a variable, use the `typeof` operator to pass the data model as a type argument to `InferTypeOf`.
-
-You can now use the `Post` type to reference a data model in other types, such as in workflow inputs or service method outputs:
-
-```ts title="Example Service"
-// other imports...
-import { InferTypeOf } from "@medusajs/framework/types"
-import { Post } from "../models/post"
-
-type Post = InferTypeOf
-
-class BlogModuleService extends MedusaService({ Post }) {
- async doSomething(): Promise {
- // ...
- }
+// The widget
+const ProductWidget = () => {
+ return (
+
+
+ Product Widget
+
+
+ )
}
+
+// The widget's configurations
+export const config = defineWidgetConfig({
+ zone: "product.details.before",
+})
+
+export default ProductWidget
```
+You export the `ProductWidget` component, which shows the heading `Product Widget`. In the widget, you use [Medusa UI](https://docs.medusajs.com/ui/index.html.md), a package that Medusa maintains to allow you to customize the dashboard with the same components used to build it.
-# Manage Relationships
+To export the widget's configurations, you use `defineWidgetConfig` from the Admin Extension SDK. It accepts as a parameter an object with the `zone` property, whose value is a string or an array of strings, each being the name of the zone to inject the widget into.
-In this chapter, you'll learn how to manage relationships between data models when creating, updating, or retrieving records using the module's main service.
+In the example above, the widget is injected at the top of a product’s details.
-## Manage One-to-One Relationship
+The widget component must be created as an arrow function.
-### BelongsTo Side of One-to-One
+### Test the Widget
-When you create a record of a data model that belongs to another through a one-to-one relation, pass the ID of the other data model's record in the `{relation}_id` property, where `{relation}` is the name of the relation property.
+To test out the widget, start the Medusa application:
-For example, assuming you have the [User and Email data models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#one-to-one-relationship/index.html.md), set an email's user ID as follows:
-
-```ts highlights={belongsHighlights}
-// when creating an email
-const email = await helloModuleService.createEmails({
- // other properties...
- user_id: "123",
-})
-
-// when updating an email
-const email = await helloModuleService.updateEmails({
- id: "321",
- // other properties...
- user_id: "123",
-})
+```bash npm2yarn
+npm run dev
```
-In the example above, you pass the `user_id` property when creating or updating an email to specify the user it belongs to.
-
-### HasOne Side
-
-When you create a record of a data model that has one of another, pass the ID of the other data model's record in the relation property.
-
-For example, assuming you have the [User and Email data models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#one-to-one-relationship/index.html.md), set a user's email ID as follows:
-
-```ts highlights={hasOneHighlights}
-// when creating a user
-const user = await helloModuleService.createUsers({
- // other properties...
- email: "123",
-})
-
-// when updating a user
-const user = await helloModuleService.updateUsers({
- id: "321",
- // other properties...
- email: "123",
-})
-```
-
-In the example above, you pass the `email` property when creating or updating a user to specify the email it has.
+Then, open a product’s details page. You’ll find your custom widget at the top of the page.
***
-## Manage One-to-Many Relationship
-
-In a one-to-many relationship, you can only manage the associations from the `belongsTo` side.
-
-When you create a record of the data model on the `belongsTo` side, pass the ID of the other data model's record in the `{relation}_id` property, where `{relation}` is the name of the relation property.
-
-For example, assuming you have the [Product and Store data models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#one-to-many-relationship/index.html.md), set a product's store ID as follows:
-
-```ts highlights={manyBelongsHighlights}
-// when creating a product
-const product = await helloModuleService.createProducts({
- // other properties...
- store_id: "123",
-})
-
-// when updating a product
-const product = await helloModuleService.updateProducts({
- id: "321",
- // other properties...
- store_id: "123",
-})
-```
-
-In the example above, you pass the `store_id` property when creating or updating a product to specify the store it belongs to.
-
-***
-
-## Manage Many-to-Many Relationship
-
-If your many-to-many relation is represented with a [pivotEntity](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#many-to-many-with-custom-columns/index.html.md), refer to [this section](#manage-many-to-many-relationship-with-pivotentity) instead.
-
-### Create Associations
-
-When you create a record of a data model that has a many-to-many relationship to another data model, pass an array of IDs of the other data model's records in the relation property.
-
-For example, assuming you have the [Order and Product data models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#many-to-many-relationship/index.html.md), set the association between products and orders as follows:
-
-```ts highlights={manyHighlights}
-// when creating a product
-const product = await helloModuleService.createProducts({
- // other properties...
- orders: ["123", "321"],
-})
-
-// when creating an order
-const order = await helloModuleService.createOrders({
- id: "321",
- // other properties...
- products: ["123", "321"],
-})
-```
-
-In the example above, you pass the `orders` property when you create a product, and you pass the `products` property when you create an order.
-
-### Update Associations
-
-When you use the `update` methods generated by the service factory, you also pass an array of IDs as the relation property's value to add new associated records.
-
-However, this removes any existing associations to records whose IDs aren't included in the array.
-
-For example, assuming you have the [Order and Product data models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#many-to-many-relationship/index.html.md), you update the product's related orders as so:
-
-```ts
-const product = await helloModuleService.updateProducts({
- id: "123",
- // other properties...
- orders: ["321"],
-})
-```
-
-If the product was associated with an order, and you don't include that order's ID in the `orders` array, the association between the product and order is removed.
-
-So, to add a new association without removing existing ones, retrieve the product first to pass its associated orders when updating the product:
-
-```ts highlights={updateAssociationHighlights}
-const product = await helloModuleService.retrieveProduct(
- "123",
- {
- relations: ["orders"],
- }
-)
-
-const updatedProduct = await helloModuleService.updateProducts({
- id: product.id,
- // other properties...
- orders: [
- ...product.orders.map((order) => order.id),
- "321",
- ],
-})
-```
-
-This keeps existing associations between the product and orders, and adds a new one.
-
-***
-
-## Manage Many-to-Many Relationship with pivotEntity
-
-If your many-to-many relation is represented without a [pivotEntity](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#many-to-many-with-custom-columns/index.html.md), refer to [this section](#manage-many-to-many-relationship) instead.
-
-If you have a many-to-many relation with a `pivotEntity` specified, make sure to pass the data model representing the pivot table to [MedusaService](https://docs.medusajs.com/learn/fundamentals/modules/service-factory/index.html.md) that your module's service extends.
-
-For example, assuming you have the [Order, Product, and OrderProduct models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#many-to-many-with-custom-columns/index.html.md), add `OrderProduct` to `MedusaService`'s object parameter:
-
-```ts highlights={["4"]}
-class BlogModuleService extends MedusaService({
- Order,
- Product,
- OrderProduct,
-}) {}
-```
-
-This will generate Create, Read, Update and Delete (CRUD) methods for the `OrderProduct` data model, which you can use to create relations between orders and products and manage the extra columns in the pivot table.
-
-For example:
-
-```ts
-// create order-product association
-const orderProduct = await blogModuleService.createOrderProducts({
- order_id: "123",
- product_id: "123",
- metadata: {
- test: true,
- },
-})
-
-// update order-product association
-const orderProduct = await blogModuleService.updateOrderProducts({
- id: "123",
- metadata: {
- test: false,
- },
-})
-
-// delete order-product association
-await blogModuleService.deleteOrderProducts("123")
-```
-
-Since the `OrderProduct` data model belongs to the `Order` and `Product` data models, you can set its order and product as explained in the [one-to-many relationship section](#manage-one-to-many-relationship) using `order_id` and `product_id`.
-
-Refer to the [service factory reference](https://docs.medusajs.com/resources/service-factory-reference/index.html.md) for a full list of generated methods and their usages.
-
-***
-
-## Retrieve Records of Relation
-
-The `list`, `listAndCount`, and `retrieve` methods of a module's main service accept as a second parameter an object of options.
-
-To retrieve the records associated with a data model's records through a relationship, pass in the second parameter object a `relations` property whose value is an array of relationship names.
-
-For example, assuming you have the [Order and Product data models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#many-to-many-relationship/index.html.md), you retrieve a product's orders as follows:
-
-```ts highlights={retrieveHighlights}
-const product = await blogModuleService.retrieveProducts(
- "123",
- {
- relations: ["orders"],
- }
-)
-```
-
-In the example above, the retrieved product has an `orders` property, whose value is an array of orders associated with the product.
-
-
-# Data Model Properties
-
-In this chapter, you'll learn about the different property types you can use in a data model and how to configure a data model's properties.
-
-## Data Model's Default Properties
-
-By default, Medusa creates the following properties for every data model:
-
-- `created_at`: A [dateTime](#dateTime) property that stores when a record of the data model was created.
-- `updated_at`: A [dateTime](#dateTime) property that stores when a record of the data model was updated.
-- `deleted_at`: A [dateTime](#dateTime) property that stores when a record of the data model was deleted. When you soft-delete a record, Medusa sets the `deleted_at` property to the current date.
-
-***
-
-## Property Types
-
-This section covers the different property types you can define in a data model's schema using the `model` methods.
-
-### id
-
-The `id` method defines an automatically generated string ID property. The generated ID is a unique string that has a mix of letters and numbers.
-
-For example:
-
-```ts highlights={idHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- id: model.id(),
- // ...
-})
-
-export default Post
-```
-
-### text
-
-The `text` method defines a string property.
-
-For example:
-
-```ts highlights={textHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- name: model.text(),
- // ...
-})
-
-export default Post
-```
-
-### number
-
-The `number` method defines a number property.
-
-For example:
-
-```ts highlights={numberHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- age: model.number(),
- // ...
-})
-
-export default Post
-```
-
-### float
-
-This property is only available after [Medusa v2.1.2](https://github.com/medusajs/medusa/releases/tag/v2.1.2).
-
-The `float` method defines a number property that allows for values with decimal places.
-
-Use this property type when it's less important to have high precision for numbers with large decimal places. Alternatively, for higher percision, use the [bigNumber property](#bignumber).
-
-For example:
-
-```ts highlights={floatHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- rating: model.float(),
- // ...
-})
-
-export default Post
-```
-
-### bigNumber
-
-The `bigNumber` method defines a number property that expects large numbers, such as prices.
-
-Use this property type when it's important to have high precision for numbers with large decimal places. Alternatively, for less percision, use the [float property](#float).
-
-For example:
-
-```ts highlights={bigNumberHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- price: model.bigNumber(),
- // ...
-})
-
-export default Post
-```
-
-### boolean
-
-The `boolean` method defines a boolean property.
-
-For example:
-
-```ts highlights={booleanHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- hasAccount: model.boolean(),
- // ...
-})
-
-export default Post
-```
-
-### enum
-
-The `enum` method defines a property whose value can only be one of the specified values.
-
-For example:
-
-```ts highlights={enumHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- color: model.enum(["black", "white"]),
- // ...
-})
-
-export default Post
-```
-
-The `enum` method accepts an array of possible string values.
-
-### dateTime
-
-The `dateTime` method defines a timestamp property.
-
-For example:
-
-```ts highlights={dateTimeHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- date_of_birth: model.dateTime(),
- // ...
-})
-
-export default Post
-```
-
-### json
-
-The `json` method defines a property whose value is a stringified JSON object.
-
-For example:
-
-```ts highlights={jsonHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- metadata: model.json(),
- // ...
-})
-
-export default Post
-```
-
-### array
-
-The `array` method defines an array of strings property.
-
-For example:
-
-```ts highlights={arrHightlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- names: model.array(),
- // ...
-})
-
-export default Post
-```
-
-### Properties Reference
-
-Refer to the [Data Model Language (DML) reference](https://docs.medusajs.com/resources/references/data-model/index.html.md) for a full reference of the properties.
-
-***
-
-## Set Primary Key Property
-
-To set any `id`, `text`, or `number` property as a primary key, use the `primaryKey` method.
-
-For example:
-
-```ts highlights={highlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- id: model.id().primaryKey(),
- // ...
-})
-
-export default Post
-```
-
-In the example above, the `id` property is defined as the data model's primary key.
-
-***
-
-## Property Default Value
-
-Use the `default` method on a property's definition to specify the default value of a property.
-
-For example:
-
-```ts highlights={defaultHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- color: model
- .enum(["black", "white"])
- .default("black"),
- age: model
- .number()
- .default(0),
- // ...
-})
-
-export default Post
-```
-
-In this example, you set the default value of the `color` enum property to `black`, and that of the `age` number property to `0`.
-
-***
-
-## Make Property Optional
-
-Use the `nullable` method to indicate that a property’s value can be `null`. This is useful when you want a property to be optional.
-
-For example:
-
-```ts highlights={nullableHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- price: model.bigNumber().nullable(),
- // ...
-})
-
-export default Post
-```
-
-In the example above, the `price` property is configured to allow `null` values, making it optional.
-
-***
-
-## Unique Property
-
-The `unique` method indicates that a property’s value must be unique in the database through a unique index.
-
-For example:
-
-```ts highlights={uniqueHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const User = model.define("user", {
- email: model.text().unique(),
- // ...
-})
-
-export default User
-```
-
-In this example, multiple users can’t have the same email.
-
-***
-
-## Define Database Index on Property
-
-Use the `index` method on a property's definition to define a database index.
-
-For example:
-
-```ts highlights={dbIndexHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- id: model.id().primaryKey(),
- name: model.text().index(
- "IDX_MY_CUSTOM_NAME"
- ),
-})
-
-export default Post
-```
-
-The `index` method optionally accepts the name of the index as a parameter.
-
-In this example, you define an index on the `name` property.
-
-***
-
-## Define a Searchable Property
-
-Methods generated by the [service factory](https://docs.medusajs.com/learn/fundamentals/modules/service-factory/index.html.md) that accept filters, such as `list{ModelName}s`, accept a `q` property as part of the filters.
-
-When the `q` filter is passed, the data model's searchable properties are queried to find matching records.
-
-Use the `searchable` method on a `text` property to indicate that it's searchable.
-
-For example:
-
-```ts highlights={searchableHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Post = model.define("post", {
- title: model.text().searchable(),
- // ...
-})
-
-export default Post
-```
-
-In this example, the `title` property is searchable.
-
-### Search Example
-
-If you pass a `q` filter to the `listPosts` method:
-
-```ts
-const posts = await blogModuleService.listPosts({
- q: "New Products",
-})
-```
-
-This retrieves records that include `New Products` in their `title` property.
-
-
-# Data Model Relationships
-
-In this chapter, you’ll learn how to define relationships between data models in your module.
-
-## What is a Relationship Property?
-
-A relationship property defines an association in the database between two models. It's created using the Data Model Language (DML) methods, such as `hasOne` or `belongsTo`.
-
-When you generate a migration for these data models, the migrations include foreign key columns or pivot tables, based on the relationship's type.
-
-You want to create a relation between data models in the same module.
-
-You want to create a relationship between data models in different modules. Use module links instead.
-
-***
-
-## One-to-One Relationship
-
-A one-to-one relationship indicates that one record of a data model belongs to or is associated with another.
-
-To define a one-to-one relationship, create relationship properties in the data models using the following methods:
-
-1. `hasOne`: indicates that the model has one record of the specified model.
-2. `belongsTo`: indicates that the model belongs to one record of the specified model.
-
-For example:
-
-```ts highlights={oneToOneHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const User = model.define("user", {
- id: model.id().primaryKey(),
- email: model.hasOne(() => Email),
-})
-
-const Email = model.define("email", {
- id: model.id().primaryKey(),
- user: model.belongsTo(() => User, {
- mappedBy: "email",
- }),
-})
-```
-
-In the example above, a user has one email, and an email belongs to one user.
-
-The `hasOne` and `belongsTo` methods accept a function as the first parameter. The function returns the associated data model.
-
-The `belongsTo` method also requires passing as a second parameter an object with the property `mappedBy`. Its value is the name of the relationship property in the other data model.
-
-### Optional Relationship
-
-To make the relationship optional on the `hasOne` or `belongsTo` side, use the `nullable` method on either property as explained in [this chapter](https://docs.medusajs.com/learn/fundamentals/data-models/properties#make-property-optional/index.html.md).
-
-### One-sided One-to-One Relationship
-
-If the one-to-one relationship is only defined on one side, pass `undefined` to the `mappedBy` property in the `belongsTo` method.
-
-For example:
-
-```ts highlights={oneToOneUndefinedHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const User = model.define("user", {
- id: model.id().primaryKey(),
-})
-
-const Email = model.define("email", {
- id: model.id().primaryKey(),
- user: model.belongsTo(() => User, {
- mappedBy: undefined,
- }),
-})
-```
-
-### One-to-One Relationship in the Database
-
-When you generate the migrations of data models that have a one-to-one relationship, the migration adds to the table of the data model that has the `belongsTo` property:
-
-1. A column of the format `{relation_name}_id` to store the ID of the record of the related data model. For example, the `email` table will have a `user_id` column.
-2. A foreign key on the `{relation_name}_id` column to the table of the related data model.
-
-
-
-***
-
-## One-to-Many Relationship
-
-A one-to-many relationship indicates that one record of a data model has many records of another data model.
-
-To define a one-to-many relationship, create relationship properties in the data models using the following methods:
-
-1. `hasMany`: indicates that the model has more than one record of the specified model.
-2. `belongsTo`: indicates that the model belongs to one record of the specified model.
-
-For example:
-
-```ts highlights={oneToManyHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Store = model.define("store", {
- id: model.id().primaryKey(),
- products: model.hasMany(() => Product),
-})
-
-const Product = model.define("product", {
- id: model.id().primaryKey(),
- store: model.belongsTo(() => Store, {
- mappedBy: "products",
- }),
-})
-```
-
-In this example, a store has many products, but a product belongs to one store.
-
-### Optional Relationship
-
-To make the relationship optional on the `belongsTo` side, use the `nullable` method on the property as explained in [this chapter](https://docs.medusajs.com/learn/fundamentals/data-models/properties#make-property-optional/index.html.md).
-
-### One-to-Many Relationship in the Database
-
-When you generate the migrations of data models that have a one-to-many relationship, the migration adds to the table of the data model that has the `belongsTo` property:
-
-1. A column of the format `{relation_name}_id` to store the ID of the record of the related data model. For example, the `product` table will have a `store_id` column.
-2. A foreign key on the `{relation_name}_id` column to the table of the related data model.
-
-
-
-***
-
-## Many-to-Many Relationship
-
-A many-to-many relationship indicates that many records of a data model can be associated with many records of another data model.
-
-To define a many-to-many relationship, create relationship properties in the data models using the `manyToMany` method.
-
-For example:
-
-```ts highlights={manyToManyHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const Order = model.define("order", {
- id: model.id().primaryKey(),
- products: model.manyToMany(() => Product, {
- mappedBy: "orders",
- pivotTable: "order_product",
- joinColumn: "order_id",
- inverseJoinColumn: "product_id",
- }),
-})
-
-const Product = model.define("product", {
- id: model.id().primaryKey(),
- orders: model.manyToMany(() => Order, {
- mappedBy: "products",
- }),
-})
-```
-
-The `manyToMany` method accepts two parameters:
-
-1. A function that returns the associated data model.
-2. An object of optional configuration. Only one of the data models in the relation can define the `pivotTable`, `joinColumn`, and `inverseJoinColumn` configurations, and it's considered the owner data model. The object can accept the following properties:
- - `mappedBy`: The name of the relationship property in the other data model. If not set, the property's name is inferred from the associated data model's name.
- - `pivotTable`: The name of the pivot table created in the database for the many-to-many relation. If not set, the pivot table is inferred by combining the names of the data models' tables in alphabetical order, separating them by `_`, and pluralizing the last name. For example, `order_products`.
- - `joinColumn`: The name of the column in the pivot table that points to the owner model's primary key.
- - `inverseJoinColumn`: The name of the column in the pivot table that points to the owned model's primary key.
-
-The `pivotTable`, `joinColumn`, and `inverseJoinColumn` properties are only available after [Medusa v2.0.7](https://github.com/medusajs/medusa/releases/tag/v2.0.7).
-
-Following [Medusa v2.1.0](https://github.com/medusajs/medusa/releases/tag/v2.1.0), if `pivotTable`, `joinColumn`, and `inverseJoinColumn` aren't specified on either model, the owner is decided based on alphabetical order. So, in the example above, the `Order` data model would be the owner.
-
-In this example, an order is associated with many products, and a product is associated with many orders. Since the `pivotTable`, `joinColumn`, and `inverseJoinColumn` configurations are defined on the order, it's considered the owner data model.
-
-### Many-to-Many Relationship in the Database
-
-When you generate the migrations of data models that have a many-to-many relationship, the migration adds a new pivot table. Its name is either the name you specify in the `pivotTable` configuration or the inferred name combining the names of the data models' tables in alphabetical order, separating them by `_`, and pluralizing the last name. For example, `order_products`.
-
-The pivot table has a column with the name `{data_model}_id` for each of the data model's tables. It also has foreign keys on each of these columns to their respective tables.
-
-The pivot table has columns with foreign keys pointing to the primary key of the associated tables. The column's name is either:
-
-- The value of the `joinColumn` configuration for the owner table, and the `inverseJoinColumn` configuration for the owned table;
-- Or the inferred name `{table_name}_id`.
-
-
-
-### Many-To-Many with Custom Columns
-
-To add custom columns to the pivot table between two data models having a many-to-many relationship, you must define a new data model that represents the pivot table.
-
-For example:
-
-```ts highlights={manyToManyColumnHighlights}
-import { model } from "@medusajs/framework/utils"
-
-export const Order = model.define("order_test", {
- id: model.id().primaryKey(),
- products: model.manyToMany(() => Product, {
- pivotEntity: () => OrderProduct,
- }),
-})
-
-export const Product = model.define("product_test", {
- id: model.id().primaryKey(),
- orders: model.manyToMany(() => Order),
-})
-
-export const OrderProduct = model.define("orders_products", {
- id: model.id().primaryKey(),
- order: model.belongsTo(() => Order, {
- mappedBy: "products",
- }),
- product: model.belongsTo(() => Product, {
- mappedBy: "orders",
- }),
- metadata: model.json().nullable(),
-})
-```
-
-The `Order` and `Product` data models have a many-to-many relationship. To add extra columns to the created pivot table, you pass a `pivotEntity` option to the `products` relation in `Order` (since `Order` is the owner). The value of `pivotEntity` is a function that returns the data model representing the pivot table.
-
-The `OrderProduct` model defines, aside from the ID, the following properties:
-
-- `order`: A relation that indicates this model belongs to the `Order` data model. You set the `mappedBy` option to the many-to-many relation's name in the `Order` data model.
-- `product`: A relation that indicates this model belongs to the `Product` data model. You set the `mappedBy` option to the many-to-many relation's name in the `Product` data model.
-- `metadata`: An extra column to add to the pivot table of type `json`. You can add other columns as well to the model.
-
-***
-
-## Set Relationship Name in the Other Model
-
-The relationship property methods accept as a second parameter an object of options. The `mappedBy` property defines the name of the relationship in the other data model.
-
-This is useful if the relationship property’s name is different from that of the associated data model.
-
-As seen in previous examples, the `mappedBy` option is required for the `belongsTo` method.
-
-For example:
-
-```ts highlights={relationNameHighlights}
-import { model } from "@medusajs/framework/utils"
-
-const User = model.define("user", {
- id: model.id().primaryKey(),
- email: model.hasOne(() => Email, {
- mappedBy: "owner",
- }),
-})
-
-const Email = model.define("email", {
- id: model.id().primaryKey(),
- owner: model.belongsTo(() => User, {
- mappedBy: "email",
- }),
-})
-```
-
-In this example, you specify in the `User` data model’s relationship property that the name of the relationship in the `Email` data model is `owner`.
-
-***
-
-## Cascades
-
-When an operation is performed on a data model, such as record deletion, the relationship cascade specifies what related data model records should be affected by it.
-
-For example, if a store is deleted, its products should also be deleted.
-
-The `cascades` method used on a data model configures which child records an operation is cascaded to.
-
-For example:
-
-```ts highlights={highlights}
-import { model } from "@medusajs/framework/utils"
-
-const Store = model.define("store", {
- id: model.id().primaryKey(),
- products: model.hasMany(() => Product),
-})
-.cascades({
- delete: ["products"],
-})
-
-const Product = model.define("product", {
- id: model.id().primaryKey(),
- store: model.belongsTo(() => Store, {
- mappedBy: "products",
- }),
-})
-```
-
-The `cascades` method accepts an object. Its key is the operation’s name, such as `delete`. The value is an array of relationship property names that the operation is cascaded to.
-
-In the example above, when a store is deleted, its associated products are also deleted.
-
-
-# Migrations
-
-In this chapter, you'll learn what a migration is and how to generate a migration or write it manually.
-
-## What is a Migration?
-
-A migration is a TypeScript or JavaScript file that defines database changes made by a module. Migrations are useful when you re-use a module or you're working in a team, so that when one member of a team makes a database change, everyone else can reflect it on their side by running the migrations.
-
-The migration's file has a class with two methods:
-
-- The `up` method reflects changes on the database.
-- The `down` method reverts the changes made in the `up` method.
-
-***
-
-## Generate Migration
-
-Instead of you writing the migration manually, the Medusa CLI tool provides a [db:generate](https://docs.medusajs.com/resources/medusa-cli/commands/db#dbgenerate/index.html.md) command to generate a migration for a modules' data models.
-
-For example, assuming you have a `blog` Module, you can generate a migration for it by running the following command:
-
-```bash
-npx medusa db:generate blog
-```
-
-This generates a migration file under the `migrations` directory of the Blog Module. You can then run it to reflect the changes in the database as mentioned in [this section](#run-the-migration).
-
-***
-
-## Write a Migration Manually
-
-You can also write migrations manually. To do that, create a file in the `migrations` directory of the module and in it, a class that has an `up` and `down` method. The class's name should be of the format `Migration{YEAR}{MONTH}{DAY}{HOUR}{MINUTE}.ts` to ensure migrations are ran in the correct order.
-
-For example:
-
-```ts title="src/modules/blog/migrations/Migration202507021059.ts"
-import { Migration } from "@mikro-orm/migrations"
-
-export class Migration202507021059 extends Migration {
-
- async up(): Promise {
- this.addSql("create table if not exists \"author\" (\"id\" text not null, \"name\" text not null, \"created_at\" timestamptz not null default now(), \"updated_at\" timestamptz not null default now(), \"deleted_at\" timestamptz null, constraint \"author_pkey\" primary key (\"id\"));")
- }
-
- async down(): Promise {
- this.addSql("drop table if exists \"author\" cascade;")
- }
-
+## Props Passed in Detail Pages
+
+Widgets that are injected into a details page receive a `data` prop, which is the main data of the details page.
+
+For example, a widget injected into the `product.details.before` zone receives the product's details in the `data` prop:
+
+```tsx title="src/admin/widgets/product-widget.tsx" highlights={detailHighlights}
+import { defineWidgetConfig } from "@medusajs/admin-sdk"
+import { Container, Heading } from "@medusajs/ui"
+import {
+ DetailWidgetProps,
+ AdminProduct,
+} from "@medusajs/framework/types"
+
+// The widget
+const ProductWidget = ({
+ data,
+}: DetailWidgetProps) => {
+ return (
+
+
+
+ Product Widget {data.title}
+
+
+
+ )
}
+
+// The widget's configurations
+export const config = defineWidgetConfig({
+ zone: "product.details.before",
+})
+
+export default ProductWidget
```
-The migration class in the file extends the `Migration` class imported from `@mikro-orm/migrations`. In the `up` and `down` method of the migration class, you use the `addSql` method provided by MikroORM's `Migration` class to run PostgreSQL syntax.
-
-In the example above, the `up` method creates the table `author`, and the `down` method drops the table if the migration is reverted.
-
-Refer to [MikroORM's documentation](https://mikro-orm.io/docs/migrations#migration-class) for more details on writing migrations.
+The props type is `DetailWidgetProps`, and it accepts as a type argument the expected type of `data`. For the product details page, it's `AdminProduct`.
***
-## Run the Migration
+## Injection Zone
-To run your migration, run the following command:
-
-This command also syncs module links. If you don't want that, use the `--skip-links` option.
-
-```bash
-npx medusa db:migrate
-```
-
-This reflects the changes in the database as implemented in the migration's `up` method.
+Refer to [this reference](https://docs.medusajs.com/resources/admin-widget-injection-zones/index.html.md) for the full list of injection zones and their props.
***
-## Rollback the Migration
+## Admin Components List
-To rollback or revert the last migration you ran for a module, run the following command:
-
-```bash
-npx medusa db:rollback blog
-```
-
-This rolls back the last ran migration on the Blog Module.
-
-### Caution: Rollback Migration before Deleting
-
-If you need to delete a migration file, make sure to rollback the migration first. Otherwise, you might encounter issues when generating and running new migrations.
-
-For example, if you delete the migration of the Blog Module, then try to create a new one, Medusa will create a brand new migration that re-creates the tables or indices. If those are still in the database, you might encounter errors.
-
-So, always rollback the migration before deleting it.
-
-***
-
-## More Database Commands
-
-To learn more about the Medusa CLI's database commands, refer to [this CLI reference](https://docs.medusajs.com/resources/medusa-cli/commands/db/index.html.md).
+To build admin customizations that match the Medusa Admin's designs and layouts, refer to [this guide](https://docs.medusajs.com/resources/admin-components/index.html.md) to find common components.
# Pass Additional Data to Medusa's API Route
@@ -8734,6 +8118,301 @@ createProductsWorkflow.hooks.productsCreated(
This updates the products to their original state before adding the brand to their `metadata` property.
+# Seed Data with Custom CLI Script
+
+In this chapter, you'll learn how to seed data using a custom CLI script.
+
+## How to Seed Data
+
+To seed dummy data for development or demo purposes, use a custom CLI script.
+
+In the CLI script, use your custom workflows or Medusa's existing workflows, which you can browse in [this reference](https://docs.medusajs.com/resources/medusa-workflows-reference/index.html.md), to seed data.
+
+### Example: Seed Dummy Products
+
+In this section, you'll follow an example of creating a custom CLI script that seeds fifty dummy products.
+
+First, install the [Faker](https://fakerjs.dev/) library to generate random data in your script:
+
+```bash npm2yarn
+npm install --save-dev @faker-js/faker
+```
+
+Then, create the file `src/scripts/demo-products.ts` with the following content:
+
+```ts title="src/scripts/demo-products.ts" highlights={highlights} collapsibleLines="1-12" expandButtonLabel="Show Imports"
+import { ExecArgs } from "@medusajs/framework/types"
+import { faker } from "@faker-js/faker"
+import {
+ ContainerRegistrationKeys,
+ Modules,
+ ProductStatus,
+} from "@medusajs/framework/utils"
+import {
+ createInventoryLevelsWorkflow,
+ createProductsWorkflow,
+} from "@medusajs/medusa/core-flows"
+
+export default async function seedDummyProducts({
+ container,
+}: ExecArgs) {
+ const salesChannelModuleService = container.resolve(
+ Modules.SALES_CHANNEL
+ )
+ const logger = container.resolve(
+ ContainerRegistrationKeys.LOGGER
+ )
+ const query = container.resolve(
+ ContainerRegistrationKeys.QUERY
+ )
+
+ const defaultSalesChannel = await salesChannelModuleService
+ .listSalesChannels({
+ name: "Default Sales Channel",
+ })
+
+ const sizeOptions = ["S", "M", "L", "XL"]
+ const colorOptions = ["Black", "White"]
+ const currency_code = "eur"
+ const productsNum = 50
+
+ // TODO seed products
+}
+```
+
+So far, in the script, you:
+
+- Resolve the Sales Channel Module's main service to retrieve the application's default sales channel. This is the sales channel the dummy products will be available in.
+- Resolve the Logger to log messages in the terminal, and Query to later retrieve data useful for the seeded products.
+- Initialize some default data to use when seeding the products next.
+
+Next, replace the `TODO` with the following:
+
+```ts title="src/scripts/demo-products.ts"
+const productsData = new Array(productsNum).fill(0).map((_, index) => {
+ const title = faker.commerce.product() + "_" + index
+ return {
+ title,
+ is_giftcard: true,
+ description: faker.commerce.productDescription(),
+ status: ProductStatus.PUBLISHED,
+ options: [
+ {
+ title: "Size",
+ values: sizeOptions,
+ },
+ {
+ title: "Color",
+ values: colorOptions,
+ },
+ ],
+ images: [
+ {
+ url: faker.image.urlPlaceholder({
+ text: title,
+ }),
+ },
+ {
+ url: faker.image.urlPlaceholder({
+ text: title,
+ }),
+ },
+ ],
+ variants: new Array(10).fill(0).map((_, variantIndex) => ({
+ title: `${title} ${variantIndex}`,
+ sku: `variant-${variantIndex}${index}`,
+ prices: new Array(10).fill(0).map((_, priceIndex) => ({
+ currency_code,
+ amount: 10 * priceIndex,
+ })),
+ options: {
+ Size: sizeOptions[Math.floor(Math.random() * 3)],
+ },
+ })),
+ shipping_profile_id: "sp_123",
+ sales_channels: [
+ {
+ id: defaultSalesChannel[0].id,
+ },
+ ],
+ }
+})
+
+// TODO seed products
+```
+
+You generate fifty products using the sales channel and variables you initialized, and using Faker for random data, such as the product's title or images.
+
+Then, replace the new `TODO` with the following:
+
+```ts title="src/scripts/demo-products.ts"
+const { result: products } = await createProductsWorkflow(container).run({
+ input: {
+ products: productsData,
+ },
+})
+
+logger.info(`Seeded ${products.length} products.`)
+
+// TODO add inventory levels
+```
+
+You create the generated products using the `createProductsWorkflow` imported previously from `@medusajs/medusa/core-flows`. It accepts the product data as input, and returns the created products.
+
+Only thing left is to create inventory levels for the products. So, replace the last `TODO` with the following:
+
+```ts title="src/scripts/demo-products.ts"
+logger.info("Seeding inventory levels.")
+
+const { data: stockLocations } = await query.graph({
+ entity: "stock_location",
+ fields: ["id"],
+})
+
+const { data: inventoryItems } = await query.graph({
+ entity: "inventory_item",
+ fields: ["id"],
+})
+
+const inventoryLevels = inventoryItems.map((inventoryItem) => ({
+ location_id: stockLocations[0].id,
+ stocked_quantity: 1000000,
+ inventory_item_id: inventoryItem.id,
+}))
+
+await createInventoryLevelsWorkflow(container).run({
+ input: {
+ inventory_levels: inventoryLevels,
+ },
+})
+
+logger.info("Finished seeding inventory levels data.")
+```
+
+You use Query to retrieve the stock location, to use the first location in the application, and the inventory items.
+
+Then, you generate inventory levels for each inventory item, associating it with the first stock location.
+
+Finally, you use the `createInventoryLevelsWorkflow` from Medusa's core workflows to create the inventory levels.
+
+### Test Script
+
+To test out the script, run the following command in your project's directory:
+
+```bash
+npx medusa exec ./src/scripts/demo-products.ts
+```
+
+This seeds the products to your database. If you run your Medusa application and view the products in the dashboard, you'll find fifty new products.
+
+
+# Throwing and Handling Errors
+
+In this guide, you'll learn how to throw errors in your Medusa application, how it affects an API route's response, and how to change the default error handler of your Medusa application.
+
+## Throw MedusaError
+
+When throwing an error in your API routes, middlewares, workflows, or any customization, throw a `MedusaError` from the Medusa Framework.
+
+The Medusa application's API route error handler then wraps your thrown error in a uniform object and returns it in the response.
+
+For example:
+
+```ts
+import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { MedusaError } from "@medusajs/framework/utils"
+
+export const GET = async (
+ req: MedusaRequest,
+ res: MedusaResponse
+) => {
+ if (!req.query.q) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ "The `q` query parameter is required."
+ )
+ }
+
+ // ...
+}
+```
+
+The `MedusaError` class accepts in its constructor two parameters:
+
+1. The first is the error's type. `MedusaError` has a static property `Types` that you can use. `Types` is an enum whose possible values are explained in the next section.
+2. The second is the message to show in the error response.
+
+### Error Object in Response
+
+The error object returned in the response has two properties:
+
+- `type`: The error's type.
+- `message`: The error message, if available.
+- `code`: A common snake-case code. Its values can be:
+ - `invalid_request_error` for the `DUPLICATE_ERROR` type.
+ - `api_error`: for the `DB_ERROR` type.
+ - `invalid_state_error` for `CONFLICT` error type.
+ - `unknown_error` for any unidentified error type.
+ - For other error types, this property won't be available unless you provide a code as a third parameter to the `MedusaError` constructor.
+
+### MedusaError Types
+
+|Type|Description|Status Code|
+|---|---|---|---|---|
+|\`DB\_ERROR\`|Indicates a database error.|\`500\`|
+|\`DUPLICATE\_ERROR\`|Indicates a duplicate of a record already exists. For example, when trying to create a customer whose email is registered by another customer.|\`422\`|
+|\`INVALID\_ARGUMENT\`|Indicates an error that occurred due to incorrect arguments or other unexpected state.|\`500\`|
+|\`INVALID\_DATA\`|Indicates a validation error.|\`400\`|
+|\`UNAUTHORIZED\`|Indicates that a user is not authorized to perform an action or access a route.|\`401\`|
+|\`NOT\_FOUND\`|Indicates that the requested resource, such as a route or a record, isn't found.|\`404\`|
+|\`NOT\_ALLOWED\`|Indicates that an operation isn't allowed.|\`400\`|
+|\`CONFLICT\`|Indicates that a request conflicts with another previous or ongoing request. The error message in this case is ignored for a default message.|\`409\`|
+|\`PAYMENT\_AUTHORIZATION\_ERROR\`|Indicates an error has occurred while authorizing a payment.|\`422\`|
+|Other error types|Any other error type results in an |\`500\`|
+
+***
+
+## Override Error Handler
+
+The `defineMiddlewares` function used to apply middlewares on routes accepts an `errorHandler` in its object parameter. Use it to override the default error handler for API routes.
+
+This error handler will also be used for errors thrown in Medusa's API routes and resources.
+
+For example, create `src/api/middlewares.ts` with the following:
+
+```ts title="src/api/middlewares.ts" collapsibleLines="1-8" expandMoreLabel="Show Imports"
+import {
+ defineMiddlewares,
+ MedusaNextFunction,
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { MedusaError } from "@medusajs/framework/utils"
+
+export default defineMiddlewares({
+ errorHandler: (
+ error: MedusaError | any,
+ req: MedusaRequest,
+ res: MedusaResponse,
+ next: MedusaNextFunction
+ ) => {
+ res.status(400).json({
+ error: "Something happened.",
+ })
+ },
+})
+```
+
+The `errorHandler` property's value is a function that accepts four parameters:
+
+1. The error thrown. Its type can be `MedusaError` or any other thrown error type.
+2. A request object of type `MedusaRequest`.
+3. A response object of type `MedusaResponse`.
+4. A function of type MedusaNextFunction that executes the next middleware in the stack.
+
+This example overrides Medusa's default error handler with a handler that always returns a `400` status code with the same message.
+
+
# Handling CORS in API Routes
In this chapter, you’ll learn about the CORS middleware and how to configure it for custom API routes.
@@ -8846,156 +8525,6 @@ export default defineMiddlewares({
This retrieves the configurations exported from `medusa-config.ts` and applies the `storeCors` to routes starting with `/custom`.
-# Throwing and Handling Errors
-
-In this guide, you'll learn how to throw errors in your Medusa application, how it affects an API route's response, and how to change the default error handler of your Medusa application.
-
-## Throw MedusaError
-
-When throwing an error in your API routes, middlewares, workflows, or any customization, throw a `MedusaError` from the Medusa Framework.
-
-The Medusa application's API route error handler then wraps your thrown error in a uniform object and returns it in the response.
-
-For example:
-
-```ts
-import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
-import { MedusaError } from "@medusajs/framework/utils"
-
-export const GET = async (
- req: MedusaRequest,
- res: MedusaResponse
-) => {
- if (!req.query.q) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- "The `q` query parameter is required."
- )
- }
-
- // ...
-}
-```
-
-The `MedusaError` class accepts in its constructor two parameters:
-
-1. The first is the error's type. `MedusaError` has a static property `Types` that you can use. `Types` is an enum whose possible values are explained in the next section.
-2. The second is the message to show in the error response.
-
-### Error Object in Response
-
-The error object returned in the response has two properties:
-
-- `type`: The error's type.
-- `message`: The error message, if available.
-- `code`: A common snake-case code. Its values can be:
- - `invalid_request_error` for the `DUPLICATE_ERROR` type.
- - `api_error`: for the `DB_ERROR` type.
- - `invalid_state_error` for `CONFLICT` error type.
- - `unknown_error` for any unidentified error type.
- - For other error types, this property won't be available unless you provide a code as a third parameter to the `MedusaError` constructor.
-
-### MedusaError Types
-
-|Type|Description|Status Code|
-|---|---|---|---|---|
-|\`DB\_ERROR\`|Indicates a database error.|\`500\`|
-|\`DUPLICATE\_ERROR\`|Indicates a duplicate of a record already exists. For example, when trying to create a customer whose email is registered by another customer.|\`422\`|
-|\`INVALID\_ARGUMENT\`|Indicates an error that occurred due to incorrect arguments or other unexpected state.|\`500\`|
-|\`INVALID\_DATA\`|Indicates a validation error.|\`400\`|
-|\`UNAUTHORIZED\`|Indicates that a user is not authorized to perform an action or access a route.|\`401\`|
-|\`NOT\_FOUND\`|Indicates that the requested resource, such as a route or a record, isn't found.|\`404\`|
-|\`NOT\_ALLOWED\`|Indicates that an operation isn't allowed.|\`400\`|
-|\`CONFLICT\`|Indicates that a request conflicts with another previous or ongoing request. The error message in this case is ignored for a default message.|\`409\`|
-|\`PAYMENT\_AUTHORIZATION\_ERROR\`|Indicates an error has occurred while authorizing a payment.|\`422\`|
-|Other error types|Any other error type results in an |\`500\`|
-
-***
-
-## Override Error Handler
-
-The `defineMiddlewares` function used to apply middlewares on routes accepts an `errorHandler` in its object parameter. Use it to override the default error handler for API routes.
-
-This error handler will also be used for errors thrown in Medusa's API routes and resources.
-
-For example, create `src/api/middlewares.ts` with the following:
-
-```ts title="src/api/middlewares.ts" collapsibleLines="1-8" expandMoreLabel="Show Imports"
-import {
- defineMiddlewares,
- MedusaNextFunction,
- MedusaRequest,
- MedusaResponse,
-} from "@medusajs/framework/http"
-import { MedusaError } from "@medusajs/framework/utils"
-
-export default defineMiddlewares({
- errorHandler: (
- error: MedusaError | any,
- req: MedusaRequest,
- res: MedusaResponse,
- next: MedusaNextFunction
- ) => {
- res.status(400).json({
- error: "Something happened.",
- })
- },
-})
-```
-
-The `errorHandler` property's value is a function that accepts four parameters:
-
-1. The error thrown. Its type can be `MedusaError` or any other thrown error type.
-2. A request object of type `MedusaRequest`.
-3. A response object of type `MedusaResponse`.
-4. A function of type MedusaNextFunction that executes the next middleware in the stack.
-
-This example overrides Medusa's default error handler with a handler that always returns a `400` status code with the same message.
-
-
-# HTTP Methods
-
-In this chapter, you'll learn about how to add new API routes for each HTTP method.
-
-## HTTP Method Handler
-
-An API route is created for every HTTP method you export a handler function for in a route file.
-
-Allowed HTTP methods are: `GET`, `POST`, `DELETE`, `PUT`, `PATCH`, `OPTIONS`, and `HEAD`.
-
-For example, create the file `src/api/hello-world/route.ts` with the following content:
-
-```ts title="src/api/hello-world/route.ts"
-import type {
- MedusaRequest,
- MedusaResponse,
-} from "@medusajs/framework/http"
-
-export const GET = async (
- req: MedusaRequest,
- res: MedusaResponse
-) => {
- res.json({
- message: "[GET] Hello world!",
- })
-}
-
-export const POST = async (
- req: MedusaRequest,
- res: MedusaResponse
-) => {
- res.json({
- message: "[POST] Hello world!",
- })
-}
-```
-
-This adds two API Routes:
-
-- A `GET` route at `http://localhost:9000/hello-world`.
-- A `POST` route at `http://localhost:9000/hello-world`.
-
-
# Middlewares
In this chapter, you’ll learn about middlewares and how to create them.
@@ -9344,6 +8873,49 @@ A middleware can not override an existing middleware. Instead, middlewares are a
For example, if you define a custom validation middleware, such as `validateAndTransformBody`, on an existing route, then both the original and the custom validation middleware will run.
+# HTTP Methods
+
+In this chapter, you'll learn about how to add new API routes for each HTTP method.
+
+## HTTP Method Handler
+
+An API route is created for every HTTP method you export a handler function for in a route file.
+
+Allowed HTTP methods are: `GET`, `POST`, `DELETE`, `PUT`, `PATCH`, `OPTIONS`, and `HEAD`.
+
+For example, create the file `src/api/hello-world/route.ts` with the following content:
+
+```ts title="src/api/hello-world/route.ts"
+import type {
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+
+export const GET = async (
+ req: MedusaRequest,
+ res: MedusaResponse
+) => {
+ res.json({
+ message: "[GET] Hello world!",
+ })
+}
+
+export const POST = async (
+ req: MedusaRequest,
+ res: MedusaResponse
+) => {
+ res.json({
+ message: "[POST] Hello world!",
+ })
+}
+```
+
+This adds two API Routes:
+
+- A `GET` route at `http://localhost:9000/hello-world`.
+- A `POST` route at `http://localhost:9000/hello-world`.
+
+
# Configure Request Body Parser
In this chapter, you'll learn how to configure the request body parser for your API routes.
@@ -9862,51 +9434,6 @@ export const GET = async (
In the route handler, you resolve the User Module's main service, then use it to retrieve the logged-in admin user.
-# Event Data Payload
-
-In this chapter, you'll learn how subscribers receive an event's data payload.
-
-## Access Event's Data Payload
-
-When events are emitted, they’re emitted with a data payload.
-
-The object that the subscriber function receives as a parameter has an `event` property, which is an object holding the event payload in a `data` property with additional context.
-
-For example:
-
-```ts title="src/subscribers/product-created.ts" highlights={highlights} collapsibleLines="1-5" expandButtonLabel="Show Imports"
-import type {
- SubscriberArgs,
- SubscriberConfig,
-} from "@medusajs/framework"
-
-export default async function productCreateHandler({
- event,
-}: SubscriberArgs<{ id: string }>) {
- const productId = event.data.id
- console.log(`The product ${productId} was created`)
-}
-
-export const config: SubscriberConfig = {
- event: "product.created",
-}
-```
-
-The `event` object has the following properties:
-
-- data: (\`object\`) The data payload of the event. Its properties are different for each event.
-- name: (string) The name of the triggered event.
-- metadata: (\`object\`) Additional data and context of the emitted event.
-
-This logs the product ID received in the `product.created` event’s data payload to the console.
-
-{/* ---
-
-## List of Events with Data Payload
-
-Refer to [this reference](!resources!/events-reference) for a full list of events emitted by Medusa and their data payloads. */}
-
-
# API Route Response
In this chapter, you'll learn how to send a response in your API route.
@@ -10009,172 +9536,76 @@ This API route opens a stream by setting the `Content-Type` in the header to `te
The `MedusaResponse` type is based on [Express's Response](https://expressjs.com/en/api.html#res). Refer to their API reference for other uses of responses.
-# Emit Workflow and Service Events
+# Add Data Model Check Constraints
-In this chapter, you'll learn about event types and how to emit an event in a service or workflow.
+In this chapter, you'll learn how to add check constraints to your data model.
-## Event Types
+## What is a Check Constraint?
-In your customization, you can emit an event, then listen to it in a subscriber and perform an asynchronus action, such as send a notification or data to a third-party system.
+A check constraint is a condition that must be satisfied by records inserted into a database table, otherwise an error is thrown.
-There are two types of events in Medusa:
-
-1. Workflow event: an event that's emitted in a workflow after a commerce feature is performed. For example, Medusa emits the `order.placed` event after a cart is completed.
-2. Service event: an event that's emitted to track, trace, or debug processes under the hood. For example, you can emit an event with an audit trail.
-
-### Which Event Type to Use?
-
-**Workflow events** are the most common event type in development, as most custom features and customizations are built around workflows.
-
-Some examples of workflow events:
-
-1. When a user creates a blog post and you're emitting an event to send a newsletter email.
-2. When you finish syncing products to a third-party system and you want to notify the admin user of new products added.
-3. When a customer purchases a digital product and you want to generate and send it to them.
-
-You should only go for a **service event** if you're emitting an event for processes under the hood that don't directly affect front-facing features.
-
-Some examples of service events:
-
-1. When you're tracing data manipulation and changes, and you want to track every time some custom data is changed.
-2. When you're syncing data with a search engine.
+For example, if you have a data model with a `price` property, you want to only allow positive number values. So, you add a check constraint that fails when inserting a record with a negative price value.
***
-## Emit Event in a Workflow
+## How to Set a Check Constraint?
-To emit a workflow event, use the `emitEventStep` helper step provided in the `@medusajs/medusa/core-flows` package.
+To set check constraints on a data model, use the `checks` method. This method accepts an array of check constraints to apply on the data model.
-For example:
+For example, to set a check constraint on a `price` property that ensures its value can only be a positive number:
-```ts highlights={highlights}
-import {
- createWorkflow,
-} from "@medusajs/framework/workflows-sdk"
-import {
- emitEventStep,
-} from "@medusajs/medusa/core-flows"
+```ts highlights={checks1Highlights}
+import { model } from "@medusajs/framework/utils"
-const helloWorldWorkflow = createWorkflow(
- "hello-world",
- () => {
- // ...
-
- emitEventStep({
- eventName: "custom.created",
- data: {
- id: "123",
- // other data payload
- },
- })
- }
-)
-```
-
-The `emitEventStep` accepts an object having the following properties:
-
-- `eventName`: The event's name.
-- `data`: The data payload as an object. You can pass any properties in the object, and subscribers listening to the event will receive this data in the event's payload.
-
-In this example, you emit the event `custom.created` and pass in the data payload an ID property.
-
-### Test it Out
-
-If you execute the workflow, the event is emitted and you can see it in your application's logs.
-
-Any subscribers listening to the event are executed.
-
-***
-
-## Emit Event in a Service
-
-To emit a service event:
-
-1. Resolve `event_bus` from the module's container in your service's constructor:
-
-### Extending Service Factory
-
-```ts title="src/modules/blog/service.ts" highlights={["9"]}
-import { IEventBusService } from "@medusajs/framework/types"
-import { MedusaService } from "@medusajs/framework/utils"
-
-class BlogModuleService extends MedusaService({
- Post,
-}){
- protected eventBusService_: AbstractEventBusModuleService
-
- constructor({ event_bus }) {
- super(...arguments)
- this.eventBusService_ = event_bus
- }
-}
-```
-
-### Without Service Factory
-
-```ts title="src/modules/blog/service.ts" highlights={["6"]}
-import { IEventBusService } from "@medusajs/framework/types"
-
-class BlogModuleService {
- protected eventBusService_: AbstractEventBusModuleService
-
- constructor({ event_bus }) {
- this.eventBusService_ = event_bus
- }
-}
-```
-
-2. Use the event bus service's `emit` method in the service's methods to emit an event:
-
-```ts title="src/modules/blog/service.ts" highlights={serviceHighlights}
-class BlogModuleService {
+const CustomProduct = model.define("custom_product", {
// ...
- performAction() {
- // TODO perform action
-
- this.eventBusService_.emit({
- name: "custom.event",
- data: {
- id: "123",
- // other data payload
- },
- })
- }
-}
-```
-
-The method accepts an object having the following properties:
-
-- `name`: The event's name.
-- `data`: The data payload as an object. You can pass any properties in the object, and subscribers listening to the event will receive this data in the event's payload.
-
-3. By default, the Event Module's service isn't injected into your module's container. To add it to the container, pass it in the module's registration object in `medusa-config.ts` in the `dependencies` property:
-
-```ts title="medusa-config.ts" highlights={depsHighlight}
-import { Modules } from "@medusajs/framework/utils"
-
-module.exports = defineConfig({
- // ...
- modules: [
- {
- resolve: "./src/modules/blog",
- dependencies: [
- Modules.EVENT_BUS,
- ],
- },
- ],
+ price: model.bigNumber(),
})
+.checks([
+ (columns) => `${columns.price} >= 0`,
+])
```
-The `dependencies` property accepts an array of module registration keys. The specified modules' main services are injected into the module's container.
+The item passed in the array parameter of `checks` can be a callback function that accepts as a parameter an object whose keys are the names of the properties in the data model schema, and values the respective column name in the database.
-That's how you can resolve it in your module's main service's constructor.
+The function returns a string indicating the [SQL check constraint expression](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-CHECK-CONSTRAINTS). In the expression, use the `columns` parameter to access a property's column name.
-### Test it Out
+You can also pass an object to the `checks` method:
-If you execute the `performAction` method of your service, the event is emitted and you can see it in your application's logs.
+```ts highlights={checks2Highlights}
+import { model } from "@medusajs/framework/utils"
-Any subscribers listening to the event are also executed.
+const CustomProduct = model.define("custom_product", {
+ // ...
+ price: model.bigNumber(),
+})
+.checks([
+ {
+ name: "custom_product_price_check",
+ expression: (columns) => `${columns.price} >= 0`,
+ },
+])
+```
+
+The object accepts the following properties:
+
+- `name`: The check constraint's name.
+- `expression`: A function similar to the one that can be passed to the array. It accepts an object of columns and returns an [SQL check constraint expression](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-CHECK-CONSTRAINTS).
+
+***
+
+## Apply in Migrations
+
+After adding the check constraint, make sure to generate and run migrations if you already have the table in the database. Otherwise, the check constraint won't be reflected.
+
+To generate a migration for the data model's module then reflect it on the database, run the following command:
+
+```bash
+npx medusa db:generate custom_module
+npx medusa db:migrate
+```
+
+The first command generates the migration under the `migrations` directory of your module's directory, and the second reflects it on the database.
# Request Body and Query Parameter Validation
@@ -10426,438 +9857,1332 @@ For example, if you omit the `a` parameter, you'll receive a `400` response code
To see different examples and learn more about creating a validation schema, refer to [Zod's documentation](https://zod.dev).
-# Create a Plugin
+# Data Model Database Index
-In this chapter, you'll learn how to create a Medusa plugin and publish it.
+In this chapter, you’ll learn how to define a database index on a data model.
-A [plugin](https://docs.medusajs.com/learn/fundamentals/plugins/index.html.md) is a package of reusable Medusa customizations that you can install in any Medusa application. By creating and publishing a plugin, you can reuse your Medusa customizations across multiple projects or share them with the community.
+You can also define an index on a property as explained in the [Properties chapter](https://docs.medusajs.com/learn/fundamentals/data-models/properties#define-database-index-on-property/index.html.md).
-Plugins are available starting from [Medusa v2.3.0](https://github.com/medusajs/medusa/releases/tag/v2.3.0).
+## Define Database Index on Data Model
-## 1. Create a Plugin Project
+A data model has an `indexes` method that defines database indices on its properties.
-Plugins are created in a separate Medusa project. This makes the development and publishing of the plugin easier. Later, you'll install that plugin in your Medusa application to test it out and use it.
+The index can be on multiple columns (composite index). For example:
-Medusa's `create-medusa-app` CLI tool provides the option to create a plugin project. Run the following command to create a new plugin project:
+```ts highlights={dataModelIndexHighlights}
+import { model } from "@medusajs/framework/utils"
-```bash
-npx create-medusa-app my-plugin --plugin
-```
-
-This will create a new Medusa plugin project in the `my-plugin` directory.
-
-### Plugin Directory Structure
-
-After the installation is done, the plugin structure will look like this:
-
-
-
-- `src/`: Contains the Medusa customizations.
-- `src/admin`: Contains [admin extensions](https://docs.medusajs.com/learn/fundamentals/admin/index.html.md).
-- `src/api`: Contains [API routes](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md) and [middlewares](https://docs.medusajs.com/learn/fundamentals/api-routes/middlewares/index.html.md). You can add store, admin, or any custom API routes.
-- `src/jobs`: Contains [scheduled jobs](https://docs.medusajs.com/learn/fundamentals/scheduled-jobs/index.html.md).
-- `src/links`: Contains [module links](https://docs.medusajs.com/learn/fundamentals/module-links/index.html.md).
-- `src/modules`: Contains [modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md).
-- `src/provider`: Contains [module providers](#create-module-providers).
-- `src/subscribers`: Contains [subscribers](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md).
-- `src/workflows`: Contains [workflows](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md). You can also add [hooks](https://docs.medusajs.com/learn/fundamentals/workflows/add-workflow-hook/index.html.md) under `src/workflows/hooks`.
-- `package.json`: Contains the plugin's package information, including general information and dependencies.
-- `tsconfig.json`: Contains the TypeScript configuration for the plugin.
-
-***
-
-## 2. Prepare Plugin
-
-### Package Name
-
-Before developing, testing, and publishing your plugin, make sure its name in `package.json` is correct. This is the name you'll use to install the plugin in your Medusa application.
-
-For example:
-
-```json title="package.json"
-{
- "name": "@myorg/plugin-name",
- // ...
-}
-```
-
-### Package Keywords
-
-Medusa scrapes NPM for a list of plugins that integrate third-party services, to later showcase them on the Medusa website. If you want your plugin to appear in that listing, make sure to add the `medusa-v2` and `medusa-plugin-integration` keywords to the `keywords` field in `package.json`.
-
-Only plugins that integrate third-party services are listed in the Medusa integrations page. If your plugin doesn't integrate a third-party service, you can skip this step.
-
-```json title="package.json"
-{
- "keywords": [
- "medusa-plugin-integration",
- "medusa-v2"
- ],
- // ...
-}
-```
-
-In addition, make sure to use one of the following keywords based on your integration type:
-
-|Keyword|Description|Example|
-|---|---|---|
-|\`medusa-plugin-analytics\`|Analytics service integration|Google Analytics|
-|\`medusa-plugin-auth\`|Authentication service integration|Auth0|
-|\`medusa-plugin-cms\`|CMS service integration|Contentful|
-|\`medusa-plugin-notification\`|Notification service integration|Twilio SMS|
-|\`medusa-plugin-payment\`|Payment service integration|PayPal|
-|\`medusa-plugin-search\`|Search service integration|MeiliSearch|
-|\`medusa-plugin-shipping\`|Shipping service integration|DHL|
-|\`medusa-plugin-other\`|Other third-party integrations|Sentry|
-
-### Package Dependencies
-
-Your plugin project will already have the dependencies mentioned in this section. Unless you made changes to the dependencies, you can skip this section.
-
-In the `package.json` file you must have the Medusa dependencies as `devDependencies` and `peerDependencies`. In addition, you must have `@swc/core` as a `devDependency`, as it's used by the plugin CLI tools.
-
-For example, assuming `2.5.0` is the latest Medusa version:
-
-```json title="package.json"
-{
- "devDependencies": {
- "@medusajs/admin-sdk": "2.5.0",
- "@medusajs/cli": "2.5.0",
- "@medusajs/framework": "2.5.0",
- "@medusajs/medusa": "2.5.0",
- "@medusajs/test-utils": "2.5.0",
- "@medusajs/ui": "4.0.4",
- "@medusajs/icons": "2.5.0",
- "@swc/core": "1.5.7",
+const MyCustom = model.define("my_custom", {
+ id: model.id().primaryKey(),
+ name: model.text(),
+ age: model.number(),
+}).indexes([
+ {
+ on: ["name", "age"],
},
- "peerDependencies": {
- "@medusajs/admin-sdk": "2.5.0",
- "@medusajs/cli": "2.5.0",
- "@medusajs/framework": "2.5.0",
- "@medusajs/test-utils": "2.5.0",
- "@medusajs/medusa": "2.5.0",
- "@medusajs/ui": "4.0.3",
- "@medusajs/icons": "2.5.0",
- }
-}
+])
+
+export default MyCustom
```
-### Package Exports
+The `indexes` method receives an array of indices as a parameter. Each index is an object with a required `on` property indicating the properties to apply the index on.
-Your plugin project will already have the exports mentioned in this section. Unless you made changes to the exports or you created your plugin before [Medusa v2.7.0](https://github.com/medusajs/medusa/releases/tag/v2.7.0), you can skip this section.
+In the above example, you define a composite index on the `name` and `age` properties.
-In the `package.json` file, make sure your plugin has the following exports:
+### Index Conditions
-```json title="package.json"
-{
- "exports": {
- "./package.json": "./package.json",
- "./workflows": "./.medusa/server/src/workflows/index.js",
- "./.medusa/server/src/modules/*": "./.medusa/server/src/modules/*/index.js",
- "./providers/*": "./.medusa/server/src/providers/*/index.js",
- "./admin": {
- "import": "./.medusa/server/src/admin/index.mjs",
- "require": "./.medusa/server/src/admin/index.js",
- "default": "./.medusa/server/src/admin/index.js"
+An index can have conditions. For example:
+
+```ts highlights={conditionHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const MyCustom = model.define("my_custom", {
+ id: model.id().primaryKey(),
+ name: model.text(),
+ age: model.number(),
+}).indexes([
+ {
+ on: ["name", "age"],
+ where: {
+ age: 30,
},
- "./*": "./.medusa/server/src/*.js"
- }
-}
+ },
+])
+
+export default MyCustom
```
-Aside from the `./package.json`, `./providers`, and `./admin`, these exports are only a recommendation. You can cherry-pick the files and directories you want to export.
+The index object passed to `indexes` accepts a `where` property whose value is an object of conditions. The object's key is a property's name, and its value is the condition on that property.
-The plugin exports the following files and directories:
+In the example above, the composite index is created on the `name` and `age` properties when the `age`'s value is `30`.
-- `./package.json`: The `package.json` file. Medusa needs to access the `package.json` when registering the plugin.
-- `./workflows`: The workflows exported in `./src/workflows/index.ts`.
-- `./.medusa/server/src/modules/*`: The definition file of modules. This is useful if you create links to the plugin's modules in the Medusa application.
-- `./providers/*`: The definition file of module providers. This is useful if your plugin includes a module provider, allowing you to register the plugin's providers in Medusa applications. Learn more in the [Create Module Providers](#create-module-providers) section.
-- `./admin`: The admin extensions exported in `./src/admin/index.ts`.
-- `./*`: Any other files in the plugin's `src` directory.
+A property's condition can be a negation. For example:
-***
+```ts highlights={negationHighlights}
+import { model } from "@medusajs/framework/utils"
-## 3. Publish Plugin Locally for Development and Testing
-
-Medusa's CLI tool provides commands to simplify developing and testing your plugin in a local Medusa application. You start by publishing your plugin in the local package registry, then install it in your Medusa application. You can then watch for changes in the plugin as you develop it.
-
-### Publish and Install Local Package
-
-### Prerequisites
-
-- [Medusa application installed.](https://docs.medusajs.com/learn/installation/index.html.md)
-
-The first time you create your plugin, you need to publish the package into a local package registry, then install it in your Medusa application. This is a one-time only process.
-
-To publish the plugin to the local registry, run the following command in your plugin project:
-
-```bash title="Plugin project"
-npx medusa plugin:publish
-```
-
-This command uses [Yalc](https://github.com/wclr/yalc) under the hood to publish the plugin to a local package registry. The plugin is published locally under the name you specified in `package.json`.
-
-Next, navigate to your Medusa application:
-
-```bash title="Medusa application"
-cd ~/path/to/medusa-app
-```
-
-Make sure to replace `~/path/to/medusa-app` with the path to your Medusa application.
-
-Then, if your project was created before v2.3.1 of Medusa, make sure to install `yalc` as a development dependency:
-
-```bash npm2yarn title="Medusa application"
-npm install --save-dev yalc
-```
-
-After that, run the following Medusa CLI command to install the plugin:
-
-```bash title="Medusa application"
-npx medusa plugin:add @myorg/plugin-name
-```
-
-Make sure to replace `@myorg/plugin-name` with the name of your plugin as specified in `package.json`. Your plugin will be installed from the local package registry into your Medusa application.
-
-### Register Plugin in Medusa Application
-
-After installing the plugin, you need to register it in your Medusa application in the configurations defined in `medusa-config.ts`.
-
-Add the plugin to the `plugins` array in the `medusa-config.ts` file:
-
-```ts title="medusa-config.ts" highlights={pluginHighlights}
-module.exports = defineConfig({
- // ...
- plugins: [
- {
- resolve: "@myorg/plugin-name",
- options: {},
- },
- ],
-})
-```
-
-The `plugins` configuration is an array of objects where each object has a `resolve` key whose value is the name of the plugin package.
-
-#### Pass Module Options through Plugin
-
-Each plugin configuration also accepts an `options` property, whose value is an object of options to pass to the plugin's modules.
-
-For example:
-
-```ts title="medusa-config.ts" highlights={pluginOptionsHighlight}
-module.exports = defineConfig({
- // ...
- plugins: [
- {
- resolve: "@myorg/plugin-name",
- options: {
- apiKey: true,
+const MyCustom = model.define("my_custom", {
+ id: model.id().primaryKey(),
+ name: model.text(),
+ age: model.number().nullable(),
+}).indexes([
+ {
+ on: ["name", "age"],
+ where: {
+ age: {
+ $ne: null,
},
},
+ },
+])
+
+export default MyCustom
+```
+
+A property's value in `where` can be an object having a `$ne` property. `$ne`'s value indicates what the specified property's value shouldn't be.
+
+In the example above, the composite index is created on the `name` and `age` properties when `age`'s value is not `null`.
+
+### Unique Database Index
+
+The object passed to `indexes` accepts a `unique` property indicating that the created index must be a unique index.
+
+For example:
+
+```ts highlights={uniqueHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const MyCustom = model.define("my_custom", {
+ id: model.id().primaryKey(),
+ name: model.text(),
+ age: model.number(),
+}).indexes([
+ {
+ on: ["name", "age"],
+ unique: true,
+ },
+])
+
+export default MyCustom
+```
+
+This creates a unique composite index on the `name` and `age` properties.
+
+
+# Infer Type of Data Model
+
+In this chapter, you'll learn how to infer the type of a data model.
+
+## How to Infer Type of Data Model?
+
+Consider you have a `Post` data model. You can't reference this data model in a type, such as a workflow input or service method output types, since it's a variable.
+
+Instead, Medusa provides `InferTypeOf` that transforms your data model to a type.
+
+For example:
+
+```ts
+import { InferTypeOf } from "@medusajs/framework/types"
+import { Post } from "../modules/blog/models/post" // relative path to the model
+
+export type Post = InferTypeOf
+```
+
+`InferTypeOf` accepts as a type argument the type of the data model.
+
+Since the `Post` data model is a variable, use the `typeof` operator to pass the data model as a type argument to `InferTypeOf`.
+
+You can now use the `Post` type to reference a data model in other types, such as in workflow inputs or service method outputs:
+
+```ts title="Example Service"
+// other imports...
+import { InferTypeOf } from "@medusajs/framework/types"
+import { Post } from "../models/post"
+
+type Post = InferTypeOf
+
+class BlogModuleService extends MedusaService({ Post }) {
+ async doSomething(): Promise {
+ // ...
+ }
+}
+```
+
+
+# Data Model Properties
+
+In this chapter, you'll learn about the different property types you can use in a data model and how to configure a data model's properties.
+
+## Data Model's Default Properties
+
+By default, Medusa creates the following properties for every data model:
+
+- `created_at`: A [dateTime](#dateTime) property that stores when a record of the data model was created.
+- `updated_at`: A [dateTime](#dateTime) property that stores when a record of the data model was updated.
+- `deleted_at`: A [dateTime](#dateTime) property that stores when a record of the data model was deleted. When you soft-delete a record, Medusa sets the `deleted_at` property to the current date.
+
+***
+
+## Property Types
+
+This section covers the different property types you can define in a data model's schema using the `model` methods.
+
+### id
+
+The `id` method defines an automatically generated string ID property. The generated ID is a unique string that has a mix of letters and numbers.
+
+For example:
+
+```ts highlights={idHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ id: model.id(),
+ // ...
+})
+
+export default Post
+```
+
+### text
+
+The `text` method defines a string property.
+
+For example:
+
+```ts highlights={textHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ name: model.text(),
+ // ...
+})
+
+export default Post
+```
+
+### number
+
+The `number` method defines a number property.
+
+For example:
+
+```ts highlights={numberHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ age: model.number(),
+ // ...
+})
+
+export default Post
+```
+
+### float
+
+This property is only available after [Medusa v2.1.2](https://github.com/medusajs/medusa/releases/tag/v2.1.2).
+
+The `float` method defines a number property that allows for values with decimal places.
+
+Use this property type when it's less important to have high precision for numbers with large decimal places. Alternatively, for higher percision, use the [bigNumber property](#bignumber).
+
+For example:
+
+```ts highlights={floatHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ rating: model.float(),
+ // ...
+})
+
+export default Post
+```
+
+### bigNumber
+
+The `bigNumber` method defines a number property that expects large numbers, such as prices.
+
+Use this property type when it's important to have high precision for numbers with large decimal places. Alternatively, for less percision, use the [float property](#float).
+
+For example:
+
+```ts highlights={bigNumberHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ price: model.bigNumber(),
+ // ...
+})
+
+export default Post
+```
+
+### boolean
+
+The `boolean` method defines a boolean property.
+
+For example:
+
+```ts highlights={booleanHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ hasAccount: model.boolean(),
+ // ...
+})
+
+export default Post
+```
+
+### enum
+
+The `enum` method defines a property whose value can only be one of the specified values.
+
+For example:
+
+```ts highlights={enumHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ color: model.enum(["black", "white"]),
+ // ...
+})
+
+export default Post
+```
+
+The `enum` method accepts an array of possible string values.
+
+### dateTime
+
+The `dateTime` method defines a timestamp property.
+
+For example:
+
+```ts highlights={dateTimeHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ date_of_birth: model.dateTime(),
+ // ...
+})
+
+export default Post
+```
+
+### json
+
+The `json` method defines a property whose value is a stringified JSON object.
+
+For example:
+
+```ts highlights={jsonHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ metadata: model.json(),
+ // ...
+})
+
+export default Post
+```
+
+### array
+
+The `array` method defines an array of strings property.
+
+For example:
+
+```ts highlights={arrHightlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ names: model.array(),
+ // ...
+})
+
+export default Post
+```
+
+### Properties Reference
+
+Refer to the [Data Model Language (DML) reference](https://docs.medusajs.com/resources/references/data-model/index.html.md) for a full reference of the properties.
+
+***
+
+## Set Primary Key Property
+
+To set any `id`, `text`, or `number` property as a primary key, use the `primaryKey` method.
+
+For example:
+
+```ts highlights={highlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ id: model.id().primaryKey(),
+ // ...
+})
+
+export default Post
+```
+
+In the example above, the `id` property is defined as the data model's primary key.
+
+***
+
+## Property Default Value
+
+Use the `default` method on a property's definition to specify the default value of a property.
+
+For example:
+
+```ts highlights={defaultHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ color: model
+ .enum(["black", "white"])
+ .default("black"),
+ age: model
+ .number()
+ .default(0),
+ // ...
+})
+
+export default Post
+```
+
+In this example, you set the default value of the `color` enum property to `black`, and that of the `age` number property to `0`.
+
+***
+
+## Make Property Optional
+
+Use the `nullable` method to indicate that a property’s value can be `null`. This is useful when you want a property to be optional.
+
+For example:
+
+```ts highlights={nullableHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ price: model.bigNumber().nullable(),
+ // ...
+})
+
+export default Post
+```
+
+In the example above, the `price` property is configured to allow `null` values, making it optional.
+
+***
+
+## Unique Property
+
+The `unique` method indicates that a property’s value must be unique in the database through a unique index.
+
+For example:
+
+```ts highlights={uniqueHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const User = model.define("user", {
+ email: model.text().unique(),
+ // ...
+})
+
+export default User
+```
+
+In this example, multiple users can’t have the same email.
+
+***
+
+## Define Database Index on Property
+
+Use the `index` method on a property's definition to define a database index.
+
+For example:
+
+```ts highlights={dbIndexHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ id: model.id().primaryKey(),
+ name: model.text().index(
+ "IDX_MY_CUSTOM_NAME"
+ ),
+})
+
+export default Post
+```
+
+The `index` method optionally accepts the name of the index as a parameter.
+
+In this example, you define an index on the `name` property.
+
+***
+
+## Define a Searchable Property
+
+Methods generated by the [service factory](https://docs.medusajs.com/learn/fundamentals/modules/service-factory/index.html.md) that accept filters, such as `list{ModelName}s`, accept a `q` property as part of the filters.
+
+When the `q` filter is passed, the data model's searchable properties are queried to find matching records.
+
+Use the `searchable` method on a `text` property to indicate that it's searchable.
+
+For example:
+
+```ts highlights={searchableHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Post = model.define("post", {
+ title: model.text().searchable(),
+ // ...
+})
+
+export default Post
+```
+
+In this example, the `title` property is searchable.
+
+### Search Example
+
+If you pass a `q` filter to the `listPosts` method:
+
+```ts
+const posts = await blogModuleService.listPosts({
+ q: "New Products",
+})
+```
+
+This retrieves records that include `New Products` in their `title` property.
+
+
+# Manage Relationships
+
+In this chapter, you'll learn how to manage relationships between data models when creating, updating, or retrieving records using the module's main service.
+
+## Manage One-to-One Relationship
+
+### BelongsTo Side of One-to-One
+
+When you create a record of a data model that belongs to another through a one-to-one relation, pass the ID of the other data model's record in the `{relation}_id` property, where `{relation}` is the name of the relation property.
+
+For example, assuming you have the [User and Email data models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#one-to-one-relationship/index.html.md), set an email's user ID as follows:
+
+```ts highlights={belongsHighlights}
+// when creating an email
+const email = await helloModuleService.createEmails({
+ // other properties...
+ user_id: "123",
+})
+
+// when updating an email
+const email = await helloModuleService.updateEmails({
+ id: "321",
+ // other properties...
+ user_id: "123",
+})
+```
+
+In the example above, you pass the `user_id` property when creating or updating an email to specify the user it belongs to.
+
+### HasOne Side
+
+When you create a record of a data model that has one of another, pass the ID of the other data model's record in the relation property.
+
+For example, assuming you have the [User and Email data models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#one-to-one-relationship/index.html.md), set a user's email ID as follows:
+
+```ts highlights={hasOneHighlights}
+// when creating a user
+const user = await helloModuleService.createUsers({
+ // other properties...
+ email: "123",
+})
+
+// when updating a user
+const user = await helloModuleService.updateUsers({
+ id: "321",
+ // other properties...
+ email: "123",
+})
+```
+
+In the example above, you pass the `email` property when creating or updating a user to specify the email it has.
+
+***
+
+## Manage One-to-Many Relationship
+
+In a one-to-many relationship, you can only manage the associations from the `belongsTo` side.
+
+When you create a record of the data model on the `belongsTo` side, pass the ID of the other data model's record in the `{relation}_id` property, where `{relation}` is the name of the relation property.
+
+For example, assuming you have the [Product and Store data models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#one-to-many-relationship/index.html.md), set a product's store ID as follows:
+
+```ts highlights={manyBelongsHighlights}
+// when creating a product
+const product = await helloModuleService.createProducts({
+ // other properties...
+ store_id: "123",
+})
+
+// when updating a product
+const product = await helloModuleService.updateProducts({
+ id: "321",
+ // other properties...
+ store_id: "123",
+})
+```
+
+In the example above, you pass the `store_id` property when creating or updating a product to specify the store it belongs to.
+
+***
+
+## Manage Many-to-Many Relationship
+
+If your many-to-many relation is represented with a [pivotEntity](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#many-to-many-with-custom-columns/index.html.md), refer to [this section](#manage-many-to-many-relationship-with-pivotentity) instead.
+
+### Create Associations
+
+When you create a record of a data model that has a many-to-many relationship to another data model, pass an array of IDs of the other data model's records in the relation property.
+
+For example, assuming you have the [Order and Product data models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#many-to-many-relationship/index.html.md), set the association between products and orders as follows:
+
+```ts highlights={manyHighlights}
+// when creating a product
+const product = await helloModuleService.createProducts({
+ // other properties...
+ orders: ["123", "321"],
+})
+
+// when creating an order
+const order = await helloModuleService.createOrders({
+ id: "321",
+ // other properties...
+ products: ["123", "321"],
+})
+```
+
+In the example above, you pass the `orders` property when you create a product, and you pass the `products` property when you create an order.
+
+### Update Associations
+
+When you use the `update` methods generated by the service factory, you also pass an array of IDs as the relation property's value to add new associated records.
+
+However, this removes any existing associations to records whose IDs aren't included in the array.
+
+For example, assuming you have the [Order and Product data models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#many-to-many-relationship/index.html.md), you update the product's related orders as so:
+
+```ts
+const product = await helloModuleService.updateProducts({
+ id: "123",
+ // other properties...
+ orders: ["321"],
+})
+```
+
+If the product was associated with an order, and you don't include that order's ID in the `orders` array, the association between the product and order is removed.
+
+So, to add a new association without removing existing ones, retrieve the product first to pass its associated orders when updating the product:
+
+```ts highlights={updateAssociationHighlights}
+const product = await helloModuleService.retrieveProduct(
+ "123",
+ {
+ relations: ["orders"],
+ }
+)
+
+const updatedProduct = await helloModuleService.updateProducts({
+ id: product.id,
+ // other properties...
+ orders: [
+ ...product.orders.map((order) => order.id),
+ "321",
],
})
```
-The `options` property in the plugin configuration is passed to all modules in the plugin. Learn more about module options in [this chapter](https://docs.medusajs.com/learn/fundamentals/modules/options/index.html.md).
-
-### Watch Plugin Changes During Development
-
-While developing your plugin, you can watch for changes in the plugin and automatically update the plugin in the Medusa application using it. This is the only command you'll continuously need during your plugin development.
-
-To do that, run the following command in your plugin project:
-
-```bash title="Plugin project"
-npx medusa plugin:develop
-```
-
-This command will:
-
-- Watch for changes in the plugin. Whenever a file is changed, the plugin is automatically built.
-- Publish the plugin changes to the local package registry. This will automatically update the plugin in the Medusa application using it. You can also benefit from real-time HMR updates of admin extensions.
-
-### Start Medusa Application
-
-You can start your Medusa application's development server to test out your plugin:
-
-```bash npm2yarn title="Medusa application"
-npm run dev
-```
-
-While your Medusa application is running and the plugin is being watched, you can test your plugin while developing it in the Medusa application.
+This keeps existing associations between the product and orders, and adds a new one.
***
-## 4. Create Customizations in the Plugin
+## Manage Many-to-Many Relationship with pivotEntity
-You can now build your plugin's customizations. The following guide explains how to build different customizations in your plugin.
+If your many-to-many relation is represented without a [pivotEntity](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#many-to-many-with-custom-columns/index.html.md), refer to [this section](#manage-many-to-many-relationship) instead.
-- [Create a module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md)
-- [Create a module link](https://docs.medusajs.com/learn/fundamentals/module-links/index.html.md)
-- [Create a workflow](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md)
-- [Add a workflow hook](https://docs.medusajs.com/learn/fundamentals/workflows/add-workflow-hook/index.html.md)
-- [Create an API route](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md)
-- [Add a subscriber](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md)
-- [Add a scheduled job](https://docs.medusajs.com/learn/fundamentals/scheduled-jobs/index.html.md)
-- [Add an admin widget](https://docs.medusajs.com/learn/fundamentals/admin/widgets/index.html.md)
-- [Add an admin UI route](https://docs.medusajs.com/learn/fundamentals/admin/ui-routes/index.html.md)
+If you have a many-to-many relation with a `pivotEntity` specified, make sure to pass the data model representing the pivot table to [MedusaService](https://docs.medusajs.com/learn/fundamentals/modules/service-factory/index.html.md) that your module's service extends.
-While building those customizations, you can test them in your Medusa application by [watching the plugin changes](#watch-plugin-changes-during-development) and [starting the Medusa application](#start-medusa-application).
+For example, assuming you have the [Order, Product, and OrderProduct models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#many-to-many-with-custom-columns/index.html.md), add `OrderProduct` to `MedusaService`'s object parameter:
-### Generating Migrations for Modules
-
-During your development, you may need to generate migrations for modules in your plugin. To do that, first, add the following environment variables in your plugin project:
-
-```plain title="Plugin project"
-DB_USERNAME=postgres
-DB_PASSWORD=123...
-DB_HOST=localhost
-DB_PORT=5432
-DB_NAME=db_name
+```ts highlights={["4"]}
+class BlogModuleService extends MedusaService({
+ Order,
+ Product,
+ OrderProduct,
+}) {}
```
-You can add these environment variables in a `.env` file in your plugin project. The variables are:
+This will generate Create, Read, Update and Delete (CRUD) methods for the `OrderProduct` data model, which you can use to create relations between orders and products and manage the extra columns in the pivot table.
-- `DB_USERNAME`: The username of the PostgreSQL user to connect to the database.
-- `DB_PASSWORD`: The password of the PostgreSQL user to connect to the database.
-- `DB_HOST`: The host of the PostgreSQL database. Typically, it's `localhost` if you're running the database locally.
-- `DB_PORT`: The port of the PostgreSQL database. Typically, it's `5432` if you're running the database locally.
-- `DB_NAME`: The name of the PostgreSQL database to connect to.
+For example:
-Then, run the following command in your plugin project to generate migrations for the modules in your plugin:
+```ts
+// create order-product association
+const orderProduct = await blogModuleService.createOrderProducts({
+ order_id: "123",
+ product_id: "123",
+ metadata: {
+ test: true,
+ },
+})
-```bash title="Plugin project"
-npx medusa plugin:db:generate
+// update order-product association
+const orderProduct = await blogModuleService.updateOrderProducts({
+ id: "123",
+ metadata: {
+ test: false,
+ },
+})
+
+// delete order-product association
+await blogModuleService.deleteOrderProducts("123")
```
-This command generates migrations for all modules in the plugin.
+Since the `OrderProduct` data model belongs to the `Order` and `Product` data models, you can set its order and product as explained in the [one-to-many relationship section](#manage-one-to-many-relationship) using `order_id` and `product_id`.
-Finally, run these migrations on the Medusa application that the plugin is installed in using the `db:migrate` command:
+Refer to the [service factory reference](https://docs.medusajs.com/resources/service-factory-reference/index.html.md) for a full list of generated methods and their usages.
-```bash title="Medusa application"
+***
+
+## Retrieve Records of Relation
+
+The `list`, `listAndCount`, and `retrieve` methods of a module's main service accept as a second parameter an object of options.
+
+To retrieve the records associated with a data model's records through a relationship, pass in the second parameter object a `relations` property whose value is an array of relationship names.
+
+For example, assuming you have the [Order and Product data models from the previous chapter](https://docs.medusajs.com/learn/fundamentals/data-models/relationships#many-to-many-relationship/index.html.md), you retrieve a product's orders as follows:
+
+```ts highlights={retrieveHighlights}
+const product = await blogModuleService.retrieveProducts(
+ "123",
+ {
+ relations: ["orders"],
+ }
+)
+```
+
+In the example above, the retrieved product has an `orders` property, whose value is an array of orders associated with the product.
+
+
+# Data Model Relationships
+
+In this chapter, you’ll learn how to define relationships between data models in your module.
+
+## What is a Relationship Property?
+
+A relationship property defines an association in the database between two models. It's created using the Data Model Language (DML) methods, such as `hasOne` or `belongsTo`.
+
+When you generate a migration for these data models, the migrations include foreign key columns or pivot tables, based on the relationship's type.
+
+You want to create a relation between data models in the same module.
+
+You want to create a relationship between data models in different modules. Use module links instead.
+
+***
+
+## One-to-One Relationship
+
+A one-to-one relationship indicates that one record of a data model belongs to or is associated with another.
+
+To define a one-to-one relationship, create relationship properties in the data models using the following methods:
+
+1. `hasOne`: indicates that the model has one record of the specified model.
+2. `belongsTo`: indicates that the model belongs to one record of the specified model.
+
+For example:
+
+```ts highlights={oneToOneHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const User = model.define("user", {
+ id: model.id().primaryKey(),
+ email: model.hasOne(() => Email),
+})
+
+const Email = model.define("email", {
+ id: model.id().primaryKey(),
+ user: model.belongsTo(() => User, {
+ mappedBy: "email",
+ }),
+})
+```
+
+In the example above, a user has one email, and an email belongs to one user.
+
+The `hasOne` and `belongsTo` methods accept a function as the first parameter. The function returns the associated data model.
+
+The `belongsTo` method also requires passing as a second parameter an object with the property `mappedBy`. Its value is the name of the relationship property in the other data model.
+
+### Optional Relationship
+
+To make the relationship optional on the `hasOne` or `belongsTo` side, use the `nullable` method on either property as explained in [this chapter](https://docs.medusajs.com/learn/fundamentals/data-models/properties#make-property-optional/index.html.md).
+
+### One-sided One-to-One Relationship
+
+If the one-to-one relationship is only defined on one side, pass `undefined` to the `mappedBy` property in the `belongsTo` method.
+
+For example:
+
+```ts highlights={oneToOneUndefinedHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const User = model.define("user", {
+ id: model.id().primaryKey(),
+})
+
+const Email = model.define("email", {
+ id: model.id().primaryKey(),
+ user: model.belongsTo(() => User, {
+ mappedBy: undefined,
+ }),
+})
+```
+
+### One-to-One Relationship in the Database
+
+When you generate the migrations of data models that have a one-to-one relationship, the migration adds to the table of the data model that has the `belongsTo` property:
+
+1. A column of the format `{relation_name}_id` to store the ID of the record of the related data model. For example, the `email` table will have a `user_id` column.
+2. A foreign key on the `{relation_name}_id` column to the table of the related data model.
+
+
+
+***
+
+## One-to-Many Relationship
+
+A one-to-many relationship indicates that one record of a data model has many records of another data model.
+
+To define a one-to-many relationship, create relationship properties in the data models using the following methods:
+
+1. `hasMany`: indicates that the model has more than one record of the specified model.
+2. `belongsTo`: indicates that the model belongs to one record of the specified model.
+
+For example:
+
+```ts highlights={oneToManyHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Store = model.define("store", {
+ id: model.id().primaryKey(),
+ products: model.hasMany(() => Product),
+})
+
+const Product = model.define("product", {
+ id: model.id().primaryKey(),
+ store: model.belongsTo(() => Store, {
+ mappedBy: "products",
+ }),
+})
+```
+
+In this example, a store has many products, but a product belongs to one store.
+
+### Optional Relationship
+
+To make the relationship optional on the `belongsTo` side, use the `nullable` method on the property as explained in [this chapter](https://docs.medusajs.com/learn/fundamentals/data-models/properties#make-property-optional/index.html.md).
+
+### One-to-Many Relationship in the Database
+
+When you generate the migrations of data models that have a one-to-many relationship, the migration adds to the table of the data model that has the `belongsTo` property:
+
+1. A column of the format `{relation_name}_id` to store the ID of the record of the related data model. For example, the `product` table will have a `store_id` column.
+2. A foreign key on the `{relation_name}_id` column to the table of the related data model.
+
+
+
+***
+
+## Many-to-Many Relationship
+
+A many-to-many relationship indicates that many records of a data model can be associated with many records of another data model.
+
+To define a many-to-many relationship, create relationship properties in the data models using the `manyToMany` method.
+
+For example:
+
+```ts highlights={manyToManyHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const Order = model.define("order", {
+ id: model.id().primaryKey(),
+ products: model.manyToMany(() => Product, {
+ mappedBy: "orders",
+ pivotTable: "order_product",
+ joinColumn: "order_id",
+ inverseJoinColumn: "product_id",
+ }),
+})
+
+const Product = model.define("product", {
+ id: model.id().primaryKey(),
+ orders: model.manyToMany(() => Order, {
+ mappedBy: "products",
+ }),
+})
+```
+
+The `manyToMany` method accepts two parameters:
+
+1. A function that returns the associated data model.
+2. An object of optional configuration. Only one of the data models in the relation can define the `pivotTable`, `joinColumn`, and `inverseJoinColumn` configurations, and it's considered the owner data model. The object can accept the following properties:
+ - `mappedBy`: The name of the relationship property in the other data model. If not set, the property's name is inferred from the associated data model's name.
+ - `pivotTable`: The name of the pivot table created in the database for the many-to-many relation. If not set, the pivot table is inferred by combining the names of the data models' tables in alphabetical order, separating them by `_`, and pluralizing the last name. For example, `order_products`.
+ - `joinColumn`: The name of the column in the pivot table that points to the owner model's primary key.
+ - `inverseJoinColumn`: The name of the column in the pivot table that points to the owned model's primary key.
+
+The `pivotTable`, `joinColumn`, and `inverseJoinColumn` properties are only available after [Medusa v2.0.7](https://github.com/medusajs/medusa/releases/tag/v2.0.7).
+
+Following [Medusa v2.1.0](https://github.com/medusajs/medusa/releases/tag/v2.1.0), if `pivotTable`, `joinColumn`, and `inverseJoinColumn` aren't specified on either model, the owner is decided based on alphabetical order. So, in the example above, the `Order` data model would be the owner.
+
+In this example, an order is associated with many products, and a product is associated with many orders. Since the `pivotTable`, `joinColumn`, and `inverseJoinColumn` configurations are defined on the order, it's considered the owner data model.
+
+### Many-to-Many Relationship in the Database
+
+When you generate the migrations of data models that have a many-to-many relationship, the migration adds a new pivot table. Its name is either the name you specify in the `pivotTable` configuration or the inferred name combining the names of the data models' tables in alphabetical order, separating them by `_`, and pluralizing the last name. For example, `order_products`.
+
+The pivot table has a column with the name `{data_model}_id` for each of the data model's tables. It also has foreign keys on each of these columns to their respective tables.
+
+The pivot table has columns with foreign keys pointing to the primary key of the associated tables. The column's name is either:
+
+- The value of the `joinColumn` configuration for the owner table, and the `inverseJoinColumn` configuration for the owned table;
+- Or the inferred name `{table_name}_id`.
+
+
+
+### Many-To-Many with Custom Columns
+
+To add custom columns to the pivot table between two data models having a many-to-many relationship, you must define a new data model that represents the pivot table.
+
+For example:
+
+```ts highlights={manyToManyColumnHighlights}
+import { model } from "@medusajs/framework/utils"
+
+export const Order = model.define("order_test", {
+ id: model.id().primaryKey(),
+ products: model.manyToMany(() => Product, {
+ pivotEntity: () => OrderProduct,
+ }),
+})
+
+export const Product = model.define("product_test", {
+ id: model.id().primaryKey(),
+ orders: model.manyToMany(() => Order),
+})
+
+export const OrderProduct = model.define("orders_products", {
+ id: model.id().primaryKey(),
+ order: model.belongsTo(() => Order, {
+ mappedBy: "products",
+ }),
+ product: model.belongsTo(() => Product, {
+ mappedBy: "orders",
+ }),
+ metadata: model.json().nullable(),
+})
+```
+
+The `Order` and `Product` data models have a many-to-many relationship. To add extra columns to the created pivot table, you pass a `pivotEntity` option to the `products` relation in `Order` (since `Order` is the owner). The value of `pivotEntity` is a function that returns the data model representing the pivot table.
+
+The `OrderProduct` model defines, aside from the ID, the following properties:
+
+- `order`: A relation that indicates this model belongs to the `Order` data model. You set the `mappedBy` option to the many-to-many relation's name in the `Order` data model.
+- `product`: A relation that indicates this model belongs to the `Product` data model. You set the `mappedBy` option to the many-to-many relation's name in the `Product` data model.
+- `metadata`: An extra column to add to the pivot table of type `json`. You can add other columns as well to the model.
+
+***
+
+## Set Relationship Name in the Other Model
+
+The relationship property methods accept as a second parameter an object of options. The `mappedBy` property defines the name of the relationship in the other data model.
+
+This is useful if the relationship property’s name is different from that of the associated data model.
+
+As seen in previous examples, the `mappedBy` option is required for the `belongsTo` method.
+
+For example:
+
+```ts highlights={relationNameHighlights}
+import { model } from "@medusajs/framework/utils"
+
+const User = model.define("user", {
+ id: model.id().primaryKey(),
+ email: model.hasOne(() => Email, {
+ mappedBy: "owner",
+ }),
+})
+
+const Email = model.define("email", {
+ id: model.id().primaryKey(),
+ owner: model.belongsTo(() => User, {
+ mappedBy: "email",
+ }),
+})
+```
+
+In this example, you specify in the `User` data model’s relationship property that the name of the relationship in the `Email` data model is `owner`.
+
+***
+
+## Cascades
+
+When an operation is performed on a data model, such as record deletion, the relationship cascade specifies what related data model records should be affected by it.
+
+For example, if a store is deleted, its products should also be deleted.
+
+The `cascades` method used on a data model configures which child records an operation is cascaded to.
+
+For example:
+
+```ts highlights={highlights}
+import { model } from "@medusajs/framework/utils"
+
+const Store = model.define("store", {
+ id: model.id().primaryKey(),
+ products: model.hasMany(() => Product),
+})
+.cascades({
+ delete: ["products"],
+})
+
+const Product = model.define("product", {
+ id: model.id().primaryKey(),
+ store: model.belongsTo(() => Store, {
+ mappedBy: "products",
+ }),
+})
+```
+
+The `cascades` method accepts an object. Its key is the operation’s name, such as `delete`. The value is an array of relationship property names that the operation is cascaded to.
+
+In the example above, when a store is deleted, its associated products are also deleted.
+
+
+# Migrations
+
+In this chapter, you'll learn what a migration is and how to generate a migration or write it manually.
+
+## What is a Migration?
+
+A migration is a TypeScript or JavaScript file that defines database changes made by a module. Migrations are useful when you re-use a module or you're working in a team, so that when one member of a team makes a database change, everyone else can reflect it on their side by running the migrations.
+
+The migration's file has a class with two methods:
+
+- The `up` method reflects changes on the database.
+- The `down` method reverts the changes made in the `up` method.
+
+***
+
+## Generate Migration
+
+Instead of you writing the migration manually, the Medusa CLI tool provides a [db:generate](https://docs.medusajs.com/resources/medusa-cli/commands/db#dbgenerate/index.html.md) command to generate a migration for a modules' data models.
+
+For example, assuming you have a `blog` Module, you can generate a migration for it by running the following command:
+
+```bash
+npx medusa db:generate blog
+```
+
+This generates a migration file under the `migrations` directory of the Blog Module. You can then run it to reflect the changes in the database as mentioned in [this section](#run-the-migration).
+
+***
+
+## Write a Migration Manually
+
+You can also write migrations manually. To do that, create a file in the `migrations` directory of the module and in it, a class that has an `up` and `down` method. The class's name should be of the format `Migration{YEAR}{MONTH}{DAY}{HOUR}{MINUTE}.ts` to ensure migrations are ran in the correct order.
+
+For example:
+
+```ts title="src/modules/blog/migrations/Migration202507021059.ts"
+import { Migration } from "@mikro-orm/migrations"
+
+export class Migration202507021059 extends Migration {
+
+ async up(): Promise {
+ this.addSql("create table if not exists \"author\" (\"id\" text not null, \"name\" text not null, \"created_at\" timestamptz not null default now(), \"updated_at\" timestamptz not null default now(), \"deleted_at\" timestamptz null, constraint \"author_pkey\" primary key (\"id\"));")
+ }
+
+ async down(): Promise {
+ this.addSql("drop table if exists \"author\" cascade;")
+ }
+
+}
+```
+
+The migration class in the file extends the `Migration` class imported from `@mikro-orm/migrations`. In the `up` and `down` method of the migration class, you use the `addSql` method provided by MikroORM's `Migration` class to run PostgreSQL syntax.
+
+In the example above, the `up` method creates the table `author`, and the `down` method drops the table if the migration is reverted.
+
+Refer to [MikroORM's documentation](https://mikro-orm.io/docs/migrations#migration-class) for more details on writing migrations.
+
+***
+
+## Run the Migration
+
+To run your migration, run the following command:
+
+This command also syncs module links. If you don't want that, use the `--skip-links` option.
+
+```bash
npx medusa db:migrate
```
-The migrations in your application, including your plugin, will run and update the database.
+This reflects the changes in the database as implemented in the migration's `up` method.
-### Importing Module Resources
+***
-In the [Prepare Plugin](#2-prepare-plugin) section, you learned about [exported resources](#package-exports) in your plugin.
+## Rollback the Migration
-These exports allow you to import your plugin resources in your Medusa application, including workflows, links and modules.
+To rollback or revert the last migration you ran for a module, run the following command:
-For example, to import the plugin's workflow in your Medusa application:
-
-`@myorg/plugin-name` is the plugin package's name.
-
-```ts
-import { Workflow1, Workflow2 } from "@myorg/plugin-name/workflows"
-import BlogModule from "@myorg/plugin-name/modules/blog"
-// import other files created in plugin like ./src/types/blog.ts
-import BlogType from "@myorg/plugin-name/types/blog"
+```bash
+npx medusa db:rollback blog
```
-### Create Module Providers
+This rolls back the last ran migration on the Blog Module.
-The [exported resources](#package-exports) also allow you to import module providers in your plugin and register them in the Medusa application's configuration. A module provider is a module that provides the underlying logic or integration related to a commerce or architectural module.
+### Caution: Rollback Migration before Deleting
-For example, assuming your plugin has a [Notification Module Provider](https://docs.medusajs.com/resources/architectural-modules/notification/index.html.md) called `my-notification`, you can register it in your Medusa application's configuration like this:
+If you need to delete a migration file, make sure to rollback the migration first. Otherwise, you might encounter issues when generating and running new migrations.
-`@myorg/plugin-name` is the plugin package's name.
+For example, if you delete the migration of the Blog Module, then try to create a new one, Medusa will create a brand new migration that re-creates the tables or indices. If those are still in the database, you might encounter errors.
+
+So, always rollback the migration before deleting it.
+
+***
+
+## More Database Commands
+
+To learn more about the Medusa CLI's database commands, refer to [this CLI reference](https://docs.medusajs.com/resources/medusa-cli/commands/db/index.html.md).
+
+
+# Event Data Payload
+
+In this chapter, you'll learn how subscribers receive an event's data payload.
+
+## Access Event's Data Payload
+
+When events are emitted, they’re emitted with a data payload.
+
+The object that the subscriber function receives as a parameter has an `event` property, which is an object holding the event payload in a `data` property with additional context.
+
+For example:
+
+```ts title="src/subscribers/product-created.ts" highlights={highlights} collapsibleLines="1-5" expandButtonLabel="Show Imports"
+import type {
+ SubscriberArgs,
+ SubscriberConfig,
+} from "@medusajs/framework"
+
+export default async function productCreateHandler({
+ event,
+}: SubscriberArgs<{ id: string }>) {
+ const productId = event.data.id
+ console.log(`The product ${productId} was created`)
+}
+
+export const config: SubscriberConfig = {
+ event: "product.created",
+}
+```
+
+The `event` object has the following properties:
+
+- data: (\`object\`) The data payload of the event. Its properties are different for each event.
+- name: (string) The name of the triggered event.
+- metadata: (\`object\`) Additional data and context of the emitted event.
+
+This logs the product ID received in the `product.created` event’s data payload to the console.
+
+{/* ---
+
+## List of Events with Data Payload
+
+Refer to [this reference](!resources!/events-reference) for a full list of events emitted by Medusa and their data payloads. */}
+
+
+# Emit Workflow and Service Events
+
+In this chapter, you'll learn about event types and how to emit an event in a service or workflow.
+
+## Event Types
+
+In your customization, you can emit an event, then listen to it in a subscriber and perform an asynchronus action, such as send a notification or data to a third-party system.
+
+There are two types of events in Medusa:
+
+1. Workflow event: an event that's emitted in a workflow after a commerce feature is performed. For example, Medusa emits the `order.placed` event after a cart is completed.
+2. Service event: an event that's emitted to track, trace, or debug processes under the hood. For example, you can emit an event with an audit trail.
+
+### Which Event Type to Use?
+
+**Workflow events** are the most common event type in development, as most custom features and customizations are built around workflows.
+
+Some examples of workflow events:
+
+1. When a user creates a blog post and you're emitting an event to send a newsletter email.
+2. When you finish syncing products to a third-party system and you want to notify the admin user of new products added.
+3. When a customer purchases a digital product and you want to generate and send it to them.
+
+You should only go for a **service event** if you're emitting an event for processes under the hood that don't directly affect front-facing features.
+
+Some examples of service events:
+
+1. When you're tracing data manipulation and changes, and you want to track every time some custom data is changed.
+2. When you're syncing data with a search engine.
+
+***
+
+## Emit Event in a Workflow
+
+To emit a workflow event, use the `emitEventStep` helper step provided in the `@medusajs/medusa/core-flows` package.
+
+For example:
+
+```ts highlights={highlights}
+import {
+ createWorkflow,
+} from "@medusajs/framework/workflows-sdk"
+import {
+ emitEventStep,
+} from "@medusajs/medusa/core-flows"
+
+const helloWorldWorkflow = createWorkflow(
+ "hello-world",
+ () => {
+ // ...
+
+ emitEventStep({
+ eventName: "custom.created",
+ data: {
+ id: "123",
+ // other data payload
+ },
+ })
+ }
+)
+```
+
+The `emitEventStep` accepts an object having the following properties:
+
+- `eventName`: The event's name.
+- `data`: The data payload as an object. You can pass any properties in the object, and subscribers listening to the event will receive this data in the event's payload.
+
+In this example, you emit the event `custom.created` and pass in the data payload an ID property.
+
+### Test it Out
+
+If you execute the workflow, the event is emitted and you can see it in your application's logs.
+
+Any subscribers listening to the event are executed.
+
+***
+
+## Emit Event in a Service
+
+To emit a service event:
+
+1. Resolve `event_bus` from the module's container in your service's constructor:
+
+### Extending Service Factory
+
+```ts title="src/modules/blog/service.ts" highlights={["9"]}
+import { IEventBusService } from "@medusajs/framework/types"
+import { MedusaService } from "@medusajs/framework/utils"
+
+class BlogModuleService extends MedusaService({
+ Post,
+}){
+ protected eventBusService_: AbstractEventBusModuleService
+
+ constructor({ event_bus }) {
+ super(...arguments)
+ this.eventBusService_ = event_bus
+ }
+}
+```
+
+### Without Service Factory
+
+```ts title="src/modules/blog/service.ts" highlights={["6"]}
+import { IEventBusService } from "@medusajs/framework/types"
+
+class BlogModuleService {
+ protected eventBusService_: AbstractEventBusModuleService
+
+ constructor({ event_bus }) {
+ this.eventBusService_ = event_bus
+ }
+}
+```
+
+2. Use the event bus service's `emit` method in the service's methods to emit an event:
+
+```ts title="src/modules/blog/service.ts" highlights={serviceHighlights}
+class BlogModuleService {
+ // ...
+ performAction() {
+ // TODO perform action
+
+ this.eventBusService_.emit({
+ name: "custom.event",
+ data: {
+ id: "123",
+ // other data payload
+ },
+ })
+ }
+}
+```
+
+The method accepts an object having the following properties:
+
+- `name`: The event's name.
+- `data`: The data payload as an object. You can pass any properties in the object, and subscribers listening to the event will receive this data in the event's payload.
+
+3. By default, the Event Module's service isn't injected into your module's container. To add it to the container, pass it in the module's registration object in `medusa-config.ts` in the `dependencies` property:
+
+```ts title="medusa-config.ts" highlights={depsHighlight}
+import { Modules } from "@medusajs/framework/utils"
-```ts highlights={[["9"]]} title="medusa-config.ts"
module.exports = defineConfig({
// ...
modules: [
{
- resolve: "@medusajs/medusa/notification",
- options: {
- providers: [
- {
- resolve: "@myorg/plugin-name/providers/my-notification",
- id: "my-notification",
- options: {
- channels: ["email"],
- // provider options...
- },
- },
- ],
- },
+ resolve: "./src/modules/blog",
+ dependencies: [
+ Modules.EVENT_BUS,
+ ],
},
],
})
```
-You pass to `resolve` the path to the provider relative to the plugin package. So, in this example, the `my-notification` provider is located in `./src/providers/my-notification/index.ts` of the plugin.
+The `dependencies` property accepts an array of module registration keys. The specified modules' main services are injected into the module's container.
-To learn how to create module providers, refer to the following guides:
+That's how you can resolve it in your module's main service's constructor.
-- [File Module Provider](https://docs.medusajs.com/resources/references/file-provider-module/index.html.md)
-- [Notification Module Provider](https://docs.medusajs.com/resources/references/notification-provider-module/index.html.md)
-- [Auth Module Provider](https://docs.medusajs.com/resources/references/auth/provider/index.html.md)
-- [Payment Module Provider](https://docs.medusajs.com/resources/references/payment/provider/index.html.md)
-- [Fulfillment Module Provider](https://docs.medusajs.com/resources/references/fulfillment/provider/index.html.md)
-- [Tax Module Provider](https://docs.medusajs.com/resources/references/tax/provider/index.html.md)
+### Test it Out
-***
+If you execute the `performAction` method of your service, the event is emitted and you can see it in your application's logs.
-## 5. Publish Plugin to NPM
-
-Make sure to add the keywords mentioned in the [Package Keywords](#package-keywords) section in your plugin's `package.json` file.
-
-Medusa's CLI tool provides a command that bundles your plugin to be published to npm. Once you're ready to publish your plugin publicly, run the following command in your plugin project:
-
-```bash
-npx medusa plugin:build
-```
-
-The command will compile an output in the `.medusa/server` directory.
-
-You can now publish the plugin to npm using the [NPM CLI tool](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm). Run the following command to publish the plugin to npm:
-
-```bash
-npm publish
-```
-
-If you haven't logged in before with your NPM account, you'll be asked to log in first. Then, your package is published publicly to be used in any Medusa application.
-
-### Install Public Plugin in Medusa Application
-
-You install a plugin that's published publicly using your package manager. For example:
-
-```bash npm2yarn
-npm install @myorg/plugin-name
-```
-
-Where `@myorg/plugin-name` is the name of your plugin as published on NPM.
-
-Then, register the plugin in your Medusa application's configurations as explained in [this section](#register-plugin-in-medusa-application).
-
-***
-
-## Update a Published Plugin
-
-To update the Medusa dependencies in a plugin, refer to [this documentation](https://docs.medusajs.com/learn/update#update-plugin-project/index.html.md).
-
-If you've published a plugin and you've made changes to it, you'll have to publish the update to NPM again.
-
-First, run the following command to change the version of the plugin:
-
-```bash
-npm version
-```
-
-Where `` indicates the type of version update you’re publishing. For example, it can be `major` or `minor`. Refer to the [npm version documentation](https://docs.npmjs.com/cli/v10/commands/npm-version) for more information.
-
-Then, re-run the same commands for publishing a plugin:
-
-```bash
-npx medusa plugin:build
-npm publish
-```
-
-This will publish an updated version of your plugin under a new version.
+Any subscribers listening to the event are also executed.
# Add Columns to a Link Table
@@ -11018,36 +11343,6 @@ await link.create({
```
-# Scheduled Jobs Number of Executions
-
-In this chapter, you'll learn how to set a limit on the number of times a scheduled job is executed.
-
-## numberOfExecutions Option
-
-The export configuration object of the scheduled job accepts an optional property `numberOfExecutions`. Its value is a number indicating how many times the scheduled job can be executed during the Medusa application's runtime.
-
-For example:
-
-```ts highlights={highlights}
-export default async function myCustomJob() {
- console.log("I'll be executed three times only.")
-}
-
-export const config = {
- name: "hello-world",
- // execute every minute
- schedule: "* * * * *",
- numberOfExecutions: 3,
-}
-```
-
-The above scheduled job has the `numberOfExecutions` configuration set to `3`.
-
-So, it'll only execute 3 times, each every minute, then it won't be executed anymore.
-
-If you restart the Medusa application, the scheduled job will be executed again until reaching the number of executions specified.
-
-
# Module Link Direction
In this chapter, you'll learn about the difference in module link directions, and which to use based on your use case.
@@ -11109,436 +11404,6 @@ export default defineLink(
```
-# Link
-
-In this chapter, you’ll learn what Link is and how to use it to manage links.
-
-As of [Medusa v2.2.0](https://github.com/medusajs/medusa/releases/tag/v2.2.0), Remote Link has been deprecated in favor of Link. They have the same usage, so you only need to change the key used to resolve the tool from the Medusa container as explained below.
-
-## What is Link?
-
-Link is a class with utility methods to manage links between data models. It’s registered in the Medusa container under the `link` registration name.
-
-For example:
-
-```ts collapsibleLines="1-9" expandButtonLabel="Show Imports"
-import {
- MedusaRequest,
- MedusaResponse,
-} from "@medusajs/framework/http"
-import {
- ContainerRegistrationKeys,
-} from "@medusajs/framework/utils"
-
-export async function POST(
- req: MedusaRequest,
- res: MedusaResponse
-): Promise {
- const link = req.scope.resolve(
- ContainerRegistrationKeys.LINK
- )
-
- // ...
-}
-```
-
-You can use its methods to manage links, such as create or delete links.
-
-***
-
-## Create Link
-
-To create a link between records of two data models, use the `create` method of Link.
-
-For example:
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await link.create({
- [Modules.PRODUCT]: {
- product_id: "prod_123",
- },
- "helloModuleService": {
- my_custom_id: "mc_123",
- },
-})
-```
-
-The `create` method accepts as a parameter an object. The object’s keys are the names of the linked modules.
-
-The keys (names of linked modules) must be in the same [direction](https://docs.medusajs.com/learn/fundamentals/module-links/directions/index.html.md) of the link definition.
-
-The value of each module’s property is an object, whose keys are of the format `{data_model_snake_name}_id`, and values are the IDs of the linked record.
-
-So, in the example above, you link a record of the `MyCustom` data model in a `hello` module to a `Product` record in the Product Module.
-
-### Enforced Integrity Constraints on Link Creation
-
-Medusa enforces integrity constraints on links based on the link's relation type. So, an error is thrown in the following scenarios:
-
-- If the link is one-to-one and one of the linked records already has a link to another record of the same data model. For example:
-
-```ts
-// no error
-await link.create({
- [Modules.PRODUCT]: {
- product_id: "prod_123",
- },
- "helloModuleService": {
- my_custom_id: "mc_123",
- },
-})
-
-// throws an error because `prod_123` already has a link to `mc_123`
-await link.create({
- [Modules.PRODUCT]: {
- product_id: "prod_123",
- },
- "helloModuleService": {
- my_custom_id: "mc_456",
- },
-})
-```
-
-- If the link is one-to-many and the "one" side already has a link to another record of the same data model. For example, if a product can have many `MyCustom` records, but a `MyCustom` record can only have one product:
-
-```ts
-// no error
-await link.create({
- [Modules.PRODUCT]: {
- product_id: "prod_123",
- },
- "helloModuleService": {
- my_custom_id: "mc_123",
- },
-})
-
-// also no error
-await link.create({
- [Modules.PRODUCT]: {
- product_id: "prod_123",
- },
- "helloModuleService": {
- my_custom_id: "mc_456",
- },
-})
-
-// throws an error because `mc_123` already has a link to `prod_123`
-await link.create({
- [Modules.PRODUCT]: {
- product_id: "prod_456",
- },
- "helloModuleService": {
- my_custom_id: "mc_123",
- },
-})
-```
-
-There are no integrity constraints in a many-to-many link, so you can create multiple links between the same records.
-
-***
-
-## Dismiss Link
-
-To remove a link between records of two data models, use the `dismiss` method of Link.
-
-For example:
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await link.dismiss({
- [Modules.PRODUCT]: {
- product_id: "prod_123",
- },
- "helloModuleService": {
- my_custom_id: "mc_123",
- },
-})
-```
-
-The `dismiss` method accepts the same parameter type as the [create method](#create-link).
-
-The keys (names of linked modules) must be in the same [direction](https://docs.medusajs.com/learn/fundamentals/module-links/directions/index.html.md) of the link definition.
-
-***
-
-## Cascade Delete Linked Records
-
-If a record is deleted, use the `delete` method of Link to delete all linked records.
-
-For example:
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await productModuleService.deleteVariants([variant.id])
-
-await link.delete({
- [Modules.PRODUCT]: {
- product_id: "prod_123",
- },
-})
-```
-
-This deletes all records linked to the deleted product.
-
-***
-
-## Restore Linked Records
-
-If a record that was previously soft-deleted is now restored, use the `restore` method of Link to restore all linked records.
-
-For example:
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await productModuleService.restoreProducts(["prod_123"])
-
-await link.restore({
- [Modules.PRODUCT]: {
- product_id: "prod_123",
- },
-})
-```
-
-
-# Query Context
-
-In this chapter, you'll learn how to pass contexts when retrieving data with [Query](https://docs.medusajs.com/learn/fundamentals/module-links/query/index.html.md).
-
-## What is Query Context?
-
-Query context is a way to pass additional information when retrieving data with Query. This data can be useful when applying custom transformations to the retrieved data based on the current context.
-
-For example, consider you have a Blog Module with posts and authors. You can accept the user's language as a context and return the posts in the user's language. Another example is how Medusa uses Query Context to [retrieve product variants' prices based on the customer's currency](https://docs.medusajs.com/resources/commerce-modules/product/guides/price/index.html.md).
-
-***
-
-## How to Use Query Context
-
-The `query.graph` method accepts an optional `context` parameter that can be used to pass additional context either to the data model you're retrieving (for example, `post`), or its related and linked models (for example, `author`).
-
-You initialize a context using `QueryContext` from the Modules SDK. It accepts an object of contexts as an argument.
-
-For example, to retrieve posts using Query while passing the user's language as a context:
-
-```ts
-const { data } = await query.graph({
- entity: "post",
- fields: ["*"],
- context: QueryContext({
- lang: "es",
- }),
-})
-```
-
-In this example, you pass in the context a `lang` property whose value is `es`.
-
-Then, to handle the context while retrieving records of the data model, in the associated module's service you override the generated `list` method of the data model.
-
-For example, continuing the example above, you can override the `listPosts` method of the Blog Module's service to handle the context:
-
-```ts highlights={highlights2}
-import { MedusaContext, MedusaService } from "@medusajs/framework/utils"
-import { Context, FindConfig } from "@medusajs/framework/types"
-import Post from "./models/post"
-import Author from "./models/author"
-
-class BlogModuleService extends MedusaService({
- Post,
- Author,
-}){
- // @ts-ignore
- async listPosts(
- filters?: any,
- config?: FindConfig | undefined,
- @MedusaContext() sharedContext?: Context | undefined
- ) {
- const context = filters.context ?? {}
- delete filters.context
-
- let posts = await super.listPosts(filters, config, sharedContext)
-
- if (context.lang === "es") {
- posts = posts.map((post) => {
- return {
- ...post,
- title: post.title + " en español",
- }
- })
- }
-
- return posts
- }
-}
-
-export default BlogModuleService
-```
-
-In the above example, you override the generated `listPosts` method. This method receives as a first parameter the filters passed to the query, but it also includes a `context` property that holds the context passed to the query.
-
-You extract the context from `filters`, then retrieve the posts using the parent's `listPosts` method. After that, if the language is set in the context, you transform the titles of the posts.
-
-All posts returned will now have their titles appended with "en español".
-
-Learn more about the generated `list` method in [this reference](https://docs.medusajs.com/resources/service-factory-reference/methods/list/index.html.md).
-
-### Using Pagination with Query
-
-If you pass pagination fields to `query.graph`, you must also override the `listAndCount` method in the service.
-
-For example, following along with the previous example, you must override the `listAndCountPosts` method of the Blog Module's service:
-
-```ts
-import { MedusaContext, MedusaService } from "@medusajs/framework/utils"
-import { Context, FindConfig } from "@medusajs/framework/types"
-import Post from "./models/post"
-import Author from "./models/author"
-
-class BlogModuleService extends MedusaService({
- Post,
- Author,
-}){
- // @ts-ignore
- async listAndCountPosts(
- filters?: any,
- config?: FindConfig | undefined,
- @MedusaContext() sharedContext?: Context | undefined
- ) {
- const context = filters.context ?? {}
- delete filters.context
-
- const result = await super.listAndCountPosts(
- filters,
- config,
- sharedContext
- )
-
- if (context.lang === "es") {
- result.posts = posts.map((post) => {
- return {
- ...post,
- title: post.title + " en español",
- }
- })
- }
-
- return result
- }
-}
-
-export default BlogModuleService
-```
-
-Now, the `listAndCountPosts` method will handle the context passed to `query.graph` when you pass pagination fields. You can also move the logic to transform the posts' titles to a separate method and call it from both `listPosts` and `listAndCountPosts`.
-
-***
-
-## Passing Query Context to Related Data Models
-
-If you're retrieving a data model and you want to pass context to its associated model in the same module, you can pass them as part of `QueryContext`'s parameter, then handle them in the same `list` method.
-
-For linked data models, check out the [next section](#passing-query-context-to-linked-data-models).
-
-For example, to pass a context for the post's authors:
-
-```ts highlights={highlights3}
-const { data } = await query.graph({
- entity: "post",
- fields: ["*"],
- context: QueryContext({
- lang: "es",
- author: QueryContext({
- lang: "es",
- }),
- }),
-})
-```
-
-Then, in the `listPosts` method, you can handle the context for the post's authors:
-
-```ts highlights={highlights4}
-import { MedusaContext, MedusaService } from "@medusajs/framework/utils"
-import { Context, FindConfig } from "@medusajs/framework/types"
-import Post from "./models/post"
-import Author from "./models/author"
-
-class BlogModuleService extends MedusaService({
- Post,
- Author,
-}){
- // @ts-ignore
- async listPosts(
- filters?: any,
- config?: FindConfig | undefined,
- @MedusaContext() sharedContext?: Context | undefined
- ) {
- const context = filters.context ?? {}
- delete filters.context
-
- let posts = await super.listPosts(filters, config, sharedContext)
-
- const isPostLangEs = context.lang === "es"
- const isAuthorLangEs = context.author?.lang === "es"
-
- if (isPostLangEs || isAuthorLangEs) {
- posts = posts.map((post) => {
- return {
- ...post,
- title: isPostLangEs ? post.title + " en español" : post.title,
- author: {
- ...post.author,
- name: isAuthorLangEs ? post.author.name + " en español" : post.author.name,
- },
- }
- })
- }
-
- return posts
- }
-}
-
-export default BlogModuleService
-```
-
-The context in `filters` will also have the context for `author`, which you can use to make transformations to the post's authors.
-
-***
-
-## Passing Query Context to Linked Data Models
-
-If you're retrieving a data model and you want to pass context to a linked model in a different module, pass to the `context` property an object instead, where its keys are the linked model's name and the values are the context for that linked model.
-
-For example, consider the Product Module's `Product` data model is linked to the Blog Module's `Post` data model. You can pass context to the `Post` data model while retrieving products like so:
-
-```ts highlights={highlights5}
-const { data } = await query.graph({
- entity: "product",
- fields: ["*", "post.*"],
- context: {
- post: QueryContext({
- lang: "es",
- }),
- },
-})
-```
-
-In this example, you retrieve products and their associated posts. You also pass a context for `post`, indicating the customer's language.
-
-To handle the context, you override the generated `listPosts` method of the Blog Module as explained [previously](#how-to-use-query-context).
-
-
# Query
In this chapter, you’ll learn about Query and how to use it to fetch data from modules.
@@ -12090,6 +11955,436 @@ Try passing one of the Query configuration parameters, like `fields` or `limit`,
Learn more about [specifing fields and relations](https://docs.medusajs.com/api/store#select-fields-and-relations) and [pagination](https://docs.medusajs.com/api/store#pagination) in the API reference.
+# Link
+
+In this chapter, you’ll learn what Link is and how to use it to manage links.
+
+As of [Medusa v2.2.0](https://github.com/medusajs/medusa/releases/tag/v2.2.0), Remote Link has been deprecated in favor of Link. They have the same usage, so you only need to change the key used to resolve the tool from the Medusa container as explained below.
+
+## What is Link?
+
+Link is a class with utility methods to manage links between data models. It’s registered in the Medusa container under the `link` registration name.
+
+For example:
+
+```ts collapsibleLines="1-9" expandButtonLabel="Show Imports"
+import {
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import {
+ ContainerRegistrationKeys,
+} from "@medusajs/framework/utils"
+
+export async function POST(
+ req: MedusaRequest,
+ res: MedusaResponse
+): Promise {
+ const link = req.scope.resolve(
+ ContainerRegistrationKeys.LINK
+ )
+
+ // ...
+}
+```
+
+You can use its methods to manage links, such as create or delete links.
+
+***
+
+## Create Link
+
+To create a link between records of two data models, use the `create` method of Link.
+
+For example:
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await link.create({
+ [Modules.PRODUCT]: {
+ product_id: "prod_123",
+ },
+ "helloModuleService": {
+ my_custom_id: "mc_123",
+ },
+})
+```
+
+The `create` method accepts as a parameter an object. The object’s keys are the names of the linked modules.
+
+The keys (names of linked modules) must be in the same [direction](https://docs.medusajs.com/learn/fundamentals/module-links/directions/index.html.md) of the link definition.
+
+The value of each module’s property is an object, whose keys are of the format `{data_model_snake_name}_id`, and values are the IDs of the linked record.
+
+So, in the example above, you link a record of the `MyCustom` data model in a `hello` module to a `Product` record in the Product Module.
+
+### Enforced Integrity Constraints on Link Creation
+
+Medusa enforces integrity constraints on links based on the link's relation type. So, an error is thrown in the following scenarios:
+
+- If the link is one-to-one and one of the linked records already has a link to another record of the same data model. For example:
+
+```ts
+// no error
+await link.create({
+ [Modules.PRODUCT]: {
+ product_id: "prod_123",
+ },
+ "helloModuleService": {
+ my_custom_id: "mc_123",
+ },
+})
+
+// throws an error because `prod_123` already has a link to `mc_123`
+await link.create({
+ [Modules.PRODUCT]: {
+ product_id: "prod_123",
+ },
+ "helloModuleService": {
+ my_custom_id: "mc_456",
+ },
+})
+```
+
+- If the link is one-to-many and the "one" side already has a link to another record of the same data model. For example, if a product can have many `MyCustom` records, but a `MyCustom` record can only have one product:
+
+```ts
+// no error
+await link.create({
+ [Modules.PRODUCT]: {
+ product_id: "prod_123",
+ },
+ "helloModuleService": {
+ my_custom_id: "mc_123",
+ },
+})
+
+// also no error
+await link.create({
+ [Modules.PRODUCT]: {
+ product_id: "prod_123",
+ },
+ "helloModuleService": {
+ my_custom_id: "mc_456",
+ },
+})
+
+// throws an error because `mc_123` already has a link to `prod_123`
+await link.create({
+ [Modules.PRODUCT]: {
+ product_id: "prod_456",
+ },
+ "helloModuleService": {
+ my_custom_id: "mc_123",
+ },
+})
+```
+
+There are no integrity constraints in a many-to-many link, so you can create multiple links between the same records.
+
+***
+
+## Dismiss Link
+
+To remove a link between records of two data models, use the `dismiss` method of Link.
+
+For example:
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await link.dismiss({
+ [Modules.PRODUCT]: {
+ product_id: "prod_123",
+ },
+ "helloModuleService": {
+ my_custom_id: "mc_123",
+ },
+})
+```
+
+The `dismiss` method accepts the same parameter type as the [create method](#create-link).
+
+The keys (names of linked modules) must be in the same [direction](https://docs.medusajs.com/learn/fundamentals/module-links/directions/index.html.md) of the link definition.
+
+***
+
+## Cascade Delete Linked Records
+
+If a record is deleted, use the `delete` method of Link to delete all linked records.
+
+For example:
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await productModuleService.deleteVariants([variant.id])
+
+await link.delete({
+ [Modules.PRODUCT]: {
+ product_id: "prod_123",
+ },
+})
+```
+
+This deletes all records linked to the deleted product.
+
+***
+
+## Restore Linked Records
+
+If a record that was previously soft-deleted is now restored, use the `restore` method of Link to restore all linked records.
+
+For example:
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await productModuleService.restoreProducts(["prod_123"])
+
+await link.restore({
+ [Modules.PRODUCT]: {
+ product_id: "prod_123",
+ },
+})
+```
+
+
+# Query Context
+
+In this chapter, you'll learn how to pass contexts when retrieving data with [Query](https://docs.medusajs.com/learn/fundamentals/module-links/query/index.html.md).
+
+## What is Query Context?
+
+Query context is a way to pass additional information when retrieving data with Query. This data can be useful when applying custom transformations to the retrieved data based on the current context.
+
+For example, consider you have a Blog Module with posts and authors. You can accept the user's language as a context and return the posts in the user's language. Another example is how Medusa uses Query Context to [retrieve product variants' prices based on the customer's currency](https://docs.medusajs.com/resources/commerce-modules/product/guides/price/index.html.md).
+
+***
+
+## How to Use Query Context
+
+The `query.graph` method accepts an optional `context` parameter that can be used to pass additional context either to the data model you're retrieving (for example, `post`), or its related and linked models (for example, `author`).
+
+You initialize a context using `QueryContext` from the Modules SDK. It accepts an object of contexts as an argument.
+
+For example, to retrieve posts using Query while passing the user's language as a context:
+
+```ts
+const { data } = await query.graph({
+ entity: "post",
+ fields: ["*"],
+ context: QueryContext({
+ lang: "es",
+ }),
+})
+```
+
+In this example, you pass in the context a `lang` property whose value is `es`.
+
+Then, to handle the context while retrieving records of the data model, in the associated module's service you override the generated `list` method of the data model.
+
+For example, continuing the example above, you can override the `listPosts` method of the Blog Module's service to handle the context:
+
+```ts highlights={highlights2}
+import { MedusaContext, MedusaService } from "@medusajs/framework/utils"
+import { Context, FindConfig } from "@medusajs/framework/types"
+import Post from "./models/post"
+import Author from "./models/author"
+
+class BlogModuleService extends MedusaService({
+ Post,
+ Author,
+}){
+ // @ts-ignore
+ async listPosts(
+ filters?: any,
+ config?: FindConfig | undefined,
+ @MedusaContext() sharedContext?: Context | undefined
+ ) {
+ const context = filters.context ?? {}
+ delete filters.context
+
+ let posts = await super.listPosts(filters, config, sharedContext)
+
+ if (context.lang === "es") {
+ posts = posts.map((post) => {
+ return {
+ ...post,
+ title: post.title + " en español",
+ }
+ })
+ }
+
+ return posts
+ }
+}
+
+export default BlogModuleService
+```
+
+In the above example, you override the generated `listPosts` method. This method receives as a first parameter the filters passed to the query, but it also includes a `context` property that holds the context passed to the query.
+
+You extract the context from `filters`, then retrieve the posts using the parent's `listPosts` method. After that, if the language is set in the context, you transform the titles of the posts.
+
+All posts returned will now have their titles appended with "en español".
+
+Learn more about the generated `list` method in [this reference](https://docs.medusajs.com/resources/service-factory-reference/methods/list/index.html.md).
+
+### Using Pagination with Query
+
+If you pass pagination fields to `query.graph`, you must also override the `listAndCount` method in the service.
+
+For example, following along with the previous example, you must override the `listAndCountPosts` method of the Blog Module's service:
+
+```ts
+import { MedusaContext, MedusaService } from "@medusajs/framework/utils"
+import { Context, FindConfig } from "@medusajs/framework/types"
+import Post from "./models/post"
+import Author from "./models/author"
+
+class BlogModuleService extends MedusaService({
+ Post,
+ Author,
+}){
+ // @ts-ignore
+ async listAndCountPosts(
+ filters?: any,
+ config?: FindConfig | undefined,
+ @MedusaContext() sharedContext?: Context | undefined
+ ) {
+ const context = filters.context ?? {}
+ delete filters.context
+
+ const result = await super.listAndCountPosts(
+ filters,
+ config,
+ sharedContext
+ )
+
+ if (context.lang === "es") {
+ result.posts = posts.map((post) => {
+ return {
+ ...post,
+ title: post.title + " en español",
+ }
+ })
+ }
+
+ return result
+ }
+}
+
+export default BlogModuleService
+```
+
+Now, the `listAndCountPosts` method will handle the context passed to `query.graph` when you pass pagination fields. You can also move the logic to transform the posts' titles to a separate method and call it from both `listPosts` and `listAndCountPosts`.
+
+***
+
+## Passing Query Context to Related Data Models
+
+If you're retrieving a data model and you want to pass context to its associated model in the same module, you can pass them as part of `QueryContext`'s parameter, then handle them in the same `list` method.
+
+For linked data models, check out the [next section](#passing-query-context-to-linked-data-models).
+
+For example, to pass a context for the post's authors:
+
+```ts highlights={highlights3}
+const { data } = await query.graph({
+ entity: "post",
+ fields: ["*"],
+ context: QueryContext({
+ lang: "es",
+ author: QueryContext({
+ lang: "es",
+ }),
+ }),
+})
+```
+
+Then, in the `listPosts` method, you can handle the context for the post's authors:
+
+```ts highlights={highlights4}
+import { MedusaContext, MedusaService } from "@medusajs/framework/utils"
+import { Context, FindConfig } from "@medusajs/framework/types"
+import Post from "./models/post"
+import Author from "./models/author"
+
+class BlogModuleService extends MedusaService({
+ Post,
+ Author,
+}){
+ // @ts-ignore
+ async listPosts(
+ filters?: any,
+ config?: FindConfig | undefined,
+ @MedusaContext() sharedContext?: Context | undefined
+ ) {
+ const context = filters.context ?? {}
+ delete filters.context
+
+ let posts = await super.listPosts(filters, config, sharedContext)
+
+ const isPostLangEs = context.lang === "es"
+ const isAuthorLangEs = context.author?.lang === "es"
+
+ if (isPostLangEs || isAuthorLangEs) {
+ posts = posts.map((post) => {
+ return {
+ ...post,
+ title: isPostLangEs ? post.title + " en español" : post.title,
+ author: {
+ ...post.author,
+ name: isAuthorLangEs ? post.author.name + " en español" : post.author.name,
+ },
+ }
+ })
+ }
+
+ return posts
+ }
+}
+
+export default BlogModuleService
+```
+
+The context in `filters` will also have the context for `author`, which you can use to make transformations to the post's authors.
+
+***
+
+## Passing Query Context to Linked Data Models
+
+If you're retrieving a data model and you want to pass context to a linked model in a different module, pass to the `context` property an object instead, where its keys are the linked model's name and the values are the context for that linked model.
+
+For example, consider the Product Module's `Product` data model is linked to the Blog Module's `Post` data model. You can pass context to the `Post` data model while retrieving products like so:
+
+```ts highlights={highlights5}
+const { data } = await query.graph({
+ entity: "product",
+ fields: ["*", "post.*"],
+ context: {
+ post: QueryContext({
+ lang: "es",
+ }),
+ },
+})
+```
+
+In this example, you retrieve products and their associated posts. You also pass a context for `post`, indicating the customer's language.
+
+To handle the context, you override the generated `listPosts` method of the Blog Module as explained [previously](#how-to-use-query-context).
+
+
# Read-Only Module Link
In this chapter, you’ll learn what a read-only module link is and how to define one.
@@ -12592,6 +12887,440 @@ There are different architectural module types including:
Refer to the [Architectural Modules reference](https://docs.medusajs.com/resources/architectural-modules/index.html.md) for a list of Medusa’s architectural modules, available modules to install, and how to create an architectural module.
+# Create a Plugin
+
+In this chapter, you'll learn how to create a Medusa plugin and publish it.
+
+A [plugin](https://docs.medusajs.com/learn/fundamentals/plugins/index.html.md) is a package of reusable Medusa customizations that you can install in any Medusa application. By creating and publishing a plugin, you can reuse your Medusa customizations across multiple projects or share them with the community.
+
+Plugins are available starting from [Medusa v2.3.0](https://github.com/medusajs/medusa/releases/tag/v2.3.0).
+
+## 1. Create a Plugin Project
+
+Plugins are created in a separate Medusa project. This makes the development and publishing of the plugin easier. Later, you'll install that plugin in your Medusa application to test it out and use it.
+
+Medusa's `create-medusa-app` CLI tool provides the option to create a plugin project. Run the following command to create a new plugin project:
+
+```bash
+npx create-medusa-app my-plugin --plugin
+```
+
+This will create a new Medusa plugin project in the `my-plugin` directory.
+
+### Plugin Directory Structure
+
+After the installation is done, the plugin structure will look like this:
+
+
+
+- `src/`: Contains the Medusa customizations.
+- `src/admin`: Contains [admin extensions](https://docs.medusajs.com/learn/fundamentals/admin/index.html.md).
+- `src/api`: Contains [API routes](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md) and [middlewares](https://docs.medusajs.com/learn/fundamentals/api-routes/middlewares/index.html.md). You can add store, admin, or any custom API routes.
+- `src/jobs`: Contains [scheduled jobs](https://docs.medusajs.com/learn/fundamentals/scheduled-jobs/index.html.md).
+- `src/links`: Contains [module links](https://docs.medusajs.com/learn/fundamentals/module-links/index.html.md).
+- `src/modules`: Contains [modules](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md).
+- `src/provider`: Contains [module providers](#create-module-providers).
+- `src/subscribers`: Contains [subscribers](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md).
+- `src/workflows`: Contains [workflows](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md). You can also add [hooks](https://docs.medusajs.com/learn/fundamentals/workflows/add-workflow-hook/index.html.md) under `src/workflows/hooks`.
+- `package.json`: Contains the plugin's package information, including general information and dependencies.
+- `tsconfig.json`: Contains the TypeScript configuration for the plugin.
+
+***
+
+## 2. Prepare Plugin
+
+### Package Name
+
+Before developing, testing, and publishing your plugin, make sure its name in `package.json` is correct. This is the name you'll use to install the plugin in your Medusa application.
+
+For example:
+
+```json title="package.json"
+{
+ "name": "@myorg/plugin-name",
+ // ...
+}
+```
+
+### Package Keywords
+
+Medusa scrapes NPM for a list of plugins that integrate third-party services, to later showcase them on the Medusa website. If you want your plugin to appear in that listing, make sure to add the `medusa-v2` and `medusa-plugin-integration` keywords to the `keywords` field in `package.json`.
+
+Only plugins that integrate third-party services are listed in the Medusa integrations page. If your plugin doesn't integrate a third-party service, you can skip this step.
+
+```json title="package.json"
+{
+ "keywords": [
+ "medusa-plugin-integration",
+ "medusa-v2"
+ ],
+ // ...
+}
+```
+
+In addition, make sure to use one of the following keywords based on your integration type:
+
+|Keyword|Description|Example|
+|---|---|---|
+|\`medusa-plugin-analytics\`|Analytics service integration|Google Analytics|
+|\`medusa-plugin-auth\`|Authentication service integration|Auth0|
+|\`medusa-plugin-cms\`|CMS service integration|Contentful|
+|\`medusa-plugin-notification\`|Notification service integration|Twilio SMS|
+|\`medusa-plugin-payment\`|Payment service integration|PayPal|
+|\`medusa-plugin-search\`|Search service integration|MeiliSearch|
+|\`medusa-plugin-shipping\`|Shipping service integration|DHL|
+|\`medusa-plugin-other\`|Other third-party integrations|Sentry|
+
+### Package Dependencies
+
+Your plugin project will already have the dependencies mentioned in this section. Unless you made changes to the dependencies, you can skip this section.
+
+In the `package.json` file you must have the Medusa dependencies as `devDependencies` and `peerDependencies`. In addition, you must have `@swc/core` as a `devDependency`, as it's used by the plugin CLI tools.
+
+For example, assuming `2.5.0` is the latest Medusa version:
+
+```json title="package.json"
+{
+ "devDependencies": {
+ "@medusajs/admin-sdk": "2.5.0",
+ "@medusajs/cli": "2.5.0",
+ "@medusajs/framework": "2.5.0",
+ "@medusajs/medusa": "2.5.0",
+ "@medusajs/test-utils": "2.5.0",
+ "@medusajs/ui": "4.0.4",
+ "@medusajs/icons": "2.5.0",
+ "@swc/core": "1.5.7",
+ },
+ "peerDependencies": {
+ "@medusajs/admin-sdk": "2.5.0",
+ "@medusajs/cli": "2.5.0",
+ "@medusajs/framework": "2.5.0",
+ "@medusajs/test-utils": "2.5.0",
+ "@medusajs/medusa": "2.5.0",
+ "@medusajs/ui": "4.0.3",
+ "@medusajs/icons": "2.5.0",
+ }
+}
+```
+
+### Package Exports
+
+Your plugin project will already have the exports mentioned in this section. Unless you made changes to the exports or you created your plugin before [Medusa v2.7.0](https://github.com/medusajs/medusa/releases/tag/v2.7.0), you can skip this section.
+
+In the `package.json` file, make sure your plugin has the following exports:
+
+```json title="package.json"
+{
+ "exports": {
+ "./package.json": "./package.json",
+ "./workflows": "./.medusa/server/src/workflows/index.js",
+ "./.medusa/server/src/modules/*": "./.medusa/server/src/modules/*/index.js",
+ "./providers/*": "./.medusa/server/src/providers/*/index.js",
+ "./admin": {
+ "import": "./.medusa/server/src/admin/index.mjs",
+ "require": "./.medusa/server/src/admin/index.js",
+ "default": "./.medusa/server/src/admin/index.js"
+ },
+ "./*": "./.medusa/server/src/*.js"
+ }
+}
+```
+
+Aside from the `./package.json`, `./providers`, and `./admin`, these exports are only a recommendation. You can cherry-pick the files and directories you want to export.
+
+The plugin exports the following files and directories:
+
+- `./package.json`: The `package.json` file. Medusa needs to access the `package.json` when registering the plugin.
+- `./workflows`: The workflows exported in `./src/workflows/index.ts`.
+- `./.medusa/server/src/modules/*`: The definition file of modules. This is useful if you create links to the plugin's modules in the Medusa application.
+- `./providers/*`: The definition file of module providers. This is useful if your plugin includes a module provider, allowing you to register the plugin's providers in Medusa applications. Learn more in the [Create Module Providers](#create-module-providers) section.
+- `./admin`: The admin extensions exported in `./src/admin/index.ts`.
+- `./*`: Any other files in the plugin's `src` directory.
+
+***
+
+## 3. Publish Plugin Locally for Development and Testing
+
+Medusa's CLI tool provides commands to simplify developing and testing your plugin in a local Medusa application. You start by publishing your plugin in the local package registry, then install it in your Medusa application. You can then watch for changes in the plugin as you develop it.
+
+### Publish and Install Local Package
+
+### Prerequisites
+
+- [Medusa application installed.](https://docs.medusajs.com/learn/installation/index.html.md)
+
+The first time you create your plugin, you need to publish the package into a local package registry, then install it in your Medusa application. This is a one-time only process.
+
+To publish the plugin to the local registry, run the following command in your plugin project:
+
+```bash title="Plugin project"
+npx medusa plugin:publish
+```
+
+This command uses [Yalc](https://github.com/wclr/yalc) under the hood to publish the plugin to a local package registry. The plugin is published locally under the name you specified in `package.json`.
+
+Next, navigate to your Medusa application:
+
+```bash title="Medusa application"
+cd ~/path/to/medusa-app
+```
+
+Make sure to replace `~/path/to/medusa-app` with the path to your Medusa application.
+
+Then, if your project was created before v2.3.1 of Medusa, make sure to install `yalc` as a development dependency:
+
+```bash npm2yarn title="Medusa application"
+npm install --save-dev yalc
+```
+
+After that, run the following Medusa CLI command to install the plugin:
+
+```bash title="Medusa application"
+npx medusa plugin:add @myorg/plugin-name
+```
+
+Make sure to replace `@myorg/plugin-name` with the name of your plugin as specified in `package.json`. Your plugin will be installed from the local package registry into your Medusa application.
+
+### Register Plugin in Medusa Application
+
+After installing the plugin, you need to register it in your Medusa application in the configurations defined in `medusa-config.ts`.
+
+Add the plugin to the `plugins` array in the `medusa-config.ts` file:
+
+```ts title="medusa-config.ts" highlights={pluginHighlights}
+module.exports = defineConfig({
+ // ...
+ plugins: [
+ {
+ resolve: "@myorg/plugin-name",
+ options: {},
+ },
+ ],
+})
+```
+
+The `plugins` configuration is an array of objects where each object has a `resolve` key whose value is the name of the plugin package.
+
+#### Pass Module Options through Plugin
+
+Each plugin configuration also accepts an `options` property, whose value is an object of options to pass to the plugin's modules.
+
+For example:
+
+```ts title="medusa-config.ts" highlights={pluginOptionsHighlight}
+module.exports = defineConfig({
+ // ...
+ plugins: [
+ {
+ resolve: "@myorg/plugin-name",
+ options: {
+ apiKey: true,
+ },
+ },
+ ],
+})
+```
+
+The `options` property in the plugin configuration is passed to all modules in the plugin. Learn more about module options in [this chapter](https://docs.medusajs.com/learn/fundamentals/modules/options/index.html.md).
+
+### Watch Plugin Changes During Development
+
+While developing your plugin, you can watch for changes in the plugin and automatically update the plugin in the Medusa application using it. This is the only command you'll continuously need during your plugin development.
+
+To do that, run the following command in your plugin project:
+
+```bash title="Plugin project"
+npx medusa plugin:develop
+```
+
+This command will:
+
+- Watch for changes in the plugin. Whenever a file is changed, the plugin is automatically built.
+- Publish the plugin changes to the local package registry. This will automatically update the plugin in the Medusa application using it. You can also benefit from real-time HMR updates of admin extensions.
+
+### Start Medusa Application
+
+You can start your Medusa application's development server to test out your plugin:
+
+```bash npm2yarn title="Medusa application"
+npm run dev
+```
+
+While your Medusa application is running and the plugin is being watched, you can test your plugin while developing it in the Medusa application.
+
+***
+
+## 4. Create Customizations in the Plugin
+
+You can now build your plugin's customizations. The following guide explains how to build different customizations in your plugin.
+
+- [Create a module](https://docs.medusajs.com/learn/fundamentals/modules/index.html.md)
+- [Create a module link](https://docs.medusajs.com/learn/fundamentals/module-links/index.html.md)
+- [Create a workflow](https://docs.medusajs.com/learn/fundamentals/workflows/index.html.md)
+- [Add a workflow hook](https://docs.medusajs.com/learn/fundamentals/workflows/add-workflow-hook/index.html.md)
+- [Create an API route](https://docs.medusajs.com/learn/fundamentals/api-routes/index.html.md)
+- [Add a subscriber](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers/index.html.md)
+- [Add a scheduled job](https://docs.medusajs.com/learn/fundamentals/scheduled-jobs/index.html.md)
+- [Add an admin widget](https://docs.medusajs.com/learn/fundamentals/admin/widgets/index.html.md)
+- [Add an admin UI route](https://docs.medusajs.com/learn/fundamentals/admin/ui-routes/index.html.md)
+
+While building those customizations, you can test them in your Medusa application by [watching the plugin changes](#watch-plugin-changes-during-development) and [starting the Medusa application](#start-medusa-application).
+
+### Generating Migrations for Modules
+
+During your development, you may need to generate migrations for modules in your plugin. To do that, first, add the following environment variables in your plugin project:
+
+```plain title="Plugin project"
+DB_USERNAME=postgres
+DB_PASSWORD=123...
+DB_HOST=localhost
+DB_PORT=5432
+DB_NAME=db_name
+```
+
+You can add these environment variables in a `.env` file in your plugin project. The variables are:
+
+- `DB_USERNAME`: The username of the PostgreSQL user to connect to the database.
+- `DB_PASSWORD`: The password of the PostgreSQL user to connect to the database.
+- `DB_HOST`: The host of the PostgreSQL database. Typically, it's `localhost` if you're running the database locally.
+- `DB_PORT`: The port of the PostgreSQL database. Typically, it's `5432` if you're running the database locally.
+- `DB_NAME`: The name of the PostgreSQL database to connect to.
+
+Then, run the following command in your plugin project to generate migrations for the modules in your plugin:
+
+```bash title="Plugin project"
+npx medusa plugin:db:generate
+```
+
+This command generates migrations for all modules in the plugin.
+
+Finally, run these migrations on the Medusa application that the plugin is installed in using the `db:migrate` command:
+
+```bash title="Medusa application"
+npx medusa db:migrate
+```
+
+The migrations in your application, including your plugin, will run and update the database.
+
+### Importing Module Resources
+
+In the [Prepare Plugin](#2-prepare-plugin) section, you learned about [exported resources](#package-exports) in your plugin.
+
+These exports allow you to import your plugin resources in your Medusa application, including workflows, links and modules.
+
+For example, to import the plugin's workflow in your Medusa application:
+
+`@myorg/plugin-name` is the plugin package's name.
+
+```ts
+import { Workflow1, Workflow2 } from "@myorg/plugin-name/workflows"
+import BlogModule from "@myorg/plugin-name/modules/blog"
+// import other files created in plugin like ./src/types/blog.ts
+import BlogType from "@myorg/plugin-name/types/blog"
+```
+
+### Create Module Providers
+
+The [exported resources](#package-exports) also allow you to import module providers in your plugin and register them in the Medusa application's configuration. A module provider is a module that provides the underlying logic or integration related to a commerce or architectural module.
+
+For example, assuming your plugin has a [Notification Module Provider](https://docs.medusajs.com/resources/architectural-modules/notification/index.html.md) called `my-notification`, you can register it in your Medusa application's configuration like this:
+
+`@myorg/plugin-name` is the plugin package's name.
+
+```ts highlights={[["9"]]} title="medusa-config.ts"
+module.exports = defineConfig({
+ // ...
+ modules: [
+ {
+ resolve: "@medusajs/medusa/notification",
+ options: {
+ providers: [
+ {
+ resolve: "@myorg/plugin-name/providers/my-notification",
+ id: "my-notification",
+ options: {
+ channels: ["email"],
+ // provider options...
+ },
+ },
+ ],
+ },
+ },
+ ],
+})
+```
+
+You pass to `resolve` the path to the provider relative to the plugin package. So, in this example, the `my-notification` provider is located in `./src/providers/my-notification/index.ts` of the plugin.
+
+To learn how to create module providers, refer to the following guides:
+
+- [File Module Provider](https://docs.medusajs.com/resources/references/file-provider-module/index.html.md)
+- [Notification Module Provider](https://docs.medusajs.com/resources/references/notification-provider-module/index.html.md)
+- [Auth Module Provider](https://docs.medusajs.com/resources/references/auth/provider/index.html.md)
+- [Payment Module Provider](https://docs.medusajs.com/resources/references/payment/provider/index.html.md)
+- [Fulfillment Module Provider](https://docs.medusajs.com/resources/references/fulfillment/provider/index.html.md)
+- [Tax Module Provider](https://docs.medusajs.com/resources/references/tax/provider/index.html.md)
+
+***
+
+## 5. Publish Plugin to NPM
+
+Make sure to add the keywords mentioned in the [Package Keywords](#package-keywords) section in your plugin's `package.json` file.
+
+Medusa's CLI tool provides a command that bundles your plugin to be published to npm. Once you're ready to publish your plugin publicly, run the following command in your plugin project:
+
+```bash
+npx medusa plugin:build
+```
+
+The command will compile an output in the `.medusa/server` directory.
+
+You can now publish the plugin to npm using the [NPM CLI tool](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm). Run the following command to publish the plugin to npm:
+
+```bash
+npm publish
+```
+
+If you haven't logged in before with your NPM account, you'll be asked to log in first. Then, your package is published publicly to be used in any Medusa application.
+
+### Install Public Plugin in Medusa Application
+
+You install a plugin that's published publicly using your package manager. For example:
+
+```bash npm2yarn
+npm install @myorg/plugin-name
+```
+
+Where `@myorg/plugin-name` is the name of your plugin as published on NPM.
+
+Then, register the plugin in your Medusa application's configurations as explained in [this section](#register-plugin-in-medusa-application).
+
+***
+
+## Update a Published Plugin
+
+To update the Medusa dependencies in a plugin, refer to [this documentation](https://docs.medusajs.com/learn/update#update-plugin-project/index.html.md).
+
+If you've published a plugin and you've made changes to it, you'll have to publish the update to NPM again.
+
+First, run the following command to change the version of the plugin:
+
+```bash
+npm version
+```
+
+Where `` indicates the type of version update you’re publishing. For example, it can be `major` or `minor`. Refer to the [npm version documentation](https://docs.npmjs.com/cli/v10/commands/npm-version) for more information.
+
+Then, re-run the same commands for publishing a plugin:
+
+```bash
+npx medusa plugin:build
+npm publish
+```
+
+This will publish an updated version of your plugin under a new version.
+
+
# Commerce Modules
In this chapter, you'll learn about Medusa's commerce modules.
@@ -13661,6 +14390,44 @@ The `configModule` has a `modules` property that includes all registered modules
If its value is not a `boolean`, set the service's options to the module configuration's `options` property.
+# Service Constraints
+
+This chapter lists constraints to keep in mind when creating a service.
+
+## Use Async Methods
+
+Medusa wraps service method executions to inject useful context or transactions. However, since Medusa can't detect whether the method is asynchronous, it always executes methods in the wrapper with the `await` keyword.
+
+For example, if you have a synchronous `getMessage` method, and you use it in other resources like workflows, Medusa executes it as an async method:
+
+```ts
+await blogModuleService.getMessage()
+```
+
+So, make sure your service's methods are always async to avoid unexpected errors or behavior.
+
+```ts highlights={[["8", "", "Method must be async."], ["13", "async", "Correct way of defining the method."]]}
+import { MedusaService } from "@medusajs/framework/utils"
+import Post from "./models/post"
+
+class BlogModuleService extends MedusaService({
+ Post,
+}){
+ // Don't
+ getMessage(): string {
+ return "Hello, World!"
+ }
+
+ // Do
+ async getMessage(): Promise {
+ return "Hello, World!"
+ }
+}
+
+export default BlogModuleService
+```
+
+
# Module Options
In this chapter, you’ll learn about passing options to your module from the Medusa application’s configurations and using them in the module’s resources.
@@ -13826,44 +14593,6 @@ export default Module(BLOG_MODULE, {
Now, when the Medusa application starts, the loader will run, validating the module's options and throwing an error if the `apiKey` option is missing.
-# Service Constraints
-
-This chapter lists constraints to keep in mind when creating a service.
-
-## Use Async Methods
-
-Medusa wraps service method executions to inject useful context or transactions. However, since Medusa can't detect whether the method is asynchronous, it always executes methods in the wrapper with the `await` keyword.
-
-For example, if you have a synchronous `getMessage` method, and you use it in other resources like workflows, Medusa executes it as an async method:
-
-```ts
-await blogModuleService.getMessage()
-```
-
-So, make sure your service's methods are always async to avoid unexpected errors or behavior.
-
-```ts highlights={[["8", "", "Method must be async."], ["13", "async", "Correct way of defining the method."]]}
-import { MedusaService } from "@medusajs/framework/utils"
-import Post from "./models/post"
-
-class BlogModuleService extends MedusaService({
- Post,
-}){
- // Don't
- getMessage(): string {
- return "Hello, World!"
- }
-
- // Do
- async getMessage(): Promise {
- return "Hello, World!"
- }
-}
-
-export default BlogModuleService
-```
-
-
# Service Factory
In this chapter, you’ll learn about what the service factory is and how to use it.
@@ -14039,6 +14768,394 @@ export default BlogModuleService
```
+# Scheduled Jobs Number of Executions
+
+In this chapter, you'll learn how to set a limit on the number of times a scheduled job is executed.
+
+## numberOfExecutions Option
+
+The export configuration object of the scheduled job accepts an optional property `numberOfExecutions`. Its value is a number indicating how many times the scheduled job can be executed during the Medusa application's runtime.
+
+For example:
+
+```ts highlights={highlights}
+export default async function myCustomJob() {
+ console.log("I'll be executed three times only.")
+}
+
+export const config = {
+ name: "hello-world",
+ // execute every minute
+ schedule: "* * * * *",
+ numberOfExecutions: 3,
+}
+```
+
+The above scheduled job has the `numberOfExecutions` configuration set to `3`.
+
+So, it'll only execute 3 times, each every minute, then it won't be executed anymore.
+
+If you restart the Medusa application, the scheduled job will be executed again until reaching the number of executions specified.
+
+
+# Docs Contribution Guidelines
+
+Thank you for your interest in contributing to the documentation! You will be helping the open source community and other developers interested in learning more about Medusa and using it.
+
+This guide is specific to contributing to the documentation. If you’re interested in contributing to Medusa’s codebase, check out the [contributing guidelines in the Medusa GitHub repository](https://github.com/medusajs/medusa/blob/develop/CONTRIBUTING.md).
+
+## What Can You Contribute?
+
+You can contribute to the Medusa documentation in the following ways:
+
+- Fixes to existing content. This includes small fixes like typos, or adding missing information.
+- Additions to the documentation. If you think a documentation page can be useful to other developers, you can contribute by adding it.
+ - Make sure to open an issue first in the [medusa repository](https://github.com/medusajs/medusa) to confirm that you can add that documentation page.
+- Fixes to UI components and tooling. If you find a bug while browsing the documentation, you can contribute by fixing it.
+
+***
+
+## Documentation Workspace
+
+Medusa's documentation projects are all part of the documentation yarn workspace, which you can find in the [medusa repository](https://github.com/medusajs/medusa) under the `www` directory.
+
+The workspace has the following two directories:
+
+- `apps`: this directory holds the different documentation websites and projects.
+ - `book`: includes the codebase for the [main Medusa documentation](https://docs.medusajs.com//index.html.md). It's built with [Next.js 15](https://nextjs.org/).
+ - `resources`: includes the codebase for the resources documentation, which powers different sections of the docs such as the [Integrations](https://docs.medusajs.com/resources/integrations/index.html.md) or [How-to & Tutorials](https://docs.medusajs.com/resources/how-to-tutorials/index.html.md) sections. It's built with [Next.js 15](https://nextjs.org/).
+ - `api-reference`: includes the codebase for the API reference website. It's built with [Next.js 15](https://nextjs.org/).
+ - `ui`: includes the codebase for the Medusa UI documentation website. It's built with [Next.js 15](https://nextjs.org/).
+- `packages`: this directory holds the shared packages and components necessary for the development of the projects in the `apps` directory.
+ - `docs-ui` includes the shared React components between the different apps.
+ - `remark-rehype-plugins` includes Remark and Rehype plugins used by the documentation projects.
+
+***
+
+## Documentation Content
+
+All documentation projects are built with Next.js. The content is writtin in MDX files.
+
+### Medusa Main Docs Content
+
+The content of the Medusa main docs are under the `www/apps/book/app` directory.
+
+### Medusa Resources Content
+
+The content of all pages under the `/resources` path are under the `www/apps/resources/app` directory.
+
+Documentation pages under the `www/apps/resources/references` directory are generated automatically from the source code under the `packages/medusa` directory. So, you can't directly make changes to them. Instead, you'll have to make changes to the comments in the original source code.
+
+### API Reference
+
+The API reference's content is split into two types:
+
+1. Static content, which are the content related to getting started, expanding fields, and more. These are located in the `www/apps/api-reference/markdown` directory. They are MDX files.
+2. OpenAPI specs that are shown to developers when checking the reference of an API Route. These are generated from OpenApi Spec comments, which are under the `www/utils/generated/oas-output` directory.
+
+### Medusa UI Documentation
+
+The content of the Medusa UI documentation are located under the `www/apps/ui/src/content/docs` directory. They are MDX files.
+
+The UI documentation also shows code examples, which are under the `www/apps/ui/src/examples` directory.
+
+The UI component props are generated from the source code and placed into the `www/apps/ui/src/specs` directory. To contribute to these props and their comments, check the comments in the source code under the `packages/design-system/ui` directory.
+
+***
+
+## Style Guide
+
+When you contribute to the documentation content, make sure to follow the [documentation style guide](https://www.notion.so/Style-Guide-Docs-fad86dd1c5f84b48b145e959f36628e0).
+
+***
+
+## How to Contribute
+
+If you’re fixing errors in an existing documentation page, you can scroll down to the end of the page and click on the “Edit this page” link. You’ll be redirected to the GitHub edit form of that page and you can make edits directly and submit a pull request (PR).
+
+If you’re adding a new page or contributing to the codebase, fork the repository, create a new branch, and make all changes necessary in your repository. Then, once you’re done, create a PR in the Medusa repository.
+
+### Base Branch
+
+When you make an edit to an existing documentation page or fork the repository to make changes to the documentation, create a new branch.
+
+Documentation contributions always use `develop` as the base branch. Make sure to also open your PR against the `develop` branch.
+
+### Branch Name
+
+Make sure that the branch name starts with `docs/`. For example, `docs/fix-services`. Vercel deployed previews are only triggered for branches starting with `docs/`.
+
+### Pull Request Conventions
+
+When you create a pull request, prefix the title with `docs:` or `docs(PROJECT_NAME):`, where `PROJECT_NAME` is the name of the documentation project this pull request pertains to. For example, `docs(ui): fix titles`.
+
+In the body of the PR, explain clearly what the PR does. If the PR solves an issue, use [closing keywords](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword) with the issue number. For example, “Closes #1333”.
+
+***
+
+## Images
+
+If you are adding images to a documentation page, you can host the image on [Imgur](https://imgur.com) for free to include it in the PR. Our team will later upload it to our image hosting.
+
+***
+
+## NPM and Yarn Code Blocks
+
+If you’re adding code blocks that use NPM and Yarn, you must add the `npm2yarn` meta field.
+
+For example:
+
+````md
+```bash npm2yarn
+npm run start
+```
+````
+
+The code snippet must be written using NPM.
+
+### Global Option
+
+When a command uses the global option `-g`, add it at the end of the NPM command to ensure that it’s transformed to a Yarn command properly. For example:
+
+```bash npm2yarn
+npm install @medusajs/cli -g
+```
+
+***
+
+## Linting with Vale
+
+Medusa uses [Vale](https://vale.sh/) to lint documentation pages and perform checks on incoming PRs into the repository.
+
+### Result of Vale PR Checks
+
+You can check the result of running the "lint" action on your PR by clicking the Details link next to it. You can find there all errors that you need to fix.
+
+### Run Vale Locally
+
+If you want to check your work locally, you can do that by:
+
+1. [Installing Vale](https://vale.sh/docs/vale-cli/installation/) on your machine.
+2. Changing to the `www/vale` directory:
+
+```bash
+cd www/vale
+```
+
+3\. Running the `run-vale` script:
+
+```bash
+# to lint content for the main documentation
+./run-vale.sh book/app/learn error resources
+# to lint content for the resources documentation
+./run-vale.sh resources/app error
+# to lint content for the API reference
+./run-vale.sh api-reference/markdown error
+# to lint content for the Medusa UI documentation
+./run-vale.sh ui/src/content/docs error
+# to lint content for the user guide
+./run-vale.sh user-guide/app error
+```
+
+{/* TODO need to enable MDX v1 comments first. */}
+
+{/* ### Linter Exceptions
+
+If it's needed to break some style guide rules in a document, you can wrap the parts that the linter shouldn't scan with the following comments in the `md` or `mdx` files:
+
+```md
+
+
+content that shouldn't be scanned for errors here...
+
+
+```
+
+You can also disable specific rules. For example:
+
+```md
+
+
+Medusa supports Node versions 14 and 16.
+
+
+```
+
+If you use this in your PR, you must justify its usage. */}
+
+***
+
+## Linting with ESLint
+
+Medusa uses ESlint to lint code blocks both in the content and the code base of the documentation apps.
+
+### Linting Content with ESLint
+
+Each PR runs through a check that lints the code in the content files using ESLint. The action's name is `content-eslint`.
+
+If you want to check content ESLint errors locally and fix them, you can do that by:
+
+1\. Install the dependencies in the `www` directory:
+
+```bash
+yarn install
+```
+
+2\. Run the turbo command in the `www` directory:
+
+```bash
+turbo run lint:content
+```
+
+This will fix any fixable errors, and show errors that require your action.
+
+### Linting Code with ESLint
+
+Each PR runs through a check that lints the code in the content files using ESLint. The action's name is `code-docs-eslint`.
+
+If you want to check code ESLint errors locally and fix them, you can do that by:
+
+1\. Install the dependencies in the `www` directory:
+
+```bash
+yarn install
+```
+
+2\. Run the turbo command in the `www` directory:
+
+```bash
+yarn lint
+```
+
+This will fix any fixable errors, and show errors that require your action.
+
+{/* TODO need to enable MDX v1 comments first. */}
+
+{/* ### ESLint Exceptions
+
+If some code blocks have errors that can't or shouldn't be fixed, you can add the following command before the code block:
+
+~~~md
+
+
+```js
+console.log("This block isn't linted")
+```
+
+```js
+console.log("This block is linted")
+```
+~~~
+
+You can also disable specific rules. For example:
+
+~~~md
+
+
+```js
+console.log("This block can use semicolons");
+```
+
+```js
+console.log("This block can't use semi colons")
+```
+~~~ */}
+
+
+# Translate Medusa Admin
+
+The Medusa Admin supports multiple languages, with the default being English. In this documentation, you'll learn how to contribute to the community by translating the Medusa Admin to a language you're fluent in.
+
+{/* vale docs.We = NO */}
+
+You can contribute either by translating the admin to a new language, or fixing translations for existing languages. As we can't validate every language's translations, some translations may be incorrect. Your contribution is welcome to fix any translation errors you find.
+
+{/* vale docs.We = YES */}
+
+Check out the translated languages either in the admin dashboard's settings or on [GitHub](https://github.com/medusajs/medusa/blob/develop/packages/admin/dashboard/src/i18n/languages.ts).
+
+***
+
+## How to Contribute Translation
+
+1. Clone the [Medusa monorepository](https://github.com/medusajs/medusa) to your local machine:
+
+```bash
+git clone https://github.com/medusajs/medusa.git
+```
+
+If you already have it cloned, make sure to pull the latest changes from the `develop` branch.
+
+2. Install the monorepository's dependencies. Since it's a Yarn workspace, it's highly recommended to use yarn:
+
+```bash
+yarn install
+```
+
+3. Create a branch that you'll use to open the pull request later:
+
+```bash
+git checkout -b feat/translate-
+```
+
+Where `` is your language name. For example, `feat/translate-da`.
+
+4. Translation files are under `packages/admin/dashboard/src/i18n/translations` as JSON files whose names are the ISO-2 name of the language.
+ - If you're adding a new language, copy the file `packages/admin/dashboard/src/i18n/translations/en.json` and paste it with the ISO-2 name for your language. For example, if you're adding Danish translations, copy the `en.json` file and paste it as `packages/admin/dashboard/src/i18n/translations/de.json`.
+ - If you're fixing a translation, find the JSON file of the language under `packages/admin/dashboard/src/i18n/translations`.
+
+5. Start translating the keys in the JSON file (or updating the targeted ones). All keys in the JSON file must be translated, and your PR tests will fail otherwise.
+ - You can check whether the JSON file is valid by running the following command in `packages/admin/dashboard`, replacing `da.json` with the JSON file's name:
+
+```bash title="packages/admin/dashboard"
+yarn i18n:validate da.json
+```
+
+6. After finishing the translation, if you're adding a new language, import its JSON file in `packages/admin/dashboard/src/i18n/translations/index.ts` and add it to the exported object:
+
+```ts title="packages/admin/dashboard/src/i18n/translations/index.ts" highlights={[["2"], ["6"], ["7"], ["8"]]}
+// other imports...
+import da from "./da.json"
+
+export default {
+ // other languages...
+ da: {
+ translation: da,
+ },
+}
+```
+
+The language's key in the object is the ISO-2 name of the language.
+
+7. If you're adding a new language, add it to the file `packages/admin/dashboard/src/i18n/languages.ts`:
+
+```ts title="packages/admin/dashboard/src/i18n/languages.ts" highlights={languageHighlights}
+import { da } from "date-fns/locale"
+// other imports...
+
+export const languages: Language[] = [
+ // other languages...
+ {
+ code: "da",
+ display_name: "Danish",
+ ltr: true,
+ date_locale: da,
+ },
+]
+```
+
+`languages` is an array having the following properties:
+
+- `code`: The ISO-2 name of the language. For example, `da` for Danish.
+- `display_name`: The language's name to be displayed in the admin.
+- `ltr`: Whether the language supports a left-to-right layout. For example, set this to `false` for languages like Arabic.
+- `date_locale`: An instance of the locale imported from the [date-fns/locale](https://date-fns.org/) package.
+
+8. Once you're done, push the changes into your branch and open a pull request on GitHub.
+
+Our team will perform a general review on your PR and merge it if no issues are found. The translation will be available in the admin after the next release.
+
+
# Expose a Workflow Hook
In this chapter, you'll learn how to expose a hook in your workflow.
@@ -14660,6 +15777,136 @@ const step1 = createStep(
```
+# Execute Another Workflow
+
+In this chapter, you'll learn how to execute a workflow in another.
+
+## Execute in a Workflow
+
+To execute a workflow in another, use the `runAsStep` method that every workflow has.
+
+For example:
+
+```ts highlights={workflowsHighlights} collapsibleLines="1-7" expandMoreButton="Show Imports"
+import {
+ createWorkflow,
+} from "@medusajs/framework/workflows-sdk"
+import {
+ createProductsWorkflow,
+} from "@medusajs/medusa/core-flows"
+
+const workflow = createWorkflow(
+ "hello-world",
+ async (input) => {
+ const products = createProductsWorkflow.runAsStep({
+ input: {
+ products: [
+ // ...
+ ],
+ },
+ })
+
+ // ...
+ }
+)
+```
+
+Instead of invoking the workflow and passing it the container, you use its `runAsStep` method and pass it an object as a parameter.
+
+The object has an `input` property to pass input to the workflow.
+
+***
+
+## Preparing Input Data
+
+If you need to perform some data manipulation to prepare the other workflow's input data, use `transform` from the Workflows SDK.
+
+Learn about transform in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/variable-manipulation/index.html.md).
+
+For example:
+
+```ts highlights={transformHighlights} collapsibleLines="1-12"
+import {
+ createWorkflow,
+ transform,
+} from "@medusajs/framework/workflows-sdk"
+import {
+ createProductsWorkflow,
+} from "@medusajs/medusa/core-flows"
+
+type WorkflowInput = {
+ title: string
+}
+
+const workflow = createWorkflow(
+ "hello-product",
+ async (input: WorkflowInput) => {
+ const createProductsData = transform({
+ input,
+ }, (data) => [
+ {
+ title: `Hello ${data.input.title}`,
+ },
+ ])
+
+ const products = createProductsWorkflow.runAsStep({
+ input: {
+ products: createProductsData,
+ },
+ })
+
+ // ...
+ }
+)
+```
+
+In this example, you use the `transform` function to prepend `Hello` to the title of the product. Then, you pass the result as an input to the `createProductsWorkflow`.
+
+***
+
+## Run Workflow Conditionally
+
+To run a workflow in another based on a condition, use when-then from the Workflows SDK.
+
+Learn about when-then in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/conditions/index.html.md).
+
+For example:
+
+```ts highlights={whenHighlights} collapsibleLines="1-16"
+import {
+ createWorkflow,
+ when,
+} from "@medusajs/framework/workflows-sdk"
+import {
+ createProductsWorkflow,
+} from "@medusajs/medusa/core-flows"
+import {
+ CreateProductWorkflowInputDTO,
+} from "@medusajs/framework/types"
+
+type WorkflowInput = {
+ product?: CreateProductWorkflowInputDTO
+ should_create?: boolean
+}
+
+const workflow = createWorkflow(
+ "hello-product",
+ async (input: WorkflowInput) => {
+ const product = when(input, ({ should_create }) => should_create)
+ .then(() => {
+ return createProductsWorkflow.runAsStep({
+ input: {
+ products: [input.product],
+ },
+ })
+ })
+ }
+)
+```
+
+In this example, you use when-then to run the `createProductsWorkflow` only if `should_create` (passed in the `input`) is enabled.
+
+
# Compensation Function
In this chapter, you'll learn what a compensation function is and how to add it to a step.
@@ -15209,134 +16456,57 @@ To find a full example of a long-running workflow, refer to the [restaurant-deli
In the recipe, you use a long-running workflow that moves an order from placed to completed. The workflow waits for the restaurant to accept the order, the driver to pick up the order, and other external actions.
-# Execute Another Workflow
+# Run Workflow Steps in Parallel
-In this chapter, you'll learn how to execute a workflow in another.
+In this chapter, you’ll learn how to run workflow steps in parallel.
-## Execute in a Workflow
+## parallelize Utility Function
-To execute a workflow in another, use the `runAsStep` method that every workflow has.
+If your workflow has steps that don’t rely on one another’s results, run them in parallel using `parallelize` from the Workflows SDK.
+
+The workflow waits until all steps passed to the `parallelize` function finish executing before continuing to the next step.
For example:
-```ts highlights={workflowsHighlights} collapsibleLines="1-7" expandMoreButton="Show Imports"
+```ts highlights={highlights} collapsibleLines="1-12" expandButtonLabel="Show Imports"
import {
createWorkflow,
+ WorkflowResponse,
+ parallelize,
} from "@medusajs/framework/workflows-sdk"
-import {
- createProductsWorkflow,
-} from "@medusajs/medusa/core-flows"
-
-const workflow = createWorkflow(
- "hello-world",
- async (input) => {
- const products = createProductsWorkflow.runAsStep({
- input: {
- products: [
- // ...
- ],
- },
- })
-
- // ...
- }
-)
-```
-
-Instead of invoking the workflow and passing it the container, you use its `runAsStep` method and pass it an object as a parameter.
-
-The object has an `input` property to pass input to the workflow.
-
-***
-
-## Preparing Input Data
-
-If you need to perform some data manipulation to prepare the other workflow's input data, use `transform` from the Workflows SDK.
-
-Learn about transform in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/variable-manipulation/index.html.md).
-
-For example:
-
-```ts highlights={transformHighlights} collapsibleLines="1-12"
import {
- createWorkflow,
- transform,
-} from "@medusajs/framework/workflows-sdk"
-import {
- createProductsWorkflow,
-} from "@medusajs/medusa/core-flows"
+ createProductStep,
+ getProductStep,
+ createPricesStep,
+ attachProductToSalesChannelStep,
+} from "./steps"
-type WorkflowInput = {
+interface WorkflowInput {
title: string
}
-const workflow = createWorkflow(
- "hello-product",
- async (input: WorkflowInput) => {
- const createProductsData = transform({
- input,
- }, (data) => [
- {
- title: `Hello ${data.input.title}`,
- },
- ])
+const myWorkflow = createWorkflow(
+ "my-workflow",
+ (input: WorkflowInput) => {
+ const product = createProductStep(input)
- const products = createProductsWorkflow.runAsStep({
- input: {
- products: createProductsData,
- },
- })
+ const [prices, productSalesChannel] = parallelize(
+ createPricesStep(product),
+ attachProductToSalesChannelStep(product)
+ )
- // ...
- }
+ const refetchedProduct = getProductStep(product.id)
+
+ return new WorkflowResponse(refetchedProduct)
+ }
)
```
-In this example, you use the `transform` function to prepend `Hello` to the title of the product. Then, you pass the result as an input to the `createProductsWorkflow`.
+The `parallelize` function accepts the steps to run in parallel as a parameter.
-***
+It returns an array of the steps' results in the same order they're passed to the `parallelize` function.
-## Run Workflow Conditionally
-
-To run a workflow in another based on a condition, use when-then from the Workflows SDK.
-
-Learn about when-then in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/conditions/index.html.md).
-
-For example:
-
-```ts highlights={whenHighlights} collapsibleLines="1-16"
-import {
- createWorkflow,
- when,
-} from "@medusajs/framework/workflows-sdk"
-import {
- createProductsWorkflow,
-} from "@medusajs/medusa/core-flows"
-import {
- CreateProductWorkflowInputDTO,
-} from "@medusajs/framework/types"
-
-type WorkflowInput = {
- product?: CreateProductWorkflowInputDTO
- should_create?: boolean
-}
-
-const workflow = createWorkflow(
- "hello-product",
- async (input: WorkflowInput) => {
- const product = when(input, ({ should_create }) => should_create)
- .then(() => {
- return createProductsWorkflow.runAsStep({
- input: {
- products: [input.product],
- },
- })
- })
- }
-)
-```
-
-In this example, you use when-then to run the `createProductsWorkflow` only if `should_create` (passed in the `input`) is enabled.
+So, `prices` is the result of `createPricesStep`, and `productSalesChannel` is the result of `attachProductToSalesChannelStep`.
# Multiple Step Usage in Workflow
@@ -15413,129 +16583,6 @@ The `config` method accepts an object with a `name` property. Its value is a new
The first `useQueryGraphStep` usage has the ID `use-query-graph`, and the second `useQueryGraphStep` usage has the ID `fetch-customers`.
-# Retry Failed Steps
-
-In this chapter, you’ll learn how to configure steps to allow retrial on failure.
-
-## What is a Step Retrial?
-
-A step retrial is a mechanism that allows a step to be retried automatically when it fails. This is useful for handling transient errors, such as network issues or temporary unavailability of a service.
-
-When a step fails, the workflow engine can automatically retry the step a specified number of times before marking the workflow as failed. This can help improve the reliability and resilience of your workflows.
-
-You can also configure the interval between retries, allowing you to wait for a certain period before attempting the step again. This is useful when the failure is due to a temporary issue that may resolve itself after some time.
-
-For example, if a step captures a payment, you may want to retry it the next day until the payment is successful or the maximum number of retries is reached.
-
-***
-
-## Configure a Step’s Retrial
-
-By default, when an error occurs in a step, the step and the workflow fail, and the execution stops.
-
-You can configure the step to retry on failure. The `createStep` function can accept a configuration object instead of the step’s name as a first parameter.
-
-For example:
-
-```ts title="src/workflows/hello-world.ts" highlights={[["10"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
-import {
- createStep,
- createWorkflow,
- WorkflowResponse,
-} from "@medusajs/framework/workflows-sdk"
-
-const step1 = createStep(
- {
- name: "step-1",
- maxRetries: 2,
- },
- async () => {
- console.log("Executing step 1")
-
- throw new Error("Oops! Something happened.")
- }
-)
-
-const myWorkflow = createWorkflow(
- "hello-world",
- function () {
- const str1 = step1()
-
- return new WorkflowResponse({
- message: str1,
- })
-})
-
-export default myWorkflow
-```
-
-The step’s configuration object accepts a `maxRetries` property, which is a number indicating the number of times a step can be retried when it fails.
-
-When you execute the above workflow, you’ll see the following result in the terminal:
-
-```bash
-Executing step 1
-Executing step 1
-Executing step 1
-error: Oops! Something happened.
-Error: Oops! Something happened.
-```
-
-The first line indicates the first time the step was executed, and the next two lines indicate the times the step was retried. After that, the step and workflow fail.
-
-***
-
-## Step Retry Intervals
-
-By default, a step is retried immediately after it fails. To specify a wait time before a step is retried, pass a `retryInterval` property to the step's configuration object. Its value is a number of seconds to wait before retrying the step.
-
-For example:
-
-```ts title="src/workflows/hello-world.ts" highlights={[["5"]]}
-const step1 = createStep(
- {
- name: "step-1",
- maxRetries: 2,
- retryInterval: 2, // 2 seconds
- },
- async () => {
- // ...
- }
-)
-```
-
-In this example, if the step fails, it will be retried after two seconds.
-
-### Maximum Retry Interval
-
-The `retryInterval` property's maximum value is [Number.MAX\_SAFE\_INTEGER](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). So, you can set a very long wait time before the step is retried, allowing you to retry steps after a long period.
-
-For example, to retry a step after a day:
-
-```ts title="src/workflows/hello-world.ts" highlights={[["5"]]}
-const step1 = createStep(
- {
- name: "step-1",
- maxRetries: 2,
- retryInterval: 86400, // 1 day
- },
- async () => {
- // ...
- }
-)
-```
-
-In this example, if the step fails, it will be retried after `86400` seconds (one day).
-
-### Interval Changes Workflow to Long-Running
-
-By setting `retryInterval` on a step, a workflow that uses that step becomes a [long-running workflow](https://docs.medusajs.com/learn/fundamentals/workflows/long-running-workflow/index.html.md) that runs asynchronously in the background. This is useful when creating workflows that may fail and should run for a long time until they succeed, such as waiting for a payment to be captured or a shipment to be delivered.
-
-However, since the long-running workflow runs in the background, you won't receive its result or errors immediately when you execute the workflow.
-
-Instead, you must subscribe to the workflow's execution using the Workflow Engine Module Service. Learn more about it in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/long-running-workflow#access-long-running-workflow-status-and-result/index.html.md).
-
-
# Store Workflow Executions
In this chapter, you'll learn how to store workflow executions in the database and access them later.
@@ -15681,6 +16728,129 @@ if (workflowExecution.state === "failed") {
Other state values include `done`, `invoking`, and `compensating`.
+# Retry Failed Steps
+
+In this chapter, you’ll learn how to configure steps to allow retrial on failure.
+
+## What is a Step Retrial?
+
+A step retrial is a mechanism that allows a step to be retried automatically when it fails. This is useful for handling transient errors, such as network issues or temporary unavailability of a service.
+
+When a step fails, the workflow engine can automatically retry the step a specified number of times before marking the workflow as failed. This can help improve the reliability and resilience of your workflows.
+
+You can also configure the interval between retries, allowing you to wait for a certain period before attempting the step again. This is useful when the failure is due to a temporary issue that may resolve itself after some time.
+
+For example, if a step captures a payment, you may want to retry it the next day until the payment is successful or the maximum number of retries is reached.
+
+***
+
+## Configure a Step’s Retrial
+
+By default, when an error occurs in a step, the step and the workflow fail, and the execution stops.
+
+You can configure the step to retry on failure. The `createStep` function can accept a configuration object instead of the step’s name as a first parameter.
+
+For example:
+
+```ts title="src/workflows/hello-world.ts" highlights={[["10"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
+import {
+ createStep,
+ createWorkflow,
+ WorkflowResponse,
+} from "@medusajs/framework/workflows-sdk"
+
+const step1 = createStep(
+ {
+ name: "step-1",
+ maxRetries: 2,
+ },
+ async () => {
+ console.log("Executing step 1")
+
+ throw new Error("Oops! Something happened.")
+ }
+)
+
+const myWorkflow = createWorkflow(
+ "hello-world",
+ function () {
+ const str1 = step1()
+
+ return new WorkflowResponse({
+ message: str1,
+ })
+})
+
+export default myWorkflow
+```
+
+The step’s configuration object accepts a `maxRetries` property, which is a number indicating the number of times a step can be retried when it fails.
+
+When you execute the above workflow, you’ll see the following result in the terminal:
+
+```bash
+Executing step 1
+Executing step 1
+Executing step 1
+error: Oops! Something happened.
+Error: Oops! Something happened.
+```
+
+The first line indicates the first time the step was executed, and the next two lines indicate the times the step was retried. After that, the step and workflow fail.
+
+***
+
+## Step Retry Intervals
+
+By default, a step is retried immediately after it fails. To specify a wait time before a step is retried, pass a `retryInterval` property to the step's configuration object. Its value is a number of seconds to wait before retrying the step.
+
+For example:
+
+```ts title="src/workflows/hello-world.ts" highlights={[["5"]]}
+const step1 = createStep(
+ {
+ name: "step-1",
+ maxRetries: 2,
+ retryInterval: 2, // 2 seconds
+ },
+ async () => {
+ // ...
+ }
+)
+```
+
+In this example, if the step fails, it will be retried after two seconds.
+
+### Maximum Retry Interval
+
+The `retryInterval` property's maximum value is [Number.MAX\_SAFE\_INTEGER](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). So, you can set a very long wait time before the step is retried, allowing you to retry steps after a long period.
+
+For example, to retry a step after a day:
+
+```ts title="src/workflows/hello-world.ts" highlights={[["5"]]}
+const step1 = createStep(
+ {
+ name: "step-1",
+ maxRetries: 2,
+ retryInterval: 86400, // 1 day
+ },
+ async () => {
+ // ...
+ }
+)
+```
+
+In this example, if the step fails, it will be retried after `86400` seconds (one day).
+
+### Interval Changes Workflow to Long-Running
+
+By setting `retryInterval` on a step, a workflow that uses that step becomes a [long-running workflow](https://docs.medusajs.com/learn/fundamentals/workflows/long-running-workflow/index.html.md) that runs asynchronously in the background. This is useful when creating workflows that may fail and should run for a long time until they succeed, such as waiting for a payment to be captured or a shipment to be delivered.
+
+However, since the long-running workflow runs in the background, you won't receive its result or errors immediately when you execute the workflow.
+
+Instead, you must subscribe to the workflow's execution using the Workflow Engine Module Service. Learn more about it in [this chapter](https://docs.medusajs.com/learn/fundamentals/workflows/long-running-workflow#access-long-running-workflow-status-and-result/index.html.md).
+
+
# Variable Manipulation in Workflows with transform
In this chapter, you'll learn how to use `transform` from the Workflows SDK to manipulate variables in a workflow.
@@ -16096,362 +17266,74 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
Your hook handler then receives that passed data in the `additional_data` object.
-# Translate Medusa Admin
+# Example: Integration Tests for a Module
-The Medusa Admin supports multiple languages, with the default being English. In this documentation, you'll learn how to contribute to the community by translating the Medusa Admin to a language you're fluent in.
+In this chapter, find an example of writing an integration test for a module using [moduleIntegrationTestRunner](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools/modules-tests/index.html.md) from Medusa's Testing Framework.
-{/* vale docs.We = NO */}
+### Prerequisites
-You can contribute either by translating the admin to a new language, or fixing translations for existing languages. As we can't validate every language's translations, some translations may be incorrect. Your contribution is welcome to fix any translation errors you find.
+- [Testing Tools Setup](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools/index.html.md)
-{/* vale docs.We = YES */}
+## Write Integration Test for Module
-Check out the translated languages either in the admin dashboard's settings or on [GitHub](https://github.com/medusajs/medusa/blob/develop/packages/admin/dashboard/src/i18n/languages.ts).
+Consider a `blog` module with a `BlogModuleService` that has a `getMessage` method:
-***
+```ts title="src/modules/blog/service.ts"
+import { MedusaService } from "@medusajs/framework/utils"
+import MyCustom from "./models/my-custom"
-## How to Contribute Translation
-
-1. Clone the [Medusa monorepository](https://github.com/medusajs/medusa) to your local machine:
-
-```bash
-git clone https://github.com/medusajs/medusa.git
-```
-
-If you already have it cloned, make sure to pull the latest changes from the `develop` branch.
-
-2. Install the monorepository's dependencies. Since it's a Yarn workspace, it's highly recommended to use yarn:
-
-```bash
-yarn install
-```
-
-3. Create a branch that you'll use to open the pull request later:
-
-```bash
-git checkout -b feat/translate-
-```
-
-Where `` is your language name. For example, `feat/translate-da`.
-
-4. Translation files are under `packages/admin/dashboard/src/i18n/translations` as JSON files whose names are the ISO-2 name of the language.
- - If you're adding a new language, copy the file `packages/admin/dashboard/src/i18n/translations/en.json` and paste it with the ISO-2 name for your language. For example, if you're adding Danish translations, copy the `en.json` file and paste it as `packages/admin/dashboard/src/i18n/translations/de.json`.
- - If you're fixing a translation, find the JSON file of the language under `packages/admin/dashboard/src/i18n/translations`.
-
-5. Start translating the keys in the JSON file (or updating the targeted ones). All keys in the JSON file must be translated, and your PR tests will fail otherwise.
- - You can check whether the JSON file is valid by running the following command in `packages/admin/dashboard`, replacing `da.json` with the JSON file's name:
-
-```bash title="packages/admin/dashboard"
-yarn i18n:validate da.json
-```
-
-6. After finishing the translation, if you're adding a new language, import its JSON file in `packages/admin/dashboard/src/i18n/translations/index.ts` and add it to the exported object:
-
-```ts title="packages/admin/dashboard/src/i18n/translations/index.ts" highlights={[["2"], ["6"], ["7"], ["8"]]}
-// other imports...
-import da from "./da.json"
-
-export default {
- // other languages...
- da: {
- translation: da,
- },
+class BlogModuleService extends MedusaService({
+ MyCustom,
+}){
+ getMessage(): string {
+ return "Hello, World!"
+ }
}
+
+export default BlogModuleService
```
-The language's key in the object is the ISO-2 name of the language.
+To create an integration test for the method, create the file `src/modules/blog/__tests__/service.spec.ts` with the following content:
-7. If you're adding a new language, add it to the file `packages/admin/dashboard/src/i18n/languages.ts`:
+```ts title="src/modules/blog/__tests__/service.spec.ts"
+import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
+import { BLOG_MODULE } from ".."
+import BlogModuleService from "../service"
+import MyCustom from "../models/my-custom"
-```ts title="packages/admin/dashboard/src/i18n/languages.ts" highlights={languageHighlights}
-import { da } from "date-fns/locale"
-// other imports...
+moduleIntegrationTestRunner({
+ moduleName: BLOG_MODULE,
+ moduleModels: [MyCustom],
+ resolve: "./src/modules/blog",
+ testSuite: ({ service }) => {
+ describe("BlogModuleService", () => {
+ it("says hello world", () => {
+ const message = service.getMessage()
-export const languages: Language[] = [
- // other languages...
- {
- code: "da",
- display_name: "Danish",
- ltr: true,
- date_locale: da,
+ expect(message).toEqual("Hello, World!")
+ })
+ })
},
-]
+})
+
+jest.setTimeout(60 * 1000)
```
-`languages` is an array having the following properties:
-
-- `code`: The ISO-2 name of the language. For example, `da` for Danish.
-- `display_name`: The language's name to be displayed in the admin.
-- `ltr`: Whether the language supports a left-to-right layout. For example, set this to `false` for languages like Arabic.
-- `date_locale`: An instance of the locale imported from the [date-fns/locale](https://date-fns.org/) package.
-
-8. Once you're done, push the changes into your branch and open a pull request on GitHub.
-
-Our team will perform a general review on your PR and merge it if no issues are found. The translation will be available in the admin after the next release.
-
-
-# Docs Contribution Guidelines
-
-Thank you for your interest in contributing to the documentation! You will be helping the open source community and other developers interested in learning more about Medusa and using it.
-
-This guide is specific to contributing to the documentation. If you’re interested in contributing to Medusa’s codebase, check out the [contributing guidelines in the Medusa GitHub repository](https://github.com/medusajs/medusa/blob/develop/CONTRIBUTING.md).
-
-## What Can You Contribute?
-
-You can contribute to the Medusa documentation in the following ways:
-
-- Fixes to existing content. This includes small fixes like typos, or adding missing information.
-- Additions to the documentation. If you think a documentation page can be useful to other developers, you can contribute by adding it.
- - Make sure to open an issue first in the [medusa repository](https://github.com/medusajs/medusa) to confirm that you can add that documentation page.
-- Fixes to UI components and tooling. If you find a bug while browsing the documentation, you can contribute by fixing it.
+You use the `moduleIntegrationTestRunner` function to add tests for the `blog` module. You have one test that passes if the `getMessage` method returns the `"Hello, World!"` string.
***
-## Documentation Workspace
+## Run Test
-Medusa's documentation projects are all part of the documentation yarn workspace, which you can find in the [medusa repository](https://github.com/medusajs/medusa) under the `www` directory.
-
-The workspace has the following two directories:
-
-- `apps`: this directory holds the different documentation websites and projects.
- - `book`: includes the codebase for the [main Medusa documentation](https://docs.medusajs.com//index.html.md). It's built with [Next.js 15](https://nextjs.org/).
- - `resources`: includes the codebase for the resources documentation, which powers different sections of the docs such as the [Integrations](https://docs.medusajs.com/resources/integrations/index.html.md) or [How-to & Tutorials](https://docs.medusajs.com/resources/how-to-tutorials/index.html.md) sections. It's built with [Next.js 15](https://nextjs.org/).
- - `api-reference`: includes the codebase for the API reference website. It's built with [Next.js 15](https://nextjs.org/).
- - `ui`: includes the codebase for the Medusa UI documentation website. It's built with [Next.js 15](https://nextjs.org/).
-- `packages`: this directory holds the shared packages and components necessary for the development of the projects in the `apps` directory.
- - `docs-ui` includes the shared React components between the different apps.
- - `remark-rehype-plugins` includes Remark and Rehype plugins used by the documentation projects.
-
-***
-
-## Documentation Content
-
-All documentation projects are built with Next.js. The content is writtin in MDX files.
-
-### Medusa Main Docs Content
-
-The content of the Medusa main docs are under the `www/apps/book/app` directory.
-
-### Medusa Resources Content
-
-The content of all pages under the `/resources` path are under the `www/apps/resources/app` directory.
-
-Documentation pages under the `www/apps/resources/references` directory are generated automatically from the source code under the `packages/medusa` directory. So, you can't directly make changes to them. Instead, you'll have to make changes to the comments in the original source code.
-
-### API Reference
-
-The API reference's content is split into two types:
-
-1. Static content, which are the content related to getting started, expanding fields, and more. These are located in the `www/apps/api-reference/markdown` directory. They are MDX files.
-2. OpenAPI specs that are shown to developers when checking the reference of an API Route. These are generated from OpenApi Spec comments, which are under the `www/utils/generated/oas-output` directory.
-
-### Medusa UI Documentation
-
-The content of the Medusa UI documentation are located under the `www/apps/ui/src/content/docs` directory. They are MDX files.
-
-The UI documentation also shows code examples, which are under the `www/apps/ui/src/examples` directory.
-
-The UI component props are generated from the source code and placed into the `www/apps/ui/src/specs` directory. To contribute to these props and their comments, check the comments in the source code under the `packages/design-system/ui` directory.
-
-***
-
-## Style Guide
-
-When you contribute to the documentation content, make sure to follow the [documentation style guide](https://www.notion.so/Style-Guide-Docs-fad86dd1c5f84b48b145e959f36628e0).
-
-***
-
-## How to Contribute
-
-If you’re fixing errors in an existing documentation page, you can scroll down to the end of the page and click on the “Edit this page” link. You’ll be redirected to the GitHub edit form of that page and you can make edits directly and submit a pull request (PR).
-
-If you’re adding a new page or contributing to the codebase, fork the repository, create a new branch, and make all changes necessary in your repository. Then, once you’re done, create a PR in the Medusa repository.
-
-### Base Branch
-
-When you make an edit to an existing documentation page or fork the repository to make changes to the documentation, create a new branch.
-
-Documentation contributions always use `develop` as the base branch. Make sure to also open your PR against the `develop` branch.
-
-### Branch Name
-
-Make sure that the branch name starts with `docs/`. For example, `docs/fix-services`. Vercel deployed previews are only triggered for branches starting with `docs/`.
-
-### Pull Request Conventions
-
-When you create a pull request, prefix the title with `docs:` or `docs(PROJECT_NAME):`, where `PROJECT_NAME` is the name of the documentation project this pull request pertains to. For example, `docs(ui): fix titles`.
-
-In the body of the PR, explain clearly what the PR does. If the PR solves an issue, use [closing keywords](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword) with the issue number. For example, “Closes #1333”.
-
-***
-
-## Images
-
-If you are adding images to a documentation page, you can host the image on [Imgur](https://imgur.com) for free to include it in the PR. Our team will later upload it to our image hosting.
-
-***
-
-## NPM and Yarn Code Blocks
-
-If you’re adding code blocks that use NPM and Yarn, you must add the `npm2yarn` meta field.
-
-For example:
-
-````md
-```bash npm2yarn
-npm run start
-```
-````
-
-The code snippet must be written using NPM.
-
-### Global Option
-
-When a command uses the global option `-g`, add it at the end of the NPM command to ensure that it’s transformed to a Yarn command properly. For example:
+Run the following command to run your module integration tests:
```bash npm2yarn
-npm install @medusajs/cli -g
+npm run test:integration:modules
```
-***
+If you don't have a `test:integration:modules` script in `package.json`, refer to the [Medusa Testing Tools chapter](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools#add-test-commands/index.html.md).
-## Linting with Vale
-
-Medusa uses [Vale](https://vale.sh/) to lint documentation pages and perform checks on incoming PRs into the repository.
-
-### Result of Vale PR Checks
-
-You can check the result of running the "lint" action on your PR by clicking the Details link next to it. You can find there all errors that you need to fix.
-
-### Run Vale Locally
-
-If you want to check your work locally, you can do that by:
-
-1. [Installing Vale](https://vale.sh/docs/vale-cli/installation/) on your machine.
-2. Changing to the `www/vale` directory:
-
-```bash
-cd www/vale
-```
-
-3\. Running the `run-vale` script:
-
-```bash
-# to lint content for the main documentation
-./run-vale.sh book/app/learn error resources
-# to lint content for the resources documentation
-./run-vale.sh resources/app error
-# to lint content for the API reference
-./run-vale.sh api-reference/markdown error
-# to lint content for the Medusa UI documentation
-./run-vale.sh ui/src/content/docs error
-# to lint content for the user guide
-./run-vale.sh user-guide/app error
-```
-
-{/* TODO need to enable MDX v1 comments first. */}
-
-{/* ### Linter Exceptions
-
-If it's needed to break some style guide rules in a document, you can wrap the parts that the linter shouldn't scan with the following comments in the `md` or `mdx` files:
-
-```md
-
-
-content that shouldn't be scanned for errors here...
-
-
-```
-
-You can also disable specific rules. For example:
-
-```md
-
-
-Medusa supports Node versions 14 and 16.
-
-
-```
-
-If you use this in your PR, you must justify its usage. */}
-
-***
-
-## Linting with ESLint
-
-Medusa uses ESlint to lint code blocks both in the content and the code base of the documentation apps.
-
-### Linting Content with ESLint
-
-Each PR runs through a check that lints the code in the content files using ESLint. The action's name is `content-eslint`.
-
-If you want to check content ESLint errors locally and fix them, you can do that by:
-
-1\. Install the dependencies in the `www` directory:
-
-```bash
-yarn install
-```
-
-2\. Run the turbo command in the `www` directory:
-
-```bash
-turbo run lint:content
-```
-
-This will fix any fixable errors, and show errors that require your action.
-
-### Linting Code with ESLint
-
-Each PR runs through a check that lints the code in the content files using ESLint. The action's name is `code-docs-eslint`.
-
-If you want to check code ESLint errors locally and fix them, you can do that by:
-
-1\. Install the dependencies in the `www` directory:
-
-```bash
-yarn install
-```
-
-2\. Run the turbo command in the `www` directory:
-
-```bash
-yarn lint
-```
-
-This will fix any fixable errors, and show errors that require your action.
-
-{/* TODO need to enable MDX v1 comments first. */}
-
-{/* ### ESLint Exceptions
-
-If some code blocks have errors that can't or shouldn't be fixed, you can add the following command before the code block:
-
-~~~md
-
-
-```js
-console.log("This block isn't linted")
-```
-
-```js
-console.log("This block is linted")
-```
-~~~
-
-You can also disable specific rules. For example:
-
-~~~md
-
-
-```js
-console.log("This block can use semicolons");
-```
-
-```js
-console.log("This block can't use semi colons")
-```
-~~~ */}
+This runs your Medusa application and runs the tests available in any `__tests__` directory under the `src/modules` directory.
# Example: Write Integration Tests for API Routes
@@ -17023,129 +17905,6 @@ const response = await api.post(`/custom`, form, {
```
-# Example: Integration Tests for a Module
-
-In this chapter, find an example of writing an integration test for a module using [moduleIntegrationTestRunner](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools/modules-tests/index.html.md) from Medusa's Testing Framework.
-
-### Prerequisites
-
-- [Testing Tools Setup](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools/index.html.md)
-
-## Write Integration Test for Module
-
-Consider a `blog` module with a `BlogModuleService` that has a `getMessage` method:
-
-```ts title="src/modules/blog/service.ts"
-import { MedusaService } from "@medusajs/framework/utils"
-import MyCustom from "./models/my-custom"
-
-class BlogModuleService extends MedusaService({
- MyCustom,
-}){
- getMessage(): string {
- return "Hello, World!"
- }
-}
-
-export default BlogModuleService
-```
-
-To create an integration test for the method, create the file `src/modules/blog/__tests__/service.spec.ts` with the following content:
-
-```ts title="src/modules/blog/__tests__/service.spec.ts"
-import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
-import { BLOG_MODULE } from ".."
-import BlogModuleService from "../service"
-import MyCustom from "../models/my-custom"
-
-moduleIntegrationTestRunner({
- moduleName: BLOG_MODULE,
- moduleModels: [MyCustom],
- resolve: "./src/modules/blog",
- testSuite: ({ service }) => {
- describe("BlogModuleService", () => {
- it("says hello world", () => {
- const message = service.getMessage()
-
- expect(message).toEqual("Hello, World!")
- })
- })
- },
-})
-
-jest.setTimeout(60 * 1000)
-```
-
-You use the `moduleIntegrationTestRunner` function to add tests for the `blog` module. You have one test that passes if the `getMessage` method returns the `"Hello, World!"` string.
-
-***
-
-## Run Test
-
-Run the following command to run your module integration tests:
-
-```bash npm2yarn
-npm run test:integration:modules
-```
-
-If you don't have a `test:integration:modules` script in `package.json`, refer to the [Medusa Testing Tools chapter](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools#add-test-commands/index.html.md).
-
-This runs your Medusa application and runs the tests available in any `__tests__` directory under the `src/modules` directory.
-
-
-# Run Workflow Steps in Parallel
-
-In this chapter, you’ll learn how to run workflow steps in parallel.
-
-## parallelize Utility Function
-
-If your workflow has steps that don’t rely on one another’s results, run them in parallel using `parallelize` from the Workflows SDK.
-
-The workflow waits until all steps passed to the `parallelize` function finish executing before continuing to the next step.
-
-For example:
-
-```ts highlights={highlights} collapsibleLines="1-12" expandButtonLabel="Show Imports"
-import {
- createWorkflow,
- WorkflowResponse,
- parallelize,
-} from "@medusajs/framework/workflows-sdk"
-import {
- createProductStep,
- getProductStep,
- createPricesStep,
- attachProductToSalesChannelStep,
-} from "./steps"
-
-interface WorkflowInput {
- title: string
-}
-
-const myWorkflow = createWorkflow(
- "my-workflow",
- (input: WorkflowInput) => {
- const product = createProductStep(input)
-
- const [prices, productSalesChannel] = parallelize(
- createPricesStep(product),
- attachProductToSalesChannelStep(product)
- )
-
- const refetchedProduct = getProductStep(product.id)
-
- return new WorkflowResponse(refetchedProduct)
- }
-)
-```
-
-The `parallelize` function accepts the steps to run in parallel as a parameter.
-
-It returns an array of the steps' results in the same order they're passed to the `parallelize` function.
-
-So, `prices` is the result of `createPricesStep`, and `productSalesChannel` is the result of `attachProductToSalesChannelStep`.
-
-
# Example: Write Integration Tests for Workflows
In this chapter, you'll learn how to write integration tests for workflows using [medusaIntegrationTestRunner](https://docs.medusajs.com/learn/debugging-and-testing/testing-tools/integration-tests/index.html.md) from Medusa's Testing Framwork.
@@ -17598,6 +18357,154 @@ Learn more about workflows in [this documentation](https://docs.medusajs.com/doc
***
+# Currency Module
+
+In this section of the documentation, you will find resources to learn more about the Currency Module and how to use it in your application.
+
+Refer to the [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/store/index.html.md) to learn how to manage your store's currencies using the dashboard.
+
+Medusa has currency related features available out-of-the-box through the Currency Module. A [module](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md) is a standalone package that provides features for a single domain. Each of Medusa's commerce features are placed in commerce modules, such as this Currency Module.
+
+Learn more about why modules are isolated in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/isolation/index.html.md).
+
+## Currency Features
+
+- [Currency Management and Retrieval](https://docs.medusajs.com/references/currency/listAndCountCurrencies/index.html.md): This module adds all common currencies to your application and allows you to retrieve them.
+- [Support Currencies in Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/currency/links-to-other-modules/index.html.md): Other commerce modules use currency codes in their data models or operations. Use the Currency Module to retrieve a currency code and its details.
+
+***
+
+## How to Use the Currency Module
+
+In your Medusa application, you build flows around commerce modules. A flow is built as a [Workflow](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md), which is a special function composed of a series of steps that guarantees data consistency and reliable roll-back mechanism.
+
+You can build custom workflows and steps. You can also re-use Medusa's workflows and steps, which are provided by the `@medusajs/medusa/core-flows` package.
+
+For example:
+
+```ts title="src/workflows/retrieve-price-with-currency.ts" highlights={highlights}
+import {
+ createWorkflow,
+ WorkflowResponse,
+ createStep,
+ StepResponse,
+ transform,
+} from "@medusajs/framework/workflows-sdk"
+import { Modules } from "@medusajs/framework/utils"
+
+const retrieveCurrencyStep = createStep(
+ "retrieve-currency",
+ async ({}, { container }) => {
+ const currencyModuleService = container.resolve(Modules.CURRENCY)
+
+ const currency = await currencyModuleService
+ .retrieveCurrency("usd")
+
+ return new StepResponse({ currency })
+ }
+)
+
+type Input = {
+ price: number
+}
+
+export const retrievePriceWithCurrency = createWorkflow(
+ "create-currency",
+ (input: Input) => {
+ const { currency } = retrieveCurrencyStep()
+
+ const formattedPrice = transform({
+ input,
+ currency,
+ }, (data) => {
+ return `${data.currency.symbol}${data.input.price}`
+ })
+
+ return new WorkflowResponse({
+ formattedPrice,
+ })
+ }
+)
+```
+
+You can then execute the workflow in your custom API routes, scheduled jobs, or subscribers:
+
+### API Route
+
+```ts title="src/api/workflow/route.ts" highlights={[["11"], ["12"], ["13"], ["14"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
+import type {
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { retrievePriceWithCurrency } from "../../workflows/retrieve-price-with-currency"
+
+export async function GET(
+ req: MedusaRequest,
+ res: MedusaResponse
+) {
+ const { result } = await retrievePriceWithCurrency(req.scope)
+ .run({
+ price: 10,
+ })
+
+ res.send(result)
+}
+```
+
+### Subscriber
+
+```ts title="src/subscribers/user-created.ts" highlights={[["11"], ["12"], ["13"], ["14"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
+import {
+ type SubscriberConfig,
+ type SubscriberArgs,
+} from "@medusajs/framework"
+import { retrievePriceWithCurrency } from "../workflows/retrieve-price-with-currency"
+
+export default async function handleUserCreated({
+ event: { data },
+ container,
+}: SubscriberArgs<{ id: string }>) {
+ const { result } = await retrievePriceWithCurrency(container)
+ .run({
+ price: 10,
+ })
+
+ console.log(result)
+}
+
+export const config: SubscriberConfig = {
+ event: "user.created",
+}
+```
+
+### Scheduled Job
+
+```ts title="src/jobs/run-daily.ts" highlights={[["7"], ["8"], ["9"], ["10"]]}
+import { MedusaContainer } from "@medusajs/framework/types"
+import { retrievePriceWithCurrency } from "../workflows/retrieve-price-with-currency"
+
+export default async function myCustomJob(
+ container: MedusaContainer
+) {
+ const { result } = await retrievePriceWithCurrency(container)
+ .run({
+ price: 10,
+ })
+
+ console.log(result)
+}
+
+export const config = {
+ name: "run-once-a-day",
+ schedule: `0 0 * * *`,
+}
+```
+
+Learn more about workflows in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md).
+
+***
+
+
# Cart Module
In this section of the documentation, you will find resources to learn more about the Cart Module and how to use it in your application.
@@ -17748,136 +18655,6 @@ Learn more about workflows in [this documentation](https://docs.medusajs.com/doc
***
-# Auth Module
-
-In this section of the documentation, you will find resources to learn more about the Auth Module and how to use it in your application.
-
-Medusa has auth related features available out-of-the-box through the Auth Module. A [module](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md) is a standalone package that provides features for a single domain. Each of Medusa's commerce features are placed in commerce modules, such as this Auth Module.
-
-Learn more about why modules are isolated in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/isolation/index.html.md).
-
-## Auth Features
-
-- [Basic User Authentication](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#1-basic-authentication-flow/index.html.md): Authenticate users using their email and password credentials.
-- [Third-Party and Social Authentication](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#2-third-party-service-authenticate-flow/index.html.md): Authenticate users using third-party services and social platforms, such as [Google](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-providers/google/index.html.md) and [GitHub](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-providers/github/index.html.md).
-- [Authenticate Custom Actor Types](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/create-actor-type/index.html.md): Create custom user or actor types, such as managers, authenticate them in your application, and guard routes based on the custom user types.
-- [Custom Authentication Providers](https://docs.medusajs.com/references/auth/provider/index.html.md): Integrate third-party services with custom authentication providors.
-
-***
-
-## How to Use the Auth Module
-
-In your Medusa application, you build flows around commerce modules. A flow is built as a [Workflow](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md), which is a special function composed of a series of steps that guarantees data consistency and reliable roll-back mechanism.
-
-You can build custom workflows and steps. You can also re-use Medusa's workflows and steps, which are provided by the `@medusajs/medusa/core-flows` package.
-
-For example:
-
-```ts title="src/workflows/authenticate-user.ts" highlights={highlights}
-import {
- createWorkflow,
- WorkflowResponse,
- createStep,
- StepResponse,
-} from "@medusajs/framework/workflows-sdk"
-import { Modules, MedusaError } from "@medusajs/framework/utils"
-import { MedusaRequest } from "@medusajs/framework/http"
-import { AuthenticationInput } from "@medusajs/framework/types"
-
-type Input = {
- req: MedusaRequest
-}
-
-const authenticateUserStep = createStep(
- "authenticate-user",
- async ({ req }: Input, { container }) => {
- const authModuleService = container.resolve(Modules.AUTH)
-
- const { success, authIdentity, error } = await authModuleService
- .authenticate(
- "emailpass",
- {
- url: req.url,
- headers: req.headers,
- query: req.query,
- body: req.body,
- authScope: "admin", // or custom actor type
- protocol: req.protocol,
- } as AuthenticationInput
- )
-
- if (!success) {
- // incorrect authentication details
- throw new MedusaError(
- MedusaError.Types.UNAUTHORIZED,
- error || "Incorrect authentication details"
- )
- }
-
- return new StepResponse({ authIdentity }, authIdentity?.id)
- },
- async (authIdentityId, { container }) => {
- if (!authIdentityId) {
- return
- }
-
- const authModuleService = container.resolve(Modules.AUTH)
-
- await authModuleService.deleteAuthIdentities([authIdentityId])
- }
-)
-
-export const authenticateUserWorkflow = createWorkflow(
- "authenticate-user",
- (input: Input) => {
- const { authIdentity } = authenticateUserStep(input)
-
- return new WorkflowResponse({
- authIdentity,
- })
- }
-)
-```
-
-You can then execute the workflow in your custom API routes, scheduled jobs, or subscribers:
-
-```ts title="API Route" highlights={[["11"], ["12"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
-import type {
- MedusaRequest,
- MedusaResponse,
-} from "@medusajs/framework/http"
-import { authenticateUserWorkflow } from "../../workflows/authenticate-user"
-
-export async function GET(
- req: MedusaRequest,
- res: MedusaResponse
-) {
- const { result } = await authenticateUserWorkflow(req.scope)
- .run({
- req,
- })
-
- res.send(result)
-}
-```
-
-Learn more about workflows in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md).
-
-***
-
-## Configure Auth Module
-
-The Auth Module accepts options for further configurations. Refer to [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/module-options/index.html.md) for details on the module's options.
-
-***
-
-## Providers
-
-Medusa provides the following authentication providers out-of-the-box. You can use them to authenticate admin users, customers, or custom actor types.
-
-***
-
-
# Fulfillment Module
In this section of the documentation, you will find resources to learn more about the Fulfillment Module and how to use it in your application.
@@ -18044,6 +18821,136 @@ The Fulfillment Module accepts options for further configurations. Refer to [thi
***
+# Auth Module
+
+In this section of the documentation, you will find resources to learn more about the Auth Module and how to use it in your application.
+
+Medusa has auth related features available out-of-the-box through the Auth Module. A [module](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md) is a standalone package that provides features for a single domain. Each of Medusa's commerce features are placed in commerce modules, such as this Auth Module.
+
+Learn more about why modules are isolated in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/isolation/index.html.md).
+
+## Auth Features
+
+- [Basic User Authentication](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#1-basic-authentication-flow/index.html.md): Authenticate users using their email and password credentials.
+- [Third-Party and Social Authentication](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#2-third-party-service-authenticate-flow/index.html.md): Authenticate users using third-party services and social platforms, such as [Google](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-providers/google/index.html.md) and [GitHub](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-providers/github/index.html.md).
+- [Authenticate Custom Actor Types](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/create-actor-type/index.html.md): Create custom user or actor types, such as managers, authenticate them in your application, and guard routes based on the custom user types.
+- [Custom Authentication Providers](https://docs.medusajs.com/references/auth/provider/index.html.md): Integrate third-party services with custom authentication providors.
+
+***
+
+## How to Use the Auth Module
+
+In your Medusa application, you build flows around commerce modules. A flow is built as a [Workflow](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md), which is a special function composed of a series of steps that guarantees data consistency and reliable roll-back mechanism.
+
+You can build custom workflows and steps. You can also re-use Medusa's workflows and steps, which are provided by the `@medusajs/medusa/core-flows` package.
+
+For example:
+
+```ts title="src/workflows/authenticate-user.ts" highlights={highlights}
+import {
+ createWorkflow,
+ WorkflowResponse,
+ createStep,
+ StepResponse,
+} from "@medusajs/framework/workflows-sdk"
+import { Modules, MedusaError } from "@medusajs/framework/utils"
+import { MedusaRequest } from "@medusajs/framework/http"
+import { AuthenticationInput } from "@medusajs/framework/types"
+
+type Input = {
+ req: MedusaRequest
+}
+
+const authenticateUserStep = createStep(
+ "authenticate-user",
+ async ({ req }: Input, { container }) => {
+ const authModuleService = container.resolve(Modules.AUTH)
+
+ const { success, authIdentity, error } = await authModuleService
+ .authenticate(
+ "emailpass",
+ {
+ url: req.url,
+ headers: req.headers,
+ query: req.query,
+ body: req.body,
+ authScope: "admin", // or custom actor type
+ protocol: req.protocol,
+ } as AuthenticationInput
+ )
+
+ if (!success) {
+ // incorrect authentication details
+ throw new MedusaError(
+ MedusaError.Types.UNAUTHORIZED,
+ error || "Incorrect authentication details"
+ )
+ }
+
+ return new StepResponse({ authIdentity }, authIdentity?.id)
+ },
+ async (authIdentityId, { container }) => {
+ if (!authIdentityId) {
+ return
+ }
+
+ const authModuleService = container.resolve(Modules.AUTH)
+
+ await authModuleService.deleteAuthIdentities([authIdentityId])
+ }
+)
+
+export const authenticateUserWorkflow = createWorkflow(
+ "authenticate-user",
+ (input: Input) => {
+ const { authIdentity } = authenticateUserStep(input)
+
+ return new WorkflowResponse({
+ authIdentity,
+ })
+ }
+)
+```
+
+You can then execute the workflow in your custom API routes, scheduled jobs, or subscribers:
+
+```ts title="API Route" highlights={[["11"], ["12"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
+import type {
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { authenticateUserWorkflow } from "../../workflows/authenticate-user"
+
+export async function GET(
+ req: MedusaRequest,
+ res: MedusaResponse
+) {
+ const { result } = await authenticateUserWorkflow(req.scope)
+ .run({
+ req,
+ })
+
+ res.send(result)
+}
+```
+
+Learn more about workflows in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md).
+
+***
+
+## Configure Auth Module
+
+The Auth Module accepts options for further configurations. Refer to [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/module-options/index.html.md) for details on the module's options.
+
+***
+
+## Providers
+
+Medusa provides the following authentication providers out-of-the-box. You can use them to authenticate admin users, customers, or custom actor types.
+
+***
+
+
# Inventory Module
In this section of the documentation, you will find resources to learn more about the Inventory Module and how to use it in your application.
@@ -18344,161 +19251,6 @@ Learn more about workflows in [this documentation](https://docs.medusajs.com/doc
***
-# Payment Module
-
-In this section of the documentation, you will find resources to learn more about the Payment Module and how to use it in your application.
-
-Refer to the [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/orders/payments/index.html.md) to learn how to manage order payments using the dashboard.
-
-Medusa has payment related features available out-of-the-box through the Payment Module. A [module](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md) is a standalone package that provides features for a single domain. Each of Medusa's commerce features are placed in commerce modules, such as this Payment Module.
-
-Learn more about why modules are isolated in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/isolation/index.html.md).
-
-## Payment Features
-
-- [Authorize, Capture, and Refund Payments](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment/index.html.md): Authorize, capture, and refund payments for a single resource.
-- [Payment Collection Management](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-collection/index.html.md): Store and manage all payments of a single resources, such as a cart, in payment collections.
-- [Integrate Third-Party Payment Providers](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-provider/index.html.md): Use payment providers like [Stripe](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-provider/stripe/index.html.md) to handle and process payments, or integrate custom payment providers.
-- [Saved Payment Methods](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/account-holder/index.html.md): Save payment methods for customers in third-party payment providers.
-- [Handle Webhook Events](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/webhook-events/index.html.md): Handle webhook events from third-party providers and process the associated payment.
-
-***
-
-## How to Use the Payment Module
-
-In your Medusa application, you build flows around commerce modules. A flow is built as a [Workflow](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md), which is a special function composed of a series of steps that guarantees data consistency and reliable roll-back mechanism.
-
-You can build custom workflows and steps. You can also re-use Medusa's workflows and steps, which are provided by the `@medusajs/medusa/core-flows` package.
-
-For example:
-
-```ts title="src/workflows/create-payment-collection.ts" highlights={highlights}
-import {
- createWorkflow,
- WorkflowResponse,
- createStep,
- StepResponse,
-} from "@medusajs/framework/workflows-sdk"
-import { Modules } from "@medusajs/framework/utils"
-
-const createPaymentCollectionStep = createStep(
- "create-payment-collection",
- async ({}, { container }) => {
- const paymentModuleService = container.resolve(Modules.PAYMENT)
-
- const paymentCollection = await paymentModuleService.createPaymentCollections({
- currency_code: "usd",
- amount: 5000,
- })
-
- return new StepResponse({ paymentCollection }, paymentCollection.id)
- },
- async (paymentCollectionId, { container }) => {
- if (!paymentCollectionId) {
- return
- }
- const paymentModuleService = container.resolve(Modules.PAYMENT)
-
- await paymentModuleService.deletePaymentCollections([paymentCollectionId])
- }
-)
-
-export const createPaymentCollectionWorkflow = createWorkflow(
- "create-payment-collection",
- () => {
- const { paymentCollection } = createPaymentCollectionStep()
-
- return new WorkflowResponse({
- paymentCollection,
- })
- }
-)
-```
-
-You can then execute the workflow in your custom API routes, scheduled jobs, or subscribers:
-
-### API Route
-
-```ts title="src/api/workflow/route.ts" highlights={[["11"], ["12"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
-import type {
- MedusaRequest,
- MedusaResponse,
-} from "@medusajs/framework/http"
-import { createPaymentCollectionWorkflow } from "../../workflows/create-payment-collection"
-
-export async function GET(
- req: MedusaRequest,
- res: MedusaResponse
-) {
- const { result } = await createPaymentCollectionWorkflow(req.scope)
- .run()
-
- res.send(result)
-}
-```
-
-### Subscriber
-
-```ts title="src/subscribers/user-created.ts" highlights={[["11"], ["12"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
-import {
- type SubscriberConfig,
- type SubscriberArgs,
-} from "@medusajs/framework"
-import { createPaymentCollectionWorkflow } from "../workflows/create-payment-collection"
-
-export default async function handleUserCreated({
- event: { data },
- container,
-}: SubscriberArgs<{ id: string }>) {
- const { result } = await createPaymentCollectionWorkflow(container)
- .run()
-
- console.log(result)
-}
-
-export const config: SubscriberConfig = {
- event: "user.created",
-}
-```
-
-### Scheduled Job
-
-```ts title="src/jobs/run-daily.ts" highlights={[["7"], ["8"]]}
-import { MedusaContainer } from "@medusajs/framework/types"
-import { createPaymentCollectionWorkflow } from "../workflows/create-payment-collection"
-
-export default async function myCustomJob(
- container: MedusaContainer
-) {
- const { result } = await createPaymentCollectionWorkflow(container)
- .run()
-
- console.log(result)
-}
-
-export const config = {
- name: "run-once-a-day",
- schedule: `0 0 * * *`,
-}
-```
-
-Learn more about workflows in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md).
-
-***
-
-## Configure Payment Module
-
-The Payment Module accepts options for further configurations. Refer to [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/module-options/index.html.md) for details on the module's options.
-
-***
-
-## Providers
-
-Medusa provides the following payment providers out-of-the-box. You can use them to process payments for orders, returns, and other resources.
-
-***
-
-
# Pricing Module
In this section of the documentation, you will find resources to learn more about the Pricing Module and how to use it in your application.
@@ -18653,154 +19405,6 @@ Learn more about workflows in [this documentation](https://docs.medusajs.com/doc
***
-# Currency Module
-
-In this section of the documentation, you will find resources to learn more about the Currency Module and how to use it in your application.
-
-Refer to the [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/store/index.html.md) to learn how to manage your store's currencies using the dashboard.
-
-Medusa has currency related features available out-of-the-box through the Currency Module. A [module](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md) is a standalone package that provides features for a single domain. Each of Medusa's commerce features are placed in commerce modules, such as this Currency Module.
-
-Learn more about why modules are isolated in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/isolation/index.html.md).
-
-## Currency Features
-
-- [Currency Management and Retrieval](https://docs.medusajs.com/references/currency/listAndCountCurrencies/index.html.md): This module adds all common currencies to your application and allows you to retrieve them.
-- [Support Currencies in Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/currency/links-to-other-modules/index.html.md): Other commerce modules use currency codes in their data models or operations. Use the Currency Module to retrieve a currency code and its details.
-
-***
-
-## How to Use the Currency Module
-
-In your Medusa application, you build flows around commerce modules. A flow is built as a [Workflow](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md), which is a special function composed of a series of steps that guarantees data consistency and reliable roll-back mechanism.
-
-You can build custom workflows and steps. You can also re-use Medusa's workflows and steps, which are provided by the `@medusajs/medusa/core-flows` package.
-
-For example:
-
-```ts title="src/workflows/retrieve-price-with-currency.ts" highlights={highlights}
-import {
- createWorkflow,
- WorkflowResponse,
- createStep,
- StepResponse,
- transform,
-} from "@medusajs/framework/workflows-sdk"
-import { Modules } from "@medusajs/framework/utils"
-
-const retrieveCurrencyStep = createStep(
- "retrieve-currency",
- async ({}, { container }) => {
- const currencyModuleService = container.resolve(Modules.CURRENCY)
-
- const currency = await currencyModuleService
- .retrieveCurrency("usd")
-
- return new StepResponse({ currency })
- }
-)
-
-type Input = {
- price: number
-}
-
-export const retrievePriceWithCurrency = createWorkflow(
- "create-currency",
- (input: Input) => {
- const { currency } = retrieveCurrencyStep()
-
- const formattedPrice = transform({
- input,
- currency,
- }, (data) => {
- return `${data.currency.symbol}${data.input.price}`
- })
-
- return new WorkflowResponse({
- formattedPrice,
- })
- }
-)
-```
-
-You can then execute the workflow in your custom API routes, scheduled jobs, or subscribers:
-
-### API Route
-
-```ts title="src/api/workflow/route.ts" highlights={[["11"], ["12"], ["13"], ["14"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
-import type {
- MedusaRequest,
- MedusaResponse,
-} from "@medusajs/framework/http"
-import { retrievePriceWithCurrency } from "../../workflows/retrieve-price-with-currency"
-
-export async function GET(
- req: MedusaRequest,
- res: MedusaResponse
-) {
- const { result } = await retrievePriceWithCurrency(req.scope)
- .run({
- price: 10,
- })
-
- res.send(result)
-}
-```
-
-### Subscriber
-
-```ts title="src/subscribers/user-created.ts" highlights={[["11"], ["12"], ["13"], ["14"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
-import {
- type SubscriberConfig,
- type SubscriberArgs,
-} from "@medusajs/framework"
-import { retrievePriceWithCurrency } from "../workflows/retrieve-price-with-currency"
-
-export default async function handleUserCreated({
- event: { data },
- container,
-}: SubscriberArgs<{ id: string }>) {
- const { result } = await retrievePriceWithCurrency(container)
- .run({
- price: 10,
- })
-
- console.log(result)
-}
-
-export const config: SubscriberConfig = {
- event: "user.created",
-}
-```
-
-### Scheduled Job
-
-```ts title="src/jobs/run-daily.ts" highlights={[["7"], ["8"], ["9"], ["10"]]}
-import { MedusaContainer } from "@medusajs/framework/types"
-import { retrievePriceWithCurrency } from "../workflows/retrieve-price-with-currency"
-
-export default async function myCustomJob(
- container: MedusaContainer
-) {
- const { result } = await retrievePriceWithCurrency(container)
- .run({
- price: 10,
- })
-
- console.log(result)
-}
-
-export const config = {
- name: "run-once-a-day",
- schedule: `0 0 * * *`,
-}
-```
-
-Learn more about workflows in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md).
-
-***
-
-
# Product Module
In this section of the documentation, you will find resources to learn more about the Product Module and how to use it in your application.
@@ -18955,6 +19559,161 @@ Learn more about workflows in [this documentation](https://docs.medusajs.com/doc
***
+# Payment Module
+
+In this section of the documentation, you will find resources to learn more about the Payment Module and how to use it in your application.
+
+Refer to the [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/orders/payments/index.html.md) to learn how to manage order payments using the dashboard.
+
+Medusa has payment related features available out-of-the-box through the Payment Module. A [module](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md) is a standalone package that provides features for a single domain. Each of Medusa's commerce features are placed in commerce modules, such as this Payment Module.
+
+Learn more about why modules are isolated in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/isolation/index.html.md).
+
+## Payment Features
+
+- [Authorize, Capture, and Refund Payments](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment/index.html.md): Authorize, capture, and refund payments for a single resource.
+- [Payment Collection Management](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-collection/index.html.md): Store and manage all payments of a single resources, such as a cart, in payment collections.
+- [Integrate Third-Party Payment Providers](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-provider/index.html.md): Use payment providers like [Stripe](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-provider/stripe/index.html.md) to handle and process payments, or integrate custom payment providers.
+- [Saved Payment Methods](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/account-holder/index.html.md): Save payment methods for customers in third-party payment providers.
+- [Handle Webhook Events](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/webhook-events/index.html.md): Handle webhook events from third-party providers and process the associated payment.
+
+***
+
+## How to Use the Payment Module
+
+In your Medusa application, you build flows around commerce modules. A flow is built as a [Workflow](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md), which is a special function composed of a series of steps that guarantees data consistency and reliable roll-back mechanism.
+
+You can build custom workflows and steps. You can also re-use Medusa's workflows and steps, which are provided by the `@medusajs/medusa/core-flows` package.
+
+For example:
+
+```ts title="src/workflows/create-payment-collection.ts" highlights={highlights}
+import {
+ createWorkflow,
+ WorkflowResponse,
+ createStep,
+ StepResponse,
+} from "@medusajs/framework/workflows-sdk"
+import { Modules } from "@medusajs/framework/utils"
+
+const createPaymentCollectionStep = createStep(
+ "create-payment-collection",
+ async ({}, { container }) => {
+ const paymentModuleService = container.resolve(Modules.PAYMENT)
+
+ const paymentCollection = await paymentModuleService.createPaymentCollections({
+ currency_code: "usd",
+ amount: 5000,
+ })
+
+ return new StepResponse({ paymentCollection }, paymentCollection.id)
+ },
+ async (paymentCollectionId, { container }) => {
+ if (!paymentCollectionId) {
+ return
+ }
+ const paymentModuleService = container.resolve(Modules.PAYMENT)
+
+ await paymentModuleService.deletePaymentCollections([paymentCollectionId])
+ }
+)
+
+export const createPaymentCollectionWorkflow = createWorkflow(
+ "create-payment-collection",
+ () => {
+ const { paymentCollection } = createPaymentCollectionStep()
+
+ return new WorkflowResponse({
+ paymentCollection,
+ })
+ }
+)
+```
+
+You can then execute the workflow in your custom API routes, scheduled jobs, or subscribers:
+
+### API Route
+
+```ts title="src/api/workflow/route.ts" highlights={[["11"], ["12"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
+import type {
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { createPaymentCollectionWorkflow } from "../../workflows/create-payment-collection"
+
+export async function GET(
+ req: MedusaRequest,
+ res: MedusaResponse
+) {
+ const { result } = await createPaymentCollectionWorkflow(req.scope)
+ .run()
+
+ res.send(result)
+}
+```
+
+### Subscriber
+
+```ts title="src/subscribers/user-created.ts" highlights={[["11"], ["12"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
+import {
+ type SubscriberConfig,
+ type SubscriberArgs,
+} from "@medusajs/framework"
+import { createPaymentCollectionWorkflow } from "../workflows/create-payment-collection"
+
+export default async function handleUserCreated({
+ event: { data },
+ container,
+}: SubscriberArgs<{ id: string }>) {
+ const { result } = await createPaymentCollectionWorkflow(container)
+ .run()
+
+ console.log(result)
+}
+
+export const config: SubscriberConfig = {
+ event: "user.created",
+}
+```
+
+### Scheduled Job
+
+```ts title="src/jobs/run-daily.ts" highlights={[["7"], ["8"]]}
+import { MedusaContainer } from "@medusajs/framework/types"
+import { createPaymentCollectionWorkflow } from "../workflows/create-payment-collection"
+
+export default async function myCustomJob(
+ container: MedusaContainer
+) {
+ const { result } = await createPaymentCollectionWorkflow(container)
+ .run()
+
+ console.log(result)
+}
+
+export const config = {
+ name: "run-once-a-day",
+ schedule: `0 0 * * *`,
+}
+```
+
+Learn more about workflows in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md).
+
+***
+
+## Configure Payment Module
+
+The Payment Module accepts options for further configurations. Refer to [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/module-options/index.html.md) for details on the module's options.
+
+***
+
+## Providers
+
+Medusa provides the following payment providers out-of-the-box. You can use them to process payments for orders, returns, and other resources.
+
+***
+
+
# Promotion Module
In this section of the documentation, you will find resources to learn more about the Promotion Module and how to use it in your application.
@@ -19246,24 +20005,38 @@ Learn more about workflows in [this documentation](https://docs.medusajs.com/doc
***
-# Stock Location Module
+# Sales Channel Module
-In this section of the documentation, you will find resources to learn more about the Stock Location Module and how to use it in your application.
+In this section of the documentation, you will find resources to learn more about the Sales Channel Module and how to use it in your application.
-Refer to the [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/locations-and-shipping/index.html.md) to learn how to manage stock locations using the dashboard.
+Refer to the [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/sales-channels/index.html.md) to learn how to manage sales channels using the dashboard.
-Medusa has stock location related features available out-of-the-box through the Stock Location Module. A [module](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md) is a standalone package that provides features for a single domain. Each of Medusa's commerce features are placed in commerce modules, such as this Stock Location Module.
+Medusa has sales channel related features available out-of-the-box through the Sales Channel Module. A [module](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md) is a standalone package that provides features for a single domain. Each of Medusa's commerce features are placed in commerce modules, such as this Sales Channel Module.
Learn more about why modules are isolated in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/isolation/index.html.md).
-## Stock Location Features
+## What's a Sales Channel?
-- [Stock Location Management](https://docs.medusajs.com/references/stock-location-next/models/index.html.md): Store and manage stock locations. Medusa links stock locations with data models of other modules that require a location, such as the [Inventory Module's InventoryLevel](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/stock-location/links-to-other-modules/index.html.md).
-- [Address Management](https://docs.medusajs.com/references/stock-location-next/models/StockLocationAddress/index.html.md): Manage the address of each stock location.
+A sales channel indicates an online or offline channel that you sell products on.
+
+Some use case examples for using a sales channel:
+
+- Implement a B2B Ecommerce Store.
+- Specify different products for each channel you sell in.
+- Support omnichannel in your ecommerce store.
***
-## How to Use Stock Location Module's Service
+## Sales Channel Features
+
+- [Sales Channel Management](https://docs.medusajs.com/references/sales-channel/models/SalesChannel/index.html.md): Manage sales channels in your store. Each sales channel has different meta information such as name or description, allowing you to easily differentiate between sales channels.
+- [Product Availability](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/sales-channel/links-to-other-modules/index.html.md): Medusa uses the Product and Sales Channel modules to allow merchants to specify a product's availability per sales channel.
+- [Cart and Order Scoping](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/sales-channel/links-to-other-modules/index.html.md): Carts, available through the Cart Module, are scoped to a sales channel. Paired with the product availability feature, you benefit from more features like allowing only products available in sales channel in a cart.
+- [Inventory Availability Per Sales Channel](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/sales-channel/links-to-other-modules/index.html.md): Medusa links sales channels to stock locations, allowing you to retrieve available inventory of products based on the specified sales channel.
+
+***
+
+## How to Use Sales Channel Module's Service
In your Medusa application, you build flows around commerce modules. A flow is built as a [Workflow](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md), which is a special function composed of a series of steps that guarantees data consistency and reliable roll-back mechanism.
@@ -19271,7 +20044,7 @@ You can build custom workflows and steps. You can also re-use Medusa's workflows
For example:
-```ts title="src/workflows/create-stock-location.ts" highlights={highlights}
+```ts title="src/workflows/create-sales-channel.ts" highlights={highlights}
import {
createWorkflow,
WorkflowResponse,
@@ -19280,33 +20053,42 @@ import {
} from "@medusajs/framework/workflows-sdk"
import { Modules } from "@medusajs/framework/utils"
-const createStockLocationStep = createStep(
- "create-stock-location",
+const createSalesChannelStep = createStep(
+ "create-sales-channel",
async ({}, { container }) => {
- const stockLocationModuleService = container.resolve(Modules.STOCK_LOCATION)
+ const salesChannelModuleService = container.resolve(Modules.SALES_CHANNEL)
- const stockLocation = await stockLocationModuleService.createStockLocations({
- name: "Warehouse 1",
- })
+ const salesChannels = await salesChannelModuleService.createSalesChannels([
+ {
+ name: "B2B",
+ },
+ {
+ name: "Mobile App",
+ },
+ ])
- return new StepResponse({ stockLocation }, stockLocation.id)
+ return new StepResponse({ salesChannels }, salesChannels.map((sc) => sc.id))
},
- async (stockLocationId, { container }) => {
- if (!stockLocationId) {
+ async (salesChannelIds, { container }) => {
+ if (!salesChannelIds) {
return
}
- const stockLocationModuleService = container.resolve(Modules.STOCK_LOCATION)
+ const salesChannelModuleService = container.resolve(Modules.SALES_CHANNEL)
- await stockLocationModuleService.deleteStockLocations([stockLocationId])
+ await salesChannelModuleService.deleteSalesChannels(
+ salesChannelIds
+ )
}
)
-export const createStockLocationWorkflow = createWorkflow(
- "create-stock-location",
+export const createSalesChannelWorkflow = createWorkflow(
+ "create-sales-channel",
() => {
- const { stockLocation } = createStockLocationStep()
+ const { salesChannels } = createSalesChannelStep()
- return new WorkflowResponse({ stockLocation })
+ return new WorkflowResponse({
+ salesChannels,
+ })
}
)
```
@@ -19320,13 +20102,13 @@ import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
-import { createStockLocationWorkflow } from "../../workflows/create-stock-location"
+import { createSalesChannelWorkflow } from "../../workflows/create-sales-channel"
export async function GET(
req: MedusaRequest,
res: MedusaResponse
) {
- const { result } = await createStockLocationWorkflow(req.scope)
+ const { result } = await createSalesChannelWorkflow(req.scope)
.run()
res.send(result)
@@ -19340,13 +20122,13 @@ import {
type SubscriberConfig,
type SubscriberArgs,
} from "@medusajs/framework"
-import { createStockLocationWorkflow } from "../workflows/create-stock-location"
+import { createSalesChannelWorkflow } from "../workflows/create-sales-channel"
export default async function handleUserCreated({
event: { data },
container,
}: SubscriberArgs<{ id: string }>) {
- const { result } = await createStockLocationWorkflow(container)
+ const { result } = await createSalesChannelWorkflow(container)
.run()
console.log(result)
@@ -19361,12 +20143,12 @@ export const config: SubscriberConfig = {
```ts title="src/jobs/run-daily.ts" highlights={[["7"], ["8"]]}
import { MedusaContainer } from "@medusajs/framework/types"
-import { createStockLocationWorkflow } from "../workflows/create-stock-location"
+import { createSalesChannelWorkflow } from "../workflows/create-sales-channel"
export default async function myCustomJob(
container: MedusaContainer
) {
- const { result } = await createStockLocationWorkflow(container)
+ const { result } = await createSalesChannelWorkflow(container)
.run()
console.log(result)
@@ -19524,6 +20306,143 @@ Learn more about workflows in [this documentation](https://docs.medusajs.com/doc
***
+# Stock Location Module
+
+In this section of the documentation, you will find resources to learn more about the Stock Location Module and how to use it in your application.
+
+Refer to the [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/locations-and-shipping/index.html.md) to learn how to manage stock locations using the dashboard.
+
+Medusa has stock location related features available out-of-the-box through the Stock Location Module. A [module](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md) is a standalone package that provides features for a single domain. Each of Medusa's commerce features are placed in commerce modules, such as this Stock Location Module.
+
+Learn more about why modules are isolated in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/isolation/index.html.md).
+
+## Stock Location Features
+
+- [Stock Location Management](https://docs.medusajs.com/references/stock-location-next/models/index.html.md): Store and manage stock locations. Medusa links stock locations with data models of other modules that require a location, such as the [Inventory Module's InventoryLevel](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/stock-location/links-to-other-modules/index.html.md).
+- [Address Management](https://docs.medusajs.com/references/stock-location-next/models/StockLocationAddress/index.html.md): Manage the address of each stock location.
+
+***
+
+## How to Use Stock Location Module's Service
+
+In your Medusa application, you build flows around commerce modules. A flow is built as a [Workflow](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md), which is a special function composed of a series of steps that guarantees data consistency and reliable roll-back mechanism.
+
+You can build custom workflows and steps. You can also re-use Medusa's workflows and steps, which are provided by the `@medusajs/medusa/core-flows` package.
+
+For example:
+
+```ts title="src/workflows/create-stock-location.ts" highlights={highlights}
+import {
+ createWorkflow,
+ WorkflowResponse,
+ createStep,
+ StepResponse,
+} from "@medusajs/framework/workflows-sdk"
+import { Modules } from "@medusajs/framework/utils"
+
+const createStockLocationStep = createStep(
+ "create-stock-location",
+ async ({}, { container }) => {
+ const stockLocationModuleService = container.resolve(Modules.STOCK_LOCATION)
+
+ const stockLocation = await stockLocationModuleService.createStockLocations({
+ name: "Warehouse 1",
+ })
+
+ return new StepResponse({ stockLocation }, stockLocation.id)
+ },
+ async (stockLocationId, { container }) => {
+ if (!stockLocationId) {
+ return
+ }
+ const stockLocationModuleService = container.resolve(Modules.STOCK_LOCATION)
+
+ await stockLocationModuleService.deleteStockLocations([stockLocationId])
+ }
+)
+
+export const createStockLocationWorkflow = createWorkflow(
+ "create-stock-location",
+ () => {
+ const { stockLocation } = createStockLocationStep()
+
+ return new WorkflowResponse({ stockLocation })
+ }
+)
+```
+
+You can then execute the workflow in your custom API routes, scheduled jobs, or subscribers:
+
+### API Route
+
+```ts title="src/api/workflow/route.ts" highlights={[["11"], ["12"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
+import type {
+ MedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { createStockLocationWorkflow } from "../../workflows/create-stock-location"
+
+export async function GET(
+ req: MedusaRequest,
+ res: MedusaResponse
+) {
+ const { result } = await createStockLocationWorkflow(req.scope)
+ .run()
+
+ res.send(result)
+}
+```
+
+### Subscriber
+
+```ts title="src/subscribers/user-created.ts" highlights={[["11"], ["12"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
+import {
+ type SubscriberConfig,
+ type SubscriberArgs,
+} from "@medusajs/framework"
+import { createStockLocationWorkflow } from "../workflows/create-stock-location"
+
+export default async function handleUserCreated({
+ event: { data },
+ container,
+}: SubscriberArgs<{ id: string }>) {
+ const { result } = await createStockLocationWorkflow(container)
+ .run()
+
+ console.log(result)
+}
+
+export const config: SubscriberConfig = {
+ event: "user.created",
+}
+```
+
+### Scheduled Job
+
+```ts title="src/jobs/run-daily.ts" highlights={[["7"], ["8"]]}
+import { MedusaContainer } from "@medusajs/framework/types"
+import { createStockLocationWorkflow } from "../workflows/create-stock-location"
+
+export default async function myCustomJob(
+ container: MedusaContainer
+) {
+ const { result } = await createStockLocationWorkflow(container)
+ .run()
+
+ console.log(result)
+}
+
+export const config = {
+ name: "run-once-a-day",
+ schedule: `0 0 * * *`,
+}
+```
+
+Learn more about workflows in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md).
+
+***
+
+
# Tax Module
In this section of the documentation, you will find resources to learn more about the Tax Module and how to use it in your application.
@@ -19815,194 +20734,6 @@ The User Module accepts options for further configurations. Refer to [this docum
***
-# API Key Concepts
-
-In this document, you’ll learn about the different types of API keys, their expiration and verification.
-
-## API Key Types
-
-There are two types of API keys:
-
-- `publishable`: A public key used in client applications, such as a storefront.
-- `secret`: A secret key used for authentication and verification purposes, such as an admin user’s authentication token or a password reset token.
-
-The API key’s type is stored in the `type` property of the [ApiKey data model](https://docs.medusajs.com/references/api-key/models/ApiKey/index.html.md).
-
-***
-
-## API Key Expiration
-
-An API key expires when it’s revoked using the [revoke method of the module’s main service](https://docs.medusajs.com/references/api-key/revoke/index.html.md).
-
-The associated token is no longer usable or verifiable.
-
-***
-
-## Token Verification
-
-To verify a token received as an input or in a request, use the [authenticate method of the module’s main service](https://docs.medusajs.com/references/api-key/authenticate/index.html.md) which validates the token against all non-expired tokens.
-
-
-# Sales Channel Module
-
-In this section of the documentation, you will find resources to learn more about the Sales Channel Module and how to use it in your application.
-
-Refer to the [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/sales-channels/index.html.md) to learn how to manage sales channels using the dashboard.
-
-Medusa has sales channel related features available out-of-the-box through the Sales Channel Module. A [module](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md) is a standalone package that provides features for a single domain. Each of Medusa's commerce features are placed in commerce modules, such as this Sales Channel Module.
-
-Learn more about why modules are isolated in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/isolation/index.html.md).
-
-## What's a Sales Channel?
-
-A sales channel indicates an online or offline channel that you sell products on.
-
-Some use case examples for using a sales channel:
-
-- Implement a B2B Ecommerce Store.
-- Specify different products for each channel you sell in.
-- Support omnichannel in your ecommerce store.
-
-***
-
-## Sales Channel Features
-
-- [Sales Channel Management](https://docs.medusajs.com/references/sales-channel/models/SalesChannel/index.html.md): Manage sales channels in your store. Each sales channel has different meta information such as name or description, allowing you to easily differentiate between sales channels.
-- [Product Availability](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/sales-channel/links-to-other-modules/index.html.md): Medusa uses the Product and Sales Channel modules to allow merchants to specify a product's availability per sales channel.
-- [Cart and Order Scoping](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/sales-channel/links-to-other-modules/index.html.md): Carts, available through the Cart Module, are scoped to a sales channel. Paired with the product availability feature, you benefit from more features like allowing only products available in sales channel in a cart.
-- [Inventory Availability Per Sales Channel](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/sales-channel/links-to-other-modules/index.html.md): Medusa links sales channels to stock locations, allowing you to retrieve available inventory of products based on the specified sales channel.
-
-***
-
-## How to Use Sales Channel Module's Service
-
-In your Medusa application, you build flows around commerce modules. A flow is built as a [Workflow](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md), which is a special function composed of a series of steps that guarantees data consistency and reliable roll-back mechanism.
-
-You can build custom workflows and steps. You can also re-use Medusa's workflows and steps, which are provided by the `@medusajs/medusa/core-flows` package.
-
-For example:
-
-```ts title="src/workflows/create-sales-channel.ts" highlights={highlights}
-import {
- createWorkflow,
- WorkflowResponse,
- createStep,
- StepResponse,
-} from "@medusajs/framework/workflows-sdk"
-import { Modules } from "@medusajs/framework/utils"
-
-const createSalesChannelStep = createStep(
- "create-sales-channel",
- async ({}, { container }) => {
- const salesChannelModuleService = container.resolve(Modules.SALES_CHANNEL)
-
- const salesChannels = await salesChannelModuleService.createSalesChannels([
- {
- name: "B2B",
- },
- {
- name: "Mobile App",
- },
- ])
-
- return new StepResponse({ salesChannels }, salesChannels.map((sc) => sc.id))
- },
- async (salesChannelIds, { container }) => {
- if (!salesChannelIds) {
- return
- }
- const salesChannelModuleService = container.resolve(Modules.SALES_CHANNEL)
-
- await salesChannelModuleService.deleteSalesChannels(
- salesChannelIds
- )
- }
-)
-
-export const createSalesChannelWorkflow = createWorkflow(
- "create-sales-channel",
- () => {
- const { salesChannels } = createSalesChannelStep()
-
- return new WorkflowResponse({
- salesChannels,
- })
- }
-)
-```
-
-You can then execute the workflow in your custom API routes, scheduled jobs, or subscribers:
-
-### API Route
-
-```ts title="src/api/workflow/route.ts" highlights={[["11"], ["12"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
-import type {
- MedusaRequest,
- MedusaResponse,
-} from "@medusajs/framework/http"
-import { createSalesChannelWorkflow } from "../../workflows/create-sales-channel"
-
-export async function GET(
- req: MedusaRequest,
- res: MedusaResponse
-) {
- const { result } = await createSalesChannelWorkflow(req.scope)
- .run()
-
- res.send(result)
-}
-```
-
-### Subscriber
-
-```ts title="src/subscribers/user-created.ts" highlights={[["11"], ["12"]]} collapsibleLines="1-6" expandButtonLabel="Show Imports"
-import {
- type SubscriberConfig,
- type SubscriberArgs,
-} from "@medusajs/framework"
-import { createSalesChannelWorkflow } from "../workflows/create-sales-channel"
-
-export default async function handleUserCreated({
- event: { data },
- container,
-}: SubscriberArgs<{ id: string }>) {
- const { result } = await createSalesChannelWorkflow(container)
- .run()
-
- console.log(result)
-}
-
-export const config: SubscriberConfig = {
- event: "user.created",
-}
-```
-
-### Scheduled Job
-
-```ts title="src/jobs/run-daily.ts" highlights={[["7"], ["8"]]}
-import { MedusaContainer } from "@medusajs/framework/types"
-import { createSalesChannelWorkflow } from "../workflows/create-sales-channel"
-
-export default async function myCustomJob(
- container: MedusaContainer
-) {
- const { result } = await createSalesChannelWorkflow(container)
- .run()
-
- console.log(result)
-}
-
-export const config = {
- name: "run-once-a-day",
- schedule: `0 0 * * *`,
-}
-```
-
-Learn more about workflows in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md).
-
-***
-
-
# Links between API Key Module and Other Modules
This document showcases the module links defined between the API Key Module and other commerce modules.
@@ -20301,6 +21032,91 @@ const { data: orders } = useQueryGraphStep({
```
+# Links between Currency Module and Other Modules
+
+This document showcases the module links defined between the Currency Module and other commerce modules.
+
+## Summary
+
+The Currency Module has the following links to other modules:
+
+Read-only links are used to query data across modules, but the relations aren't stored in a pivot table in the database.
+
+|First Data Model|Second Data Model|Type|Description|
+|---|---|---|---|
+| in ||Read-only||
+
+***
+
+## Store Module
+
+The Store Module has a `Currency` data model that stores the supported currencies of a store. However, these currencies don't hold all the details of a currency, such as its name or symbol.
+
+Instead, Medusa defines a read-only link between the [Store Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/store/index.html.md)'s `Currency` data model and the Currency Module's `Currency` data model. Because the link is read-only from the `Store`'s side, you can only retrieve the details of a store's supported currencies, and not the other way around.
+
+### Retrieve with Query
+
+To retrieve the details of a store's currencies with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `supported_currencies.currency.*` in `fields`:
+
+### query.graph
+
+```ts
+const { data: stores } = await query.graph({
+ entity: "store",
+ fields: [
+ "supported_currencies.currency.*",
+ ],
+})
+
+// stores.supported_currencies
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: stores } = useQueryGraphStep({
+ entity: "store",
+ fields: [
+ "supported_currencies.currency.*",
+ ],
+})
+
+// stores.supported_currencies
+```
+
+
+# API Key Concepts
+
+In this document, you’ll learn about the different types of API keys, their expiration and verification.
+
+## API Key Types
+
+There are two types of API keys:
+
+- `publishable`: A public key used in client applications, such as a storefront.
+- `secret`: A secret key used for authentication and verification purposes, such as an admin user’s authentication token or a password reset token.
+
+The API key’s type is stored in the `type` property of the [ApiKey data model](https://docs.medusajs.com/references/api-key/models/ApiKey/index.html.md).
+
+***
+
+## API Key Expiration
+
+An API key expires when it’s revoked using the [revoke method of the module’s main service](https://docs.medusajs.com/references/api-key/revoke/index.html.md).
+
+The associated token is no longer usable or verifiable.
+
+***
+
+## Token Verification
+
+To verify a token received as an input or in a request, use the [authenticate method of the module’s main service](https://docs.medusajs.com/references/api-key/authenticate/index.html.md) which validates the token against all non-expired tokens.
+
+
# Cart Concepts
In this document, you’ll get an overview of the main concepts of a cart.
@@ -20338,124 +21154,6 @@ If the fulfillment provider requires additional custom data to be passed along f
The `data` property is an object used to store custom data relevant later for fulfillment.
-# Promotions Adjustments in Carts
-
-In this document, you’ll learn how a promotion is applied to a cart’s line items and shipping methods using adjustment lines.
-
-## What are Adjustment Lines?
-
-An adjustment line indicates a change to an item or a shipping method’s amount. It’s used to apply promotions or discounts on a cart.
-
-The [LineItemAdjustment](https://docs.medusajs.com/references/cart/models/LineItemAdjustment/index.html.md) data model represents changes on a line item, and the [ShippingMethodAdjustment](https://docs.medusajs.com/references/cart/models/ShippingMethodAdjustment/index.html.md) data model represents changes on a shipping method.
-
-
-
-The `amount` property of the adjustment line indicates the amount to be discounted from the original amount. Also, the ID of the applied promotion is stored in the `promotion_id` property of the adjustment line.
-
-***
-
-## Discountable Option
-
-The [LineItem](https://docs.medusajs.com/references/cart/models/LineItem/index.html.md) data model has an `is_discountable` property that indicates whether promotions can be applied to the line item. It’s enabled by default.
-
-When disabled, a promotion can’t be applied to a line item. In the context of the Promotion Module, the promotion isn’t applied to the line item even if it matches its rules.
-
-***
-
-## Promotion Actions
-
-When using the Cart and Promotion modules together, such as in the Medusa application, use the [computeActions method of the Promotion Module’s main service](https://docs.medusajs.com/references/promotion/computeActions/index.html.md). It retrieves the actions of line items and shipping methods.
-
-Learn more about actions in the [Promotion Module’s documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/promotion/actions/index.html.md).
-
-For example:
-
-```ts collapsibleLines="1-8" expandButtonLabel="Show Imports"
-import {
- ComputeActionAdjustmentLine,
- ComputeActionItemLine,
- ComputeActionShippingLine,
- // ...
-} from "@medusajs/framework/types"
-
-// retrieve the cart
-const cart = await cartModuleService.retrieveCart("cart_123", {
- relations: [
- "items.adjustments",
- "shipping_methods.adjustments",
- ],
-})
-
-// retrieve line item adjustments
-const lineItemAdjustments: ComputeActionItemLine[] = []
-cart.items.forEach((item) => {
- const filteredAdjustments = item.adjustments?.filter(
- (adjustment) => adjustment.code !== undefined
- ) as unknown as ComputeActionAdjustmentLine[]
- if (filteredAdjustments.length) {
- lineItemAdjustments.push({
- ...item,
- adjustments: filteredAdjustments,
- })
- }
-})
-
-// retrieve shipping method adjustments
-const shippingMethodAdjustments: ComputeActionShippingLine[] =
- []
-cart.shipping_methods.forEach((shippingMethod) => {
- const filteredAdjustments =
- shippingMethod.adjustments?.filter(
- (adjustment) => adjustment.code !== undefined
- ) as unknown as ComputeActionAdjustmentLine[]
- if (filteredAdjustments.length) {
- shippingMethodAdjustments.push({
- ...shippingMethod,
- adjustments: filteredAdjustments,
- })
- }
-})
-
-// compute actions
-const actions = await promotionModuleService.computeActions(
- ["promo_123"],
- {
- items: lineItemAdjustments,
- shipping_methods: shippingMethodAdjustments,
- }
-)
-```
-
-The `computeActions` method accepts the existing adjustments of line items and shipping methods to compute the actions accurately.
-
-Then, use the returned `addItemAdjustment` and `addShippingMethodAdjustment` actions to set the cart’s line item and the shipping method’s adjustments.
-
-```ts collapsibleLines="1-8" expandButtonLabel="Show Imports"
-import {
- AddItemAdjustmentAction,
- AddShippingMethodAdjustment,
- // ...
-} from "@medusajs/framework/types"
-
-// ...
-
-await cartModuleService.setLineItemAdjustments(
- cart.id,
- actions.filter(
- (action) => action.action === "addItemAdjustment"
- ) as AddItemAdjustmentAction[]
-)
-
-await cartModuleService.setShippingMethodAdjustments(
- cart.id,
- actions.filter(
- (action) =>
- action.action === "addShippingMethodAdjustment"
- ) as AddShippingMethodAdjustment[]
-)
-```
-
-
# Links between Cart Module and Other Modules
This document showcases the module links defined between the Cart Module and other commerce modules.
@@ -20970,6 +21668,836 @@ await cartModuleService.setLineItemTaxLines(
```
+# Promotions Adjustments in Carts
+
+In this document, you’ll learn how a promotion is applied to a cart’s line items and shipping methods using adjustment lines.
+
+## What are Adjustment Lines?
+
+An adjustment line indicates a change to an item or a shipping method’s amount. It’s used to apply promotions or discounts on a cart.
+
+The [LineItemAdjustment](https://docs.medusajs.com/references/cart/models/LineItemAdjustment/index.html.md) data model represents changes on a line item, and the [ShippingMethodAdjustment](https://docs.medusajs.com/references/cart/models/ShippingMethodAdjustment/index.html.md) data model represents changes on a shipping method.
+
+
+
+The `amount` property of the adjustment line indicates the amount to be discounted from the original amount. Also, the ID of the applied promotion is stored in the `promotion_id` property of the adjustment line.
+
+***
+
+## Discountable Option
+
+The [LineItem](https://docs.medusajs.com/references/cart/models/LineItem/index.html.md) data model has an `is_discountable` property that indicates whether promotions can be applied to the line item. It’s enabled by default.
+
+When disabled, a promotion can’t be applied to a line item. In the context of the Promotion Module, the promotion isn’t applied to the line item even if it matches its rules.
+
+***
+
+## Promotion Actions
+
+When using the Cart and Promotion modules together, such as in the Medusa application, use the [computeActions method of the Promotion Module’s main service](https://docs.medusajs.com/references/promotion/computeActions/index.html.md). It retrieves the actions of line items and shipping methods.
+
+Learn more about actions in the [Promotion Module’s documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/promotion/actions/index.html.md).
+
+For example:
+
+```ts collapsibleLines="1-8" expandButtonLabel="Show Imports"
+import {
+ ComputeActionAdjustmentLine,
+ ComputeActionItemLine,
+ ComputeActionShippingLine,
+ // ...
+} from "@medusajs/framework/types"
+
+// retrieve the cart
+const cart = await cartModuleService.retrieveCart("cart_123", {
+ relations: [
+ "items.adjustments",
+ "shipping_methods.adjustments",
+ ],
+})
+
+// retrieve line item adjustments
+const lineItemAdjustments: ComputeActionItemLine[] = []
+cart.items.forEach((item) => {
+ const filteredAdjustments = item.adjustments?.filter(
+ (adjustment) => adjustment.code !== undefined
+ ) as unknown as ComputeActionAdjustmentLine[]
+ if (filteredAdjustments.length) {
+ lineItemAdjustments.push({
+ ...item,
+ adjustments: filteredAdjustments,
+ })
+ }
+})
+
+// retrieve shipping method adjustments
+const shippingMethodAdjustments: ComputeActionShippingLine[] =
+ []
+cart.shipping_methods.forEach((shippingMethod) => {
+ const filteredAdjustments =
+ shippingMethod.adjustments?.filter(
+ (adjustment) => adjustment.code !== undefined
+ ) as unknown as ComputeActionAdjustmentLine[]
+ if (filteredAdjustments.length) {
+ shippingMethodAdjustments.push({
+ ...shippingMethod,
+ adjustments: filteredAdjustments,
+ })
+ }
+})
+
+// compute actions
+const actions = await promotionModuleService.computeActions(
+ ["promo_123"],
+ {
+ items: lineItemAdjustments,
+ shipping_methods: shippingMethodAdjustments,
+ }
+)
+```
+
+The `computeActions` method accepts the existing adjustments of line items and shipping methods to compute the actions accurately.
+
+Then, use the returned `addItemAdjustment` and `addShippingMethodAdjustment` actions to set the cart’s line item and the shipping method’s adjustments.
+
+```ts collapsibleLines="1-8" expandButtonLabel="Show Imports"
+import {
+ AddItemAdjustmentAction,
+ AddShippingMethodAdjustment,
+ // ...
+} from "@medusajs/framework/types"
+
+// ...
+
+await cartModuleService.setLineItemAdjustments(
+ cart.id,
+ actions.filter(
+ (action) => action.action === "addItemAdjustment"
+ ) as AddItemAdjustmentAction[]
+)
+
+await cartModuleService.setShippingMethodAdjustments(
+ cart.id,
+ actions.filter(
+ (action) =>
+ action.action === "addShippingMethodAdjustment"
+ ) as AddShippingMethodAdjustment[]
+)
+```
+
+
+# Fulfillment Concepts
+
+In this document, you’ll learn about some basic fulfillment concepts.
+
+## Fulfillment Set
+
+A fulfillment set is a general form or way of fulfillment. For example, shipping is a form of fulfillment, and pick-up is another form of fulfillment. Each of these can be created as fulfillment sets.
+
+A fulfillment set is represented by the [FulfillmentSet data model](https://docs.medusajs.com/references/fulfillment/models/FulfillmentSet/index.html.md). All other configurations, options, and management features are related to a fulfillment set, in one way or another.
+
+```ts
+const fulfillmentSets = await fulfillmentModuleService.createFulfillmentSets(
+ [
+ {
+ name: "Shipping",
+ type: "shipping",
+ },
+ {
+ name: "Pick-up",
+ type: "pick-up",
+ },
+ ]
+)
+```
+
+***
+
+## Service Zone
+
+A service zone is a collection of geographical zones or areas. It’s used to restrict available shipping options to a defined set of locations.
+
+A service zone is represented by the [ServiceZone data model](https://docs.medusajs.com/references/fulfillment/models/ServiceZone/index.html.md). It’s associated with a fulfillment set, as each service zone is specific to a form of fulfillment. For example, if a customer chooses to pick up items, you can restrict the available shipping options based on their location.
+
+
+
+A service zone can have multiple geographical zones, each represented by the [GeoZone data model](https://docs.medusajs.com/references/fulfillment/models/GeoZone/index.html.md). It holds location-related details to narrow down supported areas, such as country, city, or province code.
+
+***
+
+## Shipping Profile
+
+A shipping profile defines a type of items that are shipped in a similar manner. For example, a `default` shipping profile is used for all item types, but the `digital` shipping profile is used for digital items that aren’t shipped and delivered conventionally.
+
+A shipping profile is represented by the [ShippingProfile data model](https://docs.medusajs.com/references/fulfillment/models/ShippingProfile/index.html.md). It only defines the profile’s details, but it’s associated with the shipping options available for the item type.
+
+
+# Fulfillment Module Provider
+
+In this document, you’ll learn what a fulfillment module provider is.
+
+Refer to this [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/locations-and-shipping/locations#manage-fulfillment-providers/index.html.md) to learn how to add a fulfillment provider to a location using the dashboard.
+
+## What’s a Fulfillment Module Provider?
+
+A fulfillment module provider handles fulfilling items, typically using a third-party integration.
+
+Fulfillment module providers registered in the Fulfillment Module's [options](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/fulfillment/module-options/index.html.md) are stored and represented by the [FulfillmentProvider data model](https://docs.medusajs.com/references/fulfillment/models/FulfillmentProvider/index.html.md).
+
+***
+
+## Configure Fulfillment Providers
+
+The Fulfillment Module accepts a `providers` option that allows you to register providers in your application.
+
+Learn more about the `providers` option in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/fulfillment/module-options/index.html.md).
+
+***
+
+## How to Create a Fulfillment Provider?
+
+Refer to [this guide](https://docs.medusajs.com/references/fulfillment/provider/index.html.md) to learn how to create a fulfillment module provider.
+
+
+# Item Fulfillment
+
+In this document, you’ll learn about the concepts of item fulfillment.
+
+## Fulfillment Data Model
+
+A fulfillment is the shipping and delivery of one or more items to the customer. It’s represented by the [Fulfillment data model](https://docs.medusajs.com/references/fulfillment/models/Fulfillment/index.html.md).
+
+***
+
+## Fulfillment Processing by a Fulfillment Provider
+
+A fulfillment is associated with a fulfillment provider that handles all its processing, such as creating a shipment for the fulfillment’s items.
+
+The fulfillment is also associated with a shipping option of that provider, which determines how the item is shipped.
+
+
+
+***
+
+## data Property
+
+The `Fulfillment` data model has a `data` property that holds any necessary data for the third-party fulfillment provider to process the fulfillment.
+
+For example, the `data` property can hold the ID of the fulfillment in the third-party provider. The associated fulfillment provider then uses it whenever it retrieves the fulfillment’s details.
+
+***
+
+## Fulfillment Items
+
+A fulfillment is used to fulfill one or more items. Each item is represented by the `FulfillmentItem` data model.
+
+The fulfillment item holds details relevant to fulfilling the item, such as barcode, SKU, and quantity to fulfill.
+
+
+
+***
+
+## Fulfillment Label
+
+Once a shipment is created for the fulfillment, you can store its tracking number, URL, or other related details as a label, represented by the `FulfillmentLabel` data model.
+
+***
+
+## Fulfillment Status
+
+The `Fulfillment` data model has three properties to keep track of the current status of the fulfillment:
+
+- `packed_at`: The date the fulfillment was packed. If set, then the fulfillment has been packed.
+- `shipped_at`: The date the fulfillment was shipped. If set, then the fulfillment has been shipped.
+- `delivered_at`: The date the fulfillment was delivered. If set, then the fulfillment has been delivered.
+
+
+# Fulfillment Module Options
+
+In this document, you'll learn about the options of the Fulfillment Module.
+
+## providers
+
+The `providers` option is an array of fulfillment module providers.
+
+When the Medusa application starts, these providers are registered and can be used to process fulfillments.
+
+For example:
+
+```ts title="medusa-config.ts"
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+module.exports = defineConfig({
+ // ...
+ modules: [
+ {
+ resolve: "@medusajs/medusa/fulfillment",
+ options: {
+ providers: [
+ {
+ resolve: `@medusajs/medusa/fulfillment-manual`,
+ id: "manual",
+ options: {
+ // provider options...
+ },
+ },
+ ],
+ },
+ },
+ ],
+})
+```
+
+The `providers` option is an array of objects that accept the following properties:
+
+- `resolve`: A string indicating either the package name of the module provider or the path to it relative to the `src` directory.
+- `id`: A string indicating the provider's unique name or ID.
+- `options`: An optional object of the module provider's options.
+
+
+# Links between Fulfillment Module and Other Modules
+
+This document showcases the module links defined between the Fulfillment Module and other commerce modules.
+
+## Summary
+
+The Fulfillment Module has the following links to other modules:
+
+|First Data Model|Second Data Model|Type|Description|
+|---|---|---|---|
+| in ||Stored||
+| in ||Stored||
+| in ||Stored||
+| in ||Stored||
+| in ||Stored||
+| in ||Stored||
+
+***
+
+## Order Module
+
+The [Order Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/order/index.html.md) provides order-management functionalities.
+
+Medusa defines a link between the `Fulfillment` and `Order` data models. A fulfillment is created for an orders' items.
+
+
+
+A fulfillment is also created for a return's items. So, Medusa defines a link between the `Fulfillment` and `Return` data models.
+
+
+
+### Retrieve with Query
+
+To retrieve the order of a fulfillment with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `order.*` in `fields`:
+
+To retrieve the return, pass `return.*` in `fields`.
+
+### query.graph
+
+```ts
+const { data: fulfillments } = await query.graph({
+ entity: "fulfillment",
+ fields: [
+ "order.*",
+ ],
+})
+
+// fulfillments.order
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: fulfillments } = useQueryGraphStep({
+ entity: "fulfillment",
+ fields: [
+ "order.*",
+ ],
+})
+
+// fulfillments.order
+```
+
+### Manage with Link
+
+To manage the order of a cart, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
+
+### link.create
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await link.create({
+ [Modules.ORDER]: {
+ order_id: "order_123",
+ },
+ [Modules.FULFILLMENT]: {
+ fulfillment_id: "ful_123",
+ },
+})
+```
+
+### createRemoteLinkStep
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+createRemoteLinkStep({
+ [Modules.ORDER]: {
+ order_id: "order_123",
+ },
+ [Modules.FULFILLMENT]: {
+ fulfillment_id: "ful_123",
+ },
+})
+```
+
+***
+
+## Pricing Module
+
+The Pricing Module provides features to store, manage, and retrieve the best prices in a specified context.
+
+Medusa defines a link between the `PriceSet` and `ShippingOption` data models. A shipping option's price is stored as a price set.
+
+
+
+### Retrieve with Query
+
+To retrieve the price set of a shipping option with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `price_set.*` in `fields`:
+
+### query.graph
+
+```ts
+const { data: shippingOptions } = await query.graph({
+ entity: "shipping_option",
+ fields: [
+ "price_set.*",
+ ],
+})
+
+// shippingOptions.price_set
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: shippingOptions } = useQueryGraphStep({
+ entity: "shipping_option",
+ fields: [
+ "price_set.*",
+ ],
+})
+
+// shippingOptions.price_set
+```
+
+### Manage with Link
+
+To manage the price set of a shipping option, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
+
+### link.create
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await link.create({
+ [Modules.FULFILLMENT]: {
+ shipping_option_id: "so_123",
+ },
+ [Modules.PRICING]: {
+ price_set_id: "pset_123",
+ },
+})
+```
+
+### createRemoteLinkStep
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+createRemoteLinkStep({
+ [Modules.FULFILLMENT]: {
+ shipping_option_id: "so_123",
+ },
+ [Modules.PRICING]: {
+ price_set_id: "pset_123",
+ },
+})
+```
+
+***
+
+## Product Module
+
+Medusa defines a link between the `ShippingProfile` data model and the `Product` data model of the Product Module. Each product must belong to a shipping profile.
+
+This link is introduced in [Medusa v2.5.0](https://github.com/medusajs/medusa/releases/tag/v2.5.0).
+
+### Retrieve with Query
+
+To retrieve the products of a shipping profile with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `products.*` in `fields`:
+
+### query.graph
+
+```ts
+const { data: shippingProfiles } = await query.graph({
+ entity: "shipping_profile",
+ fields: [
+ "products.*",
+ ],
+})
+
+// shippingProfiles.products
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: shippingProfiles } = useQueryGraphStep({
+ entity: "shipping_profile",
+ fields: [
+ "products.*",
+ ],
+})
+
+// shippingProfiles.products
+```
+
+### Manage with Link
+
+To manage the shipping profile of a product, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
+
+### link.create
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await link.create({
+ [Modules.PRODUCT]: {
+ product_id: "prod_123",
+ },
+ [Modules.FULFILLMENT]: {
+ shipping_profile_id: "sp_123",
+ },
+})
+```
+
+### createRemoteLinkStep
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+createRemoteLinkStep({
+ [Modules.PRODUCT]: {
+ product_id: "prod_123",
+ },
+ [Modules.FULFILLMENT]: {
+ shipping_profile_id: "sp_123",
+ },
+})
+```
+
+***
+
+## Stock Location Module
+
+The Stock Location Module provides features to manage stock locations in a store.
+
+Medusa defines a link between the `FulfillmentSet` and `StockLocation` data models. A fulfillment set can be conditioned to a specific stock location.
+
+
+
+Medusa also defines a link between the `FulfillmentProvider` and `StockLocation` data models to indicate the providers that can be used in a location.
+
+
+
+### Retrieve with Query
+
+To retrieve the stock location of a fulfillment set with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `location.*` in `fields`:
+
+To retrieve the stock location of a fulfillment provider, pass `locations.*` in `fields`.
+
+### query.graph
+
+```ts
+const { data: fulfillmentSets } = await query.graph({
+ entity: "fulfillment_set",
+ fields: [
+ "location.*",
+ ],
+})
+
+// fulfillmentSets.location
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: fulfillmentSets } = useQueryGraphStep({
+ entity: "fulfillment_set",
+ fields: [
+ "location.*",
+ ],
+})
+
+// fulfillmentSets.location
+```
+
+### Manage with Link
+
+To manage the stock location of a fulfillment set, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
+
+### link.create
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await link.create({
+ [Modules.STOCK_LOCATION]: {
+ stock_location_id: "sloc_123",
+ },
+ [Modules.FULFILLMENT]: {
+ fulfillment_set_id: "fset_123",
+ },
+})
+```
+
+### createRemoteLinkStep
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+createRemoteLinkStep({
+ [Modules.STOCK_LOCATION]: {
+ stock_location_id: "sloc_123",
+ },
+ [Modules.FULFILLMENT]: {
+ fulfillment_set_id: "fset_123",
+ },
+})
+```
+
+
+# Shipping Option
+
+In this document, you’ll learn about shipping options and their rules.
+
+## What’s a Shipping Option?
+
+A shipping option is a way of shipping an item. Each fulfillment provider provides a set of shipping options. For example, a provider may provide a shipping option for express shipping and another for standard shipping.
+
+When the customer places their order, they choose a shipping option to be used to fulfill their items.
+
+A shipping option is represented by the [ShippingOption data model](https://docs.medusajs.com/references/fulfillment/models/ShippingOption/index.html.md).
+
+***
+
+## Service Zone Restrictions
+
+A shipping option is restricted by a service zone, limiting the locations a shipping option be used in.
+
+For example, a fulfillment provider may have a shipping option that can be used in the United States, and another in Canada.
+
+
+
+Service zones can be more restrictive, such as restricting to certain cities or province codes.
+
+
+
+***
+
+## Shipping Option Rules
+
+You can restrict shipping options by custom rules, such as the item’s weight or the customer’s group.
+
+These rules are represented by the [ShippingOptionRule data model](https://docs.medusajs.com/references/fulfillment/models/ShippingOptionRule/index.html.md). Its properties define the custom rule:
+
+- `attribute`: The name of a property or table that the rule applies to. For example, `customer_group`.
+- `operator`: The operator used in the condition. For example:
+ - To allow multiple values, use the operator `in`, which validates that the provided values are in the rule’s values.
+ - To create a negation condition that considers `value` against the rule, use `nin`, which validates that the provided values aren’t in the rule’s values.
+ - Check out more operators in [this reference](https://docs.medusajs.com/references/fulfillment/types/fulfillment.RuleOperatorType/index.html.md).
+- `value`: One or more values.
+
+
+
+A shipping option can have multiple rules. For example, you can add rules to a shipping option so that it's available if the customer belongs to the VIP group and the total weight is less than 2000g.
+
+
+
+***
+
+## Shipping Profile and Types
+
+A shipping option belongs to a type. For example, a shipping option’s type may be `express`, while another `standard`. The type is represented by the [ShippingOptionType data model](https://docs.medusajs.com/references/fulfillment/models/ShippingOptionType/index.html.md).
+
+A shipping option also belongs to a shipping profile, as each shipping profile defines the type of items to be shipped in a similar manner.
+
+***
+
+## data Property
+
+When fulfilling an item, you might use a third-party fulfillment provider that requires additional custom data to be passed along from the checkout or order-creation process.
+
+The `ShippingOption` data model has a `data` property. It's an object that stores custom data relevant later when creating and processing a fulfillment.
+
+
+# Auth Identity and Actor Types
+
+In this document, you’ll learn about concepts related to identity and actors in the Auth Module.
+
+## What is an Auth Identity?
+
+The [AuthIdentity data model](https://docs.medusajs.com/references/auth/models/AuthIdentity/index.html.md) represents a user registered by an [authentication provider](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-providers/index.html.md). When a user is registered using an authentication provider, the provider creates a record of `AuthIdentity`.
+
+Then, when the user logs-in in the future with the same authentication provider, the associated auth identity is used to validate their credentials.
+
+***
+
+## Actor Types
+
+An actor type is a type of user that can be authenticated. The Auth Module doesn't store or manage any user-like models, such as for customers or users. Instead, the user types are created and managed by other modules. For example, a customer is managed by the [Customer Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/customer/index.html.md).
+
+Then, when an auth identity is created for the actor type, the ID of the user is stored in the `app_metadata` property of the auth identity.
+
+For example, an auth identity of a customer has the following `app_metadata` property:
+
+```json
+{
+ "app_metadata": {
+ "customer_id": "cus_123"
+ }
+}
+```
+
+The ID of the user is stored in the key `{actor_type}_id` of the `app_metadata` property.
+
+***
+
+## Protect Routes by Actor Type
+
+When you protect routes with the `authenticate` middleware, you specify in its first parameter the actor type that must be authenticated to access the specified API routes.
+
+For example:
+
+```ts title="src/api/middlewares.ts" highlights={highlights}
+import {
+ defineMiddlewares,
+ authenticate,
+} from "@medusajs/framework/http"
+
+export default defineMiddlewares({
+ routes: [
+ {
+ matcher: "/custom/admin*",
+ middlewares: [
+ authenticate("user", ["session", "bearer", "api-key"]),
+ ],
+ },
+ ],
+})
+```
+
+By specifying `user` as the first parameter of `authenticate`, only authenticated users of actor type `user` (admin users) can access API routes starting with `/custom/admin`.
+
+***
+
+## Custom Actor Types
+
+You can define custom actor types that allows a custom user, managed by your custom module, to authenticate into Medusa.
+
+For example, if you have a custom module with a `Manager` data model, you can authenticate managers with the `manager` actor type.
+
+Learn how to create a custom actor type in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/create-actor-type/index.html.md).
+
+
+# Auth Providers
+
+In this document, you’ll learn how the Auth Module handles authentication using providers.
+
+## What's an Auth Module Provider?
+
+An auth module provider handles authenticating customers and users, either using custom logic or by integrating a third-party service.
+
+For example, the EmailPass Auth Module Provider authenticates a user using their email and password, whereas the Google Auth Module Provider authenticates users using their Google account.
+
+### Auth Providers List
+
+- [Emailpass](https://docs.medusajs.com/commerce-modules/auth/auth-providers/emailpass/index.html.md)
+- [Google](https://docs.medusajs.com/commerce-modules/auth/auth-providers/google/index.html.md)
+- [GitHub](https://docs.medusajs.com/commerce-modules/auth/auth-providers/github/index.html.md)
+
+***
+
+## Configure Allowed Auth Providers of Actor Types
+
+By default, users of all actor types can authenticate with all installed auth module providers.
+
+To restrict the auth providers used for actor types, use the [authMethodsPerActor option](https://docs.medusajs.com/docs/learn/configurations/medusa-config#httpauthMethodsPerActor/index.html.md) in Medusa's configurations:
+
+```ts title="medusa-config.ts"
+module.exports = defineConfig({
+ projectConfig: {
+ http: {
+ authMethodsPerActor: {
+ user: ["google"],
+ customer: ["emailpass"],
+ },
+ // ...
+ },
+ // ...
+ },
+})
+```
+
+When you specify the `authMethodsPerActor` configuration, it overrides the default. So, if you don't specify any providers for an actor type, users of that actor type can't authenticate with any provider.
+
+***
+
+## How to Create an Auth Module Provider
+
+Refer to [this guide](https://docs.medusajs.com/references/auth/provider/index.html.md) to learn how to create an auth module provider.
+
+
# Authentication Flows with the Auth Main Service
In this document, you'll learn how to use the Auth Module's main service's methods to implement authentication flows and reset a user's password.
@@ -21172,121 +22700,348 @@ In the example above, you use the `emailpass` provider, so you have to pass an o
If the returned `success` property is `true`, the password has reset successfully.
-# Auth Providers
+# How to Use Authentication Routes
-In this document, you’ll learn how the Auth Module handles authentication using providers.
+In this document, you'll learn about the authentication routes and how to use them to create and log-in users, and reset their password.
-## What's an Auth Module Provider?
+These routes are added by Medusa's HTTP layer, not the Auth Module.
-An auth module provider handles authenticating customers and users, either using custom logic or by integrating a third-party service.
+## Types of Authentication Flows
-For example, the EmailPass Auth Module Provider authenticates a user using their email and password, whereas the Google Auth Module Provider authenticates users using their Google account.
+### 1. Basic Authentication Flow
-### Auth Providers List
+This authentication flow doesn't require validation with third-party services.
-- [Emailpass](https://docs.medusajs.com/commerce-modules/auth/auth-providers/emailpass/index.html.md)
-- [Google](https://docs.medusajs.com/commerce-modules/auth/auth-providers/google/index.html.md)
-- [GitHub](https://docs.medusajs.com/commerce-modules/auth/auth-providers/github/index.html.md)
+[How to register customer in storefront using basic authentication flow](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/register/index.html.md).
+
+The steps are:
+
+
+
+1. Register the user with the [Register Route](#register-route).
+2. Use the authentication token to create the user with their respective API route.
+ - For example, for customers you would use the [Create Customer API route](https://docs.medusajs.com/api/store#customers_postcustomers).
+ - For admin users, you accept an invite using the [Accept Invite API route](https://docs.medusajs.com/api/admin#invites_postinvitesaccept)
+3. Authenticate the user with the [Auth Route](#login-route).
+
+After registration, you only use the [Auth Route](#login-route) for subsequent authentication.
+
+To handle errors related to existing identities, refer to [this section](#handling-existing-identities).
+
+### 2. Third-Party Service Authenticate Flow
+
+This authentication flow authenticates the user with a third-party service, such as Google.
+
+[How to authenticate customer with a third-party provider in the storefront.](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/third-party-login/index.html.md).
+
+It requires the following steps:
+
+
+
+1. Authenticate the user with the [Auth Route](#login-route).
+2. The auth route returns a URL to authenticate with third-party service, such as login with Google. The frontend (such as a storefront), when it receives a `location` property in the response, must redirect to the returned location.
+3. Once the authentication with the third-party service finishes, it redirects back to the frontend with a `code` query parameter. So, make sure your third-party service is configured to redirect to your frontend page after successful authentication.
+4. The frontend sends a request to the [Validate Callback Route](#validate-callback-route) passing it the query parameters received from the third-party service, such as the `code` and `state` query parameters.
+5. If the callback validation is successful, the frontend receives the authentication token.
+6. Decode the received token in the frontend using tools like [react-jwt](https://www.npmjs.com/package/react-jwt).
+ - If the decoded data has an `actor_id` property, then the user is already registered. So, use this token for subsequent authenticated requests.
+ - If not, follow the rest of the steps.
+7. The frontend uses the authentication token to create the user with their respective API route.
+ - For example, for customers you would use the [Create Customer API route](https://docs.medusajs.com/api/store#customers_postcustomers).
+ - For admin users, you accept an invite using the [Accept Invite API route](https://docs.medusajs.com/api/admin#invites_postinvitesaccept)
+8. The frontend sends a request to the [Refresh Token Route](#refresh-token-route) to retrieve a new token with the user information populated.
***
-## Configure Allowed Auth Providers of Actor Types
+## Register Route
-By default, users of all actor types can authenticate with all installed auth module providers.
+The Medusa application defines an API route at `/auth/{actor_type}/{provider}/register` that creates an auth identity for an actor type, such as a `customer`. It returns a JWT token that you pass to an API route that creates the user.
-To restrict the auth providers used for actor types, use the [authMethodsPerActor option](https://docs.medusajs.com/docs/learn/configurations/medusa-config#httpauthMethodsPerActor/index.html.md) in Medusa's configurations:
-
-```ts title="medusa-config.ts"
-module.exports = defineConfig({
- projectConfig: {
- http: {
- authMethodsPerActor: {
- user: ["google"],
- customer: ["emailpass"],
- },
- // ...
- },
- // ...
- },
-})
+```bash
+curl -X POST http://localhost:9000/auth/{actor_type}/{providers}/register
+-H 'Content-Type: application/json' \
+--data-raw '{
+ "email": "Whitney_Schultz@gmail.com"
+ // ...
+}'
```
-When you specify the `authMethodsPerActor` configuration, it overrides the default. So, if you don't specify any providers for an actor type, users of that actor type can't authenticate with any provider.
+This API route is useful for providers like `emailpass` that uses custom logic to authenticate a user. For authentication providers that authenticate with third-party services, such as Google, use the [Auth Route](#login-route) instead.
-***
+For example, if you're registering a customer, you:
-## How to Create an Auth Module Provider
+1. Send a request to `/auth/customer/emailpass/register` to retrieve the registration JWT token.
+2. Send a request to the [Create Customer API route](https://docs.medusajs.com/api/store#customers_postcustomers) to create the customer, passing the [JWT token in the header](https://docs.medusajs.com/api/store#authentication).
-Refer to [this guide](https://docs.medusajs.com/references/auth/provider/index.html.md) to learn how to create an auth module provider.
+### Path Parameters
+Its path parameters are:
-# Auth Identity and Actor Types
+- `{actor_type}`: the actor type of the user you're authenticating. For example, `customer`.
+- `{provider}`: the auth provider to handle the authentication. For example, `emailpass`.
-In this document, you’ll learn about concepts related to identity and actors in the Auth Module.
+### Request Body Parameters
-## What is an Auth Identity?
+This route accepts in the request body the data that the specified authentication provider requires to handle authentication.
-The [AuthIdentity data model](https://docs.medusajs.com/references/auth/models/AuthIdentity/index.html.md) represents a user registered by an [authentication provider](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-providers/index.html.md). When a user is registered using an authentication provider, the provider creates a record of `AuthIdentity`.
+For example, the EmailPass provider requires an `email` and `password` fields in the request body.
-Then, when the user logs-in in the future with the same authentication provider, the associated auth identity is used to validate their credentials.
+### Response Fields
-***
-
-## Actor Types
-
-An actor type is a type of user that can be authenticated. The Auth Module doesn't store or manage any user-like models, such as for customers or users. Instead, the user types are created and managed by other modules. For example, a customer is managed by the [Customer Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/customer/index.html.md).
-
-Then, when an auth identity is created for the actor type, the ID of the user is stored in the `app_metadata` property of the auth identity.
-
-For example, an auth identity of a customer has the following `app_metadata` property:
+If the authentication is successful, you'll receive a `token` field in the response body object:
```json
{
- "app_metadata": {
- "customer_id": "cus_123"
- }
+ "token": "..."
}
```
-The ID of the user is stored in the key `{actor_type}_id` of the `app_metadata` property.
+Use that token in the header of subsequent requests to send authenticated requests.
-***
+### Handling Existing Identities
-## Protect Routes by Actor Type
+An auth identity with the same email may already exist in Medusa. This can happen if:
-When you protect routes with the `authenticate` middleware, you specify in its first parameter the actor type that must be authenticated to access the specified API routes.
+- Another actor type is using that email. For example, an admin user is trying to register as a customer.
+- The same email belongs to a record of the same actor type. For example, another customer has the same email.
-For example:
+In these scenarios, the Register Route will return an error instead of a token:
-```ts title="src/api/middlewares.ts" highlights={highlights}
-import {
- defineMiddlewares,
- authenticate,
-} from "@medusajs/framework/http"
-
-export default defineMiddlewares({
- routes: [
- {
- matcher: "/custom/admin*",
- middlewares: [
- authenticate("user", ["session", "bearer", "api-key"]),
- ],
- },
- ],
-})
+```json
+{
+ "type": "unauthorized",
+ "message": "Identity with email already exists"
+}
```
-By specifying `user` as the first parameter of `authenticate`, only authenticated users of actor type `user` (admin users) can access API routes starting with `/custom/admin`.
+To handle these scenarios, you can use the [Login Route](#login-route) to validate that the email and password match the existing identity. If so, you can allow the admin user, for example, to register as a customer.
+
+Otherwise, if the email and password don't match the existing identity, such as when the email belongs to another customer, the [Login Route](#login-route) returns an error:
+
+```json
+{
+ "type": "unauthorized",
+ "message": "Invalid email or password"
+}
+```
+
+You can show that error message to the customer.
***
-## Custom Actor Types
+## Login Route
-You can define custom actor types that allows a custom user, managed by your custom module, to authenticate into Medusa.
+The Medusa application defines an API route at `/auth/{actor_type}/{provider}` that authenticates a user of an actor type. It returns a JWT token that can be passed in [the header of subsequent requests](https://docs.medusajs.com/api/store#authentication) to send authenticated requests.
-For example, if you have a custom module with a `Manager` data model, you can authenticate managers with the `manager` actor type.
+```bash
+curl -X POST http://localhost:9000/auth/{actor_type}/{providers}
+-H 'Content-Type: application/json' \
+--data-raw '{
+ "email": "Whitney_Schultz@gmail.com"
+ // ...
+}'
+```
-Learn how to create a custom actor type in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/create-actor-type/index.html.md).
+For example, if you're authenticating a customer, you send a request to `/auth/customer/emailpass`.
+
+### Path Parameters
+
+Its path parameters are:
+
+- `{actor_type}`: the actor type of the user you're authenticating. For example, `customer`.
+- `{provider}`: the auth provider to handle the authentication. For example, `emailpass`.
+
+### Request Body Parameters
+
+This route accepts in the request body the data that the specified authentication provider requires to handle authentication.
+
+For example, the EmailPass provider requires an `email` and `password` fields in the request body.
+
+#### Overriding Callback URL
+
+For the [GitHub](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-providers/github/index.html.md) and [Google](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-providers/google/index.html.md) providers, you can pass a `callback_url` body parameter that overrides the `callbackUrl` set in the provider's configurations.
+
+This is useful if you want to redirect the user to a different URL after authentication based on their actor type. For example, you can set different `callback_url` for admin users and customers.
+
+### Response Fields
+
+If the authentication is successful, you'll receive a `token` field in the response body object:
+
+```json
+{
+ "token": "..."
+}
+```
+
+Use that token in the header of subsequent requests to send authenticated requests.
+
+If the authentication requires more action with a third-party service, you'll receive a `location` property:
+
+```json
+{
+ "location": "https://..."
+}
+```
+
+Redirect to that URL in the frontend to continue the authentication process with the third-party service.
+
+[How to login Customers using the authentication route](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/login/index.html.md).
+
+***
+
+## Validate Callback Route
+
+The Medusa application defines an API route at `/auth/{actor_type}/{provider}/callback` that's useful for validating the authentication callback or redirect from third-party services like Google.
+
+```bash
+curl -X POST http://localhost:9000/auth/{actor_type}/{providers}/callback?code=123&state=456
+```
+
+Refer to the [third-party authentication flow](#2-third-party-service-authenticate-flow) section to see how this route fits into the authentication flow.
+
+### Path Parameters
+
+Its path parameters are:
+
+- `{actor_type}`: the actor type of the user you're authenticating. For example, `customer`.
+- `{provider}`: the auth provider to handle the authentication. For example, `google`.
+
+### Query Parameters
+
+This route accepts all the query parameters that the third-party service sends to the frontend after the user completes the authentication process, such as the `code` and `state` query parameters.
+
+### Response Fields
+
+If the authentication is successful, you'll receive a `token` field in the response body object:
+
+```json
+{
+ "token": "..."
+}
+```
+
+In your frontend, decode the token using tools like [react-jwt](https://www.npmjs.com/package/react-jwt):
+
+- If the decoded data has an `actor_id` property, the user is already registered. So, use this token for subsequent authenticated requests.
+- If not, use the token in the header of a request that creates the user, such as the [Create Customer API route](https://docs.medusajs.com/api/store#customers_postcustomers).
+
+***
+
+## Refresh Token Route
+
+The Medusa application defines an API route at `/auth/token/refresh` that's useful after authenticating a user with a third-party service to populate the user's token with their new information.
+
+It requires the user's JWT token that they received from the authentication or callback routes.
+
+```bash
+curl -X POST http://localhost:9000/auth/token/refresh \
+-H 'Authorization: Bearer {token}'
+```
+
+### Response Fields
+
+If the token was refreshed successfully, you'll receive a `token` field in the response body object:
+
+```json
+{
+ "token": "..."
+}
+```
+
+Use that token in the header of subsequent requests to send authenticated requests.
+
+***
+
+## Reset Password Routes
+
+To reset a user's password:
+
+1. Generate a token using the [Generate Reset Password Token API route](#generate-reset-password-token-route).
+ - The API route emits the `auth.password_reset` event, passing the token in the payload.
+ - You can create a subscriber, as seen in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/reset-password/index.html.md), that listens to the event and send a notification to the user.
+2. Pass the token to the [Reset Password API route](#reset-password-route) to reset the password.
+ - The URL in the user's notification should direct them to a frontend URL, which sends a request to this route.
+
+[Storefront Development: How to Reset a Customer's Password.](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/reset-password/index.html.md)
+
+### Generate Reset Password Token Route
+
+The Medusa application defines an API route at `/auth/{actor_type}/{auth_provider}/reset-password` that emits the `auth.password_reset` event, passing the token in the payload.
+
+```bash
+curl -X POST http://localhost:9000/auth/{actor_type}/{providers}/reset-password
+-H 'Content-Type: application/json' \
+--data-raw '{
+ "identifier": "Whitney_Schultz@gmail.com"
+}'
+```
+
+This API route is useful for providers like `emailpass` that store a user's password and use it for authentication.
+
+#### Path Parameters
+
+Its path parameters are:
+
+- `{actor_type}`: the actor type of the user you're authenticating. For example, `customer`.
+- `{provider}`: the auth provider to handle the authentication. For example, `emailpass`.
+
+#### Request Body Parameters
+
+This route accepts in the request body an object having the following property:
+
+- `identifier`: The user's identifier in the specified auth provider. For example, for the `emailpass` auth provider, you pass the user's email.
+
+#### Response Fields
+
+If the authentication is successful, the request returns a `201` response code.
+
+### Reset Password Route
+
+The Medusa application defines an API route at `/auth/{actor_type}/{auth_provider}/update` that accepts a token and, if valid, updates the user's password.
+
+```bash
+curl -X POST http://localhost:9000/auth/{actor_type}/{providers}/update
+-H 'Content-Type: application/json' \
+-H 'Authorization: Bearer {token}' \
+--data-raw '{
+ "email": "Whitney_Schultz@gmail.com",
+ "password": "supersecret"
+}'
+```
+
+This API route is useful for providers like `emailpass` that store a user's password and use it for logging them in.
+
+#### Path Parameters
+
+Its path parameters are:
+
+- `{actor_type}`: the actor type of the user you're authenticating. For example, `customer`.
+- `{provider}`: the auth provider to handle the authentication. For example, `emailpass`.
+
+#### Pass Token in Authorization Header
+
+Before [Medusa v2.6](https://github.com/medusajs/medusa/releases/tag/v2.6), you passed the token as a query parameter. Now, you must pass it in the `Authorization` header.
+
+In the request's authorization header, you must pass the token generated using the [Generate Reset Password Token route](#generate-reset-password-token-route). You pass it as a bearer token.
+
+### Request Body Parameters
+
+This route accepts in the request body an object that has the data necessary for the provider to update the user's password.
+
+For the `emailpass` provider, you must pass the following properties:
+
+- `email`: The user's email.
+- `password`: The new password.
+
+### Response Fields
+
+If the authentication is successful, the request returns an object with a `success` property set to `true`:
+
+```json
+{
+ "success": "true"
+}
+```
# How to Create an Actor Type
@@ -21682,350 +23437,6 @@ In the workflow, you:
You can use this workflow when deleting a manager, such as in an API route.
-# How to Use Authentication Routes
-
-In this document, you'll learn about the authentication routes and how to use them to create and log-in users, and reset their password.
-
-These routes are added by Medusa's HTTP layer, not the Auth Module.
-
-## Types of Authentication Flows
-
-### 1. Basic Authentication Flow
-
-This authentication flow doesn't require validation with third-party services.
-
-[How to register customer in storefront using basic authentication flow](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/register/index.html.md).
-
-The steps are:
-
-
-
-1. Register the user with the [Register Route](#register-route).
-2. Use the authentication token to create the user with their respective API route.
- - For example, for customers you would use the [Create Customer API route](https://docs.medusajs.com/api/store#customers_postcustomers).
- - For admin users, you accept an invite using the [Accept Invite API route](https://docs.medusajs.com/api/admin#invites_postinvitesaccept)
-3. Authenticate the user with the [Auth Route](#login-route).
-
-After registration, you only use the [Auth Route](#login-route) for subsequent authentication.
-
-To handle errors related to existing identities, refer to [this section](#handling-existing-identities).
-
-### 2. Third-Party Service Authenticate Flow
-
-This authentication flow authenticates the user with a third-party service, such as Google.
-
-[How to authenticate customer with a third-party provider in the storefront.](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/third-party-login/index.html.md).
-
-It requires the following steps:
-
-
-
-1. Authenticate the user with the [Auth Route](#login-route).
-2. The auth route returns a URL to authenticate with third-party service, such as login with Google. The frontend (such as a storefront), when it receives a `location` property in the response, must redirect to the returned location.
-3. Once the authentication with the third-party service finishes, it redirects back to the frontend with a `code` query parameter. So, make sure your third-party service is configured to redirect to your frontend page after successful authentication.
-4. The frontend sends a request to the [Validate Callback Route](#validate-callback-route) passing it the query parameters received from the third-party service, such as the `code` and `state` query parameters.
-5. If the callback validation is successful, the frontend receives the authentication token.
-6. Decode the received token in the frontend using tools like [react-jwt](https://www.npmjs.com/package/react-jwt).
- - If the decoded data has an `actor_id` property, then the user is already registered. So, use this token for subsequent authenticated requests.
- - If not, follow the rest of the steps.
-7. The frontend uses the authentication token to create the user with their respective API route.
- - For example, for customers you would use the [Create Customer API route](https://docs.medusajs.com/api/store#customers_postcustomers).
- - For admin users, you accept an invite using the [Accept Invite API route](https://docs.medusajs.com/api/admin#invites_postinvitesaccept)
-8. The frontend sends a request to the [Refresh Token Route](#refresh-token-route) to retrieve a new token with the user information populated.
-
-***
-
-## Register Route
-
-The Medusa application defines an API route at `/auth/{actor_type}/{provider}/register` that creates an auth identity for an actor type, such as a `customer`. It returns a JWT token that you pass to an API route that creates the user.
-
-```bash
-curl -X POST http://localhost:9000/auth/{actor_type}/{providers}/register
--H 'Content-Type: application/json' \
---data-raw '{
- "email": "Whitney_Schultz@gmail.com"
- // ...
-}'
-```
-
-This API route is useful for providers like `emailpass` that uses custom logic to authenticate a user. For authentication providers that authenticate with third-party services, such as Google, use the [Auth Route](#login-route) instead.
-
-For example, if you're registering a customer, you:
-
-1. Send a request to `/auth/customer/emailpass/register` to retrieve the registration JWT token.
-2. Send a request to the [Create Customer API route](https://docs.medusajs.com/api/store#customers_postcustomers) to create the customer, passing the [JWT token in the header](https://docs.medusajs.com/api/store#authentication).
-
-### Path Parameters
-
-Its path parameters are:
-
-- `{actor_type}`: the actor type of the user you're authenticating. For example, `customer`.
-- `{provider}`: the auth provider to handle the authentication. For example, `emailpass`.
-
-### Request Body Parameters
-
-This route accepts in the request body the data that the specified authentication provider requires to handle authentication.
-
-For example, the EmailPass provider requires an `email` and `password` fields in the request body.
-
-### Response Fields
-
-If the authentication is successful, you'll receive a `token` field in the response body object:
-
-```json
-{
- "token": "..."
-}
-```
-
-Use that token in the header of subsequent requests to send authenticated requests.
-
-### Handling Existing Identities
-
-An auth identity with the same email may already exist in Medusa. This can happen if:
-
-- Another actor type is using that email. For example, an admin user is trying to register as a customer.
-- The same email belongs to a record of the same actor type. For example, another customer has the same email.
-
-In these scenarios, the Register Route will return an error instead of a token:
-
-```json
-{
- "type": "unauthorized",
- "message": "Identity with email already exists"
-}
-```
-
-To handle these scenarios, you can use the [Login Route](#login-route) to validate that the email and password match the existing identity. If so, you can allow the admin user, for example, to register as a customer.
-
-Otherwise, if the email and password don't match the existing identity, such as when the email belongs to another customer, the [Login Route](#login-route) returns an error:
-
-```json
-{
- "type": "unauthorized",
- "message": "Invalid email or password"
-}
-```
-
-You can show that error message to the customer.
-
-***
-
-## Login Route
-
-The Medusa application defines an API route at `/auth/{actor_type}/{provider}` that authenticates a user of an actor type. It returns a JWT token that can be passed in [the header of subsequent requests](https://docs.medusajs.com/api/store#authentication) to send authenticated requests.
-
-```bash
-curl -X POST http://localhost:9000/auth/{actor_type}/{providers}
--H 'Content-Type: application/json' \
---data-raw '{
- "email": "Whitney_Schultz@gmail.com"
- // ...
-}'
-```
-
-For example, if you're authenticating a customer, you send a request to `/auth/customer/emailpass`.
-
-### Path Parameters
-
-Its path parameters are:
-
-- `{actor_type}`: the actor type of the user you're authenticating. For example, `customer`.
-- `{provider}`: the auth provider to handle the authentication. For example, `emailpass`.
-
-### Request Body Parameters
-
-This route accepts in the request body the data that the specified authentication provider requires to handle authentication.
-
-For example, the EmailPass provider requires an `email` and `password` fields in the request body.
-
-#### Overriding Callback URL
-
-For the [GitHub](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-providers/github/index.html.md) and [Google](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-providers/google/index.html.md) providers, you can pass a `callback_url` body parameter that overrides the `callbackUrl` set in the provider's configurations.
-
-This is useful if you want to redirect the user to a different URL after authentication based on their actor type. For example, you can set different `callback_url` for admin users and customers.
-
-### Response Fields
-
-If the authentication is successful, you'll receive a `token` field in the response body object:
-
-```json
-{
- "token": "..."
-}
-```
-
-Use that token in the header of subsequent requests to send authenticated requests.
-
-If the authentication requires more action with a third-party service, you'll receive a `location` property:
-
-```json
-{
- "location": "https://..."
-}
-```
-
-Redirect to that URL in the frontend to continue the authentication process with the third-party service.
-
-[How to login Customers using the authentication route](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/login/index.html.md).
-
-***
-
-## Validate Callback Route
-
-The Medusa application defines an API route at `/auth/{actor_type}/{provider}/callback` that's useful for validating the authentication callback or redirect from third-party services like Google.
-
-```bash
-curl -X POST http://localhost:9000/auth/{actor_type}/{providers}/callback?code=123&state=456
-```
-
-Refer to the [third-party authentication flow](#2-third-party-service-authenticate-flow) section to see how this route fits into the authentication flow.
-
-### Path Parameters
-
-Its path parameters are:
-
-- `{actor_type}`: the actor type of the user you're authenticating. For example, `customer`.
-- `{provider}`: the auth provider to handle the authentication. For example, `google`.
-
-### Query Parameters
-
-This route accepts all the query parameters that the third-party service sends to the frontend after the user completes the authentication process, such as the `code` and `state` query parameters.
-
-### Response Fields
-
-If the authentication is successful, you'll receive a `token` field in the response body object:
-
-```json
-{
- "token": "..."
-}
-```
-
-In your frontend, decode the token using tools like [react-jwt](https://www.npmjs.com/package/react-jwt):
-
-- If the decoded data has an `actor_id` property, the user is already registered. So, use this token for subsequent authenticated requests.
-- If not, use the token in the header of a request that creates the user, such as the [Create Customer API route](https://docs.medusajs.com/api/store#customers_postcustomers).
-
-***
-
-## Refresh Token Route
-
-The Medusa application defines an API route at `/auth/token/refresh` that's useful after authenticating a user with a third-party service to populate the user's token with their new information.
-
-It requires the user's JWT token that they received from the authentication or callback routes.
-
-```bash
-curl -X POST http://localhost:9000/auth/token/refresh \
--H 'Authorization: Bearer {token}'
-```
-
-### Response Fields
-
-If the token was refreshed successfully, you'll receive a `token` field in the response body object:
-
-```json
-{
- "token": "..."
-}
-```
-
-Use that token in the header of subsequent requests to send authenticated requests.
-
-***
-
-## Reset Password Routes
-
-To reset a user's password:
-
-1. Generate a token using the [Generate Reset Password Token API route](#generate-reset-password-token-route).
- - The API route emits the `auth.password_reset` event, passing the token in the payload.
- - You can create a subscriber, as seen in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/reset-password/index.html.md), that listens to the event and send a notification to the user.
-2. Pass the token to the [Reset Password API route](#reset-password-route) to reset the password.
- - The URL in the user's notification should direct them to a frontend URL, which sends a request to this route.
-
-[Storefront Development: How to Reset a Customer's Password.](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/reset-password/index.html.md)
-
-### Generate Reset Password Token Route
-
-The Medusa application defines an API route at `/auth/{actor_type}/{auth_provider}/reset-password` that emits the `auth.password_reset` event, passing the token in the payload.
-
-```bash
-curl -X POST http://localhost:9000/auth/{actor_type}/{providers}/reset-password
--H 'Content-Type: application/json' \
---data-raw '{
- "identifier": "Whitney_Schultz@gmail.com"
-}'
-```
-
-This API route is useful for providers like `emailpass` that store a user's password and use it for authentication.
-
-#### Path Parameters
-
-Its path parameters are:
-
-- `{actor_type}`: the actor type of the user you're authenticating. For example, `customer`.
-- `{provider}`: the auth provider to handle the authentication. For example, `emailpass`.
-
-#### Request Body Parameters
-
-This route accepts in the request body an object having the following property:
-
-- `identifier`: The user's identifier in the specified auth provider. For example, for the `emailpass` auth provider, you pass the user's email.
-
-#### Response Fields
-
-If the authentication is successful, the request returns a `201` response code.
-
-### Reset Password Route
-
-The Medusa application defines an API route at `/auth/{actor_type}/{auth_provider}/update` that accepts a token and, if valid, updates the user's password.
-
-```bash
-curl -X POST http://localhost:9000/auth/{actor_type}/{providers}/update
--H 'Content-Type: application/json' \
--H 'Authorization: Bearer {token}' \
---data-raw '{
- "email": "Whitney_Schultz@gmail.com",
- "password": "supersecret"
-}'
-```
-
-This API route is useful for providers like `emailpass` that store a user's password and use it for logging them in.
-
-#### Path Parameters
-
-Its path parameters are:
-
-- `{actor_type}`: the actor type of the user you're authenticating. For example, `customer`.
-- `{provider}`: the auth provider to handle the authentication. For example, `emailpass`.
-
-#### Pass Token in Authorization Header
-
-Before [Medusa v2.6](https://github.com/medusajs/medusa/releases/tag/v2.6), you passed the token as a query parameter. Now, you must pass it in the `Authorization` header.
-
-In the request's authorization header, you must pass the token generated using the [Generate Reset Password Token route](#generate-reset-password-token-route). You pass it as a bearer token.
-
-### Request Body Parameters
-
-This route accepts in the request body an object that has the data necessary for the provider to update the user's password.
-
-For the `emailpass` provider, you must pass the following properties:
-
-- `email`: The user's email.
-- `password`: The new password.
-
-### Response Fields
-
-If the authentication is successful, the request returns an object with a `success` property set to `true`:
-
-```json
-{
- "success": "true"
-}
-```
-
-
# Auth Module Options
In this document, you'll learn about the options of the Auth Module.
@@ -22206,601 +23617,6 @@ The page shows the user password fields to enter their new password, then submit
- [Storefront Guide: Reset Customer Password](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/reset-password/index.html.md)
-# Fulfillment Concepts
-
-In this document, you’ll learn about some basic fulfillment concepts.
-
-## Fulfillment Set
-
-A fulfillment set is a general form or way of fulfillment. For example, shipping is a form of fulfillment, and pick-up is another form of fulfillment. Each of these can be created as fulfillment sets.
-
-A fulfillment set is represented by the [FulfillmentSet data model](https://docs.medusajs.com/references/fulfillment/models/FulfillmentSet/index.html.md). All other configurations, options, and management features are related to a fulfillment set, in one way or another.
-
-```ts
-const fulfillmentSets = await fulfillmentModuleService.createFulfillmentSets(
- [
- {
- name: "Shipping",
- type: "shipping",
- },
- {
- name: "Pick-up",
- type: "pick-up",
- },
- ]
-)
-```
-
-***
-
-## Service Zone
-
-A service zone is a collection of geographical zones or areas. It’s used to restrict available shipping options to a defined set of locations.
-
-A service zone is represented by the [ServiceZone data model](https://docs.medusajs.com/references/fulfillment/models/ServiceZone/index.html.md). It’s associated with a fulfillment set, as each service zone is specific to a form of fulfillment. For example, if a customer chooses to pick up items, you can restrict the available shipping options based on their location.
-
-
-
-A service zone can have multiple geographical zones, each represented by the [GeoZone data model](https://docs.medusajs.com/references/fulfillment/models/GeoZone/index.html.md). It holds location-related details to narrow down supported areas, such as country, city, or province code.
-
-***
-
-## Shipping Profile
-
-A shipping profile defines a type of items that are shipped in a similar manner. For example, a `default` shipping profile is used for all item types, but the `digital` shipping profile is used for digital items that aren’t shipped and delivered conventionally.
-
-A shipping profile is represented by the [ShippingProfile data model](https://docs.medusajs.com/references/fulfillment/models/ShippingProfile/index.html.md). It only defines the profile’s details, but it’s associated with the shipping options available for the item type.
-
-
-# Fulfillment Module Provider
-
-In this document, you’ll learn what a fulfillment module provider is.
-
-Refer to this [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/locations-and-shipping/locations#manage-fulfillment-providers/index.html.md) to learn how to add a fulfillment provider to a location using the dashboard.
-
-## What’s a Fulfillment Module Provider?
-
-A fulfillment module provider handles fulfilling items, typically using a third-party integration.
-
-Fulfillment module providers registered in the Fulfillment Module's [options](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/fulfillment/module-options/index.html.md) are stored and represented by the [FulfillmentProvider data model](https://docs.medusajs.com/references/fulfillment/models/FulfillmentProvider/index.html.md).
-
-***
-
-## Configure Fulfillment Providers
-
-The Fulfillment Module accepts a `providers` option that allows you to register providers in your application.
-
-Learn more about the `providers` option in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/fulfillment/module-options/index.html.md).
-
-***
-
-## How to Create a Fulfillment Provider?
-
-Refer to [this guide](https://docs.medusajs.com/references/fulfillment/provider/index.html.md) to learn how to create a fulfillment module provider.
-
-
-# Item Fulfillment
-
-In this document, you’ll learn about the concepts of item fulfillment.
-
-## Fulfillment Data Model
-
-A fulfillment is the shipping and delivery of one or more items to the customer. It’s represented by the [Fulfillment data model](https://docs.medusajs.com/references/fulfillment/models/Fulfillment/index.html.md).
-
-***
-
-## Fulfillment Processing by a Fulfillment Provider
-
-A fulfillment is associated with a fulfillment provider that handles all its processing, such as creating a shipment for the fulfillment’s items.
-
-The fulfillment is also associated with a shipping option of that provider, which determines how the item is shipped.
-
-
-
-***
-
-## data Property
-
-The `Fulfillment` data model has a `data` property that holds any necessary data for the third-party fulfillment provider to process the fulfillment.
-
-For example, the `data` property can hold the ID of the fulfillment in the third-party provider. The associated fulfillment provider then uses it whenever it retrieves the fulfillment’s details.
-
-***
-
-## Fulfillment Items
-
-A fulfillment is used to fulfill one or more items. Each item is represented by the `FulfillmentItem` data model.
-
-The fulfillment item holds details relevant to fulfilling the item, such as barcode, SKU, and quantity to fulfill.
-
-
-
-***
-
-## Fulfillment Label
-
-Once a shipment is created for the fulfillment, you can store its tracking number, URL, or other related details as a label, represented by the `FulfillmentLabel` data model.
-
-***
-
-## Fulfillment Status
-
-The `Fulfillment` data model has three properties to keep track of the current status of the fulfillment:
-
-- `packed_at`: The date the fulfillment was packed. If set, then the fulfillment has been packed.
-- `shipped_at`: The date the fulfillment was shipped. If set, then the fulfillment has been shipped.
-- `delivered_at`: The date the fulfillment was delivered. If set, then the fulfillment has been delivered.
-
-
-# Links between Fulfillment Module and Other Modules
-
-This document showcases the module links defined between the Fulfillment Module and other commerce modules.
-
-## Summary
-
-The Fulfillment Module has the following links to other modules:
-
-|First Data Model|Second Data Model|Type|Description|
-|---|---|---|---|
-| in ||Stored||
-| in ||Stored||
-| in ||Stored||
-| in ||Stored||
-| in ||Stored||
-| in ||Stored||
-
-***
-
-## Order Module
-
-The [Order Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/order/index.html.md) provides order-management functionalities.
-
-Medusa defines a link between the `Fulfillment` and `Order` data models. A fulfillment is created for an orders' items.
-
-
-
-A fulfillment is also created for a return's items. So, Medusa defines a link between the `Fulfillment` and `Return` data models.
-
-
-
-### Retrieve with Query
-
-To retrieve the order of a fulfillment with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `order.*` in `fields`:
-
-To retrieve the return, pass `return.*` in `fields`.
-
-### query.graph
-
-```ts
-const { data: fulfillments } = await query.graph({
- entity: "fulfillment",
- fields: [
- "order.*",
- ],
-})
-
-// fulfillments.order
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: fulfillments } = useQueryGraphStep({
- entity: "fulfillment",
- fields: [
- "order.*",
- ],
-})
-
-// fulfillments.order
-```
-
-### Manage with Link
-
-To manage the order of a cart, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
-
-### link.create
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await link.create({
- [Modules.ORDER]: {
- order_id: "order_123",
- },
- [Modules.FULFILLMENT]: {
- fulfillment_id: "ful_123",
- },
-})
-```
-
-### createRemoteLinkStep
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-createRemoteLinkStep({
- [Modules.ORDER]: {
- order_id: "order_123",
- },
- [Modules.FULFILLMENT]: {
- fulfillment_id: "ful_123",
- },
-})
-```
-
-***
-
-## Pricing Module
-
-The Pricing Module provides features to store, manage, and retrieve the best prices in a specified context.
-
-Medusa defines a link between the `PriceSet` and `ShippingOption` data models. A shipping option's price is stored as a price set.
-
-
-
-### Retrieve with Query
-
-To retrieve the price set of a shipping option with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `price_set.*` in `fields`:
-
-### query.graph
-
-```ts
-const { data: shippingOptions } = await query.graph({
- entity: "shipping_option",
- fields: [
- "price_set.*",
- ],
-})
-
-// shippingOptions.price_set
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: shippingOptions } = useQueryGraphStep({
- entity: "shipping_option",
- fields: [
- "price_set.*",
- ],
-})
-
-// shippingOptions.price_set
-```
-
-### Manage with Link
-
-To manage the price set of a shipping option, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
-
-### link.create
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await link.create({
- [Modules.FULFILLMENT]: {
- shipping_option_id: "so_123",
- },
- [Modules.PRICING]: {
- price_set_id: "pset_123",
- },
-})
-```
-
-### createRemoteLinkStep
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-createRemoteLinkStep({
- [Modules.FULFILLMENT]: {
- shipping_option_id: "so_123",
- },
- [Modules.PRICING]: {
- price_set_id: "pset_123",
- },
-})
-```
-
-***
-
-## Product Module
-
-Medusa defines a link between the `ShippingProfile` data model and the `Product` data model of the Product Module. Each product must belong to a shipping profile.
-
-This link is introduced in [Medusa v2.5.0](https://github.com/medusajs/medusa/releases/tag/v2.5.0).
-
-### Retrieve with Query
-
-To retrieve the products of a shipping profile with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `products.*` in `fields`:
-
-### query.graph
-
-```ts
-const { data: shippingProfiles } = await query.graph({
- entity: "shipping_profile",
- fields: [
- "products.*",
- ],
-})
-
-// shippingProfiles.products
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: shippingProfiles } = useQueryGraphStep({
- entity: "shipping_profile",
- fields: [
- "products.*",
- ],
-})
-
-// shippingProfiles.products
-```
-
-### Manage with Link
-
-To manage the shipping profile of a product, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
-
-### link.create
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await link.create({
- [Modules.PRODUCT]: {
- product_id: "prod_123",
- },
- [Modules.FULFILLMENT]: {
- shipping_profile_id: "sp_123",
- },
-})
-```
-
-### createRemoteLinkStep
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-createRemoteLinkStep({
- [Modules.PRODUCT]: {
- product_id: "prod_123",
- },
- [Modules.FULFILLMENT]: {
- shipping_profile_id: "sp_123",
- },
-})
-```
-
-***
-
-## Stock Location Module
-
-The Stock Location Module provides features to manage stock locations in a store.
-
-Medusa defines a link between the `FulfillmentSet` and `StockLocation` data models. A fulfillment set can be conditioned to a specific stock location.
-
-
-
-Medusa also defines a link between the `FulfillmentProvider` and `StockLocation` data models to indicate the providers that can be used in a location.
-
-
-
-### Retrieve with Query
-
-To retrieve the stock location of a fulfillment set with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `location.*` in `fields`:
-
-To retrieve the stock location of a fulfillment provider, pass `locations.*` in `fields`.
-
-### query.graph
-
-```ts
-const { data: fulfillmentSets } = await query.graph({
- entity: "fulfillment_set",
- fields: [
- "location.*",
- ],
-})
-
-// fulfillmentSets.location
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: fulfillmentSets } = useQueryGraphStep({
- entity: "fulfillment_set",
- fields: [
- "location.*",
- ],
-})
-
-// fulfillmentSets.location
-```
-
-### Manage with Link
-
-To manage the stock location of a fulfillment set, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
-
-### link.create
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await link.create({
- [Modules.STOCK_LOCATION]: {
- stock_location_id: "sloc_123",
- },
- [Modules.FULFILLMENT]: {
- fulfillment_set_id: "fset_123",
- },
-})
-```
-
-### createRemoteLinkStep
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-createRemoteLinkStep({
- [Modules.STOCK_LOCATION]: {
- stock_location_id: "sloc_123",
- },
- [Modules.FULFILLMENT]: {
- fulfillment_set_id: "fset_123",
- },
-})
-```
-
-
-# Fulfillment Module Options
-
-In this document, you'll learn about the options of the Fulfillment Module.
-
-## providers
-
-The `providers` option is an array of fulfillment module providers.
-
-When the Medusa application starts, these providers are registered and can be used to process fulfillments.
-
-For example:
-
-```ts title="medusa-config.ts"
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-module.exports = defineConfig({
- // ...
- modules: [
- {
- resolve: "@medusajs/medusa/fulfillment",
- options: {
- providers: [
- {
- resolve: `@medusajs/medusa/fulfillment-manual`,
- id: "manual",
- options: {
- // provider options...
- },
- },
- ],
- },
- },
- ],
-})
-```
-
-The `providers` option is an array of objects that accept the following properties:
-
-- `resolve`: A string indicating either the package name of the module provider or the path to it relative to the `src` directory.
-- `id`: A string indicating the provider's unique name or ID.
-- `options`: An optional object of the module provider's options.
-
-
-# Shipping Option
-
-In this document, you’ll learn about shipping options and their rules.
-
-## What’s a Shipping Option?
-
-A shipping option is a way of shipping an item. Each fulfillment provider provides a set of shipping options. For example, a provider may provide a shipping option for express shipping and another for standard shipping.
-
-When the customer places their order, they choose a shipping option to be used to fulfill their items.
-
-A shipping option is represented by the [ShippingOption data model](https://docs.medusajs.com/references/fulfillment/models/ShippingOption/index.html.md).
-
-***
-
-## Service Zone Restrictions
-
-A shipping option is restricted by a service zone, limiting the locations a shipping option be used in.
-
-For example, a fulfillment provider may have a shipping option that can be used in the United States, and another in Canada.
-
-
-
-Service zones can be more restrictive, such as restricting to certain cities or province codes.
-
-
-
-***
-
-## Shipping Option Rules
-
-You can restrict shipping options by custom rules, such as the item’s weight or the customer’s group.
-
-These rules are represented by the [ShippingOptionRule data model](https://docs.medusajs.com/references/fulfillment/models/ShippingOptionRule/index.html.md). Its properties define the custom rule:
-
-- `attribute`: The name of a property or table that the rule applies to. For example, `customer_group`.
-- `operator`: The operator used in the condition. For example:
- - To allow multiple values, use the operator `in`, which validates that the provided values are in the rule’s values.
- - To create a negation condition that considers `value` against the rule, use `nin`, which validates that the provided values aren’t in the rule’s values.
- - Check out more operators in [this reference](https://docs.medusajs.com/references/fulfillment/types/fulfillment.RuleOperatorType/index.html.md).
-- `value`: One or more values.
-
-
-
-A shipping option can have multiple rules. For example, you can add rules to a shipping option so that it's available if the customer belongs to the VIP group and the total weight is less than 2000g.
-
-
-
-***
-
-## Shipping Profile and Types
-
-A shipping option belongs to a type. For example, a shipping option’s type may be `express`, while another `standard`. The type is represented by the [ShippingOptionType data model](https://docs.medusajs.com/references/fulfillment/models/ShippingOptionType/index.html.md).
-
-A shipping option also belongs to a shipping profile, as each shipping profile defines the type of items to be shipped in a similar manner.
-
-***
-
-## data Property
-
-When fulfilling an item, you might use a third-party fulfillment provider that requires additional custom data to be passed along from the checkout or order-creation process.
-
-The `ShippingOption` data model has a `data` property. It's an object that stores custom data relevant later when creating and processing a fulfillment.
-
-
# Inventory Concepts
In this document, you’ll learn about the main concepts in the Inventory Module, and how data is stored and related.
@@ -23647,6 +24463,75 @@ Any payment or refund made is stored in the [Transaction data model](https://doc
When an exchange is confirmed, the order’s version is incremented.
+# Order Change
+
+In this document, you'll learn about the Order Change data model and possible actions in it.
+
+## OrderChange Data Model
+
+The [OrderChange data model](https://docs.medusajs.com/references/order/models/OrderChange/index.html.md) represents any kind of change to an order, such as a return, exchange, or edit.
+
+Its `change_type` property indicates what the order change is created for:
+
+1. `edit`: The order change is making edits to the order, as explained in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/order/edit/index.html.md).
+2. `exchange`: The order change is associated with an exchange, which you can learn about in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/order/exchange/index.html.md).
+3. `claim`: The order change is associated with a claim, which you can learn about in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/order/claim/index.html.md).
+4. `return_request` or `return_receive`: The order change is associated with a return, which you can learn about in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/order/return/index.html.md).
+
+Once the order change is confirmed, its changes are applied on the order.
+
+***
+
+## Order Change Actions
+
+The actions to perform on the original order by a change, such as adding an item, are represented by the [OrderChangeAction data model](https://docs.medusajs.com/references/order/models/OrderChangeAction/index.html.md).
+
+The `OrderChangeAction` has an `action` property that indicates the type of action to perform on the order, and a `details` property that holds more details related to the action.
+
+The following table lists the possible `action` values that Medusa uses and what `details` they carry.
+
+|Action|Description|Details|
+|---|---|---|---|---|
+|\`ITEM\_ADD\`|Add an item to the order.|\`details\`|
+|\`ITEM\_UPDATE\`|Update an item in the order.|\`details\`|
+|\`RETURN\_ITEM\`|Set an item to be returned.|\`details\`|
+|\`RECEIVE\_RETURN\_ITEM\`|Mark a return item as received.|\`details\`|
+|\`RECEIVE\_DAMAGED\_RETURN\_ITEM\`|Mark a return item that's damaged as received.|\`details\`|
+|\`SHIPPING\_ADD\`|Add a shipping method for new or returned items.|No details added. The ID to the shipping method is added in the |
+|\`SHIPPING\_ADD\`|Add a shipping method for new or returned items.|No details added. The ID to the shipping method is added in the |
+|\`WRITE\_OFF\_ITEM\`|Remove an item's quantity as part of the claim, without adding the quantity back to the item variant's inventory.|\`details\`|
+
+
+# Order Versioning
+
+In this document, you’ll learn how an order and its details are versioned.
+
+## What's Versioning?
+
+Versioning means assigning a version number to a record, such as an order and its items. This is useful to view the different versions of the order following changes in its lifetime.
+
+When changes are made on an order, such as an item is added or returned, the order's version changes.
+
+***
+
+## version Property
+
+The `Order` and `OrderSummary` data models have a `version` property that indicates the current version. By default, its value is `1`.
+
+Other order-related data models, such as `OrderItem`, also has a `version` property, but it indicates the version it belongs to.
+
+***
+
+## How the Version Changes
+
+When the order is changed, such as an item is exchanged, this changes the version of the order and its related data:
+
+1. The version of the order and its summary is incremented.
+2. Related order data that have a `version` property, such as the `OrderItem`, are duplicated. The duplicated item has the new version, whereas the original item has the previous version.
+
+When the order is retrieved, only the related data having the same version is retrieved.
+
+
# Links between Order Module and Other Modules
This document showcases the module links defined between the Order Module and other commerce modules.
@@ -24171,75 +25056,6 @@ const { data: orders } = useQueryGraphStep({
```
-# Order Change
-
-In this document, you'll learn about the Order Change data model and possible actions in it.
-
-## OrderChange Data Model
-
-The [OrderChange data model](https://docs.medusajs.com/references/order/models/OrderChange/index.html.md) represents any kind of change to an order, such as a return, exchange, or edit.
-
-Its `change_type` property indicates what the order change is created for:
-
-1. `edit`: The order change is making edits to the order, as explained in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/order/edit/index.html.md).
-2. `exchange`: The order change is associated with an exchange, which you can learn about in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/order/exchange/index.html.md).
-3. `claim`: The order change is associated with a claim, which you can learn about in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/order/claim/index.html.md).
-4. `return_request` or `return_receive`: The order change is associated with a return, which you can learn about in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/order/return/index.html.md).
-
-Once the order change is confirmed, its changes are applied on the order.
-
-***
-
-## Order Change Actions
-
-The actions to perform on the original order by a change, such as adding an item, are represented by the [OrderChangeAction data model](https://docs.medusajs.com/references/order/models/OrderChangeAction/index.html.md).
-
-The `OrderChangeAction` has an `action` property that indicates the type of action to perform on the order, and a `details` property that holds more details related to the action.
-
-The following table lists the possible `action` values that Medusa uses and what `details` they carry.
-
-|Action|Description|Details|
-|---|---|---|---|---|
-|\`ITEM\_ADD\`|Add an item to the order.|\`details\`|
-|\`ITEM\_UPDATE\`|Update an item in the order.|\`details\`|
-|\`RETURN\_ITEM\`|Set an item to be returned.|\`details\`|
-|\`RECEIVE\_RETURN\_ITEM\`|Mark a return item as received.|\`details\`|
-|\`RECEIVE\_DAMAGED\_RETURN\_ITEM\`|Mark a return item that's damaged as received.|\`details\`|
-|\`SHIPPING\_ADD\`|Add a shipping method for new or returned items.|No details added. The ID to the shipping method is added in the |
-|\`SHIPPING\_ADD\`|Add a shipping method for new or returned items.|No details added. The ID to the shipping method is added in the |
-|\`WRITE\_OFF\_ITEM\`|Remove an item's quantity as part of the claim, without adding the quantity back to the item variant's inventory.|\`details\`|
-
-
-# Order Versioning
-
-In this document, you’ll learn how an order and its details are versioned.
-
-## What's Versioning?
-
-Versioning means assigning a version number to a record, such as an order and its items. This is useful to view the different versions of the order following changes in its lifetime.
-
-When changes are made on an order, such as an item is added or returned, the order's version changes.
-
-***
-
-## version Property
-
-The `Order` and `OrderSummary` data models have a `version` property that indicates the current version. By default, its value is `1`.
-
-Other order-related data models, such as `OrderItem`, also has a `version` property, but it indicates the version it belongs to.
-
-***
-
-## How the Version Changes
-
-When the order is changed, such as an item is exchanged, this changes the version of the order and its related data:
-
-1. The version of the order and its summary is incremented.
-2. Related order data that have a `version` property, such as the `OrderItem`, are duplicated. The duplicated item has the new version, whereas the original item has the previous version.
-
-When the order is retrieved, only the related data having the same version is retrieved.
-
-
# Order Return
In this document, you’ll learn about order returns.
@@ -24301,6 +25117,83 @@ The order’s version is incremented when:
2. A return is marked as received.
+# Tax Lines in Order Module
+
+In this document, you’ll learn about tax lines in an order.
+
+## What are Tax Lines?
+
+A tax line indicates the tax rate of a line item or a shipping method.
+
+The [OrderLineItemTaxLine data model](https://docs.medusajs.com/references/order/models/OrderLineItemTaxLine/index.html.md) represents a line item’s tax line, and the [OrderShippingMethodTaxLine data model](https://docs.medusajs.com/references/order/models/OrderShippingMethodTaxLine/index.html.md) represents a shipping method’s tax line.
+
+
+
+***
+
+## Tax Inclusivity
+
+By default, the tax amount is calculated by taking the tax rate from the line item or shipping method’s amount and then adding it to the item/method’s subtotal.
+
+However, line items and shipping methods have an `is_tax_inclusive` property that, when enabled, indicates that the item or method’s price already includes taxes.
+
+So, instead of calculating the tax rate and adding it to the item/method’s subtotal, it’s calculated as part of the subtotal.
+
+The following diagram is a simplified showcase of how a subtotal is calculated from the tax perspective.
+
+
+
+For example, if a line item's amount is `5000`, the tax rate is `10`, and `is_tax_inclusive` is enabled, the tax amount is 10% of `5000`, which is `500`. The item's unit price becomes `4500`.
+
+
+# Transactions
+
+In this document, you’ll learn about an order’s transactions and its use.
+
+## What is a Transaction?
+
+A transaction represents any order payment process, such as capturing or refunding an amount. It’s represented by the [OrderTransaction data model](https://docs.medusajs.com/references/order/models/OrderTransaction/index.html.md).
+
+The transaction’s main purpose is to ensure a correct balance between paid and outstanding amounts.
+
+Transactions are also associated with returns, claims, and exchanges if additional payment or refund is required.
+
+***
+
+## Checking Outstanding Amount
+
+The order’s total amounts are stored in the `OrderSummary`'s `totals` property, which is a JSON object holding the total details of the order.
+
+```json
+{
+ "totals": {
+ "total": 30,
+ "subtotal": 30,
+ // ...
+ }
+}
+```
+
+To check the outstanding amount of the order, its transaction amounts are summed. Then, the following conditions are checked:
+
+|Condition|Result|
+|---|---|---|
+|summary’s total - transaction amounts total = 0|There’s no outstanding amount.|
+|summary’s total - transaction amounts total > 0|The customer owes additional payment to the merchant.|
+|summary’s total - transaction amounts total \< 0|The merchant owes the customer a refund.|
+
+***
+
+## Transaction Reference
+
+The Order Module doesn’t provide payment processing functionalities, so it doesn’t store payments that can be processed. Payment functionalities are provided by the [Payment Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/index.html.md).
+
+The `OrderTransaction` data model has two properties that determine which data model and record holds the actual payment’s details:
+
+- `reference`: indicates the table’s name in the database. For example, `payment` from the Payment Module.
+- `reference_id`: indicates the ID of the record in the table. For example, `pay_123`.
+
+
# Promotions Adjustments in Orders
In this document, you’ll learn how a promotion is applied to an order’s items and shipping methods using adjustment lines.
@@ -24423,892 +25316,6 @@ await orderModuleService.setOrderShippingMethodAdjustments(
```
-# Tax Lines in Order Module
-
-In this document, you’ll learn about tax lines in an order.
-
-## What are Tax Lines?
-
-A tax line indicates the tax rate of a line item or a shipping method.
-
-The [OrderLineItemTaxLine data model](https://docs.medusajs.com/references/order/models/OrderLineItemTaxLine/index.html.md) represents a line item’s tax line, and the [OrderShippingMethodTaxLine data model](https://docs.medusajs.com/references/order/models/OrderShippingMethodTaxLine/index.html.md) represents a shipping method’s tax line.
-
-
-
-***
-
-## Tax Inclusivity
-
-By default, the tax amount is calculated by taking the tax rate from the line item or shipping method’s amount and then adding it to the item/method’s subtotal.
-
-However, line items and shipping methods have an `is_tax_inclusive` property that, when enabled, indicates that the item or method’s price already includes taxes.
-
-So, instead of calculating the tax rate and adding it to the item/method’s subtotal, it’s calculated as part of the subtotal.
-
-The following diagram is a simplified showcase of how a subtotal is calculated from the tax perspective.
-
-
-
-For example, if a line item's amount is `5000`, the tax rate is `10`, and `is_tax_inclusive` is enabled, the tax amount is 10% of `5000`, which is `500`. The item's unit price becomes `4500`.
-
-
-# Transactions
-
-In this document, you’ll learn about an order’s transactions and its use.
-
-## What is a Transaction?
-
-A transaction represents any order payment process, such as capturing or refunding an amount. It’s represented by the [OrderTransaction data model](https://docs.medusajs.com/references/order/models/OrderTransaction/index.html.md).
-
-The transaction’s main purpose is to ensure a correct balance between paid and outstanding amounts.
-
-Transactions are also associated with returns, claims, and exchanges if additional payment or refund is required.
-
-***
-
-## Checking Outstanding Amount
-
-The order’s total amounts are stored in the `OrderSummary`'s `totals` property, which is a JSON object holding the total details of the order.
-
-```json
-{
- "totals": {
- "total": 30,
- "subtotal": 30,
- // ...
- }
-}
-```
-
-To check the outstanding amount of the order, its transaction amounts are summed. Then, the following conditions are checked:
-
-|Condition|Result|
-|---|---|---|
-|summary’s total - transaction amounts total = 0|There’s no outstanding amount.|
-|summary’s total - transaction amounts total > 0|The customer owes additional payment to the merchant.|
-|summary’s total - transaction amounts total \< 0|The merchant owes the customer a refund.|
-
-***
-
-## Transaction Reference
-
-The Order Module doesn’t provide payment processing functionalities, so it doesn’t store payments that can be processed. Payment functionalities are provided by the [Payment Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/index.html.md).
-
-The `OrderTransaction` data model has two properties that determine which data model and record holds the actual payment’s details:
-
-- `reference`: indicates the table’s name in the database. For example, `payment` from the Payment Module.
-- `reference_id`: indicates the ID of the record in the table. For example, `pay_123`.
-
-
-# Account Holders and Saved Payment Methods
-
-In this documentation, you'll learn about account holders, and how they're used to save payment methods in third-party payment providers.
-
-Account holders are available starting from Medusa `v2.5.0`.
-
-## What's an Account Holder?
-
-An account holder represents a customer that can have saved payment methods in a third-party service. It's represented by the `AccountHolder` data model.
-
-It holds fields retrieved from the third-party provider, such as:
-
-- `external_id`: The ID of the equivalent customer or account holder in the third-party provider.
-- `data`: Data returned by the payment provider when the account holder is created.
-
-A payment provider that supports saving payment methods for customers would create the equivalent of an account holder in the third-party provider. Then, whenever a payment method is saved, it would be saved under the account holder in the third-party provider.
-
-### Relation between Account Holder and Customer
-
-The Medusa application creates a link between the [Customer](https://docs.medusajs.com/references/customer/models/Customer/index.html.md) data model of the [Customer Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/customer/index.html.md) and the `AccountHolder` data model of the Payment Module.
-
-This link indicates that a customer can have more than one account holder, each representing saved payment methods in different payment providers.
-
-Learn more about this link in the [Link to Other Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/links-to-other-modules/index.html.md) guide.
-
-***
-
-## Save Payment Methods
-
-If a payment provider supports saving payment methods for a customer, they must implement the following methods:
-
-- `createAccountHolder`: Creates an account holder in the payment provider. The Payment Module uses this method before creating the account holder in Medusa, and uses the returned data to set fields like `external_id` and `data` in the created `AccountHolder` record.
-- `deleteAccountHolder`: Deletes an account holder in the payment provider. The Payment Module uses this method when an account holder is deleted in Medusa.
-- `savePaymentMethod`: Saves a payment method for an account holder in the payment provider.
-- `listPaymentMethods`: Lists saved payment methods in the third-party service for an account holder. This is useful when displaying the customer's saved payment methods in the storefront.
-
-Learn more about implementing these methods in the [Create Payment Provider guide](https://docs.medusajs.com/references/payment/provider/index.html.md).
-
-***
-
-## Account Holder in Medusa Payment Flows
-
-In the Medusa application, when a payment session is created for a registered customer, the Medusa application uses the Payment Module to create an account holder for the customer.
-
-Consequently, the Payment Module uses the payment provider to create an account holder in the third-party service, then creates the account holder in Medusa.
-
-This flow is only supported if the chosen payment provider has implemented the necessary [save payment methods](#save-payment-methods).
-
-
-# Links between Payment Module and Other Modules
-
-This document showcases the module links defined between the Payment Module and other commerce modules.
-
-## Summary
-
-The Payment Module has the following links to other modules:
-
-|First Data Model|Second Data Model|Type|Description|
-|---|---|---|---|
-| in ||Stored||
-| in ||Stored||
-| in ||Stored||
-| in ||Stored||
-| in ||Stored||
-| in ||Stored||
-
-***
-
-## Cart Module
-
-The Cart Module provides cart-related features, but not payment processing.
-
-Medusa defines a link between the `Cart` and `PaymentCollection` data models. A cart has a payment collection which holds all the authorized payment sessions and payments made related to the cart.
-
-Learn more about this relation in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-collection#usage-with-the-cart-module/index.html.md).
-
-### Retrieve with Query
-
-To retrieve the cart associated with the payment collection with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `cart.*` in `fields`:
-
-### query.graph
-
-```ts
-const { data: paymentCollections } = await query.graph({
- entity: "payment_collection",
- fields: [
- "cart.*",
- ],
-})
-
-// paymentCollections.cart
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: paymentCollections } = useQueryGraphStep({
- entity: "payment_collection",
- fields: [
- "cart.*",
- ],
-})
-
-// paymentCollections.cart
-```
-
-### Manage with Link
-
-To manage the payment collection of a cart, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
-
-### link.create
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await link.create({
- [Modules.CART]: {
- cart_id: "cart_123",
- },
- [Modules.PAYMENT]: {
- payment_collection_id: "paycol_123",
- },
-})
-```
-
-### createRemoteLinkStep
-
-```ts
-import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-createRemoteLinkStep({
- [Modules.CART]: {
- cart_id: "cart_123",
- },
- [Modules.PAYMENT]: {
- payment_collection_id: "paycol_123",
- },
-})
-```
-
-***
-
-## Customer Module
-
-Medusa defines a link between the `Customer` and `AccountHolder` data models, allowing payment providers to save payment methods for a customer, if the payment provider supports it.
-
-This link is available starting from Medusa `v2.5.0`.
-
-### Retrieve with Query
-
-To retrieve the customer associated with an account holder with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `customer.*` in `fields`:
-
-### query.graph
-
-```ts
-const { data: accountHolders } = await query.graph({
- entity: "account_holder",
- fields: [
- "customer.*",
- ],
-})
-
-// accountHolders.customer
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: accountHolders } = useQueryGraphStep({
- entity: "account_holder",
- fields: [
- "customer.*",
- ],
-})
-
-// accountHolders.customer
-```
-
-### Manage with Link
-
-To manage the account holders of a customer, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
-
-### link.create
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await link.create({
- [Modules.CUSTOMER]: {
- customer_id: "cus_123",
- },
- [Modules.PAYMENT]: {
- account_holder_id: "acchld_123",
- },
-})
-```
-
-### createRemoteLinkStep
-
-```ts
-import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-createRemoteLinkStep({
- [Modules.CUSTOMER]: {
- customer_id: "cus_123",
- },
- [Modules.PAYMENT]: {
- account_holder_id: "acchld_123",
- },
-})
-```
-
-***
-
-## Order Module
-
-An order's payment details are stored in a payment collection. This also applies for claims and exchanges.
-
-So, Medusa defines links between the `PaymentCollection` data model and the `Order`, `OrderClaim`, and `OrderExchange` data models.
-
-
-
-### Retrieve with Query
-
-To retrieve the order of a payment collection with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `order.*` in `fields`:
-
-### query.graph
-
-```ts
-const { data: paymentCollections } = await query.graph({
- entity: "payment_collection",
- fields: [
- "order.*",
- ],
-})
-
-// paymentCollections.order
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: paymentCollections } = useQueryGraphStep({
- entity: "payment_collection",
- fields: [
- "order.*",
- ],
-})
-
-// paymentCollections.order
-```
-
-### Manage with Link
-
-To manage the payment collections of an order, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
-
-### link.create
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await link.create({
- [Modules.ORDER]: {
- order_id: "order_123",
- },
- [Modules.PAYMENT]: {
- payment_collection_id: "paycol_123",
- },
-})
-```
-
-### createRemoteLinkStep
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-createRemoteLinkStep({
- [Modules.ORDER]: {
- order_id: "order_123",
- },
- [Modules.PAYMENT]: {
- payment_collection_id: "paycol_123",
- },
-})
-```
-
-***
-
-## Region Module
-
-You can specify for each region which payment providers are available. The Medusa application defines a link between the `PaymentProvider` and the `Region` data models.
-
-
-
-This increases the flexibility of your store. For example, you only show during checkout the payment providers associated with the cart's region.
-
-### Retrieve with Query
-
-To retrieve the regions of a payment provider with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `regions.*` in `fields`:
-
-### query.graph
-
-```ts
-const { data: paymentProviders } = await query.graph({
- entity: "payment_provider",
- fields: [
- "regions.*",
- ],
-})
-
-// paymentProviders.regions
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: paymentProviders } = useQueryGraphStep({
- entity: "payment_provider",
- fields: [
- "regions.*",
- ],
-})
-
-// paymentProviders.regions
-```
-
-### Manage with Link
-
-To manage the payment providers in a region, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
-
-### link.create
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await link.create({
- [Modules.REGION]: {
- region_id: "reg_123",
- },
- [Modules.PAYMENT]: {
- payment_provider_id: "pp_stripe_stripe",
- },
-})
-```
-
-### createRemoteLinkStep
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-createRemoteLinkStep({
- [Modules.REGION]: {
- region_id: "reg_123",
- },
- [Modules.PAYMENT]: {
- payment_provider_id: "pp_stripe_stripe",
- },
-})
-```
-
-
-# Payment Module Options
-
-In this document, you'll learn about the options of the Payment Module.
-
-## All Module Options
-
-|Option|Description|Required|Default|
-|---|---|---|---|---|---|---|
-|\`webhook\_delay\`|A number indicating the delay in milliseconds before processing a webhook event.|No|\`5000\`|
-|\`webhook\_retries\`|The number of times to retry the webhook event processing in case of an error.|No|\`3\`|
-|\`providers\`|An array of payment providers to install and register. Learn more |No|-|
-
-***
-
-## providers Option
-
-The `providers` option is an array of payment module providers.
-
-When the Medusa application starts, these providers are registered and can be used to process payments.
-
-For example:
-
-```ts title="medusa-config.ts"
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-module.exports = defineConfig({
- // ...
- modules: [
- {
- resolve: "@medusajs/medusa/payment",
- options: {
- providers: [
- {
- resolve: "@medusajs/medusa/payment-stripe",
- id: "stripe",
- options: {
- // ...
- },
- },
- ],
- },
- },
- ],
-})
-```
-
-The `providers` option is an array of objects that accept the following properties:
-
-- `resolve`: A string indicating the package name of the module provider or the path to it relative to the `src` directory.
-- `id`: A string indicating the provider's unique name or ID.
-- `options`: An optional object of the module provider's options.
-
-
-# Payment
-
-In this document, you’ll learn what a payment is and how it's created, captured, and refunded.
-
-## What's a Payment?
-
-When a payment session is authorized, a payment, represented by the [Payment data model](https://docs.medusajs.com/references/payment/models/Payment/index.html.md), is created. This payment can later be captured or refunded.
-
-A payment carries many of the data and relations of a payment session:
-
-- It belongs to the same payment collection.
-- It’s associated with the same payment provider, which handles further payment processing.
-- It stores the payment session’s `data` property in its `data` property, as it’s still useful for the payment provider’s processing.
-
-***
-
-## Capture Payments
-
-When a payment is captured, a capture, represented by the [Capture data model](https://docs.medusajs.com/references/payment/models/Capture/index.html.md), is created. It holds details related to the capture, such as the amount, the capture date, and more.
-
-The payment can also be captured incrementally, each time a capture record is created for that amount.
-
-
-
-***
-
-## Refund Payments
-
-When a payment is refunded, a refund, represented by the [Refund data model](https://docs.medusajs.com/references/payment/models/Refund/index.html.md), is created. It holds details related to the refund, such as the amount, refund date, and more.
-
-A payment can be refunded multiple times, and each time a refund record is created.
-
-
-
-
-# Payment Collection
-
-In this document, you’ll learn what a payment collection is and how the Medusa application uses it with the Cart Module.
-
-## What's a Payment Collection?
-
-A payment collection stores payment details related to a resource, such as a cart or an order. It’s represented by the [PaymentCollection data model](https://docs.medusajs.com/references/payment/models/PaymentCollection/index.html.md).
-
-Every purchase or request for payment starts with a payment collection. The collection holds details necessary to complete the payment, including:
-
-- The [payment sessions](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-session/index.html.md) that represents the payment amount to authorize.
-- The [payments](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment/index.html.md) that are created when a payment session is authorized. They can be captured and refunded.
-- The [payment providers](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-provider/index.html.md) that handle the processing of each payment session, including the authorization, capture, and refund.
-
-***
-
-## Multiple Payments
-
-The payment collection supports multiple payment sessions and payments.
-
-You can use this to accept payments in increments or split payments across payment providers.
-
-
-
-***
-
-## Usage with the Cart Module
-
-The Cart Module provides cart management features. However, it doesn’t provide any features related to accepting payment.
-
-During checkout, the Medusa application links a cart to a payment collection, which will be used for further payment processing.
-
-It also implements the payment flow during checkout as explained in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-flow/index.html.md).
-
-
-
-
-# Accept Payment Flow
-
-In this document, you’ll learn how to implement an accept-payment flow using workflows or the Payment Module's main service.
-
-It's highly recommended to use Medusa's workflows to implement this flow. Use the Payment Module's main service for more complex cases.
-
-For a guide on how to implement this flow in the storefront, check out [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/checkout/payment/index.html.md).
-
-## Flow Overview
-
-
-
-***
-
-## 1. Create a Payment Collection
-
-A payment collection holds all details related to a resource’s payment operations. So, you start off by creating a payment collection.
-
-For example:
-
-### Using Workflow
-
-```ts
-import { createPaymentCollectionForCartWorkflow } from "@medusajs/medusa/core-flows"
-
-// ...
-
-await createPaymentCollectionForCartWorkflow(req.scope)
- .run({
- input: {
- cart_id: "cart_123",
- },
- })
-```
-
-### Using Service
-
-```ts
-const paymentCollection =
- await paymentModuleService.createPaymentCollections({
- currency_code: "usd",
- amount: 5000,
- })
-```
-
-***
-
-## 2. Create Payment Sessions
-
-The payment collection has one or more payment sessions, each being a payment amount to be authorized by a payment provider.
-
-So, after creating the payment collection, create at least one payment session for a provider.
-
-For example:
-
-### Using Workflow
-
-```ts
-import { createPaymentSessionsWorkflow } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { result: paymentSesion } = await createPaymentSessionsWorkflow(req.scope)
- .run({
- input: {
- payment_collection_id: "paycol_123",
- provider_id: "stripe",
- },
- })
-```
-
-### Using Service
-
-```ts
-const paymentSession =
- await paymentModuleService.createPaymentSession(
- paymentCollection.id,
- {
- provider_id: "stripe",
- currency_code: "usd",
- amount: 5000,
- data: {
- // any necessary data for the
- // payment provider
- },
- }
- )
-```
-
-***
-
-## 3. Authorize Payment Session
-
-Once the customer chooses a payment session, start the authorization process. This may involve some action performed by the third-party payment provider, such as entering a 3DS code.
-
-For example:
-
-### Using Step
-
-```ts
-import { authorizePaymentSessionStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-authorizePaymentSessionStep({
- id: "payses_123",
- context: {},
-})
-```
-
-### Using Service
-
-```ts
-const payment = authorizePaymentSessionStep({
- id: "payses_123",
- context: {},
-})
-```
-
-When the payment authorization is successful, a payment is created and returned.
-
-### Handling Additional Action
-
-If you used the `authorizePaymentSessionStep`, you don't need to implement this logic as it's implemented in the step.
-
-If the payment authorization isn’t successful, whether because it requires additional action or for another reason, the method updates the payment session with the new status and throws an error.
-
-In that case, you can catch that error and, if the session's `status` property is `requires_more`, handle the additional action, then retry the authorization.
-
-For example:
-
-```ts
-try {
- const payment =
- await paymentModuleService.authorizePaymentSession(
- paymentSession.id,
- {}
- )
-} catch (e) {
- // retrieve the payment session again
- const updatedPaymentSession = (
- await paymentModuleService.listPaymentSessions({
- id: [paymentSession.id],
- })
- )[0]
-
- if (updatedPaymentSession.status === "requires_more") {
- // TODO perform required action
- // TODO authorize payment again.
- }
-}
-```
-
-***
-
-## 4. Payment Flow Complete
-
-The payment flow is complete once the payment session is authorized and the payment is created.
-
-You can then:
-
-- Capture the payment either using the [capturePaymentWorkflow](https://docs.medusajs.com/references/medusa-workflows/capturePaymentWorkflow/index.html.md) or [capturePayment method](https://docs.medusajs.com/references/payment/capturePayment/index.html.md).
-- Refund captured amounts using the [refundPaymentWorkflow](https://docs.medusajs.com/references/medusa-workflows/refundPaymentWorkflow/index.html.md) or [refundPayment method](https://docs.medusajs.com/references/payment/refundPayment/index.html.md).
-
-Some payment providers allow capturing the payment automatically once it’s authorized. In that case, you don’t need to do it manually.
-
-
-# Payment Module Provider
-
-In this document, you’ll learn what a payment module provider is.
-
-Refer to this [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/regions/index.html.md) to learn how to manage the payment providers available in a region using the dashboard.
-
-## What's a Payment Module Provider?
-
-A payment module provider registers a payment provider that handles payment processing in the Medusa application. It integrates third-party payment providers, such as Stripe.
-
-To authorize a payment amount with a payment provider, a payment session is created and associated with that payment provider. The payment provider is then used to handle the authorization.
-
-After the payment session is authorized, the payment provider is associated with the resulting payment and handles its payment processing, such as to capture or refund payment.
-
-### List of Payment Module Providers
-
-- [Stripe](https://docs.medusajs.com/commerce-modules/payment/payment-provider/stripe/index.html.md)
-
-***
-
-## System Payment Provider
-
-The Payment Module provides a `system` payment provider that acts as a placeholder payment provider.
-
-It doesn’t handle payment processing and delegates that to the merchant. It acts similarly to a cash-on-delivery (COD) payment method.
-
-***
-
-## How are Payment Providers Created?
-
-A payment provider is a module whose main service extends the `AbstractPaymentProvider` imported from `@medusajs/framework/utils`.
-
-Refer to [this guide](https://docs.medusajs.com/references/payment/provider/index.html.md) on how to create a payment provider for the Payment Module.
-
-***
-
-## Configure Payment Providers
-
-The Payment Module accepts a `providers` option that allows you to register providers in your application.
-
-Learn more about this option in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/module-options#providers/index.html.md).
-
-***
-
-## PaymentProvider Data Model
-
-When the Medusa application starts and registers the payment providers, it also creates a record of the `PaymentProvider` data model if none exists.
-
-This data model is used to reference a payment provider and determine whether it’s installed in the application.
-
-
-# Webhook Events
-
-In this document, you’ll learn how the Payment Module supports listening to webhook events.
-
-## What's a Webhook Event?
-
-A webhook event is sent from a third-party payment provider to your application. It indicates a change in a payment’s status.
-
-This is useful in many cases such as when a payment is being processed asynchronously or when a request is interrupted and the payment provider is sending details on the process later.
-
-***
-
-## getWebhookActionAndData Method
-
-The Payment Module’s main service has a [getWebhookActionAndData method](https://docs.medusajs.com/references/payment/getWebhookActionAndData/index.html.md) used to handle incoming webhook events from third-party payment services. The method delegates the handling to the associated payment provider, which returns the event's details.
-
-Medusa implements a webhook listener route at the `/hooks/payment/[identifier]_[provider]` API route, where:
-
-- `[identifier]` is the `identifier` static property defined in the payment provider. For example, `stripe`.
-- `[provider]` is the ID of the provider. For example, `stripe`.
-
-For example, when integrating basic Stripe payments with the [Stripe Module Provider](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-provider/stripe/index.html.md), the webhook listener route is `/hooks/payment/stripe_stripe`. If you're integrating Stripe's Bancontact payments, the webhook listener route is `/hooks/payment/stripe-bancontact_stripe`.
-
-Use that webhook listener in your third-party payment provider's configurations.
-
-
-
-If the event's details indicate that the payment should be authorized, then the [authorizePaymentSession method of the main service](https://docs.medusajs.com/references/payment/authorizePaymentSession/index.html.md) is executed on the specified payment session.
-
-If the event's details indicate that the payment should be captured, then the [capturePayment method of the main service](https://docs.medusajs.com/references/payment/capturePayment/index.html.md) is executed on the payment of the specified payment session.
-
-### Actions After Webhook Payment Processing
-
-After the payment webhook actions are processed and the payment is authorized or captured, the Medusa application completes the cart associated with the payment's collection if it's not completed yet.
-
-
-# Payment Session
-
-In this document, you’ll learn what a payment session is.
-
-## What's a Payment Session?
-
-A payment session, represented by the [PaymentSession data model](https://docs.medusajs.com/references/payment/models/PaymentSession/index.html.md), is a payment amount to be authorized. It’s associated with a payment provider that handles authorizing it.
-
-A payment collection can have multiple payment sessions. Using this feature, you can implement payment in installments or payments using multiple providers.
-
-
-
-***
-
-## data Property
-
-Payment providers may need additional data to process the payment later. The `PaymentSession` data model has a `data` property used to store that data.
-
-For example, the customer's ID in Stripe is stored in the `data` property.
-
-***
-
-## Payment Session Status
-
-The `status` property of a payment session indicates its current status. Its value can be:
-
-- `pending`: The payment session is awaiting authorization.
-- `requires_more`: The payment session requires an action before it’s authorized. For example, to enter a 3DS code.
-- `authorized`: The payment session is authorized.
-- `error`: An error occurred while authorizing the payment.
-- `canceled`: The authorization of the payment session has been canceled.
-
-
# Pricing Concepts
In this document, you’ll learn about the main concepts in the Pricing Module.
@@ -25740,131 +25747,6 @@ The `rules_count` property of a `PriceList` indicates how many rules are applied

-# Tax-Inclusive Pricing
-
-In this document, you’ll learn about tax-inclusive pricing and how it's used when calculating prices.
-
-## What is Tax-Inclusive Pricing?
-
-A tax-inclusive price is a price of a resource that includes taxes. Medusa calculates the tax amount from the price rather than adds the amount to it.
-
-For example, if a product’s price is $50, the tax rate is 2%, and tax-inclusive pricing is enabled, then the product's price is $49, and the applied tax amount is $1.
-
-***
-
-## How is Tax-Inclusive Pricing Set?
-
-The [PricePreference data model](https://docs.medusajs.com/references/pricing/models/PricePreference/index.html.md) holds the tax-inclusive setting for a context. It has two properties that indicate the context:
-
-- `attribute`: The name of the attribute to compare against. For example, `region_id` or `currency_code`.
-- `value`: The attribute’s value. For example, `reg_123` or `usd`.
-
-Only `region_id` and `currency_code` are supported as an `attribute` at the moment.
-
-The `is_tax_inclusive` property indicates whether tax-inclusivity is enabled in the specified context.
-
-For example:
-
-```json
-{
- "attribute": "currency_code",
- "value": "USD",
- "is_tax_inclusive": true,
-}
-```
-
-In this example, tax-inclusivity is enabled for the `USD` currency code.
-
-***
-
-## Tax-Inclusive Pricing in Price Calculation
-
-### Tax Context
-
-As mentioned in the [Price Calculation documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/pricing/price-calculation#calculation-context/index.html.md), The `calculatePrices` method accepts as a parameter a calculation context.
-
-To get accurate tax results, pass the `region_id` and / or `currency_code` in the calculation context.
-
-### Returned Tax Properties
-
-The `calculatePrices` method returns two properties related to tax-inclusivity:
-
-Learn more about the returned properties in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/pricing/price-calculation#returned-price-object/index.html.md).
-
-- `is_calculated_price_tax_inclusive`: Whether the selected `calculated_price` is tax-inclusive.
-- `is_original_price_tax_inclusive` : Whether the selected `original_price` is tax-inclusive.
-
-A price is considered tax-inclusive if:
-
-1. It belongs to the region or currency code specified in the calculation context;
-2. and the region or currency code has a price preference with `is_tax_inclusive` enabled.
-
-### Tax Context Precedence
-
-A region’s price preference’s `is_tax_inclusive`'s value takes higher precedence in determining whether a price is tax-inclusive if:
-
-- both the `region_id` and `currency_code` are provided in the calculation context;
-- the selected price belongs to the region;
-- and the region has a price preference
-
-
-# Links between Currency Module and Other Modules
-
-This document showcases the module links defined between the Currency Module and other commerce modules.
-
-## Summary
-
-The Currency Module has the following links to other modules:
-
-Read-only links are used to query data across modules, but the relations aren't stored in a pivot table in the database.
-
-|First Data Model|Second Data Model|Type|Description|
-|---|---|---|---|
-| in ||Read-only||
-
-***
-
-## Store Module
-
-The Store Module has a `Currency` data model that stores the supported currencies of a store. However, these currencies don't hold all the details of a currency, such as its name or symbol.
-
-Instead, Medusa defines a read-only link between the [Store Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/store/index.html.md)'s `Currency` data model and the Currency Module's `Currency` data model. Because the link is read-only from the `Store`'s side, you can only retrieve the details of a store's supported currencies, and not the other way around.
-
-### Retrieve with Query
-
-To retrieve the details of a store's currencies with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `supported_currencies.currency.*` in `fields`:
-
-### query.graph
-
-```ts
-const { data: stores } = await query.graph({
- entity: "store",
- fields: [
- "supported_currencies.currency.*",
- ],
-})
-
-// stores.supported_currencies
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: stores } = useQueryGraphStep({
- entity: "store",
- fields: [
- "supported_currencies.currency.*",
- ],
-})
-
-// stores.supported_currencies
-```
-
-
# Links between Product Module and Other Modules
This document showcases the module links defined between the Product Module and other commerce modules.
@@ -26428,6 +26310,883 @@ The following guides provide more details on inventory management in the Medusa
- [Storefront guide: how to retrieve a product variant's inventory details](https://docs.medusajs.com/resources/storefront-development/products/inventory/index.html.md).
+# Account Holders and Saved Payment Methods
+
+In this documentation, you'll learn about account holders, and how they're used to save payment methods in third-party payment providers.
+
+Account holders are available starting from Medusa `v2.5.0`.
+
+## What's an Account Holder?
+
+An account holder represents a customer that can have saved payment methods in a third-party service. It's represented by the `AccountHolder` data model.
+
+It holds fields retrieved from the third-party provider, such as:
+
+- `external_id`: The ID of the equivalent customer or account holder in the third-party provider.
+- `data`: Data returned by the payment provider when the account holder is created.
+
+A payment provider that supports saving payment methods for customers would create the equivalent of an account holder in the third-party provider. Then, whenever a payment method is saved, it would be saved under the account holder in the third-party provider.
+
+### Relation between Account Holder and Customer
+
+The Medusa application creates a link between the [Customer](https://docs.medusajs.com/references/customer/models/Customer/index.html.md) data model of the [Customer Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/customer/index.html.md) and the `AccountHolder` data model of the Payment Module.
+
+This link indicates that a customer can have more than one account holder, each representing saved payment methods in different payment providers.
+
+Learn more about this link in the [Link to Other Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/links-to-other-modules/index.html.md) guide.
+
+***
+
+## Save Payment Methods
+
+If a payment provider supports saving payment methods for a customer, they must implement the following methods:
+
+- `createAccountHolder`: Creates an account holder in the payment provider. The Payment Module uses this method before creating the account holder in Medusa, and uses the returned data to set fields like `external_id` and `data` in the created `AccountHolder` record.
+- `deleteAccountHolder`: Deletes an account holder in the payment provider. The Payment Module uses this method when an account holder is deleted in Medusa.
+- `savePaymentMethod`: Saves a payment method for an account holder in the payment provider.
+- `listPaymentMethods`: Lists saved payment methods in the third-party service for an account holder. This is useful when displaying the customer's saved payment methods in the storefront.
+
+Learn more about implementing these methods in the [Create Payment Provider guide](https://docs.medusajs.com/references/payment/provider/index.html.md).
+
+***
+
+## Account Holder in Medusa Payment Flows
+
+In the Medusa application, when a payment session is created for a registered customer, the Medusa application uses the Payment Module to create an account holder for the customer.
+
+Consequently, the Payment Module uses the payment provider to create an account holder in the third-party service, then creates the account holder in Medusa.
+
+This flow is only supported if the chosen payment provider has implemented the necessary [save payment methods](#save-payment-methods).
+
+
+# Links between Payment Module and Other Modules
+
+This document showcases the module links defined between the Payment Module and other commerce modules.
+
+## Summary
+
+The Payment Module has the following links to other modules:
+
+|First Data Model|Second Data Model|Type|Description|
+|---|---|---|---|
+| in ||Stored||
+| in ||Stored||
+| in ||Stored||
+| in ||Stored||
+| in ||Stored||
+| in ||Stored||
+
+***
+
+## Cart Module
+
+The Cart Module provides cart-related features, but not payment processing.
+
+Medusa defines a link between the `Cart` and `PaymentCollection` data models. A cart has a payment collection which holds all the authorized payment sessions and payments made related to the cart.
+
+Learn more about this relation in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-collection#usage-with-the-cart-module/index.html.md).
+
+### Retrieve with Query
+
+To retrieve the cart associated with the payment collection with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `cart.*` in `fields`:
+
+### query.graph
+
+```ts
+const { data: paymentCollections } = await query.graph({
+ entity: "payment_collection",
+ fields: [
+ "cart.*",
+ ],
+})
+
+// paymentCollections.cart
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: paymentCollections } = useQueryGraphStep({
+ entity: "payment_collection",
+ fields: [
+ "cart.*",
+ ],
+})
+
+// paymentCollections.cart
+```
+
+### Manage with Link
+
+To manage the payment collection of a cart, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
+
+### link.create
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await link.create({
+ [Modules.CART]: {
+ cart_id: "cart_123",
+ },
+ [Modules.PAYMENT]: {
+ payment_collection_id: "paycol_123",
+ },
+})
+```
+
+### createRemoteLinkStep
+
+```ts
+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+createRemoteLinkStep({
+ [Modules.CART]: {
+ cart_id: "cart_123",
+ },
+ [Modules.PAYMENT]: {
+ payment_collection_id: "paycol_123",
+ },
+})
+```
+
+***
+
+## Customer Module
+
+Medusa defines a link between the `Customer` and `AccountHolder` data models, allowing payment providers to save payment methods for a customer, if the payment provider supports it.
+
+This link is available starting from Medusa `v2.5.0`.
+
+### Retrieve with Query
+
+To retrieve the customer associated with an account holder with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `customer.*` in `fields`:
+
+### query.graph
+
+```ts
+const { data: accountHolders } = await query.graph({
+ entity: "account_holder",
+ fields: [
+ "customer.*",
+ ],
+})
+
+// accountHolders.customer
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: accountHolders } = useQueryGraphStep({
+ entity: "account_holder",
+ fields: [
+ "customer.*",
+ ],
+})
+
+// accountHolders.customer
+```
+
+### Manage with Link
+
+To manage the account holders of a customer, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
+
+### link.create
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await link.create({
+ [Modules.CUSTOMER]: {
+ customer_id: "cus_123",
+ },
+ [Modules.PAYMENT]: {
+ account_holder_id: "acchld_123",
+ },
+})
+```
+
+### createRemoteLinkStep
+
+```ts
+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+createRemoteLinkStep({
+ [Modules.CUSTOMER]: {
+ customer_id: "cus_123",
+ },
+ [Modules.PAYMENT]: {
+ account_holder_id: "acchld_123",
+ },
+})
+```
+
+***
+
+## Order Module
+
+An order's payment details are stored in a payment collection. This also applies for claims and exchanges.
+
+So, Medusa defines links between the `PaymentCollection` data model and the `Order`, `OrderClaim`, and `OrderExchange` data models.
+
+
+
+### Retrieve with Query
+
+To retrieve the order of a payment collection with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `order.*` in `fields`:
+
+### query.graph
+
+```ts
+const { data: paymentCollections } = await query.graph({
+ entity: "payment_collection",
+ fields: [
+ "order.*",
+ ],
+})
+
+// paymentCollections.order
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: paymentCollections } = useQueryGraphStep({
+ entity: "payment_collection",
+ fields: [
+ "order.*",
+ ],
+})
+
+// paymentCollections.order
+```
+
+### Manage with Link
+
+To manage the payment collections of an order, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
+
+### link.create
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await link.create({
+ [Modules.ORDER]: {
+ order_id: "order_123",
+ },
+ [Modules.PAYMENT]: {
+ payment_collection_id: "paycol_123",
+ },
+})
+```
+
+### createRemoteLinkStep
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+createRemoteLinkStep({
+ [Modules.ORDER]: {
+ order_id: "order_123",
+ },
+ [Modules.PAYMENT]: {
+ payment_collection_id: "paycol_123",
+ },
+})
+```
+
+***
+
+## Region Module
+
+You can specify for each region which payment providers are available. The Medusa application defines a link between the `PaymentProvider` and the `Region` data models.
+
+
+
+This increases the flexibility of your store. For example, you only show during checkout the payment providers associated with the cart's region.
+
+### Retrieve with Query
+
+To retrieve the regions of a payment provider with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `regions.*` in `fields`:
+
+### query.graph
+
+```ts
+const { data: paymentProviders } = await query.graph({
+ entity: "payment_provider",
+ fields: [
+ "regions.*",
+ ],
+})
+
+// paymentProviders.regions
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: paymentProviders } = useQueryGraphStep({
+ entity: "payment_provider",
+ fields: [
+ "regions.*",
+ ],
+})
+
+// paymentProviders.regions
+```
+
+### Manage with Link
+
+To manage the payment providers in a region, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
+
+### link.create
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await link.create({
+ [Modules.REGION]: {
+ region_id: "reg_123",
+ },
+ [Modules.PAYMENT]: {
+ payment_provider_id: "pp_stripe_stripe",
+ },
+})
+```
+
+### createRemoteLinkStep
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+createRemoteLinkStep({
+ [Modules.REGION]: {
+ region_id: "reg_123",
+ },
+ [Modules.PAYMENT]: {
+ payment_provider_id: "pp_stripe_stripe",
+ },
+})
+```
+
+
+# Payment Module Options
+
+In this document, you'll learn about the options of the Payment Module.
+
+## All Module Options
+
+|Option|Description|Required|Default|
+|---|---|---|---|---|---|---|
+|\`webhook\_delay\`|A number indicating the delay in milliseconds before processing a webhook event.|No|\`5000\`|
+|\`webhook\_retries\`|The number of times to retry the webhook event processing in case of an error.|No|\`3\`|
+|\`providers\`|An array of payment providers to install and register. Learn more |No|-|
+
+***
+
+## providers Option
+
+The `providers` option is an array of payment module providers.
+
+When the Medusa application starts, these providers are registered and can be used to process payments.
+
+For example:
+
+```ts title="medusa-config.ts"
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+module.exports = defineConfig({
+ // ...
+ modules: [
+ {
+ resolve: "@medusajs/medusa/payment",
+ options: {
+ providers: [
+ {
+ resolve: "@medusajs/medusa/payment-stripe",
+ id: "stripe",
+ options: {
+ // ...
+ },
+ },
+ ],
+ },
+ },
+ ],
+})
+```
+
+The `providers` option is an array of objects that accept the following properties:
+
+- `resolve`: A string indicating the package name of the module provider or the path to it relative to the `src` directory.
+- `id`: A string indicating the provider's unique name or ID.
+- `options`: An optional object of the module provider's options.
+
+
+# Payment
+
+In this document, you’ll learn what a payment is and how it's created, captured, and refunded.
+
+## What's a Payment?
+
+When a payment session is authorized, a payment, represented by the [Payment data model](https://docs.medusajs.com/references/payment/models/Payment/index.html.md), is created. This payment can later be captured or refunded.
+
+A payment carries many of the data and relations of a payment session:
+
+- It belongs to the same payment collection.
+- It’s associated with the same payment provider, which handles further payment processing.
+- It stores the payment session’s `data` property in its `data` property, as it’s still useful for the payment provider’s processing.
+
+***
+
+## Capture Payments
+
+When a payment is captured, a capture, represented by the [Capture data model](https://docs.medusajs.com/references/payment/models/Capture/index.html.md), is created. It holds details related to the capture, such as the amount, the capture date, and more.
+
+The payment can also be captured incrementally, each time a capture record is created for that amount.
+
+
+
+***
+
+## Refund Payments
+
+When a payment is refunded, a refund, represented by the [Refund data model](https://docs.medusajs.com/references/payment/models/Refund/index.html.md), is created. It holds details related to the refund, such as the amount, refund date, and more.
+
+A payment can be refunded multiple times, and each time a refund record is created.
+
+
+
+
+# Tax-Inclusive Pricing
+
+In this document, you’ll learn about tax-inclusive pricing and how it's used when calculating prices.
+
+## What is Tax-Inclusive Pricing?
+
+A tax-inclusive price is a price of a resource that includes taxes. Medusa calculates the tax amount from the price rather than adds the amount to it.
+
+For example, if a product’s price is $50, the tax rate is 2%, and tax-inclusive pricing is enabled, then the product's price is $49, and the applied tax amount is $1.
+
+***
+
+## How is Tax-Inclusive Pricing Set?
+
+The [PricePreference data model](https://docs.medusajs.com/references/pricing/models/PricePreference/index.html.md) holds the tax-inclusive setting for a context. It has two properties that indicate the context:
+
+- `attribute`: The name of the attribute to compare against. For example, `region_id` or `currency_code`.
+- `value`: The attribute’s value. For example, `reg_123` or `usd`.
+
+Only `region_id` and `currency_code` are supported as an `attribute` at the moment.
+
+The `is_tax_inclusive` property indicates whether tax-inclusivity is enabled in the specified context.
+
+For example:
+
+```json
+{
+ "attribute": "currency_code",
+ "value": "USD",
+ "is_tax_inclusive": true,
+}
+```
+
+In this example, tax-inclusivity is enabled for the `USD` currency code.
+
+***
+
+## Tax-Inclusive Pricing in Price Calculation
+
+### Tax Context
+
+As mentioned in the [Price Calculation documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/pricing/price-calculation#calculation-context/index.html.md), The `calculatePrices` method accepts as a parameter a calculation context.
+
+To get accurate tax results, pass the `region_id` and / or `currency_code` in the calculation context.
+
+### Returned Tax Properties
+
+The `calculatePrices` method returns two properties related to tax-inclusivity:
+
+Learn more about the returned properties in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/pricing/price-calculation#returned-price-object/index.html.md).
+
+- `is_calculated_price_tax_inclusive`: Whether the selected `calculated_price` is tax-inclusive.
+- `is_original_price_tax_inclusive` : Whether the selected `original_price` is tax-inclusive.
+
+A price is considered tax-inclusive if:
+
+1. It belongs to the region or currency code specified in the calculation context;
+2. and the region or currency code has a price preference with `is_tax_inclusive` enabled.
+
+### Tax Context Precedence
+
+A region’s price preference’s `is_tax_inclusive`'s value takes higher precedence in determining whether a price is tax-inclusive if:
+
+- both the `region_id` and `currency_code` are provided in the calculation context;
+- the selected price belongs to the region;
+- and the region has a price preference
+
+
+# Payment Collection
+
+In this document, you’ll learn what a payment collection is and how the Medusa application uses it with the Cart Module.
+
+## What's a Payment Collection?
+
+A payment collection stores payment details related to a resource, such as a cart or an order. It’s represented by the [PaymentCollection data model](https://docs.medusajs.com/references/payment/models/PaymentCollection/index.html.md).
+
+Every purchase or request for payment starts with a payment collection. The collection holds details necessary to complete the payment, including:
+
+- The [payment sessions](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-session/index.html.md) that represents the payment amount to authorize.
+- The [payments](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment/index.html.md) that are created when a payment session is authorized. They can be captured and refunded.
+- The [payment providers](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-provider/index.html.md) that handle the processing of each payment session, including the authorization, capture, and refund.
+
+***
+
+## Multiple Payments
+
+The payment collection supports multiple payment sessions and payments.
+
+You can use this to accept payments in increments or split payments across payment providers.
+
+
+
+***
+
+## Usage with the Cart Module
+
+The Cart Module provides cart management features. However, it doesn’t provide any features related to accepting payment.
+
+During checkout, the Medusa application links a cart to a payment collection, which will be used for further payment processing.
+
+It also implements the payment flow during checkout as explained in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-flow/index.html.md).
+
+
+
+
+# Accept Payment Flow
+
+In this document, you’ll learn how to implement an accept-payment flow using workflows or the Payment Module's main service.
+
+It's highly recommended to use Medusa's workflows to implement this flow. Use the Payment Module's main service for more complex cases.
+
+For a guide on how to implement this flow in the storefront, check out [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/checkout/payment/index.html.md).
+
+## Flow Overview
+
+
+
+***
+
+## 1. Create a Payment Collection
+
+A payment collection holds all details related to a resource’s payment operations. So, you start off by creating a payment collection.
+
+For example:
+
+### Using Workflow
+
+```ts
+import { createPaymentCollectionForCartWorkflow } from "@medusajs/medusa/core-flows"
+
+// ...
+
+await createPaymentCollectionForCartWorkflow(req.scope)
+ .run({
+ input: {
+ cart_id: "cart_123",
+ },
+ })
+```
+
+### Using Service
+
+```ts
+const paymentCollection =
+ await paymentModuleService.createPaymentCollections({
+ currency_code: "usd",
+ amount: 5000,
+ })
+```
+
+***
+
+## 2. Create Payment Sessions
+
+The payment collection has one or more payment sessions, each being a payment amount to be authorized by a payment provider.
+
+So, after creating the payment collection, create at least one payment session for a provider.
+
+For example:
+
+### Using Workflow
+
+```ts
+import { createPaymentSessionsWorkflow } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { result: paymentSesion } = await createPaymentSessionsWorkflow(req.scope)
+ .run({
+ input: {
+ payment_collection_id: "paycol_123",
+ provider_id: "stripe",
+ },
+ })
+```
+
+### Using Service
+
+```ts
+const paymentSession =
+ await paymentModuleService.createPaymentSession(
+ paymentCollection.id,
+ {
+ provider_id: "stripe",
+ currency_code: "usd",
+ amount: 5000,
+ data: {
+ // any necessary data for the
+ // payment provider
+ },
+ }
+ )
+```
+
+***
+
+## 3. Authorize Payment Session
+
+Once the customer chooses a payment session, start the authorization process. This may involve some action performed by the third-party payment provider, such as entering a 3DS code.
+
+For example:
+
+### Using Step
+
+```ts
+import { authorizePaymentSessionStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+authorizePaymentSessionStep({
+ id: "payses_123",
+ context: {},
+})
+```
+
+### Using Service
+
+```ts
+const payment = authorizePaymentSessionStep({
+ id: "payses_123",
+ context: {},
+})
+```
+
+When the payment authorization is successful, a payment is created and returned.
+
+### Handling Additional Action
+
+If you used the `authorizePaymentSessionStep`, you don't need to implement this logic as it's implemented in the step.
+
+If the payment authorization isn’t successful, whether because it requires additional action or for another reason, the method updates the payment session with the new status and throws an error.
+
+In that case, you can catch that error and, if the session's `status` property is `requires_more`, handle the additional action, then retry the authorization.
+
+For example:
+
+```ts
+try {
+ const payment =
+ await paymentModuleService.authorizePaymentSession(
+ paymentSession.id,
+ {}
+ )
+} catch (e) {
+ // retrieve the payment session again
+ const updatedPaymentSession = (
+ await paymentModuleService.listPaymentSessions({
+ id: [paymentSession.id],
+ })
+ )[0]
+
+ if (updatedPaymentSession.status === "requires_more") {
+ // TODO perform required action
+ // TODO authorize payment again.
+ }
+}
+```
+
+***
+
+## 4. Payment Flow Complete
+
+The payment flow is complete once the payment session is authorized and the payment is created.
+
+You can then:
+
+- Capture the payment either using the [capturePaymentWorkflow](https://docs.medusajs.com/references/medusa-workflows/capturePaymentWorkflow/index.html.md) or [capturePayment method](https://docs.medusajs.com/references/payment/capturePayment/index.html.md).
+- Refund captured amounts using the [refundPaymentWorkflow](https://docs.medusajs.com/references/medusa-workflows/refundPaymentWorkflow/index.html.md) or [refundPayment method](https://docs.medusajs.com/references/payment/refundPayment/index.html.md).
+
+Some payment providers allow capturing the payment automatically once it’s authorized. In that case, you don’t need to do it manually.
+
+
+# Payment Module Provider
+
+In this document, you’ll learn what a payment module provider is.
+
+Refer to this [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/regions/index.html.md) to learn how to manage the payment providers available in a region using the dashboard.
+
+## What's a Payment Module Provider?
+
+A payment module provider registers a payment provider that handles payment processing in the Medusa application. It integrates third-party payment providers, such as Stripe.
+
+To authorize a payment amount with a payment provider, a payment session is created and associated with that payment provider. The payment provider is then used to handle the authorization.
+
+After the payment session is authorized, the payment provider is associated with the resulting payment and handles its payment processing, such as to capture or refund payment.
+
+### List of Payment Module Providers
+
+- [Stripe](https://docs.medusajs.com/commerce-modules/payment/payment-provider/stripe/index.html.md)
+
+***
+
+## System Payment Provider
+
+The Payment Module provides a `system` payment provider that acts as a placeholder payment provider.
+
+It doesn’t handle payment processing and delegates that to the merchant. It acts similarly to a cash-on-delivery (COD) payment method.
+
+***
+
+## How are Payment Providers Created?
+
+A payment provider is a module whose main service extends the `AbstractPaymentProvider` imported from `@medusajs/framework/utils`.
+
+Refer to [this guide](https://docs.medusajs.com/references/payment/provider/index.html.md) on how to create a payment provider for the Payment Module.
+
+***
+
+## Configure Payment Providers
+
+The Payment Module accepts a `providers` option that allows you to register providers in your application.
+
+Learn more about this option in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/module-options#providers/index.html.md).
+
+***
+
+## PaymentProvider Data Model
+
+When the Medusa application starts and registers the payment providers, it also creates a record of the `PaymentProvider` data model if none exists.
+
+This data model is used to reference a payment provider and determine whether it’s installed in the application.
+
+
+# Payment Session
+
+In this document, you’ll learn what a payment session is.
+
+## What's a Payment Session?
+
+A payment session, represented by the [PaymentSession data model](https://docs.medusajs.com/references/payment/models/PaymentSession/index.html.md), is a payment amount to be authorized. It’s associated with a payment provider that handles authorizing it.
+
+A payment collection can have multiple payment sessions. Using this feature, you can implement payment in installments or payments using multiple providers.
+
+
+
+***
+
+## data Property
+
+Payment providers may need additional data to process the payment later. The `PaymentSession` data model has a `data` property used to store that data.
+
+For example, the customer's ID in Stripe is stored in the `data` property.
+
+***
+
+## Payment Session Status
+
+The `status` property of a payment session indicates its current status. Its value can be:
+
+- `pending`: The payment session is awaiting authorization.
+- `requires_more`: The payment session requires an action before it’s authorized. For example, to enter a 3DS code.
+- `authorized`: The payment session is authorized.
+- `error`: An error occurred while authorizing the payment.
+- `canceled`: The authorization of the payment session has been canceled.
+
+
+# Webhook Events
+
+In this document, you’ll learn how the Payment Module supports listening to webhook events.
+
+## What's a Webhook Event?
+
+A webhook event is sent from a third-party payment provider to your application. It indicates a change in a payment’s status.
+
+This is useful in many cases such as when a payment is being processed asynchronously or when a request is interrupted and the payment provider is sending details on the process later.
+
+***
+
+## getWebhookActionAndData Method
+
+The Payment Module’s main service has a [getWebhookActionAndData method](https://docs.medusajs.com/references/payment/getWebhookActionAndData/index.html.md) used to handle incoming webhook events from third-party payment services. The method delegates the handling to the associated payment provider, which returns the event's details.
+
+Medusa implements a webhook listener route at the `/hooks/payment/[identifier]_[provider]` API route, where:
+
+- `[identifier]` is the `identifier` static property defined in the payment provider. For example, `stripe`.
+- `[provider]` is the ID of the provider. For example, `stripe`.
+
+For example, when integrating basic Stripe payments with the [Stripe Module Provider](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/payment/payment-provider/stripe/index.html.md), the webhook listener route is `/hooks/payment/stripe_stripe`. If you're integrating Stripe's Bancontact payments, the webhook listener route is `/hooks/payment/stripe-bancontact_stripe`.
+
+Use that webhook listener in your third-party payment provider's configurations.
+
+
+
+If the event's details indicate that the payment should be authorized, then the [authorizePaymentSession method of the main service](https://docs.medusajs.com/references/payment/authorizePaymentSession/index.html.md) is executed on the specified payment session.
+
+If the event's details indicate that the payment should be captured, then the [capturePayment method of the main service](https://docs.medusajs.com/references/payment/capturePayment/index.html.md) is executed on the payment of the specified payment session.
+
+### Actions After Webhook Payment Processing
+
+After the payment webhook actions are processed and the payment is authorized or captured, the Medusa application completes the cart associated with the payment's collection if it's not completed yet.
+
+
# Promotion Actions
In this document, you’ll learn about promotion actions and how they’re computed using the [computeActions method](https://docs.medusajs.com/references/promotion/computeActions/index.html.md).
@@ -26539,6 +27298,43 @@ export interface CampaignBudgetExceededAction {
Refer to [this reference](https://docs.medusajs.com/references/promotion/interfaces/promotion.CampaignBudgetExceededAction/index.html.md) for details on the object’s properties.
+# Application Method
+
+In this document, you'll learn what an application method is.
+
+## What is an Application Method?
+
+The [ApplicationMethod data model](https://docs.medusajs.com/references/promotion/models/ApplicationMethod/index.html.md) defines how a promotion is applied:
+
+|Property|Purpose|
+|---|---|
+|\`type\`|Does the promotion discount a fixed amount or a percentage?|
+|\`target\_type\`|Is the promotion applied on a cart item, shipping method, or the entire order?|
+|\`allocation\`|Is the discounted amount applied on each item or split between the applicable items?|
+
+## Target Promotion Rules
+
+When the promotion is applied to a cart item or a shipping method, you can restrict which items/shipping methods the promotion is applied to.
+
+The `ApplicationMethod` data model has a collection of `PromotionRule` records to restrict which items or shipping methods the promotion applies to. The `target_rules` property represents this relation.
+
+
+
+In this example, the promotion is only applied on products in the cart having the SKU `SHIRT`.
+
+***
+
+## Buy Promotion Rules
+
+When the promotion’s type is `buyget`, you must specify the “buy X” condition. For example, a cart must have two shirts before the promotion can be applied.
+
+The application method has a collection of `PromotionRule` items to define the “buy X” rule. The `buy_rules` property represents this relation.
+
+
+
+In this example, the cart must have two products with the SKU `SHIRT` for the promotion to be applied.
+
+
# Promotion Concepts
In this document, you’ll learn about the main promotion and rule concepts in the Promotion Module.
@@ -26622,43 +27418,6 @@ There are two types of budgets:

-# Application Method
-
-In this document, you'll learn what an application method is.
-
-## What is an Application Method?
-
-The [ApplicationMethod data model](https://docs.medusajs.com/references/promotion/models/ApplicationMethod/index.html.md) defines how a promotion is applied:
-
-|Property|Purpose|
-|---|---|
-|\`type\`|Does the promotion discount a fixed amount or a percentage?|
-|\`target\_type\`|Is the promotion applied on a cart item, shipping method, or the entire order?|
-|\`allocation\`|Is the discounted amount applied on each item or split between the applicable items?|
-
-## Target Promotion Rules
-
-When the promotion is applied to a cart item or a shipping method, you can restrict which items/shipping methods the promotion is applied to.
-
-The `ApplicationMethod` data model has a collection of `PromotionRule` records to restrict which items or shipping methods the promotion applies to. The `target_rules` property represents this relation.
-
-
-
-In this example, the promotion is only applied on products in the cart having the SKU `SHIRT`.
-
-***
-
-## Buy Promotion Rules
-
-When the promotion’s type is `buyget`, you must specify the “buy X” condition. For example, a cart must have two shirts before the promotion can be applied.
-
-The application method has a collection of `PromotionRule` items to define the “buy X” rule. The `buy_rules` property represents this relation.
-
-
-
-In this example, the cart must have two products with the SKU `SHIRT` for the promotion to be applied.
-
-
# Links between Promotion Module and Other Modules
This document showcases the module links defined between the Promotion Module and other commerce modules.
@@ -27022,624 +27781,6 @@ createRemoteLinkStep({
```
-# Stock Location Concepts
-
-In this document, you’ll learn about the main concepts in the Stock Location Module.
-
-## Stock Location
-
-A stock location, represented by the `StockLocation` data model, represents a location where stock items are kept. For example, a warehouse.
-
-Medusa uses stock locations to provide inventory details, from the Inventory Module, per location.
-
-***
-
-## StockLocationAddress
-
-The `StockLocationAddress` data model belongs to the `StockLocation` data model. It provides more detailed information of the location, such as country code or street address.
-
-
-# Links between Stock Location Module and Other Modules
-
-This document showcases the module links defined between the Stock Location Module and other commerce modules.
-
-## Summary
-
-The Stock Location Module has the following links to other modules:
-
-Read-only links are used to query data across modules, but the relations aren't stored in a pivot table in the database.
-
-|First Data Model|Second Data Model|Type|Description|
-|---|---|---|---|
-| in ||Stored||
-| in ||Stored||
-| in ||Stored||
-| in ||Stored||
-
-***
-
-## Fulfillment Module
-
-A fulfillment set can be conditioned to a specific stock location.
-
-Medusa defines a link between the `FulfillmentSet` and `StockLocation` data models.
-
-
-
-Medusa also defines a link between the `FulfillmentProvider` and `StockLocation` data models to indicate the providers that can be used in a location.
-
-
-
-### Retrieve with Query
-
-To retrieve the fulfillment sets of a stock location with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `fulfillment_sets.*` in `fields`:
-
-To retrieve the fulfillment providers, pass `fulfillment_providers.*` in `fields`.
-
-### query.graph
-
-```ts
-const { data: stockLocations } = await query.graph({
- entity: "stock_location",
- fields: [
- "fulfillment_sets.*",
- ],
-})
-
-// stockLocations.fulfillment_sets
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: stockLocations } = useQueryGraphStep({
- entity: "stock_location",
- fields: [
- "fulfillment_sets.*",
- ],
-})
-
-// stockLocations.fulfillment_sets
-```
-
-### Manage with Link
-
-To manage the stock location of a fulfillment set, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
-
-### link.create
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await link.create({
- [Modules.STOCK_LOCATION]: {
- stock_location_id: "sloc_123",
- },
- [Modules.FULFILLMENT]: {
- fulfillment_set_id: "fset_123",
- },
-})
-```
-
-### createRemoteLinkStep
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-createRemoteLinkStep({
- [Modules.STOCK_LOCATION]: {
- stock_location_id: "sloc_123",
- },
- [Modules.FULFILLMENT]: {
- fulfillment_set_id: "fset_123",
- },
-})
-```
-
-***
-
-## Inventory Module
-
-Medusa defines a read-only link between the [Inventory Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/inventory/index.html.md)'s `InventoryLevel` data model and the `StockLocation` data model. Because the link is read-only from the `InventoryLevel`'s side, you can only retrieve the stock location of an inventory level, and not the other way around.
-
-### Retrieve with Query
-
-To retrieve the stock locations of an inventory level with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `stock_locations.*` in `fields`:
-
-### query.graph
-
-```ts
-const { data: inventoryLevels } = await query.graph({
- entity: "inventory_level",
- fields: [
- "stock_locations.*",
- ],
-})
-
-// inventoryLevels.stock_locations
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: inventoryLevels } = useQueryGraphStep({
- entity: "inventory_level",
- fields: [
- "stock_locations.*",
- ],
-})
-
-// inventoryLevels.stock_locations
-```
-
-***
-
-## Sales Channel Module
-
-A stock location is associated with a sales channel. This scopes inventory quantities in a stock location by the associated sales channel.
-
-Medusa defines a link between the `SalesChannel` and `StockLocation` data models.
-
-
-
-### Retrieve with Query
-
-To retrieve the sales channels of a stock location with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `sales_channels.*` in `fields`:
-
-### query.graph
-
-```ts
-const { data: stockLocations } = await query.graph({
- entity: "stock_location",
- fields: [
- "sales_channels.*",
- ],
-})
-
-// stockLocations.sales_channels
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: stockLocations } = useQueryGraphStep({
- entity: "stock_location",
- fields: [
- "sales_channels.*",
- ],
-})
-
-// stockLocations.sales_channels
-```
-
-### Manage with Link
-
-To manage the stock locations of a sales channel, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
-
-### link.create
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-await link.create({
- [Modules.SALES_CHANNEL]: {
- sales_channel_id: "sc_123",
- },
- [Modules.STOCK_LOCATION]: {
- sales_channel_id: "sloc_123",
- },
-})
-```
-
-### createRemoteLinkStep
-
-```ts
-import { Modules } from "@medusajs/framework/utils"
-import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-createRemoteLinkStep({
- [Modules.SALES_CHANNEL]: {
- sales_channel_id: "sc_123",
- },
- [Modules.STOCK_LOCATION]: {
- sales_channel_id: "sloc_123",
- },
-})
-```
-
-
-# Links between Store Module and Other Modules
-
-This document showcases the module links defined between the Store Module and other commerce modules.
-
-## Summary
-
-The Store Module has the following links to other modules:
-
-Read-only links are used to query data across modules, but the relations aren't stored in a pivot table in the database.
-
-|First Data Model|Second Data Model|Type|Description|
-|---|---|---|---|
-|| in |Read-only||
-
-***
-
-## Currency Module
-
-The Store Module has a `Currency` data model that stores the supported currencies of a store. However, these currencies don't hold all the details of a currency, such as its name or symbol.
-
-Instead, Medusa defines a read-only link between the [Currency Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/currency/index.html.md)'s `Currency` data model and the Store Module's `Currency` data model. This means you can retrieve the details of a store's supported currencies, but you don't manage the links in a pivot table in the database. The currencies of a store are determined by the `currency_code` of the [Currency](https://docs.medusajs.com/references/store/models/Currency/index.html.md) data model in the Store Module (not in the Currency Module).
-
-### Retrieve with Query
-
-To retrieve the details of a store's currencies with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `supported_currencies.currency.*` in `fields`:
-
-### query.graph
-
-```ts
-const { data: stores } = await query.graph({
- entity: "store",
- fields: [
- "supported_currencies.currency.*",
- ],
-})
-
-// stores.supported_currencies
-```
-
-### useQueryGraphStep
-
-```ts
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-
-// ...
-
-const { data: stores } = useQueryGraphStep({
- entity: "store",
- fields: [
- "supported_currencies.currency.*",
- ],
-})
-
-// stores.supported_currencies
-```
-
-
-# Tax Module Options
-
-In this document, you'll learn about the options of the Tax Module.
-
-## providers
-
-The `providers` option is an array of either tax module providers or path to a file that defines a tax provider.
-
-When the Medusa application starts, these providers are registered and can be used to retrieve tax lines.
-
-```ts title="medusa-config.ts"
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-module.exports = defineConfig({
- // ...
- modules: [
- {
- resolve: "@medusajs/tax",
- options: {
- providers: [
- {
- resolve: "./path/to/my-provider",
- id: "my-provider",
- options: {
- // ...
- },
- },
- ],
- },
- },
- ],
-})
-```
-
-The objects in the array accept the following properties:
-
-- `resolve`: A string indicating the package name of the module provider or the path to it.
-- `id`: A string indicating the provider's unique name or ID.
-- `options`: An optional object of the module provider's options.
-
-
-# Tax Calculation with the Tax Provider
-
-In this document, you’ll learn how tax lines are calculated and what a tax provider is.
-
-## Tax Lines Calculation
-
-Tax lines are calculated and retrieved using the [getTaxLines method of the Tax Module’s main service](https://docs.medusajs.com/references/tax/getTaxLines/index.html.md). It accepts an array of line items and shipping methods, and the context of the calculation.
-
-For example:
-
-```ts
-const taxLines = await taxModuleService.getTaxLines(
- [
- {
- id: "cali_123",
- product_id: "prod_123",
- unit_price: 1000,
- quantity: 1,
- },
- {
- id: "casm_123",
- shipping_option_id: "so_123",
- unit_price: 2000,
- },
- ],
- {
- address: {
- country_code: "us",
- },
- }
-)
-```
-
-The context object is used to determine which tax regions and rates to use in the calculation. It includes properties related to the address and customer.
-
-The example above retrieves the tax lines based on the tax region for the United States.
-
-The method returns tax lines for the line item and shipping methods. For example:
-
-```json
-[
- {
- "line_item_id": "cali_123",
- "rate_id": "txr_1",
- "rate": 10,
- "code": "XXX",
- "name": "Tax Rate 1"
- },
- {
- "shipping_line_id": "casm_123",
- "rate_id": "txr_2",
- "rate": 5,
- "code": "YYY",
- "name": "Tax Rate 2"
- }
-]
-```
-
-***
-
-## Using the Tax Provider in the Calculation
-
-The tax lines retrieved by the `getTaxLines` method are actually retrieved from the tax region’s provider.
-
-A tax module provider whose main service implements the logic to shape tax lines. Each tax region has a tax provider.
-
-The Tax Module provides a `system` tax provider that only transforms calculated item and shipping tax rates into the required return type.
-
-{/* ---
-
-TODO add once tax provider guide is updated + add module providers match other modules.
-
-## Create Tax Provider
-
-Refer to [this guide](/modules/tax/provider) to learn more about creating a tax provider. */}
-
-
-# Tax Region
-
-In this document, you’ll learn about tax regions and how to use them with the Region Module.
-
-Refer to this [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/tax-regions/index.html.md) to learn how to manage tax regions using the dashboard.
-
-## What is a Tax Region?
-
-A tax region, represented by the [TaxRegion data model](https://docs.medusajs.com/references/tax/models/TaxRegion/index.html.md), stores tax settings related to a region that your store serves.
-
-Tax regions can inherit settings and rules from a parent tax region.
-
-Each tax region has tax rules and a tax provider.
-
-
-# Tax Rates and Rules
-
-In this document, you’ll learn about tax rates and rules.
-
-Refer to this [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/tax-regions#manage-tax-rate-overrides/index.html.md) to learn how to manage tax rates using the dashboard.
-
-## What are Tax Rates?
-
-A tax rate is a percentage amount used to calculate the tax amount for each taxable item’s price, such as line items or shipping methods, in a cart. The sum of all calculated tax amounts are then added to the cart’s total as a tax total.
-
-Each tax region has a default tax rate. This tax rate is applied to all taxable items of a cart in that region.
-
-### Combinable Tax Rates
-
-Tax regions can have parent tax regions. To inherit the tax rates of the parent tax region, set the `is_combinable` of the child’s tax rates to `true`.
-
-Then, when tax rates are retrieved for a taxable item in the child region, both the child and the parent tax regions’ applicable rates are returned.
-
-***
-
-## Override Tax Rates with Rules
-
-You can create tax rates that override the default for specific conditions or rules.
-
-For example, you can have a default tax rate is 10%, but for products of type “Shirt” is %15.
-
-A tax region can have multiple tax rates, and each tax rate can have multiple tax rules. The [TaxRateRule data model](https://docs.medusajs.com/references/tax/models/TaxRateRule/index.html.md) represents a tax rate’s rule.
-
-
-
-These two properties of the data model identify the rule’s target:
-
-- `reference`: the name of the table in the database that this rule points to. For example, `product_type`.
-- `reference_id`: the ID of the data model’s record that this points to. For example, a product type’s ID.
-
-So, to override the default tax rate for product types “Shirt”, you create a tax rate and associate with it a tax rule whose `reference` is `product_type` and `reference_id` the ID of the “Shirt” product type.
-
-
-# User Creation Flows
-
-In this document, learn the different ways to create a user using the User Module.
-
-Refer to this [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/users/index.html.md) to learn how to manage users using the dashboard.
-
-## Straightforward User Creation
-
-To create a user, use the [create method of the User Module’s main service](https://docs.medusajs.com/references/user/create/index.html.md):
-
-```ts
-const user = await userModuleService.createUsers({
- email: "user@example.com",
-})
-```
-
-You can pair this with the Auth Module to allow the user to authenticate, as explained in a [later section](#create-identity-with-the-auth-module).
-
-***
-
-## Invite Users
-
-To create a user, you can create an invite for them using the [createInvites method](https://docs.medusajs.com/references/user/createInvites/index.html.md) of the User Module's main service:
-
-```ts
-const invite = await userModuleService.createInvites({
- email: "user@example.com",
-})
-```
-
-Later, you can accept the invite and create a new user for them:
-
-```ts
-const invite =
- await userModuleService.validateInviteToken("secret_123")
-
-await userModuleService.updateInvites({
- id: invite.id,
- accepted: true,
-})
-
-const user = await userModuleService.createUsers({
- email: invite.email,
-})
-```
-
-### Invite Expiry
-
-An invite has an expiry date. You can renew the expiry date and refresh the token using the [refreshInviteTokens method](https://docs.medusajs.com/references/user/refreshInviteTokens/index.html.md):
-
-```ts
-await userModuleService.refreshInviteTokens(["invite_123"])
-```
-
-***
-
-## Create Identity with the Auth Module
-
-By combining the User and Auth Modules, you can use the Auth Module for authenticating users, and the User Module to manage those users.
-
-So, when a user is authenticated, and you receive the `AuthIdentity` object, you can use it to create a user if it doesn’t exist:
-
-```ts
-const { success, authIdentity } =
- await authModuleService.authenticate("emailpass", {
- // ...
- })
-
-const [, count] = await userModuleService.listAndCountUsers({
- email: authIdentity.entity_id,
-})
-
-if (!count) {
- const user = await userModuleService.createUsers({
- email: authIdentity.entity_id,
- })
-}
-```
-
-
-# User Module Options
-
-In this document, you'll learn about the options of the User Module.
-
-## Module Options
-
-```ts title="medusa-config.ts"
-import { Modules } from "@medusajs/framework/utils"
-
-// ...
-
-module.exports = defineConfig({
- // ...
- modules: [
- {
- resolve: "@medusajs/user",
- options: {
- jwt_secret: process.env.JWT_SECRET,
- },
- },
- ],
-})
-```
-
-|Option|Description|Required|
-|---|---|---|---|---|
-|\`jwt\_secret\`|A string indicating the secret used to sign the invite tokens.|Yes|
-
-### Environment Variables
-
-Make sure to add the necessary environment variables for the above options in `.env`:
-
-```bash
-JWT_SECRET=supersecret
-```
-
-
-# Publishable API Keys with Sales Channels
-
-In this document, you’ll learn what publishable API keys are and how to use them with sales channels.
-
-## Publishable API Keys with Sales Channels
-
-A publishable API key, provided by the API Key Module, is a client key scoped to one or more sales channels.
-
-When sending a request to a Store API route, you must pass a publishable API key in the header of the request:
-
-```bash
-curl http://localhost:9000/store/products \
- x-publishable-api-key: {your_publishable_api_key}
-```
-
-The Medusa application infers the associated sales channels and ensures that only data relevant to the sales channel are used.
-
-***
-
-## How to Create a Publishable API Key?
-
-To create a publishable API key, either use the [Medusa Admin](https://docs.medusajs.com/user-guide/settings/developer/publishable-api-keys/index.html.md) or the [Admin API Routes](https://docs.medusajs.com/api/admin#publishable-api-keys).
-
-
# Links between Sales Channel Module and Other Modules
This document showcases the module links defined between the Sales Channel Module and other commerce modules.
@@ -27988,6 +28129,624 @@ createRemoteLinkStep({
```
+# Publishable API Keys with Sales Channels
+
+In this document, you’ll learn what publishable API keys are and how to use them with sales channels.
+
+## Publishable API Keys with Sales Channels
+
+A publishable API key, provided by the API Key Module, is a client key scoped to one or more sales channels.
+
+When sending a request to a Store API route, you must pass a publishable API key in the header of the request:
+
+```bash
+curl http://localhost:9000/store/products \
+ x-publishable-api-key: {your_publishable_api_key}
+```
+
+The Medusa application infers the associated sales channels and ensures that only data relevant to the sales channel are used.
+
+***
+
+## How to Create a Publishable API Key?
+
+To create a publishable API key, either use the [Medusa Admin](https://docs.medusajs.com/user-guide/settings/developer/publishable-api-keys/index.html.md) or the [Admin API Routes](https://docs.medusajs.com/api/admin#publishable-api-keys).
+
+
+# Links between Store Module and Other Modules
+
+This document showcases the module links defined between the Store Module and other commerce modules.
+
+## Summary
+
+The Store Module has the following links to other modules:
+
+Read-only links are used to query data across modules, but the relations aren't stored in a pivot table in the database.
+
+|First Data Model|Second Data Model|Type|Description|
+|---|---|---|---|
+|| in |Read-only||
+
+***
+
+## Currency Module
+
+The Store Module has a `Currency` data model that stores the supported currencies of a store. However, these currencies don't hold all the details of a currency, such as its name or symbol.
+
+Instead, Medusa defines a read-only link between the [Currency Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/currency/index.html.md)'s `Currency` data model and the Store Module's `Currency` data model. This means you can retrieve the details of a store's supported currencies, but you don't manage the links in a pivot table in the database. The currencies of a store are determined by the `currency_code` of the [Currency](https://docs.medusajs.com/references/store/models/Currency/index.html.md) data model in the Store Module (not in the Currency Module).
+
+### Retrieve with Query
+
+To retrieve the details of a store's currencies with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `supported_currencies.currency.*` in `fields`:
+
+### query.graph
+
+```ts
+const { data: stores } = await query.graph({
+ entity: "store",
+ fields: [
+ "supported_currencies.currency.*",
+ ],
+})
+
+// stores.supported_currencies
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: stores } = useQueryGraphStep({
+ entity: "store",
+ fields: [
+ "supported_currencies.currency.*",
+ ],
+})
+
+// stores.supported_currencies
+```
+
+
+# Stock Location Concepts
+
+In this document, you’ll learn about the main concepts in the Stock Location Module.
+
+## Stock Location
+
+A stock location, represented by the `StockLocation` data model, represents a location where stock items are kept. For example, a warehouse.
+
+Medusa uses stock locations to provide inventory details, from the Inventory Module, per location.
+
+***
+
+## StockLocationAddress
+
+The `StockLocationAddress` data model belongs to the `StockLocation` data model. It provides more detailed information of the location, such as country code or street address.
+
+
+# Links between Stock Location Module and Other Modules
+
+This document showcases the module links defined between the Stock Location Module and other commerce modules.
+
+## Summary
+
+The Stock Location Module has the following links to other modules:
+
+Read-only links are used to query data across modules, but the relations aren't stored in a pivot table in the database.
+
+|First Data Model|Second Data Model|Type|Description|
+|---|---|---|---|
+| in ||Stored||
+| in ||Stored||
+| in ||Stored||
+| in ||Stored||
+
+***
+
+## Fulfillment Module
+
+A fulfillment set can be conditioned to a specific stock location.
+
+Medusa defines a link between the `FulfillmentSet` and `StockLocation` data models.
+
+
+
+Medusa also defines a link between the `FulfillmentProvider` and `StockLocation` data models to indicate the providers that can be used in a location.
+
+
+
+### Retrieve with Query
+
+To retrieve the fulfillment sets of a stock location with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `fulfillment_sets.*` in `fields`:
+
+To retrieve the fulfillment providers, pass `fulfillment_providers.*` in `fields`.
+
+### query.graph
+
+```ts
+const { data: stockLocations } = await query.graph({
+ entity: "stock_location",
+ fields: [
+ "fulfillment_sets.*",
+ ],
+})
+
+// stockLocations.fulfillment_sets
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: stockLocations } = useQueryGraphStep({
+ entity: "stock_location",
+ fields: [
+ "fulfillment_sets.*",
+ ],
+})
+
+// stockLocations.fulfillment_sets
+```
+
+### Manage with Link
+
+To manage the stock location of a fulfillment set, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
+
+### link.create
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await link.create({
+ [Modules.STOCK_LOCATION]: {
+ stock_location_id: "sloc_123",
+ },
+ [Modules.FULFILLMENT]: {
+ fulfillment_set_id: "fset_123",
+ },
+})
+```
+
+### createRemoteLinkStep
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+createRemoteLinkStep({
+ [Modules.STOCK_LOCATION]: {
+ stock_location_id: "sloc_123",
+ },
+ [Modules.FULFILLMENT]: {
+ fulfillment_set_id: "fset_123",
+ },
+})
+```
+
+***
+
+## Inventory Module
+
+Medusa defines a read-only link between the [Inventory Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/inventory/index.html.md)'s `InventoryLevel` data model and the `StockLocation` data model. Because the link is read-only from the `InventoryLevel`'s side, you can only retrieve the stock location of an inventory level, and not the other way around.
+
+### Retrieve with Query
+
+To retrieve the stock locations of an inventory level with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `stock_locations.*` in `fields`:
+
+### query.graph
+
+```ts
+const { data: inventoryLevels } = await query.graph({
+ entity: "inventory_level",
+ fields: [
+ "stock_locations.*",
+ ],
+})
+
+// inventoryLevels.stock_locations
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: inventoryLevels } = useQueryGraphStep({
+ entity: "inventory_level",
+ fields: [
+ "stock_locations.*",
+ ],
+})
+
+// inventoryLevels.stock_locations
+```
+
+***
+
+## Sales Channel Module
+
+A stock location is associated with a sales channel. This scopes inventory quantities in a stock location by the associated sales channel.
+
+Medusa defines a link between the `SalesChannel` and `StockLocation` data models.
+
+
+
+### Retrieve with Query
+
+To retrieve the sales channels of a stock location with [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), pass `sales_channels.*` in `fields`:
+
+### query.graph
+
+```ts
+const { data: stockLocations } = await query.graph({
+ entity: "stock_location",
+ fields: [
+ "sales_channels.*",
+ ],
+})
+
+// stockLocations.sales_channels
+```
+
+### useQueryGraphStep
+
+```ts
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+const { data: stockLocations } = useQueryGraphStep({
+ entity: "stock_location",
+ fields: [
+ "sales_channels.*",
+ ],
+})
+
+// stockLocations.sales_channels
+```
+
+### Manage with Link
+
+To manage the stock locations of a sales channel, use [Link](https://docs.medusajs.com/docs/learn/fundamentals/module-links/link/index.html.md):
+
+### link.create
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+await link.create({
+ [Modules.SALES_CHANNEL]: {
+ sales_channel_id: "sc_123",
+ },
+ [Modules.STOCK_LOCATION]: {
+ sales_channel_id: "sloc_123",
+ },
+})
+```
+
+### createRemoteLinkStep
+
+```ts
+import { Modules } from "@medusajs/framework/utils"
+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
+
+// ...
+
+createRemoteLinkStep({
+ [Modules.SALES_CHANNEL]: {
+ sales_channel_id: "sc_123",
+ },
+ [Modules.STOCK_LOCATION]: {
+ sales_channel_id: "sloc_123",
+ },
+})
+```
+
+
+# Tax Rates and Rules
+
+In this document, you’ll learn about tax rates and rules.
+
+Refer to this [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/tax-regions#manage-tax-rate-overrides/index.html.md) to learn how to manage tax rates using the dashboard.
+
+## What are Tax Rates?
+
+A tax rate is a percentage amount used to calculate the tax amount for each taxable item’s price, such as line items or shipping methods, in a cart. The sum of all calculated tax amounts are then added to the cart’s total as a tax total.
+
+Each tax region has a default tax rate. This tax rate is applied to all taxable items of a cart in that region.
+
+### Combinable Tax Rates
+
+Tax regions can have parent tax regions. To inherit the tax rates of the parent tax region, set the `is_combinable` of the child’s tax rates to `true`.
+
+Then, when tax rates are retrieved for a taxable item in the child region, both the child and the parent tax regions’ applicable rates are returned.
+
+***
+
+## Override Tax Rates with Rules
+
+You can create tax rates that override the default for specific conditions or rules.
+
+For example, you can have a default tax rate is 10%, but for products of type “Shirt” is %15.
+
+A tax region can have multiple tax rates, and each tax rate can have multiple tax rules. The [TaxRateRule data model](https://docs.medusajs.com/references/tax/models/TaxRateRule/index.html.md) represents a tax rate’s rule.
+
+
+
+These two properties of the data model identify the rule’s target:
+
+- `reference`: the name of the table in the database that this rule points to. For example, `product_type`.
+- `reference_id`: the ID of the data model’s record that this points to. For example, a product type’s ID.
+
+So, to override the default tax rate for product types “Shirt”, you create a tax rate and associate with it a tax rule whose `reference` is `product_type` and `reference_id` the ID of the “Shirt” product type.
+
+
+# Tax Region
+
+In this document, you’ll learn about tax regions and how to use them with the Region Module.
+
+Refer to this [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/tax-regions/index.html.md) to learn how to manage tax regions using the dashboard.
+
+## What is a Tax Region?
+
+A tax region, represented by the [TaxRegion data model](https://docs.medusajs.com/references/tax/models/TaxRegion/index.html.md), stores tax settings related to a region that your store serves.
+
+Tax regions can inherit settings and rules from a parent tax region.
+
+Each tax region has tax rules and a tax provider.
+
+
+# Tax Calculation with the Tax Provider
+
+In this document, you’ll learn how tax lines are calculated and what a tax provider is.
+
+## Tax Lines Calculation
+
+Tax lines are calculated and retrieved using the [getTaxLines method of the Tax Module’s main service](https://docs.medusajs.com/references/tax/getTaxLines/index.html.md). It accepts an array of line items and shipping methods, and the context of the calculation.
+
+For example:
+
+```ts
+const taxLines = await taxModuleService.getTaxLines(
+ [
+ {
+ id: "cali_123",
+ product_id: "prod_123",
+ unit_price: 1000,
+ quantity: 1,
+ },
+ {
+ id: "casm_123",
+ shipping_option_id: "so_123",
+ unit_price: 2000,
+ },
+ ],
+ {
+ address: {
+ country_code: "us",
+ },
+ }
+)
+```
+
+The context object is used to determine which tax regions and rates to use in the calculation. It includes properties related to the address and customer.
+
+The example above retrieves the tax lines based on the tax region for the United States.
+
+The method returns tax lines for the line item and shipping methods. For example:
+
+```json
+[
+ {
+ "line_item_id": "cali_123",
+ "rate_id": "txr_1",
+ "rate": 10,
+ "code": "XXX",
+ "name": "Tax Rate 1"
+ },
+ {
+ "shipping_line_id": "casm_123",
+ "rate_id": "txr_2",
+ "rate": 5,
+ "code": "YYY",
+ "name": "Tax Rate 2"
+ }
+]
+```
+
+***
+
+## Using the Tax Provider in the Calculation
+
+The tax lines retrieved by the `getTaxLines` method are actually retrieved from the tax region’s provider.
+
+A tax module provider whose main service implements the logic to shape tax lines. Each tax region has a tax provider.
+
+The Tax Module provides a `system` tax provider that only transforms calculated item and shipping tax rates into the required return type.
+
+{/* ---
+
+TODO add once tax provider guide is updated + add module providers match other modules.
+
+## Create Tax Provider
+
+Refer to [this guide](/modules/tax/provider) to learn more about creating a tax provider. */}
+
+
+# Tax Module Options
+
+In this document, you'll learn about the options of the Tax Module.
+
+## providers
+
+The `providers` option is an array of either tax module providers or path to a file that defines a tax provider.
+
+When the Medusa application starts, these providers are registered and can be used to retrieve tax lines.
+
+```ts title="medusa-config.ts"
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+module.exports = defineConfig({
+ // ...
+ modules: [
+ {
+ resolve: "@medusajs/tax",
+ options: {
+ providers: [
+ {
+ resolve: "./path/to/my-provider",
+ id: "my-provider",
+ options: {
+ // ...
+ },
+ },
+ ],
+ },
+ },
+ ],
+})
+```
+
+The objects in the array accept the following properties:
+
+- `resolve`: A string indicating the package name of the module provider or the path to it.
+- `id`: A string indicating the provider's unique name or ID.
+- `options`: An optional object of the module provider's options.
+
+
+# User Module Options
+
+In this document, you'll learn about the options of the User Module.
+
+## Module Options
+
+```ts title="medusa-config.ts"
+import { Modules } from "@medusajs/framework/utils"
+
+// ...
+
+module.exports = defineConfig({
+ // ...
+ modules: [
+ {
+ resolve: "@medusajs/user",
+ options: {
+ jwt_secret: process.env.JWT_SECRET,
+ },
+ },
+ ],
+})
+```
+
+|Option|Description|Required|
+|---|---|---|---|---|
+|\`jwt\_secret\`|A string indicating the secret used to sign the invite tokens.|Yes|
+
+### Environment Variables
+
+Make sure to add the necessary environment variables for the above options in `.env`:
+
+```bash
+JWT_SECRET=supersecret
+```
+
+
+# User Creation Flows
+
+In this document, learn the different ways to create a user using the User Module.
+
+Refer to this [Medusa Admin User Guide](https://docs.medusajs.com/user-guide/settings/users/index.html.md) to learn how to manage users using the dashboard.
+
+## Straightforward User Creation
+
+To create a user, use the [create method of the User Module’s main service](https://docs.medusajs.com/references/user/create/index.html.md):
+
+```ts
+const user = await userModuleService.createUsers({
+ email: "user@example.com",
+})
+```
+
+You can pair this with the Auth Module to allow the user to authenticate, as explained in a [later section](#create-identity-with-the-auth-module).
+
+***
+
+## Invite Users
+
+To create a user, you can create an invite for them using the [createInvites method](https://docs.medusajs.com/references/user/createInvites/index.html.md) of the User Module's main service:
+
+```ts
+const invite = await userModuleService.createInvites({
+ email: "user@example.com",
+})
+```
+
+Later, you can accept the invite and create a new user for them:
+
+```ts
+const invite =
+ await userModuleService.validateInviteToken("secret_123")
+
+await userModuleService.updateInvites({
+ id: invite.id,
+ accepted: true,
+})
+
+const user = await userModuleService.createUsers({
+ email: invite.email,
+})
+```
+
+### Invite Expiry
+
+An invite has an expiry date. You can renew the expiry date and refresh the token using the [refreshInviteTokens method](https://docs.medusajs.com/references/user/refreshInviteTokens/index.html.md):
+
+```ts
+await userModuleService.refreshInviteTokens(["invite_123"])
+```
+
+***
+
+## Create Identity with the Auth Module
+
+By combining the User and Auth Modules, you can use the Auth Module for authenticating users, and the User Module to manage those users.
+
+So, when a user is authenticated, and you receive the `AuthIdentity` object, you can use it to create a user if it doesn’t exist:
+
+```ts
+const { success, authIdentity } =
+ await authModuleService.authenticate("emailpass", {
+ // ...
+ })
+
+const [, count] = await userModuleService.listAndCountUsers({
+ email: authIdentity.entity_id,
+})
+
+if (!count) {
+ const user = await userModuleService.createUsers({
+ email: authIdentity.entity_id,
+ })
+}
+```
+
+
# Emailpass Auth Module Provider
In this document, you’ll learn about the Emailpass auth module provider and how to install and use it in the Auth Module.
@@ -28050,6 +28809,175 @@ const hashConfig = \{
- [How to register a customer using email and password](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/register/index.html.md)
+# GitHub Auth Module Provider
+
+In this document, you’ll learn about the GitHub Auth Module Provider and how to install and use it in the Auth Module.
+
+The Github Auth Module Provider authenticates users with their GitHub account.
+
+Learn about the authentication flow in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route/index.html.md).
+
+***
+
+## Register the Github Auth Module Provider
+
+### Prerequisites
+
+- [Register GitHub App. When setting the Callback URL, set it to a URL in your frontend that later uses Medusa's callback route to validate the authentication.](https://docs.github.com/en/apps/creating-github-apps/setting-up-a-github-app/creating-a-github-app)
+- [Retrieve the client ID and client secret of your GitHub App](https://docs.github.com/en/rest/authentication/authenticating-to-the-rest-api?apiVersion=2022-11-28#using-basic-authentication)
+
+Add the module to the array of providers passed to the Auth Module:
+
+```ts title="medusa-config.ts"
+import { Modules, ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+// ...
+
+module.exports = defineConfig({
+ // ...
+ modules: [
+ {
+ resolve: "@medusajs/medusa/auth",
+ dependencies: [Modules.CACHE, ContainerRegistrationKeys.LOGGER],
+ options: {
+ providers: [
+ // other providers...
+ {
+ resolve: "@medusajs/medusa/auth-github",
+ id: "github",
+ options: {
+ clientId: process.env.GITHUB_CLIENT_ID,
+ clientSecret: process.env.GITHUB_CLIENT_SECRET,
+ callbackUrl: process.env.GITHUB_CALLBACK_URL,
+ },
+ },
+ ],
+ },
+ },
+ ],
+})
+```
+
+### Environment Variables
+
+Make sure to add the necessary environment variables for the above options in `.env`:
+
+```plain
+GITHUB_CLIENT_ID=
+GITHUB_CLIENT_SECRET=
+GITHUB_CALLBACK_URL=
+```
+
+### Module Options
+
+|Configuration|Description|Required|
+|---|---|---|---|---|
+|\`clientId\`|A string indicating the client ID of your GitHub app.|Yes|
+|\`clientSecret\`|A string indicating the client secret of your GitHub app.|Yes|
+|\`callbackUrl\`|A string indicating the URL to redirect to in your frontend after the user completes their authentication in GitHub.|Yes|
+
+***
+
+## Override Callback URL During Authentication
+
+In many cases, you may have different callback URL for actor types. For example, you may redirect admin users to a different URL than customers after authentication.
+
+The [Authenticate or Login API Route](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#login-route/index.html.md) can accept a `callback_url` body parameter to override the provider's `callbackUrl` option. Learn more in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#login-route/index.html.md).
+
+***
+
+## Examples
+
+- [How to implement third-party / social login in the storefront.](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/third-party-login/index.html.md).
+
+
+# Google Auth Module Provider
+
+In this document, you’ll learn about the Google Auth Module Provider and how to install and use it in the Auth Module.
+
+The Google Auth Module Provider authenticates users with their Google account.
+
+Learn about the authentication flow for third-party providers in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#2-third-party-service-authenticate-flow/index.html.md).
+
+***
+
+## Register the Google Auth Module Provider
+
+### Prerequisites
+
+- [Create a project in Google Cloud.](https://cloud.google.com/resource-manager/docs/creating-managing-projects)
+- [Create authorization credentials. When setting the Redirect Uri, set it to a URL in your frontend that later uses Medusa's callback route to validate the authentication.](https://developers.google.com/identity/protocols/oauth2/web-server#creatingcred)
+
+Add the module to the array of providers passed to the Auth Module:
+
+```ts title="medusa-config.ts"
+import { Modules, ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+// ...
+
+module.exports = defineConfig({
+ // ...
+ modules: [
+ {
+ // ...
+ [Modules.AUTH]: {
+ resolve: "@medusajs/medusa/auth",
+ dependencies: [Modules.CACHE, ContainerRegistrationKeys.LOGGER],
+ options: {
+ providers: [
+ // other providers...
+ {
+ resolve: "@medusajs/medusa/auth-google",
+ id: "google",
+ options: {
+ clientId: process.env.GOOGLE_CLIENT_ID,
+ clientSecret: process.env.GOOGLE_CLIENT_SECRET,
+ callbackUrl: process.env.GOOGLE_CALLBACK_URL,
+ },
+ },
+ ],
+ },
+ },
+ },
+ ],
+})
+```
+
+### Environment Variables
+
+Make sure to add the necessary environment variables for the above options in `.env`:
+
+```plain
+GOOGLE_CLIENT_ID=
+GOOGLE_CLIENT_SECRET=
+GOOGLE_CALLBACK_URL=
+```
+
+### Module Options
+
+|Configuration|Description|Required|
+|---|---|---|---|---|
+|\`clientId\`|A string indicating the |Yes|
+|\`clientSecret\`|A string indicating the |Yes|
+|\`callbackUrl\`|A string indicating the URL to redirect to in your frontend after the user completes their authentication in Google.|Yes|
+
+***
+
+***
+
+## Override Callback URL During Authentication
+
+In many cases, you may have different callback URL for actor types. For example, you may redirect admin users to a different URL than customers after authentication.
+
+The [Authenticate or Login API Route](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#login-route/index.html.md) can accept a `callback_url` body parameter to override the provider's `callbackUrl` option. Learn more in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#login-route/index.html.md).
+
+***
+
+## Examples
+
+- [How to implement Google social login in the storefront](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/third-party-login/index.html.md).
+
+
# Stripe Module Provider
In this document, you’ll learn about the Stripe Module Provider and how to configure it in the Payment Module.
@@ -28425,351 +29353,177 @@ For each product variant, you:
- `priceWithoutTax`: The variant's price without taxes applied.
-# Google Auth Module Provider
-
-In this document, you’ll learn about the Google Auth Module Provider and how to install and use it in the Auth Module.
-
-The Google Auth Module Provider authenticates users with their Google account.
-
-Learn about the authentication flow for third-party providers in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#2-third-party-service-authenticate-flow/index.html.md).
-
-***
-
-## Register the Google Auth Module Provider
-
-### Prerequisites
-
-- [Create a project in Google Cloud.](https://cloud.google.com/resource-manager/docs/creating-managing-projects)
-- [Create authorization credentials. When setting the Redirect Uri, set it to a URL in your frontend that later uses Medusa's callback route to validate the authentication.](https://developers.google.com/identity/protocols/oauth2/web-server#creatingcred)
-
-Add the module to the array of providers passed to the Auth Module:
-
-```ts title="medusa-config.ts"
-import { Modules, ContainerRegistrationKeys } from "@medusajs/framework/utils"
-
-// ...
-
-module.exports = defineConfig({
- // ...
- modules: [
- {
- // ...
- [Modules.AUTH]: {
- resolve: "@medusajs/medusa/auth",
- dependencies: [Modules.CACHE, ContainerRegistrationKeys.LOGGER],
- options: {
- providers: [
- // other providers...
- {
- resolve: "@medusajs/medusa/auth-google",
- id: "google",
- options: {
- clientId: process.env.GOOGLE_CLIENT_ID,
- clientSecret: process.env.GOOGLE_CLIENT_SECRET,
- callbackUrl: process.env.GOOGLE_CALLBACK_URL,
- },
- },
- ],
- },
- },
- },
- ],
-})
-```
-
-### Environment Variables
-
-Make sure to add the necessary environment variables for the above options in `.env`:
-
-```plain
-GOOGLE_CLIENT_ID=
-GOOGLE_CLIENT_SECRET=
-GOOGLE_CALLBACK_URL=
-```
-
-### Module Options
-
-|Configuration|Description|Required|
-|---|---|---|---|---|
-|\`clientId\`|A string indicating the |Yes|
-|\`clientSecret\`|A string indicating the |Yes|
-|\`callbackUrl\`|A string indicating the URL to redirect to in your frontend after the user completes their authentication in Google.|Yes|
-
-***
-
-***
-
-## Override Callback URL During Authentication
-
-In many cases, you may have different callback URL for actor types. For example, you may redirect admin users to a different URL than customers after authentication.
-
-The [Authenticate or Login API Route](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#login-route/index.html.md) can accept a `callback_url` body parameter to override the provider's `callbackUrl` option. Learn more in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#login-route/index.html.md).
-
-***
-
-## Examples
-
-- [How to implement Google social login in the storefront](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/third-party-login/index.html.md).
-
-
-# GitHub Auth Module Provider
-
-In this document, you’ll learn about the GitHub Auth Module Provider and how to install and use it in the Auth Module.
-
-The Github Auth Module Provider authenticates users with their GitHub account.
-
-Learn about the authentication flow in [this guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route/index.html.md).
-
-***
-
-## Register the Github Auth Module Provider
-
-### Prerequisites
-
-- [Register GitHub App. When setting the Callback URL, set it to a URL in your frontend that later uses Medusa's callback route to validate the authentication.](https://docs.github.com/en/apps/creating-github-apps/setting-up-a-github-app/creating-a-github-app)
-- [Retrieve the client ID and client secret of your GitHub App](https://docs.github.com/en/rest/authentication/authenticating-to-the-rest-api?apiVersion=2022-11-28#using-basic-authentication)
-
-Add the module to the array of providers passed to the Auth Module:
-
-```ts title="medusa-config.ts"
-import { Modules, ContainerRegistrationKeys } from "@medusajs/framework/utils"
-
-// ...
-
-module.exports = defineConfig({
- // ...
- modules: [
- {
- resolve: "@medusajs/medusa/auth",
- dependencies: [Modules.CACHE, ContainerRegistrationKeys.LOGGER],
- options: {
- providers: [
- // other providers...
- {
- resolve: "@medusajs/medusa/auth-github",
- id: "github",
- options: {
- clientId: process.env.GITHUB_CLIENT_ID,
- clientSecret: process.env.GITHUB_CLIENT_SECRET,
- callbackUrl: process.env.GITHUB_CALLBACK_URL,
- },
- },
- ],
- },
- },
- ],
-})
-```
-
-### Environment Variables
-
-Make sure to add the necessary environment variables for the above options in `.env`:
-
-```plain
-GITHUB_CLIENT_ID=
-GITHUB_CLIENT_SECRET=
-GITHUB_CALLBACK_URL=
-```
-
-### Module Options
-
-|Configuration|Description|Required|
-|---|---|---|---|---|
-|\`clientId\`|A string indicating the client ID of your GitHub app.|Yes|
-|\`clientSecret\`|A string indicating the client secret of your GitHub app.|Yes|
-|\`callbackUrl\`|A string indicating the URL to redirect to in your frontend after the user completes their authentication in GitHub.|Yes|
-
-***
-
-## Override Callback URL During Authentication
-
-In many cases, you may have different callback URL for actor types. For example, you may redirect admin users to a different URL than customers after authentication.
-
-The [Authenticate or Login API Route](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#login-route/index.html.md) can accept a `callback_url` body parameter to override the provider's `callbackUrl` option. Learn more in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/authentication-route#login-route/index.html.md).
-
-***
-
-## Examples
-
-- [How to implement third-party / social login in the storefront.](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/storefront-development/customers/third-party-login/index.html.md).
-
-
## Workflows
- [createApiKeysWorkflow](https://docs.medusajs.com/references/medusa-workflows/createApiKeysWorkflow/index.html.md)
-- [deleteApiKeysWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteApiKeysWorkflow/index.html.md)
-- [linkSalesChannelsToApiKeyWorkflow](https://docs.medusajs.com/references/medusa-workflows/linkSalesChannelsToApiKeyWorkflow/index.html.md)
- [revokeApiKeysWorkflow](https://docs.medusajs.com/references/medusa-workflows/revokeApiKeysWorkflow/index.html.md)
+- [linkSalesChannelsToApiKeyWorkflow](https://docs.medusajs.com/references/medusa-workflows/linkSalesChannelsToApiKeyWorkflow/index.html.md)
- [updateApiKeysWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateApiKeysWorkflow/index.html.md)
-- [createCustomerAccountWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCustomerAccountWorkflow/index.html.md)
-- [createCustomerAddressesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCustomerAddressesWorkflow/index.html.md)
-- [createCustomersWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCustomersWorkflow/index.html.md)
-- [deleteCustomerAddressesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteCustomerAddressesWorkflow/index.html.md)
-- [removeCustomerAccountWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeCustomerAccountWorkflow/index.html.md)
-- [updateCustomerAddressesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateCustomerAddressesWorkflow/index.html.md)
-- [updateCustomersWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateCustomersWorkflow/index.html.md)
-- [deleteCustomersWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteCustomersWorkflow/index.html.md)
-- [generateResetPasswordTokenWorkflow](https://docs.medusajs.com/references/medusa-workflows/generateResetPasswordTokenWorkflow/index.html.md)
-- [batchLinksWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchLinksWorkflow/index.html.md)
-- [createLinksWorkflow](https://docs.medusajs.com/references/medusa-workflows/createLinksWorkflow/index.html.md)
-- [updateLinksWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateLinksWorkflow/index.html.md)
-- [dismissLinksWorkflow](https://docs.medusajs.com/references/medusa-workflows/dismissLinksWorkflow/index.html.md)
-- [addShippingMethodToCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/addShippingMethodToCartWorkflow/index.html.md)
-- [completeCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/completeCartWorkflow/index.html.md)
+- [deleteApiKeysWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteApiKeysWorkflow/index.html.md)
- [addToCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/addToCartWorkflow/index.html.md)
+- [addShippingMethodToCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/addShippingMethodToCartWorkflow/index.html.md)
- [confirmVariantInventoryWorkflow](https://docs.medusajs.com/references/medusa-workflows/confirmVariantInventoryWorkflow/index.html.md)
-- [createCartCreditLinesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCartCreditLinesWorkflow/index.html.md)
+- [completeCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/completeCartWorkflow/index.html.md)
- [createCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCartWorkflow/index.html.md)
+- [createCartCreditLinesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCartCreditLinesWorkflow/index.html.md)
- [createPaymentCollectionForCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/createPaymentCollectionForCartWorkflow/index.html.md)
- [deleteCartCreditLinesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteCartCreditLinesWorkflow/index.html.md)
- [listShippingOptionsForCartWithPricingWorkflow](https://docs.medusajs.com/references/medusa-workflows/listShippingOptionsForCartWithPricingWorkflow/index.html.md)
-- [refreshCartItemsWorkflow](https://docs.medusajs.com/references/medusa-workflows/refreshCartItemsWorkflow/index.html.md)
-- [listShippingOptionsForCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/listShippingOptionsForCartWorkflow/index.html.md)
-- [refreshPaymentCollectionForCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/refreshPaymentCollectionForCartWorkflow/index.html.md)
- [refreshCartShippingMethodsWorkflow](https://docs.medusajs.com/references/medusa-workflows/refreshCartShippingMethodsWorkflow/index.html.md)
+- [listShippingOptionsForCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/listShippingOptionsForCartWorkflow/index.html.md)
+- [refreshCartItemsWorkflow](https://docs.medusajs.com/references/medusa-workflows/refreshCartItemsWorkflow/index.html.md)
+- [refreshPaymentCollectionForCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/refreshPaymentCollectionForCartWorkflow/index.html.md)
- [transferCartCustomerWorkflow](https://docs.medusajs.com/references/medusa-workflows/transferCartCustomerWorkflow/index.html.md)
- [updateCartPromotionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateCartPromotionsWorkflow/index.html.md)
- [updateCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateCartWorkflow/index.html.md)
- [updateLineItemInCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateLineItemInCartWorkflow/index.html.md)
- [updateTaxLinesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateTaxLinesWorkflow/index.html.md)
- [validateExistingPaymentCollectionStep](https://docs.medusajs.com/references/medusa-workflows/validateExistingPaymentCollectionStep/index.html.md)
-- [createCustomerGroupsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCustomerGroupsWorkflow/index.html.md)
-- [linkCustomerGroupsToCustomerWorkflow](https://docs.medusajs.com/references/medusa-workflows/linkCustomerGroupsToCustomerWorkflow/index.html.md)
-- [deleteCustomerGroupsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteCustomerGroupsWorkflow/index.html.md)
-- [updateCustomerGroupsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateCustomerGroupsWorkflow/index.html.md)
-- [linkCustomersToCustomerGroupWorkflow](https://docs.medusajs.com/references/medusa-workflows/linkCustomersToCustomerGroupWorkflow/index.html.md)
-- [createDefaultsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createDefaultsWorkflow/index.html.md)
+- [generateResetPasswordTokenWorkflow](https://docs.medusajs.com/references/medusa-workflows/generateResetPasswordTokenWorkflow/index.html.md)
+- [createCustomerAccountWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCustomerAccountWorkflow/index.html.md)
+- [createCustomerAddressesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCustomerAddressesWorkflow/index.html.md)
+- [createCustomersWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCustomersWorkflow/index.html.md)
+- [deleteCustomerAddressesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteCustomerAddressesWorkflow/index.html.md)
+- [removeCustomerAccountWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeCustomerAccountWorkflow/index.html.md)
+- [deleteCustomersWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteCustomersWorkflow/index.html.md)
+- [updateCustomerAddressesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateCustomerAddressesWorkflow/index.html.md)
+- [updateCustomersWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateCustomersWorkflow/index.html.md)
- [deleteFilesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteFilesWorkflow/index.html.md)
- [uploadFilesWorkflow](https://docs.medusajs.com/references/medusa-workflows/uploadFilesWorkflow/index.html.md)
-- [calculateShippingOptionsPricesWorkflow](https://docs.medusajs.com/references/medusa-workflows/calculateShippingOptionsPricesWorkflow/index.html.md)
-- [cancelFulfillmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelFulfillmentWorkflow/index.html.md)
-- [createFulfillmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/createFulfillmentWorkflow/index.html.md)
-- [createReturnFulfillmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/createReturnFulfillmentWorkflow/index.html.md)
-- [createServiceZonesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createServiceZonesWorkflow/index.html.md)
-- [createShipmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/createShipmentWorkflow/index.html.md)
-- [batchShippingOptionRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchShippingOptionRulesWorkflow/index.html.md)
-- [createShippingOptionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createShippingOptionsWorkflow/index.html.md)
-- [deleteServiceZonesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteServiceZonesWorkflow/index.html.md)
-- [deleteShippingOptionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteShippingOptionsWorkflow/index.html.md)
-- [deleteFulfillmentSetsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteFulfillmentSetsWorkflow/index.html.md)
-- [createShippingProfilesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createShippingProfilesWorkflow/index.html.md)
-- [markFulfillmentAsDeliveredWorkflow](https://docs.medusajs.com/references/medusa-workflows/markFulfillmentAsDeliveredWorkflow/index.html.md)
-- [updateFulfillmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateFulfillmentWorkflow/index.html.md)
-- [updateShippingOptionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateShippingOptionsWorkflow/index.html.md)
-- [updateShippingProfilesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateShippingProfilesWorkflow/index.html.md)
-- [updateServiceZonesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateServiceZonesWorkflow/index.html.md)
-- [validateFulfillmentDeliverabilityStep](https://docs.medusajs.com/references/medusa-workflows/validateFulfillmentDeliverabilityStep/index.html.md)
+- [createDefaultsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createDefaultsWorkflow/index.html.md)
+- [createCustomerGroupsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCustomerGroupsWorkflow/index.html.md)
+- [deleteCustomerGroupsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteCustomerGroupsWorkflow/index.html.md)
+- [updateCustomerGroupsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateCustomerGroupsWorkflow/index.html.md)
+- [linkCustomerGroupsToCustomerWorkflow](https://docs.medusajs.com/references/medusa-workflows/linkCustomerGroupsToCustomerWorkflow/index.html.md)
+- [linkCustomersToCustomerGroupWorkflow](https://docs.medusajs.com/references/medusa-workflows/linkCustomersToCustomerGroupWorkflow/index.html.md)
- [batchInventoryItemLevelsWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchInventoryItemLevelsWorkflow/index.html.md)
- [bulkCreateDeleteLevelsWorkflow](https://docs.medusajs.com/references/medusa-workflows/bulkCreateDeleteLevelsWorkflow/index.html.md)
- [createInventoryItemsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createInventoryItemsWorkflow/index.html.md)
- [createInventoryLevelsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createInventoryLevelsWorkflow/index.html.md)
- [deleteInventoryItemWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteInventoryItemWorkflow/index.html.md)
- [deleteInventoryLevelsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteInventoryLevelsWorkflow/index.html.md)
-- [updateInventoryLevelsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateInventoryLevelsWorkflow/index.html.md)
- [updateInventoryItemsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateInventoryItemsWorkflow/index.html.md)
+- [updateInventoryLevelsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateInventoryLevelsWorkflow/index.html.md)
- [validateInventoryLevelsDelete](https://docs.medusajs.com/references/medusa-workflows/validateInventoryLevelsDelete/index.html.md)
-- [createInvitesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createInvitesWorkflow/index.html.md)
- [deleteInvitesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteInvitesWorkflow/index.html.md)
- [acceptInviteWorkflow](https://docs.medusajs.com/references/medusa-workflows/acceptInviteWorkflow/index.html.md)
+- [createInvitesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createInvitesWorkflow/index.html.md)
- [refreshInviteTokensWorkflow](https://docs.medusajs.com/references/medusa-workflows/refreshInviteTokensWorkflow/index.html.md)
+- [cancelFulfillmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelFulfillmentWorkflow/index.html.md)
+- [batchShippingOptionRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchShippingOptionRulesWorkflow/index.html.md)
+- [createFulfillmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/createFulfillmentWorkflow/index.html.md)
+- [calculateShippingOptionsPricesWorkflow](https://docs.medusajs.com/references/medusa-workflows/calculateShippingOptionsPricesWorkflow/index.html.md)
+- [createReturnFulfillmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/createReturnFulfillmentWorkflow/index.html.md)
+- [createServiceZonesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createServiceZonesWorkflow/index.html.md)
+- [createShipmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/createShipmentWorkflow/index.html.md)
+- [createShippingProfilesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createShippingProfilesWorkflow/index.html.md)
+- [createShippingOptionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createShippingOptionsWorkflow/index.html.md)
+- [deleteFulfillmentSetsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteFulfillmentSetsWorkflow/index.html.md)
+- [deleteServiceZonesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteServiceZonesWorkflow/index.html.md)
+- [markFulfillmentAsDeliveredWorkflow](https://docs.medusajs.com/references/medusa-workflows/markFulfillmentAsDeliveredWorkflow/index.html.md)
+- [updateFulfillmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateFulfillmentWorkflow/index.html.md)
+- [deleteShippingOptionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteShippingOptionsWorkflow/index.html.md)
+- [updateServiceZonesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateServiceZonesWorkflow/index.html.md)
+- [updateShippingOptionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateShippingOptionsWorkflow/index.html.md)
+- [updateShippingProfilesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateShippingProfilesWorkflow/index.html.md)
+- [validateFulfillmentDeliverabilityStep](https://docs.medusajs.com/references/medusa-workflows/validateFulfillmentDeliverabilityStep/index.html.md)
- [deleteLineItemsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteLineItemsWorkflow/index.html.md)
+- [createLinksWorkflow](https://docs.medusajs.com/references/medusa-workflows/createLinksWorkflow/index.html.md)
+- [batchLinksWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchLinksWorkflow/index.html.md)
+- [dismissLinksWorkflow](https://docs.medusajs.com/references/medusa-workflows/dismissLinksWorkflow/index.html.md)
+- [updateLinksWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateLinksWorkflow/index.html.md)
- [capturePaymentWorkflow](https://docs.medusajs.com/references/medusa-workflows/capturePaymentWorkflow/index.html.md)
- [processPaymentWorkflow](https://docs.medusajs.com/references/medusa-workflows/processPaymentWorkflow/index.html.md)
-- [refundPaymentsWorkflow](https://docs.medusajs.com/references/medusa-workflows/refundPaymentsWorkflow/index.html.md)
- [refundPaymentWorkflow](https://docs.medusajs.com/references/medusa-workflows/refundPaymentWorkflow/index.html.md)
+- [refundPaymentsWorkflow](https://docs.medusajs.com/references/medusa-workflows/refundPaymentsWorkflow/index.html.md)
- [validatePaymentsRefundStep](https://docs.medusajs.com/references/medusa-workflows/validatePaymentsRefundStep/index.html.md)
- [validateRefundStep](https://docs.medusajs.com/references/medusa-workflows/validateRefundStep/index.html.md)
-- [createPaymentSessionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createPaymentSessionsWorkflow/index.html.md)
-- [createRefundReasonsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createRefundReasonsWorkflow/index.html.md)
-- [deletePaymentSessionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deletePaymentSessionsWorkflow/index.html.md)
-- [deleteRefundReasonsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteRefundReasonsWorkflow/index.html.md)
-- [updateRefundReasonsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateRefundReasonsWorkflow/index.html.md)
-- [createPriceListPricesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createPriceListPricesWorkflow/index.html.md)
- [batchPriceListPricesWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchPriceListPricesWorkflow/index.html.md)
+- [createPriceListPricesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createPriceListPricesWorkflow/index.html.md)
- [createPriceListsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createPriceListsWorkflow/index.html.md)
-- [deletePriceListsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deletePriceListsWorkflow/index.html.md)
- [removePriceListPricesWorkflow](https://docs.medusajs.com/references/medusa-workflows/removePriceListPricesWorkflow/index.html.md)
-- [updatePriceListsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updatePriceListsWorkflow/index.html.md)
+- [deletePriceListsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deletePriceListsWorkflow/index.html.md)
- [updatePriceListPricesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updatePriceListPricesWorkflow/index.html.md)
+- [updatePriceListsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updatePriceListsWorkflow/index.html.md)
- [acceptOrderTransferValidationStep](https://docs.medusajs.com/references/medusa-workflows/acceptOrderTransferValidationStep/index.html.md)
- [acceptOrderTransferWorkflow](https://docs.medusajs.com/references/medusa-workflows/acceptOrderTransferWorkflow/index.html.md)
- [addOrderLineItemsWorkflow](https://docs.medusajs.com/references/medusa-workflows/addOrderLineItemsWorkflow/index.html.md)
- [archiveOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/archiveOrderWorkflow/index.html.md)
- [beginClaimOrderValidationStep](https://docs.medusajs.com/references/medusa-workflows/beginClaimOrderValidationStep/index.html.md)
-- [beginClaimOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/beginClaimOrderWorkflow/index.html.md)
- [beginExchangeOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/beginExchangeOrderWorkflow/index.html.md)
+- [beginClaimOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/beginClaimOrderWorkflow/index.html.md)
- [beginOrderEditOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/beginOrderEditOrderWorkflow/index.html.md)
-- [beginOrderExchangeValidationStep](https://docs.medusajs.com/references/medusa-workflows/beginOrderExchangeValidationStep/index.html.md)
- [beginOrderEditValidationStep](https://docs.medusajs.com/references/medusa-workflows/beginOrderEditValidationStep/index.html.md)
+- [beginOrderExchangeValidationStep](https://docs.medusajs.com/references/medusa-workflows/beginOrderExchangeValidationStep/index.html.md)
- [beginReceiveReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/beginReceiveReturnValidationStep/index.html.md)
- [beginReceiveReturnWorkflow](https://docs.medusajs.com/references/medusa-workflows/beginReceiveReturnWorkflow/index.html.md)
-- [beginReturnOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/beginReturnOrderWorkflow/index.html.md)
- [beginReturnOrderValidationStep](https://docs.medusajs.com/references/medusa-workflows/beginReturnOrderValidationStep/index.html.md)
-- [cancelBeginOrderClaimValidationStep](https://docs.medusajs.com/references/medusa-workflows/cancelBeginOrderClaimValidationStep/index.html.md)
-- [cancelBeginOrderEditValidationStep](https://docs.medusajs.com/references/medusa-workflows/cancelBeginOrderEditValidationStep/index.html.md)
-- [cancelBeginOrderEditWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelBeginOrderEditWorkflow/index.html.md)
+- [beginReturnOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/beginReturnOrderWorkflow/index.html.md)
- [cancelBeginOrderClaimWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelBeginOrderClaimWorkflow/index.html.md)
-- [cancelBeginOrderExchangeValidationStep](https://docs.medusajs.com/references/medusa-workflows/cancelBeginOrderExchangeValidationStep/index.html.md)
+- [cancelBeginOrderEditValidationStep](https://docs.medusajs.com/references/medusa-workflows/cancelBeginOrderEditValidationStep/index.html.md)
+- [cancelBeginOrderClaimValidationStep](https://docs.medusajs.com/references/medusa-workflows/cancelBeginOrderClaimValidationStep/index.html.md)
+- [cancelBeginOrderEditWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelBeginOrderEditWorkflow/index.html.md)
- [cancelBeginOrderExchangeWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelBeginOrderExchangeWorkflow/index.html.md)
+- [cancelBeginOrderExchangeValidationStep](https://docs.medusajs.com/references/medusa-workflows/cancelBeginOrderExchangeValidationStep/index.html.md)
- [cancelClaimValidateOrderStep](https://docs.medusajs.com/references/medusa-workflows/cancelClaimValidateOrderStep/index.html.md)
- [cancelExchangeValidateOrder](https://docs.medusajs.com/references/medusa-workflows/cancelExchangeValidateOrder/index.html.md)
- [cancelOrderChangeWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelOrderChangeWorkflow/index.html.md)
- [cancelOrderClaimWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelOrderClaimWorkflow/index.html.md)
- [cancelOrderExchangeWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelOrderExchangeWorkflow/index.html.md)
-- [cancelOrderFulfillmentValidateOrder](https://docs.medusajs.com/references/medusa-workflows/cancelOrderFulfillmentValidateOrder/index.html.md)
- [cancelOrderFulfillmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelOrderFulfillmentWorkflow/index.html.md)
-- [cancelReceiveReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/cancelReceiveReturnValidationStep/index.html.md)
+- [cancelOrderFulfillmentValidateOrder](https://docs.medusajs.com/references/medusa-workflows/cancelOrderFulfillmentValidateOrder/index.html.md)
- [cancelOrderTransferRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelOrderTransferRequestWorkflow/index.html.md)
-- [cancelOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelOrderWorkflow/index.html.md)
- [cancelRequestReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/cancelRequestReturnValidationStep/index.html.md)
+- [cancelReceiveReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/cancelReceiveReturnValidationStep/index.html.md)
+- [cancelOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelOrderWorkflow/index.html.md)
- [cancelReturnReceiveWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelReturnReceiveWorkflow/index.html.md)
-- [cancelReturnValidateOrder](https://docs.medusajs.com/references/medusa-workflows/cancelReturnValidateOrder/index.html.md)
- [cancelReturnRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelReturnRequestWorkflow/index.html.md)
+- [cancelReturnValidateOrder](https://docs.medusajs.com/references/medusa-workflows/cancelReturnValidateOrder/index.html.md)
- [cancelReturnWorkflow](https://docs.medusajs.com/references/medusa-workflows/cancelReturnWorkflow/index.html.md)
-- [cancelValidateOrder](https://docs.medusajs.com/references/medusa-workflows/cancelValidateOrder/index.html.md)
- [cancelTransferOrderRequestValidationStep](https://docs.medusajs.com/references/medusa-workflows/cancelTransferOrderRequestValidationStep/index.html.md)
- [completeOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/completeOrderWorkflow/index.html.md)
+- [cancelValidateOrder](https://docs.medusajs.com/references/medusa-workflows/cancelValidateOrder/index.html.md)
- [confirmClaimRequestValidationStep](https://docs.medusajs.com/references/medusa-workflows/confirmClaimRequestValidationStep/index.html.md)
-- [confirmClaimRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/confirmClaimRequestWorkflow/index.html.md)
-- [confirmExchangeRequestValidationStep](https://docs.medusajs.com/references/medusa-workflows/confirmExchangeRequestValidationStep/index.html.md)
- [confirmExchangeRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/confirmExchangeRequestWorkflow/index.html.md)
+- [confirmExchangeRequestValidationStep](https://docs.medusajs.com/references/medusa-workflows/confirmExchangeRequestValidationStep/index.html.md)
+- [confirmClaimRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/confirmClaimRequestWorkflow/index.html.md)
- [confirmOrderEditRequestValidationStep](https://docs.medusajs.com/references/medusa-workflows/confirmOrderEditRequestValidationStep/index.html.md)
-- [confirmOrderEditRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/confirmOrderEditRequestWorkflow/index.html.md)
- [confirmReceiveReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/confirmReceiveReturnValidationStep/index.html.md)
+- [confirmOrderEditRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/confirmOrderEditRequestWorkflow/index.html.md)
- [confirmReturnReceiveWorkflow](https://docs.medusajs.com/references/medusa-workflows/confirmReturnReceiveWorkflow/index.html.md)
- [confirmReturnRequestValidationStep](https://docs.medusajs.com/references/medusa-workflows/confirmReturnRequestValidationStep/index.html.md)
- [confirmReturnRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/confirmReturnRequestWorkflow/index.html.md)
-- [createAndCompleteReturnOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/createAndCompleteReturnOrderWorkflow/index.html.md)
- [createClaimShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/createClaimShippingMethodValidationStep/index.html.md)
+- [createAndCompleteReturnOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/createAndCompleteReturnOrderWorkflow/index.html.md)
- [createClaimShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/createClaimShippingMethodWorkflow/index.html.md)
-- [createCompleteReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/createCompleteReturnValidationStep/index.html.md)
-- [createExchangeShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/createExchangeShippingMethodWorkflow/index.html.md)
- [createExchangeShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/createExchangeShippingMethodValidationStep/index.html.md)
+- [createExchangeShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/createExchangeShippingMethodWorkflow/index.html.md)
+- [createCompleteReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/createCompleteReturnValidationStep/index.html.md)
- [createFulfillmentValidateOrder](https://docs.medusajs.com/references/medusa-workflows/createFulfillmentValidateOrder/index.html.md)
- [createOrUpdateOrderPaymentCollectionWorkflow](https://docs.medusajs.com/references/medusa-workflows/createOrUpdateOrderPaymentCollectionWorkflow/index.html.md)
-- [createOrderChangeActionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createOrderChangeActionsWorkflow/index.html.md)
- [createOrderChangeWorkflow](https://docs.medusajs.com/references/medusa-workflows/createOrderChangeWorkflow/index.html.md)
+- [createOrderChangeActionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createOrderChangeActionsWorkflow/index.html.md)
- [createOrderEditShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/createOrderEditShippingMethodValidationStep/index.html.md)
-- [createOrderFulfillmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/createOrderFulfillmentWorkflow/index.html.md)
- [createOrderEditShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/createOrderEditShippingMethodWorkflow/index.html.md)
- [createOrderPaymentCollectionWorkflow](https://docs.medusajs.com/references/medusa-workflows/createOrderPaymentCollectionWorkflow/index.html.md)
+- [createOrderFulfillmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/createOrderFulfillmentWorkflow/index.html.md)
- [createOrderShipmentWorkflow](https://docs.medusajs.com/references/medusa-workflows/createOrderShipmentWorkflow/index.html.md)
-- [createReturnShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/createReturnShippingMethodValidationStep/index.html.md)
-- [createReturnShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/createReturnShippingMethodWorkflow/index.html.md)
- [createOrdersWorkflow](https://docs.medusajs.com/references/medusa-workflows/createOrdersWorkflow/index.html.md)
+- [createReturnShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/createReturnShippingMethodValidationStep/index.html.md)
- [createOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/createOrderWorkflow/index.html.md)
-- [createShipmentValidateOrder](https://docs.medusajs.com/references/medusa-workflows/createShipmentValidateOrder/index.html.md)
+- [createReturnShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/createReturnShippingMethodWorkflow/index.html.md)
- [declineOrderChangeWorkflow](https://docs.medusajs.com/references/medusa-workflows/declineOrderChangeWorkflow/index.html.md)
- [declineOrderTransferRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/declineOrderTransferRequestWorkflow/index.html.md)
+- [createShipmentValidateOrder](https://docs.medusajs.com/references/medusa-workflows/createShipmentValidateOrder/index.html.md)
- [declineTransferOrderRequestValidationStep](https://docs.medusajs.com/references/medusa-workflows/declineTransferOrderRequestValidationStep/index.html.md)
- [deleteOrderChangeActionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteOrderChangeActionsWorkflow/index.html.md)
-- [deleteOrderChangeWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteOrderChangeWorkflow/index.html.md)
- [deleteOrderPaymentCollections](https://docs.medusajs.com/references/medusa-workflows/deleteOrderPaymentCollections/index.html.md)
+- [deleteOrderChangeWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteOrderChangeWorkflow/index.html.md)
- [dismissItemReturnRequestValidationStep](https://docs.medusajs.com/references/medusa-workflows/dismissItemReturnRequestValidationStep/index.html.md)
- [dismissItemReturnRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/dismissItemReturnRequestWorkflow/index.html.md)
- [exchangeAddNewItemValidationStep](https://docs.medusajs.com/references/medusa-workflows/exchangeAddNewItemValidationStep/index.html.md)
-- [getOrderDetailWorkflow](https://docs.medusajs.com/references/medusa-workflows/getOrderDetailWorkflow/index.html.md)
- [exchangeRequestItemReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/exchangeRequestItemReturnValidationStep/index.html.md)
+- [getOrderDetailWorkflow](https://docs.medusajs.com/references/medusa-workflows/getOrderDetailWorkflow/index.html.md)
- [getOrdersListWorkflow](https://docs.medusajs.com/references/medusa-workflows/getOrdersListWorkflow/index.html.md)
- [markOrderFulfillmentAsDeliveredWorkflow](https://docs.medusajs.com/references/medusa-workflows/markOrderFulfillmentAsDeliveredWorkflow/index.html.md)
- [markPaymentCollectionAsPaid](https://docs.medusajs.com/references/medusa-workflows/markPaymentCollectionAsPaid/index.html.md)
@@ -28780,300 +29534,305 @@ The [Authenticate or Login API Route](https://docs.medusajs.com/Users/shahednass
- [orderClaimRequestItemReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/orderClaimRequestItemReturnValidationStep/index.html.md)
- [orderClaimRequestItemReturnWorkflow](https://docs.medusajs.com/references/medusa-workflows/orderClaimRequestItemReturnWorkflow/index.html.md)
- [orderEditAddNewItemValidationStep](https://docs.medusajs.com/references/medusa-workflows/orderEditAddNewItemValidationStep/index.html.md)
-- [orderEditUpdateItemQuantityValidationStep](https://docs.medusajs.com/references/medusa-workflows/orderEditUpdateItemQuantityValidationStep/index.html.md)
- [orderEditAddNewItemWorkflow](https://docs.medusajs.com/references/medusa-workflows/orderEditAddNewItemWorkflow/index.html.md)
+- [orderEditUpdateItemQuantityValidationStep](https://docs.medusajs.com/references/medusa-workflows/orderEditUpdateItemQuantityValidationStep/index.html.md)
- [orderExchangeAddNewItemWorkflow](https://docs.medusajs.com/references/medusa-workflows/orderExchangeAddNewItemWorkflow/index.html.md)
-- [orderFulfillmentDeliverablilityValidationStep](https://docs.medusajs.com/references/medusa-workflows/orderFulfillmentDeliverablilityValidationStep/index.html.md)
-- [orderEditUpdateItemQuantityWorkflow](https://docs.medusajs.com/references/medusa-workflows/orderEditUpdateItemQuantityWorkflow/index.html.md)
- [orderExchangeRequestItemReturnWorkflow](https://docs.medusajs.com/references/medusa-workflows/orderExchangeRequestItemReturnWorkflow/index.html.md)
+- [orderEditUpdateItemQuantityWorkflow](https://docs.medusajs.com/references/medusa-workflows/orderEditUpdateItemQuantityWorkflow/index.html.md)
+- [orderFulfillmentDeliverablilityValidationStep](https://docs.medusajs.com/references/medusa-workflows/orderFulfillmentDeliverablilityValidationStep/index.html.md)
- [receiveAndCompleteReturnOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/receiveAndCompleteReturnOrderWorkflow/index.html.md)
- [receiveCompleteReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/receiveCompleteReturnValidationStep/index.html.md)
- [receiveItemReturnRequestValidationStep](https://docs.medusajs.com/references/medusa-workflows/receiveItemReturnRequestValidationStep/index.html.md)
- [receiveItemReturnRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/receiveItemReturnRequestWorkflow/index.html.md)
-- [removeAddItemClaimActionWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeAddItemClaimActionWorkflow/index.html.md)
- [removeClaimAddItemActionValidationStep](https://docs.medusajs.com/references/medusa-workflows/removeClaimAddItemActionValidationStep/index.html.md)
- [removeClaimItemActionValidationStep](https://docs.medusajs.com/references/medusa-workflows/removeClaimItemActionValidationStep/index.html.md)
-- [removeClaimShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeClaimShippingMethodWorkflow/index.html.md)
+- [removeAddItemClaimActionWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeAddItemClaimActionWorkflow/index.html.md)
- [removeClaimShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/removeClaimShippingMethodValidationStep/index.html.md)
+- [removeClaimShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeClaimShippingMethodWorkflow/index.html.md)
- [removeExchangeItemActionValidationStep](https://docs.medusajs.com/references/medusa-workflows/removeExchangeItemActionValidationStep/index.html.md)
- [removeExchangeShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/removeExchangeShippingMethodValidationStep/index.html.md)
-- [removeItemClaimActionWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeItemClaimActionWorkflow/index.html.md)
-- [removeItemExchangeActionWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeItemExchangeActionWorkflow/index.html.md)
- [removeExchangeShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeExchangeShippingMethodWorkflow/index.html.md)
+- [removeItemClaimActionWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeItemClaimActionWorkflow/index.html.md)
- [removeItemOrderEditActionWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeItemOrderEditActionWorkflow/index.html.md)
+- [removeItemExchangeActionWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeItemExchangeActionWorkflow/index.html.md)
- [removeItemReceiveReturnActionValidationStep](https://docs.medusajs.com/references/medusa-workflows/removeItemReceiveReturnActionValidationStep/index.html.md)
-- [removeItemReceiveReturnActionWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeItemReceiveReturnActionWorkflow/index.html.md)
- [removeOrderEditItemActionValidationStep](https://docs.medusajs.com/references/medusa-workflows/removeOrderEditItemActionValidationStep/index.html.md)
- [removeItemReturnActionWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeItemReturnActionWorkflow/index.html.md)
+- [removeItemReceiveReturnActionWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeItemReceiveReturnActionWorkflow/index.html.md)
- [removeOrderEditShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/removeOrderEditShippingMethodValidationStep/index.html.md)
- [removeOrderEditShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeOrderEditShippingMethodWorkflow/index.html.md)
- [removeReturnItemActionValidationStep](https://docs.medusajs.com/references/medusa-workflows/removeReturnItemActionValidationStep/index.html.md)
- [removeReturnShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/removeReturnShippingMethodValidationStep/index.html.md)
-- [requestItemReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/requestItemReturnValidationStep/index.html.md)
- [removeReturnShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeReturnShippingMethodWorkflow/index.html.md)
-- [requestItemReturnWorkflow](https://docs.medusajs.com/references/medusa-workflows/requestItemReturnWorkflow/index.html.md)
+- [requestItemReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/requestItemReturnValidationStep/index.html.md)
- [requestOrderEditRequestValidationStep](https://docs.medusajs.com/references/medusa-workflows/requestOrderEditRequestValidationStep/index.html.md)
-- [requestOrderTransferValidationStep](https://docs.medusajs.com/references/medusa-workflows/requestOrderTransferValidationStep/index.html.md)
+- [requestItemReturnWorkflow](https://docs.medusajs.com/references/medusa-workflows/requestItemReturnWorkflow/index.html.md)
- [requestOrderEditRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/requestOrderEditRequestWorkflow/index.html.md)
- [requestOrderTransferWorkflow](https://docs.medusajs.com/references/medusa-workflows/requestOrderTransferWorkflow/index.html.md)
+- [requestOrderTransferValidationStep](https://docs.medusajs.com/references/medusa-workflows/requestOrderTransferValidationStep/index.html.md)
- [throwUnlessPaymentCollectionNotPaid](https://docs.medusajs.com/references/medusa-workflows/throwUnlessPaymentCollectionNotPaid/index.html.md)
-- [updateClaimAddItemValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateClaimAddItemValidationStep/index.html.md)
- [throwUnlessStatusIsNotPaid](https://docs.medusajs.com/references/medusa-workflows/throwUnlessStatusIsNotPaid/index.html.md)
+- [updateClaimAddItemValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateClaimAddItemValidationStep/index.html.md)
- [updateClaimItemValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateClaimItemValidationStep/index.html.md)
- [updateClaimAddItemWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateClaimAddItemWorkflow/index.html.md)
- [updateClaimItemWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateClaimItemWorkflow/index.html.md)
-- [updateClaimShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateClaimShippingMethodValidationStep/index.html.md)
- [updateClaimShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateClaimShippingMethodWorkflow/index.html.md)
- [updateExchangeAddItemValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateExchangeAddItemValidationStep/index.html.md)
+- [updateClaimShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateClaimShippingMethodValidationStep/index.html.md)
- [updateExchangeAddItemWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateExchangeAddItemWorkflow/index.html.md)
-- [updateExchangeShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateExchangeShippingMethodWorkflow/index.html.md)
- [updateExchangeShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateExchangeShippingMethodValidationStep/index.html.md)
+- [updateExchangeShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateExchangeShippingMethodWorkflow/index.html.md)
- [updateOrderChangeActionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateOrderChangeActionsWorkflow/index.html.md)
-- [updateOrderEditAddItemWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateOrderEditAddItemWorkflow/index.html.md)
-- [updateOrderEditAddItemValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateOrderEditAddItemValidationStep/index.html.md)
-- [updateOrderEditItemQuantityValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateOrderEditItemQuantityValidationStep/index.html.md)
- [updateOrderChangesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateOrderChangesWorkflow/index.html.md)
+- [updateOrderEditAddItemWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateOrderEditAddItemWorkflow/index.html.md)
+- [updateOrderEditItemQuantityValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateOrderEditItemQuantityValidationStep/index.html.md)
+- [updateOrderEditAddItemValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateOrderEditAddItemValidationStep/index.html.md)
- [updateOrderEditItemQuantityWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateOrderEditItemQuantityWorkflow/index.html.md)
- [updateOrderEditShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateOrderEditShippingMethodWorkflow/index.html.md)
- [updateOrderTaxLinesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateOrderTaxLinesWorkflow/index.html.md)
-- [updateOrderValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateOrderValidationStep/index.html.md)
- [updateOrderEditShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateOrderEditShippingMethodValidationStep/index.html.md)
+- [updateOrderValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateOrderValidationStep/index.html.md)
- [updateOrderWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateOrderWorkflow/index.html.md)
-- [updateReceiveItemReturnRequestValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateReceiveItemReturnRequestValidationStep/index.html.md)
- [updateReceiveItemReturnRequestWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateReceiveItemReturnRequestWorkflow/index.html.md)
+- [updateReceiveItemReturnRequestValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateReceiveItemReturnRequestValidationStep/index.html.md)
- [updateRequestItemReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateRequestItemReturnValidationStep/index.html.md)
- [updateRequestItemReturnWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateRequestItemReturnWorkflow/index.html.md)
- [updateReturnShippingMethodValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateReturnShippingMethodValidationStep/index.html.md)
- [updateReturnShippingMethodWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateReturnShippingMethodWorkflow/index.html.md)
- [updateReturnValidationStep](https://docs.medusajs.com/references/medusa-workflows/updateReturnValidationStep/index.html.md)
- [updateReturnWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateReturnWorkflow/index.html.md)
+- [createPaymentSessionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createPaymentSessionsWorkflow/index.html.md)
+- [createRefundReasonsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createRefundReasonsWorkflow/index.html.md)
+- [deletePaymentSessionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deletePaymentSessionsWorkflow/index.html.md)
+- [deleteRefundReasonsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteRefundReasonsWorkflow/index.html.md)
+- [updateRefundReasonsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateRefundReasonsWorkflow/index.html.md)
- [createPricePreferencesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createPricePreferencesWorkflow/index.html.md)
- [deletePricePreferencesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deletePricePreferencesWorkflow/index.html.md)
- [updatePricePreferencesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updatePricePreferencesWorkflow/index.html.md)
-- [batchLinkProductsToCategoryWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchLinkProductsToCategoryWorkflow/index.html.md)
+- [addOrRemoveCampaignPromotionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/addOrRemoveCampaignPromotionsWorkflow/index.html.md)
+- [batchPromotionRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchPromotionRulesWorkflow/index.html.md)
+- [createCampaignsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCampaignsWorkflow/index.html.md)
+- [createPromotionRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createPromotionRulesWorkflow/index.html.md)
+- [deleteCampaignsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteCampaignsWorkflow/index.html.md)
+- [createPromotionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createPromotionsWorkflow/index.html.md)
+- [deletePromotionRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deletePromotionRulesWorkflow/index.html.md)
+- [updatePromotionRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updatePromotionRulesWorkflow/index.html.md)
+- [updateCampaignsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateCampaignsWorkflow/index.html.md)
+- [deletePromotionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deletePromotionsWorkflow/index.html.md)
+- [updatePromotionsStatusWorkflow](https://docs.medusajs.com/references/medusa-workflows/updatePromotionsStatusWorkflow/index.html.md)
+- [updatePromotionsValidationStep](https://docs.medusajs.com/references/medusa-workflows/updatePromotionsValidationStep/index.html.md)
+- [updatePromotionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updatePromotionsWorkflow/index.html.md)
- [batchProductVariantsWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchProductVariantsWorkflow/index.html.md)
-- [createCollectionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCollectionsWorkflow/index.html.md)
- [batchLinkProductsToCollectionWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchLinkProductsToCollectionWorkflow/index.html.md)
+- [batchLinkProductsToCategoryWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchLinkProductsToCategoryWorkflow/index.html.md)
- [batchProductsWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchProductsWorkflow/index.html.md)
- [createProductOptionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createProductOptionsWorkflow/index.html.md)
- [createProductTagsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createProductTagsWorkflow/index.html.md)
+- [createCollectionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCollectionsWorkflow/index.html.md)
- [createProductTypesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createProductTypesWorkflow/index.html.md)
-- [createProductVariantsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createProductVariantsWorkflow/index.html.md)
- [createProductsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createProductsWorkflow/index.html.md)
- [deleteCollectionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteCollectionsWorkflow/index.html.md)
+- [createProductVariantsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createProductVariantsWorkflow/index.html.md)
- [deleteProductOptionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteProductOptionsWorkflow/index.html.md)
- [deleteProductTagsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteProductTagsWorkflow/index.html.md)
-- [deleteProductTypesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteProductTypesWorkflow/index.html.md)
- [deleteProductVariantsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteProductVariantsWorkflow/index.html.md)
+- [deleteProductTypesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteProductTypesWorkflow/index.html.md)
- [deleteProductsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteProductsWorkflow/index.html.md)
-- [exportProductsWorkflow](https://docs.medusajs.com/references/medusa-workflows/exportProductsWorkflow/index.html.md)
- [importProductsWorkflow](https://docs.medusajs.com/references/medusa-workflows/importProductsWorkflow/index.html.md)
+- [exportProductsWorkflow](https://docs.medusajs.com/references/medusa-workflows/exportProductsWorkflow/index.html.md)
- [updateCollectionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateCollectionsWorkflow/index.html.md)
- [updateProductOptionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateProductOptionsWorkflow/index.html.md)
-- [updateProductTypesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateProductTypesWorkflow/index.html.md)
- [updateProductTagsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateProductTagsWorkflow/index.html.md)
-- [updateProductsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateProductsWorkflow/index.html.md)
- [updateProductVariantsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateProductVariantsWorkflow/index.html.md)
+- [updateProductTypesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateProductTypesWorkflow/index.html.md)
+- [updateProductsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateProductsWorkflow/index.html.md)
- [upsertVariantPricesWorkflow](https://docs.medusajs.com/references/medusa-workflows/upsertVariantPricesWorkflow/index.html.md)
- [validateProductInputStep](https://docs.medusajs.com/references/medusa-workflows/validateProductInputStep/index.html.md)
- [createProductCategoriesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createProductCategoriesWorkflow/index.html.md)
- [deleteProductCategoriesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteProductCategoriesWorkflow/index.html.md)
- [updateProductCategoriesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateProductCategoriesWorkflow/index.html.md)
-- [addOrRemoveCampaignPromotionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/addOrRemoveCampaignPromotionsWorkflow/index.html.md)
-- [batchPromotionRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/batchPromotionRulesWorkflow/index.html.md)
-- [createCampaignsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createCampaignsWorkflow/index.html.md)
-- [createPromotionRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createPromotionRulesWorkflow/index.html.md)
-- [createPromotionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createPromotionsWorkflow/index.html.md)
-- [deleteCampaignsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteCampaignsWorkflow/index.html.md)
-- [deletePromotionRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deletePromotionRulesWorkflow/index.html.md)
-- [deletePromotionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deletePromotionsWorkflow/index.html.md)
-- [updateCampaignsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateCampaignsWorkflow/index.html.md)
-- [updatePromotionsStatusWorkflow](https://docs.medusajs.com/references/medusa-workflows/updatePromotionsStatusWorkflow/index.html.md)
-- [updatePromotionRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updatePromotionRulesWorkflow/index.html.md)
-- [updatePromotionsValidationStep](https://docs.medusajs.com/references/medusa-workflows/updatePromotionsValidationStep/index.html.md)
-- [updatePromotionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updatePromotionsWorkflow/index.html.md)
+- [createRegionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createRegionsWorkflow/index.html.md)
+- [deleteRegionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteRegionsWorkflow/index.html.md)
+- [updateRegionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateRegionsWorkflow/index.html.md)
+- [createReservationsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createReservationsWorkflow/index.html.md)
- [deleteReservationsByLineItemsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteReservationsByLineItemsWorkflow/index.html.md)
- [deleteReservationsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteReservationsWorkflow/index.html.md)
-- [createReservationsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createReservationsWorkflow/index.html.md)
- [updateReservationsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateReservationsWorkflow/index.html.md)
- [createReturnReasonsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createReturnReasonsWorkflow/index.html.md)
-- [deleteReturnReasonsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteReturnReasonsWorkflow/index.html.md)
- [updateReturnReasonsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateReturnReasonsWorkflow/index.html.md)
-- [deleteRegionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteRegionsWorkflow/index.html.md)
-- [createRegionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createRegionsWorkflow/index.html.md)
-- [updateRegionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateRegionsWorkflow/index.html.md)
+- [deleteReturnReasonsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteReturnReasonsWorkflow/index.html.md)
- [createSalesChannelsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createSalesChannelsWorkflow/index.html.md)
-- [deleteSalesChannelsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteSalesChannelsWorkflow/index.html.md)
- [linkProductsToSalesChannelWorkflow](https://docs.medusajs.com/references/medusa-workflows/linkProductsToSalesChannelWorkflow/index.html.md)
+- [deleteSalesChannelsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteSalesChannelsWorkflow/index.html.md)
- [updateSalesChannelsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateSalesChannelsWorkflow/index.html.md)
-- [validateStepShippingProfileDelete](https://docs.medusajs.com/references/medusa-workflows/validateStepShippingProfileDelete/index.html.md)
- [deleteShippingProfileWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteShippingProfileWorkflow/index.html.md)
-- [createStockLocationsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createStockLocationsWorkflow/index.html.md)
+- [validateStepShippingProfileDelete](https://docs.medusajs.com/references/medusa-workflows/validateStepShippingProfileDelete/index.html.md)
- [createLocationFulfillmentSetWorkflow](https://docs.medusajs.com/references/medusa-workflows/createLocationFulfillmentSetWorkflow/index.html.md)
+- [createStockLocationsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createStockLocationsWorkflow/index.html.md)
- [deleteStockLocationsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteStockLocationsWorkflow/index.html.md)
- [linkSalesChannelsToStockLocationWorkflow](https://docs.medusajs.com/references/medusa-workflows/linkSalesChannelsToStockLocationWorkflow/index.html.md)
- [updateStockLocationsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateStockLocationsWorkflow/index.html.md)
- [createStoresWorkflow](https://docs.medusajs.com/references/medusa-workflows/createStoresWorkflow/index.html.md)
-- [deleteStoresWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteStoresWorkflow/index.html.md)
- [updateStoresWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateStoresWorkflow/index.html.md)
+- [deleteStoresWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteStoresWorkflow/index.html.md)
- [createTaxRateRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createTaxRateRulesWorkflow/index.html.md)
-- [deleteTaxRateRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteTaxRateRulesWorkflow/index.html.md)
-- [createTaxRegionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createTaxRegionsWorkflow/index.html.md)
- [createTaxRatesWorkflow](https://docs.medusajs.com/references/medusa-workflows/createTaxRatesWorkflow/index.html.md)
+- [createTaxRegionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createTaxRegionsWorkflow/index.html.md)
+- [deleteTaxRateRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteTaxRateRulesWorkflow/index.html.md)
- [deleteTaxRatesWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteTaxRatesWorkflow/index.html.md)
- [deleteTaxRegionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteTaxRegionsWorkflow/index.html.md)
- [maybeListTaxRateRuleIdsStep](https://docs.medusajs.com/references/medusa-workflows/maybeListTaxRateRuleIdsStep/index.html.md)
- [setTaxRateRulesWorkflow](https://docs.medusajs.com/references/medusa-workflows/setTaxRateRulesWorkflow/index.html.md)
- [updateTaxRatesWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateTaxRatesWorkflow/index.html.md)
- [updateTaxRegionsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateTaxRegionsWorkflow/index.html.md)
-- [createUserAccountWorkflow](https://docs.medusajs.com/references/medusa-workflows/createUserAccountWorkflow/index.html.md)
- [createUsersWorkflow](https://docs.medusajs.com/references/medusa-workflows/createUsersWorkflow/index.html.md)
- [deleteUsersWorkflow](https://docs.medusajs.com/references/medusa-workflows/deleteUsersWorkflow/index.html.md)
-- [updateUsersWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateUsersWorkflow/index.html.md)
+- [createUserAccountWorkflow](https://docs.medusajs.com/references/medusa-workflows/createUserAccountWorkflow/index.html.md)
- [removeUserAccountWorkflow](https://docs.medusajs.com/references/medusa-workflows/removeUserAccountWorkflow/index.html.md)
+- [updateUsersWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateUsersWorkflow/index.html.md)
## Steps
+- [deleteApiKeysStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteApiKeysStep/index.html.md)
+- [linkSalesChannelsToApiKeyStep](https://docs.medusajs.com/references/medusa-workflows/steps/linkSalesChannelsToApiKeyStep/index.html.md)
+- [revokeApiKeysStep](https://docs.medusajs.com/references/medusa-workflows/steps/revokeApiKeysStep/index.html.md)
+- [createApiKeysStep](https://docs.medusajs.com/references/medusa-workflows/steps/createApiKeysStep/index.html.md)
+- [validateSalesChannelsExistStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateSalesChannelsExistStep/index.html.md)
+- [updateApiKeysStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateApiKeysStep/index.html.md)
+- [setAuthAppMetadataStep](https://docs.medusajs.com/references/medusa-workflows/steps/setAuthAppMetadataStep/index.html.md)
- [createRemoteLinkStep](https://docs.medusajs.com/references/medusa-workflows/steps/createRemoteLinkStep/index.html.md)
- [dismissRemoteLinkStep](https://docs.medusajs.com/references/medusa-workflows/steps/dismissRemoteLinkStep/index.html.md)
-- [removeRemoteLinkStep](https://docs.medusajs.com/references/medusa-workflows/steps/removeRemoteLinkStep/index.html.md)
- [emitEventStep](https://docs.medusajs.com/references/medusa-workflows/steps/emitEventStep/index.html.md)
-- [useRemoteQueryStep](https://docs.medusajs.com/references/medusa-workflows/steps/useRemoteQueryStep/index.html.md)
-- [useQueryGraphStep](https://docs.medusajs.com/references/medusa-workflows/steps/useQueryGraphStep/index.html.md)
- [updateRemoteLinksStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateRemoteLinksStep/index.html.md)
+- [useQueryGraphStep](https://docs.medusajs.com/references/medusa-workflows/steps/useQueryGraphStep/index.html.md)
+- [useRemoteQueryStep](https://docs.medusajs.com/references/medusa-workflows/steps/useRemoteQueryStep/index.html.md)
+- [removeRemoteLinkStep](https://docs.medusajs.com/references/medusa-workflows/steps/removeRemoteLinkStep/index.html.md)
- [validatePresenceOfStep](https://docs.medusajs.com/references/medusa-workflows/steps/validatePresenceOfStep/index.html.md)
- [addShippingMethodToCartStep](https://docs.medusajs.com/references/medusa-workflows/steps/addShippingMethodToCartStep/index.html.md)
- [createCartsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createCartsStep/index.html.md)
- [createLineItemAdjustmentsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createLineItemAdjustmentsStep/index.html.md)
-- [confirmInventoryStep](https://docs.medusajs.com/references/medusa-workflows/steps/confirmInventoryStep/index.html.md)
- [createLineItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createLineItemsStep/index.html.md)
- [createPaymentCollectionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createPaymentCollectionsStep/index.html.md)
- [createShippingMethodAdjustmentsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createShippingMethodAdjustmentsStep/index.html.md)
- [findOneOrAnyRegionStep](https://docs.medusajs.com/references/medusa-workflows/steps/findOneOrAnyRegionStep/index.html.md)
-- [findOrCreateCustomerStep](https://docs.medusajs.com/references/medusa-workflows/steps/findOrCreateCustomerStep/index.html.md)
- [findSalesChannelStep](https://docs.medusajs.com/references/medusa-workflows/steps/findSalesChannelStep/index.html.md)
+- [findOrCreateCustomerStep](https://docs.medusajs.com/references/medusa-workflows/steps/findOrCreateCustomerStep/index.html.md)
+- [confirmInventoryStep](https://docs.medusajs.com/references/medusa-workflows/steps/confirmInventoryStep/index.html.md)
- [getActionsToComputeFromPromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/getActionsToComputeFromPromotionsStep/index.html.md)
- [getLineItemActionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/getLineItemActionsStep/index.html.md)
-- [getPromotionCodesToApply](https://docs.medusajs.com/references/medusa-workflows/steps/getPromotionCodesToApply/index.html.md)
- [getVariantPriceSetsStep](https://docs.medusajs.com/references/medusa-workflows/steps/getVariantPriceSetsStep/index.html.md)
- [getVariantsStep](https://docs.medusajs.com/references/medusa-workflows/steps/getVariantsStep/index.html.md)
- [prepareAdjustmentsFromPromotionActionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/prepareAdjustmentsFromPromotionActionsStep/index.html.md)
+- [getPromotionCodesToApply](https://docs.medusajs.com/references/medusa-workflows/steps/getPromotionCodesToApply/index.html.md)
- [removeLineItemAdjustmentsStep](https://docs.medusajs.com/references/medusa-workflows/steps/removeLineItemAdjustmentsStep/index.html.md)
-- [removeShippingMethodAdjustmentsStep](https://docs.medusajs.com/references/medusa-workflows/steps/removeShippingMethodAdjustmentsStep/index.html.md)
- [removeShippingMethodFromCartStep](https://docs.medusajs.com/references/medusa-workflows/steps/removeShippingMethodFromCartStep/index.html.md)
+- [removeShippingMethodAdjustmentsStep](https://docs.medusajs.com/references/medusa-workflows/steps/removeShippingMethodAdjustmentsStep/index.html.md)
- [reserveInventoryStep](https://docs.medusajs.com/references/medusa-workflows/steps/reserveInventoryStep/index.html.md)
-- [retrieveCartStep](https://docs.medusajs.com/references/medusa-workflows/steps/retrieveCartStep/index.html.md)
- [setTaxLinesForItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/setTaxLinesForItemsStep/index.html.md)
-- [updateCartPromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateCartPromotionsStep/index.html.md)
+- [retrieveCartStep](https://docs.medusajs.com/references/medusa-workflows/steps/retrieveCartStep/index.html.md)
- [updateCartsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateCartsStep/index.html.md)
+- [updateShippingMethodsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateShippingMethodsStep/index.html.md)
- [updateLineItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateLineItemsStep/index.html.md)
+- [updateCartPromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateCartPromotionsStep/index.html.md)
- [validateAndReturnShippingMethodsDataStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateAndReturnShippingMethodsDataStep/index.html.md)
- [validateCartPaymentsStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateCartPaymentsStep/index.html.md)
- [validateCartShippingOptionsPriceStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateCartShippingOptionsPriceStep/index.html.md)
-- [updateShippingMethodsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateShippingMethodsStep/index.html.md)
- [validateCartShippingOptionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateCartShippingOptionsStep/index.html.md)
- [validateLineItemPricesStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateLineItemPricesStep/index.html.md)
-- [validateCartStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateCartStep/index.html.md)
- [validateShippingStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateShippingStep/index.html.md)
- [validateVariantPricesStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateVariantPricesStep/index.html.md)
-- [createApiKeysStep](https://docs.medusajs.com/references/medusa-workflows/steps/createApiKeysStep/index.html.md)
-- [deleteApiKeysStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteApiKeysStep/index.html.md)
-- [linkSalesChannelsToApiKeyStep](https://docs.medusajs.com/references/medusa-workflows/steps/linkSalesChannelsToApiKeyStep/index.html.md)
-- [revokeApiKeysStep](https://docs.medusajs.com/references/medusa-workflows/steps/revokeApiKeysStep/index.html.md)
-- [validateSalesChannelsExistStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateSalesChannelsExistStep/index.html.md)
-- [updateApiKeysStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateApiKeysStep/index.html.md)
-- [setAuthAppMetadataStep](https://docs.medusajs.com/references/medusa-workflows/steps/setAuthAppMetadataStep/index.html.md)
+- [validateCartStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateCartStep/index.html.md)
- [createCustomerAddressesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createCustomerAddressesStep/index.html.md)
- [createCustomersStep](https://docs.medusajs.com/references/medusa-workflows/steps/createCustomersStep/index.html.md)
- [deleteCustomerAddressesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteCustomerAddressesStep/index.html.md)
+- [maybeUnsetDefaultShippingAddressesStep](https://docs.medusajs.com/references/medusa-workflows/steps/maybeUnsetDefaultShippingAddressesStep/index.html.md)
- [maybeUnsetDefaultBillingAddressesStep](https://docs.medusajs.com/references/medusa-workflows/steps/maybeUnsetDefaultBillingAddressesStep/index.html.md)
- [deleteCustomersStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteCustomersStep/index.html.md)
-- [updateCustomersStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateCustomersStep/index.html.md)
-- [maybeUnsetDefaultShippingAddressesStep](https://docs.medusajs.com/references/medusa-workflows/steps/maybeUnsetDefaultShippingAddressesStep/index.html.md)
- [updateCustomerAddressesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateCustomerAddressesStep/index.html.md)
+- [updateCustomersStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateCustomersStep/index.html.md)
- [validateCustomerAccountCreation](https://docs.medusajs.com/references/medusa-workflows/steps/validateCustomerAccountCreation/index.html.md)
-- [createCustomerGroupsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createCustomerGroupsStep/index.html.md)
- [deleteCustomerGroupStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteCustomerGroupStep/index.html.md)
-- [linkCustomerGroupsToCustomerStep](https://docs.medusajs.com/references/medusa-workflows/steps/linkCustomerGroupsToCustomerStep/index.html.md)
+- [createCustomerGroupsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createCustomerGroupsStep/index.html.md)
- [linkCustomersToCustomerGroupStep](https://docs.medusajs.com/references/medusa-workflows/steps/linkCustomersToCustomerGroupStep/index.html.md)
-- [updateCustomerGroupsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateCustomerGroupsStep/index.html.md)
+- [linkCustomerGroupsToCustomerStep](https://docs.medusajs.com/references/medusa-workflows/steps/linkCustomerGroupsToCustomerStep/index.html.md)
- [createDefaultStoreStep](https://docs.medusajs.com/references/medusa-workflows/steps/createDefaultStoreStep/index.html.md)
-- [adjustInventoryLevelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/adjustInventoryLevelsStep/index.html.md)
-- [attachInventoryItemToVariants](https://docs.medusajs.com/references/medusa-workflows/steps/attachInventoryItemToVariants/index.html.md)
-- [createInventoryItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createInventoryItemsStep/index.html.md)
-- [createInventoryLevelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createInventoryLevelsStep/index.html.md)
-- [deleteInventoryItemStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteInventoryItemStep/index.html.md)
-- [updateInventoryItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateInventoryItemsStep/index.html.md)
-- [deleteInventoryLevelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteInventoryLevelsStep/index.html.md)
-- [updateInventoryLevelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateInventoryLevelsStep/index.html.md)
-- [validateInventoryDeleteStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateInventoryDeleteStep/index.html.md)
-- [validateInventoryItemsForCreate](https://docs.medusajs.com/references/medusa-workflows/steps/validateInventoryItemsForCreate/index.html.md)
-- [validateInventoryLocationsStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateInventoryLocationsStep/index.html.md)
+- [updateCustomerGroupsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateCustomerGroupsStep/index.html.md)
- [deleteFilesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteFilesStep/index.html.md)
- [uploadFilesStep](https://docs.medusajs.com/references/medusa-workflows/steps/uploadFilesStep/index.html.md)
- [buildPriceSet](https://docs.medusajs.com/references/medusa-workflows/steps/buildPriceSet/index.html.md)
-- [cancelFulfillmentStep](https://docs.medusajs.com/references/medusa-workflows/steps/cancelFulfillmentStep/index.html.md)
- [calculateShippingOptionsPricesStep](https://docs.medusajs.com/references/medusa-workflows/steps/calculateShippingOptionsPricesStep/index.html.md)
+- [cancelFulfillmentStep](https://docs.medusajs.com/references/medusa-workflows/steps/cancelFulfillmentStep/index.html.md)
- [createFulfillmentStep](https://docs.medusajs.com/references/medusa-workflows/steps/createFulfillmentStep/index.html.md)
-- [createFulfillmentSets](https://docs.medusajs.com/references/medusa-workflows/steps/createFulfillmentSets/index.html.md)
- [createReturnFulfillmentStep](https://docs.medusajs.com/references/medusa-workflows/steps/createReturnFulfillmentStep/index.html.md)
-- [createShippingOptionsPriceSetsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createShippingOptionsPriceSetsStep/index.html.md)
-- [createShippingOptionRulesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createShippingOptionRulesStep/index.html.md)
+- [createFulfillmentSets](https://docs.medusajs.com/references/medusa-workflows/steps/createFulfillmentSets/index.html.md)
- [createServiceZonesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createServiceZonesStep/index.html.md)
+- [createShippingOptionRulesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createShippingOptionRulesStep/index.html.md)
- [createShippingProfilesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createShippingProfilesStep/index.html.md)
- [deleteFulfillmentSetsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteFulfillmentSetsStep/index.html.md)
+- [createShippingOptionsPriceSetsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createShippingOptionsPriceSetsStep/index.html.md)
- [deleteServiceZonesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteServiceZonesStep/index.html.md)
- [deleteShippingOptionRulesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteShippingOptionRulesStep/index.html.md)
- [deleteShippingOptionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteShippingOptionsStep/index.html.md)
- [updateServiceZonesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateServiceZonesStep/index.html.md)
-- [updateFulfillmentStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateFulfillmentStep/index.html.md)
- [setShippingOptionsPricesStep](https://docs.medusajs.com/references/medusa-workflows/steps/setShippingOptionsPricesStep/index.html.md)
+- [updateFulfillmentStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateFulfillmentStep/index.html.md)
- [updateShippingOptionRulesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateShippingOptionRulesStep/index.html.md)
+- [validateShipmentStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateShipmentStep/index.html.md)
- [updateShippingProfilesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateShippingProfilesStep/index.html.md)
- [upsertShippingOptionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/upsertShippingOptionsStep/index.html.md)
- [validateShippingOptionPricesStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateShippingOptionPricesStep/index.html.md)
-- [validateShipmentStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateShipmentStep/index.html.md)
-- [createInviteStep](https://docs.medusajs.com/references/medusa-workflows/steps/createInviteStep/index.html.md)
+- [adjustInventoryLevelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/adjustInventoryLevelsStep/index.html.md)
+- [createInventoryItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createInventoryItemsStep/index.html.md)
+- [attachInventoryItemToVariants](https://docs.medusajs.com/references/medusa-workflows/steps/attachInventoryItemToVariants/index.html.md)
+- [createInventoryLevelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createInventoryLevelsStep/index.html.md)
+- [deleteInventoryItemStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteInventoryItemStep/index.html.md)
+- [deleteInventoryLevelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteInventoryLevelsStep/index.html.md)
+- [updateInventoryItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateInventoryItemsStep/index.html.md)
+- [updateInventoryLevelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateInventoryLevelsStep/index.html.md)
+- [validateInventoryDeleteStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateInventoryDeleteStep/index.html.md)
+- [validateInventoryLocationsStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateInventoryLocationsStep/index.html.md)
+- [validateInventoryItemsForCreate](https://docs.medusajs.com/references/medusa-workflows/steps/validateInventoryItemsForCreate/index.html.md)
- [deleteInvitesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteInvitesStep/index.html.md)
+- [createInviteStep](https://docs.medusajs.com/references/medusa-workflows/steps/createInviteStep/index.html.md)
- [refreshInviteTokensStep](https://docs.medusajs.com/references/medusa-workflows/steps/refreshInviteTokensStep/index.html.md)
+- [sendNotificationsStep](https://docs.medusajs.com/references/medusa-workflows/steps/sendNotificationsStep/index.html.md)
- [validateTokenStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateTokenStep/index.html.md)
- [notifyOnFailureStep](https://docs.medusajs.com/references/medusa-workflows/steps/notifyOnFailureStep/index.html.md)
-- [sendNotificationsStep](https://docs.medusajs.com/references/medusa-workflows/steps/sendNotificationsStep/index.html.md)
-- [deleteLineItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteLineItemsStep/index.html.md)
-- [listLineItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/listLineItemsStep/index.html.md)
- [updateLineItemsStepWithSelector](https://docs.medusajs.com/references/medusa-workflows/steps/updateLineItemsStepWithSelector/index.html.md)
+- [listLineItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/listLineItemsStep/index.html.md)
+- [deleteLineItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteLineItemsStep/index.html.md)
- [addOrderTransactionStep](https://docs.medusajs.com/references/medusa-workflows/steps/addOrderTransactionStep/index.html.md)
-- [archiveOrdersStep](https://docs.medusajs.com/references/medusa-workflows/steps/archiveOrdersStep/index.html.md)
- [cancelOrderChangeStep](https://docs.medusajs.com/references/medusa-workflows/steps/cancelOrderChangeStep/index.html.md)
+- [archiveOrdersStep](https://docs.medusajs.com/references/medusa-workflows/steps/archiveOrdersStep/index.html.md)
- [cancelOrderClaimStep](https://docs.medusajs.com/references/medusa-workflows/steps/cancelOrderClaimStep/index.html.md)
-- [cancelOrderExchangeStep](https://docs.medusajs.com/references/medusa-workflows/steps/cancelOrderExchangeStep/index.html.md)
- [cancelOrderFulfillmentStep](https://docs.medusajs.com/references/medusa-workflows/steps/cancelOrderFulfillmentStep/index.html.md)
-- [cancelOrdersStep](https://docs.medusajs.com/references/medusa-workflows/steps/cancelOrdersStep/index.html.md)
- [cancelOrderReturnStep](https://docs.medusajs.com/references/medusa-workflows/steps/cancelOrderReturnStep/index.html.md)
+- [cancelOrderExchangeStep](https://docs.medusajs.com/references/medusa-workflows/steps/cancelOrderExchangeStep/index.html.md)
+- [cancelOrdersStep](https://docs.medusajs.com/references/medusa-workflows/steps/cancelOrdersStep/index.html.md)
+- [createOrderChangeStep](https://docs.medusajs.com/references/medusa-workflows/steps/createOrderChangeStep/index.html.md)
- [completeOrdersStep](https://docs.medusajs.com/references/medusa-workflows/steps/completeOrdersStep/index.html.md)
- [createCompleteReturnStep](https://docs.medusajs.com/references/medusa-workflows/steps/createCompleteReturnStep/index.html.md)
- [createOrderClaimItemsFromActionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createOrderClaimItemsFromActionsStep/index.html.md)
-- [createOrderChangeStep](https://docs.medusajs.com/references/medusa-workflows/steps/createOrderChangeStep/index.html.md)
-- [createOrderClaimsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createOrderClaimsStep/index.html.md)
-- [createOrderExchangesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createOrderExchangesStep/index.html.md)
-- [createOrderLineItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createOrderLineItemsStep/index.html.md)
- [createOrderExchangeItemsFromActionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createOrderExchangeItemsFromActionsStep/index.html.md)
+- [createOrderExchangesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createOrderExchangesStep/index.html.md)
+- [createOrderClaimsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createOrderClaimsStep/index.html.md)
+- [createOrderLineItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createOrderLineItemsStep/index.html.md)
- [createOrdersStep](https://docs.medusajs.com/references/medusa-workflows/steps/createOrdersStep/index.html.md)
- [createReturnsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createReturnsStep/index.html.md)
-- [deleteClaimsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteClaimsStep/index.html.md)
- [declineOrderChangeStep](https://docs.medusajs.com/references/medusa-workflows/steps/declineOrderChangeStep/index.html.md)
+- [deleteClaimsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteClaimsStep/index.html.md)
- [deleteExchangesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteExchangesStep/index.html.md)
- [deleteOrderChangeActionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteOrderChangeActionsStep/index.html.md)
-- [deleteOrderLineItems](https://docs.medusajs.com/references/medusa-workflows/steps/deleteOrderLineItems/index.html.md)
- [deleteOrderChangesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteOrderChangesStep/index.html.md)
+- [deleteOrderLineItems](https://docs.medusajs.com/references/medusa-workflows/steps/deleteOrderLineItems/index.html.md)
- [deleteOrderShippingMethods](https://docs.medusajs.com/references/medusa-workflows/steps/deleteOrderShippingMethods/index.html.md)
+- [deleteReturnsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteReturnsStep/index.html.md)
- [previewOrderChangeStep](https://docs.medusajs.com/references/medusa-workflows/steps/previewOrderChangeStep/index.html.md)
- [registerOrderChangesStep](https://docs.medusajs.com/references/medusa-workflows/steps/registerOrderChangesStep/index.html.md)
-- [deleteReturnsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteReturnsStep/index.html.md)
- [registerOrderFulfillmentStep](https://docs.medusajs.com/references/medusa-workflows/steps/registerOrderFulfillmentStep/index.html.md)
-- [setOrderTaxLinesForItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/setOrderTaxLinesForItemsStep/index.html.md)
- [updateOrderChangeActionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateOrderChangeActionsStep/index.html.md)
+- [setOrderTaxLinesForItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/setOrderTaxLinesForItemsStep/index.html.md)
- [registerOrderShipmentStep](https://docs.medusajs.com/references/medusa-workflows/steps/registerOrderShipmentStep/index.html.md)
- [updateOrderShippingMethodsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateOrderShippingMethodsStep/index.html.md)
- [updateOrderChangesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateOrderChangesStep/index.html.md)
@@ -29082,116 +29841,116 @@ The [Authenticate or Login API Route](https://docs.medusajs.com/Users/shahednass
- [updateReturnsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateReturnsStep/index.html.md)
- [authorizePaymentSessionStep](https://docs.medusajs.com/references/medusa-workflows/steps/authorizePaymentSessionStep/index.html.md)
- [cancelPaymentStep](https://docs.medusajs.com/references/medusa-workflows/steps/cancelPaymentStep/index.html.md)
-- [capturePaymentStep](https://docs.medusajs.com/references/medusa-workflows/steps/capturePaymentStep/index.html.md)
-- [createPriceListPricesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createPriceListPricesStep/index.html.md)
-- [refundPaymentsStep](https://docs.medusajs.com/references/medusa-workflows/steps/refundPaymentsStep/index.html.md)
- [refundPaymentStep](https://docs.medusajs.com/references/medusa-workflows/steps/refundPaymentStep/index.html.md)
-- [deletePriceListsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deletePriceListsStep/index.html.md)
-- [createPriceListsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createPriceListsStep/index.html.md)
-- [getExistingPriceListsPriceIdsStep](https://docs.medusajs.com/references/medusa-workflows/steps/getExistingPriceListsPriceIdsStep/index.html.md)
-- [removePriceListPricesStep](https://docs.medusajs.com/references/medusa-workflows/steps/removePriceListPricesStep/index.html.md)
-- [updatePriceListsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updatePriceListsStep/index.html.md)
-- [updatePriceListPricesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updatePriceListPricesStep/index.html.md)
-- [validatePriceListsStep](https://docs.medusajs.com/references/medusa-workflows/steps/validatePriceListsStep/index.html.md)
-- [validateVariantPriceLinksStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateVariantPriceLinksStep/index.html.md)
+- [refundPaymentsStep](https://docs.medusajs.com/references/medusa-workflows/steps/refundPaymentsStep/index.html.md)
+- [capturePaymentStep](https://docs.medusajs.com/references/medusa-workflows/steps/capturePaymentStep/index.html.md)
- [createPaymentAccountHolderStep](https://docs.medusajs.com/references/medusa-workflows/steps/createPaymentAccountHolderStep/index.html.md)
-- [createRefundReasonStep](https://docs.medusajs.com/references/medusa-workflows/steps/createRefundReasonStep/index.html.md)
-- [deletePaymentSessionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deletePaymentSessionsStep/index.html.md)
- [createPaymentSessionStep](https://docs.medusajs.com/references/medusa-workflows/steps/createPaymentSessionStep/index.html.md)
+- [createRefundReasonStep](https://docs.medusajs.com/references/medusa-workflows/steps/createRefundReasonStep/index.html.md)
- [deleteRefundReasonsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteRefundReasonsStep/index.html.md)
+- [deletePaymentSessionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deletePaymentSessionsStep/index.html.md)
- [updateRefundReasonsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateRefundReasonsStep/index.html.md)
- [updatePaymentCollectionStep](https://docs.medusajs.com/references/medusa-workflows/steps/updatePaymentCollectionStep/index.html.md)
- [validateDeletedPaymentSessionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateDeletedPaymentSessionsStep/index.html.md)
+- [createPriceListPricesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createPriceListPricesStep/index.html.md)
+- [getExistingPriceListsPriceIdsStep](https://docs.medusajs.com/references/medusa-workflows/steps/getExistingPriceListsPriceIdsStep/index.html.md)
+- [createPriceListsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createPriceListsStep/index.html.md)
+- [deletePriceListsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deletePriceListsStep/index.html.md)
+- [removePriceListPricesStep](https://docs.medusajs.com/references/medusa-workflows/steps/removePriceListPricesStep/index.html.md)
+- [updatePriceListPricesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updatePriceListPricesStep/index.html.md)
+- [validatePriceListsStep](https://docs.medusajs.com/references/medusa-workflows/steps/validatePriceListsStep/index.html.md)
+- [updatePriceListsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updatePriceListsStep/index.html.md)
+- [validateVariantPriceLinksStep](https://docs.medusajs.com/references/medusa-workflows/steps/validateVariantPriceLinksStep/index.html.md)
+- [deletePricePreferencesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deletePricePreferencesStep/index.html.md)
- [createPriceSetsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createPriceSetsStep/index.html.md)
- [createPricePreferencesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createPricePreferencesStep/index.html.md)
-- [deletePricePreferencesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deletePricePreferencesStep/index.html.md)
-- [updatePricePreferencesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updatePricePreferencesStep/index.html.md)
-- [updatePriceSetsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updatePriceSetsStep/index.html.md)
- [updatePricePreferencesAsArrayStep](https://docs.medusajs.com/references/medusa-workflows/steps/updatePricePreferencesAsArrayStep/index.html.md)
-- [batchLinkProductsToCollectionStep](https://docs.medusajs.com/references/medusa-workflows/steps/batchLinkProductsToCollectionStep/index.html.md)
-- [batchLinkProductsToCategoryStep](https://docs.medusajs.com/references/medusa-workflows/steps/batchLinkProductsToCategoryStep/index.html.md)
+- [updatePriceSetsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updatePriceSetsStep/index.html.md)
+- [updatePricePreferencesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updatePricePreferencesStep/index.html.md)
- [createCollectionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createCollectionsStep/index.html.md)
- [createProductOptionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createProductOptionsStep/index.html.md)
+- [batchLinkProductsToCollectionStep](https://docs.medusajs.com/references/medusa-workflows/steps/batchLinkProductsToCollectionStep/index.html.md)
+- [batchLinkProductsToCategoryStep](https://docs.medusajs.com/references/medusa-workflows/steps/batchLinkProductsToCategoryStep/index.html.md)
+- [createProductVariantsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createProductVariantsStep/index.html.md)
- [createProductTypesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createProductTypesStep/index.html.md)
- [createProductTagsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createProductTagsStep/index.html.md)
-- [createProductVariantsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createProductVariantsStep/index.html.md)
-- [createVariantPricingLinkStep](https://docs.medusajs.com/references/medusa-workflows/steps/createVariantPricingLinkStep/index.html.md)
-- [deleteCollectionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteCollectionsStep/index.html.md)
- [createProductsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createProductsStep/index.html.md)
+- [deleteCollectionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteCollectionsStep/index.html.md)
+- [createVariantPricingLinkStep](https://docs.medusajs.com/references/medusa-workflows/steps/createVariantPricingLinkStep/index.html.md)
- [deleteProductOptionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteProductOptionsStep/index.html.md)
-- [deleteProductTypesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteProductTypesStep/index.html.md)
- [deleteProductTagsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteProductTagsStep/index.html.md)
-- [deleteProductVariantsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteProductVariantsStep/index.html.md)
- [deleteProductsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteProductsStep/index.html.md)
-- [generateProductCsvStep](https://docs.medusajs.com/references/medusa-workflows/steps/generateProductCsvStep/index.html.md)
+- [deleteProductVariantsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteProductVariantsStep/index.html.md)
+- [deleteProductTypesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteProductTypesStep/index.html.md)
+- [getVariantAvailabilityStep](https://docs.medusajs.com/references/medusa-workflows/steps/getVariantAvailabilityStep/index.html.md)
- [getAllProductsStep](https://docs.medusajs.com/references/medusa-workflows/steps/getAllProductsStep/index.html.md)
- [getProductsStep](https://docs.medusajs.com/references/medusa-workflows/steps/getProductsStep/index.html.md)
-- [getVariantAvailabilityStep](https://docs.medusajs.com/references/medusa-workflows/steps/getVariantAvailabilityStep/index.html.md)
+- [generateProductCsvStep](https://docs.medusajs.com/references/medusa-workflows/steps/generateProductCsvStep/index.html.md)
- [parseProductCsvStep](https://docs.medusajs.com/references/medusa-workflows/steps/parseProductCsvStep/index.html.md)
-- [updateProductOptionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateProductOptionsStep/index.html.md)
- [groupProductsForBatchStep](https://docs.medusajs.com/references/medusa-workflows/steps/groupProductsForBatchStep/index.html.md)
-- [updateProductTagsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateProductTagsStep/index.html.md)
- [updateCollectionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateCollectionsStep/index.html.md)
+- [updateProductTagsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateProductTagsStep/index.html.md)
- [updateProductTypesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateProductTypesStep/index.html.md)
-- [waitConfirmationProductImportStep](https://docs.medusajs.com/references/medusa-workflows/steps/waitConfirmationProductImportStep/index.html.md)
- [updateProductVariantsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateProductVariantsStep/index.html.md)
+- [updateProductOptionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateProductOptionsStep/index.html.md)
+- [waitConfirmationProductImportStep](https://docs.medusajs.com/references/medusa-workflows/steps/waitConfirmationProductImportStep/index.html.md)
- [updateProductsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateProductsStep/index.html.md)
-- [createProductCategoriesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createProductCategoriesStep/index.html.md)
-- [deleteProductCategoriesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteProductCategoriesStep/index.html.md)
-- [updateProductCategoriesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateProductCategoriesStep/index.html.md)
+- [addCampaignPromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/addCampaignPromotionsStep/index.html.md)
- [addRulesToPromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/addRulesToPromotionsStep/index.html.md)
- [createPromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createPromotionsStep/index.html.md)
- [createCampaignsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createCampaignsStep/index.html.md)
-- [addCampaignPromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/addCampaignPromotionsStep/index.html.md)
-- [removeCampaignPromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/removeCampaignPromotionsStep/index.html.md)
-- [deleteCampaignsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteCampaignsStep/index.html.md)
-- [removeRulesFromPromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/removeRulesFromPromotionsStep/index.html.md)
- [deletePromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deletePromotionsStep/index.html.md)
+- [deleteCampaignsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteCampaignsStep/index.html.md)
+- [removeCampaignPromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/removeCampaignPromotionsStep/index.html.md)
- [updateCampaignsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateCampaignsStep/index.html.md)
+- [removeRulesFromPromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/removeRulesFromPromotionsStep/index.html.md)
- [updatePromotionRulesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updatePromotionRulesStep/index.html.md)
- [updatePromotionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updatePromotionsStep/index.html.md)
+- [deleteProductCategoriesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteProductCategoriesStep/index.html.md)
+- [createProductCategoriesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createProductCategoriesStep/index.html.md)
+- [updateProductCategoriesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateProductCategoriesStep/index.html.md)
- [createRegionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createRegionsStep/index.html.md)
- [deleteRegionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteRegionsStep/index.html.md)
- [setRegionsPaymentProvidersStep](https://docs.medusajs.com/references/medusa-workflows/steps/setRegionsPaymentProvidersStep/index.html.md)
- [updateRegionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateRegionsStep/index.html.md)
-- [listShippingOptionsForContextStep](https://docs.medusajs.com/references/medusa-workflows/steps/listShippingOptionsForContextStep/index.html.md)
-- [createReturnReasonsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createReturnReasonsStep/index.html.md)
-- [deleteReturnReasonStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteReturnReasonStep/index.html.md)
-- [updateReturnReasonsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateReturnReasonsStep/index.html.md)
- [deleteReservationsByLineItemsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteReservationsByLineItemsStep/index.html.md)
- [createReservationsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createReservationsStep/index.html.md)
- [deleteReservationsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteReservationsStep/index.html.md)
- [updateReservationsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateReservationsStep/index.html.md)
- [associateLocationsWithSalesChannelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/associateLocationsWithSalesChannelsStep/index.html.md)
- [associateProductsWithSalesChannelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/associateProductsWithSalesChannelsStep/index.html.md)
-- [createDefaultSalesChannelStep](https://docs.medusajs.com/references/medusa-workflows/steps/createDefaultSalesChannelStep/index.html.md)
- [canDeleteSalesChannelsOrThrowStep](https://docs.medusajs.com/references/medusa-workflows/steps/canDeleteSalesChannelsOrThrowStep/index.html.md)
- [createSalesChannelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createSalesChannelsStep/index.html.md)
+- [createDefaultSalesChannelStep](https://docs.medusajs.com/references/medusa-workflows/steps/createDefaultSalesChannelStep/index.html.md)
+- [deleteSalesChannelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteSalesChannelsStep/index.html.md)
- [detachLocationsFromSalesChannelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/detachLocationsFromSalesChannelsStep/index.html.md)
- [detachProductsFromSalesChannelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/detachProductsFromSalesChannelsStep/index.html.md)
- [updateSalesChannelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateSalesChannelsStep/index.html.md)
-- [deleteSalesChannelsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteSalesChannelsStep/index.html.md)
- [deleteShippingProfilesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteShippingProfilesStep/index.html.md)
+- [createReturnReasonsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createReturnReasonsStep/index.html.md)
+- [deleteReturnReasonStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteReturnReasonStep/index.html.md)
+- [updateReturnReasonsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateReturnReasonsStep/index.html.md)
+- [listShippingOptionsForContextStep](https://docs.medusajs.com/references/medusa-workflows/steps/listShippingOptionsForContextStep/index.html.md)
- [createStockLocations](https://docs.medusajs.com/references/medusa-workflows/steps/createStockLocations/index.html.md)
-- [deleteStockLocationsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteStockLocationsStep/index.html.md)
- [updateStockLocationsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateStockLocationsStep/index.html.md)
-- [updateStoresStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateStoresStep/index.html.md)
-- [createStoresStep](https://docs.medusajs.com/references/medusa-workflows/steps/createStoresStep/index.html.md)
+- [deleteStockLocationsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteStockLocationsStep/index.html.md)
- [deleteStoresStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteStoresStep/index.html.md)
+- [createStoresStep](https://docs.medusajs.com/references/medusa-workflows/steps/createStoresStep/index.html.md)
+- [updateStoresStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateStoresStep/index.html.md)
+- [createUsersStep](https://docs.medusajs.com/references/medusa-workflows/steps/createUsersStep/index.html.md)
+- [deleteUsersStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteUsersStep/index.html.md)
+- [updateUsersStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateUsersStep/index.html.md)
- [createTaxRateRulesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createTaxRateRulesStep/index.html.md)
- [createTaxRatesStep](https://docs.medusajs.com/references/medusa-workflows/steps/createTaxRatesStep/index.html.md)
-- [deleteTaxRatesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteTaxRatesStep/index.html.md)
- [createTaxRegionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/createTaxRegionsStep/index.html.md)
-- [deleteTaxRegionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteTaxRegionsStep/index.html.md)
- [deleteTaxRateRulesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteTaxRateRulesStep/index.html.md)
- [getItemTaxLinesStep](https://docs.medusajs.com/references/medusa-workflows/steps/getItemTaxLinesStep/index.html.md)
+- [deleteTaxRegionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteTaxRegionsStep/index.html.md)
+- [deleteTaxRatesStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteTaxRatesStep/index.html.md)
- [listTaxRateIdsStep](https://docs.medusajs.com/references/medusa-workflows/steps/listTaxRateIdsStep/index.html.md)
-- [listTaxRateRuleIdsStep](https://docs.medusajs.com/references/medusa-workflows/steps/listTaxRateRuleIdsStep/index.html.md)
- [updateTaxRatesStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateTaxRatesStep/index.html.md)
+- [listTaxRateRuleIdsStep](https://docs.medusajs.com/references/medusa-workflows/steps/listTaxRateRuleIdsStep/index.html.md)
- [updateTaxRegionsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateTaxRegionsStep/index.html.md)
-- [createUsersStep](https://docs.medusajs.com/references/medusa-workflows/steps/createUsersStep/index.html.md)
-- [updateUsersStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateUsersStep/index.html.md)
-- [deleteUsersStep](https://docs.medusajs.com/references/medusa-workflows/steps/deleteUsersStep/index.html.md)
# Medusa CLI Reference
@@ -29217,6 +29976,84 @@ npx medusa --help
***
+# build Command - Medusa CLI Reference
+
+Create a standalone build of the Medusa application.
+
+This creates a build that:
+
+- Doesn't rely on the source TypeScript files.
+- Can be copied to a production server reliably.
+
+The build is outputted to a new `.medusa/server` directory.
+
+```bash
+npx medusa build
+```
+
+Refer to [this section](#run-built-medusa-application) for next steps.
+
+## Options
+
+|Option|Description|
+|---|---|---|
+|\`--admin-only\`|Whether to only build the admin to host it separately. If this option is not passed, the admin is built to the |
+
+***
+
+## Run Built Medusa Application
+
+After running the `build` command, use the following step to run the built Medusa application:
+
+- Change to the `.medusa/server` directory and install the dependencies:
+
+```bash npm2yarn
+cd .medusa/server && npm install
+```
+
+- When running the application locally, make sure to copy the `.env` file from the root project's directory. In production, use system environment variables instead.
+
+```bash npm2yarn
+cp .env .medusa/server/.env.production
+```
+
+- In the system environment variables, set `NODE_ENV` to `production`:
+
+```bash
+NODE_ENV=production
+```
+
+- Use the `start` command to run the application:
+
+```bash npm2yarn
+cd .medusa/server && npm run start
+```
+
+***
+
+## Build Medusa Admin
+
+By default, the Medusa Admin is built to the `.medusa/server/public/admin` directory.
+
+If you want a separate build to host the admin standalone, such as on Vercel, pass the `--admin-only` option as explained in the [Options](#options) section. This outputs the admin to the `.medusa/admin` directory instead.
+
+
+# develop Command - Medusa CLI Reference
+
+Start Medusa application in development. This command watches files for any changes, then rebuilds the files and restarts the Medusa application.
+
+```bash
+npx medusa develop
+```
+
+## Options
+
+|Option|Description|Default|
+|---|---|---|---|---|
+|\`-H \\`|Set host of the Medusa server.|\`localhost\`|
+|\`-p \\`|Set port of the Medusa server.|\`9000\`|
+
+
# db Commands - Medusa CLI Reference
Commands starting with `db:` perform actions on the database.
@@ -29337,68 +30174,6 @@ npx medusa db:sync-links
|\`--execute-all\`|Skip prompts when syncing links and execute all (including unsafe) actions.|No|Prompts are shown for unsafe actions, by default.|
-# build Command - Medusa CLI Reference
-
-Create a standalone build of the Medusa application.
-
-This creates a build that:
-
-- Doesn't rely on the source TypeScript files.
-- Can be copied to a production server reliably.
-
-The build is outputted to a new `.medusa/server` directory.
-
-```bash
-npx medusa build
-```
-
-Refer to [this section](#run-built-medusa-application) for next steps.
-
-## Options
-
-|Option|Description|
-|---|---|---|
-|\`--admin-only\`|Whether to only build the admin to host it separately. If this option is not passed, the admin is built to the |
-
-***
-
-## Run Built Medusa Application
-
-After running the `build` command, use the following step to run the built Medusa application:
-
-- Change to the `.medusa/server` directory and install the dependencies:
-
-```bash npm2yarn
-cd .medusa/server && npm install
-```
-
-- When running the application locally, make sure to copy the `.env` file from the root project's directory. In production, use system environment variables instead.
-
-```bash npm2yarn
-cp .env .medusa/server/.env.production
-```
-
-- In the system environment variables, set `NODE_ENV` to `production`:
-
-```bash
-NODE_ENV=production
-```
-
-- Use the `start` command to run the application:
-
-```bash npm2yarn
-cd .medusa/server && npm run start
-```
-
-***
-
-## Build Medusa Admin
-
-By default, the Medusa Admin is built to the `.medusa/server/public/admin` directory.
-
-If you want a separate build to host the admin standalone, such as on Vercel, pass the `--admin-only` option as explained in the [Options](#options) section. This outputs the admin to the `.medusa/admin` directory instead.
-
-
# exec Command - Medusa CLI Reference
Run a custom CLI script. Learn more about it in [this guide](https://docs.medusajs.com/docs/learn/fundamentals/custom-cli-scripts/index.html.md).
@@ -29415,22 +30190,6 @@ npx medusa exec [file] [args...]
|\`args\`|A list of arguments to pass to the function. These arguments are passed in the |No|
-# develop Command - Medusa CLI Reference
-
-Start Medusa application in development. This command watches files for any changes, then rebuilds the files and restarts the Medusa application.
-
-```bash
-npx medusa develop
-```
-
-## Options
-
-|Option|Description|Default|
-|---|---|---|---|---|
-|\`-H \\`|Set host of the Medusa server.|\`localhost\`|
-|\`-p \\`|Set port of the Medusa server.|\`9000\`|
-
-
# new Command - Medusa CLI Reference
Create a new Medusa application. Unlike the `create-medusa-app` CLI tool, this command provides more flexibility for experienced Medusa developers in creating and configuring their project.
@@ -29658,6 +30417,38 @@ By default, the Medusa Admin is built to the `.medusa/server/public/admin` direc
If you want a separate build to host the admin standalone, such as on Vercel, pass the `--admin-only` option as explained in the [Options](#options) section. This outputs the admin to the `.medusa/admin` directory instead.
+# exec Command - Medusa CLI Reference
+
+Run a custom CLI script. Learn more about it in [this guide](https://docs.medusajs.com/docs/learn/fundamentals/custom-cli-scripts/index.html.md).
+
+```bash
+npx medusa exec [file] [args...]
+```
+
+## Arguments
+
+|Argument|Description|Required|
+|---|---|---|---|---|
+|\`file\`|The path to the TypeScript or JavaScript file holding the function to execute.|Yes|
+|\`args\`|A list of arguments to pass to the function. These arguments are passed in the |No|
+
+
+# develop Command - Medusa CLI Reference
+
+Start Medusa application in development. This command watches files for any changes, then rebuilds the files and restarts the Medusa application.
+
+```bash
+npx medusa develop
+```
+
+## Options
+
+|Option|Description|Default|
+|---|---|---|---|---|
+|\`-H \\`|Set host of the Medusa server.|\`localhost\`|
+|\`-p \\`|Set port of the Medusa server.|\`9000\`|
+
+
# new Command - Medusa CLI Reference
Create a new Medusa application. Unlike the `create-medusa-app` CLI tool, this command provides more flexibility for experienced Medusa developers in creating and configuring their project.
@@ -29687,22 +30478,6 @@ medusa new [ []]
|\`--db-host \\`|The database host to use for database setup.|
-# develop Command - Medusa CLI Reference
-
-Start Medusa application in development. This command watches files for any changes, then rebuilds the files and restarts the Medusa application.
-
-```bash
-npx medusa develop
-```
-
-## Options
-
-|Option|Description|Default|
-|---|---|---|---|---|
-|\`-H \\`|Set host of the Medusa server.|\`localhost\`|
-|\`-p \\`|Set port of the Medusa server.|\`9000\`|
-
-
# db Commands - Medusa CLI Reference
Commands starting with `db:` perform actions on the database.
@@ -29823,6 +30598,23 @@ npx medusa db:sync-links
|\`--execute-all\`|Skip prompts when syncing links and execute all (including unsafe) actions.|No|Prompts are shown for unsafe actions, by default.|
+# start Command - Medusa CLI Reference
+
+Start the Medusa application in production.
+
+```bash
+npx medusa start
+```
+
+## Options
+
+|Option|Description|Default|
+|---|---|---|---|---|
+|\`-H \\`|Set host of the Medusa server.|\`localhost\`|
+|\`-p \\`|Set port of the Medusa server.|\`9000\`|
+|\`--cluster \\`|Start Medusa's Node.js server in |Cluster mode is disabled by default. If the option is passed but no number is passed, Medusa will try to consume all available CPU cores.|
+
+
# plugin Commands - Medusa CLI Reference
Commands starting with `plugin:` perform actions related to [plugin](https://docs.medusajs.com/docs/learn/fundamentals/plugins/index.html.md) development.
@@ -29884,37 +30676,20 @@ npx medusa plugin:build
```
-# exec Command - Medusa CLI Reference
+# telemetry Command - Medusa CLI Reference
-Run a custom CLI script. Learn more about it in [this guide](https://docs.medusajs.com/docs/learn/fundamentals/custom-cli-scripts/index.html.md).
+Enable or disable the collection of anonymous data usage. If no option is provided, the command enables the collection of anonymous data usage.
```bash
-npx medusa exec [file] [args...]
+npx medusa telemetry
```
-## Arguments
+#### Options
-|Argument|Description|Required|
-|---|---|---|---|---|
-|\`file\`|The path to the TypeScript or JavaScript file holding the function to execute.|Yes|
-|\`args\`|A list of arguments to pass to the function. These arguments are passed in the |No|
-
-
-# start Command - Medusa CLI Reference
-
-Start the Medusa application in production.
-
-```bash
-npx medusa start
-```
-
-## Options
-
-|Option|Description|Default|
-|---|---|---|---|---|
-|\`-H \\`|Set host of the Medusa server.|\`localhost\`|
-|\`-p \\`|Set port of the Medusa server.|\`9000\`|
-|\`--cluster \\`|Start Medusa's Node.js server in |Cluster mode is disabled by default. If the option is passed but no number is passed, Medusa will try to consume all available CPU cores.|
+|Option|Description|
+|---|---|---|
+|\`--enable\`|Enable telemetry (default).|
+|\`--disable\`|Disable telemetry.|
# user Command - Medusa CLI Reference
@@ -29936,22 +30711,6 @@ npx medusa user --email [--password ]
If ran successfully, you'll receive the invite token in the output.|No|\`false\`|
-# telemetry Command - Medusa CLI Reference
-
-Enable or disable the collection of anonymous data usage. If no option is provided, the command enables the collection of anonymous data usage.
-
-```bash
-npx medusa telemetry
-```
-
-#### Options
-
-|Option|Description|
-|---|---|---|
-|\`--enable\`|Enable telemetry (default).|
-|\`--disable\`|Disable telemetry.|
-
-
# Medusa JS SDK
In this documentation, you'll learn how to install and use Medusa's JS SDK.
@@ -34402,6 +35161,795 @@ const user = await userModuleService.createUsers({
```
+# Implement Custom Line Item Pricing in Medusa
+
+In this guide, you'll learn how to add line items with custom prices to a cart in Medusa.
+
+When you install a Medusa application, you get a fully-fledged commerce platform with a framework for customization. The Medusa application's commerce features are built around [commerce modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md) which are available out-of-the-box. These features include managing carts and adding line items to them.
+
+By default, you can add product variants to the cart, where the price of its associated line item is based on the product variant's price. However, you can build customizations to add line items with custom prices to the cart. This is useful when integrating an Enterprise Resource Planning (ERP), Product Information Management (PIM), or other third-party services that provide real-time prices for your products.
+
+To showcase how to add line items with custom prices to the cart, this guide uses [GoldAPI.io](https://www.goldapi.io) as an example of a third-party system that you can integrate for real-time prices. You can follow the same approach for other third-party integrations that provide custom pricing.
+
+You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
+
+### Summary
+
+This guide will teach you how to:
+
+- Install and set up Medusa.
+- Integrate the third-party service [GoldAPI.io](https://www.goldapi.io) that retrieves real-time prices for metals like Gold and Silver.
+- Add an API route to add a product variant that has metals, such as a gold ring, to the cart with the real-time price retrieved from the third-party service.
+
+
+
+- [Custom Item Price Repository](https://github.com/medusajs/examples/tree/main/custom-item-price): Find the full code for this guide in this repository.
+- [OpenApi Specs for Postman](https://res.cloudinary.com/dza7lstvk/raw/upload/v1738246728/OpenApi/Custom_Item_Price_gdfnl3.yaml): Import this OpenApi Specs file into tools like Postman.
+
+***
+
+## Step 1: Install a Medusa Application
+
+### Prerequisites
+
+- [Node.js v20+](https://nodejs.org/en/download)
+- [Git CLI tool](https://git-scm.com/downloads)
+- [PostgreSQL](https://www.postgresql.org/download/)
+
+Start by installing the Medusa application on your machine with the following command:
+
+```bash
+npx create-medusa-app@latest
+```
+
+You'll first be asked for the project's name. You can also optionally choose to install the [Next.js starter storefront](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/nextjs-starter/index.html.md).
+
+Afterwards, the installation process will start, which will install the Medusa application in a directory with your project's name. If you chose to install the Next.js starter, it'll be installed in a separate directory with the `{project-name}-storefront` name.
+
+The Medusa application is composed of a headless Node.js server and an admin dashboard. The storefront is installed or custom-built separately and connects to the Medusa application through its REST endpoints, called [API routes](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md). Learn more about Medusa's architecture in [this documentation](https://docs.medusajs.com/docs/learn/introduction/architecture/index.html.md).
+
+Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterwards, you can log in with the new user and explore the dashboard.
+
+Check out the [troubleshooting guides](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/troubleshooting/create-medusa-app-errors/index.html.md) for help.
+
+***
+
+## Step 2: Integrate GoldAPI.io
+
+### Prerequisites
+
+- [GoldAPI.io Account. You can create a free account.](https://www.goldapi.io)
+
+To integrate third-party services into Medusa, you create a custom module. A module is a reusable package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
+
+In this step, you'll create a Metal Price Module that uses the GoldAPI.io service to retrieve real-time prices for metals like Gold and Silver. You'll use this module later to retrieve the real-time price of a product variant based on the metals in it, and add it to the cart with that custom price.
+
+Learn more about modules in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md).
+
+### Create Module Directory
+
+A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/metal-prices`.
+
+
+
+### Create Module's Service
+
+You define a module's functionalities in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to the database, which is useful if your module defines tables in the database, or connect to a third-party service.
+
+In this section, you'll create the Metal Prices Module's service that connects to the GoldAPI.io service to retrieve real-time prices for metals.
+
+Start by creating the file `src/modules/metal-prices/service.ts` with the following content:
+
+
+
+```ts title="src/modules/metal-prices/service.ts"
+type Options = {
+ accessToken: string
+ sandbox?: boolean
+}
+
+export default class MetalPricesModuleService {
+ protected options_: Options
+
+ constructor({}, options: Options) {
+ this.options_ = options
+ }
+}
+```
+
+A module can accept options that are passed to its service. You define an `Options` type that indicates the options the module accepts. It accepts two options:
+
+- `accessToken`: The access token for the GoldAPI.io service.
+- `sandbox`: A boolean that indicates whether to simulate sending requests to the GoldAPI.io service. This is useful when running in a test environment.
+
+The service's constructor receives the module's options as a second parameter. You store the options in the service's `options_` property.
+
+A module has a container of Medusa framework tools and local resources in the module that you can access in the service constructor's first parameter. Learn more in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/container/index.html.md).
+
+#### Add Method to Retrieve Metal Prices
+
+Next, you'll add the method to retrieve the metal prices from the third-party service.
+
+First, add the following types at the beginning of `src/modules/metal-prices/service.ts`:
+
+```ts title="src/modules/metal-prices/service.ts"
+export enum MetalSymbols {
+ Gold = "XAU",
+ Silver = "XAG",
+ Platinum = "XPT",
+ Palladium = "XPD"
+}
+
+export type PriceResponse = {
+ metal: MetalSymbols
+ currency: string
+ exchange: string
+ symbol: string
+ price: number
+ [key: string]: unknown
+}
+
+```
+
+The `MetalSymbols` enum defines the symbols for metals like Gold, Silver, Platinum, and Palladium. The `PriceResponse` type defines the structure of the response from the GoldAPI.io's endpoint.
+
+Next, add the method `getMetalPrices` to the `MetalPricesModuleService` class:
+
+```ts title="src/modules/metal-prices/service.ts"
+import { MedusaError } from "@medusajs/framework/utils"
+
+// ...
+
+export default class MetalPricesModuleService {
+ // ...
+ async getMetalPrice(
+ symbol: MetalSymbols,
+ currency: string
+ ): Promise {
+ const upperCaseSymbol = symbol.toUpperCase()
+ const upperCaseCurrency = currency.toUpperCase()
+
+ return fetch(`https://www.goldapi.io/api/${upperCaseSymbol}/${upperCaseCurrency}`, {
+ headers: {
+ "x-access-token": this.options_.accessToken,
+ "Content-Type": "application/json",
+ },
+ redirect: "follow",
+ }).then((response) => response.json())
+ .then((response) => {
+ if (response.error) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ response.error
+ )
+ }
+
+ return response
+ })
+ }
+}
+```
+
+The `getMetalPrice` method accepts the metal symbol and currency as parameters. You send a request to GoldAPI.io's `/api/{symbol}/{currency}` endpoint to retrieve the metal's price, also passing the access token in the request's headers.
+
+If the response contains an error, you throw a `MedusaError` with the error message. Otherwise, you return the response, which is of type `PriceResponse`.
+
+#### Add Helper Methods
+
+You'll also add two helper methods to the `MetalPricesModuleService`. The first one is `getMetalSymbols` that returns the metal symbols as an array of strings:
+
+```ts title="src/modules/metal-prices/service.ts"
+export default class MetalPricesModuleService {
+ // ...
+ async getMetalSymbols(): Promise {
+ return Object.values(MetalSymbols)
+ }
+}
+```
+
+The second is `getMetalSymbol` that receives a name like `gold` and returns the corresponding metal symbol:
+
+```ts title="src/modules/metal-prices/service.ts"
+export default class MetalPricesModuleService {
+ // ...
+ async getMetalSymbol(name: string): Promise {
+ const formattedName = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase()
+ return MetalSymbols[formattedName as keyof typeof MetalSymbols]
+ }
+}
+```
+
+You'll use these methods in later steps.
+
+### Export Module Definition
+
+The final piece to a module is its definition, which you export in an `index.ts` file at its root directory. This definition tells Medusa the name of the module and its service.
+
+So, create the file `src/modules/metal-prices/index.ts` with the following content:
+
+
+
+```ts title="src/modules/metal-prices/index.ts"
+import { Module } from "@medusajs/framework/utils"
+import MetalPricesModuleService from "./service"
+
+export const METAL_PRICES_MODULE = "metal-prices"
+
+export default Module(METAL_PRICES_MODULE, {
+ service: MetalPricesModuleService,
+})
+```
+
+You use the `Module` function from the Modules SDK to create the module's definition. It accepts two parameters:
+
+1. The module's name, which is `metal-prices`.
+2. An object with a required property `service` indicating the module's service.
+
+### Add Module to Medusa's Configurations
+
+Once you finish building the module, add it to Medusa's configurations to start using it.
+
+In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
+
+```ts title="medusa-config.ts"
+module.exports = defineConfig({
+ // ...
+ modules: [
+ {
+ resolve: "./src/modules/metal-prices",
+ options: {
+ accessToken: process.env.GOLD_API_TOKEN,
+ sandbox: process.env.GOLD_API_SANDBOX === "true",
+ },
+ },
+ ],
+})
+```
+
+Each object in the `modules` array has a `resolve` property, whose value is either a path to the module's directory, or an `npm` package’s name.
+
+The object also has an `options` property that accepts the module's options. You set the `accessToken` and `sandbox` options based on environment variables.
+
+You'll find the access token at the top of your GoldAPI.io dashboard.
+
+
+
+Set the access token as an environment variable in `.env`:
+
+```bash
+GOLD_API_TOKEN=
+```
+
+You'll start using the module in the next steps.
+
+***
+
+## Step 3: Add Custom Item to Cart Workflow
+
+In this section, you'll implement the logic to retrieve the real-time price of a variant based on the metals in it, then add the variant to the cart with the custom price. You'll implement this logic in a workflow.
+
+A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it's a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in an endpoint.
+
+Learn more about workflows in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md)
+
+The workflow you'll implement in this section has the following steps:
+
+- [useQueryGraphStep (Retrieve Cart)](https://docs.medusajs.com/references/helper-steps/useQueryGraphStep/index.html.md): Retrieve the cart's ID and currency using Query.
+- [useQueryGraphStep (Retrieve Variant)](https://docs.medusajs.com/references/helper-steps/useQueryGraphStep/index.html.md): Retrieve the variant's details using Query
+- [getVariantMetalPricesStep](#getvariantmetalpricesstep): Retrieve the variant's price using the third-party service.
+- [addToCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/addToCartWorkflow/index.html.md): Add the item with the custom price to the cart.
+- [useQueryGraphStep (Retrieve Cart)](https://docs.medusajs.com/references/helper-steps/useQueryGraphStep/index.html.md): Retrieve the updated cart's details using Query.
+
+`useQueryGraphStep` and `addToCartWorkflow` are available through Medusa's core workflows package. You'll only implement the `getVariantMetalPricesStep`.
+
+### getVariantMetalPricesStep
+
+The `getVariantMetalPricesStep` will retrieve the real-time metal price of a variant received as an input.
+
+To create the step, create the file `src/workflows/steps/get-variant-metal-prices.ts` with the following content:
+
+
+
+```ts title="src/workflows/steps/get-variant-metal-prices.ts"
+import { createStep } from "@medusajs/framework/workflows-sdk"
+import { ProductVariantDTO } from "@medusajs/framework/types"
+import { METAL_PRICES_MODULE } from "../../modules/metal-prices"
+import MetalPricesModuleService from "../../modules/metal-prices/service"
+
+export type GetVariantMetalPricesStepInput = {
+ variant: ProductVariantDTO & {
+ calculated_price?: {
+ calculated_amount: number
+ }
+ }
+ currencyCode: string
+ quantity?: number
+}
+
+export const getVariantMetalPricesStep = createStep(
+ "get-variant-metal-prices",
+ async ({
+ variant,
+ currencyCode,
+ quantity = 1,
+ }: GetVariantMetalPricesStepInput, { container }) => {
+ const metalPricesModuleService: MetalPricesModuleService =
+ container.resolve(METAL_PRICES_MODULE)
+
+ // TODO
+ }
+)
+```
+
+You create a step with `createStep` from the Workflows SDK. It accepts two parameters:
+
+1. The step's unique name, which is `get-variant-metal-prices`.
+2. An async function that receives two parameters:
+ - An input object with the variant, currency code, and quantity. The variant has a `calculated_price` property that holds the variant's fixed price in the Medusa application. This is useful when you want to add a fixed price to the real-time custom price, such as handling fees.
+ - The [Medusa container](https://docs.medusajs.com/docs/learn/fundamentals/medusa-container/index.html.md), which is a registry of framework and commerce tools that you can access in the step.
+
+In the step function, so far you only resolve the Metal Prices Module's service from the Medusa container.
+
+Next, you'll validate that the specified variant can have its price calculated. Add the following import at the top of the file:
+
+```ts title="src/workflows/steps/get-variant-metal-prices.ts"
+import { MedusaError } from "@medusajs/framework/utils"
+```
+
+And replace the `TODO` in the step function with the following:
+
+```ts title="src/workflows/steps/get-variant-metal-prices.ts"
+const variantMetal = variant.options.find(
+ (option) => option.option?.title === "Metal"
+)?.value
+const metalSymbol = await metalPricesModuleService
+ .getMetalSymbol(variantMetal || "")
+
+if (!metalSymbol) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ "Variant doesn't have metal. Make sure the variant's SKU matches a metal symbol."
+ )
+}
+
+if (!variant.weight) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ "Variant doesn't have weight. Make sure the variant has weight to calculate its price."
+ )
+}
+
+// TODO retrieve custom price
+```
+
+In the code above, you first retrieve the metal option's value from the variant's options, assuming that a variant has metals if it has a `Metal` option. Then, you retrieve the metal symbol of the option's value using the `getMetalSymbol` method of the Metal Prices Module's service.
+
+If the variant doesn't have a metal in its options, the option's value is not valid, or the variant doesn't have a weight, you throw an error. The weight is necessary to calculate the price based on the metal's price per weight.
+
+Next, you'll retrieve the real-time price of the metal using the third-party service. Replace the `TODO` with the following:
+
+```ts title="src/workflows/steps/get-variant-metal-prices.ts"
+let price = variant.calculated_price?.calculated_amount || 0
+const weight = variant.weight
+const { price: metalPrice } = await metalPricesModuleService.getMetalPrice(
+ metalSymbol as MetalSymbols, currencyCode
+)
+price += (metalPrice * weight * quantity)
+
+return new StepResponse(price)
+```
+
+In the code above, you first set the price to the variant's fixed price, if it has one. Then, you retrieve the metal's price using the `getMetalPrice` method of the Metal Prices Module's service.
+
+Finally, you calculate the price by multiplying the metal's price by the variant's weight and the quantity to add to the cart, then add the fixed price to it.
+
+Every step must return a `StepResponse` instance. The `StepResponse` constructor accepts the step's output as a parameter, which in this case is the variant's price.
+
+### Create addCustomToCartWorkflow
+
+Now that you have the `getVariantMetalPricesStep`, you can create the workflow that adds the item with custom pricing to the cart.
+
+Create the file `src/workflows/add-custom-to-cart.ts` with the following content:
+
+
+
+```ts title="src/workflows/add-custom-to-cart.ts" highlights={workflowHighlights}
+import { createWorkflow } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { QueryContext } from "@medusajs/framework/utils"
+
+type AddCustomToCartWorkflowInput = {
+ cart_id: string
+ item: {
+ variant_id: string
+ quantity: number
+ metadata?: Record
+ }
+}
+
+export const addCustomToCartWorkflow = createWorkflow(
+ "add-custom-to-cart",
+ ({ cart_id, item }: AddCustomToCartWorkflowInput) => {
+ // @ts-ignore
+ const { data: carts } = useQueryGraphStep({
+ entity: "cart",
+ filters: { id: cart_id },
+ fields: ["id", "currency_code"],
+ })
+
+ const { data: variants } = useQueryGraphStep({
+ entity: "variant",
+ fields: [
+ "*",
+ "options.*",
+ "options.option.*",
+ "calculated_price.*",
+ ],
+ filters: {
+ id: item.variant_id,
+ },
+ options: {
+ throwIfKeyNotFound: true,
+ },
+ context: {
+ calculated_price: QueryContext({
+ currency_code: carts[0].currency_code,
+ }),
+ },
+ }).config({ name: "retrieve-variant" })
+
+ // TODO add more steps
+ }
+)
+```
+
+You create a workflow with `createWorkflow` from the Workflows SDK. It accepts two parameters:
+
+1. The workflow's unique name, which is `add-custom-to-cart`.
+2. A function that receives an input object with the cart's ID and the item to add to the cart. The item has the variant's ID, quantity, and optional metadata.
+
+In the function, you first retrieve the cart's details using the `useQueryGraphStep` helper step. This step uses [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md) which is a Modules SDK tool that retrieves data across modules. You use it to retrieve the cart's ID and currency code.
+
+You also retrieve the variant's details using the `useQueryGraphStep` helper step. You pass the variant's ID to the step's filters and specify the fields to retrieve. To retrieve the variant's price based on the cart's context, you pass the cart's currency code to the `calculated_price` context.
+
+Next, you'll retrieve the variant's real-time price using the `getVariantMetalPricesStep` you created earlier. First, add the following import:
+
+```ts title="src/workflows/add-custom-to-cart.ts"
+import {
+ getVariantMetalPricesStep,
+ GetVariantMetalPricesStepInput,
+} from "./steps/get-variant-metal-prices"
+```
+
+Then, replace the `TODO` in the workflow with the following:
+
+```ts title="src/workflows/add-custom-to-cart.ts"
+const price = getVariantMetalPricesStep({
+ variant: variants[0],
+ currencyCode: carts[0].currency_code,
+ quantity: item.quantity,
+} as unknown as GetVariantMetalPricesStepInput)
+
+// TODO add item with custom price to cart
+```
+
+You execute the `getVariantMetalPricesStep` passing it the variant's details, the cart's currency code, and the quantity of the item to add to the cart. The step returns the variant's custom price.
+
+Next, you'll add the item with the custom price to the cart. First, add the following imports at the top of the file:
+
+```ts title="src/workflows/add-custom-to-cart.ts"
+import { transform } from "@medusajs/framework/workflows-sdk"
+import { addToCartWorkflow } from "@medusajs/medusa/core-flows"
+```
+
+Then, replace the `TODO` in the workflow with the following:
+
+```ts title="src/workflows/add-custom-to-cart.ts"
+const itemToAdd = transform({
+ item,
+ price,
+}, (data) => {
+ return [{
+ ...data.item,
+ unit_price: data.price,
+ }]
+})
+
+addToCartWorkflow.runAsStep({
+ input: {
+ items: itemToAdd,
+ cart_id,
+ },
+})
+
+// TODO retrieve and return cart
+```
+
+You prepare the item to add to the cart using `transform` from the Workflows SDK. It allows you to manipulate and create variables in a workflow. After that, you use Medusa's `addToCartWorkflow` to add the item with the custom price to the cart.
+
+A workflow's constructor function has some constraints in implementation, which is why you need to use `transform` for variable manipulation. Learn more about these constraints in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/constructor-constraints/index.html.md).
+
+Lastly, you'll retrieve the cart's details again and return them. Add the following import at the beginning of the file:
+
+```ts title="src/workflows/add-custom-to-cart.ts"
+import { WorkflowResponse } from "@medusajs/framework/workflows-sdk"
+```
+
+And replace the last `TODO` in the workflow with the following:
+
+```ts title="src/workflows/add-custom-to-cart.ts"
+// @ts-ignore
+const { data: updatedCarts } = useQueryGraphStep({
+ entity: "cart",
+ filters: { id: cart_id },
+ fields: ["id", "items.*"],
+}).config({ name: "refetch-cart" })
+
+return new WorkflowResponse({
+ cart: updatedCarts[0],
+})
+```
+
+In the code above, you retrieve the updated cart's details using the `useQueryGraphStep` helper step. To return data from the workflow, you create and return a `WorkflowResponse` instance. It accepts as a parameter the data to return, which is the updated cart.
+
+In the next step, you'll use the workflow in a custom route to add an item with a custom price to the cart.
+
+***
+
+## Step 4: Create Add Custom Item to Cart API Route
+
+Now that you've implemented the logic to add an item with a custom price to the cart, you'll expose this functionality in an API route.
+
+An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts. You'll create an API route at the path `/store/carts/:id/line-items-metals` that executes the workflow from the previous step to add a product variant with custom price to the cart.
+
+Learn more about API routes in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md).
+
+### Create API Route
+
+An API route is created in a `route.ts` file under a sub-directory of the `src/api` directory.
+
+The path of the API route is the file's path relative to `src/api`. So, to create the `/store/carts/:id/line-items-metals` API route, create the file `src/api/store/carts/[id]/line-items-metals/route.ts` with the following content:
+
+
+
+```ts title="src/api/store/carts/[id]/line-items-metals/route.ts"
+import { MedusaRequest, MedusaResponse } from "@medusajs/framework"
+import { HttpTypes } from "@medusajs/framework/types"
+import { addCustomToCartWorkflow } from "../../../../../workflows/add-custom-to-cart"
+
+export const POST = async (
+ req: MedusaRequest,
+ res: MedusaResponse
+) => {
+ const { id } = req.params
+ const item = req.validatedBody
+
+ const { result } = await addCustomToCartWorkflow(req.scope)
+ .run({
+ input: {
+ cart_id: id,
+ item,
+ },
+ })
+
+ res.status(200).json({ cart: result.cart })
+}
+```
+
+Since you export a `POST` function in this file, you're exposing a `POST` API route at `/store/carts/:id/line-items-metals`. The route handler function accepts two parameters:
+
+1. A request object with details and context on the request, such as path and body parameters.
+2. A response object to manipulate and send the response.
+
+In the function, you retrieve the cart's ID from the path parameter, and the item's details from the request body. This API route will accept the same request body parameters as Medusa's [Add Item to Cart API Route](https://docs.medusajs.com/api/store#carts_postcartsidlineitems).
+
+Then, you execute the `addCustomToCartWorkflow` by invoking it, passing it the Medusa container, which is available in the request's `scope` property, then executing its `run` method. You pass the workflow's input object with the cart's ID and the item to add to the cart.
+
+Finally, you return a response with the updated cart's details.
+
+### Add Request Body Validation Middleware
+
+To ensure that the request body contains the required parameters, you'll add a middleware that validates the incoming request's body based on a defined schema.
+
+A middleware is a function executed before the API route when a request is sent to it. You define middlewares in Medusa in the `src/api/middlewares.ts` directory.
+
+Learn more about middlewares in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/middlewares/index.html.md).
+
+To add a validation middleware to the custom API route, create the file `src/api/middlewares.ts` with the following content:
+
+
+
+```ts title="src/api/middlewares.ts"
+import {
+ defineMiddlewares,
+ validateAndTransformBody,
+} from "@medusajs/framework/http"
+import {
+ StoreAddCartLineItem,
+} from "@medusajs/medusa/api/store/carts/validators"
+
+export default defineMiddlewares({
+ routes: [
+ {
+ matcher: "/store/carts/:id/line-items-metals",
+ method: "POST",
+ middlewares: [
+ validateAndTransformBody(
+ StoreAddCartLineItem
+ ),
+ ],
+ },
+ ],
+})
+```
+
+In this file, you export the middlewares definition using `defineMiddlewares` from the Medusa Framework. This function accepts an object having a `routes` property, which is an array of middleware configurations to apply on routes.
+
+You pass in the `routes` array an object having the following properties:
+
+- `matcher`: The route to apply the middleware on.
+- `method`: The HTTP method to apply the middleware on for the specified API route.
+- `middlewares`: An array of the middlewares to apply. You apply the `validateAndTransformBody` middleware, which validates the request body based on the `StoreAddCartLineItem` schema. This validation schema is the same schema used for Medusa's [Add Item to Cart API Route](https://docs.medusajs.com/api/store#carts_postcartsidlineitems).
+
+Any request sent to the `/store/carts/:id/line-items-metals` API route will now fail if it doesn't have the required parameters.
+
+Learn more about API route validation in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/validation/index.html.md).
+
+### Prepare to Test API Route
+
+Before you test the API route, you'll prepare and retrieve the necessary data to add a product variant with a custom price to the cart.
+
+#### Create Product with Metal Variant
+
+You'll first create a product that has a `Metal` option, and variant(s) with values for this option.
+
+Start the Medusa application with the following command:
+
+```bash npm2yarn
+npm run dev
+```
+
+Then, open the Medusa Admin dashboard at `localhost:9000/app` and log in with the email and password you created when you installed the Medusa application in the first step.
+
+Once you log in, click on Products in the sidebar, then click the Create button at the top right.
+
+
+
+Then, in the Create Product form:
+
+1. Enter a name for the product, and optionally enter other details like description.
+2. Enable the "Yes, this is a product with variants" toggle.
+3. Under Product Options, enter "Metal" for the title, and enter "Gold" for the values.
+
+Once you're done, click the Continue button.
+
+
+
+You can skip the next two steps by clicking the Continue button again, then the Publish button.
+
+Once you're done, the product's page will open. You'll now add weight to the product's Gold variant. To do that:
+
+- Scroll to the Variants section and find the Gold variant.
+- Click on the three-dots icon at its right.
+- Choose "Edit" from the dropdown.
+
+
+
+In the side window that opens, find the Weight field, enter the weight, and click the Save button.
+
+
+
+Finally, you need to set fixed prices for the variant, even if they're just `0`. To do that:
+
+1. Click on the three-dots icon at the top right of the Variants section.
+2. Choose "Edit Prices" from the dropdown.
+
+
+
+For each cell in the table, either enter a fixed price for the specified currency or leave it as `0`. Once you're done, click the Save button.
+
+
+
+You'll use this variant to add it to the cart later. You can find its ID by clicking on the variant, opening its details page. Then, on the details page, click on the icon at the right of the JSON section, and copy the ID from the JSON data.
+
+
+
+#### Retrieve Publishable API Key
+
+All requests sent to API routes starting with `/store` must have a publishable API key in the header. This ensures the request's operations are scoped to the publishable API key's associated sales channels. For example, products that aren't available in a cart's sales channel can't be added to it.
+
+To retrieve the publishable API key, on the Medusa Admin:
+
+1. Click on Settings in the sidebar at the bottom left.
+2. Click on Publishable API Keys from the sidebar, then click on a publishable API key in the list.
+
+
+
+3. Click on the publishable API key to copy it.
+
+
+
+You'll use this key when you test the API route.
+
+### Test API Route
+
+To test out the API route, you need to create a cart. A cart must be associated with a region. So, to retrieve the ID of a region in your store, send a `GET` request to the `/store/regions` API route:
+
+```bash
+curl 'localhost:9000/store/regions' \
+-H 'x-publishable-api-key: {api_key}'
+```
+
+Make sure to replace `{api_key}` with the publishable API key you copied earlier.
+
+This will return a list of regions. Copy the ID of one of the regions.
+
+Then, send a `POST` request to the `/store/carts` API route to create a cart:
+
+```bash
+curl -X POST 'localhost:9000/store/carts' \
+-H 'x-publishable-api-key: {api_key}' \
+-H 'Content-Type: application/json' \
+--data '{
+ "region_id": "{region_id}"
+}'
+```
+
+Make sure to replace `{api_key}` with the publishable API key you copied earlier, and `{region_id}` with the ID of a region from the previous request.
+
+This will return the created cart. Copy the ID of the cart to use it next.
+
+Finally, to add the Gold variant to the cart with a custom price, send a `POST` request to the `/store/carts/:id/line-items-metals` API route:
+
+```bash
+curl -X POST 'localhost:9000/store/carts/{cart_id}/line-items-metals' \
+-H 'x-publishable-api-key: {api_key}' \
+-H 'Content-Type: application/json' \
+--data '{
+ "variant_id": "{variant_id}",
+ "quantity": 1
+}'
+```
+
+Make sure to replace:
+
+- `{api_key}` with the publishable API key you copied earlier.
+- `{cart_id}` with the ID of the cart you created.
+- `{variant_id}` with the ID of the Gold variant you created.
+
+This will return the cart's details, where you can see in its `items` array the item with the custom price:
+
+```json title="Example Response"
+{
+ "cart": {
+ "items": [
+ {
+ "variant_id": "{variant_id}",
+ "quantity": 1,
+ "is_custom_price": true,
+ // example custom price
+ "unit_price": 2000
+ }
+ ]
+ }
+}
+```
+
+The price will be the result of the calculation you've implemented earlier, which is the fixed price of the variant plus the real-time price of the metal, multiplied by the weight of the variant and the quantity added to the cart.
+
+This price will be reflected in the cart's total price, and you can proceed to checkout with the custom-priced item.
+
+***
+
+## Next Steps
+
+You've now implemented custom item pricing in Medusa. You can also customize the [storefront](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/nextjs-starter/index.html.md) to use the new API route to add custom-priced items to the cart.
+
+If you're new to Medusa, check out the [main documentation](https://docs.medusajs.com/docs/learn/index.html.md), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
+
+To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
+
+
# Implement Quote Management in Medusa
In this guide, you'll learn how to implement quote management in Medusa.
@@ -38283,795 +39831,6 @@ If you're new to Medusa, check out the [main documentation](https://docs.medusaj
To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
-# Implement Custom Line Item Pricing in Medusa
-
-In this guide, you'll learn how to add line items with custom prices to a cart in Medusa.
-
-When you install a Medusa application, you get a fully-fledged commerce platform with a framework for customization. The Medusa application's commerce features are built around [commerce modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md) which are available out-of-the-box. These features include managing carts and adding line items to them.
-
-By default, you can add product variants to the cart, where the price of its associated line item is based on the product variant's price. However, you can build customizations to add line items with custom prices to the cart. This is useful when integrating an Enterprise Resource Planning (ERP), Product Information Management (PIM), or other third-party services that provide real-time prices for your products.
-
-To showcase how to add line items with custom prices to the cart, this guide uses [GoldAPI.io](https://www.goldapi.io) as an example of a third-party system that you can integrate for real-time prices. You can follow the same approach for other third-party integrations that provide custom pricing.
-
-You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
-
-### Summary
-
-This guide will teach you how to:
-
-- Install and set up Medusa.
-- Integrate the third-party service [GoldAPI.io](https://www.goldapi.io) that retrieves real-time prices for metals like Gold and Silver.
-- Add an API route to add a product variant that has metals, such as a gold ring, to the cart with the real-time price retrieved from the third-party service.
-
-
-
-- [Custom Item Price Repository](https://github.com/medusajs/examples/tree/main/custom-item-price): Find the full code for this guide in this repository.
-- [OpenApi Specs for Postman](https://res.cloudinary.com/dza7lstvk/raw/upload/v1738246728/OpenApi/Custom_Item_Price_gdfnl3.yaml): Import this OpenApi Specs file into tools like Postman.
-
-***
-
-## Step 1: Install a Medusa Application
-
-### Prerequisites
-
-- [Node.js v20+](https://nodejs.org/en/download)
-- [Git CLI tool](https://git-scm.com/downloads)
-- [PostgreSQL](https://www.postgresql.org/download/)
-
-Start by installing the Medusa application on your machine with the following command:
-
-```bash
-npx create-medusa-app@latest
-```
-
-You'll first be asked for the project's name. You can also optionally choose to install the [Next.js starter storefront](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/nextjs-starter/index.html.md).
-
-Afterwards, the installation process will start, which will install the Medusa application in a directory with your project's name. If you chose to install the Next.js starter, it'll be installed in a separate directory with the `{project-name}-storefront` name.
-
-The Medusa application is composed of a headless Node.js server and an admin dashboard. The storefront is installed or custom-built separately and connects to the Medusa application through its REST endpoints, called [API routes](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md). Learn more about Medusa's architecture in [this documentation](https://docs.medusajs.com/docs/learn/introduction/architecture/index.html.md).
-
-Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterwards, you can log in with the new user and explore the dashboard.
-
-Check out the [troubleshooting guides](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/troubleshooting/create-medusa-app-errors/index.html.md) for help.
-
-***
-
-## Step 2: Integrate GoldAPI.io
-
-### Prerequisites
-
-- [GoldAPI.io Account. You can create a free account.](https://www.goldapi.io)
-
-To integrate third-party services into Medusa, you create a custom module. A module is a reusable package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
-
-In this step, you'll create a Metal Price Module that uses the GoldAPI.io service to retrieve real-time prices for metals like Gold and Silver. You'll use this module later to retrieve the real-time price of a product variant based on the metals in it, and add it to the cart with that custom price.
-
-Learn more about modules in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md).
-
-### Create Module Directory
-
-A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/metal-prices`.
-
-
-
-### Create Module's Service
-
-You define a module's functionalities in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to the database, which is useful if your module defines tables in the database, or connect to a third-party service.
-
-In this section, you'll create the Metal Prices Module's service that connects to the GoldAPI.io service to retrieve real-time prices for metals.
-
-Start by creating the file `src/modules/metal-prices/service.ts` with the following content:
-
-
-
-```ts title="src/modules/metal-prices/service.ts"
-type Options = {
- accessToken: string
- sandbox?: boolean
-}
-
-export default class MetalPricesModuleService {
- protected options_: Options
-
- constructor({}, options: Options) {
- this.options_ = options
- }
-}
-```
-
-A module can accept options that are passed to its service. You define an `Options` type that indicates the options the module accepts. It accepts two options:
-
-- `accessToken`: The access token for the GoldAPI.io service.
-- `sandbox`: A boolean that indicates whether to simulate sending requests to the GoldAPI.io service. This is useful when running in a test environment.
-
-The service's constructor receives the module's options as a second parameter. You store the options in the service's `options_` property.
-
-A module has a container of Medusa framework tools and local resources in the module that you can access in the service constructor's first parameter. Learn more in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/container/index.html.md).
-
-#### Add Method to Retrieve Metal Prices
-
-Next, you'll add the method to retrieve the metal prices from the third-party service.
-
-First, add the following types at the beginning of `src/modules/metal-prices/service.ts`:
-
-```ts title="src/modules/metal-prices/service.ts"
-export enum MetalSymbols {
- Gold = "XAU",
- Silver = "XAG",
- Platinum = "XPT",
- Palladium = "XPD"
-}
-
-export type PriceResponse = {
- metal: MetalSymbols
- currency: string
- exchange: string
- symbol: string
- price: number
- [key: string]: unknown
-}
-
-```
-
-The `MetalSymbols` enum defines the symbols for metals like Gold, Silver, Platinum, and Palladium. The `PriceResponse` type defines the structure of the response from the GoldAPI.io's endpoint.
-
-Next, add the method `getMetalPrices` to the `MetalPricesModuleService` class:
-
-```ts title="src/modules/metal-prices/service.ts"
-import { MedusaError } from "@medusajs/framework/utils"
-
-// ...
-
-export default class MetalPricesModuleService {
- // ...
- async getMetalPrice(
- symbol: MetalSymbols,
- currency: string
- ): Promise {
- const upperCaseSymbol = symbol.toUpperCase()
- const upperCaseCurrency = currency.toUpperCase()
-
- return fetch(`https://www.goldapi.io/api/${upperCaseSymbol}/${upperCaseCurrency}`, {
- headers: {
- "x-access-token": this.options_.accessToken,
- "Content-Type": "application/json",
- },
- redirect: "follow",
- }).then((response) => response.json())
- .then((response) => {
- if (response.error) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- response.error
- )
- }
-
- return response
- })
- }
-}
-```
-
-The `getMetalPrice` method accepts the metal symbol and currency as parameters. You send a request to GoldAPI.io's `/api/{symbol}/{currency}` endpoint to retrieve the metal's price, also passing the access token in the request's headers.
-
-If the response contains an error, you throw a `MedusaError` with the error message. Otherwise, you return the response, which is of type `PriceResponse`.
-
-#### Add Helper Methods
-
-You'll also add two helper methods to the `MetalPricesModuleService`. The first one is `getMetalSymbols` that returns the metal symbols as an array of strings:
-
-```ts title="src/modules/metal-prices/service.ts"
-export default class MetalPricesModuleService {
- // ...
- async getMetalSymbols(): Promise {
- return Object.values(MetalSymbols)
- }
-}
-```
-
-The second is `getMetalSymbol` that receives a name like `gold` and returns the corresponding metal symbol:
-
-```ts title="src/modules/metal-prices/service.ts"
-export default class MetalPricesModuleService {
- // ...
- async getMetalSymbol(name: string): Promise {
- const formattedName = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase()
- return MetalSymbols[formattedName as keyof typeof MetalSymbols]
- }
-}
-```
-
-You'll use these methods in later steps.
-
-### Export Module Definition
-
-The final piece to a module is its definition, which you export in an `index.ts` file at its root directory. This definition tells Medusa the name of the module and its service.
-
-So, create the file `src/modules/metal-prices/index.ts` with the following content:
-
-
-
-```ts title="src/modules/metal-prices/index.ts"
-import { Module } from "@medusajs/framework/utils"
-import MetalPricesModuleService from "./service"
-
-export const METAL_PRICES_MODULE = "metal-prices"
-
-export default Module(METAL_PRICES_MODULE, {
- service: MetalPricesModuleService,
-})
-```
-
-You use the `Module` function from the Modules SDK to create the module's definition. It accepts two parameters:
-
-1. The module's name, which is `metal-prices`.
-2. An object with a required property `service` indicating the module's service.
-
-### Add Module to Medusa's Configurations
-
-Once you finish building the module, add it to Medusa's configurations to start using it.
-
-In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
-
-```ts title="medusa-config.ts"
-module.exports = defineConfig({
- // ...
- modules: [
- {
- resolve: "./src/modules/metal-prices",
- options: {
- accessToken: process.env.GOLD_API_TOKEN,
- sandbox: process.env.GOLD_API_SANDBOX === "true",
- },
- },
- ],
-})
-```
-
-Each object in the `modules` array has a `resolve` property, whose value is either a path to the module's directory, or an `npm` package’s name.
-
-The object also has an `options` property that accepts the module's options. You set the `accessToken` and `sandbox` options based on environment variables.
-
-You'll find the access token at the top of your GoldAPI.io dashboard.
-
-
-
-Set the access token as an environment variable in `.env`:
-
-```bash
-GOLD_API_TOKEN=
-```
-
-You'll start using the module in the next steps.
-
-***
-
-## Step 3: Add Custom Item to Cart Workflow
-
-In this section, you'll implement the logic to retrieve the real-time price of a variant based on the metals in it, then add the variant to the cart with the custom price. You'll implement this logic in a workflow.
-
-A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it's a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in an endpoint.
-
-Learn more about workflows in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md)
-
-The workflow you'll implement in this section has the following steps:
-
-- [useQueryGraphStep (Retrieve Cart)](https://docs.medusajs.com/references/helper-steps/useQueryGraphStep/index.html.md): Retrieve the cart's ID and currency using Query.
-- [useQueryGraphStep (Retrieve Variant)](https://docs.medusajs.com/references/helper-steps/useQueryGraphStep/index.html.md): Retrieve the variant's details using Query
-- [getVariantMetalPricesStep](#getvariantmetalpricesstep): Retrieve the variant's price using the third-party service.
-- [addToCartWorkflow](https://docs.medusajs.com/references/medusa-workflows/addToCartWorkflow/index.html.md): Add the item with the custom price to the cart.
-- [useQueryGraphStep (Retrieve Cart)](https://docs.medusajs.com/references/helper-steps/useQueryGraphStep/index.html.md): Retrieve the updated cart's details using Query.
-
-`useQueryGraphStep` and `addToCartWorkflow` are available through Medusa's core workflows package. You'll only implement the `getVariantMetalPricesStep`.
-
-### getVariantMetalPricesStep
-
-The `getVariantMetalPricesStep` will retrieve the real-time metal price of a variant received as an input.
-
-To create the step, create the file `src/workflows/steps/get-variant-metal-prices.ts` with the following content:
-
-
-
-```ts title="src/workflows/steps/get-variant-metal-prices.ts"
-import { createStep } from "@medusajs/framework/workflows-sdk"
-import { ProductVariantDTO } from "@medusajs/framework/types"
-import { METAL_PRICES_MODULE } from "../../modules/metal-prices"
-import MetalPricesModuleService from "../../modules/metal-prices/service"
-
-export type GetVariantMetalPricesStepInput = {
- variant: ProductVariantDTO & {
- calculated_price?: {
- calculated_amount: number
- }
- }
- currencyCode: string
- quantity?: number
-}
-
-export const getVariantMetalPricesStep = createStep(
- "get-variant-metal-prices",
- async ({
- variant,
- currencyCode,
- quantity = 1,
- }: GetVariantMetalPricesStepInput, { container }) => {
- const metalPricesModuleService: MetalPricesModuleService =
- container.resolve(METAL_PRICES_MODULE)
-
- // TODO
- }
-)
-```
-
-You create a step with `createStep` from the Workflows SDK. It accepts two parameters:
-
-1. The step's unique name, which is `get-variant-metal-prices`.
-2. An async function that receives two parameters:
- - An input object with the variant, currency code, and quantity. The variant has a `calculated_price` property that holds the variant's fixed price in the Medusa application. This is useful when you want to add a fixed price to the real-time custom price, such as handling fees.
- - The [Medusa container](https://docs.medusajs.com/docs/learn/fundamentals/medusa-container/index.html.md), which is a registry of framework and commerce tools that you can access in the step.
-
-In the step function, so far you only resolve the Metal Prices Module's service from the Medusa container.
-
-Next, you'll validate that the specified variant can have its price calculated. Add the following import at the top of the file:
-
-```ts title="src/workflows/steps/get-variant-metal-prices.ts"
-import { MedusaError } from "@medusajs/framework/utils"
-```
-
-And replace the `TODO` in the step function with the following:
-
-```ts title="src/workflows/steps/get-variant-metal-prices.ts"
-const variantMetal = variant.options.find(
- (option) => option.option?.title === "Metal"
-)?.value
-const metalSymbol = await metalPricesModuleService
- .getMetalSymbol(variantMetal || "")
-
-if (!metalSymbol) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- "Variant doesn't have metal. Make sure the variant's SKU matches a metal symbol."
- )
-}
-
-if (!variant.weight) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- "Variant doesn't have weight. Make sure the variant has weight to calculate its price."
- )
-}
-
-// TODO retrieve custom price
-```
-
-In the code above, you first retrieve the metal option's value from the variant's options, assuming that a variant has metals if it has a `Metal` option. Then, you retrieve the metal symbol of the option's value using the `getMetalSymbol` method of the Metal Prices Module's service.
-
-If the variant doesn't have a metal in its options, the option's value is not valid, or the variant doesn't have a weight, you throw an error. The weight is necessary to calculate the price based on the metal's price per weight.
-
-Next, you'll retrieve the real-time price of the metal using the third-party service. Replace the `TODO` with the following:
-
-```ts title="src/workflows/steps/get-variant-metal-prices.ts"
-let price = variant.calculated_price?.calculated_amount || 0
-const weight = variant.weight
-const { price: metalPrice } = await metalPricesModuleService.getMetalPrice(
- metalSymbol as MetalSymbols, currencyCode
-)
-price += (metalPrice * weight * quantity)
-
-return new StepResponse(price)
-```
-
-In the code above, you first set the price to the variant's fixed price, if it has one. Then, you retrieve the metal's price using the `getMetalPrice` method of the Metal Prices Module's service.
-
-Finally, you calculate the price by multiplying the metal's price by the variant's weight and the quantity to add to the cart, then add the fixed price to it.
-
-Every step must return a `StepResponse` instance. The `StepResponse` constructor accepts the step's output as a parameter, which in this case is the variant's price.
-
-### Create addCustomToCartWorkflow
-
-Now that you have the `getVariantMetalPricesStep`, you can create the workflow that adds the item with custom pricing to the cart.
-
-Create the file `src/workflows/add-custom-to-cart.ts` with the following content:
-
-
-
-```ts title="src/workflows/add-custom-to-cart.ts" highlights={workflowHighlights}
-import { createWorkflow } from "@medusajs/framework/workflows-sdk"
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-import { QueryContext } from "@medusajs/framework/utils"
-
-type AddCustomToCartWorkflowInput = {
- cart_id: string
- item: {
- variant_id: string
- quantity: number
- metadata?: Record
- }
-}
-
-export const addCustomToCartWorkflow = createWorkflow(
- "add-custom-to-cart",
- ({ cart_id, item }: AddCustomToCartWorkflowInput) => {
- // @ts-ignore
- const { data: carts } = useQueryGraphStep({
- entity: "cart",
- filters: { id: cart_id },
- fields: ["id", "currency_code"],
- })
-
- const { data: variants } = useQueryGraphStep({
- entity: "variant",
- fields: [
- "*",
- "options.*",
- "options.option.*",
- "calculated_price.*",
- ],
- filters: {
- id: item.variant_id,
- },
- options: {
- throwIfKeyNotFound: true,
- },
- context: {
- calculated_price: QueryContext({
- currency_code: carts[0].currency_code,
- }),
- },
- }).config({ name: "retrieve-variant" })
-
- // TODO add more steps
- }
-)
-```
-
-You create a workflow with `createWorkflow` from the Workflows SDK. It accepts two parameters:
-
-1. The workflow's unique name, which is `add-custom-to-cart`.
-2. A function that receives an input object with the cart's ID and the item to add to the cart. The item has the variant's ID, quantity, and optional metadata.
-
-In the function, you first retrieve the cart's details using the `useQueryGraphStep` helper step. This step uses [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md) which is a Modules SDK tool that retrieves data across modules. You use it to retrieve the cart's ID and currency code.
-
-You also retrieve the variant's details using the `useQueryGraphStep` helper step. You pass the variant's ID to the step's filters and specify the fields to retrieve. To retrieve the variant's price based on the cart's context, you pass the cart's currency code to the `calculated_price` context.
-
-Next, you'll retrieve the variant's real-time price using the `getVariantMetalPricesStep` you created earlier. First, add the following import:
-
-```ts title="src/workflows/add-custom-to-cart.ts"
-import {
- getVariantMetalPricesStep,
- GetVariantMetalPricesStepInput,
-} from "./steps/get-variant-metal-prices"
-```
-
-Then, replace the `TODO` in the workflow with the following:
-
-```ts title="src/workflows/add-custom-to-cart.ts"
-const price = getVariantMetalPricesStep({
- variant: variants[0],
- currencyCode: carts[0].currency_code,
- quantity: item.quantity,
-} as unknown as GetVariantMetalPricesStepInput)
-
-// TODO add item with custom price to cart
-```
-
-You execute the `getVariantMetalPricesStep` passing it the variant's details, the cart's currency code, and the quantity of the item to add to the cart. The step returns the variant's custom price.
-
-Next, you'll add the item with the custom price to the cart. First, add the following imports at the top of the file:
-
-```ts title="src/workflows/add-custom-to-cart.ts"
-import { transform } from "@medusajs/framework/workflows-sdk"
-import { addToCartWorkflow } from "@medusajs/medusa/core-flows"
-```
-
-Then, replace the `TODO` in the workflow with the following:
-
-```ts title="src/workflows/add-custom-to-cart.ts"
-const itemToAdd = transform({
- item,
- price,
-}, (data) => {
- return [{
- ...data.item,
- unit_price: data.price,
- }]
-})
-
-addToCartWorkflow.runAsStep({
- input: {
- items: itemToAdd,
- cart_id,
- },
-})
-
-// TODO retrieve and return cart
-```
-
-You prepare the item to add to the cart using `transform` from the Workflows SDK. It allows you to manipulate and create variables in a workflow. After that, you use Medusa's `addToCartWorkflow` to add the item with the custom price to the cart.
-
-A workflow's constructor function has some constraints in implementation, which is why you need to use `transform` for variable manipulation. Learn more about these constraints in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/constructor-constraints/index.html.md).
-
-Lastly, you'll retrieve the cart's details again and return them. Add the following import at the beginning of the file:
-
-```ts title="src/workflows/add-custom-to-cart.ts"
-import { WorkflowResponse } from "@medusajs/framework/workflows-sdk"
-```
-
-And replace the last `TODO` in the workflow with the following:
-
-```ts title="src/workflows/add-custom-to-cart.ts"
-// @ts-ignore
-const { data: updatedCarts } = useQueryGraphStep({
- entity: "cart",
- filters: { id: cart_id },
- fields: ["id", "items.*"],
-}).config({ name: "refetch-cart" })
-
-return new WorkflowResponse({
- cart: updatedCarts[0],
-})
-```
-
-In the code above, you retrieve the updated cart's details using the `useQueryGraphStep` helper step. To return data from the workflow, you create and return a `WorkflowResponse` instance. It accepts as a parameter the data to return, which is the updated cart.
-
-In the next step, you'll use the workflow in a custom route to add an item with a custom price to the cart.
-
-***
-
-## Step 4: Create Add Custom Item to Cart API Route
-
-Now that you've implemented the logic to add an item with a custom price to the cart, you'll expose this functionality in an API route.
-
-An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts. You'll create an API route at the path `/store/carts/:id/line-items-metals` that executes the workflow from the previous step to add a product variant with custom price to the cart.
-
-Learn more about API routes in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md).
-
-### Create API Route
-
-An API route is created in a `route.ts` file under a sub-directory of the `src/api` directory.
-
-The path of the API route is the file's path relative to `src/api`. So, to create the `/store/carts/:id/line-items-metals` API route, create the file `src/api/store/carts/[id]/line-items-metals/route.ts` with the following content:
-
-
-
-```ts title="src/api/store/carts/[id]/line-items-metals/route.ts"
-import { MedusaRequest, MedusaResponse } from "@medusajs/framework"
-import { HttpTypes } from "@medusajs/framework/types"
-import { addCustomToCartWorkflow } from "../../../../../workflows/add-custom-to-cart"
-
-export const POST = async (
- req: MedusaRequest,
- res: MedusaResponse
-) => {
- const { id } = req.params
- const item = req.validatedBody
-
- const { result } = await addCustomToCartWorkflow(req.scope)
- .run({
- input: {
- cart_id: id,
- item,
- },
- })
-
- res.status(200).json({ cart: result.cart })
-}
-```
-
-Since you export a `POST` function in this file, you're exposing a `POST` API route at `/store/carts/:id/line-items-metals`. The route handler function accepts two parameters:
-
-1. A request object with details and context on the request, such as path and body parameters.
-2. A response object to manipulate and send the response.
-
-In the function, you retrieve the cart's ID from the path parameter, and the item's details from the request body. This API route will accept the same request body parameters as Medusa's [Add Item to Cart API Route](https://docs.medusajs.com/api/store#carts_postcartsidlineitems).
-
-Then, you execute the `addCustomToCartWorkflow` by invoking it, passing it the Medusa container, which is available in the request's `scope` property, then executing its `run` method. You pass the workflow's input object with the cart's ID and the item to add to the cart.
-
-Finally, you return a response with the updated cart's details.
-
-### Add Request Body Validation Middleware
-
-To ensure that the request body contains the required parameters, you'll add a middleware that validates the incoming request's body based on a defined schema.
-
-A middleware is a function executed before the API route when a request is sent to it. You define middlewares in Medusa in the `src/api/middlewares.ts` directory.
-
-Learn more about middlewares in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/middlewares/index.html.md).
-
-To add a validation middleware to the custom API route, create the file `src/api/middlewares.ts` with the following content:
-
-
-
-```ts title="src/api/middlewares.ts"
-import {
- defineMiddlewares,
- validateAndTransformBody,
-} from "@medusajs/framework/http"
-import {
- StoreAddCartLineItem,
-} from "@medusajs/medusa/api/store/carts/validators"
-
-export default defineMiddlewares({
- routes: [
- {
- matcher: "/store/carts/:id/line-items-metals",
- method: "POST",
- middlewares: [
- validateAndTransformBody(
- StoreAddCartLineItem
- ),
- ],
- },
- ],
-})
-```
-
-In this file, you export the middlewares definition using `defineMiddlewares` from the Medusa Framework. This function accepts an object having a `routes` property, which is an array of middleware configurations to apply on routes.
-
-You pass in the `routes` array an object having the following properties:
-
-- `matcher`: The route to apply the middleware on.
-- `method`: The HTTP method to apply the middleware on for the specified API route.
-- `middlewares`: An array of the middlewares to apply. You apply the `validateAndTransformBody` middleware, which validates the request body based on the `StoreAddCartLineItem` schema. This validation schema is the same schema used for Medusa's [Add Item to Cart API Route](https://docs.medusajs.com/api/store#carts_postcartsidlineitems).
-
-Any request sent to the `/store/carts/:id/line-items-metals` API route will now fail if it doesn't have the required parameters.
-
-Learn more about API route validation in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/validation/index.html.md).
-
-### Prepare to Test API Route
-
-Before you test the API route, you'll prepare and retrieve the necessary data to add a product variant with a custom price to the cart.
-
-#### Create Product with Metal Variant
-
-You'll first create a product that has a `Metal` option, and variant(s) with values for this option.
-
-Start the Medusa application with the following command:
-
-```bash npm2yarn
-npm run dev
-```
-
-Then, open the Medusa Admin dashboard at `localhost:9000/app` and log in with the email and password you created when you installed the Medusa application in the first step.
-
-Once you log in, click on Products in the sidebar, then click the Create button at the top right.
-
-
-
-Then, in the Create Product form:
-
-1. Enter a name for the product, and optionally enter other details like description.
-2. Enable the "Yes, this is a product with variants" toggle.
-3. Under Product Options, enter "Metal" for the title, and enter "Gold" for the values.
-
-Once you're done, click the Continue button.
-
-
-
-You can skip the next two steps by clicking the Continue button again, then the Publish button.
-
-Once you're done, the product's page will open. You'll now add weight to the product's Gold variant. To do that:
-
-- Scroll to the Variants section and find the Gold variant.
-- Click on the three-dots icon at its right.
-- Choose "Edit" from the dropdown.
-
-
-
-In the side window that opens, find the Weight field, enter the weight, and click the Save button.
-
-
-
-Finally, you need to set fixed prices for the variant, even if they're just `0`. To do that:
-
-1. Click on the three-dots icon at the top right of the Variants section.
-2. Choose "Edit Prices" from the dropdown.
-
-
-
-For each cell in the table, either enter a fixed price for the specified currency or leave it as `0`. Once you're done, click the Save button.
-
-
-
-You'll use this variant to add it to the cart later. You can find its ID by clicking on the variant, opening its details page. Then, on the details page, click on the icon at the right of the JSON section, and copy the ID from the JSON data.
-
-
-
-#### Retrieve Publishable API Key
-
-All requests sent to API routes starting with `/store` must have a publishable API key in the header. This ensures the request's operations are scoped to the publishable API key's associated sales channels. For example, products that aren't available in a cart's sales channel can't be added to it.
-
-To retrieve the publishable API key, on the Medusa Admin:
-
-1. Click on Settings in the sidebar at the bottom left.
-2. Click on Publishable API Keys from the sidebar, then click on a publishable API key in the list.
-
-
-
-3. Click on the publishable API key to copy it.
-
-
-
-You'll use this key when you test the API route.
-
-### Test API Route
-
-To test out the API route, you need to create a cart. A cart must be associated with a region. So, to retrieve the ID of a region in your store, send a `GET` request to the `/store/regions` API route:
-
-```bash
-curl 'localhost:9000/store/regions' \
--H 'x-publishable-api-key: {api_key}'
-```
-
-Make sure to replace `{api_key}` with the publishable API key you copied earlier.
-
-This will return a list of regions. Copy the ID of one of the regions.
-
-Then, send a `POST` request to the `/store/carts` API route to create a cart:
-
-```bash
-curl -X POST 'localhost:9000/store/carts' \
--H 'x-publishable-api-key: {api_key}' \
--H 'Content-Type: application/json' \
---data '{
- "region_id": "{region_id}"
-}'
-```
-
-Make sure to replace `{api_key}` with the publishable API key you copied earlier, and `{region_id}` with the ID of a region from the previous request.
-
-This will return the created cart. Copy the ID of the cart to use it next.
-
-Finally, to add the Gold variant to the cart with a custom price, send a `POST` request to the `/store/carts/:id/line-items-metals` API route:
-
-```bash
-curl -X POST 'localhost:9000/store/carts/{cart_id}/line-items-metals' \
--H 'x-publishable-api-key: {api_key}' \
--H 'Content-Type: application/json' \
---data '{
- "variant_id": "{variant_id}",
- "quantity": 1
-}'
-```
-
-Make sure to replace:
-
-- `{api_key}` with the publishable API key you copied earlier.
-- `{cart_id}` with the ID of the cart you created.
-- `{variant_id}` with the ID of the Gold variant you created.
-
-This will return the cart's details, where you can see in its `items` array the item with the custom price:
-
-```json title="Example Response"
-{
- "cart": {
- "items": [
- {
- "variant_id": "{variant_id}",
- "quantity": 1,
- "is_custom_price": true,
- // example custom price
- "unit_price": 2000
- }
- ]
- }
-}
-```
-
-The price will be the result of the calculation you've implemented earlier, which is the fixed price of the variant plus the real-time price of the metal, multiplied by the weight of the variant and the quantity added to the cart.
-
-This price will be reflected in the cart's total price, and you can proceed to checkout with the custom-priced item.
-
-***
-
-## Next Steps
-
-You've now implemented custom item pricing in Medusa. You can also customize the [storefront](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/nextjs-starter/index.html.md) to use the new API route to add custom-priced items to the cart.
-
-If you're new to Medusa, check out the [main documentation](https://docs.medusajs.com/docs/learn/index.html.md), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
-
-To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
-
-
# How-to & Tutorials
In this section of the documentation, you'll find how-to guides and tutorials that will help you customize the Medusa server and admin. These guides are useful after you've learned Medusa's main concepts in the [Get Started](https://docs.medusajs.com/docs/learn/index.html.md) section of the documentation.
@@ -39091,10 +39850,643 @@ For a quick access to code snippets of the different concepts you learned about,
Deployment guides are a collection of guides that help you deploy your Medusa server and admin to different platforms. Learn more in the [Deployment Overview](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/deployment/index.html.md) documentation.
+# Send Abandoned Cart Notifications in Medusa
+
+In this tutorial, you will learn how to send notifications to customers who have abandoned their carts.
+
+When you install a Medusa application, you get a fully-fledged commerce platform with a framework for customization. The Medusa application's commerce features are built around [commerce modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md), which are available out-of-the-box. These features include cart-management capabilities.
+
+Medusa's [Notification Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/architectural-modules/notification/index.html.md) allows you to send notifications to users or customers, such as password reset emails, order confirmation SMS, or other types of notifications.
+
+In this tutorial, you will use the Notification Module to send an email to customers who have abandoned their carts. The email will contain a link to recover the customer's cart, encouraging them to complete their purchase. You will use SendGrid to send the emails, but you can also use other email providers.
+
+## Summary
+
+By following this tutorial, you will:
+
+- Install and set up Medusa.
+- Create the logic to send an email to customers who have abandoned their carts.
+- Run the above logic once a day.
+- Add a route to the storefront to recover the cart.
+
+
+
+[View on Github](https://github.com/medusajs/examples/tree/main/abandoned-cart): Find the full code for this tutorial.
+
+***
+
+## Step 1: Install a Medusa Application
+
+### Prerequisites
+
+- [Node.js v20+](https://nodejs.org/en/download)
+- [Git CLI tool](https://git-scm.com/downloads)
+- [PostgreSQL](https://www.postgresql.org/download/)
+
+Start by installing the Medusa application on your machine with the following command:
+
+```bash
+npx create-medusa-app@latest
+```
+
+You will first be asked for the project's name. Then, when asked whether you want to install the [Next.js starter storefront](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/nextjs-starter/index.html.md), choose "Yes."
+
+Afterwards, the installation process will start, which will install the Medusa application in a directory with your project's name and the Next.js Starter Storefront in a separate directory with the `{project-name}-storefront` name.
+
+The Medusa application is composed of a headless Node.js server and an admin dashboard. The storefront is installed or custom-built separately and connects to the Medusa application through its REST endpoints, called [API routes](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md). Learn more in [Medusa's Architecture documentation](https://docs.medusajs.com/docs/learn/introduction/architecture/index.html.md).
+
+Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterwards, you can log in with the new user and explore the dashboard.
+
+Check out the [troubleshooting guides](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/troubleshooting/create-medusa-app-errors/index.html.md) for help.
+
+***
+
+## Step 2: Set up SendGrid
+
+### Prerequisites
+
+- [SendGrid account](https://sendgrid.com)
+- [Verified Sender Identity](https://mc.sendgrid.com/senders)
+- [SendGrid API Key](https://app.sendgrid.com/settings/api_keys)
+
+Medusa's Notification Module provides the general functionality to send notifications, but the sending logic is implemented in a module provider. This allows you to integrate the email provider of your choice.
+
+To send the cart-abandonment emails, you will use SendGrid. Medusa provides a [SendGrid Notification Module Provider](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/architectural-modules/notification/sendgrid/index.html.md) that you can use to send emails.
+
+Alternatively, you can use [other Notification Module Providers](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/architectural-modules/notification#what-is-a-notification-module-provider/index.html.md) or [create a custom provider](https://docs.medusajs.com/references/notification-provider-module/index.html.md).
+
+To set up SendGrid, add the SendGrid Notification Module Provider to `medusa-config.ts`:
+
+```ts title="medusa-config.ts"
+module.exports = defineConfig({
+ // ...
+ modules: [
+ {
+ resolve: "@medusajs/medusa/notification",
+ options: {
+ providers: [
+ {
+ resolve: "@medusajs/medusa/notification-sendgrid",
+ id: "sendgrid",
+ options: {
+ channels: ["email"],
+ api_key: process.env.SENDGRID_API_KEY,
+ from: process.env.SENDGRID_FROM,
+ },
+ },
+ ],
+ },
+ },
+ ],
+})
+```
+
+In the `modules` configuration, you pass the Notification Provider and add SendGrid as a provider. You also pass to the SendGrid Module Provider the following options:
+
+- `channels`: The channels that the provider supports. In this case, it is only email.
+- `api_key`: Your SendGrid API key.
+- `from`: The email address that the emails will be sent from.
+
+Then, set the SendGrid API key and "from" email as environment variables, such as in the `.env` file at the root of your project:
+
+```plain
+SENDGRID_API_KEY=your-sendgrid-api-key
+SENDGRID_FROM=test@gmail.com
+```
+
+You can now use SendGrid to send emails in Medusa.
+
+***
+
+## Step 3: Send Abandoned Cart Notification Flow
+
+You will now implement the sending logic for the abandoned cart notifications.
+
+To build custom commerce features in Medusa, you create a [workflow](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md). A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it is a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in a scheduled job.
+
+In this step, you will create the workflow that sends the abandoned cart notifications. Later, you will learn how to execute it once a day.
+
+The workflow will receive the list of abandoned carts as an input. The workflow has the following steps:
+
+- [sendAbandonedNotificationsStep](#sendAbandonedNotificationsStep): Send the abandoned cart notifications.
+- [updateCartsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateCartsStep/index.html.md): Update the cart to store the last notification date.
+
+Medusa provides the second step in its `@medusajs/medusa/core-flows` package. So, you only need to implement the first one.
+
+### sendAbandonedNotificationsStep
+
+The first step of the workflow sends a notification to the owners of the abandoned carts that are passed as an input.
+
+To implement the step, create the file `src/workflows/steps/send-abandoned-notifications.ts` with the following content:
+
+```ts title="src/workflows/steps/send-abandoned-notifications.ts"
+import {
+ createStep,
+ StepResponse,
+} from "@medusajs/framework/workflows-sdk"
+import { Modules } from "@medusajs/framework/utils"
+import { CartDTO, CustomerDTO } from "@medusajs/framework/types"
+
+type SendAbandonedNotificationsStepInput = {
+ carts: (CartDTO & {
+ customer: CustomerDTO
+ })[]
+}
+
+export const sendAbandonedNotificationsStep = createStep(
+ "send-abandoned-notifications",
+ async (input: SendAbandonedNotificationsStepInput, { container }) => {
+ const notificationModuleService = container.resolve(
+ Modules.NOTIFICATION
+ )
+
+ const notificationData = input.carts.map((cart) => ({
+ to: cart.email!,
+ channel: "email",
+ template: process.env.ABANDONED_CART_TEMPLATE_ID || "",
+ data: {
+ customer: {
+ first_name: cart.customer?.first_name || cart.shipping_address?.first_name,
+ last_name: cart.customer?.last_name || cart.shipping_address?.last_name,
+ },
+ cart_id: cart.id,
+ items: cart.items?.map((item) => ({
+ product_title: item.title,
+ quantity: item.quantity,
+ unit_price: item.unit_price,
+ thumbnail: item.thumbnail,
+ })),
+ },
+ }))
+
+ const notifications = await notificationModuleService.createNotifications(
+ notificationData
+ )
+
+ return new StepResponse({
+ notifications,
+ })
+ }
+)
+```
+
+You create a step with `createStep` from the Workflows SDK. It accepts two parameters:
+
+1. The step's unique name, which is `create-review`.
+2. An async function that receives two parameters:
+ - The step's input, which is in this case an object with the review's properties.
+ - An object that has properties including the [Medusa container](https://docs.medusajs.com/docs/learn/fundamentals/medusa-container/index.html.md), which is a registry of framework and commerce tools that you can access in the step.
+
+In the step function, you first resolve the Notification Module's service, which has methods to manage notifications. Then, you prepare the data of each notification, and create the notifications with the `createNotifications` method.
+
+Notice that each notification is an object with the following properties:
+
+- `to`: The email address of the customer.
+- `channel`: The channel that the notification will be sent through. The Notification Module uses the provider registered for the channel.
+- `template`: The ID or name of the email template in the third-party provider. Make sure to set it as an environment variable once you have it.
+- `data`: The data to pass to the template to render the email's dynamic content.
+
+Based on the dynamic template you create in SendGrid or another provider, you can pass different data in the `data` object.
+
+A step function must return a `StepResponse` instance. The `StepResponse` constructor accepts the step's output as a parameter, which is the created notifications.
+
+### Create Workflow
+
+You can now create the workflow that uses the step you just created to send the abandoned cart notifications.
+
+Create the file `src/workflows/send-abandoned-carts.ts` with the following content:
+
+```ts title="src/workflows/send-abandoned-carts.ts"
+import {
+ createWorkflow,
+ WorkflowResponse,
+ transform,
+} from "@medusajs/framework/workflows-sdk"
+import {
+ sendAbandonedNotificationsStep,
+} from "./steps/send-abandoned-notifications"
+import { updateCartsStep } from "@medusajs/medusa/core-flows"
+import { CartDTO } from "@medusajs/framework/types"
+import { CustomerDTO } from "@medusajs/framework/types"
+
+export type SendAbandonedCartsWorkflowInput = {
+ carts: (CartDTO & {
+ customer: CustomerDTO
+ })[]
+}
+
+export const sendAbandonedCartsWorkflow = createWorkflow(
+ "send-abandoned-carts",
+ function (input: SendAbandonedCartsWorkflowInput) {
+ sendAbandonedNotificationsStep(input)
+
+ const updateCartsData = transform(
+ input,
+ (data) => {
+ return data.carts.map((cart) => ({
+ id: cart.id,
+ metadata: {
+ ...cart.metadata,
+ abandoned_notification: new Date().toISOString(),
+ },
+ }))
+ }
+ )
+
+ const updatedCarts = updateCartsStep(updateCartsData)
+
+ return new WorkflowResponse(updatedCarts)
+ }
+)
+```
+
+You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
+
+It accepts as a second parameter a constructor function, which is the workflow's implementation. The function can accept input, which in this case is an arra of carts.
+
+In the workflow's constructor function, you:
+
+- Use the `sendAbandonedNotificationsStep` to send the notifications to the carts' customers.
+- Use the `updateCartsStep` from Medusa's core flows to update the carts' metadata with the last notification date.
+
+Notice that you use the `transform` function to prepare the `updateCartsStep`'s input. Medusa does not support direct data manipulation in a workflow's constructor function. You can learn more about it in the [Data Manipulation in Workflows documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/variable-manipulation/index.html.md).
+
+Your workflow is now ready for use. You will learn how to execute it in the next section.
+
+### Setup Email Template
+
+Before you can test the workflow, you need to set up an email template in SendGrid. The template should contain the dynamic content that you pass in the workflow's step.
+
+To create an email template in SendGrid:
+
+- Go to [Dynamic Templates](https://mc.sendgrid.com/dynamic-templates) in the SendGrid dashboard.
+- Click on the "Create Dynamic Template" button.
+
+
+
+- In the side window that opens, enter a name for the template, then click on the Create button.
+- The template will be added to the middle of the page. When you click on it, a new section will show with an "Add Version" button. Click on it.
+
+
+
+In the form that opens, you can either choose to start with a blank template or from an existing design. You can then use the drag-and-drop or code editor to design the email template.
+
+You can also use the following template as an example:
+
+```html title="Abandoned Cart Email Template"
+
+
+
+
+
+ Complete Your Purchase
+
+
+
+
+
Hi {{customer.first_name}}, your cart is waiting! 🛍️
+
You left some great items in your cart. Complete your purchase before they're gone!
+
+
+```
+
+This template will show each item's image, title, quantity, and price in the cart. It will also show a button to return to the cart and checkout.
+
+You can replace `https://yourstore.com` with your storefront's URL. You'll later implement the `/cart/recover/:cart_id` route in the storefront to recover the cart.
+
+Once you are done, copy the template ID from SendGrid and set it as an environment variable in your Medusa project:
+
+```plain
+ABANDONED_CART_TEMPLATE_ID=your-sendgrid-template-id
+```
+
+***
+
+## Step 4: Schedule Cart Abandonment Notifications
+
+The next step is to automate sending the abandoned cart notifications. You need a task that runs once a day to find the carts that have been abandoned for a certain period and send the notifications to the customers.
+
+To run a task at a scheduled interval, you can use a [scheduled job](https://docs.medusajs.com/docs/learn/fundamentals/scheduled-jobs/index.html.md). A scheduled job is an asynchronous function that the Medusa application runs at the interval you specify during the Medusa application's runtime.
+
+You can create a scheduled job in a TypeScript or JavaScript file under the `src/jobs` directory. So, to create the scheduled job that sends the abandoned cart notifications, create the file `src/jobs/send-abandoned-cart-notification.ts` with the following content:
+
+```ts title="src/jobs/send-abandoned-cart-notification.ts"
+import { MedusaContainer } from "@medusajs/framework/types"
+import {
+ sendAbandonedCartsWorkflow,
+ SendAbandonedCartsWorkflowInput,
+} from "../workflows/send-abandoned-carts"
+
+export default async function abandonedCartJob(
+ container: MedusaContainer
+) {
+ const logger = container.resolve("logger")
+ const query = container.resolve("query")
+
+ const oneDayAgo = new Date()
+ oneDayAgo.setDate(oneDayAgo.getDate() - 1)
+ const limit = 100
+ const offset = 0
+ const totalCount = 0
+ const abandonedCartsCount = 0
+
+ do {
+ // TODO retrieve paginated abandoned carts
+ } while (offset < totalCount)
+
+ logger.info(`Sent ${abandonedCartsCount} abandoned cart notifications`)
+}
+
+export const config = {
+ name: "abandoned-cart-notification",
+ schedule: "0 0 * * *", // Run at midnight every day
+}
+```
+
+In a scheduled job's file, you must export:
+
+1. An asynchronous function that holds the job's logic. The function receives the [Medusa container](https://docs.medusajs.com/docs/learn/fundamentals/medusa-container/index.html.md) as a parameter.
+2. A `config` object that specifies the job's name and schedule. The schedule is a [cron expression](https://crontab.guru/) that defines the interval at which the job runs.
+
+In the scheduled job function, so far you resolve the [Logger](https://docs.medusajs.com/docs/learn/debugging-and-testing/logging/index.html.md) to log messages, and [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md) to retrieve data across modules.
+
+You also define a `oneDayAgo` date, which is the date that you will use as the condition of an abandoned cart. In addition, you define variables to paginate the carts.
+
+Next, you will retrieve the abandoned carts using Query. Replace the `TODO` with the following:
+
+```ts title="src/jobs/send-abandoned-cart-notification.ts"
+const {
+ data: abandonedCarts,
+ metadata,
+} = await query.graph({
+ entity: "cart",
+ fields: [
+ "id",
+ "email",
+ "items.*",
+ "metadata",
+ "customer.*",
+ ],
+ filters: {
+ updated_at: {
+ $lt: oneDayAgo,
+ },
+ // @ts-ignore
+ email: {
+ $ne: null,
+ },
+ // @ts-ignore
+ completed_at: null,
+ },
+ pagination: {
+ skip: offset,
+ take: limit,
+ },
+})
+
+totalCount = metadata?.count ?? 0
+const cartsWithItems = abandonedCarts.filter((cart) =>
+ cart.items?.length > 0 && !cart.metadata?.abandoned_notification
+)
+
+try {
+ await sendAbandonedCartsWorkflow(container).run({
+ input: {
+ carts: cartsWithItems,
+ } as unknown as SendAbandonedCartsWorkflowInput,
+ })
+ abandonedCartsCount += cartsWithItems.length
+
+} catch (error) {
+ logger.error(
+ `Failed to send abandoned cart notification: ${error.message}`
+ )
+}
+
+offset += limit
+```
+
+In the do-while loop, you use Query to retrieve carts matching the following criteria:
+
+- The cart was last updated more than a day ago.
+- The cart has an email address.
+- The cart has not been completed.
+
+You also filter the retrieved carts to only include carts with items and customers that have not received an abandoned cart notification.
+
+Finally, you execute the `sendAbandonedCartsWorkflow` passing it the abandoned carts as an input. You will execute the workflow for each paginated batch of carts.
+
+### Test it Out
+
+To test out the scheduled job and workflow, it is recommended to change the `oneDayAgo` date to a minute before now for easy testing:
+
+```ts title="src/jobs/send-abandoned-cart-notification.ts"
+oneDayAgo.setMinutes(oneDayAgo.getMinutes() - 1) // For testing
+```
+
+And to change the job's schedule in `config` to run every minute:
+
+```ts title="src/jobs/send-abandoned-cart-notification.ts"
+export const config = {
+ // ...
+ schedule: "* * * * *", // Run every minute for testing
+}
+```
+
+Finally, start the Medusa application with the following command:
+
+```bash npm2yarn
+npm run dev
+```
+
+And in the [Next.js Starter Storefront](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/nextjs-starter/index.html.md)'s directory (that you installed in the first step), start the storefront with the following command:
+
+```bash npm2yarn
+npm run dev
+```
+
+Open the storefront at `localhost:8000`. You can either:
+
+- Create an account and add items to the cart, then leave the cart for a minute.
+- Add an item to the cart as a guest. Then, start the checkout process, but only enter the shipping and email addresses, and leave the cart for a minute.
+
+Afterwards, wait for the job to execute. Once it is executed, you will see the following message in the terminal:
+
+```bash
+info: Sent 1 abandoned cart notifications
+```
+
+Once you're done testing, make sure to revert the changes to the `oneDayAgo` date and the job's schedule.
+
+***
+
+## Step 5: Recover Cart in Storefront
+
+In the storefront, you need to add a route that recovers the cart when the customer clicks on the link in the email. The route should receive the cart ID, set the cart ID in the cookie, and redirect the customer to the cart page.
+
+To implement the route, in the Next.js Starter Storefront create the file `src/app/[countryCode]/(main)/cart/recover/[id]/route.tsx` with the following content:
+
+```tsx title="src/app/[countryCode]/(main)/cart/recover/[id]/route.tsx" badgeLabel="Storefront" badgeColor="blue"
+import { NextRequest } from "next/server"
+import { retrieveCart } from "../../../../../../lib/data/cart"
+import { setCartId } from "../../../../../../lib/data/cookies"
+import { notFound, redirect } from "next/navigation"
+type Params = Promise<{
+ id: string
+}>
+
+export async function GET(req: NextRequest, { params }: { params: Params }) {
+ const { id } = await params
+ const cart = await retrieveCart(id)
+
+ if (!cart) {
+ return notFound()
+ }
+
+ setCartId(id)
+
+ const countryCode = cart.shipping_address?.country_code ||
+ cart.region?.countries?.[0]?.iso_2
+
+ redirect(
+ `/${countryCode ? `${countryCode}/` : ""}cart`
+ )
+}
+```
+
+You add a `GET` route handler that receives the cart ID as a path parameter. In the route handler, you:
+
+- Try to retrieve the cart from the Medusa application. The `retrieveCart` function is already available in the Next.js storefront. If the cart is not found, you return a 404 response.
+- Set the cart ID in a cookie using the `setCartId` function. This is also a function that is already available in the storefront.
+- Redirect the customer to the cart page. You set the country code in the URL based on the cart's shipping address or region.
+
+### Test it Out
+
+To test it out, start the Medusa application:
+
+```bash npm2yarn
+npm run dev
+```
+
+And in the Next.js Starter Storefront's directory, start the storefront:
+
+```bash npm2yarn
+npm run dev
+```
+
+Then, either open the link in an abandoned cart email or navigate to `localhost:8000/cart/recover/:cart_id` in your browser. You will be redirected to the cart page with the recovered cart.
+
+
+
+***
+
+## Next Steps
+
+You have now implemented the logic to send abandoned cart notifications in Medusa. You can implement other customizations with Medusa, such as:
+
+- [Implement Product Reviews](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/how-to-tutorials/tutorials/product-reviews/index.html.md).
+- [Implement Wishlist](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/plugins/guides/wishlist/index.html.md).
+- [Allow Custom-Item Pricing](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/examples/guides/custom-item-price/index.html.md).
+
+If you are new to Medusa, check out the [main documentation](https://docs.medusajs.com/docs/learn/index.html.md), where you will get a more in-depth learning of all the concepts you have used in this guide and more.
+
+To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
+
+
# Implement Loyalty Points System in Medusa
In this tutorial, you'll learn how to implement a loyalty points system in Medusa.
+Medusa Cloud provides a beta Store Credits feature that facilitates building a loyalty point system. [Get in touch](https://medusajs.com/contact) for early access.
+
When you install a Medusa application, you get a fully-fledged commerce platform with a framework for customization. The Medusa application's commerce features are built around [commerce modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md), which are available out-of-the-box. These features include management capabilities related to carts, orders, promotions, and more.
A loyalty point system allows customers to earn points for purchases, which can be redeemed for discounts or rewards. In this tutorial, you'll learn how to customize the Medusa application to implement a loyalty points system.
@@ -40880,637 +42272,6 @@ If you're new to Medusa, check out the [main documentation](https://docs.medusaj
To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
-# Send Abandoned Cart Notifications in Medusa
-
-In this tutorial, you will learn how to send notifications to customers who have abandoned their carts.
-
-When you install a Medusa application, you get a fully-fledged commerce platform with a framework for customization. The Medusa application's commerce features are built around [commerce modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md), which are available out-of-the-box. These features include cart-management capabilities.
-
-Medusa's [Notification Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/architectural-modules/notification/index.html.md) allows you to send notifications to users or customers, such as password reset emails, order confirmation SMS, or other types of notifications.
-
-In this tutorial, you will use the Notification Module to send an email to customers who have abandoned their carts. The email will contain a link to recover the customer's cart, encouraging them to complete their purchase. You will use SendGrid to send the emails, but you can also use other email providers.
-
-## Summary
-
-By following this tutorial, you will:
-
-- Install and set up Medusa.
-- Create the logic to send an email to customers who have abandoned their carts.
-- Run the above logic once a day.
-- Add a route to the storefront to recover the cart.
-
-
-
-[View on Github](https://github.com/medusajs/examples/tree/main/abandoned-cart): Find the full code for this tutorial.
-
-***
-
-## Step 1: Install a Medusa Application
-
-### Prerequisites
-
-- [Node.js v20+](https://nodejs.org/en/download)
-- [Git CLI tool](https://git-scm.com/downloads)
-- [PostgreSQL](https://www.postgresql.org/download/)
-
-Start by installing the Medusa application on your machine with the following command:
-
-```bash
-npx create-medusa-app@latest
-```
-
-You will first be asked for the project's name. Then, when asked whether you want to install the [Next.js starter storefront](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/nextjs-starter/index.html.md), choose "Yes."
-
-Afterwards, the installation process will start, which will install the Medusa application in a directory with your project's name and the Next.js Starter Storefront in a separate directory with the `{project-name}-storefront` name.
-
-The Medusa application is composed of a headless Node.js server and an admin dashboard. The storefront is installed or custom-built separately and connects to the Medusa application through its REST endpoints, called [API routes](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md). Learn more in [Medusa's Architecture documentation](https://docs.medusajs.com/docs/learn/introduction/architecture/index.html.md).
-
-Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterwards, you can log in with the new user and explore the dashboard.
-
-Check out the [troubleshooting guides](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/troubleshooting/create-medusa-app-errors/index.html.md) for help.
-
-***
-
-## Step 2: Set up SendGrid
-
-### Prerequisites
-
-- [SendGrid account](https://sendgrid.com)
-- [Verified Sender Identity](https://mc.sendgrid.com/senders)
-- [SendGrid API Key](https://app.sendgrid.com/settings/api_keys)
-
-Medusa's Notification Module provides the general functionality to send notifications, but the sending logic is implemented in a module provider. This allows you to integrate the email provider of your choice.
-
-To send the cart-abandonment emails, you will use SendGrid. Medusa provides a [SendGrid Notification Module Provider](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/architectural-modules/notification/sendgrid/index.html.md) that you can use to send emails.
-
-Alternatively, you can use [other Notification Module Providers](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/architectural-modules/notification#what-is-a-notification-module-provider/index.html.md) or [create a custom provider](https://docs.medusajs.com/references/notification-provider-module/index.html.md).
-
-To set up SendGrid, add the SendGrid Notification Module Provider to `medusa-config.ts`:
-
-```ts title="medusa-config.ts"
-module.exports = defineConfig({
- // ...
- modules: [
- {
- resolve: "@medusajs/medusa/notification",
- options: {
- providers: [
- {
- resolve: "@medusajs/medusa/notification-sendgrid",
- id: "sendgrid",
- options: {
- channels: ["email"],
- api_key: process.env.SENDGRID_API_KEY,
- from: process.env.SENDGRID_FROM,
- },
- },
- ],
- },
- },
- ],
-})
-```
-
-In the `modules` configuration, you pass the Notification Provider and add SendGrid as a provider. You also pass to the SendGrid Module Provider the following options:
-
-- `channels`: The channels that the provider supports. In this case, it is only email.
-- `api_key`: Your SendGrid API key.
-- `from`: The email address that the emails will be sent from.
-
-Then, set the SendGrid API key and "from" email as environment variables, such as in the `.env` file at the root of your project:
-
-```plain
-SENDGRID_API_KEY=your-sendgrid-api-key
-SENDGRID_FROM=test@gmail.com
-```
-
-You can now use SendGrid to send emails in Medusa.
-
-***
-
-## Step 3: Send Abandoned Cart Notification Flow
-
-You will now implement the sending logic for the abandoned cart notifications.
-
-To build custom commerce features in Medusa, you create a [workflow](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md). A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it is a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in a scheduled job.
-
-In this step, you will create the workflow that sends the abandoned cart notifications. Later, you will learn how to execute it once a day.
-
-The workflow will receive the list of abandoned carts as an input. The workflow has the following steps:
-
-- [sendAbandonedNotificationsStep](#sendAbandonedNotificationsStep): Send the abandoned cart notifications.
-- [updateCartsStep](https://docs.medusajs.com/references/medusa-workflows/steps/updateCartsStep/index.html.md): Update the cart to store the last notification date.
-
-Medusa provides the second step in its `@medusajs/medusa/core-flows` package. So, you only need to implement the first one.
-
-### sendAbandonedNotificationsStep
-
-The first step of the workflow sends a notification to the owners of the abandoned carts that are passed as an input.
-
-To implement the step, create the file `src/workflows/steps/send-abandoned-notifications.ts` with the following content:
-
-```ts title="src/workflows/steps/send-abandoned-notifications.ts"
-import {
- createStep,
- StepResponse,
-} from "@medusajs/framework/workflows-sdk"
-import { Modules } from "@medusajs/framework/utils"
-import { CartDTO, CustomerDTO } from "@medusajs/framework/types"
-
-type SendAbandonedNotificationsStepInput = {
- carts: (CartDTO & {
- customer: CustomerDTO
- })[]
-}
-
-export const sendAbandonedNotificationsStep = createStep(
- "send-abandoned-notifications",
- async (input: SendAbandonedNotificationsStepInput, { container }) => {
- const notificationModuleService = container.resolve(
- Modules.NOTIFICATION
- )
-
- const notificationData = input.carts.map((cart) => ({
- to: cart.email!,
- channel: "email",
- template: process.env.ABANDONED_CART_TEMPLATE_ID || "",
- data: {
- customer: {
- first_name: cart.customer?.first_name || cart.shipping_address?.first_name,
- last_name: cart.customer?.last_name || cart.shipping_address?.last_name,
- },
- cart_id: cart.id,
- items: cart.items?.map((item) => ({
- product_title: item.title,
- quantity: item.quantity,
- unit_price: item.unit_price,
- thumbnail: item.thumbnail,
- })),
- },
- }))
-
- const notifications = await notificationModuleService.createNotifications(
- notificationData
- )
-
- return new StepResponse({
- notifications,
- })
- }
-)
-```
-
-You create a step with `createStep` from the Workflows SDK. It accepts two parameters:
-
-1. The step's unique name, which is `create-review`.
-2. An async function that receives two parameters:
- - The step's input, which is in this case an object with the review's properties.
- - An object that has properties including the [Medusa container](https://docs.medusajs.com/docs/learn/fundamentals/medusa-container/index.html.md), which is a registry of framework and commerce tools that you can access in the step.
-
-In the step function, you first resolve the Notification Module's service, which has methods to manage notifications. Then, you prepare the data of each notification, and create the notifications with the `createNotifications` method.
-
-Notice that each notification is an object with the following properties:
-
-- `to`: The email address of the customer.
-- `channel`: The channel that the notification will be sent through. The Notification Module uses the provider registered for the channel.
-- `template`: The ID or name of the email template in the third-party provider. Make sure to set it as an environment variable once you have it.
-- `data`: The data to pass to the template to render the email's dynamic content.
-
-Based on the dynamic template you create in SendGrid or another provider, you can pass different data in the `data` object.
-
-A step function must return a `StepResponse` instance. The `StepResponse` constructor accepts the step's output as a parameter, which is the created notifications.
-
-### Create Workflow
-
-You can now create the workflow that uses the step you just created to send the abandoned cart notifications.
-
-Create the file `src/workflows/send-abandoned-carts.ts` with the following content:
-
-```ts title="src/workflows/send-abandoned-carts.ts"
-import {
- createWorkflow,
- WorkflowResponse,
- transform,
-} from "@medusajs/framework/workflows-sdk"
-import {
- sendAbandonedNotificationsStep,
-} from "./steps/send-abandoned-notifications"
-import { updateCartsStep } from "@medusajs/medusa/core-flows"
-import { CartDTO } from "@medusajs/framework/types"
-import { CustomerDTO } from "@medusajs/framework/types"
-
-export type SendAbandonedCartsWorkflowInput = {
- carts: (CartDTO & {
- customer: CustomerDTO
- })[]
-}
-
-export const sendAbandonedCartsWorkflow = createWorkflow(
- "send-abandoned-carts",
- function (input: SendAbandonedCartsWorkflowInput) {
- sendAbandonedNotificationsStep(input)
-
- const updateCartsData = transform(
- input,
- (data) => {
- return data.carts.map((cart) => ({
- id: cart.id,
- metadata: {
- ...cart.metadata,
- abandoned_notification: new Date().toISOString(),
- },
- }))
- }
- )
-
- const updatedCarts = updateCartsStep(updateCartsData)
-
- return new WorkflowResponse(updatedCarts)
- }
-)
-```
-
-You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
-
-It accepts as a second parameter a constructor function, which is the workflow's implementation. The function can accept input, which in this case is an arra of carts.
-
-In the workflow's constructor function, you:
-
-- Use the `sendAbandonedNotificationsStep` to send the notifications to the carts' customers.
-- Use the `updateCartsStep` from Medusa's core flows to update the carts' metadata with the last notification date.
-
-Notice that you use the `transform` function to prepare the `updateCartsStep`'s input. Medusa does not support direct data manipulation in a workflow's constructor function. You can learn more about it in the [Data Manipulation in Workflows documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/variable-manipulation/index.html.md).
-
-Your workflow is now ready for use. You will learn how to execute it in the next section.
-
-### Setup Email Template
-
-Before you can test the workflow, you need to set up an email template in SendGrid. The template should contain the dynamic content that you pass in the workflow's step.
-
-To create an email template in SendGrid:
-
-- Go to [Dynamic Templates](https://mc.sendgrid.com/dynamic-templates) in the SendGrid dashboard.
-- Click on the "Create Dynamic Template" button.
-
-
-
-- In the side window that opens, enter a name for the template, then click on the Create button.
-- The template will be added to the middle of the page. When you click on it, a new section will show with an "Add Version" button. Click on it.
-
-
-
-In the form that opens, you can either choose to start with a blank template or from an existing design. You can then use the drag-and-drop or code editor to design the email template.
-
-You can also use the following template as an example:
-
-```html title="Abandoned Cart Email Template"
-
-
-
-
-
- Complete Your Purchase
-
-
-
-
-
Hi {{customer.first_name}}, your cart is waiting! 🛍️
-
You left some great items in your cart. Complete your purchase before they're gone!
-
-
-```
-
-This template will show each item's image, title, quantity, and price in the cart. It will also show a button to return to the cart and checkout.
-
-You can replace `https://yourstore.com` with your storefront's URL. You'll later implement the `/cart/recover/:cart_id` route in the storefront to recover the cart.
-
-Once you are done, copy the template ID from SendGrid and set it as an environment variable in your Medusa project:
-
-```plain
-ABANDONED_CART_TEMPLATE_ID=your-sendgrid-template-id
-```
-
-***
-
-## Step 4: Schedule Cart Abandonment Notifications
-
-The next step is to automate sending the abandoned cart notifications. You need a task that runs once a day to find the carts that have been abandoned for a certain period and send the notifications to the customers.
-
-To run a task at a scheduled interval, you can use a [scheduled job](https://docs.medusajs.com/docs/learn/fundamentals/scheduled-jobs/index.html.md). A scheduled job is an asynchronous function that the Medusa application runs at the interval you specify during the Medusa application's runtime.
-
-You can create a scheduled job in a TypeScript or JavaScript file under the `src/jobs` directory. So, to create the scheduled job that sends the abandoned cart notifications, create the file `src/jobs/send-abandoned-cart-notification.ts` with the following content:
-
-```ts title="src/jobs/send-abandoned-cart-notification.ts"
-import { MedusaContainer } from "@medusajs/framework/types"
-import {
- sendAbandonedCartsWorkflow,
- SendAbandonedCartsWorkflowInput,
-} from "../workflows/send-abandoned-carts"
-
-export default async function abandonedCartJob(
- container: MedusaContainer
-) {
- const logger = container.resolve("logger")
- const query = container.resolve("query")
-
- const oneDayAgo = new Date()
- oneDayAgo.setDate(oneDayAgo.getDate() - 1)
- const limit = 100
- const offset = 0
- const totalCount = 0
- const abandonedCartsCount = 0
-
- do {
- // TODO retrieve paginated abandoned carts
- } while (offset < totalCount)
-
- logger.info(`Sent ${abandonedCartsCount} abandoned cart notifications`)
-}
-
-export const config = {
- name: "abandoned-cart-notification",
- schedule: "0 0 * * *", // Run at midnight every day
-}
-```
-
-In a scheduled job's file, you must export:
-
-1. An asynchronous function that holds the job's logic. The function receives the [Medusa container](https://docs.medusajs.com/docs/learn/fundamentals/medusa-container/index.html.md) as a parameter.
-2. A `config` object that specifies the job's name and schedule. The schedule is a [cron expression](https://crontab.guru/) that defines the interval at which the job runs.
-
-In the scheduled job function, so far you resolve the [Logger](https://docs.medusajs.com/docs/learn/debugging-and-testing/logging/index.html.md) to log messages, and [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md) to retrieve data across modules.
-
-You also define a `oneDayAgo` date, which is the date that you will use as the condition of an abandoned cart. In addition, you define variables to paginate the carts.
-
-Next, you will retrieve the abandoned carts using Query. Replace the `TODO` with the following:
-
-```ts title="src/jobs/send-abandoned-cart-notification.ts"
-const {
- data: abandonedCarts,
- metadata,
-} = await query.graph({
- entity: "cart",
- fields: [
- "id",
- "email",
- "items.*",
- "metadata",
- "customer.*",
- ],
- filters: {
- updated_at: {
- $lt: oneDayAgo,
- },
- // @ts-ignore
- email: {
- $ne: null,
- },
- // @ts-ignore
- completed_at: null,
- },
- pagination: {
- skip: offset,
- take: limit,
- },
-})
-
-totalCount = metadata?.count ?? 0
-const cartsWithItems = abandonedCarts.filter((cart) =>
- cart.items?.length > 0 && !cart.metadata?.abandoned_notification
-)
-
-try {
- await sendAbandonedCartsWorkflow(container).run({
- input: {
- carts: cartsWithItems,
- } as unknown as SendAbandonedCartsWorkflowInput,
- })
- abandonedCartsCount += cartsWithItems.length
-
-} catch (error) {
- logger.error(
- `Failed to send abandoned cart notification: ${error.message}`
- )
-}
-
-offset += limit
-```
-
-In the do-while loop, you use Query to retrieve carts matching the following criteria:
-
-- The cart was last updated more than a day ago.
-- The cart has an email address.
-- The cart has not been completed.
-
-You also filter the retrieved carts to only include carts with items and customers that have not received an abandoned cart notification.
-
-Finally, you execute the `sendAbandonedCartsWorkflow` passing it the abandoned carts as an input. You will execute the workflow for each paginated batch of carts.
-
-### Test it Out
-
-To test out the scheduled job and workflow, it is recommended to change the `oneDayAgo` date to a minute before now for easy testing:
-
-```ts title="src/jobs/send-abandoned-cart-notification.ts"
-oneDayAgo.setMinutes(oneDayAgo.getMinutes() - 1) // For testing
-```
-
-And to change the job's schedule in `config` to run every minute:
-
-```ts title="src/jobs/send-abandoned-cart-notification.ts"
-export const config = {
- // ...
- schedule: "* * * * *", // Run every minute for testing
-}
-```
-
-Finally, start the Medusa application with the following command:
-
-```bash npm2yarn
-npm run dev
-```
-
-And in the [Next.js Starter Storefront](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/nextjs-starter/index.html.md)'s directory (that you installed in the first step), start the storefront with the following command:
-
-```bash npm2yarn
-npm run dev
-```
-
-Open the storefront at `localhost:8000`. You can either:
-
-- Create an account and add items to the cart, then leave the cart for a minute.
-- Add an item to the cart as a guest. Then, start the checkout process, but only enter the shipping and email addresses, and leave the cart for a minute.
-
-Afterwards, wait for the job to execute. Once it is executed, you will see the following message in the terminal:
-
-```bash
-info: Sent 1 abandoned cart notifications
-```
-
-Once you're done testing, make sure to revert the changes to the `oneDayAgo` date and the job's schedule.
-
-***
-
-## Step 5: Recover Cart in Storefront
-
-In the storefront, you need to add a route that recovers the cart when the customer clicks on the link in the email. The route should receive the cart ID, set the cart ID in the cookie, and redirect the customer to the cart page.
-
-To implement the route, in the Next.js Starter Storefront create the file `src/app/[countryCode]/(main)/cart/recover/[id]/route.tsx` with the following content:
-
-```tsx title="src/app/[countryCode]/(main)/cart/recover/[id]/route.tsx" badgeLabel="Storefront" badgeColor="blue"
-import { NextRequest } from "next/server"
-import { retrieveCart } from "../../../../../../lib/data/cart"
-import { setCartId } from "../../../../../../lib/data/cookies"
-import { notFound, redirect } from "next/navigation"
-type Params = Promise<{
- id: string
-}>
-
-export async function GET(req: NextRequest, { params }: { params: Params }) {
- const { id } = await params
- const cart = await retrieveCart(id)
-
- if (!cart) {
- return notFound()
- }
-
- setCartId(id)
-
- const countryCode = cart.shipping_address?.country_code ||
- cart.region?.countries?.[0]?.iso_2
-
- redirect(
- `/${countryCode ? `${countryCode}/` : ""}cart`
- )
-}
-```
-
-You add a `GET` route handler that receives the cart ID as a path parameter. In the route handler, you:
-
-- Try to retrieve the cart from the Medusa application. The `retrieveCart` function is already available in the Next.js storefront. If the cart is not found, you return a 404 response.
-- Set the cart ID in a cookie using the `setCartId` function. This is also a function that is already available in the storefront.
-- Redirect the customer to the cart page. You set the country code in the URL based on the cart's shipping address or region.
-
-### Test it Out
-
-To test it out, start the Medusa application:
-
-```bash npm2yarn
-npm run dev
-```
-
-And in the Next.js Starter Storefront's directory, start the storefront:
-
-```bash npm2yarn
-npm run dev
-```
-
-Then, either open the link in an abandoned cart email or navigate to `localhost:8000/cart/recover/:cart_id` in your browser. You will be redirected to the cart page with the recovered cart.
-
-
-
-***
-
-## Next Steps
-
-You have now implemented the logic to send abandoned cart notifications in Medusa. You can implement other customizations with Medusa, such as:
-
-- [Implement Product Reviews](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/how-to-tutorials/tutorials/product-reviews/index.html.md).
-- [Implement Wishlist](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/plugins/guides/wishlist/index.html.md).
-- [Allow Custom-Item Pricing](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/examples/guides/custom-item-price/index.html.md).
-
-If you are new to Medusa, check out the [main documentation](https://docs.medusajs.com/docs/learn/index.html.md), where you will get a more in-depth learning of all the concepts you have used in this guide and more.
-
-To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
-
-
# Implement Product Reviews in Medusa
In this tutorial, you'll learn how to implement product reviews in Medusa.
@@ -43466,1054 +44227,6 @@ Integrate a search engine to index and search products or other types of data in
- [Algolia](https://docs.medusajs.com/integrations/guides/algolia/index.html.md)
-# How to Build Magento Data Migration Plugin
-
-In this tutorial, you'll learn how to build a [plugin](https://docs.medusajs.com/docs/learn/fundamentals/plugins/index.html.md) that migrates data, such as products, from Magento to Medusa.
-
-Magento is known for its customization capabilities. However, its monolithic architecture imposes limitations on business requirements, often forcing development teams to implement hacky workarounds. Over time, these customizations become challenging to maintain, especially as the business scales, leading to increased technical debt and slower feature delivery.
-
-Medusa's modular architecture allows you to build a custom digital commerce platform that meets your business requirements without the limitations of a monolithic system. By migrating from Magento to Medusa, you can take advantage of Medusa's modern technology stack to build a scalable and flexible commerce platform that grows with your business.
-
-By following this tutorial, you'll create a Medusa plugin that migrates data from a Magento server to a Medusa application in minimal time. You can re-use this plugin across multiple Medusa applications, allowing you to adopt Medusa across your projects.
-
-## Summary
-
-### Prerequisites
-
-
-
-This tutorial will teach you how to:
-
-- Install and set up a Medusa application project.
-- Install and set up a Medusa plugin.
-- Implement a Magento Module in the plugin to connect to Magento's APIs and retrieve products.
- - This guide will only focus on migrating product data from Magento to Medusa. You can extend the implementation to migrate other data, such as customers, orders, and more.
-- Trigger data migration from Magento to Medusa in a scheduled job.
-
-You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer.
-
-
-
-[Example Repository](https://github.com/medusajs/examples/tree/main/migrate-from-magento): Find the full code of the guide in this repository. The repository also includes additional features, such as triggering migrations from the Medusa Admin dashboard.
-
-***
-
-## Step 1: Install a Medusa Application
-
-You'll first install a Medusa application that exposes core commerce features through REST APIs. You'll later install the Magento plugin in this application to test it out.
-
-### Prerequisites
-
-- [Node.js v20+](https://nodejs.org/en/download)
-- [Git CLI tool](https://git-scm.com/downloads)
-- [PostgreSQL](https://www.postgresql.org/download/)
-
-Start by installing the Medusa application on your machine with the following command:
-
-```bash
-npx create-medusa-app@latest
-```
-
-You'll be asked for the project's name. You can also optionally choose to install the [Next.js starter storefront](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/nextjs-starter/index.html.md).
-
-Afterward, the installation process will start, which will install the Medusa application in a directory with your project's name. If you chose to install the Next.js starter, it'll be installed in a separate directory with the `{project-name}-storefront` name.
-
-The Medusa application is composed of a headless Node.js server and an admin dashboard. The storefront is installed or custom-built separately and connects to the Medusa application through its REST endpoints, called [API routes](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md). Refer to the [Medusa Architecture](https://docs.medusajs.com/docs/learn/introduction/architecture/index.html.md) documentation to learn more.
-
-Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterward, you can log in with the new user and explore the dashboard.
-
-Check out the [troubleshooting guides](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/troubleshooting/create-medusa-app-errors/index.html.md) for help.
-
-***
-
-## Step 2: Install a Medusa Plugin Project
-
-A plugin is a package of reusable Medusa customizations that you can install in any Medusa application. You can add in the plugin [API Routes](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md), [Workflows](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md), and other customizations, as you'll see in this guide. Afterward, you can test it out locally in a Medusa application, then publish it to npm to install and use it in any Medusa application.
-
-Refer to the [Plugins](https://docs.medusajs.com/docs/learn/fundamentals/plugins/index.html.md) documentation to learn more about plugins.
-
-A Medusa plugin is set up in a different project, giving you the flexibility in building and publishing it, while providing you with the tools to test it out locally in a Medusa application.
-
-To create a new Medusa plugin project, run the following command in a directory different than that of the Medusa application:
-
-```bash npm2yarn
-npx create-medusa-app@latest medusa-plugin-magento --plugin
-```
-
-Where `medusa-plugin-magento` is the name of the plugin's directory and the name set in the plugin's `package.json`. So, if you wish to publish it to NPM later under a different name, you can change it here in the command or later in `package.json`.
-
-Once the installation process is done, a new directory named `medusa-plugin-magento` will be created with the plugin project files.
-
-
-
-***
-
-## Step 3: Set up Plugin in Medusa Application
-
-Before you start your development, you'll set up the plugin in the Medusa application you installed in the first step. This will allow you to test the plugin during your development process.
-
-In the plugin's directory, run the following command to publish the plugin to the local package registry:
-
-```bash title="Plugin project"
-npx medusa plugin:publish
-```
-
-This command uses [Yalc](https://github.com/wclr/yalc) under the hood to publish the plugin to a local package registry. The plugin is published locally under the name you specified in `package.json`.
-
-Next, you'll install the plugin in the Medusa application from the local registry.
-
-If you've installed your Medusa project before v2.3.1, you must install [yalc](https://github.com/wclr/yalc) as a development dependency first.
-
-Run the following command in the Medusa application's directory to install the plugin:
-
-```bash title="Medusa application"
-npx medusa plugin:add medusa-plugin-magento
-```
-
-This command installs the plugin in the Medusa application from the local package registry.
-
-Next, register the plugin in the `medusa-config.ts` file of the Medusa application:
-
-```ts title="medusa-config.ts"
-module.exports = defineConfig({
- // ...
- plugins: [
- {
- resolve: "medusa-plugin-magento",
- options: {
- // TODO add options
- },
- },
- ],
-})
-```
-
-You add the plugin to the array of plugins. Later, you'll pass options useful to retrieve data from Magento.
-
-Finally, to ensure your plugin's changes are constantly published to the local registry, simplifying your testing process, keep the following command running in the plugin project during development:
-
-```bash title="Plugin project"
-npx medusa plugin:develop
-```
-
-***
-
-## Step 4: Implement Magento Module
-
-To connect to external applications in Medusa, you create a custom module. A module is a reusable package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
-
-In this step, you'll create a Magento Module in the Magento plugin that connects to a Magento server's REST APIs and retrieves data, such as products.
-
-Refer to the [Modules](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md) documentation to learn more about modules.
-
-### Create Module Directory
-
-A module is created under the `src/modules` directory of your plugin. So, create the directory `src/modules/magento`.
-
-
-
-### Create Module's Service
-
-You define a module's functionalities in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to external systems or the database, which is useful if your module defines tables in the database.
-
-In this section, you'll create the Magento Module's service that connects to Magento's REST APIs and retrieves data.
-
-Start by creating the file `src/modules/magento/service.ts` in the plugin with the following content:
-
-
-
-```ts title="src/modules/magento/service.ts"
-type Options = {
- baseUrl: string
- storeCode?: string
- username: string
- password: string
- migrationOptions?: {
- imageBaseUrl?: string
- }
-}
-
-export default class MagentoModuleService {
- private options: Options
-
- constructor({}, options: Options) {
- this.options = {
- ...options,
- storeCode: options.storeCode || "default",
- }
- }
-}
-```
-
-You create a `MagentoModuleService` that has an `options` property to store the module's options. These options include:
-
-- `baseUrl`: The base URL of the Magento server.
-- `storeCode`: The store code of the Magento store, which is `default` by default.
-- `username`: The username of a Magento admin user to authenticate with the Magento server.
-- `password`: The password of the Magento admin user.
-- `migrationOptions`: Additional options useful for migrating data, such as the base URL to use for product images.
-
-The service's constructor accepts as a first parameter the [Module Container](https://docs.medusajs.com/docs/learn/fundamentals/modules/container/index.html.md), which allows you to access resources available for the module. As a second parameter, it accepts the module's options.
-
-### Add Authentication Logic
-
-To authenticate with the Magento server, you'll add a method to the service that retrieves an access token from Magento using the username and password in the options. This access token is used in subsequent requests to the Magento server.
-
-First, add the following property to the `MagentoModuleService` class:
-
-```ts title="src/modules/magento/service.ts"
-export default class MagentoModuleService {
- private accessToken: {
- token: string
- expiresAt: Date
- }
- // ...
-}
-```
-
-You add an `accessToken` property to store the access token and its expiration date. The access token Magento returns expires after four hours, so you store the expiration date to know when to refresh the token.
-
-Next, add the following `authenticate` method to the `MagentoModuleService` class:
-
-```ts title="src/modules/magento/service.ts"
-import { MedusaError } from "@medusajs/framework/utils"
-
-export default class MagentoModuleService {
- // ...
- async authenticate() {
- const response = await fetch(`${this.options.baseUrl}/rest/${this.options.storeCode}/V1/integration/admin/token`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ username: this.options.username, password: this.options.password }),
- })
-
- const token = await response.text()
-
- if (!response.ok) {
- throw new MedusaError(MedusaError.Types.UNAUTHORIZED, `Failed to authenticate with Magento: ${token}`)
- }
-
- this.accessToken = {
- token: token.replaceAll("\"", ""),
- expiresAt: new Date(Date.now() + 4 * 60 * 60 * 1000), // 4 hours in milliseconds
- }
- }
-}
-```
-
-You create an `authenticate` method that sends a POST request to the Magento server's `/rest/{storeCode}/V1/integration/admin/token` endpoint, passing the username and password in the request body.
-
-If the request is successful, you store the access token and its expiration date in the `accessToken` property. If the request fails, you throw a `MedusaError` with the error message returned by Magento.
-
-Lastly, add an `isAccessTokenExpired` method that checks if the access token has expired:
-
-```ts title="src/modules/magento/service.ts"
-export default class MagentoModuleService {
- // ...
- async isAccessTokenExpired(): Promise {
- return !this.accessToken || this.accessToken.expiresAt < new Date()
- }
-}
-```
-
-In the `isAccessTokenExpired` method, you return a boolean indicating whether the access token has expired. You'll use this in later methods to check if you need to refresh the access token.
-
-### Retrieve Products from Magento
-
-Next, you'll add a method that retrieves products from Magento. Due to limitations in Magento's API that makes it difficult to differentiate between simple products that don't belong to a configurable product and those that do, you'll only retrieve configurable products and their children. You'll also retrieve the configurable attributes of the product, such as color and size.
-
-First, you'll add some types to represent a Magento product and its attributes. Create the file `src/modules/magento/types.ts` in the plugin with the following content:
-
-
-
-```ts title="src/modules/magento/types.ts"
-export type MagentoProduct = {
- id: number
- sku: string
- name: string
- price: number
- status: number
- // not handling other types
- type_id: "simple" | "configurable"
- created_at: string
- updated_at: string
- extension_attributes: {
- category_links: {
- category_id: string
- }[]
- configurable_product_links?: number[]
- configurable_product_options?: {
- id: number
- attribute_id: string
- label: string
- position: number
- values: {
- value_index: number
- }[]
- }[]
- }
- media_gallery_entries: {
- id: number
- media_type: string
- label: string
- position: number
- disabled: boolean
- types: string[]
- file: string
- }[]
- custom_attributes: {
- attribute_code: string
- value: string
- }[]
- // added by module
- children?: MagentoProduct[]
-}
-
-export type MagentoAttribute = {
- attribute_code: string
- attribute_id: number
- default_frontend_label: string
- options: {
- label: string
- value: string
- }[]
-}
-
-export type MagentoPagination = {
- search_criteria: {
- filter_groups: [],
- page_size: number
- current_page: number
- }
- total_count: number
-}
-
-export type MagentoPaginatedResponse = {
- items: TData[]
-} & MagentoPagination
-```
-
-You define the following types:
-
-- `MagentoProduct`: Represents a product in Magento.
-- `MagentoAttribute`: Represents an attribute in Magento.
-- `MagentoPagination`: Represents the pagination information returned by Magento's API.
-- `MagentoPaginatedResponse`: Represents a paginated response from Magento's API for a specific item type, such as products.
-
-Next, add the `getProducts` method to the `MagentoModuleService` class:
-
-```ts title="src/modules/magento/service.ts"
-export default class MagentoModuleService {
- // ...
- async getProducts(options?: {
- currentPage?: number
- pageSize?: number
- }): Promise<{
- products: MagentoProduct[]
- attributes: MagentoAttribute[]
- pagination: MagentoPagination
- }> {
- const { currentPage = 1, pageSize = 100 } = options || {}
- const getAccessToken = await this.isAccessTokenExpired()
- if (getAccessToken) {
- await this.authenticate()
- }
-
- // TODO prepare query params
- }
-}
-```
-
-The `getProducts` method receives an optional `options` object with the `currentPage` and `pageSize` properties. So far, you check if the access token has expired and, if so, retrieve a new one using the `authenticate` method.
-
-Next, you'll prepare the query parameters to pass in the request that retrieves products. Replace the `TODO` with the following:
-
-```ts title="src/modules/magento/service.ts"
-const searchQuery = new URLSearchParams()
-// pass pagination parameters
-searchQuery.append(
- "searchCriteria[currentPage]",
- currentPage?.toString() || "1"
-)
-searchQuery.append(
- "searchCriteria[pageSize]",
- pageSize?.toString() || "100"
-)
-
-// retrieve only configurable products
-searchQuery.append(
- "searchCriteria[filter_groups][1][filters][0][field]",
- "type_id"
-)
-searchQuery.append(
- "searchCriteria[filter_groups][1][filters][0][value]",
- "configurable"
-)
-searchQuery.append(
- "searchCriteria[filter_groups][1][filters][0][condition_type]",
- "in"
-)
-
-// TODO send request to retrieve products
-```
-
-You create a `searchQuery` object to store the query parameters to pass in the request. Then, you add the pagination parameters and the filter to retrieve only configurable products.
-
-Next, you'll send the request to retrieve products from Magento. Replace the `TODO` with the following:
-
-```ts title="src/modules/magento/service.ts"
-const { items: products, ...pagination }: MagentoPaginatedResponse = await fetch(
- `${this.options.baseUrl}/rest/${this.options.storeCode}/V1/products?${searchQuery}`,
- {
- headers: {
- "Authorization": `Bearer ${this.accessToken.token}`,
- },
- }
-).then((res) => res.json())
-.catch((err) => {
- console.log(err)
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- `Failed to get products from Magento: ${err.message}`
- )
-})
-
-// TODO prepare products
-```
-
-You send a `GET` request to the Magento server's `/rest/{storeCode}/V1/products` endpoint, passing the query parameters in the URL. You also pass the access token in the `Authorization` header.
-
-Next, you'll prepare the retrieved products by retrieving their children, configurable attributes, and modifying their image URLs. Replace the `TODO` with the following:
-
-```ts title="src/modules/magento/service.ts"
-const attributeIds: string[] = []
-
-await promiseAll(
- products.map(async (product) => {
- // retrieve its children
- product.children = await fetch(
- `${this.options.baseUrl}/rest/${this.options.storeCode}/V1/configurable-products/${product.sku}/children`,
- {
- headers: {
- "Authorization": `Bearer ${this.accessToken.token}`,
- },
- }
- ).then((res) => res.json())
- .catch((err) => {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- `Failed to get product children from Magento: ${err.message}`
- )
- })
-
- product.media_gallery_entries = product.media_gallery_entries.map(
- (entry) => ({
- ...entry,
- file: `${this.options.migrationOptions?.imageBaseUrl}${entry.file}`,
- }
- ))
-
- attributeIds.push(...(
- product.extension_attributes.configurable_product_options?.map(
- (option) => option.attribute_id) || []
- )
- )
- })
-)
-
-// TODO retrieve attributes
-```
-
-You loop over the retrieved products and retrieve their children using the `/rest/{storeCode}/V1/configurable-products/{sku}/children` endpoint. You also modify the image URLs to use the base URL in the migration options, if provided.
-
-In addition, you store the IDs of the configurable products' attributes in the `attributeIds` array. You'll add a method that retrieves these attributes.
-
-Add the new method `getAttributes` to the `MagentoModuleService` class:
-
-```ts title="src/modules/magento/service.ts"
-export default class MagentoModuleService {
- // ...
- async getAttributes({
- ids,
- }: {
- ids: string[]
- }): Promise {
- const getAccessToken = await this.isAccessTokenExpired()
- if (getAccessToken) {
- await this.authenticate()
- }
-
- // filter by attribute IDs
- const searchQuery = new URLSearchParams()
- searchQuery.append(
- "searchCriteria[filter_groups][0][filters][0][field]",
- "attribute_id"
- )
- searchQuery.append(
- "searchCriteria[filter_groups][0][filters][0][value]",
- ids.join(",")
- )
- searchQuery.append(
- "searchCriteria[filter_groups][0][filters][0][condition_type]",
- "in"
- )
-
- const {
- items: attributes,
- }: MagentoPaginatedResponse = await fetch(
- `${this.options.baseUrl}/rest/${this.options.storeCode}/V1/products/attributes?${searchQuery}`,
- {
- headers: {
- "Authorization": `Bearer ${this.accessToken.token}`,
- },
- }
- ).then((res) => res.json())
- .catch((err) => {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- `Failed to get attributes from Magento: ${err.message}`
- )
- })
-
- return attributes
- }
-}
-```
-
-The `getAttributes` method receives an object with the `ids` property, which is an array of attribute IDs. You check if the access token has expired and, if so, retrieve a new one using the `authenticate` method.
-
-Next, you prepare the query parameters to pass in the request to retrieve attributes. You send a `GET` request to the Magento server's `/rest/{storeCode}/V1/products/attributes` endpoint, passing the query parameters in the URL. You also pass the access token in the `Authorization` header.
-
-Finally, you return the retrieved attributes.
-
-Now, go back to the `getProducts` method and replace the `TODO` with the following:
-
-```ts title="src/modules/magento/service.ts"
-const attributes = await this.getAttributes({ ids: attributeIds })
-
-return { products, attributes, pagination }
-```
-
-You retrieve the configurable products' attributes using the `getAttributes` method and return the products, attributes, and pagination information.
-
-You'll use this method in a later step to retrieve products from Magento.
-
-### Export Module Definition
-
-The final piece to a module is its definition, which you export in an `index.ts` file at its root directory. This definition tells Medusa the name of the module and its service.
-
-So, create the file `src/modules/magento/index.ts` with the following content:
-
-
-
-```ts title="src/modules/magento/index.ts"
-import { Module } from "@medusajs/framework/utils"
-import MagentoModuleService from "./service"
-
-export const MAGENTO_MODULE = "magento"
-
-export default Module(MAGENTO_MODULE, {
- service: MagentoModuleService,
-})
-```
-
-You use the `Module` function from the Modules SDK to create the module's definition. It accepts two parameters:
-
-1. The module's name, which is `magento`.
-2. An object with a required property `service` indicating the module's service.
-
-You'll later use the module's service to retrieve products from Magento.
-
-### Pass Options to Plugin
-
-As mentioned earlier when you registered the plugin in the Medusa Application's `medusa-config.ts` file, you can pass options to the plugin. These options are then passed to the modules in the plugin.
-
-So, add the following options to the plugin's registration in the `medusa-config.ts` file of the Medusa application:
-
-```ts title="medusa-config.ts"
-module.exports = defineConfig({
- // ...
- plugins: [
- {
- resolve: "medusa-plugin-magento",
- options: {
- baseUrl: process.env.MAGENTO_BASE_URL,
- username: process.env.MAGENTO_USERNAME,
- password: process.env.MAGENTO_PASSWORD,
- migrationOptions: {
- imageBaseUrl: process.env.MAGENTO_IMAGE_BASE_URL,
- },
- },
- },
- ],
-})
-```
-
-You pass the options that you defined in the `MagentoModuleService`. Make sure to also set their environment variables in the `.env` file:
-
-```bash
-MAGENTO_BASE_URL=https://magento.example.com
-MAGENTO_USERNAME=admin
-MAGENTO_PASSWORD=password
-MAGENTO_IMAGE_BASE_URL=https://magento.example.com/pub/media/catalog/product
-```
-
-Where:
-
-- `MAGENTO_BASE_URL`: The base URL of the Magento server. It can also be a local URL, such as `http://localhost:8080`.
-- `MAGENTO_USERNAME`: The username of a Magento admin user to authenticate with the Magento server.
-- `MAGENTO_PASSWORD`: The password of the Magento admin user.
-- `MAGENTO_IMAGE_BASE_URL`: The base URL to use for product images. Magento stores product images in the `pub/media/catalog/product` directory, so you can reference them directly or use a CDN URL. If the URLs of product images in the Medusa server already have a different base URL, you can omit this option.
-
-Medusa supports integrating third-party services, such as [S3](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/architectural-modules/file/s3/index.html.md), in a File Module Provider. Refer to the [File Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/architectural-modules/file/index.html.md) documentation to find other module providers and how to create a custom provider.
-
-You can now use the Magento Module to migrate data, which you'll do in the next steps.
-
-***
-
-## Step 5: Build Product Migration Workflow
-
-In this section, you'll add the feature to migrate products from Magento to Medusa. To implement this feature, you'll use a workflow.
-
-A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it's a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in an API route or a scheduled job.
-
-By implementing the migration feature in a workflow, you ensure that the data remains consistent and that the migration process can be rolled back if an error occurs.
-
-Refer to the [Workflows](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md) documentation to learn more about workflows.
-
-### Workflow Steps
-
-The workflow you'll create will have the following steps:
-
-- [getMagentoProductsStep](#getMagentoProductsStep): Retrieve products from Magento using the Magento Module.
-- [useQueryGraphStep](https://docs.medusajs.com/references/helper-steps/useQueryGraphStep/index.html.md): Retrieve Medusa store details, which you'll need when creating the products.
-- [useQueryGraphStep](https://docs.medusajs.com/references/helper-steps/useQueryGraphStep/index.html.md): Retrieve a shipping profile, which you'll associate the created products with.
-- [useQueryGraphStep](https://docs.medusajs.com/references/helper-steps/useQueryGraphStep/index.html.md): Retrieve Magento products that are already in Medusa to update them, instead of creating them.
-- [createProductsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createProductsWorkflow/index.html.md): Create products in the Medusa application.
-- [updateProductsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateProductsWorkflow/index.html.md): Update existing products in the Medusa application.
-
-You only need to implement the `getMagentoProductsStep` step, which retrieves the products from Magento. The other steps and workflows are provided by Medusa's `@medusajs/medusa/core-flows` package.
-
-### getMagentoProductsStep
-
-The first step of the workflow retrieves and returns the products from Magento.
-
-In your plugin, create the file `src/workflows/steps/get-magento-products.ts` with the following content:
-
-
-
-```ts title="src/workflows/steps/get-magento-products.ts"
-import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
-import { MAGENTO_MODULE } from "../../modules/magento"
-import MagentoModuleService from "../../modules/magento/service"
-
-type GetMagentoProductsInput = {
- currentPage: number
- pageSize: number
-}
-
-export const getMagentoProductsStep = createStep(
- "get-magento-products",
- async ({ currentPage, pageSize }: GetMagentoProductsInput, { container }) => {
- const magentoModuleService: MagentoModuleService =
- container.resolve(MAGENTO_MODULE)
-
- const response = await magentoModuleService.getProducts({
- currentPage,
- pageSize,
- })
-
- return new StepResponse(response)
- }
-)
-```
-
-You create a step using `createStep` from the Workflows SDK. It accepts two parameters:
-
-1. The step's name, which is `get-magento-products`.
-2. An async function that executes the step's logic. The function receives two parameters:
- - The input data for the step, which in this case is the pagination parameters.
- - An object holding the workflow's context, including the [Medusa Container](https://docs.medusajs.com/docslearn/fundamentals/medusa-container/index.html.md) that allows you to resolve framework and commerce tools.
-
-In the step function, you resolve the Magento Module's service from the container, then use its `getProducts` method to retrieve the products from Magento.
-
-Steps that return data must return them in a `StepResponse` instance. The `StepResponse` constructor accepts as a parameter the data to return.
-
-### Create migrateProductsFromMagentoWorkflow
-
-You'll now create the workflow that migrates products from Magento using the step you created and steps from Medusa's `@medusajs/medusa/core-flows` package.
-
-In your plugin, create the file `src/workflows/migrate-products-from-magento.ts` with the following content:
-
-
-
-```ts title="src/workflows/migrate-products-from-magento.ts"
-import {
- createWorkflow, transform, WorkflowResponse,
-} from "@medusajs/framework/workflows-sdk"
-import {
- CreateProductWorkflowInputDTO, UpsertProductDTO,
-} from "@medusajs/framework/types"
-import {
- createProductsWorkflow,
- updateProductsWorkflow,
- useQueryGraphStep,
-} from "@medusajs/medusa/core-flows"
-import { getMagentoProductsStep } from "./steps/get-magento-products"
-
-type MigrateProductsFromMagentoWorkflowInput = {
- currentPage: number
- pageSize: number
-}
-
-export const migrateProductsFromMagentoWorkflowId =
- "migrate-products-from-magento"
-
-export const migrateProductsFromMagentoWorkflow = createWorkflow(
- {
- name: migrateProductsFromMagentoWorkflowId,
- retentionTime: 10000,
- store: true,
- },
- (input: MigrateProductsFromMagentoWorkflowInput) => {
- const { pagination, products, attributes } = getMagentoProductsStep(
- input
- )
- // TODO prepare data to create and update products
- }
-)
-```
-
-You create a workflow using `createWorkflow` from the Workflows SDK. It accepts two parameters:
-
-1. An object with the workflow's configuration, including the name and whether to store the workflow's executions. You enable storing the workflow execution so that you can view it later in the Medusa Admin dashboard.
-2. A worflow constructor function, which holds the workflow's implementation. The function receives the input data for the workflow, which is the pagination parameters.
-
-In the workflow constructor function, you use the `getMagentoProductsStep` step to retrieve the products from Magento, passing it the pagination parameters from the workflow's input.
-
-Next, you'll retrieve the Medusa store details and shipping profiles. These are necessary to prepare the data of the products to create or update.
-
-Replace the `TODO` in the workflow function with the following:
-
-```ts title="src/workflows/migrate-products-from-magento.ts"
-const { data: stores } = useQueryGraphStep({
- entity: "store",
- fields: ["supported_currencies.*", "default_sales_channel_id"],
- pagination: {
- take: 1,
- skip: 0,
- },
-})
-
-const { data: shippingProfiles } = useQueryGraphStep({
- entity: "shipping_profile",
- fields: ["id"],
- pagination: {
- take: 1,
- skip: 0,
- },
-}).config({ name: "get-shipping-profiles" })
-
-// TODO retrieve existing products
-```
-
-You use the `useQueryGraphStep` step to retrieve the store details and shipping profiles. `useQueryGraphStep` is a Medusa step that wraps [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), allowing you to use it in a workflow. Query is a tool that retrieves data across modules.
-
-Whe retrieving the store details, you specifically retrieve its supported currencies and default sales channel ID. You'll associate the products with the store's default sales channel, and set their variant prices in the supported currencies. You'll also associate the products with a shipping profile.
-
-Next, you'll retrieve products that were previously migrated from Magento to determine which products to create or update. Replace the `TODO` with the following:
-
-```ts title="src/workflows/migrate-products-from-magento.ts"
-const externalIdFilters = transform({
- products,
-}, (data) => {
- return data.products.map((product) => product.id.toString())
-})
-
-const { data: existingProducts } = useQueryGraphStep({
- entity: "product",
- fields: ["id", "external_id", "variants.id", "variants.metadata"],
- filters: {
- external_id: externalIdFilters,
- },
-}).config({ name: "get-existing-products" })
-
-// TODO prepare products to create or update
-```
-
-Since the Medusa application creates an internal representation of the workflow's constructor function, you can't manipulate data directly, as variables have no value while creating the internal representation.
-
-Refer to the [Workflows](https://docs.medusajs.com/docs/learn/fundamentals/workflows/constructor-constraints/index.html.md) documentation to learn more about the workflow constructor function's constraints.
-
-Instead, you can manipulate data in a workflow's constructor function using `transform` from the Workflows SDK. `transform` is a function that accepts two parameters:
-
-- The data to transform, which in this case is the Magento products.
-- A function that transforms the data. The function receives the data passed in the first parameter and returns the transformed data.
-
-In the transformation function, you return the IDs of the Magento products. Then, you use the `useQueryGraphStep` to retrieve products in the Medusa application that have an `external_id` property matching the IDs of the Magento products. You'll use this property to store the IDs of the products in Magento.
-
-Next, you'll prepare the data to create and update the products. Replace the `TODO` in the workflow function with the following:
-
-```ts title="src/workflows/migrate-products-from-magento.ts" highlights={prepareHighlights}
-const {
- productsToCreate,
- productsToUpdate,
-} = transform({
- products,
- attributes,
- stores,
- shippingProfiles,
- existingProducts,
-}, (data) => {
- const productsToCreate = new Map()
- const productsToUpdate = new Map()
-
- data.products.forEach((magentoProduct) => {
- const productData: CreateProductWorkflowInputDTO | UpsertProductDTO = {
- title: magentoProduct.name,
- description: magentoProduct.custom_attributes.find(
- (attr) => attr.attribute_code === "description"
- )?.value,
- status: magentoProduct.status === 1 ? "published" : "draft",
- handle: magentoProduct.custom_attributes.find(
- (attr) => attr.attribute_code === "url_key"
- )?.value,
- external_id: magentoProduct.id.toString(),
- thumbnail: magentoProduct.media_gallery_entries.find(
- (entry) => entry.types.includes("thumbnail")
- )?.file,
- sales_channels: [{
- id: data.stores[0].default_sales_channel_id,
- }],
- shipping_profile_id: data.shippingProfiles[0].id,
- }
- const existingProduct = data.existingProducts.find((p) => p.external_id === productData.external_id)
-
- if (existingProduct) {
- productData.id = existingProduct.id
- }
-
- productData.options = magentoProduct.extension_attributes.configurable_product_options?.map((option) => {
- const attribute = data.attributes.find((attr) => attr.attribute_id === parseInt(option.attribute_id))
- return {
- title: option.label,
- values: attribute?.options.filter((opt) => {
- return option.values.find((v) => v.value_index === parseInt(opt.value))
- }).map((opt) => opt.label) || [],
- }
- }) || []
-
- productData.variants = magentoProduct.children?.map((child) => {
- const childOptions: Record = {}
-
- child.custom_attributes.forEach((attr) => {
- const attrData = data.attributes.find((a) => a.attribute_code === attr.attribute_code)
- if (!attrData) {
- return
- }
-
- childOptions[attrData.default_frontend_label] = attrData.options.find((opt) => opt.value === attr.value)?.label || ""
- })
-
- const variantExternalId = child.id.toString()
- const existingVariant = existingProduct.variants.find((v) => v.metadata.external_id === variantExternalId)
-
- return {
- title: child.name,
- sku: child.sku,
- options: childOptions,
- prices: data.stores[0].supported_currencies.map(({ currency_code }) => {
- return {
- amount: child.price,
- currency_code,
- }
- }),
- metadata: {
- external_id: variantExternalId,
- },
- id: existingVariant?.id,
- }
- })
-
- productData.images = magentoProduct.media_gallery_entries.filter((entry) => !entry.types.includes("thumbnail")).map((entry) => {
- return {
- url: entry.file,
- metadata: {
- external_id: entry.id.toString(),
- },
- }
- })
-
- if (productData.id) {
- productsToUpdate.set(existingProduct.id, productData)
- } else {
- productsToCreate.set(productData.external_id!, productData)
- }
- })
-
- return {
- productsToCreate: Array.from(productsToCreate.values()),
- productsToUpdate: Array.from(productsToUpdate.values()),
- }
-})
-
-// TODO create and update products
-```
-
-You use `transform` again to prepare the data to create and update the products in the Medusa application. For each Magento product, you map its equivalent Medusa product's data:
-
-- You set the product's general details, such as the title, description, status, handle, external ID, and thumbnail using the Magento product's data and custom attributes.
-- You associate the product with the default sales channel and shipping profile retrieved previously.
-- You map the Magento product's configurable product options to Medusa product options. In Medusa, a product's option has a label, such as "Color", and values, such as "Red". To map the option values, you use the attributes retrieved from Magento.
-- You map the Magento product's children to Medusa product variants. For the variant options, you pass an object whose keys is the option's label, such as "Color", and values is the option's value, such as "Red". For the prices, you set the variant's price based on the Magento child's price for every supported currency in the Medusa store. Also, you set the Magento child product's ID in the Medusa variant's `metadata.external_id` property.
-- You map the Magento product's media gallery entries to Medusa product images. You filter out the thumbnail image and set the URL and the Magento image's ID in the Medusa image's `metadata.external_id` property.
-
-In addition, you use the existing products retrieved in the previous step to determine whether a product should be created or updated. If there's an existing product whose `external_id` matches the ID of the magento product, you set the existing product's ID in the `id` property of the product to be updated. You also do the same for its variants.
-
-Finally, you return the products to create and update.
-
-The last steps of the workflow is to create and update the products. Replace the `TODO` in the workflow function with the following:
-
-```ts title="src/workflows/migrate-products-from-magento.ts"
-createProductsWorkflow.runAsStep({
- input: {
- products: productsToCreate,
- },
-})
-
-updateProductsWorkflow.runAsStep({
- input: {
- products: productsToUpdate,
- },
-})
-
-return new WorkflowResponse(pagination)
-```
-
-You use the `createProductsWorkflow` and `updateProductsWorkflow` workflows from Medusa's `@medusajs/medusa/core-flows` package to create and update the products in the Medusa application.
-
-Workflows must return an instance of `WorkflowResponse`, passing as a parameter the data to return to the workflow's executor. This workflow returns the pagination parameters, allowing you to paginate the product migration process.
-
-You can now use this workflow to migrate products from Magento to Medusa. You'll learn how to use it in the next steps.
-
-***
-
-## Step 6: Schedule Product Migration
-
-There are many ways to execute tasks asynchronously in Medusa, such as [scheduling a job](https://docs.medusajs.com/docs/learn/fundamentals/scheduled-jobs/index.html.md) or [handling emitted events](https://docs.medusajs.com/docs/learn/fundamentals/events-and-subscribers/index.html.md).
-
-In this guide, you'll learn how to schedule the product migration at a specified interval using a scheduled job. A scheduled job is an asynchronous function that the Medusa application runs at the interval you specify during the Medusa application's runtime.
-
-Refer to the [Scheduled Jobs](https://docs.medusajs.com/docs/learn/fundamentals/scheduled-jobs/index.html.md) documentation to learn more about scheduled jobs.
-
-To create a scheduled job, in your plugin, create the file `src/jobs/migrate-magento.ts` with the following content:
-
-
-
-```ts title="src/jobs/migrate-magento.ts"
-import { MedusaContainer } from "@medusajs/framework/types"
-import { migrateProductsFromMagentoWorkflow } from "../workflows"
-
-export default async function migrateMagentoJob(
- container: MedusaContainer
-) {
- const logger = container.resolve("logger")
- logger.info("Migrating products from Magento...")
-
- let currentPage = 0
- const pageSize = 100
- let totalCount = 0
-
- do {
- currentPage++
-
- const {
- result: pagination,
- } = await migrateProductsFromMagentoWorkflow(container).run({
- input: {
- currentPage,
- pageSize,
- },
- })
-
- totalCount = pagination.total_count
- } while (currentPage * pageSize < totalCount)
-
- logger.info("Finished migrating products from Magento")
-}
-
-export const config = {
- name: "migrate-magento-job",
- schedule: "0 0 * * *",
-}
-```
-
-A scheduled job file must export:
-
-- An asynchronous function that executes the job's logic. The function receives the [Medusa container](https://docs.medusajs.com/docs/learn/fundamentals/medusa-container/index.html.md) as a parameter.
-- An object with the job's configuration, including the name and the schedule. The schedule is a cron job pattern as a string.
-
-In the job function, you resolve the [logger](https://docs.medusajs.com/docs/learn/debugging-and-testing/logging/index.html.md) from the container to log messages. Then, you paginate the product migration process by running the `migrateProductsFromMagentoWorkflow` workflow at each page until you've migrated all products. You use the pagination result returned by the workflow to determine whether there are more products to migrate.
-
-Based on the job's configurations, the Medusa application will run the job at midnight every day.
-
-### Test it Out
-
-To test out this scheduled job, first, change the configuration to run the job every minute:
-
-```ts title="src/jobs/migrate-magento.ts"
-export const config = {
- // ...
- schedule: "* * * * *",
-}
-```
-
-Then, make sure to run the `plugin:develop` command in the plugin if you haven't already:
-
-```bash
-npx medusa plugin:develop
-```
-
-This ensures that the plugin's latest changes are reflected in the Medusa application.
-
-Finally, start the Medusa application that the plugin is installed in:
-
-```bash npm2yarn
-npm run dev
-```
-
-After a minute, you'll see a message in the terminal indicating that the migration started:
-
-```plain title="Terminal"
-info: Migrating products from Magento...
-```
-
-Once the migration is done, you'll see the following message:
-
-```plain title="Terminal"
-info: Finished migrating products from Magento
-```
-
-To confirm that the products were migrated, open the Medusa Admin dashboard at `http://localhost:9000/app` and log in. Then, click on Products in the sidebar. You'll see your magento products in the list of products.
-
-
-
-***
-
-## Next Steps
-
-You've now implemented the logic to migrate products from Magento to Medusa. You can re-use the plugin across Medusa applications. You can also expand on the plugin to:
-
-- Migrate other entities, such as orders, customers, and categories. Migrating other entities follows the same pattern as migrating products, using workflows and scheduled jobs. You only need to format the data to be migrated as needed.
-- Allow triggering migrations from the Medusa Admin dashboard using [Admin Customizations](https://docs.medusajs.com/docs/learn/fundamentals/admin/index.html.md). This feature is available in the [Example Repository](https://github.com/medusajs/example-repository/tree/main/src/admin).
-
-If you're new to Medusa, check out the [main documentation](https://docs.medusajs.com/docs/learn/index.html.md), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
-
-To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
-
-
# Integrate Algolia (Search) with Medusa
In this tutorial, you'll learn how to integrate Medusa with Algolia.
@@ -45728,6 +45441,757 @@ If you're new to Medusa, check out the [main documentation](https://docs.medusaj
To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
+# Integrate Medusa with Resend (Email Notifications)
+
+In this guide, you'll learn how to integrate Medusa with Resend.
+
+When you install a Medusa application, you get a fully-fledged commerce platform with a framework for customization. Medusa's architecture supports integrating third-party services, such as an email service, that allow you to build your unique requirements around core commerce flows.
+
+[Resend](https://resend.com/docs/introduction) is an email service with an intuitive developer experience to send emails from any application type, including Node.js servers. By integrating Resend with Medusa, you can build flows to send an email when a commerce operation is performed, such as when an order is placed.
+
+This guide will teach you how to:
+
+- Install and set up Medusa.
+- Integrate Resend into Medusa for sending emails.
+- Build a flow to send an email with Resend when a customer places an order.
+
+You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
+
+[Example Repository](https://github.com/medusajs/examples/tree/main/resend-integration): Find the full code of the guide in this repository.
+
+***
+
+## Step 1: Install a Medusa Application
+
+### Prerequisites
+
+- [Node.js v20+](https://nodejs.org/en/download)
+- [Git CLI tool](https://git-scm.com/downloads)
+- [PostgreSQL](https://www.postgresql.org/download/)
+
+Start by installing the Medusa application on your machine with the following command:
+
+```bash
+npx create-medusa-app@latest
+```
+
+You'll first be asked for the project's name. Then, when you're asked whether you want to install the Next.js storefront, choose `Y` for yes.
+
+Afterwards, the installation process will start, which will install the Medusa application in a directory with your project's name, and the Next.js storefront in a directory with the `{project-name}-storefront` name.
+
+The Medusa application is composed of a headless Node.js server and an admin dashboard. The storefront is installed or custom-built separately and connects to the Medusa application through its REST endpoints, called [API routes](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md). Learn more about Medusa's architecture in [this documentation](https://docs.medusajs.com/docs/learn/introduction/architecture/index.html.md).
+
+Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credential and submit the form. Afterwards, you can login with the new user and explore the dashboard.
+
+The Next.js storefront is also running at `http://localhost:8000`.
+
+Check out the [troubleshooting guides](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/troubleshooting/create-medusa-app-errors/index.html.md) for help.
+
+***
+
+## Step 2: Prepare Resend Account
+
+If you don't have a Resend Account, create one on [their website](https://resend.com/emails).
+
+In addition, Resend allows you to send emails from the address `onboarding@resend.dev` only to your account's email, which is useful for development purposes. If you have a custom domain to send emails from, add it to your Resend account's domains:
+
+1. Go to Domains from the sidebar.
+2. Click on Add Domain.
+
+
+
+3\. In the form that opens, enter your domain name and select a region close to your users, then click Add.
+
+
+
+4\. In the domain's details page that opens, you'll find DNS records to add to your DNS provider. After you add them, click on Verify DNS Records. You can start sending emails from your custom domain once it's verified.
+
+The steps to add DNS records are different for each provider, so refer to your provider's documentation or knowledge base for more details.
+
+
+
+You also need an API key to connect to your Resend account from Medusa, but you'll create that one in a later section.
+
+***
+
+## Step 3: Install Resend Dependencies
+
+In this step, you'll install two packages useful for your Resend integration:
+
+1. `resend`, which is the Resend SDK:
+
+```bash npm2yarn
+npm install resend
+```
+
+2\. [react-email](https://github.com/resend/react-email), which is a package created by Resend to create email templates with React:
+
+```bash npm2yarn
+npm install @react-email/components -E
+```
+
+You'll use these packages in the next steps.
+
+***
+
+## Step 4: Create Resend Module Provider
+
+To integrate third-party services into Medusa, you create a custom module. A module is a re-usable package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
+
+Medusa's Notification Module delegates sending notifications to other modules, called module providers. In this step, you'll create a Resend Module Provider that implements sending notifications through the email channel. In later steps, you'll send email notifications with Resend when an order is placed through this provider.
+
+Learn more about modules in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md).
+
+### Create Module Directory
+
+A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/resend`.
+
+### Create Service
+
+You define a module's functionalities in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to the database, which is useful if your module defines tables in the database, or connect to a third-party service.
+
+In this section, you'll create the Resend Module Provider's service and the methods necessary to send an email with Resend.
+
+Start by creating the file `src/modules/resend/service.ts` with the following content:
+
+```ts title="src/modules/resend/service.ts" highlights={serviceHighlights1}
+import {
+ AbstractNotificationProviderService,
+} from "@medusajs/framework/utils"
+import {
+ Logger,
+} from "@medusajs/framework/types"
+import {
+ Resend,
+} from "resend"
+
+type ResendOptions = {
+ api_key: string
+ from: string
+ html_templates?: Record
+}
+
+class ResendNotificationProviderService extends AbstractNotificationProviderService {
+ static identifier = "notification-resend"
+ private resendClient: Resend
+ private options: ResendOptions
+ private logger: Logger
+
+ // ...
+}
+
+export default ResendNotificationProviderService
+```
+
+A Notification Module Provider's service must extend the `AbstractNotificationProviderService`. It has a `send` method that you'll implement soon. The service must also have an `identifier` static property, which is a unique identifier that the Medusa application will use to register the provider in the database.
+
+The `ResendNotificationProviderService` class also has the following properties:
+
+- `resendClient` of type `Resend` (from the Resend SDK you installed in the previous step) to send emails through Resend.
+- `options` of type `ResendOptions`. Modules accept options through Medusa's configurations. This ensures that the module is reusable across applications and you don't use sensitive variables like API keys directly in your code. The options that the Resend Module Provider accepts are:
+ - `api_key`: The Resend API key.
+ - `from`: The email address to send the emails from.
+ - `html_templates`: An optional object to replace the default subject and template that the Resend Module uses. This is also useful to support custom emails in different Medusa application setups.
+- `logger` property, which is an instance of Medusa's [Logger](https://docs.medusajs.com/docs/learn/debugging-and-testing/logging/index.html.md), to log messages.
+
+To send requests using the `resendClient`, you need to initialize it in the class's constructor. So, add the following constructor to `ResendNotificationProviderService`:
+
+```ts title="src/modules/resend/service.ts"
+// ...
+
+type InjectedDependencies = {
+ logger: Logger
+}
+
+class ResendNotificationProviderService extends AbstractNotificationProviderService {
+ // ...
+ constructor(
+ { logger }: InjectedDependencies,
+ options: ResendOptions
+ ) {
+ super()
+ this.resendClient = new Resend(options.api_key)
+ this.options = options
+ this.logger = logger
+ }
+}
+```
+
+A module's service accepts two parameters:
+
+1. Dependencies resolved from the [Module's container](https://docs.medusajs.com/docs/learn/fundamentals/modules/container/index.html.md), which is the module's local registry that the Medusa application adds framework tools to. In this service, you resolve the [Logger utility](https://docs.medusajs.com/docs/learn/debugging-and-testing/logging/index.html.md) from the module's container.
+2. The module's options that are passed to the module in Medusa's configuration as you'll see in a later section.
+
+Using the API key passed in the module's options, you initialize the Resend client. You also set the `options` and `logger` properties.
+
+#### Validate Options Method
+
+A Notification Module Provider's service can implement a static `validateOptions` method that ensures the options passed to the module through Medusa's configurations are valid.
+
+So, add to the `ResendNotificationProviderService` the `validateOptions` method:
+
+```ts title="src/modules/resend/service.ts"
+// other imports...
+import {
+ // other imports...
+ MedusaError,
+} from "@medusajs/framework/utils"
+
+// ...
+
+class ResendNotificationProviderService extends AbstractNotificationProviderService {
+ // ...
+ static validateOptions(options: Record) {
+ if (!options.api_key) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ "Option `api_key` is required in the provider's options."
+ )
+ }
+ if (!options.from) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ "Option `from` is required in the provider's options."
+ )
+ }
+ }
+}
+```
+
+In the `validateOptions` method, you throw an error if the `api_key` or `from` options aren't passed to the module. To throw errors, you use `MedusaError` from the Modules SDK. This ensures errors follow Medusa's conventions and are displayed similar to Medusa's errors.
+
+#### Implement Template Methods
+
+Each email type has a different template and content. For example, order confirmation emails show the order's details, whereas customer confirmation emails show a greeting message to the customer.
+
+So, add two methods to the `ResendNotificationProviderService` class that retrieve the email template and subject of a specified template type:
+
+```ts title="src/modules/resend/service.ts" highlights={serviceHighlights2}
+// imports and types...
+
+enum Templates {
+ ORDER_PLACED = "order-placed",
+}
+
+const templates: {[key in Templates]?: (props: unknown) => React.ReactNode} = {
+ // TODO add templates
+}
+
+class ResendNotificationProviderService extends AbstractNotificationProviderService {
+ // ...
+ getTemplate(template: Templates) {
+ if (this.options.html_templates?.[template]) {
+ return this.options.html_templates[template].content
+ }
+ const allowedTemplates = Object.keys(templates)
+
+ if (!allowedTemplates.includes(template)) {
+ return null
+ }
+
+ return templates[template]
+ }
+
+ getTemplateSubject(template: Templates) {
+ if (this.options.html_templates?.[template]?.subject) {
+ return this.options.html_templates[template].subject
+ }
+ switch(template) {
+ case Templates.ORDER_PLACED:
+ return "Order Confirmation"
+ default:
+ return "New Email"
+ }
+ }
+}
+```
+
+You first define a `Templates` enum, which holds the names of supported template types. You can add more template types to this enum later. You also define a `templates` variable that specifies the React template for each template type. You'll add templates to this variable later.
+
+In the `ResendNotificationProviderService` you add two methods:
+
+- `getTemplate`: Retrieve the template of a template type. If the `html_templates` option is set for the specified template type, you return its `content`'s value. Otherwise, you retrieve the template from the `templates` variable.
+- `getTemplateSubject`: Retrieve the subject of a template type. If a `subject` is passed for the template type in the `html_templates`, you return its value. Otherwise, you return a subject based on the template type.
+
+You'll use these methods in the `send` method next.
+
+#### Implement Send Method
+
+In this section, you'll implement the `send` method of `ResendNotificationProviderService`. When you send a notification through the email channel later using the Notification Module, the Notification Module's service will use this `send` method under the hood to send the email with Resend.
+
+In the `send` method, you'll retrieve the template and subject of the email template, then send the email using the Resend client.
+
+Add the `send` method to the `ResendNotificationProviderService` class:
+
+```ts title="src/modules/resend/service.ts" highlights={serviceHighlights3}
+// other imports...
+import {
+ // ...
+ ProviderSendNotificationDTO,
+ ProviderSendNotificationResultsDTO,
+} from "@medusajs/framework/types"
+import {
+ // ...
+ CreateEmailOptions,
+} from "resend"
+
+class ResendNotificationProviderService extends AbstractNotificationProviderService {
+ // ...
+ async send(
+ notification: ProviderSendNotificationDTO
+ ): Promise {
+ const template = this.getTemplate(notification.template as Templates)
+
+ if (!template) {
+ this.logger.error(`Couldn't find an email template for ${notification.template}. The valid options are ${Object.values(Templates)}`)
+ return {}
+ }
+
+ const emailOptions: CreateEmailOptions = {
+ from: this.options.from,
+ to: [notification.to],
+ subject: this.getTemplateSubject(notification.template as Templates),
+ html: "",
+ }
+
+ if (typeof template === "string") {
+ emailOptions.html = template
+ } else {
+ emailOptions.react = template(notification.data)
+ delete emailOptions.html
+ }
+
+ const { data, error } = await this.resendClient.emails.send(emailOptions)
+
+ if (error) {
+ this.logger.error(`Failed to send email`, error)
+ return {}
+ }
+
+ return { id: data.id }
+ }
+}
+```
+
+The `send` method receives the notification details object as a parameter. Some of its properties include:
+
+- `to`: The address to send the notification to.
+- `template`: The template type of the notification.
+- `data`: The data useful for the email type. For example, when sending an order-confirmation email, `data` would hold the order's details.
+
+In the method, you retrieve the template and subject of the email using the methods you defined earlier. Then, you put together the data to pass to Resend, such as the email address to send the notification to and the email address to send from. Also, if the email's template is a string, it's passed as an HTML template. Otherwise, it's passed as a React template.
+
+Finally, you use the `emails.send` method of the Resend client to send the email. If an error occurs you log it in the terminal. Otherwise, you return the ID of the send email as received from Resend. Medusa uses this ID when creating the notification in its database.
+
+### Export Module Definition
+
+The `ResendNotificationProviderService` class now has the methods necessary to start sending emails.
+
+Next, you must export the module provider's definition, which lets Medusa know what module this provider belongs to and its service.
+
+Create the file `src/modules/resend/index.ts` with the following content:
+
+```ts title="src/modules/resend/index.ts"
+import {
+ ModuleProvider,
+ Modules,
+} from "@medusajs/framework/utils"
+import ResendNotificationProviderService from "./service"
+
+export default ModuleProvider(Modules.NOTIFICATION, {
+ services: [ResendNotificationProviderService],
+})
+```
+
+You export the module provider's definition using `ModuleProvider` from the Modules SDK. It accepts as a first parameter the name of the module that this provider belongs to, which is the Notification Module. It also accepts as a second parameter an object having a `service` property indicating the provider's service.
+
+### Add Module to Configurations
+
+Finally, to register modules and module providers in Medusa, you must add them to Medusa's configurations.
+
+Medusa's configurations are set in the `medusa-config.ts` file, which is at the root directory of your Medusa application. The configuration object accepts a `modules` array, whose value is an array of modules to add to the application.
+
+Add the `modules` property to the exported configurations in `medusa-config.ts`:
+
+```ts title="medusa-config.ts"
+module.exports = defineConfig({
+ // ...
+ modules: [
+ {
+ resolve: "@medusajs/medusa/notification",
+ options: {
+ providers: [
+ {
+ resolve: "./src/modules/resend",
+ id: "resend",
+ options: {
+ channels: ["email"],
+ api_key: process.env.RESEND_API_KEY,
+ from: process.env.RESEND_FROM_EMAIL,
+ },
+ },
+ ],
+ },
+ },
+ ],
+})
+```
+
+In the `modules` array, you pass a module object having the following properties:
+
+- `resolve`: The NPM package of the Notification Module. Since the Resend Module is a Notification Module Provider, it'll be passed in the options of the Notification Module.
+- `options`: An object of options to pass to the module. It has a `providers` property which is an array of module providers to register. Each module provider object has the following properties:
+ - `resolve`: The path to the module provider to register in the application. It can also be the name of an NPM package.
+ - `id`: A unique ID, which Medusa will use along with the `identifier` static property that you set earlier in the class to identify this module provider.
+ - `options`: An object of options to pass to the module provider. These are the options you expect and use in the module provider's service. You must also specify the `channels` option, which indicates the channels that this provider sends notifications through.
+
+Some of the module's options, such as the Resend API key, are set in environment variables. So, add the following environment variables to `.env`:
+
+```shell
+RESEND_FROM_EMAIL=onboarding@resend.dev
+RESEND_API_KEY=
+```
+
+Where:
+
+- `RESEND_FROM_EMAIL`: The email to send emails from. If you've configured the custom domain as explained in [Step 2](#step-2-prepare-resend-account), change this email to an email from your custom domain. Otherwise, you can use `onboarding@resend.dev` for development purposes.
+- `RESEND_API_KEY` is the API key of your Resend account. To retrieve it:
+ - Go to API Keys in the sidebar.
+ - Click on the Create API Key button.
+
+
+
+- In the form that opens, enter a name for the API key (for example, Medusa). You can keep its permissions to Full Access or change it to Sending Access. Once you're done, click Add.
+
+
+
+- A new pop-up will show with your API key hidden. Copy it before closing the pop-up, since you can't access the key again afterwards. Use its value for the `RESEND_API_KEY` environment variable.
+
+
+
+Your Resend Module Provider is all set up. You'll test it out in a later section.
+
+***
+
+## Step 5: Add Order Confirmation Template
+
+In this step, you'll add a React template for order confirmation emails. You'll create it using the [react-email](https://github.com/resend/react-email) package you installed earlier. You can follow the same steps for other email templates, such as for customer confirmation.
+
+Create the directory `src/modules/resend/emails` that will hold the email templates. Then, to add the template for order confirmation, create the file `src/modules/resend/emails/order-placed.tsx` with the following content:
+
+```tsx title="src/modules/resend/emails/order-placed.tsx" highlights={templateHighlights}
+import { Text, Column, Container, Heading, Html, Img, Row, Section } from "@react-email/components"
+import { BigNumberValue, OrderDTO } from "@medusajs/framework/types"
+
+type OrderPlacedEmailProps = {
+ order: OrderDTO
+}
+
+function OrderPlacedEmailComponent({ order }: OrderPlacedEmailProps) {
+ const formatter = new Intl.NumberFormat([], {
+ style: "currency",
+ currencyDisplay: "narrowSymbol",
+ currency: order.currency_code,
+ })
+
+ const formatPrice = (price: BigNumberValue) => {
+ if (typeof price === "number") {
+ return formatter.format(price)
+ }
+
+ if (typeof price === "string") {
+ return formatter.format(parseFloat(price))
+ }
+
+ return price?.toString() || ""
+ }
+
+ return (
+
+ Thank you for your order
+ {order.email}'s Items
+
+ {order.items.map((item) => {
+ return (
+
+
+
+
+
+
+
+ {item.product_title}
+
+ {item.variant_title}
+ {formatPrice(item.total)}
+
+
+
+ )
+ })}
+
+
+ )
+}
+
+export const orderPlacedEmail = (props: OrderPlacedEmailProps) => (
+
+)
+```
+
+You define the `OrderPlacedEmailComponent` which is a React email template that shows the order's details, such as items and their totals. The component accepts an `order` object as a prop.
+
+You also export an `orderPlacedEmail` function, which accepts props as an input and returns the `OrderPlacedEmailComponent` passing it the props. Because you can't use JSX syntax in `src/modules/resend/service.ts`, you'll import this function instead.
+
+Next, update the `templates` variable in `src/modules/resend/service.ts` to assign this template to the `order-placed` template type:
+
+```ts title="src/modules/resend/service.ts"
+// other imports...
+import { orderPlacedEmail } from "./emails/order-placed"
+
+const templates: {[key in Templates]?: (props: unknown) => React.ReactNode} = {
+ [Templates.ORDER_PLACED]: orderPlacedEmail,
+}
+```
+
+The `ResendNotificationProviderService` will now use the `OrderPlacedEmailComponent` as the template of order confirmation emails.
+
+***
+
+## Step 6: Send Email when Order is Placed
+
+Medusa has an event system that emits an event when a commerce operation is performed. You can then listen and handle that event in an asynchronous function called a subscriber.
+
+So, to send a confirmation email when a customer places an order, which is a commerce operation that Medusa already implements, you don't need to extend or hack your way into Medusa's implementation as you would do with other commerce platforms.
+
+Instead, you'll create a subscriber that listens to the `order.placed` event and sends an email when the event is emitted.
+
+Learn more about Medusa's event system in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/events-and-subscribers/index.html.md).
+
+### Send Order Confirmation Email Workflow
+
+To send the order confirmation email, you need to retrieve the order's details first, then use the Notification Module's service to send the email. To implement this flow, you'll create a workflow.
+
+A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it's a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in a subscriber.
+
+Learn more about workflows in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md)
+
+#### Send Notification Step
+
+You'll start by implementing the step of the workflow that sends the notification. To do that, create the file `src/workflows/steps/send-notification.ts` with the following content:
+
+```ts title="src/workflows/steps/send-notification.ts"
+import { Modules } from "@medusajs/framework/utils"
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { CreateNotificationDTO } from "@medusajs/framework/types"
+
+export const sendNotificationStep = createStep(
+ "send-notification",
+ async (data: CreateNotificationDTO[], { container }) => {
+ const notificationModuleService = container.resolve(
+ Modules.NOTIFICATION
+ )
+ const notification = await notificationModuleService.createNotifications(data)
+ return new StepResponse(notification)
+ }
+)
+```
+
+You define the `sendNotificationStep` using the `createStep` function that accepts two parameters:
+
+- A string indicating the step's unique name.
+- The step's function definition as a second parameter. It accepts the step's input as a first parameter, and an object of options as a second.
+
+The `container` property in the second parameter is an instance of the [Medusa container](https://docs.medusajs.com/docs/learn/fundamentals/medusa-container/index.html.md), which is a registry of framework and commerce tools, such a module's service, that you can resolve to utilize their functionalities.
+
+The Medusa container is accessible by all customizations, such as workflows and subscribers, except for modules. Each module has its own container with framework tools like the Logger utility.
+
+In the step function, you resolve the Notification Module's service, and use its `createNotifications` method, passing it the notification's data that the step receives as an input.
+
+The step returns an instance of `StepResponse`, which must be returned by any step. It accepts as a parameter the data to return to the workflow that executed this step.
+
+#### Workflow Implementation
+
+You'll now create the workflow that uses the `sendNotificationStep` to send the order confirmation email.
+
+Create the file `src/workflows/send-order-confirmation.ts` with the following content:
+
+```ts title="src/workflows/send-order-confirmation.ts" highlights={workflowHighlights}
+import {
+ createWorkflow,
+ WorkflowResponse,
+} from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { sendNotificationStep } from "./steps/send-notification"
+
+type WorkflowInput = {
+ id: string
+}
+
+export const sendOrderConfirmationWorkflow = createWorkflow(
+ "send-order-confirmation",
+ ({ id }: WorkflowInput) => {
+ // @ts-ignore
+ const { data: orders } = useQueryGraphStep({
+ entity: "order",
+ fields: [
+ "id",
+ "email",
+ "currency_code",
+ "total",
+ "items.*",
+ ],
+ filters: {
+ id,
+ },
+ })
+
+ const notification = sendNotificationStep([{
+ to: orders[0].email,
+ channel: "email",
+ template: "order-placed",
+ data: {
+ order: orders[0],
+ },
+ }])
+
+ return new WorkflowResponse(notification)
+ }
+)
+```
+
+You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
+
+It accepts as a second parameter a constructor function, which is the workflow's implementation. The workflow has the following steps:
+
+1. `useQueryGraphStep`, which is a step implemented by Medusa that uses [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), a tool that allows you to retrieve data across modules. You use it to retrieve the order's details.
+2. `sendNotificationStep` which is the step you implemented. You pass it an array with one object, which is the notification's details having following properties:
+ - `to`: The address to send the email to. You pass the customer's email that is stored in the order.
+ - `channel`: The channel to send the notification through, which is `email`. Since you specified `email` in the Resend Module Provider's `channel` option, the Notification Module will delegate the sending to the Resend Module Provider's service.
+ - `template`: The email's template type. You retrieve the template content in the `ResendNotificationProviderService`'s `send` method based on the template specified here.
+ - `data`: The data to pass to the email template, which is the order's details.
+
+A workflow's constructor function has some constraints in implementation. Learn more about them in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/constructor-constraints/index.html.md).
+
+You'll execute the workflow when you create the subscriber next.
+
+#### Add the Order Placed Subscriber
+
+Now that you have the workflow to send an order-confirmation email, you'll execute it in a subscriber that's executed whenever an order is placed.
+
+You create a subscriber in a TypeScript or JavaScript file under the `src/subscribers` directory. So, create the file `src/subscribers/order-placed.ts` with the following content:
+
+```ts title="src/subscribers/order-placed.ts" highlights={subscriberHighlights}
+import type {
+ SubscriberArgs,
+ SubscriberConfig,
+} from "@medusajs/framework"
+import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"
+
+export default async function orderPlacedHandler({
+ event: { data },
+ container,
+}: SubscriberArgs<{ id: string }>) {
+ await sendOrderConfirmationWorkflow(container)
+ .run({
+ input: {
+ id: data.id,
+ },
+ })
+}
+
+export const config: SubscriberConfig = {
+ event: "order.placed",
+}
+```
+
+A subscriber file exports:
+
+- An asynchronous function that's executed whenever the associated event is emitted, which is the `order.placed` event.
+- A configuration object with an `event` property indicating the event the subscriber is listening to.
+
+The subscriber function accepts the event's details as a first paramter which has a `data` property that holds the data payload of the event. For example, Medusa emits the `order.placed` event with the order's ID in the data payload. The function also accepts as a second parameter the [Medusa container](https://docs.medusajs.com/docs/learn/fundamentals/medusa-container/index.html.md).
+
+In the function, you execute the `sendOrderConfirmationWorkflow` by invoking it, passing it the `container`, then using its `run` method. The `run` method accepts an object having an `input` property, which is the input to pass to the workflow. You pass the ID of the placed order as received in the event's data payload.
+
+This subscriber now runs whenever an order is placed. You'll see this in action in the next section.
+
+***
+
+## Test it Out: Place an Order
+
+To test out the Resend integration, you'll place an order using the [Next.js storefront](https://docs.medusajs.com/docs/learn/storefront-development/nextjs-starter/index.html.md) that you installed as part of installing Medusa.
+
+Start your Medusa application first:
+
+```bash npm2yarn
+npm run dev
+```
+
+Then, in the Next.js storefront's directory (which was installed in a directory outside of the Medusa application's directory with the name `{project-name}-storefront`, where `{project-name}` is the name of the Medusa application's directory), run the following command to start the storefront:
+
+```bash npm2yarn
+npm run dev
+```
+
+Then, open the storefront in your browser at `http://localhost:8000` and:
+
+1. Go to Menu -> Store.
+
+
+
+2\. Click on a product, select its options, and add it to the cart.
+
+
+
+3\. Click on Cart at the top right, then click Go to Cart.
+
+
+
+4\. On the cart's page, click on the "Go to checkout" button.
+
+
+
+5\. On the checkout page, when entering the shipping address, make sure to set the email to your Resend account's email if you didn't set up a custom domain.
+
+
+
+6\. After entering the shipping address, choose a delivery and payment methods, then click the Place Order button.
+
+Once the order is placed, you'll find the following message logged in the Medusa application's terminal:
+
+```bash
+info: Processing order.placed which has 1 subscribers
+```
+
+This indicates that the `order.placed` event was emitted and its subscriber, which you added in the previous step, is executed.
+
+If you check the inbox of the email address you specified in the shipping address, you'll find a new email with the order's details.
+
+
+
+***
+
+## Next Steps
+
+You've now integrated Medusa with Resend. You can add more templates for other emails, such as customer registration confirmation, user invites, and more. Check out the [Events Reference](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/events-reference/index.html.md) for a list of all events that the Medusa application emits.
+
+If you're new to Medusa, check out the [main documentation](https://docs.medusajs.com/docs/learn/index.html.md), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
+
+To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
+
+
# Integrate Medusa with Sanity (CMS)
In this guide, you'll learn how to integrate Medusa with Sanity.
@@ -47542,757 +48006,6 @@ If you're new to Medusa, check out the [main documentation](https://docs.medusaj
To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
-# Integrate Medusa with Resend (Email Notifications)
-
-In this guide, you'll learn how to integrate Medusa with Resend.
-
-When you install a Medusa application, you get a fully-fledged commerce platform with a framework for customization. Medusa's architecture supports integrating third-party services, such as an email service, that allow you to build your unique requirements around core commerce flows.
-
-[Resend](https://resend.com/docs/introduction) is an email service with an intuitive developer experience to send emails from any application type, including Node.js servers. By integrating Resend with Medusa, you can build flows to send an email when a commerce operation is performed, such as when an order is placed.
-
-This guide will teach you how to:
-
-- Install and set up Medusa.
-- Integrate Resend into Medusa for sending emails.
-- Build a flow to send an email with Resend when a customer places an order.
-
-You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
-
-[Example Repository](https://github.com/medusajs/examples/tree/main/resend-integration): Find the full code of the guide in this repository.
-
-***
-
-## Step 1: Install a Medusa Application
-
-### Prerequisites
-
-- [Node.js v20+](https://nodejs.org/en/download)
-- [Git CLI tool](https://git-scm.com/downloads)
-- [PostgreSQL](https://www.postgresql.org/download/)
-
-Start by installing the Medusa application on your machine with the following command:
-
-```bash
-npx create-medusa-app@latest
-```
-
-You'll first be asked for the project's name. Then, when you're asked whether you want to install the Next.js storefront, choose `Y` for yes.
-
-Afterwards, the installation process will start, which will install the Medusa application in a directory with your project's name, and the Next.js storefront in a directory with the `{project-name}-storefront` name.
-
-The Medusa application is composed of a headless Node.js server and an admin dashboard. The storefront is installed or custom-built separately and connects to the Medusa application through its REST endpoints, called [API routes](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md). Learn more about Medusa's architecture in [this documentation](https://docs.medusajs.com/docs/learn/introduction/architecture/index.html.md).
-
-Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credential and submit the form. Afterwards, you can login with the new user and explore the dashboard.
-
-The Next.js storefront is also running at `http://localhost:8000`.
-
-Check out the [troubleshooting guides](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/troubleshooting/create-medusa-app-errors/index.html.md) for help.
-
-***
-
-## Step 2: Prepare Resend Account
-
-If you don't have a Resend Account, create one on [their website](https://resend.com/emails).
-
-In addition, Resend allows you to send emails from the address `onboarding@resend.dev` only to your account's email, which is useful for development purposes. If you have a custom domain to send emails from, add it to your Resend account's domains:
-
-1. Go to Domains from the sidebar.
-2. Click on Add Domain.
-
-
-
-3\. In the form that opens, enter your domain name and select a region close to your users, then click Add.
-
-
-
-4\. In the domain's details page that opens, you'll find DNS records to add to your DNS provider. After you add them, click on Verify DNS Records. You can start sending emails from your custom domain once it's verified.
-
-The steps to add DNS records are different for each provider, so refer to your provider's documentation or knowledge base for more details.
-
-
-
-You also need an API key to connect to your Resend account from Medusa, but you'll create that one in a later section.
-
-***
-
-## Step 3: Install Resend Dependencies
-
-In this step, you'll install two packages useful for your Resend integration:
-
-1. `resend`, which is the Resend SDK:
-
-```bash npm2yarn
-npm install resend
-```
-
-2\. [react-email](https://github.com/resend/react-email), which is a package created by Resend to create email templates with React:
-
-```bash npm2yarn
-npm install @react-email/components -E
-```
-
-You'll use these packages in the next steps.
-
-***
-
-## Step 4: Create Resend Module Provider
-
-To integrate third-party services into Medusa, you create a custom module. A module is a re-usable package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
-
-Medusa's Notification Module delegates sending notifications to other modules, called module providers. In this step, you'll create a Resend Module Provider that implements sending notifications through the email channel. In later steps, you'll send email notifications with Resend when an order is placed through this provider.
-
-Learn more about modules in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md).
-
-### Create Module Directory
-
-A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/resend`.
-
-### Create Service
-
-You define a module's functionalities in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to the database, which is useful if your module defines tables in the database, or connect to a third-party service.
-
-In this section, you'll create the Resend Module Provider's service and the methods necessary to send an email with Resend.
-
-Start by creating the file `src/modules/resend/service.ts` with the following content:
-
-```ts title="src/modules/resend/service.ts" highlights={serviceHighlights1}
-import {
- AbstractNotificationProviderService,
-} from "@medusajs/framework/utils"
-import {
- Logger,
-} from "@medusajs/framework/types"
-import {
- Resend,
-} from "resend"
-
-type ResendOptions = {
- api_key: string
- from: string
- html_templates?: Record
-}
-
-class ResendNotificationProviderService extends AbstractNotificationProviderService {
- static identifier = "notification-resend"
- private resendClient: Resend
- private options: ResendOptions
- private logger: Logger
-
- // ...
-}
-
-export default ResendNotificationProviderService
-```
-
-A Notification Module Provider's service must extend the `AbstractNotificationProviderService`. It has a `send` method that you'll implement soon. The service must also have an `identifier` static property, which is a unique identifier that the Medusa application will use to register the provider in the database.
-
-The `ResendNotificationProviderService` class also has the following properties:
-
-- `resendClient` of type `Resend` (from the Resend SDK you installed in the previous step) to send emails through Resend.
-- `options` of type `ResendOptions`. Modules accept options through Medusa's configurations. This ensures that the module is reusable across applications and you don't use sensitive variables like API keys directly in your code. The options that the Resend Module Provider accepts are:
- - `api_key`: The Resend API key.
- - `from`: The email address to send the emails from.
- - `html_templates`: An optional object to replace the default subject and template that the Resend Module uses. This is also useful to support custom emails in different Medusa application setups.
-- `logger` property, which is an instance of Medusa's [Logger](https://docs.medusajs.com/docs/learn/debugging-and-testing/logging/index.html.md), to log messages.
-
-To send requests using the `resendClient`, you need to initialize it in the class's constructor. So, add the following constructor to `ResendNotificationProviderService`:
-
-```ts title="src/modules/resend/service.ts"
-// ...
-
-type InjectedDependencies = {
- logger: Logger
-}
-
-class ResendNotificationProviderService extends AbstractNotificationProviderService {
- // ...
- constructor(
- { logger }: InjectedDependencies,
- options: ResendOptions
- ) {
- super()
- this.resendClient = new Resend(options.api_key)
- this.options = options
- this.logger = logger
- }
-}
-```
-
-A module's service accepts two parameters:
-
-1. Dependencies resolved from the [Module's container](https://docs.medusajs.com/docs/learn/fundamentals/modules/container/index.html.md), which is the module's local registry that the Medusa application adds framework tools to. In this service, you resolve the [Logger utility](https://docs.medusajs.com/docs/learn/debugging-and-testing/logging/index.html.md) from the module's container.
-2. The module's options that are passed to the module in Medusa's configuration as you'll see in a later section.
-
-Using the API key passed in the module's options, you initialize the Resend client. You also set the `options` and `logger` properties.
-
-#### Validate Options Method
-
-A Notification Module Provider's service can implement a static `validateOptions` method that ensures the options passed to the module through Medusa's configurations are valid.
-
-So, add to the `ResendNotificationProviderService` the `validateOptions` method:
-
-```ts title="src/modules/resend/service.ts"
-// other imports...
-import {
- // other imports...
- MedusaError,
-} from "@medusajs/framework/utils"
-
-// ...
-
-class ResendNotificationProviderService extends AbstractNotificationProviderService {
- // ...
- static validateOptions(options: Record) {
- if (!options.api_key) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- "Option `api_key` is required in the provider's options."
- )
- }
- if (!options.from) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- "Option `from` is required in the provider's options."
- )
- }
- }
-}
-```
-
-In the `validateOptions` method, you throw an error if the `api_key` or `from` options aren't passed to the module. To throw errors, you use `MedusaError` from the Modules SDK. This ensures errors follow Medusa's conventions and are displayed similar to Medusa's errors.
-
-#### Implement Template Methods
-
-Each email type has a different template and content. For example, order confirmation emails show the order's details, whereas customer confirmation emails show a greeting message to the customer.
-
-So, add two methods to the `ResendNotificationProviderService` class that retrieve the email template and subject of a specified template type:
-
-```ts title="src/modules/resend/service.ts" highlights={serviceHighlights2}
-// imports and types...
-
-enum Templates {
- ORDER_PLACED = "order-placed",
-}
-
-const templates: {[key in Templates]?: (props: unknown) => React.ReactNode} = {
- // TODO add templates
-}
-
-class ResendNotificationProviderService extends AbstractNotificationProviderService {
- // ...
- getTemplate(template: Templates) {
- if (this.options.html_templates?.[template]) {
- return this.options.html_templates[template].content
- }
- const allowedTemplates = Object.keys(templates)
-
- if (!allowedTemplates.includes(template)) {
- return null
- }
-
- return templates[template]
- }
-
- getTemplateSubject(template: Templates) {
- if (this.options.html_templates?.[template]?.subject) {
- return this.options.html_templates[template].subject
- }
- switch(template) {
- case Templates.ORDER_PLACED:
- return "Order Confirmation"
- default:
- return "New Email"
- }
- }
-}
-```
-
-You first define a `Templates` enum, which holds the names of supported template types. You can add more template types to this enum later. You also define a `templates` variable that specifies the React template for each template type. You'll add templates to this variable later.
-
-In the `ResendNotificationProviderService` you add two methods:
-
-- `getTemplate`: Retrieve the template of a template type. If the `html_templates` option is set for the specified template type, you return its `content`'s value. Otherwise, you retrieve the template from the `templates` variable.
-- `getTemplateSubject`: Retrieve the subject of a template type. If a `subject` is passed for the template type in the `html_templates`, you return its value. Otherwise, you return a subject based on the template type.
-
-You'll use these methods in the `send` method next.
-
-#### Implement Send Method
-
-In this section, you'll implement the `send` method of `ResendNotificationProviderService`. When you send a notification through the email channel later using the Notification Module, the Notification Module's service will use this `send` method under the hood to send the email with Resend.
-
-In the `send` method, you'll retrieve the template and subject of the email template, then send the email using the Resend client.
-
-Add the `send` method to the `ResendNotificationProviderService` class:
-
-```ts title="src/modules/resend/service.ts" highlights={serviceHighlights3}
-// other imports...
-import {
- // ...
- ProviderSendNotificationDTO,
- ProviderSendNotificationResultsDTO,
-} from "@medusajs/framework/types"
-import {
- // ...
- CreateEmailOptions,
-} from "resend"
-
-class ResendNotificationProviderService extends AbstractNotificationProviderService {
- // ...
- async send(
- notification: ProviderSendNotificationDTO
- ): Promise {
- const template = this.getTemplate(notification.template as Templates)
-
- if (!template) {
- this.logger.error(`Couldn't find an email template for ${notification.template}. The valid options are ${Object.values(Templates)}`)
- return {}
- }
-
- const emailOptions: CreateEmailOptions = {
- from: this.options.from,
- to: [notification.to],
- subject: this.getTemplateSubject(notification.template as Templates),
- html: "",
- }
-
- if (typeof template === "string") {
- emailOptions.html = template
- } else {
- emailOptions.react = template(notification.data)
- delete emailOptions.html
- }
-
- const { data, error } = await this.resendClient.emails.send(emailOptions)
-
- if (error) {
- this.logger.error(`Failed to send email`, error)
- return {}
- }
-
- return { id: data.id }
- }
-}
-```
-
-The `send` method receives the notification details object as a parameter. Some of its properties include:
-
-- `to`: The address to send the notification to.
-- `template`: The template type of the notification.
-- `data`: The data useful for the email type. For example, when sending an order-confirmation email, `data` would hold the order's details.
-
-In the method, you retrieve the template and subject of the email using the methods you defined earlier. Then, you put together the data to pass to Resend, such as the email address to send the notification to and the email address to send from. Also, if the email's template is a string, it's passed as an HTML template. Otherwise, it's passed as a React template.
-
-Finally, you use the `emails.send` method of the Resend client to send the email. If an error occurs you log it in the terminal. Otherwise, you return the ID of the send email as received from Resend. Medusa uses this ID when creating the notification in its database.
-
-### Export Module Definition
-
-The `ResendNotificationProviderService` class now has the methods necessary to start sending emails.
-
-Next, you must export the module provider's definition, which lets Medusa know what module this provider belongs to and its service.
-
-Create the file `src/modules/resend/index.ts` with the following content:
-
-```ts title="src/modules/resend/index.ts"
-import {
- ModuleProvider,
- Modules,
-} from "@medusajs/framework/utils"
-import ResendNotificationProviderService from "./service"
-
-export default ModuleProvider(Modules.NOTIFICATION, {
- services: [ResendNotificationProviderService],
-})
-```
-
-You export the module provider's definition using `ModuleProvider` from the Modules SDK. It accepts as a first parameter the name of the module that this provider belongs to, which is the Notification Module. It also accepts as a second parameter an object having a `service` property indicating the provider's service.
-
-### Add Module to Configurations
-
-Finally, to register modules and module providers in Medusa, you must add them to Medusa's configurations.
-
-Medusa's configurations are set in the `medusa-config.ts` file, which is at the root directory of your Medusa application. The configuration object accepts a `modules` array, whose value is an array of modules to add to the application.
-
-Add the `modules` property to the exported configurations in `medusa-config.ts`:
-
-```ts title="medusa-config.ts"
-module.exports = defineConfig({
- // ...
- modules: [
- {
- resolve: "@medusajs/medusa/notification",
- options: {
- providers: [
- {
- resolve: "./src/modules/resend",
- id: "resend",
- options: {
- channels: ["email"],
- api_key: process.env.RESEND_API_KEY,
- from: process.env.RESEND_FROM_EMAIL,
- },
- },
- ],
- },
- },
- ],
-})
-```
-
-In the `modules` array, you pass a module object having the following properties:
-
-- `resolve`: The NPM package of the Notification Module. Since the Resend Module is a Notification Module Provider, it'll be passed in the options of the Notification Module.
-- `options`: An object of options to pass to the module. It has a `providers` property which is an array of module providers to register. Each module provider object has the following properties:
- - `resolve`: The path to the module provider to register in the application. It can also be the name of an NPM package.
- - `id`: A unique ID, which Medusa will use along with the `identifier` static property that you set earlier in the class to identify this module provider.
- - `options`: An object of options to pass to the module provider. These are the options you expect and use in the module provider's service. You must also specify the `channels` option, which indicates the channels that this provider sends notifications through.
-
-Some of the module's options, such as the Resend API key, are set in environment variables. So, add the following environment variables to `.env`:
-
-```shell
-RESEND_FROM_EMAIL=onboarding@resend.dev
-RESEND_API_KEY=
-```
-
-Where:
-
-- `RESEND_FROM_EMAIL`: The email to send emails from. If you've configured the custom domain as explained in [Step 2](#step-2-prepare-resend-account), change this email to an email from your custom domain. Otherwise, you can use `onboarding@resend.dev` for development purposes.
-- `RESEND_API_KEY` is the API key of your Resend account. To retrieve it:
- - Go to API Keys in the sidebar.
- - Click on the Create API Key button.
-
-
-
-- In the form that opens, enter a name for the API key (for example, Medusa). You can keep its permissions to Full Access or change it to Sending Access. Once you're done, click Add.
-
-
-
-- A new pop-up will show with your API key hidden. Copy it before closing the pop-up, since you can't access the key again afterwards. Use its value for the `RESEND_API_KEY` environment variable.
-
-
-
-Your Resend Module Provider is all set up. You'll test it out in a later section.
-
-***
-
-## Step 5: Add Order Confirmation Template
-
-In this step, you'll add a React template for order confirmation emails. You'll create it using the [react-email](https://github.com/resend/react-email) package you installed earlier. You can follow the same steps for other email templates, such as for customer confirmation.
-
-Create the directory `src/modules/resend/emails` that will hold the email templates. Then, to add the template for order confirmation, create the file `src/modules/resend/emails/order-placed.tsx` with the following content:
-
-```tsx title="src/modules/resend/emails/order-placed.tsx" highlights={templateHighlights}
-import { Text, Column, Container, Heading, Html, Img, Row, Section } from "@react-email/components"
-import { BigNumberValue, OrderDTO } from "@medusajs/framework/types"
-
-type OrderPlacedEmailProps = {
- order: OrderDTO
-}
-
-function OrderPlacedEmailComponent({ order }: OrderPlacedEmailProps) {
- const formatter = new Intl.NumberFormat([], {
- style: "currency",
- currencyDisplay: "narrowSymbol",
- currency: order.currency_code,
- })
-
- const formatPrice = (price: BigNumberValue) => {
- if (typeof price === "number") {
- return formatter.format(price)
- }
-
- if (typeof price === "string") {
- return formatter.format(parseFloat(price))
- }
-
- return price?.toString() || ""
- }
-
- return (
-
- Thank you for your order
- {order.email}'s Items
-
- {order.items.map((item) => {
- return (
-
-
-
-
-
-
-
- {item.product_title}
-
- {item.variant_title}
- {formatPrice(item.total)}
-
-
-
- )
- })}
-
-
- )
-}
-
-export const orderPlacedEmail = (props: OrderPlacedEmailProps) => (
-
-)
-```
-
-You define the `OrderPlacedEmailComponent` which is a React email template that shows the order's details, such as items and their totals. The component accepts an `order` object as a prop.
-
-You also export an `orderPlacedEmail` function, which accepts props as an input and returns the `OrderPlacedEmailComponent` passing it the props. Because you can't use JSX syntax in `src/modules/resend/service.ts`, you'll import this function instead.
-
-Next, update the `templates` variable in `src/modules/resend/service.ts` to assign this template to the `order-placed` template type:
-
-```ts title="src/modules/resend/service.ts"
-// other imports...
-import { orderPlacedEmail } from "./emails/order-placed"
-
-const templates: {[key in Templates]?: (props: unknown) => React.ReactNode} = {
- [Templates.ORDER_PLACED]: orderPlacedEmail,
-}
-```
-
-The `ResendNotificationProviderService` will now use the `OrderPlacedEmailComponent` as the template of order confirmation emails.
-
-***
-
-## Step 6: Send Email when Order is Placed
-
-Medusa has an event system that emits an event when a commerce operation is performed. You can then listen and handle that event in an asynchronous function called a subscriber.
-
-So, to send a confirmation email when a customer places an order, which is a commerce operation that Medusa already implements, you don't need to extend or hack your way into Medusa's implementation as you would do with other commerce platforms.
-
-Instead, you'll create a subscriber that listens to the `order.placed` event and sends an email when the event is emitted.
-
-Learn more about Medusa's event system in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/events-and-subscribers/index.html.md).
-
-### Send Order Confirmation Email Workflow
-
-To send the order confirmation email, you need to retrieve the order's details first, then use the Notification Module's service to send the email. To implement this flow, you'll create a workflow.
-
-A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it's a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in a subscriber.
-
-Learn more about workflows in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md)
-
-#### Send Notification Step
-
-You'll start by implementing the step of the workflow that sends the notification. To do that, create the file `src/workflows/steps/send-notification.ts` with the following content:
-
-```ts title="src/workflows/steps/send-notification.ts"
-import { Modules } from "@medusajs/framework/utils"
-import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
-import { CreateNotificationDTO } from "@medusajs/framework/types"
-
-export const sendNotificationStep = createStep(
- "send-notification",
- async (data: CreateNotificationDTO[], { container }) => {
- const notificationModuleService = container.resolve(
- Modules.NOTIFICATION
- )
- const notification = await notificationModuleService.createNotifications(data)
- return new StepResponse(notification)
- }
-)
-```
-
-You define the `sendNotificationStep` using the `createStep` function that accepts two parameters:
-
-- A string indicating the step's unique name.
-- The step's function definition as a second parameter. It accepts the step's input as a first parameter, and an object of options as a second.
-
-The `container` property in the second parameter is an instance of the [Medusa container](https://docs.medusajs.com/docs/learn/fundamentals/medusa-container/index.html.md), which is a registry of framework and commerce tools, such a module's service, that you can resolve to utilize their functionalities.
-
-The Medusa container is accessible by all customizations, such as workflows and subscribers, except for modules. Each module has its own container with framework tools like the Logger utility.
-
-In the step function, you resolve the Notification Module's service, and use its `createNotifications` method, passing it the notification's data that the step receives as an input.
-
-The step returns an instance of `StepResponse`, which must be returned by any step. It accepts as a parameter the data to return to the workflow that executed this step.
-
-#### Workflow Implementation
-
-You'll now create the workflow that uses the `sendNotificationStep` to send the order confirmation email.
-
-Create the file `src/workflows/send-order-confirmation.ts` with the following content:
-
-```ts title="src/workflows/send-order-confirmation.ts" highlights={workflowHighlights}
-import {
- createWorkflow,
- WorkflowResponse,
-} from "@medusajs/framework/workflows-sdk"
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-import { sendNotificationStep } from "./steps/send-notification"
-
-type WorkflowInput = {
- id: string
-}
-
-export const sendOrderConfirmationWorkflow = createWorkflow(
- "send-order-confirmation",
- ({ id }: WorkflowInput) => {
- // @ts-ignore
- const { data: orders } = useQueryGraphStep({
- entity: "order",
- fields: [
- "id",
- "email",
- "currency_code",
- "total",
- "items.*",
- ],
- filters: {
- id,
- },
- })
-
- const notification = sendNotificationStep([{
- to: orders[0].email,
- channel: "email",
- template: "order-placed",
- data: {
- order: orders[0],
- },
- }])
-
- return new WorkflowResponse(notification)
- }
-)
-```
-
-You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
-
-It accepts as a second parameter a constructor function, which is the workflow's implementation. The workflow has the following steps:
-
-1. `useQueryGraphStep`, which is a step implemented by Medusa that uses [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), a tool that allows you to retrieve data across modules. You use it to retrieve the order's details.
-2. `sendNotificationStep` which is the step you implemented. You pass it an array with one object, which is the notification's details having following properties:
- - `to`: The address to send the email to. You pass the customer's email that is stored in the order.
- - `channel`: The channel to send the notification through, which is `email`. Since you specified `email` in the Resend Module Provider's `channel` option, the Notification Module will delegate the sending to the Resend Module Provider's service.
- - `template`: The email's template type. You retrieve the template content in the `ResendNotificationProviderService`'s `send` method based on the template specified here.
- - `data`: The data to pass to the email template, which is the order's details.
-
-A workflow's constructor function has some constraints in implementation. Learn more about them in [this documentation](https://docs.medusajs.com/docs/learn/fundamentals/workflows/constructor-constraints/index.html.md).
-
-You'll execute the workflow when you create the subscriber next.
-
-#### Add the Order Placed Subscriber
-
-Now that you have the workflow to send an order-confirmation email, you'll execute it in a subscriber that's executed whenever an order is placed.
-
-You create a subscriber in a TypeScript or JavaScript file under the `src/subscribers` directory. So, create the file `src/subscribers/order-placed.ts` with the following content:
-
-```ts title="src/subscribers/order-placed.ts" highlights={subscriberHighlights}
-import type {
- SubscriberArgs,
- SubscriberConfig,
-} from "@medusajs/framework"
-import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"
-
-export default async function orderPlacedHandler({
- event: { data },
- container,
-}: SubscriberArgs<{ id: string }>) {
- await sendOrderConfirmationWorkflow(container)
- .run({
- input: {
- id: data.id,
- },
- })
-}
-
-export const config: SubscriberConfig = {
- event: "order.placed",
-}
-```
-
-A subscriber file exports:
-
-- An asynchronous function that's executed whenever the associated event is emitted, which is the `order.placed` event.
-- A configuration object with an `event` property indicating the event the subscriber is listening to.
-
-The subscriber function accepts the event's details as a first paramter which has a `data` property that holds the data payload of the event. For example, Medusa emits the `order.placed` event with the order's ID in the data payload. The function also accepts as a second parameter the [Medusa container](https://docs.medusajs.com/docs/learn/fundamentals/medusa-container/index.html.md).
-
-In the function, you execute the `sendOrderConfirmationWorkflow` by invoking it, passing it the `container`, then using its `run` method. The `run` method accepts an object having an `input` property, which is the input to pass to the workflow. You pass the ID of the placed order as received in the event's data payload.
-
-This subscriber now runs whenever an order is placed. You'll see this in action in the next section.
-
-***
-
-## Test it Out: Place an Order
-
-To test out the Resend integration, you'll place an order using the [Next.js storefront](https://docs.medusajs.com/docs/learn/storefront-development/nextjs-starter/index.html.md) that you installed as part of installing Medusa.
-
-Start your Medusa application first:
-
-```bash npm2yarn
-npm run dev
-```
-
-Then, in the Next.js storefront's directory (which was installed in a directory outside of the Medusa application's directory with the name `{project-name}-storefront`, where `{project-name}` is the name of the Medusa application's directory), run the following command to start the storefront:
-
-```bash npm2yarn
-npm run dev
-```
-
-Then, open the storefront in your browser at `http://localhost:8000` and:
-
-1. Go to Menu -> Store.
-
-
-
-2\. Click on a product, select its options, and add it to the cart.
-
-
-
-3\. Click on Cart at the top right, then click Go to Cart.
-
-
-
-4\. On the cart's page, click on the "Go to checkout" button.
-
-
-
-5\. On the checkout page, when entering the shipping address, make sure to set the email to your Resend account's email if you didn't set up a custom domain.
-
-
-
-6\. After entering the shipping address, choose a delivery and payment methods, then click the Place Order button.
-
-Once the order is placed, you'll find the following message logged in the Medusa application's terminal:
-
-```bash
-info: Processing order.placed which has 1 subscribers
-```
-
-This indicates that the `order.placed` event was emitted and its subscriber, which you added in the previous step, is executed.
-
-If you check the inbox of the email address you specified in the shipping address, you'll find a new email with the order's details.
-
-
-
-***
-
-## Next Steps
-
-You've now integrated Medusa with Resend. You can add more templates for other emails, such as customer registration confirmation, user invites, and more. Check out the [Events Reference](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/events-reference/index.html.md) for a list of all events that the Medusa application emits.
-
-If you're new to Medusa, check out the [main documentation](https://docs.medusajs.com/docs/learn/index.html.md), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
-
-To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
-
-
# Integrate Medusa with ShipStation (Fulfillment)
In this guide, you'll learn how to integrate Medusa with ShipStation.
@@ -49532,6 +49245,1054 @@ If you're new to Medusa, check out the [main documentation](https://docs.medusaj
To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
+# How to Build Magento Data Migration Plugin
+
+In this tutorial, you'll learn how to build a [plugin](https://docs.medusajs.com/docs/learn/fundamentals/plugins/index.html.md) that migrates data, such as products, from Magento to Medusa.
+
+Magento is known for its customization capabilities. However, its monolithic architecture imposes limitations on business requirements, often forcing development teams to implement hacky workarounds. Over time, these customizations become challenging to maintain, especially as the business scales, leading to increased technical debt and slower feature delivery.
+
+Medusa's modular architecture allows you to build a custom digital commerce platform that meets your business requirements without the limitations of a monolithic system. By migrating from Magento to Medusa, you can take advantage of Medusa's modern technology stack to build a scalable and flexible commerce platform that grows with your business.
+
+By following this tutorial, you'll create a Medusa plugin that migrates data from a Magento server to a Medusa application in minimal time. You can re-use this plugin across multiple Medusa applications, allowing you to adopt Medusa across your projects.
+
+## Summary
+
+### Prerequisites
+
+
+
+This tutorial will teach you how to:
+
+- Install and set up a Medusa application project.
+- Install and set up a Medusa plugin.
+- Implement a Magento Module in the plugin to connect to Magento's APIs and retrieve products.
+ - This guide will only focus on migrating product data from Magento to Medusa. You can extend the implementation to migrate other data, such as customers, orders, and more.
+- Trigger data migration from Magento to Medusa in a scheduled job.
+
+You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer.
+
+
+
+[Example Repository](https://github.com/medusajs/examples/tree/main/migrate-from-magento): Find the full code of the guide in this repository. The repository also includes additional features, such as triggering migrations from the Medusa Admin dashboard.
+
+***
+
+## Step 1: Install a Medusa Application
+
+You'll first install a Medusa application that exposes core commerce features through REST APIs. You'll later install the Magento plugin in this application to test it out.
+
+### Prerequisites
+
+- [Node.js v20+](https://nodejs.org/en/download)
+- [Git CLI tool](https://git-scm.com/downloads)
+- [PostgreSQL](https://www.postgresql.org/download/)
+
+Start by installing the Medusa application on your machine with the following command:
+
+```bash
+npx create-medusa-app@latest
+```
+
+You'll be asked for the project's name. You can also optionally choose to install the [Next.js starter storefront](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/nextjs-starter/index.html.md).
+
+Afterward, the installation process will start, which will install the Medusa application in a directory with your project's name. If you chose to install the Next.js starter, it'll be installed in a separate directory with the `{project-name}-storefront` name.
+
+The Medusa application is composed of a headless Node.js server and an admin dashboard. The storefront is installed or custom-built separately and connects to the Medusa application through its REST endpoints, called [API routes](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md). Refer to the [Medusa Architecture](https://docs.medusajs.com/docs/learn/introduction/architecture/index.html.md) documentation to learn more.
+
+Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterward, you can log in with the new user and explore the dashboard.
+
+Check out the [troubleshooting guides](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/troubleshooting/create-medusa-app-errors/index.html.md) for help.
+
+***
+
+## Step 2: Install a Medusa Plugin Project
+
+A plugin is a package of reusable Medusa customizations that you can install in any Medusa application. You can add in the plugin [API Routes](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md), [Workflows](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md), and other customizations, as you'll see in this guide. Afterward, you can test it out locally in a Medusa application, then publish it to npm to install and use it in any Medusa application.
+
+Refer to the [Plugins](https://docs.medusajs.com/docs/learn/fundamentals/plugins/index.html.md) documentation to learn more about plugins.
+
+A Medusa plugin is set up in a different project, giving you the flexibility in building and publishing it, while providing you with the tools to test it out locally in a Medusa application.
+
+To create a new Medusa plugin project, run the following command in a directory different than that of the Medusa application:
+
+```bash npm2yarn
+npx create-medusa-app@latest medusa-plugin-magento --plugin
+```
+
+Where `medusa-plugin-magento` is the name of the plugin's directory and the name set in the plugin's `package.json`. So, if you wish to publish it to NPM later under a different name, you can change it here in the command or later in `package.json`.
+
+Once the installation process is done, a new directory named `medusa-plugin-magento` will be created with the plugin project files.
+
+
+
+***
+
+## Step 3: Set up Plugin in Medusa Application
+
+Before you start your development, you'll set up the plugin in the Medusa application you installed in the first step. This will allow you to test the plugin during your development process.
+
+In the plugin's directory, run the following command to publish the plugin to the local package registry:
+
+```bash title="Plugin project"
+npx medusa plugin:publish
+```
+
+This command uses [Yalc](https://github.com/wclr/yalc) under the hood to publish the plugin to a local package registry. The plugin is published locally under the name you specified in `package.json`.
+
+Next, you'll install the plugin in the Medusa application from the local registry.
+
+If you've installed your Medusa project before v2.3.1, you must install [yalc](https://github.com/wclr/yalc) as a development dependency first.
+
+Run the following command in the Medusa application's directory to install the plugin:
+
+```bash title="Medusa application"
+npx medusa plugin:add medusa-plugin-magento
+```
+
+This command installs the plugin in the Medusa application from the local package registry.
+
+Next, register the plugin in the `medusa-config.ts` file of the Medusa application:
+
+```ts title="medusa-config.ts"
+module.exports = defineConfig({
+ // ...
+ plugins: [
+ {
+ resolve: "medusa-plugin-magento",
+ options: {
+ // TODO add options
+ },
+ },
+ ],
+})
+```
+
+You add the plugin to the array of plugins. Later, you'll pass options useful to retrieve data from Magento.
+
+Finally, to ensure your plugin's changes are constantly published to the local registry, simplifying your testing process, keep the following command running in the plugin project during development:
+
+```bash title="Plugin project"
+npx medusa plugin:develop
+```
+
+***
+
+## Step 4: Implement Magento Module
+
+To connect to external applications in Medusa, you create a custom module. A module is a reusable package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
+
+In this step, you'll create a Magento Module in the Magento plugin that connects to a Magento server's REST APIs and retrieves data, such as products.
+
+Refer to the [Modules](https://docs.medusajs.com/docs/learn/fundamentals/modules/index.html.md) documentation to learn more about modules.
+
+### Create Module Directory
+
+A module is created under the `src/modules` directory of your plugin. So, create the directory `src/modules/magento`.
+
+
+
+### Create Module's Service
+
+You define a module's functionalities in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to external systems or the database, which is useful if your module defines tables in the database.
+
+In this section, you'll create the Magento Module's service that connects to Magento's REST APIs and retrieves data.
+
+Start by creating the file `src/modules/magento/service.ts` in the plugin with the following content:
+
+
+
+```ts title="src/modules/magento/service.ts"
+type Options = {
+ baseUrl: string
+ storeCode?: string
+ username: string
+ password: string
+ migrationOptions?: {
+ imageBaseUrl?: string
+ }
+}
+
+export default class MagentoModuleService {
+ private options: Options
+
+ constructor({}, options: Options) {
+ this.options = {
+ ...options,
+ storeCode: options.storeCode || "default",
+ }
+ }
+}
+```
+
+You create a `MagentoModuleService` that has an `options` property to store the module's options. These options include:
+
+- `baseUrl`: The base URL of the Magento server.
+- `storeCode`: The store code of the Magento store, which is `default` by default.
+- `username`: The username of a Magento admin user to authenticate with the Magento server.
+- `password`: The password of the Magento admin user.
+- `migrationOptions`: Additional options useful for migrating data, such as the base URL to use for product images.
+
+The service's constructor accepts as a first parameter the [Module Container](https://docs.medusajs.com/docs/learn/fundamentals/modules/container/index.html.md), which allows you to access resources available for the module. As a second parameter, it accepts the module's options.
+
+### Add Authentication Logic
+
+To authenticate with the Magento server, you'll add a method to the service that retrieves an access token from Magento using the username and password in the options. This access token is used in subsequent requests to the Magento server.
+
+First, add the following property to the `MagentoModuleService` class:
+
+```ts title="src/modules/magento/service.ts"
+export default class MagentoModuleService {
+ private accessToken: {
+ token: string
+ expiresAt: Date
+ }
+ // ...
+}
+```
+
+You add an `accessToken` property to store the access token and its expiration date. The access token Magento returns expires after four hours, so you store the expiration date to know when to refresh the token.
+
+Next, add the following `authenticate` method to the `MagentoModuleService` class:
+
+```ts title="src/modules/magento/service.ts"
+import { MedusaError } from "@medusajs/framework/utils"
+
+export default class MagentoModuleService {
+ // ...
+ async authenticate() {
+ const response = await fetch(`${this.options.baseUrl}/rest/${this.options.storeCode}/V1/integration/admin/token`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ username: this.options.username, password: this.options.password }),
+ })
+
+ const token = await response.text()
+
+ if (!response.ok) {
+ throw new MedusaError(MedusaError.Types.UNAUTHORIZED, `Failed to authenticate with Magento: ${token}`)
+ }
+
+ this.accessToken = {
+ token: token.replaceAll("\"", ""),
+ expiresAt: new Date(Date.now() + 4 * 60 * 60 * 1000), // 4 hours in milliseconds
+ }
+ }
+}
+```
+
+You create an `authenticate` method that sends a POST request to the Magento server's `/rest/{storeCode}/V1/integration/admin/token` endpoint, passing the username and password in the request body.
+
+If the request is successful, you store the access token and its expiration date in the `accessToken` property. If the request fails, you throw a `MedusaError` with the error message returned by Magento.
+
+Lastly, add an `isAccessTokenExpired` method that checks if the access token has expired:
+
+```ts title="src/modules/magento/service.ts"
+export default class MagentoModuleService {
+ // ...
+ async isAccessTokenExpired(): Promise {
+ return !this.accessToken || this.accessToken.expiresAt < new Date()
+ }
+}
+```
+
+In the `isAccessTokenExpired` method, you return a boolean indicating whether the access token has expired. You'll use this in later methods to check if you need to refresh the access token.
+
+### Retrieve Products from Magento
+
+Next, you'll add a method that retrieves products from Magento. Due to limitations in Magento's API that makes it difficult to differentiate between simple products that don't belong to a configurable product and those that do, you'll only retrieve configurable products and their children. You'll also retrieve the configurable attributes of the product, such as color and size.
+
+First, you'll add some types to represent a Magento product and its attributes. Create the file `src/modules/magento/types.ts` in the plugin with the following content:
+
+
+
+```ts title="src/modules/magento/types.ts"
+export type MagentoProduct = {
+ id: number
+ sku: string
+ name: string
+ price: number
+ status: number
+ // not handling other types
+ type_id: "simple" | "configurable"
+ created_at: string
+ updated_at: string
+ extension_attributes: {
+ category_links: {
+ category_id: string
+ }[]
+ configurable_product_links?: number[]
+ configurable_product_options?: {
+ id: number
+ attribute_id: string
+ label: string
+ position: number
+ values: {
+ value_index: number
+ }[]
+ }[]
+ }
+ media_gallery_entries: {
+ id: number
+ media_type: string
+ label: string
+ position: number
+ disabled: boolean
+ types: string[]
+ file: string
+ }[]
+ custom_attributes: {
+ attribute_code: string
+ value: string
+ }[]
+ // added by module
+ children?: MagentoProduct[]
+}
+
+export type MagentoAttribute = {
+ attribute_code: string
+ attribute_id: number
+ default_frontend_label: string
+ options: {
+ label: string
+ value: string
+ }[]
+}
+
+export type MagentoPagination = {
+ search_criteria: {
+ filter_groups: [],
+ page_size: number
+ current_page: number
+ }
+ total_count: number
+}
+
+export type MagentoPaginatedResponse = {
+ items: TData[]
+} & MagentoPagination
+```
+
+You define the following types:
+
+- `MagentoProduct`: Represents a product in Magento.
+- `MagentoAttribute`: Represents an attribute in Magento.
+- `MagentoPagination`: Represents the pagination information returned by Magento's API.
+- `MagentoPaginatedResponse`: Represents a paginated response from Magento's API for a specific item type, such as products.
+
+Next, add the `getProducts` method to the `MagentoModuleService` class:
+
+```ts title="src/modules/magento/service.ts"
+export default class MagentoModuleService {
+ // ...
+ async getProducts(options?: {
+ currentPage?: number
+ pageSize?: number
+ }): Promise<{
+ products: MagentoProduct[]
+ attributes: MagentoAttribute[]
+ pagination: MagentoPagination
+ }> {
+ const { currentPage = 1, pageSize = 100 } = options || {}
+ const getAccessToken = await this.isAccessTokenExpired()
+ if (getAccessToken) {
+ await this.authenticate()
+ }
+
+ // TODO prepare query params
+ }
+}
+```
+
+The `getProducts` method receives an optional `options` object with the `currentPage` and `pageSize` properties. So far, you check if the access token has expired and, if so, retrieve a new one using the `authenticate` method.
+
+Next, you'll prepare the query parameters to pass in the request that retrieves products. Replace the `TODO` with the following:
+
+```ts title="src/modules/magento/service.ts"
+const searchQuery = new URLSearchParams()
+// pass pagination parameters
+searchQuery.append(
+ "searchCriteria[currentPage]",
+ currentPage?.toString() || "1"
+)
+searchQuery.append(
+ "searchCriteria[pageSize]",
+ pageSize?.toString() || "100"
+)
+
+// retrieve only configurable products
+searchQuery.append(
+ "searchCriteria[filter_groups][1][filters][0][field]",
+ "type_id"
+)
+searchQuery.append(
+ "searchCriteria[filter_groups][1][filters][0][value]",
+ "configurable"
+)
+searchQuery.append(
+ "searchCriteria[filter_groups][1][filters][0][condition_type]",
+ "in"
+)
+
+// TODO send request to retrieve products
+```
+
+You create a `searchQuery` object to store the query parameters to pass in the request. Then, you add the pagination parameters and the filter to retrieve only configurable products.
+
+Next, you'll send the request to retrieve products from Magento. Replace the `TODO` with the following:
+
+```ts title="src/modules/magento/service.ts"
+const { items: products, ...pagination }: MagentoPaginatedResponse = await fetch(
+ `${this.options.baseUrl}/rest/${this.options.storeCode}/V1/products?${searchQuery}`,
+ {
+ headers: {
+ "Authorization": `Bearer ${this.accessToken.token}`,
+ },
+ }
+).then((res) => res.json())
+.catch((err) => {
+ console.log(err)
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Failed to get products from Magento: ${err.message}`
+ )
+})
+
+// TODO prepare products
+```
+
+You send a `GET` request to the Magento server's `/rest/{storeCode}/V1/products` endpoint, passing the query parameters in the URL. You also pass the access token in the `Authorization` header.
+
+Next, you'll prepare the retrieved products by retrieving their children, configurable attributes, and modifying their image URLs. Replace the `TODO` with the following:
+
+```ts title="src/modules/magento/service.ts"
+const attributeIds: string[] = []
+
+await promiseAll(
+ products.map(async (product) => {
+ // retrieve its children
+ product.children = await fetch(
+ `${this.options.baseUrl}/rest/${this.options.storeCode}/V1/configurable-products/${product.sku}/children`,
+ {
+ headers: {
+ "Authorization": `Bearer ${this.accessToken.token}`,
+ },
+ }
+ ).then((res) => res.json())
+ .catch((err) => {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Failed to get product children from Magento: ${err.message}`
+ )
+ })
+
+ product.media_gallery_entries = product.media_gallery_entries.map(
+ (entry) => ({
+ ...entry,
+ file: `${this.options.migrationOptions?.imageBaseUrl}${entry.file}`,
+ }
+ ))
+
+ attributeIds.push(...(
+ product.extension_attributes.configurable_product_options?.map(
+ (option) => option.attribute_id) || []
+ )
+ )
+ })
+)
+
+// TODO retrieve attributes
+```
+
+You loop over the retrieved products and retrieve their children using the `/rest/{storeCode}/V1/configurable-products/{sku}/children` endpoint. You also modify the image URLs to use the base URL in the migration options, if provided.
+
+In addition, you store the IDs of the configurable products' attributes in the `attributeIds` array. You'll add a method that retrieves these attributes.
+
+Add the new method `getAttributes` to the `MagentoModuleService` class:
+
+```ts title="src/modules/magento/service.ts"
+export default class MagentoModuleService {
+ // ...
+ async getAttributes({
+ ids,
+ }: {
+ ids: string[]
+ }): Promise {
+ const getAccessToken = await this.isAccessTokenExpired()
+ if (getAccessToken) {
+ await this.authenticate()
+ }
+
+ // filter by attribute IDs
+ const searchQuery = new URLSearchParams()
+ searchQuery.append(
+ "searchCriteria[filter_groups][0][filters][0][field]",
+ "attribute_id"
+ )
+ searchQuery.append(
+ "searchCriteria[filter_groups][0][filters][0][value]",
+ ids.join(",")
+ )
+ searchQuery.append(
+ "searchCriteria[filter_groups][0][filters][0][condition_type]",
+ "in"
+ )
+
+ const {
+ items: attributes,
+ }: MagentoPaginatedResponse = await fetch(
+ `${this.options.baseUrl}/rest/${this.options.storeCode}/V1/products/attributes?${searchQuery}`,
+ {
+ headers: {
+ "Authorization": `Bearer ${this.accessToken.token}`,
+ },
+ }
+ ).then((res) => res.json())
+ .catch((err) => {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Failed to get attributes from Magento: ${err.message}`
+ )
+ })
+
+ return attributes
+ }
+}
+```
+
+The `getAttributes` method receives an object with the `ids` property, which is an array of attribute IDs. You check if the access token has expired and, if so, retrieve a new one using the `authenticate` method.
+
+Next, you prepare the query parameters to pass in the request to retrieve attributes. You send a `GET` request to the Magento server's `/rest/{storeCode}/V1/products/attributes` endpoint, passing the query parameters in the URL. You also pass the access token in the `Authorization` header.
+
+Finally, you return the retrieved attributes.
+
+Now, go back to the `getProducts` method and replace the `TODO` with the following:
+
+```ts title="src/modules/magento/service.ts"
+const attributes = await this.getAttributes({ ids: attributeIds })
+
+return { products, attributes, pagination }
+```
+
+You retrieve the configurable products' attributes using the `getAttributes` method and return the products, attributes, and pagination information.
+
+You'll use this method in a later step to retrieve products from Magento.
+
+### Export Module Definition
+
+The final piece to a module is its definition, which you export in an `index.ts` file at its root directory. This definition tells Medusa the name of the module and its service.
+
+So, create the file `src/modules/magento/index.ts` with the following content:
+
+
+
+```ts title="src/modules/magento/index.ts"
+import { Module } from "@medusajs/framework/utils"
+import MagentoModuleService from "./service"
+
+export const MAGENTO_MODULE = "magento"
+
+export default Module(MAGENTO_MODULE, {
+ service: MagentoModuleService,
+})
+```
+
+You use the `Module` function from the Modules SDK to create the module's definition. It accepts two parameters:
+
+1. The module's name, which is `magento`.
+2. An object with a required property `service` indicating the module's service.
+
+You'll later use the module's service to retrieve products from Magento.
+
+### Pass Options to Plugin
+
+As mentioned earlier when you registered the plugin in the Medusa Application's `medusa-config.ts` file, you can pass options to the plugin. These options are then passed to the modules in the plugin.
+
+So, add the following options to the plugin's registration in the `medusa-config.ts` file of the Medusa application:
+
+```ts title="medusa-config.ts"
+module.exports = defineConfig({
+ // ...
+ plugins: [
+ {
+ resolve: "medusa-plugin-magento",
+ options: {
+ baseUrl: process.env.MAGENTO_BASE_URL,
+ username: process.env.MAGENTO_USERNAME,
+ password: process.env.MAGENTO_PASSWORD,
+ migrationOptions: {
+ imageBaseUrl: process.env.MAGENTO_IMAGE_BASE_URL,
+ },
+ },
+ },
+ ],
+})
+```
+
+You pass the options that you defined in the `MagentoModuleService`. Make sure to also set their environment variables in the `.env` file:
+
+```bash
+MAGENTO_BASE_URL=https://magento.example.com
+MAGENTO_USERNAME=admin
+MAGENTO_PASSWORD=password
+MAGENTO_IMAGE_BASE_URL=https://magento.example.com/pub/media/catalog/product
+```
+
+Where:
+
+- `MAGENTO_BASE_URL`: The base URL of the Magento server. It can also be a local URL, such as `http://localhost:8080`.
+- `MAGENTO_USERNAME`: The username of a Magento admin user to authenticate with the Magento server.
+- `MAGENTO_PASSWORD`: The password of the Magento admin user.
+- `MAGENTO_IMAGE_BASE_URL`: The base URL to use for product images. Magento stores product images in the `pub/media/catalog/product` directory, so you can reference them directly or use a CDN URL. If the URLs of product images in the Medusa server already have a different base URL, you can omit this option.
+
+Medusa supports integrating third-party services, such as [S3](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/architectural-modules/file/s3/index.html.md), in a File Module Provider. Refer to the [File Module](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/architectural-modules/file/index.html.md) documentation to find other module providers and how to create a custom provider.
+
+You can now use the Magento Module to migrate data, which you'll do in the next steps.
+
+***
+
+## Step 5: Build Product Migration Workflow
+
+In this section, you'll add the feature to migrate products from Magento to Medusa. To implement this feature, you'll use a workflow.
+
+A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it's a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in an API route or a scheduled job.
+
+By implementing the migration feature in a workflow, you ensure that the data remains consistent and that the migration process can be rolled back if an error occurs.
+
+Refer to the [Workflows](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md) documentation to learn more about workflows.
+
+### Workflow Steps
+
+The workflow you'll create will have the following steps:
+
+- [getMagentoProductsStep](#getMagentoProductsStep): Retrieve products from Magento using the Magento Module.
+- [useQueryGraphStep](https://docs.medusajs.com/references/helper-steps/useQueryGraphStep/index.html.md): Retrieve Medusa store details, which you'll need when creating the products.
+- [useQueryGraphStep](https://docs.medusajs.com/references/helper-steps/useQueryGraphStep/index.html.md): Retrieve a shipping profile, which you'll associate the created products with.
+- [useQueryGraphStep](https://docs.medusajs.com/references/helper-steps/useQueryGraphStep/index.html.md): Retrieve Magento products that are already in Medusa to update them, instead of creating them.
+- [createProductsWorkflow](https://docs.medusajs.com/references/medusa-workflows/createProductsWorkflow/index.html.md): Create products in the Medusa application.
+- [updateProductsWorkflow](https://docs.medusajs.com/references/medusa-workflows/updateProductsWorkflow/index.html.md): Update existing products in the Medusa application.
+
+You only need to implement the `getMagentoProductsStep` step, which retrieves the products from Magento. The other steps and workflows are provided by Medusa's `@medusajs/medusa/core-flows` package.
+
+### getMagentoProductsStep
+
+The first step of the workflow retrieves and returns the products from Magento.
+
+In your plugin, create the file `src/workflows/steps/get-magento-products.ts` with the following content:
+
+
+
+```ts title="src/workflows/steps/get-magento-products.ts"
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { MAGENTO_MODULE } from "../../modules/magento"
+import MagentoModuleService from "../../modules/magento/service"
+
+type GetMagentoProductsInput = {
+ currentPage: number
+ pageSize: number
+}
+
+export const getMagentoProductsStep = createStep(
+ "get-magento-products",
+ async ({ currentPage, pageSize }: GetMagentoProductsInput, { container }) => {
+ const magentoModuleService: MagentoModuleService =
+ container.resolve(MAGENTO_MODULE)
+
+ const response = await magentoModuleService.getProducts({
+ currentPage,
+ pageSize,
+ })
+
+ return new StepResponse(response)
+ }
+)
+```
+
+You create a step using `createStep` from the Workflows SDK. It accepts two parameters:
+
+1. The step's name, which is `get-magento-products`.
+2. An async function that executes the step's logic. The function receives two parameters:
+ - The input data for the step, which in this case is the pagination parameters.
+ - An object holding the workflow's context, including the [Medusa Container](https://docs.medusajs.com/docslearn/fundamentals/medusa-container/index.html.md) that allows you to resolve framework and commerce tools.
+
+In the step function, you resolve the Magento Module's service from the container, then use its `getProducts` method to retrieve the products from Magento.
+
+Steps that return data must return them in a `StepResponse` instance. The `StepResponse` constructor accepts as a parameter the data to return.
+
+### Create migrateProductsFromMagentoWorkflow
+
+You'll now create the workflow that migrates products from Magento using the step you created and steps from Medusa's `@medusajs/medusa/core-flows` package.
+
+In your plugin, create the file `src/workflows/migrate-products-from-magento.ts` with the following content:
+
+
+
+```ts title="src/workflows/migrate-products-from-magento.ts"
+import {
+ createWorkflow, transform, WorkflowResponse,
+} from "@medusajs/framework/workflows-sdk"
+import {
+ CreateProductWorkflowInputDTO, UpsertProductDTO,
+} from "@medusajs/framework/types"
+import {
+ createProductsWorkflow,
+ updateProductsWorkflow,
+ useQueryGraphStep,
+} from "@medusajs/medusa/core-flows"
+import { getMagentoProductsStep } from "./steps/get-magento-products"
+
+type MigrateProductsFromMagentoWorkflowInput = {
+ currentPage: number
+ pageSize: number
+}
+
+export const migrateProductsFromMagentoWorkflowId =
+ "migrate-products-from-magento"
+
+export const migrateProductsFromMagentoWorkflow = createWorkflow(
+ {
+ name: migrateProductsFromMagentoWorkflowId,
+ retentionTime: 10000,
+ store: true,
+ },
+ (input: MigrateProductsFromMagentoWorkflowInput) => {
+ const { pagination, products, attributes } = getMagentoProductsStep(
+ input
+ )
+ // TODO prepare data to create and update products
+ }
+)
+```
+
+You create a workflow using `createWorkflow` from the Workflows SDK. It accepts two parameters:
+
+1. An object with the workflow's configuration, including the name and whether to store the workflow's executions. You enable storing the workflow execution so that you can view it later in the Medusa Admin dashboard.
+2. A worflow constructor function, which holds the workflow's implementation. The function receives the input data for the workflow, which is the pagination parameters.
+
+In the workflow constructor function, you use the `getMagentoProductsStep` step to retrieve the products from Magento, passing it the pagination parameters from the workflow's input.
+
+Next, you'll retrieve the Medusa store details and shipping profiles. These are necessary to prepare the data of the products to create or update.
+
+Replace the `TODO` in the workflow function with the following:
+
+```ts title="src/workflows/migrate-products-from-magento.ts"
+const { data: stores } = useQueryGraphStep({
+ entity: "store",
+ fields: ["supported_currencies.*", "default_sales_channel_id"],
+ pagination: {
+ take: 1,
+ skip: 0,
+ },
+})
+
+const { data: shippingProfiles } = useQueryGraphStep({
+ entity: "shipping_profile",
+ fields: ["id"],
+ pagination: {
+ take: 1,
+ skip: 0,
+ },
+}).config({ name: "get-shipping-profiles" })
+
+// TODO retrieve existing products
+```
+
+You use the `useQueryGraphStep` step to retrieve the store details and shipping profiles. `useQueryGraphStep` is a Medusa step that wraps [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md), allowing you to use it in a workflow. Query is a tool that retrieves data across modules.
+
+Whe retrieving the store details, you specifically retrieve its supported currencies and default sales channel ID. You'll associate the products with the store's default sales channel, and set their variant prices in the supported currencies. You'll also associate the products with a shipping profile.
+
+Next, you'll retrieve products that were previously migrated from Magento to determine which products to create or update. Replace the `TODO` with the following:
+
+```ts title="src/workflows/migrate-products-from-magento.ts"
+const externalIdFilters = transform({
+ products,
+}, (data) => {
+ return data.products.map((product) => product.id.toString())
+})
+
+const { data: existingProducts } = useQueryGraphStep({
+ entity: "product",
+ fields: ["id", "external_id", "variants.id", "variants.metadata"],
+ filters: {
+ external_id: externalIdFilters,
+ },
+}).config({ name: "get-existing-products" })
+
+// TODO prepare products to create or update
+```
+
+Since the Medusa application creates an internal representation of the workflow's constructor function, you can't manipulate data directly, as variables have no value while creating the internal representation.
+
+Refer to the [Workflows](https://docs.medusajs.com/docs/learn/fundamentals/workflows/constructor-constraints/index.html.md) documentation to learn more about the workflow constructor function's constraints.
+
+Instead, you can manipulate data in a workflow's constructor function using `transform` from the Workflows SDK. `transform` is a function that accepts two parameters:
+
+- The data to transform, which in this case is the Magento products.
+- A function that transforms the data. The function receives the data passed in the first parameter and returns the transformed data.
+
+In the transformation function, you return the IDs of the Magento products. Then, you use the `useQueryGraphStep` to retrieve products in the Medusa application that have an `external_id` property matching the IDs of the Magento products. You'll use this property to store the IDs of the products in Magento.
+
+Next, you'll prepare the data to create and update the products. Replace the `TODO` in the workflow function with the following:
+
+```ts title="src/workflows/migrate-products-from-magento.ts" highlights={prepareHighlights}
+const {
+ productsToCreate,
+ productsToUpdate,
+} = transform({
+ products,
+ attributes,
+ stores,
+ shippingProfiles,
+ existingProducts,
+}, (data) => {
+ const productsToCreate = new Map()
+ const productsToUpdate = new Map()
+
+ data.products.forEach((magentoProduct) => {
+ const productData: CreateProductWorkflowInputDTO | UpsertProductDTO = {
+ title: magentoProduct.name,
+ description: magentoProduct.custom_attributes.find(
+ (attr) => attr.attribute_code === "description"
+ )?.value,
+ status: magentoProduct.status === 1 ? "published" : "draft",
+ handle: magentoProduct.custom_attributes.find(
+ (attr) => attr.attribute_code === "url_key"
+ )?.value,
+ external_id: magentoProduct.id.toString(),
+ thumbnail: magentoProduct.media_gallery_entries.find(
+ (entry) => entry.types.includes("thumbnail")
+ )?.file,
+ sales_channels: [{
+ id: data.stores[0].default_sales_channel_id,
+ }],
+ shipping_profile_id: data.shippingProfiles[0].id,
+ }
+ const existingProduct = data.existingProducts.find((p) => p.external_id === productData.external_id)
+
+ if (existingProduct) {
+ productData.id = existingProduct.id
+ }
+
+ productData.options = magentoProduct.extension_attributes.configurable_product_options?.map((option) => {
+ const attribute = data.attributes.find((attr) => attr.attribute_id === parseInt(option.attribute_id))
+ return {
+ title: option.label,
+ values: attribute?.options.filter((opt) => {
+ return option.values.find((v) => v.value_index === parseInt(opt.value))
+ }).map((opt) => opt.label) || [],
+ }
+ }) || []
+
+ productData.variants = magentoProduct.children?.map((child) => {
+ const childOptions: Record = {}
+
+ child.custom_attributes.forEach((attr) => {
+ const attrData = data.attributes.find((a) => a.attribute_code === attr.attribute_code)
+ if (!attrData) {
+ return
+ }
+
+ childOptions[attrData.default_frontend_label] = attrData.options.find((opt) => opt.value === attr.value)?.label || ""
+ })
+
+ const variantExternalId = child.id.toString()
+ const existingVariant = existingProduct.variants.find((v) => v.metadata.external_id === variantExternalId)
+
+ return {
+ title: child.name,
+ sku: child.sku,
+ options: childOptions,
+ prices: data.stores[0].supported_currencies.map(({ currency_code }) => {
+ return {
+ amount: child.price,
+ currency_code,
+ }
+ }),
+ metadata: {
+ external_id: variantExternalId,
+ },
+ id: existingVariant?.id,
+ }
+ })
+
+ productData.images = magentoProduct.media_gallery_entries.filter((entry) => !entry.types.includes("thumbnail")).map((entry) => {
+ return {
+ url: entry.file,
+ metadata: {
+ external_id: entry.id.toString(),
+ },
+ }
+ })
+
+ if (productData.id) {
+ productsToUpdate.set(existingProduct.id, productData)
+ } else {
+ productsToCreate.set(productData.external_id!, productData)
+ }
+ })
+
+ return {
+ productsToCreate: Array.from(productsToCreate.values()),
+ productsToUpdate: Array.from(productsToUpdate.values()),
+ }
+})
+
+// TODO create and update products
+```
+
+You use `transform` again to prepare the data to create and update the products in the Medusa application. For each Magento product, you map its equivalent Medusa product's data:
+
+- You set the product's general details, such as the title, description, status, handle, external ID, and thumbnail using the Magento product's data and custom attributes.
+- You associate the product with the default sales channel and shipping profile retrieved previously.
+- You map the Magento product's configurable product options to Medusa product options. In Medusa, a product's option has a label, such as "Color", and values, such as "Red". To map the option values, you use the attributes retrieved from Magento.
+- You map the Magento product's children to Medusa product variants. For the variant options, you pass an object whose keys is the option's label, such as "Color", and values is the option's value, such as "Red". For the prices, you set the variant's price based on the Magento child's price for every supported currency in the Medusa store. Also, you set the Magento child product's ID in the Medusa variant's `metadata.external_id` property.
+- You map the Magento product's media gallery entries to Medusa product images. You filter out the thumbnail image and set the URL and the Magento image's ID in the Medusa image's `metadata.external_id` property.
+
+In addition, you use the existing products retrieved in the previous step to determine whether a product should be created or updated. If there's an existing product whose `external_id` matches the ID of the magento product, you set the existing product's ID in the `id` property of the product to be updated. You also do the same for its variants.
+
+Finally, you return the products to create and update.
+
+The last steps of the workflow is to create and update the products. Replace the `TODO` in the workflow function with the following:
+
+```ts title="src/workflows/migrate-products-from-magento.ts"
+createProductsWorkflow.runAsStep({
+ input: {
+ products: productsToCreate,
+ },
+})
+
+updateProductsWorkflow.runAsStep({
+ input: {
+ products: productsToUpdate,
+ },
+})
+
+return new WorkflowResponse(pagination)
+```
+
+You use the `createProductsWorkflow` and `updateProductsWorkflow` workflows from Medusa's `@medusajs/medusa/core-flows` package to create and update the products in the Medusa application.
+
+Workflows must return an instance of `WorkflowResponse`, passing as a parameter the data to return to the workflow's executor. This workflow returns the pagination parameters, allowing you to paginate the product migration process.
+
+You can now use this workflow to migrate products from Magento to Medusa. You'll learn how to use it in the next steps.
+
+***
+
+## Step 6: Schedule Product Migration
+
+There are many ways to execute tasks asynchronously in Medusa, such as [scheduling a job](https://docs.medusajs.com/docs/learn/fundamentals/scheduled-jobs/index.html.md) or [handling emitted events](https://docs.medusajs.com/docs/learn/fundamentals/events-and-subscribers/index.html.md).
+
+In this guide, you'll learn how to schedule the product migration at a specified interval using a scheduled job. A scheduled job is an asynchronous function that the Medusa application runs at the interval you specify during the Medusa application's runtime.
+
+Refer to the [Scheduled Jobs](https://docs.medusajs.com/docs/learn/fundamentals/scheduled-jobs/index.html.md) documentation to learn more about scheduled jobs.
+
+To create a scheduled job, in your plugin, create the file `src/jobs/migrate-magento.ts` with the following content:
+
+
+
+```ts title="src/jobs/migrate-magento.ts"
+import { MedusaContainer } from "@medusajs/framework/types"
+import { migrateProductsFromMagentoWorkflow } from "../workflows"
+
+export default async function migrateMagentoJob(
+ container: MedusaContainer
+) {
+ const logger = container.resolve("logger")
+ logger.info("Migrating products from Magento...")
+
+ let currentPage = 0
+ const pageSize = 100
+ let totalCount = 0
+
+ do {
+ currentPage++
+
+ const {
+ result: pagination,
+ } = await migrateProductsFromMagentoWorkflow(container).run({
+ input: {
+ currentPage,
+ pageSize,
+ },
+ })
+
+ totalCount = pagination.total_count
+ } while (currentPage * pageSize < totalCount)
+
+ logger.info("Finished migrating products from Magento")
+}
+
+export const config = {
+ name: "migrate-magento-job",
+ schedule: "0 0 * * *",
+}
+```
+
+A scheduled job file must export:
+
+- An asynchronous function that executes the job's logic. The function receives the [Medusa container](https://docs.medusajs.com/docs/learn/fundamentals/medusa-container/index.html.md) as a parameter.
+- An object with the job's configuration, including the name and the schedule. The schedule is a cron job pattern as a string.
+
+In the job function, you resolve the [logger](https://docs.medusajs.com/docs/learn/debugging-and-testing/logging/index.html.md) from the container to log messages. Then, you paginate the product migration process by running the `migrateProductsFromMagentoWorkflow` workflow at each page until you've migrated all products. You use the pagination result returned by the workflow to determine whether there are more products to migrate.
+
+Based on the job's configurations, the Medusa application will run the job at midnight every day.
+
+### Test it Out
+
+To test out this scheduled job, first, change the configuration to run the job every minute:
+
+```ts title="src/jobs/migrate-magento.ts"
+export const config = {
+ // ...
+ schedule: "* * * * *",
+}
+```
+
+Then, make sure to run the `plugin:develop` command in the plugin if you haven't already:
+
+```bash
+npx medusa plugin:develop
+```
+
+This ensures that the plugin's latest changes are reflected in the Medusa application.
+
+Finally, start the Medusa application that the plugin is installed in:
+
+```bash npm2yarn
+npm run dev
+```
+
+After a minute, you'll see a message in the terminal indicating that the migration started:
+
+```plain title="Terminal"
+info: Migrating products from Magento...
+```
+
+Once the migration is done, you'll see the following message:
+
+```plain title="Terminal"
+info: Finished migrating products from Magento
+```
+
+To confirm that the products were migrated, open the Medusa Admin dashboard at `http://localhost:9000/app` and log in. Then, click on Products in the sidebar. You'll see your magento products in the list of products.
+
+
+
+***
+
+## Next Steps
+
+You've now implemented the logic to migrate products from Magento to Medusa. You can re-use the plugin across Medusa applications. You can also expand on the plugin to:
+
+- Migrate other entities, such as orders, customers, and categories. Migrating other entities follows the same pattern as migrating products, using workflows and scheduled jobs. You only need to format the data to be migrated as needed.
+- Allow triggering migrations from the Medusa Admin dashboard using [Admin Customizations](https://docs.medusajs.com/docs/learn/fundamentals/admin/index.html.md). This feature is available in the [Example Repository](https://github.com/medusajs/example-repository/tree/main/src/admin).
+
+If you're new to Medusa, check out the [main documentation](https://docs.medusajs.com/docs/learn/index.html.md), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
+
+To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/index.html.md).
+
+
# How to Build a Wishlist Plugin
In this guide, you'll learn how to build a wishlist [plugin](https://docs.medusajs.com/docs/learn/fundamentals/plugins/index.html.md) in Medusa.
@@ -51369,349 +52130,349 @@ To learn more about the commerce features that Medusa provides, check out Medusa
## JS SDK Admin
-- [create](https://docs.medusajs.com/references/js_sdk/admin/Campaign/methods/js_sdk.admin.Campaign.create/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.create/index.html.md)
+- [batchSalesChannels](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.batchSalesChannels/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.delete/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.list/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.retrieve/index.html.md)
+- [revoke](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.revoke/index.html.md)
+- [update](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.update/index.html.md)
- [batchPromotions](https://docs.medusajs.com/references/js_sdk/admin/Campaign/methods/js_sdk.admin.Campaign.batchPromotions/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/Campaign/methods/js_sdk.admin.Campaign.create/index.html.md)
- [delete](https://docs.medusajs.com/references/js_sdk/admin/Campaign/methods/js_sdk.admin.Campaign.delete/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/Campaign/methods/js_sdk.admin.Campaign.list/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Campaign/methods/js_sdk.admin.Campaign.retrieve/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/Campaign/methods/js_sdk.admin.Campaign.update/index.html.md)
-- [addInboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.addInboundShipping/index.html.md)
-- [addInboundItems](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.addInboundItems/index.html.md)
-- [cancel](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.cancel/index.html.md)
-- [addOutboundItems](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.addOutboundItems/index.html.md)
-- [addOutboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.addOutboundShipping/index.html.md)
-- [addItems](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.addItems/index.html.md)
-- [deleteInboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.deleteInboundShipping/index.html.md)
-- [deleteOutboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.deleteOutboundShipping/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.create/index.html.md)
-- [cancelRequest](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.cancelRequest/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.list/index.html.md)
-- [removeItem](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.removeItem/index.html.md)
-- [removeInboundItem](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.removeInboundItem/index.html.md)
-- [removeOutboundItem](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.removeOutboundItem/index.html.md)
-- [updateInboundItem](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.updateInboundItem/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.retrieve/index.html.md)
-- [request](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.request/index.html.md)
-- [updateInboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.updateInboundShipping/index.html.md)
-- [updateItem](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.updateItem/index.html.md)
-- [updateOutboundItem](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.updateOutboundItem/index.html.md)
-- [updateOutboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.updateOutboundShipping/index.html.md)
-- [batchSalesChannels](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.batchSalesChannels/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.create/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.delete/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.list/index.html.md)
-- [revoke](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.revoke/index.html.md)
-- [update](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.update/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/ApiKey/methods/js_sdk.admin.ApiKey.retrieve/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/Currency/methods/js_sdk.admin.Currency.list/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Currency/methods/js_sdk.admin.Currency.retrieve/index.html.md)
-- [getItem](https://docs.medusajs.com/references/js_sdk/admin/CustomStorage/methods/js_sdk.admin.CustomStorage.getItem/index.html.md)
-- [setItem](https://docs.medusajs.com/references/js_sdk/admin/CustomStorage/methods/js_sdk.admin.CustomStorage.setItem/index.html.md)
-- [removeItem](https://docs.medusajs.com/references/js_sdk/admin/CustomStorage/methods/js_sdk.admin.CustomStorage.removeItem/index.html.md)
- [clearToken](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.clearToken/index.html.md)
-- [clearToken\_](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.clearToken_/index.html.md)
- [fetch](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.fetch/index.html.md)
+- [clearToken\_](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.clearToken_/index.html.md)
- [getApiKeyHeader\_](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.getApiKeyHeader_/index.html.md)
- [fetchStream](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.fetchStream/index.html.md)
- [getJwtHeader\_](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.getJwtHeader_/index.html.md)
- [getTokenStorageInfo\_](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.getTokenStorageInfo_/index.html.md)
- [getToken\_](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.getToken_/index.html.md)
-- [initClient](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.initClient/index.html.md)
- [getPublishableKeyHeader\_](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.getPublishableKeyHeader_/index.html.md)
-- [setToken](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.setToken/index.html.md)
+- [initClient](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.initClient/index.html.md)
- [setToken\_](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.setToken_/index.html.md)
+- [setToken](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.setToken/index.html.md)
- [throwError\_](https://docs.medusajs.com/references/js_sdk/admin/Client/methods/js_sdk.admin.Client.throwError_/index.html.md)
-- [batchCustomers](https://docs.medusajs.com/references/js_sdk/admin/CustomerGroup/methods/js_sdk.admin.CustomerGroup.batchCustomers/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/CustomerGroup/methods/js_sdk.admin.CustomerGroup.create/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/CustomerGroup/methods/js_sdk.admin.CustomerGroup.list/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/CustomerGroup/methods/js_sdk.admin.CustomerGroup.delete/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/CustomerGroup/methods/js_sdk.admin.CustomerGroup.retrieve/index.html.md)
-- [update](https://docs.medusajs.com/references/js_sdk/admin/CustomerGroup/methods/js_sdk.admin.CustomerGroup.update/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.create/index.html.md)
-- [batchCustomerGroups](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.batchCustomerGroups/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/Currency/methods/js_sdk.admin.Currency.list/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Currency/methods/js_sdk.admin.Currency.retrieve/index.html.md)
+- [addInboundItems](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.addInboundItems/index.html.md)
+- [addOutboundItems](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.addOutboundItems/index.html.md)
+- [addInboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.addInboundShipping/index.html.md)
+- [addOutboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.addOutboundShipping/index.html.md)
+- [addItems](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.addItems/index.html.md)
+- [cancel](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.cancel/index.html.md)
+- [deleteInboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.deleteInboundShipping/index.html.md)
+- [cancelRequest](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.cancelRequest/index.html.md)
+- [deleteOutboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.deleteOutboundShipping/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.create/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.list/index.html.md)
+- [removeInboundItem](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.removeInboundItem/index.html.md)
+- [removeItem](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.removeItem/index.html.md)
+- [request](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.request/index.html.md)
+- [updateInboundItem](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.updateInboundItem/index.html.md)
+- [removeOutboundItem](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.removeOutboundItem/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.retrieve/index.html.md)
+- [updateInboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.updateInboundShipping/index.html.md)
+- [updateItem](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.updateItem/index.html.md)
+- [updateOutboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.updateOutboundShipping/index.html.md)
+- [updateOutboundItem](https://docs.medusajs.com/references/js_sdk/admin/Claim/methods/js_sdk.admin.Claim.updateOutboundItem/index.html.md)
+- [getItem](https://docs.medusajs.com/references/js_sdk/admin/CustomStorage/methods/js_sdk.admin.CustomStorage.getItem/index.html.md)
+- [removeItem](https://docs.medusajs.com/references/js_sdk/admin/CustomStorage/methods/js_sdk.admin.CustomStorage.removeItem/index.html.md)
+- [setItem](https://docs.medusajs.com/references/js_sdk/admin/CustomStorage/methods/js_sdk.admin.CustomStorage.setItem/index.html.md)
- [createAddress](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.createAddress/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.delete/index.html.md)
+- [batchCustomerGroups](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.batchCustomerGroups/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.create/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.list/index.html.md)
- [deleteAddress](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.deleteAddress/index.html.md)
- [listAddresses](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.listAddresses/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.list/index.html.md)
-- [retrieveAddress](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.retrieveAddress/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.delete/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.retrieve/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.update/index.html.md)
+- [retrieveAddress](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.retrieveAddress/index.html.md)
- [updateAddress](https://docs.medusajs.com/references/js_sdk/admin/Customer/methods/js_sdk.admin.Customer.updateAddress/index.html.md)
+- [batchCustomers](https://docs.medusajs.com/references/js_sdk/admin/CustomerGroup/methods/js_sdk.admin.CustomerGroup.batchCustomers/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/CustomerGroup/methods/js_sdk.admin.CustomerGroup.create/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/CustomerGroup/methods/js_sdk.admin.CustomerGroup.delete/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/CustomerGroup/methods/js_sdk.admin.CustomerGroup.list/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/CustomerGroup/methods/js_sdk.admin.CustomerGroup.retrieve/index.html.md)
+- [update](https://docs.medusajs.com/references/js_sdk/admin/CustomerGroup/methods/js_sdk.admin.CustomerGroup.update/index.html.md)
+- [addInboundItems](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.addInboundItems/index.html.md)
+- [addInboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.addInboundShipping/index.html.md)
+- [addOutboundItems](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.addOutboundItems/index.html.md)
+- [cancel](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.cancel/index.html.md)
+- [cancelRequest](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.cancelRequest/index.html.md)
+- [addOutboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.addOutboundShipping/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.create/index.html.md)
+- [deleteInboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.deleteInboundShipping/index.html.md)
+- [deleteOutboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.deleteOutboundShipping/index.html.md)
+- [removeInboundItem](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.removeInboundItem/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.list/index.html.md)
+- [removeOutboundItem](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.removeOutboundItem/index.html.md)
+- [request](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.request/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.retrieve/index.html.md)
+- [updateInboundItem](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.updateInboundItem/index.html.md)
+- [updateInboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.updateInboundShipping/index.html.md)
+- [updateOutboundItem](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.updateOutboundItem/index.html.md)
+- [addItems](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.addItems/index.html.md)
+- [updateOutboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.updateOutboundShipping/index.html.md)
- [addPromotions](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.addPromotions/index.html.md)
- [addShippingMethod](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.addShippingMethod/index.html.md)
-- [addItems](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.addItems/index.html.md)
-- [beginEdit](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.beginEdit/index.html.md)
- [cancelEdit](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.cancelEdit/index.html.md)
+- [beginEdit](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.beginEdit/index.html.md)
- [confirmEdit](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.confirmEdit/index.html.md)
+- [convertToOrder](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.convertToOrder/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.list/index.html.md)
- [removeActionItem](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.removeActionItem/index.html.md)
-- [convertToOrder](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.convertToOrder/index.html.md)
- [create](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.create/index.html.md)
- [removeActionShippingMethod](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.removeActionShippingMethod/index.html.md)
-- [removePromotions](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.removePromotions/index.html.md)
- [requestEdit](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.requestEdit/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.retrieve/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.update/index.html.md)
-- [updateActionItem](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.updateActionItem/index.html.md)
+- [removePromotions](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.removePromotions/index.html.md)
- [updateActionShippingMethod](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.updateActionShippingMethod/index.html.md)
- [updateItem](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.updateItem/index.html.md)
+- [updateActionItem](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.updateActionItem/index.html.md)
- [updateShippingMethod](https://docs.medusajs.com/references/js_sdk/admin/DraftOrder/methods/js_sdk.admin.DraftOrder.updateShippingMethod/index.html.md)
- [cancel](https://docs.medusajs.com/references/js_sdk/admin/Fulfillment/methods/js_sdk.admin.Fulfillment.cancel/index.html.md)
- [create](https://docs.medusajs.com/references/js_sdk/admin/Fulfillment/methods/js_sdk.admin.Fulfillment.create/index.html.md)
- [createShipment](https://docs.medusajs.com/references/js_sdk/admin/Fulfillment/methods/js_sdk.admin.Fulfillment.createShipment/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/FulfillmentProvider/methods/js_sdk.admin.FulfillmentProvider.list/index.html.md)
+- [listFulfillmentOptions](https://docs.medusajs.com/references/js_sdk/admin/FulfillmentProvider/methods/js_sdk.admin.FulfillmentProvider.listFulfillmentOptions/index.html.md)
- [batchInventoryItemLocationLevels](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.batchInventoryItemLocationLevels/index.html.md)
- [batchInventoryItemsLocationLevels](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.batchInventoryItemsLocationLevels/index.html.md)
- [batchUpdateLevels](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.batchUpdateLevels/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.create/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.delete/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.list/index.html.md)
- [deleteLevel](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.deleteLevel/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.delete/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.create/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.list/index.html.md)
- [listLevels](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.listLevels/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.retrieve/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.update/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.retrieve/index.html.md)
- [updateLevel](https://docs.medusajs.com/references/js_sdk/admin/InventoryItem/methods/js_sdk.admin.InventoryItem.updateLevel/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/FulfillmentProvider/methods/js_sdk.admin.FulfillmentProvider.list/index.html.md)
-- [listFulfillmentOptions](https://docs.medusajs.com/references/js_sdk/admin/FulfillmentProvider/methods/js_sdk.admin.FulfillmentProvider.listFulfillmentOptions/index.html.md)
- [createServiceZone](https://docs.medusajs.com/references/js_sdk/admin/FulfillmentSet/methods/js_sdk.admin.FulfillmentSet.createServiceZone/index.html.md)
-- [deleteServiceZone](https://docs.medusajs.com/references/js_sdk/admin/FulfillmentSet/methods/js_sdk.admin.FulfillmentSet.deleteServiceZone/index.html.md)
- [delete](https://docs.medusajs.com/references/js_sdk/admin/FulfillmentSet/methods/js_sdk.admin.FulfillmentSet.delete/index.html.md)
-- [updateServiceZone](https://docs.medusajs.com/references/js_sdk/admin/FulfillmentSet/methods/js_sdk.admin.FulfillmentSet.updateServiceZone/index.html.md)
-- [accept](https://docs.medusajs.com/references/js_sdk/admin/Invite/methods/js_sdk.admin.Invite.accept/index.html.md)
+- [deleteServiceZone](https://docs.medusajs.com/references/js_sdk/admin/FulfillmentSet/methods/js_sdk.admin.FulfillmentSet.deleteServiceZone/index.html.md)
- [retrieveServiceZone](https://docs.medusajs.com/references/js_sdk/admin/FulfillmentSet/methods/js_sdk.admin.FulfillmentSet.retrieveServiceZone/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/Invite/methods/js_sdk.admin.Invite.create/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/Invite/methods/js_sdk.admin.Invite.delete/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Invite/methods/js_sdk.admin.Invite.retrieve/index.html.md)
-- [resend](https://docs.medusajs.com/references/js_sdk/admin/Invite/methods/js_sdk.admin.Invite.resend/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/Invite/methods/js_sdk.admin.Invite.list/index.html.md)
+- [updateServiceZone](https://docs.medusajs.com/references/js_sdk/admin/FulfillmentSet/methods/js_sdk.admin.FulfillmentSet.updateServiceZone/index.html.md)
+- [addItems](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.addItems/index.html.md)
+- [cancelRequest](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.cancelRequest/index.html.md)
+- [confirm](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.confirm/index.html.md)
+- [removeAddedItem](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.removeAddedItem/index.html.md)
+- [initiateRequest](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.initiateRequest/index.html.md)
+- [request](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.request/index.html.md)
+- [updateAddedItem](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.updateAddedItem/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/Notification/methods/js_sdk.admin.Notification.list/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Notification/methods/js_sdk.admin.Notification.retrieve/index.html.md)
+- [updateOriginalItem](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.updateOriginalItem/index.html.md)
+- [accept](https://docs.medusajs.com/references/js_sdk/admin/Invite/methods/js_sdk.admin.Invite.accept/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/Invite/methods/js_sdk.admin.Invite.create/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/Invite/methods/js_sdk.admin.Invite.delete/index.html.md)
+- [resend](https://docs.medusajs.com/references/js_sdk/admin/Invite/methods/js_sdk.admin.Invite.resend/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Invite/methods/js_sdk.admin.Invite.retrieve/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/Invite/methods/js_sdk.admin.Invite.list/index.html.md)
- [capture](https://docs.medusajs.com/references/js_sdk/admin/Payment/methods/js_sdk.admin.Payment.capture/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/Payment/methods/js_sdk.admin.Payment.list/index.html.md)
- [listPaymentProviders](https://docs.medusajs.com/references/js_sdk/admin/Payment/methods/js_sdk.admin.Payment.listPaymentProviders/index.html.md)
-- [refund](https://docs.medusajs.com/references/js_sdk/admin/Payment/methods/js_sdk.admin.Payment.refund/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Payment/methods/js_sdk.admin.Payment.retrieve/index.html.md)
+- [refund](https://docs.medusajs.com/references/js_sdk/admin/Payment/methods/js_sdk.admin.Payment.refund/index.html.md)
- [cancel](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.cancel/index.html.md)
- [cancelFulfillment](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.cancelFulfillment/index.html.md)
- [createCreditLine](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.createCreditLine/index.html.md)
-- [cancelTransfer](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.cancelTransfer/index.html.md)
- [createFulfillment](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.createFulfillment/index.html.md)
- [createShipment](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.createShipment/index.html.md)
+- [cancelTransfer](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.cancelTransfer/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.list/index.html.md)
- [listChanges](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.listChanges/index.html.md)
- [listLineItems](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.listLineItems/index.html.md)
- [markAsDelivered](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.markAsDelivered/index.html.md)
- [requestTransfer](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.requestTransfer/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.retrieve/index.html.md)
-- [retrievePreview](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.retrievePreview/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.update/index.html.md)
-- [addItems](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.addItems/index.html.md)
-- [cancelRequest](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.cancelRequest/index.html.md)
-- [initiateRequest](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.initiateRequest/index.html.md)
-- [confirm](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.confirm/index.html.md)
-- [request](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.request/index.html.md)
-- [removeAddedItem](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.removeAddedItem/index.html.md)
-- [updateAddedItem](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.updateAddedItem/index.html.md)
-- [updateOriginalItem](https://docs.medusajs.com/references/js_sdk/admin/OrderEdit/methods/js_sdk.admin.OrderEdit.updateOriginalItem/index.html.md)
-- [addInboundItems](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.addInboundItems/index.html.md)
-- [addInboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.addInboundShipping/index.html.md)
-- [addOutboundItems](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.addOutboundItems/index.html.md)
-- [addOutboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.addOutboundShipping/index.html.md)
-- [cancelRequest](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.cancelRequest/index.html.md)
-- [cancel](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.cancel/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.create/index.html.md)
-- [deleteOutboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.deleteOutboundShipping/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.list/index.html.md)
-- [deleteInboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.deleteInboundShipping/index.html.md)
-- [removeInboundItem](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.removeInboundItem/index.html.md)
-- [removeOutboundItem](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.removeOutboundItem/index.html.md)
-- [updateInboundItem](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.updateInboundItem/index.html.md)
-- [request](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.request/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.retrieve/index.html.md)
-- [updateInboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.updateInboundShipping/index.html.md)
-- [updateOutboundItem](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.updateOutboundItem/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/PriceList/methods/js_sdk.admin.PriceList.create/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/PriceList/methods/js_sdk.admin.PriceList.delete/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/PricePreference/methods/js_sdk.admin.PricePreference.create/index.html.md)
+- [retrievePreview](https://docs.medusajs.com/references/js_sdk/admin/Order/methods/js_sdk.admin.Order.retrievePreview/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/PricePreference/methods/js_sdk.admin.PricePreference.delete/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/PricePreference/methods/js_sdk.admin.PricePreference.retrieve/index.html.md)
+- [update](https://docs.medusajs.com/references/js_sdk/admin/PricePreference/methods/js_sdk.admin.PricePreference.update/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/PricePreference/methods/js_sdk.admin.PricePreference.list/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/Plugin/methods/js_sdk.admin.Plugin.list/index.html.md)
- [batchPrices](https://docs.medusajs.com/references/js_sdk/admin/PriceList/methods/js_sdk.admin.PriceList.batchPrices/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/PriceList/methods/js_sdk.admin.PriceList.delete/index.html.md)
- [linkProducts](https://docs.medusajs.com/references/js_sdk/admin/PriceList/methods/js_sdk.admin.PriceList.linkProducts/index.html.md)
-- [updateOutboundShipping](https://docs.medusajs.com/references/js_sdk/admin/Exchange/methods/js_sdk.admin.Exchange.updateOutboundShipping/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/PriceList/methods/js_sdk.admin.PriceList.create/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/PriceList/methods/js_sdk.admin.PriceList.list/index.html.md)
-- [update](https://docs.medusajs.com/references/js_sdk/admin/PriceList/methods/js_sdk.admin.PriceList.update/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/PriceList/methods/js_sdk.admin.PriceList.retrieve/index.html.md)
+- [update](https://docs.medusajs.com/references/js_sdk/admin/PriceList/methods/js_sdk.admin.PriceList.update/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/PaymentCollection/methods/js_sdk.admin.PaymentCollection.create/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/PaymentCollection/methods/js_sdk.admin.PaymentCollection.delete/index.html.md)
+- [markAsPaid](https://docs.medusajs.com/references/js_sdk/admin/PaymentCollection/methods/js_sdk.admin.PaymentCollection.markAsPaid/index.html.md)
- [delete](https://docs.medusajs.com/references/js_sdk/admin/ProductCategory/methods/js_sdk.admin.ProductCategory.delete/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/ProductCategory/methods/js_sdk.admin.ProductCategory.create/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/ProductCategory/methods/js_sdk.admin.ProductCategory.list/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/ProductCategory/methods/js_sdk.admin.ProductCategory.retrieve/index.html.md)
-- [update](https://docs.medusajs.com/references/js_sdk/admin/ProductCategory/methods/js_sdk.admin.ProductCategory.update/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/ProductCategory/methods/js_sdk.admin.ProductCategory.list/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/ProductCategory/methods/js_sdk.admin.ProductCategory.create/index.html.md)
- [updateProducts](https://docs.medusajs.com/references/js_sdk/admin/ProductCategory/methods/js_sdk.admin.ProductCategory.updateProducts/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/PricePreference/methods/js_sdk.admin.PricePreference.delete/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/PricePreference/methods/js_sdk.admin.PricePreference.list/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/PricePreference/methods/js_sdk.admin.PricePreference.retrieve/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/PricePreference/methods/js_sdk.admin.PricePreference.create/index.html.md)
-- [update](https://docs.medusajs.com/references/js_sdk/admin/PricePreference/methods/js_sdk.admin.PricePreference.update/index.html.md)
+- [update](https://docs.medusajs.com/references/js_sdk/admin/ProductCategory/methods/js_sdk.admin.ProductCategory.update/index.html.md)
- [create](https://docs.medusajs.com/references/js_sdk/admin/ProductCollection/methods/js_sdk.admin.ProductCollection.create/index.html.md)
- [delete](https://docs.medusajs.com/references/js_sdk/admin/ProductCollection/methods/js_sdk.admin.ProductCollection.delete/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/ProductCollection/methods/js_sdk.admin.ProductCollection.retrieve/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/ProductCollection/methods/js_sdk.admin.ProductCollection.list/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/ProductCollection/methods/js_sdk.admin.ProductCollection.update/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/ProductTag/methods/js_sdk.admin.ProductTag.delete/index.html.md)
- [updateProducts](https://docs.medusajs.com/references/js_sdk/admin/ProductCollection/methods/js_sdk.admin.ProductCollection.updateProducts/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/ProductTag/methods/js_sdk.admin.ProductTag.list/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/ProductTag/methods/js_sdk.admin.ProductTag.create/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/ProductTag/methods/js_sdk.admin.ProductTag.retrieve/index.html.md)
- [batch](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.batch/index.html.md)
+- [update](https://docs.medusajs.com/references/js_sdk/admin/ProductTag/methods/js_sdk.admin.ProductTag.update/index.html.md)
+- [confirmImport](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.confirmImport/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.create/index.html.md)
- [batchVariants](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.batchVariants/index.html.md)
- [batchVariantInventoryItems](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.batchVariantInventoryItems/index.html.md)
-- [confirmImport](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.confirmImport/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/ProductCollection/methods/js_sdk.admin.ProductCollection.list/index.html.md)
- [createOption](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.createOption/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.create/index.html.md)
- [createVariant](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.createVariant/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.delete/index.html.md)
+- [deleteOption](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.deleteOption/index.html.md)
- [deleteVariant](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.deleteVariant/index.html.md)
- [export](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.export/index.html.md)
-- [deleteOption](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.deleteOption/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.delete/index.html.md)
-- [import](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.import/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.list/index.html.md)
+- [listVariants](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.listVariants/index.html.md)
- [listOptions](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.listOptions/index.html.md)
+- [import](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.import/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.retrieve/index.html.md)
- [retrieveVariant](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.retrieveVariant/index.html.md)
-- [listVariants](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.listVariants/index.html.md)
- [retrieveOption](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.retrieveOption/index.html.md)
- [updateVariant](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.updateVariant/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/ProductVariant/methods/js_sdk.admin.ProductVariant.list/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.update/index.html.md)
- [updateOption](https://docs.medusajs.com/references/js_sdk/admin/Product/methods/js_sdk.admin.Product.updateOption/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/ProductVariant/methods/js_sdk.admin.ProductVariant.list/index.html.md)
- [create](https://docs.medusajs.com/references/js_sdk/admin/ProductType/methods/js_sdk.admin.ProductType.create/index.html.md)
- [delete](https://docs.medusajs.com/references/js_sdk/admin/ProductType/methods/js_sdk.admin.ProductType.delete/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/ProductType/methods/js_sdk.admin.ProductType.retrieve/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/PaymentCollection/methods/js_sdk.admin.PaymentCollection.create/index.html.md)
-- [update](https://docs.medusajs.com/references/js_sdk/admin/ProductType/methods/js_sdk.admin.ProductType.update/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/ProductType/methods/js_sdk.admin.ProductType.list/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/PaymentCollection/methods/js_sdk.admin.PaymentCollection.delete/index.html.md)
-- [markAsPaid](https://docs.medusajs.com/references/js_sdk/admin/PaymentCollection/methods/js_sdk.admin.PaymentCollection.markAsPaid/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.create/index.html.md)
+- [update](https://docs.medusajs.com/references/js_sdk/admin/ProductType/methods/js_sdk.admin.ProductType.update/index.html.md)
- [addRules](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.addRules/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.create/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.list/index.html.md)
- [listRuleAttributes](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.listRuleAttributes/index.html.md)
-- [listRuleValues](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.listRuleValues/index.html.md)
- [delete](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.delete/index.html.md)
+- [listRuleValues](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.listRuleValues/index.html.md)
- [listRules](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.listRules/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.retrieve/index.html.md)
-- [removeRules](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.removeRules/index.html.md)
- [updateRules](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.updateRules/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/ProductTag/methods/js_sdk.admin.ProductTag.create/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/ProductTag/methods/js_sdk.admin.ProductTag.delete/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.update/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/ProductTag/methods/js_sdk.admin.ProductTag.retrieve/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/ProductTag/methods/js_sdk.admin.ProductTag.list/index.html.md)
-- [update](https://docs.medusajs.com/references/js_sdk/admin/ProductTag/methods/js_sdk.admin.ProductTag.update/index.html.md)
+- [removeRules](https://docs.medusajs.com/references/js_sdk/admin/Promotion/methods/js_sdk.admin.Promotion.removeRules/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/RefundReason/methods/js_sdk.admin.RefundReason.list/index.html.md)
- [create](https://docs.medusajs.com/references/js_sdk/admin/Region/methods/js_sdk.admin.Region.create/index.html.md)
- [delete](https://docs.medusajs.com/references/js_sdk/admin/Region/methods/js_sdk.admin.Region.delete/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/Region/methods/js_sdk.admin.Region.list/index.html.md)
+- [update](https://docs.medusajs.com/references/js_sdk/admin/Region/methods/js_sdk.admin.Region.update/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Region/methods/js_sdk.admin.Region.retrieve/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/Reservation/methods/js_sdk.admin.Reservation.delete/index.html.md)
- [create](https://docs.medusajs.com/references/js_sdk/admin/Reservation/methods/js_sdk.admin.Reservation.create/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/Reservation/methods/js_sdk.admin.Reservation.list/index.html.md)
-- [update](https://docs.medusajs.com/references/js_sdk/admin/Region/methods/js_sdk.admin.Region.update/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Reservation/methods/js_sdk.admin.Reservation.retrieve/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/Reservation/methods/js_sdk.admin.Reservation.delete/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Region/methods/js_sdk.admin.Region.retrieve/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/Reservation/methods/js_sdk.admin.Reservation.update/index.html.md)
-- [addReturnShipping](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.addReturnShipping/index.html.md)
-- [cancel](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.cancel/index.html.md)
-- [cancelReceive](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.cancelReceive/index.html.md)
-- [cancelRequest](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.cancelRequest/index.html.md)
-- [addReturnItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.addReturnItem/index.html.md)
-- [confirmReceive](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.confirmReceive/index.html.md)
-- [confirmRequest](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.confirmRequest/index.html.md)
-- [deleteReturnShipping](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.deleteReturnShipping/index.html.md)
-- [dismissItems](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.dismissItems/index.html.md)
-- [initiateRequest](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.initiateRequest/index.html.md)
-- [initiateReceive](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.initiateReceive/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.list/index.html.md)
-- [removeReceiveItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.removeReceiveItem/index.html.md)
-- [receiveItems](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.receiveItems/index.html.md)
-- [removeReturnItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.removeReturnItem/index.html.md)
-- [removeDismissItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.removeDismissItem/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.retrieve/index.html.md)
-- [updateDismissItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.updateDismissItem/index.html.md)
-- [updateReceiveItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.updateReceiveItem/index.html.md)
-- [updateReturnItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.updateReturnItem/index.html.md)
- [batchProducts](https://docs.medusajs.com/references/js_sdk/admin/SalesChannel/methods/js_sdk.admin.SalesChannel.batchProducts/index.html.md)
- [create](https://docs.medusajs.com/references/js_sdk/admin/SalesChannel/methods/js_sdk.admin.SalesChannel.create/index.html.md)
-- [updateReturnShipping](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.updateReturnShipping/index.html.md)
-- [updateRequest](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.updateRequest/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/SalesChannel/methods/js_sdk.admin.SalesChannel.list/index.html.md)
- [delete](https://docs.medusajs.com/references/js_sdk/admin/SalesChannel/methods/js_sdk.admin.SalesChannel.delete/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/SalesChannel/methods/js_sdk.admin.SalesChannel.retrieve/index.html.md)
- [updateProducts](https://docs.medusajs.com/references/js_sdk/admin/SalesChannel/methods/js_sdk.admin.SalesChannel.updateProducts/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/ReturnReason/methods/js_sdk.admin.ReturnReason.delete/index.html.md)
- [create](https://docs.medusajs.com/references/js_sdk/admin/ReturnReason/methods/js_sdk.admin.ReturnReason.create/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/ReturnReason/methods/js_sdk.admin.ReturnReason.list/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/SalesChannel/methods/js_sdk.admin.SalesChannel.list/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/ReturnReason/methods/js_sdk.admin.ReturnReason.delete/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/SalesChannel/methods/js_sdk.admin.SalesChannel.update/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/ReturnReason/methods/js_sdk.admin.ReturnReason.list/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/ReturnReason/methods/js_sdk.admin.ReturnReason.retrieve/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/ShippingOption/methods/js_sdk.admin.ShippingOption.create/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/ReturnReason/methods/js_sdk.admin.ReturnReason.update/index.html.md)
+- [addReturnItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.addReturnItem/index.html.md)
+- [addReturnShipping](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.addReturnShipping/index.html.md)
+- [cancel](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.cancel/index.html.md)
+- [cancelReceive](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.cancelReceive/index.html.md)
+- [confirmReceive](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.confirmReceive/index.html.md)
+- [confirmRequest](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.confirmRequest/index.html.md)
+- [cancelRequest](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.cancelRequest/index.html.md)
+- [deleteReturnShipping](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.deleteReturnShipping/index.html.md)
+- [initiateReceive](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.initiateReceive/index.html.md)
+- [initiateRequest](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.initiateRequest/index.html.md)
+- [dismissItems](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.dismissItems/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.list/index.html.md)
+- [receiveItems](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.receiveItems/index.html.md)
+- [removeReceiveItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.removeReceiveItem/index.html.md)
+- [removeDismissItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.removeDismissItem/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.retrieve/index.html.md)
+- [removeReturnItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.removeReturnItem/index.html.md)
+- [updateRequest](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.updateRequest/index.html.md)
+- [updateDismissItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.updateDismissItem/index.html.md)
+- [updateReceiveItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.updateReceiveItem/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/ShippingOption/methods/js_sdk.admin.ShippingOption.create/index.html.md)
+- [updateReturnShipping](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.updateReturnShipping/index.html.md)
+- [updateReturnItem](https://docs.medusajs.com/references/js_sdk/admin/Return/methods/js_sdk.admin.Return.updateReturnItem/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/ShippingOption/methods/js_sdk.admin.ShippingOption.retrieve/index.html.md)
-- [update](https://docs.medusajs.com/references/js_sdk/admin/ShippingOption/methods/js_sdk.admin.ShippingOption.update/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/ShippingOption/methods/js_sdk.admin.ShippingOption.list/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/ShippingOption/methods/js_sdk.admin.ShippingOption.delete/index.html.md)
+- [update](https://docs.medusajs.com/references/js_sdk/admin/ShippingOption/methods/js_sdk.admin.ShippingOption.update/index.html.md)
- [updateRules](https://docs.medusajs.com/references/js_sdk/admin/ShippingOption/methods/js_sdk.admin.ShippingOption.updateRules/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/ShippingProfile/methods/js_sdk.admin.ShippingProfile.create/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.create/index.html.md)
+- [createFulfillmentSet](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.createFulfillmentSet/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.delete/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.list/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.retrieve/index.html.md)
+- [update](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.update/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/ShippingOption/methods/js_sdk.admin.ShippingOption.delete/index.html.md)
+- [updateFulfillmentProviders](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.updateFulfillmentProviders/index.html.md)
+- [updateSalesChannels](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.updateSalesChannels/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Store/methods/js_sdk.admin.Store.retrieve/index.html.md)
+- [update](https://docs.medusajs.com/references/js_sdk/admin/Store/methods/js_sdk.admin.Store.update/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/Store/methods/js_sdk.admin.Store.list/index.html.md)
- [delete](https://docs.medusajs.com/references/js_sdk/admin/ShippingProfile/methods/js_sdk.admin.ShippingProfile.delete/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/ShippingProfile/methods/js_sdk.admin.ShippingProfile.create/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/ShippingProfile/methods/js_sdk.admin.ShippingProfile.update/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/ShippingProfile/methods/js_sdk.admin.ShippingProfile.retrieve/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/ShippingProfile/methods/js_sdk.admin.ShippingProfile.list/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/Store/methods/js_sdk.admin.Store.list/index.html.md)
- [create](https://docs.medusajs.com/references/js_sdk/admin/TaxRate/methods/js_sdk.admin.TaxRate.create/index.html.md)
-- [update](https://docs.medusajs.com/references/js_sdk/admin/Store/methods/js_sdk.admin.Store.update/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/TaxRate/methods/js_sdk.admin.TaxRate.list/index.html.md)
- [delete](https://docs.medusajs.com/references/js_sdk/admin/TaxRate/methods/js_sdk.admin.TaxRate.delete/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/TaxRate/methods/js_sdk.admin.TaxRate.list/index.html.md)
- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/TaxRate/methods/js_sdk.admin.TaxRate.retrieve/index.html.md)
-- [update](https://docs.medusajs.com/references/js_sdk/admin/TaxRate/methods/js_sdk.admin.TaxRate.update/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.delete/index.html.md)
-- [createFulfillmentSet](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.createFulfillmentSet/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.retrieve/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Store/methods/js_sdk.admin.Store.retrieve/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.create/index.html.md)
-- [update](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.update/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.list/index.html.md)
-- [updateSalesChannels](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.updateSalesChannels/index.html.md)
-- [updateFulfillmentProviders](https://docs.medusajs.com/references/js_sdk/admin/StockLocation/methods/js_sdk.admin.StockLocation.updateFulfillmentProviders/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/WorkflowExecution/methods/js_sdk.admin.WorkflowExecution.list/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/WorkflowExecution/methods/js_sdk.admin.WorkflowExecution.retrieve/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/TaxRegion/methods/js_sdk.admin.TaxRegion.create/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/TaxRegion/methods/js_sdk.admin.TaxRegion.delete/index.html.md)
-- [list](https://docs.medusajs.com/references/js_sdk/admin/TaxRegion/methods/js_sdk.admin.TaxRegion.list/index.html.md)
- [delete](https://docs.medusajs.com/references/js_sdk/admin/User/methods/js_sdk.admin.User.delete/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/TaxRegion/methods/js_sdk.admin.TaxRegion.retrieve/index.html.md)
- [list](https://docs.medusajs.com/references/js_sdk/admin/User/methods/js_sdk.admin.User.list/index.html.md)
- [me](https://docs.medusajs.com/references/js_sdk/admin/User/methods/js_sdk.admin.User.me/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/User/methods/js_sdk.admin.User.retrieve/index.html.md)
-- [create](https://docs.medusajs.com/references/js_sdk/admin/Upload/methods/js_sdk.admin.Upload.create/index.html.md)
-- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Upload/methods/js_sdk.admin.Upload.retrieve/index.html.md)
-- [delete](https://docs.medusajs.com/references/js_sdk/admin/Upload/methods/js_sdk.admin.Upload.delete/index.html.md)
+- [update](https://docs.medusajs.com/references/js_sdk/admin/TaxRate/methods/js_sdk.admin.TaxRate.update/index.html.md)
- [update](https://docs.medusajs.com/references/js_sdk/admin/User/methods/js_sdk.admin.User.update/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/User/methods/js_sdk.admin.User.retrieve/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/WorkflowExecution/methods/js_sdk.admin.WorkflowExecution.retrieve/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/TaxRegion/methods/js_sdk.admin.TaxRegion.create/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/WorkflowExecution/methods/js_sdk.admin.WorkflowExecution.list/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/TaxRegion/methods/js_sdk.admin.TaxRegion.delete/index.html.md)
+- [create](https://docs.medusajs.com/references/js_sdk/admin/Upload/methods/js_sdk.admin.Upload.create/index.html.md)
+- [list](https://docs.medusajs.com/references/js_sdk/admin/TaxRegion/methods/js_sdk.admin.TaxRegion.list/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/TaxRegion/methods/js_sdk.admin.TaxRegion.retrieve/index.html.md)
+- [delete](https://docs.medusajs.com/references/js_sdk/admin/Upload/methods/js_sdk.admin.Upload.delete/index.html.md)
+- [retrieve](https://docs.medusajs.com/references/js_sdk/admin/Upload/methods/js_sdk.admin.Upload.retrieve/index.html.md)
## JS SDK Auth
- [callback](https://docs.medusajs.com/references/js-sdk/auth/callback/index.html.md)
- [login](https://docs.medusajs.com/references/js-sdk/auth/login/index.html.md)
-- [logout](https://docs.medusajs.com/references/js-sdk/auth/logout/index.html.md)
- [refresh](https://docs.medusajs.com/references/js-sdk/auth/refresh/index.html.md)
-- [resetPassword](https://docs.medusajs.com/references/js-sdk/auth/resetPassword/index.html.md)
+- [logout](https://docs.medusajs.com/references/js-sdk/auth/logout/index.html.md)
- [register](https://docs.medusajs.com/references/js-sdk/auth/register/index.html.md)
+- [resetPassword](https://docs.medusajs.com/references/js-sdk/auth/resetPassword/index.html.md)
- [updateProvider](https://docs.medusajs.com/references/js-sdk/auth/updateProvider/index.html.md)
## JS SDK Store
- [cart](https://docs.medusajs.com/references/js-sdk/store/cart/index.html.md)
+- [category](https://docs.medusajs.com/references/js-sdk/store/category/index.html.md)
- [customer](https://docs.medusajs.com/references/js-sdk/store/customer/index.html.md)
- [collection](https://docs.medusajs.com/references/js-sdk/store/collection/index.html.md)
-- [category](https://docs.medusajs.com/references/js-sdk/store/category/index.html.md)
- [fulfillment](https://docs.medusajs.com/references/js-sdk/store/fulfillment/index.html.md)
- [order](https://docs.medusajs.com/references/js-sdk/store/order/index.html.md)
- [region](https://docs.medusajs.com/references/js-sdk/store/region/index.html.md)
-- [product](https://docs.medusajs.com/references/js-sdk/store/product/index.html.md)
- [payment](https://docs.medusajs.com/references/js-sdk/store/payment/index.html.md)
+- [product](https://docs.medusajs.com/references/js-sdk/store/product/index.html.md)
# Configure Medusa Backend
@@ -52743,65 +53504,6 @@ export default ProductWidget
```
-# Container - Admin Components
-
-The Medusa Admin wraps each section of a page in a container.
-
-
-
-To create a component that uses the same container styling in your widgets or UI routes, create the file `src/admin/components/container.tsx` with the following content:
-
-```tsx
-import {
- Container as UiContainer,
- clx,
-} from "@medusajs/ui"
-
-type ContainerProps = React.ComponentProps
-
-export const Container = (props: ContainerProps) => {
- return (
-
- )
-}
-```
-
-The `Container` component re-uses the component from the [Medusa UI package](https://docs.medusajs.com/ui/components/container/index.html.md) and applies to it classes to match the Medusa Admin's design conventions.
-
-***
-
-## Example
-
-Use that `Container` component in any widget or UI route.
-
-For example, create the widget `src/admin/widgets/product-widget.tsx` with the following content:
-
-```tsx title="src/admin/widgets/product-widget.tsx"
-import { defineWidgetConfig } from "@medusajs/admin-sdk"
-import { Container } from "../components/container"
-import { Header } from "../components/header"
-
-const ProductWidget = () => {
- return (
-
-
-
- )
-}
-
-export const config = defineWidgetConfig({
- zone: "product.details.before",
-})
-
-export default ProductWidget
-```
-
-This widget also uses a [Header](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/admin-components/components/header/index.html.md) custom component.
-
-
# Data Table - Admin Components
This component is available after [Medusa v2.4.0+](https://github.com/medusajs/medusa/releases/tag/v2.4.0).
@@ -53862,6 +54564,303 @@ This component uses the [Container](https://docs.medusajs.com/Users/shahednasser
It will add at the top of a product's details page a new section, and in its header you'll find an "Edit Item" button. If you click on it, it will open the drawer with your form.
+# Container - Admin Components
+
+The Medusa Admin wraps each section of a page in a container.
+
+
+
+To create a component that uses the same container styling in your widgets or UI routes, create the file `src/admin/components/container.tsx` with the following content:
+
+```tsx
+import {
+ Container as UiContainer,
+ clx,
+} from "@medusajs/ui"
+
+type ContainerProps = React.ComponentProps
+
+export const Container = (props: ContainerProps) => {
+ return (
+
+ )
+}
+```
+
+The `Container` component re-uses the component from the [Medusa UI package](https://docs.medusajs.com/ui/components/container/index.html.md) and applies to it classes to match the Medusa Admin's design conventions.
+
+***
+
+## Example
+
+Use that `Container` component in any widget or UI route.
+
+For example, create the widget `src/admin/widgets/product-widget.tsx` with the following content:
+
+```tsx title="src/admin/widgets/product-widget.tsx"
+import { defineWidgetConfig } from "@medusajs/admin-sdk"
+import { Container } from "../components/container"
+import { Header } from "../components/header"
+
+const ProductWidget = () => {
+ return (
+
+
+
+ )
+}
+
+export const config = defineWidgetConfig({
+ zone: "product.details.before",
+})
+
+export default ProductWidget
+```
+
+This widget also uses a [Header](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/admin-components/components/header/index.html.md) custom component.
+
+
+# Section Row - Admin Components
+
+The Medusa Admin often shows information in rows of label-values, such as when showing a product's details.
+
+
+
+To create a component that shows information in the same structure, create the file `src/admin/components/section-row.tsx` with the following content:
+
+```tsx title="src/admin/components/section-row.tsx"
+import { Text, clx } from "@medusajs/ui"
+
+export type SectionRowProps = {
+ title: string
+ value?: React.ReactNode | string | null
+ actions?: React.ReactNode
+}
+
+export const SectionRow = ({ title, value, actions }: SectionRowProps) => {
+ const isValueString = typeof value === "string" || !value
+
+ return (
+
+ )
+}
+```
+
+The `SectionRow` component shows a title and a value in the same row.
+
+It accepts the following props:
+
+- title: (\`string\`) The title to show on the left side.
+- value: (\`React.ReactNode\` \\| \`string\` \\| \`null\`) The value to show on the right side.
+- actions: (\`React.ReactNode\`) The actions to show at the end of the row.
+
+***
+
+## Example
+
+Use the `SectionRow` component in any widget or UI route.
+
+For example, create the widget `src/admin/widgets/product-widget.tsx` with the following content:
+
+```tsx title="src/admin/widgets/product-widget.tsx"
+import { defineWidgetConfig } from "@medusajs/admin-sdk"
+import { Container } from "../components/container"
+import { Header } from "../components/header"
+import { SectionRow } from "../components/section-row"
+
+const ProductWidget = () => {
+ return (
+
+
+
+
+ )
+}
+
+export const config = defineWidgetConfig({
+ zone: "product.details.before",
+})
+
+export default ProductWidget
+```
+
+This widget also uses the [Container](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/admin-components/components/container/index.html.md) and [Header](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/admin-components/components/header/index.html.md) custom component.
+
+
+# Header - Admin Components
+
+Each section in the Medusa Admin has a header with a title, and optionally a subtitle with buttons to perform an action.
+
+
+
+To create a component that uses the same header styling and structure, create the file `src/admin/components/header.tsx` with the following content:
+
+```tsx title="src/admin/components/header.tsx"
+import { Heading, Button, Text } from "@medusajs/ui"
+import React from "react"
+import { Link, LinkProps } from "react-router-dom"
+import { ActionMenu, ActionMenuProps } from "./action-menu"
+
+export type HeadingProps = {
+ title: string
+ subtitle?: string
+ actions?: (
+ {
+ type: "button",
+ props: React.ComponentProps
+ link?: LinkProps
+ } |
+ {
+ type: "action-menu"
+ props: ActionMenuProps
+ } |
+ {
+ type: "custom"
+ children: React.ReactNode
+ }
+ )[]
+}
+
+export const Header = ({
+ title,
+ subtitle,
+ actions = [],
+}: HeadingProps) => {
+ return (
+
+ )
+}
+```
+
+The `Header` component shows a title, and optionally a subtitle and action buttons.
+
+The component also uses the [Action Menu](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/admin-components/components/action-menu/index.html.md) custom component.
+
+It accepts the following props:
+
+- title: (\`string\`) The section's title.
+- subtitle: (\`string\`) The section's subtitle.
+- actions: (\`object\[]\`) An array of actions to show.
+
+ - type: (\`button\` \\| \`action-menu\` \\| \`custom\`) The type of action to add.
+
+ \- If its value is \`button\`, it'll show a button that can have a link or an on-click action.
+
+ \- If its value is \`action-menu\`, it'll show a three dot icon with a dropdown of actions.
+
+ \- If its value is \`custom\`, you can pass any React nodes to render.
+
+ - props: (object)
+
+ - children: (React.ReactNode) This property is only accepted if \`type\` is \`custom\`. Its content is rendered as part of the actions.
+
+***
+
+## Example
+
+Use the `Header` component in any widget or UI route.
+
+For example, create the widget `src/admin/widgets/product-widget.tsx` with the following content:
+
+```tsx title="src/admin/widgets/product-widget.tsx"
+import { defineWidgetConfig } from "@medusajs/admin-sdk"
+import { Container } from "../components/container"
+import { Header } from "../components/header"
+
+const ProductWidget = () => {
+ return (
+
+ {
+ alert("You clicked the button.")
+ },
+ },
+ },
+ ]}
+ />
+
+ )
+}
+
+export const config = defineWidgetConfig({
+ zone: "product.details.before",
+})
+
+export default ProductWidget
+```
+
+This widget also uses a [Container](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/admin-components/components/container/index.html.md) custom component.
+
+
# JSON View - Admin Components
Detail pages in the Medusa Admin show a JSON section to view the current page's details in JSON format.
@@ -54090,244 +55089,6 @@ export default ProductWidget
This shows the JSON section at the top of the product page, passing it the object `{ name: "John" }`.
-# Header - Admin Components
-
-Each section in the Medusa Admin has a header with a title, and optionally a subtitle with buttons to perform an action.
-
-
-
-To create a component that uses the same header styling and structure, create the file `src/admin/components/header.tsx` with the following content:
-
-```tsx title="src/admin/components/header.tsx"
-import { Heading, Button, Text } from "@medusajs/ui"
-import React from "react"
-import { Link, LinkProps } from "react-router-dom"
-import { ActionMenu, ActionMenuProps } from "./action-menu"
-
-export type HeadingProps = {
- title: string
- subtitle?: string
- actions?: (
- {
- type: "button",
- props: React.ComponentProps
- link?: LinkProps
- } |
- {
- type: "action-menu"
- props: ActionMenuProps
- } |
- {
- type: "custom"
- children: React.ReactNode
- }
- )[]
-}
-
-export const Header = ({
- title,
- subtitle,
- actions = [],
-}: HeadingProps) => {
- return (
-
- )
-}
-```
-
-The `Header` component shows a title, and optionally a subtitle and action buttons.
-
-The component also uses the [Action Menu](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/admin-components/components/action-menu/index.html.md) custom component.
-
-It accepts the following props:
-
-- title: (\`string\`) The section's title.
-- subtitle: (\`string\`) The section's subtitle.
-- actions: (\`object\[]\`) An array of actions to show.
-
- - type: (\`button\` \\| \`action-menu\` \\| \`custom\`) The type of action to add.
-
- \- If its value is \`button\`, it'll show a button that can have a link or an on-click action.
-
- \- If its value is \`action-menu\`, it'll show a three dot icon with a dropdown of actions.
-
- \- If its value is \`custom\`, you can pass any React nodes to render.
-
- - props: (object)
-
- - children: (React.ReactNode) This property is only accepted if \`type\` is \`custom\`. Its content is rendered as part of the actions.
-
-***
-
-## Example
-
-Use the `Header` component in any widget or UI route.
-
-For example, create the widget `src/admin/widgets/product-widget.tsx` with the following content:
-
-```tsx title="src/admin/widgets/product-widget.tsx"
-import { defineWidgetConfig } from "@medusajs/admin-sdk"
-import { Container } from "../components/container"
-import { Header } from "../components/header"
-
-const ProductWidget = () => {
- return (
-
- {
- alert("You clicked the button.")
- },
- },
- },
- ]}
- />
-
- )
-}
-
-export const config = defineWidgetConfig({
- zone: "product.details.before",
-})
-
-export default ProductWidget
-```
-
-This widget also uses a [Container](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/admin-components/components/container/index.html.md) custom component.
-
-
-# Section Row - Admin Components
-
-The Medusa Admin often shows information in rows of label-values, such as when showing a product's details.
-
-
-
-To create a component that shows information in the same structure, create the file `src/admin/components/section-row.tsx` with the following content:
-
-```tsx title="src/admin/components/section-row.tsx"
-import { Text, clx } from "@medusajs/ui"
-
-export type SectionRowProps = {
- title: string
- value?: React.ReactNode | string | null
- actions?: React.ReactNode
-}
-
-export const SectionRow = ({ title, value, actions }: SectionRowProps) => {
- const isValueString = typeof value === "string" || !value
-
- return (
-
- )
-}
-```
-
-The `SectionRow` component shows a title and a value in the same row.
-
-It accepts the following props:
-
-- title: (\`string\`) The title to show on the left side.
-- value: (\`React.ReactNode\` \\| \`string\` \\| \`null\`) The value to show on the right side.
-- actions: (\`React.ReactNode\`) The actions to show at the end of the row.
-
-***
-
-## Example
-
-Use the `SectionRow` component in any widget or UI route.
-
-For example, create the widget `src/admin/widgets/product-widget.tsx` with the following content:
-
-```tsx title="src/admin/widgets/product-widget.tsx"
-import { defineWidgetConfig } from "@medusajs/admin-sdk"
-import { Container } from "../components/container"
-import { Header } from "../components/header"
-import { SectionRow } from "../components/section-row"
-
-const ProductWidget = () => {
- return (
-
-
-
-
- )
-}
-
-export const config = defineWidgetConfig({
- zone: "product.details.before",
-})
-
-export default ProductWidget
-```
-
-This widget also uses the [Container](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/admin-components/components/container/index.html.md) and [Header](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/admin-components/components/header/index.html.md) custom component.
-
-
# Table - Admin Components
If you're using [Medusa v2.4.0+](https://github.com/medusajs/medusa/releases/tag/v2.4.0), it's recommended to use the [Data Table](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/admin-components/components/data-table/index.html.md) component instead as it provides features for sorting, filtering, pagination, and more with a simpler API.
@@ -54645,6 +55406,46 @@ Some examples of method names:
The reference uses only the operation name to refer to the method.
+# delete Method - Service Factory Reference
+
+This method deletes one or more records.
+
+## Delete One Record
+
+```ts
+await postModuleService.deletePosts("123")
+```
+
+To delete one record, pass its ID as a parameter of the method.
+
+***
+
+## Delete Multiple Records
+
+```ts
+await postModuleService.deletePosts([
+ "123",
+ "321",
+])
+```
+
+To delete multiple records, pass an array of IDs as a parameter of the method.
+
+***
+
+## Delete Records Matching Filters
+
+```ts
+await postModuleService.deletePosts({
+ name: "My Post",
+})
+```
+
+To delete records matching a set of filters, pass an object of filters as a parameter.
+
+Learn more about accepted filters in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/service-factory-reference/tips/filtering/index.html.md).
+
+
# create Method - Service Factory Reference
This method creates one or more records of the data model.
@@ -54801,44 +55602,61 @@ To sort records by one or more properties, pass to the second object parameter t
The method returns an array of the first `15` records matching the filters.
-# delete Method - Service Factory Reference
+# retrieve Method - Service Factory Reference
-This method deletes one or more records.
+This method retrieves one record of the data model by its ID.
-## Delete One Record
+## Retrieve a Record
```ts
-await postModuleService.deletePosts("123")
+const post = await postModuleService.retrievePost("123")
```
-To delete one record, pass its ID as a parameter of the method.
+### Parameters
+
+Pass the ID of the record to retrieve.
+
+### Returns
+
+The method returns the record as an object.
***
-## Delete Multiple Records
+## Retrieve a Record's Relations
+
+This applies to relations between data models of the same module. To retrieve linked records of different modules, use [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md).
```ts
-await postModuleService.deletePosts([
- "123",
- "321",
-])
-```
-
-To delete multiple records, pass an array of IDs as a parameter of the method.
-
-***
-
-## Delete Records Matching Filters
-
-```ts
-await postModuleService.deletePosts({
- name: "My Post",
+const post = await postModuleService.retrievePost("123", {
+ relations: ["author"],
})
```
-To delete records matching a set of filters, pass an object of filters as a parameter.
+### Parameters
-Learn more about accepted filters in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/service-factory-reference/tips/filtering/index.html.md).
+To retrieve the data model with relations, pass as a second parameter of the method an object with the property `relations`. `relations`'s value is an array of relation names.
+
+### Returns
+
+The method returns the record as an object.
+
+***
+
+## Select Properties to Retrieve
+
+```ts
+const post = await postModuleService.retrievePost("123", {
+ select: ["id", "name"],
+})
+```
+
+### Parameters
+
+By default, all of the record's properties are retrieved. To select specific ones, pass in the second object parameter a `select` property. Its value is an array of property names.
+
+### Returns
+
+The method returns the record as an object.
# restore Method - Service Factory Reference
@@ -54928,273 +55746,6 @@ restoredPosts = {
```
-# retrieve Method - Service Factory Reference
-
-This method retrieves one record of the data model by its ID.
-
-## Retrieve a Record
-
-```ts
-const post = await postModuleService.retrievePost("123")
-```
-
-### Parameters
-
-Pass the ID of the record to retrieve.
-
-### Returns
-
-The method returns the record as an object.
-
-***
-
-## Retrieve a Record's Relations
-
-This applies to relations between data models of the same module. To retrieve linked records of different modules, use [Query](https://docs.medusajs.com/docs/learn/fundamentals/module-links/query/index.html.md).
-
-```ts
-const post = await postModuleService.retrievePost("123", {
- relations: ["author"],
-})
-```
-
-### Parameters
-
-To retrieve the data model with relations, pass as a second parameter of the method an object with the property `relations`. `relations`'s value is an array of relation names.
-
-### Returns
-
-The method returns the record as an object.
-
-***
-
-## Select Properties to Retrieve
-
-```ts
-const post = await postModuleService.retrievePost("123", {
- select: ["id", "name"],
-})
-```
-
-### Parameters
-
-By default, all of the record's properties are retrieved. To select specific ones, pass in the second object parameter a `select` property. Its value is an array of property names.
-
-### Returns
-
-The method returns the record as an object.
-
-
-# update Method - Service Factory Reference
-
-This method updates one or more records of the data model.
-
-## Update One Record
-
-```ts
-const post = await postModuleService.updatePosts({
- id: "123",
- name: "My Post",
-})
-```
-
-### Parameters
-
-To update one record, pass an object that at least has an `id` property, identifying the ID of the record to update.
-
-You can pass in the same object any other properties to update.
-
-### Returns
-
-The method returns the updated record as an object.
-
-***
-
-## Update Multiple Records
-
-```ts
-const posts = await postModuleService.updatePosts([
- {
- id: "123",
- name: "My Post",
- },
- {
- id: "321",
- published_at: new Date(),
- },
-])
-```
-
-### Parameters
-
-To update multiple records, pass an array of objects. Each object has at least an `id` property, identifying the ID of the record to update.
-
-You can pass in each object any other properties to update.
-
-### Returns
-
-The method returns an array of objects of updated records.
-
-***
-
-## Update Records Matching a Filter
-
-```ts
-const posts = await postModuleService.updatePosts({
- selector: {
- name: "My Post",
- },
- data: {
- published_at: new Date(),
- },
-})
-```
-
-### Parameters
-
-To update records that match specified filters, pass as a parameter an object having two properties:
-
-- `selector`: An object of filters that a record must match to be updated.
-- `data`: An object of the properties to update in every record that match the filters in `selector`.
-
-In the example above, you update the `published_at` property of every post record whose name is `My Post`.
-
-Learn more about accepted filters in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/service-factory-reference/tips/filtering/index.html.md).
-
-### Returns
-
-The method returns an array of objects of updated records.
-
-***
-
-## Multiple Record Updates with Filters
-
-```ts
-const posts = await postModuleService.updatePosts([
- {
- selector: {
- name: "My Post",
- },
- data: {
- published_at: new Date(),
- },
- },
- {
- selector: {
- name: "Another Post",
- },
- data: {
- metadata: {
- external_id: "123",
- },
- },
- },
-])
-```
-
-### Parameters
-
-To update records matching different sets of filters, pass an array of objects, each having two properties:
-
-- `selector`: An object of filters that a record must match to be updated.
-- `data`: An object of the properties to update in every record that match the filters in `selector`.
-
-In the example above, you update the `published_at` property of post records whose name is `My Post`, and update the `metadata` property of post records whose name is `Another Post`.
-
-Learn more about accepted filters in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/service-factory-reference/tips/filtering/index.html.md).
-
-### Returns
-
-The method returns an array of objects of updated records.
-
-
-# softDelete Method - Service Factory Reference
-
-This method soft deletes one or more records of the data model.
-
-## Soft Delete One Record
-
-```ts
-const deletedPosts = await postModuleService.softDeletePosts(
- "123"
-)
-```
-
-### Parameters
-
-To soft delete a record, pass its ID as a parameter of the method.
-
-### Returns
-
-The method returns an object, whose keys are of the format `{camel_case_data_model_name}_id`, and their values are arrays of soft-deleted records' IDs.
-
-For example, the returned object of the above example is:
-
-```ts
-deletedPosts = {
- post_id: ["123"],
-}
-```
-
-***
-
-## Soft Delete Multiple Records
-
-```ts
-const deletedPosts = await postModuleService.softDeletePosts([
- "123",
- "321",
-])
-```
-
-### Parameters
-
-To soft delete multiple records, pass an array of IDs as a parameter of the method.
-
-### Returns
-
-The method returns an object, whose keys are of the format `{camel_case_data_model_name}_id`, and their values are arrays of soft-deleted records' IDs.
-
-For example, the returned object of the above example is:
-
-```ts
-deletedPosts = {
- post_id: [
- "123",
- "321",
- ],
-}
-```
-
-***
-
-## Soft Delete Records Matching Filters
-
-```ts
-const deletedPosts = await postModuleService.softDeletePosts({
- name: "My Post",
-})
-```
-
-### Parameters
-
-To soft delete records matching a set of filters, pass an object of filters as a parameter.
-
-Learn more about accepted filters in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/service-factory-reference/tips/filtering/index.html.md).
-
-### Returns
-
-The method returns an object, whose keys are of the format `{camel_case_data_model_name}_id`, and their values are arrays of soft-deleted records' IDs.
-
-For example, the returned object of the above example is:
-
-```ts
-deletedPosts = {
- post_id: ["123"],
-}
-```
-
-
# listAndCount Method - Service Factory Reference
This method retrieves a list of records with the total count.
@@ -55331,6 +55882,129 @@ The method returns an array with two items:
2. The second is the total count of records.
+# update Method - Service Factory Reference
+
+This method updates one or more records of the data model.
+
+## Update One Record
+
+```ts
+const post = await postModuleService.updatePosts({
+ id: "123",
+ name: "My Post",
+})
+```
+
+### Parameters
+
+To update one record, pass an object that at least has an `id` property, identifying the ID of the record to update.
+
+You can pass in the same object any other properties to update.
+
+### Returns
+
+The method returns the updated record as an object.
+
+***
+
+## Update Multiple Records
+
+```ts
+const posts = await postModuleService.updatePosts([
+ {
+ id: "123",
+ name: "My Post",
+ },
+ {
+ id: "321",
+ published_at: new Date(),
+ },
+])
+```
+
+### Parameters
+
+To update multiple records, pass an array of objects. Each object has at least an `id` property, identifying the ID of the record to update.
+
+You can pass in each object any other properties to update.
+
+### Returns
+
+The method returns an array of objects of updated records.
+
+***
+
+## Update Records Matching a Filter
+
+```ts
+const posts = await postModuleService.updatePosts({
+ selector: {
+ name: "My Post",
+ },
+ data: {
+ published_at: new Date(),
+ },
+})
+```
+
+### Parameters
+
+To update records that match specified filters, pass as a parameter an object having two properties:
+
+- `selector`: An object of filters that a record must match to be updated.
+- `data`: An object of the properties to update in every record that match the filters in `selector`.
+
+In the example above, you update the `published_at` property of every post record whose name is `My Post`.
+
+Learn more about accepted filters in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/service-factory-reference/tips/filtering/index.html.md).
+
+### Returns
+
+The method returns an array of objects of updated records.
+
+***
+
+## Multiple Record Updates with Filters
+
+```ts
+const posts = await postModuleService.updatePosts([
+ {
+ selector: {
+ name: "My Post",
+ },
+ data: {
+ published_at: new Date(),
+ },
+ },
+ {
+ selector: {
+ name: "Another Post",
+ },
+ data: {
+ metadata: {
+ external_id: "123",
+ },
+ },
+ },
+])
+```
+
+### Parameters
+
+To update records matching different sets of filters, pass an array of objects, each having two properties:
+
+- `selector`: An object of filters that a record must match to be updated.
+- `data`: An object of the properties to update in every record that match the filters in `selector`.
+
+In the example above, you update the `published_at` property of post records whose name is `My Post`, and update the `metadata` property of post records whose name is `Another Post`.
+
+Learn more about accepted filters in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/service-factory-reference/tips/filtering/index.html.md).
+
+### Returns
+
+The method returns an array of objects of updated records.
+
+
# Filter Records - Service Factory Reference
Many of the service factory's generated methods allow passing filters to perform an operation, such as to update or delete records matching the filters.
@@ -55589,6 +56263,93 @@ In the example above, posts are retrieved if they meet either of the following c
By combining `and` and `or` conditions, you can create complex filters to retrieve records that meet specific criteria.
+# softDelete Method - Service Factory Reference
+
+This method soft deletes one or more records of the data model.
+
+## Soft Delete One Record
+
+```ts
+const deletedPosts = await postModuleService.softDeletePosts(
+ "123"
+)
+```
+
+### Parameters
+
+To soft delete a record, pass its ID as a parameter of the method.
+
+### Returns
+
+The method returns an object, whose keys are of the format `{camel_case_data_model_name}_id`, and their values are arrays of soft-deleted records' IDs.
+
+For example, the returned object of the above example is:
+
+```ts
+deletedPosts = {
+ post_id: ["123"],
+}
+```
+
+***
+
+## Soft Delete Multiple Records
+
+```ts
+const deletedPosts = await postModuleService.softDeletePosts([
+ "123",
+ "321",
+])
+```
+
+### Parameters
+
+To soft delete multiple records, pass an array of IDs as a parameter of the method.
+
+### Returns
+
+The method returns an object, whose keys are of the format `{camel_case_data_model_name}_id`, and their values are arrays of soft-deleted records' IDs.
+
+For example, the returned object of the above example is:
+
+```ts
+deletedPosts = {
+ post_id: [
+ "123",
+ "321",
+ ],
+}
+```
+
+***
+
+## Soft Delete Records Matching Filters
+
+```ts
+const deletedPosts = await postModuleService.softDeletePosts({
+ name: "My Post",
+})
+```
+
+### Parameters
+
+To soft delete records matching a set of filters, pass an object of filters as a parameter.
+
+Learn more about accepted filters in [this documentation](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/service-factory-reference/tips/filtering/index.html.md).
+
+### Returns
+
+The method returns an object, whose keys are of the format `{camel_case_data_model_name}_id`, and their values are arrays of soft-deleted records' IDs.
+
+For example, the returned object of the above example is:
+
+```ts
+deletedPosts = {
+ post_id: ["123"],
+}
+```
+
+
Just Getting Started?
@@ -56047,125 +56808,6 @@ How to install and setup Medusa UI.
-# Medusa Admin Extension
-
-How to install and use Medusa UI for building Admin extensions.
-
-## Installation
-
-***
-
-The `@medusajs/ui` package is a already installed as a dependency of the `@medusajs/admin` package. Due to this you can simply import the package and use it in your local Admin extensions.
-
-If you are building a Admin extension as part of a Medusa plugin, you can install the package as a dependency of your plugin.
-
-```bash
-npm install @medusajs/ui
-```
-
-## Configuration
-
-***
-
-The configuration of the UI package is handled by the `@medusajs/admin` package. Therefore, you do not need to any additional configuration to use the UI package in your Admin extensions.
-
-
-# Standalone Project
-
-How to install and use Medusa UI in a standalone project.
-
-## Installation
-
-***
-
-Medusa UI is a React UI library and while it's intended for usage within Medusa projects, it can also be used in any React project.
-
-### Install Medusa UI
-
-Install the React UI library with the following command:
-
-```bash
-npm install @medusajs/ui
-```
-
-### Configuring Tailwind CSS
-
-The components are styled using Tailwind CSS, and in order to use them, you will need to install Tailwind CSS in your project as well.
-For more information on how to install Tailwind CSS, please refer to the [Tailwind CSS documentation](https://tailwindcss.com/docs/installation).
-
-All of the classes used for Medusa UI are shipped as a Tailwind CSS customization.
-You can install it with the following command:
-
-```bash
-npm install @medusajs/ui-preset
-```
-
-After you have installed Tailwind CSS and the Medusa UI preset, you need to add the following to your `tailwind.config.js`file:
-
-```tsx
-module.exports = {
- presets: [require("@medusajs/ui-preset")],
- // ...
-}
-```
-
-In order for the styles to be applied correctly to the components, you will also need to ensure that
-`@medusajs/ui` is included in the content field of your `tailwind.config.js` file:
-
-```tsx
-module.exports = {
- content: [
- // ...
- "./node_modules/@medusajs/ui/dist/**/*.{js,jsx,ts,tsx}",
- ],
- // ...
-}
-```
-
-If you are working within a monorepo, you may need to add the path to the `@medusajs/ui` package in your `tailwind.config.js` like so:
-
-```tsx
-const path = require("path")
-
-const uiPath = path.resolve(
- require.resolve("@medusajs/ui"),
- "../..",
- "\*_/_.{js,jsx,ts,tsx}"
-)
-
-module.exports = {
- content: [
- // ...
- uiPath,
- ],
- // ...
-}
-
-```
-
-## Start building
-
-***
-
-You are now ready to start building your application with Medusa UI. You can import the components like so:
-
-```tsx
-import { Button, Drawer } from "@medusajs/ui"
-```
-
-## Updating UI Packages
-
-***
-
-Medusa's design-system packages, including `@medusajs/ui`, `@medusajs/ui-preset`, and `@medusajs/ui-icons`, are versioned independently. However, they're still part of the latest Medusa release. So, you can browse the [release notes](https://github.com/medusajs/medusa/releases) to see if there are any breaking changes to these packages.
-
-To update these packages, update their version in your `package.json` file and re-install dependencies. For example:
-
-```bash
-npm install @medusajs/ui
-```
-
-
# Alert
A component for displaying important messages.
@@ -62555,6 +63197,125 @@ If you're using the `Tooltip` component in a project other than the Medusa Admin
- disableHoverableContent: (boolean) When \`true\`, trying to hover the content will result in the tooltip closing as the pointer leaves the trigger.
+# Medusa Admin Extension
+
+How to install and use Medusa UI for building Admin extensions.
+
+## Installation
+
+***
+
+The `@medusajs/ui` package is a already installed as a dependency of the `@medusajs/admin` package. Due to this you can simply import the package and use it in your local Admin extensions.
+
+If you are building a Admin extension as part of a Medusa plugin, you can install the package as a dependency of your plugin.
+
+```bash
+npm install @medusajs/ui
+```
+
+## Configuration
+
+***
+
+The configuration of the UI package is handled by the `@medusajs/admin` package. Therefore, you do not need to any additional configuration to use the UI package in your Admin extensions.
+
+
+# Standalone Project
+
+How to install and use Medusa UI in a standalone project.
+
+## Installation
+
+***
+
+Medusa UI is a React UI library and while it's intended for usage within Medusa projects, it can also be used in any React project.
+
+### Install Medusa UI
+
+Install the React UI library with the following command:
+
+```bash
+npm install @medusajs/ui
+```
+
+### Configuring Tailwind CSS
+
+The components are styled using Tailwind CSS, and in order to use them, you will need to install Tailwind CSS in your project as well.
+For more information on how to install Tailwind CSS, please refer to the [Tailwind CSS documentation](https://tailwindcss.com/docs/installation).
+
+All of the classes used for Medusa UI are shipped as a Tailwind CSS customization.
+You can install it with the following command:
+
+```bash
+npm install @medusajs/ui-preset
+```
+
+After you have installed Tailwind CSS and the Medusa UI preset, you need to add the following to your `tailwind.config.js`file:
+
+```tsx
+module.exports = {
+ presets: [require("@medusajs/ui-preset")],
+ // ...
+}
+```
+
+In order for the styles to be applied correctly to the components, you will also need to ensure that
+`@medusajs/ui` is included in the content field of your `tailwind.config.js` file:
+
+```tsx
+module.exports = {
+ content: [
+ // ...
+ "./node_modules/@medusajs/ui/dist/**/*.{js,jsx,ts,tsx}",
+ ],
+ // ...
+}
+```
+
+If you are working within a monorepo, you may need to add the path to the `@medusajs/ui` package in your `tailwind.config.js` like so:
+
+```tsx
+const path = require("path")
+
+const uiPath = path.resolve(
+ require.resolve("@medusajs/ui"),
+ "../..",
+ "\*_/_.{js,jsx,ts,tsx}"
+)
+
+module.exports = {
+ content: [
+ // ...
+ uiPath,
+ ],
+ // ...
+}
+
+```
+
+## Start building
+
+***
+
+You are now ready to start building your application with Medusa UI. You can import the components like so:
+
+```tsx
+import { Button, Drawer } from "@medusajs/ui"
+```
+
+## Updating UI Packages
+
+***
+
+Medusa's design-system packages, including `@medusajs/ui`, `@medusajs/ui-preset`, and `@medusajs/ui-icons`, are versioned independently. However, they're still part of the latest Medusa release. So, you can browse the [release notes](https://github.com/medusajs/medusa/releases) to see if there are any breaking changes to these packages.
+
+To update these packages, update their version in your `package.json` file and re-install dependencies. For example:
+
+```bash
+npm install @medusajs/ui
+```
+
+
# clx
Utility function for working with classNames.
diff --git a/www/apps/book/sidebar.mjs b/www/apps/book/sidebar.mjs
index dee991f3ad..7261687ebc 100644
--- a/www/apps/book/sidebar.mjs
+++ b/www/apps/book/sidebar.mjs
@@ -128,6 +128,11 @@ export const sidebars = [
type: "category",
title: "Framework",
children: [
+ {
+ type: "link",
+ path: "/learn/fundamentals/framework",
+ title: "Overview",
+ },
{
type: "link",
path: "/learn/fundamentals/medusa-container",
diff --git a/www/packages/docs-ui/src/components/SplitLists/index.tsx b/www/packages/docs-ui/src/components/SplitLists/index.tsx
new file mode 100644
index 0000000000..74757aadf8
--- /dev/null
+++ b/www/packages/docs-ui/src/components/SplitLists/index.tsx
@@ -0,0 +1,49 @@
+import React, { useMemo } from "react"
+import { Link } from "../Link"
+
+type SplitListItem = {
+ title: string
+ link: string
+ description?: string
+}
+
+export type SplitListProps = {
+ items: SplitListItem[]
+ listsNum?: number
+}
+
+export const SplitList = ({ items, listsNum = 2 }: SplitListProps) => {
+ const lists = useMemo(() => {
+ const lists: SplitListItem[][] = new Array(listsNum).fill(0).map(() => [])
+ // Split the items into listsNum lists
+ // by pushing each item into the list at index i % listsNum
+ // where i is the index of the item in the items array
+ // This will create a round-robin distribution of the items
+ // across the lists
+ // For example, if items = [1, 2, 3, 4, 5] and listsNum = 2
+ // the result will be [[1, 3, 5], [2, 4]]
+ items.forEach((item, index) => {
+ lists[index % listsNum].push(item)
+ })
+ return lists
+ }, [items, listsNum])
+
+ return (
+