Skip to main content
Skip to main content

ITaxCalculationStrategy

Overview

A tax calculation strategy is used to calculate taxes when calculating a cart's totals. The Medusa backend provides a tax calculation strategy that handles calculating the taxes, taking into account the defined tax rates and settings such as whether tax-inclusive pricing is enabled.

You can override the tax calculation strategy to implement different calculation logic or to integrate a third-party service that handles the tax calculation. You can override it either in a Medusa backend setup or in a plugin.

A tax calculation strategy should be defined in a TypeScript or JavaScript file created under the src/strategies directory. The class must also implement the ITaxCalculationStrategy interface imported from the @medusajs/medusa package.

For example, you can create the file src/strategies/tax-calculation.ts with the following content:

src/strategies/tax-calculation.ts
import {
ITaxCalculationStrategy,
LineItem,
LineItemTaxLine,
ShippingMethodTaxLine,
TaxCalculationContext,
} from "@medusajs/medusa"

class TaxCalculationStrategy
implements ITaxCalculationStrategy {

async calculate(
items: LineItem[],
taxLines: (ShippingMethodTaxLine | LineItemTaxLine)[],
calculationContext: TaxCalculationContext
): Promise<number> {
throw new Error("Method not implemented.")
}

}

export default TaxCalculationStrategy

calculate

This method calculates the tax amount for a given set of line items under applicable tax conditions and calculation contexts.

This method is used whenever taxes are calculated. If automatic tax calculation is disabled in a region, then it's only triggered when taxes are calculated manually as explained in this guide.

Example

An example of the general implementation of this method in the Medusa backend's tax calculation strategy:

async calculate(
items: LineItem[],
taxLines: (ShippingMethodTaxLine | LineItemTaxLine)[],
calculationContext: TaxCalculationContext
): Promise<number> {
const lineItemsTaxLines = taxLines.filter(
(tl) => "item_id" in tl
) as LineItemTaxLine[]
const shippingMethodsTaxLines = taxLines.filter(
(tl) => "shipping_method_id" in tl
) as ShippingMethodTaxLine[]

const lineItemsTax = this.calculateLineItemsTax(
items,
lineItemsTaxLines,
calculationContext
)

const shippingMethodsTax = this.calculateShippingMethodsTax(
calculationContext.shipping_methods,
shippingMethodsTaxLines
)

return Math.round(lineItemsTax + shippingMethodsTax)
}

Parameters

itemsLineItem[]Required
The line items to calculate the tax total for.
The tax lines used for the calculation
calculationContextTaxCalculationContextRequired
Other details relevant for the calculation

Returns

PromisePromise<number>Required
The calculated tax total
Was this section helpful?