1 ---
2 products:
3 - tax
4 tag:
5 - tax
6 - server
7 - tutorial
8 ---
9
10 import { Card, Prerequisites, Details, WorkflowDiagram, InlineIcon } from "docs-ui"
11 import { Github, PlaySolid, EllipsisHorizontal } from "@medusajs/icons"
12
13 export const metadata = {
14 title: `Integrate Avalara (AvaTax) for Tax Calculation`,
15 }
16
17 # {metadata.title}
18
19 In this tutorial, you'll learn how to integrate Avalara with Medusa to handle tax calculations.
20
21 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 tax providers, allowing you to build custom features around core commerce flows.
22
23 [Avalara](https://www.avalara.com/) is a leading provider of tax compliance solutions, including sales tax calculation, filing, and remittance. By integrating Avalara with Medusa, you can calculate taxes during checkout with accurate rates based on customer location.
24
25 ## Summary
26
27 By following this tutorial, you'll learn how to:
28
29 - Install and set up Medusa.
30 - Create the Avalara Tax Module Provider that calculates taxes using Avalara.
31 - Create transactions in Avalara when an order is placed.
32 - Sync products to Avalara to manage their tax codes and classifications.
33
34 You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer.
35
36 ![Diagram showing Avalara integration with Medusa for tax calculation during checkout](https://res.cloudinary.com/dza7lstvk/image/upload/v1760969087/Medusa%20Resources/avalara-summary_rqrkpf.jpg)
37
38 <Card
39 title="Example Repository"
40 text="Find the full code of the guide in this repository."
41 href="https://github.com/medusajs/examples/tree/main/avalara-integration"
42 icon={Github}
43 />
44
45 ---
46
47 ## Step 1: Install a Medusa Application
48
49 <Prerequisites items={[
50 {
51 text: "Node.js v20.19.0+ or v22.12.0+",
52 link: "https://nodejs.org/en/download"
53 },
54 {
55 text: "Git CLI tool",
56 link: "https://git-scm.com/downloads"
57 },
58 {
59 text: "PostgreSQL",
60 link: "https://www.postgresql.org/download/"
61 }
62 ]} />
63
64 Start by installing the Medusa application on your machine with the following command:
65
66 ```bash
67 npx create-medusa-app@latest
68 ```
69
70 You'll first be asked for the project's name. Then, when asked whether you want to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose "Yes."
71
72 Afterwards, 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, and the Next.js Starter Storefront is installed in the `apps/storefront` directory.
73
74 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.
75
76 <Note title="Ran into Errors?">
77
78 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
79
80 </Note>
81
82 <Note>
83
84 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
85
86 </Note>
87
88 ---
89
90 ## Step 2: Create Avalara Tax Module Provider
91
92 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.
93
94 Medusa's [Tax Module](../../../commerce-modules/tax/page.mdx) implements concepts and functionalities related to taxes, but delegates tax calculations to external services through Tax Module Providers.
95
96 In this step, you'll integrate Avalara as a Tax Module Provider. Later, you'll use it to calculate taxes in your Medusa application.
97
98 <Note>
99
100 Refer to the [Modules](!docs!/learn/fundamentals/modules) documentation to learn more about modules in Medusa.
101
102 </Note>
103
104 ### a. Install AvaTax SDK
105
106 First, install the AvaTax SDK package to interact with Avalara's API. Run the following command in your `apps/backend` directory:
107
108 ```bash npm2yarn
109 npm install avatax
110 ```
111
112 ### b. Create Module Directory
113
114 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/avalara`.
115
116 ### c. Define Module Options
117
118 Next, define a TypeScript type for the Avalara Module options. These options configure the module when it's registered in the Medusa application.
119
120 Create the file `src/modules/avalara/types.ts` with the following content:
121
122 export const moduleOptionsHighlights = [
123 ["2", "username", "The Avalara account ID."],
124 ["3", "password", "The Avalara license key."],
125 ["4", "appName", "The name of your application."],
126 ["5", "appVersion", "The version of your application."],
127 ["6", "appEnvironment", "The environment of your application, either production or sandbox."],
128 ["7", "machineName", "The name of the machine where your application is running."],
129 ["8", "timeout", "The timeout for API requests in milliseconds."],
130 ["9", "companyCode", "The Avalara company code to use for tax calculations."],
131 ["10", "companyId", "The Avalara company ID, necessary later when creating items in Avalara."],
132 ]
133
134 ```ts title="src/modules/avalara/types.ts" highlights={moduleOptionsHighlights}
135 export type ModuleOptions = {
136 username?: string
137 password?: string
138 appName?: string
139 appVersion?: string
140 appEnvironment?: string
141 machineName?: string
142 timeout?: number
143 companyCode?: string
144 companyId?: number
145 }
146 ```
147
148 The module options include:
149
150 - `username`: The Avalara account ID or username.
151 - `password`: The Avalara license key or password.
152 - `appName`: The name of your application. Defaults to `medusa`.
153 - `appVersion`: The version of your application. Defaults to `1.0.0`.
154 - `appEnvironment`: The environment of your application, either `production` or `sandbox`. Defaults to `sandbox`.
155 - `machineName`: The name of the machine where your application is running. Defaults to `medusa`.
156 - `timeout`: The timeout for API requests in milliseconds. Defaults to `3000`.
157 - `companyCode`: The Avalara company code to use for tax calculations. If not provided, the default company in Avalara is used.
158 - `companyId`: The Avalara company ID, which is necessary later when creating items in Avalara.
159
160 You'll learn how to set these options when you [register the module](#f-add-module-provider-to-medusas-configuration).
161
162 ### d. Create Avalara Service
163
164 A module has a service that contains its logic. For Tax Module Providers, the service implements the logic to calculate taxes using the third-party service.
165
166 To create the service for the Avalara Tax Module Provider, create the file `src/modules/avalara/service.ts` with the following content:
167
168 export const serviceHighlights = [
169 ["11", "identifier", "The unique identifier of the Avalara Tax Module Provider."],
170 ["15", "constructor", "Create the Avatax client instance and validate module options."],
171 ]
172
173 ```ts title="src/modules/avalara/service.ts" highlights={serviceHighlights}
174 import { ITaxProvider } from "@medusajs/framework/types"
175 import Avatax from "avatax"
176 import { MedusaError } from "@medusajs/framework/utils"
177 import { ModuleOptions } from "./types"
178
179 type InjectedDependencies = {
180 // Add any dependencies you want to inject via the module container
181 }
182
183 class AvalaraTaxModuleProvider implements ITaxProvider {
184 static identifier = "avalara"
185 private readonly avatax: Avatax
186 private readonly options: ModuleOptions
187
188 constructor({}: InjectedDependencies, options: ModuleOptions) {
189 this.options = options
190 if (!options?.username || !options?.password || !options?.companyId) {
191 throw new MedusaError(
192 MedusaError.Types.INVALID_DATA,
193 "Avalara module options are required: username, password and companyId"
194 )
195 }
196 this.avatax = new Avatax({
197 appName: options.appName || "medusa",
198 appVersion: options.appVersion || "1.0.0",
199 machineName: options.machineName || "medusa",
200 environment: options.appEnvironment === "production" ? "production" : "sandbox",
201 timeout: options.timeout || 3000,
202 }).withSecurity({
203 username: options.username,
204 password: options.password,
205 })
206 }
207 getIdentifier(): string {
208 return AvalaraTaxModuleProvider.identifier
209 }
210 }
211
212 export default AvalaraTaxModuleProvider
213 ```
214
215 A Tax Module Provider's service must implement the `ITaxProvider` interface. It must also have an `identifier` static property with the unique identifier of the provider.
216
217 The constructor of a module's service receives the following parameters:
218
219 1. An object with the dependencies to resolve from the [Module's container](!docs!/learn/fundamentals/modules/container).
220 2. An object with the module options passed to the provider when it's registered.
221
222 In the constructor, you validate that the required options are provided. Then, you create an instance of the `Avatax` client using the provided options.
223
224 You also define the `getIdentifier` method required by the `ITaxProvider` interface, which returns the provider's identifier.
225
226 #### getTaxLines Method
227
228 Next, you'll implement the `getTaxLines` method required by the `ITaxProvider` interface. This method calculates the tax lines for line items and shipping methods. Medusa uses this method during checkout to calculate taxes.
229
230 Before creating the method, you'll create a `createTransaction` method that creates a transaction in Avalara to calculate taxes.
231
232 First, add the following import at the top of the file:
233
234 ```ts title="src/modules/avalara/service.ts"
235 import { CreateTransactionModel } from "avatax/lib/models/CreateTransactionModel"
236 ```
237
238 Then, add the following in the `AvalaraTaxModuleProvider` class:
239
240 ```ts title="src/modules/avalara/service.ts"
241 class AvalaraTaxModuleProvider implements ITaxProvider {
242 // ...
243 async createTransaction(model: CreateTransactionModel) {
244 try {
245 const response = await this.avatax.createTransaction({
246 model,
247 include: "Details",
248 })
249
250 return response
251 } catch (error) {
252 throw new MedusaError(
253 MedusaError.Types.UNEXPECTED_STATE,
254 `An error occurred while creating transaction for Avalara: ${error}`
255 )
256 }
257 }
258 }
259 ```
260
261 This method receives the details of the transaction to create in Avalara. It calls the `avatax.createTransaction` method to create the transaction. If the transaction's type ends with `Order`, Avalara will calculate and return the tax details only. If it ends with `Invoice`, Avalara will save the transaction.
262
263 You return the response from Avalara, which contains the tax details.
264
265 <Note title="Tip">
266
267 Refer to [Avalara's documentation](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Transactions/CreateTransaction/) for details on other accepted parameters when creating a transaction.
268
269 </Note>
270
271 You'll now add the `getTaxLines` method to calculate tax lines using Avalara.
272
273 First, add the following imports at the top of the file:
274
275 ```ts title="src/modules/avalara/service.ts"
276 import {
277 ItemTaxCalculationLine,
278 ItemTaxLineDTO,
279 ShippingTaxCalculationLine,
280 ShippingTaxLineDTO,
281 TaxCalculationContext,
282 } from "@medusajs/framework/types"
283 ```
284
285 Then, add the method to the `AvalaraTaxModuleProvider` class:
286
287 export const getTaxLinesHighlights = [
288 ["10", "currencyCode", "Determine the currency code from the line items or shipping methods."],
289 ["13", "createTransaction", "Create a transaction in Avalara for the line items and shipping methods."],
290 ["47", "type", "Set the transaction type to SalesOrder to calculate taxes without saving the transaction."]
291 ]
292
293 ```ts title="src/modules/avalara/service.ts" highlights={getTaxLinesHighlights}
294 class AvalaraTaxModuleProvider implements ITaxProvider {
295 // ...
296
297 async getTaxLines(
298 itemLines: ItemTaxCalculationLine[],
299 shippingLines: ShippingTaxCalculationLine[],
300 context: TaxCalculationContext
301 ): Promise<(ItemTaxLineDTO | ShippingTaxLineDTO)[]> {
302 try {
303 const currencyCode = (
304 itemLines[0]?.line_item.currency_code || shippingLines[0]?.shipping_line.currency_code
305 )?.toUpperCase()
306 const response = await this.createTransaction({
307 lines: [
308 ...(itemLines.length ? itemLines.map((line) => {
309 const quantity = Number(line.line_item.quantity) ?? 0
310 return {
311 number: line.line_item.id,
312 quantity,
313 amount: quantity * (Number(line.line_item.unit_price) ?? 0),
314 taxCode: line.rates.find((rate) => rate.is_default)?.code ?? "",
315 itemCode: line.line_item.product_id,
316 }
317 }) : []),
318 ...(shippingLines.length ? shippingLines.map((line) => {
319 return {
320 number: line.shipping_line.id,
321 quantity: 1,
322 amount: Number(line.shipping_line.unit_price) ?? 0,
323 taxCode: line.rates.find((rate) => rate.is_default)?.code ?? "",
324 }
325 }) : []),
326 ],
327 date: new Date(),
328 customerCode: context.customer?.id ?? "",
329 addresses: {
330 "singleLocation": {
331 line1: context.address.address_1 ?? "",
332 line2: context.address.address_2 ?? "",
333 city: context.address.city ?? "",
334 region: context.address.province_code ?? "",
335 postalCode: context.address.postal_code ?? "",
336 country: context.address.country_code.toUpperCase() ?? "",
337 },
338 },
339 currencyCode,
340 type: DocumentType.SalesOrder,
341 })
342
343 // TODO return tax lines
344 } catch (error) {
345 throw new MedusaError(
346 MedusaError.Types.UNEXPECTED_STATE,
347 `An error occurred while getting tax lines from Avalara: ${error}`
348 )
349 }
350 }
351 }
352 ```
353
354 The `getTaxLines` method receives the following parameters:
355
356 - `itemLines`: An array of line items to calculate taxes for.
357 - `shippingLines`: An array of shipping methods to calculate taxes for.
358 - `context`: Additional context for tax calculation, such as customer and address information.
359
360 In the method, you create a transaction in Avalara for both line items and shipping methods using the `avatax.createTransaction` method. Since you set the type to `DocumentType.SalesOrder`, Avalara will calculate and return the tax details for the provided items and shipping methods without saving the transaction.
361
362 <Note title="Tip">
363
364 Refer to [Avalara's documentation](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Transactions/CreateTransaction/) for details on other accepted parameters when creating a transaction.
365
366 </Note>
367
368 Next, you'll extract the tax lines from the response and return them in the expected format. Replace the `// TODO return tax lines` comment with the following:
369
370 ```ts title="src/modules/avalara/service.ts"
371 const taxLines: (ItemTaxLineDTO | ShippingTaxLineDTO)[] = []
372 response?.lines?.forEach((line) => {
373 line.details?.forEach((detail) => {
374 const isShippingLine = shippingLines.find(
375 (sLine) => sLine.shipping_line.id === line.lineNumber
376 ) !== undefined
377 const commonData = {
378 rate: (detail.rate ?? 0) * 100,
379 name: detail.taxName ?? "",
380 code: line.taxCode || detail.rateTypeCode || detail.signatureCode || "",
381 provider_id: this.getIdentifier(),
382 }
383 if (!isShippingLine) {
384 taxLines.push({
385 ...commonData,
386 line_item_id: line.lineNumber ?? "",
387 })
388 } else {
389 taxLines.push({
390 ...commonData,
391 shipping_line_id: line.lineNumber ?? "",
392 })
393 }
394 })
395 })
396
397 return taxLines
398 ```
399
400 This code extracts the tax details from the Avalara response and constructs an array of tax lines in the expected format. Finally, it returns the array of tax lines.
401
402 ### e. Export Module Definition
403
404 You've finished implementing the Avalara Tax Module Provider's service and its required method.
405
406 The final piece of a module is its definition, which you export in an `index.ts` file at the module's root directory. This definition tells Medusa the module's details, including its service.
407
408 To create the module's definition, create the file `src/modules/avalara/index.ts` with the following content:
409
410 ```ts title="src/modules/avalara/index.ts"
411 import AvalaraTaxModuleProvider from "./service"
412 import {
413 ModuleProvider,
414 Modules,
415 } from "@medusajs/framework/utils"
416
417 export default ModuleProvider(Modules.TAX, {
418 services: [AvalaraTaxModuleProvider],
419 })
420 ```
421
422 You use `ModuleProvider` from the Modules SDK to create the module provider's definition. It accepts two parameters:
423
424 1. The name of the module that this provider belongs to, which is `Modules.TAX` in this case.
425 2. An object with a required `services` property indicating the Module Provider's services.
426
427 ### f. Add Module Provider to Medusa's Configuration
428
429 After finishing the module, add it to Medusa's configuration to start using it.
430
431 In `medusa-config.ts`, add a `modules` property:
432
433 ```ts title="medusa-config.ts"
434 module.exports = defineConfig({
435 // ...
436 modules: [
437 {
438 resolve: "@medusajs/medusa/tax",
439 options: {
440 providers: [
441 {
442 resolve: "./src/modules/avalara",
443 id: "avalara",
444 options: {
445 username: process.env.AVALARA_USERNAME,
446 password: process.env.AVALARA_PASSWORD,
447 appName: process.env.AVALARA_APP_NAME,
448 appVersion: process.env.AVALARA_APP_VERSION,
449 appEnvironment: process.env.AVALARA_APP_ENVIRONMENT,
450 machineName: process.env.AVALARA_MACHINE_NAME,
451 timeout: process.env.AVALARA_TIMEOUT,
452 companyCode: process.env.AVALARA_COMPANY_CODE,
453 companyId: process.env.AVALARA_COMPANY_ID,
454 },
455 },
456 ],
457 },
458 },
459 ],
460 })
461 ```
462
463 To pass a Tax Module Provider to the Tax Module, add the `modules` property to the Medusa configuration and pass the Tax Module in its value.
464
465 The Tax Module accepts a `providers` option, which is an array of Tax Module Providers to register.
466
467 You register the Avalara Tax Module Provider and pass it the expected options.
468
469 ### g. Set Environment Variables
470
471 Finally, set the required environment variables in your `.env` file:
472
473 ```bash title=".env"
474 AVALARA_USERNAME=
475 AVALARA_PASSWORD=
476 AVALARA_APP_ENVIRONMENT=production # or sandbox
477 AVALARA_COMPANY_ID=
478 ```
479
480 You set the following variables:
481
482 1. `AVALARA_USERNAME`: Your Avalara account ID. You can retrieve it from the Avalara dashboard by clicking on "Account" at the top right. It's at the top of the dropdown.
483
484 ![Avalara Account ID in the account dropdown at the top right of the Avalara dashboard](https://res.cloudinary.com/dza7lstvk/image/upload/v1760967142/Medusa%20Resources/CleanShot_2025-10-20_at_16.30.55_2x_gpqi9i.png)
485
486 2. `AVALARA_PASSWORD`: Your Avalara license key. To retrieve it from the Avalara dashboard:
487 1. From the sidebar, click on "Integrations."
488 2. Choose the "License Keys" tab.
489 3. Click on the "Generate new key" button.
490 4. Confirm generating the key.
491 5. Copy the generated key.
492
493 ![The Avalara license key tab with the "Generate new key" button](https://res.cloudinary.com/dza7lstvk/image/upload/v1760967334/Medusa%20Resources/CleanShot_2025-10-20_at_16.35.06_2x_fe7cym.png)
494
495 3. `AVALARA_APP_ENVIRONMENT`: The environment of your application, which can be either `production` or `sandbox`. Set it based on your Avalara account type. Note that Avalara provides separate accounts for production and sandbox environments.
496 4. `AVALARA_COMPANY_ID`: The company ID in Avalara for creating products for tax code management. To retrieve it from the Avalara dashboard:
497 1. From the sidebar, click on "Settings" → "All settings."
498 2. Find the "Companies" card and click on "Manage."
499 3. Click on the company you want to use.
500 4. Copy the company ID from the URL. It's the number at the end of the URL, after `/companies/`.
501
502 You can also set other optional environment variables for further configuration. Refer to [Avalara's documentation for more details about these options](https://developer.avalara.com/avatax/client-headers/).
503
504 ---
505
506 ## Step 3: Test Tax Calculation with Avalara
507
508 You'll test the Avalara integration using the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) that you installed earlier. You'll proceed through checkout and verify that taxes are calculated using Avalara.
509
510 ### Prerequisite: Set Region's Provider to Avalara
511
512 Before testing the integration, configure the regions you want to use Avalara for tax calculations.
513
514 First, run the following command in your `apps/backend` directory to start the server:
515
516 ```bash npm2yarn
517 npm run dev
518 ```
519
520 Then:
521
522 1. Go to `http://localhost:9000/admin` and log in to the Medusa Admin dashboard.
523 2. Go to "Settings" → "Tax Regions."
524 3. Select the country you want to configure Avalara for. You can repeat these steps for multiple countries.
525 4. In the first section, click on the <InlineIcon Icon={EllipsisHorizontal} alt="three-dots" /> icon at the top right and choose "Edit."
526 5. In the "Tax Provider" dropdown, select "Avalara (AVALARA)."
527 6. Click on "Save."
528
529 ![Setting Avalara as the tax provider for a region in the Medusa Admin dashboard](https://res.cloudinary.com/dza7lstvk/image/upload/v1760968076/Medusa%20Resources/CleanShot_2025-10-20_at_16.47.45_2x_g96acs.png)
530
531 ### Test Checkout with Avalara
532
533 Now you can test the checkout process in the Next.js Starter Storefront.
534
535 <Note title="Reminder" forceMultiline>
536
537 The Next.js Starter Storefront is available in the `apps/storefront` directory of your project:
538
539 ```bash
540 cd apps/storefront
541 ```
542
543 </Note>
544
545 While the Medusa server is running, open another terminal window in the storefront's directory and run the following command to start the storefront:
546
547 ```bash npm2yarn
548 npm run dev
549 ```
550
551 Then:
552
553 1. Go to `http://localhost:8000` to open the storefront.
554 2. Go to "Menu" → "Store" and click on a product.
555 3. Select the product's options if any, then click on "Add to cart."
556 4. Click on the cart icon at the top right to open the cart.
557 5. Click on "Go to checkout."
558 6. Enter the shipping information and click on "Continue to delivery." The tax amount will update in the right section.
559
560 ![Taxes calculated during checkout in the Next.js Starter Storefront](https://res.cloudinary.com/dza7lstvk/image/upload/v1760968357/Medusa%20Resources/CleanShot_2025-10-20_at_16.52.14_2x_bgozfz.png)
561
562 7. In the Delivery step, select a shipping method. This will update the tax amount based on the shipping method's price.
563
564 ![Taxes updated based on the selected shipping method during checkout in the Next.js Starter Storefront](https://res.cloudinary.com/dza7lstvk/image/upload/v1760968412/Medusa%20Resources/CleanShot_2025-10-20_at_16.53.14_2x_wxcuyn.png)
565
566 You can now complete the checkout with the taxes calculated by Avalara.
567
568 ---
569
570 ## Step 4: Create Transactions in Avalara on Order Placement
571
572 Avalara allows you to create transactions when an order is placed. This helps you keep track of sales and tax liabilities in Avalara.
573
574 In this step, you'll implement the logic to create an Avalara transaction when an order is placed in Medusa. You will:
575
576 1. Add a method in the Avalara Tax Module Provider's service to uncommit a transaction. This is useful for rolling back the transaction if an error occurs or the order is canceled.
577 2. Create a [workflow](!docs!/learn/fundamentals/workflows) that creates a transaction in Avalara for an order.
578 3. Create a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that listens to the `order.placed` event and triggers the workflow.
579
580 ### a. Add Uncommit Transaction Method
581
582 First, you'll add a method in the Avalara Tax Module Provider's service to uncommit a transaction.
583
584 In `src/modules/avalara/service.ts`, add the following method to the `AvalaraTaxModuleProvider` class:
585
586 ```ts title="src/modules/avalara/service.ts"
587 class AvalaraTaxModuleProvider implements ITaxProvider {
588 // ...
589 async uncommitTransaction(transactionCode: string) {
590 try {
591 const response = await this.avatax.uncommitTransaction({
592 companyCode: this.options.companyCode!,
593 transactionCode: transactionCode,
594 })
595
596 return response
597 }
598 catch (error) {
599 throw new MedusaError(
600 MedusaError.Types.UNEXPECTED_STATE,
601 `An error occurred while uncommitting transaction for Avalara: ${error}`
602 )
603 }
604 }
605 }
606 ```
607
608 This method receives the code of the transaction to uncommit. It calls the `avatax.uncommitTransaction` method to uncommit the transaction in Avalara.
609
610 ### b. Create Order Transaction Workflow
611
612 Next, you'll create a workflow that creates an order transaction. A workflow is a series of 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 execution progress, define roll-back logic, and configure other advanced features.
613
614 <Note>
615
616 Learn more about workflows in the [Workflows documentation](!docs!/learn/fundamentals/workflows).
617
618 </Note>
619
620 The workflow to create an Avalara transaction has the following steps:
621
622 <WorkflowDiagram
623 workflow={{
624 name: "createOrderTransactionWorkflow",
625 steps: [
626 {
627 type: "step",
628 name: "useQueryGraphStep",
629 description: "Retrieve order's details.",
630 link: "/references/helper-steps/useQueryGraphStep",
631 depth: 1
632 },
633 {
634 type: "step",
635 name: "createTransactionStep",
636 description: "Create a transaction for order.",
637 depth: 2
638 },
639 {
640 type: "workflow",
641 name: "updateOrderWorkflow",
642 description: "Save transaction code in order metadata.",
643 link: "/references/medusa-workflows/updateOrderWorkflow",
644 depth: 3
645 }
646 ]
647 }}
648 />
649
650 Medusa provides the first and last step out of the box. You only need to create the `createTransactionStep`.
651
652 #### createTransactionStep
653
654 The `createTransactionStep` creates a transaction in Avalara.
655
656 To create the step, create the file `src/workflows/steps/create-transaction.ts` with the following content:
657
658 export const createTransactionStepHighlights = [
659 ["34", "avalaraProviderService", "Retrieve the Avalara Tax Module Provider's service from the Tax Module."],
660 ["38", "createTransaction", "Create a transaction in Avalara using the provider's createTransaction method."],
661 ["51", "uncommitTransaction", "Uncommit the created transaction if an error occurs during the workflow's execution."]
662 ]
663
664 ```ts title="src/workflows/steps/create-transaction.ts" highlights={createTransactionStepHighlights}
665 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
666 import AvalaraTaxModuleProvider from "../../modules/avalara/service"
667 import { DocumentType } from "avatax/lib/enums/DocumentType"
668 import { Modules } from "@medusajs/framework/utils"
669
670 type StepInput = {
671 lines: {
672 number: string
673 quantity: number
674 amount: number
675 taxCode: string
676 itemCode?: string
677 }[]
678 date: Date
679 customerCode: string
680 addresses: {
681 singleLocation: {
682 line1: string
683 line2: string
684 city: string
685 region: string
686 postalCode: string
687 country: string
688 }
689 }
690 currencyCode: string
691 type: DocumentType
692 }
693
694 export const createTransactionStep = createStep(
695 "create-transaction",
696 async (input: StepInput, { container }) => {
697 const taxModuleService = container.resolve(Modules.TAX)
698 const avalaraProviderService = taxModuleService.getProvider(
699 `tp_${AvalaraTaxModuleProvider.identifier}_avalara`
700 ) as AvalaraTaxModuleProvider
701
702 const response = await avalaraProviderService.createTransaction(input)
703
704 return new StepResponse(response, response)
705 },
706 async (data, { container }) => {
707 if (!data?.code) {
708 return
709 }
710 const taxModuleService = container.resolve(Modules.TAX)
711 const avalaraProviderService = taxModuleService.getProvider(
712 `tp_${AvalaraTaxModuleProvider.identifier}_avalara`
713 ) as AvalaraTaxModuleProvider
714
715 await avalaraProviderService.uncommitTransaction(data.code)
716 }
717 )
718 ```
719
720 You create a step with `createStep` from the Workflows SDK. It accepts three parameters:
721
722 1. The step's unique name, which is `create-transaction`.
723 2. An async function that receives two parameters:
724 - The step's input, which is an object containing the transaction's details.
725 - An object that has properties including the [Medusa container](!docs!/learn/fundamentals/medusa-container), which is a registry of Framework and commerce tools that you can access in the step.
726 3. An async compensation function that runs if an error occurs during the workflow's execution. It rolls back changes made in the step.
727
728 In the step function, you retrieve the Avalara Tax Module Provider's service from the Tax Module. Then, you call its `createTransaction` method to create a transaction in Avalara.
729
730 A step function must return a `StepResponse` instance. The `StepResponse` constructor accepts two parameters:
731
732 1. The step's output, which is the created transaction.
733 2. Data to pass to the step's compensation function.
734
735 In the compensation function, you uncommit the created transaction if an error occurs during the workflow's execution.
736
737 #### Create Transaction Workflow
738
739 You'll now create the workflow. Create the file `src/workflows/create-order-transaction.ts` with the following content:
740
741 ```ts title="src/workflows/create-order-transaction.ts"
742 import { createWorkflow, transform, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
743 import { updateOrderWorkflow, useQueryGraphStep } from "@medusajs/medusa/core-flows"
744 import { createTransactionStep } from "./steps/create-transaction"
745 import AvalaraTaxModuleProvider from "../modules/avalara/service"
746 import { DocumentType } from "avatax/lib/enums/DocumentType"
747
748 type WorkflowInput = {
749 order_id: string
750 }
751
752 export const createOrderTransactionWorkflow = createWorkflow(
753 "create-order-transaction-workflow",
754 (input: WorkflowInput) => {
755 const { data: orders } = useQueryGraphStep({
756 entity: "order",
757 fields: [
758 "id",
759 "currency_code",
760 "items.quantity",
761 "items.id",
762 "items.unit_price",
763 "items.product_id",
764 "items.tax_lines.id",
765 "items.tax_lines.description",
766 "items.tax_lines.code",
767 "items.tax_lines.rate",
768 "items.tax_lines.provider_id",
769 "items.variant.sku",
770 "shipping_methods.id",
771 "shipping_methods.amount",
772 "shipping_methods.tax_lines.id",
773 "shipping_methods.tax_lines.description",
774 "shipping_methods.tax_lines.code",
775 "shipping_methods.tax_lines.rate",
776 "shipping_methods.tax_lines.provider_id",
777 "shipping_methods.shipping_option_id",
778 "customer.id",
779 "customer.email",
780 "customer.metadata",
781 "customer.groups.id",
782 "shipping_address.id",
783 "shipping_address.address_1",
784 "shipping_address.address_2",
785 "shipping_address.city",
786 "shipping_address.postal_code",
787 "shipping_address.country_code",
788 "shipping_address.region_code",
789 "shipping_address.province",
790 "shipping_address.metadata",
791 ],
792 filters: {
793 id: input.order_id,
794 },
795 })
796
797 // TODO create transaction
798 }
799 )
800 ```
801
802 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
803
804 As a second parameter, it accepts a constructor function, which is the workflow's implementation. The function can accept input, which in this case is the order ID.
805
806 So far, you retrieve the order's details using the `useQueryGraphStep`. It uses [Query](!docs!/learn/fundamentals/query) under the hood to retrieve data across modules.
807
808 Next, you'll prepare the transaction input, create the transaction, and update the order with the transaction code. Replace the `// TODO create transaction` comment with the following:
809
810 export const createOrderTransactionWorkflowHighlights = [
811 ["1", "transactionInput", "Prepare the transaction input using the order's details."],
812 ["40", "type", "Set the type to SalesInvoice to save the transaction in Avalara."],
813 ["44", "createTransactionStep", "Create the transaction in Avalara."],
814 ["46", "updateOrderWorkflow", "Update the order with the created transaction's code."]
815 ]
816
817 ```ts title="src/workflows/create-order-transaction.ts" highlights={createOrderTransactionWorkflowHighlights}
818 const transactionInput = transform({ orders }, ({ orders }) => {
819 const providerId = `tp_${AvalaraTaxModuleProvider.identifier}_avalara`
820 return {
821 lines: [
822 ...(orders[0]?.items?.map((item) => {
823 return {
824 number: item?.id ?? "",
825 quantity: item?.quantity ?? 0,
826 amount: item?.unit_price ?? 0,
827 taxCode: item?.tax_lines?.find(
828 (taxLine) => taxLine?.provider_id === providerId
829 )?.code ?? "",
830 itemCode: item?.product_id ?? "",
831 }
832 }) ?? []),
833 ...(orders[0]?.shipping_methods?.map((shippingMethod) => {
834 return {
835 number: shippingMethod?.id ?? "",
836 quantity: 1,
837 amount: shippingMethod?.amount ?? 0,
838 taxCode: shippingMethod?.tax_lines?.find(
839 (taxLine) => taxLine?.provider_id === providerId
840 )?.code ?? "",
841 }
842 }) ?? []),
843 ],
844 date: new Date(),
845 customerCode: orders[0]?.customer?.id ?? "",
846 addresses: {
847 singleLocation: {
848 line1: orders[0]?.shipping_address?.address_1 ?? "",
849 line2: orders[0]?.shipping_address?.address_2 ?? "",
850 city: orders[0]?.shipping_address?.city ?? "",
851 region: orders[0]?.shipping_address?.province ?? "",
852 postalCode: orders[0]?.shipping_address?.postal_code ?? "",
853 country: orders[0]?.shipping_address?.country_code?.toUpperCase() ?? "",
854 },
855 },
856 currencyCode: orders[0]?.currency_code.toUpperCase() ?? "",
857 type: DocumentType.SalesInvoice,
858 }
859 })
860
861 const response = createTransactionStep(transactionInput)
862
863 const order = updateOrderWorkflow.runAsStep({
864 input: {
865 id: input.order_id,
866 user_id: "",
867 metadata: {
868 avalara_transaction_code: response.code,
869 },
870 },
871 })
872
873 return new WorkflowResponse(order)
874 ```
875
876 You prepare the transaction input using the `transform` function. You include in the input the line items and shipping methods from the order, along with the customer and address details.
877
878 Notice that you set the type to `DocumentType.SalesInvoice` to save the transaction in Avalara.
879
880 <Note>
881
882 Refer to [Avalara's documentation](https://developer.avalara.com/avatax/client-headers/) for details on other accepted parameters when creating a transaction.
883
884 </Note>
885
886 Then, you call the `createTransactionStep` to create the transaction in Avalara.
887
888 Finally, you use the `updateOrderWorkflow` to save the created transaction's code in the order's metadata.
889
890 A workflow must return an instance of `WorkflowResponse`. The `WorkflowResponse` constructor accepts the workflow's output as a parameter, which is the updated order in this case.
891
892 <Note title="Tip">
893
894 `transform` allows you to access the values of data during execution. Learn more in the [Data Manipulation](!docs!/learn/fundamentals/workflows/variable-manipulation) documentation.
895
896 </Note>
897
898 ### c. Create Order Placed Subscriber
899
900 Next, you'll create a subscriber that listens to the `order.placed` event and executes the `createOrderTransactionWorkflow` when the event is emitted.
901
902 A subscriber is an asynchronous function that is executed when its associated event is emitted.
903
904 To create the subscriber, create the file `src/subscribers/order-placed.ts` with the following content:
905
906 ```ts title="src/subscribers/order-placed.ts"
907 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
908 import { createOrderTransactionWorkflow } from "../workflows/create-order-transaction"
909
910 export default async function orderPlacedHandler({
911 event: { data },
912 container,
913 }: SubscriberArgs<{ id: string }>) {
914 await createOrderTransactionWorkflow(container).run({
915 input: {
916 order_id: data.id,
917 },
918 })
919 }
920
921 export const config: SubscriberConfig = {
922 event: `order.placed`,
923 }
924 ```
925
926 A subscriber file must export:
927
928 - An asynchronous function that is executed when its associated event is emitted.
929 - An object that indicates the event that the subscriber is listening to.
930
931 The subscriber receives among its parameters the data payload of the emitted event, which includes the order ID.
932
933 In the subscriber, you call the `createOrderTransactionWorkflow` with the order ID to create the transaction in Avalara.
934
935 ### Test Order Placement with Avalara Transaction
936
937 To test the order placement with Avalara transaction creation, make sure both the Medusa server and the Next.js Starter Storefront are running.
938
939 Then, go to the storefront at `http://localhost:8000` and complete the checkout process you started in the [previous step](#step-3-test-tax-calculation-with-avalara).
940
941 You can verify that the transaction was created in Avalara by going to your Avalara dashboard:
942
943 1. From the sidebar, click on "Transactions" → "Transactions."
944 2. In the filter at the top, select "This month to date."
945 3. In the list, the first transaction should correspond to the order you just placed. Click on it to view its details.
946
947 You can view the tax details calculated by Avalara for the order, with the line items and shipping method included in the transaction.
948
949 ![The transaction's details in the Avalara dashboard showing the calculated taxes for the order](https://res.cloudinary.com/dza7lstvk/image/upload/v1761122370/Medusa%20Resources/CleanShot_2025-10-22_at_11.38.09_2x_bu0jwl.png)
950
951 ---
952
953 ## Step 5: Sync Products with Avalara
954
955 In Avalara, you can manage the items you sell to set classifications, tax codes, exemptions, and other tax-related settings.
956
957 In this step, you'll sync Medusa's products with Avalara items. This way, you can manage tax codes and other settings for your products directly from Avalara.
958
959 To do this, you will:
960
961 1. Add methods to the Avalara Tax Module Provider's service to manage Avalara items.
962 2. Build workflows to create, update, and delete Avalara items.
963 3. Create subscribers that listen to product events and trigger the workflows.
964
965 ### a. Add Methods to Avalara Tax Module Provider
966
967 To manage Avalara items, you'll add methods to the Avalara Tax Module Provider's service that uses the AvaTax API to create, update, and delete items.
968
969 In `src/modules/avalara/service.ts`, add the following methods to the `AvalaraTaxModuleProvider` class:
970
971 export const avalaraItemMethodsHighlights = [
972 ["3", "createItems", "Create multiple items in Avalara using the Create Items API."],
973 ["35", "getItem", "Retrieve an item from Avalara using the Get Item API."],
974 ["51", "updateItem", "Update an item in Avalara using the Update Item API."],
975 ["79", "deleteItem", "Delete an item in Avalara using the Delete Item API."]
976 ]
977
978 ```ts title="src/modules/avalara/service.ts" highlights={avalaraItemMethodsHighlights}
979 class AvalaraTaxModuleProvider implements ITaxProvider {
980 // ...
981 async createItems(items: {
982 medusaId: string
983 itemCode: string
984 description: string
985 [key: string]: unknown
986 }[]) {
987 try {
988 const response = await this.avatax.createItems({
989 companyId: this.options.companyId!,
990 model: await Promise.all(
991 items.map(async (item) => {
992 return {
993 ...item,
994 id: 0, // Avalara will generate an ID for the item
995 itemCode: item.itemCode,
996 description: item.description,
997 source: "medusa",
998 sourceEntityId: item.medusaId,
999 }
1000 })
1001 ),
1002 })
1003
1004 return response
1005 } catch (error) {
1006 throw new MedusaError(
1007 MedusaError.Types.UNEXPECTED_STATE,
1008 `An error occurred while creating item classifications for Avalara: ${error}`
1009 )
1010 }
1011 }
1012
1013 async getItem(id: number) {
1014 try {
1015 const response = await this.avatax.getItem({
1016 companyId: this.options.companyId!,
1017 id,
1018 })
1019
1020 return response
1021 } catch (error) {
1022 throw new MedusaError(
1023 MedusaError.Types.UNEXPECTED_STATE,
1024 `An error occurred while retrieving item classification from Avalara: ${error}`
1025 )
1026 }
1027 }
1028
1029 async updateItem(item: {
1030 id: number
1031 itemCode: string
1032 description: string
1033 [key: string]: unknown
1034 }) {
1035 try {
1036 const response = await this.avatax.updateItem({
1037 companyId: this.options.companyId!,
1038 id: item.id,
1039 model: {
1040 ...item,
1041 id: item.id,
1042 itemCode: item.itemCode,
1043 description: item.description,
1044 source: "medusa",
1045 },
1046 })
1047
1048 return response
1049 } catch (error) {
1050 throw new MedusaError(
1051 MedusaError.Types.UNEXPECTED_STATE,
1052 `An error occurred while updating item classifications for Avalara: ${error}`
1053 )
1054 }
1055 }
1056
1057 async deleteItem(id: number) {
1058 try {
1059 const response = await this.avatax.deleteItem({
1060 companyId: this.options.companyId!,
1061 id,
1062 })
1063
1064 return response
1065 } catch (error) {
1066 throw new MedusaError(
1067 MedusaError.Types.UNEXPECTED_STATE,
1068 `An error occurred while deleting item classifications for Avalara: ${error}`
1069 )
1070 }
1071 }
1072 }
1073 ```
1074
1075 You add the following methods:
1076
1077 1. `createItems`: Creates multiple items in Avalara using their [Create Items API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Items/CreateItems/).
1078 2. `getItem`: Retrieves an item from Avalara using their [Get Item API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Items/GetItem/).
1079 3. `updateItem`: Updates an item in Avalara using their [Update Item API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Items/UpdateItem/).
1080 4. `deleteItem`: Deletes an item in Avalara using their [Delete Item API](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Items/DeleteItem/).
1081
1082 You'll use these methods in the next sections to build workflows that sync products with Avalara items.
1083
1084 ### b. Create Avalara Item Workflow
1085
1086 The first workflow you'll build creates an item for a product in Avalara. It has the following steps:
1087
1088 <WorkflowDiagram
1089 workflow={{
1090 name: "createProductItemWorkflow",
1091 steps: [
1092 {
1093 type: "step",
1094 name: "useQueryGraphStep",
1095 link: "/references/helper-steps/useQueryGraphStep",
1096 description: "Retrieve product's details.",
1097 },
1098 {
1099 type: "step",
1100 name: "createItemStep",
1101 description: "Create Avalara item for the product.",
1102 depth: 2
1103 },
1104 {
1105 type: "workflow",
1106 name: "updateProductsWorkflow",
1107 description: "Save Avalara item ID in product metadata.",
1108 link: "/references/medusa-workflows/updateProductsWorkflow",
1109 depth: 3
1110 }
1111 ]
1112 }}
1113 />
1114
1115 Medusa provides the first and last step out of the box. You only need to create the `createItemStep`.
1116
1117 #### createItemStep
1118
1119 The `createItemStep` creates an item in Avalara.
1120
1121 To create the step, create the file `src/workflows/steps/create-item.ts` with the following content:
1122
1123 ```ts title="src/workflows/steps/create-item.ts"
1124 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1125 import AvalaraTaxModuleProvider from "../../modules/avalara/service"
1126 import { Modules } from "@medusajs/framework/utils"
1127
1128 type StepInput = {
1129 item: {
1130 medusaId: string
1131 itemCode: string
1132 description: string
1133 [key: string]: unknown
1134 }
1135 }
1136
1137 export const createItemStep = createStep(
1138 "create-item",
1139 async ({ item }: StepInput, { container }) => {
1140 const taxModuleService = container.resolve(Modules.TAX)
1141 const avalaraProviderService = taxModuleService.getProvider(
1142 `tp_${AvalaraTaxModuleProvider.identifier}_avalara`
1143 ) as AvalaraTaxModuleProvider
1144
1145 const response = await avalaraProviderService.createItems(
1146 [item]
1147 )
1148
1149 return new StepResponse(response[0], response[0].id)
1150 },
1151 async (data, { container }) => {
1152 if (!data) {
1153 return
1154 }
1155 const taxModuleService = container.resolve(Modules.TAX)
1156 const avalaraProviderService = taxModuleService.getProvider(
1157 `tp_${AvalaraTaxModuleProvider.identifier}_avalara`
1158 ) as AvalaraTaxModuleProvider
1159
1160 avalaraProviderService.deleteItem(data)
1161 }
1162 )
1163 ```
1164
1165 The step receives the details of the item to create as input.
1166
1167 In the step, you retrieve the Avalara Tax Module Provider's service from the Tax Module. Then, you call its `createItems` method to create the item in Avalara.
1168
1169 You return the created item, and you pass its ID to the compensation function to delete the item if an error occurs during the workflow's execution.
1170
1171 <Note>
1172
1173 Refer to [Avalara's documentation](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Items/CreateItems/) for details on other accepted parameters when creating an item.
1174
1175 </Note>
1176
1177 #### Create Product Item Workflow
1178
1179 You can now create the workflow. Create the file `src/workflows/create-product-item.ts` with the following content:
1180
1181 export const createProductItemWorkflowHighlights = [
1182 ["12", "products", "Retrieve the product's details."],
1183 ["26", "createItemStep", "Create the item in Avalara."],
1184 ["34", "updateProductsWorkflow", "Save the created item's ID in the product's metadata."]
1185 ]
1186
1187 ```ts title="src/workflows/create-product-item.ts" highlights={createProductItemWorkflowHighlights}
1188 import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
1189 import { updateProductsWorkflow, useQueryGraphStep } from "@medusajs/medusa/core-flows"
1190 import { createItemStep } from "./steps/create-item"
1191
1192 type WorkflowInput = {
1193 product_id: string
1194 }
1195
1196 export const createProductItemWorkflow = createWorkflow(
1197 "create-product-item",
1198 (input: WorkflowInput) => {
1199 const { data: products } = useQueryGraphStep({
1200 entity: "product",
1201 fields: [
1202 "id",
1203 "title",
1204 ],
1205 filters: {
1206 id: input.product_id,
1207 },
1208 options: {
1209 throwIfKeyNotFound: true,
1210 },
1211 })
1212
1213 const response = createItemStep({
1214 item: {
1215 medusaId: products[0].id,
1216 itemCode: products[0].id,
1217 description: products[0].title,
1218 },
1219 })
1220
1221 updateProductsWorkflow.runAsStep({
1222 input: {
1223 products: [
1224 {
1225 id: input.product_id,
1226 metadata: {
1227 avalara_item_id: response.id,
1228 },
1229 },
1230 ],
1231 },
1232 })
1233
1234 return new WorkflowResponse(response)
1235 }
1236 )
1237 ```
1238
1239 The workflow receives the product ID as input.
1240
1241 In the workflow, you:
1242
1243 1. Retrieve the product's details using the `useQueryGraphStep`.
1244 2. Create the item in Avalara using the `createItemStep`.
1245 3. Save the created item's ID in the product's metadata using the `updateProductsWorkflow`. This ID is useful when you want to update or delete the item later.
1246
1247 You return the created item as the workflow's output.
1248
1249 ### c. Create Product Created Subscriber
1250
1251 Next, you'll create a subscriber that listens to the `product.created` event and executes the `createProductItemWorkflow`.
1252
1253 Create the file `src/subscribers/product-created.ts` with the following content:
1254
1255 ```ts title="src/subscribers/product-created.ts"
1256 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
1257 import { createProductItemWorkflow } from "../workflows/create-product-item"
1258
1259 export default async function productCreatedHandler({
1260 event: { data },
1261 container,
1262 }: SubscriberArgs<{ id: string }>) {
1263 await createProductItemWorkflow(container).run({
1264 input: {
1265 product_id: data.id,
1266 },
1267 })
1268 }
1269
1270 export const config: SubscriberConfig = {
1271 event: `product.created`,
1272 }
1273 ```
1274
1275 You create a subscriber similar to the one you created for the `order.placed` event. This time, it listens to the `product.created` event and triggers the `createProductItemWorkflow` with the product ID.
1276
1277 ### d. Test Product Creation with Avalara Item
1278
1279 To test the product creation with Avalara item creation, make sure the Medusa server is running.
1280
1281 Then:
1282
1283 1. Open the Medusa Admin dashboard at `http://localhost:9000/admin`.
1284 2. Go to "Products," and create a new product.
1285 3. After creating the product, go to your Avalara dashboard.
1286 4. From the sidebar, click on "Settings" → "What you sell and buy."
1287
1288 This will open the Items page, where you can see the product you created as items in Avalara. You can click on an item to view it, add a classification, and more.
1289
1290 ![The list of items in the Avalara dashboard showing the item created for the product](https://res.cloudinary.com/dza7lstvk/image/upload/v1761123470/Medusa%20Resources/CleanShot_2025-10-22_at_11.57.33_2x_jbb4km.png)
1291
1292 ### e. Update Avalara Item Workflow
1293
1294 Next, you'll create a workflow that updates a product's item in Avalara. The workflow has the following steps:
1295
1296 <WorkflowDiagram
1297 workflow={{
1298 name: "updateProductItemWorkflow",
1299 steps: [
1300 {
1301 type: "step",
1302 name: "useQueryGraphStep",
1303 description: "Retrieve product's details.",
1304 link: "/references/helper-steps/useQueryGraphStep",
1305 depth: 1
1306 },
1307 {
1308 type: "when",
1309 condition: "products.length > 0 && !products[0].metadata?.avalara_item_id",
1310 steps: [
1311 {
1312 type: "workflow",
1313 name: "createProductItemWorkflow",
1314 description: "Create an item for the product.",
1315 depth: 1
1316 }
1317 ],
1318 depth: 2
1319 },
1320 {
1321 type: "when",
1322 condition: "products.length > 0 && !!products[0].metadata?.avalara_item_id",
1323 steps: [
1324 {
1325 type: "step",
1326 name: "updateItemStep",
1327 description: "Update Avalara item for product.",
1328 depth: 2
1329 }
1330 ],
1331 depth: 3
1332 }
1333 ]
1334 }}
1335 />
1336
1337 Medusa provides the first step out of the box, and you have already created the `createProductItemWorkflow`. You only need to create the `updateItemStep`.
1338
1339 #### updateItemStep
1340
1341 The `updateItemStep` updates an item in Avalara.
1342
1343 To create the step, create the file `src/workflows/steps/update-item.ts` with the following content:
1344
1345 export const updateItemStepHighlights = [
1346 ["24", "getItem", "Retrieve the original item before updating."],
1347 ["27", "updateItem", "Update the item in Avalara using the provider's updateItem method."],
1348 ["44", "updateItem", "Revert the updates by restoring the original values if an error occurs during the workflow's execution."]
1349 ]
1350
1351 ```ts title="src/workflows/steps/update-item.ts" highlights={updateItemStepHighlights}
1352 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1353 import AvalaraTaxModuleProvider from "../../modules/avalara/service"
1354 import { Modules } from "@medusajs/framework/utils"
1355
1356 type StepInput = {
1357 item: {
1358 id: number
1359 medusaId: string
1360 itemCode: string
1361 description: string
1362 [key: string]: unknown
1363 }
1364 }
1365
1366 export const updateItemStep = createStep(
1367 "update-item",
1368 async ({ item }: StepInput, { container }) => {
1369 const taxModuleService = container.resolve(Modules.TAX)
1370 const avalaraProviderService = taxModuleService.getProvider(
1371 `tp_${AvalaraTaxModuleProvider.identifier}_avalara`
1372 ) as AvalaraTaxModuleProvider
1373
1374 // Retrieve original item before updating
1375 const originalItem = await avalaraProviderService.getItem(item.id)
1376
1377 // Update the item
1378 const response = await avalaraProviderService.updateItem(item)
1379
1380 return new StepResponse(response, {
1381 originalItem,
1382 })
1383 },
1384 async (data, { container }) => {
1385 if (!data) {
1386 return
1387 }
1388
1389 const taxModuleService = container.resolve(Modules.TAX)
1390 const avalaraProviderService = taxModuleService.getProvider(
1391 `tp_${AvalaraTaxModuleProvider.identifier}_avalara`
1392 ) as AvalaraTaxModuleProvider
1393
1394 // Revert the updates by restoring original values
1395 await avalaraProviderService.updateItem({
1396 id: data.originalItem.id,
1397 itemCode: data.originalItem.itemCode,
1398 description: data.originalItem.description,
1399 })
1400 }
1401 )
1402 ```
1403
1404 The step receives the details of the item to update as input.
1405
1406 In the step, you:
1407
1408 1. Retrieve the Avalara Tax Module Provider's service from the Tax Module.
1409 2. Retrieve the original item from Avalara before updating it.
1410 3. Call the `updateItem` method to update the item in Avalara.
1411 4. Return the updated item and pass the original item to the compensation function.
1412
1413 In the compensation function, you revert the updates by restoring the original values if an error occurs during the workflow's execution.
1414
1415 #### Update Product Item Workflow
1416
1417 You can now create the workflow. Create the file `src/workflows/update-product-item.ts` with the following content:
1418
1419 export const updateProductItemWorkflowHighlights = [
1420 ["13", "products", "Retrieve the product's details."],
1421 ["28", "when", "Check whether product does not have an Avalara item ID in its metadata."],
1422 ["32", "createProductItemWorkflow", "Create the item in Avalara if it doesn't exist."],
1423 ["39", "when", "Check whether product has an Avalara item ID in its metadata."],
1424 ["48", "updateItemStep", "Update the item in Avalara if it exists."],
1425 ["58", "transform", "Return either the created or updated item as the workflow's output."]
1426 ]
1427
1428 ```ts title="src/workflows/update-variant-item.ts" highlights={updateProductItemWorkflowHighlights}
1429 import { createWorkflow, WorkflowResponse, transform, when } from "@medusajs/framework/workflows-sdk"
1430 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
1431 import { updateItemStep } from "./steps/update-item"
1432 import { createProductItemWorkflow } from "./create-product-item"
1433
1434 type WorkflowInput = {
1435 product_id: string
1436 }
1437
1438 export const updateProductItemWorkflow = createWorkflow(
1439 "update-product-item",
1440 (input: WorkflowInput) => {
1441 const { data: products } = useQueryGraphStep({
1442 entity: "product",
1443 fields: [
1444 "id",
1445 "title",
1446 "metadata",
1447 ],
1448 filters: {
1449 id: input.product_id,
1450 },
1451 options: {
1452 throwIfKeyNotFound: true,
1453 },
1454 })
1455
1456 const createResponse = when({ products }, ({ products }) =>
1457 products.length > 0 && !products[0].metadata?.avalara_item_id
1458 )
1459 .then(() => {
1460 return createProductItemWorkflow.runAsStep({
1461 input: {
1462 product_id: input.product_id,
1463 },
1464 })
1465 })
1466
1467 const updateResponse = when({ products }, ({ products }) =>
1468 products.length > 0 && !!products[0].metadata?.avalara_item_id
1469 )
1470 .then(() => {
1471 const avalaraItemId = transform(
1472 { products },
1473 ({ products }) => products[0].metadata?.avalara_item_id as number
1474 )
1475
1476 return updateItemStep({
1477 item: {
1478 id: avalaraItemId,
1479 medusaId: products[0].id,
1480 itemCode: products[0].id,
1481 description: products[0].title,
1482 },
1483 })
1484 })
1485
1486 const response = transform({
1487 createResponse,
1488 updateResponse,
1489 }, (data) => {
1490 return data.createResponse || data.updateResponse
1491 })
1492
1493 return new WorkflowResponse(response)
1494 }
1495 )
1496 ```
1497
1498 The workflow receives the product ID as input.
1499
1500 In the workflow, you:
1501
1502 1. Retrieve the product's details using the `useQueryGraphStep`.
1503 2. Use a `when` condition to check whether the product has an Avalara item ID in its metadata.
1504 - If it doesn't, you call the `createProductItemWorkflow` to create the item in Avalara.
1505 - If it does, you prepare the input and call the `updateItemStep` to update the item in Avalara.
1506 3. Use `transform` to return either the created or updated item as the workflow's output.
1507
1508 <Note title="Tip">
1509
1510 `when-then` allows you to run steps based on conditions during execution. Learn more in the [Conditions in Workflows](!docs!/learn/fundamentals/workflows/conditions) documentation.
1511
1512 </Note>
1513
1514 ### f. Create Product Updated Subscriber
1515
1516 Next, you'll create a subscriber that listens to the `product.updated` event and executes the `updateProductItemWorkflow`.
1517
1518 Create the file `src/subscribers/product-updated.ts` with the following content:
1519
1520 ```ts title="src/subscribers/product-updated.ts"
1521 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
1522 import { updateProductItemWorkflow } from "../workflows/update-product-item"
1523
1524 export default async function productUpdatedHandler({
1525 event: { data },
1526 container,
1527 }: SubscriberArgs<{ id: string }>) {
1528 await updateProductItemWorkflow(container).run({
1529 input: {
1530 product_id: data.id,
1531 },
1532 })
1533 }
1534
1535 export const config: SubscriberConfig = {
1536 event: `product.updated`,
1537 }
1538
1539
1540 ```
1541
1542 You create a subscriber similar to the one you created for the `product.created` event. This time, it listens to the `product.updated` event and triggers the `updateProductItemWorkflow` with the product ID.
1543
1544 ### g. Test Product Update with Avalara Item
1545
1546 To test the product update with Avalara item update, make sure the Medusa server is running.
1547
1548 Then:
1549
1550 1. Open the Medusa Admin dashboard at `http://localhost:9000/admin`.
1551 2. Go to "Products," and edit an existing product. For example, you can edit its title.
1552 3. After updating the product, go to your Avalara dashboard.
1553 4. From the sidebar, click on "Settings" → "What you sell and buy."
1554 - If the product already had an item in Avalara, click on it to view its details and confirm that the changes were applied.
1555 - If the product didn't have an item in Avalara, you should see a new item created for it.
1556
1557 ### h. Delete Avalara Item Workflow
1558
1559 The last workflow you'll build deletes a product's item from Avalara. The workflow has the following steps:
1560
1561 <WorkflowDiagram
1562 workflow={{
1563 name: "deleteProductItemWorkflow",
1564 steps: [
1565 {
1566 type: "step",
1567 name: "useQueryGraphStep",
1568 description: "Retrieve the product's details.",
1569 link: "/references/helper-steps/useQueryGraphStep",
1570 depth: 1,
1571 },
1572 {
1573 type: "when",
1574 condition: "products.length > 0 && !!products[0].metadata?.avalara_item_id",
1575 steps: [
1576 {
1577 type: "step",
1578 name: "deleteItemStep",
1579 description: "Delete the product's item from Avalara.",
1580 depth: 1
1581 }
1582 ],
1583 depth: 2
1584 }
1585 ]
1586 }}
1587 />
1588
1589 Medusa provides the first step out of the box. You only need to create the `deleteItemStep`.
1590
1591 #### deleteItemStep
1592
1593 The `deleteItemStep` deletes an item from Avalara.
1594
1595 To create the step, create the file `src/workflows/steps/delete-item.ts` with the following content:
1596
1597 export const deleteItemStepHighlights = [
1598 ["19", "getItem", "Retrieve the original item before deleting."],
1599 ["21", "deleteItem", "Delete the item in Avalara using the provider's deleteItem method."],
1600 ["42", "createItems", "Recreate the item using the original values if an error occurs during the workflow's execution."]
1601 ]
1602
1603 ```ts title="src/workflows/steps/delete-item.ts" highlights={deleteItemStepHighlights}
1604 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1605 import AvalaraTaxModuleProvider from "../../modules/avalara/service"
1606 import { Modules } from "@medusajs/framework/utils"
1607
1608 type StepInput = {
1609 item_id: number
1610 }
1611
1612 export const deleteItemStep = createStep(
1613 "delete-item",
1614 async ({ item_id }: StepInput, { container }) => {
1615 const taxModuleService = container.resolve(Modules.TAX)
1616 const avalaraProviderService = taxModuleService.getProvider(
1617 `tp_${AvalaraTaxModuleProvider.identifier}_avalara`
1618 ) as AvalaraTaxModuleProvider
1619
1620 try {
1621 // Retrieve original item before deleting
1622 const original = await avalaraProviderService.getItem(item_id)
1623 // Delete the item
1624 const response = await avalaraProviderService.deleteItem(original.id)
1625
1626 return new StepResponse(response, {
1627 originalItem: original,
1628 })
1629 } catch (error) {
1630 console.error(error)
1631 // Item does not exist in Avalara, so we can skip deletion
1632 return new StepResponse(void 0)
1633 }
1634 },
1635 async (data, { container }) => {
1636 if (!data) {
1637 return
1638 }
1639
1640 const taxModuleService = container.resolve(Modules.TAX)
1641 const avalaraProviderService = taxModuleService.getProvider(
1642 `tp_${AvalaraTaxModuleProvider.identifier}_avalara`
1643 ) as AvalaraTaxModuleProvider
1644
1645 await avalaraProviderService.createItems(
1646 [{
1647 medusaId: data.originalItem.sourceEntityId ?? "",
1648 description: data.originalItem.description,
1649 itemCode: data.originalItem.itemCode,
1650 }]
1651 )
1652 }
1653 )
1654 ```
1655
1656 The step receives the ID of the item to delete as input.
1657
1658 In the step, you:
1659
1660 1. Retrieve the Avalara Tax Module Provider's service from the Tax Module.
1661 2. Retrieve the original item before deleting it.
1662 3. Call the `deleteItem` method to delete the item in Avalara.
1663 4. Return the deletion response and pass the original item to the compensation function.
1664
1665 In the compensation function, you recreate the item using the original values if an error occurs during the workflow's execution.
1666
1667 #### Delete Product Item Workflow
1668
1669 You can now create the workflow. Create the file `src/workflows/delete-product-item.ts` with the following content:
1670
1671 export const deleteProductItemWorkflowHighlights = [
1672 ["12", "products", "Retrieve the product's details."],
1673 ["27", "when", "Check whether product has an Avalara item ID in its metadata."],
1674 ["31", "deleteItemStep", "Delete the item in Avalara if it exists."]
1675 ]
1676
1677 ```ts title="src/workflows/delete-product-item.ts" highlights={deleteProductItemWorkflowHighlights}
1678 import { createWorkflow, when, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
1679 import { deleteItemStep } from "./steps/delete-item"
1680 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
1681
1682 type WorkflowInput = {
1683 product_id: string
1684 }
1685
1686 export const deleteProductItemWorkflow = createWorkflow(
1687 "delete-product-item",
1688 (input: WorkflowInput) => {
1689 const { data: products } = useQueryGraphStep({
1690 entity: "product",
1691 fields: [
1692 "id",
1693 "metadata",
1694 ],
1695 filters: {
1696 id: input.product_id,
1697 },
1698 withDeleted: true,
1699 options: {
1700 throwIfKeyNotFound: true,
1701 },
1702 })
1703
1704 when({ products }, ({ products }) =>
1705 products.length > 0 && !!products[0].metadata?.avalara_item_id
1706 )
1707 .then(() => {
1708 deleteItemStep({ item_id: products[0].metadata!.avalara_item_id as number })
1709 })
1710
1711 return new WorkflowResponse(void 0)
1712 }
1713 )
1714 ```
1715
1716 The workflow receives the product ID as input.
1717
1718 In the workflow, you:
1719
1720 1. Retrieve the product's details using the `useQueryGraphStep`, including deleted products.
1721 2. Use a `when` condition to check whether the product has an Avalara item ID in its metadata.
1722 - If it does, you call the `deleteItemStep` to delete the item in Avalara.
1723
1724 ### i. Create Product Deleted Subscriber
1725
1726 Finally, you'll create a subscriber to delete the Avalara item when a product is deleted.
1727
1728 Create the file `src/subscribers/product-deleted.ts` with the following content:
1729
1730 ```ts title="src/subscribers/product-deleted.ts"
1731 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
1732 import { deleteProductItemWorkflow } from "../workflows/delete-product-item"
1733
1734 export default async function productDeletedHandler({
1735 event: { data },
1736 container,
1737 }: SubscriberArgs<{ id: string }>) {
1738 await deleteProductItemWorkflow(container).run({
1739 input: {
1740 product_id: data.id,
1741 },
1742 throwOnError: false,
1743 })
1744 }
1745
1746 export const config: SubscriberConfig = {
1747 event: `product.deleted`,
1748 }
1749
1750
1751 ```
1752
1753 You create a subscriber similar to the previous ones. This time, the subscriber listens to the `product.deleted` event and triggers the `deleteProductItemWorkflow` with the product ID.
1754
1755 ### j. Test Product Deletion with Avalara Item
1756
1757 To test the product deletion with Avalara item deletion, make sure the Medusa server is running.
1758
1759 Then:
1760
1761 1. Open the Medusa Admin dashboard at `http://localhost:9000/admin`.
1762 2. Go to "Products," and delete a product.
1763 3. After deleting the product, go to your Avalara dashboard.
1764 4. From the sidebar, click on "Settings" → "What you sell and buy." The product's item should no longer be listed.
1765
1766 ---
1767
1768 ## Next Steps
1769
1770 You've successfully integrated Avalara with Medusa to handle tax calculations during checkout, create transactions when orders are placed, and sync products with Avalara items.
1771
1772 You can expand on this integration by managing tax features in Avalara, such as exemptions. You can also handle order events like `order.canceled` to void transactions in Avalara when orders are canceled.
1773
1774 ### Learn More About Medusa
1775
1776 If you're new to Medusa, check out the [main documentation](!docs!/learn) for a more in-depth understanding of the concepts used in this guide.
1777
1778 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).
1779
1780 ### Troubleshooting
1781
1782 If you encounter issues during your development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx).
1783
1784 ### Getting Help
1785
1786 If you encounter issues not covered in the troubleshooting guides:
1787
1788 1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions.
1789 2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members.