1 ---
2 products:
3 - product
4 ---
5
6 import { Prerequisites, WorkflowDiagram } from "docs-ui"
7
8 export const metadata = {
9 title: `Integrate Odoo with Medusa`,
10 }
11
12 # {metadata.title}
13
14 In this guide, you will learn how to implement the integration layer between Odoo and Medusa.
15
16 When you install a Medusa application, you get a fully-fledged commerce platform that supports customizations. However, your business might already be using other systems such as an ERP to centralize data and processes. The Medusa Framework facilitates integrating the ERP system and using its data to enrich your commerce platform.
17
18 Odoo is a suite of open-source business apps that covers all your business needs, including an ERP system. You can use Odoo to store products and their prices, manage orders, and more.
19
20 This guide will teach you how to implement the general integration between Medusa and Odoo. You will learn how to connect to Odoo's APIs and fetch data such as products. You can then expand on this integration to implement your business requirements. You can also refer to [this recipe](../page.mdx) to find general examples of ERP integration use cases and how to implement them.
21
22 ---
23
24 ## Step 1: Install a Medusa Application
25
26 <Prerequisites items={[
27 {
28 text: "Node.js v20.19.0+ or v22.12.0+",
29 link: "https://nodejs.org/en/download"
30 },
31 {
32 text: "Git CLI tool",
33 link: "https://git-scm.com/downloads"
34 },
35 {
36 text: "PostgreSQL",
37 link: "https://www.postgresql.org/download/"
38 }
39 ]} />
40
41 Start by installing the Medusa application on your machine with the following command:
42
43 ```bash npx2yarnExec
44 npx create-medusa-app@latest
45 ```
46
47 You will first be asked for the project's name. You can also optionally choose to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx).
48
49 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.
50
51 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.
52
53 <Note title="Ran into Errors">
54
55 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
56
57 </Note>
58
59 <Note>
60
61 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
62
63 </Note>
64
65 ---
66
67 ## Step 2: Install JSONRPC Package
68
69 [Odoo's APIs](https://www.odoo.com/documentation/18.0/developer/reference/external_api.html) are based on the XML-RPC and JSON-RPC protocols. So, to connect to Odoo's APIs, you need a JSON-RPC client library.
70
71 Run the following command in the Medusa application to install the `json-rpc-2.0` package:
72
73 ```bash npm2yarn
74 npm install json-rpc-2.0
75 ```
76
77 You will use this package in the next steps to connect to Odoo's APIs.
78
79 ---
80
81 ## Step 3: Create Odoo Module
82
83 To integrate third-party systems into Medusa, you create a custom [module](!docs!/learn/fundamentals/modules). 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.
84
85 In this step, you'll create an Odoo Module that provides the interface to connect to and interact with Odoo. You will later use this module when implementing the product syncing logic.
86
87 <Note>
88
89 Learn more about modules in [this documentation](!docs!/learn/fundamentals/modules).
90
91 </Note>
92
93 ### Create Module Directory
94
95 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/odoo`.
96
97 ![Diagram showcasing directory structure after creating the module directory](https://res.cloudinary.com/dza7lstvk/image/upload/v1740474975/Medusa%20Resources/odoo-1_en3bso.jpg)
98
99 ### Create Service
100
101 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.
102
103 Medusa registers the module's service in the [Medusa container](!docs!/learn/fundamentals/medusa-container), allowing you to easily resolve the service from other customizations and use its methods.
104
105 <Note title="What is the Medusa Container?">
106
107 The Medusa application registers resources, such as a module's service or the [logging tool](!docs!/learn/debugging-and-testing/logging), in the Medusa container so that you can resolve them from other customizations, as you'll see in later sections. Learn more about it in [this documentation](!docs!/learn/fundamentals/medusa-container).
108
109 </Note>
110
111 In this section, you'll create the Odoo Module's service and the methods necessary to connect to Odoo.
112
113 To create the service, create the file `src/modules/odoo/service.ts` with the following content:
114
115 ![Diagram showcasing directory structure after creating the service file](https://res.cloudinary.com/dza7lstvk/image/upload/v1740474976/Medusa%20Resources/odoo-2_y76dfs.jpg)
116
117 ```ts title="src/modules/odoo/service.ts"
118 import { JSONRPCClient } from "json-rpc-2.0"
119
120 type Options = {
121 url: string
122 dbName: string
123 username: string
124 apiKey: string
125 }
126
127 export default class OdooModuleService {
128 private options: Options
129 private client: JSONRPCClient
130
131 constructor({}, options: Options) {
132 this.options = options
133
134 this.client = new JSONRPCClient((jsonRPCRequest) => {
135 fetch(`${options.url}/jsonrpc`, {
136 method: "POST",
137 headers: {
138 "content-type": "application/json",
139 },
140 body: JSON.stringify(jsonRPCRequest),
141 }).then((response) => {
142 if (response.status === 200) {
143 // Use client.receive when you received a JSON-RPC response.
144 return response
145 .json()
146 .then((jsonRPCResponse) => this.client.receive(jsonRPCResponse))
147 } else if (jsonRPCRequest.id !== undefined) {
148 return Promise.reject(new Error(response.statusText))
149 }
150 })
151 })
152 }
153 }
154 ```
155
156 You create an `OdooModuleService` class that has two class properties:
157
158 1. `options`: An object that holds the Odoo Module's options. Those include the API key, URL, database name, and username. You'll learn how to pass those to the module later.
159 2. `client`: An instance of the `JSONRPCClient` class from the `json-rpc-2.0` package. You'll use this client to connect to Odoo's APIs.
160
161 The service's constructor accepts as a second parameter the module's options. So, you use those to initialize the `options` property and create the `client` property. The `client` property is initialized with a function that sends a JSON-RPC request to Odoo's API and receives the response.
162
163 Next, you will add the methods to log in and fetch data from Odoo.
164
165 ### Login Method
166
167 Before sending any request to Odoo's APIs, you need to have an authenticated UID of the user. So, you'll implement a method to retrieve that UID when it's not set.
168
169 Start by adding a `uid` property to the `OdooModuleService` class:
170
171 ```ts title="src/modules/odoo/service.ts"
172 export default class OdooModuleService {
173 private uid?: number
174 // ...
175 }
176 ```
177
178 Then, add the following `login` method:
179
180 ```ts title="src/modules/odoo/service.ts"
181 export default class OdooModuleService {
182 // ...
183 async login() {
184 this.uid = await this.client.request("call", {
185 service: "common",
186 method: "authenticate",
187 args: [
188 this.options.dbName,
189 this.options.username,
190 this.options.apiKey,
191 {},
192 ],
193 })
194 }
195 }
196 ```
197
198 The `login` method sends a JSON-RPC request to [Odoo's API to authenticate the user](https://www.odoo.com/documentation/18.0/developer/reference/external_api.html#logging-in). It uses the `client` property to send a request with the `service`, `method`, and `args` properties.
199
200 If the authentication was successful, Odoo returns a UID, which you store in the `uid` property.
201
202 ### Fetch Products Method
203
204 You can fetch many data from Odoo based on your business requirements, or create data in Odoo. For this guide, you'll only learn how to fetch products. You will use this method later to sync products from Odoo to Medusa.
205
206 First, add the following types to `src/modules/odoo/service.ts`:
207
208 ```ts title="src/modules/odoo/service.ts"
209 export type Pagination = {
210 offset?: number
211 limit?: number
212 }
213
214 export type OdooProduct = {
215 id: number
216 display_name: string
217 is_published: boolean
218 website_url: string
219 name: string
220 list_price: number
221 description: string | false
222 description_sale: string | false
223 product_variant_ids: OdooProductVariant[]
224 qty_available: number
225 location_id: number | false
226 taxes_id: number[]
227 hs_code: string | false
228 allow_out_of_stock_order: boolean
229 is_kits: boolean
230 image_1920: string
231 image_1024: string
232 image_512: string
233 image_256: string
234 image_128: string
235 attribute_line_ids: {
236 attribute_id: {
237 display_name: string
238 }
239 value_ids: {
240 display_name: string
241 }[]
242 }[]
243 currency_id: {
244 id: number
245 display_name: string
246 }
247 }
248
249 export type OdooProductVariant = Omit<
250 OdooProduct,
251 "product_variant_ids" | "attribute_line_ids"
252 > & {
253 product_template_variant_value_ids: {
254 id: number
255 name: string
256 attribute_id: {
257 display_name: string
258 }
259 }[]
260 code: string
261 }
262 ```
263
264 You define the following types:
265
266 - `Pagination`: An object that holds the pagination options for fetching products.
267 - `OdooProduct`: An object that represents an Odoo product. You define the properties that you'll fetch from Odoo's API. You can add more properties based on your business requirements.
268 - `OdooProductVariant`: An object that represents an Odoo product variant. You define the properties that you'll fetch from Odoo's API. You can add more properties based on your business requirements.
269
270 Then, add the following `listProducts` method to the `OdooModuleService` class:
271
272 ```ts title="src/modules/odoo/service.ts"
273 export default class OdooModuleService {
274 // ...
275 async listProducts(filters?: any, pagination?: Pagination) {
276 if (!this.uid) {
277 await this.login()
278 }
279
280 const { offset, limit } = pagination || { offset: 0, limit: 10 }
281
282 const ids = await this.client.request("call", {
283 service: "object",
284 method: "execute_kw",
285 args: [
286 this.options.dbName,
287 this.uid,
288 this.options.apiKey,
289 "product.template",
290 "search",
291 filters || [[
292 ["is_product_variant", "=", false],
293 ]], {
294 offset,
295 limit,
296 },
297 ],
298 })
299
300 // TODO retrieve product details based on ids
301 }
302 }
303 ```
304
305 In the `listProducts` method, you first check if the user is authenticated, and call the `login` method otherwise. Then, you send a JSON-RPC request to retrieve product IDs from Odoo with pagination and filter options. Odoo's APIs require you to first retrieve the IDs of the products and then fetch the details of each product.
306
307 To retrieve the products, replace the `TODO` with the following:
308
309 ```ts title="src/modules/odoo/service.ts"
310 // product fields to retrieve
311 const productSpecifications = {
312 id: {},
313 display_name: {},
314 is_published: {},
315 website_url: {},
316 name: {},
317 list_price: {},
318 description: {},
319 description_sale: {},
320 qty_available: {},
321 location_id: {},
322 taxes_id: {},
323 hs_code: {},
324 allow_out_of_stock_order: {},
325 is_kits: {},
326 image_1920: {},
327 image_1024: {},
328 image_512: {},
329 image_256: {},
330 currency_id: {
331 fields: {
332 display_name: {},
333 },
334 },
335 }
336
337 // retrieve products
338 const products: OdooProduct[] = await this.client.request("call", {
339 service: "object",
340 method: "execute_kw",
341 args: [
342 this.options.dbName,
343 this.uid,
344 this.options.apiKey,
345 type,
346 "web_read",
347 [ids],
348 {
349 specification: {
350 ...productSpecifications,
351 product_variant_ids: {
352 fields: {
353 ...productSpecifications,
354 product_template_variant_value_ids: {
355 fields: {
356 name: {},
357 attribute_id: {
358 fields: {
359 display_name: {},
360 },
361 },
362 },
363 context: {
364 show_attribute: false,
365 },
366 },
367 code: {},
368 },
369 context: {
370 show_code: false,
371 },
372 },
373 attribute_line_ids: {
374 fields: {
375 attribute_id: {
376 fields: {
377 display_name: {},
378 },
379 },
380 value_ids: {
381 fields: {
382 display_name: {},
383 },
384 context: {
385 show_attribute: false,
386 },
387 },
388 },
389 },
390 },
391 },
392 ],
393 })
394
395 return products
396 ```
397
398 You first define the `productSpecifications` object that holds the fields you want to fetch for each product and its variants. So, if you want to add more fields, you can add them in this object.
399
400 Then, you send a request to Odoo to fetch the products' details based on the IDs you retrieved earlier. You use the `productSpecifications` object to define the fields you want to fetch for each product and its variants. Finally, you return the fetched products.
401
402 You will use the `listProducts` method to sync products from Odoo to Medusa in the next steps.
403
404 ### Export Module Definition
405
406 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.
407
408 So, create the file `src/modules/odoo/index.ts` with the following content:
409
410 ![Diagram showcasing directory structure after creating the module definition file](https://res.cloudinary.com/dza7lstvk/image/upload/v1740475883/Medusa%20Resources/odoo-3_q5y803.jpg)
411
412 ```ts title="src/modules/odoo/index.ts"
413 import OdooModuleService from "./service"
414 import { Module } from "@medusajs/framework/utils"
415
416 export const ODOO_MODULE = "odoo"
417
418 export default Module(ODOO_MODULE, {
419 service: OdooModuleService,
420 })
421 ```
422
423 You use the `Module` function from the Modules SDK to create the module's definition. It accepts two parameters:
424
425 1. The module's name, which is `odoo`.
426 2. An object with a required property `service` indicating the module's service.
427
428 ### Add Module to Medusa's Configurations
429
430 Once you finish building the module, add it to Medusa's configurations to start using it.
431
432 In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
433
434 ```ts title="medusa-config.ts"
435 module.exports = defineConfig({
436 // ...
437 modules: [
438 {
439 resolve: "./src/modules/odoo",
440 options: {
441 url: process.env.ODOO_URL,
442 dbName: process.env.ODOO_DB_NAME,
443 username: process.env.ODOO_USERNAME,
444 apiKey: process.env.ODOO_API_KEY,
445 },
446 },
447 ],
448 })
449 ```
450
451 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. Modules that accept options also have an `options` property. You pass the options you defined in the `OdooModuleService` class to the module.
452
453 Then, set the environment variables in the `.env` file or system environment variables:
454
455 ```plain
456 ODOO_URL=https://medusa8.odoo.com
457 ODOO_DB_NAME=medusa8
458 ODOO_USERNAME=test@gmail.com # username or email
459 ODOO_API_KEY=12345...
460 ```
461
462 Where:
463
464 - `ODOO_URL`: The URL of your Odoo instance, which is of the format `https://<domain>.odoo.com`.
465 - `ODOO_DB_NAME`: The name of the database in your Odoo instance, which is the same as the domain in the URL.
466 - `ODOO_USERNAME`: The username or email of an Odoo user.
467 - `ODOO_API_KEY`: The API key of an Odoo user, or the user's password. To retrieve an API Key:
468 - On your Odoo dashboard, click on the user's avatar at the top right and choose "My Profile" from the dropdown.
469
470 ![My profile dropdown in Odoo](https://res.cloudinary.com/dza7lstvk/image/upload/v1740476295/Medusa%20Resources/Screenshot_2025-02-25_at_11.36.23_AM_h9iind.png)
471
472 - On your profile's page, click the "Account Security" tab, then the "New API Key" button.
473
474 ![Profile page in Odoo](https://res.cloudinary.com/dza7lstvk/image/upload/v1740476296/Medusa%20Resources/Screenshot_2025-02-25_at_11.36.55_AM_gl4wfu.png)
475
476 - In the pop-up that opens, enter your password.
477 - Enter the API Key's name, and set the expiration to "Persistent Key", then click the "Generate Key" button.
478
479 ![Generate key pop-up](https://res.cloudinary.com/dza7lstvk/image/upload/v1740476443/Medusa%20Resources/Screenshot_2025-02-25_at_11.40.19_AM_ntbx1c.png)
480
481 - Copy the generated API Key and use it as the `ODOO_API_KEY` environment variable's value.
482
483 You will test that the Odoo Module works as expected in the next steps.
484
485 ---
486
487 ## Step 4: Sync Products from Odoo to Medusa
488
489 There are different use cases you can implement when integrating an ERP like Odoo. One of them is syncing products from the ERP to Medusa. This way, you can manage products in Odoo and have them reflected in your commerce platform.
490
491 To implement the syncing functionality, you need to create a [workflow](!docs!/learn/fundamentals/workflows). A workflow is 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.
492
493 After defining the workflow, you can execute it in other customizations, such as periodically or when an event occurs.
494
495 In this section, you'll create a workflow that syncs products from Odoo to Medusa. Then, you'll execute that workflow once a day using a [scheduled job](!docs!/learn/fundamentals/scheduled-jobs). The workflow has the following steps:
496
497 <WorkflowDiagram
498 workflow={{
499 name: "get-products-from-erp",
500 steps: [
501 {
502 type: "step",
503 name: "getProductsFromErp",
504 description: "Fetch products from Odoo",
505 depth: 1,
506 },
507 {
508 type: "step",
509 name: "useQueryGraphStep",
510 description: "Get Medusa store configurations to use when creating the products.",
511 depth: 1,
512 link: "/references/helper-steps/useQueryGraphStep",
513 },
514 {
515 type: "step",
516 name: "useQueryGraphStep",
517 description: "Get Medusa sales channels to use when creating the products.",
518 depth: 1,
519 link: "/references/helper-steps/useQueryGraphStep",
520 },
521 {
522 type: "step",
523 name: "useQueryGraphStep",
524 description: "Get Medusa shipping profiles to use when creating the products.",
525 depth: 1,
526 link: "/references/helper-steps/useQueryGraphStep",
527 },
528 {
529 type: "step",
530 name: "createProductsWorkflow",
531 description: "Create new products in Medusa.",
532 depth: 1,
533 link: "/references/medusa-workflows/createProductsWorkflow",
534 },
535 {
536 type: "step",
537 name: "updateProductsWorkflow",
538 description: "Update existing products in Medusa.",
539 depth: 1,
540 link: "/references/medusa-workflows/updateProductsWorkflow",
541 }
542 ]
543 }}
544 hideLegend
545 />
546
547 The only step you'll need to implement is the `getProductsFromErp` step. The other steps are available through Medusa's `@medusajs/medusa/core-flows` package.
548
549 ### getProductsFromErp
550
551 The first step of the workflow is to retrieve the products from the ERP. So, create the file `src/workflows/sync-from-erp.ts` with the following content:
552
553 ![Diagram showcasing directory structure after creating the workflow file](https://res.cloudinary.com/dza7lstvk/image/upload/v1740479240/Medusa%20Resources/odoo-4_jrh5mx.jpg)
554
555 ```ts title="src/workflows/sync-from-erp.ts"
556 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
557
558 type Input = {
559 offset: number
560 limit: number
561 }
562
563 const getProductsFromErp = createStep(
564 "get-products-from-erp",
565 async (input: Input, { container }) => {
566 const odooModuleService = container.resolve("odoo")
567
568 const products = await odooModuleService.listProducts(undefined, input)
569
570 return new StepResponse(products)
571 }
572 )
573 ```
574
575 You create a step using `createStep` from the Workflows SDK. It accepts two parameters:
576
577 1. The step's name, which is `get-products-from-erp`.
578 2. An async function that executes the step's logic. The function receives two parameters:
579 - The input data for the step, which are the pagination fields `offset` and `limit`.
580 - An object holding the workflow's context, including the [Medusa Container](!docs!/learn/fundamentals/medusa-container) that allows you to resolve Framework and commerce tools.
581
582 In this step, you resolve the Odoo Module's service from the container and use its `listProducts` method to fetch products from Odoo. You pass the pagination options from the input data to the method.
583
584 A step must return an instance of `StepResponse` which accepts as a parameter the data to return, which is in this case the products.
585
586 ### Create Workflow
587
588 You can now create the workflow that syncs the products from Odoo to Medusa.
589
590 In the same `src/workflows/sync-from-erp.ts` file, add the following imports:
591
592 ```ts title="src/workflows/sync-from-erp.ts"
593 import {
594 createWorkflow, transform, WorkflowResponse,
595 } from "@medusajs/framework/workflows-sdk"
596 import {
597 createProductsWorkflow, updateProductsWorkflow, useQueryGraphStep,
598 } from "@medusajs/medusa/core-flows"
599 import {
600 CreateProductWorkflowInputDTO, UpdateProductWorkflowInputDTO,
601 } from "@medusajs/framework/types"
602 ```
603
604 Then, add the workflow after the step:
605
606 ```ts title="src/workflows/sync-from-erp.ts"
607 export const syncFromErpWorkflow = createWorkflow(
608 "sync-from-erp",
609 (input: Input) => {
610 const odooProducts = getProductsFromErp(input)
611
612 // @ts-ignore
613 const { data: stores } = useQueryGraphStep({
614 entity: "store",
615 fields: [
616 "default_sales_channel_id",
617 ],
618 })
619
620 // @ts-ignore
621 const { data: shippingProfiles } = useQueryGraphStep({
622 entity: "shipping_profile",
623 fields: ["id"],
624 pagination: {
625 take: 1,
626 },
627 }).config({ name: "shipping-profile" })
628
629 const externalIdsFilters = transform({
630 odooProducts,
631 }, (data) => {
632 return data.odooProducts.map((product) => `${product.id}`)
633 })
634
635 // @ts-ignore
636 const { data: existingProducts } = useQueryGraphStep({
637 entity: "product",
638 fields: ["id", "external_id", "variants.*"],
639 filters: {
640 // @ts-ignore
641 external_id: externalIdsFilters,
642 },
643 }).config({ name: "existing-products" })
644
645 // TODO prepare products to create and update
646 }
647 )
648 ```
649
650 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
651
652 It accepts as a second parameter a constructor function, which is the workflow's implementation. The function receives the pagination options as a parameter. In the workflow, you:
653
654 - Call the `getProductsFromErp` step to fetch products from Odoo.
655 - Use the [useQueryGraphStep](/references/helper-steps/useQueryGraphStep) to fetch the Medusa store configurations, sales channels, and shipping profiles. You'll use this data when creating the products in a later step.
656 - The `useQueryGraphStep` uses [Query](!docs!/learn/fundamentals/query), which is a tool that retrieves data across modules.
657 - To figure out which products need to be updated, you retrieve products filtered by their `external_id` field, which you'll set to the Odoo product's ID when you create the products next.
658 - Notice that you use `transform` from the Workflows SDK to create the external IDs filters. That's because data manipulation is not allowed in a workflow. You can learn more about this and other restrictions in [this documentation](!docs!/learn/fundamentals/workflows/constructor-constraints).
659
660 Next, you need to prepare the products that should be created or updated. To do that, replace the `TODO` with the following:
661
662 ```ts title="src/workflows/sync-from-erp.ts"
663 const {
664 productsToCreate,
665 productsToUpdate,
666 } = transform({
667 existingProducts,
668 odooProducts,
669 shippingProfiles,
670 stores,
671 }, (data) => {
672 const productsToCreate: CreateProductWorkflowInputDTO[] = []
673 const productsToUpdate: UpdateProductWorkflowInputDTO[] = []
674
675 data.odooProducts.forEach((odooProduct) => {
676 const product: CreateProductWorkflowInputDTO | UpdateProductWorkflowInputDTO = {
677 external_id: `${odooProduct.id}`,
678 title: odooProduct.display_name,
679 description: odooProduct.description || odooProduct.description_sale || "",
680 status: odooProduct.is_published ? "published" : "draft",
681 options: odooProduct.attribute_line_ids.length ? odooProduct.attribute_line_ids.map((attribute) => {
682 return {
683 title: attribute.attribute_id.display_name,
684 values: attribute.value_ids.map((value) => value.display_name),
685 }
686 }) : [
687 {
688 title: "Default",
689 values: ["Default"],
690 },
691 ],
692 hs_code: odooProduct.hs_code || "",
693 handle: odooProduct.website_url.replace("/shop/", ""),
694 variants: [],
695 shipping_profile_id: data.shippingProfiles[0].id,
696 sales_channels: [
697 {
698 id: data.stores[0].default_sales_channel_id || "",
699 },
700 ],
701 }
702
703 const existingProduct = data.existingProducts.find((p) => p.external_id === product.external_id)
704 if (existingProduct) {
705 product.id = existingProduct.id
706 }
707
708 if (odooProduct.product_variant_ids?.length) {
709 product.variants = odooProduct.product_variant_ids.map((variant) => {
710 const options = {}
711 if (variant.product_template_variant_value_ids.length) {
712 variant.product_template_variant_value_ids.forEach((value) => {
713 options[value.attribute_id.display_name] = value.name
714 })
715 } else {
716 product.options?.forEach((option) => {
717 options[option.title] = option.values[0]
718 })
719 }
720 return {
721 id: existingProduct ? existingProduct.variants.find((v) => v.sku === variant.code)?.id : undefined,
722 title: variant.display_name.replace(`[${variant.code}] `, ""),
723 sku: variant.code || undefined,
724 options,
725 prices: [
726 {
727 amount: variant.list_price,
728 currency_code: variant.currency_id.display_name.toLowerCase(),
729 },
730 ],
731 manage_inventory: false, // change to true if syncing inventory from Odoo
732 metadata: {
733 external_id: `${variant.id}`,
734 },
735 }
736 })
737 } else {
738 product.variants?.push({
739 id: existingProduct ? existingProduct.variants[0].id : undefined,
740 title: "Default",
741 options: {
742 Default: "Default",
743 },
744 // @ts-ignore
745 prices: [
746 {
747 amount: odooProduct.list_price,
748 currency_code: odooProduct.currency_id.display_name.toLowerCase(),
749 },
750 ],
751 metadata: {
752 external_id: `${odooProduct.id}`,
753 },
754 manage_inventory: false, // change to true if syncing inventory from Odoo
755 })
756 }
757
758 if (existingProduct) {
759 productsToUpdate.push(product as UpdateProductWorkflowInputDTO)
760 } else {
761 productsToCreate.push(product as CreateProductWorkflowInputDTO)
762 }
763 })
764
765 return {
766 productsToCreate,
767 productsToUpdate,
768 }
769 })
770
771 // TODO create and update the products
772 ```
773
774 You use `transform` again to prepare the products to create and update. It receives two parameters:
775
776 - An object with the data you'll use in the transform function.
777 - The transform function, which receives the object from the first parameter, and returns the data that can be used in the rest of the workflow.
778
779 In the transform function, you:
780
781 - Create the `productsToCreate` and `productsToUpdate` arrays to hold the products that should be created and updated, respectively.
782 - Iterate over the products fetched from Odoo and create a product object for each. You set the product's properties based on the Odoo product's properties. If you want to add more properties, you can do so at this point.
783 - Most importantly, you set the `external_id` to the Odoo product's ID, which allows you later to identify the product later when updating it or for other operations.
784 - You also set the product's variants either to Odoo's variants or to a default variant. You set the product variant's Odoo ID in the `metadata.external_id` field, which allows you to identify the variant later when updating it or for other operations.
785 - To determine if a product already exists, you check if the product's `external_id` matches an existing product's `external_id`. You add it to the products to be updated. You apply a similar logic for the variants.
786 - Finally, you return an object with the `productsToCreate` and `productsToUpdate` arrays.
787
788 You can now create and update the products in the workflow. Replace the `TODO` with the following:
789
790 ```ts title="src/workflows/sync-from-erp.ts"
791 createProductsWorkflow.runAsStep({
792 input: {
793 products: productsToCreate,
794 },
795 })
796
797 updateProductsWorkflow.runAsStep({
798 input: {
799 products: productsToUpdate,
800 },
801 })
802
803 return new WorkflowResponse({
804 odooProducts,
805 })
806 ```
807
808 You use the `createProductsWorkflow` and `updateProductsWorkflow` to create and update the products returned from the transform function. Since both of these are workflows, you use the `runAsStep` method to run them as steps in the current workflow.
809
810 Finally, a workflow must return a instance of `WorkflowResponse` passing it as a parameter the data to return, which in this case is the products fetched from Odoo.
811
812 You can now execute this workflow in other customizations, such as a scheduled job.
813
814 ### Create Scheduled Job
815
816 In Medusa, you can run a task at a specified interval using a [scheduled job](!docs!/learn/fundamentals/scheduled-jobs). A scheduled job is an asynchronous function that runs at a regular interval during the Medusa application's runtime to perform tasks such as syncing products from Odoo to Medusa.
817
818 To create a scheduled job, create the file `src/jobs/sync-products-from-erp.ts` with the following content:
819
820 ![Diagram showcasing directory structure after creating the scheduled job file](https://res.cloudinary.com/dza7lstvk/image/upload/v1740480934/Medusa%20Resources/odoo-5_xf0xug.jpg)
821
822 ```ts title="src/jobs/sync-products-from-erp.ts"
823 import {
824 MedusaContainer,
825 } from "@medusajs/framework/types"
826 import { syncFromErpWorkflow } from "../workflows/sync-from-erp"
827 import { OdooProduct } from "../modules/odoo/service"
828
829 export default async function syncProductsJob(container: MedusaContainer) {
830 const limit = 10
831 let offset = 0
832 let total = 0
833 let odooProducts: OdooProduct[] = []
834
835 console.log("Syncing products...")
836
837 do {
838 odooProducts = (await syncFromErpWorkflow(container).run({
839 input: {
840 limit,
841 offset,
842 },
843 })).result.odooProducts
844
845 offset += limit
846 total += odooProducts.length
847 } while (odooProducts.length > 0)
848
849 console.log(`Synced ${total} products`)
850 }
851
852 export const config = {
853 name: "daily-product-sync",
854 schedule: "0 0 * * *", // Every day at midnight
855 }
856 ```
857
858 In this file, you export:
859
860 - An asynchronous function, which is the task to execute at the specified schedule.
861 - A configuration object having the following properties:
862 - `name`: A unique name for the scheduled job.
863 - `schedule`: A [cron expression](https://crontab.guru/) string indicating the schedule to run the job at. The specified schedule indicates that this job should run every day at midnight.
864
865 The scheduled job function accepts the Medusa container as a parameter. In the function, you define the pagination options for the products to fetch from Odoo. You then run the `syncFromErpWorkflow` workflow with the pagination options. You increment the offset by the limit each time you run the workflow until you fetch all the products.
866
867 ---
868
869 ## Test it Out
870
871 To test out syncing the products from Odoo to Medusa, first, change the schedule of the job in `src/jobs/sync-products-from-erp.ts` to run every minute:
872
873 ```ts title="src/jobs/sync-products-from-erp.ts"
874 export const config = {
875 name: "daily-product-sync",
876 schedule: "* * * * *", // Every minute
877 }
878 ```
879
880 Then, start the Medusa application with the following command:
881
882 ```bash npm2yarn
883 npm run dev
884 ```
885
886 A minute later, you should find the message `Syncing products...` in the console. Once the job finishes, you should see the message `Synced <number> products`, indicating the number of products synced.
887
888 You can also confirm that the products were synced by checking the products in the Medusa Admin dashboard.
889
890 If you encounter any issues, make sure the module options are set correctly as explained in [this section](#add-module-to-medusas-configurations).
891
892 ---
893
894 ## Next Steps
895
896 You now have the foundation for integrating Odoo with Medusa. You can expand on this integration to implement more use cases, such as syncing orders, restricting purchases of products based on custom rules, and checking inventory in Odoo before adding to the cart. You can find the approach to implement these use cases in [this recipe](../page.mdx).
897
898 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
899
900 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).