1 ---
2 products:
3 - product
4 - pricing
5 - cart
6 - order
7 - inventory
8 ---
9
10 import { Prerequisites } from "docs-ui"
11
12 export const ogImage = "https://res.cloudinary.com/dza7lstvk/image/upload/v1740556002/Medusa%20Resources/erp-guide_sucmxz.jpg"
13
14 export const metadata = {
15 title: `Integrate ERP with Medusa`,
16 openGraph: {
17 images: [
18 {
19 url: ogImage,
20 width: 1600,
21 height: 836,
22 type: "image/jpeg"
23 }
24 ],
25 },
26 twitter: {
27 images: [
28 {
29 url: ogImage,
30 width: 1600,
31 height: 836,
32 type: "image/jpeg"
33 }
34 ]
35 }
36 }
37
38 # {metadata.title}
39
40 In this recipe, you'll learn about the general approach to integrating an ERP system with Medusa.
41
42 Businesses often rely on an ERP system to centralize their data and custom business rules and operations. This includes using the ERP to store special product prices, manage custom business rules that change how their customers make purchases, and handle the fulfillment and processing of orders.
43
44 When integrating the ERP system with other ecommerce platforms, you'll face complications maintaining data consistency across systems and customizing the platform's existing flows to accommodate the ERP system's data and operations. For example, the ecommerce platform may not support purchasing products with custom pricing or restricting certain products from purchase under certain conditions.
45
46 The Medusa Framework solves these challenges by giving you a durable execution engine to orchestrate operations through custom flows, and the flexibility to customize the platform's existing flows. You can wrap existing flows with custom logic, inject custom features into existing flows, and create new flows that interact with the ERP system and sync data between the two systems.
47
48 ![ERP Integration Illustration](https://res.cloudinary.com/dza7lstvk/image/upload/v1740470820/Medusa%20Resources/erp-medusa-integration_pxjpcx.jpg)
49
50 In this recipe, you'll learn how to implement some common use cases when integrating an ERP system with Medusa. This includes how to purchase products with custom pricing, restrict products from purchase under conditions in the ERP, sync orders to the ERP, and more.
51
52 You can use the code snippets in the recipe as a starting point for your ERP integration, making changes as necessary for your use case. You can also implement other use cases using the same Medusa concepts.
53
54 ---
55
56 ## Prerequisite: Install Medusa
57
58 If you don't have a Medusa application yet, you can install it with the following command:
59
60 <Prerequisites items={[
61 {
62 text: "Node.js v20.19.0+ or v22.12.0+",
63 link: "https://nodejs.org/en/download"
64 },
65 {
66 text: "Git CLI tool",
67 link: "https://git-scm.com/downloads"
68 },
69 {
70 text: "PostgreSQL",
71 link: "https://www.postgresql.org/download/"
72 }
73 ]} />
74
75 ```bash npx2yarnExec
76 npx create-medusa-app@latest
77 ```
78
79 You'll first be asked for the project's name. You can also optionally choose to install the [Next.js Starter Storefront](../../nextjs-starter/page.mdx).
80
81 the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory. If you chose to install the Next.js Starter Storefront, it'll be in the `apps/storefront` directory.
82
83 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.
84
85 <Note title="Ran into Errors">
86
87 Check out the [troubleshooting guides](../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
88
89 </Note>
90
91 <Note>
92
93 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
94
95 </Note>
96
97 ---
98
99 ## Integrate ERP in a Module
100
101 Before you start integrating the ERP system into existing or new flows in Medusa, you must build the integration layer that allows you to communicate with the ERP in your customizations.
102
103 In Medusa, you implement integrations or features around a single commerce domain in a [module](!docs!/learn/fundamentals/modules). A module is a reusable package that can interact with the database or external APIs. The module integrates into your Medusa application without side effects to the existing setup.
104
105 So, you can create a module that exports a class called a service, and in that service, you implement the logic to connect to your ERP system, fetch data from it, and send data to it. The service may look like this:
106
107 ```ts title="src/modules/erp/service.ts"
108 type Options = {
109 apiKey: string
110 }
111
112 export default class ErpModuleService {
113 private options: Options
114 private client
115
116 constructor({}, options: Options) {
117 this.options = options
118 // TODO initialize client that connects to ERP
119 }
120
121 async getProducts() {
122 // assuming client has a method to fetch products
123 return this.client.getProducts()
124 }
125
126 // TODO add more methods
127 }
128 ```
129
130 You can then use the module's service in the custom flows and customizations that you'll see in later sections.
131
132 ### How to Create Module
133
134 Refer to [this documentation](!docs!/learn/fundamentals/modules) on how to create a module. You can also refer to the [Odoo Integration guide](./odoo/page.mdx) as an example of how to build a module that integrates an ERP into Medusa.
135
136 The rest of this recipe assumes you have an ERP Module with some methods to retrieve products, prices, and other relevant data.
137
138 ---
139
140 ## Sync Products from ERP
141
142 If you store products in the ERP system, you want to sync them into Medusa to allow customers to purchase them. You may sync them once or periodically to keep the products in Medusa up-to-date with the ERP.
143
144 Syncing data between systems is a big challenge and it's often the pitfall of most ecommerce platforms, as you need to ensure data consistency and handle errors gracefully. Medusa solves this challenge by providing a durable execution engine to complete tasks that span multiple systems, allowing you to orchestrate your operations across systems in Medusa instead of managing it yourself.
145
146 Medusa's workflows are a series of queries and actions, called steps, that complete a task. You construct a workflow similar to how you create a JavaScript function, but with additional features like defining rollback logic for each step, performing long actions asynchronously, and tracking the progress of the steps. You can then use these workflows in other customizations, such as:
147
148 - [API routes](!docs!/learn/fundamentals/api-routes) to allow clients to trigger the workflow's execution.
149 - [Subscribers](!docs!/learn/fundamentals/events-and-subscribers) to trigger the workflow when an event occurs.
150 - [Scheduled jobs](!docs!/learn/fundamentals/scheduled-jobs) to run the workflow periodically.
151
152 So, to sync products from the ERP system to Medusa, you can create a custom workflow that fetches the products from the ERP system and adds them to Medusa. Then, you can create a scheduled job that syncs the products once a day, for example.
153
154 ### 1. Create Workflow to Sync Products
155
156 The workflow that syncs products from the ERP system to Medusa will have a step that fetches the product from the ERP, and another step that adds the product to Medusa.
157
158 For example, you can create the following workflow:
159
160 ```ts title="src/workflows/sync-products.ts"
161 import {
162 createStep, createWorkflow, StepResponse,
163 transform, WorkflowResponse,
164 } from "@medusajs/framework/workflows-sdk"
165 import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
166
167 const getProductsFromErpStep = createStep(
168 "get-products-from-erp",
169 async (_, { container }) => {
170 const erpModuleService = container.resolve("erp")
171
172 const products = await erpModuleService.getProducts()
173
174 return new StepResponse(products)
175 }
176 )
177
178 export const syncFromErpWorkflow = createWorkflow(
179 "sync-from-erp",
180 () => {
181 const erpProducts = getProductsFromErpStep()
182
183 const productsToCreate = transform({
184 erpProducts,
185 }, (data) => {
186 // TODO prepare ERP products to be created in Medusa
187 return data.erpProducts.map((erpProduct) => {
188 return {
189 title: erpProduct.title,
190 external_id: erpProduct.id,
191 variants: erpProduct.variants.map((variant) => ({
192 title: variant.title,
193 metadata: {
194 external_id: variant.id,
195 },
196 })),
197 // other data...
198 }
199 })
200 })
201
202 createProductsWorkflow.runAsStep({
203 input: {
204 products: productsToCreate,
205 },
206 })
207
208 return new WorkflowResponse({
209 erpProducts,
210 })
211 }
212 )
213 ```
214
215 In the above file, you first create a `getProductsFromErpStep` that resolves the ERP Module's service from the [Medusa container](!docs!/learn/fundamentals/medusa-container), which is a registry of Framework and commerce tools, including your modules, that you can access in your customizations. You can then call the `getProducts` method in the ERP Module's service to fetch the products from the ERP and return them.
216
217 Then, you create a `syncFromErpWorkflow` that executes the `getProductsFromErpStep` to get the products from the ERP, then prepare the products to be created in Medusa. For example, you can set the product's title, and specify its ID in the ERP using the `external_id` field. Also, assuming the ERP products have variants, you can map the variants to Medusa's format, setting the variant's title and its ERP ID in the metadata.
218
219 Finally, you pass the products to be created to the `createProductsWorkflow`, which is a built-in Medusa workflow that creates products.
220
221 Learn more about creating workflows and steps in [this documentation](!docs!/learn/fundamentals/workflows).
222
223 <Note title="Tip">
224
225 Find a detailed example of implementing this workflow in the [Odoo Integration guide](./odoo/page.mdx).
226
227 </Note>
228
229 ### 2. Create Scheduled Job to Sync Products
230
231 After creating a workflow, you can create a scheduled job that runs the workflow periodically to sync the products from the ERP to Medusa.
232
233 For example, you can create the following scheduled job:
234
235 ```ts title="src/scheduled-jobs/sync-products.ts"
236 import {
237 MedusaContainer,
238 } from "@medusajs/framework/types"
239 import { syncFromErpWorkflow } from "../workflows/sync-from-erp"
240
241 export default async function syncProductsJob(container: MedusaContainer) {
242 await syncFromErpWorkflow(container).run({})
243 }
244
245 export const config = {
246 name: "daily-product-sync",
247 schedule: "0 0 * * *", // Every day at midnight
248 }
249 ```
250
251 You create a scheduled job that runs once a day, executing the `syncFromErpWorkflow` to sync the products from the ERP to Medusa.
252
253 Learn more about creating scheduled jobs in [this documentation](!docs!/learn/fundamentals/scheduled-jobs).
254
255 ---
256
257 ## Retrieve Custom Prices from ERP
258
259 Consider you store products in an ERP system with fixed prices, or prices based on different conditions. You want to display these prices in the storefront and allow customers to purchase products with these prices. To do that, you need the mechanism to fetch the custom prices from the ERP system and add the product to the cart with the custom price.
260
261 To do that, you can build a custom workflow that uses the ERP Module to retrieve the custom price of a product variant, then add the product to the cart with that price.
262
263 <Note title="Tip">
264
265 You can also follow [this guide](../../examples/guides/custom-item-price/page.mdx) for a step-by-step guide on how to add items with custom prices to the cart.
266
267 </Note>
268
269 ### 1. Create Step to Get Variant Price
270
271 One of the steps in the custom add-to-cart workflow is to retrieve the custom price of the product variant from the ERP system. The step's implementation will differ based on the ERP system you're integrating. Here's a general implementation of how the step would look like:
272
273 ```ts title="src/workflows/steps/get-erp-price.ts"
274 import { MedusaError } from "@medusajs/framework/utils"
275 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
276
277 export type GetVariantErpPriceStepInput = {
278 variant_external_id: string
279 currencyCode: string
280 quantity: number
281 }
282
283 export const getVariantErpPriceStep = createStep(
284 "get-variant-erp-price",
285 async (input: GetVariantErpPriceStepInput, { container }) => {
286 const { variant_external_id, currencyCode, quantity } = input
287
288 const erpModuleService = container.resolve("erp")
289
290 const price = await erpModuleService.getErpPrice(
291 variant_external_id,
292 currencyCode
293 )
294
295 return new StepResponse(
296 price * quantity
297 )
298 }
299 )
300 ```
301
302 You create the step using the `createStep` from the Workflows SDK. The step has a function that receives the variant's ID in the ERP, the currency code, and the quantity as input.
303
304 The function then resolves the ERP Module's service from the [Medusa container](!docs!/learn/fundamentals/medusa-container) and, assuming you have a `getErpPrice` method in your ERP Module's service, you call it to retrieve that price, and return it multiplied by the quantity.
305
306 ### 2. Create Custom Add-to-Cart Workflow
307
308 You can now create the custom workflow that uses the previous step to retrieve a variant's custom price from the ERP, then add it to the cart with that price.
309
310 For example, you can create the following workflow:
311
312 ```ts title="src/workflows/add-custom-to-cart.ts"
313 import { createWorkflow, transform, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
314 import { addToCartWorkflow, useQueryGraphStep } from "@medusajs/medusa/core-flows"
315 import { getVariantErpPriceStep } from "./steps/get-erp-price"
316
317 type AddCustomToCartWorkflowInput = {
318 cart_id: string
319 item: {
320 variant_id: string
321 quantity: number
322 }
323 }
324
325 export const addCustomToCartWorkflow = createWorkflow(
326 "add-custom-to-cart",
327 ({ cart_id, item }: AddCustomToCartWorkflowInput) => {
328 // Retrieve the cart's currency code
329 const { data: carts } = useQueryGraphStep({
330 entity: "cart",
331 filters: { id: cart_id },
332 fields: ["id", "currency_code"],
333 })
334
335 // Retrieve the variant's metadata to get its ERP ID
336 const { data: variants } = useQueryGraphStep({
337 entity: "variant",
338 fields: [
339 "id",
340 "metadata",
341 ],
342 filters: {
343 id: item.variant_id,
344 },
345 options: {
346 throwIfKeyNotFound: true,
347 },
348 }).config({ name: "retrieve-variant" })
349
350 const variantExternalId = transform(
351 { variants },
352 ({ variants }) => variants[0].metadata?.external_id as string
353 )
354
355 // get the variant's price from the ERP
356 const price = getVariantErpPriceStep({
357 variant_external_id: variantExternalId,
358 currencyCode: carts[0].currency_code,
359 quantity: item.quantity,
360 })
361
362 // prepare to add the variant to the cart
363 const itemToAdd = transform({
364 item,
365 price,
366 variants,
367 }, (data) => {
368 return [{
369 ...data.item,
370 unit_price: data.price,
371 metadata: data.variants[0].metadata,
372 }]
373 })
374
375 // add the variant to the cart
376 addToCartWorkflow.runAsStep({
377 input: {
378 items: itemToAdd,
379 cart_id,
380 },
381 })
382 }
383 )
384 ```
385
386 In this workflow, you first fetch the details of the cart and the variant from the database using the [useQueryGraphStep](/references/helper-steps/useQueryGraphStep) that Medusa defines.
387
388 Then, you use the `getVariantErpPriceStep` you created to retrieve the price from the ERP. You pass it the variant's ERP ID, supposedly stored in the variant's metadata as shown in the [previous section](#1-create-workflow-to-sync-products), the cart's currency code, and the quantity of the item.
389
390 Finally, you prepare the item to be added to the cart, setting the unit price to the price you retrieved from the ERP. You then call the `addToCartWorkflow` to add the item to the cart.
391
392 ### 3. Execute Workflow in API Route
393
394 To allow clients to add products to the cart with custom prices, you can create an [API route](!docs!/learn/fundamentals/api-routes) that exposes the workflow's functionality. An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts.
395
396 For example, you can create the following API route:
397
398 ```ts title="src/api/store/cart/[id]/custom-line-items/route.ts"
399 import { MedusaRequest, MedusaResponse } from "@medusajs/framework"
400 import { HttpTypes } from "@medusajs/framework/types"
401 import { addCustomToCartWorkflow } from "../../../../../workflows/add-custom-to-cart"
402
403 export const POST = async (
404 req: MedusaRequest,
405 res: MedusaResponse
406 ) => {
407 const { id } = req.params
408 const item = req.body
409
410 await addCustomToCartWorkflow(req.scope)
411 .run({
412 input: {
413 cart_id: id,
414 item,
415 },
416 })
417
418 res.status(200).json({ success: true })
419 }
420 ```
421
422 In this API route, you receive the cart's ID from the route's parameters, and the item to be added to the cart from the request body. You then call the `addCustomToCartWorkflow` to add the item to the cart with the custom price.
423
424 Learn more about how to create an API route in [this documentation](!docs!/learn/fundamentals/api-routes). You can also add request body validation as explained in [this documentation](!docs!/learn/fundamentals/api-routes/validation).
425
426 ---
427
428 ## Restrict Purchase with Custom ERP Rules
429
430 Your ERP may store restrictions on who can purchase what products. For example, you may allow only some companies to purchase certain products.
431
432 Since Medusa implements the add-to-cart functionality within a workflow, it allows you to inject custom logic into the workflow using [workflow hooks](!docs!/learn/fundamentals/workflows/workflow-hooks). A workflow hook is a point in a workflow where you can inject a step and perform a custom functionality.
433
434 So, to implement the use case of product-purchase restriction, you can use the `validate` hook of the `addToCartWorkflow` or the [completeCartWorkflow](/references/medusa-workflows/completeCartWorkflow) to check if the customer is allowed to purchase the product. For example:
435
436 ```ts title="src/workflows/hooks/validate-purchase.ts"
437 import { MedusaError, Modules } from "@medusajs/framework/utils"
438 import { addToCartWorkflow } from "@medusajs/medusa/core-flows"
439
440 addToCartWorkflow.hooks.validate(
441 async ({ input, cart }, { container }) => {
442 const erpModuleService = container.resolve("erp")
443 const productModuleService = container.resolve(
444 Modules.PRODUCT
445 )
446 const customerModuleService = container.resolve(
447 Modules.CUSTOMER
448 )
449
450 const customer = cart.customer_id ? await customerModuleService.retrieveCustomer(cart.customer_id) : undefined
451 const productVariants = await productModuleService.listProductVariants({
452 id: input.items.map((item) => item.variant_id).filter(Boolean) as string[],
453 }, {
454 relations: ["product"],
455 })
456
457 await Promise.all(
458 productVariants.map(async (productVariant) => {
459 if (!productVariant.product?.external_id) {
460 // product isn't in ERP
461 return
462 }
463
464 const isAllowed = await erpModuleService.canCompanyPurchaseProduct(
465 productVariant.product.external_id,
466 customer?.company_name || undefined
467 )
468
469 if (!isAllowed) {
470 throw new MedusaError(
471 MedusaError.Types.NOT_ALLOWED,
472 `Company ${customer?.company_name || ""} is not allowed to purchase product ${productVariant.product.id}`
473 )
474 }
475 })
476 )
477 }
478 )
479 ```
480
481 You consume a hook using the workflow's `hooks` property. In the above example, you consume the `validate` hook of the `addToCartWorkflow` to inject a step.
482
483 In the step, you resolve the ERP Module's service, the Product Module's service, and the Customer Module's service from the [Medusa container](!docs!/learn/fundamentals/medusa-container). You then retrieve the cart's customer and the product variants to be added to the cart.
484
485 Then, for each product variant, you use a `canCompanyPurchaseProduct` method in the ERP Module's service that checks if the customer's company is allowed to purchase the product. If not, you throw a `MedusaError` with a message that the company is not allowed to purchase the product.
486
487 So, only customers who are allowed in the ERP system to purchase a product can add it to the cart.
488
489 Learn more about workflow hooks and how to consume them in [this documentation](!docs!/learn/fundamentals/workflows/workflow-hooks).
490
491 ---
492
493 ## Two-Way Order Syncing
494
495 After a customer places an order in Medusa, you may want to sync the order to the ERP system where you handle its fulfillment and processing. However, you may also want to sync the order back to Medusa, where you handle customer-service related operations, such as returns and refunds.
496
497 As explained earlier, workflows facilitate the orchestration of operations across systems while maintaining data consistency. So, you can create two workflows:
498
499 1. A workflow that syncs the order from Medusa to the ERP system. You can execute this workflow in a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that is triggered when an order is created in Medusa.
500 2. A workflow that syncs the order from the ERP system back to Medusa. Then, you can create a webhook listener in Medusa that executes the workflow, and use the webhook in the ERP system to send order updates to Medusa.
501
502 ### 1. Sync Order to ERP
503
504 To sync the order from Medusa to the ERP system, you can create a custom workflow that sends the order's details from Medusa to the ERP system. For example:
505
506 ```ts title="src/workflows/sync-order-to-erp.ts"
507 import { createStep, createWorkflow, StepResponse, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
508 import { updateOrderWorkflow, useQueryGraphStep } from "@medusajs/medusa/core-flows"
509 import { OrderDTO } from "@medusajs/framework/types"
510
511 type StepInput = {
512 order: OrderDTO
513 }
514
515 export const syncOrderToErpStep = createStep(
516 "sync-order-to-erp",
517 async ({ order }: StepInput, { container }) => {
518 const erpModuleService = container.resolve("erp")
519
520 const erpOrderId = await erpModuleService.createOrder(order)
521
522 return new StepResponse(erpOrderId, erpOrderId)
523 },
524 async (erpOrderId, { container }) => {
525 if (!erpOrderId) {
526 return
527 }
528
529 const erpModuleService = container.resolve("erp")
530 await erpModuleService.deleteOrder(erpOrderId)
531 }
532 )
533
534 type WorkflowInput = {
535 order_id: string
536 }
537
538 export const syncOrderToErpWorkflow = createWorkflow(
539 "sync-order-to-erp",
540 ({ order_id }: WorkflowInput) => {
541 // @ts-ignore
542 const { data: orders } = useQueryGraphStep({
543 entity: "order",
544 fields: [
545 "*",
546 "shipping_address.*",
547 "billing_address.*",
548 "items.*",
549 ],
550 filters: {
551 id: order_id,
552 },
553 options: {
554 throwIfKeyNotFound: true,
555 },
556 })
557
558 const erpOrderId = syncOrderToErpStep({
559 order: orders[0] as unknown as OrderDTO,
560 })
561
562 updateOrderWorkflow.runAsStep({
563 input: {
564 id: order_id,
565 user_id: "",
566 metadata: {
567 external_id: erpOrderId,
568 },
569 },
570 })
571
572 return new WorkflowResponse(erpOrderId)
573 })
574 ```
575
576 You first create a `syncOrderToErpStep` that receives an order's details, resolves the ERP Module's service from the Medusa container, and calls a `createOrder` method in the ERP Module's service that creates the order in the ERP.
577
578 Notice that you pass to `createStep` a third-parameter function. This is the compensation function that defines how to rollback changes. So, when an error occurs during the workflow's execution, the step deletes the order from the ERP system. This ensures that the data remains consistent across systems.
579
580 <Note>
581
582 Learn more about the compensation function in [this documentation](!docs!/learn/fundamentals/workflows/compensation-function).
583
584 </Note>
585
586 Then, you create a `syncOrderToErpWorkflow` that retrieves the order's details from the database using the `useQueryGraphStep`, then executes the `syncOrderToErpStep` to sync the order to the ERP system. Finally, you update the order in Medusa to set the ERP order's ID in the `metadata` field.
587
588 You can now use this workflow whenever an order is placed. To do that, you can create a subscriber that listens to the `order.created` event and executes the workflow:
589
590 ```ts title="src/subscribers/sync-order-to-erp.ts"
591 import type {
592 SubscriberArgs,
593 SubscriberConfig,
594 } from "@medusajs/framework"
595 import { syncOrderToErpWorkflow } from "../workflows/sync-order-to-erp"
596
597 export default async function productCreateHandler({
598 event: { data },
599 container,
600 }: SubscriberArgs<{ id: string }>) {
601 const { result } = await syncOrderToErpWorkflow(container)
602 .run({
603 input: {
604 order_id: data.id,
605 },
606 })
607
608 console.log(`Order synced to ERP with id: ${result}`)
609 }
610
611 export const config: SubscriberConfig = {
612 event: "order.placed",
613 }
614 ```
615
616 You create a subscriber that listens to the `order.placed` event. When the event is triggered, the subscriber executes the `syncOrderToErpWorkflow` to sync the order to the ERP system.
617
618 Learn more about events and subscribers in [this documentation](!docs!/learn/fundamentals/events-and-subscribers).
619
620 ### 2. Sync Order from ERP to Medusa
621
622 To sync the order from the ERP system back to Medusa, create first the workflow that receives the updated order data and reflects them in Medusa:
623
624 ```ts title="src/workflows/sync-order-from-erp.ts"
625 import { createWorkflow, transform, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
626 import { updateOrderWorkflow, useQueryGraphStep } from "@medusajs/medusa/core-flows"
627
628 type Input = {
629 order_erp_data: any
630 }
631
632 export const syncOrderFromErpWorkflow = createWorkflow(
633 "sync-order-from-erp",
634 ({ order_erp_data }: Input) => {
635 const { data: orders } = useQueryGraphStep({
636 entity: "order",
637 fields: ["*"],
638 filters: {
639 // @ts-ignore
640 metadata: {
641 external_id: order_erp_data.id,
642 },
643 },
644 })
645
646 const orderUpdateData = transform({
647 order_erp_data,
648 orders,
649 }, (data) => {
650 return {
651 id: data.orders[0].id,
652 user_id: "",
653 status: data.order_erp_data.status,
654 }
655 })
656
657 const order = updateOrderWorkflow.runAsStep({
658 input: orderUpdateData,
659 })
660
661 return new WorkflowResponse(order)
662 }
663 )
664 ```
665
666 In the workflow, you retrieve the order from the database using the `useQueryGraphStep`, assuming that the ERP order's ID is stored in the order's metadata. Then, you prepare the order's data to be updated in Medusa, setting the order's status to the status you received from the ERP system. Finally, you update the order using the `updateOrderWorkflow`.
667
668 You can now create an API route that receives webhook updates from the ERP system and executes the workflow:
669
670 ```ts title="src/api/erp/order-updates/route.ts"
671 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
672 import { syncOrderFromErpWorkflow } from "../../workflows/sync-order-from-erp"
673
674 export async function POST(
675 req: MedusaRequest,
676 res: MedusaResponse
677 ) {
678 const webhookData = req.rawBody
679
680 // TODO construct the order object from the webhook data
681
682 // execute the workflow
683 await syncOrderFromErpWorkflow(req.scope).run({
684 input: {
685 order_erp_data, // pass constructed order object
686 },
687 })
688 }
689 ```
690
691 In the API route, you receive the raw webhook data from the request body. You can then construct the order object from the webhook data based on the ERP system's format.
692
693 Then, you call the `syncOrderFromErpWorkflow` to sync the order from the ERP system back to Medusa.
694
695 Finally, to ensure the webhook's raw data is received, you need to configure the middleware that runs before the route handler to preserve the raw body data. To do that, add the following middleware configuration in `src/api/middlewares.ts`:
696
697 ```ts title="src/api/middlewares.ts"
698 import { defineMiddlewares } from "@medusajs/framework/http"
699
700 export default defineMiddlewares({
701 routes: [
702 {
703 method: ["POST"],
704 bodyParser: { preserveRawBody: true },
705 matcher: "/erp/order-updates",
706 },
707 ],
708 })
709 ```
710
711 You configure the body parser of `POST` requests to the `/erp/order-updates` route to preserve the raw body data.
712
713 You can now receive webhook requests from your ERP system and sync the order data back to Medusa.
714
715 <Note>
716
717 Learn more about middlewares in [this documentation](!docs!/learn/fundamentals/api-routes/middlewares).
718
719 </Note>
720
721 ---
722
723 ## Validate Inventory Availability in ERP
724
725 An ERP system often manages the inventory of products, with the ability to track the stock levels and availability of products. When a customer is purchasing a product through Medusa, you want to ensure that the product is available in the ERP system before allowing the purchase.
726
727 Similar to the [product-purchase restriction](#restrict-purchase-with-custom-erp-rules) use case, you can use the `validate` hook of the `addToCartWorkflow` or the [completeCartWorkflow](/references/medusa-workflows/completeCartWorkflow) to check the product's availability in the ERP system. For example:
728
729 ```ts title="src/workflows/hooks/validate-inventory.ts"
730 import { MedusaError, Modules } from "@medusajs/framework/utils"
731 import { addToCartWorkflow } from "@medusajs/medusa/core-flows"
732
733 addToCartWorkflow.hooks.validate(
734 async ({ input }, { container }) => {
735 const erpModuleService = container.resolve("erp")
736 const productModuleService = container.resolve(
737 Modules.PRODUCT
738 )
739
740 const productVariants = await productModuleService.listProductVariants({
741 id: input.items.map((item) => item.variant_id).filter(Boolean) as string[],
742 }, {
743 relations: ["product"],
744 })
745
746 await Promise.all(
747 productVariants.map(async (productVariant) => {
748 const erpVariant = await erpModuleService.getQty(productVariant.metadata?.external_id)
749 const item = input.items.find((item) => item.variant_id === productVariant.id)!
750
751 if (erpVariant.qty_available < item.quantity && !erpVariant.allow_out_of_stock_order) {
752 throw new MedusaError(
753 MedusaError.Types.NOT_ALLOWED,
754 `Not enough stock for product ${productVariant.product?.id}`
755 )
756 }
757 })
758 )
759 }
760 )
761 ```
762
763 You consume the `validate` hook of the `addToCartWorkflow` to inject a step function. In the step, you resolve the services of the ERP Module and the Product Module from the Medusa container. Then, you loop over the product variants to be added to the cart, and for each variant, you call a `getQty` method in the ERP Module's service to get the variant's quantity available.
764
765 If the available quantity in the ERP is less than the quantity to be added to the cart, and the ERP doesn't allow out-of-stock orders for the variant, you throw an error that the product is out of stock.
766
767 So, only products that have sufficient quantity in the ERP system can be added to the cart.
768
769 ---
770
771 ## Implement More Use Cases
772
773 The use cases covered in this guide are some common ERP integration scenarios that you can implement with Medusa. However, you can implement more use cases based on your ERP system's capabilities and your business requirements.
774
775 Refer to the [main documentation](!docs!/learn) to learn more about Medusa's concepts and how to implement customizations. You can also use the feedback form at the end of this guide to suggest more use cases you'd like to see implemented.